diff --git "a/343.jsonl" "b/343.jsonl" new file mode 100644--- /dev/null +++ "b/343.jsonl" @@ -0,0 +1,630 @@ +{"seq_id":"624289127","text":"from tqdm import tqdm_notebook as tqdm\nimport pandas as pd\nimport numpy as np\nfrom sklearn.cluster import KMeans\nimport matplotlib.pyplot as plt\n\ndef elbow_method(df_, k_initial=1, maxClusters=15, k_iteration=1):\n # to validing K value in K-means\n print('Executing Elbow Method to:\\n...K of {} to {} from k_iteration:{}\\n'.format(k_initial,maxClusters, k_iteration))\n inertia_dic = {}\n for k in tqdm(range(k_initial, maxClusters, k_iteration)):\n ## validing K value in K-means\n\n # print('...testing k: {}'.format(k))\n inertia_dic[k] = KMeans(n_clusters=k).fit(df_).inertia_\n return inertia_dic\n\ndef gap_statistic(df_, nrefs=3, maxClusters=15, k_initial=1, k_iteration=1):\n #### Gap\n #https://anaconda.org/milesgranger/gap-statistic/notebook\n \"\"\"\n Calculates KMeans optimal K using Gap Statistic from Tibshirani, Walther, Hastie\n Params:\n df: ndarry of shape (n_samples, n_features)\n nrefs: number of sample reference datasets to create\n maxClusters: Maximum number of clusters to test for\n Returns: (gaps, optimalK)\n \"\"\"\n gaps = {}\n for k in tqdm(range(k_initial, maxClusters, k_iteration)):\n # Holder for reference dispersion results\n refDisps = np.zeros(nrefs)\n # For n references, generate random sample and perform kmeans getting resulting dispersion of each loop\n for i in range(nrefs):\n # Create new random reference set\n randomReference = np.random.random_sample(size=df_.shape)\n # Fit to it\n km = KMeans(k)\n km.fit(randomReference)\n refDisp = km.inertia_\n refDisps[i] = refDisp\n # Fit cluster to original data and create dispersion\n km = KMeans(k).fit(df_)\n origDisp = km.inertia_\n # Calculate gap statistic\n gap = np.log(np.mean(refDisps)) - np.log(origDisp)\n # Assign this loop's gap statistic to gaps\n gaps[k] = gap\n\n return gaps # Plus 1 because index of 0 means 1 cluster is optimal, index 2 = 3 clusters are optimal","sub_path":"pymove/clustering.py","file_name":"clustering.py","file_ext":"py","file_size_in_byte":2071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"280020761","text":"import pydash\n\nfrom dashboard.data.utils import values_for_records, QCheck, facility_not_reporting, multiple_orders_score\nfrom dashboard.helpers import *\n\n\nclass BlanksQualityCheck(QCheck):\n test = ORDER_FORM_FREE_OF_GAPS\n combinations = [{NAME: DEFAULT}]\n\n fields = [OPENING_BALANCE,\n QUANTITY_RECEIVED,\n ART_CONSUMPTION,\n LOSES_ADJUSTMENTS,\n ESTIMATED_NUMBER_OF_NEW_ART_PATIENTS]\n\n def for_each_facility(self, data, combination, previous_cycle_data=None):\n result = NOT_REPORTING\n\n values = values_for_records(self.fields, data.get(C_RECORDS, []))\n number_of_consumption_record_blanks = len(pydash.select(\n values, lambda v: v is None))\n\n c_count_ = data.get(C_COUNT, 0)\n a_count_ = data.get(A_COUNT, 0)\n p_count_ = data.get(P_COUNT, 0)\n if c_count_ == 0 and a_count_ == 0 and p_count_ == 0:\n return result\n if c_count_ < 25 or a_count_ < 22 or p_count_ < 7:\n result = NO\n elif number_of_consumption_record_blanks > 2:\n result = NO\n else:\n result = YES\n return result\n\n\nclass WebBasedCheck(QCheck):\n test = WEB_BASED\n combinations = [{NAME: DEFAULT}]\n\n def for_each_facility(self, data, combination, previous_cycle_data=None):\n value = data[WEB_PAPER].strip()\n result = NOT_REPORTING\n if value:\n if value.lower() == WEB.lower():\n result = WEB\n if value.lower() == PAPER.lower():\n result = PAPER\n\n return result\n\n\nclass IsReportingCheck(QCheck):\n test = REPORTING\n combinations = [{NAME: DEFAULT}]\n\n def for_each_facility(self, facility, combination, previous_cycle_data=None):\n return NO if facility_not_reporting(facility) else YES\n\n\nclass MultipleCheck(QCheck):\n test = MULTIPLE_ORDERS\n combinations = [{NAME: DEFAULT}]\n\n def for_each_facility(self, facility, combination, previous_cycle_data=None):\n return multiple_orders_score(facility)\n","sub_path":"dashboard/data/blanks.py","file_name":"blanks.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"273889285","text":"import scrapy\nimport datetime\nfrom scrape_img.items import ScrapeImgItem\n\n\nclass imgSpider(scrapy.Spider):\n name = \"imgSpider\"\n domain = \"http://www.gettyimages.com\"\n\n def start_requests(self):\n yield scrapy.Request(\"http://www.gettyimages.ca/photos/arne-friedrich?family=editorial&phrase=arne%20friedrich&sort=best&excludenudity=true\", \\\n callback=self.parse_page)\n\n\n def parse_page(self, response):\n for href in response.xpath('//a[@class=\"search-result-asset-link\"]/@href').extract():\n yield scrapy.Request(self.domain + href, callback=self.parse_pic)\n\n last_page = response.xpath('//section[@class=\"gallery\"]/@data-is-last-page').extract_first()\n\n if last_page == \"false\":\n next_page = response.xpath('//a[@id=\"next-gallery-page\"]/@href').extract_first()\n yield scrapy.Request(self.domain + next_page, callback=self.parse_page)\n\n\n def parse_pic(self, response):\n id = response.xpath('//div[@class=\"image-container\"]/img/@asset-id').extract_first()\n title = response.xpath('//h1[@class=\"gallery_title active follow-header\"]/span/text()').extract_first()\n description = response.xpath('//meta[@name=\"description\"]/@content').extract_first().decode('utf_8')\n date = response.xpath('//div[@class=\"footer\"]/div[@class=\"credit\"]/span[1]/text()').extract_first()\n url = response.xpath('//div[@class=\"image-container\"]/img/@src').extract_first()\n\n\n #\n date = datetime.datetime.strptime(date, '%B %d, %Y').strftime('%Y_%m_%d')\n\n if id and title and date:\n image_name = date+ \"_\" + title + \"_\" + id\n image_name = image_name.replace('\\\\','_').replace('/','_')\n image_name = 'full/' + image_name[0:200] + '.jpg'\n\n\n #\n item = ScrapeImgItem()\n item['id'] = id\n item['title'] = title\n item['description'] = description\n item['date'] = date\n item['image_urls'] = [url]\n item['image_name'] = image_name\n\n yield item\n","sub_path":"scrape_img/spiders/imgspider.py","file_name":"imgspider.py","file_ext":"py","file_size_in_byte":2065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"197463100","text":"print(\"Exercise 1\")\n\ndays=0\nwell_height = 125\ndaily_distance = 30\nnightly_distance = 20\nsnail_position = 0\n\nwhile snail_position <= well_height:\n if snail_position < well_height:\n pass\n snail_position+=daily_distance-nightly_distance\n days+=1\nelse:\n print(\"The snail take\", days, \"days to get out.\")\n \nprint(\"Bonus 1\")\nsnail_position = 0\nadvance_cm = [30, 21, 33, 77, 44, 45, 23, 45, 12, 34, 55]\n#i=0\ndisplacement = []\n\nfor i in range(0,10):\n displacement.append(advance_cm[i]-nightly_distance)\n if snail_position <= well_height:\n snail_position += advance_cm[i]-nightly_distance\n else:\n break\nprint(\"The snail take\", i, \"days to get out.\")\n#print(displacement)\nprint(\"The maximum displacement is\",max(displacement))\nprint(\"The minimum displacement is\",min(displacement))\n\naverage = sum(displacement)/len(displacement)\nprint(\"The average progress is\",average)\n\nimport statistics\nprint(\"The standart deviation is\",statistics.stdev(displacement))\n","sub_path":"1.-Python/1.-Snail-and-Well/1-Snail-and-Well_ANSWER.py","file_name":"1-Snail-and-Well_ANSWER.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"558531039","text":"import xlsxwriter\nimport csv\nimport xlrd\n\ndef open_xlsx_file(input_file_path):\n\n xls_file = xlrd.open_workbook(input_file_path)\n sheet = xls_file.sheet_by_index(0)\n xls_dict = {}\n for rownum in range(sheet.nrows):\n xls_row = sheet.row_values(rownum)\n try:\n xls_dict[int(xls_row[0])] = int(xls_row[2])\n except ValueError:\n continue\n return xls_dict\n\ndef open_csv_file(input_file_path):\n\n with open(input_file_path, 'r') as csv_file:\n csv_read = csv.reader(csv_file)\n csv_dict = {}\n for csv_row in csv_read:\n try:\n csv_dict[int(csv_row[1])] = int(csv_row[0])\n except ValueError:\n continue\n\n return csv_dict\n\ndef compare_files(xlsx_file_path, csv_file_path):\n\n xlsx_input_file_path = xlsx_file_path\n csv_input_file_path = csv_file_path\n\n xls_dict = open_xlsx_file(xlsx_input_file_path)\n csv_dict = open_csv_file(csv_input_file_path)\n\n result_dict = {}\n\n for key, csv_value in csv_dict.items():\n if key in xls_dict.keys():\n xls_value = xls_dict[key]\n result_sum = csv_value + xls_value\n if result_sum != 0:\n result_dict[key] = result_sum\n\n return result_dict\n\ndef save_report(output_file_path, xlsx_file_path, csv_file_path):\n\n xlsx_input_file_path = xlsx_file_path\n csv_input_file_path = csv_file_path\n\n result_dict = compare_files(xlsx_input_file_path, csv_input_file_path)\n\n workbook = xlsxwriter.Workbook(output_file_path)\n worksheet = workbook.add_worksheet('Result Sheet')\n worksheet.set_column(0, 0, 15)\n top_format = workbook.add_format({'bold': True, 'align': 'right'})\n worksheet.write(0, 0, 'Account', top_format)\n worksheet.write(0, 1, 'Balance', top_format)\n row = 1\n column = 0\n num_format = workbook.add_format()\n num_format.set_num_format('0')\n for acc, bal in result_dict.items():\n worksheet.write(row, column, acc, num_format)\n worksheet.write(row, column + 1, bal, num_format)\n row = row + 1\n workbook.close()\n\ndef main():\n\n xlsx_input_file_path = 'C://Users//dmitriy.khimich//Downloads//DMS_RPA_Challenge//DMS_RPA_Challenge//Банк выгрузка 2017 Сент.xlsx'\n csv_input_file_path = 'C://Users//dmitriy.khimich//Downloads//DMS_RPA_Challenge//DMS_RPA_Challenge//торговая сеть сент 2017.csv'\n xlsx_output_file_path = 'C://Users//dmitriy.khimich//Downloads//DMS_RPA_Challenge//DMS_RPA_Challenge//example2.xlsx'\n\n open_xlsx_file(xlsx_input_file_path)\n open_csv_file(csv_input_file_path)\n compare_files(xlsx_input_file_path, csv_input_file_path)\n save_report(xlsx_output_file_path, xlsx_input_file_path, csv_input_file_path)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"task_for_DMS_(with func).py","file_name":"task_for_DMS_(with func).py","file_ext":"py","file_size_in_byte":2802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"561796997","text":"#coding=utf-8\n\n\"\"\"\nCreated on 2020/9/8\n@usergpor: lianxiujuan\n@desc: 用户组\n\"\"\"\n\nimport pytest\nimport sys\nfrom src.pageobjectAdmin.pageUsergp import *\nfrom DataAdmin.UsergrpData import *\nfrom src.public.common.Login import *\nfrom src.public.common.Select_Item import *\n\n\n\nclass Test_Usergp:\n def test_usergp_login(self):\n login_usergp()\n sleep(1)\n\n # 新增用户组\n def test_add_usergp(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n usergp_add(addcodedata, addnamedata)\n time.sleep(2)\n assert new_page_source(addnamedata)\n\n # 设置权限\n def test_setauth_usergp(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n select_item(addnamedata)\n usergp_setauth()\n time.sleep(2)\n usergp_setauth()\n\n # 编辑用户组\n def test_edit_usergp(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n select_item(addnamedata)\n usergp_edit(editnamedata)\n time.sleep(2)\n assert new_page_source(editnamedata)\n\n # 删除用户组\n def test_delete_usergp(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n select_item(addnamedata)\n usergp_delete()\n time.sleep(2)\n assert new_page_source(addnamedata) == False\n new_click(authmg)\n\n\n\n","sub_path":"TestcaseAdmin/Usermg&Group&Authmg/test_Usergpcase.py","file_name":"test_Usergpcase.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"572478598","text":"from sense_hat import SenseHat\nimport time\nimport sys\nimport serial\nimport datetime\nimport os\nfrom urllib import urlencode\nimport urllib2\nsense = SenseHat()\nMEASURMENT_INTERVAL = 2\n\nWEATHER_UPLOAD = True\n\nWU_URL = \"http://weatherstation.wunderground.com/weatherstation/updateweatherstation.php\"\n\nSINGLE_HASH = '#'\n\nHASHES = '####################################'\nSLASH_N = '\\n'\n\n\ndef main():\n\n global last_temp\n\n last_minute = datetime.datetime.now().minute\n\n last_minute -= 1\n if last_minute == 0: \n last_minute = 59\n while 1:\n\n current_second = datetime.datetime.now().second\n if (current_second == 0) or ((current_second % 5) == 0):\n serialMsg = serial.Serial(\"/dev/ttyACM0\", 9600, timeout = 1)\n rawMsg = serialMsg.readline()\n message = (rawMsg.decode().strip())\n calc_temp = message\n print(calc_temp)\n temp_f = calc_temp \n humidity = round(sense.get_humidity(), 0)\n pressure = round(sense.get_pressure() * 0.0295300, 1)\n print(\"Temp: %sF, Pressure: %s inHg, Humidity: %s%%\" % (temp_f, pressure, humidity))\n current_minute = datetime.datetime.now().minute\n if current_minute:\n last_minute = current_minute\n if (current_minute == 0) or ((current_minute % MEASURMENT_INTERVAL) == 0):\n now = datetime.datetime.now()\n print(\"\\n%d minute mark (%d @ %s)\" % (MEASURMENT_INTERVAL, current_minute, str(now)))\n\n if WEATHER_UPLOAD:\n print(\"Uploading data to Weather Underground\")\n\n weather_data = {\n \"action\": \"updateraw\",\n \"ID\": wu_station_id,\n \"PASSWORD\": wu_station_key,\n \"dateutc\": \"now\",\n \"tempf\": str(temp_f),\n \"humidity\": str(humidity),\n \"baromin\": str(pressure),\n }\n try:\n upload_url = WU_URL + \"?\" + urlencode(weather_data)\n response = urllib2.urlopen(upload_url)\n html = response.read()\n print(\"Server response:\", html)\n response.close()\n except:\n print(\"Exception:\", sys.exc_info()[0], SLASH_N)\n else:\n print(\"Skipping Weather Underground upload\")\n time.sleep(1)\n print(\"Leaving main()\")\n\nprint(SLASH_N + HASHES)\nprint(SINGLE_HASH, \"Pi Weather Station \", SINGLE_HASH)\nprint(HASHES)\n\nif (MEASURMENT_INTERVAL is None) or (MEASURMENT_INTERVAL > 60):\n print(\"The application's 'MEASURMENT_INTERVAL' cannot be empty or greater than 60\")\n sys.exit(1)\n\nprint(\"\\nIntalising Weather Underground configuration\")\nwu_station_id = \"IDROITWI14\"\nwu_station_key = \"tbrmknbc\"\nif (wu_station_id is None) or (wu_station_key is None):\n print(\"Missingvalues from the Weather Underground config\")\n sys.exit(1)\n\nprint(\"Sucsessfully read Weather Underground config\")\nprint(\"Station ID:\", wu_station_id)\n\n\n\ntry:\n main()\nexcept KeyboardInterrupt:\n print(\"\\nExiting application\\n\")\n sys.exit(0)\n \n \n\n","sub_path":"weather-script-for-wu.py","file_name":"weather-script-for-wu.py","file_ext":"py","file_size_in_byte":4250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"492609734","text":"import os\nimport argparse\nfrom copy import deepcopy\n\nDATA_DIR = '../data'\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--seed\", type=int, default=0)\nparser.add_argument(\"--epochs\", nargs='+', type=int,\n default=[10, 10, 10, 10, 10],\n help='Epoch number for each task')\nparser.add_argument(\"--batch_size\", type=int, default=8,\n help='training batch size')\nparser.add_argument(\"--bert_learning_rate\", type=float, default=3e-5,\n help='learning rate for pretrained Bert')\nparser.add_argument(\"--learning_rate\", type=float, default=3e-5,\n help='learning rate for Class Classifier')\nparser.add_argument('--gpu', default='0', type=str,\n help='id(s) for CUDA_VISIBLE_DEVICES')\nparser.add_argument('--n-labeled', type=int, default=2000,\n help='Number of labeled data')\nparser.add_argument('--tasks', nargs='+', type=str,\n default=['ag', 'yelp', 'amazon', 'yahoo', 'dbpedia'],\n help='Task Sequence')\n\nargs = parser.parse_args()\nos.environ['CUDA_VISIBLE_DEVICES'] = args.gpu\n\nimport numpy as np\nimport torch\nfrom tqdm import tqdm\nfrom transformers import AdamW\n\nfrom model import BaseModel\nfrom read_data import compute_class_offsets, prepare_dataloaders\n\nuse_cuda = torch.cuda.is_available()\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nargs.device = device\nn_gpu = torch.cuda.device_count()\n\ndataset_classes = {\n 'amazon' : 5,\n 'yelp' : 5,\n 'yahoo' : 10,\n 'ag' : 4,\n 'dbpedia' : 14,\n}\n\n\ndef train_step(model, optimizer, cls_CR, x, y):\n model.train()\n logits = model(x)\n loss = cls_CR(logits, y)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n return loss\n\n\ndef validation(model, t, validation_loaders):\n '''\n Compute the validation accuracy on the first (t + 1) tasks,\n return the average accuracy over (t + 1) tasks and detailed accuracy\n on each task.\n '''\n model.eval()\n acc_list = []\n with torch.no_grad():\n avg_acc = 0.0\n for i in range(t + 1):\n valid_loader = validation_loaders[i]\n total = 0\n correct = 0\n for x, mask, y in valid_loader:\n x, y = x.to(device), y.to(device)\n batch_size = x.size(0)\n logits = model(x)\n _, pred_cls = logits.max(1)\n correct += pred_cls.eq(y.view_as(pred_cls)).sum().item()\n total += batch_size\n print(\"acc on task {} : {}\".format(i, correct * 100.0 / total))\n avg_acc += correct * 100.0 / total\n acc_list.append(correct * 100.0 / total)\n\n return avg_acc / (t + 1), acc_list\n\n\ndef main():\n np.random.seed(0)\n torch.manual_seed(args.seed)\n if torch.cuda.is_available():\n torch.cuda.manual_seed(args.seed)\n\n task_num = len(args.tasks)\n task_classes = [dataset_classes[task] for task in args.tasks]\n total_classes, offsets = compute_class_offsets(args.tasks, task_classes)\n train_loaders, validation_loaders, test_loaders = \\\n prepare_dataloaders(DATA_DIR, args.tasks, offsets, args.n_labeled,\n 2000, args.batch_size, 128, 128)\n\n # Reset random seed by the torch seed\n np.random.seed(torch.randint(1000, [1]).item())\n\n model = BaseModel(total_classes).to(args.device)\n cls_CR = torch.nn.CrossEntropyLoss()\n\n for task_id in range(task_num):\n data_loader = train_loaders[task_id]\n length = len(data_loader)\n\n optimizer = AdamW(\n [\n {\"params\": model.bert.parameters(), \"lr\": args.bert_learning_rate},\n {\"params\": model.classifier.parameters(), \"lr\": args.learning_rate},\n ]\n )\n\n best_acc = 0\n best_model = deepcopy(model.state_dict())\n\n acc_track = []\n\n for epoch in range(args.epochs[task_id]):\n iteration = 1\n for x, mask, y in tqdm(data_loader, total=length, ncols=100):\n x, y = x.to(device), y.to(device)\n train_step(model, optimizer, cls_CR, x, y)\n\n if iteration % 250 == 0:\n print(\"----------------Validation-----------------\")\n avg_acc, acc_list = validation(model, task_id, validation_loaders)\n acc_track.append(acc_list)\n\n if avg_acc > best_acc:\n print(\"------------------Best Model Till Now------------------------\")\n best_acc = avg_acc\n best_model = deepcopy(model.state_dict())\n\n iteration += 1\n\n if len(acc_track) > 0:\n print(\"ACC Track: {}\".format(acc_track))\n\n model.load_state_dict(deepcopy(best_model))\n print(\"------------------Best Result------------------\")\n avg_acc, _ = validation(model, task_id, test_loaders)\n print(\"Best avg acc: {}\".format(avg_acc))\n\n\nif __name__ == '__main__':\n print(args)\n main()\n","sub_path":"src/finetune.py","file_name":"finetune.py","file_ext":"py","file_size_in_byte":5085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"571450762","text":"#!/usr/bin/env python\r\n# -- coding: utf-8 --\r\nimport sys\r\nfrom config import *\r\nfrom pymongo import MongoClient\r\nfrom data_parse import *\r\nreload(sys)\r\nsys.setdefaultencoding(\"utf-8\")\r\n\r\nclass MongoConnect():\r\n def __init__(self,mongo_database,mongo_set,mongo_host='172.25.3.215',mongo_port=27017):\r\n self.mongo_host=mongo_host\r\n self.mongo_port=mongo_port\r\n self.mongo_database=mongo_database\r\n self.mongo_set=mongo_set\r\n self.mongo_cursor,self.mongo_client=self.connect_mongo()\r\n self.bulk_mongodb_cursor, self.bulk_mongo_client=self.bulk_connect_mongo()\r\n\r\n def connect_mongo(self):\r\n mongo_client=MongoClient(host=self.mongo_host,port=self.mongo_port)\r\n mongo_db=mongo_client[self.mongo_database]\r\n mongo_cursor=mongo_db[self.mongo_set]\r\n return mongo_cursor,mongo_client\r\n\r\n def bulk_connect_mongo(self):\r\n bulk_mongo_client=MongoClient(host=self.mongo_host,port=self.mongo_port)\r\n bulk_mongo_db=bulk_mongo_client[self.mongo_database]\r\n bulk_mongodb_cursor = bulk_mongo_db[self.mongo_set].initialize_ordered_bulk_op()\r\n return bulk_mongodb_cursor,bulk_mongo_client\r\n\r\n def mongo_save_many(self,datas):\r\n res=self.mongo_cursor.insert_many(datas)\r\n print(res)\r\n\r\n def mongo_create_index(self,index_col_name):\r\n self.mongo_cursor.create_index([(index_col_name,1)])\r\n\r\n def get_mongo_endtime_starttime(self,sort_col_name,query={}):\r\n '''\r\n 用于分页查找时建立基于分页的索引项\r\n :param sort_col_name:\r\n :param query:\r\n :return:\r\n '''\r\n if query=={}:\r\n datanum = self.mongo_cursor.count()\r\n\r\n res1 = self.mongo_cursor.find().sort(sort_col_name, 1).limit(1)\r\n starttimestamp = -1\r\n for data in res1:\r\n starttimestamp += data.get(sort_col_name)\r\n\r\n res2 = self.mongo_cursor.find().sort(sort_col_name, -1).limit(1)\r\n endtimestamp = 0\r\n for data in res2:\r\n endtimestamp += data.get(sort_col_name)\r\n else:\r\n datanum = self.mongo_cursor.find(query).count()\r\n\r\n res1 = self.mongo_cursor.find(query).sort(sort_col_name, 1).limit(1)\r\n starttimestamp = -1\r\n for data in res1:\r\n starttimestamp += data.get(sort_col_name)\r\n\r\n res2 = self.mongo_cursor.find(query).sort(sort_col_name, -1).limit(1)\r\n endtimestamp = 0\r\n for data in res2:\r\n endtimestamp += data.get(sort_col_name)\r\n return datanum,starttimestamp,endtimestamp\r\n\r\n def mongo_update_bulk(self,query_col_name,query_respon_name,datas):\r\n for data in datas:\r\n self.bulk_mongodb_cursor.find({query_col_name:data.get(query_respon_name)}).update({'$set':data})\r\n result=self.bulk_mongodb_cursor.execute()\r\n print(result)\r\n\r\n def close_mongo_client(self):\r\n self.mongo_client.close()\r\n\r\n def close_bulk_mongo_client(self):\r\n self.bulk_mongo_client.close()\r\n\r\n\r\nclass MongoFold():\r\n '''\r\n 对mongodb的数据分页查找并更新,实际用时需对具体方法继承更新\r\n '''\r\n def __init__(self,parse_mongo_db_name,parse_mongo_set_name,save_mongo_db,save_mongo_set,query={}):\r\n self.mongo_db_name = parse_mongo_db_name\r\n self.mongo_set_name = parse_mongo_set_name\r\n self.mongo_connect_model = MongoConnect(mongo_host='172.25.3.215',mongo_port=27017, mongo_database=self.mongo_db_name,\r\n mongo_set=self.mongo_set_name)\r\n # self.parse_model=DataParse(parse_db_name=self.mongo_db_name,parse_set_name=self.mongo_set_name)\r\n self.query=query\r\n self.mongo_save_model = MongoConnect(mongo_database=save_mongo_db, mongo_set=save_mongo_set)\r\n\r\n\r\n def get_query_params(self,sort_col_name):\r\n query = self.query\r\n mongo_connect_model=self.mongo_connect_model\r\n datanum, starttimestamp, endtimestamp=mongo_connect_model.get_mongo_endtime_starttime(sort_col_name=sort_col_name,query=query)\r\n return datanum,starttimestamp,endtimestamp\r\n\r\n def person_fundinfo_parse(self,id):\r\n pass\r\n\r\n def fold_find_parse(self,sort_col_name,fold_row_num):\r\n datanum, starttimestamp, endtimestamp=self.get_query_params(sort_col_name)\r\n while starttimestamp < endtimestamp:\r\n for i in range(datanum / fold_row_num + 1):\r\n res_datas = []\r\n print(i+1)\r\n datas = self.mongo_connect_model.mongo_cursor.find({sort_col_name: {'$gt': starttimestamp},\"nationality\": {'$exists': False}},{\"_id\":1,\"updatetime_stamp\":1}).sort(sort_col_name, 1).limit(fold_row_num)\r\n for data in datas:\r\n res_datas.append(self.person_fundinfo_parse(data))\r\n timestamp=data.get('updatetime_stamp')\r\n starttimestamp=timestamp\r\n yield res_datas\r\n\r\n def create_indexes(self,index_col_name):\r\n self.mongo_save_model.mongo_create_index(index_col_name)\r\n\r\n def save_data(self,sort_col_name,fold_row_num):\r\n for datas in self.fold_find_parse(sort_col_name=sort_col_name,fold_row_num=fold_row_num):\r\n try:\r\n self.mongo_save_model.mongo_save_many(datas=datas)\r\n except:\r\n continue\r\n\r\n def insert_update_data(self,data,update_mongo_db,update_mongo_set):\r\n '''\r\n 插入或更新\r\n :param upate_mongo_db:\r\n :param update_mongo_set:\r\n :param sort_col_name:\r\n :return:\r\n '''\r\n mongo_update_model = MongoConnect(mongo_database=update_mongo_db, mongo_set=update_mongo_set)\r\n res=mongo_update_model.mongo_cursor.update({\"_id\": data[\"resource_id\"]},{'$set': data}, upsert=True)\r\n print(res)\r\n\r\n def update_data(self,upate_mongo_db,update_mongo_set,sort_col_name,fold_row_num):\r\n for datas in self.fold_find_parse(sort_col_name=sort_col_name,fold_row_num=fold_row_num):\r\n try:\r\n mongo_update_model=MongoConnect(mongo_database=upate_mongo_db,mongo_set=update_mongo_set)\r\n mongo_update_model.mongo_update_bulk(query_col_name=\"_id\",query_respon_name='resource_id',datas=datas)\r\n mongo_update_model.close_bulk_mongo_client()\r\n except:\r\n continue\r\n\r\n\r\nif __name__ == '__main__':\r\n pass","sub_path":"company_data_mapping/util_functions/database_connect.py","file_name":"database_connect.py","file_ext":"py","file_size_in_byte":6461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"155667619","text":"class Student:\n\tcourseMarks={}\n\tname= \"\"\n\n\tdef __init__(self, first_name, last_name):\n\t\tself.name = \"%s %s\" % (first_name, last_name)\n\n\tdef addCourseMark(self, course, mark):\n\t\tself.courseMarks[course] = mark\n\n\tdef average(self):\n\t\ttotal = 0\n\t\tcount = 0\n\t\tfor key, value in self.courseMarks.iteritems():\n\t\t\ttotal += value\n\t\t\tcount += 1\n\t\taverage = total/count\n\t\treturn average\n\nS = Student(\"John\", \"Doe\")\nS.addCourseMark(\"CMPUT410\", 50)\nS.addCourseMark(\"CMPUT391\", 100)\nS.addCourseMark(\"CMPUT400\", 100)\nS.addCourseMark(\"CMPUT495\", 50)\nprint(S.courseMarks)\nprint(S.name)\nprint(S.average())\n","sub_path":"name-family.py","file_name":"name-family.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"216622149","text":"from m5stack import *\nfrom machine import Timer\n\nimport Data.Menu\n\n\nclass Battery:\n\n def __init__(self):\n\n \"\"\"Initialize Battery.\"\"\"\n\n self.vbat = int()\n\n lcd.clear(0xFF8000)\n\n buttonA.wasPressed(callback=self.exit)\n buttonB.wasPressed(callback=lambda: None)\n\n self.show_battery()\n\n self.refresh = Timer(0)\n self.refresh.init(period=10000, mode=Timer.PERIODIC, callback=self.show_battery)\n\n def show_battery(self, t=None):\n\n \"\"\"Convert battery voltage into bars.\"\"\"\n\n self.vbat = self.map_value(axp.getVbatData() * 1.1, 3000, 4100, 0, 6)\n print(axp.getVbatData() * 1.1)\n print(self.vbat)\n\n if axp.getIChargeData() / 2 > 0:\n color = lcd.YELLOW\n elif self.vbat == 1:\n color = lcd.RED\n elif self.vbat == 2:\n color = lcd.ORANGE\n else:\n color = lcd.GREEN\n\n # Battery Icon.\n lcd.fillRect(22, 10, 125, 60, lcd.BLACK)\n lcd.fillRect(12, 30, 10, 20, lcd.BLACK)\n\n # Reset bars.\n lcd.fillRect(127, 15, 15, 50, lcd.BLACK)\n lcd.fillRect(107, 15, 15, 50, lcd.BLACK)\n lcd.fillRect(87, 15, 15, 50, lcd.BLACK)\n lcd.fillRect(67, 15, 15, 50, lcd.BLACK)\n lcd.fillRect(47, 15, 15, 50, lcd.BLACK)\n lcd.fillRect(27, 15, 15, 50, lcd.BLACK)\n\n # Draw bars.\n if self.vbat >= 1:\n lcd.fillRect(127, 15, 15, 50, color)\n if self.vbat >= 2:\n lcd.fillRect(107, 15, 15, 50, color)\n if self.vbat >= 3:\n lcd.fillRect(87, 15, 15, 50, color)\n if self.vbat >= 4:\n lcd.fillRect(67, 15, 15, 50, color)\n if self.vbat >= 5:\n lcd.fillRect(47, 15, 15, 50, color)\n if self.vbat >= 6:\n lcd.fillRect(27, 15, 15, 50, color)\n\n def exit(self):\n\n \"\"\"De-init timer and exit.\"\"\"\n\n self.refresh.deinit()\n\n # Return to menu\n return Data.Menu.Menu()\n\n @staticmethod\n def map_value(x, in_min, in_max, out_min, out_max):\n return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min\n","sub_path":"Data/Battery.py","file_name":"Battery.py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"419901075","text":"from django.urls import path\nfrom .views import StudentStreamListCreateView, StudentStreamRetrieveUpdateView,\\\n StudentGroupListCreateView, StudentGroupRetrieveUpdateView, \\\n StudentGroupMembersListCreateView, GroupInStreamListCreateView, StudentListView\nfrom .views import CourseCreateView, CourseRetrieveUpdateView, LessonCreateView, \\\n LessonRetrieveUpdateView, StudentLessonResultCreateView, \\\n StudentLessonResultRetrieveUpdateView, CourseListView, \\\n LessonListView, StudentLessonResultListView\n\nfrom .views import ClassmatesCheckedTaskListCreateView, ClassmatesCheckedTaskRetrieveUpdateDestroyView\nfrom .views import TaskOptionListCreateView, TaskOptionRetrieveUpdateDestroyView\nfrom .views import StudentResultListCreateView, StudentResultRetrieveUpdateDestroyView\nfrom .views import CheckListCreateView, CheckRetrieveUpdateDestroyView\n\nfrom .views import TaskWithTeacherCheckListCreateView, TaskWithTeacherCheckRetrieveUpdateDestroyView\nfrom .views import TaskWithTeacherCheckOptionListCreateView, TaskWithTeacherCheckOptionRetrieveUpdateDestroyView\nfrom .views import TaskWithTeacherCheckResultListCreateView, TaskWithTeacherCheckResultRetrieveUpdateDestroyView\nfrom .views import TaskWithTeacherCheckCheckListCreateView, TaskWithTeacherCheckCheckRetrieveUpdateDestroyView\n\nfrom .views import SectionCreateView, SectionListView, SectionRetrieveView, \\\n SectionUpdateView, TaskWithTickCreateView, TaskWithTickListView\nfrom .views import TaskWithTickRetrieveView, TaskWithTickUpdateView, \\\n TaskWithTickOptionCreateView, TaskWithTickOptionListView, \\\n TaskWithTickOptionRetrieveView, TaskWithTickOptionUpdateView, \\\n TaskWithTickStudentResultCreateView, TaskWithTickStudentResultRetrieveView, \\\n TaskWithTickStudentResultUpdateView, TaskWithTickStudentResultListView, \\\n StatisticsTaskByStudent, StatisticsStudentResults\n\n# task with keyword views\nfrom .views import TaskWithKeywordCreateView, TaskWithKeywordRetrieveView, \\\n TaskWithKeywordUpdateView, TaskWithKeywordListView, TaskWithKeywordOptionCreateView, \\\n TaskWithKeywordOptionRetrieveView, TaskWithKeywordOptionUpdateView, \\\n TaskWithKeywordOptionListView, TaskWithKeywordResultCreateView, \\\n TaskWithKeywordResultRetrieveView, TaskWithKeywordResultUpdateView, \\\n TaskWithKeywordResultListView\n\n\napp_name = \"courses_app\"\n\nurlpatterns = [\n path('students/', StudentListView.as_view()),\n\n path('streams/', StudentStreamListCreateView.as_view()),\n path('streams//', StudentStreamRetrieveUpdateView.as_view()),\n path('streams//groups/', GroupInStreamListCreateView.as_view()),\n\n path('groups/', StudentGroupListCreateView.as_view()),\n path('groups//', StudentGroupRetrieveUpdateView.as_view()),\n path('groups//members/', StudentGroupMembersListCreateView.as_view()),\n\n path('courses/add/', CourseCreateView.as_view()),\n path('courses/all/', CourseListView.as_view()),\n path('courses//', CourseRetrieveUpdateView.as_view()),\n\n path('classmates/tasks/', ClassmatesCheckedTaskListCreateView.as_view()),\n path('classmates/tasks//', ClassmatesCheckedTaskRetrieveUpdateDestroyView.as_view()),\n\n path('classmates/options/', TaskOptionListCreateView.as_view()),\n path('classmates/options//', TaskOptionRetrieveUpdateDestroyView.as_view()),\n\n path('classmates/results/', StudentResultListCreateView.as_view()),\n path('classmates/results//', StudentResultRetrieveUpdateDestroyView.as_view()),\n\n path('classmates/checks/', CheckListCreateView.as_view()),\n path('classmates/checks//', CheckRetrieveUpdateDestroyView.as_view()),\n\n path('teacher/tasks/', TaskWithTeacherCheckListCreateView.as_view()),\n path('teacher/tasks//', TaskWithTeacherCheckResultRetrieveUpdateDestroyView.as_view()),\n\n path('teacher/options/', TaskWithTeacherCheckOptionListCreateView.as_view()),\n path('teacher/options//', TaskWithTeacherCheckOptionRetrieveUpdateDestroyView.as_view()),\n\n path('teacher/results/', TaskWithTeacherCheckResultListCreateView.as_view()),\n path('teacher/results//', TaskWithTeacherCheckResultRetrieveUpdateDestroyView.as_view()),\n\n path('teacher/checks/', TaskWithTeacherCheckCheckListCreateView.as_view()),\n path('teacher/checks//', TaskWithTeacherCheckCheckRetrieveUpdateDestroyView.as_view()),\n\n path('lessons/add/', LessonCreateView.as_view()),\n path('lessons/all/', LessonListView.as_view()),\n path('lessons//', LessonRetrieveUpdateView.as_view()),\n\n path('lessons/results/add/', StudentLessonResultCreateView.as_view()),\n path('lessons/results/all/', StudentLessonResultListView.as_view()),\n path('lessons/results//', StudentLessonResultRetrieveUpdateView.as_view()),\n\n path('courses/sections/add/', SectionCreateView.as_view()),\n path('courses/sections/all/', SectionListView.as_view()),\n path('courses/sections//', SectionRetrieveView.as_view()),\n path('courses/sections/update//', SectionUpdateView.as_view()),\n\n path('tasks/with_tick/add/', TaskWithTickCreateView.as_view()),\n path('tasks/with_tick/all/', TaskWithTickListView.as_view()),\n path('tasks/with_tick//', TaskWithTickRetrieveView.as_view()),\n path('tasks/with_tick/update//', TaskWithTickUpdateView.as_view()),\n\n path('tasks/with_tick/options/add/', TaskWithTickOptionCreateView.as_view()),\n path('tasks/with_tick/options/all/', TaskWithTickOptionListView.as_view()),\n path('tasks/with_tick/options//', TaskWithTickOptionRetrieveView.as_view()),\n path('tasks/with_tick/options/update//', TaskWithTickOptionUpdateView.as_view()),\n\n path('tasks/with_tick/results/add/', TaskWithTickStudentResultCreateView.as_view()),\n path('tasks/with_tick/results/all/', TaskWithTickStudentResultListView.as_view()),\n path('tasks/with_tick/results//', TaskWithTickStudentResultRetrieveView.as_view()),\n path('tasks/with_tick/results/update//', TaskWithTickStudentResultUpdateView.as_view()),\n\n path('tasks/with_keyword/add/', TaskWithKeywordCreateView.as_view()),\n path('tasks/with_keyword/all/', TaskWithKeywordListView.as_view()),\n path('tasks/with_keyword//', TaskWithKeywordRetrieveView.as_view()),\n path('tasks/with_keyword/update//', TaskWithKeywordUpdateView.as_view()),\n\n path('tasks/with_keyword/options/add/', TaskWithKeywordOptionCreateView.as_view()),\n path('tasks/with_keyword/options/all/', TaskWithKeywordOptionListView.as_view()),\n path('tasks/with_keyword/options//', TaskWithKeywordOptionRetrieveView.as_view()),\n path('tasks/with_keyword/options/update//', TaskWithKeywordOptionUpdateView.as_view()),\n\n path('tasks/with_keyword/results/add/', TaskWithKeywordResultCreateView.as_view()),\n path('tasks/with_keyword/results/all/', TaskWithKeywordResultListView.as_view()),\n path('tasks/with_keyword/results//', TaskWithKeywordResultRetrieveView.as_view()),\n path('tasks/with_keyword/results/update//', TaskWithKeywordResultUpdateView.as_view()),\n\n path('statistics/sections//tasks//results/', StatisticsTaskByStudent.as_view()),\n path(\n 'statistics/sections//tasks//students//results/',\n StatisticsStudentResults.as_view(),\n ),\n]\n","sub_path":"application/courses_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":7410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"611967079","text":"import torch\nimport torch.nn as nn\nimport torch.autograd as autograd\nfrom torch.autograd import Variable\n\n\nimport neural_ner\nfrom neural_ner.util import Initializer\nfrom neural_ner.util import Loader\nfrom neural_ner.modules import CharEncoderCNN\nfrom neural_ner.modules import WordEncoderRNN\nfrom neural_ner.modules import DecoderCRF\n\nclass CNN_BiLSTM_CRF(nn.Module):\n \n def __init__(self, word_vocab_size, word_embedding_dim, word_hidden_dim, char_vocab_size,\n char_embedding_dim, char_out_channels, tag_to_id, cap_input_dim=4 ,\n cap_embedding_dim=0, pretrained=None):\n \n super(CNN_BiLSTM_CRF, self).__init__()\n \n self.word_vocab_size = word_vocab_size\n self.word_embedding_dim = word_embedding_dim\n self.word_hidden_dim = word_hidden_dim\n \n self.char_vocab_size = char_vocab_size\n self.char_embedding_dim = char_embedding_dim\n self.char_out_channels = char_out_channels\n \n self.cap_input_dim = cap_input_dim\n self.cap_embedding_dim = cap_embedding_dim\n \n self.tag_to_ix = tag_to_id\n self.tagset_size = len(tag_to_id)\n \n self.initializer = Initializer()\n self.loader = Loader()\n \n if self.cap_embedding_dim:\n self.cap_embedder = nn.Embedding(self.cap_input_dim, self.cap_embedding_dim)\n self.initializer.init_embedding(self.cap_embedder.weight)\n \n self.char_encoder = CharEncoderCNN(char_vocab_size, char_embedding_dim, char_out_channels, \n kernel_width=3, pad_width=1)\n \n self.initializer.init_embedding(self.char_encoder.embedding.weight)\n \n self.word_encoder = WordEncoderRNN(word_vocab_size, word_embedding_dim ,word_hidden_dim, \n char_out_channels, cap_embedding_dim, input_dropout_p=0.5)\n \n if pretrained is not None:\n self.word_encoder.embedding.weight = nn.Parameter(torch.FloatTensor(pretrained))\n \n self.initializer.init_lstm(self.word_encoder.rnn)\n \n self.decoder = DecoderCRF(word_hidden_dim*2, self.tag_to_ix, input_dropout_p=0.5)\n self.initializer.init_linear(self.decoder.hidden2tag)\n \n def forward(self, words, tags, chars, caps, wordslen, charslen, tagsmask, usecuda=True):\n \n batch_size, max_len = words.size()\n \n cap_features = self.cap_embedder(caps) if self.cap_embedding_dim else None\n \n char_features = self.char_encoder(chars)\n char_features = char_features.view(batch_size, max_len, -1)\n \n word_features = self.word_encoder(words, char_features, cap_features, wordslen)\n \n score = self.decoder(word_features, tags, tagsmask, usecuda=usecuda)\n \n return score\n \n def decode(self, words, chars, caps, wordslen, charslen, tagsmask, usecuda=True,\n score_only = False):\n \n batch_size, max_len = words.size()\n \n cap_features = self.cap_embedder(caps) if self.cap_embedding_dim else None\n \n char_features = self.char_encoder(chars)\n char_features = char_features.view(batch_size, max_len, -1)\n \n word_features = self.word_encoder(words, char_features, cap_features, wordslen)\n \n if score_only:\n score = self.decoder.decode(word_features, tagsmask, usecuda=usecuda, \n score_only = True)\n return score\n score, tag_seq = self.decoder.decode(word_features, tagsmask, usecuda=usecuda)\n return score, tag_seq","sub_path":"neural_ner/models/cnn_bilstm_crf.py","file_name":"cnn_bilstm_crf.py","file_ext":"py","file_size_in_byte":3690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"152467651","text":"s = ['hi', 'hello', 'word']\ndef g(x):\n return x[::-1]\ns = list(map(g,s))\nprint(s)\n\n# or by lambda\ns = ['hi', 'hello', 'word']\ns = list(map(lambda x: x[::-1], s))\nprint(s)\n\n\n# max of x, y -----------------------------------------\ndef mx(x, y):\n if x > y:\n return x\n else:\n return y\nprint((mx(8,5)))\n\n# by lambda\nmx = lambda x, y: x if x > y else y\nprint(mx(20, 10))\n\nprint('\\n\\n\\n')\n\n\n# map ---------------------------------------------------\ndef square(lst1):\n lst2 = []\n for num in lst1:\n lst2.append(num**2)\n return lst2\nprint(square([4,3,2,1]))\n\n# by lambda\nn = [4,3,2,1]\nprint(list(map(lambda x: x**2, n)))\n\n# by list comprehension\nn = [4,3,2,1]\nprint([x**2 for x in n])\n\nprint('\\n\\n\\n')\n\n\n\n# filter -----------------------------------------------\ndef over_two(lst1):\n lst2 = [x for x in lst1 if x > 2]\n return lst2\nprint(over_two([4,3,2,1]))\n\n# by lambda\nn = [4,3,2,1]\nprint(list(filter(lambda x: x>2, n)))\n\n# by list comprehension\nn = [4,3,2,1]\nprint([x for x in n if x>2])\n\nprint('\\n\\n\\n')\n\n\n\n\n# reduce -----------------------------------------------\ndef mult(lst1):\n prod = lst1[0]\n for i in range(1, len(lst1)):\n prod *=lst1[i]\n return prod\nprint(mult([4,3,2,1]))\n\n# by lambda\n# import reduce\n# n = [4,3,2,1]\n# print(reduce(lambda x,y: x*y, n))\n","sub_path":"lambda/lambda_examples.py","file_name":"lambda_examples.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"245675189","text":"#!/usr/bin/env python3\n\nimport sys\n\ndef help():\n\tprint('''\n\t\tUsage:\n\t\t------------\n\t\tretrotransposonNamesFromDomainOrganization.py -features -domains \n\t\t-OR-\n\t\tretrotransposonNamesFromDomainOrganization.py -features \n\n\t\tDescription:\n\t\t------------\n\t\tTakes a two column file as input via -features and a list of comma-separated\n\t\tprotein domains via -domains and outputs feature names (from the first column\n\t\tof the -features file) if the domain organization of the feature is one of those\n\t\tin the -domains file.\n\n\n\n\t\tOptions:\n\t\t------------\n\t\t-features\tA two-column tab-separated file. It's assumed that the first column\n\t\t\t\tis the name of a feature and the second column is a component of that\n\t\t\t\tfeature and that components for a given feature are in order such that\n\t\t\t\ta compenent at row n is before the component at row n+1\n\n\t\t-domains\tLines in this file should be comma separated names of domains.\n\n\t\t-names\t\tPrint out domain structure as comma-separated list for feature names in\n\t\t\t\tthe file specified by -names.\n\t\t\n\t\t''')\n\tsys.exit(0)\n\n\nargs = sys.argv\n\nif len(args) != 5 or '-features' not in args:\n\thelp()\n\nfeatures_fl_pth = args[args.index('-features') + 1]\n\nif '-domains' in args:\n\tdomains_fl_pth = args[args.index('-domains') + 1]\nelif '-names' in args:\n\tnames_fl_pth = args[args.index('-names') + 1]\n\n\nd = {} # this dict will have domain organization for each ltr in the -features file\n\n\nwith open(features_fl_pth) as features_fl:\n\tfor line in features_fl:\n\t\tcontents = line.split()\n\t\tltrname = contents[0]\n\t\tdomain = contents[1]\n\t\tif ltrname in d:\n\t\t\td[ltrname].append(domain)\n\t\telse:\n\t\t\td[ltrname] = [domain]\nif '-domains' in args:\n\tdomain_organization = []\n\twith open(domains_fl_pth) as domains_fl:\n\t\tfor line in domains_fl:\n\t\t\tdomain_organization.append(line.strip().split(','))\n\n\tfor ltr in d:\n\t\tif d[ltr] in domain_organization:\n\t\t\tprint(ltr)\n\nelif '-names' in args:\n\tnames_list = []\n\twith open(names_fl_pth) as names_fl:\n\t\tfor line in names_fl:\n\t\t\tnames_list.append(line.strip())\n\n\tfor ltr in d:\n\t\tif ltr in names_list:\n\t\t\tprint('{0}\\t{1}'.format(ltr, ','.join(d[ltr])))\n","sub_path":"retrotransposonNamesFromDomainOrganization.py","file_name":"retrotransposonNamesFromDomainOrganization.py","file_ext":"py","file_size_in_byte":2131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"539541755","text":"import os\nfrom time import time\nfrom sys import stdout\nimport torch\nimport h5py as h5\nimport numpy as np\nimport torch.nn as nn\nfrom networks.models import Conditional_RNVP_with_image_prior\nfrom networks.losses import Conditional_RNVP_with_image_prior_loss\nfrom networks.optimizers import Adam, LRUpdater\nimport visdom\n\n\nclass AverageMeter(object):\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\n\ndef save_model(state, model_name):\n torch.save(state, model_name)\n print('Model saved to ' + model_name)\n\ndef cnt_params(params):\n return sum(p.numel() for p in params if p.requires_grad)\n\n\ndef save_point_clouds(batch_i, gt_cloud, gen_cloud, image, len_dataset, **kwargs):\n\n clouds_fname = '{}_{}_{}_{}_segs_clouds.h5'.format(kwargs['model_name'][:-4],\n kwargs['cloud_size'],\n kwargs['sampled_cloud_size'],\n kwargs['usage_mode'])\n cloud_fname = os.path.join(kwargs['path2save'], clouds_fname)\n if not os.path.exists(cloud_fname):\n clouds_file = h5.File(cloud_fname, 'w')\n sampled_clouds = clouds_file.create_dataset(\n 'sampled_clouds',\n shape=(kwargs['N_samples'] * len_dataset, 3,\n kwargs['cloud_size']),dtype=np.float32)\n gt_clouds = clouds_file.create_dataset(\n 'gt_clouds',\n shape=(kwargs['N_samples'] * len_dataset, 3,\n kwargs['cloud_size']),dtype=np.float32)\n gt_images = clouds_file.create_dataset(\n 'images',\n shape=(kwargs['N_samples'] * len_dataset, 4, 224, 224), dtype=np.uint8)\n else:\n clouds_file = h5.File(cloud_fname, 'a')\n sampled_clouds = clouds_file['sampled_clouds']\n gt_clouds = clouds_file['gt_clouds']\n gt_images = clouds_file['images']\n\n gen = torch.zeros((kwargs['batch_size'], 3,\n kwargs['cloud_size']))\n\n gen[:, :, :gen_cloud.size(2)] = gen_cloud\n sampled_clouds[kwargs['batch_size'] * batch_i:kwargs['batch_size'] * batch_i + gen.shape[0]] = gen\n\n gt_clouds[kwargs['batch_size'] * batch_i:kwargs['batch_size'] * batch_i + gt_cloud.shape[0]] = gt_cloud\n\n gt_images[kwargs['batch_size'] * batch_i: kwargs['batch_size'] * batch_i + image.shape[0]] = image\n clouds_file.close()\n\n\n\ndef train_test(iterator, model, loss_func, optimizer, scheduler, epoch, iter, **config):\n num_workers = config.get('num_workers')\n model_name = config.get('model_name')\n train_mode = config.get('usage_mode')\n\n batch_time = AverageMeter()\n data_time = AverageMeter()\n\n\n torch.set_grad_enabled(True)\n\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n end = time()\n model.train()\n for i, data in enumerate(iterator):\n if iter + i >= len(iterator):\n break\n data_time.update(time() - end)\n scheduler(optimizer, epoch, iter + i)\n\n input = data[0].to(device)\n seg = data[1].to(device)\n image = data[2].to(device)\n num_seg_classes = data[3][0].to(device)\n\n segs_batches = []\n segs_images = []\n for n in range(1, num_seg_classes + 1):\n new_image = []\n new_batch = []\n min = 2500\n for t in range(len(input)): # for each batch, create a new batch\n new_seg = []\n k = 0\n for j in range(len(seg[t])):\n if seg[t][j] == n:\n new_seg.append(input[t][j])\n k += 1\n min = k if k <= min and k > 0 else min\n if k:\n new_seg = torch.cat(new_seg).reshape(-1, 3).unsqueeze(0)\n new_seg = torch.transpose(new_seg, 1, 2)\n new_batch.append(new_seg)\n cur_image = image[t].unsqueeze(0)\n new_image.append(cur_image) #get the corresponding image of each part\n\n if new_batch:\n for t in range(len(new_batch)):\n new_batch[t] = new_batch[t][:, :, :min] # then a new batch comes, with only a seg, with the same size\n\n new_batch = torch.cat(new_batch, dim=0) # 对每一个batch,都加上他的seg: N * 3 * min_seg_num\n new_image = torch.cat(new_image, dim=0)\n if len(new_batch) > 1:\n segs_batches.append(new_batch) #get a list, with num_seg_classes tensor, each has a N * 3 * min_seg_num point cloud\n segs_images.append(new_image) # get a list, with num_seg_classes tensor, each has a N * 3 * size * size image\n\n\n if not segs_batches:\n continue\n\n seg_labels = []\n loss_for_one_epoch = model(segs_batches, segs_images, seg_labels, train_mode, optimizer, loss_func)\n\n with torch.no_grad():\n if torch.isnan(loss_for_one_epoch):\n print('Loss is NaN! Stopping without updating the net...')\n exit()\n\n batch_time.update(time() - end)\n\n end = time()\n\n print('[epoch %d] [%d / %d]: loss %f' % (epoch, i, len(iterator), loss_for_one_epoch))\n\n\n if (iter + i + 1) % (100 * num_workers) == 0:\n save_model({\n 'epoch': epoch,\n 'iter': iter + i + 1,\n 'model_state': model.state_dict(),\n 'optimizer_state': optimizer.state_dict()\n }, model_name)\n\n save_model({\n 'epoch': epoch + 1,\n 'iter': 0,\n 'model_state': model.state_dict(),\n 'optimizer_state': optimizer.state_dict()\n }, model_name)\n\ndef evaluate_test(iterator, model, optimizer, loss_func, **kwargs):\n train_mode = kwargs.get('train_mode')\n saving_mode = kwargs.get('saving_mode')\n model.eval()\n torch.set_grad_enabled(False)\n #vis = visdom.Visdom()\n\n for i, data in enumerate(iterator):\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n input = data[0].to(device)\n seg = data[1].to(device)\n image = data[2].to(device)\n num_seg_classes = data[3][0].to(device)\n\n\n\n segs_batches = []\n seg_labels = []\n\n #reconsturuct each image at a time\n # first get all the labels appear in one image\n segs_images = []\n seg_labels = []\n for n in range(1, num_seg_classes + 1):\n num = 0\n for j in range(seg[0]):\n if seg[0][j] == n:\n num += 1\n if num:\n segs_images.append(image)\n new_batch = torch.zeros((len(input), 3, num))\n segs_batches.append(new_batch)\n seg_labels.append(n)\n\n with torch.no_grad():\n full_obj, loss = model(segs_batches, image, seg_labels, train_mode, optimizer, loss_func)\n if torch.isnan(loss):\n print('Loss is NaN! Stopping without updating the net...')\n exit()\n\n if saving_mode:\n input = torch.transpose(input, 1, 2)\n save_point_clouds(i, input, full_obj, image, len(iterator), **kwargs)\n print(\"full_obj: \", full_obj.size())\n print(\"evaluate: [%d / %d]: loss: %f\" % (i, len(iterator), loss))\n","sub_path":"training_with_segs.py","file_name":"training_with_segs.py","file_ext":"py","file_size_in_byte":7587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"478830190","text":"import torch\nfrom torch.utils.data import Dataset\nfrom torchvision import utils\nfrom matplotlib import pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport scipy.misc\nimport os\n\nnum_class = 2\nroot_dir = './Tactile/'\ntrain_file = os.path.join(root_dir, 'train.csv')\nval_file = os.path.join(root_dir, 'val.csv')\nmeans = np.array([103.939, 116.779, 123.68]) / 255.\n\n\nclass TactileDataset(Dataset):\n\n def __init__(self, csv_file, phase, n_class=num_class, crop=False, flip_rate=0):\n self.data = pd.read_csv(csv_file)\n self.means = means\n self.n_class = n_class\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, idx):\n img_name = self.data.iloc[idx, 0]\n img = scipy.misc.imread(img_name, mode='RGB')\n\n label_name = self.data.iloc[idx, 1]\n label = np.load(label_name)\n # convert to tensor\n img = torch.from_numpy(img.copy()).float()\n img = img.transpose(0, 2)\n img = img.transpose(1, 2)\n label = torch.from_numpy(label.copy()).long()\n\n # create one-hot encoding\n h, w = label.size()\n target = torch.zeros(self.n_class, h, w)\n for c in range(self.n_class):\n target[c][label == c] = 1\n\n sample = {'X': img, 'Y': target, 'l': label}\n\n return sample\n\n\ndef show_batch(batch):\n img_batch = batch['X']\n img_batch[:,0,...].add_(means[0])\n img_batch[:,1,...].add_(means[1])\n img_batch[:,2,...].add_(means[2])\n batch_size = len(img_batch)\n\n grid = utils.make_grid(img_batch)\n plt.imshow(grid.numpy()[::-1].transpose((1, 2, 0)))\n\n plt.title('Batch from dataloader')\n\n\ndef imshow(img):\n img = img / 2\n npimg = img.numpy()\n plt.imshow(np.transpose(npimg, (1, 2, 0)))\n\n\nif __name__ == '__main__':\n train_data = TactileDataset(csv_file=train_file, phase='train')\n print(train_data.__len__())\n data_loader = torch.utils.data.DataLoader(train_data, batch_size=4, shuffle=True, num_workers=1)\n\n batch_size = 4\n for i in range(batch_size):\n sample = train_data[i]\n print(i, sample['X'].size(), sample['Y'].size())\n\n for i, batch in enumerate(data_loader):\n print(i, batch['X'].size(), batch['Y'].size())\n","sub_path":"utils/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":2229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"386515031","text":"# -*- encoding: utf-8 -*-\n# Copyright (C) 2017 TSDV TTEC. All rights reserved.\n\"\"\"\nThis module is used to draw position of elements over input image.\nThe purpose is for easy debugging PHOcrOffice module\n\"\"\"\nimport os\nfrom PIL import Image, ImageDraw, ImageFont\nfrom .base_element import BaseElement\n\n# Define some constant tag of PHOcr office\nOCR_PAGE = \"ocr_page\"\nOCR_TABLE = \"ocr_table_mask\"\nOCR_CAREA = \"ocr_carea\"\nOCR_ROW = \"ocr_row\"\n\nclass ElementDraw(object):\n \"\"\"\n Draw box of elements over image\n \"\"\"\n blank_layer = \"blank_layer.png\"\n output_file = \"element_draw.png\"\n def __init__(self, img_width, img_height, source_image=None):\n \"\"\"Init\"\"\"\n self._width = img_width\n self._height = img_height\n source_img = \"\"\n if source_image is None:\n # Create a blank layer with A4 size\n img = Image.new('RGB', (self._width, self._height), color='white')\n img.save(ElementDraw.blank_layer)\n source_img = ElementDraw.blank_layer\n else:\n source_img = source_image\n self._source_img = Image.open(source_img)\n self._draw = ImageDraw.Draw(self._source_img)\n self._font = ImageFont.load_default()\n\n def __del__(self):\n \"\"\"Destructor\"\"\"\n if os.path.exists(ElementDraw.blank_layer):\n os.remove(ElementDraw.blank_layer)\n\n def write(self, tree_element):\n \"\"\"\n Save the box of element\n The main api to outside\n :return:\n \"\"\"\n self.write_down_element(tree_element)\n self._source_img.save(self.output_file, \"PNG\")\n\n def _draw_text_box(self, textbox_element):\n \"\"\"\n Draw boxes related with text attributes element\n :return:\n \"\"\"\n textbox = BaseElement(textbox_element)\n self._draw_element(textbox)\n\n def _draw_table(self, table_element):\n \"\"\"\n Draw boxes related with table element\n :return:\n \"\"\"\n table = BaseElement(table_element)\n # Draw table box first\n self._draw_element(table)\n\n # Draw rows\n for row_element in table_element:\n row = BaseElement(row_element)\n self._draw_element(row)\n for col_element in row_element:\n col = BaseElement(col_element)\n self._draw_element(col)\n\n def _draw_element(self, base_element):\n \"\"\"Draw rectangle of element\"\"\"\n self._draw.rectangle([(base_element.box.left, base_element.box.top),\n (base_element.box.left + base_element.box.width,\n base_element.box.top + base_element.box.height)],\n outline='red', fill=None)\n\n # Write text down to photo\n text_value = base_element.tag + \" \" + base_element.m_id\n\n # Write table name to upper middle of table\n if base_element.tag == OCR_TABLE:\n self._draw.text((base_element.box.left + base_element.box.width / 2,\n base_element.box.top - 10),\n text_value, font=self._font, fill=255)\n # Write ocr row to lower of row\n elif base_element.tag == OCR_ROW:\n self._draw.text((base_element.box.left,\n base_element.box.top + 5),\n text_value, font=self._font, fill=255)\n # Write col and other to middle\n else:\n self._draw.text((base_element.box.left,\n base_element.box.top + base_element.box.height / 2),\n text_value, font=self._font, fill=255)\n\n def write_down_element(self, tree_element):\n \"\"\"\n Write down the image for input element\n Can use outside\n \"\"\"\n element = BaseElement(tree_element)\n input_tag = element.tag\n if input_tag == OCR_TABLE:\n self._draw_table(tree_element)\n if input_tag == OCR_CAREA:\n self._draw_text_box(tree_element)\n if input_tag == OCR_PAGE:\n for member in tree_element:\n self.write_down_element(member)\n","sub_path":"Run_PHocr_test/PHOcr_C2404_D3_linux_release/lib/phocroffice/phocr_shared/element_draw.py","file_name":"element_draw.py","file_ext":"py","file_size_in_byte":4129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"208290487","text":"from ipaddress import ip_network, ip_address\nimport csv\nimport time\nimport random\n\nlistOfPrivateIp = []\nfor k in ip_network(\"10.0.0.0/16\"):\n listOfPrivateIp.append(str(k))\n#print(len(listOfPrivateIp))\nlistOfPrivateIp_src = random.sample(listOfPrivateIp, 3500)\nlistOfPrivateIp = list(set(listOfPrivateIp)-set(listOfPrivateIp_src))\nlistOfPrivateIp_dst = random.sample(listOfPrivateIp,1500)\n# listOfPrivateIp_src = listOfPrivateIp[:3500]\n# listOfPrivateIp_dst = listOfPrivateIp[3501:5000]\n\nlistOfPublicIp = []\nfor k in ip_network(\"14.141.56.0/21\"):\n listOfPublicIp.append(str(k))\n#print(len(listOfPublicIp))\nlistOfPublicIp_src = random.sample(listOfPublicIp, 1500)\nlistOfPublicIp = list(set(listOfPublicIp)-set(listOfPublicIp_src))\nlistOfPublicIp_dst = random.sample(listOfPublicIp, 500)\nsrc_ip = listOfPrivateIp_src + listOfPublicIp_src\ndst_ip = listOfPrivateIp_dst + listOfPublicIp_dst\ninfo = 'src_dst_ip_info.csv'\nwith open(info,'a') as infofile:\n writer = csv.writer(infofile)\n writer.writerows([[src_ip],[dst_ip]])\n\n#print(len(src_ip))\n#print(len(dst_ip))\n\nports_name_protocol = [(80, 'http', 'TCP'), (443, 'https', 'TCP'), (123, 'ntp', 'UDP'), (22, 'ssh', 'TCP'),\n (53, 'dns', 'UDP'), (445, 'microsoft-ds', 'TCP'), (389, 'ldap', 'UDP'), (514, 'syslog', 'TCP'),\n (137, 'netbios-ns', 'TCP'), (902, 'ideafarm-door', 'TCP'), (23, 'telnet', 'TCP'), (2049,'nfs','TCP'),\n (88,'kerberos','TCP'), (111,'sunrpc', 'TCP'), (135,'epmap', 'TCP'), (1433, 'ms-sql-server', 'TCP'),\n (3306,'mysql','TCP'), (67,'bootps','UDP'), (161, 'snmp', 'UDP'), (138, 'netbios-dgm', 'UDP'), (1434, 'ms-sql-m', 'UDP'),\n (25,'smtp', 'TCP'), (21, 'ftp', 'TCP'), (179,'bgp','TCP'), (110,'pop3','TCP'), (500,'isakmp', 'UDP'),\n (465,'igmpv3lite','TCP'), (19,'chargen','UDP'), (139,'netbios-ssn', 'TCP')]\ni = 0\nj = 0\nfourTupleForPlanning = []\nstart = time.time()\nwhile (len(fourTupleForPlanning) < 30000000):\n srcip = int(ip_address(src_ip[i]))\n dstip = int(ip_address(dst_ip[j]))\n rand = random.randint(1,100)\n if rand == 1:\n portsSet = random.sample(ports_name_protocol,2)\n elif rand == 2:\n portsSet = random.sample(ports_name_protocol,3)\n elif rand == 3:\n portsSet = random.sample(ports_name_protocol,4)\n else:\n portsSet = random.sample(ports_name_protocol[:10],4)\n for set in portsSet:\n port = set[0]\n portName = set[1]\n protocol = set[2]\n fourTupleForPlanning.append([srcip, dstip, port, portName, protocol])\n if len(fourTupleForPlanning) == 30000000:\n break\n j = j+1\n if (j == 2000):\n i = i + 1\n j = 0\nfilename = 'fourTupleIntIpPlanning.csv'\nwith open (filename, 'a') as file:\n writer = csv.writer(file)\n writer.writerows(fourTupleForPlanning)\nend = time.time()\ntook = round(end-start,2)\nprint(f'inserted into {filename} 30million entries took {took} seconds')\n","sub_path":"fourtupleintip.py","file_name":"fourtupleintip.py","file_ext":"py","file_size_in_byte":3000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"348747971","text":"from graph import Graph\nfrom indexed_priority_queue import PriorityQueue\n\nclass LazyPrim:\n def __init__(self, g):\n self.g = g\n self._mst_vertices = {} #Vertices already in MST\n self._mst_edges = []\n self._pq = PriorityQueue()\n\n #Get vertex labeled '0': this is our starting point\n list_of_v = g.vertices_with_labels()\n s = list_of_v['0']\n\n self._visit(s)\n\n while len(self._pq) > 0:\n (wt, (u, e)) = self._pq.remove_min()\n v = e.other(u)\n if v not in self._mst_vertices:\n self._mst_edges.append(e)\n self._visit(v)\n\n def _visit(self, v):\n \"\"\"Visit a vertex:\n - Include the vertex in MST\n - For each edge from vertex s to the PQ, iff the edge is not already part of the MST\n \"\"\"\n self._mst_vertices[v] = True\n for e in self.g.incident_edges(v):\n if e.other(v) not in self._mst_vertices:\n self._pq.add(float(e.element()), (v, e))\n\n def edges(self):\n return self._mst_edges\n\nif __name__ == '__main__':\n g = Graph(directed=False,file_path = \"prim_ewg.txt\")\n mst = LazyPrim(g)\n mst_edges = mst.edges()\n for e in mst_edges:\n (u, v) = e.endpoints()\n print(\"(\", u.element(), v.element(), \"): \", e.element())\n","sub_path":"graphs/lazy_prim.py","file_name":"lazy_prim.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"600764375","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 20 16:15:16 2018\n\n@author: yangyr\n\"\"\"\n\nimport tensorflow as tf\nimport tensorlayer as tl\nimport numpy as np\n\ndef u_net(x, is_train=False, reuse=False, n_out=1):\n _, nx, ny, nz = x.shape\n nx = int(nx)\n ny = int(ny)\n nz = int(nz)\n with tf.variable_scope(\"u_net\", reuse=reuse):\n tl.layers.set_name_reuse(reuse)\n inputs = tl.layers.InputLayer(x, name='inputs')\n conv1 = tl.layers.Conv2d(inputs, 64, (3, 3), act=tf.nn.relu, name='conv1_1')\n conv1 = tl.layers.Conv2d(conv1, 64, (3, 3), act=tf.nn.relu, name='conv1_2')\n pool1 = tl.layers.MaxPool2d(conv1, (2, 2), name='pool1')\n conv2 = tl.layers.Conv2d(pool1, 128, (3, 3), act=tf.nn.relu, name='conv2_1')\n conv2 = tl.layers.Conv2d(conv2, 128, (3, 3), act=tf.nn.relu, name='conv2_2')\n pool2 = tl.layers.MaxPool2d(conv2, (2, 2), name='pool2')\n conv3 = tl.layers.Conv2d(pool2, 256, (3, 3), act=tf.nn.relu, name='conv3_1')\n conv3 = tl.layers.Conv2d(conv3, 256, (3, 3), act=tf.nn.relu, name='conv3_2')\n pool3 = tl.layers.MaxPool2d(conv3, (2, 2), name='pool3')\n conv4 = tl.layers.Conv2d(pool3, 512, (3, 3), act=tf.nn.relu, name='conv4_1')\n conv4 = tl.layers.Conv2d(conv4, 512, (3, 3), act=tf.nn.relu, name='conv4_2')\n pool4 = tl.layers.MaxPool2d(conv4, (2, 2), name='pool4')\n conv5 = tl.layers.Conv2d(pool4, 1024, (3, 3), act=tf.nn.relu, name='conv5_1')\n conv5 = tl.layers.Conv2d(conv5, 1024, (3, 3), act=tf.nn.relu, name='conv5_2')\n\n up4 = tl.layers.DeConv2d(conv5, 512, (3, 3), (nx/8, ny/8), (2, 2), name='deconv4')\n up4 = tl.layers.ConcatLayer([up4, conv4], 3, name='concat4')\n conv4 = tl.layers.Conv2d(up4, 512, (3, 3), act=tf.nn.relu, name='uconv4_1')\n conv4 = tl.layers.Conv2d(conv4, 512, (3, 3), act=tf.nn.relu, name='uconv4_2')\n up3 = tl.layers.DeConv2d(conv4, 256, (3, 3), (nx/4, ny/4), (2, 2), name='deconv3')\n up3 = tl.layers.ConcatLayer([up3, conv3], 3, name='concat3')\n conv3 = tl.layers.Conv2d(up3, 256, (3, 3), act=tf.nn.relu, name='uconv3_1')\n conv3 = tl.layers.Conv2d(conv3, 256, (3, 3), act=tf.nn.relu, name='uconv3_2')\n up2 = tl.layers.DeConv2d(conv3, 128, (3, 3), (nx/2, ny/2), (2, 2), name='deconv2')\n up2 = tl.layers.ConcatLayer([up2, conv2], 3, name='concat2')\n conv2 = tl.layers.Conv2d(up2, 128, (3, 3), act=tf.nn.relu, name='uconv2_1')\n conv2 = tl.layers.Conv2d(conv2, 128, (3, 3), act=tf.nn.relu, name='uconv2_2')\n up1 = tl.layers.DeConv2d(conv2, 64, (3, 3), (nx/1, ny/1), (2, 2), name='deconv1')\n up1 = tl.layers.ConcatLayer([up1, conv1] , 3, name='concat1')\n conv1 = tl.layers.Conv2d(up1, 64, (3, 3), act=tf.nn.relu, name='uconv1_1')\n conv1 = tl.layers.Conv2d(conv1, 64, (3, 3), act=tf.nn.relu, name='uconv1_2')\n conv1 = tl.layers.Conv2d(conv1, n_out, (1, 1), act=tf.nn.sigmoid, name='uconv1')\n return conv1","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"155342412","text":"import random\nimport play_sound\nimport os\nfrom colorama import Fore, Back, Style , init\n\ndef create_cube():\n number_on = False\n #number_on = True\n #\n # 5 top\n # 0 1 2 3 left front right back\n # 4 bottom\n #\n cube = []\n for loop in range(6):\n side = []\n number = 0\n for loop2 in range(3):\n temp = []\n for loop3 in range(3):\n if number_on:\n temp += [str(loop)+str(number)]\n else:\n temp += [loop]\n number +=1\n side += [temp]\n cube += [side]\n return cube\n\ndef string_to_colour(string):\n new_string = \"\"\n\n for loop in range(len(string)):\n if string[loop] == \"0\":\n new_string += Back.RED\n elif string[loop] == \"1\":\n new_string += Back.WHITE\n new_string += Fore.BLACK\n elif string[loop] == \"2\":\n new_string += Back.MAGENTA\n elif string[loop] == \"3\":\n new_string += Back.YELLOW\n new_string += Fore.BLACK\n elif string[loop] == \"4\":\n new_string += Back.BLUE\n elif string[loop] == \"4\":\n new_string += Back.GREEN\n\n\n\n new_string += string[loop]\n new_string += Style.RESET_ALL\n \n\n return new_string\n\ndef print_cube(cube):\n lenght = len(str(cube[0][0]))\n print(\"\")\n print(string_to_colour(\" \"*lenght + str(cube[5][0])))\n print(string_to_colour(\" \"*lenght + str(cube[5][1])))\n print(string_to_colour(\" \"*lenght + str(cube[5][2])))\n \n print(string_to_colour(str(cube[0][0])+str(cube[1][0])+str(cube[2][0])+str(cube[3][0])))\n print(string_to_colour(str(cube[0][1])+str(cube[1][1])+str(cube[2][1])+str(cube[3][1])))\n print(string_to_colour(str(cube[0][2])+str(cube[1][2])+str(cube[2][2])+str(cube[3][2])))\n \n print(string_to_colour(\" \"*lenght + str(cube[4][0])))\n print(string_to_colour(\" \"*lenght + str(cube[4][1])))\n print(string_to_colour(\" \"*lenght + str(cube[4][2])))\n print(\"\")\n print(Style.RESET_ALL)\n return\n\ndef turn_face(cube,times=1):\n new_cube = create_cube()\n\n new_cube[3] = copy_plane(cube[3])\n\n new_cube[0] = copy_plane(cube[0])\n new_cube[0][0][2] = cube[4][0][0]\n new_cube[0][1][2] = cube[4][0][1]\n new_cube[0][2][2] = cube[4][0][2]\n\n new_cube[5] = copy_plane(cube[5])\n new_cube[5][2][0] = cube[0][0][2]\n new_cube[5][2][1] = cube[0][1][2]\n new_cube[5][2][2] = cube[0][2][2]\n\n new_cube[2] = copy_plane(cube[2])\n new_cube[2][0][0] = cube[5][2][0]\n new_cube[2][1][0] = cube[5][2][1]\n new_cube[2][2][0] = cube[5][2][2]\n\n new_cube[4] = copy_plane(cube[4])\n new_cube[4][0][0] = cube[2][0][0]\n new_cube[4][0][1] = cube[2][1][0]\n new_cube[4][0][2] = cube[2][2][0]\n\n\n new_cube[1] = turn_plane_no_side(cube[1])\n \n if times > 1:\n new_cube = turn_face(new_cube,times=times-1)\n\n return new_cube\n\ndef copy_plane(plane):\n new_plane = [[0,0,0],[0,0,0],[0,0,0]]\n for loop in range(3):\n for loop2 in range(3):\n new_plane[loop][loop2] = plane[loop][loop2]\n return new_plane\n\ndef turn_plane_no_side(plane):\n new_plane = [[0,0,0],[0,0,0],[0,0,0]]\n #middle\n new_plane[1][1] = plane[1][1]\n \n #corners\n new_plane[0][0] = plane[2][0]\n new_plane[2][0] = plane[2][2]\n new_plane[0][2] = plane[0][0]\n new_plane[2][2] = plane[0][2]\n \n #edges\n new_plane[0][1] = plane[1][0]\n new_plane[2][1] = plane[1][2]\n new_plane[1][2] = plane[0][1]\n new_plane[1][0] = plane[2][1]\n return new_plane\n\ndef turn_cube_horizontal(cube):\n new_cube = create_cube()\n new_cube[0] = cube[3]\n new_cube[1] = cube[0]\n new_cube[2] = cube[1]\n new_cube[3] = cube[2]\n\n new_cube[4] = turn_plane_no_side(cube[4])\n\n\n cube[5] = turn_plane_no_side(cube[5])\n cube[5] = turn_plane_no_side(cube[5])\n new_cube[5] = turn_plane_no_side(cube[5])\n return new_cube\n\ndef turn_cube_vertical(cube):\n new_cube = create_cube()\n new_cube[1] = cube[4]\n new_cube[5] = cube[1]\n\n new_cube[4] = copy_plane(cube[3])\n new_cube[4][0] = cube[3][2]\n new_cube[4][2] = cube[3][0]\n\n new_cube[3] = copy_plane(cube[5])\n new_cube[3][0] = cube[5][2]\n new_cube[3][2] = cube[5][0]\n new_cube[3][1] = cube[5][1]\n \n cube[0] = turn_plane_no_side(cube[0])\n cube[0] = turn_plane_no_side(cube[0])\n new_cube[0] = turn_plane_no_side(cube[0])\n\n new_cube[2] = turn_plane_no_side(cube[2])\n return new_cube\n\ndef turn_cal(cube,face=1,times=1):\n \n times = times%4\n if times == 0:\n return cube\n\n if face == 0:\n cube = turn_cube_horizontal(cube)\n cube = turn_face(cube,times=times)\n cube = turn_cube_horizontal(cube)\n cube = turn_cube_horizontal(cube)\n cube = turn_cube_horizontal(cube)\n elif face == 1:\n cube = turn_face(cube,times=times)\n elif face == 2:\n cube = turn_cube_horizontal(cube)\n cube = turn_cube_horizontal(cube)\n cube = turn_cube_horizontal(cube)\n cube = turn_face(cube,times=times)\n cube = turn_cube_horizontal(cube)\n elif face == 3:\n cube = turn_cube_horizontal(cube)\n cube = turn_cube_horizontal(cube)\n cube = turn_face(cube,times=times)\n cube = turn_cube_horizontal(cube)\n cube = turn_cube_horizontal(cube)\n elif face == 4:\n cube = turn_cube_vertical(cube)\n cube = turn_face(cube,times=times)\n cube = turn_cube_vertical(cube)\n cube = turn_cube_vertical(cube)\n cube = turn_cube_vertical(cube)\n elif face == 5:\n cube = turn_cube_vertical(cube)\n cube = turn_cube_vertical(cube)\n cube = turn_cube_vertical(cube)\n cube = turn_face(cube,times=times)\n cube = turn_cube_vertical(cube)\n\n return cube\n\ndef fittness_cal(cube):\n completed = create_cube()\n fittness = 0\n\n for loop in range(6):\n for loop2 in range(3):\n for loop3 in range(3):\n if cube[loop][loop2][loop3] == completed[loop][loop2][loop3]:\n fittness += 1\n return fittness/(6*3*3)*100\n\ndef random_play(cube,turns):\n for loop in range(turns):\n face = random.randint(0,5)\n times = random.randint(1,3)\n cube = turn_cal(cube,face=face,times=times)\n print(str(face) + \" \" + str(times))\n return cube\n\n\n\n\ninit()\ncube = create_cube()\nplay_sound.sound_setup(\"sounds\\\\your amazing.ogg\")\nprint_cube(cube)\n\nwhile True:\n \n turns = int(input(\"turns to random: \"))\n os.system(\"cls\")\n if turns > 0:\n cube = random_play(cube,turns)\n print_cube(cube)\n fittness = fittness_cal(cube)\n print(fittness)\n \n while True:\n face = int(input(\"face number: \"))\n if face > 5 or face < 0:\n print(\"error bad input for face number!\")\n continue\n times = int(input(\"times: \"))\n \n cube = turn_cal(cube,face=face,times=times)\n \n \n \n print_cube(cube)\n fittness = fittness_cal(cube)\n print(fittness)\n\n if fittness == 100:\n play_sound.play_sound()\n break\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"545225797","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\nimport tensorflow as tf\nfrom collections import deque\nfrom random import randint\nimport os\nimport dqn\nimport random\nimport itertools\nfrom os import path\n\ndf = pd.read_csv('AMZN.csv')\n\ndf2 = df.iloc[[0, -1]]\n\ntotal_rows = df2.index.values[1]\n\nstart = pd.to_numeric(df2['Adj Close']).values.item(0)\nend = pd.to_numeric(df2['Adj Close']).values.item(1)\n\ndef get_velocity(start, end, span) :\n return (end - start) / span\n\ndef get_v(data, span) :\n i = 0\n v = np.zeros(span).tolist()\n\n while i < len(data) - span :\n range = data[i:i+span]\n v.append(get_velocity(range.item(0), range.item(span - 1), span))\n i = i + 1\n\n return v\n\n# velocity = get_velocity(start, end, total_rows)\n\n# 0.0311424636872 => 3 cents a day\n# print velocity\n# print '---'\n\nv5 = get_v(pd.to_numeric(df['Adj Close']).values, 5)\na5 = get_v(np.asarray(v5), 5)\n\ndfV5 = pd.DataFrame(v5)\ndfA5 = pd.DataFrame(a5)\n\nv20 = get_v(pd.to_numeric(df['Adj Close']).values, 20)\na20 = get_v(np.asarray(v20), 20)\n\ndfV20 = pd.DataFrame(v20)\ndfA20 = pd.DataFrame(a20)\n\nma5 = df['Adj Close'].rolling(window=5).mean()\nma20 = df['Adj Close'].rolling(window=20).mean()\n\nema12 = df['Adj Close'].ewm(span=12).mean()\nema26 = df['Adj Close'].ewm(span=26).mean()\nmacd = ema12 - ema26\nsignal = macd.ewm(span=9).mean()\noscillator = macd - signal\n\ndata = pd.concat([df.loc[:, ['Date', 'Adj Close']], ma5, ma20, dfA5, dfA20, macd, signal, oscillator], axis=1)\ndata.columns = ['Date', 'Adj Close', '5MA', '20MA', '5A', '20A', 'MACD', 'SIGNAL', 'OSCILLATOR']\n# print pd.concat([df.loc[:, ['Date', 'Adj Close']], dfA5, dfA20], axis=1)\n\n# print data.tail(360)\n\nnp_data = data.loc[data.shape[0] - 360: data.shape[0] - 356, 'Adj Close':].as_matrix()\n\n# print np_data[4, 0]\n\n# print Decimal(3 * (-19 * -5) / 100.0).quantize(Decimal('.1'), rounding=ROUND_FLOOR)\n# print Decimal(3 * (-19 * -5) / 100.0).quantize(Decimal('.1'), rounding=ROUND_DOWN)\n# print '{0}% {1} - {2}'.format((-19 * -5), round(3 * (-19 * -5) / 100.0, 2), round(round(3 * (-19 * -5) / 100.0, 0)))\n# print '{0}% {1} - {2}'.format((-18 * -5), round(3 * (-18 * -5) / 100.0, 2), round(round(3 * (-18 * -5) / 100.0, 0)))\n# print '{0}% {1} - {2}'.format((-17 * -5), round(3 * (-17 * -5) / 100.0, 2), round(round(3 * (-17 * -5) / 100.0, 0)))\n# print '{0}% {1} - {2}'.format((-16 * -5), round(3 * (-16 * -5) / 100.0, 2), round(round(3 * (-16 * -5) / 100.0, 0)))\n# print '{0}% {1} - {2}'.format((-15 * -5), round(3 * (-15 * -5) / 100.0, 2), round(round(3 * (-15 * -5) / 100.0, 0)))\n# print '{0}% {1} - {2}'.format((-14 * -5), round(3 * (-14 * -5) / 100.0, 2), round(round(3 * (-14 * -5) / 100.0, 0)))\n# print '{0}% {1} - {2}'.format((-11 * -5), round(3 * (-11 * -5) / 100.0, 2), round(round(3 * (-11 * -5) / 100.0, 0)))\n# print '{0}% {1} - {2}'.format((-10 * -5), round(3 * (-10 * -5) / 100.0, 2), round(round(3 * (-10 * -5) / 100.0, 0)))\n# print '{0}% {1} - {2}'.format((-9 * -5), round(3 * (-9 * -5) / 100.0, 2), round(round(3 * (-9 * -5) / 100.0, 0)))\n# print '{0}% {1} - {2}'.format((-8 * -5), round(3 * (-8 * -5) / 100.0, 2), round(round(3 * (-8 * -5) / 100.0, 0)))\n# print '{0}% {1} - {2}'.format((-7 * -5), round(3 * (-7 * -5) / 100.0, 2), round(round(3 * (-7 * -5) / 100.0, 0)))\n# print '{0}% {1} - {2}'.format((-6 * -5), round(3 * (-6 * -5) / 100.0, 2), round(round(3 * (-6 * -5) / 100.0, 0)))\n# print '{0}% {1} - {2}'.format((-5 * -5), round(3 * (-5 * -5) / 100.0, 2), round(round(3 * (-5 * -5) / 100.0, 0)))\n# print '{0}% {1} - {2}'.format((-4 * -5), round(3 * (-4 * -5) / 100.0, 2), round(round(3 * (-4 * -5) / 100.0, 0)))\n# print '{0}% {1} - {2}'.format((-3 * -5), round(3 * (-3 * -5) / 100.0, 2), round(round(3 * (-3 * -5) / 100.0, 0)))\n\n# print '{0} {1} {2} {3}'.format(np_data[4, 0], 10000 // np_data[4, 0], math.floor((10000 // np_data[4, 0]) * (1 * 5 / 100.0)), 1 * 5)\n# print '{0} {1} {2} {3}'.format(np_data[4, 0], 10000 // np_data[4, 0], math.floor((10000 // np_data[4, 0]) * (2 * 5 / 100.0)), 2 * 5)\n# print '{0} {1} {2} {3}'.format(np_data[4, 0], 10000 // np_data[4, 0], math.floor((10000 // np_data[4, 0]) * (3 * 5 / 100.0)), 3 * 5)\n# print '{0} {1} {2} {3}'.format(np_data[4, 0], 10000 // np_data[4, 0], math.floor((10000 // np_data[4, 0]) * (4 * 5 / 100.0)), 4 * 5)\n# print '{0} {1} {2} {3}'.format(np_data[4, 0], 10000 // np_data[4, 0], math.floor((10000 // np_data[4, 0]) * (5 * 5 / 100.0)), 5 * 5)\n\n\n# print(data.loc[data.shape[0] - 360: data.shape[0] - 356, 'Adj Close':].as_matrix())\n# print(data.loc[data.shape[0] - 359: data.shape[0] - 355, 'Adj Close':].as_matrix())\n#\n# print(np.ravel(data.loc[data.shape[0] - 360: data.shape[0] - 356, 'Adj Close':].as_matrix())[20])\n# print(np.ravel(data.loc[data.shape[0] - 359: data.shape[0] - 355, 'Adj Close':].as_matrix())[20])\n\n# plt.figure()\n# plt.plot(dfA5.tail(30))\n# plt.plot(dfA20.tail(30))\n# plt.grid()\n# plt.show()\n\nprop_count = 8\n# take last 20 screens as input with 8 properties each (price, 5ma, 20ma, 5a, 20a, macd, signal, oscillator)\nnum_screen = 20\ninput_size = num_screen * prop_count + 1\noutput_size = 41\nminibatch_size = 30\n\nstarting_point = 360\n\n# discount factor\ndis = 0.9\n# buffer size\nREPLAY_MEMORY = 50000\n\nmax_episodes = 2000\n# store the previous observations in replay memory\nreplay_buffer = deque()\n\nlast_100_game_reward = deque()\n\ncsv = np.zeros((max_episodes, starting_point - num_screen))\n\ndef get_copy_var_ops(dest_scope_name=\"target\", src_scope_name=\"main\"):\n\n # Copy variables src_scope to dest_scope\n op_holder = []\n\n src_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=src_scope_name)\n dest_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=dest_scope_name)\n\n for src_var, dest_var in zip(src_vars, dest_vars):\n op_holder.append(dest_var.assign(src_var.value()))\n\n return op_holder\n\ndef _slice(data, start, span=19):\n return np.ravel(data.loc[data.shape[0] - start: data.shape[0] - (start - span), 'Adj Close':].as_matrix())\n\ndef ddqn_replay_train(mainDQN, targetDQN, train_batch):\n '''\n Double DQN implementation\n :param mainDQN: main DQN\n :param targetDQN: target DQN\n :param train_batch: minibatch for train\n :return: loss\n '''\n x_stack = np.empty(0).reshape(0, mainDQN.input_size)\n y_stack = np.empty(0).reshape(0, mainDQN.output_size)\n\n # Get stored information from the buffer\n for state, action, reward, next_state, done in train_batch:\n Q = mainDQN.predict(state)\n\n # terminal?\n if done:\n Q[0, action] = reward\n else:\n # Double DQN: y = r + gamma * targetDQN(s')[a] where\n # a = argmax(mainDQN(s'))\n Q[0, action] = reward + dis * \\\n targetDQN.predict(next_state)[\n 0, np.argmax(mainDQN.predict(next_state))]\n\n y_stack = np.vstack([y_stack, Q])\n x_stack = np.vstack([x_stack, state])\n\n # Train our network using target and predicted Q values on each episode\n return mainDQN.update(x_stack, y_stack)\n\nwith tf.Session() as sess:\n mainDQN = dqn.DQN(sess, input_size, output_size, name=\"main\")\n targetDQN = dqn.DQN(sess, input_size, output_size, name=\"target\")\n tf.global_variables_initializer().run()\n\n # writer = tf.summary.FileWriter(path.abspath(path.join(os.sep, '/Users/seanlee', 'logdir')), sess.graph)\n\n copy_ops = get_copy_var_ops(dest_scope_name=\"target\", src_scope_name=\"main\")\n sess.run(copy_ops)\n\n # e = 0.1\n\n for episode in range(max_episodes):\n e = 1. / ((episode / 10) + 1)\n # print(\"E: {}\".format(e))\n done = False\n step_count = 1\n cash = 10000\n holdings = 0\n state = np.append(_slice(data, starting_point), 0)\n next_state = []\n rewards = []\n\n while not done:\n # del rewards[:]\n if np.random.rand(1) < e:\n # Explore\n # Random action between -20 and 20\n action = randint(-20, 20)\n # action = env.action_space.sample()\n else:\n # Exploit\n # Choose an action greedily from the Q-network\n action = np.argmax(mainDQN.predict(state)) - 20\n\n # Get new state and reward from environment\n # next_state, reward, done, _ = _step(action, step_count)\n next_state = _slice(data, starting_point - step_count)\n price = next_state[prop_count * num_screen - prop_count]\n\n if (action < 0 and holdings < 1) or action == 0:\n # cannot sell while no shares are held. thus do nothing\n reward = cash + (price * holdings)\n # print(\"{} \\t{}% \\tCash: {} \\tHoldings: {} \\tReward: {} \\tsteps: {}\".format(0, action*5, cash, holdings, reward, step_count))\n elif action < 0 and holdings > 0:\n qty = round(round(holdings * (action * -5) / 100.0, 0))\n holdings = holdings - qty\n cash = cash + (price * qty)\n reward = cash + (price * holdings)\n # print(\"{} \\t{}% \\tCash: {} \\tHoldings: {} \\tReward: {} \\tsteps: {}\".format(int(round(qty)), action*5, cash, holdings, reward, step_count))\n elif action > 0:\n qty = math.floor((cash // price) * (action * 5 / 100.0))\n holdings = holdings + qty\n cash = cash - (price * qty)\n reward = cash + (price * holdings)\n # print(\"{} \\t{}% \\tCash: {} \\tHoldings: {} \\tReward: {} \\tsteps: {}\".format(int(round(qty)), action*5, cash, holdings, reward, step_count))\n\n next_state = np.append(next_state, reward)\n\n if starting_point - step_count <= num_screen:\n done = True\n else:\n done = False\n\n csv[episode][step_count - 1] = reward\n # Save the experience to our buffer\n replay_buffer.append((state, action, reward, next_state, done))\n if len(replay_buffer) > REPLAY_MEMORY:\n replay_buffer.popleft()\n\n state = next_state\n step_count += 1\n\n # if e > 0.0001:\n # e -= (0.1 - 0.0001) / max_episodes\n\n # print(\"Episode: {} steps: {}\".format(episode, step_count))\n\n if episode % 10 == 1: # train every 10 episode\n # Get a random batch of experiences.\n for _ in range(50):\n minibatch_start = randint(0, len(replay_buffer) - minibatch_size)\n minibatch = list(itertools.islice(replay_buffer, minibatch_start, minibatch_start + minibatch_size))\n # minibatch = random.sample(replay_buffer, 25)\n loss, _ = ddqn_replay_train(mainDQN, targetDQN, minibatch)\n\n # copy q_net -> target_net\n sess.run(copy_ops)\n\n # print(\"Cash: {} Holdings: {} Price: {}\".format(cash, holdings, next_state[20]))\n # last_100_game_reward.append(cash + (holdings * next_state[20]))\n #\n # if len(last_100_game_reward) > 100:\n # last_100_game_reward.popleft()\n #\n # avg_reward = np.mean(last_100_game_reward)\n #\n # if avg_reward > 199:\n # print(\"Game Cleared in {:f} episodes with avg reward {:f}\".format(episode, avg_reward))\n # break\n\n # pd.DataFrame(csv).to_csv('333.csv')\n\n # Predict on new state\n # print mainDQN.predict()\n\n plt.figure()\n plt.plot(csv[:, -1])\n plt.grid()\n plt.show()","sub_path":"examples/agents/amzn.py","file_name":"amzn.py","file_ext":"py","file_size_in_byte":11539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"245903798","text":"from functools import partial\nimport numpy\nimport h5py\nfrom lazyflow.request import Request\nfrom lazyflow.graph import Operator, InputSlot, OutputSlot, OperatorWrapper\nfrom lazyflow.operators import OpCompressedCache, OpVigraLabelVolume, OpFilterLabels, OpSelectLabel, OpMaskedSelect, OpDtypeView\nfrom lazyflow.operators.ioOperators import OpH5WriterBigDataset\nfrom lazyflow.operators.opReorderAxes import OpReorderAxes\n\nfrom lazyflow.utility import PathComponents\nfrom ilastik.utility import bind\nfrom ilastik.applets.splitBodyPostprocessing.opSplitBodyPostprocessing import OpAccumulateFragmentSegmentations, OpMaskedWatershed\n\nimport logging\nlogger = logging.getLogger(__name__)\n\nclass OpSplitBodySupervoxelExport(Operator):\n\n DatasetInfos = InputSlot(level=1) # Used to extract the other datasets from the segmentation file.\n WorkingDirectory = InputSlot()\n \n RawData = InputSlot() # (Display only)\n InputData = InputSlot() # The membrane probabilities\n RavelerLabels = InputSlot()\n Supervoxels = InputSlot()\n AnnotationBodyIds = InputSlot() # The list of bodies actually edited\n # (Must be connected to ensure that setupOutputs will be \n # called resize the multi-slots when necessary)\n\n # For these multislots, N = number of raveler bodies that were edited\n EditedRavelerBodies = OutputSlot(level=1)\n MaskedSupervoxels = OutputSlot(level=1)\n RelabeledSupervoxels = OutputSlot(level=1)\n FilteredMaskedSupervoxels = OutputSlot(level=1)\n HoleFilledSupervoxels = OutputSlot(level=1)\n \n FinalSupervoxels = OutputSlot()\n SupervoxelMapping = OutputSlot()\n\n # RavelerLabels ------>------------------------------------------------------------------------------------------------------------------------------------------------>------------------------------------------------------------------------------------------------------------------------------------\n # \\ \\ \\\n # \\ Supervoxels -- MaskedSupervoxels \\ \\\n # \\ \\ / \\ \\\n # AnnotationBodyIds ----> opSelectLabel[n] --> opMaskedSelect[n] --> opRelabelMaskedSupervoxels[n] --> opRelabeledMaskedSupervoxelsCaches[n] --> opSmallLabelFilter[n] --> opMaskedWatershed[n] --> opMaskedWatershedCaches[n] --> opRelabelMergedSupervoxels[n] --> opRelabeledMergedSupervoxelsCaches[n] --> opAccumulateFinalImage --> opFinalCache --> FinalSupervoxels\n # \\ / \\ \\\n # ------------------------------------------------------------------------------------------------------------------------------- RelabeledSupervoxels (SupervoxelMapping)\n\n def __init__(self, *args, **kwargs):\n super( OpSplitBodySupervoxelExport, self ).__init__(*args, **kwargs)\n\n # HACK: Be sure that the output slots are resized if the raveler body list changes\n self.AnnotationBodyIds.notifyDirty( bind(self._setupOutputs) )\n\n # Prepare a set of OpSelectLabels for easy access to raveler object masks\n self._opSelectLabel = OperatorWrapper( OpSelectLabel, parent=self, broadcastingSlotNames=['Input'] )\n self._opSelectLabel.Input.connect( self.RavelerLabels )\n self.EditedRavelerBodies.connect( self._opSelectLabel.Output )\n\n # Mask in the body of interest\n self._opMaskedSelect = OperatorWrapper( OpMaskedSelectUint32, parent=self, broadcastingSlotNames=['Input'] )\n self._opMaskedSelect.Input.connect( self.Supervoxels )\n self._opMaskedSelect.Mask.connect( self._opSelectLabel.Output )\n self.MaskedSupervoxels.connect( self._opMaskedSelect.Output ) \n\n # Must run CC before filter, to ensure that discontiguous labels can't avoid the filter.\n self._opRelabelMaskedSupervoxels = OperatorWrapper( OpVigraLabelVolume, parent=self )\n self._opRelabelMaskedSupervoxels.Input.connect( self._opMaskedSelect.Output )\n \n self._opRelabeledMaskedSupervoxelCaches = OperatorWrapper( OpCompressedCache, parent=self )\n self._opRelabeledMaskedSupervoxelCaches.Input.connect( self._opRelabelMaskedSupervoxels.Output )\n\n # Filter out the small CC to eliminate tiny pieces of supervoxels that overlap the mask boundaries\n self._opSmallLabelFilter = OperatorWrapper( OpFilterLabels, parent=self, broadcastingSlotNames=['MinLabelSize'] )\n self._opSmallLabelFilter.MinLabelSize.setValue( 10 )\n self._opSmallLabelFilter.Input.connect( self._opRelabeledMaskedSupervoxelCaches.Output )\n\n self._opSmallLabelFilterCaches = OperatorWrapper( OpCompressedCache, parent=self )\n self._opSmallLabelFilterCaches.Input.connect( self._opSmallLabelFilter.Output )\n self.FilteredMaskedSupervoxels.connect( self._opSmallLabelFilterCaches.Output )\n\n # Re-fill the holes left by the filter using region growing (with a mask)\n self._opMaskedWatersheds = OperatorWrapper( OpMaskedWatershed, parent=self )\n self._opMaskedWatersheds.Input.connect( self.InputData )\n self._opMaskedWatersheds.Mask.connect( self._opSelectLabel.Output )\n self._opMaskedWatersheds.Seeds.connect( self._opSmallLabelFilterCaches.Output )\n\n # Cache is necessary because it ensures that the entire volume is used for watershed.\n self._opMaskedWatershedCaches = OperatorWrapper( OpCompressedCache, parent=self )\n self._opMaskedWatershedCaches.Input.connect( self._opMaskedWatersheds.Output )\n self.HoleFilledSupervoxels.connect( self._opMaskedWatershedCaches.Output )\n\n # Relabel the supervoxels in the mask to ensure contiguous supervoxels (after mask) and consecutive labels\n self._opRelabelMergedSupervoxels = OperatorWrapper( OpVigraLabelVolume, parent=self )\n self._opRelabelMergedSupervoxels.Input.connect( self._opMaskedWatershedCaches.Output )\n \n self._opRelabeledMergedSupervoxelCaches = OperatorWrapper( OpCompressedCache, parent=self )\n self._opRelabeledMergedSupervoxelCaches.Input.connect( self._opRelabelMergedSupervoxels.Output )\n self.RelabeledSupervoxels.connect( self._opRelabeledMergedSupervoxelCaches.Output )\n\n self._opAccumulateFinalImage = OpAccumulateFragmentSegmentations( parent=self )\n self._opAccumulateFinalImage.RavelerLabels.connect( self.RavelerLabels )\n self._opAccumulateFinalImage.FragmentSegmentations.connect( self._opRelabeledMergedSupervoxelCaches.Output )\n \n self._opFinalCache = OpCompressedCache( parent=self )\n self._opFinalCache.Input.connect( self._opAccumulateFinalImage.Output )\n self.FinalSupervoxels.connect( self._opFinalCache.Output )\n self.SupervoxelMapping.connect( self._opAccumulateFinalImage.Mapping )\n \n def setupOutputs(self):\n raveler_bodies = self.AnnotationBodyIds.value\n num_bodies = len(raveler_bodies)\n\n # Map raveler body ids to the subslots that need them.\n self._opSelectLabel.SelectedLabel.resize( num_bodies )\n for index, raveler_body_id in enumerate(raveler_bodies):\n self._opSelectLabel.SelectedLabel[index].setValue( raveler_body_id )\n\n def execute(self, slot, subindex, roi, result):\n assert False, \"Can't execute slot {}. All slots should be connected to internal operators\".format( slot.name )\n\n def propagateDirty(self, slot, subindex, roi):\n # If anything is dirty, the entire output is dirty\n self.FinalSupervoxels.setDirty()\n\n def exportFinalSupervoxels(self, outputPath, axisorder, progressCallback=None):\n \"\"\"\n Executes the export process within a request.\n The (already-running) request is returned, in case you want to wait for it or monitor its progress.\n \"\"\"\n assert self.FinalSupervoxels.ready(), \"Can't export yet: The final segmentation isn't ready!\"\n\n logger.info(\"Starting Final Segmentation Export...\")\n \n opTranspose = OpReorderAxes( parent=self )\n opTranspose.AxisOrder.setValue( axisorder )\n opTranspose.Input.connect( self.FinalSupervoxels )\n \n f = h5py.File(outputPath, 'w')\n opExporter = OpH5WriterBigDataset(parent=self)\n opExporter.hdf5File.setValue( f )\n opExporter.hdf5Path.setValue( 'stack' )\n opExporter.Image.connect( opTranspose.Output )\n if progressCallback is not None:\n opExporter.progressSignal.subscribe( progressCallback )\n \n req = Request( partial(self._runExporter, opExporter) )\n\n def cleanOps():\n opExporter.cleanUp()\n opTranspose.cleanUp()\n \n def handleFailed( exc, exc_info ):\n cleanOps() \n f.close()\n import traceback\n traceback.print_tb(exc_info[2])\n msg = \"Final Supervoxel export FAILED due to the following error:\\n{}\".format( exc )\n logger.error( msg )\n\n def handleFinished( result ):\n # Generate the mapping transforms dataset\n mapping = self._opAccumulateFinalImage.Mapping.value\n num_labels = mapping.keys()[-1][1]\n transform = numpy.zeros( shape=(num_labels, 2), dtype=numpy.uint32 )\n for (start, stop), body_id in mapping.items():\n for supervoxel_label in range(start, stop):\n transform[supervoxel_label][0] = supervoxel_label\n if body_id == -1:\n # Special case: -1 means \"identity transform\" for this supervoxel\n # (Which is really an untouched raveler body)\n transform[supervoxel_label][1] = supervoxel_label\n else:\n transform[supervoxel_label][1] = body_id\n\n # Save the transform before closing the file\n f.create_dataset('transforms', data=transform)\n\n # Copy all other datasets from the original segmentation file.\n ravelerSegmentationInfo = self.DatasetInfos[2].value\n pathComponents = PathComponents(ravelerSegmentationInfo.filePath, self.WorkingDirectory.value)\n with h5py.File(pathComponents.externalPath, 'r') as originalFile:\n for k,dset in originalFile.items():\n if k not in ['transforms', 'stack']:\n f.copy(dset, k)\n \n try:\n cleanOps()\n logger.info(\"FINISHED Final Supervoxel Export\")\n finally:\n f.close()\n\n def handleCancelled():\n cleanOps()\n f.close()\n logger.info( \"Final Supervoxel export was cancelled!\" )\n\n req.notify_failed( handleFailed )\n req.notify_finished( handleFinished )\n req.notify_cancelled( handleCancelled )\n \n req.submit()\n return req # Returned in case the user wants to cancel it.\n\n def _runExporter(self, opExporter):\n # Trigger the export\n success = opExporter.WriteImage.value\n assert success\n return success\n\nclass OpMaskedSelectUint32(Operator):\n # Upstream watershed is output as signed int32.\n # We must produce uint32 for the label op.\n Input = InputSlot()\n Mask = InputSlot()\n Output = OutputSlot()\n \n def __init__(self, *args, **kwargs):\n super( OpMaskedSelectUint32, self ).__init__( *args, **kwargs )\n \n self._opMaskedSelect = OpMaskedSelect( parent=self )\n self._opMaskedSelect.Input.connect( self.Input )\n self._opMaskedSelect.Mask.connect( self.Mask )\n \n self._opConvertDtype = OpDtypeView( parent=self )\n self._opConvertDtype.Input.connect( self._opMaskedSelect.Output )\n self._opConvertDtype.OutputDtype.setValue( numpy.uint32 )\n self.Output.connect( self._opConvertDtype.Output )\n\n def setupOutputs(self):\n pass\n \n def execute(self, slot, subindex, roi, result):\n pass\n\n def propagateDirty(self, slot, subindex, roi):\n pass\n\n\n\n","sub_path":"ilastik/applets/splitBodySupervoxelExport/opSplitBodySupervoxelExport.py","file_name":"opSplitBodySupervoxelExport.py","file_ext":"py","file_size_in_byte":13289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"398890996","text":"\"\"\"\nTest obs package to make sure that the header in output csv files is\ncorrect.\n\"\"\"\nimport os\nimport numpy as np\n\ntry:\n import pymake\nexcept:\n msg = 'Error. Pymake package is not available.\\n'\n msg += 'Try installing using the following command:\\n'\n msg += ' pip install https://github.com/modflowpy/pymake/zipball/master'\n raise Exception(msg)\n\ntry:\n import flopy\nexcept:\n msg = 'Error. FloPy package is not available.\\n'\n msg += 'Try installing using the following command:\\n'\n msg += ' pip install flopy'\n raise Exception(msg)\n\nfrom framework import testing_framework\nfrom simulation import Simulation\n\ncell_dimensions = (300,)\nex = ['gwf_obs02']\nexdirs = []\nfor s in ex:\n exdirs.append(os.path.join('temp', s))\nddir = 'data'\n\nh0, h1 = 1., 0.\nnlay, nrow, ncol = 1, 10, 10\n\ndef get_model(idx, dir):\n nper = 1\n perlen = [5.0]\n nstp = [1]\n tsmult = [1.]\n delr = 1.\n delc = 1.\n top = 1.\n laytyp = 0\n botm = [0.]\n hk = 1.0\n\n nouter, ninner = 100, 300\n hclose, rclose, relax = 1e-6, 1e-6, 1.\n\n tdis_rc = []\n for i in range(nper):\n tdis_rc.append((perlen[i], nstp[i], tsmult[i]))\n\n name = ex[idx]\n\n # build MODFLOW 6 files\n ws = dir\n sim = flopy.mf6.MFSimulation(sim_name=name, version='mf6',\n exe_name='mf6',\n sim_ws=ws)\n # create tdis package\n flopy.mf6.ModflowTdis(sim, time_units='DAYS',\n nper=nper, perioddata=tdis_rc)\n\n # create iterative model solution and register the gwf model with it\n flopy.mf6.ModflowIms(sim, print_option='SUMMARY',\n no_ptcrecord=\"ALL\",\n outer_dvclose=hclose,\n outer_maximum=nouter,\n inner_maximum=ninner,\n inner_dvclose=hclose, rcloserecord=rclose,\n linear_acceleration='CG',\n relaxation_factor=relax,\n )\n\n # create gwf model\n gwfname = name\n gwf = flopy.mf6.MFModel(sim, model_type='gwf6', modelname=gwfname,\n model_nam_file='{}.nam'.format(gwfname))\n gwf.name_file.save_flows = True\n\n flopy.mf6.ModflowGwfdis(gwf, nlay=nlay, nrow=nrow, ncol=ncol,\n delr=delr, delc=delc,\n top=top, botm=botm,\n idomain=np.ones((nlay, nrow, ncol),\n dtype=np.int))\n\n # build list of obs csv files to create\n obsdict = {}\n for i in range(nrow):\n obslst = [('h_{}_{}'.format(i, j), 'head', (0, i, j))\n for j in range(ncol)]\n fname = '{}.{}.obs.csv'.format(name, i)\n obsdict[fname] = obslst\n\n flopy.mf6.ModflowUtlobs(gwf, pname='head_obs',\n digits=20,\n continuous=obsdict)\n\n # initial conditions\n flopy.mf6.ModflowGwfic(gwf, strt=1.)\n\n # node property flow\n flopy.mf6.ModflowGwfnpf(gwf,\n save_specific_discharge=True,\n icelltype=laytyp,\n k=hk,\n k33=hk)\n\n # chd files\n chdlist = [[(0, 0, 0), h0]]\n chdlist += [[(0, nrow - 1, ncol - 1), h1]]\n flopy.mf6.ModflowGwfchd(gwf,\n stress_period_data=chdlist,\n save_flows=False,\n print_flows=True,\n pname='CHD-1')\n\n # output control\n flopy.mf6.ModflowGwfoc(gwf,\n head_filerecord='{}.hds'.format(name),\n printrecord=[('BUDGET', 'LAST'), ('HEAD', 'LAST')],\n saverecord=[('HEAD', 'LAST')],\n )\n\n return sim\n\n\ndef build_models():\n for idx, dir in enumerate(exdirs):\n sim = get_model(idx, dir)\n sim.write_simulation()\n return\n\n\ndef eval_model(sim):\n print('evaluating model observations...')\n name = ex[sim.idxsim]\n headcsv = np.empty((nlay, nrow, ncol), dtype=np.float)\n for i in range(nrow):\n fname = '{}.{}.obs.csv'.format(name, i)\n print('Loading and testing {}'.format(fname))\n fname = os.path.join(sim.simpath, fname)\n rec = np.genfromtxt(fname, names=True, delimiter=',', deletechars='')\n for j in range(ncol):\n obsname_true = 'h_{}_{}'.format(i, j).upper()\n obsname_found = rec.dtype.names[j + 1].upper()\n errmsg = 'obsname in {} is incorrect. Looking for \"{}\" but found \"{}\"'\n errmsg = errmsg.format(fname, obsname_true, obsname_found)\n assert obsname_true == obsname_found, errmsg\n headcsv[0, i, :] = np.array(rec.tolist()[1:])\n\n fn = os.path.join(sim.simpath, '{}.hds'.format(name))\n hobj = flopy.utils.HeadFile(fn)\n headbin = hobj.get_data()\n\n assert np.allclose(headcsv, headbin), 'headcsv not equal head from binary file'\n\n return\n\n\n# - No need to change any code below\ndef test_mf6model():\n # initialize testing framework\n test = testing_framework()\n\n # build all of the models\n build_models()\n\n # run the test models\n for idx, dir in enumerate(exdirs):\n yield test.run_mf6, Simulation(dir, exfunc=eval_model, idxsim=idx)\n\n return\n\n\ndef main():\n # initialize testing framework\n test = testing_framework()\n\n # build all of the models\n build_models()\n\n # run the test models\n for idx, dir in enumerate(exdirs):\n sim = Simulation(dir, exfunc=eval_model, idxsim=idx)\n test.run_mf6(sim)\n\n return\n\n\nif __name__ == \"__main__\":\n # print message\n print('standalone run of {}'.format(os.path.basename(__file__)))\n\n # run main routine\n main()\n","sub_path":"Groundwater/mf6/autotest/test_gwf_obs02.py","file_name":"test_gwf_obs02.py","file_ext":"py","file_size_in_byte":5819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"255968483","text":"def solve():\n\tsum_swifts = 0\n\tsum_semaphores = 0\n\n\tcounter = 0\n\n\tfor i in range(n):\n\t\tsum_swifts = sum_swifts + scores_swifts[i]\n\t\tsum_semaphores = sum_semaphores + scores_semaphores[i]\n\n\t\tif sum_swifts == sum_semaphores:\n\t\t\tcounter = i + 1\n\n\treturn counter\n\n\nn = int(input())\nscores_swifts = [int(s) for s in input().split(' ')]\nscores_semaphores = [int(s) for s in input().split(' ')]\n\nsol = solve()\nprint(sol)","sub_path":"2017/s1.py","file_name":"s1.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"266591622","text":"\"\"\"\r\nCreate two lists - students and marks\r\nCreate a dictionary from these two lists using dictionary comprehension\r\nUse names as keys and marks as values\r\n\"\"\"\r\n\r\n# lists of keys and values\r\nlstnames = ['Sunil', 'Sachin', 'Rahul', 'Kapil', 'Rohit']\r\nlstmarks = [54, 65, 45, 67, 78]\r\n\r\n# dictionary comprehension\r\nd = {k:v for (k,v) in zip(lstnames, lstmarks)}\r\nprint(d)","sub_path":"Chapter-9-Dictionaries/Examples/3-create-dictionary-from-two-lists.py","file_name":"3-create-dictionary-from-two-lists.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"28702522","text":"# License\n'''\nCode by Rishitha\nApril 29,2020\nReleased under GNU GPL\n'''\n\nfrom scipy import signal\nimport matplotlib.pyplot as plt\nfrom pylab import*\nimport control\nfrom control import tf\nfrom scipy.interpolate import interp1d\n\n#if using termux\nimport subprocess\nimport shlex\n#end if\n\n#Defining the transfer function \ns1 = signal.lti([1778.8], [1,27,207,405]) #Transfer Function = 75(1+0.2s)/s(s^2+16s+100)\n\n#signal.bode takes transfer function as input and returns frequency,magnitude and phase arrays\nw,mag,phase = signal.bode(s1)\nsys = tf([1778.8], [1,27,207,405])\ngm, pm, Wgc, Wpc = control.margin(sys)\nfreq_as_fn_of_w = interp1d(phase, w)\nWgc = freq_as_fn_of_w(-140)\nGm = -20*log10(gm)\nGm = 0\nprint(\"Phase Margin=\",pm) #Phase margin\nprint(\"Gain Margin=\",Gm) #Gain margin\nprint(\"Gain crossover frequency(dB)=\",Wgc) #Gain crossover freq.(dB)\nprint(\"Phase crossover frequency(dB)=\",Wpc) #Phase crossover freq.(dB)\n\nplt.subplot(2,1,1)\nplt.plot(Wgc,0,'o', label='_nolegend_')\nplt.ylabel('Magnitude(deg)')\nplt.text(3.5,-10, '({}, {})'.format(Wgc.round(2),0))\nplt.semilogx(w, mag,'b') \nplt.axhline(y = 0,xmin=0,xmax= 1,color = 'b',linestyle='dashed')\nplt.axvline(x = Wgc, ymin = -140 ,color='k',linestyle='dashed')\nplt.legend(['0 dB line'], loc= 'lower left')\nplt.grid() \n\n\nplt.subplot(2,1,2)\nplt.xlabel('Frequency(rad/s)')\nplt.ylabel('Phase(deg)')\nplt.plot(14.39,-180,'x')\nplt.text(14.39,-180, '({}, {})'.format(14.39,-180))\nplt.semilogx(w,phase, label='_nolegend_') \nplt.plot(Wgc,-140,'o', label='_nolegend_')\nplt.axhline(y = -140,xmin=0,xmax= Wgc,color = 'r',linestyle='dashed')\nplt.axvline(x = Wgc, ymin = -140 ,color='k',linestyle='dashed')\nplt.text(2,-180, '({}, {})'.format(Wgc.round(2),-140))\nplt.legend(['-140 deg line'], loc= 'lower left')\nplt.grid() \n\n\n#if using termux\n\nplt.savefig('./figs/ee18btech11033/ee18btech11033_ver2.pdf')\nplt.savefig('./figs/ee18btech11033/ee18btech11033_ver2.eps')\nsubprocess.run(shlex.split(\"termux-open ./figs/ee18btech11033/ee18btech11033_ver2.pdf\"))\n\n#else \n\n \n#plt.show()\n","sub_path":"codes/ee18btech11033/ee18btech11033_ver2.py","file_name":"ee18btech11033_ver2.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"456534656","text":"# encoding: utf-8\nfrom __future__ import unicode_literals\n\nimport re\nimport os\n\nfrom datetime import date\nfrom urlparse import urlparse\n\nfrom django import template\nfrom django.db.models import Model\nfrom django.conf import settings\nfrom django.core.serializers.json import DjangoJSONEncoder\n\nfrom cmdb.models import PKG_STATUS_CHOICES, PkgStatus, UploadStatus\nfrom autopkg.views import DeployView\nfrom menus.views import get_perms, get_menus_map\n\nregister = template.Library()\nencoder = DjangoJSONEncoder()\n\nPATH_RE = re.compile(r'((&)?page=(\\d+))')\n\n\n@register.filter\ndef json_encode(data):\n if isinstance(data, Model):\n data = {field.name: getattr(data, field.name) for field in data._meta.fields}\n\n return encoder.encode(data)\n\n\n@register.filter\ndef get_pkg_status(key):\n return dict(PKG_STATUS_CHOICES).get(key, \"\")\n\n\n@register.filter\ndef get_label_class(key):\n if key in [PkgStatus.deploy_success, PkgStatus.rollback_success]:\n return \"pass\"\n elif key in [PkgStatus.abort]:\n return \"stop\"\n else:\n return \"nopass\"\n\n\n@register.filter\ndef get_pkg_status_img(status):\n if status in [PkgStatus.deploy_success, PkgStatus.rollback_success]:\n return os.path.join(settings.STATIC_URL, \"kylin/img/pass.png\")\n elif status in DeployView.deploying_status:\n return os.path.join(settings.STATIC_URL, \"public/img/refresh.png\")\n elif status in [PkgStatus.abort]:\n return os.path.join(settings.STATIC_URL, \"kylin/img/stop.png\")\n else:\n return os.path.join(settings.STATIC_URL, \"kylin/img/nopass.png\")\n\n\n@register.filter\ndef status_icon(status):\n if status in [PkgStatus.deploy_success, PkgStatus.rollback_success]:\n return '󰃢'\n elif status in DeployView.deploying_status:\n return ''\n elif status in [PkgStatus.abort]:\n return ''\n else:\n return ''\n\n\n@register.filter\ndef pkg_host_label_class(key):\n if key in [UploadStatus.start_success, UploadStatus.rollback_success, UploadStatus.restart_success]:\n return \"label-success\"\n elif key in [UploadStatus.start_fail, UploadStatus.rollback_fail, UploadStatus.restart_fail]:\n return \"label-danger\"\n else:\n return \"label-default\"\n\n\n@register.filter\ndef get_map_value(key, _map):\n return _map.get(key, \"\")\n\n\n@register.filter\ndef disable_status(pkg):\n if pkg.status not in DeployView.deploying_status:\n return \"disabled\"\n else:\n return \"\"\n\n\n@register.filter\ndef has_perm(request, menu):\n if request.session.get(\"menus\"):\n context = request.session[\"menus\"]\n perms = context.get(\"perm_names\", None)\n else:\n perms = get_perms(request, get_menus_map())\n return (perms is None) or (str(menu.unique_id) in perms)\n\n\n@register.filter\ndef concat_page(path, page):\n urlparts = urlparse(path)\n path = path.replace(\"?{}\".format(urlparts.query), \"\")\n query = urlparts.query\n if not query:\n return \"{path}?page={page}\".format(path=path, page=page)\n query_parts = query.split(\"&\")\n result_query = []\n has_page = False\n for q in query_parts:\n if q.startswith(\"page\"):\n has_page = True\n result_query.append(\"page={}\".format(page))\n else:\n result_query.append(q)\n query_str = \"&\".join(result_query)\n if not has_page:\n query_str = \"{}&page={}\".format(query_str, page)\n return \"{path}?{qs}\".format(path=path, qs=query_str)\n\n\n@register.filter\ndef env_label_class(env):\n if env == \"DEVELOP\":\n return \"cor_blue\"\n else:\n return \"cor_green\"\n\n\n@register.filter\ndef get_log_url(log):\n log_name = log.log_name\n if not log_name.endswith(\".tar.gz\"):\n log_name = \"{}.tar.gz\".format(log_name)\n url = settings.LOG_DOWNLOAD_URL.format(\n date=date.today().strftime(\"%Y%m%d\"), artifact_id=log.artifact_id, log_name=log_name)\n return url\n\n\n@register.filter\ndef to_name(directory):\n return directory.replace(\"/\", \"_\")\n","sub_path":"autopkg/templatetags/mytags.py","file_name":"mytags.py","file_ext":"py","file_size_in_byte":4289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"278314915","text":"import os\nimport sys\nimport time\n# Several Polkit functions used to depend pot.py (ALL GLOBAL) #\ndef polerror2a():\n\tprint('Error in function polt2a: Equal - int1=int2')\ndef polt2a(int1,int2):\n\tif(int1 > int2):\n\t\tglobal result\n\t\tresult = 1\n\telif(int1 < int2):\n\t\tglobal result\n\t\tresult = 0\n\telse:\n\t\traise polerror2a()\ndef poltquit():\n\tprint('PoltPy either has an error or is done. Exitting')\n\tsys.exit()\n","sub_path":"libdewstar/polkit.py","file_name":"polkit.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"461539375","text":"#!/usr/bin/python\nimport sys\nimport nwb\nimport numpy as np\nfrom nwb.nwbco import *\n\n\"\"\" \nStore extracellular ephys data\n\n\"\"\"\n\n########################################################################\n# create a new NWB file\n# several settings are specified when doing so. these can be supplied within\n# the NWB constructor or defined in a dict, as in in this example\nsettings = {}\nsettings[\"filename\"] = \"sample_extracellular_spikes.nwb\"\n\n# each file should have a descriptive globally unique identifier \n# that specifies the lab and this experiment session\n# the function nwb.create_identifier() is recommended to use as it takes\n# the string and appends the present date and time\nsettings[\"identifier\"] = nwb.create_identifier(\"extracellular spikes example\")\n\n# indicate that it's OK to overwrite exting file\nsettings[\"overwrite\"] = True\n\n# specify the start time of the experiment. all times in the NWB file\n# are relative to experiment start time\n# if the start time is not specified the present time will be used\nsettings[\"start_time\"] = \"Sat Jul 04 2015 3:14:16\"\n\n# provide one or two sentences that describe the experiment and what\n# data is in the file\nsettings[\"description\"] = \"Test file demonstrating a simple extracellular ephys recording\"\n\n# create the NWB object. this manages the file\nprint(\"Creating \" + settings[\"filename\"])\nneurodata = nwb.NWB(**settings)\n\n########################################################################\n# create two electrical series, one with a single electrode and one with many\n# then create a spike event series\n\n# first create the electrode map\n# example simulated recording is made from two 2-electrode probes named\n# 'p0' and 'p1'. we need to define the locations of the electrodes\n# relative to each probe, and the location of the probes\n# electrode coordinates are in meters and their positions \n# are relative to each other. the location of the probe itself is\n# stored separately. using absolute coordinates here, if they are known, \n# is still OK\nelectrode_map = [[0, 0, 0], [0, 1.5e-6, 0], [0, 0, 0], [0, 3.0e-5, 0]]\nelectrode_group = [ \"p0\", \"p0\", \"p1\", \"p1\" ]\nneurodata.set_metadata(EXTRA_ELECTRODE_MAP, electrode_map)\nneurodata.set_metadata(EXTRA_ELECTRODE_GROUP, electrode_group)\n# set electrode impedances\nneurodata.set_metadata(EXTRA_IMPEDANCE, [ 1e6, 1.1e6, 1.2e6, 1.3e6 ])\n\n# define the placement of each probe\nneurodata.set_metadata(EXTRA_SHANK_LOCATION(\"p0\"), \"CA1, left hemisphere, stereotactic coordinates xx, yy\")\nneurodata.set_metadata(EXTRA_SHANK_LOCATION(\"p1\"), \"CA3, left hemisphere, stereotactic coordinates xx, yy\")\n\n########################################################################\n# the example is of two 2-electrode probes. the electrode data from these\n# probes can be stored individually, grouped as probes (eg, 2-electrode\n# pair) or all stored together. these approaches are all exampled here \n\n# create time series with all electrode data stored together\nquad = neurodata.create_timeseries(\"ElectricalSeries\", \"quad\", \"acquisition\")\nquad.set_comment(\"Data corresponds to four electrodes (two probes)\")\nquad.set_data(np.zeros((10000, 4)), resolution=1.2345e-6)\nquad.set_time(np.arange(10000) * 0.0001)\n# indicate that we're recording from the first electrode defined in the\n# above map (electrode numbers start at zero, so electrodes are \n# 0, 1, 2 and 3\nquad.set_value(\"electrode_idx\", [0, 1, 2, 3])\n# finish the time series and write data to disk\nquad.finalize()\n\n########################################################################\n# spikes can be reported by hardware or be detected by software\n# in both cases, they are considered to be processed data and so belong\n# in a processing module\n\n# create the module\nspike_mod = neurodata.create_module(\"my spikes\")\n\n# create an interface that stores the events. here they will be stored\n# with their waveforms, such as would be the input to a spike-sorting\n# algorithm\nspike_iface = spike_mod.create_interface(\"EventWaveform\")\nspike_iface.set_source(\"Data from device FooBar-X1 using dynamic multi-phasic threshold of 5xRMS\")\n\n# the event waveform interface publishes a SpikeEventSeries. make \n# that series\nspike = neurodata.create_timeseries(\"SpikeEventSeries\", \"my waveforms\")\nspike.set_comment(\"Snapshots of spike events pulled from a recording\")\nspike.set_value(\"electrode_idx\", [2, 3]) # probe 'p1'\n# describe the source of the data (may be redundant w/ interface source)\nspike.set_value(\"source\", \"Data from device FooBar-X1 using dynamic multi-phasic threshold of 5xRMS\")\n# make some bogus simulated data\n# this is 20 events all having the same shape and a pseudorandom time\nevt = np.zeros((8,2))\nevt[3][0] = 0.01\nevt[4][0] = -0.005\nevt[3][1] = 0.005\nevt[4][1] = -0.0025\ndata = []\nt = []\nlast = 1.0\nfor i in range(20):\n data.append(evt)\n last = last + (i * 17) % 29\n t.append(last)\n# \nspike.set_time(t)\nspike.set_data(data, resolution=1.2345e-6)\n# if data were stored in another unit such as microvolts, it would be\n# necessary to specify a converstion between that unit and Volts.\n# that would be done using the following:\n#spike.set_data(data, conversion=1.0e-6)\n\n# add the time series to the interface. the interface will manage \n# finalizing the time series\nspike_iface.add_timeseries(spike)\n\n# now close the interface and its parent module\nspike_iface.finalize()\nspike_mod.finalize()\n\n# close file, otherwise it will fail to write properly\nneurodata.close()\n\n","sub_path":"ainwb/examples/extracellular_spikes.py","file_name":"extracellular_spikes.py","file_ext":"py","file_size_in_byte":5471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"513045986","text":"\"\"\"\n@version: 1\n@author: zyb\n@site: \n@software: PyCharm Community Edition\n@file: multipleMatrix.py\n@time: 2017/3/10 10:06\n矩阵乘法运算\n\"\"\"\ndef multipleMatrix(ma1,ma2,n):\n new_ma=[]\n\n for i in range(0,n):\n new_ma.append([])\n for j in range(0,n):\n temp = 0\n for k in range(0,n):\n temp=temp+ma1[i][k]*ma2[k][j]\n new_ma[i].append(temp)\n return new_ma\n\nif __name__==\"__main__\":\n\n ma1=[[1,2],[1,2]]\n ma2=[[2,1],[2,1]]\n print(ma1)\n new_ma=multipleMatrix(ma1,ma2,2)\n print(new_ma)","sub_path":"multipleMatrix.py","file_name":"multipleMatrix.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"394992328","text":"from student import Student\n\n\ns1 = Student('Didas','Mbalanya','TZ')\ns2 = Student('Cynthia','Chepkemoi',)\ns3 = Student('Kennedy','Mutemi','UG')\ns4 = Student('Victor','Muthomi')\ns5 = Student('Paul','Kahohi','NG')\ns6 = Student('john','Ouma','NG')\ns7 = Student('james','john')\ns8 = Student('nevo','nunda')\ns9 = Student('boom','pow')\ns10= Student('brian','john')\n\ns1.attend_class()\ns2.attend_class()\ns3.attend_class()\ns4.attend_class()\ns5.attend_class()","sub_path":"attendFun.py","file_name":"attendFun.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"338619704","text":"import copy\nfrom rl.make_game import is_atari_game\nimport numpy as np\nfrom particle_filtering.pf_uct import PFMCTS\n\n\nclass PFMCTS3(PFMCTS):\n\n def search(self, n_mcts, c, Env, mcts_env, budget, max_depth=200, fixed_depth=True):\n \"\"\" Perform the MCTS search from the root \"\"\"\n env = copy.deepcopy(Env)\n self.create_root(env, budget)\n if self.root.terminal:\n raise (ValueError(\"Can't do tree search from a terminal state\"))\n\n is_atari = is_atari_game(env)\n if is_atari:\n raise NotImplementedError\n while budget > 0:\n state = self.root # reset to root for new trace\n if not is_atari:\n mcts_env = copy.deepcopy(Env) # copy original Env to rollout from\n else:\n raise NotImplementedError\n mcts_env.seed(np.random.randint(1e7))\n st = 0\n source_particle = None\n could_sample = True\n n_particles = 1\n while not state.terminal:\n bias = c * self.gamma ** st / (1 - self.gamma) if self.depth_based_bias else c\n action = state.select(c=bias, variance=self.variance)\n st += 1\n k = np.ceil(self.beta * state.n ** self.alpha)\n previous_particles = n_particles\n n_particles = state.get_n_particles()\n previous_could_sample = could_sample\n could_sample = n_particles >= k or state.root\n if not could_sample and source_particle is None:\n source_particle, budget = state.parent_action.sample_from_parent_state(mcts_env, budget)\n state.add_particle(source_particle)\n if source_particle.terminal:\n break\n if action.child_state is not None:\n # select\n state = action.child_state\n if source_particle is not None:\n source_particle, budget = action.sample_from_particle(source_particle, mcts_env, budget)\n state.add_particle(source_particle)\n if source_particle.terminal:\n break\n elif state.terminal:\n source_particle, budget = state.parent_action.sample_from_parent_state(mcts_env, budget)\n state.add_particle(source_particle)\n else:\n rollout_depth = max_depth if fixed_depth else max_depth - st\n state, budget, source_particle = action.add_child_state(mcts_env, budget, max_depth=rollout_depth,\n source_particle=source_particle,\n depth=st) # expand\n break\n\n # Back-up\n R = state.V\n state.update()\n particle = source_particle\n while state.parent_action is not None: # loop back-up until root is reached\n r = particle.reward\n if not particle.terminal:\n R = r + self.gamma * R\n else:\n R = r\n action = state.parent_action\n action.update(R)\n state = action.parent_state\n state.update()\n particle = particle.parent_particle\n","sub_path":"particle_filtering/pf_uct_3.py","file_name":"pf_uct_3.py","file_ext":"py","file_size_in_byte":3483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"456586616","text":"import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time, datetime\nfrom tensorflow.examples.tutorials.mnist import input_data\n# 최신 Windows Laptop에서만 사용할것.CPU Version이 높을때 사용.\n# AVX를 지원하는 CPU는 Giuthub: How to compile tensorflow using SSE4.1, SSE4.2, and AVX. \n# Ubuntu와 MacOS는 지원하지만 Windows는 없었음. 2018-09-29\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\n# Compuntational Graph Initialization\nfrom tensorflow.python.framework import ops\nops.reset_default_graph()\n\nDATA_DIR = \"/tmp/ML/MNIST_data\"\nmnist = input_data.read_data_sets(DATA_DIR, one_hot=True)\n\n# Define Hyper Parameters\nAlpha_Lr = 0.001 # Learning Rate Alpha\nN_EPISODES = 15\nbatch_size = 100\n\n#########\n# 신경망 모델 구성\n######\n# 기존 모델에서는 입력 값을 28x28 하나의 차원으로 구성하였으나,\n# CNN 모델을 사용하기 위해 2차원 평면과 특성치의 형태를 갖는 구조로 만듭니다.\nX = tf.placeholder(tf.float32, [None, 28, 28, 1])\nY = tf.placeholder(tf.float32, [None, 10])\n# dropout (keep_prob) rate 0.7~0.5 on training, but should be 1 for testing\nkeep_prob = tf.placeholder(tf.float32)\n\n# 각각의 변수와 레이어는 다음과 같은 형태로 구성됩니다.\n# W01_m [3 3 1 32] -> [3 3]: 커널 크기, 1: 입력값 X 의 특성수, 32: 필터 갯수\n# _LAY01_m Conv shape=(?, 28, 28, 32)\n# Pool ->(?, 14, 14, 32)\nW01_m = tf.Variable(tf.random_normal([3, 3, 1, 32], stddev=0.01))\n# tf.nn.conv2d 를 이용해 한칸씩 움직이는 컨볼루션 레이어를 쉽게 만들 수 있습니다.\n# padding='SAME' 은 커널 슬라이딩시 최외곽에서 한칸 밖으로 더 움직이는 옵션\nCONV_01 = tf.nn.conv2d(X, W01_m, strides=[1, 1, 1, 1], padding='SAME')\nRELU_01 = tf.nn.relu(CONV_01)\n# Pooling 역시 tf.nn.max_pool 을 이용하여 쉽게 구성할 수 있습니다.\nMAX_POOL_01 = tf.nn.max_pool(RELU_01, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n# _LAY01_m = tf.nn.dropout(_LAY01_m, keep_prob)\n\n# _LAY02_m Conv shape=(?, 14, 14, 64)\n# Pool ->(?, 7, 7, 64)\n# W02_m 의 [3, 3, 32, 64] 에서 32 는 _LAY01_m 에서 출력된 W01_m 의 마지막 차원, 필터의 크기 입니다.\nW02_m = tf.Variable(tf.random_normal([3, 3, 32, 64], stddev=0.01))\nCONV_02 = tf.nn.conv2d(MAX_POOL_01, W02_m, strides=[1, 1, 1, 1], padding='SAME')\nRELU_02 = tf.nn.relu(CONV_02)\nMAX_POOL_02 = tf.nn.max_pool(RELU_02, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n# _LAY02_m = tf.nn.dropout(_LAY02_m, keep_prob)\n\n# FC 레이어: 입력값 7x7x64 -> 출력값 256\n# Full connect를 위해 직전의 Pool 사이즈인 (?, 7, 7, 64) 를 참고하여 차원을 줄여줍니다.\n# Reshape ->(?, 256)\nW03_m = tf.Variable(tf.random_normal([7 * 7 * 64, 256], stddev=0.01))\n_LAY03_m = tf.reshape(MAX_POOL_02, [-1, 7 * 7 * 64])\nFULLY_CONN_03 = tf.matmul(_LAY03_m, W03_m)\nRELU_03 = tf.nn.relu(FULLY_CONN_03)\nDROP_OUT_03 = tf.nn.dropout(RELU_03, keep_prob)\n\n# 최종 출력값 _LAY03_m 에서의 출력 256개를 입력값으로 받아서 0~9 레이블인 10개의 출력값을 만듭니다.\nW04_m = tf.Variable(tf.random_normal([256, 10], stddev=0.01))\nPred_m = tf.matmul(DROP_OUT_03, W04_m)\n\ncost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=Pred_m, labels=Y))\noptimizer = tf.train.AdamOptimizer(learning_rate = Alpha_Lr).minimize(cost)\n# 최적화 함수를 RMSPropOptimizer 로 바꿔서 결과를 확인해봅시다.\n# optimizer = tf.train.RMSPropOptimizer(0.001, 0.9).minimize(cost)\n\n#########\n# 신경망 모델 학습\n######\ninit = tf.global_variables_initializer()\nsess = tf.Session()\nsess.run(init)\nstart_time = time.time()\nprint('Learning Started!')\n\ntotal_batch = int(mnist.train.num_examples / batch_size)\n\nfor episode in range(N_EPISODES):\n total_cost = 0\n\n for i in range(total_batch):\n batch_xs, batch_ys = mnist.train.next_batch(batch_size)\n # 이미지 데이터를 CNN 모델을 위한 자료형태인 [28 28 1] 의 형태로 재구성합니다.\n batch_xs = batch_xs.reshape(-1, 28, 28, 1)\n\n _, cost_val = sess.run([optimizer, cost],\n feed_dict={X: batch_xs,\n Y: batch_ys,\n keep_prob: 0.7})\n total_cost += cost_val\n\n print('episode:', '%05d' % (episode + 1),\n 'Avg. cost =', '{:.5f}'.format(total_cost / total_batch))\n \n elapsed_time = datetime.timedelta(seconds=int(time.time()-start_time))\n print(\"[{}]\".format(elapsed_time))\n\nprint('Optimization Completed!')\n\n#########\n# 결과 확인\n######\nis_correct = tf.equal(tf.argmax(Pred_m, 1), tf.argmax(Y, 1))\naccuracy = tf.reduce_mean(tf.cast(is_correct, tf.float32))\nprint('Accuracy:', sess.run(accuracy,\n feed_dict={X: mnist.test.images.reshape(-1, 28, 28, 1),\n Y: mnist.test.labels,\n keep_prob: 1}))\n\nprint('Total_batch =', total_batch)\n\nelapsed_time = time.time() - start_time\nformatted = datetime.timedelta(seconds=int(elapsed_time))\nprint(\"=== training time elapsed: {}s ===\".format(formatted))\n\n#########\n# 결과 확인 (matplot)\n######\nlabels = sess.run(Pred_m,\n feed_dict={X: mnist.test.images.reshape(-1, 28, 28, 1),\n Y: mnist.test.labels,\n keep_prob: 1})\n\nfig = plt.figure()\nfor i in range(60):\n subplot = fig.add_subplot(4, 15, i + 1)\n subplot.set_xticks([])\n subplot.set_yticks([])\n subplot.set_title('%d' % np.argmax(labels[i]))\n subplot.imshow(mnist.test.images[i].reshape((28, 28)),\n cmap=plt.cm.gray_r)\n\nplt.show()\n\n\n# 세션을 닫습니다.\nsess.close()\n\n\n# Step 10. Tune hyperparameters:\n# Step 11. Deploy/predict new outcomes:\n\n","sub_path":"05_MNIST_CNN_Tensorboard_Save_Restore/01_MNIST_Simple_CNN_01_w_time.py","file_name":"01_MNIST_Simple_CNN_01_w_time.py","file_ext":"py","file_size_in_byte":5871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"96186836","text":"\"\"\"\nCopyright 2013 Rackspace\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nfrom datetime import datetime\n\nfrom cloudcafe.compute.common.constants import Constants\nfrom cloudroast.stacktach.fixtures import StackTachComputeIntegration,\\\n StackTachTestAssertionsFixture\n\n\nclass StackTachDBServerResizeUpConfirmTests(StackTachComputeIntegration,\n StackTachTestAssertionsFixture):\n \"\"\"\n @summary: With Server Resize Up (e.g., from flavor 2 -> 3),\n tests the entries created in StackTach DB.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n cls.create_server()\n cls.resize_server()\n cls.confirm_resize_server()\n cls.audit_period_beginning = \\\n datetime.utcnow().strftime(Constants.DATETIME_0AM_FORMAT)\n\n cls.stacktach_events_for_server(server=cls.confirmed_resized_server)\n cls.event_launch_resize_server = cls.event_launches[1]\n\n def test_launch_entry_on_resize_server_up_response(self):\n \"\"\"\n Verify the Launch parameters are being returned in the\n Server Resize Up response\n \"\"\"\n # There should be 2 launch entries for a resize.\n self.validate_attributes_in_launch_response(num_of_launch_entry=2)\n\n def test_launch_entry_fields_on_create_server(self):\n \"\"\"\n Verify that the first Launch entry will have all expected fields\n after a Server Resize Up\n \"\"\"\n self.validate_launch_entry_field_values(\n server=self.created_server)\n\n def test_launch_entry_fields_on_resize_up(self):\n \"\"\"\n Verify that the second Launch entry will have all expected fields\n after a Server Resize Up\n \"\"\"\n self.validate_launch_entry_field_values(\n server=self.verify_resized_server,\n event_launch_server=self.event_launch_resize_server,\n expected_flavor_ref=self.flavor_ref_alt,\n launched_at=self.launched_at_resized_server)\n\n def test_exist_entry_on_resize_up_server_response(self):\n \"\"\"\n Verify the Exist parameters are correct after a Server Resize Up\n \"\"\"\n self.validate_attributes_in_exist_response()\n\n def test_exists_entry_fields_on_resize_up(self):\n \"\"\"\n Verify that the Exist entry will have all expected fields\n after Server Resize Up\n \"\"\"\n self.validate_exist_entry_field_values(\n server=self.created_server)\n self.validate_exist_entry_audit_period_values(\n expected_audit_period_ending=self.resize_start_time,\n expected_audit_period_beginning=self.audit_period_beginning)\n\n def test_exist_launched_at_field_match_on_resize_up(self):\n \"\"\"\n Verify that the Exists entry launched_at matches the\n Launch entry launched_at for a Server Resize Up\n \"\"\"\n\n self.assertEqual(self.event_launch.launched_at,\n self.event_exist.launched_at,\n self.msg.format(\n \"launched_at\",\n self.event_launch.launched_at,\n self.event_exist.launched_at,\n self.exist_response.reason,\n self.exist_response.content))\n\n def test_no_delete_entry_on_resize_up_server_response(self):\n \"\"\"\n Verify that there is no delete entry after a Server Resize Up\n \"\"\"\n self.validate_no_deletes_entry_returned()\n","sub_path":"cloudroast/stacktach/functional/test_server_resize_up_confirm_in_stacktach_db.py","file_name":"test_server_resize_up_confirm_in_stacktach_db.py","file_ext":"py","file_size_in_byte":3984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"121884733","text":"import tornado.websocket\nimport tornado.web\nimport tornado.ioloop\nimport time\nfrom tributary.reactive.input import _gen\n\n\nclass DummyWebSocket(tornado.websocket.WebSocketHandler):\n def open(self):\n print(\"WebSocket opened\")\n i = 0\n x = {y: _gen() for y in ('A', 'B', 'C', 'D')}\n try:\n while i < len(x['A']):\n self.write_message({'A': x['A'][i],\n 'B': x['B'][i],\n 'C': x['C'][i],\n 'D': x['D'][i]})\n i += 1\n time.sleep(.1)\n finally:\n print(\"WebSocket closed\")\n self.close()\n\n def on_message(self, message):\n self.write_message(u\"You said: \" + message)\n\n def on_close(self):\n print(\"WebSocket closed\")\n\n\ndef main():\n app = tornado.web.Application([(r\"/\", DummyWebSocket)])\n app.listen(8899)\n print('listening on %d' % 8899)\n tornado.ioloop.IOLoop.current().start()\n\nif __name__ == '__main__':\n main()\n","sub_path":"tests/dummy_ws.py","file_name":"dummy_ws.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"398751667","text":"import pandas as pd\nfrom konlpy import tag\nimport random\nimport pickle\nfrom keras.preprocessing import sequence\nimport numpy as np\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import losses\nfrom tensorflow.keras import optimizers\nfrom tensorflow.keras import models\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.preprocessing import StandardScaler\nimport matplotlib.pyplot as plt\nimport os.path\nfrom flask import Flask, request\n\n\ndef data_load(option):\n csv = pd.read_csv('train_data_add_add.csv')\n titles_csv = csv['title']\n prices_csv = csv['price']\n if option == \"titles\":\n csv = titles_csv\n elif option == 'price':\n csv = prices_csv\n return csv\n\n\ndef words_to_ids(words, word_dict):\n ids = []\n for word in words:\n try:\n ids.append(word_dict.index(word))\n except Exception as e:\n print(e)\n return ids\n\n\nclass RNN:\n\n def __init__(self, model_name):\n self._model_name = model_name\n\n try:\n with open(\"titles_words.bin\", \"rb\") as f:\n self._titles_words = pickle.load(f)\n with open(\"dictionary.bin\", \"rb\") as f:\n self._dictionary = pickle.load(f)\n with open(\"titles_ids.bin\", \"rb\") as f:\n self._titles_ids = pickle.load(f)\n print(\"------------Data 사전을 로드합니다--------------\")\n\n except Exception as e:\n print(\"------------Data 사전이 없으므로 생성합니다----------\")\n okt = tag.Okt()\n words_set = set()\n self._titles_words = []\n count = 1\n for title in data_load(\"titles\"):\n title_pos = okt.pos(title, norm=True)\n words = []\n for word in title_pos:\n words_set.add(word[0])\n words.append(word[0])\n self._titles_words.append(words)\n count += 1\n\n dictionary = list(words_set)\n random.shuffle(dictionary)\n self._dictionary = [0] + dictionary\n\n self._titles_ids = []\n count = 1\n for title in self._titles_words:\n words_id = words_to_ids(title, self._dictionary)\n self._titles_ids.append(words_id)\n count += 1\n with open(\"titles_words.bin\", \"wb\") as f:\n pickle.dump(self._titles_words, f)\n with open(\"dictionary.bin\", \"wb\") as f:\n pickle.dump(self._dictionary, f)\n with open(\"titles_ids.bin\", \"wb\") as f:\n pickle.dump(self._titles_ids, f)\n\n def ids_to_words(self, ids):\n words = []\n for word_id in ids:\n if word_id != 0:\n words.append(self._dictionary[word_id])\n return words\n\n def index_process(self):\n self._max_title_len = max(len(title_ids) for title_ids in self._titles_ids)\n # print(max_title_len)\n titles_ids_np = sequence.pad_sequences(self._titles_ids, maxlen=self._max_title_len, padding='post')\n # print(titles_ids_np)\n self._prices_np = np.array([[price] for price in data_load(\"price\")])\n # print(prices_np)\n\n index = [i for i in range(len(titles_ids_np))]\n random.shuffle(index)\n\n train_len = int(len(index) * 0.9)\n train_index = index[:train_len]\n test_index = index[train_len:]\n\n # print(len(titles_ids_np))\n # print(len(train_index))\n # print(len(test_index))\n\n self._X_train = titles_ids_np[train_index]\n self._X_test = titles_ids_np[test_index]\n\n self._scaler = MinMaxScaler() # StandardScaler()\n self._scaler.fit(self._prices_np)\n y_scaled = self._scaler.transform(self._prices_np)\n\n self._y_train_scaled = y_scaled[train_index]\n self._y_test_scaled = y_scaled[test_index]\n\n # print(prices_np)\n # print(y_scaled)\n\n self._vocab_size = len(self._dictionary)\n\n @staticmethod\n def tokenizer_create(text):\n okt = tag.Okt()\n text_pos = okt.pos(text, norm=True)\n\n words = []\n for word in text_pos:\n words.append(word[0])\n\n return words\n\n def sequence_create(self, text_ids):\n sequence_np = sequence.pad_sequences([text_ids], maxlen=self._max_title_len, padding='post')\n return sequence_np\n\n def model_create(self):\n model = keras.Sequential([\n layers.Embedding(self._vocab_size, 64),\n layers.Bidirectional(layers.LSTM(64, return_sequences=True)),\n layers.Bidirectional(layers.LSTM(32)),\n layers.Dense(64, activation='relu'),\n layers.Dropout(0.5),\n layers.Dense(1)\n ])\n model.summary()\n\n model.compile(loss=losses.MeanSquaredError(), optimizer=optimizers.Adam(1e-4), metrics=['mae'])\n history = model.fit(self._X_train, self._y_train_scaled, epochs=30,\n validation_data=(self._X_test, self._y_test_scaled),\n validation_steps=30, verbose=1)\n model.save(self._model_name)\n\n return model\n\n def model_load(self):\n try:\n model = models.load_model(self._model_name)\n print(\"-----------RNN 모델을 로드합니다-------------\")\n return model\n except Exception as e:\n print(e)\n print(\"-----------RNN 모델이 없으므로 학습을 진행합니다-------------\")\n model = self.model_create()\n return model\n\n def plot_graphs(history, metric):\n plt.plot(history.history[metric])\n plt.plot(history.history['val_' + metric], '')\n plt.xlabel(\"Epochs\")\n plt.ylabel(metric)\n plt.legend([metric, 'val_' + metric])\n plt.show()\n\n # plot_graphs(history, 'mae')\n # plot_graphs(history, 'loss')\n\n # price_predictions = model.predict(X_test)\n #\n # y_test_inverse = scaler.inverse_transform(y_test_scaled)\n # price_predictions_inverse = scaler.inverse_transform(price_predictions)\n\n # for i in range(100):\n # print(f\"{i}: {ids_to_words(X_test[i])}\")\n # print(f\"{i}: {y_test_inverse[i]} = {price_predictions_inverse[i]}\")\n # print()\n\n # print(ids_to_words(X_test[5]))\n\n def predict_phone(self, text):\n text_words = self.tokenizer_create(text)\n print(text_words)\n text_ids = words_to_ids(text_words, self._dictionary)\n text_ids_np = self.sequence_create(text_ids)\n model = self.model_load()\n predictions = model.predict(text_ids_np)\n text_predictions_inverse = self._scaler.inverse_transform(predictions)\n # print(f'{text} -> {text_predictions_inverse}')\n return text_predictions_inverse[0][0]\n\n\nrnn = RNN(\"baseline_model_data_add.h5\")\nrnn.index_process()\nfile_1 = 'C:\\\\Users\\\\JEONKYUBIN\\\\Desktop\\\\AI\\\\RNN\\\\data.txt'\nfile_2 = 'C:\\\\Users\\\\JEONKYUBIN\\\\Desktop\\\\AI\\\\RNN\\\\prediction.txt'\n\napp = Flask(__name__)\n\n\n\n\n@app.route('/volt/ai', methods=['GET'])\ndef ai_route() -> None:\n try:\n product_name = request.args.get('product_name')\n price_float: float = rnn.predict_phone(product_name.upper())\n price_int: int = round(int(price_float), -3)\n return {\n 'data': price_int\n }\n except:\n return {\n 'data': 'error'\n }\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0')\n\n# while True:\n# if os.path.isfile(file_1): # if 문 쓰기 (파일 존재 유무 검사)\n# with open(\"data.txt\", 'r', encoding='UTF-8') as f:\n# test = f.read()\n# if not test:\n# # print(\"문자열이 비어있음\")\n# continue\n# text_upped = test.upper()\n# print(test)\n# price_float = rnn.predict_phone(text_upped)\n# price_int = round(int(price_float), -3)\n# price_str = str(price_int)\n# with open(\"prediction.txt\", 'w', encoding='UTF-8') as f:\n# f.write(price_str)\n# print(price_str + \"원\")\n#\n# os.remove(file_1)\n# # data.txt 파일 지우기 추가\n# else:\n# pass\n# # print(\"AI 작동에 문제가 생겼습니다\")\n","sub_path":"RNN/PredictPrice.py","file_name":"PredictPrice.py","file_ext":"py","file_size_in_byte":8251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"115775353","text":"LETTERS = ['Z','E','R','O','N','T','W','H','F','U','V','S','I','X','G']\nCOUNT_0 = [1,1,1,1,0,0,0,0,0,0,0,0,0,0,0]\nCOUNT_1 = [0,1,0,1,1,0,0,0,0,0,0,0,0,0,0]\nCOUNT_2 = [0,0,0,1,0,1,1,0,0,0,0,0,0,0,0]\nCOUNT_3 = [0,2,1,0,0,1,0,1,0,0,0,0,0,0,0]\nCOUNT_4 = [0,0,1,1,0,0,0,0,1,1,0,0,0,0,0]\nCOUNT_5 = [0,1,0,0,0,0,0,0,1,0,1,0,1,0,0]\nCOUNT_6 = [0,0,0,0,0,0,0,0,0,0,0,1,1,1,0]\nCOUNT_7 = [0,2,0,0,1,0,0,0,0,0,1,1,0,0,0]\nCOUNT_8 = [0,1,0,0,0,1,0,1,0,0,0,0,1,0,1]\nCOUNT_9 = [0,1,0,0,2,0,0,0,0,0,0,0,1,0,0]\n\ndef read(name):\n return [s.split('\\n')[0] for s in open(name,'r').readlines()[1:]]\n \ndef count(s):\n counts = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\n for c in s:\n counts[LETTERS.index(c)] += 1\n return counts\n \ndef subtract_counts(c1,c2):\n # subtract c2 from c1\n return [v1-v2 for v1,v2 in zip(c1,c2)]\n \ndef find_number(counts):\n number = []\n \n for zero in range(0,counts[LETTERS.index('Z')]):\n counts = subtract_counts(counts,COUNT_0)\n number.append(0)\n \n for six in range(0,counts[LETTERS.index('X')]):\n counts = subtract_counts(counts,COUNT_6)\n number.append(6)\n \n for eight in range(0,counts[LETTERS.index('G')]):\n counts = subtract_counts(counts,COUNT_8)\n number.append(8)\n \n for seven in range(0,counts[LETTERS.index('S')]):\n counts = subtract_counts(counts,COUNT_7)\n number.append(7)\n \n for seven in range(0,counts[LETTERS.index('V')]):\n counts = subtract_counts(counts,COUNT_5)\n number.append(5)\n \n for nine in range(0,counts[LETTERS.index('I')]):\n counts = subtract_counts(counts,COUNT_9)\n number.append(9)\n \n for four in range(0,counts[LETTERS.index('U')]):\n counts = subtract_counts(counts,COUNT_4)\n number.append(4)\n \n for three in range(0,counts[LETTERS.index('H')]):\n counts = subtract_counts(counts,COUNT_3)\n number.append(3)\n \n for one in range(0,counts[LETTERS.index('E')]):\n counts = subtract_counts(counts,COUNT_1)\n number.append(1)\n \n for two in range(0,counts[LETTERS.index('O')]):\n counts = subtract_counts(counts,COUNT_2)\n number.append(2)\n \n return sorted(number)\n \n\ncases = read('A-large.in')\nnumbers = []\nfor case in cases:\n counts = count(case)\n number = find_number(counts)\n numbers.append(number)\n\noutfile = open('out','w')\nfor i,number in enumerate(numbers):\n outfile.write('Case #%s: %s\\n' % (i+1,''.join([str(n) for n in number])))\noutfile.close()\n ","sub_path":"codes/CodeJamCrawler/16_2_1_neat/16_2_1_ThomasB_code.py","file_name":"16_2_1_ThomasB_code.py","file_ext":"py","file_size_in_byte":2562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"211842175","text":"from tests import DocumentPageTestCase\nfrom document_generator.decorators import IdTitleCollectorFileDecorator\n\n\nclass IdTitleCollectorFileDecoratorTest(DocumentPageTestCase):\n def decorate(self, node):\n decorator = IdTitleCollectorFileDecorator()\n state = decorator.init_state(node)\n decorator.run(node, state)\n return (state, decorator)\n\n def test_no_files(self):\n node = {\n 'files': {},\n 'subnodes': [],\n }\n\n state, decorator = self.decorate(node)\n\n self.assertEmpty(state['id-title-map'])\n\n self.assertEmpty(decorator.get_messages(state))\n\n def test_plain(self):\n node = {\n 'name': 'bar',\n 'files': {\n 'en': {\n 'id': 'id-foo',\n 'key': 'en',\n 'markdown': 'foo\\nbar',\n },\n },\n 'subnodes': [],\n }\n\n state, decorator = self.decorate(node)\n\n self.assertEqual(state['id-title-map']['id-foo']['en'], 'foo')\n self.assertLenIs(state['id-title-map']['id-foo'], 1)\n\n self.assertEmpty(decorator.get_messages(state))\n\n def test_multiple_files(self):\n node = {\n 'name': 'bar',\n 'files': {\n 'en': {\n 'id': 'id-foo',\n 'key': 'en',\n 'markdown': 'foo\\nbar',\n },\n 'de': {\n 'id': 'id-foo',\n 'key': 'de',\n 'markdown': 'quux\\nbar',\n },\n },\n 'subnodes': [],\n }\n\n state, decorator = self.decorate(node)\n\n self.assertEqual(state['id-title-map']['id-foo']['en'], 'foo')\n self.assertEqual(state['id-title-map']['id-foo']['de'], 'quux')\n self.assertLenIs(state['id-title-map']['id-foo'], 2)\n\n self.assertEmpty(decorator.get_messages(state))\n\n def test_empty_lines(self):\n node = {\n 'name': 'bar',\n 'files': {\n 'en': {\n 'id': 'id-foo',\n 'key': 'en',\n 'markdown': '\\n \\nfoo\\nbar',\n },\n },\n 'subnodes': [],\n }\n\n state, decorator = self.decorate(node)\n\n self.assertEqual(state['id-title-map']['id-foo']['en'], 'foo')\n self.assertLenIs(state['id-title-map']['id-foo'], 1)\n\n self.assertEmpty(decorator.get_messages(state))\n\n def test_section_marker_stripping(self):\n node = {\n 'name': 'bar',\n 'files': {\n 'en': {\n 'id': 'id-foo',\n 'key': 'en',\n 'markdown': '## # # foo\\nbar',\n },\n },\n 'subnodes': [],\n }\n\n state, decorator = self.decorate(node)\n\n self.assertEqual(state['id-title-map']['id-foo'],\n {'en': 'foo'})\n\n self.assertEmpty(decorator.get_messages(state))\n\n def test_attribute_stripping(self):\n node = {\n 'name': 'bar',\n 'files': {\n 'en': {\n 'id': 'id-foo',\n 'key': 'en',\n 'markdown': 'foo {=BAR} {: class=quux}\\nbar',\n },\n },\n 'subnodes': [],\n }\n\n state, decorator = self.decorate(node)\n\n self.assertEqual(state['id-title-map']['id-foo'],\n {'en': 'foo {=BAR}'})\n\n self.assertEmpty(decorator.get_messages(state))\n\n def test_anonymous(self):\n node = {\n 'name': 'bar',\n 'files': {\n 'en': {\n 'id': 'id-foo',\n 'key': 'en',\n 'markdown': '',\n },\n },\n 'subnodes': [],\n }\n\n state, decorator = self.decorate(node)\n\n self.assertEqual(state['id-title-map']['id-foo'],\n {'en': '(anonymous)'})\n\n messages = decorator.get_messages(state)\n self.assertEqual(messages[0]['kind'], 'error')\n self.assertIn('title', messages[0]['text'])\n self.assertLenIs(messages, 1)\n\n def test_default(self):\n node = {\n 'name': 'bar',\n 'files': {\n 'default': {\n 'id': 'id-foo',\n 'key': 'en',\n 'is-default': True,\n 'markdown': 'foo'\n },\n },\n 'subnodes': [],\n }\n\n state, decorator = self.decorate(node)\n\n self.assertEqual(state['id-title-map']['id-foo'],\n {'default': 'foo'})\n\n self.assertEmpty(decorator.get_messages(state))\n","sub_path":"tests/decorators/test_id_title_collector_file_decorator.py","file_name":"test_id_title_collector_file_decorator.py","file_ext":"py","file_size_in_byte":4796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"9815310","text":"from config import Config\nna = \"1970-01-01 08:00:00\"\n\nopt = Config()\n\ndef divide_data(para):\n if para == 0:\n filename = opt.TRAIN_FILE\n else:\n filename = opt.TEST_FILE\n with open(filename, 'r') as f:\n with open('data/withoutpreselling.csv', 'w') as out1:\n with open('data/preselling.csv', 'w') as out2:\n idx = 0\n for line in f:\n if idx == 0:\n out1.write(line)\n out2.write(line)\n else:\n preselling = line.split('\\t')[9]\n if preselling == '0' or preselling == na:\n out1.write(line)\n else:\n out2.write(line)\n idx+=1\n\n# 0 means train\n# 1 means test\ndivide_data(0)\n","sub_path":"seedcup_tf/data_process.py","file_name":"data_process.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"324204561","text":"#!/usr/bin/python3\n\nfrom which_pyqt import PYQT_VER\nif PYQT_VER == 'PYQT5':\n\tfrom PyQt5.QtCore import QLineF, QPointF\nelif PYQT_VER == 'PYQT4':\n\tfrom PyQt4.QtCore import QLineF, QPointF\nelse:\n\traise Exception('Unsupported Version of PyQt: {}'.format(PYQT_VER))\n\n\n\n\nimport time\nimport numpy as np\nfrom TSPClasses import *\nimport heapq\nimport itertools\nfrom MyClasses import *\nimport HeapQueue\n\n\n\nclass TSPSolver:\n\tdef __init__( self, gui_view ):\n\t\tself._scenario = None\n\n\tdef setupWithScenario( self, scenario ):\n\t\tself._scenario = scenario\n\n\n\t''' \n\t\tThis is the entry point for the default solver\n\t\twhich just finds a valid random tour. Note this could be used to find your\n\t\tinitial BSSF.\n\t\t\n\t\tresults dictionary for GUI that contains three ints: cost of solution, \n\t\ttime spent to find solution, number of permutations tried during search, the \n\t\tsolution found, and three null values for fields not used for this \n\t\talgorithm \n\t'''\n\t\n\tdef defaultRandomTour( self, time_allowance=60.0 ):\n\t\tresults = {}\n\t\tcities = self._scenario.getCities()\n\t\tncities = len(cities)\n\t\tfoundTour = False\n\t\tcount = 0\n\t\tbssf = None\n\t\tstart_time = time.time()\n\t\twhile not foundTour and time.time()-start_time < time_allowance:\n\t\t\t# create a random permutation\n\t\t\tperm = np.random.permutation( ncities )\n\t\t\troute = []\n\t\t\t# Now build the route using the random permutation\n\t\t\tfor i in range( ncities ):\n\t\t\t\troute.append( cities[ perm[i] ] )\n\t\t\tbssf = TSPSolution(route)\n\t\t\tcount += 1\n\t\t\tif bssf.cost < np.inf:\n\t\t\t\t# Found a valid route\n\t\t\t\tfoundTour = True\n\t\tend_time = time.time()\n\t\tresults['cost'] = bssf.cost if foundTour else math.inf\n\t\tresults['time'] = end_time - start_time\n\t\tresults['count'] = count\n\t\tresults['soln'] = bssf\n\t\tresults['max'] = None\n\t\tresults['total'] = None\n\t\tresults['pruned'] = None\n\t\treturn results\n\n\n\t''' \n\t\tThis is the entry point for the greedy solver, which you must implement for \n\t\tthe group project (but it is probably a good idea to just do it for the branch-and\n\t\tbound project as a way to get your feet wet). Note this could be used to find your\n\t\tinitial BSSF.\n\t\t\n\t\tresults dictionary for GUI that contains three ints: cost of best solution, \n\t\ttime spent to find best solution, total number of solutions found, the best\n\t\tsolution found, and three null values for fields not used for this \n\t\talgorithm \n\t'''\n\n\tdef greedy( self,time_allowance=60.0, all_solns = False ):\n\t\tresults = {}\n\t\tsolutions = []\n\t\tnsolutions = 0\n\t\tcities = self._scenario.getCities()\n\t\tncities = len(cities)\n\t\tbssf = None\n\t\tstart_time = time.time()\n\t\tfor start_city in cities:\n\t\t\troute_set = set()\n\t\t\troute_set.add(start_city)\n\t\t\troute = [start_city]\n\t\t\tcurrent_city = start_city\n\t\t\twhile len(route) < ncities and time.time()-start_time < time_allowance:\n\t\t\t\tmin_cost = np.inf\n\t\t\t\tnext_city = None\n\t\t\t\tfor c2 in cities:\n\t\t\t\t\tif c2 not in route_set:\n\t\t\t\t\t\tcost_to = current_city.costTo(c2)\n\t\t\t\t\t\tif cost_to < min_cost:\n\t\t\t\t\t\t\tnext_city = c2\n\t\t\t\t\t\t\tmin_cost = cost_to\n\t\t\t\tif next_city is not None:\n\t\t\t\t\troute_set.add(next_city)\n\t\t\t\t\troute.append(next_city)\n\t\t\t\t\tcurrent_city = next_city\n\t\t\t\telse:\n\t\t\t\t\tbreak\n\t\t\tif time.time()-start_time < time_allowance and len(route) == ncities:\n\t\t\t\tbssf_candidate = TSPSolution(route)\n\t\t\t\tif bssf_candidate.cost < np.inf:\n\t\t\t\t\tnsolutions += 1\n\t\t\t\t\t#print(f\"Cost of solution starting at {start_city._name} - {bssf_candidate.cost}\")\n\t\t\t\t\tif bssf is None or bssf_candidate.cost < bssf.cost:\n\t\t\t\t\t\tbssf = bssf_candidate\n\t\t\t\t\tif all_solns:\n\t\t\t\t\t\tsolutions.append(bssf_candidate)\n\n\t\tend_time = time.time()\n\t\tif bssf is not None:\n\t\t\tresults['cost'] = bssf.cost\n\t\telse:\n\t\t\tresults['cost'] = math.inf\n\t\tresults['time'] = end_time - start_time\n\t\tresults['count'] = nsolutions\n\t\tif all_solns:\n\t\t\tresults['soln'] = (solutions, bssf)\n\t\telse:\n\t\t\tresults['soln'] = bssf\n\t\tresults['max'] = None\n\t\tresults['total'] = None\n\t\tresults['pruned'] = None\n\t\treturn results\t\t\t\t\n\t\n\n\t''' \n\t\tThis is the entry point for the branch-and-bound algorithm that you will implement\n\t\t\n\t\tresults dictionary for GUI that contains three ints: cost of best solution, \n\t\ttime spent to find best solution, total number solutions found during search (does\n\t\tnot include the initial BSSF), the best solution found, and three more ints: \n\t\tmax queue size, total number of states created, and number of pruned states. \n\t'''\n\t\t\n\tdef branchAndBound( self, time_allowance=60.0 ):\n\t\t# Set bssf to greedy solution\n\t\tstart_time = time.time()\n\t\tcities = self._scenario.getCities()\n\t\tncities = len(cities)\n\t\t#greedy_results = self.defaultRandomTour(time_allowance)\n\t\tgreedy_results = self.greedy(time_allowance)\n\t\tif greedy_results['soln'] is None:\n\t\t\tgreedy_results = self.defaultRandomTour(time_allowance)\n\n\t\tself._priority_queue = MyHeap()\n\t\tself._bssf = greedy_results['soln']\n\t\tself._states_created = 0\n\t\tself._pruned_states = 0\n\t\tself._max_queue_size = 0\n\t\tself._solutions_found = 0\n\n\t\t#initialize rcm\n\t\tstart_rcm = self.init_rcm(cities, ncities)\n\t\t# Start at first city and create nodes for each city not in route\n\t\troute = [cities[0]]\n\t\troute_set = set()\n\t\troute_set.add(cities[0])\n\t\tstart_node = Node(route, route_set, start_rcm)\n\t\tself._priority_queue.insert(start_node)\n\n\t\t# This creates at most, n! states but won't ever actually make that many\n\t\t# Because of this, the total time and space complexity is O(n!n^2)\n\t\twhile time.time()-start_time < time_allowance and self._priority_queue.size() > 0:\n\t\t\tnode = self._priority_queue.delete_min()\n\t\t\troute = node.route\n\t\t\troute_set = node.route_set\n\t\t\trcm = node.rcm\n\t\t\tif (rcm.lower_bound >= self._bssf.cost):\n\t\t\t\tself._pruned_states += 1\n\t\t\t\tcontinue\n\n\t\t\t# Runs O(n) times, but the complexity is factored into the while loop\n\t\t\t# The time complexity isn't in the update_rcm function, but is when we make a copy of the matrix\n\t\t\t# So this section is O(n^3)\n\t\t\tfor city in cities:\n\t\t\t\tif city not in route_set:\n\t\t\t\t\tself._states_created += 1\n\t\t\t\t\tnew_route = route[:]\n\t\t\t\t\tnew_route.append(city)\n\t\t\t\t\tnew_route_set = route_set.copy()\n\t\t\t\t\tnew_route_set.add(city)\n\t\t\t\t\tnew_rcm = rcm.copy()\n\t\t\t\t\tself.update_rcm(new_rcm, route[-1]._index, city._index, ncities)\n\t\t\t\t\tif new_rcm.lower_bound >= self._bssf.cost:\n\t\t\t\t\t\tself._pruned_states += 1\n\t\t\t\t\telse:\n\t\t\t\t\t\tif len(new_route) == ncities:\n\t\t\t\t\t\t\tbssf_candidate = TSPSolution(new_route)\n\t\t\t\t\t\t\tself._solutions_found += 1\n\t\t\t\t\t\t\tif bssf_candidate.cost < self._bssf.cost:\n\t\t\t\t\t\t\t\tself._bssf = bssf_candidate\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tself._pruned_states += 1\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tnew_node = Node(new_route, new_route_set, new_rcm)\n\t\t\t\t\t\t\tnew_node.update_priority()\n\t\t\t\t\t\t\tself._priority_queue.insert(new_node)\n\t\t\t\t\t\t\tif self._priority_queue.size() > self._max_queue_size:\n\t\t\t\t\t\t\t\tself._max_queue_size = self._priority_queue.size()\n\t\tend_time = time.time()\n\t\tif time.time()-start_time < time_allowance:\n\t\t\tself._pruned_states += self._priority_queue.size()\n\t\tresults = {}\n\t\tresults['cost'] = self._bssf.cost\n\t\tresults['time'] = end_time - start_time\n\t\tresults['count'] = self._solutions_found\n\t\tresults['soln'] = self._bssf\n\t\tresults['max'] = self._max_queue_size\n\t\tresults['total'] = self._states_created\n\t\tresults['pruned'] = self._pruned_states\n\t\treturn results\t\t\n\n\n\t# city_start and city_end are indices\n\tdef update_rcm(self, rcm, city_start, city_end, ncities):\n\t\t# Add residual cost of edge we ended up taking to lower bound\n\t\trcm.lower_bound += rcm.matrix[city_start][city_end]\n\t\t\n\t\t# replace every value in that node's rows and columns with np.inf\n\t\tfor i in range(ncities):\n\t\t\trcm.matrix[i][city_end] = np.inf\n\t\t\trcm.matrix[city_start][i] = np.inf \n\n\t\t# Turn reverse node into infty\n\t\trcm.matrix[city_end][city_start] = np.inf\n\t\t\n\t\t# reduce so each row and column has a 0 in it (except ones with only infinity)\n\t\tself.reduce_rcm(ncities, rcm)\n\n\n\t# O(n^2) time and space complexity\n\tdef init_rcm(self, cities, ncities):\n\t\trcm = ReducedCostMatrix(ncities)\n\t\t#fill in edges from graph O(n^2)\n\t\tfor i in range(ncities):\n\t\t\tfor j in range(ncities):\n\t\t\t\tif i != j:\n\t\t\t\t\trcm.matrix[i][j] = cities[i].costTo(cities[j])\n\t\t#self.print_matrix(rcm.matrix)\n\t\t# reduce the rcm\n\t\tself.reduce_rcm(ncities, rcm)\n\t\treturn rcm\n\n\t# Constant space complexity, O(n^2) time complexity\n\tdef reduce_rcm(self, ncities, rcm):\n\t\t# For each row, find lowest number and add to lower bound\n\t\t# then replace each node in that row with cost - lowest_cost O(n^2)\n\t\tfor row in range(ncities):\n\t\t\tmin_cost = np.inf\n\t\t\tfor column in range(ncities):\n\t\t\t\t\tif rcm.matrix[row][column] < min_cost:\n\t\t\t\t\t\tmin_cost = rcm.matrix[row][column]\n\t\t\t#print(f\"Min cost = {min_cost}\")\n\t\t\tif min_cost != 0 and min_cost != np.inf:\n\t\t\t\t\trcm.lower_bound += min_cost\n\t\t\t\t\tfor column in range(ncities):\n\t\t\t\t\t\trcm.matrix[row][column] -= min_cost\n\t\t# Do the same thing for each column\n\t\tfor column in range(ncities):\n\t\t\tmin_cost = np.inf\n\t\t\tfor row in range(ncities):\n\t\t\t\t\tif rcm.matrix[row][column] < min_cost:\n\t\t\t\t\t\tmin_cost = rcm.matrix[row][column]\n\t\t\tif min_cost != 0 and min_cost != np.inf:\n\t\t\t\t\trcm.lower_bound += min_cost\n\t\t\t\t\tfor row in range(ncities):\n\t\t\t\t\t\trcm.matrix[row][column] -= min_cost\n\n\tdef print_matrix(self, A):\n\t\tprint('\\n'.join([''.join(['{:5} '.format(item) for item in row]) for row in A]))\n\n\n\n\n\n\t''' \n\t\tThis is the entry point for the algorithm you'll write for your group project.\n\t\t\n\t\tresults dictionary for GUI that contains three ints: cost of best solution, \n\t\ttime spent to find best solution, total number of solutions found during search, the \n\t\tbest solution found. You may use the other three field however you like.\n\t\talgorithm \n\t'''\n\t\t\n\tdef fancy( self,time_allowance=60.0 ):\n\t\tself.population_size = 1000\n\t\tself.mating_size = int(self.population_size/2)\n\t\tself.num_mutations = int(self.population_size/4)\n\t\tself.random_sol_time = 10\n\t\tself.greedy_sol_time = 600\n\t\tself.total_solutions = 0\n\t\tself.bssf_updates = 0\n\t\tself.invalid_sols_generated = 0\n\t\tself.num_generations = 0\n\t\tsolution_timeout = 15.0\n\t\tself.last_solution_update = time.time()\n\t\tstart_time = time.time()\t\t\n\t\tself.init_population()\n\t\tself.max_generations_since_update = 5000\n\t\tself.num_generations_since_update = 0\n\t\twhile time.time()-start_time < time_allowance and self.num_generations_since_update < self.max_generations_since_update:\n\t\t\t# Determine Fitness --> Already done because our population is just the solutions\n\t\t\t# Select mating pool\n\t\t\tmating_population = self.select_mates()\n\t\t\t# Breed\n\t\t\tbreeding_order = np.random.permutation(mating_population)\n\t\t\tfor i in range(0, len(breeding_order), 2):\n\t\t\t\tself.breed(breeding_order[i], breeding_order[i+1])\n\t\t\t# Mutate\n\t\t\tfor _ in range(self.num_mutations):\n\t\t\t\tself.mutate(self.population[random.randint(0,len(self.population)-1)])\n\t\t\t# Prune to population size\n\t\t\tself.prune()\n\t\t\tself.num_generations += 1\n\t\t\tself.num_generations_since_update += 1\n\t\tend_time = time.time()\n\n\t\tresults = {}\n\t\tresults['cost'] = self.bssf.cost\n\t\tresults['time'] = end_time - start_time\n\t\tresults['count'] = self.bssf_updates\n\t\tresults['soln'] = self.bssf\n\t\tresults['max'] = self.num_generations\n\t\tresults['total'] = self.total_solutions\n\t\tresults['pruned'] = self.invalid_sols_generated\n\t\t# print(self.bssf_updates)\n\t\treturn results\n\n\n\tdef select_mates(self):\n\t\tpopulation_costs = np.array([1/p.cost for p in self.population])\n\t\tpopulation_distribution = population_costs/np.sum(population_costs)\n\t\treturn np.random.choice(self.population, self.mating_size, p=population_distribution)\n\n\tdef init_population(self):\n\t\t# self.population, bssf = [], self.defaultRandomTour()['soln'] \n\t\tself.population, bssf = self.greedy(time_allowance=self.greedy_sol_time, all_solns=True)['soln']\n\t\tself.bssf = bssf\n\t\tnum_iters = 0\n\t\t# while len(self.population) < self.population_size or num_iters < self.population_size*5:\n\t\t# \tsol = self.defaultRandomTour(time_allowance=self.random_sol_time)['soln']\n\t\t# \tself.add_sol(sol)\n\t\t# \tnum_iters += 1\n\t\twhile len(self.population) < self.population_size:\n\t\t\tself.add_sol(self.random())\n\n\tdef mutate(self, sol):\n\t\tidx = random.randint(0, len(sol.route)-2)\n\t\troute = sol.route.copy()\n\t\troute[idx], route[idx+1] = route[idx+1], route[idx]\n\t\tnew_sol = TSPSolution(route)\n\t\tself.add_sol(new_sol)\n\t\t\n\n\tdef add_sol(self, new_sol, keep_inf_prob=.5):\n\t\tself.total_solutions += 1\n\t\tif new_sol.cost < np.inf or random.random() < keep_inf_prob:\n\t\t\tself.population.append(new_sol)\n\t\telif new_sol.cost == np.inf:\n\t\t\tself.invalid_sols_generated += 1\n\t\tif self.bssf is None or new_sol.cost < self.bssf.cost:\n\t\t\t\tself.bssf = new_sol\n\t\t\t\tself.num_generations_since_update = 0\n\t\t\t\tself.last_solution_update = time.time()\n\t\t\t\tself.bssf_updates += 1\n\t\t\n\tdef breed(self, sol1, sol2):\n\t\trange1 = random.randint(0, len(sol1.route)-1)\n\t\trange2 = random.randint(0, len(sol1.route)-1)\n\n\t\tstart_idx = min(range1, range2)\n\t\tend_idx = max(range1, range2)\n\t\tself.add_sol(self.breed_single(sol1, sol2, start_idx, end_idx))\n\t\tself.add_sol(self.breed_single(sol2, sol1, start_idx, end_idx))\n\t\n\n\tdef breed_single(self, sol1, sol2, start_idx, end_idx):\n\t\tcities = set(map(lambda x: x._index, sol1.route[start_idx:end_idx+1]))\n\t\tnew_route = sol1.route.copy()\n\t\tj = 0\n\t\tfor i in range(len(sol1.route)):\n\t\t\tif i >= start_idx or i <= end_idx:\n\t\t\t\tcontinue\n\t\t\twhile sol2.route[j]._index in cities:\n\t\t\t\tj += 1\n\t\t\tnew_route[i] = sol2.route[j]\n\t\t\tj += 1\n\t\treturn TSPSolution(new_route)\n\n\tdef prune(self):\n\t\tnum_to_prune = len(self.population) - self.population_size\n\t\tif num_to_prune > 0:\n\t\t\tcosts = [p.cost for p in self.population]\n\t\t\tmax_cost = max(filter(lambda x: x < np.inf, costs))\n\t\t\tcosts = [c if c < np.inf else max_cost for c in costs]\n\t\t\tpopulation_costs = np.array(costs)\n\t\t\tpopulation_distribution = population_costs/np.sum(population_costs)\n\t\t\tdelete_routes = np.random.choice(self.population, num_to_prune, p=population_distribution)\n\t\t\tself.population = list(filter(lambda city: city not in delete_routes, self.population))\n\n\tdef random(self):\n\t\tresults = {}\n\t\tcities = self._scenario.getCities()\n\t\tncities = len(cities)\n\t\tperm = np.random.permutation(ncities)\n\t\troute = []\n\t\t# Now build the route using the random permutation\n\t\tfor i in range(ncities):\n\t\t\troute.append(cities[perm[i]])\n\t\tbssf = TSPSolution(route)\n\t\treturn bssf\n","sub_path":"TSPSolver.py","file_name":"TSPSolver.py","file_ext":"py","file_size_in_byte":14238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"472144497","text":"import sys\n\nN = int(sys.stdin.readline())\nK = int(sys.stdin.readline())\nboard = [[0 for _ in range(N+1)] for _ in range(N+1)]\nboard[0][0]=1\n\nr = 0\nc = 0\nfor i in range(K):\n r,c = map(int,sys.stdin.readline().split())\n if r>= 1 and c >=1:\n board[r-1][c-1] = 2\n \n\nL = int(sys.stdin.readline())\n\nsecs= [0 for _ in range(L+1)]\ndirection=[0 for _ in range(L+1)]\n\nfor i in range(L):\n s,dr = sys.stdin.readline().split()\n secs[i] = int(s)\n direction[i] = dr\n\ndx = [0,1,0,-1]\ndy = [-1,0,1,0]\n\nsec = 0\nx = 0\ny = 0\nht = 0 # head turn\ntt = 0 # tail turn\nd = 1\ntail_d = 1\ntail = [0,0]\nwhile(True):\n sec +=1\n next_x = x+ dx[d]\n next_y = y + dy[d]\n \n if next_x < 0 or next_x >=N or next_y < 0 or next_y >=N:\n break\n if board[next_y][next_x] == 1:\n break\n \n x = next_x\n y = next_y\n\n if board[y][x] == 2:\n board[tail[0]][tail[1]] = 1\n board[y][x] = 1\n elif board[y][x] == 0:\n board[y][x] = 1\n board[tail[0]][tail[1]] = 0\n next_t_y = tail[0] + dy[tail_d]\n next_t_x = tail[1] + dx[tail_d]\n\n if (next_t_x < 0 or next_t_x >=N or next_t_y < 0 or next_t_y >=N):\n if tt < L:\n if direction[tt] == 'L':\n tail_d = (tail_d+3)%4\n elif direction[tt] == 'D':\n tail_d = (tail_d+1)%4\n tt += 1\n else:\n break\n tail[0] = tail[0] + dy[tail_d]\n if(tail[0] < 0 or tail[0] >=N):\n break\n tail[1] = tail[1] + dx[tail_d]\n if(tail[1] < 0 or tail[1] >=N):\n break\n board[tail[0]][tail[1]] = 1\n\n if ht < L:\n if sec == secs[ht]:\n if direction[ht] == 'L':\n d = (d+3)%4\n elif direction[ht] == 'D':\n d = (d+1)%4\n ht += 1\n\nprint(sec) \n\n\n","sub_path":"2020_spring/samsungSW/3190.py","file_name":"3190.py","file_ext":"py","file_size_in_byte":1864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"327453173","text":"import time\ndef addUpToV1(n):\n total = 0\n for i in range(n):\n total += (i+1)\n return(total)\n\ndef addUpToV2(n):\n return n * (n+1)/2\n\nn = int(input('Input Value:'))\n\nstart = time.time()\nprint('answer V1:', addUpToV1(n))\nprint('time V1', (time.time()-start)*1000)\n\nstart = time.time()\nprint('answer V2:', addUpToV2(n))\nprint('time V2:', (time.time()-start)*1000)","sub_path":"week3/addUp.py","file_name":"addUp.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"33400351","text":"import random as rand\nimport abc\n\n\nclass List:\n # Initializes an empty linked list.\n def __init__(self):\n self.liste = []\n\n # Returns true if this linked list is empty.\n def isEmpty(self):\n return len(self.liste) == 0\n\n # Returns the number of items in this linked list.\n def size(self):\n return len(self.liste)\n\n # Returns the first item added to this linked list\n def check(self):\n if self.isEmpty():\n raise ValueError(\"linked list underflow\")\n return self.liste[0]\n\n # Removes and returns the first item in the linked list\n def peek(self):\n if self.isEmpty():\n raise ValueError(\"linked list underflow\")\n item = self.liste.pop(0)\n return item\n\n def append(self, item):\n self.liste.append(item)\n\n def prepend(self, item):\n self.liste.insert(0, item)\n\n def accept(self, visitor):\n visitor.visit(self)\n\n\nclass Queue(List):\n\n # Initializes an empty queue.\n def __init__(self, max_size, *args, **kwargs):\n self.max_size = max_size\n super(Queue, self).__init__()\n\n def isFull(self):\n return len(self.liste) == self.max_size\n\n # Adds the item to this queue.\n def enqueue(self, item):\n if self.isFull():\n raise ValueError(\"Queue overflow\")\n self.append(item)\n\n # Removes and returns the item on this queue that was least recently added.\n def dequeue(self):\n try:\n return self.peek()\n except ValueError:\n raise ValueError(\"Queue underflow\")\n\n\nclass Stack(List):\n # Initializes an empty stack.\n def __init__(self, max_size, *args, **kwargs):\n self.max_size = max_size\n super(Stack, self).__init__()\n\n # Returns true if this stack is full.\n def isFull(self):\n return len(self.liste) == self.max_size\n\n # Adds the item to this stack.\n def push(self, item):\n if self.isFull():\n raise ValueError(\"Stack overflow\")\n self.prepend(item)\n\n # Removes and returns the item most recently added to this stack.\n def pop(self):\n try:\n return self.peek()\n except ValueError:\n raise ValueError(\"Stack underflow\")\n\n\nclass AutoAdaptiveStack(Stack):\n\n def __init__(self, max_trials, size_increment, *args, **kwargs):\n self.max_trials = max_trials\n self.size_increment = size_increment\n self.trials = 0\n self.waiting_list = []\n self.waiting_list_size = 1\n super(AutoAdaptiveStack, self).__init__(*args, **kwargs)\n\n def push(self, item):\n try:\n super(AutoAdaptiveStack, self).push(item)\n except ValueError:\n print(\"There is no free space actually :( try later\")\n if len(self.waiting_list) < self.waiting_list_size:\n self.waiting_list.append(item)\n self.trials += 1\n if self.trials == self.max_trials:\n self.max_size += self.size_increment\n for i in range(self.size_increment):\n if len(self.waiting_list) > 0:\n self.push(self.waiting_list.pop(0))\n else:\n break\n self.trials = 0\n\n def pop(self):\n try:\n removed_el = self.peek()\n if len(self.waiting_list) > 0:\n self.push(self.waiting_list.pop(0))\n return removed_el\n except ValueError:\n raise ValueError(\"Stack underflow\")\n\n\nclass AutoAdaptiveQueue(Queue):\n\n def __init__(self, max_trials, size_increment, *args, **kwargs):\n self.max_trials = max_trials\n self.size_increment = size_increment\n self.trials = 0\n self.waiting_list = []\n self.waiting_list_size = 1\n super(AutoAdaptiveQueue, self).__init__(*args, **kwargs)\n\n def enqueue(self, item):\n try:\n super(AutoAdaptiveQueue, self).enqueue(item)\n except ValueError:\n print(\"There is no free space actually :( try later\")\n if len(self.waiting_list) < self.waiting_list_size:\n self.waiting_list.append(item)\n self.trials += 1\n if self.trials == self.max_trials:\n self.max_size += self.size_increment\n for i in range(self.size_increment):\n if len(self.waiting_list) > 0:\n self.append(self.waiting_list.pop(0))\n else:\n break\n self.trials = 0\n\n def dequeue(self):\n try:\n removed_el = self.peek()\n if len(self.waiting_list) > 0:\n self.enqueue(self.waiting_list.pop(0))\n return removed_el\n except ValueError:\n raise ValueError(\"Queue underflow\")\n\n\nclass Printer(object, metaclass=abc.ABCMeta):\n def __init__(self, name):\n self.name = name\n\n def visit(self, list_obj):\n if isinstance(list_obj, Stack):\n display_message = \"\\n-------\\n\"\n i = 0\n while i < list_obj.size():\n display_message += ' ' + str(list_obj.liste[i]) + ' '\n display_message += \"\\n-------\\n\"\n i += 1\n elif isinstance(list_obj, Queue):\n display_message = \"\\n|\"\n i = 0\n while i < list_obj.size():\n display_message += str(list_obj.liste[i]) + \"|\"\n i += 1\n display_message += \"\\n\"\n else:\n display_message = \"\\n(\"\n i = 0\n while i < list_obj.size() - 1:\n display_message += str(list_obj.liste[i]) + \",\"\n i += 1\n display_message += str(list_obj.liste[i]) + \")\\n\"\n self.log(display_message)\n\n @abc.abstractmethod\n def log(self, display_message):\n raise NotImplementedError('child objects must define log to create a printer')\n\n\nclass ScreenPrinter(Printer):\n def __init__(self, *args, **kwargs):\n super(ScreenPrinter, self).__init__(*args, **kwargs)\n\n def log(self, display_message):\n print(self.name)\n print(display_message)\n\n\nclass FilePrinter(Printer):\n def __init__(self, file_path, *args, **kwargs):\n self.file_path = file_path\n super(FilePrinter, self).__init__(*args, **kwargs)\n\n def log(self, display_message):\n with open(self.file_path, 'a') as f:\n f.write(self.name)\n f.write(display_message)\n\n\nclass Calculator:\n\n @staticmethod\n def union(first_list, second_list):\n if isinstance(first_list, Queue) and isinstance(second_list, Queue):\n merged_queue = Queue(max_size=first_list.max_size + second_list.max_size)\n if first_list.size() > 0: # On check si first_list contient bien des éléments\n merged_queue.liste = first_list.liste + second_list.liste\n else:\n merged_queue.liste = second_list.liste\n return merged_queue\n elif isinstance(first_list, Stack) and isinstance(second_list, Stack):\n merged_stack = Stack(max_size=first_list.max_size + second_list.max_size)\n if first_list.size() > 0: # On check si first_list contient bien des éléments\n merged_stack.liste = first_list.liste + second_list.liste\n else:\n merged_stack.liste = second_list.liste\n return merged_stack\n # Test pour voir si first_list et second_list sont des linkedlist mais pas des stacks ni des queues\n elif isinstance(first_list, List) and not (isinstance(first_list, Stack) or isinstance(first_list, Queue)) \\\n and isinstance(second_list, List) and not (\n isinstance(second_list, Stack) or isinstance(second_list, Queue)):\n merged_list = List()\n first_list_copy = first_list.liste.copy()\n second_list_copy = second_list.liste.copy()\n\n while len(first_list_copy) > 0 and len(second_list_copy) > 0:\n if rand.uniform(0, 1) < 0.5:\n merged_list.append(first_list_copy.pop(0))\n else:\n merged_list.append(second_list_copy.pop(0))\n while len(first_list_copy) > 0:\n merged_list.append(first_list_copy.pop(0))\n while len(second_list_copy) > 0:\n merged_list.append(second_list_copy.pop(0))\n return merged_list\n else:\n raise ValueError('The types of both lists are different')\n","sub_path":"TP6/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"644371052","text":"import unittest\n\nimport config\nfrom app import create_app\nfrom app.models import db, Inventory, Item, User, Shop, Discrepancy\n\n\nclass InventoryTestCase(unittest.TestCase):\n\n def setUp(self):\n self.app = create_app(config.TestConfig)\n self.app_context = self.app.app_context()\n self.app_context.push()\n db.create_all()\n # add test user\n self.user = User(username=\"Test\")\n self.user.set_pwd('12345678')\n db.session.add(self.user)\n # add test items\n for i in range(3):\n db.session.add(Item(name=f'Item-{i}'))\n # add test shop\n self.shop = Shop(name='Test-Shop')\n db.session.add(self.shop)\n db.session.commit()\n\n def tearDown(self):\n db.session.remove()\n db.drop_all()\n self.app_context.pop()\n\n def test_basic_inventory(self):\n self.assertIsNone(Inventory.query.first())\n inventory = Inventory(user=self.user, shop=self.shop)\n db.session.add(inventory)\n db.session.commit()\n inventory = Inventory.query.first()\n\n self.assertIsNotNone(inventory)\n self.assertIsNotNone(inventory.created_at)\n self.assertEqual(inventory.user, self.user)\n self.assertEqual(inventory.shop, self.shop)\n\n # add some association objects\n items = Item.query.all()\n for i in range(3):\n inventory.discrepancies.append(Discrepancy(item=items[i], target=3, actual=i))\n db.session.commit()\n\n self.assertEqual(len(inventory.discrepancies), 3)\n self.assertTrue(any([inventory.discrepancies[0].item == x for x in Item.query.all()]))\n\n def test_user_deletion(self):\n # should NOT delete the inventory\n inventory = Inventory(user=self.user, shop=self.shop)\n db.session.add(inventory)\n db.session.commit()\n db.session.delete(self.user)\n db.session.commit()\n inventory = Inventory.query.first()\n self.assertIsNotNone(inventory) # inventory still exists\n self.assertIsNone(inventory.user) # but has no associated user\n\n def test_shop_deletion(self):\n # should delete the inventory\n inventory = Inventory(user=self.user, shop=self.shop)\n db.session.add(inventory)\n db.session.commit()\n db.session.delete(self.shop)\n db.session.commit()\n self.assertIsNone(Inventory.query.first()) # no shop -> no inventory\n\n def test_delete_inventory(self):\n # should delete ALL discrepancies\n inventory = Inventory(user=self.user, shop=self.shop)\n db.session.add(inventory)\n db.session.commit()\n # add some association objects\n items = Item.query.all()\n for i in range(3):\n inventory.discrepancies.append(Discrepancy(item=items[i], target=3, actual=i))\n db.session.commit()\n\n self.assertEqual(len(Discrepancy.query.all()), 3) # there are existing discrepancies\n db.session.delete(inventory)\n db.session.commit()\n # after the associated inventory got deleted they are also gone\n self.assertEqual(len(Discrepancy.query.all()), 0)\n self.assertIsNone(Discrepancy.query.first())\n\n def test_discrepancy(self):\n self.assertIsNone(Inventory.query.first())\n inventory = Inventory(user=self.user, shop=self.shop)\n db.session.add(inventory)\n db.session.commit()\n inventory = Inventory.query.first()\n\n # add some association objects\n items = Item.query.all()\n for i in range(3):\n inventory.discrepancies.append(Discrepancy(item=items[i], target=3, actual=i))\n db.session.commit()\n self.assertEqual(Discrepancy.query.first().inventory, inventory)\n self.assertTrue(any([Discrepancy.query.first().item == x for x in items]))\n\n def test_delete_discrepancy(self):\n # shouldn´t change anything\n self.assertIsNone(Inventory.query.first())\n inventory = Inventory(user=self.user, shop=self.shop)\n db.session.add(inventory)\n db.session.commit()\n inventory = Inventory.query.first()\n\n # add some association objects\n items = Item.query.all()\n for i in range(3):\n inventory.discrepancies.append(Discrepancy(item=items[i], target=3, actual=i))\n db.session.commit()\n\n for d in Discrepancy.query.all():\n db.session.delete(d)\n db.session.commit()\n\n self.assertIsNotNone(Inventory.query.first())\n self.assertEqual(len(inventory.discrepancies), 0)\n\n def test_delete_item(self):\n # should delete discrepancy but not inventory\n # shouldn´t change anything\n self.assertIsNone(Inventory.query.first())\n inventory = Inventory(user=self.user, shop=self.shop)\n db.session.add(inventory)\n db.session.commit()\n inventory = Inventory.query.first()\n\n # add a association object\n item = Item.query.first()\n inventory.discrepancies.append(Discrepancy(item=item, target=3, actual=93))\n db.session.commit()\n\n # remove it again\n db.session.delete(Discrepancy.query.first())\n db.session.commit()\n\n # deletes discrepancy\n self.assertIsNone(Discrepancy.query.first())\n # but inventory remains\n self.assertIsNotNone(Inventory.query.first())\n self.assertEqual(len(Inventory.query.first().discrepancies), 0)\n","sub_path":"tests/test_model_inventory.py","file_name":"test_model_inventory.py","file_ext":"py","file_size_in_byte":5437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"424516917","text":"value = 0\nwhile value <= 10:\n print(value)\n value += 1\n\nstart = 100\nwhile start > 0:\n print(\"Start is {}\".format(start))\n start -= 10\n print(\"Start is now {}\".format(start))\n print()\n\nname = \"\"\nwhile len(name) < 2:\n print(\"Your full name\")\n name = input(\"Enter your name: \")\n\nnumber = 0\nwhile number != 3:\n print(\"Type the number 3.\")\n number = int(input(\">_ \"))\nprint(\"You typed the number 3!\")\nprint(\"Good Job!\")\n\nimport random # This only has to happen once!\nnum = 0\ncounter = 0\nwhile num != 6:\n num = random.randint(1, 100)\n counter += 1\n print(\"Our random number is {}\".format(num))\nprint(\"We got the number 6!\")\nprint(\"It took us {} tries to get the number 6\"\n .format(counter))\n","sub_path":"While Loops.py","file_name":"While Loops.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"473896441","text":"from tests.cases.base import TestAuthorized\nfrom tests.pages.pin import PinDetailsPage\nfrom tests.pages.user_details import UserDetailsPage\n\n\nclass Test(TestAuthorized):\n def setUp(self):\n super().setUp()\n self.page = UserDetailsPage(self.driver, \"testTest\")\n\n def test_subscribe(self):\n self.page.form.subscribe()\n try:\n self.assertTrue(\n self.page.form.check_subscription(), \"You have not subscribed to user\"\n )\n except TimeoutError:\n self.fail(\"Cannot find subscription button!\")\n\n def test_unsubscribe(self):\n self.page.form.unsubscribe()\n try:\n self.assertFalse(\n self.page.form.check_subscription(estimated=False),\n \"You have not unsubscribed from user\",\n )\n except TimeoutError:\n self.fail(\"Cannot find subscription button!\")\n\n def test_open_pin(self):\n name, link = self.page.form.open_pin(0)\n page = PinDetailsPage(self.driver, False)\n real_name = page.form.get_title()\n self.assertEqual(real_name, name, \"Names are different\")\n self.assertEqual(self.driver.current_url, link, \"Wrong page opened\")\n","sub_path":"tests/cases/user_test.py","file_name":"user_test.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"234113705","text":"from os import cpu_count\nfrom typing import Optional\n\nimport psutil\nimport pydantic\nfrom pydantic import Field, PositiveInt\n\nfrom gfw_pixetl import get_module_logger\nfrom gfw_pixetl.models.enums import DstFormat\nfrom gfw_pixetl.settings.models import EnvSettings\n\nLOGGER = get_module_logger(__name__)\n\n\nclass Secret:\n \"\"\"Holds a string value that should not be revealed in tracebacks etc.\n\n You should cast the value to `str` at the point it is required.\n \"\"\"\n\n def __init__(self, value: str):\n self._value = value\n\n def __repr__(self) -> str:\n class_name = self.__class__.__name__\n return f\"{class_name}('**********')\"\n\n def __str__(self) -> str:\n return self._value\n\n\nclass Globals(EnvSettings):\n\n #####################\n # General\n #####################\n\n default_dst_format = DstFormat.geotiff\n\n #####################\n # Resource management\n ######################\n cores: PositiveInt = Field(cpu_count(), description=\"Number of CPU cores available\")\n num_processes: PositiveInt = Field(\n cpu_count(), description=\"Max number of parallel processes to use\"\n )\n max_mem: PositiveInt = Field(\n psutil.virtual_memory()[1] / 1000000,\n description=\"Max memory available to pixETL\",\n )\n divisor: PositiveInt = Field(\n 4,\n description=\"Fraction of memory per worker to use to compute maximum block size.\"\n \"(ie 4 => size = 25% of available memory)\",\n )\n workers: PositiveInt = Field(\n cpu_count(), description=\"Number of workers to use to execute job.\"\n )\n\n ########################\n # PostgreSQL authentication\n ########################\n db_username: Optional[str] = Field(\n None, env=\"PGUSER\", description=\"PostgreSQL user name\"\n )\n db_password: Optional[Secret] = Field(\n None, env=\"PGPASSWORD\", description=\"PostgreSQL password\"\n )\n db_host: Optional[str] = Field(None, env=\"PGHOST\", description=\"PostgreSQL host\")\n db_port: Optional[int] = Field(None, env=\"PGPORT\", description=\"PostgreSQL port\")\n db_name: Optional[str] = Field(\n None, env=\"PGDATABASE\", description=\"PostgreSQL database name\"\n )\n\n ######################\n # AWS configuration\n ######################\n aws_region: str = Field(\"us-east-1\", description=\"AWS region\")\n aws_batch_job_id: Optional[str] = Field(None, description=\"AWS Batch job ID\")\n aws_job_role_arn: Optional[str] = Field(\n None,\n description=\"ARN of the AWS IAM role which runs the batch job on docker host\",\n )\n aws_gcs_key_secret_arn: Optional[str] = Field(\n None, description=\"ARN of AWS Secret which holds GCS key\"\n )\n\n aws_endpoint_url: Optional[str] = Field(\n None, description=\"Endpoint URL for AWS S3 Server (required for Moto)\"\n )\n\n aws_secretsmanager_url: Optional[str] = Field(\n None,\n description=\"Endpoint URL for AWS Secretsmanager Server (required for Moto)\",\n )\n\n @pydantic.validator(\"db_password\", pre=True, always=True)\n def hide_password(cls, v):\n return Secret(v) or None\n\n @pydantic.root_validator()\n def set_processes_workers(cls, values):\n cores = values.get(\"cores\")\n\n # Don't allow specifying more processes than cores\n num_processes = max(min(cores, values.get(\"num_processes\")), 1)\n\n # Don't allow specifying more workers than processes\n workers = max(min(num_processes, values.get(\"workers\")), 1)\n\n values[\"num_processes\"] = num_processes\n values[\"workers\"] = workers\n\n LOGGER.info(f\"Set num_processes to {num_processes}\")\n LOGGER.info(f\"Set workers to {workers}\")\n\n return values\n\n @pydantic.validator(\"max_mem\", pre=True, always=True)\n def set_max_mem(cls, v, *, values, **kwargs):\n max_mem = max(min(psutil.virtual_memory()[1] / 1000000, float(v)), 1)\n LOGGER.info(f\"Set maximum memory to {max_mem} MB\")\n return max_mem\n\n\nGLOBALS = Globals()\n","sub_path":"gfw_pixetl/settings/globals.py","file_name":"globals.py","file_ext":"py","file_size_in_byte":3998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"292695102","text":"import cv2\nimport numpy as np\nimport time\nfrom matplotlib import pyplot as plt\n\n# Função histograma\ndef histograma(img):\n vet = np.zeros((256), dtype=np.uint16)\n img = np.uint8(img)\n for l in range(0, altura):\n for c in range(0, largura):\n vet[img[l,c]] += 1\n plt.plot(vet)\n plt.title('Histograma')\n plt.ylabel('Quantidade de pixels')\n plt.xlabel('Intensidade de cor')\n string = str(int(time.time()))\n print(string)\n plt.savefig('processadas/'+nome+'_histograma_'+string)\n axes = plt.gca()\n axes.set_ylim(0,)\n plt.show()\n\n# Altera a intensidade do pixel, para mais ou para menos\ndef alteraBrilho(img, intensidade):\n nova = np.zeros((altura,largura))\n for l in range(0, altura):\n for c in range(0, largura):\n nova[l,c] = max(min(img[l,c]+intensidade,255),0)\n cv2.imshow('Imagem alterada', np.uint8(nova))\n cv2.imwrite('processadas/'+nome+'_altera_brilho_'+str(intensidade)+'.png', np.uint8(nova))\n cv2.waitKey(0)\n return np.uint8(nova)\n\n# Aplica o filtro de média à imagem\ndef media(img):\n nova = np.zeros((altura,largura))\n for l in range(0, altura):\n for c in range(0, largura):\n soma = 0\n interacoes = 0\n for lm in range (-1,2):\n for cm in range (-1,2):\n if(l+lm>=0 and c+cm>=0 and l+lm= 0 and c + cm >= 0 and l + lm < altura and c + cm < largura):\n m[i] = img[l+lm,c+cm]\n else:\n m[i] = 0\n i += 1\n nova[l,c] = np.median(m)\n cv2.imshow('Imagem - Filtro de média', np.uint8(nova))\n cv2.imwrite('processadas/' + nome + '_mediana.png', np.uint8(nova))\n cv2.waitKey(0)\n return np.uint8(nova)\n\n# Aplica filtros na imagem com o uso de máscaras\ndef mascara(img, tipo):\n nova = np.zeros((altura,largura))\n m = np.zeros((3, 3))\n\n if(tipo==\"sobel\"):\n m[0,0] = 1\n m[0, 1] = 0\n m[0, 2] = -1\n m[1, 0] = 2\n m[1, 1] = 0\n m[1, 2] = -2\n m[2, 0] = 1\n m[2, 1] = 0\n m[2, 2] = -1\n elif (tipo == \"prewitt\"):\n m[0, 0] = -1\n m[0, 1] = 0\n m[0, 2] = 1\n m[1, 0] = -1\n m[1, 1] = 0\n m[1, 2] = 1\n m[2, 0] = -1\n m[2, 1] = 0\n m[2, 2] = 1\n elif (tipo == \"laplaciano\"):\n m[0, 0] = 0\n m[0, 1] = -1\n m[0, 2] = 0\n m[1, 0] = -1\n m[1, 1] = 4\n m[1, 2] = -1\n m[2, 0] = 0\n m[2, 1] = -1\n m[2, 2] = 0\n elif (tipo == \"passa-alta\"):\n m[0, 0] = -1\n m[0, 1] = -1\n m[0, 2] = -1\n m[1, 0] = -1\n m[1, 1] = 8\n m[1, 2] = -1\n m[2, 0] = -1\n m[2, 1] = -1\n m[2, 2] = -1\n\n for l in range(0, altura):\n for c in range(0, largura):\n soma = 0\n for lm in range (-1,2):\n for cm in range (-1,2):\n if (l + lm >= 0 and c + cm >= 0 and l + lm < altura and c + cm < largura):\n soma = soma + (int(m[lm+1,cm+1]) * img[l+lm,c+cm])\n else:\n soma = soma + (int(m[lm+1,cm+1]) * img[l,c])\n nova[l,c] = max(min(soma, 255), 0)\n cv2.imshow('Imagem - Filtro mask', np.uint8(nova))\n cv2.imwrite('processadas/' + nome + '_mascara_'+tipo+'.png', nova)\n cv2.waitKey(0)\n return np.uint8(nova)\n\n\n#Definições de arquivo\nnome = 'passaro'\nimagem = cv2.imread('imagens/'+nome+'.jpg')\ncv2.imwrite('processadas/' + nome + '_original.png', imagem)\nimagem = cv2.cvtColor(imagem, cv2.COLOR_BGR2GRAY)\ncv2.imwrite('processadas/' + nome + '_cinza.png', imagem)\n#cv2.imshow('Imagem original', imagem)\n#cv2.waitKey(0)\n\n#Informações de tamanho da imagem\naltura = imagem.shape[0]\nlargura = imagem.shape[1]\n\nhistograma(imagem)\nhistograma(mascara(imagem,\"passa-alta\"))\nhistograma(mascara(imagem,\"laplaciano\"))\nhistograma(mascara(imagem,\"sobel\"))\n\n#alteraBrilho(imagem,-90)\n#alteraBrilho(imagem,90)\n#media(imagem)\n#mediana(imagem)\n#mascara(imagem,\"sobel\")\n","sub_path":"atividades.py","file_name":"atividades.py","file_ext":"py","file_size_in_byte":4719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"106906326","text":"# -*- coding: utf-8 -*-\n\"\"\"\nTencentBlueKing is pleased to support the open source community by making 蓝鲸智云-用户管理(Bk-User) available.\nCopyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.\nLicensed under the MIT License (the \"License\"); you may not use this file except in compliance with the License.\nYou may obtain a copy of the License at http://opensource.org/licenses/MIT\nUnless required by applicable law or agreed to in writing, software distributed under the License is distributed on\nan \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the\nspecific language governing permissions and limitations under the License.\n\"\"\"\nfrom django.conf.urls import url\n\nfrom . import views\n\nPVAR_CATEGORIES_ID = r\"(?P[0-9]+)\"\nPVAR_ANOTHER_CATEGORIES_ID = r\"(?P[a-z0-9-]+)\"\n\n\nurlpatterns = [\n ##############\n # categories #\n ##############\n url(\n r\"^api/v2/categories_metas/$\",\n views.CategoriesViewSet.as_view(\n {\n \"get\": \"list_metas\",\n }\n ),\n name=\"categories.metas\",\n ),\n url(\n r\"^api/v2/categories/$\",\n views.CategoriesViewSet.as_view(\n {\n \"get\": \"list\",\n \"post\": \"create\",\n }\n ),\n name=\"categories\",\n ),\n url(\n r\"^api/v2/categories/default/$\",\n views.CategoriesViewSet.as_view(\n {\n \"get\": \"get_default\",\n }\n ),\n name=\"categories.default\",\n ),\n url(\n r\"^api/v2/categories/%s/$\" % PVAR_CATEGORIES_ID,\n views.CategoriesViewSet.as_view(\n {\n \"patch\": \"update\",\n \"delete\": \"delete\",\n }\n ),\n name=\"categories.actions\",\n ),\n url(\n r\"^api/v2/categories/%s/switch_order/%s/$\" % (PVAR_CATEGORIES_ID, PVAR_ANOTHER_CATEGORIES_ID),\n views.CategoriesViewSet.as_view(\n {\n \"patch\": \"switch_order\",\n }\n ),\n name=\"categories.switch_order\",\n ),\n url(\n r\"^api/v2/categories/%s/sync/$\" % PVAR_CATEGORIES_ID,\n views.CategoriesSyncViewSet.as_view(\n {\n \"post\": \"sync\",\n }\n ),\n name=\"categories.sync\",\n ),\n url(\n r\"^api/v2/categories/%s/activate/$\" % PVAR_CATEGORIES_ID,\n views.CategoriesSyncViewSet.as_view(\n {\n \"post\": \"activate\",\n }\n ),\n name=\"categories.activate\",\n ),\n url(\n r\"^api/v2/categories/%s/test_connection/$\" % PVAR_CATEGORIES_ID,\n views.CategoriesSyncViewSet.as_view(\n {\n \"post\": \"test_connection\",\n }\n ),\n name=\"categories.test_connection\",\n ),\n url(\n r\"^api/v2/categories/%s/test_fetch_data/$\" % PVAR_CATEGORIES_ID,\n views.CategoriesSyncViewSet.as_view(\n {\n \"post\": \"test_fetch_data\",\n }\n ),\n name=\"categories.test_fetch_data\",\n ),\n url(\n r\"^api/v2/categories/%s/export/$\" % PVAR_CATEGORIES_ID,\n views.CategoriesExportViewSet.as_view(\n {\n \"get\": \"export\",\n }\n ),\n name=\"categories.export\",\n ),\n url(\n r\"^api/v2/categories/%s/export_template/$\" % PVAR_CATEGORIES_ID,\n views.CategoriesExportViewSet.as_view(\n {\n \"get\": \"export_template\",\n }\n ),\n name=\"categories.export_template\",\n ),\n]\n","sub_path":"src/saas/bkuser_shell/categories/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"15866226","text":"\n\n#calss header\nclass _CHIGGER():\n\tdef __init__(self,): \n\t\tself.name = \"CHIGGER\"\n\t\tself.definitions = [u\"a type of flea (= very small jumping insect) that lays eggs beneath an animal's or person's skin\", u\"a type of mite (= very small animal similar to a spider) that lays eggs under an animal's or person's skin causing small red bumps that are very itchy (= you want to scratch them)\"]\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/_chigger.py","file_name":"_chigger.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"521283825","text":"#!/usr/bin/env python\n# (C) 2017 OpenEye Scientific Software Inc. All rights reserved.\n#\n# TERMS FOR USE OF SAMPLE CODE The software below (\"Sample Code\") is\n# provided to current licensees or subscribers of OpenEye products or\n# SaaS offerings (each a \"Customer\").\n# Customer is hereby permitted to use, copy, and modify the Sample Code,\n# subject to these terms. OpenEye claims no rights to Customer's\n# modifications. Modification of Sample Code is at Customer's sole and\n# exclusive risk. Sample Code may require Customer to have a then\n# current license or subscription to the applicable OpenEye offering.\n# THE SAMPLE CODE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT\n# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall OpenEye be\n# liable for any damages or liability in connection with the Sample Code\n# or its use.\n\n#############################################################################\n# Modifies the SD data of a set of input molecules by clearing all tags,\n# defining which tags to keep or defining which tags to remove\n#############################################################################\nimport sys\nfrom openeye import oechem\n\n\ndef ClearProps(ifs, ofs):\n for mol in ifs.GetOEGraphMols():\n oechem.OEClearSDData(mol)\n oechem.OEWriteMolecule(ofs, mol)\n\n\ndef KeepProps(proplist, ifs, ofs):\n for mol in ifs.GetOEGraphMols():\n for dp in oechem.OEGetSDDataPairs(mol):\n if dp.GetTag() not in proplist:\n oechem.OEDeleteSDData(mol, dp.GetTag())\n oechem.OEWriteMolecule(ofs, mol)\n\n\ndef RemoveProps(proplist, ifs, ofs):\n for mol in ifs.GetOEGraphMols():\n for tag in proplist:\n oechem.OEDeleteSDData(mol, tag)\n oechem.OEWriteMolecule(ofs, mol)\n\n\ndef ModProps(itf, ifs, ofs):\n proplist = []\n if itf.HasString(\"-keep\"):\n for prop in itf.GetStringList(\"-keep\"):\n proplist.append(prop)\n KeepProps(proplist, ifs, ofs)\n elif itf.HasString(\"-remove\"):\n for prop in itf.GetStringList(\"-remove\"):\n proplist.append(prop)\n RemoveProps(proplist, ifs, ofs)\n elif itf.GetBool(\"-clearAll\"):\n ClearProps(ifs, ofs)\n\n\ndef main(argv=[__name__]):\n itf = oechem.OEInterface(InterfaceData, argv)\n\n haskeep = itf.HasString(\"-keep\")\n hasremove = itf.HasString(\"-remove\")\n hasclear = itf.GetBool(\"-clearAll\")\n\n numoption = 0\n for hasoption in [haskeep, hasremove, hasclear]:\n if hasoption:\n numoption += 1\n\n if numoption != 1:\n oechem.OEThrow.Usage(\"Need to pick one from -keep, -remove, or -clearAll\")\n\n ifs = oechem.oemolistream()\n if not ifs.open(itf.GetString(\"-i\")):\n oechem.OEThrow.Fatal(\"Unable to open %s for reading\" % itf.GetString(\"-i\"))\n if not oechem.OEIsSDDataFormat(ifs.GetFormat()):\n oechem.OEThrow.Fatal(\"Only works for input file formats that support SD data (sdf,oeb,csv)\")\n\n ofs = oechem.oemolostream()\n if not ofs.open(itf.GetString(\"-o\")):\n oechem.OEThrow.Fatal(\"Unable to open %s for writing\" % itf.GetString(\"-o\"))\n if not oechem.OEIsSDDataFormat(ofs.GetFormat()):\n oechem.OEThrow.Fatal(\"Only works for output file formats that support SD data \\\n (sdf,oeb,csv)\")\n\n ModProps(itf, ifs, ofs)\n\n\nInterfaceData = \"\"\"\n!BRIEF [-remove] [-keep] [-clearAll] -i -o \n!PARAMETER -i\n !ALIAS -in\n !TYPE string\n !REQUIRED true\n !BRIEF Input file name\n !END\n!PARAMETER -o\n !ALIAS -out\n !TYPE string\n !REQUIRED true\n !BRIEF Output file name\n !END\n!PARAMETER -keep\n !ALIAS -k\n !TYPE string\n !LIST true\n !BRIEF SD tags to be kept\n !END\n!PARAMETER -remove\n !ALIAS -r\n !TYPE string\n !LIST true\n !BRIEF SD tags to be removed\n !END\n!PARAMETER -clearAll\n !ALIAS -c\n !TYPE bool\n !DEFAULT false\n !BRIEF Removes all SD tags\n !END\n!END\n\"\"\"\n\n\nif __name__ == \"__main__\":\n sys.exit(main(sys.argv))\n","sub_path":"venv/Scripts/sdfmodprops.py","file_name":"sdfmodprops.py","file_ext":"py","file_size_in_byte":4088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"93467514","text":"import io\nimport os\n\n# Imports the Google Cloud client library\nfrom google.cloud import speech\n\n# Instantiates a client\nspeech_client = speech.Client()\n\n# The name of the audio file to transcribe\nfile_name = os.path.join(\n\tos.path.dirname(__file__),\n\t'resources',\n\t'obbatriple.flac')\n\n# Loads the audio into memory\nwith io.open(file_name, 'rb') as audio_file:\n\tcontent = audio_file.read()\n\taudio_sample = speech_client.sample(\n\t\tcontent,\n\t\tsource_uri=None,\n\t\tencoding='FLAC',\n\t\tsample_rate=48000)\n\n# Detects speech in the audio file\nalternatives = speech_client.speech_api.sync_recognize(audio_sample)\n\nfor alternative in alternatives:\n\tprint('Transcript: {}'.format(alternative.transcript))\n","sub_path":"tests-google-cloud-sdk/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"345524166","text":"import json\nimport pandas as pd\nfrom gensim.models import Word2Vec\n\njson_file = 'intents.json'\nwith open('intents.json','r') as f:\n\tdata = json.load(f)\n\ndf = pd.DataFrame(data)\nprint(df)\ndf['patterns'] = df['patterns'].apply(', '.join) \nprint(df)\n\nfrom nltk.corpus import stopwords\nfrom textblob import Word\nimport string\nstop = stopwords.words('english')\ndf['patterns'] = df['patterns'].apply(lambda x:' '.join(x.lower() for x in x.split())) # lower every word\ndf['patterns']= df['patterns'].apply(lambda x: ' '.join(x for x in x.split() if x not in string.punctuation)) # exclude punctuation\ndf['patterns']= df['patterns'].str.replace('[^\\w\\s]','') # replace non-word\ndf['patterns']= df['patterns'].apply(lambda x: ' '.join(x for x in x.split() if not x.isdigit())) # exclude numbers\ndf['patterns'] = df['patterns'].apply(lambda x:' '.join(x for x in x.split() if not x in stop)) # exclude stopwords\ndf['patterns'] = df['patterns'].apply(lambda x: \" \".join([Word(word).lemmatize() for word in x.split()])) # textblob is another library like nltk\n\nbigger_list=[]\nfor i in df['patterns']:\n li = list(i.split(\" \"))\n bigger_list.append(li)\t\nmodel = Word2Vec(bigger_list,min_count=1,size=300,workers=4)\nprint(\"Data format for the overall list:\",bigger_list)\n#custom data is fed to machine for further processing\nmodel = Word2Vec(bigger_list, min_count=1,size=300,workers=4)\n\nmodel.save(\"model.bin\")\ndel model\nmodel = Word2Vec.load('model.bin')\nprint(model)\n\n# Most Similar words checking\nsimilar_words = model.most_similar('thanks')\t\nprint(similar_words)\n\n# Does not match word from words supplied\ndissimlar_words = model.doesnt_match('See you later, thanks for visiting'.split())\nprint(dissimlar_words)\n\n# Finding the similarity between two words\nsimilarity_two_words = model.similarity('please','see')\nprint(\"Please provide the similarity between these two words:\")\nprint(similarity_two_words)\n\nsimilar = model.similar_by_word('kind')\nprint(similar)","sub_path":"complex_word2vec.py","file_name":"complex_word2vec.py","file_ext":"py","file_size_in_byte":1955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"613389506","text":"GET_MEMBERS_FIELDS = {\n \"id\": {},\n \"username\": {},\n \"email\": {},\n \"member_purchases\": {\n \"id\": {},\n \"purchase_date\": {},\n \"amount\": {},\n \"approved\": {}\n },\n \"member_payments\": {\n \"id\": {},\n \"payment_date\": {},\n \"recipient\": {},\n \"amount\": {},\n \"confirmed\": {}\n },\n \"owed_amounts\": {\n \"id\": {},\n \"creditor_id\": {},\n \"living_group_id\": {},\n \"amount\": {}\n },\n \"owed_monthly_expenses\": {\n \"id\": {},\n \"living_group\": {},\n \"amount\": {}\n }\n}\n\nUPDATE_MEMBER_FIELDS = {\n \"id\": {},\n \"username\": {},\n \"email\": {},\n}\n\nGET_LIVING_GROUPS_FIELDS = {\n \"id\": {},\n \"name\": {},\n \"admin_id\": {},\n \"members\": {\n \"id\": {},\n \"username\": {},\n \"email\": {},\n \"member_purchases\": {\n \"id\": {},\n \"purchase_date\": {},\n \"amount\": {},\n \"approved\": {},\n \"living_group\": {}\n },\n \"member_payments\": {\n \"id\": {},\n \"payment_date\": {},\n \"recipient\": {},\n \"living_group\": {},\n \"amount\": {},\n \"confirmed\": {}\n },\n \"owed_amounts\": {\n \"id\": {},\n \"creditor_id\": {},\n \"living_group_id\": {},\n \"amount\": {}\n },\n \"owed_monthly_expenses\": {\n \"id\": {},\n \"living_group\": {},\n \"amount\": {}\n }\n },\n \"monthly_shared_expenses\": {\n \"id\": {},\n \"name\": {},\n \"start_date\": {},\n \"end_date\": {},\n \"amount\": {}\n },\n \"shopping_categories\": {\n \"id\": {},\n \"name\": {}\n },\n \"shopping_lists\": {\n \"id\": {},\n \"name\": {}\n }\n}\n\nUPDATE_LIVING_GROUP_FIELDS = {\n \"id\": {},\n \"name\": {},\n \"admin_id\": {}\n}\n\nCREATE_LIVING_GROUP_FIELDS = {\n \"id\": {},\n \"name\": {},\n \"admin_id\": {},\n \"members\": {\n \"id\": {},\n \"username\": {},\n \"email\": {},\n \"member_purchases\": {\n \"id\": {},\n \"purchase_date\": {},\n \"amount\": {},\n \"approved\": {},\n \"living_group\": {}\n },\n \"member_payments\": {\n \"id\": {},\n \"payment_date\": {},\n \"recipient\": {},\n \"living_group\": {},\n \"amount\": {},\n \"confirmed\": {}\n },\n \"owed_amounts\": {\n \"id\": {},\n \"creditor_id\": {},\n \"living_group_id\": {},\n \"amount\": {}\n },\n \"owed_monthly_expenses\": {\n \"id\": {},\n \"living_group\": {},\n \"amount\": {}\n }\n },\n \"monthly_shared_expenses\": {},\n \"shopping_categories\": {},\n \"shopping_lists\": {}\n}\n\nGET_MONTHLY_SHARED_EXPENSES_FIELDS = {\n \"id\": {},\n \"name\": {},\n \"start_date\": {},\n \"end_date\": {},\n \"amount\": {}\n}\n\nGET_SHOPPING_CATEGORIES_FIELDS = {\n \"id\": {},\n \"name\": {}\n}\n\nGET_MEMBER_PURCHASES_FIELDS = {\n \"id\": {},\n \"purchase_date\": {},\n \"amount\": {},\n \"approved\": {},\n \"living_group\": {}\n}\n\nGET_MEMBER_PAYMENTS_FIELDS = {\n \"id\": {},\n \"payment_date\": {},\n \"recipient\": {},\n \"living_group\": {},\n \"amount\": {},\n \"confirmed\": {}\n}\n\nGET_SHOPPING_LISTS_FIELDS = {\n \"id\": {},\n \"name\": {},\n \"added_date\": {},\n \"list_items\": {\n \"id\": {},\n \"name\": {},\n \"added_date\": {},\n \"member_purchase\": {},\n \"gotten\": {}\n }\n}\n\nUPDATE_SHOPPING_LIST_FIELDS = {\n \"id\": {},\n \"name\": {}\n}\n\nLIST_ITEM_FIELDS = {\n \"id\": {},\n \"name\": {},\n \"added_date\": {},\n \"member_purchase\": {},\n \"gotten\": {}\n}\n\nLOGS_FIELDS = {\n \"id\": {},\n \"date\": {},\n \"log\": {}\n}\n\nNOT_ADMIN = {\n \"code\": 401,\n \"status\": \"Failure\",\n \"message\": \"Cannot perform this action, not admin member.\"\n}\n\nFAILED_ACCESS = {\n \"code\": 401,\n \"status\": \"Failure\",\n \"message\": \"Cannot get/change what does not exist/belong to you.\"\n}\n","sub_path":"engine/api/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":4007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"131856686","text":"from __future__ import print_function\nimport tensorflow as tf\n\nimport utility as util\nfrom model import config_model\n\nflags = tf.app.flags\nflags.DEFINE_string(\"ps_hosts\",\"192.168.10.200:2222\", \"Comma-separated list of hostname:port pairs\")\nflags.DEFINE_string(\"worker_hosts\", \"192.168.10.155:2222, 192.168.10.181:2222\", \"Comma-separated list of hostname:port pairs\")\nflags.DEFINE_string(\"job_name\", None, \"Job name: worker or ps\")\nflags.DEFINE_integer(\"task_index\", None, \"Worker task index, should be >= 0.\")\nflags.DEFINE_string('train_data', './data/train_32x32.mat', 'File of input data to train')\nflags.DEFINE_integer('iteration_steps', 10000, 'Number of global training steps to perform')\nflags.DEFINE_integer('display_delay', 50, 'Delay of global training steps to print')\nflags.DEFINE_integer('batch_size', 64, 'Size of samples for one iteration')\nflags.DEFINE_string('log_dir', None, 'Directory of log')\nFLAGS = flags.FLAGS\n\ndef main(argv):\n # check flags\n if FLAGS.job_name is None or (FLAGS.job_name != \"ps\" and FLAGS.job_name != \"worker\"):\n raise ValueError(\"Must specify an explicit `job_name`, one of 'ps' and 'worker'\")\n if FLAGS.task_index is None or FLAGS.task_index < 0:\n raise ValueError(\"Must specify an explicit `task_index`\")\n print(\"job name = %s\" % FLAGS.job_name)\n print(\"task index = %d\" % FLAGS.task_index)\n\n # construct the cluster\n ps_spec = map(lambda str: str.strip(), FLAGS.ps_hosts.split(\",\"))\n worker_spec = map(lambda str: str.strip(), FLAGS.worker_hosts.split(\",\"))\n cluster = tf.train.ClusterSpec({ \"ps\": ps_spec, \"worker\": worker_spec})\n\n # server\n server = tf.train.Server(cluster, job_name=FLAGS.job_name, task_index=FLAGS.task_index)\n\n # ps\n if FLAGS.job_name == \"ps\":\n server.join()\n else:\n print(\"Loading data from\", FLAGS.train_data)\n samples, labels = util.load(FLAGS.train_data)\n print(\"The shape of train samples:\", samples.shape)\n print(\"The shape of train labels:\", labels.shape)\n dnn = config_model(input_samples_shape=(FLAGS.batch_size, samples.shape[1], samples.shape[2], samples.shape[3]), input_labels_shape=(FLAGS.batch_size, labels.shape[1]))\n dnn.distributed_train(samples, labels, cluster, server, FLAGS.task_index, batch_size=FLAGS.batch_size, iteration_steps=FLAGS.iteration_steps, display_delay=FLAGS.display_delay, sum_dir=FLAGS.log_dir)\n\nif __name__ == '__main__':\n tf.app.run()","sub_path":"svhn/distributed_train.py","file_name":"distributed_train.py","file_ext":"py","file_size_in_byte":2448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"207131392","text":"from styx_msgs.msg import TrafficLight\nimport numpy as np\nimport cv2\nimport tensorflow as tf\nimport rospy\nimport traceback\nimport json\nimport time\nimport os\nimport re\n\ndirname = os.path.dirname(__file__)\n\nroot_path = re.findall('^/home/.*Capstone/', dirname)[0]\n\nGRAPH_FILE = os.path.join(root_path, 'data/graphs/frozen_inference_graph.pb')\n\n\nBOXES_SCORE_MIN = 0.5 # Minimum passing score for detection\n\n'''\ndef log(arg):\n #writes log information to debug file\n with open('logfile.txt','a') as f:\n f.write(arg+'\\n')\n'''\n\n\ndef load_graph(graph_file):\n # Loads a frozen inference graph\n graph = tf.Graph()\n with graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(graph_file, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\n return graph\n\n# ----------FUNCTIONS FOR CLASSIFICATION----------\n\n\ndef draw_boxes(img, bboxes, color=(0, 0, 255), thick=3):\n # Draws bounding boxes\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(imcopy, (bbox[1], bbox[0]), (bbox[3], bbox[2]), color, thick)\n # Return the image copy with boxes drawn\n return imcopy\n\n\ndef TLDetection(image, sess):\n\n image_np = np.expand_dims(np.asarray(image, dtype = np.uint8), 0)\n boxes, scores, classes = sess.run([detection_boxes, detection_scores, detection_classes], feed_dict = {image_tensor: image_np})\n\n boxes = np.squeeze(boxes)\n scores = np.squeeze(scores)\n classes = np.squeeze(classes)\n\n return boxes, scores, classes\n\n\ndef TLBoxes(prob, boxes, scores, classes):\n # filter boxes under minimum probability 'prob'\n # COCO class index for TrafficLight is '10'\n n = len(boxes)\n idxs = []\n # target = {1, 2, 3}\n for i in range(n):\n if scores[i] >= prob:\n # if scores[i] >= prob and classes[i] in target:\n idxs.append(i)\n\n filtered_boxes = boxes[idxs, ...]\n filtered_scores = scores[idxs, ...]\n filtered_classes = classes[idxs, ...]\n # print(filtered_classes)\n # print()\n return filtered_boxes, filtered_scores, filtered_classes\n\n\ndef TLResizeBoxes(boxes, image_height, image_width):\n # Resize boxes from original values (0:1) to image size\n box_coords = np.zeros_like(boxes)\n box_coords[:, 0] = boxes[:, 0] * image_height\n box_coords[:, 1] = boxes[:, 1] * image_width\n box_coords[:, 2] = boxes[:, 2] * image_height\n box_coords[:, 3] = boxes[:, 3] * image_width\n\n return box_coords\n\n\ndef TLTrim(image, box_coordinates):\n # return trimmed images containing all traffic light signals ahead: from\n # zero (no traffic lights) to whatever\n images = []\n for box in box_coordinates:\n x = int(np.round(box[1]))\n y = int(np.round(box[0]))\n w = int(np.round(box[3] - box[1]))\n h = int(np.round(box[2] - box[0]))\n trimmed_image = image[y:y + h, x:x + w]\n\n # return trimmed_image\n # cv2.imwrite('/home/gabymoynahan/CarND-Capstone/data/processed_images/trimmed_{}.png'.format(time.time()),trimmed_image)\n images.append(trimmed_image)\n\n return images\n\n\ndef TLImage_Pro(image):\n # Image processing using openCV\n image_hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n # cv2.imwrite('/home/gabymoynahan/CarND-Capstone/data/processed_images/HSV_{}.png'.format(time.time()),image_hsv)\n lower_red = np.array([0, 50, 50])\n upper_red = np.array([10, 255, 255])\n red1 = cv2.inRange(image_hsv, lower_red, upper_red)\n\n lower_red = np.array([170, 50, 50])\n upper_red = np.array([180, 255, 255])\n red2 = cv2.inRange(image_hsv, lower_red, upper_red)\n converted_img = cv2.addWeighted(red1, 1.0, red2, 1.0, 0.0)\n # cv2.imwrite('/home/gabymoynahan/CarND-Capstone/data/processed_images/converted_{}.png'.format(time.time()),converted_img)\n blur_img = cv2.GaussianBlur(converted_img, (15, 15), 0)\n\n circles = cv2.HoughCircles(blur_img, cv2.HOUGH_GRADIENT, 0.5, 41, param1=70,\n param2=30, minRadius=5, maxRadius=120)\n # cv2.imwrite('/home/gabymoynahan/CarND-Capstone/data/processed_images/circles_{}.png'.format(time.time()),circles)\n return circles\n\n\n'''\nwith open('logfile.txt','wb') as f:\n #creates logfile from scratch\n f.write('new log file \\n')\n'''\n\n\ndetection_graph = load_graph(GRAPH_FILE)\n\nimage_tensor = detection_graph.get_tensor_by_name('image_tensor:0')\ndetection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')\ndetection_scores = detection_graph.get_tensor_by_name('detection_scores:0')\ndetection_classes = detection_graph.get_tensor_by_name('detection_classes:0')\n\nsess = tf.Session(graph=detection_graph)\n\n\nclass TLClassifier(object):\n def __init__(self):\n print(\"Classifier: initialized\")\n\n def get_classification(self, image, work_mode):\n\n if work_mode == \"simulator\":\n img_circles = TLImage_Pro(image)\n if img_circles is not None:\n return TrafficLight.RED\n\n else:\n return TrafficLight.UNKNOWN\n\n # SSD with Image Processing\n elif work_mode == \"site\":\n\n # Blur the image so it seems more realistic and the classificator performs better\n gbeq_image = cv2.GaussianBlur(image, (5, 5), 0)\n boxes, scores, classes = TLDetection(gbeq_image, sess)\n # log('CAMERA IMAGE PROCESSED, {} boxes detected'.format(len(boxes)))\n boxes, scores, classes = TLBoxes(BOXES_SCORE_MIN, boxes, scores, classes)\n\n image_height = image.shape[0]\n image_width = image.shape[1]\n box_coordinates = TLResizeBoxes(boxes, image_height, image_width)\n # trimmed_lights = TLTrim(image, box_coordinates)\n\n if len(boxes) != 0:\n print(\"found boxes with prob > 0.5: \", boxes)\n most_common = np.argmax(np.bincount(classes))\n\n if most_common == 1:\n print(\"Red!\")\n return TrafficLight.RED\n\n elif most_common == 2:\n print(\"Yellow\")\n return TrafficLight.YELLOW\n elif most_common == 3:\n print(\"Green\")\n return TrafficLight.GREEN\n else:\n print(\"Unknown\")\n return TrafficLight.UNKNOWN\n else:\n return TrafficLight.UNKNOWN\n\n else:\n print(\"wrong working mode, the model only works with simulator or site\")\n return None\n","sub_path":"ros/src/tl_detector/light_classification/tl_classifier.py","file_name":"tl_classifier.py","file_ext":"py","file_size_in_byte":6723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"453013422","text":"from pathlib import Path\nimport pandas as pd\nimport us\nimport download\nimport geopandas as gpd\nimport zipfile\n\n# STEP 0\n# Download data manually from American Fact Finder\n# Go to Advanced Search\n# Geography: Block 100, Topic: Total Population, Table : P12 - SEX BY AGE\n# Save each batch into format: census_data/SF2010_zips/SF2010_{state_abbr}_{batch_num}\n\nCENSUS_DATA_PATH = Path('census_data')\nif not CENSUS_DATA_PATH.exists(): CENSUS_DATA_PATH.mkdir()\n\n\ndef get_us_county_shapefiles():\n filepath = CENSUS_DATA_PATH / 'tl_2018_us_county' / 'tl_2018_us_county.shp'\n if not filepath.exists():\n # download from internet\n shape_link = 'https://www2.census.gov/geo/tiger/TIGER2018/COUNTY/'\\\n +'tl_2018_us_county.zip'\n zipped = download.download_file(shape_link, \"US Counties\")\n with zipfile.ZipFile(zipped) as z:\n z.extractall(filepath.parent)\n gdf = gpd.read_file('census_data/tl_2018_us_county/tl_2018_us_county.shp')\n return gdf\n\n\ndef are_all_counties_included(sfs, gdf):\n sfs['COUNTYFP'] = sfs['GEO.id2'].apply(lambda x: x[:5])\n state_counties = gdf.loc[gdf.STATEFP == state_fip, 'GEOID']\n result = True\n if not state_counties.isin(sfs.COUNTYFP).all():\n print(\n f'{state_abbr} dont have population count for all of its counties!'\n )\n notin = state_counties[~state_counties.isin(sfs.COUNTYFP)]\n notinstr = ', '.join(notin)\n print(f'Counties missing in {state_abbr}: {notinstr}')\n result = False\n sfs.drop('COUNTYFP', axis=1, inplace=True)\n return result\n\n\n# STEP 1\n# Run this loop\nSHAPEFILE_OUTPATH = str(CENSUS_DATA_PATH / 'census_blocks_shapefiles')\n# Shape file county level\ngdf = get_us_county_shapefiles()\n# Summary files manually selected and downloaded from American Fact Finder\nSF2010_DOWNLOADED_PATH = CENSUS_DATA_PATH / 'SF2010_zips'\nSF2010_DOWNLOADED_FILENAME = 'DEC_10_SF1_P12_with_ann.csv'\nSF2010_OUTPATH = CENSUS_DATA_PATH / 'SF2010'\n# One iteration for each state\nstate_abbrs = ['NH', 'NJ', 'CT', 'RI', 'ME', 'VT']\nfor state_abbr in state_abbrs:\n\n state_fip = us.states.lookup(state_abbr).fips\n\n # Download shapefile for this state, block level:\n shape_link = 'https://www2.census.gov/geo/tiger/TIGER2018/TABBLOCK/'\\\n + f'tl_2018_{state_fip}_tabblock10.zip'\n print(shape_link)\n zipped = download.download_file(shape_link, state_abbr)\n with zipfile.ZipFile(zipped) as z:\n z.extractall(SHAPEFILE_OUTPATH)\n\n # 2 diff name format depends on which state so just get both\n sfpaths = [SF2010_DOWNLOADED_PATH.glob(f'{state_abbr}_download_?')]\n sfpaths += [SF2010_DOWNLOADED_PATH.glob(f'SF2010_{state_abbr}_?')]\n\n dflist = []\n for i, sfp in enumerate(sfpaths):\n if i > 0:\n dflist.append(\n pd.read_csv(sfp / SF2010_DOWNLOADED_FILENAME,\n dtype=str,\n skiprows=[1]))\n else:\n dflist.append(\n pd.read_csv(sfp / SF2010_DOWNLOADED_FILENAME, dtype=str))\n sfs = pd.concat(dflist, ignore_index=True).drop_duplicates(\n ) # incase a county is included twice\n\n # check to make sure all counties are included in analysis\n checkresult = are_all_counties_included(sfs, gdf)\n if checkresult:\n sfs.to_csv(SF2010_OUTPATH /\n f'{state_abbr}_blocks_from_all_counties.csv',\n index=False)\n","sub_path":"curate_census_data.py","file_name":"curate_census_data.py","file_ext":"py","file_size_in_byte":3427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"403548292","text":"import glob\nimport pandas as pd\nfrom dask import delayed\n\n\ndef counts_by_origin():\n frames = []\n # For each file\n for f in sorted(glob.glob('data/*.csv')):\n # Load the dataframe\n df = delayed(pd.read_csv)(f,\n parse_dates={'Date': [0, 1, 2]},\n infer_datetime_format=True)\n\n # Store in list of frames\n frames.append(df)\n\n # concatenate all the frames together\n df = delayed(pd.concat)(frames)\n\n # Resample by month\n by_month = (df.resample('MS', on='Date')\n .Origin.value_counts()\n .unstack())\n\n # Resample by year\n by_year = (df.resample('AS', on='Date')\n .Origin.value_counts()\n .unstack())\n\n return by_month, by_year\n","sub_path":"profile_and_debug_dask/rev2.py","file_name":"rev2.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"310689491","text":"#!/usr/bin/env python\n#-*- coding:utf-8 -*-\n\nimport pygame\nfrom pygame.locals import *\nimport random\nimport os\n\nclass PuyoGame(object):\n MAX_COLOMN = 13\n MAX_RAW = 6\n MAX_COLORS = 5\n\n def __init__(self):\n self.GameField = [[0 for i in xrange(self.MAX_RAW)] for j in xrange(self.MAX_COLOMN)]\n self.mainPuyo = {\"x\":self.MAX_RAW/2-1 ,\"y\":0 ,\"color\":random.randint(1 ,self.MAX_COLORS)}\n self.subPuyo = {\"x\":self.MAX_RAW/2 ,\"y\":0 ,\"color\":random.randint(1 ,self.MAX_COLORS)}\n self.onPuyo = 1 #onPuyo parameter mods meens; 0:top ,1:right ,2:bellow ,3:left\n self.chaining = False\n\n def move(self ,dx):\n \"\"\"\n move main and sub Puyos to dx\n if it isn't moveable area,return false\n \"\"\"\n if self.mainPuyo == None:\n return False\n if self.is_moveable(self.mainPuyo[\"x\"]+dx ,self.mainPuyo[\"y\"]) and \\\n self.is_moveable(self.subPuyo[\"x\"]+dx ,self.subPuyo[\"y\"]):\n self.mainPuyo[\"x\"] += dx\n self.subPuyo[\"x\"] += dx\n return True\n else:\n return False\n\n\n def turn(self ,left=False):\n \"\"\"\n turn Puyo couple;change subPuyo possision\n if left arg is True ,turnig left\n default setting is turnig right\n \"\"\"\n if self.mainPuyo == None:\n return False\n if self.onPuyo%4 == 0:\n if left:\n if self.is_moveable(self.mainPuyo[\"x\"]-1 ,self.mainPuyo[\"y\"]):\n self.subPuyo[\"x\"] = self.mainPuyo[\"x\"]-1\n self.subPuyo[\"y\"] = self.mainPuyo[\"y\"]\n self.onPuyo -= 1\n return True\n elif self.is_moveable(self.mainPuyo[\"x\"]+1 ,self.mainPuyo[\"y\"]):\n self.subPuyo[\"x\"] = self.mainPuyo[\"x\"]\n self.subPuyo[\"y\"] = self.mainPuyo[\"y\"]\n self.mainPuyo[\"x\"] +=1\n self.onPuyo -= 1\n return True\n else:\n return False\n else:\n if self.is_moveable(self.mainPuyo[\"x\"]+1 ,self.mainPuyo[\"y\"]):\n self.subPuyo[\"x\"] = self.mainPuyo[\"x\"]+1\n self.subPuyo[\"y\"] = self.mainPuyo[\"y\"]\n self.onPuyo += 1\n return True\n elif self.is_moveable(self.mainPuyo[\"x\"]-1 ,self.mainPuyo[\"y\"]):\n self.subPuyo[\"x\"] = self.mainPuyo[\"x\"]\n self.subPuyo[\"y\"] = self.mainPuyo[\"y\"]\n self.mainPuyo[\"x\"] -=1\n self.onPuyo += 1\n return True\n else:\n return False\n elif self.onPuyo%4 == 1:\n if left:\n if self.is_moveable(self.mainPuyo[\"x\"] ,self.mainPuyo[\"y\"]-1):\n self.subPuyo[\"x\"] = self.mainPuyo[\"x\"]\n self.subPuyo[\"y\"] = self.mainPuyo[\"y\"]-1\n self.onPuyo -= 1\n return True\n elif self.is_moveable(self.mainPuyo[\"x\"] ,self.mainPuyo[\"y\"]+1):\n self.subPuyo[\"x\"] = self.mainPuyo[\"x\"]\n self.subPuyo[\"y\"] = self.mainPuyo[\"y\"]\n self.mainPuyo[\"y\"] -=1\n self.onPuyo -= 1\n return True\n else:\n return False\n else:\n if self.is_moveable(self.mainPuyo[\"x\"] ,self.mainPuyo[\"y\"]+1):\n self.subPuyo[\"x\"] = self.mainPuyo[\"x\"]\n self.subPuyo[\"y\"] = self.mainPuyo[\"y\"]+1\n self.onPuyo += 1\n return True\n elif self.is_moveable(self.mainPuyo[\"x\"] ,self.mainPuyo[\"y\"]-1):\n self.subPuyo[\"x\"] = self.mainPuyo[\"x\"]\n self.subPuyo[\"y\"] = self.mainPuyo[\"y\"]\n self.mainPuyo[\"y\"] -=1\n self.onPuyo += 1\n return True\n else:\n return False\n elif self.onPuyo%4 == 2:\n if left:\n if self.is_moveable(self.mainPuyo[\"x\"]+1 ,self.mainPuyo[\"y\"]):\n self.subPuyo[\"x\"] = self.mainPuyo[\"x\"]+1\n self.subPuyo[\"y\"] = self.mainPuyo[\"y\"]\n self.onPuyo -= 1\n return True\n elif self.is_moveable(self.mainPuyo[\"x\"]-1 ,self.mainPuyo[\"y\"]):\n self.subPuyo[\"x\"] = self.mainPuyo[\"x\"]\n self.subPuyo[\"y\"] = self.mainPuyo[\"y\"]\n self.mainPuyo[\"x\"] -=1\n self.onPuyo -= 1\n return True\n else:\n return False\n else:\n if self.is_moveable(self.mainPuyo[\"x\"]-1 ,self.mainPuyo[\"y\"]):\n self.subPuyo[\"x\"] = self.mainPuyo[\"x\"]-1\n self.subPuyo[\"y\"] = self.mainPuyo[\"y\"]\n self.onPuyo += 1\n return True\n elif self.is_moveable(self.mainPuyo[\"x\"]+1 ,self.mainPuyo[\"y\"]):\n self.subPuyo[\"x\"] = self.mainPuyo[\"x\"]\n self.subPuyo[\"y\"] = self.mainPuyo[\"y\"]\n self.mainPuyo[\"x\"] +=1\n self.onPuyo += 1\n return True\n else:\n return False\n else:\n if left:\n if self.is_moveable(self.mainPuyo[\"x\"] ,self.mainPuyo[\"y\"]+1):\n self.subPuyo[\"x\"] = self.mainPuyo[\"x\"]\n self.subPuyo[\"y\"] = self.mainPuyo[\"y\"]+1\n self.onPuyo -= 1\n return True\n elif self.is_moveable(self.mainPuyo[\"x\"] ,self.mainPuyo[\"y\"]-1):\n self.subPuyo[\"x\"] = self.mainPuyo[\"x\"]\n self.subPuyo[\"y\"] = self.mainPuyo[\"y\"]\n self.mainPuyo[\"y\"] -=1\n self.onPuyo -= 1\n return True\n else:\n return False\n else:\n if self.is_moveable(self.mainPuyo[\"x\"] ,self.mainPuyo[\"y\"]-1):\n self.subPuyo[\"x\"] = self.mainPuyo[\"x\"]\n self.subPuyo[\"y\"] = self.mainPuyo[\"y\"]-1\n self.onPuyo += 1\n return True\n elif self.is_moveable(self.mainPuyo[\"x\"] ,self.mainPuyo[\"y\"]+1):\n self.subPuyo[\"x\"] = self.mainPuyo[\"x\"]\n self.subPuyo[\"y\"] = self.mainPuyo[\"y\"]\n self.mainPuyo[\"y\"] +=1\n self.onPuyo += 1\n return True\n else:\n return False\n\n def check_chain(self):\n \"\"\"\n if 4 Puyos are combined,remove their from GameField\n and return True else False\n \"\"\"\n def inner_cc(x ,y ,checked=set()):\n if len(checked) == 0:\n return inner_cc(x ,y ,set([(x ,y)]))\n else:\n if x == 0:\n raws = [x ,x+1]\n elif x == self.MAX_RAW-1:\n raws = [x-1 ,x]\n else:\n raws = [x-1 ,x ,x+1]\n if y == 0:\n colomns = [y ,y+1]\n elif y == self.MAX_COLOMN-1:\n colomns = [y-1 ,y]\n else:\n colomns = [y-1 ,y ,y+1]\n chain_poses = set([(i ,j) for i in raws for j in colomns if self.GameField[y][x] == self.GameField[j][i] and abs(i-x+j-y)==1])\n if chain_poses.issubset(checked):\n return checked\n checked.update(chain_poses)\n [inner_cc(psx ,psy ,checked) for psx ,psy in chain_poses]\n return checked\n chained = False\n for y in xrange(len(self.GameField)):\n for x in xrange(len(self.GameField[y])):\n if self.GameField[y][x] == 0:\n continue\n combs = inner_cc(x ,y)\n if len(combs) >= 4:\n for rx ,ry in combs:\n self.GameField[ry][rx] = 0\n chained = True\n return chained\n\n def drop(self):\n \"\"\"\n if you call this method,drop Puyos that is possible to drop on field\n if no Puyos are dropped,this method return False\n \"\"\"\n dropped = False\n for y in xrange(self.MAX_COLOMN):\n for x in xrange(self.MAX_RAW):\n if self.GameField[y][x] == 0:\n continue\n if self.is_moveable(x ,y+1):\n self.GameField[y+1][x] = self.GameField[y][x]\n self.GameField[y][x] = 0\n dropped = True\n if dropped:\n self.drop()\n return dropped\n\n def next(self):\n \"\"\"\n this method will progress game\n \"\"\"\n if not self.chaining:\n if self.mainPuyo == None:\n self.mainPuyo = {\"x\":self.MAX_RAW/2-1 ,\"y\":0 ,\"color\":random.randint(1 ,self.MAX_COLORS)}\n self.subPuyo = {\"x\":self.MAX_RAW/2 ,\"y\":0 ,\"color\":random.randint(1 ,self.MAX_COLORS)}\n self.onPuyo = 1\n return 0\n elif self.is_moveable(self.mainPuyo[\"x\"] ,self.mainPuyo[\"y\"]+1) and \\\n self.is_moveable(self.subPuyo[\"x\"] ,self.subPuyo[\"y\"]+1):\n self.mainPuyo[\"y\"] += 1\n self.subPuyo[\"y\"] += 1\n return -1\n else:\n self.GameField[self.mainPuyo[\"y\"]][self.mainPuyo[\"x\"]] = self.mainPuyo[\"color\"]\n self.GameField[self.subPuyo[\"y\"]][self.subPuyo[\"x\"]] = self.subPuyo[\"color\"]\n self.mainPuyo = self.subPuyo = None\n if self.drop():\n self.chaining = True\n return 0\n if self.check_chain():\n self.chaining = True\n else:\n self.chaining = False\n if self.GameField[0][self.MAX_RAW/2-1] != 0 or self.GameField[0][self.MAX_RAW/2] != 0:\n return -2\n else:\n if self.drop():\n return\n if self.check_chain():\n self.chaining = True\n else:\n self.chaining = False\n if self.GameField[0][self.MAX_RAW/2-1] != 0 or self.GameField[0][self.MAX_RAW/2] != 0:\n return -2\n return 0\n\n\n def is_moveable(self ,x ,y):\n \"\"\"\n return arg's possision is moveable or not\n \"\"\"\n if (0 <= x < self.MAX_RAW) and (0 <= y < self.MAX_COLOMN) and (self.GameField[y][x] == 0):\n return True\n else:\n return False\n\ndef LoadImage(name):\n \"\"\"\n load image from file name and change sxale\n \"\"\"\n path = os.path.join(\"img\" ,name)\n image = pygame.image.load(path).convert_alpha()\n rect = image.get_rect()\n image = pygame.transform.scale(image ,(32 ,32))\n return image\n\ndef main():\n pygame.init()\n screen = pygame.display.set_mode((6*32 ,13*32))\n pygame.display.set_caption(\"Puyo2\")\n clock = pygame.time.Clock()\n spend_time = 0\n puyo2 = PuyoGame()\n colors = {1:LoadImage(\"b.gif\") ,2:LoadImage(\"g.gif\") ,3:LoadImage(\"r.gif\")\n ,4:LoadImage(\"y.gif\") ,5:LoadImage(\"p.gif\") ,6:LoadImage(\"e.gif\")}\n while 1:\n clock.tick(60)\n spend_time += 1\n if spend_time%60 == 0 or (spend_time%30 == 0 and puyo2.chaining):\n puyo2.next()\n screen.fill((0 ,0 ,0))\n for y in xrange(len(puyo2.GameField)):\n for x in xrange(len(puyo2.GameField[y])):\n if puyo2.GameField[y][x] != 0:\n screen.blit(colors[puyo2.GameField[y][x]] ,(x*32 ,y*32))\n if puyo2.mainPuyo != None:\n screen.blit(colors[puyo2.mainPuyo[\"color\"]] ,(puyo2.mainPuyo[\"x\"]*32 ,puyo2.mainPuyo[\"y\"]*32))\n screen.blit(colors[puyo2.subPuyo[\"color\"]] ,(puyo2.subPuyo[\"x\"]*32 ,puyo2.subPuyo[\"y\"]*32))\n pygame.display.flip()\n pressed_keys = pygame.key.get_pressed()\n if pressed_keys[K_DOWN] and spend_time%6 == 0 and not puyo2.chaining:\n puyo2.next()\n for event in pygame.event.get():\n if event.type == QUIT:\n return\n if event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n return\n if event.key == K_LEFT:\n puyo2.move(-1)\n if event.key == K_RIGHT:\n puyo2.move(1)\n if event.key == K_UP:\n puyo2.turn()\n if event.key == K_z:\n puyo2.turn(left = True)\n if event.key == K_x:\n puyo2.turn()\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"419714778","text":"#!/usr/bin/python\n# -*- coding: UTF-8\nimport sys\n\nsys.path.append(\"..\")\nfrom OneNetApp.OneNetApi import *\nimport json\nfrom PublicLib.Protocol.ly_Json import subStrToJson\nimport time\nimport logging\nfrom PublicLib import public as pub\n\n\ndef onenet_paresdata(res):\n # bytes to str\n data = bytes.decode(res)\n\n # 将json对象转换成python对象\n data_python = json.loads(data)\n if data_python[\"errno\"] == 0 and data_python[\"error\"] == \"succ\":\n if 'data' in data_python:\n return True, data_python[\"data\"]\n else:\n return True, None\n else:\n return False, None\n\n\ndef onenet_contjson(content):\n jsondata = bytes.decode(content)\n\n # 将json对象转换成python对象\n data = json.loads(jsondata)\n\n count = data[\"data\"][\"count\"]\n recvtimelist = []\n valuelist = []\n for i in range(count):\n dic = data[\"data\"][\"datastreams\"][0][\"datapoints\"][i]\n\n recvtime = dic[\"at\"]\n value = dic[\"value\"]\n value = subStrToJson(value)\n recvtimelist += [recvtime]\n valuelist += [value]\n return count, recvtimelist, valuelist\n\n\ndef onenet_makeframe(con, deviceinfo, val):\n # nbiot_url = {\"imei\": device_imei, \"obj_id\": obj_id, \"obj_inst_id\": obj_inst_id, \"mode\": mode} # params\n # '3308_0_5750'\n # nbiot_url = {\"imei\": deviceinfo[\"rg_id\"], \"obj_id\": deviceinfo[\"datastreams\"][0][\"id\"][:4],\n # \"obj_inst_id\": deviceinfo[\"datastreams\"][0][\"id\"][5:6], \"mode\": 2} # params\n nbiot_url = {\"imei\": deviceinfo[\"rg_id\"], \"obj_id\": '3308',\n \"obj_inst_id\": '0', \"mode\": 2} # params\n nbiot_data = {\"data\": [{\"res_id\": '5750', \"val\": val}]} # data\n\n res4 = con.nbiot_write(nbiot_data, nbiot_url)\n return (res4.content)\n\n\ndef onenet_senddata(con, deviceinfo, val):\n if deviceinfo[\"online\"]:\n # 发送数据\n # 其中datastream_id等于obj_id, obj_inst_id, res_id,如obj_id:3200,obj_inst_id:0,res_id:5501,那么这个datastream_id就为3200_0_5501。 ['3308_0_5750']\n # val = \"{'Len':'312','Cmd':'Read','SN':'1','DataTime':'180706121314','CRC':'FFFF','DataValue':{'0201FF00':''}}\" # object\n res = onenet_makeframe(con, deviceinfo, val)\n ret, data = onenet_paresdata(res)\n return ret\n return None\n\n\ndef getcurtime():\n # 时间戳\n now = time.time()\n int(now)\n\n # 时间\n tl = time.localtime(now)\n\n # 格式化时间\n return time.strftime(\"%Y-%m-%d %H:%M:%S\", tl)\n\n\ndef getpreday(n):\n # 时间戳\n now = time.time()\n int(now)\n\n pre = now - n*24*3600\n\n # 时间\n tl = time.localtime(pre)\n\n # 格式化时间\n return time.strftime(\"%Y-%m-%d %H:%M:%S\", tl)\n\n\n# 查询最近N条数据\ndef onenet_recvdata(con, deviceinfo, parm):\n if deviceinfo[\"online\"]:\n # res3 = con.datapoint_multi_get(device_id = deviceinfo[\"id\"], limit = 1, datastream_ids = deviceinfo[\"datastreams\"][0][\"id\"])\n\n if \"start_time\" in parm and \"end_time\" in parm and \"limit\" in parm:\n res3 = con.datapoint_multi_get(device_id=deviceinfo[\"id\"],\n start_time=parm[\"start_time\"],\n end_time=parm[\"end_time\"],\n limit=parm[\"limit\"],\n datastream_ids='3308_0_5750')\n elif \"start_time\" in parm and \"end_time\":\n res3 = con.datapoint_multi_get(device_id=deviceinfo[\"id\"],\n start_time=parm[\"start_time\"],\n end_time=parm[\"end_time\"],\n datastream_ids='3308_0_5750')\n elif \"limit\" in parm:\n res3 = con.datapoint_multi_get(device_id=deviceinfo[\"id\"],\n limit=parm[\"limit\"],\n datastream_ids='3308_0_5750')\n else:\n res3 = con.datapoint_multi_get(device_id=deviceinfo[\"id\"],\n limit=1,\n datastream_ids='3308_0_5750')\n count, recvtime, jsonstr = onenet_contjson(res3.content)\n return count, jsonstr\n else:\n print('设备不在线')\n\n\ndef connectonenet(rlist, devlist):\n for i in range(len(devlist)):\n rlist += [con.device_info(device_id=devlist[i])]\n return rlist\n\n\ndef getdevinfo(res3, device_id):\n # 获取设备信息\n ret, deviceinfo = onenet_paresdata(res3.content)\n # print('当前测试设备信息', device_id, deviceinfo['auth_info'], 'online:',deviceinfo[\"online\"])\n return ret, deviceinfo\n\n\ndef getcurinfo(con, rlist, devlist, prelist, parm):\n # 获取设备信息\n for i in range(len(devlist)):\n nret, deviceinfo = getdevinfo(rlist[i], devlist[i])\n\n if nret is True and deviceinfo[\"online\"]:\n # val = \"{'Len':'312','Cmd':'Set','SN':'2','DataTime':'200428121314','CRC':'FFFF','DataValue':{'04A20105':'01'}}\" # object\n val = \"{'Len':'312','Cmd':'Set','SN':'2','DataTime':'180706121314','CRC':'FFFF','DataValue':{'04A10101':'02#FF#8002#0005#180901120100#05#00900200#05060101#04A20201#04A50302#04A50303','04A10102':'02#01'}}\" # object\n ret = onenet_senddata(con, deviceinfo, val)\n print(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()), 'send: ', val)\n time.sleep(5) # 等待间隔\n\n # val = \"{'Len':'312','Cmd':'Read','SN':'1','DataTime':'200428121314','CRC':'FFFF','DataValue':{'04A00101':'','04A00102':'','04A20201':'','04A50302':'','04A50303':''}}\" # object\n val = \"{'Len':'0104','Cmd':'Set','SN':'179','DataTime':'200527144935','CRC':'FFFF','DataValue':{'04A20106':'0060'}}\" # object\n ret = onenet_senddata(con, deviceinfo, val)\n print(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()), 'send: ', val)\n time.sleep(1) # 等待间隔\n\n\n if nret is True and deviceinfo[\"online\"]:\n n, data = onenet_recvdata(con, deviceinfo, parm)\n if n > 0:\n s = deviceinfo['title'] + ', ' + deviceinfo['rg_id']\n print(s)\n logger.info(s)\n for d in data:\n print(d)\n logger.info(d)\n else:\n # print(deviceinfo['title'], '不在线! 最近在线时间:',deviceinfo[\"act_time\"])\n try:\n s = deviceinfo['title'] + ', ' + deviceinfo['rg_id'] + ', 不在线! 最近在线时间:' + deviceinfo[\"last_ct\"]\n if prelist[i] != s:\n prelist[i] = s\n print(s)\n logger.info(s)\n except:\n pass\n\n\n\nif __name__ == '__main__':\n pub.loggingConfig('logging.conf')\n logger = logging.getLogger('ToolMain')\n\n # 定义设备信息\n deviceinfo = {}\n\n # 定义设备云端信息\n # device_contents = \"4Hkjc25uOQ6qDd4AsfMyvMOJLSg=\"\n # device_id = 522658053\n # device_contents = \"mBnDJfsR8paDmq3g7mh=iWi9lb4=\" # NB电表\n # device_id = 525383929\n device_contents = \"sP5Mezphc5YUN9Q=mdISOM6UKVM=\" # NB生产\n con = OneNetApi(device_contents) # 文件目录\n\n # 设备ID\n # device_id_1 = 593477971 # IMEI: 868334034252753 TLY2821_移动_200424\n # device_id_2 = 593476181 # IMEI: 868334034332290 TLY2823_联通_200424\n # device_id_3 = 593474168 # IMEI: 868334033126362 TLY2823_电信_200424\n # device_id_4 = 586340334 # IMEI: 868334034332431 TLY2821_联通_200424\n\n config = pub.loadDefaultSettings(\"devIDcfg.json\")\n devlist = config['deviceID']\n\n # namelist = ['TLY2821_移动_200424', 'TLY2823_联通_200424', 'TLY2823_电信_200424', 'TLY2821_联通_200424']\n # devlist = [device_id_1, device_id_2, device_id_3, device_id_4]\n # devnum = len(devlist)\n predata = [''] * 4\n\n # start_time = getpreday(3)\n # end_time = getcurtime()\n # parm = {\"start_time\":start_time, \"end_time\":end_time, \"limit\":64}\n\n parm = {\"limit\": 64}\n\n # 连接设备\n rlist = []\n connectonenet(rlist, devlist)\n\n # 获取最近信息\n getcurinfo(con, rlist, devlist, predata, parm)\n time.sleep(3)\n\n","sub_path":"OneNetGetLog.py","file_name":"OneNetGetLog.py","file_ext":"py","file_size_in_byte":8228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"102900344","text":"\"\"\"Encapsulates datasets in a generic Dataset class, and in some more specific classes that inherit\nfrom it\n\n\"\"\"\n\nimport os\nimport json\nimport math\nfrom multiprocessing import Pool\n\nimport cv2\nfrom PIL import Image\n\nimport numpy as np\n\nfrom deeposlandia import utils\n\nclass Dataset:\n \"\"\"Generic class that describes the behavior of a Dataset object: it is initialized at least\n with an image size, its label are added always through the same manner, it can be serialized (save) and\n deserialized (load) from/to a `.json` file\n\n Attributes\n ----------\n image_size : int\n Size of considered images (height=width), raw images will be resized during the\n preprocessing\n\n \"\"\"\n def __init__(self, image_size):\n self.image_size = image_size\n self.label_info = []\n self.image_info = []\n\n @property\n def label_ids(self):\n \"\"\"Return the list of labels ids taken into account in the dataset\n\n They can be grouped.\n\n Returns\n -------\n list\n List of label ids\n \"\"\"\n return [label_id for label_id, attr in enumerate(self.label_info)\n if attr['is_evaluate']]\n\n @property\n def labels(self):\n \"\"\"Return the description of label that will be evaluated during the process\n \"\"\"\n return [label for label in self.label_info if label[\"is_evaluate\"]]\n\n def get_nb_labels(self, see_all=False):\n \"\"\"Return the number of labels\n\n Parameters\n ----------\n see_all : boolean\n If True, consider all labels, otherwise consider only labels for which `is_evaluate` is\n True\n \"\"\"\n if see_all:\n return len(self.label_info)\n else:\n return len(self.label_ids)\n\n def get_nb_images(self):\n \"\"\" `image_info` getter, return the size of `image_info`, i.e. the\n number of images in the dataset\n \"\"\"\n return len(self.image_info)\n\n def get_label_popularity(self):\n \"\"\"Return the label popularity in the current dataset, *i.e.* the proportion of images that\n contain corresponding object\n \"\"\"\n labels = [img[\"labels\"] for img in self.image_info]\n if self.get_nb_images() == 0:\n utils.logger.error(\"No images in the dataset.\")\n return None\n else:\n return np.round(np.divide(sum(np.array([list(l.values()) for l in labels])),\n self.get_nb_images()), 3)\n\n\n def add_label(self, label_id, label_name, color, is_evaluate,\n category=None, aggregated_label_ids=None,\n contained_labels=None):\n \"\"\" Add a new label to the dataset with label id `label_id`\n\n Parameters\n ----------\n label_id : integer\n Id of the new label\n label_name : str\n String designing the new label name\n color : list\n List of three integers (between 0 and 255) that characterizes the\n label (useful for semantic segmentation result printing)\n is_evaluate : bool\n category : str\n String designing the category of the dataset label\n aggregate_label_ids : list (optional)\n List of label ids aggregated by the current label_id\n contained_labels : list\n List of raw labels aggregated by the current label\n \"\"\"\n if label_id in self.label_info:\n utils.logger.error(\"Label {} already stored into the label set.\".format(label_id))\n return None\n category = label_name if category is None else category\n contains = label_name if contained_labels is None else contained_labels\n self.label_info.append({\"name\": label_name,\n \"id\": label_id,\n \"category\": category,\n \"is_evaluate\": is_evaluate,\n \"aggregate\": aggregated_label_ids,\n \"contains\": contained_labels,\n \"color\": color})\n\n def save(self, filename):\n \"\"\"Save dataset in a json file indicated by `filename`\n\n Parameters\n ----------\n filename : str\n String designing the relative path where the dataset must be saved\n \"\"\"\n with open(filename, 'w') as fp:\n json.dump({\"image_size\": self.image_size,\n \"labels\": self.label_info,\n \"images\": self.image_info}, fp)\n utils.logger.info(\"The dataset has been saved into {}\".format(filename))\n\n def load(self, filename, nb_images=None):\n \"\"\"Load a dataset from a json file indicated by `filename` ; use dict comprehension instead\n of direct assignments in order to convert dict keys to integers\n\n Parameters\n ----------\n filename : str\n String designing the relative path from where the dataset must be\n loaded\n nb_images : integer\n Number of images that must be loaded (if None, the whole dataset is loaded)\n \"\"\"\n with open(filename) as fp:\n ds = json.load(fp)\n self.image_size = ds[\"image_size\"]\n self.label_info = ds[\"labels\"]\n if nb_images is None:\n self.image_info = ds[\"images\"]\n else:\n self.image_info = ds[\"images\"][:nb_images]\n utils.logger.info(\"The dataset has been loaded from {}\".format(filename))\n\nclass MapillaryDataset(Dataset):\n \"\"\"Dataset structure that gathers all information related to the Mapillary images\n\n Attributes\n ----------\n image_size : int\n Size of considered images (height=width), raw images will be resized during the\n preprocessing\n glossary_filename : str\n Name of the Mapillary input glossary, that contains every information about Mapillary\n labels\n\n \"\"\"\n\n def __init__(self, image_size, glossary_filename):\n \"\"\" Class constructor ; instanciates a MapillaryDataset as a standard Dataset which is\n completed by a glossary file that describes the dataset labels\n \"\"\"\n super().__init__(image_size)\n self.build_glossary(glossary_filename)\n\n def build_glossary(self, config_filename):\n \"\"\"Read the Mapillary glossary stored as a json file at the data\n repository root\n\n Parameters\n ----------\n config_filename : str\n String designing the relative path of the dataset glossary\n (based on Mapillary dataset)\n \"\"\"\n with open(config_filename) as config_file:\n glossary = json.load(config_file)\n if \"labels\" not in glossary:\n utils.logger.error(\"There is no 'label' key in the provided glossary.\")\n return None\n for lab_id, label in enumerate(glossary[\"labels\"]):\n name_items = label[\"name\"].split('--')\n category = '-'.join(name_items)\n self.add_label(lab_id, name_items, label[\"color\"],\n label['evaluate'], category, label[\"contains_id\"],\n label['contains'])\n\n def group_image_label(self, image):\n \"\"\"Group the labels\n\n If the label ids 4, 5 and 6 belong to the same group, they will be turned\n into the label id 4.\n\n Parameters\n ----------\n image : PIL.Image\n\n Returns\n -------\n PIL.Image\n \"\"\"\n # turn all label ids into the lowest digits/label id according to its \"group\"\n # (manually built)\n a = np.array(image)\n for root_id, label in enumerate(self.label_info):\n for label_id in label['aggregate']:\n mask = a == label_id\n a[mask] = root_id\n return Image.fromarray(a, mode=image.mode)\n\n def _preprocess(self, image_filename, output_dir, aggregate, labelling=True):\n \"\"\"Resize/crop then save the training & label images\n\n Parameters\n ----------\n datadir : str\n image_filaname : str\n aggregate : boolean\n labelling : boolean\n\n Returns\n -------\n dict\n Key/values with the filenames and label ids\n \"\"\"\n # open original images\n img_in = Image.open(image_filename)\n\n # resize images (self.image_size*larger_size or larger_size*self.image_size)\n img_in = utils.resize_image(img_in, self.image_size)\n\n # crop images to get self.image_size*self.image_size dimensions\n crop_pix = np.random.randint(0, 1 + max(img_in.size) - self.image_size)\n final_img_in = utils.mono_crop_image(img_in, crop_pix)\n\n # save final image\n new_in_filename = os.path.join(output_dir, 'images',\n os.path.basename(image_filename))\n final_img_in.save(new_in_filename)\n\n # label_filename vs label image\n if labelling:\n label_filename = image_filename.replace(\"images/\", \"labels/\")\n label_filename = label_filename.replace(\".jpg\", \".png\")\n img_out = Image.open(label_filename)\n img_out = utils.resize_image(img_out, self.image_size)\n final_img_out = utils.mono_crop_image(img_out, crop_pix)\n # group some labels\n if aggregate:\n final_img_out = self.group_image_label(final_img_out)\n\n labels = utils.mapillary_label_building(final_img_out,\n self.label_ids)\n new_out_filename = os.path.join(output_dir, 'labels',\n os.path.basename(label_filename))\n final_img_out = utils.build_image_from_config(final_img_out,\n self.label_info)\n final_img_out.save(new_out_filename)\n else:\n new_out_filename = None\n labels = {i: 0 for i in range(self.get_nb_labels())}\n\n return {\"raw_filename\": image_filename,\n \"image_filename\": new_in_filename,\n \"label_filename\": new_out_filename,\n \"labels\": labels}\n\n def populate(self, output_dir, input_dir, nb_images=None, aggregate=False, labelling=True):\n \"\"\" Populate the dataset with images contained into `datadir` directory\n\n Parameters\n ----------\n output_dir : str\n Path of the directory where the preprocessed image must be saved\n input_dir : str\n Path of the directory that contains input images\n nb_images : integer\n Number of images to be considered in the dataset; if None, consider the whole\n repository\n aggregate : bool\n Aggregate some labels into more generic ones, e.g. cars and bus into the vehicle label\n labelling: boolean\n If True labels are recovered from dataset, otherwise dummy label are generated\n \"\"\"\n image_list = os.listdir(os.path.join(input_dir, \"images\"))[:nb_images]\n image_list_longname = [os.path.join(input_dir, \"images\", l) for l in image_list]\n with Pool() as p:\n self.image_info = p.starmap(self._preprocess, [(x, output_dir, aggregate, labelling)\n for x in image_list_longname])\n\nclass ShapeDataset(Dataset):\n \"\"\"Dataset structure that gathers all information related to a randomly-generated shape Dataset\n\n In such a dataset, a set of images is generated with either a square, or a\n circle or a triangle, or two of them, or all of them. A random background\n color is applied, and shape color itself is also randomly generated. Each\n of these labels are characterized with a fixed color for comparison between\n ground truth and predictions: squares, circles and triangles will be\n respectively set as blue, red and green, whilst background will be set as\n light grey.\n\n Attributes\n ----------\n image_size : int\n Size of considered images (height=width), raw images will be resized during the\n preprocessing\n nb_labels : int\n Number of shape types that must be integrated into the dataset (only 1, 2 and 3 are supported)\n\n \"\"\"\n\n SQUARE = 0\n SQUARE_COLOR = (50, 50, 200) # Blue\n CIRCLE = 1\n CIRCLE_COLOR = (200, 50, 50) # Red\n TRIANGLE = 2\n TRIANGLE_COLOR = (50, 200, 50) # Green\n BACKGROUND = 3\n BACKGROUND_COLOR = (200, 200, 200) # Light grey\n\n def __init__(self, image_size):\n \"\"\" Class constructor\n \"\"\"\n super().__init__(image_size)\n self.build_glossary()\n\n def build_glossary(self):\n \"\"\"Read the shape glossary stored as a json file at the data\n repository root\n\n Parameters\n ----------\n nb_labels : integer\n Number of shape types (either 1, 2 or 3, warning if more)\n \"\"\"\n self.add_label(self.SQUARE, \"square\", self.SQUARE_COLOR, True)\n self.add_label(self.CIRCLE, \"circle\", self.CIRCLE_COLOR, True)\n self.add_label(self.TRIANGLE, \"triangle\", self.TRIANGLE_COLOR, True)\n self.add_label(self.BACKGROUND, \"background\", self.BACKGROUND_COLOR, True)\n\n def generate_labels(self, nb_images):\n \"\"\" Generate random shape labels in order to prepare shape image\n generation; use numpy to generate random indices for each labels, these\n indices will be the positive examples; return a 2D-list\n\n Parameters\n ----------\n nb_images : integer\n Number of images to label in the dataset\n \"\"\"\n raw_labels = [np.random.choice(np.arange(nb_images),\n int(nb_images/2),\n replace=False)\n for i in range(self.get_nb_labels())]\n labels = np.zeros([nb_images, self.get_nb_labels()], dtype=int)\n for i in range(self.get_nb_labels()):\n labels[raw_labels[i], i] = 1\n return [dict([(i, int(j)) for i, j in enumerate(l)]) for l in labels]\n\n def populate(self, output_dir=None, input_dir=None, nb_images=10000, aggregate=False, labelling=True, buf=8):\n \"\"\" Populate the dataset with images contained into `datadir` directory\n\n Parameters\n ----------\n output_dir : str\n Path of the directory where the preprocessed image must be saved\n input_dir : str\n Path of the directory that contains input images\n nb_images: integer\n Number of images that must be added in the dataset\n aggregate: bool\n Aggregate some labels into more generic ones, e.g. cars and bus into the vehicle label\n labelling: boolean\n Dummy parameter: in this dataset, labels are always generated, as images are drawed with them\n buf: integer\n Minimal number of pixels between shape base point and image borders\n \"\"\"\n shape_gen = self.generate_labels(nb_images)\n for i, image_label in enumerate(shape_gen):\n bg_color = np.random.randint(0, 255, 3).tolist()\n shape_specs = []\n for l in image_label.items():\n if l:\n shape_color = np.random.randint(0, 255, 3).tolist()\n x, y = np.random.randint(buf, self.image_size - buf - 1, 2).tolist()\n shape_size = np.random.randint(buf, self.image_size // 4)\n shape_specs.append([shape_color, x, y, shape_size])\n else:\n shape_specs.append([None, None, None, None])\n self.add_image(i, bg_color, shape_specs, image_label)\n if not output_dir is None:\n self.draw_image(i, output_dir)\n\n def add_image(self, image_id, background, specifications, labels):\n \"\"\" Add a new image to the dataset with image id `image_id`; an image\n in the dataset is represented by an id, a list of shape specifications,\n a background color and a list of 0-1 labels (1 if the i-th label is on\n the image, 0 otherwise)\n\n Parameters\n ----------\n image_id : integer\n Id of the new image\n background : list\n List of three integer between 0 and 255 that designs the image\n background color\n specifications : list\n Image specifications, as a list of shapes (color, coordinates and\n size)\n labels : list\n List of 0-1 values, the i-th value being 1 if the i-th label is on\n the new image, 0 otherwise; the label list length correspond to the\n number of labels in the dataset\n \"\"\"\n if image_id in self.image_info:\n utils.logger.error(\"Image {} already stored into the label set.\".format(image_id))\n return None\n self.image_info.append({\"background\": background,\n \"shape_specs\": specifications,\n \"labels\": labels})\n\n def draw_image(self, image_id, datapath):\n \"\"\"Draws an image from the specifications of its shapes and saves it on\n the file system to `datapath`\n\n Save labels as mono-channel images on the file system by using the label ids\n\n Parameters\n ----------\n image_id : integer\n Image id\n datapath : str\n String that characterizes the repository in which images will be stored\n \"\"\"\n image_info = self.image_info[image_id]\n\n image = np.ones([self.image_size, self.image_size, 3], dtype=np.uint8)\n image = image * np.array(image_info[\"background\"], dtype=np.uint8)\n label = np.full([self.image_size, self.image_size, 3], self.BACKGROUND_COLOR, dtype=np.uint8)\n\n # Get the center x, y and the size s\n if image_info[\"labels\"][self.SQUARE]:\n color, x, y, s = image_info[\"shape_specs\"][self.SQUARE]\n color = tuple(map(int, color))\n image = cv2.rectangle(image, (x - s, y - s), (x + s, y + s), color, -1)\n label = cv2.rectangle(label, (x - s, y - s), (x + s, y + s), self.SQUARE_COLOR, -1)\n if image_info[\"labels\"][self.CIRCLE]:\n color, x, y, s = image_info[\"shape_specs\"][self.CIRCLE]\n color = tuple(map(int, color))\n image = cv2.circle(image, (x, y), s, color, -1)\n label = cv2.circle(label, (x, y), s, self.CIRCLE_COLOR, -1)\n if image_info[\"labels\"][self.TRIANGLE]:\n color, x, y, s = image_info[\"shape_specs\"][self.TRIANGLE]\n color = tuple(map(int, color))\n x, y, s = map(int, (x, y, s))\n points = np.array([[(x, y - s),\n (x - s / math.sin(math.radians(60)), y + s),\n (x + s / math.sin(math.radians(60)), y + s),]],\n dtype=np.int32)\n image = cv2.fillPoly(image, points, color)\n label = cv2.fillPoly(label, points, self.TRIANGLE_COLOR)\n image_filename = os.path.join(datapath, \"images\", \"shape_{:05}.png\".format(image_id))\n self.image_info[image_id][\"image_filename\"] = image_filename\n Image.fromarray(image).save(image_filename)\n label_filename = os.path.join(datapath, \"labels\", \"shape_{:05}.png\".format(image_id))\n self.image_info[image_id][\"label_filename\"] = label_filename\n Image.fromarray(label).save(label_filename)\n","sub_path":"deeposlandia/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":19460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"563470262","text":"import re\n\nfrom grab import Grab\n\nfrom grab_site.models import Vacancy\nfrom grab_worker.celery import app\n\n\ndef parse_vacancy_salary(vacancy_salary):\n replace_string = vacancy_salary.replace(u'\\xa0', '').replace(' ', '')\n salaries = re.findall('(\\d+)', replace_string)\n salary_from, salary_to = None, None\n if vacancy_salary.find('до') != -1:\n salary_to = salaries.pop()\n if vacancy_salary.find('от') != -1:\n salary_from = salaries.pop()\n\n return salary_from, salary_to\n\n\n@app.task\ndef grab_vacancies():\n g = Grab()\n g.go('https://spb.hh.ru/employer/889')\n\n xpath = '//div[contains(@class, \"resume-search-item__name\")]/a'\n vacancy_links = g.xpath_list(xpath)\n for item in vacancy_links:\n g_info = Grab()\n link = item.get('href')\n g_info.go(link)\n title = g_info.xpath('//h1[contains(@class, \"header\")]').text\n salary_from, salary_to = parse_vacancy_salary(g_info.xpath('//p[contains(@class, \"vacancy-salary\")]').text)\n vacancy_description = g_info.xpath('//div[contains(@itemprop, \"description\")]/p').text\n\n Vacancy.objects.update_or_create(vacancy_id=re.findall('\\d+', link)[0], name=title,\n description=vacancy_description, link=link,\n salary_from=salary_from, salary_to=salary_to)\n","sub_path":"grab_site/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"24916811","text":"\"\"\"\nmount - Command\n===============\n\nThis module provides parsing for the ``mount`` command. The ``Mount`` class\nimplements parsing for the ``mount`` command output which looks like::\n\n sysfs on /sys type sysfs (rw,nosuid,nodev,noexec,relatime,seclabel)\n proc on /proc type proc (rw,nosuid,nodev,noexec,relatime)\n /dev/mapper/HostVG-Config on /etc/shadow type ext4 (rw,noatime,seclabel,stripe=256,data=ordered)\n dev/sr0 on /run/media/root/VMware Tools type iso9660 (ro,nosuid,nodev,relatime,uid=0,gid=0,iocharset=utf8,mode=0400,dmode=0500,uhelper=udisks2) [VMware Tools]\n\nThe information is stored as a list of ``AttributeDict`` objects. Each\n``AttributeDict`` object contains attributes for the following information that\nare listed in the same order as in the command output::\n\n - filesystem: (str) Name of filesystem\n - mount_point: (str) Name of mount point for filesystem\n - mount_type: (str) Name of filesystem type\n - mount_options: (AttributeDict) Mount options as ``AttributeDict`` object\n - mount_label: (str) Only present if optional label is present\n - mount_clause: (str) Full string from command output\n\nThe `` mount_options`` contains the mount options as attributes accessible\nvia the attribute name as it appears in the command output. For instance, the\noptions ``(rw,dmode=0500)`` may be accessed as ''mnt_row_info.rw`` with the value\n``True`` and ``mnt_row_info.dmode`` with the value \"0500\". The ``in`` operator\nmay be used to determine if an option is present.\n\nMountEntry lines are also available in a ``mounts`` property, keyed on the\nmount point.\n\nExamples:\n >>> mnt_info = shared[Mount]\n >>> mnt_info\n \n >>> len(mnt_info)\n 4\n >>> mnt_info[3].__dict__\n {'filesystem': 'dev/sr0',\n 'mount_clause': 'dev/sr0 on /run/media/root/VMware Tools type iso9660 (ro,nosuid,nodev,relatime,uid=0,gid=0,iocharset=utf8,mode=0400,dmode=0500,uhelper=udisks2) [VMware Tools]',\n 'mount_label': 'VMware Tools',\n 'mount_options': {'dmode': '0500', 'relatime': True, 'uid': '0',\n 'iocharset': 'utf8', 'gid': '0', 'mode': '0400', 'ro': True,\n 'nosuid': True, 'uhelper': 'udisks2', 'nodev': True}\n 'mount_point': '/run/media/root/VMware Tools',\n 'mount_type': 'iso9660'}\n >>> mnt_info[3].filesystem\n 'dev/sr0'\n >>> mnt_info[3].mount_type\n 'iso9660'\n >>> mnt_info[3].mount_options\n {'dmode': '0500', 'gid': '0', 'iocharset': 'utf8', 'mode': '0400', 'nodev': True,\n 'nosuid': True, 'relatime': True, 'ro': True, 'uhelper': 'udisks2', 'uid': '0'}\n >>> mnt_info[3].mount_options.dmode\n >>> 'dmode' in mnt_info[3].mount_options\n True\n >>> mnt_info.mounts['/run/media/root/VMware Tools'].filesystem\n 'dev/sr0'\n\"\"\"\n\nfrom ..parsers import optlist_to_dict\nfrom .. import Parser, parser, get_active_lines, AttributeDict\n\nimport re\n\n\n@parser('mount')\nclass Mount(Parser):\n \"\"\"Class of information for all output from ``mount`` command.\n\n Attributes:\n rows (list of AttributeDict): List of ``AttributeDict`` objects for\n each row of the command output.\n\n Raises:\n ParseException: Raised when any problem parsing the command output.\n \"\"\"\n\n def __len__(self):\n return len(self.rows)\n\n def __iter__(self):\n for row in self.rows:\n yield row\n\n def __getitem__(self, idx):\n if isinstance(idx, int):\n return self.rows[idx]\n elif isinstance(idx, str):\n return self.mounts[idx]\n\n # /dev/mapper/fedora-home on /home type ext4 (rw,relatime,seclabel,data=ordered) [HOME]\n mount_line_re = r'^(?P\\S+) on (?P.+?) type ' + \\\n r'(?P\\S+) \\((?P[^)]+)\\)' + \\\n r'(?: \\[(?P.*)\\])?$'\n mount_line_rex = re.compile(mount_line_re)\n\n def parse_content(self, content):\n self.rows = []\n self.mounts = {}\n for line in get_active_lines(content):\n mount = {}\n mount['mount_clause'] = line\n match = self.mount_line_rex.search(line)\n if match:\n mount['filesystem'] = match.group('filesystem')\n mount['mount_point'] = match.group('mount_point')\n mount['mount_type'] = match.group('mount_type')\n mount_options = match.group('mount_options')\n mount['mount_options'] = AttributeDict(optlist_to_dict(mount_options))\n if match.group('mount_label'):\n mount['mount_label'] = match.group('mount_label')\n else:\n mount['parse_error'] = 'Unable to parse line'\n\n entry = AttributeDict(mount)\n self.rows.append(entry)\n if match:\n self.mounts[mount['mount_point']] = entry\n","sub_path":"insights/parsers/mount.py","file_name":"mount.py","file_ext":"py","file_size_in_byte":4832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"142659717","text":"\"\"\"\n@Authors Leo.cui\n7/5/2018\nFormat train data\n\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\n\ndef get_score_format(test_path, answer_sheet_path):\n #read_data\n df = pd.read_csv(test_path)\n\n answer_sheet = df['id']\n\n #save answer_sheet csv\n answer_sheet.to_csv(answer_sheet_path, index = None, header = True)\n\n return\n\n\ndef xbg_format(data_path, save_path, sort_data = True, fillzero = True):\n\n #read_data\n df = pd.read_csv(data_path)\n\n #get ride off -1 label\n df = df[(df.label==0)|(df.label==1)]\n\n #sorting by data\n if sort_data == True:\n df.sort_values('date', inplace = True)\n\n #delete data column\n df = df.drop(['date','id'], axis=1)\n\n if fillzero == True:\n #fill na\n df = df.fillna(-999)\n\n #save csv\n df.to_csv(save_path, index = None, header = False)\n\n return\n\n\ndef csv2npy(csv_path, npy_path):\n\n _csv = np.loadtxt(csv_path, delimiter=',')\n\n #_csv = np.genfromtxt(csv_path, delimiter=\",\", filling_values = -999)\n\n np.save(npy_path, _csv)\n\n\ndef main():\n\n data_path = \"/home/leo/ant/model/data/train.csv\"\n save_path = \"/home/leo/ant/model/data/train_dw.csv\"\n\n #csv_path = \"/home/leo/ant/model/data/test_a_xgb_1.csv\"\n #npy_path = \"/home/leo/ant/model/data/test_a_xgb_1.npy\"\n\n #test_path = \"/home/leo/ant/model/data/test_a.csv\"\n #answer_sheet_path = \"/home/leo/ant/score/answer_sheet.csv\"\n\n xbg_format(data_path, save_path, sort_data = True, fillzero = False)\n #csv2npy(csv_path, npy_path)\n #get_score_format(test_path, answer_sheet_path)\n\nif __name__ == '__main__':\n main()\n","sub_path":"code/lib/read_data.py","file_name":"read_data.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"49449572","text":"import random\nranddna=''\n#for i in range(100000000):\n# randdna=randdna+'ACGT'[random.randint(0,3)]\n\nranddna= ''.join(['ACGT'[random.randint(0,3)] for i in range(10000000)])\n#print(randdna)\nranddna=list(randdna)\nfor i in range(0,len(randdna),10):\n randdna[i:i+3]=list('XYZ')\nranddna=''.join(randdna)\n#print(randdna)\nprint(randdna.count('X'))\n","sub_path":"python_examples/randdna.py","file_name":"randdna.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"82281645","text":"from pprint import pprint\r\n\r\n\r\ndef composition_dict(list):\r\n if len(list) == 3:\r\n composition = {'ingridient_name': list[0], 'quantity': list[1], 'measure': list[2]}\r\n elif len(list) == 4:\r\n composition = {'ingridient_name': list[0] + ' ' + list[1], 'quantity': list[2], 'measure': list[3]}\r\n return composition\r\n\r\n\r\ndef main():\r\n with open('recipes.txt', encoding='utf8') as f:\r\n cook_book = {}\r\n for line in f:\r\n name = line.strip()\r\n amount = int(f.readline().strip())\r\n for i in range(amount):\r\n add_line = f.readline().replace('|', '').split()\r\n cook_book.setdefault(name, [])\r\n cook_book[name].append(composition_dict(add_line))\r\n f.readline()\r\n\r\n pprint(cook_book)\r\n\r\n def get_shop_list_by_dishes(dishes, person_count):\r\n shop_list = {}\r\n for items in dishes:\r\n if items in cook_book:\r\n for ingredients_dict in cook_book[items]:\r\n # print(k)\r\n for items in ingredients_dict.values():\r\n\r\n if items not in shop_list:\r\n shop_list.setdefault(ingredients_dict['ingridient_name'],\r\n {'measure': ingredients_dict['measure'],\r\n 'quantity': int(ingredients_dict['quantity']) * person_count})\r\n else:\r\n shop_list[items]['quantity'] += shop_list[items]['quantity']\r\n\r\n return shop_list\r\n\r\n pprint(get_shop_list_by_dishes(['Запеченный картофель', 'Омлет'], 2))\r\n\r\n\r\nmain()\r\n","sub_path":"home_work_files.py","file_name":"home_work_files.py","file_ext":"py","file_size_in_byte":1777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"593409909","text":"\n\nimport pickle\nimport wx\nimport wx.grid\nimport wx.html\nimport wx.aui as aui\nfrom wx.py.shell import Shell\nfrom xit_matrixunit import *\nfrom xit_Global import *\nfrom xit_Global_myop import *\n\nfrom xit_UI_tripleTextPanel import xit_MyTripleElementScrolledWindow\nfrom xit_UI_mygrid import *\nfrom xit_UI_downradioPanel import *\nfrom xit_UI_menu import MyMenuControl\nfrom six import BytesIO\n\n \n#----------------------------------------------------------------------\ndef GetMondrianData():\n return \\\nb'\\x89PNG\\r\\n\\x1a\\n\\x00\\x00\\x00\\rIHDR\\x00\\x00\\x00 \\x00\\x00\\x00 \\x08\\x06\\x00\\\n\\x00\\x00szz\\xf4\\x00\\x00\\x00\\x04sBIT\\x08\\x08\\x08\\x08|\\x08d\\x88\\x00\\x00\\x00qID\\\nATX\\x85\\xed\\xd6;\\n\\x800\\x10E\\xd1{\\xc5\\x8d\\xb9r\\x97\\x16\\x0b\\xad$\\x8a\\x82:\\x16\\\no\\xda\\x84pB2\\x1f\\x81Fa\\x8c\\x9c\\x08\\x04Z{\\xcf\\xa72\\xbcv\\xfa\\xc5\\x08 \\x80r\\x80\\\n\\xfc\\xa2\\x0e\\x1c\\xe4\\xba\\xfaX\\x1d\\xd0\\xde]S\\x07\\x02\\xd8>\\xe1wa-`\\x9fQ\\xe9\\\n\\x86\\x01\\x04\\x10\\x00\\\\(Dk\\x1b-\\x04\\xdc\\x1d\\x07\\x14\\x98;\\x0bS\\x7f\\x7f\\xf9\\x13\\\n\\x04\\x10@\\xf9X\\xbe\\x00\\xc9 \\x14K\\xc1<={\\x00\\x00\\x00\\x00IEND\\xaeB`\\x82'\n\n\ndef GetMondrianBitmap():\n return wx.Bitmap(GetMondrianImage())\n\n\ndef GetMondrianImage():\n stream = BytesIO(GetMondrianData())\n return wx.Image(stream)\n\n\ndef GetMondrianIcon():\n icon = wx.Icon()\n icon.CopyFromBitmap(GetMondrianBitmap())\n return icon\n\n\n\n\n#-----xit_MyCenterTextNotebook---------中心部分的NoteBook,包含有矩阵前页,矩阵第一页、第二页等------------------------------------------------------------------------------------- \nclass xit_MyCenterTextNotebook(wx.Notebook):\n def __init__(self, parent):\n wx.Notebook.__init__(self, parent, -1, style=wx.BK_DEFAULT )\n self._pageList=[]\n textctrlPage=wx.TextCtrl(self,-1,style=wx.TE_MULTILINE|wx.HSCROLL)\n textctrlPage.SetFont(xit_G.G_fontandcolour._firstfont)\n textctrlPage.SetForegroundColour(xit_G.G_fontandcolour._firstcolour)\n self._pageList.append(textctrlPage)\n self.AddPage(textctrlPage, \"矩阵前页\")\n self.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnPageChanged)\n self.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGING, self.OnPageChanging)\n\n \n\n #用崭新的myMatrixUnit替换所有页面,这适用于矩阵页的完全更换\n def setALLPagesFromMatrixUnit(self,myMatrixUnit):\n cur=myMatrixUnit.cur\n #除首页外,其它页全部删除\n n=self.GetPageCount()\n for i in range(1,n):\n j=n-i\n self.DeletePage(j)\n self._pageList=[self._pageList[0]]\n\n self._pageList[0].SetValue(str(myMatrixUnit._mat))#首页赋值\n\n n=len(myMatrixUnit.matList)\n \n for i in range(n):\n \n myTextPage=xit_MyTripleElementScrolledWindow(self,myMatrixUnit[i])\n self._pageList.append(myTextPage)\n name=(\"第%d个矩阵\" %(i+1))\n self.AddPage(myTextPage, name)\n \n if cur==\"ZERO\":\n self.SetSelection(0)\n else:\n self.SetSelection(cur+1) \n \n def setSelectionPageFromMatrixUnit(self,myMatrixUnit):\n new=self.GetSelection()\n if new==0:\n self._pageList[0].SetValue(str(myMatrixUnit._mat))\n else:\n self._pageList[new].setMyText(myMatrixUnit[new-1])\n def setSelectionPageFromMatrix(self,myMatrix):\n new=self.GetSelection()\n if new==0:\n self._pageList[0].SetValue(str(myMatrix))\n else:\n self._pageList[new].setMyText(myMatrix)\n\n def AddPageFromMatrix(self,myMatrix):#增加时间:2020年1月20日,增加一个页面,避免刷屏\n n=self.GetPageCount()\n myTextPage=xit_MyTripleElementScrolledWindow(self,myMatrix)\n myTextPage.setMyText(myMatrix)\n self._pageList.append(myTextPage)\n name=(\"第%d个矩阵\" %(n))\n self.AddPage(myTextPage, name)\n self.SetSelection(n)\n \n def OnPageChanged(self, event):\n if self:\n old = event.GetOldSelection()\n new = event.GetSelection()\n sel = self.GetSelection()\n if new==0:\n xit_G.G_myOP.setUnitAndGridFromCUR(\"ZERO\")\n else:\n xit_G.G_myOP.setUnitAndGridFromCUR(new-1)\n event.Skip()\n def OnPageChanging(self, event):\n if self:\n old = event.GetOldSelection()\n new = event.GetSelection()\n sel = self.GetSelection()\n \n event.Skip()\n# \n#-----xit_AUIFrame----------------主面板------------------------------------------------------- \nclass xit_AUIFrame(wx.Frame):\n\n def __init__(self, parent, id=-1, title=\"线性代数小专家\",style=wx.DEFAULT_FRAME_STYLE |\n wx.SUNKEN_BORDER |wx.MAXIMIZE|\n wx.CLIP_CHILDREN):\n\n wx.Frame.__init__(self,parent,id=id,title=title,pos=wx.DefaultPosition,\n size=wx.Size(900,650),style=style)\n\n # tell FrameManager to manage this frame\n self._mgr = aui.AuiManager()\n self._mgr.SetManagedWindow(self)\n\n self._perspectives = []\n self.n = 0\n self.x = 0\n self._matTree=[]\n self.font = wx.Font(wx.FontInfo(10).FaceName(\"新宋体\"))\n xit_G.G_fontandcolour=G_fontcolour()\n\n #生成菜单\n self._menudict={}\n mb = wx.MenuBar()\n menuctrl=MyMenuControl(self,\"mainframe\")\n #文件菜单 \n file_menu = wx.Menu()\n tmp=file_menu.Append(wx.ID_ANY,\"新建(&N)\")\n self._menudict[tmp.GetId()]=tmp\n self.Bind(wx.EVT_MENU, menuctrl.Control, id=tmp.GetId())\n tmp=file_menu.Append(wx.ID_ANY,\"打开...\")\n self._menudict[tmp.GetId()]=tmp\n self.Bind(wx.EVT_MENU, menuctrl.Control, id=tmp.GetId())\n tmp=file_menu.Append(wx.ID_ANY,\"合并打开...\")\n self._menudict[tmp.GetId()]=tmp\n self.Bind(wx.EVT_MENU, menuctrl.Control, id=tmp.GetId())\n tmp=file_menu.Append(wx.ID_ANY,\"保存\")\n self._menudict[tmp.GetId()]=tmp\n self.Bind(wx.EVT_MENU, menuctrl.Control, id=tmp.GetId())\n tmp=file_menu.Append(wx.ID_ANY,\"另存为...\")\n self._menudict[tmp.GetId()]=tmp\n self.Bind(wx.EVT_MENU, menuctrl.Control, id=tmp.GetId())\n tmp=file_menu.Append(wx.ID_ANY,\"退出\")\n self._menudict[tmp.GetId()]=tmp\n self.Bind(wx.EVT_MENU, menuctrl.Control, id=tmp.GetId())\n #视图菜单--视图菜单的方法在这里更方便\n view_menu = wx.Menu()\n tmp=view_menu.Append(wx.ID_ANY,\"显示左侧矩阵树\")\n self._menudict[tmp.GetId()]=tmp\n self.Bind(wx.EVT_MENU, self.ViewControl, id=tmp.GetId())\n tmp=view_menu.Append(wx.ID_ANY,\"显示矩阵网格\")\n self._menudict[tmp.GetId()]=tmp\n self.Bind(wx.EVT_MENU, self.ViewControl, id=tmp.GetId())\n tmp=view_menu.Append(wx.ID_ANY,\"显示下侧面板\")\n self._menudict[tmp.GetId()]=tmp\n self.Bind(wx.EVT_MENU, self.ViewControl, id=tmp.GetId())\n tmp=view_menu.Append(wx.ID_ANY,\"显示控制台\")\n self._menudict[tmp.GetId()]=tmp\n self.Bind(wx.EVT_MENU, self.ViewControl, id=tmp.GetId())\n tmp=view_menu.Append(wx.ID_ANY,\"恢复默认设置\")\n self._menudict[tmp.GetId()]=tmp\n self.Bind(wx.EVT_MENU, self.ViewControl, id=tmp.GetId())\n\n #self.Bind(wx.EVT_CONTEXT_MENU, MyMenuControl(self).OnContextMenu)\n\n mb.Append(file_menu, \"文件(&F)\")\n mb.Append(view_menu, \"视图(&V)\")\n \n self.SetMenuBar(mb)\n #生成子面板\n \n self._mymattree=self.CreateTreeCtrl()\n self._mygrid=xit_MyGrid(self)\n self._mycentertextnotebook=xit_MyCenterTextNotebook(self)\n self._myshell=self.CreateShell()\n self._mynotebook=xit_MyNotebookPanel(self)\n\n \n xit_G.G_myOP=xit_MyOP(myCenterTextNotebook=self._mycentertextnotebook,cur=\"ZERO\",grid=self._mygrid,tree=self._mymattree,treedict=self.treedict,menudict=self._menudict,mainwindow=self)\n \n \n self.SetIcon(GetMondrianIcon())\n self.SetMinSize(wx.Size(800, 600))\n\n self._mymattree.SetFont(self.font)\n self._myshell.SetFont(self.font)\n self._mynotebook.SetFont(self.font)\n # add a bunch of panes\n self._mgr.AddPane(self._mymattree, aui.AuiPaneInfo().Name(\"练习题集合\").Caption(\"练习题集合\").BestSize(wx.Size(250,600)).Left())\n self._mgr.AddPane(self._myshell, aui.AuiPaneInfo().Name(\"控制台\").Caption(\"控制台\").BestSize(wx.Size(600,800)).Right())\n self._mgr.AddPane(self._mynotebook, aui.AuiPaneInfo().Name(\"选项卡\").Caption(\"选项卡\").BestSize(wx.Size(650,350)).Bottom())\n self._mgr.AddPane(self._mygrid, aui.AuiPaneInfo().Name(\"矩阵网格\").Caption(\"矩阵网格\").BestSize(wx.Size(250,200)).Left().Position(1))\n # create some center panes\n \n self._mgr.AddPane(self._mycentertextnotebook, aui.AuiPaneInfo().Name(\"结果\").CenterPane())\n\n # make some default perspectives\n\n self._mgr.GetPane(\"练习题集合\").Show()\n self._mgr.GetPane(\"选项卡\").Show()\n self._mgr.GetPane(\"控制台\").Show()\n self._mgr.GetPane(\"结果\").Show()\n self._mgr.GetPane(\"矩阵网格\").Show()\n #self._mgr.GetPane(\"测试框\").Hide()\n self.perspective_default = self._mgr.SavePerspective()\n\n # \"commit\" all changes made to FrameManager\n self._mgr.Update()\n\n \n\n self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)\n self.Bind(wx.EVT_SIZE, self.OnSize)\n self.Bind(wx.EVT_CLOSE, self.OnClose)\n\n # Show How To Use The Closing Panes Event\n self.Bind(aui.EVT_AUI_PANE_CLOSE, self.OnPaneClose)\n \n \n def ViewControl(self,event):\n menuname=self._menudict[event.GetId()].GetName()\n if menuname==\"显示左侧矩阵树\":\n '''self._mgr.AddPane(self.CreateTreeCtrl(), aui.AuiPaneInfo().\n Caption(\"Tree Control\").\n Float().FloatingPosition(self.GetStartPosition()).\n FloatingSize(wx.Size(150, 300)).CloseButton(True).MaximizeButton(True))\n ''' \n self._mgr.GetPane(\"练习题集合\").Float().FloatingSize(wx.Size(250,500)).CloseButton(True).MaximizeButton(True).Show()\n self._mgr.Update()\n elif menuname==\"显示矩阵网格\":\n self._mgr.GetPane(\"矩阵网��\").Float().FloatingSize(wx.Size(400,300)).CloseButton(True).MaximizeButton(True).Show()\n self._mgr.Update()\n elif menuname==\"显示下侧面板\":\n self._mgr.GetPane(\"选项卡\").Float().FloatingSize(wx.Size(1000,300)).CloseButton(True).MaximizeButton(True).Show()\n self._mgr.Update()\n elif menuname==\"显示控制台\":\n self._mgr.GetPane(\"控制台\").Float().FloatingSize(wx.Size(400,1000)).CloseButton(True).MaximizeButton(True).Show()\n self._mgr.Update()\n elif menuname==\"恢复默认设置\":\n self._mgr.LoadPerspective(self.perspective_default)\n def DoUpdate(self):\n\n self._mgr.Update()\n\n\n def OnEraseBackground(self, event):\n\n event.Skip()\n\n\n def OnSize(self, event):\n\n event.Skip()\n\n\n def CreateTreeCtrl(self):\n\n tree = wx.TreeCtrl(self, -1, wx.Point(0, 0), wx.Size(250, 100),\n wx.TR_DEFAULT_STYLE | wx.NO_BORDER|wx.TR_HIDE_ROOT)\n\n root = tree.AddRoot(\"线性代数习题集\")\n items = []\n self.treedict={}\n\n imglist = wx.ImageList(16, 16, True, 2)\n imglist.Add(wx.ArtProvider.GetBitmap(wx.ART_FOLDER, wx.ART_OTHER, wx.Size(16,16)))\n imglist.Add(wx.ArtProvider.GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, wx.Size(16,16)))\n tree.AssignImageList(imglist)\n for (_id,_father,_label) in xit_G.getTreeList():\n if _father==\"root\":\n self.treedict[_id]=tree.AppendItem(root,_label, 0)\n else:\n self.treedict[_id]=tree.AppendItem(self.treedict[_father], _label,0)\n \n \n self.Bind(wx.EVT_TREE_ITEM_EXPANDED, self.OnItemExpanded_Tree,tree)\n self.Bind(wx.EVT_TREE_ITEM_COLLAPSED,self.OnItemCollapsed_Tree,tree)\n self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged_Tree,tree)\n self.Bind(wx.EVT_TREE_ITEM_ACTIVATED,self.OnActivated_Tree,tree)\n self.Bind(wx.EVT_TREE_ITEM_EXPANDING,self.OnItemExpanding_Tree,tree)\n init_printing(use_unicode=True)\n Lst=FileHelper.getUnitListFromSRC()\n\n for _matUnit in Lst:\n \n self.treedict[_matUnit.ID]=tree.AppendItem(self.treedict[_matUnit.matType], _matUnit.Riddle,1,data=\"\")\n tree.SetItemData(self.treedict[_matUnit.ID],_matUnit)\n \n #添加时间:2020年2月1日,初始化我的矩阵\n try:\n f=open(\"mytreedefault.dat\",\"rb\")\n while True:\n _unit=pickle.load(f)\n if _unit==None:\n break\n tmp=tree.AppendItem(self.treedict[\"MYTREE\"], _unit.Riddle,1,data=\"\")\n tree.SetItemData(tmp,_unit)\n except:\n pass\n finally:\n pass\n \n\n return tree\n\n def OnItemExpanded_Tree(self,evt):\n pass\n def OnItemCollapsed_Tree(self,evt):\n pass\n def OnSelChanged_Tree(self,evt):\n \n item=evt.GetItem()\n \n xit_G.G_myOP._myMatrixUnit=self._mymattree.GetItemData(item)\n if xit_G.G_myOP._myMatrixUnit!=None:\n xit_G.G_myOP._myMatrixUnit.cur=0\n xit_G.G_myOP.setFromxitMatrixUnit(xit_G.G_myOP._myMatrixUnit,0)\n self._mgr.Update() \n \n self._myshell.prompt()\n \n \n \n #self._mgr.Update()\n \n def OnActivated_Tree(self,evt):\n pass\n def OnItemExpanding_Tree(self,evt):\n pass\n\n def CreateShell(self):\n ctrl=Shell(parent=self)\n ctrl.redirectStdout(redirect=True)\n ctrl.redirectStdin(redirect=True)\n ctrl.redirectStderr(redirect=True)\n init_printing(use_unicode=False)\n \n return ctrl\n\n \n \n\n def OnPaneClose(self, event):\n\n caption = event.GetPane().caption\n\n if caption in [\"Tree Pane\", \"Dock Manager Settings\", \"Fixed Pane\"]:\n msg = \"Are You Sure You Want To Close This Pane?\"\n dlg = wx.MessageDialog(self, msg, \"AUI Question\",\n wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)\n\n if dlg.ShowModal() in [wx.ID_NO, wx.ID_CANCEL]:\n event.Veto()\n dlg.Destroy()\n\n\n def OnClose(self, event):\n self._mgr.UnInit()\n del self._mgr\n self.Destroy()\n\n\n def OnExit(self, event):\n self.Close()\n\n def OnAbout(self, event):\n\n msg = \"wx.aui Demo\\n\" + \\\n \"An advanced window management library for wxWidgets\\n\" + \\\n \"(c) Copyright 2005-2006, Kirix Corporation\"\n dlg = wx.MessageDialog(self, msg, \"About wx.aui Demo\",\n wx.OK | wx.ICON_INFORMATION)\n dlg.ShowModal()\n dlg.Destroy()\n\n\n#------------------------------------------------------------------------------------------------ \nOP=None\nU=None\nM=None\ndef Update():\n print(\"你牛!你操作吧���!\\n\")\n print(\"A--当前运行的矩阵(中心页面没有定位矩阵则为None)\")\n global OP,U,M\n OP=xit_G.G_myOP\n U=xit_G.G_myOP._myMatrixUnit\n if xit_G.G_myOP._myMatrixUnit!=None and type(xit_G.G_myOP._myMatrixUnit.cur)==type(0):\n M=xit_G.G_myOP._myMatrixUnit[xit_G.G_myOP._myMatrixUnit.cur]\nif __name__ == '__main__':\n app=wx.App()\n frame = xit_AUIFrame(parent=None)\n\n frame.Show()\n app.MainLoop()\n","sub_path":"xit_ds_wxpython/xit_main.py","file_name":"xit_main.py","file_ext":"py","file_size_in_byte":15841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"47608017","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright © 2017 Matthew Stone \n# Distributed under terms of the MIT license.\n\n\"\"\"\nClassification of reciprocal translocations.\n\"\"\"\n\n\ndef classify_insertion(plus, minus, mh_buffer=50):\n plus_A = plus.pos\n minus_A = minus.pos\n plus_B = plus.stop\n minus_B = minus.stop\n\n # Buffer comparisons\n def _greater(p1, p2):\n return p1 > p2 - mh_buffer\n\n if _greater(minus_A, plus_A) and _greater(minus_B, plus_B):\n return 'INS_B2A'\n elif _greater(plus_A, minus_A) and _greater(plus_B, minus_B):\n return 'INS_A2B'\n else:\n return 'INS_UNCLASSIFIED'\n\n\ndef classify_simple_translocation(plus, minus, mh_buffer=10):\n \"\"\"\n Resolve a pair of interchromosomal breakends.\n\n Parameters\n ----------\n FF : pysam.VariantRecord\n FF inversion breakpoint.\n RR : pysam.VariantRecord\n RR inversion breakpoint.\n cnvs : list of pysam.VariantRecord\n List of overlapping CNVs.\n\n Returns\n -------\n svtype : str\n Complex SV class.\n \"\"\"\n\n # plus refers to breakend whose strand begins with '+'\n if plus.chrom != minus.chrom or plus.info['CHR2'] != minus.info['CHR2']:\n return 'TLOC_MISMATCH_CHROM'\n\n # Reference chromosomes are labeled A and B\n # Breakpoints/Derivative chromosomes are labeled plus and minus, based on\n # ref chromosome A's strandedness on each breakpoint\n # plus_A = the breakend of ref chrom A on derivative chrom where A is\n # forward-stranded\n\n # get positions\n plus_A = plus.pos\n minus_A = minus.pos\n plus_B = plus.stop\n minus_B = minus.stop\n\n plus_strands = plus.info['STRANDS']\n\n # Buffer comparisons\n def _greater(p1, p2):\n return p1 > p2 - mh_buffer\n\n if plus_strands == '+-':\n if _greater(minus_A, plus_A) and _greater(plus_B, minus_B):\n return 'CTX_PP/QQ'\n if _greater(minus_A, plus_A) and _greater(minus_B, plus_B):\n return 'CTX_INS_B2A'\n if _greater(plus_A, minus_A) and _greater(plus_B, minus_B):\n return 'CTX_INS_A2B'\n else:\n if _greater(minus_A, plus_A) and _greater(minus_B, plus_B):\n return 'CTX_PQ/QP'\n if _greater(minus_A, plus_A) and _greater(plus_B, minus_B):\n return 'CTX_INV_INS_B2A'\n if _greater(plus_A, minus_A) and _greater(minus_B, plus_B):\n return 'CTX_INV_INS_A2B'\n\n return 'CTX_UNR'\n","sub_path":"svtk/cxsv/cpx_tloc.py","file_name":"cpx_tloc.py","file_ext":"py","file_size_in_byte":2463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"620191472","text":"\"\"\"\nScript for plotting evaluated fluxes. \nIt uses mean fluxes saved in the numpy array Fluxesxx.npy (model)\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\nimport sys\nimport os\n\nsys.path.append('D:\\Evaporation\\Source_Codes\\TwoSourceEnergy' +\n 'BalanceModel\\pyTSEBmod')\nfrom Statistics import NSE, Bias, MAE, RMSD, R2\n\n#%% Get data\n\nhome = 'D:\\Auswertung_Feldarbeiten_Pt_Nobressart\\TIR_Processing'\nflightDates = np.load(os.path.join(home, 'InputsProcessing', \n 'FlightDates.npy')).item()\n \n## Input here fluxes that should be plotted\nPT_Flux = np.load(os.path.join(home, 'Fluxes', 'rs03', \n 'FluxesPT_LAI08_20_FG09_NDI06_lowEl_selected.npy')).item()\nOS_Flux = np.load(os.path.join(home, 'Fluxes', 'rs03', \n 'FluxesOS_NDI06_lowEl_Kustas_selected_cut0.npy')).item()\n##FluxesPT_LAI08_20_FG09_NDI06_lowEl_selected \n\nflights = []\nfor date in flightDates:\n for hours in flightDates[date]:\n flights.append(flightDates[date][hours])\nflights.sort()\ndates = np.array(flights, dtype = np.datetime64)\n \ndef extractFluxes(modeFluxes_dict, flux_source, *args):\n keys = modeFluxes_dict.keys()\n keys.sort()\n fluxes = []\n if args:\n [fluxes.append(modeFluxes_dict[key][flux_source][args[0]]) for key in keys]\n else:\n [fluxes.append(modeFluxes_dict[key][flux_source]) for key in keys]\n return fluxes\n \nH_mod_PT = np.array(extractFluxes(PT_Flux, 'Modelled_Flux_masked', 0)).astype('float64')\nH_mod_OS = np.array(extractFluxes(OS_Flux, 'Modelled_Flux_masked', 0)).astype('float64')\nH_EC = np.array(extractFluxes(PT_Flux, 'EC_Flux', 0))\nH_Scinti = np.array(extractFluxes(PT_Flux, 'Scinti_H_Flux'))\n\nRn_mod_PT = np.array(extractFluxes(PT_Flux, 'Modelled_Flux_masked', 3)).astype('float64')\nRn_mod_OS = np.array(extractFluxes(OS_Flux, 'Modelled_Flux_masked', 3)).astype('float64')\nRn_EC = np.array(extractFluxes(PT_Flux, 'EC_Flux', 3))\nG_mod_PT = np.array(extractFluxes(PT_Flux, 'Modelled_Flux_masked', 2)).astype('float64')\nG_mod_OS = np.array(extractFluxes(OS_Flux, 'Modelled_Flux_masked', 2)).astype('float64')\nG_EC = np.array(extractFluxes(PT_Flux, 'EC_Flux', 2))\n\nLE_mod_PT = np.array(extractFluxes(PT_Flux, 'Modelled_Flux_masked', 1)).astype('float64')\nLE_mod_OS = np.array(extractFluxes(OS_Flux, 'Modelled_Flux_masked', 1)).astype('float64')\nLE_EC = np.array(extractFluxes(PT_Flux, 'EC_Flux', 1))\nLE_Scinti = Rn_EC - G_EC - H_Scinti\n\n# corrected according to Bowen ratio and residual method\nebcGap = Rn_EC - G_EC - LE_EC - H_EC\nEBR = (LE_EC + H_EC)/(Rn_EC - G_EC)\nEF = LE_EC/(LE_EC + H_EC)\n\n# Threshold according to Ingwersen et al. 2015\nthres = 0.5\nthres_EBR = ((EBR > thres) & (EBR < (2 - thres)))\n\nLE_EC_corr_EB = LE_EC + EF*ebcGap\nLE_EC_corr_EB[~thres_EBR] = LE_EC[~thres_EBR]\nH_EC_corr_EB = H_EC + (1 - EF)*ebcGap\nH_EC_corr_EB[~thres_EBR] = H_EC[~thres_EBR]\nLE_EC_corr_res = LE_EC + ebcGap\nH_EC_corr_res = H_EC + ebcGap\n\nFluxes = pd.DataFrame({'Rn' : Rn_EC, 'Rn_PT' : Rn_mod_PT, 'Rn_OS' : Rn_mod_OS, \n 'G' : G_EC, 'G_PT' : G_mod_PT, 'G_OS' : G_mod_OS, 'H' : H_EC, \n 'LE' : LE_EC, 'H_BR' : H_EC_corr_EB,\n 'LE_BR' : LE_EC_corr_EB, 'H_res' : H_EC_corr_res,\n 'LE_res' : LE_EC_corr_res, 'H_Sc' : H_Scinti,\n 'LE_Sc' : LE_Scinti, 'H_PT' : H_mod_PT, \n 'LE_PT' : LE_mod_PT, 'H_OS' : H_mod_OS,\n 'LE_OS' : LE_mod_OS, 'Flights' : flights}, index = pd.DatetimeIndex(dates))\n\n\n#%% Difference statistics\n\nDiff_stats = {'Mean_OBS' : {}, 'NSE_PT' : {}, 'NSE_OS' : {},\n 'Bias_PT' : {}, 'Bias_PT' : {},\n 'MAE_PT' : {}, 'RMSD_PT' : {}}\n\nDiff_stats['Mean_OBS'] = {\n 'Rn' : np.round(Rn_EC.mean(), decimals = 2),\n 'G' : np.round(G_EC.mean(), decimals = 2),\n 'H' : np.round(H_EC.mean(), decimals = 2),\n 'LE' : np.round(LE_EC.mean(), decimals = 2),\n 'H_BR' : np.round(H_EC_corr_EB.mean(), decimals = 2),\n 'LE_BR' : np.round(LE_EC_corr_EB.mean(), decimals = 2),\n 'H_res' : np.round(H_EC_corr_res.mean(), decimals = 2), \n 'LE_res': np.round(LE_EC_corr_res.mean(), decimals = 2),\n 'H_Sc' : np.round(H_Scinti.mean(), decimals = 2),\n 'LE_Sc' : np.round(LE_Scinti.mean(), decimals = 2)} \n\nDiff_stats['NSE_PT'] = {\n 'Rn' : NSE(Rn_EC, Rn_mod_PT),\n 'G' : NSE(G_EC, G_mod_PT),\n 'H' : NSE(H_EC, H_mod_PT),\n 'LE' : NSE(LE_EC, LE_mod_PT),\n 'H_BR' : NSE(H_EC_corr_EB, H_mod_PT),\n 'LE_BR' : NSE(LE_EC_corr_EB, LE_mod_PT),\n 'H_res' : NSE(H_EC_corr_res, H_mod_PT),\n 'LE_res': NSE(LE_EC_corr_res, LE_mod_PT),\n 'H_Sc' : NSE(H_Scinti, H_mod_PT),\n 'LE_Sc' : NSE(LE_Scinti, LE_mod_PT)} \n\nDiff_stats['NSE_OS'] = {\n 'Rn' : NSE(Rn_EC, Rn_mod_OS),\n 'G' : NSE(G_EC, G_mod_OS),\n 'H' : NSE(H_EC, H_mod_OS),\n 'LE' : NSE(LE_EC, LE_mod_OS),\n 'H_BR' : NSE(H_EC_corr_EB, H_mod_OS),\n 'LE_BR' : NSE(LE_EC_corr_EB, LE_mod_OS),\n 'H_res' : NSE(H_EC_corr_res, H_mod_OS),\n 'LE_res': NSE(LE_EC_corr_res, LE_mod_OS),\n 'H_Sc' : NSE(H_Scinti, H_mod_OS),\n 'LE_Sc' : NSE(LE_Scinti, LE_mod_OS)} \n\nDiff_stats['Bias_PT'] = {\n 'Rn' : Bias(Rn_EC, Rn_mod_PT),\n 'G' : Bias(G_EC, G_mod_PT),\n 'H' : Bias(H_EC, H_mod_PT),\n 'LE' : Bias(LE_EC, LE_mod_PT),\n 'H_BR' : Bias(H_EC_corr_EB, H_mod_PT),\n 'LE_BR' : Bias(LE_EC_corr_EB, LE_mod_PT),\n 'H_res' : Bias(H_EC_corr_res, H_mod_PT),\n 'LE_res': Bias(LE_EC_corr_res, LE_mod_PT),\n 'H_Sc' : Bias(H_Scinti, H_mod_PT),\n 'LE_Sc' : Bias(LE_Scinti, LE_mod_PT)} \n\nDiff_stats['Bias_OS'] = {\n 'Rn' : Bias(Rn_EC, Rn_mod_OS),\n 'G' : Bias(G_EC, G_mod_OS),\n 'H' : Bias(H_EC, H_mod_OS),\n 'LE' : Bias(LE_EC, LE_mod_OS),\n 'H_BR' : Bias(H_EC_corr_EB, H_mod_OS),\n 'LE_BR' : Bias(LE_EC_corr_EB, LE_mod_OS),\n 'H_res' : Bias(H_EC_corr_res, H_mod_OS),\n 'LE_res': Bias(LE_EC_corr_res, LE_mod_OS),\n 'H_Sc' : Bias(H_Scinti, H_mod_OS),\n 'LE_Sc' : Bias(LE_Scinti, LE_mod_OS)} \n \nDiff_stats['MAE_PT'] = {\n 'Rn' : MAE(Rn_EC, Rn_mod_PT),\n 'G' : MAE(G_EC, G_mod_PT),\n 'H' : MAE(H_EC, H_mod_PT),\n 'LE' : MAE(LE_EC, LE_mod_PT),\n 'H_BR' : MAE(H_EC_corr_EB, H_mod_PT),\n 'LE_BR' : MAE(LE_EC_corr_EB, LE_mod_PT),\n 'H_res' : MAE(H_EC_corr_res, H_mod_PT),\n 'LE_res': MAE(LE_EC_corr_res, LE_mod_PT),\n 'H_Sc' : MAE(H_Scinti, H_mod_PT),\n 'LE_Sc' : MAE(LE_Scinti, LE_mod_PT)} \n\nDiff_stats['MAE_OS'] = {\n 'Rn' : MAE(Rn_EC, Rn_mod_OS),\n 'G' : MAE(G_EC, G_mod_OS),\n 'H' : MAE(H_EC, H_mod_OS),\n 'LE' : MAE(LE_EC, LE_mod_OS),\n 'H_BR' : MAE(H_EC_corr_EB, H_mod_OS),\n 'LE_BR' : MAE(LE_EC_corr_EB, LE_mod_OS),\n 'H_res' : MAE(H_EC_corr_res, H_mod_OS),\n 'LE_res': MAE(LE_EC_corr_res, LE_mod_OS),\n 'H_Sc' : MAE(H_Scinti, H_mod_OS),\n 'LE_Sc' : MAE(LE_Scinti, LE_mod_OS)} \n \nDiff_stats['RMSD_PT'] = {\n 'Rn' : RMSD(Rn_EC, Rn_mod_PT),\n 'G' : RMSD(G_EC, G_mod_PT),\n 'H' : RMSD(H_EC, H_mod_PT),\n 'LE' : RMSD(LE_EC, LE_mod_PT),\n 'H_BR' : RMSD(H_EC_corr_EB, H_mod_PT),\n 'LE_BR' : RMSD(LE_EC_corr_EB, LE_mod_PT),\n 'H_res' : RMSD(H_EC_corr_res, H_mod_PT),\n 'LE_res': RMSD(LE_EC_corr_res, LE_mod_PT),\n 'H_Sc' : RMSD(H_Scinti, H_mod_PT),\n 'LE_Sc' : RMSD(LE_Scinti, LE_mod_PT)} \n\nDiff_stats['RMSD_OS'] = {\n 'Rn' : RMSD(Rn_EC, Rn_mod_OS),\n 'G' : RMSD(G_EC, G_mod_OS),\n 'H' : RMSD(H_EC, H_mod_OS),\n 'LE' : RMSD(LE_EC, LE_mod_OS),\n 'H_BR' : RMSD(H_EC_corr_EB, H_mod_OS),\n 'LE_BR' : RMSD(LE_EC_corr_EB, LE_mod_OS),\n 'H_res' : RMSD(H_EC_corr_res, H_mod_OS),\n 'LE_res': RMSD(LE_EC_corr_res, LE_mod_OS),\n 'H_Sc' : RMSD(H_Scinti, H_mod_OS),\n 'LE_Sc' : RMSD(LE_Scinti, LE_mod_OS)} \n \nDiff_stats['R2_PT'] = {\n 'Rn' : R2(Rn_EC, Rn_mod_PT),\n 'G' : R2(G_EC, G_mod_PT),\n 'H' : R2(H_EC, H_mod_PT),\n 'LE' : R2(LE_EC, LE_mod_PT),\n 'H_BR' : R2(H_EC_corr_EB, H_mod_PT),\n 'LE_BR' : R2(LE_EC_corr_EB, LE_mod_PT),\n 'H_res' : R2(H_EC_corr_res, H_mod_PT),\n 'LE_res': R2(LE_EC_corr_res, LE_mod_PT),\n 'H_Sc' : R2(H_Scinti, H_mod_PT),\n 'LE_Sc' : R2(LE_Scinti, LE_mod_PT)} \n\nDiff_stats['R2_OS'] = {\n 'Rn' : R2(Rn_EC, Rn_mod_OS),\n 'G' : R2(G_EC, G_mod_OS),\n 'H' : R2(H_EC, H_mod_OS),\n 'LE' : R2(LE_EC, LE_mod_OS),\n 'H_BR' : R2(H_EC_corr_EB, H_mod_OS),\n 'LE_BR' : R2(LE_EC_corr_EB, LE_mod_OS),\n 'H_res' : R2(H_EC_corr_res, H_mod_OS),\n 'LE_res': R2(LE_EC_corr_res, LE_mod_OS),\n 'H_Sc' : R2(H_Scinti, H_mod_OS),\n 'LE_Sc' : R2(LE_Scinti, LE_mod_OS)} \n\ndiff_Stats = pd.DataFrame(Diff_stats, columns = ['Mean_OBS', 'Bias_PT', \n 'Bias_OS', 'MAE_PT', 'MAE_OS', 'RMSD_PT', 'RMSD_OS', 'NSE_PT', \n 'NSE_OS'])\n \ndel [Diff_stats, NSE, MAE, Bias]\n\n#%% Plotting against raw EC fluxes\n\ncolors = ['#3498db', '#2ecc71', '#f7cf33', '#fc9d1d','#fd484d', '#9b59b6', '#51677b']\npal = sns.color_palette(colors)\n\ncolors_rgb = [(52, 152, 219), (46, 204, 113), (247, 207, 51), (252, 157, 29),\n (253, 72, 77),(155, 89, 182), (81, 103, 123)]\n# http://www.husl-colors.org/\npal_red_light = sns.light_palette((11.4, 97.4, 58.1), input=\"husl\")\npal_red_dark = sns.dark_palette((11.4, 97.4, 58.1), input=\"husl\")\npal_blue_light = sns.light_palette((242.2, 90.1, 60.2), input=\"husl\")\npal_blue_dark = sns.dark_palette((242.2, 90.1, 60.2), input=\"husl\")\npal_orange_light = sns.light_palette((41.2, 96.8, 72.8), input=\"husl\")\npal_orange_dark = sns.dark_palette((41.2, 96.8, 72.8), input=\"husl\")\npal_green_light = sns.light_palette((137.9, 93.2, 72.9), input=\"husl\")\npal_green_dark = sns.dark_palette((137.9, 93.2, 72.9), input=\"husl\")\n\nsns.set(context = \"paper\", style = 'white', palette = pal,\n rc = {'axes.labelsize': 18.0, 'figure.figsize': [14, 14], \n 'legend.fontsize': 16.0, 'xtick.labelsize': 18.0,\n 'ytick.labelsize': 18.0, 'xtick.major.size': 4.0,\n 'ytick.major.size': 4.0})\n\n# Options: EC_raw,\n\nobs_options = {'EC_raw' : \n {'title' : 'Modeled fluxes vs EC flux without EB closure',\n 'H' : H_EC, 'LE' : LE_EC,\n 'outFile' : 'Flux_EC_Comparison.png'},\n 'EC_corr_EB': \n {'title' : 'Modeled fluxes vs EC fluxes with Bowen Ratio closure',\n 'H' : H_EC_corr_EB, 'LE' : LE_EC_corr_EB,\n 'outFile' : 'Flux_EC_corr_BR_Comparison'},\n 'EC_corr_LE_res': \n {'title' : 'Modeled fluxes vs EC flux with LE residual closure',\n 'H' : H_EC, 'LE' : LE_EC_corr_res,\n 'outFile' : 'Flux_EC_corr_LE_residual_Comparison.png'},\n 'EC_corr_H_res': \n {'title' : 'Modeled fluxes vs EC flux with H residual closure',\n 'H' : H_EC_corr_res, 'LE' : LE_EC,\n 'outFile' : 'Flux_EC_corr_H_residual_Comparison.png'},\n 'Scinti': \n {'title' : 'Modeled fluxes vs scintillometer fluxes',\n 'H' : H_Scinti, 'LE' : LE_Scinti,\n 'outFile' : 'Flux_Scinti_Comparison.png'},\n }\n\n## Select observed fluxes to which modelled fluxes are compared \nobs_chosen = 'EC_corr_EB'\n##\n\ntitle = obs_options[obs_chosen]['title']\nH_obs = obs_options[obs_chosen]['H']\nLE_obs = obs_options[obs_chosen]['LE']\noutFile = obs_options[obs_chosen]['outFile']\n\nfig = plt.figure()\n\nax = fig.add_subplot(111, aspect = 1)\nax.spines['top'].set_visible(False)\nax.spines['right'].set_visible(False)\nax.spines['bottom'].set_visible(False)\nax.spines['left'].set_visible(False)\nax.set_ylabel(r'Modeled fluxes (W m$^{-2}$)', labelpad=10, fontsize=20, zorder = 2)\nax.set_xlabel(r'Observed fluxes (W m$^{-2}$)', labelpad=10, fontsize=20, zorder = 2)\nax.get_yaxis().set_label_coords(-0.08,0.5)\nax.get_xaxis().set_label_coords(0.5, -0.07)\nfigure_title = title\nplt.text(0.5, 1.08, figure_title,\n horizontalalignment='center',\n fontsize=20,\n transform = ax.transAxes)\n\n\nax.set_axis_bgcolor('white')\nplt.tick_params(\n which='both', # both major and minor ticks are affected\n labelleft='off',\n labelright = 'off',\n labelbottom='off',\n bottom = 'off',\n top = 'off',\n right = 'off',\n left = 'off') # labels along the bottom edge are off\n\n\nax1 = fig.add_subplot(221, aspect = 1)\n\nH_PT_plot = plt.plot(H_obs, H_mod_PT, 'o', color = pal[4], \n label = 'TSEB', lw = 1, ms = 10)\n\n\n#h = sns.lmplot('H_BR', 'H_PT', data = Fluxes, hue = 'Day', fit_reg = False, \n# size = 10, scatter_kws={\"s\": 150, 'alpha' : 1, \n# 'linewidth' : 0.5, 'edgecolor' : None, \n# 'zorder' : 2}, legend = False,\n# markers =[\"o\", \"v\", '^', '*','p']\n# )\n\nH_OS_plot = plt.plot(H_obs, H_mod_OS, 'v', color = pal_red_dark[-3], \n label = 'OSEB', lw = 1, ms = 10)\n\nH_mod = np.concatenate((H_mod_PT, H_mod_OS)) \nlim_max = max(np.ceil(H_mod[~np.isnan(H_mod)].max()/50)*50, \n np.ceil(H_obs[~np.isnan(H_obs)].max()/50)*50)\nlim_min = min(np.floor(H_mod[~np.isnan(H_mod)].min()/50)*50, \n np.floor(H_obs[~np.isnan(H_obs)].min()/50)*50)\nax1.set_xlim([lim_min, lim_max])\nax1.set_ylim([lim_min, lim_max])\nax1.xaxis.set_ticks(np.arange(lim_min,ax1.get_ylim()[1]+1,100))\nax1.yaxis.set_ticks(np.arange(lim_min,ax1.get_ylim()[1]+1,100))\nax1.plot([lim_min, lim_max], [lim_min, lim_max], '--', \n color = (0.75, 0.75, 0.75) , lw = 1, zorder = 1)\nax1.text(0.04, 0.96,'R$^2$$_{TSEB}$: %.2f\\nR$^2$$_{OSEB}$: %.2f' % (diff_Stats.NSE_PT.H_BR, \n diff_Stats.NSE_OS.H_BR), horizontalalignment='left', fontsize = 16,\n verticalalignment='top', transform=ax1.transAxes)\nlegend = ax1.legend(loc = 'lower right') # , frameon = True\nplt.title('($a$) Sensible heat flux', fontsize = 18, y = 1.02)\n\nplt.tick_params(\n which='both', # both major and minor ticks are affected\n top = 'off',\n right = 'off') # labels along the bottom edge are off\n \nax2 = fig.add_subplot(222, aspect = 1)\nLE_PT_plot = plt.plot(LE_obs, LE_mod_PT, 'o', color = pal[0], \n label = 'TSEB', lw = 1, ms = 10)\n\nLE_OS_plot = plt.plot(LE_obs, LE_mod_OS, 'v', color = pal_blue_dark[-3], \n label = 'OSEB', lw = 1, ms = 10)\n \nLE_mod = np.concatenate((LE_mod_PT, LE_mod_OS)) \nlim_max = max(np.ceil(LE_mod[~np.isnan(LE_mod)].max()/50)*50, \n np.ceil(LE_obs[~np.isnan(LE_obs)].max()/50)*50)\nlim_min = min(np.floor(LE_mod[~np.isnan(LE_mod)].min()/50)*50, \n np.floor(LE_obs[~np.isnan(LE_obs)].min()/50)*50)\nax2.set_xlim([lim_min, lim_max])\nax2.set_ylim([lim_min, lim_max])\nax2.xaxis.set_ticks(np.arange(lim_min,ax2.get_ylim()[1]+1,150))\nax2.xaxis.set_ticks([0, 100, 200, 300, 400])\nax2.yaxis.set_ticks(np.arange(lim_min,ax2.get_ylim()[1]+1,150))\nax2.yaxis.set_ticks([0, 100, 200, 300, 400])\n\nax2.plot([lim_min, lim_max], [lim_min, lim_max], '--', \n color = (0.75, 0.75, 0.75) , lw = 1, zorder = 1)\nax2.text(0.04, 0.96,'R$^2$$_{TSEB}$: %.2f\\nR$^2$$_{OSEB}$: %.2f' % (diff_Stats.NSE_PT.LE_BR, \n diff_Stats.NSE_OS.LE_BR), horizontalalignment='left', fontsize = 16,\n verticalalignment='top', transform=ax2.transAxes)\nlegend = ax2.legend(loc = 'lower right') # , frameon = True\nplt.title('($b$) Latent heat flux', fontsize = 18, y = 1.02)\n\nplt.tick_params(\n which='both', # both major and minor ticks are affected\n top = 'off',\n right = 'off') # labels along the bottom edge are off\n \nax3 = fig.add_subplot(223, aspect = 1)\nG_PT_plot = plt.plot(G_EC, G_mod_PT, 'o', color = pal[3], \n label = 'TSEB', lw = 1, ms = 10)\n\nG_OS_plot = plt.plot(G_EC, G_mod_OS, 'v', color = pal_orange_dark[-3], \n label = 'OSEB', lw = 1, ms = 10)\n \nG_mod = np.concatenate((G_mod_PT, G_mod_OS)) \nlim_max = max(np.ceil(G_mod[~np.isnan(G_mod)].max()/50)*50, \n np.ceil(G_EC[~np.isnan(G_EC)].max()/50)*50)\nlim_min = min(np.floor(G_mod[~np.isnan(G_mod)].min()/50)*50, \n np.floor(G_EC[~np.isnan(G_EC)].min()/50)*50)\nax3.set_xlim([lim_min, lim_max])\nax3.set_ylim([lim_min, lim_max])\nax3.xaxis.set_ticks(np.arange(lim_min,ax3.get_ylim()[1]+1,50))\nax3.yaxis.set_ticks(np.arange(lim_min,ax3.get_ylim()[1]+1,50)) \nax3.plot([lim_min, lim_max], [lim_min, lim_max], '--', \n color = (0.75, 0.75, 0.75) , lw = 1, zorder = 1)\nax3.text(0.04, 0.96,'R$^2$$_{TSEB}$: %.2f\\nR$^2$$_{OSEB}$: %.2f' % (diff_Stats.NSE_PT.G, \n diff_Stats.NSE_OS.G), horizontalalignment='left', fontsize = 16,\n verticalalignment='top', transform=ax3.transAxes)\n\nlegend = ax3.legend(loc = 'lower right') # , frameon = True\nplt.title('($c$) Soil heat flux', fontsize = 18, y = 1.02)\n\nplt.tick_params(\n which='both', # both major and minor ticks are affected\n top = 'off',\n right = 'off') # labels along the bottom edge are off\n\nax4 = fig.add_subplot(224, aspect = 1) \nRn_PT_plot = plt.plot(Rn_EC, Rn_mod_PT, 'o', color = pal[1], \n label = 'TSEB', lw = 1, ms = 10)\n\nRn_OS_plot = plt.plot(Rn_EC, Rn_mod_OS, 'v', color = pal_green_dark[-3], \n label = 'OSEB', lw = 1, ms = 10) \n \nRn_mod = np.concatenate((Rn_mod_PT, Rn_mod_OS)) \nlim_max = max(np.ceil(Rn_mod[~np.isnan(Rn_mod)].max()/50)*50, \n np.ceil(Rn_EC[~np.isnan(Rn_EC)].max()/50)*50)\nlim_min = min(np.floor(Rn_mod[~np.isnan(Rn_mod)].min()/50)*50, \n np.floor(Rn_EC[~np.isnan(Rn_EC)].min()/50)*50)\nax4.set_xlim([lim_min, lim_max])\nax4.set_ylim([lim_min, lim_max]) \nax4.xaxis.set_ticks(np.arange(lim_min,ax4.get_ylim()[1]+1,150))\nax4.yaxis.set_ticks(np.arange(lim_min,ax4.get_ylim()[1]+1,150)) \nax4.xaxis.set_ticks(np.arange(0, 601, 150))\nax4.yaxis.set_ticks(np.arange(0, 601, 150))\n \nax4.plot([lim_min, lim_max], [lim_min, lim_max], '--', \n color = (0.75, 0.75, 0.75) , lw = 1, zorder = 1)\nax4.text(0.04, 0.96,'R$^2$$_{TSEB}$: %.2f\\nR$^2$$_{OSEB}$: %.2f' % (diff_Stats.NSE_PT.Rn, \n diff_Stats.NSE_OS.Rn), horizontalalignment='left', fontsize = 16,\n verticalalignment='top', transform=ax4.transAxes)\nlegend = ax4.legend(loc = 'lower right') # , frameon = True\nplt.title('($d$) Net radiation', fontsize = 18, y = 1.02) \n\nplt.tick_params(\n which='both', # both major and minor ticks are affected\n top = 'off',\n right = 'off') # labels along the bottom edge are off\n\nplt.subplots_adjust(left = None, right=None, top=None, wspace=0.35, hspace=0.20) \n \nfig.savefig('D:\\Auswertung_Feldarbeiten_Pt_Nobressart\\TIR_Pro' + \\\n 'cessing\\FurtherAnalysis\\%s.eps' % outFile, format = 'eps', dpi = 1000)\n\nfig.savefig('D:\\Auswertung_Feldarbeiten_Pt_Nobressart\\TIR_Pro' + \\\n 'cessing\\FurtherAnalysis\\%s.png' % outFile)\n\nfig.savefig('D:\\Auswertung_Feldarbeiten_Pt_Nobressart\\TIR_Pro' + \\\n 'cessing\\FurtherAnalysis\\%s.tif' % outFile, dpi = 600)\n\n#%% \nFlux_deviations = pd.DataFrame(Fluxes.LE_OS - Fluxes.LE_BR, columns = ['Dev_LE_OS'])\nFlux_deviations['Dev_LE_PT'] = Fluxes.LE_PT - Fluxes.LE_BR\nFlux_deviations['Diff_LE_OS_PT'] = Flux_deviations.Dev_LE_PT - Flux_deviations.Dev_LE_OS\nFlux_deviations['LE_Flag'] = 'PT'\nFlux_deviations.loc[(Flux_deviations[\"Dev_LE_OS\"].abs() <= Flux_deviations[\"Dev_LE_PT\"].abs()), \"LE_Flag\"] = 'OS'\n\nFlux_deviations['Dev_H_OS'] = Fluxes.H_OS - Fluxes.H_BR \nFlux_deviations['Dev_H_PT'] = Fluxes.H_PT - Fluxes.H_BR \nFlux_deviations['Diff_H_OS_PT'] = Flux_deviations.Dev_H_PT - Flux_deviations.Dev_H_OS\nFlux_deviations['H_Flag'] = 'PT'\nFlux_deviations.loc[(Flux_deviations[\"Dev_H_OS\"].abs() <= Flux_deviations[\"Dev_H_PT\"].abs()), \"H_Flag\"] = 'OS'\n\nFlux_deviations['Dev_G_OS'] = Fluxes.G_OS - Fluxes.G \nFlux_deviations['Dev_G_PT'] = Fluxes.G_PT - Fluxes.G \nFlux_deviations['Diff_G_OS_PT'] = Flux_deviations.Dev_G_PT - Flux_deviations.Dev_G_OS\nFlux_deviations['G_Flag'] = 'PT'\nFlux_deviations.loc[(Flux_deviations[\"Dev_G_OS\"].abs() <= Flux_deviations[\"Dev_G_PT\"].abs()), \"G_Flag\"] = 'OS'\n\ndel [Rn_EC, Rn_mod_PT, Rn_mod_OS, G_EC, G_mod_PT, G_mod_OS, H_EC, LE_EC, \n H_EC_corr_EB, LE_EC_corr_EB, H_EC_corr_res,\n LE_EC_corr_res, H_Scinti, LE_Scinti, H_mod_PT, \n LE_mod_PT, H_mod_OS, LE_mod_OS, flights,\n H_mod, H_obs, LE_mod, LE_obs, G_mod, Rn_mod]\n \ndel [H_OS_plot, H_PT_plot, LE_OS_plot, LE_PT_plot, G_OS_plot, G_PT_plot,\n Rn_OS_plot, Rn_PT_plot, ax, ax1, ax2, ax3, ax4]\n \n ","sub_path":"plot_Fluxes_IJRS.py","file_name":"plot_Fluxes_IJRS.py","file_ext":"py","file_size_in_byte":20661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"45467744","text":"\"\"\"\nORM models for MySQL DB.\n\n\"\"\"\nfrom datetime import datetime\n\nfrom peewee import (CharField,\n DateTimeField,\n ForeignKeyField,\n Model,\n MySQLDatabase,\n PrimaryKeyField)\n\nfrom etl_tool import settings as config\n\nMYSQL_HOST = config.DATABASE['MYSQL']['HOST']\nMYSQL_PORT = int(config.DATABASE['MYSQL']['PORT'])\nMYSQL_DATABASE = config.DATABASE['MYSQL']['DATABASE']\nMYSQL_USER = config.DATABASE['MYSQL']['USER']\nMYSQL_PASSWORD = config.DATABASE['MYSQL']['PASSWORD']\n\n\ndb_handle = MySQLDatabase(database=MYSQL_DATABASE,\n host=MYSQL_HOST,\n port=MYSQL_PORT,\n user=MYSQL_USER,\n password=MYSQL_PASSWORD)\n\n\nclass BaseModel(Model):\n class Meta:\n database = db_handle\n\n\nclass MakerDimension(BaseModel):\n uk = PrimaryKeyField(null=False)\n name = CharField(max_length=32)\n created_at = DateTimeField(default=datetime.now())\n updated_at = DateTimeField(default=datetime.now())\n\n class Meta:\n db_table = 'maker_dim'\n order_by = ('created_at',)\n\n\nclass ModelDimension(BaseModel):\n uk = PrimaryKeyField(null=False)\n maker_uk = ForeignKeyField(MakerDimension,\n related_name='fk_maker_model',\n to_field='uk',\n on_update='cascade',\n on_delete='cascade',\n db_column='maker_uk',\n null=False)\n name = CharField(max_length=32)\n created_at = DateTimeField(default=datetime.now())\n updated_at = DateTimeField(default=datetime.now())\n\n class Meta:\n db_table = 'model_dim'\n order_by = ('created_at',)\n","sub_path":"project/etl_tool/models/mysql_models.py","file_name":"mysql_models.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"47788609","text":"def full_install(package):\n import configparser\n import os\n import sys\n import installer\n\n config = configparser.ConfigParser()\n config.read('config.ini')\n platform = config['OS']['platform']\n cache_boolean =(\"True\" == config['Cache']['keep_cache'])\n cache_location = config['Cache']['cache_location']\n remote_url = config['Remote']['location']\n remote_branch = config['Remote']['location_branch']\n file_extension = config['Remote']['file_extension']\n\n full_file = package + file_extension\n file_url = fix_path(\n remote_url + 'packages-' + platform + '/'\n + remote_branch + '/scripts/' + full_file, platform)\n get_file(file_url, cache_location, full_file)\n return run_script(cache_location, full_file, cache_boolean, platform)\n\ndef get_file(file_url, cache_location, local_name):\n from urllib import request\n import shutil\n import os\n os.chdir(cache_location)\n with request.urlopen(file_url) as response, open(local_name, 'wb') as out_file:\n shutil.copyfileobj(response, out_file)\n\ndef run_script(directory, file, cache, platform):\n import subprocess\n import os\n try:\n directory = fix_path(os.path.dirname(__file__) + '/' + directory, platform)\n os.chdir(directory)\n with open(file, 'r') as file_script:\n bashCommand = ''\n for line in file_script.readlines():\n if line[0] != '#':\n bashCommand += line\n bashCommand = bashCommand.replace('\\n', '; ')\n output =subprocess.call(\n bashCommand, stderr=subprocess.STDOUT, shell=True)\n if cache != True:\n os.remove(file)\n return output\n except (OSError, IOError, KeyError):\n return 'Issue Installing'\n if cache != True:\n os.remove(file)\n\ndef fix_path(path, platform):\n if platform == \"windows\":\n path.replace(\"/\", \"\\\\\")\n else:\n path.replace(\"\\\\\", \"/\")\n return path\n","sub_path":"installer.py","file_name":"installer.py","file_ext":"py","file_size_in_byte":2002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"259683674","text":"import json\nfrom DataStructures import Queue\nfrom sms import send\n\n# there queue has to be declared globally (outside any other function)\n# that way all methods have access to it\nqueue = Queue(mode=\"FIFO\")\n#queue = Queue(mode=\"LIFO\")\n \ndef print_queue():\n # you must print on the console the entire queue list\n print(\"Printing the entire list...\")\n lista = queue.get_queue()\n y=1\n for x in lista:\n print(str(y) + \"-\" + x)\n y=y+1\n\ndef add():\n print(\"Ingresa el nombre del guevon que va a entrar en lista: \")\n usuario=input()\n cola=queue.enqueue(usuario)\n mensaje=\"Has sido agregado a la lista, tienes \" , str(len(cola) - 1), \" por delante\"\n send(mensaje)\n print(\"Has sido agregado a la lista, tienes \" , str(len(cola) - 1), \" por delante\")\n \n\ndef dequeue():\n cliente=queue.dequeue()\n print(\"has eliminados a el usuario\",cliente)\n mensaje='Le toca comer a :'+cliente\n send(mensaje)\n \ndef save():\n queue_file=queue.get_queue()\n file_to_save = open(\"queue.json\",\"w+\")\n file_to_save.write(json.dumps(queue_file))\n file_to_save.close()\n\n\ndef load():\n # pass\n file=open(\"queue.json\",\"r\")\n contenido=file.read()\n resultado = json.loads(contenido)\n queue._queue=resultado\n\n\n file.close()\n\n\n \nprint(\"\\nHello, this is the Command Line Interface for a Queue Managment application.\")\nstop = False\nwhile stop == False:\n \n print('''\nWhat would you like to do (type a number and press Enter)?\n- Type 1: For adding someone to the Queue.\n- Type 2: For removing someone from the Queue.\n- Type 3: For printing the current Queue state.\n- Type 4: To export the queue to the queue.json file.\n- Type 5: To import the queue from the queue.json file.\n- Type 6: To quit\n ''')\n\n option = int(input(\"Enter a number:\"))\n # add your options here using conditionals (if)\n\n if option == 3:\n print_queue()\n elif option== 1:\n add()\n elif option== 2:\n dequeue()\n elif option == 4:\n print(\"Guardando lista de espera\")\n save()\n elif option == 5:\n print(\"abriendo lista\")\n load()\n elif option == 6:\n print(\"Bye bye!\")\n stop = True\n else:\n print(\"Not implemented yet or invalid option \"+str(option))\n","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"220870875","text":"# 문제 유형 : 그리디\n\n# 문제\n# 2007년 KOI에 N명의 학생들이 참가하였다. \n# 경시일 전날인 예비소집일에, 모든 학생들은 자신이 N명 중에서 몇 등을 할 것인지 예상 등수를 적어서 제출하도록 하였다.\n\n# KOI 담당조교로 참가한 김진영 조교는 실수로 모든 학생의 프로그램을 날려 버렸다. \n# 1등부터 N등까지 동석차 없이 등수를 매겨야 하는 김 조교는, 어쩔 수 없이 각 사람이 제출한 예상 등수를 바탕으로 임의로 등수를 매기기로 했다.\n\n# 자신의 등수를 A등으로 예상하였는데 실제 등수가 B등이 될 경우, 이 사람의 불만도는 A와 B의 차이 ( |A-B| )로 수치화할 수 있다. \n# 당신은 N명의 사람들의 불만도의 총 합을 최소로 하면서, 학생들의 등수를 매기려고 한다.\n\n# 각 사람의 예상 등수가 주어졌을 때, 김 조교를 도와 이러한 불만도의 합을 최소로 하는 프로그램을 작성하시오.\n\n# 입력\n# 첫째 줄에 자연수 N이 주어진다. (1 ≤ N ≤ 500,000) 둘째 줄부터 N개의 줄에 걸쳐 각 사람의 예상 등수가 순서대로 주어진다. \n# 예상 등수는 500,000 이하의 자연수이다.\n\n# 출력\n# 첫째 줄에 불만도의 합을 최소로 할 때, 그 불만도를 출력한다.\n\n# 예제 입력 1 \n# 5\n# 1\n# 5\n# 3\n# 1\n# 2\n# 예제 출력 1 \n# 3\n\n# 문제 풀이 핵심 아이디어\n## 예상된 등수와 실제 등수의 차이를 최소화 해야 한다.\n## 예상된 등수를 오름차순으로 정렬하여 실제 등수와 - 해주면 된다.\n\nn = int(input('사람의 수 : '))\narray = []\n\nfor aa in range(n):\n array.append(int(input(f'{aa+1}번째 사람의 예상 등수 : ')))\n\n# 오름차순 정렬\narray.sort()\nprint(array)\n\n# 불만도의 합 계산\nresult = 0\nfor i in range(1, len(array)+1):\n result += abs(i-array[i-1])\n\nprint(result)\n\n# 그리디 알고리즘은 정렬과 함께 사용되는 경우가 많다.\n","sub_path":"Algorithm/Algorithm_exercise/num2012.py","file_name":"num2012.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"469951198","text":"import hashlib\nimport json\nimport datetime\nimport calendar\n\nfrom django.db.models import Max\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.core.paginator import Paginator\nfrom django.shortcuts import render, HttpResponse\nfrom django.shortcuts import redirect\nfrom django.http import StreamingHttpResponse, JsonResponse\nfrom django.urls import reverse\nfrom rent.models import rentOrder\nfrom . import forms\nfrom house.models import house\nfrom login.models import User\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.http import FileResponse\n\n\ndef search(request):\n if request.method == \"GET\":\n houses = request.session.get('houses',None)\n house_list = house.objects.all()\n flag = 1\n if houses:\n for i in houses:\n print(i)\n print(flag)\n if i != 0:\n if flag == 1:\n if i == 1:\n pass\n elif i == 2:\n house_list = house_list.filter(area='ChaoYang')\n elif i == 3:\n house_list = house_list.filter(area='HaiDian')\n elif i == 4:\n house_list = house_list.filter(area='ChangPing')\n elif flag == 2:\n if i == 1:\n house_list = house_list.filter(rental__lte=1000)\n elif i == 2:\n house_list = house_list.filter(rental__gt=1000, rental__lte=1500)\n elif i == 3:\n house_list = house_list.filter(rental__gt=1500, rental__lte=2000)\n elif i == 4:\n house_list = house_list.filter(rental__gt=2000, rental__lte=3000)\n elif i == 5:\n house_list = house_list.filter(rental__gt=3000)\n elif flag == 3:\n if i == 1:\n house_list = house_list.filter(type='single')\n elif i == 2:\n house_list = house_list.filter(type='double')\n elif i == 3:\n house_list = house_list.filter(type='triple')\n elif i == 4:\n house_list = house_list.filter(type='quad')\n elif flag == 4:\n if i == 1:\n house_list = house_list.filter(elevator=True)\n elif i == 2:\n house_list = house_list.filter(elevator=False)\n elif i == 0:\n flag += 1\n if flag == 6:\n keyword = request.session.get('keyword', None)\n print(keyword)\n if keyword:\n house_list = house.objects.filter(housename__contains=keyword)\n\n\n\n if request.method == \"POST\":\n house_list = house.objects.all()\n houses = []\n if 'area' in request.POST:\n areas = request.POST.getlist('area',[])\n print('areas')\n for i in range(0,len(areas)):\n print (areas[i])\n if areas[i] == '1':\n houses.append(1)\n elif areas[i] == '2':\n houses.append(2)\n house_list = house_list.filter(area='ChaoYang')\n elif areas[i] == '3':\n houses.append(3)\n house_list = house_list.filter(area='HaiDian')\n elif areas[i] == '4':\n houses.append(4)\n house_list = house_list.filter(area='ChangPing')\n houses.append(0)\n if 'rental' in request.POST:\n rentals = request.POST.getlist('rental',[])\n print('rentals')\n for i in range(0,len(rentals)):\n print(rentals[i])\n if rentals[i] == '1':\n houses.append(1)\n house_list = house_list.filter(rental__lte=1000)\n elif rentals[i] == '2':\n houses.append(2)\n house_list = house_list.filter(rental__gt=1000,rental__lte=1500)\n elif rentals[i] == '3':\n houses.append(3)\n house_list = house_list.filter(rental__gt=1500, rental__lte=2000)\n elif rentals[i] == '4':\n houses.append(4)\n house_list = house_list.filter(rental__gt=2000,rental__lte=3000)\n elif rentals[i] == '5':\n houses.append(5)\n house_list = house_list.filter(rental__gt=3000)\n houses.append(0)\n if 'type' in request.POST:\n types = request.POST.getlist('type',[])\n print('types')\n for i in range(0,len(types)):\n print(types[i])\n if types[i] == '1':\n houses.append(1)\n house_list = house_list.filter(type='single')\n elif types[i] == '2':\n houses.append(2)\n house_list = house_list.filter(type='double')\n elif types[i] == '3':\n houses.append(3)\n house_list = house_list.filter(type='triple')\n elif types[i] == '4':\n houses.append(4)\n house_list = house_list.filter(type='quad')\n houses.append(0)\n if 'elevator' in request.POST:\n elevators = request.POST.getlist('elevator', [])\n print('elevators')\n for i in range(0, len(elevators)):\n print(elevators[i])\n if elevators[i] == '1':\n houses.append(1)\n house_list = house_list.filter(elevator=True)\n elif elevators[i] == '2':\n houses.append(2)\n house_list = house_list.filter(elevator=False)\n houses.append(0)\n if 'keyword' in request.POST:\n keyword = request.POST.get('keyword')\n print('keyword')\n house_list = house.objects.filter(housename__contains=keyword)\n request.session['keyword'] = keyword\n houses.append(0)\n request.session['houses'] = houses\n\n house_list = house_list.order_by('id')\n paginator = Paginator(house_list,2)\n try:\n page_num = request.GET.get('page',1)\n page = paginator.page(page_num)\n except PageNotAnInteger as e:\n # 不是整数返回第一页数据\n page = paginator.page('1')\n page_num = 1\n except EmptyPage as e:\n # 当参数页码大于或小于页码范围时,会触发该异常\n print('EmptyPage:{}'.format(e))\n if int(page_num) > paginator.num_pages:\n # 大于 获取最后一页数据返回\n page = paginator.page(paginator.num_pages)\n else:\n # 小于 获取第一页\n page = paginator.page(1)\n\n # 这部分是为了再有大量数据时,仍然保证所显示的页码数量不超过10,\n page_num = int(page_num)\n if page_num < 6:\n if paginator.num_pages <= 10:\n pageRange = range(1, paginator.num_pages + 1)\n else:\n pageRange = range(1, 11)\n elif (page_num >= 6) and (page_num <= paginator.num_pages - 5):\n pageRange = range(page_num - 5, page_num + 5)\n else:\n pageRange = range(paginator.num_pages - 9, paginator.num_pages + 1)\n\n\n return render(request,'rent/search.html',locals())\n\n@csrf_exempt\ndef pay(request,rentorder_id):\n order = rentOrder.objects.get(id=rentorder_id)\n return render(request, 'rent/pay.html', locals())\n#TODO:长租的pay应该提示下载合同,审核问题\n\n\ndef download_template(request):\n file = open('static/files/hetong.docx', 'rb')\n response = FileResponse(file)\n response['Content-Type'] = 'application/octet-stream'\n response['Content-Disposition'] = 'attachment;filename=\"hetong.docx\"'\n return response\n","sub_path":"rent/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"416574398","text":"import os\nimport time\n\nvideoext = [\".3gp\", \".asf\", \".avi\", \".divx\", \".fiv\", \".swf\", \".mp4\", \".mpeg\", \".mpg\",\n \".ogm\", \".wmv\", \".mov\", \".mkv\", \".nbr\", \".rm\", \".vob\", \".sfd\", \".webm\", \".xvid\"]\n\n\n\nlista_percorsi = []\ndef filechecker(path):\n file_trovati = 0\n if os.path.isdir(path) == True:\n for cartella, sottocartella, files in os.walk(path):\n for ext in videoext:\n for file in files:\n if file.endswith(ext):\n pos = os.path.join(cartella, file)\n print(f\"Trovato file {ext}\")\n file_trovati+=1\n lista_percorsi.append(f'{pos}')\n f = open(\"cronologia.txt\", \"a\")\n f.write(f\"\\nTrovato file {ext} in: {pos}\")\n f.close()\n else:\n print(\"Percorso non trovato! Controlla e riprova!\")\n print(f\"File trovati: {file_trovati}\")\n print(\"Se vuoi vedere tutti i percorsi, apri il file 'cronologia.txt'\")\n try:\n scelta = input(\"Desideri rimuoverli tutti? y/n: \")\n except:\n print(\"Devi inserire y/n!\")\n if scelta.lower() == 'y':\n for percorso in lista_percorsi:\n try:\n print(f\"Rimuovo {percorso}\")\n os.remove(percorso)\n print(\"Fatto!\")\n except PermissionError:\n print(\"Permesso negato.\")","sub_path":"cleanvideos.py","file_name":"cleanvideos.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"503877554","text":"from ruamel import yaml\r\nfrom subprocess import Popen, PIPE\r\nimport os\r\n\r\n\r\nCURRENT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\r\n\r\nclass JadeAnsible(object):\r\n\r\n\tdef __init__(self):\r\n\t\tself.base_path = CURRENT + '/tools/ansible/'\r\n\t\tself.host_path = self.base_path + 'host/'\r\n\t\tself.yaml_path = self.base_path + 'yml/'\r\n\t\tself.beat_path = self.yaml_path + 'filebeat/'\r\n\t\tself.pkgs_path = self.base_path + 'pkgs/'\r\n\t\tself.group_name = 'filebeats'\r\n\t\tself.home_dir = '/its/'\r\n\t\tself.script_file = 'getAppname.sh'\r\n\t\tself.package = 'filebeat-6.3.0-linux-x86_64'\r\n\t\tself.filebeat_inputs = []\r\n\t\tself.filebeat_overwrite = []\r\n\t\tself.filebeat_template = { \r\n\t\t\t\t'filebeat.prospectors': [],\r\n\t\t\t\t'output.kafka': \r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t'hosts': 1, \r\n\t\t\t\t\t\t'topic': \"its_log\", \r\n\t\t\t\t\t\t'partition.round_robin': {'reachable_only': False}, \r\n\t\t\t\t\t\t'required_acks': 1, \r\n\t\t\t\t\t\t'compression': 'gzip', \r\n\t\t\t\t\t\t'max_message_bytes': 1000000\r\n\t\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\tself.filebeat_playbook = [\r\n\t\t\t{\r\n\t\t\t\t'name': 'setup filebeat', \r\n\t\t\t\t'hosts': 'filebeats', \r\n\t\t\t\t'remote_user': 'root', \r\n\t\t\t\t'tasks': []\r\n\t\t\t}\r\n\t\t]\r\n\r\n\tdef create_filebeat_kafka(self, kafkas):\r\n\t\tself.filebeat_template['output.kafka']['hosts'] = kafkas\r\n\t\t\r\n\tdef create_filebeat_input(self, path, topic, addr='127.0.0.1'):\r\n\r\n\t\tdata = {\r\n\t\t\t'input_type': 'log', \r\n\t\t\t'paths': \"{{%s}}\" % path,\r\n\t\t\t'multiline': { 'pattern': '^\\\\[', 'negate': True, 'match': 'after' }, \r\n\t\t\t'fields': { 'topic': '{{' + topic + '}}', 'ip_address': addr },\t \r\n\t\t\t'fields_under_root': True\r\n\t\t}\r\n\t\t\r\n\t\tself.filebeat_inputs.append(data)\r\n\r\n\r\n\tdef create_filebeat_script_upload(self, script_file):\r\n\t\tdata = {\r\n\t\t\t'name': 'upload script', \r\n\t\t\t'copy': 'src=' + self.pkgs_path + script_file + ' dest=' + self.home_dir + 'filebeat' + ' mode=0755',\r\n\t\t\t'ignore_errors': 'yes'\r\n\t\t}\r\n\r\n\t\tself.filebeat_playbook[0]['tasks'].append(data)\r\n\r\n\tdef create_filebeat_script_tasks(self, script_file):\r\n\r\n\t\tdata = {\r\n\t\t\t'name': 'get appname', \r\n\t\t\t'script': self.pkgs_path + script_file, \r\n\t\t\t'register': 'appname',\r\n\t\t\t'ignore_errors': 'yes'\r\n\t\t}\r\n\r\n\t\tself.filebeat_playbook[0]['tasks'].append(data)\r\n\r\n\tdef create_filebeat_home_tasks(self):\r\n\r\n\t\tdata = {\r\n\t\t\t'name': 'create ' + self.home_dir, \r\n\t\t\t'file': 'path=' + self.home_dir + ' state=directory mode=755'\r\n\t\t}\r\n\t\tself.filebeat_playbook[0]['tasks'].append(data)\r\n\r\n\tdef create_filebeat_unacrchive_tasks(self):\r\n\r\n\t\tdata = {\r\n\t\t\t'name': 'unarchive filebeat', \r\n\t\t\t'unarchive': 'src=' + self.pkgs_path + self.package + '.tar.gz dest=' + self.home_dir + ' creates=' + self.home_dir +'filebeat', \r\n\t\t\t'notify': 'change name'\r\n\t\t}\r\n\t\tself.filebeat_playbook[0]['tasks'].append(data)\r\n\r\n\tdef create_filebeat_meta_tasks(self):\r\n\t\tdata = {\r\n\t\t\t'meta': 'flush_handlers'\r\n\t\t}\r\n\t\tself.filebeat_playbook[0]['tasks'].append(data)\r\n\r\n\tdef create_filebeat_config_dir(self):\r\n\t\tdata = {\r\n\t\t\t'name': 'change dir name', \r\n\t\t\t'shell': 'cd ' + self.home_dir + ';mv ' + self.package + ' filebeat'\r\n\t\t}\r\n\t\tself.filebeat_playbook[0]['tasks'].append(data)\r\n\r\n\tdef create_filebeat_backup_tasks(self):\r\n\r\n\t\tdata = {\r\n\t\t\t'name': 'backup configfile', \r\n\t\t\t'shell': 'cp ' + self.home_dir + 'filebeat/filebeat.yml ' + self.home_dir +'filebeat/filebeat.yml_bak$(date +%Y%m%d-%H%M%S)',\r\n\t\t\t'ignore_errors': 'yes'\r\n\t\t}\r\n\t\tself.filebeat_playbook[0]['tasks'].append(data)\r\n\r\n\tdef generate_overwrite_tasks(self, hostname, addr):\r\n\t\ttemp_name = '%s_filebeat.yml' % hostname\r\n\t\tdata = {\r\n\t\t\t'name': 'overwrite configfile', \r\n\t\t\t'template': 'src=' + self.beat_path + temp_name + ' dest=' + self.home_dir + 'filebeat/filebeat.yml',\r\n\t\t\t'delegate_to': addr\r\n\t\t}\r\n\t\tself.filebeat_overwrite.append(data)\r\n\r\n\tdef create_filebeat_overwrite_tasks(self):\r\n\t\tfor data in self.filebeat_overwrite:\r\n\t\t\tself.filebeat_playbook[0]['tasks'].append(data)\r\n\r\n\tdef create_filebeat_autostart_tasks(self):\r\n\t\ttemp_name = 'filebeat'\r\n\t\tdatas = [\r\n\t\t\t{\r\n\t\t\t\t'name': 'create autostart', \r\n\t\t\t\t'template': 'src=' + self.beat_path + temp_name + ' dest=/etc/init.d/logcenter mode=775'\r\n\t\t\t},\r\n\t\t\t{\r\n\t\t\t\t'name': 'config autostart', \r\n\t\t\t\t'shell': '/bin/systemctl daemon-reload;/bin/systemctl enable logcenter.service',\r\n\t\t\t\t'ignore_errors': 'yes'\r\n\t\t\t},\r\n\t\t\t{\r\n\t\t\t\t'name': 'start filebeat', \r\n\t\t\t\t'shell': '/etc/init.d/logcenter start'\r\n\t\t\t}\r\n\t\t]\r\n\t\tfor data in datas:\r\n\t\t\tself.filebeat_playbook[0]['tasks'].append(data)\r\n\r\n\tdef create_filebeat_config(self, hostname):\r\n\t\tfor data in self.filebeat_inputs:\r\n\t\t\tself.filebeat_template['filebeat.prospectors'].append(data)\r\n\t\tfilename = (self.beat_path + '%s_filebeat.yml') % hostname\r\n\t\twith open(filename, \"w\") as fp:\r\n\t\t\tyaml.dump(self.filebeat_template, fp, Dumper=yaml.RoundTripDumper)\r\n\t\t\tfp.close()\r\n\r\n\tdef create_hosts(self, hosts_var, hosts='filebeathosts'):\r\n\t\tfilename = self.host_path + hosts\r\n\t\twith open(filename, \"w\") as fp:\r\n\t\t\tfp.writelines(\"[%s]\\n\" % self.group_name)\r\n\t\t\tfor config in hosts_var:\r\n\t\t\t\tfp.writelines(config + \"\\n\")\r\n\t\t\tfp.close()\r\n\r\n\tdef create_filebeat_playbook(self):\r\n\t\tself.create_filebeat_home_tasks()\r\n\t\tself.create_filebeat_unacrchive_tasks()\r\n\t\tself.create_filebeat_config_dir()\r\n\t\tself.create_filebeat_script_upload(self.script_file)\r\n\t\tself.create_filebeat_script_tasks(self.script_file)\r\n\t\tself.create_filebeat_meta_tasks()\r\n\t\tself.create_filebeat_backup_tasks()\r\n\t\tself.create_filebeat_overwrite_tasks()\r\n\t\tself.create_filebeat_autostart_tasks()\r\n\r\n\t\tfilename = self.yaml_path + 'filebeat_playbook.yml'\r\n\t\twith open(filename, 'w') as fp:\r\n\t\t\tyaml.dump(self.filebeat_playbook, fp, Dumper=yaml.RoundTripDumper)\r\n\t\t\tfp.close()\r\n\r\n\tdef run_playbook(self):\r\n\t\thosts = self.host_path + 'filebeathosts'\r\n\t\tplaybook = self.yaml_path + 'filebeat_playbook.yml'\r\n\t\tcommand = \"ansible-playbook %s -i %s\" % (playbook, hosts)\r\n\t\tproc = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)\r\n\t\tres, err = proc.communicate()\r\n\t\treturn (res, err)\r\n\r\n\tdef purge_task_file(self, hosts, playbook):\r\n\t\tpass\r\n\r\n\tdef parse_playbook(self, template):\r\n\t\ttry:\r\n\t\t\tdata = yaml.safe_load(template)\r\n\t\t\treturn data\r\n\t\texcept:\r\n\t\t\treturn False","sub_path":"comlib/ansible.py","file_name":"ansible.py","file_ext":"py","file_size_in_byte":6026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"424252402","text":"# exixe modules: https://github.com/dekuNukem/exixe\n# python library docs: https://github.com/dekuNukem/exixe/tree/master/python_library\n# Demo 5: Loop digits on two tubes with crossfade animation\nimport exixe\nimport spidev\nimport time\n\nspi = spidev.SpiDev()\nspi.open(0, 0)\nspi.max_speed_hz = 7800000\ncs_pin_1 = 16\ncs_pin_2 = 32\n\nmy_tube_1 = exixe.Exixe(cs_pin_1, spi)\nmy_tube_2 = exixe.Exixe(cs_pin_2, spi)\n\ncount = 0\n# my_tube.crossfade_run is a non-blocking call which can allow a main loop to handle more tasks\n# Ideally there will be a 33ms delay but this needs to take in account all other tasks within the loop\nwhile True:\n my_tube_1.set_led(127, 64, 0) # Orange\n my_tube_2.set_led(127, 0, 127) # Purple\n\n # Initialize the crossfade with next digit and how many frames desired.\n my_tube_1.crossfade_init(count, 30)\n my_tube_2.crossfade_init(10 - count, 30)\n while my_tube_1.animation_in_progress and my_tube_2.animation_in_progress:\n my_tube_1.crossfade_run()\n my_tube_2.crossfade_run()\n # 30 frames at a 33ms delay will ~1 second\n time.sleep(0.033)\n\n count = (count + 1) % 10\n","sub_path":"python_examples/5_multiple_tubes_crossfade/5_multiple_tubes_crossfade.py","file_name":"5_multiple_tubes_crossfade.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"486605239","text":"#元组的创建\na = (1,2,3)\nb = 1,2,3\nc = (1,) #c为元组\nc = (1) #c为int\n\n#tuple(可迭代的对象)\na = tuple((1,2,3))\nb= tuple([1,2,3])\nc= tuple(range(3))\n#删除\ndel c\n\n#元组的元素不能修改,列表可以\na = (20,10,5)\n#a[0] = 1\n#TypeError: 'tuple' object does not support item assignment\n\n#通过索引和切片来访问元组对象\nprint (a[0:3:2])\n\n#元组的排序:sorted(),排序生成新的对象,不对原有的对象更改\nsorted(a)\n\n'''\n元组的处理速度比列表快;\n不可变序列;\n元组可以作为字典的键使用,列表不能\n'''","sub_path":"Pycoding/1_tuple().py","file_name":"1_tuple().py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"538537709","text":"from telegram import Bot\nimport json\n\n\nclass TelegramApi(object):\n def __init__(self):\n self.__token_file = {}\n\n with open(\"../etc/tokens.json\") as file:\n for line in file.readlines():\n self.__token_file = json.loads(line.strip())\n\n self.bot = Bot(token=self.__token_file[\"telegram\"])\n\n\nclass TelegramMessaging(TelegramApi):\n def __init__(self):\n super().__init__()\n self.__answered_dates = []\n\n def send_message(self, chat_id, message_text):\n self.bot.sendMessage(chat_id=chat_id, text=message_text)\n\n def get_message(self):\n updates = self.bot.getUpdates()\n result = []\n\n for update in updates:\n if update.message.date not in self.__answered_dates:\n self.__answered_dates.append(update.message.date)\n result.append((update.message.chat_id, update.message.text))\n\n return result\n","sub_path":"src/libs/api/telegramapi.py","file_name":"telegramapi.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"145288686","text":"\"\"\"Write report about a GNSS velocity analysis run\n\nDescription:\n------------\n\n\n\n\"\"\"\n# Standard library imports\nfrom enum import Enum\nfrom collections import namedtuple\nfrom datetime import datetime\nfrom typing import List, Tuple, Union\n\n# External library imports\nimport numpy as np\nimport pandas as pd\n\n# Midgard imports\nfrom midgard.collections import enums \nfrom midgard.dev import plugins\nfrom midgard.gnss import gnss\nfrom midgard.plot.matplotlib_extension import plot_scatter_subplots, plot\nfrom midgard.math import rotation\nfrom midgard.writers._writers import get_existing_fields_by_attrs, get_field_by_attrs\n\n# Where imports\nfrom where.data import dataset3 as dataset\nfrom where.lib import config\nfrom where.lib import log\nfrom where.writers._report import Report\n\n\nFIGURE_DPI = 200\nFIGURE_FORMAT = \"png\"\n\nPlotField = namedtuple(\"PlotField\", [\"name\", \"attrs\", \"unit\", \"ylabel\", \"caption\"])\nPlotField.__new__.__defaults__ = (None,) * len(PlotField._fields)\nPlotField.__doc__ = \"\"\"A convenience class for defining a output field for plotting\n\n Args:\n name (str): Unique name\n attrs (Tuple[str]): Dataset field attributes\n unit (str): Unit of field\n ylabel (str): Y-axis label description\n caption (str): Caption of plot\n \"\"\"\n\nFIELDS = (\n PlotField(\n \"gnss_range_rate\", (\"delay\", \"gnss_range_rate\"), \"m/s\", \"Range rate\", \"Correction of range between satellite and receiver\"\n ),\n PlotField(\n \"gnss_satellite_clock_rate\",\n (\"delay\", \"gnss_satellite_clock_rate\"),\n \"m/s\",\n \"Satellite clock rate\",\n \"Correction of satellite clock rate\",\n ),\n PlotField(\n \"gnss_earth_rotation_drift\",\n (\"delay\", \"gnss_earth_rotation_drift\"),\n \"m/s\",\n \"Earth rotation drift\",\n \"Correction of Earth rotation drift\",\n ),\n PlotField(\n \"gnss_relativistic_clock_rate\",\n (\"delay\", \"gnss_relativistic_clock_rate\"),\n \"m/s\",\n \"Relativistic clock rate\",\n \"Correction of relativistic clock rate effect due to orbit eccentricity\",\n ),\n # PlotField(\n # \"estimate_gnss_rcv_clock_rate\",\n # (\"estimate_gnss_rcv_clock_rate\",),\n # \"m\",\n # \"Receiver clock rate estimate\",\n # \"Estimate of receiver clock rate\",\n # ),\n)\n\n\n@plugins.register\ndef gnss_vel_report(dset: \"Dataset\") -> None:\n \"\"\"Write report about a GNSS velocity analysis run\n\n Args:\n dset: A dataset containing the data.\n \"\"\"\n file_vars = {**dset.vars, **dset.analysis}\n # TODO: Better solution?\n if \"station\" not in file_vars: # necessary if called for example by ./where/tools/concatenate.py\n file_vars[\"station\"] = \"\"\n file_vars[\"STATION\"] = \"\"\n\n # Generate figure directory to save figures generated for GNSS report\n figure_dir = config.files.path(\"output_gnss_vel_report_figure\", file_vars=file_vars)\n figure_dir.mkdir(parents=True, exist_ok=True)\n\n # Generate plots\n _plot_velocity(dset, figure_dir)\n _plot_residual(dset, figure_dir)\n _plot_number_of_satellites(dset, figure_dir)\n _plot_satellite_overview(dset, figure_dir)\n _plot_skyplot(dset, figure_dir)\n _plot_satellite_elevation(dset, figure_dir)\n _plot_model(dset, figure_dir)\n\n if \"pdop\" in dset.fields:\n _plot_dop(dset, figure_dir)\n\n # Generate GNSS velocity report\n path = config.files.path(\"output_gnss_vel_report\", file_vars=file_vars)\n with config.files.open_path(path, create_dirs=True, mode=\"wt\") as fid:\n rpt = Report(fid, rundate=dset.analysis[\"rundate\"], path=path, description=\"GNSS analysis\")\n rpt.title_page()\n rpt.write_config()\n _add_to_report(dset, rpt, figure_dir)\n rpt.markdown_to_pdf()\n\n\ndef _add_to_report(dset: \"Dataset\", rpt: \"Report\", figure_dir: \"pathlib.PosixPath\") -> None:\n \"\"\"Add figures and tables to report\n\n Args:\n dset: A dataset containing the data.\n rpt: Report object.\n figure_dir: Figure directory.\n \"\"\"\n\n #\n # Position\n #\n rpt.add_text(\"\\n# GNSS site velocity analysis\\n\\n\")\n\n # Plot site velocity\n rpt.add_figure(\n f\"{figure_dir}/plot_timeseries_enu.{FIGURE_FORMAT}\",\n caption=\"Site velocity in topocentric coordinates (East, North, Up).\",\n clearpage=True,\n )\n\n # Plot horizontal error\n rpt.add_figure(\n f\"{figure_dir}/plot_horizontal_velocity.{FIGURE_FORMAT}\",\n caption=\"Horizontal velocity\",\n clearpage=True,\n )\n\n # Plot 3D timeseries\n rpt.add_figure(\n f\"{figure_dir}/plot_timeseries_pdop_hv_3d.{FIGURE_FORMAT}\",\n caption=\"Horizontal, vertical and 3D velocity of site position\",\n clearpage=True,\n )\n\n #\n # Residual\n #\n rpt.add_text(\"\\n# GNSS residual\\n\\n\")\n\n # Add outlier table\n # MURKS: does not work at the moment. complement_with is not implemented in Dataset v3.\n # MURKS rpt.write_dataframe_to_markdown(_table_outlier_overview(dset))\n\n # Plot residuals\n rpt.add_figure(\n f\"{figure_dir}/plot_residual.{FIGURE_FORMAT}\",\n # MURKScaption=\"Post-fit residuals, whereby the red dots represents the rejected outliers. The histogram represent only number of residuals from kept observations.\",\n caption=\"Post-fit residuals.\",\n clearpage=True,\n )\n\n #\n # Dilution of precision (DOP)\n #\n if \"pdop\" in dset.fields:\n rpt.add_text(\"\\n# Dilution of precision\\n\\n\")\n\n # Plot DOP\n rpt.add_figure(f\"{figure_dir}/plot_dop.{FIGURE_FORMAT}\", caption=\"Dilution of precision.\", clearpage=True)\n\n #\n # Satellite plots\n #\n rpt.add_text(\"\\n# Satellite plots\\n\\n\")\n\n rpt.add_figure(\n f\"{figure_dir}/plot_number_of_satellites.{FIGURE_FORMAT}\",\n caption=\"Number of satellites for each observation epoch\",\n clearpage=False,\n )\n\n figure_path = figure_path = figure_dir / f\"plot_satellite_overview.{FIGURE_FORMAT}\"\n if figure_path.exists(): # Note: Does not exists for concatenated Datasets.\n rpt.add_figure(\n figure_path,\n caption=\"Overview over satellite observations. Red coloured: Observation rejected in orbit stage (e.g. unhealthy satellites, exceeding validity length, no orbit data available); Orange coloured: Observation rejected in edit stage; Green coloured: Kept observations after edit stage.\",\n clearpage=False,\n )\n\n rpt.add_figure(f\"{figure_dir}/plot_skyplot.{FIGURE_FORMAT}\", caption=\"Skyplot\", clearpage=False)\n\n rpt.add_figure(\n f\"{figure_dir}/plot_satellite_elevation.{FIGURE_FORMAT}\", caption=\"Satellite elevation\", clearpage=True\n )\n\n #\n # Model parameter plots\n #\n rpt.add_text(\"\\n# Plots of model parameters\\n\\n\")\n\n for f in get_existing_fields_by_attrs(dset, FIELDS):\n rpt.add_figure(f\"{figure_dir}/plot_{f.name}.{FIGURE_FORMAT}\", caption=f.caption, clearpage=False)\n\n\n#\n# PLOT FUNCTIONS\n#\ndef _plot_velocity(dset: \"Dataset\", figure_dir: \"pathlib.PosixPath\") -> None:\n \"\"\"Plot site velocity plots\n\n Args:\n dset: A dataset containing the data.\n figure_dir: Figure directory\n \"\"\"\n\n \n lat, lon, height = dset.site_pos.pos.llh.T\n vel_enu = np.squeeze(rotation.trs2enu(lat, lon) @ dset.site_vel[:,:,None]) \n\n plot_scatter_subplots(\n x_array=dset.time.gps.datetime,\n y_arrays=[vel_enu[:, 0], vel_enu[:, 1], vel_enu[:, 2]],\n xlabel=\"Time [GPS]\",\n ylabels=[\"East\", \"North\", \"Up\"],\n colors=[\"steelblue\", \"darkorange\", \"limegreen\"],\n y_units=[\"m/s\", \"m/s\", \"m/s\"],\n figure_path=figure_dir / f\"plot_timeseries_enu.{FIGURE_FORMAT}\",\n opt_args={\n \"figsize\": (6, 6.8),\n \"plot_to\": \"file\",\n \"sharey\": True,\n \"title\": \"Site velocity\",\n \"statistic\": [\"rms\", \"mean\", \"std\", \"min\", \"max\", \"percentile\"],\n },\n )\n\n vel_h = np.sqrt(vel_enu[:,0] ** 2 + vel_enu[:,1] ** 2) \n vel_v = np.absolute(vel_enu[:,2])\n #vel_3d = np.sqrt(vel_enu[:,0] ** 2 + vel_enu[:,1] ** 2 + vel_enu[:,2] ** 2)\n vel_3d = np.sqrt(dset.site_vel[:,0] ** 2 + dset.site_vel[:,1] ** 2 + dset.site_vel[:,2] ** 2)\n\n plot_scatter_subplots(\n x_array=dset.time.gps.datetime,\n y_arrays=[dset.pdop, vel_h, vel_v, vel_3d],\n xlabel=\"Time [GPS]\",\n ylabels=[\"PDOP\", \"HV\", \"VV\", \"3D\"],\n colors=[\"steelblue\", \"darkorange\", \"limegreen\", \"red\"],\n y_units=[None, \"m/s\", \"m/s\", \"m/s\"],\n figure_path=figure_dir / f\"plot_timeseries_pdop_hv_3d.{FIGURE_FORMAT}\",\n opt_args={\n \"figsize\": (7, 7),\n \"plot_to\": \"file\",\n \"sharey\": False,\n # \"title\": \"2D (horizontal) and 3D velocity\",\n \"statistic\": [\"rms\", \"mean\", \"std\", \"min\", \"max\", \"percentile\"],\n },\n )\n\n plot_scatter_subplots(\n x_array=vel_enu[:, 0],\n y_arrays=[vel_enu[:, 1]],\n xlabel=\"East [m/s]\",\n ylabels=[\"North\"],\n y_units=[\"m/s\"],\n figure_path=figure_dir / f\"plot_horizontal_velocity.{FIGURE_FORMAT}\",\n opt_args={\n \"grid\": True,\n \"figsize\": (6, 6),\n \"histogram\": \"x, y\",\n \"histogram_binwidth\": 0.002,\n \"plot_to\": \"file\",\n \"title\": \"Horizontal velocity\",\n \"xlim\": [-0.1, 0.1],\n \"ylim\": [-0.1, 0.1],\n },\n )\n\n\ndef _plot_residual(dset: \"Dataset\", figure_dir: \"pathlib.PosixPath\") -> None:\n \"\"\"Plot residual plot\n\n Args:\n dset: A dataset containing the data.\n figure_dir: Figure directory\n \"\"\"\n figure_path = figure_dir / f\"plot_residual.{FIGURE_FORMAT}\"\n dset_outlier = _get_outliers_dataset(dset)\n\n if dset_outlier == enums.ExitStatus.error:\n # NOTE: This is the case for concatencated Datasets, where \"calculate\" stage data are not available.\n log.warn(f\"No data for calculate stage available. No outliers are plotted in {figure_path}.\")\n x_arrays = [dset.time.gps.datetime]\n y_arrays = [dset.residual]\n colors = [\"dodgerblue\"]\n else:\n if dset_outlier.num_obs:\n x_arrays = [dset_outlier.time.gps.datetime, dset.time.gps.datetime]\n y_arrays = [dset_outlier.residual, dset.residual]\n colors = [\"red\", \"dodgerblue\"]\n else:\n log.debug(\"No outliers detected.\")\n x_arrays = [dset.time.gps.datetime]\n y_arrays = [dset.residual]\n colors = [\"dodgerblue\"]\n\n plot(\n x_arrays=x_arrays,\n y_arrays=y_arrays,\n xlabel=\"Time [GPS]\",\n ylabel=\"Post-fit residual\",\n y_unit=\"m/s\",\n colors=colors,\n figure_path=figure_path,\n opt_args={\n \"figsize\": (7, 4),\n \"histogram\": \"y\",\n \"histogram_size\": 0.8,\n \"histogram_binwidth\": 0.002,\n \"plot_to\": \"file\",\n \"statistic\": [\"rms\", \"mean\", \"std\", \"min\", \"max\", \"percentile\"],\n },\n )\n\n\ndef _plot_dop(dset: \"Dataset\", figure_dir: \"pathlib.PosixPath\") -> None:\n \"\"\"Plot DOP\n\n Args:\n dset: A dataset containing the data.\n figure_dir: Figure directory\n \"\"\"\n plot(\n x_arrays=[\n dset.time.gps.datetime,\n dset.time.gps.datetime,\n dset.time.gps.datetime,\n dset.time.gps.datetime,\n dset.time.gps.datetime,\n ],\n y_arrays=[dset.gdop, dset.pdop, dset.vdop, dset.hdop, dset.tdop],\n xlabel=\"Time [GPS]\",\n ylabel=\"Dilution of precision\",\n y_unit=\"\",\n labels=[\"GDOP\", \"PDOP\", \"VDOP\", \"HDOP\", \"TDOP\"],\n figure_path=figure_dir / f\"plot_dop.{FIGURE_FORMAT}\",\n opt_args={\"figsize\": (7, 4), \"legend\": True, \"plot_to\": \"file\"},\n )\n\n\ndef _plot_number_of_satellites(dset: \"Dataset\", figure_dir: \"pathlib.PosixPath\") -> None:\n \"\"\"Plot number of satellites\n\n Args:\n dset: A dataset containing the data.\n figure_dir: Figure directory\n \"\"\"\n\n if \"num_satellite_used\" not in dset.fields:\n dset.add_float(\n \"num_satellite_used\",\n val=gnss.get_number_of_satellites(dset.system, dset.satellite, dset.time.gps.datetime),\n write_level=\"detail\",\n )\n\n plot(\n x_arrays=[dset.time.gps.datetime, dset.time.gps.datetime],\n y_arrays=[dset.num_satellite_available, dset.num_satellite_used],\n xlabel=\"Time [GPS]\",\n ylabel=\"Number of satellites\",\n y_unit=\"\",\n labels=[\"Available\", \"Used\"],\n figure_path=figure_dir / f\"plot_number_of_satellites.{FIGURE_FORMAT}\",\n opt_args={\"figsize\": (7, 4), \"legend\": True, \"marker\": \",\", \"plot_to\": \"file\", \"plot_type\": \"plot\"},\n )\n\n\ndef _plot_skyplot(dset: \"Dataset\", figure_dir: \"pathlib.PosixPath\") -> None:\n \"\"\"Plot skyplot\n\n Args:\n dset: A dataset containing the data.\n figure_dir: Figure directory\n \"\"\"\n\n # Convert azimuth to range 0-360 degree\n azimuth = dset.site_pos.azimuth\n idx = azimuth < 0\n azimuth[idx] = 2 * np.pi + azimuth[idx]\n\n # Convert zenith distance from radian to degree\n zenith_distance = np.rad2deg(dset.site_pos.zenith_distance)\n\n # Generate x- and y-axis data per satellite\n x_arrays = []\n y_arrays = []\n labels = []\n for sat in dset.unique(\"satellite\"):\n idx = dset.filter(satellite=sat)\n x_arrays.append(azimuth[idx])\n y_arrays.append(zenith_distance[idx])\n labels.append(sat)\n\n # Plot with polar projection\n # TODO: y-axis labels are overwritten after second array plot. Why? What to do?\n plot(\n x_arrays=x_arrays,\n y_arrays=y_arrays,\n xlabel=\"\",\n ylabel=\"\",\n y_unit=\"\",\n labels=labels,\n figure_path=figure_dir / f\"plot_skyplot.{FIGURE_FORMAT}\",\n opt_args={\n \"colormap\": \"tab20\",\n \"figsize\": (7, 7.5),\n \"legend\": True,\n \"legend_ncol\": 6,\n \"legend_location\": \"bottom\",\n \"plot_to\": \"file\",\n \"plot_type\": \"scatter\",\n \"projection\": \"polar\",\n \"title\": \"Skyplot\\n Azimuth [deg] / Elevation[deg]\",\n \"xlim\": [0, 2 * np.pi],\n \"ylim\": [0, 90],\n \"yticks\": (range(0, 90, 30)), # sets 3 concentric circles\n \"yticklabels\": (map(str, range(90, 0, -30))), # reverse labels from zenith distance to elevation\n },\n )\n\n\ndef _plot_satellite_elevation(dset: \"Dataset\", figure_dir: \"pathlib.PosixPath\") -> None:\n \"\"\"Plot satellite elevation\n\n Args:\n dset: A dataset containing the data.\n figure_dir: Figure directory\n \"\"\"\n\n # Convert elevation from radian to degree\n elevation = np.rad2deg(dset.site_pos.elevation)\n\n # Limit x-axis range to rundate\n day_start, day_end = _get_day_limits(dset)\n\n # Generate x- and y-axis data per satellite\n x_arrays = []\n y_arrays = []\n labels = []\n\n for sat in dset.unique(\"satellite\"):\n idx = dset.filter(satellite=sat)\n x_arrays.append(dset.time.gps.datetime[idx])\n y_arrays.append(elevation[idx])\n labels.append(sat)\n\n # Plot with scatter plot\n plot(\n x_arrays=x_arrays,\n y_arrays=y_arrays,\n xlabel=\"Time [GPS]\",\n ylabel=\"Elevation [deg]\",\n y_unit=\"\",\n labels=labels,\n figure_path=figure_dir / f\"plot_satellite_elevation.{FIGURE_FORMAT}\",\n opt_args={\n \"colormap\": \"tab20\",\n \"figsize\": (7, 8),\n \"legend\": True,\n \"legend_ncol\": 6,\n \"legend_location\": \"bottom\",\n \"plot_to\": \"file\",\n \"plot_type\": \"scatter\",\n \"title\": \"Satellite elevation\",\n \"xlim\": [day_start, day_end],\n },\n )\n\n\ndef _plot_satellite_overview(dset: \"Dataset\", figure_dir: \"pathlib.PosixPath\") -> Union[None, Enum]:\n \"\"\"Plot satellite observation overview\n\n Args:\n dset: A dataset containing the data.\n figure_dir: Figure directory\n \n Returns:\n Error exit status if necessary datasets could not be read\n \"\"\"\n figure_path = figure_dir / f\"plot_satellite_overview.{FIGURE_FORMAT}\"\n\n # Limit x-axis range to rundate\n day_start, day_end = _get_day_limits(dset)\n\n # Get time and satellite data from read and orbit stage\n file_vars = {**dset.vars, **dset.analysis}\n file_vars[\"stage\"] = \"read\"\n file_path = config.files.path(\"dataset\", file_vars=file_vars)\n if file_path.exists(): \n time_read, satellite_read = _sort_by_satellite(\n _get_dataset(dset, stage=\"read\", systems=dset.meta[\"obstypes\"].keys())\n )\n time_orbit, satellite_orbit = _sort_by_satellite(\n _get_dataset(dset, stage=\"orbit\", systems=dset.meta[\"obstypes\"].keys())\n )\n time_edit, satellite_edit = _sort_by_satellite(\n _get_dataset(dset, stage=\"edit\", systems=dset.meta[\"obstypes\"].keys())\n )\n \n else:\n # NOTE: This is the case for concatencated Datasets, where \"read\" and \"edit\" stage data are not available.\n log.warn(f\"Read dataset does not exists: {file_path}. Plot {figure_path} can not be plotted.\")\n return enums.ExitStatus.error\n\n # Generate plot\n plot(\n x_arrays=[time_read, time_orbit, time_edit],\n y_arrays=[satellite_read, satellite_orbit, satellite_edit],\n xlabel=\"Time [GPS]\",\n ylabel=\"Satellite\",\n y_unit=\"\",\n # labels = [\"Rejected in orbit stage\", \"Rejected in edit stage\", \"Kept observations\"],\n colors=[\"red\", \"orange\", \"green\"],\n figure_path=figure_path,\n opt_args={\n \"colormap\": \"tab20\",\n \"figsize\": (7, 6),\n \"marker\": \"|\",\n \"plot_to\": \"file\",\n \"plot_type\": \"scatter\",\n \"title\": \"Overview over satellites\",\n \"xlim\": [day_start, day_end],\n },\n )\n\n\ndef _plot_model(dset: \"Dataset\", figure_dir: \"pathlib.PosixPath\") -> None:\n \"\"\"Plot model parameters\n\n Args:\n dset: A dataset containing the data.\n figure_dir: Figure directory\n \"\"\"\n\n # Limit x-axis range to rundate\n day_start, day_end = _get_day_limits(dset)\n\n for f in get_existing_fields_by_attrs(dset, FIELDS):\n\n # Generate x- and y-axis data per satellite\n x_arrays = []\n y_arrays = []\n labels = []\n\n for sat in dset.unique(\"satellite\"):\n idx = dset.filter(satellite=sat)\n x_arrays.append(dset.time.gps.datetime[idx])\n y_arrays.append(get_field_by_attrs(dset, f.attrs, f.unit)[idx])\n labels.append(sat)\n\n # Plot with scatter plot\n plot(\n x_arrays=x_arrays,\n y_arrays=y_arrays,\n xlabel=\"Time [GPS]\",\n ylabel=f.ylabel,\n y_unit=f.unit,\n labels=labels,\n figure_path=figure_dir / f\"plot_{f.name}.{FIGURE_FORMAT}\",\n opt_args={\n \"colormap\": \"tab20\",\n \"figsize\": (7, 6),\n \"legend\": True,\n \"legend_ncol\": 6,\n \"legend_location\": \"bottom\",\n \"plot_to\": \"file\",\n \"plot_type\": \"scatter\",\n \"statistic\": [\"rms\", \"mean\", \"std\", \"min\", \"max\", \"percentile\"],\n \"xlim\": [day_start, day_end],\n },\n )\n\n\n#\n# TABLE GENERATION FUNCTIONS\n#\ndef _table_outlier_overview(dset: \"Dataset\"):\n \"\"\"Generate Dataframe table with overview over number of navigation messages\n\n Args:\n dset: A dataset containing the data.\n\n Returns:\n Dataframe with satellites as indices and following columns:\n\n | Name | Description |\n |-------------|----------------------------------------------------------------------------------------------|\n | outlier | Number of outliers for each satellite |\n\n\n Example:\n\n | |outlier | \n |----|--------|\n | G01| 0 |\n | G02| 11 |\n | G03| 3 |\n | .. | ... |\n | SUM| 42 |\n\n \"\"\"\n columns = [\"outlier\"]\n df = pd.DataFrame(columns=columns)\n\n dset_outlier = _get_outliers_dataset(dset)\n if dset_outlier == enums.ExitStatus.error:\n # NOTE: This is the case for concatencated Datasets, where \"calculate\" stage data are not available.\n log.warn(f\"No data for calculate stage available. Outliers can not be detected.\")\n return df\n\n if dset_outlier.num_obs:\n log.debug(\"No outlier detected.\")\n return df\n\n for satellite in sorted(dset.unique(\"satellite\")):\n idx = dset_outlier.filter(satellite=satellite)\n row = [len(dset_outlier.satellite[idx])]\n df = df.append(pd.DataFrame([row], columns=columns, index=[satellite]))\n\n df = df.append(pd.DataFrame([[len(dset_outlier.satellite)]], columns=columns, index=[\"**SUM**\"]))\n\n return df\n\n\n#\n# AUXILIARY FUNCTIONS\n#\ndef _get_day_limits(dset: \"Dataset\") -> Tuple[datetime, datetime]:\n \"\"\"Get start and end time for given run date\n\n Args:\n dset: A dataset containing the data.\n\n Returns:\n Start and end date. \n \"\"\"\n day_start = min(dset.time.datetime)\n day_end = max(dset.time.datetime)\n\n return day_start, day_end\n\n\ndef _get_outliers_dataset(dset: \"Dataset\") -> Union[\"Dataset\", Enum]:\n \"\"\"Get dataset with outliers\n\n Args:\n dset: A dataset containing the data.\n\n Returns:\n Dataset with outliers or error exit status if no data for \"calculate\" stage are available\n \"\"\"\n\n # Get Dataset where no outliers are rejected\n file_vars = {**dset.vars, **dset.analysis}\n file_vars[\"stage\"] = \"calculate\"\n\n try:\n dset_complete = dataset.Dataset.read(**file_vars)\n except OSError:\n log.warn(f\"Could not read dataset {config.files.path('dataset', file_vars=file_vars)}.\")\n return enums.ExitStatus.error\n\n # Get relative complement, which corresponds to \"outlier\" dataset\n # dset_outliers = dset_complete.complement_with(dset, complement_by=[\"time\", \"satellite\"])\n dset_outliers = dataset.Dataset(num_obs=0) # MURKS: complement_with does not exists so far in Dataset v3.\n\n return dset_outliers\n\n\ndef _get_dataset(dset: \"Dataset\", stage: str, systems: Union[List[str], None] = None) -> Union[\"Dataset\", Enum]:\n \"\"\"Get dataset for given stage\n\n Args:\n dset: A dataset containing the data.\n systems: List with GNSS identifiers (e.g. E, G, ...)\n\n Returns:\n Dataset for given stage or error exit status if dataset could not be read\n \"\"\"\n\n # Get Dataset\n # TODO: \"label\" should have a default value.\n file_vars = {**dset.vars, **dset.analysis}\n file_vars[\"stage\"] = stage\n try:\n dset_out = dataset.Dataset.read(**file_vars)\n except OSError:\n log.warn(\"Could not read dataset {config.files.path('dataset', file_vars=file_vars)}.\")\n return enums.ExitStatus.error\n\n # Reject not defined GNSS observations\n if systems:\n systems = [systems] if isinstance(systems, str) else systems\n keep_idx = np.zeros(dset_out.num_obs, dtype=bool)\n for sys in systems:\n idx = dset_out.filter(system=sys)\n keep_idx[idx] = True\n dset_out.subset(keep_idx)\n\n return dset_out\n\n\ndef _sort_by_satellite(dset: \"Dataset\") -> Tuple[List[datetime], List[str]]:\n \"\"\"Sort time and satellite fields of dataset by satellite order\n\n Args: \n dset: A dataset containing the data.\n\n Returns:\n Tuple with ordered time array and satellite array\n \"\"\"\n time = []\n satellite = []\n for sat in sorted(dset.unique(\"satellite\"), reverse=True):\n idx = dset.filter(satellite=sat)\n time.extend(dset.time.gps.datetime[idx])\n satellite.extend(dset.satellite[idx])\n\n return time, satellite\n","sub_path":"where/writers/gnss_vel_report.py","file_name":"gnss_vel_report.py","file_ext":"py","file_size_in_byte":24087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"358451349","text":"from __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nimport os\nimport sys\nimport time\nimport codecs\n\nimport torch\nimport torchtext.data as data\n# import numpy as np\n# import matplotlib\n# matplotlib.use('Agg')\n# import matplotlib.pyplot as plt\n# from sklearn.metrics import f1_score, accuracy_score, precision_score, recall_score\n#\n#\n# def train(train_iter, val_iter, model, args, sentence_field, label_field):\n# start_time = time.time()\n# optimizer = torch.optim.Adam(model.parameters(), lr=args.lr)\n# loss_func = torch.nn.CrossEntropyLoss()\n#\n# steps = 0\n# best_acc = 0\n# last_step = 0\n# model.train()\n#\n# plot_steps = list()\n# plot_losses = list()\n# plot_accs = list()\n# annotate_best_step = 0\n# annotate_best_acc = 0\n#\n# for epoch in range(1, args.epochs + 1):\n# for batch in train_iter:\n# sentence1 = batch.sentence1\n# sentence2 = batch.sentence2\n# target = batch.label\n# sentence1 = sentence1.t_()\n# sentence2 = sentence2.t_()\n# # target = target.t_()\n#\n# model.batch_size = batch.batch_size\n#\n# if args.cuda:\n# sentence1 = sentence1.cuda()\n# sentence2 = sentence2.cuda()\n#\n# # print(sentence1.data.size())\n# # print(sentence2.data.size())\n# # print(sentence1_lengths.data)\n# # orig_text = sentence_field.reverse(sentence1.data)\n# # print(type(orig_text), len(orig_text))\n# # print(orig_text[0])\n# # print(target.data)\n#\n# optimizer.zero_grad()\n# logit = model(sentence1, sentence2)\n# loss = loss_func(logit, target)\n# # print(loss)\n# loss.backward()\n# optimizer.step()\n#\n# steps += 1\n# if steps % args.log_interval == 0:\n# plot_losses.append(loss.data[0].item())\n# plot_steps.append(steps)\n#\n# target = target.data\n# logit = torch.max(logit, 1)[1].data\n# accuracy = accuracy_score(target, logit)\n# # recall = recall_score(target, logit)\n# # precision = precision_score(target, logit)\n# f1 = f1_score(target, logit)\n# plot_accs.append(accuracy)\n# sys.stdout.write(\n# '\\rBatch[{}-{}] - loss: {:.6f} acc: {} f1: {} time: {}s'.format(\n# epoch, steps, loss.data[0].item(), accuracy, f1, time.time()-start_time))\n# if steps % args.test_interval == 0:\n# dev_acc = eval(val_iter, model, args)\n# if dev_acc > best_acc:\n# best_acc = dev_acc\n# last_step = steps\n# annotate_best_acc = best_acc\n# annotate_best_step = last_step\n# if args.save_best:\n# save(model, args.save_dir, 'best', steps)\n# else:\n# if steps - last_step >= args.early_stop:\n# print('early stop by {} steps.'.format(args.early_stop))\n# elif steps % args.save_interval == 0:\n# save(model, args.save_dir, 'snapshot', steps)\n#\n# plt.figure()\n# x = np.array(plot_steps)\n# y1 = np.array(plot_losses)\n# y2 = np.array(plot_accs)\n#\n# plt.subplot(211)\n# plt.plot(x, y1, 'r-')\n# plt.xlabel('step')\n# plt.ylabel('loss')\n#\n# plt.subplot(212)\n# plt.plot(x, y2, 'b-')\n# plt.annotate('best_acc {}'.format(annotate_best_acc), xy=(annotate_best_step, annotate_best_acc),\n# xytext=(annotate_best_step - 100, annotate_best_acc - 100),\n# arrowprops=dict(facecolor='black', shrink=0.05), )\n# plt.xlabel('step')\n# plt.ylabel('accuracy')\n#\n# plt.savefig('./img/bcdssm_acc_epoch{}.jpg'.format(epoch))\n\n\ndef eval(data_iter, model, args):\n start_time = time.time()\n model.eval()\n loss_func = torch.nn.CrossEntropyLoss()\n logits = []\n targets = []\n\n corrects, avg_loss = 0, 0\n for batch in data_iter:\n sentence1 = batch.sentence1\n sentence2 = batch.sentence2\n target = batch.label\n sentence1 = sentence1.t_()\n sentence2 = sentence2.t_()\n\n model.batch_size = batch.batch_size\n\n if args.cuda:\n sentence1 = sentence1.cuda()\n sentence2 = sentence2.cuda()\n\n logit = model(sentence1, sentence2)\n\n loss = loss_func(logit, target)\n\n avg_loss += loss.data[0]\n\n logit = torch.max(logit, 1)[1].data.tolist()\n target = target.data.tolist()\n\n logits.extend(logit)\n targets.extend(target)\n\n f1 = f1_score(targets, logits)\n accuracy = accuracy_score(targets, logits)\n\n size = len(data_iter.dataset)\n avg_loss /= size\n print('\\nEvaluation - loss: {:.6f} acc: {} f1: {} time: {}s\\n'.format(\n avg_loss, accuracy, f1, time.time()-start_time))\n return f1\n\n\ndef predict(inpath, outpath, model, sentence_field, id_field, cuda_flag):\n predict_data = data.TabularDataset(inpath, format='tsv',\n fields=[(\"id\", id_field),\n ('sentence1', sentence_field),\n ('sentence2', sentence_field)])\n batch_size = 64\n # print('DATA_SIZE={}'.format(len(predict_data)))\n # print('BATCH_SIZE={}'.format(batch_size))\n\n predict_iter = data.Iterator(predict_data, batch_size=batch_size, device=-1, repeat=False, shuffle=False)\n steps = 0\n for batch in predict_iter:\n sentence1 = batch.sentence1\n sentence2 = batch.sentence2\n # orig_sent1 = sentence_field.reverse(sentence1)\n # orig_sent2 = sentence_field.reverse(sentence2)\n sentence1 = sentence1.t_()\n sentence2 = sentence2.t_()\n if cuda_flag:\n sentence1 = sentence1.cuda()\n sentence2 = sentence2.cuda()\n model.batch_size = batch.batch_size\n\n logit = model(sentence1, sentence2)\n\n steps += 1\n # sys.stdout.write('\\rBatch[{}]'.format(steps))\n\n idx = batch.id.tolist()\n predict_label = torch.max(logit, 1)[1].data.tolist()\n results = [str(i)+'\\t'+str(l)+'\\n' for i, l in zip(idx, predict_label)]\n # print(results)\n with codecs.open(outpath, 'a', 'utf-8') as fw:\n fw.writelines(results)\n\n\ndef save(model, save_dir, save_prefix, steps):\n if not os.path.isdir(save_dir):\n os.makedirs(save_dir)\n save_prefix = os.path.join(save_dir, save_prefix)\n save_path = '{}_steps_{}.pt'.format(save_prefix, steps)\n torch.save(model.state_dict(), save_path)\n","sub_path":"bcdssm/train_bcdssm.py","file_name":"train_bcdssm.py","file_ext":"py","file_size_in_byte":6948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"465693330","text":"import math\nfrom functools import lru_cache\n\nfrom util.hexboard import HexBoard\n\nclass HexEvalMethod:\n\n def __init(self, eval_method):\n self.eval_method = eval_method\n\n def evaluate_board(board, color):\n raise NotImplementedError\n \n @lru_cache(maxsize=8)\n def distance_to(self, color_b, opposite_color):\n \"\"\"Returns the distance between the two provided colors, this is the vertex cost for Dijkstra\"\"\"\n if color_b == opposite_color:\n return math.inf\n elif color_b == HexBoard.EMPTY:\n return 1\n else:\n return 0\n\n def evaluate_board(self, board, color):\n winner = board.get_winner()\n if winner is not None: return HexBoard.get_reward(color, winner) * 1000\n \n player_sp = self.find_shortest_path_to_border(board, color)\n opponent_sp = self.find_shortest_path_to_border(board, HexBoard.get_opposite_color(color))\n\n if player_sp == math.inf: player_sp = 0\n if opponent_sp == math.inf: opponent_sp = 0\n\n return -(player_sp - opponent_sp)\n\n def get_score(self, board, from_coord, target_coords, color, opposite_color):\n raise NotImplementedError\n\n def find_shortest_path_to_border(self, board, color):\n \"\"\"Returns the length of the shortest possible path to the border for the specified color\"\"\"\n source_coords = board.source_coords[color]\n target_coords = board.target_coords[color]\n opposite_color = HexBoard.get_opposite_color(color)\n \n min_score = board.size**2\n\n for from_coord in source_coords:\n if board.get_color(from_coord) == opposite_color:\n continue\n\n score = self.get_score(board, from_coord, target_coords, color, opposite_color)\n\n if score < min_score:\n min_score = score\n\n return min_score\n","sub_path":"a4/evaluate/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"361016542","text":"import os\n\nfrom dvc.command.common.base import CmdBase\nfrom dvc.logger import Logger\nfrom dvc.state_file import StateFile\nfrom dvc.path.data_item import DataItem\n\n\nclass CmdAdd(CmdBase):\n def __init__(self, settings):\n super(CmdAdd, self).__init__(settings)\n\n def collect_file(self, fname):\n return [self.settings.path_factory.data_item(fname)]\n\n def collect_dir(self, dname):\n targets = []\n for root, dirs, files in os.walk(dname):\n for fname in files:\n targets += self.collect_file(os.path.join(root, fname))\n return targets\n\n def collect_targets(self, inputs):\n targets = []\n for i in inputs:\n if not os.path.isdir(i):\n targets += self.collect_file(i)\n else:\n targets += self.collect_dir(i)\n return targets\n\n def add_files(self, targets):\n for data_item in targets:\n data_item.move_data_to_cache()\n\n def create_state_files(self, targets):\n \"\"\"\n Create state files for all targets.\n \"\"\"\n for data_item in targets:\n Logger.debug('Creating state file for {}'.format(data_item.data.relative))\n\n fname = os.path.basename(data_item.data.relative + StateFile.STATE_FILE_SUFFIX)\n out = StateFile.parse_deps_state(self.settings, [data_item.data.relative],\n currdir=os.path.curdir)\n state_file = StateFile(fname=fname,\n cmd=None,\n out=out,\n out_git=[],\n deps=[],\n locked=True)\n state_file.save()\n Logger.debug('State file \"{}\" was created'.format(data_item.state.relative))\n\n def run(self):\n targets = self.collect_targets(self.parsed_args.input)\n self.add_files(targets)\n self.create_state_files(targets)\n msg = 'DVC add: {}'.format(str(self.parsed_args.input))\n self.commit_if_needed(msg)\n","sub_path":"dvc/command/add.py","file_name":"add.py","file_ext":"py","file_size_in_byte":2100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"218151889","text":"from globus_sdk._testing.models import RegisteredResponse, ResponseSet\n\nmetadata = {\n \"id\": \"daa09846-eb92-11e9-b89c-9cb6d0d9fd63\",\n \"display_name\": \"example gateway 1\",\n}\n\nRESPONSES = ResponseSet(\n metadata=metadata,\n default=RegisteredResponse(\n service=\"gcs\",\n method=\"PATCH\",\n path=f\"/storage_gateways/{metadata['id']}\",\n json={\n \"DATA_TYPE\": \"result#1.0.0\",\n \"http_response_code\": 200,\n \"detail\": \"success\",\n \"message\": \"Operation successful\",\n \"code\": \"success\",\n \"data\": [\n {\n \"DATA_TYPE\": \"storage_gateway#1.0.0\",\n \"id\": metadata[\"id\"],\n \"display_name\": metadata[\"display_name\"],\n \"connector_id\": \"145812c8-decc-41f1-83cf-bb2a85a2a70b\",\n \"require_high_assurance\": False,\n \"high_assurance\": False,\n \"authentication_assurance_timeout\": 15840,\n \"authentication_timeout_mins\": 15840,\n \"allowed_domains\": [\"example.edu\"],\n \"mapping\": \"username_without_domain\",\n \"restrict_paths\": {\n \"DATA_TYPE\": \"path_restrictions#1.0.0\",\n \"read\": [\"/\"],\n },\n \"policies\": {\n \"DATA_TYPE\": \"posix_storage_gateway#1.0.0\",\n \"groups_allow\": [\"globus\"],\n \"groups_deny\": [\"nonglobus\"],\n },\n \"users_allow\": [\"user1\"],\n \"users_deny\": [\"user2\"],\n }\n ],\n },\n ),\n)\n","sub_path":"src/globus_sdk/_testing/data/globus_connect_server/update_storage_gateway.py","file_name":"update_storage_gateway.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"41672648","text":"import numpy as np\n\n\n\ndef linear_triangulation(p1, p2, m1, m2):\n\t\"\"\"\n\tLinear triangulation to find the 3D point X where p1=m1*X\n\tand p2=m2*X. Solve AX = 0.\n\n\tArgs:\n\t\tp1: 2D points from image 1\n\t\tp2: 2Dpoints from image 2\n\t\tm1: Camera matrices for image 1\n\t\tm2: Camera matrices for image 2\n\tReturns:\n\t\"\"\"\n\n\tnum_points = p1.shape[1] #calculate number of points\n\tout = np.ones((4, num_points)) #array storinng\n\n\tfor i in range(num_points):\n\t\tA = np.asarray([\n\t\t\t(p1[0,i]*m1[2,:] - m1[0,:]),\n\t\t\t(p1[1,i]*m1[2,:] - m1[1,:]),\n\t\t\t(p2[0,i]*m2[2,:] - m2[0,:]),\n\t\t\t(p2[1,i]*m2[2,:] - m2[1,:])\n\t\t])\n\n\t\t_, _, V = np.linalg.svd(A)\n\t\tX = V[-1, :4]\n\t\tout[:,i] = X/X[3]\n\n\treturn out\n\n\ndef skew(x):\n\t\"\"\"\n\tCreate a skew symmetric matrix A from a 3D vector x\n\n\tArgs:\n\t\tx: 3D vector\n\tReturns:\n\t\t3 x 3 skew symmetric matrix from x\n\t\"\"\"\n\n\treturn np.array([\n\t\t[0, -x[2], x[1]],\n\t\t[x[2], 0, -x[0]],\n\t\t[-x[1], x[0], 0]\n\t])\n\n\n\ndef computeEightPointMatrix(p1, p2):\n\t\"\"\"\n\tComputing a nx8 matrix for corresponding points in the two images\n\tfor n scene point\n\n\tArgs:\n\t\tp1:\n\t\tp2:\n\n\tReturns:\n\t\t1x8 matrix\n\t\"\"\"\n\n\tnum_points=p1.shape[0]\n\n\tp1x, p1y = p1[:2]\n\tp1y, p2y = p2[:2]\n\n\n\treturn np.array([\n\t\tp1x * p2x, p1x * p2y, p1x,\n\t\tp1y * p2x, p1y * p2y, p1y,\n\t\tp2x, p2y, np.ones(len(p1x))\n\t]).T\n\n\n\ndef computeFundamenalMatrix(p1, p2):\n\t\"\"\"\n\tArgs:\n\t\t\n\n\tReturns:\n\t\"\"\"\n\n\tn = x1.shape[1]\n\tif x2.shape[1] != n:\n\t\traise ValueError(\"Number of points don't match.\")\n\n\tA = computeEightPointMatrix(p1, p2)\n\ndef computeEssentialMatrix(x1, x2):\n\traise NotImplementedError\n\n\n\n\ndef computeCameraMatrix(p2d, p3d):\n\t\"\"\"\n\tComputes the camera matrix using Direct Linear Transformation.\n\tThis method formulates a homogeneous linear system of equations and\n\tsolves this by finding an approximate null space of the system matrix\n\n\tArgs:\n\t\tX: scene point in the 3D coordinate\n\t\tx: scene point in the image coordinate\n\n\tReturns:\n\t\t3 x 4 camera matrix\n\t\"\"\"\n\n\tn = p2d.shape[1]\n\tif p3d.shape[1] != n:\n\t\traise ValueError(\"Number of points don't match.\")\n\n\n\t# create matrix for DLT solution\n\tM = zeros((3*n,12+n))\n\tfor i in range(n):\n\t\tM[3*i,0:4] = p3d[:,i]\n\t\tM[3*i+1,4:8] = p3d[:,i]\n\t\tM[3*i+2,8:12] = p3d[:,i]\n\t\tM[3*i:3*i+3,i+12] = -p2d[:,i]\n\t\t\n\tU,S,V = linalg.svd(M)\n\t\n\treturn V[-1,:12].reshape((3,4))\n\n\n\ndef compute_epipole(F):\n\t\"\"\" Computes the (right) epipole from a \n\t\tfundamental matrix F. \n\t\t(Use with F.T for left epipole.) \"\"\"\n\t\n\t# return null space of F (Fx=0)\n\tU,S,V = linalg.svd(F)\n\te = V[-1]\n\treturn e/e[2]\n\n\n\ndef triangulate_point(x1,x2,P1,P2):\n\t\"\"\" Point pair triangulation from \n\t\tleast squares solution. \"\"\"\n\t\t\n\tM = zeros((6,6))\n\tM[:3,:4] = P1\n\tM[3:,:4] = P2\n\tM[:3,4] = -x1\n\tM[3:,5] = -x2\n\n\tU,S,V = linalg.svd(M)\n\tX = V[-1,:4]\n\n\treturn X / X[3]\n\n\ndef triangulate(x1,x2,P1,P2):\n\t\"\"\" Two-view triangulation of points in \n\t\tx1,x2 (3*n homog. coordinates). \"\"\"\n\t\t\n\tn = x1.shape[1]\n\tif x2.shape[1] != n:\n\t\traise ValueError(\"Number of points don't match.\")\n\n\n\tX = [ triangulate_point(x1[:,i],x2[:,i],P1,P2) for i in range(n)]\n\treturn array(X).T\n\n\n\ndef compute_normalized_image_to_image_matrix(p1, p2, compute_essential=False):\n\t\"\"\" Computes the fundamental or essential matrix from corresponding points\n\t\tusing the normalized 8 point algorithm.\n\t:input p1, p2: corresponding points with shape 3 x n\n\t:returns: fundamental or essential matrix with shape 3 x 3\n\t\"\"\"\n\tn = p1.shape[1]\n\tif p2.shape[1] != n:\n\t\traise ValueError('Number of points do not match.')\n\n\t# preprocess image coordinates\n\tp1n, T1 = scale_and_translate_points(p1)\n\tp2n, T2 = scale_and_translate_points(p2)\n\n\t# compute F or E with the coordinates\n\tF = compute_image_to_image_matrix(p1n, p2n, compute_essential)\n\n\t# reverse preprocessing of coordinates\n\t# We know that P1' E P2 = 0\n\tF = np.dot(T1.T, np.dot(F, T2))\n\n\treturn F / F[2, 2]\n\n\ndef compute_image_to_image_matrix(x1, x2, compute_essential=False):\n\t\"\"\" Compute the fundamental or essential matrix from corresponding points\n\t\t(x1, x2 3*n arrays) using the 8 point algorithm.\n\t\tEach row in the A matrix below is constructed as\n\t\t[x'*x, x'*y, x', y'*x, y'*y, y', x, y, 1]\n\t\"\"\"\n\tA = correspondence_matrix(x1, x2)\n\t# compute linear least square solution\n\tU, S, V = np.linalg.svd(A)\n\tF = V[-1].reshape(3, 3)\n\n\t# constrain F. Make rank 2 by zeroing out last singular value\n\tU, S, V = np.linalg.svd(F)\n\tS[-1] = 0\n\tif compute_essential:\n\t\tS = [1, 1, 0] # Force rank 2 and equal eigenvalues\n\tF = np.dot(U, np.dot(np.diag(S), V))\n\n\treturn F\n\n\ndef compute_fundamental_normalized(p1, p2):\n\treturn compute_normalized_image_to_image_matrix(p1, p2)\n\n\ndef compute_essential_normalized(p1, p2):\n\treturn compute_normalized_image_to_image_matrix(p1, p2, compute_essential=True)\n\n\ndef scale_and_translate_points(points):\n\t\"\"\" Scale and translate image points so that centroid of the points\n\t\tare at the origin and avg distance to the origin is equal to sqrt(2).\n\t:param points: array of homogenous point (3 x n)\n\t:returns: array of same input shape and its normalization matrix\n\t\"\"\"\n\tx = points[0]\n\ty = points[1]\n\tcenter = points.mean(axis=1) # mean of each row\n\tcx = x - center[0] # center the points\n\tcy = y - center[1]\n\tdist = np.sqrt(np.power(cx, 2) + np.power(cy, 2))\n\tscale = np.sqrt(2) / dist.mean()\n\tnorm3d = np.array([\n\t\t[scale, 0, -scale * center[0]],\n\t\t[0, scale, -scale * center[1]],\n\t\t[0, 0, 1]\n\t])\n\n\treturn np.dot(norm3d, points), norm3d\n\n\n\ndef correspondence_matrix(p1, p2):\n\tp1x, p1y = p1[:2]\n\tp2x, p2y = p2[:2]\n\n\treturn np.array([\n\t\tp1x * p2x, p1x * p2y, p1x,\n\t\tp1y * p2x, p1y * p2y, p1y,\n\t\tp2x, p2y, np.ones(len(p1x))\n\t]).T\n\n\n\n\ndef compute_P_from_essential(E):\n\t\"\"\" Compute the second camera matrix (assuming P1 = [I 0])\n\t\tfrom an essential matrix. E = [t]R\n\t:returns: list of 4 possible camera matrices.\n\t\"\"\"\n\tU, S, V = np.linalg.svd(E)\n\n\t# Ensure rotation matrix are right-handed with positive determinant\n\tif np.linalg.det(np.dot(U, V)) < 0:\n\t\tV = -V\n\n\t# create 4 possible camera matrices (Hartley p 258)\n\tW = np.array([[0, -1, 0], [1, 0, 0], [0, 0, 1]])\n\tP2s = [np.vstack((np.dot(U, np.dot(W, V)).T, U[:, 2])).T,\n\t\t np.vstack((np.dot(U, np.dot(W, V)).T, -U[:, 2])).T,\n\t\t np.vstack((np.dot(U, np.dot(W.T, V)).T, U[:, 2])).T,\n\t\t np.vstack((np.dot(U, np.dot(W.T, V)).T, -U[:, 2])).T]\n\n\treturn P2s\n\n\n\ndef reconstruct_one_point(pt1, pt2, m1, m2):\n\t\"\"\"\n\t\tpt1 and m1 * X are parallel and cross product = 0\n\t\tpt1 x m1 * X = pt2 x m2 * X = 0\n\t\"\"\"\n\tA = np.vstack([\n\t\tnp.dot(skew(pt1), m1),\n\t\tnp.dot(skew(pt2), m2)\n\t])\n\tU, S, V = np.linalg.svd(A)\n\tP = np.ravel(V[-1, :4])\n\n\treturn P / P[3]","sub_path":"reconstruct/sfm.py","file_name":"sfm.py","file_ext":"py","file_size_in_byte":6465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"513466817","text":"import logging\n\n# logger = logging.basicConfig(\n# filename='debug.log', level=logging.DEBUG, format='%(levelname)s :: %(asctime)s %(message)s')\n# logging.warning('This is a message')\n# # logger.warning('This is a test')\n\n# logger = logging.getLogger('Something')\n# formatter = logging.Formatter(\n# '%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n# handler = logging.FileHandler('something.log')\n# handler.setLevel(logging.DEBUG)\n# handler.setFormatter(formatter)\n# logger.addHandler(handler)\n# logger.warning('This is a test')\n\n\nclass Logs:\n \"\"\"\n Base logger for all applications in scrappers\n \"\"\"\n logger = None\n\n def __init__(self, name='Default', logfile_name='scrappers.log'):\n logger = logging.getLogger(name)\n formatter = logging.Formatter('%(levelname)s :: %(asctime)s - %(name)s - %(message)s')\n handler = logging.FileHandler(logfile_name)\n handler.setLevel(logging.DEBUG)\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n self.logger = logger\n\n def __call__(self, name, logfile_name='scrappers.log'):\n self.__init__(name, logfile_name=logfile_name)\n return self.logger\n\ndefault = Logs()\n","sub_path":"apps/config/logs.py","file_name":"logs.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"570773224","text":"from tkinter import *\nfrom tkinter import filedialog\nimport random\nroot = Tk()\n\n\ndef sumBin(dec):\n if(dec[-1]==\"d\"):\n dec = int(dec[:-1])\n else:\n dec = int(dec)\n b = ''\n if(dec==0):\n b = '0'\n while(dec!=0):\n if(dec%2==1):\n b='1'+b\n dec=(dec-1)/2\n else:\n b='0'+b\n dec=dec/2\n return b\n\ndef hexaBin(hexa):\n numero =''\n diccionario = {\n '0':'0000',\n '1':'0001',\n '2':'0010',\n '3':'0011',\n '4':'0100',\n '5':'0101',\n '6':'0110',\n '7':'0111',\n '8':'1000',\n '9':'1001',\n 'A':'1010',\n 'B':'1011',\n 'C':'1100',\n 'D':'1101',\n 'E':'1110',\n 'F':'1111',\n }\n\n for i in hexa:\n numero+=diccionario[i]\n\n return numero\n\ndef Rellena(N,hasta):\n N=N.strip()\n longitud = hasta-len(N)\n Numero = '0'*longitud\n Numero+=N\n return Numero\n\n\nlista = {\n 'MOV A,B' : '1111110',\n 'MOV B,A' : '0000001',\n 'MOV A,Lit' : '0000010',\n 'MOV B,Lit' : '0000011',\n 'MOV A,(Dir)' : '0000100',\n 'MOV B,(Dir)' : '0000101',\n 'MOV (Dir),A' : '0000110',\n 'MOV (Dir),B' : '0000111',\n\n 'ADD A,B' : '0001011',\n 'ADD B,A' : '0001100',\n 'ADD A,Lit' : '0001101',\n 'ADD B,Lit' : '1000000',\n 'ADD A,(Dir)' : '0001110',\n 'ADD B,(Dir)' : '1000001',\n 'ADD (Dir)' : '0010000',\n\n 'SUB A,B' : '0010001',\n 'SUB B,A' : '0010010',\n 'SUB A,Lit' : '1000010',\n 'SUB B,Lit' : '1000011',\n 'SUB A,(Dir)' : '0010011',\n 'SUB B,(Dir)' : '1000100',\n 'SUB (Dir)' : '0010101',\n\n 'AND A,B' : '0010110',\n 'AND B,A' : '0010111',\n 'AND A,Lit' : '0011000',\n 'AND B,Lit' : '1000101',\n 'AND A,(Dir)' : '0011001',\n 'AND B,(Dir)' : '1000101',\n 'AND(Dir)' : '0011011',\n\n 'OR A,B' : '0011100',\n 'OR B,A' : '0011101',\n 'OR A,Lit' : '0011110',\n 'OR B,Lit' : '1000111',\n 'OR A,(Dir)' : '0011111',\n 'OR B,(Dir)' : '1001000',\n 'OR (Dir)' : '0100001',\n\n 'NOT A' : '0100010',\n 'NOT B,A' : '0100011',\n 'NOT (Dir),A' : '1010100',\n\n 'XOR A,B' : '0101000',\n 'XOR B,A' : '0101001',\n 'XOR A,Lit' : '0101010',\n 'XOR B,Lit' : '1001001',\n 'XOR A,(Dir)' : '0101011',\n 'XOR B,(Dir)' : '1001010',\n 'XOR (Dir)' : '0101101',\n\n 'SHL A' : '0101110',\n 'SHL B,A' : '0101111',\n 'SHL (Dir),A' : '0110011',\n\n 'SHR A' : '0110100',\n 'SHR B,A' : '0110101',\n 'SHR (Dir),A' : '0111001',\n\n 'INC A' : '11111110', ##sin uso\n 'INC B' : '0111010',\n 'INC (Dir)' : '1001011',\n\n 'DEC A' : '11111111', ##sin uso\n\n 'CMP A,B' : '0111011',\n 'CMP A,Lit' : '0111100',\n 'CMP A,(Dir)' : '1001100',\n\n 'JMP Ins' : '0111101',\n 'JEQ Ins' : '1001101',\n 'JNE Ins' : '1001110',\n 'JGT Ins' : '1001111',\n 'JGE Ins' : '1010001',\n 'JLT Ins' : '1010000',\n 'JLE Ins' : '1010010',\n 'JCR Ins' : '1010011',\n 'NOP' : '0000000'\n}\n#print(lista)\ninstrucciones = {}\n\n\nlabel = {}\n#labelVar = []\n'''for i in range(len(lista)):\n instrucciones[lista[i]]=Rellena(sumBin(i))\n ##print(lista[i]+\"=\"+str(i))\n#print(instrucciones)'''\n\n\norden_labels =[]\nl = []\n\n'''def leer(Archivo,label):\n ar = open(Archivo,'r')\n linea = ar.readline()\n\n while linea:\n\n nombre = linea.split(':')\n Nombre = nombre[0].strip()\n orden_labels.append(Nombre)\n\n label[Nombre]=[]\n while linea:\n linea = ar.readline()\n\n w = linea.split('//')\n\n if( ':' not in w[0]):\n label[Nombre].append(w[0].strip())\n else:\n break\n ar.close()'''\n\n\nvariables = {} #Diccionario de variables a direccion en ram\ndef variablesDataRAM(var):\n var = var.strip()\n [nombre,valor] = var.split(\" \")\n variables[nombre] = len(variables.keys())\n return variables\n\ndef variablesIns(var):\n var = var.strip()\n [nombre,valor] = var.split(\" \")\n variablesDataRAM(var)\n if(valor[-1]!=\"b\"):\n if(valor[-1]!=\"h\"):\n valor=sumBin(str(valor))\n else:\n valor = hexaBin(valor[:-1])\n else:\n valor = valor[:-1]\n return [\"MOV A,\"+str(valor)+\"b\",\"MOV (\"+str(variables[nombre])+\"),A\"] #transforma data a instruciones\n\ndef contador(Linea):\n conta = 0\n for i in Linea:\n if i == ' ':\n conta+=1\n else:\n break\n return conta\n\n\n'''def Leer(Archivo, label):\n Ar = open(Archivo,'r',encoding=\"latin-1\")\n Lineas = Ar.readlines()\n cont = 0\n cccc = -1\n primeras_lineas = []\n while cont < len(Lineas):\n nombre = Lineas[cont].strip()\n nombre = nombre.split(':')\n Nombre = nombre[0].strip()\n orden_labels.append(Nombre)\n label[Nombre]=[]\n #labelVar.append(Nombre+\" 0\") #Agregamos cada label como una var de valor 0\n\n while cont < len(Lineas):\n cont+=1\n if cont>=len(Lineas):\n break\n else:\n Linea_anterior = Lineas[cont-1].split(':')\n Linea_anterior = Linea_anterior[0].split('//')\n Linea_anterior = Linea_anterior[0].strip()\n w = Lineas[cont].split('//')\n\n if Linea_anterior in orden_labels:\n primeras_lineas.append(contador(w[0]))\n cccc+=1\n if w[0]!= '\\n':\n if(':' not in w[0]):\n cc = contador(w[0])\n\n if cc == primeras_lineas[cccc]:\n #label[Nombre].append(w[0].strip())\n l=w[0].strip()\n ins = l.split(\" \")[0]+\" \"+\"\".join(l.split(\" \")[1:])\n if(ins==\"DEC A\"):\n ins = \"SUB A,1\"\n if(ins==\"INC A\"):\n ins = \"ADD A,1\"\n label[Nombre].append(ins)\n else:\n label[\"CODE\"].append(w[0].strip())\n else:\n break\n Ar.close()'''\n\ndef orden_instrucciones(diccionario,valor,cantidad):\n if len(l)< cantidad:\n if valor != '':\n l.append(valor)\n x = valor.split()\n if len(x)>=2:\n if x != [] and x[1] in orden_labels:\n for z in diccionario[x[1]]:\n if z != '' :\n orden_instrucciones(diccionario,z,cantidad)\n\ndef lista_instrucciones(diccionario,cantidad):\n for x in diccionario[\"CODE\"]:\n orden_instrucciones(diccionario,x,cantidad)\n\ndef suma_instrucciones(diccionario, orden_labels):\n contador = 0\n for i in orden_labels:\n if i != \"DATA\":\n for x in diccionario[i]:\n if x != '':\n contador+= 1\n return contador\n\ninstrucciones2 = {} #Dict con data con instrucciones\ndef dataFinal(diccionario):\n for nombre2 in diccionario:\n if(nombre2 != \"DATA\"):\n instrucciones2[nombre2] = diccionario[nombre2]\n else:\n instrucciones2[\"DATA\"] = []\n\n for nombre in diccionario[\"DATA\"]:\n for ins in variablesIns(nombre):\n instrucciones2[\"DATA\"].append(ins)\n\n if(len(instrucciones2[\"DATA\"])>0):\n instrucciones2[\"DATA\"].append(\"MOV A,0\") #Limpia registro A despues de las variables\n\n '''for labelNombre in labelVar:\n for labelIns in variablesIns(labelNombre):\n instrucciones2[\"DATA\"].append(labelIns)'''\n\ndef esint(num):\n try:\n int(num)\n return True\n except:\n return False\n\ndef instr_binario(inst):\n #inst = inst.split(\" \")[1]\n lista_inst = inst.split(',')\n if lista_inst[0][0] == '(': #tipo mov (a),A\n #print('es direccion')\n if not esint(lista_inst[0][1]): #tipo mov (c),A\n if(not lista_inst[0][-2] == 'h'):\n return('variable izq')\n else:\n return('hexa izq')\n else:\n if lista_inst[0][-2] == 'b': #tipo mov (10b),A\n return('bin izq')\n elif lista_inst[0][-2] == 'h': #tipo mov (10h),A\n return('hexa izq')\n else:\n return('decimal izq') #tipo mov (10),A\n elif lista_inst[1][0] == '(': #Analogo al anterior\n if not esint(lista_inst[1][1]):\n if(not lista_inst[1][-2] == 'h'):\n return('variable der')\n else:\n return('hexa der')\n\n else:\n if lista_inst[1][-2] == 'b':\n return('bin der')\n elif lista_inst[1][-2] == 'h':\n return('hexa der')\n else:\n return('decimal der')\n\n elif lista_inst[1][-1] =='h':\n return('instruccion')\n else:\n return(\"instruccion\")\n\ndef insToType(valor):\n if not valor[0] == '(': #tipo XOR (var)\n return 0 #return('instruccion')\n elif not esint(valor[1]): #valor var\n if(not valor[-2] == 'h'):\n return 1 #return('variable')\n else:\n return 3 #return('hexa')\n else:\n if valor[-2] == 'b': #valor 10b\n return 2 #return('bin')\n elif valor[-2] == 'h': #valor 10h\n return 3 #return('hexa')\n else:\n return 4 #return('decimal') #valor 10\n\n###cambie esto\ndef tipoVar(valor):\n if(valor[-1]==\"b\"):\n return 1 #es binario\n elif(valor[-1]==\"h\"):\n return 2 #es hexa\n elif(not esint(valor[0])):\n return 0 #es variable\n else:\n return 3 #es dec\n\ndef transformarBin(valor):\n if(tipoVar(valor)==1): #lit binario\n return valor[:-1] #lit en binario sin \"b\"\n elif(tipoVar(valor)==2): #lit hexa\n return hexaBin(valor[:-1]) #lit en bin transformado desde hexa\n elif(tipoVar(valor)==3): #lit en dec\n return sumBin(str(valor)) #lit en bin transformado desde\n\ndef ins_generica(ins):\n valor=\" \" #por si aparece 'NOP'\n izqcoma=\" \"\n dercoma=\" \"\n nombre,valor=ins.split(\" \")\n nombre = nombre.strip()\n nombre = nombre.replace(\"\\t\",\"\")\n valor = valor.strip()\n retorna = \"\"\n if(nombre!=\"\"):\n if(valor.count(\",\")>0): #del tipo MOV x,y\n izqcoma,dercoma=valor.split(\",\") #lado izq y lado der de la coma\n if(instr_binario(valor)==\"instruccion\"): #tipo MOV A,Lit || MOV A,B\n if(tipoVar(izqcoma)!=0): #tipo MOV Lit,A\n retorna = str(nombre)+\" Lit,\"+str(dercoma)\n izqcoma=transformarBin(izqcoma)\n elif(tipoVar(dercoma)!=0): #tipo MOV A,Lit\n retorna = str(nombre)+\" \"+str(izqcoma)+\",Lit\"\n dercoma=transformarBin(dercoma)\n else:\n retorna = str(nombre)+\" \"+str(izqcoma)+\",\"+str(dercoma)\n elif(instr_binario(valor)==\"variable izq\"): #tipo MOV (c),A\n retorna = str(nombre)+\" (Dir),\"+str(dercoma)\n izqcoma = \"(\"+str(transformarBin(str(variables[izqcoma[1:-1]])))+\")\" #transforma var a lugar en ram (binario)\n elif(instr_binario(valor)==\"variable der\"): #tipo MOV A,(c)\n retorna = str(nombre)+\" \"+str(izqcoma)+\",(Dir)\"\n dercoma = \"(\"+str(transformarBin(str(variables[dercoma[1:-1]])))+\")\" #transforma var a lugar en ram (binario)\n elif(instr_binario(valor)==\"bin izq\" or instr_binario(valor)==\"hexa izq\" or instr_binario(valor)==\"decimal izq\"): #tipo MOV (6),A\n retorna = str(nombre)+\" (Dir),\"+str(dercoma)\n izqcoma = \"(\"+str(transformarBin(izqcoma[1:-1]))+\")\"\n elif(instr_binario(valor)==\"bin der\" or instr_binario(valor)==\"hexa der\" or instr_binario(valor)==\"decimal der\"): #tipo MOV A,(6)\n retorna = str(nombre)+\" \"+str(izqcoma)+\",(Dir)\"\n dercoma = \"(\"+str(transformarBin(dercoma[1:-1]))+\")\"\n '''print(valor)\n print(instr_binario(valor))\n print(izqcoma)\n print(dercoma)'''\n else: #del tipo JMP abc || DEC A\n dercoma = \" \"\n '''if(valor.count(\"(\")>0): #del tipo ICL (Dir)\n retorna = str(nombre)+\" (Dir)\"\n if not esint(valor[1]): #tipo\n izqcoma = valor\n else:\n izqcoma = \"(\"+transformarBin(valor[1:-1])+\")\"\n else:'''\n if(nombre==\"NOP\"):\n retorna = str(nombre)\n izqcoma = \" \"\n elif(nombre[0]!=\"J\"): #Todos los que no comienzan con J\n #retorna = str(nombre)+\" \"+str(valor)\n if(insToType(valor)==0): #instruccion: tipo INC A\n retorna = str(nombre)+\" \"+str(valor)\n izqcoma = str(valor)\n elif(insToType(valor)==1): #variable: tipo INC (var)\n retorna = str(nombre)+\" (Dir)\"\n izqcoma = \"(\"+str(transformarBin(str(variables[valor[1:-1]])))+\")\"\n dercoma = str(valor)\n else:\n #retorna = str(nombre)+\" Lit\"\n retorna = str(nombre)+\" (Dir)\" #Deberia ser Lit, pero no existe, y en ejemplo 6 se cae\n izqcoma = \"(\"+str(transformarBin(str(valor[1:-1])))+\")\"\n dercoma = str(valor)\n else: #JMP etc\n retorna = str(nombre)+\" Ins\"\n izqcoma = \"(\"+str(transformarBin(str(countIns[valor])))+\")\"\n dercoma = valor\n\n return [retorna,izqcoma,dercoma]\n else:\n return False\n '''print(izqcoma)\n print(dercoma)\n print(retorna)\n print()\n #print(nombre)\n #print(valor)'''\n\nlistaInsBin = []\nlistaInsTxt = []\ncountIns = {}\ndef dataFinalBin(dict):\n opcode = 0\n literal = 0\n count = 0 #num de linea q estamos\n ###cambie esto!!! #no era lo mismo? pero bueno lo dejo asi\n for nombre in orden_labels:\n countIns[nombre] = count\n funcion = dict[nombre]\n for ins in funcion:\n count+=1\n\n\n for nombre in orden_labels:\n #print(nombre)\n #countIns[nombre] = count\n #print(countIns)\n funcion = dict[nombre] #data,code,end,etc\n for ins in funcion: #cada instruccion de cada funcion\n if(ins_generica(ins)):\n print(ins_generica(ins))\n insgen,izq,der=ins_generica(ins)\n if(izq[0]==\"(\"): #direccion\n literal=Rellena(str(izq[1:-1]),16)\n elif(der[0]==\"(\"): #direccion\n literal=Rellena(str(der[1:-1]),16)\n elif(esint(izq)):\n literal=Rellena(str(izq),16)\n elif(esint(der)):\n literal=Rellena(str(der),16)\n else:\n literal=Rellena(\"\",16)\n opcode=Rellena(str(lista[insgen]),17)\n #print(lista)\n #print(str(lista[insgen]))\n #print(opcode)\n #print(var)\n print(str(opcode)+str(literal))\n listaInsBin.append(str(opcode)+str(literal))\n listaInsTxt.append(ins_generica(ins))\n #count += 1\n print(listaInsTxt)\n\ndef rellenaLista(lista,N):\n for i in range(len(lista), N):\n lista.append(Rellena(\"\",33))\n\ndef outputTXT(file):\n f = open(file,'w+')\n\n ##Info\n f.write(\"-- Variable | Direccion (dec) | Direccion (bin)\\n\")\n for variable in variables:\n f.write(\"-- \"+str(variable)+\" | \"+str(variables[variable])+\" | \"+str(sumBin(str(variables[variable])))+\"\\n\")\n f.write(\"---\\n\")\n for linea in countIns:\n f.write(\"-- \"+str(linea)+\" | \"+str(countIns[linea])+\" | \"+str(sumBin(str(countIns[linea])))+\"\\n\")\n f.write(\"\\n\")\n f.write(\"library IEEE;\\n\")\n f.write(\"use IEEE.STD_LOGIC_1164.ALL;\\n\")\n f.write(\"use IEEE.STD_LOGIC_UNSIGNED.ALL;\\n\")\n f.write(\"USE IEEE.NUMERIC_STD.ALL;\\n\")\n f.write(\"\\n\")\n f.write(\"entity ROM is\\n\")\n f.write(\"\\tPort (\\n\")\n f.write(\"\\t\\taddress : in std_logic_vector(11 downto 0);\\n\")\n f.write(\"\\t\\tdataout : out std_logic_vector(32 downto 0)\\n\")\n f.write(\"\\t\\t);\\n\")\n f.write(\"end ROM;\\n\")\n f.write(\"\\n\")\n f.write(\"architecture Behavioral of ROM is\\n\")\n f.write(\"\\n\")\n f.write(\"type memory_array is array (0 to ((2 ** 12) - 1) ) of std_logic_vector (32 downto 0);\\n\")\n f.write(\"\\n\")\n f.write(\"signal memory : memory_array:= (\\n\")\n for i in range(len(listaInsBin)):\n if((i+1) != len(listaInsBin)):\n f.write(str('\\t\"'+listaInsBin[i]+'\",'))\n else: #sin coma al final\n f.write(str('\\t\"'+listaInsBin[i]+'\"'))\n\n try:\n f.write(str(\" -- \"+listaInsTxt[i][0]+\" | \"+listaInsTxt[i][1]+\" | \"+listaInsTxt[i][2]+\"\\n\"))\n except:\n f.write(\"\\n\")\n f.write(\");\\n\")\n f.write(\"begin\\n\")\n f.write(\"\\n\")\n f.write(\"\\tdataout <= memory(to_integer(unsigned(address)));\\n\")\n f.write(\"\\n\")\n f.write(\"end Behavioral;\")\n\n f.close()\n\ndef Leer_Archivo(Archivo,label):\n archivo = open(Archivo,'r',encoding='latin-1')\n Linea= archivo.readline()\n Lineas = [] ## las Lineas que nos sirver\n Espacios_Label=[] ## espacios o tabulaciones de los Labels\n contador_label =-1 ## cuantos labels hay\n\n while Linea:\n temp = Linea.split('//')\n Linea = temp[0] # si la linea tiene comentarios no los pesacamos\n if Linea.strip():\n Lineas.append(Linea) ## agregamos las lineas que no son // y que no son espacion es blanco\n Linea = archivo.readline()\n\n for i in range(len(Lineas)):\n Linea_actual = Lineas[i]\n if Linea_actual.strip():\n\n if ':' in Linea_actual:\n Auxiliar = Linea_actual.split(':')\n Nombre_Label = Auxiliar[0].strip()#Nombre label\n label[Nombre_Label] = []\n orden_labels.append(Nombre_Label)\n contador_label+=1\n\n try:\n if':' in Lineas[i+1]:\n Espacios_Label.append(0)#si el label no tiene ninguna instruccion le ponemos 0 nomas\n except:\n continue\n else:\n Linea_anterior = Lineas[i-1]# linea anterior a la liena en la que vamos\n Espacios_linea_actual = contador(Linea_actual) #espacios o tabulaciones de la linea actual\n Linea_actual = Linea_actual.strip()\n Linea_actual = Linea_actual.split(\" \")[0]+\" \"+\"\".join(Linea_actual.split(\" \")[1:])\n Linea_actual = Linea_actual.replace('\\r',' ') #Porsiacaso\n Linea_actual = Linea_actual.replace(' ','\\t')\n Linea_actual = Linea_actual.replace('\\t',' ',1)\n Linea_actual = Linea_actual.replace('\\t','') # la dejamos con un solo espacio MOV A,B\n\n if ':' in Linea_anterior:\n Espacios_Label.append(Espacios_linea_actual)#Primera linea de cada label, agregamos sus espacios en blaco al comienzo\n if Espacios_linea_actual >= Espacios_Label[contador_label]: # si la linea en la que vamos tiene igual o mas espacios al comienzo que la linea anterior es porque\n #pertenence al mismo label, sino es de CODE\n LabelName = orden_labels[contador_label]\n if(Linea_actual==\"DEC A\"):\n Linea_actual = \"SUB A,1\"\n if(Linea_actual==\"INC A\"):\n Linea_actual = \"ADD A,1\"\n label[LabelName].append(Linea_actual)\n else:\n r = random.randint(0,100000)\n extra = str(r)\n label[extra]=[]\n label[extra].append(Linea_actual)\n orden_labels.append(str(r))\n print(label)\n archivo.close()\n\nroot.fileopenname = filedialog.askopenfilename(initialdir = \"./\",title = \"Escoge input\")\nLeer_Archivo(root.fileopenname,label)\n\ndataFinal(label) #Calcula los comandos en texto\n\ndataFinalBin(instrucciones2) #transforma instrucciones a bin y agrega en lista listaInsBin\n\nrellenaLista(listaInsBin,4096) #rellena la lista listaInsBin con 4096 elementos\n\nroot.filesavename = filedialog.asksaveasfilename(initialdir = \"./\", title = \"Escoge output\")\noutputTXT(root.filesavename)\n#IMPORTATE: LISTA CON 4096 ES LA LISTA listaInsBin\n\n\n\n\n#print(listaInsBin)\n#print(variables)\n\n\nlista_instrucciones(label,suma_instrucciones(label,orden_labels))\n\n#print(l)\n","sub_path":"Entrega 2/python/4096.py","file_name":"4096.py","file_ext":"py","file_size_in_byte":20476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"135145820","text":"import tensorflow as tf\n\n\nclass DeepCoNN(object):\n def __init__(\n self, user_length, item_length, num_classes, user_vocab_size, item_vocab_size, fm_k, n_latent, user_num,\n item_num,\n embedding_size, filter_sizes, num_filters, l2_reg_lambda=0.0, l2_reg_V=0.0):\n self.input_u = tf.placeholder(tf.int32, [None, user_length], name=\"input_u\")\n self.input_i = tf.placeholder(tf.int32, [None, item_length], name=\"input_i\")\n self.input_y = tf.placeholder(tf.float32, [None, 1], name=\"input_y\")\n self.input_uid = tf.placeholder(tf.int32, [None, 1], name=\"input_uid\")\n self.input_iid = tf.placeholder(tf.int32, [None, 1], name=\"input_iid\")\n self.dropout_keep_prob = tf.placeholder(tf.float32, name=\"dropout_keep_prob\")\n batch_size = tf.shape(self.input_u)[0]\n print(\"user_length: \", user_length)\n print(\"item_length: \", item_length)\n print(\"batch_size \", batch_size)\n\n l2_loss = tf.constant(0.0)\n\n with tf.name_scope(\"user_embedding\"):\n self.W1 = tf.Variable(\n tf.random_uniform([user_vocab_size, embedding_size], -1.0, 1.0),\n name=\"W\")\n self.embedded_users = tf.nn.embedding_lookup(self.W1, self.input_u)\n # N x user_len x emb_size (N x in_w x in_c)\n\n with tf.name_scope(\"item_embedding\"):\n self.W2 = tf.Variable(\n tf.random_uniform([item_vocab_size, embedding_size], -1.0, 1.0),\n name=\"W\")\n self.embedded_items = tf.nn.embedding_lookup(self.W2, self.input_i)\n\n x = self.embedded_users\n print(\"embedded_users: \", x)\n for i in range(len(filter_sizes)):\n k = filter_sizes[i]\n n_channels = num_filters[i]\n with tf.name_scope(\"user_conv-maxpool-%s\" % k):\n conv = tf.layers.conv1d(inputs=x, filters=n_channels, kernel_size=k, strides=1,\n padding='same', activation=tf.nn.relu)\n max_pool = tf.layers.max_pooling1d(inputs=conv, pool_size=4, strides=4, padding='same')\n x = max_pool\n print(\"conv: \", conv)\n print(\"max_pool: \", max_pool)\n dim = x.get_shape()[1] * x.get_shape()[2]\n self.h_pool_flat_u = tf.reshape(x, [-1, dim])\n\n x = self.embedded_items\n print(\"embedded_items: \", x)\n for i in range(len(filter_sizes)):\n k = filter_sizes[i]\n n_channels = num_filters[i]\n with tf.name_scope(\"item_conv-maxpool-%s\" % k):\n conv = tf.layers.conv1d(inputs=x, filters=n_channels, kernel_size=k, strides=1,\n padding='same', activation=tf.nn.relu)\n max_pool = tf.layers.max_pooling1d(inputs=conv, pool_size=4, strides=4, padding='same')\n x = max_pool\n print(\"conv: \", conv)\n print(\"max_pool: \", max_pool)\n\n dim = x.get_shape()[1] * x.get_shape()[2]\n self.h_pool_flat_i = tf.reshape(x, [-1, dim])\n\n with tf.name_scope(\"dropout\"):\n self.h_drop_u = tf.nn.dropout(self.h_pool_flat_u, 1.0)\n self.h_drop_i = tf.nn.dropout(self.h_pool_flat_i, 1.0)\n print(\"self.h_drop_u: \", self.h_drop_u)\n print(\"self.h_drop_i: \", self.h_drop_i)\n\n with tf.name_scope(\"get_fea\"):\n self.u_fea = tf.layers.dense(self.h_drop_u, n_latent)\n self.i_fea = tf.layers.dense(self.h_drop_i, n_latent)\n\n with tf.name_scope('fm'):\n self.z = tf.nn.relu(tf.concat([self.u_fea, self.i_fea], axis=1))\n\n # self.z=tf.nn.dropout(self.z,self.dropout_keep_prob)\n\n WF1 = tf.Variable(\n tf.random_uniform([n_latent * 2, 1], -0.1, 0.1), name='fm1')\n Wf2 = tf.Variable(\n tf.random_uniform([n_latent * 2, fm_k], -0.1, 0.1), name='fm2')\n one = tf.matmul(self.z, WF1)\n\n inte1 = tf.matmul(self.z, Wf2)\n inte2 = tf.matmul(tf.square(self.z), tf.square(Wf2))\n\n inter = (tf.square(inte1) - inte2) * 0.5\n\n inter = tf.nn.dropout(inter, self.dropout_keep_prob)\n\n inter = tf.reduce_sum(inter, 1, keepdims=True)\n print(inter)\n b = tf.Variable(tf.constant(0.1), name='bias')\n\n self.predictions = one + inter + b\n\n print(self.predictions)\n with tf.name_scope(\"loss\"):\n # losses = tf.reduce_mean(tf.square(tf.subtract(self.predictions, self.input_y)))\n losses = tf.nn.l2_loss(tf.subtract(self.predictions, self.input_y))\n\n self.loss = losses + l2_reg_lambda * l2_loss\n\n with tf.name_scope(\"accuracy\"):\n self.mae = tf.reduce_mean(tf.abs(tf.subtract(self.predictions, self.input_y)))\n self.accuracy = tf.sqrt(tf.reduce_mean(tf.square(tf.subtract(self.predictions, self.input_y))))\n","sub_path":"model/myDeepCoNN.py","file_name":"myDeepCoNN.py","file_ext":"py","file_size_in_byte":4934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"429761661","text":"import random\n\nif __name__ == '__main__':\n V = 100\n C_atk = 100\n C_def = 100\n N = 500\n M_atk = 5\n M_def = 5\n\n P_def = 0\n P_atk = 0\n\n S_atk = 1.0\n\n k = 100\n mean_attacker_payoff = 0\n mean_defender_payoff = 0\n for a in range(0, k):\n current_atk_v = -1\n current_def_v = -1\n\n atk_vectors = [i for i in range(100)]\n M_atk_vectors = []\n M_def_vectors = []\n\n successful_atks = 0\n for i in range(0, N):\n # Attacker chooses attack vector\n if i < M_atk:\n current_atk_v = atk_vectors[int(random.random()*len(atk_vectors))]\n M_atk_vectors.append(current_atk_v)\n else:\n prob = random.random()\n if prob <= S_atk:\n chosen_index = int(random.random()*len(M_atk_vectors))\n current_atk_v = M_atk_vectors[chosen_index]\n else:\n remaining_atk_vectors = atk_vectors[:]\n for atk_vec in M_atk_vectors:\n if atk_vec in remaining_atk_vectors:\n remaining_atk_vectors.remove(atk_vec)\n\n current_atk_v = remaining_atk_vectors[int(random.random()*len(remaining_atk_vectors))]\n\n M_atk_vectors.pop(0)\n M_atk_vectors.append(current_atk_v)\n\n # Defender chooses defense vector\n if i < M_def:\n current_def_v = int(random.random()*len(atk_vectors))\n M_def_vectors.append(current_atk_v)\n else:\n chosen_index = int(random.random()*len(M_def_vectors))\n current_def_v = M_def_vectors[chosen_index]\n\n M_def_vectors.pop(0)\n M_def_vectors.append(current_atk_v)\n\n # See if attack was successful or not\n if current_atk_v == current_def_v: # successful defense\n P_atk += -C_atk\n P_def += -C_def\n else: # successful attack\n successful_atks += 1\n P_atk += 10000 - C_atk\n P_def += -10000 - C_def\n\n mean_attacker_payoff += P_atk\n mean_defender_payoff += P_def\n\n #print(\"Successful Attacks: \" + str(successful_atks))\n #print(\"Successful Defenses: \" + str(N - successful_atks))\n #print(\"Attacker Payoff: \" + str(P_atk))\n #print(\"CactusCard Payoff: \" + str(P_def))\n\n mean_attacker_payoff = float(mean_attacker_payoff) / float(k)\n mean_defender_payoff = float(mean_defender_payoff) / float(k)\n\n print(\"Attacker Payoff: \" + str(mean_attacker_payoff))\n print(\"CactusCard Payoff: \" + str(mean_defender_payoff))","sub_path":"project/part3/Question4Simulation.py","file_name":"Question4Simulation.py","file_ext":"py","file_size_in_byte":2715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"163510503","text":"__author__ = 'drizzutojr'\n\n# this code is from rosetta code\n\ndef quickSort(arr):\n less = []\n pivotList = []\n more = []\n if len(arr) <= 1:\n return arr\n else:\n initial_date = arr[0][\"due date\"]\n initial_date_format = str(initial_date[6:10]) + str(initial_date[3:5]) + str(initial_date[0:2])\n pivot = int(initial_date_format)\n for assignment in arr:\n compare_date = str(assignment[\"due date\"][6:10]) + \\\n str(assignment[\"due date\"][3:5]) + \\\n str(assignment[\"due date\"][0:2])\n if int(compare_date) < pivot:\n less.append(assignment)\n elif int(compare_date) > pivot:\n more.append(assignment)\n else:\n pivotList.append(assignment)\n less = quickSort(less)\n more = quickSort(more)\n return less + pivotList + more","sub_path":"Middleware/date_quicksort.py","file_name":"date_quicksort.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"84144040","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\n\nfrom PIL import Image\nimport numpy as np\nimport math\n\nw, h = 5000, 6000\n\ndata = np.zeros((h, w, 3), dtype=np.int8)\n\ncolCnt = 0\nfor i in range(w):\n value = 125+125.0*math.sin(0.00005*colCnt*i)#*colCnt*1.0)\n\n for j in range(h):\n data[j,i] = [value, value, value]\n colCnt = colCnt+2\nimg = Image.fromarray(data, 'RGB')\n\nimg.save('my.png')\n\nimg.show()\n","sub_path":"createHDNCMask_SineVerlauf.py","file_name":"createHDNCMask_SineVerlauf.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"242646993","text":"from ROOT import TGraph, TFile, TGraphAsymmErrors\nfrom array import array\nimport os\nimport glob,math\nimport matplotlib.pyplot as plt\n\nfile1='/Users/dekumar/cernbox/monoH_lhefiles/2HDM_sintheta_scan_tan_1_mh3_600_mh4_100/Events/scan_run_[03-12].txt'\nfile2='/Users/dekumar/cernbox/monoH_lhefiles/monoH_tanbetascan_Ma_100_MA_600_sintheta_7/Events/scan_run_[01-11].txt'\nf=open(file1,'r')\n\nsin=[]\ncross=[]\n\nfor line in f:\n if 'run_' in line:\n # print (line.split()[1],\" \",line.split()[2])\n sp=line.split()[1]\n CS=line.split()[2]\n # print (CS)\n sin.append(float(sp))\n cross.append(float(CS))\n\nf.close()\n\nprint (sin)\nprint (cross)\nplt.plot(sin,cross,'-o',label='$M_{A}=600, M_{a}=100,M_{\\chi}=10, $'+r'$tan{\\beta}$=1 ',color='red')\n\n# plt.rc('axes', labelsize=20)\nplt.xlabel(r'$Sin{\\theta}$')\nplt.ylabel(\"Cross section(pb)\")\n# plt.xticks([.1, .2, .3, .35, .4, .5,.6,.7,.8,.9])\nplt.legend()#ncol=3,title=r\"tan$\\beta$\")\nplt.title(r\"monoH+DM 2HDM+a\")\nplt.savefig('sintheta_scan.pdf')\nplt.savefig('sintheta_scan.png')\nplt.close('all')\n\n\nf=open(file2,'r')\n\ntan=[]\ncross2=[]\n\nfor line in f:\n if 'run_' in line:\n # print (line.split()[1],\" \",line.split()[2])\n sp=line.split()[1]\n CS=line.split()[2]\n # print (CS)\n tan.append(float(sp))\n cross2.append(float(CS))\n\nf.close()\n\nprint (tan)\nprint (cross2)\nplt.plot(tan,cross2,'-o',label='$M_{A}=600, M_{a}=100,M_{\\chi}=10, $'+r'$Sin{\\theta}$=0.7 ',color='red')\n\nplt.rc('axes', labelsize=20)\nplt.xlabel(r'$Tan{\\beta}$')\nplt.ylabel(\"Cross section(pb)\")\n# plt.xticks([.1, .2, .3, .35, .4, .5,.6,.7,.8,.9])\nplt.legend()#ncol=3,title=r\"tan$\\beta$\")\nplt.title(r\"monoH+DM 2HDM+a\")\nplt.savefig('tan_scan.pdf')\nplt.savefig('tan_scan.png')\nplt.close('all')\n","sub_path":"bbDM_2HDM_gridpack_cards/XsectionPlotter.py","file_name":"XsectionPlotter.py","file_ext":"py","file_size_in_byte":1786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"623355378","text":"import redis\nimport pylab as plt\n\nplt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签\nplt.rcParams['axes.unicode_minus']=False #用来正常显示负号\n\n\n# 连接池\npool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)\nr = redis.Redis(connection_pool=pool)\nsex_dict = eval(r.hget('anadata', 'sex'))\n\n'''\nsex_dict['男']\nsex_dict['女']\nsex_dict['未知']\n'''\nfig1 = plt.figure('男女比例')\nrects1 =plt.bar(left = (0.2),height = (sex_dict['男']),color=('g'),label=(('男')),width = 0.2,align=\"center\",yerr=0.000001)\nrects2 =plt.bar(left = (0.6),height = (sex_dict['女']),color=('b'),label=(('女')),width = 0.2,align=\"center\",yerr=0.000001)\nrects3 =plt.bar(left = (1),height = (sex_dict['未知']),color=('r'),label=(('未知')),width = 0.2,align=\"center\",yerr=0.000001)\n\nplt.legend()\nplt.xticks((0.2,0.6,1),('男','女','未知'))\nplt.title('男女比例') # 标题\nplt.ylim(0,40000)\nplt.xlabel('性别')\nplt.ylabel('人数')\n\ndef autolabel(rects):\n for rect in rects:\n height = rect.get_height()\n plt.text(rect.get_x()+rect.get_width()/2., 1.03*height, '%s' % float(height))\nautolabel(rects1)\nautolabel(rects2)\nautolabel(rects3)\nplt.show()\n\n","sub_path":"userfulPythonScript/spider/coding_spider/sex_figure.py","file_name":"sex_figure.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"374159431","text":"import html\nimport requests\nimport os\nimport xml.etree.ElementTree as ET\nimport sys\nimport re\nfrom enum import Enum\nimport xml.dom.minidom\n\n\nclass StringResourcePartType(Enum):\n TEXT = 1\n SPECIALCHAR = 2\n ESCAPESEQUENCE = 3\n WHITESPACE = 4\n\n\nclass StringResourcePart:\n type = None\n text = None\n\n\nclass StringResource:\n translatable = False\n name = \"\"\n parts = None\n\n\nclass StringResourceFile:\n strings = None\n\n\ndef concatstringresourceparts(parts):\n ret = \"\"\n for part in parts:\n ret += part.text\n return ret\n\n\ndef extractstring(text, name, translatable):\n string = StringResource()\n string.name = name\n string.translatable = translatable\n string.parts = []\n current = \"\"\n charIndex = 0\n while charIndex < len(text):\n if text[charIndex] == \"%\":\n if len(current) > 0:\n part = StringResourcePart()\n part.type = StringResourcePartType.TEXT\n part.text = current\n string.parts.append(part)\n\n current = text[charIndex]\n charIndex += 1\n while charIndex < len(text):\n if text[charIndex] == \" \":\n charIndex -= 1\n break\n current += text[charIndex]\n charIndex += 1\n part = StringResourcePart()\n part.type = StringResourcePartType.SPECIALCHAR\n part.text = current\n string.parts.append(part)\n current = \"\"\n elif text[charIndex] == \" \":\n if len(current) > 0:\n part = StringResourcePart()\n part.type = StringResourcePartType.TEXT\n part.text = current\n string.parts.append(part)\n\n current = text[charIndex]\n charIndex += 1\n while charIndex < len(text):\n if text[charIndex] != \" \":\n charIndex -= 1\n break\n current += text[charIndex]\n charIndex += 1\n part = StringResourcePart()\n part.type = StringResourcePartType.WHITESPACE\n part.text = current\n string.parts.append(part)\n current = \"\"\n elif text[charIndex] == \"\\\\\":\n if len(current) > 0:\n part = StringResourcePart()\n part.type = StringResourcePartType.TEXT\n part.text = current\n string.parts.append(part)\n current = text[charIndex]\n charIndex += 1\n current += text[charIndex]\n part = StringResourcePart()\n part.type = StringResourcePartType.ESCAPESEQUENCE\n part.text = current\n string.parts.append(part)\n current = \"\"\n elif text[charIndex] == \"\\t\":\n print(\"TAB\")\n elif text[charIndex] == \"\\n\":\n print(\"NEWLINE\")\n else:\n current += text[charIndex]\n charIndex += 1\n if len(current) > 0:\n part = StringResourcePart()\n part.type = StringResourcePartType.TEXT\n part.text = current\n string.parts.append(part)\n return string\n\n\ndef readresourcefile(file):\n print(\"ReadResource: \" + file)\n ret = StringResourceFile()\n ret.strings = []\n\n tree = ET.parse(file)\n root = tree.getroot()\n\n for i in range(len(root)):\n text = root[i].get('translatable')\n isTranslatable = False\n if text is None:\n isTranslatable = True\n elif text == \"true\":\n isTranslatable = True\n if root[i].tag == 'string-array':\n for j in range(len(root[i])):\n isItemTranslatable = root[i][j].get('translatable')\n if isItemTranslatable is None:\n isItemTranslatable = True\n ret.strings.append(extractstring(root[i][j].text, root[i][j].get('name'), isItemTranslatable))\n else:\n ret.strings.append(extractstring(root[i].text, root[i].get('name'), isTranslatable))\n print(\"Done Reading\")\n return ret\n\n\ndef writeresourcefile(resource, outfile):\n print(\"Write Resource: \" + outfile)\n resources = ET.Element(\"resources\")\n for string in resource.strings:\n stringelement = ET.SubElement(resources, 'string')\n stringelement.set('name', string.name)\n if not string.translatable:\n stringelement.set('translatable', \"false\")\n stringelement.text = concatstringresourceparts(string.parts)\n xmlstring = ET.tostring(resources, encoding=\"utf8\", method=\"xml\")\n minixml = xml.dom.minidom.parseString(xmlstring.decode(\"utf-8\"))\n prettystring = minixml.toprettyxml()\n\n file = open(outfile, \"w\", encoding=\"utf8\")\n file.write(prettystring)\n file.close()\n return\n\n\ndef translatestring(string, from_language=\"auto\", to_language=\"auto\"):\n ret = StringResource()\n ret.translatable = True\n ret.name = string.name\n ret.parts = []\n for part in string.parts:\n if part.type == StringResourcePartType.TEXT:\n respart = StringResourcePart()\n respart.type = StringResourcePartType.TEXT\n respart.text = translate(part.text, to_language, from_language)\n ret.parts.append(respart)\n else:\n ret.parts.append(part)\n return ret\n\n\ndef translateresource(resource, from_language=\"auto\", to_language=\"auto\"):\n print(\"Translate Resource\")\n ret = StringResourceFile()\n ret.strings = []\n for string in resource.strings:\n if string.translatable:\n ret.strings.append(translatestring(string, from_language, to_language))\n else:\n ret.strings.append(string)\n print(\"Done Translating\")\n return ret\n\n\n# This subroutine extracts the string including html tags\n# and may replace \"root[i].text\". \n# It cannot digest arbitrary encodings, so use it only if necessary.\ndef findall_content(xml_string, tag):\n pattern = r\"<(?:\\w+:)?%(tag)s(?:[^>]*)>(.*)'\n after_trans = ' \" + result)\n return result\n\n\ndef printusage():\n print(\"Usage: parrot.py RESOURCES_ROOT\")\n\n\ndef main():\n if len(sys.argv) != 2:\n printusage()\n return\n inlang = \"en\"\n langs = [\"cs\", \"de\", \"es\", \"fr\", \"hu\", \"in\", \"it\", \"ja\", \"nl\", \"ru\", \"sl\", \"sv\", \"th\", \"tr\", \"vi\", \"zh\"]\n rootpath = sys.argv[1]\n infile = rootpath + \"/values/strings.xml\"\n\n inputResource = readresourcefile(infile)\n\n for lang in langs:\n langdir = rootpath + \"/values-\" + lang\n langfile = langdir + \"/strings.xml\"\n if not os.path.exists(langdir):\n os.makedirs(langdir)\n elif os.path.exists(langfile):\n print(\"Language File: \" + langfile + \" already exists. Skipping...\")\n continue\n writeresourcefile(translateresource(inputResource, inlang, lang), langfile)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"parrot.py","file_name":"parrot.py","file_ext":"py","file_size_in_byte":8666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"9451665","text":"from mTree.microeconomic_system.agent import Agent\nfrom mTree.microeconomic_system.directive_decorators import *\nfrom mTree.microeconomic_system.message_space import Message\nfrom random import *\n\n\n@directive_enabled_class\nclass SearchAgent(Agent):\n def __init__(self):\n print(\"a class has been created... or something\")\n self.property_x = 1\n self.property_y = 2\n self.box_list = None\n self.institution = None\n\n @directive_decorator(\"initialize_agent\")\n def initialize_agent(self, message:Message):\n print(\"initializing agent\")\n payload = message.get_payload()\n self.institution = payload[\"institution\"]\n\n @directive_decorator(\"start_agent\")\n def start_agent(self, message):\n print(\"starting the agent...\")\n\n @directive_decorator(\"setup_boxes\")\n def setup_boxes(self, message:Message):\n payload = message.get_payload()\n self.box_list = payload[\"box_list\"]\n\n @directive_decorator(\"make_choice\")\n def make_choice(self, message):\n print(\"received choices from institution...\")\n element_selected = self.select_box()\n choice_message = Message()\n choice_message.set_sender(self)\n choice_message.set_directive(\"choice\")\n choice_message.set_payload({\"selected_element\": element_selected})\n self.send(self.institution, choice_message)\n\n def select_box(self):\n random_element = randrange(0, len(self.box_list))\n box_value = self.box_list[random_element]\n if box_value == \"R\":\n random_element = self.select_box()\n return random_element\n\n","sub_path":"Holt_Laury Monte Carlo and analysis with new mTree/box_search/search_agent.py","file_name":"search_agent.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"229621236","text":"import json\nimport os, os.path\nfrom django.utils.decorators import method_decorator\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.views.generic import View\nfrom django.http import HttpResponse\nfrom datetime import datetime\nimport markdown2\n\n# Create your views here.\nclass FilesProxy(View):\n\n def http_response_from_struct(self, answer):\n return HttpResponse(json.dumps(answer))\n\n def not_authenticated_error(self, request):\n \"\"\"\n The error to return as-is if user is not authenticated\n \"\"\"\n if 'r2lab_context' not in request.session or \\\n 'user_details' not in request.session['r2lab_context']:\n return self.http_response_from_struct(\n {'error' : 'User is not authenticated'})\n\n def decode_body_as_json(self, request):\n utf8 = request.body.decode()\n return json.loads(utf8)\n\n # @method_decorator(csrf_protect)\n def post(self, request, verb):\n # auth_error = self.not_authenticated_error(request)\n # if auth_error:\n # return auth_error\n try:\n record = self.decode_body_as_json(request)\n if verb == 'get':\n return self.which_file(record)\n else:\n return self.http_response_from_struct(\n {'error' : \"Unknown verb {}\".format(verb)})\n except Exception as e:\n return self.http_response_from_struct(\n { 'error' : \"Failure when running verb {}\".format(verb),\n 'message' : e})\n\n def which_file(self, record):\n \"\"\"\n return nigthly routine file in json format\n \"\"\"\n option = record['file']\n if option == 'nigthly':\n return self.get_nigthly()\n elif option == 'detail':\n return self.get_detail()\n elif int(option['info']) in list(range(1,38)):\n node = option['info']\n return self.get_info(node)\n else:\n return self.http_response_from_struct(\n { 'error' : \"File not found or not alowed\" })\n\n def get_detail(self):\n \"\"\"\n return nodes details in json format\n \"\"\"\n directory = os.path.dirname(os.path.abspath(__file__))\n directory = directory+'/nodes/'\n the_file = 'table_nodes.json'\n try:\n with open(directory + the_file) as data_file:\n data = json.load(data_file)\n data = self.build_detail(data)\n return self.http_response_from_struct(data)\n except Exception as e:\n data = {}\n print(\"Failure in read node detail file - {} - {} - {}\".format(directory, the_file, e))\n return self.http_response_from_struct(data)\n\n def get_nigthly(self):\n \"\"\"\n return nodes infos in json format\n \"\"\"\n directory = os.path.dirname(os.path.abspath(__file__))\n directory = directory+'/nightly/'\n data = []\n the_file = 'nightly_data.json'\n try:\n with open(directory + the_file) as f:\n for line in f:\n temp_line = self.remove_issue_after_maintenance(line)\n data.append(json.loads(temp_line))\n f.close()\n return self.http_response_from_struct(data)\n except Exception as e:\n return self.http_response_from_struct(\n { 'error' : \"Failure running get file\",\n 'message' : e})\n\n def get_info(self, node):\n \"\"\"\n return nodes infos in json format\n \"\"\"\n try:\n content = self.build_node_info(node)\n return self.http_response_from_struct(content)\n except Exception as e:\n return self.http_response_from_struct(\n { 'error' : \"Failure running get file\",\n 'message' : e})\n\n def build_detail(self, data):\n \"\"\"\n parse image to and md to html\n \"\"\"\n directory = os.path.dirname(os.path.abspath(__file__))\n directory = directory+'/nodes/'\n images = ['.jpg', '.jpeg', '.png']\n content = ['.md']\n new_data = data\n\n for dt in data:\n for d in data[dt]:\n file = d['value']\n ftype = os.path.splitext(file)[1]\n\n if ftype.lower() in content:\n try:\n with open(directory + file) as f:\n lines = f.readlines()\n lines = ('').join([markdown2.markdown(x.rstrip()) for x in lines])\n d['value'] = lines\n f.close()\n d['value'] = '
{}
'.format(d['value'])\n except Exception as e:\n pass\n elif ftype.lower() in images:\n # img_tag = '\"\"'.format(file, file)\n img_tag = ''.format(file, file)\n d['value'] = img_tag\n return new_data\n\n def build_node_info(self, node):\n \"\"\"\n find the node info throught the files already saved\n \"\"\"\n directory = os.path.dirname(os.path.abspath(__file__))\n directory = directory+'/nodes/'\n data = False\n setup_file= 'info_nodes.json'\n try:\n with open(directory + setup_file) as f:\n data = json.load(f)\n f.close()\n except Exception as e:\n print(\"Failure in read node config file - {} - {} - {}\".format(directory, setup_file, e))\n\n if data:\n for dt in data:\n if dt == node:\n #find the files and serve them\n tabs = data[dt]\n for tb, tab in enumerate(tabs):\n file = tab[\"file\"]\n if not type(file) is list:\n try:\n with open(directory + file) as f:\n lines = f.readlines()\n lines = ('').join([markdown2.markdown(x.rstrip()) for x in lines])\n data[dt][tb][\"content\"] = lines\n f.close()\n except Exception as e:\n pass\n return json.dumps(data)\n\n def remove_issue_after_maintenance(self, line):\n \"\"\"\n remove elements after maintenance to send to the page the data after maintenance\n 'node' : 'maintenance date'\n \"\"\"\n directory = os.path.dirname(os.path.abspath(__file__))\n directory = directory+'/nodes/'\n the_file = 'maintenance_nodes.json'\n data = []\n\n try:\n with open(directory + the_file) as data_file:\n maintenance_nodes = json.load(data_file)\n #LOAD JSON WHEN IS EACH LINE A JSON DB\n # data = []\n # with open(directory + the_file) as fi:\n # for linex in fi:\n # data.append(json.loads(linex))\n # fi.close()\n except Exception as e:\n maintenance_nodes = {}\n print(\"Failure in read maintenance file - {} - {} - {}\".format(directory, the_file, e))\n\n element = json.loads(line)\n for el in maintenance_nodes:\n for item in maintenance_nodes[el]:\n try:\n avoid_date = datetime.strptime(item['date'], \"%Y-%m-%d\")#maintenance nodes date\n based_date = datetime.strptime(element['date'], \"%Y-%m-%d\")#database\n if(based_date <= avoid_date and item['reset'] == 'yes'):\n element['data'].pop(el)\n\n except Exception as e:\n pass\n\n return json.dumps(element)\n","sub_path":"r2lab.inria.fr/files/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"400999718","text":"# ------------------------------------------------------------------------------------------------------- #\n# Rodney Edwards\n# --------------------------------------------------------------------------------------------------------- #\n# ---------------------------------- Final Project Overview ----------------------------------------------- #\n# For your final project you will create a game inspired by the 80’s arcade. You’ll put together all the programming \n# techniques we’ve learned: branching, looping, data structures and functions along with a couple of new concepts: \n# events and graphics. This project will extend the simulation concept from the midterm to include real-time interaction \n# with a user and an ending condition based on user input.\n# --------------------------------------------------------------------------------------------------------- #\n# -------------------------------------- Snake Game ------------------------------------------------------- #\n# The purpose of the game is to collect the highest score by eating food, \n# while avoiding poison objects as well as colliding with yourself and the gameboard.\n# --------------------------------------------------------------------------------------------------------- #\n\n# -------------------------------------- Pre-Flight ------------------------------------------------------- #\n# Initializing Pygame, Imports, Defining Global Constants, Functions\n\n# 1. Imports\nimport pygame, sys\nimport random\nimport time\nclock = pygame.time.Clock()\n\n# 2. Initialize Pygame\npygame.init()\npygame.font.init()\n\n# 3. Declare constants\n## I wanted to make utility variables, to abstract any hard code values at the function call level.\n\n# Utilities ------------------------------------------------------- #\nCUBE = 20 # Generic block, to pass in as snake, food, poison \n\n# Set the GAME_DISPLAY window sizes\nSCREEN_SIZE_BEGINNER = 600\n#Descoped feature\n## I wanted to have an advanced mode that would load the initial snake speed faster with the GAME_DISPLAY being smaller. \n### if I had more time...\n# SCREEN_SIZE_ADVANCED = 400\n\n# 4. Game Window Title\npygame.display.set_caption('Snakeyy - a python game.')\n\n# 5. Write boilerplate Pygame Syntax to Draw basic window\n# Pass through screen size variables into the Tuple with an extra set of ()\nGAME_DISPLAY = pygame.display.set_mode((SCREEN_SIZE_BEGINNER, SCREEN_SIZE_BEGINNER))\n\n# Bounding Frame Size\nBUTTON_PLATE = (100, 50)\n\n# Colors ---------------------------------------------------------- #\nWHITE = (255, 255, 255)\nBLACK = (0, 0, 0)\nRED = (255, 0, 0)\nGREEN = (0, 255, 0)\nBLUE = (0, 0, 255)\n\nNEON_PURPLE = (193,131,255)\nNEON_BLUE = (73,222,255)\nNEON_GREEN =(67,255,175)\n\n# Fonts ---------------------------------------------------------- #\nFONT_SIZE_SM = 20\nFONT_SIZE_MD = 30\nFONT_SIZE_LG = 60\nFONT_SIZE_XL = 80\n\nsmall_font = pygame.font.SysFont(None, FONT_SIZE_SM)\nmedium_font = pygame.font.SysFont(None, FONT_SIZE_MD)\nlarge_font = pygame.font.SysFont(None, FONT_SIZE_LG) \nxlarge_font = pygame.font.SysFont(None, FONT_SIZE_XL) \n\ntext_x = 20\ntexy_y = 30\n\n# Image Loads ------------------------------------------------------- #\nsnake_header_img = pygame.image.load('imgs/snake_xl.png')\nfood_img = pygame.image.load('imgs/donut.png')\n\n# ---------------------------------- Pre-Flight: Functions -------------------------------------------------- #\n\n# Defining message function(s) to draw text to screen ------------------------------------------------------- #\ndef text_object(text, color, size):\n # 1. First Render Font\n ## The first parmeter is text, which stands for what text string you will pass through\n ### The second patameter is set to True, which means Anti-Aliasing\n ### The third parameter is color which equals the text color\n #### The fourth parameter is for the font size\n if size == \"small\":\n text_surface = small_font.render(text, True, color)\n elif size == \"medium\":\n text_surface = medium_font.render(text, True, color)\n elif size == \"large\":\n text_surface = large_font.render(text, True, color)\n elif size == \"xlarge\":\n text_surface = xlarge_font.render(text, True, color)\n\n # returns the text_surface and gets the empty text rectangle\n return text_surface, text_surface.get_rect()\n\ndef message_on_screen(msg, color, x_displace=0, y_displace=0, size = \"medium\" ):\n # 2. Putting the text onto GAME_DISPLAY, i.e., \"to blit\"\n # Display the text_object\n # Text Object is a rectangle, with an invisible plate, and then you can center plate around text\n ## Text Surface is like a pygame.surface object - where we put the text\n ## Tuple Text rect is the rectangle around text data\n\n text_surface, text_rect = text_object (msg, color, size)\n\n # What is the center of this text rectangle object? \n ## - it's width and height of the main display divided by two.\n ### I added the ability to displace the x or y coordinate to make this message function more flexible,\n #### as I knew I would need to draw text in a few locations\n text_rect.center = (int(SCREEN_SIZE_BEGINNER/2) + x_displace, int(SCREEN_SIZE_BEGINNER/2) + y_displace)\n\n # We blit to text surface, which blits the text rectangle\n GAME_DISPLAY.blit(text_surface, text_rect)\n\n\n# Flight: Main Game Window Function(s) ---------------------------------------------------------------------- #\n\ndef start_screen():\n # Scene 1 - Game Starting Menu Screen\n\n # - Player is greeted with a welcome, Title\n # - Under Title, there is a sub-title that says, \"Click Start to Begin!\"\n # - Player can choose between difficulty level\n # - Easy Mode = Slower starting speed for snake body and large screen display\n # - Feature Omitted\n # ## Hard Mode = Faster starting speed for snake body and smaller screen display\n\n # This click variable is my switcher for the mouseclick event later referenced\n click = False\n \n # Function Game Loop\n ## to solve for needing screens in my game, i.e., the ability to present a user with a \n ## starting screen and a game_over screen, I solved by running an independent game loop\n ## per function\n running = True\n while running:\n\n # 1. Draw the game window\n # Draw to surface (with fill color) or background color\n GAME_DISPLAY.fill(BLACK)\n\n # 2. Draw a Title, in the center of the window\n # 3. Draw a Sub-Title under Title. \n message_on_screen(\"Neon Dragon\", NEON_GREEN, x_displace = 0, y_displace= -50, size= \"xlarge\")\n message_on_screen(\"Click Start to Begin!\", WHITE, x_displace = 0, y_displace= 0, size=\"medium\")\n\n \n GAME_DISPLAY.blit(snake_header_img, (200, 0))\n # GAME_DISPLAY.blit(snake_header_img, (600-snake_header_img.get_width()/2, 600-snake_header_img.get_height()/2))\n \n\n # 4. Easy and Hard Buttons\n # 4a. - This Button needs to run the game in easy mode\n ## - This Button needs to run the game in easy mode\n easy = pygame.Rect((250, 400), BUTTON_PLATE)\n pygame.draw.rect(GAME_DISPLAY, NEON_PURPLE, easy)\n\n # # 4b. Draw a button that has text inside that reads, \"Hard.\"\n # ## - This Button needs to run the game in hard mode\n # hard = pygame.Rect((400, 250), BUTTON_PLATE)\n # pygame.draw.rect(GAME_DISPLAY, NEON_PURPLE, hard)\n\n\n # 5. There needs to be a click state for the buttons\n mx, my = pygame.mouse.get_pos()\n\n if easy.collidepoint((mx, my)):\n if click:\n game()\n # if hard.collidepoint((mx, my)):\n # if click:\n # game_over()\n \n\n # 6. Event List\n #resets every frame before handling the input\n click = False \n\n event_list = pygame.event.get()\n\n for event in event_list:\n if event.type == pygame.QUIT:\n running = False\n sys.exit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n running = False\n sys.exit()\n if event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 1:\n click = True \n\n # updates the entire the surface\n ## pygame.display.flip()\n ### updates the area around what's suppose to update\n pygame.display.update()\n\n\nscale = 5\n\ndef update(snake, speed_x, speed_y):\n head = snake[-1].copy()\n snake.pop(0)\n head.x += speed_x * scale\n head.y += speed_y * scale\n snake.append(head)\n \ndef grow(snake, speed_x, speed_y):\n head = snake[-1].copy()\n head.x += speed_x * scale\n head.y += speed_y * scale\n snake.append(head)\n\ndef random_location(screen_size):\n x = random.randrange(10, screen_size-CUBE, CUBE)\n y = random.randrange(10, screen_size-CUBE, CUBE)\n print(x,y)\n return(x, y)\n\n# returns if snake collides with something that should end the game\ndef end_game_collision(snake, screen_size):\n head = snake[-1]\n x, y = head.x, head.y\n # collides with wall\n if x > screen_size - 10 or x < 0 or y > screen_size - 10 or y < 0:\n return True\n # collides with self not including head\n for i in range(len(snake) - 1):\n part = snake[i]\n if part.x == x and part.y == y:\n return True\n\n# loads a random location for x, y equal to the screen_size\ndef random_location(screen_size):\n x = random.randrange(10, screen_size-CUBE, CUBE)\n y = random.randrange(10, screen_size-CUBE, CUBE)\n print(x,y)\n return(x, y)\n\ndef score(score):\n # Top Score ------------------------------------------------------- #\n # Scene 2 - Main Game Window\n # A. There is a score at the top of the screen\n # -- Draw text to the top right of the game window\n message_on_screen(\"Score:\" +str(score), WHITE, x_displace = -200, y_displace = -280, size=\"small\")\n # text = small_font.render(\"Score\" +str(score), True, WHITE)\n # GAME_DISPLAY.blit(text, (0, 0))\n\n # Game Environment ------------------------------------------------- #\ndef game():\n\n # Function Variables ---------------------------------------------- #\n FPS = 60 # Frames Per Second\n screen_size = SCREEN_SIZE_BEGINNER\n\n # Snake ---------------------------------------------------------- #\n # There needs to be an object which will represent our snake\n # 1. Define variable named snake, and generate poisition on screen \n\n # I CAN'T FIGURE OUT HOW TO GET THE SNAKE TO BE ON THE SAME X OR Y DURING COLLISON\n # head_of_snake_top = random.randrange(10, screen_size-CUBE, CUBE)\n # head_of_snake_left = random.randrange(10, screen_size-CUBE, CUBE)\n\n head_of_snake_top = 20\n head_of_snake_left = 30\n\n snake = [pygame.Rect((head_of_snake_top, head_of_snake_left), (CUBE, CUBE))]\n\n # Intial speed of snake\n speed_x = 0 # Container for storing updated location change: x-axis\n speed_y = 0 # Container for storing updated location change: y-axis\n\n # Food ---------------------------------------------------------- #\n\n # Food is generated on the screen\n # -- 1. Define variable named food\n # -- 2. Draw the object to the screen to represent food\n # -- 3. Food object appears on game board in random x / y position\n # -- 4. When the snake object collides with food object\n # --- 4a. The food is redrawn in a different location within the game board\n # --- 4b. Snake object grows by one\n # ----4b.1. Append to back of the snake object\n # -- 5. Arbitrary Score is added to the Score at the top of the screen\n \n food = pygame.Rect(random_location(screen_size), (30, 30))\n\n # Poison ------------------------------------------------------- #\n\n # Poison is randomly generated on the screen at a time interval\n # -- 1. Define variable named poison\n # -- 2. Poison object to screen to represent poison\n # -- 3. Poison object appears on game board in random x / y position\n # -- 4. When the snake object collides with poison object\n # --- 4a. The snake object shrinks\n # ----4b. Delete from the back of the snake object\n # -- 5. Arbitrary Score is reduced to the Score at the top of the screen\n\n poison = pygame.Rect(random_location(screen_size), (CUBE, CUBE))\n\n \n # distance_traveled = 10 #distance traveled when location is updated\n\n running = True # Default Loop Running State\n while running:\n event_list = pygame.event.get()\n for event in event_list:\n if event.type == pygame.QUIT:\n game_exit = False\n sys.exit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n running = False\n sys.exit()\n elif event.key == pygame.K_LEFT:\n speed_x = -1\n speed_y = 0\n elif event.key == pygame.K_RIGHT:\n speed_x = 1\n speed_y = 0\n elif event.key == pygame.K_UP:\n speed_x = 0\n speed_y = -1\n elif event.key == pygame.K_DOWN:\n speed_x = 0\n speed_y = 1\n \n # head_of_snake_top += speed_x\n # head_of_snake_left += speed_y\n update(snake, speed_x, speed_y)\n\n # -- 3. Snake may not exit through the walls of the game display\n # --- 3/4a. The game will be over if the snake object hits the walls or itself\n # if snake[0].right > screen_size or snake[0].left < 0:\n # running = False\n # if snake[0].bottom > screen_size or snake[0].top < 0:\n # running = False\n running = not end_game_collision(snake, screen_size)\n if end_game_collision(snake, screen_size):\n game_over()\n \n\n # Draw to surface (with fill color) or background color\n GAME_DISPLAY.fill(BLACK)\n # Message_on_screen\n # message_on_screen(\"Top Score:\", BLACK, x_displace=-200, y_displace=-400)\n\n # # Snake needs to be drawn to screen\n # snake(head_of_snake_top, head_of_snake_left)\n for body in snake:\n pygame.draw.rect(GAME_DISPLAY, NEON_GREEN, body)\n\n # Generate food on window\n # # Food needs a location on window\n # pygame.draw.rect(GAME_DISPLAY, GREEN, food)\n GAME_DISPLAY.blit(food_img, food)\n\n # Generate poison on window\n # # at random\n pygame.draw.rect(GAME_DISPLAY, NEON_BLUE, poison)\n\n # When snake collides \n if snake[-1].colliderect(food):\n # snake.append(snake[-1].copy())\n grow(snake, speed_x, speed_y)\n food.x, food.y = random_location(screen_size)\n if snake[-1].colliderect(poison):\n game_over()\n \n #Call Score\n\n pygame.display.update()\n clock.tick(FPS)\n pygame.quit()\n\ndef game_over():\n\n click = False\n # Scene 3 - Game Over Screen\n \n # - Player dies\n # - Game over screen pops up\n # - Under Title, there is a sub-title that says, \"Start Over\"\n # - Player can select button to start over\n\n running = True\n while running:\n\n # 1. Draw the game window\n # Draw to surface (with fill color) or background color\n GAME_DISPLAY.fill(BLACK)\n\n # 2. Draw a Title, in the center of the window\n message_on_screen(\"Game Over!\", NEON_GREEN, x_displace=0, y_displace=-50, size=\"large\")\n # 3. Draw a Sub-Title = to score() under Title. \n\n \n # 4. Start Over\n # 4a. - This Button needs to return player to the start screen\n start_again = pygame.Rect((250, 400), BUTTON_PLATE)\n pygame.draw.rect(GAME_DISPLAY, NEON_PURPLE, start_again)\n \n \n # 5. There needs to be a click state for the buttons\n mx, my = pygame.mouse.get_pos()\n\n if start_again.collidepoint((mx, my)):\n if click:\n start_screen()\n \n # 6. Event List\n #resets every frame before handling the input\n click = False \n\n event_list = pygame.event.get()\n\n for event in event_list:\n if event.type == pygame.QUIT:\n running = False\n sys.exit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n running = False\n sys.exit()\n if event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 1:\n click = True \n\n # updates the entire the surface\n ## pygame.display.flip()\n ### updates the area around what's suppose to update\n pygame.display.update()\n\nstart_screen()\ngame()\n\n\n# event handling\n# logic\n# graphics rendering\n # if head_of_snake_top == food.x and head_of_snake_left == food.y:\n # food = pygame.Rect(random_location(screen_size), (CUBE, CUBE))\n","sub_path":"v3.py","file_name":"v3.py","file_ext":"py","file_size_in_byte":16951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"475190940","text":"import pytest\nimport mbuild as mb\nfrom mbuild.tests.base_test import BaseTest\n\n\nclass TestPattern(BaseTest):\n\n def test_apply_to_compound(self, betacristobalite, alkyl, ch3):\n pattern = mb.Random2DPattern(90)\n chains, backfills = pattern.apply_to_compound(\n guest=alkyl, host=betacristobalite, backfill=ch3)\n assert len(chains) == 90\n assert len(backfills) == 10\n\n with pytest.raises(AssertionError):\n pattern = mb.Random2DPattern(101)\n chains, backfills = pattern.apply_to_compound(\n guest=alkyl, host=betacristobalite, backfill=ch3)\n","sub_path":"mbuild/tests/test_pattern.py","file_name":"test_pattern.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"357518520","text":"from data import drivers, trips, locations, names, num_trips\nfrom matplotlib import pyplot as plt\n\nexplode = [0 for _ in drivers]\nfor i in range(len(drivers)):\n if 'William Ford' in drivers[i]['name']:\n explode[i] = 0.2\n\nfig1, ax1 = plt.subplots()\n\n\nax1.pie(num_trips, explode=explode, labels=names, autopct='%1.1f%%', shadow='True')\n\nax1.axis('equal')\n\nplt.show()\n","sub_path":"pie_chart.py","file_name":"pie_chart.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"49133474","text":"import sys\r\nfrom PyQt5 import QtGui\r\nfrom PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton, \r\n QToolTip, QMessageBox, QLabel)\r\nfrom PyQt5.QtWidgets import QPushButton, QLineEdit, QApplication, QFormLayout, QWidget, QTextEdit, QSpinBox, QListWidget\r\nfrom PyQt5.QtWidgets import QApplication, QWidget, QComboBox, QPushButton\r\n\r\nclass FormWindow(QWidget):\r\n\r\n def __init__(self):\r\n super().__init__()\r\n \r\n self.setWindowTitle(\"Patient Form\")\r\n \r\n lstCompany = ['a', 'b', 'c', 'd', 'e']\r\n\r\n \r\n self.name = QLineEdit()\r\n self.Surename = QLineEdit()\r\n self.Birthday = QLineEdit()\r\n self.customer = QLineEdit()\r\n self.Address = QLineEdit()\r\n self.Patology = QComboBox(self)\r\n self.Patology.addItems(lstCompany)\r\n self.comments = QTextEdit()\r\n\r\n self.generate_btn = QPushButton(\"Save\")\r\n\r\n layout = QFormLayout()\r\n layout.addRow(\"Name\", self.name)\r\n layout.addRow(\"Surename\", self.Surename)\r\n layout.addRow(\"Birthday\", self.Birthday)\r\n layout.addRow(\"Address\", self.Address)\r\n layout.addRow(\"Patology\", self.Patology)\r\n # Añadir las imagenes de los dientes.\r\n\r\n layout.addRow(\"Comments\", self.comments)\r\n layout.addRow(self.generate_btn)\r\n\r\n self.setLayout(layout)\r\n\r\n\r\n \r\n def getComboValue(self):\r\n print((self.comboBox.currentText(), self.comboBox.currentIndex()))\r\n\r\n\r\n\r\n\r\nclass Window(QMainWindow):\r\n def __init__(self):\r\n super().__init__()\r\n\r\n self.title = \"Menu\"\r\n self.top = 100\r\n self.left = 100\r\n self.width = 680\r\n self.height = 500\r\n\r\n self.pushButton = QPushButton(\"Medical Form\", self)\r\n self.pushButton.move(275, 200)\r\n\r\n self.pushButton.clicked.connect(self.medicalForm) # <===\r\n self.main_window()\r\n\r\n\r\n\r\n def main_window(self):\r\n self.label = QLabel(\"Medical Forms Administrator\", self)\r\n self.label.move(285, 175)\r\n self.setWindowTitle(self.title)\r\n self.setGeometry(self.top, self.left, self.width, self.height)\r\n self.show()\r\n\r\n\r\n def medicalForm(self): # <===\r\n self.w = FormWindow()\r\n self.w.show()\r\n self.hide()\r\n\r\nif __name__ == \"__main__\":\r\n app = QApplication(sys.argv)\r\n window = Window()\r\n sys.exit(app.exec())","sub_path":"untitled1.py","file_name":"untitled1.py","file_ext":"py","file_size_in_byte":2471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"519666152","text":"import os\nfrom data import *\nfrom collections import defaultdict, Counter # yuvalk I added counter\n\ndef most_frequent_train(train_data):\n \"\"\"\n Gets training data that includes tagged sentences.\n Returns a dictionary that maps every word in the training set to its most frequent tag.\n The dictionary should have a default value.\n \"\"\"\n ### YOUR CODE HERE\n word2tags2count = defaultdict(lambda: Counter())\n for sent in train_data:\n for word, tag in sent:\n word2tags2count[word][tag] += 1\n\n word2max_tag = {}\n for word, counter in word2tags2count.items():\n tag, _ = counter.most_common(1)[0]\n word2max_tag[word] = tag\n\n return word2max_tag\n ### YOUR CODE HERE\n\ndef most_frequent_eval(test_set, pred_tags):\n \"\"\"\n Gets test data and tag prediction map.\n Returns an evaluation of the accuracy of the most frequent tagger.\n \"\"\"\n gold_tag_seqs = []\n pred_tag_seqs = []\n for sent in test_set:\n words, true_tags = zip(*sent)\n gold_tag_seqs.append(true_tags)\n\n ### YOUR CODE HERE\n pred_tag_seqs.append([pred_tags[word] for word, _ in sent])\n ### YOUR CODE HERE\n\n return evaluate_ner(gold_tag_seqs, pred_tag_seqs) # yuvalk F1 is 0.80\n\n\nif __name__ == \"__main__\":\n train_sents = read_conll_ner_file(\"data/train.conll\")\n dev_sents = read_conll_ner_file(\"data/dev.conll\")\n vocab = compute_vocab_count(train_sents)\n train_sents = preprocess_sent(vocab, train_sents)\n dev_sents = preprocess_sent(vocab, dev_sents)\n\n model = most_frequent_train(train_sents)\n most_frequent_eval(dev_sents, model)\n\n","sub_path":"q1-4/most_frequent.py","file_name":"most_frequent.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"334099627","text":"\"\"\"\nhttps://www.geeksforgeeks.org/adding-two-polynomials-using-linked-list/\nAdding two polynomials using Linked List\nGiven two polynomial numbers represented by a linked list. Write a function that add these lists means add the\ncoefficients who have same variable powers.\n\nExample:\nInput:\n 1st number = 5x^2 + 4x^1 + 2x^0\n 2nd number = 5x^1 + 5x^0\nOutput:\n 5x^2 + 9x^1 + 7x^0\nInput:\n 1st number = 5x^3 + 4x^2 + 2x^0\n 2nd number = 5x^1 + 5x^0\nOutput:\n 5x^3 + 4x^2 + 5x^1 + 7x^0\n\"\"\"\nfrom linked_list.ll_class import LinkedList, Node\n\n\nclass PolynomialNode(Node):\n def __init__(self, coefficient, power):\n self.coefficient = coefficient\n self.power = power\n self.next = None\n\n def print_node(self):\n print(\"|{coefficient}|{power}|->\".format(coefficient=self.coefficient, power=self.power), end='',\n flush=True)\n\n\ndef add_polynomials(ll_1, ll_2):\n temp1 = ll_1.head\n temp2 = ll_2.head\n ll_3 = LinkedList(PolynomialNode)\n\n while temp1 and temp2:\n if temp1.power == temp2.power:\n temp1.coefficient += temp2.coefficient\n ll_3.add_node2(temp1)\n temp1 = temp1.next\n temp2 = temp2.next\n\n elif temp1.power > temp2.power:\n ll_3.add_node2(temp1)\n temp1 = temp1.next\n\n elif temp1.power < temp2.power:\n ll_3.add_node2(temp2)\n temp2 = temp2.next\n\n return ll_3\n\n\ndef main():\n ll_1 = LinkedList(PolynomialNode)\n ll_1.add_node(5, 2)\n ll_1.add_node(4, 1)\n ll_1.add_node(2, 0)\n ll_1.print_linkedlist()\n\n ll_2 = LinkedList(PolynomialNode)\n ll_2.add_node(10, 3)\n ll_2.add_node(5, 1)\n ll_2.add_node(5, 0)\n\n ll_3 = add_polynomials(ll_2, ll_1)\n ll_3.print_linkedlist()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"linked_list/add_polynomials_linked_list.py","file_name":"add_polynomials_linked_list.py","file_ext":"py","file_size_in_byte":1817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"6255611","text":"from serve_model import ServeModelType, ServeModel\nfrom utiils import get_random_hash_key\n\nclass ModelBuilder(object):\n \n @staticmethod\n def create_model(serve_model_type=None):\n if not serve_model_type:\n raise ValueError('[%s] %s' %(__name__,\n 'Must give a model type before call create_model method'))\n\n new_hash_key = get_random_hash_key()\n return ServeModel.create(new_hash_key, serve_model_type)\n ","sub_path":"ai_serving/model_builder.py","file_name":"model_builder.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"411591338","text":"################################################################################\n## 6.0002 Fall 2018\n## Problem Set 1\n## Written By: habadio, mkebede\n## Name: Julia Balla\n## Collaborators: \n## Time: 11:00\n\n\n# Problem 1\nclass State():\n \"\"\"\n A class representing the election results for a given state. \n Assumes there are no ties between dem and gop votes. The party with a \n majority of votes receives all the Electoral College (EC) votes for \n the given state.\n \"\"\"\n def __init__(self, name, dem, gop, ec):\n \"\"\"\n Parameters:\n name - the 2 letter abbreviation of a state\n dem - number of Democrat votes cast\n gop - number of Republican votes cast\n ec - number of EC votes a state has \n\n Attributes:\n self.name - str, the 2 letter abbreviation of a state\n self.winner - str, the winner of the state, \"dem\" or \"gop\"\n self.margin - int, difference in votes cast between the two parties, a positive number\n self.ec - int, number of EC votes a state has\n \"\"\"\n self.name = name\n self.winner = \"dem\" if dem > gop else \"gop\"\n self.margin = abs(dem - gop)\n self.ec = ec\n\n def get_name(self):\n \"\"\"\n Returns:\n str, the 2 letter abbreviation of the state \n \"\"\"\n return self.name\n\n def get_ecvotes(self):\n \"\"\"\n Returns:\n int, the number of EC votes the state has \n \"\"\"\n return self.ec\n\n def get_margin(self):\n \"\"\"\n Returns: \n int, difference in votes cast between the two parties, a positive number\n \"\"\"\n return self.margin\n\n def get_winner(self):\n \"\"\"\n Returns:\n str, the winner of the state, \"dem\" or \"gop\"\n \"\"\"\n return self.winner\n\n def __str__(self):\n \"\"\"\n Returns:\n str, representation of this state in the following format,\n \"In , EC votes were won by by a vote margin.\"\n \"\"\"\n return \"In \" + self.name + \", \" + str(self.ec) + \" EC votes were won by \" + self.winner + \\\n \" by a \" + str(self.margin) + \" vote margin.\"\n \n def __eq__(self, other):\n \"\"\"\n Determines if two State instances are the same.\n They are the same if they have the same state name, winner, margin and ec votes\n Note: Allows you to check if State_1 == State_2\n\n Param:\n other - State object to compare against \n\n Returns:\n bool, True if the two states are the same, False otherwise\n \"\"\"\n return self.name == other.name and self.winner == other.winner and self.margin == other.margin \\\n and self.ec == other.ec\n \n\n# Problem 2\ndef load_election_results(filename):\n \"\"\"\n Reads the contents of a file, with data given in the following tab-delimited format,\n State Democrat_votes Republican_votes EC_votes \n\n Parameters:\n filename - the name of the data file as a string\n\n Returns:\n a list of State instances\n \"\"\"\n f = open(filename)\n state_list = []\n for line in f:\n state_params = line.split() #turns each line into a list of 4 elements\n if state_params[0] != \"State\": #don't include first line of file\n state_list.append(State(state_params[0], int(state_params[1]), int(state_params[2]), int(state_params[3])))\n return state_list\n\n# Problem 3\ndef find_winner(election):\n \"\"\"\n Finds the winner of the election based on who has the most amount of EC votes.\n Note: In this simplified representation, all of EC votes from a state go\n to the party with the majority vote.\n\n Parameters:\n election - a list of State instances \n\n Returns:\n a tuple, (winner, loser) of the election i.e. ('dem', 'gop') if Democrats won, else ('gop', 'dem')\n \"\"\"\n dem_ec = 0 #Democrat EC vote counter\n gop_ec = 0 #Republican EC vote counter\n for state in election:\n if state.get_winner() == \"dem\":\n dem_ec += state.get_ecvotes()\n else:\n gop_ec += state.get_ecvotes()\n return ((\"dem\", \"gop\") if dem_ec > gop_ec else (\"gop\", \"dem\"))\n \n \n\ndef states_lost(election):\n \"\"\"\n Finds the list of States that were lost by the losing candidate (states won by the winning candidate).\n \n Parameters:\n election - a list of State instances \n\n Returns:\n A list of State instances lost by the loser (won by the winner)\n \"\"\"\n lost_states = []\n for state in election:\n if state.get_winner() == find_winner(election)[0]: #if state is won by the overall winner\n lost_states.append(state)\n return lost_states\n \n\ndef ec_votes_reqd(election, total=538):\n \"\"\"\n Finds the number of additional EC votes required by the loser to change election outcome.\n Note: A party wins when they earn half the total number of EC votes plus 1.\n\n Parameters:\n election - a list of State instances \n total - total possible number of EC votes\n\n Returns:\n int, number of additional EC votes required by the loser to change the election outcome\n \"\"\"\n #find current number of ec votes of loser\n loser_ec = 0 #loser EC vote counter\n for state in election:\n if state.get_winner() == find_winner(election)[1]:\n loser_ec += state.get_ecvotes()\n \n #return difference between amount needed to win and current number of ec votes of loser\n return int(total/2 + 1 - loser_ec)\n \n# Problem 4\ndef greedy_election(lost_states, ec_votes_needed):\n \"\"\"\n Finds a subset of lost_states that would change an election outcome if\n voters moved into those states. First chooses the states with the smallest \n win margin, i.e. state that was won by the smallest difference in number of voters. \n Continues to choose other states up until it meets or exceeds the ec_votes_needed. \n Should only return states that were originally lost by the loser (won by the winner) in the election.\n\n Parameters:\n lost_states - a list of State instances that were lost by the loser of the election\n ec_votes_needed - int, number of EC votes needed to change the election outcome\n \n Returns:\n A list of State instances such that the election outcome would change if additional\n voters relocated to those states (also can be referred to as our swing states)\n The empty list, if no possible swing states\n \"\"\"\n swing_states = []\n lost_states_copy = lost_states[:]\n swing_ec = 0 #counter for how many ec votes have transferred to losing party\n while len(lost_states_copy) >= 0:\n #default swing_state will be the first element in the list:\n swing_state = lost_states_copy[0] #this is so we have a default win margin to compare to\n for state in lost_states_copy:\n if state.get_margin() < swing_state.get_margin():\n swing_state = state #state with smallest win margin\n elif state.get_margin() == swing_state.get_margin():\n #if multiple states have same margin, pick the one with largest number of ec votes\n if state.get_ecvotes() > swing_state.get_ecvotes(): \n swing_state = state\n lost_states_copy.remove(swing_state)\n swing_states.append(swing_state)\n swing_ec += swing_state.get_ecvotes()\n if swing_ec >= ec_votes_needed: #while election not flipped\n return swing_states \n return []\n\n# Problem 5\ndef dp_move_max_voters(lost_states, ec_votes, memo = None):\n \"\"\"\n Finds the largest number of voters needed to relocate to get at most ec_votes\n for the election loser. Analogy to the knapsack problem:\n Given a list of states each with a weight(#ec_votes) and value(#margin),\n determine the states to include in a collection so the total weight(#ec_votes)\n is less than or equal to the given limit(ec_votes) and the total value(#voters displaced)\n is as large as possible.\n\n Parameters:\n lost_states - a list of State instances that were lost by the loser \n ec_votes - int, the maximum number of EC votes \n memo - dictionary, an OPTIONAL parameter for memoization (don't delete!).\n Note: If you decide to use the memo make sure to override the default value when it's first called.\n\n Returns:\n A list of State instances such that the maximum number of voters need to be relocated\n to these states in order to get at most ec_votes \n The empty list, if no possible states\n \"\"\"\n return list(dp_move_max_voters_tuple(lost_states, ec_votes, memo = None)[1])\n \ndef dp_move_max_voters_tuple(lost_states, ec_votes, memo = None):\n if memo == None: \n memo = {} \n if (len(lost_states), ec_votes) in memo: #check if this is has already been solved\n result = memo[(len(lost_states), ec_votes)]\n elif lost_states == [] or ec_votes <= 0: #base cases\n result = (0, ()) #no voter val, no states swung\n elif lost_states[0].get_ecvotes() > ec_votes: #Explore right branch\n result = dp_move_max_voters_tuple(lost_states[1:], ec_votes, memo)\n else:\n swing_state = lost_states[0]\n remaining_ec_votes = ec_votes - swing_state.get_ecvotes()\n #Explore left branch:\n voters_with, states_with = dp_move_max_voters_tuple(lost_states[1:], remaining_ec_votes , memo)\n #voter displacement count must also include the state you just took\n voters_with += swing_state.get_margin() \n #Explore right branch:\n voters_without, states_without = dp_move_max_voters_tuple(lost_states[1:], ec_votes, memo)\n if voters_with > voters_without:\n result = (voters_with, states_with + (swing_state,))\n else:\n result = (voters_without, states_without)\n memo[(len(lost_states), ec_votes)] = result\n return result\n\n \ndef move_min_voters(lost_states, ec_votes_needed):\n \"\"\"\n Finds a subset of lost_states that would change an election outcome if\n voters moved into those states. Should minimize the number of voters being relocated. \n Only return states that were originally lost by the loser (won by the winner)\n of the election.\n Hint: This problem is simply the complement of dp_move_max_voters\n\n Parameters:\n lost_states - a list of State instances that the loser of the election lost\n ec_votes_needed - int, number of EC votes needed to change the election outcome\n\n Returns:\n A list of State instances such that the election outcome would change if additional\n voters relocated to those states (also can be referred to as our swing states)\n The empty list, if no possible swing states\n \"\"\"\n ec_votes = 0 #loser EC vote counter\n for state in lost_states:\n ec_votes += state.get_ecvotes()\n \n #we found states that move the most voters that have least influence on outcome, while we want the opposite\n complement_states = dp_move_max_voters(lost_states, ec_votes - ec_votes_needed, memo = None)\n\n #we found the complement, now we need all states that are not those states\n swing_states = []\n for state in lost_states:\n if state not in complement_states:\n swing_states.append(state)\n return swing_states\n \n\n#Problem 6\ndef flip_election(election, swing_states):\n \"\"\"\n Finds a way to shuffle voters in order to flip an election outcome. \n Moves voters from states that were won by the losing candidate (any state not in lost_states), \n to each of the states in swing_states. To win a swing state, must move (margin + 1) new voters into that state. \n Also finds the number of EC votes gained by this rearrangement, as well as the minimum number of \n voters that need to be moved.\n\n Parameters:\n election - a list of State instances representing the election \n swing_states - a list of State instances where people need to move to flip the election outcome \n (result of move_min_voters or greedy_election)\n \n Return:\n A tuple that has 3 elements in the following order:\n - a dictionary with the following (key, value) mapping: \n - Key: a 2 element tuple, (from_state, to_state), the 2 letter abbreviation of the State \n - Value: int, number of people that are being moved \n - an int, the total number of EC votes gained by moving the voters \n - an int, the total number of voters moved \n None, if it is not possible to sway the election\n \"\"\"\n winning_states = [] #list of states won by losing candidate\n losing_states = states_lost(election)\n #winning_states is the complement of losing_states\n for state in election:\n if state not in losing_states:\n winning_states.append(state) \n \n if len(winning_states) == 0 or len(swing_states) == 0:\n return None #impossible to sway election if there are no states to move from/to \n \n #sort swing states from greatest to least ec/margin ratio\n sorted_swing_states = sorted(swing_states, key = lambda state: state.get_ecvotes()/state.get_margin(), reverse = True)\n \n #sort winning states from greatest to least margins of voters that it can afford to give while still winning\n sorted_winning_states = sorted(winning_states, key = lambda state: state.get_margin() - 1, reverse = True)\n \n ec_votes_needed = ec_votes_reqd(election, total=538)\n state_mapping = {}\n swing_ec = 0\n total_voters_moved = 0\n \n voters_avail = sorted_winning_states[0].get_margin() - 1 #amount of voters the winning state can give while still winning\n voters_needed = sorted_swing_states[0].get_margin() + 1 #amount of voters needed to swing the state\n \n while swing_ec < ec_votes_needed:\n if voters_avail >= voters_needed:\n total_voters_moved += voters_needed\n state_mapping[(sorted_winning_states[0].get_name(), sorted_swing_states[0].get_name())] = voters_needed\n voters_avail -= voters_needed\n #state has been swung:\n swing_ec += sorted_swing_states[0].get_ecvotes()\n del sorted_swing_states[0]\n if len(sorted_swing_states) > 0:\n voters_needed = sorted_swing_states[0].get_margin() + 1 #voters needed by the next swing state\n #if all swing states have been tried and there aren't enough ec votes:\n elif swing_ec < ec_votes_needed:\n return None\n else:\n total_voters_moved += voters_avail\n state_mapping[(sorted_winning_states[0].get_name(), sorted_swing_states[0].get_name())] = voters_avail\n voters_needed -= voters_avail\n #winning state has run out of voters to give:\n del sorted_winning_states[0]\n if len(sorted_winning_states) > 0:\n voters_avail = sorted_winning_states[0].get_margin() - 1 #voters available to be moved from the next winning state\n #if all winning states have been tried and there aren't enough ec votes:\n elif swing_ec < ec_votes_needed:\n return None\n return (state_mapping, swing_ec, total_voters_moved)\n \n \nif __name__ == \"__main__\":\n pass\n # Uncomment the following lines to test each of the problems\n\n # # tests Problem 1 and Problem 2 \n# election2012 = load_election_results(\"2012_results.txt\")\n#\n# # # tests Problem 3 \n# winner, loser = find_winner(election2012)\n# lost_states = states_lost(election2012)\n# names_lost_states = [state.get_name() for state in lost_states]\n# ec_votes_needed = ec_votes_reqd(election2012)\n# print(\"Winner:\", winner, \"\\nLoser:\", loser)\n# print(\"EC votes needed:\",ec_votes_needed)\n# print(\"States lost by the loser: \", names_lost_states, \"\\n\")\n#\n# # tests Problem 4\n# print(\"greedy_election\")\n# greedy_swing = greedy_election(lost_states, ec_votes_needed)\n# names_greedy_swing = [state.get_name() for state in greedy_swing]\n# voters_greedy = sum([state.get_margin()+1 for state in greedy_swing])\n# ecvotes_greedy = sum([state.get_ecvotes() for state in greedy_swing])\n# print(\"Greedy swing states results:\", names_greedy_swing)\n# print(\"Greedy voters displaced:\", voters_greedy, \"for a total of\", ecvotes_greedy, \"Electoral College votes.\", \"\\n\")\n#\n# # tests Problem 5: dp_move_max_voters\n# print(\"dp_move_max_voters\")\n# total_lost = sum(state.get_ecvotes() for state in lost_states)\n# move_max = dp_move_max_voters(lost_states, total_lost-ec_votes_needed)\n# max_states_names = [state.get_name() for state in move_max]\n# max_voters_displaced = sum([state.get_margin()+1 for state in move_max])\n# max_ec_votes = sum([state.get_ecvotes() for state in move_max])\n# print(\"States with the largest margins:\", max_states_names)\n# print(\"Max voters displaced:\", max_voters_displaced, \"for a total of\", max_ec_votes, \"Electoral College votes.\", \"\\n\")\n#\n# # tests Problem 5: move_min_voters\n# print(\"move_min_voters\")\n# swing_states = move_min_voters(lost_states, ec_votes_needed)\n# swing_state_names = [state.get_name() for state in swing_states]\n# min_voters = sum([state.get_margin()+1 for state in swing_states])\n# swing_ec_votes = sum([state.get_ecvotes() for state in swing_states])\n# print(\"Complementary knapsack swing states results:\", swing_state_names)\n# print(\"Min voters displaced:\", min_voters, \"for a total of\", swing_ec_votes, \"Electoral College votes. \\n\")","sub_path":"6.0002/PSets/2_ps1/ps1.py","file_name":"ps1.py","file_ext":"py","file_size_in_byte":17519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"82097345","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nimport time\n\n# Using your browser driver\nurl = 'https://www.google.com.co'\nurl1 = 'https://www.udemy.com/'\nurl2 = 'https://www.facebook.com'\nwith webdriver.Firefox(executable_path='Drivers/geckodriver') as driver:\n driver.maximize_window()\n driver.get(url)\n\n # Go to Udemy, and next to facebook\n driver.execute_script(\"window.open('');\")\n driver.switch_to.window(driver.window_handles[1])\n driver.get(url1)\n driver.get(url2)\n\n # Go to Google, and next to Facebook\n driver.execute_script(\"window.open('');\")\n driver.switch_to.window(driver.window_handles[2])\n driver.get(url)\n driver.get(url2)\n\n # Move to tab 1, and go to previous web: from Facebook to Udemy\n driver.switch_to.window(driver.window_handles[1])\n driver.back()\n\n # Move to tab 0, close tab 0 and tab 1 and move from Udemy to Facebook\n driver.switch_to.window(driver.window_handles[0])\n driver.close()\n driver.switch_to.window(driver.window_handles[0])\n driver.close()\n driver.switch_to.window(driver.window_handles[0])\n driver.back()\n driver.forward()\n","sub_path":"front_back.py","file_name":"front_back.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"423333720","text":"import json\n\nfrom requests_aws4auth import AWS4Auth\nimport boto3\nimport requests\n\nimport traceback\nfrom datetime import datetime\n\n''' \nInputs:\n product_name: string\n image_link: string\n description: string\n quantity: integer\n units: string\n'''\n\nrequired_attributes = ['product_name', 'image_link', 'description', 'quantity', 'units']\n\n# Get products\ndef lambda_handler(event, context):\n try:\n # Set up some credentials for AWS\n region = 'us-east-2' # For example, us-west-1\n service = 'es'\n credentials = boto3.Session().get_credentials()\n awsauth = AWS4Auth(credentials.access_key, credentials.secret_key, region, service, session_token=credentials.token)\n\n url = 'http://search-slp-es-database-7docgoiohso2wq5yypuwhvsuwq.us-east-2.es.amazonaws.com/'\n \n if 'body' not in event:\n event['body'] = {}\n \n # Get data\n if isinstance(event['body'], str):\n data = json.loads(event['body'])\n else:\n data = event['body']\n\n\n # Check all attributes are given\n for attr in required_attributes:\n if attr not in data:\n return {\n 'statusCode': 400,\n 'body': json.dumps('Bad Request. Missing field: {}'.format(attr))\n }\n\n\n # Check that quantity is an integer\n try:\n int(data['quantity'])\n except ValueError:\n return {\n 'statusCode': 400,\n 'body': json.dumps('Bad Request. Quantity must be an integer.')\n }\n\n # Create the payload\n payload = {\n \"product_name\": data['product_name'],\n \"image_link\": data['image_link'],\n \"description\": data['description'],\n \"quantity\": data['quantity'],\n \"units\": data['units'],\n \"date_created\": datetime.now().isoformat(),\n \"claimed\": False\n }\n\n print(payload)\n\n # Make the request\n r = requests.post(url + 'product/_doc', auth=awsauth, json=payload)\n print(r.text)\n\n # If the request failed\n if r.status_code != 201:\n return {\n 'statusCode': 500,\n 'body': json.dumps('Internal Server Error.')\n }\n\n return {\n 'statusCode': 201,\n 'body': json.dumps(r.text)\n }\n\n except Exception as e:\n print(e)\n return {\n 'statusCode': 500,\n 'body': json.dumps('Internal Server Error.' + json.dumps(traceback.format_exc()))\n }\n\n","sub_path":"backend/es_post/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":2732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"259186256","text":"class Veiculo:\n def __init__(self,cor,marca,modelo,cap_tanque):\n self.cor=cor\n self.marca=marca\n self.modelo=modelo\n self.cap_tanque=cap_tanque\n\n def abastecer(self,litros):\n self.cap_tanque+=litros\n \n def retorno(self):\n return self.__dict__\n\nclass Carro(Veiculo):\n def __init__(self,cor, marca, modelo, cap_tanque,ano):\n Veiculo.__init__(self,cor,marca,modelo,cap_tanque)\n self.ano=ano\n\n def abastecer(self,litros):\n if self.cap_tanque + litros >50:\n print(\"vai da nao\")\n else:\n self.cap_tanque+=litros\n \n def retorno(self):\n return self.__dict__\n\n#main\nx=Veiculo(\"a\",\"m\",\"c\",55)\nx.abastecer(133)\nw=Carro(\"a\",\"m\",\"c\",55,2000)\nw.abastecer(999)\nprint(w.retorno())\nprint(x.retorno())\n\ncarros=[]\nwhile True:\n comando=input(\"\"\" \n A - registrar carro\n B - abastecer\n C - \n \"\"\").upper()\n \n if comando==\"A\":\n comand=input(\"A- veiculo B- carro\").upper()\n if comand==\"A\":\n a=input(\"cor\")\n b=input(\"Marca\")\n c=input(\"modelo\")\n d=input(\"tanque\")\n x=Veiculo(a,b,c,d)\n carros.append(x)\n print(carros)\n\n elif comand==\"B\":\n a=input(\"cor\")\n b=input(\"Marca\")\n c=input(\"modelo\")\n d=input(\"tanque\")\n e=input(\"ano\")\n x=Carro(a,b,c,d,e)\n carros.append(x)\n print(carros)\n\n elif comando ==\"C\":\n break","sub_path":"POO/abastecer_carro/carro.py","file_name":"carro.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"525934230","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# Copyright (c) 2014, Blue Box Group, Inc.\n# Copyright (c) 2014, Craig Tracey \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\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport argparse\nimport logging\nimport os\nimport subprocess\nimport sys\nimport yaml\n\nfrom fabric.api import env, execute, hide, parallel, put, sudo\nfrom swifttool.ring_defintion import SwiftRingsDefinition\n\nLOG = logging.getLogger(__name__)\n\n\ndef _setup_logger(level=logging.INFO):\n logger = logging.getLogger()\n logger.setLevel(level)\n log_handler = logging.StreamHandler(sys.stdout)\n fmt = logging.Formatter(fmt='%(asctime)s %(threadName)s %(name)s '\n '%(levelname)s: %(message)s',\n datefmt='%F %H:%M:%S')\n log_handler.setFormatter(fmt)\n logger.addHandler(log_handler)\n\n\n@parallel\ndef _fab_copy_swift_directory(local_files, remote_dir):\n put(local_files, remote_dir, mirror_local_mode=True)\n\n\n@parallel\ndef _fab_start_swift_services():\n with hide('running', 'stdout', 'stderr'):\n sudo(\"swift-init start all\", pty=False, shell=False)\n\n\ndef bootstrap(args):\n rc = 0\n if not os.path.exists(args.config):\n raise Exception(\"Could not find confguration file '%s'\" % args.config)\n\n config = yaml.load(open(args.config, 'r'))\n ringsdef = SwiftRingsDefinition(config)\n\n build_script = ringsdef.generate_script(outdir=args.outdir,\n meta=args.meta)\n subprocess.call(build_script)\n\n tempfiles = os.path.join(ringsdef.workspace, \"*\")\n execute(_fab_copy_swift_directory, tempfiles, args.outdir,\n hosts=ringsdef.nodes)\n execute(_fab_start_swift_services, hosts=ringsdef.nodes)\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Tool to modify swift config')\n parser.add_argument('-d', '--debug', action='store_true')\n parser.add_argument('-i', dest='keyfile')\n parser.add_argument('-u', dest='user')\n\n subparsers = parser.add_subparsers()\n parser_genconfig = subparsers.add_parser('bootstrap')\n parser_genconfig.add_argument('--config', required=True)\n parser_genconfig.add_argument('--outdir', required=True)\n parser_genconfig.add_argument('--meta', default=None)\n parser_genconfig.set_defaults(func=bootstrap)\n\n args = parser.parse_args()\n\n level = logging.INFO\n if args.debug:\n level = logging.DEBUG\n _setup_logger(level)\n\n if args.keyfile:\n env.key_filename = args.keyfile\n if args.user:\n env.user = args.user\n\n try:\n args.func(args)\n except Exception as e:\n LOG.error(\"There was an error running swifttool: '%s'\", e)\n sys.exit(-1)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"swifttool/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"467908264","text":"import numpy as np\nfrom numba import jit,double, int64, int32, char\n\n@jit(char[:](int32,int32,char[:]))\ndef convert(N, base, s):\n '''\n Hash function to turn a string in a given base \n (e.g. base-2, base-3 etc.) to an integer index\n '''\n if N>1:\n s+=convert(N//base,base,s)\n s+=str(N%base)\n return s\n\n\n@jit(double(int64[:,:], int64, int64, int64, int64, int64, int64[:,:], int64[:,:], int64[:,:] ))\ndef GTE(dat, i, j, k, delay, bins, xp_y_mask, x_xp_mask, xp_mask):\n \"\"\"\n Transfer entropy for spike data\n \n Computes the generalized transfer entropy testing the amount of \n information that flows from dat[i,:] -> dat[j,:]\n \"\"\" \n n = int(delay!=0); \n indices = [j,i]\n \n Joint_Dist = np.zeros(bins**(2*k+2-n))\n\n ### go through each bit in X and look at the k bits predecing it in \n ### i and j\n for idx in range(k-n, dat.shape[1]-delay): \n index=0; pos=0\n for ix in range(2):\n for kx in reversed(range(k+1-n)):\n ### if an observation is observed convert it to the \n ### relevant base-10 array index observations are taken \n ### to be in base-(bins) so convert the base-(bin) \n ### number to base-10 to get appropriate index\n index += dat[indices[1-ix], idx-kx] *(bins**pos)\n pos+=1\n if delay!=0:\n index += dat[indices[0], idx+delay]*(bins**pos) \n \n ### add one to running count\n Joint_Dist[ index ] +=1\n\n ### normalize the joint probability distribution\n Joint_Dist /= Joint_Dist.sum()\n \n ### compute marginalized distributions by summing via matrix multiplication\n P_xp_y = xp_y_mask.dot( Joint_Dist )\n P_x_xp = x_xp_mask.dot( Joint_Dist )\n P_xp = xp_mask.dot( Joint_Dist )\n\n ### normalize \n P_xp_y /= P_xp_y.sum(); P_x_xp /= P_x_xp.sum(); P_xp /= P_xp.sum();\n \n te=0\n ### sum over all possible combinations \n for ix,(i,j,l) in enumerate(zip(Joint_Dist*P_xp, P_xp_y, P_x_xp)):\n ### skip if one of the distributions is zero. This only happens \n ### if the joint distribution is also zero.\n if i*j*l !=0: ### if i*j*l == 0 : continue\n te+=Joint_Dist[ix]*np.log(i/(j*l)) /np.log(bins)\n return te\n\n\nclass GeneralizedTransferEntropy():\n \n def __init__( self, number_of_classes = 2, MarkovOrder=1, TimeDelay=1):\n self.k = MarkovOrder\n self.delay = TimeDelay\n self.bins = number_of_classes\n\n @property\n def bit_strs(self):\n \"\"\"\n All possible combinations of observations\n \"\"\"\n n = int(self.delay!=0)\n nums = 2*self.k+2-n ### total number of bit string combinations to consider. \n ### Sizing of the storage arrays\n return [convert(i, self.bins,'').zfill(nums)[-(nums):] for i in range(self.bins**(nums))]\n \n @property\n def xp_y_mask(self):\n \"\"\"\n Mask to select combinations where the last 2*k +1-n bits are the same\n \"\"\"\n n = int(self.delay!=0)\n return np.array([[ int(string1[-(2*self.k+1-n):]==string2[-(2*self.k+1-n):]) \n for string1 in self.bit_strs ] for string2 in self.bit_strs], dtype='int64')\n \n @property\n def x_xp_mask(self):\n \"\"\"\n Mask to select combinations where the first k+1 bits are the same\n \"\"\"\n return np.array([[ int(string1[:self.k+1]==string2[:self.k+1]) \n for string1 in self.bit_strs ] for string2 in self.bit_strs], dtype='int64')\n @property\n def xp_mask(self):\n \"\"\"\n Mask to select combinations where the middle k bits are the same\n \"\"\"\n return np.array([[ int(string1[1:self.k+1]==string2[1:self.k+1]) \n for string1 in self.bit_strs ] for string2 in self.bit_strs], dtype='int64')\n \n def fit(self, X, y):\n \"\"\"\n Compute the generalized transfer entropy testing if the ith column of X causes the observations in Y. \n Returns the amount of information transfered by the ith column of X[:,i] -> Y\n \"\"\"\n n_cols = X.shape[1]\n y = y.reshape(y.shape[0],1)\n dat = np.hstack((y,X)).transpose()\n \n dat = dat.astype('int64') ### force dat to be integer valued\n \n ### compute the information transfer from the col_indx+1 column of dat to the 0th column of dat\n return np.array( [GTE(dat, col_indx+1, 0, self.k, self.delay, self.bins, self.xp_y_mask, self.x_xp_mask, self.xp_mask)\n for col_indx in xrange(n_cols)] )\n \n def fit_transform(self, X, y, threshold = 0.1):\n \"\"\"\n Reduce X to the columns which transfer the threshold amount of information to y\n \"\"\"\n te = self.fit(X,y)\n indices = np.where( te >= threshold)[0]\n return X[:,indices]\n","sub_path":"MRpy/time_series/GeneralizedTranserEntropy.py","file_name":"GeneralizedTranserEntropy.py","file_ext":"py","file_size_in_byte":4904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"338677981","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport os\nimport sys\nimport csv\nimport json\nimport hashlib\nimport optparse\nimport collections\npath = os.path.dirname(os.path.abspath(__file__))\nlibpath = os.path.join(path, '../lib/')\nsys.path.insert(0, libpath)\nimport grouping\n\n\ndef parse_dataset_split_by_fingerprints(cert_path, dataset):\n pre = {}\n data = {}\n # Load fingerprints and classes from the dataset\n with open(dataset) as csv_file:\n csv_dict = csv.DictReader(csv_file, delimiter='\\t')\n for elem in csv_dict:\n eid = '{}:{}'.format(elem['sha2'], elem['conn_uid'])\n fgpt = elem['c_tls_fingerprint_label']\n avc = elem['avclass_family']\n data.update({eid: {'fgpt': fgpt, 'avclass': avc}})\n # Load groups by server certificate\n with open(cert_path) as pf:\n for line in pf:\n pline = line.strip().split(',')\n cid = pline[0]\n label = pline[1]\n fgpt = data[cid]['fgpt']\n if label in pre:\n if fgpt in pre[label]:\n pre[label][fgpt].append(cid)\n else:\n pre[label].update({fgpt: [cid]})\n else:\n pre.update({label: {fgpt: [cid]}})\n return (pre, data)\n\n#def output_as_json(clusters, classes):\n# res = []\n# for label, cids in sorted(clusters.items()):\n# idclasses = collections.Counter(classes[i] for i in cids).most_common()\n# current = {\n# 'label': int(label),\n# 'ids': cids,\n# 'avclass': idclasses,\n# 'size': len(cids),\n# }\n# res.append(current)\n# return res\n\ndef main(options, args):\n # Parse original dataset and split CERT groups by fingerprint\n pre, data = parse_dataset_split_by_fingerprints(options.groups, args[0])\n if options.debug:\n print('Groups by CERT: {}.'.format(len(pre)))\n new_groups = 0\n for label in pre:\n print('Group {}'.format(label))\n print('TLS FINGERPRINTS: {}.'.format(pre[label].keys()))\n new_groups += len(pre[label].keys())\n print('New groups: {}.'.format(new_groups))\n\n output_file = 'tls_clustering_grouping_cfp.tsv'\n output_json = 'tls_clustering_grouping_cfp.json'\n\n new_label = 0\n labels = []\n with open(output_file, 'w') as of:\n classes = {}\n clusters = collections.defaultdict(list)\n # Split clusters by client fingerprints\n for c, fgpts in pre.items():\n for fgpt, ids in fgpts.items():\n clusters[new_label] = ids\n for id in ids:\n print('{},{},{}'.format(id, new_label, fgpt), file=of)\n labels.append(new_label)\n classes[id] = data[id]['avclass']\n new_label += 1\n\n with open(output_json, 'w') as oj:\n json_out = grouping.output_as_json(clusters, classes)\n json.dump(json_out, oj)\n\n if options.debug:\n print('Groups in the most common(20) list:')\n for label, total in collections.Counter(labels).most_common(20):\n print('\\t{}:\\t{}'.format(label, total))\n\n if options.debug:\n print('Grouping by TLS fingerprint, done.')\n\n\nif __name__ == '__main__':\n parser = optparse.OptionParser(\n usage=\"Usage: %prog [options] dataset_filename\",\n version=\"%prog 1.0\")\n parser.add_option(\n '-g', '--groups', action='store', dest='groups',\n help='Path to the file containing the groups by CERT')\n parser.add_option(\n '-D', '--debug', action='store_true', dest='debug',\n help='Print debug messages',\n default=False)\n\n options, args = parser.parse_args()\n\n if len(args) != 1 or not os.path.isfile(args[0]):\n parser.error(\"Dataset not found. Aborting...\")\n if not os.path.isfile(options.groups):\n parser.error(\"File with groups by CERT not found. Aborting...\")\n\n main(options, args)\n","sub_path":"clustering/fishdbc_notebook/fp_grouping.py","file_name":"fp_grouping.py","file_ext":"py","file_size_in_byte":3994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"46234625","text":"# Author: Brian Busemeyer bbusemeyer@gmail.com. \n# Released under GNU licence.\nimport numpy as np\nfrom functools import partial\nimport time\nimport subprocess as sub\nimport multiprocessing as mp\nimport matplotlib.pyplot as plt\nimport plot_tools as pt\npt.matplotlib_header()\nfrom copy import deepcopy\n\nclass GeneticOptimizer:\n def __init__(self,fitness,breed,nthreads=1):\n \"\"\" \n fitness(sol) is a function that defines the fitness of a solution. Space of\n solutions is implicitly defined by fitness function. \n breed(solist) takes a list of solutions and produces a new solution.\n mutate(sol,frac) takes a solution and perturbs a fraction of it. \n \"\"\"\n # FIXME Breed has issue when number of parents doesn't match what breed is expecting.\n self.fitness = fitness\n self.breed = breed\n self.best_fitness = -np.inf\n self.best_fitness_history = []\n self.best_solution = None\n self.population = None\n self.nthreads = nthreads\n\n\n def optimize(self,init_pop, mutate_frac=0.1, nparents=2, \n elitist_frac=0.0, max_gens=1000, fitness_goal=np.inf, warn=False):\n \"\"\" \n Perform genetic optimization on space defined by `self.fitness` and `init_pop`.\n `mutate` is the fraction of mutation for the gene.\n The top `breeding_frac` of population is bred. \n Number of parents is `parents`. \n Top `elitist_frac` of population is kept between generations.\n Keeps population constant, so breeding fraction is determined by number of\n parents.\n `warn` warns when fitness goals aren't met.\n \"\"\"\n # TODO mutations, test >2 number of parents. \n self.population = init_pop\n keep = int(round(elitist_frac*len(self.population)))\n for gen in range(max_gens):\n fitnesses = [self.fitness(unit) for unit in self.population]\n #best_order = [np.argmax(fitnesses)]\n best_order = np.argsort(fitnesses)\n self.best_fitness = fitnesses[best_order[-1]]\n self.best_fitness_history.append(self.best_fitness)\n self.best_solution = self.population[best_order[-1]]\n if self.best_fitness > fitness_goal: break\n\n # Breed population by sampling best fitnesses.\n norm = np.linalg.norm(fitnesses,1)\n grabp = [fitness/norm for fitness in fitnesses]\n breed_pairs = [\n [\n self.population[packidx] for packidx in \n np.random.choice(range(len(self.population)),nparents,replace=False,p=grabp)\n ]\n for p in self.population[keep:]\n ]\n self.population = [self.population[pidx] for pidx in best_order[-keep:]] +\\\n [self.breed(pair) for pair in breed_pairs]\n #self.population = [self.best_solution] +\\\n # [self.breed(pair) for pair in breed_pairs]\n \n #TODO mutate.\n if gen+1==max_gens and warn: \n print(\"Warning: did not reach fitness goal.\")\n return self.best_fitness\n\nclass BinPackingProblem:\n def __init__(self,packages,binsize=1.0):\n self.packages = packages\n self.binsize = binsize\n\n def compute_fillings(self,packings):\n fillings = [0.0 for packing in packings]\n for packidx,packing in enumerate(packings):\n for pidx in packing:\n fillings[packidx] += self.packages[pidx]\n return fillings\n\n def greedy_pack(self,pidx,packings,fillings):\n for packidx,pack in enumerate(packings):\n if fillings[packidx]+self.packages[pidx] <= self.binsize:\n fillings[packidx] += self.packages[pidx]\n packings[packidx].append(pidx)\n return packings, fillings\n packings.append([pidx])\n fillings.append([self.packages[pidx]])\n return packings, fillings\n\n def compute_greedy_solution(self,order='unsorted'):\n if order == 'sorted': \n order = np.argsort(self.packages)[::-1]\n elif order=='backwards': \n order = np.argsort(self.packages)\n elif order=='unsorted':\n order = np.arange(len(self.packages))\n np.random.shuffle(order)\n else: \n raise AssertionError(\"\"\"\n Illegal order value: %s. \n Available settings: 'sorted','backwards', or 'unsorted' (default).\n \"\"\"%order)\n\n packings = [[]]\n fillings = [0.0]\n for pidx in order:\n packings, fillings = self.greedy_pack(pidx,packings,fillings)\n return packings\n\n def evaluate(self,packings):\n packed = [package for pack in packings for package in pack]\n packed = set(packed)\n fillings = self.compute_fillings(packings)\n if len(packed)!=len(self.packages):\n print(\"evaluate finds failed: some packages not packed.\")\n return 0.0\n for filling in fillings:\n if filling>self.binsize:\n print(\"evaluate finds failed: some packs overfilled.\")\n return 0.0\n return sum(fillings) / (self.binsize*len(packings))\n\nclass BinPackingGenAlg(BinPackingProblem):\n def breed_packings(self,packings_list,frac_remove=0.5):\n fillings_list = [self.compute_fillings(packings) for packings in packings_list]\n nremoved = min([int(frac_remove*len(pl)) for pl in packings_list])\n premoved = [1.-fill for fill in fillings_list[0]]\n premoved /= sum(premoved)\n pcopy = [fill for fill in fillings_list[1]]\n pcopy /= sum(pcopy)\n removed = np.random.choice(range(len(packings_list[0])),\n nremoved,p=premoved,replace=False)\n copyover = np.random.choice(range(len(packings_list[1])),\n nremoved,p=pcopy,replace=False)\n new_packings = deepcopy(packings_list[0])\n new_fillings = deepcopy(fillings_list[0])\n for remidx,packidx in enumerate(removed):\n new_packings[packidx] = packings_list[1][copyover[remidx]]\n new_fillings[packidx] = fillings_list[1][copyover[remidx]]\n ret = self._fix_packings(new_packings,new_fillings)[0]\n return ret\n\n def mutate_packings(self,packings_list,npackage_delete):\n return packings_list\n\n def _fix_packings(self,packings,fillings):\n done = set()\n repack = []\n for packidx,packing in enumerate(packings):\n packset = set(packing)\n if len(done.intersection(packset)) > 0:\n packings.pop(packidx)\n fillings.pop(packidx)\n repack.extend(packset.difference(done))\n else:\n done = done.union(packset)\n repack.extend(set(range(len(self.packages))).difference(done))\n for pidx in repack:\n self.greedy_pack(pidx,packings,fillings)\n return packings, fillings\n\ndef greedy_hist(fig,ax,size,order='unsorted',stats=1000):\n res = []\n for i in range(stats):\n prob = BinPackingProblem(np.random.random(size))\n res.append(prob.evaluate(prob.compute_greedy_solution(order)))\n n,bins = np.histogram(res,normed=True)\n ax.bar(bins[:-1],n/n.sum(),width=bins[0]-bins[1])\n return fig,ax\n\ndef stat_greedy(order='sort',stats=300,size=100):\n ret = 0.0\n for i in range(stats):\n prob = BinPackingGenAlg(np.random.random(size))\n ret += prob.evaluate(prob.compute_greedy_solution(order))\n return ret/stats\n\ndef plot_size_trend(fig,ax,powers,stats=300,size=100):\n res = []\n for i in [10*j for j in powers]:\n res.append((\n stat_greedy(order='sorted', stats=stats,size=size),\n stat_greedy(order='unsorted', stats=stats,size=size),\n stat_greedy(order='backwards',stats=stats,size=size)\n ))\n res = np.array(res).T\n ax.semilogx(10**powers,res[0],label='sort')\n ax.semilogx(10**powers,res[1],label='unsort')\n ax.semilogx(10**powers,res[2],label='backwards')\n return fig,ax\n\ndef test_genalg(fig,ax,max_gens,popsize,npackages,max_package=1.0):\n\t# Compare to random sampling of the same number of generations.\n\tprob = BinPackingGenAlg(np.random.random(npackages)*max_package)\n\tinit_pop = [prob.compute_greedy_solution() for i in range(popsize*max_gens-2)]+\\\n\t\t\t[prob.compute_greedy_solution('sorted'),prob.compute_greedy_solution('backwards')]\n\tinit_fitnesses = [prob.evaluate(packings) for packings in init_pop]\n\tbest_rand = max(init_fitnesses)\n\tprint(\"Best random\",best_rand)\n\n\t# Now optimize it with genetic algorithm.\n\tinit_pop = [prob.compute_greedy_solution() for i in range(popsize-2)]+\\\n\t\t\t[prob.compute_greedy_solution('sorted'),prob.compute_greedy_solution('backwards')]\n\tinit_fitnesses = [prob.evaluate(packings) for packings in init_pop]\n\toptimizer = GeneticOptimizer(prob.evaluate,prob.breed_packings,nthreads=1)\n\tstart=time.clock()\n\toptimizer.optimize(init_pop,elitist_frac=0.1,max_gens=100)\n\tend=time.clock()\n\tprint(\"Best Vol. Frac.\",optimizer.best_fitness)\n\tprint(\"Time:\",end-start)\n\tprint(\"Generations\",len(optimizer.best_fitness_history))\n\tax.axhline(best_rand,color='k',label=\"Best random\")\n\tax.plot([dat for dat in optimizer.best_fitness_history],label=\"Genetic\")\n\ndef _perform_greedy(dummy,max_gens,popsize,npackages,max_package=1.0):\n prob = BinPackingGenAlg(np.random.random(npackages)*max_package)\n init_pop = [prob.compute_greedy_solution() for i in range(popsize-2)]+\\\n [prob.compute_greedy_solution('sorted'),prob.compute_greedy_solution('backwards')]\n init_fitnesses = [prob.evaluate(packings) for packings in init_pop]\n return max(init_fitnesses)\n\ndef _perform_genalg(dummy,max_gens,popsize,npackages,max_package=1.0):\n prob = BinPackingGenAlg(np.random.random(npackages)*max_package)\n init_pop = [prob.compute_greedy_solution() for i in range(popsize-2)]+\\\n [prob.compute_greedy_solution('sorted'),prob.compute_greedy_solution('backwards')]\n init_fitnesses = [prob.evaluate(packings) for packings in init_pop]\n optimizer = GeneticOptimizer(prob.evaluate,prob.breed_packings,nthreads=1)\n start=time.clock()\n optimizer.optimize(init_pop,elitist_frac=0.1,max_gens=100)\n end=time.clock()\n return optimizer.best_fitness\n\ndef genalg_hist(fig,ax,stats,max_gens,popsize,npackages,max_package=1.0):\n onerun = partial(_perform_genalg, \n max_gens=max_gens,\n popsize=popsize,\n npackages=npackages,\n max_package=max_package\n )\n with mp.Pool(8) as pool:\n res = pool.map(onerun,list(range(stats)))\n\n n,bins = np.histogram(res,normed=True)\n ax.bar(bins[:-1],n/n.sum(),width=bins[0]-bins[1])\n \ndef scan_max_package(fig,ax,stats,max_gens,popsize,npackages,max_packages):\n ref = np.zeros(len(max_packages))\n res = np.zeros(len(max_packages))\n for midx,max_package in enumerate(max_packages):\n oneref = partial(_perform_greedy, \n max_gens=max_gens,\n popsize=popsize,\n npackages=npackages,\n max_package=max_package\n )\n onerun = partial(_perform_genalg, \n max_gens=max_gens,\n popsize=popsize,\n npackages=npackages,\n max_package=max_package\n )\n with mp.Pool(8) as pool:\n ref[midx] = np.array(pool.map(oneref,list(range(stats)))).mean()\n res[midx] = np.array(pool.map(onerun,list(range(stats)))).mean()\n print(\"Done with \",max_package)\n ax.plot(max_packages,ref,'k')\n ax.plot(max_packages,res)\n \ndef scan_popsize(fig,ax,stats,max_gens,popsizes,npackages,max_package):\n ref = np.zeros(len(popsizes))\n res = np.zeros(len(popsizes))\n for midx,popsize in enumerate(popsizes):\n oneref = partial(_perform_greedy, \n max_gens=max_gens,\n popsize=popsize,\n npackages=npackages,\n max_package=max_package\n )\n onerun = partial(_perform_genalg, \n max_gens=max_gens,\n popsize=popsize,\n npackages=npackages,\n max_package=max_package\n )\n with mp.Pool(8) as pool:\n ref[midx] = np.array(pool.map(oneref,list(range(stats)))).mean()\n res[midx] = np.array(pool.map(onerun,list(range(stats)))).mean()\n print(\"Done with \",popsize)\n ax.plot(popsizes,ref,'k')\n ax.plot(popsizes,res)\n\ndef scan_npackages(fig,ax,stats,max_gens,popsize,npackagess,max_package):\n ref = np.zeros(len(npackagess))\n res = np.zeros(len(npackagess))\n for midx,npackages in enumerate(npackagess):\n oneref = partial(_perform_greedy, \n max_gens=max_gens,\n popsize=popsize,\n npackages=npackages,\n max_package=max_package\n )\n onerun = partial(_perform_genalg, \n max_gens=max_gens,\n popsize=popsize,\n npackages=npackages,\n max_package=max_package\n )\n with mp.Pool(8) as pool:\n ref[midx] = np.array(pool.map(oneref,list(range(stats)))).mean()\n res[midx] = np.array(pool.map(onerun,list(range(stats)))).mean()\n print(\"Done with \",npackages)\n ax.plot(npackagess,ref,'k')\n ax.plot(npackagess,res)\n","sub_path":"assets/notebooks/gen_alg.py","file_name":"gen_alg.py","file_ext":"py","file_size_in_byte":12215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"307793871","text":"# Copyright 2017 Intel Corporation\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\"\"\"Intersubject analyses (ISC/ISFC)\r\n\r\nFunctions for computing intersubject correlation (ISC) and intersubject\r\nfunctional correlation (ISFC), and utility functions for loading subject data\r\nfiles and masks\r\n\r\nPaper references:\r\nISC: Hasson, U., Nir, Y., Levy, I., Fuhrmann, G. & Malach, R. Intersubject\r\nsynchronization of cortical activity during natural vision. Science 303,\r\n1634–1640 (2004).\r\n\r\nISFC: Simony E, Honey CJ, Chen J, Lositsky O, Yeshurun Y, Wiesel A, Hasson U\r\n(2016) Dynamic reconfiguration of the default mode network during narrative\r\ncomprehension. Nat Commun 7.\r\n\"\"\"\r\n\r\n# Authors: Christopher Baldassano and Mor Regev\r\n# Princeton University, 2017\r\n\r\nfrom brainiak.fcma.util import compute_correlation\r\nimport numpy as np\r\nfrom scipy import stats\r\n\r\n\r\ndef isc(D, collapse_subj=True):\r\n \"\"\"Intersubject correlation\r\n\r\n For each voxel, computes the correlation of each subject's timecourse with\r\n the mean of all other subjects' timecourses. By default the result is\r\n averaged across subjects, unless collapse_subj is set to False.\r\n\r\n Parameters\r\n ----------\r\n D : voxel by time by subject ndarray\r\n fMRI data for which to compute ISC\r\n\r\n collapse_subj : bool, default:True\r\n Whether to average across subjects before returning result\r\n\r\n Returns\r\n -------\r\n ISC : voxel ndarray (or voxel by subject ndarray, if collapse_subj=False)\r\n pearson correlation for each voxel, across subjects\r\n \"\"\"\r\n\r\n n_vox = D.shape[0]\r\n n_subj = D.shape[2]\r\n ISC = np.zeros((n_vox, n_subj))\r\n\r\n # Loop across choice of leave-one-out subject\r\n for loo_subj in range(n_subj):\r\n group = np.mean(D[:, :, np.arange(n_subj) != loo_subj], axis=2)\r\n subj = D[:, :, loo_subj]\r\n for v in range(n_vox):\r\n ISC[v, loo_subj] = stats.pearsonr(group[v, :], subj[v, :])[0]\r\n\r\n if collapse_subj:\r\n ISC = np.mean(ISC, axis=1)\r\n return ISC\r\n\r\n\r\ndef isfc(D, collapse_subj=True):\r\n \"\"\"Intersubject functional correlation\r\n\r\n Computes the correlation between the timecoure of each voxel in each\r\n subject with the average of all other subjects' timecourses in *all*\r\n voxels. By default the result is averaged across subjects, unless\r\n collapse_subj is set to False.\r\n\r\n Uses the high performance compute_correlation routine from fcma.util\r\n\r\n Parameters\r\n ----------\r\n D : voxel by time by subject ndarray\r\n fMRI data for which to compute ISFC\r\n\r\n collapse_subj : bool, default:True\r\n Whether to average across subjects before returning result\r\n\r\n Returns\r\n -------\r\n ISFC : voxel by voxel ndarray\r\n (or voxel by voxel by subject ndarray, if collapse_subj=False)\r\n pearson correlation between all pairs of voxels, across subjects\r\n \"\"\"\r\n\r\n n_vox = D.shape[0]\r\n n_subj = D.shape[2]\r\n ISFC = np.zeros((n_vox, n_vox, n_subj))\r\n\r\n # Loop across choice of leave-one-out subject\r\n for loo_subj in range(D.shape[2]):\r\n group = np.mean(D[:, :, np.arange(n_subj) != loo_subj], axis=2)\r\n subj = D[:, :, loo_subj]\r\n ISFC[:, :, loo_subj] = compute_correlation(group, subj)\r\n\r\n # Symmetrize matrix\r\n ISFC[:, :, loo_subj] = (ISFC[:, :, loo_subj] +\r\n ISFC[:, :, loo_subj].T) / 2\r\n\r\n if collapse_subj:\r\n ISFC = np.mean(ISFC, axis=2)\r\n return ISFC\r\n","sub_path":"brainiak/isfc.py","file_name":"isfc.py","file_ext":"py","file_size_in_byte":4001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"315556623","text":"import numpy as np\nimport numpy.random as rand \nimport matplotlib.pyplot as plt\n\nsample_size = input ('Sample Size: ')\nx = [(rand.random() - .5) for i in range(sample_size)]\ny = [(rand.random() - .5) for i in range(sample_size)]\nPoints = zip(x, y)\n\nCircle = [i for i in Points if (np.sqrt(i[0]**2 + i[1]**2) <= .5)]\nSquare = [i for i in Points if (np.sqrt(i[0]**2 + i[1]**2) > .5)]\n\nCircle_x = [i[0] for i in Circle]\nCircle_y = [i[1] for i in Circle]\nSquare_x = [i[0] for i in Square]\nSquare_y = [i[1] for i in Square]\n\n\nplt.figure(1)\ncircle, = plt.plot(Circle_x, Circle_y, 'r.', label = 'Circle')\nsquare, = plt.plot(Square_x, Square_y, 'b.', label ='Square')\nplt.title('Darts')\nplt.show()\n","sub_path":"day2/exercises/Moiya/pi_estimate/plot_darts.py","file_name":"plot_darts.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"650414703","text":"i = 0\r\na = []\r\nwhile i < 1001:\r\n if i % 2 == 0 and i % 3 == 0:\r\n a.append(i)\r\n i = i + 1\r\n\r\nb = [i for i in range(1000) if i % 2 == 0 and i % 3 == 0]\r\nc = filter(lambda i: i % 2 == 0 and i % 3 == 0, range(1000))\r\n\r\nprint (a)\r\nprint (b)\r\nprint (c)\r\n","sub_path":"lesson3/3-1.py","file_name":"3-1.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"170136904","text":"def isPalindrome(x):\n if x < 0 or (x % 10 == 0 and x != 0):\n return False\n\n if x < 10:\n return True \n\n reversed = 0\n while x > reversed:\n reversed = reversed * 10 + x % 10\n x = int(x / 10)\n \n return x == reversed or x == int(reversed / 10) ","sub_path":"py/leetcode_easy/palindrome_number.py","file_name":"palindrome_number.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"185361318","text":"import numpy as np\n\nfrom scipy.signal import butter, sosfiltfilt, ricker, cwt, correlate, savgol_filter\nfrom scipy.optimize import curve_fit, differential_evolution\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import colorConverter\n\nEXCLUDE_COLOR = 'xkcd:salmon'\nSAMPLE_SETTINGS = {\n \"Glucose [mM]\": 8,\n \"Sampling [Hz]\": 10,\n \"Stimulation [frame]\": [0, 0],\n \"Filter\":\n {\n \"Slow [Hz]\": [0.001, 0.005],\n \"Fast [Hz]\": [0.04, 0.4],\n \"Plot [s]\": [250, 1750]\n },\n \"Distribution order\": 5,\n \"Exclude\":\n {\n \"Score threshold\": 1.5,\n \"Spikes threshold\": 0.01\n },\n \"Distance [um]\": 1\n }\n\nclass Data(object):\n \"\"\"\n A class for signal analysis.\n \"\"\"\n# ------------------------------- INITIALIZER -------------------------------- #\n def __init__(self):\n self.__signal = False\n self.__mean_islet = False\n self.__time = False\n self.__settings = False\n\n self.__points = False\n self.__cells = False\n self.__filtered_slow = False\n self.__filtered_fast = False\n self.__distributions = False\n self.__binarized_slow = False\n self.__binarized_fast = False\n self.__activity = False\n self.__good_cells = False\n\n# --------------------------------- IMPORTS ---------------------------------- #\n def import_data(self, signal):\n if not len(signal.shape)==2:\n raise ValueError(\"Signal shape not 2x2.\")\n self.__signal = np.around(signal[:,1:].transpose(), decimals=3)\n self.__mean_islet = np.mean(self.__signal, 0) # average over 0 axis\n self.__mean_islet = self.__mean_islet - np.mean(self.__mean_islet)\n if self.__settings is False:\n self.__settings = SAMPLE_SETTINGS\n sampling = self.__settings[\"Sampling [Hz]\"]\n self.__time = np.arange(len(self.__signal[0]))*(1/sampling)\n\n self.__points = len(self.__time)\n self.__cells = len(self.__signal)\n\n self.__good_cells = np.ones(self.__cells, dtype=\"bool\")\n\n def import_settings(self, settings=SAMPLE_SETTINGS):\n if not \"Sampling [Hz]\" in settings and not \"Stimulation [frame]\" in settings and not \"Filter\" in settings and not \"Exclude\" in settings and not \"Distance [um]\" in settings:\n raise ValueError(\"Bad keys in settings.\")\n if not \"Slow [Hz]\" in settings[\"Filter\"] and not \"Fast [Hz]\" in settings[\"Filter\"] and not \"Plot [s]\" in settings[\"Filter\"]:\n raise ValueError(\"Bad keys in settings[filter].\")\n if not \"Score threshold\" in settings[\"Exclude\"] and not \"Spikes threshold\" in settings[\"Exclude\"]:\n raise ValueError(\"Bad keys in settings[exclude].\")\n self.__settings = settings\n\n def import_good_cells(self, cells):\n if self.__signal is False:\n raise ValueError(\"No imported data!\")\n if len(cells) != self.__cells:\n raise ValueError(\"Cell number does not match.\")\n self.__good_cells = cells\n\n def reset_computations(self):\n self.__filtered_slow = False\n self.__filtered_fast = False\n self.__distributions = False\n self.__binarized_slow = False\n self.__binarized_fast = False\n self.__activity = False\n self.__good_cells = np.ones(self.__cells, dtype=\"bool\")\n\n\n# --------------------------------- GETTERS ---------------------------------- #\n def get_settings(self): return self.__settings\n def get_time(self): return self.__time\n def get_signal(self): return self.__signal\n def get_mean_islet(self): return self.__mean_islet\n def get_points(self): return self.__points\n def get_cells(self): return self.__cells\n def get_filtered_slow(self): return self.__filtered_slow\n def get_filtered_fast(self): return self.__filtered_fast\n def get_distributions(self): return self.__distributions\n def get_binarized_slow(self): return self.__binarized_slow\n def get_binarized_fast(self): return self.__binarized_fast\n def get_activity(self): return self.__activity\n def get_good_cells(self): return self.__good_cells\n\n# ----------------------------- ANALYSIS METHODS ----------------------------- #\n def plot(self, i):\n if self.__signal is False:\n raise ValueError(\"No imported data!\")\n if i not in range(self.__cells):\n raise ValueError(\"Cell index not in range.\")\n mean = np.mean(self.__signal[i])\n\n fig, ax = plt.subplots()\n ax.plot(self.__time, self.__signal[i]-mean, linewidth=0.5, color='dimgrey')\n ax.plot(self.__time, self.__mean_islet, linewidth=0.5, color='k')\n ax.set_xlim(self.__settings[\"Filter\"][\"Plot [s]\"])\n ax.set_xlabel(\"Time [s]\")\n ax.set_ylabel(\"Amplitude\")\n\n return fig\n# ---------- Filter + smooth ---------- #\n def filter(self):\n if self.__signal is False:\n raise ValueError(\"No imported data!\")\n slow, fast = self.__settings[\"Filter\"][\"Slow [Hz]\"], self.__settings[\"Filter\"][\"Fast [Hz]\"]\n self.__filtered_slow = np.zeros((self.__cells, self.__points))\n self.__filtered_fast = np.zeros((self.__cells, self.__points))\n\n for i in range(self.__cells):\n self.__filtered_slow[i] = self.__bandpass(self.__signal[i], (*slow))\n self.__filtered_fast[i] = self.__bandpass(self.__signal[i], (*fast))\n\n def __bandpass(self, data, lowcut, highcut, order=5):\n nyq = 0.5*self.__settings[\"Sampling [Hz]\"]\n low = lowcut / nyq\n high = highcut / nyq\n sos = butter(order, [low, high], analog=False, btype='band', output='sos')\n y = sosfiltfilt(sos, data)\n return y\n\n def plot_filtered(self, i):\n if self.__filtered_slow is False or self.__filtered_fast is False:\n raise ValueError(\"No filtered data!\")\n if i not in range(self.__cells):\n raise ValueError(\"Cell index not in range.\")\n mean = np.mean(self.__signal[i])\n\n fig, (ax1, ax2) = plt.subplots(2)\n if not self.__good_cells[i]:\n ax1.set_facecolor(EXCLUDE_COLOR)\n fig.suptitle(\"Filtered data ({0})\".format(\"keep\" if self.__good_cells[i] else \"exclude\"))\n\n ax1.plot(self.__time, self.__signal[i]-mean, linewidth=0.5, color='dimgrey', alpha=0.5)\n ax1.plot(self.__time, self.__filtered_fast[i], linewidth=0.5, color='red')\n ax1.set_xlim(self.__settings[\"Filter\"][\"Plot [s]\"])\n ax1.set_ylabel(\"Amplitude (fast)\")\n\n ax2.plot(self.__time, self.__signal[i]-mean, linewidth=0.5, color='dimgrey', alpha=0.5)\n ax2.plot(self.__time, self.__filtered_slow[i], linewidth=2, color='blue')\n ax2.set_xlabel(\"Time [s]\")\n ax2.set_ylabel(\"Amplitude (slow)\")\n\n return fig\n\n# ---------- Binarize ---------- #\n\n def compute_distributions(self):\n if self.__filtered_slow is False:\n raise ValueError(\"No filtered data.\")\n self.__distributions = [dict() for i in range(self.__cells)]\n\n for cell in range(self.__cells):\n # Compute cumulative histogram and bins\n signal = np.clip(self.__filtered_fast[cell], 0, None)\n hist = np.histogram(signal, 50)\n cumulative_hist = np.flip(np.cumsum(np.flip(hist[0])))\n bins = hist[1]\n x = (bins[1:] + bins[:-1])/2 # middle points of bins\n\n # Fit polynomial of nth order\n order = self.__settings[\"Distribution order\"]\n z = np.polyfit(x, np.log(cumulative_hist), order, w=np.sqrt(cumulative_hist))\n p = np.poly1d(z)\n\n # Transitions of polynomial\n first_derivative = np.polyder(p, 1)\n second_derivative = np.polyder(p, 2)\n roots = np.roots(second_derivative)\n real_roots = roots.real[abs(roots.imag) < 1e-5]\n final_roots = real_roots[np.logical_and(real_roots > 0, real_roots < bins[-1])]\n p_root = min(final_roots)\n min_value = first_derivative(p_root)\n\n # Quadratic function around 0\n q = np.poly1d([second_derivative(0)/2, first_derivative(0), p(0)])\n q_root = np.roots(np.polyder(q, 1))\n q_root = q_root[0] if q_root>0 or q_root>bins[-1] else np.inf\n\n # Goodness score\n phi = np.arctan(abs(min_value))/(np.pi/2)\n score = (1-phi)*p_root/q_root\n\n spikes_threshold = self.__settings[\"Exclude\"][\"Spikes threshold\"]\n if np.exp(p(p_root)) 0:\n return np.where(M == True)[0]\n else:\n return np.array([], dtype=\"int\") # No match found\n\n def binarize_fast(self):\n if self.__distributions is False or self.__filtered_fast is False:\n raise ValueError(\"No distribution or filtered data.\")\n self.__binarized_fast = np.zeros((self.__cells, self.__points))\n for cell in range(self.__cells):\n threshold = self.__distributions[cell][\"p_root\"]\n self.__binarized_fast[cell] = np.where(self.__filtered_fast[cell]>threshold, 1, 0)\n self.__binarized_fast = self.__binarized_fast.astype(int)\n\n def binarize_slow(self):\n if self.__filtered_slow is False:\n raise ValueError(\"No filtered data.\")\n self.__binarized_slow = np.zeros((self.__cells, self.__points))\n for cell in range(self.__cells):\n signal = self.__filtered_slow[cell]\n heavisided_gradient = np.heaviside(np.gradient(signal), 0)\n minima = self.__search_sequence(heavisided_gradient, [0,1])\n maxima = self.__search_sequence(heavisided_gradient, [1,0])\n extremes = np.sort(np.concatenate((minima, maxima)))\n\n reverse_mode = False if minima[0] < maxima[0] else True\n\n self.__binarized_slow[cell, 0:extremes[0]] = 0\n for i in range(len(extremes)-1):\n e1, e2 = extremes[i], extremes[i+1]\n if i%2 == int(reverse_mode):\n self.__binarized_slow[cell, e1:e2] = np.floor(np.linspace(1,7,e2-e1, endpoint=False))\n else:\n self.__binarized_slow[cell, e1:e2] = np.floor(np.linspace(7,13,e2-e1, endpoint=False))\n self.__binarized_slow[cell, extremes[-1]:] = 0\n self.__binarized_slow = self.__binarized_slow.astype(int)\n\n def autolimit(self):\n if self.__binarized_fast is False:\n raise ValueError(\"No binarized data.\")\n print(\"Computing activity...\")\n self.__activity = []\n for cell in range(self.__cells):\n data = self.__binarized_fast[cell]\n box = lambda t, a, t_start, t_end: a*(np.heaviside(t-t_start, 0)-np.heaviside(t-t_end, 0))\n t_half = self.__time[-1]/2\n res = differential_evolution(lambda p: np.sum((box(self.__time, *p) - data)**2), # quadratic cost function\n # [[0, 100], [0, t_half], [t_half, 2*t_half]]) # parameter bounds\n [[0, 100], [0, 2*t_half], [0, 2*t_half]]) # parameter bounds\n self.__activity.append(res.x[1:])\n\n if self.__activity[cell][0] < self.__settings[\"Stimulation [frame]\"][0]/self.__settings[\"Sampling [Hz]\"]:\n self.__good_cells[cell] = False\n self.__activity = np.array(self.__activity)\n\n\n def plot_binarized(self, cell):\n if self.__binarized_slow is False or self.__binarized_fast is False:\n raise ValueError(\"No binarized data!\")\n\n fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)\n if not self.__good_cells[cell]:\n ax1.set_facecolor(EXCLUDE_COLOR)\n fig.suptitle(\"Binarized data ({0})\".format(\"keep\" if self.__good_cells[cell] else \"exclude\"))\n\n mean = np.mean(self.__signal[cell])\n max_signal = max(abs(self.__signal[cell]-mean))\n norm_signal = (self.__signal[cell]-mean)/max_signal\n max_fast = max(abs(self.__filtered_fast[cell]))\n\n filtered_fast = self.__filtered_fast[cell]\n threshold = self.__distributions[cell][\"p_root\"]\n ax1.plot(self.__time, norm_signal*max_fast, linewidth=0.5, color='dimgrey', alpha=0.5)\n ax1.plot(self.__time, filtered_fast, linewidth=0.5, color='red')\n ax1.plot(self.__time, self.__binarized_fast[cell]*threshold, linewidth=0.75, color='black')\n ax1.axvline(self.__settings[\"Stimulation [frame]\"][0]/self.__settings[\"Sampling [Hz]\"], c=\"grey\")\n ax1.axvline(self.__settings[\"Stimulation [frame]\"][1]/self.__settings[\"Sampling [Hz]\"], c=\"grey\")\n ax1.set_ylabel(\"Amplitude\")\n\n if self.__activity is not False:\n border = self.__activity[cell]\n ax1.axvspan(0, border[0], alpha=0.5, color=EXCLUDE_COLOR)\n ax1.axvspan(border[1], self.__time[-1], alpha=0.5, color=EXCLUDE_COLOR)\n\n ax3 = ax1.twinx()\n ax3.set_ylabel(\"Action potentials\")\n\n filtered_slow = self.__filtered_slow[cell]\n ax2.plot(self.__time, 12/2*(norm_signal+1), linewidth=0.5, color='dimgrey', alpha=0.5)\n ax2.plot(self.__time, (filtered_slow/max(abs(filtered_slow))*6)+6, color='blue')\n ax2.plot(self.__time, self.__binarized_slow[cell], color='black')\n ax2.set_xlabel(\"Time [s]\")\n ax2.set_ylabel(\"Amplitude\")\n\n ax4 = ax2.twinx()\n ax4.set_ylabel(\"Phase\")\n\n return fig\n\n def save_plots(self, type, directory):\n if type not in (\"imported\", \"filtered\", \"distributions\", \"binarized\"):\n raise ValueError(\"Unknown 'type' argument.\")\n for i in range(self.__cells):\n if type == \"imported\":\n fig = self.plot(i)\n elif type == \"filtered\":\n fig = self.plot_filtered(i)\n elif type == \"distributions\":\n fig = self.plot_distributions(i)\n elif type == \"binarized\":\n fig = self.plot_binarized(i)\n plt.savefig(\"{0}/{1}.pdf\".format(directory, i), dpi=200, bbox_inches='tight')\n plt.close()\n\n def is_analyzed(self):\n if self.__filtered_slow is False or self.__filtered_fast is False:\n return False\n elif self.__distributions is False:\n return False\n elif self.__binarized_slow is False or self.__binarized_fast is False:\n return False\n elif self.__good_cells is False:\n return False\n elif self.__activity is False:\n return False\n else:\n return True\n","sub_path":"src/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":18276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"150953692","text":"import json\nimport os\nimport numpy as np\nimport re\n\n\ndef get_entity_count(folder_path):\n entity_count = {}\n\n for filename in os.listdir(folder_path):\n print(filename)\n\n with open(folder_path + \"/\" + filename) as json_file:\n data = json.load(json_file)\n\n for session in data['sessions']:\n session_sentiment = []\n parliament_sitting_date = re.findall(r\"\\d\\d\\d\\d-\\d\\d-\\d\\d\", data['filename'])[0] \n for speech in session['speeches']:\n for content in speech['content']:\n\n sentiment = content['sentiment']\n session_sentiment.append(sentiment)\n\n for entity in content['entities']:\n label = entity['label']\n if label in entity_count:\n entity_count[label] += 1\n else:\n entity_count[label] = 0\n\n return entity_count\n\n\ndef get_speaker_entity_count(folder_path):\n speaker_entity_count = {}\n\n for filename in os.listdir(folder_path):\n print(filename)\n\n with open(folder_path + \"/\" + filename) as json_file:\n data = json.load(json_file)\n\n for session in data['sessions']:\n session_sentiment = []\n parliament_sitting_date = re.findall(r\"\\d\\d\\d\\d-\\d\\d-\\d\\d\", data['filename'])[0] \n for speech in session['speeches']:\n name = speech['speaker']\n\n if name not in speaker_entity_count:\n speaker_entity_count[name] = {}\n\n for content in speech['content']:\n for entity in content['entities']:\n label = entity['label']\n if label in speaker_entity_count[name]:\n speaker_entity_count[name][label] += 1\n else:\n speaker_entity_count[name][label] = 0\n\n return speaker_entity_count\n","sub_path":"misc_stats.py","file_name":"misc_stats.py","file_ext":"py","file_size_in_byte":2002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"24244904","text":"from django.conf.urls.defaults import patterns, url\nfrom django.contrib.auth.decorators import login_required\n\nfrom evenio import views\n\nurlpatterns = patterns('',\n url(r'^$', views.EventsByDay.as_view(), name='list'),\n\n # Datebased views\n \n url(r'^today/(?P)',\n views.EventsByCategory.as_view()),\n \n url(r'^today',\n views.EventsByDay.as_view()),\n\n url(r'^this-week',\n views.EventsByWeek.as_view()),\n\n url(r'^this-month',\n views.EventsByMonth.as_view()),\n\n url(r'^this-year',\n views.EventsByYear.as_view()),\n\n # CRUD\n url(r'^events/(?P[\\w-]+)$', views.EventDetail.as_view(), name='show'),\n url(r'^events/(?P[\\w-]+)/update$', login_required(views.EventUpdate.as_view()), name='update'),\n url(r'^create$', login_required(views.EventCreate.as_view()), name='create'),\n\n)\n","sub_path":"evenio/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"181138389","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n功能:学习StringIO\n时间:2018年04月20日10:27:06\n备注:StringIO顾名思义就是在内存中读写str。\n\"\"\"\n\nfrom six.moves import StringIO\nimport pandas as pd\n\n\ndef just_try():\n data = StringIO() # 创建\n data.write(\"Hello\")\n data.write(\" \")\n data.write(\"world!\")\n\n print(data.getvalue())\n print(\"----------\")\n\n\ndef just_try2():\n CSV_COLUMN_NAMES = ['SepalLength', 'SepalWidth',\n 'PetalLength', 'PetalWidth', 'Species']\n\n FOUR_LINES = \"\\n\".join([\n \"1,52.40, 2823,152,2\",\n \"164, 99.80,176.60,66.20,1\",\n \"176,2824, 136,3.19,0\",\n \"2,177.30,66.30, 53.10,1\", ])\n\n text = StringIO(FOUR_LINES)\n df = pd.read_csv(text, names=CSV_COLUMN_NAMES) # 读取text数据,加上标题\n print(df)\n print(\"----------\")\n xy = (df, df.pop(\"Species\")) # df.pop(\"Species\")表示弹出Species这一列,特征和标签列就分离了\n print(xy[0])\n print(\"----------\")\n print(xy[1])\n\n\njust_try()\njust_try2()\nif __name__ == \"__main__\":\n pass\n","sub_path":"StringIO学习.py","file_name":"StringIO学习.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"112300826","text":"from direct.task import Task\nfrom panda3d.core import *\n\n# Global Variables for camera rotation\nheading = 0\npitch = 0\n\nclass Camera:\n def __init__(self, app):\n app = app\n\n # Hide cursor\n #props = WindowProperties()\n #props.setCursorHidden(True)\n #app.win.requestProperties(props)\n\n # dummy node for camera, we will rotate the dummy node fro camera rotation\n parentnode = app.render.attachNewNode('camparent')\n\n # parentnode.reparentTo(model) # inherit transforms, set to rocket node later on\n # parentnode.setEffect(CompassEffect.make(render)) # NOT inherit rotation\n\n # the camera\n app.camera.reparentTo(parentnode)\n app.camera.lookAt(parentnode)\n app.camera.setY(-10) # camera distance from model\n\n # camera zooming\n app.accept('wheel_up', lambda: app.camera.setY(app.camera.getY() + 200 * globalClock.getDt()))\n app.accept('wheel_down', lambda: app.camera.setY(app.camera.getY() - 200 * globalClock.getDt()))\n\n\n # camera rotation task\n def thirdPersonCameraTask(self):\n global heading\n global pitch\n\n md = app.win.getPointer(0)\n x = md.getX()\n y = md.getY()\n\n if app.win.movePointer(0, 300, 300):\n heading -= (x - 300) * 0.5\n pitch -= (y - 300) * 0.5\n\n parentnode.setHpr(heading, pitch, 0)\n\n return Task.cont\n\n app.taskMgr.add(thirdPersonCameraTask, 'thirdPersonCameraTask')","sub_path":"src/CameraControls.py","file_name":"CameraControls.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"332496780","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tempfile\n\nfrom tensorflow.compiler.plugin.poplar.driver.config_pb2 import IpuOptions\nfrom tensorflow.compiler.plugin.poplar.driver.trace_pb2 import IpuTraceEvent\nfrom tensorflow.compiler.plugin.poplar.ops import gen_ipu_ops\nfrom tensorflow.contrib.ipu import ipu_compiler\nfrom tensorflow.keras import layers\nfrom tensorflow.python.client import session as sl\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import init_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import rnn\nfrom tensorflow.python.ops import rnn_cell\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.ops.losses import losses\nfrom tensorflow.python.platform import googletest\nfrom tensorflow.contrib import ipu\nfrom tensorflow.python.training import gradient_descent\n\n\ndef count_compile_end_events(events):\n fn = (lambda x: 1 if x.type == IpuTraceEvent.COMPILE_END and len(\n x.compile_end.compilation_report) > 10 else 0)\n return sum(map(fn, events))\n\n\nclass ContribIpuOpsTest(test_util.TensorFlowTestCase):\n def testSummary(self):\n with ops.device(\"/device:IPU:0\"):\n a = array_ops.placeholder(np.float32, [1], name=\"a\")\n b = array_ops.placeholder(np.float32, [1], name=\"b\")\n out = a + b\n\n summary = ipu.ops.ipu_compile_summary('comp', out)\n\n cfg = ipu.utils.create_ipu_config(profiling=True)\n cfg = ipu.utils.set_ipu_model_options(cfg, compile_ipu_code=False)\n ipu.utils.configure_ipu_system(cfg)\n\n with sl.Session() as sess:\n fd = {\n a: [1.0],\n b: [2.0],\n }\n result, s = sess.run([out, summary], fd)\n self.assertAllClose(result, [3.0])\n self.assertTrue(len(s) > 100)\n\n def testCreateConfig(self):\n cfg = ipu.utils.create_ipu_config()\n cfg = ipu.utils.auto_select_ipus(cfg, [1, 1])\n self.assertTrue(isinstance(cfg, IpuOptions))\n self.assertTrue(len(cfg.device_config), 2)\n\n cfg = ipu.utils.create_ipu_config()\n cfg = ipu.utils.auto_select_ipus(cfg, [4, 4])\n self.assertTrue(isinstance(cfg, IpuOptions))\n self.assertTrue(len(cfg.device_config), 2)\n self.assertTrue(cfg.device_config[0].auto_count, 4)\n self.assertTrue(cfg.device_config[1].auto_count, 4)\n\n cfg = ipu.utils.create_ipu_config()\n cfg = ipu.utils.auto_select_ipus(cfg, [4, 4])\n self.assertTrue(isinstance(cfg, IpuOptions))\n self.assertTrue(len(cfg.device_config), 2)\n self.assertTrue(cfg.device_config[0].auto_count, 4)\n self.assertTrue(cfg.device_config[1].auto_count, 4)\n\n cfg = ipu.utils.create_ipu_config()\n cfg = ipu.utils.select_ipus(cfg, [2, 3])\n self.assertTrue(isinstance(cfg, IpuOptions))\n self.assertTrue(len(cfg.device_config), 2)\n self.assertTrue(cfg.device_config[0].cfg_index, 2)\n self.assertTrue(cfg.device_config[1].cfg_index, 3)\n\n cfg = ipu.utils.create_ipu_config()\n cfg = ipu.utils.set_compilation_options(cfg, {'A': 'B', 'C': 'D'})\n self.assertTrue(len(cfg.compilation_options), 2)\n self.assertTrue(cfg.compilation_options[0].option, \"A\")\n self.assertTrue(cfg.compilation_options[0].value, \"B\")\n self.assertTrue(cfg.compilation_options[1].option, \"C\")\n self.assertTrue(cfg.compilation_options[1].value, \"D\")\n\n with self.assertRaises(Exception):\n cfg = ipu.utils.create_ipu_config()\n cfg = ipu.utils.select_ipus(cfg, [4, 4])\n\n with self.assertRaises(Exception):\n cfg = ipu.utils.create_ipu_config(profiling=True, enable_ipu_events=True)\n\n with self.assertRaises(Exception):\n cfg = ipu.utils.create_ipu_config(\n profiling=False, profile_execution=True)\n\n def testEventFetchAndStringDecode(self):\n with ops.device(\"/device:IPU:0\"):\n a = array_ops.placeholder(np.float32, [1], name=\"a\")\n b = array_ops.placeholder(np.float32, [1], name=\"b\")\n out = a + b\n\n events = gen_ipu_ops.ipu_event_trace()\n\n cfg = ipu.utils.create_ipu_config(profiling=True)\n cfg = ipu.utils.set_ipu_model_options(cfg, compile_ipu_code=False)\n ipu.utils.configure_ipu_system(cfg)\n\n with sl.Session() as sess:\n # Discard any existing events\n sess.run(events)\n\n fd = {\n a: [1.0],\n b: [2.0],\n }\n result = sess.run(out, fd)\n self.assertAllClose(result, [3.0])\n\n # 1x compile begin, 1x compile end, 1x load engine, 1x execute\n e = sess.run(events)\n self.assertEqual(len(e), 4)\n\n dump = ipu.utils.extract_all_strings_from_event_trace(e)\n self.assertTrue(len(dump) > 100)\n\n def testMaxReportSize(self):\n with ops.device(\"/device:IPU:0\"):\n a = array_ops.placeholder(np.float32, [1], name=\"a\")\n b = array_ops.placeholder(np.float32, [1], name=\"b\")\n out = a + b\n\n events = gen_ipu_ops.ipu_event_trace()\n\n cfg = ipu.utils.create_ipu_config(\n profiling=True, profile_execution=True, max_report_size=10)\n cfg = ipu.utils.set_ipu_model_options(cfg, compile_ipu_code=False)\n ipu.utils.configure_ipu_system(cfg)\n\n with sl.Session() as sess:\n # Discard any existing events\n sess.run(events)\n\n result = sess.run(out, {a: [1.0], b: [2.0]})\n self.assertAllClose(result, [3.0])\n\n # 1x compile begin, 1x compile end, 1x load engine, 1x execute\n e = sess.run(events)\n self.assertEqual(len(e), 4)\n\n reps = ipu.utils.extract_compile_reports(e)\n self.assertEqual(len(reps), 0)\n\n reps = ipu.utils.extract_execute_reports(e)\n self.assertEqual(len(reps), 0)\n\n def testDumpReportsToFile(self):\n with ops.device(\"/device:IPU:0\"):\n a = array_ops.placeholder(np.float32, [1], name=\"a\")\n b = array_ops.placeholder(np.float32, [1], name=\"b\")\n out = a + b\n\n tmpdir = tempfile.mkdtemp()\n\n events = gen_ipu_ops.ipu_event_trace()\n\n cfg = ipu.utils.create_ipu_config(\n profiling=True, profile_execution=True, report_directory=tmpdir)\n cfg = ipu.utils.set_ipu_model_options(cfg, compile_ipu_code=False)\n ipu.utils.configure_ipu_system(cfg)\n\n with sl.Session() as sess:\n # Discard any existing events\n sess.run(events)\n\n result = sess.run(out, {a: [1.0], b: [2.0]})\n self.assertAllClose(result, [3.0])\n\n # 1x compile begin, 1x compile end, 1x load engine, 1x execute\n e = sess.run(events)\n self.assertEqual(len(e), 4)\n\n reps = ipu.utils.extract_compile_reports(e)\n self.assertEqual(len(reps), 1)\n self.assertTrue(reps[0][1].startswith(tmpdir))\n with open(reps[0][1]) as f:\n rep = f.read()\n self.assertTrue(len(rep) > 1000)\n self.assertEqual(rep[0], '{')\n\n reps = ipu.utils.extract_execute_reports(e)\n self.assertEqual(len(reps), 1)\n self.assertTrue(reps[0][1].startswith(tmpdir))\n with open(reps[0][1]) as f:\n rep = f.read()\n self.assertTrue(len(rep) > 1000)\n self.assertEqual(rep[0], '{')\n\n def testIpuSimpleScopeAndExecutionReport(self):\n def my_net(a, b):\n c = a + b\n return [c]\n\n with ops.device('cpu'):\n a = array_ops.placeholder(np.float32, [1], name=\"a\")\n b = array_ops.placeholder(np.float32, [1], name=\"b\")\n events = gen_ipu_ops.ipu_event_trace()\n\n with ipu.ops.ipu_scope(\"/device:IPU:0\"):\n r = ipu_compiler.compile(my_net, inputs=[a, b])\n\n cfg = ipu.utils.create_ipu_config(profiling=True, profile_execution=True)\n cfg = ipu.utils.set_ipu_model_options(cfg, compile_ipu_code=False)\n ipu.utils.configure_ipu_system(cfg)\n\n with sl.Session() as sess:\n\n fd = {\n a: [1],\n b: [2],\n }\n\n sess.run(events)\n\n res = sess.run(r[0], fd)\n self.assertEqual(res, [3])\n\n e = sess.run(events)\n evts = ipu.utils.extract_all_events(e)\n self.assertEqual(count_compile_end_events(evts), 1)\n\n compilation_rep = ipu.utils.extract_compile_reports(e)\n self.assertEqual(len(compilation_rep), 1)\n self.assertEqual(type(compilation_rep), list)\n self.assertEqual(type(compilation_rep[0]), tuple)\n self.assertTrue(compilation_rep[0][0].startswith(\"cluster\"))\n self.assertTrue(len(compilation_rep[0][1]) > 1000)\n self.assertTrue(compilation_rep[0][1].startswith('{'))\n\n execution_rep = ipu.utils.extract_execute_reports(e)\n self.assertEqual(len(execution_rep), 1)\n self.assertEqual(type(execution_rep), list)\n self.assertEqual(type(execution_rep[0]), tuple)\n self.assertTrue(execution_rep[0][0].startswith(\"cluster\"))\n self.assertTrue(len(execution_rep[0][1]) > 1000)\n self.assertTrue(execution_rep[0][1].startswith('{'))\n\n def testIpuWhileScope(self):\n # 1: design is targetted at the device\n # 2: variables are resource variables\n # 3: training a while_loop is possible\n def my_net(a, b):\n c = variable_scope.get_variable('c', initializer=[1.0])\n self.assertTrue(\"ResourceVariable\" in str(type(c)))\n\n lstm_cell = rnn_cell.LSTMCell(1, forget_bias=1.0)\n outputs, states = rnn.dynamic_rnn(lstm_cell, a, dtype=np.float32)\n\n logits = outputs[-1] * c\n self.assertEqual(logits.device, \"/device:IPU:0\")\n\n res = array_ops.reshape(logits, [1, 8, 1])\n\n l = losses.mean_squared_error(res, b)\n\n optimizer = gradient_descent.GradientDescentOptimizer(0.1)\n train = optimizer.minimize(l)\n\n return [l, train]\n\n with ops.device('cpu'):\n a = array_ops.placeholder(np.float32, [1, 8, 1], name=\"a\")\n b = array_ops.placeholder(np.float32, [1, 8, 1], name=\"b\")\n\n with ipu.ops.ipu_scope(\"/device:IPU:0\"):\n\n l = ipu_compiler.compile(my_net, inputs=[a, b])\n\n cfg = ipu.utils.create_ipu_config()\n cfg = ipu.utils.set_ipu_model_options(cfg, compile_ipu_code=False)\n ipu.utils.configure_ipu_system(cfg)\n\n with sl.Session() as sess:\n # Initialize and then discard events relating to initialization\n sess.run(variables.global_variables_initializer())\n\n fd = {\n a: [[[1.], [1.], [1.], [1.], [1.], [1.], [1.], [1.]]],\n b: [[[1.], [1.], [1.], [1.], [1.], [1.], [1.], [1.]]],\n }\n\n l_initial = sess.run([l], fd)\n\n for _ in range(100):\n _ = sess.run([l], fd)\n\n l_final = sess.run([l], fd)\n\n self.assertTrue(l_initial > l_final)\n\n def testInitializerDeviceChange(self):\n\n inp = array_ops.placeholder(np.float32, [1, 8, 8, 4])\n with ipu.ops.ipu_scope(\"/device:IPU:0\"):\n out = layers.Conv2D(8, 1)(inp)\n\n events = gen_ipu_ops.ipu_event_trace()\n\n ipu.utils.move_variable_initialization_to_cpu()\n\n cfg = ipu.utils.create_ipu_config(profiling=True)\n cfg = ipu.utils.set_ipu_model_options(cfg, compile_ipu_code=False)\n ipu.utils.configure_ipu_system(cfg)\n\n with sl.Session() as sess:\n # Discard any pending events\n sess.run(events)\n\n # Run initializer (should be on CPU)\n sess.run(variables.global_variables_initializer())\n\n e = sess.run(events)\n self.assertEqual(len(e), 2) # compile begin/end, no load/execute\n\n def testVarsInitializedByStreamsAreLoggedAsOnDevice(self):\n # This verifies that when an initialization graph has no ops in it (it is\n # a pass through of streaming inputs to initialized resources) then the\n # resources are logged as resources on the device so that a future execution\n # sees them as valid and on device\n w_val1 = np.array([1, 2, 3, 4])\n w_val2 = np.array([4, 3, 2, 1])\n w_val3 = np.array([9, 0, 9, 0])\n with ops.device(\"/device:IPU:1\"):\n with variable_scope.variable_scope(\"vs\", use_resource=True):\n w1 = variable_scope.get_variable(\n \"w1\",\n shape=[4],\n dtype=np.float32,\n initializer=init_ops.constant_initializer(\n w_val1, dtype=np.float32))\n w2 = variable_scope.get_variable(\n \"w2\",\n shape=[4],\n dtype=np.float32,\n initializer=init_ops.constant_initializer(\n w_val2, dtype=np.float32))\n w3 = variable_scope.get_variable(\n \"w3\",\n shape=[4],\n dtype=np.float32,\n initializer=init_ops.constant_initializer(\n w_val3, dtype=np.float32))\n\n y = w1 + w2 + w3\n\n ipu.utils.move_variable_initialization_to_cpu()\n\n cfg = ipu.utils.create_ipu_config(profiling=False)\n cfg = ipu.utils.set_ipu_model_options(cfg, compile_ipu_code=False)\n cfg = ipu.utils.auto_select_ipus(cfg, 2)\n ipu.utils.configure_ipu_system(cfg)\n\n with sl.Session() as sess:\n sess.run(variables.global_variables_initializer())\n\n xs = [\n np.array([7, 3, 5, 9], dtype=np.float32),\n np.array([1, 8, 3, 4], dtype=np.float32),\n np.array([9, 2, 2, 6], dtype=np.float32)\n ]\n for x in xs:\n out = sess.run(y)\n self.assertAllClose(out, w_val1 + w_val2 + w_val3)\n\n def testMultiScopeTest(self):\n with ops.device('cpu'):\n x = array_ops.placeholder(np.float32, [2, 2])\n y = array_ops.placeholder(np.float32, [2, 2])\n report = gen_ipu_ops.ipu_event_trace()\n\n with ipu.ops.ipu_scope('/device:IPU:0'):\n z = math_ops.matmul(x, y)\n with ipu.ops.ipu_scope('/device:IPU:0'):\n z2 = math_ops.matmul(x, z)\n\n cfg = ipu.utils.create_ipu_config(profiling=True)\n cfg = ipu.utils.set_ipu_model_options(cfg, compile_ipu_code=False)\n ipu.utils.configure_ipu_system(cfg)\n\n with sl.Session() as sess:\n sess.run(report)\n result = sess.run(z2, {x: np.ones([2, 2]), y: np.ones([2, 2])})\n\n self.assertAllEqual(result, [[4, 4], [4, 4]])\n\n rep = sess.run(report)\n evts = ipu.utils.extract_all_types_from_event_trace(rep)\n\n num_compiles = 0\n num_executions = 0\n for e in evts:\n if e == IpuTraceEvent.COMPILE_END:\n num_compiles += 1\n if e == IpuTraceEvent.EXECUTE:\n num_executions += 1\n\n self.assertEqual(num_compiles, 1)\n self.assertEqual(num_executions, 1)\n\n def testResetSeedTest(self):\n # This tests that the API can be called - full testing must be performed\n # on hardware because the IPU_MODEL doesn't have full random number support.\n with ops.device('cpu'):\n x = array_ops.placeholder(np.float32, [2, 2])\n\n with ipu.ops.ipu_scope('/device:IPU:0'):\n z = math_ops.cast(x, dtype=np.float16)\n\n cfg = ipu.utils.create_ipu_config(profiling=True)\n cfg = ipu.utils.set_ipu_model_options(cfg, compile_ipu_code=False)\n ipu.utils.configure_ipu_system(cfg)\n\n with sl.Session() as sess:\n result = sess.run(z, {x: [[1., 1.], [1., 1.]]})\n self.assertAllEqual(result, [[1., 1.], [1., 1.]])\n\n ipu.utils.reset_ipu_seed(1)\n\n result = sess.run(z, {x: [[2., 2.], [2., 2.]]})\n self.assertAllEqual(result, [[2., 2.], [2., 2.]])\n\n\nif __name__ == \"__main__\":\n googletest.main()\n","sub_path":"tensorflow/contrib/ipu/python/tests/ops_test.py","file_name":"ops_test.py","file_ext":"py","file_size_in_byte":14953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"486514778","text":"\ndef count_bits(num):\n count = 0\n while num:\n count = count ^ 1\n num = num & (num-1)\n return count\n\nvar = int(input(\"Give a number\"))\nset_bits = count_bits(var)\nif set_bits:\n print(\"It is odd parity\")\nelse:\n print(\"It is even parity\")\n","sub_path":"python-programming-workshop/algorithms/find_parity_three.py","file_name":"find_parity_three.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"40692790","text":"# -*- coding: utf-8 -*-\n\nimport unittest\nimport os\nimport tempfile\nfrom io import StringIO\nfrom mock import patch, Mock\nimport numpy as np\nfrom common import constants, trie_replace\nfrom deeplearning.short_mention_classification.data_preprocess import \\\n create_training_data, preprocess_mentions\n\n\nclass DataPreprocessTest(unittest.TestCase):\n\n @patch('deeplearning.short_mention_classification.data_preprocess.load_word_embedding_model')\n def test_create_training_data(self, load_word_embedding_model_mock):\n training_hdf5_path = tempfile.mkdtemp() + '/training.hdf5'\n vocab_path = tempfile.mkdtemp() + '/sentiment_vocab.hdf5'\n\n negative_data = u'iphone đẹp quá\\nngân hàng A tuyệt vời'\n not_negative_data = u'samsung như shit\\n chán quá'\n\n constants.SHORT_MENTION_NEGATIVE_TRAINING_HDF5_PATH = training_hdf5_path\n constants.VOCAB_PATH = vocab_path\n word_vectors_mock = load_word_embedding_model_mock.return_value\n word_vectors_mock.index2word = [u'iphone', u'tuyệt', u'shit', u'chán']\n\n create_training_data(constants.NEGATIVE,\n StringIO(negative_data), StringIO(not_negative_data))\n\n self.assertTrue(os.path.isfile(training_hdf5_path))\n\n os.remove(training_hdf5_path)\n os.remove(vocab_path)\n constants.SHORT_MENTION_NEGATIVE_TRAINING_HDF5_PATH = '/data/sentimentv2/training_data/short_mention_negative_training.hdf5'\n constants.VOCAB_PATH = '/data/sentimentv2/models/word_embedding/sentiment_vocab.bin'\n\n def test_preprocess_mentions(self):\n mentions = [u'iphone đẹp quá', u'samsung như shit']\n keywords = [u'iphone', u'samsung']\n ent_trie = trie_replace.get_entity_trie()\n vocab_processor = Mock()\n vocab_processor.transform.return_value = [1, 2, 3, 4, 5]\n\n preprocessed_mentions = preprocess_mentions(\n vocab_processor, mentions, keywords, ent_trie)\n\n self.assertItemsEqual(preprocessed_mentions, np.array([1, 2, 3, 4, 5]))\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"SentimentV2/Sentiment/deeplearning/short_mention_classification/data_preprocess_test.py","file_name":"data_preprocess_test.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"524161426","text":"from __future__ import print_function\n\nimport pickle\nimport numpy as np\nimport os\nimport gzip\nimport random\nimport matplotlib.pyplot as plt\n\nfrom model import Model\nfrom utils import *\nfrom tensorboard_evaluation import Evaluation\n\ndef read_data(datasets_dir=\"./data\", frac = 0.1):\n \"\"\"\n This method reads the states and actions recorded in drive_manually.py \n and splits it into training/ validation set.\n \"\"\"\n print(\"... read data\")\n data_file = os.path.join(datasets_dir, 'data.pkl.gzip')\n \n f = gzip.open(data_file,'rb')\n data = pickle.load(f)\n\n # get images as features and actions as targets\n X = np.array(data[\"state\"]).astype('float32')\n y = np.array(data[\"action\"]).astype('float32')\n\n # split data into training and validation set\n n_samples = len(data[\"state\"])\n X_train, y_train = X[:int((1-frac) * n_samples)], y[:int((1-frac) * n_samples)]\n X_valid, y_valid = X[int((1-frac) * n_samples):], y[int((1-frac) * n_samples):]\n return X_train, y_train, X_valid, y_valid\n\n\ndef preprocessing(X_train, y_train, X_valid, y_valid, history_length=1):\n\n # TODO: preprocess your data here.\n # 1. convert the images in X_train/X_valid to gray scale. If you use rgb2gray() from utils.py, the output shape (96, 96, 1)\n # 2. you can either train your model with continous actions (as you get them from read_data) using regression\n # or you discretize the action space using action_to_id() from utils.py. If you discretize them, you'll maybe find one_hot() \n # useful and you may want to return X_train_unhot ... as well.\n n_train = X_train.shape[0]\n n_valid = X_valid.shape[0]\n dim_X = X_train.shape[1]\n \n X_train = rgb2gray(X_train)\n X_valid = rgb2gray(X_valid)\n \n y_train_ids = np.zeros(n_train)\n y_valid_ids = np.zeros(n_valid)\n for i in range(n_train):\n y_train_ids[i] = action_to_id(y_train[i])\n for i in range(n_valid):\n y_valid_ids[i] = action_to_id(y_valid[i])\n #print(y_train_ids.shape)\n y_train = one_hot(y_train_ids.astype(int))\n y_valid = one_hot(y_valid_ids.astype(int))\n # History:\n # At first you should only use the current image as input to your network to learn the next action. Then the input states\n # have shape (96, 96,1). Later, add a history of the last N images to your state so that a state has shape (96, 96, N).\n \n X_train = build_history(X_train, n_train, dim_X, history_length)\n X_valid = build_history(X_valid, n_valid, dim_X, history_length)\n \n #print(X_train.shape)\n #print(y_train.shape)\n \n return X_train, y_train, X_valid, y_valid\n\ndef build_history(X, n, dim, history_length):\n X_hist = np.zeros((n, dim, dim, history_length))\n for i in range(n):\n for j in range(history_length):\n X_hist[i, :, :, j] = X[max(0, i-j), :, :]\n \n return X_hist\n\ndef train_model(X_train, y_train, X_valid, y_valid, n_minibatches, batch_size, lr, model_dir=\"./models\", tensorboard_dir=\"./tensorboard\"):\n \n # create result and model folders\n if not os.path.exists(model_dir):\n os.mkdir(model_dir) \n \n print(\"... train model\")\n\n\n # TODO: specify your neural network in model.py \n agent = Model(input_shape=X_train.shape[1:], n_classes=y_train.shape[1], learning_rate=lr)\n \n tensorboard_eval = Evaluation(tensorboard_dir)\n \n # TODO: implement the training\n # \n # 1. write a method sample_minibatch and perform an update step\n # 2. compute training/ validation accuracy and loss for the batch and visualize them with tensorboard. You can watch the progress of\n # your training in your web browser\n # \n # training loop\n for i in range(n_minibatches):\n X_batch, y_batch = sample_minibatch(X_train, y_train, batch_size)\n _, loss = agent.session.run([agent.optimizer, agent.loss], \n feed_dict={agent.X : X_batch, agent.y : y_batch})\n \n if i % 10 == 0:\n print(\"... %i / %i\" % (i, n_minibatches))\n train_acc = agent.accuracy.eval({agent.X : X_batch, agent.y : y_batch}, session=agent.session)\n val_acc = agent.accuracy.eval({agent.X : X_valid, agent.y : y_valid}, session=agent.session)\n tensorboard_eval.write_episode_data(i, {\"loss\" : loss, \"train_acc\" : train_acc, \"val_acc\" : val_acc})\n \n # TODO: save your agent\n model_path = os.path.join(model_dir, \"agent.ckpt\")\n model_dir = agent.save(model_path)\n print(\"Model saved in file: %s\" % model_path)\n\n\ndef sample_minibatch(X, y, batch_size):\n batch_indices = random.sample(range(len(X)), batch_size)\n X_batch = X[batch_indices]\n y_batch = y[batch_indices]\n return X_batch, y_batch\n\nif __name__ == \"__main__\":\n\n # read data \n X_train, y_train, X_valid, y_valid = read_data(\"./data\")\n\n # preprocess data\n X_train, y_train, X_valid, y_valid = preprocessing(X_train, y_train, X_valid, y_valid, history_length=1)\n\n # train model (you can change the parameters!)\n train_model(X_train, y_train, X_valid, y_valid, n_minibatches=1000, batch_size=64, lr=0.0001)\n \n","sub_path":"exercise3_R_NR/train_agent.py","file_name":"train_agent.py","file_ext":"py","file_size_in_byte":5155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"241326171","text":"import json\nfrom _md5 import md5\nfrom multiprocessing.pool import Pool\nimport re\nimport os\nimport pymongo\nimport requests\nfrom bs4 import BeautifulSoup\nfrom config import *\n\n# 链接mongodb数据库,多进程这里可能会报警告\nclient = pymongo.MongoClient(MONGO_URL,connect=False)\n# 定义一个数据库\ndb = client[MONGO_DB]\n\ndef get_page_list(offset,keyword):\n '''\n 获取主页面所有帖子的链接\n '''\n # 请求ajax的一些参数,通过浏览器F12看到的\n params = {\n 'offset': offset,\n 'format': 'json',\n 'keyword': keyword,\n 'autoload': 'true',\n 'count': '20',\n 'cur_tab': 1,\n 'from': 'search_tab'\n }\n # from urllib.parse import urlencode # 用下面这种要import这个\n # url解析自带的,就是把那个参数弄成一个链接,教程用的是下面这种方式把参数和url拼接\n # url = 'https://www.toutiao.com/search_content/?' + urlencode(params)\n\n url = 'https://www.toutiao.com/search_content'\n try:\n # 我是把参数传入到get请求里面,如果用上面那种,这里的params形参就要删掉\n response = requests.get(url,headers = HEADERS,params=params)\n # 因为要返回的是一个文本,所以用response.text,若要返回二进制数据,用response.content\n return response.text\n except:\n # 可能会url请求出错,避免停止,捕获一下异常\n return None\n\ndef parse_page_list(html):\n '''\n 解析主页,取得帖子的链接\n '''\n # 把得到的ajax弄成一个json,方便处理,另外,注意是loads不是load\n data = json.loads(html)\n # 下面的内容是分析浏览器F12的network中的各种数据得到的\n if data and 'data' in data.keys():\n # 数据是层层字典嵌套的,一步步取出来\n for item in data.get('data'):\n # 这个yield如果不懂可以理解为return的高级版本\n yield item.get('article_url')\n\ndef get_page_detail(url):\n '''\n 根据主页的那些链接,访问帖子\n '''\n try:\n response = requests.get(url,headers=HEADERS)\n # 帖子请求成功才返回\n if response.status_code == 200:\n return response.text\n return None\n except:\n return None\n\ndef parse_page_detail(html):\n '''\n 爬取帖子里面的所以照片链接和帖子名称\n '''\n try:\n # 一开始用的正则,有点小错误,直接拿汤器祭神\n soup = BeautifulSoup(html, 'lxml')\n # 用选择,直接找到项目为title的内容\n title = soup.select('title')[0].get_text()\n # 这是图片的正则模式\n pattern = re.compile('"(http:.*?)"', re.S)\n # 找到所有的图片链接\n images = re.findall(pattern,html)\n except:\n return None\n # 以特定格式返回,title是str,images是list\n return {\n 'title':title,\n 'images':images\n }\n\ndef save_to_mongo(result):\n '''\n 存储\n {\n 'title':title,\n 'images':images\n }\n '''\n # 把结果插入到表MONGO_TABLE中,成功返回True,失败False\n if db[MONGO_TABLE].insert(result):\n print('存到mongodb成功: ',result['title'])\n return True\n return False\n\ndef download_save_image(url):\n '''\n 下载图片,并保存到本地\n '''\n try:\n # 封装请求\n response = requests.get(url,headers=HEADERS)\n # 如果是图片就返回content好,如果是网页就text\n content = response.content\n # 图片的存路径,因为图片可能会重复,所以加一个md5的命名规则,避免重复下载\n file_path = '{0}/images/{1}.{2}'.format(os.getcwd(), md5(content).hexdigest(),'jpg')\n # 我是把图片都放在images文件夹下,如果还要分得更细,可以再创建一个\"./images/图片集名字\"这样的文件夹\n dir = '{0}/images'.format(os.getcwd())\n # 如果没有images文件夹,就新建一个\n if not os.path.exists(dir):\n os.mkdir(dir)\n # 这个就是创建图片(因为用了md5,所以不允许有重复的图片)\n if not os.path.exists(file_path):\n with open(file_path,'wb') as f:\n f.write(content)\n print('图片保存成功:'+url)\n except:\n return None\n\n\n\n\ndef main(offset):\n # 获取主页html\n html = get_page_list(offset,KEYWORD)\n # 解析上面的html得到链接\n url_list = parse_page_list(html)\n\n for url in url_list:\n print(url)\n # 进入详情页\n html = get_page_detail(url)\n if html:\n # 得到详情页的图片链接\n result = parse_page_detail(html)\n print(html)\n # 如果图片链接结果不为空\n if result and result['images']:\n\n # 先存相关信息到mongo\n save_to_mongo(result)\n # 再下载一份到本地\n for url in result['images']:\n download_save_image(url)\n\nif __name__ == '__main__':\n # 三行加起来是并行进行\n # l = [i*20 for i in range(START_OFFSET,END_OFFSET)]\n # pool = Pool()\n # pool.map(main,l)\n main(0)","sub_path":"spider_toutiao/spider_toutiao_jiepai.py","file_name":"spider_toutiao_jiepai.py","file_ext":"py","file_size_in_byte":5282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"151224200","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 18 09:55:42 2020\n\n@author: maurop\n\"\"\"\n\n# =============================================================================\n# Imports\n# =============================================================================\n\nimport re\n\nimport RequestsHandler\nimport Taxa\nimport FileInfo\nimport ProgressBar\nimport LogFiles\n\n# =============================================================================\n# Logging\n# =============================================================================\n\nlogger = LogFiles.Logger(__name__)\n\n# =============================================================================\n# Scrape NBN Atlas\n# =============================================================================\n\nNBN_HOME = \"https://species.nbnatlas.org\" \n\n\ndef process_author(html_element):\n author = html_element.text\n\n # remove the nomen nudum here\n author = author.replace(\"nomen nudum\", \"\")\n \n if author != html_element.text:\n logger.report_log(html_element.text + \" Removed nomen nudum\")\n \n author = author.strip()\n \n regex = re.compile(r\"[^,] [(\\[]?\\d\\d\\d\\d[)\\]]?\")\n \n # add the comma before the year\n rematch = regex.findall(author)\n \n if rematch:\n \n pos = author.find(rematch[0])\n \n author = author[:pos + 1] + \",\" + author[pos + 1:] \n \n logger.report_log(author + \" Added comma\")\n \n return author\n\n\ndef gather_child_taxa(url, filename):\n '''Function that scans the web page and gathers the child taxa of the url'''\n \n soup = RequestsHandler.get_soup(url, filename)\n \n # search for the child taxa section that contains all the names\n children = soup.find(\"dl\", class_=\"child-taxa\")\n \n # names with hierarchy tags (subfamily, genus, ...)\n dts = children.find_all(\"dt\")\n \n # the real names\n dds = children.find_all(\"dd\")\n \n if len(dts) != len(dds):\n raise Exception(\"Gather child taxa: dts / dds different length\")\n \n\n # return the zipped elements\n return zip(dts, dds)\n\n\nclass NBNElement:\n ''' Class that processes the informations inside the gathered taxa'''\n \n def __init__(self, html_rank, html_name, fileinfo):\n self.html_rank = html_rank\n self.html_name = html_name\n self.fileinfo = fileinfo\n \n def get_link(self):\n '''Method that gets the link from the name box'''\n link = self.html_name.find(\"a\")\n if link:\n link = link.get(\"href\")\n if link.startswith(NBN_HOME):\n return link\n else:\n return NBN_HOME + link\n else:\n return None \n \n def get_name(self):\n '''Method that gets the name (e.g. Boletina plana)'''\n return self.html_name.find(\"span\", class_=\"name\").text\n \n def get_rank(self):\n '''Method that gets the rank (specie, genus, ...) '''\n return self.html_rank.text\n\n def gather_child_elements(self):\n '''Method that gather the child elements from the page \n pointed by the get_link() method'''\n if self.get_link():\n link = self.get_link()\n filename = self.fileinfo.cache_filename(self.get_name())\n html_elements = gather_child_taxa(link, filename)\n \n return [NBNElement(dt, dd, self.fileinfo) for dt, dd in html_elements]\n \n def get_author(self):\n '''Method that gets the author name for the element'''\n author = self.html_name.find(\"span\", class_=\"author\")\n if author:\n return process_author(author)\n else:\n return None\n\n\ndef gather_taxonomy(url, filename):\n ''' Function that scraps the taxonomy of a specie,\n it searches in the classification section the various ranks, and groups\n them in a dictionary. The function gathers the data for the subspecies too.\n returns a list of dictionaries where the first element is the specie and is\n always present, the other elements are subspecies in case they exist'''\n \n # find ranks and the name associated\n soup = RequestsHandler.get_soup(url, filename)\n children = soup.find(\"section\", id=\"classification\")\n \n dts = children.find_all(\"dt\")\n dds = children.find_all(\"dd\")\n\n html_parts = zip(dts, dds)\n \n # compiles the specie + subspecie list\n species = []\n \n species.append({})\n \n # find the subspecie and append the eventual subspecie name and author\n \n for dt, dd in html_parts:\n if dt.text == \"subspecies\":\n subspecie_name = dd.find(\"span\", class_=\"name\").text.split(\" \")[3]\n subspecie_author = process_author(dd.find(\"span\", class_=\"author\"))\n species.append({\"subspecies\" : subspecie_name, \"author\" : subspecie_author})\n \n # fill in the dictionary the rest of the taxonomy\n for dt, dd in zip(dts, dds):\n if dt.text == \"subspecies\":\n continue\n \n for specie in species:\n name = dd.find(\"span\", class_=\"name\").text\n \n if dt.text == \"species\":\n name = name.split(\" \")[1]\n \n specie[dt.text] = name\n\n return species\n\n\ndef generate_lists(family_name, fileinfo, load_lists = True):\n '''Function that arranges the genuses and species in a list, the function\n could be translated in a tree, but ... is difficult. The function returns\n a list of Taxa with name, author and reference link'''\n \n logger.main_log(\"Generating taxa list from NBN Atlas...\")\n logger.log_short_report(\"Input name: \" + family_name)\n \n api_url = \"https://species-ws.nbnatlas.org/search?\"\n \n param = {\"q\" : family_name,\n \"fq\": \"idxtype:TAXON\"}\n \n req = RequestsHandler.Request(api_url, fileinfo.cache_filename(\"family_search\"), param)\n req.load()\n \n search_json = req.get_json()\n search_results = search_json[\"searchResults\"][\"results\"]\n \n # display the possible matches\n logger.log_short_report(f\"Possible matches: {len(search_results)}\")\n for result in search_results:\n logger.log_short_report(f\" -{result['name']} ({result['guid']})\")\n \n # pick the first result\n family_guid = search_results[0][\"guid\"]\n \n # parameters for the webpage corresponding to the family\n family_url = \"https://species.nbnatlas.org/species/\" + family_guid\n \n filename = fileinfo.cache_filename(\"family\")\n \n taxa = gather_child_taxa(family_url, filename)\n \n \n # start getting the speceis\n genus_list = []\n species_list = []\n \n pwheel = ProgressBar.ProgressWheel()\n \n # search for the child taxa\n for dt, dd in taxa:\n \n fam_taxa = Taxa.Taxa()\n fam_taxa.family = family_name\n \n fam_taxa.rank = Taxa.Taxa.rank_genus\n fam_taxa.source = \"n\"\n \n pwheel.draw_symbol()\n \n element = NBNElement(dt, dd, fileinfo)\n \n # if is a subfamily\n if element.get_rank() == \"subfamily\":\n \n subfam = element.gather_child_elements()\n\n for subf in subfam:\n \n subfam_taxa = Taxa.Taxa()\n subfam_taxa.copy_taxa(fam_taxa)\n subfam_taxa.subfamily = element.get_name()\n \n if subf.get_rank() == \"tribe\":\n genuses = subf.gather_child_elements()\n \n # if is a genus with a tribe and subfamily\n for genus in genuses:\n if genus.get_rank() == \"genus\":\n \n taxa = Taxa.Taxa()\n taxa.copy_taxa(subfam_taxa)\n \n taxa.author = genus.get_author()\n taxa.genus = genus.get_name()\n taxa.links.append(genus.get_link())\n taxa.tribe = subf.get_name()\n \n genus_list.append(taxa)\n \n # if is a genus with subfamily without a tribe\n if subf.get_rank() == \"genus\":\n \n taxa = Taxa.Taxa()\n taxa.copy_taxa(subfam_taxa)\n\n taxa.author = genus.get_author()\n taxa.genus = genus.get_name()\n taxa.links.append(genus.get_link())\n \n genus_list.append(taxa)\n \n # if is a genus without subfamily\n if element.get_rank() == \"genus\":\n taxa = Taxa.Taxa()\n taxa.copy_taxa(fam_taxa)\n\n taxa.author = element.get_author()\n taxa.genus = element.get_name()\n taxa.links.append(element.get_link())\n \n genus_list.append(taxa) \n \n for genus in genus_list:\n pwheel.draw_symbol()\n \n filename = fileinfo.cache_filename(f\"{genus.genus}_webpage\")\n\n html_elements = gather_child_taxa(genus.links[0], filename)\n \n for dt, dd in html_elements:\n specie = NBNElement(dt, dd, fileinfo) \n\n taxa = Taxa.Taxa()\n taxa.copy_taxa(genus)\n \n taxa.author = specie.get_author()\n taxa.specie = specie.get_name().replace(genus.genus, \"\").strip()\n taxa.rank = Taxa.Taxa.rank_specie\n taxa.links.append(specie.get_link())\n \n species_list.append(taxa)\n \n # find subspecies somehow\n # is possible that the name of the specie wuld be separated by / \n # like tritici/obelisca and will break the file name\n filename = fileinfo.cache_filename(taxa.specie.replace(\"/\", \"_\"))\n soup = RequestsHandler.get_soup(taxa.links[0], filename)\n children = soup.find(\"section\", id=\"classification\")\n \n print(taxa.links[0])\n \n if children:\n \n dts = children.find_all(\"dt\")\n dds = children.find_all(\"dd\")\n \n html_parts = zip(dts, dds)\n \n # find the subspecie and append the eventual subspecie name and author\n \n for dth, ddh in html_parts:\n if dth.text == \"subspecies\":\n staxa = Taxa.Taxa()\n staxa.copy_taxonomy(taxa)\n \n subspecie_element = NBNElement(dth, ddh, fileinfo)\n staxa.author = subspecie_element.get_author()\n \n name_text = subspecie_element.get_name()\n \n # clean the subsp. mention that sometimes appears\n name_text.replace(\"subsp. \", \"\")\n \n # select the subspecie name\n staxa.subspecie = name_text.split(\" \")[2]\n \n staxa.rank = Taxa.Taxa.rank_subspecie\n staxa.links.append(specie.get_link())\n staxa.source = \"n\"\n \n species_list.append(staxa)\n \n \n pwheel.end()\n \n logger.log_short_report(f\"Genus retrived: {len(genus_list)} Species retrived: {len(species_list)}\")\n \n return genus_list, species_list\n\n\nif __name__ == \"__main__\":\n \n base_folder = \"./Tests/test_NBN\"\n family_name = \"Mycetophilidae\"\n \n fi = FileInfo.FileInfo(base_folder, \"nbn\", family_name)\n \n logger.set_run_log_filename(fi.name_only(\"test_log_myceto\"))\n \n genus_list, specie_list = generate_lists(family_name, fi)\n \n print(\"{:-^79}\".format(\" GENERA \"))\n print(\"rank family subfamily tribe genus specie subspecie author\")\n for genus in genus_list:\n genus.print_extended()\n\n print(\"{:-^79}\".format(\" SPECIES (first 50) \")) \n for specie in specie_list[:50]:\n print(specie)\n \n \n\n \n \n \n \n \n \n \n ","sub_path":"ParseNBN.py","file_name":"ParseNBN.py","file_ext":"py","file_size_in_byte":12317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"367926259","text":"from copy import deepcopy\n\nfrom Bio import Phylo\nfrom termcolor import colored\n\n# global variables\nsubtree_otts = [['ott304358', 'Eukaryota'], ['ott361838', 'Chloroplastida'],\n ['ott691846', 'Metazoa'], ['ott395057', 'Nematoda'], ['ott801601', 'Vertebrata'],\n ['ott229562', 'Tetrapoda'], ['ott244265', 'Mammalia'], ['ott913935', 'Primates'],\n ['ott770311', 'Hominidae'], ['ott352914', 'Fungi'], ['ott844192', 'Bacteria'],\n ['ott996421', 'Archaea']]\nindex = 0\nnr_internal_nodes = 0\nnr_leaf_nodes = 0\n\ndef main():\n path_tree = \"../data/opentree9.1_tree/labelled_supertree/labelled_supertree.tre\"\n\n print(colored(\"---------------- read tree ----------------\", \"green\"))\n tree = Phylo.read(path_tree, 'newick')\n \n print(colored(\"---------------- find subtrees ----------------\", \"green\"))\n find_subtree(tree.clade)\n return\n\ndef find_subtree(subtree):\n global subtree_otts\n global index\n global nr_internal_nodes\n global nr_leaf_nodes\n if len(subtree_otts) == 0:\n return\n if not subtree.is_terminal():\n for item in subtree_otts:\n if subtree.name == item[0]:\n new_subtree = deepcopy(subtree)\n new_subtree = prepare_subtree(new_subtree)\n index = 0\n subtree_path = '../data/subtree/' + item[1] + '.tre'\n print(\"save tree at\", subtree_path)\n Phylo.write(new_subtree, subtree_path, 'newick')\n print(item[1], 'has', nr_internal_nodes, 'internal nodes and', nr_leaf_nodes, 'leaf_nodes')\n nr_internal_nodes = 0\n nr_leaf_nodes = 0\n subtree_otts.remove(item)\n for clade in subtree.clades:\n find_subtree(clade)\n return\n\ndef prepare_subtree(subtree):\n global index\n global nr_internal_nodes\n global nr_leaf_nodes\n # For the quicker finding of the element in the nodelist of the accociated node.\n subtree.name = subtree.name + \"$\" + str(index)\n index += 1\n if subtree.is_terminal():\n nr_leaf_nodes += 1\n else:\n nr_internal_nodes += 1\n for clade in subtree.clades:\n clade = prepare_subtree(clade)\n return subtree\n \nmain()\n","sub_path":"metadata/build_subtrees.py","file_name":"build_subtrees.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"275131756","text":"import tensorflow as tf\r\nimport numpy as np\r\nimport cv2\r\nimport os\r\n\r\nfrom efficientnet_lite import efficientnet_lite\r\n\r\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\r\n\r\nGPU_ID = '0'\r\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = str(GPU_ID)\r\n\r\n\r\ncifar10 = tf.keras.datasets.cifar10\r\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\r\n\r\n\r\nx_train = x_train.astype('float32')\r\nx_test = x_test.astype('float32')\r\n\r\nx_train = x_train/127.5 - 1\r\nx_test = x_test/127.5 - 1\r\n\r\ny_train = tf.keras.utils.to_categorical(y_train, 10)\r\ny_test = tf.keras.utils.to_categorical(y_test, 10)\r\n\r\nmodel = efficientnet_lite(input_shape=(32, 32, 3), alpha=1, classes=10)\r\nmodel.summary()\r\n\r\nmodel.compile(\r\n loss='categorical_crossentropy',\r\n optimizer='adam',\r\n metrics=['accuracy']\r\n)\r\n\r\nmodel.fit(\r\n x_train,\r\n y_train,\r\n batch_size=32,\r\n validation_data=(x_test, y_test),\r\n epochs=20,\r\n verbose=1\r\n)\r\n\r\nscores = model.evaluate(x_test, y_test, verbose=1)\r\nprint('Test loss:', scores[0])\r\nprint('Test accuracy:', scores[1])\r\n","sub_path":"cifar10.py","file_name":"cifar10.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"512739882","text":"import pandas as pd\nimport numpy as np\nimport os\nimport csv\nimport time\nimport sys \nimport xlrd\nfrom sklearn.cluster import KMeans\nfrom sklearn.cluster import AgglomerativeClustering\n\nfile_social_data = '../../data/social/PIBMunicipal_2010.csv'\ndf_social = pd.read_csv(file_social_data, delimiter=';', decimal=',')\ndolar = 3.97\nhigh_gdp = 16000\nlow_gdp = 4000\n\ndef remove_accents(a):\n return unidecode.unidecode(a.decode('utf-8'))\n\ndef formatting_data(df):\n\tdf['CITY'] = df['CITY'].str.normalize('NFKD').str.encode('ascii', errors='ignore').str.decode('utf-8')\n\tdf['CITY'] = map(lambda x: str(x).upper(), df['CITY'])\n\treturn df\n\ndef scorer_GDP(df_GDP):\n\tdf_GDP['CLASS'] = ''\n\tfor index, row in df_GDP.iterrows():\n\t\tper_capita = row['PER CAPITA']\n\t\tif per_capita >= (dolar*high_gdp):\n\t\t\tdf_GDP.set_value(index,'CLASS',3)\n\t\telif per_capita > (dolar*low_gdp) and per_capita < (dolar*high_gdp): \n\t\t\tdf_GDP.set_value(index,'CLASS',2)\n\t\telse:\n\t\t\tdf_GDP.set_value(index,'CLASS',1)\n\n\tdf_GDP.to_csv('../../data/scored_GDP.csv', decimal=',', sep=';', encoding='utf-8')\n\ndef scorer_kmeans(df):\n\tX = df['PER CAPITA'].values\n\tX = X.reshape(-1, 1)\n\n\tkmeans = KMeans(n_clusters=3)\n\tkmeans.fit(X)\n\ty_kmeans = kmeans.predict(X)\n\ty_kmeans = y_kmeans.reshape(-1, 1)\n\tdf2 = pd.DataFrame(y_kmeans, columns=['CLASS']) \n\tfor index, row in df2.iterrows():\n\t\tdf2.set_value(index,'CLASS',row['CLASS']+1)\n\n\tdf = df.join(df2)\n\n\tdf.to_csv('../../data/scored_KMMEANS.csv', decimal=',', sep=';', encoding='utf-8')\n\nif __name__ == '__main__':\n\t\n\t# bibliograph: \n\t#\thttp://www.ipea.gov.br/ipeageo/bases.html\n\t#\tftp://ftp.ibge.gov.br/Pib_Municipios/2010_2013/xls/\n\t#\tused class\n\t#\thttps://pt.wikipedia.org/wiki/Lista_de_munic%C3%ADpios_de_S%C3%A3o_Paulo_por_IDH-M\n\n\tdf_social = formatting_data(df_social)\n\n\tscorer_GDP(df_social)\n\tscorer_kmeans(df_social)","sub_path":"Python/helpers/2_social_csv_organizer.py","file_name":"2_social_csv_organizer.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"248428063","text":"#!/usr/bin/env python\n# _*_coding:utf-8_*_\n# Author: create by yang.hong\n# Time: 2018-09-11 9:14\n\nimport redisPubSubCluster\n\n# 创建一个连接redis的对象(使用发布与订阅模式的redis对象)\nr = redisPubSubCluster.RedisPubSubHelper()\n\n# 指定订阅频道\ndata = r.subscribe('NGINX_1B1_COPY_REDIS_KEY')\n\n# 接收频道中的内容,代码会阻塞到这里,直到收到消息\nprint(data.parse_response())","sub_path":"devops/redis-api/redisPubSubCluster/listenRedisCluster.py","file_name":"listenRedisCluster.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"372944167","text":"\"\"\"\n numpy和torch对比\n\"\"\"\n\nimport torch\nimport numpy as np\n\n# 新建一个numpy数组,[[0,1,2],[3,4,5]]\nnp_data = np.arange(6).reshape((2, 3))\ntorch_data = torch.from_numpy(np_data)\ntensor2array = torch_data.numpy()\n\nprint(\n '\\nnumpy:', np_data,\n '\\ntorch', torch_data,\n '\\ntensor2array', tensor2array,\n)\n\n\n# abs\ndata = [[-1, -2], [1, 2]]\ntensor = torch.FloatTensor(data) # 32bit\n\nprint(\n '\\nnumpy:', np.matmul(data, data), # data.dot(data) 结果相同\n '\\ntorch:', torch.mm(tensor, tensor) # tensor.dot(tensor) 点乘相加\n)\n","sub_path":"python/pytorch_test/nump_torch.py","file_name":"nump_torch.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"18922309","text":"import numpy as np\nimport json\n\nwith open('model_parameters.json', 'r') as file:\n params = json.loads(file.read())\n \ndef C_an(xi, tau, r):\n # note that tau = D t / xb ** 2, where t is the time\n Cb = params['bulkConcentration']\n D = params['diffusionCoefficientCu']#Diffusion Coefficient\n d = 1e-9 #Laminar flow sheet\n totalA = 0\n totalB = 0\n tolMax = 1e-10 \n tolMin = tolMax*1e-2\n m = 0\n cond = True\n previo = 10 * np.ones(len(xi))\n \n while(cond):\n Am = ((-1) ** m ) / ( 2 * m + 1 ) * np.exp( - ( ( 2 * m + 1 ) * ( np.pi / 2 ) ) ** 2 * tau ) * np.cos( (2 * m + 1) * np.pi / 2 * xi )\n Bm = 1 / ( 2 * m + 1 ) ** 2 * np.exp( - ( ( 2 * m + 1 ) * ( np.pi / 2 ) ) ** 2 * tau ) * np.cos( (2 * m + 1) * np.pi / 2 * xi )\n actualA = Am\n actualB = Bm\n totalA += actualA\n totalB += actualB\n m = m + 1\n \n if (m > 1):\n contrib = (actualA)/previo\n for i in range(0, len(xi)-1):\n# if ( np.abs(contrib[i]) > tolMin):\n# cond = True\n if ( np.abs(max(contrib)) < tolMax):\n \n cond = False\n \n previoA = actualA\n print(\"Series truncation at n = \" + str(m) + \" with maximnum local error \" + str(np.amax(np.abs(contrib))) + \"%\")\n return Cb - ( (4 * Cb / np.pi ) * totalA + ( r * d / D ) * (np.ones(len(xi)) - xi - ( 8 / np.pi ** 2 ) * totalB )) \n\n\n\n\n\n\n\n","sub_path":"thesis/chapters/ch03/code/.ipynb_checkpoints/analyticDiffusionReaction-checkpoint.py","file_name":"analyticDiffusionReaction-checkpoint.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"180574543","text":"from __future__ import absolute_import\n\"\"\"proc URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.8/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Add an import: from blog import urls as blog_urls\n 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))\n\"\"\"\nfrom django.conf.urls import include, url\nfrom django.contrib import admin\nfrom tasks import views\n\nurlpatterns = [\n url(r'^admin/', include(admin.site.urls)),\n url(r'^options/', views.options),\n url(r'^check/(?P.+?)/', views.check),\n url(r'^available/', views.available),\n url(r'^run/(?P.+?)/', views.run),\n url(r'^status/(?P.+?)/', views.status),\n url(r'^finished/(?P.+?)/', views.finished),\n url(r'^info/(?P.+?)/', views.info),\n url(r'^projects/', views.projects),\n url(r'^results/', views.results),\n url(r'^projects/', views.projects),\n]\n","sub_path":"tasks/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"23062303","text":"# ----------------------------------------------------------------------------\n# Copyright (c) 2017, QIIME 2 development team.\n#\n# Distributed under the terms of the Modified BSD License.\n#\n# The full license is in the file LICENSE, distributed with this software.\n# ----------------------------------------------------------------------------\n\nimport unittest\n\nimport pandas as pd\nimport numpy as np\nimport skbio\nimport qiime2\n\nfrom q2_metadata import distance_matrix\n\n\nclass DistanceMatrixTests(unittest.TestCase):\n def test_int_category(self):\n md = qiime2.MetadataCategory(\n pd.Series([1, 2, 3], name='number',\n index=['sample1', 'sample2', 'sample3']))\n exp = skbio.DistanceMatrix([[0, 1, 2],\n [1, 0, 1],\n [2, 1, 0]],\n ids=['sample1', 'sample2', 'sample3'])\n\n obs = distance_matrix(md)\n\n self.assertEqual(exp, obs)\n\n def test_float_category(self):\n md = qiime2.MetadataCategory(\n pd.Series([1.5, 2.0, 3.0], name='number',\n index=['sample1', 'sample2', 'sample3']))\n exp = skbio.DistanceMatrix([[0.0, 0.5, 1.5],\n [0.5, 0.0, 1.0],\n [1.5, 1.0, 0.0]],\n ids=['sample1', 'sample2', 'sample3'])\n obs = distance_matrix(md)\n\n self.assertEqual(exp, obs)\n\n def test_one_sample(self):\n md = qiime2.MetadataCategory(\n pd.Series([1.5], name='number', index=['sample1']))\n exp = skbio.DistanceMatrix([[0.0]],\n ids=['sample1'])\n\n obs = distance_matrix(md)\n\n self.assertEqual(exp, obs)\n\n def test_str_casting(self):\n md = qiime2.MetadataCategory(\n pd.Series(['1', '2', '3', '4'], name='number',\n index=['sample1', 'sample2', 'sample3', 'sample4']))\n exp = skbio.DistanceMatrix([[0.0, 1.0, 2.0, 3.0],\n [1.0, 0.0, 1.0, 2.0],\n [2.0, 1.0, 0.0, 1.0],\n [3.0, 2.0, 1.0, 0.0]],\n ids=['sample1', 'sample2', 'sample3',\n 'sample4'])\n\n obs = distance_matrix(md)\n\n self.assertEqual(exp, obs)\n\n def test_non_numeric_category(self):\n md = qiime2.MetadataCategory(\n pd.Series(['x1', 'x2', '3', '4'], name='number',\n index=['sample1', 'sample2', 'sample3', 'sample4']))\n\n with self.assertRaisesRegex(ValueError,\n 'non-numeric values.*\\n\\n.*x1'):\n distance_matrix(md)\n\n def test_missing_values(self):\n md = qiime2.MetadataCategory(\n pd.Series([1.0, 2.0, np.nan, 4.0], name='number',\n index=['sample1', 'sample2', 'sample3', 'sample4']))\n\n with self.assertRaisesRegex(ValueError, 'missing values'):\n distance_matrix(md)\n\n def test_empty_metadata_category(self):\n md = qiime2.MetadataCategory(pd.Series([], name='number', index=[]))\n\n with self.assertRaisesRegex(ValueError, 'metadata category.*empty'):\n distance_matrix(md)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"q2_metadata/tests/test_distance.py","file_name":"test_distance.py","file_ext":"py","file_size_in_byte":3376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"77721264","text":"import gzip\nfrom collections import defaultdict\nimport math\nimport numpy\nimport urllib\nimport scipy.optimize\nimport random\nimport json\nfrom sklearn.metrics import accuracy_score\n\ndef readGz(f):\n for l in gzip.open(f):\n yield eval(l)\n\n\ndef diff_gender_clothing(user, item):\n clothing = 'Clothing, Shoes & Jewelry'\n if user not in I_u or item not in U_i:\n return False \n item_cw = category_words(U_i[item][0]['categories'])\n if clothing in item_cw:\n for i in I_u[user]:\n i_cw = category_words(i['categories'])\n if clothing not in i_cw:\n continue\n if ('Men' in i_cw and 'Women' in item_cw) or ('Women' in i_cw and 'Men' in item_cw):\n return True\n return False\n\ndef category_words(category):\n return set([word for subcategory in category for word in subcategory])\n\ndef pearson_item(i1, i2):\n R_i1_avg = numpy.mean([u['rating'] for u in U_i[i1]])\n R_i2_avg = numpy.mean([u['rating'] for u in U_i[i2]])\n R_intersection = [{'i1': u['rating'], 'i2': v['rating']} for u in U_i[i1] for v in U_i[i2] if u['reviewerID'] == v['reviewerID']]\n numerator = (sum([(r['i1'] - R_i1_avg) * (r['i2'] - R_i2_avg) for r in R_intersection])) * 1.0\n denominator = (sum([(r['i1'] - R_i1_avg) ** 2 for r in R_intersection]) * sum([(r['i2'] - R_i2_avg) ** 2 for r in R_intersection])) ** 0.5\n return 0.0 if denominator == 0.0 else numerator / denominator \n\ndef pearson(user, item):\n if user not in I_u or item not in U_i:\n return True \n for i in I_u[user]:\n if pearson_item(i['itemID'], item) > 0.5:\n return True\n return False\n\n# Classification Accuracy\n\n### Purchasing baseline: just rank which items are popular and which are not, and return '1' if an item is among the top-ranked\n\nitemCount = defaultdict(int)\nuserCount = defaultdict(int)\nI_u = {k:[] for k in range(794768)}\nU_i = {k:[] for k in range(244412)}\ntotalPurchases = 0\n\n\nfor l in readGz(\"train.json.gz\"):\n user,item,category = l['reviewerID'],l['itemID'],l['categories']\n itemCount[item] += 1\n totalPurchases += 1\n # Figure out how active a user is.\n userCount[user] += 1\n if item not in U_i:\n U_i[item] = [l]\n U_i[item].append(l)\n if user not in I_u:\n I_u[user] = [l]\n I_u[user].append(l)\n\n\nmostPopular = [(itemCount[x], x) for x in itemCount]\nmostPopular.sort()\nmostPopular.reverse()\n\nmostActive = [(userCount[x],x) for x in userCount]\nmostActive.sort()\nmostActive.reverse()\n\nreturn1 = set()\ncount = 0\nfor ic, i in mostPopular:\n count += ic\n return1.add(i)\n if count > (totalPurchases*2)/3: break\n\nreturn2 = set()\nactive = 0\nfor ic, i in mostActive:\n active += ic\n return2.add(i)\n if active > (totalPurchases*1)/12: break\n\npredictions = open(\"predictions_Purchase.txt\", 'w')\nfor l in open(\"pairs_Purchase.txt\"):\n if l.startswith(\"userID\"):\n #header\n predictions.write(l)\n continue\n u,i = l.strip().split('-')\n if pearson(u,i):\n if diff_gender_clothing(u, i):\n predictions.write(u + '-' + i + \",0\\n\")\n else:\n if i in return1 or u in return2:\n predictions.write(u + '-' + i + \",1\\n\")\n else:\n predictions.write(u + '-' + i + \",0\\n\")\n else:\n predictions.write(u + '-' + i + \",0\\n\")\n\npredictions.close()\n","sub_path":"assignment1/task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":3174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"154278165","text":"#!/usr/bin/env python\n\nimport rospy\nimport numpy as np\nimport cv2\nimport os\nimport tf2_ros\nimport datetime\nimport json\nfrom std_srvs.srv import Trigger, TriggerResponse\nfrom rospy_message_converter import message_converter\n\nimport miro_teach_repeat.image_processing as image_processing\nfrom miro_teach_repeat.srv import SaveImageAndPose, SaveImageAndPoseResponse\n\nclass data_save:\n\n\tdef __init__(self):\n\t\tself.setup_parameters()\n\t\tself.setup_publishers()\n\t\tself.setup_subscribers()\n\n\tdef setup_parameters(self):\n\t\tself.ready = not rospy.get_param('/wait_for_ready', False)\n\t\tself.save_id = 0\n\t\tself.save_dir = os.path.expanduser(rospy.get_param('~save_dir', '~/miro/data'))\n\t\tself.save_full_res_images = rospy.get_param('/save_full_res_images', True)\n\t\tself.save_gt_data = rospy.get_param('/save_gt_data', True)\n\t\tself.timestamp_dir = rospy.get_param('~timestamp_folder', False)\n\t\tif self.save_dir[-1] != '/':\n\t\t\tself.save_dir += '/'\n\t\tif self.timestamp_dir:\n\t\t\tself.save_dir += datetime.datetime.now().strftime('%Y-%m-%d_%H:%M:%S/')\n\t\tif not os.path.isdir(self.save_dir):\n\t\t\tos.makedirs(self.save_dir)\n\t\tif self.save_full_res_images:\n\t\t\tif not os.path.isdir(self.save_dir+'full/'):\n\t\t\t\tos.makedirs(self.save_dir+'full/')\n\t\tif not os.path.isdir(self.save_dir+'norm/'):\n\t\t\tos.makedirs(self.save_dir+'norm/')\n\t\tself.resize = image_processing.make_size(height=rospy.get_param('/image_resize_height', None), width=rospy.get_param('/image_resize_width', None))\n\t\tif self.resize[0] is None and self.resize[1] is None:\n\t\t\tself.resize = None\n\n\t\tself.patch_size = image_processing.parse_patch_size_parameter(rospy.get_param('/patch_size', (9,9)))\n\n\t\tself.save_params()\n\n\tdef setup_publishers(self):\n\t\tpass\n\n\tdef setup_subscribers(self):\n\t\tif not self.ready:\n\t\t\tself.srv_ready = rospy.Service('ready_data_save', Trigger, self.on_ready)\n\t\tself.tfBuffer = tf2_ros.Buffer()\n\t\tself.tfListener = tf2_ros.TransformListener(self.tfBuffer)\n\t\trospy.sleep(0.2)\n\t\tself.service = rospy.Service('save_image_pose', SaveImageAndPose, self.process_image_and_pose)\n\n\tdef save_params(self):\n\t\tparams = {\n\t\t\t'resize': self.resize,\n\t\t\t'patch_size': self.patch_size\n\t\t}\n\t\twith open(self.save_dir + 'params.txt', 'w') as params_file:\n\t\t\tparams_file.write(json.dumps(params))\n\n\tdef on_ready(self, srv):\n\t\tif not self.ready:\n\t\t\tself.ready = True\n\t\t\treturn TriggerResponse(success=True)\n\t\telse:\n\t\t\treturn TriggerResponse(success=False, message=\"Data save already started.\")\n\n\tdef process_image_and_pose(self, request):\n\t\tif self.ready:\n\t\t\timage = image_processing.msg_to_image(request.image)\n\t\t\tpose = request.pose\n\t\t\tid = \"%06d\" % (self.save_id)\n\t\t\tnormalised_image = image_processing.patch_normalise_image(image, self.patch_size, resize=self.resize)\n\t\t\tmessage_as_text = json.dumps(message_converter.convert_ros_message_to_dictionary(pose))\n\n\t\t\tif self.save_gt_data:\n\t\t\t\ttry:\n\t\t\t\t\ttrans = self.tfBuffer.lookup_transform('map', 'base_link', rospy.Time())\n\t\t\t\t\ttrans_as_text = json.dumps(message_converter.convert_ros_message_to_dictionary(trans))\n\t\t\t\t\twith open(self.save_dir + id + '_map_to_base_link.txt', 'w') as pose_file:\n\t\t\t\t\t\tpose_file.write(trans_as_text)\n\t\t\t\texcept (tf2_ros.LookupException, tf2_ros.ConnectivityException, tf2_ros.ExtrapolationException):\n\t\t\t\t\tprint('Could not lookup transform from /map to /base_link')\n\t\t\t\t\tpass\n\t\t\t\n\t\t\tif self.save_full_res_images:\n\t\t\t\tcv2.imwrite(self.save_dir+'full/'+id+'.png', image)\n\t\t\tcv2.imwrite(self.save_dir+'norm/'+id+'.png', np.uint8(255.0 * (1 + normalised_image) / 2.0))\n\t\t\twith open(self.save_dir+id+'_pose.txt', 'w') as pose_file:\n\t\t\t\tpose_file.write(message_as_text)\n\t\t\tself.save_id += 1\n\t\t\tprint('saved frame %d' % self.save_id)\n\t\t\treturn SaveImageAndPoseResponse(success=True)\n\n\nif __name__ == \"__main__\":\n\trospy.init_node(\"data_save\")\n\tsaver = data_save()\n\trospy.spin()\n","sub_path":"nodes/data_save.py","file_name":"data_save.py","file_ext":"py","file_size_in_byte":3800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"250223171","text":"import html\nimport random\nimport re\n\nimport numpy as np\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\nfrom common.client import AnimeApiClient\n\nrandom.seed(12345)\n\n\nclass DatasetGenerator:\n def __init__(self, api_client: AnimeApiClient):\n self.api_client = api_client\n self.anime_lists = {\n 'training': [],\n 'validation': [],\n }\n self.vectorizer = None\n self.inverse_vectorizer = None\n self.selector = None\n self.dataset = {\n 'training': {\n 'ids': [],\n 'data': np.array([]),\n 'labels': [],\n },\n 'validation': {\n 'ids': [],\n 'data': np.array([]),\n 'labels': [],\n }\n }\n self.metadata = {}\n\n def get_vectorized_dataset(self, set_name, max_df=0.4, min_df=4):\n self.dataset[set_name]['data'] = self._vectorize_synopses(\n set_name=set_name,\n synopses=[anime['sanitized_synopsis'] for anime in self.anime_lists[set_name]],\n max_df=max_df,\n min_df=min_df)\n return self.dataset[set_name]\n\n def load_dataset(self, begin, end, validation_split=0.2):\n imported_anime = self.api_client.get_anime_range(begin, end)\n random.shuffle(imported_anime)\n self.metadata['total_num_media_queried'] = len(imported_anime)\n pruned_imported_anime = [\n sanitized_anime\n for sanitized_anime\n in (\n self._sanitize_synopsis(anime)\n for anime in imported_anime\n )\n if sanitized_anime['sanitized_synopsis_length'] > 10\n ]\n total_synopsis_length = sum(anime['sanitized_synopsis_length'] for anime in pruned_imported_anime)\n self.anime_lists['training'], self.anime_lists['validation'] = self._train_val_split(data=pruned_imported_anime, validation_split=validation_split)\n for set_name in ['training', 'validation']:\n self.dataset[set_name]['ids'] = [anime['id'] for anime in self.anime_lists[set_name]]\n self.dataset[set_name]['labels'] = [self._is_lewd(anime) for anime in self.anime_lists[set_name]]\n self.metadata['num_media_in_{}_set'.format(set_name)] = len(self.dataset[set_name]['ids'])\n self.metadata['num_lewd_media_in_{}_set'.format(set_name)] = sum(self.dataset[set_name]['labels'])\n self.metadata['total_num_media_kept'] = len(pruned_imported_anime)\n self.metadata['total_num_media_discarded'] = self.metadata['total_num_media_queried'] - self.metadata['total_num_media_kept']\n self.metadata['average_synopsis_length'] = total_synopsis_length / self.metadata['total_num_media_kept']\n self.metadata['num_media_in_validation_set'] = len(self.dataset['validation']['ids'])\n return self.metadata\n\n def _vectorize_synopses(self, synopses, set_name, max_df, min_df):\n if not self.vectorizer:\n self.vectorizer = TfidfVectorizer(**{\n 'ngram_range': (1, 2),\n 'strip_accents': 'unicode',\n 'decode_error': 'replace',\n 'analyzer': 'word',\n 'max_df': max_df,\n 'min_df': min_df,\n })\n if set_name == 'training':\n self.vectorizer.fit(synopses)\n self.dataset[set_name]['data'] = self.vectorizer.transform(synopses).astype('float32')\n self.metadata['num_tokens'] = self.dataset[set_name]['data'].shape[1]\n self.metadata['{}_set_data_vector_shape'.format(set_name)] = self.dataset[set_name]['data'].shape\n return self.dataset[set_name]['data']\n\n @staticmethod\n def _train_val_split(data, validation_split):\n return data[int(round(len(data) * validation_split)):], data[:int(round(len(data) * validation_split))]\n\n def vector_to_ngram(self, index):\n if not self.inverse_vectorizer:\n self.inverse_vectorizer = {v: k for k, v in self.vectorizer.vocabulary_.items()}\n return self.inverse_vectorizer[index]\n\n @staticmethod\n def _is_lewd(anime):\n return bool(anime['is_nsfw'] or \"Ecchi\" in anime['tags'])\n\n @staticmethod\n def _sanitize_synopsis(anime):\n if not anime['synopsis']:\n anime['sanitized_synopsis'] = ''\n anime['sanitized_synopsis_length'] = 0\n return anime\n anime['sanitized_synopsis'] = anime['synopsis'].strip()\n anime['sanitized_synopsis'] = html.unescape(anime['sanitized_synopsis'])\n # Remove URLs\n anime['sanitized_synopsis'] = re.sub(r'https?:\\/\\/(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b([-a-zA-Z0-9()@:%_\\+.~#?&//=]*)', '', anime['sanitized_synopsis'])\n # Remove html elements\n anime['sanitized_synopsis'] = re.sub(r'<[\\w\\/=\"!\\s]+?>', '', anime['sanitized_synopsis'])\n # If the line contains source and a colon, delete source and everything after, as well as parentheses if they exist\n anime['sanitized_synopsis'] = re.sub(r'[\\[\\(]?\\s*Source?\\s*:.{0,40}\\s*$', '', anime['sanitized_synopsis'], flags=re.IGNORECASE | re.MULTILINE)\n # If the line contains source and a parentheses, delete it and everything after\n anime['sanitized_synopsis'] = re.sub(r'[\\[\\(]\\s*Source?.{0,40}\\s*$', '', anime['sanitized_synopsis'], flags=re.IGNORECASE | re.MULTILINE)\n # If the line contains from and a weird character in front of it, delete from and everything after\n anime['sanitized_synopsis'] = re.sub(r'[~\\[\\(]\\s*from.{0,40}\\s*$', '', anime['sanitized_synopsis'], flags=re.IGNORECASE | re.MULTILINE)\n anime['sanitized_synopsis'] = re.sub(r'\\'’', '', anime['sanitized_synopsis'])\n anime['sanitized_synopsis'] = re.sub(r'[^a-zA-Z]', ' ', anime['sanitized_synopsis']).lower().strip()\n anime['sanitized_synopsis_length'] = len(anime['sanitized_synopsis'].split())\n return anime\n","sub_path":"common/dataset_generator.py","file_name":"dataset_generator.py","file_ext":"py","file_size_in_byte":5955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"40322563","text":"#!/usr/bin/python3\n\nfrom flask import Flask\nfrom flask import request\nfrom werkzeug.serving import make_server\nimport logging\nfrom fabric import Connection\nfrom fabric import ThreadingGroup\nimport threading\nimport time\nimport signal\nimport sys\nimport os\n\nlog = logging.getLogger('werkzeug')\nlog.setLevel(logging.ERROR)\n\nos.system('/home/img/optimus-host-module/reload.sh')\nos.system('sudo /usr/local/bin/fpgaconf -b 0x5e /home/img/bitstream/mux8_membench.gbs')\nos.system('/home/img/optimus-host-module/reload.sh')\n\nprint(\"reconfiguration is done\")\n\nip_list = []\napp = Flask(__name__)\n\n@app.route('/ping')\ndef ping():\n if (request.remote_addr in ip_list):\n return \"existed\"\n ip_list.append(request.remote_addr)\n return \"pong\"\n\n@app.route('/report', methods=['POST'])\ndef report():\n s = request.form.get('s')\n print(\"received from [\", request.remote_addr, \"]:\", s)\n return \"\"\n\nclass ServerThread(threading.Thread):\n def __init__(self, app):\n threading.Thread.__init__(self)\n self.srv = make_server('0.0.0.0', 5000, app)\n self.ctx = app.app_context()\n self.ctx.push()\n\n def run(self):\n print('starting server')\n self.srv.serve_forever()\n\n def shutdown(self):\n self.srv.shutdown()\n\ndef start_server():\n global server\n server = ServerThread(app)\n server.start()\n print('server started')\n\ndef stop_server():\n global server\n server.shutdown()\n\nstart_server()\n\ndef sigint_handler(sig, frame):\n stop_server()\n os.system('sudo pkill -9 qemu > /dev/null')\n sys.exit()\n\nsignal.signal(signal.SIGINT, sigint_handler)\n\nprint(\"Booting VM 0...\")\nos.system('bash /home/img/script/boot-vm.sh 0 > /dev/null 2> /dev/null &')\nprint(\"Booting VM 1...\")\nos.system('bash /home/img/script/boot-vm.sh 1 > /dev/null 2> /dev/null &')\n\nwhile True:\n time.sleep(1)\n if (len(ip_list) == 0):\n print(\"No received IP address, wait for booting...\")\n if (len(ip_list) == 1):\n print(\"Received IP addresses:\", ip_list, \"wait for the other to boot up...\")\n if (len(ip_list) == 2):\n print(\"Received IP addresses:\", ip_list, \"start running benchmark...\")\n break\n\nlogin_list = []\nfor ip in ip_list:\n login_list.append(\"root@\"+ip)\n\n\ncmd_tmpl = '''curl -F \"s=`/root/optimus-intel-fpga-bbb/samples/tutorial/vai_membench/sw/cci_membench_vai ${SIZE} 10000000 0 RD_VA WR_VA RDLINE_I WRLINE_I RAND RDCL1 2>/dev/null | grep \"RD thr\" | awk '{print $3 $4}'`\" http://fpga-skx:5000/report'''\n\nprint(\"\\n******************************** 1 VM: MemBench with 4096-page working set **************************************\")\nresult = Connection(login_list[0], connect_kwargs={\"password\": \"a\"}).run(cmd_tmpl.replace(\"${SIZE}\", \"4096\"), hide=True)\n\nprint(\"\\n*************************** 2 VMs: MemBench with 2048-page working set for each *********************************\")\nresult = ThreadingGroup(*login_list, connect_kwargs={\"password\": \"a\"}).run(cmd_tmpl.replace(\"${SIZE}\", \"2048\"), hide=True)\n\ninput('\\nPress ENTER to exit...')\nstop_server()\nos.system('sudo pkill -9 qemu > /dev/null')\n","sub_path":"optimus-scripts/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":3077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"159518819","text":"# your code goes here\n# cook your dish here\nimport math\n \ntestCaseCount = int(input())\n \nfinalPrime = []\n \ndef simplesieve(num):\n flist = []\n plist = {}\n plist = {x: 1 for x in range(2, num + 1)}\n #print(\"list is \", plist)\n b = int(num / 2) + 1\n for i in range(2, b):\n a = i\n c = int(num / i) + 1\n for x in range(a, c):\n p = a * x\n #print(\"p\", p)\n # if p in plist.keys():\n if plist[p] == 1: # if it is prime\n plist[p] = 0\n \n for k in plist:\n if plist[k] == 1:\n flist.append(k)\n return flist\n \ndef findPrime(lowerLim, upperLim):\n primelist = []\n if upperLim == 1:\n return primelist\n if lowerLim < 2:\n lowerLim = 2\n sqroot = int(math.sqrt(upperLim))\n # use sieve algo to find prime upto sqroot of upperlim\n primesieve = []\n primesieve = simplesieve(sqroot)\n #print(\"prime upto sqroot is\", primesieve)\n num_list = {x: 1 for x in range(lowerLim, upperLim + 1)}\n #print(\"numlist is\", num_list)\n for i in primesieve:\n if i < lowerLim:\n #print(\"in\")\n initPoint = int(lowerLim / i) * i\n else:\n initPoint = i\n #print(\"init is\", initPoint)\n if lowerLim == initPoint:\n for key in range(initPoint, upperLim + 1, i):\n num_list[initPoint] = 0\n initPoint = initPoint + i\n else:\n initPoint = initPoint + i\n for key in range(initPoint, upperLim + 1, i):\n num_list[initPoint] = 0\n initPoint = initPoint + i\n \n if lowerLim <= 2:\n num_list[2] = 1\n elif lowerLim == 3:\n num_list[3] = 1\n #print(\"final numlist is\", num_list)\n for k in num_list:\n if num_list[k] == 1:\n #print(\"prime is\", k)\n primelist.append(k)\n \n return primelist\n \n \nfor i in range(testCaseCount):\n limitArr = list(map(int,input().split()))\n lowerLim = limitArr[0]\n upperLim = limitArr[1]\n finalPrime = findPrime(lowerLim, upperLim)\n \n print(*finalPrime,sep=\"\\n\",end=\"\")\n if(i != (testCaseCount-1) and finalPrime != []):\n print(\"\\n\") \n","sub_path":"test_Prime.py","file_name":"test_Prime.py","file_ext":"py","file_size_in_byte":2235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"100058547","text":"import joblib\nimport pathlib\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.model_selection import GridSearchCV\n\ndef model(x_train, y_train):\n print(\"Grid search: finding best hyperparameter for DecisionTreeClassifier...\")\n # Grid search: finding best hyperparameters\n parameters = {\n 'criterion': ['gini', 'entropy'],\n 'splitter': ['best', 'random'],\n 'max_depth': [None, 2, 4, 8, 10]\n }\n clf = DecisionTreeClassifier()\n grid_cv = GridSearchCV(clf, parameters, cv=10, n_jobs=-1)\n grid_cv.fit(x_train, y_train)\n print(f\"Parameters of best model: {grid_cv.best_params_}\")\n print(f\"Score of best model: {grid_cv.best_score_}\")\n\n # Use best hyperparameters to train model\n clf = DecisionTreeClassifier(criterion=grid_cv.best_params_[\"criterion\"], max_depth=grid_cv.best_params_[\"max_depth\"]) \n clf.fit(x_train, y_train)\n\n model_name = \"DecisionTreeClassifier\" \n joblib.dump(clf, pathlib.Path(__file__).parent.joinpath(\"trained_model_dumps\").joinpath(model_name + \".model\").resolve())\n return clf","sub_path":"src/04a-training/src/python/models/DecisionTreeClassifier.py","file_name":"DecisionTreeClassifier.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"132736361","text":"from tkinter import *\nfrom tkinter import font\n\n\nclass point:\n def __init__(self, name, x=0, y=0, w=5, h=5, v=0):\n self.x = x\n self.y = y\n self.width = w\n self.height = h\n self.value = v\n self.name = name\n\n def getRect(self):\n return self.x - self.width, self.y - self.height, self.x + self.width, self.y + self.height\n\nclass GraphGUI:\n # global mailMarked\n\n def __init__(self, mailMarked):\n self.window = Tk()\n\n # window\n self.width = 800\n self.height = 600\n self.widthBorder = 100\n self.heightBorder = 100\n self.window.geometry(str(self.width) + 'x' + str(self.height))\n self.window.resizable(False, False)\n self.window.title('test')\n\n # canvas\n self.canvas = Canvas(self.window, relief='solid', bd=2, bg='white', width=self.width, height=self.height)\n self.canvas.pack()\n\n # font\n self.fontValue = font.Font(self.canvas, size=10, weight='bold', family='consolas')\n self.fontName = font.Font(self.canvas, size=20, weight='bold', family='consolas')\n\n # point\n self.points = [point('기술사'), point('기능장'), point('기사'), point('기능사')]\n self.size = 0\n self.maxValue = 0\n\n self.setPoint(mailMarked)\n self.drawGraph()\n\n self.window.mainloop()\n\n def setPoint(self, mailMarked):\n for mark in mailMarked:\n if mark.seriesCode == '01':\n self.points[0].value += 1\n elif mark.seriesCode == '02':\n self.points[1].value += 1\n elif mark.seriesCode == '03':\n self.points[2].value += 1\n elif mark.seriesCode == '04':\n self.points[3].value += 1\n\n for p in self.points:\n if p.value > 0:\n self.size += 1\n if p.value > self.maxValue:\n self.maxValue = p.value\n\n def drawGraph(self):\n\n idx = 0.5\n w = self.width - self.widthBorder\n h = self.height - self.heightBorder * 2\n for p in self.points:\n if p.value > 0:\n p.x = w / self.size * idx + self.widthBorder\n p.y = (1 - p.value / self.maxValue) * h + self.heightBorder + 50\n self.canvas.create_oval(p.getRect(), fill='red')\n self.canvas.create_text(p.x, p.y - 20, text=p.value, font=self.fontValue)\n self.canvas.create_text(p.x, self.height - self.heightBorder + 50, text=p.name, font=self.fontName)\n idx += 1\n self.canvas.create_rectangle(self.widthBorder, self.heightBorder, self.width,\n self.height - self.heightBorder)\n for i in range(self.maxValue):\n self.canvas.create_text(self.widthBorder // 2, i / self.maxValue * h + self.heightBorder + 50,\n text=self.maxValue - i, font=self.fontValue)\n self.canvas.create_rectangle(0, 0, self.width, self.heightBorder)\n self.canvas.create_text(self.width//2, self.heightBorder//2, text='북마크 된 정보 그래프', font=self.fontName)","sub_path":"program/GraphGUI.py","file_name":"GraphGUI.py","file_ext":"py","file_size_in_byte":3161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"98993066","text":"# coding=utf-8\nimport xml.parsers.expat\nimport os\nimport os.path\nfrom os.path import splitext\nimport sys\nimport shutil\n\n# 3 handler functions\ndef start_element(name, attrs):\n global STATES, TYPES, current_state_id, seeking_start_state, \\\n seeking_end_state, seeking_trans\n # print 'Start element:', name, attrs\n if name == \"state\":\n string = attrs['id']\n state_placeholder = [int(s) for s in string.split() if s.isdigit()]\n STATES += state_placeholder\n current_state_id = state_placeholder[0]\n if name == \"from\":\n seeking_start_state = True\n if name == \"to\":\n seeking_end_state = True\n if name == \"read\":\n seeking_trans = True\n if name == \"initial\":\n #print \"State #\", current_state_id,\"is an initial state\"\n TYPES[current_state_id] = [\"initial\"]\n if name == \"final\":\n # print \"State #\", current_state_id, \"is a final state\"\n if TYPES.has_key(current_state_id):\n TYPES[current_state_id] += [\"final\"]\n else:\n TYPES[current_state_id] = [\"final\"]\n\ndef end_element(name):\n # print 'End element:', name\n pass\n\ndef char_data(data):\n global TRANS, current_state_id, \\\n current_start_state, current_end_state, \\\n seeking_start_state, current_trans, seeking_trans, \\\n seeking_end_state\n\n data_without_space = data.strip()\n if len(data_without_space) > 0:\n state_desc = \"seeking_start_state\"\n if seeking_end_state: state_desc = \"seeking_end_state\"\n if seeking_trans: state_desc = \"seeking_trans\"\n #print 'Data: (', data, \") and state=\", state_desc\n pass\n\n if seeking_start_state:\n string = data_without_space\n state_placeholder = [int(s) for s in string.split() if s.isdigit()]\n current_start_state = state_placeholder[0]\n seeking_start_state = False\n\n if seeking_end_state:\n string = data_without_space\n state_placeholder = [int(s) for s in string.split() if s.isdigit()]\n current_end_state = state_placeholder[0]\n seeking_end_state = False\n\n if seeking_trans:\n string = data_without_space\n if string.strip() == '':\n this_trans = 'X'\n else:\n s = string.strip()\n this_trans = str(s)\n\n if (current_start_state,current_end_state) not in TRANS:\n TRANS[current_start_state,current_end_state] = [this_trans]\n else:\n TRANS[current_start_state,current_end_state] += [this_trans]\n seeking_trans = False\n\n\ndef TRANSprocessing():\n global TRANS, TRANS2\n TRANS2 = []\n for k in TRANS.iteritems():\n TRANS2.extend([k])\n\ndef takingInput(filename):\n global INPUTS,INPUTS2\n INPUTS2 = {}\n f = open(filename)\n L = f.readlines()\n for line in L:\n line = line.strip()\n pieces = line.split()\n if len(pieces)==1:\n if not pieces[0].isdigit():\n pieces = ['','reject']\n if len(pieces)==0:\n pieces = ['']\n INPUTS.extend([pieces])\n for i in range(len(INPUTS)):\n if len(INPUTS[i])<2:\n INPUTS2[INPUTS[i][0]] = True\n else:\n INPUTS2[INPUTS[i][0]] = False\n f.close()\n## print 'INPUTS are', INPUTS\n## print 'INPUTS2 are', INPUTS2\n\ndef stateTrans2(sState, inputstring):\n # BEENTO should store both the current state AND the inputstring.\n # so when it returns again, it'll def. be a loop.\n global BEENTO\n\n if (inputstring,sState) in BEENTO:\n return False # already been here!\n\n BEENTO[ (inputstring,sState) ] = True # now we've been here!\n\n if len(inputstring) == 0: # done!\n for k in range(len(TRANS2)):\n if TRANS2[k][0][0] == sState and TRANS2[k][1] == 'X':\n #print inputstring, 'current state', sState, TRANS2[k], TRANS2[k][1] == 'X'\n newState = TRANS2[k][0][1]\n #print inputstring, 'newState', newState, newState in TYPES, 'final' in TYPES[newState]\n if newState in TYPES and 'final' in TYPES[newState]:\n return True\n if sState in TYPES and 'final' in TYPES[sState]:\n return True\n\n\n # handle the lambdas\n N = len(TRANS2)\n for k in range(N):\n cur_trans = TRANS2[k]\n src, dst = cur_trans[0]\n trans_chars = cur_trans[1]\n\n if src != sState: continue # not the right start state\n\n if 'X' in trans_chars:\n s = stateTrans2(dst,inputstring)\n if s == True: return True\n\n if len(inputstring) > 0:\n next_char = inputstring[0]\n rest_of_input = inputstring[1:]\n\n N = len(TRANS2)\n for k in range(N):\n cur_trans = TRANS2[k]\n src, dst = cur_trans[0]\n trans_chars = cur_trans[1]\n\n if src != sState: continue # not the right start state\n\n if next_char in trans_chars:\n s = stateTrans2(dst,rest_of_input)\n if s == True: return True\n\n return False\n\ndef checker(filename):\n global BEENTO, TYPES\n count = 0\n takingInput(filename)\n # find initial state\n initial_state = None\n for k in TYPES.keys():\n if 'initial' in TYPES[k]:\n initial_state = k\n # run all of the inputs\n for i in INPUTS2.iterkeys():\n if initial_state == None:\n print_result_line( i, \"No initial state\", \" \" )\n BEENTO = {}\n result = stateTrans2(initial_state,i)\n expected = INPUTS2[i]\n print_result_line( i, result, expected )\n if INPUTS2[i] == result:\n count +=1\n num_inputs = len(INPUTS2)\n return count, num_inputs\n\ndef print_result_line( inpt, result, expected ):\n \"\"\" print a nice rendition of a result line \"\"\"\n if len(inpt) <= 7:\n input_w_tabs = inpt + \"\\t\\t\"\n else:\n input_w_tabs = inpt + \"\\t\"\n\n\n global of\n if of != None: # if there is an output file\n print >> of, input_w_tabs + str(result) + \"\\t\" + \\\n str(expected) + \"\\t\",\n if expected == result: print >> of, \"correct\"\n else: print >> of, \" *** INCORRECT *** \"\n else:\n print (input_w_tabs + str(result) + \"\\t\" + \\\n str(expected) + \"\\t\"),\n if expected == result: print (\"correct\")\n else: print( \" *** INCORRECT *** \" )\n\n\ndef overall(filename1,filename2):\n global INPUTS, TRANS, STATES, TYPES, TRANS2, TRANS3, BEENTO, count, success, \\\n current_state_id, current_start_state, current_end_state, seeking_start_state, \\\n seeking_end_state, seeking_trans, current_trans\n STATES = []\n TYPES = {}\n TRANS = {}\n TRANS2 = []\n TRANS3 = []\n INPUTS = []\n BEENTO = {}\n count = 0\n current_state_id = None\n current_start_state = None\n current_end_state = None\n seeking_start_state = False\n seeking_end_state = False\n seeking_trans = False\n current_trans = None\n\n p = xml.parsers.expat.ParserCreate()\n\n p.StartElementHandler = start_element\n p.EndElementHandler = end_element\n p.CharacterDataHandler = char_data\n\n f = open(filename1)\n p.ParseFile(f)\n f.close()\n\n TRANSprocessing()\n\n num_states = len(STATES)\n #print \"STATES are\", STATES\n #print \"TYPES are\", TYPES\n #print \"TRANS are\", TRANS\n #print \"processed TRANS are\", TRANS2\n score, num_inputs = checker(filename2)\n return (score,num_inputs,num_states)\n\n\n#\n# this is the test function...\n#\ndef test(student_file, tests_file, f):\n \"\"\" reads the jff student_file, e.g., part1.jff\n tests vs. the tests_file, e.g., part1.sols\n f, an open file indicating where\n the output file goes...\n \"\"\"\n print >> f, \"\\n+-+-+-+-+-+-+-+-+\\n\\n\"\n print >> f, \"\\n File to be tested:\\n\"\n print >> f, \"\\n \" + str(student_file) + \"\\n\"\n print >> f, \"Input\\t\\toutput\\texpected ~ result\"\n score, num_inputs, num_states = overall(student_file,tests_file)\n print >> f, \"\\nHere is the total # correct :\", score\n print >> f, \"Here is the total # of tests:\", num_inputs\n # Here is the # of states: num_states\n # each is out of 10 points, with -2 for each incorrect answer\n # So, if you miss five, no points remain!\n num_points_missed = min(10, 2*(num_inputs-score))\n print >> f, \"# of pts missed (out of 10):\", num_points_missed\n total_points = 10-num_points_missed\n print >> f, \"\\nTotal points for this problem :\", total_points\n print >> f, \"\\n\\n\\n\"\n return total_points\n\n\n\ndef tm_test(student_file, tests_file, f):\n \"\"\" reads the jff student_file, e.g., part1.jff\n tests vs. the tests_file, e.g., part1.sols\n f, an open file indicating where\n the output file goes...\n \"\"\"\n print >> f, \"\\n+-+-+-+-+-+-+-+-+\\n\\n\"\n print >> f, \"\\n File to be tested:\\n\"\n print >> f, \"\\n \" + str(student_file) + \"\\n\"\n print >> f, \"Input\\t\\toutput\\texpected ~ result\"\n score, num_inputs, num_states = tm_overall(student_file,tests_file)\n print >> f, \"\\nHere is the total # correct :\", score\n print >> f, \"Here is the total # of tests:\", num_inputs\n # Here is the # of states: num_states\n # each is out of 10 points, with -2 for each incorrect answer\n # So, if you miss five, no points remain!\n num_points_missed = min(10, 2*(num_inputs-score))\n print >> f, \"# of pts missed (out of 10):\", num_points_missed\n total_points = 10-num_points_missed\n print >> f, \"\\nTotal points for this problem :\", total_points\n print >> f, \"\\n\\n\\n\"\n return total_points\n\ndef testFileParser(filename):\n '''\n Takes a jflap *.soln file and parses the tests in the file\n '''\n global INPUTS, INPUTS2\n INPUTS = []\n INPUTS2 = {}\n\n takingInput(filename)\n\n names = []\n for n in INPUTS2.keys():\n if n == '':\n names.append('empty')\n else:\n names.append(n)\n\n return names\n\n\n\ndef currentRunTests(cmdPrefix, testFile, solution, timeLimit):\n # The students file is the basename of the test file with the jflap extension\n studentFile = splitext(testFile)[0] + '.jff'\n try:\n # The code below is modified from the overall function (defined above)\n global INPUTS, TRANS, STATES, TYPES, TRANS2, TRANS3, BEENTO, count, success, \\\n current_state_id, current_start_state, current_end_state, seeking_start_state, \\\n seeking_end_state, seeking_trans, current_trans\n # Reset globals so we can run multiple test files in sequence\n STATES = []\n TYPES = {}\n TRANS = {}\n TRANS2 = []\n TRANS3 = []\n INPUTS = []\n BEENTO = {}\n count = 0\n current_state_id = None\n current_start_state = None\n current_end_state = None\n seeking_start_state = False\n seeking_end_state = False\n seeking_trans = False\n current_trans = None\n\n p = xml.parsers.expat.ParserCreate()\n\n p.StartElementHandler = start_element\n p.EndElementHandler = end_element\n p.CharacterDataHandler = char_data\n\n # Using with syntax to parse the student's file\n with open(studentFile) as f:\n p.ParseFile(f)\n\n # Don't know what this does the original was not documented\n TRANSprocessing()\n\n # Get the number of states\n num_states = len(STATES)\n\n #\n # We deviate from overall here so that we can handle the output the way we\n # want to provide data back to the caller. This code is based on checker\n #\n\n # Load the inputs\n takingInput(solution)\n\n # Find the initial state\n initial_state = None\n for k in TYPES.keys():\n if 'initial' in TYPES[k]:\n initial_state = k\n\n if initial_state == None:\n # If we have no initial state, just die\n summary = {}\n summary['died'] = True\n summary['rawErr'] = \"Automaton is missing its initial state\"\n summary['timeout'] = False\n return summary, {}\n\n summary = {}\n summary['rawout'] = ''\n summary['rawErr'] = ''\n summary['failedTests'] = 0\n summary['totalTests'] = 0\n summary['timeout'] = False\n summary['died'] = False\n failedTests = {}\n\n for i in INPUTS2.iterkeys():\n BEENTO = {}\n result = stateTrans2(initial_state,i)\n summary['totalTests'] += 1\n if INPUTS2[i] != result:\n summary['failedTests'] += 1\n\n # create a failure report\n report = {}\n report['hint'] = \"Expected: \" + str(INPUTS2[i]) + \" Got: \" + str(result)\n if i == '':\n failedTests['empty'] = report\n else:\n failedTests[i] = report\n\n return summary, failedTests\n\n except Exception as e:\n # I don't know what errors the system can throw or how it throws them so I\n # will catch all errors and just report them rather than trying to be smart\n import traceback\n tb = traceback.format_exc()\n summary = {}\n summary['died'] = True\n summary['rawErr'] = str(tb)\n summary['timeout'] = False\n return summary, {}\n\ndef runTests(cmdPrefix, testFile, solution, timeLimit = None):\n # Get the result dictionaries from both systems.\n print(\"[JFLAP] Calling into current testing system...\")\n currentSummary, currentFailedTests = currentRunTests(cmdPrefix, testFile, solution, timeLimit)\n\n # Get the total number of tests from both systems.\n if not currentSummary['died']:\n currentTotalTests = currentSummary[\"totalTests\"]\n # Get the names of the failed tests from both systems.\n currentFailedTestNames = list(currentFailedTests)\n\n print(\"[JFLAP] summary = {}\" .format(currentSummary))\n print(\"[JFLAP] failedTests = {}\" .format(currentFailedTests))\n\n return currentSummary, currentFailedTests\n\n#if __name__ == \"__main__\":\n# filename = sys.argv[1]\n# solutions = sys.argv[2]\n# runTests([], filename, solutions)\n","sub_path":"Fall2018/SampleAutograders/JFlapAutograder/jflapgrader_v2.py","file_name":"jflapgrader_v2.py","file_ext":"py","file_size_in_byte":13707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"297951844","text":"import unittest\nfrom name_function import get_formated_name\n\nclass NameTestCase(unittest.TestCase):\n \"\"\"Testes para 'name_function.py' \"\"\"\n def test_first_last_name(self):\n \"\"\"Nomes como 'Janis Joplin' funcionam?\"\"\"\n formatted_name = get_formated_name('janis','joplin')\n self.assertEqual(formatted_name, 'Janis Joplin')\n\n def test_fisrt_last_midle_name(self):\n \"\"\"Nomes como 'Wolfgang Amadeus Mozart' funcionam?\"\"\"\n formatted_name = get_formated_name('Wolfgang','mozart','aMadeuS')\n self.assertEqual(formatted_name,'Wolfgang Amadeus Mozart')\n\n\nunittest.main()","sub_path":"Testes/test_name_function.py","file_name":"test_name_function.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"156938752","text":"#!/usr/bin/env python\n#\n# Author: Qiming Sun \n#\n\n'''\nExact density fitting with Gaussian and planewaves\nRef:\n'''\n\nimport time\nimport copy\nimport numpy\nfrom pyscf import lib\nfrom pyscf.lib import logger\nfrom pyscf.pbc import tools\n\n#\n# Split the Coulomb potential to two parts. Computing short range part in\n# real space, long range part in reciprocal space.\n#\n\ndef density_fit(mf, auxbasis=None, gs=None, with_df=None):\n '''Generte density-fitting SCF object\n\n Args:\n auxbasis : str or basis dict\n Same format to the input attribute mol.basis.\n The default basis 'weigend+etb' means weigend-coulomb-fit basis\n for light elements and even-tempered basis for heavy elements.\n gs : tuple\n number of grids in each (+)direction\n with_df : MDF object\n '''\n from pyscf.pbc.df import mdf\n if with_df is None:\n if hasattr(mf, 'kpts'):\n kpts = mf.kpts\n else:\n kpts = numpy.reshape(mf.kpt, (1,3))\n\n with_df = mdf.MDF(mf.cell, kpts)\n with_df.max_memory = mf.max_memory\n with_df.stdout = mf.stdout\n with_df.verbose = mf.verbose\n with_df.auxbasis = auxbasis\n if gs is not None:\n with_df.gs = gs\n\n mf = copy.copy(mf)\n mf.with_df = with_df\n return mf\n\n\ndef get_j_kpts(mydf, dm_kpts, hermi=1, kpts=numpy.zeros((1,3)), kpt_band=None):\n cell = mydf.cell\n log = logger.Logger(mydf.stdout, mydf.verbose)\n t1 = (time.clock(), time.time())\n if mydf._cderi is None:\n mydf.build()\n t1 = log.timer_debug1('Init get_j_kpts', *t1)\n\n dm_kpts = lib.asarray(dm_kpts, order='C')\n dms = _format_dms(dm_kpts, kpts)\n nset, nkpts, nao = dms.shape[:3]\n auxcell = mydf.auxcell\n naux = auxcell.nao_nr()\n nao_pair = nao * (nao+1) // 2\n\n rho_tot = numpy.zeros((nset,naux))\n jaux = numpy.zeros((nset,naux))\n rho_coeffs = numpy.empty((nset,nkpts,naux))\n for k, kpt in enumerate(kpts):\n kptii = numpy.asarray((kpt,kpt))\n for Lpq in mydf.load_Lpq(kptii):\n if Lpq.shape[1] == nao_pair:\n Lpq = lib.unpack_tril(Lpq)\n for jpq in mydf.load_j3c(kptii):\n if jpq.shape[1] == nao_pair:\n jpq = lib.unpack_tril(jpq)\n\n for i in range(nset):\n jaux[i] += numpy.einsum('kij,ji->k', jpq, dms[i,k]).real\n rho_coeff = numpy.einsum('kij,ji->k', Lpq, dms[i,k]).real\n rho_tot[i] += rho_coeff\n rho_coeffs[i,k] = rho_coeff\n Lpq = jpq = None\n weight = 1./nkpts\n jaux *= weight\n rho_tot *= weight\n j2c = auxcell.pbc_intor('cint2c2e_sph', 1, lib.HERMITIAN)\n jaux -= numpy.dot(rho_tot, j2c.T)\n j2c = None\n\n dmsR = dms.real.reshape(nset,nkpts,nao**2)\n dmsI = dms.imag.reshape(nset,nkpts,nao**2)\n kpt_allow = numpy.zeros(3)\n coulG = tools.get_coulG(cell, kpt_allow, gs=mydf.gs) / cell.vol\n ngs = len(coulG)\n vR = numpy.zeros((nset,ngs))\n vI = numpy.zeros((nset,ngs))\n max_memory = mydf.max_memory - lib.current_memory()[0]\n for k, pqkR, LkR, pqkI, LkI, p0, p1 \\\n in mydf.ft_loop(cell, auxcell, mydf.gs, kpt_allow, kpts, max_memory):\n # contract dm to rho_rs(-G+k_rs) (Note no .T on dm)\n # rho_rs(-G+k_rs) is computed as conj(rho_{rs^*}(G-k_rs))\n # == conj(transpose(rho_sr(G+k_sr), (0,2,1)))\n for i in range(nset):\n rhoR = numpy.dot(dmsR[i,k], pqkR)\n rhoR-= numpy.dot(dmsI[i,k], pqkI)\n rhoR-= numpy.dot(rho_coeffs[i,k], LkR)\n rhoI = numpy.dot(dmsR[i,k], pqkI)\n rhoI+= numpy.dot(dmsI[i,k], pqkR)\n rhoI-= numpy.dot(rho_coeffs[i,k], LkI)\n vR[i,p0:p1] += rhoR * coulG[p0:p1]\n vI[i,p0:p1] += rhoI * coulG[p0:p1]\n weight = 1./nkpts\n vR *= weight\n vI *= weight\n\n pqkR = LkR = pqkI = LkI = coulG = None\n t1 = log.timer_debug1('get_j pass 1 to compute J(G)', *t1)\n\n if kpt_band is None:\n kpts_band = kpts\n else:\n kpts_band = numpy.reshape(kpt_band, (-1,3))\n gamma_point = abs(kpts_band).sum() < 1e-9\n nband = len(kpts_band)\n\n vjR = numpy.zeros((nset,nband,nao*nao))\n vjI = numpy.zeros((nset,nband,nao*nao))\n for k, pqkR, LkR, pqkI, LkI, p0, p1 \\\n in mydf.ft_loop(cell, auxcell, mydf.gs, kpt_allow, kpts_band, max_memory):\n for i in range(nset):\n vjR[i,k] += numpy.dot(pqkR, vR[i,p0:p1])\n vjR[i,k] += numpy.dot(pqkI, vI[i,p0:p1])\n if not gamma_point:\n for i in range(nset):\n vjI[i,k] += numpy.dot(pqkI, vR[i,p0:p1])\n vjI[i,k] -= numpy.dot(pqkR, vI[i,p0:p1])\n if k+1 == nband: # Construct jaux once, it is the same for all kpts\n for i in range(nset):\n jaux[i] -= numpy.dot(LkR, vR[i,p0:p1])\n jaux[i] -= numpy.dot(LkI, vI[i,p0:p1])\n pqkR = LkR = pqkI = LkI = coulG = None\n\n if gamma_point:\n vj_kpts = vjR\n else:\n vj_kpts = vjR + vjI*1j\n\n for k, kpt in enumerate(kpts_band):\n kptii = numpy.asarray((kpt,kpt))\n for Lpq in mydf.load_Lpq(kptii):\n if Lpq.shape[1] == nao_pair:\n Lpq = lib.unpack_tril(Lpq).reshape(naux,-1)\n for jpq in mydf.load_j3c(kptii):\n if jpq.shape[1] == nao_pair:\n jpq = lib.unpack_tril(jpq).reshape(naux,-1)\n\n vj_kpts[:,k] += numpy.dot(jaux, Lpq)\n vj_kpts[:,k] += numpy.dot(rho_tot, jpq)\n vj_kpts = vj_kpts.reshape(-1,nband,nao,nao)\n t1 = log.timer_debug1('get_j pass 2', *t1)\n\n if kpt_band is not None and numpy.shape(kpt_band) == (3,):\n if dm_kpts.ndim == 3: # One set of dm_kpts for KRHF\n return vj_kpts[0,0]\n else:\n return vj_kpts[:,0]\n else:\n return vj_kpts.reshape(dm_kpts.shape)\n\n\ndef get_k_kpts(mydf, dm_kpts, hermi=1, kpts=numpy.zeros((1,3)), kpt_band=None):\n cell = mydf.cell\n log = logger.Logger(mydf.stdout, mydf.verbose)\n t1 = (time.clock(), time.time())\n if mydf._cderi is None:\n mydf.build()\n t1 = log.timer_debug1('Init get_k_kpts', *t1)\n\n dm_kpts = lib.asarray(dm_kpts, order='C')\n dms = _format_dms(dm_kpts, kpts)\n nset, nkpts, nao = dms.shape[:3]\n auxcell = mydf.auxcell\n naux = auxcell.nao_nr()\n nao_pair = nao * (nao+1) // 2\n\n if kpt_band is None:\n kpts_band = kpts\n swap_2e = True\n else:\n kpts_band = numpy.reshape(kpt_band, (-1,3))\n nband = len(kpts_band)\n kk_table = kpts_band.reshape(-1,1,3) - kpts.reshape(1,-1,3)\n kk_todo = numpy.ones(kk_table.shape[:2], dtype=bool)\n vk_kpts = numpy.zeros((nset,nband,nao,nao), dtype=numpy.complex128)\n\n # K_pq = ( p{k1} i{k2} | i{k2} q{k1} )\n def make_kpt(kpt): # kpt = kptj - kpti\n # search for all possible ki and kj that has ki-kj+kpt=0\n kk_match = numpy.einsum('ijx->ij', abs(kk_table + kpt)) < 1e-9\n kpti_idx, kptj_idx = numpy.where(kk_todo & kk_match)\n nkptj = len(kptj_idx)\n log.debug1('kpt = %s', kpt)\n log.debug1('kpti_idx = %s', kpti_idx)\n log.debug1('kptj_idx = %s', kptj_idx)\n kk_todo[kpti_idx,kptj_idx] = False\n if swap_2e and abs(kpt).sum() > 1e-9:\n kk_todo[kptj_idx,kpti_idx] = False\n\n # Note: kj-ki for electorn 1 and ki-kj for electron 2\n # j2c ~ ({kj-ki}|{ks-kr}) ~ ({kj-ki}|-{kj-ki}) ~ ({kj-ki}|{ki-kj})\n # j3c ~ (Q|kj,ki) = j3c{ji} = (Q|ki,kj)* = conj(transpose(j3c{ij}, (0,2,1)))\n kptkl = -kpt # = kpti-kptj\n j2c = auxcell.pbc_intor('cint2c2e_sph', 1, lib.HERMITIAN, kptkl)\n\n LpqR = []\n LpqI = []\n for ki,kj in zip(kpti_idx,kptj_idx):\n kpti = kpts_band[ki]\n kptj = kpts[kj]\n kptij = numpy.asarray((kpti,kptj))\n for Lpq in mydf.load_Lpq(kptij):\n if Lpq.shape[1] == nao_pair:\n Lpq = lib.unpack_tril(Lpq)\n for jpq in mydf.load_j3c(kptij):\n if jpq.shape[1] == nao_pair:\n jpq = lib.unpack_tril(jpq)\n\n # K ~ 'Lpq,jrs,qr->ps' + 'jpq,Lrs,qr->ps' - 'Lpq,LM,Mrs,qr->ps'\n if hermi == lib.HERMITIAN:\n jpq1 = lib.dot(j2c.T, Lpq.reshape(naux,-1), -.5).reshape(-1,nao,nao)\n jpq1 += jpq.reshape(-1,nao,nao)\n for i in range(nset):\n dm = dms[i,kj]\n Lpi = lib.dot(Lpq.reshape(-1,nao), dm).reshape(-1,nao,nao)\n v = numpy.einsum('Lpi,Lqi->pq', Lpi, jpq1.conj())\n vk_kpts[i,ki] += v\n vk_kpts[i,ki] += v.T.conj()\n else:\n jpq1 = lib.dot(j2c.T, Lpq.reshape(naux,-1), -1).reshape(-1,nao,nao)\n jpq1 += jpq.reshape(-1,nao,nao)\n for i in range(nset):\n dm = dms[i,kj]\n Lpi = lib.dot(Lpq.reshape(-1,nao), dm).reshape(-1,nao,nao)\n vk_kpts[i,ki] += numpy.einsum('Lpi,Lqi->pq', Lpi, jpq1.conj())\n jpq1 = lib.dot(jpq.reshape(-1,nao), dm).reshape(-1,nao,nao)\n vk_kpts[i,ki] += numpy.einsum('Lpi,Lqi->pq', jpq1,\n Lpq.reshape(-1,nao,nao).conj())\n Lpi = jpq1 = None\n\n if swap_2e and abs(kpt).sum() > 1e-9:\n # pqrs = Lpq,jrs' + 'jpq,Lrs' - 'Lpq,LM,Mrs'\n # K ~ 'pqrs,sp->rq'\n #:tmp = lib.dot(j2c.T, Lpq.reshape(naux,-1), -1).reshape(-1,nao,nao)\n #:tmp+= jpq\n #:v4 = lib.dot(Lpq.reshape(naux,-1).T, tmp.conj().reshape(naux,-1))\n #:v4+= lib.dot(jpq.reshape(naux,-1).T, Lpq.conj().reshape(naux,-1))\n #:vk_kpts[kj] += numpy.einsum('pqsr,sp->rq', v4.reshape((nao,)*4), dm)\n if hermi == lib.HERMITIAN:\n jpq1 = lib.dot(j2c.T, Lpq.reshape(naux,-1), -.5).reshape(-1,nao,nao)\n jpq1 += jpq.reshape(-1,nao,nao)\n for i in range(nset):\n dm = dms[i,ki]\n Lip = numpy.einsum('Lpq,sp->Lsq', Lpq.reshape(-1,nao,nao), dm)\n v = numpy.einsum('Lsq,Lsr->rq', Lip, jpq1.conj())\n vk_kpts[i,kj] += v\n vk_kpts[i,kj] += v.T.conj()\n else:\n jpq1 = lib.dot(j2c.T, Lpq.reshape(naux,-1), -1).reshape(-1,nao,nao)\n jpq1 += jpq.reshape(-1,nao,nao)\n for i in range(nset):\n dm = dms[i,ki]\n Lip = numpy.einsum('Lpq,sp->Lsq', Lpq.reshape(-1,nao,nao), dm)\n vk_kpts[i,kj] += numpy.einsum('Lsq,Lsr->rq', Lip, jpq1.conj())\n jpq1 = numpy.einsum('jpq,sp->jsq', jpq.reshape(-1,nao,nao), dm)\n vk_kpts[i,kj] += numpy.einsum('Lsq,Lsr->rq', jpq1,\n Lpq.reshape(-1,nao,nao).conj())\n Lip = jpq1 = None\n\n LpqR.append(numpy.asarray(Lpq.real.reshape(naux,-1), order='C'))\n LpqI.append(numpy.asarray(Lpq.imag.reshape(naux,-1), order='C'))\n Lpq = jpq = None\n\n max_memory = (mydf.max_memory - lib.current_memory()[0]) * .8\n vkcoulG = tools.get_coulG(cell, kpt, True, mydf, mydf.gs) / cell.vol\n kptjs = kpts[kptj_idx]\n # = conj() = conj()\n for k, pqkR, LkR, pqkI, LkI, p0, p1 \\\n in mydf.ft_loop(cell, auxcell, mydf.gs, kpt, kptjs, max_memory):\n ki = kpti_idx[k]\n kj = kptj_idx[k]\n coulG = numpy.sqrt(vkcoulG[p0:p1])\n\n# case 1: k_pq = (pi|iq)\n lib.dot(LpqR[k].T, LkR, -1, pqkR, 1)\n lib.dot(LpqI[k].T, LkI, 1, pqkR, 1)\n pqkR *= coulG\n lib.dot(LpqI[k].T, LkR, -1, pqkI, 1)\n lib.dot(LpqR[k].T, LkI, -1, pqkI, 1)\n pqkI *= coulG\n rsk =(pqkR.reshape(nao,nao,-1).transpose(1,0,2) -\n pqkI.reshape(nao,nao,-1).transpose(1,0,2)*1j)\n qpk = rsk.conj()\n for i in range(nset):\n qsk = lib.dot(dms[i,kj], rsk.reshape(nao,-1)).reshape(nao,nao,-1)\n vk_kpts[i,ki] += numpy.einsum('qpk,qsk->ps', qpk, qsk)\n qsk = None\n rsk = qpk = None\n\n# case 2: k_pq = (iq|pi)\n if swap_2e and abs(kpt).sum() > 1e-9:\n srk = pqkR - pqkI*1j\n pqk = srk.reshape(nao,nao,-1).conj()\n for i in range(nset):\n prk = lib.dot(dms[i,ki].T, srk.reshape(nao,-1)).reshape(nao,nao,-1)\n vk_kpts[i,kj] += numpy.einsum('prk,pqk->rq', prk, pqk)\n prk = None\n srk = pqk = None\n\n LpqR = LpqI = pqkR = LkR = pqkI = LkI = coulG = None\n return None\n\n for ki, kpti in enumerate(kpts_band):\n for kj, kptj in enumerate(kpts):\n if kk_todo[ki,kj]:\n make_kpt(kptj-kpti)\n\n vk_kpts *= 1./nkpts\n if abs(kpts).sum() < 1e-9 and abs(kpts_band).sum() < 1e-9:\n vk_kpts = vk_kpts.real\n\n if kpt_band is not None and numpy.shape(kpt_band) == (3,):\n if dm_kpts.ndim == 3: # One set of dm_kpts for KRHF\n return vk_kpts[0,0]\n else:\n return vk_kpts[:,0]\n else:\n return vk_kpts.reshape(dm_kpts.shape)\n\n\n##################################################\n#\n# Single k-point\n#\n##################################################\n\ndef get_jk(mydf, dm, hermi=1, kpt=numpy.zeros(3),\n kpt_band=None, with_j=True, with_k=True):\n '''JK for given k-point'''\n vj = vk = None\n if kpt_band is not None and abs(kpt-kpt_band).sum() > 1e-9:\n kpt = numpy.reshape(kpt, (1,3))\n if with_k:\n vk = get_k_kpts(mydf, [dm], hermi, kpt, kpt_band)\n if with_j:\n vj = get_j_kpts(mydf, [dm], hermi, kpt, kpt_band)\n return vj, vk\n\n cell = mydf.cell\n log = logger.Logger(mydf.stdout, mydf.verbose)\n t1 = (time.clock(), time.time())\n if mydf._cderi is None:\n mydf.build()\n t1 = log.timer_debug1('Init get_jk', *t1)\n\n dm = numpy.asarray(dm, order='C')\n dms = _format_dms(dm, [kpt])\n nset, _, nao = dms.shape[:3]\n dms = dms.reshape(nset,nao,nao)\n\n auxcell = mydf.auxcell\n naux = auxcell.nao_nr()\n nao_pair = nao * (nao+1) // 2\n kptii = numpy.asarray((kpt,kpt))\n kpt_allow = numpy.zeros(3)\n gamma_point = abs(kpt).sum() < 1e-9\n\n for Lpq in mydf.load_Lpq(kptii):\n if Lpq.shape[1] == nao_pair:\n Lpq = lib.unpack_tril(Lpq)\n for jpq in mydf.load_j3c(kptii):\n if jpq.shape[1] == nao_pair:\n jpq = lib.unpack_tril(jpq)\n\n # j2c is real because for i,j,k,l, same kpt is applied\n j2c = auxcell.pbc_intor('cint2c2e_sph', 1, lib.HERMITIAN)\n if with_j:\n rho_coeff = lib.asarray([numpy.einsum('kij,ji->k', Lpq, dm) for dm in dms])\n jaux = lib.asarray([numpy.einsum('kij,ji->k', jpq, dm) for dm in dms])\n jaux -= numpy.dot(rho_coeff, j2c.T)\n rho_coeff = rho_coeff.real.copy()\n jaux = jaux.real.copy()\n\n if with_k:\n vk = numpy.empty((nset,nao,nao), dtype=numpy.complex128)\n if hermi == lib.HERMITIAN:\n tmp = lib.dot(j2c, Lpq.reshape(naux,-1), -.5).reshape(-1,nao,nao)\n tmp += jpq\n for i in range(nset):\n Lpi = lib.dot(Lpq.reshape(-1,nao), dms[i]).reshape(-1,nao,nao)\n vk[i] = numpy.einsum('Lpi,Liq->pq', Lpi, tmp)\n vk[i] += vk[i].T.conj()\n else:\n tmp = lib.dot(j2c, Lpq.reshape(naux,-1), -1).reshape(-1,nao,nao)\n tmp += jpq\n for i in range(nset):\n Lpi = lib.dot(Lpq.reshape(-1,nao), dms[i]).reshape(-1,nao,nao)\n vk[i] = numpy.einsum('Lpi,Liq->pq', Lpi, tmp)\n tmp = lib.dot(jpq.reshape(-1,nao), dms[i]).reshape(-1,nao,nao)\n vk[i] += numpy.einsum('Lpi,Liq->pq', tmp, Lpq)\n Lpi = tmp = None\n LpqR = numpy.asarray(Lpq.real, order='C')\n LpqI = numpy.asarray(Lpq.imag, order='C')\n j2c = None\n\n if with_j:\n vjcoulG = tools.get_coulG(cell, kpt_allow, gs=mydf.gs) / cell.vol\n if with_k:\n vkcoulG = tools.get_coulG(cell, kpt_allow, True, mydf, mydf.gs) / cell.vol\n dmsR = dms.real.reshape(nset,nao**2)\n dmsI = dms.imag.reshape(nset,nao**2)\n vjR = numpy.zeros((nset,nao**2))\n vjI = numpy.zeros((nset,nao**2))\n max_memory = (mydf.max_memory - lib.current_memory()[0]) * .8\n # rho_rs(-G+k_rs) is computed as conj(rho_{rs^*}(G-k_rs))\n # == conj(transpose(rho_sr(G+k_sr), (0,2,1)))\n for pqkR, LkR, pqkI, LkI, p0, p1 \\\n in mydf.pw_loop(cell, auxcell, mydf.gs, kptii, max_memory):\n if with_j:\n for i in range(nset):\n rhoR = numpy.dot(dmsR[i], pqkR)\n rhoR-= numpy.dot(dmsI[i], pqkI)\n rhoR-= numpy.dot(rho_coeff[i], LkR)\n rhoI = numpy.dot(dmsR[i], pqkI)\n rhoI+= numpy.dot(dmsI[i], pqkR)\n rhoI-= numpy.dot(rho_coeff[i], LkI)\n rhoR *= vjcoulG[p0:p1]\n rhoI *= vjcoulG[p0:p1]\n if not gamma_point:\n vjI[i] += numpy.dot(pqkI, rhoR)\n vjI[i] -= numpy.dot(pqkR, rhoI)\n jaux[i] -= numpy.dot(LkI, rhoR) * 1j\n jaux[i] += numpy.dot(LkR, rhoI) * 1j\n vjR[i] += numpy.dot(pqkR, rhoR)\n vjR[i] += numpy.dot(pqkI, rhoI)\n jaux[i] -= numpy.dot(LkR, rhoR)\n jaux[i] -= numpy.dot(LkI, rhoI)\n\n if with_k:\n coulG = numpy.sqrt(vkcoulG[p0:p1])\n lib.dot(LpqR.reshape(naux,-1).T, LkR, -1, pqkR, 1)\n lib.dot(LpqI.reshape(naux,-1).T, LkI, 1, pqkR, 1)\n pqkR *= coulG\n lib.dot(LpqI.reshape(naux,-1).T, LkR, -1, pqkI, 1)\n lib.dot(LpqR.reshape(naux,-1).T, LkI, -1, pqkI, 1)\n pqkI *= coulG\n #:v4 = numpy.einsum('ijL,lkL->ijkl', pqk, pqk.conj())\n #:vk += numpy.einsum('ijkl,jk->il', v4, dm)\n rsk =(pqkR.reshape(nao,nao,-1).transpose(1,0,2) -\n pqkI.reshape(nao,nao,-1).transpose(1,0,2)*1j)\n pqk =(pqkR+pqkI*1j).reshape(nao,nao,-1)\n for i in range(nset):\n qsk = numpy.dot(dms[i], rsk.reshape(nao,-1)).reshape(nao,nao,-1)\n vk[i] += numpy.einsum('ijG,jlG->il', pqk, qsk)\n pqkR = LkR = pqkI = LkI = coulG = None\n\n if with_j:\n if gamma_point:\n vj = vjR\n else:\n vj = vjR + vjI * 1j\n vj += numpy.dot(jaux, Lpq.reshape(naux,-1))\n vj += numpy.dot(rho_coeff, jpq.reshape(naux,-1))\n vj = vj.reshape(dm.shape)\n\n if with_k:\n if gamma_point:\n vk = vk.real\n vk = vk.reshape(dm.shape)\n return vj, vk\n\ndef _format_dms(dm_kpts, kpts):\n nkpts = len(kpts)\n nao = dm_kpts.shape[-1]\n dms = dm_kpts.reshape(-1,nkpts,nao,nao)\n return dms\n\n\nif __name__ == '__main__':\n import pyscf.pbc.gto as pgto\n import pyscf.pbc.scf as pscf\n import pyscf.pbc.dft as pdft\n\n L = 5.\n n = 5\n cell = pgto.Cell()\n cell.h = numpy.diag([L,L,L])\n cell.gs = numpy.array([n,n,n])\n\n cell.atom = '''C 3. 2. 3.\n C 1. 1. 1.'''\n #cell.basis = {'He': [[0, (1.0, 1.0)]]}\n #cell.basis = '631g'\n #cell.basis = {'He': [[0, (2.4, 1)], [1, (1.1, 1)]]}\n cell.basis = 'ccpvdz'\n cell.verbose = 0\n cell.build(0,0)\n cell.verbose = 5\n #print cell.nimgs\n #cell.nimgs = [4,4,4]\n\n mf = pscf.RHF(cell)\n auxbasis = 'weigend'\n mf = density_fit(mf, auxbasis)\n mf.with_df.gs = (5,) * 3\n mf.with_df.approx_sr_level = 3\n dm = mf.get_init_guess()\n vj = mf.get_j(cell, dm)\n print(numpy.einsum('ij,ji->', vj, dm), 'ref=46.69745030912447')\n vj, vk = mf.get_jk(cell, dm)\n print(numpy.einsum('ij,ji->', vj, dm), 'ref=46.69745030912447')\n print(numpy.einsum('ij,ji->', vk, dm), 'ref=37.33704732444835')\n print(numpy.einsum('ij,ji->', mf.get_hcore(cell), dm), 'ref=-75.574414055823766')\n","sub_path":"pbc/df/mdf_jk.py","file_name":"mdf_jk.py","file_ext":"py","file_size_in_byte":20206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"615069507","text":"import json\r\nimport os\r\nimport importlib.util\r\nimport threading\r\n\r\nfrom BaseLibraries.messaging import FIPA_message\r\n# 1. iterate over each functions introduction at start of agent\r\n# 2. key will be performative_type and value will be function_type\r\n# 3. there is additional function type to function mapping text file that user can edit\r\n# this file is read it is the function_pointing text file\r\n# ---------------------------------------------------------------------------------------\r\n# type to function_type mapping creator (at start of agent)\r\n # create a file\r\n # read intro\r\n # map type to function type\r\n\r\n\r\n# There is a need of function pointing generator (at start of agent)\r\n # read each intro\r\n # for each function type (key) these function name (values) are to be added in text file\r\n\r\n# the below function creates both mapping as well as pointing text files\r\nfrom DownloadableFunctions import Single_Machine_Sequencing_Considering_Maintenace_Action\r\n\r\nfolder_location = r'C:\\Users\\Saourabh\\PycharmProjects\\phase2\\AgentFunctions'\r\n\r\n\r\ndef create_mapping_and_pointing_files(paths_dictionary,msg_to_send_queue):\r\n\r\n # creating files for mapping and pointing at start of agent\r\n folder_path = paths_dictionary['agent_functions_path']\r\n mapping = open(\"type_to_function_mapping.txt\", \"w+\")\r\n pointing = open(\"function_pointing.txt\", \"w+\")\r\n\r\n # recognizing which active functions to start using the config file\r\n # config file exists, and is not created when agent starts\r\n active_fn_flags = {}\r\n active_fns_file = open(paths_dictionary['active_functions_configuration'],'r')\r\n config_file_contents = active_fns_file.read()\r\n Lines = config_file_contents.splitlines()\r\n for line in Lines:\r\n key_values = line.split(\"=>\")\r\n key = key_values[0]\r\n values = key_values[1]\r\n active_fn_flags[key] = values\r\n\r\n # initials for creating an agent file\r\n agent_file_data = {}\r\n agent_file_data['agent_name'] = paths_dictionary['agent_name']\r\n agent_file_data['agent_role'] = paths_dictionary['agent_role']\r\n\r\n filenames = os.listdir(folder_path) # filenames in folder of active and passive functions\r\n current_performative_types = []\r\n active_responce_list, passive_responce_list = [],[]\r\n dict_pointer = {}\r\n for filename in filenames:\r\n if filename[-3:] == '.py':\r\n filepath = os.path.join(folder_path, filename)\r\n spec = importlib.util.spec_from_file_location(filename, filepath)\r\n python_script = importlib.util.module_from_spec(spec)\r\n spec.loader.exec_module(python_script)\r\n func_intro = python_script.introduction()\r\n # now func_intro has dictionary returned by the individual module in AgentFunctions\r\n print('reading ',filename)\r\n if func_intro['active_passive'] == 'passive':\r\n # creating performative_type to function_type mapping\r\n try:\r\n for prf_typ in func_intro['performative_types']:\r\n passive_responce_list.append(prf_typ)\r\n if prf_typ not in current_performative_types:\r\n mapping.write(f\"{prf_typ}=>{func_intro['function_type']}\\n\")\r\n current_performative_types.append(prf_typ)\r\n except:\r\n print(f\"{filename} does not have performative_type\")\r\n\r\n # adding available pointer fuctions (.py filenames) to function types\r\n # for each function type (key) these function name (values) are to be added in text file\r\n\r\n curr_fn_typ = func_intro['function_type']\r\n if curr_fn_typ not in dict_pointer:\r\n # [1] is given to the first function recognized in the function_type\r\n dict_pointer[curr_fn_typ] = f\"{filename[:-3]}[1]\"\r\n else:\r\n current_value = dict_pointer[curr_fn_typ]\r\n # other functions recognized for same function_type are given [0] as preference\r\n # the pointing file is made such that 0 and 1 value are editable by user\r\n new_value = f\"{current_value}|{filename[:-3]}[0]\"\r\n dict_pointer[curr_fn_typ] = new_value\r\n\r\n elif func_intro['active_passive'] == 'active':\r\n for prf_typ in func_intro['performative_types']:\r\n active_responce_list.append(prf_typ)\r\n if active_fn_flags[filename[:-3]] in ['1', 1]:\r\n (threading.Thread(target = python_script.active, args = [msg_to_send_queue,])).start()\r\n\r\n for key in dict_pointer:\r\n pointing.write(f\"{key}=>{dict_pointer[key]}\\n\")\r\n\r\n for prf_typ in active_responce_list:\r\n agent_file_data[prf_typ] = {'send': 1, 'receive': 0}\r\n for prf_typ in passive_responce_list:\r\n if prf_typ not in active_responce_list:\r\n agent_file_data[prf_typ] = {'send': 0, 'receive': 1}\r\n else:\r\n agent_file_data[prf_typ] = {'send': 1, 'receive': 1}\r\n agent_nickname = paths_dictionary['agent_name']\r\n with open(f\"{agent_nickname}.json\", \"w+\") as json_file:\r\n json.dump(agent_file_data, json_file)\r\n json_file.close()\r\n mapping.close()\r\n pointing.close()\r\n active_fns_file.close()\r\n\r\n return\r\n\r\n\r\n# reading type to function mapping\r\n # read type to function mapping txt\r\n # see key = type and get value = function type\r\n # return function type string\r\ndef map_performative_type(performative_type):\r\n\r\n mapping_table = {}\r\n mapping_file = open(\"type_to_function_mapping.txt\", \"r\")\r\n mapping_file_contents = mapping_file.read()\r\n Lines = mapping_file_contents.splitlines()\r\n\r\n for line in Lines:\r\n key_values = line.split(\"=>\")\r\n key = key_values[0]\r\n values = key_values[1]\r\n mapping_table[key] = values\r\n required_value = mapping_table[performative_type]\r\n return required_value\r\n\r\n\r\n# the below part is reading... function_type to fuction mapping (or) function pointing\r\n# this should return target function name as string\r\n# =============================================================================\r\n\r\ndef pointing(function_type):\r\n function_pointing_table={}\r\n function_pointing_file = open(\"function_pointing.txt\",\"r\")\r\n function_pointing_file_contents = function_pointing_file.read()\r\n Lines = function_pointing_file_contents.splitlines()\r\n\r\n for line in Lines:\r\n key_values=line.split(\"=>\")\r\n key=key_values[0]\r\n values=(key_values[1]).split(\"|\")\r\n function_pointing_table[key] = values\r\n\r\n required_values = function_pointing_table[function_type]\r\n\r\n for value in required_values:\r\n if value[-3:] == '[1]':\r\n return value[:-3]\r\n\r\n return\r\n\r\n# =========================================================================\r\n# the final part is execution of that function and generating an output\r\n\r\n\r\ndef function_execution(function_name,performative_type,inputs,paths_dictionary): # filename is actually the .py file\r\n folder_location = paths_dictionary['agent_functions_path']\r\n filenames = os.listdir(folder_location) # filenames in folder of active and passive functions\r\n for filename in filenames:\r\n print(function_name,filename[:-3])\r\n if filename[-3:] == '.py' and filename[:-3] == function_name:\r\n filepath = os.path.join(folder_location, filename)\r\n spec = importlib.util.spec_from_file_location(filename, filepath)\r\n python_script = importlib.util.module_from_spec(spec)\r\n spec.loader.exec_module(python_script)\r\n execution_result = python_script.execute(performative_type,inputs)\r\n\r\n print(execution_result)\r\n return execution_result\r\n\r\n print('executable function file not found in downloadable functions')\r\n return\r\n\r\n\r\ndef create_a_reply_to_send(message,reply_parameters):\r\n\r\n if reply_parameters:\r\n reply = FIPA_message()\r\n reply.performative = reply_parameters[\"reply_performative\"]\r\n reply.type = reply_parameters[\"reply_type\"]\r\n reply.content = reply_parameters[\"reply_content\"]\r\n reply.receiver = message.sender\r\n reply.protocol = message.protocol\r\n reply.conversation_id = message.conversation_id\r\n return reply\r\n\r\n\r\ndef map_and_point(message):\r\n performative_type = message.type\r\n function_category = map_performative_type(performative_type)\r\n executable_function_name = pointing(function_category)\r\n if executable_function_name:\r\n return executable_function_name\r\n else:\r\n return None\r\n\r\n\r\n","sub_path":"Machine_Agent 3/BaseLibraries/support_files.py","file_name":"support_files.py","file_ext":"py","file_size_in_byte":8758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"571485681","text":"#coding:utf-8\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nimport time\nbrowser = webdriver.Chrome()\nbrowser.maximize_window()\nbrowser.get('C://Users//Administrator//Desktop//test.html')\ntime.sleep(4)\n#checkbox\nbrowser.find_element_by_xpath('//input[@value=\"cv1\"]').click()\nbrowser.find_element_by_xpath('//input[@value=\"cv2\"]').send_keys(Keys.SPACE) #对这个狂发送空格键也能选中\ntime.sleep(5)\n\n#radio\nbrowser.find_element_by_xpath('//input[@value=\"rv1\"]').click()\nbrowser.find_element_by_xpath('//input[@value=\"rv2\"]').send_keys(Keys.SPACE) #对这个狂发送空格键也能选中\ntime.sleep(5)\n#上例可以看出我们对这种checkbox和radio,可以通过直接点击或者发送��格的方式达到选中或者反选的目的\n\nbrowser.close()\nbrowser.quit()","sub_path":"check_box.py","file_name":"check_box.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"139002685","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/sutekh/gui/plugins/ClusterCardList.py\n# Compiled at: 2019-12-11 16:37:54\n\"\"\"Plugin to find clusters in the card lists.\"\"\"\nimport random, math, gtk\nfrom sutekh.base.core.BaseTables import PhysicalCard, PhysicalCardSet\nfrom sutekh.base.core.BaseAdapters import IPhysicalCard\nfrom sutekh.base.core.CardSetUtilities import check_cs_exists\nfrom sutekh.base.gui.AutoScrolledWindow import AutoScrolledWindow\nfrom sutekh.base.gui.SutekhDialog import NotebookDialog, do_complaint_error\nfrom sutekh.core.CardListTabulator import CardListTabulator\nfrom sutekh.gui.PluginManager import SutekhPlugin\n\nclass ClusterCardList(SutekhPlugin):\n \"\"\"Plugin that attempts to find clusters in the card list.\n\n Allows the user to choose various clustering parameters, such as\n attributes to to use and methods, and then to create card sets\n from the clustering results.\"\"\"\n dTableVersions = {}\n aModelsSupported = (\n PhysicalCard, PhysicalCardSet)\n\n def __init__(self, *args, **kwargs):\n super(ClusterCardList, self).__init__(*args, **kwargs)\n if not self.model:\n self._fMakeCardSetFromCluster = None\n self._fMakeCardSetFromCluster = self._make_pcs_from_cluster\n self._dPropButtons = {}\n self._dGroups = {}\n self._oResultsVbox = None\n self._aDistanceMeasureGroup = None\n self._oAutoNumClusters = None\n self._oNumClustersSpin = None\n self._oNumIterSpin = None\n return\n\n def get_menu_item(self):\n \"\"\"Register on the 'Analyze' menu.\"\"\"\n oCluster = gtk.MenuItem('Cluster Cards')\n oCluster.connect('activate', self.activate)\n return ('Analyze', oCluster)\n\n def activate(self, _oWidget):\n \"\"\"In response to the menu, create the correct dialog.\"\"\"\n oDlg = self.make_dialog()\n oDlg.run()\n\n def make_dialog(self):\n \"\"\"Create the dialog for the clustering options.\"\"\"\n sDlgName = 'Cluster Cards in List'\n self._make_prop_groups()\n oDlg = NotebookDialog(sDlgName, self.parent, gtk.DIALOG_DESTROY_WITH_PARENT)\n oDlg.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE)\n oDlg.add_button(gtk.STOCK_EXECUTE, gtk.RESPONSE_APPLY)\n oDlg.connect('response', self.handle_response)\n oTableSection = self._make_table_section()\n oAlgorithmSection = self._make_algorithm_section()\n oResultsSection = self._make_results_section()\n oDlg.add_widget_page(oTableSection, 'Select Columns')\n oDlg.add_widget_page(oAlgorithmSection, 'Settings')\n oDlg.add_widget_page(oResultsSection, 'Results')\n oDlg.show_all()\n return oDlg\n\n def _make_prop_groups(self):\n \"\"\"Extract the list of possible properties to cluster on.\"\"\"\n dPropFuncs = CardListTabulator.get_default_prop_funcs()\n self._dGroups = {}\n for sName, fProp in dPropFuncs.iteritems():\n aParts = sName.split(':')\n if len(aParts) == 1:\n self._dGroups.setdefault('Miscellaneous', {})[sName.capitalize()] = fProp\n else:\n sGroup, sRest = aParts[0].strip().capitalize(), (':').join(aParts[1:]).strip().capitalize()\n self._dGroups.setdefault(sGroup, {})[sRest] = fProp\n\n def _make_table_section(self):\n \"\"\"Create a notebook, and populate the first tabe with a list of\n properties to cluster on.\"\"\"\n oNotebook = gtk.Notebook()\n aGroups = self._dGroups.keys()\n aGroups.sort()\n self._dPropButtons = {}\n for sGroup in aGroups:\n self._dPropButtons[sGroup] = {}\n dPropFuncs = self._dGroups[sGroup]\n oHbx = gtk.HBox(False, 0)\n iCols = 3\n iPropsPerCol = len(dPropFuncs) // iCols\n if len(dPropFuncs) % iCols != 0:\n iPropsPerCol += 1\n aPropNames = dPropFuncs.keys()\n aPropNames.sort()\n for iProp, sName in enumerate(aPropNames):\n if iProp % iPropsPerCol == 0:\n oVbx = gtk.VBox(False, 0)\n oHbx.pack_start(oVbx)\n oBut = gtk.CheckButton(sName)\n oVbx.pack_start(oBut, False)\n self._dPropButtons[sGroup][sName] = oBut\n\n oNotebook.append_page(oHbx, gtk.Label(sGroup))\n\n return oNotebook\n\n def _make_algorithm_section(self):\n \"\"\"Populate a tab on the notebook with the parameters and options for\n the clustering algorithm.\n \"\"\"\n oVbx = gtk.VBox(False, 0)\n oHeading = gtk.Label()\n oHeading.set_markup('Parameters for K-Means Clustering')\n oVbx.pack_start(oHeading, False, False, 5)\n oNumIterLabel = gtk.Label('Number of Iterations:')\n self._oNumIterSpin = gtk.SpinButton()\n self._oNumIterSpin.set_range(1, 50)\n self._oNumIterSpin.set_increments(1, 10)\n self._oNumIterSpin.set_value(10)\n oHbox = gtk.HBox(False, 0)\n oHbox.pack_start(oNumIterLabel, False)\n oHbox.pack_end(self._oNumIterSpin, False)\n oVbx.pack_start(oHbox, False)\n self._oAutoNumClusters = gtk.CheckButton('One cluster per 80 cards')\n oHbox = gtk.HBox(False, 0)\n oHbox.pack_start(self._oAutoNumClusters, False)\n oVbx.pack_start(oHbox, False)\n oNumClustersLabel = gtk.Label('Number of Clusters:')\n self._oNumClustersSpin = gtk.SpinButton()\n self._oNumClustersSpin.set_range(2, 50)\n self._oNumClustersSpin.set_increments(1, 10)\n self._oNumClustersSpin.set_value(10)\n oHbox = gtk.HBox(False, 0)\n oHbox.pack_start(oNumClustersLabel, False)\n oHbox.pack_end(self._oNumClustersSpin, False)\n oVbx.pack_start(oHbox, False)\n self._oAutoNumClusters.set_active(True)\n self._oNumClustersSpin.set_sensitive(False)\n\n def auto_toggled(oAutoNumClusters):\n \"\"\"Called when oAutoNumClusters is toggled.\"\"\"\n if oAutoNumClusters.get_active():\n self._oNumClustersSpin.set_sensitive(False)\n else:\n self._oNumClustersSpin.set_sensitive(True)\n\n self._oAutoNumClusters.connect('toggled', auto_toggled)\n oVbx.pack_start(gtk.HSeparator(), False, False, 10)\n oDistLabel = gtk.Label()\n oDistLabel.set_markup('Distance Measure for Clustering')\n oVbx.pack_start(oDistLabel, False, False, 5)\n oIter = Vector.METRICS.iterkeys()\n for sName in oIter:\n oFirstBut = gtk.RadioButton(None, sName, False)\n oVbx.pack_start(oFirstBut, False)\n break\n\n for sName in oIter:\n oBut = gtk.RadioButton(oFirstBut, sName)\n oVbx.pack_start(oBut, False)\n\n self._aDistanceMeasureGroup = oFirstBut.get_group()\n return oVbx\n\n def _make_results_section(self):\n \"\"\"Create a widget in the notebook which can be used to display\n the clustering results.\"\"\"\n oVbx = gtk.VBox(False, 0)\n self._oResultsVbox = gtk.VBox(False, 0)\n oHeading = gtk.Label()\n oHeading.set_markup('Results')\n oVbx.pack_start(oHeading, False)\n oLabel = gtk.Label('No results yet.')\n self._oResultsVbox.pack_start(oLabel)\n oVbx.pack_start(self._oResultsVbox)\n return oVbx\n\n def _populate_results(self, aCards, aColNames, aMeans, aClusters):\n \"\"\"Populate the results tab of the notebook with the results of\n clustering run.\"\"\"\n self._aCards, self._aColNames, self._aMeans, self._aClusters = (\n aCards, aColNames, aMeans, aClusters)\n for oChild in self._oResultsVbox.get_children():\n self._oResultsVbox.remove(oChild)\n\n iHeaderRows = 1\n iExtraCols = 4\n oTable = gtk.Table(rows=len(aMeans) + iHeaderRows, columns=iExtraCols)\n oTable.set_row_spacings(0)\n oLabel = gtk.Label()\n oLabel.set_markup('Save Deck')\n oTable.attach(oLabel, 0, 1, 0, 1, xpadding=3)\n oLabel = gtk.Label()\n oLabel.set_markup('Cluster Id')\n oTable.attach(oLabel, 1, 2, 0, 1, xpadding=3)\n oLabel = gtk.Label()\n oLabel.set_markup('No. Cards')\n oTable.attach(oLabel, 2, 3, 0, 1, xpadding=3)\n oLabel = gtk.Label()\n oLabel.set_markup('Cluster Center')\n oTable.attach(oLabel, 3, 4, 0, 1, xpadding=3)\n self._dCardSetMakingButtons = {}\n for iId, oMean in enumerate(self._aMeans):\n iRow = iId + iHeaderRows\n oBut = gtk.CheckButton()\n self._dCardSetMakingButtons[iId] = oBut\n sCenterText = ('\\n').join([ '%s: %.2f' % (sColName, fColVal) for sColName, fColVal in zip(aColNames, oMean) if abs(fColVal) > 0.01\n ])\n oCenterLabel = gtk.Label(sCenterText)\n oCenterLabel.set_alignment(0.0, 0.5)\n oTable.attach(oBut, 0, 1, iRow, iRow + 1)\n oTable.attach(gtk.Label(str(iId)), 1, 2, iRow, iRow + 1)\n oTable.attach(gtk.Label(str(len(aClusters[iId]))), 2, 3, iRow, iRow + 1)\n oTable.attach(oCenterLabel, 3, 4, iRow, iRow + 1)\n\n self._oResultsVbox.pack_start(AutoScrolledWindow(oTable, True))\n oMakeCardSetsButton = gtk.Button('Make Card Sets from Selected Clusters')\n oMakeCardSetsButton.connect('clicked', self.handle_make_card_sets)\n self._oResultsVbox.pack_end(oMakeCardSetsButton, False)\n self._oResultsVbox.show_all()\n\n def handle_response(self, oDlg, oResponse):\n \"\"\"Handle the user's response to the options dialog.\"\"\"\n if oResponse == gtk.RESPONSE_CLOSE:\n oDlg.destroy()\n elif oResponse == gtk.RESPONSE_APPLY:\n self.do_clustering()\n oDlg.notebook.set_current_page(2)\n\n def handle_make_card_sets(self, _oSomeObj):\n \"\"\"Create card a suitable card set from the chosen clusters\"\"\"\n for iId, oBut in self._dCardSetMakingButtons.iteritems():\n if oBut.get_active():\n self._fMakeCardSetFromCluster(iId)\n\n @staticmethod\n def k_means_plus_plus(aCards, iNumClust, fDist):\n \"\"\"Find a set of initial centers using the k-means++ algorithm.\n\n See http://www.stanford.edu/~darthur/kMeansPlusPlus.pdf.\n \"\"\"\n aMeans = [\n random.choice(aCards)]\n while len(aMeans) < iNumClust:\n aDists = []\n for oVec in aCards:\n fMinD = min(fDist(oVec, oMean) for oMean in aMeans) ** 2\n aDists.append(fMinD)\n\n fSumSq = sum(aDists)\n fPick = random.uniform(0, fSumSq)\n for iCard, fMinD in enumerate(aDists):\n fPick -= fMinD\n if fPick <= 0:\n break\n\n if iCard == len(aCards):\n iCard -= 1\n aMeans.append(aCards[iCard])\n\n return aMeans\n\n def k_means(self, aCards, iNumClust, iIterations, fDist):\n \"\"\"Perform k-means clustering on a list of cards using Lloyd's\n algorithm.\"\"\"\n if not aCards or not aCards[0]:\n return ([], [])\n aCards = [ Vector(x) for x in aCards ]\n aMeans = self.k_means_plus_plus(aCards, iNumClust, fDist)\n iCards = len(aCards)\n for _iIter in range(iIterations):\n aClusters = []\n for iClust in xrange(iNumClust):\n aClusters.append([])\n\n for iCard in xrange(iCards):\n oVec = aCards[iCard]\n iVmin = min(xrange(iNumClust), key=lambda iV: fDist(oVec, aMeans[iV]))\n aClusters[iVmin].append(iCard)\n\n for iClust in xrange(iNumClust):\n if aClusters[iClust]:\n aMeans[iClust] = 1.0 / len(aClusters[iClust]) * sum(aCards[x] for x in aClusters[iClust])\n\n return (aMeans, aClusters)\n\n def do_clustering(self):\n \"\"\"Call the chosen clustering algorithm\"\"\"\n aCards = list(self.model.get_card_iterator(None))\n dPropFuncs = {}\n for sGroup, dButtons in self._dPropButtons.iteritems():\n for sName, oBut in dButtons.iteritems():\n if oBut.get_active():\n dPropFuncs[sGroup + ': ' + sName] = self._dGroups[sGroup][sName]\n\n aColNames = dPropFuncs.keys()\n aColNames.sort()\n oTab = CardListTabulator(aColNames, dPropFuncs)\n aTable = oTab.tabulate(aCards)\n if self._oAutoNumClusters.get_active():\n iNumClusts = max(4, int(len(aTable) / 80.0) + 1)\n else:\n iNumClusts = max(2, int(self._oNumClustersSpin.get_value()))\n iIterations = max(2, int(self._oNumIterSpin.get_value()))\n for oBut in self._aDistanceMeasureGroup:\n if oBut.get_active():\n sName = oBut.get_label()\n fDist = Vector.METRICS[sName]\n break\n else:\n fDist = Vector.METRICS['Euclidean Distance']\n\n aMeans, aClusters = self.k_means(aTable, iNumClusts, iIterations, fDist)\n self._populate_results(aCards, aColNames, aMeans, aClusters)\n return\n\n def _make_pcs_from_cluster(self, iClusterId):\n \"\"\"Create a Card Set from the chosen cluster\"\"\"\n sDeckName = '_cluster_deck_%d' % (iClusterId,)\n if check_cs_exists(sDeckName):\n do_complaint_error('Card Set %s already exists.' % sDeckName)\n return\n oDeck = PhysicalCardSet(name=sDeckName)\n aCards = [ IPhysicalCard(self._aCards[x]) for x in self._aClusters[iClusterId]\n ]\n self._commit_cards(oDeck, aCards)\n self._open_cs(sDeckName, True)\n\n\nclass Vector(object):\n \"\"\"Really simple class representing a row of card table data.\"\"\"\n METRICS = {}\n\n def __init__(self, aData):\n self._aData = aData\n\n def euclidian_distance(self, oVec2):\n \"\"\"Euclidean distance between two vectors.\"\"\"\n assert len(self._aData) == len(oVec2._aData)\n fSum = sum((x - y) ** 2 for x, y in zip(self._aData, oVec2._aData))\n return math.sqrt(fSum)\n\n METRICS['Euclidean Distance'] = euclidian_distance\n\n def sutekh_distance(self, oVec2):\n \"\"\"Like Euclidean distance, but -1 is distance 0.25 to anything\n (including 0 and -1) and 0 is distance 4.0 from anything other\n than 0.\n \"\"\"\n assert len(self._aData) == len(oVec2._aData)\n fSum = sum((x == -1 or y == -1) and 0.25 or (x == 0) ^ (y == 0) and 4.0 or (x - y) ** 2 for x, y in zip(self._aData, oVec2._aData))\n return math.sqrt(fSum)\n\n METRICS['Sutekh Distance'] = sutekh_distance\n\n def __add__(self, oOther):\n \"\"\"Sum this vector with another.\"\"\"\n if oOther == 0:\n return self\n assert len(self._aData) == len(oOther._aData)\n return Vector([ x + y for x, y in zip(self._aData, oOther._aData) ])\n\n def __radd__(self, oOther):\n \"\"\"Sum this vector with another.\"\"\"\n if oOther == 0:\n return self\n assert len(self._aData) == len(oOther._aData)\n return Vector([ x + y for x, y in zip(self._aData, oOther._aData) ])\n\n def __mul__(self, fScale):\n \"\"\"Multiply this vector by a scalar.\"\"\"\n fScale = float(fScale)\n return Vector([ x * fScale for x in self._aData ])\n\n def __rmul__(self, fScale):\n \"\"\"Multiply this vector by a scalar.\"\"\"\n fScale = float(fScale)\n return Vector([ x * fScale for x in self._aData ])\n\n def __len__(self):\n \"\"\"Length of this vector.\"\"\"\n return len(self._aData)\n\n def __str__(self):\n \"\"\"String representation of this vector.\"\"\"\n return str(self._aData)\n\n def __iter__(self):\n \"\"\"Iterator.\"\"\"\n return iter(self._aData)\n\n\nplugin = ClusterCardList","sub_path":"pycfiles/Sutekh-1.0.0-py2.7/ClusterCardList.py","file_name":"ClusterCardList.py","file_ext":"py","file_size_in_byte":15982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"175962013","text":"from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\n\nfrom bayarea_relief.search import search_bp\n\napp = Flask(__name__)\napp.register_blueprint(search_bp)\nurl = \"postgresql://postgres:postgres@localhost:5000/bar\"\napp.config['SQLALCHEMY_DATABASE_URI'] = url\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # silence the deprecation warning\ndb = SQLAlchemy(app)\ndb.init_app(app)\n","sub_path":"bayarea_relief/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"247212367","text":"import os\nimport hashlib\nimport encryption\nimport binascii\n\nclass PublicKey:\n\n def __init__(self, identity, N, e, n):\n self.identity = identity\n self.N = int(N)\n self.e = int(e)\n self.n = int(n)\n\n @staticmethod\n def from_file(file_name):\n key_file = open(file_name, 'r')\n key_vals = str.split(key_file.read())\n return PublicKey(key_vals[0], key_vals[1], key_vals[2], key_vals[3])\n\n def verify(self, plain_text, signature):\n sha_hash = long(hashlib.sha256(plain_text).hexdigest(), 16)\n return pow(signature, self.e) % self.N == sha_hash % self.N\n\n def formatted(self):\n return '{} {} {} {}'.format(self.identity, self.N, self.e, self.n)\n\nclass PrivateKey:\n\n def __init__(self, identity, N, d, n):\n self.identity = identity\n self.N = int(N)\n self.d = int(d)\n self.n = int(n)\n\n @staticmethod\n def from_file(file_name):\n key_file = open(file_name, 'r')\n key_vals = str.split(key_file.read())\n return PrivateKey(key_vals[0], key_vals[1], key_vals[2], key_vals[3])\n\n def sign(self, plain_text):\n sha_hash = long(hashlib.sha256(plain_text).hexdigest(), 16)\n sig = encryption.pow_mod(sha_hash, self.d, self.N)\n return sig\n\n def formatted(self):\n return '{} {} {} {}'.format(self.identity, self.N, self.d, self.n)\n\ndef generate_key_pair(security_parameter, identity):\n\n n = security_parameter\n\n # Choose two distinct n bit prime numbers p, q\n p = int(binascii.hexlify(os.urandom(n / 8)), 16) # Use PRNG to generate n bit random number\n while not encryption.is_prime(p, 3):\n p = int(binascii.hexlify(os.urandom(n/8)), 16)\n\n q = int(binascii.hexlify(os.urandom(n / 8)), 16) # Use PRNG to generate n bit random number\n while not encryption.is_prime(q, 3):\n q = int(binascii.hexlify(os.urandom(n / 8)), 16)\n\n # Compute N as p * q\n N = p * q\n\n # zN_star_order = (p-1)(q-1)\n zN_star_order = (p - 1) * (q - 1)\n\n # Generate e > 1 such that e is coprime with zN_star_order\n e = encryption.find_coprime(zN_star_order)\n\n # d = e's inverse mod zN_star_order\n d = encryption.inverse_mod(e, zN_star_order)\n\n # public_key is N and e and n\n public_key = PublicKey(identity, N, e, n)\n\n # private_key is N and d and n\n private_key = PrivateKey(identity, N, d, n)\n\n return (public_key, private_key)\n","sub_path":"security/RSA_key_generation_and_encryption_and_decryption/key.py","file_name":"key.py","file_ext":"py","file_size_in_byte":2421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"447597671","text":"#!/usr/bin/env python\n\nimport numpy as np\nimport theano\nimport theano.tensor as T\n\ntheano.config.int_division = 'floatX'\n\nclass Logistic(object):\n '''Logistic regression, maximizes $p_j \\propto w_{ij}\\cdot x_i+b_j$'''\n def __init__(self,nIn,nOut,x):\n self.W = theano.shared(value=np.zeros((nIn,nOut),dtype=theano.config.floatX), name='W',borrow=True)\n self.b = theano.shared(value=np.zeros((nOut,),dtype=theano.config.floatX), name='b',borrow=True)\n self.input = x\n self.P = T.nnet.softmax(T.dot(self.input,self.W) + self.b)\n self.yHat = T.argmax(self.P,axis=1)\n testX = T.matrix('testX')\n testY = T.ivector('testY')\n self.evaluate = theano.function(\n inputs = [testX],\n outputs = self.yHat,\n givens = {\n self.input : testX\n }\n )\n self.errors = theano.function(\n inputs = [testX,testY],\n outputs = T.mean(T.neq(self.yHat,testY)),\n givens = {\n self.input : testX\n },\n allow_input_downcast=True\n )\n self.probabilities = theano.function(\n inputs = [testX],\n outputs = self.P,\n givens = {\n self.input : testX\n }\n )\n def __getstate__(self):\n return {'W':self.W, 'b':self.b}\n def __setstate__(self,d):\n self.W = d['W']\n self.b = d['b']\n def NLL(self,y):\n '''\n NLL loss\n this assumes the classes are indexed 0...N\n '''\n return -T.mean(T.log(self.P)[T.arange(y.shape[0]),y])\n def WeightedNLL(self):\n '''\n constructs a NLL function that weights the signal \n (can be used to balance MC yields)\n '''\n return lambda y,w : -T.mean(w*T.log(self.P)[T.arange(y.shape[0]),y])\n def WindowedWeightedNLL(self):\n return lambda y,w,mask : -T.mean(w*T.log(self.P)[T.arange(y.shape[0]),y]*mask)\n def aNLL(self,y):\n '''\n OBSOLETE - Use WeightedNLL (more general)\n Asymmetric NLL loss\n gives more weight to classes with higher numbers\n (i.e. y=1 errors are penalized more than y=0)\n this assumes the classes are indexed 0...N\n '''\n return -T.mean((1*y+1)*T.log(self.P)[T.arange(y.shape[0]),y])\n def MSE(self,y):\n '''\n Mean square error loss\n only works for signal/background discrimination currently\n '''\n return T.mean((self.P[T.arange(y.shape[0]),1]-y)**2)\n def BoverS2(self,y):\n '''\n sqrt(B)/S loss, computed as B/S**2\n '''\n return T.sum(self.P[T.arange(y.shape[0]),1]*(1-y)) / (T.sum(self.P[T.arange(y.shape[0]),1]*y)**2)\n def BGReg(self,y):\n '''\n crappy regularization\n '''\n probs = self.P[T.arange(y.shape[0]),1]\n return T.max(probs*(1-y)) - T.min(probs*(1-y))\n def BGBinnedReg(self,y,varBinned):\n '''\n regularizes background efficiency in a binned variable\n '''\n # baseHist = 0\n probs = self.P[T.arange(y.shape[0]),1]\n baseHist = T.bincount(varBinned,1-y)\n selectedHist = T.bincount(varBinned,(1-y)*probs)\n indices = baseHist.nonzero()\n # ratioHist = selectedHist/baseHist\n ratioHist = selectedHist[indices]/baseHist[indices]\n # return T.std(selectedHist/baseHist)\n rVal = ratioHist - T.mean(ratioHist)\n return T.sum(rVal*rVal)\n def BGBinnedYield(self,y,varBinned):\n '''\n regularizes background yield in a binned variable\n '''\n probs = self.P[T.arange(y.shape[0]),1]\n selectedHist = T.bincount(varBinned,(1-y)*probs)\n rVal = (selectedHist - T.mean(selectedHist))/T.sum(selectedHist)\n return T.mean(rVal*rVal)\n def evalSelectedHist(self,y,varBinned):\n probs = self.P[T.arange(y.shape[0]),1]\n selectedHist = T.bincount(varBinned,(1-y)*probs)\n return selectedHist\n def getTrainer(self,lossType=\"NLL\"):\n '''\n return a function to do MBSGD on (trainX,trainY)\n '''\n trainY = T.ivector('y')\n alpha = T.dscalar('a')\n lowIdx = T.iscalar()\n highIdx = T.iscalar()\n trainX = T.matrix()\n if lossType==\"aNLL\":\n loss = self.aNLL(trainY)\n elif lossType=='MSE':\n loss = self.MSE(trainY)\n else:\n loss = self.NLL(trainY)\n dW = T.grad(cost = loss, wrt = self.W)\n db = T.grad(cost = loss, wrt = self.b)\n updates = [(self.W,self.W - alpha * dW), (self.b,self.b - alpha * db)]\n trainer = theano.function(\n inputs = [trainX,trainY,alpha],\n outputs = loss,\n updates=updates,\n givens = {\n self.input : trainX,\n },\n allow_input_downcast=True\n )\n return trainer\n","sub_path":"Classifiers/Logistic.py","file_name":"Logistic.py","file_ext":"py","file_size_in_byte":4416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"147890187","text":"import urllib.request\nfrom bs4 import BeautifulSoup\nimport re\nfrom datetime import datetime\nimport time\nimport schedule\n\njh = []\nsh = []\n\ndef job():\n datetime.today()\n date = datetime.today().strftime(\"%Y-%m-%d.md\")\n date = date[2:]\n week = ['(월)', '(화)', '(수)', '(��)', '(금)', '(토)', '(일)']\n day = week[datetime.today().weekday()]\n # 현재 날짜와 시간을 변수들에 저장한다.\n\n url = \"https://github.com/jeonjeunghoon/TIL/tree/master\"\n web = urllib.request.urlopen(url)\n res = web.read()\n soup = BeautifulSoup(res, 'html.parser')\n keywords = soup.find_all('a', class_='js-navigation-open link-gray-dark')\n keywords = [each_line.get_text().strip() for each_line in keywords[:10000000]]\n if date in keywords:\n date = date[:8]\n jh_res = date + day + \": O\"\n jh.append(jh_res)\n else:\n date = date[:8]\n jh_res = date + day + \": X\"\n jh.append(jh_res)\n\n url = \"\"\n web = urllib.request.urlopen(url)\n res = web.read()\n soup = BeautifulSoup(res, 'html.parser')\n keywords = soup.find_all('a', class_='js-navigation-open link-gray-dark')\n keywords = [each_line.get_text().strip() for each_line in keywords[:10000000]]\n if date in keywords:\n date = date[:8]\n sh_res = date + day + \": O\"\n sh.append(sh_res)\n else:\n date = date[:8]\n sh_res = date + day + \": X\"\n sh.append(sh_res)\n # 크롤링 코드\n\n import telegram\n\n token = '1629335207:AAEgc2pO4-xVY1L_gJjAhlCubrdGOzo7xjs'\n bot = telegram.Bot(token=token)\n chat_id = \"-1001353446448\"\n jh_text = \"증훈의 기록\\n\" + jh_res\n bot.sendMessage(chat_id = chat_id , text=jh_text)\n sh_text = \"세환의 기록\\n\" + sh_res\n bot.sendMessage(chat_id = chat_id , text=sh_text)\n # 텔레그램 봇과 연동하는 코드\n\nschedule.every().day.at(\"23:59\").do(job)\n# 매일 23:59 마다 코드 실행\n\nwhile True:\n schedule.run_pending()\n time.sleep(1)\n# 파이썬 스케쥴","sub_path":"til_bot.py","file_name":"til_bot.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"210361040","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nimport unittest\nimport doctest\nimport os\nfrom os.path import join as p\nimport tempfile\nimport shutil\nimport pytest\nfrom collections import namedtuple\ntry:\n from unittest.mock import MagicMock\nexcept ImportError:\n from mock import MagicMock\nfrom .doctest_plugin import ALLOW_UNICODE, UnicodeOutputChecker\nfrom .TestUtilities import xfail_without_db\n\n\ndoctest.OutputChecker = UnicodeOutputChecker\n\n\n@pytest.mark.inttest\nclass READMETest(unittest.TestCase):\n ''' Executes doctests '''\n def setUp(self):\n xfail_without_db()\n self.startdir = os.getcwd()\n self.testdir = tempfile.mkdtemp(prefix=__name__ + '.')\n shutil.copytree('.pow', p(self.testdir, '.pow'), symlinks=True)\n shutil.copyfile('README.md', p(self.testdir, 'README.md'))\n shutil.copyfile('readme.conf', p(self.testdir, 'readme.conf'))\n os.chdir(self.testdir)\n\n def tearDown(self):\n os.chdir(self.startdir)\n shutil.rmtree(self.testdir)\n\n def test_readme(self):\n [failure_count, return_count] = doctest.testfile(\"README.md\", module_relative=False,\n optionflags=(ALLOW_UNICODE | doctest.ELLIPSIS))\n self.assertEqual(failure_count, 0)\n\n\nclass SphinxTest(unittest.TestCase):\n ''' Executes doctests in Sphinx documentation '''\n def setUp(self):\n self.startdir = os.getcwd()\n self.testdir = tempfile.mkdtemp(prefix=__name__ + '.')\n shutil.copytree('docs', p(self.testdir, 'docs'))\n os.chdir(self.testdir)\n\n def tearDown(self):\n os.chdir(self.startdir)\n shutil.rmtree(self.testdir)\n\n def execute(self, fname, **kwargs):\n failure_count, _ = doctest.testfile(p('docs', fname + '.rst'), module_relative=False,\n optionflags=(ALLOW_UNICODE | doctest.ELLIPSIS), **kwargs)\n self.assertEqual(failure_count, 0)\n\n def test_adding_data(self):\n # Setup a class imported by docs for demonstration purposes\n from PyOpenWorm.dataObject import DataObject, DatatypeProperty\n from PyOpenWorm.context import Context\n Load = lambda *args, **kwargs: [namedtuple('Record', ('pnum', 'flns', 'hrds'))(12, 1.0, 100)]\n\n class Widget(DataObject):\n hardiness = DatatypeProperty()\n fullness = DatatypeProperty()\n part_number = DatatypeProperty()\n\n def identifier_augment(self):\n return self.make_identifier_direct(str(self.part_number.onedef()))\n\n def defined_augment(self):\n return self.part_number.has_defined_value()\n\n ctx = Context(ident='http://example.org/data/imports/BDW_Widgets_2018-2019')\n ctx.mapper.process_class(Widget)\n\n ctx(Widget)(part_number=15)\n ctx(Widget)(part_number=17)\n ctx(Widget)(part_number=20)\n\n self.execute('adding_data', extraglobs={'Load': Load, 'Widget': Widget, 'ctx18': ctx})\n\n def test_making_dataObjects(self):\n self.execute('making_dataObjects')\n","sub_path":"tests/DocumentationTest.py","file_name":"DocumentationTest.py","file_ext":"py","file_size_in_byte":3116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"15296257","text":"from django.shortcuts import render,get_object_or_404\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.db import models\nfrom django.forms.models import model_to_dict\nfrom django.contrib.auth.models import User,Group\nfrom django.contrib.auth import authenticate, login\nimport json\nimport datetime\nfrom django.contrib.auth import logout\n\nfrom dateutil import parser\n\nfrom models import Event,Location,Task,Profile,Usercategory,Frontline\n\nfrom django.template import RequestContext, loader\n\n\n# Create your views here.\n\n\nclass ComplexEncoder(json.JSONEncoder):\n def default(self, obj):\n try:\n return super(ComplexEncoder, obj).default(obj)\n except TypeError:\n return str(obj)\n\n\ndef homeindex(request):\n# return HttpResponse(\"Hello, handstack.\")\n template=loader.get_template('home.html')\n context = RequestContext(request, {\n 'pageinfo': 5,\n })\n return HttpResponse(template.render(context))\n\n\ndef htmlserve(request,path,filename=\"thankyou.html\"):\n# return HttpResponse(\"Hello, handstack.\")\n template=loader.get_template(path)\n context = RequestContext(request, {\n 'pageinfo': filename,\n })\n return HttpResponse(template.render(context))\n\n\n\ndef htmlevent(request,eid):\n# return HttpResponse(\"Hello, handstack.\")\n template=loader.get_template(\"eventemplate.html\")\n q=Event.objects\n tdata=dict()\n cdata=dict()\n\n q=q.filter(id=int(eid))\n\n for thing in q.all():\n cdata=thing.to_dict()\n\n context = RequestContext(request, cdata)\n return HttpResponse(template.render(context))\n\n\n\ndef bigdump(request):\n data=dict()\n cdata=dict()\n for thing in Event.objects.all():\n cdata[str(thing.id)]=thing.to_dict()\n data[\"events\"]=cdata\n data[\"success\"]=True\n return HttpResponse(json.dumps(data),content_type=\"application/json\")\n\n\n\ndef frontlinedump(request):\n data=dict()\n cdata=dict()\n if 'code' in request.GET and request.GET[\"code\"]==\"frob\":\n for thing in Frontline.objects.all():\n cdata[str(thing.id)]=thing.to_dict()\n data[\"contacts\"]=cdata\n data[\"success\"]=True\n else:\n data[\"success\"]=True\n return HttpResponse(json.dumps(data),content_type=\"application/json\")\n\n\n\ndef taskdump(request):\n data=dict()\n cdata=dict()\n for thing in Task.objects.all():\n cdata[str(thing.id)]=thing.to_dict()\n data[\"events\"]=cdata\n data[\"success\"]=True\n return HttpResponse(json.dumps(data),content_type=\"application/json\")\n\ndef search(request):\n data=dict()\n cdata=dict()\n \n q=Event.objects\n latDist=1.0\n lonDist=1.0\n ringwdth=0.1\n qdata=dict()\n\n if 'eventid' in request.GET:\n q=q.filter(id=int(request.GET['eventid']) )\n\n if 'latDist' in request.GET:\n latDist=float(request.GET['latDist'])\n if 'lonDist' in request.GET:\n lonDist=float(request.GET['lonDist'])\n\n if 'startafter' in request.GET:\n startafter=request.GET['startafter']\n q=q.filter(eventComputedStartTime__gt=parser.parse(startafter))\n\n if 'startbefore' in request.GET:\n startbefore=request.GET['startbefore']\n q=q.filter(eventComputedStartTime__lt=parser.parse(startbefore))\n \n if 'ring' in request.GET:\n if 'latitude' in request.GET:\n lat=float(request.GET['latitude'])\n if 'longitude' in request.GET:\n lon=float(request.GET['longitude'])\n ring=float(request.GET['ring'])\n\n if 'latitude' in request.GET:\n lat=float(request.GET['latitude'])\n qdata['latitude']=lat\n\n q=q.filter(latitude__range=(lat-latDist, lat+latDist))\n if 'longitude' in request.GET:\n lon=float(request.GET['longitude'])\n qdata['longitude']=lon\n q=q.filter(longitude__range=(lon-lonDist, lon+lonDist))\n\n\n\n for thing in q.all():\n cdata[str(thing.id)]=thing.to_dict()\n data[\"events\"]=cdata\n qdata['lonDist']=lonDist\n qdata['latDist']=latDist\n data['queryterms']=qdata\n data[\"success\"]=True\n return HttpResponse(json.dumps(data, cls=ComplexEncoder),content_type=\"application/json\")\n\ndef tasksearch(request):\n data=dict()\n cdata=dict()\n \n q=Event.objects\n\n if 'eventid' in request.GET:\n q=q.get(id__exact=int(request.GET['eventid']))\n for thing in q.tasklist.all():\n cdata[str(thing.id)]=thing.to_dict()\n data[\"tasks\"]=cdata\n data[\"success\"]=True\n return HttpResponse(json.dumps(data, cls=ComplexEncoder),content_type=\"application/json\")\n\n#Modify models too\ndef rmtask(request):\n return HttpResponse('{\"success\": true}',content_type=\"application/json\")\n\ndef rmevent(request):\n q=Event.objects\n #If Permission\n if 'eventid' in request.GET:\n q=q.get(id__exact=int(request.GET['eventid']))\n \n q.hidemode=1\n q.save()\n data[\"success\"]=True\n #Handle orphan tasks\n return HttpResponse(json.dumps(data, cls=ComplexEncoder),content_type=\"application/json\")\n\n\ndef rsvpme(request):\n data=dict()\n cdata=dict()\n q=Event.objects\n if request.user.is_authenticated():\n if 'eventid' in request.GET:\n q=q.get(id__exact=int(request.GET['eventid']))\n if not request.user.id in q.EventRSVPS.all():\n q.EventRSVPS.add(request.user)\n q.save()\n data[\"success\"]=True\n return HttpResponse(json.dumps(data, cls=ComplexEncoder),content_type=\"application/json\")\n else:\n data[\"success\"]=False\n return HttpResponse(json.dumps(data, cls=ComplexEncoder),content_type=\"application/json\")\n\n\ndef unrsvpme(request):\n data=dict()\n\n bdata=dict()\n cdata=dict()\n q=Event.objects\n if request.user.is_authenticated():\n if 'eventid' in request.POST:\n q=q.get(id__exact=int(request.POST['eventid']))\n q.EventRSVPS.remove(request.user)\n q.save()\n data[\"success\"]=True\n return HttpResponse(json.dumps(data, cls=ComplexEncoder),content_type=\"application/json\")\n else:\n data[\"success\"]=False\n return HttpResponse(json.dumps(data, cls=ComplexEncoder),content_type=\"application/json\")\n\n\ndef myevents(request):\n data=dict()\n cdata=dict()\n bdata=dict()\n \n q=Event.objects\n if request.user.is_authenticated():\n q=request.user.eventrsvplist\n\n data[\"success\"]=True\n for thing in q.all():\n cdata[str(thing.id)]=thing.to_dict()\n data[\"eventrsvplist\"]=cdata\n return HttpResponse(json.dumps(data, cls=ComplexEncoder),content_type=\"application/json\")\n else:\n data[\"success\"]=False\n return HttpResponse(json.dumps(data, cls=ComplexEncoder),content_type=\"application/json\")\n\n\n\n\n\ndef taketask(request):\n data=dict()\n cdata=dict()\n q=Task.objects\n if request.user.is_authenticated():\n if 'taskid' in request.POST:\n q=q.get(id__exact=int(request.POST['taskid']))\n if not request.user.id in q.assignments.all():\n q.assignments.add(request.user)\n q.save()\n data[\"success\"]=True\n return HttpResponse(json.dumps(data, cls=ComplexEncoder),content_type=\"application/json\")\n else:\n data[\"success\"]=False\n return HttpResponse(json.dumps(data, cls=ComplexEncoder),content_type=\"application/json\")\n\n\n\n\n\n\ndef givetask(request):\n data=dict()\n cdata=dict()\n t=Task.objects\n u=User.objects\n if request.user.is_authenticated():\n if 'taskid' in request.GET and 'uid' in request.POST: \n t=t.get(id__exact=int(request.POST['taskid']))\n u=u.get(id__exact=int(request.POST['userid']))\n e=t.event_set.all()[0]\n data[\"E\"]=e.to_dict()\n\n if request.user.id == e.creator.id:\n data[\"owner\"]=\"ok\"\n t.assignments.add(u)\n t.save()\n data[\"success\"]=True\n return HttpResponse(json.dumps(data, cls=ComplexEncoder),content_type=\"application/json\")\n else:\n data[\"success\"]=False\n return HttpResponse(json.dumps(data, cls=ComplexEncoder),content_type=\"application/json\")\n\n\ndef droptask(request):\n data=dict()\n\n cdata=dict()\n q=Task.objects\n if request.user.is_authenticated():\n if 'taskid' in request.GET:\n q=q.get(id__exact=int(request.GET['taskid']))\n q.assignments.remove(request.user)\n q.save()\n data[\"success\"]=True\n return HttpResponse(json.dumps(data, cls=ComplexEncoder),content_type=\"application/json\")\n else:\n data[\"success\"]=False\n return HttpResponse(json.dumps(data, cls=ComplexEncoder),content_type=\"application/json\")\n\n\ndef mytasks(request):\n data=dict()\n cdata=dict()\n \n q=Task.objects\n if request.user.is_authenticated():\n q=request.user.task_set\n\n data[\"success\"]=True\n for thing in q.all():\n cdata[str(thing.id)]=thing.to_dict()\n data[\"tasklist\"]=cdata\n return HttpResponse(json.dumps(data, cls=ComplexEncoder),content_type=\"application/json\")\n else:\n data[\"success\"]=False\n return HttpResponse(json.dumps(data, cls=ComplexEncoder),content_type=\"application/json\")\n\n\n\n\n\n\n\n\n\n\ndef blockuser(request):\n return HttpResponse('{\"success\": true}',content_type=\"application/json\")\n \ndef obliviate(request):\n #If user=admin\n for thing in Event.objects.all():\n thing.delete()\n for thing in Task.objects.all():\n thing.delete()\n return HttpResponse('{\"success\": true}',content_type=\"application/json\")\n\n@csrf_exempt\ndef mkevent(request):\n newevent=Event();\n newevent.latitude=0.0\n newevent.longitude=0.0\n\n for field in request.POST:\n setattr(newevent,field, request.POST[field])\n if request.user.is_authenticated():\n newevent.creator=request.user\n newevent.eventComputedStartTime=parser.parse(newevent.eventStartTime)\n newevent.eventComputedEndTime=newevent.eventComputedStartTime + datetime.timedelta(seconds=int(float(newevent.eventDuration)))\n newevent.save()\n newevent.EventRSVPS.add(request.user)\n newevent.save()\n\n else: \n return HttpResponse('{\"success\": false }',content_type=\"application/json\")\n\n return HttpResponse('{\"success\": true, \"id\": ' + str(newevent.id) + '}',content_type=\"application/json\")\n\n\n\nfrom django import forms\n\nclass UploadFileForm(forms.Form):\n eventid = forms.CharField(max_length=50)\n eventimage = forms.FileField()\n\n\n\n@csrf_exempt\ndef eventimage(request):\n data=dict()\n e=Event.objects\n e=e.get(id__exact=int(request.POST['eventid'])) \n form = UploadFileForm(request.POST, request.FILES)\n e.image=request.FILES['eventimage']\n e.save() \n data[\"success\"]=True\n return HttpResponse(json.dumps(data),content_type=\"application/json\")\n\n\n#import magic #wtf python\n\n\n@csrf_exempt\ndef geteventimage(request):\n if \"eventid\" in request.GET:\n e=Event.objects\n e=get_object_or_404(Event,id__exact=int(request.GET['eventid']))\n if \"thumbnail\" in request.GET:\n file=e.image_thumbnail\n else:\n file=e.image\n handle=file._get_file()\n data=handle.read()\n type=magic.from_buffer(data,mime=True)\n if \"gid\" in request.GET:\n cat=usercategory.objects\n cat=e.get(id__exact=int(request.GET['eventid']))\n file=e.image\n handle=file._get_file()\n data=handle.read()\n type=magic.from_buffer(data,mime=True)\n\n return HttpResponse(data,content_type=type)\n\n\n\n\n\n\n\n\n\n@csrf_exempt\ndef frontline(request):\n newF=Frontline();\n for field in request.POST:\n setattr(newF,field, request.POST[field])\n #get event\n newF.save()\n template=loader.get_template('thankyou.html')\n context = RequestContext(request, {\n 'pageinfo': \"We appreciate your interest. \",\n })\n return HttpResponse(template.render(context))\n\n\n\n\n\n\n\n@csrf_exempt\ndef mktask(request):\n newtask=Task();\n for field in request.POST:\n setattr(newtask,field, request.POST[field])\n user = request.user\n newtask.creator=user\n newtask.save()\n #get event\n parentevent=Event.objects.get(id__exact=int(request.POST['eventid']))\n #add task to tasklist\n parentevent.tasklist.add(newtask)\n #save event\n parentevent.save() \n return HttpResponse('{\"success\": true, \"id\": ' + str(newtask.id) + ', \"eventName\": \"' + str(parentevent.eventName) + '\"}',content_type=\"application/json\")\n\n\n@csrf_exempt\ndef mkgroup(request):\n user = request.user\n newgroup,created=Group.objects.get_or_create(name=request.GET['name'])\n newcat=Usercategory()\n newcat.group=newgroup\n \n newgroup.save()\n\n newgroup.user_set.add(user)\n \n newgroup.save()\n newcat.save()\n return HttpResponse('{\"success\": true, \"gid\": ' + str(newcat.id) + '}',content_type=\"application/json\")\n\n\n\n#get group image (overload get user image)\n\n\n@csrf_exempt\ndef listgroups(request):\n data=dict()\n data[\"success\"]=True\n return HttpResponse(json.dumps(data),content_type=\"application/json\")\n\n\n@csrf_exempt\ndef joingroup(request):\n data=dict()\n data[\"success\"]=True\n return HttpResponse(json.dumps(data),content_type=\"application/json\")\n\n\n@csrf_exempt\ndef leavegroup(request):\n data=dict()\n data[\"success\"]=True\n return HttpResponse(json.dumps(data),content_type=\"application/json\")\n\n\n@csrf_exempt\ndef kickuserfromgroup(request):\n data=dict()\n data[\"success\"]=True\n return HttpResponse(json.dumps(data),content_type=\"application/json\")\n\n\n\n\n@csrf_exempt\ndef LookUpUserName(request):\n data=dict()\n try:\n user = User.objects.get(username=request.GET['username'])\n except User.DoesNotExist:\n data[\"uid\"]=-1\n data[\"success\"]=True\n return HttpResponse(json.dumps(data),content_type=\"application/json\")\n data[\"success\"]=True\n data[\"uid\"]=user.id\n return HttpResponse(json.dumps(data),content_type=\"application/json\")\n\n\n\n\n\n\n\ndef logout_view(request):\n logout(request)\n data=dict();\n data[\"success\"]=True\n return HttpResponse(json.dumps(data, cls=ComplexEncoder),content_type=\"application/json\")\n\ndef whoami(request):\n data=dict();\n if request.user.is_authenticated():\n data[\"success\"]=True\n data[\"uid\"]=request.user.id\n return HttpResponse(json.dumps(data, cls=ComplexEncoder),content_type=\"application/json\")\n else:\n data[\"success\"]=True\n data[\"uid\"]=-1\n return HttpResponse(json.dumps(data, cls=ComplexEncoder),content_type=\"application/json\")\n\n\n#Registration name lookup\n\n@csrf_exempt\ndef userregister(request):\n email=request.POST['email']\n pword=request.POST['pword']\n uname=request.POST['username']\n data=dict();\n #test for already registered\n \n newuser = User.objects.create_user(uname, email, pword)\n user = authenticate(username=uname, password=pword)\n login(request, user)\n\n profile=Profile()\n profile.user=user\n profile.save()\n\n data[\"success\"]=True\n data[\"uid\"]=str(user.id)\n\n return HttpResponse(json.dumps(data, cls=ComplexEncoder),content_type=\"application/json\")\n \n\n\n\n\n\n#Login Form\n\n\n\n#login Handler\n@csrf_exempt\ndef userlogin(request):\n pword=request.POST['pword']\n uname=request.POST['username']\n\n thisuser = authenticate(username=uname, password=pword)\n\n data=dict()\n if not thisuser or not thisuser.is_active:\n data[\"success\"]=False\n data[\"reason\"]=\"Authentication failed.\"\n return HttpResponse(json.dumps(data, cls=ComplexEncoder),content_type=\"application/json\")\n else:\n login(request, thisuser)\n data[\"success\"]=True\n data[\"uid\"]=thisuser.id\n return HttpResponse(json.dumps(data, cls=ComplexEncoder),content_type=\"application/json\")\n\n","sub_path":"event/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":15835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"217994232","text":"# -*- coding:utf-8 -*-\n\n# sub app setting\n# try not to include function or class\nimport os\n\nTEMPLATE_PATH = 'app/'\n\nSECRET_KEY = 'kgIq_JZKLEm18s-NbUD4-wlyBJReid9FVmcximf1'\nACCESS_KEY = 'WFSZh7ihx3Xm-p7UkRBWUJDZj5JUwkygWRf4q_3X'\n\nQINIU_BUCKET = 'novapps'\nQINIU_HOST = 'http://novapps.qiniucdn.dandanjiang.tv'\n\nif os.path.exists(os.path.join(os.path.dirname(os.path.abspath(__file__)), '__test__')):\n QINIU_BUCKET = 'test'\n QINIU_HOST = 'http://7xlipz.com1.z0.glb.clouddn.com'\n","sub_path":"taoke-sever/zhuzhu-service/apps/app/setting.py","file_name":"setting.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"114949982","text":"import torch\nfrom torch.utils.data import DataLoader\nimport torch.optim as optim\nimport torch.nn as nn\n\nimport torchvision\nfrom torchvision.datasets import MNIST\nfrom model import Encoder_FC, Discriminator_FC, Decoder_FC, initialize_weights, Encoder, Discriminator, Decoder\n\nimport numpy as np\nimport config\nfrom utils import load_checkpoint, save_checkpoint, save_latent_distribution, save_reconstructed_images, get_digit_distribution, plot_batch_latent_distribution\nimport random\n\n# Load data\ntrain_Dataset = MNIST(root=\"dataset/\", train=True, transform=config.Mytransforms, download=True)\ntrain_Loader = DataLoader(train_Dataset, shuffle=True, batch_size=config.BATCH_SIZE, pin_memory=True)\ntest_Dataset = MNIST(root=\"dataset/\", train=False, transform=config.Mytransforms, download=True)\ntest_Loader = DataLoader(test_Dataset, shuffle=True, batch_size=100, pin_memory=True)\n\n\n# Mode - Semi-Supervised\nlatent_dim = config.latent_space_dim + config.NUM_CLASSES + 1\n\n# Model\nif True: # use FC architectures\n gen = Encoder_FC().to(config.device)\n disc = Discriminator_FC(latent_dim).to(config.device)\n decoder = Decoder_FC().to(config.device)\n dir_string = \"FC_SSAAE\"\n saved_model_name = 'SSAEE_FC_checkpoint.pth.tar'\nelse: # use CNN architecture\n gen = Encoder().to(config.device)\n disc = Discriminator(latent_dim).to(config.device)\n decoder = Decoder().to(config.device)\n dir_string = \"CNN_SSAAE\"\n saved_model_name = 'SSAEE_CNN_checkpoint.pth.tar'\n\ninitialize_weights(gen)\ninitialize_weights(disc)\ninitialize_weights(decoder)\n\n# Optimizer\nopt_gen = optim.Adam(params=gen.parameters(), lr=0.0002, betas=(config.ADAM_BETA1, config.ADAM_BETA2))\nopt_disc = optim.Adam(params=disc.parameters(), lr=0.0002, betas=(config.ADAM_BETA1, config.ADAM_BETA2))\nopt_decoder = optim.Adam(params=decoder.parameters(), lr=0.0001,\n betas=(config.ADAM_BETA1, config.ADAM_BETA2))\n\nscheduler_gen = optim.lr_scheduler.MultiStepLR(opt_gen, gamma=0.316, milestones=[100, 1000]) # 0.316 = sqrt(0.1)\nscheduler_disc = optim.lr_scheduler.MultiStepLR(opt_disc, gamma=0.316, milestones=[100, 1000])\nscheduler_decoder = optim.lr_scheduler.MultiStepLR(opt_decoder, gamma=0.316, milestones=[100, 1000])\n\n# Loss\nloss_BCE = nn.BCELoss()\nloss_MSE = nn.MSELoss()\n\n# Tensor-board parameters\nmy_epoch = 0\nisSaved = False # save once in every chosen num of epochs\nunlabeled_ratio = 0.8\n# Load pre-trained model\nload_model = True\ntry:\n if load_model:\n my_epoch = load_checkpoint(torch.load(saved_model_name), gen, disc, decoder, opt_gen, opt_disc, opt_decoder,\n scheduler_gen, scheduler_disc, scheduler_decoder)\nexcept FileNotFoundError:\n print(\"Model file doesn't exist\")\n\n# --------------------------------\n# --------Training ---------------\n\ngen.train()\ndisc.train()\ndecoder.train()\n\n\n# start Train loop\nfor epoch in range(my_epoch, config.NUM_EPOCHS):\n # save checkpoint\n if epoch % 10 == 0 or epoch == config.NUM_EPOCHS - 1:\n checkpoint = {'gen_state_dict': gen.state_dict(), 'gen_optimizer': opt_gen.state_dict(),\n 'disc_state_dict': disc.state_dict(), 'disc_optimizer': opt_disc.state_dict(),\n 'decoder_state_dict': decoder.state_dict(), 'decoder_optimizer': opt_decoder.state_dict(),\n 'epoch_num': epoch, 'decoder_scheduler': scheduler_decoder.state_dict(),\n 'gen_scheduler': scheduler_gen.state_dict(), 'disc_scheduler': scheduler_disc.state_dict()}\n\n save_checkpoint(checkpoint, filename=saved_model_name)\n\n for batch_idx, (image, label) in enumerate(train_Loader):\n image = image.to(config.device)\n label = label.to(config.device)\n\n this_batch_size = len(image)\n hot_vector = np.zeros((this_batch_size, config.NUM_CLASSES + 1), dtype=np.float32)\n idx_unlabeled = random.sample(range(0, this_batch_size), int(this_batch_size * unlabeled_ratio))\n idx_labeled = list(set(range(0, this_batch_size)) - set(idx_unlabeled))\n hot_vector[idx_unlabeled, -1] = 1\n np_label = label.cpu().numpy()\n hot_vector[idx_labeled, np_label[idx_labeled]] = 1\n\n hot_vector = torch.tensor(hot_vector).unsqueeze(2).unsqueeze(3).to(config.device)\n label[idx_unlabeled] = torch.randint(0, 10, (int(this_batch_size * unlabeled_ratio),)).to(config.device)\n\n # ----------------------------------\n # Reconstruction training:\n latentCode = gen(image) # same as fake_latentCode, with changed\n dec_output = decoder(latentCode)\n loss_AE = loss_MSE(dec_output, image)\n\n decoder.zero_grad()\n gen.zero_grad()\n\n loss_AE.backward()\n opt_gen.step()\n opt_decoder.step()\n\n # ----------------------------------\n # Adversarial training:\n\n # train Discriminator:\n fake_latentCode = gen(image)\n samples_new = get_digit_distribution(label, num_elements=this_batch_size)\n # plot_batch_latent_distribution(samples_new, label) # verify p(x) distribution.\n real_latentCode = torch.tensor(samples_new, dtype=torch.float32).unsqueeze(2).unsqueeze(3).to(config.device)\n\n disc_real = disc(torch.cat((real_latentCode, hot_vector), 1)).view(-1)\n loss_disc_real = loss_BCE(disc_real, torch.ones_like(disc_real))\n disc_fake = disc(torch.cat((fake_latentCode, hot_vector), 1)).view(-1)\n loss_disc_fake = loss_BCE(disc_fake, torch.zeros_like(disc_fake))\n loss_disc = 0.5 * (loss_disc_real + loss_disc_fake)\n\n disc.zero_grad()\n loss_disc.backward(retain_graph=True)\n opt_disc.step()\n\n # Train Generator\n fake_latentCode = gen(image)\n disc_fake = disc(torch.cat((fake_latentCode, hot_vector), 1)).view(-1)\n loss_gen = loss_BCE(disc_fake, torch.ones_like(disc_fake))\n gen.zero_grad()\n loss_gen.backward()\n opt_gen.step()\n\n # Print losses occasionally and print to tensorboard\n if batch_idx % 225 == 0 and batch_idx > 0:\n print(\n f\"Epoch [{epoch + 1}/{config.NUM_EPOCHS}] Batch {batch_idx}/{len(train_Loader)} \\\n Loss Disc: {loss_disc:.4f}, loss G: {loss_gen:.4f}, loss AE: {loss_AE:.4f}\"\n )\n\n if epoch == config.NUM_EPOCHS - 1 or (epoch % 10 == 0 and not isSaved):\n isSaved = True\n with torch.no_grad():\n img_orig_image = torchvision.utils.make_grid(image, normalize=True)\n img_orig_image = img_orig_image.permute(1, 2, 0).detach().cpu().numpy()\n img_reconstructed_image = torchvision.utils.make_grid(dec_output, normalize=True)\n img_reconstructed_image = img_reconstructed_image.permute(1, 2, 0).detach().cpu().numpy()\n\n # print('save figures')\n save_reconstructed_images(img_orig_image, img_reconstructed_image, epoch, dir_string)\n save_latent_distribution(test_Loader, gen, epoch, dir_string)\n\n isSaved = False\n scheduler_gen.step()\n scheduler_disc.step()\n scheduler_decoder.step()\n","sub_path":"AAE_reconstruct/train_SSAAE.py","file_name":"train_SSAAE.py","file_ext":"py","file_size_in_byte":7158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"96785761","text":"q=int(input())\narr=[]\nb=[]\nfor i in range (q):\n s=input()\n t=input()\n arr.append(s)\n b.append(t)\ndef checkSimilar(x,y):\n count=0\n for i in range (len(x)):\n for j in range (i-1,i+1):\n if (x[i])==(y[j]):\n if (i==j):\n count+=2\n i+=1\n continue\n count+=1\n continue\n else:\n if (x[i-1]==y[j]):\n count+=1\n continue\n return count\nfor i in range (q):\n if (checkSimilar(arr[i],b[i])>=len(arr[i])-1):\n print (checkSimilar(arr[i],b[i]))\n print (\"YES\") \n else:\n print (\"NO\") \n","sub_path":"python code/SimilarStr.py","file_name":"SimilarStr.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"513355719","text":"import torch\nimport pickle\nimport numpy as np\nfrom matplotlib import rcParams\nrcParams['font.family'] = 'serif'\nimport matplotlib.pyplot as plt\nfrom matplotlib import gridspec\nimport timeit\nimport pandas as pd\nimport resource\nimport os\nimport Parameters as param\n\n# rescaling function\ndef rescale(scaled_array, max_array, min_array):\n domain = max_array - min_array\n rescaled_array = np.empty([1, domain.size])\n for j in range(len(scaled_array)):\n row_change = np.array([])\n for a in range(domain.size):\n row_change = np.append(row_change, domain[a] * scaled_array[j, a])\n relative_change = row_change + min_array\n rescaled_array = np.vstack((rescaled_array, relative_change))\n\n rescaled_array = np.delete(rescaled_array, 0, axis=0)\n return rescaled_array\n\n\n# mean array function\ndef mean_array(array):\n transpose = array.T\n mean = np.array([])\n for i in range(len(transpose)):\n mean = np.append(mean, np.mean(transpose[i]))\n\n return mean\n\n\ndef init_model(ML_Model, input_array, output_array):\n # model exporter\n if ML_Model == \"Neural Network\":\n return NN_init(input_array, output_array)\n\n elif ML_Model == \"Random Forest\":\n return RF_init(input_array)\n\n elif ML_Model == \"Autoencoder\":\n return AE_init(input_array, output_array)\n\n else:\n print(\"Failed to compile program, please correct ML_Model syntax in Parameters.py\")\n\n\ndef NN_init(input_array, output_array):\n from model_training_files import NN\n import matplotlib\n matplotlib.use('TkAgg')\n\n # load neural network class\n neural_network = NN\n\n torch.cuda.empty_cache()\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n # initialise mlp structures\n NN_struct = neural_network.NN(input_dim=input_array.shape[1], output_dim=output_array.shape[1],\n n_hidden=128)\n\n # upload trained algorithim states\n NN_struct.load_state_dict(torch.load('./supporting_data_files/NN.pt',\n map_location=torch.device('cpu')))\n NN_struct.to(device)\n NN_struct.eval()\n instance_tensor = torch.from_numpy(input_array).to(device)\n\n return instance_tensor, NN_struct, device\n\n\ndef RF_init(input_array):\n # load pickle files\n regressor = pd.read_pickle(open('./supporting_data_files/Random_Forest.pkl', 'rb'))\n\n return input_array, regressor\n\ndef AE_init(input_array, output_array):\n from model_training_files import Autoencoder\n from model_training_files import Neural_Network\n\n # declare imported files as variables\n neural_network = Neural_Network\n autoencoder = Autoencoder\n\n torch.cuda.empty_cache()\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n layers = [512, 128, 64, 32]\n\n # initialise mlp structures\n nn_struct = neural_network.NN(input_dim=input_array.shape[1], output_dim=layers[3],\n n_hidden=512)\n ae_struct = autoencoder.Autoencoder(visible_dim=output_array.shape[1], coding_dim1=layers[0],\n coding_dim2=layers[1], coding_dim3=layers[2], coding_dim4=layers[3])\n\n # upload trained algorithim states\n nn_struct.load_state_dict(torch.load('./supporting_data_files/NN_512.pt',\n map_location=torch.device('cpu')))\n ae_struct.load_state_dict(torch.load('./supporting_data_files/Autoencoder_512.pt',\n map_location=torch.device('cpu')))\n\n nn_struct = nn_struct.to(device)\n ae_struct = ae_struct.to(device)\n nn_struct.eval()\n ae_struct.eval()\n\n input_tensor = torch.from_numpy(input_array).to(device)\n\n return input_tensor, nn_struct, ae_struct, device\n\n\ndef contour_plotter(output, prediction_error):\n # plot mean and error\n df = pickle.load(open('./supporting_data_files/coordinate_data_frame.pkl', 'rb'))\n pos_data = (np.asmatrix(df.iloc[:, :]))\n\n x_pos = np.array(pos_data[0, 0:5000]).flatten()\n y_pos = np.array(pos_data[1, 0:5000]).flatten()\n\n # prediction plot\n fig = plt.figure(0, figsize=(15, 8))\n spec = gridspec.GridSpec(ncols=3, nrows=1,\n width_ratios=[4, 1, 4])\n plt.subplot(spec[0])\n rect_top = plt.Rectangle((0.0025, 0.0975), 0.5, 0.4, fc='white')\n rect_bottom = plt.Rectangle((0.0025, 0.025), 0.55, -0.5225, fc='white')\n plt.gca().add_patch(rect_top)\n plt.gca().add_patch(rect_bottom)\n plt.tricontour(x_pos, y_pos, output, 200, linewidths=0, colors='k')\n plt.tricontourf(x_pos, y_pos, output, 200, cmap=plt.cm.jet)\n plt.title('Mean ' + param.Fluid_Property + ' Prediction Contour for ' + param.ML_Model)\n plt.xlabel('x (m)')\n plt.ylabel('y (m)')\n clb = plt.colorbar()\n clb.set_label(param.Fluid_Property + param.metric)\n\n # error plot\n plt.subplot(spec[2])\n rect_top = plt.Rectangle((0.0025, 0.0975), 0.5, 0.4, fc='white')\n rect_bottom = plt.Rectangle((0.0025, 0.025), 0.55, -0.5225, fc='white')\n plt.gca().add_patch(rect_top)\n plt.gca().add_patch(rect_bottom)\n plt.tricontour(x_pos, y_pos, prediction_error, 200, linewidths=0, colors='k')\n plt.tricontourf(x_pos, y_pos, prediction_error, 200, cmap=plt.cm.jet)\n plt.title('Mean ' + param.Fluid_Property + ' Error Contour for ' + param.ML_Model)\n plt.xlabel('x (m)')\n plt.ylabel('y (m)')\n clb = plt.colorbar()\n clb.set_label('Error (%)')\n\n plt.show()\n\ndef hist_plotter(error_mean):\n # histogram\n t_data_error, v_data_error = np.hsplit(error_mean, 2)\n\n temp_e = t_data_error.flatten()\n vel_e = v_data_error.flatten()\n\n t_data_error, v_data_error = np.hsplit(error_mean, 2)\n temp_err = t_data_error.flatten()\n vel_err = v_data_error.flatten()\n\n print(\"Mean Temperature Error = {:.3f}%, Max Temperature Error = {:.3f}%\"\n .format(np.mean(temp_e), np.max(temp_e)))\n print(\"Mean \" + param.Fluid_Property + \" Error = {:.3f}%, Max \" + param.Fluid_Property + \" Error = {:.3f}%\"\n .format(np.mean(vel_e), np.max(vel_e)))\n n_bins = 30\n cm = plt.cm.jet\n\n fig = plt.figure(1, figsize=(15, 8))\n spec = gridspec.GridSpec(ncols=3, nrows=1,\n width_ratios=[4, 1, 4])\n plt.subplot(spec[0])\n plt.title('Temperature Error Distribution for ' + param.ML_Model)\n plt.xlabel('Error Range (%)')\n plt.ylabel('Frequency')\n (counts, bins) = np.histogram(temp_err, n_bins)\n factor = 0.00002\n N, bins, patches = plt.hist(bins[:-1], bins, weights=counts * factor)\n plt.yscale('log')\n bin_centers = 0.5 * (bins[:-1] + bins[1:])\n col = bin_centers - min(bin_centers)\n col /= max(col)\n for c, p in zip(col, patches):\n plt.setp(p, 'facecolor', cm(c))\n\n plt.subplot(spec[2])\n plt.title('Velocity Error Distribution for ' + param.ML_Model)\n plt.xlabel('Error Range (%)')\n plt.ylabel('Frequency')\n (counts, bins) = np.histogram(vel_err, n_bins)\n factor = 0.00002\n N, bins, patches = plt.hist(bins[:-1], bins, weights=counts * factor)\n plt.yscale('log')\n bin_centers = 0.5 * (bins[:-1] + bins[1:])\n col = bin_centers - min(bin_centers)\n col /= max(col)\n for c, p in zip(col, patches):\n plt.setp(p, 'facecolor', cm(c))\n\n plt.show()\n\ndef main():\n print(\"Generating prediction contours...\")\n print()\n\n # load pickle files\n instance_array = np.asmatrix(pickle.load(open('./supporting_data_files/input_scalar_df.pkl', 'rb')))\n actual_output = np.asmatrix(pickle.load(open('./supporting_data_files/Actual_Output.pkl', 'rb')))\n\n # open origional df\n max_output_array = pickle.load(open('./supporting_data_files/Max_array_output.pkl', 'rb'))\n min_output_array = pickle.load(open('./supporting_data_files/Min_array_output.pkl', 'rb'))\n\n model_params = init_model(param.ML_Model, instance_array, actual_output)\n\n start = timeit.default_timer()\n # regressor predictions\n memoryUse_a = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss\n if param.ML_Model == \"Neural Network\":\n prediction = model_params[1](model_params[0].float())\n prediction = prediction.detach().cpu().numpy()\n elif param.ML_Model == \"Random Forest\":\n prediction = model_params[1](model_params[0])\n else:\n prediction = model_params[1](model_params[0].float())\n prediction = model_params[2].decoder(prediction)\n prediction = prediction.detach().cpu().numpy()\n\n # create rescaled arrays\n rescaled_prediction = rescale(prediction, max_output_array, min_output_array)\n memoryUse_b = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss\n stop = timeit.default_timer()\n\n total_time = stop - start\n total_memory = (memoryUse_b - memoryUse_a) * (10 ** -6)\n print(\"Run time = {:.3f} s\".format(total_time))\n print(\"memory use = {:.3f} MB\".format(total_memory))\n print()\n\n # calculate error matrix\n error = rescaled_prediction[0] - actual_output[0]\n for row in range(len(rescaled_prediction) - 1):\n error = np.vstack((error, rescaled_prediction[row + 1] - actual_output[row + 1]))\n\n error = (np.divide(np.absolute(error), actual_output)) * 100\n prediction_mean = mean_array(rescaled_prediction)\n error_mean = mean_array(error)\n\n # split mean and error arrays\n t_data_prediction, v_data_prediction = np.hsplit(prediction_mean, 2)\n t_data_error, v_data_error = np.hsplit(error_mean, 2)\n\n if param.Fluid_Property == \"Temperature\":\n output = np.array(t_data_prediction).flatten()\n prediction_error = np.array(t_data_error).flatten()\n elif param.Fluid_Property == \"Velocity\":\n output = np.array(v_data_prediction).flatten()\n prediction_error = np.array(v_data_error).flatten()\n else:\n print(\"Incorrect fluid property specified, please use correct syntax in Parameters.py\")\n\n contour_plotter(output, prediction_error)\n hist_plotter(error_mean)\n\nif __name__ == '__main__':\n if param.Training_Status == \"Evaluation\":\n main()\n elif param.Training_Status == \"Training\":\n os.system('python ./model_training.py')\n else:\n print(\"Failed to compile program, please indicate correct Training_Status in Parameters.py\")\n\n print()\n","sub_path":"model_evaluation.py","file_name":"model_evaluation.py","file_ext":"py","file_size_in_byte":10256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"292104375","text":"import itertools,time\n#i=itertools.count(1)\n#n=itertools.takewhile(lambda x:x<10,i)\n#print(list(n))\nfor i,j in itertools.groupby('aabBBbbaaa',lambda x:x.upper()):\n print(i,list(j))\ndef pi(N):\n temp=0\n r=4\n i=itertools.takewhile(lambda x:x<=2*N-1,itertools.count(1,2))\n return sum(map(lambda x:-4/x*(-1)**((x+1)/2),i))\n\n#print(pi(10))\n#print(pi(100))\n#print(pi(1000))\n#print(pi(10000))\n#assert 3.04 < pi(10) < 3.05\n#assert 3.13 < pi(100) < 3.14\n#assert 3.140 < pi(1000) < 3.141\n#assert 3.1414 < pi(10000) < 3.1415\n#print('ok')","sub_path":"pythonproject/廖雪峰--网站相关练习/itertools.py","file_name":"itertools.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"461023745","text":"#!/usr/bin/env python3\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom codecs import open\nfrom os import path \nimport sys\nimport re\nimport csv\nimport os\n\n# OptionParser imports\nfrom optparse import OptionParser\nfrom optparse import OptionGroup\n\n\n# Python 2 and 3 compatibility\nif (sys.version_info < (3, 0)):\n fd_read_options = 'rb'\n fd_write_options = 'wb'\nelse:\n fd_read_options = 'r'\n fd_write_options = 'w'\n\n# Handful patterns\n# -- Entering sslvpn definition block\np_entering_sslvpn_block = re.compile(r'^\\s*config vpn ssl settings$', re.IGNORECASE)\np_entering_subsslvpn_block = re.compile(r'^\\s*config .*$', re.IGNORECASE)\n\n# -- Exiting sslvpn definition block\np_exiting_sslvpn_block = re.compile(r'^end$', re.IGNORECASE)\n\n# -- Commiting the current sslvpn definition and going to the next one\np_sslvpn_next = re.compile(r'^next$', re.IGNORECASE)\n\n# -- sslvpn number\np_sslvpn_number = re.compile(r'^\\s*edit\\s+(?P\\S*)', re.IGNORECASE)\n\n# -- sslvpn setting\np_sslvpn_set = re.compile(r'\\s*set\\s(?P\\S+)\\s+(?P.*)', re.IGNORECASE)\n\n# Functions\ndef parse(options,full_path):\n \"\"\"\n Parse the data according to several regexes\n \"\"\"\n global p_entering_sslvpn_block, p_exiting_sslvpn_block, p_sslvpn_next, p_sslvpn_number, p_sslvpn_set\n \n in_sslvpn_block = False\n \n sslvpn_list = []\n sslvpn_elem = {}\n \n order_keys = []\n\n if (options.input_file != None):\n with open(options.input_file, mode=fd_read_options) as fd_input:\n for line in fd_input:\n line = line.strip()\n \n # We match a sslvpn block\n if p_entering_sslvpn_block.search(line):\n in_sslvpn_block = True\n \n # We are in a sslvpn block\n if in_sslvpn_block:\n\n # We match a setting\n if p_sslvpn_set.search(line):\n sslvpn_key = p_sslvpn_set.search(line).group('sslvpn_key')\n if not(sslvpn_key in order_keys):\n order_keys.append(sslvpn_key)\n \n sslvpn_value = p_sslvpn_set.search(line).group('sslvpn_value').strip()\n sslvpn_value = re.sub('[\"]', '', sslvpn_value)\n sslvpn_elem[sslvpn_key] = sslvpn_value\n\n # We are done with the current sslvpn id\n if p_exiting_sslvpn_block.search(line):\n sslvpn_list.append(sslvpn_elem)\n sslvpn_elem = {}\n \n # We are exiting the sslvpn block\n if p_exiting_sslvpn_block.search(line):\n in_sslvpn_block = False\n \n return (sslvpn_list, order_keys)\n\n\n else:\n #for files in os.listdir(os.path.abspath(options.input_folder)):\n with open(full_path, mode=fd_read_options) as fd_input:\n for line in fd_input:\n line = line.strip()\n \n # We match a sslvpn block\n if p_entering_sslvpn_block.search(line):\n in_sslvpn_block = True\n \n # We are in a sslvpn block\n if in_sslvpn_block:\n # We match a setting\n if p_sslvpn_set.search(line):\n sslvpn_key = p_sslvpn_set.search(line).group('sslvpn_key')\n if not(sslvpn_key in order_keys):\n order_keys.append(sslvpn_key)\n \n sslvpn_value = p_sslvpn_set.search(line).group('sslvpn_value').strip()\n sslvpn_value = re.sub('[\"]', '', sslvpn_value)\n sslvpn_elem[sslvpn_key] = sslvpn_value\n\n # We are done with the current sslvpn id\n if p_exiting_sslvpn_block.search(line):\n sslvpn_list.append(sslvpn_elem)\n sslvpn_elem = {}\n \n # We are exiting the sslvpn block\n if p_exiting_sslvpn_block.search(line):\n in_sslvpn_block = False\n return (sslvpn_list, order_keys)\n","sub_path":"parse_ssl_settings.py","file_name":"parse_ssl_settings.py","file_ext":"py","file_size_in_byte":4350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"421627733","text":"import GiniTree\nimport pickle\nimport sys\nimport copy\nimport time\nimport scipy.io\nimport numpy as np\nimport pandas as pd\n\n\nbatchNum = 7\ntrainBatchName=\"train%d.dataframe.pkl\"%batchNum\n\nfp = open(trainBatchName, 'rb')\ntrain = pickle.load(fp)\nfp.close()\n\nfp = open(\"test.dataframe.pkl\", 'rb')\ntest = pickle.load(fp)\nfp.close()\n\n\nt1=time.time()\nmodel = GiniTree.treeGeneration(Dataset=train, Attributes=list(range(1,1+1200)))\nt2=time.time()\nprint(\"&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\")\nprint(\"training takes %f secs\"%(t2-t1))\n\npredicted = GiniTree.predict(model, test)\ncorrect=list(test['label'].values)\naccuracy=sum([predicted[labelID]==correct[labelID] for labelID in range(len(predicted))])/len(correct)\nprint(\"validating accuracy=%f\"%accuracy)\n\nfp = open('predicted%d.pkl'%batchNum, 'wb')\npickle.dump(predicted, fp)\nfp.close()","sub_path":"DecisionTree/决策树作业_陈斯杰_2016310721/代码/bagging7.py","file_name":"bagging7.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"115513912","text":"num = input()\ntemp = num.split()\na = int(temp[0])\nb = int(temp[1])\nc = int(temp[2])\nresult_a = (a+b)%c\nresult_b = ((a%c)+(b%c))%c\nresult_c = (a*b)%c\nresult_d = ((a%c)*(b%c))%c\n\nprint(result_a)\nprint(result_b)\nprint(result_c)\nprint(result_d)","sub_path":"Baekjoon/입출력과 사칙연산/10430.py","file_name":"10430.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"233982296","text":"from sklearn.cluster import AgglomerativeClustering\n\nfrom clustering.ensembles.utils import get_ensemble_distance_matrix\n\n\ndef eac(\n ensemble,\n k: int,\n linkage_method: str = \"average\",\n ensemble_is_coassoc_matrix: bool = False,\n):\n \"\"\"\n Using an Evidence Accumulation method (EAC) [1], it derives a consensus\n partition with k clusters from the clustering solutions in ensemble.\n\n [1] Fred, Ana L. N. and Jain, Anil K., \"Combining Multiple Clusterings Using\n Evidence Accumulation\", IEEE Trans. Pattern Anal. Mach. Intell., 27(6):\n 835-850, 2005.\n\n Args:\n ensemble:\n Set of `p` clustering solutions generated by any clustering method.\n It must have `p` rows (number of clustering solutions) and `n`\n columns (number of data objects).\n k:\n Number of clusters that will have the `x` (consensus partition).\n linkage_method:\n Linkage criterion used for the hierachical algorithm applied on the\n ensemble. It supports any criterion provied by the `linkage`\n function of the `fastcluster` package.\n\n Returns:\n A 1D numpy array with the consensus clustering solution.\n \"\"\"\n\n if ensemble_is_coassoc_matrix:\n data = ensemble\n else:\n data = get_ensemble_distance_matrix(ensemble)\n\n return AgglomerativeClustering(\n n_clusters=k,\n affinity=\"precomputed\",\n linkage=linkage_method,\n ).fit_predict(data)\n\n\ndef eac_single(ensemble, k, **kwargs):\n \"\"\"\n Shortcut to run EAC using the single linkage method on the ensemble.\n \"\"\"\n return eac(ensemble, k, linkage_method=\"single\")\n\n\ndef eac_single_coassoc_matrix(coassoc_matrix, k, **kwargs):\n \"\"\"\n Shortcut to run EAC using the single linkage method on the coassociation\n matrix.\n \"\"\"\n return eac(\n coassoc_matrix, k, ensemble_is_coassoc_matrix=True, linkage_method=\"single\"\n )\n\n\ndef eac_complete(ensemble, k, **kwargs):\n \"\"\"\n Shortcut to run EAC using the complete linkage method on the ensemble.\n \"\"\"\n return eac(ensemble, k, linkage_method=\"complete\")\n\n\ndef eac_complete_coassoc_matrix(coassoc_matrix, k, **kwargs):\n \"\"\"\n Shortcut to run EAC using the complete linkage method on the coassociation\n matrix.\n \"\"\"\n return eac(\n coassoc_matrix, k, ensemble_is_coassoc_matrix=True, linkage_method=\"complete\"\n )\n\n\ndef eac_average(ensemble, k, **kwargs):\n \"\"\"\n Shortcut to run EAC using the average linkage method on the ensemble.\n \"\"\"\n return eac(ensemble, k, linkage_method=\"average\")\n\n\ndef eac_average_coassoc_matrix(coassoc_matrix, k, **kwargs):\n \"\"\"\n Shortcut to run EAC using the average linkage method on the coassociation\n matrix.\n \"\"\"\n return eac(\n coassoc_matrix, k, ensemble_is_coassoc_matrix=True, linkage_method=\"average\"\n )\n","sub_path":"libs/clustering/ensembles/eac.py","file_name":"eac.py","file_ext":"py","file_size_in_byte":2868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"355056020","text":"import os\n\n# dirname removes the last segment of a path.\n# abspath(__FILE__) returns the absolute path of a file\n# So basedir is the parent directory of the directory\n# this settings.py file is in.\n# So this is ../machine_learner/machine_learner/settings.py\n# so basedir = ../machine_learner\n# this is the directory manage.py resides in\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\nSECRET_KEY = 's7og$shd9^4s4ji(ju1g3toy79&snz440^x1ezzs@9om2-yqb%'\n\nDEBUG = True\n\nALLOWED_HOSTS = []\n\nINSTALLED_APPS = [\n 'django.contrib.contenttypes'\n]\n\nMIDDLEWARE = [\n 'django.middleware.csrf.CsrfViewMiddleware'\n]\n\nROOT_URLCONF = 'machine_learner.urls'\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'CET'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\nSTATIC_URL = '/static/'\n","sub_path":"machine_learner/machine_learner/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"26633731","text":"#!/usr/bin/env python\n#-*- coding:utf-8 -*-\n#@time: 2020/6/20 8:15\n\n''''''\n'''\n需求:\n1、小明开了一个男澡堂,来了一个女的,让进么,不让进,主动抛出性别异常--raise\n2、要求能够看到堆栈的报错信息\n\n思路:\n0、引入traceback模块\n1、自定义一个性别异常的异常类,继承异常的基类\n2、定义一个人的类,构造方法,传入参数姓名和性别\n3、定义一个函数,参数是人的对象\n 如果人的对象的性别不是男,就raise一个性别异常,给出提示语\n4、新建2个人的对象\n5、调函数,传入2个人的对象,try except捕获和处理异常\n 引入traceback来打印堆栈报错信息\n'''\n\nimport traceback\n\n# 1、自定义一个性别异常的异常类,继承异常的基类\nclass Gender_error(Exception):\n pass\n\n# 2、定义一个人的类,构造方法,传入参数姓名和性别\nclass Person:\n def __init__(self,name,gender):\n self.name = name\n self.gender = gender\n\n# 3、定义一个函数,参数是人的对象\n# 如果人的对象的性别不是男,就raise一个性别异常,给出提示语\ndef bashroom_men(person):\n if person.gender != '男': #对象调成员变量\n raise Gender_error('这里是男澡堂哈,女生不能入内')\n\n# 4、新建2个人的对象\np1 = Person('jack','男')\np2 = Person('lucy','女')\n\n# 5、调函数,传入2个人的对象,try except捕获和处理异常\ntry:\n bashroom_men(p1)\n bashroom_men(p2)\nexcept Gender_error as e:\n val = traceback.format_exc() #打印堆栈信息,返回字符串保存在val中\n print(e) #这里是男澡堂哈,女生不能入内\n print(val) #把堆栈的报错信息,作为字符串保存在变量val后,打印出来\nexcept Exception as e:\n print(e)\n\n'''\n\n\n'''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"python16/day1-21/day020 约束和异常处理/02pdf/02自定义异常_堆栈信息.py","file_name":"02自定义异常_堆栈信息.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"632756428","text":"# команда для прикола\nimport command_system\nfrom random import randint\n\n\ndef biba(token, user_id, stroka='', peer_id=''):\n # подкрутка для меня и влада\n if str(user_id) == '171859787' or str(user_id) == '148267214':\n message = 'Твоя биба 100 см'\n # для всех остальных пользователей\n else:\n message = 'Твоя биба '+str(randint(1, 51))+'см'\n return message, ''\n\n\nbiba_command = command_system.Command()\n\nbiba_command.keys = ['!биба']\nbiba_command.description = 'Размер бибы'\nbiba_command.process = biba","sub_path":"commands/biba.py","file_name":"biba.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"385703236","text":"from data.load import BulletSprites, EnemySprite\nfrom data.scripts.timer import Countdown\n\n\nclass StageSystem(object):\n def __init__(self, spawner):\n self.done = False\n self.enemy_count = 5\n self.stage = 1\n self.spawner = spawner\n self.banner_timer = Countdown()\n self.countdown_timer = Countdown()\n self.banner_timer.setup_countdown(1)\n self.countdown_timer.setup_countdown(3)\n self.init()\n\n def init(self):\n EnemySprite.empty()\n BulletSprites.empty()\n self.enemy_count = 5\n self.stage = 1\n self.banner_timer.reset_timer()\n self.countdown_timer.reset_timer()\n self.spawner(self.enemy_count)\n\n def update(self, tick, enemies):\n if enemies == 0:\n self.banner_timer.reset_timer()\n BulletSprites.empty()\n self.done = True\n self.stage += 1\n self.enemy_count = self.enemy_count + 1\n self.spawner(self.enemy_count)\n\n if self.countdown_timer.done and self.done:\n self.done = False\n self.countdown_timer.reset_timer()\n\n if self.banner_timer.done:\n self.countdown_timer.tick_timer(tick)\n\n self.banner_timer.tick_timer(tick)\n","sub_path":"data/scripts/stage.py","file_name":"stage.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"560696598","text":"import torch\nfrom torch import nn\n\nclass Agent(nn.Module):\n\n def __init__(self):\n super().__init__()\n\n self.dense_1 = nn.Linear(1,100)\n self.dense_2 = nn.Linear(100,1)\n self.tanh = nn.Tanh()\n self.relu = nn.ReLU()\n self.opt = torch.optim.Adam(self.parameters(), lr=0.1)\n\n def forward(self, input):\n hidden = self.dense_1(input)\n hidden = self.tanh(hidden)\n output = self.dense_2(hidden)\n return output\n\n def learn(self, input, target):\n for _ in range(1000):\n loss = torch.mean((self.forward(input) - target) ** 2)\n loss.backward()\n self.opt.step()\n self.opt.zero_grad()\n\n#Data\nx = torch.tensor([0.01 * i for i in range(300)]).reshape(300,1)\nnoise = torch.tensor([torch.normal(torch.tensor(0.1), torch.tensor(0.1)) for i in range(300)]).reshape(300,1)\ny = torch.sin(x) + noise\n\n#Agent learn\nagent = Agent()\nagent.learn(x, y)\n\n#Show\nimport matplotlib.pyplot as plt\nplt.plot(x.numpy(), y.numpy())\nplt.plot(x.numpy(), agent(x).data.numpy())\nplt.show()","sub_path":"Coding/Practice-2_Problem-1.py","file_name":"Practice-2_Problem-1.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"23179122","text":"#!/usr/bin/env python\nimport rospy\nimport time\nimport random\nimport gym\nimport math\nimport rospkg\nimport os\nimport copy\nfrom geometry_msgs.msg import Pose\nfrom my_randomgazebomanager_pkg.rviz_markers import MarkerBasics\n#from my_randomgazebomanager_pkg.rviz_markers import PickObjectMenu\nfrom my_randomgazebomanager_pkg.move_fetch_client import MoveFetchClient\nfrom sensor_msgs.msg import Image\nfrom get_model_gazebo_pose import GazeboModel\nfrom std_srvs.srv import Empty, EmptyRequest\n\n# Dont put anything ros related after this import because it removes ROS from imports to\n# import the cv2 installed and not the ROS version\nfrom rgb_camera_python3 import RGBCamera\nimport sys\n#print(sys.path)\ntry:\n sys.path.remove('/opt/ros/kinetic/lib/python2.7/dist-packages')\nexcept ValueError:\n ImportError\n#print(sys.path)\nimport cv2\nimport numpy as np\n\nfrom train_model import create_model\nfrom keras.applications.mobilenetv2 import preprocess_input\n\nimport xml.etree.ElementTree as ET\n\n\nclass FetchDCNN():\n def __init__(self, environment_name, weight_file_name, image_size, ALPHA, grasp_activated, number_of_elements_to_be_output):\n\n\n self._image_size = image_size\n self._number_of_elements_to_be_output = number_of_elements_to_be_output\n\n self.init_rviz_markers()\n\n # Init service to move fetch, this is because moveit doenst work in python 3\n self._grasp_activated = grasp_activated\n if self._grasp_activated == True:\n self.fetch_move_client = MoveFetchClient()\n self.fetch_move_client.go_to_safe_arm_pose()\n\n # Init camera RGB object\n self.rgb_camera_object = RGBCamera(\"/dynamic_objects/camera/raw_image\")\n\n # This are the models that we will generate information about.\n self.model_to_track_name = \"demo_spam1\"\n self.table_to_track_name = \"demo_table1\"\n\n model_to_track_list = [self.model_to_track_name, self.table_to_track_name]\n self.gz_model_obj = GazeboModel(model_to_track_list)\n\n # We start the model in Keras\n self.model = create_model(self._image_size, ALPHA, self._number_of_elements_to_be_output)\n\n rospack = rospkg.RosPack()\n # get the file path for rospy_tutorials\n path_to_package = rospack.get_path('my_dcnn_training_pkg')\n models_weight_checkpoints_folder = os.path.join(path_to_package, \"bk\")\n model_file_path = os.path.join(models_weight_checkpoints_folder, weight_file_name)\n\n print (model_file_path)\n\n self.model.load_weights(model_file_path)\n\n self.testing_unscaled_img_folder = os.path.join(path_to_package, \"testing/dataset_gen/images\")\n self.testing_unscaled_anotations_folder = os.path.join(path_to_package, \"testing/dataset_gen_annotations\")\n\n\n # We reset the environent to a random state\n print(\"Starting Service to Reset World Randomly....\")\n self.dynamic_world_service_call = rospy.ServiceProxy('/dynamic_world_service', Empty)\n self.change_env_request = EmptyRequest()\n self.dynamic_world_service_call(self.change_env_request)\n print(\"Starting Service to Reset World Randomly....DONE\")\n\n\n\n def init_rviz_markers(self):\n \"\"\"\n We initialise the markers used to visualise the predictions vs the\n real data.\n \"\"\"\n # We initialise the Markers for Center Of Mass estimation and the Object real position\n marker_type = \"cube\"\n namespace = \"demo_table\"\n mesh_package_path = \"\"\n self.demo_table_position = MarkerBasics(type=marker_type,\n namespace=namespace,\n index=0,\n red=0.0,\n green=0.0,\n blue=1.0,\n alfa=1.0,\n scale=[0.6,0.6,0.6],\n mesh_package_path=mesh_package_path)\n\n\n marker_type = \"mesh\"\n namespace = \"spam_real_position\"\n mesh_package_path = \"dynamic_objects/models/demo_spam/meshes/nontextured_fixed.stl\"\n\n self.spam_real_position = MarkerBasics(type=marker_type,\n namespace=namespace,\n index=0,\n red=1.0,\n green=0.0,\n blue=0.0,\n alfa=1.0,\n scale=[1.0, 1.0, 1.0],\n mesh_package_path=mesh_package_path)\n\n marker_type = \"sphere\"\n mesh_package_path = \"\"\n namespace = \"com_prediction\"\n self.com_prediction_marker = MarkerBasics(type=marker_type,\n namespace=namespace,\n index=0,\n red=0.0,\n green=1.0,\n blue=0.0,\n alfa=1.0,\n scale=[0.1, 0.1, 0.1],\n mesh_package_path=mesh_package_path)\n\n #self.pick_object_menu = PickObjectMenu()\n\n\n def publish_markers_new_data(self,pred, reality, reality_table):\n\n spam_real_pose = Pose()\n spam_real_pose.position.x = reality[0]\n spam_real_pose.position.y = reality[1]\n spam_real_pose.position.z = reality[2]\n\n com_prediction_pose = Pose()\n com_prediction_pose.position.x = pred[0]\n com_prediction_pose.position.y = pred[1]\n com_prediction_pose.position.z = pred[2]\n\n demo_table_pose = Pose()\n demo_table_pose.position.x = reality_table[0]\n demo_table_pose.position.y = reality_table[1]\n demo_table_pose.position.z = reality_table[2]\n\n self.spam_real_position.publish_marker(spam_real_pose)\n self.com_prediction_marker.publish_marker(com_prediction_pose)\n self.demo_table_position.publish_marker(demo_table_pose)\n\n \"\"\"\n def publish_new_grasp_state(self, grasp_state):\n\n if (grasp_state == \"grasp_success\"):\n print(\">>>>grasp_success....\")\n self.pick_object_menu.update_menu(index=1)\n elif (grasp_state == \"grasp_fail\"):\n print(\">>>>grasp_fail....\")\n self.pick_object_menu.update_menu(index=2)\n else:\n print(\">>>>nothing....\")\n self.pick_object_menu.update_menu(index=0)\n \"\"\"\n\n\n\n def predict_image(self,model,cv2_img=None, path=None):\n\n if cv2_img.all() != None:\n im = cv2_img\n else:\n if path != None:\n im = cv2.imread(path)\n else:\n print (\"Predict Image had no path image or image CV2\")\n return None\n\n if im.shape[0] != self._image_size:\n im = cv2.resize(im, (self._image_size, self._image_size))\n \"\"\"\n self.rgb_camera_object.display_image( image_display=im,\n life_time_ms=50,\n name=\"ResizedCAM\"\n )\n \"\"\"\n\n image = np.array(im, dtype='f')\n image = preprocess_input(image)\n\n\n self.rgb_camera_object.display_image( image_display=image,\n life_time_ms=50,\n name=\"ImagePredict\"\n )\n\n prediction = model.predict(x=np.array([image]))[0]\n\n return prediction\n\n def show_image(self,path, wait_time=500):\n image = cv2.imread(path)\n cv2.imshow(\"image\", image)\n print (\"Waiting \" + str(wait_time) + \"ms...\")\n cv2.waitKey(wait_time)\n print (\"Waiting \"+str(wait_time)+\"ms...END\")\n cv2.destroyAllWindows()\n\n def get_xyz_from_xml(self,path_xml_file):\n\n tree = ET.parse(path_xml_file)\n\n x_com = float(tree.findtext(\"./object/pose3d/x_com\"))\n y_com = float(tree.findtext(\"./object/pose3d/y_com\"))\n z_com = float(tree.findtext(\"./object/pose3d/z_com\"))\n\n return [x_com, y_com, z_com]\n\n def get_xyz_from_world(self, model_name):\n \"\"\"\n Retrieves the position of an object from the world\n \"\"\"\n pose_now = self.gz_model_obj.get_model_pose(model_name)\n\n XYZ = [pose_now.position.x,pose_now.position.y,pose_now.position.z]\n\n return XYZ\n\n\n def start_prediction_test(self):\n\n print(\"\\nTrying out unscaled image\")\n for k in os.listdir(self.testing_unscaled_img_folder):\n print (\"Name File==>\" + str(k))\n\n rospy.logwarn(\"We Reset Simulation\")\n\n init_joints_config = [0.0] * 7\n self.move_joints(init_joints_config)\n\n if \"png\" in k:\n\n img_path = os.path.join(self.testing_unscaled_img_folder, k)\n pred = self.predict_image(img_path, self.model)\n\n base_name_file = os.path.splitext(k)[0]\n annotation_file = base_name_file + \".xml\"\n img_anotation_path = os.path.join(self.testing_unscaled_anotations_folder, annotation_file)\n reality = self.get_xyz_from_xml(img_anotation_path)\n\n print (\"Class Prediction=>\" + str(pred))\n print (\"Class Reality File Image=>\" + str(reality))\n\n self.publish_markers_new_data(pred, reality)\n\n self.show_image(img_path, wait_time=5000)\n\n if self._grasp_activated == True:\n self.start_grasp_sequence(pred)\n\n\n rospy.loginfo(\"Start Prediction DONE...\")\n\n\n def start_camera_rgb_prediction(self, number_of_tests=1, camera_period = 5.0, wait_reset_period=3.0, go_dustbin=False):\n\n for i in range(number_of_tests):\n print (\"Number of Image=>\" + str(i))\n\n self.dynamic_world_service_call(self.change_env_request)\n print (\"Waiting for Reset Env to settle=>\")\n rospy.sleep(wait_reset_period)\n print (\"Waiting for Reset Env to settle...DONE\")\n\n cv2_img = self.rgb_camera_object.get_latest_image()\n pred = self.predict_image(self.model,cv2_img)\n\n # Add Z Axis value\n z_value = 0.6 + 0.042\n pred_mod = [pred[0],pred[1],z_value]\n\n\n reality = self.get_xyz_from_world(self.model_to_track_name)\n reality_table = self.get_xyz_from_world(self.table_to_track_name)\n\n print (\"Class Prediction=>\" + str(pred))\n print (\"Class Prediction Corrected=>\" + str(pred_mod))\n print (\"Class Reality SIMULATION=>\" + str(reality))\n print (\"Class RealityTabel SIMULATION=>\" + str(reality_table))\n self.publish_markers_new_data(pred_mod, reality, reality_table)\n\n\n #self.rgb_camera_object.display_latest_image(int(camera_period*1000))\n\n if self._grasp_activated == True:\n if go_dustbin:\n self.start_grasp_sequence_leave_dustbin(pred_mod)\n else:\n self.start_grasp_sequence(pred_mod)\n\n rospy.loginfo(\"Start Prediction DONE...\")\n\n\n def start_camera_rgb_prediction_continuous(self, image_freq= 20.0):\n \"\"\"\n It continuously make predictions\n \"\"\"\n # We reset the world Once\n self.dynamic_world_service_call(self.change_env_request)\n print (\"Waiting for Reset Env to settle=>\")\n wait_reset_period = 3.0\n rospy.sleep(wait_reset_period)\n print (\"Waiting for Reset Env to settle...DONE\")\n\n rate = rospy.Rate(image_freq)\n life_time_ms = int((1.0/ image_freq)*1000)\n while not rospy.is_shutdown():\n\n cv2_img = self.rgb_camera_object.get_latest_image()\n\n self.rgb_camera_object.display_image( image_display=cv2_img,\n life_time_ms=life_time_ms\n )\n\n pred = self.predict_image(self.model,cv2_img)\n # Add Z Axis value\n z_value = 0.6 + 0.042\n pred_mod = [pred[0],pred[1],z_value]\n\n reality = self.get_xyz_from_world(self.model_to_track_name)\n reality_table = self.get_xyz_from_world(self.table_to_track_name)\n\n\n print (\"Class Prediction=>\" + str(pred))\n print (\"Class PredictionMod=>\" + str(pred_mod))\n print (\"Class Reality SIMULATION=>\" + str(reality))\n self.publish_markers_new_data(pred_mod, reality, reality_table)\n rate.sleep()\n\n rospy.loginfo(\"Start Prediction DONE...\")\n\n def move_endeffector(self, position_XYZ):\n \"\"\"\n Move the EndEffector to the position given, orientation set\n \"\"\"\n rospy.logwarn(\"START Move ENd Effector\")\n\n orientation_XYZW = [-0.707, 0.000, 0.707, 0.001]\n\n result = self.fetch_move_client.move_endeffector(position_XYZ, orientation_XYZW)\n\n rospy.logwarn(\"END Move End Effector, result=\"+str(result))\n\n return result\n\n def move_joints(self, joints_config):\n \"\"\"\n Move the joints to the specified configuration.\n \"\"\"\n rospy.logwarn(\"START Move Joints\")\n\n result = self.fetch_move_client.move_joints(joints_config)\n\n rospy.logwarn(\"END Move Joints, result=\"+str(result))\n\n return result\n\n\n def open_close_gripper(self, open_or_close):\n \"\"\"\n Choose if you want to open or close\n \"\"\"\n if open_or_close == \"open\":\n # Open\n gripper_x = 0.4\n max_effort = 10.0\n else:\n # Close\n gripper_x = 0.05\n max_effort = 20.0\n\n self.fetch_move_client.move_gripper(gripper_x, max_effort)\n\n\n def check_if_object_grasped(self, tcp_xyz, wait_time=2.0, max_delta=0.2):\n \"\"\"\n It checks if the object to graps has been lifted from the table\n \"\"\"\n\n model_to_track_reality = self.get_xyz_from_world(self.model_to_track_name)\n\n print (\"model_to_track_reality=>\" + str(model_to_track_reality))\n print (\"tcp_xyz=>\" + str(tcp_xyz))\n\n z_model = model_to_track_reality[2]\n z_tcp = tcp_xyz[2]\n\n delta = z_tcp - z_model\n\n rospy.logwarn(\"delta==\"+str(delta)+\" <= \"+str(max_delta))\n\n if delta <= max_delta:\n grasp_state = \"grasp_success\"\n else:\n grasp_state = \"grasp_fail\"\n\n #self.publish_new_grasp_state(grasp_state)\n\n rospy.sleep(wait_time)\n\n return grasp_state == \"grasp_success\"\n\n\n def start_grasp_sequence(self, predicted_position_XYZ):\n\n #Init Pose\n self.fetch_move_client.go_to_safe_arm_pose()\n\n # Set optimum torso height\n height = 0.2\n result = self.fetch_move_client.move_torso(height)\n\n height_delta = 0.3\n position_XYZ = [predicted_position_XYZ[0],\n predicted_position_XYZ[1],\n predicted_position_XYZ[2] + height_delta ]\n orientation_XYZW = [-0.707, 0.000, 0.707, 0.001]\n self.fetch_move_client.move_endeffector(position_XYZ, orientation_XYZW)\n\n # Test Gripper\n self.open_close_gripper(open_or_close=\"open\")\n self.open_close_gripper(open_or_close=\"close\")\n self.open_close_gripper(open_or_close=\"open\")\n\n # Lower ARM\n height_delta = 0.19\n position_XYZ = [predicted_position_XYZ[0],\n predicted_position_XYZ[1],\n predicted_position_XYZ[2] + height_delta ]\n orientation_XYZW = [-0.707, 0.000, 0.707, 0.001]\n self.fetch_move_client.move_endeffector(position_XYZ, orientation_XYZW)\n\n # Close Gripper to grasp\n self.open_close_gripper(open_or_close=\"close\")\n\n # Go Up with the object\n height_delta = 0.3\n position_XYZ = [predicted_position_XYZ[0],\n predicted_position_XYZ[1],\n predicted_position_XYZ[2] + height_delta ]\n orientation_XYZW = [-0.707, 0.000, 0.707, 0.001]\n self.fetch_move_client.move_endeffector(position_XYZ, orientation_XYZW)\n\n\n # We check if we grapsed the object\n self.check_if_object_grasped(tcp_xyz=position_XYZ)\n\n # Go down with the object\n height_delta = 0.19\n position_XYZ = [predicted_position_XYZ[0],\n predicted_position_XYZ[1],\n predicted_position_XYZ[2] + height_delta ]\n orientation_XYZW = [-0.707, 0.000, 0.707, 0.001]\n self.fetch_move_client.move_endeffector(position_XYZ, orientation_XYZW)\n\n # Release the object\n self.open_close_gripper(open_or_close=\"open\")\n\n # We reset the Graps Marker\n #self.publish_new_grasp_state(grasp_state=\"nothing\")\n\n # Up again\n height_delta = 0.3\n position_XYZ = [predicted_position_XYZ[0],\n predicted_position_XYZ[1],\n predicted_position_XYZ[2] + height_delta ]\n orientation_XYZW = [-0.707, 0.000, 0.707, 0.001]\n self.fetch_move_client.move_endeffector(position_XYZ, orientation_XYZW)\n\n # Go to Init Safe pose\n self.fetch_move_client.go_to_safe_arm_pose()\n\n def start_grasp_sequence_leave_dustbin(self, predicted_position_XYZ):\n\n #Init Pose\n self.fetch_move_client.go_to_safe_arm_pose()\n\n # Set optimum torso height\n height = 0.2\n result = self.fetch_move_client.move_torso(height)\n\n height_delta = 0.3\n position_XYZ = [predicted_position_XYZ[0],\n predicted_position_XYZ[1],\n predicted_position_XYZ[2] + height_delta ]\n orientation_XYZW = [-0.707, 0.000, 0.707, 0.001]\n self.fetch_move_client.move_endeffector(position_XYZ, orientation_XYZW)\n\n # Test Gripper\n self.open_close_gripper(open_or_close=\"open\")\n self.open_close_gripper(open_or_close=\"close\")\n self.open_close_gripper(open_or_close=\"open\")\n\n # Lower ARM\n height_delta = 0.19\n position_XYZ = [predicted_position_XYZ[0],\n predicted_position_XYZ[1],\n predicted_position_XYZ[2] + height_delta ]\n orientation_XYZW = [-0.707, 0.000, 0.707, 0.001]\n self.fetch_move_client.move_endeffector(position_XYZ, orientation_XYZW)\n\n # Close Gripper to grasp\n self.open_close_gripper(open_or_close=\"close\")\n\n # Go Up with the object\n height_delta = 0.3\n position_XYZ = [predicted_position_XYZ[0],\n predicted_position_XYZ[1],\n predicted_position_XYZ[2] + height_delta ]\n orientation_XYZW = [-0.707, 0.000, 0.707, 0.001]\n self.fetch_move_client.move_endeffector(position_XYZ, orientation_XYZW)\n\n\n # We check if we grapsed the object\n grasp_success = self.check_if_object_grasped(tcp_xyz=position_XYZ)\n\n if grasp_success:\n # The Graps Succeeeded We place object in DustBin\n # Move to dustbin Pose\n self.fetch_move_client.go_to_dustbin_arm_pose()\n\n # Release the object\n self.open_close_gripper(open_or_close=\"open\")\n\n # We reset the Graps Marker\n #self.publish_new_grasp_state(grasp_state=\"nothing\")\n\n # Go to Init Safe pose\n self.fetch_move_client.go_to_safe_arm_pose()\n\n\n\nif __name__ == '__main__':\n rospy.init_node('fetch_randomenv_node', anonymous=True, log_level=rospy.INFO)\n\n\n if len(sys.argv) < 10:\n rospy.logfatal(\"usage: fetch_randomenv.py environment_name weight_file_name grasp_activated number_of_tests camera_period image_size ALPHA number_of_elements_to_be_output go_dustbin\")\n else:\n\n rospy.logwarn(str(sys.argv))\n\n environment_name = sys.argv[1]\n weight_file_name = sys.argv[2]\n grasp_activated = bool(sys.argv[3] == \"True\")\n number_of_tests = int(sys.argv[4])\n camera_period = float(sys.argv[5])\n image_size = int(sys.argv[6])\n ALPHA = float(sys.argv[7])\n number_of_elements_to_be_output = int(sys.argv[8])\n go_dustbin = bool(sys.argv[9] == \"True\")\n\n rospy.logwarn(\"environment_name:\"+str(environment_name))\n rospy.logwarn(\"weight_file_name:\"+str(weight_file_name))\n rospy.logwarn(\"grasp_activated:\"+str(grasp_activated))\n rospy.logwarn(\"number_of_tests:\"+str(number_of_tests))\n rospy.logwarn(\"camera_period:\"+str(camera_period))\n rospy.logwarn(\"image_size:\"+str(image_size))\n rospy.logwarn(\"ALPHA:\"+str(ALPHA))\n rospy.logwarn(\"number_of_elements_to_be_output:\"+str(number_of_elements_to_be_output))\n\n agent = FetchDCNN( environment_name,weight_file_name,\n image_size,\n ALPHA,\n grasp_activated,\n number_of_elements_to_be_output)\n\n agent.start_camera_rgb_prediction(number_of_tests=number_of_tests, camera_period = camera_period, wait_reset_period=3.0, go_dustbin=go_dustbin)\n #agent.start_camera_rgb_prediction_continuous()\n","sub_path":"src/my_dcnn_training_pkg/scripts/fetch_randomenv.py","file_name":"fetch_randomenv.py","file_ext":"py","file_size_in_byte":21504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"159256650","text":"import numpy as np\n\nfrom .basepreprocessor import BasePreprocessor, BasePreprocessorSegment\nfrom spikeinterface.core.core_tools import define_function_from_class\n\nfrom ..core import get_random_data_chunks\nfrom .filter import fix_dtype\n\n\nclass WhitenRecording(BasePreprocessor):\n \"\"\"\n Whitens the recording extractor traces.\n\n Parameters\n ----------\n recording: RecordingExtractor\n The recording extractor to be whitened.\n num_chunks_per_segment: int\n Number of chunks per segment for random chunk, by default 20\n chunk_size : int\n Size of a chunk in number for random chunk, by default 10000\n seed : int\n Random seed for random chunk, by default None\n W : 2d np.array\n Pre-computed whitening matrix, by default None\n M : 1d np.array\n Pre-computed means\n\n Returns\n -------\n whitened_recording: WhitenRecording\n The whitened recording extractor\n \"\"\"\n name = 'whiten'\n\n def __init__(self, recording, dtype=\"float32\", num_chunks_per_segment=20,\n chunk_size=10000, seed=None, W=None, M=None):\n # fix dtype\n dtype_ = fix_dtype(recording, dtype)\n\n if W is not None:\n assert M is not None, \"W and M must be not None\"\n W = np.array(W)\n M = np.array(M)\n else:\n random_data = get_random_data_chunks(recording, num_chunks_per_segment=num_chunks_per_segment,\n chunk_size=chunk_size, concatenated=True, seed=seed,\n return_scaled=False)\n random_data = random_data.astype(dtype_)\n # compute whitening matrix\n M = np.mean(random_data, axis=0)\n M = M[None, :]\n data = random_data - M\n AAt = data.T @ data\n AAt = AAt / data.shape[0]\n U, S, Ut = np.linalg.svd(AAt, full_matrices=True)\n W = (U @ np.diag(1 / np.sqrt(S))) @ Ut\n\n BasePreprocessor.__init__(self, recording, dtype=dtype_)\n\n for parent_segment in recording._recording_segments:\n rec_segment = WhitenRecordingSegment(parent_segment, W, M, dtype_)\n self.add_recording_segment(rec_segment)\n\n self._kwargs = dict(recording=recording, dtype=dtype,\n num_chunks_per_segment=num_chunks_per_segment,\n chunk_size=chunk_size, seed=seed, \n W=W.tolist(), M=M.tolist())\n\n\nclass WhitenRecordingSegment(BasePreprocessorSegment):\n def __init__(self, parent_recording_segment, W, M, dtype):\n BasePreprocessorSegment.__init__(self, parent_recording_segment)\n self.W = W\n self.M = M\n self.dtype = dtype\n\n def get_traces(self, start_frame, end_frame, channel_indices):\n traces = self.parent_recording_segment.get_traces(\n start_frame, end_frame, slice(None))\n traces_dtype = traces.dtype\n # if uint --> force int\n if traces_dtype.kind == \"u\":\n traces_chunk = traces_chunk.astype(\"float32\")\n\n whiten_traces = (traces - self.M) @ self.W\n whiten_traces = whiten_traces[:, channel_indices]\n return whiten_traces.astype(self.dtype)\n\n\n# function for API\nwhiten = define_function_from_class(source_class=WhitenRecording, name=\"whiten\")\n","sub_path":"spikeinterface/preprocessing/whiten.py","file_name":"whiten.py","file_ext":"py","file_size_in_byte":3356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"212746209","text":"import os\nimport cgi\nimport logging\nfrom urlparse import urljoin, urlparse\nfrom lxml import html\ntry:\n from cStringIO import StringIO\nexcept ImportError:\n from StringIO import StringIO\n\nfrom krauler.util import normalize_url\nfrom krauler.ua import get_ua\nfrom krauler.signals import on_parse\n\nlog = logging.getLogger(__name__)\n\n\nclass Page(object):\n\n def __init__(self, state, url, path):\n self.state = state\n self.url = url\n self.path = path\n\n @property\n def response(self):\n if not hasattr(self, '_response'):\n headers = {}\n if self.state.hidden:\n headers['User-Agent'] = get_ua()\n self._response = self.state.session.get(self.url, stream=True,\n headers=headers)\n return self._response\n\n @property\n def content(self):\n if not hasattr(self, '_content'):\n data = StringIO()\n try:\n for chunk in self.response.iter_content(chunk_size=1024):\n if chunk:\n data.write(chunk)\n self._content = data\n finally:\n self.response.close()\n return self._content.getvalue()\n\n @property\n def doc(self):\n if not hasattr(self, '_doc'):\n self._doc = html.fromstring(self.content)\n return self._doc\n\n @property\n def normalized_url(self):\n url = self.url\n if hasattr(self, '_response'):\n url = self._response.url\n url = normalize_url(url)\n return url\n\n @property\n def next_path(self):\n return self.path + [self.normalized_url]\n\n @property\n def terminate_path(self):\n if self.state.depth is None or self.state.depth < 0:\n return False\n return len(self.path) >= self.state.depth\n\n @property\n def mime_type(self):\n content_type = self.response.headers.get('content-type')\n if content_type is None:\n return 'text/html'\n mime_type, _ = cgi.parse_header(content_type)\n return mime_type\n\n @property\n def file_name(self):\n disp = self.response.headers.get('content-disposition')\n if disp is not None:\n _, attrs = cgi.parse_header(disp)\n if 'filename' in attrs:\n return attrs.get('filename')\n\n parsed = urlparse(self.normalized_url)\n file_name = os.path.basename(parsed.path)\n if file_name is not None and len(file_name):\n return file_name\n\n @property\n def is_html(self):\n if 'html' in self.mime_type:\n return True\n return False\n\n def parse(self):\n tags = [('a', 'href'), ('img', 'src'), ('link', 'href'),\n ('iframe', 'src')]\n\n # TODO: check rel=\"canonical\"\n urls = set([])\n for tag_name, attr_name in tags:\n for tag in self.doc.findall('.//%s' % tag_name):\n attr = tag.get(attr_name)\n if attr is None:\n continue\n url = normalize_url(urljoin(self.normalized_url, attr))\n if url is not None:\n urls.add(url)\n\n on_parse.send(self, urls=urls)\n\n for url in urls:\n self.state.crawl(url, path=self.next_path)\n\n def process(self):\n if not self.state.should_crawl(self.normalized_url):\n log.info(\"Skipping: %r\", self.normalized_url)\n return\n\n self.state.mark_seen(self.normalized_url)\n if self.response.status_code > 300:\n log.warning(\"Failure: %r, status: %r\", self.normalized_url,\n self.response.status_code)\n return\n self.state.mark_seen(self.normalized_url)\n\n if self.state.should_retain(self):\n self.retain()\n\n if self.is_html and not self.terminate_path:\n self.parse()\n\n def retain(self):\n self.state.emit(self)\n","sub_path":"krauler/page.py","file_name":"page.py","file_ext":"py","file_size_in_byte":3979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"417191101","text":"# -*- coding: utf-8 -*-\n\"\"\"\nExercise 200\n\"\"\"\n\nimport sys\n\ndef is_prime(num):\n if num == 1:\n return False\n if num == 2:\n return True\n if num == 3:\n return True\n counter=num-1 \n while counter > 3:\n if num % counter == 0:\n return False\n counter=counter - 1\n return True\n","sub_path":"exercices/200/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"301265066","text":"import turtle,random\n\nt = turtle.Turtle()\nt.speed('fastest')\ncolor = ['red', 'blue', 'green', 'yellow', 'gold1', 'lightSkyBlue1', 'DeepSkyBlue2', 'IndianRed1', 'DeepPink1', 'orchid1']\nwin=turtle.Screen()\nrandbg = random.randrange(len(color))\nwin.bgcolor(color[randbg])\n\nfor i in range(30):\n randcol = random.randrange(len(color))\n t.color(color[randcol])\n t.begin_fill()\n t.penup()\n size = random.randrange(10,200)\n tx = random.randrange(-250,250)\n ty = random.randrange(-250,250)\n t.setposition(tx,ty)\n t.pendown()\n \n for i in range(5):\n \n t.forward(size)\n t.right(144)\n t.end_fill()\n","sub_path":"HW#3/Hw22.py","file_name":"Hw22.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"503356782","text":"''' lets simulate a roulette wheel!\na program that takes as input your bet, and gives as output how much you won,\nwith the appropriate probability\n\nwrite a program that will take a players bet and output the resulting spin and payout. try using an\namerican roulette wheel (which has the 00 slot) to add a slight twist.\nand try to incorporate as many complex bets as you can to. a comprehensive list can be found here\n'''\nimport random\n\ntable = [0, 28, 9, 26, 30, 11, 7, 20, 32, 17, 5, 22, 34, 15, 3, 24, 36, 13, 1, 00, 27, 10, 25, 29, 12, 8, 19,\n 31, 18, 6, 21, 33, 16, 4, 23, 35, 14, 2]\n\nspin = random.randrange(0, len(table))\nresult = table[spin]\n\n#bet = input('Pick your numbers in the form n/n/n.....: ')\nbet = '15/8/7'\n#cash = input('Amount to be bet £s : ')\ncash = '100'\n\n\nbet = bet.split('/')\n\n\nif str(result) in bet:\n\n n = len(bet)\n payout = ((36/n) - 1) * cash\n print(str(result) + '!!! You won £' + str(payout) + ' !!')\nelse:\n print(str(result) + '!!!! LOSER!! Keep betting sucker')","sub_path":"albums/3/challenge32_easy/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"143862404","text":"from tkinter import *\n#from tkinter import ttk\nimport os\nimport tkinter.filedialog as tk\nimport tkinter.messagebox as tk2\nimport pyglet\nfrom PIL import Image\n\nfrom PIL import ImageTk\n\n#from mutagen.mp3 import MP3\n#import subprocess,os,glob\n#import time\n#import datetime\n#import threading\nplaylist = []\n\n\nplayer=pyglet.media.Player()\n#pygame.init()\n\nclass Application(Frame):\n \n def __init__(self,master):\n super(Application, self).__init__(master)\n #self.create_widgets()\n self.playlistbox = Listbox(self, width = 35, height = 10, selectmode = SINGLE) #TODO: ---> BROWSE, MULTIPLE, EXTENDED (p.379)\n for song in playlist:\n self.playlistbox.insert(END, song)\n self.bttn_clicks = 0\n self.bttn_clicks1 = 0 \n self.grid(rowspan=5, columnspan=4)\n self.playlistbox.grid(row = 1)\n self.playButton = Button(self, text = '>', command = self.play)\n #self.loopButton = Button(self, text = '[]', command = self.loop)\n \n self.addButton = Button(self, text = '+', command = self.add)\n self.nextButton = Button(self, text = '>>', command = self.next)\n \n self.pauseButton = Button(self, text = '.', command = self.pause)\n \n self.quitButton = Button(self, text = 'X', command = self.quit)\n \n self.volumeupButton = Button(self, text = '^', command = self.volumeup)\n \n self.volumedownButton = Button(self, text = '~', command = self.volumedown)\n \n self.removelistButton=Button(self, text = 'del', command = self.remove)\n #self.after(0) \n #tix.Button(root, text=\"Play\")\n self.playButton.grid(row=4, column = 0)\n #self.loopButton.grid(row=4, column = 1)\n self.addButton.grid(row=4, column = 2)\n self.nextButton.grid(row=4, column = 3)\n self.pauseButton.grid(row=4, column = 4)\n self.quitButton.grid(row=4, column = 5)\n self.volumeupButton.grid(row=3, column = 1)\n self.volumedownButton.grid(row=3, column = 2)\n \n self.removelistButton.grid(row=3, column = 3)\n self.pack()\n \n #pygame initialize\n #pygame.init()\n\n def play(self):\n #l=len(playlist)\n \n if(len(playlist) == 0):\n tk2.showinfo('Notice', 'No songs in your playlist!\\nClick Add to add songs.')\n else:\n #path=abspath(playlist)\n global player\n for i in range(len(playlist)):\n path=os.path.abspath(playlist[i])\n #playit=i\n source=pyglet.media.load(path)\n player.queue(source)\n player.play()\n \n playlist.clear()\n remove()\n \n \n\n \n\n def remove(self):\n items = self.playlistbox.curselection()\n pos = 0\n #print(items)\n for i in items :\n idx = int(i) - pos\n self.playlistbox.delete( idx,idx )\n pos = pos + 1\n \n \n \"\"\"if items!=():\n\n tk2.showinfo('Notice', 'No more items to delete')\"\"\"\n\n if items==():\n \n tk2.showinfo('Notice', 'No item is selected to delete or \\n Playlist is Empty')\n\n else: \n pass\n\n\n \n \"\"\"def loop(self):\n pygame.mixer.music.stop()\n pygame.mixer.music.play(-1,0.0)\"\"\"\n\n def add(self):\n file = tk.askopenfilenames(parent=root,title='Choose a file')#initialdir='/home/vineel/workspace/vin/src/Practice/mp3/') \n #songsTuple = root.splitlist(file) #turn user's opened filenames into tuple\n songsList = list(file) #convert to list\n #Add the full filename of songto playlist list, and a shortened version to the listBox\n\n for song in songsList: \n\n if song.endswith('.mp3'):\n\n playlist.append(song); \n tempArray = song.split('/') \n songShort = tempArray[len(tempArray)-1]\n self.playlistbox.insert(END, songShort)\n else:\n tk2.showinfo('Notice', 'Selected files are not mp3 files')\n \n def volumedown(self):\n self.bttn_clicks += 1\n while True:\n if self.bttn_clicks==1:\n player.volume=1.0\n elif self.bttn_clicks==2:\n player.volume=0.9\n elif self.bttn_clicks==3:\n player.volume=0.8\n elif self.bttn_clicks==4:\n player.volume=0.7\n elif self.bttn_clicks==5:\n player.volume=0.6\n elif self.bttn_clicks==6:\n player.volume=0.5 \n elif self.bttn_clicks==7:\n player.volume=0.4\n elif self.bttn_clicks==8:\n player.volume=0.3\n elif self.bttn_clicks==9:\n player.volume=0.2\n elif self.bttn_clicks==10:\n player.volume=0.1\n elif self.bttn_clicks==11:\n player.volume=0.0\n else:\n tk2.showinfo('Notice', 'Volume Muted!Further Reduction of volume is not possible') \n self.bttn_clicks=0\n break\n #print(\"Total Clicks: \" + str(self.bttn_clicks))\n \n def volumeup(self):\n self.bttn_clicks1 += 1\n while True: \n if self.bttn_clicks1==1:\n player.volume=0.0\n elif self.bttn_clicks1==2:\n player.volume=0.1\n elif self.bttn_clicks1==3:\n player.volume=0.2\n elif self.bttn_clicks1==4:\n player.volume=0.3\n elif self.bttn_clicks1==5:\n player.volume=0.4\n elif self.bttn_clicks1==6:\n player.volume=0.5\n elif self.bttn_clicks1==7:\n player.volume=0.6\n elif self.bttn_clicks1==8:\n player.volume=0.7\n elif self.bttn_clicks1==9:\n player.volume=0.8\n elif self.bttn_clicks1==10:\n player.volume=0.9\n elif self.bttn_clicks1==11:\n player.volume=1.0 \n\n else:\n tk2.showinfo('Notice', 'You cann`t set Maximum Volume!Further Increase of volume is not possible') \n self.bttn_clicks1=0 \n #print(\"Total Clicks: \" + str(self.bttn_clicks))\n break\n\n def pause(self):\n \n player.pause()\n tk2.showinfo('Notice', 'Press > button to play again')\n \n\n\n\n def next(self):\n player.next_source()\n\n \n \n def quit(self):\n \n sys.exit()\n \nroot = Tk()\n#root = ImageTk.PhotoImage(\"images.jpeg\")\n#background_image=PhotoImage(\"images.jpg\")\nroot.title('Python Rocks')\nroot.geometry('500x500')\nim = Image.open('bostan.jpg')\ntkimage = ImageTk.PhotoImage(im)\nmyvar=tk.Label(root,image = tkimage)\nmyvar.place(x=0, y=0, relwidth=1, relheight=1)\n\napp = Application(root)\napp.mainloop()\n","sub_path":"python_exercises/20project_ideas/music6.py","file_name":"music6.py","file_ext":"py","file_size_in_byte":7049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"486025033","text":"import json\nimport pytest\nimport unittest\nfrom entries_functions_combined import app\nfrom datetime import datetime\n\n#pytest.fixture provide a fixed baseline upon which tests can reliably and repeatedly executed\n@pytest.fixture\ndef client(request):\n test_client = app.test_client()\n return test_client\n\ndef post_json(client, url, json_dict):\n return client.post(url, data = json.dumps(json_dict),\n content_type='application/json')\n\ndef json_reply(reponse):\n return json.loads(reponse.data.decode('utf8'))\n\ndef test_get_all_entries(client):\n reponse = client.get('http://127.0.0.1:8080/api/v1/entries')\n assert reponse.status_code == 200\n\ndef test_add_entry(client):\n response = post_json(client, 'http://127.0.0.1:8080/api/v1/entries',\n {\"title\":'Vivian In Andela',\"content\": 'New content added'})\n assert response.status_code == 201\n # assert json_reply(response) == {\"entry\": {\"content\": \"New content added\", \"date\": \"Thursday.September.2018\", \"id\": 3, \"title\": \"Vivian In Andela\"}}\n json_reply(response)['entry']['id'] == 3\n # client.delete('http://127.0.0.1:8080/api/v1/entries')\n\ndef test_get_entry(client):\n '''Create entry that has an id of one, changing previous content id to 2'''\n post_response = post_json(client, 'http://127.0.0.1:8080/api/v1/entries', \n {\"content\": \"Funny moments\",\"title\": \"Funny moments\"})\n id = 1\n get_response = client.get('http://127.0.0.1:8080/api/v1/entries/1')\n assert post_response.status_code == 201\n assert get_response.status_code == 200\n # client.delete('http://127.0.0.1:8080/api/v1/entries/1')\n\ndef test_modifiy_entry(client):\n post_json(client, 'http://127.0.0.1:8080/api/v1/entries', \n {\"content\": \"Funny moments\",\"title\": \"Funny moments\"})\n response_to_change = client.put('http://127.0.0.1:8080/api/v1/entries/1', data=\n json.dumps({\"content\": \"Funny momenModify Data\",\"title\": \"Funny moments moments\"}), \n content_type = 'application/json')\n assert response_to_change.status_code == 200\n\ndef test_delete_entry(client):\n '''Create entry that has an id of one, changing previous content id to 2'''\n post_response = post_json(client, 'http://127.0.0.1:8080/api/v1/entries', \n {\"content\": \"Funny moments\",\"title\": \"Funny moments\"})\n id = 1\n get_response = client.get('http://127.0.0.1:8080/api/v1/entries/1')\n assert post_response.status_code == 201\n assert get_response.status_code == 200\n response = client.delete('http://127.0.0.1:8080/api/v1/entries/1')\n assert json_reply(response) == {\"Result\": 'entry successfully deleted'}\n\nif __name__ == '__main__':\n unittest.main()\n \n\n","sub_path":"test_every_endpoint.py","file_name":"test_every_endpoint.py","file_ext":"py","file_size_in_byte":2768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"295365603","text":"from modules import *\n\n# img_bill = face_recognition.load_image_file('./img/known/bill-gates.jpg')\n# bill_face_encoding = face_recognition.face_encodings(img_bill)[0]\n\n# img_mark = face_recognition.load_image_file('./img/known/mark-zuckerberg.jpg')\n# mark_face_encoding = face_recognition.face_encodings(img_mark)[0]\n\n# img_elon = face_recognition.load_image_file('./img/known/elon-musk.jpg')\n# elon_face_encoding = face_recognition.face_encodings(img_elon)[0]\n\nimg_sunil = face_recognition.load_image_file('./img/known/sunil-grover.jpeg')\nsunil_face_encoding = face_recognition.face_encodings(img_sunil)[0]\n\n#print('JOBS FACE ENCODINGS : ', jobs_face_encoding)\n#Create an array of encodings and names\n\nknown_face_encodings = [\n # bill_face_encoding,\n # mark_face_encoding,\n # elon_face_encoding,\n sunil_face_encoding\n]\n\nknown_face_names = [\n \"Sunil Grover\"\n]\n\n#Load test image to find faces in\ntest_image = face_recognition.load_image_file('./img/unknown/unknown8.jpeg')\n\n#Find faces in test image\nface_locations = face_recognition.face_locations(test_image)\nface_encodings = face_recognition.face_encodings(test_image, face_locations)\n#print('TEST IMAGE ENCODINGs', face_encodings)\n\n\n#Convert to PIL format\npil_image = Image.fromarray(test_image)\n\n#Create a image draw instance\ndraw = ImageDraw.Draw(pil_image)\n\n\n#Loop through faces in test image\nfor (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):\n matches = face_recognition.compare_faces(known_face_encodings, face_encoding, tolerance=0.70)\n\n name = \"Unknown person\".upper()\n\n #If match\n if True in matches:\n first_match_index = matches.index(True)\n name = known_face_names[first_match_index].upper()\n\n #Draw box\n draw.rectangle(((left, top), (right, bottom)), outline=(0,0,0))\n\n #Draw label\n text_width, text_height = draw.textsize(name)\n draw.rectangle(((left, bottom - text_height - 10), (right, bottom)), fill=(0,0,0), outline=(0,0,0))\n draw.text((left + 6, bottom - text_height - 5), name, fill=(255,255,255))\n\ndel draw\n\n#Display the image\npil_image.show()\n","sub_path":"ignored/face recognition/identify.py","file_name":"identify.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"303258381","text":"from torch.nn import Linear, Module, Conv2d, Dropout2d\nimport torch.nn.functional as F\nimport torch.nn as nn\nimport torch as t\n\n\nclass Model1(Module):\n def __init__(self, input_shape):\n super(Model1, self).__init__()\n\n self.conv1 = Conv2d(1, 10, 5)\n self.conv2 = Conv2d(10, 20, 5)\n self.fc1 = Linear(320, 80) # 20(conv2 output) Bilder aufgeteilt in 4x4 = 320\n self.fc2 = Linear(80, 10) # 10 outputs für 0-9\n\n\n\n def forward(self, x):\n x = self.conv1(x)\n x = F.max_pool2d(x, 2)\n x = self.conv2(x)\n x = F.max_pool2d(x, 2)\n\n x = x.view(-1, 320) #ignoriert 1. Dimension und legt 320 pixel nebeneinander\n x = t.sigmoid(self.fc1(x))\n x = t.sigmoid(self.fc2(x))\n return F.log_softmax(x, dim=1) # höchster output 1, rest 0 (klassifizierung)\n","sub_path":"models/Model1.py","file_name":"Model1.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"545635608","text":"#Agenda telefonica\n#Apenas para estudo,\n#Criado e Editado com base no vídeo:\n#https://www.youtube.com/watch?v=XCNvEV8oGvo\n\nimport os\n\nlista = []\narq2 = open(\"agenda.csv\", \"r\")\nlista = arq2.readlines()\narq2.close()\n\ndef menu():\n print(\"Bem Vindo a Sua Agenda :)\")\n print(\"\\n\", \"=\" * 30)\n print(\"1 - Criar Pessoa \\n2 - Excluir Pessoa \\n3 - Listar Pessoa \\n4 - Sair\")\n\ndef lista_agenda(nome, descricao, opcao):\n if(opcao ==1):\n pessoa = nome+ \";\" +descricao+\"\\n\"\n \n lista.append(pessoa) ##append - acrescentar informação\n lista.sort()\n\n print(\"Pessoa Adicionada!!\")\n os.system(\"sleep 2s\")\n print(lista)\n #Excluindo pessoa através do id\n if(opcao == 2):\n tam = len(lista)\n for i in range(tam):\n print(i,\" - \", lista[i])\n\n delete = int(input(\"Qual deseja Apagar? \"))\n lista.pop(delete)\n print(\"Registro excluido\")\n os.system(\"sleep 2s\")\n ##Listando Pessoas\n if(opcao == 3):\n tam = len(lista)\n for i in range(tam):\n print(lista[i])\n os.system(\"sleep 2s\")\n #Abrindo o arquivo e retornando o tamanho da lista.\n arq = open(\"agenda.csv\", \"w\")\n tam = len(lista)\n\n for i in range(tam):\n arq.write(lista[i])\n arq.close()\n\no = 0\nwhile True:\n os.system(\"Clear\")\n \n menu()\n op = int(input(\"Opção: \"))\n\n ##1 - Adicionando Pessoa\n if(op == 1):\n n = input(\"Digite um nome: \")\n desc = input(\"Digite uma descrição: \")\n lista_agenda(n, desc, 1)\n ##2 - Excluindo Pessoa\n if (op ==2):\n lista_agenda(0, 0, 2) \n ##3 - Listando Pessoas\n if (op == 3):\n lista_agenda(0, 0, 3)\n ##Saindo da Agenda\n if (op == 4):\n break\n","sub_path":"agenda.py","file_name":"agenda.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"163775770","text":"snmpHost = '211.9.4.100'\nsnmpPort = 161\n\ndata = {\n 'to': '',\n 'fr': 'SiotTestAE',\n 'rqi': '',\n 'pc': {'m2m:cin': {'con': 0.0}},\n 'op': 1,\n 'ty': 4,\n 'sec': 0\n}\n\n\nintveral = 5\n\ntrapAgentAddress = '0.0.0.0'\nsnmpTrapPort = 9162\n\n#SNMPv3/USM setup\n\n# userInfo = {\n# 'username': 'tester',\n# 'authProtocol': 'authkey1',\n# 'privProtocol': 'privkey1',\n# 'OctetValue': '0x0102030405'\n# }\n\n\n","sub_path":"Config/snmpConfig.py","file_name":"snmpConfig.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"279679538","text":"import os\nimport nuke\nfrom cgl.core.path import PathObject, lj_list_dir, find_latest_publish_objects\nfrom .smart_task import SmartTask\nimport cgl.plugins.nuke.alchemy as alc\nreload(alc)\nfrom os.path import isdir\n\nclass Task(SmartTask):\n defaut_color = (0,0.255,0)\n default_task_file = alc.scene_object().copy(shot = '000',\n set_proper_filename = True,\n context = 'render',\n user= 'publish',\n latest =True)\n\n def __init__(self, path_object=None):\n if not path_object:\n self.path_object = alc.scene_object()\n\n def build(self):\n \"\"\"\n 1.Import Plate\n 2.Import Lut\n 3.Set comp settings\n 4.Import default comp\n :return:\n \"\"\"\n from cgl.plugins.nuke.utils import set_default_settings, backdrop, tag_object\n\n\n alc.import_task(task = 'plate')\n alc.import_task(task='lut')\n set_default_settings()\n backdrop = backdrop('key',bg_color=self.defaut_color)\n tag_object('task','key',backdrop)\n if isdir(self.default_task_file.copy(filename = '').path_root):\n alc.import_file(self.default_task_file.path_root)\n\n def _import(self, filepath, **kwargs):\n pass\n\ndef setup_proxy_settings():\n import nuke\n alc.scene_object()\n\n\ndef get_dependencies():\n current_shot = PathObject(nuke.root().name())\n all_tasks = current_shot.glob_project_element('task')\n publish_objects = []\n\n for task in all_tasks:\n\n task_object = current_shot.copy(filename='',\n task=task,\n user='publish',\n context='render').latest_version()\n if os.path.isdir(task_object.copy(filename='').path_root):\n publish_objects.append(task_object)\n\n return (publish_objects)\n\n\ndef import_dependencies():\n current_shot = PathObject(nuke.root().name())\n publish_objects = get_dependencies()\n spread = 0\n\n for task_object in publish_objects:\n\n if task_object.task != current_shot.task:\n\n filename = lj_list_dir(task_object.path_root)[0]\n sequence_path = task_object.copy(filename=filename)\n print(task_object.path)\n readNode = import_media(sequence_path.path_root, name=task_object.task)\n readNode.setSelected(True)\n\n color_dic = {'plate': 1278818815.0, 'elem': 1230983935.0, 'cam': 1264526079.0, 'default': 825305599.0}\n\n if task_object.task in color_dic.keys():\n tile_color = color_dic[task_object.task]\n else:\n tile_color = color_dic['default']\n\n n = nuke.nodes.BackdropNode(xpos=readNode.xpos() - 20,\n bdwidth=120,\n ypos=readNode.ypos() - 80,\n bdheight=170,\n tile_color=tile_color,\n note_font_size=42,\n z_order=0,\n name='{} BACKDROP'.format(\n task_object.task.upper()),\n label=task_object.task.upper())\n return publish_objects\n\n\ndef set_comp_default_settings():\n from cgl.plugins.nuke.tasks import plate as plate_task\n plate = plate_task.Task()\n proxy_res = alc.scene_object().project_info['proxy_resolution']\n readNode = nuke.toNode('plate_Read')\n resolution = alc.scene_object().project_info['full_resolution']\n root = nuke.root()\n startFrame = float(plate.start_frame)\n lastFrame = float(plate.end_frame)\n\n proxy_width, proxy_height = proxy_res.split('x')\n\n\n for f in nuke.formats():\n\n if f.name() == 'DEFAULT_PROXY':\n f.setWidth(int(proxy_width))\n f.setHeight(int(proxy_width))\n\n DEFAULT_PROXY = '%s PROXY' % proxy_res.replace('x', ' ')\n FULL = '%s FULL' % alc.scene_object().project_info['full'].replace('x', ' ')\n\n nuke.addFormat(DEFAULT_PROXY)\n nuke.addFormat(FULL)\n\n root['proxy_type'].setValue('format')\n root['proxy_format'].setValue('PROXY')\n root['proxySetting'].setValue('if nearest')\n\n nuke.root()['format'].setValue('FULL')\n nuke.frame(startFrame)\n nuke.alert(\"Comp Size, duration and proxy set\")\n","sub_path":"cgl/plugins/nuke/tasks/key.py","file_name":"key.py","file_ext":"py","file_size_in_byte":4513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"233848523","text":"from ethereum import utils as ethereum_utils\nfrom ethereum import tester\nimport numpy as np\nfrom scipy.interpolate import spline\nimport matplotlib.pyplot as plt\n\n\n# removes 0x prefix\ndef strip_0x(value):\n if value and value.startswith(\"0x\"):\n return value[2:]\n return value\n\n\ndef encode_hex(value):\n return \"0x\" + ethereum_utils.encode_hex(value)\n\n\ndef buildGraph(households, datadict, ylabel, title, grid):\n for house in households:\n dataList = datadict[house.address]\n x = np.arange(0, len(dataList))\n y = dataList\n plt.plot(x, y, label=house.address)\n\n plt.xlabel(\"Time (hours)\")\n plt.ylabel(ylabel)\n plt.title(title)\n plt.grid(grid)\n name = title + \".png\"\n plt.savefig(\"pics/\" + name)\n plt.legend()\n plt.show()\n\n\ndef buildSmoothXY(xlist, ylist):\n x = np.array(xlist)\n y = np.array(ylist)\n\n x_s = np.linspace(x.min(), x.max(), 300)\n y_s = spline(x, y, x_s)\n\n return (x_s, y_s)\n\n\ndef generateAdresses(number):\n number += 1\n listAdr = []\n for x in range(number):\n item = \"0x\" + str(x)\n listAdr.append(item)\n return listAdr\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"380191949","text":"n=int(input())\nresult=[]\nfor i in range(n):\n num=input().split(\" \")\n m=num[0]\n n=num[1]\n count=0\n for j in range(m,n+1):\n if j%num[2]==0 or j%num[3]==0:\n count=count+1\n result.append(count)\nfor f in range(n):\n print(result[f])","sub_path":"Code/CodeRecords/2759/60747/246162.py","file_name":"246162.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"439352187","text":"import helper\nimport model\nimport numpy as np\n\ntrain_path = 'train_BISE.txt'\nembedding_index = helper.load_embedding()\nword2id = helper.word2id(embedding_index)\ntrain_x, train_y = helper.traindata(train_path, word2id)\n\nmodel = model.model_build()\nmodel.fit(train_x, np.array(train_y), batch_size=50, epochs=5, verbose=1)\n\nmodel.save('crf.h5_2')\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"563775627","text":"from celery import task\nfrom django.core.mail import send_mail\nfrom .models import Order\n\n\n@task\ndef order_created(order_id):\n \"\"\"\n Zadanie wysyłające powiadomienie za pomocą mail'a po zakończonym powodzeniem złożeniem zamówienia.\n :param order_id: numer id zamówienia.\n :return: funkcja wysyłająca maila.\n \"\"\"\n order = Order.objects.get(id=order_id)\n subject = 'Zamówienie nr {}'.format(order.id)\n message = 'Witaj {}!\\n\\nZłożyłeś zamówienie w naszym sklepie. ' \\\n 'Numer zamówienia to {}.'.format(order.first_name, order.id)\n mail_sent = send_mail(subject, message, 'admin@myshop.com', [order.email])\n\n return mail_sent","sub_path":"orders/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"378455243","text":"# -*- coding: utf-8 -*-\nfrom StringUtil import StringUtil\nfrom ConnUtile import HiveClient\nimport os\nimport time\nimport Levenshtein\n\nHIVE_ONLINE_IP = '192.168.128.69'\nHIVE_ONLINE_DB_NAME = 'jk_mid_recall_source'\nHIVE_ONLINE_PORT = 10000\n\n#定义获取数据的sql\nSQL_PAPER_RECALL_QUESTIONS = '''select distinct \n paper_quest.paper_question_id\n ,recall_quest.questno\n ,paper_quest.three_know_code\n ,paper_quest.three_know_name\n ,paper_quest.txt_content_clean\n ,recall_quest.txt_content_clean\n from (select * \n from jk_mid_recall_source.fact_paperquestion_basic_content_info \n where txt_content_clean is not NULL \n and three_know_code is not NULL\n and questtype_id = 3\n ) as paper_quest \n inner join (select * \n from jk_mid_recall_source.fact_recall_source_question_bank \n where txt_content_clean is not NULL\n and three_know_code is not NULL\n and questtype_id = 3\n ) as recall_quest \n on recall_quest.questtype_id = paper_quest.questtype_id \n and recall_quest.three_know_code = paper_quest.three_know_code'''\n#定义存储数据的路径\nMAIN_PATH = '/opt/sys/schoolquestion_examresult/wrongquest-V2.2.0.2018.11.27_release/recall/similar'\nPATH_PAPER_RECALL_CHECK = MAIN_PATH + '/sim_result/paperrecallcheck/' + 'paper_recall_check_3.txt'\n\n'''\n从hive获取题的信息数据\ninput:str\nreturn:list\nauthor:roy\ndt:2019-05-27\n'''\ndef getRecomSubjects():\n #获取一个hive连接\n connGetSubjects = HiveClient(HIVE_ONLINE_IP,HIVE_ONLINE_DB_NAME,HIVE_ONLINE_PORT)\n #获得数据\n subjectResult = connGetSubjects.query(SQL_PAPER_RECALL_QUESTIONS)\n #重命名一下字段\n listQuest = []\n for lineSubject in subjectResult:\n dictSubject = {}\n dictSubject['y_id'] = lineSubject[0]\n dictSubject['t_id'] = lineSubject[1]\n dictSubject['y_know_code'] = lineSubject[2]\n dictSubject['y_know_name'] = lineSubject[3]\n dictSubject['y_content'] = lineSubject[4]\n dictSubject['t_content'] = lineSubject[5]\n listQuest.append(dictSubject)\n connGetSubjects.close()\n return listQuest\n\nif __name__ == \"__main__\":\n #查询数据\n print('开始读取数据')\n listSujects = getRecomSubjects()\n print('读取数据完成')\n \n print('开始计算相似度')\n listCheck = []\n for dictSubject in listSujects:\n dictSubjectCheck = {}\n dictSubjectCheck['y_id'] = dictSubject['y_id']\n dictSubjectCheck['y_know_code'] = dictSubject['y_know_code']\n dictSubjectCheck['y_know_name'] = dictSubject['y_know_name']\n dictSubjectCheck['t_id'] = dictSubject['t_id']\n #计算相似度\n simiValue = 0.0\n simiValue = round(Levenshtein.ratio(dictSubject['y_content'],dictSubject['t_content']),3)\n #相等时,相似度是1\n if dictSubject['y_content'] == dictSubject['t_content']:\n simiValue = 1.0\n dictSubjectCheck['simi_value'] = simiValue\n listCheck.append(dictSubjectCheck)\n print('相似度计算完成')\n\n #开始写出数据\n if os.path.exists(PATH_PAPER_RECALL_CHECK) == True:\n os.remove(PATH_PAPER_RECALL_CHECK)\n print('删除数据文件')\n\n\n fileOut = open(PATH_PAPER_RECALL_CHECK,'a+')\n for dictSubjectCheck in listCheck:\n fileOut.write(dictSubjectCheck['y_id'] + '\\t')\n fileOut.write(dictSubjectCheck['y_know_code'] + '\\t')\n fileOut.write(dictSubjectCheck['y_know_name'] + '\\t')\n fileOut.write(dictSubjectCheck['t_id'] + '\\t')\n fileOut.write(str(dictSubjectCheck['simi_value']) + '\\t')\n fileOut.write('\\n')\n fileOut.close()\n","sub_path":"Python/题干去重/paperRecallCheck_3.py","file_name":"paperRecallCheck_3.py","file_ext":"py","file_size_in_byte":4338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"48786713","text":"from django.conf.urls import patterns, include, url\n\nfrom django.contrib import admin\nfrom pic_site import views\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'pic_site.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n\turl(r'^home/', 'pic_site.views.home', name='home'),\n\turl(r'^presentation/', views.presentation, name='presentation'),\n\turl(r'^actualites/', views.actualites, name='actualites'),\n\turl(r'^shell/', views.shell, name='shell'),\n\t\n\turl(r'^projects/', include('projects.urls')),\n\turl(r'^events/', include('events.urls')),\n url(r'^admin/', include(admin.site.urls)),\n)\n","sub_path":"pic_site/pic_site/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"462213492","text":"import urllib2\nfrom bs4 import BeautifulSoup\n\n\n\n\nmesse = \"http://messes.info/horaires/saint%20maur%20des%20fosses\"\npage = urllib2.urlopen(messe)\n\n\nsoup = BeautifulSoup(page)\n\nf = open(\"data\", \"w\")\nf.write(soup.prettify())\n\nf.close()\n\n#print(soup.prettify())\n\nprint(\"page loaded\")\n\n\n#print(soup.findAll(\"div\", role=\"treeitem\"))\n\n#print(soup.findAll(\"div\"))\n\n\n#align=\"center\"\n\n\n#print(soup.prettify())\n","sub_path":"scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"46999994","text":"import os\nfrom unittest.mock import patch\n\nimport responses\n\nfrom hyp3lib import get_orb\n\n_GRANULE = 'S1A_IW_SLC__1SSV_20150621T120220_20150621T120232_006471_008934_72D8'\n\n\n@responses.activate\ndef test_download_sentinel_orbit_file_esa(tmp_path):\n responses.add(responses.GET, 'https://foo.bar/hello.txt', body='content')\n\n with patch('hyp3lib.get_orb.get_orbit_url', return_value='https://foo.bar/hello.txt'):\n responses.add(responses.GET, 'https://foo.bar/hello.txt', body='content')\n orbit_file, provider = get_orb.downloadSentinelOrbitFile(_GRANULE, providers=('ESA',), directory=str(tmp_path))\n\n assert provider == 'ESA'\n assert os.path.exists(orbit_file)\n assert orbit_file == str(tmp_path / 'hello.txt')\n\n\n@responses.activate\ndef test_get_orbit_url_esa_poeorb():\n search_url = 'https://scihub.copernicus.eu/gnss/api/stub/products.json' \\\n '?filter=%28platformname%3ASentinel-1+AND+producttype%3AAUX_POEORB+AND+filename%3AS1A%2A+' \\\n 'AND+beginPosition%3A%5B%2A+TO+2015-06-21T12%3A02%3A20Z%5D+' \\\n 'AND+endPosition%3A%5B2015-06-21T12%3A02%3A32Z+TO+NOW%5D%29' \\\n '&limit=1&offset=0&sortedby=ingestiondate&order=desc'\n search_response = {'products': [{'uuid': 'myUUID'}]}\n responses.add(responses.GET, search_url, json=search_response)\n\n orbit_url = get_orb.get_orbit_url(_GRANULE, provider='ESA')\n assert orbit_url == \"https://scihub.copernicus.eu/gnss/odata/v1/Products('myUUID')/$value\"\n\n\n@responses.activate\ndef test_get_orbit_url_esa_resorb():\n search_url = 'https://scihub.copernicus.eu/gnss/api/stub/products.json' \\\n '?filter=%28platformname%3ASentinel-1+AND+producttype%3AAUX_RESORB+AND+filename%3AS1A%2A+' \\\n 'AND+beginPosition%3A%5B%2A+TO+2015-06-21T12%3A02%3A20Z%5D+' \\\n 'AND+endPosition%3A%5B2015-06-21T12%3A02%3A32Z+TO+NOW%5D%29' \\\n '&limit=1&offset=0&sortedby=ingestiondate&order=desc'\n search_response = {'products': [{'uuid': 'myUUID'}]}\n responses.add(responses.GET, search_url, json=search_response)\n\n orbit_url = get_orb.get_orbit_url(_GRANULE, provider='ESA', orbit_type='AUX_RESORB')\n assert orbit_url == \"https://scihub.copernicus.eu/gnss/odata/v1/Products('myUUID')/$value\"\n\n\ndef test_get_orbit_url_asf():\n orbit_url = get_orb.get_orbit_url(_GRANULE, provider='ASF')\n\n assert 'https://s1qc.asf.alaska.edu/aux_poeorb/' \\\n 'S1A_OPER_AUX_POEORB_OPOD_20150711T121908_V20150620T225944_20150622T005944.EOF' \\\n == orbit_url\n","sub_path":"tests/test_get_orb.py","file_name":"test_get_orb.py","file_ext":"py","file_size_in_byte":2557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"222171657","text":"# -*- coding:utf-8 -*-\n'''\n项目的配置文件,配置的key必须为大写字母\n'''\n# 是否开启调试模式\nDEBUG = True\n\n# session必须要设置key\nSECRET_KEY='A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'\n\n# mysql数据库连接信息,mysql+mysqlconnector(解决 Warning: (1366, \"Incorrect string value: '\\xD6\\xD0\\xB9\\xFA\\xB1\\xEA.)\n# https://segmentfault.com/a/1190000010596306\nSQLALCHEMY_DATABASE_URI = 'mysql+mysqlconnector://root:123456@localhost:3306/blog_db'\n\nSQLALCHEMY_COMMIT_TEARDOWN = True\nSQLALCHEMY_TRACK_MODIFICATIONS = True","sub_path":"Flask_basic/FlaskModles/blog/instance/setting.py","file_name":"setting.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"432138423","text":"from skimage.color import rgb2gray\nfrom skimage.color import rgb2grey\nimport matplotlib.pyplot as plt\nimport matplotlib.image as im # im 用于读取图片\nimport numpy as np\nimport cv2\n\ndef grayAndBinary(img):\n '''\n 1、三通道彩色图转灰度图\n 2、灰度图二值化\n 各通道的权重:\n Y = 0.2125 R + 0.7154 G + 0.0721 B\n :param img:\n :return:\n '''\n print(img.shape)\n # 设置2行,2列的图像网格,img填充第一个单元格\n plt.subplot(221)\n plt.imshow(img)\n\n # 彩色图片灰度化处理\n gray_img = rgb2gray(img)\n # gray_img填充第二个单元格\n plt.subplot(222)\n plt.imshow(gray_img)\n\n # rgb2grey = rgb2gray\n grey_img = rgb2grey(img)\n plt.subplot(223)\n plt.imshow(grey_img)\n\n (h, w) = gray_img.shape\n two_value_img = np.zeros(gray_img.shape, dtype=np.uint8)\n for i in range(h):\n for j in range(w):\n ori_px = gray_img[i, j]\n # 灰度化处理后的图像像素值已经转为[0,1]浮点数\n if ori_px <= 0.5:\n two_value_img[i, j] = 0\n else:\n two_value_img[i, j] = 1\n\n plt.subplot(224)\n plt.imshow(two_value_img)\n plt.show()\n\n\ndef bilinear_interpolation(img, out_dim):\n '''\n 双线性插值\n :param img: 输入图片\n :param out_dim: 输出图片纬度[h,w]\n :return:\n '''\n src_h, src_w, channel = img.shape\n dst_img = np.zeros((out_dim[0], out_dim[1], 3), dtype=np.uint8)\n print(dst_img.shape)\n (h, w, c) = dst_img.shape\n\n # 计算原始图片与目标图片的比例\n scale_y = float(src_h) / h\n scale_x = float(src_w) / w\n for n in range(3):\n for dst_y in range(h):\n for dst_x in range(w):\n # 计算目标做标在原图像的位置\n src_x = scale_x * (dst_x + 0.5) - 0.5\n src_y = scale_y * (dst_y + 0.5) - 0.5\n\n # 目标在原图上最邻近的四个点的坐标\n src_x_1 = int(np.floor(src_x))\n src_y_1 = int(np.floor(src_y))\n src_x_2 = min(src_x_1 + 1, src_w - 1)\n src_y_2 = min(src_y_1 + 1, src_h - 1)\n\n # 双线性插值计算\n # X方向进行两次插值,得到temp0(原始图像中坐标[src_y_1, src_x_1]和坐标[src_y_1, src_x_2])和temp1(原始图像中坐标[src_y_2, src_x_1]和坐标[src_y_2, src_x_2])两个像素值\n temp0 = (src_x_2 - src_x) * img[src_y_1, src_x_1, n] + (src_x - src_x_1) * img[src_y_1, src_x_2, n]\n temp1 = (src_x_2 - src_x) * img[src_y_2, src_x_1, n] + (src_x - src_x_1) * img[src_y_2, src_x_2, n]\n # Y方向进行插值,得到目标图像坐标[dst_y, dst_x]的像素值\n dst_img[dst_y, dst_x, n] = int((src_y_2 - src_y) * temp0 + (src_y - src_y_1) * (temp1))\n\n return dst_img\n\n\ndef hisogram_equalization(img):\n '''\n 直方图均衡化\n :param img: 原始三通道图片\n :return: 均衡化处理后的图片\n '''\n cv2.imshow('src img', img)\n # 分割三通道图片\n (b, g, r) = cv2.split(img)\n bh = _equalization(b)\n gh = _equalization(g)\n rh = _equalization(r)\n\n # bh = cv2.equalizeHist(b)\n # gh = cv2.equalizeHist(g)\n # rh = cv2.equalizeHist(r)\n\n dst_img = cv2.merge((bh, gh, rh))\n print(dst_img.shape)\n plt.hist(rh.flatten(), bins=256, density=1)\n plt.show()\n return dst_img\n\ndef _equalization(img):\n '''\n 对输入图片进行均衡化处理\n :param img: 单通道图片\n :return: 均衡化之后的单通道图片\n '''\n (h, w) = img.shape\n img_vector = img.flatten()\n ni = [0] * 256\n for i in img_vector:\n ni[i] += 1\n pi = [ni[j] / (h * w) for j in range(256)]\n\n sum_pi = [0] * 256\n # 初始累加第一个值\n sum_pi[0] = pi[0]\n # 从1开始遍历累加\n for i in range(1, 256):\n sum_pi[i] = sum_pi[i - 1] + pi[i]\n\n dst_img = np.zeros((h, w), dtype=np.uint8)\n for y in range(h):\n for x in range(w):\n dst_img[y, x] = sum_pi[img[y, x]] * 256 - 1\n\n return dst_img\n\n\nif __name__ == '__main__':\n img = cv2.imread('lenna.png')\n # # 灰度处理&二值化处理\n # grayAndBinary(img)\n # # 双线性插值\n dst = bilinear_interpolation(img, [1080, 1080])\n # dst = hisogram_equalization(img)\n cv2.imshow('histogram equliazation img',dst )\n # cv2.imshow('bilinear interpolation', dst)\n # cv2.imwrite('lenna.1080.1080.png', dst)\n # cv2.waitKey()\n\n\n # 直方图均衡化测试数据\n # arr = np.array([[1, 3, 9, 9, 8], [2, 1, 3, 7, 3], [3, 6, 0, 6, 4], [6, 8, 2, 0, 5], [2, 9, 2, 6, 0]])\n # print(_equalization(arr))\n","sub_path":"Homework/54-丁玉民-北京/week2/week2.py","file_name":"week2.py","file_ext":"py","file_size_in_byte":4703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"577424673","text":"\"\"\"\nBy uploading model predictions to Nucleus, you can compare your predictions to ground truth annotations and discover problems with your Models or Dataset.\n\nYou can also upload predictions for unannotated images, letting you query them based on model predictions. This can help you prioritize which unlabeled data to label next.\n\nWithin Nucleus, Models work in the following way:\n\n1. You first create a Model. You can do this just once and reuse the model on multiple datasets.\n2. You then upload predictions to a dataset.\n3. Trigger calculation of model metrics in order to view model debugging insights.\n\nDoing the three steps above allows you to visualize model performance within Nucleus, or compare multiple models that have been run on the same Dataset.\n\n\nNote that you can always add more predictions to a dataset, but then you will need to re-run the calculation of metrics in order to have them be correct.\n\n::\n\n import nucleus\n\n client = nucleus.NucleusClient(\"YOUR_SCALE_API_KEY\")\n dataset = client.get_dataset(\"YOUR_DATASET_ID\")\n prediction_1 = nucleus.BoxPrediction(\n label=\"label\",\n x=0,\n y=0,\n width=10,\n height=10,\n reference_id=\"1\",\n confidence=0.9,\n class_pdf={\"label\": 0.9, \"other_label\": 0.1},\n )\n prediction_2 = nucleus.BoxPrediction(\n label=\"label\",\n x=0,\n y=0,\n width=10,\n height=10,\n reference_id=\"2\",\n confidence=0.2,\n class_pdf={\"label\": 0.2, \"other_label\": 0.8},\n )\n model = client.add_model(\n name=\"My Model\", reference_id=\"My-CNN\", metadata={\"timestamp\": \"121012401\"}\n )\n # For small ingestions, we recommend synchronous ingestion\n response = dataset.upload_predictions(model, [prediction_1, prediction_2])\n # For large ingestions, we recommend asynchronous ingestion\n job = dataset.upload_predictions(\n [prediction_1, prediction_2], asynchronous=True\n )\n # Check current status\n job.status()\n # Sleep until ingestion is done\n job.sleep_until_complete()\n # Check errors\n job.errors()\n\n dataset.calculate_evaluation_metrics(model)\n\"\"\"\nfrom typing import List, Optional, Dict, Union\nfrom .dataset import Dataset\nfrom .prediction import (\n BoxPrediction,\n CuboidPrediction,\n PolygonPrediction,\n SegmentationPrediction,\n)\nfrom .model_run import ModelRun\nfrom .constants import (\n NAME_KEY,\n REFERENCE_ID_KEY,\n METADATA_KEY,\n)\n\n\nclass Model:\n \"\"\"A model that can be used to upload predictions to a dataset.\n\n Attributes:\n model_id: The scale-generated unique id for this model\n name: A human-readable name for the model\n reference_id: This is a unique, user-controlled ID for the model. This can be\n used, for example, to link to an external storage of models which may\n have its own id scheme.\n metadata: An arbitrary dictionary of additional data about this model that\n can be stored and retrieved. For example, you can store information\n about the hyperparameters used in training this model.\n \"\"\"\n\n def __init__(\n self,\n model_id: str,\n name: str,\n reference_id: str,\n metadata: Optional[Dict],\n client,\n ):\n self.id = model_id\n self.name = name\n self.reference_id = reference_id\n self.metadata = metadata\n self._client = client\n\n def __repr__(self):\n return f\"Model(model_id='{self.id}', name='{self.name}', reference_id='{self.reference_id}', metadata={self.metadata}, client={self._client})\"\n\n def __eq__(self, other):\n return (\n (self.id == other.id)\n and (self.name == other.name)\n and (self.metadata == other.metadata)\n and (self._client == other._client)\n )\n\n def __hash__(self):\n return hash(self.id)\n\n @classmethod\n def from_json(cls, payload: dict, client):\n return cls(\n model_id=payload[\"id\"],\n name=payload[\"name\"],\n reference_id=payload[\"ref_id\"],\n metadata=payload[\"metadata\"] or None,\n client=client,\n )\n\n def create_run(\n self,\n name: str,\n dataset: Dataset,\n predictions: List[\n Union[\n BoxPrediction,\n PolygonPrediction,\n CuboidPrediction,\n SegmentationPrediction,\n ]\n ],\n metadata: Optional[Dict] = None,\n asynchronous: bool = False,\n ) -> ModelRun:\n \"\"\"Note: this method, as well as model runs in general are now deprecated.\n\n Instead models will automatically generate a model run when applied to a dataset\n using dataset.upload_predictions(model, predictions). Therefore there is no\n longer any need to create a model run, since you can upload predictions\n without needing to explicitly create a model run.\n\n When uploading to a dataset twice using the same model, the same model run\n will be reused by Nucleus.\n \"\"\"\n payload: dict = {\n NAME_KEY: name,\n REFERENCE_ID_KEY: self.reference_id,\n }\n if metadata:\n payload[METADATA_KEY] = metadata\n model_run: ModelRun = self._client.create_model_run(\n dataset.id, payload\n )\n\n model_run.predict(predictions, asynchronous=asynchronous)\n\n return model_run\n","sub_path":"nucleus/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"333948049","text":"import sys\n\n# create a new list with the transcriptions in the table\ntranscriptions = []\n\n# creates a list of tuples with the latin (nahuatl) alphabet\n# and the ipa-ish character\nfd = open('transtable.txt', 'r')\nfor line in fd.readlines():\n stripped = line.strip('\\n')\n (latin, ipa) = stripped.split(' ')\n # for some reason it said it was split by spaces instead of tabs even though I used tabs, so I just had it split by space\n couple = (latin, ipa)\n transcriptions.append(couple)\n\n# this function converts a string from nahuatl orthography to IPA (ish)\n# it reads a string by character\ndef to_ipa(s):\n in_ipa = \"\"\n lowered = s.lower()\n for letter in lowered: # iterates by character through string\n for pair in transcriptions: #iterates by tuple in the transcription list\n if letter == pair[0]: #if the current letter of the given string is equal to the latin letter in the tuple\n in_ipa = in_ipa + pair[1] #concatenate the already transcribed characters and this new character\n continue # the character has been found, so we can break the inner loop over transcriptions for this character only\n return in_ipa\n\ntext = sys.stdin.read()\n\nlines = text.split(\"\\n\") #split by line in input text\n\n\n\n#for j in range(0, len(lines)):\nfor line in lines:\n\n #if '\\t' not in line:\n # continue\n row = line.split('\\t')\n if len(row) != 10:\n print(row[0])\n continue\n transcribed = to_ipa(row[1])\n if (transcribed is None): # if something was not transcribed (punctuation mark, etc)\n row[9] = \"IPA=\"\n else: # if something was transcribed\n row[9] = \"IPA=\"+transcribed\n count = row[0]\n token = row[1]\n transcription = row[9]\n print(f'{count}\\t{token}\\t_\\t_\\t_\\t_\\t_\\t_\\t_\\t{transcription}')\n\n\n\"\"\"\nQuestions:\n\nIf there's an environment that triggers a certain sound, like if a letter is a certain sound\nafter a vowel and a different sound in other environments, then the program could look\nat the environment surrounding the letter to see which\n\nEach letter, instead of containing a single mapping, could contain a list of tuples containing an environment (like\na certain letter combination)\nSimilarly, we could check if there was no preceeding character or following character in this by checking what was\non either side of this character in the string.\n\"\"\"\n","sub_path":"practicals/transcribe.py","file_name":"transcribe.py","file_ext":"py","file_size_in_byte":2387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"122198046","text":"#Reference Video: https://youtu.be/m7GyMS67110\n# \"\"\"\n# This is ArrayReader's API interface.\n# You should not implement it, or speculate about its implementation\n# \"\"\"\n#class ArrayReader:\n# def get(self, index: int) -> int:\n\nclass Solution:\n def search(self, reader, target):\n \"\"\"\n :type reader: ArrayReader\n :type target: int\n :rtype: int\n \"\"\"\n #Initially consider left as 0 and right as 1 since they are the minimum values possible for left and right\n left = 0\n right = 1\n \n #we have to keep checking until the target falls before right pointer in the array\n #if not found, make the right as left and multiply the right by 2 to obtain new right pointer\n while (reader.get(right) < target):\n left = right\n right = right * 2\n\n #perform binary search \n while (left <= right):\n mid = (left + right) // 2\n if reader.get(mid) == target:\n return mid\n elif target < reader.get(mid):\n right = mid - 1\n else:\n left = mid + 1\n \n return -1\n ","sub_path":"Search-in-a-sorted-array-of-unknown-size.py","file_name":"Search-in-a-sorted-array-of-unknown-size.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"466772403","text":"# -*- coding: utf-8 -*-\n# File: config.py\n\nimport numpy as np\nimport os\nimport pprint\nfrom tensorpack.utils import logger\nfrom tensorpack.utils.gpu import get_num_gpu\n\n__all__ = ['config', 'finalize_configs']\n\n\nclass AttrDict():\n\n _freezed = False\n \"\"\" Avoid accidental creation of new hierarchies. \"\"\"\n\n def __getattr__(self, name):\n if self._freezed:\n raise AttributeError(name)\n ret = AttrDict()\n setattr(self, name, ret)\n return ret\n\n def __setattr__(self, name, value):\n if self._freezed and name not in self.__dict__:\n raise AttributeError(\"Cannot create new attribute!\")\n super().__setattr__(name, value)\n\n def __str__(self):\n return pprint.pformat(self.to_dict(), indent=1)\n\n __repr__ = __str__\n\n def to_dict(self):\n \"\"\"Convert to a nested dict. \"\"\"\n return {k: v.to_dict() if isinstance(v, AttrDict) else v\n for k, v in self.__dict__.items() if not k.startswith('_')}\n\n def update_args(self, args):\n \"\"\"Update from command line args. \"\"\"\n for cfg in args:\n keys, v = cfg.split('=', maxsplit=1)\n keylist = keys.split('.')\n\n dic = self\n for i, k in enumerate(keylist[:-1]):\n assert k in dir(dic), \"Unknown config key: {}\".format(keys)\n dic = getattr(dic, k)\n key = keylist[-1]\n\n oldv = getattr(dic, key)\n if not isinstance(oldv, str):\n v = eval(v)\n setattr(dic, key, v)\n\n def freeze(self):\n self._freezed = True\n for v in self.__dict__.values():\n if isinstance(v, AttrDict):\n v.freeze()\n\n # avoid silent bugs\n def __eq__(self, _):\n raise NotImplementedError()\n\n def __ne__(self, _):\n raise NotImplementedError()\n\n\nconfig = AttrDict()\n_C = config # short alias to avoid coding\n\n# mode flags ---------------------\n\n\n# dataset -----------------------\n_C.DATA.BASEDIR = '/data1/junjiaot/data'#'/path/to/your/COCO/DIR'\n_C.DATA.IMGDIR = '/data1/junjiaot/images/resized'\n_C.DATA.FEATUREDIR = '/home/junjiaot/data_local'\n_C.DATA.DATA = 'frcnn_features36'\n# TRAINING ----------------------\n_C.LR = 5e-4 \n_C.DECAY_EPOCH = 20\n_C.MIL_STOP_EPOCH = 5\n_C.DECAY_STEP = 70\n_C.DECAY_RATE = 0.5\n_C.MAX_EPOCH = 70\n_C.EVAL_PERIOD = 1000\n_C.PRINT_EVERY = 100\n_C.BATCH_SIZE = 128\n_C.START_EPOCH = 0\n_C.EVAL = False\n_C.LOAD = None#'/data1/junjiaot/data/checkpoint_v16_bare/checkpoint'#'/data1/junjiaot/data/checkpoint_v16/checkpoint'#None#'/data1/junjiaot/data/checkpoint_v10_3/checkpoint'\n_C.CHECKPOINT_DIR = '/data1/junjiaot/data/checkpoint_v16_no_MIL'\n_C.CHECKPOINT_DIR_MAX = '/data1/junjiaot/data/checkpoint_v16_no_MIL'\n_C.SCORE_DIR = './score_v16_no_MIL'\n_C.EVAL_CAP = 'eval_v16_no_MIL'\n#MODEL --------------------\n_C.VOCAB_DIM = 300\n_C.NUM_REGION = 36\n_C.GLOBAL_FEATURE_DIM = 2048\n_C.REGION_FEATURE_DIM = 2053\n_C.PRE_EMB = True\n\ndef finalize_configs(is_training):\n \"\"\"\n Run some sanity checks, and populate some configs from others\n \"\"\" \n pass\n","sub_path":"modular_captioning/model/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"43898256","text":"def numero_no_indice(lista):\n indice = [i for i in range(len(lista))]\n iguais = []\n i = 0 \n while i list:\n \"\"\"Query side and return a list of events\n\n :param kargs: Extra options for the call\n :return: A list of items. The type of these items depends on the derived\n class\n \"\"\"\n raise NotImplementedError(\"Implement in derived\")\n\n @abc.abstractmethod\n def get_item(self, item_id: str, use_cached: bool = False) -> Optional[dict]:\n \"\"\"Get a single item based on the given UUID.\n\n :use_cached: False if you want to fetch the latest version of the item. True if a\n cached version would do.\n :returns: None if not found, the item in dict representation otherwise\n \"\"\"\n raise NotImplementedError(\"Should be implemented in derived\")\n\n @abc.abstractmethod\n def delete_single_item(self, item_id: str):\n \"\"\"Delete an item based on the given UUID.\n\n .. raises:: Keyerror if item is not found.\n \"\"\"\n raise NotImplementedError(\"Should be implemented in derived\")\n\n @abc.abstractmethod\n def update_item(self, item_id: str, **changes):\n \"\"\"Update with the given item.\n\n :param item_id : ID of item to update\n :param changes: Keyword only parameters that are to change in the item\n .. warning:: The item must already be present\n \"\"\"\n raise NotImplementedError(\"Should be implemented in derived\")\n\n @abc.abstractmethod\n def add_item(self, item: dict) -> dict:\n \"\"\"Add a new item.\n\n :returns: The newly added event\n \"\"\"\n raise NotImplementedError(\"Implement in derived\")\n\n @staticmethod\n def items_are_identical(item1: dict, item2: dict, ignore_keys=[]) -> bool:\n \"\"\"Determine whether two items are identical.\n\n .. returns:: True if items are identical, False otherwise.\n \"\"\"\n raise NotImplementedError(\"Implement in derived\")\n\n @staticmethod\n def _items_are_identical(item1: dict, item2: dict, keys: list) -> bool:\n \"\"\"Compare the provided keys of the two given items.\n\n Take extra care of the datetime key.\n \"\"\"\n\n for k in keys:\n if k not in item1 and k not in item2:\n continue\n\n if (k in item1 and k not in item2) or (k not in item1 and k in item2):\n return False\n\n if isinstance(item1[k], datetime.datetime) and isinstance(\n item2[k], datetime.datetime\n ):\n if is_same_datetime(item1[k], item2[k]):\n continue\n else:\n logger.opt(lazy=True).trace(\n f\"\\n\\nItems differ\\n\\nItem1\\n\\n{item1}\\n\\nItem2\\n\\n{item2}\"\n f\"\\n\\nKey [{k}] is different - [{repr(item1[k])}] | [{repr(item2[k])}]\"\n )\n return False\n else:\n if item1[k] == item2[k]:\n continue\n else:\n logger.opt(lazy=True).trace(\n f\"\\n\\nItems differ\\n\\nItem1\\n\\n{item1}\\n\\nItem2\\n\\n{item2}\"\n f\"\\n\\nKey [{k}] is different - [{repr(item1[k])}] | [{repr(item2[k])}]\"\n )\n return False\n\n return True\n","sub_path":"taskw_gcal_sync/GenericSide.py","file_name":"GenericSide.py","file_ext":"py","file_size_in_byte":3741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"320393052","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def sortList(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n def sort(head, tail, res):\n slow = head\n fast = head.next.next\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n res1 = sort(head, slow)\n res2 = sort(slow.next, tail)\n res_head = merge(res1, res2)\n return res_head\n \n def merge(head1, head2):\n while head1 and head2:\n if head1.val > head2.val:\n tmp1 = head1.next\n tmp2 = head2.next\n head1.next = head2\n head1.next = tmp1.next\n head2.next = tmp2\n","sub_path":"148 Sort List.py","file_name":"148 Sort List.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"268480004","text":"import boto3\nddb = boto3.client(\"dynamodb\")\nimport pandas as pd\ns3 = boto3.client(\"s3\")\n\ndef read_file(event, context):\n # print(\"Reading from s3...\")\n try:\n data = s3.get_object(\n Bucket=\"awssigmabocket\",\n Key=\"testdata.csv\"\n )\n books_df = pd.read_csv(data.get(\"Body\"))\n print(books_df)\n \n for i in range(len(books_df)):\n try:\n dy_db = ddb.put_item(\n TableName=\"emptable\",\n Item={\n 'id': {\n 'N': str(books_df['id'][i])\n },\n 'name': {\n 'S': books_df['name'][i]\n }\n }\n )\n print(dy_db,\"@@@\")\n except BaseException as e:\n print(e)\n raise(e)\n \n except BaseException as e:\n print(e)\n raise(e)\n \n return {\"message\": \"Successfully read file from S3 and inserted to DDB\"}\n\n","sub_path":"sigma_demo.py","file_name":"sigma_demo.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"504251320","text":"import os\nimport argparse\nimport re\nimport chardet\nfrom collections import Counter\n\nMOST_COMMON_WORDS_NUMB = 10\n\ndef define_charset(filepath):\n if not os.path.isfile(filepath):\n return None\n with open(filepath,'rb') as file_with_unkwown_charset:\n file_charset = chardet.detect(file_with_unkwown_charset.read()).get('encoding')\n return file_charset\n\ndef load_data(filepath):\n if not os.path.isfile(filepath):\n return None\n with open(filepath, 'r', encoding = define_charset(filepath)) as content:\n opened_text = content.read()\n return opened_text\n \ndef get_most_frequent_words(opened_text):\n separated_text = re.findall(r'\\w+', opened_text.lower())\n most_frequent_words = Counter(separated_text).most_common(MOST_COMMON_WORDS_NUMB) \n return most_frequent_words\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-p','--path', required = True,\n help = 'Enter path to file')\n namespace = parser.parse_args()\n\n try:\n file_text = load_data(namespace.path)\n frequent_words_list = get_most_frequent_words(file_text)\n print('\\n{} the most frequent words in text:\\n'.format(MOST_COMMON_WORDS_NUMB))\n for word_count in frequent_words_list:\n print('\"{}\": {}'.format(word_count[0].capitalize(), word_count[1]))\n except AttributeError:\n print('\\nWrong filepath.')\n","sub_path":"lang_frequency.py","file_name":"lang_frequency.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"214640702","text":"from django.shortcuts import render, redirect\nfrom .models import Proposition\n# Add the following import\nfrom django.http import HttpResponse, HttpResponseRedirect\n\n# Define the home view\ndef home(request):\n return render(request, 'home.html')\n\ndef about(request):\n return render(request, 'about.html')\n\ndef start(request):\n return redirect('show', proposition_id=1)\n\ndef index(request):\n propositions = Proposition.objects.all().order_by('number')\n context = {\n 'propositions': propositions\n }\n return render(request, 'index.html', context)\n\n\ndef show(request, proposition_id):\n side_bar_proposition_numbers = Proposition.objects.all().order_by('number')\n proposition = Proposition.objects.get(id=proposition_id)\n \n if request.method == 'POST':\n\n print(request.POST['proposition'])\n selected_option = request.POST.get('proposition', False);\n\n if selected_option == 'yes':\n proposition.yes_count += 1\n proposition.color = '#EBB62B'\n # print(proposition.color)\n elif selected_option == 'no':\n proposition.no_count += 1\n proposition.color = '#EBB62B'\n # print(proposition.color)\n else:\n return HttpResponse(400, 'Invalid Form') \n \n proposition.save()\n\n # return redirect('index')\n return HttpResponseRedirect(request.path_info)\n\n context = {\n 'proposition': proposition,\n 'side_bar_proposition_numbers': side_bar_proposition_numbers,\n }\n return render(request, 'show.html', context)","sub_path":"main_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"275656423","text":"# 核心处理文件\nimport numpy as np\nimport pandas as pd\nimport random\nfrom sklearn import svm\nfrom sklearn import tree\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.svm import SVC\nfrom data.Data import shuffle, splitDataToCouples\nfrom models.models import single_train, cross_val_train\nfrom transforms.TheFirstRelationship import single_sin, single_cos, single_tan, ori_sin, ori_cos, ori_tan, \\\n single_arcsin, single_arccos, single_arctan, ori_arcsin, ori_arccos, ori_arctan, \\\n single_square, ori_square, single_normalizetion, ori_normalizetion\nfrom transforms.TheSecondRelationship import single_pca, ori_pca, newly_feature, ori_newly\nfrom transforms.TheThirdRelationship import get_newly_feature_x_y, ori_newly_feature_x_y\nfrom transforms.unio import A_plus_B\nfrom RL.rl_brain import QLearningTable\nfrom Selection import selectByIG\nimport copy\n\nnp.random.seed(7)\n\n\ndef execu_action(action, dataset, clf, state, actions):\n '''\n 执行一次动作计算奖励\n :param action:\n :param dataset:\n :param clf:\n :param state:\n :param actions:\n :return:\n '''\n # state_ = state\n state_ = copy.deepcopy(state)\n state_.append(action)\n acc_ori = single_train(clf, dataset)\n df = actions[action](dataset)\n df = selectByIG(df)\n global max_acc\n global max_state\n try:\n acc = single_train(clf, df)\n if acc > max_acc:\n max_acc = acc\n max_state = state_\n print(\"cuttent_acc:\", acc)\n print(\"max_acc:\", max_acc)\n print(\"max_state:\", max_state)\n except Exception as e:\n print(e)\n reward = acc - acc_ori\n return state_, reward, df\n\n\ndef RL_update(q_table, dataset, train=True, clf=\"PSVM\"):\n '''\n Q-learning的训练过程\n :param q_table:\n :param dataset:\n :return:\n '''\n models = [KNeighborsClassifier(), svm.LinearSVC(), SVC(kernel='rbf', gamma=\"auto\"),\n RandomForestClassifier(), AdaBoostClassifier(), MLPClassifier(), tree.DecisionTreeClassifier()]\n model_names = ['kNN', 'LSVM', 'PSVM', 'RF', 'AB', 'NN', 'DT']\n if not train:\n model_name = clf\n clf_i = model_names.index(clf)\n clf = models[clf_i]\n for episode in range(MAX_EPISODE):\n if train:\n n_clfs = len(models)\n model_num = random.randint(0, n_clfs - 1)\n model_name = model_names[model_num]\n clf = models[model_num]\n df = dataset\n process_flow = [model_name]\n state = process_flow\n for i in range(MAX_DEPTH):\n # choose acton\n action = q_table.choose_action(str(state))\n while i < MAX_DEPTH - 1 and action >= 14:\n action = q_table.choose_action(str(state))\n # exec action\n state_, reward, df = execu_action(action, df, clf, state, actions)\n # update qtable\n q_table.learn(str(state), action, reward, str(state_))\n # update state\n state = state_\n print(q_table.q_table)\n print(\"episode:\", episode)\n q_table.q_table.to_csv(\"qtable.csv\")\n print(\"done!\")\n # q_table.q_table.to_csv(\"qtable.csv\")\n print(\"max_acc:\", max_acc)\n print(\"max_state:\", max_state)\n\n\nactions = [single_sin, single_cos, single_tan, ori_sin, ori_cos, ori_tan, single_square, ori_square,\n single_normalizetion, ori_normalizetion, single_pca, ori_pca, get_newly_feature_x_y, ori_newly_feature_x_y,\n newly_feature, ori_newly, ]\n\ndataset_path = 'datasets/sonar/sonar.csv'\nsave_to = 'datasets/ecoli/'\nMAX_EPISODE = 100 # 训练次数\nMAX_DEPTH = 5 # 深度\nmax_acc = 0\nmax_state = [] # 12 13 13\n\nif __name__ == '__main__':\n # RL train process\n df = pd.read_csv(dataset_path, header=None)\n df = shuffle(df)\n q_table = QLearningTable(actions=list(range(len(actions))))\n RL_update(q_table, df, True, \"PSVM\")\n\n # test train process\n # df = get_newly_feature_x_y(df)\n # df = selectByIG(df)\n # df = ori_newly_feature_x_y(df)\n # df = selectByIG(df)\n # df = ori_newly_feature_x_y(df)\n # df = selectByIG(df)\n # clf = SVC(kernel='rbf', gamma=\"auto\")\n # acc = single_train(clf, df)\n # print(acc)\n","sub_path":"Handle.py","file_name":"Handle.py","file_ext":"py","file_size_in_byte":4410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"176479069","text":"from time import sleep\nfrom datetime import date\nimport random\nimport os\n\nimport telepot\nimport psutil\n\n\ndef get_cpu_percentage():\n return f'CPU usage is at {psutil.cpu_percent()}%'\n\n\ndef get_random_phrase():\n messages = [\n 'Some',\n 'random',\n 'responses'\n ]\n return random.choice(messages)\n\n\ndef get_current_date():\n today = date.today()\n return f'Today is {today.strftime(\"%d/%m/%Y\")}'\n\n\nTOKEN = os.environ['TELEGRAM_TOKEN']\nBOT = telepot.Bot(TOKEN)\nOPTIONS = {\n 'cpu_percentage': get_cpu_percentage,\n 'random_phrase': get_random_phrase,\n 'current_date': get_current_date\n}\n\n\ndef get_response(msg):\n chat_id = msg['chat']['id']\n command = msg['text']\n\n if command in OPTIONS.keys():\n BOT.sendMessage(chat_id, OPTIONS[command]())\n\n\nBOT.message_loop(get_response)\n\nwhile True:\n sleep(1)\n","sub_path":"telegram_chatbot.py","file_name":"telegram_chatbot.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"316613085","text":"# t = \"a\", \"b\", \"c\"\n# print(t)\n#\n# print(\"a\", \"b\", \"c\")\n# print((\"a\", \"b\", \"c\"))\n\n# welcome = \"Welcome to my Nightmare\", \"Alice Cooper\", 1975\n# bad = \"Bad Company\" \"Bad Company\", 1974\n# budgie = \"Nightflight\", \"Budgie\", 1981\n# # imelda = \"More Mayhem\", \"Imilda May\", 2011, (1, \"Pulling the Rug\"), (2, \"Psycho\"), (3, \"Mayhem\"), (4, \"Kentish Town Waltz\")\n# imelda = \"More Mayhem\", \"Imelda May\", 2011, 1, \"Pulling the Rug\", 2, \"Psycho\", 3, \"Mayhem\", 4, \"Kentish Town Waltz\"\n#\n# print(imelda)\n#\n# title, artist, year, track1, track2, track3, track4 = imelda\n# print(title)\n# print(artist)\n# print(year)\n# print(track1)\n# print(track2)\n# print(track3)\n# print(track4)\n\n# metallica = \"Ride the Lightning\", \"Metallica\", 1984\n\n# print(metallica)\n# print(metallica[0])\n# print(metallica[1])\n# print(metallica[2])\n#\n# # metallica[0] = \"Master of Puppets\" # Error, tuples does not support item assignment, but slicing and indexing...\n#\n# imelda = imelda[0], \"Imelda May\", imelda[2]\n# print(imelda)\n\n# metallica2 = [\"Ride the Lightning\", \"Metallica\", 1984]\n# print(metallica2)\n\n# a = b = c = d = 12\n# print(c)\n# a, b = 12, 13\n# print(a, b)\n#\n# a, b = b, a\n# print(\"a is {}\".format(a))\n# print(\"b is {}\".format(b))\n\n# title, artist, year = imelda\n# metallica2.append(\"Rock\") # If tuple is used, can't append / immutable => Less errors\n# imelda.append(\"Jazz\")\n\n# title, artist, year = metallica2 # Error, too many values to unpack\n# print(title)\n# print(artist)\n# print(year)\n\n# CHALLENGE\n# Given the tuple below that represents the Imleda May track \"More Mayhem\", write\n# code to print the album details, followed by a listing of all the tracks in the album.\n#\n# Indent the tracks by a single tab stop when printing them (remember that you can pass\n# more than one item to the print function, separating them with a comma)\n\nimelda = \"More Mayhem\", \"Imelda May\", 2011, (\n (1, \"Pulling the Rug\"), (2, \"Psycho\"), (3, \"Mayhem\"), (4, \"Kentish Town Waltz\"),\n)\nalbum, author, year, tracks = imelda\nprint(\"Album\\t\\tAuthor\\t\\tYear\")\nprint(album, author, year, sep=\"\\t\")\n\nfor track in tracks:\n print(\"\\t\", track)\n\nimelda = \"More Mayhem\", \"Imelda May\", 2011, (\n [(1, \"Pulling the Rug\"), (2, \"Psycho\"), (3, \"Mayhem\"), (4, \"Kentish Town Waltz\")]\n)\n\nprint(imelda)\n\nimelda[3].append((5, \"All For You\"))\n\ntitle, artist, year, tracks = imelda\ntracks.append((6, \"Eternity\"))\nprint(title)\nprint(artist)\nprint(year)\nfor song in tracks:\n track, title = song\n print(\"\\tTrack number {}, Title: {}\".format(track, title))\n","sub_path":"ListsRanges&Tuples/tuples.py","file_name":"tuples.py","file_ext":"py","file_size_in_byte":2502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"142177231","text":"import scrapy\nfrom scrapy.spiders import Spider \nimport json\nfrom scrapy.selector import Selector\nfrom scrapy.utils.response import open_in_browser\n\nclass MyItem(scrapy.Item):\n\tlink_url=scrapy.Field()\n\tauthor = scrapy.Field()\n\tdate = scrapy.Field()\n\nclass MySpider(Spider):\n\tname = 'myspider'\n\tstart_urls = ['http://gcaptain.com/' ]\n\tdownload_delay =1.5\n\n\tdef parse(self, response):\n\t\tprint(response.url)\n\t\tyield self.create_ajax_next_page_request('1')\n\n\tdef create_ajax_next_page_request(self,page):\n\t\t\tprint('yield page: ', page)\n\t\t\tcookies = {\n\t\t\t '__cfduid': 'd1ed137e97e97b743f2166818aa58fc9d1517302758',\n\t\t\t '__gads': 'ID=7b2dc51b035f63a5:T=1517302762:S=ALNI_Maz4hK4lnY6qC7cmNm3GhMCwqo_SQ',\n\t\t\t 'CFID': 'Z3od2j13nv3v62q4bduqcgjydr1hkoum3ulfclae6uij7vazub-602819736',\n\t\t\t 'CFTOKEN': 'Z3od2j13nv3v62q4bduqcgjydr1hkoum3ulfclae6uij7vazub-fd08a43e662b4d6d-BF1E95F7-5056-AD21-4E7B692CBA4B2640',\n\t\t\t 'contextly': '%7B%22id%22%3A%22EZcmklikwjNZUtMnWdpv1974T%22%7D',\n\t\t\t '__smSmartbarShown': 'Tue%20Jan%2030%202018%2015:00:38%20GMT+0600%20(BDT)',\n\t\t\t '__smListBuilderShown': 'Tue%20Jan%2030%202018%2015:07:36%20GMT+0600%20(BDT)',\n\t\t\t '__smListBuilderOptOut': 'true',\n\t\t\t '__smScrollBoxShown': 'Tue%20Jan%2030%202018%2015:15:26%20GMT+0600%20(BDT)',\n\t\t\t '_ga': 'GA1.2.1331354219.1517302761',\n\t\t\t '_gid': 'GA1.2.1919337390.1517302761',\n\t\t\t '_gat': '1',\n\t\t\t '__smVID': '9a73c374d9f2bc374b37fa1df4834b19568aa555272f1f91aaeea7c4cda3f075',\n\t\t\t '__smToken': '7hoUl8NULiQtIkRAR9fX2aNZ',\n\t\t\t '__lx209024_load_cnt': '107',\n\t\t\t '__lx209024_load_tmr': '1517322623079',\n\t\t\t '__lx209024_load_tmr_pre': '1517322624918',\n\t\t\t}\n\n\t\t\theaders = {\n\t\t\t 'Origin': 'http://gcaptain.com',\n\t\t\t 'Accept-Encoding': 'gzip, deflate',\n\t\t\t 'Accept-Language': 'en-US,en;q=0.8,bn;q=0.6,af;q=0.4',\n\t\t\t 'User-Agent': 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/59.0.3071.109 Chrome/59.0.3071.109 Safari/537.36',\n\t\t\t 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n\t\t\t 'Accept': '*/*',\n\t\t\t 'Referer': 'http://gcaptain.com/',\n\t\t\t 'X-Requested-With': 'XMLHttpRequest',\n\t\t\t 'Connection': 'keep-alive',\n\t\t\t}\n\n\t\t\tdata = {'infinity':'scrolling',\n\t\t\t\t\t\t\t 'action': 'infinite_scroll',\n\t\t\t\t\t\t\t 'page':page,\n\t\t\t\t\t\t\t 'currentday': '30.01.18',\n\t\t\t\t\t\t\t 'order': 'DESC',\n\t\t\t\t\t\t\t 'scripts[]': 'jquery-core',\n\t\t\t\t\t\t\t 'scripts[]': 'jquery-migrate',\n\t\t\t\t\t\t\t 'scripts[]': 'jquery',\n\t\t\t\t\t\t\t 'scripts[]': 'spin',\n\t\t\t\t\t\t\t 'scripts[]': 'jquery.spin',\n\t\t\t\t\t\t\t 'scripts[]': 'tiled-gallery',\n\t\t\t\t\t\t\t 'scripts[]': 'mediaelement-core',\n\t\t\t\t\t\t\t 'scripts[]': 'mediaelement-migrate',\n\t\t\t\t\t\t\t 'scripts[]': 'mediaelement',\n\t\t\t\t\t\t\t 'scripts[]': 'html5shiv',\n\t\t\t\t\t\t\t 'scripts[]': 'magazine-entry-date',\n\t\t\t\t\t\t\t 'scripts[]': 'magazine-responsive-menu',\n\t\t\t\t\t\t\t 'scripts[]': 'imgareaselect',\n\t\t\t\t\t\t\t 'scripts[]': 'thickbox',\n\t\t\t\t\t\t\t 'scripts[]': 'ubermenu',\n\t\t\t\t\t\t\t 'scripts[]': 'ubermenu-sticky-js',\n\t\t\t\t\t\t\t 'scripts[]': 'the-neverending-homepage',\n\t\t\t\t\t\t\t 'scripts[]': 'devicepx',\n\t\t\t\t\t\t\t 'scripts[]': 'jetpack-carousel',\n\t\t\t\t\t\t\t 'scripts[]': 'wp-mediaelement',\n\t\t\t\t\t\t\t 'scripts[]':'wp-embed',\n\t\t\t\t\t\t\t 'styles[]': 'avatars',\n\t\t\t\t\t\t\t 'styles[]': 'imgareaselect',\n\t\t\t\t\t\t\t 'styles[]': 'dashicons',\n\t\t\t\t\t\t\t 'styles[]': 'thickbox',\n\t\t\t\t\t\t\t 'styles[]': 'the-neverending-homepage',\n\t\t\t\t\t\t\t 'styles[]': 'magazine-pro-theme',\n\t\t\t\t\t\t\t 'styles[]': 'ubermenu-raleway',\n\t\t\t\t\t\t\t 'styles[]': 'iconize-styles',\n\t\t\t\t\t\t\t 'styles[]': 'iconize-default-font-styles',\n\t\t\t\t\t\t\t 'styles[]': 'iconize-dashicons-font-styles',\n\t\t\t\t\t\t\t 'styles[]': 'jetpack-carousel',\n\t\t\t\t\t\t\t 'styles[]': 'jetpack-carousel-ie8fix',\n\t\t\t\t\t\t\t 'styles[]': 'tiled-gallery',\n\t\t\t\t\t\t\t 'styles[]': 'mediaelement',\n\t\t\t\t\t\t\t 'styles[]': 'wp-mediaelement',\n\t\t\t\t\t\t\t 'styles[]': 'google-fonts',\n\t\t\t\t\t\t\t 'styles[]': 'ubermenu',\n\t\t\t\t\t\t\t 'styles[]': 'ubermenu-flat-red-dark',\n\t\t\t\t\t\t\t 'styles[]': 'ubermenu-font-awesome',\n\t\t\t\t\t\t\t 'styles[]': 'gppro-style',\n\t\t\t\t\t\t\t 'styles[]': 'jetpack_css',\n\t\t\t\t\t\t\t 'query_args[error]': '',\n\t\t\t\t\t\t\t 'query_args[m]': '',\n\t\t\t\t\t\t\t 'query_args[p]':'0',\n\t\t\t\t\t\t\t 'query_args[post_parent]': '',\n\t\t\t\t\t\t\t 'query_args[subpost]': '',\n\t\t\t\t\t\t\t 'query_args[subpost_id]': '',\n\t\t\t\t\t\t\t 'query_args[attachment]':'',\n\t\t\t\t\t\t\t 'query_args[attachment_id]': '0',\n\t\t\t\t\t\t\t 'query_args[name]': '',\n\t\t\t\t\t\t\t 'query_args[static]': '',\n\t\t\t\t\t\t\t 'query_args[pagename]': '',\n\t\t\t\t\t\t\t 'query_args[page_id]': '0',\n\t\t\t\t\t\t\t 'query_args[second]': '',\n\t\t\t\t\t\t\t 'query_args[minute]': '',\n\t\t\t\t\t\t\t 'query_args[hour]': '',\n\t\t\t\t\t\t\t 'query_args[day]': '0',\n\t\t\t\t\t\t\t 'query_args[monthnum]': '0',\n\t\t\t\t\t\t\t 'query_args[year]':'0',\n\t\t\t\t\t\t\t 'query_args[w]': '0',\n\t\t\t\t\t\t\t 'query_args[category_name]': '',\n\t\t\t\t\t\t\t 'query_args[tag]': '',\n\t\t\t\t\t\t\t 'query_args[cat]': '',\n\t\t\t\t\t\t\t 'query_args[tag_id]': '',\n\t\t\t\t\t\t\t 'query_args[author]': '',\n\t\t\t\t\t\t\t 'query_args[author_name]': '',\n\t\t\t\t\t\t\t 'query_args[feed]': '',\n\t\t\t\t\t\t\t 'query_args[tb]': '',\n\t\t\t\t\t\t\t 'query_args[paged]': '0',\n\t\t\t\t\t\t\t 'query_args[meta_key]': '',\n\t\t\t\t\t\t\t 'query_args[meta_value]': '',\n\t\t\t\t\t\t\t 'query_args[preview]': '',\n\t\t\t\t\t\t\t 'query_args[s]': '',\n\t\t\t\t\t\t\t 'query_args[sentence]': '',\n\t\t\t\t\t\t\t 'query_args[title]': '',\n\t\t\t\t\t\t\t 'query_args[fields]': '',\n\t\t\t\t\t\t\t 'query_args[menu_order]': '',\n\t\t\t\t\t\t\t 'query_args[embed]': '',\n\t\t\t\t\t\t\t 'query_args[category__not_in][]': '3230',\n\t\t\t\t\t\t\t 'query_args[category__not_in][]': '1',\n\t\t\t\t\t\t\t 'query_args[posts_per_page]': '7',\n\t\t\t\t\t\t\t 'query_args[ignore_sticky_posts]': 'false',\n\t\t\t\t\t\t\t 'query_args[suppress_filters]': 'false',\n\t\t\t\t\t\t\t 'query_args[cache_results]': 'true',\n\t\t\t\t\t\t\t 'query_args[update_post_term_cache]': 'true',\n\t\t\t\t\t\t\t 'query_args[lazy_load_term_meta]': 'true',\n\t\t\t\t\t\t\t 'query_args[update_post_meta_cache]': 'true',\n\t\t\t\t\t\t\t 'query_args[post_type]':'',\n\t\t\t\t\t\t\t 'query_args[nopaging]': 'false',\n\t\t\t\t\t\t\t 'query_args[comments_per_page]': '50',\n\t\t\t\t\t\t\t 'query_args[no_found_rows]': 'false',\n\t\t\t\t\t\t\t 'query_args[order]':'DESC',\n\t\t\t\t\t\t\t 'last_post_date': '2018-01-29 05:12:25',}\n\t\t\t\n\t\t\treturn scrapy.FormRequest('http://gcaptain.com/page/{}'.format(page),\n\t\t\t\t\tmethod='POST',\n\t\t\t\t\tformdata=data,\n\t\t\t\t\tcookies=cookies,\n\t\t\t\t\theaders=headers,\n\t\t\t\t\tcallback=self.parse_items,\n\t\t\t\t\tdont_filter=True,)\n\n\tdef parse_items(self,response):\n\t\n\t\tfor itex in response.css('header.entry-header'):\n\t\t\titem={}\n\t\t\t\n\t\t\titem['link_url'] = itex.css('h2.entry-title a::attr(href)')[0:7].extract_first()\n\t\t\titem['author'] = itex.css('span.entry-author-name ::text').extract_first()\n\t\t\titem['date'] = itex.css('time.entry-time ::text').extract_first()\n\n\t\t\titem_to_yield = {}\n\t\t\tfor k, v in item.items():\n\t\t\t\tif v is not None:\n\t\t\t\t\titem_to_yield[k] = item[k]\n\t\t\tyield MyItem(**item_to_yield)\n\t\n\n\t\tpage = response.url.split('/')[-1]\n\t\tpage = str(int(page)+1)\n\t\tyield self.create_ajax_next_page_request(page )\n\n\t\t\n","sub_path":"form_post_per_request_with_discard_None_itemspider.py","file_name":"form_post_per_request_with_discard_None_itemspider.py","file_ext":"py","file_size_in_byte":6867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"272979621","text":"#!/usr/bin/python\n\nfrom __future__ import print_function # to enable the print function for backward compatiblity with python2\nimport json\n\ntry:\n\n # imports\n import os\n import urlparse\n import requests\n import hmac\n import hashlib\n import sys\n import time\n import threading\n import fcntl\n import datetime\n import Cookie\n import re\n import shutil\n\n # config file: this will lock the config file for the lifetime of this object\n class ConfigFile(object):\n def __init__(self, rw):\n self.rw=rw\n def __enter__(self):\n configFilename=\"/home/mbsim/BuildServiceConfig/mbsimBuildService.conf\"\n if self.rw:\n self.fd=open(configFilename, 'r+')\n fcntl.lockf(self.fd, fcntl.LOCK_EX)\n self.config=json.load(self.fd)\n else:\n fd=open(configFilename, 'r')\n fcntl.lockf(fd, fcntl.LOCK_SH)\n self.config=json.load(fd)\n fcntl.lockf(fd, fcntl.LOCK_UN)\n fd.close()\n return self.config\n def __exit__(self, exc_type, exc_value, traceback):\n if self.rw:\n self.fd.seek(0)\n json.dump(self.config, self.fd, indent=2)\n self.fd.truncate()\n fcntl.lockf(self.fd, fcntl.LOCK_UN)\n self.fd.close()\n\n def checkCredicals(config, sessionid=None):\n if sessionid==None and 'HTTP_COOKIE' in os.environ:\n cookie=os.environ[\"HTTP_COOKIE\"]\n c=Cookie.SimpleCookie(cookie)\n sessionid=c['mbsimenvsessionid'].value\n # check\n response_data={'success': False, 'message': 'Unknown'}\n if sessionid==None:\n response_data['success']=False\n response_data['message']=\"Not logged in.\"\n else:\n # check whether sessionid is known by the server (logged in)\n if sessionid not in config['session']:\n response_data['success']=False\n response_data['message']=\"Unknown session ID.\"\n else:\n # get access token for login\n access_token=config['session'][sessionid]['access_token']\n # check whether the sessionid is correct\n if not hmac.compare_digest(hmac.new(config['client_secret'].encode('utf-8'), access_token, hashlib.sha1).hexdigest(), sessionid):\n response_data['success']=False\n response_data['message']=\"Invalid access token hmac! Maybe the login was faked! If not, try to relogin again.\"\n else:\n # check whether this login is permitted to save data on the server (query github collaborators)\n headers={'Authorization': 'token '+access_token,\n 'Accept': 'application/vnd.github.v3+json'}\n login=config['session'][sessionid]['login']\n response=requests.get('https://api.github.com/teams/1451964/memberships/%s'%(login), headers=headers)\n if response.status_code!=200:\n response_data['success']=False\n response_data['message']=\"Not allowed, since you (\"+login+\") are not a member of the team Developers of the organization mbsim-env. Please login as a user with valid permissions.\"\n elif response.json()['state']!='active':\n response_data['success']=False\n response_data['message']=\"Not allowed, since your (\"+login+\") status in the team Developers of the organization mbsim-env is pending.\"\n else:\n response_data['success']=True\n return response_data\n\n if __name__ == \"__main__\":\n # get the script action = path info after the script url\n action=os.environ.get('PATH_INFO', None)\n method=os.environ.get('REQUEST_METHOD', None)\n \n # default response\n defaultOutput=True\n response_data={'success': False, 'message': \"Internal error: Unknown action or request method: \"+action}\n \n # login using github\n if action==\"/login\" and method==\"GET\":\n # get the github code passed provided by html get methode\n query=urlparse.parse_qs(os.environ['QUERY_STRING'])\n if 'error' in query:\n response_data['success']=False\n response_data['message']=\"Authorization request failed: \"+query['error']\n else:\n code=query['code']\n with ConfigFile(True) as config:\n # get access token from github (as a json response)\n data={'client_id': '987997eb60fc086e9707', 'client_secret': config['client_secret'], 'code': code}\n headers={'Accept': 'application/json'}\n response=requests.post('https://github.com/login/oauth/access_token', headers=headers, data=data).json()\n if 'error' in response:\n response_data['success']=False\n response_data['message']=\"Access token request failed: \"+response['error']\n else:\n access_token=response['access_token']\n # get github login name using github API request\n headers={'Authorization': 'token '+access_token,\n 'Accept': 'application/vnd.github.v3+json'}\n response=requests.get('https://api.github.com/user', headers=headers)\n if response.status_code!=200:\n response_data['success']=False\n response_data['message']=\"Internal error. Cannot get user information.\"\n else:\n response=response.json()\n login=response['login']\n # redirect to the example web side and pass login and access token hmac as http get methode\n sessionid=hmac.new(config['client_secret'].encode('utf-8'), access_token, hashlib.sha1).hexdigest()\n # save login and access token in a dictionary on the server\n config['session'][sessionid]={'access_token': access_token,\n 'login': login,\n 'avatar_url': response['avatar_url'],\n 'name': response['name']}\n # create cookie\n c=Cookie.SimpleCookie()\n # sessionid cookie not visible to javascript\n c['mbsimenvsessionid']=sessionid\n c['mbsimenvsessionid']['comment']=\"Session ID for www.mbsim-env.de\"\n c['mbsimenvsessionid']['domain']='www.mbsim-env.de'\n c['mbsimenvsessionid']['path']='/'\n c['mbsimenvsessionid']['secure']=True\n c['mbsimenvsessionid']['httponly']=True\n # javascript cookie just to show the the user is logged in\n c['mbsimenvsessionid_js']=\"logged_in\"\n c['mbsimenvsessionid_js']['comment']=\"User logged into for www.mbsim-env.de\"\n c['mbsimenvsessionid_js']['domain']='www.mbsim-env.de'\n c['mbsimenvsessionid_js']['path']='/'\n c['mbsimenvsessionid_js']['secure']=True\n defaultOutput=False\n print('Status: 301 Moved Permanently')\n print('Location: https://www.mbsim-env.de/mbsim/html/index.html')\n print(c)\n print()\n\n # logout\n if action==\"/logout\" and method==\"GET\":\n # get login\n if 'HTTP_COOKIE' in os.environ:\n c=Cookie.SimpleCookie(os.environ[\"HTTP_COOKIE\"])\n sessionid=c['mbsimenvsessionid'].value\n else:\n sessionid=None\n if sessionid==None:\n response_data['success']=True\n response_data['message']=\"Nobody to log out.\"\n else:\n with ConfigFile(True) as config:\n # remove sessionid from server config\n config['session'].pop(sessionid, None)\n # generate json response\n response_data['success']=True\n response_data['message']=\"Logged out from server.\"\n \n # return current checked examples\n if action==\"/getcheck\" and method==\"GET\":\n with ConfigFile(False) as config: pass\n # not json input via http post required\n # return the checkedExamples entries of the config as json response\n response_data['success']=True\n response_data['message']=\"To be updated examples loaded.\"\n response_data['checkedExamples']=config['checkedExamples']\n \n # save checked examples (if logged in)\n if action==\"/setcheck\" and method==\"POST\":\n with ConfigFile(True) as config:\n response_data=checkCredicals(config)\n data=json.load(sys.stdin)\n if response_data['success']:\n # save checked examples\n config['checkedExamples']=data['checkedExamples']\n # response\n response_data['success']=True\n response_data['message']=\"Successfully saved.\"\n\n # return current ci branches of all repos\n if action==\"/getcibranches\" and method==\"GET\":\n with ConfigFile(False) as config: pass\n repos=['fmatvec', 'hdf5serie', 'openmbv', 'mbsim']\n # use a authentificated request if logged in (to avoid rate limit problems on github)\n headers={'Accept': 'application/vnd.github.v3+json'}\n if 'HTTP_COOKIE' in os.environ:\n c=Cookie.SimpleCookie(os.environ[\"HTTP_COOKIE\"])\n sessionid=c['mbsimenvsessionid'].value\n if sessionid in config['session']:\n headers['Authorization']='token '+config['session'][sessionid]['access_token']\n # worker function to make github api requests in parallel\n def getBranch(repo, out):\n response=requests.get('https://api.github.com/repos/mbsim-env/'+repo+'/branches', headers=headers)\n if response.status_code==200:\n out.extend([b['name'] for b in response.json()])\n # start worker threads\n thread={}\n out={}\n for repo in repos:\n out[repo]=[]\n thread[repo]=threading.Thread(target=getBranch, args=(repo, out[repo]))\n thread[repo].start()\n # wait for all threads\n for repo in repos:\n thread[repo].join()\n # generate output\n curcibranch=config['curcibranch']\n response_data['success']=True\n response_data['message']=\"Continuous integration braches loaded.\"\n response_data['curcibranch']=curcibranch\n response_data['fmatvecbranch']=out['fmatvec']\n response_data['hdf5seriebranch']=out['hdf5serie']\n response_data['openmbvbranch']=out['openmbv']\n response_data['mbsimbranch']=out['mbsim']\n\n # return current checked examples\n if action==\"/addcibranch\" and method==\"POST\":\n with ConfigFile(True) as config:\n response_data=checkCredicals(config)\n data=json.load(sys.stdin)\n if response_data['success']:\n # save checked examples\n newcibranch=data['addcibranch']\n curcibranch=config['curcibranch']\n add=True\n for c in curcibranch:\n if c['fmatvec']==newcibranch['fmatvec'] and c['hdf5serie']==newcibranch['hdf5serie'] and \\\n c['openmbv']==newcibranch['openmbv'] and c['mbsim']==newcibranch['mbsim']:\n add=False\n break\n if add:\n curcibranch.append(newcibranch)\n # update tobuild\n tobuild=config['tobuild']\n toadd=newcibranch.copy()\n toadd['timestamp']=int(time.time())\n tobuild.append(toadd)\n # response\n response_data['message']='New CI branch combination saved.'\n\n # return current checked examples\n if action==\"/delcibranch\" and method==\"POST\":\n with ConfigFile(True) as config:\n response_data=checkCredicals(config)\n data=json.load(sys.stdin)\n if response_data['success']:\n # del ci branch\n delcibranch=data['delcibranch']\n newcurcibranch=[]\n for c in config['curcibranch']:\n # never delete master\n if c['fmatvec']=='master' and c['hdf5serie']=='master' and \\\n c['openmbv']=='master' and c['mbsim']=='master':\n newcurcibranch.append(c)\n else:\n # do not add the deleted one\n if c['fmatvec']==delcibranch['fmatvec'] and c['hdf5serie']==delcibranch['hdf5serie'] and \\\n c['openmbv']==delcibranch['openmbv'] and c['mbsim']==delcibranch['mbsim']:\n continue\n # add others\n newcurcibranch.append(c)\n config['curcibranch']=newcurcibranch\n response_data['message']='CI branch combination deleted.'\n\n # get user information\n if action==\"/getuser\" and method==\"GET\":\n if 'HTTP_COOKIE' in os.environ:\n c=Cookie.SimpleCookie(os.environ[\"HTTP_COOKIE\"])\n sessionid=c['mbsimenvsessionid'].value\n else:\n sessionid=None\n if sessionid==None:\n response_data['success']=True\n response_data['username']=None\n response_data['avatar_url']=''\n response_data['message']=\"No session ID cookie found on your browser.\"\n else:\n with ConfigFile(False) as config: pass\n if not sessionid in config['session']:\n response_data['success']=True\n response_data['username']=None\n response_data['avatar_url']=''\n response_data['message']=\"The username of the browser cookie is not known by the server. Please relogin.\"\n else:\n response_data['success']=True\n response_data['username']=config['session'][sessionid]['name']+\" (\"+config['session'][sessionid]['login']+\")\"\n response_data['avatar_url']=config['session'][sessionid]['avatar_url']\n response_data['message']=\"User information returned.\"\n\n # react on web hooks\n if action==\"/webhook\" and method==\"POST\":\n with ConfigFile(True) as config:\n rawdata=sys.stdin.read()\n sig=os.environ['HTTP_X_HUB_SIGNATURE'][5:]\n if not hmac.compare_digest(sig, hmac.new(config['webhook_secret'].encode('utf-8'), rawdata, hashlib.sha1).hexdigest()):\n response_data['success']=False\n response_data['message']=\"Invalid signature. Only github is allowed to send hooks.\"\n else:\n response_data['success']=True\n response_data['message']=\"not implemented yet\"\n data=json.loads(rawdata)\n # get current config\n curcibranch=config['curcibranch']\n tobuild=config['tobuild']\n # get repo and branch from this push\n repo=data['repository']['name']\n branch=data['ref'][11:]\n # update tobuild\n for c in curcibranch:\n if c[repo]==branch:\n toadd=c.copy()\n toadd['timestamp']=int(time.time())\n tobuild.append(toadd)\n # create response\n response_data['success']=True\n response_data['message']=\"OK\"\n\n # copy distribution to release and tag on github\n if action==\"/releasedistribution\" and method==\"POST\":\n with ConfigFile(False) as config: pass\n response_data=checkCredicals(config)\n data=json.load(sys.stdin)\n if response_data['success']:\n # generate tagname, platform and relArchiveName\n tagName=re.sub(\"mbsim-env-(.*)-shared-build-xxx\\..*\", \"release/\"+data['relStr']+\"-\\\\1\", data['distArchiveName'])\n platform=re.sub(\"mbsim-env-(.*)-shared-build-xxx\\..*\", \"\\\\1\", data['distArchiveName'])\n relArchiveName=re.sub(\"mbsim-env-.*-shared-build-xxx(\\..*)\", \"mbsim-env-release-\"+data['relStr']+\"-\"+platform+\"\\\\1\", data['distArchiveName'])\n # access token from config file and standard http header\n c=Cookie.SimpleCookie(os.environ[\"HTTP_COOKIE\"])\n sessionid=c['mbsimenvsessionid'].value\n access_token=config['session'][sessionid]['access_token']\n headers={'Authorization': 'token '+access_token,\n 'Accept': 'application/vnd.github.v3+json'}\n # the default response -> is changed/appended later\n response_data['success']=True\n response_data['message']=\"\"\n # the current time -> the create date of the tag object\n curtime=datetime.datetime.utcnow()\n # get user email\n response=requests.get('https://api.github.com/user/emails', headers=headers)\n if response.status_code!=200:\n response_data['success']=False\n response_data['message']=\"Internal error. Cannot get email address of user.\"\n else:\n response=response.json()\n # get primary email\n for item in response:\n if item['primary']:\n email=item['email']\n # create tag object, create git reference and create a github release for all repositories\n org=\"mbsim-env\"\n repos=['fmatvec', 'hdf5serie', 'openmbv', 'mbsim']\n # worker function to make github api requests in parallel\n def tagRefRelease(repo, out):\n # create the git tag object\n createTagData={\"tag\": tagName,\n \"message\": \"Release \"+data['relStr']+\" of MBSim-Env for \"+platform+\"\\n\"+\\\n \"\\n\"+\\\n \"The binary \"+platform+\" release can be downloaded from\\n\"+\\\n \"https://www.mbsim-env.de/mbsim/releases/\"+relArchiveName+\"\\n\"+\\\n \"Please note that this binary release includes a full build of MBSim-Env not only of this repository.\\n\"+\\\n \"Also look at https://www.mbsim-env.de/mbsim/releases for other platforms of this release version.\\n\",\n \"object\": data['commitid'][repo],\n \"type\": \"commit\",\n \"tagger\": {\n \"name\": config['session'][sessionid]['name'],\n \"email\": email,\n \"date\": curtime.strftime(\"%Y-%m-%dT%H:%M:%SZ\")\n }}\n response=requests.post('https://api.github.com/repos/'+org+'/'+repo+'/git/tags',\n headers=headers, data=json.dumps(createTagData))\n # check if the create was successfull\n if response.status_code!=201:\n # not successfull -> set out\n out['success']=False\n out['message']=\"Unable to create the git tag object for repo \"+repo+\". Please check the tag status of (at least) this repository manually; \"\n else:\n # git tag object created -> get the tag object id\n tagObjectID=response.json()['sha']\n # create the github ref\n createRefData={\"ref\": \"refs/tags/\"+tagName,\n \"sha\": tagObjectID}\n response=requests.post('https://api.github.com/repos/'+org+'/'+repo+'/git/refs',\n headers=headers, data=json.dumps(createRefData))\n # check if the create was successfull\n if response.status_code!=201:\n # not successfull -> set out\n out['success']=False\n out['message']=\"Unable to create the git reference for repo \"+repo+\". Please check the tag status of (at least) this repository manually; \"\n else:\n # git ref object created -> create GitHub release info\n createRelData={\"tag_name\": tagName,\n \"name\": \"Release \"+data['relStr']+\" of MBSim-Env for \"+platform,\n \"body\": \"The binary \"+platform+\" release can be downloaded from\\n\"+\\\n \"https://www.mbsim-env.de/mbsim/releases/\"+relArchiveName+\"\\n\"+\\\n \"Please note that this binary release includes a full build of MBSim-Env not only of this repository. \"+\\\n \"Also look at https://www.mbsim-env.de/mbsim/releases for other platforms of this release version.\",\n \"draft\": False,\n \"prerelease\": False}\n response=requests.post('https://api.github.com/repos/'+org+'/'+repo+'/releases',\n headers=headers, data=json.dumps(createRelData))\n # check if the update was successfull\n if response.status_code!=201:\n # not successfull -> set out\n out['success']=False\n out['message']=\"Unable to create the GitHub release info for repo \"+repo+\". \"+\\\n \"Please check the tag/release status of (at least) this repository manually; \"\n # start worker threads\n thread={}\n out={}\n for repo in repos:\n out[repo]={'success': True, 'message': ''}\n thread[repo]=threading.Thread(target=tagRefRelease, args=(repo, out[repo]))\n thread[repo].start()\n # wait for all threads\n for repo in repos:\n thread[repo].join()\n # combine output of all threads\n for repo in repos:\n if not out[repo]['success']:\n response_data['success']=False\n response_data['message']=response_data['message']+out[repo]['message']\n # set message if everything was done Successfully\n if response_data['success']==True:\n response_data['message']=\"Successfully released and tagged this distribution.\"\n # copy the distribution to the release dir\n srcFile=data['reportOutDir']+\"/distribute/\"+data['distArchiveName']\n dstFile=\"/var/www/html/mbsim/releases/\"+relArchiveName\n shutil.copyfile(srcFile, dstFile)\n \n # check if the session ID provided as POST is authorizised \n if action==\"/checkmbsimenvsessionid\" and method==\"POST\":\n with ConfigFile(False) as config: pass\n data=json.load(sys.stdin)\n if 'mbsimenvsessionid' in data:\n response_data=checkCredicals(config, data['mbsimenvsessionid'])\n\nexcept:\n if __name__ == \"__main__\":\n # reset all output and generate a json error message\n import traceback\n defaultOutput=True\n response_data={}\n response_data['success']=False\n response_data['message']=\"Internal error: Please report the following error to the maintainer:\\n\"+traceback.format_exc()\n else:\n raise\n \nif __name__ == \"__main__\":\n # generate response\n if defaultOutput:\n print('Content-Type: application/json')\n print('Access-Control-Allow-Credentials: true')\n print()\n print(json.dumps(response_data))\n","sub_path":"misc/BuildService/cgi-bin/mbsimBuildServiceServer.py","file_name":"mbsimBuildServiceServer.py","file_ext":"py","file_size_in_byte":22082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"13076049","text":"import os\nimport shutil\n\nsourcepath1= r'D:\\buildSupport\\UIM01.16.000_QA\\CommonCodeVOB\\UICCommonWeb\\src\\main\\webapp\\static'\nsourcepath2= r'D:\\buildSupport\\UIM01.16.000_QA\\AppealsCodeVOB\\Appeals\\src\\main\\webapp\\static'\nsourcepath3= r'D:\\buildSupport\\UIM01.16.000_QA\\BenefitsCodeVOB\\Benefits\\src\\main\\webapp\\static'\nsourcepath4= r'D:\\buildSupport\\UIM01.16.000_QA\\IWFCodeVOB\\src\\main\\webapp\\static'\nsourcepath5= r'D:\\buildSupport\\UIM01.16.000_QA\\TaxCodeVOB\\ESS\\src\\main\\webapp\\static'\nsourcepath6= r'D:\\buildSupport\\UIM01.16.000_QA\\BenefitsCodeVOB\\CSS\\src\\main\\webapp\\static'\nsourcepath7= r'D:\\buildSupport\\UIM01.16.000_QA\\TaxCodeVOB\\Tax\\src\\main\\webapp\\static'\n\n\ndestpath = r'D:\\UIMEnvEARs\\StaticContent_INTB\\static'\ndef CopyStaticContent(sourcepath):\n\tfor root, dirs, files in os.walk(sourcepath):\n\t#destination folder where we will be copying the files from source folder\n\t#root = 'D:\\\\buildSupport\\\\UIM01.14.100_QA\\\\CommonCodeVOB\\\\UICCommonWeb\\\\WebContent\\\\static'\t\n\t\tdest=destpath + root.replace(sourcepath, '')\n\t#dest = 'D:\\\\UIMEnvEARs\\\\StaticContetnt\\\\static'\n\t\n\t#create the destination directory if it doesn't exist\n\t\tif not os.path.isdir(dest):\n\t\t\tos.mkdir(dest)\n\t\t\tprint ('Directory create at: ' + dest)\n\t\n\t\tfor filename in files:\n\t\t\toldloc = root +'\\\\'+filename\n\t\t\tnewloc = dest +'\\\\'+filename\n\t\t\n\t\t\ttry:\n\t\t\t\tshutil.copy2(oldloc, newloc)\n\t\t\t\tprint('File '+filename+' copied')\n\t\t\texcept IOError:\n\t\t\t\tprint ('file \"' +filename+ '\" already exists')\n\t\t\t\t\t\nCopyStaticContent(sourcepath1);\nCopyStaticContent(sourcepath2);\nCopyStaticContent(sourcepath3);\nCopyStaticContent(sourcepath4);\nCopyStaticContent(sourcepath5);\nCopyStaticContent(sourcepath6);\nCopyStaticContent(sourcepath7);\n\t\t\t\t\n\n\t","sub_path":"static content/copyStaticContent_QATB.py","file_name":"copyStaticContent_QATB.py","file_ext":"py","file_size_in_byte":1690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"40234919","text":"#!python3.6\n\"\"\"Standings Tab clsses\"\"\"\n\nfrom PyQt5.QtWidgets import (QWidget, QLabel, QLineEdit, QSpacerItem,\n QTabWidget, QGridLayout, QSizePolicy)\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtGui import QFont\n\n\nclass GameStandings(QWidget):\n def __init__(self, event, game):\n super().__init__()\n self.event = event\n self.game = game\n self.lastGame = game == self.event.numGames - 1\n layout = QGridLayout(self)\n\n def _clear(self):\n layout = self.layout()\n while True:\n item = layout.takeAt(0)\n if item is None:\n break\n if item.widget() is not None:\n item.widget().setParent(None)\n\n def _setDataGenerator(self, teamid):\n def setData(lane):\n self.event.teamInfo.setLane(teamid, self.game, lane)\n return setData\n\n def showEvent(self, event):\n super().showEvent(event)\n self._clear()\n standings = self.event.teamStandings(self.game)\n if not standings:\n return\n layout = self.layout()\n font = QFont()\n font.setPointSize(14)\n for n in range(len(self.event.teamInfo.ids())):\n s = standings[n]\n label = QLabel(str(n+1))\n label.setFont(font)\n layout.addWidget(label, n, 0)\n for m in range(1, len(s)):\n label = QLabel(str(s[m]))\n label.setFont(font)\n layout.addWidget(label, n, m + 1)\n if not self.lastGame:\n lane = QLineEdit()\n lane.setFont(font)\n lane.setMaximumWidth(50)\n lane.editingFinished.connect(self._setDataGenerator(s[0]))\n layout.addWidget(lane, n, m + 2)\n spacer = QSpacerItem(200, 1, QSizePolicy.Expanding, QSizePolicy.Minimum)\n layout.addItem(spacer, 0, m + 3)\n spacer = QSpacerItem(1, 200, QSizePolicy.Minimum, QSizePolicy.Expanding)\n layout.addItem(spacer, n + 1, 0)\n\n\nclass TeamStandings(QTabWidget):\n def __init__(self, event_model):\n super().__init__()\n self.event_model = event_model\n event_model.modelReset.connect(self._createTabs)\n\n def _clear(self):\n for n in reversed(range(self.count())):\n widget = self.widget(n)\n self.removeWidget(n)\n widget.deleteLater()\n\n def _createTabs(self):\n self._clear()\n if self.event_model.isValid():\n for n in range(self.event_model.numGames):\n gameWidget = GameStandings(self.event_model, n)\n self.addTab(gameWidget, \"Game \" + str(n + 1))\n self._setCurrentIndex()\n\n def _setCurrentIndex(self):\n if self.event_model.isValid():\n gamesCompleted = self.event_model.gamesCompleted()\n if gamesCompleted is None:\n gamesCompleted = 1\n self.setCurrentIndex(gamesCompleted - 1)\n\n def showEvent(self, event):\n super().showEvent(event)\n self._setCurrentIndex()\n","sub_path":"gui/standings.py","file_name":"standings.py","file_ext":"py","file_size_in_byte":3063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"602294399","text":"import json\nimport boto3\nimport botocore\nimport cv2\nimport sys\n\ndef handler(event, context):\n s3 = boto3.resource('s3')\n bucket = 'iosprojfixed-deployments-mobilehub-1649974884'\n key = 'party-dresses.jpg'\n local_path = '/tmp/local_party-dresses.jpg'\n\n try:\n s3.meta.client.download_file(bucket, key, local_path)\n except botocore.exceptions.ClientError as e:\n if e.response['Error']['Code'] == \"404\":\n print(\"The object does not exist.\")\n else:\n raise\n\n # Create the haar cascade\n faceCascade = cv2.CascadeClassifier(\"haarcascade_frontalface_default.xml\")\n\n # Read the image\n image = cv2.imread(local_path)\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n # Detect faces in the image\n faces = faceCascade.detectMultiScale(\n gray,\n scaleFactor=1.1,\n minNeighbors=5,\n minSize=(30, 30),\n flags = cv2.CASCADE_SCALE_IMAGE\n )\n print (\"Found {0} faces!\".format(len(faces)))\n\n # Draw a rectangle around the faces\n for (x, y, w, h) in faces:\n cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)\n\n local_path2 = \"tmp/detected_image.jpg\"\n # save image\n status = cv2.imwrite(local_path2,image)\n \n print(\"Image written to file-system : \",status)\n\n\n\n try:\n s3.meta.client.upload_file(local_path2, bucket, 'hello.jpg')\n except botocore.exceptions.ClientError as e:\n print(\"error\");\n raise\n \n # s3 = boto3.resource(\"s3\")\n # s3.Bucket(\"iosprojfixed-deployments-mobilehub-1649974884\").download_file('party-dresses.jpg', '/tmp/party-dresses.jpg')\n\n responseCode = 200\n link = \"https://s3.amazonaws.com/iosprojfixed-deployments-mobilehub-1649974884/hello.jpg\" \n # image_result = open(path,'wb')\n # image_result.write(img)\n # image_result.close()\n \n # image_64_encode = base64.encodestring(path)\n response = {\n 'statusCode': responseCode,\n 'headers':{\n # \"x-custom-header\":\"custom header value\",\n \"content-type\":\"image/jpg\"\n },\n 'body':\"\",\n 'isBase64Encoded':True,\n 'link':link\n }\n\n return response","sub_path":"aws-lambda-python-opencv-master/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":2167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"2295185","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport argparse\nimport os\nimport sys\n\nimport mmguero\n\n###################################################################################################\nargs = None\ndebug = False\nscript_name = os.path.basename(__file__)\nscript_path = os.path.dirname(os.path.realpath(__file__))\norig_path = os.getcwd()\n\n###################################################################################################\n# main\ndef main():\n global args\n global debug\n\n parser = argparse.ArgumentParser(description=script_name, add_help=False, usage='{} '.format(script_name))\n parser.add_argument('-d', '--defaults', dest='accept_defaults', type=mmguero.str2bool, nargs='?', const=True, default=False, metavar='true|false', help=\"Accept defaults to prompts without user interaction\")\n parser.add_argument('-v', '--verbose', dest='debug', type=mmguero.str2bool, nargs='?', const=True, default=False, metavar='true|false', help=\"Verbose/debug output\")\n parser.add_argument('-i', '--input', dest='input', type=str, default=None, required=False, metavar='', help=\"Input\")\n try:\n parser.error = parser.exit\n args = parser.parse_args()\n except SystemExit:\n parser.print_help()\n exit(2)\n\n debug = args.debug\n if debug:\n eprint(os.path.join(script_path, script_name))\n eprint(\"Arguments: {}\".format(sys.argv[1:]))\n eprint(\"Arguments: {}\".format(args))\n else:\n sys.tracebacklimit = 0\n\n if args.input is not None:\n cmd_code, cmd_output = mmguero.RunProcess(args.input)\n print(f\"{cmd_code}: {cmd_output}\")\n\n###################################################################################################\nif __name__ == '__main__':\n main()\n","sub_path":"templates/Python Script.py","file_name":"Python Script.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"571212827","text":"# -*- coding: utf-8 -*-\nfrom tests.routes.base import BaseTestCase\nfrom mock import patch\nfrom app.models import Source\nfrom app import db, app\nfrom app.helpers.message import MESSAGE\n\nimport mock\nimport json\nimport time\n\nclass TestSourceBluePrint(BaseTestCase):\n \n def setUp(self):\n # create source\n source = Source.find_source_by_id(1)\n if source is None:\n source = Source(\n id=1,\n name=\"source1\",\n url=\"url1\"\n )\n db.session.add(source)\n db.session.commit()\n \n else:\n source.name = \"source1\"\n source.url = \"url1\"\n db.session.flush()\n db.session.commit()\n\n def tearDown(self):\n pass\n\n def clear_data_before_test(self):\n pass\n\n def test_validate_source(self):\n with self.client:\n Uid = 66\n params = {\n \"name\": \"1\",\n \"url\": \"\"\n }\n response = self.client.post(\n '/source/validate',\n data=json.dumps(params), \n content_type='application/json',\n headers={\n \"Uid\": \"{}\".format(Uid),\n \"Fcm-Token\": \"{}\".format(123),\n \"Payload\": \"{}\".format(123),\n })\n\n data = json.loads(response.data.decode()) \n self.assertTrue(data['status'] == 1)\n\n \"---> case 2:\"\n\n params = {\n \"name\": \"source1\",\n \"url\": \"url1\"\n }\n response = self.client.post(\n '/source/validate',\n data=json.dumps(params), \n content_type='application/json',\n headers={\n \"Uid\": \"{}\".format(Uid),\n \"Fcm-Token\": \"{}\".format(123),\n \"Payload\": \"{}\".format(123),\n })\n\n data = json.loads(response.data.decode()) \n self.assertTrue(data['status'] == 0)\n \nif __name__ == '__main__':\n unittest.main()","sub_path":"restapi/tests/routes/source.py","file_name":"source.py","file_ext":"py","file_size_in_byte":2432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"163646794","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom numpy import load\nfrom numpy import save\nimport random\n\n\n# Load the files and put them as dataframe\ndef plot_scatter(lista, names, title, xlabel, ylabel):\n '''Function that shows/saves a scatter plot\n Args: lista: data to plot, names: names of the particles, title: title of the plot, xlabel,ylabel: name of labels'''\n plt.title(title)\n contador = 1\n for i, j in zip(lista, names):\n plt.scatter(contador, i[i[4] == 1][3].values.max(), label=j)\n contador = contador + 1\n\n plt.xlabel(xlabel)\n plt.ylabel(ylabel)\n plt.legend(loc=\"upper right\")\n\n plt.savefig(\"images/plots/MaxInt.png\")\n plt.show()\n\n return None\n\ndef plot_histogram (lista, names, title, xlabel, ylabel, bins , limit, xlim, ylim, pixel):\n '''Function that shows/saves a histogram1\n Args: lista: data to plot, names: names of the particles, title: title of the plot, xlabel,ylabel: name of labels\n bins: number of bins, limit: amount of data to plot, pixel: whether activated pixels or not,\n xlim,ylim: limits in x and y axes'''\n\n for i, j in zip(lista, names):\n plt.hist(i.loc[i[4] == pixel][3][:limit], bins=bins, label=j)\n\n plt.title(title)\n plt.legend(loc=\"upper right\")\n plt.ylim(0, ylim)\n plt.xlim(0, xlim)\n plt.xlabel(xlabel)\n plt.ylabel(ylabel)\n title=title.replace(\" \", \"_\")\n title = title.replace(\":\", \"_\")\n plt.savefig(\"images/plots/\" + title + \".png\")\n plt.show()\n return None\n\ndef plot_histogram2(df, title, xlabel, ylabel,particle, bins , limit, xlim, ylim, pixel, xmin=0, ymin=0):\n '''Same as plot_histogram, but this is used to compare particles'''\n\n plt.hist(df.loc[df[4] == pixel][3][:limit], bins=bins, color='c', label=particle)\n plt.title(title)\n plt.legend(loc=\"upper right\")\n plt.ylim(ymin, ylim)\n plt.xlim(xmin, xlim)\n plt.xlabel(xlabel)\n plt.ylabel(ylabel)\n plt.grid(True)\n title = title.replace(\" \", \"_\")\n title = title.replace(\":\", \"_\")\n plt.savefig(\"images/plots/\" + title + \".png\")\n plt.show()\n return None\n\ndef plot(lista, names):\n '''Function used to plot and save plots'''\n\n for i in range(7):\n lista[i] = pd.DataFrame(data=lista[i])\n\n title = 'Maximum of intensity for activated pixels'\n xlabel = 'Particle'\n ylabel = 'Maximum of intensity'\n #plot_scatter(lista, names, title, xlabel, ylabel)\n\n title = 'Histogram: deactivated pixels in the range [0,0.01]'\n xlabel = 'Intensity'\n ylabel = 'Frequency'\n plot_histogram(lista, names, title, xlabel, ylabel, bins=1000, limit=3500000, xlim=0.01, ylim=200000, pixel=0)\n\n title = 'Histogram: activated pixels in the range [0,1]'\n plot_histogram(lista, names, title, xlabel, ylabel, bins=1000, limit=7500, xlim=1, ylim=140, pixel=1)\n\n df1 = lista[0]\n df2 = lista[1]\n df1 = df1.sample(frac=1).reset_index(\n drop=True) # barajo gamma para que no haya problema al coger una cierta cantidad de datos de gamma\n\n title = 'Histogram: Activated pixels (gamma)'\n plot_histogram2(df1, title, xlabel, ylabel,particle='gamma', bins=500 , limit=100818, xlim=1, ylim=4000, pixel=1)\n\n title = 'Histogram: Activated pixels (electron)'\n plot_histogram2(df2, title, xlabel, ylabel,particle='electron', bins=500 , limit=100818, xlim=1, ylim=4000, pixel=1)\n\n title = 'Histogram: Activated pixels (gamma)'\n plot_histogram2(df1, title, xlabel, ylabel, particle='gamma', bins=500 , limit=100818, xlim=1, ylim=15, pixel=1, xmin=0.4)\n\n title = 'Histogram: Activated pixels (electron)'\n plot_histogram2(df2, title, xlabel, ylabel, particle='electron', bins=500 , limit=100818, xlim=1, ylim=15, pixel=1, xmin=0.4)\n\n\n\n\n\n\n\n\n\n","sub_path":"Part_2_version_2/visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":3762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"244967081","text":"# !/usr/bin/env python\n\nfrom pyzbar.pyzbar import decode\nimport cv2\nimport numpy as np\n\nfrom itertools import tee\nimport binascii\nimport math\n\n\ndef pairwise(iterable):\n a, b = tee(iterable)\n next(b, None)\n return zip(a, b)\n\ndef nothing(kargs=[]):\n pass\n\nclass QrFinder():\n cap = None\n img = None\n\n def __init__(self):\n self.cap = None\n self.corrected = np.zeros((100, 100), np.uint8) # image with corrected perspective\n\n cv2.namedWindow('edge')\n cv2.createTrackbar('thrs1', 'edge', 2000, 5000, nothing)\n cv2.createTrackbar('thrs2', 'edge', 4000, 5000, nothing)\n\n self.center = [0, 0]\n self.size = [0, 0]\n\n def try_to_decode(self, candidate, source, target):\n epsilon = 0.01 * cv2.arcLength(candidate, True)\n approx = cv2.approxPolyDP(candidate, epsilon, True)\n\n while len(approx) > 4:\n epsilon *= 1.01\n approx = cv2.approxPolyDP(candidate, epsilon, True)\n\n center = sum(approx) / 4\n\n topleft = None\n topright = None\n bottomleft = None\n bottomright = None\n\n for i in approx:\n if i[0][0] < center[0][0] and i[0][1] < center[0][1]:\n topleft = i\n elif i[0][0] > center[0][0] and i[0][1] < center[0][1]:\n topright = i\n elif i[0][0] < center[0][0] and i[0][1] > center[0][1]:\n bottomleft = i\n elif i[0][0] > center[0][0] and i[0][1] > center[0][1]:\n bottomright = i\n\n self.center = center[0]\n self.size = [topright[0][0] - topleft[0][0], bottomright[0][1] - topright[0][1]]\n\n x, y, w, h = cv2.boundingRect(candidate)\n ddd = target[y: y + h, x: x + w]\n cv2.namedWindow('masked_image')\n cv2.imshow('masked_image', ddd)\n\n return decode(ddd)\n\n\n def find_code(self, img):\n h, w = img.shape[:2]\n\n gray=img\n thrs1 = cv2.getTrackbarPos('thrs1', 'edge')\n thrs2 = cv2.getTrackbarPos('thrs2', 'edge')\n edge = cv2.Canny(gray, thrs1, thrs2, apertureSize=5)\n vis = cv2.cvtColor(img.copy(), cv2.COLOR_GRAY2BGR)\n vis /= 2\n\n\n vis2 = np.zeros((h, w), np.uint8)\n vis2[edge != 0] = 255\n\n _, contours0, hierarchy = cv2.findContours(vis2.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n contours = [cv2.approxPolyDP(cnt, 3, True) for cnt in contours0]\n\n selected = []\n # [Next, Previous, First_Child, Parent]\n if np.all(hierarchy != None): # TEMP: Modified\n for c, h in zip(contours, hierarchy[0]):\n if h[0] == -1 and h[1] == -1:\n kid = h[2]\n if kid != -1:\n kidh = hierarchy[0][kid]\n if kidh[0] == -1 and kidh[1] == -1:\n selected.append(c)\n result = []\n for candidate in selected:\n\n try:\n result = self.try_to_decode(candidate, gray, vis)\n except Exception as e:\n print(e)\n if result != []:\n break\n\n cv2.imshow('contours', vis)\n\n ch = cv2.waitKey(5) & 0xFF\n if ch == 27:\n exit()\n\n return result\n\nif __name__ == '__main__':\n finder = QrFinder()\n","sub_path":"drone/simulation/vision/token_locator.py","file_name":"token_locator.py","file_ext":"py","file_size_in_byte":3300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"241283540","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef plot_sine_wave(**kwargs):\n \"\"\"\n plot sine wave\n y = a sin(2 pi f t + t_0) + b\n \"\"\"\n \n end_time = kwargs.get(\"end_time\", 1)\n sample_time = kwargs.get(\"sample_time\", 0.01)\n amp = kwargs.get(\"amp\", 1)\n freq = kwargs.get(\"freq\", 1)\n start_time = kwargs.get(\"start_time\", 0)\n bias = kwargs.get(\"bias\", 0)\n figsize = kwargs.get(\"figsize\", (12, 6))\n \n time = np.arange(start_time, end_time, sample_time)\n result = amp * np.sin(2* np.pi * freq * time + start_time) + bias\n \n plt.figure(figsize=(12, 6))\n plt.plot(time, result)\n plt.grid(True)\n plt.xlabel(\"time\")\n plt.ylabel(\"sin\")\n plt.title(str(amp) + \"*sin(2*pi)\" + str(freq) + \"*t+\" + str(start_time) + \")+\" + str(bias))\n plt.show()\n \nif __name__ == \"__main__\":\n plot_sine_wave()","sub_path":"ds_study/code/plot_sin_wave.py","file_name":"plot_sin_wave.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"630339001","text":"from django.db import models\nfrom markdown import markdown\nimport datetime\n\nclass Location(models.Model):\n title = models.CharField(max_length = 64)\n street = models.CharField(max_length = 64)\n city = models.CharField(max_length = 64)\n state = models.CharField(max_length = 2)\n zip = models.IntegerField(max_length = 5)\n\n def __unicode__(self):\n return self.title\n \n class Meta:\n ordering = ['title']\n\nclass UpcomingDate(models.Model):\n location = models.ForeignKey(Location)\n date = models.DateTimeField(default = datetime.datetime.now)\n \n def __unicode__(self):\n return \"%s at %s\" % (self.date, self.location.title)\n \n class Meta:\n ordering = ['date']\n get_latest_by = 'date'\n \nclass ClassType(models.Model):\n order = models.IntegerField(max_length = 3, unique = True, help_text = \"The place in which this Class Type will fall on the list of all Class Types, 1 is the highest.\")\n title = models.CharField(max_length = 128)\n description = models.TextField(help_text = \"Markdown Syntax is enabled.\")\n description_html = models.TextField(editable = False, blank = True)\n price = models.CharField(max_length = 10, blank = True)\n paypal = models.TextField(blank = True, help_text = \"Paste the HTML for the PayPal button here.\")\n \n def __unicode__(self):\n return self.title\n \n class Meta:\n ordering = ['order']\n \n def save(self):\n if self.description:\n self.description_html = markdown(self.description)\n \n super(ClassType, self).save()","sub_path":"classes/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"122477274","text":"import keras\nfrom utils import compressed_pickle, decompress_pickle, plotLearningCurve\nfrom ourGenerator import OurGenerator\nfrom keras.applications.resnet50 import ResNet50\nimport numpy as np\n\n\nmodel = keras.models.load_model('models/features_2epochs', compile = True)\n\nlabels = decompress_pickle('labels.pickle.pbz2')\npartition = decompress_pickle('partition.pickle.pbz2')\n\nresnet = ResNet50(include_top=False,\n weights=\"imagenet\",\n input_tensor=None,\n input_shape=(240, 320, 3),\n pooling=None\n )\n\ncorrect_count = 0\nincorrect_count = 0\n\nfor ID in partition['test']:\n x = np.array(decompress_pickle('input/' + ID + '.pickle.pbz2'))\n x = keras.applications.resnet.preprocess_input(x)\n x = resnet.predict(x)\n x = x.reshape(1, -1, 2048, 1)\n prediction = model.predict(x)[0]\n prediction = np.argmax(prediction)\n label = labels[ID]\n if label == prediction:\n correct_count += 1\n print('correct')\n print(ID)\n else:\n incorrect_count += 1\n print('incorrect')\n print(ID)\n print(label)\n print(prediction)\n\nprint('accuracy')\naccuracy = float(correct_count) / float(correct_count + incorrect_count)\nprint(accuracy)\n","sub_path":"test-prediction.py","file_name":"test-prediction.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"171193286","text":"# -*- coding: utf-8 -*-\nimport unittest\nfrom openprocurement.auctions.core.tests.base import snitch\nfrom openprocurement.auctions.geb.tests.base import (\n BaseWebTest\n)\nfrom openprocurement.auctions.geb.tests.states import (\n ProcedureMachine\n)\nfrom openprocurement.auctions.geb.tests.blanks.active_qualification import (\n auction_put_auction_document_audit,\n bid_get,\n bid_owner_uploads_the_auction_protocol,\n organizer_activate_award,\n organizer_rejection_award,\n organizer_uploads_the_auction_protocol,\n winner_activate_award,\n winner_rejection_award,\n module_auction_get_auction_auction,\n winner_upload_rejection_protocol\n)\nfrom openprocurement.auctions.geb.tests.fixtures.active_qualification import (\n AUCTION_WITH_AWARD_WITH_PROTOCOL\n)\n\n\nclass StatusActiveQualificationTest(BaseWebTest):\n docservice = True\n\n test_organizer_downloads_the_auction_protocol = snitch(organizer_uploads_the_auction_protocol)\n test_organizer_rejection_award = snitch(organizer_rejection_award)\n test_winner_rejection_award = snitch(winner_rejection_award)\n test_module_auction_get_auction_auction = snitch(module_auction_get_auction_auction)\n test_winner_upload_rejection_protocol = snitch(winner_upload_rejection_protocol)\n test_auction_put_auction_document_audit = snitch(auction_put_auction_document_audit)\n test_bid_owner_downloads_the_auction_protocol = snitch(bid_owner_uploads_the_auction_protocol)\n\n def setUp(self):\n super(StatusActiveQualificationTest, self).setUp()\n procedure = ProcedureMachine()\n procedure.set_db_connector(self.db)\n procedure.toggle('active.qualification')\n context = procedure.snapshot()\n\n award = context['awards'][0]\n bid = context['bids'][0]\n audit_document = context['documents'][0]\n auction = context['auction']\n entrypoints = {}\n pattern = '/auctions/{}/awards/{}/documents?acc_token={}'\n entrypoints['award_document_post'] = pattern.format(auction['data']['id'],\n award['data']['id'],\n auction['access']['token'])\n\n pattern = '/auctions/{}/awards/{}?acc_token={}'\n entrypoints['award_patch'] = pattern.format(auction['data']['id'],\n award['data']['id'],\n auction['access']['token'])\n\n pattern = '/auctions/{}/awards/{}'\n entrypoints['award_get'] = pattern.format(auction['data']['id'],\n award['data']['id'])\n\n pattern = '/auctions/{}'\n entrypoints['auction_get'] = pattern.format(auction['data']['id'])\n\n pattern = '/auctions/{}/documents/{}?acc_token={}'\n entrypoints['auction_audit_put'] = pattern.format(auction['data']['id'],\n audit_document['data']['id'],\n auction['access']['token'])\n self.ENTRYPOINTS = entrypoints\n self.auction = auction\n self.award = award\n self.bid = bid\n\n\nclass AwardWithProtocolTest(BaseWebTest):\n test_organizer_activate_award = snitch(organizer_activate_award)\n test_winner_activate_award = snitch(winner_activate_award)\n\n def setUp(self):\n super(AwardWithProtocolTest, self).setUp()\n procedure = ProcedureMachine()\n procedure.set_db_connector(self.db)\n procedure.toggle('active.qualification')\n context = procedure.snapshot(fixture=AUCTION_WITH_AWARD_WITH_PROTOCOL)\n\n award = context['awards'][0]\n bid = context['bids'][0]\n auction = context['auction']\n entrypoints = {}\n\n pattern = '/auctions/{}'\n entrypoints['auction_get'] = pattern.format(auction['data']['id'])\n\n pattern = '/auctions/{}/contracts'\n entrypoints['contracts_get'] = pattern.format(auction['data']['id'])\n\n pattern = '/auctions/{}/awards/{}'\n entrypoints['award_get'] = pattern.format(auction['data']['id'],\n award['data']['id'])\n\n pattern = '/auctions/{}/awards/{}?acc_token={}'\n entrypoints['award_patch'] = pattern.format(auction['data']['id'],\n award['data']['id'],\n auction['access']['token'])\n self.ENTRYPOINTS = entrypoints\n self.auction = auction\n self.award = award\n self.bid = bid\n\n\nclass StatusActiveQualificationBidsTest(BaseWebTest):\n docservice = True\n\n test_bid_get = snitch(bid_get)\n\n def setUp(self):\n super(StatusActiveQualificationBidsTest, self).setUp()\n procedure = ProcedureMachine()\n procedure.set_db_connector(self.db)\n procedure.toggle('active.qualification')\n context = procedure.snapshot()\n\n auction = context['auction']\n bid = context['bids'][0]\n entrypoints = {}\n pattern = '/auctions/{}/bids/{}'\n entrypoints['bid_get'] = pattern.format(auction['data']['id'],\n bid['data']['id'])\n self.ENTRYPOINTS = entrypoints\n self.auction = auction\n self.bid = bid\n\n\ndef suite():\n suite = unittest.TestSuite()\n suite.addTest(unittest.makeSuite(StatusActiveQualificationTest))\n suite.addTest(unittest.makeSuite(StatusActiveQualificationBidsTest))\n suite.addTest(unittest.makeSuite(AwardWithProtocolTest))\n return suite\n\n\nif __name__ == '__main__':\n unittest.main(defaultTest='suite')\n","sub_path":"openprocurement/auctions/geb/tests/cases/active_qualification.py","file_name":"active_qualification.py","file_ext":"py","file_size_in_byte":5713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"490675183","text":"#Imports ZeroMQ module\nimport zmq\nimport json\n\n\ncontext = zmq.Context()\nsocket = context.socket(zmq.PULL)\nsocket.connect(\"tcp://127.0.0.1:4321\")\n\nwhile True:\n\ttweet = json.loads(socket.recv_json())\n\tif \"user\" in tweet and \"text\" in tweet:\n\t\toutput_tweet = tweet[\"user\"]\n\t\toutput_tweet[\"the_tweet\"] = tweet[\"text\"]\n\t\tprint(json.dumps(tweet))\n","sub_path":"twitter_subscriber.py","file_name":"twitter_subscriber.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"432059357","text":"from flask import Flask, render_template, request\nfrom werkzeug import secure_filename\nimport zipfile\nimport os\nimport face_training, face_detection_and_matching\n\napp = Flask(__name__)\n@app.route('/')\ndef main_page():\n return render_template('upload.html')\n\t\n@app.route('/training_path', methods = ['GET', 'POST'])\ndef upload_training():\n if request.method == 'POST':\n #try :\n for class_dir in os.listdir(\"data/train\"):\n for i in os.listdir(os.path.join(\"data/train\",class_dir)):\n print (os.path.join(\"data/train\",class_dir,i))\n os.remove(os.path.join(\"data/train\",class_dir,i))\n f = request.files['file']\n f.save(secure_filename(f.filename))\n with zipfile.ZipFile(secure_filename(f.filename),\"r\") as zip_ref: zip_ref.extractall(\"data/train\")\n os.remove(secure_filename(f.filename))\n face_training.train(\"data/train\", model_save_path=\"trained_knn_model.clf\")\n return 'file uploaded successfully'\n #except: return 'Error ' \n\n@app.route('/testing_path', methods = ['GET', 'POST'])\ndef upload_testing():\n if request.method == 'POST':\n #try :\n for image_file in os.listdir(\"data/test\"):\n os.remove(os.path.join(\"data/test\", image_file))\n f = request.files['file']\n f.save(secure_filename(f.filename))\n with zipfile.ZipFile(secure_filename(f.filename),\"r\") as zip_ref: zip_ref.extractall(\"data/test\")\n os.remove(secure_filename(f.filename))\n face_detection_and_matching.main(\"data/test\")\n return 'file uploaded successfully'\n\n #except: return 'Error ' \n\t\t\nif __name__ == '__main__':\n app.run(debug = True)","sub_path":"servingstatic/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"640421975","text":"# coding: utf-8\nimport re\nimport os\nfrom setuptools import setup, find_packages\n\n\ndef fpath(name):\n return os.path.join(os.path.dirname(__file__), name)\n\n\ndef read(fname):\n return open(fpath(fname)).read()\n\n\nfile_text = read(fpath('chiki_jssdk.py'))\n\n\ndef grep(attrname):\n pattern = r\"{0}\\W*=\\W*'([^']+)'\".format(attrname)\n strval, = re.findall(pattern, file_text)\n return strval\n\n\ndef get_data_files(*dirs):\n results = []\n for src_dir in dirs:\n for root, dirs, files in os.walk(src_dir):\n results.append((root, map(lambda f: root + \"/\" + f, files)))\n return results\n\n\nsetup(\n name='chiki-jssdk',\n version='0.0.1',\n url='https://github.com/endsh/chiki-jssdk',\n author='Linshao',\n author_email='438985635@qq.com',\n description='chiki jssdk libs.',\n py_modules=['chiki_jssdk'],\n packages=find_packages(),\n include_package_data=True,\n zip_safe=False,\n platforms='any',\n install_requires=[\n 'Flask==0.10.1',\n 'requests==2.9.1',\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"327029186","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 5 22:33:37 2020\n\n@author: xingwenpeng\n\"\"\"\n\nimport csv\nimport pandas as pd\n\n\npath0 = \"/Users/xingwenpeng/Desktop/agg_doc_vecs.csv\"\nfh = open(path0, encoding='utf-8') # 要检测文章的路径\ndata = csv.reader(fh) # 打开文章\ni=0\nID=[1,2,3,4] #要删除的序号\ndoc=[]\nfor row in data:\n i=i+1\n if i not in ID:\n doc.append(row)#把不需要删除的文章加进去\n # print(i)\n \n \ndf = pd.DataFrame(doc)","sub_path":"deleteArticle.py","file_name":"deleteArticle.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"90502966","text":"from typing import Union\n\nimport tamr_client as tc\nfrom tamr_client.types import JsonDict\n\nProject = Union[tc.mastering.Project]\n\n\nclass NotFound(Exception):\n \"\"\"Raised when referencing (e.g. updating or deleting) a project\n that does not exist on the server.\"\"\"\n\n pass\n\n\ndef from_resource_id(session: tc.Session, instance: tc.Instance, id: str) -> Project:\n \"\"\"Get project by resource ID\n\n Fetches project from Tamr server\n\n Args:\n instance: Tamr instance containing this dataset\n id: Project ID\n\n Raises:\n NotFound: If no project could be found at the specified URL.\n Corresponds to a 404 HTTP error.\n requests.HTTPError: If any other HTTP error is encountered.\n \"\"\"\n url = tc.URL(instance=instance, path=f\"projects/{id}\")\n return _from_url(session, url)\n\n\ndef _from_url(session: tc.Session, url: tc.URL) -> Project:\n \"\"\"Get project by URL\n\n Fetches project from Tamr server\n\n Args:\n url: Project URL\n\n Raises:\n NotFound: If no project could be found at the specified URL.\n Corresponds to a 404 HTTP error.\n requests.HTTPError: If any other HTTP error is encountered.\n \"\"\"\n r = session.get(str(url))\n if r.status_code == 404:\n raise NotFound(str(url))\n data = tc.response.successful(r).json()\n return _from_json(url, data)\n\n\ndef _from_json(url: tc.URL, data: JsonDict) -> Project:\n \"\"\"Make project from JSON data (deserialize)\n\n Args:\n url: Project URL\n data: Project JSON data from Tamr server\n \"\"\"\n proj_type = data[\"type\"]\n if proj_type == \"DEDUP\":\n return tc.mastering.project._from_json(url, data)\n else:\n raise ValueError(f\"Unrecognized project type '{proj_type}' in {repr(data)}\")\n","sub_path":"tamr_client/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"487945301","text":"__author__ = 'Konstantin Glazyrin'\n\nimport re\n\nfrom PyQt4 import QtGui, QtCore\n\nfrom PyTango import DevState, DeviceAttribute\n\nimport taurus\nfrom taurus.core import TaurusAttribute, TaurusException\nfrom taurus.qt.qtgui.application import TaurusApplication\nfrom taurus.qt.qtgui.container.tauruswidget import TaurusWidget\nfrom sardana.taurus.qt.qtcore.tango.sardana.macroserver import QDoor, QMacroServer\n\nfrom app.ui.base_ui.ui_quickmotor import Ui_quickmotor\nfrom app.common import logger, common\n\nfrom app.pytango.manager import CustomAttributeManager, CustomAttribute\nfrom app.pytango import signals as motor_signals\n\n\n\nKEY_MOTORSOURCE = \"source\"\nKEY_MOTORSTATE, KEY_MOTORPOSITION = \"state\", \"position\"\n\nKEY_MOTORSTATECHANGE, KEY_MOTORPOSITIONCHANGE, KEY_DOORSTATECHANGE = \"MotorState\", \"MotorPosition\", \"DoorState\"\n\nKEY_POSITIONZERO, KEY_POSITIONINITIAL, KEY_POSITIONSELECTED = 0, 1, 2\n\nclass WidgetQuickMotor(QtGui.QWidget, Ui_quickmotor, logger.LocalLogger, common.Checker):\n # maximum number of selected points to keep in the buffer\n MAX_SELECTED = 5\n DISTANCE_FORMAT = '%0.04f'\n MOTOR_FORMAT = '%6.4f'\n\n # defualt polling parameters\n DEFAULTDOORPOLLING = 1000\n DEFAULTMOTORPOSPOLLING = 500\n DEFAULTMOTORSTATEPOLLING = 1000\n\n signsetposition = QtCore.pyqtSignal(float)\n signreportposition = QtCore.pyqtSignal(str, float)\n\n def __init__(self, parent=None, debug_level=None):\n QtGui.QWidget.__init__(self, parent=parent)\n Ui_quickmotor.setupUi(self, self)\n logger.LocalLogger.__init__(self, parent=parent, debug_level=debug_level)\n common.Checker.__init__(self)\n\n self.__init_variables()\n self.__init_ui()\n self.__init_events()\n\n def __init_variables(self):\n self.__motor = None\n self.__motorpos = None\n self.__motorstate = None\n\n # macro server\n self.macro_server = None\n\n self.__motor_name = \"\"\n self.__motor_device_path = \"\"\n self.__door = None\n self.__door_state = None\n\n # states saved for processing\n self.__last_door_state = DevState.ON\n self.__last_motor_state = DevState.ON\n self.__last_motor_position = None\n\n # buffer for storing positions\n self.__positions = [0.000, 0.000]\n\n self.__manager = CustomAttributeManager().getDefaultManager()\n\n # value kept for checking if motor is moving or not\n self.__oldposition = None\n\n self._lambdams = lambda o=\"\", d=KEY_MOTORSTATECHANGE: self.processAttributeChangeEvent(o, d)\n self._lambdamp = lambda o=\"\", d=KEY_MOTORPOSITIONCHANGE: self.processAttributeChangeEvent(o, d)\n self._lambdads = lambda o=\"\", d=KEY_DOORSTATECHANGE: self.processAttributeChangeEvent(o, d)\n\n def __init_ui(self):\n self.setupMotor()\n self.motor_label.hide()\n self.btn_center.setEnabled(False)\n\n self._rebuildPositionsSelector()\n\n def __init_events(self):\n self.signsetposition.connect(self.processPositionChange)\n\n @property\n def motor(self):\n return self.__motor\n\n @property\n def door(self):\n return self.__door\n\n @property\n def attrposition(self):\n return self.__motorpos\n\n @property\n def name(self):\n return self.__motor_name\n\n def setDoor(self, door=None):\n \"\"\"\n Function setting up the Sardana Door\n :param door:\n :return:\n \"\"\"\n if door is not None:\n if isinstance(door, str):\n wdgt, door = self, taurus.Device(door)\n door = QDoor(door.getFullName())\n if isinstance(door, QDoor):\n self._setup_door(door)\n\n def cleanupDoor(self):\n \"\"\"\n An internal function deleting information on the Sardana Door\n :return:\n \"\"\"\n\n\n if self.__door is not None:\n self.info(\"Cleaning door %s\" % self.__door.getFullName())\n self.__door = None\n\n # cleaning up door state polling\n if self.check(self.__door_state):\n self.__door_state.stopPolling()\n self.disconnect(self.__door_state, QtCore.SIGNAL(motor_signals.SIGNAL_STATE_CHANGE), self._lambdads)\n self.__door_state = None\n\n def _setup_door(self, door=None):\n \"\"\"\n An internal function setting up a doo object\n :param door: Qdoor()\n :return:\n \"\"\"\n if door is not None and isinstance(door, QDoor):\n self.cleanupDoor()\n self.__door = door\n\n try:\n self.__door_state = self.__manager.getAttribute(device_path=self.__door.getFullName(), attr=\"state\")\n self.__door_state.startPolling()\n\n self.connect(self.__door_state, QtCore.SIGNAL(motor_signals.SIGNAL_STATE_CHANGE), self._lambdads)\n except TaurusException:\n pass\n\n def processAttributeChangeEvent(self, *args):\n \"\"\"\n Performs an analysis of the values reported by Taurus\n :param args:\n :return:\n \"\"\"\n value, key = args\n\n if key == KEY_MOTORPOSITIONCHANGE:\n if self.__last_motor_position == None:\n self.addInitialPosition(value)\n\n self.__last_motor_position = value\n self.reportPosition(value)\n\n elif key == KEY_MOTORSTATECHANGE:\n self.__last_motor_state = value\n elif key == KEY_DOORSTATECHANGE:\n self.__last_door_state = value\n\n self.enableMotorControls()\n\n\n def setupMotor(self, name=None):\n \"\"\"\n Function setting up new motor\n :param name: str() - motor name as given through in the pool of a macro server\n :return:\n \"\"\"\n self.cleanupMotor()\n\n if self.__door is None or name is None or not isinstance(name, str):\n return\n\n # get macro server, motor\n self.macro_server = QMacroServer(self.__door.macro_server.getFullName())\n self.__motor = self.macro_server.getElementInfo(name)\n\n if self.check(self.__motor):\n try:\n motor_source = str(self.__motor.read_attribute(\"TangoDevice\").value)\n except KeyError:\n return\n\n parent_model = motor_source.lower().replace(\"/%s\" % KEY_MOTORPOSITION, \"\")\n self._setMotorModel(name=name, model=parent_model)\n\n def cleanupMotor(self):\n \"\"\"\n Function resets internal parameters\n :return:\n \"\"\"\n\n if self.check(self.__motor):\n self.info(\"Cleaning motor %s\" % self.motor_name.text())\n\n if self.__motorpos is not None and isinstance(self.__motorpos, CustomAttribute):\n self.__motorpos.stopPolling()\n\n self.disconnect(self.__motorpos, QtCore.SIGNAL(motor_signals.SIGNAL_STATE_CHANGE), self._lambdams)\n self.disconnect(self.__motorpos, QtCore.SIGNAL(motor_signals.SIGNAL_VALUE_CHANGE), self._lambdamp)\n\n self.__motor_name = None\n\n self.__motor = None\n\n self._setMotorModel()\n\n def _setMotor(self, model):\n \"\"\"\n Function establishing motor event listening and motor models\n :param model: str() - motor device Tango reference\n :param position: str() - motor device attribute reference\n :return:\n \"\"\"\n # redesign - listen to the real motor, not the Sardana Motor\n device_path = self.__motor.read_attribute('TangoDevice').value\n\n # start polling\n self.__motorpos = self.__manager.getAttribute(device_path=device_path, attr=\"position\", polltime=500)\n self.__motorpos.startPolling()\n\n self.__motorstate = self.__manager.getAttribute(device_path=device_path, attr=\"state\", polltime=500)\n self.__motorstate.startPolling()\n\n # subscribe for events\n self.connect(self.__motorpos, QtCore.SIGNAL(motor_signals.SIGNAL_STATE_CHANGE), self._lambdams)\n self.connect(self.__motorpos, QtCore.SIGNAL(motor_signals.SIGNAL_VALUE_CHANGE), self._lambdamp)\n\n\n def setMotorFormat(self, strformat):\n \"\"\"\n Set Motor format for device\n :param strformat: str() - like '%6.4'\n :return:\n \"\"\"\n berror = True\n if self.check(strformat, str) or self.check(strformat, unicode):\n # test for correct format\n try:\n value = strformat % 10\n berror = False\n except ValueError:\n pass\n\n if not berror:\n self.MOTOR_FORMAT = strformat\n\n if self.check(self.__motorpos):\n try:\n self.__motorpos.getConfig().setFormat(self.MOTOR_FORMAT)\n except AttributeError:\n pass\n\n if berror:\n self.error('Wrong format for Motor representation (%s)' % str(strformat))\n\n def _setMotorModel(self, name=\"\", model=\"\"):\n \"\"\"\n Function setting motor widget models and motor model\n :param name: name of the motor\n :param model: str() - Tango reference\n :return:\n \"\"\"\n motor_state, motor_position = \"%s/%s\" % (model, KEY_MOTORSTATE), \"%s/%s\" % (model, KEY_MOTORPOSITION)\n\n self.motor_state.setModel(motor_state)\n self.motor_edit.setModel(motor_position)\n self.motor_label.setModel(motor_position)\n\n self.motor_name.setText(name)\n\n if len(model) > 0:\n # if we have change motor name - clear selection\n if self.__motor_name != name:\n pass\n\n self.__motor_name = name\n\n self._setMotor(model)\n self.stacked_motor.setCurrentWidget(self.page_motor)\n else:\n self.stacked_motor.setCurrentWidget(self.page_nomotor)\n\n def forcePosition(self):\n \"\"\"\n Moves motor to a selected position\n :return:\n \"\"\"\n if self.__motorpos is not None:\n position = self.__positions[self.cmb_position.currentIndex()]\n self.info(\"Moving to position \"+self.DISTANCE_FORMAT % position)\n\n # report value\n if self.check(self.__motorpos):\n self.__motorpos.setValue(position)\n\n self._resetCalculated()\n\n def addInitialPosition(self, value=None):\n \"\"\"\n Function adding position as an initial\n :param value: float() - value to added\n :return:\n \"\"\"\n if value is not None and isinstance(value, float):\n self.__positions[KEY_POSITIONINITIAL] = value\n\n self._rebuildPositionsSelector()\n\n def addSelectedPosition(self, value=None):\n \"\"\"\n Function adds a new position marked as a selected\n :param value: float() - value to added\n :return:\n \"\"\"\n if value is not None and isinstance(value, float):\n length = len(self.__positions)\n\n # check size of buffer - wee need +2 (Zero + Initial)\n if len(self.__positions) > self.MAX_SELECTED+1:\n self.__positions.pop(KEY_POSITIONSELECTED)\n\n distance = float(value - self.__positions[-1])\n self.pos_distance.setText(self.DISTANCE_FORMAT % distance)\n\n center = float(value + self.__positions[-1])/2.\n self.pos_center.setText(self.DISTANCE_FORMAT % center)\n\n self.__positions.append(value)\n\n self._rebuildPositionsSelector()\n self.btn_center.setEnabled(True)\n\n def _rebuildPositionsSelector(self):\n \"\"\"\n Rebuilding combo box containing selected positions\n :return:\n \"\"\"\n strlist = QtCore.QStringList()\n for (i, pos) in enumerate(self.__positions):\n format = \"\"+self.DISTANCE_FORMAT\n\n if i == KEY_POSITIONINITIAL:\n format = self.DISTANCE_FORMAT + \" - Start\"\n elif i == KEY_POSITIONZERO:\n format = self.DISTANCE_FORMAT + \" - Zero \"\n string = format % pos\n\n strlist.append(string)\n\n self.cmb_position.clear()\n self.cmb_position.addItems(strlist)\n self.cmb_position.setCurrentIndex(self.cmb_position.count()-1)\n\n def processPositionChange(self, value=None):\n \"\"\"\n Sets a selected value to a position\n :param value:\n :return:\n \"\"\"\n if value is not None:\n if isinstance(value, str):\n value = float(value)\n\n self.motor_edit.setValue(value)\n self.__oldposition = value\n\n def reportPosition(self, value=None):\n \"\"\"\n Sets a selected value to a position\n :param value:\n :return:\n \"\"\"\n if self.check(value, float):\n self.emit(QtCore.SIGNAL(motor_signals.SIGNAL_VALUE_CHANGE), value)\n self.signsetposition.emit(value)\n dir(self.__motor.name)\n self.signreportposition.emit(self.__motor.name, value)\n\n def registerPositionChange(self, func):\n \"\"\"\n Register an external fucntion which should be executed upon a change of a motor\n :param func:\n :return:\n \"\"\"\n self.signreportposition.connect(func)\n\n def enableMotorControls(self):\n \"\"\"\n Disables or enables motor control\n :param bflag:\n :return:\n \"\"\"\n\n benabled = False\n\n if self.__last_door_state == DevState.ON or self.__last_door_state == DevState.ALARM:\n if self.__last_motor_state == DevState.ON or self.__last_door_state == DevState.ALARM:\n benabled = True\n\n for wdgt in (self.motor_edit, self.btn_position, self.btn_center, self.cmb_position):\n try:\n wdgt.setEnabled(benabled)\n except RuntimeError as e:\n self.error(str(wdgt))\n\n def isMotorInitializied(self):\n \"\"\"\n Returns information on motor initialization state\n :return:\n \"\"\"\n res = False\n if self.__motor is not None:\n res = True\n return res\n\n def forceCenter(self):\n \"\"\"\n Move to the center position relative to the last selected point\n :return:\n \"\"\"\n if self.__motorpos is not None:\n try:\n position = float(self.pos_center.text())\n except ValueError:\n return\n\n self.info(\"Moving to position \"+self.DISTANCE_FORMAT % position)\n\n self.__motorpos.setValue(position)\n\n self._resetCalculated()\n\n def _resetCalculated(self):\n \"\"\"\n Resets a calculated value for center position (between two last selected points)\n :return:\n \"\"\"\n for w in (self.pos_distance, self.pos_center):\n w.setText(\"\")\n\n self.btn_center.setEnabled(False)\n\n def closeEvent(self, event):\n self.info(\"quick motor closing ----------------------------------\")","sub_path":"ScanTracker/app/ui/gui_widget_quickmotor.py","file_name":"gui_widget_quickmotor.py","file_ext":"py","file_size_in_byte":14834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"328010720","text":"#Exercício Python 064: Crie um programa que leia vários números inteiros pelo teclado.\r\n# O programa só vai parar quando o usuário digitar o valor 999, que é a condição de parada.\r\n# No final, mostre quantos números foram digitados e qual foi a soma entre eles (desconsiderando o flag).\r\n\r\ni = 0\r\nsoma = 0\r\ncontador = 0\r\nwhile i!= 999:\r\n i = int(input(f'Insira o {contador+1}º número: '))\r\n if i!=999:\r\n contador += 1\r\n soma += i\r\n else:\r\n print(f'Foram digitados {contador} números')\r\n print(f'A soma entre eles resultou em {soma}')","sub_path":"10.8 - Exercicio 8.py","file_name":"10.8 - Exercicio 8.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"340282889","text":"from users import models\nimport datetime\n\ndef findAppByRP(userID):\n receptor=models.Adminreceptor.objects.get(id_adminreceptor=userID)\n hospitalID=receptor.id_hospital\n today=datetime.date.today()\n tomorrow = today + datetime.timedelta(days=1)\n departmentList=list(models.Department.objects.filter(id_hospital=hospitalID))\n appDicList=[]\n for i in departmentList:\n docDepList=list(models.DoctorDepartment.objects.filter(id_department=i.id_department))\n for j in docDepList:\n bulletinList=list(models.Bulletin.objects.filter(id_doctor_department=j.id_doctor_department).filter(availabletime__range=(today,tomorrow)))\n for k in bulletinList:\n appointmentList=list(models.Appointment.objects.filter(id_bulletin=k.id_bulletin))\n for l in appointmentList:\n if l is not None:\n regiistrationtime=l.registrationtime\n if regiistrationtime is not None:\n appDic = {'anAppointment': l, 'patient': l.id_patient, 'doctor': j.id_doctor,\n 'department': i, 'time': k.availabletime, 'fee': k.fee, 'isShow': True}\n appDicList.append(appDic)\n else:\n appDic = {'anAppointment': l, 'patient': l.id_patient, 'doctor': j.id_doctor,\n 'department': i, 'time': k.availabletime, 'fee': k.fee, 'isShow': False}\n appDicList.append(appDic)\n\n return appDicList;\n\ndef findAppByUser(name):\n patientList=list(models.Patient.objects.filter(name=name))\n appDicList=[]\n for i in patientList:\n appointmentsList=list(models.Appointment.objects.filter(id_patient=i.id_patient).filter(registrationtime__isnull=True))\n for j in appointmentsList :\n appDic={'anAppointment':j,'patient':j.id_patient,'bulletin':j.id_bulletin}\n appDicList.append(appDic)\n return appDicList;\n\ndef addUser(form):\n data = form.cleaned_data\n hospitalID=models.Hospital.objects.get(name=data['hospital'])\n receptor = models.Adminreceptor.objects.create(loginname=data['username'], password=data['password'],\n createtime=datetime.datetime.now(), id_hospital=hospitalID)\n\n receptor.save()\n\n\n\n","sub_path":"receptor/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"372012376","text":"def display(dic):\n\tprint(\"\\n/*** COMMANDS ***/\")\n\tkeys = sorted(dic.keys())\n\tfor k in keys:\n\t\tprint(k, \"<-->\", dic[k])\n\tprint()\n\ndef addCommand(dic, path):\n\tcmd = input(\"insert new command ('e' to exit): \")\n\tif cmd == \"e\":\n\t\treturn\n\tdesc = input(\"insert description: \")\n\tdic[cmd] = desc\n\tf = open(path + \"commands.txt\", \"a\")\n\tf.write(cmd + \"$$$\" + desc + \"\\n\")\n\tf.close()\n\ndef removeCommand(dic, path):\n\tcmd = input(\"command to delete ('e' to exit): \")\n\tif cmd == \"e\":\n\t\treturn\n\tyn = input(\"Are you sure you want to delete it permanently? (y/n): \")\n\tif yn != \"n\":\n\t\tif cmd in dic:\n\t\t\tdel dic[cmd]\n\t\t\tf_supp = open(path + \"tmp.txt\", \"w\")\t\t\t\n\t\t\tf = open(path + \"commands.txt\", \"r\")\n\t\t\tfor line in f:\n\t\t\t\tif line.split(\"$$$\")[0] != cmd:\n\t\t\t\t\tf_supp.write(line)\n\t\t\tf.close()\n\t\t\tf_supp.close()\n\t\t\tf_supp = open(path + \"tmp.txt\", \"r\")\n\t\t\tf = open(path + \"commands.txt\", \"w\")\n\t\t\tfor line in f_supp:\n\t\t\t\tf.write(line)\n\t\t\tf_supp.close()\n\t\t\tf.close()\n\t\t\tprint(\"Command successfully removed!\")\n\npath = \"/usr/bash-reminder/\"\n\t\nf_in = open(path + \"commands.txt\", \"r\")\ndic = {}\n\nfor line in f_in:\n\tl = line.strip().split(\"$$$\")\n\tcommand = l[0]\n\tdescription = l[1]\n\tdic[command] = description\n\nf_in.close()\n\n#commands.txt loaded\nisRunning = True\nwhile isRunning:\n\ti = input(\"Usage:\\n~ 'a' to add a new command\\n~ 'r' to remove a command\\n~ 'd' for display\\n~ 'q' to quit\\n\")\n\tif i == \"q\":\n\t\tisRunning = False\n\t\tbreak\n\telif i == \"r\":\n\t\tremoveCommand(dic, path)\n\telif i == \"d\":\n\t\tdisplay(dic)\n\telif i == \"a\":\n\t\taddCommand(dic, path)\n","sub_path":"bash-reminder.py","file_name":"bash-reminder.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"520149524","text":"import os\nimport zipfile\nfrom utils import run, dpath, rm, symlink_in_tempdir\nfrom test_bowtie2 import bowtie2_indexes\n\ndef test_fastq_screen(sample1_se_tiny_fq, bowtie2_indexes, tmpdir):\n snakefile = '''\n rule fastq_screen:\n input:\n fastq='sample1_R1.fastq.gz',\n dm6={indexes}\n output:\n txt='sample1_R1_screen.txt'\n params:\n subset=100000,\n aligner='bowtie2'\n wrapper:\n \"file:wrapper\"\n '''.format(indexes=bowtie2_indexes)\n\n input_data_func=symlink_in_tempdir(\n {\n sample1_se_tiny_fq: 'sample1_R1.fastq.gz'\n }\n )\n\n def check():\n with open('sample1_R1_screen.txt') as fh:\n res = fh.readlines()\n r1 = res[0].strip().split()\n r3 = res[2].strip().split()\n assert r1[-1] == '100000'\n assert r3[0] == 'dm6'\n\n\n run(dpath('../wrappers/fastq_screen'), snakefile, check, input_data_func, tmpdir)\n","sub_path":"wrappers/test/test_fastq_screen.py","file_name":"test_fastq_screen.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"494896452","text":"import torch\n\n\nclass GAN_generator (torch.nn.Module):\n\n def __init__(self, H):\n #for gan\n # H=[384,16384, 256, 128, 64, 1]\n #for cgan\n # H=[576,16384, 256, 128, 64, 1]\n super(GAN_generator, self).__init__()\n\n self.dense0 = torch.nn.Linear(H[0],H[1])\n #Relu\n self.batchNorm0 = torch.nn.BatchNorm2d(H[2])\n\n self.upsample1 = torch.nn.ConvTranspose2d(H[2],H[2],2, stride=2)\n self.convolution1 = torch.nn.Conv2d(H[2],H[2],3, stride=1, padding=1)\n # Relu\n self.batchNorm1 = torch.nn.BatchNorm2d(H[2])\n\n self.upsample2 = torch.nn.ConvTranspose2d(H[2],H[2],2,stride=2)\n self.convolution2 = torch.nn.Conv2d(H[2],H[3],3,stride=1,padding=1)\n # Relu\n self.batchNorm2 = torch.nn.BatchNorm2d(H[3])\n\n self.upsample3 = torch.nn.ConvTranspose2d(H[3], H[3],2,stride=2)\n self.convolution3 = torch.nn.Conv2d(H[3], H[4],3,stride=1,padding=1)\n # Relu\n self.batchNorm3 = torch.nn.BatchNorm2d(H[4])\n\n self.convolution4 = torch.nn.Conv2d(H[4],H[5],3,stride=1,padding=1)\n self.tanh4 = torch.nn.Tanh()\n\n def forward(self,x, modis):\n if modis is None:\n h_conc0 = x.view(len(x),-1)\n else:\n h_conc0 = torch.cat([x.reshape(len(x),-1),modis.reshape(len(modis),-1)],dim=1)\n h_relu0 = self.dense0(h_conc0).clamp(min=0)\n h_relu0 = h_relu0.view(len(x),256,8, 8)\n h_norm0 = self.batchNorm0(h_relu0)\n h_upsample1 = self.upsample1(h_norm0)\n h_relu1 = self.convolution1(h_upsample1).clamp(min=0)\n h_norm1 = self.batchNorm1(h_relu1)\n h_upsample2 = self.upsample2(h_norm1)\n h_relu2 = self.convolution2(h_upsample2).clamp(min=0)\n h_norm2 = self.batchNorm2(h_relu2)\n h_upsample3 = self.upsample3(h_norm2)\n h_relu3 = self.convolution3(h_upsample3).clamp(min=0)\n h_norm3 = self.batchNorm3(h_relu3)\n h_convolution4 = self.convolution4(h_norm3)\n out = self.tanh4(h_convolution4)\n return out","sub_path":"GAN_generator.py","file_name":"GAN_generator.py","file_ext":"py","file_size_in_byte":2043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"361085458","text":"import numpy as np\r\nimport math\r\nimport time\r\n\r\n#needed for MPI treatment ------------\r\nfrom mpi4py import MPI\r\ncomm = MPI.COMM_WORLD # to comunicate between nodes\r\nrank= comm.Get_rank() # rank of one process\r\nsize= comm.Get_size() # number of proccess\r\n# ------------------------------------\r\nif(rank==0): #True si rank est 0, pas la peine de faire l'initialisation sur plusieurs noeuds\r\n start = time.time()\r\n \r\ndef printTable(A):\r\n for row in A:\r\n print(row)\r\n\r\n# NxN matrix\r\nN = 60\r\n\r\ndef getRowsStartEnd(node_number):\r\n row_start=int(node_number*N/size)#first ligne index\r\n row_end=int((node_number+1)*N/size)#last ligne index +1\r\n return(row_start,row_end)\r\n\r\nif(rank==0):\r\n # Matrix for calculation input and output\r\n A = np.zeros((N-2, N-2))\r\n A = np.pad(A, pad_width=1, mode='constant', constant_values=1)\r\n printTable(A)\r\nelse:\r\n A=None #Initialisation in order to broadcast\r\nA=comm.bcast(A,root=0)\r\n# Sub_Matrix for calculation output temp\r\n(row_start,row_end)=getRowsStartEnd(rank)\r\nB = np.zeros((row_end-row_start,N))\r\nconverge = False\r\niteration_num = 0\r\n\r\nwhile (converge==False):\r\n if(rank==0):\r\n iteration_num = iteration_num+1#seul le noeud 0 va compter les iterations\r\n diffnorm = 0.0\r\n # for convenience, use padding border\r\n A_padding = np.pad(A, pad_width=1, mode='constant', constant_values=0)#on ajoute des 0 tout autour#2 lors de la prod\r\n\r\n # partie a decouper -------------------------------------------------------------------------------\r\n for n in range (size):\r\n if(rank==n):\r\n (row_start,row_end)=getRowsStartEnd(rank)\r\n sub_copy_A_padding = A_padding[row_start:row_end+2]\r\n for i in range(0,row_end-row_start):# pour que ca corresponde au index de sub_copy_A_padding\r\n for j in range(N):\r\n # because we do padding, index changed\r\n #print(\"rang : \"+str(rank)+\" | i : \"+str(i)+\" | j : \"+str(j))\r\n i_padd=i+1\r\n j_padd=j+1\r\n B[i][j] = 0.25*(sub_copy_A_padding[i_padd+1, j_padd]\r\n + sub_copy_A_padding[i_padd-1, j_padd]\r\n + sub_copy_A_padding[i_padd, j_padd+1]\r\n + sub_copy_A_padding[i_padd, j_padd-1])\r\n diffnorm += math.sqrt((B[i, j] - A[i+row_start, j])*(B[i, j] - A[i+row_start, j]))\r\n comm.barrier()#on doit attendre tout les traitement avant de copier B dans A\r\n \r\n if(rank!=0):\r\n comm.send(B,0)\r\n comm.send(diffnorm,0)\r\n else:\r\n A[row_start:row_end]=B\r\n for node in range (1,size):\r\n (row_start,row_end)=getRowsStartEnd(node)\r\n A[row_start:row_end]=comm.recv(source=node)\r\n diffnorm=diffnorm+comm.recv(source=node)\r\n # check converge\r\n if diffnorm <= 0.01:\r\n converge = True\r\n else:\r\n converge = False\r\n \r\n \r\n \r\n if iteration_num % 100 == 0:\r\n print(\"*************\")\r\n printTable(A)\r\n print(\"*************\")\r\n \r\n A=comm.bcast(A,0)\r\n converge=comm.bcast(converge,0)\r\n comm.barrier()#on attends la nouvelle valeur de converge pour etre sur de ne pas faire un tour de boucle inutile\r\n\r\nif (rank==0):\r\n print(\"*************\")\r\n printTable(A)\r\n print(\"*************\")\r\n print('Converge, iteration : %d' % iteration_num)\r\n print('Error : %f' % diffnorm)\r\n end = time.time()\r\n print('execution time : ')\r\n print(end - start)\r\n ","sub_path":"Matrix_Convolution.py","file_name":"Matrix_Convolution.py","file_ext":"py","file_size_in_byte":3336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"523666314","text":"from django.db.models import Sum, Avg, Max, Min, Count\n\ndef order_rank_json(kpp_queryset, model, items):\n data = {\n 'cols':[\n {'id': 'A', 'label': '파레트코드+이산수량', 'type' : 'string'},\n {'id':'B', 'label':'횟수', 'type' :'number'},\n ],\n 'rows':[]\n }\n\n if model=='code':\n # 한 기업의 거래 내역에 대해서, 가장 많이 등장하는 파레트유형 순으로 파레트 유형 정렬\n #palletcode_top_three = items.annotate(pallet_count = Count(kpp_queryset)).order_by('-pallet_count')[:3]\n # 결과값이 담겨질 리스트\n answerset = []\n for pc in items:\n filtered = kpp_queryset.filter(palletcode=pc)\n palletset_ordered = list(set(datarow.pallet for datarow in filtered))\n palletset_ordered.sort(reverse=True)\n\n\n for p in palletset_ordered:\n howmany = filtered.filter(pallet=p).count()\n answerset.append([howmany, pc.palletcode, p])\n\n answerset.sort(reverse=True)\n # answerset 에서는 [횟수 , 파레트유형, 주문수량] 순으로 들어가 있다.\n for a in answerset:\n rowname = str(a[1]) + '를 ' + str(a[2]) + '개씩'\n cell = {'c': [\n {'v': rowname, 'f': rowname},\n {'v': a[0], 'f': str(a[0])}\n ]}\n data['rows'].append(cell)\n\n else : #model=='palletcode'\n answerset = []\n codes = list(set(kpp.code for kpp in kpp_queryset))\n for c in codes:\n filtered = kpp_queryset.filter(code=c)\n palletset_ordered = list(set(datarow.pallet for datarow in filtered))\n palletset_ordered.sort(reverse=True)\n\n\n for p in palletset_ordered:\n howmany = filtered.filter(pallet=p).count()\n answerset.append([howmany, c.code, p])\n\n answerset.sort(reverse=True)\n # answerset 에서는 [횟수 , 기업코드, 주문수량] 순으로 들어가 있다.\n for a in answerset:\n rowname = str(a[1]) + '기업서 ' + str(a[2]) + '개씩'\n cell = {'c': [\n {'v': rowname, 'f': rowname},\n {'v': a[0], 'f': str(a[0])}\n ]}\n data['rows'].append(cell)\n\n\n return data\n\ndef order_analysis_json(kpp_queryset,model):\n\n data = {\n 'cols':[\n {'id': 'A', 'label': 'date', 'type' : 'string'},\n {'id':'B', 'label':'OUT pallet', 'type' :'number'}\n ],\n 'rows':[]\n }\n\n # for plotting chart\n kpp_queryset = kpp_queryset.order_by('date')\n\n for one_q in kpp_queryset:\n pretty_datestr = str(one_q.date)[:10]\n if model==\"code\":\n pretty_palletstr = str(one_q.palletcode.palletcode) + \" 를 \" + str(one_q.pallet) +\"개\"\n else :\n pretty_palletstr = str(one_q.code.code) + \" 기업서 \" + str(one_q.pallet) + \"개\"\n cell = {'c': [\n {'v': str(pretty_datestr), 'f': str(pretty_datestr)},\n {'v': one_q.pallet, 'f' : pretty_palletstr},\n ]}\n\n data['rows'].append(cell)\n\n return data\n\n\n\n\n\ndef trend_json(queryset,unit=\"year\"):\n '''\n :param queryset: 트렌드 합산치를 계산하고싶은 쿼리셋 (pallet 라는 컬럼이 반드시 존재해야함)\n :param unit: Choice amonge year,month,weekday,day__year,day__month\n :return: data[dictionary]\n '''\n\n data = {\n 'cols':[\n {'id': 'A', 'label': 'date', 'type' : 'string'},\n {'id':'B', 'label':'OUT Sum', 'type' :'number'},\n {'id':'C', 'label':'IN Sum', 'type' : 'number'}\n ],\n 'rows':[]\n }\n\n\n if unit==\"year\":\n #(sum,date)\n sums = [(queryset.filter(date__year=n).aggregate(Sum('pallet'))['pallet__sum'], n) for n in\n range(2010, 2018)]\n elif unit==\"month\":\n # (sum,date)\n sums = [(queryset.filter(date__month=n).aggregate(Sum('pallet'))['pallet__sum'], n) for n in range(1, 13)]\n\n elif unit==\"weekday\" :\n # (sum,date)\n labels=[\"토\",\"일\",'월','화','수','목','금','토']\n sums = [(queryset.filter(date__week_day=n).aggregate(Sum('pallet'))['pallet__sum'], labels[n]) for n in\n range(1, 8)]\n\n elif unit==\"day__year\" :\n # (sum,date)\n datelist = queryset.filter(date__year=2017).values('date').annotate(pallet__sum=Sum('pallet')).order_by('date')\n sums = [(dt['pallet__sum'], dt['date']) for dt in datelist]\n\n elif unit==\"day__month\":\n data = {\n 'cols': [\n {'id': 'A', 'label': 'date', 'type': 'string'},\n ],\n 'rows': []\n }\n for month in range(1,13):\n data['cols'].append({\n 'id':str(month)+'월',\n 'label':str(month)+'월',\n 'type':'number'\n })\n\n\n #일별로 파레트 총합 합산합니다.\n only2017 = queryset.filter(date__year=2017).values('date').annotate(pallet__sum=Sum('pallet')).order_by('date')\n\n\n for day in range(1,32):\n cell = {'c':[\n {'v':str(day), 'f':str(day)},\n ]}\n #12줄이 추가됨\n #누적수치\n for month in range(1,13):\n day_cumulate = only2017.filter(date__month=month, date__day__lte=day).aggregate(cumulate=Sum('pallet__sum'))['cumulate']\n cell['c'].append({\n 'v': day_cumulate,\n 'f': str(day_cumulate)\n })\n\n data['rows'].append(cell)\n\n return data\n\n elif unit==\"day__week\":\n data = {\n 'cols': [\n {'id': 'A', 'label': 'date', 'type': 'string'},\n ],\n 'rows': []\n }\n for week in range(1,10):\n data['cols'].append({\n 'id':str(week)+'째주',\n 'label':str(week)+'째주',\n 'type':'number'\n })\n\n\n\n datelist = queryset.values('date').annotate(pallet__sum=Sum('pallet')).order_by('date')\n only2017 = datelist.filter(date__year=2017)\n\n #월화수목금토일\n weekstr=['토','일','월','화','수','목','금','토','일']\n for weekday in range(1,8):\n daylist = []\n for week in range(1,10):\n try:\n day = only2017.get(date__week=week, date__week_day=weekday)['pallet__sum']\n except:\n day = 0\n daylist.append(day)\n\n #첫번째줄\n cell = {'c':[\n {'v':weekstr[weekday], 'f':weekstr[weekday]},\n ]}\n for day in daylist:\n cell['c'].append({\n 'v': day,\n 'f': str(day)\n })\n\n data['rows'].append(cell)\n\n return data\n\n\n for ys in sums:\n\n cell = {'c':[\n {'v' : str(ys[1]), 'f':str(ys[1])},\n {'v' : ys[0],'f':str(ys[0])}\n ]}\n\n data[\"rows\"].append(cell)\n\n return data\n\n\ndef rank_json(queryset,m,clean_key):\n\n data = {\n 'cols':[\n {'id': 'A', 'label': m, 'type' : 'string'},\n {'id':'B', 'label':clean_key, 'type' :'number'}\n ],\n 'rows':[]\n }\n if m==\"code\":\n for q in queryset:\n cell = {'c':[\n {'v':str(q.code),'f':str(q.code)},\n {'v':str(q.key),'f':str(q.key)}\n ]}\n data[\"rows\"].append(cell)\n else :\n for q in queryset:\n cell = {'c':[\n {'v':str(q.palletcode),'f':str(q.palletcode)},\n {'v':str(q.key),'f':str(q.key)}\n ]}\n data[\"rows\"].append(cell)\n\n return data","sub_path":"host-docker-machine-file/web-volume/avocado_project/datamanager_app/shortcuts/googlechart.py","file_name":"googlechart.py","file_ext":"py","file_size_in_byte":7800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"364017872","text":"import pandas as pd\nfrom functools import partial\nfrom multiprocessing import Pool\n\ndef replace_nl(string):\n return ' '.join(string.split())\n\ndef write_them(d, outfile=\"tweet.txt\"):\n with open(outfile, \"a\") as f:\n f.write('\\n'.join(list(map(replace_nl, d['text']))))\n \ndef run_it(df_iter):\n while(True):\n try:\n for d in df_iter:\n try:\n write_them(d)\n except:\n pass\n except:\n print(\"iter_error\")\n continue\n \n #pool = Pool(8)\n #pool.map(write_them, df_iter)\n \nif __name__ == \"__main__\":\n df_iter = pd.read_json(\"../tweet.dat\", chunksize=100, lines=True)\n run_it(df_iter)","sub_path":"dat2txt.py","file_name":"dat2txt.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"10330744","text":"# Program: Given a perfect binary tree, populate the next pointer in a level order traversal fashion\n# Author: Ankit Srivastava\n#\n# Date: 9/10/2018\n\nclass TreeNode:\n def __init__(self, d):\n self.val = d\n self.left = None\n self.right = None\n self.next = None\n\nclass Solution:\n # @param root, a tree link node\n # @return nothing\n def connect(self, root):\n if(root == None):\n return\n else:\n q = []\n depth = []\n q.insert(0, root)\n depth.insert(0, 0)\n\n while(len(q) > 0):\n currNode = q.pop()\n val = depth.pop()\n if(currNode != None and len(q) > 0 and len(depth) > 0 and depth[len(depth) - 1] == val):\n currNode.next = q[len(q) - 1]\n else:\n currNode.next = None\n \n if(currNode.left != None):\n q.insert(0, currNode.left)\n depth.insert(0, val + 1)\n \n if(currNode.right != None):\n q.insert(0, currNode.right)\n depth.insert(0, val + 1)\n\n return\n","sub_path":"LeetCode/117 PopulationNextRightPointerInEachNodeII/PopulatingNextPointerInEachNode.py","file_name":"PopulatingNextPointerInEachNode.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"17056307","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport os\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"\n\nimport numpy as np\nfrom iminuit import Minuit\nfrom probfit import UnbinnedLH, gaussian, AddPdf, Normalized, Extended, describe, gen_toy, rename, SimultaneousFit\nimport time\n\nresults = {'probfit': [26],\n 'zfit_eager': [6, 10, 12],\n 'zfit': [1.6 + 0.5, 3 + 1.5, 4 + 1.5, 11],\n 'roofit': [0.5, 2, 4, 12],\n 'nevents': [10000, 50000, 100000, 300000]\n }\n\n# In[2]:\ndo_probfit = False\n# do_probfit = False\n# zfit_eager = True\nzfit_eager = False\n\nnevents = 150000\n\n\ndef gen_samples(nevents, fraction=0.9, slope=0.005):\n fract = sum(np.random.binomial(1, 1 - fraction, nevents) == 0)\n bound = (2900, 3300)\n bkg_m = gen_toy(lambda x: slope * np.math.exp(-slope * x), nevents // 2, bound)\n sig_m = np.random.normal(3096.916, 12, fract)\n tot_m = np.concatenate([sig_m, bkg_m])\n\n bkg_u = gen_toy(lambda x: slope * np.math.exp(-slope * x), nevents // 2, bound)\n sig_u = np.random.normal(3096.916, 12, nevents - fract)\n tot_u = np.concatenate([sig_u, bkg_u])\n\n print(\"matching efficiency = \", fract / nevents)\n\n return tot_m, tot_u\n\n\ntot_m, tot_u = gen_samples(nevents=nevents)\n\n\ndef exp(x, l):\n return l * np.exp(-l * x)\n\n\ndef model(fit_range, bin):\n nrm_bkg_pdf = Normalized(rename(exp, ['x', 'l%d' % bin]), fit_range)\n ext_bkg_pdf = Extended(nrm_bkg_pdf, extname='Ncomb_%d' % bin)\n\n ext_sig_pdf = Extended(rename(gaussian, ['x', 'm%d' % bin, \"sigma%d\" % bin]), extname='Nsig_%d' % bin)\n tot_pdf = AddPdf(ext_bkg_pdf, ext_sig_pdf)\n print('pdf: {}'.format(describe(tot_pdf)))\n\n return tot_pdf\n\n\nfit_range = (2900, 3300)\n\nmod_1 = model(fit_range, 1)\nlik_1 = UnbinnedLH(mod_1, tot_m, extended=True)\nmod_2 = model(fit_range, 2)\nlik_2 = UnbinnedLH(mod_2, tot_u, extended=True)\nsim_lik = SimultaneousFit(lik_1, lik_2)\ndescribe(sim_lik)\n\npars = dict(l1=0.002, Ncomb_1=1000, m1=3100, sigma1=10, Nsig_1=1000, l2=0.002, Ncomb_2=1000, m2=3100, sigma2=10,\n Nsig_2=1000)\nminuit = Minuit(sim_lik, pedantic=False, print_level=0, **pars)\n\n# In[8]:\n\n\nif do_probfit:\n start = time.time()\n minuit.migrad()\n time_probfit = time.time() - start\n\nprint(\"starting zfit\")\nimport zfit\n\nzfit.run.set_graph_mode(not zfit_eager)\n\nmass = zfit.Space(\"mass\", limits=fit_range)\n\n\ndef zfit_model(obs, bin, limits):\n mu = zfit.Parameter(\"mu{}\".format(bin), 3100, limits[0], limits[1])\n sigma = zfit.Parameter(\"sigma{}\".format(bin), 10, 1, 30)\n gauss = zfit.pdf.Gauss(mu=mu, sigma=sigma, obs=obs)\n\n slope = zfit.Parameter(\"slope{}\".format(bin), -0.002, -0.05, 0.0)\n exp = zfit.pdf.Exponential(lambda_=slope, obs=obs)\n\n Nsig = zfit.Parameter(\"Nsig{}\".format(bin), 1000, 0, 1000000)\n Nbkg = zfit.Parameter(\"Nbkg{}\".format(bin), 1000, 0, 2000000)\n ext_gauss = gauss.create_extended(Nsig)\n ext_exp = exp.create_extended(Nbkg)\n\n model = zfit.pdf.SumPDF([ext_exp, ext_gauss])\n return model\n\n\nmodel_ = [zfit_model(mass, i, fit_range) for i in range(2)]\ndata_ = [zfit.Data.from_numpy(obs=mass.obs, array=mass.filter(dataset)) for dataset in [tot_m, tot_u]]\n\nnll_simultaneous = zfit.loss.ExtendedUnbinnedNLL(model=model_, data=data_)\nminimizer = zfit.minimize.Minuit(ncall=10000, verbosity=7, tolerance=1e-3, use_minuit_grad=False)\n\nstart = time.time()\nnll_simultaneous.value_gradients(params=list(nll_simultaneous.get_params()))\ntime_zfit_compile = time.time() - start\n\nstart = time.time()\nresult = minimizer.minimize(nll_simultaneous)\ntime_zfit_min = time.time() - start\nprint(result)\nprint(result.params)\n\n# x = tf.linspace(mass.lower[0][0], mass.upper[0][0], num=1000)\n# nbins = 40\n# for mod, data in zip(model_, [tot_m, tot_u]):\n# y = mod.pdf(x) * mod.get_yield() / nbins * mass.rect_area()\n# plt.figure()\n# plt.plot(x, y, label=mod.name)\n# plt.hist(data, bins=nbins)\n\n# Test ROOT too\nfrom ROOT import RooDataSet, RooRealVar, RooGaussian, RooExponential, RooAbsRealLValue, \\\n RooArgSet, RooFit, RooCategory, RooSimultaneous, RooArgList, RooAddPdf\n\n\ndef load_set(array, var, dataset):\n for entry in array:\n RooAbsRealLValue.__assign__(var, entry)\n dataset.add(RooArgSet(var))\n return dataset\n\n\nm = RooRealVar(\"Jpsi_M\", \"mass\", fit_range[0], fit_range[1])\ndata_m = RooDataSet(\"data_m\", \"data_m\", RooArgSet(m))\ndata_u = RooDataSet(\"data_u\", \"data_u\", RooArgSet(m))\n\ndata_m = load_set(tot_m, m, data_m)\ndata_u = load_set(tot_u, m, data_u)\n\ndata_m.Print(\"v\")\ndata_u.Print(\"v\")\n\nsample = RooCategory(\"sample\", \"sample\")\nsample.defineType(\"matched\")\nsample.defineType(\"unmatched\")\n\n# define the combined set\ncombData = RooDataSet(\n \"combData\",\n \"combined data\",\n RooArgSet(m),\n RooFit.Index(sample),\n RooFit.Import(\n \"matched\",\n data_m),\n RooFit.Import(\n \"unmatched\",\n data_u))\ncombData.Print(\"v\")\n\n# Not working below, bug?\n# # create model\n# def model(var, bin):\n# # define signal pdf\n# mean = RooRealVar(\"mean{}\".format(bin), \"mean{}\".format(bin), 3090, 2900, 3300)\n# sigma = RooRealVar(\"sigma{}\".format(bin), \"sigma{}\".format(bin), 10, 0, 30)\n# gaus = RooGaussian(\"gx{}\".format(bin), \"gx{}\".format(bin), var, mean, sigma)\n#\n# # define background pdf\n# slope = RooRealVar(\"slope{}\".format(bin), \"slope{}\".format(bin), -0.04, -0.1, -0.0001)\n# exp = RooExponential(\"exp{}\".format(bin), \"exp{}\".format(bin), var, slope)\n#\n# # define yields\n# nsig = RooRealVar(\"nsig{}\".format(bin), \"n. sig bin{}\".format(bin), 1000, 0., 1000000)\n# nbkg = RooRealVar(\"nbkg{}\".format(bin), \"n. bkg bin{}\".format(bin), 1000, 0, 2000000)\n#\n# # sum pdfs\n# model = RooAddPdf(\"model{}\".format(bin), \"model{}\".format(bin),\n# RooArgList(exp, gaus),\n# RooArgList(nbkg, nsig))\n# return model\n\n\n# define signal pdf\nbin = \"0\"\nmean0 = RooRealVar(\"mean{}\".format(bin), \"mean{}\".format(bin), 3090, 2900, 3300)\nsigma0 = RooRealVar(\"sigma{}\".format(bin), \"sigma{}\".format(bin), 10, 0, 30)\ngaus0 = RooGaussian(\"gx{}\".format(bin), \"gx{}\".format(bin), m, mean0, sigma0)\n\n# define background pdf\nslope0 = RooRealVar(\"slope{}\".format(bin), \"slope{}\".format(bin), -0.005, -0.1, -0.0001)\nexp0 = RooExponential(\"exp{}\".format(bin), \"exp{}\".format(bin), m, slope0)\n\n# define yields\nnsig0 = RooRealVar(\"nsig{}\".format(bin), \"n. sig bin{}\".format(bin), 1000, 0., 1000000)\nnbkg0 = RooRealVar(\"nbkg{}\".format(bin), \"n. bkg bin{}\".format(bin), 1000, 0, 2000000)\n\n# sum pdfs\nmodel0 = RooAddPdf(\"model{}\".format(bin), \"model{}\".format(bin),\n RooArgList(exp0, gaus0),\n RooArgList(nbkg0, nsig0))\n\n# define signal pdf\nbin = \"1\"\nmean1 = RooRealVar(\"mean{}\".format(bin), \"mean{}\".format(bin), 3090, 2900, 3300)\nsigma1 = RooRealVar(\"sigma{}\".format(bin), \"sigma{}\".format(bin), 10, 0, 30)\ngaus1 = RooGaussian(\"gx{}\".format(bin), \"gx{}\".format(bin), m, mean1, sigma1)\n\n# define background pdf\nslope1 = RooRealVar(\"slope{}\".format(bin), \"slope{}\".format(bin), -0.005, -0.01, -0.0001)\nexp1 = RooExponential(\"exp{}\".format(bin), \"exp{}\".format(bin), m, slope1)\n\n# define yields\nnsig1 = RooRealVar(\"nsig{}\".format(bin), \"n. sig bin{}\".format(bin), 1000, 0., 1000000)\nnbkg1 = RooRealVar(\"nbkg{}\".format(bin), \"n. bkg bin{}\".format(bin), 1000, 0, 2000000)\n\n# sum pdfs\nmodel1 = RooAddPdf(\"model{}\".format(bin), \"model{}\".format(bin),\n RooArgList(exp1, gaus1),\n RooArgList(nbkg1, nsig1))\n\nsimPdf = RooSimultaneous(\"simPdf\", \"simultaneous pdf\", sample)\nsimPdf.addPdf(model0, \"matched\")\nsimPdf.addPdf(model1, \"unmatched\")\n\nstart = time.time()\nresult = simPdf.fitTo(combData, RooFit.Save(True), RooFit.NumCPU(12))\ntime_roofit = time.time() - start\n\nif do_probfit:\n print(f\"time probfit: {time_probfit}\")\nprint(f\"time RooFit: {time_roofit}\")\nprint(f\"time zfit {'eager' if zfit_eager else 'graph'} compile: {time_zfit_compile}, time zfit min={time_zfit_min}\")\n","sub_path":"src/sim_fit_probfit_roofit.py","file_name":"sim_fit_probfit_roofit.py","file_ext":"py","file_size_in_byte":7931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"75508550","text":"import os\nimport base64\nimport model as ml\nimport data_processor as dp\nfrom flask import Flask, make_response, jsonify, request\n\ncategories = dp.get_plants_name('ja')\nclasses = len(categories)\nimage_size = 120\n\napi = Flask(__name__)\n\n\n@api.route('/get_plant', methods=['POST'])\ndef main():\n\n post_file = request.data\n\n dir_name = 'temp_img'\n file_name = dp.make_random_str(5)+'.png'\n file_path = dir_name + '/' + file_name\n\n if not os.path.isdir(dir_name):\n os.makedirs(dir_name)\n\n with open(file_path, 'wb') as f:\n f.write(base64.decodebytes(post_file))\n\n read_file = open(file_path, 'rb')\n\n X = dp.image_convert(read_file, image_size)\n\n read_file.close()\n os.remove(file_path)\n\n model = ml.build_model(X.shape[1:], classes)\n model.load_weights(os.path.join(os.path.dirname(__file__), 'store/model.hdf5'))\n\n predict = model.predict_proba(X)\n predict_key = dp.sort_predict_key(predict[0], 3)\n\n plants = []\n\n for y in predict_key:\n plants.append(categories[y])\n\n result = {\n \"data\": {\n \"plant\": plants\n }\n }\n\n return make_response(jsonify(result))\n\n\n@api.errorhandler(404)\ndef not_found(error):\n\n return make_response(jsonify({'error': 'Not found'}), 404)\n\n\n@api.errorhandler(400)\ndef bad_request(error):\n\n return make_response(jsonify({'error': 'Nothing post data'}), 400)\n\n\nif __name__ == '__main__':\n api.run(host='0.0.0.0', port=8000)\n","sub_path":"ml/model_api.py","file_name":"model_api.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"121352979","text":"import json\nimport numpy as np\nimport random\nfrom random import choice\nfrom tqdm import tqdm\nimport collections\n\nglobal num\n\ndef get_nearest_start_position_(S1_):\n nearest_start_list = []\n current_distance_list = []\n S1 = []\n S1_ = np.array(S1_)\n for i in S1_:\n j = np.argmax(i, 1)\n S1.append(j)\n\n for start_pos_list in S1:\n nearest_start_pos = []\n current_start_pos = 0\n current_pos = []\n flag = False\n for i, start_label in enumerate(start_pos_list):\n if start_label > 0:\n current_start_pos = i\n flag = True\n nearest_start_pos.append(current_start_pos)\n if flag > 0:\n if i-current_start_pos > 10:\n current_pos.append(499)\n else:\n current_pos.append(i-current_start_pos)\n else:\n current_pos.append(499)\n # print(start_pos_list)\n # print(nearest_start_pos)\n # print(current_pos)\n # print('-----')\n nearest_start_list.append(nearest_start_pos)\n current_distance_list.append(current_pos)\n return nearest_start_list, current_distance_list\n\n\ndef get_nearest_start_position(S1):\n nearest_start_list = []\n current_distance_list = []\n for start_pos_list in S1:\n nearest_start_pos = []\n current_start_pos = 0\n current_pos = []\n flag = False\n for i, start_label in enumerate(start_pos_list):\n if start_label > 0:\n current_start_pos = i\n flag = True\n nearest_start_pos.append(current_start_pos)\n if flag > 0:\n if i-current_start_pos > 10:\n current_pos.append(499)\n else:\n current_pos.append(i-current_start_pos)\n else:\n current_pos.append(499)\n # print(start_pos_list)\n # print(nearest_start_pos)\n # print(current_pos)\n # print('-----')\n nearest_start_list.append(nearest_start_pos)\n current_distance_list.append(current_pos)\n return nearest_start_list, current_distance_list\n\ndef locate_entity(token_list, entity):\n try:\n for i, token in enumerate(token_list):\n if entity.startswith(token):\n len_ = len(token)\n j = i+1 ; joined_tokens = [token]\n while len_ < len(entity):\n len_ += len(token_list[j])\n joined_tokens.append(token_list[j])\n j = j+1\n if ''.join(joined_tokens) == entity:\n return i, len(joined_tokens)\n except Exception:\n # print(entity,token_list)\n pass\n return -1, -1\n\ndef seq_padding(X):\n L = [len(x) for x in X]\n # ML = config.MAX_LEN #max(L)\n ML = max(L)\n return [x + [0] * (ML - len(x)) for x in X]\n\ndef seq_padding_(X):\n tmp = [0.0 for i in range(len(X[0][0]))]\n L = [len(x) for x in X]\n # ML = config.MAX_LEN #max(L)\n ML = max(L)\n for x in X:\n for i in range(ML - len(x)):\n x.append(tmp)\n return X\n\n\ndef char_padding(X):\n L_S = [len(x) for x in X]\n ML_S = max(L_S)\n L = [[len(t) for t in s] for s in X]\n # ML = config.MAX_LEN #max(L)\n ML = max([max(l) for l in L])\n if ML <= 15:\n return [[t + [0] * (15 - len(t)) for t in s]+[[1] * 15 for i in range(ML_S-len(s))] for s in X]\n else:\n return [[t + [0] * (15 - len(t)) if len(t) <=15 else t[:15] for t in s]+[[1] * 15 for i in range(ML_S-len(s))] for s in X]\ndef get_pos_tags(tokens, pos_tags, pos2id):\n pos_labels = [pos2id.get(flag,1) for flag in pos_tags]\n if len(pos_labels) != len(tokens):\n print(pos_labels)\n return False\n return pos_labels\n\ndef get_positions(start_idx, end_idx, length):\n \"\"\" Get subj/obj position sequence. \"\"\"\n return list(range(-start_idx, 0)) + [0]*(end_idx - start_idx + 1) + \\\n list(range(1, length-end_idx))\n\n\ndef sort_all(batch, lens):\n \"\"\" Sort all fields by descending order of lens, and return the original indices. \"\"\"\n unsorted_all = [lens] + [range(len(lens))] + list(batch)\n sorted_all = [list(t) for t in zip(*sorted(zip(*unsorted_all), reverse=True))]\n return sorted_all[2:], sorted_all[1]\n\n\n\n# {\n# \"sent\": \"半导体行情的风险是什么\",\n# \"sent_tokens\": [\"半\", \"导\", \"体\", \"行\", \"情\", \"的\", \"风\", \"险\", \"是\", \"什\", \"么\"],\n# \"sent_token_ids\": [1288, 2193, 860, 6121, 2658, 4638, 7599, 7372, 3221, 784, 720],\n# \"entity_labels\": [{\"entity_type\": \"研报\", \"start_token_id\": 0, \"end_token_id\": 10, \"start_index\": 0, \"end_index\": 10,\n# \"entity_tokens\": [\"半\", \"导\", \"体\", \"行\", \"情\", \"的\", \"风\", \"险\", \"是\", \"什\", \"么\"],\n# \"entity_name\": \"半导体行情的风险是什么\"}],\n# \"tags\": [\"B-Report\", \"I-Report\", \"I-Report\", \"I-Report\", \"I-Report\", \"I-Report\", \"I-Report\", \"I-Report\", \"I-Report\", \"I-Report\", \"I-Report\"],\n# \"tag_ids\": [11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12]},\n\nclass DataLoader(object):\n def __init__(self, origin_data, subj_type2id, batch_size=64, evaluation=True):\n\n self.batch_size = batch_size\n self.subj_type2id = subj_type2id\n self.evaluation = evaluation\n\n data = self.preprocess(origin_data)\n if not self.evaluation:\n indices = list(range(len(data)))\n random.shuffle(indices)\n data = [data[i] for i in indices]\n self.num_examples = len(data)\n self.data = [data[i:i + self.batch_size] for i in range(0, len(data), self.batch_size)]\n\n def preprocess(self, data):\n processed = []\n for index, d in enumerate(data):\n # if index > 800:\n # break\n # d = self.data[i]\n tokens = d['sent_tokens']\n if len(tokens) > 180:\n continue\n items = d['entity_labels']\n\n if items:\n tokens_ids = d['sent_token_ids']\n tags_ids = d['tag_ids']\n\n processed += [(tokens_ids, tags_ids)]\n return processed\n\n def __len__(self):\n return len(self.data)\n\n def __iter__(self):\n for i in range(self.__len__()):\n yield self.__getitem__(i)\n\n def __getitem__(self, key):\n \"\"\" Get a batch with index. \"\"\"\n if not isinstance(key, int):\n raise TypeError\n if key < 0 or key >= len(self.data):\n raise IndexError\n batch = self.data[key]\n batch_size = len(batch)\n batch = list(zip(*batch))\n assert len(batch) == 2\n lens = [len(x) for x in batch[0]]\n\n batch, orig_idx = sort_all(batch, lens)\n T = np.array(seq_padding(batch[0]))\n\n tags = np.array(seq_padding(batch[1]))\n\n return (T, tags, orig_idx)\n\n\nif __name__ == '__main__':\n s = [[[1,3,4],[2,2,2,2,2]],[[1,3,4,6,6,6,6,6,6],[2,2,2,2,2,7,7,7]]]\n print(char_padding(s))\n\n\n","sub_path":"expirement_er/bertcrf/utils/loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":6955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"131414373","text":"import xlrd\r\nimport re\r\nimport pickle\r\nfrom .xlsutils import *\r\nfrom .tp_classes import Predmet\r\nfrom .tp_info_parse import get_tp_info\r\nfrom .tp_tit_parse import tit_parse\r\n\r\ndef TP_Parse(tp_filename):\r\n SHEET_TP_NAME = \"РНП\"\r\n SHEET_TITLE_NAME = \"ТитулНП\"\r\n PREDM_DATA_START = 3\r\n\r\n\r\n\r\n PRED_FRAGS = ('ekz','zal','kp','kr','rgr','normativ', 'full_ld','cred',\r\n 'aud_ld', 'lec', 'prac', 'lab', 'srs')\r\n\r\n SEM_POS = ('Q','W','AC', \"AI\", \"AO\", \"AU\", \"BA\", \"BG\" )\r\n\r\n\r\n\r\n def extract_predmet(raw):\r\n\r\n def extract_semdata(raw):\r\n def fix_blank(x):\r\n return 0 if x == '' else x\r\n sem_data = []\r\n sem_map = []\r\n srs_min= []\r\n for s in SEM_POS:\r\n s = col_coord(s)\r\n frag = raw[s:s+6]\r\n #del frag[-3]\r\n frag = list(map(fix_blank,frag))\r\n srs_min.append(frag.pop(-2))# srs_min remove \r\n frag[:-1] = map(int,frag[:-1])\r\n if sum(frag):\r\n sem_data.append(frag)\r\n sem_map.append(1)\r\n else:\r\n sem_map.append(0)\r\n \r\n return sem_data, sem_map, srs_min\r\n\r\n def is_cw_element(test_str,cur_sem):\r\n test_str = str(test_str)\r\n if str(cur_sem) in test_str:\r\n return True\r\n if (len(test_str)>2) and ('-' in test_str):\r\n (x1,x2) = test_str.split('-')\r\n if int(x2[0])>cur_sem>int(x1[-1]):\r\n return True\r\n return False\r\n \r\n \r\n def def_control(info, cur_sem):\r\n if is_cw_element(info['ekz'],cur_sem):\r\n return 'ekz'\r\n elif is_cw_element(info['zal'],cur_sem):\r\n return 'zal'\r\n else:\r\n return None\r\n \r\n def def_krgr(info, cur_sem):\r\n if is_cw_element(info['rgr'],cur_sem):\r\n return 'rgr'\r\n elif is_cw_element(info['kr'],cur_sem):\r\n return 'kr'\r\n elif is_cw_element(info['kp'],cur_sem):\r\n return 'kp'\r\n else:\r\n return None \r\n\r\n code = raw[0]\r\n title = raw[1]\r\n kafedra = raw[col_coord('BM')]\r\n gen_info = {f:raw[PREDM_DATA_START+PRED_FRAGS.index(f)] for f in PRED_FRAGS}\r\n semdata, smap, srs_min = extract_semdata(raw)\r\n \r\n q_sem = sum(smap)\r\n cur_sem = smap.index(1)+1\r\n for frag in semdata:\r\n control = def_control(gen_info, cur_sem)\r\n krgr = def_krgr(gen_info, cur_sem)\r\n cur_sem += 1\r\n frag.append(krgr)\r\n frag.append(control)\r\n\r\n \r\n #print(code,title, gen_info,'\\n\\t',semdata,'\\n\\t', smap)\r\n return Predmet(code, title, semdata, smap, kafedra, srs_min) \r\n \r\n \r\n \r\n\r\n\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n\r\n \r\n\r\n\r\n tp = xlrd.open_workbook(tp_filename,formatting_info=False)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n\r\n def test_row_content(r):\r\n if isinstance(r,(int,float)) or r ==\"\":\r\n return False\r\n ptrn_pred_code = r\"(?:ГСЕ|МПН|ПП)(?:\\.|\\s+)\\d\\.\\d+\" # шаблон для кода предмета\r\n if type(r) == str and re.search(ptrn_pred_code,r.strip()):\r\n return \"predmet\"\r\n \r\n elif \"НОРМАТИВНІ НАВЧАЛЬНІ ДИСЦИПЛІНИ\" in r:\r\n status['part'] = \"НОРМАТИВ\"\r\n status['cycle']= None\r\n status['block']= None\r\n \r\n elif \"ВИБІРКОВІ НАВЧАЛЬНІ ДИСЦИПЛІНИ\" in r:\r\n status['part'] = \"ВАРІАТИВ\"\r\n status['cycle']= None\r\n status['block']= None\r\n elif \"Гуманітарні та соціально-економічні дисципліни\" in r:\r\n status['cycle']= \"ГСЕ\"\r\n status['block']= None\r\n\r\n elif \"Дисципліни математичної, природничо-наукової (фундаментальної) підготовки\" in r:\r\n status['cycle']= \"МПН\"\r\n status['block']= None\r\n\r\n elif \"Дисципліни професійної і практичної підготовки\" in r:\r\n status['cycle']= \"ПП\"\r\n status['block']= None\r\n\r\n elif (\"Професійна підготовка\" in r) and status['cycle']== \"ПП\" :\r\n status['block']= \"ПрофП\"\r\n elif (\"Практична підготовка\" in r) and status['cycle']== \"ПП\" and status['block']== \"ПрофП\":\r\n status['block']= \"ПрактП\"\r\n \r\n elif \"Дисципліни самостійного вибору навчального закладу\" in r:\r\n status['cycle']= \"СВНЗ\"\r\n status['block']= None\r\n\r\n elif \"Дисципліни вільного вибору студента\" in r:\r\n status['cycle']= \"ВВС\"\r\n status['block']= None\r\n ## else:\r\n ## print(\"!!!!\", r, r2)\r\n\r\n elif (\"Блок А\" in r) and status['cycle']== \"ВВС\" :\r\n status['block']= \"Блок А\"\r\n elif (\"Блок Б\" in r) and status['cycle']== \"ВВС\" :\r\n status['block']= \"Блок Б\"\r\n elif (\"Блок В\" in r) and status['cycle']== \"ВВС\" :\r\n status['block']= \"Блок В\"\r\n\r\n \r\n \r\n #----MAIN------\r\n predm_map = []\r\n stp = tp.sheet_by_name(SHEET_TP_NAME)\r\n #nrows = stp.nrows\r\n raw_col0,raw_col1 = stp.col_values(0),stp.col_values(1)\r\n status = {'part':None, 'cycle':None, 'block':None }\r\n\r\n\r\n for i,d in enumerate(raw_col0):\r\n s = test_row_content(d) # проверка, что в строке \r\n if s == \"predmet\":\r\n #print(i, d, raw_col1[i], status['part'], status['cycle'], status['block'])\r\n predm_map.append((i, d, raw_col1[i], status['part'], status['cycle'], status['block']))\r\n #print(predm_map[-1])\r\n\r\n ##\r\n ##for p in predm_map:\r\n ## print(p)\r\n #### \r\n ##0/0 \r\n predmets = []\r\n for pred in predm_map:\r\n raw = stp.row_values(pred[0])\r\n \r\n predmets.append(extract_predmet(raw))\r\n \r\n predmets[-1].part = pred[-3]\r\n predmets[-1].cycle = pred[-2]\r\n predmets[-1].block = pred[-1]\r\n\r\n## n = 1\r\n##\r\n## def add_predm(predm):\r\n## for i in range(len(psum)):\r\n## psum[i]+=predm[i]\r\n## \r\n##\r\n## sem = 1\r\n## psum = [0,0,0,0,0.0]\r\n## for p in predmets:\r\n## if p.is_in_sem(sem):\r\n## print(n, p.get_sem(sem))\r\n## add_predm(p.get_sem(sem))\r\n## n+=1\r\n## print(psum)\r\n stit = tp.sheet_by_name(SHEET_TITLE_NAME) \r\n TP_ATTRIB, TP_TITLE_TABLES = tit_parse(stit)\r\n TP_INFO = get_tp_info(stp)\r\n TP_INFO['year'] = TP_ATTRIB['year'][1]\r\n return predmets, TP_INFO, TP_ATTRIB, TP_TITLE_TABLES \r\n\r\n## #print(get_tp_info(stp))\r\n## with open('tp_info.pickle', 'wb') as f:\r\n## pickle.dump(get_tp_info(stp), f)\r\n## with open('pred_data.pickle', 'wb') as f:\r\n## pickle.dump(predmets, f)\r\n\r\n\r\n","sub_path":"tp/tp_parse.py","file_name":"tp_parse.py","file_ext":"py","file_size_in_byte":7440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"314375883","text":"import logging\nimport math\nimport numpy as np\nimport random\n\nimport settings\n\nlogger = logging.getLogger(__name__)\n\nfloor = math.floor\nmod = np.remainder\nround = np.around\nrand = np.random.rand\nrandi = np.random.randint\nrandom_unif = np.random.uniform\nrandperm = np.random.permutation\ndiff = np.diff\npolyval = np.polyval\nbetarnd = random.betavariate\n# TODO: verify correctness that randsample is equivalent to random.choices\nrandsample = random.choices\n\n\ndef iff(condition, value1, value2):\n return value1 if condition else value2\n\n\ndef dec2bin(decimal):\n return f'{160:3b}'.replace(' ', '0')\n\n\ndef GetCatchStimIdx(stimulus_omega):\n # stimulus_omega is between 0 and 1, we break it down to bins of 20\n def calc_catch_stim_idx(omega):\n return round(omega * 20) + 1\n if isinstance(stimulus_omega, list):\n catch_stim_idx = [calc_catch_stim_idx(\n omega) for omega in stimulus_omega]\n else:\n catch_stim_idx = calc_catch_stim_idx(stimulus_omega)\n return catch_stim_idx\n\n\ndef TruncatedExponential(min_value, max_value, tau):\n if min_value == max_value == 0:\n raise ValueError('Invalid value 0 for min_value and max_value.')\n # Initialize to a large value\n exp = max_value + 1\n # sample until in range\n while exp > (max_value - min_value):\n exp = random.expovariate(tau)\n # add the offset\n exp += min_value\n return exp\n\n\ndef EncTrig(trigger_id):\n # Provides V1 & V2 compatibility\n return iff(settings.IS_V2, dec2bin(trigger_id), trigger_id)\n\n\ndef CalcAudClickTrain(data, trial_num):\n return 1\n\n\ndef CalcLightIntensity(data, trial_num):\n data.Custom.LightIntensityLeft[trial_num] = \\\n round(data.Custom.StimulusOmega[trial_num] * 100)\n data.Custom.LightIntensityRight[trial_num] = \\\n round((1 - data.Custom.StimulusOmega[trial_num]) * 100)\n dv = (data.Custom.StimulusOmega[trial_num] * 2) - 1\n return dv\n\n\ndef CalcGratingOrientation(data, trial_num):\n return 1\n\n\ndef CalcDotsCoherence(data, trial_num):\n return 1\n\n\nclass GetValveTimesError(Exception):\n pass\n\n\ndef error(message):\n logger.error(message)\n raise GetValveTimesError(message)\n\n\nclass LiquidCalClass:\n def __init__(self, Table, Coeffs):\n self.Table = Table\n self.Coeffs = Coeffs\n\n\nclass CalibrationTables:\n DEFAULT_TABLES = [\n [\n [15.0000, 0],\n [20.0000, 0.1700],\n [50.0000, 1.3500],\n [50.0000, 1.3100],\n [30.0000, 0.5500],\n [75.0000, 2.6350],\n [100.0000, 3.8200],\n [150.0000, 6.5900],\n ],\n [\n [10.0000, 0],\n [20.0000, 0.2050],\n [50.0000, 1.1800],\n [50.0000, 1.0850],\n [30.0000, 0.4600],\n [75.0000, 2.2000],\n [100.0000, 3.3600],\n [150.0000, 5.6300],\n ],\n [\n [10.0000, 0],\n [20.0000, 0.4900],\n [50.0000, 1.5200],\n [50.0000, 1.2950],\n [30.0000, 0.6200],\n [75.0000, 2.7750],\n [100.0000, 4.1800],\n [150.0000, 6.6500],\n ],\n [], [], [], [], []\n ]\n COEFFS = [\n [0.6847, 24.7278, 16.3721],\n [1.1799, 30.5735, 14.1329],\n [0.6150, 24.5236, 12.5769],\n [0], [0], [0], [0], [0]\n ]\n\n LiquidCal = [LiquidCalClass(table, coeffs)\n for table, coeffs in zip(DEFAULT_TABLES, COEFFS)]\n\n\ndef GetValveTimes(LiquidAmount, TargetValves):\n if isinstance(TargetValves, int):\n TargetValves = [TargetValves]\n nValves = len(TargetValves)\n ValveTimes = [0] * nValves\n for x in range(nValves):\n ValidTable = True\n TargetValveIdx = TargetValves[x] - 1\n CurrentTable = CalibrationTables.LiquidCal[\n TargetValveIdx].Table\n if CurrentTable:\n ValveDurations = [row[0] for row in CurrentTable]\n nMeasurements = len(ValveDurations)\n if nMeasurements < 2:\n ValidTable = False\n error('Not enough liquid calibration measurements exist for'\n f'valve {TargetValves[x]}. Bpod needs at least 3'\n 'measurements.')\n else:\n ValidTable = False\n error('Not enough liquid calibration measurements exist for valve '\n f'{TargetValves[x]}. Bpod needs at least 3 measurements.')\n if ValidTable:\n ValveTimes[x] = polyval(CalibrationTables.LiquidCal[\n TargetValveIdx].Coeffs, LiquidAmount)\n if ValveTimes[x] is None:\n ValveTimes[x] = 0\n if any([(valve_time < 0) for valve_time in ValveTimes]):\n error(f'Wrong liquid calibration for valve {TargetValves[x]}.'\n 'Negative open time.')\n ValveTimes[x] /= 1000\n result = ValveTimes[0] if nValves == 1 else ValveTimes\n return result\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"560444929","text":"#!/bin/env python\nimport ssl\nimport socket\nimport json\nfrom enum import Enum\n\nmain_currency = [\"BTC\", \"btc\", \"ETH\", \"eth\"]\nalt_currency = [\"HPB\", \"hpb\"]\n\n\n# Query types for which QueryBuilder can build API queries\nclass QueryType(Enum):\n PRICE_TICKER = 1\n MARKET_DEPTH = 2\n TRADE_SELL = 3 # amount api_key price sign symbol type\n TRADE_BUY = 4\n TRADE_CANCEL = 5\n\n\n# Build API query for market\nclass QueryBuilder():\n # Build API query\n # Arguments:\n # market - address on which market will respond for API query\n # qtype - defining which query should be build\n # arg - touple of variable length containig specific arguments for query\n # Return:\n # query in string format\n def build(self, market, qtype, *arg):\n if qtype == QueryType.PRICE_TICKER:\n return \"GET /api/v1/ticker?symbol=\"+arg[0]+\"_\"+arg[1]+\" HTTP/1.1\\r\\nHost: \"+market+\"\\r\\nConnection: keep-alive\\r\\n\\r\\n\"\n elif qtype == QueryType.TRADE_SELL:\n return \"POST /api/v1/trade\\r\\nHost: \"+market+\"\\r\\n\\r\\namount=\"+arg[0]+\"&api_key=\"+arg[1]+\"&price=\"+arg[2]+\"&sign=\"+arg[3]+\"&symbol=\"+arg[4]+\"&type=sell\"\n elif qtype == QueryType.TRADE_BUY:\n raise \"QueryType.TRADE_BUY unimplementd\"\n elif qtype == QueryType.TRADE_CANCEL:\n return \"QueryType.TRADE_CANCEL unimplementd\"\n\n\n# Represents market and holds functionality for comunincating with market\nclass Market:\n tcp_socket = 0\n ssl_wraper = 0\n address = \"\"\n api_key = \"\"\n secret_key = \"\"\n market_query = None\n\n\n def __init__(self, address, api_key, secret_key):\n self.address = address\n self.api_key = api_key\n self.secret_key = secret_key\n self.market_query = QueryBuilder()\n\n self.tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.tcp_socket.connect((self.address, 443))\n self.ssl_wraper = ssl.wrap_socket(self.tcp_socket, keyfile=None, certfile=None, server_side=False, cert_reqs=ssl.CERT_NONE, ssl_version=ssl.PROTOCOL_TLSv1_2)\n\n\n def __del__(self):\n self.ssl_wraper.close()\n\n\n # Send API query to market and parse response\n # Arguments:\n # query - String query obtained from QueryBuilder.build()\n # Return:\n # On sucess: resp - Parsed response without HTTP headers\n # On fail: None\n def query_market(self, query):\n self.ssl_wraper.sendall(query.encode())\n\n resp = self.ssl_wraper.recv(4096).decode()\n if not resp:\n print(\"Market \"+self.address+\" did not respod for query: \"+query)\n self.ssl_wraper.close()\n return None\n\n header_delim = resp.find(\"\\r\\n\\r\\n\")\n payload = resp[header_delim+4:]\n return json.loads(payload)\n\n\n # Get currency info\n # API reference: https://api.allcoin.com/api/v1/ticker\n #\n # Arguments:\n # cofi - Currency of Interest. For this currency we want statistics\n # cotc - Currency to compare. Currency stats will be comapred against this currency\n # both arguments cotains 3 letter identifier (btc, ltc, hpb, usd, ...)\n # Return:\n # JSON parsed to python dictionary\n # For more info see: https://www.allcoin.com/About/APIReference/\n def currency_info(self, cofi, ctoc):\n q = self.market_query.build(self.address, QueryType.PRICE_TICKER, cofi, ctoc)\n return self.query_market(q)\n\n # Get last price of currency from market.\n #\n # Argument:\n # currency - three letter identifier of currency (btc, ltc, hpb, ...)\n # Return:\n # Last price of currency compared to USD or Bitcoin. Values is float.\n def last_price(self, currency):\n info = None\n if currency in main_currency:\n info = self.currency_info(currency, \"usd\")\n elif currency in alt_currency:\n info = self.currency_info(currency, \"btc\")\n else:\n print(\"Unknow currency: \"+currency)\n return None\n\n return info['ticker']['last']\n\n\n # Sell security at given price or with current price\n #\n # Arguments:\n # what - Three letter symbol of currency which should be sold\n # amount - amount of security to be sold\n # at_price - price at which security should be sold. If 0 it will be sold with current price\n # Return:\n # On sucess: Order id in string format\n # On failure: None\n def sell(self, what, amount, at_price=0):\n if at_price == 0:\n at_price = self.last_price(what)\n if not at_price:\n return None\n\n # TODO sign quey with secret_key\n q = self.market_query.build(self.address, QueryType.TRADE_SELL, amount, self.api_key, at_price, \"TODO sign\", what)\n response = self.query_market(q)\n\n if not response or response['result'] == \"false\":\n return None\n else:\n return response['order_id']\n\n\n def buy(self):\n raise \"buy unimplementd\"\n\n\n def cancel(self, api_key, order_id, sign, symbol):\n raise \"cancel unimplementd\"\n\n\n\n#######################\n# MAIN #\n#######################\nm = Market(\"api.allcoin.com\", \"\", \"\")\n\np = m.last_price(\"btc\")\nif p:\n print(p)\n\np = m.last_price(\"hpb\")\nif p:\n print(p)\n\nm.last_price(\"dfsdf\")\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"650916166","text":"\"\"\"\nTrains a Pixel-CNN++ generative model on CIFAR-10 or Tiny ImageNet data.\nUses multiple GPUs, indicated by the flag --nr_gpu\n\nExample usage:\nCUDA_VISIBLE_DEVICES=0,1,2,3 python train_double_cnn.py --nr_gpu 4\n\"\"\"\n\nimport os\nimport sys\nimport json\nimport argparse\nimport time\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom pixel_cnn_pp import nn\nfrom pixel_cnn_pp.model import model_spec\nfrom utils import plotting\n\n# -----------------------------------------------------------------------------\nparser = argparse.ArgumentParser()\n# data I/O\nparser.add_argument('-i', '--data_dir', type=str, default='data/', help='Location for the dataset')\nparser.add_argument('-o', '--save_dir', type=str, default='logs/', help='Location for parameter checkpoints and samples')\nparser.add_argument('-d', '--data_set', type=str, default='cifar100', help='Can be either cifar100|cifar10|imagenet')\nparser.add_argument('-t', '--save_interval', type=int, default=20, help='Every how many epochs to write checkpoint/samples?')\nparser.add_argument('-r', '--load_params', dest='load_params', action='store_true', help='Restore training from previous model checkpoint?')\n# model\nparser.add_argument('-q', '--nr_resnet', type=int, default=5, help='Number of residual blocks per stage of the model')\nparser.add_argument('-n', '--nr_filters', type=int, default=160, help='Number of filters to use across the model. Higher = larger model.')\nparser.add_argument('-m', '--nr_logistic_mix', type=int, default=10, help='Number of logistic components in the mixture. Higher = more flexible model')\nparser.add_argument('-z', '--resnet_nonlinearity', type=str, default='concat_elu', help='Which nonlinearity to use in the ResNet layers. One of \"concat_elu\", \"elu\", \"relu\" ')\nparser.add_argument('-c', '--class_conditional', dest='class_conditional', action='store_true', help='Condition generative model on labels?')\nparser.add_argument('-ed', '--energy_distance', dest='energy_distance', action='store_true', help='use energy distance in place of likelihood')\n# optimization\nparser.add_argument('-l', '--learning_rate', type=float, default=0.001, help='Base learning rate')\nparser.add_argument('-e', '--lr_decay', type=float, default=0.999995, help='Learning rate decay, applied every step of the optimization')\nparser.add_argument('-b', '--batch_size', type=int, default=16, help='Batch size during training per GPU')\nparser.add_argument('-u', '--init_batch_size', type=int, default=16, help='How much data to use for data-dependent initialization.')\nparser.add_argument('-p', '--dropout_p', type=float, default=0.5, help='Dropout strength (i.e. 1 - keep_prob). 0 = No dropout, higher = more dropout.')\nparser.add_argument('-x', '--max_epochs', type=int, default=5000, help='How many epochs to run in total?')\n# evaluation\nparser.add_argument('--polyak_decay', type=float, default=0.9995, help='Exponential decay rate of the sum of previous model iterates during Polyak averaging')\nparser.add_argument('-ns', '--num_samples', type=int, default=1, help='How many batches of samples to output.')\n# reproducibility\nparser.add_argument('-s', '--seed', type=int, default=1, help='Random seed to use')\nargs = parser.parse_args()\nprint('input args:\\n', json.dumps(vars(args), indent=4, separators=(',',':'))) # pretty print args\n\n# -----------------------------------------------------------------------------\n# fix random seed for reproducibility\nrng = np.random.RandomState(args.seed)\ntf.set_random_seed(args.seed)\n\n# energy distance or maximum likelihood?\nif args.energy_distance:\n loss_fun = nn.energy_distance\nelse:\n loss_fun = nn.discretized_mix_logistic_loss\n\n# initialize data loaders for train/test splits\nif args.data_set == 'imagenet' and args.class_conditional:\n raise(\"We currently don't have labels for the small imagenet data set\")\nif args.data_set == 'cifar10':\n import data.cifar10_data as cifar10_data\n DataLoader = cifar10_data.DataLoader\nelif args.data_set == 'cifar100':\n import data.cifar100_data as cifar100_data\n DataLoader = cifar100_data.DataLoader\nelif args.data_set == 'imagenet':\n import data.imagenet_data as imagenet_data\n DataLoader = imagenet_data.DataLoader\nelse:\n raise(\"unsupported dataset\")\ntrain_data = DataLoader(args.data_dir, 'train', args.batch_size, rng=rng, shuffle=True, return_labels=args.class_conditional)\ntest_data = DataLoader(args.data_dir, 'test', args.batch_size, shuffle=False, return_labels=args.class_conditional)\nobs_shape = train_data.get_observation_size() # e.g. a tuple (32,32,3)\nassert len(obs_shape) == 3, 'assumed right now'\n\n# data place holders\nx_init = tf.placeholder(tf.float32, shape=(args.init_batch_size,) + obs_shape)\nxs = tf.placeholder(tf.float32, shape=(args.batch_size, ) + obs_shape)\n\n# if the model is class-conditional we'll set up label placeholders + one-hot encodings 'h' to condition on\nif args.class_conditional:\n num_labels = train_data.get_num_labels()\n y_init = tf.placeholder(tf.int32, shape=(args.init_batch_size,))\n h_init = tf.one_hot(y_init, num_labels)\n ys = tf.placeholder(tf.int32, shape=(args.batch_size,))\n hs = tf.one_hot(ys, num_labels)\nelse:\n h_init = None\n hs = None\n\n# create the model\nmodel_opt = { 'nr_resnet': args.nr_resnet, 'nr_filters': args.nr_filters, 'nr_logistic_mix': args.nr_logistic_mix, 'resnet_nonlinearity': args.resnet_nonlinearity, 'energy_distance': args.energy_distance }\nmodel = tf.make_template('model', model_spec)\n\n# run once for data dependent initialization of parameters\ninit_pass = model(x_init, h_init, init=True, dropout_p=args.dropout_p, **model_opt)\n\n# keep track of moving average\nall_params = tf.trainable_variables()\nema = tf.train.ExponentialMovingAverage(decay=args.polyak_decay)\nmaintain_averages_op = tf.group(ema.apply(all_params))\nema_params = [ema.average(p) for p in all_params]\n\n# train\nout = model(xs, hs, ema=None, dropout_p=args.dropout_p, **model_opt)\nloss_gen = loss_fun(tf.stop_gradient(xs), out)\n\n# gradients\ngrads = tf.gradients(loss_gen, all_params, colocate_gradients_with_ops=True)\n\n# test\nout = model(xs, hs, ema=ema, dropout_p=0., **model_opt)\nloss_gen_test = loss_fun(xs, out)\n\n# sample\nout = model(xs, hs, ema=ema, dropout_p=0, **model_opt)\nif args.energy_distance:\n new_x_gen = out[0]\nelse:\n new_x_gen = nn.sample_from_discretized_mix_logistic(out, args.nr_logistic_mix)\n\n# add losses and gradients together and get training updates\ntf_lr = tf.placeholder(tf.float32, shape=[])\n# training op\noptimizer = tf.group(nn.adam_updates(all_params, grads, lr=tf_lr, mom1=0.95, mom2=0.9995), maintain_averages_op)\n\n# convert loss to bits/dim\nbits_per_dim = loss_gen/(np.log(2.)*np.prod(obs_shape))\nbits_per_dim_test = loss_gen_test/(np.log(2.)*np.prod(obs_shape))\n\ntf.summary.scalar(\"Loss\", loss_gen / args.batch_size)\ntf.summary.scalar(\"BPD\", bits_per_dim / args.batch_size)\ntf.summary.scalar(\"Learning rate\", tf_lr)\nsummary = tf.summary.merge_all()\n\n# sample from the model\ndef sample_from_model(sess):\n x_gen = np.zeros((args.batch_size,) + obs_shape, dtype=np.float32)\n for yi in range(obs_shape[0]):\n for xi in range(obs_shape[1]):\n new_x_gen_np = sess.run(new_x_gen, {xs: x_gen})\n x_gen[:,yi,xi,:] = new_x_gen_np[:,yi,xi,:]\n return x_gen\n\n# init & save\ninitializer = tf.global_variables_initializer()\nsaver = tf.train.Saver()\n\n# turn numpy inputs into feed_dict for use with tensorflow\ndef make_feed_dict(data, init=False):\n if type(data) is tuple:\n x,y = data\n else:\n x = data\n y = None\n x = np.cast[np.float32]((x - 127.5) / 127.5) # input to pixelCNN is scaled from uint8 [0,255] to float in range [-1,1]\n if init:\n feed_dict = {x_init: x}\n if y is not None:\n feed_dict.update({y_init: y})\n else:\n feed_dict = {xs: x}\n if y is not None:\n feed_dict.update({ys: y})\n return feed_dict\n\n# //////////// perform training //////////////\nif not os.path.exists(args.save_dir):\n os.makedirs(args.save_dir)\ntest_bpd = []\nlr = args.learning_rate\nwith tf.Session() as sess:\n writer = tf.summary.FileWriter(args.save_dir + '/train', sess.graph)\n test_writer = tf.summary.FileWriter(args.save_dir + '/test', sess.graph)\n for epoch in range(args.max_epochs):\n begin = time.time()\n\n # init\n if epoch == 0:\n train_data.reset() # rewind the iterator back to 0 to do one full epoch\n if args.load_params:\n ckpt_file = args.save_dir + '/params_' + args.data_set + '.ckpt'\n print('restoring parameters from', ckpt_file)\n saver.restore(sess, ckpt_file)\n else:\n print('initializing the model...')\n sess.run(initializer)\n feed_dict = make_feed_dict(train_data.next(args.init_batch_size), init=True) # manually retrieve exactly init_batch_size examples\n sess.run(init_pass, feed_dict)\n print('starting training')\n\n # train for one epoch\n train_losses = []\n for d in train_data:\n feed_dict = make_feed_dict(d)\n # forward/backward/update model on each gpu\n lr *= args.lr_decay\n feed_dict.update({ tf_lr: lr })\n sum_, l,_ = sess.run([summary, bits_per_dim, optimizer], feed_dict)\n writer.add_summary(sum_, counter)\n train_losses.append(l)\n\n train_loss_gen = np.mean(train_losses)\n\n # compute likelihood over test data\n test_losses = []\n for d in test_data:\n feed_dict = make_feed_dict(d)\n l = sess.run(bits_per_dim_test, feed_dict)\n test_losses.append(l)\n test_loss_gen = np.mean(test_losses)\n test_bpd.append(test_loss_gen)\n\n test_summary = tf.Summary(value=[\n tf.Summary.Value(tag=\"BPD\", simple_value=test_loss_gen / args.batch_size)])\n test_writer.add_summary(test_summary, counter)\n\n\n # log progress to console\n print(\"Iteration %d, time = %ds, train bits_per_dim = %.4f, test bits_per_dim = %.4f\" % (\n epoch, time.time()-begin, train_loss_gen / args.batch_size, test_loss_gen / args.batch_size))\n sys.stdout.flush()\n\n\n # generate samples from the model\n sample_x = []\n for i in range(args.num_samples):\n sample_x.append(sample_from_model(sess))\n sample_x = np.concatenate(sample_x,axis=0)\n img_tile = plotting.img_tile(sample_x[:100], aspect_ratio=1.0, border_color=1.0, stretch=True)\n img = plotting.plot_img(img_tile, title=args.data_set + ' samples')\n plotting.plt.savefig(os.path.join(args.save_dir,'%s_sample%d.png' % (args.data_set, epoch)))\n plotting.plt.close('all')\n # save params\n saver.save(sess, args.save_dir + '/params_' + args.data_set + '.ckpt')\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":10844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"632652496","text":"from easydict import EasyDict\n\nhopper_medium_cql_default_config = dict(\n env=dict(\n env_id='hopper-medium-v0',\n norm_obs=dict(use_norm=False, ),\n norm_reward=dict(use_norm=False, ),\n collector_env_num=1,\n evaluator_env_num=8,\n use_act_scale=True,\n n_evaluator_episode=8,\n stop_value=6000,\n ),\n policy=dict(\n cuda=True,\n model=dict(\n obs_shape=11,\n action_shape=3,\n twin_critic=True,\n actor_head_type='reparameterization',\n actor_head_hidden_size=256,\n critic_head_hidden_size=256,\n ),\n learn=dict(\n data_path=None,\n train_epoch=30000,\n batch_size=256,\n learning_rate_q=3e-4,\n learning_rate_policy=1e-4,\n learning_rate_alpha=1e-4,\n ignore_done=False,\n target_theta=0.005,\n discount_factor=0.99,\n alpha=0.2,\n reparameterization=True,\n auto_alpha=False,\n lagrange_thresh=-1.0,\n min_q_weight=5.0,\n ),\n collect=dict(\n n_sample=1,\n unroll_len=1,\n data_type='d4rl',\n ),\n command=dict(),\n eval=dict(evaluator=dict(eval_freq=500, )),\n other=dict(replay_buffer=dict(replay_buffer_size=2000000, ), ),\n ),\n)\n\nhopper_medium_cql_default_config = EasyDict(hopper_medium_cql_default_config)\nmain_config = hopper_medium_cql_default_config\n\nhopper_medium_cql_default_create_config = dict(\n env=dict(\n type='d4rl',\n import_names=['dizoo.d4rl.envs.d4rl_env'],\n ),\n env_manager=dict(type='base'),\n policy=dict(\n type='cql',\n import_names=['ding.policy.cql'],\n ),\n replay_buffer=dict(type='naive', ),\n)\nhopper_medium_cql_default_create_config = EasyDict(hopper_medium_cql_default_create_config)\ncreate_config = hopper_medium_cql_default_create_config\n","sub_path":"dizoo/d4rl/config/hopper_medium_cql_default_config.py","file_name":"hopper_medium_cql_default_config.py","file_ext":"py","file_size_in_byte":1966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"590988463","text":"#! /usr/bin/python\n\nimport numpy as np\n#from scipy import linalg\nimport math\nfrom math import pow,atan2,sqrt,cos,sin,asin,pi\n\n\nclass KF():\n \n # Init fuction for KF\n def __init__(self, A, B, C, R, Q, K):\n\n self.A = A\n self.B = B\n self.C = C\n self.R = R\n self.Q = Q\n self.K = K\n self.I = np.identity(len(A))\n\n #predicted state\n\n pmt_1 = 0.0\n pmt_2 = 0.0\n pmt_3 = 0.0\n pmt_4 = 0.0\n\n self.pmt_ = [[pmt_1],\n [pmt_2],\n [pmt_3],\n [pmt_4]]\n\n #corrected state\n\n mt1 = 0.0\n mt2 = 0.0\n mt3 = 0.0\n mt4 = 0.0\n\n self.mt = [[mt1],\n [mt2],\n [mt3],\n [mt4]]\n\n\n #predicted covariance\n\n pSt_1 = 0.0\n pSt_2 = 0.0\n pSt_3 = 0.0\n pSt_4 = 0.0\n\n self.pSt_ = [[pSt_1,0,0,0],\n [0,pSt_2,0,0],\n [0,0,pSt_3,0],\n [0,0,0,pSt_4]]\n\n #corrected covariance\n\n St1 = 0.0\n St2 = 0.0\n St3 = 0.0\n St4 = 0.0\n\n self.St = [[St1,0,0,0],\n [0,St2,0,0],\n [0,0,St3,0],\n [0,0,0,St4]]\n\n self.z_last = [[0],[0],[0]]\n self.flag1 = 0\n self.flag2 = 0\n self.cont = 0\n\n\n # This function computes the kalman filter its arguments are:\n # mt_ : is the previous state as a result of KF\n # St_ : is the previous Coveriance as a result of KF\n # ut : is the control input vector \n # zt : is the vector of measurments from sensors\n # Q : is the covariance matrix from the sensors\n # dt : is the sample peroid in seconds\n\n def KF_compute(self, mt_, St_, ut, zt, Q, dt):\n #control matrix\n self.B = [[dt,0,0],\n [0,dt,0],\n [0,0,dt]]\t\n #covariance matrix from sensors\n #self.Q = Q\n\n # if zt == self.z_last:\n # self.falg1 = 1\n # if self.flag1\n\n #predict the state Ax+Bu = x' \n self.pmt_ = np.add( np.dot( self.A , mt_ ) , np.dot( self.B , ut ) )\n #predict the covariance matrix\n self.pSt_ = np.add( np.dot( np.dot( self.A , St_ ) , np.transpose(self.A) ) , self.R )\n\n # Step 2: Belief compute and corrective\n # if not (self.flag == 10):\n #determinate the Kalman gain\n self.K = np.dot( np.dot( self.pSt_ , np.transpose(self.C)) , np.linalg.inv( np.add( np.dot( np.dot( self.C , self.pSt_ ) , np.transpose(self.C) ) , self.Q)))\n # cont+=cont\n # print(\"adentro\")\n # else:\n # print(\"afuera\")\n #determinate the corrected state\n self.mt = np.add( self.pmt_ , np.dot( self.K , np.subtract( zt , np.dot( self.C , self.pmt_ ) ) ) )\n #determinate the corrected covariance matrix\n self.St = np.dot( np.subtract( self.I , np.dot( self.K , self.C ) ) , self.pSt_ )\n \n # self.z_last = zt\n #retun KF results: state vector and Covariance matrix\n return [self.mt, self.St]\n\n #this fuction is used to test the model\n def compute(self, mt_, ut, dt):\n #control matrix\n self.B = [[dt,0,0],\n [0,dt,0],\n [0,0,dt]]\n self.mt = np.add( np.dot( self.A , mt_ ) , np.dot( self.B , ut ) )\n\t \n return [self.mt, self.St]\n\n\n#if __name__ == '__main__':\n\n\n","sub_path":"scripts/KF_class/kalman.py","file_name":"kalman.py","file_ext":"py","file_size_in_byte":3813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"519761816","text":"from pyspark.ml.classification import DecisionTreeClassifier\r\nfrom pyspark.ml.evaluation import MulticlassClassificationEvaluator\r\nfrom pyspark.sql import SparkSession\r\nfrom pyspark.ml.classification import RandomForestClassifier\r\n\r\nif __name__ == \"__main__\":\r\n\r\n\r\n spark_session = SparkSession\\\r\n .builder\\\r\n .appName(\"Spark ML Random Forest\")\\\r\n .master(\"local[4]\")\\\r\n .getOrCreate()\r\n\r\n data_frame = spark_session\\\r\n .read\\\r\n .format(\"libsvm\")\\\r\n .load(\"breast-cancer_scale.txt\")\r\n\r\n data_frame.show()\r\n\r\n (training_data, test_data) = data_frame.randomSplit([0.75, 0.25])\r\n\r\n print(\"training data: \" + str(training_data.count()))\r\n training_data.printSchema()\r\n training_data.show()\r\n\r\n print(\"test data: \" + str(test_data.count()))\r\n test_data.printSchema()\r\n test_data.show()\r\n\r\n decision_tree = RandomForestClassifier(labelCol=\"label\", featuresCol=\"features\")\r\n\r\n model = decision_tree.fit(training_data)\r\n\r\n prediction = model.transform(test_data)\r\n prediction.printSchema()\r\n prediction.show()\r\n\r\n prediction\\\r\n .select(\"prediction\", \"label\", \"features\")\\\r\n .show(5)\r\n\r\n # Select (prediction, true label) and compute test error\r\n evaluator = MulticlassClassificationEvaluator(\r\n labelCol=\"label\", predictionCol=\"prediction\", metricName=\"accuracy\")\r\n accuracy = evaluator.evaluate(prediction)\r\n print(\"Accuracy = %g \" % (accuracy))\r\n\r\n spark_session.stop()\r\n","sub_path":"Spark ML/RandomForest.py","file_name":"RandomForest.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"515273136","text":"#\n# Copyright (c) 2017 Juniper Networks, Inc. All rights reserved.\n#\n\n\"\"\"\nVNC management for Mesos\n\"\"\"\n\nimport gevent\nfrom gevent.queue import Empty\nimport requests\nfrom vnc_mesos_config import VncMesosConfig as vnc_mesos_config\nfrom cfgm_common import importutils\nfrom cfgm_common import vnc_cgitb\nfrom cfgm_common.exceptions import *\nfrom cfgm_common.utils import cgitb_hook\nfrom cfgm_common.vnc_amqp import VncAmqpHandle\nfrom vnc_api.vnc_api import *\nfrom pysandesh.sandesh_base import *\nfrom pysandesh.sandesh_logger import *\nfrom pysandesh.gen_py.sandesh.ttypes import SandeshLevel\nfrom cfgm_common.uve.virtual_network.ttypes import *\nfrom sandesh_common.vns.ttypes import Module\nfrom sandesh_common.vns.constants import ModuleNames, Module2NodeType, \\\n NodeTypeNames, INSTANCE_ID_DEFAULT\nfrom pysandesh.connection_info import ConnectionState\nfrom pysandesh.gen_py.process_info.ttypes import ConnectionType as ConnType\nfrom pysandesh.gen_py.process_info.ttypes import ConnectionStatus\n\nclass VncMesos(object):\n \"Class to handle vnc operations\"\n _vnc_mesos = None\n def __init__(self, args=None, logger=None, queue=None):\n self.args = args\n self.logger = logger\n self.queue = queue\n\n \"\"\"Initialize vnc connection\"\"\"\n self.vnc_lib = self._vnc_connect()\n\n # Cache common config.\n self.vnc_mesos_config = vnc_mesos_config(logger=self.logger,\n vnc_lib=self.vnc_lib, args=self.args, queue=self.queue)\n\n # provision cluster\n self._provision_cluster()\n VncMesos._vnc_mesos = self\n\n def connection_state_update(self, status, message=None):\n ConnectionState.update(\n conn_type=ConnType.APISERVER, name='ApiServer',\n status=status, message=message or '',\n server_addrs=['%s:%s' % (self.args.vnc_endpoint_ip,\n self.args.vnc_endpoint_port)])\n # end connection_state_update\n\n def _vnc_connect(self):\n # Retry till API server connection is up\n connected = False\n self.connection_state_update(ConnectionStatus.INIT)\n api_server_list = self.args.vnc_endpoint_ip.split(',')\n while not connected:\n try:\n vnc_lib = VncApi(self.args.auth_user,\n self.args.auth_password, self.args.auth_tenant,\n api_server_list, self.args.vnc_endpoint_port,\n auth_token_url=self.args.auth_token_url)\n connected = True\n self.connection_state_update(ConnectionStatus.UP)\n except requests.exceptions.ConnectionError as e:\n # Update connection info\n self.connection_state_update(ConnectionStatus.DOWN, str(e))\n time.sleep(3)\n except ResourceExhaustionError:\n time.sleep(3)\n return vnc_lib\n\n def _create_project(self, project_name):\n proj_fq_name = vnc_mesos_config.cluster_project_fq_name(project_name)\n proj_obj = Project(name=proj_fq_name[-1], fq_name=proj_fq_name)\n try:\n self.vnc_lib.project_create(proj_obj)\n except RefsExistError:\n proj_obj = self.vnc_lib.project_read(\n fq_name=proj_fq_name)\n return proj_obj\n\n def _create_network(self, vn_name, vn_type, proj_obj,\n ipam_obj, ipam_update, provider=None):\n # Check if the VN already exists.\n # If yes, update existing VN object with k8s config.\n vn_exists = False\n vn = VirtualNetwork(name=vn_name, parent_obj=proj_obj,\n address_allocation_mode='flat-subnet-only')\n try:\n vn_obj = self.vnc_lib.virtual_network_read(\n fq_name=vn.get_fq_name())\n vn_exists = True\n except NoIdError:\n # VN does not exist. Create one.\n vn_obj = vn\n\n # Attach IPAM to virtual network.\n #\n # For flat-subnets, the subnets are specified on the IPAM and\n # not on the virtual-network to IPAM link. So pass an empty\n # list of VnSubnetsType.\n if ipam_update or \\\n not self._is_ipam_exists(vn_obj, ipam_obj.get_fq_name()):\n vn_obj.add_network_ipam(ipam_obj, VnSubnetsType([]))\n\n vn_obj.set_virtual_network_properties(\n VirtualNetworkType(forwarding_mode='l3'))\n\n fabric_snat = False\n if vn_type == 'pod-task-network':\n fabric_snat = True\n\n if not vn_exists:\n if self.args.ip_fabric_forwarding:\n if provider:\n #enable ip_fabric_forwarding\n vn_obj.add_virtual_network(provider)\n elif fabric_snat and self.args.ip_fabric_snat:\n #enable fabric_snat\n vn_obj.set_fabric_snat(True)\n else:\n #disable fabric_snat\n vn_obj.set_fabric_snat(False)\n # Create VN.\n self.vnc_lib.virtual_network_create(vn_obj)\n else:\n self.vnc_lib.virtual_network_update(vn_obj)\n\n vn_obj = self.vnc_lib.virtual_network_read(\n fq_name=vn_obj.get_fq_name())\n\n return vn_obj\n\n def _create_ipam(self, ipam_name, subnets, proj_obj,\n type='flat-subnet'):\n ipam_obj = NetworkIpam(name=ipam_name, parent_obj=proj_obj)\n\n ipam_subnets = []\n for subnet in subnets:\n pfx, pfx_len = subnet.split('/')\n ipam_subnet = IpamSubnetType(subnet=SubnetType(pfx, int(pfx_len)))\n ipam_subnets.append(ipam_subnet)\n if not len(ipam_subnets):\n self.logger.error(\"%s - %s subnet is empty for %s\" \\\n %(self._name, ipam_name, subnets))\n\n if type == 'flat-subnet':\n ipam_obj.set_ipam_subnet_method('flat-subnet')\n ipam_obj.set_ipam_subnets(IpamSubnets(ipam_subnets))\n\n ipam_update = False\n try:\n ipam_uuid = self.vnc_lib.network_ipam_create(ipam_obj)\n ipam_update = True\n except RefsExistError:\n curr_ipam_obj = self.vnc_lib.network_ipam_read(\n fq_name=ipam_obj.get_fq_name())\n ipam_uuid = curr_ipam_obj.get_uuid()\n if type == 'flat-subnet' and not curr_ipam_obj.get_ipam_subnets():\n self.vnc_lib.network_ipam_update(ipam_obj)\n ipam_update = True\n\n return ipam_update, ipam_obj, ipam_subnets\n\n def _is_ipam_exists(self, vn_obj, ipam_fq_name, subnet=None):\n curr_ipam_refs = vn_obj.get_network_ipam_refs()\n if curr_ipam_refs:\n for ipam_ref in curr_ipam_refs:\n if ipam_fq_name == ipam_ref['to']:\n if subnet:\n # Subnet is specified.\n # Validate that we are able to match subnect as well.\n if len(ipam_ref['attr'].ipam_subnets) and \\\n subnet == ipam_ref['attr'].ipam_subnets[0].subnet:\n return True\n else:\n # Subnet is not specified.\n # So ipam-fq-name match will suffice.\n return True\n return False\n\n def _allocate_fabric_snat_port_translation_pools(self):\n global_vrouter_fq_name = \\\n ['default-global-system-config', 'default-global-vrouter-config']\n try:\n global_vrouter_obj = \\\n self.vnc_lib.global_vrouter_config_read(\n fq_name=global_vrouter_fq_name)\n except NoIdError:\n return\n snat_port_range = PortType(start_port = 56000, end_port = 57023)\n port_pool_tcp = PortTranslationPool(\n protocol=\"tcp\", port_count='1024', port_range=snat_port_range)\n snat_port_range = PortType(start_port = 57024, end_port = 58047)\n port_pool_udp = PortTranslationPool(\n protocol=\"udp\", port_count='1024', port_range=snat_port_range)\n port_pools = PortTranslationPools([port_pool_tcp, port_pool_udp])\n global_vrouter_obj.set_port_translation_pools(port_pools)\n try:\n self.vnc_lib.global_vrouter_config_update(global_vrouter_obj)\n except NoIdError:\n pass\n\n def _provision_cluster(self):\n ''' Pre creating default project before namespace add event.'''\n proj_obj = self._create_project('default')\n\n # Allocate fabric snat port translation pools.\n self._allocate_fabric_snat_port_translation_pools()\n\n ip_fabric_fq_name = vnc_mesos_config.cluster_ip_fabric_network_fq_name()\n ip_fabric_vn_obj = self.vnc_lib. \\\n virtual_network_read(fq_name=ip_fabric_fq_name)\n\n # Create ip-fabric IPAM.\n ipam_name = vnc_mesos_config.cluster_name() + '-ip-fabric-ipam'\n ip_fabric_ipam_update, ip_fabric_ipam_obj, ip_fabric_ipam_subnets = \\\n self._create_ipam(ipam_name, self.args.ip_fabric_subnets, proj_obj)\n self._cluster_ip_fabric_ipam_fq_name = ip_fabric_ipam_obj.get_fq_name()\n\n # Create Pod Task IPAM.\n ipam_name = vnc_mesos_config.cluster_name() + '-pod-task-ipam'\n pod_task_ipam_update, pod_task_ipam_obj, pod_task_ipam_subnets = \\\n self._create_ipam(ipam_name, self.args.pod_task_subnets, proj_obj)\n # Cache cluster pod ipam name.\n # This will be referenced by ALL pods that are spawned in the cluster.\n self._cluster_pod_task_ipam_fq_name = pod_task_ipam_obj.get_fq_name()\n\n ''' Create a default pod-task-network. '''\n if self.args.ip_fabric_forwarding:\n cluster_pod_task_vn_obj = self._create_network(\n vnc_mesos_config.cluster_default_pod_task_network_name(),\n 'pod-task-network', proj_obj,\n ip_fabric_ipam_obj, ip_fabric_ipam_update, ip_fabric_vn_obj)\n else:\n cluster_pod_vn_obj = self._create_network(\n vnc_mesos_config.cluster_default_pod_task_network_name(),\n 'pod-task-network', proj_obj,\n pod_task_ipam_obj, pod_task_ipam_update, ip_fabric_vn_obj)\n\n def process_q_event(self, event):\n \"\"\"Process ADD/DEL event\"\"\"\n obj_labels = MesosCniLabels(event, self.logger)\n if obj_labels.operation == 'ADD':\n self.logger.info('Add request.')\n elif obj_labels.operation == 'DEL':\n self.logger.info('Delete request')\n else:\n self.logger.error('Invalid operation')\n\n def vnc_process(self):\n \"\"\"Process event from the work queue\"\"\"\n while True:\n try:\n event = self.queue.get()\n self.logger.info(\"VNC: Handle CNI Data for ContainerId: {}.\"\n .format(event['cid']))\n print (\"VNC: Handle CNI Data for ContainerId: {}.\"\n .format(event['cid']))\n self.process_q_event(event)\n except Empty:\n gevent.sleep(0)\n\n\nclass MesosCniLabels(object):\n \"\"\"Handle label processing\"\"\"\n def __init__(self, event, logger):\n \"\"\"Initialize all labels to default vaule\"\"\"\n self.logger = logger\n self.operation = event['cmd']\n self.task_uuid = event['cid']\n self.domain_name = 'default-domain'\n self.project_name = 'mesos-system'\n self.cluster_name = ''\n self.networks = ''\n self.security_groups = ''\n self.floating_ips = ''\n self.app_subnets = '10.10.10.0/24'\n self._extract_values(event)\n\n def _extract_values(self, event):\n \"\"\"Extract values from args\"\"\"\n if 'app_subnets' in event.keys():\n self.app_subnets = event['app_subnets']\n labels = event['labels']\n \"\"\"Extract values from label\"\"\"\n if 'domain-name' in labels.keys():\n self.domain_name = labels['domain-name']\n if 'project-name' in labels.keys():\n self.project_name = labels['project-name']\n if 'networks' in labels.keys():\n self.networks = labels['networks']\n if 'app_subnets' in labels.keys():\n self.app_subnets = labels['network-subnets']\n if 'security-groups' in labels.keys():\n self.security_groups = labels['security-groups']\n if 'floating-ips' in labels.keys():\n self.floating_ips = labels['floating-ips']\n if 'cluster-name' in labels.keys():\n self.cluster_name = labels['cluster-name']\n self.logger.info(\"Debug:{}{}{}{}{}{}{}\"\n .format(self.domain_name, self.project_name,\n self.networks, self.security_groups,\n self.floating_ips, self.cluster_name,\n self.app_subnets))\n self.logger.info(\"Extracting labels done\")\n\n","sub_path":"src/container/mesos-manager/mesos_manager/vnc/vnc_mesos.py","file_name":"vnc_mesos.py","file_ext":"py","file_size_in_byte":12947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"609114441","text":"#Time Complexity=O(amount*n),\n#SC-O(amount)\n#Ran successfully in Leetcode:Yes\n#Same procedure as followed for previous COin chane problem . Here we do not calculate the min(dp[i],dp[i-coin], here we just increment the dp[amount]by dp[amount-coin]).And return the value stored at dp[amount]\n\nclass Solution:\n def change(self, amount: int, coins: List[int]) -> int:\n\n dp = [0]*(amount+1)\n dp[0] = 1\n for coin in coins:\n for i in range( 1,amount+1):\n if i>=coin:\n dp[i] += dp[i-coin]\n # dp[i]=dp[i]\n # print(dp)\n return dp[-1] \n \n","sub_path":"change.py","file_name":"change.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"77524776","text":"import numpy as np\nfrom numpy import clip\nfrom copy import copy\n\nfrom .._base_layer import Layer\nfrom ..._vispy.scene.visuals import Image as ImageNode\n\nfrom ...util.colormaps import colormaps\nfrom ...util.event import Event\n\nfrom .._register import add_to_viewer\n\nfrom .view import QtLabelsLayer\n\n\n@add_to_viewer\nclass Labels(Layer):\n \"\"\"Labels (or segmentation) layer.\n\n An image layer where every pixel contains an integer ID corresponding\n to the region it belongs to.\n\n Parameters\n ----------\n image : np.ndarray\n Image data.\n meta : dict, optional\n Image metadata.\n multichannel : bool, optional\n Whether the image is multichannel. Guesses if None.\n name : str, keyword-only\n Name of the layer.\n num_colors : int, optional\n Number of unique colors to use. Default used if not given.\n **kwargs : dict\n Parameters that will be translated to metadata.\n \"\"\"\n def __init__(self, label_image, meta=None, *, name=None, num_colors=256, **kwargs):\n if name is None and meta is not None:\n if 'name' in meta:\n name = meta['name']\n\n visual = ImageNode(None, method='auto')\n super().__init__(visual, name)\n self.events.add(colormap=Event)\n\n self.seed = 0.5\n self._raw_image = label_image\n self._max_label = np.max(label_image)\n self._image = colormaps._low_discrepancy_image(self._raw_image, self.seed)\n self._meta = meta\n self.interpolation = 'nearest'\n self.colormap_name = 'random'\n self.colormap = colormaps.label_colormap(num_colors)\n self.opacity = 0.7\n\n\n # update flags\n self._need_display_update = False\n self._need_visual_update = False\n\n self._qt_properties = QtLabelsLayer(self)\n\n self._node.clim = [0., 1.]\n self.events.colormap()\n\n def new_colormap(self):\n self.seed = np.random.rand()\n self._image = colormaps._low_discrepancy_image(self._raw_image, self.seed)\n self.refresh()\n \n\n def label_color(self, label):\n \"\"\"Return the color corresponding to a specific label.\"\"\"\n return self.colormap.map(colormaps._low_discrepancy_image(np.array([label]), self.seed))\n\n @property\n def image(self):\n \"\"\"np.ndarray: Image data.\n \"\"\"\n return self._image\n\n @image.setter\n def image(self, image):\n self._image = image\n self.refresh()\n\n @property\n def meta(self):\n \"\"\"dict: Image metadata.\n \"\"\"\n return self._meta\n\n @meta.setter\n def meta(self, meta):\n self._meta = meta\n self.refresh()\n\n @property\n def data(self):\n \"\"\"tuple of np.ndarray, dict: Image data and metadata.\n \"\"\"\n return self.image, self.meta\n\n @data.setter\n def data(self, data):\n self._image, self._meta = data\n self.refresh()\n\n def _get_shape(self):\n return self.image.shape\n\n def _update(self):\n \"\"\"Update the underlying visual.\n \"\"\"\n if self._need_display_update:\n self._need_display_update = False\n\n self.viewer.dims._child_layer_changed = True\n self.viewer.dims._update()\n\n self._node._need_colortransform_update = True\n self._set_view_slice(self.viewer.dims.indices)\n\n if self._need_visual_update:\n self._need_visual_update = False\n self._node.update()\n\n def _refresh(self):\n \"\"\"Fully refresh the underlying visual.\n \"\"\"\n self._need_display_update = True\n self._update()\n\n def _slice_image(self, indices, image=None):\n \"\"\"Determines the slice of image given the indices.\n\n Parameters\n ----------\n indices : sequence of int or slice\n Indices to slice with.\n image : array, optional\n The image to slice. Defaults to self._image if None.\n\n Returns\n -------\n sliced : array or value\n The requested slice.\n \"\"\"\n if image is None:\n image = self._image\n ndim = self.ndim\n indices = list(indices)[:ndim]\n\n for dim in range(len(indices)):\n max_dim_index = self.image.shape[dim] - 1\n\n try:\n if indices[dim] > max_dim_index:\n indices[dim] = max_dim_index\n except TypeError:\n pass\n\n return image[tuple(indices)]\n\n def _set_view_slice(self, indices):\n \"\"\"Sets the view given the indices to slice with.\n\n Parameters\n ----------\n indices : sequence of int or slice\n Indices to slice with.\n \"\"\"\n sliced_image = self._slice_image(indices)\n self._node.set_data(sliced_image)\n\n self._need_visual_update = True\n self._update()\n\n @property\n def method(self):\n \"\"\"string: Selects method of rendering image in case of non-linear\n transforms. Each method produces similar results, but may trade\n efficiency and accuracy. If the transform is linear, this parameter\n is ignored and a single quad is drawn around the area of the image.\n\n * 'auto': Automatically select 'impostor' if the image is drawn\n with a nonlinear transform; otherwise select 'subdivide'.\n * 'subdivide': ImageVisual is represented as a grid of triangles\n with texture coordinates linearly mapped.\n * 'impostor': ImageVisual is represented as a quad covering the\n entire view, with texture coordinates determined by the\n transform. This produces the best transformation results, but may\n be slow.\n \"\"\"\n return self._node.method\n\n @method.setter\n def method(self, method):\n self._node.method = method\n\n def get_value(self, position, indices):\n \"\"\"Returns coordinates, values, and a string for a given mouse position\n and set of indices.\n\n Parameters\n ----------\n position : sequence of two int\n Position of mouse cursor in canvas.\n indices : sequence of int or slice\n Indices that make up the slice.\n\n Returns\n ----------\n coord : sequence of int\n Position of mouse cursor in data.\n label : int\n Value of the label image at the coord.\n msg : string\n String containing a message that can be used as\n a status update.\n \"\"\"\n transform = self._node.canvas.scene.node_transform(self._node)\n pos = transform.map(position)\n pos = [clip(pos[1], 0, self.shape[0]-1), clip(pos[0], 0,\n self.shape[1]-1)]\n coord = copy(indices)\n coord[0] = int(pos[0])\n coord[1] = int(pos[1])\n label = self._slice_image(coord, image=self._raw_image)\n msg = f'{coord}, {self.name}, label {label}'\n return coord, label, msg\n\n def on_mouse_move(self, event):\n \"\"\"Called whenever mouse moves over canvas.\n \"\"\"\n if event.pos is None:\n return\n coord, value, msg = self.get_value(event.pos, self.viewer.dims.indices)\n self.status = msg\n","sub_path":"napari/layers/_labels_layer/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":7264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"101932594","text":"\"\"\"\nGiven an array of integers nums.\n\nA pair (i,j) is called good if nums[i] == nums[j] and i < j.\n\nReturn the number of good pairs.\n\"\"\"\n\n#Brute Force Solution O(n^2)\ndef numIdenticalPairs(self, nums: List[int]) -> int:\n pairs = 0\n for bb in range(len(nums)-1, 0, -1):\n for ff in range(bb):\n if nums[bb]==nums[ff]:\n pairs += 1\n return pairs\n\n#Notes: Others solved using a dictionary to store occurences of each integer.\n#Then it is only a matter of calculating the number of pairs for a given frequency\n#This enhanced solution runs in only O(n) time\n\n","sub_path":"Arrays/numIdenticalPairs.py","file_name":"numIdenticalPairs.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"21357067","text":"# import libraries\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output\nimport plotly.graph_objs as go\nimport pandas as pd\n\n# import data\ndf = pd.read_csv(\"FAO.csv\", encoding=\"iso-8859-1\")\n# get column names of production years\nyear_col_names = list(df.columns[10:])\n\n# set external stylesheets and initiate app instance\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\n\n# configure app layout\napp.layout = html.Div([\n html.Div([\n html.H1(\"Worldwide Food & Feed Production\", style={\"text-align\": \"center\"})\n ]),\n\n # dropdown for country\n html.Div([\n html.Label(\"Country\"),\n dcc.Dropdown(\n id=\"selected-country\",\n options=[{\"label\": i, \"value\": i} for i in df.Area.unique()],\n value=\"Afghanistan\"\n )], style={\"width\": \"30%\", \"display\": \"inline-block\"}),\n\n # dropdown for item\n html.Div([\n html.Label(\"Item\"),\n dcc.Dropdown(\n id=\"selected-item\",\n options=[{\"label\": i, \"value\": i} for i in df.Item.unique()],\n value=\"Wheat and products\"\n )], style={\"width\": \"30%\", \"display\": \"inline-block\"}),\n\n # dropdown for element\n html.Div([\n html.Label(\"Element\"),\n dcc.Dropdown(id=\"selected-element\")\n ], style={\"width\": \"30%\", \"display\": \"inline-block\"}),\n\n # graph element to be populated\n html.Div([\n dcc.Graph(id=\"graph-element\")\n ], style={\"width\": \"100%\", \"display\": \"inline-block\"}),\n])\n\n\n# update element dropdown because some choices don't have both food and feed\n@app.callback(\n Output(\"selected-element\", \"options\"),\n [Input(\"selected-country\", \"value\"),\n Input(\"selected-item\", \"value\")]\n)\ndef update_element_choices(selected_country, selected_item):\n # filter df\n filtered_df = df[(df[\"Area\"] == selected_country) &\n (df[\"Item\"] == selected_item)]\n # return choices\n return [\n {\"label\": i, \"value\": i} for i in filtered_df.Element.unique()\n ]\n\n# return a default value to element dropdown\n@app.callback(\n Output(\"selected-element\", \"value\"),\n [Input(\"selected-element\", \"options\")]\n)\ndef update_element_value(available_options):\n return available_options[0][\"value\"]\n\n# update graph\n@app.callback(\n Output(\"graph-element\", \"figure\"),\n [Input(\"selected-country\", \"value\"),\n Input(\"selected-item\", \"value\"),\n Input(\"selected-element\", \"value\")]\n)\ndef update_graph(selected_country, selected_item, selected_element):\n # filter dataframe\n filtered_df = df[(df[\"Area\"] == selected_country) &\n (df[\"Item\"] == selected_item) &\n (df[\"Element\"] == selected_element)]\n\n # return graph parameters\n return {\n \"data\": [\n go.Bar(\n x=year_col_names,\n y=filtered_df[year_col_names].values.tolist()[0]\n )\n ],\n\n \"layout\": go.Layout(\n xaxis={\"title\": \"Production Years\"},\n yaxis={\"title\": \"1000 Tonnes\"}\n )\n }\n\nif __name__ == \"__main__\":\n app.run_server(debug=True)","sub_path":"my-apps/app_food_production.py","file_name":"app_food_production.py","file_ext":"py","file_size_in_byte":3223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"510747782","text":"import cv2\nimport numpy as np\nfrom collections import deque\n\n\nclass BackgroundExtraction:\n def __init__(self, xwidth, yheight, xyscale, maxlen=10):\n self.maxlen = maxlen\n self.scale = xyscale\n self.width = xwidth\n self.height = yheight # // scale\n self.buffer = deque(maxlen=maxlen)\n self.background = None\n\n def calculate_background(self):\n self.background = np.zeros((self.height, self.width), dtype='float32')\n for item in self.buffer:\n self.background += item\n self.background /= len(self.buffer)\n\n def update_background(self, old_frame, new_frame):\n self.background -= old_frame / self.maxlen\n self.background += new_frame / self.maxlen\n\n def update_frame(self, gframe):\n if len(self.buffer) < self.maxlen:\n self.buffer.append(gframe)\n self.calculate_background()\n else:\n old_frame = self.buffer.popleft()\n self.buffer.append(gframe)\n self.update_background(old_frame, gframe)\n\n def get_background(self):\n return self.background.astype('uint8')\n\n def apply(self, frame_cam):\n down_scale = cv2.resize(frame_cam, (self.width, self.height))\n gray = cv2.cvtColor(down_scale, cv2.COLOR_BGR2GRAY)\n gray = cv2.GaussianBlur(gray, (5, 5), 0)\n\n self.update_frame(gray)\n abs_diff = cv2.absdiff(bg_buffer.get_background(), gray) # ABSOLUTE DIFF of FRAMES\n _, ad_mask = cv2.threshold(abs_diff, 15, 255, cv2.THRESH_BINARY) # MASK using THRESHOLD\n return ad_mask\n\n\nclass Game:\n def __init__(self, xwidth, yheight, size=50):\n self.width = xwidth\n self.height = yheight\n self.size = size\n self.logo = cv2.imread(\"ball_round.png\")\n self.logo = cv2.resize(self.logo, (self.size, self.size))\n gray = cv2.cvtColor(self.logo, cv2.COLOR_BGR2GRAY)\n self.mask = cv2.threshold(gray, 1, 255, cv2.THRESH_BINARY)[1]\n self.x = np.random.randint(0, self.width - self.size) # Insert OBJECT at RANDOM position on X-AXIS\n self.y = 100\n self.speed = np.random.randint(10, 20)\n self.score = 0\n self.flag = 0 # Going UP or DOWN flag\n\n def update_frame(self, gframe):\n roi = gframe[self.y:self.y + self.size, self.x:self.x + self.size]\n roi[np.where(self.mask)] = 0\n roi += self.logo\n\n def update_position(self, mask):\n if self.flag:\n self.y -= self.speed\n else:\n self.y += self.speed\n\n # Object HITS Bottom of Screen\n if self.y + self.size >= self.height:\n self.score = 0 # DEDUCT SCORE if OBJECT FALLS\n self.speed = np.random.randint(10, 30)\n self.y = 0\n self.x = np.random.randint(0, self.width - self.size)\n self.flag = 1\n\n # Object HITs TOP of Screen\n if self.y <= 0:\n self.flag = 0\n self.speed = np.random.randint(10, 30)\n self.x = np.random.randint(0, self.width - self.size)\n self.y = 0\n self.score += 1\n\n roi = mask[self.y:self.y + self.size, self.x:self.x + self.size] # Region Of Interest\n check = np.any(roi[np.where(self.mask)]) # CHECK Collision\n\n if check: # ADD SCORE if OBJECT CAUGHT\n self.flag = 1 # GO UPWARDS\n\n return check\n\n\ncap = cv2.VideoCapture(0)\nwidth = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\nheight = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\nscale = 1\n\n# cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)\n# cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)\n\nbg_buffer = BackgroundExtraction(width, height, scale, maxlen=5)\ngame = Game(width, height)\n\nwhile True:\n # Reading, Flipping the frame\n _, frame = cap.read()\n frame = cv2.flip(frame, 1)\n\n # Processing the frame\n fg_mask = bg_buffer.apply(frame) # Calculate MASK\n caught = game.update_position(fg_mask)\n game.update_frame(frame)\n\n text = f\"Score: {game.score-1}\"\n cv2.putText(frame, text, (10, 30), cv2.FONT_HERSHEY_PLAIN, 1.0, (0, 0, 255), 2)\n\n cv2.imshow(\"FG Mask\", fg_mask)\n cv2.imshow(\"Webcam\", frame)\n\n if cv2.waitKey(1) == ord('q'):\n break\n\n\ncap.release()\ncv2.destroyAllWindows()\n","sub_path":"OpenCVGame/opencv_bounce_logo.py","file_name":"opencv_bounce_logo.py","file_ext":"py","file_size_in_byte":4340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"646923098","text":"import matplotlib.pyplot as plt\nimport pkg_resources\nimport numpy as np\nfrom ast import literal_eval\nfrom .taxipoint import point\n\n\n__all__ = ['district', 'plot_seoul','plot']\n\n\ndistrict_file = pkg_resources.resource_stream(__name__,\"district.DAT\")\ndist_position = []#dist_pos\ndist_name = []#fname\ndist_id = []#fid\n\n\n\nclass dist:\n id = []\n name = []\n position = []\n\n def __init__(self):\n self.index = None\n\n def __call__(self, key):\n '''In old version, plot some district or seoul is somehow hard.\n So, Here is Solution. Only need is typing name or\n id or number of order. then this instance will give you proper things.'''\n try:\n key = int(key)\n except:\n for n in dist.name:\n if key in n:\n ret = dist.name.index(n)\n return self.set(ret)\n raise KeyError('Wrong input')\n ret = dist.id.index(key)\n return self.set(ret)\n\n def __repr__(self):\n return \"\".format(dist.id[self.index],dist.name[self.index])\n\n def __getitem__(self, key):\n return self.set(key)\n\n def get_list(self):\n di = {}\n for i,j in zip(dist.id, dist.name):\n di[j]=i\n return di\n\n def set(self, key):\n if self.index == key:\n return self\n if key>=25:\n raise KeyError(\"Out of range.\")\n self.index = key\n self.id = dist.id[self.index]\n self.name = dist.name[self.index]\n self.x = [i.x for i in self.position[key]]\n self.y = [i.y for i in self.position[key]]\n return self\n\n def plot(self, *arg, **kwarg):\n plt.plot(self.x, self.y, *arg,**kwarg)\n\ndistrict = dist()\n\nfor i in range(25):\n dist.id.append(int(district_file.readline().decode()))\n dist.name.append(district_file.readline().decode(\"utf-8\").split()[0])\n position = district_file.readline().decode().split()\n dpos = []\n for pos in position:\n #print(pos.split(\",\"))\n dpos.append(point(pos.split(\",\"), ctype = int))\n dist.position.append(dpos)\n\ndist_max = max([len(comp) for comp in dist.position])\nseoul = np.zeros([dist_max,25,2])\n\nfor i in range(dist_max):\n for j in range(25):\n try:\n seoul[i][j] = np.array([dist.position[j][i].x,dist.position[j][i].y])\n except:\n seoul[i][j] = np.array([None,None])\nseoul_X = seoul[:,:,0]\nseoul_Y = seoul[:,:,1]\n\nplot = lambda taxi,*arg,**kwarg: plt.scatter(taxi['x'],taxi['y'],*arg,**kwarg)\n\ndef plot_seoul(*arg,**kwarg):\n plt.plot(seoul_X, seoul_Y,*arg,**kwarg)\n","sub_path":"taxidata/core/lib/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":2631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"430810626","text":"class PhoenixActors:\n actorsTable = None\n photosTable = None\n actorsNum = 0\n def __init__(self):\n self.actorsTable = [None] * 100\n self.photosTable = [None] * 100\n self.actorsNum = 0\n def addActor(self,newActor,newPhoto):\n self.actorsTable[self.actorsNum] = newActor\n self.photosTable[self.actorsNum] = newPhoto\n self.actorsNum = self.actorsNum + 1\n def clearActors(self):\n self.actorsNum = 0\n def processActors(self,metadata):\n actorsProcessed = 0\n while actorsProcessed < self.actorsNum:\n skip = False\n # Save the potentional new Actor or Actress to a new variable, replace   with a true space, and strip off any surrounding whitespace\n newActor = self.actorsTable[actorsProcessed].replace(\"\\xc2\\xa0\", \" \").strip()\n newPhoto = self.photosTable[actorsProcessed].strip()\n\n ##### Skip an actor completely; this could be used to filter out male actors if desired\n if \"Bad Name\" == newActor:\n skip = True\n\n ##### Replace by actor name; for actors that have different aliases in the industry\n if \"Josephine\" == newActor or \"Conny\" == newActor or \"Conny Carter\" == newActor or \"Connie\" == newActor:\n newActor = \"Connie Carter\"\n if \"Doris Ivy\" == newActor:\n newActor = \"Gina Gerson\"\n if \"Anjelica\" == newActor or \"Ebbi\" == newActor or \"Abby H\" == newActor or \"Katherine A\" == newActor:\n newActor = \"Krystal Boyd\"\n if \"Nathaly\" == newActor or \"Nathalie Cherie\" == newActor:\n newActor = \"Nathaly Cherie\"\n\n ##### Replace by site + actor; use when an actor just has an alias or abbreviated name on one site\n if metadata.studio == \"21Sextury\" and \"Abbie\" == newActor:\n newActor = \"Krystal Boyd\"\n if metadata.studio == \"Babes\" and \"Angelica\" == newActor:\n newActor = \"Krystal Boyd\"\n if metadata.studio == \"LegalPorno\" and \"Abby\" == newActor:\n newActor = \"Krystal Boyd\"\n if metadata.studio == \"Joymii\":\n if \"Valentina\" in newActor:\n newActor == \"Valentina Nappi\"\n if newActor == \"Gina G.\":\n newActor = \"Gina Gerson\"\n if newActor == \"Tasha R.\":\n newActor = \"Tasha Reign\"\n if newActor == \"Piper P.\":\n newActor = \"Piper Perri\"\n if newActor == \"Lara\":\n newActor = \"Dido Angel\"\n if newActor == \"Cindy L.\":\n newActor = \"Cindy Carson\"\n if newActor == \"Denisa\":\n newActor == \"Denisa Heaven\"\n if newActor == \"Abigail\":\n newActor = \"Abigaile Johnson\"\n\n if not skip:\n if newPhoto == '':\n newPhoto = actorDBfinder(newActor)\n Log(\"Actor: \"+newActor+\" \"+newPhoto)\n\n role = metadata.roles.new()\n role.name = newActor\n role.photo = newPhoto\n actorsProcessed = actorsProcessed + 1\n\n# https://www.indexxx.com/models/59558/anjelica-1/\n\n# For sites without a proper actor profile picture, this method looks in external databases based on actorName \ndef actorDBfinder(actorName):\n try:\n databaseName = \"AdultDVDEmpire\"\n actorsearch = HTML.ElementFromURL(\"https://www.adultdvdempire.com/performer/search?q=\" + actorName.replace(' ','%20'))\n actorPageURL = actorsearch.xpath('//div[@class=\"col-xs-6 col-sm-3 grid-item grid-item-performer grid-item-performer-145\"]/a')[0].get(\"href\")\n actorPageURL = \"https://www.adultdvdempire.com\" + actorPageURL\n actorPage = HTML.ElementFromURL(actorPageURL)\n actorPhotoURL = actorPage.xpath('//a[@class=\"fancy headshot\"]')[0].get(\"href\")\n Log(actorName + \" found in \" + databaseName)\n Log(\"PhotoURL: \" + actorPhotoURL)\n except:\n try:\n databaseName = \"Boobpedia\"\n # Code Removed - website has standardized actor page\n # searchURL = \"http://www.boobpedia.com/wiki/index.php?title=Special%3ASearch&profile=default&search=\" + actorName.replace(' ', '+') + \"&fulltext=Search\"\n # Log(databaseName + \"-searchURL: \" + searchURL)\n # actorSearch = HTML.ElementFromURL(searchURL)\n # actorPageURL = actorSearch.xpath('//div[@class=\"mw-search-result-heading\"]/a')[0].get(\"href\")\n # actorPageURL = \"http://www.boobpedia.com\" + actorPageURL\n actorPageURL = \"http://www.boobpedia.com/boobs/\" + actorName.lower().replace(\" \", \"_\")\n # Log(databaseName + \"-PageURL: \" + actorPageURL)\n actorPage = HTML.ElementFromURL(actorPageURL)\n actorPhotoURL = actorPage.xpath('//table[@class=\"infobox\"]//a[@class=\"image\"]//img')[0].get(\"src\")\n actorPhotoURL = \"http://www.boobpedia.com\" + actorPhotoURL\n Log(actorName + \" found in \" + databaseName)\n Log(\"PhotoURL: \" + actorPhotoURL)\n except:\n try:\n databaseName = \"Babes and Stars\"\n # searchURL = \"http://www.babesandstars.com/search/?t=models&q=\" + actorName.replace(' ','+')\n # Log(databaseName + \"-searchURL: \" + searchURL)\n # actorSearch = HTML.ElementFromURL(searchURL)\n # actorPageURL = actorSearch.xpath('//div[contains(@class,\"thumb\")]//a')[0].get(\"href\")\n actorPageURL = \"http://www.babesandstars.com/\" + actorName[0:1] + \"/\" + actorName.lower().replace(\" \",\"-\") +\"/\"\n actorPage = HTML.ElementFromURL(actorPageURL)\n actorPhotoURL = actorPage.xpath('//div[@class=\"profile\"]//div[@class=\"thumb\"]/img')[0].get(\"src\")\n Log(actorName + \" found in \" + databaseName)\n Log(\"PhotoURL: \" + actorPhotoURL)\n except:\n try:\n databaseName = \"IAFD\"\n searchURL = \"http://www.iafd.com/results.asp?searchtype=comprehensive&searchstring=\" + actorName.replace(' ', '+')\n actorSearch = HTML.ElementFromURL(searchURL)\n actorPageURL = actorSearch.xpath('//table[@id=\"tblFem\"]//tbody//a')[0].get(\"href\")\n actorPageURL = \"http://www.iafd.com\" + actorPageURL\n actorPage = HTML.ElementFromURL(actorPageURL)\n actorPhotoURL = actorPage.xpath('//div[@id=\"headshot\"]//img')[0].get(\"src\")\n Log(actorName + \" found in \" + databaseName)\n Log(\"PhotoURL: \" + actorPhotoURL)\n except:\n try:\n databaseName = \"Babepedia\"\n # searchURL = \"https://www.babepedia.com/search/\" + actorName.replace(' ', '%20')\n # Log(databaseName + \"-searchURL: \" + searchURL)\n # actorSearch = HTML.ElementFromURL(searchURL)\n # actorPageURL = actorSearch.xpath('//div[contains(@class,\"thumbshot\")]//a')[0].get(\"href\")\n # actorPageURL = \"http://www.babepedia.com\" + actorPageURL\n # actorPageURL = \"http://www.babepedia.com/babe/\" + actorName.lower().replace(\" \", \"_\")\n # actorPage = HTML.ElementFromURL(actorPageURL)\n # actorPhotoURL = actorPage.xpath('//div[@id=\"profimg\"]//a')[0].get(\"href\")\n # actorPhotoURL = \"http://www.babepedia.com\" + actorPhotoURL\n actorPhotoURL = \"http://www.babepedia.com/pics/\" + actorName.title().replace(\" \", \"%20\") + \".jpg\"\n Log(actorName + \" found in \" + databaseName)\n Log(\"PhotoURL: \" + actorPhotoURL)\n except:\n Log(actorName + \"not found.\")\n actorPhotoURL = \"\"\n return actorPhotoURL\n","sub_path":"Contents/Code/PAactors.py","file_name":"PAactors.py","file_ext":"py","file_size_in_byte":8051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"31313528","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jan 11 20:22:50 2020\n\n@author: Iikka\n\"\"\"\n\nimport tensorflow as tf\nfrom tensorflow.contrib import lite\nfrom tensorflow import keras\nimport numpy as np\n\n\nfrom __future__ import print_function\nimport keras\nfrom keras.datasets import cifar10\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nimport os\n\nbatch_size = 32\nnum_classes = 10\nepochs = 1\ndata_augmentation = True\nnum_predictions = 20\nsave_dir = os.path.join(os.getcwd(), 'saved_models')\nmodel_name = 'keras_cifar10_trained_model.h5'\n\n# The data, split between train and test sets:\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\n\n# Convert class vectors to binary class matrices.\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nmodel = Sequential()\nmodel.add(Conv2D(32, (3, 3), padding='same',\n input_shape=x_train.shape[1:]))\nmodel.add(Activation('relu'))\nmodel.add(Conv2D(32, (3, 3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(64, (3, 3), padding='same'))\nmodel.add(Activation('relu'))\nmodel.add(Conv2D(64, (3, 3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Flatten())\nmodel.add(Dense(512))\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(num_classes))\nmodel.add(Activation('softmax'))\n\n# initiate RMSprop optimizer\nopt = keras.optimizers.RMSprop(lr=0.0001, decay=1e-6)\n\n# Let's train the model using RMSprop\nmodel.compile(loss='categorical_crossentropy',\n optimizer=opt,\n metrics=['accuracy'])\n\nx_train = x_train.astype('float32')\nx_test = x_test.astype('float32')\nx_train /= 255\nx_test /= 255\n\n\nmodel.fit(x_train, y_train,\n\t\t batch_size=batch_size,\n\t\t epochs=epochs,\n\t\t validation_data=(x_test, y_test),\n\t\t shuffle=True)\n\n\nconverter = lite.TFLiteConverter.from_keras_model(model)\ntflite_model = converter.convert()\nopen(\"tflite_model.tflite\", \"wb\").write(tflite_model)","sub_path":"lite_test.py","file_name":"lite_test.py","file_ext":"py","file_size_in_byte":2327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"330181025","text":"# Adjacency matrix representation of graphs\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport math\r\nfrom scipy.interpolate import interp1d\r\nimport graph_AL as g_AL\r\nimport graph_EL as g_EL\r\n\r\nclass Graph:\r\n # Constructor\r\n def __init__(self, vertices, weighted=False, directed = False):\r\n self.am = np.zeros((vertices,vertices),dtype=int) - 1\r\n self.weighted = weighted\r\n self.directed = directed\r\n self.representation = 'AM'\r\n \r\n def BFS(self):\r\n frontierQ = []\r\n discovered = []\r\n path = []\r\n for v in range(self.am.shape[0]):\r\n discovered.append(False) #We populate the discovered list with False for every vertex\r\n path.append(-1) #we populate the path list with -1's for every vertex\r\n frontierQ.append(0) #We acknowledge vertex 0 as discovered.\r\n discovered[0] = True\r\n while (len(frontierQ) > 0):\r\n currentV = frontierQ.pop(0)\r\n for adjV in range(self.am.shape[1]): #We loop through the adjacent vertices in the AM by looping through the row corresponding to currentV and looking to see if the weight is not -1. If not, we identify it as adjacent.\r\n if self.am[currentV][adjV] != -1:\r\n if not discovered[adjV]:\r\n frontierQ.append(adjV)\r\n discovered[adjV] = True\r\n path[adjV] = currentV\r\n a = returnPath(path, 15)\r\n return a\r\n \r\n #DFS is the same as BFS but with a stack instead of a queue.\r\n def DFS(self):\r\n stack = []\r\n discovered = []\r\n path = []\r\n for v in range(self.am.shape[0]):\r\n discovered.append(False)\r\n path.append(-1)\r\n stack.append(0)\r\n discovered[0] = True\r\n while (len(stack) > 0):\r\n currentV = stack.pop(0)\r\n for adjV in range(self.am.shape[1]):\r\n if self.am[currentV][adjV] != -1:\r\n if not discovered[adjV]:\r\n stack.insert(0, adjV)\r\n discovered[adjV] = True\r\n path[adjV] = currentV\r\n a = returnPath(path, 15)\r\n return a\r\n \r\n def insert_edge(self,source,dest,weight=1):\r\n if self.directed:\r\n self.am[source][dest] = weight\r\n else:\r\n self.am[source][dest] = weight\r\n self.am[dest][source] = weight\r\n \r\n def delete_edge(self,source,dest): #assumes -1 is indicative of no edge.\r\n if self.directed:\r\n self.am[source][dest] = -1 \r\n else:\r\n self.am[source][dest] = -1\r\n self.am[dest][source] = -1\r\n \r\n def display(self):\r\n print(self.am)\r\n \r\n def draw(self):\r\n g = self.as_AL()\r\n g.draw()\r\n \r\n def as_EL(self):\r\n g = g_EL.Graph(self.am.shape[0], weighted = self.weighted, directed = self.directed)\r\n if self.directed: \r\n for i in range(self.am.shape[0]):\r\n for j in range(self.am.shape[1]):\r\n if self.am[i][j] != -1:\r\n g.insert_edge(i, j, self.am[i][j])\r\n g.el.sort(key = lambda edge: edge.source)\r\n else:\r\n for i in range(self.am.shape[0]):\r\n for j in range(i, self.am.shape[1]):\r\n if self.am[i][j] != -1:\r\n g.insert_edge(i, j, self.am[i][j])\r\n return g\r\n \r\n def as_AM(self):\r\n return self\r\n \r\n def as_AL(self):\r\n g = g_AL.Graph(self.am.shape[0], weighted = self.weighted, directed = self.directed)\r\n if self.directed:\r\n for i in range(self.am.shape[0]):\r\n for j in range(self.am.shape[1]):\r\n if self.am[i][j] != -1:\r\n g.insert_edge(i, j, self.am[i][j])\r\n else:\r\n for i in range(self.am.shape[0]):\r\n for j in range(i, self.am.shape[1]):\r\n if self.am[i][j] != -1:\r\n g.insert_edge(i, j, self.am[i][j])\r\n g.insert_edge(j, i, self.am[i][j])\r\n return g\r\n \r\ndef printPath(path, dest):\r\n if path[dest] != -1:\r\n printPath(path, path[dest])\r\n print(' ', dest)\r\n else:\r\n print(' ', dest)\r\n\r\ndef returnPath(path, dest):\r\n L = []\r\n if path[dest] != -1:\r\n L += returnPath(path, path[dest])\r\n L.append(dest)\r\n else:\r\n L.append(dest)\r\n return L","sub_path":"graph_AM.py","file_name":"graph_AM.py","file_ext":"py","file_size_in_byte":4554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"329027047","text":"import gi\ngi.require_version('Gtk', '3.0')\nfrom gi.repository import Gtk\n\nclass LinkButton(Gtk.Button):\n\tdef __init__(self, common, target_agenda):\n\t\tGtk.Button.__init__(self)\n\t\tself.target_agenda = target_agenda\n\t\tself.common = common\n\t\tself.set_title()\n\t\tself.connect(\"clicked\", self.set_link)\n\n\n\tdef is_linked(self):\n\t\tuser_linked_agendas = self.common.user_clicked._agenda.linked_agendas\n\t\treturn target_agenda in user_linked_agendas\n\n\tdef set_title(self):\n\t\tif (self.is_linked()):\n\t\t\ttitle = \"Délier\"\n\t\telse:\n\t\t\ttitle = \"Lier\"\n\t\tself.set_label(title)\n\n\tdef set_link(self, button, common):\n\t\tcurrent_user_agenda = common.user_clicked.agenda\n\t\tif (self.is_linked()):\n\t\t\tcurrent_user_agenda.unlink_agenda(target_agenda)\n\t\telse:\n\t\t\tcurrent_user_agenda.link_agenda(target_agenda)\n\n\t\tself.update()\n\t\n\tdef update(self):\n\t\tself.set_title()\n\n","sub_path":"Source/client/view/link_button.py","file_name":"link_button.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"130149127","text":"import numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\n\ng1=0.4\ng2=1.7\n\nIMG=cv2.imread('photo.jpg',cv2.IMREAD_GRAYSCALE)\n\n##Find width and height of Image\nheight,width = IMG.shape[:2]\n\n##Declare histogram data structure type for the original and 2 transform image\nIMG_H=[0 for x in range(256)]\nI=[0 for x in range(256)]\nPT1_H=[0 for x in range(256)]\nP1=[0 for x in range(256)]\nPT2_H=[0 for x in range(256)]\nP2=[0 for x in range(256)]\n\n##Convert 2D array to 1D\nIMG_F=IMG.flatten()\n##Declare PT1 nad PT2 array\nPT1_F=np.arange(width*height)\nPT2_F=np.arange(width*height)\n\n\n\n##Power Transformation\nfor j in range (0,height*width):\n if((IMG_F[j]*g1)>255):\n PT1_F[j]=255\n else:\n PT1_F[j]=IMG_F[j]*g1\n if((IMG_F[j]*g2)>255):\n PT2_F[j]=255\n else:\n PT2_F[j]=IMG_F[j]*g2\n\n##Histogram graypixel Frquency\nfor i in range(0,width*height):\n IMG_H[round(IMG_F[i])]+=1\n PT1_H[round(PT1_F[i])]+=1\n PT2_H[round(PT2_F[i])]+=1\n\n##Accumulative Frequency\nI[0]=IMG_H[0]\nP1[0]=PT1_H[0]\nP2[0]=PT2_H[0]\nfor i in range (1,256):\n I[i]=I[i-1]+IMG_H[i]\n P1[i]=P1[i-1]+PT1_H[i]\n P2[i]=P2[i-1]+PT2_H[i]\n\n\nbins=np.linspace(0,255,256)\nbar_width=0.35\nf,ax=plt.subplots(1)\nplt.xlabel('Levels')\nplt.ylabel('Acumulative Frequency')\nax.plot(bins,I,color='red',label='Original')\nax.plot(bins,P1,color='blue',label='Darker')\nax.plot(bins,P2,color='green',label='Lighter')\nplt.legend(loc='upper right')\nplt.title('Accumulative frequency')\nax.set_ylim(ymin=0)\nplt.show(f)\n\ncv2.imwrite('o.png',IMG)\ncv2.imwrite('gray.png',np.reshape(PT1_F,(-1,width)))\ncv2.imwrite('light.png',np.reshape(PT2_F,(-1,width)))\nprint(\"Complete\")","sub_path":"Homeork1/OLD/IPhm1.py","file_name":"IPhm1.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"206664542","text":"import pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport datetime\r\n\r\nf = open('血小板.csv')\r\ndf1 = pd.read_csv(f)\r\n\r\n#print(df1.columns)\r\n#df1['ctime'].apply(lambda x: x.split(' ')[0])\r\n#print(df1['ctime'])\r\n#print(df1.loc[4,'ctime'].split(' ')[0])\r\n\r\ndf2 = df1['ctime'].apply(lambda x:x.split(' ')[0])\r\ndf3 = df2.value_counts()\r\n\r\n\r\nday_list = sorted(list(df3.index),key=lambda x:datetime.datetime.strptime(x,'%Y/%m/%d').timestamp())\r\nprint(df3)\r\nprint(df3['2018/7/8'])\r\nlist1 = list(map(lambda x:x.split('/',1)[1],day_list))\r\nlist2=[]\r\nfor i,x in enumerate(list1):\r\n if i%15==0:\r\n list2.append(list1[i])\r\n else:\r\n list2.append('')\r\n\r\nplt.title('Commentary heat')\r\nplt.bar(list(map(lambda x:x.split('/',1)[1],day_list)),df3[day_list])\r\nfor x,y in zip(list1,df3[day_list]):\r\n plt.text(x,y+25,y,ha='center',va='top')\r\nplt.xticks(list1,list2)\r\nplt.xlabel('Date of review')\r\nplt.ylabel('Number of comments')\r\n\r\nplt.show()\r\n\r\n","sub_path":"pachong/selenium/xuexiaoban/Analy_xuexiaopan.py","file_name":"Analy_xuexiaopan.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"51560580","text":"import copy\n\nwidth = 5\nheight = 5\n\ndef update_tile(next_layout, x, y, bug_change):\n next_layout[(x,y)]['bug'] += bug_change\n for step in [(1,0),(-1,0),(0,1),(0,-1)]:\n adj_x = x + step[0]\n adj_y = y + step[1]\n if ((adj_x,adj_y) not in next_layout):\n continue\n next_layout[(adj_x,adj_y)]['adjacent'] += bug_change\n\ndef create_empty_layer(width, height):\n layer = {}\n for y in range(height):\n for x in range(width):\n layer[(x,y)] = {'bug': 0, 'adjacent': 0}\n return layer\n\ndef get_tile(layout, x, y):\n return layout.get((x,y), {'bug': 0,'adjacent': 0})\n\ndef get_num_bugs(layout, x, y):\n return get_tile(layout, x, y)['bug']\n\ndef get_adjacent_bugs(layout, x, y):\n adjacent_bugs = 0\n for step in [(1,0),(-1,0),(0,1),(0,-1)]:\n adj_x = x + step[0]\n adj_y = y + step[1]\n adjacent_bugs += get_num_bugs(layout, adj_x, adj_y)\n return adjacent_bugs\n\ndef update(layout, widht, height):\n next_layout = copy.deepcopy(layout)\n for y in range(height):\n for x in range(width):\n if layout[(x,y)]['bug']:\n if layout[(x,y)]['adjacent'] != 1:\n update_tile(next_layout, x, y, -1)\n else:\n if layout[(x,y)]['adjacent'] in [1,2]:\n update_tile(next_layout, x, y, 1)\n return next_layout\n\ndef print_layout(layout, widht, height):\n for y in range(height):\n for x in range(width):\n if layout[(x,y)]['bug']:\n print('#', end='')\n else:\n print('.', end='')\n print('')\n print('')\n print('')\n\ndef calculate_biodiversity(layout, widht, height):\n biodiversity = 0\n for y in range(height):\n for x in range(width):\n if layout[(x,y)]['bug']:\n biodiversity += pow(2,width*y + x)\n return biodiversity\n\nlayout = create_empty_layer(width,height)\n\nwith open(\"day24.input\") as file:\n y = 0\n for line in file:\n x = 0\n for tile in line.rstrip():\n if tile == '#':\n update_tile(layout, x, y, 1)\n x += 1\n y += 1\n\nlayouts = [layout]\nwhile True:\n layout = update(layout, width, height)\n if layout in layouts:\n print(calculate_biodiversity(layout, width, height))\n break\n layouts.append(layout)\n\n","sub_path":"24/day24.py","file_name":"day24.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"244828246","text":"from collections import OrderedDict, defaultdict\n\nclass Solution:\n def frequencySort(self, s: str) -> str:\n d = defaultdict(int)\n for x in s:\n d[x]+=1\n order = OrderedDict(sorted(d.items(),key=lambda item: item[1], reverse=True))\n val = \"\"\n for x in order:\n val = val+x*order[x]\n return val","sub_path":"Solutions/Week 2/sort-characters-by-frequency.py","file_name":"sort-characters-by-frequency.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"38800455","text":"# -*- coding:utf-8 -*-\n\n\n# Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.\r\n#\n# Note:\r\n#\n# The solution set must not contain duplicate triplets.\r\n#\n# Example:\r\n#\n#\n# Given array nums = [-1, 0, 1, 2, -1, -4],\r\n#\n# A solution set is:\r\n# [\r\n# [-1, 0, 1],\r\n# [-1, -1, 2]\r\n# ]\r\n#\n#\n\n\n#!/usr/bin/env python\n\n# -*- Coding: UTF-8 -*-\n# @Time : 9/17/18 8:27 AM\n# @Author : Terry LAI\n# @Email : terry.lai@hotmail.com\n# @File : 015.py\n\n# !/usr/bin/env python\n\n# -*- Coding: UTF-8 -*-\n# @Time : 9/17/18 8:27 AM\n# @Author : Terry LAI\n# @Email : terry.lai@hotmail.com\n# @File : 015.py\n\nclass Solution(object):\n def threeSum(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]\n 先排序,然后左右夹逼,时间复杂度O(n^2).可以推广到 k-sum ,先做 k-2次循环,在最内层做夹逼\n\n \"\"\"\n i, j, k = 0,0,0\n if len(nums) < 3:\n return []\n\n nums.sort()\n result = []\n for i in range(len(nums)):\n j = i + 1\n k = len(nums) - 1\n\n #重复的数字只算一次\n if i >=1 and nums[i] == nums[i-1]:\n continue\n\n while j