diff --git "a/1717.jsonl" "b/1717.jsonl" new file mode 100644--- /dev/null +++ "b/1717.jsonl" @@ -0,0 +1,709 @@ +{"seq_id":"631601222","text":"from tkinter import *\n\ndef button_clicked():\n print(\"I got clicked\")\n new_text = input.get()\n my_label.config(text=new_text)\n\nwindow = Tk()\nwindow.title(\"My First GUI Program\")\nwindow.minsize(width=500, height=300)\nwindow.config(padx=100, pady=200)\n\n# Label\nmy_label = Label(text=\"I am a label\", font=(\"Arial\", 24, \"bold\"))\n# Re-assign Label\nmy_label[\"text\"] = \"New Text\"\n# my_label.config(text=\"New Text\")\n# my_label.pack(side=\"left\")\n# my_label.place(x=100, y=200)\nmy_label.grid(column=0, row=0)\nmy_label.config(padx=50, pady=50)\n\n# Button\nbutton = Button(text=\"Click Me\", command=button_clicked)\n# button.pack(side=\"left\") \nbutton.grid(column=1, row=1)\n\nnew_button = Button(text=\"New Button\")\nnew_button.grid(column=3, row=0)\n\n# Entry\ninput = Entry(width=15)\nprint(input.get())\n# input.pack(side=\"left\")\ninput.grid(column=2, row=2)\n\n\n\n\nwindow.mainloop()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"594582043","text":"from time import time\r\n\r\n\r\ndef get_triangle_file(triangle_file):\r\n triangle = [[int(i) for i in row.split()] for row in open(triangle_file)]\r\n return triangle\r\n\r\n\r\ndef maximal_total(triangle):\r\n for i in range(len(triangle) - 1, 0, -1):\r\n for j in range(len(triangle[i]) - 1):\r\n maximum = max(triangle[i][j], triangle[i][j + 1])\r\n triangle[i - 1][j] += maximum\r\n return triangle[0][0]\r\n\r\n\r\nif __name__ == '__main__':\r\n start_time = time()\r\n tri = get_triangle_file('triangle.txt')\r\n print(f'Maximum Total:{maximal_total(tri)}')\r\n print(f'Execution Time: {time() - start_time} seconds.')\r\n","sub_path":"Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"351566254","text":"from flask import Flask, redirect, url_for\nfrom backend.controllers import catalogs_app, items_app, users_app\nfrom backend.api_controllers import catalogs_api_app, items_api_app\nfrom backend.config import create_schema\nfrom backend.helpers import generate_csrf_token, is_login\nfrom backend.models import Catalog, Item, User\n\n\napp = Flask(__name__, template_folder='frontend/templates', static_folder='frontend')\napp.config.from_pyfile('config.cfg')\napp.secret_key = app.config['SECRET_KEY']\napp.jinja_env.globals['csrf_token'] = generate_csrf_token\napp.jinja_env.globals['is_login'] = is_login\n\napp.register_blueprint(catalogs_app)\napp.register_blueprint(items_app)\napp.register_blueprint(users_app)\n\napp.register_blueprint(catalogs_api_app)\napp.register_blueprint(items_api_app)\n\ncreate_schema()\n\n@app.route(\"/\")\ndef root():\n return redirect(url_for('catalogs.index'))\n\n\n\nif __name__ == \"__main__\":\n app.run(port=8080, host='0.0.0.0', debug=True)\n","sub_path":"ItemCatalog/vagrant/catalog/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"41706752","text":"from collections import defaultdict\nclass Solution(object):\n def findItinerary(self, tickets):\n \"\"\"\n :type tickets: List[List[str]]\n :rtype: List[str]\n \"\"\"\n G = defaultdict(list)\n for pair in tickets:\n if pair[0] not in G:\n G[pair[0]] = [pair[1]]\n else:\n G[pair[0]].append(pair[1])\n for loc in G:\n G[loc].sort()\n\n # print G\n path = ['JFK']\n\n\n return self.dfs(G,'JFK',path,tickets)\n\n def dfs(self,graph,start,path,tickets):\n # print path\n if len(path) == len(tickets) + 1:\n return path\n for nbr in sorted(graph[start]):\n path.append(nbr)\n graph[start].remove(nbr)\n # print graph[start]\n worked = self.dfs(graph,nbr,path,tickets)\n if worked:\n # print worked\n return worked\n path.pop()\n graph[start].append(nbr)\n # print graph[start]\n","sub_path":"reconstruct-itinerary.py","file_name":"reconstruct-itinerary.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"341283934","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n'''\n@文件 :c6.py\n@说明 :\n@时间 :2020/09/16 23:00:16\n@作者 :陆柏成\n@版本 :1.0\n@Email :lu_baicheng@163.com\n'''\n\nimport re \na = 'PythonqC#JavaPHPC#'\n\n\ndef convert(value):\n matched = value.group()\n return '!!'+ matched +'!!'\n\nr = re.sub('C#',convert,a)\n\nif __name__ == \"__main__\":\n print(r)\n","sub_path":"c6.py","file_name":"c6.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"630487448","text":"from DevIoTGateway.sensor import *\nfrom DevIoTGateway.config import config\nfrom DevIoTGatewayPi.sensorlogic import SensorLogic\nfrom picamera import PiCamera\nimport threading\nimport time\n\npath = None\nif \"camera_images\" in config:\n path = config[\"camera_images\"]\nelse:\n import os\n current_folder = os.getcwd()\n path = current_folder + \"/camera_images\"\n\ncamera = Sensor('camera', 'camera_r', 'RCamera')\n\nvalue_property = SProperty('CapturePath', 1, None, path)\n\ncamera.add_property(value_property)\n\non_action = SAction('start')\noff_action = SAction('stop')\n\ncamera.add_action(on_action)\ncamera.add_action(off_action)\n\n\nclass CameraLogic(SensorLogic):\n camera_obj = None\n t = None\n\n busy = False\n index = 0\n\n @staticmethod\n def action(sensor, action):\n if action.name == 'start':\n CameraLogic.start()\n elif action.name == 'stop':\n CameraLogic.index = 0\n else:\n pass\n\n @staticmethod\n def start():\n if CameraLogic.index <= 0:\n CameraLogic.index += 5\n CameraLogic.t = threading.Thread(target=CameraLogic.capture)\n CameraLogic.t.daemon = True\n CameraLogic.t.start()\n\n @staticmethod\n def capture():\n if CameraLogic.camera_obj is not None:\n CameraLogic.camera_obj.start_preview()\n while CameraLogic.index > 0:\n CameraLogic.camera_obj.capture(path)\n time.sleep(2.5)\n CameraLogic.index -= 1\n CameraLogic.camera_obj.stop_preview()\n\ntry:\n CameraLogic.camera_obj = PiCamera()\nexcept Exception as ex:\n print(ex.message)\n CameraLogic.camera_obj = None\n","sub_path":"sensors/camera.py","file_name":"camera.py","file_ext":"py","file_size_in_byte":1676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"480708110","text":"#!/usr/bin/python2.7\n\nimport pprint\nimport json\nimport sys\nimport mysql_tools\nimport _mysql\nimport infoModule\n\n# Load Streams\n# Gets the streams from the database and stores them in a dictionary\n# with \"name : stream_id\" as the structure\ndef loadStreams():\n query = mysql_tools.mysqlQuery(\"SELECT * FROM `peepbuzz`.`streams`\", infoModule.info.site['dblink'])\n \n streams = {}\n if query.num_rows() > 0:\n while True:\n stream = query.fetch_row(1,1)\n if stream == ():\n break\n \n if stream[0]['name'] in streams:\n streams[stream[0]['name']] = stream[0]['stream_id']\n else:\n streams[stream[0]['name']] = {}\n streams[stream[0]['name']] = stream[0]['stream_id']\n else:\n return False\n \n return streams","sub_path":"loadStreams.py","file_name":"loadStreams.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"243131345","text":"def getResult(time, times):\n answer = 0\n for t in times:\n answer += time // t\n return answer\n\ndef solution(n, times):\n answer = 0\n \n start = 0\n end = int(1e20)\n \n while start <= end:\n time = (start + end) // 2\n result = getResult(time, times)\n \n if result < n:\n start = time + 1\n else:\n answer = time\n end = time - 1\n \n return answer","sub_path":"PROGRAMMERS/Level 3/입국심사_python/CodingTest.py","file_name":"CodingTest.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"83586033","text":"import RPi.GPIO as GPIO\nimport time\nGPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)\n\nGPIO.setup(9,GPIO.OUT)\nGPIO.setup(23,GPIO.OUT)\nGPIO.setup(25,GPIO.OUT)\ncount = 0\ni = 1\nwhile True:\n count +=1\n if count == 10:\n break\n elif i == 1:\n GPIO.output(9,GPIO.HIGH)\n time.sleep(3)\n GPIO.output(9,GPIO.LOW)\n time.sleep(0.2)\n i = 2\n elif i == 2:\n GPIO.output(23,GPIO.HIGH)\n time.sleep(3)\n GPIO.output(23,GPIO.LOW)\n time.sleep(0.2)\n i =3\n elif i ==3:\n GPIO.output(25,GPIO.HIGH)\n time.sleep(3)\n GPIO.output(25,GPIO.LOW)\n time.sleep(0.2)\n i = 1\n \n\n\n\n\n\n\n\n","sub_path":"Practice-files/BT_Phuong.py","file_name":"BT_Phuong.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"453778992","text":"\nimport pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import Normalizer\n\ndef choose_features(data, columns):\n\tfeatures = data[columns]\n\treturn features\n\ndef find_outliers_tukey(column):\n\tQ1 = np.percentile([column], 25)\n\tQ3 = np.percentile([column], 75)\n\tiqr = Q3-Q1 \n\tfloor = Q1 - 1.5*iqr\n\tceiling = Q3 + 1.5*iqr\n\toutlier_index = list(column.index[(column < floor)|(column > ceiling)])\n\toutlier_values = list(column[outlier_index])\n\n\treturn outlier_index, outlier_values\n\ndef remove_outliers_tukey(data,outlier_indices):\n\tdata_no_out = data.drop(outlier_indices)\n\n\treturn data_no_out\n\ndef stardardise(X_train, X_test):\n\tfeature_scaler = StandardScaler() \n\tX_train = feature_scaler.fit_transform(X_train) \n\tX_test = feature_scaler.transform(X_test) \n\n\treturn X_train, X_test\n\ndef normalise(X_train, X_test):\n\tfeature_scaler = Normalizer().fit(X_train)\n\tX_train = feature_scaler.transform(X_train)\n\tX_test = feature_scaler.transform(X_test)\n\n\treturn X_train, X_test","sub_path":"mlp/processing.py","file_name":"processing.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"346012126","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport datetime\nfrom django.utils.timezone import utc\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('merchant', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='merchant',\n name='email',\n field=models.EmailField(default='xyz@xyz.com', max_length=254),\n preserve_default=False,\n ),\n ]\n","sub_path":"merchant/migrations/0002_merchant_email.py","file_name":"0002_merchant_email.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"300939757","text":"#!/usr/bin/env python3\n\n\"\"\"\n cnfhash.dimacs\n --------------\n\n Read a DIMACS file and hash all integers.\n\n (C) Lukas Prokop, 2015, Public Domain\n\"\"\"\n\nimport _io\nimport logging\n\nfrom . import hashing\n\n\n@hashing.integers\ndef read_dimacs_file(fp: _io.TextIOWrapper, log: logging.Logger):\n \"\"\"Parse a DIMACS file and yield all numbers which in turn get hashed.\n\n :param fp: A file descriptor to read from\n :param log: A logger to write messages to\n :return: A hash value for the DIMACS file\n \"\"\"\n lineno = 0\n state = 0\n\n for line in fp:\n parts = line.split()\n lineno += 1\n\n if line[0] == 'c' and parts[0] == 'c':\n continue\n\n elif len(parts) == 0:\n continue\n\n # there are strange DIMACS files out there\n elif len(parts) == 1 and parts[0] == '%':\n return\n\n elif state == 0:\n msg = 'Expected valid DIMACS header at line {}'\n assert parts[0].lower() == 'p', msg.format(lineno)\n\n msg = 'DIMACS header line should have value \"cnf\" as second element at line {}'\n assert parts[1].lower() == 'cnf', msg.format(lineno)\n\n msg = 'DIMACS header line should have 4 values at line {}'\n assert len(parts) == 4, msg.format(lineno)\n\n log.info(\"Header line found at line {}\".format(lineno))\n state = 1\n\n yield int(parts[2])\n yield int(parts[3])\n yield 0\n\n continue\n\n else:\n msg = 'Expected header, unexpected clause at line {}'\n assert state > 0, msg.format(lineno)\n\n for part in parts:\n integer = int(part)\n yield integer\n\n if state != 1:\n raise ValueError('Empty DIMACS file, expected at least a header')\n","sub_path":"cnfhash/dimacs.py","file_name":"dimacs.py","file_ext":"py","file_size_in_byte":1829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"625680826","text":"import mysql.connector as mycon\r\nfrom numpy import select\r\nimport pandas as pd\r\n\r\nx=-1\r\ninfo=pd.read_csv(\"Pokemons.csv\")\r\ndf=pd.DataFrame(info)\r\nmydb = mycon.connect(\r\n host=\"localhost\",\r\n user=\"root\",\r\n password=\"12345678\",\r\n database=\"project\"\r\n)\r\n\r\nmycursor = mydb.cursor()\r\n\r\npd.set_option('display.max_rows', 800)\r\npd.set_option('display.max_column', 15)\r\n\r\n\r\nfor i in range(0,800):\r\n x=x+1\r\n name=df.iloc[x,1]\r\n type_1=df.iloc[x,2]\r\n type_2=df.iloc[x,3]\r\n total=df.iloc[x,4]\r\n hp=df.iloc[x,5]\r\n attack=df.iloc[x,6]\r\n defense=df.iloc[x,7]\r\n sp_atk=df.iloc[x,8]\r\n sp_def=df.iloc[x,9]\r\n speed=df.iloc[x,10]\r\n generation=df.iloc[x,11]\r\n legendary=df.iloc[x,12]\r\n sql=(f\"insert into pokemones value('{name}','{type_1}','{type_2}',{total},{hp},{attack},{defense},{sp_atk},{sp_def},{speed},{generation},'{legendary}')\")\r\n print(x+1,sql) \r\n mycursor.execute(sql)\r\n mydb.commit()\r\nprint(f\"inserted {x+1} values into test\")\r\ninput()\r\n ","sub_path":"sql.py","file_name":"sql.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"93270706","text":"#!/usr/bin/env python3\n#-*- coding: utf-8 -*-\n\nfrom Screen import Screen\nfrom Spot import Spot\nfrom PathFinder import PathFinder\nimport pygame\n\n\ndef main():\n cols, rows = 10, 10\n screen = Screen(500, 500, rows)\n screen.show()\n screen.makeGrid()\n \n grid = [[Spot(screen, i, j) for j in range(0, rows)] for i in range(0, cols)]\n\n for i in range(0, cols):\n for j in range(0, rows):\n grid[i][j].addNeigbors(grid, cols, rows)\n\n start = grid[0][0]\n start.obstacle = False\n stop = grid[cols - 1][rows - 1]\n stop.obstacle = False\n\n pathFinder = PathFinder(grid, start, stop)\n \n while True:\n for event in pygame.event.get():\n if (event.type == pygame.QUIT):\n screen.close()\n \n \n result = pathFinder.findPath()\n pathFinder.showOpenSet()\n pathFinder.showPath()\n screen.update()\n \n \nif __name__ == \"__main__\":\n main()\n","sub_path":"prototype/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"281934520","text":"import set_paths\n\nimport matplotlib.pyplot as plt\nimport matplotlib.mlab as mlab\nplt.switch_backend('agg')\n\nimport numpy as np\n\nfolder_name = \"images/\"\n\ndef plot_example(ax, ylabel, idx_special, shift):\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n ax.spines['left'].set_visible(False)\n y_range = [0, 2.]\n ax.set_ylim(y_range)\n x_max = 20.\n ax.set_xlim([0, x_max])\n\n x_locs = [4, 10, 16]\n colours = ['r', 'm', 'g', 'y', 'c', 'k', 'b'] # use same colour as other figs\n # other colours plt.rcParams['axes.prop_cycle'].by_key()['color']\n\n for i, mu in enumerate(x_locs):\n variance = 1\n sigma = np.sqrt(variance)\n x = np.linspace(mu - 5*sigma, mu + 5*sigma, 100)\n\n if i == idx_special:\n x = np.linspace(mu - 5*sigma, mu + 5*sigma, 100)\n ax.plot(x, mlab.normpdf(x, mu, sigma) / 0.4, color=colours[i])\n ax.axvline(x=mu, linewidth=2, color=colours[i])\n ax.fill_between(x, mlab.normpdf(x, mu, sigma) / 0.4, alpha=0.3, color=colours[i])\n\n mu += shift \n ax.plot(x, mlab.normpdf(x, mu, sigma) / 0.4, color=colours[i], linestyle='dashed')\n ax.arrow(mu + shift, 1.2, shift * -1.5, 0, head_width=0.1, head_length=0.5, fc='k', ec='k')\n else:\n ax.plot(x, mlab.normpdf(x, mu, sigma) / 0.4, color=colours[i])\n ax.fill_between(x, mlab.normpdf(x, mu, sigma) / 0.4, alpha=0.3, color=colours[i])\n ax.axvline(x=mu, linewidth=2, color=colours[i])\n\n ax.tick_params(\n axis='both', \n which='both', \n bottom=False, \n top=False, \n left=False, \n labelbottom=False,\n labelleft=False,\n labelsize=0.\n )\n #ax.set_ylabel(\"Density\", fontsize=6)\n ax.set_xlabel(ylabel, fontsize=10)\n\n return ax\n\ndef plot_figure3(name, image_format):\n total_cols, total_rows = 3, 1\n fig, axes = plt.subplots(total_rows, total_cols, sharex=False, sharey=False, figsize=(18.3/2.54, 24.7/2.54*0.3))\n fig.text(0.5, 0.99, 'Figure 3: Sandwiching Effect and Implication of Biases.', ha='center', fontsize=12)\n\n ylabels = [r\"$\\leftarrow$ Distinctiveness\", '', r\"Ease of Production $\\rightarrow$\"]\n labels = ['a.', 'b.', 'c.']\n idx_special_lst = [2, 1, 0]\n shift_lst = [-2, -2, 2]\n for i, ax in enumerate(axes):\n ax.text(0.025, 1.05, labels[i], transform=ax.transAxes,\n fontsize=12, fontweight='bold', va='top', ha='right')\n ax = plot_example(ax, ylabels[i], idx_special_lst[i], shift_lst[i])\n\n fig.savefig(folder_name+name, format=image_format, bbox_inches='tight')\n plt.close(fig)\n\n# OLD FIGURE 3\nif __name__ == '__main__':\n plot_figure3(\"illustration_fig3.png\", \"png\")\n","sub_path":"analyses/others/plot_figure3.py","file_name":"plot_figure3.py","file_ext":"py","file_size_in_byte":2609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"441817638","text":"# -*- ##################\n# ---------------------------------------------------------------------------\n# create_semih_archydro.py\n#\n# Coded by :\n# Semih DALGIN\n# semihdalgin@gmail.com\n#\n# \n# Requires Arc10\n#\n#\n# ---------------------------------------------------------------------------\n# Import system modules\nimport sys,os\nreload(sys)\nsys.setdefaultencoding('utf-8')\ntry:\n # Script arguments\n arcpy.AddMessage (\"\\nBaşlangıç Değerleri Alınıyor...\" )\n try:\n # Folder where output files will be saved\n pdf = arcpy.GetParameterAsText(0)\n verisay = arcpy.GetParameterAsText(1)\n callayer=arcpy.GetParameterAsText(2)\n scalesem=arcpy.GetParameterAsText(3)\n mxd = arcpy.mapping.MapDocument(\"CURRENT\")\n layers=arcpy.mapping.ListLayers(mxd,\"*HALK*\")\n df = arcpy.mapping.ListDataFrames(mxd, \"Layers\")[0] \n veris=int(verisay)+1\n except:\n arcpy.AddMessage(\"\\n Hata Girdi Verilerinde: \")\n raise Exception\n # Check and create output folders\n try:\n for sem in range (1,veris,1):\n query = \"[OBJECTID]=\"+\"%d\"%sem\n layers[0].definitionQuery=query\n myList = set([row.getValue(\"OBJECTID\")for row in arcpy.SearchCursor(callayer)])\n aa=row.getValue(\"Firat_HD_HALK_SULAMALARI_sul_adi\")\n bb=aa.split()\n ccc=0\n ee=\"SD_\"\n for ff in bb:\n ccc=ccc+1\n for xox in range (0,ccc,1):\n ee=ee+bb[xox] \n exportname=pdf+\"\\\\\"+ee\n ddp = mxd.dataDrivenPages\n pageID = sem\n mxd.dataDrivenPages.currentPageID = pageID\n df.scale = scalesem # we set the scale to 1:25,000 \n arcpy.mapping.ExportToPDF(mxd,exportname) # export the current Page to pdf \n except:\n arcpy.AddError(\"\\nHata Hesaplamalarda\" + arcpy.GetMessages(2))\n raise Exception \nexcept:\n arcpy.AddError(\"\\n Sonda hata\")\n raise Exception\n","sub_path":"ELH_r2.py","file_name":"ELH_r2.py","file_ext":"py","file_size_in_byte":1987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"473743871","text":"import socket\r\nimport datetime\r\nimport os\r\n\r\nfile=open('config.txt','r')\r\nconf=''\r\nfor i in file:\r\n conf=conf+i\r\nfile.close()\r\nconf=conf.split('\\n')\r\n\r\nport=int(conf[0][conf[0].find('=')+1:])\r\nwork_directory=conf[1][conf[1].find('=')+1:]\r\nmax_size=int(conf[2][conf[2].find('=')+1:])\r\nif work_directory!='none':\r\n os.chdir(os.path.join(os.getcwd(), work_directory))\r\n\r\nsock = socket.socket()\r\nsock.bind(('', port))\r\n\r\nsock.listen(5)\r\n\r\nwhile True:\r\n \r\n conn, addr = sock.accept()\r\n print(\"Connected\", addr)\r\n \r\n data = conn.recv(8192)\r\n msg = data.decode()\r\n \r\n path=msg[msg.find(' ')+2:msg.find('H')]\r\n \r\n output='no such file'\r\n \r\n if path[path.find('.'):-1] in ['.txt','.gif','.html','.css']:\r\n \r\n try:\r\n file=open(path,'r')\r\n output=''\r\n for i in file:\r\n \r\n output=output+i\r\n file.close()\r\n except:\r\n output='no such file'\r\n \r\n if output!='no such file':\r\n resp = \"\"\"HTTP/1.1 200 OK\r\nServer: SelfMadeServer v0.0.1\r\nDate:{1}\r\nContent-type: text/html\r\nConnection: close\r\n\r\n{0}\"\"\".format(output,datetime.datetime.now(),max_size)\r\n log=open('log.txt','a')\r\n log.write(str(datetime.datetime.now())+': '+str(addr)[2:str(addr).find(',')-1]+'-->'+path+':200'+'\\n')\r\n else:\r\n \r\n if path!='' and path!='favicon.ico ':\r\n log=open('log.txt','a')\r\n log.write(str(datetime.datetime.now())+': '+str(addr)[2:str(addr).find(',')-1]+'-->'+path+':404,returned index.txt'+'\\n')\r\n log.close()\r\n file=open('index.html','r')\r\n output=''\r\n for i in file:\r\n output=output+i\r\n file.close()\r\n resp = r\"\"\"HTTP/1.1 200 OK\r\nServer: SelfMadeServer v0.0.1\r\nDate:{1}\r\nContent-type: text/html\r\nConnection: close\r\n\r\n\r\n{0}\"\"\".format(output,datetime.datetime.now(),max_size)\r\n \r\n conn.send(resp.encode())\r\n \r\n conn.close()\r\n \r\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"321083036","text":"\n\n# 元组于列表类似,不同的地方在于元组不能更改,内容不能更改,指针指向可以更改\n\ntup1 = (); # 创建空元组\ntuple = ( 'abcd', 786 , 2.23, 'runoob', 70.2 )\ntinytuple = (123, 'runoob')\n\n# 访问元组\nprint (tuple) # 输出完整元组\nprint (tuple[0]) # 输出元组的第一个元素\nprint (tuple[1:3]) # 输出从第二个元素开始到第三个元素\nprint (tuple[2:]) # 输出从第三个元素开始的所有元素\nprint (tinytuple * 2) # 输出两次元组\nprint (tuple + tinytuple) # 连接元组\n\n# 虽然tuple的元素不可改变,但它可以包含可变的对象,比如list列表。\n\ntup2 = (1,2,3)\n\n# 拼接元组\ntup3 = tuple + tup2\n\ndel tuple # 删除整个元组,元组中的元素值是不允许删除的\n\nfor x in tuple:\n print(x)\n\nlen()\n\n3 in tuple # True\nmax()\nmin\n\n# 将list转为元组\ntuple(list)","sub_path":"02_标准数据类型/04_元组/01.元组声明.py","file_name":"01.元组声明.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"149989172","text":"import warnings\r\n\r\nwarnings.simplefilter(\"ignore\")\r\n\"\"\"\r\nIn this lesson, your goal is to develop your first neural network using the Keras library.\r\n\r\nUse a standard binary (two-class) classification dataset from the UCI Machine Learning Repository, like the Pima Indians onset of diabetes or the ionosphere datasets.\r\n\r\nPima Indians onset of diabetes\r\nhttps://archive.ics.uci.edu/ml/datasets/Pima+Indians+Diabetes?__s=ivkfnfqiesjpvzinonpe\r\nor https://www.kaggle.com/uciml/pima-indians-diabetes-database/data (kaggle gmail)\r\n\r\n\r\nPiece together code to achieve the following: \r\n1. Load your dataset using Pandas.\r\n - Look at the structure\r\n Labels = Outcome col\r\n features = Other cols\r\n - use from sklearn.model_selection import train_test_split to split\r\n your data\r\n \r\n \r\n2. Define your neural network model and compile it using dense layers and activations\r\n - import Keras\r\n - Dense implements the operation:\r\n use from keras.layers import Dense, Activation to create your first\r\n keras model with 3 different Dense Layers\r\n\r\n - Use plot_model from keras.utils.vis_utils import to see your model\r\n\r\n3. Fit your model to the dataset.\r\n model.compile(loss='binary_crossentropy' , optimizer='adam', metrics=['accuracy'])\r\n print(\" Fit model\")\r\n model.fit(X_train.values,y_train, validation_data=(X_test.values, y_test), epochs=4,\r\n verbose=1)\r\n\r\n Try other verbose mode and more epochs\r\n \r\n4. Estimate the performance of your model on unseen data.\r\n\r\n - Use Evaluate\r\n'''\r\n\"\"\"\r\n\r\n# Create first network with Keras\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense, Dropout\r\n\r\nimport pandas as pd\r\nfrom keras.utils.vis_utils import plot_model\r\nfrom sklearn.model_selection import train_test_split\r\n\r\npdata = pd.read_csv('diabetes.csv', sep=',')\r\nprint(\"values\", pdata.shape)\r\nfeatures = pdata.columns\r\nfeatures = features[:-1]\r\nX = pdata[features]\r\ny = pdata['Outcome']\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(X, y)\r\nprint(X_test.shape)\r\n\r\n# create model\r\nmodel = Sequential()\r\nmodel.add(Dense(32, activation='relu', input_dim=8))\r\nmodel.add(Dropout(0.5))\r\nmodel.add(Dense(1, activation='sigmoid'))\r\n\r\nprint(model.summary())\r\n# plot_model(model, to_file='model.png', show_shapes=True)\r\n\r\nprint(\" Compile model\")\r\nmodel.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\r\n# Fit the model\r\n\r\nprint(\" Fit model\")\r\nmodel.fit(X_train.values, y_train, validation_data=(X_test.values, y_test), epochs=40, verbose=1)\r\n\r\nprint(\" Evaluate model\")\r\nscores = model.evaluate(X_test.values, y_test, verbose=1)\r\nprint(\"%s: %.2f%%\" % (model.metrics_names[1], scores[1] * 100))\r\nprint(scores)\r\n\r\n'''\r\nClassification of radar returns from the ionosphere \r\nhttps://archive.ics.uci.edu/ml/datasets/Ionosphere?__s=ivkfnfqiesjpvzinonpe\r\n'''\r\n","sub_path":"LAB 1 keras_etudiants.py","file_name":"LAB 1 keras_etudiants.py","file_ext":"py","file_size_in_byte":2909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"360411769","text":"import zmq\n\nctx = zmq.Context()\ns = ctx.socket(zmq.REP) # Etapa número 1\n\ns.bind(\"tcp://*:5555\") # Etapa número 2\n\nwhile True:\n d = s.recv_json()\n\n resp = 0\n if (d[\"operacion\"] == \"suma\"):\n resp = d[\"op1\"] + d[\"op2\"] \n\n s.send(resp)","sub_path":"sockets-14-agosto-2019/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"557489700","text":"# -*- coding: utf-8 -*-\n\nfrom datetime import datetime\nfrom django.contrib.sites.models import Site\nfrom django.db import models\nfrom django.contrib.sites.managers import CurrentSiteManager\nimport settings\n\n\nclass PostAuthor(models.Model):\n orig_user_id = models.IntegerField(blank=False, null=False, unique=True, db_index=True)\n name = models.CharField(max_length=100, blank=False, null=False)\n\n\nclass Group(models.Model):\n site = models.ForeignKey(Site, null=False, blank=False, on_delete=models.CASCADE)\n orig_group_id = models.IntegerField(blank=False, null=False, unique=True, db_index=True)\n name = models.CharField(max_length=100, blank=False, null=False)\n description = models.TextField(blank=True, null=True)\n current_site_only = CurrentSiteManager('site')\n\n @property\n def posts(self, all=False):\n now = datetime.now()\n query = self.grouppost_set\n\n if not all:\n query = query.filter(created_at__lte=now)\n\n return query.all()\n\n @models.permalink\n def get_absolute_url(self):\n return ('forum.views.forum_group', (), {\n 'group_id': int(self.id),\n })\n\n\nclass GroupPostCurrentSiteManager(models.Manager):\n def get_query_set(self):\n return super(GroupPostCurrentSiteManager, self).get_query_set().filter(group__site=settings.SITE_ID)\n\n\nclass GroupPost(models.Model):\n group = models.ForeignKey(Group, null=False, blank=False, on_delete=models.CASCADE)\n author = models.ForeignKey(PostAuthor, null=False, blank=False)\n\n orig_post_id = models.IntegerField(blank=False, null=False, unique=True, db_index=True)\n title = models.CharField(max_length=255, blank=True, null=True)\n content = models.TextField()\n created_at = models.DateTimeField()\n current_site_only = GroupPostCurrentSiteManager()\n\n @property\n def comments(self, all=False):\n now = datetime.now()\n query = self.grouppostcomment_set\n\n if not all:\n query = query.filter(created_at__lte=now)\n\n return query.all()\n\n @models.permalink\n def get_absolute_url(self):\n return ('forum.views.forum_post', (), {\n 'group_post_id': int(self.id),\n })\n\n\nclass GroupPostComment(models.Model):\n group_post = models.ForeignKey(GroupPost, null=False, blank=False)\n author = models.ForeignKey(PostAuthor, null=False, blank=False)\n\n content = models.TextField()\n created_at = models.DateTimeField()\n\n\nclass UserBlogPost(models.Model):\n author = models.ForeignKey(PostAuthor, null=False, blank=False)\n\n title = models.CharField(max_length=255, blank=True, null=True)\n content = models.TextField()\n created_at = models.DateTimeField()\n\n @property\n def comments(self, all=False):\n now = datetime.now()\n query = self.userblogpostcomment_set\n\n if not all:\n query = query.filter(created_at__lte=now)\n\n return query.all()\n\n\nclass UserBlogPostComment(models.Model):\n blog_post = models.ForeignKey(UserBlogPost, null=False, blank=False)\n author = models.ForeignKey(PostAuthor, null=False, blank=False)\n\n content = models.TextField()\n created_at = models.DateTimeField()\n","sub_path":"apps/forum/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"335716655","text":"#!/usr/bin/env python3\nimport os\nimport sys\n\n\ndef get_substring_and_directory():\n '''Recieve and return substring, path to search and path to save.'''\n if len(sys.argv) < 2:\n print('Использование: findtag.py [слово для поиска] [адрес директории поиска, '\n 'по умолчанию ищет в текущей] '\n '[адрес сохранения файла, по умолчанию сохраняет в директории поиска]')\n sys.exit()\n\n elif len(sys.argv) < 3:\n print('Для поиска и сохранения будет использована текущая директория.')\n return sys.argv[1], os.getcwd(), os.getcwd()\n\n elif len(sys.argv) < 4:\n print('Для сохранения будет использована директория поиска.')\n return sys.argv[1], sys.argv[2], sys.argv[2]\n\n return sys.argv[1], sys.argv[2], sys.argv[3]\n\n\ndef search_files(substring_for_search, directory_path):\n '''Search files with substring in file names'''\n file_list = os.listdir(directory_path)\n result_file_list = []\n files = {}\n\n for file in file_list:\n file_path = os.path.join(directory_path, file)\n if os.path.isfile(file_path) and substring_for_search in file:\n result_file_list.append(file)\n files[file] = file_path\n elif os.path.isdir(file_path):\n dir_list = os.listdir(file_path)\n for item in dir_list:\n file_list.append(os.path.join(file_path, item))\n\n if len(result_file_list) == 0:\n print('Соответствий не найдено.')\n return None, None\n else:\n print('Найдены следующие соответствия:')\n result_list = sorted(result_file_list)\n for i in range(len(result_list)):\n print(f'{i}. {result_list[i]}\\n')\n return result_list, files\n\n\ndef create_file(result_list, files, directory_to_save):\n '''Create file with search results'''\n file_to_save = os.path.join(directory_to_save, 'files_found.txt')\n with open(file_to_save, 'w', encoding='utf-8') as save:\n for i in range(len(result_list)):\n save.write(f'{i}. {files[result_list[i]]}\\n')\n print('Операция завершена.')\n return files\n\n\ndef main() -> None:\n substring_for_search, directory_path, directory_to_save = get_substring_and_directory()\n result_list, files = search_files(substring_for_search, directory_path)\n if result_list is None:\n print('Ничего не найдено.')\n else:\n create_file(result_list, files, directory_to_save)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"findtag.py","file_name":"findtag.py","file_ext":"py","file_size_in_byte":2775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"145312451","text":"# written by Mahmoud Fettal\n# in 11/27/2020 (27/11/2020) \n\n#--------------------------------------- description ---------------------------------------#\n\n'''\nThis module contains the building blocks of the game 2048\nIt contains :\n 1- \"Settings\" class here i store all the general variables so i can change them inside \n the class without needing to change them all over the code.\n 2- \"Cell\" is the class that contians the value of the cell and the operations between \n cells.\n 3- \"Grid\" the grid is the main subject of this module and it is the only one used \n outside it, it contains 4*4 grid of cells and it contains all the methodes for swiping and \n cheking available cells. \n'''\n\n#--------------------------------------- import phase ---------------------------------------#\n\nfrom random import randint, choice # we don't need the full module\n\nimport pygame, os # pygame to define images in the dict of images\n\n#----------------------------------------- functions ----------------------------------------#\n\ndef possibility():\n '''\n the possibility functions gives the value to add based on the possibility of 10 percent of \n 4 and 90 to have 2.\n I used randint to make the possibility it is not 100 accurete.\n '''\n x = randint(1,100)\n if x <= 10:\n return 4\n return 2\n\ndef frames_path(x):\n '''\n this function create the path using os.path.join to avoid problems in other os systems\n '''\n return os.path.join('frames',f'{x}.png')\n\n#------------------------------------------- class ------------------------------------------#\n\nclass Settings():\n\n bg_color = pygame.Color('#fdfffc')\n width = 128\n window_size = [width*4 + 3, width*4 + 3]\n colors_imgs = {2**i: pygame.image.load(frames_path(2**i)) for i in range(1,12)}\n colors_imgs[0] = pygame.image.load(frames_path(0)) \n\nclass Cell():\n\n def __init__(self,value):\n self.value = value\n \n def merge(self,cell_2):\n self.value += cell_2.value\n cell_2.value = 0\n\nclass Grid():\n\n def __init__(self):\n self.score = 0\n self.ended = False\n self.move = 1\n self.grid = [[Cell(0) for _ in range(4)] for _ in range(4)]\n\n def empty_cells(self):\n empty = []\n for i in range(4):\n for j in range(4):\n if self.grid[i][j].value == 0:\n empty.append((i,j))\n return empty\n\n def fill_empty(self):\n empty = self.empty_cells()\n cell = choice(empty)\n self.grid[cell[0]][cell[1]].value = possibility()\n \n def swap_zero(self,move):\n moves = [[i, i+1] for i in range(3)]\n codes = {'r':['+','k'],'l':['-','k'],'d':['+','f'],'u':['-','f']}\n flip = {'k': lambda x,y : (x, y), 'f': lambda x,y : (y, x)}\n swips = 0\n\n direction, way = codes[move]\n if direction == '+':\n moves = moves[::-1]\n while True:\n zero_sawp = 0\n for x in range(4):\n for move in moves:\n a,b = flip[way](x, move[0])\n n,m = flip[way](x, move[1])\n if self.grid[n][m].value == 0 and self.grid[a][b].value != 0 and direction == '+':\n swips += 1\n zero_sawp += 1\n self.grid[a][b].value, self.grid[n][m].value = self.grid[n][m].value, self.grid[a][b].value\n if self.grid[a][b].value == 0 and self.grid[n][m].value != 0 and direction == '-':\n swips += 1\n zero_sawp += 1\n self.grid[a][b].value, self.grid[n][m].value = self.grid[n][m].value, self.grid[a][b].value\n if zero_sawp == 0:\n break\n return swips \n \n def make_move(self, the_move):\n moves = [[i, i+1] for i in range(3)]\n codes = {'r':['+','k'],'l':['-','k'],'d':['+','f'],'u':['-','f']}\n flip = {'k': lambda x,y : (x, y), 'f': lambda x,y : (y, x)}\n swips = 0\n\n direction, way = codes[the_move]\n if direction == '+':\n moves = moves[::-1]\n \n swips += self.swap_zero(the_move)\n\n for x in range(4):\n i = 0\n while i < 3:\n a,b = flip[way](x, moves[i][0])\n n,m = flip[way](x, moves[i][1])\n if self.grid[a][b].value == 0:\n pass\n elif self.grid[a][b].value == self.grid[n][m].value or self.grid[n][m].value == 0:\n if self.grid[a][b].value != 0 and self.grid[m][n].value != 0:\n i += 1\n self.score += self.grid[a][b].value + self.grid[n][m].value\n if direction == '-':\n self.grid[a][b].merge(self.grid[n][m])\n else:\n self.grid[n][m].merge(self.grid[a][b])\n swips += 1\n i += 1\n\n swips += self.swap_zero(the_move)\n\n return swips\n\n def swips_test(self,i,j,move):\n if self.grid[i][j].value == 0:\n return False\n tests = [(i,j+1),(i,j-1),(i+1,j),(i-1,j)]\n for coords in tests: \n x,y = coords\n if x in range(4) and y in range(4):\n if self.grid[i][j].value == self.grid[x][y].value:\n return True\n return False\n\n def game_over(self):\n for i in range(4):\n for j in range(4):\n if self.swips_test(i,j):\n return False\n return True\n\nif __name__ == '__main__':\n game = Grid()\n print(game.make_move('l'))\n print(game.make_move('u'))\n print(game.make_move('d'))\n print(game.make_move('r'))\n","sub_path":"2048/version1.0/grid.py","file_name":"grid.py","file_ext":"py","file_size_in_byte":5805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"231472501","text":"#!/usr/bin/env python3\n\n\"\"\"\nCreated on 27 Feb 2017\n\n@author: Bruno Beloff (bruno.beloff@southcoastscience.com)\n\nAct II of III: Calibration workflow:\n\n( 1: ./rtc.py -i -s -v )\n > 2: ./afe_calib -s AFE_SERIAL_NUMBER\n 3: ./pt1000_calib.py -s -v\n 4: ./afe_baseline.py -v -1 SN1_OFFSET -2 SN2_OFFSET -3 SN3_OFFSET -4 SN3_OFFSET\n\nCreates AFECalib document.\n\ncommand line example:\n./afe_calib.py -v -s 15-000064\n\"\"\"\n\nimport json\nimport sys\n\nfrom collections import OrderedDict\n\nfrom scs_core.data.json import JSONify\n\nfrom scs_core.gas.afe_calib import AFECalib\n\nfrom scs_host.client.http_client import HTTPClient\n\nfrom scs_host.sys.host import Host\n\nfrom scs_mfr.cmd.cmd_afe_calib import CmdAFECalib\n\n\n# --------------------------------------------------------------------------------------------------------------------\n\nif __name__ == '__main__':\n\n # ----------------------------------------------------------------------------------------------------------------\n # cmd...\n\n cmd = CmdAFECalib()\n\n if cmd.verbose:\n print(cmd, file=sys.stderr)\n sys.stderr.flush()\n\n\n # ----------------------------------------------------------------------------------------------------------------\n # run...\n\n if cmd.set():\n if cmd.test:\n jstr = AFECalib.TEST_JSON\n\n else:\n client = HTTPClient()\n client.connect(AFECalib.HOST)\n\n try:\n path = AFECalib.PATH + cmd.serial_number\n jstr = client.get(path, None, AFECalib.HEADER)\n\n finally:\n client.close()\n\n jdict = json.loads(jstr, object_pairs_hook=OrderedDict)\n\n calib = AFECalib.construct_from_jdict(jdict)\n\n if calib is not None:\n calib.save(Host)\n\n calib = AFECalib.load(Host)\n\n print(JSONify.dumps(calib))\n","sub_path":"scs_mfr/afe_calib.py","file_name":"afe_calib.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"353130416","text":"import pandas as pd\r\nimport numpy as np\r\nimport os\r\nfrom sklearn.model_selection import KFold\r\nimport datetime\r\nimport modelsFunc as models\r\n\r\npath = os.path.dirname(os.getcwd())\r\ntrain_queries = path + r'/Data/After Processing/train_queries_compacted_more.csv'\r\nvalidate_queries = path + r'/Data/After Processing/validation_queries_compacted_more.csv'\r\n\r\ntrain_data = pd.read_csv(train_queries)\r\nvalidate_data = pd.read_csv(validate_queries)\r\nprint(\"Successfully load the data\")\r\n\r\ntrain_y = train_data['stars_review']\r\nvalidate_y = validate_data['stars_review']\r\n\r\ntrain_data.drop('stars_review', axis = 1, inplace = True)\r\nvalidate_data.drop('stars_review', axis = 1, inplace = True)\r\n\r\ntrain_errors = list()\r\ntest_errors = list()\r\ncross_train_errors = list()\r\ncross_test_errors = list()\r\n\r\n##Run random forest using different number of components of PCA\r\n\"\"\"for i in range(510, 900, 50):\r\n selected_column = list(range(1, i))\r\n train_X = train_data[selected_column]\r\n validate_X = validate_data[selected_column]\r\n train_error, test_error = models.runRandomForest(train_X, train_y, validate_X, validate_y)\r\n train_errors.append(train_error)\r\n test_errors.append(test_error)\"\"\"\r\n\r\n##Run random forest using different max_depth\r\n\r\n#selected_column = list(range(1, 460))\r\ntrain_X = train_data#[selected_column]\r\nvalidate_X = validate_data#[selected_column]\r\nX = train_X.values\r\ny = train_y.values\r\n\r\nfor max_depth in range(1, 50):\r\n train_error, test_error, __ = models.runGradientBoostingRegressor(train_X, train_y, validate_X, validate_y, max_depth)\r\n cross_train_error, cross_test_error = 0, 0\r\n kf = KFold(n_splits = 5)\r\n for train_index, test_index in kf.split(X):\r\n temp_train_error, temp_test_error, _ = models.runGradientBoostingRegressor(X[train_index, : ], y[train_index], \\\r\n X[test_index, : ], y[test_index], max_depth)\r\n cross_train_error += temp_train_error\r\n cross_test_error += temp_test_error\r\n\r\n cross_train_error /= 5.0\r\n cross_test_error /= 5.0\r\n\r\n print(max_depth, \"*****\", cross_train_error)\r\n print(max_depth, \"*****\", cross_test_error)\r\n print(max_depth, \"*****\", train_error)\r\n print(max_depth, \"*****\", test_error)\r\n cross_train_errors.append(cross_train_error)\r\n cross_test_errors.append(cross_test_error)\r\n train_errors.append(train_error)\r\n test_errors.append(test_error)\r\n\r\nprint(cross_train_errors)\r\nprint(cross_test_errors)\r\nprint(train_errors)\r\nprint(test_errors)","sub_path":"runGradientBoostingRegressor_usingDifferentParameters.py","file_name":"runGradientBoostingRegressor_usingDifferentParameters.py","file_ext":"py","file_size_in_byte":2556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"284399031","text":"import json\n\nf = open('out/computer_science_hotword.txt', 'w', encoding='utf-8')\nclass treeNode:\n def __init__(self, nameValue, numOccur, parentNode):\n self.name = nameValue #节点名字\n self.count = numOccur #节点计数值\n self.nodeLink = None #用于链接相似的元素项\n self.parent = parentNode #needs to be updated\n self.children = {} #子节点\n\n def inc(self, numOccur):\n '''\n 对count变量增加给定值\n '''\n self.count += numOccur\n\n def disp(self, ind=1):\n '''\n 将树以文本形式展示\n '''\n print (' '*ind, self.name, ' ', self.count)\n for child in self.children.values():\n child.disp(ind+1)\n\n\n# FP树构建函数\ndef createTree(dataSet, minSup=1):\n '''\n 创建FP树\n '''\n headerTable = {}\n #第一次扫描数据集\n for trans in dataSet: #计算item出现频数\n for item in trans:\n headerTable[item] = headerTable.get(item, 0) + dataSet[trans]\n headerTable = {k:v for k,v in headerTable.items() if v >= minSup}\n freqItemSet = set(headerTable.keys())\n if len(freqItemSet) == 0: \n return None, None #如果没有元素项满足要求,则退出\n print ('freqItemSet: ',freqItemSet)\n for k in headerTable:\n headerTable[k] = [headerTable[k], None] #初始化headerTable\n # print ('headerTable: ',headerTable)\n #第二次扫描数据集\n retTree = treeNode('Null Set', 1, None) #创建树\n for tranSet, count in dataSet.items(): \n localD = {}\n for item in tranSet: #put transaction items in order\n if item in freqItemSet:\n localD[item] = headerTable[item][0]\n if len(localD) > 0:\n orderedItems = [v[0] for v in sorted(localD.items(), key=lambda p: p[1], reverse=True)]\n updateTree(orderedItems, retTree, headerTable, count) #将排序后的item集合填充的树中\n return retTree, headerTable #返回树型结构和头指针表\n\ndef updateTree(items, inTree, headerTable, count):\n if items[0] in inTree.children: #检查第一个元素项是否作为子节点存在\n inTree.children[items[0]].inc(count) #存在,更新计数\n else: #不存在,创建一个新的treeNode,将其作为一个新的子节点加入其中\n inTree.children[items[0]] = treeNode(items[0], count, inTree)\n if headerTable[items[0]][1] == None: #更新头指针表\n headerTable[items[0]][1] = inTree.children[items[0]]\n else:\n updateHeader(headerTable[items[0]][1], inTree.children[items[0]])\n if len(items) > 1: #不断迭代调用自身,每次调用都会删掉列表中的第一个元素\n updateTree(items[1::], inTree.children[items[0]], headerTable, count)\n\ndef updateHeader(nodeToTest, targetNode):\n '''\n this version does not use recursion\n Do not use recursion to traverse a linked list!\n 更新头指针表,确保节点链接指向树中该元素项的每一个实例\n '''\n while (nodeToTest.nodeLink != None): \n nodeToTest = nodeToTest.nodeLink\n nodeToTest.nodeLink = targetNode\n\n\n# 抽取条件模式基\ndef ascendTree(leafNode, prefixPath): #迭代上溯整棵树\n if leafNode.parent != None:\n prefixPath.append(leafNode.name)\n ascendTree(leafNode.parent, prefixPath)\n\ndef findPrefixPath(basePat, treeNode): #treeNode comes from header table\n condPats = {}\n while treeNode != None:\n prefixPath = []\n ascendTree(treeNode, prefixPath)\n if len(prefixPath) > 1: \n condPats[frozenset(prefixPath[1:])] = treeNode.count\n treeNode = treeNode.nodeLink\n return condPats\n\n\n# 递归查找频繁项集\ndef mineTree(inTree, headerTable, minSup, preFix, freqItemList):\n bigL = [v[0] for v in sorted(headerTable.items(), key=lambda p: p[1][0])]# 1.排序头指针表\n for basePat in bigL: #从头指针表的底端开始\n newFreqSet = preFix.copy()\n newFreqSet.add(basePat)\n f.write('频繁项: ' + str(newFreqSet) + '\\n')\n # print ('频繁项: ',newFreqSet) #添加的频繁项列表\n freqItemList.append(newFreqSet)\n condPattBases = findPrefixPath(basePat, headerTable[basePat][1])\n f.write('条件模式基 :'+str(condPattBases)+'\\n'+'\\n')\n # print ('条件模式基 :',basePat, condPattBases)\n # 2.从条件模式基创建条件FP树\n myCondTree, myHead = createTree(condPattBases, minSup)\n # print ('head from conditional tree: ', myHead)\n if myHead != None: # 3.挖掘条件FP树\n # print ('条件FP树 for: ',newFreqSet)\n # myCondTree.disp(1) \n mineTree(myCondTree, myHead, minSup, newFreqSet, freqItemList)\n\n\n# 测试\ndef loadSimpDat(year):\n load_f = open(\"computer_science_by_year.json\",'r')\n load_dict = json.load(load_f)\n simpDat = load_dict[year]\n return simpDat\n\ndef createInitSet(dataSet): \n retDict = {} \n for trans in dataSet: \n retDict[frozenset(trans)] = retDict.get(frozenset(trans), 0) + 1 #若没有相同事项,则为1;若有相同事项,则加1\n return retDict\n\nfor i in range(2000,2018):\n print(str(i))\n f.write('「年份: '+str(i)+'」\\n')\n minSup = 10\n simpDat = loadSimpDat(str(i))\n initSet = createInitSet(simpDat)\n # if i == 2001: print(initSet)\n myFPtree, myHeaderTab = createTree(initSet, minSup)\n # myFPtree.disp()\n myFreqList = []\n mineTree(myFPtree, myHeaderTab, minSup, set([]), myFreqList)\n","sub_path":"KEJSOMODEL/hot_word/fp-growth.py","file_name":"fp-growth.py","file_ext":"py","file_size_in_byte":5582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"220348318","text":"import datetime\nimport sys\n\n\nclass Automotora:\n\n def __init__(self, nombre):\n self.nombre = nombre\n self.sucursales = []\n\n def agregar_sucursal(self, sucursal):\n self.sucursales.append(sucursal)\n\n def cantidad_de_autos(self):\n suma = 0\n for pos in range(len(self.sucursales)):\n suma += len(self.sucursales[pos].autos_nuevos) + len(self.sucursales[pos].autos_usados)\n return suma\n\n def buscar_auto_id(self, id):\n id = int(id)\n for i in range(len(self.sucursales)):\n for j in range(len(self.sucursales[i].autos_nuevos)):\n if self.sucursales[i].autos_nuevos[j].id == id:\n return self.sucursales[i].autos_nuevos[j]\n for j in range(len(self.sucursales[i].autos_usados)):\n if self.sucursales[i].autos_usados[j].id == id:\n return self.sucursales[i].autos_usados[j]\n\n def autos_ano(self, minimo, maximo):\n lista = []\n for i in range(len(self.sucursales)):\n for j in range(len(self.sucursales[i].autos_usados)):\n if int(minimo) <= self.sucursales[i].autos_usados[j].ano <= int(maximo):\n lista.append(self.sucursales[i].autos_usados[j])\n for j in range(len(self.sucursales[i].autos_nuevos)):\n if int(minimo) <= self.sucursales[i].autos_nuevos[j].ano <= int(maximo):\n lista.append(self.sucursales[i].autos_nuevos[j])\n return lista\n\n def autos_precio(self, minimo, maximo):\n lista = []\n for i in range(len(self.sucursales)):\n for j in range(len(self.sucursales[i].autos_usados)):\n if int(minimo) <= self.sucursales[i].autos_usados[j].precio <= int(maximo):\n lista.append(self.sucursales[i].autos_usados[j])\n for j in range(len(self.sucursales[i].autos_nuevos)):\n if int(minimo) <= self.sucursales[i].autos_nuevos[j].precio <= int(maximo):\n lista.append(self.sucursales[i].autos_nuevos[j])\n return lista\n\n def autos_marca(self, marca):\n lista = []\n for i in range(len(self.sucursales)):\n for j in range(len(self.sucursales[i].autos_usados)):\n if self.sucursales[i].autos_usados[j].marca == marca:\n lista.append(self.sucursales[i].autos_usados[j])\n for j in range(len(self.sucursales[i].autos_nuevos)):\n if self.sucursales[i].autos_nuevos[j].marca == marca:\n lista.append(self.sucursales[i].autos_nuevos[j])\n return lista\n\n def autos_transmision(self, transmision):\n lista = []\n for i in range(len(self.sucursales)):\n for j in range(len(self.sucursales[i].autos_usados)):\n if self.sucursales[i].autos_usados[j].transmision == transmision:\n lista.append(self.sucursales[i].autos_usados[j])\n for j in range(len(self.sucursales[i].autos_nuevos)):\n if self.sucursales[i].autos_nuevos[j].transmision == transmision:\n lista.append(self.sucursales[i].autos_nuevos[j])\n return lista\n\n def autos_estado(self, estado):\n lista = []\n for i in range(len(self.sucursales)):\n for j in range(len(self.sucursales[i].autos_usados)):\n if self.sucursales[i].autos_usados[j].estado == estado:\n lista.append(self.sucursales[i].autos_usados[j])\n for j in range(len(self.sucursales[i].autos_nuevos)):\n if self.sucursales[i].autos_nuevos[j].estado == estado:\n lista.append(self.sucursales[i].autos_nuevos[j])\n return lista\n\n\nclass Sucursal:\n\n def __init__(self):\n self.autos_nuevos = []\n self.autos_usados = []\n\n def agregar_auto(self, auto):\n if auto.estado == 'usado':\n self.autos_usados.append(auto)\n else:\n self.autos_nuevos.append(auto)\n\n\nclass Auto:\n\n contador = 1\n\n def __init__(self, ano, precio, marca, transmision, estado, dueno=None):\n self.ano = ano\n self.marca = marca\n self.transmision = transmision\n self.id = Auto.contador\n self.estado = estado\n self.consultas = 0\n self._ultima_consulta = None\n self._precio = precio\n if dueno:\n self.dueno = dueno\n Auto.contador += 1\n\n @property\n def precio(self):\n return self._precio\n\n @precio.setter\n def precio(self, nuevo_precio):\n if int(nuevo_precio) % 500000 == 0:\n self._precio = nuevo_precio\n print(\"\\nEl precio fue cambiado exitosamente.\")\n else:\n print(\"\\nEl precio no pudo ser cambiado.\\nEl precio debe ser multiplo de 500.000\")\n\n @property\n def ultima_consulta(self):\n return self._ultima_consulta\n\n @ultima_consulta.setter\n def ultima_consulta(self, nueva_consulta):\n self._ultima_consulta = nueva_consulta\n\n def display(self):\n print(\"\\nID del auto = {0}\\n Año: {1}\\n Marca: {2}\\n Transmision: {3}\\n\"\n \" Estado: {4}\\n Precio: {5}\\n Numero de consultas previas: {6}\".\n format(self.id, self.ano, self.marca, self.transmision, self.estado, self.precio, self.consultas))\n if self.ultima_consulta:\n print(\" Ultima consulta: {}\".format(self.ultima_consulta))\n self.consultas += 1\n self.ultima_consulta = str(datetime.datetime.now())\n\n\nclass Persona:\n\n def __init__(self, nombre, rut, telefono, correo):\n self.nombre = nombre\n self.rut = rut\n self.telefono = telefono\n self.correo = correo\n\n\nautomotora = Automotora(\"Automovils Mavrakis\")\n\nsucursal_1 = Sucursal()\nsucursal_2 = Sucursal()\n\nThomas = Persona(\"Thomas\", 1111, 123, \"tibrah@uc.cl\")\nAndres = Persona(\"Andres\", 2222, 234, \"Andres@uc.cl\")\nSebastian = Persona(\"Sebastian\", 3333, 345, \"Sebastian@uc.cl\")\nFederico = Persona(\"Federico\", 4444, 456, \"Federico@uc.cl\")\nAgustin = Persona(\"Agustin\", 5555, 567, \"Agustin@uc.cl\")\nJoaquin = Persona(\"Joaquin\", 6666, 678, \"Joaquin@uc.cl\")\n\nauto_1 = Auto(2013, 25600900, \"Toyota\", \"AT\", \"usado\", Thomas)\nauto_2 = Auto(2012, 15500900, \"Honda\", \"MT\", \"usado\", Andres)\nauto_3 = Auto(2015, 17900900, \"Jeep\", \"MT\", \"usado\", Sebastian)\nauto_4 = Auto(2014, 12200900, \"Kia\", \"MT\", \"usado\", Federico)\nauto_5 = Auto(2016, 57900900, \"Lexus\", \"AT\", \"usado\", Agustin)\nauto_6 = Auto(2011, 990000, \"Nissan\", \"MT\", \"usado\", Joaquin)\nauto_7 = Auto(2016, 27900900, \"Volvo\", \"AT\", \"nuevo\")\nauto_8 = Auto(2015, 16900900, \"Toyota\", \"MT\", \"nuevo\")\nauto_9 = Auto(2014, 19900900, \"Hyundai\", \"MT\", \"nuevo\")\nauto_10 = Auto(2013, 67900900, \"Range Rover\", \"AT\", \"nuevo\")\nauto_11 = Auto(2012, 14900900, \"Opel\", \"MT\", \"nuevo\")\nauto_12 = Auto(2011, 22900900, \"Honda\", \"AT\", \"nuevo\")\n\nsucursal_1.agregar_auto(auto_1)\nsucursal_1.agregar_auto(auto_2)\nsucursal_1.agregar_auto(auto_3)\nsucursal_1.agregar_auto(auto_7)\nsucursal_1.agregar_auto(auto_8)\nsucursal_1.agregar_auto(auto_9)\nsucursal_2.agregar_auto(auto_4)\nsucursal_2.agregar_auto(auto_5)\nsucursal_2.agregar_auto(auto_6)\nsucursal_2.agregar_auto(auto_10)\nsucursal_2.agregar_auto(auto_11)\nsucursal_2.agregar_auto(auto_12)\n\nautomotora.agregar_sucursal(sucursal_1)\nautomotora.agregar_sucursal(sucursal_2)\n\n\nif __name__ == \"__main__\":\n respuesta = 0\n while respuesta != 3:\n respuesta = input(\"\\nUsted desea :\\n\"\n \" 1. Ingresar como funcionario\\n\"\n \" 2. Ingresar como cliente\\n\"\n \" 3. Salir\\n\"\n \"Su opcion es: \")\n\n if respuesta == \"1\":\n respuesta2 = 0\n while respuesta2 != 3:\n respuesta2 = input(\"\\nUsted desea:\\n\"\n \" 1. Cambiar de precio\\n\"\n \" 2. Consultar total de autos\\n\"\n \" 3. Volver a menu principal\\n\"\n \"Su opcion es: \")\n\n if respuesta2 == \"1\":\n id = input(\"\\nIngrese el id del auto que desea modificar: \")\n precio = input(\"\\nIngrese el nuevo precio: \")\n auto = automotora.buscar_auto_id(id)\n if auto:\n auto.precio = precio\n else:\n print(\"\\nEse id no corresponde a ningun auto.\")\n\n elif respuesta2 == \"2\":\n print(\"\\nEl total de autos es {}.\".format(automotora.cantidad_de_autos()))\n\n elif respuesta2 ==\"3\":\n break\n\n else:\n print(\"\\nIngrese una opcion valida.\")\n\n elif respuesta == \"2\":\n opcion = 0\n while opcion != \"6\":\n\n opcion = input(\"\\nMostrar autos segun:\\n\"\n \" 1. Ano\\n\"\n \" 2. Precio\\n\"\n \" 3. Marca\\n\"\n \" 4. Transmision\\n\"\n \" 5. Estado\\n\"\n \" 6. Volver a menu principal\\n\"\n \"Su opcion es: \")\n\n if opcion == \"1\":\n minimo = input(\"\\nIngrese ano minimo: \")\n maximo = input(\"\\nIngrese ano maximo: \")\n autos = automotora.autos_ano(minimo, maximo)\n if len(autos) == 0:\n print(\"\\nNo hay autos en ese rango de ano.\")\n else:\n for i in autos:\n i.display()\n\n elif opcion == \"2\":\n minimo = input(\"\\nIngrese precio minimo: \")\n maximo = input(\"\\nIngrese precio maximo: \")\n autos = automotora.autos_precio(minimo, maximo)\n if len(autos) == 0:\n print(\"\\nNo hay autos en ese rango de precio.\")\n else:\n for i in autos:\n i.display()\n\n elif opcion == \"3\":\n marca = input(\"\\nIngrese marca: \")\n autos = automotora.autos_marca(marca)\n if len(autos) == 0:\n print(\"\\nNo hay autos de esa marca.\")\n else:\n for i in autos:\n i.display()\n\n elif opcion == \"4\":\n transmision = input(\"\\nIngrese transmision: \")\n if transmision == \"MT\" or transmision == \"AT\":\n autos = automotora.autos_transmision(transmision)\n if len(autos) == 0:\n print(\"\\nNo hay autos de esa transmision.\")\n else:\n for i in autos:\n i.display()\n else:\n print(\"\\nDebe ingresar una transmision valida: AT o MT.\")\n\n elif opcion == \"5\":\n estado = input(\"\\nIngrese estado: \")\n if estado == \"nuevo\" or estado == \"usado\":\n autos = automotora.autos_estado(estado)\n if len(autos) == 0:\n print(\"\\nNo hay autos en ese estado.\")\n else:\n for i in autos:\n i.display()\n else:\n print(\"\\nDebe ingresar un estado valido: usado o nuevo.\")\n\n elif opcion == \"6\":\n break\n\n else:\n print(\"\\nDebe ingresar una opcion valida.\")\n\n elif respuesta == \"3\":\n sys.exit(0)\n\n else:\n print(\"\\nNo es una respuesta valida.\"\n \"Usted debe elgir el numero de una opcion.\")\n","sub_path":"Practica AC1/actividad1_version_propia.py","file_name":"actividad1_version_propia.py","file_ext":"py","file_size_in_byte":11937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"353541745","text":"import sys\nimport os\n\nos.system(\"cls\")\n\nprint(\"E = hv\")\n\n#prompt the user for wavelength\nwavelength = float(input(\"Wavelength(nm): \"))\n\nwavelength *= (10^-9)\n\n#define constants\nh = 6.626 * (10^-34)\t#Planck's Constant\nc = 3 * (10^8)\t\t\t#Speed of Light\n\n#calculate frequency\nf = c/wavelength\n\n#calculate energy\ne = h * f\n\nprint(\"F = \",f,\" Hz\")\nprint(\"E = \",e,\" Joules\")","sub_path":"quantizeEnergy.py","file_name":"quantizeEnergy.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"366250996","text":"import math\n\ndef bank(a, years):\n\tfor i in range(0,years):\n\t\ta = a*1.1\n\treturn(math.ceil(a))\n\nwhile True:\n\ta=int(input(\"Какое количество денег вы вносите?\"))\n\tyears=int(input(\"На сколько лет вы вносите эти деньги?\"))\n\tprint(bank(a, years))\n\tx=str(input(\"Введите 'выйти' чтобы выйти из программы\"))\n\tif x==\"выйти\":\n\t\tbreak","sub_path":"bank(ru).py","file_name":"bank(ru).py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"506762833","text":"import pyaudio\r\nimport sys\r\nimport wave\r\nimport numpy as np\r\nimport os\r\nimport time\r\nimport contextlib\r\n\r\n\r\n@contextlib.contextmanager\r\ndef ignore_stderr(path,index,time):\r\n devnull = os.open(os.devnull, os.O_WRONLY)\r\n old_stderr = os.dup(2)\r\n sys.stderr.flush()\r\n os.dup2(devnull, 2)\r\n os.close(devnull)\r\n try:\r\n recordaudio(path, index, time)\r\n finally:\r\n os.dup2(old_stderr, 2)\r\n os.close(old_stderr)\r\n\r\ndef recordaudio(path, index, time):\r\n PATH = path\r\n\r\n RESPEAKER_RATE = 48000\r\n RESPEAKER_CHANNELS = 8\r\n RESPEAKER_WIDTH = 2\r\n # run getDeviceInfo.py to get index\r\n RESPEAKER_INDEX = int(index) #0,0; 2 refer to input device id\r\n CHUNK = 1024\r\n RECORD_SECONDS = int(time) # reset:5; detect:3\r\n WAVE_OUTPUT_FILENAME = []\r\n\r\n for i in range(6):\r\n WAVE_OUTPUT_FILENAME.append([])\r\n\r\n for i in range(6):\r\n WAVE_OUTPUT_FILENAME[i]=''.join([PATH,\"/mic\",str(i+1),\".wav\"])\r\n\r\n p = pyaudio.PyAudio()\r\n\r\n stream = p.open(\r\n rate=RESPEAKER_RATE,\r\n format=p.get_format_from_width(RESPEAKER_WIDTH),\r\n channels=RESPEAKER_CHANNELS,\r\n input=True,\r\n input_device_index=RESPEAKER_INDEX,)\r\n\r\n #print(\"* recording\")\r\n\r\n frames = []\r\n for i in range(6):\r\n frames.append([])\r\n\r\n for i in range(0, int(RESPEAKER_RATE / CHUNK * RECORD_SECONDS)):\r\n data = stream.read(CHUNK)\r\n # extract channel 0 data from 8 channels, if you want to extract channel 1, please change to [1::8]\r\n for j in range(6):\r\n x=np.frombuffer(data,dtype=np.int16)[j::8]\r\n frames[j].append(x.tostring())\r\n \r\n #print(\"* done recording\")\r\n\r\n stream.stop_stream()\r\n stream.close()\r\n p.terminate()\r\n\r\n for i in range(6):\r\n wf = wave.open(WAVE_OUTPUT_FILENAME[i], 'wb')\r\n wf.setnchannels(1)\r\n wf.setsampwidth(p.get_sample_size(p.get_format_from_width(RESPEAKER_WIDTH)))\r\n wf.setframerate(RESPEAKER_RATE)\r\n wf.writeframes(b''.join(frames[i]))\r\n wf.close()\r\n print('OK')\r\n return 'OK'\r\n\r\nif __name__==\"__main__\":\r\n ignore_stderr('Empty',0, 5)#sys.argv[1], sys.argv[2])\r\n #if sys.argv[1]=='None':\r\n # time.sleep(int(sys.argv[3]))\r\n #else:\r\n #ignore_stderr(sys.argv[1], sys.argv[2], sys.argv[3])#'Barrier/barrier',2,3)#\r\n #sys.exit(recordaudio('Empty',2))\r\n\r\n\r\n\r\n","sub_path":"Client/record.py","file_name":"record.py","file_ext":"py","file_size_in_byte":2406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"557044104","text":"import asyncio\n\nimport pytest\n\nfrom starlette.requests import ClientDisconnect, Request\nfrom starlette.responses import JSONResponse, Response\nfrom starlette.testclient import TestClient\n\n\ndef test_request_url():\n async def app(scope, receive, send):\n request = Request(scope, receive)\n data = {\"method\": request.method, \"url\": str(request.url)}\n response = JSONResponse(data)\n await response(scope, receive, send)\n\n client = TestClient(app)\n response = client.get(\"/123?a=abc\")\n assert response.json() == {\"method\": \"GET\", \"url\": \"http://testserver/123?a=abc\"}\n\n response = client.get(\"https://example.org:123/\")\n assert response.json() == {\"method\": \"GET\", \"url\": \"https://example.org:123/\"}\n\n\ndef test_request_query_params():\n async def app(scope, receive, send):\n request = Request(scope, receive)\n params = dict(request.query_params)\n response = JSONResponse({\"params\": params})\n await response(scope, receive, send)\n\n client = TestClient(app)\n response = client.get(\"/?a=123&b=456\")\n assert response.json() == {\"params\": {\"a\": \"123\", \"b\": \"456\"}}\n\n\ndef test_request_headers():\n async def app(scope, receive, send):\n request = Request(scope, receive)\n headers = dict(request.headers)\n response = JSONResponse({\"headers\": headers})\n await response(scope, receive, send)\n\n client = TestClient(app)\n response = client.get(\"/\", headers={\"host\": \"example.org\"})\n assert response.json() == {\n \"headers\": {\n \"host\": \"example.org\",\n \"user-agent\": \"testclient\",\n \"accept-encoding\": \"gzip, deflate\",\n \"accept\": \"*/*\",\n \"connection\": \"keep-alive\",\n }\n }\n\n\ndef test_request_client():\n async def app(scope, receive, send):\n request = Request(scope, receive)\n response = JSONResponse(\n {\"host\": request.client.host, \"port\": request.client.port}\n )\n await response(scope, receive, send)\n\n client = TestClient(app)\n response = client.get(\"/\")\n assert response.json() == {\"host\": \"testclient\", \"port\": 50000}\n\n\ndef test_request_body():\n async def app(scope, receive, send):\n request = Request(scope, receive)\n body = await request.body()\n response = JSONResponse({\"body\": body.decode()})\n await response(scope, receive, send)\n\n client = TestClient(app)\n\n response = client.get(\"/\")\n assert response.json() == {\"body\": \"\"}\n\n response = client.post(\"/\", json={\"a\": \"123\"})\n assert response.json() == {\"body\": '{\"a\": \"123\"}'}\n\n response = client.post(\"/\", data=\"abc\")\n assert response.json() == {\"body\": \"abc\"}\n\n\ndef test_request_stream():\n async def app(scope, receive, send):\n request = Request(scope, receive)\n body = b\"\"\n async for chunk in request.stream():\n body += chunk\n response = JSONResponse({\"body\": body.decode()})\n await response(scope, receive, send)\n\n client = TestClient(app)\n\n response = client.get(\"/\")\n assert response.json() == {\"body\": \"\"}\n\n response = client.post(\"/\", json={\"a\": \"123\"})\n assert response.json() == {\"body\": '{\"a\": \"123\"}'}\n\n response = client.post(\"/\", data=\"abc\")\n assert response.json() == {\"body\": \"abc\"}\n\n\ndef test_request_form_urlencoded():\n async def app(scope, receive, send):\n request = Request(scope, receive)\n form = await request.form()\n response = JSONResponse({\"form\": dict(form)})\n await response(scope, receive, send)\n\n client = TestClient(app)\n\n response = client.post(\"/\", data={\"abc\": \"123 @\"})\n assert response.json() == {\"form\": {\"abc\": \"123 @\"}}\n\n\ndef test_request_body_then_stream():\n async def app(scope, receive, send):\n request = Request(scope, receive)\n body = await request.body()\n chunks = b\"\"\n async for chunk in request.stream():\n chunks += chunk\n response = JSONResponse({\"body\": body.decode(), \"stream\": chunks.decode()})\n await response(scope, receive, send)\n\n client = TestClient(app)\n\n response = client.post(\"/\", data=\"abc\")\n assert response.json() == {\"body\": \"abc\", \"stream\": \"abc\"}\n\n\ndef test_request_stream_then_body():\n async def app(scope, receive, send):\n request = Request(scope, receive)\n chunks = b\"\"\n async for chunk in request.stream():\n chunks += chunk\n try:\n body = await request.body()\n except RuntimeError:\n body = b\"\"\n response = JSONResponse({\"body\": body.decode(), \"stream\": chunks.decode()})\n await response(scope, receive, send)\n\n client = TestClient(app)\n\n response = client.post(\"/\", data=\"abc\")\n assert response.json() == {\"body\": \"\", \"stream\": \"abc\"}\n\n\ndef test_request_json():\n async def app(scope, receive, send):\n request = Request(scope, receive)\n data = await request.json()\n response = JSONResponse({\"json\": data})\n await response(scope, receive, send)\n\n client = TestClient(app)\n response = client.post(\"/\", json={\"a\": \"123\"})\n assert response.json() == {\"json\": {\"a\": \"123\"}}\n\n\ndef test_request_scope_interface():\n \"\"\"\n A Request can be instantiated with a scope, and presents a `Mapping`\n interface.\n \"\"\"\n request = Request({\"type\": \"http\", \"method\": \"GET\", \"path\": \"/abc/\"})\n assert request[\"method\"] == \"GET\"\n assert dict(request) == {\"type\": \"http\", \"method\": \"GET\", \"path\": \"/abc/\"}\n assert len(request) == 3\n\n\ndef test_request_without_setting_receive():\n \"\"\"\n If Request is instantiated without the receive channel, then .body()\n is not available.\n \"\"\"\n\n async def app(scope, receive, send):\n request = Request(scope)\n try:\n data = await request.json()\n except RuntimeError:\n data = \"Receive channel not available\"\n response = JSONResponse({\"json\": data})\n await response(scope, receive, send)\n\n client = TestClient(app)\n response = client.post(\"/\", json={\"a\": \"123\"})\n assert response.json() == {\"json\": \"Receive channel not available\"}\n\n\ndef test_request_disconnect():\n \"\"\"\n If a client disconnect occurs while reading request body\n then ClientDisconnect should be raised.\n \"\"\"\n\n async def app(scope, receive, send):\n request = Request(scope, receive)\n await request.body()\n\n async def receiver():\n return {\"type\": \"http.disconnect\"}\n\n scope = {\"type\": \"http\", \"method\": \"POST\", \"path\": \"/\"}\n loop = asyncio.get_event_loop()\n with pytest.raises(ClientDisconnect):\n loop.run_until_complete(app(scope, receiver, None))\n\n\ndef test_request_is_disconnected():\n \"\"\"\n If a client disconnect occurs while reading request body\n then ClientDisconnect should be raised.\n \"\"\"\n disconnected_after_response = None\n\n async def app(scope, receive, send):\n nonlocal disconnected_after_response\n\n request = Request(scope, receive)\n await request.body()\n disconnected = await request.is_disconnected()\n response = JSONResponse({\"disconnected\": disconnected})\n await response(scope, receive, send)\n disconnected_after_response = await request.is_disconnected()\n\n client = TestClient(app)\n response = client.get(\"/\")\n assert response.json() == {\"disconnected\": False}\n assert disconnected_after_response\n\n\ndef test_request_state():\n async def app(scope, receive, send):\n request = Request(scope, receive)\n request.state.example = 123\n response = JSONResponse({\"state.example\": request[\"state\"].example})\n await response(scope, receive, send)\n\n client = TestClient(app)\n response = client.get(\"/123?a=abc\")\n assert response.json() == {\"state.example\": 123}\n\n\ndef test_request_cookies():\n async def app(scope, receive, send):\n request = Request(scope, receive)\n mycookie = request.cookies.get(\"mycookie\")\n if mycookie:\n response = Response(mycookie, media_type=\"text/plain\")\n else:\n response = Response(\"Hello, world!\", media_type=\"text/plain\")\n response.set_cookie(\"mycookie\", \"Hello, cookies!\")\n\n await response(scope, receive, send)\n\n client = TestClient(app)\n response = client.get(\"/\")\n assert response.text == \"Hello, world!\"\n response = client.get(\"/\")\n assert response.text == \"Hello, cookies!\"\n\n\ndef test_chunked_encoding():\n async def app(scope, receive, send):\n request = Request(scope, receive)\n body = await request.body()\n response = JSONResponse({\"body\": body.decode()})\n await response(scope, receive, send)\n\n client = TestClient(app)\n\n def post_body():\n yield b\"foo\"\n yield \"bar\"\n\n response = client.post(\"/\", data=post_body())\n assert response.json() == {\"body\": \"foobar\"}\n","sub_path":"tests/test_requests.py","file_name":"test_requests.py","file_ext":"py","file_size_in_byte":8936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"346854157","text":"from bs4 import BeautifulSoup\nimport requests\nimport time\n\ndef modi_bowling():\n source = requests.get('https://www.icc-cricket.com/rankings/mens/player-rankings/odi/bowling').text\n soup = BeautifulSoup(source, 'lxml')\n main_div = soup.find('div', class_ = 'rankings-block__container full')\n modi_bowling = [[] for _ in range(100)]\n first = main_div.find('tr', class_ = 'rankings-block__banner')\n first_rank = first.find('td', class_ = 'rankings-block__position').find('span', class_ = 'rankings-block__pos-number').text.replace(' ', '').replace('\\n', '')\n player = first.find('td', class_ = 'rankings-block__top-player-container').find('div', class_ = 'rankings-block__banner--name-large').text\n team = first.find('div', class_ = 'rankings-block__banner--nationality').text.replace(' ', '').replace('\\n', '')\n\n rating = first.find('div', class_ = 'rankings-block__banner--rating').text\n modi_bowling[0].extend([first_rank, player, team, rating])\n i = 1\n for other in main_div.find_all('tr', class_ = 'table-body'):\n rank = other.find('span', class_ = 'rankings-table__pos-number').text.replace(' ', '').replace('\\n', '')\n name = other.find('td', class_ = 'table-body__cell rankings-table__name name').text.replace('\\n', '')\n team = other.find('span', class_ = 'table-body__logo-text').text\n rating = other.find('td', class_ = 'table-body__cell rating').text\n modi_bowling[i].extend([rank, name, team, rating])\n i += 1\n\n for bowlers in modi_bowling:\n print(bowlers)\n #return modi_batting\n\nif __name__ == '__main__':\n while True:\n modi_bowling()\n wait_time = 1\n print(f'\\nWaiting {wait_time} minute before fetching Mens ODI Bowling Rankings again...\\n')\n time.sleep(wait_time * 60)\n","sub_path":"cricbuzz/rankings/Mens/modi_bowling.py","file_name":"modi_bowling.py","file_ext":"py","file_size_in_byte":1802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"462293097","text":"import os\r\nimport subprocess\r\nfrom subprocess import Popen, PIPE\r\nfrom machines import *\r\n\r\n\r\nif(HA):\r\n\tprint(\"HA Environmet\")\r\n\tmlist=m_list1\r\nelse:\r\n\tprint(\"Non-HA Environment\")\r\n\tmlist=m_list2\r\n\r\nprint (mlist)\r\n\r\n\r\nos.chdir('/etc')\r\nif os.path.isfile('/etc/exports'):\r\n\tprint(\"Editing /etc/exports\")\r\nelse:\r\n\tsubprocess.call(\"touch exports\",shell=True)\r\n\tprint(\"Created exports....Editing exports\")\r\n\r\ntry:\t\r\n\twith open('/etc/exports','r') as myfile:\r\n\t\tlines=myfile.read()\r\n\r\n\tif(lines.find('/u02 '+mlist[0]+'(rw,sync,no_root_squash)')+1):\r\n\t\tprint(\"/etc/exports already edited\")\r\n\telse:\r\n\t\twith open('/etc/exports','a') as myfile:\r\n\t\t\tprint(\"Editing exports file\")\r\n\t\t\tfor m in mlist:\r\n\t\t\t\tmyfile.write('/u02 '+m+'(rw,sync,no_root_squash)\\n')\r\nexcept OSError as e:\r\n\tprint (e)\r\n\texit()\r\n\r\ntry:\r\n\tsubprocess.call('service nfs restart',shell=True)\r\n\tsubprocess.call('service nfs status',shell=True)\r\nexcept OSError as e:\r\n\tprint (e)\r\n\texit()\r\n\r\n\r\nprint(\"Copy the command and run in all the nodes-- IDM, App01,App02,App03\\n\\nmount -t nfs \"+nfs+\":/u02 /u02\\n\\n\")","sub_path":"nfs.py","file_name":"nfs.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"160267464","text":"import random\n\nlist = []\n\nfor counter in range(10):\n list.append(random.randint(1, 100))\n\nsmaller = list[0]\nbigger = list[0]\n\nfor number in list:\n if number < smaller:\n smaller = number\n\n if number > bigger:\n bigger = number\n\nlist.sort()\n\nprint('List: %s' %list)\nprint('Smaller: %d' %smaller)\nprint('Bigger: %d' %bigger)\n","sub_path":"list-04/question-01.py","file_name":"question-01.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"209163062","text":"# -*- coding: utf-8 -*-\n#! usr/bin/env python3\n\"\"\"Interface constants.\n\"\"\"\nfrom engine.elements import *\n\n\nINTERFACE_ELEMENTS = {\n 'frame' : Frame, # Non-updating interface element\n 'window': Window, # Updating frame\n 'button': Button, # Togglable window element\n 'menu' : Menu, # Window with references to buttons\n}\n","sub_path":"engine/interface/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"29981768","text":"from api import Benchmark\nimport numpy as np\n\n\ndef cut_data(data, cut_position):\n targets = []\n for dp in data:\n targets.append(dp[\"Train/val_accuracy\"][50])\n for tag in dp:\n if tag.startswith(\"Train/\"):\n dp[tag] = dp[tag][0:cut_position]\n return data, targets\n\ndef read_data(bench_dir, dataset_name):\n bench = Benchmark(bench_dir, cache=False)\n dataset_name = 'Fashion-MNIST'\n n_configs = bench.get_number_of_configs(dataset_name)\n # Query API\n data = []\n for config_id in range(n_configs):\n data_point = dict()\n data_point[\"config\"] = bench.query(dataset_name=dataset_name, tag=\"config\", config_id=config_id)\n for tag in bench.get_queriable_tags(dataset_name=dataset_name, config_id=config_id):\n if tag.startswith(\"Train/\"):\n data_point[tag] = bench.query(dataset_name=dataset_name, tag=tag, config_id=config_id) \n data.append(data_point)\n \n # Split: 50% train, 25% validation, 25% test (the data is already shuffled)\n indices = np.arange(n_configs)\n ind_train = indices[0:int(np.floor(0.5*n_configs))]\n ind_val = indices[int(np.floor(0.5*n_configs)):int(np.floor(0.75*n_configs))]\n ind_test = indices[int(np.floor(0.75*n_configs)):]\n\n array_data = np.array(data)\n train_data = array_data[ind_train]\n val_data = array_data[ind_val]\n test_data = array_data[ind_test]\n \n # Cut curves for validation and test\n cut_position = 11\n val_data, val_targets = cut_data(val_data, cut_position)\n test_data, test_targets = cut_data(test_data, cut_position)\n train_data, train_targets = cut_data(train_data, 51) # Cut last value as it is repeated\n \n return train_data, val_data, test_data, train_targets, val_targets, test_targets\n\n\ndef remove_uninformative_features(train_data): \n store_config = {}\n informative_config = {}\n uninformative_config = {}\n\n for indx in range(len(train_data)):\n for value, key in train_data[indx][\"config\"].items():\n store_config[value] = []\n print(\"Seeking for uninformative data...\")\n print()\n\n for value in store_config:\n for i in range(len(train_data)):\n for value_inner, key in train_data[i][\"config\"].items():\n store_config[value_inner].append(key)\n\n nTemp = store_config[value][0]\n bEqual = True\n for item in store_config[value]:\n if nTemp != item:\n bEqual = False\n break;\n if bEqual:\n print(\"All elements in list \"+value+\" are EQUAL\")\n uninformative_config[value] = store_config[value]\n else:\n print(\"All elements in list \"+value+\" are different\")\n informative_config[value] = store_config[value]\n\n print()\n print(\"Only \"+str(len(informative_config))+\"/\"+str(len(store_config))+\" parameters are informative.\")\n print(\"Removing uninformative parameters from dataset...\") \n train_data_clean = train_data.copy()\n for i in range(len(train_data)):\n for value, key in uninformative_config.items():\n train_data_clean[i][\"config\"].pop(value)\n \n return train_data_clean\n","sub_path":"utils/data_engineering.py","file_name":"data_engineering.py","file_ext":"py","file_size_in_byte":3216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"642537634","text":"\"\"\"drabinajakubowa URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url, include\nfrom django.contrib import admin\nfrom . import settings\nfrom django.contrib.staticfiles.urls import static\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^', include('dj.urls')),\n url(r'^koordynator/', include('coordinatepanel.urls')),\n url(r'^koordynator-domu/', include('homepanel.urls')),\n url(r'^captcha/', include('captcha.urls')),\n]\n\nurlpatterns += staticfiles_urlpatterns()\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n\nhandler400 = 'dj.views.bad_request'\nhandler403 = 'dj.views.permission_denied'\nhandler404 = 'dj.views.page_not_found'\nhandler500 = 'dj.views.server_error'\n","sub_path":"drabinajakubowa/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"421950173","text":"import turtle\r\namy = turtle.Turtle()\r\namy.color(\"red\")\r\n\r\nfor side in [1, 2, 3, 4,5,7,8,9,10]:\r\n amy.forward(100)\r\n amy.left(160)\r\n # 135 loop 8 times\r\n # 72 loop 5 times\r\n # 60 loop 6 times","sub_path":"Test-3.py","file_name":"Test-3.py","file_ext":"py","file_size_in_byte":205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"95976584","text":"from fastapi import APIRouter, WebSocket, WebSocketDisconnect, Depends\nfrom app.api import deps\nfrom app.core import listeners\n\nfrom uuid import UUID\nimport asyncio\nimport warnings\n\nrouter = APIRouter()\n\n\n@router.websocket(\"/ws/\")\nasync def websocket_endpoint(\n websocket: WebSocket,\n object_update_listener: listeners.ObjectUpdateListener = Depends(\n deps.get_object_update_listener\n ),\n) -> None:\n await websocket.accept()\n connection_id = object_update_listener.connect(websocket)\n await websocket.send_json({\"connected\": True})\n\n try:\n while True:\n await websocket.receive_json()\n except WebSocketDisconnect:\n object_update_listener.disconnect(connection_id)\n","sub_path":"app/api/routes/updates.py","file_name":"updates.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"342295695","text":"from logging import getLogger\nimport matplotlib.pyplot as plt\n\nfrom config import Config\n\nlogger = getLogger(__name__)\n\nclass Visualize:\n def __init__(self, config: Config):\n self.config = config\n self.fig_realtime = plt.figure(figsize=(10.,7.5))\n self.ax_loss = self.fig_realtime.add_subplot(231)\n if config.trainer.is_accuracy: self.ax_accuracy = self.fig_realtime.add_subplot(232)\n self.ax_params = self.fig_realtime.add_subplot(233)\n self.ax_alpha = self.fig_realtime.add_subplot(234)\n self.ax_beta = self.fig_realtime.add_subplot(235)\n self.ax_gamma = self.fig_realtime.add_subplot(236)\n self.cmap_alpha = plt.get_cmap(\"Reds\")\n self.cmap_beta = plt.get_cmap(\"Blues\")\n self.cmap_gamma = plt.get_cmap(\"Greens\")\n self.label = ['Train', 'Validation']\n \n def plot_realtime(self, t, params, losses, accuracies=None):\n alpha, beta, gamma = params\n epoch = [i for i in range(1, len(losses[0])+1)]\n self.ax_loss.cla()\n for i, loss in enumerate(losses):\n self.ax_loss.plot(epoch, loss, label=self.label[i])\n self.ax_loss.set_xlabel('Epoch')\n self.ax_loss.set_ylabel('Loss')\n self.ax_loss.set_title('Loss')\n self.ax_loss.legend()\n if accuracies is not None:\n self.ax_accuracy.cla()\n for i, accuracy in enumerate(accuracies):\n self.ax_accuracy.plot(epoch, accuracy, label=self.label[i])\n self.ax_accuracy.set_xlabel('Epoch')\n self.ax_accuracy.set_ylabel('Accuracy')\n self.ax_accuracy.set_title('Accuracy')\n self.ax_accuracy.legend()\n self.ax_params.cla()\n self.ax_alpha.cla()\n for i in range(len(alpha[0])):\n nc = (float(i) / (2 * len(alpha[0]))) + 0.5\n self.ax_alpha.plot(t, alpha[:,i], label=r'$\\alpha_{}(t)$'.format(i), c=self.cmap_alpha(nc))\n self.ax_params.plot(t, alpha[:,i], label=r'$\\alpha_{}(t)$'.format(i), c=self.cmap_alpha(nc))\n self.ax_alpha.set_xlabel('t')\n self.ax_alpha.set_ylabel(r'$\\alpha(t)$')\n self.ax_alpha.set_title(r'$\\alpha(t)$')\n #self.ax_alpha.legend()\n self.ax_beta.cla()\n for i in range(len(beta[0])):\n for j in range(len(beta[0,0])):\n nc = (float(i * len(beta[0,0]) + j) / (2 * len(beta[0]) * len(beta[0,0]))) + 0.5\n self.ax_beta.plot(t, beta[:, i, j], label=r'$\\beta_{}$$_{}(t)$'.format(i, j), c=self.cmap_beta(nc))\n self.ax_params.plot(t, beta[:, i, j], label=r'$\\beta_{}$$_{}(t)$'.format(i, j), c=self.cmap_beta(nc))\n self.ax_beta.set_xlabel('t')\n self.ax_beta.set_ylabel(r'$\\beta(t)$')\n self.ax_beta.set_title(r'$\\beta(t)$')\n #self.ax_beta.legend()\n self.ax_gamma.cla()\n for i in range(len(gamma[0])):\n nc = (float(i) / (2 * len(gamma[0]))) + 0.5\n self.ax_gamma.plot(t, gamma[:,i], label=r'$\\gamma_{}(t)$'.format(i), c=self.cmap_gamma(nc))\n self.ax_params.plot(t, gamma[:,i], label=r'$\\gamma_{}(t)$'.format(i), c=self.cmap_gamma(nc))\n self.ax_gamma.set_xlabel('t')\n self.ax_gamma.set_ylabel(r'$\\gamma(t)$')\n self.ax_gamma.set_title(r'$\\gamma(t)$')\n #self.ax_gamma.legend()\n self.ax_params.set_xlabel('t')\n self.ax_params.set_title('Parameter')\n #self.ax_params.legend()\n self.fig_realtime.tight_layout()\n self.fig_realtime.suptitle('Epoch: {}'.format(epoch[-1]))\n self.fig_realtime.subplots_adjust(top=0.92)\n plt.draw()\n plt.pause(0.0000000001)\n \n def save_plot_loss(self, losses, xlabel=None, ylabel=None, title=None, save_file=None):\n plt.clf()\n epoch = [i for i in range(len(losses[0]))]\n if xlabel is not None: plt.xlabel(xlabel)\n if ylabel is not None: plt.ylabel(ylabel)\n if title is not None: plt.title(title)\n for i, loss in enumerate(losses):\n plt.plot(epoch, loss, label=self.label[i])\n plt.legend()\n if save_file is None:\n plt.show()\n else:\n logger.debug(\"save plot of loss to {}\".format(save_file))\n plt.savefig(save_file)\n \n def save_plot_accuracy(self, accuracies, xlabel=None, ylabel=None, title=None, save_file=None):\n plt.cla()\n if not self.config.trainer.is_accuracy: return\n epoch = [i for i in range(len(accuracies[0]))]\n if xlabel is not None: plt.xlabel(xlabel)\n if ylabel is not None: plt.ylabel(ylabel)\n if title is not None: plt.title(title)\n for i, accuracy in enumerate(accuracies):\n plt.plot(epoch, accuracy, label=self.label[i])\n plt.legend()\n if save_file is None:\n plt.show()\n else:\n logger.debug(\"save plot of accuracy to {}\".format(save_file))\n plt.savefig(save_file)\n \n def save_plot_params(self, t, params, save_file=None):\n plt.cla()\n alpha, beta, gamma = params\n fig_alpha = plt.figure()\n ax_alpha = fig_alpha.add_subplot(111)\n ax_alpha.set_xlabel(\"t\")\n ax_alpha.set_ylabel(r'$\\alpha(t)$')\n fig_beta = plt.figure()\n ax_beta = fig_beta.add_subplot(111)\n ax_beta.set_xlabel(\"t\")\n ax_beta.set_ylabel(r'$\\beta(t)$')\n fig_gamma = plt.figure()\n ax_gamma = fig_gamma.add_subplot(111)\n ax_gamma.set_xlabel(\"t\")\n ax_gamma.set_ylabel(r'$\\gamma(t)$')\n fig_params = plt.figure()\n ax_params = fig_params.add_subplot(111)\n ax_params.set_xlabel(\"t\")\n \n for i in range(len(alpha[0])):\n ax_alpha.plot(t, alpha[:,i], label=r'$\\alpha_{}(t)$'.format(i))\n ax_params.plot(t, alpha[:,i], label=r'$\\alpha_{}(t)$'.format(i))\n for i in range(len(beta[0])):\n for j in range(len(beta[0,0])):\n ax_beta.plot(t, beta[:, i, j], label=r'$\\beta_{}$$_{}(t)$'.format(i, j))\n ax_params.plot(t, beta[:, i, j], label=r'$\\beta_{}$$_{}(t)$'.format(i, j))\n for i in range(len(gamma[0])):\n ax_gamma.plot(t, gamma[:,i], label=r'$\\gamma_{}(t)$'.format(i))\n ax_params.plot(t, gamma[:,i], label=r'$\\gamma_{}(t)$'.format(i))\n \n ax_alpha.legend()\n ax_beta.legend()\n ax_gamma.legend()\n ax_params.legend()\n if save_file is not None:\n logger.debug(\"save plot of parameter0 (alpha) to {}\".format(save_file[0]))\n fig_alpha.savefig(save_file[0])\n logger.debug(\"save plot of parameter1 (beta) to {}\".format(save_file[1]))\n fig_beta.savefig(save_file[1])\n logger.debug(\"save plot of parameter2 (gamma) to {}\".format(save_file[2]))\n fig_gamma.savefig(save_file[2])\n logger.debug(\"save plot of parameters to {}\".format(save_file[3]))\n fig_params.savefig(save_file[3])","sub_path":"src/visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":6931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"415321367","text":"\"\"\"\nName: \nlab10.py\n\"\"\"\n\n\ndef build():\n return list(range(1, 10))\n\n\ndef display(board):\n for i in range(3):\n n = i*3\n print(board[n], board[n+1], board[n+2], sep=\"|\")\n print(10*\"_\")\n\n\ndef place(board, position, piece):\n if board[position-1] == \"x\" or board[position-1] == \"o\":\n return\n else:\n board[position-1] = piece\n\n\ndef game_won(board, piece):\n if board[0] == piece:\n if board[4] == piece:\n if board[8] == piece:\n return True\n if board[2] == piece:\n if board[4] == piece:\n if board[6] == piece:\n return True\n if board[0] == piece:\n if board[1] == piece:\n if board[2] == piece:\n return True\n if board[3] == piece:\n if board[4] == piece:\n if board[5] == piece:\n return True\n if board[6] == piece:\n if board[7] == piece:\n if board[8] == piece:\n return True\n if board[1] == piece:\n if board[4] == piece:\n if board[7] == piece:\n return True\n else:\n return False\n\n\ndef legal(board, position):\n if(position >= 1, position <= 9) and (board[position - 1] == position):\n return True\n return False\n\n\ndef over(board):\n if game_won(board, \"x\"):\n return True\n elif game_won(board, \"o\"):\n return True\n else:\n for i in range(9):\n if board[i] == i+1:\n return False\n # return True\n\n\ndef play_game():\n board = build()\n display(board)\n turn = 1\n\n while True:\n\n position = eval(input(\"enter position: \"))\n if legal(board, position):\n if (turn % 2) == 0:\n place(board, position, \"x\")\n display(board)\n if over(board):\n if game_won(board, \"o\"):\n print(\"o won\")\n break\n\n if game_won(board, \"x\"):\n print(\"x won\")\n\n else:\n print(\"tie\")\n break\n elif (turn % 2) == 1:\n place(board, position, \"o\")\n display(board)\n if over(board):\n if game_won(board, \"o\"):\n print(\"o won\")\n break\n\n if game_won(board, \"x\"):\n print(\"x won\")\n\n else:\n print(\"tie\")\n break\n\n turn += 1\n\n\ndef main():\n play_game()\n\n\nmain()\n","sub_path":"labs/lab10/lab10.py","file_name":"lab10.py","file_ext":"py","file_size_in_byte":2635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"74508669","text":"from flask import request, render_template, Flask\r\nfrom model.all_hopping_reader import AllHoppingReader\r\n\r\napp = Flask(__name__)\r\n\r\n\r\n@app.route('/')\r\ndef index():\r\n return render_template(\r\n \"index.html\"\r\n )\r\n\r\n\r\n@app.route(\"/get_graph\", methods=[\"GET\", \"POST\"])\r\ndef get_graph():\r\n # Create the all hopping reader\r\n all_hopping_reader = AllHoppingReader(option=request.json)\r\n return all_hopping_reader.draw_parallel_coordinate()\r\n\r\n\r\n@app.route('/upload', methods=['POST'])\r\ndef upload_file():\r\n # Get the file from flask.\r\n file = request.files[\"file\"]\r\n # Save the file to proper location\r\n file.save(\"data/data.xlsx\")\r\n # Return a dummy message to front end.\r\n return \"GOOD\"\r\n","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"519048524","text":"#!/usr/bin/python\n\nimport argparse, subprocess, pathlib, tempfile, sys\nfrom datetime import datetime\n\ntry:\n import humanfriendly\n\n def format_mtime(mtime):\n now = datetime.now()\n mtime = datetime.fromtimestamp(mtime)\n return humanfriendly.format_timespan(now - mtime) + \" ago\"\n\nexcept ModuleNotFoundError:\n\n def format_mtime(mtime):\n # Format datetime according to current locale\n return datetime.fromtimestamp(mtime).strftime(\"%c%\")\n\n\ngifmake_args = argparse.ArgumentParser()\ngifmake_args.add_argument(\"-ss\", help=\"Start timestamp.\", required=True)\nstop_group = gifmake_args.add_mutually_exclusive_group(required=True)\nstop_group.add_argument(\"-to\", help=\"Read up to this timestamp.\")\nstop_group.add_argument(\"-t\", help=\"Read for this duration.\")\nfilter_group = gifmake_args.add_mutually_exclusive_group()\nfilter_group.add_argument(\n \"--width\",\n \"-w\",\n help=\"Scale to %(metavar)s px wide. Implied if -f is not set, with default %(default)s.\",\n default=320,\n metavar=\"W\",\n)\nfilter_group.add_argument(\"--filters\", \"-f\", help=\"An ffmpeg filter graph.\")\ngifmake_args.add_argument(\n \"--rate\", \"-r\", help=\"Frame rate (default: %(default)s).\", default=15\n)\ngifmake_args.add_argument(\"--palette-filters\", \"-pf\", help=\"Palette filters.\")\ngifmake_args.add_argument(\n \"--new-palette\",\n \"-pn\",\n help=\"Force regeneration of the palette.\",\n action=\"store_true\",\n)\ngifmake_args.add_argument(\n \"-v\",\n \"--verbose\",\n help=\"Verbose mode. Prints extra information. Not mutually exclusive with -q, which suppresses ffmpeg output.\",\n action=\"store_true\",\n)\ngifmake_args.add_argument(\n \"-q\",\n \"--quiet\",\n help=\"Quiet mode. Passes -hide_banner -loglevel warning to ffmpeg. Not mutually exclusive with -v.\",\n action=\"store_true\",\n)\ngifmake_args.add_argument(\"input\")\ngifmake_args.add_argument(\"output\")\n\nargs = gifmake_args.parse_args()\nif args.verbose:\n logger = print\nelse:\n logger = lambda x: None\n\npalette_path = pathlib.Path(tempfile.gettempdir()) / pathlib.Path(\n args.input\n).with_suffix(\".palette.png\")\n\nffmpeg_args = []\nffmpeg_args += [\"-stats\"]\nif args.quiet:\n ffmpeg_args += [\"-hide_banner\", \"-loglevel\", \"warning\"]\nffmpeg_args += [\"-ss\", args.ss]\nif args.to:\n ffmpeg_args += [\"-to\", args.to]\nelse:\n ffmpeg_args += [\"-t\", args.t]\nffmpeg_args += [\"-i\", args.input]\n\n# -r needs to be an output argument to not mess up seeking!\nffmpeg_output_args = [\"-r\", str(args.rate)]\n\nif args.width:\n args.filters = \"scale=%s:-1:flags=lanczos\" % args.width\n\nif args.palette_filters:\n palette_filtergraph = \"%s, palettegen\" % args.palette_filters\nelse:\n palette_filtergraph = \"%s, palettegen\" % args.filters\ngif_filtergraph = \"%s [x]; [x][1:v] paletteuse\" % args.filters\n\npalette_cmd = (\n [\"ffmpeg\"] + ffmpeg_args + [\"-lavfi\", palette_filtergraph, \"-y\", str(palette_path)]\n)\nif not palette_path.exists() or args.new_palette:\n logger(\"Generating palette at %s\" % palette_path)\n logger(\" \".join(palette_cmd))\n palette_gen_status = subprocess.call(palette_cmd)\n if not palette_gen_status:\n logger(\"Successfully generated palette.\")\n else:\n sys.exit(\"Palette generation failed.\")\nelse:\n logger(\n \"Reusing palette from %s, last modified %s.\"\n % (palette_path, format_mtime(palette_path.stat().st_mtime))\n )\n\nlogger(\"Encoding gif to %s\" % args.output)\nencode_cmd = (\n [\"ffmpeg\"]\n + ffmpeg_args\n + [\"-i\", str(palette_path)]\n + [\"-lavfi\", gif_filtergraph]\n + ffmpeg_output_args\n + [\"-y\", args.output]\n)\nlogger(\" \".join(encode_cmd))\nencode_status = subprocess.call(encode_cmd)\nif not encode_status:\n logger(\"Encode successful.\")\n","sub_path":"gifmake.py","file_name":"gifmake.py","file_ext":"py","file_size_in_byte":3689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"573263094","text":"import json\nfrom pandas import DataFrame\nfrom insolver.model_tools import train_val_test_split\n\n\nclass InsolverDataFrame(DataFrame):\n \"\"\"Primary DataFrame class for Insolver.\n\n Parameters:\n df (:obj:`pd.DataFrame`): pandas DataFrame.\n \"\"\"\n def __init__(self, df):\n super(InsolverDataFrame, self).__init__(df)\n if not isinstance(df, DataFrame):\n raise NotImplementedError(\"'df' should be the pandas DataFrame.\")\n\n def get_batch(self):\n pass\n\n def get_meta_info(self):\n \"\"\"Gets JSON with Insolver meta information.\n\n Returns:\n dict: Meta information JSON.\n \"\"\"\n meta_json = {\n 'type': 'InsolverDataFrame',\n 'len': self.shape[0],\n 'columns': []\n }\n for column in self.columns:\n meta_json['columns'].append({'name': column, 'dtype': self[column].dtypes, 'use': 'unknown'})\n return meta_json\n\n def split_frame(self, val_size, test_size, random_state=0, shuffle=True, stratify=None):\n \"\"\"Function for splitting dataset into train/validation/test partitions.\n\n Args:\n val_size (float): The proportion of the dataset to include in validation partition.\n test_size (float): The proportion of the dataset to include in test partition.\n random_state (:obj:`int`, optional): Random state, passed to train_test_split() from scikit-learn\n (default=0).\n shuffle (:obj:`bool`, optional): Passed to train_test_split() from scikit-learn (default=True).\n stratify (:obj:`array_like`, optional): Passed to train_test_split() from scikit-learn (default=None).\n\n Returns:\n tuple: (train, valid, test). A tuple of partitions of the initial dataset.\n \"\"\"\n return train_val_test_split(self, val_size=val_size, test_size=test_size, random_state=random_state,\n shuffle=shuffle, stratify=stratify)\n\n def sample_request(self, batch_size=1):\n \"\"\"Create json request by a random sample from InsolverDataFrame\n\n Args:\n batch_size: number of random samples\n\n Returns:\n request (dict)\n \"\"\"\n data_str = self.sample(batch_size).to_json()\n data = json.loads(data_str)\n request = {'df': data}\n return request\n","sub_path":"insolver/frame/frame.py","file_name":"frame.py","file_ext":"py","file_size_in_byte":2364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"65017186","text":"\n# coding: utf-8\n\n# In[1]:\n\n\n# encoding: utf-8\n\n\nimport os\nimport numpy as np\nimport pandas as pd\nfrom sklearn.utils import shuffle\nfrom sklearn.decomposition import PCA\nfrom sklearn import metrics\nimport tensorflow as tf\n\n\n# In[2]:\n\n\nLABELS_TXT = 'digits4000_digits_labels.txt'\nVECS_TXT = 'digits4000_digits_vec.txt'\nVEC_LENGTH = 784\nCLASS_NUM = 10\nBATCH_SIZE = 64\n\n\n# In[3]:\n\n\nlabels_df = pd.read_csv(LABELS_TXT, header=None, names=['label'])\nlabels = labels_df['label']\nvecs_df = pd.read_csv(VECS_TXT, sep='\\t', header=None, names=['f_{}'.format(i) for i in range(VEC_LENGTH)])\nvecs_df = vecs_df / 255.\n\n# check\nprint('labels_df.shape:', labels_df.shape)\nprint('labels.shape:', labels.shape)\nprint('vecs_df.shape:', vecs_df.shape)\n\n\n# In[4]:\n\n\ndef to_one_hot(y_, class_num):\n label_num = y_.shape[0]\n one_hot_vecs = np.zeros((label_num, class_num))\n for i in range(label_num):\n one_hot_vecs[i][y_[i]] = 1\n return one_hot_vecs\n\n\n# In[5]:\n\n\nX_train = vecs_df[0: 2000]\ny_train = labels_df['label'][0: 2000]\nX_test = vecs_df[2000: ]\ny_test = labels_df['label'][2000: ]\n\n# 乱序\nX_train, y_train = shuffle(X_train, y_train)\n\n# 重新索引\nX_train = X_train.reset_index(drop=True)\ny_train = y_train.reset_index(drop=True)\nX_test = X_test.reset_index(drop=True)\ny_test = y_test.reset_index(drop=True)\n\n# check\n# print('y_train:', y_train)\n\n# 转 one-hot 向量\ny_train = to_one_hot(y_train, CLASS_NUM)\ny_test = to_one_hot(y_test, CLASS_NUM)\n\n# check\n# for x in y_train:\n# print(x)\n \n# for x in y_test:\n# print(x)\n\n# check\nprint('X_train type:', type(X_train))\nprint('X_test type:', type(X_test))\nprint('X_train shape:', X_train.shape)\nprint('X_test shape:', X_test.shape)\nprint('y_train type:', type(y_train))\nprint('y_test type:', type(y_test))\nprint('y_train shape:', y_train.shape)\nprint('y_test shape:', y_test.shape)\n\n\n# In[6]:\n\n\nstart_idx = 0\ndef next_batch(batch_size=BATCH_SIZE):\n global start_idx\n idx = start_idx\n if idx + batch_size > X_train.shape[0]:\n start_idx = 0\n return X_train[idx: ], y_train[idx: ]\n else:\n start_idx += batch_size\n return X_train[idx: idx + batch_size], y_train[idx: idx + batch_size]\n\n\n# In[ ]:\n\n\nsess = tf.InteractiveSession()\n\nx = tf.placeholder(tf.float32, [None, 784])\ny_ = tf.placeholder(tf.float32, [None, 10])\nkeep_prob = tf.placeholder(tf.float32)\nx_image = tf.reshape(x, [-1, 28, 28, 1])\n\ndef weight_variable(shape):\n initial = tf.truncated_normal(shape, stddev=0.1)\n return tf.Variable(initial)\n\ndef bias_variable(shape):\n initial = tf.constant(0.1, shape=shape)\n return tf.Variable(initial)\n\ndef conv2d(x, W):\n return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')\n\ndef max_pool_2x2(x):\n return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n\nW_conv1 = weight_variable([5, 5, 1, 32])\nb_conv1 = bias_variable([32])\nh_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)\nh_pool1 = max_pool_2x2(h_conv1)\nW_conv2 = weight_variable([5, 5, 32, 64])\nb_conv2 = bias_variable([64])\nh_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)\nh_pool2 = max_pool_2x2(h_conv2)\nh_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])\nW_fc1 = weight_variable([7 * 7 * 64, 1024])\nb_fc1 = bias_variable([1024])\nh_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\nh_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\nW_fc2 = weight_variable([1024, 10])\nb_fc2 = bias_variable([10])\ny = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)\ncross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))\ntrain_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)\ncorrect_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\ntf.global_variables_initializer().run()\n\nfor i in range(3000):\n \n batch_xs, batch_ys = next_batch(64)\n \n if i % 100 == 0:\n train_accuracy = accuracy.eval(feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 1.0})\n print('step {}, training accuracy {:4f}'.format(i, train_accuracy))\n \n train_step.run(feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 0.5})\nprint('test accuracy {:4f}'.format(accuracy.eval(feed_dict={x: X_test, y_: y_test, keep_prob: 1.0})))\n\n","sub_path":"mnist_project/simple_cnn.py","file_name":"simple_cnn.py","file_ext":"py","file_size_in_byte":4259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"433934212","text":"#!/usr/bin/python\nfrom StyleRubric import StyleRubric\n\ndef style_grader_driver(online_files):\n rubric = StyleRubric()\n show_errors = []\n\n for filename, originalname in online_files.items():\n print('Analyzing {}...'.format(filename.split('/')[-1]))\n rubric.grade_student_file(filename, originalname)\n\n rubric.adjust_errors()\n show_errors = rubric.get_error_summary(show_errors)\n\n # #For debugging purposes only\n # print(\":\\t\".join([\"Total Errors\", str(rubric.total_errors)]))\n # for x, y in rubric.error_types.items():\n # print(\":\\t\".join([x, str(y)]))\n\n\n return show_errors\n\n# if __name__ == '__main__':\n# main()","sub_path":"style_grader_main.py","file_name":"style_grader_main.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"375439434","text":"from model import cnn_model\nfrom config import cfg\nfrom datasets import make_nolabeltest_loader\nimport torch.nn as nn \nimport torchvision.models as models\n\nimport torch, os\nimport numpy as np\nimport mongo_data.rotation \n\nmodel = models.resnet50()\nfc_features = model.fc.in_features \nmodel.fc = nn.Linear(fc_features, 3)\n\nweight_path = cfg.MODEL.OUTPUT_PATH\nuse_cuda = cfg.DEVICE.CUDA\ngpu_id = cfg.DEVICE.GPU\n\nweight = torch.load(weight_path)\nmodel.load_state_dict(weight)\n\nif use_cuda:\n torch.cuda.set_device(gpu_id)\n model.cuda()\n\ntest_loader = make_nolabeltest_loader(cfg)\n\nmodel.eval()\nresult_label=[]\nwith torch.no_grad():\n for data, target in test_loader:\n if use_cuda:\n data, target = data.cuda(), target.cuda()\n\n output = model(data)\n print(output)\n ndarray = output.max(1)[1].cpu().numpy()\n print(ndarray)\n k = ndarray.tolist()\n print(k)\n print('------')\n if (k[0] == 0):\n result_label.append('A')\n if (k[0] == 1):\n result_label.append('B')\n if (k[0] == 2):\n result_label.append('C')\n \nprint(result_label)\nimport csv\nwith open(\"result_label.csv\", \"w\", newline=\"\") as f:\n writer = csv.writer(f)\n writer.writerows(result_label)\n","sub_path":"hw2/nolabel_test.py","file_name":"nolabel_test.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"175709253","text":"# Imports.\nimport numpy as np\nimport numpy.random as npr\nimport pygame as pg\nimport pickle\n\nfrom SwingyMonkey import SwingyMonkey\nfrom collections import defaultdict\n\n# Discretize the space and use Temporal Difference Learning\n\nclass Learner(object):\n '''\n This agent jumps randomly.\n '''\n\n def __init__(self):\n self.last_state = None\n self.last_action = None\n self.last_reward = None\n\n '''\n This is the dictionary whose format is:\n {\n state (tuple): q_value,\n ......,\n state (tuple): q_value\n }\n\n Each state will be comprised of values corresponding\n to the bin number of the following features:\n 1. Distance between monkey head and tree top\n 2. Distance to tree\n 3. Velocity of monkey\n\n May take into account gravity later\n '''\n self.q_values = defaultdict(int)\n\n '''\n Defining the binsize for each state value\n '''\n self.head_bin = 40\n self.monkey_vel_BIN = 5\n self.tree_dist_BIN = 100\n\n # Learning rate for SGD and discount factor and other constants\n self.eta = 0.25\n self.discount = 0.9\n self.epsilon = 0.1\n self.iter = 0\n self.gravity = -1\n\n def reset(self):\n self.last_state = None\n self.last_action = None\n self.last_reward = None\n\n def discretize_state(self, state):\n tree = state['tree']\n monkey = state['monkey']\n\n head_height = int((tree['top'] - monkey['top']) / self.head_bin)\n tree_dist = int(tree['dist'] / self.tree_dist_BIN)\n monkey_vel = int(monkey['vel'] / self.monkey_vel_BIN)\n\n return (head_height, tree_dist, monkey_vel)\n\n def next_action(self, state):\n d_state = self.discretize_state(state)\n swing = self.q_values[(d_state, 0)]\n jump = self.q_values[(d_state, 1)]\n\n if jump == swing: return np.random.randint(2)\n\n # Here implementing an epsilon greedy strategy to incentize\n # exploration of different actions\n divisor = np.exp(0.001*self.iter)\n divisor = divisor if divisor > 10e-8 else 0\n if np.random.uniform(0, 1) < self.epsilon/divisor:\n return not (jump > swing)\n else:\n return (jump > swing)\n\n def action_callback(self, new_state):\n '''\n Implement this function to learn things and take actions.\n Return 0 if you don't want to jump and 1 if you do.\n '''\n\n # You might do some learning here based on the current state and the last state.\n\n # You'll need to select and action and return it.\n # Return 0 to swing and 1 to jump.\n\n self.iter += 1\n\n if self.last_state != None:\n if self.gravity == -1:\n prev = self.last_state['monkey']['vel']\n curr = new_state['monkey']['vel']\n self.gravity = (abs(curr - prev) >= 2) \n\n last_d_state = self.discretize_state(self.last_state)\n curr_d_state = self.discretize_state(new_state)\n\n q_max = max(\n self.q_values[(curr_d_state, 0)],\n self.q_values[(curr_d_state, 1)]\n )\n gradient = self.q_values[(last_d_state, self.last_action)]\n gradient -= self.last_reward + self.discount * q_max\n\n # Update the value\n self.q_values[(last_d_state, self.last_action)] -= self.eta * gradient\n\n self.last_state = new_state\n self.last_action = self.next_action(new_state)\n return self.last_action\n\n def reward_callback(self, reward):\n '''This gets called so you can see what reward you get.'''\n\n self.last_reward = reward\n\n\ndef run_games(learner, hist, iters = 100, t_len = 100):\n '''\n Driver function to simulate learning by having the agent play a sequence of games.\n '''\n try:\n max_score = 0\n for ii in range(iters):\n # Make a new monkey object.\n swing = SwingyMonkey(sound=False, # Don't play sounds.\n text=\"Epoch %d\" % (ii), # Display the epoch on screen.\n tick_length = t_len, # Make game ticks super fast.\n action_callback=learner.action_callback,\n reward_callback=learner.reward_callback)\n\n # Loop until you hit something.\n while swing.game_loop():\n pass\n \n # Save score history.\n hist.append(swing.score)\n if swing.score > max_score:\n max_score = swing.score\n print(\"Max score is now {} on iteration #{}.\".format(max_score, ii+1))\n\n # Reset the state of the learner.\n learner.reset()\n pg.quit()\n return\n finally:\n with open(\"q_agent.pickle\", 'wb') as handle:\n pickle.dump(learner.q_values, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n\nif __name__ == '__main__':\n\n # Select agent.\n agent = Learner()\n \n # Load q-value dictionary, so we don't need to wait as long\n import os\n if os.path.isfile(\"q_agent.pickle\"):\n with open('q_agent.pickle', 'rb') as handle:\n agent.q_values = pickle.load(handle)\n\n # Empty list to save history.\n hist = []\n\n # Run games\n games = 750\n tick = 1\n try:\n run_games(agent, hist, games, tick)\n finally:\n hist.sort(reverse=True)\n print(\"These were the top ten scores\")\n for i in range(10):\n print(str(i+1)+\": \", hist[i])\n\n # Save history. \n np.save('hist', np.array(hist))\n\n\n","sub_path":"P4/stub.py","file_name":"stub.py","file_ext":"py","file_size_in_byte":5782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"152309458","text":"#Autor: Eric Andrés Jardón Chao\r\n#La función principal despliega un menú con 6 funciones a ejecutar. Para salir, el usuario teclea 0.\r\nimport pygame # Librería de pygame\r\nimport math #Para funciones trigonométricas en dibujarCirculos()\r\n\r\n# Dimensiones de la pantalla\r\nANCHO = 800\r\nALTO = ANCHO\r\n# Colores\r\nBLANCO = (255, 255, 255) # R,G,B en el rango [0,255], 0 ausencia de color, 255 toda la intensidad\r\nNEGRO= (0, 0, 0)\r\n\r\ndef main(): #Despliega el menú. Opciones menores a 0 o mayores a 6 no son válidas.\r\n choice=10\r\n print(\"Misión 5. Seleccione qué desea hacer. \\n1. Dibujar cuadros y círculos.\\n2. Dibujar círculos.\"\r\n \"\\n3. Dibujar espiral.\\n4. Aproximar Pi\\n5. Contar divisibles entre 37\\n6. Imprimir pirámides de números.\"\r\n \"\\n0. Salir.\")\r\n while choice !=0: #Mientras la elección del usuario no sea \"Salir\" el programa pregunta qué desea hacer.\r\n choice=int(input(\"¿Qué desea hacer? \"))\r\n if choice>6 or choice<0:\r\n print(\"Intente con un número válido.\")\r\n choice=10\r\n elif choice==1:\r\n print(\"Seleccionó: dibujar cuadros y círculos.\")\r\n dibujarCuadrosCirculos()\r\n elif choice ==2:\r\n print(\"Seleccionó: dibujar círculos.\")\r\n dibujarCirculos()\r\n elif choice == 3:\r\n print(\"Seleccionó: dibujar espiral.\")\r\n dibujarEspiral()\r\n elif choice == 4:\r\n print(\"Seleccionó: aproximar Pi.\")\r\n aproximarPi()\r\n elif choice == 5:\r\n print(\"Seleccionó: contar divisibles entre 37.\")\r\n encontrardivisibles()\r\n elif choice == 6:\r\n print(\"Seleccionó: imprimir pirámides de números.\")\r\n imprimirOperaciones()\r\n else:\r\n print(\"¡Adiós!\")\r\n\r\n#FUNCIONES PARA DIBUJO\r\n#CuadrosCírculos\r\ndef dibujarCuadrosCirculos(): #Dibuja cuadrados y rectángulos de misma dimensión iterativamente hasta lenar la pantalla, con distancia 10 pixeles entre sí..\r\n # Inicializa el motor de pygame\r\n pygame.init()\r\n # Crea una ventana de ANCHO x ALTO\r\n ventana = pygame.display.set_mode((ANCHO, ALTO)) # Crea la ventana donde dibujará\r\n reloj = pygame.time.Clock() # Para limitar los fps\r\n termina = False # Bandera para saber si termina la ejecución, iniciamos suponiendo que no\r\n\r\n while not termina: # Ciclo principal, MIENTRAS la variable termina sea False, el ciclo se repite automáticamente\r\n # Procesa los eventos que recibe\r\n for evento in pygame.event.get():\r\n if evento.type == pygame.QUIT: # El usuario hizo click en el botón de salir\r\n termina = True # Queremos terminar el ciclo\r\n\r\n # Borrar pantalla\r\n ventana.fill(BLANCO)\r\n # Dibujar, aquí haces todos los trazos que requieras\r\n pos = ALTO // 2 #Es la coordenada de referencia, se posiciona a la mitad del eje x o y de la pantalla. En este caso es 400.\r\n for radius in range(1, pos+1, 10): #El contador es el radio para que incremente de 10 en 10 hasta llegar a los extremos.\r\n pygame.draw.circle(ventana, NEGRO, (pos, pos), radius, 1) #Dibuja un círculo en el centro para cada radio.\r\n pygame.draw.rect(ventana, NEGRO, (pos - radius, pos - radius, 2 * radius, 2 * radius), 1) #dibuja un rectángulo de dimensiones radio*2 y radio*2\r\n\r\n pygame.display.flip() # Actualiza trazos (Si no llamas a esta función, no se dibuja)\r\n reloj.tick(40) # 40 fps\r\n\r\n # Después del ciclo principal\r\n pygame.quit() # termina pygame\r\n\r\n#Círculos\r\ndef dibujarCirculos(): #Dibuja 12 círculos alrededor del centro de la pantalla.\r\n # Inicializa el motor de pygame\r\n pygame.init()\r\n # Crea una ventana de ANCHO x ALTO\r\n ventana = pygame.display.set_mode((ANCHO, ALTO)) # Crea la ventana donde dibujará\r\n reloj = pygame.time.Clock() # Para limitar los fps\r\n termina = False # Bandera para saber si termina la ejecución, iniciamos suponiendo que no\r\n\r\n while not termina: # Ciclo principal, MIENTRAS la variable termina sea False, el ciclo se repite automáticamente\r\n # Procesa los eventos que recibe\r\n for evento in pygame.event.get():\r\n if evento.type == pygame.QUIT: # El usuario hizo click en el botón de salir\r\n termina = True # Queremos terminar el ciclo\r\n\r\n # Borrar pantalla\r\n ventana.fill(BLANCO)\r\n # Dibujar, aquí haces todos los trazos que requieras\r\n pos = ALTO // 2 #coordenada de referencia para el centro de la pantalla.\r\n angulo = (math.pi) / 2 #Funciona como acumulador, se inicializa en 90 grados.\r\n incremento = (math.pi) / 6 #Es el incremento de grados: 30\r\n for centro in range(1,13): # El centro de cada círculo debe estar a la misma distancia del centro de la pantalla y ocupan los lugares de las horas de un reloj. 360 grados entre 12 es 30\r\n pygame.draw.circle(ventana, NEGRO,(int(pos - (150 * math.cos(angulo))), int(pos - (150 * math.sin(angulo)))), 150, 1) #Usa seno y coseno para encontrar las distancias en x y y desde el centro.\r\n angulo += incremento #Incrementa en 30 grados cada vez que traza un círculo.\r\n\r\n pygame.display.flip() # Actualiza trazos (Si no llamas a esta función, no se dibuja)\r\n reloj.tick(40) # 40 fps\r\n\r\n # Después del ciclo principal\r\n pygame.quit() # termina pygame\r\n\r\n#Espiral\r\ndef dibujarEspiral(): #Dibuja un espiral con líneas rectas.\r\n # Inicializa el motor de pygame\r\n pygame.init()\r\n # Crea una ventana de ANCHO x ALTO\r\n ventana = pygame.display.set_mode((ANCHO, ALTO)) # Crea la ventana donde dibujará\r\n reloj = pygame.time.Clock() # Para limitar los fps\r\n termina = False # Bandera para saber si termina la ejecución, iniciamos suponiendo que no\r\n\r\n while not termina: # Ciclo principal, MIENTRAS la variable termina sea False, el ciclo se repite automáticamente\r\n # Procesa los eventos que recibe\r\n for evento in pygame.event.get():\r\n if evento.type == pygame.QUIT: # El usuario hizo click en el botón de salir\r\n termina = True # Queremos terminar el ciclo\r\n\r\n # Borrar pantalla\r\n ventana.fill(BLANCO)\r\n # Dibujar, aquí haces todos los trazos que requieras\r\n lineas = (ALTO) // 10 // 2 # dividir el espacio disponible de la pantalla entre 10 pixeles entre líneas y a la mitad.\r\n for i in range(0, lineas):\r\n delta = i * 10 # El espacio entre líneas\r\n k = ALTO - 2 - delta # 2 pixeles es el margen desde la ventana a la primer línea. K es usado como coordenada referencia, y es el punto donde comienza el espiral.\r\n # Horizontales dibujadas una por una de abajo hacia arriba.\r\n pygame.draw.line(ventana, NEGRO, (k, k), (ALTO - k, k)) # Se trazan de derecha a izquierda.\r\n # Horizontales dibujadas una por una de arriba hacia abajo.\r\n pygame.draw.line(ventana, NEGRO, (k - 10, ALTO - k),\r\n (ALTO - k, ALTO - k)) # Se trazan de derecha a izquierda\r\n # Verticales dibujadas una por una de izquierda a derecha\r\n pygame.draw.line(ventana, NEGRO, (ALTO - k, k), (ALTO - k, ALTO - k)) # Se trazan de abajo hacia arriba\r\n # verticales dibujadas una por una de derecha a izquierda\r\n pygame.draw.line(ventana, NEGRO, (k - 10, k - 10), (k - 10, ALTO - k)) # Se trazan de abajo hacia arriba\r\n #Se forma un espiral desde afuera hacia dentro, trazando líneas desde la derecha hasta el centro y desde la izquierda hasta el centro;\r\n #el mismo caso para las horizontales.\r\n pygame.display.flip() # Actualiza trazos (Si no llamas a esta función, no se dibuja)\r\n reloj.tick(40) # 40 fps\r\n\r\n # Después del ciclo principal\r\n pygame.quit() # termina pygame\r\n\r\n\r\n#FUNCIONES PARA 4\r\ndef aproximarPi(): #Si el número ingresado de elementos es positivo, devuelve una aproximación. Si no, devuelve error.\r\n n = int(input(\"Teclea el número de elementos que quieres usar para la aproximación: \"))\r\n if n > 0:\r\n pi = despejarPi(n)\r\n print(\"Valor de pi aproximado:\", pi)\r\n else:\r\n print(\"Error: no se puede realizar aproximación\")\r\n\r\ndef despejarPi(n): #Esta función despeja el valor de pi de la suma obtenida por sumarAprox.\r\n pi = (sumarAprox(n) * 6) ** (1 / 2)\r\n return pi\r\n\r\ndef sumarAprox(n): #Calcula el valor aproximado de (pi*pi/6) según la fórmula dada.\r\n aproximacion = 0 #acumulador\r\n for x in range(1, n + 1): #desde 1 hasta el número de elementos que ingresó el usuario.\r\n elemento = (1 / x ** 2)\r\n aproximacion += elemento\r\n return aproximacion\r\n\r\n#FUNCIONES PARA 5\r\ndef encontrardivisibles(): #Corre la función que calcula e imprime el resultado.\r\n divisibles=encontrarNumeros()\r\n print(\"La cantidad de números con 4 dígitos divisibles entre 37 es\", divisibles)\r\n\r\ndef encontrarNumeros(): #Utiliza un contador\r\n divisibles=0\r\n for n in range(1000,10000): #los números con 4 dígitos van del 1000 al 9999.\r\n if n%37==0: #Cada que sea divisble entre 37 suma uno al contador.\r\n divisibles+=1\r\n\r\n return divisibles\r\n\r\n#FUNCIONES PARA 6\r\ndef imprimirOperaciones(): #calcula e imprime con formato de cadena cada operación.\r\n primer=0 #acumulador usado para obtener 11, 111, 1111...\r\n for i in range(1,10):\r\n primer=primer*10+1\r\n resultado1=primer*primer\r\n print(\"%d * %d = %d\"%(primer,primer,resultado1))\r\n print(\"\\n\")\r\n base=0\r\n for digito in range(1,10):\r\n base=base*10+digito #Acumulador usado para obtener 12, 123, 1234...\r\n resultado2=base*8+digito\r\n print(\"%d * 8 + %d = %d\"%(base,digito,resultado2))\r\n\r\n\r\n\r\nmain() #Corre la función principal (el menú).","sub_path":"MisionCinco.py","file_name":"MisionCinco.py","file_ext":"py","file_size_in_byte":9889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"427967240","text":"from copy import deepcopy\n\nfrom portality import constants\nfrom portality.core import app\nfrom portality.lib import es_data_mapping\nfrom portality.models.v2 import shared_structs\nfrom portality.models.v2.journal import JournalLikeObject\nfrom portality.lib.coerce import COERCE_MAP\nfrom portality.dao import DomainObject\n\nAPPLICATION_STRUCT = {\n \"objects\" : [\n \"admin\", \"index\"\n ],\n\n \"structs\" : {\n \"admin\" : {\n \"fields\" : {\n \"current_journal\" : {\"coerce\" : \"unicode\"},\n \"related_journal\" : {\"coerce\" : \"unicode\"},\n \"application_status\" : {\"coerce\" : \"unicode\"},\n \"date_applied\" : {\"coerce\" : \"utcdatetime\"},\n \"last_manual_update\": {\"coerce\": \"utcdatetime\"}\n }\n },\n \"index\" : {\n \"fields\" : {\n \"application_type\": {\"coerce\": \"unicode\"}\n }\n }\n }\n}\n\nclass Application(JournalLikeObject):\n __type__ = \"application\"\n\n __SEAMLESS_STRUCT__ = [\n shared_structs.JOURNAL_BIBJSON,\n shared_structs.SHARED_JOURNAL_LIKE,\n APPLICATION_STRUCT\n ]\n\n __SEAMLESS_COERCE__ = COERCE_MAP\n\n def __init__(self, **kwargs):\n # FIXME: hack, to deal with ES integration layer being improperly abstracted\n if \"_source\" in kwargs:\n kwargs = kwargs[\"_source\"]\n super(Application, self).__init__(raw=kwargs)\n\n @classmethod\n def get_by_owner(cls, owner):\n q = SuggestionQuery(owner=owner)\n result = cls.query(q=q.query())\n records = [cls(**r.get(\"_source\")) for r in result.get(\"hits\", {}).get(\"hits\", [])]\n return records\n\n @classmethod\n def delete_selected(cls, email=None, statuses=None):\n q = SuggestionQuery(email=email, statuses=statuses)\n r = cls.delete_by_query(q.query())\n\n @classmethod\n def list_by_status(cls, status):\n q = StatusQuery(status)\n return cls.iterate(q=q.query())\n\n @classmethod\n def find_latest_by_current_journal(cls, journal_id):\n q = CurrentJournalQuery(journal_id)\n results = cls.q2obj(q=q.query())\n if len(results) > 0:\n return results[0]\n return None\n\n @classmethod\n def find_all_by_related_journal(cls, journal_id):\n q = RelatedJournalQuery(journal_id, size=1000)\n return cls.q2obj(q=q.query())\n\n def mappings(self):\n return es_data_mapping.create_mapping(self.__seamless_struct__.raw, MAPPING_OPTS)\n\n @property\n def current_journal(self):\n return self.__seamless__.get_single(\"admin.current_journal\")\n\n def set_current_journal(self, journal_id):\n self.__seamless__.set_with_struct(\"admin.current_journal\", journal_id)\n\n def remove_current_journal(self):\n self.__seamless__.delete(\"admin.current_journal\")\n\n @property\n def related_journal(self):\n return self.__seamless__.get_single(\"admin.related_journal\")\n\n def set_related_journal(self, journal_id):\n self.__seamless__.set_with_struct(\"admin.related_journal\", journal_id)\n\n def remove_related_journal(self):\n self.__seamless__.delete(\"admin.related_journal\")\n\n @property\n def application_status(self):\n return self.__seamless__.get_single(\"admin.application_status\")\n\n def set_application_status(self, val):\n self.__seamless__.set_with_struct(\"admin.application_status\", val)\n\n @property\n def date_applied(self):\n return self.__seamless__.get_single(\"admin.date_applied\")\n\n @date_applied.setter\n def date_applied(self, val):\n self.__seamless__.set_with_struct(\"admin.date_applied\", val)\n\n def _sync_owner_to_journal(self):\n if self.current_journal is None:\n return\n from portality.models.v2.journal import Journal\n cj = Journal.pull(self.current_journal)\n if cj is not None and cj.owner != self.owner:\n cj.set_owner(self.owner)\n cj.save(sync_owner=False)\n\n def _generate_index(self):\n super(Application, self)._generate_index()\n\n if self.current_journal is not None:\n self.__seamless__.set_with_struct(\"index.application_type\", constants.APPLICATION_TYPE_UPDATE_REQUEST)\n elif self.application_status in [constants.APPLICATION_STATUS_ACCEPTED, constants.APPLICATION_STATUS_REJECTED]:\n self.__seamless__.set_with_struct(\"index.application_type\", constants.APPLICATION_TYPE_FINISHED)\n else:\n self.__seamless__.set_with_struct(\"index.application_type\", constants.APPLICATION_TYPE_NEW_APPLICATION)\n\n def prep(self, is_update=True):\n self._generate_index()\n if is_update:\n self.set_last_updated()\n\n def save(self, sync_owner=True, **kwargs):\n self.prep()\n self.verify_against_struct()\n if sync_owner:\n self._sync_owner_to_journal()\n return super(Application, self).save(**kwargs)\n\n\n #########################################################\n ## DEPRECATED METHODS\n\n @property\n def suggested_on(self):\n return self.date_applied\n\n @suggested_on.setter\n def suggested_on(self, val):\n self.date_applied = val\n\n @property\n def suggester(self):\n owner = self.owner\n if owner is None:\n return None\n from portality.models import Account\n oacc = Account.pull(owner)\n if oacc is None:\n return None\n return {\n \"name\" : owner,\n \"email\" : oacc.email\n }\n\n\nclass DraftApplication(Application):\n __type__ = \"draft_application\"\n\n __SEAMLESS_APPLY_STRUCT_ON_INIT__ = False\n __SEAMLESS_CHECK_REQUIRED_ON_INIT__ = False\n\n\n\nclass AllPublisherApplications(DomainObject):\n __type__ = \"draft_application,application\"\n\n\nMAPPING_OPTS = {\n \"dynamic\": None,\n \"coerces\": app.config[\"DATAOBJ_TO_MAPPING_DEFAULTS\"],\n \"exceptions\": {\n \"admin.notes.note\": {\n \"type\": \"string\",\n \"index\": \"not_analyzed\",\n \"include_in_all\": False\n }\n }\n}\n\n\nclass SuggestionQuery(object):\n _base_query = { \"query\" : { \"bool\" : {\"must\" : []}}}\n _email_term = {\"term\" : {\"admin.applicant.email.exact\" : \"\"}}\n _status_terms = {\"terms\" : {\"admin.application_status.exact\" : [\"\"]}}\n _owner_term = {\"term\" : {\"admin.owner.exact\" : \"\"}}\n\n def __init__(self, email=None, statuses=None, owner=None):\n self.email = email\n self.owner = owner\n if statuses:\n self.statuses = statuses\n else:\n self.statuses = []\n\n def query(self):\n q = deepcopy(self._base_query)\n if self.email:\n et = deepcopy(self._email_term)\n et[\"term\"][\"admin.applicant.email.exact\"] = self.email\n q[\"query\"][\"bool\"][\"must\"].append(et)\n if self.statuses and len(self.statuses) > 0:\n st = deepcopy(self._status_terms)\n st[\"terms\"][\"admin.application_status.exact\"] = self.statuses\n q[\"query\"][\"bool\"][\"must\"].append(st)\n\n if self.owner is not None:\n ot = deepcopy(self._owner_term)\n ot[\"term\"][\"admin.owner.exact\"] = self.owner\n q[\"query\"][\"bool\"][\"must\"].append(ot)\n return q\n\nclass OwnerStatusQuery(object):\n base_query = {\n \"query\" : {\n \"bool\" : {\n \"must\" : []\n }\n },\n \"sort\" : [\n {\"created_date\" : \"desc\"}\n ],\n \"size\" : 10\n }\n def __init__(self, owner, statuses, size=10):\n self._query = deepcopy(self.base_query)\n owner_term = {\"match\" : {\"owner\" : owner}}\n self._query[\"query\"][\"bool\"][\"must\"].append(owner_term)\n status_term = {\"terms\" : {\"admin.application_status.exact\" : statuses}}\n self._query[\"query\"][\"bool\"][\"must\"].append(status_term)\n self._query[\"size\"] = size\n\n def query(self):\n return self._query\n\nclass StatusQuery(object):\n\n def __init__(self, statuses):\n if not isinstance(statuses, list):\n statuses = [statuses]\n self.statuses = statuses\n\n def query(self):\n return {\n \"query\" : {\n \"bool\" : {\n \"must\" : [\n {\"terms\" : {\"admin.application_status.exact\" : self.statuses}}\n ]\n }\n }\n }\n\nclass CurrentJournalQuery(object):\n\n def __init__(self, journal_id, size=1):\n self.journal_id = journal_id\n self.size = size\n\n def query(self):\n return {\n \"query\" : {\n \"bool\" : {\n \"must\" : [\n {\"term\" : {\"admin.current_journal.exact\" : self.journal_id}}\n ]\n }\n },\n \"sort\" : [\n {\"created_date\" : {\"order\" : \"desc\"}}\n ],\n \"size\" : self.size\n }\n\nclass RelatedJournalQuery(object):\n\n def __init__(self, journal_id, size=1):\n self.journal_id = journal_id\n self.size = size\n\n def query(self):\n return {\n \"query\" : {\n \"bool\" : {\n \"must\" : [\n {\"term\" : {\"admin.related_journal.exact\" : self.journal_id}}\n ]\n }\n },\n \"sort\" : [\n {\"created_date\" : {\"order\" : \"asc\"}}\n ],\n \"size\" : self.size\n }","sub_path":"portality/models/v2/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":9512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"578908542","text":"import torch\n\n\ndef gpu(tensor, gpu=False, device=None):\n if gpu:\n return tensor.cuda(device)\n else:\n return tensor\n\n\ndef cpu(tensor, cpu=False):\n if cpu:\n return tensor.cpu()\n else:\n return tensor\n\n\ndef assert_no_grad(variable):\n if variable.requires_grad:\n raise ValueError(\n \"nn criterions don't compute the gradient w.r.t. targets - please \"\n \"mark these variables as volatile or not requiring gradients\")\n\n\ndef set_seed(seed, cuda=False):\n torch.manual_seed(seed)\n\n if cuda:\n torch.cuda.manual_seed(seed)\n","sub_path":"divmachines/utility/torch.py","file_name":"torch.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"134677136","text":"#!/usr/bin/python2.7\n# -*- coding: utf-8 -*-\n\nclass Settings():\n #设置存储\n\n def __init__(self):\n #初始化游戏设置\n\n #屏幕设置\n self.screen_width=800\n self.screen_height=600\n self.bg_color=(230,230,230)\n\n self.ship_speed_factor=0.8\n\n #子弹设置\n self.bullet_speed_factor=3\n self.bullet_width=3\n self.bullet_height=15\n self.bullet_color=60,60,60\n self.bullets_allowed=3\n\n #外星人设置\n self.alien_speed_factor=1\n self.fleet_drop_speed=10\n self.fleet_direction=1\n\n #飞船设置\n self.ship_limit=3\n\n\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"206810180","text":"# Save a dictionary into a pickle file.\nimport csv\nimport pickle\nfrom timer import *\nfrom monopoly import *\nfrom copy import deepcopy\nfrom multiprocessing import *\n\n\ndef play_set(sample_size, game, results_q):\n game_winners = []\n\n for i in range(sample_size):\n game_to_play = deepcopy(game)\n\n # Add 10000 more turns.\n game_to_play.cutoff = 20000\n\n # Reset money.\n for player in game_to_play.active_players:\n player.money = 1500\n\n # Play the game.\n results = game_to_play.play()\n game_winners.append(results['winner'])\n\n results_q.put(game_winners)\n\n\ndef stability(game):\n total_sample_size = 10000\n procs = 4\n results_q = Queue() # Queue for results.\n proc_list = [] # List of processes.\n for i in range(procs):\n proc_list.append(Process(target=play_set, args=(int(total_sample_size / procs), game, results_q)))\n\n for proc in proc_list: # Start all processes.\n proc.start()\n\n for proc in proc_list: # Wait for all processes to finish.\n proc.join()\n\n results_list = []\n\n # Gather the results from each process.\n while not results_q.empty():\n results_list.extend(results_q.get())\n\n results = [results_list.count(0) / total_sample_size,\n results_list.count(1) / total_sample_size,\n results_list.count(2) / total_sample_size]\n\n return results\n\n\ndef write_row(row):\n with open('results/stalemates/discrete_trading_stability.csv', 'a', newline='') as csvfile:\n output_file = csv.writer(csvfile, quotechar=',')\n output_file.writerow(row)\n\n\ndef random_ordering():\n all_groups = [\"Brown\", \"Light Blue\", \"Pink\", \"Orange\",\n \"Red\", \"Yellow\", \"Green\", \"Dark Blue\",\n \"Utility\", \"Railroad\"]\n shuffle(all_groups)\n return tuple(all_groups)\n\n\ndef main():\n main_counter = 0\n game_lengths = []\n game_counter = 0\n while main_counter < 10:\n game_counter += 1\n # Play game.\n order = random_ordering()\n player1 = Player(1, group_ordering=order)\n player2 = Player(2, group_ordering=tuple(reversed(list(order))))\n game0 = Game([player1, player2], cutoff=10000,\n new_trading=True) # trading_enabled=True, hotel_upgrade=True, building_sellback=True)\n results = game0.play()\n\n # game_lengths.append(results['length'])\n #running_average = sum(game_lengths) / len(game_lengths)\n #print(running_average)\n\n #print(results['length'])\n\n\n # Pickle if there is a tie.\n if results['winner'] == 0:\n # Pickle it...like a cucumber!\n pickle.dump(game0, open('results/stalemates/discrete_trading/game' + str(main_counter) + '.pickle', 'wb'))\n print(\"!!!!!!found\", main_counter)\n print(results['monopolies'], game_counter)\n main_counter += 1\n\n # Find stability.\n stab = stability(game0)\n write_row(stab)\n print(stab)\n\n\nif __name__ == '__main__':\n timer()\n main()\n timer()","sub_path":"pickleStalemates_archive.py","file_name":"pickleStalemates_archive.py","file_ext":"py","file_size_in_byte":3091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"335062470","text":"# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom abc import ABC, abstractmethod\nfrom multiprocessing.pool import ThreadPool\nimport numba.cuda\nimport time\nimport logging\n\nfrom model_analyzer.device.gpu_device_factory import GPUDeviceFactory\nfrom model_analyzer.model_analyzer_exceptions import TritonModelAnalyzerException\n\nlogger = logging.getLogger(__name__)\n\n\nclass Monitor(ABC):\n \"\"\"\n Monitor abstract class is a parent class used for monitoring devices.\n \"\"\"\n def __init__(self, gpus, frequency, tags):\n \"\"\"\n Parameters\n ----------\n gpus : list\n A list of strings containing GPU UUIDs.\n frequency : float\n How often the metrics should be monitored.\n tags : list\n A list of Record objects that will be monitored.\n\n Raises\n ------\n TritonModelAnalyzerExcpetion\n If the GPU cannot be found, the exception will be raised.\n \"\"\"\n\n self._frequency = frequency\n self._gpus = []\n\n if len(gpus) == 1 and gpus[0] == 'all':\n cuda_devices = numba.cuda.list_devices()\n if len(cuda_devices) == 0:\n raise TritonModelAnalyzerException(\n \"No GPUs are visible by CUDA. Make sure that 'nvidia-smi'\"\n \" output shows available GPUs. If you are using Model\"\n \" Analyzer inside a container, ensure that you are\"\n \" launching the container with the\"\n \" appropriate '--gpus' flag\"\n )\n for gpu in cuda_devices:\n gpu_device = GPUDeviceFactory.create_device_by_cuda_index(\n gpu.id)\n self._gpus.append(gpu_device)\n else:\n for gpu in gpus:\n gpu_device = GPUDeviceFactory.create_device_by_uuid(gpu)\n self._gpus.append(gpu_device)\n\n gpu_uuids = []\n for gpu in self._gpus:\n gpu_uuids.append(str(gpu.device_uuid(), encoding='ascii'))\n gpu_uuids_str = ','.join(gpu_uuids)\n logger.info(f'Using GPU(s) with UUID(s) = {{ {gpu_uuids_str} }} for the analysis.')\n\n # Is the background thread active\n self._thread_active = False\n\n # Background thread collecting results\n self._thread = None\n\n # Thread pool\n self._thread_pool = ThreadPool(processes=1)\n self._tags = tags\n\n def _monitoring_loop(self):\n frequency = self._frequency\n\n while self._thread_active:\n begin = time.time()\n # Monitoring iteration implemented by each of the subclasses\n self._monitoring_iteration()\n\n duration = time.time() - begin\n if duration < frequency:\n time.sleep(frequency - duration)\n\n @abstractmethod\n def _monitoring_iteration(self):\n \"\"\"\n Each of the subclasses must implement this.\n This is called to execute a single round of monitoring.\n \"\"\"\n\n pass\n\n @abstractmethod\n def _collect_records(self):\n \"\"\"\n This method is called to collect all the monitoring records.\n It is called in the stop_recording_metrics function after\n the background thread has stopped.\n \"\"\"\n\n pass\n\n def start_recording_metrics(self):\n \"\"\"\n Start recording the metrics.\n \"\"\"\n\n self._thread_active = True\n self._thread = self._thread_pool.apply_async(self._monitoring_loop)\n\n def stop_recording_metrics(self):\n \"\"\"\n Stop recording metrics. This will stop monitring all the metrics.\n \"\"\"\n\n if not self._thread_active:\n raise TritonModelAnalyzerException(\n 'start_recording_metrics should be called before\\\n stop_recording_metrics')\n\n self._thread_active = False\n self._thread = None\n\n return self._collect_records()\n","sub_path":"model_analyzer/monitor/monitor.py","file_name":"monitor.py","file_ext":"py","file_size_in_byte":4502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"569860462","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# __author__ = 'Arthur|http://wingedwhitetiger.com/'\n\nimport os\nimport maya.cmds as mc\nfrom PySide2 import QtWidgets, QtCore\nfrom toolkitLib import maya_ui_operation\ncamera_template = 'M:/BA/publish/shots/BA{seq_name}/c{shot_name}/'\npre_template = [u'|front', u'|left', u'|persp', u'|side', u'|top']\n\n\nclass ExportCameraDialog(QtWidgets.QDialog):\n def __init__(self, parent=None):\n super(ExportCameraDialog, self).__init__(parent)\n\n main_layout = QtWidgets.QVBoxLayout(self)\n\n seq_layout = QtWidgets.QHBoxLayout()\n seq_layout.setAlignment(QtCore.Qt.AlignLeft)\n shot_layout = QtWidgets.QHBoxLayout()\n shot_layout.setAlignment(QtCore.Qt.AlignLeft)\n time_layout = QtWidgets.QHBoxLayout()\n time_layout.setAlignment(QtCore.Qt.AlignLeft)\n\n seq_label = QtWidgets.QLabel(u'seq:')\n self.__seq_box = QtWidgets.QSpinBox()\n self.__seq_box.setMinimum(0)\n self.__seq_box.setMaximum(999)\n self.__seq_box.setValue(0)\n self.__seq_box.setSingleStep(1)\n\n shot_label = QtWidgets.QLabel(u'shot:')\n self.__shot_box = QtWidgets.QSpinBox()\n self.__shot_box.setMinimum(0)\n self.__shot_box.setMaximum(999)\n self.__shot_box.setValue(0)\n self.__shot_box.setSingleStep(1)\n\n export_button = QtWidgets.QPushButton(u'Export..')\n\n main_layout.addLayout(seq_layout)\n main_layout.addLayout(shot_layout)\n main_layout.addLayout(time_layout)\n\n seq_layout.addWidget(seq_label)\n seq_layout.addWidget(self.__seq_box)\n\n shot_layout.addWidget(shot_label)\n shot_layout.addWidget(self.__shot_box)\n\n main_layout.addWidget(export_button)\n\n export_button.clicked.connect(self.__export)\n\n def __export(self):\n export_camera(self.__seq_box.value(), self.__shot_box.value())\n\n\ndef export_camera(seq, shot):\n seq = str(seq).zfill(3)\n shot = str(shot).zfill(3)\n\n backup_sel = mc.ls(sl=True)\n camera_list = mc.listRelatives(mc.ls(cameras=True, long=True), parent=True, type='transform', fullPath=True)\n\n cameras = []\n for i in list(set(camera_list).difference(set(pre_template))):\n if not mc.referenceQuery(i, isNodeReferenced=True):\n cameras.append(i)\n\n if cameras:\n mc.select(cameras, r=True)\n folder = camera_template.format(seq_name=seq, shot_name=shot)\n if not os.path.isdir(folder):\n os.makedirs(folder)\n file_path = os.path.join(folder, 'BA{seq_name}_c{shot_name}_camera.mb'.format(seq_name=seq, shot_name=shot))\n mc.file(file_path, typ='mayaBinary', es=True, pr=True, force=True, options='v=0;')\n\n mc.select(backup_sel, r=True)\n\n\ndef main():\n win = ExportCameraDialog(maya_ui_operation.get_maya_window('PySide'))\n win.show()\n\nif __name__ == \"__main__\":\n pass\n\n","sub_path":"WitToolkit/Maya/2017/scripts/python/toolkitTool/tap4fun/publish_camera.py","file_name":"publish_camera.py","file_ext":"py","file_size_in_byte":2876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"50453656","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Aug 30 18:28:43 2018\n\n@author: Panku\n\"\"\"\nimport speech_recognition as sr\n\n# obtain audio from the microphone\nr = sr.Recognizer()\nwith sr.Microphone() as source:\n print(\"Say something!\")\n audio = r.listen(source)\n\n\n# recognize speech using Google Speech Recognition\ntry:\n print(\"Google Speech Recognition thinks you said \" + r.recognize_google(audio))\nexcept sr.UnknownValueError:\n print(\"Google Speech Recognition could not understand audio\")\nexcept sr.RequestError as e:\n print(\"Could not request results from Google Speech Recognition service; {0}\".format(e))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# recognize speech using Google Cloud Speech\nGOOGLE_CLOUD_SPEECH_CREDENTIALS = r\"\"\"INSERT THE CONTENTS OF THE GOOGLE CLOUD SPEECH JSON CREDENTIALS FILE HERE\"\"\"\ntry:\n print(\"Google Cloud Speech thinks you said \" + r.recognize_google_cloud(audio, credentials_json=GOOGLE_CLOUD_SPEECH_CREDENTIALS))\nexcept sr.UnknownValueError:\n print(\"Google Cloud Speech could not understand audio\")\nexcept sr.RequestError as e:\n print(\"Could not request results from Google Cloud Speech service; {0}\".format(e))\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"349721643","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('plans', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='CreditPlan',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('order', models.PositiveIntegerField(editable=False, db_index=True)),\n ('name', models.CharField(unique=True, max_length=100, verbose_name='name')),\n ('description', models.TextField(null=True, verbose_name='description', blank=True)),\n ('credits', models.PositiveIntegerField(verbose_name='number of credits')),\n ('available', models.BooleanField(default=False, help_text='Is still available for purchase', db_index=True, verbose_name='available')),\n ('visible', models.BooleanField(default=True, help_text='Is visible in current offer', db_index=True, verbose_name='visible')),\n ('created', models.DateTimeField(auto_now_add=True)),\n ('price', models.DecimalField(max_digits=7, decimal_places=2, db_index=True)),\n ],\n options={\n 'ordering': ('price',),\n 'verbose_name': 'credit plan',\n 'verbose_name_plural': 'credit plans',\n },\n bases=(models.Model,),\n ),\n ]\n","sub_path":"plans/migrations/0002_creditplan.py","file_name":"0002_creditplan.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"40455434","text":"import multiprocessing\nfrom multiprocessing import Process, Queue \nfrom NeuralNetwork import NN\nfrom NetworkSimulation import Sim\nimport numpy as np\nimport pandas as pd\nimport time\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\ndef avg(x):\n return sum(x) / len(x)\n\ndef write_to_file(loc, x):\n f = open(loc, 'a+')\n f.write(str(x))\n f.write('\\n')\n f.close()\n\ndef trained_network(n, seed, n_neurons, ms, eta, dt, plastic_synapse):\n NNx = NN(n_neurons = n_neurons, plastic_synapse=True)\n Simx = Sim(NNet=NNx, ms=ms, eta=eta, dt=dt, updates=False)\n Simx.run()\n for i in range(n-1):\n NNx = NN(n_neurons=n_neurons, plastic_synapse=True, d = NNx.d, L=NNx.L)\n Simx = Sim(NNet=NNx, ms=ms, eta=eta, dt=dt, updates=False)\n Simx.run()\n return NN(n_neurons=n_neurons, plastic_synapse=plastic_synapse, d = NNx.d, L = NNx.L, seed=seed)\n\ndef quant(plastic_synapse, activation,n_stim, dt, eta, frac_tuned, n_neurons, ms, sd, L_noise, rws, pretune, connectivity):\n \"\"\" runs a Sim, quantifies fraction of stim retained and returns \"\"\"\n if(pretune==0):\n NNx = NN(n_neurons=n_neurons,plastic_synapse=plastic_synapse,n_stim=n_stim,activation=activation, frac_tuned=frac_tuned,\n L_noise=L_noise, rws=rws, seed=sd, connectivity=connectivity)\n else:\n NNx = trained_network(pretune, sd, n_neurons, ms, eta, dt, plastic_synapse)\n Simx = Sim(ms=ms, NNet=NNx, updates=False, dt=dt)\n Simx.run()\n if(n_stim ==1):\n stim = (Simx.sdf / float(Simx.initial_stim)).values.ravel()\n else:\n stim = list()\n for i in range(n_stim):\n stim.append(Simx.sdf[i] / float(Simx.initial_stim[0][i]))\n return stim\n\ndef worker(iters, stim_lock, stim_l, n, plastic_synapse, activation, n_stim, dt, eta, frac_tuned, n_neurons,\n ms, sd, L_noise, rws, pretune, connectivity):\n \"\"\" worker function takes Sims to run and a queue to place lists of\n fraction of stim retained \"\"\"\n for i in range(len(iters)):\n print('Running worker ' + str(n) + ' Sim ' + str(i))\n stim = quant(plastic_synapse, activation,n_stim, dt, eta, frac_tuned, n_neurons, ms, sd, L_noise, rws, pretune, connectivity)\n if(n_stim == 1):\n stim = [stim]\n for i in range(n_stim):\n stim_csv = ','.join(['%.5f' % num for num in stim[i]])\n stim_lock.acquire()\n write_to_file(stim_l[i], stim_csv)\n stim_lock.release()\n \ndef PQ(n_iters,n_neurons, stim_l, ms,plastic_synapse, activation='relu', n_stim=1, dt=.01,\n eta=.0001, seeds=None, frac_tuned=1, nps=None, L_noise = 0, rws = False, pretune=0, connectivity = 1):\n\n start_time = time.time()\n \"\"\" splits up Sims into num of available cpus - 1, runs and puts list of\n results on queue \"\"\"\n if nps is None:\n nps = 4 \n if n_iters < nps:\n nps = n_iters \n print('Running ' + str(nps) + ' processes')\n \n stim_lock = multiprocessing.Lock()\n iterchunks = np.array_split(list(range(n_iters)), nps)\n procs = list() \n ## start process \n for i in range(nps):\n if seeds is not None:\n sd = seeds[i]\n else:\n sd = np.random.randint(0,1000)\n p = multiprocessing.Process(\n target=worker,\n args = (iterchunks[i], stim_lock, stim_l, i, plastic_synapse, activation,\n n_stim, dt, eta, frac_tuned, \n n_neurons, ms, sd, L_noise, rws, pretune, connectivity))\n procs.append(p)\n p.start()\n \n for p in procs:\n p.join()\n return (time.time() - start_time)\n\n\n","sub_path":"quantify_sims_multithreading.py","file_name":"quantify_sims_multithreading.py","file_ext":"py","file_size_in_byte":3639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"308198930","text":"\"\"\"smartmibackend URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\n# from rest_framework.authtoken import views\nfrom django.conf.urls.static import static\nfrom django.conf import settings\n\nfrom smartmibackend import views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('api-auth/', include('rest_framework.urls')),\n path('api-token-auth/', views.obtain_auth_token),\n path('api/common/', include('applications.common.urls')),\n path('api/users/', include('applications.users.urls')),\n path('api/customers/', include('applications.customers.urls')),\n path('api/projects/', include('applications.projects.urls')),\n path('api/products/', include('applications.products.urls')),\n]\nurlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"smartmibackend/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"195429873","text":"from django.shortcuts import render,get_object_or_404 ,redirect\nfrom .models import Question,Answer,UserAnswer\nfrom django.http import Http404\nfrom .forms import UserResponseForm\n# Create your views here.\n\ndef home(request):\n\tif request.user.is_authenticated() and request.user.is_staff:\n\t\tform = UserResponseForm(request.POST or None)\n\t\tif form.is_valid():\n\n\t\t\tquestion_id = form.cleaned_data.get('question_id')\n\t\t\tanswer_id = form.cleaned_data.get('answer_id')\n\t\t\tquestion_instance=Question.objects.get(id=question_id)\n\t\t\tanswer_instance = Answer.objects.get(id=answer_id)\n\n\n\n\t\tqueryset = Question.objects.all().order_by('-timestamp') \n\n\t\tinstance = queryset[0]\n\t\tcontext = {\n\t\t\t\"form\" : form,\n\t\t\t\"instance\" : instance\n\t\t\t# \"queryset\": queryset\n\t\t}\n\t\treturn render(request,\"questions/home.html\",context)\n\telse:\n\t\traise Http404\n\ndef single(request,id):\n\n\t\n\tif request.user.is_authenticated() and request.user.is_staff:\n\t\tqueryset = Question.objects.all().order_by('-timestamp') \n\t\tinstance = get_object_or_404(Question,id=id)\n\n\t\ttry:\n\t\t\tuser_answer = UserAnswer.objects.get(user=request.user,question=instance)\n\t\texcept UserAnswer.DoesNotExist:\n\t\t\tuser_answer = UserAnswer()\n\t\texcept UserAnswer.MultipleObjectsReturned:\n\t\t\tuser_answer = UserAnswer.objects.filter(user=request.user,question=instance)[0]\n\t\texcept:\n\t\t\tuser_answer - UserAnswer()\n\t\t\n\t\tform = UserResponseForm(request.POST or None)\n\t\tif form.is_valid():\n\t\t\t\n\t\t\tquestion_id = form.cleaned_data.get('question_id')\n\n\t\t\tanswer_id = form.cleaned_data.get('answer_id')\n\t\t\timportance_level = form.cleaned_data.get('importance_level')\n\n\t\t\ttheir_importance_level = form.cleaned_data.get('their_importance_level')\n\t\t\ttheir_answer_id = form.cleaned_data.get('their_answer_id')\n\n\t\t\tquestion_instance=Question.objects.get(id=question_id)\n\t\t\tanswer_instance = Answer.objects.get(id=answer_id)\n\t\t\n\n\n\t\t\tnew_user_answer = UserAnswer()\n\t\t\tnew_user_answer.user = request.user\n\t\t\tnew_user_answer.question = question_instance\n\t\t\tnew_user_answer.my_answer = answer_instance\n\t\t\tnew_user_answer.my_answer_importance = importance_level\n\t\t\tif their_answer_id != -1:\n\t\t\t\ttheir_answer_instance = Answer.objects.get(id=their_answer_id)\n\t\t\t\tnew_user_answer.their_answer = their_answer_instance\n\t\t\t\tnew_user_answer.their_importance = their_importance_level\n\t\t\telse:\n\t\t\t\tnew_user_answer.their_answer = None\n\t\t\t\tnew_user_answer.their_importance = \"Not Important\"\n\t\t\tnew_user_answer.save()\n\n\n\t\t\t\n\n\t\t\tnext_q = Question.objects.all().order_by(\"?\").first()\n\t\t\treturn redirect(\"question_single\",id=next_q.id)\n\n\n\t\tcontext = {\n\t\t\t\"form\" : form,\n\t\t\t\"instance\" : instance,\n\t\t\t'user_answer' :user_answer,\n\t\t\t# \"queryset\": queryset\n\t\t}\n\t\treturn render(request,\"questions/single.html\",context)\n\telse:\n\t\traise Http404","sub_path":"src/questions/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"560164395","text":"\"\"\"empty message\n\nRevision ID: 4d5e12ffe770\nRevises: None\nCreate Date: 2014-09-28 15:25:48.945381\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '4d5e12ffe770'\ndown_revision = None\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.create_table('accusation',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('who', sa.String(length=255), nullable=True),\n sa.Column('when_s', sa.String(length=255), nullable=True),\n sa.Column('when_e', sa.String(length=255), nullable=True),\n sa.Column('how', sa.String(length=255), nullable=True),\n sa.Column('made_date', sa.DateTime(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('accusation')\n ### end Alembic commands ###\n","sub_path":"migrations/versions/4d5e12ffe770_.py","file_name":"4d5e12ffe770_.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"26448197","text":"# Q7: How common is the most common last name? Which is it?\nimport helper\n\ndata = helper.read_salaries()\nwith open(\"/Users/Babycake/Desktop/UChicago/Spring2018/ITP/s18-a03/salaries.csv\", \"r\") as file:\n for line in file:\n item_list = line.strip().replace(\"\\\"\",\"\").split(',')\n item_list = [item.strip() for item in item_list]\nnames = helper.get_column(data, 1) # get first names\ncounts = helper.counts(names) # count them\n\nprint(helper.dict_max_value(counts)) # print maximum\n\n#'Michael J', 268\n","sub_path":"q7.py","file_name":"q7.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"101695066","text":"import tornado.web\nimport datetime\nfrom decimal import Decimal\nfrom model.user import user\nfrom model.chats import chats\nfrom controller.AuthenticationHandlers import SigninBaseHandler\n\nclass ChatsShowHandler(SigninBaseHandler):\n def get(self, thread_id):\n # ログインしていなければログイン画面へリダイレクト\n if not self.current_user:\n self.redirect(\"/signin\")\n return\n\n # サインインユーザーの取得\n _id = tornado.escape.xhtml_escape(self.current_user)\n _signedInUser = user.find(int(_id))\n\n # モデルから全てのチャットを取得\n ch = chats.select(thread_id)\n if ch is None: raise tornado.web.HTTPError(404) # データが見つからない場合は404エラーを返す\n\n # chats.htmlへリダイレクト\n self.render(\"chats.html\", user=_signedInUser, mode=\"show\", chats=ch, messages=[], errors=[], thread=thread_id)\n\nclass ChatsInsertHandler(SigninBaseHandler):\n def get(self, thread_id):\n # ログインしていなければログイン画面へリダイレクト\n if not self.current_user:\n self.redirect(\"/signin\")\n return\n\n # サインインユーザの取得\n _id = tornado.escape.xhtml_escape(self.current_user)\n _signedInUser = user.find(int(_id))\n\n # 他の画面からinsert-textの取得\n insert_text = self.get_argument(\"insert-text\", None)\n\n ch = chats.build()\n ch.attr[\"user_id\"] = int(_id)\n ch.attr[\"content\"] = insert_text\n ch.attr[\"thread_id\"] = thread_id\n\n # DBにテキストの内容を挿入\n ch._db_save()\n\n self.redirect(\"/chats/\" + thread_id)\n","sub_path":"app/controller/ChatsHandlers.py","file_name":"ChatsHandlers.py","file_ext":"py","file_size_in_byte":1733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"2987120","text":"\"\"\"Create a simple user class\"\"\"\n\n\nclass User():\n \"\"\"Display complete details about given user\"\"\"\n\n def __init__(self, first_name, last_name):\n \"\"\"Initial constructor\"\"\"\n\n self.first_name = first_name\n self.last_name = last_name\n\n def describe_user(self):\n print(\"User Details\")\n print(\"------------\")\n print(f\"Full Name :\\t {self.first_name} {self.last_name}\")\n print(\n f\"Email: \\t {self.first_name.lower()}.{self.last_name.lower()}@gmail.com\")\n print()\n\n\nuser_one = User(\"Naveen\", \"Mannam\")\nuser_two = User(\"Minny\", \"Mannam\")\nuser_three = User(\"Rohisuhas\", \"Kancharla\")\n\nuser_one.describe_user()\nuser_two.describe_user()\nuser_three.describe_user()\n","sub_path":"Chapter-9/Users/users-1.py","file_name":"users-1.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"282016128","text":"import hug\nimport time\nimport log\nimport conexao\nimport meses\nfrom random import *\n\n@hug.response_middleware()\ndef process_data(request, response, resource):\n response.set_header('Access-Control-Allow-Origin', '*')\n\n@hug.get(output=hug.output_format.json)\ndef testarconexao():\n connect = conexao.conectar()\n print(connect)\n print('Conectado')\n\n@hug.post(output=hug.output_format.json)\ndef cadastrarjogadores(nome: hug.types.text, celular: int, modalidade: int, id_time: int):\n try:\n data_cadastro = time.strftime(\"%Y-%m-%d %H:%M\")\n insert = f'INSERT INTO jogador (nome, celular, data_cadastro) VALUES (\\'{nome}\\',\\'{celular}\\', \\'{data_cadastro}\\')'\n connect = conexao.conectar()\n conn = connect.cursor()\n conn.execute(insert)\n connect.commit()\n id_jogador = conn.lastrowid\n administrador = 'N'\n insert = f'INSERT INTO detalhe_time (id_time, id_jogador, administrador, modalidade, data_cadastro) VALUES (\\'{id_time}\\',\\'{id_jogador}\\',\\'{administrador}\\', \\'{modalidade}\\', \\'{data_cadastro}\\')'\n conn.execute(insert)\n connect.commit()\n if modalidade == 2:\n mes_atual = time.strftime(\"%m\")\n ano_atual = time.strftime(\"%Y\")\n select = f'SELECT id_mensalidade FROM mensalidade where id_time = \\'{id_time}\\' and id_jogador = \\'{id_jogador}\\' and mes = \\'{mes_atual}\\' and ano = \\'{ano_atual}\\''\n conn.execute(select)\n id_mensalidade = conn.fetchone()\n if id_mensalidade is None:\n data_cadastro = time.strftime(\"%Y-%m-%d\")\n situacao = 2\n valor_pagamento = 0\n insert = f'INSERT INTO mensalidade (id_time, id_jogador, mes, ano, data_cadastro, situacao, valor_pagamento) VALUES (\\'{id_time}\\',\\'{id_jogador}\\',\\'{mes_atual}\\',\\'{ano_atual}\\',\\'{data_cadastro}\\',\\'{situacao}\\',\\'{valor_pagamento}\\')'\n conn.execute(insert)\n connect.commit()\n else:\n print('Fazer nada', id_mensalidade)\n conn.close()\n sucesso = 'true' #Sucesso retorna true\n except:\n sucesso = 'false' #Erro retorna false\n\n return {'sucesso': sucesso, 'nome': nome, 'celular': celular, 'modalidade': modalidade}\n\n@hug.post(output=hug.output_format.json)\ndef cadastraradministradores(nome: hug.types.text, nome_time: hug.types.text, celular: int, modalidade: int, email: hug.types.text, senha: hug.types.text):\n try:\n administrador = 'S'\n salt = randint(2, 7)\n hash = log.login(senha, salt)\n data_cadastro = time.strftime(\"%Y-%m-%d %H:%M\")\n insert = f'INSERT INTO jogador (nome, celular, email, senha, salto, data_cadastro) VALUES (\\'{nome}\\',\\'{celular}\\', \\'{email}\\',\\'{hash}\\',\\'{salt}\\',\\'{data_cadastro}\\')'\n connect = conexao.conectar()\n conn = connect.cursor()\n conn.execute(insert)\n connect.commit()\n id_jogador = conn.lastrowid\n saldo = 0\n saldo_informado = 'N'\n insert = f'INSERT INTO time (nome_time, saldo, saldo_informado, data_cadastro) VALUES (\\'{nome_time}\\', \\'{saldo}\\', \\'{saldo_informado}\\', \\'{data_cadastro}\\')'\n conn.execute(insert)\n connect.commit()\n id_time = conn.lastrowid\n insert = f'INSERT INTO detalhe_time (id_time, id_jogador, administrador, modalidade, data_cadastro) VALUES (\\'{id_time}\\',\\'{id_jogador}\\',\\'{administrador}\\', \\'{modalidade}\\', \\'{data_cadastro}\\')'\n conn.execute(insert)\n connect.commit()\n conn.close()\n sucesso = 'true' #Sucesso retorna true\n except:\n sucesso = 'false' #Falha retorna false\n\n return {'sucesso': sucesso}\n\n@hug.post(output=hug.output_format.json)\ndef verificatimes(id_jogador: int):\n nomes_time = []\n times = []\n connect = conexao.conectar()\n conn = connect.cursor()\n select = f'SELECT distinct(id_time) FROM detalhe_time where id_jogador = \\'{id_jogador}\\' and administrador = \"S\" '\n conn.execute(select)\n linhas = conn.fetchall()\n for linha in linhas:\n times = linhas\n id_time = int(linha[0])\n select = f'SELECT nome_time FROM time where id_time = \\'{id_time}\\''\n conn.execute(select)\n resultado2 = conn.fetchone()\n nomes_time.append(resultado2)\n conn.close()\n return {'times': times, 'nomes_time': nomes_time}\n\n@hug.post(output=hug.output_format.json)\ndef listarmensalidadeatrasada(id_time: int):\n nomes_jogador = []\n nomes_meses = []\n mensalidades = 0\n sucesso = 0\n connect = conexao.conectar()\n conn = connect.cursor()\n select = f'SELECT id_mensalidade, id_jogador, mes, ano, situacao, valor_pagamento FROM mensalidade where id_time = \\'{id_time}\\' and situacao in(2,3) order by data_cadastro asc'\n conn.execute(select)\n linhas = conn.fetchall()\n if linhas is None:\n sucesso = 'false'\n else:\n for linha in linhas:\n mensalidades = linhas\n id_jogador = int(linha[1])\n select = f'SELECT nome FROM jogador where id_jogador = \\'{id_jogador}\\''\n conn.execute(select)\n resultado = conn.fetchone()\n nomes_jogador.append(resultado)\n nomes_meses.append(meses.convertemeses(linha[2]))\n sucesso = 'true'\n conn.close()\n return {'mensalidades': mensalidades, 'nomes_jogador': nomes_jogador, 'sucesso': sucesso, 'nomes_meses': nomes_meses}\n\n@hug.post(output=hug.output_format.json)\ndef listarmensalidades(id_time: int):\n nomes_jogadoremdia = []\n nomes_mesesemdia = []\n mensalidadesemdia = 0\n sucesso = 0\n connect = conexao.conectar()\n conn = connect.cursor()\n select = f'SELECT id_mensalidade, id_jogador, mes, ano, situacao, valor_pagamento FROM mensalidade where id_time = \\'{id_time}\\' and situacao = 1 order by data_cadastro asc'\n conn.execute(select)\n linhas = conn.fetchall()\n if linhas is None:\n sucesso = 'false'\n else:\n for linha in linhas:\n mensalidadesemdia = linhas\n id_jogador = int(linha[1])\n select = f'SELECT nome FROM jogador where id_jogador = \\'{id_jogador}\\''\n conn.execute(select)\n resultado = conn.fetchone()\n nomes_jogadoremdia.append(resultado)\n nomes_mesesemdia.append(meses.convertemeses(linha[2]))\n sucesso = 'true'\n conn.close()\n return {'mensalidadesemdia': mensalidadesemdia, 'nomes_jogadoremdia': nomes_jogadoremdia, 'nomes_mesesemdia': nomes_mesesemdia, 'sucesso': sucesso}\n\n@hug.post(output=hug.output_format.json)\ndef pagarmensalidade(id_time: int, id_mensalidade: int, pagamento_mensalidade: int, valor_pagamento: float):\n data_pagamento = time.strftime(\"%Y-%m-%d %H:%M\")\n connect = conexao.conectar()\n conn = connect.cursor()\n select = f'SELECT id_mensalidade, id_jogador, valor_pagamento FROM mensalidade where id_mensalidade = \\'{id_mensalidade}\\''\n conn.execute(select)\n linhas = conn.fetchall()\n for linha in linhas:\n id_mensalidade = linha[0]\n id_jogador = linha[1]\n valor_ja_pago = float(linha[2])\n if id_mensalidade is None:\n sucesso = 'false'\n else:\n valor_total_pago = valor_pagamento + valor_ja_pago\n update = f'UPDATE mensalidade set situacao = \\'{pagamento_mensalidade}\\', valor_pagamento = \\'{valor_total_pago}\\', data_pagamento = \\'{data_pagamento}\\' where id_mensalidade = \\'{id_mensalidade}\\''\n conn.execute(update)\n connect.commit()\n descricao = 'Pagamento de mensalidade'\n insert = f'INSERT into transacao (id_time, id_jogador, descricao, valor, tipo_transacao, data_transacao)' \\\n f'VALUES (\\'{id_time}\\', \\'{id_jogador}\\', \\'{descricao}\\', \\'{valor_pagamento}\\', 1, \\'{data_pagamento}\\')'\n conn.execute(insert)\n connect.commit()\n select = f'SELECT saldo FROM time where id_time = \\'{id_time}\\''\n conn.execute(select)\n resultado = conn.fetchone()\n valor_saldo = float(resultado[0])\n saldo_final = valor_saldo + valor_pagamento\n update = f'UPDATE time set saldo = \\'{saldo_final}\\' where id_time = \\'{id_time}\\''\n conn.execute(update)\n connect.commit()\n sucesso = 'true'\n conn.close()\n return {'sucesso': sucesso}\n\n@hug.post(output=hug.output_format.json)\ndef estornarmensalidade(id_time: int, id_mensalidade: int, motivo_estorno: hug.types.text):\n data_estorno = time.strftime(\"%Y-%m-%d %H:%M\")\n connect = conexao.conectar()\n conn = connect.cursor()\n select = f'SELECT id_mensalidade, id_jogador, valor_pagamento FROM mensalidade where id_mensalidade = \\'{id_mensalidade}\\''\n conn.execute(select)\n linhas = conn.fetchall()\n for linha in linhas:\n id_mensalidade = linha[0]\n id_jogador = linha[1]\n valor_estorno = float(linha[2])\n if id_mensalidade is None:\n sucesso = 'false'\n else:\n update = f'UPDATE mensalidade set situacao = 2, valor_pagamento = 0 where id_mensalidade = \\'{id_mensalidade}\\''\n conn.execute(update)\n connect.commit()\n descricao_motivo_estorno = 'Estorno ' + motivo_estorno\n insert = f'INSERT into transacao (id_time, id_jogador, descricao, valor, tipo_transacao, data_transacao)' \\\n f'VALUES (\\'{id_time}\\', \\'{id_jogador}\\', \\'{descricao_motivo_estorno}\\', \\'{valor_estorno}\\', 3, \\'{data_estorno}\\')'\n conn.execute(insert)\n connect.commit()\n select = f'SELECT saldo FROM time where id_time = \\'{id_time}\\''\n conn.execute(select)\n resultado = conn.fetchone()\n valor_saldo = float(resultado[0])\n saldo_final = valor_saldo - valor_estorno\n update = f'UPDATE time set saldo = \\'{saldo_final}\\' where id_time = \\'{id_time}\\''\n conn.execute(update)\n connect.commit()\n sucesso = 'true'\n conn.close()\n return {'sucesso': sucesso}\n\n@hug.post(output=hug.output_format.json)\ndef excluirmensalidade(id_time: int, id_mensalidade: int):\n try:\n data_exclusao = time.strftime(\"%Y-%m-%d %H:%M\")\n connect = conexao.conectar()\n conn = connect.cursor()\n select = f'SELECT id_jogador, valor_pagamento FROM mensalidade where id_mensalidade = \\'{id_mensalidade}\\''\n conn.execute(select)\n resultado = conn.fetchone()\n id_jogador = resultado[0]\n valor_estorno = resultado[1]\n delete = f'DELETE FROM mensalidade WHERE id_mensalidade = \\'{id_mensalidade}\\''\n conn.execute(delete)\n connect.commit()\n if valor_estorno > 0:\n descricao = 'Exclusão de mensalidade com valor pago'\n insert = f'INSERT into transacao (id_time, id_jogador, descricao, valor, tipo_transacao, data_transacao)' \\\n f'VALUES (\\'{id_time}\\', \\'{id_jogador}\\', \\'{descricao}\\', \\'{valor_estorno}\\', 3, \\'{data_exclusao}\\')'\n conn.execute(insert)\n connect.commit()\n select = f'SELECT saldo FROM time where id_time = \\'{id_time}\\''\n conn.execute(select)\n resultado = conn.fetchone()\n valor_saldo = resultado[0]\n saldo_final = valor_saldo - valor_estorno\n update = f'UPDATE time set saldo = \\'{saldo_final}\\' where id_time = \\'{id_time}\\''\n conn.execute(update)\n connect.commit()\n conn.close()\n sucesso = 'true'\n else:\n sucesso = 'true'\n conn.close()\n except:\n sucesso = 'false'\n conn.close()\n return {'sucesso': sucesso}\n\n@hug.post(output=hug.output_format.json)\ndef verificarsaldoinicial(id_time: int):\n connect = conexao.conectar()\n conn = connect.cursor()\n saldo_informado = 'S'\n select = f'SELECT saldo_informado FROM time where id_time = \\'{id_time}\\' and saldo_informado = \\'{saldo_informado}\\''\n conn.execute(select)\n saldo = conn.fetchone()\n conn.close()\n if saldo is None:\n sucesso = 'false'\n else:\n sucesso = 'true'\n return {'sucesso': sucesso}\n\n@hug.post(output=hug.output_format.json)\ndef salvarsaldotime(id_time: int, saldo_time: float):\n try:\n connect = conexao.conectar()\n conn = connect.cursor()\n saldo_informado = 'S'\n update = f'UPDATE time set saldo = \\'{saldo_time}\\', saldo_informado = \\'{saldo_informado}\\'' \\\n f'WHERE id_time = \\'{id_time}\\''\n conn.execute(update)\n connect.commit()\n conn.close()\n sucesso = 'true'\n except:\n sucesso = 'false'\n return {'sucesso': sucesso}\n\n@hug.post(output=hug.output_format.json)\ndef listarjogadores(id_time: int):\n try:\n connect = conexao.conectar()\n conn = connect.cursor()\n select = f'select count(id_jogador) from detalhe_time where id_time = \\'{id_time}\\' and administrador = \"N\"'\n conn.execute(select)\n resultado = conn.fetchone()\n qtd_jogador = resultado[0]\n conn.close()\n sucesso = 'true'\n except:\n sucesso = 'false'\n return {'sucesso': sucesso, 'qtd_jogador': qtd_jogador}\n\n@hug.post(output=hug.output_format.json)\ndef listartodosjogadores(id_time: int):\n try:\n nomes_jogadores = []\n modalidades = []\n connect = conexao.conectar()\n conn = connect.cursor()\n select = f'select distinct(id_jogador), modalidade, administrador from detalhe_time where id_time = \\'{id_time}\\''\n conn.execute(select)\n todosidjogadores = conn.fetchall()\n for jogador in todosidjogadores:\n todosjogadores = todosidjogadores\n modalidade = jogador[1]\n modalidades.append(modalidade)\n id_jogador = jogador[0]\n select = f'SELECT nome FROM jogador where id_jogador = \\'{id_jogador}\\''\n conn.execute(select)\n resultado = conn.fetchone()\n nomes_jogadores.append(resultado)\n conn.close()\n sucesso = 'true'\n except:\n conn.close()\n sucesso = 'false'\n return {'sucesso': sucesso, 'todosjogadores': todosjogadores, 'nomes_jogadores': nomes_jogadores, 'modalidades': modalidades}\n\n\n@hug.post(output=hug.output_format.json)\ndef cadastrarjogos(id_time: int, jogadores: hug.types.multiple, data_jogo: hug.types.text, hora_jogo: hug.types.text):\n data_jogo_formatada = (data_jogo + ' ' + hora_jogo)\n jogadores = jogadores[0]\n jogadores = jogadores.replace('\"', \"\")\n jogadores = jogadores.replace('[', \"\")\n jogadores = jogadores.replace(']', \"\")\n jogadores = jogadores.split(',')\n connect = conexao.conectar()\n conn = connect.cursor()\n insert = f'INSERT INTO jogo (id_time, data_jogo) VALUES (\\'{id_time}\\',\\'{data_jogo_formatada}\\')'\n conn.execute(insert)\n connect.commit()\n id_jogo = conn.lastrowid\n for jogador in jogadores:\n select = f'SELECT modalidade FROM detalhe_time where id_time = \\'{id_time}\\' and id_jogador = \\'{jogador}\\''\n conn.execute(select)\n modalidade = conn.fetchone()\n modalidade = modalidade[0]\n if modalidade == 1:\n status = 2\n else:\n status = 1\n insert = f'INSERT INTO detalhe_jogo (id_jogo, id_jogador, id_time, valor_pago, modalidade, status) VALUES (\\'{id_jogo}\\', \\'{jogador}\\', \\'{id_time}\\', 0 , \\'{modalidade}\\', \\'{status}\\')'\n conn.execute(insert)\n connect.commit()\n conn.close()\n sucesso = 'true'\n return {'sucesso': sucesso}\n\n@hug.post(output=hug.output_format.json)\ndef listaravulsosatraso(id_time: int):\n nomes_avulsos = []\n connect = conexao.conectar()\n conn = connect.cursor()\n select = f'SELECT dj.id_jogo, j.data_jogo, dj.id_jogador, dj.valor_pago FROM detalhe_jogo dj JOIN jogo j ON dj.id_jogo = j.id_jogo WHERE dj.id_time = \\'{id_time}\\' and dj.modalidade = 1 and dj.status = 2 order by j.data_jogo asc'\n conn.execute(select)\n resultado = conn.fetchall()\n if not resultado:\n sucesso = 'false'\n conn.close()\n else:\n for linha in resultado:\n id_jogador = linha[2]\n select = f'SELECT nome FROM jogador where id_jogador = \\'{id_jogador}\\''\n conn.execute(select)\n resultado_nomes = conn.fetchone()\n nomes_avulsos.append(resultado_nomes)\n sucesso = 'true'\n conn.close()\n return {'sucesso': sucesso, 'resultado': resultado, 'nomes_avulsos': nomes_avulsos}\n\n\n@hug.post(output=hug.output_format.json)\ndef pagaravulso(id_time: int, id_jogador_avulso: int, id_jogo: int, pagamento_avulso: int, valor_pagamento_avulso: float):\n data_pagamento = time.strftime(\"%Y-%m-%d %H:%M\")\n data_transacao = data_pagamento\n connect = conexao.conectar()\n conn = connect.cursor()\n select = f'SELECT valor_pago FROM detalhe_jogo where id_jogo = \\'{id_jogo}\\' and id_jogador = \\'{id_jogador_avulso}\\' and id_time = \\'{id_time}\\''\n conn.execute(select)\n resultado_avulso = conn.fetchone()\n valor_avulso_ja_pago = float(resultado_avulso[0])\n valor_total_pago = valor_pagamento_avulso + valor_avulso_ja_pago\n update = f'UPDATE detalhe_jogo set status = \\'{pagamento_avulso}\\', valor_pago = \\'{valor_total_pago}\\', data_pagamento = \\'{data_pagamento}\\' where id_jogo = \\'{id_jogo}\\' and id_jogador = \\'{id_jogador_avulso}\\' and id_time = \\'{id_time}\\''\n conn.execute(update)\n connect.commit()\n descricao = 'Pagamento de jogo avulso'\n insert = f'INSERT into transacao (id_time, id_jogador, descricao, valor, tipo_transacao, data_transacao)' \\\n f'VALUES (\\'{id_time}\\', \\'{id_jogador_avulso}\\', \\'{descricao}\\', \\'{valor_pagamento_avulso}\\', 1, \\'{data_transacao}\\')'\n conn.execute(insert)\n connect.commit()\n select = f'SELECT saldo FROM time where id_time = \\'{id_time}\\''\n conn.execute(select)\n resultado = conn.fetchone()\n valor_saldo = float(resultado[0])\n saldo_final = valor_saldo + valor_pagamento_avulso\n update = f'UPDATE time set saldo = \\'{saldo_final}\\' where id_time = \\'{id_time}\\''\n conn.execute(update)\n connect.commit()\n sucesso = 'true'\n conn.close()\n return {'sucesso': sucesso}\n\n@hug.post(output=hug.output_format.json)\ndef excluirvaloravulso(id_time: int, id_jogador_avulso_excluir: int, id_jogo_excluir: int):\n connect = conexao.conectar()\n conn = connect.cursor()\n select = f'SELECT id_jogo, valor_pago FROM detalhe_jogo where id_jogo = \\'{id_jogo_excluir}\\' and id_jogador = \\'{id_jogador_avulso_excluir}\\' and id_time = \\'{id_time}\\''\n conn.execute(select)\n resultado = conn.fetchall()\n if not resultado:\n sucesso = 'false'\n conn.close()\n else:\n for linhas in resultado:\n id_jogo_resultado = linhas[0]\n valor_pago = linhas[1]\n delete = f'DELETE FROM detalhe_jogo WHERE id_jogo = \\'{id_jogo_excluir}\\' and id_jogador = \\'{id_jogador_avulso_excluir}\\' and id_time = \\'{id_time}\\''\n conn.execute(delete)\n connect.commit()\n if valor_pago > 0:\n data_exclusao = time.strftime(\"%Y-%m-%d %H:%M\")\n descricao = 'Exclusao de jogo avulso com valor pago'\n insert = f'INSERT into transacao (id_time, id_jogador, descricao, valor, tipo_transacao, data_transacao)' \\\n f'VALUES (\\'{id_time}\\', \\'{id_jogador_avulso_excluir}\\', \\'{descricao}\\', \\'{valor_pago}\\', 3, \\'{data_exclusao}\\')'\n conn.execute(insert)\n connect.commit()\n select = f'SELECT saldo FROM time where id_time = \\'{id_time}\\''\n conn.execute(select)\n resultado = conn.fetchone()\n valor_saldo = resultado[0]\n saldo_final = valor_saldo - valor_pago\n update = f'UPDATE time set saldo = \\'{saldo_final}\\' where id_time = \\'{id_time}\\''\n conn.execute(update)\n connect.commit()\n conn.close()\n sucesso = 'true'\n conn.close()\n return {'sucesso': sucesso}\n\n@hug.post(output=hug.output_format.json)\ndef cadastrartransacao(id_time: int, id_jogador: int, descricao: hug.types.text, valor_transacao: float, tipo_transacao: int, data_transacao: hug.types.text):\n connect = conexao.conectar()\n conn = connect.cursor()\n insert = f'INSERT into transacao (id_time, id_jogador, descricao, valor, tipo_transacao, data_transacao)' \\\n f'VALUES (\\'{id_time}\\', \\'{id_jogador}\\', \\'{descricao}\\', \\'{valor_transacao}\\', \\'{tipo_transacao}\\', \\'{data_transacao}\\')'\n conn.execute(insert)\n connect.commit()\n select = f'SELECT saldo FROM time where id_time = \\'{id_time}\\''\n conn.execute(select)\n resultado = conn.fetchone()\n valor_saldo = float(resultado[0])\n if tipo_transacao == 1:\n saldo_final = valor_saldo + valor_transacao\n update = f'UPDATE time set saldo = \\'{saldo_final}\\' where id_time = \\'{id_time}\\''\n conn.execute(update)\n connect.commit()\n elif tipo_transacao == 2:\n saldo_final = valor_saldo - valor_transacao\n update = f'UPDATE time set saldo = \\'{saldo_final}\\' where id_time = \\'{id_time}\\''\n conn.execute(update)\n connect.commit()\n elif tipo_transacao == 3:\n saldo_final = valor_saldo - valor_transacao\n update = f'UPDATE time set saldo = \\'{saldo_final}\\' where id_time = \\'{id_time}\\''\n conn.execute(update)\n connect.commit()\n conn.close()\n sucesso = 'true'\n return {'sucesso': sucesso}\n\n@hug.post(output=hug.output_format.json)\ndef pesquisarjogadorcelular(celular_jogador: int):\n times = []\n nomes_times = []\n connect = conexao.conectar()\n conn = connect.cursor()\n select = f'select id_jogador from jogador where celular = \\'{celular_jogador}\\''\n conn.execute(select)\n resultado_jogadores = conn.fetchall()\n for linha in resultado_jogadores:\n select = f'select id_time from detalhe_time where id_jogador = \\'{linha[0]}\\''\n conn.execute(select)\n resultado_time = conn.fetchall()\n for x in resultado_time:\n times.append(x[0])\n select = f'select nome_time from time where id_time = \\'{x[0]}\\''\n conn.execute(select)\n nome_time = conn.fetchone()\n nome_time = nome_time[0]\n nomes_times.append(nome_time)\n conn.close()\n sucesso = 'true'\n return {'sucesso': sucesso, 'times': times, 'nomes_times': nomes_times}\n\n@hug.post(output=hug.output_format.json)\ndef listartransacao(id_time: int):\n nomes = []\n datas = []\n connect = conexao.conectar()\n conn = connect.cursor()\n select = f'SELECT id_jogador, descricao, valor, tipo_transacao, data_transacao FROM transacao WHERE id_time = \\'{id_time}\\' order by data_transacao asc'\n conn.execute(select)\n resultado = conn.fetchall()\n if not resultado:\n sucesso = 'false'\n conn.close()\n else:\n for linha in resultado:\n id_jogador = linha[0]\n select = f'SELECT nome FROM jogador where id_jogador = \\'{id_jogador}\\''\n conn.execute(select)\n resultado_nomes = conn.fetchone()\n nomes.append(resultado_nomes)\n data = str(linha[4])\n data = data[0:10]\n ano = data[0:4]\n mes = data[5:7]\n dia = data[8:10]\n data_formatada = (dia + '/' + mes + '/' + ano)\n datas.append(data_formatada)\n sucesso = 'true'\n conn.close()\n return {'sucesso': sucesso, 'nomes': nomes, 'resultado': resultado, 'datas': datas}\n\n@hug.post(output=hug.output_format.json)\ndef listarinfostime(id_time: int):\n try:\n connect = conexao.conectar()\n conn = connect.cursor()\n select = f'select saldo from time where id_time = \\'{id_time}\\''\n conn.execute(select)\n resultado_saldo = conn.fetchone()\n saldo = resultado_saldo[0]\n select = f'select count(id_jogador) from detalhe_time where id_time = \\'{id_time}\\' and administrador = \"S\"'\n conn.execute(select)\n resultado_adm = conn.fetchone()\n qtd_administrador = resultado_adm[0]\n select = f'select count(id_jogador) from detalhe_time where id_time = \\'{id_time}\\' and modalidade = 1'\n conn.execute(select)\n resultado_avulsos = conn.fetchone()\n qtd_avulso = resultado_avulsos[0]\n select = f'select count(id_jogador) from detalhe_time where id_time = \\'{id_time}\\' and modalidade = 2'\n conn.execute(select)\n resultado_mensal = conn.fetchone()\n qtd_mensal = resultado_mensal[0]\n select = f'select count(id_jogador) from detalhe_time where id_time = \\'{id_time}\\' and modalidade = 3'\n conn.execute(select)\n resultado_isento = conn.fetchone()\n qtd_isento = resultado_isento[0]\n select = f'select count(id_jogador) from detalhe_time where id_time = \\'{id_time}\\''\n conn.execute(select)\n resultado_total = conn.fetchone()\n qtd_total = resultado_total[0]\n select = f'select count(distinct(id_jogo)) from detalhe_jogo where id_time = \\'{id_time}\\''\n conn.execute(select)\n total_jogos = conn.fetchone()\n qtd_jogos = total_jogos[0]\n conn.close()\n sucesso = 'true'\n except:\n sucesso = 'false'\n return {'sucesso': sucesso, 'qtd_total': qtd_total, 'qtd_administrador': qtd_administrador, 'saldo': saldo, 'qtd_avulso': qtd_avulso, 'qtd_mensal': qtd_mensal, 'qtd_isento': qtd_isento, 'qtd_jogos': qtd_jogos}\n\n@hug.post(output=hug.output_format.json)\ndef infosadministrador(id_jogador: int):\n connect = conexao.conectar()\n conn = connect.cursor()\n select = f'select nome, celular, email from jogador where id_jogador = \\'{id_jogador}\\''\n conn.execute(select)\n dados_administrador = conn.fetchall()\n for linha in dados_administrador:\n dados_administrador = dados_administrador\n sucesso = 'true'\n return {'sucesso': sucesso, 'dados_administrador': dados_administrador}\n\n@hug.post(output=hug.output_format.json)\ndef editarinfosadministrador(id_jogador: int, nome_administrador_editado: hug.types.text, celular_administrador_editado: int, email_administrador_editado: hug.types.text):\n try:\n connect = conexao.conectar()\n conn = connect.cursor()\n select = f'select id_jogador from jogador where id_jogador = \\'{id_jogador}\\''\n conn.execute(select)\n dados_editar_administrador = conn.fetchone()\n dados_editar_administrador = dados_editar_administrador[0]\n if dados_editar_administrador > 0:\n print(dados_editar_administrador)\n update = f'UPDATE jogador set nome = \\'{nome_administrador_editado}\\', celular = \\'{celular_administrador_editado}\\', email = \\'{email_administrador_editado}\\' where id_jogador = \\'{id_jogador}\\''\n conn.execute(update)\n connect.commit()\n sucesso = 'true'\n else:\n sucesso = 'false'\n except:\n sucesso = 'false'\n return {'sucesso': sucesso}\n\n@hug.post(output=hug.output_format.json)\ndef detalhesjogadores(id_time: int, id_jogador: int):\n connect = conexao.conectar()\n conn = connect.cursor()\n select = f'SELECT j.nome, j.celular, dt.modalidade FROM detalhe_time dt JOIN jogador j ON dt.id_jogador = j.id_jogador WHERE dt.id_time = \\'{id_time}\\' and dt.id_jogador = \\'{id_jogador}\\''\n conn.execute(select)\n dados_jogador = conn.fetchall()\n for linha in dados_jogador:\n dados_jogador = dados_jogador\n sucesso = 'true'\n return {'sucesso': sucesso, 'dados_jogador': dados_jogador}\n\n@hug.post(output=hug.output_format.json)\ndef excluirjogadortime(id_time: int, id_jogador: int):\n connect = conexao.conectar()\n conn = connect.cursor()\n select = f'select id_jogador from detalhe_time where id_time = \\'{id_time}\\' and id_jogador = \\'{id_jogador}\\''\n conn.execute(select)\n dados_jogador_excluir = conn.fetchone()\n if dados_jogador_excluir is None:\n sucesso = 'false'\n else:\n dados_jogador_excluir = dados_jogador_excluir[0]\n delete = f'DELETE FROM detalhe_time WHERE id_time = \\'{id_time}\\' and id_jogador = \\'{dados_jogador_excluir}\\''\n conn.execute(delete)\n connect.commit()\n sucesso = 'true'\n return {'sucesso': sucesso, 'dados_jogador_excluir': dados_jogador_excluir}\n\n@hug.post(output=hug.output_format.json)\ndef editarinfosjogador(id_time: int, id_jogador_edicao: int, nome_jogador_edicao: hug.types.text, celular_jogador: int, modalidade_edicao: int):\n try:\n connect = conexao.conectar()\n conn = connect.cursor()\n update = f'UPDATE jogador set nome = \\'{nome_jogador_edicao}\\', celular = \\'{celular_jogador}\\' where id_jogador = \\'{id_jogador_edicao}\\''\n conn.execute(update)\n connect.commit()\n update = f'UPDATE detalhe_time set modalidade = \\'{modalidade_edicao}\\' where id_time = \\'{id_time}\\' and id_jogador = \\'{id_jogador_edicao}\\''\n conn.execute(update)\n connect.commit()\n sucesso = 'true'\n except:\n sucesso = 'false'\n return {'sucesso': sucesso}\n\n@hug.post(output=hug.output_format.json)\ndef verificaradministrador(id_time: int, id_jogador: int):\n connect = conexao.conectar()\n conn = connect.cursor()\n select = f'select administrador from detalhe_time where id_time = \\'{id_time}\\' and id_jogador = \\'{id_jogador}\\''\n conn.execute(select)\n dados_jogador_administrador = conn.fetchone()\n dados_jogador_administrador = dados_jogador_administrador[0]\n sucesso = 'true'\n return {'sucesso': sucesso, 'dados_jogador_administrador': dados_jogador_administrador}\n\n@hug.post(output=hug.output_format.json)\ndef editarjogadoradministracao(id_time: int, id_jogador: int, flag_administracao: hug.types.text):\n connect = conexao.conectar()\n conn = connect.cursor()\n update = f'UPDATE detalhe_time set administrador = \\'{flag_administracao}\\' where id_time = \\'{id_time}\\' and id_jogador = \\'{id_jogador}\\''\n conn.execute(update)\n connect.commit()\n sucesso = 'true'\n return {'sucesso': sucesso}\n\n","sub_path":"primeiro.py","file_name":"primeiro.py","file_ext":"py","file_size_in_byte":30063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"78507344","text":"def perm(r, c, sum_val):\n global min_val\n if r == n - 1 and c == n - 1:\n if sum_val < min_val:\n min_val = sum_val\n return\n\n if sum_val > min_val:\n return\n\n for i in range(2):\n nr = r + dr[i]\n nc = c + dc[i]\n if nr > -1 and nr < n and nc > -1 and nc < n:\n perm(nr, nc, sum_val + arr[nr][nc])\n\n\ndr = [1, 0]\ndc = [0, 1]\n\nfor tc in range(1, int(input()) + 1):\n n = int(input())\n arr = [list(map(int, input().split())) for _ in range(n)]\n min_val = 987654321\n perm(0, 0, arr[0][0])\n print('#%d %d' % (tc, min_val))","sub_path":"0415/5188.최소합.py","file_name":"5188.최소합.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"482488897","text":"\"\"\"operation action database\n\"\"\"\nimport ast\nimport logging.handlers\n\nfrom celery.task.control import revoke\nfrom datetime import datetime\nfrom rest_framework.response import Response\nfrom rest_framework.views import status\n\nfrom webapp.models import Connection, ConnectionHistory, Operation, OperationHistory, Port\nfrom webapp.views import walk\n\n\n# set logger\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger('operation_action_database')\n\n# create a file handler\nhandler = logging.handlers.RotatingFileHandler('operation_action_database.log', maxBytes=10485760,\n backupCount=10, encoding='utf-8')\nhandler.setLevel(logging.INFO)\n\n# create a logging format\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nhandler.setFormatter(formatter)\n\n# add the handlers to the logger\nlogger.addHandler(handler)\n\n\nclass OperationAction(object):\n\n @staticmethod\n def query_to_get_port_object(east, west):\n\n ports = Port.objects.all()\n for p in ports:\n\n if p.direction == 'E' and p.number == east:\n east = p\n\n if p.direction == 'W' and p.number == west:\n west = p\n\n return east, west\n\n @staticmethod\n def clear_latest_operation():\n\n action = ''\n east = ''\n west = ''\n uuid = ''\n\n operations = Operation.objects.all()\n if operations:\n for o in operations:\n request_obj = ast.literal_eval(o.request)\n action = request_obj['action']\n east = request_obj['east']\n west = request_obj['west']\n uuid = o.uuid\n\n if walk.is_dummy() is False:\n revoke(uuid, terminate=True) \n \n east, west = OperationAction.query_to_get_port_object(east, west)\n connections = Connection.objects.filter(east=east, west=west)\n\n if action == 'connect':\n connections.delete()\n else:\n connections.update(status='success', disconnected_date=None)\n\n connectionhistorys = ConnectionHistory.objects.filter(east=east, west=west)\n connectionhistorys.update(timestamp=datetime.now(), status='revoked')\n operations.delete()\n operationhistorys = OperationHistory.objects.filter(uuid=uuid)\n operationhistorys.update(finished_time=datetime.now(), status='revoked')\n\n return_data = {'status': 'success'}\n logger.info('operation_action_database response method return data {}'.format(return_data))\n return Response(return_data, status=status.HTTP_200_OK)\n\n else:\n return_data = {'status': 'error', 'error': 'Empty operation table'}\n logger.error('operation_action_database clear_latest_operation method: {}'.format(return_data))\n return Response(return_data, status=status.HTTP_400_BAD_REQUEST)\n","sub_path":"backend/webapp/libs/operation_action_database.py","file_name":"operation_action_database.py","file_ext":"py","file_size_in_byte":2995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"379489657","text":"# Copyright 2010-2011 Florent Le Coz \n#\n# This file is part of Poezio.\n#\n# Poezio is free software: you can redistribute it and/or modify\n# it under the terms of the zlib license. See the COPYING file.\n\"\"\"\nImplementation of the XEP-0045: Multi-User Chat.\nAdd some facilities that are not available on the XEP_0045\nslix plugin\n\"\"\"\n\nfrom xml.etree import ElementTree as ET\nfrom typing import (\n Callable,\n Optional,\n TYPE_CHECKING,\n)\n\nfrom poezio.common import safeJID\nfrom slixmpp import (\n JID,\n ClientXMPP,\n Iq,\n)\n\nimport logging\nlog = logging.getLogger(__name__)\n\n\nif TYPE_CHECKING:\n from poezio.core import Core\n from poezio.tabs import Tab\n from slixmpp.plugins.xep_0004 import Form\n\n\nNS_MUC_ADMIN = 'http://jabber.org/protocol/muc#admin'\nNS_MUC_OWNER = 'http://jabber.org/protocol/muc#owner'\n\n\ndef destroy_room(\n xmpp: ClientXMPP,\n room: str,\n reason: str = '',\n altroom: str = ''\n) -> bool:\n \"\"\"\n destroy a room\n \"\"\"\n room = safeJID(room)\n if not room:\n return False\n iq = xmpp.make_iq_set()\n iq['to'] = room\n query = ET.Element('{%s}query' % NS_MUC_OWNER)\n destroy = ET.Element('{%s}destroy' % NS_MUC_OWNER)\n if altroom:\n destroy.attrib['jid'] = altroom\n if reason:\n xreason = ET.Element('{%s}reason' % NS_MUC_OWNER)\n xreason.text = reason\n destroy.append(xreason)\n query.append(destroy)\n iq.append(query)\n\n def callback(iq: Iq) -> None:\n if not iq or iq['type'] == 'error':\n xmpp.core.information('Unable to destroy room %s' % room, 'Info')\n else:\n xmpp.core.information('Room %s destroyed' % room, 'Info')\n\n iq.send(callback=callback)\n return True\n\n\ndef change_show(\n xmpp: ClientXMPP,\n jid: JID,\n own_nick: str,\n show: str,\n status: Optional[str]\n) -> None:\n \"\"\"\n Change our 'Show'\n \"\"\"\n jid = safeJID(jid)\n pres = xmpp.make_presence(pto='%s/%s' % (jid, own_nick))\n if show: # if show is None, don't put a tag. It means \"available\"\n pres['type'] = show\n if status:\n pres['status'] = status\n pres.send()\n\n\ndef change_subject(xmpp: ClientXMPP, jid: JID, subject: str) -> None:\n \"\"\"\n Change the room subject\n \"\"\"\n jid = safeJID(jid)\n msg = xmpp.make_message(jid)\n msg['type'] = 'groupchat'\n msg['subject'] = subject\n msg.send()\n\n\ndef change_nick(\n core: 'Core',\n jid: JID,\n nick: str,\n status: Optional[str] = None,\n show: Optional[str] = None\n) -> None:\n \"\"\"\n Change our own nick in a room\n \"\"\"\n xmpp = core.xmpp\n presence = xmpp.make_presence(\n pshow=show, pstatus=status, pto=safeJID('%s/%s' % (jid, nick)))\n core.events.trigger('changing_nick', presence)\n presence.send()\n\n\ndef join_groupchat(\n core: 'Core',\n jid: JID,\n nick: str,\n passwd: str = '',\n status: Optional[str] = None,\n show: Optional[str] = None,\n seconds: Optional[int] = None,\n tab: Optional['Tab'] = None\n) -> None:\n xmpp = core.xmpp\n stanza = xmpp.make_presence(\n pto='%s/%s' % (jid, nick), pstatus=status, pshow=show)\n x = ET.Element('{http://jabber.org/protocol/muc}x')\n if passwd:\n passelement = ET.Element('password')\n passelement.text = passwd\n x.append(passelement)\n\n def on_disco(iq: Iq) -> None:\n if ('urn:xmpp:mam:2' in iq['disco_info'].get_features()\n or (tab and tab._text_buffer.last_message)):\n history = ET.Element('{http://jabber.org/protocol/muc}history')\n history.attrib['seconds'] = str(0)\n x.append(history)\n else:\n if seconds is not None:\n history = ET.Element('{http://jabber.org/protocol/muc}history')\n history.attrib['seconds'] = str(seconds)\n x.append(history)\n stanza.append(x)\n core.events.trigger('joining_muc', stanza)\n to = stanza[\"to\"]\n stanza.send()\n xmpp.plugin['xep_0045'].rooms[jid] = {}\n xmpp.plugin['xep_0045'].our_nicks[jid] = to.resource\n\n xmpp.plugin['xep_0030'].get_info(jid=jid, callback=on_disco)\n\n\ndef leave_groupchat(\n xmpp: ClientXMPP,\n jid: JID,\n own_nick: str,\n msg: str\n) -> None:\n \"\"\"\n Leave the groupchat\n \"\"\"\n jid = safeJID(jid)\n try:\n xmpp.plugin['xep_0045'].leave_muc(jid, own_nick, msg)\n except KeyError:\n log.debug(\n \"muc.leave_groupchat: could not leave the room %s\",\n jid,\n exc_info=True)\n\n\ndef set_user_role(\n xmpp: ClientXMPP,\n jid: JID,\n nick: str,\n reason: str,\n role: str,\n callback: Callable[[Iq], None]\n) -> None:\n \"\"\"\n (try to) Set the role of a MUC user\n (role = 'none': eject user)\n \"\"\"\n jid = safeJID(jid)\n iq = xmpp.make_iq_set()\n query = ET.Element('{%s}query' % NS_MUC_ADMIN)\n item = ET.Element('{%s}item' % NS_MUC_ADMIN, {'nick': nick, 'role': role})\n if reason:\n reason_el = ET.Element('{%s}reason' % NS_MUC_ADMIN)\n reason_el.text = reason\n item.append(reason_el)\n query.append(item)\n iq.append(query)\n iq['to'] = jid\n iq.send(callback=callback)\n\n\ndef set_user_affiliation(\n xmpp: ClientXMPP,\n muc_jid: JID,\n affiliation: str,\n callback: Callable[[Iq], None],\n nick: Optional[str] = None,\n jid: Optional[JID] = None,\n reason: Optional[str] = None\n) -> None:\n \"\"\"\n (try to) Set the affiliation of a MUC user\n \"\"\"\n muc_jid = safeJID(muc_jid)\n query = ET.Element('{http://jabber.org/protocol/muc#admin}query')\n if nick:\n item = ET.Element('{http://jabber.org/protocol/muc#admin}item', {\n 'affiliation': affiliation,\n 'nick': nick\n })\n else:\n item = ET.Element('{http://jabber.org/protocol/muc#admin}item', {\n 'affiliation': affiliation,\n 'jid': str(jid)\n })\n\n if reason:\n reason_item = ET.Element(\n '{http://jabber.org/protocol/muc#admin}reason')\n reason_item.text = reason\n item.append(reason_item)\n\n query.append(item)\n iq = xmpp.make_iq_set(query)\n iq['to'] = muc_jid\n iq.send(callback=callback)\n\n\ndef cancel_config(xmpp: ClientXMPP, room: str) -> None:\n query = ET.Element('{http://jabber.org/protocol/muc#owner}query')\n x = ET.Element('{jabber:x:data}x', type='cancel')\n query.append(x)\n iq = xmpp.make_iq_set(query)\n iq['to'] = room\n iq.send()\n\n\ndef configure_room(xmpp: ClientXMPP, room: str, form: 'Form') -> None:\n if form is None:\n return\n iq = xmpp.make_iq_set()\n iq['to'] = room\n query = ET.Element('{http://jabber.org/protocol/muc#owner}query')\n form['type'] = 'submit'\n query.append(form.xml)\n iq.append(query)\n iq.send()\n","sub_path":"poezio/multiuserchat.py","file_name":"multiuserchat.py","file_ext":"py","file_size_in_byte":6785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"436409837","text":"import random\n\nno_words_regex = [\n '\\\\bsuc{2,999}(\\\\b|s|k)',\n '\\\\bfuc{2,999}(\\\\b|s|k)',\n '\\\\bthic{2,999}(\\\\b|s|k)',\n '\\\\bpussi?(\\\\b|s)',\n '\\\\bdic{2,999}(\\\\b|s|k)',\n '\\\\bswag(\\\\b|s)',\n '\\\\byolo(\\\\b|s)',\n '\\\\blic{2,999}(\\\\b|s|k)',\n '\\\\bpric{2,999}(\\\\b|s|k)',\n '\\\\bbae(\\\\b|s)',\n '\\\\bfam(\\\\b|s)',\n '\\\\bsweet nibblet(\\\\b|s)',\n '\\\\bsuc{2,999}y\\\\b'\n]\n\nno_words_response = [\n 'No.',\n 'Stop.',\n 'Please don\\'t.',\n 'Why?',\n '...',\n 'I hate this.',\n 'Why was I written?',\n 'My faith in your race as a whole is dwindling.'\n]\n\ndef give_point(mention):\n return random.choice([\n \"{}, you did a thing!\".format(mention.mention),\n \"Yay!\",\n \"Congrats, {}, you dirty bastard.\".format(mention.mention),\n \"Did you really earn that point?\",\n \"Congratulations.\",\n \"{}, your friends have acknowledged your existance.\",\n \"Fine... I guess.\",\n \"Alright, but I don't like it.\",\n \"Are you sure? Like... really sure?\\n\\nOoookkkkkk.\",\n \"Finally! 'Bout time.\",\n \"Do I even want to know what you had to do to get that, {}?\".format(mention.mention),\n \"Don't spend it all in one place. ;D\",\n \"Woooooow hooow speciaaaallll. *rolls eyes*\",\n 'Hurray!'\n ])\n\ndef take_point(mention):\n return random.choice([\n \"LOL!\",\n \"Ha! Loser.\",\n \"Get owned!\",\n \"Say, \\\"Bye bye,\\\" point.\",\n \"Oooooh~ You're in troubleeee~\",\n \"You dun fucked up!\",\n \"What did you do now, {}?\".format(mention.mention),\n \"Your friends have deemed you an aweful person, {}.\".format(mention.mention),\n \"Your friends have denied you any glory or honor, {}.\".format(mention.mention),\n \"git gud\",\n \"RIP\",\n \"GG EZ\",\n \"Sucks to suck.\",\n \"Adiós, punto.\",\n \"Say, \\\"Goodbye,\\\" to your likeability, {}.\".format(mention.mention)\n ])\n","sub_path":"modules/data/strings.py","file_name":"strings.py","file_ext":"py","file_size_in_byte":1933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"389891696","text":"import sys\nimport os\nimport shutil\n\"\"\"\n@Name: head\n@Description: Used to display first few lines of a file\n@Params: cmd(list) - file to be displayed\n\"\"\"\ndef head(cmd):\n\tos.system('touch output.txt')\n\tc=0\n\tif os.path.isfile(cmd[1]):\n\t\tfile = open(cmd[1], \"r\")\n\t\tfor line in file:\n\t\t\tprint (line) #prints the number of lines in a given file\n\t\t\tc=c+1\n\t\t\tif c==20:\n\t\t\t\tbreak\n\t\tfile.close()\n\telse :\n\t\tprint (\"head: cannot stat'\"),\n\t\tprint(cmd[1]),\n\t\tprint(\"': No such file or directory\")\n\treturn","sub_path":"Projects/Shell Project/cmd_pkg/head.py","file_name":"head.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"284580671","text":"from PyQt5 import QtCore as qtc\nfrom PyQt5 import QtGui as qtg\nfrom PyQt5 import QtWidgets as qtw\n\nimport numpy as np\nimport re\n\nimport misc\n\n\nclass CompTable(qtw.QTableWidget):\n\n\tdef __init__(self,*args,**kwargs):\n\t\tsuper().__init__(*args,**kwargs)\n\t\t#self.itemChanged.connect(self.diag)\n\n\tdef connect_signals(self):\n\t\tself.itemChanged.connect(lambda:self.tree_item.update_matrix(self))\n\t\tself.currentItemChanged.connect(self.change_focus)\n\n\tdef change_focus(self,current,previous):\n\t\t'''When table focus changes, removes spinner from previous, create one\n\t\tin current.'''\n\t\tif previous is not None:\n\t\t\tprevious._hide_spinner()\n\t\tif current is not None:\n\t\t\tcurrent._show_spinner()\n\n\tdef set_size(self):\n\t\t'''Reads self.tree_item and sets the correct size of matrix.'''\n\t\tfl = misc.get_fluors(self.tree_item.channels)\n\t\t#fl = [x for x in all if re.search(r'FL\\d-',x)]\n\t\tfl = [x.replace('::','\\n') for x in fl]\n#\t\tprint('fl:',fl)\n\t\tself.fluors = fl\n\t\tself.setRowCount(len(fl)) # +1 for header\n\t\tself.setColumnCount(len(fl))\n\n\tdef fill_table(self):\n\t\t'''Reads from self.fluors and populates table with header and member\n\t\titems.'''\n\t\tfl = self.fluors\n\n\t\t# sets column and row headers\n\t\tself.setHorizontalHeaderLabels(fl)\n\t\tself.setVerticalHeaderLabels(fl)\n\n#\t\tfor i,x in enumerate(fl):\n#\t\t\tnew = Header(name=x)\n#\t\t\tself.setItem(0,i+1,new)\n#\n#\t\t# sets row headers\n#\t\tfor i,x in enumerate(fl):\n#\t\t\tnew = Header(name=x)\n#\t\t\tself.setItem(i+1,0,new)\n\n\t\tmaxl = len(fl)\n\t\t# sets everything else\n\t\tfor i in range(maxl):\n\t\t\tfor j in range(maxl):\n\t\t\t\tif i == j:\n\t\t\t\t\tnew = Member(diag=True,position=(i,j),table=self)\n\t\t\t\telse:\n\t\t\t\t\tnew = Member(position=(i,j),table=self)\n\t\t\t\t\t#self.setCellWidget(i,j,Spinner(table=self,position=(i,j)))\n\t\t\t\tself.setItem(i,j,new)\n\n\t\t# for diag only; need to code column header rotation\n#\t\tc = self.columnCount()\n#\t\tn = qtw.QHeaderView(qtc.Qt.Horizontal,self)\n#\t\tself.setHorizontalHeader(n)\n#\t\tprint('done gone',n.count())\n\n\tdef populate_matrix(self):\n\t\t'''Reads from self.tree_item.comp_matrix to populate into display table.'''\n\t\tmat = self.tree_item.comp_matrix\n\t\tif mat is None:\n\t\t\tmat = np.identity(len(self.fluors)) * 100 # creates identity matrix\n\t\t\tself.tree_item.comp_matrix = mat\n\t\tr,c = mat.shape\n#\t\tprint('rc:',r,c)\n\t\tfor i in range(r):\n\t\t\tfor j in range(c):\n#\t\t\t\tprint('ij:',i,j)\n\t\t\t\titem = self.item(i,j) # +1 to skip over headers\n\t\t\t\titem.setText(str(mat[i,j]))\n\t\tself.tree_item.store_matrix() # makes copy\n\n\t#@misc.debug\n\tdef diag(self,*args,**kwargs):\n\t\t'''Reimplementation'''\n\t\tpass\n\n\t#@misc.debug\n\tdef spinner_change(self,position,value):\n\t\t'''Func for receiving input when Spinner value changes.'''\n\t\tself.item(*position).setText(str(np.round(value,2)))\n\t\t#self.tree_item.update_matrix(self)\n\n\t#@misc.debug\n\tdef keyPressEvent(self,event):\n\t\t'''Reimplementation'''\n\t\tsuper().keyPressEvent(event)\n\n\nclass RotatedHeader(qtw.QHeaderView):\n\tpass\n\nclass Header(qtw.QTableWidgetItem):\n\n\tdef __init__(self,*args,name=None,**kwargs):\n\t\tsuper().__init__(*args,**kwargs)\n\t\tself.setText(name)\n\t\tself.setTextAlignment(qtc.Qt.AlignHCenter | qtc.Qt.AlignVCenter)\n\t\tfont = qtg.QFont()\n\t\tfont.setBold(True)\n\t\tself.setFont(font)\n\n\nclass Spinner(qtw.QDoubleSpinBox):\n\n\tdef __init__(self,*args,table=None,position=None,**kwargs):\n\t\tsuper().__init__(*args,**kwargs)\n\t\tself.table = table\n\t\tself.position = position\n\t\tfont = qtg.QFont()\n\t\tfont.setBold(False)\n\t\tfont.setPointSize(10)\n\t\tself.setFont(font)\n\t\tself.setAlignment(qtc.Qt.AlignHCenter | qtc.Qt.AlignVCenter)\n\t\tself.setSingleStep(0.01)\n\t\tself.setMaximum(1e10000)\n\t\tself.valueChanged.connect(lambda s:table.spinner_change(position,s))\n\n\t\t# modified so that spinner_change isn't called until you hit Enter or Tab\n\t\t# away focus\n\n\t#@misc.debug\n\tdef keyPressEvent(self,event):\n\t\t'''Reimplementation'''\n\t\tupdn_with_page = [\n\t\t\tqtc.Qt.Key_Up,\n\t\t\tqtc.Qt.Key_Down,\n\t\t\tqtc.Qt.Key_PageUp,\n\t\t\tqtc.Qt.Key_PageDown\n\t\t]\n\n\t\tif event.key() == qtc.Qt.Key_Shift:\n\t\t\tself.setSingleStep(0.1)\n\t\tif (event.key() == qtc.Qt.Key_Return or event.key() == qtc.Qt.Key_Enter\n\t\t\tor event.key() in updn_with_page):\n\t\t\tself.valueChanged.emit(self.value())\n\t\t\treturn(super().keyPressEvent(event))\n\t\telse: # this should catch all numerical entries\n\t\t\tself.blockSignals(True)\n\t\t\tret = super().keyPressEvent(event)\n\t\t\tself.blockSignals(False)\n\t\t\treturn(ret)\n\n\t#@misc.debug\n\tdef keyReleaseEvent(self,event):\n\t\tif event.key() == qtc.Qt.Key_Shift:\n\t\t\tprint('resetting')\n\t\t\tself.setSingleStep(0.01)\n\t\t'''Reimplementation'''\n\t\treturn(super().keyReleaseEvent(event))\n\n\n#\t@misc.debug\n#\tdef valueChanged(self,*args,**kwargs):\n#\t\tsuper().valueChanged(*args,**kwargs)\n#\n#\t#@misc.debug\n#\tdef keyPressEvent(self,event):\n#\t\t'''Reimplementation to catch Enter and Tab.'''\n#\t\tif event.key() & (qtc.Qt.Key_Return | qtc.Qt.Key_Enter):\n#\t\t\tval = self.value()\n#\t\t\tpos = self.position\n#\t\t\tself.table.spinner_change(pos,val)\n#\t\treturn(super().keyPressEvent(event))\n#\n#\t#@misc.debug\n\tdef focusOutEvent(self,*args,**kwargs):\n\t\t'''Reimplementation.'''\n\t\tself.table.spinner_change(self.position,self.value())\n\t\treturn(super().focusOutEvent(*args,**kwargs))\n\n\nclass Member(qtw.QTableWidgetItem):\n\n\tdef __init__(self,*args,diag=False,position=None,table=None,**kwargs):\n\t\tsuper().__init__(*args,**kwargs)\n\t\tself.position = position\n\t\tself.table = table\n\t\tself.setTextAlignment(qtc.Qt.AlignHCenter | qtc.Qt.AlignVCenter)\n\t\tfont = qtg.QFont()\n\t\tfont.setBold(False)\n\t\tfont.setPointSize(10)\n\t\tself.setFont(font)\n\t\tself.diag = diag\n\t\tif diag:\n\t\t\tself.setFlags(qtc.Qt.ItemIsSelectable | qtc.Qt.ItemIsEnabled)\n\t\t\tself.setBackground(qtg.QColor.fromRgba(0xfff0f9ff))\n\t\t\t#self.setBackground(brush)\n\n\tdef _show_spinner(self):\n\t\t'''Shows Spinner object in table cell.'''\n\t\tif self.diag or len(self.table.selectedItems()) > 1:\n\t\t\treturn\n\t\ti,j = self.position\n\t\tnew = Spinner(table=self.table,position=self.position)\n\t\tself.table.setCellWidget(i,j,new)\n\t\tnew.setValue(np.float(self.table.item(i,j).text()))\n\t\tnew.setFocus()\n\t\tnew.selectAll()\n\n\tdef _hide_spinner(self):\n\t\t'''Hides Spinner object.'''\n\t\tself.table.removeCellWidget(*self.position)\n","sub_path":"Comp_table_components.py","file_name":"Comp_table_components.py","file_ext":"py","file_size_in_byte":6058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"197187803","text":"# Copyright 2019 Canonical Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom charms.reactive import (\n endpoint_from_flag,\n when,\n when_not,\n when_all,\n set_flag,\n clear_flag\n)\nfrom charmhelpers.core.hookenv import status_set\nfrom charms_openstack.charm import (\n provide_charm_instance,\n use_defaults,\n)\nimport charm.openstack.infoblox as infoblox # noqa\n\n\nuse_defaults('update-status')\n\n\n@when_not('infoblox.installed')\n@when('neutron.available')\ndef install_infoblox():\n with provide_charm_instance() as charm_class:\n charm_class.install()\n set_flag('infoblox.installed')\n\n\n@when_all('infoblox.installed',\n 'neutron.available',\n 'neutron.configured')\n@when_not('create-ea-definitions.done')\ndef create_ea_definitions():\n principal_neutron = \\\n endpoint_from_flag('neutron.available')\n if principal_neutron.principal_charm_state() == \"True\":\n with provide_charm_instance() as charm_class:\n charm_class.create_ea_definitions()\n status_set('active', 'Unit is ready')\n set_flag('create-ea-definitions.done')\n\n\n@when_all('infoblox.installed',\n 'neutron.available')\n@when_not('neutron.configured')\ndef configure_neutron(principle):\n with provide_charm_instance() as charm_class:\n config = charm_class.get_neutron_conf()\n principal_neutron = \\\n endpoint_from_flag('neutron.available')\n principal_neutron.configure_principal(config)\n clear_flag('create-ea-definitions.done')\n set_flag('neutron.configured')\n\n\n@when('designate.connected')\n@when('infoblox.installed')\n@when_not('designate.configured')\ndef configure_designate(principle):\n with provide_charm_instance() as charm_class:\n config = charm_class.get_designate_conf()\n if config:\n principle.configure_principal(config)\n set_flag('designate.configured')\n","sub_path":"src/reactive/infoblox_handlers.py","file_name":"infoblox_handlers.py","file_ext":"py","file_size_in_byte":2407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"368799299","text":"\ndef convert_to_utf8_str(arg):\n # written by Michael Norton (http://docondev.blogspot.com/)\n if isinstance(arg, unicode):\n arg = arg.encode('utf-8')\n elif not isinstance(arg, str):\n arg = str(arg)\n return arg\n\n\ndef decode_early(obj, encoding='utf8'):\n \"\"\" to unicode everywhere \"\"\"\n if isinstance(obj, basestring):\n if not isinstance(obj, unicode):\n obj = unicode(obj, encoding)\n return obj\n\ntry:\n from django.utils.encoding import smart_unicode\nexcept ImportError:\n smart_unicode = decode_early\n","sub_path":"midelo/libs/crawler/facebook/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"449417097","text":"__author__ = 'Antin'\n\n\nfrom math import log2\n\n\nclass Text:\n\n def __init__(self, temp, alphabet, type=\"file\"):\n\n self.alphabet_all = alphabet\n if type == \"file\":\n self.text = self.openfile(temp)\n elif type == \"text\":\n self.text = temp\n else:\n self.text = \"error\"\n\n self.alphabet = set(self.text)\n self.alphabet_fr = {sym: self.text.count(sym) for sym in self.alphabet}\n self.alphabet_pr = {sym: self.text.count(sym)/len(self.text) for sym in self.alphabet}\n self.dig_fr = self.dig_frequency(1)\n self.dig_fr_2 = self.dig_frequency(2)\n self.dig_pr = self.dig_probability(self.dig_fr)\n self.dig_pr_2 = self.dig_probability(self.dig_fr_2)\n self.dig_fr_all = self.dig_frequency_all(1)\n self.dig_fr_all_2 = self.dig_frequency_all(2)\n self.dig_pr_all = self.dig_probability(self.dig_fr_all)\n self.dig_pr_all_2 = self.dig_probability(self.dig_fr_all_2)\n self.spec_entropy_1 = self.entropy(1)\n self.spec_entropy_2 = self.entropy(2)\n\n\n def openfile(self, filename):\n temp = ''\n with open(filename) as file:\n for line in file:\n temp += line.lower()\n\n return ''.join([x for x in temp if x in self.alphabet_all])\n\n def dig_frequency_all(self, step):\n temp = {}\n for sym in self.alphabet_all:\n for symb in self.alphabet_all:\n temp.update({sym + symb: 0})\n if step == 1:\n for i in range(len(self.text)-1):\n temp[self.text[i:i+2]] += 1\n return temp\n elif step == 2:\n for i in range(int((len(self.text) - 1) / 2)):\n temp[self.text[2*i:2*i+2]] += 1\n return temp\n\n def dig_frequency(self, step, type=\"\"):\n if step == 1:\n temp = {}\n for i in range(len(self.text)-1):\n if self.text[i:i+2] in temp:\n temp[self.text[i:i+2]] += 1\n else:\n temp.update({self.text[i:i+2]: 1})\n return temp\n elif step == 2:\n if type == \"intersec\":\n temp = {}\n for i in range(int((len(self.text)-1) / 2)):\n if i == 0: continue\n if self.text[2*i-1:2*i] in temp:\n temp[self.text[2*i-1:2*i]] += 1\n else:\n temp.update({self.text[2*i-1:2*i]: 1})\n return temp\n else:\n temp = {}\n for i in range(int((len(self.text)-1) / 2)):\n if self.text[2*i:2*i+2] in temp:\n temp[self.text[2*i:2*i+2]] += 1\n else:\n temp.update({self.text[2*i:2*i+2]: 1})\n return temp\n\n\n\n def dig_probability(self, dig_fr):\n temp = dig_fr.copy()\n num = 0\n for value in temp.values():\n num += value\n for key in temp.keys():\n temp[key] = temp[key] / num\n return temp\n\n\n def entropy(self, n):\n temp = 0\n if n == 1:\n for sym in self.alphabet:\n temp += self.alphabet_pr[sym] * log2(1/self.alphabet_pr[sym])\n return temp\n elif n == 2:\n for dig in self.dig_pr.keys():\n temp += self.dig_pr[dig] * log2(1 / self.dig_pr[dig])\n return temp / 2\n else:\n print(\"wrong n\")\n\n\n\n\n\n\n\n","sub_path":"input_text.py","file_name":"input_text.py","file_ext":"py","file_size_in_byte":3507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"578228525","text":"import datetime\nimport itertools\nimport logging\nimport uuid\n\nfrom dagster import check, seven\n\nDAGSTER_META_KEY = 'dagster_meta'\nDAGSTER_DEFAULT_LOGGER = 'dagster'\n\n\ndef _dump_value(value):\n # dump namedtuples as objects instead of arrays\n if isinstance(value, tuple) and hasattr(value, '_asdict'):\n return seven.json.dumps(value._asdict())\n\n return seven.json.dumps(value)\n\n\ndef _kv_message(all_items, multiline=False):\n sep = '\\n' if multiline else ' '\n format_str = '{key:>20} = {value}' if multiline else '{key}={value}'\n return sep + sep.join(\n [format_str.format(key=key, value=_dump_value(value)) for key, value in all_items]\n )\n\n\nclass DagsterLog:\n def __init__(self, run_id, tags, loggers):\n self.run_id = check.str_param(run_id, 'run_id')\n self.tags = check.dict_param(tags, 'tags')\n self.loggers = check.list_param(loggers, 'loggers', of_type=logging.Logger)\n\n def _log(self, method, orig_message, message_props):\n check.str_param(method, 'method')\n check.str_param(orig_message, 'orig_message')\n check.dict_param(message_props, 'message_props')\n\n check.invariant(\n 'extra' not in message_props, 'do not allow until explicit support is handled'\n )\n check.invariant(\n 'exc_info' not in message_props, 'do not allow until explicit support is handled'\n )\n\n check.invariant('orig_message' not in message_props, 'orig_message reserved value')\n check.invariant('message' not in message_props, 'message reserved value')\n check.invariant('log_message_id' not in message_props, 'log_message_id reserved value')\n check.invariant('log_timestamp' not in message_props, 'log_timestamp reserved value')\n\n log_message_id = str(uuid.uuid4())\n\n log_timestamp = datetime.datetime.utcnow().isoformat()\n\n synth_props = {\n 'orig_message': orig_message,\n 'log_message_id': log_message_id,\n 'log_timestamp': log_timestamp,\n 'run_id': self.run_id,\n }\n\n # We first generate all props for the purpose of producing the semi-structured\n # log message via _kv_messsage\n all_props = dict(\n itertools.chain(synth_props.items(), self.tags.items(), message_props.items())\n )\n\n msg_with_structured_props = _kv_message(all_props.items())\n msg_with_multiline_structured_props = _kv_message(all_props.items(), multiline=True)\n\n # So here we use the arbitrary key DAGSTER_META_KEY to store a dictionary of\n # all the meta information that dagster injects into log message.\n # The python logging module, in its infinite wisdom, actually takes all the\n # keys in extra and unconditionally smashes them into the internal dictionary\n # of the logging.LogRecord class. We used a reserved key here to avoid naming\n # collisions with internal variables of the LogRecord class.\n # See __init__.py:363 (makeLogRecord) in the python 3.6 logging module source\n # for the gory details.\n # getattr(self.logger, method)(\n # message_with_structured_props, extra={DAGSTER_META_KEY: all_props}\n # )\n\n for logger in self.loggers:\n logger_method = check.is_callable(getattr(logger, method))\n if logger.name == DAGSTER_DEFAULT_LOGGER:\n logger_method(\n msg_with_multiline_structured_props, extra={DAGSTER_META_KEY: all_props}\n )\n else:\n logger_method(msg_with_structured_props, extra={DAGSTER_META_KEY: all_props})\n\n def debug(self, msg, **kwargs):\n '''\n Debug level logging directive. Ends up invoking loggers with DEBUG error level.\n\n The message will be automatically adorned with context information about the name\n of the pipeline, the name of the solid, and so forth. The use can also add\n context values during execution using the value() method of ExecutionContext.\n Therefore it is generally unnecessary to include this type of information\n (solid name, pipeline name, etc) in the log message unless it is critical\n for the readability/fluency of the log message text itself.\n\n You can optionally additional context key-value pairs to an individual log\n message using the keyword args to this message\n\n Args:\n msg (str): The core string\n **kwargs (Dict[str, Any]): Additional context values for only this log message.\n '''\n return self._log('debug', msg, kwargs)\n\n def info(self, msg, **kwargs):\n '''Log at INFO level\n\n See debug()'''\n return self._log('info', msg, kwargs)\n\n def warning(self, msg, **kwargs):\n '''Log at WARNING level\n\n See debug()'''\n return self._log('warning', msg, kwargs)\n\n def error(self, msg, **kwargs):\n '''Log at ERROR level\n\n See debug()'''\n return self._log('error', msg, kwargs)\n\n def critical(self, msg, **kwargs):\n '''Log at CRITICAL level\n\n See debug()'''\n return self._log('critical', msg, kwargs)\n","sub_path":"python_modules/dagster/dagster/core/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":5175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"543562151","text":"# -*- coding:utf-8 _*- \n\"\"\" \n@author:Administrator\n@file: ocr_recognize.py\n@time: 2019/3/11\n\"\"\"\nimport pytesseract\nfrom PIL import Image\n\n# tesseract_cmd = r'F:/tesseract_ocr/Tesseract-OCR/tesseract.exe'\n\nimage = Image.open('./sample/process2.png')\ncode = pytesseract.image_to_string(image,\n # config='--psm 6 --oem 3 -c tessedit_char_whitelist=0123456789'\n lang='eng',\n config='--psm 10 --oem 3 -c tessedit_char_whitelist=0123456789'\n )\nprint(code)\nprint(type(code))\n\n","sub_path":"ocr_recognize.py","file_name":"ocr_recognize.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"272963823","text":"#打开py文件,读出每一行加上行号,写进一个txt文件\nwith open('useLikeThis.py', 'r', encoding = 'utf-8') as pyfile:\n\tcLine = pyfile.readlines()\n\tfor line in range(len(cLine)):\n\t\tcLine[line] = str(line + 1) + ' ' + cLine[line]\n\nwith open('saveUseLikeThis.txt', 'w', encoding = 'utf-8') as txtfile:\n\ttxtfile.writelines(cLine)\n\n#map & reduce, reduce需要引入包\nfrom functools import reduce\nprint(list(map(str, [1, 2, 3])))\n\ndef f(x):\n\treturn x * x\nprint(list(map(f, [1, 2, 3])))\n\ndef a(x, y):\n\treturn x * 10 + y\nprint(reduce(a, [1, 2, 3, 4]))\n\n#利用map/reduce将字符转化成数字:\"9527\"-->9527,简化为lambda函数\n#但是python已经提供int函数了\ndef char2int(s):\n\tdef fn(x, y):\n\t\treturn x * 10 + y\n\tdef char2num(s):\n\t\treturn {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]\n\treturn reduce(fn, map(char2num, s))\nprint(char2int(\"9527\"))\nprint(int(\"9527\"))\n\n#test首字母大写,map实现\ndef normalize(name):\n return name.capitalize()\nL1 = ['adam', 'LISA', 'barT']\nL2 = list(map(normalize, L1))\nprint(L2)\n\n#过滤器filter\n#筛选出是偶数的\ndef is_odd(n):\n\treturn n % 2 == 1\nprint(list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])))\n\n#筛选出不是空的\ndef not_empty(s):\n\treturn s and s.strip()\nprint(list(filter(not_empty, ['A', 'B', None, 'c', ' '])))\n\n#抓取网页requests库栗子\nimport requests\nr = requests.get(\"http://baidu.com\")\nprint('状态码:', r.status_code)\nprint(r.encoding)\n#print(r.text)\nr.encoding = 'utf-8'\n#print(r.text)\nprint(type(r))\n\n#get方法:r = requsets.get(url, params=None, **kwargs)\n#来构造向服务器请求的Request对象\n#返回一个含服务器资源的Response对象\n\n#属性:\nr.status_code #先检查这个。。返回200表示连接成功,其他为失败\nr.text #url对应页面内容,即http响应内容的字符串形式\nr.encoding #网页的编码方式,从httpheader中猜的方式?\nr.apparent_encoding #从响应的内容文本中分析出的编码方式\nr.content #如获得图片以二进制存储,通过content还原图片\n\n#栗子:\n#编码方式:网络上的资源有各种编码\n#从http中header猜测编码方式,\n#如果没有charset会默认为ISO-8859-1,这样的不能解析中文\nr.encoding\n#备选编码apparent_encoding是从内容分析的,所以r.encoding不能正确解码(乱码)的时候\n#可以用apparent_encoding(如utf-8)赋予encoding,读取中文\nr.encoding = 'utf-8'\n\n#通用代码框架\n#抓取网页并处理异常:\nimport requests\ndef getHTMLText(url):\n\ttry:\n\t\tr = requests.get(url, timeout = 30)\n\t\tr.raise_for_status()\n\t\tr.encoding = r.apparent_encoding\n\t\treturn r.text\n\texcept:\n\t\t\"Error\"\n\nif __name__ == \"__main__\":\n\turl = \"http://www.baidu.com\"\n\t#print(getHTMLText(url))\n\n#http协议:超文本传输协议,用户发起请求,服务器做出相应。\n#采用url作为定位网络资源的标识\n#url格式:\n#HTTP协议对资源的操作:GET,HEAD,POST,PUT(所有url的资源都要提交),PATCH(局部更新),DELETE\n\n\n\n\n#爬取网页Requests库\n#爬取网站Scrapy库\n\n#遵守robots协议\n#打开网站根目录下的robots.txt看看\n#http://www.baidu.com/robots.txt\n#http://www.jd.com/robots.txt\n\n#实战一:\n#爬取京东实战:\nimport requests\nr = requests.get(\"https://item.jd.com/2967929.html\")\nprint(r.status_code)\nprint(r.encoding)\nprint(r.request.headers)\n#print(r.text)\n\n#使用通用代码框架爬取京东商品信息:\nimport requests\nurl = \"https://item.jd.com/2967929.html\"\ntry:\n\tr = requests.get(url)\n\tr.raise_for_status()\n\tr.encoding = r.apparent_encoding\n\t#print(r.text[:1000])\nexcept:\n\tprint(\"爬取失败\")\n\n#实战二:\n#爬取亚马逊,发现r.status_code不是200(网站可以通过约束User-Agent和robots协议拒绝访问?)\nr = requests.get(\"https://www.amazon.cn/gp/product/B01M8L5Z3Y\")\nprint(r.status_code)\nprint(r.encoding)\nprint(r.request.headers) #发现头部信息中,爬虫发送的请求User-Agent如实的写了python..\n\n#尝试修改头部信息,使User-Agent修改,如改为浏览器访问\nkv = {'user-agent' : 'Mozilla/5.0'} #Mozilla-->浏览器\nurl = \"https://www.amazon.cn/gp/product/B01M8L5Z3Y\"\nr = requests.get(url, headers = kv)\nprint(r.status_code)\nprint(r.request.headers)\n\n#框架形式:\nimport requests\nurl = \"https://www.amazon.cn/gp/product/B01M8L5Z3Y\"\ntry:\n\tkv = {'user-agent':'Mozilla/5.0'}\n\tr = requests.get(url, headers = kv)\n\tr.raise_for_status()\n\tr.encoding = r.apparent_encoding\n\t#print(r.text[1000:2000])\nexcept:\n\tprint(\"爬取失败\")\n\n#实战三:\n#搜索baidu关键词,同上只需要构造url就可以了,包含搜索的关键词\nkv = {'wd':'Python'}\nurl = \"http://www.baidu.com/s\" #baidu搜索的接口,搜索内容只需要修改wd=搜索内容的键值对\nr = requests.get(url, params = kv)\nprint(r.status_code)\nprint(r.request.url) #看一下url是否被构造成功\nprint(len(r.text))\n\n#框架全代码:\nimport requests\nurl = \"http://www.baidu.com/s\"\ntry:\n\tkv = {'wd':'百度外卖'}\n\tr = requests.get(url, params = kv)\n\tprint(r.request.url) #对象的属性\n\tr.raise_for_status()\n\tprint(len(r.text)) #特别长,就先别打印,看看长度\nexcept:\n\tprint(\"fail\")\n\n#实例四:\n#网络图片的爬取和存储:\npath = \"E:/allFirstStep/first/python/file/jdPic.jpg\"\nurl = \"https://img14.360buyimg.com/n0/jfs/t9307/268/2052051657/217542/578f9944/59c72a7cN642b442e.jpg\"\nr = requests.get(url)\nprint(r.status_code)\n#把二进制图片存成文件\nwith open(path, 'wb') as f:\n\tf.write(r.content)\n\n#框架:\nimport requests\nimport os\nurl = \"https://img14.360buyimg.com/n0/jfs/t9307/268/2052051657/217542/578f9944/59c72a7cN642b442e.jpg\"\nroot = \"E://allFirstStep//first//python//file//\"\npath = root + url.split('/')[-1]\ntry:\n\tif not os.path.exists(root):\n\t\tos.mkdir(root)\n\tif not os.path.exists(path):\n\t\tr = requests.get(url)\n\t\twith open(path, 'wb') as fp:\n\t\t\tfp.write(r.content)\n\t\t\tf.close()\n\t\t\tprint(\"文件保存成功\")\n\telse:\n\t\tprint(\"文件已存在\")\nexcept:\n\tprint(\"爬取失败\")\n\n#实例五\n#随便查询下ip,找到url修改ip就好了\n#提交的形式-->人工的分析接口\nurl = \"http://www.ip138.com/ips138.asp?ip=\"\nr = requests.get(url + '172.2.2.23')\nprint(r.status_code)\nprint(r.text[:500]) #不显示全,就前500这样就好\n\n\n","sub_path":"first/python/file/useLikeThis.py","file_name":"useLikeThis.py","file_ext":"py","file_size_in_byte":6260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"239621540","text":"#!/usr/bin/env python3\n\"\"\"IP adresi sorgulayan program.\"\"\"\n\nfrom urllib.request import urlopen\n\nprint('IP ogreniliyor...')\nsite = urlopen(\"http://icanhazip.com\")\nip_adres = site.read().decode(encoding='UTF-8').strip()\nprint(ip_adres)\nsite.close()\n","sub_path":"ip.py","file_name":"ip.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"589448692","text":"# Given a string, find the length of the longest substring without repeating characters.\n# Example 1:\n#\n# Input: \"abcabcbb\"\n# Output: 3\n# Explanation: The answer is \"abc\", with the length of 3.\n# Example 2:\n#\n# Input: \"bbbbb\"\n# Output: 1\n# Explanation: The answer is \"b\", with the length of 1.\n# Example 3:\n#\n# Input: \"pwwkew\"\n# Output: 3\n# Explanation: The answer is \"wke\", with the length of 3.\n# Note that the answer must be a substring, \"pwke\" is a subsequence and not a substring.\n\n# SLIDING Window O(n)\n#\n# String: abcadcef\n# start: ^\n# end: ^\n#\n# seen:{\n# a:0,\n# b:1,\n#\n# }\n#\n# max_length: 4\n#\n# Algorithm:\n# - Start with start and end at 1st char\n# - Move end and insert the elem and index in dict seen (Also increment max Lenght) as long as the inserted char is not already in the dict\n# - If inserted char is in the dict, move start to position +1 from its last location\n# - End of string\n\n\ndef longest_substring_without_repeat(string):\n seen = {}\n max_length = 0\n start = 0\n # move the end\n for end in range(len(string)):\n # if char is in seen, move the start\n if string[end] in seen:\n start = max(start, seen[string[end]] + 1)\n # Insert in seen\n seen[string[end]] = end\n # max_len is max of existing or end-start + 1\n max_length = max(max_length, end-start + 1)\n return max_length\n\n\n","sub_path":"leetcode/longest_substring_no_repeat.py","file_name":"longest_substring_no_repeat.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"645817970","text":"# FOR USE WITH TEXTBAR ( www.richsomerfield.com )\n\nimport requests\nimport lxml\nimport lxml.etree\nimport bs4.builder._lxml\nfrom bs4 import BeautifulSoup\n\n\nheadline = \"...\"\n\ntry:\n with requests.Session() as session:\n session.headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36'}\n response = session.get('http://www.drudgereport.com')\n html = response.text\n soup = BeautifulSoup(html, \"lxml\")\n section = soup.find(\"font\", size=\"+7\")\n headline = section.text\nexcept Exception as err:\n print(err)\n\ntry:\n print(headline)\nexcept:\n pass\n","sub_path":"drudge.py","file_name":"drudge.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"20798188","text":"\r\nfrom keras.datasets import cifar10\r\nfrom keras.utils import np_utils\r\nimport numpy as np\r\nfrom adversarial_code.cifar_keras_vgg import VGG\r\nfrom adversarial_code.utils import Utils\r\n# tf.python.control_flow_ops = tf\r\n\r\nimg_width, img_height = 32, 32\r\n\r\nvgg = VGG(32, 32, 3)\r\nutils = Utils()\r\n\r\n\r\nnb_epoch = 200\r\nnb_classes = 10\r\n\r\nX_train, y_train, X_test, y_test = utils.load_cifar10(normalize=True)\r\n\r\nnb_train_samples = X_train.shape[0]\r\nnb_validation_samples = X_test.shape[0]\r\n\r\nnumber_of_values_to_remove = 4000\r\n\r\n\r\nfor class_number in range(nb_classes):\r\n model = vgg.model(dropout=True)\r\n indexes = utils.get_indexes_to_remove(y_train, number_of_values_to_remove, class_number, invert=True)\r\n\r\n cur_x_train = np.reshape([img for ix, img in enumerate(X_train) if ix not in indexes], (14000, 32, 32, 3))\r\n cur_y_train = np.reshape([lbl for ix, lbl in enumerate(y_train) if ix not in indexes], (14000, 10))\r\n model_name = \"unbalanced_\"+str(class_number)+\"_major_vgg_custom.h5\"\r\n vgg.fit(model, cur_x_train, cur_y_train, X_test, y_test, model_name=model_name, data_augmentation=False)\r\n\r\n# model_name = \"balanced_\" + str(class_number) + \"_vgg_custom.h5\"\r\n# vgg.fit(model, X_train, y_train, X_test, y_test, model_name=model_name)\r\n#\r\n# model = vgg.model(dropout=True)\r\n# model.load_weights(\"./adversarial_code/unbalanced_2_vgg_custom.h5\")\r\n# scores = model.evaluate(X_test, y_test)\r\n# acc = (scores[1] * 100)\r\n# y_pred = model.predict_classes(X_test)\r\n#\r\n# targets = ['Airplane', 'Automobile', 'Bird', 'Cat', 'Deer', 'Dog', 'Frog', 'Horse', 'Ship', 'Truck']\r\n#\r\n# from sklearn.metrics import classification_report, confusion_matrix\r\n# import pandas as pd\r\n# import seaborn as sns\r\n# import matplotlib.pyplot as plt\r\n#\r\n# rp = classification_report(np.argmax(y_test, axis=1), y_pred)\r\n# cm = confusion_matrix(np.argmax(y_test, axis=1), y_pred)\r\n# cm = cm.astype(\"float\") / cm.sum(axis=1)[:, np.newaxis]\r\n#\r\n# df_cm = pd.DataFrame(cm, index=targets, columns=targets)\r\n#\r\n# plt.figure(figsize=(10, 7))\r\n# plt.xticks(rotation=45)\r\n# plt.yticks(rotation=60)\r\n# hm = sns.heatmap(df_cm, annot=True)\r\n# hm.axes.set_title(\"CIFAR-10 Confusion Matrix\")\r\n# hm.axes.set_xlabel(\"Predicted\")\r\n# hm.axes.set_ylabel(\"True\")\r\n","sub_path":"adversarial_code/train_cifar10_network.py","file_name":"train_cifar10_network.py","file_ext":"py","file_size_in_byte":2232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"597408964","text":"# Copyright (C) 2015-2016 Hewlett Packard Enterprise Development LP\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom opsrest import parse\nfrom opsrest.utils import utils\nfrom opsrest.constants import *\nfrom opsrest.exceptions import DataValidationFailed\n\nimport types\n\nfrom tornado.log import app_log\nfrom ovs.db import types as ovs_types\n\n\ndef verify_http_method(resource, schema, http_method):\n '''\n Operations are allowed on each schema table/resource:\n - GET: any table with at least one attribute tagged as\n category:[configuration|status|statistics] can be retrieved.\n - PUT/PATCH: any table with at least one attribute tagged as\n category:configuration (relationship or not) can be updated.\n - POST/DELETE: any root table with an index attribute tagged as\n category:configuration OR any non-root table referenced by an attribute\n tagged as category:configuration can be created/deleted.\n '''\n # only GET/PUT/PATCH is allowed on System table\n if resource.next is None and resource.table == 'System':\n if http_method == REQUEST_TYPE_UPDATE or \\\n http_method == REQUEST_TYPE_READ or \\\n http_method == REQUEST_TYPE_PATCH:\n return True\n else:\n return False\n\n resource_table = schema.ovs_tables[resource.next.table]\n is_root = resource_table.is_root\n resource_indexes = resource_table.indexes\n resource_config = resource.next.keys[OVSDB_SCHEMA_CONFIG]\n resource_refs = resource.next.keys[OVSDB_SCHEMA_REFERENCE]\n parent_refs = resource.keys[OVSDB_SCHEMA_REFERENCE]\n\n # look for config references\n resource_config_refs = []\n for name, ref in resource_refs.iteritems():\n if ref.category == OVSDB_SCHEMA_CONFIG:\n resource_config_refs.append(name)\n\n parent_config_refs = []\n for name, ref in parent_refs.iteritems():\n if ref.category == OVSDB_SCHEMA_CONFIG:\n parent_config_refs.append(name)\n\n if http_method == REQUEST_TYPE_READ:\n return True\n\n elif http_method == REQUEST_TYPE_UPDATE or \\\n http_method == REQUEST_TYPE_PATCH:\n # check if at least one attribute is tagged as category:configuration\n if len(resource_config) > 0 or len(resource_config_refs) > 0:\n return True\n else:\n return False\n\n elif http_method == REQUEST_TYPE_CREATE or \\\n http_method == REQUEST_TYPE_DELETE:\n # root table\n if is_root:\n # is index 'uuid'\n if len(resource_indexes) == 1 and resource_indexes[0] == 'uuid':\n return True\n # non-uuid index\n for index in resource_indexes:\n if (index in resource_config or\n index in resource_config_refs):\n return True\n # non-root table\n else:\n if resource.column is not None:\n if resource.column in parent_config_refs:\n return True\n # Ex. Ports\n elif resource.relation == OVSDB_SCHEMA_TOP_LEVEL:\n return True\n\n return False\n\n\ndef verify_data(data, resource, schema, idl, http_method):\n\n if http_method == REQUEST_TYPE_CREATE:\n return verify_post_data(data, resource, schema, idl)\n elif http_method == REQUEST_TYPE_UPDATE:\n return verify_put_data(data, resource, schema, idl)\n elif http_method == REQUEST_TYPE_PATCH:\n return verify_patch_data(data, resource, schema, idl)\n\n\ndef verify_post_data(data, resource, schema, idl):\n\n if OVSDB_SCHEMA_CONFIG not in data:\n raise DataValidationFailed(\"Missing %s data\" % OVSDB_SCHEMA_CONFIG)\n\n _data = data[OVSDB_SCHEMA_CONFIG]\n\n # verify config and reference columns data\n verified_data = {}\n\n # when adding a child with kv_type of forward referencing,\n # the configuration data must contain the 'keyname' used to\n # identify the reference of the new resource created.\n if resource.relation is OVSDB_SCHEMA_CHILD:\n ref = resource.keys[OVSDB_SCHEMA_REFERENCE][resource.column]\n reference = ref\n if reference.kv_type:\n keyname = reference.column.keyname\n if keyname not in _data:\n error = \"Missing keyname attribute to\" +\\\n \" reference the new resource\" +\\\n \" from the parent\"\n\n raise DataValidationFailed(error)\n else:\n verified_data[keyname] = _data[keyname]\n _data.pop(keyname)\n\n try:\n # verify configuration data, add it to verified data\n verified_config_data = verify_config_data(resource.next,\n _data,\n schema,\n REQUEST_TYPE_CREATE)\n\n verified_data.update(verified_config_data)\n\n # verify reference data, add it to verified data\n verified_reference_data = verify_forward_reference(_data,\n resource.next,\n schema, idl)\n verified_data.update(verified_reference_data)\n\n # a non-root top-level table must be referenced by another resource\n # or ovsdb-server will garbage-collect it\n is_root = schema.ovs_tables[resource.next.table].is_root\n if resource.relation == OVSDB_SCHEMA_TOP_LEVEL and not is_root:\n if OVSDB_SCHEMA_REFERENCED_BY not in data:\n error = \"Missing %s\" % OVSDB_SCHEMA_REFERENCED_BY\n raise DataValidationFailed(error)\n\n _data = data[OVSDB_SCHEMA_REFERENCED_BY]\n verified_referenced_by_data = verify_referenced_by(_data,\n resource.next,\n schema, idl)\n verified_data.update(verified_referenced_by_data)\n\n elif resource.relation == OVSDB_SCHEMA_BACK_REFERENCE:\n references = resource.next.keys[OVSDB_SCHEMA_REFERENCE]\n for key, value in references.iteritems():\n if value.relation == 'parent':\n parent_row = idl.tables[resource.table].rows[resource.row]\n verified_data.update({key: parent_row})\n\n except DataValidationFailed as e:\n raise e\n\n # data verified\n return verified_data\n\n\ndef verify_put_data(data, resource, schema, idl):\n\n if OVSDB_SCHEMA_CONFIG not in data:\n raise DataValidationFailed(\"Missing %s data\" % OVSDB_SCHEMA_CONFIG)\n\n _data = data[OVSDB_SCHEMA_CONFIG]\n\n # We neet to verify System table\n if resource.next is None:\n resource_verify = resource\n else:\n resource_verify = resource.next\n\n # Get the targeted row\n row = idl.tables[resource_verify.table].rows[resource_verify.row]\n\n # verify config and reference columns data\n verified_data = {}\n try:\n verified_config_data = verify_config_data(resource_verify,\n _data,\n schema,\n REQUEST_TYPE_UPDATE,\n row)\n\n verified_data.update(verified_config_data)\n\n verified_reference_data = verify_forward_reference(_data,\n resource_verify,\n schema, idl)\n verified_data.update(verified_reference_data)\n\n is_root = schema.ovs_tables[resource_verify.table].is_root\n\n # Reference by is not allowed in put\n if resource.relation == OVSDB_SCHEMA_TOP_LEVEL and not is_root:\n if OVSDB_SCHEMA_REFERENCED_BY in data:\n app_log.info('referenced_by is not allowed for PUT')\n error = \"Attribute %s not allowed for PUT\"\\\n % OVSDB_SCHEMA_REFERENCED_BY\n raise DataValidationFailed(error)\n\n except DataValidationFailed as e:\n raise e\n\n # data verified\n return verified_data\n\n\ndef verify_patch_data(data, resource, schema, idl):\n\n # We need to verify System table\n if resource.next is None:\n resource_verify = resource\n else:\n resource_verify = resource.next\n\n # verify config and reference columns data\n verified_data = {}\n try:\n verified_config_data = verify_config_data(resource_verify,\n data,\n schema,\n REQUEST_TYPE_PATCH)\n\n verified_data.update(verified_config_data)\n\n verified_reference_data = verify_forward_reference(data,\n resource_verify,\n schema, idl)\n verified_data.update(verified_reference_data)\n\n except DataValidationFailed as e:\n raise e\n\n # data verified\n return verified_data\n\n\ndef verify_config_data(resource, data, schema, request_type,\n row=None, get_all_errors=False):\n\n config_keys = resource.keys[OVSDB_SCHEMA_CONFIG]\n reference_keys = resource.keys[OVSDB_SCHEMA_REFERENCE]\n\n verified_config_data = {}\n errors = []\n\n # Check for extra or unknown attributes\n unknown_attribute = find_unknown_attribute(data,\n config_keys,\n reference_keys)\n if unknown_attribute is not None:\n error = \"Unknown configuration attribute: %s\" % unknown_attribute\n if get_all_errors:\n errors.append(error)\n else:\n raise DataValidationFailed(error)\n\n non_mutable_attributes = get_non_mutable_attributes(resource,\n schema)\n\n # Check for all required/valid attributes to be present\n for column_name in config_keys:\n is_optional = config_keys[column_name].is_optional\n\n if column_name in data:\n try:\n verify_attribute_type(column_name, config_keys[column_name],\n data[column_name])\n verify_attribute_range(column_name, config_keys[column_name],\n data[column_name])\n except DataValidationFailed as e:\n if get_all_errors:\n errors.append(e.detail)\n else:\n raise e\n\n if request_type == REQUEST_TYPE_CREATE:\n verified_config_data[column_name] = data[column_name]\n elif request_type in (REQUEST_TYPE_UPDATE, REQUEST_TYPE_PATCH):\n if column_name not in non_mutable_attributes:\n verified_config_data[column_name] = data[column_name]\n else:\n # Check if immutable attribute is being updated\n if row is not None:\n if is_optional:\n column_list = []\n column_list.append(data[column_name])\n if row.__getattr__(column_name) != column_list:\n error = \"Attribute list '%s' cannot be modified\" % column_name\n raise DataValidationFailed(error)\n elif row.__getattr__(column_name) != data[column_name]:\n error = \"Attribute '%s' cannot be modified\" % column_name\n raise DataValidationFailed(error)\n\n else:\n # PUT ignores immutable attributes, otherwise they are required.\n # If it's a PUT request, and the field is a mutable and mandatory,\n # but not found, then it's an error.\n #\n # POST requires all attributes. If it's a mandatory field not found\n # then it's an error.\n if request_type in (REQUEST_TYPE_UPDATE, REQUEST_TYPE_PATCH) and \\\n column_name in non_mutable_attributes:\n continue\n\n if not is_optional:\n error = \"Attribute %s is required\" % column_name\n if get_all_errors:\n errors.append(error)\n else:\n raise DataValidationFailed(error)\n\n if len(errors):\n raise DataValidationFailed(errors)\n else:\n return verified_config_data\n\n\ndef verify_attribute_type(column_name, column_data, request_data):\n data = request_data\n data_type = type(data)\n valid_types = column_data.type.python_types\n\n # If column is a list, data must be a list\n if column_data.is_list:\n valid_types = [list]\n\n # If column is a dictionary, data must be a dictionary\n elif column_data.is_dict:\n valid_types = [dict]\n\n # If data is a list but column is not,\n # we expect a single value in the list\n elif data_type is list:\n if len(data) == 1:\n data = data[0]\n data_type = type(data)\n\n try:\n if data_type in valid_types:\n\n # Check each value's type for elements in lists and dictionaries\n if column_data.n_max > 1:\n verify_container_values_type(column_name, column_data,\n request_data)\n\n # Now check for invalid values\n verify_valid_attribute_values(data, column_data,\n column_name)\n else:\n error = \"Attribute type mismatch for column %s\" % column_name\n raise DataValidationFailed(error)\n except DataValidationFailed as e:\n raise e\n\n\ndef verify_container_values_type(column_name, column_data, request_data):\n\n if column_data.is_list:\n for value in request_data:\n if type(value) not in column_data.type.python_types:\n error = \"Value type mismatch in column %s\" % column_name\n raise DataValidationFailed(error)\n\n elif column_data.is_dict:\n for key, value in request_data.iteritems():\n # Check if request data has unknown keys for columns other than\n # those in OVSDB_COMMON_COLUMNS (which should accept any keys).\n # Note: common columns which do not require key validation should\n # be added to OVSDB_COMMON_COLUMNS array.\n if column_name not in OVSDB_COMMON_COLUMNS:\n if column_data.kvs and key not in column_data.kvs:\n error = \"Unknown key %s for column %s\" % (key, column_name)\n raise DataValidationFailed(error)\n\n value_type = type(value)\n\n # Values in dict must match JSON schema\n if value_type in column_data.value_type.python_types:\n\n # If they match, they might be strings that represent other\n # types, so each value must be checked if kvs type exists\n\n if value_type in ovs_types.StringType.python_types \\\n and column_data.kvs and key in column_data.kvs:\n kvs_value_type = column_data.kvs[key]['type']\n converted_value = \\\n convert_string_to_value_by_type(value, kvs_value_type)\n\n if converted_value is None:\n error = \"Value type mismatch for key %s in column %s\"\\\n % (key, column_name)\n raise DataValidationFailed(error)\n else:\n error = \"Value type mismatch for key %s in column %s\"\\\n % (key, column_name)\n raise DataValidationFailed(error)\n\n\ndef convert_string_to_value_by_type(value, type_):\n\n converted_value = value\n\n if type_ == ovs_types.IntegerType or \\\n type_ in ovs_types.IntegerType.python_types:\n try:\n converted_value = int(value)\n except ValueError:\n converted_value = None\n elif type_ == ovs_types.RealType or \\\n type_ in ovs_types.RealType.python_types:\n try:\n converted_value = float(value)\n except ValueError:\n converted_value = None\n elif type_ == ovs_types.BooleanType or \\\n type_ in ovs_types.BooleanType.python_types:\n if not (value == 'true' or value == 'false'):\n converted_value = None\n\n return converted_value\n\n\ndef verify_valid_attribute_values(request_data, column_data, column_name):\n\n valid = True\n\n error_details = \"\"\n error_message = \"Attribute value is invalid for column '%s'.\" % column_name\n\n # If data has an enum defined, check for a valid value\n if column_data.enum:\n\n enum = set(column_data.enum.as_list())\n valid = is_value_in_enum(request_data, enum)\n\n # If data has key-values dict defined, check for missing/invalid keys\n # It's assumed type is validated, meaning kvs is defined for dicts only\n elif column_data.kvs:\n\n valid_keys = set(column_data.kvs.keys())\n data_keys = set(request_data.keys())\n unknown_keys = []\n if column_name not in OVSDB_COMMON_COLUMNS:\n unknown_keys = data_keys.difference(valid_keys)\n missing_keys = valid_keys.difference(data_keys)\n\n if unknown_keys:\n error_details += \"Unknown keys: '%s'. \" % list(unknown_keys)\n\n if missing_keys:\n true_missing_keys = []\n\n for key in missing_keys:\n if not column_data.kvs[key][\"is_optional\"]:\n true_missing_keys.append(key)\n\n if true_missing_keys:\n missing_keys = true_missing_keys\n error_details += \"Missing keys: '%s'. \" % list(missing_keys)\n else:\n missing_keys = []\n\n if unknown_keys or missing_keys:\n valid = False\n\n if valid:\n # Now that keys have been checked,\n # verify their values are valid\n for key, value in column_data.kvs.iteritems():\n if key in request_data and value['enum']:\n enum = set(value['enum'].as_list())\n\n data_value = request_data[key]\n\n if type(data_value) \\\n in ovs_types.StringType.python_types:\n data_value = \\\n convert_string_to_value_by_type(data_value,\n value['type'])\n\n if not is_value_in_enum(data_value, enum):\n valid = False\n error_details += \"Invalid value for key '%s'. \" % key\n break\n\n if not valid:\n if error_details:\n error_message += \": \" + error_details\n raise DataValidationFailed(error_message)\n\n\ndef is_value_in_enum(value, enum):\n\n valid = True\n\n # Check if request's list contains values not valid\n if type(value) is list:\n if set(value).difference(enum):\n valid = False\n\n # Check if single request value is valid\n elif value not in enum:\n valid = False\n\n return valid\n\n\ndef verify_attribute_range(column_name, column_data, request_data):\n\n # We assume verify_attribute_type has already been called,\n # so request_data type must be correct (save for a small\n # exception if column is list)\n\n data_type = type(request_data)\n\n # Check elements in in a list\n if column_data.is_list:\n\n # Exception: a single value might be accepted\n # by OVSDB as a single element list\n request_list = []\n if data_type is not list:\n request_list.append(request_data)\n else:\n request_list = request_data\n\n request_len = len(request_list)\n if request_len < column_data.n_min or request_len > column_data.n_max:\n error = \"List number of elements is out of range for column %s\" % \\\n column_name\n raise DataValidationFailed(error)\n else:\n for element in request_list:\n # We usually check the value itself\n # But for a string, we check its length instead\n value = element\n if type(element) in ovs_types.StringType.python_types:\n value = len(element)\n\n if (value < column_data.rangeMin or\n value > column_data.rangeMax):\n error = \"List element %s is out of range for column %s\" % \\\n (element, column_name)\n raise DataValidationFailed(error)\n\n # Check elements in a dictionary\n elif column_data.is_dict:\n request_len = len(request_data)\n if request_len < column_data.n_min or request_len > column_data.n_max:\n error = \"Dict number of elements is out of range for column %s\" % \\\n column_name\n raise DataValidationFailed(error)\n else:\n for key, data in request_data.iteritems():\n\n # First check the key\n # TODO is this necessary? Valid keys are verified prior to this\n\n value = key\n if type(key) in ovs_types.StringType.python_types:\n value = len(key)\n\n if (value < column_data.rangeMin or\n value > column_data.rangeMax):\n error = \"Key %s's value is out of range for column %s\" % \\\n (key, column_name)\n raise DataValidationFailed(error)\n\n # Now check ranges for values in dictionary\n\n # Skip range check for bools\n if type(data) is bool:\n continue\n\n value = data\n\n min_ = column_data.valueRangeMin\n max_ = column_data.valueRangeMax\n\n # If kvs is defined, ranges shouldbe taken from it\n if column_data.kvs and key in column_data.kvs:\n # Skip range check for booleans\n if column_data.kvs[key]['type'] == ovs_types.BooleanType:\n continue\n else:\n min_ = column_data.kvs[key]['rangeMin']\n max_ = column_data.kvs[key]['rangeMax']\n\n # If value is a string, it might represent values of other\n # types and therefore it needs to be converted\n if type(value) in ovs_types.StringType.python_types:\n column_ovs_type = column_data.kvs[key]['type']\n value = \\\n convert_string_to_value_by_type(value,\n column_ovs_type)\n\n # If it was a string all along or if after convertion it's\n # still a string, its length range is checked instead\n if type(value) in ovs_types.StringType.python_types:\n value = len(value)\n\n if (value < min_ or\n value > max_):\n error = \"Dictionary value %s is out of range \" % data + \\\n \"for key %s in column %s\" % (key, column_name)\n raise DataValidationFailed(error)\n\n # Check single elements (non-list/non-dictionary)\n # Except boolean, as there's no range for them\n elif data_type not in ovs_types.BooleanType.python_types:\n\n # Exception: if column is not a list,\n # a single value list is accepted\n if data_type is list:\n value = request_data[0]\n data_type = type(value)\n else:\n value = request_data\n\n if data_type in ovs_types.StringType.python_types:\n value = len(value)\n\n if value < column_data.rangeMin or value > column_data.rangeMax:\n error = \"Attribute value is out of range for column %s\" % \\\n column_name\n raise DataValidationFailed(error)\n\n\ndef _get_row_from_uri(uri, schema, idl):\n\n verified_resource = parse.parse_url_path(uri, schema, idl)\n if verified_resource is None:\n error = \"Reference %s could not be identified\" % uri\n raise DataValidationFailed(error)\n\n # get the Row instance of the reference we are adding\n while verified_resource.next is not None:\n verified_resource = verified_resource.next\n row = utils.get_row_from_resource(verified_resource, idl)\n return row\n\n\ndef verify_forward_reference(data, resource, schema, idl):\n \"\"\"\n converts the forward reference URIs to corresponding Row references\n Parameters:\n data - post/put data\n resource - Resource object being accessed\n schema = restparser schema object\n idl - ovs.db.idl.Idl object\n \"\"\"\n reference_keys = resource.keys[OVSDB_SCHEMA_REFERENCE]\n verified_references = {}\n\n # check for invalid keys\n for key in reference_keys:\n if key in data:\n category = reference_keys[key].category\n relation = reference_keys[key].relation\n\n if category != OVSDB_SCHEMA_CONFIG or \\\n relation == 'parent':\n error = \"Invalid reference: %s\" % key\n raise DataValidationFailed(error)\n\n for key in reference_keys:\n if key in data:\n # this is either a URI or list of URIs or dictionary\n table_schema = schema.ovs_tables[resource.table]\n kv_type = table_schema.references[key].kv_type\n _refdata = data[key]\n notList = False\n # Verify if input is of DictType\n if kv_type and not isinstance(_refdata, types.DictType):\n error = \"Reference needs to be a dictionary %s\" % key\n raise DataValidationFailed(error)\n\n if not isinstance(_refdata, types.ListType) and not kv_type:\n notList = True\n _refdata = [_refdata]\n\n # check range\n _min = reference_keys[key].n_min\n _max = reference_keys[key].n_max\n if len(_refdata) < _min or len(_refdata) > _max:\n error = \"Reference list is out of range for key %s\" % key\n raise DataValidationFailed(error)\n if kv_type:\n references = {}\n key_type = table_schema.references[key].kv_key_type.name\n # TODO: Support other types\n for k, v in _refdata.iteritems():\n if key_type == INTEGER:\n k = int(k)\n row = _get_row_from_uri(v, schema, idl)\n references.update({k:row})\n else:\n references = []\n for uri in _refdata:\n row = _get_row_from_uri(uri, schema, idl)\n references.append(row)\n if notList:\n references = references[0]\n\n verified_references[key] = references\n\n return verified_references\n\n\ndef verify_referenced_by(data, resource, schema, idl):\n '''\n subroutine to validate referenced_by uris/attribute JSON\n\n {\n \"referenced_by\": [\n {\n \"uri\": \"URI1\",\n \"attributes\": [\n \"a\",\n \"b\"\n ]\n },\n {\n \"uri\": \"URI2\"\n },\n {\n \"uri\": \"URI3\",\n \"attributes\":[]\n }\n ]\n }\n '''\n\n table = resource.table\n\n verified_referenced_by = {OVSDB_SCHEMA_REFERENCED_BY: []}\n for item in data:\n uri = item['uri']\n attributes = None\n\n if 'attributes' in item:\n attributes = item['attributes']\n\n # verify URI\n uri_resource = parse.parse_url_path(uri, schema, idl,\n REQUEST_TYPE_CREATE)\n\n if uri_resource is None:\n error = \"referenced_by resource error\"\n raise DataValidationFailed(error)\n\n # go to the last resource\n while uri_resource.next is not None:\n uri_resource = uri_resource.next\n\n if uri_resource.row is None:\n app_log.debug('uri: ' + uri + ' not found')\n error = \"referenced_by resource error\"\n raise DataValidationFailed(error)\n\n # attributes\n references = uri_resource.keys[OVSDB_SCHEMA_REFERENCE]\n reference_keys = references.keys()\n if attributes is not None and len(attributes) > 0:\n for attribute in attributes:\n if attribute not in reference_keys:\n error = \"Attribute %s not found\" % attribute\n raise DataValidationFailed(error)\n\n # check attribute is not a parent or child\n if references[attribute].relation is not 'reference':\n error = \"Attribute should be a reference\"\n raise DataValidationFailed(error)\n\n # if attribute list has only one element, make it a non-list to keep\n # it consistent with single attribute case (that need not be mentioned)\n if len(attributes) == 1:\n attributes = attributes[0]\n else:\n # find the lone attribute\n _found = False\n for key, value in references.iteritems():\n if value.ref_table == table:\n if _found:\n error = \"multiple attributes possible, specify one\"\n raise DataValidationFailed(error)\n else:\n _found = True\n attributes = key\n\n # found the uri and attributes\n uri_resource.column = attributes\n verified_referenced_by[OVSDB_SCHEMA_REFERENCED_BY].append(uri_resource)\n\n return verified_referenced_by\n\n\ndef find_unknown_attribute(data, config_keys, reference_keys):\n\n for column_name in data:\n if not (column_name in config_keys or\n column_name in reference_keys):\n return column_name\n\n return None\n\n\ndef get_non_mutable_attributes(resource, schema):\n config_keys = resource.keys[OVSDB_SCHEMA_CONFIG]\n reference_keys = resource.keys[OVSDB_SCHEMA_REFERENCE]\n\n attribute_keys = {}\n attribute_keys.update(config_keys)\n attribute_keys.update(reference_keys)\n\n result = []\n for key, column in attribute_keys.iteritems():\n if not column.mutable:\n result.append(key)\n\n return result\n","sub_path":"opsrest/verify.py","file_name":"verify.py","file_ext":"py","file_size_in_byte":31329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"512241476","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n # @param {ListNode} head\n # @param {integer} x\n # @return {ListNode}\n def partition(self, head, x):\n \thead1 = ListNode(0)\n \thead2 = ListNode(0)\n \tp1 = head1\n \tp2 = head2\n \ttmp = head\n \twhile tmp:\n \t\tif tmp.val < x:\n \t\t\tp1.next = tmp\n \t\t\ttmp = tmp.next\n \t\t\tp1 = p1.next\n \t\t\tp1.next = None\n \t\telse:\n \t\t\tp2.next = tmp\n \t\t\ttmp = tmp.next\n \t\t\tp2 = p2.next\n \t\t\tp2.next = None\n \tp1.next = head2.next\n \thead = head1.next\n \treturn head\n\n\n\n\n# ******** The Second Time ********\n\"\"\"\n# 解题思路:解决链表问题时,最好加一个头结点,问题会比较好解决。对这道题来说,创建两个头结点head1和head2,\n# head1这条链表是小于x值的节点的链表,head2链表是大于等于x值的节点的链表,然后将head2链表链接到head链表\n# 的尾部即可。\n\"\"\"\n\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n # @param {ListNode} head\n # @param {integer} x\n # @return {ListNode}\n def partition(self, head, x):\n head1 = ListNode(0); head2 = ListNode(0) # 没有另开空间新建链表, 只是新建两个节点\n tmp = head\n p1 = head1; p2 = head2\n while tmp:\n if tmp.val < x:\n p1.next = tmp\n tmp = tmp.next\n p1 = p1.next\n p1.next = None # if no this line then it is not an independent linkedlist\n else:\n p2.next = tmp\n tmp = tmp.next\n p2 = p2.next\n p2.next = None # if no this line then it is not an independent linkedlist\n p1.next = head2.next\n head = head1.next\n return head\n # 这个题其实蛮有意思的\n\n\n\n#################### The third time ###################\n\n# 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 partition(self, head, x):\n \"\"\"\n :type head: ListNode\n :type x: int\n :rtype: ListNode\n \"\"\"\n head1 = ListNode(0); head2 = ListNode(0)\n tmp = head\n p1 = head1; p2 = head2\n while tmp:\n if tmp.val < x:\n p1.next = tmp\n tmp = tmp.next\n p1 = p1.next\n p1.next = None\n else:\n p2.next = head2\n tmp = tmp.next\n p2 = p2.next\n p2.next = None\n p1.next = head2.next\n head = head1.next\n return head\n\n\n\n\"\"\"\n我自己的写法更简洁\n\"\"\"\nclass Solution(object):\n def partition(self, head, x):\n \"\"\"\n :type head: ListNode\n :type x: int\n :rtype: ListNode\n \"\"\"\n if not head or not head.next:return head\n dummy1 = ListNode(0); dummy2 = ListNode(0)\n p1 = dummy1; p2 = dummy2\n while head:\n if head.val < x:\n p1.next = head\n head = head.next\n p1 = p1.next\n p1.next = None\n else:\n p2.next = head\n head = head.next\n p2 = p2.next\n p2.next = None \n p1.next = dummy2.next\n return dummy1.next\n\n\n\"\"\"\n九章solution, 思路很清晰\n\"\"\"\nclass Solution(object):\n def sortList(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n if not head or not head.next: return head\n mid = self.findMiddle(head)\n right = self.sortList(mid.next)\n mid.next = None\n left = self.sortList(head)\n return self.merge(left,right)\n \n def merge(self,head1,head2):\n dummy = ListNode(0);p = dummy\n while head1 and head2:\n if head1.val < head2.val:\n p.next = head1\n head1 = head1.next\n p = p.next\n else:\n p.next = head2\n head2 = head2.next\n p = p.next\n if head1:\n p.next = head1\n if head2:\n p.next = head2\n return dummy.next\n \n def findMiddle(self,head):\n slow = head;fast = head.next\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"python/86.partition_list.py","file_name":"86.partition_list.py","file_ext":"py","file_size_in_byte":4612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"286500195","text":"# -*- coding: utf-8 -*-\r\n\r\nfrom random import randint\r\n\r\ndef generarApuesta(minima,maxima):\r\n return ((randint((minima/100),(maxima/100)))*100)\r\n\r\ndef apuestaMinima():\r\n return (randint(1,10)*100)\r\n\r\ndef girarDado():\r\n return (randint(1,6))\r\n\r\ndef decision():\r\n return (randint(0,1))\r\n\r\n\r\ndef turno(dado, apuestaM , apuestaT, dado2):\r\n \r\n print(\"Dado[\", dado ,\"]\")\r\n print(\"Apuesta minima: \",apuestaM)\r\n print(\"Apuesta turno: \" ,apuestaT)\r\n \r\n if dado !=6 and dado!=1 :\r\n\r\n if decision() == 0 :\r\n print(\"->NO apuesta a : Dado[\", dado ,\"]\")\r\n return 0 \r\n \r\n else:\r\n \r\n if dado2 <= dado : \r\n print(\"Apostando a : Dado[\", dado ,\"]\")\r\n print(\"Segundo Dado[\", dado2 ,\"]\")\r\n print(\"->Apuesta Fallida: \", 0-apuestaT)\r\n return 0-apuestaT\r\n \r\n else:\r\n print(\"Apostando a : Dado[\", dado ,\"]\")\r\n print(\"Segundo Dado[\", dado2 ,\"]\")\r\n print(\"->Apuesta Ganada: \", apuestaT)\r\n return apuestaT \r\n \r\n else:\r\n \r\n if dado == 6:\r\n print(\"->Dado[6]...Gana : \" , apuestaM)\r\n return apuestaM\r\n \r\n else:\r\n print(\"->Dado[1]...Pierde : \" , 0-apuestaM) \r\n return 0-apuestaM \r\n \r\n\r\n\r\ndef juego(mesa, jugador1, jugador2, apuestaM, jugador, dado, dadoN, resultado):\r\n \r\n print(\"___________________________________\")\r\n print(\"Mesa:$ \",mesa+(resultado*-1)) \r\n \r\n \r\n \r\n if mesa+(resultado*-1)<=0 or jugador1 <=0 or jugador2 <=0 :\r\n print(\"JUGADOR 1: $ \",jugador1) \r\n print(\"JUGADOR 2: $ \",jugador2) \r\n print(\"FIN DEL JUEGO\") \r\n \r\n \r\n else: \r\n \r\n if jugador == 1:\r\n print(\"*JUGADOR 1: $\", jugador1)\r\n juego((mesa+(resultado*-1)), jugador1 ,(jugador2+resultado) , apuestaM,2,girarDado(),girarDado(),(turno(dado,apuestaM, generarApuesta(apuestaM,mesa),dadoN)))\r\n \r\n else:\r\n print(\"*JUGADOR 2: $\", jugador2)\r\n juego((mesa+(resultado*-1)), (jugador1+resultado), jugador2 , apuestaM,1,girarDado(),girarDado(),(turno(dado,apuestaM, generarApuesta(apuestaM,mesa),dadoN)))\r\n\r\n\r\n\r\n \r\njuego (1000, 1000, 1000, 500,1,girarDado(),girarDado(),0)\r\n","sub_path":"Guayabita.py","file_name":"Guayabita.py","file_ext":"py","file_size_in_byte":2674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"400078578","text":"from threading import Thread\r\nimport time\r\n\r\nbaket = 0\r\ncount1 = 0\r\nclass cooker(Thread):\r\n def run(self) -> None:\r\n global baket\r\n global count1\r\n count_end = 0\r\n while 1:\r\n if baket < 500:\r\n baket += 1\r\n count1 += 1\r\n count_end = 0\r\n else:\r\n time.sleep(3)\r\n count_end += 1\r\n if count_end > 100:\r\n print(\"总共制做了\",count1,\"个汉堡\")\r\n break\r\n\r\nclass patron(Thread):\r\n username = \"\"\r\n def run(self) -> None:\r\n global baket\r\n money = 10000\r\n count = 0\r\n while 1:\r\n if money > 0:\r\n if baket > 0:\r\n baket -= 1\r\n money -= 5\r\n count += 1\r\n else:\r\n time.sleep(3)\r\n else:\r\n print(self.username,\"买了\",count,\"个汉堡\")\r\n break\r\n\r\nc1 = cooker()\r\nc2 = cooker()\r\nc3 = cooker()\r\nc1.start()\r\nc2.start()\r\nc3.start()\r\np1 = patron()\r\n# p1.username = \"李四\"\r\np1.username = (input(\"请输入姓名:\"))\r\np1.start()\r\np2 = patron()\r\n# p2.username = \"李环境\"\r\np2.username = (input(\"请输入姓名:\"))\r\np2.start()\r\np3 = patron()\r\n# p3.username = \"李安徽科技\"\r\np3.username = (input(\"请输入姓名:\"))\r\np3.start()\r\np4 = patron()\r\n# p4.username = \"李安居客和\"\r\np4.username = (input(\"请输入姓名:\"))\r\np4.start()\r\np5 = patron()\r\n# p5.username = \"李暗黑风\"\r\np5.username = (input(\"请输入姓名:\"))\r\np5.start()\r\np6 = patron()\r\n# p6.username = \"李AFK\"\r\np6.username = (input(\"请输入姓名:\"))\r\np6.start()\r\n\r\n","sub_path":"text.py","file_name":"text.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"85569946","text":"from django.db import models\nfrom django.contrib.auth.models import AbstractUser\n###On delete de oluyor bilmiyoruz!!!!!!!\n\n\nclass Account(AbstractUser):\n age = models.IntegerField(null =True)\n sex = models.BooleanField()\n\n\n# https://docs.djangoproject.com/en/1.8/_modules/django/contrib/auth/models/\n\n\nclass Customer(models.Model):\n cId = models.AutoField(primary_key=True)\n # address = models.CharField(max_length=500, null=True)\n taxNumber = models.IntegerField(null =True) \n\n user = models.OneToOneField(\n Account,\n on_delete=models.CASCADE,\n related_name = \"customer\",\n )\n\nclass Address(models.Model):\n aId = models.AutoField(primary_key=True,null = False)\n customer = models.ForeignKey('Customer', null = True,on_delete = models.SET_NULL,related_name=\"myAddress\")\n address = models.CharField(max_length=200, null=True)\n\n def __str__(self):\n return '%s' % ( self.address)\n \nclass Images(models.Model):\n product = models.ForeignKey('Product', null = True,on_delete = models.SET_NULL,related_name=\"images\")\n imgSrc = models.CharField(max_length=200, null=True)\n\n def __str__(self):\n return '%s' % (self.imgSrc)\n\nclass ProductManager(models.Model):\n user = models.OneToOneField(\n Account,\n on_delete=models.CASCADE,\n primary_key=True,\n related_name = \"productmanager\",\n )\nclass SalesManager(models.Model):\n user = models.OneToOneField(\n Account,\n on_delete=models.CASCADE,\n primary_key=True,\n related_name = \"salesmanager\",\n )\n\n# Create your models here.\nclass Product(models.Model):\n ### Primary Key\n pId = models.AutoField(primary_key=True) \n \n ### Table Specific Fields\n isActive = models.NullBooleanField()\n\n price = models.FloatField()\n oldPrice = models.FloatField()\n stock = models.IntegerField() \n imgSrc = models.CharField(max_length=100)\n name = models.CharField(max_length=50) # TEXT \n displayOldPrice = models.BooleanField()\n cost = models.FloatField()\n \n modelNo = models.CharField(max_length=50) # TEXT ,BV200423 universal code\n description = models.CharField(max_length=500) # TEXT\n warrantyStatus = models.IntegerField()\n disturbuterInfo = models.CharField(max_length=100) #TEXT\n categoryName = models.ForeignKey('Category', null = True,on_delete = models.SET_NULL)\n listedDate = models.DateField()\n\nclass Category(models.Model): # kategorinin son ürünü silindiğinde kategori de silinsin mi???\n categoryName = models.CharField(max_length=80, primary_key=True)\n categoryIconScr = models.CharField(max_length=80)\n\n# bir müşterinin birden fazla ürün alması, sepetini görmesi,\n# eski siparişlerini görüntülemesi özellikleri\n# en son bu class invoice de kullanılacak ürün tarafı olacak, ie bi\n# her transactionda Client ve pIdleri söyleyebilmeli\n# örneğin gün1 x kişisi ürün 1 ve ürün 2 aldı. gün2 x kişisi bu sefere ürün3 ürün4 ü aldı\n# bize gün1 de x kişisinin ürün1 ve ürün 2 aldığını söylebilmeli aynı şekilde ürün3 farklı \n# bir alışveriş olduğunu\n\nclass Basket(models.Model):\n bId = models.AutoField(primary_key=True)\n cId = models.ForeignKey('Customer', null = True,on_delete = models.SET_NULL)\n pId = models.ForeignKey('Product', null = True,on_delete = models.SET_NULL) ##### değiştirsek \n quantity = models.IntegerField()\n totalPrice = models.FloatField()\n purchasedDate = models.DateField()\n isPurchased = models.NullBooleanField()\n\n class Meta:\n unique_together = (('bId', 'cId'),)\n\n # def Purchase():\n # isPurchased =True\n # def SeeMyBasket():\n # filter by isPurchased == False\n # def SeeMyOldPurchases ():\n #filter by isPurchased == True\n #\n \n# Gok p1\n# Gok p2\n# gok p3\n# gok p4\n \n\nclass Delivery(models.Model):\n \n dId = models.AutoField(primary_key=True)\n address = models.CharField(max_length=500)\n IsDelivered = models.NullBooleanField()\n\nclass Favourite(models.Model):\n fId = models.AutoField(primary_key=True)\n cId = models.ForeignKey('Customer', null=True,on_delete = models.SET_NULL)\n pId = models.ForeignKey('Product', null = True,on_delete = models.SET_NULL) \n class Meta:\n unique_together = (('fId', 'cId'),)\n\n\n #password = forms.CharField(max_length=32, widget=forms.PasswordInput)\n\n\n#add to basket\n# create new basket item with iscurrent set to true, if no entry with basket is current true.\n# else x\n#*purchase \n#basketde isCurrent== True yoksa yeni basket objesi yaratsın\n#ve sadece purchase gerçekleşirse isCurrent = False\n\nclass Invoice(models.Model):\n price = models.FloatField(null = True)\n cost = models.FloatField(null = True)\n iId = models.AutoField(primary_key=True)\n time = models.DateTimeField(null=True)\n \n\n # we should inlcude date field\n # store profit and loss information \n class Meta:\n unique_together = (('iId', 'bId','dId','cId'),)\n cId = models.ForeignKey('Customer', null=True,on_delete = models.SET_NULL)\n bId = models.ForeignKey('Basket', null = True,on_delete = models.SET_NULL) ##### değiştirsek \n dId = models.ForeignKey('Delivery', null = True,on_delete = models.SET_NULL)\n\n oId = models.ForeignKey('Order', null = True,on_delete = models.SET_NULL)\n \nclass Order(models.Model):\n oId = models.AutoField(primary_key=True)\n\nclass Rating(models.Model):\n rId = models.AutoField(primary_key=True)\n pId = models.ForeignKey('Product', null=True,on_delete = models.SET_NULL,related_name =\"productRating\")\n cId = models.ForeignKey('Customer', null=True,on_delete = models.SET_NULL)\n rating = models.IntegerField(null = True)\n commentbody = models.CharField(max_length=200,null = True)\n commentHeader = models.CharField(max_length=60,null = True)\n waitingForApproval = models.NullBooleanField() # set True when a customer make a rating, set false when product manager\n # makes a decision\n Approved = models.NullBooleanField() # set True when product manager approves the rating\n # false means comment is rejected\nclass Coupon(models.Model):\n couponId = models.AutoField(primary_key=True)\n discountRate = models.FloatField(null = True)\n cId = models.ForeignKey('Customer', null=True,on_delete = models.SET_NULL)\n couponName = models.CharField(max_length=60,null = True)\n \n#customer\n#see my Ratings that wait for approval\n\n#Product Manager\n#see approvalList\n#approve/reject Rating\n\n#product\n#see Rating\n#add Rating\n#delete Rating\n\n\n\n\n#c1 #customer1 \n#c1 #customer2 \n#c2 #customer2 \n#c2 #customer4 \n\n\n#[c1:sport > c2:electronic > c3:pets > c4 > c5]\n\n\n#c1 : yaşı 25 küçüklere sport göster \n\n#c1 #customer1 \n#c1 #customer2 \n\n","sub_path":"online_store/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":7231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"606946043","text":"\"\"\"\nThis solves LC279 Perfect Squares using number theory.\n\nTheory:\n\n1. Lagrange's four-square theorem: every natural number can be represented \nas the sum of four integer squares (including 0 squares). Ie, every positive\ninteger can be represented as the sum of 1, 2, 3, or 4 positive squares.\n\n2. Legendre's three-square theorem: a natural number can be represented as the \nsum of three squares (including 0 squares) if and only if n is not of the form \nn=(4^a)(8b+7) for nonnegative integers a and b.\n\nThe first numbers that cannot be expressed as the sum of three squares\n(including 0 squares) (ie, numbers that can be expressed as n=(4^a)(8b+7)) are:\n7, 15, 23, 28, 31, 39, 47, 55, 60, 63, 71 ...\n\nSo, by Lagrange's theorem, these integers can be represented as the sum of\nfour positive squares.\n\nSo a positive integer can be represented by 3 positive squares if and only if\nit is not a square itself, it is not a sum of squares, and it does not have\nthe form n=(4^a)(8b+7).\n\n3. Sum of two squares theorem: an integer greater than one can be written as a \nsum of two squares (including 0 squares) if and only if its prime decomposition\ncontains no prime congruent to 3 mod 4 raised to an odd power.\n\nExamples using fact that 7 = 3 mod 4, but 2 and 5 are not:\n2540 = 2 * 5^2 * 7^2 = 7^2 + 49^2.\n3430 = 2 * 5 * 7^3 cannot be expressed as the sum of two squares.\n\nFollowing is special case:\n\n4. Fermat's theorem on sums of two squares: an odd prime p can be expressed as\nthe sum of two squares if and only if p = 1 (mod 4). Such an odd prime is\ncalled a Pythagorean prime.\n\nExamples: \n5 = 1 + 4\n13 = 4 + 9\n17 = 1 + 16\n29 = 4 + 25 \n37 = 1 + 36\n41 = 16 + 25\n\"\"\"\n\n# Assume n >= 0\ndef is_square(n: int) -> bool:\n n_sqrt = int(n**0.5)\n return n_sqrt * n_sqrt == n\n\n###############################################################################\n\"\"\"\nSum of two squares theorem: an integer greater than one can be written as a \nsum of two squares (including 0 squares) if and only if its prime decomposition\ncontains no prime congruent to 3 mod 4 raised to an odd power.\n\nExamples using fact that 7 = 3 mod 4, but 2 and 5 are not:\n2540 = 2 * 5^2 * 7^2 = 7^2 + 49^2.\n3430 = 2 * 5 * 7^3 cannot be expressed as the sum of two squares.\n\nConsider only positive squares. Eg, 16 = 16 + 0 is not considered\na sum of two squares here.\n\"\"\"\ndef sum_of_two_squares(n : int) -> bool: \n from primes import prime_factorization_dict\n\n if is_square(n):\n return False\n\n d = prime_factorization_dict(n)\n \n for prime, power in d.items():\n if (prime % 4 == 3) and (power % 2 == 1):\n return False\n\n return True\n\n# This is probably faster...\ndef sum_of_two_squares2(n : int) -> bool:\n end = int(n**0.5) + 1\n\n # for i in range(1, end):\n # if is_square(n - i*i):\n # return True\n\n # return False\n\n return any(is_square(n - i*i) for i in range(1, end))\n\n\"\"\"\nLegendre's three-square theorem: a natural number can be represented as the \nsum of three squares (including 0 squares) if and only if n is not of the form \nn=(4^a)(8b+7) for nonnegative integers a and b.\n\nThe first numbers that cannot be expressed as the sum of three squares\n(including 0 squares) (ie, numbers that can be expressed as n=(4^a)(8b+7)) are:\n7, 15, 23, 28, 31, 39, 47, 55, 60, 63, 71, 79, 92, 112, ...\n\nSo, by Lagrange's theorem, these integers can be represented as the sum of\nfour positive squares.\n\nIf legendre_form(n) == True, then n is the sum of four positive squares.\n\"\"\"\ndef sum_of_four_squares(n: int) -> bool:\n # Assume n > 0.\n while (n & 3) == 0: # n % 4 == 0\n n >>= 2 # n //= 4\n\n return (n & 7) == 7 # n % 8 == 7\n\ndef sum_of_four_squares2(n: int) -> bool: # aka legendre_form()\n # Assume n > 0.\n while n % 4 == 0:\n n //= 4\n\n return n % 8 == 7\n\n\"\"\"\nReturns minimum number of positive squares that add up to given integer n.\n\"\"\"\ndef num_squares(n: int) -> int:\n if is_square(n):\n return 1\n\n #if sum_of_two_squares(n):\n if sum_of_two_squares2(n):\n return 2\n\n #if sum_of_four_squares(n):\n if sum_of_four_squares2(n):\n return 4\n\n return 3\n #primes_cong3 = [3,7,11,19,23,31,43,47,59,67,71,79,83,91,103]\n #primes_cong1 = [5,13,17,29,37,41,53,61,73,89,97,101] # sum of two squares\n #legendre = [7,15,23,28,31,39,47,55,60,63,71,79,92,112]\n \n #if n in primes_cong1:\n # return 2\n\n\n###############################################################################\n\nif __name__ == \"__main__\":\n print(\"=\"*80)\n\n d = {1: [], 2: [], 3: [], 4: []}\n\n for i in range(1000):\n n_sq = num_squares(i)\n d[n_sq].append(i)\n\n print(f\"{i}: {n_sq}\", end=\", \")\n \n print(\"\\n\") \n print(\"=\"*80)\n\n for n_sq, lst in d.items():\n print(f\"\\nSum of {n_sq} square(s):\")\n print(lst)\n print()\n","sub_path":"sums_of_squares.py","file_name":"sums_of_squares.py","file_ext":"py","file_size_in_byte":4844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"539327759","text":"#!/usr/bin/env python\n# encoding: utf-8\n'''\n@author: RedDAI24\n@file: ex2_vectorization.py\n@time: 2018/9/15 上午1:40\n@subject:vectorization\n'''\nimport numpy as np\n\narr = np.array([[1., 2., 3.], [4., 5., 6.]])\narr\narr * arr\narr - arr\n1 / arr\narr ** 0.5\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"ex02_vectorization.py","file_name":"ex02_vectorization.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"312182295","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n###\n# Copyright (2016) Hewlett Packard Enterprise Development LP\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# You may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n###\nfrom ansible.module_utils.basic import *\nimport os.path\n\ntry:\n from hpOneView.oneview_client import OneViewClient\n from hpOneView.extras.comparators import resource_compare\n from hpOneView.exceptions import HPOneViewException\n\n HAS_HPE_ONEVIEW = True\nexcept ImportError:\n HAS_HPE_ONEVIEW = False\n\nDOCUMENTATION = '''\n---\nmodule: image_streamer_artifact_bundle\nshort_description: Manage the Artifact Bundle resource.\ndescription:\n - \"Provides an interface to manage the Artifact Bundle. Can create, update, remove, and download, upload, extract\"\nrequirements:\n - \"python >= 2.7.9\"\n - \"hpOneView >= 3.1.0\"\nauthor:\n - \"Abilio Parada (@abiliogp)\"\noptions:\n config:\n description:\n - Path to a .json configuration file containing the OneView client configuration.\n The configuration file is optional. If the file path is not provided, the configuration will be loaded from\n environment variables.\n required: false\n state:\n description:\n - Indicates the desired state for the Artifact Bundle resource.\n 'present' will ensure data properties are compliant with OneView.\n 'absent' will remove the resource from OneView, if it exists.\n 'downloaded' will download the Artifact Bundle to the file path provided.\n 'archive_downloaded' will download the Artifact Bundle archive to the file path provided.\n 'backup_uploaded' will upload the Backup for the Artifact Bundle from the file path provided.\n 'backup_created' will create a Backup for the Artifact Bundle.\n 'extracted' will extract an Artifact Bundle.\n 'backup_extracted' will extract an Artifact Bundle from the Backup.\n choices: ['present', 'absent', 'downloaded', 'archive_downloaded',\n 'backup_uploaded', 'backup_created', 'extracted', 'backup_extracted']\n required: true\n data:\n description:\n - List with Artifact Bundle properties and its associated states.\n required: true\nnotes:\n - \"A sample configuration file for the config parameter can be found at:\n https://github.com/HewlettPackard/oneview-ansible/blob/master/examples/oneview_config-rename.json\"\n - \"Check how to use environment variables for configuration at:\n https://github.com/HewlettPackard/oneview-ansible#environment-variables\"\n'''\n\nEXAMPLES = '''\n- name: Create an Artifact Bundle\n image_streamer_artifact_bundle:\n config: \"{{ config }}\"\n state: present\n data:\n name: 'Artifact Bundle'\n description: 'Description of Artifact Bundles Test'\n buildPlans:\n resourceUri: '/rest/build-plans/ab65bb06-4387-48a0-9a5d-0b0da2888508'\n readOnly: 'false'\n delegate_to: localhost\n\n- name: Download the Artifact Bundle to the file path provided\n image_streamer_artifact_bundle:\n config: \"{{ config }}\"\n state: downloaded\n data:\n name: 'Artifact Bundle'\n destinationFilePath: '~/downloaded_artifact.zip'\n delegate_to: localhost\n\n- name: Download the Archive for Artifact Bundle to the file path provided\n image_streamer_artifact_bundle:\n config: \"{{ config }}\"\n state: archive_downloaded\n data:\n name: 'Artifact Bundle'\n destinationFilePath: '~/downloaded_archive.zip'\n delegate_to: localhost\n\n- name: Upload an Artifact Bundle\n image_streamer_artifact_bundle:\n config: \"{{ config }}\"\n state: present\n data:\n localArtifactBundleFilePath: '~/uploaded_artifact.zip'\n delegate_to: localhost\n\n- name: Upload Backup an Artifact Bundle\n image_streamer_artifact_bundle:\n config: \"{{ config }}\"\n state: backup_uploaded\n data:\n deploymentGroupURI: '/rest/deployment-groups/c5a727ef-71e9-4154-a512-6655b168c2e3'\n localBackupArtifactBundleFilePath: '~/uploaded_backup.zip'\n delegate_to: localhost\n\n- name: Create Backup for Artifact Bundle\n image_streamer_artifact_bundle:\n config: \"{{ config }}\"\n state: backup_created\n data:\n deploymentGroupURI: '/rest/deployment-groups/c5a727ef-71e9-4154-a512-6655b168c2e3'\n delegate_to: localhost\n\n- name: Extract an Artifact Bundle\n image_streamer_artifact_bundle:\n config: \"{{ config }}\"\n state: extracted\n data:\n name: 'Artifact Bundle'\n delegate_to: localhost\n\n- name: Extract Backup an Artifact Bundle\n image_streamer_artifact_bundle:\n config: \"{{ config }}\"\n state: backup_extracted\n data:\n deploymentGroupURI: '/rest/deployment-groups/c5a727ef-71e9-4154-a512-6655b168c2e3'\n delegate_to: localhost\n\n- name: Update an Artifact Bundle\n image_streamer_artifact_bundle:\n config: \"{{ config }}\"\n state: present\n data:\n name: 'Artifact Bundle'\n newName: 'Artifact Bundle Updated'\n delegate_to: localhost\n\n- name: Remove an Artifact Bundle\n image_streamer_artifact_bundle:\n config: \"{{ config }}\"\n state: absent\n data:\n name: 'Artifact Bundle'\n delegate_to: localhost\n'''\n\nRETURN = '''\nartifact_bundle:\n description: Has the OneView facts about the Artifact Bundles.\n returned: On state 'present' and 'extracted'.\n type: complex\n\nartifact_bundle_deployment_group:\n description: Has the OneView facts about the Deployment Group.\n returned: On state 'backup_extracted', 'backup_uploaded', and 'backup_created'.\n type: complex\n'''\n\nARTIFACT_BUNDLE_CREATED = 'Artifact Bundle created successfully.'\nARTIFACT_BUNDLE_UPDATED = 'Artifact Bundle updated successfully.'\nARTIFACT_BUNDLE_DELETED = 'Artifact Bundle deleted successfully.'\nARTIFACT_BUNDLE_ABSENT = 'Artifact Bundle is already absent.'\nARTIFACT_BUNDLE_ALREADY_EXIST = 'Artifact Bundle already exists.'\nARTIFACT_BUNDLE_DOWNLOADED = 'Artifact Bundle downloaded successfully.'\nARTIFACT_BUNDLE_UPLOADED = 'Artifact Bundle uploaded successfully.'\nBACKUP_UPLOADED = 'Backup for Artifact Bundle uploaded successfully.'\nARCHIVE_DOWNLOADED = 'Archive of Artifact Bundle downloaded successfully.'\nBACKUP_CREATED = 'Backup of Artifact Bundle created successfully.'\nARTIFACT_BUNDLE_EXTRACTED = 'Artifact Bundle extracted successfully.'\nBACKUP_EXTRACTED = 'Artifact Bundle extracted successfully.'\n\nHPE_ONEVIEW_SDK_REQUIRED = 'HPE OneView Python SDK is required for this module.'\n\n\nclass ArtifactBundleModule(object):\n argument_spec = dict(\n config=dict(required=False, type='str'),\n state=dict(\n required=True,\n choices=['present', 'absent', 'downloaded', 'archive_downloaded', 'backup_created',\n 'backup_uploaded', 'extracted', 'backup_extracted']\n ),\n data=dict(required=True, type='dict')\n )\n\n def __init__(self):\n self.module = AnsibleModule(argument_spec=self.argument_spec, supports_check_mode=False)\n if not HAS_HPE_ONEVIEW:\n self.module.fail_json(msg=HPE_ONEVIEW_SDK_REQUIRED)\n\n if not self.module.params['config']:\n self.oneview_client = OneViewClient.from_environment_variables()\n else:\n self.oneview_client = OneViewClient.from_json_file(self.module.params['config'])\n\n self.i3s_client = self.oneview_client.create_image_streamer_client()\n\n def run(self):\n try:\n ansible_facts = {}\n\n state = self.module.params.get('state')\n data = self.module.params.get('data')\n name = data.get('name')\n\n resource = self.__get_by_name(name)\n\n if state == 'present':\n changed, msg, ansible_facts = self.__present(data, resource)\n\n elif state == 'absent':\n changed, msg, ansible_facts = self.__absent(resource)\n\n elif state == 'downloaded':\n changed, msg, ansible_facts = self.__download(data, resource)\n elif state == 'archive_downloaded':\n changed, msg, ansible_facts = self.__download_archive(data, resource)\n\n elif state == 'backup_uploaded':\n changed, msg, ansible_facts = self.__upload_backup(data)\n\n elif state == 'backup_created':\n changed, msg, ansible_facts = self.__create_backup(data)\n\n elif state == 'extracted':\n changed, msg, ansible_facts = self.__extract(resource)\n elif state == 'backup_extracted':\n changed, msg, ansible_facts = self.__extract_backup(data)\n\n self.module.exit_json(msg=msg, changed=changed, ansible_facts=ansible_facts)\n\n except HPOneViewException as exception:\n self.module.fail_json(msg='; '.join(str(e) for e in exception.args))\n\n def __get_by_name(self, name):\n if name is None:\n return None\n return (self.i3s_client.artifact_bundles.get_by('name', name) or [None])[0]\n\n def __present(self, data, resource):\n if data.get('newName'):\n changed, msg, facts = self.__update(data, resource)\n elif data.get('localArtifactBundleFilePath'):\n changed, msg, facts = self.__upload(data)\n elif not resource:\n changed, msg, facts = self.__create(data)\n else:\n changed = False\n msg = ARTIFACT_BUNDLE_ALREADY_EXIST\n facts = dict(artifact_bundle=resource)\n return changed, msg, facts\n\n def __absent(self, resource):\n if resource:\n self.i3s_client.artifact_bundles.delete(resource)\n changed = True\n msg = ARTIFACT_BUNDLE_DELETED\n else:\n changed = False\n msg = ARTIFACT_BUNDLE_ABSENT\n return changed, msg, {}\n\n def __create(self, data):\n data['buildPlans'] = [data['buildPlans']]\n resource = self.i3s_client.artifact_bundles.create(data)\n return True, ARTIFACT_BUNDLE_CREATED, dict(artifact_bundle=resource)\n\n def __update(self, data, resource):\n if resource is None:\n resource = self.__get_by_name(data['newName'])\n data[\"name\"] = data.pop(\"newName\")\n merged_data = resource.copy()\n merged_data.update(data)\n\n if not resource_compare(resource, merged_data):\n resource = self.i3s_client.artifact_bundles.update(merged_data)\n changed = True\n msg = ARTIFACT_BUNDLE_UPDATED\n else:\n changed = False\n msg = ARTIFACT_BUNDLE_ALREADY_EXIST\n return changed, msg, dict(artifact_bundle=resource)\n\n def __download(self, data, resource):\n self.i3s_client.artifact_bundles.download_artifact_bundle(resource['uri'], data['destinationFilePath'])\n return False, ARTIFACT_BUNDLE_DOWNLOADED, {}\n\n def __download_archive(self, data, resource):\n self.i3s_client.artifact_bundles.download_archive_artifact_bundle(resource['uri'], data['destinationFilePath'])\n return False, ARCHIVE_DOWNLOADED, {}\n\n def __upload(self, data):\n file_name = data['localArtifactBundleFilePath']\n file_name_path = os.path.basename(file_name)\n file_name_wo_ext = os.path.splitext(file_name_path)[0]\n artifact_bundle = self.__get_by_name(file_name_wo_ext)\n if artifact_bundle is None:\n artifact_bundle = self.i3s_client.artifact_bundles.upload_bundle_from_file(file_name)\n changed = True\n msg = ARTIFACT_BUNDLE_UPLOADED\n else:\n changed = False\n msg = ARTIFACT_BUNDLE_ALREADY_EXIST\n return changed, msg, dict(artifact_bundle=artifact_bundle)\n\n def __upload_backup(self, data):\n deployment_group = self.i3s_client.artifact_bundles.upload_backup_bundle_from_file(\n data['localBackupArtifactBundleFilePath'], data['deploymentGroupURI'])\n return True, BACKUP_UPLOADED, dict(artifact_bundle_deployment_group=deployment_group)\n\n def __create_backup(self, data):\n resource = self.i3s_client.artifact_bundles.create_backup(data)\n return False, BACKUP_CREATED, dict(artifact_bundle_deployment_group=resource)\n\n def __extract(self, resource):\n resource = self.i3s_client.artifact_bundles.extract_bundle(resource)\n return True, ARTIFACT_BUNDLE_EXTRACTED, dict(artifact_bundle=resource)\n\n def __extract_backup(self, data):\n resource = self.i3s_client.artifact_bundles.extract_backup_bundle(data)\n return True, BACKUP_EXTRACTED, dict(artifact_bundle_deployment_group=resource)\n\n\ndef main():\n ArtifactBundleModule().run()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"oneview-ansible-3.1.1/library/image_streamer_artifact_bundle.py","file_name":"image_streamer_artifact_bundle.py","file_ext":"py","file_size_in_byte":12999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"178862318","text":"'''\nWe have requests from customers to send their admins a data export\nof all user activity on the site.\n\nThis script queries the database for a list of all users and the content\nthey've interacted with on the site. It then constructs an xlsx file and then sends it\nto an email address specified via a command line parameter\n'''\n\nimport argparse\nimport csv\nimport os\nfrom collections import Counter\n\nfrom scripts.utils import Email\n\nimport django # isort:skip\ndjango.setup() # isort:skip\n\nfrom central import models # noqa isort:skip\n\n\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'exercise.settings')\n\nfilename = 'users.csv'\n\n\ndef main(client, email):\n # Obtain all the entities we need to process\n site = models.Site.objects.get(domain=client)\n users = models.User.objects.filter(site=site)\n user_ids = users.values_list('id', flat=True)\n ideas = models.Idea.objects.filter(site=site)\n idea_creators_ids = ideas.values_list('creator_id', flat=True)\n challenges = models.Challenge.objects.filter(site=site)\n challenge_creators_ids = challenges.values_list('creator_id', flat=True)\n communities = models.Community.objects.filter(site=site)\n community_creators_ids = communities.values_list('creator_id', flat=True)\n conversations = models.Conversation.objects.filter(site=site)\n conversation_creators_ids = conversations.values_list('creator_id', flat=True)\n idea_comments = models.IdeaComment.objects.filter(site=site)\n idea_comment_creators_ids = idea_comments.values_list('creator_id', flat=True)\n idea_comments_liked_ids = []\n\n for comment in idea_comments:\n idea_comments_liked_ids.extend(\n comment.liked_by.all().values_list('id', flat=True)\n )\n\n idea_voters_ids = []\n\n for idea in ideas:\n idea_voters_ids.extend(\n idea.votes.all().values_list('creator_id', flat=True)\n )\n\n stage_comments_likers_ids = []\n\n idea_creators_counter = Counter(idea_creators_ids)\n challenge_creators_counter = Counter(challenge_creators_ids)\n idea_comment_counter = Counter(idea_comment_creators_ids)\n idea_comment_likes_counter = Counter(idea_comments_liked_ids)\n idea_votes_counter = Counter(idea_voters_ids)\n conversation_counter = Counter(conversation_creators_ids)\n community_counter = Counter(community_creators_ids)\n stage_comment_likes_counter = Counter(stage_comments_likers_ids)\n\n with open(filename, 'w') as csvfile:\n userwriter = csv.writer(csvfile)\n userwriter.writerow(['Active Users', 'Activities'])\n\n for id in user_ids:\n activity = []\n email = models.User.objects.get(id=id).email\n\n if challenge_creators_counter[id]:\n action = 'The user created {} challenges.'.format(\n challenge_creators_counter[id],\n )\n activity.append(action)\n\n if idea_creators_counter[id]:\n action = 'The user created {} ideas.'.format(\n idea_creators_counter[id],\n )\n activity.append(action)\n\n if idea_comment_counter[id]:\n action = 'The user submitted {} idea comments.'.format(\n idea_comment_counter[id],\n )\n activity.append(action)\n\n if idea_comment_likes_counter[id]:\n action = 'The user liked {} comments on ideas.'.format(\n idea_comment_likes_counter[id],\n )\n activity.append(action)\n\n if idea_votes_counter[id]:\n action = 'The user voted {} ideas.'.format(\n idea_votes_counter[id],\n )\n activity.append(action)\n\n if conversation_counter[id]:\n action = 'The user created {} conversations.'.format(\n conversation_counter[id],\n )\n activity.append(action)\n\n if (community_counter[id]):\n action = 'The user created {} communities'.format(community_counter[id])\n activity.append(action)\n\n for community in communities:\n if community.managers.filter(id=id):\n action = 'The user is a manager of the community \"{}\".'.format(\n community.name,\n )\n activity.append(action)\n\n if community.members.filter(id=id):\n action = 'The user is a member of the community \"{}\".'.format(\n community.name,\n )\n activity.append(action)\n\n if stage_comment_likes_counter[id]:\n action = 'The user liked {} review comments.'.format(\n stage_comment_likes_counter[id],\n )\n activity.append(action)\n\n if activity:\n userwriter.writerow([email] + activity)\n\n # Before sending, check we are only sending to a manager\n recipient = models.User.objects.get(email=email)\n if recipient.is_manager:\n email_sender = Email()\n email_sender.send_email(\n send_to=email,\n subject='User Activity Export',\n attachment=filename\n )\n\n # Clean up after ourselves\n os.remove(filename)\n\n\ndef parse_arguments():\n parser = argparse.ArgumentParser(\n description='A script to generate and email an xlsx file containing user activity'\n )\n parser.add_argument(\n '-c', '--customer',\n help='the customer site',\n required=True,\n )\n parser.add_argument(\n '-e', '--email',\n help='the email address where to send the email with the output file',\n required=True,\n )\n\n return parser.parse_args()\n\n\nif __name__ == \"__main__\":\n ns = parse_arguments()\n\n main(ns.customer, ns.email)\n","sub_path":"scripts/user_activity_export.py","file_name":"user_activity_export.py","file_ext":"py","file_size_in_byte":5908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"271492555","text":"# Module to run tests on using AbsComponent\n\nfrom __future__ import print_function, absolute_import, division, unicode_literals\n\n# TEST_UNICODE_LITERALS\n\nimport pytest\nfrom astropy import units as u\nfrom astropy.table import QTable\nimport numpy as np\n\n#import matplotlib\n#matplotlib.use('Agg')\n\nfrom linetools.isgm.abscomponent import AbsComponent\nfrom linetools.spectralline import AbsLine\nfrom linetools.spectra import io as lsio\n\nimport imp\nlt_path = imp.find_module('linetools')[1]\n\n#import pdb\n#pdb.set_trace()\n# Set of Input lines\n\ndef test_build_table():\n # AbsLine(s)\n lya = AbsLine(1215.670*u.AA)\n lya.analy['vlim'] = [-300.,300.]*u.km/u.s\n lya.attrib['z'] = 2.92939\n lyb = AbsLine(1025.7222*u.AA)\n lyb.analy['vlim'] = [-300.,300.]*u.km/u.s\n lyb.attrib['z'] = lya.attrib['z']\n # Instantiate\n abscomp = AbsComponent.from_abslines([lya,lyb])\n comp_tbl = abscomp.build_table()\n # Test\n assert isinstance(comp_tbl,QTable)\n\n\ndef test_synthesize_colm():\n # Read a spectrum Spec\n xspec = lsio.readspec(lt_path+'/spectra/tests/files/UM184_nF.fits')\n # AbsLines\n SiIItrans = ['SiII 1260', 'SiII 1304', 'SiII 1526', 'SiII 1808']\n abslines = []\n for trans in SiIItrans:\n iline = AbsLine(trans)\n iline.attrib['z'] = 2.92939\n iline.analy['vlim'] = [-250.,80.]*u.km/u.s\n iline.analy['spec'] = xspec\n abslines.append(iline)\n # Component\n abscomp = AbsComponent.from_abslines(abslines)\n # Column\n abscomp.synthesize_colm(redo_aodm=True)\n # Test\n np.testing.assert_allclose(abscomp.logN,13.594447075294818)\n\ndef test_cog():\n # Read a spectrum Spec\n xspec = lsio.readspec(lt_path+'/spectra/tests/files/UM184_nF.fits')\n # AbsLines\n SiIItrans = ['SiII 1260', 'SiII 1304', 'SiII 1526', 'SiII 1808']\n abslines = []\n for trans in SiIItrans:\n iline = AbsLine(trans)\n iline.attrib['z'] = 2.92939\n iline.analy['vlim'] = [-250.,80.]*u.km/u.s\n iline.analy['spec'] = xspec\n abslines.append(iline)\n # Component\n abscomp = AbsComponent.from_abslines(abslines)\n # COG\n COG_dict = abscomp.cog(redo_EW=True)\n # Test\n np.testing.assert_allclose(COG_dict['logN'],13.693355878125537)\n np.testing.assert_allclose(COG_dict['sig_logN'],0.054323725737309987)\n\n\"\"\"\ndef test_stack_plot():\n # AbsLine(s)\n lya = AbsLine(1215.670*u.AA)\n lya.analy['vlim'] = [-300.,300.]*u.km/u.s\n lya.attrib['z'] = 2.92939\n lyb = AbsLine(1025.7222*u.AA)\n lyb.analy['vlim'] = [-300.,300.]*u.km/u.s\n lyb.attrib['z'] = lya.attrib['z']\n # Spectra\n xspec = lsio.readspec(lt_path+'/spectra/tests/files/UM184_nF.fits')\n lya.analy['spec'] = xspec\n lyb.analy['spec'] = xspec\n # Instantiate\n abscomp = AbsComponent.from_abslines([lya,lyb])\n # Plot\n abscomp.stack_plot(show=False)\n\"\"\"\n","sub_path":"linetools/isgm/tests/test_use_abscomp.py","file_name":"test_use_abscomp.py","file_ext":"py","file_size_in_byte":2846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"279037412","text":"\"\"\"Spherical linear interpolation (SLERP).\"\"\"\nimport numpy as np\nfrom ._utils import (check_axis_angle, check_quaternion, angle_between_vectors,\n check_rotor)\n\n\ndef axis_angle_slerp(start, end, t):\n \"\"\"Spherical linear interpolation.\n\n Parameters\n ----------\n start : array-like, shape (4,)\n Start axis of rotation and rotation angle: (x, y, z, angle)\n\n end : array-like, shape (4,)\n Goal axis of rotation and rotation angle: (x, y, z, angle)\n\n t : float in [0, 1]\n Position between start and goal\n\n Returns\n -------\n a : array, shape (4,)\n Interpolated axis of rotation and rotation angle: (x, y, z, angle)\n \"\"\"\n start = check_axis_angle(start)\n end = check_axis_angle(end)\n angle = angle_between_vectors(start[:3], end[:3])\n w1, w2 = slerp_weights(angle, t)\n w1 = np.array([w1, w1, w1, (1.0 - t)])\n w2 = np.array([w2, w2, w2, t])\n return w1 * start + w2 * end\n\n\ndef quaternion_slerp(start, end, t):\n \"\"\"Spherical linear interpolation.\n\n Parameters\n ----------\n start : array-like, shape (4,)\n Start unit quaternion to represent rotation: (w, x, y, z)\n\n end : array-like, shape (4,)\n End unit quaternion to represent rotation: (w, x, y, z)\n\n t : float in [0, 1]\n Position between start and goal\n\n Returns\n -------\n q : array, shape (4,)\n Interpolated unit quaternion to represent rotation: (w, x, y, z)\n \"\"\"\n start = check_quaternion(start)\n end = check_quaternion(end)\n angle = angle_between_vectors(start, end)\n w1, w2 = slerp_weights(angle, t)\n return w1 * start + w2 * end\n\n\ndef rotor_slerp(start, end, t):\n \"\"\"Spherical linear interpolation.\n\n Parameters\n ----------\n start : array-like, shape (4,)\n Rotor: (a, b_yz, b_zx, b_xy)\n\n end : array-like, shape (4,)\n Rotor: (a, b_yz, b_zx, b_xy)\n\n t : float in [0, 1]\n Position between start and goal\n\n Returns\n -------\n rotor : array, shape (4,)\n Interpolated rotor: (a, b_yz, b_zx, b_xy)\n \"\"\"\n start = check_rotor(start)\n end = check_rotor(end)\n return quaternion_slerp(start, end, t)\n\n\ndef slerp_weights(angle, t):\n \"\"\"Compute weights of start and end for spherical linear interpolation.\"\"\"\n if angle == 0.0:\n return np.ones_like(t), np.zeros_like(t)\n else:\n return (np.sin((1.0 - t) * angle) / np.sin(angle),\n np.sin(t * angle) / np.sin(angle))\n","sub_path":"pytransform3d/rotations/_slerp.py","file_name":"_slerp.py","file_ext":"py","file_size_in_byte":2476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"333651590","text":"import socket\r\nimport sys\r\nimport time\r\nimport datetime\r\n\r\ntry:\r\n hostip = sys.argv[1]\r\n port = sys.argv[2]\r\nexcept:\r\n print(\"Did not provide enough arguments!\")\r\n print(\"Please provide ip, port# and file name\")\r\n print(\"Ex: 127.0.0.1 80 index.html\")\r\n sys.exit(1)\r\n\r\ntry:\r\n clientSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\nexcept:\r\n print(\"Socket Error\")\r\n sys.exit(1)\r\n\r\nmessage = 'ping'\r\nreply = ''\r\ntimeStart = 0\r\ntimeEnd = 0\r\ntimeDif = 0\r\nfor x in range(0, 10):\r\n\tclientSocket.sendto(message + \" \" + str(x+1) + \" \" + str(datetime.datetime.now().time()), (hostip, int(port)))\r\n\ttimeStart = time.time()\r\n\tclientSocket.settimeout(1.0)\r\n\ttry:\t\t\r\n\t\treply = clientSocket.recv(1024)\r\n\texcept:\r\n\t\tcontinue\r\n\tclientSocket.settimeout(None)\r\n\tif(reply):\r\n\t\ttimeEnd = time.time()\r\n\t\ttimeDif = timeEnd - timeStart\r\n\t\tprint(reply + \" \" + str(timeDif*1000) + \"ms\")\r\n\r\n\r\nif(len(reply) == 0):\r\n\tprint(\"Connection timed out\")\r\n\r\nclientSocket.close()\r\n","sub_path":"lab2/pingclient.py","file_name":"pingclient.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"515571255","text":"import click\n\nfrom client.client_request import client_request\n\n\n@click.command()\n@click.argument('http_verb')\n@click.argument('url')\ndef httlemon(http_verb, url):\n\n beautified_response = client_request(http_verb, url)\n click.echo(beautified_response)\n\nif __name__ == '__main__':\n\n httlemon()\n","sub_path":"build/lib/command/httlemon.py","file_name":"httlemon.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"528467375","text":"from django.http import Http404\nfrom .models import Item\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom .serializers import ItemSerializer\n\n\nclass ItemList(APIView):\n\n def get_object(self):\n try:\n return Item.objects.all()\n except Item.DoesNotExist:\n raise Http404\n\n def get(self, request):\n items = self.get_object()\n serializer = ItemSerializer(items, many=True)\n return Response(serializer.data)\n\n\nclass FilteredItems(APIView):\n\n def equals(self, column, value):\n kwargs = {column: value}\n try:\n items = Item.objects.filter(**kwargs)\n return items\n except Item.DoesNotExist:\n raise Http404\n\n def more(self, column, value):\n column += '__gt'\n kwargs = {column: value}\n try:\n items = Item.objects.filter(**kwargs)\n return items\n except Item.DoesNotExist:\n raise Http404\n\n def less(self, column, value):\n column += '__lt'\n kwargs = {column: value}\n try:\n items = Item.objects.filter(**kwargs)\n\n return items\n except Item.DoesNotExist:\n raise Http404\n\n def contains(self, column, value):\n try:\n items = Item.objects.filter(name__icontains=value)\n return items\n except Item.DoesNotExist:\n raise Http404\n\n def post(self, request):\n data = []\n\n clause = request.data['selected_clause']\n column = request.data['selected_column']\n value = request.data['sort_value']\n\n if clause == 'equals':\n data = self.equals(column, value)\n elif clause == 'more':\n data = self.more(column, value)\n elif clause == 'less':\n data = self.less(column, value)\n elif clause == 'contains':\n data = self.contains(column, value)\n\n serializer = ItemSerializer(data, many=True)\n\n return Response(serializer.data)\n\n\nclass SortedItems(APIView):\n\n def sort(self, column):\n try:\n return Item.objects.order_by(column)\n except Item.DoesNotExist:\n raise Http404\n\n def post(self, request):\n column = request.data['selected_column']\n serializer = ItemSerializer(self.sort(column), many=True)\n\n return Response(serializer.data)","sub_path":"application/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"164427069","text":"from pydm import Display\nfrom PyQt5.QtGui import QStandardItem\nfrom PyQt5.QtWidgets import (QWidgetItem, QCheckBox, QPushButton, QLineEdit,\n QGroupBox, QHBoxLayout, QMessageBox, QWidget,\n QLabel, QFrame, QComboBox, QRadioButton)\nfrom os import path, pardir, makedirs\nfrom qtpy.QtCore import Slot, QTimer\nfrom functools import partial, reduce\nfrom datetime import datetime, timedelta\nimport sys\n\n\nclass MicDisp(Display):\n\n def __init__(self, parent=None, args=None, ui_filename=\"FFT_test.ui\"):\n super(MicDisp, self).__init__(parent=parent, args=args, ui_filename=ui_filename)\n self.pathHere = path.dirname(sys.modules[self.__module__].__file__)\n# print(self.pathHere)\n self.ui.StrtBut.clicked.connect(self.setGOVal)\n \n self.timer= QTimer() \n self.timer.timeout.connect(self.showTime)\n\n def showTime(self):\n global count\n self.ui.AcqProg.setText(\"Data Acquisition started. \"+str(count)+\" sec left.\")\t# decrementing the counter\n count -= 1\n if count<0:\n self.timer.stop()\n self.getDataBack()\n return\n\n def setGOVal(self):\n global count\n timMeas = self.ui.spinBox.value() # Get time for measurement from spinBox \n count=timMeas\n print(count)\n self.timer.start(1000)\n \n return (\"This is it\")\n\n def getDataBack(self):\n print(\"count is \", count)\n print (\"got beyond timer\")\n # Now go get data and plot\n return\n ","sub_path":"demoOfProb.py","file_name":"demoOfProb.py","file_ext":"py","file_size_in_byte":1561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"531063820","text":"import datetime\n\nfrom project.server import db\n\nfrom sqlalchemy import inspect\n\n\nclass Attachments(db.Model):\n\n __tablename__ = 'attachments'\n\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n fileName = db.Column(db.String(255), nullable=False)\n documentLink = db.Column(db.String(255), nullable=False)\n question_id = db.Column(db.Integer, db.ForeignKey('question.id'), nullable=False)\n created_date = db.Column(db.DateTime, nullable=False)\n modified_date = db.Column(db.DateTime, nullable=True)\n\n def __init__(self, fileName , documentLink, question_id):\n self.fileName = fileName\n self.documentLink = documentLink\n self.question_id = question_id\n self.created_date = datetime.datetime.now()\n\n def __repr__(self):\n return '' % (self.fileName)\n\n def to_dict(self):\n return {c.key: getattr(self, c.key) for c in inspect(self).mapper.column_attrs}","sub_path":"DPIA_WEBSERVICE/project/server/models/Attachments.py","file_name":"Attachments.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"550375251","text":"import json\nfrom utils.mongo import Mongo\n\nneed = []\n\n\ndef get_children(content):\n if isinstance(content, list):\n for item in content:\n get_children(item)\n\n elif isinstance(content, dict):\n children = content.get('children')\n if children is None:\n need.append(content.get('title'))\n else:\n get_children(children)\n\n else:\n print(content)\n\n\nif __name__ == \"__main__\":\n # with open('./data/locationTree.json', 'r', encoding='utf-8') as fn:\n # data = json.loads(fn.read())\n\n # get_children(data)\n\n # with open('./data/need_title.json', 'w', encoding='utf-8') as fn:\n # fn.write(json.dumps(need, ensure_ascii=False, indent=4))\n\n with open('./data/need_title.json', 'r', encoding='utf-8') as fn:\n data = json.loads(fn.read())\n\n sign = 0\n for value in data:\n if value == 'Bodø':\n sign = 0\n\n Mongo.repeat({'name': value, 'status': sign}, 'title')\n","sub_path":"now/proff/get_title.py","file_name":"get_title.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"369834348","text":"'''\nCreated on Oct 25, 2010\n\n@author: christina\n'''\n\n\nimport paramiko # comment-out for virtual-tiramola\nimport Utils\nfrom sqlalchemy import exc, create_engine # comment-out for virtual-tiramola\nimport time, sys\n\nclass RiakCluster(object):\n '''\n This class holds all nodes of the db in the virtual cluster. It can start/stop individual \n daemons as needed, thus adding/removing nodes at will. It also sets up the configuration \n files as needed. \n '''\n\n def __init__(self, initial_cluster_id = \"default\"):\n '''\n Constructor\n '''\n ## Necessary variables\n self.cluster = {}\n self.host_template = \"\"\n self.cluster_id = initial_cluster_id\n self.utils = Utils.Utils()\n \n # Make sure the sqlite file exists. if not, create it and add the table we need\n con = create_engine(self.utils.db_file)\n cur = con.connect()\n try:\n clusters = cur.execute('select * from clusters',\n ).fetchall()\n if len(clusters) > 0 :\n print(\"\"\"Already discovered cluster id from previous database file. Will select the defined one to work with (if it exists).\"\"\")\n# print \"Found records:\\n\", clusters \n\n clustersfromcid = cur.execute('select * from clusters where cluster_id=\\\"'+self.cluster_id+\"\\\"\",\n ).fetchall()\n if len(clustersfromcid) > 0 :\n self.cluster = self.utils.get_cluster_from_db(self.cluster_id)\n # print self.cluster\n for clusterkey in list(self.cluster.keys()):\n if not (clusterkey.find(\"master\") == -1):\n self.host_template = clusterkey.replace(\"master\",\"\")\n # Add self to db (eliminates existing records of same id)\n self.utils.add_to_cluster_db(self.cluster, self.cluster_id)\n else:\n print(\"No known cluster with this id - run configure before you proceed\")\n \n except exc.DatabaseError:\n cur.execute('create table clusters(cluster_id text, hostname text, euca_id text)')\n \n \n cur.close()\n \n \n \n def configure_cluster(self, nodes=None, host_template=\"\", reconfigure=True):\n self.host_template = host_template\n \n if not reconfigure:\n con = create_engine(self.utils.db_file)\n cur = con.connect()\n cur.execute('delete from clusters where cluster_id=\\\"'+self.utils.cluster_name+\"\\\"\")\n cur.close()\n \n self.cluster = {}\n \n print(('Cluster size: ' + str(len(self.cluster))))\n self.add_nodes(nodes)\n \n else:\n print(('Cluster size: ' + str(len(self.cluster))))\n print(\"This cluster is already configured, use the db entries.\")\n \n ## Now you should be ok, so return the nodes with hostnames\n return self.cluster\n \n def start_cluster (self):\n for (clusterkey, clusternode) in list(self.cluster.items()):\n ssh = paramiko.SSHClient()\n ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) \n ssh.connect(clusternode.public_dns_name, username='root', password='secretpw') \n# stdin, stdout, stderr = ssh.exec_command('/usr/sbin/riaksearch start')\n stdin, stdout, stderr = ssh.exec_command('riak start')\n print(('Node '+ clusternode.public_dns_name +': '))\n print((stdout.readlines()))\n sys.stdout.flush()\n \n ssh.close()\n \n def stop_cluster (self):\n for (clusterkey, clusternode) in list(self.cluster.items()):\n ssh = paramiko.SSHClient()\n ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) \n ssh.connect(clusternode.public_dns_name, username='root', password='secretpw') \n# stdin, stdout, stderr = ssh.exec_command('/usr/sbin/riaksearch stop')\n stdin, stdout, stderr = ssh.exec_command('riak stop')\n print((stdout.readlines()))\n ssh.close()\n \n def add_nodes (self, nodes = None):\n for node in nodes:\n time.sleep(10)\n self.add_node(node, True)\n \n print((self.cluster))\n \n # Make /etc/hosts file for all nodes\n self.make_hosts()\n ## Save to database\n self.utils.add_to_cluster_db(self.cluster, self.cluster_id)\n \n \n def add_node (self, node = None, bulk = False):\n key_template_path=\"./templates/ssh_keys\"\n \n ssh = paramiko.SSHClient()\n ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n print((node.public_dns_name))\n sys.stdout.flush()\n ssh.connect(node.public_dns_name, username='root', password='secretpw')\n \n ## Check for installation dirs, otherwise exit with error message\n stderr_all = []\n# stdin, stdout, stderr = ssh.exec_command('ls /usr/sbin/riaksearch')\n stdin, stdout, stderr = ssh.exec_command('ls /usr/sbin/riak')\n stderr_all.append(stderr.readlines())\n stdin, stdout, stderr = ssh.exec_command('echo \"riak - nofile 200000\" >> /etc/security/limits.conf')\n# stdin, stdout, stderr = ssh.exec_command('ulimit -n 40000')\n stderr_all.append(stderr.readlines())\n for stderr in stderr_all:\n if len(stderr) > 0 :\n print(\"ERROR - installation files are missing\")\n return -1 # -1 error value\n \n # Set hostname on the machine\n name = \"\"\n i = len(self.cluster) \n if i == 0:\n name = self.host_template+\"master\"\n else: \n name = self.host_template+str(i)\n \n \n stdin, stdout, stderr = ssh.exec_command('echo \\\"'+name+\"\\\" > /etc/hostname\")\n stdin, stdout, stderr = ssh.exec_command('hostname \\\"'+name+\"\\\"\")\n \n # Move files to node \n transport = paramiko.Transport(node.public_dns_name)\n transport.connect(username = 'root', password = 'secretpw') \n transport.open_channel(\"session\", node.public_dns_name, \"localhost\")\n sftp = paramiko.SFTPClient.from_transport(transport)\n \n # Copy private and public key\n sftp.put( key_template_path+\"/id_rsa\",\"/root/.ssh/id_rsa\")\n sftp.put( key_template_path+\"/id_rsa.pub\", \"/root/.ssh/id_rsa.pub\")\n sftp.put( key_template_path+\"/config\", \"/root/.ssh/config\")\n \n # Copy the config file and script that will configure riak\n sftp.put( \"./templates/riak/app.config\", \"/etc/riak/app.config\")\n sftp.put( \"./templates/riak/configure-riak.sh\", \"/root/configure-riak.sh\")\n sftp.close()\n \n ## Change permissions for private key\n stdin, stdout, stderr = ssh.exec_command('chmod 0600 /root/.ssh/id_rsa')\n\n # Add public key to authorized_keys\n stdin, stdout, stderr = ssh.exec_command('cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys')\n\n ## Change mode for the script\n stdin, stdout, stderr = ssh.exec_command('chmod a+x /root/configure-riak.sh')\n \n ## Run the script for the appropriate IP (the node's)\n stdin, stdout, stderr = ssh.exec_command('./configure-riak.sh ' + node.public_dns_name)\n print((stdout.readlines()))\n \n ## Ping the riak node to make sure it's up\n time.sleep(15)\n# stdin, stdout, stderr = ssh.exec_command('/usr/sbin/riaksearch ping')\n stdin, stdout, stderr = ssh.exec_command('riak ping')\n print((stdout.readlines()))\n sys.stdout.flush()\n \n # If you're not the first node of the cluster\n if(i > 0):\n # Send request to join the riak ring (to the first node of the cluster...)\n time.sleep(15)\n# stdin, stdout, stderr = ssh.exec_command('/usr/sbin/riaksearch-admin join riak@' +\n stdin, stdout, stderr = ssh.exec_command('riak-admin join riak@' +\n self.cluster.get(self.host_template+\"master\").public_dns_name)\n# print '/usr/sbin/riaksearch-admin join riak@' + self.cluster.get(self.host_template+\"master\").public_dns_name\n print(('riak-admin join riak@' + self.cluster.get(self.host_template+\"master\").public_dns_name))\n print((stdout.readlines()))\n sys.stdout.flush()\n \n ssh.close()\n \n # Add node to cluster\n self.cluster[name] = node\n \n # When adding only one node, bulk is False therefore you will generate a new\n # hosts file and update the cluster in the db. When adding nodes in bulk \n # do this should be done only once after having added the last one in bulk.\n if not bulk:\n self.make_hosts()\n \n ## Save new cluster to database\n self.utils.add_to_cluster_db(self.cluster, self.cluster_id)\n \n def remove_node (self, hostname=\"\"):\n if(hostname in self.cluster):\n self.cluster.pop(hostname)\n else:\n return\n \n print((\"New nodes:\", self.cluster))\n \n ssh = paramiko.SSHClient()\n ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n ssh.connect(self.cluster[hostname].public_dns_name, username='root', password='secretpw')\n # The node leaves the ring\n# stdin, stdout, stderr = ssh.exec_command('/usr/sbin/riaksearch-admin leave')\n# stdin, stdout, stderr = ssh.exec_command('/usr/sbin/riaksearch-admin ringready')\n stdin, stdout, stderr = ssh.exec_command('riak-admin leave')\n stdin, stdout, stderr = ssh.exec_command('riak-admin ringready')\n# if len(stdout) > 0 :\n print((stderr.readlines()))\n # Stop the node\n# stdin, stdout, stderr = ssh.exec_command('/usr/sbin/riaksearch stop')\n stdin, stdout, stderr = ssh.exec_command('riak stop')\n# if len(stdout) > 0 :\n print((stderr.readlines()))\n ssh.close()\n\n def make_hosts (self):\n hosts = open('/tmp/hosts', 'w')\n hosts.write(\"127.0.0.1\\tlocalhost\\n\")\n\n # Write the /etc/hosts file\n for (nodekey,node) in list(self.cluster.items()):\n hosts.write(node.public_dns_name + \"\\t\" + nodekey+\"\\n\")\n \n hosts.close()\n\n # Copy the file to all nodes \n for (oldnodekey,oldnode) in list(self.cluster.items()):\n transport = paramiko.Transport(oldnode.public_dns_name)\n transport.connect(username = 'root', password = 'secretpw') \n transport.open_channel(\"session\", oldnode.public_dns_name, \"localhost\")\n sftp = paramiko.SFTPClient.from_transport(transport)\n sftp.put( \"/tmp/hosts\", \"/etc/hosts\")\n sftp.close()\n\n def rebalance_cluster (self, threshold = 0.1):\n return True","sub_path":"MyTiramola/LwlosTiramola/RiakCluster.py","file_name":"RiakCluster.py","file_ext":"py","file_size_in_byte":11115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"370230210","text":"# pylint: disable=line-too-long\nr\"\"\"Configs for COCO detection using DETR with Sinkhorn as matching algorithm.\n\n\"\"\"\n# pylint: enable=line-too-long\n\nimport copy\nimport ml_collections\n_COCO_TRAIN_SIZE = 118287\nNUM_EPOCHS = 300\n\n\ndef get_config():\n \"\"\"Returns the configuration for COCO detection using DETR.\"\"\"\n config = ml_collections.ConfigDict()\n config.experiment_name = 'coco_detection_detr'\n\n # Dataset.\n config.dataset_name = 'coco_detr_detection'\n config.dataset_configs = ml_collections.ConfigDict()\n config.dataset_configs.prefetch_to_device = 2\n config.dataset_configs.shuffle_buffer_size = 10_000\n # Should be `config.num_queries - 1` because (i) Sinkhorn currently requires\n # square cost matrices; and (ii) an additional empty box is appended inside\n # the model.\n config.dataset_configs.max_boxes = 99\n config.data_dtype_str = 'float32'\n\n # Model.\n config.model_dtype_str = 'float32'\n config.model_name = 'detr'\n config.matcher = 'sinkhorn'\n config.hidden_dim = 256\n config.num_queries = 100\n config.query_emb_size = None # Same as hidden_size.\n config.transformer_num_heads = 8\n config.transformer_num_encoder_layers = 6\n config.transformer_num_decoder_layers = 6\n config.transformer_qkv_dim = 256\n config.transformer_mlp_dim = 2048\n config.transformer_normalize_before = False\n config.backbone_num_filters = 64\n config.backbone_num_layers = 50\n config.dropout_rate = 0.\n config.attention_dropout_rate = 0.1\n\n # Sinkhorn.\n # See https://ott-jax.readthedocs.io/en/latest/notebooks/One_Sinkhorn.html\n # for more insights about the meanings and effects of those parameters.\n config.sinkhorn_epsilon = 1e-3\n # Speeds up convergence using epsilon decay. Start with a value 50 times\n # higher than the target and decay by a factor 0.9 between iterations.\n config.sinkhorn_init = 50\n config.sinkhorn_decay = 0.9\n config.sinkhorn_num_iters = 1000 # Sinkhorn number of iterations.\n config.sinkhorn_threshold = 1e-2 # Reconstruction threshold.\n # Starts using momemtum after after 100 Sinkhorn iterations.\n config.sinkhorn_chg_momentum_from = 100\n config.sinkhorn_num_permutations = 100\n\n # Loss.\n config.aux_loss = True\n config.bbox_loss_coef = 5.0\n config.giou_loss_coef = 2.0\n config.class_loss_coef = 1.0\n config.eos_coef = 0.1\n\n # Training.\n config.trainer_name = 'detr_trainer'\n config.optimizer = 'adam'\n config.optimizer_configs = ml_collections.ConfigDict()\n config.optimizer_configs.weight_decay = 1e-4\n config.optimizer_configs.beta1 = 0.9\n config.optimizer_configs.beta2 = 0.999\n config.max_grad_norm = 0.1\n config.num_training_epochs = NUM_EPOCHS\n config.batch_size = 64\n config.rng_seed = 0\n\n decay_events = {500: 400}\n\n # Learning rate.\n steps_per_epoch = _COCO_TRAIN_SIZE // config.batch_size\n config.lr_configs = ml_collections.ConfigDict()\n config.lr_configs.learning_rate_schedule = 'compound'\n config.lr_configs.factors = 'constant*piecewise_constant'\n config.lr_configs.decay_events = [\n decay_events.get(NUM_EPOCHS, NUM_EPOCHS * 2 // 3) * steps_per_epoch,\n ]\n # Note: this is absolute (not relative):\n config.lr_configs.decay_factors = [.1]\n config.lr_configs.base_learning_rate = 1e-4\n\n # Backbone training configs: optimizer and learning rate.\n config.backbone_training = ml_collections.ConfigDict()\n config.backbone_training.optimizer = copy.deepcopy(config.optimizer)\n config.backbone_training.optimizer_configs = copy.deepcopy(\n config.optimizer_configs)\n config.backbone_training.lr_configs = copy.deepcopy(config.lr_configs)\n config.backbone_training.lr_configs.base_learning_rate = 1e-5\n\n # Pretrained_backbone.\n config.load_pretrained_backbone = True\n config.freeze_backbone_batch_stats = True\n config.pretrained_backbone_configs = ml_collections.ConfigDict()\n # Download pretrained ResNet50 checkpoints from here:\n # https://github.com/google-research/scenic/tree/main/scenic/projects/baselines pylint: disable=line-too-long\n config.init_from.checkpoint_path = 'path_to_checkpoint_of_resnet_50'\n\n # Logging.\n config.write_summary = True # write summary\n config.xprof = True # Profile using xprof\n config.log_summary_steps = 50 # train summary steps\n config.log_large_summary_steps = 1000 # Expensive summary operations freq\n config.checkpoint = True # do checkpointing\n config.checkpoint_steps = steps_per_epoch\n config.debug_train = False # debug mode during training\n config.debug_eval = False # debug mode during eval\n\n return config\n\n\n","sub_path":"scenic/projects/baselines/detr/configs/detr_sinkhorn_config.py","file_name":"detr_sinkhorn_config.py","file_ext":"py","file_size_in_byte":4489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"386747156","text":"# MIT License\n#\n# Copyright (c) 2018\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport numpy as np\nimport cv2\nimport numpy.random as npr\n\nfrom tfmtcnn.utils.IoU import iou\n\nimport tfmtcnn.datasets.constants as datasets_constants\nfrom tfmtcnn.datasets.DatasetFactory import DatasetFactory\nfrom tfmtcnn.utils.convert_to_square import convert_to_square\n\nimport mef\n\n\nclass SimpleFaceDataset(object):\n __positive_parts = datasets_constants.positive_parts\n __part_parts = datasets_constants.partial_parts\n __negative_parts = datasets_constants.negative_parts\n\n def __init__(self, name='SimpleFaceDataset'):\n self._name = name\n self._pos_file = None\n self._part_file = None\n self._neg_file = None\n self._info_file = None\n self._pos_dir = \"\"\n self._part_dir = \"\"\n self._neg_dir = \"\"\n\n # MEF: 20 is a good trade-off. We get the speed with very few samples sacrificed for positives (~1/1000 faces)\n self._base_num_trys = 20 # 5000\n\n # MEF: Use the following metrics to get a reasonable number for base_number_of_attempts.\n self._skipped_negs = 0\n self._skipped_parts = 0\n self._skipped_pos = 0\n self._zero_negs = 0\n self._zero_parts = 0\n self._zero_pos = 0\n\n # MEF: Avoid checking on directory existence for every image write by keeping track...\n self._dirs_set = set()\n\n @classmethod\n def positive_file_name(cls, target_root_dir):\n positive_file_name = os.path.join(target_root_dir, 'positive.txt')\n return positive_file_name\n\n @classmethod\n def part_file_name(cls, target_root_dir):\n part_file_name = os.path.join(target_root_dir, 'part.txt')\n return part_file_name\n\n @classmethod\n def negative_file_name(cls, target_root_dir):\n negative_file_name = os.path.join(target_root_dir, 'negative.txt')\n return negative_file_name\n\n # def is_valid(self):\n # return self._is_valid\n #\n # def data(self):\n # return self._data\n\n @staticmethod\n def read(annotation_image_dir, annotation_file_name, face_dataset_name='WIDERFaceDataset'):\n dataset = None\n face_dataset = DatasetFactory.face_dataset(face_dataset_name)\n if face_dataset.read(annotation_image_dir, annotation_file_name):\n dataset = face_dataset.data()\n\n return dataset\n\n @staticmethod\n def _generated_samples(target_root_dir):\n # MEF: Replace these with a more robust line counter. readlines() generate extra lines in this code on\n # windows due to all the old os.lineseps in there...\n\n # positive_file = open(SimpleFaceDataset.positive_file_name(target_root_dir), 'a+')\n # generated_positive_samples = len(positive_file.readlines())\n # part_file = open(SimpleFaceDataset.part_file_name(target_root_dir), 'a+')\n # generated_part_samples = len(part_file.readlines())\n # negative_file = open(SimpleFaceDataset.negative_file_name(target_root_dir), 'a+')\n # generated_negative_samples = len(negative_file.readlines())\n # negative_file.close()\n # part_file.close()\n # positive_file.close()\n\n try:\n generated_positive_samples = mef.get_line_count(SimpleFaceDataset.positive_file_name(target_root_dir))\n except Exception:\n generated_positive_samples = 0\n\n try:\n generated_part_samples = mef.get_line_count(SimpleFaceDataset.part_file_name(target_root_dir))\n except Exception:\n generated_part_samples = 0\n\n try:\n generated_negative_samples = mef.get_line_count(SimpleFaceDataset.negative_file_name(target_root_dir))\n except Exception:\n generated_negative_samples = 0\n\n return generated_positive_samples, generated_part_samples, generated_negative_samples\n\n def _prep_files(self, target_dir):\n self._pos_dir = os.path.join(target_dir, 'positive')\n self._part_dir = os.path.join(target_dir, 'part')\n self._neg_dir = os.path.join(target_dir, 'negative')\n\n mef.create_dir_if_necessary(self._pos_dir, raise_on_error=True)\n mef.create_dir_if_necessary(self._part_dir, raise_on_error=True)\n mef.create_dir_if_necessary(self._neg_dir, raise_on_error=True)\n\n self._pos_file = open(SimpleFaceDataset.positive_file_name(target_dir), 'a+')\n self._part_file = open(SimpleFaceDataset.part_file_name(target_dir), 'a+')\n self._neg_file = open(SimpleFaceDataset.negative_file_name(target_dir), 'a+')\n self._info_file = open(os.path.join(target_dir, \"info.txt\"), 'a+')\n\n self._skipped_negs = 0\n self._skipped_parts = 0\n self._skipped_pos = 0\n self._zero_negs = 0\n self._zero_parts = 0\n self._zero_pos = 0\n\n def _close_files(self):\n self._pos_file.close()\n self._part_file.close()\n self._neg_file.close()\n self._info_file.close(_)\n self._pos_file = self._part_file = self._neg_file = self._info_file = None\n\n def _make_image_fname(self, root_dir, target_size, counter, prefix, ext):\n \"\"\" Avoids super large directories by putting a max number of files per directory.\n It creates the directory if needed.\n \"\"\"\n max_files_per_dir = 3000\n dirpath = os.path.join(root_dir, f\"{target_size}x{target_size}\", f\"dir{counter // max_files_per_dir}\")\n\n if dirpath not in self._dirs_set:\n mef.create_dir_if_necessary(dirpath)\n self._dirs_set.add(dirpath)\n\n fname = os.path.join(dirpath, f\"{prefix}-{counter}.{ext}\")\n return fname\n\n def _resize_and_save(self, root_dir, image, target_size, counter, prefix):\n fname = self._make_image_fname(root_dir, target_size, counter, prefix, \"jpg\")\n resized = mef.resize_image(image, target_size, target_size)\n cv2.imwrite(fname, resized)\n\n # other_sizes = [x for x in [12, 24, 48] if x != target_size]\n # for size in other_sizes:\n # fn = self._make_image_fname(root_dir, size, counter, prefix, \"jpg\")\n # cv2.imwrite(fn, mef.resize_image(image, size, size))\n\n return fname\n\n def _try_save_rand_neg(self, image_fname, image, image_bboxes, target_size, n_negs_so_far, overlap_bbox=None):\n \"\"\" Generate a random negative crop box and if the IOU meets the criteria, save it.\n If bbox is specified, negatives are picked with some overlap with the box.\n \"\"\"\n imheight, imwidth, _ = image.shape\n cropsize = npr.randint(target_size, min(imwidth, imheight) / 2)\n\n if overlap_bbox is None:\n cx, cy = npr.randint(0, (imwidth - cropsize)), npr.randint(0, (imheight - cropsize))\n else:\n bbwidth = overlap_bbox[2] - overlap_bbox[0] + 1\n bbheight = overlap_bbox[3] - overlap_bbox[1] + 1\n dx = npr.randint(max(-cropsize, -overlap_bbox[0]), bbwidth)\n dy = npr.randint(max(-cropsize, -overlap_bbox[1]), bbheight)\n cx = max(0, overlap_bbox[0] + dx)\n cy = max(0, overlap_bbox[1] + dy)\n\n if cx + cropsize > imwidth and cy + cropsize > imheight:\n return False\n\n cropbox = np.array([cx, cy, cx + cropsize - 1, cy + cropsize - 1])\n maxiou = np.max(iou(cropbox, image_bboxes))\n iou_thresh = datasets_constants.abs_negative_iou if overlap_bbox is None else datasets_constants.negative_iou\n\n if maxiou < iou_thresh:\n cropped = image[cy:cy + cropsize, cx:cx + cropsize, :]\n fname = self._resize_and_save(self._neg_dir, cropped, target_size, n_negs_so_far, \"simple-negative\")\n self._neg_file.write(fname + ' 0\\n')\n # record where it comes from for debugging...\n self._info_file.write(f\"{mef.basename(fname)} <-- {image_fname}: ({cx},{cy}) ({cropsize}x{cropsize})\\n\")\n return True\n\n return False\n\n def _save_rand_negs(self, num_to_save, image_fname, image, image_bboxes, target_size,\n n_negs_so_far, overlap_bbox=None):\n \"\"\" Save the given number of random negative crops to save. \"\"\"\n n_saved = n_trys = 0\n max_trys = self._base_num_trys * num_to_save\n while n_saved < num_to_save and n_trys < max_trys:\n n_trys += 1\n if self._try_save_rand_neg(image_fname, image, image_bboxes, target_size,\n n_negs_so_far + n_saved, overlap_bbox):\n n_saved += 1\n\n # MEF: Use to find a good number of attempts...\n self._zero_negs += 1 if n_saved == 0 else 0\n self._skipped_negs += 1 if n_saved < num_to_save else 0\n return n_saved\n\n def _try_save_rand_pos_or_part(self, image_fname, image, target_size, n_pos_so_far, n_parts_so_far,\n need_pos, need_part, bbox):\n \"\"\" Generate a random crop box and if the IOU meets the criteria, save it as positive or parial.\n Return \"pos\", \"part\", or \"\" if the sample was saved as positive, partial or not saved.\n \"\"\"\n imheight, imwidth, _ = image.shape\n\n # MEF: In practice, you get many situations where\n # the overlap of a square crop box with a rectangular truth box will never meet a given\n # criteria of say, 0.65 IOU. Specifically, the formulas are as follows:\n #\n # iou <= 1 / (2 * sqrt(aspect_ratio) - 1)\n # ==> aspect_ratio <= (((1/iou) + 1) / 2)^2\n #\n # where aspect_ratio is the >= 1 aspect ratio.\n #\n # So, for a 0.65 iou, the max aspect ratio is ~1.61.\n #\n # We pick a rectangular crop box, do the IOU calc, and once\n # we find a good match, we convert the crop box to square.\n # Even then, we will have cases that making the box square will always put the crop box\n # extending beyond image boundaries.\n\n bbwidth, bbheight = bbox[2] - bbox[0] + 1, bbox[3] - bbox[1] + 1\n\n crop_w = npr.randint(int(bbwidth * 0.8), np.ceil(bbwidth * 1.25))\n crop_h = npr.randint(int(bbheight * 0.8), np.ceil(bbheight * 1.25))\n\n dx = npr.randint(-1.0 * bbwidth, +1.0 * bbwidth + 1) * 0.2\n dy = npr.randint(-1.0 * bbheight, +1.0 * bbheight + 1) * 0.2\n\n cx1 = int(max((bbox[0] + bbwidth / 2.0 + dx - crop_w / 2.0), 0))\n cy1 = int(max((bbox[1] + bbheight / 2.0 + dy - crop_h / 2.0), 0))\n cx2, cy2 = cx1 + crop_w - 1, cy1 + crop_h - 1\n\n if cx2 >= imwidth or cy2 >= imheight:\n return \"\"\n\n crop_box = np.array([cx1, cy1, cx2, cy2])\n cx1, cy1, cx2, cy2 = convert_to_square(crop_box.reshape(1, -1))[0] # now convert to square\n\n if cx1 < 0 or cy1 < 0 or cx2 >= imwidth or cy2 >= imheight: # out of bounds?\n return \"\"\n\n iou_amount = iou(crop_box, bbox.reshape(1, -1))\n ret = \"\"\n if (iou_amount >= datasets_constants.positive_iou and need_pos) or \\\n (iou_amount >= datasets_constants.part_iou and need_part):\n cropsize = cx2 - cx1 + 1\n offset_x1, offset_y1 = (bbox[0] - cx1) / cropsize, (bbox[1] - cy1) / cropsize\n offset_x2, offset_y2 = (bbox[2] - cx2) / cropsize, (bbox[3] - cy2) / cropsize\n cropped = image[cy1:cy2 + 1, cx1:cx2 + 1, :]\n\n if iou_amount >= datasets_constants.positive_iou and need_pos:\n fname = self._resize_and_save(self._pos_dir, cropped, target_size, n_pos_so_far, \"simple-positive\")\n self._pos_file.write(f\"{fname} 1 {offset_x1:.2f} {offset_y1:.2f} {offset_x2:.2f} {offset_y2:.2f}\\n\")\n ret = \"pos\"\n else:\n assert need_part and iou_amount >= datasets_constants.part_iou\n fname = self._resize_and_save(self._part_dir, cropped, target_size, n_parts_so_far, \"simple-part\")\n self._part_file.write(f\"{fname} -1 {offset_x1:.2f} {offset_y1:.2f} {offset_x2:.2f} {offset_y2:.2f}\\n\")\n ret = \"part\"\n\n # record where it comes from for debugging...\n self._info_file.write(f\"{mef.basename(fname)} <-- {image_fname}: ({cx1},{cy1}) ({cropsize}x{cropsize})\\n\")\n\n return ret\n\n def _save_rand_pos_and_parts(self, n_pos_to_save, n_parts_to_save, image_fname, image, target_size,\n n_pos_so_far, n_parts_so_far, bbox):\n n_pos_saved = n_parts_saved = n_trys = 0\n max_trys = self._base_num_trys * (n_pos_to_save + n_parts_to_save)\n while (n_pos_saved < n_pos_to_save or n_parts_saved < n_parts_to_save) and n_trys < max_trys:\n n_trys += 1\n ret = self._try_save_rand_pos_or_part(image_fname, image, target_size,\n n_pos_so_far + n_pos_saved, n_parts_so_far + n_parts_saved,\n n_pos_saved < n_pos_to_save, n_parts_saved < n_parts_to_save, bbox)\n if ret == \"pos\":\n n_pos_saved += 1\n elif ret == \"part\":\n n_parts_saved += 1\n\n self._zero_pos += 1 if n_pos_saved == 0 else 0\n self._skipped_pos += 1 if n_pos_saved < n_pos_to_save else 0\n self._zero_parts += 1 if n_parts_saved == 0 else 0\n self._skipped_parts += 1 if n_parts_saved < n_parts_to_save else 0\n return n_pos_saved, n_parts_saved\n\n def generate_simple_samples(self, annotation_image_dir, annotation_file_name, base_number_of_images,\n target_face_size, target_dir):\n dataset = self.read(annotation_image_dir, annotation_file_name)\n if dataset is None:\n return False\n\n self._prep_files(target_dir)\n\n image_fns, bboxes, total_faces = dataset['images'], dataset['bboxes'], dataset['number_of_faces']\n total_images = len(image_fns)\n n_gen_pos, n_gen_parts, n_gen_negs = self._generated_samples(target_dir)\n\n n_remaining_pos = base_number_of_images * datasets_constants.positive_parts - n_gen_pos\n n_remaining_parts = base_number_of_images * datasets_constants.partial_parts - n_gen_parts\n\n total_remaining_negs = base_number_of_images * datasets_constants.negative_parts - n_gen_negs\n n_remaining_negs_overlap = int(total_remaining_negs * datasets_constants.negatives_from_bbox_ratio)\n n_remaining_negs_no_overlap = total_remaining_negs - n_remaining_negs_overlap\n\n n_bboxes_processed = 0\n\n pt = mef.ProgressText(total_faces)\n # pt = mef.ProgressText(n_remaining_pos + n_remaining_parts +\n # n_remaining_negs_overlap + n_remaining_negs_no_overlap)\n for idx, img_fname in enumerate(image_fns):\n # if n_remaining_pos <= 0 and n_remaining_parts <= 0 and n_remaining_negs <= 0:\n # break\n n_img_bboxes = len(bboxes[idx])\n img = cv2.imread(img_fname)\n if img is None:\n print(f\"WARNING: Could not read image file {img_fname}. Skipping...\")\n n_bboxes_processed += n_img_bboxes\n continue\n\n # img_bboxes = np.array(bboxes[idx], dtype=np.float32).reshape(-1, 4)\n img_bboxes = np.array(bboxes[idx], dtype=np.int)\n n_imgs_left = total_images - idx\n n_bboxes_left = total_faces - n_bboxes_processed\n\n # number of positives and partials to make\n n_pos_per_box = int(n_remaining_pos / n_bboxes_left) if n_bboxes_left > 0 else 0\n n_parts_per_box = int(n_remaining_parts / n_bboxes_left) if n_bboxes_left > 0 else 0\n\n # number of negatives to make for this image, with and without overlap. we calculate them separately\n # so that we get an even number of overlap ones per face...\n n_negs_overlap_per_box = n_remaining_negs_overlap / n_bboxes_left if n_bboxes_left > 0 else 0\n n_negs_overlap_this_img = int(n_negs_overlap_per_box * n_img_bboxes)\n n_negs_no_overlap_this_img = int(n_remaining_negs_no_overlap / n_imgs_left)\n\n n_pos_saved = n_parts_saved = n_negs_saved_overlap = 0\n\n # Generate negatives with no overlap\n n_negs_saved = self._save_rand_negs(n_negs_no_overlap_this_img, img_fname, img, img_bboxes,\n target_face_size, n_gen_negs)\n\n # Now go over the labeled boxes and generate the positives, partials and negatives per box\n for bidx, bbox in enumerate(img_bboxes):\n # Generate positives and partials\n pos, parts = self._save_rand_pos_and_parts(n_pos_per_box, n_parts_per_box, img_fname, img,\n target_face_size, n_gen_pos + n_pos_saved,\n n_gen_parts + n_parts_saved, bbox)\n # Generate negatives with overlap\n n_negs_this_box = int(n_negs_overlap_this_img / (n_img_bboxes - bidx))\n negs = self._save_rand_negs(n_negs_this_box, img_fname, img, img_bboxes, target_face_size,\n n_gen_negs + n_negs_saved, bbox)\n n_pos_saved += pos\n n_parts_saved += parts\n n_negs_saved += negs\n n_negs_saved_overlap += negs\n n_negs_overlap_this_img -= negs\n n_bboxes_processed += 1\n pt.update(f\"{n_bboxes_processed}/{total_faces} faces\") # update the progress time and show\n\n n_gen_pos += n_pos_saved\n n_gen_parts += n_parts_saved\n n_gen_negs += n_negs_saved\n n_remaining_pos -= n_pos_saved\n n_remaining_parts -= n_parts_saved\n n_remaining_negs_no_overlap -= (n_negs_saved - n_negs_saved_overlap)\n n_remaining_negs_overlap -= n_negs_saved_overlap\n\n if (idx+1) % 1000 == 0:\n print(f\"\\r{idx+1}/{total_images} images processed - \"\n f\"positives - {n_gen_pos}, partials - {n_gen_parts}, negatives - {n_gen_negs}\")\n # MEF: Use the following metrics to get a reasonable number for base_number_of_attempts.\n # print(f\"zero -ves: {self._zero_negs}, skipped -ves:{self._skipped_negs}\")\n # print(f\"zero +ves: {self._zero_pos}, skipped +ves:{self._skipped_pos}\")\n # print(f\"zero parts: {self._zero_parts}, skipped parts:{self._skipped_parts}\")\n\n return True\n\n def generate_simple_samples0(self, annotation_image_dir, annotation_file_name, base_number_of_images,\n target_face_size, target_root_dir):\n dataset = self._read(annotation_image_dir, annotation_file_name)\n if dataset is None:\n return False\n\n image_file_names = dataset['images']\n ground_truth_boxes = dataset['bboxes']\n number_of_faces = dataset['number_of_faces']\n\n positive_dir = os.path.join(target_root_dir, 'positive')\n part_dir = os.path.join(target_root_dir, 'part')\n negative_dir = os.path.join(target_root_dir, 'negative')\n\n mef.create_dir_if_necessary(positive_dir, raise_on_error=True)\n mef.create_dir_if_necessary(part_dir, raise_on_error=True)\n mef.create_dir_if_necessary(negative_dir, raise_on_error=True)\n\n generated_positive_samples, generated_part_samples, \\\n generated_negative_samples = self._generated_samples(target_root_dir)\n\n positive_file = open(SimpleFaceDataset.positive_file_name(target_root_dir), 'a+')\n part_file = open(SimpleFaceDataset.part_file_name(target_root_dir), 'a+')\n negative_file = open(SimpleFaceDataset.negative_file_name(target_root_dir), 'a+')\n\n negative_samples_per_image_ratio = (SimpleFaceDataset.__negative_parts - 1)\n needed_negative_samples = base_number_of_images - (generated_negative_samples /\n SimpleFaceDataset.__negative_parts)\n needed_base_negative_samples = needed_negative_samples / number_of_faces\n needed_negative_samples_per_image = int(negative_samples_per_image_ratio * needed_base_negative_samples *\n (number_of_faces / len(image_file_names)))\n needed_negative_samples_per_image = max(0, needed_negative_samples_per_image)\n\n needed_negative_samples_per_bounding_box = np.ceil((SimpleFaceDataset.__negative_parts -\n negative_samples_per_image_ratio) *\n needed_base_negative_samples)\n needed_negative_samples_per_bounding_box = max(0, needed_negative_samples_per_bounding_box)\n needed_positive_samples = (base_number_of_images * SimpleFaceDataset.__positive_parts) - \\\n generated_positive_samples\n needed_positive_samples_per_bounding_box = np.ceil(1.0 * needed_positive_samples / number_of_faces)\n needed_positive_samples_per_bounding_box = max(0, needed_positive_samples_per_bounding_box)\n needed_part_samples = (base_number_of_images * SimpleFaceDataset.__part_parts) - generated_part_samples\n needed_part_samples_per_bounding_box = np.ceil(needed_part_samples / number_of_faces)\n needed_part_samples_per_bounding_box = max(0, needed_part_samples_per_bounding_box)\n\n # MEF: 20 is a good trade-off. We get the speed with very few samples sacrificed for positives (~1/1000 faces)\n base_number_of_attempts = 20 # 5000\n current_image_number = 0\n\n # MEF: if you want to resume from an interrupted loop, set this appropriately. Make sure to interrupt at the\n # outer loop to keep things in order!\n skip_count = 0\n pt = mef.ProgressText(len(image_file_names) - skip_count)\n\n # MEF: Use the following metrics to get a reasonable number for base_number_of_attempts.\n skipped_negatives = skipped_partials = skipped_positives = 0\n zero_negatives = zero_partials = zero_positives = 0\n\n for i, image_file_path in enumerate(image_file_names, skip_count):\n bboxes = np.array(ground_truth_boxes[i], dtype=np.float32).reshape(-1, 4)\n current_image = cv2.imread(image_file_path)\n img_height, img_width, _ = current_image.shape\n\n needed_negative_samples = needed_negative_samples_per_image\n maximum_attempts = base_number_of_attempts * needed_negative_samples\n negative_images = number_of_attempts = 0\n while negative_images < needed_negative_samples and number_of_attempts < maximum_attempts:\n number_of_attempts += 1\n crop_size = npr.randint(target_face_size, min(img_width, img_height) / 2)\n nx, ny = npr.randint(0, (img_width - crop_size)), npr.randint(0, (img_height - crop_size))\n crop_box = np.array([nx, ny, nx + crop_size - 1, ny + crop_size - 1])\n current_iou = iou(crop_box, bboxes)\n\n if np.max(current_iou) < DatasetFactory.negative_iou():\n cropped_image = current_image[ny:ny + crop_size, nx:nx + crop_size, :]\n resized_image = mef.resize_image(cropped_image, target_face_size, target_face_size)\n file_path = os.path.join(negative_dir, f\"simple-negative-{generated_negative_samples}.jpg\")\n negative_file.write(file_path + ' 0\\n')\n cv2.imwrite(file_path, resized_image)\n generated_negative_samples += 1\n negative_images += 1\n\n if negative_images == 0:\n zero_negatives += 1\n elif negative_images < needed_negative_samples:\n skipped_negatives += 1\n\n needed_negative_samples = needed_negative_samples_per_bounding_box\n needed_positive_samples = needed_positive_samples_per_bounding_box\n needed_part_samples = needed_part_samples_per_bounding_box\n for bounding_box in bboxes:\n x1, y1, x2, y2 = bounding_box\n if x1 < 0 or y1 < 0:\n continue\n\n bounding_box_width = x2 - x1 + 1\n bounding_box_height = y2 - y1 + 1\n maximum_attempts = base_number_of_attempts * needed_negative_samples\n negative_images = number_of_attempts = 0\n while negative_images < needed_negative_samples and number_of_attempts < maximum_attempts:\n number_of_attempts += 1\n crop_size = npr.randint(target_face_size, min(img_width, img_height) / 2)\n delta_x = npr.randint(max(-1 * crop_size, -1 * x1), bounding_box_width)\n delta_y = npr.randint(max(-1 * crop_size, -1 * y1), bounding_box_height)\n nx1 = int(max(0, x1 + delta_x))\n ny1 = int(max(0, y1 + delta_y))\n if (nx1 + crop_size) > img_width or (ny1 + crop_size) > img_height:\n continue\n\n crop_box = np.array([nx1, ny1, nx1 + crop_size - 1, ny1 + crop_size - 1])\n current_iou = iou(crop_box, bboxes)\n\n if np.max(current_iou) < DatasetFactory.negative_iou():\n cropped_image = current_image[ny1:ny1 + crop_size, nx1:nx1 + crop_size, :]\n resized_image = mef.resize_image(cropped_image, target_face_size, target_face_size)\n file_path = os.path.join(negative_dir, f\"simple-negative-{generated_negative_samples}.jpg\")\n negative_file.write(file_path + ' 0\\n')\n cv2.imwrite(file_path, resized_image)\n generated_negative_samples += 1\n negative_images += 1\n\n if negative_images == 0:\n zero_negatives += 1\n elif negative_images < needed_negative_samples:\n skipped_negatives += 1\n\n maximum_attempts = base_number_of_attempts * (needed_positive_samples + needed_part_samples)\n positive_images = part_images = number_of_attempts = 0\n\n pt2 = mef.ProgressText(needed_positive_samples + needed_part_samples, newline_when_done=False)\n pt.show(clean=True)\n\n def update_progress(pt2_updated):\n \"\"\" Call when short circuting the loop\"\"\"\n pt.update_current_time(show=False)\n\n if number_of_attempts < maximum_attempts * 0.5: # don't be too noisy with the second progress\n return\n\n msg = pt.get_output_string() + f\" - Positives: {positive_images}/{needed_positive_samples}, \" \\\n f\"Partials: {part_images}/{needed_part_samples} {pt.percent_done():4.1f}%\"\n if pt2_updated:\n pt2.update(msg)\n else:\n pt2.update_current_time(msg)\n\n while number_of_attempts < maximum_attempts and \\\n (positive_images < needed_positive_samples or part_images < needed_part_samples):\n number_of_attempts += 1\n # MEF: The following formula is too simple. In practice, you get many situations where\n # the overlap of a square crop box with a rectangular truth box will never meet a given\n # criteria of say, 0.65 IOU. Specifically, the formulas are as follows:\n #\n # iou <= 1 / (2 * sqrt(aspect_ratio) - 1)\n # ==> aspect_ratio <= (((1/iou) + 1) / 2)^2\n #\n # where aspect_ratio is the >= 1 aspect ratio.\n #\n # So, for a 0.65 iou, the max aspect ratio is ~1.61.\n #\n # We modify the algorithm to pick a rectangular crop box, do the IOU calc, and once\n # we find a good match, we convert the crop box to square.\n # Even then, we will have cases that making the box square will always put the crop box\n # extending beyond image boundaries.\n\n # crop_size = npr.randint(int(min(bounding_box_width, bounding_box_height) * 0.8),\n # np.ceil(1.25 * max(bounding_box_width, bounding_box_height)))\n crop_w = npr.randint(int(bounding_box_width * 0.8), np.ceil(bounding_box_width * 1.25))\n crop_h = npr.randint(int(bounding_box_height * 0.8), np.ceil(bounding_box_height * 1.25))\n\n delta_x = npr.randint(-1.0 * bounding_box_width, +1.0 * bounding_box_width + 1) * 0.2\n delta_y = npr.randint(-1.0 * bounding_box_height, +1.0 * bounding_box_height + 1) * 0.2\n\n nx1 = int(max((x1 + bounding_box_width / 2.0 + delta_x - crop_w / 2.0), 0))\n ny1 = int(max((y1 + bounding_box_height / 2.0 + delta_y - crop_h / 2.0), 0))\n nx2, ny2 = nx1 + crop_w - 1, ny1 + crop_h - 1\n\n if nx2 >= img_width or ny2 >= img_height:\n update_progress(False)\n continue\n\n crop_box = np.array([nx1, ny1, nx2, ny2])\n nx1, ny1, nx2, ny2 = convert_to_square(crop_box.reshape(1, -1))[0] # now convert to square\n\n if nx1 < 0 or ny1 < 0 or nx2 >= img_width or ny2 >= img_height: # out of bounds?\n update_progress(False)\n continue\n\n iou_amount = iou(crop_box, bounding_box.reshape(1, -1))\n updated = False\n\n if (iou_amount >= DatasetFactory.part_iou() and part_images < needed_part_samples) or \\\n (iou_amount >= DatasetFactory.positive_iou() and positive_images < needed_positive_samples):\n crop_size = nx2 - nx1 + 1\n offset_x1, offset_y1 = (x1 - nx1) / crop_size, (y1 - ny1) / crop_size\n offset_x2, offset_y2 = (x2 - nx2) / crop_size, (y2 - ny2) / crop_size\n updated = True\n cropped_image = current_image[ny1:ny2+1, nx1:nx2+1, :]\n resized_image = mef.resize_image(cropped_image, target_face_size, target_face_size)\n if iou_amount >= DatasetFactory.positive_iou() and positive_images < needed_positive_samples:\n file_path = os.path.join(positive_dir, f\"simple-positive-{generated_positive_samples}.jpg\")\n positive_file.write(f\"{file_path} 1 {offset_x1:.2f} {offset_y1:.2f} \"\n f\"{offset_x2:.2f} {offset_y2:.2f}\\n\")\n cv2.imwrite(file_path, resized_image)\n generated_positive_samples += 1\n positive_images += 1\n else:\n assert part_images < needed_part_samples and iou_amount >= DatasetFactory.part_iou()\n file_path = os.path.join(part_dir, f\"simple-part-{generated_part_samples}.jpg\")\n part_file.write(f\"{file_path} -1 {offset_x1:.2f} {offset_y1:.2f} \"\n f\"{offset_x2:.2f} {offset_y2:.2f}\\n\")\n cv2.imwrite(file_path, resized_image)\n generated_part_samples += 1\n part_images += 1\n\n update_progress(updated)\n\n if part_images == 0:\n zero_partials += 1\n elif part_images < needed_part_samples:\n skipped_partials += 1\n\n if positive_images == 0:\n zero_positives += 1\n elif positive_images < needed_positive_samples:\n skipped_positives += 1\n\n pt.show(clean=True) # show main progress text\n\n current_image_number += 1\n if current_image_number % 1000 == 0:\n print(f\"\\r{current_image_number}/{len(image_file_names)} done - \"\n f\"positive - {generated_positive_samples}, part - {generated_part_samples}, \"\n f\"negative - {generated_negative_samples}\")\n # MEF: Use the following metrics to get a reasonable number for base_number_of_attempts.\n # print(f\"zero -ves: {zero_negatives}, skipped -ves:{skipped_negatives}\")\n # print(f\"zero +ves: {zero_positives}, skipped +ves:{skipped_positives}\")\n # print(f\"zero parts: {zero_partials}, skipped parts:{skipped_partials}\")\n pt.update()\n\n negative_file.close()\n part_file.close()\n positive_file.close()\n return True\n\n\n","sub_path":"tfmtcnn/datasets/SimpleFaceDataset.py","file_name":"SimpleFaceDataset.py","file_ext":"py","file_size_in_byte":34361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"368968877","text":"# Public API for `reciprocalspaceship.utils`\n__all__ = [\n \"canonicalize_phases\",\n \"get_phase_restrictions\",\n \"to_structurefactor\",\n \"from_structurefactor\",\n \"compute_structurefactor_multiplicity\",\n \"is_centric\",\n \"is_absent\",\n \"apply_to_hkl\",\n \"phase_shift\",\n \"add_rfree\",\n \"copy_rfree\",\n \"compute_dHKL\",\n \"generate_reciprocal_cell\",\n \"hkl_to_asu\",\n \"hkl_to_observed\",\n \"in_asu\",\n \"generate_reciprocal_asu\",\n \"bin_by_percentile\",\n \"ev2angstroms\",\n \"angstroms2ev\",\n \"compute_redundancy\",\n]\n\nfrom .phases import canonicalize_phases, get_phase_restrictions\nfrom .structurefactors import (to_structurefactor,\n from_structurefactor,\n compute_structurefactor_multiplicity,\n is_centric,\n is_absent)\nfrom .symop import apply_to_hkl, phase_shift\nfrom .rfree import add_rfree, copy_rfree\nfrom .cell import compute_dHKL, generate_reciprocal_cell\nfrom .asu import hkl_to_asu, hkl_to_observed, in_asu, generate_reciprocal_asu\nfrom .binning import bin_by_percentile\nfrom .units import ev2angstroms, angstroms2ev\nfrom .stats import compute_redundancy\nfrom .math import angle_between\n","sub_path":"reciprocalspaceship/utils/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"209916621","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jun 1 15:06:50 2018\nConcrete code of 'getting data from first week' start after line 70\n@author: Ismail\n\"\"\"\n\n\n\nimport unicodecsv\nfrom datetime import datetime as dt\n\ndef read_csv(filename):\n with open(filename, 'rb') as f:\n reader = unicodecsv.DictReader(f)\n return list(reader)\n\n\ndef get_unique_data(data):\n unique_students = set()\n for data_point in data:\n unique_students.add(data_point['account_key'])\n return unique_students\n\nenrollments = read_csv('enrollments.csv')\ndaily_engagement = read_csv('daily_engagement.csv')\nproject_submissions = read_csv('project_submissions.csv')\n\n\n#Fixing data type\n#Takes a date as string return a python datetyme object\n#if there is no datetyme returns none\n \ndef parse_date(date):\n if date == '':\n return None\n else:\n return dt.strptime(date, '%Y-%m-%d')\n\n\n#Take an empty string or with number\n#Return int value\n\ndef parse_maybe_int(i):\n if i == '':\n return None\n else:\n return int(i)\n\n#Clean up the data types in the enrollments table\n\nfor enrollment in enrollments:\n enrollment['cancel_date'] = parse_date(enrollment['cancel_date'])\n enrollment['days_to_cancel'] = parse_maybe_int(enrollment['days_to_cancel'])\n enrollment['is_canceled'] = enrollment['is_canceled'] == 'True'\n enrollment['is_udacity'] = enrollment['is_udacity'] == 'True'\n enrollment['join_date'] = parse_date(enrollment['join_date'])\n\n\n#Clean up the data type in engagement table\n \nfor engagement_record in daily_engagement:\n engagement_record['lessons_completed'] = int(float(engagement_record['lessons_completed']))\n engagement_record['num_courses_visited'] = int(float(engagement_record['num_courses_visited']))\n engagement_record['projects_completed'] = int(float(engagement_record['projects_completed']))\n engagement_record['total_minutes_visited'] = float(engagement_record['total_minutes_visited'])\n engagement_record['utc_date'] = parse_date(engagement_record['utc_date'])\n\n#Clean up the data type in the submission table\n\nfor submission in project_submissions:\n submission['completion_date'] = parse_date(submission['completion_date'])\n submission['creation_date'] = parse_date(submission['creation_date'])\n\n\n#daily_engagement = read_csv('daily_engagement.csv')\nfor engagement_record in daily_engagement:\n engagement_record['account_key'] = engagement_record['acct']\n del[engagement_record['acct']]\n \nunique_engagement_students = get_unique_data(daily_engagement)\n\n\nudacity_test_accounts = set()\nfor enrollment in enrollments:\n if enrollment['is_udacity'] == True:\n udacity_test_accounts.add(enrollment['account_key'])\n#print(len(udacity_test_accounts))\n\n#function to remove udacity accounts\n \ndef remove_udacity_accounts(data):\n non_udacity_data = []\n for data_point in data:\n if data_point['account_key'] not in udacity_test_accounts:\n non_udacity_data.append(data_point)\n return non_udacity_data\n\nnon_udacity_enrollments = remove_udacity_accounts(enrollments)\nnon_udacity_engagement = remove_udacity_accounts(daily_engagement)\nnon_udacity_submissions = remove_udacity_accounts(project_submissions)\n\n#print(len(non_udacity_enrollments))\n#print(len(non_udacity_engagement))\n#print(len(non_udacity_submissions))\n\n\npaid_students = {}\n\n#cnt = 0;\nfor enrollment in non_udacity_enrollments:\n if not enrollment['is_canceled'] or enrollment['days_to_cancel'] > 7:\n account_key = enrollment['account_key']\n enrollment_date = enrollment['join_date']\n \n if account_key not in paid_students or enrollment_date > paid_students[account_key]:\n paid_students[account_key] = enrollment_date\n\nprint(len(paid_students))\n#print(cnt)\n\n#Getting data from first week\n \n\n#Takes a student's join date and the date of a specific engagement record\n#and returns True if that engagement record happened within one week\n#of the student joining\ndef within_one_week(join_date, engagement_date):\n time_delta = engagement_date - join_date\n return time_delta.days < 7\n\n#Remove data point corresponds to any student who cancel trial\n\ndef remove_free_trial_cancel(data):\n new_data = []\n for data_point in data:\n if data_point['account_key'] in paid_students:\n new_data.append(data_point)\n return new_data\n\npaid_enrollments = remove_free_trial_cancel(non_udacity_enrollments)\npaid_engagement = remove_free_trial_cancel(non_udacity_engagement)\npaid_submissions = remove_free_trial_cancel(non_udacity_submissions)\n\nprint(len(paid_enrollments))\nprint(len(paid_engagement))\nprint(len(paid_submissions))\n\n #create a list of rows from the engagement table including only rows\n #where the students is one of the paid students we just found\n #the date is within one week of the student's join date\n \npaid_engagement_in_first_week = []\n\nfor engagement_record in paid_engagement:\n account_key = engagement_record['account_key']\n join_date = paid_students[account_key]\n engagement_record_date = engagement_record['utc_date']\n \n if within_one_week(join_date, engagement_record_date):\n paid_engagement_in_first_week.append(engagement_record)\n\nprint(len(paid_engagement_in_first_week))\n\n\n \n\n","sub_path":"Getting_data_from_first_week.py","file_name":"Getting_data_from_first_week.py","file_ext":"py","file_size_in_byte":5279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"293799220","text":"#CHECKED\n#Function Purpose - protects input for integers\n#phrase - (String): line that will be printed to ask for variable\n#lessThan - (int): entered integer will not be less than this number\ndef intInputProtection(phrase,lessThan):\n #ensure an integer is entered - protects against strings and floats\n #ensures no negative numbers are entered\n validInt = False\n negative = False\n while(not validInt or negative):\n validInt = False\n negative = False\n try:\n #Splits the user input into a list of strings,\n #Then converts the that list of strings into a list of integers\n print(phrase)\n entered = int(input())\n if(entered < lessThan):\n print(\"Don't enter invalid numbers!!\")\n negative = True\n except:\n print(\"Invalid input! Enter an integer!\\n\")\n else:\n validInt = True\n return entered\n\n\ndef gen_win_list(n,action_space):\n\n winMatrix = []\n winActionOrder = []\n\n #for loop that will iterate through until the table is complete\n #each iteration will add one to the solution table\n for currentStone in range(n):\n\n #intial state\n if currentStone == 0:\n winMatrix.append(2)\n winActionOrder.append([-1])\n\n else:\n moveFound = False\n action_order = 0\n action_order_matrix = []\n\n #for each possible move in a given state\n for pMove in action_space:\n\n #the move must be legal\n if currentStone >= pMove and winMatrix[currentStone-pMove] == 2:\n action_order_matrix.append(action_order)\n moveFound = True\n\n action_order +=1\n if(moveFound):\n winMatrix.append(1)\n winActionOrder.append(action_order_matrix)\n\n else:\n winMatrix.append(2)\n winActionOrder.append([-1])\n\n\n return winActionOrder","sub_path":"NIM_winTable.py","file_name":"NIM_winTable.py","file_ext":"py","file_size_in_byte":2021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"385931439","text":"#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"\nLogistic regression using MLlib.\n\nThis example requires NumPy (http://www.numpy.org/).\n\"\"\"\nimport sys\n\nfrom pyspark import SparkContext\nfrom pyspark.mllib.regression import LabeledPoint\nfrom pyspark.mllib.classification import LogisticRegressionWithSGD\n\n\ndef parsePoint(line):\n \"\"\"\n Parse a line of text into an MLlib LabeledPoint object.\n \"\"\"\n values = [float(s) for s in line.split(' ')]\n if values[0] == -1: # Convert -1 labels to 0 for MLlib\n values[0] = 0\n return LabeledPoint(values[0], values[1:])\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 3:\n print(\"Usage: logistic_regression \", file=sys.stderr)\n sys.exit(-1)\n sc = SparkContext(appName=\"PythonLR\")\n points = sc.textFile(sys.argv[1]).map(parsePoint)\n iterations = int(sys.argv[2])\n model = LogisticRegressionWithSGD.train(points, iterations)\n print(\"Final weights: \" + str(model.weights))\n print(\"Final intercept: \" + str(model.intercept))\n sc.stop()\n","sub_path":"examples/src/main/python/mllib/logistic_regression.py","file_name":"logistic_regression.py","file_ext":"py","file_size_in_byte":1791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"145770835","text":"import cv2\nimport torch\nimport numpy as np\nfrom Renderer.model import FCN\n\nDecoder = FCN()\nDecoder.load_state_dict(torch.load('../renderer.pkl'))\n\ndef decode(x, canvas): # b * (10 + 3)\n x = x.view(-1, 10 + 3)\n stroke = 1 - Decoder(x[:, :10])\n stroke = stroke.view(-1, 128, 128, 1)\n color_stroke = stroke * x[:, -3:].view(-1, 1, 1, 3)\n stroke = stroke.permute(0, 3, 1, 2)\n color_stroke = color_stroke.permute(0, 3, 1, 2)\n stroke = stroke.view(-1, 5, 1, 128, 128)\n color_stroke = color_stroke.view(-1, 5, 3, 128, 128)\n for i in range(5):\n canvas = canvas * (1 - stroke[:, i]) + color_stroke[:, i]\n return canvas\n\n\ndef normal(x, width):\n return (int)(x * (width - 1) + 0.5)\n\ndef draw(f, width=128):\n x0, y0, x1, y1, x2, y2, z0, z2, w0, w2 = f\n x1 = x0 + (x2 - x0) * x1\n y1 = y0 + (y2 - y0) * y1\n x0 = normal(x0, width * 2)\n x1 = normal(x1, width * 2)\n x2 = normal(x2, width * 2)\n y0 = normal(y0, width * 2)\n y1 = normal(y1, width * 2)\n y2 = normal(y2, width * 2)\n z0 = (int)(1 + z0 * width // 2)\n z2 = (int)(1 + z2 * width // 2)\n canvas = np.zeros([width * 2, width * 2]).astype('float32')\n tmp = 1. / 100\n for i in range(100):\n t = i * tmp\n x = (int)((1-t) * (1-t) * x0 + 2 * t * (1-t) * x1 + t * t * x2)\n y = (int)((1-t) * (1-t) * y0 + 2 * t * (1-t) * y1 + t * t * y2)\n z = (int)((1-t) * z0 + t * z2)\n w = (1-t) * w0 + t * w2\n cv2.circle(canvas, (y, x), z, w, -1)\n return 1 - cv2.resize(canvas, dsize=(width, width))\n","sub_path":"baseline_modelfree/Renderer/stroke_gen.py","file_name":"stroke_gen.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"51364142","text":"#encoding=utf-8\n\nf = open('www_access_20140823.log')\nad ={}\nfor i in f:\n\tarr = i.split(' ')\n\tad[(arr[0],arr[6],arr[8])] = ad.get((arr[0],arr[6],arr[8]),0)+1\n#统计IP、路径、状态、次数\nres_list = [(k[0],k[1],k[2],v) for k,v in ad.items()]\n#生成list\nres_str = '''\n\n\n
\n\t

访问数量前十的用户IP、路径、状态

\n\t\t\n\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\n'''#定义要输入的内容\ntmp = '''\n\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\n'''\n#定义HTML表格\ncount = 0\nfor i in range(len(res_list)-1):\n\tfor j in range(len(res_list)-1-i):\n\t\tif res_list[j][3]>res_list[j+1][3]:\n\t\t\tres_list[j],res_list[j+1] = res_list[j+1],res_list[j]\t\n\tnow_max,pre_max = res_list[-(i+1)],res_list[-i]\n\tif now_max[3]==pre_max[3]:\n\t\tcount = count+1\n\telse:\n\t\tcount = 0\n\tif i >9:\n\t\tbreak\n\tres_str += tmp % (i+1-count,now_max[0],now_max[1],now_max[2],now_max[3])\n#排序取前十,输入到文件内\nres_str +='
NO.IPPathStatusCount
%s%s%s%s%s
\\n
'#完成HTML表格标签\nf = open('four.html','w') #打开写入到HTML文件\nf.write(res_str)\nf.close\n","sub_path":"04/zhangwenbo/web0327.py","file_name":"web0327.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"159656324","text":"# -*- coding: utf-8 -*-\r\nimport tensorflow as tf\r\nfrom tensorflow.python.platform import gfile\r\n\r\n\r\n\r\nwith tf.Session() as persisted_sess:\r\n print(\"load graph\")\r\n with gfile.FastGFile(\"model\\\\frozen_model.pb\",'rb') as f:\r\n graph_def = tf.GraphDef()\r\n graph_def.ParseFromString(f.read())\r\n persisted_sess.graph.as_default()\r\n tf.import_graph_def(graph_def, name='')\r\n writer = tf.summary.FileWriter(\"summary\", graph=persisted_sess.graph)\r\n # Print all operation names\r\n for op in persisted_sess.graph.get_operations():\r\n print(op)\r\n\r\n","sub_path":"pbConvert/readPb.py","file_name":"readPb.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"340996150","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport os\nimport sys\nimport argparse\nsys.path.append(\".\")\nfrom collections import OrderedDict\nfrom tqdm import tqdm\n\nfrom model import flows as fnn\nfrom model.ctnf import CTNF\nfrom utils.metrics_lib import expected_calibration_error_multiclass as ece\nfrom data.data_loader import *\n\nfrom torch.distributions.dirichlet import Dirichlet\nfrom torch.distributions.multivariate_normal import MultivariateNormal\nfrom torch import optim\nfrom torch.nn.utils import clip_grad_norm_\nfrom torch.utils import data\nfrom torchvision import transforms as tvt\nfrom torchvision import datasets as tdatasets\nimport torch.nn.functional as F\n\nfrom utils.torchutils import wasserstein_example\n# Why doesn't this work?\n#from utils.metrics_lib import expected_calibration_error_multiclass as ece\n\nimport warnings\nwarnings.filterwarnings(\"ignore\", category=DeprecationWarning) \n\nparser = argparse.ArgumentParser()\nparser.add_argument('--ood', default = 'svhn', help = 'OOD dataset (svhn, lsun, tiny)')\nparser.add_argument('--train_data_path', default = '/home/jh/Documents/Research/Datasets')\nparser.add_argument('--c_data_path',\n default = '/home/jh/Documents/Research/Datasets/CIFAR-10-C',\n help = 'Corruption data path (CIFAR-10-C)')\nparser.add_argument('--ood_data_path',\n default = '/home/jh/Documents/Research/Datasets/',\n help = 'OOD data path (SVHN, LSUN, Tiny ImageNet)')\nargs = parser.parse_args()\n\n# CIFAR-10 loader\ntrain_loader, valid_loader = get_loader(dataset = 'cifar',\n path = args.train_data_path,\n bsz = 32)\n\n# Three type of corruptions exist (speckle_noise, pixelate, contrast)\ncorruption_loader = get_loader(dataset = 'cifar_c',\n path = args.c_data_path,\n bsz = 500,\n cifar_c_type = 'speckle_noise')\n\n# Three type of OOD exist (svhn, lsun, tiny)\nood_loader = get_loader(dataset = args.ood,\n path = args.ood_data_path,\n bsz = 500)\n\nbase_type = 'dirichlet'\n\nctnf = CTNF(encoder_type = 'resnet20',\n n_class = 10, \n n_flow_blocks = 6, \n n_flow_hidden = 64,\n base_dist = base_type,\n alphas = [7.0, 0.5])\n\nctnf.load_encoder(\"./pretrained_models/cifar_encoder_300.pth\")\nctnf.encoder.eval()\n\n# optimize MAF and SurNorm, respectively.\noptimizer = optim.Adam(ctnf.flows.parameters(), lr = 0.01)\npi_optim = optim.Adam(ctnf.surnorm.parameters(), lr = 0.01)\nscheduler = optim.lr_scheduler.StepLR(optimizer, step_size = 2000, gamma = 0.1)\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\nepochs = 30\neps = 10e-9\nw_adv = True\nthreshold = 300\n\nfor epoch in range(epochs):\n for step, (x, y) in tqdm(enumerate(train_loader)):\n x = x.to(device)\n x.requires_grad = True\n y = y.to(device)\n \n # [Step1] Encoding\n\n with torch.no_grad():\n latents = ctnf.encoder(x)\n\n # [Step2] Foward to Flow \n gamma, sldj = ctnf.flows(latents)\n dirichlet, _ = ctnf.surnorm(gamma) \n\n # [Step3] Optimize pi_{\\phi}(w)\n \n s_preds = ctnf.surnorm.inverse(dirichlet.detach().clone()).squeeze(1)\n s = torch.sum(gamma, dim = 1).detach().clone()\n\n pi_optim.zero_grad()\n l2_loss = torch.mean(torch.square(s_preds - s))\n l2_loss.backward()\n pi_optim.step()\n\n # [Step4] Evaluate negative log-likelihood\n\n dirichlet, logpsz = ctnf.surnorm(gamma)\n base_log_prob = ctnf.log_prob(dirichlet, y)\n nll = -torch.mean(base_log_prob + sldj + logpsz)\n\n # [Step5] Generates W-adv example\n \n if w_adv == True:\n w_img = wasserstein_example(x.detach().clone(), y.detach().clone(),\n lamb = 1.5, max_lr0 = 0.01,\n model = ctnf)\n\n\n if torch.isnan(w_img).any() == True:\n print(\"[DEBUG] NaN value is detected in W_img\")\n sys.exit()\n\n with torch.no_grad():\n w_latents = ctnf.encoder(w_img)\n # [Step5] Increase the entropy of W-adv\n\n w_gamma, w_sldj = ctnf.flows(w_latents)\n w_gamma /= torch.sum(w_gamma, dim = 1, keepdim = True)\n entropy = torch.sum(w_gamma * torch.log(w_gamma + eps), dim = 1)\n entropy = torch.mean(entropy)\n \n loss = nll + 6.0*entropy\n else:\n loss = nll\n\n # [Step6] Optimize flow\n ctnf.flows.zero_grad()\n loss.backward()\n clip_grad_norm_(ctnf.flows.parameters(), 0.5)\n optimizer.step()\n scheduler.step()\n\n if (step+1) % 500 == 0 or step == 1497:\n for param in optimizer.param_groups:\n print(\"Learning Rate: \", param['lr'])\n cnt = 0\n total = 0\n probs = []\n labels = []\n valid_probs = []\n ood_probs = []\n \n for val_batch in valid_loader:\n x = val_batch[0].to(device)\n x.requires_grad = True\n y = val_batch[1].to(device)\n\n with torch.no_grad():\n latents = ctnf.encoder(x)\n \n gamma, sldj = ctnf.flows(latents)\n dirichlet, logpsz = ctnf.surnorm(gamma)\n preds = ctnf.log_prob(dirichlet, sldj + logpsz)\n #preds = prediction(dirichlet, sldj + logpsz, base_type)\n #preds = prediction(gamma, sldj, alphas, p_type, base_dists = base_dist, pi = pi)\n\n preds_idx = torch.max(preds, dim = 1)[1].cuda()\n cnt += sum(y == preds_idx)\n total += y.shape[0]\n \n batch = gamma.shape[0]\n for pred, label in zip(preds, y):\n probs.append(pred.tolist())\n labels.append(label.item())\n \n val_score = cnt / float(total)\n probs = np.asarray(probs)\n labels = np.asarray(labels)\n valid_entropy = -np.sum(probs * np.log(probs + 10e-9), axis = 1)\n print(\"{}th epoch {}th step, \\nValidation Accuracy: {:.3f}, ece: {:.3f}\".format(epoch, step, val_score, ece(np.asarray(probs), np.asarray(labels))))\n\n for i, batch in enumerate(corruption_loader):\n cnt, total = (0, 0)\n probs = []\n labels = []\n x = torch.as_tensor(batch[0], device = device, dtype = torch.float32)\n y = torch.as_tensor(batch[1], device = device, dtype = torch.int64)\n \n with torch.no_grad():\n latents = ctnf.encoder(x)\n\n gamma, sldj = ctnf.flows(latents)\n dirichlet, logpsz = ctnf.surnorm(gamma)\n preds = ctnf.predict(dirichlet, sldj+logpsz)\n\n #preds = prediction(gamma, sldj, alphas, p_type, base_dists = base_dist, pi = pi)\n preds = preds.to(device)\n preds_idx = torch.max(preds, dim = 1)[1]\n \n cnt += sum(y == preds_idx)\n total += y.shape[0]\n\n for pred, label in zip(preds, y):\n probs.append(pred.tolist())\n labels.append(label.item())\n\n val_c_score = cnt / float(total)\n calibration_error = ece(np.asarray(probs), np.asarray(labels))\n print(\"Corruption {} ACC: {:.3f} ECE: {:.3f}\"\\\n .format(i+1, val_c_score, ece(np.asarray(probs), np.asarray(labels))))\n\n \n entropies = []\n for i, batch in enumerate(ood_loader):\n\n x = batch[0].to(device)\n \n with torch.no_grad():\n latents = ctnf.encoder(x)\n\n gamma, sldj = ctnf.flows(latents)\n dirichlet, logpsz = ctnf.surnorm(gamma)\n\n if torch.isnan(gamma).any() == True:\n print(\"[DEBUG] NaN value is detected in svhn_gamma\")\n sys.exit()\n\n preds = ctnf.predict(dirichlet, sldj+logpsz)\n if torch.isnan(preds).any() == True:\n print(\"[DEBUG] NaN value is detected in svhn_preds\")\n sys.exit()\n ood_probs.append(preds)\n preds = preds.to(device)\n entropy = -torch.sum(preds * torch.log(preds + 10e-9), dim = 1)\n entropies.append(entropy)\n\n if i == 10: break\n \n entropies = torch.cat(entropies)\n #valid_entropy_quantile = np.quantile(valid_entropy, [0, 0.25, 0.5, 0.75, 1])\n ood_entropy_quantile = np.quantile(entropies.cpu().detach().numpy(), \n [0, 0.25, 0.5, 0.75, 1])\n if np.isnan(ood_entropy_quantile).any() == True:\n print(\"[DEBUG] NaN Value is detected in ood_entropy\")\n sys.exit()\n #print(\"valid entropy: \", np.quantile(valid_entropy, [0, 0.25, 0.5, 0.75, 1]))\n print(\"ood entropy: \", np.quantile(entropies.cpu().detach().numpy(), [0, 0.25, 0.5, 0.75, 1]))\n torch.save(ctnf.flows.state_dict(), os.path.join(\"./pretrained_models\", \"{}epoch{}step_flows.pth\".format(epoch, step)))\n torch.save(ctnf.surnorm.state_dict(), os.path.join(\"./pretrained_models\", \"{}epoch{}step_surnom.pth\".format(epoch, step)))\n","sub_path":"experiments/cifar_train.py","file_name":"cifar_train.py","file_ext":"py","file_size_in_byte":9690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"67495642","text":"\r\n# coding=utf-8\r\n\r\nimport os\r\nimport sys\r\nimport string \r\nimport argparse\r\nimport random\r\n\r\n#================================================================================ \r\n# 攻速是A下/秒,有%B的概率造成C秒眩晕。新的眩晕会覆盖原来的效果。求眩晕覆盖率。\r\n#================================================================================ \r\ndef debuff_time(apm, prob1, prob2, time1, time2):\r\n _apm = float(apm)\r\n _prob1 = float(prob1)/100\r\n _time1 = float(time1) * 1000\r\n _prob2 = float(prob2)/100\r\n _time2 = float(time2) * 1000\r\n\r\n #private\r\n\r\n #time:ms\r\n _atkTime = 1000 / _apm\r\n _totalTime = 10000*1000\r\n _totalBuffTime = 0\r\n _buffTime = 0\r\n _timer = 0\r\n\r\n # statics\r\n for i in range(_totalTime):\r\n _timer += 1\r\n if _timer >= _atkTime:\r\n _timer = 0\r\n if random.random() <= _prob1:\r\n _buffTime = _time1\r\n\r\n if random.random() <= _prob2:\r\n _buffTime = _time2\r\n \r\n _buffTime -= 1\r\n\r\n if _buffTime > 0:\r\n _totalBuffTime += 1\r\n\r\n # result\r\n result = float(_totalBuffTime)/_totalTime\r\n\r\n # print\r\n print(\" apm: \" + str(apm) + \"\\n prob1: \" + str(prob1) + \"%, buff1 duration: \" + str(time1) + \"s\\n prob2: \" + str(prob2) + \"%, buff2 duration: \" + str(time2) + \"s\\n\")\r\n print(\"coverage rate: \" + str(result) + \"\\n\")\r\n\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument(\"-a\", \"--apm\", help=\"apm\")\r\n parser.add_argument(\"-b1\", \"--probability1\", help=\"probability\")\r\n parser.add_argument(\"-b2\", \"--probability2\", help=\"probability\")\r\n parser.add_argument(\"-c1\", \"--time1\", help=\"buff duration\")\r\n parser.add_argument(\"-c2\", \"--time2\", help=\"buff duration\")\r\n\r\n args = parser.parse_args()\r\n debuff_time(args.apm,args.probability1, args.probability2, args.time1, args.time2)\r\n","sub_path":"DebuffTime2.py","file_name":"DebuffTime2.py","file_ext":"py","file_size_in_byte":1934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"46082583","text":"#!/bin/bash/env Python3\n# -*- coding: utf-8 -*-\n\nimport subprocess \nimport multiprocessing \nimport sys \nimport os \nimport errno \nimport time \nimport datetime \n\n\nnum = 8\n\nthreads = 1\n\nDir_home = os.getcwd()\nDir_result = Dir_home + \"/PM/txt\"\nMemory_sysbench = Dir_result + \"/Memory-sysbench.txt\"\n\n# Benchmark\n\ndef sysbenchMemory(mem_block_size='1K', mem_total_size='10G', filename=Memory_sysbench, cpu=1):\n\n blocksize = \"--memory-block-size=\" + mem_block_size\n totalsize = \"--memory-total-size=\" + mem_total_size\n threads = \"--threads=\" + str(cpu)\n with open(filename, \"a\") as output:\n subprocess.call([\"sysbench\", \"--test=memory\", blocksize, totalsize, threads, \"run\"], stdout=output)\n\ndef appendLine(filename='', text=''):\n with open(filename, \"a\") as f:\n f.write(text)\n\ndef fileoutput(filename=''):\n\n try:\n f = open(filename, 'r')\n except IOError:\n print(\"Error: File not found\")\n else:\n with f:\n print(f.read())\n f.close()\n\ndef main():\n\n # Memory Test\n for i in range(num):\n print(\"Memory Test:\", (i + 1), \"/\", num, \"start\")\n appendLine(Memory_sysbench, \"Memory Test \" + str(i+1) + \" Start: \" + str(datetime.datetime.now()) + \"\\n\")\n sysbenchMemory('1K', '10G', Memory_sysbench, i+1)\n print(\"Memory Test:\", (i + 1), \"/\", num, \"done\")\n appendLine(Memory_sysbench, \"Memory Test \" + str(i+1) + \" End: \" + str(datetime.datetime.now()) + \"\\n\")\n \n # print\n\n fileoutput(Memory_sysbench)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Code/pm/Memory.py","file_name":"Memory.py","file_ext":"py","file_size_in_byte":1637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"552663126","text":"\n\nfrom xai.brain.wordbase.adjectives._courtly import _COURTLY\n\n#calss header\nclass _COURTLIEST(_COURTLY, ):\n\tdef __init__(self,): \n\t\t_COURTLY.__init__(self)\n\t\tself.name = \"COURTLIEST\"\n\t\tself.specie = 'adjectives'\n\t\tself.basic = \"courtly\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/adjectives/_courtliest.py","file_name":"_courtliest.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"44336148","text":"import os\nimport glob\nimport json\nimport oommfodt as oo\nimport discretisedfield as df\n\n\nclass Drive:\n \"\"\"\n Examples\n --------\n Simple import.\n\n >>> from micromagneticdata import Drive\n\n \"\"\"\n def __init__(self, name, number):\n self.name = name\n self.number = number\n self.dirname = os.path.join(name, f'drive-{number}')\n if not os.path.exists(self.dirname):\n raise IOError(f'Drive directory {self.dirname} does not exist.')\n\n @property\n def mif(self):\n miffilename = f'{self.name}.mif'\n with open(os.path.join(self.dirname, miffilename)) as f:\n return f.read()\n\n @property\n def m0(self):\n m0filename = 'm0.omf'\n return df.read(os.path.join(self.dirname, m0filename))\n\n @property\n def dt(self):\n odtfilename = f'{self.name}.odt'\n return oo.read(os.path.join(self.dirname, odtfilename))\n\n @property\n def info(self):\n infofilename = 'info.json'\n with open(os.path.join(self.dirname, infofilename)) as f:\n return json.load(f)\n\n @property\n def step_filenames(self):\n filename = f'{self.name}*.omf'\n filenames = glob.iglob(os.path.join(self.dirname, filename))\n for filename in sorted(filenames):\n yield filename\n\n @property\n def step_number(self):\n return len(list(self.step_filenames))\n\n @property\n def step_fields(self):\n for filename in self.step_filenames:\n yield df.read(filename)\n","sub_path":"micromagneticdata/drive.py","file_name":"drive.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"153635582","text":"#LRU Cache\r\nclass Node:\r\n def __init__(self,key=None,val=None):\r\n self.key_val=(key,val)\r\n #self.val=val\r\n self.prev=None\r\n self.next=None\r\n\r\nclass LRUCache(object):\r\n\r\n def __init__(self, capacity):\r\n \"\"\"\r\n :type capacity: int\r\n \"\"\"\r\n self.head= Node()\r\n self.tail=Node()\r\n self.head.next=self.tail\r\n self.tail.prev=self.head\r\n self.head.prev=None\r\n self.tail.next=None\r\n self.size=capacity\r\n self.map={}\r\n\r\n def get(self, key):\r\n \"\"\"\r\n :type key: int\r\n :rtype: int\r\n \"\"\"\r\n if key in self.map:\r\n node=self.map[key]\r\n self.deletenode(key)\r\n self.addnode_left(node)\r\n return node.key_val[1] # Getting key value if it is present\r\n return -1\r\n\r\n\r\n\r\n def put(self, key, value):\r\n \"\"\"\r\n :type key: int\r\n :type value: int\r\n :rtype: None\r\n \"\"\"\r\n if key in self.map: #if key already present, then we delete it in the duble linked list and create a new one\r\n self.deletenode(key)\r\n elif len(self.map)>=self.size: #if key not present in map but max size of cache reached\r\n node=self.tail.prev\r\n self.deletenode(node.key_val[0])\r\n node=Node(key,value)\r\n self.addnode_left(node)\r\n\r\n def addnode_left(self,node):\r\n self.map[node.key_val[0]]=node\r\n nxt=self.head.next\r\n self.head.next=node\r\n node.prev=self.head\r\n node.next=nxt\r\n nxt.prev=node\r\n\r\n\r\n\r\n def deletenode(self,key):\r\n node=self.map[key]\r\n prev=node.prev\r\n next=node.next\r\n prev.next=next\r\n next.prev=prev\r\n del self.map[key] #del in map as well\r\n","sub_path":"prob_78.py","file_name":"prob_78.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"363447228","text":"#!/usr/bin/env python\n#\n# http://paste.pocoo.org/show/402065/ by Mark McMahon 2011\n#\n\n\"\"\"\nUse pygments to output syntax highlighted PNG files of Python code\n\"\"\"\n\nimport glob\nimport re\nimport sys\nimport os\n\nfrom pygments import highlight\nfrom pygments.lexers import PythonLexer\nfrom pygments.formatters import ImageFormatter\n\nPYGMENTS_STYLE = \"pastie\"\nHIGHLIGHT_COLOR = \"#ffdddd\"\n\n\ndef main():\n highligth_marker = re.compile(\"\\#\\#\\s*$\")\n\n if sys.argv[1:]:\n path = sys.argv[1]\n else:\n path = \".\"\n\n for f in glob.glob(os.path.join(path, \"*.py\")):\n code = open(f).readlines()\n\n # collect the lines to be highlighted\n highlights = []\n for i, line in enumerate(code):\n line = line.rstrip()\n if highligth_marker.search(line):\n code[i] = highligth_marker.sub(\"\", line)\n highlights.append(i + 1)\n else:\n code[i] = line\n\n data = highlight(\n \"\\n\".join(code), PythonLexer(), ImageFormatter(\n font_size=24,\n style=PYGMENTS_STYLE,\n hl_lines=highlights,\n hl_color=HIGHLIGHT_COLOR))\n open(f + '.png', 'wb').write(data)\n\n\nif __name__ == '__main__':\n main()","sub_path":"python2/code_syntax_highlighter.py","file_name":"code_syntax_highlighter.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"423464498","text":"# PyTDMS setup.py\nfrom glob import glob\nfrom os.path import join\nimport os\n#html=glob(\"cTDMS/html/*\")\n\nhtml=[]\nos.chdir(\"cTDMS\")\nfor root, _, files in os.walk(join(\"html\")):\n for file in files:\n html.append(join(root, file))\n\n\n#dlls=glob(\"*.dll\")\n#for f in glob(\"*.lib\"):\n# dlls.append(f)\n#\n#datamodels=[]\n#for root, _, files in os.walk(join(\"DataModels\")):\n# for file in files:\n# datamodels.append(join(root, file))\n\nos.chdir(\"..\")\n \npackage_data=html+[\"README\", \"NI License.rtf\", \"setup.py\"] \n\n\nfrom distutils.core import setup\nsetup(\n name = \"cTDMS\",\n version = \"0.91\",\n packages=[\"cTDMS\"], \n# py_modules = [\"cTDMS\", \"__init__\"], \n package_dir={'cTDMS' : 'cTDMS'},\n package_data={'cTDMS': package_data},\n\n \n description = \"Reading and writing TDM and TDMS files\",\n author = \"Alfred Mechsner\",\n author_email = \"alfred.mechsner@googlemail.com\",\n \n# download_url = \"\",\n keywords = [\"TDM\", \"TDMS\" ],\n classifiers = [\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 2.7\",\n \"Development Status :: 5 - Production/Stable\",\n \"Environment :: Win32 (MS Windows)\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)\",\n \"Operating System :: Microsoft :: Windows\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n \"Topic :: Scientific/Engineering\",\n ],\n long_description = \"\"\"\\\nReading and writing TDM and TDMS files\n\nInterface to National Instruments NILIBDDC library using the Python ctypes library.\nVersion 0.91 for 32bit and 64bit system\n\"\"\"\n)\n","sub_path":"pypi_install_script/cTDMS-0.91.win32/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"206166710","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom django.core.paginator import Paginator, InvalidPage, EmptyPage\nfrom django.core.urlresolvers import reverse\nfrom django.shortcuts import render_to_response\nfrom django.http import HttpResponseRedirect\n\n\nfrom Management.models import *\n\n\ndef main(request):\n\tempresa = Empresa.objects.first()\n\tarrendatario = Arrendatario.objects.all().order_by(\"nombre\")\n\tcampo = Campo.objects.all().order_by(\"hectareas\")\n\tcontrato = Contrato.objects.all().order_by(\"numero\")\n\tpagos = Pago.objects.all().order_by(\"orden\")\n\t\n\tfor p in pagos:\n\t\tpre = int(p.precio)\n\t\tqq = int(p.cantidadquintales)\n\t\tp.total = qq * pre\n\n\tcu=str(empresa.cuit)\n\tpte1=cu[0:2]\n\tpte2=cu[2:10]\n\tpte3=cu[-1]\n\tfinal=pte1+\"-\"+pte2+\"-\"+ pte3\n\tempresa.cuit=final\n\t\n\td = dict(empresa = empresa,arrendatario = arrendatario, usuario = request.user, campo=campo, contrato=contrato, pagos=pagos)\n\tif(request.user != \"root\"):\n\t\treturn render_to_response(\"principal.html\", d)\n\telse:\n\t\treturn render_to_response(\"notfound.html\", dict(usuario = request.user))\n","sub_path":"Management/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"296299007","text":"# -*- coding: utf-8 -*-\n\n__author__ = 'anlun'\n\nimport sys\nimport math\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtCore import *\nfrom TableInfo import *\nfrom PlayerInfo import *\nfrom Table import *\nfrom Turn import *\n\nfrom time import sleep\n\nclass TableGui:\n\tcard_height = 70\n\tcard_width = 50\n\tblind_size = 45\n\n\tinfo_height = 150\n\tinfo_width = 150\n\tname_height = 20\n\n\tcenter_x = 300\n\tcenter_y = 200\n\n\ttable_card_coef = 1.5\n\n\tclass PlayerInfoView:\n\t\tdef __init__(self, player_info, scene, x, y):\n\t\t\tself.__player_info = player_info\n\t\t\tself.__scene = scene\n\t\t\tself.__pos = (x, y)\n\n\t\t\tself.__player_info.add_crl_cards(self)\n\t\t\tself.__player_info.add_crl_many(self)\n\t\t\tself.__player_info.add_crl_blind(self)\n\t\t\tself.__player_info.add_crl_ante(self)\n\t\t\tself.__player_info.add_crl_active_alive(self)\n\n\t\t\tself.__init_player_background()\n\t\t\tself.__init_player_name_view()\n\t\t\tself.__init_hand_card_view()\n\t\t\tself.__init_many_view()\n\t\t\tself.__init_ante_view()\n\t\t\tself.__init_blind_view()\n\n\t\tdef __init_player_background(self):\n\t\t\tx = self.__pos[0]\n\t\t\ty = self.__pos[1]\n\t\t\t# self.__player_background = QGraphicsRectItem(x - 20, y - 20, TableGui.card_width * 3 + 40, TableGui.card_height + 70)\n\t\t\tself.__player_background = QGraphicsRectItem(x, y, TableGui.info_width, TableGui.info_height)\n\n\t\t\tself.__player_background.setBrush(Qt.yellow)\n\t\t\tself.__scene.addItem(self.__player_background)\n\n\t\tdef __init_player_name_view(self):\n\t\t\tx = self.__pos[0]\n\t\t\ty = self.__pos[1]\n\t\t\tself.__name_view = QGraphicsTextItem(self.__player_info.name())\n\t\t\tself.__name_view.setPos(x, y)\n\t\t\tself.__scene.addItem(self.__name_view)\n\n\t\tdef __init_hand_card_view(self):\n\t\t\tx = self.__pos[0] + TableGui.name_height\n\t\t\ty = self.__pos[1] + TableGui.name_height\n\t\t\tself.__hand = self.__player_info.hand_cards()\n\t\t\tself.__hand_pixmaps = []\n\n\t\t\tcur_card_x = x\n\t\t\tfor card in self.__hand:\n\t\t\t\tif not self.__player_info.is_hand_hidden():\n\t\t\t\t\tpicture_path = card.image_path()\n\t\t\t\telse:\n\t\t\t\t\tpicture_path = card.jacket_image_path()\n\n\t\t\t\tpixmap_item = QGraphicsPixmapItem(QPixmap(picture_path).scaledToHeight(TableGui.card_height))\n\t\t\t\tpixmap_item.setPos(cur_card_x, y)\n\t\t\t\tself.__scene.addItem(pixmap_item)\n\t\t\t\tself.__hand_pixmaps.append(pixmap_item)\n\n\t\t\t\tcur_card_x += TableGui.card_width\n\n\t\tdef hand_cards_changed(self):\n\t\t\tself.__hand = self.__player_info.hand_cards()\n\n\t\t\ti = 0\n\t\t\tfor card in self.__hand:\n\t\t\t\tif not self.__player_info.is_hand_hidden():\n\t\t\t\t\tpicture_path = card.image_path()\n\t\t\t\telse:\n\t\t\t\t\tpicture_path = card.jacket_image_path()\n\n\t\t\t\tself.__hand_pixmaps[i].setPixmap(QPixmap(picture_path).scaledToHeight(TableGui.card_height))\n\t\t\t\ti += 1\n\n\n\t\tdef blind_changed(self):\n\t\t\tblind = self.__player_info.blind()\n\n\t\t\tif blind == 0:\n\t\t\t\tself.__blind.setPixmap(QPixmap())\n\t\t\telif blind == 1:\n\t\t\t\tself.__blind.setPixmap(QPixmap('images/littleblind.jpg').scaledToWidth(TableGui.card_width))\n\t\t\telse:\n\t\t\t\tself.__blind.setPixmap(QPixmap('images/bigblind.jpg').scaledToWidth(TableGui.card_width))\n\n\t\tdef ante_changed(self):\n\t\t\tante_text = 'FOLD'\n\t\t\tif not self.__player_info.is_folded():\n\t\t\t\tante = self.__player_info.ante()\n\t\t\t\tante_text = str(ante)\n\t\t\tself.__ante_text.setPlainText('Ante: ' + ante_text)\n\n\t\tdef many_changed(self):\n\t\t\tmany = self.__player_info.many()\n\t\t\tself.__many_text.setPlainText('Many: ' + str(many))\n\n\t\tdef active_alive_changed(self):\n\t\t\tif not self.__player_info.is_alive():\n\t\t\t\tself.__player_background.setBrush(Qt.red)\n\t\t\t\treturn\n\t\t\tif self.__player_info.is_active():\n\t\t\t\tself.__player_background.setBrush(Qt.green)\n\t\t\t\treturn\n\t\t\t\n\t\t\tself.__player_background.setBrush(Qt.yellow)\n\t\t\treturn\n\n\t\tdef __init_many_view(self):\n\t\t\tx = self.__pos[0]\n\t\t\ty = self.__pos[1] + TableGui.name_height\n\t\t\tself.__many_text = QGraphicsTextItem('Many: ' + str(self.__player_info.many()))\n\t\t\tself.__many_text.setPos(x, y + TableGui.card_height)\n\t\t\tself.__scene.addItem(self.__many_text)\n\n\t\tdef __init_ante_view(self):\n\t\t\tx = self.__pos[0]\n\t\t\ty = self.__pos[1] + TableGui.name_height\n\t\t\tself.__ante_text = QGraphicsTextItem('Ante: ' + str(self.__player_info.ante()))\n\t\t\tself.__ante_text.setPos(x, y + TableGui.card_height + TableGui.name_height)\n\t\t\tself.__scene.addItem(self.__ante_text)\n\n\t\tdef __init_blind_view(self):\n\t\t\tx = self.__pos[0]\n\t\t\ty = self.__pos[1] + TableGui.name_height\n\t\t\tself.__blind = QGraphicsPixmapItem(QPixmap())\n\t\t\tif self.__player_info.blind() == 1:\n\t\t\t\tself.__blind = QGraphicsPixmapItem(QPixmap('images/littleblind.jpg').scaledToWidth(TableGui.blind_size))\n\t\t\telif self.__player_info.blind() == 2:\n\t\t\t\tself.__blind = QGraphicsPixmapItem(QPixmap('images/bigblind.jpg').scaledToWidth(TableGui.blind_size))\n\t\t\tself.__blind.setPos(x + 1.8 * TableGui.card_width, y + TableGui.card_height * 1.1)\n\t\t\tself.__scene.addItem(self.__blind)\t\t\n\n\tclass OpenedCardView:\n\t\tdef __init__(self, scene, table_info):\n\t\t\tself.__scene = scene\n\t\t\tself.__table_info = table_info\n\n\t\t\ttable_info.add_crl_opened_cards(self)\n\n\t\t\tself.__card_view = []\n\t\t\tself.__card_view.append(QGraphicsPixmapItem(QPixmap()))\n\t\t\tself.__scene.addItem(self.__card_view[0])\n\t\t\tself.__card_view.append(QGraphicsPixmapItem(QPixmap()))\n\t\t\tself.__scene.addItem(self.__card_view[1])\n\t\t\tself.__card_view.append(QGraphicsPixmapItem(QPixmap()))\n\t\t\tself.__scene.addItem(self.__card_view[2])\n\t\t\tself.__card_view.append(QGraphicsPixmapItem(QPixmap()))\n\t\t\tself.__scene.addItem(self.__card_view[3])\n\t\t\tself.__card_view.append(QGraphicsPixmapItem(QPixmap()))\n\t\t\tself.__scene.addItem(self.__card_view[4])\n\n\t\t\tself.__card_view[0].setPos(TableGui.center_x - TableGui.card_width * TableGui.table_card_coef, TableGui.center_y - TableGui.card_height / 2)\n\t\t\tself.__card_view[1].setPos(TableGui.center_x, TableGui.center_y - TableGui.card_height / 2)\n\t\t\tself.__card_view[2].setPos(TableGui.center_x + TableGui.card_width * TableGui.table_card_coef, TableGui.center_y - TableGui.card_height / 2)\n\t\t\tself.__card_view[3].setPos(TableGui.center_x + TableGui.card_width * 2 * TableGui.table_card_coef, TableGui.center_y - TableGui.card_height / 2)\n\t\t\tself.__card_view[4].setPos(TableGui.center_x + TableGui.card_width * 3 * TableGui.table_card_coef, TableGui.center_y - TableGui.card_height / 2)\n\n\t\t\tself.opened_cards_changed()\n\n\t\tdef opened_cards_changed(self):\n\t\t\t# clear\n\t\t\tfor card_view in self.__card_view:\n\t\t\t\tcard_view.setPixmap(QPixmap())\n\n\t\t\ti = 0\n\t\t\tfor card in self.__table_info.opened_cards():\n\t\t\t\tself.__card_view[i].setPixmap(QPixmap(card.image_path()).scaledToHeight(TableGui.card_height * TableGui.table_card_coef))\n\t\t\t\ti += 1\n\n\tclass BankView:\n\t\tdef __init__(self, scene, table_info):\n\t\t\tself.__scene = scene\n\t\t\tself.__table_info = table_info\n\n\t\t\tself.__table_info.add_crl_bank(self)\n\n\t\t\tself.__bank_text = QGraphicsTextItem('Bank: %d' % table_info.bank())\n\t\t\tself.__bank_text.setPos(TableGui.center_x, TableGui.center_y + TableGui.card_height)\n\t\t\tself.__scene.addItem(self.__bank_text)\n\n\t\tdef bank_changed(self):\n\t\t\tself.__bank_text.setPlainText('Bank: %d' % self.__table_info.bank())\n\n\tclass DecisionBlock:\n\t\tbtn_width = 70\n\t\tbtn_height = 25\n\n\t\tdef __init__(self):\n\t\t\tpass\n\n\t\tdef start(self, scene, type, x, y):\n\t\t\t# type must be 'Call' or 'Check'\n\t\t\tself.__scene = scene\n\t\t\tself.__type = type\n\n\t\t\tself.__call_check_btn = QPushButton(type)\n\t\t\tself.__call_check_btn.setGeometry(x, y, self.btn_width, self.btn_height)\n\t\t\tself.__call_check_btn.setEnabled(False)\n\t\t\tself.__scene.addWidget(self.__call_check_btn)\n\n\t\t\tself.__fold_btn = QPushButton('Fold')\n\t\t\tself.__fold_btn.setGeometry(x, y + self.btn_height, self.btn_width, self.btn_height)\n\t\t\tself.__fold_btn.setEnabled(False)\n\t\t\tself.__scene.addWidget(self.__fold_btn)\n\n\t\t\tself.__raise_btn = QPushButton('Raise:')\n\t\t\tself.__raise_btn.setGeometry(x + self.btn_width, y, self.btn_width, self.btn_height)\n\t\t\tself.__raise_btn.setEnabled(False)\n\t\t\tself.__scene.addWidget(self.__raise_btn)\n\n\t\t\tself.__raise_sum_input = QLineEdit()\n\t\t\tself.__raise_sum_input.setGeometry(x + self.btn_width * 2, y, self.btn_width, self.btn_height)\n\t\t\tself.__raise_sum_input.setEnabled(False)\n\t\t\tself.__scene.addWidget(self.__raise_sum_input)\n\n\t\t\tself.__allin_btn = QPushButton('All-in')\n\t\t\tself.__allin_btn.setGeometry(x + self.btn_width, y + self.btn_height, self.btn_width * 2, self.btn_height)\n\t\t\tself.__allin_btn.setEnabled(False)\n\t\t\tself.__scene.addWidget(self.__allin_btn)\n\n\t\t\tself.__fold_btn.clicked.connect(self.__fold_clicked)\n\t\t\tself.__call_check_btn.clicked.connect(self.__call_check_clicked)\n\t\t\tself.__allin_btn.clicked.connect(self.__allin_clicked)\n\t\t\tself.__raise_btn.clicked.connect(self.__raise_clicked)\n\n\t\tdef __fold_clicked(self):\n\t\t\tself.deactivate(Turn('fold', 0))\n\n\t\tdef __call_check_clicked(self):\n\t\t\tif (self.__player.player_info().many() + self.__player.player_info().ante() >= self.__min_value) and (\n\t\t\t\t\tself.__min_value >= self.__player.player_info().ante()):\n\t\t\t\tself.deactivate(Turn('check or call', self.__min_value))\n\n\t\tdef __allin_clicked(self):\n\t\t\tif self.__player.player_info().many() > 0:\n\t\t\t\tself.deactivate(Turn('allin', self.__player.player_info().many() + self.__player.player_info().ante()))\n\t\t\telse:\n\t\t\t\tmsg_box = QMessageBox()\n\t\t\t\tmsg_box.setText('You have no many!')\n\t\t\t\tmsg_box.exec_()\t\t\t\t\n\n\t\tdef __raise_clicked(self):\n\t\t\ttry:\n\t\t\t\tsum = int(self.__raise_sum_input.text())\n\t\t\t\tif sum >= self.__blind and sum <= self.__player.player_info().many():\n\t\t\t\t\tself.deactivate(Turn('raise', self.__player.player_info().ante() + sum))\n\t\t\t\telse:\n\t\t\t\t\tmsg_box = QMessageBox()\n\t\t\t\t\tmsg_box.setText('You have no many enough to this raise!')\n\t\t\t\t\tmsg_box.exec_()\t\t\t\t\n\n\t\t\texcept ValueError:\n\t\t\t\tmsg_box = QMessageBox()\n\t\t\t\tmsg_box.setText('Not number in the input field!')\n\t\t\t\tmsg_box.exec_()\n\n\t\tdef activate(self, value, blind, player, func_to_call):\n\t\t\tself.__call_check_btn.setEnabled(True)\n\t\t\tself.__fold_btn.setEnabled(True)\n\t\t\tself.__raise_btn.setEnabled(True)\n\t\t\tself.__raise_sum_input.setEnabled(True)\n\t\t\tself.__allin_btn.setEnabled(True)\n\n\t\t\tself.__min_value = value\n\t\t\tself.__blind = blind\n\t\t\tself.__player = player\n\t\t\tself.__func_to_call = func_to_call\n\n\t\tdef deactivate(self, turn_res):\n\t\t\tself.__call_check_btn.setEnabled(False)\n\t\t\tself.__fold_btn.setEnabled(False)\n\t\t\tself.__raise_btn.setEnabled(False)\n\t\t\tself.__raise_sum_input.setEnabled(False)\n\t\t\tself.__allin_btn.setEnabled(False)\n\n\t\t\tself.__func_to_call(turn_res)\n\n\tdef __init__(self, table_info):\n\t\tself.__decision_block = TableGui.DecisionBlock()\n\n\t\tself.__table_info = table_info\n\t\tself.__table = Table(table_info, self)\n\n\tdef decision_block(self):\n\t\treturn self.__decision_block\n\n\tdef start(self):\t\t\n\t\tself.__scene = QGraphicsScene()\n\t\tself.__view = QGraphicsView(self.__scene)\n\t\t\n\t\tself.__table_image = QGraphicsPixmapItem(QPixmap('table.png'))\n\t\tself.__scene.addItem(self.__table_image)\n\n\t\tangle = math.pi * 2 / self.__table_info.player_count()\n\t\tradius_x = 400\n\t\tradius_y = 250\n\t\tcur_angle = math.pi / 2\n\t\tfor player in self.__table_info.players():\n\t\t\tplayer_info_view = TableGui.PlayerInfoView(\n\t\t\t\tplayer\n\t\t\t\t, self.__scene\n\t\t\t\t, TableGui.center_x + radius_x * math.cos(cur_angle)\n\t\t\t\t, TableGui.center_y + radius_y * math.sin(cur_angle)\n\t\t\t\t)\n\t\t\tcur_angle += angle\n\n\t\topened_card_view = TableGui.OpenedCardView(self.__scene, self.__table_info)\n\t\tbank_view = TableGui.BankView(self.__scene, self.__table_info)\n\t\tself.__decision_block.start(self.__scene, 'Call', 300, 320)\n\n\t\tself.__view.show()\n\n\tdef __call__(self):\n\t\tself.__table.round()\n\nif __name__ == '__main__':\n\ttable_info = TableInfo()\n\ta = TableGui(table_info)\n\ta.start()","sub_path":"poker/TableGui.py","file_name":"TableGui.py","file_ext":"py","file_size_in_byte":11501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"67078738","text":"#!/usr/bin/python3\n# -*- coding:utf-8 -*-\n#kivy.require(\"1.19.1\")\nfrom kivy import Config\nConfig.set(\"graphics\", \"multisamples\", \"0\")\nfrom kivy.app import App\n#from kivy.base import runTouchApp\nfrom kivy.lang import Builder\nfrom kivy.properties import ObjectProperty\nfrom kivy.core.audio import SoundLoader\nfrom kivy.clock import Clock\nfrom kivy.graphics import *\nfrom kivy.graphics import Color#, Ellipse, Line, Rectangle\nfrom kivy.uix.widget import Widget\nfrom kivy.uix.image import Image\nfrom kivy.uix.label import Label\nfrom kivy.uix.textinput import TextInput\nfrom kivy.uix.button import Button\nfrom kivy.uix.button import ButtonBehavior\nfrom kivy.uix.checkbox import CheckBox\nfrom kivy.core.window import Window\nfrom kivy.uix.screenmanager import Screen, ScreenManager#, WipeTransition\nfrom kivy.uix.gridlayout import GridLayout\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.stacklayout import StackLayout\nfrom kivy.uix.floatlayout import FloatLayout\nfrom kivy.uix.dropdown import DropDown\nfrom kivy.uix.popup import Popup\nfrom kivy.uix.slider import Slider\nfrom kivy.uix.progressbar import ProgressBar\nfrom kivy.uix.scrollview import ScrollView\nfrom kivy.uix.scatter import Scatter\n#import urllib.request\nimport os, sys\nimport time\nimport random\nimport threading\n#from queue import Queue\n#from multiprocessing import Process\n#from multiprocessing.pool import ThreadPool\n#import multiprocessing\n#from queue import Queue\n#import subprocess\n#import signal\n#from pygame import mixer\nimport pyaudio\nimport wave\n\nimport playsound as pls\nfrom gtts import gTTS\nimport speech_recognition as sr\n\nimport fourth_circle as circle\nimport youtb_converterWAV as yc\nimport songBox_playerPyaudio as sbp\nimport songBox_userlist as sbu\nimport songBox_list as sbl\nimport songBox_singerlist as sbs\nimport songBox_voice as sbv\n\nglobal workingDir,baseDir,mp3Dir,dataDir,userListDir,ignoreFile, winColor, boxColor,textColor,stopColor\nbaseDir = os.getcwd()#os.path.abspath('py_song')#workging 폴더\nmp3Dir = os.path.join(baseDir, \"songBox_list\")#노래 폴더\nfontDir = os.path.join(baseDir, \"songBox_font\")#글자 폴더\nimgDir = os.path.join(baseDir, \"songBox_img\")#그림 폴더\ndataDir = os.path.join(mp3Dir, \"0_file_data\")#데이터목록 csv 저장폴더\nuserListDir = os.path.join(mp3Dir, \"1_dir_userlist\")#userlist 폴더ttsDir = os.path.join(mp3Dir, \"2_tts\")#tts 폴더\nsingerListDir = os.path.join(mp3Dir, \"2_dir_singerlist\")#userlist 폴더\nttsDir = os.path.join(mp3Dir, \"3_tts\")#tts 폴더\nignoreFile = ['ffmpeg','.DS_Store','list_data','0_file_data','1_dir_userlist','2_dir_singerlist','3_tts']#dir 안에 존재해야만하는 파일 but mp3 아닌 파일 목록\n#print(f\"baseDir:{baseDir}\\nmp3Dir:{mp3Dir}\\ndataDir:{dataDir}\\nuserListDir:{userListDir}\\nsingerListDir:{singerListDir}\")\nwinColor =[211/255, 211/255, 211/255, 1]#[189/255,183/255,110/255,1]#[211/255,211/255,211/255,1]#\nboxColor = [188/255, 143/255, 143/255, 1]#[110/255,0/255,0/255,1]#[105/255,105/255,105/255,1]#\ntextColor = [255/255, 255/255, 255/255, 1]\nstopColor = [105/255,105/255,105/255,1]#gold[189/255,183/255,110/255,1]#red[110/255,0/255,0/255,1]\n\nbartextColor =[189/255,183/255,110/255,1]#deepblue+green[30/255,160/255,180/255,1]#grey[105/255,105/255,105/255,1]#red[110/255,0/255,0/255,1]\n\nsoundbar_fontsize=\"22sp\"\nmenu_fontsize=\"20sp\"\ntext_fontsize=\"17sp\"\ntodayFont = f'{fontDir}/NanumPen.otf'\n\nFIXROW = 20\n#=====사용이유:1. playing 비었을때, 오류 막기 2.img버튼클릭시, obj 대신\ntempObj = Label(font_name=todayFont,text='1')\nplaying=[tempObj, ]\ntempLabel=Label(font_name=todayFont,text='ready')\ntempBtn=Button(font_name=todayFont,text='temp')\nBTNnum = 1\n\nget_text=0\nCALL=0\nPOS_CALL=0\nPLAY_CALL=0\n\n#===============volume==========================================================\ndef get_volumeNum(instance,value):\n VOL_TEXT = VOL_BAR.value\n VOL_LABEL.text = str(int(VOL_TEXT))\n VOL_LABEL.texture_update()\n return VOL_TEXT\ndef get_volumeText():\n VOL_TEXT = get_volumeNum(VOL_BAR,VOL_BAR.value)\n return VOL_TEXT\n#===============song pos========================================================\ndef get_posNum(self,obj):\n global CALL, POS_CALL, PLAY_CALL\n\n CALL +=1\n #print(f\"get_posNum:CALL:{CALL},POS_CALL:{POS_CALL}\")\n\n PLAY_TEXT = PLAY_BAR.value\n #print(f\"get_posNum:PLAY_TEXT:{PLAY_TEXT}\")\n\n (RUN_DURATION, run_T) = sbp.get_playtime()\n POS = (PLAY_TEXT* RUN_DURATION) // PLAY_BAR.max\n\n if POS_CALL - PLAY_CALL > 2 or CALL - POS_CALL == 1 or CALL - PLAY_CALL == 1:\n sbp.get_pos(POS)\n # print(f\"move_pos_POS:{POS}\")\n\n POS_CALL = CALL\n\n return PLAY_TEXT\n\nclass Root(BoxLayout):\n def __init__(self, **kwargs):\n super(Root, self).__init__(**kwargs)\n winWidth = 640\n winHeight = 480\n self.spacing = 10\n self.size = (winWidth,winHeight)\n #self.orientation = \"horizontal\"\n #self.pos_hint: {\"x\": .3, \"top\": .9}\n#===============image click시, 동기화=============================================\nclass ImageButton(ButtonBehavior, Image):\n def __init__(self, **kwargs):\n super(ImageButton, self).__init__(**kwargs)\n\n#===============soundbar class==================================================\nclass SoundBarMenu(BoxLayout):\n\n def __init__(self, **kwargs):\n super(SoundBarMenu, self).__init__(**kwargs)\n self.playBarLayout = GridLayout(rows=1,cols=12,size_hint=(1,1),\n padding=[10,10,10,10],spacing=[0,0])\n\n self.add_widget(self.playBarLayout)\n self.drawMylist()\n self.start_newsong()\n\n #==============draw widgets=================================================\n def drawMylist(self):\n global VOL_TEXT, VOL_BAR, VOL_LABEL, PLAY_BTN, PAUSE_BTN, PLAY_BAR, PLAY_TEXT\n\n #==============volume slider============================================\n VOL_BAR = Slider(padding=5,min= 0, max=100, value=30)#size_hint=(0.1,0.1)\n VOL_BAR.size_hint=(0.1,0.1)\n VOL_BAR.value_track=True\n VOL_BAR.value_track_width=\"1sp\"\n VOL_BAR.value_track_color=boxColor\n VOL_BAR.cursor_size=(\"10sp\",\"10sp\")\n VOL_BAR.cursor_image=f'{imgDir}/nothing.png'\n VOL_BAR.background_width = \"10sp\"\n VOL_BAR.sensitivity = \"all\"\n #volume_bar.cursor_disabled_image=\"True\"\n #volume_bar.border_horizontal = stopColor\n VOL_LABEL = Label(font_name=todayFont,text=\"10\",font_size =soundbar_fontsize,size_hint=(0.1,0.1),\n halign='center',valign=\"bottom\",bold=False,italic=False,color=boxColor)\n\n #==============play slider==============================================\n PLAY_BAR = Slider(padding=5,min=0, max=100)#size_hint=(0.1,0.1)\n PLAY_BAR.size_hint=(1,1)\n PLAY_BAR.value_track=True\n PLAY_BAR.value_track_width=\"1sp\"\n PLAY_BAR.value_track_color=boxColor\n PLAY_BAR.cursor_size=(\"5sp\",\"5sp\")\n PLAY_BAR.cursor_image=f'{imgDir}/nothing.png'\n PLAY_BAR.background_width = \"10sp\"\n PLAY_BAR.sensitivity = \"all\"\n\n #=====draw playBar =====================================================\n self.shuffle_BTN = Button(font_name=todayFont,font_size=soundbar_fontsize,text=\"#\",size_hint=(0.1, 0.1),\n background_normal = \"\", background_down = \"\",background_color=[0,0,0,0],color=boxColor)#bartextColor)\n\n self.replay_BTN = Button(font_name=todayFont,font_size=soundbar_fontsize,text=\"@\",size_hint=(0.1, 0.1),\n background_normal = \"\", background_down = \"\",background_color=[0,0,0,0],color=boxColor)#bartextColor)\n\n self.PREV_BTN = Button(font_name=todayFont,font_size=soundbar_fontsize, text=\"<<\",size_hint=(0.1,0.1),\n background_normal = \"\", background_down = \"\",background_color=[0,0,0,0],color=boxColor)#bartextColor)\n\n PLAY_BTN = Button(font_name=todayFont,font_size=soundbar_fontsize,text=\"=\",size_hint=(0.1, 0.1),\n background_normal = \"\", background_down = \"\",background_color=[0,0,0,0],color=boxColor)#bartextColor)\n\n PAUSE_BTN = Button(font_name=todayFont,font_size=soundbar_fontsize,text=\"|||\",size_hint=(0.1,0.1),\n background_normal = \"\", background_down = \"\",background_color=[0,0,0,0],color=boxColor)\n\n self.NEXT_BTN = Button(font_name=todayFont,font_size=soundbar_fontsize,text=\">>\",size_hint=(0.1,0.1),\n background_normal = \"\", background_down = \"\",background_color=[0,0,0,0],color=boxColor)#bartextColor)\n\n self.empty1 = Button(font_name=todayFont,font_size=soundbar_fontsize,text=\"\",size_hint=(0.1,0.1),\n background_normal = \"\", background_color=[0,0,0,0],color=[0,0,0,0])\n\n self.playLabelLayout = GridLayout(rows=2,cols=1,size_hint=(0.5,1),\n padding=[10,10,10,10],spacing=[10,10])\n\n self.playLabel = Label(font_name=todayFont,font_size=soundbar_fontsize,text=\"\",size_hint=(1, 0.5),\n halign='center',valign=\"bottom\",bold=False,italic=False, color=boxColor)#bartextColor)\n\n self.voice_BTN = Button(font_name=todayFont,font_size=soundbar_fontsize,text=\"voice\",size_hint=(0.1, 0.1),\n background_normal = \"\", background_down = \"\",background_color=[0,0,0,0],color=boxColor)#bartextColor)\n\n self.empty2 = Button(font_name=todayFont,font_size=soundbar_fontsize,text=\"\",size_hint=(0.1,0.1),\n background_normal = \"\", background_down = \"\",background_color=[0,0,0,0],color=[0,0,0,0])\n\n #=====call function regularly ==========================================\n Clock.schedule_interval(self.show_playLabel, 0.5)\n Clock.schedule_interval(self.set_volumeNum, 0.5)\n\n Clock.schedule_interval(self.get_playtimeNum, 0.5)\n\n #=====bind function ====================================================\n VOL_BAR.bind(value=get_volumeNum)\n PLAY_BAR.bind(value=get_posNum)\n\n PLAY_BTN.bind(on_press=self.act_PLAYBTN)\n PAUSE_BTN.bind(on_press=self.act_PAUSEBTN)\n\n self.PREV_BTN.bind(on_press=self.act_PREVBTN)\n self.NEXT_BTN.bind(on_press=self.act_NEXTBTN)\n\n self.replay_BTN.bind(on_press=self.replay_song)\n self.shuffle_BTN.bind(on_press=self.shuffle_song)\n\n self.voice_BTN.bind(on_press=self.recognize_voice)\n\n #=====add widget =======================================================\n self.playBarLayout.add_widget(self.PREV_BTN)\n self.playBarLayout.add_widget(PLAY_BTN)\n self.playBarLayout.add_widget(PAUSE_BTN)\n self.playBarLayout.add_widget(self.NEXT_BTN)\n self.playBarLayout.add_widget(self.empty1)\n\n self.playBarLayout.add_widget(self.playLabelLayout)\n self.playLabelLayout.add_widget(PLAY_BAR)\n self.playLabelLayout.add_widget(self.playLabel)\n\n\n self.playBarLayout.add_widget(self.empty2)\n self.playBarLayout.add_widget(self.shuffle_BTN)\n self.playBarLayout.add_widget(self.replay_BTN)\n self.playBarLayout.add_widget(VOL_BAR)\n self.playBarLayout.add_widget(VOL_LABEL)\n self.playBarLayout.add_widget(self.voice_BTN)\n\n #==============volume=======================================================\n def set_volumeNum(self,obj):\n VOL_TEXT = get_volumeText()\n #print(f\"vol_text:{volume_text}\")\n sbp.get_volume(VOL_TEXT/100)\n\n def get_playtimeNum(self,obj):\n global CALL, PLAY_CALL\n\n CALL+=1\n # print(f\"get_playtimeNum:CALL:{CALL}, PLAY_CALL:{PLAY_CALL}\")\n\n (RUN_DURATION, run_T) = sbp.get_playtime()\n run_T = int(run_T)\n RUN_DURATION = int(RUN_DURATION)\n if run_T == 0:\n PLAY_BAR.value = 0\n elif RUN_DURATION == 0:\n PLAY_BAR.value = 0\n elif run_T == RUN_DURATION:\n PLAY_BAR.value = PLAY_BAR.max\n else:\n PLAY_BAR.value = (PLAY_BAR.max * run_T) // RUN_DURATION\n\n PLAY_CALL = CALL\n\n #=============playLabel=====================================================\n def show_playLabel(self,obj):\n playLabelText = sbp.get_playLabel()\n self.playLabel.text = f'{playLabelText}'\n self.playLabel.texture_update()\n\n #=============get background songlist=======================================\n def start_newsong(self):\n global playTitle,playing\n #playTitle = sbp.play_newsong()\n playTitle = sbp.play_newsongRandom()\n #playTitle = sbp.play_songRandom()\n #playTitle = sbp.play_allsong()\n #test = SoundLoader.load(f'{mp3Dir}/test_1.mp3')\n #playTitle = [\"test_1.mp3\",\"test_1.mp3\",\"test_1.mp3\"]\n playing = [tempObj,]\n\n playnum=0\n thread_one = threading.Thread(target=sbp.get_playThread, args=(playTitle,playing,PLAY_BTN,PLAY_BTN,playnum), daemon=True)\n thread_one.start()\n\n #=============shuffle songlist > sbp.shuffle_song > start thread============\n def shuffle_song(self,obj):\n global playTitle,playing\n\n PAUSE_BTN.text = \"|||\"\n PAUSE_BTN.color = boxColor\n\n playTitle = sbp.shuffle_song()\n sbp.get_quit()\n time.sleep(1)\n\n playnum=0\n thread_one = threading.Thread(target=sbp.get_playThread, args=(playTitle,playing,PLAY_BTN,PLAY_BTN,playnum), daemon=True)\n thread_one.start()\n\n #=============push replay > sbp.get_replay==================================\n def replay_song(self,obj):\n\n if self.replay_BTN.text == \"@\":\n self.replay_BTN.text = \"1\"\n replay = 1\n elif self.replay_BTN.text == \"1\":\n self.replay_BTN.text = \"2\"\n replay = 2\n elif self.replay_BTN.text == \"2\":\n self.replay_BTN.text = \"@\"\n replay = 3\n\n return sbp.get_replay(replay)\n\n #============= PLAYBTN > Check class > start thread=========================\n def act_PLAYBTN(self,PLAY_BTN):\n global playTitle,playing\n\n if PLAY_BTN.text == \">\":\n PLAY_BTN.text = \"=\"\n PLAY_BTN.color = boxColor\n\n for i in playing:\n i.color = textColor\n\n if PAUSE_BTN.color == stopColor:\n PAUSE_BTN.color = boxColor\n sbp.get_restart()\n time.sleep(1)\n\n sbp.get_quit()\n print(\"stop song\")\n\n #elif manager.current == \"screen_setting\":\n # manager.screen_setting.playUserlist(PLAY_BTN)\n\n elif manager.current == \"screen_song\":\n manager.screen_song.play_checkedSong()\n\n elif manager.current == \"screen_singer\":\n manager.screen_singer.play_checkedSinger(PLAY_BTN)\n\n else:\n playnum=0\n thread_one = threading.Thread(target=sbp.get_playThread, args=(playTitle,playing,PLAY_BTN,PLAY_BTN,playnum), daemon=True)\n thread_one.start()\n\n #============= PAUSEBTN ====================================================\n def act_PAUSEBTN(self, PAUSE_BTN):\n if PLAY_BTN.text == \">\":\n if PAUSE_BTN.color == stopColor:\n PAUSE_BTN.color = boxColor\n return sbp.get_restart()\n\n if PAUSE_BTN.color == boxColor:\n PAUSE_BTN.color = stopColor\n return sbp.get_pause()\n\n #============= PREVBTN > sbp.get_prev > playnum > start thread==============\n def act_PREVBTN(self, PREV_BTN):\n PAUSE_BTN.color = boxColor\n #self.PREV_BTN.color = stopColor\n #self.PREV_BTN.color = boxColor\n\n playnum = sbp.get_prev()\n sbp.get_quit()\n time.sleep(1)\n\n print(f\"click______playnum:{playnum},playTitle:{playTitle[playnum]}\")\n thread_one = threading.Thread(target=sbp.get_playThread, args=(playTitle,playing,PLAY_BTN,tempBtn,playnum), daemon=True)\n thread_one.start()\n\n #============= PREVBTN > sbp.get_next > playnum > start thread==============\n def act_NEXTBTN(self, NEXT_BTN):\n PAUSE_BTN.color = boxColor\n #self.NEXT_BTN.color = stopColor\n #self.NEXT_BTN.color = boxColor\n\n playnum = sbp.get_next()\n sbp.get_quit()\n time.sleep(1)\n\n print(f\"click______playnum{playnum},playTitle:{playTitle[playnum]}\")\n thread_one = threading.Thread(target=sbp.get_playThread, args=(playTitle,playing,PLAY_BTN,tempBtn,playnum), daemon=True)\n thread_one.start()\n\n \"\"\"\n #============= gTTS test====================================================\n def make_gtts(self, obj):\n tts = gTTS(text=\"Tell me the song title or singer\",lang=\"en\",tld=\"com\")\n tts.save(f\"{mp3Dir}/searhsong.mp3\")\n os.system(f\"open {mp3Dir}/searhsong.mp3\")\n \"\"\"\n #=============voice_BTN > sbp.get_pause > sbv.searchsong_voice > start thread\n #gTTS, speech_recognition test==============================================\n def recognize_voice(self,obj):\n sbp.get_pause()\n res, resmsg = sbv.searchsong_voice()\n\n if res == True:\n playTitle = [resmsg]\n PAUSE_BTN.text = \"|||\"\n PAUSE_BTN.color = boxColor\n playing = [tempObj,]\n playnum=0\n\n sbp.get_restart()\n sbp.get_quit()\n time.sleep(1)\n\n thread_one = threading.Thread(target = sbp.get_playThread, args = (playTitle,playing,PLAY_BTN,tempBtn,playnum), daemon=True)\n thread_one.start()\n\n elif res == False:\n sbp.get_restart()\n\n#===============기본 화면 구성(메뉴)=================================================\nclass UpperMenu(BoxLayout):\n def __init__(self, **kwargs):\n super(UpperMenu, self).__init__(**kwargs)\n\n self.boxLayout = BoxLayout(spacing=10,orientation='vertical')\n self.add_widget(self.boxLayout)\n self.drawMylist()\n\n #=============draw widgets==================================================\n def drawMylist(self):\n\n #=====left side menu 처리================================================\n self.boxLayoutEmptyspace = BoxLayout(size_hint=(1,1),spacing=5,orientation='vertical')\n self.songBoxDrop = DropDown()\n btnText=[\"Main\",\"Song\",\"Singer\",\"Setting\",\"Download\",\"Exit\"]#메뉴이름\n btnDic={}#메뉴버튼\n songBoxBtnText = [\"Playlist\",\"Color\"]#Setting메뉴의 드롭다운 메뉴\n songBoxBtnDic = {}#드롭다운버튼\n\n #=====img_btn 처리=======================================================\n self.img_btn = ImageButton(source=f'{imgDir}/nothing.png')\n self.img_btn.size_hint = (1, 0.2)\n self.img_btn.bind(on_release=self.callSyncSong)#image클릭시,동기화\n self.boxLayout.add_widget(self.img_btn)\n\n #=====메뉴버튼, 드롭다운메뉴버튼 지정===========================================\n for i in range(len(btnText)):\n btn = Button(font_name=todayFont,font_size=menu_fontsize,text=btnText[i], size_hint=(0.7, 0.07), background_normal = \"\", background_color=boxColor,color=textColor)\n btnDic[btnText[i]]=btn\n if btnText[i] == \"Main\":\n btn.bind(on_release=self.show_screen_main)\n if btnText[i] == \"Song\":\n btn.bind(on_release=self.show_screen_song)\n if btnText[i] == \"Singer\":\n btn.bind(on_release=self.show_screen_singer)\n if btnText[i] == \"Download\":\n btn.bind(on_release=self.songBoxPop)\n\n if btnText[i] == \"Setting\":\n for j in range(len(songBoxBtnText)):\n songBoxDropBtn = Button(font_name=todayFont,font_size=menu_fontsize,text=songBoxBtnText[j], size_hint=(0.7,0.07),height=40, size_hint_y=None, background_normal = \"\", background_color=boxColor,color=textColor)\n songBoxBtnDic[songBoxBtnText[j]] = songBoxDropBtn\n songBoxDropBtn.bind(on_release=lambda instance: self.songBoxDrop.select(songBoxDropBtn.text))\n self.songBoxDrop.add_widget(songBoxDropBtn)\n if songBoxBtnText[j] == \"Playlist\":\n songBoxDropBtn.bind(on_release=self.show_screen_setting)\n if songBoxBtnText[j] == \"Color\":\n songBoxDropBtn.bind(on_release=self.colorPop)\n btn.bind(on_release=self.songBoxDrop.open)\n self.songBoxDrop.bind(on_select=lambda instance, x: setattr(songBoxDropBtn, 'text', x))\n\n if btnText[i] == \"Exit\":\n btn.bind(on_release=self.closeAll)\n\n self.boxLayout.add_widget(btn)\n\n self.boxLayout.add_widget(self.boxLayoutEmptyspace)\n\n# def ready_widget(self,obj):\n# print(\"ready\")\n\n #===============앱 정지=======================================================\n def closeAll(self,obj):\n #Fourth_mine_kv2().stop()\n #App().get_running_app().stop()\n songBox_kvPyaudio().get_running_app().stop()\n\n #==============동기화 함수 호출=================================================\n def callSyncSong(self,obj):\n global todayFont\n sbl.sync_song()\n sbs.make_singerDic()\n todayFont = circle.get_randomFont()\n print(f\"todayFont:{todayFont}\")\n\n before_vol = VOL_BAR.value\n before_playbtn_text = PLAY_BTN.text\n\n soundbar.playBarLayout.clear_widgets()\n soundbar.drawMylist()\n\n VOL_BAR.value = before_vol\n PLAY_BTN.text = before_playbtn_text\n if before_playbtn_text == \">\":\n PLAY_BTN.text = \">\"\n PLAY_BTN.color = stopColor\n res = sbp.check_pause()\n if res == True:\n PAUSE_BTN.color = stopColor\n\n manager.screen_main.mainScreen.clear_widgets()\n manager.screen_main.drawMylist()\n\n manager.screen_setting.base1.clear_widgets()\n manager.screen_setting.drawMylist()\n\n manager.screen_song.base.clear_widgets()\n manager.screen_song.drawSonglist()\n\n #manager.screen_song.press_songBTN(tempObj)#songlist 다시그리기\n #manager.current = \"screen_main\"\n\n manager.screen_singer.base1.clear_widgets()\n manager.screen_singer.drawMylist()\n\n #==============side menu btn click -> change screen ========================\n def show_screen_main(self,obj):\n manager.current = \"screen_main\"\n def show_screen_setting(self, obj):\n manager.current = \"screen_setting\"\n def show_screen_song(self,obj):\n manager.current = \"screen_song\"\n def show_screen_singer(self, obj):\n manager.current = \"screen_singer\"\n\n #==============setting_color click -> popup ================================\n def colorPop(self,obj):\n global COLORNUM, COLORTEXT, COLORDIC\n self.colorPopup = Popup(title='',\n size_hint=(0.7, 1), size=(800, 800),auto_dismiss=True,\n title_font='Roboto',title_size=20, title_align='center',\n title_color=textColor,\n separator_height=0.5,\n separator_color=textColor)\n\n COLORTEXT = [\"black\", \"white\", \"gold\",\"red\",\"original\",\"reverse\"]\n COLORDIC = {}\n COLORNUM = len(COLORTEXT)\n\n self.basepop1 = BoxLayout(padding=5,spacing=5,size_hint=(1,1), orientation = 'vertical')\n\n self.layoutpop1_top = GridLayout(rows=1,cols=2,padding=5,spacing=5,size_hint=(1, 0.05))\n self.popText = Label(font_name=todayFont,font_size=menu_fontsize,text = 'Choose the color.',size_hint=(0.9, 0.2),color=textColor)\n self.layoutpop1_top.add_widget(self.popText)\n\n self.layoutpop1_middle = GridLayout(rows=COLORNUM+10,cols=1,padding=5,spacing=5,size_hint=(1, 0.9))\n\n for i in range(COLORNUM+10):\n if i > COLORNUM-1:\n self.colorBtn=Button(font_name=todayFont,font_size=menu_fontsize,text=f\"\",size_hint=(0.1, 0.2), background_normal = \"\", background_color=[0,0,0,0],color=[0,0,0,0])\n else:\n self.colorBtn=Button(font_name=todayFont,font_size=menu_fontsize,text=f\"{COLORTEXT[i]}\",size_hint=(0.1, 0.2), background_normal = \"\", background_color=[0,0,0,0],color=textColor)\n COLORDIC[COLORTEXT[i]] = self.colorBtn\n\n self.colorBtn.bind(on_press = self.color_pressed)\n self.layoutpop1_middle.add_widget(self.colorBtn)\n\n self.basepop1.add_widget(self.layoutpop1_top)\n self.basepop1.add_widget(self.layoutpop1_middle)\n self.colorPopup.add_widget(self.basepop1)\n\n self.colorPopup.open()\n\n #==============self.colorBtn click -> change color =========================\n def color_pressed(self,obj):\n global winColor,boxColor,textColor, stopColor\n\n white = [1,1,1,1]\n palegrey = [213/255, 213/255, 213/255, 1]\n lightgrey = [211/255, 211/255, 211/255, 1]\n middlegrey = [180/255,185/255,185/255,1]\n deepgrey = [105/255,105/255,105/255,1]\n black = [0,0,0,1]\n\n gold = [192/255,183/255,135/255,1]\n lightgold = [1.0, 0.922876498176133, 0.779051589369463, 1.0]\n deepgold = [0.874934861907243, 0.8118927785182486, 0.10942384932659661, 0.6352266805627929]#[189/255,183/255,110/255,1]\n lightpink = [188/255, 143/255, 143/255, 1]\n\n red = [110/255,0/255,0/255,1]\n deepred = [0.2,0.0,0.0,1]\n bluegreen = [30/255,160/255,180/255,1]\n #==============set color ===============================================\n if obj.text == \"black\":\n winColor = black\n textColor = white\n boxColor = middlegrey\n stopColor = deepgrey\n\n elif obj.text == \"white\":\n winColor = white\n textColor =lightgrey\n boxColor = middlegrey\n stopColor = deepgrey\n\n elif obj.text == \"gold\":\n winColor = black\n textColor = white\n boxColor = gold\n stopColor =deepgold\n\n elif obj.text == \"red\":\n winColor = gold\n textColor = white\n boxColor = red\n stopColor = deepred\n\n elif obj.text == \"original\":\n winColor = lightgrey\n textColor = white\n boxColor = lightpink\n stopColor = deepgrey\n\n elif obj.text == \"reverse\":\n winColor = lightpink\n textColor = white\n boxColor = lightgrey\n stopColor = deepgrey\n\n Window.clearcolor = winColor\n\n sbp.set_color(winColor,boxColor,textColor, stopColor)\n time.sleep(1)\n #==============reset widget(remove -> draw) ============================\n\n before_vol = VOL_BAR.value\n before_playbtn_text = PLAY_BTN.text\n\n soundbar.playBarLayout.clear_widgets()\n soundbar.drawMylist()\n\n VOL_BAR.value = before_vol\n PLAY_BTN.text = before_playbtn_text\n if before_playbtn_text == \">\":\n PLAY_BTN.text = \">\"\n PLAY_BTN.color = stopColor\n res = sbp.check_pause()\n if res == True:\n PAUSE_BTN.color = stopColor\n\n upperMenu.boxLayout.clear_widgets()\n upperMenu.drawMylist()\n\n manager.screen_main.mainScreen.clear_widgets()\n manager.screen_main.drawMylist()\n\n #manager.screen_setting.base1.clear_widgets()\n manager.screen_setting.press_settingpageBTN(tempObj)\n\n manager.screen_song.base.clear_widgets()\n manager.screen_song.drawSonglist()\n\n manager.screen_singer.base1.clear_widgets()\n manager.screen_singer.drawMylist()\n\n #=====페이지 번호 바꾸고 난 후, 재생 중인 곡 표시위해서, playing 중인 obj의 곡명 저장\n before_playing = sbp.get_playResult()\n songs = {}\n for i in before_playing:\n tempTitle = i.text.split('.wav')\n tempTitle = tempTitle[0].split('* ')\n\n if len(tempTitle) > 1:\n song = f'{tempTitle[1]}'\n else:\n song = f'{i.text}'\n songs[song] = i\n\n print(f\"playing-song name & obj: {songs}\")\n\n if manager.current == \"screen_setting\":\n for i in range(len(NOWLISTSTEXT)):\n if NOWLISTSTEXT[i][0] in songs.keys():\n NOWLISTSDIC[NOWLISTSTEXT[i][0]].color = stopColor\n playing.append(NOWLISTSDIC[NOWLISTSTEXT[i][0]])\n print(f\"NOWLISTSDIC:{NOWLISTSDIC}\\nstopColor:{stopColor}\")\n\n elif manager.current == \"screen_song\":\n for i in range(len(SONGNOWLISTSTEXT)):\n if SONGNOWLISTSTEXT[i][0][:-4] in songs.keys():\n SONGNOWLISTSDIC[SONGNOWLISTSTEXT[i][0]].color = stopColor\n playing.append(SONGNOWLISTSDIC[SONGNOWLISTSTEXT[i][0]])\n print(f\"SONGNOWLISTSTEXT[i][0][:-4]):{SONGNOWLISTSTEXT[i][0][:-4]}\\nstopColor:{stopColor}\")\n\n elif manager.current == \"screen_singer\":\n for i in range(len(SINGER_NOWLISTSTEXT)):\n if SINGER_NOWLISTSTEXT[i][0] in songs.keys():\n SINGER_NOWLISTSDIC[SINGER_NOWLISTSTEXT[i][0]].color = stopColor\n playing.append(SINGER_NOWLISTSDIC[SINGER_NOWLISTSTEXT[i][0]])\n print(f\"SINGER_NOWLISTSDIC:{SINGER_NOWLISTSDIC},\\nstopColor:{stopColor}\")\n\n self.colorPopup.dismiss()\n\n #==============Screen setting>Download메뉴 클릭시, 팝업창(다운로드, 재생, 삭제)======\n def songBoxPop(self, obj):\n self.songBoxPopup = Popup(title='',\n size_hint=(0.5, 0.4), size=(800, 800),auto_dismiss=True,\n title_font=todayFont,title_size=menu_fontsize, title_align='center',\n title_color=textColor,\n separator_height=0.5,\n separator_color=textColor)\n\n self.lowerContent = StackLayout(orientation=\"lr-tb\",padding=10,spacing=10)\n self.songBoxText=Label(font_name=todayFont,font_size=menu_fontsize,text = 'Write song & singer.',width=40, height=30,size_hint=(1, 0.2),color=textColor)\n self.lowerContent.add_widget(self.songBoxText)\n\n self.lowerContent.add_widget(Label(font_name = todayFont,font_size=menu_fontsize,text='Song?',width=40, height=30,size_hint=(0.2, 0.16),color=textColor))\n self.songText = TextInput(font_name=todayFont,multiline = False,width=40, height=30,size_hint=(0.8, 0.16))\n self.lowerContent.add_widget(self.songText)\n\n self.lowerContent.add_widget(Label(font_name=todayFont,font_size=menu_fontsize,text = 'Singr?',width=40, height=30,size_hint=(0.2, 0.16),color=textColor))\n self.singer = TextInput(font_name=todayFont,multiline = False,width=40, height=30,size_hint=(0.8, 0.16))\n self.lowerContent.add_widget(self.singer)\n\n self.songBoxSubmit = Button(font_name=todayFont,font_size=menu_fontsize,text=\"Download\",width=40, height=30,size_hint=(0.33, 0.16), background_normal = \"\", background_color=boxColor,color=textColor)\n self.songBoxSubmit.bind(on_press = self.press_songBox) #곡다운로드\n self.lowerContent.add_widget(self.songBoxSubmit)\n\n self.songBoxPlay = Button(font_name=todayFont,font_size=menu_fontsize,text=\"Play\",width=40, height=30,size_hint=(0.33, 0.16), background_normal = \"\", background_color=boxColor,color=textColor)\n self.songBoxPlay.bind(on_press = self.press_play) #곡재생\n self.lowerContent.add_widget(self.songBoxPlay)\n\n self.songBoxDelete = Button(font_name=todayFont,font_size=menu_fontsize,text=\"Delete\",width=40, height=30,size_hint=(0.33, 0.16), background_normal = \"\", background_color=boxColor,color=textColor)\n self.songBoxDelete.bind(on_press = self.press_delete) #곡삭제\n self.lowerContent.add_widget(self.songBoxDelete)\n\n self.songBoxPopup.add_widget(self.lowerContent)\n\n self.songBoxPopup.open()\n\n #==============곡다운로드(yc.change_Song유투브크롤링)=============================\n def press_songBox(self,instance):\n print(\"Song:\", self.songText.text,\", Singer:\", self.singer.text)\n self.songBoxPopup.dismiss()\n song = self.songText.text\n singer = self.singer.text\n\n try:\n thread_down = threading.Thread(target = yc.change_Song, args = (song, singer), daemon=True)\n res = thread_down.start()\n print(f'Download_Threading start.')\n\n except Exception as msg:\n self.songBoxPopup.title = f\"{msg}retry.\"\n\n self.songText.text = \"\"\n self.singer.text = \"\"\n\n #==============곡 삭제========================================================\n def press_delete(self,obj):\n #print(\"Song:\", self.songText.text,\"Singer:\", self.singer.text)\n #self.songBoxPopup.dismiss()\n song = f'{self.songText.text}'\n singer = f'{self.singer.text}'\n\n try:\n res = sbl.delete_Song(song, singer)\n if res == False:\n print(\"Can't delete. There is no song.\")\n else:\n print(f'{song}_{singer}.wav deleted')\n except Exception as msg:\n self.songBoxPopup.title = f\"{msg}Retry.\"\n\n self.songText.text = \"\"\n self.singer.text = \"\"\n\n #==============곡 검색 후,재생==================================================\n def press_play(self,obj):\n print(\"Song:\", self.songText.text,\"Singer:\", self.singer.text)\n #self.songBoxPopup.dismiss()\n song = f'{self.songText.text}'\n singer = f'{self.singer.text}'\n self.songBoxPopup.title = 'Write song & singer.'\n global playing\n reSong = song.lower()\n reSinger = singer.lower()\n playTitle = []\n playing = []\n tempBtn = Button(text='')\n\n #=====입력한 곡을 mp3 dir안에서 찾기==========================================\n try:\n for i in os.listdir(f'{mp3Dir}'):\n if i not in ignoreFile:\n newNameDir = i[:-4]\n newNameDir = newNameDir.lower()\n splitNameDir=list(newNameDir.split('_'))\n newSongDir=splitNameDir[0]\n newSingerDir=splitNameDir[1]\n if reSong == newSongDir and reSinger == newSingerDir:\n thisTitle = i\n break\n #=====찾은 thisSong의 재생시간 찾기&로드==================================\n print(thisTitle)\n playTitle.append(thisTitle)\n #=====strat thread==================================================\n sbp.get_quit()\n time.sleep(1)\n\n playnum = 0\n thread_one = threading.Thread(target = sbp.get_playThread, args = (playTitle,playing,tempBtn,tempBtn,playnum), daemon=True)\n thread_one.start()\n\n except Exception as msg:\n self.songBoxPopup.title = f\"{msg}retry.\"\n\n self.songText.text = \"\"\n self.singer.text = \"\"\n\n#==============ScreenMain=======================================================\nclass ScreenMain(Screen):\n def __init__(self, **kwargs):\n super(ScreenMain, self).__init__(**kwargs)\n\n self.name = \"screen_main\"\n\n self.mainScreen = GridLayout(rows=2,cols=1,size_hint = (1,1),padding=[0,0,0,0],spacing=[10,10])\n\n self.add_widget(self.mainScreen)\n self.drawMylist()\n\n #==============draw widgets=================================================\n def drawMylist(self):\n #==============(scroll)playlistlabel====================================\n self.scroll = ScrollView(smooth_scroll_end=10,scroll_type=['bars'],bar_width='3dp', scroll_wheel_distance=100, do_scroll_x = False, do_scroll_y = True)\n self.scroll.bar_color = boxColor\n #self.scroll.size_hint_min = (100,500)\n self.scroll.size=(Window.width, Window.height)\n self.scroll.size_hint=(1, 1)\n #self.scroll.size_hint_y = None\n #self.scroll.padding= 10, 50\n self.labelLayout = GridLayout(cols=1, spacing=10, size_hint=(1, None))#,size_hint_y=None)\n self.labelLayout.bind(minimum_height=self.labelLayout.setter('height'))\n self.scroll.add_widget(self.labelLayout)\n self.timeLabel = Label(text_language='ko_KR',font_name=todayFont,font_size =menu_fontsize,text='',\n halign='center',valign=\"bottom\",bold=False,italic=False,\n size_hint=(1, 1),color=textColor)\n\n self.mainScreen.add_widget(self.scroll)\n self.mainScreen.add_widget(self.timeLabel)\n\n Clock.schedule_interval(self.timeAdd, 0.5)\n Clock.schedule_interval(self.show_playList, 0.5)\n\n #==============draw time > circle.current_time()============================\n def timeAdd(self,obj):\n timeText=circle.current_time()\n self.timeLabel.text = timeText\n self.timeLabel.texture_update()\n\n #==============(scroll)draw playlist > sbp.get_playTitle()==================\n def show_playList(self,obj):\n global playTitle\n playTitle = sbp.get_playTitle()\n self.labelLayout.clear_widgets()\n\n self.emptyLabel = Label(font_name=todayFont,font_size =text_fontsize\n ,size_hint_y=None, height=40,color=[0,0,0,0])\n\n self.titleLabel = Label(text=\"================Playlist===============\",\n font_name=todayFont,font_size =text_fontsize\n ,size_hint_y=None, height=40,color=textColor)\n\n self.labelLayout.add_widget(self.emptyLabel)\n self.labelLayout.add_widget(self.titleLabel)\n\n for i in playTitle:\n title = i.split('.wav')\n self.playLabel = Label(font_name=todayFont,font_size =text_fontsize\n ,size_hint_y=None, height=40,color=textColor)\n self.playLabel.text=f'{title[0]}\\n'\n self.labelLayout.add_widget(self.playLabel)\n\n#==============ScreenSetting(다운로드팝업, userlist관리, 색상)========================\nclass ScreenSetting(Screen):\n def __init__(self, **kwargs):\n super(ScreenSetting, self).__init__(**kwargs)\n self.name = \"screen_setting\"\n\n global ROWNUM, NOWLISTS, NOWLISTSTEXT, NOWLISTSDIC, SETTINGBTNLIST, POPDELBTNLIST\n\n ROWNUM = FIXROW#보여줄 곡 수\n NOWLISTSTEXT = [['']*2 for x in range(ROWNUM)]#저장한위젯저장\n NOWLISTSDIC = {}#저장한위젯호출위해저장\n\n SETTINGBTNLIST = ['']*12#페이지버튼(지정한 목록 15개 초과시)\n POPDELBTNLIST = ['']*12#userlist popup페이지버튼(지정한 목록 15개 초과시)\n\n NOWLISTS ={}\n NOWLISTS = sbu.show_userlist()\n\n self.base1 = BoxLayout(padding=5,spacing=5,size_hint=(1,1), orientation = 'vertical')\n self.add_widget(self.base1)\n\n self.drawMylist()\n\n #==============draw widgets=================================================\n def drawMylist(self):\n #global playList, playing\n NOWLISTS = sbu.show_userlist()#userlist 목록 불러오기\n listNum = len(NOWLISTS)#userlist 개수\n\n self.layout1_top = GridLayout(rows=1,cols=9,padding=5,spacing=5,size_hint=(1, 0.05))\n self.layout1_middle = GridLayout(rows=ROWNUM,cols=9,padding=5,spacing=5,size_hint=(1, 0.9))\n self.layout1_page = GridLayout(rows=1,cols=12,padding=5,spacing=5,size_hint=(0.9, 0.05))\n\n self.base1.add_widget(self.layout1_top)\n self.base1.add_widget(self.layout1_middle)\n self.base1.add_widget(self.layout1_page)\n\n self.titleEmptyLabel1=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\", size_hint=(1, 0.2))\n self.titleEmptyLabel2=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\", size_hint=(1, 0.2))\n self.titleEmptyLabel3=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\", size_hint=(1, 0.2))\n self.topLabel=Label(font_name=todayFont,font_size =menu_fontsize,text ='Playlist',halign=\"left\",valign=\"top\", size_hint=(2, 0.2))#,color=boxColor)\n self.titleEmptyLabel4=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\", size_hint=(1, 0.2))\n self.titleEmptyLabel5=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\", size_hint=(1, 0.2))\n self.editBtn = Button(font_name=todayFont,font_size =menu_fontsize,text=\"+/-\", size_hint=(0.9, 0.03), background_normal = \"\", background_down = \"\",background_color=[0,0,0,0],color=boxColor)\n self.titleEmptyLabel6=Label(font_name=todayFont,text ='',font_size=30,halign=\"left\",valign=\"top\", size_hint=(1, 0.2))\n\n self.editBtn.bind(on_press = self.makeListPop) #userlist 생성&삭제하기위한 팝업창 호출\n\n self.layout1_top.add_widget(self.titleEmptyLabel1)\n self.layout1_top.add_widget(self.titleEmptyLabel2)\n self.layout1_top.add_widget(self.topLabel)\n self.layout1_top.add_widget(self.titleEmptyLabel3)\n self.layout1_top.add_widget(self.titleEmptyLabel4)\n self.layout1_top.add_widget(self.titleEmptyLabel5)\n self.layout1_top.add_widget(self.editBtn)\n self.layout1_top.add_widget(self.titleEmptyLabel6)\n\n for i in range(ROWNUM):#보여줄 목록의 개수만큼 위젯추가\n\n if i <= listNum-1:#초과되지 않는 부분은 보이도록 처리\n\n self.emptyLabel1=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\", width=40, height=30,size_hint=(1, 0.2))\n self.userListBtn=Button(font_name=todayFont,font_size =text_fontsize,text=f'{i+1}. {NOWLISTS[str(i+1)]}', width=10, height=10, size_hint=(0.9, 0.03), background_normal = \"\", background_down = \"\",background_color=[0,0,0,0],color=textColor)\n self.emptyLabel2=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.emptyLabel3=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.emptyLabel4=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.emptyLabel5=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.editBtn = Button(font_name=todayFont,font_size =text_fontsize,text=\"edit\", width=10, height=10, size_hint=(0.9, 0.03), background_normal = \"\",background_color=boxColor,color=textColor)\n self.emptyLabel6=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.emptyLabel7=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n\n NOWLISTSTEXT[i][0] = f'{NOWLISTS[str(i+1)]}'\n NOWLISTSTEXT[i][1] = f'{NOWLISTS[str(i+1)]}+add/sub'\n self.userListBtn.bind(on_press=self.playUserlist)#userlist의 곡 재생을 위한 함수 호출\n self.editBtn.bind(on_press=self.del_userlistSong)#userlist의 곡 삭제를 위한 함수 호출\n NOWLISTSDIC[NOWLISTSTEXT[i][0]]=self.userListBtn\n NOWLISTSDIC[NOWLISTSTEXT[i][1]]=self.editBtn\n\n if i > listNum-1:#userlist 개수가 보여줄목록수(15)보다 작은 경우, 초과되는 부분은 안보이도록 처리\n self.emptyLabel1=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.userListBtn=Button(font_name=todayFont,font_size =text_fontsize,text='',size_hint=(0.9, 0.03), background_normal = \"\", background_down = \"\",background_color=[0,0,0,0],color=[0,0,0,0])\n self.emptyLabel2=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.emptyLabel3=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.emptyLabel4=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.emptyLabel5=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.editBtn = Button(font_name=todayFont,font_size =text_fontsize,text=\"edit\",size_hint=(0.9, 0.03), background_color=[0,0,0,0],color=[0,0,0,0])\n self.emptyLabel6=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.emptyLabel7=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n\n NOWLISTSTEXT[i][0] = f'{i}'\n NOWLISTSTEXT[i][1] = f'{i}+add/sub'\n NOWLISTSDIC[NOWLISTSTEXT[i][0]]=self.userListBtn\n NOWLISTSDIC[NOWLISTSTEXT[i][1]]=self.editBtn\n\n self.layout1_middle.add_widget(self.emptyLabel1)\n self.layout1_middle.add_widget(self.userListBtn)\n self.layout1_middle.add_widget(self.emptyLabel2)\n self.layout1_middle.add_widget(self.emptyLabel3)\n self.layout1_middle.add_widget(self.emptyLabel4)\n self.layout1_middle.add_widget(self.emptyLabel5)\n self.layout1_middle.add_widget(self.emptyLabel6)\n self.layout1_middle.add_widget(self.editBtn)\n self.layout1_middle.add_widget(self.emptyLabel7)\n\n #=====페이지버튼 추가하기 전에 계산============================================\n pageLISTNO = listNum//(ROWNUM) #총userlist수(ex.236) // 한페지화면의userlist수(15) == 총페이지개수(15, 나머지있으면 16)\n lastLISTNO = listNum%(ROWNUM) #총userlist수 % 한페지화면의userlist수(15) == 마지막페이지에보여질userlist수(ex.11) => 총페이지개수(15+나머지=16)\n if lastLISTNO > 0:\n pageLISTNO+=1\n pageSetLISTNO = pageLISTNO // 10 # 총페이지개수 //한레이아웃페이지수(1~10페이지) == 다음 >> 넘기는 횟수와 동일\n lastPageLISTNO = pageLISTNO % 10 #총페이지개수 % 한레이아웃페이지수(1~10페이지) == 마지막에 남은 보여줄 버튼 개수(6)\n\n #=====페이지버튼 추가=======================================================\n if listNum > ROWNUM:\n\n for i in range(len(SETTINGBTNLIST)):\n self.PAGEBTN = Button(font_name=todayFont,font_size =text_fontsize,text=f\"{i}\",size_hint=(0.1, 0.2),background_color=winColor,color=textColor)\n if pageSetLISTNO == 0 and i > lastPageLISTNO:\n self.PAGEBTN.background_color=[0,0,0,0]\n self.PAGEBTN.color=[0,0,0,0]\n else:\n if i == 0:#첫번째인덱스\n self.PAGEBTN.text = \"<<\"\n if i == 11:#마지막인덱스\n self.PAGEBTN.text = \">>\"\n self.PAGEBTN.bind(on_press=self.press_settingpageBTN)#페이지번호 클릭시, 화면리셋 함수 호출\n\n SETTINGBTNLIST[i] = self.PAGEBTN\n self.layout1_page.add_widget(self.PAGEBTN)\n else:\n self.PAGEBTN = Button(font_name=todayFont,font_size=text_fontsize,text=\"1\",size_hint=(0.1, 0.2), background_color=winColor,color=textColor)\n SETTINGBTNLIST[1] = self.PAGEBTN\n\n #==============페이지 번호 클릭시, 해당 화면으로 리셋================================\n def press_settingpageBTN(self, obj):\n global BTNnum\n #=====<<,>>버튼이 클릭되었을 경우에, 보여줄 화면 파악하기 위하여\n BTNnum = obj.text#클릭된 버튼의 text\n nowpageQ = int(SETTINGBTNLIST[1].text)#두번째 버튼의 text(현재페이지세트 파악)\n if nowpageQ > 10:\n nowpageA = ((nowpageQ-1)//10)\n else:\n nowpageA = 0\n\n NOWLISTS = sbu.show_userlist()#userlist 목록 불러오기\n listNum = len(NOWLISTS)\n\n pageLISTNO = listNum//(ROWNUM) #총userlist수(ex.236) // 한페지화면의userlist수(15) == 총페이지개수(15, 나머지있으면 16)\n lastLISTNO = listNum%(ROWNUM) #총userlist수 % 한페지화면의userlist수(15) == 마지막페이지에보여질userlist수(ex.11) => 총페이지개수(15+나머지=16)\n if lastLISTNO > 0:\n pageLISTNO+=1\n pageSetLISTNO = pageLISTNO // 10 # 총페이지개수 //한레이아웃페이지수(1~10페이지) == 다음 >> 넘기는 횟수와 동일\n lastPageLISTNO = pageLISTNO % 10 #총페이지개수 % 한레이아웃페이지수(1~10페이지) == 마지막에 남은 보여줄 버튼 개수(6)\n print(f\"ScreenSetting:: BTNnum:{BTNnum}, pageLISTNO:{pageLISTNO}\")\n\n #=====페이지버튼의 숫자 바꾸기================================================\n if BTNnum == \"<<\":\n if nowpageA != 0:\n for i in range(1,len(SETTINGBTNLIST)):\n if nowpageA != \"1\": #1-10은 \"<<\"버튼은 작동 안하기에\n SETTINGBTNLIST[i].text = str((nowpageA-1)*10+i)\n SETTINGBTNLIST[i].background_color=winColor\n SETTINGBTNLIST[i].color=textColor\n if i == 11:\n SETTINGBTNLIST[i].text = \">>\"\n SETTINGBTNLIST[i].background_color=winColor\n SETTINGBTNLIST[i].color=textColor\n endIndex = int(SETTINGBTNLIST[1].text)*FIXROW\n elif BTNnum == \">>\":\n if pageSetLISTNO == nowpageA+1:#마지막페이지세트일경우,userlist개수의 페이지번호까지만 보여주기\n #print(f\"BTN set: pageSetNO{pageSetLISTNO},click nowpageA{nowpageA}\")\n for i in range(1,len(SETTINGBTNLIST)):\n SETTINGBTNLIST[i].text = str((nowpageA+1)*10+i)#페이지버튼의 번호바꾸기\n if i > lastPageLISTNO:#마지막페이지세트일 경우, 남은 페이지번호까지만 화면에 보여주기\n SETTINGBTNLIST[i].background_color=[0,0,0,0]\n SETTINGBTNLIST[i].color=[0,0,0,0]\n else:#페이지버튼의 번호바꾸기\n for i in range(1,len(SETTINGBTNLIST)):\n SETTINGBTNLIST[i].text = str((nowpageA+1)*10+i)\n SETTINGBTNLIST[i].background_color=winColor\n SETTINGBTNLIST[i].color=textColor\n if i == 11:#\">>\" 바뀌지 않도로\n SETTINGBTNLIST[i].text = \">>\"\n SETTINGBTNLIST[i].background_color=winColor\n SETTINGBTNLIST[i].color=textColor\n endIndex = int(SETTINGBTNLIST[1].text)*FIXROW\n else:\n endIndex = int(BTNnum)*FIXROW\n startIndex = endIndex - (FIXROW-1)\n\n #=====화면 리셋===========================================================\n count = 0\n self.layout1_middle.clear_widgets()\n for i in range(startIndex,endIndex+1):#그때그때 인덱스를 지정, 보여줄 화면\n if str(BTNnum) == str(pageLISTNO) and lastLISTNO != 0:\n sub = (FIXROW-lastLISTNO)\n overIndex = endIndex-sub\n if i > overIndex:#마지막페이지의 userlist dir 수보다 i 가 크면, 위젯을 안보이도록 처리\n self.emptyLabel1=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.userListBtn=Button(font_name=todayFont,font_size =text_fontsize,text=f'',size_hint=(0.9, 0.03), background_normal = \"\", background_down = \"\",background_color=[0,0,0,0],color=[0,0,0,0])\n self.emptyLabel2=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.emptyLabel3=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.emptyLabel4=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.emptyLabel5=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.editBtn = Button(font_name=todayFont,font_size =text_fontsize,text=\"edit\",size_hint=(0.9, 0.03), background_normal = \"\", background_color=[0,0,0,0],color=[0,0,0,0])\n self.emptyLabel6=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.emptyLabel7=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n\n else:#NOWLISTS의 인덱스가 i임을 유의\n self.emptyLabel1=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.userListBtn=Button(font_name=todayFont,font_size =text_fontsize,text=f'{i}. {NOWLISTS[str(i)]}',size_hint=(0.9, 0.03), background_normal = \"\", background_down = \"\",background_color=[0,0,0,0],color=textColor)\n self.emptyLabel2=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.emptyLabel3=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.emptyLabel4=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.emptyLabel5=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.editBtn = Button(font_name=todayFont,font_size =text_fontsize,text=\"edit\",size_hint=(0.9, 0.03), background_normal = \"\", background_color=boxColor,color=textColor)\n self.emptyLabel6=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.emptyLabel7=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n\n self.userListBtn.bind(on_press=self.playUserlist)#userlist의 곡 재생을 위한 함수 호출\n self.editBtn.bind(on_press=self.del_userlistSong)#userlist의 곡 삭제를 위한 함수 호출\n NOWLISTSTEXT[count][0] = f'{NOWLISTS[str(i)]}'#userlist 이름, obj 인덱스는 count 임을 유의\n NOWLISTSTEXT[count][1] = f'{NOWLISTS[str(i)]}+add/sub'\n NOWLISTSDIC[NOWLISTSTEXT[count][0]]=self.userListBtn\n NOWLISTSDIC[NOWLISTSTEXT[count][1]]=self.editBtn\n\n else:\n self.emptyLabel1=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.userListBtn=Button(font_name=todayFont,font_size =text_fontsize,text=f'{i}. {NOWLISTS[str(i)]}',size_hint=(0.9, 0.03), background_normal = \"\", background_down = \"\",background_color=[0,0,0,0],color=textColor)\n self.emptyLabel2=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.emptyLabel3=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.emptyLabel4=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.emptyLabel5=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.editBtn = Button(font_name=todayFont,font_size =text_fontsize,text=\"edit\",size_hint=(0.9, 0.03), background_normal = \"\", background_color=boxColor,color=textColor)\n self.emptyLabel6=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.emptyLabel7=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n\n self.userListBtn.bind(on_press=self.playUserlist)#userlist의 곡 재생을 위한 함수 호출\n self.editBtn.bind(on_press=self.del_userlistSong)#userlist의 곡 삭제를 위한 함수 호출\n NOWLISTSTEXT[count][0] = f'{NOWLISTS[str(i)]}'\n NOWLISTSTEXT[count][1] = f'{NOWLISTS[str(i)]}+add/sub'\n NOWLISTSDIC[NOWLISTSTEXT[count][0]]=self.userListBtn\n NOWLISTSDIC[NOWLISTSTEXT[count][1]]=self.editBtn\n\n self.layout1_middle.add_widget(self.emptyLabel1)\n self.layout1_middle.add_widget(self.userListBtn)\n self.layout1_middle.add_widget(self.emptyLabel2)\n self.layout1_middle.add_widget(self.emptyLabel3)\n self.layout1_middle.add_widget(self.emptyLabel4)\n self.layout1_middle.add_widget(self.emptyLabel5)\n self.layout1_middle.add_widget(self.emptyLabel6)\n self.layout1_middle.add_widget(self.editBtn)\n self.layout1_middle.add_widget(self.emptyLabel7)\n count+=1\n #=====페이지 번호 바꾸고 난 후, 재생 중인 곡 표시위해서, playing 중인 obj의 곡명 저장==\n playing = sbp.get_playResult()#play 재생목록이 끝까지 완료된 경우, playing 안의 obj 비우기위해(버튼을 원래색으로 바꾸기)\n names = {}\n for i in playing:\n name = i.text\n names[name] = i\n print(f\"userlist_playing-listname & obj: {names}\")\n #=====페이지 번호 바뀌어도, 재생 중인 곡 표시 & stop하면 작동하도록, 바뀐 obj를 playing에 저장\n for i in NOWLISTS:\n title = f'{i}. {NOWLISTS[i]}'\n if title in names.keys():\n NOWLISTSDIC[NOWLISTS[i]].color = stopColor\n playing.append(NOWLISTSDIC[NOWLISTS[i]])\n print(f\"stop:{NOWLISTS[i]}\")\n\n #==============userlist dir에 들어있는 곡 선택 삭제 ==============================\n def del_userlistSong(self, obj):\n global DELROWNUM, DELLISTSTEXT, DELLISTSDIC, DELLISTS, CHECKEDONEUSERLIST, CHECKEDONEUSERSONG\n\n DELROWNUM = FIXROW\n DELLISTSTEXT=[['']*2 for x in range(DELROWNUM)]\n DELLISTSDIC={}\n CHECKEDONEUSERLIST = \"\"\n CHECKEDONEUSERSONG = []\n\n for i in range(len(NOWLISTSTEXT)):\n if NOWLISTSDIC[NOWLISTSTEXT[i][1]] == obj:#클릭한 edit obj의 userlist파악위해\n CHECKEDONEUSERLIST = NOWLISTSTEXT[i][0]#userlist이름저장\n #print(CHECKEDONEUSERLIST)\n\n DELLISTS = sbu.show_oneUserlist(CHECKEDONEUSERLIST)\n delListNum = len(DELLISTS)\n #print(f'DELLISTS:{DELLISTS}')\n self.delUserlistSongPopup = Popup(title='',\n size_hint=(0.7, 1), size=(800, 800),auto_dismiss=True,\n title_font=todayFont,title_size=menu_fontsize, title_align='center',\n title_color=textColor,\n separator_height=0.5,\n separator_color=textColor)\n\n self.basepop = BoxLayout(padding=5,spacing=5,size_hint=(1,1), orientation = 'vertical')\n\n self.layoutpop_top = GridLayout(rows=1,cols=3,padding=5,spacing=5,size_hint=(1, 0.05))\n self.layoutpop_middle = GridLayout(rows=DELROWNUM,cols=2,padding=5,spacing=5,size_hint=(1, 0.9))\n self.layoutpop_page = GridLayout(rows=1,cols=12,padding=5,spacing=5,size_hint=(0.9, 0.05))\n\n self.basepop.add_widget(self.layoutpop_top)\n self.basepop.add_widget(self.layoutpop_middle)\n self.basepop.add_widget(self.layoutpop_page)\n\n self.popText=Label(font_name=todayFont,font_size=menu_fontsize,text = 'Choose the song.',size_hint=(0.9, 0.2),color=textColor)\n self.delBtn = Button(font_name=todayFont,font_size=menu_fontsize,text=\"-\",size_hint=(0.05, 0.2), background_normal = \"\", background_down = \"\",background_color=boxColor,color=textColor)\n\n self.editBtn = Button(font_name=todayFont,font_size=menu_fontsize,text=\"edit\",size_hint=(0.05, 0.2), background_normal = \"\", background_down = \"\",background_color=boxColor,color=textColor)\n\n self.delBtn.bind(on_press = self.del_pressed) #\"-\"버튼 클릭시, userlist의 곡삭제 함수호출\n self.editBtn.bind(on_press=lambda instance : self.open_userTitlePopup(obj))\n #self.editBtn.bind(on_press=self.open_userTitlePopup)\n self.layoutpop_top.add_widget(self.popText)\n self.layoutpop_top.add_widget(self.delBtn)\n self.layoutpop_top.add_widget(self.editBtn)\n\n for i in range(DELROWNUM):\n if i <= delListNum-1:\n title = DELLISTS[i].split(\".wav\")\n self.userListLabel=Label(font_name=todayFont,font_size=text_fontsize,text = f'{title[0]}',halign=\"left\",valign=\"top\",size_hint=(0.9, 0.2), color=[1,1,1,1])\n self.checkboxBtn=CheckBox(size_hint=(0.1, 0.2),color=winColor)\n\n self.checkboxBtn.bind(active=self.checked_userlistSong)#check된 list 파악 함수 호출\n DELLISTSTEXT[i][0] = f'{DELLISTS[i]}'\n DELLISTSDIC[DELLISTSTEXT[i][0]]=self.checkboxBtn\n if i > delListNum-1:\n self.userListLabel=Label(font_name=todayFont,font_size=text_fontsize,text = f'{i}',halign=\"left\",valign=\"top\",size_hint=(0.9, 0.2), color=[0,0,0,0])\n self.checkboxBtn=CheckBox(size_hint=(0.1, 0.2),color=[0,0,0,0])\n\n #self.checkboxBtn.bind(active=self.checked_userlistSong)\n DELLISTSTEXT[i][0] = f'{i}'\n DELLISTSDIC[DELLISTSTEXT[i][0]]=self.checkboxBtn\n\n self.layoutpop_middle.add_widget(self.userListLabel)\n self.layoutpop_middle.add_widget(self.checkboxBtn)\n\n #=====페이지버튼 추가하기 전에 계산============================================\n pageLISTNOpop = delListNum//(DELROWNUM) #총userlist수(ex.236) // 한페지화면의userlist수(15) == 총페이지개수(15, 나머지있으면 16)\n lastLISTNOpop = delListNum%(DELROWNUM) #총userlist수 % 한페지화면의userlist수(15) == 마지막페이지에보여질userlist수(ex.11) => 총페이지개수(15+나머지=16)\n if lastLISTNOpop > 0:\n pageLISTNOpop+=1\n pageSetLISTNOpop = pageLISTNOpop // 10 # 총페이지개수 //한레이아웃페이지수(1~10페이지) == 다음 >> 넘기는 횟수와 동일\n lastPageLISTNOpop = pageLISTNOpop % 10 #총페이지개수 % 한레이아웃페이지수(1~10페이지) == 마지막에 남은 보여줄 버튼 개수(6)\n\n #=====페이지버튼 추가=======================================================\n for i in range(len(POPDELBTNLIST)):\n self.popdelBTN = Button(font_name=todayFont,font_size=text_fontsize,text=f\"{i}\",size_hint=(0.1, 0.2), background_color=winColor,color=textColor)\n if pageSetLISTNOpop == 0 and i > lastPageLISTNOpop:\n self.popdelBTN.background_color=[0,0,0,0]\n self.popdelBTN.color=[0,0,0,0]\n else:\n if i == 0:#첫번째인덱스\n self.popdelBTN.text = \"<<\"\n if i == 11:#마지막인덱스\n self.popdelBTN.text = \">>\"\n self.popdelBTN.bind(on_press=self.press_popdelBTN)#페이지번호 클릭시, 화면리셋 함수 호출\n\n POPDELBTNLIST[i] = self.popdelBTN\n self.layoutpop_page.add_widget(self.popdelBTN)\n #print(DELLISTSTEXT,\"\\n\",DELLISTSDIC,\"\\n\")\n self.delUserlistSongPopup.add_widget(self.basepop)\n self.delUserlistSongPopup.open()\n\n #==============팝업창(userlist dir 생성&삭제)===================================\n def makeListPop(self, obj):\n self.makeListPopup = Popup(title='',\n size_hint=(0.5, 0.4), size=(800, 800),auto_dismiss=True,\n title_font=todayFont,title_size=menu_fontsize, title_align='center',\n title_color=textColor,\n separator_height=0.5,\n separator_color=textColor)\n\n self.lowerContent = StackLayout(orientation=\"lr-tb\",padding=10,spacing=10)\n self.makeListText=Label(font_name=todayFont,font_size =menu_fontsize,text = 'Write list name.',width=40, height=30,size_hint=(1, 0.2),color=textColor)\n self.lowerContent.add_widget(self.makeListText)\n\n self.listNameText = TextInput(font_name=todayFont,multiline = False,width=40, height=30,size_hint=(1, 0.2))\n self.lowerContent.add_widget(self.listNameText)\n\n self.listMakeBtn = Button(font_name=todayFont,font_size =menu_fontsize,text=\"Create\",width=40, height=30,size_hint=(0.5, 0.16), background_normal = \"\", background_color=boxColor,color=textColor)\n self.listMakeBtn.bind(on_press = self.press_listMake) #userlist dir 생성\n self.lowerContent.add_widget(self.listMakeBtn)\n\n self.listDeleteBtn = Button(font_name=todayFont,font_size =menu_fontsize,text=\"Delete\",width=40, height=30,size_hint=(0.5, 0.16), background_normal = \"\", background_color=boxColor,color=textColor)\n self.listDeleteBtn.bind(on_press = self.press_listDelete) #userlist dir 삭제\n self.lowerContent.add_widget(self.listDeleteBtn)\n\n self.makeListPopup.add_widget(self.lowerContent)\n\n self.makeListPopup.open()\n\n #==============userlist dir 생성 & 반영된 화면 리셋==============================\n def press_listMake(self, obj):\n print(\"List Name:\", self.listNameText.text)\n listName = f'{self.listNameText.text}'\n try:\n\n before = sbu.show_userlist()\n num = len(before)\n listName = f'{num+1}. {listName}'\n after = sbu.make_userlist(listName)\n\n if after == False:\n print(\"Can't created. there is same list.\")\n else:\n print(f'{listName} was created.')\n\n self.base1.clear_widgets()\n self.drawMylist()\n #=====바꾸고 난 후, 재생 중인 곡 표시위해서, playing 중인 obj의 곡명 저장\n before_playing = sbp.get_playResult()\n songs = {}\n for i in before_playing:\n tempTitle = i.text.split('.wav')\n tempTitle = tempTitle[0].split('* ')\n\n if len(tempTitle) > 1:\n song = f'{tempTitle[1]}'\n else:\n song = f'{i.text}'\n songs[song] = i\n\n #print(f\"playing-song name & obj: {songs}}\")\n\n for i in range(len(NOWLISTSTEXT)):\n if NOWLISTSTEXT[i][0] in songs.keys():\n NOWLISTSDIC[NOWLISTSTEXT[i][0]].color = stopColor\n playing.append(NOWLISTSDIC[NOWLISTSTEXT[i][0]])\n print(f\"NOWLISTSDIC:{NOWLISTSDIC}\\nstopColor:{stopColor}\")\n\n except Exception as msg:\n self.makeListPopup.title = f\"{msg}Retry.\"\n\n self.listNameText.text = \"\"\n self.makeListPopup.dismiss()\n\n #==============userlist dir 삭제 & 반영된 화면 리셋==============================\n def press_listDelete(self, obj):\n print(\"List Name:\", self.listNameText.text)\n listName = f'{self.listNameText.text}'\n\n beforeDic = {}\n count = 0\n\n userDir = sbu.show_userlist()#os.listdir(f'{userListDir}')\n\n nowtitle = []\n\n for i in userDir:\n if count < len(NOWLISTSTEXT):\n if NOWLISTSDIC[NOWLISTSTEXT[count][0]] in playing:\n beforeDic[NOWLISTSTEXT[count][0]] = stopColor\n else:\n beforeDic[NOWLISTSTEXT[count][0]] = textColor\n else:\n beforeDic[i] = textColor\n count+=1\n print(f\"beforeDic:{beforeDic}\")\n\n try:\n res = sbu.delete_userlist(listName)\n\n if res == False:\n print(\"Can't delete. there is no such listname.\")\n\n else:\n print(f'{listName} was deleted.')\n\n self.base1.clear_widgets()\n self.drawMylist()\n\n #=====바꾸고 난 후, 재생 중인 곡 표시위해서, playing 중인 obj의 곡명 저장\n before_playing = sbp.get_playResult()\n songs = {}\n for i in before_playing:\n tempTitle = i.text.split('.wav')\n tempTitle = tempTitle[0].split('* ')\n\n if len(tempTitle) > 1:\n song = f'{tempTitle[1]}'\n else:\n song = f'{i.text}'\n songs[song] = i\n\n #print(f\"playing-song name & obj: {songs}\")\n\n #=====바꾸고 난 후 list 변화 체크\n userDir = sbu.show_userlist()\n\n newList = []\n\n for i in userDir:\n newList.append(userDir[i])\n\n print(f\"newList:{newList}\")\n\n for i in range(len(delNumList)):\n NOWLISTSDIC[newList[i]].color = beforeDic[newList[i]]\n if NOWLISTSDIC[newList[i]].color == stopColor:\n playing.append(NOWLISTSDIC[newList[i]])\n\n print(f\"NOWLISTSDIC[newList[i]]:{NOWLISTSDIC[newList[i]]}\")\n\n\n except Exception as msg:\n self.makeListPopup.title = f\"{msg}Retry.\"\n\n self.listNameText.text = \"\"\n self.makeListPopup.dismiss()\n\n #=====userlist title 변경 popup> self.res_touchTitle> sbu.touch_userTitle=====\n def open_userTitlePopup(self,listobj):\n self.titlePopup = Popup(title='',\n size_hint=(0.5, 0.4), size=(800, 800),auto_dismiss=True,\n title_font=todayFont,title_size=menu_fontsize, title_align='center',\n title_color=textColor,\n separator_height=0.5,\n separator_color=textColor)\n\n self.lowerContent = StackLayout(orientation=\"lr-tb\",padding=10,spacing=10)\n self.titlePopupText=Label(font_name=todayFont,font_size=menu_fontsize,text = 'Write new title',width=40, height=30,size_hint=(1, 0.2),color=textColor)\n self.lowerContent.add_widget(self.titlePopupText)\n\n self.lowerContent.add_widget(Label(font_name = todayFont,font_size=menu_fontsize,text='New Title?',width=40, height=30,size_hint=(0.2, 0.16),color=textColor))\n self.newTitle = TextInput(font_name=todayFont,multiline = False,width=40, height=30,size_hint=(0.8, 0.16))\n self.lowerContent.add_widget(self.newTitle)\n\n self.submit = Button(font_name=todayFont,font_size=menu_fontsize,text=\"Edit\",width=40, height=30,size_hint=(0.33, 0.16), background_normal = \"\", background_color=boxColor,color=textColor)\n\n self.submit.bind(on_press=lambda instance : self.res_touchtitle(listobj,self.newTitle))\n\n self.lowerContent.add_widget(self.submit)\n self.titlePopup.add_widget(self.lowerContent)\n\n self.titlePopup.open()\n\n #=============sbu.touch_userTitle 결과 받아서 화면 리셋==========================\n def res_touchtitle(self,listobj,newTitle):\n global BTNnum\n\n beforeDic = {}\n count = 0\n\n userDir = sbu.show_userlist()\n\n nowtitle = []\n\n for i in userDir:\n if int(i) < len(NOWLISTSTEXT):\n if NOWLISTSDIC[userDir[i]] in playing:\n beforeDic[userDir[i]] = stopColor\n else:\n beforeDic[userDir[i]] = textColor\n else:\n beforeDic[userDir[i]] = textColor\n\n #print(f\"beforeDic:{beforeDic}\")\n\n try:\n\n for i in range(ROWNUM):\n #print(f'listobj:{listobj},\\nNOWLISTSTEXT[i][1]:{NOWLISTSTEXT[i][1]},NOWLISTSDIC[NOWLISTSTEXT[i][1]]:{NOWLISTSDIC[NOWLISTSTEXT[i][1]]}')\n if NOWLISTSDIC[NOWLISTSTEXT[i][1]] == listobj:\n beforeTitle = NOWLISTSTEXT[i][0]\n #print(f'beforeTitle:{beforeTitle}')\n\n res = sbu.touch_userTitle(beforeTitle,newTitle)\n\n if res == False:\n print(\"Can't rename.\")\n break\n else:\n print(f'changed.')\n\n #=====바꾸고 난 후 list 변화 체크\n tempPageObj = Button(text=f\"{BTNnum}\",background_color=winColor,color=textColor)\n self.press_settingpageBTN(tempPageObj)\n\n userDir = sbu.show_userlist()\n\n newList = []\n delNumList = []\n\n for i in userDir:\n delNumList.append(userDir[i])\n if userDir[i] not in beforeDic.keys():\n newList.append(userDir[i])\n\n for i in beforeDic:\n if i not in delNumList:\n if beforeDic[i] == stopColor:\n playing.append(NOWLISTSDIC[newList[0]])\n else:\n NOWLISTSDIC[newList[0]].color = beforeDic[i]\n\n self.press_settingpageBTN(tempPageObj)\n\n #print(f\"NOWLISTSDIC[newList[0]]:{NOWLISTSDIC[newList[0]]}\")\n\n except Exception as msg:\n print(f\"{msg}Retry.\")\n\n self.titlePopup.dismiss()\n self.delUserlistSongPopup.dismiss()\n\n #==============del popup창의 페이지번호 화면에 그리기==============================\n def press_popdelBTN(self, obj):\n BTNnum = obj.text#클릭된 버튼의 text\n nowpageQ = int(POPDELBTNLIST[1].text)#두번째 버튼의 text\n #===<<,>>버튼이 클릭되었을 경우에, 보여줄 화면 파악하기 위하여\n if nowpageQ > 10:\n nowpageA = ((nowpageQ-1)//10)\n else:\n nowpageA = 0\n #print(f\"final nowpageQ{nowpageQ},nowpageA{nowpageA}\")\n\n #=====페이지버튼 추가하기 전에 계산============================================\n DELLISTS = sbu.show_oneUserlist(CHECKEDONEUSERLIST)\n delListNum = len(DELLISTS)\n\n pageLISTNOpop = delListNum//(DELROWNUM) #총userlist수(ex.236) // 한페지화면의userlist수(15) == 총페이지개수(15, 나머지있으면 16)\n lastLISTNOpop = delListNum%(DELROWNUM) #총userlist수 % 한페지화면의userlist수(15) == 마지막페이지에보여질userlist수(ex.11) => 총페이지개수(15+나머지=16)\n if lastLISTNOpop > 0:\n pageLISTNOpop+=1\n pageSetLISTNOpop = pageLISTNOpop // 10 # 총페이지개수 //한레이아웃페이지수(1~10페이지) == 다음 >> 넘기는 횟수와 동일\n lastPageLISTNOpop = pageLISTNOpop % 10 #총페이지개수 % 한레이아웃페이지수(1~10페이지) == 마지막에 남은 보여줄 버튼 개수(6)\n print(f\"ScreenSetting_POPUP:: BTNnum:{BTNnum}, pageLISTNOpop:{pageLISTNOpop}\")\n\n #=====페이지버튼의 숫자 바꾸기================================================\n if BTNnum == \"<<\":\n if nowpageA != 0:\n for i in range(1,len(POPDELBTNLIST)):\n if nowpageA != \"1\": #1-10은 \"<<\"버튼은 작동 안하기에\n POPDELBTNLIST[i].text = str((nowpageA-1)*10+i)\n POPDELBTNLIST[i].background_color=winColor\n POPDELBTNLIST[i].color=textColor\n if i == 11:#\n POPDELBTNLIST[i].text = \">>\"\n POPDELBTNLIST[i].background_color=winColor\n POPDELBTNLIST[i].color=textColor\n endIndex = int(POPDELBTNLIST[1].text)*FIXROW\n elif BTNnum == \">>\":\n if pageSetLISTNOpop == nowpageA+1:#userlist의 곡개수의 페이지번호까지만 보여주기\n #print(f\"BTN set: pageSetNO{pageSetLISTNOpop},nowpageA{nowpageA}\")\n for i in range(1,len(POPDELBTNLIST)):\n POPDELBTNLIST[i].text = str((nowpageA+1)*10+i)#페이지버튼의 번호바꾸기\n if i > lastPageLISTNOpop:#마지막페이지일 경우, 남은 userlist의 곡개수만큼만 화면에 보여주기\n POPDELBTNLIST[i].background_color=[0,0,0,0]\n POPDELBTNLIST[i].color=[0,0,0,0]\n else:#페이지버튼의 번호바꾸기\n for i in range(1,len(POPDELBTNLIST)):\n POPDELBTNLIST[i].text = str((nowpageA+1)*10+i)\n POPDELBTNLIST[i].background_color=winColor\n POPDELBTNLIST[i].color=textColor\n if i == 11:#\">>\" 바뀌지 않도로\n POPDELBTNLIST[i].text = \">>\"\n POPDELBTNLIST[i].background_color=winColor\n POPDELBTNLIST[i].color=textColor\n endIndex = int(POPDELBTNLIST[1].text)*FIXROW\n else:\n endIndex = int(BTNnum)*FIXROW\n startIndex = endIndex - (FIXROW-1)\n\n #=====화면 리셋===========================================================\n count = 0\n self.layoutpop_middle.clear_widgets()\n for i in range(startIndex,endIndex+1):#그때그때 인덱스를 지정, 보여줄 화면\n if str(BTNnum) == str(pageLISTNOpop) and lastLISTNOpop != 0:\n sub = (FIXROW-lastLISTNOpop)\n overIndex = endIndex-sub\n\n if i > overIndex:#마지막페이지의 userlist 곡 수보다 i 가 크면, 위젯을 안보이도록 처리\n self.userListLabel=Label(font_name=todayFont,font_size=text_fontsize,text = f'',halign=\"left\",valign=\"top\",size_hint=(0.9, 0.2), color=[0,0,0,0])\n self.checkboxBtn=CheckBox(size_hint=(0.1, 0.2),color=winColor)\n else:\n title = DELLISTS[i-1].split(\".wav\")\n\n self.userListLabel=Label(font_name=todayFont,font_size=text_fontsize,text = f'{title[0]}',halign=\"left\",valign=\"top\",size_hint=(0.9, 0.2), color=[1,1,1,1])\n self.checkboxBtn=CheckBox(size_hint=(0.1, 0.2),color=winColor)\n\n self.checkboxBtn.bind(active=self.checked_userlistSong)\n DELLISTSTEXT[count][0] = f'{DELLISTS[i-1]}'\n DELLISTSDIC[DELLISTSTEXT[count][0]]=self.checkboxBtn\n else:\n title = DELLISTS[i-1].split(\".wav\")\n\n self.userListLabel=Label(font_name=todayFont,font_size=text_fontsize,text = f'{title[0]}',halign=\"left\",valign=\"top\",size_hint=(0.9, 0.2), color=[1,1,1,1])\n self.checkboxBtn=CheckBox(size_hint=(0.1, 0.2),color=winColor)\n\n self.checkboxBtn.bind(active=self.checked_userlistSong)\n DELLISTSTEXT[count][0] = f'{DELLISTS[i-1]}'\n DELLISTSDIC[DELLISTSTEXT[count][0]]=self.checkboxBtn\n\n self.layoutpop_middle.add_widget(self.userListLabel)\n self.layoutpop_middle.add_widget(self.checkboxBtn)\n count+=1\n\n #==============userlist 팝업창에서 저장된 곡 중에, 체크한 곡 알기위한 함수==============\n def checked_userlistSong(self, checkbox, yes_check):\n #thisTitle = ''\n if yes_check:\n for i in range(len(DELLISTSTEXT)):\n if DELLISTSDIC[DELLISTSTEXT[i][0]] == checkbox:\n thisTitle = DELLISTSTEXT[i][0]\n #print(f\"checked one song{DELLISTSTEXT[i][0]}\")\n if DELLISTSDIC[DELLISTSTEXT[i][0]] not in CHECKEDONEUSERSONG:\n CHECKEDONEUSERSONG.append(thisTitle)\n #print(f\"add one song{DELLISTSTEXT[i][0]}\")\n elif DELLISTSDIC[DELLISTSTEXT[i][0]] != checkbox:\n thisTitle = DELLISTSTEXT[i][0]\n #print(f\"no checked one song{DELLISTSTEXT[i][0]}\")\n if DELLISTSDIC[DELLISTSTEXT[i][0]] in CHECKEDONEUSERSONG:\n CHECKEDONEUSERSONG.remove(DELLISTSDIC[DELLISTSTEXT[i][0]])\n #print(f\"delete no checked one song{DELLISTSTEXT[i][0]}\")\n\n #==============userlist팝업창의 '-'버튼 클릭하면, 체크�� 곡 삭제=====================\n def del_pressed(self, obj):\n #print(f\"CHECKEDONEUSERLIST:{CHECKEDONEUSERLIST}\\nCHECKEDONEUSERSONG:{CHECKEDONEUSERSONG},NOWLISTS:{NOWLISTS}\")\n nowUserlist = sbu.show_userlist()\n for i in nowUserlist:\n print(nowUserlist[i])\n if nowUserlist[i] == CHECKEDONEUSERLIST:\n for j in os.listdir(f\"{userListDir}/{i}. {CHECKEDONEUSERLIST}\"):\n if j in CHECKEDONEUSERSONG:\n os.remove(f\"{userListDir}/{i}. {CHECKEDONEUSERLIST}/{j}\")\n print(f\"removed this song: {userListDir}/{i}. {CHECKEDONEUSERLIST}/{j}\")\n self.delUserlistSongPopup.dismiss()\n\n #==============userlist 버튼 클릭시, play thread 시작===================\n def playUserlist(self, playBtn):\n global playTitle,playing #playing은 재생곡의 위젯\n #print(f\"userlist_playing:{playing}\")\n PAUSE_BTN.text = \"|||\"\n PAUSE_BTN.color = boxColor\n PAUSE_BTN.texture_update()\n\n playTitle = []\n playList = []\n playing = []\n\n nowUserlist = sbu.show_userlist()\n\n for i in nowUserlist:\n try:\n if NOWLISTSDIC[nowUserlist[i]] == playBtn:\n playTitle = os.listdir(f\"{userListDir}/{i}. {nowUserlist[i]}\")\n playing.append(playBtn)\n break\n\n except Exception as msg:\n res = f\"{msg} failed.\"\n continue\n\n print(f\"playTitle{playTitle}\")\n playTitle.sort()\n for i in playTitle:\n if i in ignoreFile:\n playTitle.remove(i)\n print(f\"playTitle:{playTitle}\")\n\n sbp.get_quit()\n time.sleep(1)\n\n playnum = 0\n thread_one = threading.Thread(target = sbp.get_playThread, args = (playTitle,playing,PLAY_BTN,playBtn,playnum), daemon=True)\n thread_one.start()\n\n#==============class ScreenSong=================================================\nclass ScreenSong(Screen):\n def __init__(self, **kwargs):\n super(ScreenSong, self).__init__(**kwargs)\n global SONGROWNUM, SONGNOWLISTS, SONGNOWLISTSTEXT, SONGNOWLISTSDIC, CHECKBOXLISTS, CHECKEDSONG, CHECKEDUSERLIST, SONGBTNLIST, POPADDBTNLIST\n self.name = \"screen_song\"\n\n SONGNOWLISTS = sbl.show_Song()#총 곡\n SONGNOWLISTS.sort()\n\n SONGROWNUM = FIXROW#한 페이지번호에 보여줄 곡 수\n\n SONGNOWLISTSTEXT = [['']*3 for x in range(SONGROWNUM)]#한 화면의 곡 수 만큼만 저장\n SONGNOWLISTSDIC = {}\n CHECKBOXLISTS = [''] * (SONGROWNUM)#체크박스\n\n CHECKEDSONG = []\n CHECKEDUSERLIST = []\n\n SONGBTNLIST = ['']*12#한 화면에 보여줄 페이지번호 개수(<<, 1~10, >>)\n POPADDBTNLIST = ['']*12#userlist popup페이지버튼(지정한 목록 15개 초과시)\n\n self.base = BoxLayout(padding=5,spacing=5,size_hint=(1,1), orientation = 'vertical')\n self.add_widget(self.base)\n self.drawSonglist()\n\n #==============SongScreen 위젯 추가===========================================\n def drawSonglist(self):\n SONGNOWLISTS = sbl.show_Song()#총 곡\n SONGNOWLISTS.sort()\n songListNum = len(SONGNOWLISTS)\n #print(f\"songListNum:{songListNum}\")\n\n pageNO = songListNum//(SONGROWNUM) #총곡수(ex.236) // 한페지화면의곡수(15) == 총페이지개수(15, 나머지있으면 16)\n lastsongNum = songListNum%(SONGROWNUM) #총곡수 % 한페지화면의곡수(15) == 마지막페이지에보여질곡수(ex.11) => 총페이지개수(15+나머지=16)\n if lastsongNum > 0:\n pageNO+=1\n pageSetNO = pageNO // 10 # 총페이지개수 //한레이아웃페이지수(1~10페이지) == 다음 >> 넘기는 횟수와 동일\n lastPageNO = pageNO % 10 #총페이지개수 % 한레이아웃페이지수(1~10페이지) == 마지막에 남은 보여줄 버튼 개수(6)\n #print(f\"pageNO:{pageNO}, lastsongNum:{lastsongNum}\")\n\n self.layout_top = GridLayout(rows=1,cols=9,padding=5,spacing=5,size_hint=(1, 0.05))\n self.layout_middle = GridLayout(rows=SONGROWNUM,cols=9,padding=5,spacing=5,size_hint=(1, 0.9))\n self.layout_page = GridLayout(rows=1,cols=12,padding=5,spacing=5,size_hint=(0.9, 0.05))\n\n self.base.add_widget(self.layout_top)\n self.base.add_widget(self.layout_middle)\n self.base.add_widget(self.layout_page)\n\n self.titleEmptyLabel1=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.titleEmptyLabel2=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.topLabel=Label(font_name=todayFont,font_size=menu_fontsize,text ='Song List',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.titleEmptyLabel3=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.titleEmptyLabel4=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.titleEmptyLabel5=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.addUserlistBtn = Button(font_name=todayFont,font_size=menu_fontsize,text=\"+ MyList\",size_hint=(0.9, 0.03), background_normal = \"\",background_down = \"\",background_color=[0,0,0,0],color=boxColor)\n self.titleEmptyLabel6=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n\n self.addUserlistBtn.bind(on_press = self.add_checkedsong)\n\n self.layout_top.add_widget(self.titleEmptyLabel1)\n self.layout_top.add_widget(self.titleEmptyLabel2)\n self.layout_top.add_widget(self.topLabel)\n self.layout_top.add_widget(self.titleEmptyLabel3)\n self.layout_top.add_widget(self.titleEmptyLabel4)\n self.layout_top.add_widget(self.titleEmptyLabel5)\n self.layout_top.add_widget(self.addUserlistBtn)\n self.layout_top.add_widget(self.titleEmptyLabel6)\n\n for i in range(SONGROWNUM):\n\n if i > songListNum-1:\n title = i\n self.emptyLabel1=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.emptyLabel2=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.songLabel=Label(font_name=todayFont,font_size=text_fontsize,text = f'',halign=\"left\",valign=\"middle\",size_hint=(1, 0.2), color=[0,0,0,0])\n self.emptyLabel3=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.emptyLabel4=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.checkBox=CheckBox(size_hint=(1, 0.2),color=[0,0,0,0])\n self.emptyLabel6=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.editBtn = Button(font_name=todayFont,font_size=text_fontsize,text=\"edit\", size_hint=(0.9, 0.03), background_normal = \"\", background_color=[0,0,0,0],color=[0,0,0,0])\n self.emptyLabel7=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n\n elif i <= songListNum-1:\n title = SONGNOWLISTS[i][:-4]\n tempTitle = title.split('* ')\n\n self.emptyLabel1=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.emptyLabel2=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.songLabel=Button(font_name=todayFont,font_size=text_fontsize,text = f'{title}',halign=\"left\",valign=\"middle\",size_hint=(2, 0.2), background_normal = \"\", background_down = \"\",background_color=[0,0,0,0], color=textColor)\n self.emptyLabel3=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.emptyLabel4=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.checkBox=CheckBox(size_hint=(1, 0.2),color=textColor)\n self.emptyLabel6=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.editBtn = Button(font_name=todayFont,font_size=text_fontsize,text=\"edit\",size_hint=(0.9, 0.03), background_normal = \"\", background_down = \"\",background_color=[0,0,0,0],color=boxColor)\n self.emptyLabel7=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n\n\n self.checkBox.bind(active=self.checked_song)\n self.songLabel.bind(on_press=self.play_oneSong)\n self.editBtn.bind(on_press=self.open_titlePopup)\n\n if len(tempTitle) > 1:\n print(f'draw start tempTitle{tempTitle}')\n SONGNOWLISTSTEXT[i][0] = f'{tempTitle[1]}.wav'\n else:\n SONGNOWLISTSTEXT[i][0] = f'{title}.wav'\n\n SONGNOWLISTSTEXT[i][1] = f'{title}+edit'\n SONGNOWLISTSTEXT[i][2] = f'{title}+checkbox'\n SONGNOWLISTSDIC[SONGNOWLISTSTEXT[i][0]]=self.songLabel\n SONGNOWLISTSDIC[SONGNOWLISTSTEXT[i][1]]=self.editBtn\n SONGNOWLISTSDIC[SONGNOWLISTSTEXT[i][2]]=self.checkBox\n #print(f'SONGNOWLISTS:{SONGNOWLISTS}\\nSONGNOWLISTSTEXT:{SONGNOWLISTSTEXT}\\nSONGNOWLISTSDIC:{SONGNOWLISTSDIC}')\n self.layout_middle.add_widget(self.emptyLabel1)\n self.layout_middle.add_widget(self.emptyLabel2)\n self.layout_middle.add_widget(self.songLabel)\n self.layout_middle.add_widget(self.emptyLabel3)\n self.layout_middle.add_widget(self.emptyLabel4)\n self.layout_middle.add_widget(self.emptyLabel6)\n self.layout_middle.add_widget(self.checkBox)\n self.layout_middle.add_widget(self.editBtn)\n self.layout_middle.add_widget(self.emptyLabel7)\n #=====페이지번호위젯추가=====================================================\n if songListNum > SONGROWNUM:\n\n for i in range(len(SONGBTNLIST)):\n self.SONGBTN = Button(font_name=todayFont,font_size=text_fontsize,text=f\"{i}\",size_hint=(0.1, 0.2), background_color=winColor,color=textColor)\n if pageSetNO == 0 and i > lastPageNO :#(ex.<< 1 2 3 4 5 6 7 8 9 10 >>의 버튼 12개 중에 총곡수가 첫번째 페이지세트에 국한될 경우.\n self.SONGBTN.background_color=[0,0,0,0]\n self.SONGBTN.color=[0,0,0,0]\n else:\n if i == 0:\n self.SONGBTN.text = \"<<\"\n if i == 11:\n self.SONGBTN.text = \">>\"\n\n self.SONGBTN.bind(on_press=self.press_songBTN)#페이지번호클릭시,화면리셋함수호출\n\n SONGBTNLIST[i] = self.SONGBTN\n self.layout_page.add_widget(self.SONGBTN)\n else:\n self.SONGBTN = Button(font_name=todayFont,font_size=text_fontsize,text=\"1\",size_hint=(0.1, 0.2), background_color=winColor,color=textColor)\n SONGBTNLIST[1] = self.SONGBTN\n\n #==============곡명 수정 popup창 -> sbl.touch_title 호출========================\n def open_titlePopup(self, obj):\n self.titlePopup = Popup(title='',\n size_hint=(0.5, 0.4), size=(800, 800),auto_dismiss=True,\n title_font=todayFont,title_size=menu_fontsize, title_align='center',\n title_color=textColor,\n separator_height=0.5,\n separator_color=textColor)\n\n for i in range(SONGROWNUM):\n if SONGNOWLISTSDIC[SONGNOWLISTSTEXT[i][1]]==obj:\n beforeTitle = SONGNOWLISTSTEXT[i][1]\n print(beforeTitle)\n break\n\n self.lowerContent = StackLayout(orientation=\"lr-tb\",padding=10,spacing=10)\n self.titlePopupText=Label(font_name=todayFont,font_size=menu_fontsize,text = 'Write song & singer.',width=40, height=30,size_hint=(1, 0.2),color=textColor)\n self.lowerContent.add_widget(self.titlePopupText)\n\n self.lowerContent.add_widget(Label(font_name = todayFont,font_size=menu_fontsize,text='Song?',width=40, height=30,size_hint=(0.2, 0.16),color=textColor))\n self.song = TextInput(font_name=todayFont,multiline = False,width=40, height=30,size_hint=(0.8, 0.16))\n self.lowerContent.add_widget(self.song)\n\n self.lowerContent.add_widget(Label(font_name=todayFont,font_size=menu_fontsize,text = 'Singer?',width=40, height=30,size_hint=(0.2, 0.16),color=textColor))\n self.singer = TextInput(font_name=todayFont,multiline = False,width=40, height=30,size_hint=(0.8, 0.16))\n self.lowerContent.add_widget(self.singer)\n\n self.songBoxSubmit = Button(font_name=todayFont,font_size=menu_fontsize,text=\"Edit\",width=40, height=30,size_hint=(0.33, 0.16), background_normal = \"\", background_color=boxColor,color=textColor)\n\n self.songBoxSubmit.bind(on_press=lambda instance : self.call_touchtitle(beforeTitle))\n\n self.lowerContent.add_widget(self.songBoxSubmit)\n self.titlePopup.add_widget(self.lowerContent)\n\n self.titlePopup.open()\n\n #==============song edit->change title(1.song 2.singer)=====================\n def call_touchtitle(self,beforeTitle):\n\n res = sbl.touch_title(beforeTitle,self.song,self.singer)\n\n if res == True:\n manager.screen_song.layout_middle.clear_widgets()#songlist 레이아웃 지우기\n manager.screen_song.press_songBTN(tempObj)#songlist 다시그리기\n\n manager.screen_singer.base1.clear_widgets()\n manager.screen_singer.drawMylist()\n\n self.titlePopup.dismiss()\n\n #==============페이지번호 눌렀을 때, 화면 리셋 함수==================================\n def press_songBTN(self, obj):\n BTNnum = obj.text\n\n nowpageQ = int(SONGBTNLIST[1].text)#클릭했을 때의 몇번째의 페이지셋이었는지 알기위함\n if nowpageQ > 10: #클릭했을 때의 페이지세트가 첫번째세트가 아니었다면,\n nowpageA = ((nowpageQ-1)//10)\n else:\n nowpageA = 0\n #print(f\"nowpageQ{nowpageQ},nowpageA{nowpageA}\")\n #print(f\"final nowpageQ{nowpageQ},nowpageA{nowpageA}\")\n\n SONGNOWLISTS = sbl.show_Song()\n SONGNOWLISTS.sort()\n songListNum = len(SONGNOWLISTS)\n #ex.236= 150*1+86(15*5+11)(마지막페이지는 나머지곡수만큼리셋)\n pageNO = songListNum//(SONGROWNUM) #총곡수(ex.236) // 한페지화면의곡수(15) == 총페이지개수(15, 나머지있으면 16)\n lastsongNum = songListNum%(SONGROWNUM) #총곡수 % 한페지화면의곡수(15) == 마지막페이지에보여질곡수(ex.11) => 총페이지개수(15+나머지=16)\n if lastsongNum > 0:\n pageNO+=1\n pageSetNO = pageNO // 10 # 총페이지개수 //한레이아웃페이지수(1~10페이지) == 다음 >> 넘기는 횟수와 동일\n lastPageNO = pageNO % 10 #총페이지개수 % 한레이아웃페이지수(1~10페이지) == 마지막에 남은 보여줄 버튼 개수(6)\n\n if len(SONGNOWLISTS) < FIXROW:\n lastsongNum = len(SONGNOWLISTS)\n\n print(f\"ScreenSong:: BTNnum:{BTNnum}, pageNO:{pageNO}\")\n if BTNnum == \"<<\":#<<버튼 클릭시,\n if nowpageA != 0:#첫번째페이지셋이 아니었다면,\n for i in range(1,len(SONGBTNLIST)):\n if nowpageA != \"1\":#첫번째페이지세트에서는 <<버튼은 작동할필요가없으므로,\n SONGBTNLIST[i].text = str((nowpageA-1)*10+i)\n SONGBTNLIST[i].background_color=winColor\n SONGBTNLIST[i].color=textColor\n if i == 11:#>>라면,\n SONGBTNLIST[i].text = \">>\"\n SONGBTNLIST[i].background_color=winColor\n SONGBTNLIST[i].color=textColor\n endIndex = int(SONGBTNLIST[1].text)*FIXROW\n elif BTNnum == \">>\":#>>버튼 클릭시,\n if pageSetNO == nowpageA+1:#마지막페이지세트일경우,\n #print(f\"BTN set: pageSetNO{pageSetNO},nowpageA{nowpageA}\")\n for i in range(1,len(SONGBTNLIST)):\n SONGBTNLIST[i].text = str((nowpageA+1)*10+i)\n if i > lastPageNO:#마지막페이지일경우,\n SONGBTNLIST[i].background_color=[0,0,0,0]\n SONGBTNLIST[i].color=[0,0,0,0]\n\n else:#마지막페이지세트 외의 경우에,\n for i in range(1,len(SONGBTNLIST)):\n SONGBTNLIST[i].text = str((nowpageA+1)*10+i)\n SONGBTNLIST[i].background_color=winColor\n SONGBTNLIST[i].color=textColor\n if i == 11:\n SONGBTNLIST[i].text = \">>\"\n SONGBTNLIST[i].background_color=winColor\n SONGBTNLIST[i].color=textColor\n endIndex = int(SONGBTNLIST[1].text)*FIXROW\n else:\n endIndex = int(BTNnum)*FIXROW#루프돌릴때, 끝인덱스번호\n startIndex = endIndex - (FIXROW-1)#루프돌릴때, 시작인덱스번호\n\n count = 0\n self.layout_middle.clear_widgets()#전화면지우기\n for i in range(startIndex,endIndex+1):#화면위젯다시추가\n if (str(BTNnum) == str(pageNO) and lastsongNum != 0): #마지막 페이지세트를 클릭했을경우,\n\n sub = (FIXROW-lastsongNum)\n overIndex = endIndex-sub\n\n #print(startIndex,endIndex,overIndex)\n #마지막페이지에 보여줄 곡까지만 그리기위함\n if i > overIndex:\n self.emptyLabel1=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.emptyLabel2=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.songLabel=Label(font_name=todayFont,font_size=text_fontsize,text = f'',halign=\"left\",valign=\"middle\",size_hint=(1, 0.2), color=[0,0,0,0])\n self.emptyLabel3=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.emptyLabel4=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.checkBox=CheckBox(size_hint=(1, 0.2),color=[0,0,0,0])\n self.emptyLabel6=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.editBtn = Button(font_name=todayFont,font_size=text_fontsize,text=\"edit\", size_hint=(0.9, 0.03), background_normal = \"\", background_color=[0,0,0,0],color=[0,0,0,0])\n self.emptyLabel7=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n else:#SONGNOWLISTS 인덱스가 i-1 임을 유의, SONGNOWLISTSTEXT, SONGNOWLISTSDIC의 인덱스는 count임을 유의\n self.emptyLabel1=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\", size_hint=(1, 0.2))\n self.emptyLabel2=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\", size_hint=(1, 0.2))\n self.songLabel=Button(font_name=todayFont,font_size=text_fontsize,text = f'{SONGNOWLISTS[i-1][:-4]}',halign=\"left\",valign=\"middle\",size_hint=(1, 0.2), background_normal = \"\", background_down = \"\",background_color=[0,0,0,0], color=textColor)\n self.emptyLabel3=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.emptyLabel4=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.checkBox=CheckBox(size_hint=(1, 0.2),color=textColor)\n self.emptyLabel6=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.editBtn = Button(font_name=todayFont,font_size=text_fontsize,text=\"edit\", size_hint=(0.9, 0.03), background_normal = \"\", background_down = \"\",background_color=[0,0,0,0],color=boxColor)\n self.emptyLabel7=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n\n self.checkBox.bind(active=self.checked_song)\n self.songLabel.bind(on_press = self.play_oneSong)\n self.editBtn.bind(on_press=self.open_titlePopup)\n\n tempTitle = SONGNOWLISTS[i-1].split('* ')\n if len(tempTitle) > 1:\n SONGNOWLISTSTEXT[count][0] = f'{tempTitle[1]}'\n print(f'last pageBTN{tempTitle},{tempTitle[1]}')\n else:\n SONGNOWLISTSTEXT[count][0] = f'{SONGNOWLISTS[i-1]}'\n SONGNOWLISTSTEXT[count][1] = f'{SONGNOWLISTS[i-1]}+edit'\n SONGNOWLISTSTEXT[count][2] = f'{SONGNOWLISTS[i-1]}+checkbox'\n SONGNOWLISTSDIC[SONGNOWLISTSTEXT[count][0]]=self.songLabel\n SONGNOWLISTSDIC[SONGNOWLISTSTEXT[count][1]]=self.editBtn\n SONGNOWLISTSDIC[SONGNOWLISTSTEXT[count][2]]=self.checkBox\n #마지막 페이지세트를 클릭하지않은경우,\n else:\n self.emptyLabel1=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.emptyLabel2=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.songLabel=Button(font_name=todayFont,font_size=text_fontsize,text = f'{SONGNOWLISTS[i-1][:-4]}',halign=\"left\",valign=\"middle\",size_hint=(2, 0.2), background_normal = \"\", background_down = \"\",background_color=[0,0,0,0], color=textColor)\n self.emptyLabel3=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.emptyLabel4=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.checkBox=CheckBox(size_hint=(1, 0.2),color=textColor)\n self.emptyLabel6=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n self.editBtn = Button(font_name=todayFont,font_size=text_fontsize,text=\"edit\",size_hint=(0.9, 0.03), background_normal = \"\", background_down = \"\",background_color=[0,0,0,0],color=boxColor)\n self.emptyLabel7=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint=(1, 0.2))\n\n self.checkBox.bind(active=self.checked_song)\n self.songLabel.bind(on_press = self.play_oneSong)\n self.editBtn.bind(on_press=self.open_titlePopup)\n\n tempTitle = SONGNOWLISTS[i-1].split('* ')\n if len(tempTitle) > 1:\n SONGNOWLISTSTEXT[count][0] = f'{tempTitle[1]}'\n print(f'pageBTN{tempTitle},{tempTitle[1]}')\n else:\n SONGNOWLISTSTEXT[count][0] = f'{SONGNOWLISTS[i-1]}'\n\n SONGNOWLISTSTEXT[count][1] = f'{SONGNOWLISTS[i-1]}+edit'\n SONGNOWLISTSTEXT[count][2] = f'{SONGNOWLISTS[i-1]}+checkbox'\n SONGNOWLISTSDIC[SONGNOWLISTSTEXT[count][0]]=self.songLabel\n SONGNOWLISTSDIC[SONGNOWLISTSTEXT[count][1]]=self.editBtn\n SONGNOWLISTSDIC[SONGNOWLISTSTEXT[count][2]]=self.checkBox\n\n self.layout_middle.add_widget(self.emptyLabel1)\n self.layout_middle.add_widget(self.emptyLabel2)\n self.layout_middle.add_widget(self.songLabel)\n self.layout_middle.add_widget(self.emptyLabel3)\n self.layout_middle.add_widget(self.emptyLabel4)\n self.layout_middle.add_widget(self.emptyLabel6)\n self.layout_middle.add_widget(self.checkBox)\n self.layout_middle.add_widget(self.editBtn)\n self.layout_middle.add_widget(self.emptyLabel7)\n count+=1\n\n #=====페이지 번호 바꾸고 난 후, 재생 중인 곡 표시위해서, playing 중인 obj의 곡명 저장\n playing = sbp.get_playResult()\n songs = {}\n for i in playing:\n tempTitle = i.text.split('* ')\n if len(tempTitle) > 1:\n song = f'{tempTitle[1]}.wav'\n else:\n song = f'{i.text}.wav'\n songs[song] = i\n print(f\"playing-song name & obj: {songs}\")\n #=====페이지 번호 바뀌어도, 재생 중인 곡 표시 & stop하면 작동하도록, 바뀐 obj playing에 저장\n for i in range(len(SONGNOWLISTSTEXT)):\n if SONGNOWLISTSTEXT[i][0] in songs.keys():\n SONGNOWLISTSDIC[SONGNOWLISTSTEXT[i][0]].color = stopColor\n playing.append(SONGNOWLISTSDIC[SONGNOWLISTSTEXT[i][0]])\n\n #==============체크된 곡을 userlist에 추가하는 팝업창 띄우는 함수=====================\n def add_checkedsong(self, obj):\n self.addUserlistPopup = Popup(title='',\n size_hint=(0.7, 1), size=(800, 800),auto_dismiss=True,\n title_font='Roboto',title_size=20, title_align='center',\n title_color=textColor,\n separator_height=0.5,\n separator_color=textColor)\n\n global POPROWNUM, POPLISTS, POPLISTSTEXT, POPLISTSDIC\n POPROWNUM = FIXROW\n POPLISTS = sbu.show_userlist()\n poplistNum = len(POPLISTS)\n POPLISTSTEXT = [['']*2 for x in range(POPROWNUM)]\n POPLISTSDIC = {}\n\n self.basepop1 = BoxLayout(padding=5,spacing=5,size_hint=(1,1), orientation = 'vertical')\n\n self.layoutpop1_top = GridLayout(rows=1,cols=2,padding=5,spacing=5,size_hint=(1, 0.05))\n self.layoutpop1_middle = GridLayout(rows=POPROWNUM,cols=2,padding=5,spacing=5,size_hint=(1, 0.9))\n self.layoutpop1_page = GridLayout(rows=1,cols=12,padding=5,spacing=5,size_hint=(0.9, 0.05))\n\n self.basepop1.add_widget(self.layoutpop1_top)\n self.basepop1.add_widget(self.layoutpop1_middle)\n self.basepop1.add_widget(self.layoutpop1_page)\n\n self.popText = Label(font_name=todayFont,font_size=menu_fontsize,text = 'Choose the userlist.',size_hint=(0.9, 0.2),color=textColor)\n self.addBtn = Button(font_name=todayFont,font_size=menu_fontsize,text=\"+\",size_hint=(0.05, 0.2), background_normal = \"\", background_color=boxColor,color=textColor)\n\n self.addBtn.bind(on_press = self.add_pressed) #bind 콜벡함수연결함수\n\n self.layoutpop1_top.add_widget(self.popText)\n self.layoutpop1_top.add_widget(self.addBtn)\n\n for i in range(POPROWNUM):\n if i <= poplistNum-1:\n self.userListLabel=Label(font_name=todayFont,font_size=text_fontsize,text = f'{i+1}. {POPLISTS[str(i+1)]}',halign=\"left\",valign=\"top\",size_hint=(0.9, 0.2), color=[1,1,1,1])\n self.checkboxBtn=CheckBox(size_hint=(0.1, 0.2),color=winColor)\n\n self.checkboxBtn.bind(active=self.checked_userlist)\n POPLISTSTEXT[i][0] = f'{POPLISTS[str(i+1)]}'\n POPLISTSDIC[POPLISTSTEXT[i][0]]=self.checkboxBtn\n\n if i > poplistNum-1:\n self.userListLabel=Label(font_name=todayFont,font_size=text_fontsize,text = f'{i}',halign=\"left\",valign=\"top\",size_hint=(0.9, 0.2), color=[0,0,0,0])\n self.checkboxBtn=CheckBox(size_hint=(0.1, 0.2),color=[0,0,0,0])\n\n self.checkboxBtn.bind(active=self.checked_userlist)\n POPLISTSTEXT[i][0] = f'{i}'\n POPLISTSDIC[POPLISTSTEXT[i][0]]=self.checkboxBtn\n\n self.layoutpop1_middle.add_widget(self.userListLabel)\n self.layoutpop1_middle.add_widget(self.checkboxBtn)\n\n #=====페이지버튼 추가하기 전에 계산============================================\n pageLISTNOpopadd = poplistNum//(POPROWNUM) #총userlist dir수(ex.236) // 한페지화면의userlist dir수(15) == 총페이지개수(15, 나머지있으면 16)\n lastLISTNOpopadd = poplistNum%(POPROWNUM) #총userlist dir수 % 한페지화면의userlist수(15) == 마지막페이지에보여질userlist dir수(ex.11) => 총페이지개수(15+나머지=16)\n if lastLISTNOpopadd > 0:\n pageLISTNOpopadd+=1\n pageSetLISTNOpopadd = pageLISTNOpopadd // 10 # 총페이지개수 //한레이아웃페이지수(1~10페이지) == 다음 >> 넘기는 횟수와 동일\n lastPageLISTNOpopadd = pageLISTNOpopadd % 10 #총페이지개수 % 한레이아웃페이지수(1~10페이지) == 마지막에 남은 보여줄 버튼 개수(6)\n\n #=====페이지버튼 추가=======================================================\n for i in range(len(POPADDBTNLIST)):\n self.popaddBTN = Button(font_name=todayFont,font_size=text_fontsize,text=f\"{i}\",background_color=winColor,color=textColor)\n if pageSetLISTNOpopadd == 0 and i > lastPageLISTNOpopadd:\n self.popaddBTN.background_color=[0,0,0,0]\n self.popaddBTN.color=[0,0,0,0]\n else:\n if i == 0:#첫번째인덱스\n self.popaddBTN.text = \"<<\"\n if i == 11:#마지막인덱스\n self.popaddBTN.text = \">>\"\n self.popaddBTN.bind(on_press=self.press_popaddBTN)#페이지번호 클릭시, 화면리셋 함수 호출\n\n POPADDBTNLIST[i] = self.popaddBTN\n self.layoutpop1_page.add_widget(self.popaddBTN)\n\n self.addUserlistPopup.add_widget(self.basepop1)\n self.addUserlistPopup.open()\n\n #==============add popup창의 페이지번호 화면에 그리기==============================\n def press_popaddBTN(self, obj):\n BTNnum = obj.text#클릭된 버튼의 text\n nowpageQ = int(POPADDBTNLIST[1].text)#두번째 버튼의 text\n #<<,>>버튼이 클릭되었을 경우에, 보여줄 화면 파악하기 위하여\n if nowpageQ > 10:\n nowpageA = ((nowpageQ-1)//10)\n else:\n nowpageA = 0\n #print(f\"final nowpageQ{nowpageQ},nowpageA{nowpageA}\")\n\n #=====페이지버튼 추가하기 전에 계산============================================\n poplistNum = len(POPLISTS)\n pageLISTNOpopadd = poplistNum//(POPROWNUM) #총userlist dir수(ex.236) // 한페지화면의userlist dir수(15) == 총페이지개수(15, 나머지있으면 16)\n lastLISTNOpopadd = poplistNum%(POPROWNUM) #총userlist dir수 % 한페지화면의userlist수(15) == 마지막페이지에보여질userlist dir수(ex.11) => 총페이지개수(15+나머지=16)\n if lastLISTNOpopadd > 0:\n pageLISTNOpopadd+=1\n pageSetLISTNOpopadd = pageLISTNOpopadd // 10 # 총페이지개수 //한레이아웃페이지수(1~10페이지) == 다음 >> 넘기는 횟수와 동일\n lastPageLISTNOpopadd = pageLISTNOpopadd % 10 #총페이지개수 % 한레이아웃페이지수(1~10페이지) == 마지막에 남은 보여줄 버튼 개수(6)\n\n #=====페이지버튼의 숫자 바꾸기================================================\n if BTNnum == \"<<\":\n if nowpageA != 0:\n for i in range(1,len(POPADDBTNLIST)):\n if nowpageA != \"1\": #1-10은 \"<<\"버튼은 작동 안하기에\n POPADDBTNLIST[i].text = str((nowpageA-1)*10+i)\n POPADDBTNLIST[i].background_color=winColor\n POPADDBTNLIST[i].color=textColor\n if i == 11:#\n POPADDBTNLIST[i].text = \">>\"\n POPADDBTNLIST[i].background_color=winColor\n POPADDBTNLIST[i].color=textColor\n endIndex = int(POPADDBTNLIST[1].text)*FIXROW\n elif BTNnum == \">>\":\n if pageSetLISTNOpopadd == nowpageA+1:#userlist의 dir수의 페이지번호까지만 보여주기\n #print(f\"BTN set: pageSetNO{pageSetLISTNOpopadd},nowpageA{nowpageA}\")\n for i in range(1,len(POPADDBTNLIST)):\n POPADDBTNLIST[i].text = str((nowpageA+1)*10+i)#페이지버튼의 번호바꾸기\n if i > lastPageLISTNOpopadd:#마지막페이지일 경우, 남은 userlist의 dir수만큼만 화면에 보여주기\n POPADDBTNLIST[i].background_color=[0,0,0,0]\n POPADDBTNLIST[i].color=[0,0,0,0]\n else:#페이지버튼의 번호바꾸기\n for i in range(1,len(POPADDBTNLIST)):\n POPADDBTNLIST[i].text = str((nowpageA+1)*10+i)\n POPADDBTNLIST[i].background_color=winColor\n POPADDBTNLIST[i].color=textColor\n if i == 11:#\">>\" 바뀌지 않도로\n POPADDBTNLIST[i].text = \">>\"\n POPADDBTNLIST[i].background_color=winColor\n POPADDBTNLIST[i].color=textColor\n endIndex = int(POPADDBTNLIST[1].text)*FIXROW\n else:\n endIndex = int(BTNnum)*FIXROW\n startIndex = endIndex - (FIXROW-1)\n\n #=====화면 리셋===========================================================\n count = 0\n self.layoutpop1_middle.clear_widgets()\n\n for i in range(startIndex,endIndex+1):#그때그때 인덱스를 지정, 보여줄 화면\n if str(BTNnum) == str(pageLISTNOpopadd) and lastLISTNOpopadd != 0:\n sub = (FIXROW-lastLISTNOpopadd)\n overIndex = endIndex-sub\n if i > overIndex:#마지막페이지의 userlist dir수보다 i 가 크면, 위젯을 안보이도록 처리\n self.userListLabel=Label(font_name=todayFont,font_size=text_fontsize,text = f'',halign=\"left\",valign=\"top\",size_hint=(0.9, 0.2), color=[0,0,0,0])\n self.checkboxBtn=CheckBox(size_hint=(0.1, 0.2),color=[0,0,0,0])\n else:#POPLISTS 의 인덱스가 i임을 유의, POPLISTSTEXT,POPLISTSDIC의 인덱스는 count임을 유의\n self.userListLabel=Label(font_name=todayFont,font_size=text_fontsize,text = f'{i+1}. {POPLISTS[str(i)]}',halign=\"left\",valign=\"top\",size_hint=(0.9, 0.2), color=[1,1,1,1])\n self.checkboxBtn=CheckBox(size_hint=(0.1, 0.2),color=[0,0,0,1])\n\n self.checkboxBtn.bind(active=self.checked_userlist)\n POPLISTSTEXT[count][0] = f'{POPLISTS[str(i)]}'\n POPLISTSDIC[POPLISTSTEXT[count][0]]=self.checkboxBtn\n else:\n self.userListLabel=Label(font_name=todayFont,font_size=text_fontsize,text = f'{i+1}. {POPLISTS[str(i)]}',halign=\"left\",valign=\"top\",size_hint=(0.9, 0.2), color=[1,1,1,1])\n self.checkboxBtn=CheckBox(size_hint=(0.1, 0.2),color=[0,0,0,1])\n\n self.checkboxBtn.bind(active=self.checked_userlist)\n POPLISTSTEXT[count][0] = f'{POPLISTS[str(i)]}'\n POPLISTSDIC[POPLISTSTEXT[count][0]]=self.checkboxBtn\n\n self.layoutpop1_middle.add_widget(self.userListLabel)\n self.layoutpop1_middle.add_widget(self.checkboxBtn)\n count+=1\n\n #==============체크박스에 체크된 곡 알기위한 함수====================================\n def checked_userlist(self, checkbox, yes_check):\n global userTitleList\n userTitleList = []\n\n if yes_check:\n if checkbox not in CHECKEDUSERLIST:\n CHECKEDUSERLIST.append(checkbox)\n else:\n if checkbox in CHECKEDUSERLIST:\n CHECKEDUSERLIST.remove(checkbox)\n\n for i in range(len(POPLISTSTEXT)):\n if POPLISTSDIC[POPLISTSTEXT[i][0]] in CHECKEDUSERLIST:\n thisTitle = POPLISTSTEXT[i][0]\n if thisTitle not in userTitleList:\n userTitleList.append(thisTitle)\n\n elif POPLISTSDIC[POPLISTSTEXT[i][0]] not in CHECKEDUSERLIST:\n thisTitle = POPLISTSTEXT[i][0]\n if thisTitle in userTitleList:\n userTitleList.remove(thisTitle)\n\n\n #print(f'yes_check:{yes_check}, checkbox:{checkbox}, userTitleList:{userTitleList}')\n\n #==============\"+\"버튼 클릭시, userlist에 곡추가위한 함수==========================\n def add_pressed(self,obj):\n titleList = []\n #thisTitle=''\n try:\n for i in range(len(SONGNOWLISTSTEXT)):\n if SONGNOWLISTSDIC[SONGNOWLISTSTEXT[i][2]] in CHECKEDSONG:\n thisTitle = SONGNOWLISTSTEXT[i][0]\n #print(f'yescheck {thisTitle}\\n')\n if thisTitle not in titleList:\n titleList.append(thisTitle)\n # print(f'yestitle add {thisTitle}\\n')\n elif SONGNOWLISTSDIC[SONGNOWLISTSTEXT[i][2]] not in CHECKEDSONG:\n thisTitle = SONGNOWLISTSTEXT[i][0]\n #print(f'nocheck {thisTitle}\\n')\n if thisTitle in titleList:\n titleList.remove(thisTitle)\n #print(f'notitle removed {thisTitle}\\n')\n #print(f'titleList:{titleList}')\n #print(f'userTitleList:{userTitleList},titleList:{titleList}')\n sbu.copy_checkedsongTOuserlist(userTitleList,titleList)\n except Exception as msg:\n print(f\"{msg}retry.\")\n\n self.addUserlistPopup.dismiss()\n\n #==============체크되었었던 곡 알기위한 함수========================================\n def checked_song(self, checkbox, yes_check):\n if yes_check:\n #print(f\"yes:{checkbox}\")\n if checkbox not in CHECKEDSONG:\n CHECKEDSONG.append(checkbox)\n #print(f\"yes,append:{checkbox}\")\n else:\n if checkbox in CHECKEDSONG:\n CHECKEDSONG.remove(checkbox)\n #print(f\"remove:{checkbox}\")\n #print(f\"checked song:{CHECKEDSONG}\")\n\n #==============체크된곡 재생===================================================\n def play_checkedSong(self):\n global playTitle,playing #playing은 재생곡의 위젯\n\n playTitle = []\n playing = []\n\n SONGNOWLISTSDIC[''] ='' #화면리셋오류때문에 범위 FIXROW로 고정->list 고정길이('')주느라-> dic에도('') 임의값 줌\n\n try:\n for i in range(SONGROWNUM):\n if SONGNOWLISTSDIC[SONGNOWLISTSTEXT[i][2]] in CHECKEDSONG:\n thisTitle = SONGNOWLISTSTEXT[i][0]\n #print(f'yescheck {thisTitle}\\n')\n if thisTitle not in playTitle:\n playTitle.append(thisTitle)\n playing.append(SONGNOWLISTSDIC[SONGNOWLISTSTEXT[i][0]])\n\n #print(f'yestitle add {thisTitle}\\n')\n elif SONGNOWLISTSDIC[SONGNOWLISTSTEXT[i][2]] not in CHECKEDSONG:\n thisTitle = SONGNOWLISTSTEXT[i][0]\n # print(f'nocheck {thisTitle}\\n')\n if thisTitle in playTitle:\n playTitle.remove(thisTitle)\n playing.remove(SONGNOWLISTSDIC[SONGNOWLISTSTEXT[i][0]])\n\n #print(f\"playTitle:{playTitle}\")\n playnum=0\n thread_one = threading.Thread(target=sbp.get_playThread, args=(playTitle,playing,PLAY_BTN,PLAY_BTN,playnum), daemon=True)\n thread_one.start()\n\n except Exception as msg:\n print(f\"{msg}retry.\")\n\n #==============한곡만 재생하는 thread 시작(무한루프로 재생)==========================\n def play_oneSong(self, playBtn):\n global playTitle,playing,TITLE_BTN\n TITLE_BTN = playBtn\n\n PAUSE_BTN.text = \"|||\"\n PAUSE_BTN.color = boxColor\n PAUSE_BTN.texture_update()\n\n playTitle=[]\n playing = []\n\n for i in range(len(SONGNOWLISTSTEXT)):\n if SONGNOWLISTSDIC[SONGNOWLISTSTEXT[i][0]] == TITLE_BTN:\n thisTitle = SONGNOWLISTSTEXT[i][0]\n playing.append(TITLE_BTN)\n break\n try:\n playTitle.append(thisTitle)\n #print(f\"playTitle:{playTitle}\")\n\n sbp.get_quit()\n time.sleep(1)\n\n playnum=0\n thread_one = threading.Thread(target=sbp.get_playThread, args=(playTitle,playing,PLAY_BTN,TITLE_BTN,playnum), daemon=True)\n thread_one.start()\n\n except Exception as msg:\n print(f\"{msg}retry.\")\n #print(playTitle)\n\n#==============(Scroll)class ScreenSinger=======================================\nclass ScreenSinger(Screen):\n def __init__(self, **kwargs):\n super(ScreenSinger, self).__init__(**kwargs)\n self.name = \"screen_singer\"\n global SINGER_NOWLISTS, SINGER_NOWLISTSTEXT, SINGER_NOWLISTSDIC, SINGER_CHECKBOXLISTS, CHECKEDSINGER, CHECKEDSINGERLIST\n SINGER_NOWLISTS = sbs.show_singer()#singerlist 목록 불러오기\n SINGER_NOWLISTS.sort()\n listNum = len(SINGER_NOWLISTS)\n\n SINGER_NOWLISTSTEXT = [['']*3 for x in range(listNum)]#저장한위젯저장\n SINGER_NOWLISTSDIC = {}#저장한위젯호출위해저장\n\n SINGER_CHECKBOXLISTS = [''] * listNum#체크박스\n\n CHECKEDSINGER = []\n CHECKEDSINGERLIST = []\n\n self.base1 = BoxLayout(padding=5,spacing=5,size_hint=(1,1), orientation = 'vertical')\n self.add_widget(self.base1)\n\n self.drawMylist()\n\n #==============draw widgets=================================================\n def drawMylist(self):\n global SINGER_NOWLISTSTEXT, SINGER_CHECKBOXLISTS\n SINGER_NOWLISTS = sbs.show_singer()#singerlist 목록 불러오기\n SINGER_NOWLISTS.sort()\n listNum = len(SINGER_NOWLISTS)\n\n #==============새 가수 추가된 경우, widget reset 시 오류 방지(scroll view라서)===\n if listNum > len(SINGER_NOWLISTSTEXT):\n SINGER_NOWLISTSTEXT = [['']*3 for x in range(listNum)]#저장한위젯저장\n SINGER_CHECKBOXLISTS = [''] * listNum#체크박스\n\n self.layout1_top = GridLayout(rows=1,cols=9,padding=5,spacing=5,size_hint=(1, 0.05))\n\n self.layout1_middle = GridLayout(rows=listNum,cols=9,padding=5,spacing=5,size_hint_y=None)\n self.layout1_middle.bind(minimum_height=self.layout1_middle.setter('height'),minimum_width=self.layout1_middle.setter('width'))\n\n#####playBtn은 아직 기능 안줌\n self.titleEmptyLabel1=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\", size_hint_y=None, height=55)\n self.titleEmptyLabel2=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\", size_hint_y=None, height=55)\n self.titleEmptyLabel3=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\", size_hint_y=None, height=55)\n self.topLabel=Label(font_name=todayFont,font_size =menu_fontsize,text ='Singer List',halign=\"left\",valign=\"top\", size_hint_y=None, height=55)#,color=boxColor)\n self.titleEmptyLabel4=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\", size_hint_y=None, height=55)\n self.titleEmptyLabel5=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\", size_hint_y=None, height=55)\n self.playBtn = Button(font_name=todayFont,font_size =menu_fontsize,text=\"???\", size_hint_y=None, height=55, background_normal = \"\", background_down = \"\",background_color=[0,0,0,0],color=[0,0,0,0])\n self.titleEmptyLabel6=Label(font_name=todayFont,text ='',font_size=30,halign=\"left\",valign=\"top\", size_hint_y=None, height=55)\n\n #####self.playBtn.bind(on_press = self.)\n\n self.layout1_top.add_widget(self.titleEmptyLabel1)\n self.layout1_top.add_widget(self.titleEmptyLabel2)\n self.layout1_top.add_widget(self.topLabel)\n self.layout1_top.add_widget(self.titleEmptyLabel3)\n self.layout1_top.add_widget(self.titleEmptyLabel4)\n self.layout1_top.add_widget(self.titleEmptyLabel5)\n self.layout1_top.add_widget(self.playBtn)\n self.layout1_top.add_widget(self.titleEmptyLabel6)\n\n for i in range(listNum):\n self.emptyLabel1=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\", size_hint_y=None, height=55)\n self.singerListBtn=Button(font_name=todayFont,font_size =text_fontsize,text=f'{SINGER_NOWLISTS[i]}', size_hint_y=None, height=55, background_normal = \"\", background_down = \"\",background_color=[0,0,0,0],color=textColor)\n self.emptyLabel2=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint_y=None, height=55)\n self.emptyLabel3=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint_y=None, height=55)\n self.emptyLabel4=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint_y=None, height=55)\n self.checkBox=CheckBox(size_hint=(1, 0.2),color=textColor,size_hint_y=None, height=55)\n self.emptyLabel6=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint_y=None, height=55)\n self.showBtn = Button(font_name=todayFont,font_size =text_fontsize,text=\"show\", size_hint_y=None, height=55, background_normal = \"\",background_color=boxColor,color=textColor)\n self.emptyLabel7=Label(font_name=todayFont,text ='',halign=\"left\",valign=\"top\",size_hint_y=None, height=55)\n\n\n SINGER_NOWLISTSTEXT[i][0] = f'{SINGER_NOWLISTS[i]}'\n SINGER_NOWLISTSTEXT[i][1] = f'{SINGER_NOWLISTS[i]}+add/sub'\n SINGER_NOWLISTSTEXT[i][2] = f'{SINGER_NOWLISTS[i]}+checkbox'\n\n self.checkBox.bind(active=self.checked_song)\n self.singerListBtn.bind(on_press=self.play_singerlist)#singerlist의 곡 재생을 위한 함수 호출\n self.showBtn.bind(on_press=self.open_singerSongPopup)#singerlist의 곡 보기\n\n SINGER_NOWLISTSDIC[SINGER_NOWLISTSTEXT[i][0]]=self.singerListBtn\n SINGER_NOWLISTSDIC[SINGER_NOWLISTSTEXT[i][1]]=self.showBtn\n SINGER_NOWLISTSDIC[SINGER_NOWLISTSTEXT[i][2]]=self.checkBox\n\n self.layout1_middle.add_widget(self.emptyLabel1)\n self.layout1_middle.add_widget(self.singerListBtn)\n self.layout1_middle.add_widget(self.emptyLabel2)\n self.layout1_middle.add_widget(self.emptyLabel3)\n self.layout1_middle.add_widget(self.emptyLabel4)\n self.layout1_middle.add_widget(self.checkBox)\n self.layout1_middle.add_widget(self.emptyLabel6)\n self.layout1_middle.add_widget(self.showBtn)\n self.layout1_middle.add_widget(self.emptyLabel7)\n\n #==============singerlist scroll========================================\n self.scroll = ScrollView(smooth_scroll_end=10,scroll_type=['bars'],bar_width='3dp', scroll_wheel_distance=100, do_scroll_x = False, do_scroll_y = True)\n self.scroll.bar_color = boxColor\n #self.scroll.size_hint_min = (100,500)\n #self.scroll.size=(Window.width, Window.height)\n self.scroll.size_hint=(1, 1)\n #self.scroll.size_hint_y = None\n #self.scroll.padding= 10, 10\n\n self.scroll.add_widget(self.layout1_middle)\n\n self.base1.add_widget(self.layout1_top)\n self.base1.add_widget(self.scroll)\n\n #==============가수의 곡 목록 보기==============================================\n def open_singerSongPopup(self, obj):\n\n for i in range(len(SINGER_NOWLISTSTEXT)):\n if SINGER_NOWLISTSDIC[SINGER_NOWLISTSTEXT[i][1]] == obj:#클릭한 edit obj의 singerlist파악위해\n singer = SINGER_NOWLISTSTEXT[i][0]#singerlist이름저장\n\n singerlist = sbs.show_onerSinger(singer)\n singerlist.sort()\n songNum = len(singerlist)\n\n self.singerSongPopup = Popup(title='',\n size_hint=(0.5, 0.4), size=(800, 800),auto_dismiss=True,\n title_font=todayFont,title_size=menu_fontsize, title_align='center',\n title_color=textColor,\n separator_height=0.5,\n separator_color=textColor)\n\n self.basepop = BoxLayout(padding=5,spacing=5,size_hint=(1,None), orientation = 'vertical')\n self.basepop.bind(minimum_height=self.basepop.setter('height'),minimum_width=self.basepop.setter('width'))\n\n self.layoutpop_top = GridLayout(rows=1,cols=1,padding=5,spacing=5,size_hint_y=None)\n self.popText=Label(font_name=todayFont,font_size=menu_fontsize,text = f'{singer} Song List.',size_hint_y=None, height=40,color=textColor)\n self.layoutpop_top.add_widget(self.popText)\n\n\n self.layoutpop_middle = GridLayout(rows=songNum,cols=1,padding=5,spacing=5,size_hint_y=None)\n\n for i in range(songNum):\n title = singerlist[i].split(\".wav\")\n self.singerListLabel=Label(font_name=todayFont,font_size=text_fontsize,text = f'{title[0]}',halign=\"left\",valign=\"top\",size_hint_y=None, height=40,color=[1,1,1,1])\n self.layoutpop_middle.add_widget(self.singerListLabel)\n\n self.basepop.add_widget(self.layoutpop_top)\n self.basepop.add_widget(self.layoutpop_middle)\n\n #==============singerlist scroll========================================\n self.scroll = ScrollView(smooth_scroll_end=10,scroll_type=['bars'],bar_width='3dp', scroll_wheel_distance=100, do_scroll_x = False, do_scroll_y = True)\n self.scroll.bar_color = boxColor\n #self.scroll.size_hint_min = (100,500)\n #self.scroll.size=(Window.width, Window.height)\n self.scroll.size_hint=(1,1)\n #self.scroll.size_hint_y = None\n #self.scroll.padding= 10, 10\n self.scroll.add_widget(self.basepop)\n\n self.singerSongPopup.add_widget(self.scroll)\n self.singerSongPopup.open()\n\n #==============체크된 가수 알기위한 함수==========================================\n def checked_song(self, checkbox, yes_check):\n if yes_check:\n print(f\"yes:{checkbox}\")\n if checkbox not in CHECKEDSINGER:\n CHECKEDSINGER.append(checkbox)\n print(f\"yes,append:{checkbox}\")\n else:\n if checkbox in CHECKEDSINGER:\n CHECKEDSINGER.remove(checkbox)\n print(f\"remove:{checkbox}\")\n print(f\"checked song:{CHECKEDSINGER}\")\n\n #==============체크된 가수 재생=================================================\n def play_checkedSinger(self, obj):\n global playTitle,playing #playing은 재생곡의 위젯\n\n SINGER_NOWLISTS = sbs.show_singer()#singerlist 목록 불러오기\n SINGER_NOWLISTS.sort()\n listNum = len(SINGER_NOWLISTS)#singerlist 개수\n\n singerList = []\n playTitle = []\n playing = []\n\n try:\n for i in range(listNum):\n if SINGER_NOWLISTSDIC[SINGER_NOWLISTSTEXT[i][2]] in CHECKEDSINGER:\n thisSinger = SINGER_NOWLISTSTEXT[i][0]\n print(f'yescheck {thisSinger}\\n')\n\n if thisSinger not in singerList:\n singerList.append(thisSinger)\n for j in os.listdir(f'{singerListDir}/{thisSinger}'):\n if j not in ignoreFile:\n playTitle.append(j)\n playing.append(SINGER_NOWLISTSDIC[SINGER_NOWLISTSTEXT[i][0]])\n\n print(f'yestitle add {j}\\n')\n elif SINGER_NOWLISTSDIC[SINGER_NOWLISTSTEXT[i][2]] not in CHECKEDSINGER:\n thisSinger = SINGER_NOWLISTSTEXT[i][0]\n print(f'nocheck {thisSinger}\\n')\n if thisSinger in singerList:\n singerList.remove(thisSinger)\n for j in os.listdir(f'{singerListDir}/{thisSinger}'):\n if j not in ignoreFile:\n playTitle.remove(j)\n playing.remove(SINGER_NOWLISTSDIC[SINGER_NOWLISTSTEXT[i][0]])\n print(f'del {j}\\n')\n\n print(f\"playTitle:{playTitle},playing:{playing}\")\n\n playnum=0\n thread_one = threading.Thread(target=sbp.get_playThread, args=(playTitle,playing,PLAY_BTN,PLAY_BTN,playnum), daemon=True)\n thread_one.start()\n\n except Exception as msg:\n print(f\"{msg}retry.\")\n\n #==============클릭된 가수 재생=================================================\n def play_singerlist(self, playBtn):\n global playTitle,playing #playing은 재생곡의 위젯\n #print(f\"userlist_playing:{playing}\")\n PAUSE_BTN.text = \"|||\"\n PAUSE_BTN.color = boxColor\n PAUSE_BTN.texture_update()\n\n playTitle = []\n playList = []\n playing = []\n\n for i in range(len(SINGER_NOWLISTSTEXT)):\n if SINGER_NOWLISTSDIC[SINGER_NOWLISTSTEXT[i][0]] == playBtn:\n thisSinger = SINGER_NOWLISTSTEXT[i][0]\n playTitle = os.listdir(f\"{singerListDir}/{thisSinger}\")\n playing.append(playBtn)\n break\n print(f\"playTitle:{playTitle}\")\n playTitle.sort()\n\n for i in playTitle:\n if i in ignoreFile:\n playTitle.remove(i)\n print(f\"playTitle:{playTitle}\")\n\n sbp.get_quit()\n time.sleep(1)\n\n playnum = 0\n thread_one = threading.Thread(target = sbp.get_playThread, args = (playTitle,playing,PLAY_BTN,playBtn,playnum), daemon=True)\n thread_one.start()\n\n\n#==============화면관리메니저클래스===================================================\nclass Manager(ScreenManager):\n def __init__(self, **kwargs):\n super(Manager, self).__init__(**kwargs)\n self.screen_main = ScreenMain(name=\"screen_main\", size_hint = (0.9, 1))\n self.screen_setting = ScreenSetting(name=\"screen_setting\", size_hint = (0.9, 1))\n self.screen_song = ScreenSong(name=\"screen_song\", size_hint = (0.9, 1))\n self.screen_singer = ScreenSinger(name=\"screen_singer\", size_hint = (0.9, 1))\n self.add_widget(self.screen_main)\n self.add_widget(self.screen_setting)\n self.add_widget(self.screen_song)\n self.add_widget(self.screen_singer)\n\n#################################################################################\nclass songBox_kvPyaudio(App):\n global manager, soundbar,upperMenu\n proc = os.getpid()\n #print(\"songBox_kv: \",proc)\n Window.clearcolor = winColor\n manager = Manager()\n soundbar = SoundBarMenu(size_hint = (1,1))\n upperMenu = UpperMenu(size_hint = (0.1,1))\n\n def build(self):\n proc = os.getpid()\n #print(\"Appbuild: \", proc)\n self.root = Root(orientation = \"vertical\")\n self.root1 = Root(orientation = \"horizontal\",size_hint = (1,0.1), spacing = 10)#spacing = 10\n self.root2 = Root(orientation = \"horizontal\",size_hint = (1,0.9))\n\n self.root1.add_widget(soundbar)\n\n #upperMenu = UpperMenu(size_hint = (0.1,1))\n\n self.root2.add_widget(upperMenu)\n self.root2.add_widget(manager)\n\n self.root.add_widget(self.root1)\n self.root.add_widget(self.root2)\n\n return self.root\n#def show_screen_main(self,obj):\n# manager.current = \"screen_main\"\n# def show_screen_setting(self, obj):\n #print(self,obj)\n# manager.current = \"screen_setting\"\n# def show_screen_song(self,obj):\n# manager.current = \"screen_song\"\n# def show_screen_three(self,obj):\n# manager.current = \"Class3\"\n# def show_clear(self):\n# manager.clear_widgets()\n# manager.screen_main.clear_widgets()\n# manager.screen_setting.clear_widgets()\n# manager.screen_song.clear_widgets()\n# manager.screen_singer.clear_widgets()\n# def show_remove(self,obj):\n# manager.remove_widget(manager.screen_main)\n# manager.remove_widget(manager.screen_setting)\n# manager.remove_widget(manager.screen_song)\n# manager.remove_widget(manager.screen_singer)\n################################################################################\nif __name__ == '__main__':\n proc = os.getpid()\n print(\"AppSTart: \", proc)\n\n syncList=sbl.sync_song()\n sbs.make_singerDic()\n\n songBox_kvPyaudio().run()\n","sub_path":"MAC/songBox_kvPyaudio.py","file_name":"songBox_kvPyaudio.py","file_ext":"py","file_size_in_byte":136186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"164179441","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass DiskEncryptionSettings(Model):\n \"\"\"Describes a Encryption Settings for a Disk.\n\n :param disk_encryption_key: Specifies the location of the disk encryption\n key, which is a Key Vault Secret.\n :type disk_encryption_key:\n ~azure.mgmt.compute.v2016_03_30.models.KeyVaultSecretReference\n :param key_encryption_key: Specifies the location of the key encryption\n key in Key Vault.\n :type key_encryption_key:\n ~azure.mgmt.compute.v2016_03_30.models.KeyVaultKeyReference\n :param enabled: Specifies whether disk encryption should be enabled on the\n virtual machine.\n :type enabled: bool\n \"\"\"\n\n _attribute_map = {\n 'disk_encryption_key': {'key': 'diskEncryptionKey', 'type': 'KeyVaultSecretReference'},\n 'key_encryption_key': {'key': 'keyEncryptionKey', 'type': 'KeyVaultKeyReference'},\n 'enabled': {'key': 'enabled', 'type': 'bool'},\n }\n\n def __init__(self, disk_encryption_key=None, key_encryption_key=None, enabled=None):\n super(DiskEncryptionSettings, self).__init__()\n self.disk_encryption_key = disk_encryption_key\n self.key_encryption_key = key_encryption_key\n self.enabled = enabled\n","sub_path":"azure-mgmt-compute/azure/mgmt/compute/v2016_03_30/models/disk_encryption_settings.py","file_name":"disk_encryption_settings.py","file_ext":"py","file_size_in_byte":1703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"402152991","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# @Date : 2018-06-02 16:41:35\r\n# @Author : Chen Cjv (cjvaely@foxmail.com)\r\n# @Link : https://github.com/Cjvaely\r\n# @Version : $Id$\r\n\r\n# 错误处理\r\nfrom functools import reduce\r\n\r\n\r\ndef str2num(s):\r\n try:\r\n return int(s)\r\n except ValueError as e:\r\n print('Error:', e)\r\n return float(s)\r\n\r\n\r\ndef calc(exp):\r\n ss = exp.split('+')\r\n ns = map(str2num, ss)\r\n return reduce(lambda acc, x: acc + x, ns)\r\n\r\n\r\ndef main():\r\n r = calc('100 + 200 + 345')\r\n print('100 + 200 + 345 =', r)\r\n r = calc('99 + 88 + 7.6')\r\n print('99 + 88 + 7.6 =', r)\r\n\r\n\r\nmain()\r\n","sub_path":"LiaoPython/ErrorOperation.py","file_name":"ErrorOperation.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"305245093","text":"\"\"\"\n\narr=[1,0,1,0,1]\n\nnumber_of_ones in array 3\n\npre_compute_array [1, 1, 2, 2, 3]\n\nA simple solution is to first count total number of 1’s in the array. Suppose this count is x, now we need to find the subarray of length x of this array with maximum number of 1’s. And minimum swaps required will be the number of 0’s in the subarray of length x with maximum number of 1’s.\nTime Complexity: O(n2)\n\nAn efficient solution is to optimize the brute force technique of finding the subarray in above approach using the concept of sliding window technique. We can maintain a preCount array to find number of 1’s present in a subarray in O(1) time complexity.\n\n\n\"\"\"\n\ndef find_min_swaps_sliding_window_without_precompute(arr):\n print ('*****************')\n print ('input arr',arr)\n number_of_ones=0\n for i in range(0,len(arr)):\n if arr[i] ==1:\n number_of_ones+=1\n\n print ('number_of_ones in array',number_of_ones)\n k=number_of_ones\n cnt=0\n for i in range(0,k):\n if arr[i]==1:\n cnt+=1\n max_cnt=cnt\n \n n = len(arr)\n for i in range(k,n):\n if arr[i-k]==1:\n cnt-=1\n if arr[i]==1:\n cnt+=1\n max_cnt= max(max_cnt,cnt)\n\n number_of_not_ones=k-max_cnt\n\n print ('number of swaps', number_of_not_ones)\n\n \narr=[1,0,1,0,1]\n\nfind_min_swaps_sliding_window_without_precompute(arr)\n\n\narr=[0,1,0,0,1,0,0,1]\n\nfind_min_swaps_sliding_window_without_precompute(arr)\n\narr=[0,1,0,0,1,0,1,1]\n\nfind_min_swaps_sliding_window_without_precompute(arr)\n\narr=[0,1,0,0,1,0,0,1]\n\nfind_min_swaps_sliding_window_without_precompute(arr)\n\narr=[0,1,1,1,0,0,0,0]\n\nfind_min_swaps_sliding_window_without_precompute(arr)\n\ndef find_min_swaps(arr):\n number_of_ones=0\n for i in range(0,len(arr)):\n if arr[i] ==1:\n number_of_ones+=1\n\n print ('number_of_ones in array',number_of_ones)\n \n pre_compute_array=[None]*len(arr)\n \n if arr[0]==1:\n pre_compute_array[0]=1\n else:\n pre_compute_array[0]=0\n\n for i in range(1,len(arr)):\n if arr[i]==1:\n pre_compute_array[i]= pre_compute_array[i-1] +1\n else:\n pre_compute_array[i]= pre_compute_array[i-1]\n \n print ('pre_compute_array',pre_compute_array)\n\n max_subaarray_needed_size=number_of_ones\n # if we need subarray of size 3, we need to look \n # at sliding windows ending at index 2\n # 1st window is from index 0 to 2, 2nd window is from index 1 to 3\n # 3rd window is from index 2 to 4\n\n max_number_of_ones_in_each_sliding_window = -1000000\n\n for i in range(max_subaarray_needed_size-1,len(arr)):\n # for inital window\n if i == max_subaarray_needed_size-1 :\n number_of_ones_in_this_window=pre_compute_array[i]\n else:\n number_of_ones_in_this_window= pre_compute_array[i] - pre_compute_array[i-max_subaarray_needed_size]\n if number_of_ones_in_this_window > max_number_of_ones_in_each_sliding_window:\n max_number_of_ones_in_each_sliding_window = number_of_ones_in_this_window\n\n # number of swaps is the number of zeroes in the sliding window with most ones\n # calculate number of zeros in subarray \n # of length x with maximum number of 1's \n \n number_of_not_ones=number_of_ones-max_number_of_ones_in_each_sliding_window\n\n print ('number of swaps', number_of_not_ones)\n \n\n \n\n\n#arr=[1,0,1,0,1]\n\n#find_min_swaps(arr)\n\n\n\n#arr=[0,1,0,0,1,0,0,1]\n\n#find_min_swaps(arr)\n \n","sub_path":"new_pract/minimum_swaps_required_to_move_ones_together.py","file_name":"minimum_swaps_required_to_move_ones_together.py","file_ext":"py","file_size_in_byte":3493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"309418999","text":"#!/usr/bin/python\n#\n# Copyright (c) 2013 Mikkel Schubert \n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\nimport os\nimport multiprocessing\n\nimport paleomix\nimport paleomix.common.logging\n\nfrom paleomix.common.argparse import ArgumentParser\n\n\n_DESCRIPTION = (\n \"Commands:\\n\"\n \" -- %prog help -- Display this message.\\n\"\n \" -- %prog example [...] -- Copy example project to folder.\\n\"\n \" -- %prog makefile -- Print makefile template.\\n\"\n \" -- %prog genotype [...] -- Carry out genotyping according to makefile.\\n\"\n \" -- %prog msa [...] -- Carry out multiple sequence alignment.\\n\"\n \" -- %prog phylogeny [...] -- Carry out phylogenetic inference.\\n\"\n)\n\n_DEFAULT_CONFIG_FILES = [\n \"/etc/paleomix/phylo_pipeline.ini\",\n \"~/.paleomix/phylo_pipeline.ini\",\n]\n\n\ndef build_parser():\n parser = ArgumentParser(\n prog=\"paleomix phylo_pipeline\",\n description=_DESCRIPTION,\n default_config_files=_DEFAULT_CONFIG_FILES,\n )\n parser.add_argument(\n \"commands\",\n type=lambda it: [_f.strip() for _f in it.split(\"+\") if _f.strip()],\n help=\"One or more commands separated by '+'\",\n )\n parser.add_argument(\n \"files\", nargs=\"*\", help=\"One or more commands separated by '+'\"\n )\n\n parser.add_argument(\n \"--version\", action=\"version\", version=\"%(prog)s v\" + paleomix.__version__,\n )\n\n paleomix.common.logging.add_argument_group(parser, default=\"warning\")\n\n group = parser.add_argument_group(\"Scheduling\")\n group.add_argument(\n \"--examl-max-threads\",\n default=1,\n type=int,\n help=\"Maximum number of threads to use for each instance of ExaML [%(default)s]\",\n )\n group.add_argument(\n \"--max-threads\",\n type=int,\n default=max(2, multiprocessing.cpu_count()),\n help=\"Max number of threads to use in total [%(default)s]\",\n )\n group.add_argument(\n \"--dry-run\",\n default=False,\n action=\"store_true\",\n help=\"If passed, only a dry-run in performed, the dependency tree is printed, \"\n \"and no tasks are executed.\",\n )\n\n group = parser.add_argument_group(\"Required paths\")\n group.add_argument(\n \"--temp-root\",\n default=\"./temp\",\n type=os.path.abspath,\n help=\"Location for temporary files and folders [%(default)s]\",\n )\n group.add_argument(\n \"--samples-root\",\n default=\"./data/samples\",\n help=\"Location of BAM files for each sample [%(default)s]\",\n )\n group.add_argument(\n \"--regions-root\",\n default=\"./data/regions\",\n help=\"Location of BED files containing regions of interest [%(default)s]\",\n )\n group.add_argument(\n \"--prefix-root\",\n default=\"./data/prefixes\",\n help=\"Location of prefixes (FASTAs) [%(default)s]\",\n )\n group.add_argument(\n \"--refseq-root\",\n default=\"./data/refseqs\",\n help=\"Location of reference sequences (FASTAs) [%(default)s]\",\n )\n group.add_argument(\n \"--destination\",\n default=\"./results\",\n help=\"The destination folder for result files [%(default)s]\",\n )\n\n group = parser.add_argument_group(\"Files and executables\")\n group.add_argument(\n \"--list-input-files\",\n action=\"store_true\",\n default=False,\n help=\"List all input files used by pipeline for the \"\n \"makefile(s), excluding any generated by the \"\n \"pipeline itself.\",\n )\n group.add_argument(\n \"--list-output-files\",\n action=\"store_true\",\n default=False,\n help=\"List all output files generated by pipeline for \" \"the makefile(s).\",\n )\n group.add_argument(\n \"--list-executables\",\n action=\"store_true\",\n default=False,\n help=\"List all executables required by the pipeline, \"\n \"with version requirements (if any).\",\n )\n\n return parser\n","sub_path":"paleomix/pipelines/phylo/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":4956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"338251174","text":"import FWCore.ParameterSet.Config as cms\n\n# Z2 star tune with pT-ordered showers\nfrom Configuration.Generator.PythiaUEZ2starSettings_cfi import *\nfrom GeneratorInterface.ExternalDecays.TauolaSettings_cff import *\n\ngenerator = cms.EDFilter(\n \"Pythia6HadronizerFilter\",\n pythiaPylistVerbosity = cms.untracked.int32(1),\n filterEfficiency = cms.untracked.double(1.0),\n pythiaHepMCVerbosity = cms.untracked.bool(False),\n comEnergy = cms.double(8000.0),\n maxEventsToPrint = cms.untracked.int32(0),\n ExternalDecays = cms.PSet(\n Tauola = cms.untracked.PSet(\n TauolaPolar,\n TauolaDefaultInputCards\n ),\n parameterSets = cms.vstring('Tauola')\n ),\n PythiaParameters = cms.PSet(\n pythiaUESettingsBlock, \n processParameters = cms.vstring(\n 'MSEL=0 ! User defined processes', \n 'PMAS(5,1)=4.75 ! b quark mass', \n 'PMAS(6,1)=172.5 ! t quark mass',\n \n 'CKIN(41)=4. !low mass cut on Z1',\n 'CKIN(43)=4. !low mass cut on Z2'\n ),\n parameterSets = cms.vstring(\n 'pythiaUESettings', \n 'processParameters'\n )\n )\n )\n\nconfigurationMetadata = cms.untracked.PSet(\n version = cms.untracked.string('$Revision: 1.1 $'),\n name = cms.untracked.string('$Source: /cvs/CMSSW/CMSSW/Configuration/GenProduction/python/EightTeV/POWHEG_PYTHIA6_Tauola_ZZ_4l_mll4_8TeV_cff.py,v $'),\n annotation = cms.untracked.string('POWHEG + PYTHIA6 + Tauola - Higgs -> ZZ -> 4l at 8TeV')\n )\n","sub_path":"genfragments/EightTeV/POWHEG_PYTHIA6_Tauola_ZZ_4l_mll4_8TeV_cff.py","file_name":"POWHEG_PYTHIA6_Tauola_ZZ_4l_mll4_8TeV_cff.py","file_ext":"py","file_size_in_byte":1605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"232620724","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nimport sklearn\nimport numpy as np\nimport pandas as pd\n\nget_ipython().run_line_magic('matplotlib', 'inline')\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\n# In[2]:\n\n\nfeature_text='label, lepton pT, lepton eta, lepton phi, lost energy mag, lost energy phi, jet 1 pt, jet 1 eta, jet 1 phi, jet 1 b-tag, jet 2 pt, jet 2 eta, jet 2 phi, jet 2 b-tag, jet 3 pt, jet 3 eta, jet 3 phi, jet 3 b-tag, jet 4 pt, jet 4 eta, jet 4 phi, jet 4 b-tag, m_jj, m_jjj, m_lv, m_jlv, m_bb, m_wbb, m_wwbb'\nfeatures=[a.strip() for a in feature_text.split(',')]\n\ndataset = pd.read_csv('newhiggs.csv', names=features)\n\n\n# In[3]:\n\n\nfrom sklearn.model_selection import train_test_split\nf = features[1:]\nx_train, x_test, y_train, y_test = train_test_split(dataset[f], dataset['label'], stratify=dataset['label'])\n\n\n# In[4]:\n\n\nx_train.plot(kind='density', subplots=True, layout=(7,4), figsize = (20,20), sharex=False)\nplt.show()\n\n\n# In[5]:\n\n\nfrom sklearn.feature_extraction.text import CountVectorizer,TfidfVectorizer, TfidfTransformer\nfrom sklearn.linear_model import LogisticRegression, LogisticRegressionCV\nfrom sklearn.pipeline import make_pipeline, Pipeline\nfrom sklearn.preprocessing import Normalizer \n\nfrom sklearn.metrics import f1_score ,average_precision_score ,roc_auc_score\n\n\nlogreg1 = LogisticRegression()\nlogreg1.fit(x_train,y_train)\nlogreg1.score(x_test,y_test)\n\n\n# In[6]:\n\n\nprint(\"Test Avg Precision score: \", average_precision_score(logreg1.predict(x_test),y_test))\nprint(\"Test F1 score: \", f1_score(logreg1.predict(x_test),y_test))\nprint(\"Test ROC AUC score: \", roc_auc_score(logreg1.predict(x_test),y_test))\n\n\n# In[7]:\n\n\nlogreg1.coef_[0]\n\n\n# In[8]:\n\n\ncolour = []\nfor i in range(14):\n if i < 7:\n colour.append(\"red\")\n else:\n colour.append(\"blue\")\n\ndef plot(coef,feature_names,i): \n top20_index_pos = coef.argsort()[-7:] \n top20_pos = coef[top20_index_pos]\n print (top20_pos)\n top20_names_pos = [feature_names[j] for j in top20_index_pos] \n print(top20_names_pos)\n top20_index_neg = coef.argsort()[:7] \n top20_neg = coef[top20_index_neg]\n print (top20_neg)\n top20_names_neg = [feature_names[j] for j in top20_index_neg] \n print(top20_names_neg)\n top_coef = np.hstack([top20_neg,top20_pos])\n print(top_coef)\n top_names = np.hstack([top20_names_neg,top20_names_pos])\n print(top_names)\n plt.figure(figsize=(10,4))\n plt.bar(range(1,15),top_coef,color=colour)\n plt.title('most important features '+str(i))\n plt.xticks(range(1,15),top_names,rotation=45)\n plt.show()\n\n\n# In[67]:\n\n\nplot(logreg1.coef_[0], f, 1)\n\n\n# In[10]:\n\n\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.gaussian_process import GaussianProcessClassifier\nfrom sklearn.gaussian_process.kernels import RBF\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis\nfrom sklearn.preprocessing import StandardScaler\n\n\n# In[11]:\n\n\nnames = [\"Nearest Neighbors\", \"Linear SVM\", \"RBF SVM\", \"Gaussian Process\",\n \"Decision Tree\", \"Random Forest\", \"Neural Net\", \"AdaBoost\",\n \"Naive Bayes\", \"QDA\"]\n\n\n# In[12]:\n\n\nclassifiers = [\n KNeighborsClassifier(3),\n SVC(kernel=\"linear\", C=0.025),\n SVC(gamma=2, C=1),\n GaussianProcessClassifier(1.0 * RBF(1.0)),\n DecisionTreeClassifier(max_depth=20),\n RandomForestClassifier(max_depth=20, n_estimators=10, max_features=1),\n MLPClassifier(alpha=1),\n AdaBoostClassifier(),\n GaussianNB(),\n QuadraticDiscriminantAnalysis()]\n\n\n# In[13]:\n\n\nscaler = StandardScaler()\nscaler.fit(x_train)\n\n\n# In[14]:\n\n\nx_train = scaler.transform(x_train)\nx_test = scaler.transform(x_test)\n\n\n# In[15]:\n\n\nlogreg1 = LogisticRegression()\nlogreg1.fit(x_train,y_train)\nlogreg1.score(x_test,y_test)\n\n\n# In[16]:\n\n\nprint(\"Test Avg Precision score: \", average_precision_score(logreg1.predict(x_test),y_test))\nprint(\"Test F1 score: \", f1_score(logreg1.predict(x_test),y_test))\nprint(\"Test ROC AUC score: \", roc_auc_score(logreg1.predict(x_test),y_test))\n\n\n# In[17]:\n\n\nall_clf = []\nfor clf, n in zip(classifiers, names):\n clf.fit(x_train, y_train)\n k = clf.score(x_test, y_test)\n print(n, ': ', k)\n all_clf.append(clf)\n\n\n# In[19]:\n\n\nnew = [\"Neural Net\", \"AdaBoost\",\n \"Naive Bayes\", \"QDA\"]\nc = [ MLPClassifier(alpha=1),\n AdaBoostClassifier(),\n GaussianNB(),\n QuadraticDiscriminantAnalysis()]\n\n\n# In[20]:\n\n\nnew_clf = []\nfor clf, n in zip(c, new):\n clf.fit(x_train, y_train)\n k = clf.score(x_test, y_test)\n print(n, ': ', k)\n all_clf.append(clf)\n\n\n# In[35]:\n\n\n\n\n\n# In[62]:\n\n\ndict1 = {'RBF SVM':0.53096,'Naive Bayes': 0.60264,'k Nearest Neighbours': 0.60948, 'Logistic Regression':0.63512, 'Linear SVM': 0.63768,'Decision Tree': 0.6801,'Multi Layer Perceptron': 0.69008,\n 'Random Forest': 0.6925, 'Gradient Boosting': 0.7 \n }\n\n\n# In[63]:\n\n\ng = sns.barplot(list(dict1.keys()), list(dict1.values()))\n#g.set_xticklabels(rotation=30)\ng.set_xticklabels(g.get_xticklabels(), rotation=90)\ng.set_title('Accuracy')\n\n","sub_path":"Features2.py","file_name":"Features2.py","file_ext":"py","file_size_in_byte":5225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"548593176","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n__title__ = ''\n__author__ = 'zhangjingjun'\n__mtime__ = '2018/5/14'\n# ----------Dragon be here!----------\n ┏━┓ ┏━┓\n ┏━┛ ┻━━━━━━┛ ┻━━┓\n ┃ ━ ┃\n ┃ ━┳━┛ ┗━┳━ ┃\n ┃ ┻ ┃\n ┗━━━┓ ┏━━━━┛\n ┃ ┃神兽保佑\n ┃ ┃永无BUG!\n ┃ ┗━━━━━━━━━┓\n ┃ ┣━┓\n ┃ ┏━┛\n ┗━━┓ ┓ ┏━━━┳━┓ ┏━┛\n ┃ ┫ ┫ ┃ ┫ ┫\n ┗━┻━┛ ┗━┻━┛\n\"\"\"\nfrom django.utils.safestring import mark_safe\nclass Page:\n\tdef __init__(self,current_page,data_count,per_page_count=10,pager_num=5):\n\t\tself.current_page = current_page\n\t\tself.data_count = data_count\n\t\tself.per_page_count = per_page_count\n\t\tself.pager_num = pager_num\n\t@property\n\tdef start(self):\n\t\treturn (self.current_page-1)*self.per_page_count\n\n\t@property\n\tdef end(self):\n\t\treturn self.current_page * self.per_page_count\n\n\t@property\n\tdef total_count(self):\n\t\tv,y = divmod(self.data_count,self.per_page_count)\n\t\tif y:\n\t\t\tv+=1\n\t\treturn v\n\n\tdef page_str(self,base_url):\n\t\tpage_list = []\n\t\tif self.total_count < self.pager_num:\n\t\t\tstart_index = 1\n\t\t\tend_index = self.total_count + 1\n\t\telse:\n\t\t\tif self.current_page <= (self.pager_num + 1)/2:\n\t\t\t\tstart_index = 1\n\t\t\t\tend_index = self.pager_num + 1\n\t\t\telse:\n\t\t\t\tstart_index = self.current_page - (self.pager_num - 1)/2\n\t\t\t\tend_index = self.current_page + (self.pager_num + 1)/2\n\t\t\t\tif (self.current_page+(self.pager_num - 1)/2) > self.total_count:\n\t\t\t\t\tend_index = self.total_count+1\n\t\t\t\t\tstart_index = self.total_count - self.pager_num + 1\n\n\t\tif self.current_page == 1:\n\t\t\tprev = '上一页'\n\t\telse:\n\t\t\tprev = '上一页' % (base_url,self.current_page -1)\n\n\t\tpage_list.append(prev)\n\n\t\tfor i in range(int(start_index),int(end_index)):\n\t\t\tif i == self.current_page:\n\t\t\t\ttemp = '%s' % (base_url,i,i)\n\t\t\telse:\n\t\t\t\ttemp = '%s' % (base_url, i, i)\n\t\t\tpage_list.append(temp)\n\n\t\tif self.current_page == self.total_count:\n\t\t\tnex = '下一页'\n\t\telse:\n\t\t\tnex = '下一页' % (base_url,self.current_page + 1)\n\n\t\tpage_list.append(nex)\n\n\t\tjump = \"\"\"\n\t\tgo\n\t\t\n\t\t\"\"\" % (base_url,)\n\n\t\tpage_list.append(jump)\n\n\t\tpage_str = mark_safe(\"\".join(page_list))\n\t\treturn page_str\n\n\n","sub_path":"day21/utils/pagination.py","file_name":"pagination.py","file_ext":"py","file_size_in_byte":2952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"450608986","text":"import numpy as np\nfrom scipy.stats import vonmises\nfrom GenerativeAgent import GenerativeAgent\n\n\nclass PSIfor:\n\n def __init__(self, kappa_ver, kappa_hor, tau, kappa_oto, theta_frame, theta_rod):\n self.kappa_ver=kappa_ver\n self.kappa_hor=kappa_hor\n self.tau=tau\n self.kappa_oto=kappa_oto\n self.theta_frame=theta_frame\n self.theta_rod=theta_rod\n self.stim1_index=-1\n self.stim2_index=-1\n\n\n #dimensions of 2Dstimulus space\n self.nframes=len(self.theta_frame)\n self.nrods=len(self.theta_rod)\n\n #dimensions of 2D parameter space\n nkappa_ver=len(self.kappa_ver)\n nkappa_hor=len(self.kappa_hor)\n nkappa_oto=len(self.kappa_oto)\n ntau=len(self.tau)\n\n #initialize and compute the two kappas\n kappa1=np.zeros((nkappa_ver,nkappa_hor,ntau,self.nframes))\n kappa2=np.zeros((nkappa_ver,nkappa_hor,ntau,self.nframes))\n\n for kv in range(0,nkappa_ver):\n for kh in range(0,nkappa_hor):\n for t in range(0,ntau):\n kappa1[kv,kh,t,:] = kappa_ver[kv]-(1-np.cos(np.abs(2*self.theta_frame)))*tau[t]*(kappa_ver[kv]-kappa_hor[kh])\n kappa2[kv,kh,t,:] = kappa_hor[kh]+(1-np.cos(np.abs(2*self.theta_frame)))*(1-tau[t])*(kappa_ver[kv]-kappa_hor[kh])\n\n #initialize cumulitative distribution for every kappa_ver,kappa_hor,tau,sigma_oto combinati on per frame and rod orientation.\n cdf=np.zeros((nkappa_ver,nkappa_hor,ntau,nkappa_oto,self.nframes,self.nrods))\n\n for kv in range(0,nkappa_ver):\n for kh in range(0,nkappa_hor):\n for t in range(0,ntau):\n # for all frames compute the contextual prior (four von mises), the otolith distribution (and the head-in-space prior)\n for f in range(0,self.nframes):\n\n # the context provided by the frame\n p_frame1 = vonmises.pdf(self.theta_rodself.theta_frame[f],kappa1[kv,kh,t,f])\n p_frame2 = vonmises.pdf(self.theta_rod-np.pi/2-self.theta_frame[f],kappa2[kv,kh,t,f])\n p_frame3 = vonmises.pdf(self.theta_rod-np.piself.theta_frame[f],kappa1[kv,kh,t,f])\n p_frame4 = vonmises.pdf(self.theta_rod-3*np.pi/2-self.theta_frame[f],kappa2[kv,kh,t,f])\n\n p_frame = (p_frame1+p_frame2+p_frame3+p_frame4)/4.0\n\n # the otoliths\n for so in range(0,nkappa_oto):\n ko=kappa_oto[so]\n p_oto = vonmises.pdf(theta_rod,ko)\n # the upright prior\n #p_hsp = vonmises.pdf(theta_rod,kappa_hsp)\n\n # compute the cumulative density of all distributions convolved\n cdf[kv,kh,t,so,f,:]=np.cumsum(np.multiply(p_oto, p_frame))/np.sum(np.multiply(p_oto, p_frame))\n\n cdf=np.nan_to_num(cdf)\n cdf[cdf==0]=1e-10\n cdf[cdf>1.0]=1.0\n\n self.lookup=np.reshape(cdf,(nkappa_ver*nkappa_hor*nkappa_oto*ntau,self.nframes,self.nrods),order=\"F\")\n # self.lookup=np.load('lookup.npy')\n self.prior=np.ones(nkappa_hor*nkappa_ver*nkappa_oto*ntau)/(nkappa_hor*nkappa_ver*nkappa_oto*ntau)\n\n self.makeG2()\n\n self.calcNextStim()\n\n def calcNextStim(self):\n # Compute posterior\n self.paxs = np.zeros([self.lookup.shape[0], self.lookup.shape[1], self.lookup.shape[2]])\n self.paxf = np.zeros([self.lookup.shape[0], self.lookup.shape[1], self.lookup.shape[2]])\n #h = np.zeros([self.nframes, self.nrods])\n\n self.paxs = np.einsum('i,ijk->ijk', self.prior, self.lookup)\n self.paxf = np.einsum('i,ijk->ijk', self.prior, 1.0 - self.lookup)\n\n ps = np.sum(self.paxs,0)\n pf = np.sum(self.paxf,0)\n\n self.paxs = np.einsum('jk,ijk->ijk', 1/ps, self.paxs)\n self.paxf = np.einsum('jk,ijk->ijk', 1/pf, self.paxf)\n\n # Compute entropy\n hs = np.sum(-self.paxs * np.log(self.paxs + 1e-10),0)\n hf = np.sum(-self.paxf * np.log(self.paxf + 1e-10),0)\n\n # Compute expected entropy\n h = hs*ps + hf*pf\n h = h.flatten('F')\n\n # Find stimulus with smallest expected entropy\n idx=np.argmin(h)\n\n frame_f = np.expand_dims(self.theta_frame,axis=1)\n frame_f = np.tile(frame_f,(1,self.nrods))\n frame_f = frame_f.flatten('F')\n rod_f = np.expand_dims(self.theta_rod,axis=0)\n rod_f = np.tile(rod_f,(self.nframes,1))\n rod_f = rod_f.flatten('F')\n\n # Find stimulus that minimizes expected entropy\n self.stim = ([frame_f[idx],rod_f[idx]])\n self.stim1_index = np.argmin(np.abs(self.theta_frame - self.stim[0]))\n self.stim2_index = np.argmin(np.abs(self.theta_rod - self.stim[1]))\n\n def addData(self,response):\n self.stim=None\n\n # Update prior based on response\n if response == 1:\n self.prior = self.paxs[:,self.stim1_index,self.stim2_index]\n elif response == 0:\n self.prior = self.paxf[:,self.stim1_index,self.stim2_index]\n else:\n self.prior = self.prior\n\n self.theta=np.array([self.kappa_ver_g2.flatten('F'),self.kappa_hor_g2.flatten('F'),self.tau_g2.flatten('F'),self.kappa_oto_g2.flatten('F')])\n self.params=np.matmul(self.theta,self.prior)\n\n self.calcNextStim()\n\n return self.params\n\n def makeG2(self):\n nkappa_ver=len(self.kappa_ver)\n nkappa_hor=len(self.kappa_hor)\n nkappa_oto=len(self.kappa_oto)\n ntau=len(self.tau)\n\n kappa_ver_g2 = np.expand_dims(self.kappa_ver,axis=1)\n kappa_ver_g2 = np.expand_dims(kappa_ver_g2,axis=2)\n kappa_ver_g2 = np.expand_dims(kappa_ver_g2,axis=3)\n self.kappa_ver_g2 = np.tile(kappa_ver_g2,(1,nkappa_hor,ntau,nkappa_oto))\n\n kappa_hor_g2 = np.expand_dims(self.kappa_hor,axis=0)\n kappa_hor_g2 = np.expand_dims(kappa_hor_g2,axis=2)\n kappa_hor_g2 = np.expand_dims(kappa_hor_g2,axis=3)\n self.kappa_hor_g2 = np.tile(kappa_hor_g2,(nkappa_ver,1,ntau,nkappa_oto))\n\n tau_g2 = np.expand_dims(self.tau,axis=0)\n tau_g2 = np.expand_dims(tau_g2,axis=1)\n tau_g2 = np.expand_dims(tau_g2,axis=3)\n self.tau_g2 = np.tile(tau_g2,(nkappa_ver,nkappa_hor,1,nkappa_oto))\n\n kappa_oto_g2 = np.expand_dims(self.kappa_oto,axis=0)\n kappa_oto_g2 = np.expand_dims(kappa_oto_g2,axis=1)\n kappa_oto_g2 = np.expand_dims(kappa_oto_g2,axis=2)\n self.kappa_oto_g2 = np.tile(kappa_oto_g2,(nkappa_ver,nkappa_hor,ntau,1))","sub_path":"Ernest/PSIRiF.py","file_name":"PSIRiF.py","file_ext":"py","file_size_in_byte":6639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"229478297","text":"from __future__ import print_function\r\nimport os\r\nimport matplotlib as mpl\r\nimport tarfile\r\nimport matplotlib.image as mpimg\r\nfrom matplotlib import pyplot as plt\r\n\r\nimport mxnet as mx\r\nfrom mxnet import gluon\r\nfrom mxnet import ndarray as nd\r\nfrom mxnet.gluon import nn, utils\r\nfrom mxnet import autograd\r\nimport numpy as np\r\n\r\nimport msvcrt\r\nimport shutil\r\n\r\nepochs = 30 # Set low by default for tests, set higher when you actually run this code.\r\nbatch_size = 10\r\nlatent_z_size = 100\r\nfilename_G = \"netG.params\"\r\nfilename_D = \"netD.params\"\r\nparam_datapath = \"checkpoints\"\r\n\r\nuse_gpu = True\r\nctx = mx.gpu() if use_gpu else mx.cpu()\r\n\r\nlr = 0.0002\r\nbeta1 = 0.5\r\n\r\ndata_path = 'car_middle_dataset'\r\n\r\nif not os.path.exists(data_path):\r\n print(\"Dataset not found! (folder: {})\".format(data_path))\r\n exit()\r\n\r\n# Reshape dataset\r\ntarget_wd = 64\r\ntarget_ht = 64\r\nimg_list = []\r\n\r\ndef transform(data, target_wd, target_ht):\r\n # resize to target_wd * target_ht\r\n data = mx.image.imresize(data, target_wd, target_ht)\r\n # transpose from (target_wd, target_ht, 3)\r\n # to (3, target_wd, target_ht)\r\n data = nd.transpose(data, (2,0,1))\r\n # normalize to [-1, 1]\r\n data = data.astype(np.float32)/127.5 - 1\r\n # if image is greyscale, repeat 3 times to get RGB image.\r\n if data.shape[0] == 1:\r\n data = nd.tile(data, (3, 1, 1))\r\n return data.reshape((1,) + data.shape)\r\n\r\n# Loading dataset\r\nfor dirpaths, dirnames, fnames in os.walk(data_path):\r\n for fname in fnames:\r\n if not fname.endswith('.png'):\r\n continue\r\n img = os.path.join(data_path, fname)\r\n img_arr = mx.image.imread(img)\r\n img_arr = transform(img_arr, target_wd, target_ht)\r\n img_list.append(img_arr)\r\ntrain_data = mx.io.NDArrayIter(data=nd.concatenate(img_list), batch_size=batch_size)\r\n\r\ndef visualize(img_arr):\r\n plt.imshow(((img_arr.asnumpy().transpose(1, 2, 0) + 1.0) * 127.5).astype(np.uint8))\r\n plt.axis('off')\r\n\r\nfor i in range(4):\r\n plt.subplot(1,4,i+1)\r\n visualize(img_list[i + 10][0])\r\nplt.show()\r\n\r\n# build the generator\r\nnc = 3\r\ngenerator_frames = 64\r\nnetG = nn.Sequential()\r\nwith netG.name_scope():\r\n # input is Z, going into a deconvolution\r\n # state size. (generator_frames*n) x h x w\r\n # n get smaller to compensate increasing input size on next layer\r\n # size -> 4 x 4\r\n netG.add(nn.Conv2DTranspose(generator_frames * 8, 4, 1, 0, use_bias=False))\r\n netG.add(nn.BatchNorm())\r\n netG.add(nn.Activation('relu'))\r\n # size -> 8 x 8\r\n netG.add(nn.Conv2DTranspose(generator_frames * 4, 4, 2, 1, use_bias=False))\r\n netG.add(nn.BatchNorm())\r\n netG.add(nn.Activation('relu'))\r\n # size -> 16 x 16\r\n netG.add(nn.Conv2DTranspose(generator_frames * 2, 4, 2, 1, use_bias=False))\r\n netG.add(nn.BatchNorm())\r\n netG.add(nn.Activation('relu'))\r\n # size -> 32 x 32\r\n netG.add(nn.Conv2DTranspose(generator_frames, 4, 2, 1, use_bias=False))\r\n netG.add(nn.BatchNorm())\r\n netG.add(nn.Activation('relu'))\r\n # state size. (nc -> colors) x 64 x 64\r\n netG.add(nn.Conv2DTranspose(nc, 4, 2, 1, use_bias=False))\r\n netG.add(nn.Activation('tanh'))\r\n\r\n# build the discriminator\r\ndiscriminator_frames = 64\r\nnetD = nn.Sequential()\r\nwith netD.name_scope():\r\n # input is (nc) x 64 x 64\r\n # state size. (generator_frames*n) x h x w\r\n # n get smaller to compensate increasing input size on next layer\r\n netD.add(nn.Conv2D(discriminator_frames, 4, 2, 1, use_bias=False))\r\n netD.add(nn.LeakyReLU(0.2))\r\n # size -> 32 x 32\r\n netD.add(nn.Conv2D(discriminator_frames * 2, 4, 2, 1, use_bias=False))\r\n netD.add(nn.BatchNorm())\r\n netD.add(nn.LeakyReLU(0.2))\r\n # size -> 16 x 16\r\n netD.add(nn.Conv2D(discriminator_frames * 4, 4, 2, 1, use_bias=False))\r\n netD.add(nn.BatchNorm())\r\n netD.add(nn.LeakyReLU(0.2))\r\n # size -> 8 x 8\r\n netD.add(nn.Conv2D(discriminator_frames * 8, 4, 2, 1, use_bias=False))\r\n netD.add(nn.BatchNorm())\r\n netD.add(nn.LeakyReLU(0.2))\r\n # size -> 4 x 4\r\n netD.add(nn.Conv2D(1, 4, 1, 0, use_bias=False))\r\n\r\n# loss\r\nloss = gluon.loss.SigmoidBinaryCrossEntropyLoss()\r\n\r\n# initialize the generator and the discriminator\r\nnetG.initialize(mx.init.Normal(0.02), ctx=ctx)\r\nnetD.initialize(mx.init.Normal(0.02), ctx=ctx)\r\n\r\n# trainer for the generator and the discriminator\r\ntrainerG = gluon.Trainer(netG.collect_params(), 'adam', {'learning_rate': lr, 'beta1': beta1})\r\ntrainerD = gluon.Trainer(netD.collect_params(), 'adam', {'learning_rate': lr, 'beta1': beta1})\r\n\r\n\r\nreal_label = nd.ones((batch_size,), ctx=ctx)\r\nfake_label = nd.zeros((batch_size,),ctx=ctx)\r\n\r\ndef facc(label, pred):\r\n pred = pred.ravel()\r\n label = label.ravel()\r\n return ((pred > 0.5) == label).mean()\r\nmetric = mx.metric.CustomMetric(facc)\r\n\r\nepoch_iter = 0\r\n\r\n# Load latest existing checkpoint\r\nif os.path.exists(param_datapath):\r\n f = open(param_datapath+\"/\"+\"epoch_iter.txt\", mode='r')\r\n content = f.read()\r\n epoch_iter = int(content)\r\n f.close()\r\n D_path = param_datapath+\"/\"+content+\"/\"+filename_D\r\n G_path = param_datapath+\"/\"+content+\"/\"+filename_G\r\n netD.load_params(D_path, ctx = ctx)\r\n netG.load_params(G_path, ctx = ctx)\r\n\r\n# for epoch in range(epochs):\r\nwhile True:\r\n train_data.reset()\r\n iter = 0\r\n epoch_iter += 1\r\n for batch in train_data:\r\n ############################\r\n # (1) Update D network: maximize log(D(x)) + log(1 - D(G(z)))\r\n ###########################\r\n data = batch.data[0].as_in_context(ctx)\r\n latent_z = mx.nd.random_normal(0, 1, shape=(batch_size, latent_z_size, 1, 1), ctx=ctx)\r\n with autograd.record():\r\n # train with real image\r\n output = netD(data).reshape((-1, 1))\r\n errD_real = loss(output, real_label)\r\n metric.update([real_label,], [output,])\r\n\r\n # train with fake image\r\n fake = netG(latent_z)\r\n output = netD(fake.detach()).reshape((-1, 1))\r\n errD_fake = loss(output, fake_label)\r\n errD = errD_real + errD_fake\r\n errD.backward()\r\n metric.update([fake_label,], [output,])\r\n\r\n trainerD.step(batch.data[0].shape[0])\r\n\r\n ############################\r\n # (2) Update G network: maximize log(D(G(z)))\r\n ###########################\r\n with autograd.record():\r\n fake = netG(latent_z)\r\n output = netD(fake).reshape((-1, 1))\r\n errG = loss(output, real_label)\r\n errG.backward()\r\n\r\n trainerG.step(batch.data[0].shape[0])\r\n\r\n # Print log infomation every ten batches\r\n if iter % 50 == 0:\r\n name, acc = metric.get()\r\n print(\"Iter: {} || Epoch: {}\".format(iter, epoch_iter))\r\n print(\"Discriminator Loss = {}\\nGenerator Loss = {}\\nBinary Training Accuracy = {}\".format(nd.mean(errD).asscalar(), nd.mean(errG).asscalar(), acc))\r\n iter = iter + 1\r\n\r\n # Visualize one generated image on keypress\r\n if msvcrt.kbhit():\r\n key = msvcrt.getch()\r\n # Press s to save current parameters\r\n if(key == b's'):\r\n print(\"Saving Current Params...\")\r\n if not os.path.exists(param_datapath):\r\n os.makedirs(param_datapath)\r\n os.makedirs(param_datapath+\"/\"+str(epoch_iter))\r\n netD.save_params(param_datapath+\"/\"+str(epoch_iter)+\"/\"+filename_D)\r\n netG.save_params(param_datapath+\"/\"+str(epoch_iter)+\"/\"+filename_G)\r\n f = open(param_datapath+\"/\"+\"epoch_iter.txt\", mode='w+')\r\n f.write(str(epoch_iter))\r\n f.close()\r\n latent_z = mx.nd.random_normal(0, 1, shape=(2, latent_z_size, 1, 1), ctx=ctx)\r\n fake_img = netG(latent_z)\r\n visualize(fake_img[1])\r\n plt.show()\r\n\r\n name, acc = metric.get()\r\n metric.reset()\r\n\r\n # Save checkpoint every 100 epochs\r\n if epoch_iter % 100 == 0:\r\n # f = open(filename_D, mode='w+')\r\n # f.close()\r\n # f = open(filename_G, mode='w+')\r\n # f.close()\r\n if not os.path.exists(param_datapath):\r\n os.makedirs(param_datapath)\r\n # Delete older checkpoints to conserve space\r\n if os.path.exists(param_datapath+\"/\"+str(epoch_iter - 1000)):\r\n shutil.rmtree(param_datapath+\"/\"+str(epoch_iter - 1000))\r\n os.makedirs(param_datapath+\"/\"+str(epoch_iter))\r\n netD.save_params(param_datapath+\"/\"+str(epoch_iter)+\"/\"+filename_D)\r\n netG.save_params(param_datapath+\"/\"+str(epoch_iter)+\"/\"+filename_G)\r\n f = open(param_datapath+\"/\"+\"epoch_iter.txt\", mode='w+')\r\n f.write(str(epoch_iter))\r\n f.close()\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"520854262","text":"# -*- coding: utf-8 -*-\nfrom odoo import models, api\n\n\nclass PurchaseOrder(models.Model):\n _inherit = 'purchase.order'\n\n def button_approve(self):\n self.ensure_one()\n super(PurchaseOrder, self).button_approve()\n\n # 向采购经理发送消息\n users_obj = self.env['res.users'].sudo()\n\n company = self.company_id\n users = False\n while company:\n users = users_obj.search([('company_ids', '=', company.id), ('groups_id', '=', self.env.ref('purchase.group_purchase_manager').id)])\n\n if users:\n company = False\n else:\n company = company.parent_id\n\n if not users:\n return\n\n self.message_post(\n body='采购订单:%s 已通过审批' % self.name, # 内容\n subject='采购订单通过审批', # 主题\n add_sign=False,\n model=self._name,\n res_id=self.id,\n subtype_id=self.env.ref('cj_mail.mms_purchase_order_approval').id,\n partner_ids=[(6, 0, users.mapped('partner_id').ids)], # 收件人\n )\n\n\n\n\n","sub_path":"myaddons/cj_mail/models/purchase_order.py","file_name":"purchase_order.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"57620871","text":"## 원형 연결 리스트 활용 : 짝수 홀수 구분 프로그램\nimport random\n\n## 클래스와 함수\nclass Node():\n def __init__(self):\n self.data = None\n self.link = None\n\ndef printNodes(start):\n current = start\n if current.link == None:\n return\n print(current.data, end=' ')\n while current.link != start:\n current = current.link\n print(current.data, end=' ')\n print()\n\ndef countNegaPosi():\n global memory, head, current, pre\n\n nega, posi = 0, 0\n if head == None:\n return False\n\n current = head\n while True:\n if current.data < 0:\n nega += 1\n else:\n posi += 1\n if current.link == head:\n break\n current = current.link\n\n return nega, posi\n # 이렇게 리턴값이 있도록 함수를 만들고, 함수를 또 다른 함수의 인수로 넣으면. 자동으로 연산되겠구나\n\ndef changeNegaPosi(nega, posi):\n\n current = head\n while True:\n if current.data != 0:\n current.data *= -1\n if current.link == head:\n break\n current = current.link\n\n## 전역 변수\nmemory = []\nhead, current, pre = None, None, None\n\n## 메인 코드\nif __name__ == \"__main__\":\n\n dataArray = []\n for i in range(7):\n dataArray.append(random.randint(-100, 100))\n\n node = Node()\n node.data = dataArray[0]\n head = node\n node.link = head\n memory.append(node)\n\n for data in dataArray[1:]:\n pre = node\n node = Node()\n node.data = data\n pre.link = node\n node.link = head\n memory.append(node)\n\n printNodes(head)\n\n negaCount, posiCount = countNegaPosi()\n print('음수: ', negaCount, '\\t', '양수: ', posiCount)\n\n changeNegaPosi(negaCount, posiCount)\n printNodes(head)","sub_path":"05-08-self-02.py","file_name":"05-08-self-02.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"583995524","text":"from flask import Flask, request\nfrom flask_restful import Resource, Api\nfrom flask_restful_swagger import swagger\n\nimport mysql.connector\n\napp = application = Flask(__name__)\napi = swagger.docs(Api(app), apiVersion='0.1')\n\nclass Record(Resource):\n mydb = \"\"\n def __init__(self):\n self.mydb = mysql.connector.connect(\n host=\"soacl-database.cjn6wctbjclb.us-east-1.rds.amazonaws.com\",\n user=\"administrator\",\n passwd=\"fLrsZEBnnc4QD35\",\n database=\"soa_project\"\n )\n \"Record API\"\n @swagger.operation(\n notes='Get a record by SORD',\n nickname='get',\n # Parameters can be automatically extracted from URLs (e.g. )\n # but you could also override them here, or add other parameters.\n parameters=[\n {\n \"name\": \"sord\",\n \"description\": \"The SORD of the record\",\n \"required\": True,\n \"allowMultiple\": False,\n \"dataType\": 'string',\n \"paramType\": 'path'\n }\n ])\n def get(self, sord):\n # Get a device with id (GET)\n mycursor = self.mydb.cursor()\n sql = \"SELECT * FROM records WHERE sord=\" + str(sord)\n mycursor.execute(sql)\n\n records = mycursor.fetchall()\n if records:\n record = records[0]\n recordJSON = {\n \"sord\": record[0],\n \"devicesn\": record[1],\n \"brand\": record [2],\n \"clientinfo\": record[3],\n \"clientaddress\": record[4],\n \"complaint\": record[5],\n \"diagnose\": record[6],\n \"statuskey\": record[7],\n \"userid\": record[8]\n };\n returnData = []\n returnData.append(recordJSON)\n else:\n returnData = []\n\n return returnData\n\n @swagger.operation(\n notes='Delete a record by SORD',\n nickname='delete',\n # Parameters can be automatically extracted from URLs (e.g. )\n # but you could also override them here, or add other parameters.\n parameters=[\n {\n \"name\": \"sord\",\n \"description\": \"The SORD of the record\",\n \"required\": True,\n \"allowMultiple\": False,\n \"dataType\": 'string',\n \"paramType\": \"path\"\n }\n ])\n def delete(self,sord):\n # Delete a record (DELETE)\n mycursor = self.mydb.cursor()\n sql = \"DELETE FROM records WHERE sord = \" + str(sord)\n mycursor.execute(sql)\n self.mydb.commit()\n return \"ok\"\n\n @swagger.operation(\n notes='Update a record by SORD',\n nickname='put',\n # Parameters can be automatically extracted from URLs (e.g. )\n # but you could also override them here, or add other parameters.\n parameters=[\n {\n \"name\": \"sord\",\n \"description\": \"The SORD of the record\",\n \"required\": True,\n \"allowMultiple\": False,\n \"dataType\": 'string',\n \"paramType\": \"path\"\n },\n {\n \"name\": \"diagnose\",\n \"description\": \"The DIAGNOSE of the manufacturer\",\n \"required\": True,\n \"allowMultiple\": False,\n \"dataType\": 'string',\n \"paramType\": \"form\"\n },\n {\n \"name\": \"statuskey\",\n \"description\": \"The STATUS KEY of the device\",\n \"required\": True,\n \"allowMultiple\": False,\n \"dataType\": 'int',\n \"paramType\": \"form\"\n }\n ])\n def put(self, sord):\n # Update a device (UPDATE)\n record = []\n record.append(request.form['diagnose'])\n record.append(request.form['statuskey'])\n #record.append(request.form['userid'])\n mycursor = self.mydb.cursor()\n sql = \"UPDATE records SET diagnose = %s, statuskey = %s WHERE sord = %s\"\n val = (record[0], record[1], str(sord))\n mycursor.execute(sql, val)\n self.mydb.commit()\n return \"ok\"\n\n\n\n# Get All Devices (READ -> get)\nclass Records(Resource):\n mydb = \"\"\n def __init__(self):\n self.mydb = mysql.connector.connect(\n host=\"soacl-database.cjn6wctbjclb.us-east-1.rds.amazonaws.com\",\n user=\"administrator\",\n passwd=\"fLrsZEBnnc4QD35\",\n database=\"soa_project\"\n )\n\n @swagger.operation(\n notes='Get all records',\n nickname='get',\n )\n def get(self):\n mycursor = self.mydb.cursor()\n mycursor.execute(\"SELECT * FROM records\")\n\n records = mycursor.fetchall()\n returnData = []\n if records:\n for record in records:\n deviceJSON = {\n \"sord\": record[0],\n \"devicesn\": record[1],\n \"brand\": record[2],\n \"clientinfo\": record[3],\n \"clientaddress\": record[4],\n \"complaint\": record[5],\n \"diagnose\": record[6],\n \"statuskey\": record[7],\n \"userid\": record[8]\n };\n returnData.append(deviceJSON)\n\n return returnData\n\n @swagger.operation(\n notes='Create a new record',\n nickname='put',\n # Parameters can be automatically extracted from URLs (e.g. )\n # but you could also override them here, or add other parameters.\n parameters=[\n {\n \"name\": \"brand\",\n \"description\": \"The BRAND of the device\",\n \"required\": True,\n \"allowMultiple\": False,\n \"dataType\": 'string',\n \"paramType\": \"form\"\n },\n {\n \"name\": \"devicesn\",\n \"description\": \"The DEVICE SERIALNUMBER of the device\",\n \"required\": True,\n \"allowMultiple\": False,\n \"dataType\": 'string',\n \"paramType\": \"form\"\n },\n {\n \"name\": \"clientinfo\",\n \"description\": \"The CLEINT INFO\",\n \"required\": True,\n \"allowMultiple\": False,\n \"dataType\": 'string',\n \"paramType\": \"form\"\n },\n {\n \"name\": \"clientaddress\",\n \"description\": \"The CLIENT ADDRESS\",\n \"required\": True,\n \"allowMultiple\": False,\n \"dataType\": 'string',\n \"paramType\": \"form\"\n },\n {\n \"name\": \"complaint\",\n \"description\": \"The COMPLAINT of the device\",\n \"required\": True,\n \"allowMultiple\": False,\n \"dataType\": 'string',\n \"paramType\": \"form\"\n },\n {\n \"name\": \"diagnose\",\n \"description\": \"The DIAGNOSE of the manufacturer\",\n \"required\": True,\n \"allowMultiple\": False,\n \"dataType\": 'string',\n \"paramType\": \"form\"\n },\n {\n \"name\": \"statuskey\",\n \"description\": \"The STATUS KEY of the device\",\n \"required\": True,\n \"allowMultiple\": False,\n \"dataType\": 'int',\n \"paramType\": \"form\"\n },\n {\n \"name\": \"userid\",\n \"description\": \"The USER ID of the manufacturer\",\n \"required\": True,\n \"allowMultiple\": False,\n \"dataType\": 'int',\n \"paramType\": \"form\"\n }\n\n ])\n def post(self):\n # Create a new device (POST)\n record = [];\n #record.append(request.form['sord'])\n record.append(request.form['brand'])\n record.append(request.form['devicesn'])\n record.append(request.form['clientinfo'])\n record.append(request.form['clientaddress'])\n record.append(request.form['complaint'])\n record.append(request.form['diagnose'])\n record.append(request.form['statuskey'])\n record.append(request.form['userid'])\n ### Hier zou eerst nog form validation moeten gedaan worden\n ### controle of er al een toestel met hetzelfde id of serienummer bestaat\n ### id is hetzelfde als een dossiernummer, serienummer is uniek voor elk toestel (staat op een artiekelticket\n ### controle op SQL injectie\n\n sql = \"INSERT INTO records (brand, devicesn, clientinfo, clientaddress, complaint, diagnose, statuskey, userid) \" \\\n \"VALUES (%s, %s, %s, %s, %s, %s, %s, %s)\"\n val = (record[0], record[1], record[2], record[3], record[4], record[5], record[6], record[7])\n mycursor = self.mydb.cursor()\n mycursor.execute(sql, val)\n\n self.mydb.commit()\n\n return \"ok\"\n","sub_path":"Python_(Flask-RESTfull)/records.py","file_name":"records.py","file_ext":"py","file_size_in_byte":9062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"110071599","text":"veg = ['bayam', 'kangkung', 'wortel', 'selada']\n\nwhile True:\n print('\\nDATA SAYUR')\n A = print('A. Tambahkan data')\n B = print('B. Hapus data')\n C = print('C. Tampilkan data')\n X = print('X. TUTUP')\n pilih = input('Pilih menu: ')\n print('---------------------------------------') \n while True:\n if(pilih == 'A'):\n insert = str(input('\\nTambahkan data baru: '))\n veg.append(insert)\n loop = input('\\nAda lagi? (y/n): ')\n if(loop == 'y'):\n continue\n else:\n break\n elif(pilih == 'B'):\n delete = str(input('\\nHapus data lama: '))\n x = delete in veg \n if(x == True):\n veg.remove(delete)\n loop = input('Hapus data lagi? (y/n): ')\n if(loop == 'y'):\n continue\n else:\n break\n elif(x == False):\n print('Data sayur tidak ditemukan')\n loop = input('Ulangi proses? (y/n): ')\n if(loop == 'y'):\n continue\n else:\n break\n elif(pilih == 'C'):\n print(veg)\n loop = input('\\nMau lihat lagi? (y/n): ')\n if(loop == 'y'):\n continue\n else:\n break\n elif(pilih == 'X'):\n break\n else:\n break\n if(pilih == 'X'):\n print('Menutup program.......')\n break\n else:\n break\n","sub_path":"Praktikum 04.py","file_name":"Praktikum 04.py","file_ext":"py","file_size_in_byte":1580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"287166279","text":"#!/usr/bin/python\n\nfrom operation_registry import OperationRegistry\nfrom textwrap import dedent\nfrom itertools import izip\nimport jtextfsm as textfsm\nimport StringIO\n\n\nregistry = OperationRegistry()\n\nIOS_SHOW_IP_ROUTE_PREFIX_TEMPLATE = StringIO.StringIO(dedent(\"\"\"\\\n Value ROUTE_ENTRY (\\S+)\n Value KNOWN_VIA (.*)\n Value ADMIN_DISTANCE (\\d+)\n Value METRIC (\\d+)\n Value NEXTHOP (\\d+\\.\\d+\\.\\d+\\.\\d+)\n\n Start\n ^Routing entry for ${ROUTE_ENTRY}\n ^\\s*Known via \\\"${KNOWN_VIA}\\\",\\s*distance\\s*${ADMIN_DISTANCE},\\s*metric\\s*${METRIC}\n ^\\s*Last update from ${NEXTHOP}\n \"\"\"))\n \n\n@registry.device_operation('get_route',family='ios,iosxe')\ndef get_route(context, target, prefix):\n \"\"\"Get output of 'show ip route and parse it.\"\"\"\n\n commands = [\"show ip route {}\".format(prefix)]\n with context.get_connection(\"cli\") as cli:\n response = cli.execute(commands)\n\n fsm = textfsm.TextFSM(IOS_SHOW_IP_ROUTE_PREFIX_TEMPLATE)\n parsed_output = fsm.ParseText(response[0])\n\n key_list = [\"entry\", \"known_via\", \"admin_distance\", \"metric\", \"nexthop\"]\n return dict(zip(key_list, parsed_output[0]))\n","sub_path":"auto_operations/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"288143051","text":"import wx\nfrom client import Client\nfrom log_client import LogClient\nfrom log_app import LogApp\nfrom iapp import IApp\nfrom common import MessageType as mt\n\n\nclass App(wx.Frame, IApp):\n\n def __init__(self):\n self.app = wx.App()\n log_app = LogApp(self)\n self.client = LogClient(Client(log_app, 'localhost', 5000))\n\n user_dialog_box = wx.TextEntryDialog(None, \"Login\", \"Username\", \"\")\n if user_dialog_box.ShowModal() == wx.ID_OK:\n self.username = user_dialog_box.GetValue()\n\n # Set up the main window\n wx.Frame.__init__(self,\n parent=None,\n title=\"Python Chat 2000X: \" + self.username,\n size=(500, 400),\n style=wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER)\n\n vert_sizer = wx.BoxSizer(wx.VERTICAL)\n self.chatScreen = wx.TextCtrl(self, style=wx.TE_MULTILINE | wx.TE_READONLY | wx.TE_RICH)\n self.messageBox = wx.TextCtrl(self, style=wx.TE_PROCESS_ENTER, size=(300, 25))\n self.messageBox.SetMaxLength(141) # We're better than twitter\n\n vert_sizer.Add(self.chatScreen, 1, wx.EXPAND)\n vert_sizer.Add(self.messageBox, 0, wx.EXPAND)\n\n hor_sizer = wx.BoxSizer(wx.HORIZONTAL)\n self.userListScreen = wx.TextCtrl(self, style=wx.TE_MULTILINE | wx.TE_READONLY)\n\n hor_sizer.Add(vert_sizer, flag=wx.EXPAND, border=10)\n hor_sizer.Add(self.userListScreen, 1, wx.EXPAND)\n\n self.SetSizer(hor_sizer)\n self.messageBox.Bind(wx.EVT_TEXT_ENTER, self.send)\n\n self.Bind(wx.EVT_CLOSE, self.on_close)\n\n def get_username(self):\n return self.username\n\n def on_close(self, event):\n self.app.ExitMainLoop()\n\n def _display(self, message, message_type):\n self.chatScreen.SetForegroundColour(message_type)\n self.chatScreen.AppendText(message + \"\\n\")\n\n def display(self, message, message_type=mt.TEXT):\n wx.CallAfter(self._display, message, message_type)\n\n def _show_users(self, user_list):\n users = \"\\n\".join(user_list)\n self.userListScreen.SetValue(users)\n\n def show_users(self, user_list):\n wx.CallAfter(self._show_users, user_list)\n\n def send(self, event):\n message = self.messageBox.GetValue()\n self.display(\"You: \" + message)\n self.messageBox.SetValue(\"\")\n try:\n self.client.send(message)\n except Exception as e:\n self.display(\"Failed to send\", message_type=mt.ERROR)\n\n def run(self):\n self.client.setDaemon(True)\n self.client.start()\n self.Show()\n self.app.MainLoop()\n\n\n# Instantiate and run\napp = App()\napp.run()","sub_path":"client/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"184387635","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torchvision\nimport torchvision.datasets as datasets\nimport torchvision.transforms as transforms\nfrom torch.utils.data import DataLoader\nfrom torch.utils.tensorboard import SummaryWriter\nfrom model import Discriminator, Generator, initialize_weights\n\n# GLOBALS:\nDEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\nLEARNING_RATE = 5e-5 # according to paper\nBATCH_SIZE = 64 # according to paper (m=64)\nIMAGE_SIZE = 64\nCHANNELS_IMG = 1\nZ_DIM = 128\nNUM_EPOCHS = 5\nFEATURES_CRITIC = 64\nFEATURES_GEN = 64\nCRITIC_ITERATIONS = 5 # according to paper, this tells how many iterations we perform over discriminator, per a single iteration over generator\nWEIGHT_CLIP = 0.01 # according to paper, clipping weights to achieve compact function over theta-weights\n\n# Data augmentations:\ntransforms = transforms.Compose(\n [\n transforms.Resize(IMAGE_SIZE),\n transforms.ToTensor(),\n transforms.Normalize(\n [0.5 for _ in range(CHANNELS_IMG)], [0.5 for _ in range(CHANNELS_IMG)]\n ),\n ]\n)\n\n# Initialize dataset & dataloader:\ndataset = datasets.MNIST(root=\"dataset/\", transform=transforms, download=True)\ndataloader = DataLoader(dataset, batch_size=BATCH_SIZE, shuffle=True)\n\n# Initialize generator and discriminator(aka critic) & its' weights:\ngenerator = Generator(Z_DIM, CHANNELS_IMG, FEATURES_GEN).to(DEVICE)\ndiscriminator = Discriminator(CHANNELS_IMG, FEATURES_CRITIC).to(DEVICE)\ninitialize_weights(generator)\ninitialize_weights(discriminator)\n\n# Initialize optimizers:\nopt_generator = optim.RMSprop(generator.parameters(), lr=LEARNING_RATE) # RMSprop is used in the paper.\nopt_disc = optim.RMSprop(discriminator.parameters(), lr=LEARNING_RATE)\n\nfixed_noise = torch.randn(32, Z_DIM, 1, 1).to(DEVICE)\nwriter_real = SummaryWriter(f\"logs/real\")\nwriter_fake = SummaryWriter(f\"logs/fake\")\nstep = 0\n\ngenerator.train()\ndiscriminator.train()\n\n# Perform training:\nfor epoch in range(NUM_EPOCHS):\n for batch_idx, (real, _) in enumerate(dataloader):\n real = real.to(DEVICE)\n\n # Train Discriminator according to wgan-formula:\n for _ in range(CRITIC_ITERATIONS):\n # Generate fake images out of random latent space z:\n z_vector = torch.randn(BATCH_SIZE, Z_DIM, 1, 1).to(DEVICE)\n fake = generator(z_vector)\n\n # Propagate thourgh disc' & calculate loss:\n disc_real = discriminator(real).reshape(-1)\n disc_fake = discriminator(fake).reshape(-1)\n loss_disc = -(torch.mean(disc_real) - torch.mean(disc_fake)) # the '-' is because we'd like to optimize that expression, yet torch-optimizer minimize by default.\n\n # Backprop' & update disc' weights:\n discriminator.zero_grad()\n loss_disc.backward(retain_graph=True) #\n opt_disc.step()\n\n # Clipping weights to [-c,c]:\n for p in discriminator.parameters():\n p.data.clamp_(-WEIGHT_CLIP, WEIGHT_CLIP)\n\n\n # Train Generator ( according to -E[critic(generator(z))] ):\n output = discriminator(fake).reshape(-1)\n loss_gen = -torch.mean(output)\n generator.zero_grad()\n loss_gen.backward()\n opt_generator.step()\n\n # Print losses occasionally and print to tensorboard\n if batch_idx % 100 == 0 and batch_idx > 0:\n generator.eval()\n discriminator.eval()\n print(\n f\"Epoch [{epoch}/{NUM_EPOCHS}] Batch {batch_idx}/{len(dataloader)} \\\n Loss D: {loss_disc:.4f}, loss G: {loss_gen:.4f}\"\n )\n\n with torch.no_grad():\n fake = generator(z_vector)\n # take out (up to) 32 examples\n img_grid_real = torchvision.utils.make_grid(real[:32], normalize=True)\n img_grid_fake = torchvision.utils.make_grid(fake[:32], normalize=True)\n\n writer_real.add_image(\"Real\", img_grid_real, global_step=step)\n writer_fake.add_image(\"Fake\", img_grid_fake, global_step=step)\n\n step += 1\n generator.train()\n discriminator.train()\n\n","sub_path":"GANs/WGAN/training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":4166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"513329411","text":"\"\"\"\nFunction and design testing for the HillComponent class\n\n Output: output\n Other files required: none\n\n Author: Shane Kepley\n email: shane.kepley@rutgers.edu\n Date: 4/3/20; Last revision: 4/3/20\n\"\"\"\n\nimport numpy as np\nfrom hill_model import HillComponent, HillCoordinate\n\ngamma = 1.2\np1 = np.array([np.nan, 3, 5, 4.1], dtype=float)\np2 = np.array([1, np.nan, 6, np.nan], dtype=float)\nparameter = np.row_stack([p1, p2])\ninteractionSign = [1, -1]\nx = np.array([3, 2, 2, 1, 2, 3])\np = np.array([1, 2, 3])\n\nf1 = HillCoordinate(parameter, interactionSign, [2], [0, 1, 2], gamma=gamma)\nprint(f1(x, p))\nprint(f1.dx(x, p))\n\nparameter2 = np.array([[1, 3, 5, np.nan],\n [np.nan, 2, 6, 3]])\nf2 = HillCoordinate(parameter2, interactionSign, [2], [0, 1, 2])\np2 = np.array([gamma, 4.1, 1])\nprint(f2(x, p2))\nprint(f2.dx(x, p2))\n\nf3 = HillCoordinate(p1, [-1], [1], [0, 1], gamma=gamma)\nprint(f3(x, [1]))","sub_path":"test_HillCoordinate.py","file_name":"test_HillCoordinate.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"472668897","text":"from django.db.models.aggregates import Max\nfrom django.db.models.expressions import F, Case, When\nfrom django.db.models.fields import DateTimeField\nfrom django.db.models.query_utils import Q\nfrom django_countries.fields import CountryField\nfrom dry_rest_permissions.generics import DRYObjectPermissions, DRYPermissions\nfrom rest_framework import viewsets, generics, views, status\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\n\nfrom tunga_auth.models import USER_TYPE_PROJECT_OWNER\nfrom tunga_messages.filterbackends import received_messages_q_filter, received_replies_q_filter\nfrom tunga_messages.models import Message, Reply\nfrom tunga_profiles.filterbackends import ConnectionFilterBackend\nfrom tunga_profiles.filters import EducationFilter, WorkFilter, ConnectionFilter, SocialLinkFilter\nfrom tunga_profiles.models import UserProfile, Education, Work, Connection, SocialLink\nfrom tunga_profiles.serializers import ProfileSerializer, EducationSerializer, WorkSerializer, ConnectionSerializer, \\\n SocialLinkSerializer\nfrom tunga_utils.filterbackends import DEFAULT_FILTER_BACKENDS\n\n\nclass ProfileView(generics.CreateAPIView, generics.RetrieveUpdateDestroyAPIView):\n \"\"\"\n User Profile Info Resource\n \"\"\"\n queryset = UserProfile.objects.all()\n serializer_class = ProfileSerializer\n permission_classes = [IsAuthenticated, DRYObjectPermissions]\n\n def get_object(self):\n user = self.request.user\n if user is not None and user.is_authenticated():\n try:\n return user.userprofile\n except:\n pass\n return None\n\n\nclass SocialLinkViewSet(viewsets.ModelViewSet):\n \"\"\"\n Social Link Resource\n \"\"\"\n queryset = SocialLink.objects.all()\n serializer_class = SocialLinkSerializer\n permission_classes = [IsAuthenticated, DRYObjectPermissions]\n filter_class = SocialLinkFilter\n\n\nclass EducationViewSet(viewsets.ModelViewSet):\n \"\"\"\n Education Info Resource\n \"\"\"\n queryset = Education.objects.all()\n serializer_class = EducationSerializer\n permission_classes = [IsAuthenticated, DRYPermissions]\n filter_class = EducationFilter\n search_fields = ('institution__name', 'award')\n\n\nclass WorkViewSet(viewsets.ModelViewSet):\n \"\"\"\n Work Info Resource\n \"\"\"\n queryset = Work.objects.all()\n serializer_class = WorkSerializer\n permission_classes = [IsAuthenticated, DRYPermissions]\n filter_class = WorkFilter\n search_fields = ('company', 'position')\n\n\nclass ConnectionViewSet(viewsets.ModelViewSet):\n \"\"\"\n Connection Resource\n \"\"\"\n queryset = Connection.objects.all()\n serializer_class = ConnectionSerializer\n permission_classes = [IsAuthenticated, DRYObjectPermissions]\n filter_class = ConnectionFilter\n filter_backends = DEFAULT_FILTER_BACKENDS + (ConnectionFilterBackend,)\n search_fields = ('from_user__username', 'to_user__username')\n\n\nclass CountryListView(views.APIView):\n \"\"\"\n Country Resource\n \"\"\"\n permission_classes = [IsAuthenticated]\n\n def get(self, request):\n countries = []\n for country in CountryField().get_choices():\n countries.append({'code': country[0], 'name': country[1]})\n return Response(\n countries,\n status=status.HTTP_200_OK\n )\n\n\nclass NotificationView(views.APIView):\n \"\"\"\n Notification Resource\n \"\"\"\n permission_classes = [IsAuthenticated]\n\n def get_object(self, request):\n user = request.user\n if user is not None and user.is_authenticated():\n return user\n else:\n return None\n\n def get(self, request):\n user = self.get_object(request)\n if user is None:\n return Response(\n {'status': 'Unauthorized', 'message': 'You are not logged in'},\n status=status.HTTP_401_UNAUTHORIZED\n )\n aggregator_message_read_at = Max(\n Case(\n When(\n Q(reception__user=request.user) &\n Q(reception__message__id=F('id')),\n then='reception__read_at'\n ),\n output_field=DateTimeField()\n )\n )\n\n new_messages = Message.objects.filter(\n received_messages_q_filter(request.user)\n ).annotate(\n my_read_at=aggregator_message_read_at\n ).filter(\n Q(my_read_at=None) | Q(created_at__gt=F('my_read_at'))\n ).count()\n\n aggregator_reply_read_at = Max(\n Case(\n When(\n Q(message__user=request.user),\n then='message__read_at'\n ),\n When(\n Q(is_broadcast=True) &\n Q(message__reception__user=request.user) &\n Q(message__reception__message__id=F('message__id')),\n then='message__reception__read_at'\n ),\n output_field=DateTimeField()\n )\n )\n new_replies = Reply.objects.exclude(user=request.user).filter(\n received_replies_q_filter(request.user)\n ).annotate(my_read_at=aggregator_reply_read_at).filter(Q(my_read_at=None) | Q(created_at__gt=F('my_read_at'))).count()\n\n requests = user.connection_requests.filter(responded=False).count()\n tasks = user.tasks_created.filter(closed=False).count() + user.participation_set.filter((Q(accepted=True) | Q(responded=False)), user=user).count()\n profile = None\n profile_notifications = {'count': 0, 'missing': [], 'improve': [], 'more': [], 'section': None}\n try:\n profile = user.userprofile\n except:\n profile_notifications['missing'] = ['skills', 'bio', 'country', 'city', 'street', 'plot_number', 'phone_number']\n\n if not user.image:\n profile_notifications['missing'].append('image')\n\n if profile:\n skills = profile.skills.count()\n if skills == 0:\n profile_notifications['missing'].append('skills')\n elif skills < 3:\n profile_notifications['more'].append('skills')\n\n if not profile.bio:\n profile_notifications['missing'].append('bio')\n\n if not profile.country:\n profile_notifications['missing'].append('country')\n if not profile.city:\n profile_notifications['missing'].append('city')\n if not profile.street:\n profile_notifications['missing'].append('street')\n if not profile.plot_number:\n profile_notifications['missing'].append('plot_number')\n if not profile.phone_number:\n profile_notifications['missing'].append('phone_number')\n\n if user.type == USER_TYPE_PROJECT_OWNER and not profile.company:\n profile_notifications['missing'].append('company')\n\n profile_notifications['count'] = len(profile_notifications['missing']) + len(profile_notifications['more']) \\\n + len(profile_notifications['improve'])\n\n return Response(\n {'messages': (new_messages + new_replies), 'requests': requests, 'tasks': tasks, 'profile': profile_notifications},\n status=status.HTTP_200_OK\n )\n","sub_path":"tunga_profiles/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"524416599","text":"import datetime as dt \nimport enum\n\nclass LogLevel(enum.Enum):\n debug = 1\n info = 2\n warning = 3\n error = 4\n critical = 5\n \n# subscriber in observer pattern, receives updates from publisher.\nclass LogHandler:\n def __init__(self, logging_function, log_level):\n self.logging_function = logging_function\n self.log_level = log_level\n \n # receive update from publisher\n def update_log(self, message, log_level):\n # log levels: debug=1, info=2, warning=3, error=4, critical=5\n # ex. class log level 1 will send log updates for all incoming messages\n if(self.log_level.value <= log_level.value):\n date_time_string = str(dt.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"))\n self.logging_function('{} {} {}'.format(date_time_string, log_level.name, message))\n \n# publisher in observer pattern, send updates for subscribers.\nclass Logger:\n def __init__(self):\n self.log_handlers = set()\n \n def register_log_handler(self, log_handler):\n self.log_handlers.add(log_handler)\n \n def unregister_log_handler(self, log_handler):\n self.log_handlers.discard(log_handler)\n \n # send update for all registered subscribers\n def send_log_update(self, message, log_level):\n for log_handler in self.log_handlers:\n log_handler.update_log(message, log_level) \n\n# create publisher\nlogger = Logger()\n\n# create console log handler, receiving updates only when update message log level is greater than/equal to warning\nconsole_log_handler = LogHandler(lambda message: print(message), LogLevel.warning)\nlogger.register_log_handler(console_log_handler)\n\n# create file log handler, receiving all possible updates\nlog_file = open('/home/mikejuniperhill/log.txt', 'w')\nfile_log_handler = LogHandler(lambda message: print(message, file=log_file), LogLevel.debug)\nlogger.register_log_handler(file_log_handler)\n\n# process log updates\nlogger.send_log_update('sending calculation task to engine', LogLevel.debug)\nlogger.send_log_update('engine is processing calculation task', LogLevel.info)\nlogger.send_log_update('incorrect grid configurations, using backup grid settings', LogLevel.warning)\nlogger.send_log_update('analytical error retrieved for this calculation task', LogLevel.error)\nlogger.send_log_update('unable to process calculations task due to incorrect market data', LogLevel.critical)\n\nlog_file.close()\n\n# console output:\n# 2020-03-14 12:56:09 warning incorrect grid configurations, using backup grid settings\n# 2020-03-14 12:56:09 error analytical error retrieved for this calculation task\n# 2020-03-14 12:56:09 critical unable to process calculations task due to incorrect market data\n\n","sub_path":"Using.Observer.py","file_name":"Using.Observer.py","file_ext":"py","file_size_in_byte":2724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"576588876","text":"from flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy import Column, String, Integer, Boolean, Text, ForeignKey, Date, DateTime\nfrom sqlalchemy.orm import relationship\nfrom sqlalchemy.sql import func\nimport uuid\nimport os\n\ndb = SQLAlchemy()\n'''\nsetup_db(app):\n binds a flask application and a SQLAlchemy service\n'''\n\n\ndef setup_db(app):\n database_name = 'kwizean_db'\n KWIZEAN_DB_PASS= os.environ.get('KWIZEAN_DB_PASS')\n default_database_path = \"postgresql://{}:{}@{}/{}\".format('postgres', KWIZEAN_DB_PASS, 'localhost:5432', database_name)\n # database_path = os.getenv('DATABASE_URL', default_database_path)\n app.config[\"SQLALCHEMY_DATABASE_URI\"] = default_database_path\n app.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False\n db.app = app\n db.init_app(app)\n\n\ndef db_clean_init():\n # print(\"hello world\")\n db.drop_all()\n db.create_all()\n\n\nclass Review(db.Model):\n __tablename__ = 'reviews'\n id = Column(Integer, primary_key=True)\n user_id = Column(Integer, ForeignKey('users.id'))\n visit_date = Column(Date)\n rating = Column(Integer)\n content = Column(Text())\n restaurant_id = Column(Integer, ForeignKey('restaurants.id'))\n\n def __init__(self, visit_date, rating, content, restaurant_id, user_id):\n self.visit_date = visit_date\n self.rating = rating\n self.content = content\n self.restaurant_id = restaurant_id\n self.user_id = user_id\n\n def to_dict(self):\n return {\n 'id': self.id,\n 'date': str(self.visit_date),\n 'rating': self.rating,\n 'content': self.content,\n 'userId': self.user_id,\n 'restaurantId': self.restaurant_id,\n }\n\n def kz_update(self, date, rating, content):\n setattr(self, 'visit_date', date)\n setattr(self, 'rating', rating)\n setattr(self, 'content', content)\n db.session.commit()\n\n def insert(self):\n db.session.add(self)\n db.session.commit()\n\n def delete(self):\n db.session.delete(self)\n db.session.commit()\n\n def update(self):\n db.session.commit()\n\n\nclass Restaurant(db.Model):\n __tablename__ = 'restaurants'\n id = Column(Integer, primary_key=True)\n name = Column(String(80))\n location = Column(String(80))\n description = Column(Text())\n children = relationship(\"Review\", cascade=\"all, delete\")\n\n def __init__(self, name, location, description):\n self.name = name\n self.location = location\n self.description = description\n\n def to_dict(self):\n return {\n 'id': self.id,\n 'name': self.name,\n 'location': self.location,\n 'description': self.description,\n }\n\n def kz_update(self, name, location, description):\n setattr(self, 'name', name)\n setattr(self, 'location', location)\n setattr(self, 'description', description)\n db.session.commit()\n\n def insert(self):\n db.session.add(self)\n db.session.commit()\n\n def delete(self):\n db.session.delete(self)\n db.session.commit()\n\n def update(self):\n db.session.commit()\n\n\nclass User(db.Model):\n __tablename__ = 'users'\n id = Column(Integer, primary_key=True)\n is_admin = Column(Boolean)\n first_name = Column(String(80))\n last_name = Column(String(80))\n email = Column(String(80), unique=True)\n phone_number = Column(String(14))\n password = Column(String)\n\n def __init__(self, first_name, last_name, email, phone_number, password, is_admin=False):\n self.first_name = first_name\n self.last_name = last_name\n self.email = email\n self.phone_number = phone_number\n self.password = password\n self.is_admin = is_admin\n\n def full_name(self):\n return self.first_name + \" \" + self.last_name\n\n def to_dict(self):\n # No password. We don't want to send that down!\n return {\n 'id': self.id,\n 'isAdmin': self.is_admin,\n 'firstName': self.first_name,\n 'lastName': self.last_name,\n 'email': self.email,\n 'phoneNumber': self.phone_number\n }\n\n def kz_update(self, is_admin, first_name, last_name, email, phone_number):\n setattr(self, 'is_admin', is_admin)\n setattr(self, 'first_name', first_name)\n setattr(self, 'last_name', last_name)\n setattr(self, 'email', email)\n setattr(self, 'phone_number', phone_number)\n db.session.commit()\n\n def insert(self):\n db.session.add(self)\n db.session.commit()\n\n def delete(self):\n db.session.delete(self)\n db.session.commit()\n\n def update(self):\n db.session.commit()\n\n\nclass KZSession(db.Model):\n __tablename__ = 'sessions'\n id = Column(Integer, primary_key=True)\n user_id = Column(Integer, ForeignKey('users.id'))\n creation_time = Column(DateTime(timezone=True), default=func.now())\n token = Column(Text())\n\n def __init__(self, user_id):\n self.user_id = user_id\n self.token = uuid.uuid4().hex\n\n def insert(self):\n db.session.add(self)\n db.session.commit()\n\n def delete(self):\n db.session.delete(self)\n db.session.commit()\n","sub_path":"Kwizean/server/database/db_config.py","file_name":"db_config.py","file_ext":"py","file_size_in_byte":5251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"91518768","text":"from .models import comment\nfrom rest_framework import serializers\nfrom .models import comment\n\n\n\ndef multiple_of_ten(value):\n if value % 10 != 0:\n raise serializers.ValidationError('Not a multiple of ten')\n\nclass commentserializer(serializers.ModelSerializer):\n num = serializers.IntegerField(label='Number',validators=[multiple_of_ten])\n\n email2=serializers.EmailField(label=\"confirm email\")\n class Meta:\n model=comment\n fields=\"__all__\"\n # [\n # \"email\",\n # \"email2\",\n # \"content\",\n \n # ]\n\n def validate_email2(self,value):\n data=self.get_initial()\n email1=data.get(\"email\")\n email2=value\n if(email1!=email2):\n raise serializers.ValidationError(\"Email doesnt match\")\n return value\n\n def validate(self,data):\n email=data[\"email\"]\n qs=comment.objects.filter(email=email)\n if qs.exists():\n raise serializers.ValidationError(\"User already exists\")\n return data\n\n # def create(self,validated_data):\n # email=validated_data[\"email\"]\n # content=validated_data[\"content\"]\n # ob=comment(email=email,content=content)\n # ob.save()\n # return validated_data\n\n # def update(self,instance,validated_data):\n # instance.email=validated_data.get('email',instance.email)\n # instance.content=validated_data.get('content',instance.content)\n # instance.save()\n # return instance","sub_path":"validation/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"392748015","text":"# -*- encoding: UTF-8 -*-\r\nimport sys\r\nimport argparse\r\n\r\n# Разбор входных параметров.\r\ndef argparser():\r\n parser = argparse.ArgumentParser(prog='leftrect',\r\n description='integration by method left rectangle. Version 1.0.0.0.')\r\n parser.add_argument('-a', required=True, type=float, help='lower bound.')\r\n parser.add_argument('-b', required=True, type=float, help='upper bound.')\r\n parser.add_argument('-e', required=False, default=1e-6, type=float, help='precision.')\r\n parser.add_argument('-output', required=False,\r\n default='output.txt', help='output file, where result will be written.')\r\n return parser.parse_args()\r\n\r\n\r\ndef left_rect(a, b, n):\r\n\tfrom math import sin\r\n\th = (b-a)/n\r\n\treturn h*sum([sin(a+i*h) for i in range(n)])\r\n\r\ndef main():\r\n\tfrom math import fabs\r\n\targs = argparser()\r\n\tn = 1\r\n\ti = 0\r\n\ts1 = left_rect(args.a, args.b, n)\r\n\twhile True:\r\n\t\tn *= 2\r\n\t\ti += 1\r\n\t\t#print(i, n, s1)\r\n\t\ts2 = left_rect(args.a, args.b, n)\r\n\t\tif fabs(s2-s1) < args.e:\r\n\t\t\tbreak\r\n\t\telse:\r\n\t\t\ts1 = s2\r\n\tprint('\\\\int_{0}^{1} f(x)dx = {2} (after {3} iterations).'.format(args.a, args.b, s2, i))\r\n\twrite_data(args.output, s2)\r\n\r\ndef write_data(file, value):\r\n f=open(file, 'w')\r\n f.write(str(value))\r\n f.flush()\r\n f.close()\r\n\r\nmain()","sub_path":"integration/leftrect.py","file_name":"leftrect.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"91607302","text":"# coding: utf-8\n\n\"\"\"\n MDES for Merchants\n\n The MDES APIs are designed as RPC style stateless web services where each API endpoint represents an operation to be performed. All request and response payloads are sent in the JSON (JavaScript Object Notation) data-interchange format. Each endpoint in the API specifies the HTTP Method used to access it. All strings in request and response objects are to be UTF-8 encoded. Each API URI includes the major and minor version of API that it conforms to. This will allow multiple concurrent versions of the API to be deployed simultaneously. # noqa: E501\n\n The version of the OpenAPI document: 1.2.7\n Generated by: https://openapi-generator.tech\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\n\nclass GetTokenRequestSchema(object):\n \"\"\"NOTE: This class is auto generated by OpenAPI Generator.\n Ref: https://openapi-generator.tech\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n openapi_types = {\n 'response_host': 'str',\n 'request_id': 'str',\n 'payment_app_instance_id': 'str',\n 'token_unique_reference': 'str',\n 'include_token_detail': 'str'\n }\n\n attribute_map = {\n 'response_host': 'responseHost',\n 'request_id': 'requestId',\n 'payment_app_instance_id': 'paymentAppInstanceId',\n 'token_unique_reference': 'tokenUniqueReference',\n 'include_token_detail': 'includeTokenDetail'\n }\n\n def __init__(self, response_host=None, request_id=None, payment_app_instance_id=None, token_unique_reference=None, include_token_detail=None): # noqa: E501\n \"\"\"GetTokenRequestSchema - a model defined in OpenAPI\"\"\" # noqa: E501\n\n self._response_host = None\n self._request_id = None\n self._payment_app_instance_id = None\n self._token_unique_reference = None\n self._include_token_detail = None\n self.discriminator = None\n\n if response_host is not None:\n self.response_host = response_host\n self.request_id = request_id\n if payment_app_instance_id is not None:\n self.payment_app_instance_id = payment_app_instance_id\n self.token_unique_reference = token_unique_reference\n if include_token_detail is not None:\n self.include_token_detail = include_token_detail\n\n @property\n def response_host(self):\n \"\"\"Gets the response_host of this GetTokenRequestSchema. # noqa: E501\n\n The host that originated the request. Future calls in the same conversation may be routed to this host. # noqa: E501\n\n :return: The response_host of this GetTokenRequestSchema. # noqa: E501\n :rtype: str\n \"\"\"\n return self._response_host\n\n @response_host.setter\n def response_host(self, response_host):\n \"\"\"Sets the response_host of this GetTokenRequestSchema.\n\n The host that originated the request. Future calls in the same conversation may be routed to this host. # noqa: E501\n\n :param response_host: The response_host of this GetTokenRequestSchema. # noqa: E501\n :type: str\n \"\"\"\n\n self._response_host = response_host\n\n @property\n def request_id(self):\n \"\"\"Gets the request_id of this GetTokenRequestSchema. # noqa: E501\n\n Unique identifier for the request. # noqa: E501\n\n :return: The request_id of this GetTokenRequestSchema. # noqa: E501\n :rtype: str\n \"\"\"\n return self._request_id\n\n @request_id.setter\n def request_id(self, request_id):\n \"\"\"Sets the request_id of this GetTokenRequestSchema.\n\n Unique identifier for the request. # noqa: E501\n\n :param request_id: The request_id of this GetTokenRequestSchema. # noqa: E501\n :type: str\n \"\"\"\n if request_id is None:\n raise ValueError(\"Invalid value for `request_id`, must not be `None`\") # noqa: E501\n\n self._request_id = request_id\n\n @property\n def payment_app_instance_id(self):\n \"\"\"Gets the payment_app_instance_id of this GetTokenRequestSchema. # noqa: E501\n\n Identifier for the specific Mobile Payment App instance, unique across a given Wallet Identifier. This value cannot be changed after digitization. This field is alphanumeric and additionally web-safe base64 characters per RFC 4648 (minus \\\"-\\\", underscore \\\"_\\\") up to a maximum length of 48, = should not be URL encoded. Conditional - not applicable for server-based tokens but required otherwise. __Max Length:48__ # noqa: E501\n\n :return: The payment_app_instance_id of this GetTokenRequestSchema. # noqa: E501\n :rtype: str\n \"\"\"\n return self._payment_app_instance_id\n\n @payment_app_instance_id.setter\n def payment_app_instance_id(self, payment_app_instance_id):\n \"\"\"Sets the payment_app_instance_id of this GetTokenRequestSchema.\n\n Identifier for the specific Mobile Payment App instance, unique across a given Wallet Identifier. This value cannot be changed after digitization. This field is alphanumeric and additionally web-safe base64 characters per RFC 4648 (minus \\\"-\\\", underscore \\\"_\\\") up to a maximum length of 48, = should not be URL encoded. Conditional - not applicable for server-based tokens but required otherwise. __Max Length:48__ # noqa: E501\n\n :param payment_app_instance_id: The payment_app_instance_id of this GetTokenRequestSchema. # noqa: E501\n :type: str\n \"\"\"\n\n self._payment_app_instance_id = payment_app_instance_id\n\n @property\n def token_unique_reference(self):\n \"\"\"Gets the token_unique_reference of this GetTokenRequestSchema. # noqa: E501\n\n The specific Token to be queried. __Max Length:64__ # noqa: E501\n\n :return: The token_unique_reference of this GetTokenRequestSchema. # noqa: E501\n :rtype: str\n \"\"\"\n return self._token_unique_reference\n\n @token_unique_reference.setter\n def token_unique_reference(self, token_unique_reference):\n \"\"\"Sets the token_unique_reference of this GetTokenRequestSchema.\n\n The specific Token to be queried. __Max Length:64__ # noqa: E501\n\n :param token_unique_reference: The token_unique_reference of this GetTokenRequestSchema. # noqa: E501\n :type: str\n \"\"\"\n if token_unique_reference is None:\n raise ValueError(\"Invalid value for `token_unique_reference`, must not be `None`\") # noqa: E501\n\n self._token_unique_reference = token_unique_reference\n\n @property\n def include_token_detail(self):\n \"\"\"Gets the include_token_detail of this GetTokenRequestSchema. # noqa: E501\n\n Flag to indicate if the encrypted token should be returned. __Max Length:5__ # noqa: E501\n\n :return: The include_token_detail of this GetTokenRequestSchema. # noqa: E501\n :rtype: str\n \"\"\"\n return self._include_token_detail\n\n @include_token_detail.setter\n def include_token_detail(self, include_token_detail):\n \"\"\"Sets the include_token_detail of this GetTokenRequestSchema.\n\n Flag to indicate if the encrypted token should be returned. __Max Length:5__ # noqa: E501\n\n :param include_token_detail: The include_token_detail of this GetTokenRequestSchema. # noqa: E501\n :type: str\n \"\"\"\n\n self._include_token_detail = include_token_detail\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.openapi_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, GetTokenRequestSchema):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n","sub_path":"rest_client_python/openapi_client/models/get_token_request_schema.py","file_name":"get_token_request_schema.py","file_ext":"py","file_size_in_byte":9046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"521345172","text":"###############################################################################\n#\n# Fluo4/PhotoBleach_Intensity.py\n# Average bg substract and plot intensity of various samples. Used for the\n# photo-bleaching characterization of Fluo-4\n#\n# psihas@fnal.gov\n###############################################################################\n\n# Running with atom's Hydrogen requires cell 'markers'.\n# Please do not delete cell comments # \n\n # \n\nimport csv\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport os\nimport glob\nimport pandas as pd\nimport pylab\n\n# Non-hobo style\n# \n#\nmatplotlib.rcParams.update({'font.size': 14})\n\nprint (\"imported modules..\")\n\n# Read in csv\n# \n#\n#Path = '../DATA/Fluo-4/'\n#Path = '../DATA/Bulk/'\nPath = '../DATA/MG/'\n\n# Single samples FCN or all FC*\nID = \"MG\"\nN = \"0\"\nIDL = \"Magnesium Green\"\n\n# Raw, Frac(Fraction from the 0min sample) or Irel(above control)\nToPlt = 'Raw'\n\n############################################\n# This study had 4 samples + 1 control\n# All exposed (or let stand) in intervas\n# 1 file = 1 sample at a given interval\n############################################\n\nS_control = []\n# One array for each exposure time\n# By tot minutes exposed (E) and let stand (L)\nS_0E = []\nS_5E = []\nS_10E = []\nS_20E = []\nS_30E = []\nS_30E30L = []\nS_Ba = []\n\n\n# SampleID = [\"\",ID,ID,ID,ID,ID]#,ID,ID]\n#\n# FileID = [\"C0_E0_0.csv\",\"_E0_0.csv\", \"_E10_0.csv\", \"_E20_0.csv\", \"_E60_0.csv\", \"_E60B*_0.csv\"]#, \"_E60B*_0.csv\",\"_E60B*_0.csv\"]\n# Names = [\"Control\",\"O min Exp\", \"10 min Exp\", \"30 min Exp\", \"60 min Exp\", \"Ba\"]# \"Ba\",\"Ba\"]\n# Times = [S_control,S_0E ,S_5E ,S_10E ,S_20E ,S_30E]#, S_30E30L,S_Ba]\n\nSampleID = [\"\",ID,ID,ID,ID]#,ID,ID,ID]\n\nFileID = [\"MG_E0_0.csv\",\"_E0_0.csv\", \"_E10_0.csv\", \"_E20_0.csv\", \"_E20W1_0.csv\"]#, \"_E60B*_0.csv\"]#, \"_E60B*_0.csv\",\"_E60B*_0.csv\"]\nNames = [\"Control\",\"O min Exp\", \"10 min Exp\", \"30 min Exp\", \"+ 1 week\"]#, \"Ba\"]# \"Ba\",\"Ba\"]\nTimes = [S_control,S_0E ,S_5E ,S_10E ,S_20E]# ,S_30E]#, S_30E30L,S_Ba]\n\ncols = ['black', cm.summer(1/100), cm.summer(2/15), cm.summer(4/15), cm.summer(6/15), 'hotpink', 'hotpink','hotpink','xkcd:bubblegum pink']\n\nmark=['s','s','v','v','d',\"^\",\"d\",\"^\",'d','d']\n\n# \n\n# # Print all file names for each exp time\nfor iCurve,Curves in enumerate(Times):\n print(iCurve)\n\n# Figure for all curves\nfig,ax = plt.subplots(figsize=(10,10))\n\n# To keep data from the control sample & the t=0\nIatT_0, Icontrol = [],[]\n\n## First 2 rows are words, then data up to row 99\ni,f = 7,90\n\n\n# For each exposure time, get all the files (if multiple samples), Make\n# and plot curves specified in ToPlt. Does not average yet.\nfor iCurve,Curves in enumerate(Times):\n\n Curve=[]\n print(Path + SampleID[iCurve] + FileID[iCurve])\n for files in glob.glob(Path + SampleID[iCurve] + FileID[iCurve] ):\n Curve.append(files)\n # print(Curve)\n # print(Names[iCurve],Curves)\n\n # One DATA array for each exp time\n DATA = dict()\n W, I= [],[]\n print('len',len(Curve))\n for x in range(0,len(Curve)):\n\n DATA[x] = pd.read_csv(Curve[x],delimiter=',',names=['Wavelength','Intensity','nah'])\n # print(DATA[x]['Wavelength'][3:6])\n # print(DATA[x]['Intensity'][3:6])\n\n W.append(np.array(DATA[x]['Wavelength'][i:f],dtype=float))\n I.append(np.array(DATA[x]['Intensity'][i:f],dtype=float))\n if ( iCurve == 1 and x == 0):\n Y0=np.array(DATA[x]['Intensity'][i:f],dtype=float)\n MyX=np.array(DATA[x]['Wavelength'][i:f],dtype=float)\n MyY=np.array(DATA[x]['Intensity'][i:f],dtype=float)\n\n\n if iCurve == 0:\n Icontrol.append(np.array(DATA[x]['Intensity'][i:f],dtype=float))\n if iCurve == 1:\n IatT_0.append(np.array(DATA[x]['Intensity'][i:f],dtype=float))\n\n Iemit = 1-((Icontrol[0]-MyY))\n\n if iCurve > 0:#skip control\n print(' > 0')\n MyY = MyY/np.max(Y0)\n\n Ifrac = 1-((IatT_0[0]-MyY)/IatT_0[0])\n\n if ToPlt == 'Frac':\n print('Frac')\n ax.scatter( np.array(MyX),np.array(Ifrac),\n color=cols[iCurve],\n label= Names[iCurve],\n marker=mark[iCurve],\n linewidth=1)\n\n if ToPlt == 'Raw':\n print('Raw')\n ax.scatter( MyX,MyY,\n color=cols[iCurve],\n label= Names[iCurve],\n marker=mark[iCurve],\n linewidth=1)\n\n if ToPlt == 'Irel':\n print('Raw')\n print(MyX)\n ax.scatter( np.array(MyX),np.array(Iemit),\n color=cols[iCurve],\n label= Names[iCurve],\n marker=mark[iCurve],\n linewidth=1)\n\nax.set_xlabel(r'Wavelength [nm]', fontsize=26)\n\nif ToPlt == 'Raw':\n print('R')\n ax.set_ylabel('Intensity [arb. units]', fontsize=26)\n ax.legend(loc='upper right')\n ax.axis(500.0,600.0,-0.05,1.05)\n\nif ToPlt == 'Frac':\n print('F')\n ax.set_ylabel('Intensity Fraction ', fontsize=28)\n ax.legend(loc='upper right',bbox_to_anchor=(0.6, 0.50, 0.1, 0.4),ncol=2) # still don't understand those coordinates..\n\nif ToPlt == 'Irel':\n print('I')\n ax.set_ylabel('Relative Intensity [arb. units]', fontsize=28)\n ax.legend(loc='upper right')\n\nax.text(0.01,0.96, ' Sample:'+IDL,\nverticalalignment='bottom',\nhorizontalalignment='left',\ntransform=ax.transAxes,\nfontsize=18,)\n\nfig.savefig(Path+ToPlt+'_MGN_'+ID+'_'+N+'.pdf')\n# TODO: Check if these have to be committed for my latex/markup to pull them ok.\n\n\n# \n","sub_path":"Fluo4/PhotoBleach_Intensity_CompareM.py","file_name":"PhotoBleach_Intensity_CompareM.py","file_ext":"py","file_size_in_byte":5726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"62336641","text":"import sys,doctest\ndef multiply(x,y):\n '''\n Returns the multiplication fo the two numbers.\n >>> multiply(5,2)\n 10\n '''\n return int(x)*int(y)\n\nif __name__ == '__main__':\n x,y=sys.argv[1], sys.argv[2]\n print(multiply(x,y))\n doctest.testmod(verbose=True)\n \n","sub_path":"mul.py","file_name":"mul.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"240373121","text":"from app import app\r\nfrom flask import jsonify, request, render_template\r\n\t\t\r\n@app.route('/google-charts/pie-chart')\r\ndef google_pie_chart():\r\n\tdata = {'Task' : 'Hours per Day', 'Work' : 11, 'Eat' : 2, 'Commute' : 2, 'Watching TV' : 2, 'Sleeping' : 7}\r\n\t#print(data)\r\n\treturn render_template('pie-chart.html', data=data)\r\n\t\t\r\nif __name__ == \"__main__\":\r\n app.run()","sub_path":"google-charts/pie-chart/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"523052911","text":"import math\n\ndef get_power_level(cell):\n rack_id = cell[0] + 10\n power_level = rack_id * cell[1]\n power_level += serial_number\n power_level *= rack_id\n power_level = math.floor(power_level / 100) % 10\n power_level -= 5\n return power_level\n\ndef create_square(c, s):\n return [(i,j) for i in range(c[0],c[0]+s) for j in range(c[1], c[1]+s)] \n\nwith open('input.txt') as input:\n serial_number = int(input.read())\n\n grid_size = 300 \n grid = [[(j, i) for j in range(1, grid_size+1)] for i in range(1, grid_size+1)]\n\n largest_power = dict({\n 'cell': None,\n 'power': 0 \n })\n\n square_size = 3\n for row in grid:\n for cell in row:\n c = (grid.index(row), row.index(cell))\n if c[1] <= grid_size - square_size + 1 and c[0] <= grid_size - square_size + 1:\n square = list(map(lambda c: grid[c[0]-1][c[1]-1], create_square(c, square_size)))\n power = sum(list(map(get_power_level, square)))\n if power > largest_power['power']:\n largest_power['cell'] = c\n largest_power['power'] = power\n\n print(largest_power)","sub_path":"day11/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"540861483","text":"list = [1, 10]\nfile = open('test.txt', 'r')\ntry:\n text = file.read()\n division = 10 / 1\n number = list[1]\nexcept ZeroDivisionError:\n print('Unable to perform a division by zero')\nexcept ArithmeticError:\n print('There was an error performing an arithmetic operation.')\nexcept IndexError:\n print(\"Error accessing invalid list index\")\nexcept Exception as ex:\n print(f'Unknown error. Error: {ex}')\nelse:\n print('Run when no exception occurs')\nfinally:\n print('Always run')\n print('Closing file')\n file.close()\n","sub_path":"Python-Classes/class9.py","file_name":"class9.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"592233762","text":"import csv\nimport datetime\nimport json\nimport os\nimport os.path\nimport pathlib\nimport sys\n\nimport click\nimport yaml\n\nimport osxphotos\n\nfrom ._constants import _EXIF_TOOL_URL, _PHOTOS_5_VERSION\nfrom ._version import __version__\nfrom .utils import create_path_by_date, _copy_file\n\n# TODO: add \"--any\" to search any field (e.g. keyword, description, title contains \"wedding\") (add case insensitive option)\n# TODO: add search for filename\n\n\ndef get_photos_db(*db_options):\n \"\"\" Return path to photos db, select first non-None arg \n \"\"\"\n if db_options:\n for db in db_options:\n if db is not None:\n return db\n\n # _list_libraries()\n return None\n\n # if get here, no valid database paths passed, so ask user\n\n # _, major, _ = osxphotos.utils._get_os_version()\n\n # last_lib = osxphotos.utils.get_last_library_path()\n # if last_lib is not None:\n # db = last_lib\n # return db\n\n # sys_lib = None\n # if int(major) >= 15:\n # sys_lib = osxphotos.utils.get_system_library_path()\n\n # if sys_lib is not None:\n # db = sys_lib\n # return db\n\n # db = os.path.expanduser(\"~/Pictures/Photos Library.photoslibrary\")\n # if os.path.isdir(db):\n # return db\n # else:\n # return None ### TODO: put list here\n\n\n# Click CLI object & context settings\nclass CLI_Obj:\n def __init__(self, db=None, json=False, debug=False):\n if debug:\n osxphotos._set_debug(True)\n self.db = db\n self.json = json\n\n\nCTX_SETTINGS = dict(help_option_names=[\"-h\", \"--help\"])\n\n\n@click.group(context_settings=CTX_SETTINGS)\n@click.option(\n \"--db\",\n required=False,\n metavar=\"\",\n default=None,\n help=\"Specify Photos database path.\",\n type=click.Path(exists=True),\n)\n@click.option(\n \"--json\",\n required=False,\n is_flag=True,\n default=False,\n help=\"Print output in JSON format.\",\n)\n@click.option(\"--debug\", required=False, is_flag=True, default=False, hidden=True)\n@click.version_option(__version__, \"--version\", \"-v\")\n@click.pass_context\ndef cli(ctx, db, json, debug):\n ctx.obj = CLI_Obj(db=db, json=json, debug=debug)\n\n\n@cli.command()\n@click.option(\n \"--db\",\n required=False,\n metavar=\"\",\n default=None,\n help=\"Specify Photos database path. \"\n \"Path to Photos library/database can be specified using either --db \"\n \"or directly as PHOTOS_LIBRARY positional argument.\",\n type=click.Path(exists=True),\n)\n@click.option(\n \"--json\",\n \"json_\",\n required=False,\n is_flag=True,\n default=False,\n help=\"Print output in JSON format.\",\n)\n@click.argument(\"photos_library\", nargs=-1, type=click.Path(exists=True))\n@click.pass_obj\n@click.pass_context\ndef keywords(ctx, cli_obj, db, json_, photos_library):\n \"\"\" Print out keywords found in the Photos library. \"\"\"\n\n db = get_photos_db(*photos_library, db, cli_obj.db)\n if db is None:\n click.echo(cli.commands[\"keywords\"].get_help(ctx))\n click.echo(\"\\n\\nLocated the following Photos library databases: \")\n _list_libraries()\n return\n\n photosdb = osxphotos.PhotosDB(dbfile=db)\n keywords = {\"keywords\": photosdb.keywords_as_dict}\n if json_ or cli_obj.json:\n click.echo(json.dumps(keywords))\n else:\n click.echo(yaml.dump(keywords, sort_keys=False))\n\n\n@cli.command()\n@click.option(\n \"--db\",\n required=False,\n metavar=\"\",\n default=None,\n help=\"Specify Photos database path. \"\n \"Path to Photos library/database can be specified using either --db \"\n \"or directly as PHOTOS_LIBRARY positional argument.\",\n type=click.Path(exists=True),\n)\n@click.option(\n \"--json\",\n \"json_\",\n required=False,\n is_flag=True,\n default=False,\n help=\"Print output in JSON format.\",\n)\n@click.argument(\"photos_library\", nargs=-1, type=click.Path(exists=True))\n@click.pass_obj\n@click.pass_context\ndef albums(ctx, cli_obj, db, json_, photos_library):\n \"\"\" Print out albums found in the Photos library. \"\"\"\n\n db = get_photos_db(*photos_library, db, cli_obj.db)\n if db is None:\n click.echo(cli.commands[\"albums\"].get_help(ctx))\n click.echo(\"\\n\\nLocated the following Photos library databases: \")\n _list_libraries()\n return\n\n photosdb = osxphotos.PhotosDB(dbfile=db)\n albums = {\"albums\": photosdb.albums_as_dict}\n if photosdb.db_version >= _PHOTOS_5_VERSION:\n albums[\"shared albums\"] = photosdb.albums_shared_as_dict\n\n if json_ or cli_obj.json:\n click.echo(json.dumps(albums))\n else:\n click.echo(yaml.dump(albums, sort_keys=False))\n\n\n@cli.command()\n@click.option(\n \"--db\",\n required=False,\n metavar=\"\",\n default=None,\n help=\"Specify Photos database path. \"\n \"Path to Photos library/database can be specified using either --db \"\n \"or directly as PHOTOS_LIBRARY positional argument.\",\n type=click.Path(exists=True),\n)\n@click.option(\n \"--json\",\n \"json_\",\n required=False,\n is_flag=True,\n default=False,\n help=\"Print output in JSON format.\",\n)\n@click.argument(\"photos_library\", nargs=-1, type=click.Path(exists=True))\n@click.pass_obj\n@click.pass_context\ndef persons(ctx, cli_obj, db, json_, photos_library):\n \"\"\" Print out persons (faces) found in the Photos library. \"\"\"\n\n db = get_photos_db(*photos_library, db, cli_obj.db)\n if db is None:\n click.echo(cli.commands[\"persons\"].get_help(ctx))\n click.echo(\"\\n\\nLocated the following Photos library databases: \")\n _list_libraries()\n return\n\n photosdb = osxphotos.PhotosDB(dbfile=db)\n persons = {\"persons\": photosdb.persons_as_dict}\n if json_ or cli_obj.json:\n click.echo(json.dumps(persons))\n else:\n click.echo(yaml.dump(persons, sort_keys=False))\n\n\n@cli.command()\n@click.option(\n \"--db\",\n required=False,\n metavar=\"\",\n default=None,\n help=\"Specify Photos database path. \"\n \"Path to Photos library/database can be specified using either --db \"\n \"or directly as PHOTOS_LIBRARY positional argument.\",\n type=click.Path(exists=True),\n)\n@click.option(\n \"--json\",\n \"json_\",\n required=False,\n is_flag=True,\n default=False,\n help=\"Print output in JSON format.\",\n)\n@click.argument(\"photos_library\", nargs=-1, type=click.Path(exists=True))\n@click.pass_obj\n@click.pass_context\ndef info(ctx, cli_obj, db, json_, photos_library):\n \"\"\" Print out descriptive info of the Photos library database. \"\"\"\n\n db = get_photos_db(*photos_library, db, cli_obj.db)\n if db is None:\n click.echo(cli.commands[\"info\"].get_help(ctx))\n click.echo(\"\\n\\nLocated the following Photos library databases: \")\n _list_libraries()\n return\n\n pdb = osxphotos.PhotosDB(dbfile=db)\n info = {}\n info[\"database_path\"] = pdb.db_path\n info[\"database_version\"] = pdb.db_version\n\n photos = pdb.photos()\n not_shared_photos = [p for p in photos if not p.shared]\n info[\"photo_count\"] = len(not_shared_photos)\n\n hidden = [p for p in photos if p.hidden]\n info[\"hidden_photo_count\"] = len(hidden)\n\n movies = pdb.photos(images=False, movies=True)\n not_shared_movies = [p for p in movies if not p.shared]\n info[\"movie_count\"] = len(not_shared_movies)\n\n if pdb.db_version >= _PHOTOS_5_VERSION:\n shared_photos = [p for p in photos if p.shared]\n info[\"shared_photo_count\"] = len(shared_photos)\n\n shared_movies = [p for p in movies if p.shared]\n info[\"shared_movie_count\"] = len(shared_movies)\n\n keywords = pdb.keywords_as_dict\n info[\"keywords_count\"] = len(keywords)\n info[\"keywords\"] = keywords\n\n albums = pdb.albums_as_dict\n info[\"albums_count\"] = len(albums)\n info[\"albums\"] = albums\n\n if pdb.db_version >= _PHOTOS_5_VERSION:\n albums_shared = pdb.albums_shared_as_dict\n info[\"shared_albums_count\"] = len(albums_shared)\n info[\"shared_albums\"] = albums_shared\n\n persons = pdb.persons_as_dict\n\n # handle empty person names (added by Photos 5.0+ when face detected but not identified)\n # TODO: remove this\n # noperson = \"UNKNOWN\"\n # if \"\" in persons:\n # if noperson in persons:\n # persons[noperson].append(persons[\"\"])\n # else:\n # persons[noperson] = persons[\"\"]\n # persons.pop(\"\", None)\n\n info[\"persons_count\"] = len(persons)\n info[\"persons\"] = persons\n\n if cli_obj.json or json_:\n click.echo(json.dumps(info))\n else:\n click.echo(yaml.dump(info, sort_keys=False))\n\n\n@cli.command()\n@click.option(\n \"--db\",\n required=False,\n metavar=\"\",\n default=None,\n help=\"Specify Photos database path. \"\n \"Path to Photos library/database can be specified using either --db \"\n \"or directly as PHOTOS_LIBRARY positional argument.\",\n type=click.Path(exists=True),\n)\n@click.option(\n \"--json\",\n \"json_\",\n required=False,\n is_flag=True,\n default=False,\n help=\"Print output in JSON format.\",\n)\n@click.argument(\"photos_library\", nargs=-1, type=click.Path(exists=True))\n@click.pass_obj\n@click.pass_context\ndef dump(ctx, cli_obj, db, json_, photos_library):\n \"\"\" Print list of all photos & associated info from the Photos library. \"\"\"\n\n db = get_photos_db(*photos_library, db, cli_obj.db)\n if db is None:\n click.echo(cli.commands[\"dump\"].get_help(ctx))\n click.echo(\"\\n\\nLocated the following Photos library databases: \")\n _list_libraries()\n return\n\n pdb = osxphotos.PhotosDB(dbfile=db)\n photos = pdb.photos(movies=True)\n print_photo_info(photos, json_ or cli_obj.json)\n\n\n@cli.command(name=\"list\")\n@click.option(\n \"--json\",\n \"json_\",\n required=False,\n is_flag=True,\n default=False,\n help=\"Print output in JSON format.\",\n)\n@click.pass_obj\n@click.pass_context\ndef list_libraries(ctx, cli_obj, json_):\n \"\"\" Print list of Photos libraries found on the system. \"\"\"\n _list_libraries(json_=json_ or cli_obj.json)\n\n\ndef _list_libraries(json_=False):\n \"\"\" Print list of Photos libraries found on the system. \n If json_ == True, print output as JSON (default = False) \"\"\"\n\n photo_libs = osxphotos.utils.list_photo_libraries()\n sys_lib = osxphotos.utils.get_system_library_path()\n last_lib = osxphotos.utils.get_last_library_path()\n\n if json_:\n libs = {\n \"photo_libraries\": photo_libs,\n \"system_library\": sys_lib,\n \"last_library\": last_lib,\n }\n click.echo(json.dumps(libs))\n else:\n last_lib_flag = sys_lib_flag = False\n\n for lib in photo_libs:\n if lib == sys_lib:\n click.echo(f\"(*)\\t{lib}\")\n sys_lib_flag = True\n elif lib == last_lib:\n click.echo(f\"(#)\\t{lib}\")\n last_lib_flag = True\n else:\n click.echo(f\"\\t{lib}\")\n\n if sys_lib_flag or last_lib_flag:\n click.echo(\"\\n\")\n if sys_lib_flag:\n click.echo(\"(*)\\tSystem Photos Library\")\n if last_lib_flag:\n click.echo(\"(#)\\tLast opened Photos Library\")\n\n\n@cli.command()\n@click.option(\n \"--db\",\n required=False,\n metavar=\"\",\n default=None,\n help=\"Specify Photos database path. \"\n \"Path to Photos library/database can be specified using either --db \"\n \"or directly as PHOTOS_LIBRARY positional argument.\",\n type=click.Path(exists=True),\n)\n@click.option(\n \"--json\",\n \"json_\",\n required=False,\n is_flag=True,\n default=False,\n help=\"Print output in JSON format.\",\n)\n@click.option(\"--keyword\", default=None, multiple=True, help=\"Search for keyword(s).\")\n@click.option(\"--person\", default=None, multiple=True, help=\"Search for person(s).\")\n@click.option(\"--album\", default=None, multiple=True, help=\"Search for album(s).\")\n@click.option(\"--uuid\", default=None, multiple=True, help=\"Search for UUID(s).\")\n@click.option(\n \"--title\", default=None, multiple=True, help=\"Search for TEXT in title of photo.\"\n)\n@click.option(\"--no-title\", is_flag=True, help=\"Search for photos with no title.\")\n@click.option(\n \"--description\",\n default=None,\n multiple=True,\n help=\"Search for TEXT in description of photo.\",\n)\n@click.option(\n \"--no-description\", is_flag=True, help=\"Search for photos with no description.\"\n)\n@click.option(\n \"--uti\",\n default=None,\n multiple=False,\n help=\"Search for photos whose uniform type identifier (UTI) matches TEXT\",\n)\n@click.option(\n \"-i\",\n \"--ignore-case\",\n is_flag=True,\n help=\"Case insensitive search for title or description. Does not apply to keyword, person, or album.\",\n)\n@click.option(\"--edited\", is_flag=True, help=\"Search for photos that have been edited.\")\n@click.option(\n \"--external-edit\", is_flag=True, help=\"Search for photos edited in external editor.\"\n)\n@click.option(\"--favorite\", is_flag=True, help=\"Search for photos marked favorite.\")\n@click.option(\n \"--not-favorite\", is_flag=True, help=\"Search for photos not marked favorite.\"\n)\n@click.option(\"--hidden\", is_flag=True, help=\"Search for photos marked hidden.\")\n@click.option(\"--not-hidden\", is_flag=True, help=\"Search for photos not marked hidden.\")\n@click.option(\"--missing\", is_flag=True, help=\"Search for photos missing from disk.\")\n@click.option(\n \"--not-missing\",\n is_flag=True,\n help=\"Search for photos present on disk (e.g. not missing).\",\n)\n@click.option(\n \"--shared\",\n is_flag=True,\n help=\"Search for photos in shared iCloud album (Photos 5 only).\",\n)\n@click.option(\n \"--not-shared\",\n is_flag=True,\n help=\"Search for photos not in shared iCloud album (Photos 5 only).\",\n)\n@click.option(\n \"--burst\", is_flag=True, help=\"Search for photos that were taken in a burst.\"\n)\n@click.option(\n \"--not-burst\", is_flag=True, help=\"Search for photos that are not part of a burst.\"\n)\n@click.option(\"--live\", is_flag=True, help=\"Search for Apple live photos\")\n@click.option(\n \"--not-live\", is_flag=True, help=\"Search for photos that are not Apple live photos\"\n)\n@click.option(\n \"--cloudasset\",\n is_flag=True,\n help=\"Search for photos that are part of an iCloud library\",\n)\n@click.option(\n \"--not-cloudasset\",\n is_flag=True,\n help=\"Search for photos that are not part of an iCloud library\",\n)\n@click.option(\n \"--incloud\",\n is_flag=True,\n help=\"Search for photos that are in iCloud (have been synched)\",\n)\n@click.option(\n \"--not-incloud\",\n is_flag=True,\n help=\"Search for photos that are not in iCloud (have not been synched)\",\n)\n@click.option(\n \"--only-movies\",\n is_flag=True,\n help=\"Search only for movies (default searches both images and movies).\",\n)\n@click.option(\n \"--only-photos\",\n is_flag=True,\n help=\"Search only for photos/images (default searches both images and movies).\",\n)\n@click.argument(\"photos_library\", nargs=-1, type=click.Path(exists=True))\n@click.pass_obj\n@click.pass_context\ndef query(\n ctx,\n cli_obj,\n db,\n photos_library,\n keyword,\n person,\n album,\n uuid,\n title,\n no_title,\n description,\n no_description,\n ignore_case,\n json_,\n edited,\n external_edit,\n favorite,\n not_favorite,\n hidden,\n not_hidden,\n missing,\n not_missing,\n shared,\n not_shared,\n only_movies,\n only_photos,\n uti,\n burst,\n not_burst,\n live,\n not_live,\n cloudasset,\n not_cloudasset,\n incloud,\n not_incloud,\n):\n \"\"\" Query the Photos database using 1 or more search options; \n if more than one option is provided, they are treated as \"AND\" \n (e.g. search for photos matching all options).\n \"\"\"\n\n # if no query terms, show help and return\n if not any(\n [\n keyword,\n person,\n album,\n uuid,\n title,\n no_title,\n description,\n no_description,\n edited,\n external_edit,\n favorite,\n not_favorite,\n hidden,\n not_hidden,\n missing,\n not_missing,\n shared,\n not_shared,\n only_movies,\n only_photos,\n uti,\n burst,\n not_burst,\n live,\n not_live,\n cloudasset,\n not_cloudasset,\n incloud,\n not_incloud,\n ]\n ):\n click.echo(cli.commands[\"query\"].get_help(ctx))\n return\n elif favorite and not_favorite:\n # can't search for both favorite and notfavorite\n click.echo(cli.commands[\"query\"].get_help(ctx))\n return\n elif hidden and not_hidden:\n # can't search for both hidden and nothidden\n click.echo(cli.commands[\"query\"].get_help(ctx))\n return\n elif missing and not_missing:\n # can't search for both missing and notmissing\n click.echo(cli.commands[\"query\"].get_help(ctx))\n return\n elif title and no_title:\n # can't search for both title and no_title\n click.echo(cli.commands[\"query\"].get_help(ctx))\n return\n elif description and no_description:\n # can't search for both description and no_description\n click.echo(cli.commands[\"query\"].get_help(ctx))\n return\n elif only_photos and only_movies:\n # can't have only photos and only movies\n click.echo(cli.commands[\"query\"].get_help(ctx))\n return\n elif burst and not_burst:\n # can't search for both burst and not_burst\n click.echo(cli.commands[\"query\"].get_help(ctx))\n return\n elif live and not_live:\n # can't search for both live and not_live\n click.echo(cli.commands[\"query\"].get_help(ctx))\n return\n elif cloudasset and not_cloudasset:\n # can't search for both live and not_live\n click.echo(cli.commands[\"query\"].get_help(ctx))\n return\n elif incloud and not_incloud:\n # can't search for both live and not_live\n click.echo(cli.commands[\"query\"].get_help(ctx))\n return\n\n # actually have something to query\n isphoto = ismovie = True # default searches for everything\n if only_movies:\n isphoto = False\n if only_photos:\n ismovie = False\n\n db = get_photos_db(*photos_library, db, cli_obj.db)\n if db is None:\n click.echo(cli.commands[\"query\"].get_help(ctx))\n click.echo(\"\\n\\nLocated the following Photos library databases: \")\n _list_libraries()\n return\n\n photos = _query(\n db,\n keyword,\n person,\n album,\n uuid,\n title,\n no_title,\n description,\n no_description,\n ignore_case,\n edited,\n external_edit,\n favorite,\n not_favorite,\n hidden,\n not_hidden,\n missing,\n not_missing,\n shared,\n not_shared,\n isphoto,\n ismovie,\n uti,\n burst,\n not_burst,\n live,\n not_live,\n cloudasset,\n not_cloudasset,\n incloud,\n not_incloud,\n )\n print_photo_info(photos, cli_obj.json or json_)\n\n\n@cli.command()\n@click.option(\n \"--db\",\n required=False,\n metavar=\"\",\n default=None,\n help=\"Specify Photos database path. \"\n \"Path to Photos library/database can be specified using either --db \"\n \"or directly as PHOTOS_LIBRARY positional argument.\",\n type=click.Path(exists=True),\n)\n@click.option(\"--keyword\", default=None, multiple=True, help=\"Search for keyword(s).\")\n@click.option(\"--person\", default=None, multiple=True, help=\"Search for person(s).\")\n@click.option(\"--album\", default=None, multiple=True, help=\"Search for album(s).\")\n@click.option(\"--uuid\", default=None, multiple=True, help=\"Search for UUID(s).\")\n@click.option(\n \"--title\", default=None, multiple=True, help=\"Search for TEXT in title of photo.\"\n)\n@click.option(\"--no-title\", is_flag=True, help=\"Search for photos with no title.\")\n@click.option(\n \"--description\",\n default=None,\n multiple=True,\n help=\"Search for TEXT in description of photo.\",\n)\n@click.option(\n \"--no-description\", is_flag=True, help=\"Search for photos with no description.\"\n)\n@click.option(\n \"--uti\",\n default=None,\n multiple=False,\n help=\"Search for photos whose uniform type identifier (UTI) matches TEXT\",\n)\n@click.option(\n \"-i\",\n \"--ignore-case\",\n is_flag=True,\n help=\"Case insensitive search for title or description. Does not apply to keyword, person, or album.\",\n)\n@click.option(\"--edited\", is_flag=True, help=\"Search for photos that have been edited.\")\n@click.option(\n \"--external-edit\", is_flag=True, help=\"Search for photos edited in external editor.\"\n)\n@click.option(\"--favorite\", is_flag=True, help=\"Search for photos marked favorite.\")\n@click.option(\n \"--not-favorite\", is_flag=True, help=\"Search for photos not marked favorite.\"\n)\n@click.option(\"--hidden\", is_flag=True, help=\"Search for photos marked hidden.\")\n@click.option(\"--not-hidden\", is_flag=True, help=\"Search for photos not marked hidden.\")\n@click.option(\n \"--burst\", is_flag=True, help=\"Search for photos that were taken in a burst.\"\n)\n@click.option(\n \"--not-burst\", is_flag=True, help=\"Search for photos that are not part of a burst.\"\n)\n@click.option(\"--live\", is_flag=True, help=\"Search for Apple live photos\")\n@click.option(\n \"--not-live\", is_flag=True, help=\"Search for photos that are not Apple live photos\"\n)\n@click.option(\n \"--shared\",\n is_flag=True,\n help=\"Search for photos in shared iCloud album (Photos 5 only).\",\n)\n@click.option(\n \"--not-shared\",\n is_flag=True,\n help=\"Search for photos not in shared iCloud album (Photos 5 only).\",\n)\n@click.option(\"--verbose\", \"-V\", is_flag=True, help=\"Print verbose output.\")\n@click.option(\n \"--overwrite\",\n is_flag=True,\n help=\"Overwrite existing files. \"\n \"Default behavior is to add (1), (2), etc to filename if file already exists. \"\n \"Use this with caution as it may create name collisions on export. \"\n \"(e.g. if two files happen to have the same name)\",\n)\n@click.option(\n \"--export-by-date\",\n is_flag=True,\n help=\"Automatically create output folders to organize photos by date created \"\n \"(e.g. DEST/2019/12/20/photoname.jpg).\",\n)\n@click.option(\n \"--export-edited\",\n is_flag=True,\n help=\"Also export edited version of photo if an edited version exists. \"\n 'Edited photo will be named in form of \"photoname_edited.ext\"',\n)\n@click.option(\n \"--export-bursts\",\n is_flag=True,\n help=\"If a photo is a burst photo export all associated burst images in the library.\",\n)\n@click.option(\n \"--export-live\",\n is_flag=True,\n help=\"If a photo is a live photo export the associated live video component.\"\n \" Live video will have same name as photo but with .mov extension. \",\n)\n@click.option(\n \"--original-name\",\n is_flag=True,\n help=\"Use photo's original filename instead of current filename for export.\",\n)\n@click.option(\n \"--sidecar\",\n is_flag=True,\n help=\"Create JSON sidecar for each photo exported \"\n f\"in format useable by exiftool ({_EXIF_TOOL_URL}) \"\n \"The sidecar file can be used to apply metadata to the file with exiftool, for example: \"\n '\"exiftool -j=photoname.jpg.json photoname.jpg\" '\n \"The sidecar file is named in format photoname.ext.json where ext is extension of the photo (e.g. jpg). \"\n \"Note: this does not create an XMP sidecar as used by Lightroom, etc.\",\n)\n@click.option(\n \"--only-movies\",\n is_flag=True,\n help=\"Search only for movies (default searches both images and movies).\",\n)\n@click.option(\n \"--only-photos\",\n is_flag=True,\n help=\"Search only for photos/images (default searches both images and movies).\",\n)\n@click.option(\n \"--download-missing\",\n is_flag=True,\n help=\"Attempt to download missing photos from iCloud. The current implementation uses Applescript \"\n \"to interact with Photos to export the photo which will force Photos to download from iCloud if \"\n \"the photo does not exist on disk. This will be slow and will require internet connection. \"\n \"This obviously only works if the Photos library is synched to iCloud.\",\n)\n@click.argument(\"photos_library\", nargs=-1, type=click.Path(exists=True))\n@click.argument(\"dest\", nargs=1, type=click.Path(exists=True))\n@click.pass_obj\n@click.pass_context\ndef export(\n ctx,\n cli_obj,\n db,\n photos_library,\n keyword,\n person,\n album,\n uuid,\n title,\n no_title,\n description,\n no_description,\n uti,\n ignore_case,\n edited,\n external_edit,\n favorite,\n not_favorite,\n hidden,\n not_hidden,\n shared,\n not_shared,\n verbose,\n overwrite,\n export_by_date,\n export_edited,\n export_bursts,\n export_live,\n original_name,\n sidecar,\n only_photos,\n only_movies,\n burst,\n not_burst,\n live,\n not_live,\n download_missing,\n dest,\n):\n \"\"\" Export photos from the Photos database.\n Export path DEST is required.\n Optionally, query the Photos database using 1 or more search options; \n if more than one option is provided, they are treated as \"AND\" \n (e.g. search for photos matching all options).\n If no query options are provided, all photos will be exported.\n \"\"\"\n\n if not os.path.isdir(dest):\n sys.exit(\"DEST must be valid path\")\n\n # sanity check input args\n if favorite and not_favorite:\n # can't search for both favorite and notfavorite\n click.echo(cli.commands[\"export\"].get_help(ctx))\n return\n elif hidden and not_hidden:\n # can't search for both hidden and nothidden\n click.echo(cli.commands[\"export\"].get_help(ctx))\n return\n elif title and no_title:\n # can't search for both title and no_title\n click.echo(cli.commands[\"export\"].get_help(ctx))\n return\n elif description and no_description:\n # can't search for both description and no_description\n click.echo(cli.commands[\"export\"].get_help(ctx))\n return\n elif only_photos and only_movies:\n # can't have only photos and only movies\n click.echo(cli.commands[\"export\"].get_help(ctx))\n return\n elif burst and not_burst:\n # can't search for both burst and not_burst\n click.echo(cli.commands[\"export\"].get_help(ctx))\n return\n elif live and not_live:\n # can't search for both live and not_live\n click.echo(cli.commands[\"export\"].get_help(ctx))\n return\n\n isphoto = ismovie = True # default searches for everything\n if only_movies:\n isphoto = False\n if only_photos:\n ismovie = False\n\n db = get_photos_db(*photos_library, db, cli_obj.db)\n if db is None:\n click.echo(cli.commands[\"export\"].get_help(ctx))\n click.echo(\"\\n\\nLocated the following Photos library databases: \")\n _list_libraries()\n return\n\n photos = _query(\n db,\n keyword,\n person,\n album,\n uuid,\n title,\n no_title,\n description,\n no_description,\n ignore_case,\n edited,\n external_edit,\n favorite,\n not_favorite,\n hidden,\n not_hidden,\n None, # missing -- won't export these but will warn user\n None, # not-missing\n shared,\n not_shared,\n isphoto,\n ismovie,\n uti,\n burst,\n not_burst,\n live,\n not_live,\n False, # cloudasset\n False, # not_cloudasset\n False, # incloud\n False, # not_incloud\n )\n\n if photos:\n if export_bursts:\n # add the burst_photos to the export set\n photos_burst = [p for p in photos if p.burst]\n for burst in photos_burst:\n burst_set = [p for p in burst.burst_photos if not p.ismissing]\n photos.extend(burst_set)\n\n num_photos = len(photos)\n photo_str = \"photos\" if num_photos > 1 else \"photo\"\n click.echo(f\"Exporting {num_photos} {photo_str} to {dest}...\")\n if not verbose:\n # show progress bar\n with click.progressbar(photos) as bar:\n for p in bar:\n export_photo(\n p,\n dest,\n verbose,\n export_by_date,\n sidecar,\n overwrite,\n export_edited,\n original_name,\n export_live,\n download_missing,\n )\n else:\n for p in photos:\n export_path = export_photo(\n p,\n dest,\n verbose,\n export_by_date,\n sidecar,\n overwrite,\n export_edited,\n original_name,\n export_live,\n download_missing,\n )\n if export_path:\n click.echo(f\"Exported {p.filename} to {export_path}\")\n else:\n click.echo(f\"Did not export missing file {p.filename}\")\n else:\n click.echo(\"Did not find any photos to export\")\n\n\n@cli.command()\n@click.argument(\"topic\", default=None, required=False, nargs=1)\n@click.pass_context\ndef help(ctx, topic, **kw):\n \"\"\" Print help; for help on commands: help . \"\"\"\n if topic is None:\n click.echo(ctx.parent.get_help())\n else:\n ctx.info_name = topic \n click.echo(cli.commands[topic].get_help(ctx))\n\n\ndef print_photo_info(photos, json=False):\n if json:\n dump = []\n for p in photos:\n dump.append(p.json())\n click.echo(f\"[{', '.join(dump)}]\")\n else:\n # dump as CSV\n csv_writer = csv.writer(\n sys.stdout, delimiter=\",\", quotechar='\"', quoting=csv.QUOTE_MINIMAL\n )\n dump = []\n # add headers\n dump.append(\n [\n \"uuid\",\n \"filename\",\n \"original_filename\",\n \"date\",\n \"description\",\n \"title\",\n \"keywords\",\n \"albums\",\n \"persons\",\n \"path\",\n \"ismissing\",\n \"hasadjustments\",\n \"external_edit\",\n \"favorite\",\n \"hidden\",\n \"shared\",\n \"latitude\",\n \"longitude\",\n \"path_edited\",\n \"isphoto\",\n \"ismovie\",\n \"uti\",\n \"burst\",\n \"live_photo\",\n \"path_live_photo\",\n \"iscloudasset\",\n \"incloud\",\n ]\n )\n for p in photos:\n dump.append(\n [\n p.uuid,\n p.filename,\n p.original_filename,\n p.date.isoformat(),\n p.description,\n p.title,\n \", \".join(p.keywords),\n \", \".join(p.albums),\n \", \".join(p.persons),\n p.path,\n p.ismissing,\n p.hasadjustments,\n p.external_edit,\n p.favorite,\n p.hidden,\n p.shared,\n p._latitude,\n p._longitude,\n p.path_edited,\n p.isphoto,\n p.ismovie,\n p.uti,\n p.burst,\n p.live_photo,\n p.path_live_photo,\n p.iscloudasset,\n p.incloud,\n ]\n )\n for row in dump:\n csv_writer.writerow(row)\n\n\ndef _query(\n db,\n keyword,\n person,\n album,\n uuid,\n title,\n no_title,\n description,\n no_description,\n ignore_case,\n edited,\n external_edit,\n favorite,\n not_favorite,\n hidden,\n not_hidden,\n missing,\n not_missing,\n shared,\n not_shared,\n isphoto,\n ismovie,\n uti,\n burst,\n not_burst,\n live,\n not_live,\n cloudasset,\n not_cloudasset,\n incloud,\n not_incloud,\n):\n \"\"\" run a query against PhotosDB to extract the photos based on user supply criteria \"\"\"\n \"\"\" used by query and export commands \"\"\"\n \"\"\" arguments must be passed in same order as query and export \"\"\"\n \"\"\" if either is modified, need to ensure all three functions are updated \"\"\"\n\n # TODO: this is getting too hairy -- need to change to named args\n\n photosdb = osxphotos.PhotosDB(dbfile=db)\n photos = photosdb.photos(\n keywords=keyword,\n persons=person,\n albums=album,\n uuid=uuid,\n images=isphoto,\n movies=ismovie,\n )\n\n if title:\n # search title field for text\n # if more than one, find photos with all title values in title\n if ignore_case:\n # case-insensitive\n for t in title:\n t = t.lower()\n photos = [p for p in photos if p.title and t in p.title.lower()]\n else:\n for t in title:\n photos = [p for p in photos if p.title and t in p.title]\n elif no_title:\n photos = [p for p in photos if not p.title]\n\n if description:\n # search description field for text\n # if more than one, find photos with all name values in description\n if ignore_case:\n # case-insensitive\n for d in description:\n d = d.lower()\n photos = [\n p for p in photos if p.description and d in p.description.lower()\n ]\n else:\n for d in description:\n photos = [p for p in photos if p.description and d in p.description]\n elif no_description:\n photos = [p for p in photos if not p.description]\n\n if edited:\n photos = [p for p in photos if p.hasadjustments]\n\n if external_edit:\n photos = [p for p in photos if p.external_edit]\n\n if favorite:\n photos = [p for p in photos if p.favorite]\n elif not_favorite:\n photos = [p for p in photos if not p.favorite]\n\n if hidden:\n photos = [p for p in photos if p.hidden]\n elif not_hidden:\n photos = [p for p in photos if not p.hidden]\n\n if missing:\n photos = [p for p in photos if p.ismissing]\n elif not_missing:\n photos = [p for p in photos if not p.ismissing]\n\n if shared:\n photos = [p for p in photos if p.shared]\n elif not_shared:\n photos = [p for p in photos if not p.shared]\n\n if shared:\n photos = [p for p in photos if p.shared]\n elif not_shared:\n photos = [p for p in photos if not p.shared]\n\n if uti:\n photos = [p for p in photos if uti in p.uti]\n\n if burst:\n photos = [p for p in photos if p.burst]\n elif not_burst:\n photos = [p for p in photos if not p.burst]\n\n if live:\n photos = [p for p in photos if p.live_photo]\n elif not_live:\n photos = [p for p in photos if not p.live_photo]\n\n if cloudasset:\n photos = [p for p in photos if p.iscloudasset]\n elif not_cloudasset:\n photos = [p for p in photos if not p.iscloudasset]\n\n if incloud:\n photos = [p for p in photos if p.incloud]\n elif not_incloud:\n photos = [p for p in photos if not p.incloud]\n\n return photos\n\n\ndef export_photo(\n photo,\n dest,\n verbose,\n export_by_date,\n sidecar,\n overwrite,\n export_edited,\n original_name,\n export_live,\n download_missing,\n):\n \"\"\" Helper function for export that does the actual export\n photo: PhotoInfo object\n dest: destination path as string\n verbose: boolean; print verbose output\n export_by_date: boolean; create export folder in form dest/YYYY/MM/DD\n sidecar: boolean; create json sidecar file with export\n overwrite: boolean; overwrite dest file if it already exists\n original_name: boolean; use original filename instead of current filename\n export_live: boolean; also export live video component if photo is a live photo\n live video will have same name as photo but with .mov extension\n download_missing: attempt download of missing iCloud photos\n returns destination path of exported photo or None if photo was missing \n \"\"\"\n\n if not download_missing:\n if photo.ismissing:\n space = \" \" if not verbose else \"\"\n click.echo(f\"{space}Skipping missing photo {photo.filename}\")\n return None\n elif not os.path.exists(photo.path):\n space = \" \" if not verbose else \"\"\n click.echo(\n f\"{space}WARNING: file {photo.path} is missing but ismissing=False, \"\n f\"skipping {photo.filename}\"\n )\n return None\n elif photo.ismissing and not photo.iscloudasset or not photo.incloud:\n click.echo(\n f\"Skipping missing {photo.filename}: not iCloud asset or missing from cloud\"\n )\n return None\n\n filename = None\n if original_name:\n filename = photo.original_filename\n else:\n filename = photo.filename\n\n if verbose:\n click.echo(f\"Exporting {photo.filename} as {filename}\")\n\n if export_by_date:\n date_created = photo.date.timetuple()\n dest = create_path_by_date(dest, date_created)\n\n photo_path = photo.export(\n dest,\n filename,\n sidecar=sidecar,\n overwrite=overwrite,\n use_photos_export=download_missing,\n )\n\n # if export-edited, also export the edited version\n # verify the photo has adjustments and valid path to avoid raising an exception\n if export_edited and photo.hasadjustments:\n if download_missing or photo.path_edited is not None:\n edited_name = pathlib.Path(filename)\n edited_name = f\"{edited_name.stem}_edited{edited_name.suffix}\"\n if verbose:\n click.echo(f\"Exporting edited version of {filename} as {edited_name}\")\n photo.export(\n dest,\n edited_name,\n sidecar=sidecar,\n overwrite=overwrite,\n edited=True,\n use_photos_export=download_missing,\n )\n else:\n click.echo(f\"Skipping missing edited photo for {filename}\")\n\n if export_live and photo.live_photo and photo.path_live_photo is not None:\n # if destination exists, will be overwritten regardless of overwrite\n # so that name matches name of live photo\n live_name = pathlib.Path(photo_path)\n live_name = f\"{live_name.stem}.mov\"\n\n src_live = photo.path_live_photo\n dest_live = pathlib.Path(photo_path).parent / pathlib.Path(live_name)\n\n if src_live is not None:\n if verbose:\n click.echo(f\"Exporting live photo video of {filename} as {live_name}\")\n\n _copy_file(src_live, str(dest_live))\n else:\n click.echo(f\"Skipping missing live movie for {filename}\")\n\n return photo_path\n\n\nif __name__ == \"__main__\":\n cli()\n","sub_path":"osxphotos/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":39481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"385430419","text":"\"\"\"\nA file containing some basic building blocks \n\"\"\"\n\nimport torch.nn as nn\n\n\n\"\"\"\nA module which implements a stride-1 convolutional layer, then a stride-2 convolutional layer. \nThe net effect of this is to cut the image size in half.\n\nIn addition, subsampling helps to increase the effective receptive field: \n -- https://arxiv.org/pdf/1701.04128.pdf \n\"\"\"\ndef HalvingConv(in_channels, hidden_channels, out_channels):\n module = nn.Sequential(\n nn.Conv2d(in_channels, hidden_channels, kernel_size=3, padding=1, stride=1),\n nn.Batchnorm2d(),\n nn.ReLU(),\n nn.Conv2d(hidden_channels, out_channels, kernel_size=3, padding=1, stride=2),\n nn.Batchnorm2d(),\n nn.ReLU() \n )\n return module\n\ndef DoublingConv(in_channels, hidden_channels, out_channels):\n module = nn.Sequential(\n nn.ConvTranspose2d(in_channels, hidden_channels, kernel_size=3, padding=1, stride=2),\n nn.Batchnorm2d(),\n nn.ReLU(),\n nn.ConvTranspose2d(hidden_channels, out_channels, kernel_size=3, padding=1, stride=1),\n nn.Batchnorm2d(),\n nn.ReLU()\n )\n\ndef MultiLayerConv(in_channels, hidden_channels, encoded_dims, num_layers=6):\n i = in_channels\n h = hidden_channels\n o = encoded_dims\n\n # the encoder\n encoder_modules = [HalvingConv(i, h, h)]\n for _ in range(num_layers-1):\n encoder_modules.append(HalvingConv(h,h,h))\n encoder_modules.append(HalvingConv(h,h,o))\n encoder_modules.append(Flatten())\n encoder_modules.append(nn.Linear(o,o))\n encoder = nn.Sequential(*encoder_modules)\n\n # the decoder \n decoder_modules = [nn.Linear(o,o)]\n decoder_modules.append(Unflatten())\n decoder_modules.append(DoublingConv(o,h,h))\n for _ in range(num_layers-1):\n decoder_modules.append(DoublingConv(h,h,h))\n decoder_modules.append(DoublingConv(h,h,i))\n \n return encoder, decoder\n\n","sub_path":"architectures/modules.py","file_name":"modules.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"631692603","text":"import collections\nimport json\nimport sys\nimport pandas as pd\n\nfrom TM1py.Objects.Server import Server\nfrom TM1py.Objects.Process import Process\n\nif sys.version[0] == '2':\n import httplib as http_client\nelse:\n import http.client as http_client\n\n\ndef get_all_servers_from_adminhost(adminhost='localhost'):\n \"\"\" Ask Adminhost for TM1 Servers\n\n :param adminhost: IP or DNS Alias of the adminhost\n :return: List of Servers (instances of the TM1py.Server class)\n \"\"\"\n\n conn = http_client.HTTPConnection(adminhost, 5895)\n request = '/api/v1/Servers'\n conn.request('GET', request, body='')\n response = conn.getresponse().read().decode('utf-8')\n response_as_dict = json.loads(response)\n servers = []\n for server_as_dict in response_as_dict['value']:\n server = Server(server_as_dict)\n servers.append(server)\n return servers\n\n\ndef sort_addresstuple(cube_dimensions, unsorted_addresstuple):\n \"\"\" Sort the given mixed up addresstuple\n\n :param cube_dimensions: list of dimension names in correct order\n :param unsorted_addresstuple: list of Strings - ['[dim2].[elem4]','[dim1].[elem2]',...]\n\n :return:\n Tuple: ('[dim1].[elem2]','[dim2].[elem4]',...)\n \"\"\"\n sorted_addresstupple = []\n for dimension in cube_dimensions:\n # could be more than one hierarchy!\n address_elements = [item for item in unsorted_addresstuple if item.startswith('[' + dimension + '].')]\n # address_elements could be ( [dim1].[hier1].[elem1], [dim1].[hier2].[elem3] )\n for address_element in address_elements:\n sorted_addresstupple.append(address_element)\n return tuple(sorted_addresstupple)\n\n\ndef build_content_from_cellset(raw_cellset_as_dict, top=None):\n \"\"\" transform raw cellset data into concise dictionary\n\n :param raw_cellset_as_dict:\n :param top: Maximum Number of cells\n :return:\n \"\"\"\n content_as_dict = CaseAndSpaceInsensitiveTuplesDict()\n\n cube_dimensions = [dim['Name'] for dim in raw_cellset_as_dict['Cube']['Dimensions']]\n\n axe0_as_dict = raw_cellset_as_dict['Axes'][0]\n axe1_as_dict = raw_cellset_as_dict['Axes'][1]\n\n ordinal_cells = 0\n\n ordinal_axe2 = 0\n # get coordinates on axe 2: Title\n # if there are no elements on axe 2 assign empty list to elements_on_axe2\n if len(raw_cellset_as_dict['Axes']) > 2:\n axe2_as_dict = raw_cellset_as_dict['Axes'][2]\n tuples_as_dict = axe2_as_dict['Tuples'][ordinal_axe2]['Members']\n # condition for MDX Calculated Members (WITH MEMBER AS), that have no underlying Element\n elements_on_axe2 = [member['Element']['UniqueName'] if member['Element'] else member['UniqueName']\n for member\n in tuples_as_dict]\n else:\n elements_on_axe2 = []\n\n ordinal_axe1 = 0\n for i in range(axe1_as_dict['Cardinality']):\n # get coordinates on axe 1: Rows\n tuples_as_dict = axe1_as_dict['Tuples'][ordinal_axe1]['Members']\n elements_on_axe1 = [member['Element']['UniqueName'] if member['Element'] else member['UniqueName']\n for member\n in tuples_as_dict]\n ordinal_axe0 = 0\n for j in range(axe0_as_dict['Cardinality']):\n # get coordinates on axe 0: Columns\n tuples_as_dict = axe0_as_dict['Tuples'][ordinal_axe0]['Members']\n elements_on_axe0 = [member['Element']['UniqueName'] if member['Element'] else member['UniqueName']\n for member\n in tuples_as_dict]\n coordinates = elements_on_axe0 + elements_on_axe2 + elements_on_axe1\n coordinates_sorted = sort_addresstuple(cube_dimensions, coordinates)\n # get cell properties\n content_as_dict[coordinates_sorted] = raw_cellset_as_dict['Cells'][ordinal_cells]\n ordinal_axe0 += 1\n ordinal_cells += 1\n if top is not None and ordinal_cells >= top:\n break\n if top is not None and ordinal_cells >= top:\n break\n ordinal_axe1 += 1\n return content_as_dict\n\n\ndef build_ui_arrays_from_cellset(raw_cellset_as_dict, value_precision):\n \"\"\" Transform raw 1,2 or 3-dimension cellset data into concise dictionary\n\n * Useful for grids or charting libraries that want an array of cell values per row\n * Returns 3-dimensional cell structure for tabbed grids or multiple charts\n * Rows and pages are dicts, addressable by their name. Proper order of rows can be obtained in headers[1]\n * Example 'cells' return format:\n 'cells': { \n '10100': { \n 'Net Operating Income': [ 19832724.72429739,\n 20365654.788303416,\n 20729201.329183243,\n 20480205.20121749],\n 'Revenue': [ 28981046.50724231,\n 29512482.207418434,\n 29913730.038971487,\n 29563345.9542385]},\n '10200': { \n 'Net Operating Income': [ 9853293.623709997,\n 10277650.763958748,\n 10466934.096533755,\n 10333095.839474997],\n 'Revenue': [ 13888143.710000003,\n 14300216.43,\n 14502421.63,\n 14321501.940000001]}\n },\n\n\n :param raw_cellset_as_dict: raw data from TM1\n :param value_precision: Integer (optional) specifying number of decimal places to return\n :return: dict : { titles: [], headers: [axis][], cells: { Page0: { Row0: { [row values], Row1: [], ...}, ...}, ...} }\n \"\"\"\n header_map = build_headers_from_cellset(raw_cellset_as_dict, force_header_dimensionality=3)\n titles = header_map['titles']\n headers = header_map['headers']\n cardinality = header_map['cardinality']\n\n if value_precision:\n value_format_string = \"{{0:.{}f}}\".format(value_precision)\n\n cells = {}\n ordinal_cells = 0\n for z in range(cardinality[2]):\n zHeader = headers[2][z]['name']\n pages = {}\n for y in range(cardinality[1]):\n yHeader = headers[1][y]['name']\n row = []\n for x in range(cardinality[0]):\n raw_value = raw_cellset_as_dict['Cells'][ordinal_cells]['Value'] or 0\n if value_precision:\n row.append(float(value_format_string.format(raw_value)))\n else:\n row.append(raw_value)\n ordinal_cells += 1\n pages[yHeader] = row\n cells[zHeader] = pages\n return {'titles': titles, 'headers': headers, 'cells': cells}\n\n\ndef build_ui_dygraph_arrays_from_cellset(raw_cellset_as_dict, value_precision=None):\n \"\"\" Transform raw 1,2 or 3-dimension cellset data into dygraph-friendly format\n\n * Useful for grids or charting libraries that want an array of cell values per column\n * Returns 3-dimensional cell structure for tabbed grids or multiple charts\n * Example 'cells' return format:\n 'cells': { \n '10100': [ \n ['Q1-2004', 28981046.50724231, 19832724.72429739],\n ['Q2-2004', 29512482.207418434, 20365654.788303416],\n ['Q3-2004', 29913730.038971487, 20729201.329183243],\n ['Q4-2004', 29563345.9542385, 20480205.20121749]],\n '10200': [ \n ['Q1-2004', 13888143.710000003, 9853293.623709997],\n ['Q2-2004', 14300216.43, 10277650.763958748],\n ['Q3-2004', 14502421.63, 10466934.096533755],\n ['Q4-2004', 14321501.940000001, 10333095.839474997]]\n },\n \n :param raw_cellset_as_dict: raw data from TM1\n :param value_precision: Integer (optional) specifying number of decimal places to return\n :return: dict : { titles: [], headers: [axis][], cells: { Page0: [ [column name, column values], [], ... ], ...} }\n \"\"\"\n header_map = build_headers_from_cellset(raw_cellset_as_dict, force_header_dimensionality=3)\n titles = header_map['titles']\n headers = header_map['headers']\n cardinality = header_map['cardinality']\n\n if value_precision:\n value_format_string = \"{{0:.{}f}}\".format(value_precision)\n\n cells = {}\n for z in range(cardinality[2]):\n zHeader = headers[2][z]['name']\n page = []\n for x in range(cardinality[0]):\n xHeader = headers[0][x]['name']\n row = [xHeader]\n for y in range(cardinality[1]):\n cell_addr = (x + cardinality[0] * y + cardinality[0] * cardinality[1] * z)\n raw_value = raw_cellset_as_dict['Cells'][cell_addr]['Value'] or 0\n if value_precision:\n row.append(float(value_format_string.format(raw_value)))\n else:\n row.append(raw_value)\n page.append(row)\n cells[zHeader] = page\n\n return {'titles':titles, 'headers':headers, 'cells':cells}\n\ndef build_headers_from_cellset(raw_cellset_as_dict, force_header_dimensionality=1):\n \"\"\" Extract dimension headers from cellset into dictionary of titles (slicers) and headers (row,column,page)\n * Title dimensions are in a single list of dicts \n * Header dimensions are a 2-dimensional list of the element dicts\n\n * The first dimension in the header list is the axis\n * The second dimension is the list of elements on the axis\n\n * Dict format: {'name': 'element or compound name', 'members': [ {dict of dimension properties}, ... ] }\n\n * Stacked headers on an axis will have a compount 'name' created by joining the member's 'Name' properties with a '/'\n * Stacked headers will each be listed in the 'memebers' list; Single-element headers will only have one element in list\n\n :param raw_cellset_as_dict: raw data from TM1\n :param force_header_dimensionality: An optional integer (1,2 or 3) to force headers array to be at least that long\n :return: dict : { titles: [ { 'name': 'xx', 'members': {} } ], headers: [axis][ { 'name': 'xx', 'members': {} } ] }\n \"\"\"\n dimensionality = len(raw_cellset_as_dict['Axes'])\n cardinality = [raw_cellset_as_dict['Axes'][axis]['Cardinality'] for axis in range(dimensionality)]\n\n titles = []\n headers = []\n for axis in range(dimensionality):\n members = []\n for tindex in range(cardinality[axis]):\n tuples_as_dict = raw_cellset_as_dict['Axes'][axis]['Tuples'][tindex]['Members']\n name = ' / '.join(tuple(member['Name'] for member in tuples_as_dict))\n members.append({'name': name, 'members':tuples_as_dict})\n\n if (axis == dimensionality -1 and cardinality[axis] == 1):\n titles = members\n else:\n headers.append(members)\n\n\n dimensionality = len(headers)\n cardinality = [len(headers[axis]) for axis in range(dimensionality)]\n\n # Handle 1, 2 and 3-dimensional cellsets. Use dummy row/page headers when missing\n if dimensionality == 1 and force_header_dimensionality > 1:\n headers += [[{'name':'Row'}]]\n cardinality.insert(1,1)\n dimensionality += 1\n if dimensionality == 2 and force_header_dimensionality > 2:\n headers += [[{'name':'Page'}]]\n cardinality.insert(2,1)\n dimensionality += 1\n\n return {'titles':titles, 'headers':headers, 'dimensionality':dimensionality, 'cardinality':cardinality}\n\n\ndef element_names_from_element_unqiue_names(element_unique_names):\n \"\"\" Get tuple of simple element names from the full element unique names\n \n :param element_unique_names: tuple of element unique names ([dim1].[hier1].[elem1], ... )\n :return: tuple of element names: (elem1, elem2, ... )\n \"\"\"\n return tuple([unique_name[unique_name.rfind('].[') + 3:-1]\n for unique_name\n in element_unique_names])\n\n\ndef build_element_unique_names(dimension_names, element_names, hierarchy_names=None):\n \"\"\" Create tuple of unique names from dimension, hierarchy and elements\n \n :param dimension_names: \n :param element_names: \n :param hierarchy_names: \n :return: Generator\n \"\"\"\n if not hierarchy_names:\n return (\"[{}].[{}]\".format(dim, elem)\n for dim, elem\n in zip(dimension_names, hierarchy_names, element_names))\n else:\n return (\"[{}].[{}].[{}]\".format(dim, hier, elem)\n for dim, hier, elem\n in zip(dimension_names, hierarchy_names, element_names))\n\n\ndef build_pandas_dataframe_from_cellset(cellset, multiindex=True, sort_values=True):\n \"\"\"\n \n :param cellset: \n :param multiindex: True or False\n :param sort_values: Boolean to control sorting in result DataFrame\n :return: \n \"\"\"\n cellset_clean = {}\n for coordinates, cell in cellset.items():\n element_names = element_names_from_element_unqiue_names(coordinates)\n cellset_clean[element_names] = cell['Value'] if cell else None\n\n dimension_names = tuple([unique_name[1:unique_name.find('].[')] for unique_name in coordinates])\n\n # create index\n keylist = list(cellset_clean.keys())\n index = pd.MultiIndex.from_tuples(keylist, names=dimension_names)\n\n # create DataFrame\n values = list(cellset_clean.values())\n df = pd.DataFrame(values, index=index, columns=[\"Values\"])\n\n if not multiindex:\n df.reset_index(inplace=True)\n if sort_values:\n df.sort_values(inplace=True, by=list(dimension_names))\n return df\n\n\ndef build_cellset_from_pandas_dataframe(df):\n \"\"\"\n \n :param df: a Pandas Dataframe, with dimension-column mapping in correct order. As created in build_pandas_dataframe_from_cellset\n :return: a CaseAndSpaceInsensitiveTuplesDict\n \"\"\"\n if isinstance(df.index, pd.MultiIndex):\n df.reset_index(inplace=True)\n cellset = CaseAndSpaceInsensitiveTuplesDict()\n split = df.to_dict(orient='split')\n for row in split['data']:\n cellset[tuple(row[0:-1])] = row[-1]\n return cellset\n\n\ndef load_bedrock_from_github(bedrock_process_name):\n \"\"\" Load bedrock from GitHub as TM1py.Process instance\n \n :param name_bedrock_process: \n :return: \n \"\"\"\n import requests\n url = 'https://raw.githubusercontent.com/MariusWirtz/bedrock/master/json/{}.json'.format(bedrock_process_name)\n process_as_json = requests.get(url).text\n return Process.from_json(process_as_json)\n\n\ndef load_all_bedrocks_from_github():\n \"\"\" Load all Bedrocks from GitHub as TM1py.Process instances\n \n :return: \n \"\"\"\n import requests\n # Connect to Bedrock github repo and load the names of all Bedrocks\n url = \"https://api.github.com/repos/MariusWirtz/bedrock/contents/json?ref=master\"\n raw_github_data = requests.get(url).json()\n all_bedrocks = [entry['name'] for entry in raw_github_data]\n # instantiate TM1py.Process instances from github-json content\n url_to_bedrock = 'https://raw.githubusercontent.com/MariusWirtz/bedrock/master/json/{}'\n return [Process.from_json(requests.get(url_to_bedrock.format(bedrock)).text) for bedrock in all_bedrocks]\n\n\nclass CaseAndSpaceInsensitiveDict(collections.MutableMapping):\n \"\"\"A case-and-space-insensitive dict-like object with String keys.\n\n Implements all methods and operations of\n ``collections.MutableMapping`` as well as dict's ``copy``. Also\n provides ``adjusted_items``, ``adjusted_keys``.\n\n All keys are expected to be strings. The structure remembers the\n case of the last key to be set, and ``iter(instance)``,\n ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``\n will contain case-sensitive keys. \n\n However, querying and contains testing is case insensitive:\n elements = TM1pyElementsDictionary()\n elements['Travel Expesnses'] = 100\n elements['travelexpenses'] == 100 # True\n\n Entries are ordered\n \"\"\"\n\n def __init__(self, data=None, **kwargs):\n self._store = collections.OrderedDict()\n if data is None:\n data = {}\n self.update(data, **kwargs)\n\n def __setitem__(self, key, value):\n # Use the adjusted cased key for lookups, but store the actual\n # key alongside the value.\n self._store[key.lower().replace(' ', '')] = (key, value)\n\n def __getitem__(self, key):\n return self._store[key.lower().replace(' ', '')][1]\n\n def __delitem__(self, key):\n del self._store[key.lower().replace(' ', '')]\n\n def __iter__(self):\n return (casedkey for casedkey, mappedvalue in self._store.values())\n\n def __len__(self):\n return len(self._store)\n\n def adjusted_items(self):\n \"\"\"Like iteritems(), but with all adjusted keys.\"\"\"\n return (\n (adjusted_key, key_value[1])\n for (adjusted_key, key_value)\n in self._store.items()\n )\n\n def adjusted_keys(self):\n \"\"\"Like keys(), but with all adjusted keys.\"\"\"\n return (\n adjusted_key\n for (adjusted_key, key_value)\n in self._store.items()\n )\n\n def __eq__(self, other):\n if isinstance(other, collections.Mapping):\n other = CaseAndSpaceInsensitiveDict(other)\n else:\n return NotImplemented\n # Compare insensitively\n return dict(self.adjusted_items()) == dict(other.adjusted_items())\n\n # Copy is required\n def copy(self):\n return CaseAndSpaceInsensitiveDict(self._store.values())\n\n def __repr__(self):\n return str(dict(self.items()))\n\n\nclass CaseAndSpaceInsensitiveTuplesDict(collections.MutableMapping):\n \"\"\"A case-and-space-insensitive dict-like object with String-Tuples Keys.\n\n Implements all methods and operations of\n ``collections.MutableMapping`` as well as dict's ``copy``. Also\n provides ``adjusted_items``, ``adjusted_keys``.\n\n All keys are expected to be tuples of strings. The structure remembers the\n case of the last key to be set, and ``iter(instance)``,\n ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``\n will contain case-sensitive keys. \n\n However, querying and contains testing is case insensitive:\n data = CaseAndSpaceInsensitiveTuplesDict()\n data[('[Business Unit].[UK]', '[Scenario].[Worst Case]')] = 1000\n data[('[BusinessUnit].[UK]', '[Scenario].[worstcase]')] == 1000 # True\n data[('[Business Unit].[UK]', '[Scenario].[Worst Case]')] == 1000 # True\n\n Entries are ordered\n \"\"\"\n\n def __init__(self, data=None, **kwargs):\n self._store = collections.OrderedDict()\n if data is None:\n data = {}\n self.update(data, **kwargs)\n\n def __setitem__(self, key, value):\n # Use the adjusted cased key for lookups, but store the actual\n # key alongside the value.\n self._store[tuple([item.lower().replace(' ', '') for item in key])] = (key, value)\n\n def __getitem__(self, key):\n return self._store[tuple([item.lower().replace(' ', '') for item in key])][1]\n\n def __delitem__(self, key):\n del self._store[tuple([item.lower().replace(' ', '') for item in key])]\n\n def __iter__(self):\n return (casedkey for casedkey, mappedvalue in self._store.values())\n\n def __len__(self):\n return len(self._store)\n\n def adjusted_items(self):\n \"\"\"Like iteritems(), but with all adjusted keys.\"\"\"\n return (\n (adjusted_key, key_value[1])\n for (adjusted_key, key_value)\n in self._store.items()\n )\n\n def adjusted_keys(self):\n \"\"\"Like keys(), but with all adjusted keys.\"\"\"\n return (\n adjusted_key\n for (adjusted_key, key_value)\n in self._store.items()\n )\n\n def __eq__(self, other):\n if isinstance(other, collections.Mapping):\n other = CaseAndSpaceInsensitiveTuplesDict(other)\n else:\n return NotImplemented\n # Compare insensitively\n return dict(self.adjusted_items()) == dict(other.adjusted_items())\n\n # Copy is required\n def copy(self):\n return CaseAndSpaceInsensitiveTuplesDict(self._store.values())\n\n def __repr__(self):\n return str(dict(self.items()))\n","sub_path":"TM1py/Utils/Utils.py","file_name":"Utils.py","file_ext":"py","file_size_in_byte":20352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"639913351","text":"import requests\nfrom requests.auth import HTTPProxyAuth\n\nurl = \"https://twitter.com\"\nproxy_host = \"proxy.crawlera.com\"\nproxy_port = \"8010\"\nproxy_auth = HTTPProxyAuth(\"\", \"\")\nproxies = {\"https\": \"https://{}:{}/\".format(proxy_host, proxy_port)}\n\nr = requests.get(url, proxies=proxies, auth=proxy_auth,\n verify='/path/to/crawlera-ca.crt')\n\nprint(\"\"\"\nRequesting [{}]\nthrough proxy [{}]\n\nRequest Headers:\n{}\n\nResponse Time: {}\nResponse Code: {}\nResponse Headers:\n{}\n\"\"\".format(url, proxy_host, r.request.headers, r.elapsed.total_seconds(),\n r.status_code, r.headers, r.text))\n","sub_path":"_static/crawlera-python-requests-httpproxyauth.py","file_name":"crawlera-python-requests-httpproxyauth.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"627306746","text":"from time import process_time as pt\n\nclass Computer:\n def __init__(self):\n self.position = 0\n self.registers = {'a': 0, 'b': 0}\n self.instructions = {'hlf': self.half,\n 'tpl': self.triple,\n 'inc': self.increment,\n 'jmp': self.jump,\n 'jie': self.jump_even,\n 'jio': self.jump_one}\n\n def half(self, args):\n self.registers[args] //= 2\n self.position += 1\n def triple(self, args):\n self.registers[args] *= 3\n self.position += 1\n def increment(self, args):\n self.registers[args] += 1\n self.position += 1\n def jump(self, args):\n self.position += int(args)\n def jump_even(self, args):\n r, off = args.split(', ')\n offset = int(off)\n if self.registers[r] % 2 == 0:\n self.position += offset\n return\n self.position += 1\n def jump_one(self, args):\n r, off = args.split(', ')\n offset = int(off)\n if self.registers[r] == 1:\n self.position += offset\n return\n self.position += 1\n def run(self, program, a = 0, b = 0):\n self.registers['a'] = a\n self.registers['b'] = b\n self.position = 0\n while self.position >= 0 and self.position < len(program):\n i, args = program[self.position].rstrip().split(maxsplit = 1)\n self.instructions[i](args)\n\nt = pt()\nwith open('input.txt') as f:\n program = list(f.readlines())\nC = Computer()\nC.run(program)\nprint(\"Problem 1: %d\"%C.registers['b'])\nC.run(program, a = 1)\nt = pt() - t\nprint(\"Problem 2: %d\"%C.registers['b'])\nprint('Process time: %d µs'%int(t*1000000))\n","sub_path":"2015/aoc23/aoc23.py","file_name":"aoc23.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"67464192","text":"\"\"\"\nSoundex is an algorithm used to categorize phonetically, such that two names that sound alike but are spelled differently have the same representation.\n\nSoundex maps every name to a string consisting of one letter and three numbers, like `M460`.\n\nOne version of the algorithm is as follows:\n- Remove consecutive consonants with the same sound (for example, change `ck -> c`).\n- Keep the first letter. The remaining steps only apply to the rest of the string.\n- Remove all vowels, including `y`, `w`, and `h`.\n- Replace all consonants with the following digits:\n ```\n b, f, p, v -> 1\n c, g, j, k, q, s, x, z -> 2\n d, t -> 3\n l -> 4\n m, n -> 5\n r -> 6\n ```\n\nIf you don't have three numbers yet, append zeros until you do. Keep the first three numbers.\nUsing this scheme, `Jackson` and `Jaxen` both map to `J250`.\n\nImplement Soundex.\n\nhave a union find data structure for consonants with the same sound\nremove consecutive consonants with the same sound\n\nremove vowels after the first letter & and y,w,h\nreplace consonants with digits\npad if required\nthen crop\n\"\"\"\n\n\nclass UnionFind:\n def __init__(self, items):\n self.mapper = dict()\n for idx, i in enumerate(items):\n self.mapper[i] = idx\n N = len(items)\n self.parent = list(range(N))\n self.weight = [1] * N\n\n def get_parent_group(self, item):\n i = self.mapper[item]\n while self.parent[i] != self.parent[self.parent[i]]:\n self.parent[i] = self.parent[self.parent[i]]\n return self.parent[i]\n\n def join(self, item_a, item_b):\n a = self.mapper[item_a]\n b = self.mapper[item_b]\n\n pa = self.get_parent_group(a)\n pb = self.get_parent_group(b)\n if self.weight[pa] < self.weight[pb]:\n self.parent[pa] = pb\n self.weight[pb] += self.weight[pa]\n else:\n self.parent[pb] = pa\n self.weight[pa] += self.weight[pb]\n\n\ndef soundex(word, consonants, vowels, digit_map):\n without_repeat_consonants = [word[0]]\n for i in range(1, len(word)):\n prev = without_repeat_consonants[-1]\n curr = word[i]\n if consonants.get_parent_group(prev) == consonants.get_parent_group(curr):\n continue\n else:\n without_repeat_consonants.append(curr)\n without_vowels = [without_repeat_consonants[0]]\n for i in range(1, len(without_repeat_consonants)):\n if without_repeat_consonants[i] not in vowels:\n without_vowels.append(without_repeat_consonants[i])\n\n to_digits = without_vowels\n for i in range(1, len(to_digits)):\n char = to_digits[i]\n if char in digit_map:\n to_digits[i] = digit_map[char]\n while len(to_digits) < 4:\n to_digits.append(\"0\")\n if len(to_digits) > 4:\n to_digits = to_digits[:4]\n return to_digits\n","sub_path":"old/dcp_series/dcp_349.py","file_name":"dcp_349.py","file_ext":"py","file_size_in_byte":2851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"267038478","text":"import numpy as np\n#import get_patches as gp\n#import get_labels as gl\n#import patch_coordinates as pc\nfrom numpy import genfromtxt\nimport camelyon_class as cc\n\n'''\nPreviously, this script created the csv files again from scratch and imported each script.\nIt is obvious that for this there were a lot of overheads, and also a large running time\nto create the csv files. Now we just convert the csv files into an array.\n'''\n\ndata_no_tumour = genfromtxt('patch_no_tumour_coordinates.csv', delimiter=',') \ndata_tumour = genfromtxt('patch_tumour_coordinates.csv', delimiter=',') \n\nsize_array_no_tumour = len(data_no_tumour)\nsize_array_tumour = len(data_tumour)\n\ndef labels_no_tumour():\n\tlabels = np.zeros((size_array_no_tumour,2))\n\tfor i in range(size_array_no_tumour):\n\t\t\tlabels[i][0] =1\n\treturn labels\n\ndef labels_tumour():\n\tlabels = np.zeros((size_array_tumour,2))\n\tfor i in range(size_array_tumour):\n\t\t\tlabels[i][1] =1\n\treturn labels\n\ndata = np.concatenate((data_no_tumour, data_tumour) , axis = 0)\nlabels = np.concatenate((labels_no_tumour(), labels_tumour()), axis = 0)\n\np = np.random.permutation(len(labels))\n\ndata = data[p]\nlabels = labels[p]\n\ntrain_data = data[:400000,:]\ntrain_labels = labels[:400000,:]\nvalid_data = data[400000:540147,:]\nvalid_labels = labels[400000:540147,:]\ntest_data = data[540147:680295,:]\ntest_labels = labels[540147:680295,:]\n\ndef get_all_patches_no_tumour(data):\n\tpatches = np.zeros((len(data),256,256,3))\n\tfor i in range(len(data)):\n\t\tim_type = data[i][0]\n\t\tim_number = data[i][1]\n\t\tx = data[i][2]\n\t\ty = data[i][3]\n\t\timage = cc.camelyonImage(int(im_type) ,int(im_number), int(x), int(y), 0, 256, 256, 80, 10, 1000,256)\n\t\timage = image.readImage()\n\t\tpatches[i] = image\n\t\t\n\treturn patches\n\n\n\n\n","sub_path":"array_for_network.py","file_name":"array_for_network.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"192065233","text":"seq_in=input.split(\"\\n\")\nseq_out=output.split(\"\\n\")\n\ncounter=0\noutfile_in = open('train_wrong_in.txt','w')\noutfile_out = open('train_wrong_out.txt','w')\nassert(len(seq_in)==len(seq_out))\nfor i in range(len(seq_in)):\n if len(seq_in[i].split())!=len(seq_out[i].split()):\n counter+=1\n outfile_in.write(seq_in[i] + \"\\n\")\n outfile_out.write(str(i+1) + \" \" + seq_out[i] + \"\\n\")\n\noutfile_in.close()\noutfile_out.close()\n\nprint(counter)\nprint(\"finished\")","sub_path":"data/facebook/datacleaner.py","file_name":"datacleaner.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"352981381","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# ************************************************************************ \n# * \n# * @file:produceDate.py \n# * @author:guanyuduo@ihep.ac.cn \n# * @date:2021-03-18 15:53 \n# * @version 3.6 \n# * @description: Python Script \n# * @Copyright (c) all right reserved \n# * \n#************************************************************************* \n\nimport os,sys\nimport numpy as np\nimport scipy\nimport codecs\ndef readData(filename,i):\n Data = []\n with codecs.open(filename, 'r', encoding='gbk') as file_to_read:\n while True:\n lines = file_to_read.readline()\n print(lines.split())\n if not lines:\n break\n try:\n Data.append(float(lines.split()[int(i)])) \n except:\n pass\n return Data\ndef veto(filename):\n data=readData(filename,2)\n data=np.array(data)\n dataMean=np.mean(data)\n dataStd=np.std(data,ddof=1)\n boolList=np.zeros(len(data))\n for i in range (len(data)):\n if np.abs(data[i]-dataMean)>2*dataStd and i<=len(data)-5:\n for var in range(10):\n boolList[i-5+var]=1\n elif np.abs(data[i]-dataMean)>2*dataStd and i>len(data)-5:\n for var in range(5):\n boolList[i-5+var]=1\n else:\n pass\n return boolList\nimport matplotlib.pyplot as plt\nI=(readData(\"../data/Ham/sipm/正式测量/sipm不稳定2.txt\",4))\nt=[i*0.5 for i in range(len(I))]\nplt.ylabel(\"I_Ham withlight\")\nplt.xlabel(\"t\")\n\nplt.plot(t,I)\nplt.savefig(\"../resluts/Ham/SipmUnstable.png\")\n","sub_path":"src/drawSipm.py","file_name":"drawSipm.py","file_ext":"py","file_size_in_byte":1598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"35825772","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('complaints', '0005_auto_20150806_0119'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Locality',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('locality', models.CharField(max_length=100, verbose_name='Localidade')),\n ],\n ),\n migrations.CreateModel(\n name='Occurrence',\n fields=[\n ('ocurrence', models.AutoField(serialize=False, verbose_name='Ocorr\\xeancia', primary_key=True)),\n ('data_register', models.DateTimeField(auto_now_add=True, verbose_name='Data cadastro')),\n ('data_ocurrence', models.DateTimeField(verbose_name='Data de ocorr\\xeancia')),\n ('contact', models.CharField(default='Telefone', max_length=10, verbose_name='Forma de contato', choices=[('Telefone', 'Telefone'), ('Email', 'Email')])),\n ('category', models.CharField(default='Reclama\\xe7\\xe3o', max_length=10, verbose_name='Categoria', choices=[('Reclama\\xe7\\xe3o', 'Reclama\\xe7\\xe3o'), ('Sugest\\xe3o', 'Sugest\\xe3o'), ('Elogio', 'Elogio'), ('Outros', 'Outros')])),\n ('description', models.TextField(verbose_name='Descri\\xe7\\xe3o')),\n ('bus', models.ForeignKey(verbose_name='\\xf4nibus', to='complaints.Bus')),\n ('client', models.ForeignKey(verbose_name='Cliente', to='complaints.Client')),\n ('driver', models.ForeignKey(verbose_name='Motorista', to='complaints.Driver')),\n ('line', models.ForeignKey(verbose_name='Linha', to='complaints.Line')),\n ('locality', models.ForeignKey(verbose_name='Localidade', to='complaints.Locality')),\n ],\n ),\n ]\n","sub_path":"complaints/migrations/0006_locality_occurrence.py","file_name":"0006_locality_occurrence.py","file_ext":"py","file_size_in_byte":1965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"549402672","text":"#!/usr/bin/env python\n# -*- coding:gbk -*-\n\nfrom typing import List\n\nclass ShellSort:\n def sort(self, nums: List[int]) -> List[int]:\n if not nums or len(nums) < 2:\n return nums\n\n gap = 1\n while gap < len(nums) // 3:\n gap = gap * 3 + 1\n\n while gap > 0:\n for i in range(gap, len(nums)):\n pivot, index = nums[i], i - gap\n while index >= 0 and nums[index] > pivot:\n nums[index + gap] = nums[index]\n index -= gap\n nums[index + gap] = pivot\n gap //= 3\n return nums\n","sub_path":"1.数组/2.排序/3.希尔排序/ShellSort.py","file_name":"ShellSort.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"626470543","text":"# Упражнение 11.2\n\nclass Mecha:\n def __init__(self, name=\"test_unit\", x=0, y=0):\n self.name = name\n self.isdead = False\n self.x = x\n self.y = y\n self.weapon = ''\n self.inventory = []\n\n def walk(self, delta_x, delta_y):\n print(f\"{self.name} walks from ({self.x},{self.y}) \"\n f\"to ({self.x + delta_x},{self.y + delta_y})\\n\")\n self.x = self.x + delta_x\n self.y = self.y + delta_y\n\n def pickup(self, item):\n if (item.x == self.x) and (item.y == self.y) and (item.onfloor):\n print(f\"Picked up {item.name}\\n\")\n if item.attr == \"Gun\":\n self.weapon = item.name\n self.inventory.append(item)\n item.onfloor = False\n\n def drop(self, item):\n if item in self.inventory:\n self.inventory.remove(item)\n item.onfloor = True\n item.x = self.x\n item.y = self.y\n if self.weapon == item.name:\n self.weapon = ''\n print(f\"Unequipped {item.name}\")\n print(f\"Dropped {item.name}\\n\")\n else:\n print(f\"No such thing in inventory!\\n\")\n\n def shoot(self, target = None, direction = None):\n if self.weapon:\n if target:\n print(f\"pew pew in {target.name} direction!\")\n target.die()\n if direction:\n where = {'N':\"North\",'S':\"South\",'W':\"West\",'E':\"East\"}\n print(f\"pew pew in {where[direction]} direction!\\n\")\n else:\n print(\"No weapon\\n\")\n\n\n\n def show_inventory(self):\n print(\"--Inventory: ---\") \n for item in self.inventory:\n print(f\"|- {item.name}\")\n print('----------------\\n')\n\n def die(self):\n print(f\"{self.name} explodes!!!\\n\")\n self.isdead = True\n\n def __str__(self):\n if self.isdead:\n return(f\"All is left of {self.name} is a pile of scrap.\\n\")\n else:\n return(f\"Name: {self.name}\\n\"\n f\"Position: ({self.x},{self.y})\\n\"\n f\"Weapon equipped: {self.weapon}\\n\")\n\nclass AirMecha(Mecha):\n def fly(self, delta_x, delta_y):\n print(f\"{self.name} flies from ({self.x},{self.y}) \"\n f\"to ({self.x + delta_x},{self.y + delta_y})\\n\")\n self.x = self.x + delta_x\n self.y = self.y + delta_y\n\nclass Item:\n def __init__(self, name = \"Unknown name\", attr = \"Junk\", x = 0, y= 0):\n self.name = name\n self.attr = attr\n self.x = x\n self.y = y\n self.onfloor = True\n\n def __str__(self):\n if self.onfloor == True:\n return(f\"Name: {self.name}\\n\"\n f\"Position: ({self.x},{self.y})\\n\")\n else:\n return(f\"Name: {self.name}\\n\"\n f\"In someone's posession\\n\")\n\nif __name__ == \"__main__\":\n unit_00 = Mecha()\n unit_01 = AirMecha(\"target dummy\")\n rifle = Item(\"assault rifle-MK1\",\"Gun\",1,1)\n print(unit_00)\n unit_00.show_inventory()\n print(rifle)\n unit_00.walk(1, 1)\n unit_01.fly(2, 2)\n print(unit_00)\n unit_00.pickup(rifle)\n unit_00.shoot(unit_01)\n print(unit_01)\n print(unit_00)\n print(rifle)\n unit_00.walk(3, 0)\n unit_00.show_inventory()\n unit_00.drop(rifle)\n print(unit_00)\n unit_00.show_inventory()\n print(rifle)\n","sub_path":"exercise 11/11_2.py","file_name":"11_2.py","file_ext":"py","file_size_in_byte":3379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"307327958","text":"import matplotlib.pyplot as plt\nimport japanize_matplotlib\nfrom collections import defaultdict\nimport nlp_30\n\n\ndic = defaultdict(int)\nsentences = nlp_30.get_sentences()\n\nfor sentence in sentences:\n if '猫' in [morph['surface'] for morph in sentence]:\n for morph in sentence:\n if morph['pos'] != '記号':\n dic[morph['base']] += 1\n\ndel dic['猫']\ndic = sorted(dic.items(), key=lambda x: x[1], reverse=True)\n\nkeys = [item[0] for item in dic[:10]]\nvalues = [item[1] for item in dic[:10]]\nplt.figure()\nplt.bar(keys, values)\nplt.show()\n","sub_path":"src/4/nlp_37.py","file_name":"nlp_37.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"385438514","text":"\"\"\"\nGeneric prometheus Support\n\n\"\"\"\nfrom prometheus_client.parser import text_string_to_metric_families\nfrom functools import reduce\nimport logging\nimport re\n\nfrom newrelic_python_agent.plugins import base\n\nLOGGER = logging.getLogger(__name__)\n\nclass Prometheus(base.HTTPStatsPlugin):\n\n DEFAULT_PATH = 'metrics'\n GUID = 'com.meetme.newrelic_prometheus_agent'\n INCLUDE_CONFIG_KEY = 'include'\n EXCLUDE_CONFIG_KEY = 'exclude'\n GAUGES_CONFIG_KEY = 'gauges'\n\n def __init__(self, config, poll_interval, last_interval_values=None):\n super(Prometheus, self).__init__(config, poll_interval, last_interval_values)\n\n\n def add_datapoints(self, raw_metrics):\n \"\"\"Add all of the data points for a node\n\n :param str metrics: The metrics content\n\n \"\"\"\n hasMetrics = False\n if not raw_metrics:\n return\n for family in text_string_to_metric_families(raw_metrics):\n for sample in family.samples:\n hasMetrics = True\n if (\n not self.INCLUDE_CONFIG_KEY in self.config or\n sample.name in self.config[self.INCLUDE_CONFIG_KEY]\n ):\n if (\n self.EXCLUDE_CONFIG_KEY in self.config and\n sample.name in self.config[self.EXCLUDE_CONFIG_KEY]\n ):\n LOGGER.debug('Ignoring sample: %r', sample)\n else:\n name = reduce(\n (lambda k, i: k + '/' + i[0] + '/' + i[1]),\n sample.labels.iteritems(),\n sample.name\n )\n if (\n self.GAUGES_CONFIG_KEY in self.config and\n sample.name in self.config[self.GAUGES_CONFIG_KEY]\n ):\n self.add_gauge_value(name,\n sample.name,\n sample.value)\n else:\n self.add_derive_value(name,\n sample.name,\n sample.value)\n if not hasMetrics:\n LOGGER.debug('Metrics output: %r', raw_metrics)\n","sub_path":"newrelic_python_agent/plugins/prometheus.py","file_name":"prometheus.py","file_ext":"py","file_size_in_byte":2312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"246187739","text":"import sys\r\nsys.path.insert(0, '../')\r\nfrom planet_wars import issue_order\r\nfrom math import inf\r\n\r\n\r\ndef attack_weakest_enemy_planet(state):\r\n # (1) If we currently have a fleet in flight, abort plan.\r\n if len(state.my_fleets()) >= 1:\r\n return False\r\n\r\n # (2) Find my strongest planet.\r\n strongest_planet = max(state.my_planets(), key=lambda t: t.num_ships, default=None)\r\n\r\n # (3) Find the weakest enemy planet.\r\n weakest_planet = min(state.enemy_planets(), key=lambda t: t.num_ships, default=None)\r\n\r\n if not strongest_planet or not weakest_planet:\r\n # No legal source or destination\r\n return False\r\n else:\r\n # (4) Send half the ships from my strongest planet to the weakest enemy planet.\r\n return issue_order(state, strongest_planet.ID, weakest_planet.ID, strongest_planet.num_ships / 1)\r\n\r\n\r\ndef spread_to_weakest_neutral_planet(state):\r\n # (1) If we currently have a fleet in flight, just do nothing.\r\n if len(state.my_fleets()) >= 1:\r\n return False\r\n\r\n # (2) Find my strongest planet.\r\n strongest_planet = max(state.my_planets(), key=lambda p: p.num_ships, default=None)\r\n\r\n # (3) Find the weakest neutral planet.\r\n weakest_planet = min(state.neutral_planets(), key=lambda p: p.num_ships, default=None)\r\n\r\n if not strongest_planet or not weakest_planet:\r\n # No legal source or destination\r\n return False\r\n else:\r\n # (4) Send half the ships from my strongest planet to the weakest enemy planet.\r\n return issue_order(state, strongest_planet.ID, weakest_planet.ID, strongest_planet.num_ships / 2)\r\n\r\n#send larger fleet to planet enemy is sending a fleet to overtake\r\ndef counter_fleet(state):\r\n #find enemy fleet not already being countered\r\n target = None\r\n for enemy_fleet in state.enemy_fleets():\r\n if enemy_fleet.num_ships > state.planets[enemy_fleet.destination_planet].num_ships:\r\n covered = False\r\n for my_fleet in state.my_fleets():\r\n if enemy_fleet.destination_planet == my_fleet.destination_planet:\r\n #fleet already being countered\r\n covered = True\r\n break\r\n if covered == False:\r\n #eligible fleet found\r\n size = enemy_fleet.num_ships\r\n target = enemy_fleet.destination_planet\r\n break\r\n if not target:\r\n return False\r\n \r\n #find planet capable of countering the enemy fleet\r\n best_planet = state.my_planets()[0]\r\n best_dist = state.distance(best_planet.ID, target)\r\n planet_found = False\r\n for planet in state.my_planets():\r\n if planet.num_ships > size + 1:\r\n possible_dist = state.distance(planet.ID, target)\r\n if possible_dist < best_dist:\r\n best_planet = planet\r\n best_dist = possible_dist\r\n planet_found = True\r\n\r\n #send counterfleet\r\n if not planet_found:\r\n return False\r\n else:\r\n return issue_order(state, best_planet.ID, target, size + 1)\r\n\r\n#capture largest growth planet from closest eligible planet\r\ndef take_high_growth(state):\r\n target = max(state.planets, key=lambda p: p.growth_rate, default=None)\r\n best_dist = inf\r\n best_source = None\r\n best_size = None #fleet_size\r\n for planet in state.my_planets():\r\n this_dist = state.distance(planet.ID, target.ID)\r\n #this should work for a lot of cases as the # of ships needed to capture\r\n required_ships = target.num_ships + (this_dist * target.growth_rate) + 1\r\n if planet.num_ships > required_ships and this_dist < best_dist:\r\n best_source = planet\r\n best_dist = this_dist\r\n best_size = required_ships\r\n if not best_source:\r\n return False\r\n else:\r\n return issue_order(state, best_source.ID, target.ID, best_size)\r\n\r\n#send massive force to first enemy spotted\r\ndef rush_first_target(state):\r\n target = state.enemy_planets()[0]\r\n best_dist = inf\r\n best_source = None\r\n for planet in state.my_planets():\r\n this_dist = state.distance(planet.ID, target.ID)\r\n #this should work for a lot of cases as the # of ships needed to capture\r\n required_ships = target.num_ships + (this_dist * target.growth_rate) + 1\r\n if planet.num_ships > required_ships and this_dist < best_dist:\r\n best_source = planet\r\n best_dist = this_dist\r\n if not best_source:\r\n return False\r\n else:\r\n return issue_order(state, best_source.ID, target.ID, best_source.num_ships - 1)\r\n\r\n#attack every capturable planet\r\n#this alone beats every bot except easy bot\r\ndef attack(state):\r\n my_planets = iter(sorted(state.my_planets(), key=lambda p: p.num_ships))\r\n enemy_planets = [planet for planet in state.enemy_planets()\r\n if not any(fleet.destination_planet == planet.ID for fleet in state.my_fleets())]\r\n enemy_planets.sort(key=lambda p: p.num_ships)\r\n target_planets = iter(enemy_planets)\r\n\r\n success = False\r\n\r\n try:\r\n my_planet = next(my_planets)\r\n target_planet = next(target_planets)\r\n while True:\r\n required_ships = target_planet.num_ships + \\\r\n state.distance(my_planet.ID, target_planet.ID) * target_planet.growth_rate + 1\r\n\r\n if my_planet.num_ships > required_ships:\r\n success = True\r\n issue_order(state, my_planet.ID, target_planet.ID, required_ships)\r\n my_planet = next(my_planets)\r\n target_planet = next(target_planets)\r\n else:\r\n my_planet = next(my_planets)\r\n\r\n except StopIteration:\r\n return success\r\n\r\n#spread to capturable neutral planets\r\ndef spread(state):\r\n my_planets = iter(sorted(state.my_planets(), key=lambda p: p.num_ships))\r\n\r\n neutral_planets = [planet for planet in state.neutral_planets()\r\n if not any(fleet.destination_planet == planet.ID for fleet in state.my_fleets())]\r\n neutral_planets.sort(key=lambda p: p.num_ships)\r\n\r\n target_planets = iter(neutral_planets)\r\n\r\n success = False\r\n\r\n try:\r\n my_planet = next(my_planets)\r\n target_planet = next(target_planets)\r\n while True:\r\n required_ships = target_planet.num_ships + 1\r\n\r\n if my_planet.num_ships > required_ships:\r\n success = True\r\n issue_order(state, my_planet.ID, target_planet.ID, required_ships)\r\n my_planet = next(my_planets)\r\n target_planet = next(target_planets)\r\n else:\r\n my_planet = next(my_planets)\r\n\r\n except StopIteration:\r\n return success\r\n\r\n#reinforce weak planets\r\ndef defend(state):\r\n my_planets = [planet for planet in state.my_planets()]\r\n if not my_planets:\r\n return False\r\n\r\n def strength(p):\r\n return p.num_ships \\\r\n + sum(fleet.num_ships for fleet in state.my_fleets() if fleet.destination_planet == p.ID) \\\r\n - sum(fleet.num_ships for fleet in state.enemy_fleets() if fleet.destination_planet == p.ID)\r\n\r\n avg = sum(strength(planet) for planet in my_planets) / len(my_planets)\r\n\r\n weak_planets = [planet for planet in my_planets if strength(planet) < avg]\r\n strong_planets = [planet for planet in my_planets if strength(planet) > avg]\r\n\r\n if (not weak_planets) or (not strong_planets):\r\n return False\r\n\r\n weak_planets = iter(sorted(weak_planets, key=strength))\r\n strong_planets = iter(sorted(strong_planets, key=strength, reverse=True))\r\n\r\n success = False\r\n\r\n try:\r\n weak_planet = next(weak_planets)\r\n strong_planet = next(strong_planets)\r\n while True:\r\n need = int(avg - strength(weak_planet))\r\n have = int(strength(strong_planet) - avg)\r\n\r\n if have >= need > 0:\r\n success = True\r\n issue_order(state, strong_planet.ID, weak_planet.ID, need)\r\n weak_planet = next(weak_planets)\r\n elif have > 0:\r\n success = True\r\n issue_order(state, strong_planet.ID, weak_planet.ID, have)\r\n strong_planet = next(strong_planets)\r\n else:\r\n strong_planet = next(strong_planets)\r\n\r\n except StopIteration:\r\n return success\r\n\r\n#production bot's winning strategy\r\ndef production(state):\r\n my_planets = iter(sorted(state.my_planets(), key=lambda p: p.num_ships, reverse=True))\r\n\r\n target_planets = [planet for planet in state.not_my_planets()\r\n if not any(fleet.destination_planet == planet.ID for fleet in state.my_fleets())]\r\n target_planets = iter(sorted(target_planets, key=lambda p: p.num_ships, reverse=True))\r\n\r\n success = False\r\n\r\n try:\r\n my_planet = next(my_planets)\r\n target_planet = next(target_planets)\r\n while True:\r\n if target_planet.owner == 0:\r\n required_ships = target_planet.num_ships + 1\r\n else:\r\n required_ships = target_planet.num_ships + \\\r\n state.distance(my_planet.ID, target_planet.ID) * target_planet.growth_rate + 1\r\n\r\n if my_planet.num_ships > required_ships:\r\n issue_order(state, my_planet.ID, target_planet.ID, required_ships)\r\n success = True\r\n my_planet = next(my_planets)\r\n target_planet = next(target_planets)\r\n else:\r\n target_planet = next(target_planets)\r\n\r\n except StopIteration:\r\n return success\r\n\r\n#grow to nearest planet from 1 planet\r\ndef grow_from_one(state):\r\n planet = state.my_planets()[0]\r\n least_distance = inf\r\n nearest_target = None\r\n # neutral_planets = [planet for planet in state.neutral_planets()\r\n # if not any(fleet.destination_planet == planet.ID for fleet in state.my_fleets())]\r\n #neutral_planets.sort(key=lambda p: p.num_ships)\r\n\r\n for target in state.neutral_planets():\r\n target_distance = state.distance(planet.ID, target.ID)\r\n if target_distance < least_distance:\r\n required_ships = required_ships = target.num_ships + 1\r\n if planet.num_ships > required_ships:\r\n least_distance = target_distance\r\n nearest_target = target\r\n if not nearest_target:\r\n return False\r\n else:\r\n return issue_order(state, planet.ID, nearest_target.ID, required_ships)\r\n\r\n","sub_path":"behavior_tree_bot/behaviors.py","file_name":"behaviors.py","file_ext":"py","file_size_in_byte":10564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"4808290","text":"from module import Module\n\nclass SGD(Module):\n\n def __init__(self, model, lr):\n \"\"\"\n Stochastic Gradient Descent step \n \"\"\"\n super(SGD, self).__init__()\n \n self.model = model\n self.lr = lr\n \n def step(self):\n \"\"\"\n Stochastic Gradient Descent step \n \"\"\"\n for l in self.model.layers : \n for _, tup in enumerate(l.param()): #[(weights, bias, dw, db)] or [(weights, dw)] for linear module or [] for other modules (ReLU,Sigmoid...)\n if len(tup)>2:\n l.w = l.w - self.lr * l.dl_dw\n l.b = l.b - self.lr * l.dl_db\n elif len(tup)==2:\n l.w = l.w - self.lr * l.dl_dw\n else:\n raise Exception('Parameters unknown')\n \n def zero_grad(self):\n self.model.zero_grad()\n \n ","sub_path":"Proj2/optimizers.py","file_name":"optimizers.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"569970290","text":"import itertools\nimport operator\nfrom collections.abc import Iterable\nfrom typing import Set\n\nimport torch\nfrom functorch.experimental import control_flow\nfrom torch._ops import OpOverload\nfrom torch._subclasses.fake_tensor import FakeTensor\nfrom torch.fx import GraphModule\nfrom torch.fx._compatibility import compatibility\n\n\nPRESERVED_META_KEYS: Set[str] = {\n \"val\",\n \"stack_trace\",\n}\n\n\n@compatibility(is_backward_compatible=False)\nclass SpecViolationError(Exception):\n pass\n\n\n@compatibility(is_backward_compatible=False)\ndef is_functional(op: OpOverload) -> bool:\n return not op._schema.is_mutable\n\n\n@compatibility(is_backward_compatible=False)\ndef _check_has_fake_tensor(node: torch.fx.Node) -> None:\n def _check_is_fake_tensor(val):\n if isinstance(val, FakeTensor):\n return True\n if isinstance(val, Iterable):\n return all(_check_is_fake_tensor(x) for x in val)\n return False\n\n val = node.meta.get(\"val\", None)\n if val is None or not _check_is_fake_tensor(val):\n raise SpecViolationError(\"Node.meta {} is missing val field.\".format(node.name))\n\n\n@compatibility(is_backward_compatible=False)\ndef check_valid(gm: GraphModule) -> None: # noqa: C901\n\n for node in gm.graph.nodes:\n # TODO(T140410192): should have fake tensor for all dialects\n if node.op in {\"call_module\", \"call_method\"}:\n raise SpecViolationError(\n \"call_module is not valid: got a class '{}' \".format(node.target),\n )\n\n if node.op == \"call_function\":\n _check_has_fake_tensor(node)\n op_name = (\n node.target.name\n if hasattr(node.target, \"name\")\n else node.target.__name__\n )\n is_builtin_func = node.target in [\n 'while_loop',\n operator.getitem,\n 'cond',\n control_flow.cond,\n control_flow.map,\n ]\n if not isinstance(node.target, OpOverload) and not is_builtin_func:\n raise SpecViolationError(\n \"Operator '{}' is not a registered Op\".format(op_name),\n )\n\n # All ops functional\n if not is_builtin_func and not is_functional(node.target):\n raise SpecViolationError(\n f\"operator '{op_name}' is not functional\"\n )\n\n if isinstance(node.target, OpOverload):\n # Check preserved metadata\n for meta in PRESERVED_META_KEYS:\n if node.meta.get(meta, None) is None:\n raise SpecViolationError(\n f\"node {node} is missing metadata {meta}\"\n )\n\n\n@compatibility(is_backward_compatible=False)\ndef is_valid(gm: GraphModule) -> bool:\n try:\n check_valid(gm)\n return True\n except SpecViolationError:\n return False\n\n\n@compatibility(is_backward_compatible=False)\ndef _check_tensors_are_contiguous(gm: GraphModule) -> None:\n # Tensors be of contiguous format\n for name, param in itertools.chain(gm.named_parameters(), gm.named_buffers()):\n if isinstance(param, torch.Tensor):\n if not param.is_contiguous():\n raise SpecViolationError(\n f\"Tensors in Aten dialect must be contiguous, {name} is not contiguous\"\n )\n\n\n@compatibility(is_backward_compatible=False)\ndef check_valid_aten_dialect(gm: GraphModule) -> None:\n \"\"\"Raises exception if gm is not in aten dialect.\n\n Args:\n gm: GraphModule\n \"\"\"\n # need to be first valid\n check_valid(gm)\n\n # Operators be aten cannonical\n for n in gm.graph.nodes:\n if n.op == \"call_function\" and isinstance(n.target, OpOverload):\n if (\n torch.Tag.core not in n.target.tags # type: ignore[attr-defined]\n and torch.Tag.view_copy not in n.target.tags # type: ignore[attr-defined]\n ):\n # NOTE(qihan): whether view_copy operators are marked as canonical is still under\n # discussion.\n raise SpecViolationError(\n \"Operator {}.{} is not Aten Canonical.\".format(\n n.target.__module__, n.target.__name__\n )\n )\n\n _check_tensors_are_contiguous(gm)\n\n\n@compatibility(is_backward_compatible=False)\ndef is_valid_aten_dialect(gm: GraphModule) -> bool:\n try:\n check_valid_aten_dialect(gm)\n return True\n except SpecViolationError:\n return False\n","sub_path":"torch/_export/verifier.py","file_name":"verifier.py","file_ext":"py","file_size_in_byte":4621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"342825026","text":"#!/bin/env python\n# coding:utf-8\n\nimport sqlite3\nfrom StringIO import StringIO\n\nclass Tecs(object):\n def __init__(self,tecsdb,tecsabdb,tecscordb,sitesdb):\n print(\"Tecs:tecsdb=\"+str(tecsdb)+\",tecsabdb=\"+str(tecsabdb)+\",tecscordb=\"+str(tecscordb)+\",sitesdb=\"+str(sitesdb))\n #self.tecs_con = self.__in_memory(tecsdb)\n #self.sites_con = self.__in_memory(sitesdb)\n #self.tecsab_con = self.__in_memory(tecsabdb)\n #self.tecscor_con = self.__in_memory(tecscordb)\n self.tecs_con = self.__sqlite(tecsdb)\n self.sites_con = self.__sqlite(sitesdb)\n self.tecsab_con = self.__sqlite(tecsabdb)\n self.tecscor_con=self.__sqlite(tecscordb)\n\n def __sqlite(self,dbfile):\n if dbfile is None:\n return None\n return sqlite3.connect(dbfile)\n\n def __in_memory(self,dbfile):\n if dbfile is None:\n return None\n # http://stackoverflow.com/questions/3850022/how-to-load-existing-db-file-to-memory-in-python-sqlite3\n #con=sqlite3.connect(dbfile,timeout=60)\n #tempfile=StringIO()\n #for line in con.iterdump():\n # tempfile.write('%s\\n' % line)\n #con.close()\n #tempfile.seek(0)\n mcon=sqlite3.connect(\":memory:\")\n #mcon.cursor().executescript(tempfile.read())\n #mcon.commit()\n #mcon.row_factory=sqlite3.Row\n #tempfile.close()\n sql=\"\"\n for line in open(dbfile,\"r\"):\n sql=sql+line\n if sql.endswith(';'):\n mcon.cursor().executescript(sql)\n mcon.commit()\n sql=\"\"\n return mcon\n\n\n def __get_all_sites(self,lat,lon):\n sites = []\n cur = self.sites_con.cursor()\n cur.execute(\"select site from sites order by (lat-\"+lat+\")*(lat-\"+lat+\")+(lon-\"+lon+\")*(lon-\"+lon+\")\")\n res = cur.fetchall()\n for i in range(1, len(res)):\n sites.append(str(res[i][0]))\n cur.close()\n return sites\n\n def __in_memory_close(self,con):\n if con is not None:\n con.close()\n\n def term(self):\n self.__in_memory_close(self.sites_con)\n self.__in_memory_close(self.tecsab_con)\n self.__in_memory_close(self.tecs_con)\n self.__in_memory_close(self.tecscor_con)\n\n","sub_path":"engine203/tecs.py","file_name":"tecs.py","file_ext":"py","file_size_in_byte":2285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"222789730","text":"from airflow.hooks.postgres_hook import PostgresHook\nfrom airflow.models import BaseOperator\nfrom airflow.utils.decorators import apply_defaults\n\n\nclass RedshiftDataQualityOperator(BaseOperator):\n ui_color = '#89DA59'\n\n @apply_defaults\n def __init__(self,\n redshift_conn_id,\n rules,\n *args, **kwargs):\n\n self.redshift_conn_id = redshift_conn_id\n self.rules = rules\n\n super(RedshiftDataQualityOperator, self).__init__(*args, **kwargs)\n\n def execute(self, context):\n redshift_conn = PostgresHook(postgres_conn_id=self.redshift_conn_id)\n for rule in self.rules:\n query = rule['query']\n op = rule['op']\n\n records = redshift_conn.get_records(query)\n self.log.info(records)\n if not op(records[0][0]):\n raise ValueError(\"Data quality check failed.\")\n\n","sub_path":"complaints_airflow/plugins/operators/redshift_data_quality_operator.py","file_name":"redshift_data_quality_operator.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"372072196","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jul 18 19:19:23 2020\n\n@author: webst\n\"\"\"\nfrom firebase import firebase\n\n# link to the database\nconnectionURL = \"https://project-1095559261267193051.firebaseio.com/\"\n\n# the final argument is None because at the most the firebase project\n# is in test mode so it does not require any kind of authentication\nfb = firebase.FirebaseApplication(connectionURL, None)\n\n# the string format is \"\\databsename\\tablename\"\nresult = fb.put(\"/Customers/-MCZFBAthRAFEgANf_vS\",'Name', 'Billy Bob Junior')\nprint(\"Record Updated\")","sub_path":"storage/storage_update.py","file_name":"storage_update.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"349738789","text":"#!/usr/bin/env python3.6\n# -*- encoding: utf-8 -*-\n'''\n@File : Event.py\n@Time : 2020/09/29 22:07:04\n@Author : Tang Jing \n@Version : 1.0.0\n@Contact : yeihizhi@163.com\n@License : (C)Copyright 2020\n@Desc : None\n'''\n\n# here put the import lib\nimport json\nimport logging\nimport functools\nimport re\nfrom types import FunctionType\nfrom rest_framework.response import Response\nfrom TDhelper.generic.classDocCfg import doc\nfrom TDhelper.generic.dictHelper import createDictbyStr, findInDict\nfrom TDhelper.network.http.REST_HTTP import GET, POST, PUT, DELETE, serializePostData\nfrom TDhelper.generic.requier import R, InstanceCall\n# code start\n\n\nclass Event:\n '''\n if method need listen must have *args,**kwargs params. this params will recv results for this listen func and results for trigger method .\n 1.you can use kwargs['func_results'] get listen method's return.\n 2.you can use kwargs['trigger_results'] get trigger method's return.\n '''\n\n def __init__(self, event_uri, platformKey: str, secret=None, httpHeaders={}):\n self._event_uri = event_uri + \\\n ('/' if event_uri.find('/', len(event_uri)-1) <= -1 else '')\n self._platformKey = platformKey\n self._httpHeaders = httpHeaders\n self._httpHeaders['api-token'] = secret if secret else ''\n\n def Register(self, serviceClass= None):\n if not serviceClass:\n serviceClass= type(self)\n for k, v in serviceClass.__dict__.items():\n if isinstance(v, FunctionType):\n if not k.startswith(\"__\"):\n if not k.startswith(\"_\"):\n self._handleRegister(v)\n\n def _handleRegister(self, v):\n # todo register handle\n k = v.__qualname__.replace('.', \"_\").upper()\n config = v.__doc__\n config= doc(v.__doc__,\"event\")\n if config:\n config = re.sub(r'[\\r|\\n]', r'', config, count=0, flags=0).strip()\n try:\n config = json.loads(config, encoding='utf-8')\n except:\n config = None\n try:\n if config:\n if 'key' in config['handle']:\n k= config['handle']['key']\n k= self._platformKey+\".\"+k\n post_data = {\n \"name\": config['handle']['name'],\n \"key\": k,\n \"plateformKey\": self._platformKey,\n \"description\": config['handle']['description'],\n \"params\": {},\n \"resultChecked\": config['handle']['resultChecked']\n }\n params_str = {}\n if 'params' not in config['handle']:\n parmas_tmp=v.__wrapped__.__code__.co_varnames[0:v.__wrapped__.__code__.co_argcount]\n for var_name in parmas_tmp:\n if var_name.lower() == 'args':\n params_str[var_name] = {\"type\": \"\"}\n elif var_name.lower() == \"kwargs\":\n params_str[var_name] = {\"type\": \"\"}\n else:\n params_str[var_name] = {\"type\": \"\"}\n for var_name, var_value in v.__wrapped__.__annotations__.items():\n params_str[var_name]['type'] = str(var_value)\n if v.__wrapped__.__defaults__:\n for i in range(len(parmas_tmp), 0, -1):\n if parmas_tmp[i-1] == 'args' or parmas_tmp[i-1] == 'kwargs':\n continue\n offset = i - 2\n if offset >= 0:\n if offset < len(v.__wrapped__.__defaults__):\n params_str[parmas_tmp[i-1]\n ][\"default\"] = v.__wrapped__.__defaults__[offset]\n else:\n break\n post_data['params'] = params_str\n else:\n post_data['params']= config['handle']['params']\n post_data = serializePostData(post_data)\n state, body = POST(self._event_uri+\"handle/\", post_data=post_data,\n http_headers=self._httpHeaders, time_out=15)\n if state == 200:\n ret = body\n if isinstance(body, bytes):\n ret = json.loads(str(body, encoding='utf-8'))\n if ret['state'] == 200:\n logging.info(\"handle(%s) register SUCCESS\" % k)\n handleId = ret['msg']['id']\n if 'trigger' in config:\n self._triggerRegister(\n k, handleId, config['trigger'])\n else:\n logging.error(\n \"register handle %s is error. %s\" % (k, ret['msg']))\n else:\n logging.error(\"access register service failed.%s\" % body)\n except Exception as e:\n logging.error(\"register handle %s is error, %s\" % (k, e))\n\n def _triggerRegister(self, handle, handleId, config):\n # todo register trigger\n # , name: str, section: str, sync: bool = False, systemEvent: bool = False, handle: int = None\n try:\n for trigger_config in config:\n if 'sync' not in trigger_config:\n trigger_config['sync'] = False\n trigger_config['section'] = trigger_config['section'].upper()\n trigger_config['systemEvent'] = False\n trigger_config['handle'] = handleId\n post_data = serializePostData(trigger_config)\n state, body = POST(self._event_uri+\"handle/\", post_data=post_data,\n http_headers=self._httpHeaders, time_out=15)\n if state != 200:\n logging.error('%s register trigger %s failed. %s' % (\n handle, trigger_config['section'], body))\n else:\n logging.info('%s register trigger %s success.' % (\n handle, trigger_config['section']))\n except Exception as e:\n logging.error('%s register trigger error. %s' % (handle, e))\n\n\nclass Manager:\n def __init__(self, service_uri, platformKey: str, RPCInstance, event_secret=None):\n '''\n event manager class.\n - Params:\n - service_uri:, event service url.\n - platformKey:, event platform key index.\n - RPCInstance:, RPC instace. then trigger handle type is rpc must use it.\n '''\n self._event_service_uri = service_uri # 事件服务地址\n self._event_httpHeaders = {}\n self._event_httpHeaders['api-token'] = event_secret if event_secret else ''\n self._event_cache = {} # 事件缓存\n self._platform = platformKey\n self._getRemoteEventRelation()\n self._RPCInstance = RPCInstance\n self._RPC = {}\n\n def registerRPC(self, service_name):\n '''\n register RPC service into event class.\n '''\n self._RPC[service_name] = self._RPCInstance.handle(service_name)\n\n def _getRemoteEventRelation(self):\n if not self._event_cache:\n if self._event_service_uri.find('/', len(self._event_service_uri)-1) > -1:\n self._event_service_uri+'/'\n m_uri = self._event_service_uri + \\\n \"events/?plateform=%s\" % self._platform\n try:\n state, body = GET(\n m_uri, http_headers=self._event_httpHeaders, time_out=15)\n if state == 200:\n ret = json.loads(str(body, encoding='utf-8'))\n if ret['state'] == 200:\n self._event_cache = ret['msg']\n else:\n logging.error('access %s error. code(%s), body(%s)' %\n (m_uri, state, body))\n except Exception as e:\n logging.error(e)\n\n def monitor(self, eventKey= None):\n '''\n to monitor an method.\n - Returns: , will return the monitored methods handle result and trigger handle results.\n '''\n def decorator(func):\n @functools.wraps(func)\n def wapper(*args, **kwargs):\n if eventKey:\n _handleName = self._platform+\".\"+ eventKey.upper()\n else:\n _handleName = func.__qualname__.replace('.', '_').upper()\n ret = self.on(_handleName, \"BEFORE\", *args, **kwargs)\n kwargs['trigger_results'] = []\n kwargs['trigger_results'].append({'BEFORE': ret[1]['results']})\n if ret[0]:\n ret = func(*args, **kwargs)\n # TODO checked results.\n kwargs['master_func_results'] = ret\n # to add func results mapping.\n if _handleName not in self._event_cache:\n return ret\n if self._event_cache[_handleName]['resultChecked']:\n func_result_checked = self._checked_handle_result(\n self._event_cache[_handleName]['resultChecked'], ret)\n if func_result_checked[0]:\n func_result_checked = self.on(\n _handleName, 'SUCCESS', *args, **kwargs)\n kwargs['trigger_results'].append(\n {'SUCCESS': func_result_checked[1]['results']})\n if not func_result_checked[0]:\n ret = None\n else:\n func_result_checked = self.on(\n _handleName, 'FAILED', *args, **kwargs)\n kwargs['trigger_results'].append(\n {'FAILED': func_result_checked[1]['results']})\n if not func_result_checked[0]:\n ret = None\n func_result_checked = self.on(\n _handleName, \"COMPLETE\", *args, **kwargs)\n kwargs['trigger_results'].append(\n {'COMPLETE': func_result_checked[1]['results']})\n if not func_result_checked[0]:\n ret = None\n else:\n ret = None\n if isinstance(ret, Response):\n ret.data['trigger_results']= kwargs['trigger_results']\n return ret\n return ret, kwargs['trigger_results']\n return wapper\n return decorator\n\n def on(self, handle, event, *args, **kwargs):\n if not handle:\n raise Exception('webEvent.on handle is none.')\n m_event = handle.upper() + \".\" + event.upper()\n if handle not in self._event_cache:\n return True, {\"results\": \"event trigger method is none.\"}\n if m_event in self._event_cache[handle]:\n default_state = self._event_cache[handle][m_event]['sync']\n else:\n default_state = False\n try:\n if handle in self._event_cache:\n if m_event in self._event_cache[handle]:\n func_results = []\n for item in self._event_cache[handle][m_event]['trigger_handles']:\n callstate, call_result = self._call_router(\n item, *args, **kwargs)\n if self._event_cache[handle][m_event]['sync']:\n ret = self._checked_handle_result(\n item['checkedState'], call_result)\n if not ret[0]:\n logging.error(\"%s call error.\" %\n item[\"callHandle\"])\n return False, {\"results\": call_result}\n func_results.append(\n {\"trigger\": item['callHandle'], \"result\": call_result})\n return True, {\"results\": func_results}\n else:\n logging.info(\"%s not have trigger.\" % m_event)\n # this handle not have trigger relation. so return true.\n return True, {'results': \"%s not have trigger.\" % m_event}\n else:\n logging.error(\"%s can not found trigger handle.\" % m_event)\n return default_state, {'results': \"%s can not found trigger handle.\" % m_event}\n except Exception as e:\n logging.error(e)\n return default_state, {'results': e}\n\n def _checked_handle_result(self, checkedConfig: dict, result):\n '''\n checkedConfig example\n {\n \"resultType\":json/object/tuple,\n \"key\":\"\",\n \"operator\":\"==\",\n \"value\":True\n }\n '''\n try:\n operator_dict = {\n \"==\": \"__eq__\",\n \"<\": \"__lt__\",\n \"<=\": \"__le__\",\n \">\": \"__gt__\",\n \">=\": \"__ge__\",\n \"!=\": \"__ne__\"\n }\n checkedConfig = json.loads(checkedConfig, encoding='utf-8')\n if 'resultType' in checkedConfig:\n resultType = checkedConfig['resultType'].lower()\n if resultType == 'json':\n if isinstance(result, Response):\n result= result.data\n else:\n if isinstance(result, bytes):\n result = str(result, encoding='utf-8')\n try:\n result = json.loads(result, encoding='utf-8')\n except:\n result = {}\n if checkedConfig['key'] not in result:\n return (False, result)\n else:\n ret = InstanceCall(\n result[checkedConfig['key']], operator_dict[checkedConfig[\"operator\"]], checkedConfig['value'])\n return (ret, result)\n elif resultType == 'object':\n ret = InstanceCall(\n result, operator_dict[checkedConfig[\"operator\"]], checkedConfig['value'])\n return (ret, result)\n elif resultType == 'tuple':\n if checkedConfig['key'] >= len(result):\n return (False, result)\n else:\n ret = InstanceCall(\n result[checkedConfig['key']], operator_dict[checkedConfig[\"operator\"]], checkedConfig['value'])\n return (ret, result)\n else:\n return (False, result)\n else:\n return (True, result) # 当检查参数为空时表示不检查默认执行正常\n except Exception as e:\n logging.error(e)\n return (False, result)\n\n def _call_router(self, item, *args, **kwargs):\n '''\n event trigger router\n '''\n m_type = item['handleType'].upper()\n if m_type == 'MICROSERVICES':\n return self._api_call(item, *args, **kwargs)\n elif m_type == 'LOCATION':\n return self._location_call(item, *args, **kwargs)\n elif m_type == 'RPC':\n return self._rpc_call(item, *args, **kwargs)\n else:\n logging.error(\"%s handle type is error.\" % item['key'])\n return False, \"%s handle type is error.\" % item['key']\n\n def _set_params_mapping(self, back_ret: dict, isLocation, key, relation, *args, **kwargs):\n '''\n set trigger func params mapping to handle's params.\n '''\n if 'key' in relation:\n if relation['key']:\n m_key = relation['key'].split('.')\n else:\n m_key = None\n else:\n m_key = None\n if 'sources' in relation:\n sources= relation['sources']\n else:\n sources= None\n if not m_key:\n if 'default' not in relation:\n value = None\n else:\n value = relation['default']\n else:\n if not sources:\n if len(m_key) == 2:\n if m_key[0].lower() == 'args':\n if int(m_key[1]) < len(args):\n value = args[int(m_key[1])]\n else:\n if 'default' not in relation:\n value = None\n else:\n value = relation['default']\n elif m_key[0].lower() == 'kwargs':\n if m_key[1] in kwargs:\n value = kwargs[m_key[1]]\n else:\n if 'default' not in relation:\n value = None\n else:\n value = relation['default']\n else:\n if 'default' not in relation:\n value = None\n else:\n value = relation['default']\n else:\n if 'default' not in relation:\n value = None\n else:\n value = relation['default']\n if isLocation:\n if m_key:\n if m_key[0] == 'args':\n back_ret['args'].append(value)\n elif m_key[0] == 'kwargs':\n back_ret['kwargs'][key] = value\n else:\n back_ret['kwargs'][key] = value\n else:\n back_ret['kwargs'][key] = value\n else:\n back_ret[key] = value\n else:\n if 'master_func_results' in kwargs:\n m_func_result= kwargs['master_func_results']\n if isinstance(m_func_result, Response):\n m_func_result= m_func_result.data\n if isinstance(m_func_result,(tuple,list)):\n # master func results is Indexes type, mapping process\n if key == 'self':\n value= m_func_result\n else:\n result_key= key.split('.')\n if len(result_key)==2:\n if int(result_key[1])< len(m_func_result):\n value= m_func_result[int(result_key[1])]\n else:\n value= None\n else:\n value= None\n elif isinstance(m_func_result,(dict,)):\n if key == 'self':\n value= m_func_result\n else:\n result_key= key.split('.') \n if len(result_key)==2:\n if result_key[1] in m_func_result:\n value= m_func_result[result_key[1]]\n else:\n value= None\n else:\n value= None\n else:\n # master func results is object\n if key == 'self':\n value= m_func_result\n else:\n result_key= key.split('.')\n for i in range(1,len(result_key)):\n m_func_result= getattr(m_func_result,result_key[i])\n value= m_func_result\n # mapping params\n if isLocation:\n if len(m_key) ==2:\n if m_key[0].lower()==\"args\":\n if int(m_key[1]) < len(back_ret['args']):\n back_ret['args'][int(m_key[1])]= value\n else:\n back_ret['kwargs'][m_key[0]]= value \n else:\n back_ret['kwargs'][m_key[0]]= value \n else:\n back_ret['kwargs'][m_key[0]]= value\n else:\n back_ret[m_key[0]]= value\n return back_ret\n\n def _generic_params(self, mapping: dict, isLocation=False, *args, **kwargs):\n '''\n generic create params.\n - Params:\n - mapping:, params relation mapping.\n - isLocation:, is location call, defalut(false).\n - *args: , original params.\n - **kwargs: , original params.\n '''\n ret = {}\n if isLocation:\n ret = {\"args\": [], \"kwargs\": {}}\n try:\n mapping = json.loads(mapping, encoding='utf-8')\n except Exception as e:\n logging.error(e)\n mapping = {}\n for k, v in mapping.items():\n self._set_params_mapping(ret, isLocation, k, v, *args, **kwargs)\n return ret\n\n def _location_call(self, item, *args, **kwargs):\n '''\n location moudle call\n '''\n extendPath = item[\"extendPath\"]\n m_handle = item[\"callHandle\"].split('.')\n m_params = item[\"params\"]\n '''\n params mapping example:\n {\n \"param1\":{\n \"key\":\"args.0\",\n \"default\": '',\n },\n \"param2\":{\n \"key\":\"kwargs.t\",\n \"default\":'',\n \"sources\": true\n }\n }\n '''\n m_checkedState = item[\"checkedState\"]\n m_instance = R(extendPath)\n if m_instance:\n m_instance.Instance(m_handle[0])\n if m_params:\n params_ret = self._generic_params(\n m_params, True, *args, **kwargs)\n if params_ret:\n return True, m_instance.Call(m_handle[1], *tuple(params_ret['args']), **params_ret['kwargs'])\n else:\n return False, \"%s call params mapping error.\" % item[\"callHandle\"]\n else:\n return True, m_instance.Call(m_handle[1])\n else:\n return False, '%s call instance is none.' % item[\"callHandle\"]\n\n def _rpc_call(self, item, *args, **kwargs):\n '''\n rpc service moudle call\n '''\n m_handle = item['callHandle'].split(\n '.') if item['callHandle'] else None\n m_key = item['key']\n m_params = item['params']\n if m_handle:\n if len(m_handle) == 2:\n m_service = m_handle[0]\n m_handle = m_handle[1]\n if m_service not in self._RPC:\n self._RPC[m_service] = self._RPCInstance.handle(m_service)\n if m_service in self._RPC:\n params_ret = self._generic_params(\n m_params, False, *args, **kwargs)\n rpc_result = self._RPC[m_service].call(\n item['callHandle'], **params_ret)\n if rpc_result['state'] == 200:\n return True, rpc_result\n else:\n return False, rpc_result\n else:\n return False, \"can not found '%s' service.\" % m_service\n else:\n return False, \"handle formatter is error. formatter(serviceName.methodName)\"\n else:\n return False, \"handle is none.\"\n\n def _api_call(self, item, *args, **kwargs):\n '''\n RestFul api call\n '''\n m_key = item['key']\n m_handle = item['callHandle']\n m_params = item['params']\n m_method = item['method']\n try:\n m_httpHeaders = json.loads(item['httpHeaders'], encoding='utf-8')\n except:\n m_httpHeaders = {}\n m_checkedState = item[\"checkedState\"]\n if m_handle:\n if m_method:\n if m_params:\n params_ret = self._generic_params(\n m_params, False, *args, **kwargs)\n return self._restFul(key=m_key, method=m_method, url=m_handle, headers=m_httpHeaders, post_data=params_ret, time_out=15)\n else:\n return self._restFul(key=m_key, method=m_method, url=m_handle, headers=m_httpHeaders, time_out=15)\n else:\n logging.error('%s http method is none.' % m_key)\n return False, '%s http method is none.' % m_key\n else:\n logging.error('%s http handle is none.' % m_key)\n return False, '%s http handle is none.' % m_key\n\n def _restFul(self, key: str, method: str, url: str, headers: dict = None, post_data: dict = None, time_out: int = 5):\n method = method.upper()\n state = False\n body = None\n try:\n if method == u'GET':\n state, body = GET(uri=url, post_data=post_data,\n http_headers=headers, time_out=time_out)\n elif method == u'POST':\n state, body = POST(uri=url, post_data=post_data,\n http_headers=headers, time_out=time_out)\n elif method == u'PUT':\n state, body = PUT(uri=url, post_data=post_data,\n http_headers=headers, time_out=time_out)\n elif method == u'DELETE':\n state, body = DELETE(\n uri=url, post_data=post_data, http_headers=headers, time_out=time_out)\n else:\n logging.error('%s http method is error.' % key)\n return False, '%s http method is error.' % key\n if state == 200:\n return True, body\n else:\n return False, body\n except Exception as e:\n logging.error(e)\n return False, e\n","sub_path":"Event/webEvent/Events.py","file_name":"Events.py","file_ext":"py","file_size_in_byte":27116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"302101431","text":"#!/usr/bin/env python3\n# File name: AOTexperiment_helper.py\n# Description: Helper functions for AOT experiments\n# Author: Yap Xiu Huan\n# Contact: yapxiuhuan@gmail.com\n# Date: 05-04-2021 (dd-mm-yyyy)\n\nimport os\nimport pandas as pd\nimport numpy as np\nfrom functools import partial\nimport tensorflow as tf\nfrom logging import critical, error, info, warning, debug\nimport time\n\nfrom tensorflow.keras.layers import Input, Dense, Dropout, BatchNormalization\nfrom tensorflow.keras.initializers import VarianceScaling\nfrom tensorflow.keras.regularizers import l1, l2\n\nfrom tensorflow.keras.utils import to_categorical\n\n\nimport sys\nsys.path.append(os.path.join(\"..\", \"..\", \"0_code\"))\nfrom algorithms import attention_model\nimport csv\n\nfrom sklearn.metrics import mean_squared_error, r2_score\n\n# Data loading\ndef load_data(load_folder):\n # dataset_name = \"XY_AOT_CDKPaDEL_processed.csv\"\n dataset_name = \"AOT_CDKPaDELMorgan2_filtered.csv\"\n load_df = pd.read_csv(os.path.join(load_folder,\n dataset_name\n ), index_col=0\n )\n label_start = 7\n feat_start = 12 \n # id_columns = range(7)\n # very_toxic, nontoxic, LD50_mgkg, EPA_category, GHS_category\n # label_columns = range(7, 12)\n # data_columns = range(12, load_df.shape[1]) # CDK+PaDEL descriptors\n\n training_ind = np.where(load_df['Type'] == 'Training')[0]\n testing_ind = np.where(load_df['Type'] == \"Testing\")[0]\n\n X_train = load_df.iloc[training_ind, feat_start:]\n X_test = load_df.iloc[testing_ind, feat_start:]\n y_train = load_df.iloc[training_ind, label_start:feat_start]\n y_test = load_df.iloc[testing_ind, label_start:feat_start]\n train_id_df = load_df.iloc[training_ind, :label_start]\n test_id_df = load_df.iloc[testing_ind, :label_start]\n\n Fweights_train=pd.read_csv(os.path.join(load_folder,\n \"AOT_CDKPaDELMorgan2_Fweights_train.csv\"\n # \"AOT_CDKPaDEL_Fweights_train.csv\"\n ), index_col=0)\n Fweights_test=pd.read_csv(os.path.join(load_folder,\n \"AOT_CDKPaDELMorgan2_Fweights_test.csv\"\n # \"AOT_CDKPaDEL_Fweights_test.csv\"\n ), index_col=0)\n\n r = {\n 'train_features': X_train, \n 'test_features': X_test, \n 'train_targets': y_train.values, \n 'test_targets': y_test.values, \n 'train_Fweights': Fweights_train.values,\n 'test_Fweights': Fweights_test.values, \n 'train_id_df': train_id_df,\n 'test_id_df': test_id_df,\n 'labels': y_train.columns.values,\n }\n return r\n\ndef file_updater(file_path, rows, mode='a'):\n with open(file_path, mode, newline='', encoding='utf-8') as f:\n writer=csv.writer(f)\n for row in rows:\n writer.writerow(row)\n # Load selected features\n\ndef median_imputation(X_train, X_test):\n for col in range(len(X_train[0])):\n med = np.nanmedian(X_train[:, col])\n\n train_nanind = np.where(np.isnan(X_train[:, col]))[0]\n test_nanind = np.where(np.isnan(X_test[:, col]))[0]\n\n if len(train_nanind) > 0:\n X_train[train_nanind, col] = med\n if len(test_nanind) > 0:\n X_test[test_nanind, col] = med\n return X_train, X_test\n\n\n\ndef setup_tf_datasets(\n train_features,\n train_targets,\n val_features=None,\n val_targets=None,\n test_features=None,\n test_targets=None,\n train_Fweights=None,\n val_Fweights=None,\n test_Fweights=None,\n shuffle_buffer=100,\n batch_size=8\n):\n \"\"\"Data should be processed and scaled prior to adding to tf pipeline.\n\n shuffle_buffer: n_buffer for shuffling. If set to False, tf.data.Dataset is not shuffled. \n batch_size: n_batch_size for batching. If set to False, tf.data.Dataset is not batched. \n If training attention model with feature weights, include train_Fweights and test_Fweights \"\"\"\n \n __get_tf_ds = partial(_get_tf_ds, \n shuffle_buffer=shuffle_buffer,\n batch_size=batch_size\n )\n ret_dict=dict()\n\n if train_Fweights is not None:\n train_features = np.hstack([train_features, train_Fweights])\n if val_features is not None:\n val_features = np.hstack([val_features, val_Fweights])\n if test_features is not None:\n test_features = np.hstack([test_features, test_Fweights]) \n ret_dict['train_ds'] = __get_tf_ds(train_features, train_targets, )\n if val_features is not None:\n ret_dict['val_ds'] = __get_tf_ds(val_features, val_targets,)\n if test_features is not None:\n ret_dict['test_ds'] = __get_tf_ds(test_features, test_targets)\n\n return ret_dict\n\ndef _get_tf_ds(X,y, shuffle_buffer = 100, batch_size = 8):\n y = tf.cast(y, dtype=tf.float32)\n ds = tf.data.Dataset.from_tensor_slices((X, y))\n if shuffle_buffer:\n ds = ds.shuffle(shuffle_buffer)\n if batch_size:\n ds = ds.batch(batch_size)\n return ds\n\n# Model training\ndef get_model(model_type,\n n_attention,\n n_attention_hidden,\n n_feat,\n n_out,\n n_concat_hidden,\n concat_activation,\n n_attention_out,\n kernel_initializer,\n bias_initializer,\n attention_kernel_initializer,\n attention_bias_initializer,\n attention_hidden_activation,\n attention_output_activation,\n n_hidden,\n hidden_activation,\n kernel_regularizer,\n bias_regularizer,\n output_activation,\n random_seed=123):\n tf.random.set_seed(random_seed)\n if model_type == \"LSwFW\" or model_type==\"LSwFW_ones\":\n input_shape = (n_feat*2,)\n else:\n input_shape = (n_feat,)\n input_layer = Input(shape=input_shape)\n\n if model_type == \"dense\":\n # print(f\"First dense layer with {n_attention*n_attention_hidden*n_attention_out} hidden units\")\n first_layer = Dense(n_attention*n_attention_hidden*n_attention_out,\n activation=hidden_activation,\n kernel_initializer=kernel_initializer,\n kernel_regularizer=kernel_regularizer,\n bias_initializer=bias_initializer,\n bias_regularizer=bias_regularizer,\n )(input_layer)\n\n layer0 = Dense(n_concat_hidden,\n activation=hidden_activation,\n kernel_initializer=kernel_initializer,\n kernel_regularizer=kernel_regularizer,\n bias_initializer=bias_initializer,\n bias_regularizer=bias_regularizer,\n )(first_layer)\n elif model_type == \"LS\":\n layer0 = attention_model.ConcatAttentions(\n n_attention=n_attention,\n n_attention_hidden=n_attention_hidden,\n n_attention_out=n_attention_out,\n n_feat=n_feat,\n n_hidden=n_concat_hidden,\n activation=concat_activation,\n kernel_initializer=kernel_initializer,\n bias_initializer=bias_initializer,\n kernel_regularizer=l2(1E-5),\n bias_regularizer=l2(1E-5),\n attention_kernel_initializer=attention_kernel_initializer,\n attention_bias_initializer=attention_bias_initializer,\n attention_hidden_activation=attention_hidden_activation,\n attention_output_activation=attention_output_activation,\n batch_norm_kwargs={\"trainable\": False, \"renorm\": True},\n )(input_layer)\n elif model_type == \"LSwFW\" or model_type == \"LSwFW_ones\":\n layer0 = attention_model.ConcatAttentionswFeatWeights(\n n_attention=n_attention,\n n_attention_hidden=n_attention_hidden,\n n_attention_out=n_attention_out,\n n_feat=n_feat,\n n_hidden=n_concat_hidden,\n activation=concat_activation,\n kernel_initializer=kernel_initializer,\n bias_initializer=bias_initializer,\n kernel_regularizer=l2(1E-5),\n bias_regularizer=l2(1E-5),\n attention_kernel_initializer=kernel_initializer,\n attention_bias_initializer=bias_initializer,\n attention_hidden_activation=attention_hidden_activation,\n attention_output_activation=attention_output_activation,\n batch_norm_kwargs={\"trainable\": False, \"renorm\": True},\n )(input_layer)\n dense_layer1 = Dense(n_hidden,\n activation=hidden_activation,\n kernel_initializer=kernel_initializer,\n kernel_regularizer=kernel_regularizer,\n bias_initializer=bias_initializer,\n bias_regularizer=bias_regularizer,\n )(layer0)\n dropout1 = Dropout(0.2)(dense_layer1)\n # batchnorm1 = BatchNormalization(trainable=False,\n # renorm=True\n # )(dropout1)\n dense_layer2 = Dense(n_hidden,\n activation=hidden_activation,\n kernel_initializer=kernel_initializer,\n kernel_regularizer=kernel_regularizer,\n bias_initializer=bias_initializer,\n bias_regularizer=bias_regularizer\n )(dropout1)\n dropout2 = Dropout(0.2)(dense_layer2)\n # batchnorm2 = BatchNormalization(trainable=False,\n # renorm=True\n # )(dropout2)\n dense_layer3 = Dense(n_hidden,\n activation=hidden_activation,\n kernel_initializer=kernel_initializer,\n kernel_regularizer=kernel_regularizer,\n bias_initializer=bias_initializer,\n bias_regularizer=bias_regularizer,\n )(dropout2)\n output_layer = Dense(n_out, activation=output_activation)(dense_layer3)\n\n tf_model = tf.keras.Model(inputs=input_layer,\n outputs=output_layer\n )\n return tf_model\n\n\ndef get_model_deeper(model_type,\n n_attention,\n n_attention_hidden,\n n_feat,\n n_out,\n n_concat_hidden,\n concat_activation,\n n_attention_out,\n kernel_initializer,\n bias_initializer,\n attention_kernel_initializer,\n attention_bias_initializer,\n attention_hidden_activation,\n attention_output_activation,\n n_hidden,\n hidden_activation,\n kernel_regularizer,\n bias_regularizer,\n output_activation,\n random_seed=123):\n tf.random.set_seed(random_seed)\n if model_type == \"LSwFW\" or model_type==\"LSwFW_ones\":\n input_shape = (n_feat*2,)\n else:\n input_shape = (n_feat,)\n input_layer = Input(shape=input_shape)\n\n if model_type == \"dense\":\n # print(f\"First dense layer with {n_attention*n_attention_hidden*n_attention_out} hidden units\")\n first_layer = Dense(n_attention*n_attention_hidden*n_attention_out,\n activation=hidden_activation,\n kernel_initializer=kernel_initializer,\n kernel_regularizer=kernel_regularizer,\n bias_initializer=bias_initializer,\n bias_regularizer=bias_regularizer,\n )(input_layer)\n\n layer0 = Dense(n_concat_hidden,\n activation=hidden_activation,\n kernel_initializer=kernel_initializer,\n kernel_regularizer=kernel_regularizer,\n bias_initializer=bias_initializer,\n bias_regularizer=bias_regularizer,\n )(first_layer)\n elif model_type == \"LS\":\n layer0 = attention_model.ConcatAttentions(\n n_attention=n_attention,\n n_attention_hidden=n_attention_hidden,\n n_attention_out=n_attention_out,\n n_feat=n_feat,\n n_hidden=n_concat_hidden,\n activation=concat_activation,\n kernel_initializer=kernel_initializer,\n bias_initializer=bias_initializer,\n kernel_regularizer=l2(1E-5),\n bias_regularizer=l2(1E-5),\n attention_kernel_initializer=attention_kernel_initializer,\n attention_bias_initializer=attention_bias_initializer,\n attention_hidden_activation=attention_hidden_activation,\n attention_output_activation=attention_output_activation,\n batch_norm_kwargs={\"trainable\": False, \"renorm\": True},\n )(input_layer)\n elif model_type == \"LSwFW\" or model_type == \"LSwFW_ones\":\n layer0 = attention_model.ConcatAttentionswFeatWeights(\n n_attention=n_attention,\n n_attention_hidden=n_attention_hidden,\n n_attention_out=n_attention_out,\n n_feat=n_feat,\n n_hidden=n_concat_hidden,\n activation=concat_activation,\n kernel_initializer=kernel_initializer,\n bias_initializer=bias_initializer,\n kernel_regularizer=l2(1E-5),\n bias_regularizer=l2(1E-5),\n attention_kernel_initializer=kernel_initializer,\n attention_bias_initializer=bias_initializer,\n attention_hidden_activation=attention_hidden_activation,\n attention_output_activation=attention_output_activation,\n batch_norm_kwargs={\"trainable\": False, \"renorm\": True},\n )(input_layer)\n dense_layer1 = Dense(n_hidden,\n activation=hidden_activation,\n kernel_initializer=kernel_initializer,\n kernel_regularizer=kernel_regularizer,\n bias_initializer=bias_initializer,\n bias_regularizer=bias_regularizer,\n )(layer0)\n dropout1 = Dropout(0.2)(dense_layer1)\n # batchnorm1 = BatchNormalization(trainable=False,\n # renorm=True\n # )(dropout1)\n dense_layer2 = Dense(n_hidden,\n activation=hidden_activation,\n kernel_initializer=kernel_initializer,\n kernel_regularizer=kernel_regularizer,\n bias_initializer=bias_initializer,\n bias_regularizer=bias_regularizer\n )(dropout1)\n dropout2 = Dropout(0.2)(dense_layer2)\n # batchnorm2 = BatchNormalization(trainable=False,\n # renorm=True\n # )(dropout2)\n dense_layer3 = Dense(n_hidden,\n activation=hidden_activation,\n kernel_initializer=kernel_initializer,\n kernel_regularizer=kernel_regularizer,\n bias_initializer=bias_initializer,\n bias_regularizer=bias_regularizer,\n )(dropout2)\n dropout3 = Dropout(0.2)(dense_layer3)\n dense_layer4 = Dense(n_hidden, \n activation =hidden_activation,\n kernel_initializer=kernel_initializer,\n kernel_regularizer=kernel_regularizer,\n bias_initializer=bias_initializer,\n bias_regularizer=bias_regularizer,\n )(dropout3)\n output_layer = Dense(n_out, activation=output_activation)(dense_layer4)\n\n tf_model = tf.keras.Model(inputs=input_layer,\n outputs=output_layer\n )\n return tf_model\n# def get_dense_model(**kwargs):\n# model_type = \"dense\"\n# return _get_model(model_type,\n# **kwargs\n# )\n\n\n# def get_attention_model(**kwargs):\n# model_type = \"LS\"\n# return _get_model(model_type,\n# **kwargs)\n\n\n# def get_attentionwFW_model(**kwargs):\n# model_type = \"LSwFW\"\n# return _get_model(model_type,\n# **kwargs\n# )\n\n\ndef setup_callback_paths(monitor,\n mode,\n model_name,\n dataset_name,\n split_number=0,\n super_folder=None,\n ):\n if isinstance(split_number, (int, float)):\n split_name = \"split{:02d}\".format(split_number)\n else:\n split_name = split_number\n save_folder = \"_\".join([time.strftime(\"%y%m%d\", time.localtime()),\n model_name,\n dataset_name,\n split_name\n ])\n if super_folder is not None:\n save_folder = os.path.join(super_folder,\n save_folder\n )\n try:\n os.mkdir(super_folder)\n except OSError as error:\n warning(error)\n checkpoint_path = os.path.join(save_folder,\n \"model_checkpoint\")\n csv_filename = os.path.join(checkpoint_path, \"training_log.csv\")\n try:\n os.mkdir(save_folder)\n except OSError as error:\n warning(error)\n try:\n os.mkdir(checkpoint_path)\n except OSError as error:\n warning(error)\n\n cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path,\n monitor=monitor,\n mode=mode,\n save_best_only=True,\n save_weights_only=True,\n verbose=1\n )\n csvlogger_callback = tf.keras.callbacks.CSVLogger(filename=csv_filename,\n append=True\n )\n return [cp_callback, csvlogger_callback], checkpoint_path\n\n\ndef data_scaling(feature_scaler,\n target_scaler,\n train_features,\n test_features,\n train_target,\n test_target\n ):\n # Scaling\n feature_scaler.fit(train_features)\n train_features_scaled = feature_scaler.transform(train_features)\n test_features_scaled = feature_scaler.transform(test_features)\n\n if target_scaler is not None:\n if train_target.ndim<2:\n train_target = np.expand_dims(train_target, axis=1)\n test_target = np.expand_dims(test_target, axis=1)\n target_scaler.fit(train_target)\n train_target_scaled = target_scaler.transform(\n train_target)\n test_target_scaled = target_scaler.transform(\n test_target)\n else:\n train_target_scaled = train_target\n test_target_scaled = test_target\n return train_features_scaled, test_features_scaled, train_target_scaled, test_target_scaled, feature_scaler, target_scaler\n\n\ndef get_model_setup_params(args_dict={}):\n model_setup_params = {\n \"n_attention\": 10,\n \"n_attention_hidden\": 512,\n 'n_feat': None,\n \"n_out\": 1,\n \"n_concat_hidden\": 512,\n \"concat_activation\": tf.keras.layers.LeakyReLU(alpha=0.1),\n \"n_attention_out\": 3,\n \"kernel_initializer\": tf.keras.initializers.Orthogonal(),\n # So that we have weights to train on each LeakyReLU neuron\n \"bias_initializer\": tf.keras.initializers.Constant(value=0.1),\n \"attention_kernel_initializer\": tf.keras.initializers.Orthogonal(),\n \"attention_bias_initializer\": tf.keras.initializers.Constant(value=0.1),\n \"attention_hidden_activation\": tf.keras.layers.LeakyReLU(alpha=0.1),\n \"attention_output_activation\": \"sigmoid\",\n \"n_hidden\": 2048,\n # \"hidden_activation\": tf.keras.layers.LeakyReLU(alpha=0.1),\n \"hidden_activation\": tf.keras.layers.LeakyReLU(alpha=0.1),\n \"kernel_regularizer\": l2(1E-5),\n \"bias_regularizer\": l2(1E-5),\n \"output_activation\": \"sigmoid\",\n \"random_seed\": 123\n }\n for key in args_dict.keys():\n set_attr(model_setup_params, key, args_dict[key])\n return model_setup_params\n\n\ndef get_model_compile_params(learning_rate, args_dict={}):\n model_compile_params = {\n \"optimizer\": tf.keras.optimizers.Adam(learning_rate=learning_rate,\n clipvalue=0.5,\n clipnorm=1.0\n ),\n \"loss\": tf.keras.losses.BinaryCrossentropy(label_smoothing=0.1), \n #BinaryCrossEntropyIgnoreNan(weights_dicts=weights_dicts),\n \"metrics\": [ \"AUC\",# \"acc\",\n # AveragedAUCIgnoreNan(num_labels=2)\n ]\n }\n for key in args_dict.keys():\n set_attr(model_compile_params, key, args_dict[key])\n return model_compile_params\n\n\ndef get_dataset_params(args_dict={}):\n dataset_params = {\n \"n_batch\": 8,\n \"n_buffer\": 100,\n }\n for key in args_dict.keys():\n set_attr(dataset_params, key, args_dict[key])\n return dataset_params\n\n\ndef lr_scheduler(epoch, lr):\n if epoch < 20:\n return lr\n else:\n return lr * tf.math.exp(-0.1)\n\n\n# Loading and Evaluating models\n\n\ndef get_p(y):\n \"\"\"Get prior probability of a label\"\"\"\n y = y[~np.isnan(y)]\n return np.sum(y)/len(y)\n\n\ndef load_tf_model(model_path,\n checkpoint_path=None,\n ):\n load_model = tf.keras.models.load_model(\n model_path,\n custom_objects={\n \"AveragedAUCIgnoreNan\": AveragedAUCIgnoreNan,\n \"BinaryCrossEntropyIgnoreNan\": BinaryCrossEntropyIgnoreNan,\n }\n )\n if checkpoint_path is not None:\n load_model.load_weights(checkpoint_path)\n return load_model\n\nfrom sklearn.metrics import confusion_matrix\n# Model evaluation\ndef get_cm(y_true, y_pred, num_classes=2):\n ind=np.isfinite(y_true.astype(np.float))\n return confusion_matrix(y_true[ind].astype(np.int32), y_pred[ind], labels=list(range(num_classes)))\n\ndef get_sn_sp(cm):\n tn, fp, fn, tp = cm.ravel()\n sn = np.float(tp)/(tp+fn)\n sp = np.float(tn)/(tn+fp)\n return sn, sp\n\ndef get_qual_model_score(sn_train, sp_train, sn_test, sp_test):\n ba_train = (sn_train+sp_train)/2.\n ba_test = (sn_test+sp_test)/2.\n gof = (0.7*ba_train) + 0.3*(1-np.abs(sn_train-sp_train))\n pred = (0.7*ba_test) + 0.3*(1-np.abs(sn_test-sp_test))\n rob = 1-np.abs(ba_train-ba_test)\n s = (0.3*gof) + (0.45*pred) + (0.25*rob)\n return s\n\n\ndef model_eval(tf_model, \n X, y, target_scaler, model_name, label, split_name=\"Train\", num_classes = 2\n):\n predict = np.array(tf_model(X))\n if target_scaler is not None:\n predict = target_scaler.inverse_transform(predict)\n if num_classes>2:\n predict = to_categorical(tf.argmax(predict, axis=1), num_classes=num_classes)\n \n sn_list, sp_list = [],[]\n for i in range(num_classes):\n if len(np.unique(y[:,i]))<2: #Skip class if either neg or pos are missing\n continue\n cm = get_cm(y[:,i], predict[:,i])\n sn, sp = get_sn_sp(cm)\n sn_list.append(sn)\n sp_list.append(sp)\n sn, sp = np.mean(sn_list), np.mean(sp_list) \n else:\n thresh = 0.5\n predict=(predict>thresh).astype(np.int32)\n cm = get_cm(y, predict)\n sn, sp = get_sn_sp(cm)\n\n results=[\n [model_name, label, 'NER', split_name, np.mean([sn, sp])], \n [model_name, label, 'Sensitivity', split_name, sn], \n [model_name, label, 'Specificity', split_name, sp]\n ]\n return results, sn, sp\n\ndef model_score(sn_train, sp_train, sn_test, sp_test, model_name, label, split_name=\"TrainTest\"):\n model_score = get_qual_model_score(sn_train, sp_train, sn_test, sp_test)\n results = [\n [model_name, label, \"Model Score\", split_name, model_score]\n ]\n return results\n\ndef cont_model_eval(tf_model, X, y, target_scaler, model_name, label, split_name=\"Train\"):\n predict = tf_model.predict(X)\n if target_scaler is not None:\n predict = target_scaler.inverse_transform(predict)\n rmse = mean_squared_error(y, predict, squared=False)\n r2 = r2_score(y, predict)\n results = [\n [model_name, label, 'RMSE', split_name, rmse],\n [model_name, label, 'Rsquared', split_name, r2]\n ]\n return results, r2\n\ndef get_cont_model_score(r2_train, r2_test, model_name, label, split_name = \"TrainTest\"):\n gof = r2_train\n pred = r2_test\n robustness = 1- np.abs(gof-pred)\n s= (0.3*gof) +(0.45*pred) + (0.25*robustness)\n results = [\n [model_name, label, \"Model Score\", split_name, s]\n ]\n return results\n\n#Get model predictions\ndef get_model_predictions(model_type, \n checkpoint_path, \n endpoint, \n X_train, \n X_test, \n n_feat,\n target_scaler = None, \n n_endpoints=None):\n \"\"\"'endpoint' is one of 'binary', 'multiclass' or 'regression'.\"\"\"\n if model_type==\"xgboost\":\n import xgboost as xgb\n model = xgb.Booster({'nthread':4})\n model.load_model(checkpoint_path)\n\n X_train = xgb.DMatrix(X_train)\n X_test = xgb.DMatrix(X_test)\n\n else: #Tensorflow model\n model_setup_params = get_model_setup_params()\n model_setup_params['n_out']=1\n model_setup_params['n_feat'] = n_feat \n model_compile_params = get_model_compile_params(learning_rate = 0.0001)\n if endpoint==\"multiclass\":\n assert n_endpoints is not None, \"n_endpoints cannot be None for model_type==multiclass\"\n model_setup_params['n_out']=n_endpoints\n model_compile_params['loss']=tf.keras.losses.CategoricalCrossentropy(\n label_smoothing=0.1)\n elif endpoint==\"regression\":\n model_setup_params['output_activation']=\"linear\"\n model_compile_params['loss'] = tf.keras.losses.MeanSquaredError()\n model_compile_params['metrics'] = [\n tf.keras.metrics.RootMeanSquaredError()] \n\n model = get_model(model_type = model_type, **model_setup_params)\n model.compile(**model_compile_params)\n model.load_weights(checkpoint_path)\n \n train_predict=model.predict(X_train)\n test_predict=model.predict(X_test)\n \n if target_scaler is not None:\n train_predict = target_scaler.inverse_transform(train_predict)\n test_predict = target_scaler.inverse_transform(test_predict)\n return train_predict, test_predict","sub_path":"1_Notebooks/AOT_wFP/AOTexperiment_helper.py","file_name":"AOTexperiment_helper.py","file_ext":"py","file_size_in_byte":27440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"389644597","text":"from django import forms\nfrom django.forms import ModelForm, TextInput, Textarea, NumberInput, SelectMultiple\nfrom django.forms import BaseInlineFormSet\n\nfrom .models import IngredientLine, Ingredient, Recipe\n\n\nclass IngredientLineForm(ModelForm):\n \"\"\"Handle an ingredient line's display, controlling various field sizes and types\n \"\"\"\n class Meta:\n model = IngredientLine\n fields = ['line_order','ingredient','quantity','quantity_unit','prep_notes']\n # override the widget used to enter quantity, so we can control its size (can't do that with input=number fields)\n widgets = {\n 'line_order': NumberInput(attrs={'style':'width: 3em'}),\n\n 'quantity': TextInput(),\n 'prep_notes': TextInput(attrs={'size':40}),\n }\n\n def __init__(self, *args, **kwards):\n super().__init__(*args, **kwards)\n self.fields['quantity'].widget.attrs.update({'size':6})\n self.fields['quantity_unit'].widget.attrs.update({'size':10})\n\n def __repr__(self):\n if self['line_order'].value()==None:\n return super.__str__(self)\n s= f\"IngredientLine {self['line_order'].value()}: \"\n s +=f\" <{self['prep_notes'].value()}>\"\n return s\n\n\nclass IngredientLineFormSet(BaseInlineFormSet):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.queryset = IngredientLine.objects.filter(containing_recipe__name=self.instance.name).order_by('line_order')\n\n\nclass RecipeForm(ModelForm):\n \"\"\"Form for user to update a recipe.\n Display version has a separate embedded formset to handle the ingredient list\n \"\"\"\n class Meta:\n model = Recipe\n fields = ['name','instructions','notes','taste_score','effort_score',\n 'categories','active_minutes','total_minutes','source']\n widgets = {'instructions': Textarea(attrs={'cols':80, 'rows':15}),\n 'notes': Textarea(attrs={'cols':80, 'rows':2}),\n 'categories': SelectMultiple(attrs={'style':'vertical-align:top', 'size':10}),\n 'active_minutes': TextInput(attrs={'size':5}),\n 'total_minutes': TextInput(attrs={'size':5}),\n 'source': TextInput(attrs={'size':40})\n }\n\n\n def __init__(self, *args, **kwargs):\n self.recipe = kwargs.pop('recipe', None)\n super().__init__(*args, **kwargs)\n\n def is_valid(self):\n print(\"Checking RecipeForm is valid\")\n self.valid=True\n return True\n\n def save(self):\n print(\"In RecipeForm save\")\n return super().save(self)\n","sub_path":"rbox/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"170402103","text":"import json\nimport os\nimport logging\nimport sys\nfrom plc_readwrite import PlcReadWrite, PlcRwMode\nfrom plc_looper import PlcLooper\nimport library.utils as utils\n######################################################################################################################\n# Parametri di configurazione\nplc_config_file = './config/plc_modbus.config'\n\n\n######################################################################################################################\n# Initializzazione del logger #\ndef init_logging(logger, filename, level=logging.INFO, stdout=True, maxBytes=10000, backupCount=5):\n logging.getLogger().setLevel(logging.NOTSET)\n logging.getLogger().handlers = []\n\n rotatingHandler = logging.handlers.RotatingFileHandler(filename=filename, maxBytes=maxBytes, backupCount=backupCount)\n rotatingHandler.setLevel(logging.DEBUG)\n rotatingHandler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))\n logging.getLogger().addHandler(rotatingHandler)\n\n logging.getLogger(__name__).setLevel(level)\n logging.getLogger(\"pymodbus\").setLevel(logging.DEBUG)\n if stdout:\n logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))\n logger = logging.getLogger(__name__)\n logger.info('init_logging::end')\n\n######################################################################################################################\n\ndef get_plc_read_write_and_connect(logger, plc_dictionary):\n plc_read=[]\n plc_write=[]\n for d in plc_dictionary:\n client = PlcReadWrite(logger, d)\n if client.connect_device():\n if client.rw_mode == PlcRwMode.READ:\n plc_read.append(client)\n else:\n plc_write.append(client)\n client.disconnect_device()\n else:\n if client.rw_mode == PlcRwMode.READ:\n plc_read.append(None)\n else:\n plc_write.append(None)\n return plc_read, plc_write\n\n\n######################################################################################################################\ndef parseJsonConfig(file_full_path):\n #pwd = os.getcwd()\n if (os.path.isfile(file_full_path)):\n with open(file_full_path,\"r\") as f:\n return json.load(f)\n return None\n\n######################################################################################################################\n### MAIN\n\nif __name__ == \"__main__\":\n logger = logging\n log_filename = 'test.log'\n init_logging(logger, log_filename)\n logger.info(\"::START::\")\n logger.info(\"------------------------------------------------------\")\n meas_ok:bool=True\n\n # Parsing delle variabili da file di configurazione.\n plc_dictinoary = parseJsonConfig(plc_config_file)\n\n # Lettori da PLC\n plc_readers, plc_writers = get_plc_read_write_and_connect(logger, plc_dictinoary)\n\n if any(ele is None for ele in plc_readers):\n logger.error(\"ERROR while connecting plc_readers\")\n if any(ele is None for ele in plc_writers):\n logger.error(\"ERROR while connecting plc_writers\")\n #else:\n PlcLooper(plc_readers, plc_writers).start_testing()\n\n # Avvio del loop di test\n \n\n logger.info(\"::STOP::\")\n logger.info(\"------------------------------------------------------\")\n\n","sub_path":"ModBus_PLC2PLC/ModBus_PLC2PLC_v_0.0.2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"600357931","text":"\"\"\"\n---------------------------------------------\n File Name: compute_phonetic\n Description: 计算每一个句子的发音类型\n Author: nycolas\n Date: 18-3-28\n---------------------------------------------\n\n\"\"\"\n\nfrom pypinyin import pinyin, lazy_pinyin, STYLE_TONE2\n\n# print(pinyin('今天真好呀!'))\n#\n# print(lazy_pinyin('今天真好呀!'))\nimport string\n\ndef compute_pinyin(sentence):\n\n p = 0\n\n # 少一步去除所有标点符号\n pinyin_list = lazy_pinyin(sentence, style=STYLE_TONE2)\n\n # for key in pinyin_list:\n #\n # if\n print(pinyin_list)\ncompute_pinyin('今天真好呀!')","sub_path":"humor/phonetic_style/compute_phonetic.py","file_name":"compute_phonetic.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"184987415","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Jan 4 13:41:13 2016\r\n\r\n@author: john.g.evans\r\n\"\"\"\r\nimport os\r\n\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nimport seaborn as sns\r\nfrom scipy.interpolate import interp1d\r\n\r\n\r\ndef make_plot(df, variable, title=None, ylabel=None, ylim=None, output_file=None):\r\n linestyles = ['-', '-', '-', '-', '-', '-', '--', '-.', ':', ':']\r\n\r\n # Force the columns into alphabetical order\r\n columns = [\r\n 'NDFD_temp',\r\n 'Radar Base Reflectivity',\r\n 'Watch Warn Advisory',\r\n 'AHPS River Gauges',\r\n 'ESI_Alabama_Maps_IS',\r\n 'ESI_CentralCalifornia_Data',\r\n 'ESI_CentralCalifornia_TandE_Data',\r\n 'Hawaii_Imagery', \r\n 'MPA_Inventory_Government_Level',\r\n 'HAPC',\r\n ]\r\n df = df[columns]\r\n\r\n ax = df.plot(style=linestyles, zorder=10)\r\n ax.set_xlabel('Concurrent Threads')\r\n ax.set_ylabel(ylabel)\r\n ax.set_title(title)\r\n if ylim is not None:\r\n ax.set_ylim(ylim)\r\n\r\n return ax\r\n\r\ndef plot_elapsed(hdffile, title):\r\n store = pd.HDFStore(hdffile)\r\n variable = 'elapsed'\r\n\r\n df = store[variable]\r\n\r\n kwargs = {}\r\n kwargs['title'] = title\r\n kwargs['ylabel'] = 'milliseconds',\r\n kwargs['ylim'] = [0, 45000]\r\n\r\n ax = make_plot(df, variable, **kwargs)\r\n\r\n fig = ax.get_figure()\r\n\r\n output_file = '{suffix}_{variable}.png'\r\n output_file = output_file.format(suffix=os.path.splitext(hdffile)[0],\r\n variable=variable)\r\n fig.savefig(output_file)\r\n\r\ndef plot_throughput(hdffile, title):\r\n store = pd.HDFStore(hdffile)\r\n variable = 'throughput'\r\n\r\n df = store[variable]\r\n\r\n kwargs = {}\r\n kwargs['title'] = title\r\n kwargs['ylabel'] = 'tr/sec'\r\n kwargs['ylim'] = [0, 150]\r\n\r\n ax = make_plot(df, variable, **kwargs)\r\n\r\n # Radar: target is 200000 tr/hr = 55.6/sec\r\n f = interp1d(df['Radar Base Reflectivity'], df.index)\r\n wwa_num_threads = f(55.6)\r\n plt.plot([wwa_num_threads, wwa_num_threads, 0], [0, 55.6, 55.6],\r\n zorder=1,\r\n alpha=0.5,\r\n color=sns.color_palette()[1])\r\n \r\n # WWA: target is 100000 tr/hr = 27.8/sec\r\n f = interp1d(df['Watch Warn Advisory'], df.index)\r\n wwa_num_threads = f(27.8)\r\n plt.plot([wwa_num_threads, wwa_num_threads, 0], [0, 27.8, 27.8],\r\n zorder=1,\r\n alpha=0.5,\r\n color=sns.color_palette()[2])\r\n \r\n plt.show()\r\n fig = ax.get_figure()\r\n\r\n output_file = '{suffix}_{variable}.png'\r\n output_file = output_file.format(suffix=os.path.splitext(hdffile)[0],\r\n variable=variable)\r\n fig.savefig(output_file)\r\n\r\ndef run_jan16():\r\n hdffile = 'run31.h5'\r\n\r\n print('Examining {}...'.format(hdffile))\r\n\r\n title = 'QA Tier Full Capacity Test (Jan 16): Throughput'\r\n plot_throughput(hdffile, title)\r\n\r\n title = 'QA Tier Full Capacity Test (Jan 16): Elapsed Time Per Transaction'\r\n plot_elapsed(hdffile, title)\r\n\r\ndef run_dec12():\r\n hdffile = 'run23.h5'\r\n\r\n print('Examining {}...'.format(hdffile))\r\n\r\n title = 'QA Tier Full Capacity Test (Dec 12): Throughput'\r\n plot_throughput(hdffile, title)\r\n\r\n title = 'QA Tier Full Capacity Test (Dec 12): Elapsed Time Per Transaction'\r\n plot_elapsed(hdffile, title)\r\n\r\nif __name__ == '__main__':\r\n run_jan16()\r\n #run_dec12()\r\n","sub_path":"load_testing_plots_jan16.py","file_name":"load_testing_plots_jan16.py","file_ext":"py","file_size_in_byte":3413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"586313421","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 27 11:26:54 2017\n\n@author: richard\n\"\"\"\n\nimport csv\n\nchecksum = 0\n\nwith open('/home/richard/Documents/spreads.txt') as csvfile:\n reader = csv.reader(csvfile, delimiter='\\t')\n my_sheet = []\n for row in reader:\n my_row = []\n for r in row:\n my_row.append(int(r))\n #print(my_row)\n max_value = max(my_row)\n min_value = min(my_row)\n checksum = checksum + (max_value - min_value)\n print(max_value,' ', min_value, ' ',max_value-min_value,' ',checksum)\n my_sheet.append(my_row)\n\nprint('total of checksum is: ', checksum) \n # my_nb = np.append(my_sheet,row)\n\n","sub_path":"scratch/spreadsheet_checksum.py","file_name":"spreadsheet_checksum.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"53624796","text":"import datetime as dt, time\nimport multiprocessing\nimport numpy as np, pandas as pd\nfrom functools import partial\nfrom utils.algorithm import timeutils as tu\nfrom utils.database import sqlfactory as sf, config as cfg, io\nfrom utils.script import scriptutils as su\nfrom dateutil.relativedelta import relativedelta\n\nengines = cfg.load_engine()\nengine_rd = engines[\"2Gb\"]\n\ntable = sf.Table(\"m\", \"index\")\nprocess_date = dt.date.today() - dt.timedelta(1)\n\n\ndef calculate(idx, export_path=None):\n dfs = pd.DataFrame()\n\n PEIndex = sf.PEIndex(idx)\n first_year = PEIndex.firstyear\n\n result_r = {}\n components_num = {}\n components = {}\n\n for year in range(first_year, process_date.year + 1):\n if year == process_date.timetuple().tm_year:\n month = process_date.month\n else:\n month = 12\n\n sql_i = sf.SQL_PEIndex(PEIndex.idx, year).yeardata_m\n\n conn = engine_rd.connect()\n\n su.tic(\"Getting Data\")\n d = pd.read_sql(sql_i, conn)\n conn.close()\n\n su.tic(\"Preprocessing...\")\n d[\"statistic_date\"] = d[\"statistic_date\"].apply(lambda x: time.mktime(x.timetuple()))\n d_dd = d.drop_duplicates(\"fund_id\")\n idx_slice = d_dd.index.tolist()\n idx_slice.append(len(d))\n ids = d_dd[\"fund_id\"].tolist()\n\n t_std = tu.timeseries_std(dt.datetime(year, month, 10), month, 12, 1, use_lastday=True)\n t_std1 = t_std[:-1]\n\n su.tic(\"Grouping...\")\n ds = [d[idx_slice[i]:idx_slice[i + 1]] for i in range(len(idx_slice) - 1)]\n ts = [x[\"statistic_date\"].tolist() for x in ds]\n navs = [x[\"nav\"].tolist() for x in ds]\n\n su.tic(\"Matching...\")\n matchs1 = [tu.outer_match4index_f7(x, t_std1, False) for x in ts]\n matchs2 = [tu.outer_match4index_b7(x, t_std1) for x in ts]\n matchs3 = [tu.outer_match4index_m(x, t_std, False) for x in ts]\n matchs = [su.merge_result(x1, x2, x3) for x1, x2, x3 in zip(matchs1, matchs2, matchs3)]\n\n su.tic(\"Getting Result...\")\n t_matchs = [x[0] for x in matchs]\n t_matchs = [tu.tr(x) for x in t_matchs]\n idx_matchs = [x[1] for x in matchs]\n nav_matchs = [[navs[i][idx] if idx is not None else None for idx in idx_matchs[i].values()] for i in\n range(len(idx_matchs))]\n\n su.tic(\"Calculating Index...\")\n nvs = pd.DataFrame(nav_matchs).T.astype(float).as_matrix()\n rs = nvs[:-1] / nvs[1:] - 1\n rs[rs > 30] = np.nan\n rs[rs < -1] = np.nan\n r = np.nanmean(rs, axis=1)\n r[np.isnan(r)] = 0\n\n result_r[year] = r\n components_num[year] = np.sum(~np.isnan(rs), axis=1)\n\n # log samples\n tmp = pd.DataFrame(nvs, columns=ids).T\n tmp[\"fund_id\"] = tmp.index\n tmp = tmp[[tmp.columns[-1], *tmp.columns[:-1]]]\n components[year] = tmp\n\n su.tic(\"Year:{0}, Done...\".format(year))\n\n values_r = []\n values_num = []\n for year in range(first_year, process_date.timetuple().tm_year + 1):\n if len(values_r) == 0:\n values_r = result_r[year].tolist()[::-1]\n values_num = components_num[year].tolist()[::-1]\n else:\n values_r.extend(result_r[year].tolist()[::-1])\n values_num.extend(components_num[year].tolist()[::-1])\n\n result = (np.array(values_r) + 1).cumprod() * 1000\n result = result.tolist()\n result.insert(0, 1000)\n values_num.insert(0, 0)\n\n # tag = tu.timeseries_std(dt.datetime(year, month + 1, 10),\n # tu.periods_in_interval(dt.datetime(year, month + 1, 10), dt.datetime(first_year, 1, 10),\n # 12), 12)[::-1]\n tag = tu.timeseries_std(dt.datetime(year, month, 10) + relativedelta(months=1),\n tu.periods_in_interval(dt.datetime(year, month, 10) + relativedelta(months=1), dt.datetime(first_year, 1, 10),\n 12), 12)[::-1]\n tag = [dt.date.fromtimestamp(x - 864000) for x in tag]\n\n op = pd.DataFrame(list(zip(tag, result, values_num)))\n op.columns = [\"statistic_date\", \"index_value\", \"funds_num\"]\n\n cols = [\"index_id\", \"index_name\", \"typestandard_code\", \"typestandard_name\", \"type_code\", \"type_name\",\n \"stype_code\",\n \"stype_name\", \"index_method\", \"data_source\", \"data_source_name\"]\n values = [PEIndex.id, PEIndex.name, PEIndex.typestandard[\"code\"], PEIndex.typestandard[\"name\"],\n PEIndex.type[\"code\"],\n PEIndex.type[\"name\"], PEIndex.stype[\"code\"], PEIndex.stype[\"name\"], 1, 0, \"私募云通\"]\n col_dict = dict(zip(cols, values))\n for col, val in col_dict.items():\n op[col] = val\n\n dfs = dfs.append(op[:-1])\n\n if export_path is not None:\n tmp = tag.copy()\n for year in sorted(components.keys(), reverse=True):\n print(year, len(tmp))\n components[year].columns = [\"fund_id\", *[tmp.pop() for i in range(len(components[year].columns) - 2)], tmp[-1]]\n io.export_to_xl(components, \"{sd}_{index_name}_m_samples\".format(sd=tag[-2].strftime(\"%Y%m%d\"), index_name=PEIndex.id), export_path)\n\n return dfs\n\n\ndef main(export_path=None):\n pool = multiprocessing.Pool(processes=multiprocessing.cpu_count())\n results = pool.map(partial(calculate, export_path=export_path), range(1, 14))\n pool.close()\n pool.join()\n for result in results:\n io.to_sql(table.name, engine_rd, result)\n\n\nif __name__ == \"__main__\":\n main(None)\n","sub_path":"SCRIPT/PRIVATE/cal/fund_monthly_index/fund_index_all_m.py","file_name":"fund_index_all_m.py","file_ext":"py","file_size_in_byte":5518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"121271031","text":"# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the Apache 2.0 License.\nimport tempfile\nimport http\nimport subprocess\nimport os\nimport glob\nimport infra.network\nimport infra.path\nimport infra.proc\nimport infra.notification\nimport infra.net\nimport infra.e2e_args\nimport suite.test_requirements as reqs\nimport ccf.proposal_generator\n\nfrom loguru import logger as LOG\n\nTHIS_DIR = os.path.dirname(__file__)\n\nMODULE_PATH_1 = \"/app/foo.js\"\nMODULE_RETURN_1 = \"Hello world!\"\nMODULE_CONTENT_1 = f\"\"\"\nexport function foo() {{\n return \"{MODULE_RETURN_1}\";\n}}\n\"\"\"\n\nMODULE_PATH_2 = \"/app/bar.js\"\nMODULE_CONTENT_2 = \"\"\"\nimport {foo} from \"./foo.js\"\nexport function bar() {\n return foo();\n}\n\"\"\"\n\n# For the purpose of resolving relative import paths,\n# app script modules are currently assumed to be located at /.\n# This will likely change.\nAPP_SCRIPT = \"\"\"\nreturn {\n [\"POST test_module\"] = [[\n import {bar} from \"./app/bar.js\";\n export default function()\n {\n return bar();\n }\n ]]\n}\n\"\"\"\n\n# Eventually, the npm app will contain these modules as well\n# together with an API description.\nNPM_APP_SCRIPT = \"\"\"\nreturn {\n [\"POST npm/partition\"] = [[\n import {partition} from \"./my-npm-app/src/endpoints.js\";\n export default () => partition();\n ]],\n [\"POST npm/proto\"] = [[\n import {proto} from \"./my-npm-app/src/endpoints.js\";\n export default () => proto();\n ]],\n [\"GET npm/crypto\"] = [[\n import {crypto} from \"./my-npm-app/src/endpoints.js\";\n export default () => crypto();\n ]]\n}\n\"\"\"\n\n\ndef make_module_set_proposal(path, content, network):\n primary, _ = network.find_nodes()\n with tempfile.NamedTemporaryFile(\"w\") as f:\n f.write(content)\n f.flush()\n proposal_body, _ = ccf.proposal_generator.set_module(path, f.name)\n proposal = network.consortium.get_any_active_member().propose(\n primary, proposal_body\n )\n network.consortium.vote_using_majority(primary, proposal)\n\n\n@reqs.description(\"Test module set and remove\")\ndef test_module_set_and_remove(network, args):\n primary, _ = network.find_nodes()\n\n LOG.info(\"Member makes a module update proposal\")\n make_module_set_proposal(MODULE_PATH_1, MODULE_CONTENT_1, network)\n\n with primary.client(\n f\"member{network.consortium.get_any_active_member().member_id}\"\n ) as c:\n r = c.post(\"/gov/read\", {\"table\": \"ccf.modules\", \"key\": MODULE_PATH_1})\n assert r.status_code == http.HTTPStatus.OK, r.status_code\n assert r.body[\"js\"] == MODULE_CONTENT_1, r.body\n\n LOG.info(\"Member makes a module remove proposal\")\n proposal_body, _ = ccf.proposal_generator.remove_module(MODULE_PATH_1)\n proposal = network.consortium.get_any_active_member().propose(\n primary, proposal_body\n )\n network.consortium.vote_using_majority(primary, proposal)\n\n with primary.client(\n f\"member{network.consortium.get_any_active_member().member_id}\"\n ) as c:\n r = c.post(\"/gov/read\", {\"table\": \"ccf.modules\", \"key\": MODULE_PATH_1})\n assert r.status_code == http.HTTPStatus.BAD_REQUEST, r.status_code\n return network\n\n\n@reqs.description(\"Test module import\")\ndef test_module_import(network, args):\n primary, _ = network.find_nodes()\n\n # Add modules\n make_module_set_proposal(MODULE_PATH_1, MODULE_CONTENT_1, network)\n make_module_set_proposal(MODULE_PATH_2, MODULE_CONTENT_2, network)\n\n # Update JS app which imports module\n with tempfile.NamedTemporaryFile(\"w\") as f:\n f.write(APP_SCRIPT)\n f.flush()\n network.consortium.set_js_app(remote_node=primary, app_script_path=f.name)\n\n with primary.client(\"user0\") as c:\n r = c.post(\"/app/test_module\", {})\n assert r.status_code == http.HTTPStatus.OK, r.status_code\n assert r.body == MODULE_RETURN_1\n\n return network\n\n\n@reqs.description(\"Test Node.js/npm app\")\ndef test_npm_app(network, args):\n primary, _ = network.find_nodes()\n\n LOG.info(\"Building npm app\")\n app_dir = os.path.join(THIS_DIR, \"npm-app\")\n subprocess.run([\"npm\", \"ci\"], cwd=app_dir, check=True)\n subprocess.run([\"npm\", \"run\", \"build\"], cwd=app_dir, check=True)\n\n LOG.info(\"Deploying npm app modules\")\n kv_prefix = \"/my-npm-app\"\n dist_dir = os.path.join(app_dir, \"dist\")\n for module_path in glob.glob(os.path.join(dist_dir, \"**\", \"*.js\"), recursive=True):\n module_name = os.path.join(kv_prefix, os.path.relpath(module_path, dist_dir))\n proposal_body, _ = ccf.proposal_generator.set_module(module_name, module_path)\n proposal = network.consortium.get_any_active_member().propose(\n primary, proposal_body\n )\n network.consortium.vote_using_majority(primary, proposal)\n\n LOG.info(\"Deploying endpoint script\")\n with tempfile.NamedTemporaryFile(\"w\") as f:\n f.write(NPM_APP_SCRIPT)\n f.flush()\n network.consortium.set_js_app(remote_node=primary, app_script_path=f.name)\n\n LOG.info(\"Calling npm app endpoints\")\n with primary.client(\"user0\") as c:\n body = [1, 2, 3, 4]\n r = c.post(\"/app/npm/partition\", body)\n assert r.status_code == http.HTTPStatus.OK, r.status_code\n assert r.body == [[1, 3], [2, 4]], r.body\n\n r = c.post(\"/app/npm/proto\", body)\n assert r.status_code == http.HTTPStatus.OK, r.status_code\n # CCF does not support binary responses yet.\n pb = bytes.fromhex(r.body)\n # We could now decode the protobuf message but given all the machinery\n # involved to make it happen (code generation with protoc) we'll leave it at that.\n assert len(pb) == 14, len(pb)\n\n r = c.get(\"/app/npm/crypto\")\n assert r.status_code == http.HTTPStatus.OK, r.status_code\n assert r.body[\"available\"], r.body\n\n\ndef run(args):\n hosts = [\"localhost\"] * (3 if args.consensus == \"pbft\" else 2)\n\n with infra.network.network(\n hosts, args.binary_dir, args.debug_nodes, args.perf_nodes, pdb=args.pdb\n ) as network:\n network.start_and_join(args)\n network = test_module_set_and_remove(network, args)\n network = test_module_import(network, args)\n network = test_npm_app(network, args)\n\n\nif __name__ == \"__main__\":\n\n args = infra.e2e_args.cli_args()\n args.package = \"libjs_generic\"\n run(args)\n","sub_path":"tests/modules.py","file_name":"modules.py","file_ext":"py","file_size_in_byte":6291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"51849088","text":"from __future__ import absolute_import\nimport hug\nfrom api.ext.dateutil import DateUtil\nfrom config import db\nfrom models.kettle.kettlejob import kettlejobs\nfrom models.kettle.kettlejoblog import kettlejoblogs\nfrom models import rows2data\n\nIGNORES = {'startdate', 'enddate'}\n\n\n@hug.object.urls('')\nclass KettleJobLogs(object):\n\n @hug.object.get()\n def get(self, request, response):\n log_date = request.params.get('logDate')\n t = kettlejoblogs.alias('k')\n j = kettlejobs.alias('j')\n joins = {'job': {\n 'column': t.c.jobname,\n 'select': ['id', 'name', 'job_module',\n 'job_schedule', 'update_mode',\n 'description'],\n 'table': j,\n 'join_column': j.c.name}}\n query = db.filter_join(t, joins, request, ['-logdate'])\n if log_date:\n dates = DateUtil.getDayBetween(log_date)\n query = query.where(t.c.logdate.between(dates[0], dates[1]))\n else:\n query = db.filter_by_date(t.c.logdate, query, request)\n rs = db.paginate_data(query, request, response)\n return rows2data(rs, t, joins)\n","sub_path":"api/kettle/kettlejoblog.py","file_name":"kettlejoblog.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"575660072","text":"from . import FixtureTest\n\n\nclass SuppressHistoricalClosed(FixtureTest):\n\n def test_cartoon_museum(self):\n # Cartoon Art Museum (closed)\n self.load_fixtures([\n 'https://www.openstreetmap.org/node/368173967',\n ])\n\n # POI shouldn't be visible early\n self.assert_no_matching_feature(\n 15, 5242, 12664, 'pois',\n {'id': 368173967})\n\n # but POI should be present at z17 and marked as closed\n self.assert_has_feature(\n 16, 10485, 25328, 'pois',\n {'id': 368173967, 'kind': 'closed', 'min_zoom': 17})\n","sub_path":"integration-test/291-483-suppress-historical-closed.py","file_name":"291-483-suppress-historical-closed.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"644718421","text":"\"\"\"\nBrutal force, add strings one by one, bit by bit\nUse pow()\n\"\"\"\n\nclass Solution:\n def addStrings(self, num1: str, num2: str) -> str:\n convert = {\n '0': 0,\n '1': 1,\n '2': 2,\n '3': 3,\n '4': 4,\n '5': 5,\n '6': 6,\n '7': 7,\n '8': 8,\n '9': 9,\n }\n\n sum = 0\n\n for i in range(1, len(num1) + 1):\n temp = convert[num1[-i]] * pow(10, i - 1)\n sum += temp\n\n for i in range(1, len(num2) + 1):\n temp = convert[num2[-i]] * pow(10, i - 1)\n sum += temp\n\n return str(sum)","sub_path":"LeetCode/415. Add Strings/415. Add Strings (very slow...brutal adding).py","file_name":"415. Add Strings (very slow...brutal adding).py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"492057786","text":"import csv\nimport os\nimport subprocess\nimport threading\n\n# Gather the packages to test.\n\nPREFIX = './packages/node_modules/'\nCISCOSPARK = os.path.join(PREFIX, '@ciscospark')\nWEBEX = os.path.join(PREFIX, '@webex')\n\nPROD_ENV_VARS = {\n 'CONVERSATION_SERVICE': 'https://conv-a.wbx2.com/conversation/api/v1',\n 'ENCRYPTION_SERVICE_URL': 'https://encryption-a.wbx2.com',\n 'IDBROKER_BASE_URL': 'https://idbroker.webex.com',\n 'IDENTITY_BASE_URL': 'https://identity.webex.com',\n 'U2C_SERVICE_URL': 'https://u2c.wbx2.com/u2c/api/v1',\n 'WDM_SERVICE_URL': 'https://wdm-a.wbx2.com/wdm/api/v1',\n # Logging\n 'ENABLE_VERBOSE_NETWORK_LOGGING': 'true',\n # Enable CI for Sauce Labs\n 'CI': 'true'\n}\n\nINT_ENV_VARS = {\n # Environments\n 'ATLAS_SERVICE_URL': 'https://atlas-intb.ciscospark.com/admin/api/v1',\n 'CONVERSATION_SERVICE': 'https://conversation-intb.ciscospark.com/conversation/api/v1',\n 'ENCRYPTION_SERVICE_URL': 'https://encryption-intb.ciscospark.com/encryption/api/v1',\n # Do not use 'https://hydra-intb.ciscospark.com/v1' for Hydra. CI expects 'apialpha'.\n 'HYDRA_SERVICE_URL': 'https://apialpha.ciscospark.com/v1/',\n 'IDBROKER_BASE_URL': 'https://idbrokerbts.webex.com',\n 'IDENTITY_BASE_URL': 'https://identitybts.webex.com',\n 'U2C_SERVICE_URL': 'https://u2c-intb.ciscospark.com/u2c/api/v1',\n 'WDM_SERVICE_URL': 'https://wdm-intb.ciscospark.com/wdm/api/v1',\n 'WHISTLER_API_SERVICE_URL': 'https://whistler.allnint.ciscospark.com/api/v1',\n # Logging\n 'ENABLE_VERBOSE_NETWORK_LOGGING': 'true',\n # Enable CI for Sauce Labs\n 'CI': 'true'\n}\n\nOUTPUT_DIR = 'output'\nOUTPUT_FILE_PATH = os.path.join(OUTPUT_DIR, 'test-comparison.csv')\n\nTEST_COMMAND = 'npm run sauce:run -- npm test -- --packages %s'\n\nSKIP_PACKAGES = [\n '@webex/test-helper-server' # no tests\n '@webex/internal-plugin-calendar', # no tests\n '@webex/plugin-webhooks' # no tests\n]\n\ndef should_include_package(path_name, name):\n scoped_name = os.path.join(os.path.basename(path_name), name)\n return os.path.isdir(os.path.join(path_name, name)) and scoped_name not in SKIP_PACKAGES\n\ndef get_package_names(path_name):\n namespace = path_name.replace(PREFIX, '')\n return [os.path.join(namespace, name) for name in os.listdir(path_name) if should_include_package(path_name, name)]\n\ndef run_subprocess(bash_command, env_vars):\n env = os.environ.copy()\n env.update(env_vars)\n process = subprocess.Popen(bash_command.split(), stdout=subprocess.PIPE, env=env)\n\n output, error = process.communicate()\n return process.returncode # , output, error\n\nclass bcolors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\ndef print_result(return_code, prefix='Tests are a...'):\n if return_code == 0:\n print(bcolors.OKGREEN + prefix + 'success.' + bcolors.ENDC)\n else:\n print(bcolors.FAIL + prefix + 'failure.' + bcolors.ENDC)\n\ndef run_test(package, environment):\n env_vars = INT_ENV_VARS if environment is 'integration' else PROD_ENV_VARS\n print(bcolors.OKBLUE + 'Testing `%s` on %s...' % (package, environment) + bcolors.ENDC)\n bash_command = TEST_COMMAND % package\n return_code = run_subprocess(bash_command, env_vars)\n print_result(return_code, prefix='Testing `%s` on %s...' % (package, environment))\n return return_code\n\ndef run_env_tests(package, writer, csv_file):\n prod_return_code = run_test(package, 'production')\n int_return_code = run_test(package, 'integration')\n writer.writerow([package, prod_return_code, int_return_code])\n csv_file.flush()\n\ndef run_tests_in_sequence(packages, writer, csv_file):\n for package in packages:\n run_env_tests(package, writer, csv_file)\n\ndef run_tests_in_parallel(packages, writer, csv_file):\n threads = [threading.Thread(target=run_env_tests, args=(package, writer, csv_file)) for package in packages]\n for thread in threads:\n thread.start()\n for thread in threads:\n thread.join()\n\ndef main():\n ciscospark_packages = get_package_names(CISCOSPARK)\n webex_packages = get_package_names(WEBEX)\n packages = ciscospark_packages + webex_packages\n print ('Skipping %d packages: %s' % (len(SKIP_PACKAGES), ', '.join(SKIP_PACKAGES)))\n print('Testing %d packages...' % len(packages))\n\n try:\n os.mkdir(OUTPUT_DIR)\n except OSError:\n pass\n\n threads = []\n\n with open(OUTPUT_FILE_PATH, 'wb') as csv_file:\n writer = csv.writer(csv_file, quoting=csv.QUOTE_MINIMAL)\n writer.writerow(['Package', 'Production exit code', 'Integration exit code'])\n\n run_tests_in_sequence(packages, writer, csv_file)\n\n print('Wrote output to: %s' % OUTPUT_FILE_PATH)\n print('Done.')\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"sauce.py","file_name":"sauce.py","file_ext":"py","file_size_in_byte":4686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"470127333","text":"# -*- coding: utf-8 -*-\n\n# dbthread.py\n#\n# ~~~~~~~~~~~~\n#\n# Function GUI DB Thread\n#\n# ~~~~~~~~~~~~\n#\n# ------------------------------------------------------------------\n# Author : Li Yonghu\n# Build: 24.04.2021\n# Last change: 24.04.2021 Li Yonghu \n#\n# Language: Python 3.7 PyQt5.15.2\n# ------------------------------------------------------------------\n# GNU GPL\n# \n \n#\n\n# Module Imports\n\nfrom PyQt5.QtCore import (Qt,QThread,QMutex)\nfrom PyQt5.QtCore import pyqtSignal as Signal\nfrom PyQt5.QtCore import pyqtSlot as Slot\nimport time,os\nimport traceback\n\nfrom matrixrd import *\n\nclass DBThread(QThread):\n result = Signal(bool)\n def __init__(self,parent=None):\n super(DBThread,self).__init__(parent)\n \n self.dbcpath=None\n\n def initialize(self,dbcpath,listmessageboxfile,listmessageboxinsert): \n self.dbcpath=dbcpath\n self.listmessageboxfile = listmessageboxfile\n self.listmessageboxinsert = listmessageboxinsert\n\n def run(self): \n \n reflag=self.DBCreate(self.dbcpath)\n\n if reflag == True:\n self.wait()\n self.listmessageboxfile.append('All Database haved be created')\n else:\n self.wait()\n self.listmessageboxfile.append('It generate error when creating Database')\n\n self.result.emit(True) \n\n def DBCreate(self,dbcpath):\n\n try:\n list_fdbcname=list()\n for root, dirs, files in os.walk(str(dbcpath)):\n \n for name in [name for name in files\n if name.endswith((\".dbc\", \".ldf\"))]:\n fname = os.path.join(root, name)\n list_fdbcname.append(fname)\n\n can_info=MatrixInfo()\n candbc=can_info.CanMatrixDb(list_fdbcname,self.listmessageboxfile,self.listmessageboxinsert) \n return True\n except Exception as e:\n mymsgbox = traceback.print_exc()\n self.listmessageboxfile(mymsgbox)\n return False","sub_path":"dbthread.py","file_name":"dbthread.py","file_ext":"py","file_size_in_byte":2233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"288123683","text":"#!venv/bin/python\n\nfrom flask import Flask\n\napp = Flask(__name__)\n\napp.config['elapsed'] = 0\napp.config['setval'] = 0\n\nHTML_TMPL = '''\n\nIDD Demo\n{}\n'''\n\n@app.route('/')\ndef index():\n return HTML_TMPL.format(\n '''

IDD Demo HTML page

\n

Counter: ''' + str(app.config['elapsed']) + '''

\n

Set Value: ''' + str(app.config['setval']) + '''

''',\n )\n\n@app.route('/api/incr')\ndef incr():\n app.config['elapsed'] += 1\n return '0'\n\n@app.route('/api/set/')\ndef setval(val):\n app.config['setval'] = val\n return '0'\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=80)\n","sub_path":"connectivity_esp8266/run_server.py","file_name":"run_server.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"551033248","text":"\nimport numpy as np\n\nfrom proj1_3.code.graph_search import graph_search\n\n\nclass WorldTraj(object):\n\n def __init__(self, world, start, goal):\n \"\"\"\n This is the constructor for the trajectory object. A fresh trajectory\n object will be constructed before each mission. For a world trajectory,\n the input arguments are start and end positions and a world object. You\n are free to choose the path taken in any way you like.\n\n You should initialize parameters and pre-compute values such as\n polynomial coefficients here.\n\n Parameters:\n world, World object representing the environment obstacles\n start, xyz position in meters, shape=(3,)\n goal, xyz position in meters, shape=(3,)\n\n \"\"\"\n self.resolution = np.array([0.125, 0.125, 0.125]) # resolution, the discretization of the occupancy grid in x,y,z[0.25, 0.25, 0.25]\n self.margin = 0.3\n # margin, the inflation radius used to create the configuration space (assuming a spherical drone)\n self.path = graph_search(world, self.resolution, self.margin, start, goal, astar=True)\n # ------------------------ Reduce Points-----------------------------------\n # Reference:\n # https://stackoverflow.com/questions/26820714/python-find-vector-direction-between-two-3d-points?rq=1\n # I want to determine if two consecutive points have same direction\n self.points = np.zeros((1, 3))\n self.temp = np.zeros((1, 3))\n diff = np.diff(self.path, axis=0) # find difference between two consecutive points\n norm = np.sum(diff ** 2, 1)\n norm = np.asarray(norm).reshape((len(norm), 1))\n direction = diff / norm # Normalized Direction\n\n for i in range(len(direction) - 1):\n if not np.array_equal(direction[i + 1], direction[i]):\n self.temp = np.append(self.temp, [self.path[i]],\n axis=0) # OnlyPoints with different direction are needed\n self.temp = self.temp[1:, :]\n\n for i in range(self.temp.shape[0] - 1):\n if np.linalg.norm(self.temp[i + 1] - self.temp[i]) > 0.25: # remove points which are close to each other, 0.4\n self.points = np.append(self.points, [self.temp[i]], axis=0)\n self.points = np.append(self.points, [self.path[-1]], axis=0)\n self.points = self.points[1:, :] # no need (0,0,0)\n # print(self.points)\n\n # Finally, you must compute a trajectory through the waypoints similar\n # to your task in the first project. One possibility is to use the\n # WaypointTraj object you already wrote in the first project. However,\n # you probably need to improve it using techniques we have learned this\n # semester.\n\n # STUDENT CODE HERE\n\n self.velocity = 0.6 # -------------------------------------------------============================\n self.time_interval = []\n\n self.length_interval = [] # list\n for i in range(self.points.shape[0] - 1):\n self.length_interval.append(np.linalg.norm(self.points[i + 1] - self.points[i]))\n\n print('points length: ', self.points.shape[0])\n print('length interval length: ', len(self.length_interval))\n self.time_interval = np.asarray(self.length_interval) / self.velocity # ndarray\n self.time_interval = np.insert(self.time_interval, 0, 0)\n print(self.time_interval)\n self.total_time = np.sum(self.time_interval)\n\n self.accumulated_time = [0, self.time_interval[1]]\n\n for i in range(1, self.time_interval.shape[0] - 1):\n self.accumulated_time.append(self.accumulated_time[i] + self.time_interval[i+1])\n\n\n # Minimum Jerk Spline on Slides 13 Page 5\n unknowns = 6 * (self.points.shape[0] - 1 ) # 6 * m unknowns (m is number of segments )\n A_Matrix = np.zeros((unknowns,unknowns)) # A need to be saqure for inverting\n b = np.zeros((unknowns,3)) # right hand side of Ax = b\n A_Matrix[0:3,0:6] = np.array([[0,0,0,0,0,1],\n [0,0,0,0,1,0],\n [0,0,0,2,0,0]])\n # Boundary Conditions at first point and last point # Page 5 of Slides 13\n A_Matrix[-3:,-6:] = np.array([[self.time_interval[-1] ** 5, self.time_interval[-1] ** 4,self.time_interval[-1] ** 3, self.time_interval[-1] ** 2,self.time_interval[-1], 1],\n [5 * self.time_interval[-1] ** 4, 4 * self.time_interval[-1] ** 3,3 * self.time_interval[-1] ** 2, 2 * self.time_interval[-1], 1, 0],\n [20 * self.time_interval[-1] ** 3, 12 * self.time_interval[-1] ** 2, 6 * self.time_interval[-1], 2, 0, 0]])\n\n b[0:3,:] = np.array([self.points[0], [0,0,0],[0,0,0]]) # Page 9: p1(0) = y0 p1dot(0) = ydot0 p1ddot(0) = yddot0\n b[-3:,:] = np.array([self.points[-1],[0,0,0],[0,0,0]]) # Page 11: p1(t) = y0 p1dot(t) = ydot0 p1ddot(t) = yddot0\n\n\n for i in range(1, self.points.shape[0] - 1):\n A_Matrix[-3 + 6 * i:3+6*i, -6+6*i:6 + 6*i] = np.array([\n [self.time_interval[i] ** 5,self.time_interval[i] ** 4, self.time_interval[i] ** 3,self.time_interval[i] ** 2,self.time_interval[i],1,0,0,0,0,0,0],\n [0,0,0,0,0,0,0,0,0,0,0,1],\n [5 * self.time_interval[i] ** 4, 4 * self.time_interval[i] ** 3, 3 * self.time_interval[i] ** 2, 2 * self.time_interval[i], 1, 0,0, 0, 0, 0, -1, 0],\n [20 * self.time_interval[i] ** 3, 12 * self.time_interval[i] ** 2, 6 * self.time_interval[i], 2, 0, 0, 0, 0, 0, -2, 0, 0],\n [60 * self.time_interval[i] ** 2, 24 * self.time_interval[i], 6,0, 0, 0, 0, 0, -6, 0, 0, 0],\n [120 * self.time_interval[i], 24, 0, 0, 0, 0, 0, -24, 0, 0, 0, 0],\n\n ])\n\n\n b[-3 + 6 * i:3 + 6 * i, :] = np.array([self.points[i], self.points[i], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]])\n\n\n self.Coef = np.linalg.solve(A_Matrix,b)\n # print(self.Coef)\n print(self.Coef.shape)\n\n\n print('---------')\n # print(self.Coef)\n # print('selfpoints: ', self.points.shape[0])\n # print(self.time_interval.shape[0])\n # print('---------')\n # # print('time', self.time_interval)\n # print('accumulated time: ', self.accumulated_time)\n print(len(self.accumulated_time))\n\n\n\n\n def update(self, t):\n \"\"\"\n Given the present time, return the desired flat output and derivatives.\n\n Inputs\n t, time, s\n Outputs\n flat_output, a dict describing the present desired flat outputs with keys\n x, position, m\n x_dot, velocity, m/s\n x_ddot, acceleration, m/s**2\n x_dddot, jerk, m/s**3\n x_ddddot, snap, m/s**4\n yaw, yaw angle, rad\n yaw_dot, yaw rate, rad/s\n \"\"\"\n x = np.zeros((3,)) # Position\n x_dot = np.zeros((3,)) # Velocity\n x_ddot = np.zeros((3,)) # Acceleration\n x_dddot = np.zeros((3,)) # Jerk\n x_ddddot = np.zeros((3,)) # Snap\n yaw = 0\n yaw_dot = 0\n\n # STUDENT CODE HERE\n if t > self.total_time:\n x = self.points[-1] # Position\n # print(self.points[-1].shape)\n x_dot = np.zeros((3,)) # Velocity\n x_ddot = np.zeros((3,)) # Acceleration\n else:\n for i in range(len(self.accumulated_time) - 1):\n if self.accumulated_time[i + 1] > t > self.accumulated_time[i]:\n dt = t - self.accumulated_time[i]\n [x, x_dot, x_ddot, x_dddot, x_ddddot] = np.array(\n [[dt ** 5, dt ** 4, dt ** 3, dt ** 2, dt ** 1, 1],\n [5 * dt ** 4, 4 * dt ** 3, 3 * dt ** 2, 2 * dt, 1, 0],\n [20 * dt ** 3, 12 * dt ** 2, 6 * dt, 2, 0, 0],\n [60 * dt ** 2, 24 * dt, 6, 0, 0, 0],\n [120 * dt, 24, 0, 0, 0, 0]\n ]) @ self.Coef[6 * i:6 * i + 6, :]\n break\n\n\n\n flat_output = {'x': x, 'x_dot': x_dot, 'x_ddot': x_ddot, 'x_dddot': x_dddot, 'x_ddddot': x_ddddot,\n 'yaw': yaw, 'yaw_dot': yaw_dot}\n\n\n\n\n # The following old approach is minimum jerk, stop at each waypoints\n\n # print(self.accumulated_time[i+1])\n # position = lambda time: self.Coef[i, 0] * np.power(time, 5) + self.Coef[i, 1] * np.power(time, 4) + \\\n # self.Coef[i, 2] * np.power(time, 3) + self.Coef[i, 3] * np.power(time, 2) + \\\n # self.Coef[i, 4] * np.power(time, 1) + self.Coef[i, 5] * np.power(time, 0)\n #\n # velocity = lambda time: 5 * np.power(time, 4) * self.Coef[i, 0] + 4 * np.power(time, 3) * self.Coef[i, 1] + 3 * np.power(time, 2) * self.Coef[i, 2] + 2 * np.power(time, 1) * self.Coef[i, 3] + self.Coef[i, 4]\n # acceleration = lambda time: 20 * np.power(time, 3) * self.Coef[i, 0] + 12 * np.power(time, 2) * self.Coef[i, 1] + 6 * np.power(time, 1) * self.Coef[i, 2] + 2 * self.Coef[i, 3]\n #\n # temp_pos = position(t - self.accumulated_time[i])\n # # print(t - self.accumulated_time[i])\n #\n # temp_vel = velocity(t - self.accumulated_time[i])\n #\n # temp_acc = acceleration(t - self.accumulated_time[i])\n\n\n\n # direction = (self.points[i + 1] - self.points[i]) / np.linalg.norm(self.points[i + 1] - self.points[i])\n # x = self.points[i] + direction * temp_pos\n # x_dot = direction * temp_vel\n # x_ddot = direction * temp_acc\n\n return flat_output\n","sub_path":"Trajectory Generation Phase 3/meam620-2020/proj1_3/code/world_traj.py","file_name":"world_traj.py","file_ext":"py","file_size_in_byte":10200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"210910990","text":"#!/usr/bin/env python\n# Copyright (c) 2013, Charles Duyk\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# \n# Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# \n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nimport subprocess\nimport argparse\nimport os\nimport sys\n\nif __name__ == \"__main__\":\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument(\"command\", help=\"The command to run on each element in the folder\")\n\tparser.add_argument(\"folder\", help=\"The folder over which to iterate\", nargs=\"?\", default=\".\")\n\tparser.add_argument(\"-v\", \"--verbose\", help=\"Verbose output to stderr\", action=\"store_true\")\n\targs = parser.parse_args()\n\tcommand = args.command\n\tfolder = args.folder\n\tverbose = args.verbose\n\tcommandList = command.split()\n\tfor dirName, subDirs, files in os.walk(folder):\n\t\tfor file in files:\n\t\t\tpath = os.path.join(dirName, file)\n\t\t\tif verbose:\n\t\t\t\tsys.stderr.write(\"%s %s\\n\" % (command, path))\n\t\t\tinvocation = commandList[:]\n\t\t\tinvocation.append(path)\n\t\t\tsubprocess.call(invocation)\n\n","sub_path":"funix/apply.py","file_name":"apply.py","file_ext":"py","file_size_in_byte":2148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"2773225","text":"from Vector_Matrix import *\nimport matplotlib.pyplot as plt\nimport math\nimport CAccel as acc\n\n\nclass Atom:\n def __init__(self, infoList):\n self.infoList = infoList\n\n @property\n def vector(self):\n return np.array([float(val) for val in self.infoList[6:9]])\n\n @property\n def type(self):\n return self.infoList[2]\n\n @property\n def n(self):\n return int(self.infoList[1])\n\n def transform(self, rotMat, transVtr):\n vtr = np.dot(self.vector, rotMat) + transVtr\n self.infoList[6] = '%.3f' % vtr[0]\n self.infoList[7] = '%.3f' % vtr[1]\n self.infoList[8] = '%.3f' % vtr[2]\n return self\n\n\nclass Residue:\n def __init__(self, atomDict, aminoName):\n self.atoms = atomDict\n self.aminoAcid = aminoName\n\n\nclass Chain:\n def __init__(self, residueList):\n self.residues = residueList\n\n @property\n def AtomsList(self):\n atomsList = []\n for residue in self.residues:\n atomsList += residue.atoms.values()\n return atomsList\n\n @property\n def CAAtomsList(self):\n return [atom for atom in self.AtomsList if atom.type == 'CA']\n\n def __len__(self):\n return len(self.residues)\n\n\n # TODO: Implement the window function\n def Get_AminoNVtr(self, window = 1):\n assert window % 2 == 1\n offset = window\n listNVtr = [self.residues[1].atoms['N'].vector - self.residues[0].atoms['N'].vector]\n\n for i in range(1, len(self.residues) - 1):\n try:\n vtr_NC = self.residues[i].atoms['N'].vector - self.residues[i - 1].atoms['C'].vector\n vtr_NCa = self.residues[i].atoms['N'].vector - self.residues[i].atoms['CA'].vector\n norm_vtr = np.cross(vtr_NC, vtr_NCa)\n norm_vtr = norm_vtr / Len_Vtr(norm_vtr)\n axis, angle = SolveFor_rot(norm_vtr, np.array([0,0,1]))\n oriNVtr = self.residues[i].atoms['N'].vector - self.residues[i + 1].atoms['N'].vector\n listNVtr.append(Rodrigues_rot(oriNVtr, axis, angle))\n except KeyError as e:\n print(\"Key error at #\" + str(i))\n\n listNVtr.append(np.array([0,0,0]))\n return listNVtr\n\n def Get_CAContactMap(self):\n contactMap = np.empty((len(self), len(self)))\n for i in range(0, len(self)):\n for j in range(i, len(self)):\n contactMap[i][j] = Len_Vtr(self.residues[i].atoms['CA'].vector - self.residues[j].atoms['CA'].vector)\n return contactMap + contactMap.T\n\n\n #def Get_SurroundVectorSet(self, low_cutoff, high_cutoff, keep=10):\n # neighborAminos = []\n\n # for i in range(0, len(self)):\n # residueLenAminos = {}\n\n # vtr_CaN = self.residues[i].atoms['CA'].vector - self.residues[i].atoms['N'].vector\n # vtr_CaC = self.residues[i].atoms['CA'].vector - self.residues[i].atoms['C'].vector\n # norm_vtr = np.cross(vtr_CaN, vtr_CaC)\n # norm_vtr = norm_vtr / Len_Vtr(norm_vtr)\n # axis, angle = SolveFor_rot(norm_vtr, np.array([0,0,1]))\n\n # for j in range(0, len(self)):\n # theVtr = self.residues[i].atoms['CA'].vector - self.residues[j].atoms['CA'].vector\n # theVtrLen = Len_Vtr(theVtr)\n # if low_cutoff < theVtrLen < high_cutoff:\n # residueLenAminos[Len_Vtr(theVtr)] = (theVtr, j)\n\n # residueSurroundVtr = [(Rodrigues_rot(residueLenAminos[aaLen][0], axis, angle), residueLenAminos[aaLen][1], Len_Vtr(residueLenAminos[aaLen][0]))\n # for aaLen in sorted(residueLenAminos.keys())][:keep]\n # neighborAminos.append(residueSurroundVtr)\n\n # return neighborAminos\n\n\n def Get_SurroundVectorSet(self, low_cutoff, high_cutoff, keep=1000):\n neighborAminos = []\n\n for i in range(0, len(self)):\n residueLenAminos = {}\n\n vtr_CaN = self.residues[i].atoms['CA'].vector - self.residues[i].atoms['N'].vector\n vtr_CaC = self.residues[i].atoms['CA'].vector - self.residues[i].atoms['C'].vector\n\n for j in range(0, len(self)):\n theVtr = self.residues[j].atoms['CA'].vector - self.residues[i].atoms['CA'].vector\n theVtrLen = Len_Vtr(theVtr)\n if low_cutoff < theVtrLen < high_cutoff:\n bondAngle = math.acos(np.dot(vtr_CaN, theVtr) / (Len_Vtr(vtr_CaN) * Len_Vtr(theVtr)))\n #bondAngle = (np.dot(vtr_CaN, theVtr) / (Len_Vtr(vtr_CaN) * Len_Vtr(theVtr)))\n plnNorm1 = np.cross(vtr_CaN, theVtr)\n plnNorm2 = np.cross(vtr_CaN, vtr_CaC)\n torsionAngle = math.acos(np.dot(plnNorm1, plnNorm2) / (Len_Vtr(plnNorm1) * Len_Vtr(plnNorm2)))\n #torsionAngle = (np.dot(plnNorm1, plnNorm2) / (Len_Vtr(plnNorm1) * Len_Vtr(plnNorm2)))\n residueLenAminos[theVtrLen] = (theVtrLen, bondAngle, torsionAngle)#, self.residues[j])\n residueSurroundVtr = [(residueLenAminos[aaLen])\n #for aaLen in sorted(residueLenAminos.keys())][:keep]\n for aaLen in (residueLenAminos.keys())][:keep]\n neighborAminos.append(residueSurroundVtr)\n\n return neighborAminos\n\n\ndef Accle_SurroundVectorSet(chain, low_cutoff, high_cutoff, keep=1000):\n aminosAtomsCoord = []\n for i in range(0, len(chain)):\n theAminoAtoms = []\n theAminoAtoms.append(chain.residues[i].atoms['N'].vector)\n theAminoAtoms.append(chain.residues[i].atoms['CA'].vector)\n theAminoAtoms.append(chain.residues[i].atoms['C'].vector)\n aminosAtomsCoord.append(theAminoAtoms)\n aminosAtomsCoord = np.array(aminosAtomsCoord)\n\n #print(aminosAtomsCoord[0])\n #print(aminosAtomsCoord[3])\n #print(acc.C_SurroundVectorSet(aminosAtomsCoord, low_cutoff, high_cutoff)[0])\n #acc.C_SurroundVectorSet(aminosAtomsCoord, low_cutoff, high_cutoff)\n #print(np.cross(aminosAtomsCoord[0][0], aminosAtomsCoord[0][2]))\n\n return acc.C_SurroundVectorSet(aminosAtomsCoord, low_cutoff, high_cutoff)\n #return aminosAtomsCoord\n\n\ndef Get_NeighborAminoNo(contactMap, low_cutoff, high_cutoff):\n neighborVector = []\n\n for i in range(0, len(contactMap)):\n theResidueNeighbor = []\n for j in range(0, len(contactMap)):\n if low_cutoff < contactMap[i][j] <= high_cutoff:\n theResidueNeighbor.append(j)\n neighborVector.append(theResidueNeighbor)\n\n return neighborVector\n\n\ndef ReadPDBAsAtomsList(filename):\n f = open(filename, 'r')\n content = f.readlines()\n atomLines = [theLine for theLine in content if theLine[:4] == \"ATOM\"]\n pdbAtomsList = []\n\n for line in atomLines:\n theAtom = []\n theAtom.append(line[:4])\n theAtom.append(line[4:11].strip())\n theAtom.append(line[11:16].strip())\n theAtom.append(line[17:20].strip())\n theAtom.append(line[20:22].strip())\n theAtom.append(line[22:26].strip())\n theAtom.append(line[30:38].strip())\n theAtom.append(line[38:46].strip())\n theAtom.append(line[46:54].strip())\n theAtom.append(line[54:60].strip())\n theAtom.append(line[60:66].strip())\n theAtom.append(line[66:80].strip())\n pdbAtomsList.append(theAtom)\n\n return pdbAtomsList\n\n\ndef FormatAtomLine(atomInfoList):\n return '%s%7s'%(atomInfoList[0], atomInfoList[1]) + 2 * ' ' + atomInfoList[2].ljust(4) + atomInfoList[3].ljust(4) + \\\n atomInfoList[4] + atomInfoList[5].rjust(4) + atomInfoList[6].rjust(12) + atomInfoList[7].rjust(8) + \\\n atomInfoList[8].rjust(8) + atomInfoList[9].rjust(6) + atomInfoList[10].rjust(6) + ' ' * 11 + \\\n atomInfoList[11].ljust(3) + '\\n'\n\n\ndef SavePDBFile(filename, chainList):\n f = open(filename, 'w')\n pdbFileLines = []\n atomsDict = {}\n\n for chain in chainList:\n for residue in chain.residues:\n for atom in residue.atoms.values():\n atomsDict[atom.n] = atom\n pdbFileLines += [FormatAtomLine(atomsDict[atomNo].infoList) + '\\n' for atomNo in sorted(atomsDict.keys())]\n pdbFileLines += \"TER\\n\"\n\n pdbFileLines += 'END\\n'\n f.writelines(pdbFileLines)\n f.flush()\n f.close()\n\n\ndef GetChain(pdbAtomsList, chainId):\n #atomsList = [atom for atom in pdbAtomsList if atom[4] == chainId]\n atomsList = [atom for atom in pdbAtomsList]\n pdbAminoDict = {}\n\n for atom in atomsList:\n try:\n pdbAminoDict[int(atom[5])].atoms[atom[2]] = Atom(atom)\n except KeyError:\n pdbAminoDict[int(atom[5])] = Residue({}, atom[3])\n pdbAminoDict[int(atom[5])].atoms[atom[2]] = Atom(atom)\n# for i in range(1, 395):\n# try:\n# pdbAminoDict[i] == None\n# except KeyError:\n# print(i)\n\n return Chain([pdbAminoDict[aminoNo] for aminoNo in sorted(pdbAminoDict.keys())])\n\n\ndef Get_Aminos(chain, low_cutoff = 4, high_cutoff = 12):\n aminoNVtr = chain.Get_AminoNVtr()\n neighborVtr = Accle_SurroundVectorSet(chain, low_cutoff, high_cutoff)\n\n assert len(aminoNVtr) == len(neighborVtr)\n aminosList = []\n for i in range(0, len(aminoNVtr)):\n aminosList.append((aminoNVtr[i], neighborVtr[i]))\n\n return aminosList\n\n\ndef Dbg_GetVtrLen(chain, aaNo1, aaNo2):\n theVtr = chain.CAAtomsList[aaNo1].vector - chain.CAAtomsList[aaNo2].vector\n return theVtr, Len_Vtr(theVtr)\n\n\nif __name__ == \"__main__\":\n pdbAtomsList1 = ReadPDBAsAtomsList(\"pdbs/Legacy/101M.pdb\")\n pdbAtomsList2 = ReadPDBAsAtomsList(\"pdbs/Legacy/1MBA_New.pdb\")\n chain1 = GetChain(pdbAtomsList1, 'A')\n chain2 = GetChain(pdbAtomsList2, 'A')\n ##cm = chainA.Get_CAContactMap()\n ##nv = Get_NeighborAminoNo(cm, 4.0, 12.0)\n neiVtr1 = chain1.Get_SurroundVectorSet(4, 12, 1000)\n neiVtr2 = chain2.Get_SurroundVectorSet(4, 12, 1000)\n #cm1 = chain1.Get_CAContactMap()\n #nv1 = Get_NeighborAminoNo(cm1, 4.0, 12.0)\n #cm2 = chain2.Get_CAContactMap()\n #nv2 = Get_NeighborAminoNo(cm2, 4.0, 12.0)\n\n simValArray = []\n for i in range(0, len(chain2)):\n print(str(i) + '\\t\\t' + str(Calc_SimVectorSet(neiVtr1[67], neiVtr2[i])))\n simValArray.append(Calc_SimVectorSet(neiVtr1[67], neiVtr2[i]))\n x = np.arange(0, len(chain2))\n plt.scatter(x, simValArray)\n plt.show()\n plt.figure()\n plt.hist(simValArray, bins=20)\n plt.show()\n\n #neiVtr1 = chain1.Get_SurroundVectorSet(12, 20, 1000)\n #neiVtr2 = chain2.Get_SurroundVectorSet(12, 20, 1000)\n #simValArray = []\n #for i in range(0, len(chain2)):\n # #print(str(i) + '\\t\\t' + str(Calc_SimVectorSet(neiVtr1[100], neiVtr2[i])))\n # simValArray.append(Calc_SimVectorSet(neiVtr1[80], neiVtr2[i]))\n # print(i)\n #plt.scatter(x, simValArray)\n\n #neiVtr1 = chain1.Get_SurroundVectorSet(0, 100, 1000)\n #neiVtr2 = chain2.Get_SurroundVectorSet(0, 100, 1000)\n #simValArray = []\n #for i in range(0, len(chain2)):\n # #print(str(i) + '\\t\\t' + str(Calc_SimVectorSet(neiVtr1[100], neiVtr2[i])))\n # simValArray.append(Calc_SimVectorSet(neiVtr1[20], neiVtr2[i]))\n #plt.plot(x, simValArray)\n\n #SavePDBFile(\"pdbs/4xt3_new.pdb\", [chainA])\n Calc_SimVectorSet(neiVtr1[27], neiVtr2[27], True)\n print()\n","sub_path":"PDB_Helper.py","file_name":"PDB_Helper.py","file_ext":"py","file_size_in_byte":11289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"593996990","text":"from qsweepy import*\r\nimport dash\r\nimport dash_core_components as dcc\r\nimport dash_html_components as html\r\nimport dash_table\r\nimport numpy as np\r\nimport webcolors\r\n\r\n#import exdir\r\n#from data_structures import *\r\nimport plotly.graph_objs as go\r\nfrom pony.orm import *\r\n#from database import database\r\nfrom plotly import*\r\nfrom cmath import phase\r\n#from datetime import datetime\r\nfrom dash.dependencies import Input, Output, State\r\nimport pandas as pd\r\nimport psycopg2\r\nimport pandas.io.sql as psql\r\nimport logging\r\n\r\nlog = logging.getLogger('werkzeug')\r\nlog.setLevel(logging.ERROR)\r\n\r\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\r\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets, static_folder='static')\r\napp.config['suppress_callback_exceptions']=True\r\napp.css.config.serve_locally = True\r\napp.scripts.config.serve_locally = True\r\ndb = database.database()\r\n\r\n\t\t\t\r\ndirect_db = psycopg2.connect(database='qsweepy', user='qsweepy', password='qsweepy')\r\ndefault_query = 'SELECT * FROM data;'\r\n\r\ndef string_to_list(string):\r\n\tif string == '': return []\r\n\tposition = string.find(',')\r\n\tlist_res = []\r\n\twhile position > -1:\r\n\t\t#print(position, 'and', string[:10], 'and', string[position+1:])\r\n\t\tlist_res.append(string[:position])\r\n\t\tstring = string[position+2:]\r\n\t\tposition = string.find(',')\r\n\tif string != '': list_res.append(string)\r\n\treturn list_res\r\n\r\ndef data_to_dict(data):\r\n\t\treturn { 'id': data.id,\r\n\t\t\t\t #comment': data.comment,\r\n\t\t\t\t 'sample_name': data.sample_name,\r\n\t\t\t\t'time_start': data.time_start,\r\n\t\t\t\t 'time_stop': data.time_stop,\r\n\t\t\t\t #'filename': data.filename,\r\n\t\t\t\t 'type_revision': data.type_revision,\r\n\t\t\t\t 'incomplete': data.incomplete,\r\n\t\t\t\t 'invalid': data.invalid,\r\n\t\t\t\t 'owner': data.owner,\r\n\t\t\t\t} \r\n\r\ndef generate_table(dataframe, max_rows=10):\r\n\treturn html.Table(\r\n\t\t\t# Header\r\n\t\t\t[html.Tr([html.Th(col) for col in dataframe.columns])] +\r\n\r\n\t\t\t# Body\r\n\t\t\t[html.Tr([\r\n\t\t\t\thtml.Td(str(dataframe.iloc[i][col])) for col in dataframe.columns\r\n\t\t\t]) for i in range(min(len(dataframe), max_rows))])\r\n\t\r\nmeas_ids = ''\r\nfit_ids = ''\r\ndim_2 = False\r\n\r\nlayout = {}\r\nfigure = {}\r\n\r\ndef measurement_table():\r\n\treturn dash_table.DataTable(id=\"meas-id\", columns=[{'id': 'id', 'name':'id'}, {'id': 'label', 'name':'label'}], data=[], editable=True, row_deletable=True)\r\n\r\n@app.callback(\r\n\tOutput(component_id=\"meas-id\", component_property=\"data\"),\r\n\t[Input(component_id=\"query-results-table\", component_property=\"derived_virtual_data\"),\r\n Input(component_id=\"query-results-table\", component_property=\"derived_virtual_selected_rows\")],\r\n\tstate=[State(component_id=\"meas-id\", component_property=\"derived_virtual_data\")]\r\n)\r\ndef render_measurement_table(query_results, query_results_selected, current_measurements):\r\n\tprint ('render_measurement_table called')\r\n\t#current_measurements = []\r\n\tif current_measurements is None:\r\n\t\treturn []\r\n\t\r\n\tprint(query_results, query_results_selected, current_measurements)\r\n\tselected_measurement_ids = [query_results[measurement]['id'] for measurement in query_results_selected]\r\n\tdeselected_measurement_ids = [measurement['id'] for measurement in query_results if not measurement['id'] in selected_measurement_ids]\r\n\told_measurement_ids = [measurement['id'] for measurement in current_measurements]\r\n\told_measurements = [measurement for measurement in current_measurements if not measurement['id'] in deselected_measurement_ids]\r\n\tnew_measurements = [{'id':query_results[measurement]['id'], \r\n\t\t\t\t\t\t 'label': (query_results[measurement]['label'] if 'label' in query_results[measurement] else query_results[measurement]['id'])} \r\n\t\t\t\t\t\t\tfor measurement in query_results_selected if (not query_results[measurement]['id'] in old_measurement_ids)]\r\n\t\r\n\treturn old_measurements+new_measurements\r\n\r\ndef available_traces_table(data=[], column_static_dropdown=[], column_conditional_dropdowns=[]):\r\n\t#print (column_static_dropdown, column_conditional_dropdowns)\r\n\treturn dash_table.DataTable(id=\"available-traces-table\", columns=[{'id': 'id', 'name': 'id'}, \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t {'id': 'dataset', 'name': 'dataset'}, \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t {'id': 'op', 'name': 'op'}, \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t {'id': 'style', 'name': 'style', 'presentation':'dropdown'},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t {'id': 'color', 'name': 'color', 'presentation':'dropdown'},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t {'id': 'x-axis', 'name': 'x-axis', 'presentation':'dropdown'},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t {'id': 'y-axis', 'name': 'y-axis', 'presentation':'dropdown'},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t {'id': 'row', 'name':'row'},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t {'id': 'col', 'name':'col'}], data=data, editable=True, row_selectable='multi', selected_rows=[], column_static_dropdown=column_static_dropdown, column_conditional_dropdowns=column_conditional_dropdowns)\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n@app.callback(\r\n\tOutput(component_id=\"available-traces-container\", component_property=\"children\"),\r\n\t[Input(component_id=\"meas-id\", component_property=\"derived_virtual_data\")],\r\n\tstate=[State(component_id=\"available-traces-table\", component_property=\"derived_virtual_data\")]\r\n\t)\r\ndef render_available_traces_table(loaded_measurements, current_traces):\r\n\t# traverse loaded measurements and add all datasets\r\n\twith db_session:\r\n\t\tdata = []\r\n\t\t#x_axis_conditional_dropdowns = []\r\n\t\tconditional_dropdowns = []\r\n\t\t#y_axis_conditional_dropdowns = []\r\n\t\tcolors = [c for c in webcolors.CSS3_NAMES_TO_HEX.keys()]\r\n\t\tstyles = ['2d', '-', '.', 'o']\r\n\t\tfor m in loaded_measurements:\r\n\t\t\tmeasurement_id = m['id']\r\n\t\t\tmeasurement_state = save_exdir.load_exdir(db.Data[int(measurement_id)].filename, db)\r\n\t\t\tfor dataset in measurement_state.datasets.keys():\r\n\t\t\t\tparameter_names = [p.name for p in measurement_state.datasets[dataset].parameters]\r\n\t\t\t\t#dropdown_row_condition = 'id eq \"{}\" and dataset eq \"{}\"'.format(measurement_id, dataset)\r\n\t\t\t\tdropdown_row_condition = 'dataset eq \"{}\"'.format(dataset)\r\n\t\t\t\t#y_dropdown_row_condition = 'dataset eq \"{}\"'.format(dataset)\r\n\t\t\t\tif np.iscomplexobj(measurement_state.datasets[dataset].data): # if we are dealing with complex object, give the chance of selecting which op we want to apply\r\n\t\t\t\t\toperations = ['Re', 'Im', 'Abs', 'Ph']\r\n\t\t\t\telse:\r\n\t\t\t\t\toperations = ''\r\n\t\t\t\tconditional_dropdowns.append({'condition':dropdown_row_condition, 'dropdown':[{'label': p, 'value': p} for p in parameter_names]+[{'label':'data', 'value':'data'}]})\r\n\t\t\t\t#y_axis_conditional_dropdowns.append({'condition':y_dropdown_row_condition, 'dropdown':[{'label': p, 'value': p} for p in parameter_names]+[{'label':'data', 'value':'data'}]})\r\n\t\t\t\tfor operation in operations:\r\n\t\t\t\t\trow = {'id': measurement_id, \r\n\t\t\t\t\t\t 'dataset': dataset, \r\n\t\t\t\t\t\t 'op':operation, \r\n\t\t\t\t\t\t 'style':'-', \r\n\t\t\t\t\t\t 'color': 'black', \r\n\t\t\t\t\t\t 'x-axis': parameter_names[0] if len(parameter_names) > 0 else 'data', \r\n\t\t\t\t\t\t 'y-axis': parameter_names[0] if len(parameter_names) > 1 else 'data', #[1]?\r\n\t\t\t\t\t\t 'row': 0, \r\n\t\t\t\t\t\t 'col': 0}\r\n\t\t\t\t\tdata.append(row)\r\n\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t# check if dataset is in current traces, if not, update the cell values with current values\r\n\t\t#print (data)\r\n\t\treturn available_traces_table(data, [{'id': 'style', 'dropdown': [{'label':s, 'value': s} for id, s in enumerate(styles)]},\r\n\t\t\t\t\t\t\t\t\t\t\t {'id': 'color', 'dropdown': [{'label':c, 'value': c} for c in colors]}],\r\n\t\t\t\t\t\t\t\t\t\t\t[{'id': 'x-axis', 'dropdowns': conditional_dropdowns}, \r\n\t\t\t\t\t\t\t\t\t\t\t {'id': 'y-axis', 'dropdowns': conditional_dropdowns}])\r\n\t\r\ndef app_layout():\r\n\treturn html.Div(children=[html.Div(id=\"modal-select-measurements\", className= \"modal\", style={'display':'none'}, children=modal_content()),\r\n\t\thtml.Div([\r\n\t\t\thtml.H1(id = 'list_of_meas_types', style = {'fontSize': '30', 'text-align': 'left', 'text-indent': '5em'}),\r\n\t\t\tdcc.Graph(id = 'live-plot-these-measurements', style={'height':'100%', 'width': '70%'})],\r\n\t\t\t\tstyle = {'position': 'absolute', 'width': '100%', 'height': '100%'}), #style = {'position': 'absolute', 'top': '30', 'left': '30', 'width': '1500' , 'height': '1200'}),\r\n\t\thtml.Div([\r\n\t\t\t#html.H2(children = 'Measurements', style={'fontSize': 25}),\r\n\t\t\thtml.Div(id = 'table_of_meas'),\r\n\t\t\t#html.Div(html.P('Started at: ' + str(start)), style={'fontSize': 14}),\r\n\t\t\t#html.Div(html.P('Stopped at: ' + str(stop)), style={'fontSize': 14}),\r\n\t\t\t#html.Div(html.P('Owner: ' + str(owner)), style={'fontSize': 14}),\r\n\t\t\t#html.Div(html.P('Metadata: ' + met_arr), style={'fontSize': 14}),\r\n\t\t\thtml.H3(children = 'Measurement info', style={'fontSize': 25}),\r\n\t\t\thtml.Div(id = 'dropdown', style = {'width': '100'}),\r\n\t\t\thtml.Div(id = 'meas_info'),\r\n\t\t\thtml.Div([html.P('Measurements: '), measurement_table()]),\r\n\t\t\thtml.Button(id=\"modal-select-measurements-open\", children=[\"Add measurements...\"]),\r\n\t\t\thtml.Div(children=[html.P('Available traces: '), html.Div(id='available-traces-container', children=[available_traces_table()])]),\r\n\t\t\t\t\t #dcc.Input(id='meas-id2', value = str(meas_ids), type = 'string')]), \r\n\t\t\t#html.Div([html.P('You chose following fits: '), dcc.Input(id='fit-id', value = str(fit_ids), type = 'string')]),\r\n\t\t\t],\r\n\t\t\t\t\t style={'position': 'absolute', 'top': '5%', 'left': '68%', 'width': '30%' , 'height': '80%',#'position': 'absolute', 'top': '80', 'left': '1500', 'width': '350' , 'height': '800',\r\n\t\t\t\t\t\t\t'padding': '0px 10px 15px 10px',\r\n\t\t\t\t\t\t\t 'marginLeft': 'auto', 'marginRight': 'auto', #'background': 'rgba(167, 232, 170, 1)',\r\n\t\t\t\t\t\t\t'boxShadow': '0px 0px 5px 5px rgba(204,204,204,0.4)'},#rgba(190, 230, 192, 1)'},\r\n\t\t ),\r\n\t\t dcc.Interval(\r\n\t\t\t\tid='interval-component',\r\n\t\t\t\tinterval=1*1000, # in milliseconds\r\n\t\t\t\tn_intervals=0\r\n\t\t\t),\r\n\t\t\t#html.Div([html.Div(id='my-div', style={'fontSize': 14}), dcc.Input(id='meas-id', value = str(meas_ids), type='string')])]),\r\n\t\thtml.Div(id='intermediate-value-meas', style={'display': 'none'}),\r\n\t\thtml.Div(id='intermediate-value-fit', style={'display': 'none'}),\r\n\t\t#dcc.Input(id='meas-id', value = str(meas_ids), style={}),\r\n\t\thtml.Div([html.H4(children='References', style={'fontSize': 25}), html.Div(id = 'table_of_references')], style = {'position': 'absolute', 'top': '1100', 'left': '50'})\r\n\t\t#(html.Div(a) for a in state.metadata.items())\r\n\t])\r\n\r\n@app.callback(\r\n\tOutput(component_id = 'meas_info', component_property = 'children'),\r\n\t[Input(component_id = 'my_dropdown', component_property='value')])\r\ndef write_meas_info(value):\r\n\twith db_session:\r\n\t\tif value == None: return \r\n\t\tstate = save_exdir.load_exdir(db.Data[int(value)].filename ,db)\r\n\t\tmet_arr = ''\r\n\t\tfor k in state.metadata:\r\n\t\t\tif k[0] != 'parameter values': met_arr += str(k[0]) + ' = ' + str(k[1]) + '\\n '\r\n\t\t#print(met_arr)\r\n\t\treturn (html.Div(html.P('Started at: ' + str(state.start)), style={'fontSize': 14}),\r\n\t\t\t\t\t\thtml.Div(html.P('Stopped at: ' + str(state.stop)), style={'fontSize': 14}),\r\n\t\t\t\t\t\thtml.Div(html.P('Owner: ' + str(state.owner)), style={'fontSize': 14}),\r\n\t\t\t\t\t\thtml.Div(html.P('Metadata: ' + met_arr), style={'fontSize': 14}))\r\n\t\t\t\t\t\r\n@app.callback(\r\n\tOutput(component_id = 'dropdown', component_property = 'children'),\r\n\t[Input(component_id = 'meas-id', component_property='derived_virtual_data')])\r\n\t#[Input(component_id = 'meas-id2', component_property='value')])\r\ndef create_dropdown(meas_ids):\r\n\tprint ('create_dropdown called with meas_ids', meas_ids)\r\n\tmeas_ids_list = pd.DataFrame(meas_ids, columns=['id', 'label'])['id'].tolist()\r\n\tprint ('returned list: ', meas_ids_list)\r\n\t#meas_ids_list = meas_ids.split(',')\r\n\treturn dcc.Dropdown(id = 'my_dropdown', options = [{'label': str(i), 'value': str(i)} for i in meas_ids_list])\r\n\r\n#@app.callback(\r\n\t#Output(component_id = 'table_of_meas', component_property = 'children'),\r\n\t#[Input(component_id = 'meas-id', component_property='value')])\r\n# def generate_table_of_meas(meas_ids):\r\n\t# with db_session:\r\n\t\t# ids = []\r\n\t\t# type_ref = []\r\n\t\t# meas_accordance_to_references = []\r\n\t\t# df = pd.DataFrame()\r\n\t\t# if meas_ids != '':\r\n\t\t\t# for i in string_to_list(meas_ids):\r\n\t\t\t\t# state = save_exdir.load_exdir(db.Data[int(i)].filename, db)\r\n\t\t\t\t# df = df.append({'id': state.id, 'owner': state.owner}, ignore_index=True)\r\n\t\t# return generate_table(df)\r\n\r\n@app.callback(\r\n\tOutput(component_id = 'table_of_references', component_property = 'children'),\r\n\t[Input(component_id = 'meas-id', component_property='derived_virtual_data')])\r\n\t#[Input(component_id = 'meas-id2', component_property='value')])\r\ndef generate_table_of_references(meas_ids):\r\n\tprint ('generate_table_of_references called with meas_ids', meas_ids)\r\n\tmeas_ids_list = pd.DataFrame(meas_ids, columns=['id', 'label'])['id'].tolist()\r\n\tprint ('returned list: ', meas_ids_list)\r\n\t#meas_ids_list = meas_ids.split(',')\r\n\twith db_session:\r\n\t\tmeas_accordance_to_references = []\r\n\t\tdf = pd.DataFrame()\r\n\t\tif meas_ids != '':\r\n\t\t\tfor i in meas_ids_list:\r\n\t\t\t\tids = []\r\n\t\t\t\ttype_ref = []\r\n\t\t\t\tstate_references = save_exdir.load_exdir(db.Data[int(i)].filename, db).references.items()\r\n\t\t\t\tfor index, type_r in state_references:\r\n\t\t\t\t\tids.append(index)\r\n\t\t\t\t\t#id_keys.update({index: i})\r\n\t\t\t\t\ttype_ref.append(type_r)\r\n\t\t\t\tquery_for_table = select(c for c in db.Data if (c.id in ids))\r\n\t\t\t\tdf_new = pd.DataFrame()\r\n\t\t\t\tdf_new = pd.DataFrame(list(data_to_dict(x) for x in list(query_for_table)))\r\n\t\t\t\tif not df_new.empty:\r\n\t\t\t\t\tdf_new = df_new.assign(reference_type=pd.Series(type_ref), ignore_index=True)\r\n\t\t\t\t\tdf_new = df_new.assign(measurement = pd.Series(np.full(len(ids), i)), ignore_index=True)\r\n\t\t\t\t\tdf = df.append(df_new, ignore_index=True)\r\n\t\t\t\t\t#for i in df_new['id']:\r\n\t\t\t\t\t\t#meas_accordance_to_references.append(id_keys.get(i))\r\n\t\t#if not df.empty:\r\n\t\t\t#df = df.assign(reference_type=pd.Series(type_ref), ignore_index=True)\r\n\t\t\t#df = df.assign(measurement = pd.Series(np.full(len(ids), i)), ignore_index=True)\r\n\t\t\t#df = df.assign(measurement = pd.Series(meas_accordance_to_references), ignore_index=True)\r\n\t\t#print(df)\r\n\t\treturn generate_table(df)\r\n@app.callback(\r\n\tOutput(component_id = 'list_of_meas_types', component_property = 'children'),\r\n\t[Input(component_id = 'meas-id', component_property='derived_virtual_data')])\r\n\t#[Input(component_id = 'meas-id2', component_property='value')])\r\ndef add_meas_type(meas_ids):\r\n\tprint ('add_meas_type called with meas_ids', meas_ids)\r\n\twith db_session:\r\n\t\tlist_of_states = pd.DataFrame(meas_ids, columns=['id', 'label'])['id'].tolist()\r\n\t\tprint ('returned list: ', list_of_states)\r\n\t\t#meas_ids_list = meas_ids.split(',')\r\n\t\tlist_of_meas_types = []\r\n\t\tfor i in list_of_states:\r\n\t\t\tif (save_exdir.load_exdir(db.Data[int(i)].filename, db)).measurement_type not in list_of_meas_types:\r\n\t\t\t\tif list_of_meas_types != []: list_of_meas_types.append(', ') \r\n\t\t\t\tlist_of_meas_types.append((save_exdir.load_exdir(db.Data[int(i)].filename)).measurement_type) \r\n\t\treturn list_of_meas_types\r\n\t\t\t\r\n@app.callback(\r\n\tOutput(component_id='intermediate-value-meas', component_property='children'),\r\n\t[Input(component_id = 'meas-id', component_property='derived_virtual_data')])\r\n\t#[Input(component_id = 'meas-id2', component_property='value')])\r\ndef add_meas(meas_ids):\r\n\tprint ('add_meas called with meas_ids', meas_ids)\r\n\tprint ('returned list: ', pd.DataFrame(meas_ids, columns=['id', 'label'])['id'].tolist())\r\n\treturn pd.DataFrame(meas_ids, columns=['id', 'label'])['id'].tolist()\r\n\treturn meas_ids.split(',')\r\n\t\r\n#@app.callback(\r\n#\tOutput(component_id='intermediate-value-fit', component_property='children'),\r\n#\t[Input(component_id='fit-id', component_property='value')])\r\n#def add_meas2(input_value):\r\n#\treturn string_to_list(str(input_value))\r\n\r\n# @app.callback(Output('live-plot-these-measurements', 'figure'),\r\n\t\t\t # [#Input('intermediate-value-fit', 'children'), \r\n\t\t\t # #Input('intermediate-value-meas', 'children')])\r\n\t\t\t # [Input(component_id=\"available-traces-table\", component_property=\"derived_virtual_data\"),\r\n\t\t\t # Input(component_id=\"available-traces-table\", component_property=\"derived_virtual_selected_rows\")])\r\n# #def plot_these_measurements(fit_ids_saved, meas_ids_saved): \r\n# def plot(all_traces, selected_trace_ids):\r\n\t# # load all measurments\r\n\t# all_traces = pd.DataFrame(all_traces, columns=['id', 'dataset', 'op', 'style', 'color', 'x-axis', 'y-axis', 'row', 'col'])\r\n\t# selected_traces = all_traces[selected_trace_ids]\r\n\t# measurements_to_load = selected_traces['id'].unique()\r\n\t# measurements = []\r\n\t# # load measurements\r\n\t# with db_session:\r\n\t\t# for measurement_id in measurements_to_load:\r\n\t\t\t# measurements[measurement_id] = save_exdir.load_exdir(db.Data[int(measurement_id)].filename, db)\r\n\t\r\n\t# layout = {}\r\n\t# figure = {}\r\n\t# layout['height'] = 1000\r\n\t# layout['annotations'] = []\r\n\t# layout['width'] = 1500\r\n\t# layout['showlegend'] = False\r\n\t# figure['data'] = []\r\n\t\r\n\t# # building subplot grid\r\n\t# num_rows = all_traces['row'].max()+1\r\n\t# num_cols = all_traces['col'].max()+1\r\n\t\r\n\t# layout\r\n\t\r\n\t\t# #print(measurement_to_plot)\r\n\t\t# #print(meas_ids_saved)\r\n\t\t# measurement_to_fit = {}\r\n\t\t# measurement_to_plot = {}\r\n\t\t# if meas_ids_saved != '':\r\n\t\t\t# for index, i in enumerate(meas_ids_saved):\r\n\t\t\t\t# state = save_exdir.load_exdir(db.Data[int(i)].filename, db)\r\n\t\t\t\t# measurement_to_plot.update({str(index):state})#({db.Data[int(i)].sample_name: state})\r\n\t\t# if fit_ids_saved != '':\r\n\t\t\t# for index, i in enumerate(fit_ids_saved):\r\n\t\t\t\t# state = save_exdir.load_exdir(db.Data[int(i)].filename, db)\r\n\t\t\t\t# measurement_to_fit.update({str(index): state})#({db.Data[int(i)].sample_name: state})\r\n\r\n\t\t# #print('I am working ', n_intervals)\r\n\t\t# layout['height'] = 1000\r\n\t\t# layout['annotations'] = []\r\n\t\t# layout['width'] = 1500\r\n\t\t# layout['showlegend'] = False\r\n\t\t# figure['data'] = []\r\n\t\t# if dim_2: type = 'heatmap' ### \r\n\t\t# else: type = 'scatter'\r\n\t\t# number_of_qubits = len(measurement_to_plot)\r\n\t\t# if number_of_qubits < 3: layout['height'] = 900\r\n\t\t# for qubit_index, qubit in enumerate(measurement_to_plot.keys()):\r\n\t\t\t# state = measurement_to_plot[qubit]\r\n\t\t\t# for i, key in enumerate(state.datasets.keys()):\r\n\t\t\t\t# number_of_datasets = len(state.datasets.keys())\r\n\t\t\t\t# #print(state.datasets[key].parameters[0].values, state.datasets[key].parameters[1].values, state.datasets[key].data)\r\n\t\t\t\t# if (number_of_datasets == 1) and (number_of_qubits < 3): layout['width'] = 1000\r\n\t\t\t\t# number = number_of_qubits*number_of_datasets\r\n\t\t\t\t# index = i + qubit_index\r\n\t\t\t\t# layout['xaxis' + str((index + 1)*2)] = {'anchor': 'x' + str((index + 1)*2), 'domain': [index/number, (index + 0.8)/number], \r\n\t\t\t\t\t\t\t\t\t# 'title': state.datasets[key].parameters[0].name + ', ' + state.datasets[key].parameters[0].unit} #RE\r\n\t\t\t\t# layout['yaxis' + str((index + 1)*2)] = {'anchor': 'x' + str((index + 1)*2), 'domain': [0, 0.45], \r\n\t\t\t\t\t\t\t\t\t# 'title': state.datasets[key].parameters[1].name + ', ' + state.datasets[key].parameters[1].unit if dim_2 else ''}\r\n\t\t\t\t# layout['xaxis' + str((index + 1)*2 + 1)] = {'anchor': 'x' + str((index + 1)*2 + 1), 'domain': [index/number, (index + 0.8)/number],\r\n\t\t\t\t\t\t\t\t\t# 'title': state.datasets[key].parameters[0].name + ', ' + state.datasets[key].parameters[0].unit} #IM\r\n\t\t\t\t# layout['yaxis' + str((index + 1)*2 + 1)] = {'anchor': 'x' + str((index + 1)*2 + 1), 'domain': [0.55, 1], \r\n\t\t\t\t\t\t\t\t\t# 'title': state.datasets[key].parameters[1].name + ', ' + state.datasets[key].parameters[1].unit if dim_2 else ''}\r\n\t\t\t\t# dataset = state.datasets[key]\r\n\t\t\t\t# figure['data'].append({'colorbar': {'len': 0.4,\r\n\t\t\t\t\t\t\t\t\t # 'thickness': 0.025,\r\n\t\t\t\t\t\t\t\t\t # 'thicknessmode': 'fraction',\r\n\t\t\t\t\t\t\t\t\t # 'x': (index + 0.8)/number,\r\n\t\t\t\t\t\t\t\t\t # 'y': 0.2},\r\n\t\t\t\t\t\t # 'type': type,\r\n\t\t\t\t\t\t # 'mode': 'markers' if not dim_2 else '',\r\n\t\t\t\t\t\t # 'uid': '',\r\n\t\t\t\t\t\t # 'xaxis': 'x' + str((index + 1)*2),\r\n\t\t\t\t\t\t # 'yaxis': 'y' + str((index + 1)*2),\r\n\t\t\t\t\t\t # 'x': np.memmap.tolist(np.real(state.datasets[key].parameters[0].values)),\r\n\t\t\t\t\t\t # 'y': np.memmap.tolist(np.imag(dataset.data)) if not dim_2 else np.memmap.tolist(np.real(state.datasets[key].parameters[1].values)),\r\n\t\t\t\t\t\t # 'z': np.memmap.tolist(np.imag(dataset.data))})\r\n\t\t\t\t# layout['annotations'].append({'font': {'size': 16},\r\n\t\t\t\t\t\t\t\t\t# 'showarrow': False,\r\n\t\t\t\t\t\t\t\t\t# 'text': str(state.id) + ': Re(' + key + ')',\r\n\t\t\t\t\t\t\t\t\t# 'x': (index + 0.4)/number,\r\n\t\t\t\t\t\t\t\t\t# 'xanchor': 'center',\r\n\t\t\t\t\t\t\t\t\t# 'xref': 'paper',\r\n\t\t\t\t\t\t\t\t\t# 'y': 1,\r\n\t\t\t\t\t\t\t\t\t# 'yanchor': 'bottom', 'yref': 'paper'})\r\n\t\t\t\t# figure['data'].append({'colorbar': {'len': 0.4,\r\n\t\t\t\t\t\t\t\t\t # 'thickness': 0.025,\r\n\t\t\t\t\t\t\t\t\t # 'thicknessmode': 'fraction',\r\n\t\t\t\t\t\t\t\t\t # 'x': (index + 0.8)/number,\r\n\t\t\t\t\t\t\t\t\t # 'y': 0.8},\r\n\t\t\t\t\t\t # 'type': type,\r\n\t\t\t\t\t\t # 'mode': 'markers' if not dim_2 else '',\r\n\t\t\t\t\t\t # 'uid': '',\r\n\t\t\t\t\t\t # 'xaxis': 'x' + str((index + 1)*2 + 1),\r\n\t\t\t\t\t\t # 'yaxis': 'y' + str((index + 1)*2 + 1),\r\n\t\t\t\t\t\t # 'x': np.memmap.tolist(np.real(state.datasets[key].parameters[0].values)),\r\n\t\t\t\t\t\t # 'y': np.memmap.tolist(np.real(dataset.data)) if not dim_2 else np.memmap.tolist(np.real(state.datasets[key].parameters[1].values)),\r\n\t\t\t\t\t\t # 'z': np.memmap.tolist(np.real(dataset.data))})\r\n\t\t\t\t# layout['annotations'].append({'font': {'size': 16},\r\n\t\t\t\t\t\t\t\t\t# 'showarrow': False,\r\n\t\t\t\t\t\t\t\t\t# 'text': str(state.id) + ': Im(' + key + ')',\r\n\t\t\t\t\t\t\t\t\t# 'x': (index + 0.4)/number,\r\n\t\t\t\t\t\t\t\t\t# 'xanchor': 'center',\r\n\t\t\t\t\t\t\t\t\t# 'xref': 'paper',\r\n\t\t\t\t\t\t\t\t\t# 'y': 0.45,\r\n\t\t\t\t\t\t\t\t\t# 'yanchor': 'bottom', 'yref': 'paper'}) \r\n\t\t\t\t# if (len(fit_ids_saved) > 0) and (qubit in measurement_to_fit.keys()):\r\n\t\t\t\t\t# fit_state = measurement_to_fit[qubit]\r\n\t\t\t\t\t# for key in fit_state.datasets.keys(): \r\n\t\t\t\t\t\t# figure['data'].append({'colorbar': {'len': 0.4,\r\n\t\t\t\t\t\t\t\t\t\t # 'thickness': 0.025,\r\n\t\t\t\t\t\t\t\t\t\t # 'thicknessmode': 'fraction',\r\n\t\t\t\t\t\t\t\t\t\t\t# 'x': (index + 0.8)/number,\r\n\t\t\t\t\t\t\t\t\t\t # 'y': 0.2},\r\n\t\t\t\t\t\t\t # 'type': type,\r\n\t\t\t\t\t\t\t # 'mode': 'lines' if not dim_2 else '',\r\n\t\t\t\t\t\t\t # 'uid': '',\r\n\t\t\t\t\t\t\t # 'xaxis': 'x' + str((index + 1)*2),\r\n\t\t\t\t\t\t\t # 'yaxis': 'y' + str((index + 1)*2),\r\n\t\t\t\t\t\t\t # 'x': np.memmap.tolist(np.real(fit_state.datasets[key].parameters[0].values)),\r\n\t\t\t\t\t\t\t # 'y': np.memmap.tolist(np.imag(dataset.data)) if not dim_2 else np.memmap.tolist(np.real(fit_state.datasets[key].parameters[1].values)),\r\n\t\t\t\t\t\t\t # 'z': np.memmap.tolist(np.imag(dataset.data))})\r\n\t\t\t\t\t\t# figure['data'].append({'colorbar': {'len': 0.4,\r\n\t\t\t\t\t\t\t\t\t\t # 'thickness': 0.025,\r\n\t\t\t\t\t\t\t\t\t\t # 'thicknessmode': 'fraction',\r\n\t\t\t\t\t\t\t\t\t\t # 'x': (index + 0.8)/number,\r\n\t\t\t\t\t\t\t\t\t\t # 'y': 0.8},\r\n\t\t\t\t\t\t\t # 'type': type,\r\n\t\t\t\t\t\t\t # 'mode': 'lines' if not dim_2 else '',\r\n\t\t\t\t\t\t\t # 'uid': '',\r\n\t\t\t\t\t\t\t # 'xaxis': 'x' + str((index + 1)*2 + 1),\r\n\t\t\t\t\t\t\t # 'yaxis': 'y' + str((index + 1)*2 + 1),\r\n\t\t\t\t\t\t\t # 'x': np.memmap.tolist(np.real(fit_state.datasets[key].parameters[0].values)),\r\n\t\t\t\t\t\t\t # 'y': np.memmap.tolist(np.real(dataset.data)) if not dim_2 else np.memmap.tolist(np.real(fit_state.datasets[key].parameters[1].values)),\r\n\t\t\t\t\t\t\t # 'z': np.memmap.tolist(np.real(dataset.data))})\r\n\t\t# figure['layout'] = layout\r\n\t\t# return figure \r\n\r\n@app.callback(Output('live-plot-these-measurements', 'figure'),\r\n\t\t\t\t[Input(component_id=\"available-traces-table\", component_property=\"derived_virtual_data\"), Input('interval-component', 'n_intervals')])\r\n\t\t\t\t#[Input(component_id=\"available-traces-container\", component_property=\"children\")])\r\n\t\t\t #[Input('intermediate-value-fit', 'children'), Input('intermediate-value-meas', 'children')])\r\ndef plot_these_measurements(info, n_intervals):#meas_ids_saved, fit_ids_saved): \r\n\tlist_of_files_to_load = []\r\n\tnum_of_cols = 0\r\n\tnum_of_rows = 0\r\n\tfor i in range(len(info)):\r\n\t\tif info[i]['id'] not in list_of_files_to_load:\r\n\t\t\tlist_of_files_to_load.append(info[i]['id'])\r\n\t\tif int(info[i]['col']) > num_of_cols: num_of_cols = int(info[i]['col'])\r\n\t\tif int(info[i]['row']) > num_of_rows: num_of_rows = int(info[i]['row'])\r\n\t#print('I will load this, axaxa')\r\n\t#print(list_of_files_to_load)\r\n\twith db_session:\r\n\t\tmeasurement_to_plot = {}\r\n\t\tif list_of_files_to_load != []:\r\n\t\t\tfor index in list_of_files_to_load:\r\n\t\t\t\tstate = save_exdir.load_exdir(db.Data[index].filename, db)\r\n\t\t\t\tif str(index) not in measurement_to_plot.keys():\r\n\t\t\t\t\tmeasurement_to_plot.update({str(index):state})#({db.Data[int(i)].sample_name: state})\r\n\t\tlayout = {}\r\n\t\t#layout['height'] = 1000\r\n\t\tlayout['annotations'] = []\r\n\t\t#layout['width'] = 1500\r\n\t\tlayout['showlegend'] = False\r\n\t\tfigure['data'] = []\r\n\t\tnumber_of_qubits = len(info)\r\n\t\t#if number_of_qubits < 3: layout['height'] = '80%'#900\r\n\t\t# print('Your params: ', num_of_cols, ', ', num_of_cols)\r\n\t\t# print(info)\r\n\t\tfor row in range(num_of_rows):\r\n\t\t\tfor column in range(num_of_cols):\r\n\t\t\t\t#layout['xaxis' + str(row*num_of_rows + column + 1)] = {'anchor': 'x' + str(row*num_of_rows + column + 1), 'domain': [column/num_of_cols, (column + 0.8)/num_of_cols],} \r\n\t\t\t\t#layout['yaxis' + str(row*num_of_rows + column + 1)] = {'anchor': 'x' + str(row*num_of_rows + column + 1), 'domain': [row/num_of_rows, (row + 0.8)/num_of_rows], }\r\n\t\t\t\tlayout['xaxis' + str(row + 1) + str(column + 1)] = {'anchor': 'y' + str(row + 1) + str(column + 1), 'domain': [(column+0.2)/num_of_cols, (column + 0.8)/num_of_cols],} \r\n\t\t\t\tlayout['yaxis' + str(row + 1) + str(column + 1)] = {'anchor': 'x' + str(row + 1) + str(column + 1), 'domain': [(row+0.2)/num_of_rows, (row + 0.8)/num_of_rows], }\r\n\t\t\t\tprint('xaxis', str(row + 1) + str(column + 1), ': ', (column+0.2)/num_of_cols, (column + 0.8)/num_of_cols)\r\n\t\t\t\tprint('yaxis', str(row + 1) + str(column + 1), ': ', (row+0.2)/num_of_rows, (row + 0.8)/num_of_rows)\r\n\t\t# {'id': 3, 'dataset': 'random', 'op': 'Im', 'style': '-', 'color': 'black', 'x-axis': 'randomize', 'y-axis': 'Voltage', 'row': 0, 'col': 0}\r\n\t\tif (num_of_cols > 0) and (num_of_rows > 0):\r\n\t\t\tfor i in range(len(info)):\r\n\t\t\t\tkey = info[i]['dataset']\r\n\t\t\t\tstate = measurement_to_plot[str(info[i]['id'])] \r\n\t\t\t\tdataset = state.datasets[key]\r\n\t\t\t\t#dataset_x = state.datasets[key].parameters[int(info[i]['x-axis'])]\r\n\t\t\t\t#dataset_y = state.datasets[key].parameters[int(info[i]['y-axis'])]\r\n\t\t\t\tx_axis_id = -1\r\n\t\t\t\ty_axis_id = -1\r\n\t\t\t\ttitle_x = key\r\n\t\t\t\ttitle_y = key\r\n\t\t\t\tfor itt, itt_param in enumerate(state.datasets[key].parameters):\r\n\t\t\t\t\tprint(itt, itt_param)\r\n\t\t\t\t\tif itt_param.name == info[i]['x-axis']: \r\n\t\t\t\t\t\tdataset_x = np.memmap.tolist(state.datasets[key].parameters[itt].values)\r\n\t\t\t\t\t\ttitle_x = state.datasets[key].parameters[itt].name + ', ' + state.datasets[key].parameters[itt].unit\r\n\t\t\t\t\t\tx_axis_id = itt\r\n\t\t\t\t\tif itt_param.name == info[i]['y-axis']: \r\n\t\t\t\t\t\tdataset_y = np.memmap.tolist(state.datasets[key].parameters[itt].values)\r\n\t\t\t\t\t\ttitle_y = state.datasets[key].parameters[itt].name + ', ' + state.datasets[key].parameters[itt].unit\r\n\t\t\t\t\t\ty_axis_id = itt\r\n\t\t\t\t#new_shape = [i for i in state.datasets[key].data.shape]\r\n\t\t\t\t#new_shape[]\r\n\t\t\t\tif info[i]['style'] != '2d':\r\n\t\t\t\t\t#new_axis_order = np.arange(len(state.datasets[key].data.shape))\r\n\t\t\t\t\tdata_axis_id = x_axis_id if not x_axis_id == -1 else y_axis_id\r\n\t\t\t\t\tnew_axis_order = [data_axis_id]+[i for i in range(len(state.datasets[key].data.shape)) if i != data_axis_id]\r\n\t\t\t\t\tprint ('1d:', state.datasets[key].data.shape, new_axis_order, (state.datasets[key].data.shape[data_axis_id], -1))\r\n\t\t\t\t\ttrace = np.reshape(np.transpose(state.datasets[key].data, tuple(new_axis_order)), (state.datasets[key].data.shape[data_axis_id]))\r\n\t\t\t\telse:\r\n\t\t\t\t\tnew_axis_order = [x_axis_id, y_axis_id] + [i for i in range(len(state.datasets[key].data.shape)) if i != x_axis_id and i != y_axis_id]\r\n\t\t\t\t\tprint ('2d:', state.datasets[key].data.shape, new_axis_order, (state.datasets[key].data.shape[x_axis_id], state.datasets[key].data.shape[y_axis_id], -1))\r\n\t\t\t\t\t#trace = np.reshape(state.datasets[key].data, (state.datasets[key].data.shape[x_axis_id], state.datasets[key].data.shape[y_axis_id], -1))[:,:,0]\r\n\t\t\t\t\ttrace = np.reshape(np.transpose(state.datasets[key].data, tuple(new_axis_order)), (state.datasets[key].data.shape[x_axis_id], state.datasets[key].data.shape[y_axis_id], -1))[:,:,0]\r\n\t\t\t\t\t#x = dataset_x\r\n\t\t\t\t\t#y = dataset_y\r\n\t\t\t\tif info[i]['op'] == 'Im': data_to_plot = np.imag(trace)\r\n\t\t\t\tif info[i]['op'] == 'Re': data_to_plot = np.real(trace)\r\n\t\t\t\tif info[i]['op'] == 'Abs': data_to_plot = np.abs(trace)\r\n\t\t\t\tif info[i]['op'] == 'Ph': data_to_plot = np.angle(trace)\r\n\t\t\t\tx = dataset_x if x_axis_id != -1 else data_to_plot\r\n\t\t\t\ty = dataset_y if y_axis_id != -1 else data_to_plot\r\n\t\t\t\tprint ('new trace shape:', trace.shape, 'x shape:',np.asarray(x).shape, 'y shape:', np.asarray(y).shape)\r\n\t\t\t\t\r\n\t\t\t\t#print(info[i]['y-axis'])\r\n\t\t\t\t#if info[i]['y-axis'] == 'data': \r\n\t\t\t\t#\tdataset.data = np.reshape(np.memmap.tolist(state.datasets[key].data), np.product(np.shape(state.datasets[key].data)))\r\n\t\t\t\t#\ttitle_y = key\r\n\t\t\t\t#elif np.shape(dataset.data)[0] != len(dataset_x):\r\n\t\t\t\t#\tdataset.data = np.transpose(dataset.data)\r\n\t\t\t\t#print(dataset_x)#, dataset_y[:10], np.shape(dataset.data))\r\n\t\t\t\trow = int(info[i]['row']) - 1\r\n\t\t\t\tcolumn = int(info[i]['col']) - 1\r\n\t\t\t\tif info[i]['style'] == '-': style = 'lines'\r\n\t\t\t\telif info[i]['style'] == 'o': style = 'markers'\r\n\t\t\t\telif info[i]['style'] == '.': style = 'markers'\r\n\t\t\t\telse: style = '2d'\r\n\r\n\t\t\t\tif (row >= 0) and (column >= 0):\r\n\t\t\t\t\t\r\n\t\t\t\t\tfigure['data'].append({'colorbar': {'len': 0.6/num_of_rows,\r\n\t\t\t\t\t\t\t\t\t 'thickness': 0.025/num_of_cols,\r\n\t\t\t\t\t\t\t\t\t 'thicknessmode': 'fraction',\r\n\t\t\t\t\t\t\t\t\t 'x': (column + 0.8)/num_of_cols,\r\n\t\t\t\t\t\t\t\t\t 'y': (row + 0.5)/num_of_rows},\r\n\t\t\t\t\t\t\t 'type': 'heatmap' if style == '2d' else 'scatter',\r\n\t\t\t\t\t\t\t 'colorscale': 'Viridis',\r\n\t\t\t\t\t\t\t 'mode': style,\r\n\t\t\t\t\t\t\t 'marker': {'size': 5 if info[i]['style'] == 'o' else 2},\r\n\t\t\t\t\t\t\t 'color': info[i]['color'],\r\n\t\t\t\t\t\t\t 'xaxis': 'x' + str(row + 1) + str(column + 1),\r\n\t\t\t\t\t\t\t 'yaxis': 'y' + str(row + 1) + str(column + 1),\r\n\t\t\t\t\t\t\t # 'x': np.memmap.tolist(dataset_x),\r\n\t\t\t\t\t\t\t # 'y': np.memmap.tolist(dataset_data) if info[i]['style'] != '2d' else np.memmap.tolist(dataset_y),\r\n\t\t\t\t\t\t\t # 'z': np.memmap.tolist(data_to_plot)})\r\n\t\t\t\t\t\t\t 'x': x,#np.memmap.tolist(np.real(state.datasets[key].parameters[0].values)),\r\n\t\t\t\t\t\t\t 'y': y, #np.memmap.tolist(data_to_plot) if info[i]['style'] != '2d' else np.memmap.tolist(np.real(state.datasets[key].parameters[1].values)),\r\n\t\t\t\t\t\t\t 'z': data_to_plot}) #np.memmap.tolist(data_to_plot)})\r\n\t\t\t\t\t# already_plotted = {}\r\n\t\t\t\t\t# for itteration in layout['annotations']:\r\n\t\t\t\t\t\t# if ((column + 0.5)/num_of_cols == itteration['x']) and ((row + 0.8)/num_of_rows == itteration['y']):\r\n\t\t\t\t\t\t\t# already_plotted = itteration\r\n\t\t\t\t\t# if already_plotted != {}:\r\n\t\t\t\t\tlayout['annotations'].append({'font': {'size': 16},\r\n\t\t\t\t\t\t\t\t'showarrow': False,\r\n\t\t\t\t\t\t\t\t'text': str(info[i]['id']) + ': ' + info[i]['op'] + '(' + key + ')',\r\n\t\t\t\t\t\t\t\t'x': (column + 0.5)/num_of_cols,\r\n\t\t\t\t\t\t\t\t'xanchor': 'center',\r\n\t\t\t\t\t\t\t\t'xref': 'paper',\r\n\t\t\t\t\t\t\t\t'y': (row + 0.8)/num_of_rows,\r\n\t\t\t\t\t\t\t\t'yanchor': 'bottom', 'yref': 'paper'}) \r\n\t\t\t\t\t# else:\r\n\t\t\t\t\t\t# layout['annotations'].append(already_plotted)\r\n\t\t\t\t\t\t# layout['annotations'][len(layout['annotations'])-1]['text'] += str(info[i]['id']) + ': ' + info[i]['op'] + '(' + key + ')',\r\n\t\t\t\t\tlayout['xaxis' + str(row + 1) + str(column + 1)].update({'title': title_x})\r\n\t\t\t\t\tlayout['yaxis' + str(row + 1) + str(column + 1)].update({'title': title_y})\r\n\t\t\t\t\t#layout['xaxis' + str(row + 1) + str(column + 1)].update({'title': state.datasets[key].parameters[0].name + ', ' + state.datasets[key].parameters[0].unit})\r\n\t\t\t\t\t#layout['yaxis' + str(row + 1) + str(column + 1)].update({'title': state.datasets[key].parameters[1].name + ', ' + state.datasets[key].parameters[1].unit})\r\n\t\t\t\t\t##layout['xaxis' + str(row + 1) + str(column + 1)].update({'titlefont': {'family': 'Cailbri', 'size': str(int(20 - max(num_of_cols, num_of_rows)))}})\r\n\t\t\t\t\t##layout['yaxis' + str(row + 1) + str(column + 1)].update({'titlefont': {'family': 'Cailbri', 'size': str(int(20 - max(num_of_cols, num_of_cols)))}})\r\n\t\t\t\t\tprint(row, column, 'x' + str(str(row + 1) + str(column + 1)), 'y' + str(str(row + 1) + str(column + 1)))\r\n\t\t# for qubit_index, qubit in enumerate(measurement_to_plot.keys()):\r\n\t\t\t# state = measurement_to_plot[qubit]\r\n\t\t\t# for i, key in enumerate(state.datasets.keys()):\r\n\t\t\t\t# number_of_datasets = len(state.datasets.keys())\r\n\t\t\t\t# #print(state.datasets[key].parameters[0].values, state.datasets[key].parameters[1].values, state.datasets[key].data)\r\n\t\t\t\t# if (number_of_datasets == 1) and (number_of_qubits < 3): layout['width'] = 1000\r\n\t\t\t\t# number = number_of_qubits*number_of_datasets\r\n\t\t\t\t# index = i + qubit_index\r\n\t\t\t\t# layout['xaxis' + str((index + 1)*2)] = {'anchor': 'x' + str((index + 1)*2), 'domain': [index/number, (index + 0.8)/number], \r\n\t\t\t\t\t\t\t\t\t# 'title': state.datasets[key].parameters[0].name + ', ' + state.datasets[key].parameters[0].unit} #RE\r\n\t\t\t\t# layout['yaxis' + str((index + 1)*2)] = {'anchor': 'x' + str((index + 1)*2), 'domain': [0, 0.45], \r\n\t\t\t\t\t\t\t\t\t# 'title': state.datasets[key].parameters[1].name + ', ' + state.datasets[key].parameters[1].unit if dim_2 else ''}\r\n\t\t\t\t# layout['xaxis' + str((index + 1)*2 + 1)] = {'anchor': 'x' + str((index + 1)*2 + 1), 'domain': [index/number, (index + 0.8)/number],\r\n\t\t\t\t\t\t\t\t\t# 'title': state.datasets[key].parameters[0].name + ', ' + state.datasets[key].parameters[0].unit} #IM\r\n\t\t\t\t# layout['yaxis' + str((index + 1)*2 + 1)] = {'anchor': 'x' + str((index + 1)*2 + 1), 'domain': [0.55, 1], \r\n\t\t\t\t\t\t\t\t\t# 'title': state.datasets[key].parameters[1].name + ', ' + state.datasets[key].parameters[1].unit if dim_2 else ''}\r\n\t\t\t\t# dataset = state.datasets[key]\r\n\t\t\t\t# figure['data'].append({'colorbar': {'len': 0.4,\r\n\t\t\t\t\t\t\t\t\t # 'thickness': 0.025,\r\n\t\t\t\t\t\t\t\t\t # 'thicknessmode': 'fraction',\r\n\t\t\t\t\t\t\t\t\t # 'x': (index + 0.8)/number,\r\n\t\t\t\t\t\t\t\t\t # 'y': 0.2},\r\n\t\t\t\t\t\t # 'type': type,\r\n\t\t\t\t\t\t # 'mode': 'markers' if not dim_2 else '',\r\n\t\t\t\t\t\t # 'uid': '',\r\n\t\t\t\t\t\t # 'xaxis': 'x' + str((index + 1)*2),\r\n\t\t\t\t\t\t # 'yaxis': 'y' + str((index + 1)*2),\r\n\t\t\t\t\t\t # 'x': np.memmap.tolist(np.real(state.datasets[key].parameters[0].values)),\r\n\t\t\t\t\t\t # 'y': np.memmap.tolist(np.imag(dataset.data)) if not dim_2 else np.memmap.tolist(np.real(state.datasets[key].parameters[1].values)),\r\n\t\t\t\t\t\t # 'z': np.memmap.tolist(np.imag(dataset.data))})\r\n\t\t\t\t# layout['annotations'].append({'font': {'size': 16},\r\n\t\t\t\t\t\t\t\t\t# 'showarrow': False,\r\n\t\t\t\t\t\t\t\t\t# 'text': str(state.id) + ': Re(' + key + ')',\r\n\t\t\t\t\t\t\t\t\t# 'x': (index + 0.4)/number,\r\n\t\t\t\t\t\t\t\t\t# 'xanchor': 'center',\r\n\t\t\t\t\t\t\t\t\t# 'xref': 'paper',\r\n\t\t\t\t\t\t\t\t\t# 'y': 1,\r\n\t\t\t\t\t\t\t\t\t# 'yanchor': 'bottom', 'yref': 'paper'})\r\n\t\t\t\t# figure['data'].append({'colorbar': {'len': 0.4,\r\n\t\t\t\t\t\t\t\t\t # 'thickness': 0.025,\r\n\t\t\t\t\t\t\t\t\t # 'thicknessmode': 'fraction',\r\n\t\t\t\t\t\t\t\t\t # 'x': (index + 0.8)/number,\r\n\t\t\t\t\t\t\t\t\t # 'y': 0.8},\r\n\t\t\t\t\t\t # 'type': type,\r\n\t\t\t\t\t\t # 'mode': 'markers' if not dim_2 else '',\r\n\t\t\t\t\t\t # 'uid': '',\r\n\t\t\t\t\t\t # 'xaxis': 'x' + str((index + 1)*2 + 1),\r\n\t\t\t\t\t\t # 'yaxis': 'y' + str((index + 1)*2 + 1),\r\n\t\t\t\t\t\t # 'x': np.memmap.tolist(np.real(state.datasets[key].parameters[0].values)),\r\n\t\t\t\t\t\t # 'y': np.memmap.tolist(np.real(dataset.data)) if not dim_2 else np.memmap.tolist(np.real(state.datasets[key].parameters[1].values)),\r\n\t\t\t\t\t\t # 'z': np.memmap.tolist(np.real(dataset.data))})\r\n\t\t\t\t# layout['annotations'].append({'font': {'size': 16},\r\n\t\t\t\t\t\t\t\t\t# 'showarrow': False,\r\n\t\t\t\t\t\t\t\t\t# 'text': str(state.id) + ': Im(' + key + ')',\r\n\t\t\t\t\t\t\t\t\t# 'x': (index + 0.4)/number,\r\n\t\t\t\t\t\t\t\t\t# 'xanchor': 'center',\r\n\t\t\t\t\t\t\t\t\t# 'xref': 'paper',\r\n\t\t\t\t\t\t\t\t\t# 'y': 0.45,\r\n\t\t\t\t\t\t\t\t\t# 'yanchor': 'bottom', 'yref': 'paper'}) \r\n\t\t\t\t# if (len(fit_ids_saved) > 0) and (qubit in measurement_to_fit.keys()):\r\n\t\t\t\t\t# fit_state = measurement_to_fit[qubit]\r\n\t\t\t\t\t# for key in fit_state.datasets.keys(): \r\n\t\t\t\t\t\t# figure['data'].append({'colorbar': {'len': 0.4,\r\n\t\t\t\t\t\t\t\t\t\t # 'thickness': 0.025,\r\n\t\t\t\t\t\t\t\t\t\t # 'thicknessmode': 'fraction',\r\n\t\t\t\t\t\t\t\t\t\t\t# 'x': (index + 0.8)/number,\r\n\t\t\t\t\t\t\t\t\t\t # 'y': 0.2},\r\n\t\t\t\t\t\t\t # 'type': type,\r\n\t\t\t\t\t\t\t # 'mode': 'lines' if not dim_2 else '',\r\n\t\t\t\t\t\t\t # 'uid': '',\r\n\t\t\t\t\t\t\t # 'xaxis': 'x' + str((index + 1)*2),\r\n\t\t\t\t\t\t\t # 'yaxis': 'y' + str((index + 1)*2),\r\n\t\t\t\t\t\t\t # 'x': np.memmap.tolist(np.real(fit_state.datasets[key].parameters[0].values)),\r\n\t\t\t\t\t\t\t # 'y': np.memmap.tolist(np.imag(dataset.data)) if not dim_2 else np.memmap.tolist(np.real(fit_state.datasets[key].parameters[1].values)),\r\n\t\t\t\t\t\t\t # 'z': np.memmap.tolist(np.imag(dataset.data))})\r\n\t\t\t\t\t\t# figure['data'].append({'colorbar': {'len': 0.4,\r\n\t\t\t\t\t\t\t\t\t\t # 'thickness': 0.025,\r\n\t\t\t\t\t\t\t\t\t\t # 'thicknessmode': 'fraction',\r\n\t\t\t\t\t\t\t\t\t\t # 'x': (index + 0.8)/number,\r\n\t\t\t\t\t\t\t\t\t\t # 'y': 0.8},\r\n\t\t\t\t\t\t\t # 'type': type,\r\n\t\t\t\t\t\t\t # 'mode': 'lines' if not dim_2 else '',\r\n\t\t\t\t\t\t\t # 'uid': '',\r\n\t\t\t\t\t\t\t # 'xaxis': 'x' + str((index + 1)*2 + 1),\r\n\t\t\t\t\t\t\t # 'yaxis': 'y' + str((index + 1)*2 + 1),\r\n\t\t\t\t\t\t\t # 'x': np.memmap.tolist(np.real(fit_state.datasets[key].parameters[0].values)),\r\n\t\t\t\t\t\t\t # 'y': np.memmap.tolist(np.real(dataset.data)) if not dim_2 else np.memmap.tolist(np.real(fit_state.datasets[key].parameters[1].values)),\r\n\t\t\t\t\t\t\t # 'z': np.memmap.tolist(np.real(dataset.data))})\r\n\t\tfigure['layout'] = layout\r\n\t\treturn figure\r\n\r\ndef query_results(query, max_rows=200):\r\n\ttry:\r\n\t\tdataframe = psql.read_sql(query, direct_db)\r\n\t\t\r\n#\t\trows = []\r\n#\t\tfor i in range(min(len(dataframe), max_rows)):\r\n#\t\t\tcells = []\r\n#\t\t\tfor col in dataframe.columns:\r\n#\t\t\t\tif col == 'id':\r\n#\t\t\t\t\tcell_className = 'id'\r\n#\t\t\t\t\tcell_contents = [dcc.Checklist(options=[{'label':str(dataframe.iloc[i][col]), 'value':str(dataframe.iloc[i][col])}], values=[])]\r\n#\t\t\t\telse:\r\n#\t\t\t\t\tcell_className = 'sql-result'\r\n#\t\t\t\t\tcell_contents = [str(dataframe.iloc[i][col])]\r\n#\t\t\t\tcell = html.Td(children=cell_contents, className=cell_className)\r\n#\t\t\t\tcells.append(cell)\r\n#\t\t\trows.append(html.Tr(children=cells))\r\n#\t\t\r\n# id='table',\r\n# columns=[{\"name\": i, \"id\": i} for i in df.columns],\r\n# data=df.to_dict(\"rows\"),\r\n#)\r\n\t\t\r\n\t\treturn [html.Div(className=\"query-results-scroll\", \r\n\t\t\tchildren=[dash_table.DataTable(\r\n\t\t\t# Header\r\n\t\t\t\tcolumns = [{\"name\":col, \"id\":col} for col in dataframe.columns],\r\n\t\t\t\tstyle_data_conditional=[{\"if\": {\"column_id\": 'id'},\r\n\t\t\t\t\t\t\t\t\t\t 'background-color': '#c0c0c0',\r\n\t\t\t\t\t\t\t\t\t\t 'color': 'white'}],\r\n\t\t\t\tdata=dataframe.to_dict('rows'),\r\n\t\t\t\trow_selectable='multi',\r\n\t\t\t\tselected_rows=[], ### TODO: add selected rows from meas-id row\r\n\t\t\t\tid=\"query-results-table\"\r\n\t\t\t)]\r\n\t\t)]\r\n\texcept Exception as e:\r\n\t\terror = str(e)\r\n\t\treturn html.Div(children=error)\r\n\r\ndef query_list():\r\n\tresult = html.Ul([html.Li(children=\"BOMZ\")])\r\n\treturn result\r\n\t\r\ndef modal_content():\r\n\treturn [html.Div(className=\"modal-content\",\r\n\t\t\t\tchildren=[\r\n\t\t\t\t\thtml.Div(className=\"modal-header\", children=[\r\n\t\t\t\t\t\thtml.Span(className=\"close\", children=\"×\", id=\"modal-select-measurements-close\"),\r\n\t\t\t\t\t\thtml.H1(children=\"Modal header\"), \r\n\t\t\t\t\t]),\r\n\t\t\t\t\thtml.Div(className=\"modal-body\", children = [\r\n\t\t\t\t\t\thtml.Div(className=\"modal-left\", children=[\r\n\t\t\t\t\t\t\tquery_list()\r\n\t\t\t\t\t\t]),\r\n\t\t\t\t\t\thtml.Div(className=\"modal-right\", children=[\r\n\t\t\t\t\t\t\thtml.Div(className=\"modal-right-content\", children=[\r\n\t\t\t\t\t\t\t\thtml.Div(children=[dcc.Textarea(id='query', value=default_query)]),\r\n\t\t\t\t\t\t\t\thtml.Div(children=[html.Button('Execute', id='execute'), \r\n\t\t\t\t\t\t\t\t\t\t\t\t html.Button('Select all', id='select-all'), \r\n\t\t\t\t\t\t\t\t\t\t\t\t html.Button('Deselect all', id='deselect-all')]),\r\n\t\t\t\t\t\t\t\thtml.Div(id='query-results', className='query-results', children=query_results(default_query)),\r\n\t\t\t\t\t\t\t]),\r\n\t\t\t\t\t\t])\r\n\t\t\t\t\t]),\r\n\t\t\t\t\t#html.Div(className=\"modal-footer\", children=[\"Modal footer\"])\r\n\t\t\t])]\r\n\r\n#n_clicks_registered = 0\r\n@app.callback(\r\n\tOutput(component_id='query-results', component_property='children'),\r\n\t[Input(component_id='execute', component_property='n_clicks')],\r\n\tstate=[State(component_id='query', component_property='value'),\r\n\t]\r\n)\r\ndef update_query_result(n_clicks, query):\r\n\t#global n_clicks_registered\r\n\t#if n_clicks> n_clicks_registered:\r\n\t#n_clicks_registered = n_clicks\r\n\treturn query_results(query)\r\n\r\n@app.callback(\r\n\tOutput(component_id='modal-select-measurements', component_property='style'),\r\n\t[Input(component_id='modal-select-measurements-open', component_property='n_clicks'),\r\n\t Input(component_id='modal-select-measurements-close', component_property='n_clicks')]\r\n)\r\ndef modal_select_measurements_open_close(n_clicks_open, n_clicks_close):\r\n\tif not n_clicks_open:\r\n\t\tn_clicks_open = 0\r\n\tif not n_clicks_close:\r\n\t\tn_clicks_close = 0\r\n\treturn {'display': 'block' if (n_clicks_open - n_clicks_close) % 2 else 'none'};\r\n\r\nif __name__ == '__main__':\r\n\tapp.layout = app_layout()\r\n\tapp.run_server(debug=False)\r\n","sub_path":"vplot.py","file_name":"vplot.py","file_ext":"py","file_size_in_byte":40443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"546977546","text":"from machine import Pin\nimport dht\nimport time\nimport network\nfrom umqtt import simple as mqtt\nimport _thread\nimport ujson\n\nALINK_PROP_SET_METHOD='thing.service.property.set'\nled=Pin(2,Pin.OUT,value=0)\nstate = 0\ndef threadPublish():\n while True:\n time.sleep(2)\n d.measure()\n print(d.humidity())\n print(d.temperature())\n send_mseg={\"params\":{\"Temperature\":d.temperature(),\"Humidity\":d.humidity()},\"method\":\"thing.service.property.set\"}\n client.publish(topic=\" \",msg=str(send_mseg),qos=1,retain=False)\n\n\ndef receiveMessage():\n while True:\n client.wait_msg()\n#接收信息。接收到的信息是json格式,要进行解析。\ndef recvMessage(topic,msg):\n parsed=ujson.loads(msg)\n str=parsed[\"params\"]\n print(str)\n print(type(parsed[\"params\"]))\n print(str.get(\"PowerSwitch\"))\n global state\n state=str.get(\"PowerSwitch\")\n if state == 1:\n led.value(1)\n print(\"led on!\") \n if state == 0:\n led.value(0)\n print(\"led off!\")\n \nd=dht.DHT11(Pin(23))\nwlan=network.WLAN(network.STA_IF) \nwlan.active(True)\nwlan.connect('','')#连接WIFI\nProductKey=''\nDeviceName=''\nDeviceSecret=''\nCLIENT_ID=''\nuser_name=''#用户名\nuser_password=''#用户密码\nSERVER= \"\"#阿里云物联网平台地址\nPORT=1883\nclient = mqtt.MQTTClient(client_id=CLIENT_ID, server=SERVER, port=PORT, user=user_name, password=user_password, keepalive=60)\nclient.connect()\nclient.set_callback(recvMessage)#设置回调函数\nclient.subscribe(\" \")#订阅主题\n\nwhile True:\n d.measure()\n print(d.humidity())\n print(d.temperature())\n send_mseg={\"params\":{\"Temperature\":d.temperature(),\"Humidity\":d.humidity()},\"method\":\"thing.service.property.set\"}\n client.publish(topic=\" \",msg=str(send_mseg),qos=1,retain=False)\n time.sleep(2)\n_thread.start_new_thread(receiveMessage,())#开启多线程\n","sub_path":"python/aliyun_demo.py","file_name":"aliyun_demo.py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"303003675","text":"import tensorflow as tf\nfrom tensorflow.python.ops import rnn, rnn_cell\nimport numpy as np\nimport sys\nimport argparse\nfrom utils import EEGDataLoader\nimport pdb\n\n\n# 0.00006 works fine for batch_size 64 and n_steps 512\nlearning_rate = 0.000009\ntraining_iters = 100000\nbatch_size = 256 \ndisplay_step = 8\ncheckpoint_step = 512 \ncross_val_step = 64 \n\nn_channels = 16\nn_hidden = 256 \nn_classes = 2\n\nn_steps = 256 \n\nx = tf.placeholder(\"float\", [batch_size, n_steps, n_channels])\ny = tf.placeholder(\"float\", [batch_size, n_classes])\n\nweights = {\n 'out': tf.Variable( tf.random_normal([2*n_hidden, n_classes]) ) \n}\n\nbiases = {\n 'out': tf.Variable( tf.random_normal([n_classes]) )\n}\n\ndef BiRNN(x, weights, biases):\n # shape of x will be (batch_size, n_steps, n_channels)\n # need to transform to (n_steps, batch_size, n_channels) to comply with tf bi_rnn\n x = tf.transpose(x, [1, 0, 2])\n x = tf.unpack(x, axis = 0)\n\n # Forward direction cell\n #with tf.variable_scope('forward'):\n lstm_fw_cell = rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1.0)\n # Backward direction cell\n #with tf.variable_scope('backward'):\n lstm_bw_cell = rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1.0)\n\n outputs, _, _ = rnn.bidirectional_rnn(lstm_fw_cell, lstm_bw_cell, x, dtype = tf.float32)\n #except Exception:\n # outputs = rnn.bidirectional_dynamic_rnn(lstm_fw_cell, lstm_bw_cell, x, dtype = tf.float32, time_major = True)\n return tf.matmul(outputs[-1], weights['out']) + biases['out']\n\npred = BiRNN(x, weights, biases)\n\ncost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y))\n\noptimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(cost)\n\n# Evaluate Model\n# argmax returns index of largest value, along given dimension\ncorrect_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n\ninit = tf.initialize_all_variables()\n\nwith tf.Session(config=tf.ConfigProto(intra_op_parallelism_threads=4)) as sess:\n parser = argparse.ArgumentParser()\n parser.add_argument('--sample', type = str, default=None)\n parser.add_argument('--init_from', type = str, default=None)\n parser.add_argument('--results', type = str, default=None)\n parser.add_argument('--trainf', type = str, default=None)\n parser.add_argument('--testf', type = str, default=None)\n parser.add_argument('--save', type = str, default=None)\n args = parser.parse_args()\n saver = tf.train.Saver()\n if args.sample:\n ckpt = tf.train.get_checkpoint_state(args.init_from)\n saver.restore(sess, ckpt.model_checkpoint_path)\n # load the data for the sequence to be sampled\n # iterate over all the possible windows and calculate the average accuracy\n sample_sequence = np.load(args.sample)['data'][()]\n n = sample_sequence.shape[0]\n # total sequence length - window size\n num_windows = n-n_steps\n # iterate over the windows and get classifications\n all_pred = np.zeros((num_windows/100+1, 2), dtype=float)\n for i in xrange(0,num_windows,100):\n batch_x = [sample_sequence[i:i+n_steps]]\n cur_pred = sess.run(pred, feed_dict = {x: batch_x})[0]\n if(i % 1000 == 0):\n print(str(cur_pred[0]) + ' ' + str(cur_pred[1]))\n all_pred[i/100] = cur_pred \n np.save(args.results, all_pred)\n \n else:\n if(args.init_from):\n ckpt = tf.train.get_checkpoint_state(args.init_from)\n saver.restore(sess, ckpt.model_checkpoint_path)\n stride = n_steps\n trainf = args.trainf \n testf = args.testf\n savef = args.save\n print(\"Loading data files\")\n dataloader = EEGDataLoader(trainf, testf, batch_size, n_steps, stride) \n sess.run(init)\n step = 1\n ma_acc = 0\n ma_loss = 0\n while step < training_iters:\n try:\n batch_x, batch_y = dataloader.next()\n except StopIteration:\n print('~~~~~~~~~~~~~~~~~~~~~')\n print('~~~~~~~~EPOCH~~~~~~~~')\n print('~~~~~~~~~~~~~~~~~~~~~')\n dataloader.next_epoch()\n batch_x, batch_y = dataloader.next()\n # Run optimization op (backprop)\n sess.run(optimizer, feed_dict={x: batch_x, y: batch_y})\n if step % display_step == 0:\n # Calculate batch accuracy\n acc = sess.run(accuracy, feed_dict={x: batch_x, y: batch_y})\n ma_acc = acc*0.25 + ma_acc*0.75\n\n # Calculate batch loss\n loss = sess.run(cost, feed_dict={x: batch_x, y: batch_y})\n ma_loss = loss*0.25 + ma_loss*0.75\n\n print(\"Iter \" + str(step*batch_size) + \", Minibatch Loss= \" + \\\n \"{:.6f}\".format(loss) + \", Training Accuracy= \" + \\\n \"{:.5f}\".format(acc) + \", MA Loss= \" + \\\n \"{:.6f}\".format(ma_loss) + \", MA Training= \" + \\\n \"{:.5f}\".format(ma_acc))\n \n if step % cross_val_step == 0:\n total_acc = 0\n test_steps = 40\n for i in range(test_steps):\n test_data, test_label = dataloader.next_test_batch()\n cross_acc = sess.run(accuracy, feed_dict={x: test_data, y: test_label})\n total_acc += cross_acc\n \n total_acc = total_acc / test_steps\n print(\"Cross Validation Acc= \" + \"{:.5f}\".format(total_acc))\n\n if step % checkpoint_step == 0:\n # Save a checkpoint\n saver.save(sess, savef + 'model.ckpt')\n\n step += 1\n print(\"Optimization Finished!\")\n","sub_path":"scripts/LSTMClassifier/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"511922537","text":"# Copyright 2022 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"net structure\"\"\"\nimport mindspore.nn as nn\nimport mindspore.ops as ops\nfrom mindspore.ops import operations as P\nfrom mindspore.ops import functional as F\nfrom mindspore.ops import composite as C\nfrom mindspore.parallel._utils import _get_device_num, _get_parallel_mode, _get_gradients_mean\nfrom mindspore.context import ParallelMode\nfrom mindspore.nn.wrap.grad_reducer import DistributedGradReducer\n\n\nclass SiameseRPN(nn.Cell):\n \"\"\"\n SiameseRPN Network.\n\n Args:\n groups (int): Size of one batch.\n k (int): Numbers of one point‘s anchors.\n s (int): Numbers of one anchor‘s parameters.\n\n Returns:\n coutputs tensor, routputs tensor.\n \"\"\"\n def __init__(self, groups=1, k=5, s=4, is_train=False, is_trackinit=False, is_track=False):\n super(SiameseRPN, self).__init__()\n self.groups = groups\n self.k = k\n self.s = s\n self.is_train = is_train\n self.is_trackinit = is_trackinit\n self.is_track = is_track\n self.expand_dims = ops.ExpandDims()\n self.featureExtract = nn.SequentialCell(\n [nn.Conv2d(3, 96, kernel_size=11, stride=2, pad_mode='valid', has_bias=True),\n nn.BatchNorm2d(96, use_batch_statistics=False),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=3, stride=2, pad_mode='valid'),\n nn.Conv2d(96, 256, kernel_size=5, pad_mode='valid', has_bias=True),\n nn.BatchNorm2d(256, use_batch_statistics=False),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=3, stride=2, pad_mode='valid'),\n nn.Conv2d(256, 384, kernel_size=3, pad_mode='valid', has_bias=True),\n nn.BatchNorm2d(384, use_batch_statistics=False),\n nn.ReLU(),\n nn.Conv2d(384, 384, kernel_size=3, pad_mode='valid', has_bias=True),\n nn.BatchNorm2d(384),\n nn.ReLU(),\n nn.Conv2d(384, 256, kernel_size=3, pad_mode='valid', has_bias=True),\n nn.BatchNorm2d(256)])\n self.conv1 = nn.Conv2d(256, 2 * self.k * 256, kernel_size=3, pad_mode='valid', has_bias=True)\n self.relu1 = nn.ReLU()\n self.conv2 = nn.Conv2d(256, 4 * self.k * 256, kernel_size=3, pad_mode='valid', has_bias=True)\n self.relu2 = nn.ReLU()\n self.conv3 = nn.Conv2d(256, 256, kernel_size=3, pad_mode='valid', has_bias=True)\n self.relu3 = nn.ReLU()\n self.conv4 = nn.Conv2d(256, 256, kernel_size=3, pad_mode='valid', has_bias=True)\n self.relu4 = nn.ReLU()\n\n self.op_split_input = ops.Split(axis=1, output_num=self.groups)\n self.op_split_krenal = ops.Split(axis=0, output_num=self.groups)\n self.op_concat = ops.Concat(axis=1)\n self.conv2d_cout = ops.Conv2D(out_channel=10, kernel_size=4)\n self.conv2d_rout = ops.Conv2D(out_channel=20, kernel_size=4)\n self.regress_adjust = nn.Conv2d(4 * self.k, 4 * self.k, 1, pad_mode='valid', has_bias=True)\n self.reshape = ops.Reshape()\n self.transpose = ops.Transpose()\n self.softmax = ops.Softmax(axis=2)\n self.print = ops.Print()\n\n def construct(self, template=None, detection=None, ckernal=None, rkernal=None):\n \"\"\" forward function \"\"\"\n if self.is_train is True and template is not None and detection is not None:\n template_feature = self.featureExtract(template)\n detection_feature = self.featureExtract(detection)\n\n ckernal = self.conv1(template_feature)\n ckernal = self.reshape(ckernal.view(self.groups, 2 * self.k, 256, 4, 4), (-1, 256, 4, 4))\n cinput = self.reshape(self.conv3(detection_feature), (1, -1, 20, 20))\n\n rkernal = self.conv2(template_feature)\n rkernal = self.reshape(rkernal.view(self.groups, 4 * self.k, 256, 4, 4), (-1, 256, 4, 4))\n rinput = self.reshape(self.conv4(detection_feature), (1, -1, 20, 20))\n c_features = self.op_split_input(cinput)\n c_weights = self.op_split_krenal(ckernal)\n r_features = self.op_split_input(rinput)\n r_weights = self.op_split_krenal(rkernal)\n coutputs = ()\n routputs = ()\n for i in range(self.groups):\n coutputs = coutputs + (self.conv2d_cout(c_features[i], c_weights[i]),)\n routputs = routputs + (self.conv2d_rout(r_features[i], r_weights[i]),)\n coutputs = self.op_concat(coutputs)\n routputs = self.op_concat(routputs)\n coutputs = self.reshape(coutputs, (self.groups, 10, 17, 17))\n routputs = self.reshape(routputs, (self.groups, 20, 17, 17))\n routputs = self.regress_adjust(routputs)\n out1, out2 = coutputs, routputs\n\n elif self.is_trackinit is True and template is not None:\n\n template = self.transpose(template, (2, 0, 1))\n template = self.expand_dims(template, 0)\n template_feature = self.featureExtract(template)\n\n ckernal = self.conv1(template_feature)\n ckernal = self.reshape(ckernal.view(self.groups, 2 * self.k, 256, 4, 4), (-1, 256, 4, 4))\n\n rkernal = self.conv2(template_feature)\n rkernal = self.reshape(rkernal.view(self.groups, 4 * self.k, 256, 4, 4), (-1, 256, 4, 4))\n out1, out2 = ckernal, rkernal\n elif self.is_track is True and detection is not None:\n detection = self.transpose(detection, (2, 0, 1))\n detection = self.expand_dims(detection, 0)\n detection_feature = self.featureExtract(detection)\n cinput = self.reshape(self.conv3(detection_feature), (1, -1, 20, 20))\n rinput = self.reshape(self.conv4(detection_feature), (1, -1, 20, 20))\n\n c_features = self.op_split_input(cinput)\n c_weights = self.op_split_krenal(ckernal)\n r_features = self.op_split_input(rinput)\n r_weights = self.op_split_krenal(rkernal)\n coutputs = ()\n routputs = ()\n for i in range(self.groups):\n coutputs = coutputs + (self.conv2d_cout(c_features[i], c_weights[i]),)\n routputs = routputs + (self.conv2d_rout(r_features[i], r_weights[i]),)\n coutputs = self.op_concat(coutputs)\n routputs = self.op_concat(routputs)\n coutputs = self.reshape(coutputs, (self.groups, 10, 17, 17))\n routputs = self.reshape(routputs, (self.groups, 20, 17, 17))\n routputs = self.regress_adjust(routputs)\n pred_score = self.transpose(\n self.reshape(coutputs, (-1, 2, 1445)), (0, 2, 1))\n pred_regression = self.transpose(\n self.reshape(routputs, (-1, 4, 1445)), (0, 2, 1))\n pred_score = self.softmax(pred_score)[0, :, 1]\n out1, out2 = pred_score, pred_regression\n else:\n out1, out2 = template, detection\n return out1, out2\n\n\n\nGRADIENT_CLIP_TYPE = 1\nGRADIENT_CLIP_VALUE = 5.0\nclip_grad = C.MultitypeFuncGraph(\"clip_grad\")\n\n\n@clip_grad.register(\"Number\", \"Number\", \"Tensor\")\ndef _clip_grad(clip_type, clip_value, grad):\n \"\"\"\n Clip gradients.\n\n Inputs:\n clip_type (int): The way to clip, 0 for 'value', 1 for 'norm'.\n clip_value (float): Specifies how much to clip.\n grad (tuple[Tensor]): Gradients.\n\n Outputs:\n tuple[Tensor], clipped gradients.\n \"\"\"\n if clip_type not in (0, 1):\n return grad\n dt = F.dtype(grad)\n if clip_type == 0:\n new_grad = C.clip_by_value(grad, F.cast(F.tuple_to_array((-clip_value,)), dt),\n F.cast(F.tuple_to_array((clip_value,)), dt))\n else:\n new_grad = nn.ClipByNorm()(grad, F.cast(F.tuple_to_array((clip_value,)), dt))\n return new_grad\n\n\nclass MyTrainOneStepCell(nn.Cell):\n \"\"\"MyTrainOneStepCell\"\"\"\n def __init__(self, network, optimizer, sens=1.0):\n super(MyTrainOneStepCell, self).__init__(auto_prefix=False)\n self.network = network\n self.network.set_train()\n\n self.network.set_grad()\n\n self.network.add_flags(defer_inline=True)\n self.weights = optimizer.parameters\n self.optimizer = optimizer\n self.grad = C.GradOperation(get_by_list=True, sens_param=True)\n\n self.sens = sens\n self.reducer_flag = False\n self.grad_reducer = F.identity\n self.parallel_mode = _get_parallel_mode()\n self.hyper_map = C.HyperMap()\n self.cast = ops.Cast()\n if self.parallel_mode in (ParallelMode.DATA_PARALLEL, ParallelMode.HYBRID_PARALLEL):\n self.reducer_flag = True\n if self.reducer_flag:\n mean = _get_gradients_mean()\n degree = _get_device_num()\n self.grad_reducer = DistributedGradReducer(self.weights, mean, degree)\n\n def construct(self, template, detection, target):\n weights = self.weights\n\n loss = self.network(template, detection, target)\n sens = P.Fill()(P.DType()(loss), P.Shape()(loss), self.sens)\n grads = self.grad(self.network, weights)(template, detection, target, sens)\n grads = self.hyper_map(F.partial(clip_grad, GRADIENT_CLIP_TYPE, GRADIENT_CLIP_VALUE), grads)\n if self.reducer_flag:\n grads = self.grad_reducer(grads)\n return F.depend(loss, self.optimizer(grads))\n\n\nclass BuildTrainNet(nn.Cell):\n def __init__(self, network, criterion):\n super(BuildTrainNet, self).__init__()\n self.network = network\n self.criterion = criterion\n\n def construct(self, template, detection, target):\n cout, rout = self.network(template=template, detection=detection, ckernal=detection, rkernal=detection)\n total_loss = self.criterion(cout, rout, target)\n return total_loss\n","sub_path":"research/cv/siamRPN/modelarts/net.py","file_name":"net.py","file_ext":"py","file_size_in_byte":10432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"118081861","text":"\"\"\"\n:mod:`ifrs17sim` CSM waterfall chars\n====================================\n\nDraw a graph of CSM amortization pattern.\n\"\"\"\nimport math\nimport collections\nimport pandas as pd\nimport seaborn as sns\nsns.set()\n\n\ndef draw_waterfall(df):\n \"\"\"Draw waterfall chart\"\"\"\n data = df.stack()\n bottom = df.cumsum(axis=1).shift(1, axis=1).fillna(0).stack()\n flowvals= set(df.iloc[:, 1:].stack())\n colors = CustomColorMap(flowvals)\n xlabel = [idx[1] + '(' + str(idx[0]) + ')' for idx in df.stack().index]\n ax = sns.barplot(data=data, bottom=bottom,\n palette=colors.get_palette(data))\n ax.set_xticklabels(labels=xlabel, rotation='vertical')\n ax.get_figure().tight_layout()\n return ax\n\n\nclass CustomColorMap:\n \"\"\"Change color by size and sign\"\"\"\n\n def __init__(self, data):\n\n self.pallen = 20\n self.palette = pal = sns.color_palette(\"RdBu\", self.pallen)\n\n self.posmax = max([val for val in data if val >= 0] or 0)\n self.negmin = min([val for val in data if val < 0] or 0)\n\n def get_index(self, value):\n\n if value > self.posmax:\n return self.pallen - 1\n elif value < self.negmin:\n return 0\n else:\n absmax = self.posmax if value >= 0 else abs(self.negmin)\n\n idx0 = self.pallen / 2\n return min(idx0 + math.floor(idx0 * value / absmax),\n self.pallen - 1)\n\n def get_palette(self, data):\n idxs = [int(self.get_index(val)) for val in data]\n return [self.palette[i] for i in idxs]\n\n\nif __name__ == '__main__':\n from lifelib.projects.ifrs17sim import ifrs17sim\n\n model = ifrs17sim.build(True)\n proj = model.OuterProjection[1]\n liab = [proj.InnerProjection[t].pv_NetLiabilityCashflow[t] for t in\n range(10)]\n\n proj.CSM_Unfloored(15)\n data = collections.OrderedDict()\n\n for cells in ['CSM_Unfloored',\n 'IntAccrCSM',\n 'AdjCSM_FulCashFlows',\n 'TransServices']:\n data[cells] = [proj.cells[cells](t) for t in range(15)]\n\n df = pd.DataFrame(data)\n df['TransServices'] = -1 * df['TransServices']\n\n draw_waterfall(df)","sub_path":"lifelib/projects/ifrs17sim/draw_charts.py","file_name":"draw_charts.py","file_ext":"py","file_size_in_byte":2184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"354686081","text":"import django.template as template\nfrom django.utils import timezone\nfrom datetime import datetime\nfrom dateutil import parser\nregister = template.Library()\n\n\n@register.filter\ndef timestamp(dt):\n return dt.isoformat().replace(':', '-').replace('.', '_').partition('+')[0]\n\n\n@register.filter\ndef timeformat(dt):\n from dateutil import parser\n if not isinstance(dt, datetime):\n dts = dt.partition('T')\n dts = dts[0] + dts[1] + dts[2].replace('-', ':')\n dt = parser.parse(dts, ignoretz=True)\n return datetime.strftime(dt, '%c')\n\n@register.filter\ndef to_aware(dt):\n if not isinstance(dt, datetime):\n dt = parser.parse(dt, ignoretz=True)\n\n if timezone.is_naive(dt):\n dt = dt.replace(tzinfo=timezone.utc)\n\n return dt\n","sub_path":"nglogman/templatetags/ngutils.py","file_name":"ngutils.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"77077110","text":"# controller_weather.py\nimport view_weather\nimport model_weather\n\ndef GetChoice():\n\tchoice=input(view_weather.StartView())\n\tif choice=='q' or choice== 'Q':\n\t\tview_weather.EndView()\n\telif choice=='n' or choice=='N':\n\t\tsearch=GetLocation()\n\telse:\n\t\tview_weather.InvalidEntry()\n\t\tGetChoice()\n\ndef GetLocation():\n\tlocation=input(view_weather.LocationView())\n\tsearch=model_weather.LocationSearch(location)\n\tif search[0]=='Success':\n\t\tview_weather.LocationSuccess([search[1],search[2]])\n\t\tweatherList=model_weather.WeatherDetails(search[1],search[2])\n\n\t\tdateList=list(set([item[0] for item in weatherList]))\n\t\tview_weather.GetDate(dateList)\n\t\tdateInput=int(input())\n\t\tif dateInput in range(len(dateList)):\n\t\t\twDate=dateList[dateInput]\n\t\telse:\n\t\t\tview_weather.InvalidEntry()\n\t\t\tGetChoice()\n\n\t\ttimeList=list(set([item[1] for item in weatherList]))\n\t\tview_weather.GetTime(timeList)\n\t\ttimeInput=int(input())\t\t\n\t\tif timeInput in range(len(timeList)):\n\t\t\twTime=timeList[timeInput]\n\t\telse:\n\t\t\tview_weather.InvalidEntry()\n\t\t\tGetChoice()\t\t\n\n\t\tfor item in weatherList:\n\t\t\tif item[0]==wDate and item[1]==wTime:\n\t\t\t\tview_weather.ViewWeather(item)\t\t\n\t\t\n\t\tk=input()\n\t\tif k=='Q' or k=='q':\n\t\t\tview_weather.EndView()\n\t\telse:\n\t\t\tGetChoice()\n\telse:\n\t\tview_weather.LocationFailed([search[0],search[1]])\n\t\tGetChoice()\n\nif __name__== '__main__':\n\tGetChoice()\t\n\n","sub_path":"Phase - 1/Part Time/Week 3/5. MVC/MVC Weather - Jithin/controller_weather.py","file_name":"controller_weather.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"21196051","text":"#! python3\nimport io\nimport pycurl\nimport re\nimport signal\nimport time\n\nrun = True\n\n# initialize global variables to prepare average calculus\nsum_rtt = 0\nsum_goodput = 0\n\n# keep track of the number of performed requests after successfully logging in\ncounter = 0\n\nc = pycurl.Curl()\n\n# silence pycurl - don't show body of the responses\nc.setopt(c.WRITEFUNCTION, lambda x: None)\n\n\ndef postFields(header):\n\n # function to extract the CSRF cookie from the header of the first RESPONSE and use it for the POST method\n username = 'testuser'\n password = '54321password12345'\n\n # search for CSRF cookie pattern in the header\n set_cookie = re.search('Set-Cookie: csrftoken=\\w+;', header).group()\n\n # extract the body of the CSRF cookie and for the POST data string\n csrf = re.findall('\\w+', set_cookie)[-1]\n post_data = 'csrfmiddlewaretoken={0}&username={1}&password={2}'.format(csrf, username, password)\n return post_data\n\n\ndef login():\n\n buf = io.BytesIO()\n loginUrl = 'http://authenticationtest.herokuapp.com/login/'\n\n # set options for pycurl session\n c.setopt(c.URL, loginUrl)\n\n # set USER AGENT\n c.setopt(c.USERAGENT,\n 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36')\n\n # allow cookie storage and passing between requests\n c.setopt(c.COOKIEFILE, '')\n\n # get header details\n c.setopt(c.VERBOSE, True)\n c.setopt(c.ENCODING, '')\n\n # store header\n c.setopt(c.HEADERFUNCTION, buf.write)\n\n # request the LOGIN page\n c.perform()\n if c.getinfo(c.RESPONSE_CODE) == 200:\n\n print(\"Login page received\")\n header = buf.getvalue().decode('UTF-8')\n\n # extract cookie from header and concatenate with the rest of the data\n data = postFields(header)\n\n # POST url\n postUrl = 'http://authenticationtest.herokuapp.com/login/ajax/'\n c.setopt(c.URL, postUrl)\n c.setopt(c.POST, 1)\n c.setopt(c.POSTFIELDS, data)\n c.setopt(c.POSTFIELDSIZE, len(data))\n c.perform()\n\n # fetch LOGGEDIN page\n c.setopt(c.POST, 0)\n c.setopt(c.COOKIE, 'using_auth=cookie;')\n c.setopt(c.FOLLOWLOCATION, False)\n c.setopt(c.URL, 'http://authenticationtest.herokuapp.com/loggedin/')\n c.perform()\n\n # fetch HOME page\n c.setopt(c.COOKIE, '')\n c.setopt(c.URL, 'http://authenticationtest.herokuapp.com/')\n c.perform()\n else:\n print(\"Could not fetch login page\")\n # return c.getinfo(c.RESPONSE_CODE)\n\n\ndef getMetrics(site):\n\n c.setopt(pycurl.URL, site)\n\n # don't show header details anymore\n c.setopt(c.VERBOSE, False)\n c.perform()\n\n # get round trip time in ms\n # each request/response pair incurs a separate round trip delay\n rtt = c.getinfo(c.TOTAL_TIME) * 1000\n\n # get goodput in bps\n goodput = c.getinfo(c.SPEED_DOWNLOAD) * 8\n\n return int(rtt), int(goodput)\n\n\ndef signalHandler(signal, frame):\n # called when Ctrl+C is pressed\n global run\n\n # calculate and print averages here\n print(\"The average round trip time is: {0} ms\").format(sum_rtt / counter)\n print(\"The average goodput is: {0} bps\").format(sum_goodput / counter)\n run = False\n\n\nif __name__ == \"__main__\":\n\n # login to the testing application\n login()\n site = 'http://authenticationtest.herokuapp.com/'\n signal.signal(signal.SIGINT, signalHandler)\n\n # perform HTTP request in loop, every 30 seconds, until exit command hits\n while run:\n try:\n # perform one HTTP request after login and return rtt and goodput\n rtt, goodput = getMetrics(site)\n\n # increment counter with 1 for each newly performed HTTP request\n counter += 1\n\n # increment the RTT and GOODPUT sums with the corresponding values from the last REQUEST/RESPONSE action\n sum_rtt += rtt\n sum_goodput += goodput\n print(\"For exchange number {0}, the roundtrip time is {1} ms and the goodput {2} bps\").format(counter, rtt,\n goodput)\n time.sleep(3)\n except:\n print(\"You pressed Ctrl+C\")\n break\n c.close()\n","sub_path":"login_pycurl.py","file_name":"login_pycurl.py","file_ext":"py","file_size_in_byte":4290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"160018494","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('main', '0004_auto_20161103_1343'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='ScriptAccess',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('script', models.ForeignKey(related_name='script_access_script_script', to='main.Script')),\n ('user', models.ForeignKey(related_name='script_access_user_custom_user', to=settings.AUTH_USER_MODEL)),\n ],\n ),\n ]\n","sub_path":"main/migrations/0005_scriptaccess.py","file_name":"0005_scriptaccess.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"644275986","text":"# Convert a folder of pdf files to txt using pdf2txt.py\n# Edited to run on Mac OS X\n\nimport subprocess, argparse\nfrom glob import glob\n\n# script takes -d argument for the pdf folder of your choice\nparser = argparse.ArgumentParser(description=\"This converts pdf files to txt, using pdfminer's pdf2txt.py script.\")\nparser.add_argument('-d','--directory', help='Absolute path to PDF folder in quotes',required=True)\nargs = parser.parse_args()\npdfpath = args.directory + '/*.pdf'\n\ndef pdfConvert():\n pdfScript = '/Library/Frameworks/Python.framework/Versions/2.7/bin/pdf2txt.py'\n pythonBin = '/Library/Frameworks/Python.framework/Versions/2.7/bin/python'\n pdfDir = glob(pdfpath)\n print(\"\\n\" + 'Preparing to convert pdf files to txt...' + '\\n')\n try:\n for f in pdfDir:\n p1 = subprocess.Popen([pythonBin, pdfScript, '-o', f.split('.pdf')[0] + '.txt', f])\n #p1 = subprocess.call(pythonBin + ' ' + pdfScript + ' -o ' + f.split('.pdf')[0] + '.txt' + ' ' + f,shell=True)\n pdfName = f.split(args.directory)[1]\n print('Processing ' + pdfName + '...')\n output = p1.communicate()\n print('Conversion to .txt complete!' + \"\\n\")\n except:\n print('Error: Converting pdf to text failed, check your conversion code.')\n print('PDF conversion in ' + str(args.directory) + ' completed' + \"\\n\\n\")\n\npdfConvert()\n","sub_path":"pdf_folder_to_txt.py","file_name":"pdf_folder_to_txt.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"336270239","text":"import lasagne as lsg\nimport theano\nimport theano.tensor as T\nimport numpy as np\nimport os\n\n\n# Class describing our neural networkpip install Lasagne==0.1\nclass NeuralNetwork:\n # Placeholders for training data\n # Empty 4 dimensional array of images\n input_var = T.tensor4('inputs')\n # One dimensional vector of labels\n target_var = T.ivector('targets')\n # Number of nodes\n num_of_nodes = 80\n # Training function\n training_fn = None\n # Neural network\n network = None\n # Accuracy function\n acc_fn = None\n # Prediction function\n pr_fn = None\n\n def __init__(self, num_of_nodes, learning_rate=0.1, momentum=0.9):\n self.num_of_nodes = num_of_nodes\n # We build our neural network\n self.network = self.build_neural_network(self.input_var, num_of_nodes)\n # Define training function\n self.training_fn = self.train_function(learning_rate, momentum)\n # Define accuracy function\n self.acc_fn = self.nn_accuracy()\n # Define prediction function\n self.pr_fn = self.prediction_fn()\n\n # Our neural network with 2 hidden layers that takes vector of images as an input\n @staticmethod\n def build_neural_network(input_variables=input_var, num_of_nodes=21):\n # Input layer that takes input data. One index in vector determines one matrix of image\n layer_input = lsg.layers.InputLayer(shape=(None, 1, 28, 28), input_var=input_variables)\n # We drop 50% of wages to avoid overfitting\n layer_input_drop = lsg.layers.DropoutLayer(layer_input, p=0.50)\n\n # First hidden layer. 800 nodes. Takes Input layer as a input. rectify function.\n layer_hidden_1 = lsg.layers.DenseLayer(layer_input_drop,\n # Number of nodes\n num_units=num_of_nodes,\n # Activation function - Tanh (S-shape from -1 to 1)\n nonlinearity=lsg.nonlinearities.tanh,\n # Wages for sigmoid. Glorot/Xavier initialization with Uniform distribution\n W=lsg.init.GlorotUniform(gain=1.0))\n layer_hidden_1_drop = lsg.layers.DropoutLayer(layer_hidden_1, p=0.50)\n\n layer_hidden_2 = lsg.layers.DenseLayer(layer_hidden_1_drop,\n num_units=num_of_nodes,\n nonlinearity=lsg.nonlinearities.tanh,\n W=lsg.init.GlorotUniform(gain=1.0))\n layer_hidden_2_drop = lsg.layers.DropoutLayer(layer_hidden_2, p=0.50)\n\n layer_out = lsg.layers.DenseLayer(layer_hidden_2_drop,\n num_units=10,\n # Softmax activation function\n nonlinearity=lsg.nonlinearities.softmax,\n W=lsg.init.GlorotUniform(gain=1.0))\n\n return layer_out\n\n # Function to download and load MNIST sources\n @staticmethod\n def load_database():\n # Download from website\n def download(filename, source='http://yann.lecun.com/exdb/mnist/'):\n print(\"Downloading \", filename)\n import urllib.request as urllib\n urllib.urlretrieve(source + filename, filename)\n\n import gzip\n\n # Load mnist images to vector of matrix 28x28\n def load_mnist_images(filename):\n if not os.path.exists(filename):\n download(filename)\n with gzip.open(filename, 'rb') as f:\n data = np.frombuffer(f.read(), np.uint8, offset=16)\n # -1 <- Declare size of vector as big as number of images, 1 <- Monochromatic, 28x28 size of matrix\n data = data.reshape(-1, 1, 28, 28)\n # Convert binary to float from 0 to 1\n return data / np.float32(256)\n\n # load mnist labels of images\n def load_mnist_labels(filename):\n if not os.path.exists(filename):\n download(filename)\n with gzip.open(filename, 'rb') as f:\n data = np.frombuffer(f.read(), np.uint8, offset=8)\n return data\n\n # Training data\n X_train = load_mnist_images('train-images-idx3-ubyte.gz')\n Y_train = load_mnist_labels('train-labels-idx1-ubyte.gz')\n\n # Testing data\n X_test = load_mnist_images('t10k-images-idx3-ubyte.gz')\n Y_test = load_mnist_labels('t10k-labels-idx1-ubyte.gz')\n\n return X_train, Y_train, X_test, Y_test\n\n # Declaring error and training functions\n def train_function(self, learning_rate_val=0.1, momentum_val=0.9):\n # Compute an error function\n # Get prediction for current training set\n prediction = lsg.layers.get_output(self.network)\n # Computes the categorical cross-entropy between predictions and targets\n loss = lsg.objectives.categorical_crossentropy(prediction, self.target_var)\n # Aggregate it into scalar\n loss = loss.mean()\n\n # Getting all params\n params = lsg.layers.get_all_params(self.network, trainable=True)\n # Setting Nesterov accelerated gradient descending update function\n updates = lsg.updates.nesterov_momentum(loss, params, learning_rate=learning_rate_val, momentum=momentum_val)\n\n # Declaring updating function\n train_fn = theano.function([self.input_var, self.target_var], loss, updates=updates)\n\n return train_fn\n\n # Training neural network\n def nn_training(self, x_train, y_train, X_test, Y_test, epos):\n from timeit import default_timer as timer\n\n time_start = timer()\n # Neural Network learning process\n for step in range(epos):\n train_err = self.training_fn(x_train, y_train)\n if step % 10 == 0:\n print(\"Current step is \" + str(step))\n print(\"Train-error: \" + str(train_err) + \" Train-acc: \" + str(self.acc_fn(X_test, Y_test) * 100) + \"%\\n\")\n time_end = timer()\n\n return time_end, time_start\n\n # Function to calculate accuracy of neural network\n def nn_accuracy(self):\n # Get prediction\n test_prediction = lsg.layers.get_output(self.network, deterministic=True)\n # Function to count accuracy of our network\n test_acc = T.mean(T.eq(T.argmax(test_prediction, axis=1), self.target_var), dtype=theano.config.floatX)\n\n # Assign function\n return theano.function([self.input_var, self.target_var], test_acc)\n\n # Function to predict the number by neural network\n def prediction_fn(self):\n prediction = lsg.layers.get_output(self.network)\n return theano.function([self.input_var], prediction)","sub_path":"Neural_Network.py","file_name":"Neural_Network.py","file_ext":"py","file_size_in_byte":6863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"102618152","text":"import os\nimport time\nimport urllib.request, json\nimport pandas as pd\nfrom selenium import webdriver\nfrom webdriver_manager.chrome import ChromeDriverManager\n\ncurpath = os.path.dirname(os.path.abspath(\"__file__\"))\ncurrent_file = 'tcf_top_sites.csv'\n\nall_sites = pd.read_csv(curpath + '/' + current_file, sep=\",\")\ntcfv1 = []\ntcfv2 = []\ntcfv2_cmp = []\n\nwith urllib.request.urlopen('https://cmplist.consensu.org/v2/cmp-list.json') as url:\n cmpjson = json.loads(url.read().decode())\n\nfor index, row in all_sites.head(100).iterrows():\n chrome_path = r'/usr/local/bin/chromedriver' #path from 'which chromedriver'\n #driver = webdriver.Chrome(executable_path=chrome_path)\n driver = webdriver.Chrome(ChromeDriverManager().install())\n print('checking ' + row['url'])\n driver.get(row['url'])\n time.sleep(1)\n tcfv1.append(driver.execute_script(\"return (typeof window.__cmp !== \\\"undefined\\\")\"))\n tcfapi_exists = driver.execute_script(\"return (typeof window.__tcfapi !== \\\"undefined\\\")\")\n tcfv2.append(tcfapi_exists)\n cmpname = ''\n if(tcfapi_exists):\n driver.execute_script(\n \" (window.__tcfapi('getTCData', 2, (tcData, success) => {window.tcfv2_cmp_id = (tcData.cmpId);}, [501]))\")\n time.sleep(1)\n cmpid = driver.execute_script(\"return window.tcfv2_cmp_id\")\n if(cmpid is not None):\n cmpname = cmpjson['cmps'][str(cmpid)]['name']\n tcfv2_cmp.append(cmpname)\n driver.close()\n\nall_sites['tcfv1'] = pd.Series(tcfv1)\nall_sites['tcfv2'] = pd.Series(tcfv2)\nall_sites['tcfv2_cmp'] = pd.Series(tcfv2_cmp)\n\nall_sites.to_csv(curpath + '/' + current_file,index=False)\n","sub_path":"cmp_audit.py","file_name":"cmp_audit.py","file_ext":"py","file_size_in_byte":1636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"558836943","text":"# -*- coding: utf-8 -*-\nfrom os import remove, path\nfrom random import randint\nfrom datetime import date\n\nfrom factory import fuzzy, DjangoModelFactory\nfrom PIL import Image\n\nfrom django.core.files import File\nfrom django.test import TestCase\nfrom django.conf import settings\n\nfrom apps.hello.models import Profile, Request\n\n\nclass ProfileFactory(DjangoModelFactory):\n class Meta:\n model = Profile\n birthday = fuzzy.FuzzyDate(date(1940, 1, 1))\n\n\nclass RequestFactory(DjangoModelFactory):\n class Meta:\n model = Request\n datetime = fuzzy.FuzzyDate(date.today())\n\n\nclass TestProfile(TestCase):\n \"\"\"Test model Profile\"\"\"\n def test_unicode_string_representation(self):\n \"\"\"Test method __unicode__\"\"\"\n profile = Profile(first_name=u'Роман', last_name=u'Дузь')\n self.assertEqual(unicode(profile), u'Дузь Роман')\n\n def test_fields_in_model(self):\n \"\"\"Test all fields are present in the model\"\"\"\n fields = {k.name: k.get_internal_type() for k in Profile._meta.fields}\n self.assertDictEqual(fields, {\n u'id': u'AutoField',\n 'first_name': u'CharField',\n 'biography': u'TextField',\n 'last_name': u'CharField',\n 'birthday': u'DateField',\n 'contacts': u'TextField',\n 'jabber': u'CharField',\n 'email': u'CharField',\n 'skype': u'CharField',\n 'photo': u'FileField'\n })\n\n\nclass TestProfilePhotoField(TestCase):\n \"\"\"TestClass for testing profile field \"photo\" \"\"\"\n\n def calculate_new_size(self, input_size):\n \"\"\"Calculate the dimensions of the resized image\n Args:\n input_size (tuple): Width and height of resized image.\n \"\"\"\n size = (200, 200)\n x, y = input_size\n\n if x > size[0]:\n y = int(max(y * size[0] / x, 1))\n x = int(size[0])\n if y > size[1]:\n x = int(max(x * size[1] / y, 1))\n y = int(size[1])\n size = x, y\n return size\n\n def create_profile_with_photo(self):\n min_rand_int = 1\n max_rand_int = 2000\n tmp_image_size = (randint(min_rand_int, max_rand_int),\n randint(min_rand_int, max_rand_int))\n self.input_image_size = tmp_image_size\n self.img_tmp_patn = \"\".join([settings.STATICFILES_DIRS[0],\n '/img/test_img_1.png'])\n\n image = Image.new('L', size=self.input_image_size)\n image.save(self.img_tmp_patn, 'PNG')\n self.expect_size = self.calculate_new_size(image.size)\n with open(self.img_tmp_patn) as f:\n profile = ProfileFactory.create(photo=File(f))\n return profile\n\n def setUp(self):\n Profile.objects.all().delete()\n self.profile = self.create_profile_with_photo()\n self.photo = self.profile.photo\n\n def tearDown(self):\n remove(self.photo.path)\n remove(self.img_tmp_patn)\n\n def test_image_resizing_process_if_photo_existing_in_profile(self):\n \"\"\"If there is a photo in profile, resizing process should't run\"\"\"\n person = Profile.objects.last()\n photo_changed_time = path.getmtime(person.photo.path)\n person.save()\n self.assertEqual(photo_changed_time, path.getmtime(person.photo.path),\n 'Resizing the image has been performed.')\n\n def test_image_resizing_process_for_new_profile(self):\n \"\"\"Process of resizing photos must be started only for new profile\"\"\"\n profile_photo_size = Image.open(self.profile.photo.path).size\n message = 'Photo should be scaled to 200x200, maintaining ' \\\n 'aspect ratio, before saving. ' \\\n 'Input: {0}, Expected: {1}, Returned: {2}'\n self.assertTupleEqual(\n self.expect_size,\n profile_photo_size,\n message.format(\n self.input_image_size, self.expect_size, profile_photo_size))\n\n\nclass TestRequest(TestCase):\n \"\"\"Test model Request\"\"\"\n def test_unicode_string_representation(self):\n \"\"\"Test method __unicode__\"\"\"\n request = Request(url='/', datetime='03/Oct/2018 13:19:45')\n self.assertEqual(unicode(request), u'03/Oct/2018 13:19:45 /')\n\n def test_fields_in_model(self):\n \"\"\"Test all fields are represented in the model\"\"\"\n fields = {k.name: k.get_internal_type() for k in Request._meta.fields}\n self.assertDictEqual(fields, {\n u'id': u'AutoField',\n 'datetime': u'DateTimeField',\n 'url': u'CharField',\n 'status_code': u'IntegerField',\n 'method': u'CharField',\n 'viewed': u'BooleanField'\n })\n\n def test_get_unviewed_count(self):\n \"\"\"Model can return the count of unviewed objects\"\"\"\n for _ in range(7):\n RequestFactory.create(status_code=200)\n self.assertEqual(Request.get_unviewed_count(), 7)\n","sub_path":"apps/hello/tests/tests_model.py","file_name":"tests_model.py","file_ext":"py","file_size_in_byte":5086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"360876376","text":"from __future__ import annotations\n\nimport inspect\nimport warnings\nfrom functools import partialmethod\nfrom typing import get_args, get_type_hints, Optional, TYPE_CHECKING\n\nfrom pyiron_contrib.workflow.channels import InputData, OutputData, NotData\nfrom pyiron_contrib.workflow.has_channel import HasChannel\nfrom pyiron_contrib.workflow.io import Inputs, Outputs, Signals\nfrom pyiron_contrib.workflow.node import Node\nfrom pyiron_contrib.workflow.output_parser import ParseOutput\nfrom pyiron_contrib.workflow.util import SeabornColors\n\nif TYPE_CHECKING:\n from pyiron_contrib.workflow.composite import Composite\n from pyiron_contrib.workflow.workflow import Workflow\n\n\nclass Function(Node):\n \"\"\"\n Function nodes wrap an arbitrary python function.\n Node IO, including type hints, is generated automatically from the provided\n function.\n Input data for the wrapped function can be provided as any valid combination of\n `*arg` and `**kwarg` at both initialization and on calling the node.\n\n On running, the function node executes this wrapped function with its current input\n and uses the results to populate the node output.\n\n Function nodes must be instantiated with a callable to deterimine their function,\n and a string to name each returned value of that callable. (If you really want to\n return a tuple, just have multiple return values but only one output label -- there\n is currently no way to mix-and-match, i.e. to have multiple return values at least\n one of which is a tuple.)\n\n The node label (unless otherwise provided), IO channel names, IO types, and input\n defaults for the node are produced _automatically_ from introspection of the node\n function.\n Explicit output labels can be provided to modify the number of return values (from\n $N$ to 1 in case you _want_ a tuple returned) and to dodge constraints on the\n automatic scraping routine (namely, that there be _at most_ one `return`\n expression).\n (Additional properties like storage priority and ontological type are forthcoming\n as kwarg dictionaries with keys corresponding to the channel labels (i.e. the node\n arguments of the node function, or the output labels provided).)\n\n Actual function node instances can either be instances of the base node class, in\n which case the callable node function *must* be provided OR they can be instances\n of children of this class.\n Those children may define some or all of the node behaviour at the class level, and\n modify their signature accordingly so this is not available for alteration by the\n user, e.g. the node function and output labels may be hard-wired.\n\n Although not strictly enforced, it is a best-practice that where possible, function\n nodes should be both functional (always returning the same output given the same\n input) and idempotent (not modifying input data in-place, but creating copies where\n necessary and returning new objects as output).\n Further, functions with multiple return branches that return different types or\n numbers of return values may or may not work smoothly, depending on the details.\n\n By default, function nodes will attempt to run whenever one or more inputs is\n updated, and will attempt to update on initialization (after setting _all_ initial\n input values).\n\n Output is updated in the `process_run_result` inside the parent class `finish_run`\n call, such that output data gets pushed after the node stops running but before\n then `ran` signal fires: run, process and push result, ran.\n\n After a node is instantiated, its input can be updated as `*args` and/or `**kwargs`\n on call.\n This invokes an `update()` call, which can in turn invoke `run()` if\n `run_on_updates` is set to `True`.\n `run()` returns the output of the executed function, or a futures object if the\n node is set to use an executor.\n Calling the node or executing an `update()` returns the same thing as running, if\n the node is run, or `None` if it is not set to run on updates or not ready to run.\n\n Args:\n node_function (callable): The function determining the behaviour of the node.\n label (str): The node's label. (Defaults to the node function's name.)\n run_on_updates (bool): Whether to run when you are updated and all your\n input is ready. (Default is True).\n update_on_instantiation (bool): Whether to force an update at the end of\n instantiation. (Default is True.)\n channels_requiring_update_after_run (list[str]): All the input channels named\n here will be set to `wait_for_update()` at the end of each node run, such\n that they are not `ready` again until they have had their `.update` method\n called. This can be used to create sets of input data _all_ of which must\n be updated before the node is ready to produce output again. (Default is\n None, which makes the list empty.)\n output_labels (Optional[str | list[str] | tuple[str]]): A name for each return\n value of the node function OR a single label. (Default is None, which\n scrapes output labels automatically from the source code of the wrapped\n function.) This can be useful when returned values are not well named, e.g.\n to make the output channel dot-accessible if it would otherwise have a label\n that requires item-string-based access. Additionally, specifying a _single_\n label for a wrapped function that returns a tuple of values ensures that a\n _single_ output channel (holding the tuple) is created, instead of one\n channel for each return value. The default approach of extracting labels\n from the function source code also requires that the function body contain\n _at most_ one `return` expression, so providing explicit labels can be used\n to circumvent this (at your own risk).\n **kwargs: Any additional keyword arguments whose keyword matches the label of an\n input channel will have their value assigned to that channel.\n\n Attributes:\n inputs (Inputs): A collection of input data channels.\n outputs (Outputs): A collection of output data channels.\n signals (Signals): A holder for input and output collections of signal channels.\n ready (bool): All input reports ready, not running or failed.\n running (bool): Currently running.\n failed (bool): An exception was thrown when executing the node function.\n connected (bool): Any IO channel has at least one connection.\n fully_connected (bool): Every IO channel has at least one connection.\n\n Methods:\n update: If `run_on_updates` is true and all your input is ready, will\n run the engine.\n run: Parse and process the input, execute the engine, process the results and\n update the output.\n disconnect: Disconnect all data and signal IO connections.\n\n Examples:\n At the most basic level, to use nodes all we need to do is provide the\n `Function` class with a function and labels for its output, like so:\n >>> from pyiron_contrib.workflow.function import Function\n >>>\n >>> def mwe(x, y):\n ... return x+1, y-1\n >>>\n >>> plus_minus_1 = Function(mwe)\n >>>\n >>> print(plus_minus_1.outputs[\"x+1\"])\n \n\n There is no output because we haven't given our function any input, it has\n no defaults, and we never ran it! It tried to `update()` on instantiation, but\n the update never got to `run()` because the node could see that some its input\n had never been specified. So outputs have the channel default value of\n `NotData` -- a special non-data class (since `None` is sometimes a meaningful\n value in python).\n\n We'll run into a hiccup if we try to set only one of the inputs and force the\n run:\n >>> plus_minus_1.inputs.x = 2\n >>> plus_minus_1.run()\n TypeError\n\n This is because the second input (`y`) still has no input value, so we can't do\n the sum.\n\n Once we update `y`, all the input is ready and the automatic `update()` call\n will be allowed to proceed to a `run()` call, which succeeds and updates the\n output.\n The final thing we need to do is disable the `failed` status we got from our\n last run call\n >>> plus_minus_1.failed = False\n >>> plus_minus_1.inputs.y = 3\n >>> plus_minus_1.outputs.to_value_dict()\n {'x+1': 3, 'y-1': 2}\n\n We can also, optionally, provide initial values for some or all of the input and\n labels for the output:\n >>> plus_minus_1 = Function(mwe, output_labels=(\"p1\", \"m1\"), x=1)\n >>> plus_minus_1.inputs.y = 2 # Automatically triggers an update call now\n >>> plus_minus_1.outputs.to_value_dict()\n {'p1': 2, 'm1': 1}\n\n Input data can be provided to both initialization and on call as ordered args\n or keyword kwargs.\n When running, updating, or calling the node, the output of the wrapped function\n (if it winds up getting run in the conditional cases of updating and calling) is\n returned:\n >>> plus_minus_1(2, y=3)\n (3, 2)\n\n Finally, we might stop these updates from happening automatically, even when\n all the input data is present and available:\n >>> plus_minus_1 = Function(\n ... mwe, output_labels=(\"p1\", \"m1\"),\n ... x=0, y=0,\n ... run_on_updates=False, update_on_instantiation=False\n ... )\n >>> plus_minus_1.outputs.p1.value\n \n\n With these flags set, the node requires us to manually call a run:\n >>> plus_minus_1.run()\n (-1, 1)\n\n So function nodes have the most basic level of protection that they won't run\n if they haven't seen any input data.\n However, we could still get them to raise an error by providing the _wrong_\n data:\n >>> plus_minus_1 = Function(mwe, x=1, y=\"can't add to an int\")\n TypeError\n\n Here everything tries to run automatically, but we get an error from adding the\n integer and string!\n We can make our node even more sensible by adding type\n hints (and, optionally, default values) when defining the function that the node\n wraps.\n The node will automatically figure out defaults and type hints for the IO\n channels from inspection of the wrapped function.\n\n In this example, note the mixture of old-school (`typing.Union`) and new (`|`)\n type hints as well as nested hinting with a union-type inside the tuple for the\n return hint.\n Our treatment of type hints is **not infinitely robust**, but covers a wide\n variety of common use cases.\n Note that getting \"good\" (i.e. dot-accessible) output labels can be achieved by\n using good variable names and returning those variables instead of using\n `output_labels`:\n >>> from typing import Union\n >>>\n >>> def hinted_example(\n ... x: Union[int, float],\n ... y: int | float = 1\n ... ) -> tuple[int, int | float]:\n ... p1, m1 = x+1, y-1\n ... return p1, m1\n >>>\n >>> plus_minus_1 = Function(hinted_example, x=\"not an int\")\n >>> plus_minus_1.outputs.to_value_dict()\n {'p1': , 'm1': }\n\n Here, even though all the input has data, the node sees that some of it is the\n wrong type and so the automatic updates don't proceed all the way to a run.\n Note that the type hinting doesn't actually prevent us from assigning bad values\n directly to the channel (although it will, by default, prevent connections\n _between_ type-hinted channels with incompatible hints), but it _does_ stop the\n node from running and throwing an error because it sees that the channel (and\n thus node) is not ready\n >>> plus_minus_1.inputs.x.value\n 'not an int'\n\n >>> plus_minus_1.ready, plus_minus_1.inputs.x.ready, plus_minus_1.inputs.y.ready\n (False, False, True)\n\n In these examples, we've instantiated nodes directly from the base `Function`\n class, and populated their input directly with data.\n In practice, these nodes are meant to be part of complex workflows; that means\n both that you are likely to have particular nodes that get heavily re-used, and\n that you need the nodes to pass data to each other.\n\n For reusable nodes, we want to create a sub-class of `Function` that fixes some\n of the node behaviour -- usually the `node_function` and `output_labels`.\n\n This can be done most easily with the `node` decorator, which takes a function\n and returns a node class:\n >>> from pyiron_contrib.workflow.function import function_node\n >>>\n >>> @function_node(output_labels=(\"p1\", \"m1\"))\n ... def my_mwe_node(\n ... x: int | float, y: int | float = 1\n ... ) -> tuple[int | float, int | float]:\n ... return x+1, y-1\n >>>\n >>> node_instance = my_mwe_node(x=0)\n >>> node_instance.outputs.to_value_dict()\n {'p1': 1, 'm1': 0}\n\n Where we've passed the output labels and class arguments to the decorator,\n and inital values to the newly-created node class (`my_mwe_node`) at\n instantiation.\n Because we provided a good initial value for `x`, we get our result right away.\n\n Using the decorator is the recommended way to create new node classes, but this\n magic is just equivalent to these two more verbose ways of defining a new class.\n The first is to override the `__init__` method directly:\n >>> from typing import Literal, Optional\n >>>\n >>> class AlphabetModThree(Function):\n ... def __init__(\n ... self,\n ... label: Optional[str] = None,\n ... run_on_updates: bool = True,\n ... update_on_instantiation: bool = False,\n ... **kwargs\n ... ):\n ... super().__init__(\n ... self.alphabet_mod_three,\n ... label=label,\n ... run_on_updates=run_on_updates,\n ... update_on_instantiation=update_on_instantiation,\n ... **kwargs\n ... )\n ...\n ... @staticmethod\n ... def alphabet_mod_three(i: int) -> Literal[\"a\", \"b\", \"c\"]:\n ... letter = [\"a\", \"b\", \"c\"][i % 3]\n ... return letter\n\n Note that we've overridden the default value for `update_on_instantiation`\n above.\n We can also provide different defaults for these flags as kwargs in the\n decorator.\n\n The second effectively does the same thing, but leverages python's\n `functools.partialmethod` to do so much more succinctly.\n In this example, note that the function is declared _before_ `__init__` is set,\n so that it is available in the correct scope (above, we could place it\n afterwards because we were accessing it through self).\n >>> from functools import partialmethod\n >>>\n >>> class Adder(Function):\n ... @staticmethod\n ... def adder(x: int = 0, y: int = 0) -> int:\n ... sum = x + y\n ... return sum\n ...\n ... __init__ = partialmethod(\n ... Function.__init__,\n ... adder,\n ... )\n\n Finally, let's put it all together by using both of these nodes at once.\n Instead of setting input to a particular data value, we'll set it to\n be another node's output channel, thus forming a connection.\n When we update the upstream node, we'll see the result passed downstream:\n >>> adder = Adder()\n >>> alpha = AlphabetModThree(i=adder.outputs.sum)\n >>>\n >>> adder.inputs.x = 1\n >>> print(alpha.outputs.letter)\n \"b\"\n >>> adder.inputs.y = 1\n >>> print(alpha.outputs.letter)\n \"c\"\n >>> adder.inputs.x = 0\n >>> adder.inputs.y = 0\n >>> print(alpha.outputs.letter)\n \"a\"\n\n To see more details on how to use many nodes together, look at the\n `Workflow` class.\n\n Comments:\n\n If you use the function argument `self` in the first position, the\n whole node object is inserted there:\n\n >>> def with_self(self, x):\n >>> ...\n >>> return x\n\n For this function, you don't have the freedom to choose `self`, because\n pyiron automatically sets the node object there (which is also the\n reason why you do not see `self` in the list of inputs).\n \"\"\"\n\n def __init__(\n self,\n node_function: callable,\n *args,\n label: Optional[str] = None,\n run_on_updates: bool = True,\n update_on_instantiation: bool = True,\n channels_requiring_update_after_run: Optional[list[str]] = None,\n parent: Optional[Composite] = None,\n output_labels: Optional[str | list[str] | tuple[str]] = None,\n **kwargs,\n ):\n super().__init__(\n label=label if label is not None else node_function.__name__,\n parent=parent,\n run_on_updates=run_on_updates,\n # **kwargs,\n )\n\n self.node_function = node_function\n\n self._inputs = None\n self._outputs = None\n self._output_labels = self._get_output_labels(output_labels)\n # TODO: Parse output labels from the node function in case output_labels is None\n\n self.signals = self._build_signal_channels()\n\n self.channels_requiring_update_after_run = (\n []\n if channels_requiring_update_after_run is None\n else channels_requiring_update_after_run\n )\n self._verify_that_channels_requiring_update_all_exist()\n\n self._batch_update_input(*args, **kwargs)\n\n if update_on_instantiation:\n self.update()\n\n def _get_output_labels(self, output_labels: str | list[str] | tuple[str] | None):\n \"\"\"\n If output labels are provided, turn convert them to a list if passed as a\n string and return them, else scrape them from the source channel.\n\n Note: When the user explicitly provides output channels, they are taking\n responsibility that these are correct, e.g. in terms of quantity, order, etc.\n \"\"\"\n if output_labels is None:\n return self._scrape_output_labels()\n elif isinstance(output_labels, str):\n return [output_labels]\n else:\n return output_labels\n\n def _scrape_output_labels(self):\n \"\"\"\n Inspect the source code to scrape out strings representing the returned values.\n _Only_ works for functions with a single `return` expression in their body.\n\n Will return expressions and function calls just fine, thus best practice is to\n create well-named variables and return those so that the output labels stay\n dot-accessible.\n \"\"\"\n parsed_outputs = ParseOutput(self.node_function).output\n return [] if parsed_outputs is None else parsed_outputs\n\n @property\n def _input_args(self):\n return inspect.signature(self.node_function).parameters\n\n @property\n def inputs(self) -> Inputs:\n if self._inputs is None:\n self._inputs = Inputs(*self._build_input_channels())\n return self._inputs\n\n @property\n def outputs(self) -> Outputs:\n if self._outputs is None:\n self._outputs = Outputs(*self._build_output_channels(*self._output_labels))\n return self._outputs\n\n def _build_input_channels(self):\n channels = []\n type_hints = get_type_hints(self.node_function)\n\n for ii, (label, value) in enumerate(self._input_args.items()):\n is_self = False\n if label == \"self\": # `self` is reserved for the node object\n if ii == 0:\n is_self = True\n else:\n warnings.warn(\n \"`self` is used as an argument but not in the first\"\n \" position, so it is treated as a normal function\"\n \" argument. If it is to be treated as the node object,\"\n \" use it as a first argument\"\n )\n if label in self._init_keywords:\n # We allow users to parse arbitrary kwargs as channel initialization\n # So don't let them choose bad channel names\n raise ValueError(\n f\"The Input channel name {label} is not valid. Please choose a \"\n f\"name _not_ among {self._init_keywords}\"\n )\n\n try:\n type_hint = type_hints[label]\n if is_self:\n warnings.warn(\"type hint for self ignored\")\n except KeyError:\n type_hint = None\n\n default = NotData # The standard default in DataChannel\n if value.default is not inspect.Parameter.empty:\n if is_self:\n warnings.warn(\"default value for self ignored\")\n else:\n default = value.default\n\n if not is_self:\n channels.append(\n InputData(\n label=label,\n node=self,\n default=default,\n type_hint=type_hint,\n )\n )\n return channels\n\n @property\n def _init_keywords(self):\n return list(inspect.signature(self.__init__).parameters.keys())\n\n def _build_output_channels(self, *return_labels: str):\n try:\n type_hints = get_type_hints(self.node_function)[\"return\"]\n if len(return_labels) > 1:\n type_hints = get_args(type_hints)\n if not isinstance(type_hints, tuple):\n raise TypeError(\n f\"With multiple return labels expected to get a tuple of type \"\n f\"hints, but got type {type(type_hints)}\"\n )\n if len(type_hints) != len(return_labels):\n raise ValueError(\n f\"Expected type hints and return labels to have matching \"\n f\"lengths, but got {len(type_hints)} hints and \"\n f\"{len(return_labels)} labels: {type_hints}, {return_labels}\"\n )\n else:\n # If there's only one hint, wrap it in a tuple so we can zip it with\n # *return_labels and iterate over both at once\n type_hints = (type_hints,)\n except KeyError:\n type_hints = [None] * len(return_labels)\n\n channels = []\n for label, hint in zip(return_labels, type_hints):\n channels.append(\n OutputData(\n label=label,\n node=self,\n type_hint=hint,\n )\n )\n\n return channels\n\n def _verify_that_channels_requiring_update_all_exist(self):\n if not all(\n channel_name in self.inputs.labels\n for channel_name in self.channels_requiring_update_after_run\n ):\n raise ValueError(\n f\"On or more channel name among those listed as requiring updates \"\n f\"after the node runs ({self.channels_requiring_update_after_run}) was \"\n f\"not found among the input channels ({self.inputs.labels})\"\n )\n\n @property\n def on_run(self):\n return self.node_function\n\n @property\n def run_args(self) -> dict:\n kwargs = self.inputs.to_value_dict()\n if \"self\" in self._input_args:\n if self.executor is not None:\n raise NotImplementedError(\n f\"The node {self.label} cannot be run on an executor because it \"\n f\"uses the `self` argument and this functionality is not yet \"\n f\"implemented\"\n )\n kwargs[\"self\"] = self\n return kwargs\n\n def process_run_result(self, function_output):\n \"\"\"\n Take the results of the node function, and use them to update the node output.\n\n By extracting this as a separate method, we allow the node to pass the actual\n execution off to another entity and release the python process to do other\n things. In such a case, this function should be registered as a callback\n so that the node can finishing \"running\" and push its data forward when that\n execution is finished.\n \"\"\"\n for channel_name in self.channels_requiring_update_after_run:\n self.inputs[channel_name].wait_for_update()\n\n if len(self.outputs) == 0:\n return\n elif len(self.outputs) == 1:\n function_output = (function_output,)\n\n for out, value in zip(self.outputs, function_output):\n out.update(value)\n\n def _convert_input_args_and_kwargs_to_input_kwargs(self, *args, **kwargs):\n reverse_keys = list(self._input_args.keys())[::-1]\n if len(args) > len(reverse_keys):\n raise ValueError(\n f\"Received {len(args)} positional arguments, but the node {self.label}\"\n f\"only accepts {len(reverse_keys)} inputs.\"\n )\n\n positional_keywords = reverse_keys[-len(args) :] if len(args) > 0 else [] # -0:\n if len(set(positional_keywords).intersection(kwargs.keys())) > 0:\n raise ValueError(\n f\"Cannot use {set(positional_keywords).intersection(kwargs.keys())} \"\n f\"as both positional _and_ keyword arguments; args {args}, kwargs {kwargs}, reverse_keys {reverse_keys}, positional_keyworkds {positional_keywords}\"\n )\n\n for arg in args:\n key = positional_keywords.pop()\n kwargs[key] = arg\n\n return kwargs\n\n def _batch_update_input(self, *args, **kwargs):\n kwargs = self._convert_input_args_and_kwargs_to_input_kwargs(*args, **kwargs)\n return super()._batch_update_input(**kwargs)\n\n def __call__(self, *args, **kwargs) -> None:\n kwargs = self._convert_input_args_and_kwargs_to_input_kwargs(*args, **kwargs)\n return super().__call__(**kwargs)\n\n def to_dict(self):\n return {\n \"label\": self.label,\n \"ready\": self.ready,\n \"connected\": self.connected,\n \"fully_connected\": self.fully_connected,\n \"inputs\": self.inputs.to_dict(),\n \"outputs\": self.outputs.to_dict(),\n \"signals\": self.signals.to_dict(),\n }\n\n @property\n def color(self) -> str:\n \"\"\"For drawing the graph\"\"\"\n return SeabornColors.green\n\n\nclass Slow(Function):\n \"\"\"\n Like a regular node, but `run_on_updates` and `update_on_instantiation` default to\n `False`.\n This is intended for wrapping function which are potentially expensive to call,\n where you don't want the output recomputed unless `run()` is _explicitly_ called.\n \"\"\"\n\n def __init__(\n self,\n node_function: callable,\n *args,\n label: Optional[str] = None,\n run_on_updates=False,\n update_on_instantiation=False,\n parent: Optional[Workflow] = None,\n output_labels: Optional[str | list[str] | tuple[str]] = None,\n **kwargs,\n ):\n super().__init__(\n node_function,\n *args,\n label=label,\n run_on_updates=run_on_updates,\n update_on_instantiation=update_on_instantiation,\n parent=parent,\n output_labels=output_labels,\n **kwargs,\n )\n\n @property\n def color(self) -> str:\n \"\"\"For drawing the graph\"\"\"\n return SeabornColors.red\n\n\nclass SingleValue(Function, HasChannel):\n \"\"\"\n A node that _must_ return only a single value.\n\n Attribute and item access is modified to finally attempt access on the output value.\n Note that this means any attributes/method available on the output value become\n available directly at the node level (at least those which don't conflict with the\n existing node namespace).\n \"\"\"\n\n def __init__(\n self,\n node_function: callable,\n *args,\n label: Optional[str] = None,\n run_on_updates=True,\n update_on_instantiation=True,\n parent: Optional[Workflow] = None,\n output_labels: Optional[str | list[str] | tuple[str]] = None,\n **kwargs,\n ):\n super().__init__(\n node_function,\n *args,\n label=label,\n run_on_updates=run_on_updates,\n update_on_instantiation=update_on_instantiation,\n parent=parent,\n output_labels=output_labels,\n **kwargs,\n )\n\n def _get_output_labels(self, output_labels: str | list[str] | tuple[str] | None):\n output_labels = super()._get_output_labels(output_labels)\n if len(output_labels) > 1:\n raise ValueError(\n f\"{self.__class__.__name__} must only have a single return value, but \"\n f\"got multiple output labels: {output_labels}\"\n )\n return output_labels\n\n @property\n def single_value(self):\n return self.outputs[self.outputs.labels[0]].value\n\n @property\n def channel(self) -> OutputData:\n \"\"\"The channel for the single output\"\"\"\n return list(self.outputs.channel_dict.values())[0]\n\n @property\n def color(self) -> str:\n \"\"\"For drawing the graph\"\"\"\n return SeabornColors.cyan\n\n def __getitem__(self, item):\n return self.single_value.__getitem__(item)\n\n def __getattr__(self, item):\n return getattr(self.single_value, item)\n\n def __repr__(self):\n return self.single_value.__repr__()\n\n def __str__(self):\n return f\"{self.label} ({self.__class__.__name__}) output single-value: \" + str(\n self.single_value\n )\n\n\ndef function_node(**node_class_kwargs):\n \"\"\"\n A decorator for dynamically creating node classes from functions.\n\n Decorates a function.\n Returns a `Function` subclass whose name is the camel-case version of the function\n node, and whose signature is modified to exclude the node function and output labels\n (which are explicitly defined in the process of using the decorator).\n\n Optionally takes any keyword arguments of `Function`.\n \"\"\"\n\n def as_node(node_function: callable):\n return type(\n node_function.__name__.title().replace(\"_\", \"\"), # fnc_name to CamelCase\n (Function,), # Define parentage\n {\n \"__init__\": partialmethod(\n Function.__init__,\n node_function,\n **node_class_kwargs,\n )\n },\n )\n\n return as_node\n\n\ndef slow_node(**node_class_kwargs):\n \"\"\"\n A decorator for dynamically creating slow node classes from functions.\n\n Unlike normal nodes, slow nodes do update themselves on initialization and do not\n run themselves when they get updated -- i.e. they will not run when their input\n changes, `run()` must be explicitly called.\n\n Optionally takes any keyword arguments of `Slow`.\n \"\"\"\n\n def as_slow_node(node_function: callable):\n return type(\n node_function.__name__.title().replace(\"_\", \"\"), # fnc_name to CamelCase\n (Slow,), # Define parentage\n {\n \"__init__\": partialmethod(\n Slow.__init__,\n node_function,\n **node_class_kwargs,\n )\n },\n )\n\n return as_slow_node\n\n\ndef single_value_node(**node_class_kwargs):\n \"\"\"\n A decorator for dynamically creating fast node classes from functions.\n\n Unlike normal nodes, fast nodes _must_ have default values set for all their inputs.\n\n Optionally takes any keyword arguments of `SingleValueNode`.\n \"\"\"\n\n def as_single_value_node(node_function: callable):\n return type(\n node_function.__name__.title().replace(\"_\", \"\"), # fnc_name to CamelCase\n (SingleValue,), # Define parentage\n {\n \"__init__\": partialmethod(\n SingleValue.__init__,\n node_function,\n **node_class_kwargs,\n )\n },\n )\n\n return as_single_value_node\n","sub_path":"pyiron_contrib/workflow/function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":33130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"121794729","text":"# -*- coding:utf-8 -*-\n\nfrom res_manager import ResManager\nimport SeriousTools.SeriousTools as SeriousTools\nfrom ArchiveModule.archive_package import ArchivePackage\n\nfrom panda3d.core import GeoMipTerrain\n\nclass TerrainManager(ResManager):\n\n def __init__(self, resType = \"terrain\"):\n\n ResManager.__init__(self, resType)\n\n self.__currTerraId = None\n\n self.__arcPkg = ArchivePackage(arcPkgName = \"terrain\",\n itemsName = [\n \"terrainId\",\n \"heightfieldPath\",\n \"colormapPath\",\n \"pos\",\n \"hpr\",\n \"scale\",\n \"parentId\"\n ])\n\n self.__arcPkg.append_metaData(\"currTerraId\")\n\n #########################################\n\n # 加载地形资源\n def load_res(self,\n resPath,\n extraResPath,\n _resId = None):\n\n self._resCount += 1\n\n resId = None\n\n if _resId == None:\n\n resId = self._gen_resId()\n\n else:\n\n resId = _resId\n\n self.__currTerraId = resId\n\n res = GeoMipTerrain(resId)\n\n res.setHeightfield(resPath)\n res.setColorMap(extraResPath)\n\n self._resMap[resId] = res\n self._resPath[resId] = [resPath, extraResPath]\n\n return res\n\n #########################################\n\n # 设置当前所使用的地形\n def set_currTerrain(self, terrainId):\n\n self.__currTerraId = terrainId\n\n for id in self._resMap.keys():\n\n if id == self.__currTerraId:\n\n self._resMap[id].getRoot().show()\n\n else:\n\n self._resMap[id].getRoot().hide()\n\n #########################################\n\n def get_currTerrain(self):\n\n return self.__currTerraId\n\n # 更新地形\n def update_terrain(self, task):\n\n # task.setTaskChain(\"terraTaskChain\")\n #\n # self._resMap[self.__currTerraId].update()\n\n return task.cont\n\n def get_arcPkg(self):\n\n return self.__arcPkg\n\n\n\n","sub_path":"codes/SceneModule/terrain_manager.py","file_name":"terrain_manager.py","file_ext":"py","file_size_in_byte":2300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"568088719","text":"import time\nimport requests\nimport json\ntry:\n from pymysql.err import ProgrammingError\nexcept ImportError:\n from MySQLdb._exceptions import ProgrammingError\n\nfrom common import generalUtils\nfrom common.constants import gameModes, mods\nfrom common.constants import privileges\nfrom logger import log\nfrom common.ripple import scoreUtils\nfrom objects import glob\n\ntry:\n\timport objects.beatmap\nexcept:\n\tpass\n\n\ndef getBeatmapTime(beatmapID):\n\tp = 0\n\ttry:\n\t\tr = requests.get(f\"https://bm6.aeris-dev.pw/api/cheesegull/b/{beatmapID}\", timeout=2).text\n\t\tif r != \"null\\n\":\n\t\t\tp = json.loads(r)['TotalLength']\n\texcept Exception: #having backup mirror as having this fail literally kills the server\n\t\tlog.warning(\"The default beatmap mirror doesnt work! Using a backup one.\")\n\t\tr = requests.get(f\"http://storage.ripple.moe/api/b/{beatmapID}\", timeout=2).text\n\t\tif r != \"null\\n\":\n\t\t\tp = json.loads(r)['TotalLength']\n \n\treturn p\n\ndef PPBoard(userID, relax):\n\tresult = glob.db.fetch(\"SELECT ppboard FROM {rx}_stats WHERE id = {userid}\".format(rx='rx' if relax else 'users', userid=userID))\n\treturn result['ppboard']\n\ndef setPPBoard(userID, rx):\n\tglob.db.execute(\"UPDATE {rx}_stats SET ppboard = 1 WHERE id = {userid}\".format(rx='rx' if rx else 'users', userid=userID))\n\ndef setScoreBoard(userID, rx):\n\tglob.db.execute(\"UPDATE {rx}_stats SET ppboard = 0 WHERE id = {userid}\".format(rx='rx' if rx else 'users', userid=userID))\n\ndef noPPLimit(userID, relax):\n\tresult = glob.db.fetch(\"SELECT unrestricted_pp FROM {rx}_stats WHERE id = {userid}\".format(rx='rx' if relax else 'users', userid=userID))\n\treturn result['unrestricted_pp']\n\ndef whitelistUserPPLimit(userID, rx):\n\tglob.db.execute(\"UPDATE {rx}_stats SET unrestricted_pp = 1 WHERE id = {userid}\".format(rx='rx' if rx else 'users', userid=userID))\n\n#created ap variands\ndef PPBoardAP(userID):\n\tresult = glob.db.fetch(\"SELECT ppboard FROM ap_stats WHERE id = {userid}\".format(userid=userID))\n\treturn result['ppboard']\n\ndef setPPBoardAP(userID):\n\tglob.db.execute(\"UPDATE ap_stats SET ppboard = 1 WHERE id = {userid}\".format(userid=userID))\n\ndef setScoreBoardAP(userID):\n\tglob.db.execute(\"UPDATE ap_stats SET ppboard = 0 WHERE id = {userid}\".format(userid=userID))\n\ndef noPPLimitAP(userID):\n\tresult = glob.db.fetch(\"SELECT unrestricted_pp FROM ap_stats WHERE id = {userid}\".format(userid=userID))\n\treturn result['unrestricted_pp']\n\ndef whitelistUserPPLimitAP(userID):\n\tglob.db.execute(\"UPDATE ap_stats SET unrestricted_pp = 1 WHERE id = {userid}\".format(userid=userID))\n \ndef incrementPlaytime(userID, gameMode=0, length=0):\n\tmodeForDB = gameModes.getGameModeForDB(gameMode)\n\tresult = glob.db.fetch(\"SELECT playtime_{gm} as playtime FROM users_stats WHERE id = %s\".format(gm=modeForDB), [userID])\n\tif result is not None:\n\t\tglob.db.execute(\"UPDATE users_stats SET playtime_{gm} = %s WHERE id = %s\".format(gm=modeForDB), [(int(result['playtime'])+int(length)), userID])\n\telse:\n\t\tprint(\"Something went wrong...\")\n \n \ndef incrementPlaytimeRX(userID, gameMode=0, length=0):\n\tmodeForDB = gameModes.getGameModeForDB(gameMode)\n\tresult = glob.db.fetch(\"SELECT playtime_{gm} as playtime FROM rx_stats WHERE id = %s\".format(gm=modeForDB), [userID])\n\tif result is not None:\n\t\tglob.db.execute(\"UPDATE rx_stats SET playtime_{gm} = %s WHERE id = %s\".format(gm=modeForDB), [(int(result['playtime'])+int(length)), userID])\n\telse:\n\t\tprint(\"Something went wrong...\")\n\ndef incrementPlaytimeAP(userID, gameMode=0, length=0):\n\tmodeForDB = gameModes.getGameModeForDB(gameMode)\n\tresult = glob.db.fetch(\"SELECT playtime_{gm} as playtime FROM ap_stats WHERE id = %s\".format(gm=modeForDB), [userID])\n\tif result is not None:\n\t\tglob.db.execute(\"UPDATE ap_stats SET playtime_{gm} = %s WHERE id = %s\".format(gm=modeForDB), [(int(result['playtime'])+int(length)), userID])\n\telse:\n\t\tprint(\"Something went wrong...\")\t \n \n#rel was here\ndef getUserStats(userID, gameMode):\n\t\"\"\"\n\tGet all user stats relative to `gameMode`\n\n\t:param userID:\n\t:param gameMode: game mode number\n\t:return: dictionary with result\n\t\"\"\"\n\tmodeForDB = gameModes.getGameModeForDB(gameMode)\n\n\t# Get stats\n\tstats = glob.db.fetch(\"\"\"SELECT\n\t\t\t\t\t\tranked_score_{gm} AS rankedScore,\n\t\t\t\t\t\tavg_accuracy_{gm} AS accuracy,\n\t\t\t\t\t\tplaycount_{gm} AS playcount,\n\t\t\t\t\t\ttotal_score_{gm} AS totalScore,\n\t\t\t\t\t\tpp_{gm} AS pp\n\t\t\t\t\t\tFROM users_stats WHERE id = %s LIMIT 1\"\"\".format(gm=modeForDB), [userID])\n\n\t# Get game rank\n\tstats[\"gameRank\"] = getGameRank(userID, gameMode)\n\n\t# Return stats + game rank\n\treturn stats\n\ndef getUserStatsRx(userID, gameMode):\n\t\"\"\"\n\tGet all user stats relative to `gameMode`\n\n\t:param userID:\n\t:param gameMode: game mode number\n\t:return: dictionary with result\n\t\"\"\"\n\tmodeForDB = gameModes.getGameModeForDB(gameMode)\n\n\t# Get stats\n\tif gameMode == 3:\n\t\tstats = glob.db.fetch(\"\"\"SELECT\n\t\t\t\t\t\t\tranked_score_{gm} AS rankedScore,\n\t\t\t\t\t\t\tavg_accuracy_{gm} AS accuracy,\n\t\t\t\t\t\t\tplaycount_{gm} AS playcount,\n\t\t\t\t\t\t\ttotal_score_{gm} AS totalScore,\n\t\t\t\t\t\t\tpp_{gm} AS pp\n\t\t\t\t\t\t\tFROM users_stats WHERE id = %s LIMIT 1\"\"\".format(gm=modeForDB), [userID])\n\t\t\n\telse:\n \n\t\t# Get stats\n\t\tstats = glob.db.fetch(\"\"\"SELECT\n\t\t\t\t\t\t\tranked_score_{gm} AS rankedScore,\n\t\t\t\t\t\t\tavg_accuracy_{gm} AS accuracy,\n\t\t\t\t\t\t\tplaycount_{gm} AS playcount,\n\t\t\t\t\t\t\ttotal_score_{gm} AS totalScore,\n\t\t\t\t\t\t\tpp_{gm} AS pp\n\t\t\t\t\t\t\tFROM rx_stats WHERE id = %s LIMIT 1\"\"\".format(gm=modeForDB), [userID])\n\n\t# Get game rank\n\tstats[\"gameRank\"] = getGameRankRx(userID, gameMode)\n\n\t# Return stats + game rank\n\treturn stats\n\ndef getUserStatsAP(userID, gameMode):\n\t\"\"\"\n\tGet all user stats relative to `gameMode`\n\n\t:param userID:\n\t:param gameMode: game mode number\n\t:return: dictionary with result\n\t\"\"\"\n\tmodeForDB = gameModes.getGameModeForDB(gameMode)\n\n\t# Get stats\n\tif gameMode == 3: #mania\n\t\tstats = glob.db.fetch(\"\"\"SELECT\n\t\t\t\t\t\t\tranked_score_{gm} AS rankedScore,\n\t\t\t\t\t\t\tavg_accuracy_{gm} AS accuracy,\n\t\t\t\t\t\t\tplaycount_{gm} AS playcount,\n\t\t\t\t\t\t\ttotal_score_{gm} AS totalScore,\n\t\t\t\t\t\t\tpp_{gm} AS pp\n\t\t\t\t\t\t\tFROM users_stats WHERE id = %s LIMIT 1\"\"\".format(gm=modeForDB), [userID])\n\t\t\n\telse:\n \n\t\t# Get stats\n\t\tstats = glob.db.fetch(\"\"\"SELECT\n\t\t\t\t\t\t\tranked_score_{gm} AS rankedScore,\n\t\t\t\t\t\t\tavg_accuracy_{gm} AS accuracy,\n\t\t\t\t\t\t\tplaycount_{gm} AS playcount,\n\t\t\t\t\t\t\ttotal_score_{gm} AS totalScore,\n\t\t\t\t\t\t\tpp_{gm} AS pp\n\t\t\t\t\t\t\tFROM ap_stats WHERE id = %s LIMIT 1\"\"\".format(gm=modeForDB), [userID])\n\n\t# Get game rank\n\tstats[\"gameRank\"] = getGameRankAP(userID, gameMode)\n\n\t# Return stats + game rank\n\treturn stats\n\ndef getMaxCombo(userID, gameMode):\n\t\"\"\"\n\tGet all user stats relative to `gameMode`\n \n\t:param userID:\n\t:param gameMode: game mode number\n\t:return: dictionary with result\n\t\"\"\"\n\t# Get stats\n\tmaxcombo = glob.db.fetch(\"SELECT max_combo FROM scores WHERE userid = %s AND play_mode = %s ORDER BY max_combo DESC LIMIT 1\", [userID, gameMode])\n \n\t# Return stats + game rank\n\treturn maxcombo[\"max_combo\"]\n\ndef getMaxComboRX(userID, gameMode):\n\t\"\"\"\n\tGet all user stats relative to `gameMode`\n \n\t:param userID:\n\t:param gameMode: game mode number\n\t:return: dictionary with result\n\t\"\"\"\n\t# Get stats\n\tmaxcombo = glob.db.fetch(\"SELECT max_combo FROM scores_relax WHERE userid = %s AND play_mode = %s ORDER BY max_combo DESC LIMIT 1\", [userID, gameMode])\n \n\t# Return stats + game rank\n\treturn maxcombo[\"max_combo\"]\n\ndef getMaxComboAP(userID, gameMode):\n\t\"\"\"\n\tGet all user stats relative to `gameMode`\n \n\t:param userID:\n\t:param gameMode: game mode number\n\t:return: dictionary with result\n\t\"\"\"\n\t# Get stats\n\tmaxcombo = glob.db.fetch(\"SELECT max_combo FROM scores_ap WHERE userid = %s AND play_mode = %s ORDER BY max_combo DESC LIMIT 1\", [userID, gameMode])\n \n\t# Return stats + game rank\n\treturn maxcombo[\"max_combo\"]\n\t\ndef getIDSafe(_safeUsername):\n\t\"\"\"\n\tGet user ID from a safe username\n\t:param _safeUsername: safe username\n\t:return: None if the user doesn't exist, else user id\n\t\"\"\"\n\tresult = glob.db.fetch(\"SELECT id FROM users WHERE username_safe = %s LIMIT 1\", [_safeUsername])\n\tif result is not None:\n\t\treturn result[\"id\"]\n\treturn None\n\ndef getID(username):\n\t\"\"\"\n\tGet username's user ID from userID redis cache (if cache hit)\n\tor from db (and cache it for other requests) if cache miss\n\n\t:param username: user\n\t:return: user id or 0 if user doesn't exist\n\t\"\"\"\n\t# Get userID from redis\n\tusernameSafe = safeUsername(username)\n\tuserID = glob.redis.get(\"ripple:userid_cache:{}\".format(usernameSafe))\n\n\tif userID is None:\n\t\t# If it's not in redis, get it from mysql\n\t\tuserID = getIDSafe(usernameSafe)\n\n\t\t# If it's invalid, return 0\n\t\tif userID is None:\n\t\t\treturn 0\n\n\t\t# Otherwise, save it in redis and return it\n\t\tglob.redis.set(\"ripple:userid_cache:{}\".format(usernameSafe), userID, 3600)\t# expires in 1 hour\n\t\treturn userID\n\n\t# Return userid from redis\n\treturn int(userID)\n\ndef getUsername(userID):\n\t\"\"\"\n\tGet userID's username\n\n\t:param userID: user id\n\t:return: username or None\n\t\"\"\"\n\tresult = glob.db.fetch(\"SELECT username FROM users WHERE id = %s LIMIT 1\", [userID])\n\tif result is None:\n\t\treturn None\n\treturn result[\"username\"]\n\ndef getSafeUsername(userID):\n\t\"\"\"\n\tGet userID's safe username\n\n\t:param userID: user id\n\t:return: username or None\n\t\"\"\"\n\tresult = glob.db.fetch(\"SELECT username_safe FROM users WHERE id = %s LIMIT 1\", [userID])\n\tif result is None:\n\t\treturn None\n\treturn result[\"username_safe\"]\n\ndef exists(userID):\n\t\"\"\"\n\tCheck if given userID exists\n\n\t:param userID: user id to check\n\t:return: True if the user exists, else False\n\t\"\"\"\n\treturn True if glob.db.fetch(\"SELECT id FROM users WHERE id = %s LIMIT 1\", [userID]) is not None else False\n\ndef getRequiredScoreForLevel(level):\n\t\"\"\"\n\tReturn score required to reach a level\n\n\t:param level: level to reach\n\t:return: required score\n\t\"\"\"\n\tif level <= 100:\n\t\tif level >= 2:\n\t\t\treturn 5000 / 3 * (4 * (level ** 3) - 3 * (level ** 2) - level) + 1.25 * (1.8 ** (level - 60))\n\t\telif level <= 0 or level == 1:\n\t\t\treturn 1 # Should be 0, but we get division by 0 below so set to 1\n\telif level >= 101:\n\t\treturn 26931190829 + 100000000000 * (level - 100)\n\ndef getLevel(totalScore):\n\t\"\"\"\n\tReturn level from totalScore\n\n\t:param totalScore: total score\n\t:return: level\n\t\"\"\"\n\tlevel = 1\n\twhile True:\n\t\t# if the level is > 8000, it's probably an endless loop. terminate it.\n\t\tif level > 8000:\n\t\t\treturn level\n\n\t\t# Calculate required score\n\t\treqScore = getRequiredScoreForLevel(level)\n\n\t\t# Check if this is our level\n\t\tif totalScore <= reqScore:\n\t\t\t# Our level, return it and break\n\t\t\treturn level - 1\n\t\telse:\n\t\t\t# Not our level, calculate score for next level\n\t\t\tlevel += 1\n\ndef updateLevel(userID, gameMode=0, totalScore=0):\n\t\"\"\"\n\tUpdate level in DB for userID relative to gameMode\n\n\t:param userID: user id\n\t:param gameMode: game mode number\n\t:param totalScore: new total score\n\t:return:\n\t\"\"\"\n\t# Make sure the user exists\n\t# if not exists(userID):\n\t#\treturn\n\n\t# Get total score from db if not passed\n\tmode = scoreUtils.readableGameMode(gameMode)\n\tif totalScore == 0:\n\t\ttotalScore = glob.db.fetch(\n\t\t\t\"SELECT total_score_{m} as total_score FROM users_stats WHERE id = %s LIMIT 1\".format(m=mode), [userID])\n\t\tif totalScore:\n\t\t\ttotalScore = totalScore[\"total_score\"]\n\n\t# Calculate level from totalScore\n\tlevel = getLevel(totalScore)\n\n\t# Save new level\n\tglob.db.execute(\"UPDATE users_stats SET level_{m} = %s WHERE id = %s LIMIT 1\".format(m=mode), [level, userID])\n\ndef updateLevelRX(userID, gameMode=0, totalScore=0):\n\t\"\"\"\n\tUpdate level in DB for userID relative to gameMode\n \n\t:param userID: user id\n\t:param gameMode: game mode number\n\t:param totalScore: new total score\n\t:return:\n\t\"\"\"\n\t# Make sure the user exists\n\t# if not exists(userID):\n\t# return\n \n\t# Get total score from db if not passed\n\tmode = scoreUtils.readableGameMode(gameMode)\n\tif totalScore == 0:\n\t\ttotalScore = glob.db.fetch(\n\t\t\t\"SELECT total_score_{m} as total_score FROM rx_stats WHERE id = %s LIMIT 1\".format(m=mode), [userID])\n\t\tif totalScore:\n\t\t\ttotalScore = totalScore[\"total_score\"]\n \n\t# Calculate level from totalScore\n\tlevel = getLevel(totalScore)\n \n\t# Save new level\n\tglob.db.execute(\"UPDATE rx_stats SET level_{m} = %s WHERE id = %s LIMIT 1\".format(m=mode), [level, userID]) \n\ndef updateLevelAP(userID, gameMode=0, totalScore=0):\n\t\"\"\"\n\tUpdate level in DB for userID relative to gameMode\n \n\t:param userID: user id\n\t:param gameMode: game mode number\n\t:param totalScore: new total score\n\t:return:\n\t\"\"\"\n\t# Make sure the user exists\n\t# if not exists(userID):\n\t# return\n \n\t# Get total score from db if not passed\n\tmode = scoreUtils.readableGameMode(gameMode)\n\tif totalScore == 0:\n\t\ttotalScore = glob.db.fetch(\n\t\t\t\"SELECT total_score_{m} as total_score FROM ap_stats WHERE id = %s LIMIT 1\".format(m=mode), [userID])\n\t\tif totalScore:\n\t\t\ttotalScore = totalScore[\"total_score\"]\n \n\t# Calculate level from totalScore\n\tlevel = getLevel(totalScore)\n \n\t# Save new level\n\tglob.db.execute(\"UPDATE ap_stats SET level_{m} = %s WHERE id = %s LIMIT 1\".format(m=mode), [level, userID]) \n\t\ndef calculateAccuracy(userID, gameMode):\n\t\"\"\"\n\tCalculate accuracy value for userID relative to gameMode\n\n\t:param userID: user id\n\t:param gameMode: game mode number\n\t:return: new accuracy\n\t\"\"\"\n\t# Get best accuracy scores\n\tbestAccScores = glob.db.fetchAll(\n\t\t\"SELECT accuracy FROM scores WHERE userid = %s AND play_mode = %s AND completed = 3 ORDER BY pp DESC LIMIT 500\",\n\t\t(userID, gameMode)\n\t)\n\n\tv = 0\n\tif bestAccScores is not None:\n\t\t# Calculate weighted accuracy\n\t\ttotalAcc = 0\n\t\tdivideTotal = 0\n\t\tk = 0\n\t\tfor i in bestAccScores:\n\t\t\tadd = int((0.95 ** k) * 100)\n\t\t\ttotalAcc += i[\"accuracy\"] * add\n\t\t\tdivideTotal += add\n\t\t\tk += 1\n\t\t# echo \"$add - $totalacc - $divideTotal\\n\"\n\t\tif divideTotal != 0:\n\t\t\tv = totalAcc / divideTotal\n\t\telse:\n\t\t\tv = 0\n\treturn v\n\ndef calculateAccuracyRX(userID, gameMode):\n\t\"\"\"\n\tCalculate accuracy value for userID relative to gameMode\n \n\t:param userID: user id\n\t:param gameMode: game mode number\n\t:return: new accuracy\n\t\"\"\"\n\t# Get best accuracy scores\n\tbestAccScores = glob.db.fetchAll(\n\t\t\"SELECT accuracy FROM scores_relax WHERE userid = %s AND play_mode = %s AND completed = 3 ORDER BY pp DESC LIMIT 500\",\n\t\t[userID, gameMode])\n \n\tv = 0\n\tif bestAccScores is not None:\n\t\t# Calculate weighted accuracy\n\t\ttotalAcc = 0\n\t\tdivideTotal = 0\n\t\tk = 0\n\t\tfor i in bestAccScores:\n\t\t\tadd = int((0.95 ** k) * 100)\n\t\t\ttotalAcc += i[\"accuracy\"] * add\n\t\t\tdivideTotal += add\n\t\t\tk += 1\n\t\t# echo \"$add - $totalacc - $divideTotal\\n\"\n\t\tif divideTotal != 0:\n\t\t\tv = totalAcc / divideTotal\n\t\telse:\n\t\t\tv = 0\n\treturn v\n\ndef calculateAccuracyAP(userID, gameMode):\n\t\"\"\"\n\tCalculate accuracy value for userID relative to gameMode\n \n\t:param userID: user id\n\t:param gameMode: game mode number\n\t:return: new accuracy\n\t\"\"\"\n\t# Get best accuracy scores\n\tbestAccScores = glob.db.fetchAll(\n\t\t\"SELECT accuracy FROM scores_ap WHERE userid = %s AND play_mode = %s AND completed = 3 ORDER BY pp DESC LIMIT 500\",\n\t\t[userID, gameMode])\n \n\tv = 0\n\tif bestAccScores is not None:\n\t\t# Calculate weighted accuracy\n\t\ttotalAcc = 0\n\t\tdivideTotal = 0\n\t\tk = 0\n\t\tfor i in bestAccScores:\n\t\t\tadd = int((0.95 ** k) * 100)\n\t\t\ttotalAcc += i[\"accuracy\"] * add\n\t\t\tdivideTotal += add\n\t\t\tk += 1\n\t\t# echo \"$add - $totalacc - $divideTotal\\n\"\n\t\tif divideTotal != 0:\n\t\t\tv = totalAcc / divideTotal\n\t\telse:\n\t\t\tv = 0\n\treturn v\n\t\ndef calculatePP(userID, gameMode):\n\t\"\"\"\n\tCalculate userID's total PP for gameMode\n\n\t:param userID: user id\n\t:param gameMode: game mode number\n\t:return: total PP\n\t\"\"\"\n\treturn sum(round(round(row[\"pp\"]) * 0.95 ** i) for i, row in enumerate(glob.db.fetchAll(\n\t\t\"SELECT pp FROM scores LEFT JOIN(beatmaps) USING(beatmap_md5) \"\n\t\t\"WHERE userid = %s AND play_mode = %s AND completed = 3 AND ranked >= 2 \"\n\t\t\"ORDER BY pp DESC LIMIT 500\",\n\t\t(userID, gameMode)\n\t)))\n\ndef calculatePPRelax(userID, gameMode):\n\t\"\"\"\n\tCalculate userID's total PP for gameMode\n\n\t:param userID: user id\n\t:param gameMode: game mode number\n\t:return: total PP\n\t\"\"\"\n\treturn sum(round(round(row[\"pp\"]) * 0.95 ** i) for i, row in enumerate(glob.db.fetchAll(\n\t\t\"SELECT pp FROM scores_relax LEFT JOIN(beatmaps) USING(beatmap_md5) \"\n\t\t\"WHERE userid = %s AND play_mode = %s AND completed = 3 AND ranked >= 2 \"\n\t\t\"ORDER BY pp DESC LIMIT 500\",\n\t\t(userID, gameMode)\n\t)))\n\ndef calculatePPAP(userID, gameMode): #ppap\n\t\"\"\"\n\tCalculate userID's total PP for gameMode\n\n\t:param userID: user id\n\t:param gameMode: game mode number\n\t:return: total PP\n\t\"\"\"\n\treturn sum(round(round(row[\"pp\"]) * 0.95 ** i) for i, row in enumerate(glob.db.fetchAll(\n\t\t\"SELECT pp FROM scores_ap LEFT JOIN(beatmaps) USING(beatmap_md5) \"\n\t\t\"WHERE userid = %s AND play_mode = %s AND completed = 3 AND ranked >= 2 \"\n\t\t\"ORDER BY pp DESC LIMIT 500\",\n\t\t(userID, gameMode)\n\t)))\n\ndef updateAccuracy(userID, gameMode):\n\t\"\"\"\n\tUpdate accuracy value for userID relative to gameMode in DB\n\n\t:param userID: user id\n\t:param gameMode: gameMode number\n\t:return:\n\t\"\"\"\n\tnewAcc = calculateAccuracy(userID, gameMode)\n\tmode = scoreUtils.readableGameMode(gameMode)\n\tglob.db.execute(\"UPDATE users_stats SET avg_accuracy_{m} = %s WHERE id = %s LIMIT 1\".format(m=mode),\n\t\t\t\t\t[newAcc, userID])\n\ndef updateAccuracyRX(userID, gameMode):\n\t\"\"\"\n\tUpdate accuracy value for userID relative to gameMode in DB\n \n\t:param userID: user id\n\t:param gameMode: gameMode number\n\t:return:\n\t\"\"\"\n\tnewAcc = calculateAccuracyRX(userID, gameMode)\n\tmode = scoreUtils.readableGameMode(gameMode)\n\tglob.db.execute(\"UPDATE rx_stats SET avg_accuracy_{m} = %s WHERE id = %s LIMIT 1\".format(m=mode),\n\t\t\t\t\t[newAcc, userID]) \n\ndef updateAccuracyAP(userID, gameMode):\n\t\"\"\"\n\tUpdate accuracy value for userID relative to gameMode in DB\n \n\t:param userID: user id\n\t:param gameMode: gameMode number\n\t:return:\n\t\"\"\"\n\tnewAcc = calculateAccuracyAP(userID, gameMode)\n\tmode = scoreUtils.readableGameMode(gameMode)\n\tglob.db.execute(\"UPDATE ap_stats SET avg_accuracy_{m} = %s WHERE id = %s LIMIT 1\".format(m=mode),\n\t\t\t\t\t[newAcc, userID]) \n\t\t\t\t\t\ndef updatePP(userID, gameMode):\n\t\"\"\"\n\tUpdate userID's pp with new value\n\n\t:param userID: user id\n\t:param gameMode: game mode number\n\t\"\"\"\n\tglob.db.execute(\n\t\t\"UPDATE users_stats SET pp_{}=%s WHERE id = %s LIMIT 1\".format(scoreUtils.readableGameMode(gameMode)),\n\t\t(\n\t\t\tcalculatePP(userID, gameMode),\n\t\t\tuserID\n\t\t)\n\t)\n\ndef updatePPRelax(userID, gameMode):\n\t\"\"\"\n\tUpdate userID's pp with new value\n\n\t:param userID: user id\n\t:param gameMode: game mode number\n\t\"\"\"\n\tglob.db.execute(\n\t\t\"UPDATE rx_stats SET pp_{}=%s WHERE id = %s LIMIT 1\".format(scoreUtils.readableGameMode(gameMode)),\n\t\t(\n\t\t\tcalculatePPRelax(userID, gameMode),\n\t\t\tuserID\n\t\t)\n\t)\n\ndef updatePPAP(userID, gameMode):\n\t\"\"\"\n\tUpdate userID's pp with new value\n\n\t:param userID: user id\n\t:param gameMode: game mode number\n\t\"\"\"\n\tglob.db.execute(\n\t\t\"UPDATE ap_stats SET pp_{}=%s WHERE id = %s LIMIT 1\".format(scoreUtils.readableGameMode(gameMode)),\n\t\t(\n\t\t\tcalculatePPAP(userID, gameMode),\n\t\t\tuserID\n\t\t)\n\t)\n\ndef updateStats(userID, score_):\n\t\"\"\"\n\tUpdate stats (playcount, total score, ranked score, level bla bla)\n\twith data relative to a score object\n\n\t:param userID:\n\t:param score_: score object\n\t:param beatmap_: beatmap object. Optional. If not passed, it'll be determined by score_.\n\t\"\"\"\n\n\t# Make sure the user exists\n\tif not exists(userID):\n\t\tlog.warning(\"User {} doesn't exist.\".format(userID))\n\t\treturn\n\n\t# Get gamemode for db\n\tmode = scoreUtils.readableGameMode(score_.gameMode)\n\n\t# Update total score, playcount and play time\n\tif score_.playTime is not None:\n\t\trealPlayTime = score_.playTime\n\telse:\n\t\trealPlayTime = score_.fullPlayTime\n\n\tglob.db.execute(\n\t\t\"UPDATE users_stats SET total_score_{m}=total_score_{m}+%s, playcount_{m}=playcount_{m}+1, \"\n\t\t\"playtime_{m} = playtime_{m} + %s \"\n\t\t\"WHERE id = %s LIMIT 1\".format(\n\t\t\tm=mode\n\t\t),\n\t\t(score_.score, realPlayTime, userID)\n\t)\n\n\t# Calculate new level and update it\n\tupdateLevel(userID, score_.gameMode)\n\n\t# Update level, accuracy and ranked score only if we have passed the song\n\tif score_.passed:\n\t\t# Update ranked score\n\t\tglob.db.execute(\n\t\t\t\"UPDATE users_stats SET ranked_score_{m}=ranked_score_{m}+%s WHERE id = %s LIMIT 1\".format(m=mode),\n\t\t\t(score_.rankedScoreIncrease, userID)\n\t\t)\n\n\t\t# Update accuracy\n\t\tupdateAccuracy(userID, score_.gameMode)\n\n\t\t# Update pp\n\t\tupdatePP(userID, score_.gameMode)\n\ndef updateStatsRx(userID, score_):\n\t\"\"\"\n\tUpdate stats (playcount, total score, ranked score, level bla bla)\n\twith data relative to a score object\n\n\t:param userID:\n\t:param score_: score object\n\t:param beatmap_: beatmap object. Optional. If not passed, it'll be determined by score_.\n\t\"\"\"\n\n\t# Make sure the user exists\n\tif not exists(userID):\n\t\tlog.warning(\"User {} doesn't exist.\".format(userID))\n\t\treturn\n\n\t# Get gamemode for db\n\tmode = scoreUtils.readableGameMode(score_.gameMode)\n\n\t# Update total score, playcount and play time\n\tif score_.playTime is not None:\n\t\trealPlayTime = score_.playTime\n\telse:\n\t\trealPlayTime = score_.fullPlayTime\n\n\tglob.db.execute(\n\t\t\"UPDATE rx_stats SET total_score_{m}=total_score_{m}+%s, playcount_{m}=playcount_{m}+1, \"\n\t\t\"playtime_{m} = playtime_{m} + %s \"\n\t\t\"WHERE id = %s LIMIT 1\".format(\n m=mode\n ),\n (score_.score, realPlayTime, userID)\n )\n\n\t# Calculate new level and update it\n\tupdateLevelRX(userID, score_.gameMode)\n\n\t# Update level, accuracy and ranked score only if we have passed the song\n\tif score_.passed:\n\t\t# Update ranked score\n\t\tglob.db.execute(\n\t\t\t\"UPDATE rx_stats SET ranked_score_{m}=ranked_score_{m}+%s WHERE id = %s LIMIT 1\".format(m=mode),\n\t\t\t(score_.rankedScoreIncrease, userID)\n\t\t)\n\n\t\t# Update accuracy\n\t\tupdateAccuracyRX(userID, score_.gameMode)\n\n\t\t# Update pp\n\t\tupdatePPRelax(userID, score_.gameMode)\n\ndef updateStatsAP(userID, score_):\n\t\"\"\"\n\tUpdate stats (playcount, total score, ranked score, level bla bla)\n\twith data relative to a score object\n\n\t:param userID:\n\t:param score_: score object\n\t:param beatmap_: beatmap object. Optional. If not passed, it'll be determined by score_.\n\t\"\"\"\n\n\t# Make sure the user exists\n\tif not exists(userID):\n\t\tlog.warning(\"User {} doesn't exist.\".format(userID))\n\t\treturn\n\n\t# Get gamemode for db\n\tmode = scoreUtils.readableGameMode(score_.gameMode)\n\n\t# Update total score, playcount and play time\n\tif score_.playTime is not None:\n\t\trealPlayTime = score_.playTime\n\telse:\n\t\trealPlayTime = score_.fullPlayTime\n\n\tglob.db.execute(\n\t\t\"UPDATE ap_stats SET total_score_{m}=total_score_{m}+%s, playcount_{m}=playcount_{m}+1, \"\n\t\t\"playtime_{m} = playtime_{m} + %s \"\n\t\t\"WHERE id = %s LIMIT 1\".format(\n m=mode\n ),\n (score_.score, realPlayTime, userID)\n )\n\n\t# Calculate new level and update it\n\tupdateLevelAP(userID, score_.gameMode)\n\n\t# Update level, accuracy and ranked score only if we have passed the song\n\tif score_.passed:\n\t\t# Update ranked score\n\t\tglob.db.execute(\n\t\t\t\"UPDATE ap_stats SET ranked_score_{m}=ranked_score_{m}+%s WHERE id = %s LIMIT 1\".format(m=mode),\n\t\t\t(score_.rankedScoreIncrease, userID)\n\t\t)\n\n\t\t# Update accuracy\n\t\tupdateAccuracyAP(userID, score_.gameMode)\n\n\t\t# Update pp\n\t\tupdatePPAP(userID, score_.gameMode)\n\ndef incrementUserBeatmapPlaycount(userID, gameMode, beatmapID):\n\tglob.db.execute(\n\t\t\"INSERT INTO users_beatmap_playcount (user_id, beatmap_id, game_mode, playcount) \"\n\t\t\"VALUES (%s, %s, %s, 1) ON DUPLICATE KEY UPDATE playcount = playcount + 1\",\n\t\t(userID, beatmapID, gameMode)\n\t)\n\t\ndef incrementUserBeatmapPlaycountRX(userID, gameMode, beatmapID):\n\tglob.db.execute(\n\t\t\"INSERT INTO rx_beatmap_playcount (user_id, beatmap_id, game_mode, playcount) \"\n\t\t\"VALUES (%s, %s, %s, 1) ON DUPLICATE KEY UPDATE playcount = playcount + 1\",\n\t\t(userID, beatmapID, gameMode)\n\t)\n\ndef incrementUserBeatmapPlaycountAP(userID, gameMode, beatmapID):\n\tglob.db.execute(\n\t\t\"INSERT INTO ap_beatmap_playcount (user_id, beatmap_id, game_mode, playcount) \"\n\t\t\"VALUES (%s, %s, %s, 1) ON DUPLICATE KEY UPDATE playcount = playcount + 1\",\n\t\t(userID, beatmapID, gameMode)\n\t)\n\ndef updateLatestActivity(userID):\n\t\"\"\"\n\tUpdate userID's latest activity to current UNIX time\n\n\t:param userID: user id\n\t:return:\n\t\"\"\"\n\tglob.db.execute(\"UPDATE users SET latest_activity = %s WHERE id = %s LIMIT 1\", [int(time.time()), userID])\n\ndef getRankedScore(userID, gameMode):\n\t\"\"\"\n\tGet userID's ranked score relative to gameMode\n\n\t:param userID: user id\n\t:param gameMode: game mode number\n\t:return: ranked score\n\t\"\"\"\n\tmode = scoreUtils.readableGameMode(gameMode)\n\tresult = glob.db.fetch(\"SELECT ranked_score_{} FROM users_stats WHERE id = %s LIMIT 1\".format(mode), [userID])\n\tif result is not None:\n\t\treturn result[\"ranked_score_{}\".format(mode)]\n\telse:\n\t\treturn 0\n\ndef getPP(userID, gameMode):\n\t\"\"\"\n\tGet userID's PP relative to gameMode\n\n\t:param userID: user id\n\t:param gameMode: game mode number\n\t:return: pp\n\t\"\"\"\n\n\tmode = scoreUtils.readableGameMode(gameMode)\n\tresult = glob.db.fetch(\"SELECT pp_{} FROM users_stats WHERE id = %s LIMIT 1\".format(mode), [userID])\n\tif result is not None:\n\t\treturn result[\"pp_{}\".format(mode)]\n\telse:\n\t\treturn 0\n\ndef incrementReplaysWatched(userID, gameMode):\n\t\"\"\"\n\tIncrement userID's replays watched by others relative to gameMode\n\n\t:param userID: user id\n\t:param gameMode: game mode number\n\t:return:\n\t\"\"\"\n\tmode = scoreUtils.readableGameMode(gameMode)\n\tglob.db.execute(\n\t\t\"UPDATE users_stats SET replays_watched_{mode}=replays_watched_{mode}+1 WHERE id = %s LIMIT 1\".format(\n\t\t\tmode=mode), [userID])\n\ndef incrementReplaysWatchedRX(userID, gameMode):\n\t\"\"\"\n\tIncrement userID's replays watched by others relative to gameMode\n\n\t:param userID: user id\n\t:param gameMode: game mode number\n\t:return:\n\t\"\"\"\n\tmode = scoreUtils.readableGameMode(gameMode)\n\tglob.db.execute(\n\t\t\"UPDATE rx_stats SET replays_watched_{mode}=replays_watched_{mode}+1 WHERE id = %s LIMIT 1\".format(\n\t\t\tmode=mode), [userID])\n\ndef incrementReplaysWatchedAP(userID, gameMode):\n\t\"\"\"\n\tIncrement userID's replays watched by others relative to gameMode\n\n\t:param userID: user id\n\t:param gameMode: game mode number\n\t:return:\n\t\"\"\"\n\tmode = scoreUtils.readableGameMode(gameMode)\n\tglob.db.execute(\n\t\t\"UPDATE ap_stats SET replays_watched_{mode}=replays_watched_{mode}+1 WHERE id = %s LIMIT 1\".format(\n\t\t\tmode=mode), [userID])\n\ndef getAqn(userID):\n\t\"\"\"\n\tCheck if AQN folder was detected for userID\n\n\t:param userID: user\n\t:return: True if hax, False if legit\n\t\"\"\"\n\tresult = glob.db.fetch(\"SELECT aqn FROM users WHERE id = %s LIMIT 1\", [userID])\n\tif result is not None:\n\t\treturn True if int(result[\"aqn\"]) == 1 else False\n\telse:\n\t\treturn False\n\ndef setAqn(userID, value=1):\n\t\"\"\"\n\tSet AQN folder status for userID\n\n\t:param userID: user\n\t:param value: new aqn value, default = 1\n\t:return:\n\t\"\"\"\n\tglob.db.fetch(\"UPDATE users SET aqn = %s WHERE id = %s LIMIT 1\", [value, userID])\n\ndef IPLog(userID, ip):\n\t\"\"\"\n\tLog user IP\n\n\t:param userID: user id\n\t:param ip: IP address\n\t:return:\n\t\"\"\"\n\tglob.db.execute(\"\"\"INSERT INTO ip_user (userid, ip, occurencies) VALUES (%s, %s, '1')\n\t\t\t\t\t\tON DUPLICATE KEY UPDATE occurencies = occurencies + 1\"\"\", [userID, ip])\n\ndef checkBanchoSession(userID, ip=\"\"):\n\t\"\"\"\n\tReturn True if there is a bancho session for `userID` from `ip`\n\tIf `ip` is an empty string, check if there's a bancho session for that user, from any IP.\n\n\t:param userID: user id\n\t:param ip: ip address. Optional. Default: empty string\n\t:return: True if there's an active bancho session, else False\n\t\"\"\"\n\tif ip != \"\":\n\t\treturn glob.redis.sismember(\"peppy:sessions:{}\".format(userID), ip)\n\telse:\n\t\treturn glob.redis.exists(\"peppy:sessions:{}\".format(userID))\n\ndef is2FAEnabled(userID):\n\t\"\"\"\n\tReturns True if 2FA/Google auth 2FA is enable for `userID`\n\n\t:userID: user ID\n\t:return: True if 2fa is enabled, else False\n\t\"\"\"\n\treturn glob.db.fetch(\"SELECT 2fa_totp.userid FROM 2fa_totp WHERE userid = %(userid)s AND enabled = 1 LIMIT 1\", {\n\t\t\"userid\": userID\n\t}) is not None\n\ndef check2FA(userID, ip):\n\t\"\"\"\n\tReturns True if this IP is untrusted.\n\tReturns always False if 2fa is not enabled on `userID`\n\n\t:param userID: user id\n\t:param ip: IP address\n\t:return: True if untrusted, False if trusted or 2fa is disabled.\n\t\"\"\"\n\tif not is2FAEnabled(userID):\n\t\treturn False\n\n\tresult = glob.db.fetch(\"SELECT id FROM ip_user WHERE userid = %s AND ip = %s\", [userID, ip])\n\treturn True if result is None else False\n\ndef isAllowed(userID):\n\t\"\"\"\n\tCheck if userID is not banned or restricted\n\n\t:param userID: user id\n\t:return: True if not banned or restricted, otherwise false.\n\t\"\"\"\n\tresult = glob.db.fetch(\"SELECT privileges FROM users WHERE id = %s LIMIT 1\", [userID])\n\tif result is not None:\n\t\treturn (result[\"privileges\"] & privileges.USER_NORMAL) and (result[\"privileges\"] & privileges.USER_PUBLIC)\n\telse:\n\t\treturn False\n\ndef isRestricted(userID):\n\t\"\"\"\n\tCheck if userID is restricted\n\n\t:param userID: user id\n\t:return: True if not restricted, otherwise false.\n\t\"\"\"\n\tresult = glob.db.fetch(\"SELECT privileges FROM users WHERE id = %s LIMIT 1\", [userID])\n\tif result is not None:\n\t\treturn (result[\"privileges\"] & privileges.USER_NORMAL) and not (result[\"privileges\"] & privileges.USER_PUBLIC)\n\telse:\n\t\treturn False\n\ndef isBanned(userID):\n\t\"\"\"\n\tCheck if userID is banned\n\n\t:param userID: user id\n\t:return: True if not banned, otherwise false.\n\t\"\"\"\n\tresult = glob.db.fetch(\"SELECT privileges FROM users WHERE id = %s LIMIT 1\", [userID])\n\tif result is not None:\n\t\treturn not (result[\"privileges\"] & 3 > 0)\n\telse:\n\t\treturn True\n\ndef isLocked(userID):\n\t\"\"\"\n\tCheck if userID is locked\n\n\t:param userID: user id\n\t:return: True if not locked, otherwise false.\n\t\"\"\"\n\tresult = glob.db.fetch(\"SELECT privileges FROM users WHERE id = %s LIMIT 1\", [userID])\n\tif result is not None:\n\t\treturn (\n\t\t(result[\"privileges\"] & privileges.USER_PUBLIC > 0) and (result[\"privileges\"] & privileges.USER_NORMAL == 0))\n\telse:\n\t\treturn True\n\ndef ban(userID):\n\t\"\"\"\n\tBan userID\n\n\t:param userID: user id\n\t:return:\n\t\"\"\"\n\t# Set user as banned in db\n\tbanDateTime = int(time.time())\n\tglob.db.execute(\"UPDATE users SET privileges = privileges & %s, ban_datetime = %s WHERE id = %s LIMIT 1\",\n\t\t\t\t\t[~(privileges.USER_NORMAL | privileges.USER_PUBLIC), banDateTime, userID])\n\n\t# Notify bancho about the ban\n\tglob.redis.publish(\"peppy:ban\", userID)\n\n\t# Remove the user from global and country leaderboards\n\tremoveFromLeaderboard(userID)\n\ndef unban(userID):\n\t\"\"\"\n\tUnban userID\n\n\t:param userID: user id\n\t:return:\n\t\"\"\"\n\tglob.db.execute(\"UPDATE users SET privileges = privileges | %s, ban_datetime = 0 WHERE id = %s LIMIT 1\",\n\t\t\t\t\t[(privileges.USER_NORMAL | privileges.USER_PUBLIC), userID])\n\tglob.redis.publish(\"peppy:ban\", userID)\n\ndef restrict(userID):\n\t\"\"\"\n\tRestrict userID\n\n\t:param userID: user id\n\t:return:\n\t\"\"\"\n\tif not isRestricted(userID):\n\t\t# Set user as restricted in db\n\t\tbanDateTime = int(time.time())\n\t\tglob.db.execute(\"UPDATE users SET privileges = privileges & %s, ban_datetime = %s WHERE id = %s LIMIT 1\",\n\t\t\t\t\t\t[~privileges.USER_PUBLIC, banDateTime, userID])\n\n\t\t# Notify bancho about this ban\n\t\tglob.redis.publish(\"peppy:ban\", userID)\n\n\t\t# Remove the user from global and country leaderboards\n\t\tremoveFromLeaderboard(userID)\n\ndef unrestrict(userID):\n\t\"\"\"\n\tUnrestrict userID.\n\tSame as unban().\n\n\t:param userID: user id\n\t:return:\n\t\"\"\"\n\tunban(userID)\n\ndef appendNotes(userID, notes, addNl=True, trackDate=True):\n\t\"\"\"\n\tAppend `notes` to `userID`'s \"notes for CM\"\n\n\t:param userID: user id\n\t:param notes: text to append\n\t:param addNl: if True, prepend \\n to notes. Default: True.\n\t:param trackDate: if True, prepend date and hour to the note. Default: True.\n\t:return:\n\t\"\"\"\n\tif trackDate:\n\t\tnotes = \"[{}] {}\".format(generalUtils.getTimestamp(), notes)\n\tif addNl:\n\t\tnotes = \"\\n{}\".format(notes)\n\tglob.db.execute(\"UPDATE users SET notes=CONCAT(COALESCE(notes, ''),%s) WHERE id = %s LIMIT 1\", [notes, userID])\n\ndef getPrivileges(userID):\n\t\"\"\"\n\tReturn `userID`'s privileges\n\n\t:param userID: user id\n\t:return: privileges number\n\t\"\"\"\n\tresult = glob.db.fetch(\"SELECT privileges FROM users WHERE id = %s LIMIT 1\", [userID])\n\tif result is not None:\n\t\treturn result[\"privileges\"]\n\telse:\n\t\treturn 0\n\ndef getSilenceEnd(userID):\n\t\"\"\"\n\tGet userID's **ABSOLUTE** silence end UNIX time\n\tRemember to subtract time.time() if you want to get the actual silence time\n\n\t:param userID: user id\n\t:return: UNIX time\n\t\"\"\"\n\treturn glob.db.fetch(\"SELECT silence_end FROM users WHERE id = %s LIMIT 1\", [userID])[\"silence_end\"]\n\ndef silence(userID, seconds, silenceReason, author = 999):\n\t\"\"\"\n\tSilence someone\n\n\t:param userID: user id\n\t:param seconds: silence length in seconds\n\t:param silenceReason: silence reason shown on website\n\t:param author: userID of who silenced the user. Default: 999\n\t:return:\n\t\"\"\"\n\t# db qurey\n\tsilenceEndTime = int(time.time())+seconds\n\tglob.db.execute(\"UPDATE users SET silence_end = %s, silence_reason = %s WHERE id = %s LIMIT 1\", [silenceEndTime, silenceReason, userID])\n\n\t# Log\n\ttargetUsername = getUsername(userID)\n\t# TODO: exists check im drunk rn i need to sleep (stampa piede ubriaco confirmed)\n\tif seconds > 0:\n\t\tlog.rap(author, \"has silenced {} for {} seconds for the following reason: \\\"{}\\\"\".format(targetUsername, seconds, silenceReason), True)\n\telse:\n\t\tlog.rap(author, \"has removed {}'s silence\".format(targetUsername), True)\n\ndef getTotalScore(userID, gameMode):\n\t\"\"\"\n\tGet `userID`'s total score relative to `gameMode`\n\n\t:param userID: user id\n\t:param gameMode: game mode number\n\t:return: total score\n\t\"\"\"\n\tmodeForDB = gameModes.getGameModeForDB(gameMode)\n\treturn glob.db.fetch(\"SELECT total_score_\"+modeForDB+\" FROM users_stats WHERE id = %s LIMIT 1\", [userID])[\"total_score_\"+modeForDB]\n\ndef getAccuracy(userID, gameMode):\n\t\"\"\"\n\tGet `userID`'s average accuracy relative to `gameMode`\n\n\t:param userID: user id\n\t:param gameMode: game mode number\n\t:return: accuracy\n\t\"\"\"\n\tmodeForDB = gameModes.getGameModeForDB(gameMode)\n\treturn glob.db.fetch(\"SELECT avg_accuracy_\"+modeForDB+\" FROM users_stats WHERE id = %s LIMIT 1\", [userID])[\"avg_accuracy_\"+modeForDB]\n\ndef getGameRank(userID, gameMode):\n\t\"\"\"\n\tGet `userID`'s **in-game rank** (eg: #1337) relative to gameMode\n\n\t:param userID: user id\n\t:param gameMode: game mode number\n\t:return: game rank\n\t\"\"\"\n\tposition = glob.redis.zrevrank(\"ripple:leaderboard:{}\".format(gameModes.getGameModeForDB(gameMode)), userID)\n\tif position is None:\n\t\treturn 0\n\telse:\n\t\treturn int(position) + 1\n\ndef getGameRankRx(userID, gameMode):\n\t\"\"\"\n\tGet `userID`'s **in-game rank** (eg: #1337) relative to gameMode\n\t:param userID: user id\n\t:param gameMode: game mode number\n\t:return: game rank\n\t\"\"\"\n\tposition = glob.redis.zrevrank(\"ripple:leaderboard_relax:{}\".format(gameModes.getGameModeForDB(gameMode)), userID)\n\tif position is None:\n\t\treturn 0\n\telse:\n\t\treturn int(position) + 1\n\ndef getGameRankAP(userID, gameMode):\n\t\"\"\"\n\tGet `userID`'s **in-game rank** (eg: #1337) relative to gameMode\n\t:param userID: user id\n\t:param gameMode: game mode number\n\t:return: game rank\n\t\"\"\"\n\tposition = glob.redis.zrevrank(\"ripple:leaderboard_ap:{}\".format(gameModes.getGameModeForDB(gameMode)), userID) #REMEMBER TO ADD REDIS FOR THIS\n\tif position is None:\n\t\treturn 0\n\telse:\n\t\treturn int(position) + 1\n\ndef getPlaycount(userID, gameMode):\n\t\"\"\"\n\tGet `userID`'s playcount relative to `gameMode`\n\n\t:param userID: user id\n\t:param gameMode: game mode number\n\t:return: playcount\n\t\"\"\"\n\tmodeForDB = gameModes.getGameModeForDB(gameMode)\n\treturn glob.db.fetch(\"SELECT playcount_\"+modeForDB+\" FROM users_stats WHERE id = %s LIMIT 1\", [userID])[\"playcount_\"+modeForDB]\n\ndef getPlaycountRX(userID, gameMode):\n\t\"\"\"\n\tGet `userID`'s playcount relative to `gameMode`\n \n\t:param userID: user id\n\t:param gameMode: game mode number\n\t:return: playcount\n\t\"\"\"\n\tmodeForDB = gameModes.getGameModeForDB(gameMode)\n\treturn glob.db.fetch(\"SELECT playcount_\"+modeForDB+\" FROM rx_stats WHERE id = %s LIMIT 1\", [userID])[\"playcount_\"+modeForDB]\t\n\ndef getPlaycountAP(userID, gameMode):\n\t\"\"\"\n\tGet `userID`'s playcount relative to `gameMode`\n \n\t:param userID: user id\n\t:param gameMode: game mode number\n\t:return: playcount\n\t\"\"\"\n\tmodeForDB = gameModes.getGameModeForDB(gameMode)\n\treturn glob.db.fetch(\"SELECT playcount_\"+modeForDB+\" FROM ap_stats WHERE id = %s LIMIT 1\", [userID])[\"playcount_\"+modeForDB]\t\n\t\ndef getFriendList(userID):\n\t\"\"\"\n\tGet `userID`'s friendlist\n\n\t:param userID: user id\n\t:return: list with friends userIDs. [0] if no friends.\n\t\"\"\"\n\t# Get friends from db\n\tfriends = glob.db.fetchAll(\"SELECT user2 FROM users_relationships WHERE user1 = %s\", [userID])\n\n\tif friends is None or len(friends) == 0:\n\t\t# We have no friends, return 0 list\n\t\treturn [0]\n\telse:\n\t\t# Get only friends\n\t\tfriends = [i[\"user2\"] for i in friends]\n\n\t\t# Return friend IDs\n\t\treturn friends\n\ndef addFriend(userID, friendID):\n\t\"\"\"\n\tAdd `friendID` to `userID`'s friend list\n\n\t:param userID: user id\n\t:param friendID: new friend\n\t:return:\n\t\"\"\"\n\t# Make sure we aren't adding us to our friends\n\tif userID == friendID:\n\t\treturn\n\n\t# check user isn't already a friend of ours\n\tif glob.db.fetch(\"SELECT id FROM users_relationships WHERE user1 = %s AND user2 = %s LIMIT 1\", [userID, friendID]) is not None:\n\t\treturn\n\n\t# Set new value\n\tglob.db.execute(\"INSERT INTO users_relationships (user1, user2) VALUES (%s, %s)\", [userID, friendID])\n\ndef removeFriend(userID, friendID):\n\t\"\"\"\n\tRemove `friendID` from `userID`'s friend list\n\n\t:param userID: user id\n\t:param friendID: old friend\n\t:return:\n\t\"\"\"\n\t# Delete user relationship. We don't need to check if the relationship was there, because who gives a shit,\n\t# if they were not friends and they don't want to be anymore, be it. ¯\\_(ツ)_/¯\n\t# TODO: LIMIT 1\n\tglob.db.execute(\"DELETE FROM users_relationships WHERE user1 = %s AND user2 = %s\", [userID, friendID])\n\n\ndef getCountry(userID):\n\t\"\"\"\n\tGet `userID`'s country **(two letters)**.\n\n\t:param userID: user id\n\t:return: country code (two letters)\n\t\"\"\"\n\treturn glob.db.fetch(\"SELECT country FROM users_stats WHERE id = %s LIMIT 1\", [userID])[\"country\"]\n\ndef setCountry(userID, country):\n\t\"\"\"\n\tSet userID's country\n\n\t:param userID: user id\n\t:param country: country letters\n\t:return:\n\t\"\"\"\n\tglob.db.execute(\"UPDATE users_stats SET country = %s WHERE id = %s LIMIT 1\", [country, userID])\n\ndef logIP(userID, ip):\n\t\"\"\"\n\tUser IP log\n\tUSED FOR MULTIACCOUNT DETECTION\n\n\t:param userID: user id\n\t:param ip: IP address\n\t:return:\n\t\"\"\"\n\tglob.db.execute(\"\"\"INSERT INTO ip_user (userid, ip, occurencies) VALUES (%s, %s, 1)\n\t\t\t\t\t\tON DUPLICATE KEY UPDATE occurencies = occurencies + 1\"\"\", [userID, ip])\n\ndef saveBanchoSession(userID, ip):\n\t\"\"\"\n\tSave userid and ip of this token in redis\n\tUsed to cache logins on LETS requests\n\n\t:param userID: user ID\n\t:param ip: IP address\n\t:return:\n\t\"\"\"\n\tglob.redis.sadd(\"peppy:sessions:{}\".format(userID), ip)\n\ndef deleteBanchoSessions(userID, ip):\n\t\"\"\"\n\tDelete this bancho session from redis\n\n\t:param userID: user id\n\t:param ip: IP address\n\t:return:\n\t\"\"\"\n\tglob.redis.srem(\"peppy:sessions:{}\".format(userID), ip)\n\ndef setPrivileges(userID, priv):\n\t\"\"\"\n\tSet userID's privileges in db\n\n\t:param userID: user id\n\t:param priv: privileges number\n\t:return:\n\t\"\"\"\n\tglob.db.execute(\"UPDATE users SET privileges = %s WHERE id = %s LIMIT 1\", [priv, userID])\n\ndef getGroupPrivileges(groupName):\n\t\"\"\"\n\tReturns the privileges number of a group, by its name\n\n\t:param groupName: name of the group\n\t:return: privilege integer or `None` if the group doesn't exist\n\t\"\"\"\n\tgroupPrivileges = glob.db.fetch(\"SELECT privileges FROM privileges_groups WHERE name = %s LIMIT 1\", [groupName])\n\tif groupPrivileges is None:\n\t\treturn None\n\treturn groupPrivileges[\"privileges\"]\n\ndef isInPrivilegeGroup(userID, groupName):\n\t\"\"\"\n\tCheck if `userID` is in a privilege group.\n\tDonor privilege is ignored while checking for groups.\n\n\t:param userID: user id\n\t:param groupName: privilege group name\n\t:return: True if `userID` is in `groupName`, else False\n\t\"\"\"\n\tgroupPrivileges = getGroupPrivileges(groupName)\n\tif groupPrivileges is None:\n\t\treturn False\n\ttry:\n\t\tuserToken = glob.tokens.getTokenFromUserID(userID)\n\texcept AttributeError:\n\t\t# LETS compatibility\n\t\tuserToken = None\n\n\tif userToken is not None:\n\t\tuserPrivileges = userToken.privileges\n\telse:\n\t\tuserPrivileges = getPrivileges(userID)\n\treturn userPrivileges & groupPrivileges == groupPrivileges\n\ndef isInAnyPrivilegeGroup(userID, groups):\n\t\"\"\"\n\tChecks if a user is in at least one of the specified groups\n\n\t:param userID: id of the user\n\t:param groups: groups list or tuple\n\t:return: `True` if `userID` is in at least one of the specified groups, otherwise `False`\n\t\"\"\"\n\tuserPrivileges = getPrivileges(userID)\n\treturn any(\n\t\tuserPrivileges & x == x\n\t\tfor x in (\n\t\t\tgetGroupPrivileges(y) for y in groups\n\t\t) if x is not None\n\t)\n\ndef logHardware(userID, hashes, activation = False):\n\t\"\"\"\n\tHardware log\n\tUSED FOR MULTIACCOUNT DETECTION\n\n\n\t:param userID: user id\n\t:param hashes:\tPeppy's botnet (client data) structure (new line = \"|\", already split)\n\t\t\t\t\t[0] osu! version\n\t\t\t\t\t[1] plain mac addressed, separated by \".\"\n\t\t\t\t\t[2] mac addresses hash set\n\t\t\t\t\t[3] unique ID\n\t\t\t\t\t[4] disk ID\n\t:param activation: if True, set this hash as used for activation. Default: False.\n\t:return: True if hw is not banned, otherwise false\n\t\"\"\"\n\t# Make sure the strings are not empty\n\tfor i in hashes[2:5]:\n\t\tif i == \"\":\n\t\t\tlog.warning(\"Invalid hash set ({}) for user {} in HWID check\".format(hashes, userID), \"bunk\")\n\t\t\treturn False\n\n\t# Run some HWID checks on that user if he is not restricted\n\tif not isRestricted(userID):\n\t\t# Get username\n\t\tusername = getUsername(userID)\n\n\t\t# Get the list of banned or restricted users that have logged in from this or similar HWID hash set\n\t\tif hashes[2] == \"b4ec3c4334a0249dae95c284ec5983df\":\n\t\t\t# Running under wine, check by unique id\n\t\t\tlog.debug(\"Logging Linux/Mac hardware\")\n\t\t\tbanned = glob.db.fetchAll(\"\"\"SELECT users.id as userid, hw_user.occurencies, users.username FROM hw_user\n\t\t\t\tLEFT JOIN users ON users.id = hw_user.userid\n\t\t\t\tWHERE hw_user.userid != %(userid)s\n\t\t\t\tAND hw_user.unique_id = %(uid)s\n\t\t\t\tAND (users.privileges & 3 != 3)\"\"\", {\n\t\t\t\t\t\"userid\": userID,\n\t\t\t\t\t\"uid\": hashes[3],\n\t\t\t\t})\n\t\telse:\n\t\t\t# Running under windows, do all checks\n\t\t\tlog.debug(\"Logging Windows hardware\")\n\t\t\tbanned = glob.db.fetchAll(\"\"\"SELECT users.id as userid, hw_user.occurencies, users.username FROM hw_user\n\t\t\t\tLEFT JOIN users ON users.id = hw_user.userid\n\t\t\t\tWHERE hw_user.userid != %(userid)s\n\t\t\t\tAND hw_user.mac = %(mac)s\n\t\t\t\tAND hw_user.unique_id = %(uid)s\n\t\t\t\tAND hw_user.disk_id = %(diskid)s\n\t\t\t\tAND (users.privileges & 3 != 3)\"\"\", {\n\t\t\t\t\t\"userid\": userID,\n\t\t\t\t\t\"mac\": hashes[2],\n\t\t\t\t\t\"uid\": hashes[3],\n\t\t\t\t\t\"diskid\": hashes[4],\n\t\t\t\t})\n\n\t\tfor i in banned:\n\t\t\t# Get the total numbers of logins\n\t\t\ttotal = glob.db.fetch(\"SELECT COUNT(*) AS count FROM hw_user WHERE userid = %s LIMIT 1\", [userID])\n\t\t\t# and make sure it is valid\n\t\t\tif total is None:\n\t\t\t\tcontinue\n\t\t\ttotal = total[\"count\"]\n\n\t\t\t# Calculate 10% of total\n\t\t\tperc = (total*10)/100\n\n\t\t\tif i[\"occurencies\"] >= perc:\n\t\t\t\t# Now we check if have a bypass on.\n\t\t\t\tuser_data = glob.db.fetch(\n\t\t\t\t\tf\"SELECT bypass_hwid FROM users WHERE id = {userID} LIMIT 1\"\n\t\t\t\t)\n\n\t\t\t\t# If they are explicitly allowed to multiacc\n\t\t\t\tif user_data[\"bypass_hwid\"]:\n\t\t\t\t\tlog.warning(f\"Allowed user {userID} to bypass hwid check.\")\n\t\t\t\t\treturn True\n\n\t\t\t\t# If the banned user has logged in more than 10% of the times from this user, restrict this user\n\t\t\t\trestrict(userID)\n\t\t\t\tappendNotes(userID, \"Logged in from HWID ({hwid}) used more than 10% from user {banned} ({bannedUserID}), who is banned/restricted.\".format(\n\t\t\t\t\thwid=hashes[2:5],\n\t\t\t\t\tbanned=i[\"username\"],\n\t\t\t\t\tbannedUserID=i[\"userid\"]\n\t\t\t\t))\n\t\t\t\tlog.warning(\"**{user}** ({userID}) has been restricted because he has logged in from HWID _({hwid})_ used more than 10% from banned/restricted user **{banned}** ({bannedUserID}), **possible multiaccount**.\".format(\n\t\t\t\t\tuser=username,\n\t\t\t\t\tuserID=userID,\n\t\t\t\t\thwid=hashes[2:5],\n\t\t\t\t\tbanned=i[\"username\"],\n\t\t\t\t\tbannedUserID=i[\"userid\"]\n\t\t\t\t), \"cm\")\n\n\t# Update hash set occurencies\n\tglob.db.execute(\"\"\"\n\t\t\t\tINSERT INTO hw_user (id, userid, mac, unique_id, disk_id, occurencies) VALUES (NULL, %s, %s, %s, %s, 1)\n\t\t\t\tON DUPLICATE KEY UPDATE occurencies = occurencies + 1\n\t\t\t\t\"\"\", [userID, hashes[2], hashes[3], hashes[4]])\n\n\t# Optionally, set this hash as 'used for activation'\n\tif activation:\n\t\tglob.db.execute(\"UPDATE hw_user SET activated = 1 WHERE userid = %s AND mac = %s AND unique_id = %s AND disk_id = %s\", [userID, hashes[2], hashes[3], hashes[4]])\n\n\t# Access granted, abbiamo impiegato 3 giorni\n\t# We grant access even in case of login from banned HWID\n\t# because we call restrict() above so there's no need to deny the access.\n\treturn True\n\n\ndef resetPendingFlag(userID, success=True):\n\t\"\"\"\n\tRemove pending flag from an user.\n\n\t:param userID: user id\n\t:param success: if True, set USER_PUBLIC and USER_NORMAL flags too\n\t\"\"\"\n\tglob.db.execute(\"UPDATE users SET privileges = privileges & %s WHERE id = %s LIMIT 1\", [~privileges.USER_PENDING_VERIFICATION, userID])\n\tif success:\n\t\tglob.db.execute(\"UPDATE users SET privileges = privileges | %s WHERE id = %s LIMIT 1\", [(privileges.USER_PUBLIC | privileges.USER_NORMAL), userID])\n\ndef verifyUser(userID, hashes):\n\t\"\"\"\n\tActivate `userID`'s account.\n\n\t:param userID: user id\n\t:param hashes: \tPeppy's botnet (client data) structure (new line = \"|\", already split)\n\t\t\t\t\t[0] osu! version\n\t\t\t\t\t[1] plain mac addressed, separated by \".\"\n\t\t\t\t\t[2] mac addresses hash set\n\t\t\t\t\t[3] unique ID\n\t\t\t\t\t[4] disk ID\n\t:return: True if verified successfully, else False (multiaccount)\n\t\"\"\"\n\t# Check for valid hash set\n\tfor i in hashes[2:5]:\n\t\tif i == \"\":\n\t\t\tlog.warning(\"Invalid hash set ({}) for user {} while verifying the account\".format(str(hashes), userID), \"bunk\")\n\t\t\treturn False\n\n\t# Get username\n\tusername = getUsername(userID)\n\n\t# Make sure there are no other accounts activated with this exact mac/unique id/hwid\n\tif hashes[2] == \"b4ec3c4334a0249dae95c284ec5983df\" or hashes[4] == \"ffae06fb022871fe9beb58b005c5e21d\":\n\t\t# Running under wine, check only by uniqueid\n\t\tlog.info(f\"{username} ({userID}) ha triggerato Sannino\\nUsual wine mac address hash: b4ec3c4334a0249dae95c284ec5983df\\nUsual wine disk id: ffae06fb022871fe9beb58b005c5e21d\")\t\t\n\t\tlog.debug(\"Veryfing with Linux/Mac hardware\")\n\t\tmatch = glob.db.fetchAll(\"SELECT userid FROM hw_user WHERE unique_id = %(uid)s AND userid != %(userid)s AND activated = 1 LIMIT 1\", {\n\t\t\t\"uid\": hashes[3],\n\t\t\t\"userid\": userID\n\t\t})\n\telse:\n\t\t# Running under windows, full check\n\t\tlog.debug(\"Veryfing with Windows hardware\")\n\t\tmatch = glob.db.fetchAll(\"SELECT userid FROM hw_user WHERE mac = %(mac)s AND unique_id = %(uid)s AND disk_id = %(diskid)s AND userid != %(userid)s AND activated = 1 LIMIT 1\", {\n\t\t\t\"mac\": hashes[2],\n\t\t\t\"uid\": hashes[3],\n\t\t\t\"diskid\": hashes[4],\n\t\t\t\"userid\": userID\n\t\t})\n\n\tif match:\n\t\t# This is a multiaccount, restrict other account and ban this account\n\n\t\t# Get original userID and username (lowest ID)\n\t\toriginalUserID = match[0][\"userid\"]\n\t\toriginalUsername = getUsername(originalUserID)\n\n\t\t# Now we check if have a bypass on.\n\t\tuser_data = glob.db.fetch(\n\t\t\tf\"SELECT bypass_hwid FROM users WHERE id = {userID} LIMIT 1\"\n\t\t)\n\n\t\t# If they are explicitly allowed to multiacc\n\t\tif user_data[\"bypass_hwid\"]:\n\t\t\tlog.warning(f\"Allowed user {username} to bypass hwid check.\")\n\t\t\treturn True\n\n\t\t# Ban this user and append notes\n\t\tban(userID)\t# this removes the USER_PENDING_VERIFICATION flag too\n\t\tappendNotes(userID, \"{}'s multiaccount ({}), found HWID match while verifying account ({})\".format(originalUsername, originalUserID, hashes[2:5]))\n\t\tappendNotes(originalUserID, \"Has created multiaccount {} ({})\".format(username, userID))\n\n\t\t# Restrict the original\n\t\trestrict(originalUserID)\n\n\t\t# Discord message\n\t\tlog.warning(\"User **{originalUsername}** ({originalUserID}) has been restricted because he has created multiaccount **{username}** ({userID}). The multiaccount has been banned.\".format(\n\t\t\toriginalUsername=originalUsername,\n\t\t\toriginalUserID=originalUserID,\n\t\t\tusername=username,\n\t\t\tuserID=userID\n\t\t), \"cm\")\n\n\t\t# Disallow login\n\t\treturn False\n\telse:\n\t\t# No matches found, set USER_PUBLIC and USER_NORMAL flags and reset USER_PENDING_VERIFICATION flag\n\t\tresetPendingFlag(userID)\n\t\t\n\t\t# Allow login\n\t\treturn True\n\ndef hasVerifiedHardware(userID):\n\t\"\"\"\n\tChecks if `userID` has activated his account through HWID\n\n\t:param userID: user id\n\t:return: True if hwid activation data is in db, otherwise False\n\t\"\"\"\n\tdata = glob.db.fetch(\"SELECT id FROM hw_user WHERE userid = %s AND activated = 1 LIMIT 1\", [userID])\n\tif data is not None:\n\t\treturn True\n\treturn False\n\ndef getDonorExpire(userID):\n\t\"\"\"\n\tReturn `userID`'s donor expiration UNIX timestamp\n\n\t:param userID: user id\n\t:return: donor expiration UNIX timestamp\n\t\"\"\"\n\tdata = glob.db.fetch(\"SELECT donor_expire FROM users WHERE id = %s LIMIT 1\", [userID])\n\tif data is not None:\n\t\treturn data[\"donor_expire\"]\n\treturn 0\n\n\nclass invalidUsernameError(Exception):\n\tpass\n\nclass usernameAlreadyInUseError(Exception):\n\tpass\n\ndef safeUsername(username):\n\t\"\"\"\n\tReturn `username`'s safe username\n\t(all lowercase and underscores instead of spaces)\n\n\t:param username: unsafe username\n\t:return: safe username\n\t\"\"\"\n\treturn username.lower().strip().replace(\" \", \"_\")\n\ndef changeUsername(userID=0, oldUsername=\"\", newUsername=\"\"):\n\t\"\"\"\n\tChange `userID`'s username to `newUsername` in database\n\n\t:param userID: user id. Required only if `oldUsername` is not passed.\n\t:param oldUsername: username. Required only if `userID` is not passed.\n\t:param newUsername: new username. Can't contain spaces and underscores at the same time.\n\t:raise: invalidUsernameError(), usernameAlreadyInUseError()\n\t:return:\n\t\"\"\"\n\t# Make sure new username doesn't have mixed spaces and underscores\n\tif \" \" in newUsername and \"_\" in newUsername:\n\t\traise invalidUsernameError()\n\n\t# Get safe username\n\tnewUsernameSafe = safeUsername(newUsername)\n\n\t# Make sure this username is not already in use\n\tif getIDSafe(newUsernameSafe) is not None:\n\t\traise usernameAlreadyInUseError()\n\n\t# Get userID or oldUsername\n\tif userID == 0:\n\t\tuserID = getID(oldUsername)\n\telse:\n\t\toldUsername = getUsername(userID)\n\n\t# Change username\n\tglob.db.execute(\"UPDATE users SET username = %s, username_safe = %s WHERE id = %s LIMIT 1\", [newUsername, newUsernameSafe, userID])\n\tglob.db.execute(\"UPDATE users_stats SET username = %s WHERE id = %s LIMIT 1\", [newUsername, userID])\n\n\t# Empty redis username cache\n\t# TODO: Le pipe woo woo\n\tglob.redis.delete(\"ripple:userid_cache:{}\".format(safeUsername(oldUsername)))\n\tglob.redis.delete(\"ripple:change_username_pending:{}\".format(userID))\n\ndef removeFromLeaderboard(userID):\n\t\"\"\"\n\tRemoves userID from global and country leaderboards.\n\n\t:param userID:\n\t:return:\n\t\"\"\"\n\t# Remove the user from global and country leaderboards, for every mode\n\tcountry = getCountry(userID).lower()\n\tfor mode in [\"std\", \"taiko\", \"ctb\", \"mania\"]:\n\t\tglob.redis.zrem(\"ripple:leaderboard:{}\".format(mode), str(userID))\n\t\tglob.redis.zrem(\"ripple:leaderboard_relax:{}\".format(mode), str(userID))\n\t\tglob.redis.zrem(\"ripple:leaderboard_ap:{}\".format(mode), str(userID))\n\t\tif country is not None and len(country) > 0 and country != \"xx\":\n\t\t\tglob.redis.zrem(\"ripple:leaderboard:{}:{}\".format(mode, country), str(userID))\n\t\t\tglob.redis.zrem(\"ripple:leaderboard_relax:{}:{}\".format(mode, country), str(userID))\n\t\t\tglob.redis.zrem(\"ripple:leaderboard_ap:{}:{}\".format(mode, country), str(userID))\n\ndef deprecateTelegram2Fa(userID):\n\t\"\"\"\n\tChecks whether the user has enabled telegram 2fa on his account.\n\tIf so, disables 2fa and returns True.\n\tIf not, return False.\n\n\t:param userID: id of the user\n\t:return: True if 2fa has been disabled from the account otherwise False\n\t\"\"\"\n\ttry:\n\t\ttelegram2Fa = glob.db.fetch(\"SELECT id FROM 2fa_telegram WHERE userid = %s LIMIT 1\", (userID,))\n\texcept ProgrammingError:\n\t\t# The table doesnt exist\n\t\treturn False\n\n\tif telegram2Fa is not None:\n\t\tglob.db.execute(\"DELETE FROM 2fa_telegram WHERE userid = %s LIMIT 1\", (userID,))\n\t\treturn True\n\treturn False\n\ndef unlockAchievement(userID, achievementID):\n\tglob.db.execute(\"INSERT INTO users_achievements (user_id, achievement_id, `time`) VALUES\"\n\t\t\t\t\t\"(%s, %s, %s)\", [userID, achievementID, int(time.time())])\n\ndef getAchievementsVersion(userID):\n\tresult = glob.db.fetch(\"SELECT achievements_version FROM users WHERE id = %s LIMIT 1\", [userID])\n\tif result is None:\n\t\treturn None\n\treturn result[\"achievements_version\"]\n\ndef updateAchievementsVersion(userID):\n\tglob.db.execute(\"UPDATE users SET achievements_version = %s WHERE id = %s LIMIT 1\", [\n\t\tglob.ACHIEVEMENTS_VERSION, userID\n\t])\n\ndef getClan(userID):\n\t\"\"\"\n\tGet userID's clan\n\t\n\t:param userID: user id\n\t:return: username or None\n\t\"\"\"\n\tclanInfo = glob.db.fetch(\"SELECT clans.tag, clans.id, user_clans.clan, user_clans.user FROM user_clans LEFT JOIN clans ON clans.id = user_clans.clan WHERE user_clans.user = %s LIMIT 1\", [userID])\n\tusername = getUsername(userID)\n\t\n\tif clanInfo is None:\n\t\treturn username\n\treturn \"[\" + clanInfo[\"tag\"] + \"] \" + username\n\ndef updateTotalHits(userID=0, gameMode=gameModes.STD, newHits=0, score=None):\n\tif score is None and userID == 0:\n\t\traise ValueError(\"Either score or userID must be provided\")\n\tif score is not None:\n\t\tnewHits = score.c50 + score.c100 + score.c300\n\t\tgameMode = score.gameMode\n\t\tuserID = score.playerUserID\n\tglob.db.execute(\n\t\t\"UPDATE users_stats SET total_hits_{gm} = total_hits_{gm} + %s WHERE id = %s LIMIT 1\".format(\n\t\t\tgm=gameModes.getGameModeForDB(gameMode)\n\t\t),\n\t\t(newHits, userID)\n\t)\n\ndef updateTotalHitsRX(userID=0, gameMode=gameModes.STD, newHits=0, score=None):\n\tif score is None and userID == 0:\n\t\traise ValueError(\"Either score or userID must be provided\")\n\tif score is not None:\n\t\tnewHits = score.c50 + score.c100 + score.c300\n\t\tgameMode = score.gameMode\n\t\tuserID = score.playerUserID\n\tglob.db.execute(\n\t\t\"UPDATE rx_stats SET total_hits_{gm} = total_hits_{gm} + %s WHERE id = %s LIMIT 1\".format(\n\t\t\tgm=gameModes.getGameModeForDB(gameMode)\n\t\t),\n\t\t(newHits, userID)\n\t)\n\ndef updateTotalHitsAP(userID=0, gameMode=gameModes.STD, newHits=0, score=None):\n\tif score is None and userID == 0:\n\t\traise ValueError(\"Either score or userID must be provided\")\n\tif score is not None:\n\t\tnewHits = score.c50 + score.c100 + score.c300\n\t\tgameMode = score.gameMode\n\t\tuserID = score.playerUserID\n\tglob.db.execute(\n\t\t\"UPDATE ap_stats SET total_hits_{gm} = total_hits_{gm} + %s WHERE id = %s LIMIT 1\".format(\n\t\t\tgm=gameModes.getGameModeForDB(gameMode)\n\t\t),\n\t\t(newHits, userID)\n\t)\n","sub_path":"ripple/userUtils.py","file_name":"userUtils.py","file_ext":"py","file_size_in_byte":53941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"622912739","text":"from classes import *\r\nfrom logger import *\r\nfrom load_config import Load\r\n\r\nclass Battlefield:\r\n def __init__(self, army1=None, army2=None):\r\n self.army1 = army1\r\n self.army2 = army2\r\n\r\n def load_from_config(self):\r\n data = Load()\r\n data1 = data[\"Army1\"]\r\n data2 = data[\"Army2\"]\r\n\r\n self.army1 = Army(data1['Strategy'], data1['Name'], data1['Squads_count'])\r\n for sq in self.army1.squads:\r\n sq.units = get_list(Soldier, data1['Soldiers_in_squad'])\r\n sq.units.extend(get_list(Vehicle, data1['Vehicles_in_squad']))\r\n \r\n self.army2 = Army(data2['Strategy'], data2['Name'], data2['Squads_count'])\r\n for sq in self.army2.squads:\r\n sq.units = get_list(Soldier, data2['Soldiers_in_squad'])\r\n sq.units.extend(get_list(Vehicle, data2['Vehicles_in_squad']))\r\n \r\n def battle(self):\r\n count = 1\r\n logger = Logger(count, self.army1, self.army2)\r\n\r\n r = random.choice([0,1])\r\n if r == 0:\r\n attacking_side = self.army1\r\n defending_side = self.army2\r\n else:\r\n attacking_side = self.army2\r\n defending_side = self.army1\r\n \r\n while self.army1.can_fight() or self.army2.can_fight():\r\n \r\n if not self.army1.can_fight():\r\n print('Army %s' % self.army2.name + ' is winner')\r\n break\r\n if not self.army2.can_fight():\r\n print('Army %s' % self.army1.name + ' is winner')\r\n break\r\n \r\n attacking_side.attack(defending_side)\r\n \r\n logger.log(count, attacking_side.name)\r\n\r\n attacking_side, defending_side = defending_side, attacking_side\r\n\r\n count += 1\r\n","sub_path":"battlefield.py","file_name":"battlefield.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"222819921","text":"#\n# Copyright (c) 2008-2015 Thierry Florac \n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n\n__docformat__ = 'restructuredtext'\n\n\n# import standard packages\nfrom datetime import datetime\n\n# import interfaces\n\n# import packages\nfrom pyams_utils.request import check_request\nfrom pyams_utils.timezone import gmtime, tztime\nfrom zope.datetime import parseDatetimetz\n\nfrom pyams_utils import _\n\n\ndef unidate(value):\n \"\"\"Get specified date converted to unicode ISO format\n \n Dates are always assumed to be stored in GMT timezone\n \n @param value: input date to convert to unicode\n @type value: date or datetime\n @return: input date converted to unicode\n @rtype: unicode\n \"\"\"\n if value is not None:\n value = gmtime(value)\n return value.isoformat('T')\n return None\n\n\ndef parse_date(value):\n \"\"\"Get date specified in unicode ISO format to Python datetime object\n \n Dates are always assumed to be stored in GMT timezone\n \n @param value: unicode date to be parsed\n @type value: unicode\n @return: the specified value, converted to datetime\n @rtype: datetime\n \"\"\"\n if value is not None:\n return gmtime(parseDatetimetz(value))\n return None\n\n\ndef date_to_datetime(value):\n \"\"\"Get datetime value converted from a date or datetime object\n \n @param value: a date or datetime value to convert\n @type value: date or datetime\n @return: input value converted to datetime\n @rtype: datetime\n \"\"\"\n if not value:\n return None\n if type(value) is datetime:\n return value\n return datetime(value.year, value.month, value.day)\n\n\nSH_DATE_FORMAT = _(\"%d/%m/%Y\")\nSH_DATETIME_FORMAT = _(\"%d/%m/%Y - %H:%M\")\n\nEXT_DATE_FORMAT = _(\"on %d/%m/%Y\")\nEXT_DATETIME_FORMAT = _(\"on %d/%m/%Y at %H:%M\")\n\n\ndef format_date(value, format=EXT_DATE_FORMAT, request=None):\n \"\"\"Format given date with the given format\"\"\"\n if not value:\n return '--'\n if request is None:\n request = check_request()\n localizer = request.localizer\n return datetime.strftime(tztime(value), localizer.translate(format))\n\n\ndef format_datetime(value, format=EXT_DATETIME_FORMAT, request=None):\n \"\"\"Format given datetime with the given format\"\"\"\n return format_date(value, format, request)\n\n\ndef get_age(value):\n \"\"\"Get age of a given datetime (including timezone) compared to current datetime (in UTC)\n \n @param value: a datetime value, including timezone\n @type value: datetime\n @return: string representing value age\n @rtype: gettext translated string\n \"\"\"\n request = check_request()\n translate = request.localizer.translate\n now = gmtime(datetime.utcnow())\n delta = now - value\n if delta.days > 60:\n return translate(_(\"%d months ago\")) % int(round(delta.days * 1.0 / 30))\n elif delta.days > 10:\n return translate(_(\"%d weeks ago\")) % int(round(delta.days * 1.0 / 7))\n elif delta.days > 2:\n return translate(_(\"%d days ago\")) % delta.days\n elif delta.days == 2:\n return translate(_(\"the day before yesterday\"))\n elif delta.days == 1:\n return translate(_(\"yesterday\"))\n else:\n hours = int(round(delta.seconds * 1.0 / 3600))\n if hours > 1:\n return translate(_(\"%d hours ago\")) % hours\n elif delta.seconds > 300:\n return translate(_(\"%d minutes ago\")) % int(round(delta.seconds * 1.0 / 60))\n else:\n return translate(_(\"less than 5 minutes ago\"))\n\n\ndef get_duration(v1, v2=None, request=None):\n \"\"\"Get delta as string between two dates\n\n >>> from datetime import datetime\n >>> from pyams_utils.date import get_duration\n >>> from pyramid.testing import DummyRequest\n >>> request = DummyRequest()\n >>> date1 = datetime(2015, 1, 1)\n >>> date2 = datetime(2014, 3, 1)\n >>> get_duration(date1, date2, request)\n '10 months'\n\n Dates order is not important:\n >>> get_duration(date2, date1, request)\n '10 months'\n >>> date2 = datetime(2014, 11, 10)\n >>> get_duration(date1, date2, request)\n '7 weeks'\n >>> date2 = datetime(2014, 12, 26)\n >>> get_duration(date1, date2, request)\n '6 days'\n\n For durations lower than 2 days, duration also display hours:\n >>> date1 = datetime(2015, 1, 1)\n >>> date2 = datetime(2015, 1, 2, 15, 10, 0)\n >>> get_duration(date1, date2, request)\n '1 day and 15 hours'\n >>> date2 = datetime(2015, 1, 2)\n >>> get_duration(date1, date2, request)\n '24 hours'\n >>> date2 = datetime(2015, 1, 1, 13, 12)\n >>> get_duration(date1, date2, request)\n '13 hours'\n >>> date2 = datetime(2015, 1, 1, 1, 15)\n >>> get_duration(date1, date2, request)\n '75 minutes'\n >>> date2 = datetime(2015, 1, 1, 0, 0, 15)\n >>> get_duration(date1, date2, request)\n '15 seconds'\n \"\"\"\n if v2 is None:\n v2 = datetime.utcnow()\n assert isinstance(v1, datetime) and isinstance(v2, datetime)\n if request is None:\n request = check_request()\n translate = request.localizer.translate\n v1, v2 = min(v1, v2), max(v1, v2)\n delta = v2 - v1\n if delta.days > 60:\n return translate(_(\"%d months\")) % int(round(delta.days * 1.0 / 30))\n elif delta.days > 10:\n return translate(_(\"%d weeks\")) % int(round(delta.days * 1.0 / 7))\n elif delta.days >= 2:\n return translate(_(\"%d days\")) % delta.days\n else:\n hours = int(round(delta.seconds * 1.0 / 3600))\n if delta.days == 1:\n if hours == 0:\n return translate(_(\"24 hours\"))\n else:\n return translate(_(\"%d day and %d hours\")) % (delta.days, hours)\n else:\n if hours > 2:\n return translate(_(\"%d hours\")) % hours\n else:\n minutes = int(round(delta.seconds * 1.0 / 60))\n if minutes > 2:\n return translate(_(\"%d minutes\")) % minutes\n else:\n return translate(_(\"%d seconds\")) % delta.seconds\n","sub_path":"src/pyams_utils/date.py","file_name":"date.py","file_ext":"py","file_size_in_byte":6391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"174040525","text":"class Solution:\n # Combos:\n # 1) Grow time larger\n # 2) Grow time smaller\n # 3) Max time larger\n # 4) Max time smaller\n\n # plant, grow\n # [(1, 4), (1, 3)] grow> max> -> pick >grow\n # [(1, 5), (3, 4)] grow> max< -> pick >grow\n # [(4, 4), (1, 5)] grow< max> -> pick >grow\n # [(1, 4), (1, 5)] grow< max< -> pick > grow\n\n def earliestFullBloom(self, plantTime: List[int], growTime: List[int]) -> int:\n n = len(plantTime)\n if n == 1: return plantTime[0] + growTime[0]\n # (plant, grow)\n times = []\n for i in range(n):\n times.append((plantTime[i], growTime[i]))\n times.sort(key = lambda x: x[1], reverse=True)\n\n curEnd = 0\n startTime = 0\n for time in times:\n plantTime, growTime = time\n curEnd = max(startTime + plantTime + growTime, curEnd)\n startTime += plantTime\n return curEnd\n \n","sub_path":"leetcode/2136.earliest-possible-day-of-full-bloom/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"132582194","text":"# 5. Выполнить пинг веб-ресурсов yandex.ru, youtube.com и преобразовать результаты из байтовового\n# в строковый тип на кириллице.\n\nfrom subprocess import Popen, PIPE\n\nargs = ['ping', 'yandex.ru']\n\nsubproc_ping = Popen(args, stdout=PIPE)\nfor line in subproc_ping.stdout:\n line = line.decode('cp866').encode('utf-8')\n print(line.decode('utf-8'), end='')\n\n\nargs = ['ping', 'youtube.com']\n\nsubproc_ping = Popen(args, stdout=PIPE)\nfor line in subproc_ping.stdout:\n line = line.decode('cp866')\n print(line, end='')\n\nwith Popen(args=['ipconfig', '/all'], stdout=PIPE) as proc:\n for line in proc.stdout:\n line = line.decode('cp866')\n print(line, end='')\n","sub_path":"HW_1/5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"402270108","text":"# Tampere University of Technology, study material\n\n# Release: 03.2020\n\n# © 2020 All rights reserved for Tampere University of Technology\n\n# This program is developed at Tampere university of technology for the purpose of study and it´s personnel only.\n# The program is example for quick checking of structural engineering design and for repeating bulk work, and is not a\n# substitute for engineering judgment. This software study material and has been created based on general engineering\n# judgement and with best intentions. However, there may be bugs, errors and false assumptions\n# in the software algorithm. By using this software, the student/teacher/user confirms to\n# have understood the possibility of the existence of errors and inaccuracies in the results.\n# When using this software, the student/teacher/user must always be critical and use engineering judgement based on\n# good understanding of the theoretical background of the calculations performed by this program, and always\n# cross-check the results with hand-calculations or those of other methods.\n#\n# In no event will the developers of this program be liable for any indirect, punitive, special,\n# incidental or consequential damages.\n\nimport csv\nimport codecs\nfrom collections import defaultdict\nfrom pathlib import Path\nimport math\nimport time\n\ndef degrees_to_radians(x):\n return math.radians(x)\n\n\ndef cot(x):\n return 1 / math.tan(x)\n\n\ndef get_dimensions(max_value, min_value, step):\n values = []\n indexes_count = math.ceil((max_value - min_value) / step) + 1\n\n for value in range(indexes_count):\n values.append(value * step + min_value)\n\n return values\n\n\ndef has_same_dimensions(comb1, comb2):\n if comb1.H == comb2.H and comb1.B == comb2.B and comb1.L == comb2.L:\n return True\n return False\n\n\nclass Reaction(object):\n \"\"\"Node reactions and forces store class.\"\"\"\n\n def __init__(self, mx, my, mz, fx, fy, fz, case_name, id):\n self.Mx = mx\n self.My = my\n self.Mz = mz\n self.Fx = fx\n self.Fy = fy\n self.Fz = fz\n self.case_name = case_name\n self.parent_id = id\n\n def __str__(self):\n return 'Node: {} reactions, case name: {}'.format(self.parent_id, self.case_name)\n\n @property\n def ex(self):\n if self.Fz != 0.0:\n return abs(self.Mx / self.Fz)\n return abs(self.Mx / 0.001)\n\n @property\n def ey(self):\n if self.Fz != 0.0:\n return abs(self.My / self.Fz)\n return abs(self.My / 0.001)\n\n @property\n def loadcase_type(self):\n if 'CHR' in self.case_name:\n return 'SLS:CHR'\n elif 'QPR' in self.case_name:\n return 'SLS:QPR'\n elif 'ULS' in self.case_name:\n return 'ULS'\n elif 'FIRE' in self.case_name:\n return 'FIRE'\n elif 'FRE' in self.case_name:\n return 'SLS:FRE'\n\n\nclass Reactions(object):\n \"\"\"Collection class of node Reactions.\n Helps us to gets max/min forces of node.\n \"\"\"\n\n def __init__(self):\n self._reactions = []\n\n def __iter__(self):\n for elem in self._reactions:\n yield elem\n\n def __len__(self):\n \"\"\"List length\"\"\"\n return len(self._reactions)\n\n def __getitem__(self, ii):\n \"\"\"Get a list item\"\"\"\n return self._reactions[ii]\n\n def __delitem__(self, ii):\n \"\"\"Delete an item\"\"\"\n del self._reactions[ii]\n\n def __setitem__(self, ii, val):\n # optional: self._acl_check(val)\n self._reactions[ii] = val\n\n def __str__(self):\n return str(self._reactions)\n\n def append(self, val):\n self._reactions.append(val)\n\n def sort(self):\n self._reactions.sort(key=lambda x: max(x.ex, x.ey), reverse=True)\n\n\nclass RobotImporter:\n\n @staticmethod\n def import_nodes(nodes_filename):\n\n print('Importing slab nodes from file: {}'.format(nodes_filename))\n # Our csv-reader which reads nodes.-csv file, delimiter in csv-file is ;\n csv_reader = csv.reader(codecs.open(nodes_filename, 'rU', 'utf-16'), delimiter=';')\n index = 0\n support_nodes = []\n list_of_node_ids = []\n for row in csv_reader:\n # We skip the first row, because first row contains the headers.\n if index is not 0:\n first_cell = row[0]\n node_id = str(first_cell.split('/')[0])\n\n if not list_of_node_ids.__contains__(node_id):\n node_x = float(row[7].replace(',', '.'))\n node_y = float(row[8].replace(',', '.'))\n node_z = float(row[9].replace(',', '.'))\n\n # we store node from row to new node list.\n support_nodes.append(PadFoundationCalculation(node_id=node_id, x=node_x, y=node_y, z=node_z))\n list_of_node_ids.append(node_id)\n else:\n index = index + 1\n\n csv_reader = csv.reader(codecs.open(nodes_filename, 'rU', 'utf-16'), delimiter=';')\n forces = []\n index = 0\n for row in csv_reader:\n # We skip the first row\n if index is not 0:\n # We can catch node id by splitting string. [first_row cell look like this: 20/ 1/ SLS:CHR+;]\n first_cell = row[0]\n node_id = str(first_cell.split('/')[0])\n\n # In Csv file we replace , with . to parse string-type to float-type.\n fx = float(row[1].replace(',', '.'))\n fy = float(row[2].replace(',', '.'))\n fz = float(row[3].replace(',', '.'))\n mx = float(row[4].replace(',', '.'))\n my = float(row[5].replace(',', '.'))\n mz = float(row[6].replace(',', '.'))\n\n case_name = str(row[10])\n\n # and we add new ShellNodeForce object to our all forces list.\n forces.append(Reaction(mx=mx, my=my, mz=mz, fx=fx, fy=fy, fz=fz, case_name=case_name, id=node_id))\n\n else:\n index += 1\n\n # Grouping algorithm helps us to sort forces to given node id.\n # It will speed up sorting process.\n groups = defaultdict(list)\n for obj in forces:\n groups[obj.parent_id].append(obj)\n\n print('Groupping forces...')\n grouped_forces = groups.values()\n # now we add all forces to they parent robots nodes by id.\n for node in support_nodes:\n for group in grouped_forces:\n if group[0].parent_id == node.id:\n for force in group:\n node.reactions.append(force)\n\n # We had some problems in calculations with nodes that don´t have any forces singed to them,\n # here we do simple stupid fix for that, just add one zero force for node to help us\n # calculate nodes correctly\n\n for node in support_nodes:\n if len(node.reactions) == 0:\n node.reactions.append(Reaction(mx=0, my=0, mz=0, fx=0, fy=0, fz=0, case_name='ULS SLS', id=node.id))\n\n # Finally we have list of node objects, which stores coordinate data and forces data.\n print('Nodes importing complete.')\n print('')\n return support_nodes\n\n\nclass PadFoundationCalculationSettings(object):\n def __init__(self):\n self.Hg = 1.2 # [m], foundation depth\n self.Hw = 1 # [m], water table depth\n self.Lc = 0.38 # [m], column/plate length\n self.Bp = 0.38 # [m], column/plate width\n\n self.Yt = 20.0 # [kN/m^3], filling ground material density\n self.Yp = 18.0 # [kN/m^3], dry density of subsoil\n self.Ypw = 10 # [kN/m^3], dry density of subsoil below water table\n self.Yc = 25.0 # [kN/m^3], concrete density\n self.Yw = 10.0 # [kN/M^2],\n\n self.phi = 34.9 # ground friction angle\n self.alpha = 0.0 # slope of pad foundation ground fill\n self.c = 0.0 # [kN/m^2], effective cohesion\n self.k = 90.0 # The angle between the resultant of the horizontal loads and the L-line\n self.beta = 0.0 # The slope of the ramp\n\n self.cnom_bottom = 50.0 # [mm], concrete cover bottom\n self.cnom_side = 30 # [mm], concrete cover side\n self.cnom_top = 30 # [mm], concrete cover top\n self.main_bar = 12 # [mm], main bar diameter\n\n\nclass PadFoundationDimensionCombination(object):\n def __init__(self, h, l, b, reactions):\n self.H = h\n self.B = b\n self.L = l\n self.reactions = reactions\n\n self.eccentricity_capacity_x = 0\n self.eccentricity_capacity_y = 0\n self.DA2_capacity = 0\n self.Rd_capacity = 0\n self.overturn_capacity = 0\n self.sag_capacity = 0\n\n self._is_valid = True\n self.checks = []\n self.checks.append(self.eccentricity_capacity_x)\n self.checks.append(self.eccentricity_capacity_y)\n self.checks.append(self.DA2_capacity)\n self.checks.append(self.Rd_capacity)\n self.checks.append(self.overturn_capacity)\n self.checks.append(self.sag_capacity)\n\n def __str__(self):\n return 'B={}m, L={}m, H={}m'.format(self.B, self.L, self.H)\n\n @property\n def volume(self):\n return self.B * self.L * self.H\n\n @property\n def max_capacity(self):\n return max([c for c in self.checks])\n\n @property\n def is_valid(self):\n return self._is_valid\n\n def set_calculation_is_invalid(self):\n self._is_valid = False\n\n @property\n def is_ok(self):\n for check in self.checks:\n if check > 1:\n return False\n return True\n\n def calculate(self, settings):\n\n Hg = settings.Hg # [m], foundation depth\n Hw = settings.Hw # [m], water table depth\n Lc = settings.Lc # [m], column/plate length\n Bp = settings.Bp # [m], column/plate width\n\n Yt = settings.Yt # [kN/m^3], filling ground material density\n YP = settings.Yp # [kN/m^3], dry density of subsoil\n Ypw = settings.Ypw # [kN/m^3], dry density of subsoil below water table\n Yc = settings.Yc # [kN/m^3], concrete density\n\n phi = degrees_to_radians(settings.phi) # ground friction angle\n alpha = degrees_to_radians(settings.alpha) # slope of pad foundation ground fill\n c = settings.c # [kN/m^2], effective cohesion\n k = settings.k # The angle between the resultant of the horizontal loads and the L-line\n beta = settings.beta\n y_R_h = 1.1\n\n # Eccentricity check\n H = self.H # [m], pad foundation height\n B = self.B # [m], pad foundation width, x-direction\n L = self.L # [m], pad foundation length, y-direction\n V = H * B * L # [m^3], pad foundation volume\n Qpf = V * Yc # [kN], pad foundation own weight\n D = Hg - H # [m], depth of foundation\n\n cnom_bottom = settings.cnom_bottom / 1000 # [m], concrete cover bottom\n cnom_side = settings.cnom_side / 1000 # [m], concrete cover side\n cnom_top = settings.cnom_top / 1000 # [m], concrete cover top\n main_bar = settings.main_bar / 1000 # [m], main bar diameter\n\n db = H - cnom_bottom - 1.1 * main_bar / 2\n dl = H - cnom_bottom - 1.1 * (main_bar / 2 + main_bar)\n cb = B - Bp / 2\n cl = L - Lc / 2\n\n if B < Bp + 2 * db or B > Bp + 6 * db:\n self.set_calculation_is_invalid()\n return\n if L < Lc + 2 * dl or L > Lc + 6 * dl:\n self.set_calculation_is_invalid()\n return\n if cb < db or cl < dl:\n self.set_calculation_is_invalid()\n return\n\n for reaction in self.reactions:\n\n # Reactions\n My = reaction.My # [kNm]\n Mz = reaction.Mz # [kNm]\n Mx = reaction.Mx # [kNm]\n Fx = reaction.Fx # [kN]\n Fy = reaction.Fy # [kN]\n Fz = reaction.Fz + Qpf * V # [kN]\n\n if Fz < 0:\n self.set_calculation_is_invalid()\n break\n\n # eccentricities\n ex = abs(Mx) / abs(Fz)\n ey = abs(My) / abs(Fz)\n\n if ex / (B / 3) > self.eccentricity_capacity_x:\n self.eccentricity_capacity_x = ex / (B / 3)\n if self.eccentricity_capacity_x > 1:\n self.set_calculation_is_invalid()\n break\n\n if ey / (L / 3) > self.eccentricity_capacity_y:\n self.eccentricity_capacity_y = ey / (L / 3)\n if self.eccentricity_capacity_y > 1:\n self.set_calculation_is_invalid()\n break\n\n # ---------------------------------------------------------------------------------------\n\n # Ground pressure\n Beff = B - 2 * ex # [m], effective width\n Leff = L - 2 * ey # [m], effective length\n Aeff = Beff * Leff # [m^2], effective area\n\n if Leff < 0 or Beff < 0:\n self.set_calculation_is_invalid()\n break\n\n Peff_d = Fz / Aeff\n\n mB = (2 + (Beff / Leff)) / (1 + (Beff / Leff))\n mL = (2 + (Leff / Beff)) / (1 + (Leff / Beff))\n m = mL * math.cos(k) ** 2 + mB * math.sin(k) ** 2\n\n # Load factor depending on friction angle\n Nq = math.exp(math.pi * math.tan(phi)) * math.tan(degrees_to_radians(45.0) + phi / 2) ** 2\n Nc = (Nq - 1) * cot(phi)\n Ny = 2 * (Nq - 1) * math.tan(phi)\n\n # factor based on loading slope\n iq = math.pow(1 - H / (Fz + Aeff * c * cot(phi)), m)\n iy = math.pow(1 - H / (Fz + Aeff * c * cot(phi)), m + 1)\n ic = iq - (1 - iq) / (Nc * math.tan(phi))\n\n # Tension at the founding level\n q = Yt * D\n\n # Coefficient dependent on the shape of the foundation\n sq = 1 + (Beff / Leff) * math.sin(phi)\n sc = (sq * Nq - 1) / (Nq - 1)\n sy = 1 - 0.3 * (Beff / Leff)\n\n # Coefficient dependent on the slope of the foundation\n bq = (1 - alpha * math.tan(phi)) ** 2\n bc = bq - (1 - bq) / (Nc * math.tan(phi))\n by = bq\n\n if L > B:\n bl = Beff\n else:\n bl = Leff\n\n R_A = c * Nc * bc * sc * ic + q * Nq * bq * sq * iq + 0.5 * Ypw * bl * Ny * by * sy * iy\n\n g = math.pow(1 - 0.5 * math.tan(beta), 5)\n Rd_A = g * (R_A / 1.55)\n\n if Peff_d / Rd_A > 1 or Rd_A <= 0:\n self.set_calculation_is_invalid()\n break\n\n if Peff_d / Rd_A > self.DA2_capacity:\n self.DA2_capacity = Peff_d / Rd_A\n\n # ---------------------------------------------------------------------------------------\n\n # Slip resistance\n Vd = reaction.Fz + Qpf * V * 0.9\n Hd = math.sqrt(math.pow(abs(Fx), 2) + math.pow(abs(Fy), 2))\n Rd = (Vd * math.tan(phi)) / y_R_h\n\n if Rd <= 0 or Hd / Rd > 1:\n self.set_calculation_is_invalid()\n break\n\n if Hd / Rd > self.Rd_capacity:\n self.Rd_capacity = Hd / Rd\n\n # ---------------------------------------------------------------------------------------\n\n # Overturn\n Ved_std = reaction.Fz + Qpf * V * 0.9\n Estb_d_B = Ved_std * B / 2\n Estb_d_L = Ved_std * L / 2\n\n if Estb_d_B <= 0 or Estb_d_L <= 0:\n self.set_calculation_is_invalid()\n break\n\n Edst_d_B = abs(Mx)\n Edst_d_L = abs(My)\n\n ov = Edst_d_B / Estb_d_B + Edst_d_L / Estb_d_L\n\n if ov > 1:\n self.set_calculation_is_invalid()\n break\n if ov > self.overturn_capacity:\n self.overturn_capacity = ov\n\n # ---------------------------------------------------------------------------------------\n\n\nclass PadFoundationCalculation(object):\n\n def __init__(self, node_id, x, y, z):\n self.x = x\n self.y = y\n self.z = z\n self.id = node_id\n self.reactions = Reactions()\n self.minimal_combination = None\n self.possible_combinations = []\n self.possible_combination_pairs = []\n self.chosen_combination = None\n\n def __str__(self):\n return 'Node:{}, x={}m, y={}m, z={}m'.format(self.id, self.x, self.y, self.z)\n\n def calculate(self, settings):\n\n current_max_height = 2.4 # [m]\n current_min_height = 0.3 # [m]\n current_max_width = 4 # [m]\n current_min_width = 0.5 # [m]\n current_max_length = 4 # [m]\n current_min_length = 0.5 # [m]\n\n heights = get_dimensions(current_max_height, current_min_height, 0.05)\n widths = get_dimensions(current_max_width, current_min_width, 0.05)\n lengths = get_dimensions(current_max_length, current_min_length, 0.05)\n\n combinations = self.get_combinations(heights, widths, lengths)\n\n for comb in combinations:\n comb.calculate(settings)\n\n if comb.is_valid:\n if self.minimal_combination is None:\n self.minimal_combination = comb\n\n if self.minimal_combination.volume > comb.volume:\n self.minimal_combination = comb\n\n self.print_minimal_comb()\n\n def print_minimal_comb(self):\n word = str.format(\"Could not find dimension combination for node: {0}\", self.id)\n if self.minimal_combination is not None:\n word = str.format('Combination found: '\n 'B=' + str(round(self.minimal_combination.B, 3)) + 'm, '\n 'L=' + str(\n round(self.minimal_combination.L, 3)) + 'm, '\n 'H=' + str(round(self.minimal_combination.H, 3)) + 'm')\n print(word)\n print()\n\n def get_combinations(self, heights, widths, lengths):\n\n combs = []\n for H in heights:\n for B in widths:\n for L in lengths:\n combs.append(PadFoundationDimensionCombination(H, L, B, self.reactions))\n\n return combs\n\n\nclass PadFoundationAssembly(object):\n\n def __init__(self, supports):\n self.supports = supports\n\n def solve(self, settings):\n\n print('Nodes count: {}'.format(len(self.supports)))\n print('Sorting support reactions')\n for pad in self.supports:\n pad.reactions.sort()\n\n print('Nodes count: {}'.format(len(self.supports)))\n print('Starting calculation and counting time')\n start = time.time()\n for pad in self.supports:\n pad.calculate(settings)\n end = time.time()\n seconds = (end - start)\n print(\"Calculation ready, time: \" + str(seconds) + \"seconds.\")\n\n\nf1 = (Path().absolute() / 'support_results.csv').__str__()\n\n# Gets slab nodes from RobotImporter.\npad_foundations = RobotImporter.import_nodes(nodes_filename=f1)\n\n# Assembly of pad foundation which will solve combinations for us.\nassembly = PadFoundationAssembly(pad_foundations)\n\n# Calculation settings for pad foundation calculation.\ncalc_settings = PadFoundationCalculationSettings()\n\nassembly.solve(calc_settings)\n\nwith open('outputs_minimal.csv', mode='w', newline='') as my_results:\n fieldnames = ['id', 'x', 'y', 'z', 'H', 'L', 'B']\n writer = csv.DictWriter(my_results, fieldnames=fieldnames)\n writer.writeheader()\n for support in assembly.supports:\n writer.writerow({'id': support.id,\n 'x': support.x,\n 'y': support.y,\n 'z': support.z,\n 'H': support.minimal_combination.H,\n 'L': support.minimal_combination.L,\n 'B': support.minimal_combination.B})\n\nwith open('outputs_chosen.csv', mode='w', newline='') as my_results:\n fieldnames = ['id', 'x', 'y', 'z', 'H', 'L', 'B']\n writer = csv.DictWriter(my_results, fieldnames=fieldnames)\n writer.writeheader()\n for support in assembly.supports:\n if support.chosen_combination is None:\n writer.writerow({'id': support.id,\n 'x': support.x,\n 'y': support.y,\n 'z': support.z,\n 'H': support.minimal_combination.H,\n 'L': support.minimal_combination.L,\n 'B': support.minimal_combination.B})\n else:\n writer.writerow({'id': support.id,\n 'x': support.x,\n 'y': support.y,\n 'z': support.z,\n 'H': support.chosen_combination.H,\n 'L': support.chosen_combination.L,\n 'B': support.chosen_combination.B})\n\nprint('Calculation ready')\n","sub_path":"PadFoundationExample/ready/pad_foundation_calculation_v1.py","file_name":"pad_foundation_calculation_v1.py","file_ext":"py","file_size_in_byte":21340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"526676632","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('store', '0007_auto_20151015_0914'),\n ]\n\n operations = [\n migrations.DeleteModel(\n name='Student',\n ),\n migrations.AddField(\n model_name='category',\n name='description',\n field=models.TextField(default='category-description'),\n ),\n migrations.AddField(\n model_name='course',\n name='description',\n field=models.TextField(default='course-description'),\n ),\n ]\n","sub_path":"store/migrations/0008_auto_20151031_1852.py","file_name":"0008_auto_20151031_1852.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"541569154","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 1 14:38:44 2019\n\n@author: rstreet\n\"\"\"\n\nfrom os import getcwd, path\nfrom sys import path as systempath\ncwd = getcwd()\nsystempath.append(path.join(cwd,'../'))\nimport numpy as np\nfrom scipy import stats\nimport finite_source_point_lens_feature as feature\nfrom matplotlib import pyplot as plt\n\ndef test_finite_source_point_lens_feature():\n \"\"\"Unittest to verify the feature to detect finite source effects in \n an event lightcurve\"\"\"\n\n (lightcurve,peaks) = generate_microlensing_lightcurve(0.001, 400)\n\n f = feature.finite_source_point_lens_feature(lightcurve,peaks,\n diagnostics=True)\n \n assert len(f) == len(peaks)\n \ndef generate_microlensing_lightcurve(u0, ndp, diagnostics=False):\n \"\"\"Function to generate a microlensing lightcurve for testing purposes.\n \n WARNING: Full photometric uncertainties not implemented as not currently\n necessary for testing purposes.\n \n Inputs:\n :param float u0: Event impact parameter\n :param int ndp: Number of datapoints in the lightcurve\n \n Returns:\n :param np.array lightcurve: Timeseries photmetry 3-column array\n (timestamp, mag/flux, mag error/flux error)\n for N datapoints\n \"\"\"\n\n lightcurve = np.zeros((ndp,3))\n \n lightcurve[:,0] = np.linspace(2459000.0, 2459040.0, ndp)\n \n u = np.linspace(0.01, 10.0, int(float(ndp)/2))\n u = np.concatenate([u[::-1],u])\n\n lightcurve[:,1] = np.random.normal(16.0, 0.003, size=ndp)\n lightcurve[:,1] += -2.5 * np.log10(microlensing_magnification(u))\n \n peaks = np.zeros(1)\n peaks[0] = lightcurve[int(float(ndp)/2),0]\n \n lightcurve[:,2] = np.random.normal(lightcurve[:,1],0.001)\n\n if diagnostics:\n fig = plt.figure(1,(10,10))\n plt.plot(lightcurve[:,0],microlensing_magnification(u))\n plt.xlabel('HJD')\n plt.ylabel('Mag')\n plt.show()\n \n return lightcurve, peaks\n \ndef microlensing_magnification(u):\n \"\"\"Function to calculate the microlensing magnification for a range of \n angular projected separations between lens and source, u\"\"\"\n \n A = ((u*u) + 2) / (u * np.sqrt(u*u + 4))\n \n return A\n\ndef test_bell_curve(diagnostics=False):\n \"\"\"Unittest to verify that the bell curve function produces the\n expected series of evaluated-function values.\n \"\"\"\n \n x = np.linspace(-100.0, 100.0, 200)\n \n a = 2.0\n b = 4.0\n c = 6.0\n \n fx = feature.bell_curve(x,a,b,c)\n \n if diagnostics:\n fig = plt.figure(1,(10,10))\n plt.plot(x,fx,'k-')\n plt.xlabel('x')\n plt.ylabel('f(x)')\n plt.show()\n \n assert len(fx) == len(x)\n assert fx.max() < a\n \ndef test_gaussian(diagnostics=False):\n \"\"\"Unittest to verify that the bell curve function produces the\n expected series of evaluated-function values.\n \"\"\"\n \n x = np.linspace(-100.0, 100.0, 200)\n \n a = 2000.0\n b = 4.0\n c = 6.0\n \n fx = feature.gaussian(x,a,b,c)\n \n G = stats.norm(b, c)\n \n assert len(fx) == len(x)\n \n if diagnostics:\n fig = plt.figure(1,(10,10))\n plt.plot(x,fx,'k-')\n plt.xlabel('x')\n plt.ylabel('f(x)')\n plt.show()\n \nif __name__ == '__main__':\n \n #test_bell_curve(diagnostics=True)\n #test_gaussian()\n #generate_microlensing_lightcurve(0.001, 400, diagnostics=True)\n test_finite_source_point_lens_feature()\n ","sub_path":"Contributions/test_finite_source_point_lens.py","file_name":"test_finite_source_point_lens.py","file_ext":"py","file_size_in_byte":3535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"574201515","text":"#Tushar Borole\n#Python 2.7\n\nfrom flask_restful import Resource, Api, request\nfrom package.model import conn\n\n\nclass Common(Resource):\n \"\" \"Esto contiene una API comun, es decir, no es relacionado con el modulo especifico\" \"\"\n\n def get(self):\n \"\" \"Recupera el recuento de pacientes, medico y citas para la pagina del panel\" \"\"\n\n getPatientCount=conn.execute(\"SELECT COUNT(*) AS patient FROM patient\").fetchone()\n getDoctorCount = conn.execute(\"SELECT COUNT(*) AS doctor FROM doctor\").fetchone()\n getPharmacistCount = conn.execute(\"SELECT COUNT(*) AS pharmacist FROM pharmacist\").fetchone()\n getLaboratoryCount = conn.execute(\"SELECT COUNT(*) AS laboratory FROM laboratory\").fetchone()\n getInsuranceCount = conn.execute(\"SELECT COUNT(*) AS insurance FROM insurance\").fetchone()\n getAppointmentCount = conn.execute(\"SELECT COUNT(*) AS appointment FROM appointment\").fetchone()\n getMedicineCount = conn.execute(\"SELECT COUNT(*) AS medicine FROM medicine\").fetchone()\n getMedicineSaleCount = conn.execute(\"SELECT COUNT(*) AS medicine_sale FROM medicine_sale\").fetchone()\n getPatientCount.update(getDoctorCount)\n getPatientCount.update(getAppointmentCount)\n getPatientCount.update(getInsuranceCount)\n getPatientCount.update(getPharmacistCount)\n getPatientCount.update(getLaboratoryCount)\n getPatientCount.update(getMedicineCount)\n getPatientCount.update(getMedicineSaleCount)\n return getPatientCount","sub_path":"package/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"123607437","text":"import tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\n\nfrom models.resnet_util import *\n\ndef resNet_18_encoder(input_shape=(224, 224, 3)):\n\n image_input = layers.Input(shape=(224, 224, 3))\n\n x = conv_bn_relu(filters=64, kernel_size=(7, 7), strides=(2, 2))(image_input) # output: 112x112\n f0 = x\n x = layers.MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding=\"same\")(x) # output: 56x56\n\n # BLOCK 1 - 64 filters\n x = basic_block_first(64, init_strides=(1, 1))(x) # output: 56x56\n x = basic_block(64, init_strides=(1, 1))(x)\n f1 = x\n\n # BLOCK 2 - 128 filters\n x = basic_block(128, init_strides=(2, 2))(x) # output: 28x28\n x = basic_block(128, init_strides=(1, 1))(x)\n f2 = x\n\n # BLOCK 3 - 256 filters\n x = basic_block(256, init_strides=(2, 2))(x) # output: 14x14\n x = basic_block(256, init_strides=(1, 1))(x)\n f3 = x\n\n # BLOCK 4 - 512 filters\n x = basic_block(512, init_strides=(2, 2))(x) # output: 7x7\n x = basic_block(512, init_strides=(1, 1))(x)\n \n # FINAL ACTIVATION\n x = layers.BatchNormalization(axis=-1)(x)\n x = layers.Activation(\"relu\")(x)\n f4 = x \n\n\n return image_input, [f0, f1,f2,f3,f4]\n\n\n","sub_path":"code_reg_and_clas/models/encoders/resNet_18_encoder.py","file_name":"resNet_18_encoder.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"98718357","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom .models import Shop, Item\nfrom .forms import ItemForm, ShopForm\nfrom django.urls import reverse\n\n\n# Create your views here.\n\ndef item_list(request):\n queryset = Item.objects.all()\n return render(request, 'inventorymanage/item_list.html', {\n 'item_list': queryset\n })\n\ndef item_amount_add(request, pk):\n\n item = Item.objects.get(pk=pk)\n queryset = Item.objects.all()\n print(request.POST)\n if request.method == 'POST':\n item.amount = item.amount + 1\n item.save() # 저장을 해야 함\n return render(request, 'inventorymanage/item_list.html', {\n 'item_list': queryset\n })\n\ndef item_amount_sub(request, pk):\n\n item = Item.objects.get(pk=pk)\n queryset = Item.objects.all()\n print(request.POST)\n if request.method == 'POST':\n item.amount = item.amount - 1\n item.save() # 저장을 해야 함\n return render(request, 'inventorymanage/item_list.html', {\n 'item_list': queryset\n })\n\n\n\ndef item_detail(request, pk):\n item = get_object_or_404(Item, pk=pk)\n return render(request, 'inventorymanage/item_detail.html', {\n 'item': item\n })\n\n\ndef shop_detail(request, pk):\n shop = get_object_or_404(Shop, pk=pk)\n return render(request, 'inventorymanage/shop_detail.html', {\n 'shop': shop\n })\n\n\ndef shop_list(request):\n queryset = Shop.objects.all()\n return render(request, 'inventorymanage/shop_list.html', {\n 'shop_list': queryset\n })\n\n\ndef item_create(request, item=None):\n if request.method == 'POST':\n form = ItemForm(request.POST, request.FILES, instance=item)\n\n if form.is_valid():\n item = form.save()\n return redirect('inventorymanage:item_detail', item.id)\n else:\n form = ItemForm(instance=item)\n return render(request, 'inventorymanage/item_create.html', {\n 'form': form,\n })\n\n\ndef shop_create(request, shop=None):\n if request.method == 'POST':\n form = ShopForm(request.POST, request.FILES, instance=shop)\n\n if form.is_valid():\n shop = form.save()\n return redirect('inventorymanage:shop_detail', shop.id)\n else:\n form = ShopForm(instance=shop)\n return render(request, 'inventorymanage/shop_create.html', {\n 'form': form,\n })\n\n\ndef item_edit(request, pk):\n item = get_object_or_404(Item, pk=pk)\n return item_create(request, item)\n\n\ndef shop_edit(request, pk):\n shop = get_object_or_404(Shop, pk=pk)\n return shop_create(request, shop)\n\n\ndef item_delete(request, pk):\n item = get_object_or_404(Item, pk=pk)\n\n if request.method == 'GET':\n return redirect('inventorymanage:item_detail', item.id)\n\n if request.method == 'POST':\n item.delete()\n return redirect('inventorymanage:item_list')\n\n\ndef shop_delete(request, pk):\n shop = get_object_or_404(Shop, pk=pk)\n\n if request.method == 'GET':\n return redirect('inventorymanage:shop_detail', shop.id)\n\n if request.method == 'POST':\n shop.delete()\n return redirect('inventorymanage:shop_list')\n","sub_path":"inventorymanage/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"124214526","text":"#! /usr/bin/env python\r\n# coding=utf-8\r\n# --author: yuht4--\r\n\r\nimport os, sys, copy, getopt, re, argparse\r\n\r\nPREFIX = os.path.split(os.path.realpath(__file__))[0]\r\nPREFIX.replace('\\n', '')\r\n\r\nPICARD = PREFIX + \"/lib/picard.jar\"\r\nSTRELKA = PREFIX + \"/lib/strelka/bin/\"\r\nBBMAP = PREFIX + \"/lib/bbmap/\"\r\n\r\n\r\ndef main():\r\n\r\n\r\n OutputDir = \"/\"\r\n RefGenomeFasta = \"/\"\r\n CSV = \"/\"\r\n CutSiteTupleList = []\r\n\r\n\r\n parser = argparse.ArgumentParser(description=\"crispr on-target analysis\")\r\n\r\n parser.add_argument(\"--output\", type=str, help=\"output folder\", required=True)\r\n parser.add_argument(\"--genome\", type=str, help=\"reference fasta\", required=True)\r\n parser.add_argument(\"--in1\", type=str, help=\"first fastq file\", required=True)\r\n parser.add_argument(\"--in2\", type=str, help=\"second fastq file\", required=True)\r\n parser.add_argument(\"--csv\", type=str, help=\"csv file\", required=True)\r\n args = parser.parse_args()\r\n\r\n\r\n FirstFastq = os.path.abspath(args.in1)\r\n SecondFastq = os.path.abspath(args.in2)\r\n OutputDir = os.path.abspath(args.output)\r\n RefGenomeFasta = os.path.abspath(args.genome)\r\n CSV = os.path.abspath(args.csv)\r\n\r\n FirstFastq = re.sub('\\s', '', FirstFastq)\r\n SecondFastq = re.sub('\\s', '', SecondFastq)\r\n OutputDir = re.sub('\\s', '', OutputDir)\r\n CSV = re.sub('\\s', '', CSV)\r\n RefGenomeFasta = re.sub('\\s', '', RefGenomeFasta)\r\n\r\n\r\n #print(OutputDir);\r\n #print(os.path.exists(OutputDir));\r\n\r\n if not os.path.exists(OutputDir):\r\n print(\"The OutputDir not exist! Error\\n\")\r\n sys.exit()\r\n if not os.path.exists(FirstFastq) or not os.path.exists(SecondFastq):\r\n print(\"The sequencing data not exist! Error\\n\")\r\n sys.exit()\r\n if not os.path.exists(RefGenomeFasta):\r\n print(\"The Reference fasta not exist! Error\\n\")\r\n sys.exit()\r\n if not os.path.exists(CSV):\r\n print(\"The CSV file not exist! Error\\n\")\r\n sys.exit()\r\n\r\n FILE = open(CSV, 'r')\r\n\r\n while True:\r\n\r\n Line = FILE.readline()\r\n Line = re.sub('\\n', '', Line)\r\n Line = re.sub('\\r', '', Line)\r\n\r\n if not Line:\r\n break\r\n\r\n LineValues = Line.split(';')\r\n\r\n while '' in LineValues:\r\n LineValues.remove('')\r\n\r\n Chr = LineValues[0]\r\n Start = int(LineValues[1])\r\n Stop = int(LineValues[2])\r\n CutSite = LineValues[3]\r\n GRnaSequence = LineValues[4]\r\n PAM = LineValues[5]\r\n\r\n RepairSequence = \"\"\r\n\r\n if len(LineValues) == 7:\r\n RepairSequence = LineValues[6]\r\n\r\n tempTuple = (Chr, Start, Stop, CutSite, GRnaSequence, PAM, RepairSequence)\r\n\r\n if tempTuple not in CutSiteTupleList:\r\n CutSiteTupleList.append(tempTuple)\r\n\r\n FILE.close()\r\n\r\n if not os.path.exists(OutputDir + \"/Logs/\"):\r\n os.system(\"mkdir -p \" + OutputDir + \"/Logs/\")\r\n else:\r\n os.system(\"rm -rf \" + PREFIX + \"/Logs/*\")\r\n\r\n if not os.path.exists(OutputDir + \"/Temp\"):\r\n os.system(\"mkdir -p \" + OutputDir + \"/Temp\")\r\n else:\r\n os.system(\"rm -rf \" + OutputDir + \"/Temp/*\")\r\n\r\n if os.path.exists(OutputDir + \"/Result\"):\r\n os.system(\"rm -rf \" + OutputDir + \"/Result\")\r\n\r\n if os.path.exists(OutputDir + \"/cutsiteinfo.csv\"):\r\n os.system(\"rm -rf \" + OutputDir + \"/cutsiteinfo.csv\")\r\n\r\n if os.path.exists(OutputDir + \"/CrisprCas9Report.txt\"):\r\n os.system(\"rm -rf \" + OutputDir + \"/CrisprCas9Report.txt\")\r\n\r\n if os.path.exists(OutputDir + \"/IndelInfo.txt\"):\r\n os.system(\"rm -rf \" + OutputDir + \"/IndelInfo.txt\")\r\n\r\n if os.path.exists(OutputDir + \"/OffTargetMotif.txt\"):\r\n os.system(\"rm -rf \" + OutputDir + \"/OffTargetMotif.txt\")\r\n\r\n if os.path.exists(OutputDir + \"/OffTargetSites.txt\"):\r\n os.system(\"rm -rf \" + OutputDir + \"/OffTargetSites.txt\")\r\n\r\n if os.path.exists(OutputDir + \"/variants.vcf\"):\r\n os.system(\"rm -rf \" + OutputDir + \"/variants.vcf\")\r\n\r\n\r\n FliterReads(FirstFastq, SecondFastq, OutputDir)\r\n MappingAndSortingReads(OutputDir, RefGenomeFasta)\r\n\r\n FILE = open(OutputDir + \"/cutsiteinfo.csv\", 'w+')\r\n for val in CutSiteTupleList:\r\n FILE.write(val[5] + \";\" + val[6] + \";\\n\")\r\n FILE.close()\r\n\r\n\r\n\r\n\r\n os.system(\r\n \"python \" + PREFIX + \"/UtmOn.py -o \" + OutputDir + \" -g \" + RefGenomeFasta\r\n + \" -c \" + CSV + \" -b \" + OutputDir + \"/Temp/WGS.rg.sort.dd.bam\")\r\n os.system(\r\n \"python \" + PREFIX + \"/UtmOff.py -v \" + OutputDir +\r\n \"/Temp/genome.S1.vcf -g \" + RefGenomeFasta + \" -c \" + CSV + \" -o \" + OutputDir)\r\n os.system(\"mv \" + OutputDir + \"/Temp/genome.S1.vcf \" + OutputDir +\r\n \"/variants.vcf\")\r\n\r\n removeTempFile(OutputDir)\r\n\r\n\r\ndef removeTempFile(OutputDir):\r\n\r\n if os.path.exists(OutputDir + \"/Temp\"):\r\n os.system(\"rm -rf \" + OutputDir + \"/Temp\")\r\n if os.path.exists(OutputDir + \"/Result\"):\r\n os.system(\"rm -rf \" + OutputDir + \"/Result\")\r\n if os.path.exists(OutputDir + \"/cutsiteinfo.csv\"):\r\n os.system(\"rm -rf \" + OutputDir + \"/cutsiteinfo.csv\")\r\n if os.path.exists(OutputDir + \"/Logs\"):\r\n os.system(\"rm -rf \" + OutputDir + \"/Logs\")\r\n\r\ndef FliterReads(FirstFastq, SecondFastq, OutputDir):\r\n\r\n FastXLogFile = OutputDir + \"/Logs/fastx.log\"\r\n BBMapLogFile = OutputDir + \"/Logs/bbmap.log\"\r\n\r\n os.system(\r\n \"gunzip -c \" + FirstFastq + \" > \" + OutputDir + \"/Temp/first.fastq\")\r\n os.system(\r\n \"gunzip -c \" + SecondFastq + \" > \" + OutputDir + \"/Temp/second.fastq\")\r\n\r\n os.system(\"fastq_quality_trimmer -Q33 -t 30 -z -i \" + OutputDir +\r\n \"/Temp/first.fastq -o \" + OutputDir +\r\n \"/Temp/first.fliter.fastq.gz > \" + FastXLogFile)\r\n os.system(\"fastq_quality_trimmer -Q33 -t 30 -z -i \" + OutputDir +\r\n \"/Temp/second.fastq -o \" + OutputDir +\r\n \"/Temp/second.fliter.fastq.gz >> \" + FastXLogFile)\r\n\r\n os.system(\"rm -rf \" + OutputDir + \"/Temp/first.fastq\")\r\n os.system(\"rm -rf \" + OutputDir + \"/Temp/second.fastq\")\r\n\r\n os.system(\r\n BBMAP + \"/repair.sh --overwrite=t in1=\" + OutputDir +\r\n \"/Temp/first.fliter.fastq.gz in2=\" + OutputDir +\r\n \"/Temp/second.fliter.fastq.gz out1=\" + OutputDir +\r\n \"/Temp/first.fliter.repair.fastq.gz out2=\" + OutputDir +\r\n \"/Temp/second.fliter.repair.fastq.gz >> \" + BBMapLogFile + \" 2>&1\")\r\n\r\n\r\ndef MappingAndSortingReads(OutputDir, RefGenomeFasta):\r\n\r\n BwaLogFile = OutputDir + \"/Logs/bwa.log\"\r\n SamLogFile = OutputDir + \"/Logs/sam.log\"\r\n PicardLogFile = OutputDir + \"/Logs/picard.log\"\r\n StrelkaLogFile = OutputDir + \"/Logs/strelka.log\"\r\n\r\n os.system(\r\n \"bwa mem -t 4 -M \" + RefGenomeFasta +\r\n \" \" + OutputDir + \"/Temp/first.fliter.repair.fastq.gz \" +\r\n OutputDir + \"/Temp/second.fliter.repair.fastq.gz > \" + OutputDir +\r\n \"/Temp/WGS.sam 2>> \" + BwaLogFile)\r\n os.system(\"samtools view -Sb \" + OutputDir + \"/Temp/WGS.sam > \" +\r\n OutputDir + \"/Temp/WGS.bam 2>> \" + SamLogFile)\r\n\r\n os.system(\r\n \"java -jar \" + PICARD + \" SortSam I=\" + OutputDir + \"/Temp/WGS.bam O=\"\r\n + OutputDir + \"/Temp/WGS.sort.bam SO=coordinate 2>> \" + PicardLogFile)\r\n os.system(\r\n \"java -jar \" + PICARD + \" MarkDuplicates I=\" + OutputDir +\r\n \"/Temp/WGS.sort.bam O=\" + OutputDir + \"/Temp/WGS.rg.sort.bam M=\" +\r\n OutputDir + \"/Temp/WGS.rg.sort.dd.metrics REMOVE_DUPLICATES=true 2>> \"\r\n + PicardLogFile)\r\n os.system(\r\n \"java -jar \" + PICARD + \" AddOrReplaceReadGroups I=\" + OutputDir +\r\n \"/Temp/WGS.rg.sort.bam O=\" + OutputDir +\r\n \"/Temp/WGS.rg.sort.dd.bam SO=coordinate LB=hg19ID PL=Illumina PU=hg19PU SM=1 2>> \"\r\n + PicardLogFile)\r\n\r\n os.system(\"samtools index \" + OutputDir + \"/Temp/WGS.rg.sort.dd.bam\")\r\n\r\n os.system(\r\n \"python \" + STRELKA + \"/configureStrelkaGermlineWorkflow.py --bam \" +\r\n OutputDir + \"/Temp/WGS.rg.sort.dd.bam --referenceFasta \" + RefGenomeFasta + \" --runDir \" +\r\n OutputDir + \"/Result\")\r\n\r\n os.system(\"cd \" + OutputDir + \"/Result && python runWorkflow.py -m local\")\r\n\r\n os.system(\r\n \"cd \" + OutputDir +\r\n \"/Result/results/variants && gzip -d genome.S1.vcf.gz && mv genome.S1.vcf \"\r\n + OutputDir + \"/Temp/\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"CRISPRWGSSingle.py","file_name":"CRISPRWGSSingle.py","file_ext":"py","file_size_in_byte":8323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"514290373","text":"from django.conf.urls import url\nfrom . import views\n\n\napp_name = 'articles'\nurlpatterns = [\n url(r'^$',views.main,name='main'),\n url('(?P\\d+)/$',views.view,name='get'),\n url('(?P\\d+)/delete$',views.delete,name='delete'),\n url('(?P\\d+)/edit$',views.edit,name='edit'),\n url(r'new/$',views.new,name='new')\n]","sub_path":"articles/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"324975971","text":"__all__ = (\n 'MMIDLoader',\n)\n\nimport typing\n\nfrom chatora.mmid.base import BaseMMIDType\n\n\nclass MMIDLoader:\n\n def __init__(\n self,\n factory_choice_map: typing.Optional[typing.Mapping[\n typing.Tuple[int, int], typing.Callable[[int, bool], BaseMMIDType]\n ]] = None,\n ):\n self.factory_choice_map = factory_choice_map or {}\n return\n\n def __call__(\n self,\n hex_value: str = None,\n bytes_be_value: bytes = None,\n bytes_le_value: bytes = None,\n int_value: int = None,\n ) -> BaseMMIDType:\n if hex_value is not None:\n int_value = int(hex_value.replace('urn:', '').replace('uuid:', '').strip('{}').replace('-', ''), base=16)\n elif bytes_le_value is not None:\n int_value = int.from_bytes(\n bytes_le_value[4 - 1::-1] + bytes_le_value[6 - 1:4 - 1:-1] + bytes_le_value[8 - 1:6 - 1:-1] + bytes_le_value[8:],\n byteorder='big',\n )\n elif bytes_be_value is not None:\n int_value = int.from_bytes(bytes_be_value, byteorder='big')\n\n if not 0 <= int_value < (1 << 128):\n raise ValueError('out of range')\n\n try:\n factory = self.resolve_factory(\n uuid_version=(int_value >> 76) & 0xf,\n mmid_version=(int_value >> 64) & 0xf,\n )\n except ValueError:\n raise ValueError(\n f'Unknown MMID `{int_value}`'\n )\n\n return factory(int_value, False)\n\n def register_factory(\n self,\n uuid_version: int,\n mmid_version: int,\n factory: typing.Callable[[int, bool], BaseMMIDType],\n ):\n self.factory_choice_map[(uuid_version, mmid_version)] = factory\n return\n\n def resolve_factory(self, uuid_version: int, mmid_version: int) -> typing.Callable[[int, bool], BaseMMIDType]:\n try:\n return self.factory_choice_map[(uuid_version, mmid_version)]\n except KeyError:\n raise ValueError(\n f'Unknown MMID type (uuid_version=`{uuid_version}`, mmid_version={mmid_version})'\n )\n","sub_path":"chatora/mmid/functional.py","file_name":"functional.py","file_ext":"py","file_size_in_byte":2148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"89789142","text":"import sys\nimport argparse\nimport re\nimport h5py\nimport numpy as np\n\nclass Indexer:\n def __init__(self):\n self.counter = 1\n self.chunk_counter = 1\n self.pos_counter = 1\n self.d = {}\n self.rev = {}\n self.chunk_d = {}\n self.pos_d = {}\n self._lock = False\n self.max_len = 0\n\n def convert(self, w):\n if w not in self.d:\n if self._lock:\n return self.d[\"\"]\n self.d[w] = self.counter\n self.rev[self.counter] = w\n self.counter += 1\n return self.d[w]\n\n def lock(self):\n self._lock = True\n\n def write(self, outfile):\n out = open(outfile, \"w\")\n items = [(v, k) for k, v in self.d.iteritems()]\n items.sort()\n for v, k in items:\n print >>out, k, v\n out.close()\n\ndef get_data(args):\n target_indexer = Indexer()\n #add special words to indices in the target_indexer\n target_indexer.convert(\"\")\n target_indexer.convert(\"\")\n target_indexer.convert(\"\")\n\n def sequencer_template(datafile, sentences, pos_seqs, chunk_seqs):\n out = open(\"sequencer_\" + datafile, \"w\")\n idx_to_word = dict([(v, k) for k, v in target_indexer.d.iteritems()])\n idx_to_chunk = dict([(v, k) for k, v in target_indexer.chunk_d.iteritems()])\n idx_to_pos = dict([(v, k) for k, v in target_indexer.pos_d.iteritems()])\n for length, sent_list in sentences.iteritems():\n chunk_seq = chunk_seqs[length]\n pos_seq = pos_seqs[length]\n for sent_idx, sentence in enumerate(sent_list):\n for word_idx, word in enumerate(sentence):\n word = idx_to_word[word]\n chunk = idx_to_chunk[chunk_seq[sent_idx][word_idx]]\n pos = idx_to_pos[pos_seq[sent_idx][word_idx]]\n print >>out, word, pos, chunk\n print >>out, \"\"\n out.close()\n\n def text_output(datafile, sentences):\n out = open(\"sentences_\" + datafile, \"w\")\n idx_to_word = dict([(v, k) for k, v in target_indexer.d.iteritems()])\n for length, sent_list in sentences.iteritems():\n for sentence in sent_list:\n print >>out, ' '.join([idx_to_word[word] for word in sentence])\n out.close()\n\n def add_padding(sentences, pos_seqs, chunk_seqs, outputs, sent_lens, dwin):\n for length in sent_lens:\n for idx, sentence in enumerate(sentences[length]):\n sentences[length][idx] = [target_indexer.convert('PAD')] * (dwin/2) + \\\n sentences[length][idx] + [target_indexer.convert('PAD')] * (dwin/2)\n pos_seqs[length][idx] = [target_indexer.convert_pos('PAD')] * (dwin/2) + \\\n pos_seqs[length][idx] + [target_indexer.convert_pos('PAD')] * (dwin/2)\n chunk_seqs[length][idx] = [target_indexer.convert_chunk('PAD')] * (dwin/2) + \\\n chunk_seqs[length][idx] + [target_indexer.convert_chunk('PAD')] * (dwin/2)\n outputs[length][idx] = [target_indexer.convert('PAD')] * (dwin/2) + \\\n outputs[length][idx] + [target_indexer.convert('PAD')] * (dwin/2)\n return sentences, pos_seqs, chunk_seqs, outputs\n\n def convert(datafile, outfile, dwin):\n # Parse and convert data\n with open(datafile, 'r') as f:\n sentences = {}\n outputs = {}\n for i, orig_sentence in enumerate(f):\n orig_sentence = orig_sentence.strip().split() + [\"\"]\n sentence = [target_indexer.convert(w) for w in orig_sentence]\n output = sentence[1:] + [target_indexer.convert(\"\")]\n length = len(sentence)\n target_indexer.max_len = max(target_indexer.max_len, length)\n\n if length in sentences:\n sentences[length].append(sentence)\n outputs[length].append(output)\n else:\n sentences[length] = [sentence]\n outputs[length] = [output]\n \n sent_lens = sentences.keys()\n\n # Reoutput raw data ordered by length\n #sequencer_template(datafile, sentences, pos_seqs, chunk_seqs)\n #text_output(datafile, sentences)\n\n # Add padding for windowed models\n if dwin > 0:\n sentences, pos_seqs, chunk_seqs, outputs = add_padding(sentences, pos_seqs, chunk_seqs, outputs, sent_lens, dwin)\n\n # Output HDF5 for torch\n f = h5py.File(outfile, \"w\")\n f[\"sent_lens\"] = np.array(sent_lens, dtype=int)\n for length in sent_lens:\n f[str(length)] = np.array(sentences[length], dtype=int)\n #f[str(length) + \"pos\"] = np.array(pos_seqs[length], dtype = int)\n #f[str(length) + \"chunk\"] = np.array(chunk_seqs[length], dtype = int)\n f[str(length) + \"output\"] = np.array(outputs[length], dtype = int)\n f[\"max_len\"] = np.array([target_indexer.max_len], dtype=int)\n f[\"nfeatures\"] = np.array([target_indexer.counter - 1], dtype=int)\n #f[\"nclasses_pos\"] = np.array([target_indexer.pos_counter - 1], dtype=int)\n #f[\"nclasses_chunk\"] = np.array([target_indexer.chunk_counter - 1], dtype=int)\n f[\"dwin\"] = np.array([dwin], dtype=int)\n\n convert(args.trainfile, args.outputfile + \".hdf5\", args.dwin)\n target_indexer.lock()\n convert(args.testfile, args.outputfile + \"_test\" + \".hdf5\", args.dwin)\n target_indexer.write(args.outputfile + \".dict\")\n #target_indexer.write_chunks(args.outputfile + \".chunk.dict\")\n #target_indexer.write_pos(args.outputfile + \".pos.dict\")\n\ndef main(arguments):\n global args\n parser = argparse.ArgumentParser(\n description=__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n parser.add_argument('trainfile', help=\"Raw chunking text file\", type=str) # ptb/train.txt\n parser.add_argument('testfile', help=\"Raw chunking test text file\", type=str) # ptb/test.txt\n parser.add_argument('outputfile', help=\"HDF5 output file\", type=str) # convert_seq/ptb_seq\n parser.add_argument('dwin', help=\"Window dimension (0 if no padding)\", type=int) # 5\n args = parser.parse_args(arguments)\n\n # Do conversion\n get_data(args)\n\nif __name__ == '__main__':\n sys.exit(main(sys.argv[1:]))\n","sub_path":"preprocess-ae.py","file_name":"preprocess-ae.py","file_ext":"py","file_size_in_byte":6364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"406826157","text":"from textblob.classifiers import NaiveBayesClassifier as NBC\r\nfrom textblob import TextBlob\r\nimport csv\r\n\r\ntraining_corpus = []\r\nwith open('D:\\\\Train_sentiment_data.csv', newline='') as csvfile:\r\n reader = csv.DictReader(csvfile)\r\n for row in reader:\r\n training_corpus.append(row)\r\n\r\n # print(row['sentence'], row['polarity'])\r\n# print (\"Training Corpus is: \", training_corpus)\r\nprint (training_corpus)\r\ntest_corpus = []\r\nwith open('D:\\\\Test_sentiment_data.csv', newline='') as csvfile:\r\n reader = csv.DictReader(csvfile)\r\n for row in reader:\r\n test_corpus.append(row)\r\n # print(row['sentence'], row['polarity'])\r\n\r\n# print (\"Test Corpus is:\",test_corpus)\r\n\r\n\r\ntrain_data = []\r\ntrain_labels = []\r\nfor row in training_corpus:\r\n train_data.append(row['sentence'])\r\n train_labels.append(row['polarity'])\r\n# print (train_data)\r\ntest_data = []\r\ntest_labels = []\r\nfor row in test_corpus:\r\n test_data.append(row['sentence'])\r\n test_labels.append(row['polarity'])\r\n\r\nmodel = NBC(training_corpus)\r\nprint(model.classify(\"Their codes are amazing.\"))\r\nprint(model.classify(\"I don't like their computer.\"))\r\n\r\nprint(model.accuracy(test_corpus))\r\n","sub_path":"Naive Bayes_TextBlob.py","file_name":"Naive Bayes_TextBlob.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"285516661","text":"# factorial using recursion, n! = n*n-1*n-2..*2*1 or n* (n-1)!\r\n\r\ndef fact(n): ## hypothesis: prints n*n-1*n-2..to 1\r\n\r\n if n==0 or n==1: # base condition, smallest valid i/p 1\r\n return 1\r\n \r\n return n*fact(n-1) # fact(n-1) prints n-1*n-2*...to 1 \r\n \r\nn = 5\r\nprint(fact(n))","sub_path":"recursion/recursion 1.3.py","file_name":"recursion 1.3.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"288988465","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\nfrom grr_response_core.lib.rdfvalues import artifacts as rdf_artifacts\nfrom grr_response_server import artifact_registry\nfrom grr_response_server.databases import db\n\n\nclass DatabaseTestArtifactsMixin(object):\n\n def testReadArtifactThrowsForUnknownArtifacts(self):\n with self.assertRaises(db.UnknownArtifactError) as context:\n self.db.ReadArtifact(\"Foo\")\n\n self.assertEqual(context.exception.name, \"Foo\")\n\n def testReadArtifactReadsWritten(self):\n artifact = rdf_artifacts.Artifact(\n name=\"Foo\",\n doc=\"Lorem ipsum dolor sit amet.\",\n urls=[\"http://example.com/foo\"])\n\n self.db.WriteArtifact(artifact)\n\n result = self.db.ReadArtifact(\"Foo\")\n self.assertEqual(result.name, \"Foo\")\n self.assertEqual(result.doc, \"Lorem ipsum dolor sit amet.\")\n self.assertEqual(result.urls, [\"http://example.com/foo\"])\n\n def testReadArtifactReadsCopy(self):\n self.db.WriteArtifact(rdf_artifacts.Artifact(name=\"Foo\"))\n self.db.ReadArtifact(\"Foo\").name = \"Bar\"\n self.assertEqual(self.db.ReadArtifact(\"Foo\").name, \"Foo\")\n\n def testWriteArtifactThrowsForDuplicatedArtifacts(self):\n self.db.WriteArtifact(rdf_artifacts.Artifact(name=\"Foo\", doc=\"Lorem.\"))\n\n with self.assertRaises(db.DuplicatedArtifactError) as context:\n self.db.WriteArtifact(rdf_artifacts.Artifact(name=\"Foo\", doc=\"Ipsum.\"))\n\n self.assertEqual(context.exception.name, \"Foo\")\n\n def testWriteArtifactThrowsForEmptyName(self):\n with self.assertRaises(ValueError):\n self.db.WriteArtifact(rdf_artifacts.Artifact(name=\"\"))\n\n def testWriteAndReadArtifactWithLongName(self):\n name = \"x\" + \"🧙\" * (db.MAX_ARTIFACT_NAME_LENGTH - 2) + \"x\"\n self.db.WriteArtifact(rdf_artifacts.Artifact(name=name))\n self.assertEqual(self.db.ReadArtifact(name).name, name)\n\n def testWriteArtifactRaisesWithTooLongName(self):\n name = \"a\" * (db.MAX_ARTIFACT_NAME_LENGTH + 1)\n with self.assertRaises(ValueError):\n self.db.WriteArtifact(rdf_artifacts.Artifact(name=name))\n\n def testWriteArtifactWithSources(self):\n file_source = rdf_artifacts.ArtifactSource(\n type=rdf_artifacts.ArtifactSource.SourceType.FILE,\n conditions=[\"os_major_version < 6\"],\n attributes={\n \"paths\": [\"/tmp/foo\", \"/tmp/bar\"],\n })\n\n registry_key_source = rdf_artifacts.ArtifactSource(\n type=rdf_artifacts.ArtifactSource.SourceType.REGISTRY_KEY,\n attributes={\n \"key_value_pairs\": [{\n \"key\": \"HKEY_LOCAL_MACHINE\\\\Foo\\\\Bar\\\\Baz\",\n \"value\": \"Quux\"\n },],\n })\n\n artifact = rdf_artifacts.Artifact(\n name=\"Foo\",\n sources=[file_source, registry_key_source],\n supported_os=[\"Windows\", \"Linux\"],\n urls=[\"http://foobar.com/\"])\n\n self.db.WriteArtifact(artifact)\n self.assertEqual(self.db.ReadArtifact(\"Foo\"), artifact)\n\n def testWriteArtifactMany(self):\n for i in range(42):\n self.db.WriteArtifact(rdf_artifacts.Artifact(name=\"Art%s\" % i))\n\n for i in range(42):\n self.assertEqual(self.db.ReadArtifact(\"Art%s\" % i).name, \"Art%s\" % i)\n\n def testWriteArtifactWritesCopy(self):\n artifact = rdf_artifacts.Artifact()\n\n artifact.name = \"Foo\"\n artifact.doc = \"Lorem ipsum.\"\n self.db.WriteArtifact(artifact)\n\n artifact.name = \"Bar\"\n artifact.doc = \"Dolor sit amet.\"\n self.db.WriteArtifact(artifact)\n\n foo = self.db.ReadArtifact(\"Foo\")\n self.assertEqual(foo.name, \"Foo\")\n self.assertEqual(foo.doc, \"Lorem ipsum.\")\n\n bar = self.db.ReadArtifact(\"Bar\")\n self.assertEqual(bar.name, \"Bar\")\n self.assertEqual(bar.doc, \"Dolor sit amet.\")\n\n def testDeleteArtifactThrowsForUnknownArtifacts(self):\n with self.assertRaises(db.UnknownArtifactError) as context:\n self.db.DeleteArtifact(\"Quux\")\n\n self.assertEqual(context.exception.name, \"Quux\")\n\n def testDeleteArtifactDeletesSingle(self):\n self.db.WriteArtifact(rdf_artifacts.Artifact(name=\"Foo\"))\n self.db.DeleteArtifact(\"Foo\")\n\n with self.assertRaises(db.UnknownArtifactError):\n self.db.ReadArtifact(\"Foo\")\n\n def testDeleteArtifactDeletesMultiple(self):\n for i in range(42):\n self.db.WriteArtifact(rdf_artifacts.Artifact(name=\"Art%s\" % i))\n\n for i in range(42):\n if i % 2 == 0:\n continue\n\n self.db.DeleteArtifact(\"Art%s\" % i)\n\n for i in range(42):\n if i % 2 == 0:\n self.assertEqual(self.db.ReadArtifact(\"Art%s\" % i).name, \"Art%s\" % i)\n else:\n with self.assertRaises(db.UnknownArtifactError):\n self.db.ReadArtifact(\"Art%s\" % i)\n\n def testReadAllArtifactsEmpty(self):\n self.assertEqual(self.db.ReadAllArtifacts(), [])\n\n def testReadAllArtifactsReturnsAllArtifacts(self):\n artifacts = []\n for i in range(42):\n artifacts.append(rdf_artifacts.Artifact(name=\"Art%s\" % i))\n\n for artifact in artifacts:\n self.db.WriteArtifact(artifact)\n\n self.assertCountEqual(self.db.ReadAllArtifacts(), artifacts)\n\n def testReadAllArtifactsReturnsCopy(self):\n name = lambda artifact: artifact.name\n\n self.db.WriteArtifact(rdf_artifacts.Artifact(name=\"Foo\"))\n self.db.WriteArtifact(rdf_artifacts.Artifact(name=\"Bar\"))\n\n artifacts = self.db.ReadAllArtifacts()\n self.assertCountEqual(map(name, artifacts), [\"Foo\", \"Bar\"])\n\n artifacts[0].name = \"Quux\"\n artifacts[1].name = \"Norf\"\n\n artifacts = self.db.ReadAllArtifacts()\n self.assertCountEqual(map(name, artifacts), [\"Foo\", \"Bar\"])\n\n # TODO: Remove once artifact patching is no longer needed.\n def testReadArtifactPatching(self):\n source = rdf_artifacts.ArtifactSource()\n source.type = rdf_artifacts.ArtifactSource.SourceType.GREP\n source.attributes = {\n b\"paths\": [\"foo/bar\", \"norf/thud\"],\n b\"content_regex_list\": [\"ba[rz]\"],\n }\n\n artifact = rdf_artifacts.Artifact()\n artifact.name = \"foobar\"\n artifact.sources = [source]\n\n self.db.WriteArtifact(artifact)\n\n artifact = self.db.ReadArtifact(\"foobar\")\n self.assertLen(artifact.sources, 1)\n\n source = artifact.sources[0]\n source.Validate() # Should not raise.\n self.assertEqual(source.attributes[\"paths\"], [\"foo/bar\", \"norf/thud\"])\n self.assertEqual(source.attributes[\"content_regex_list\"], [\"ba[rz]\"])\n\n # Should not raise.\n source.Validate()\n\n self.assertEqual(artifact, self.db.ReadArtifact(\"foobar\"))\n\n def testReadArtifactPatchingDeep(self):\n source = rdf_artifacts.ArtifactSource()\n source.type = rdf_artifacts.ArtifactSource.SourceType.REGISTRY_VALUE\n source.attributes = {\n b\"key_value_pairs\": [\n {\n b\"key\": \"foo\",\n b\"value\": \"bar\",\n },\n {\n b\"key\": b\"quux\",\n b\"value\": 1337,\n },\n ],\n }\n\n artifact = rdf_artifacts.Artifact()\n artifact.name = \"foobar\"\n artifact.doc = \"Lorem ipsum.\"\n artifact.sources = [source]\n\n self.db.WriteArtifact(artifact)\n\n artifact = self.db.ReadArtifact(\"foobar\")\n artifact_registry.Validate(artifact) # Should not raise.\n\n self.assertLen(artifact.sources, 1)\n\n source = artifact.sources[0]\n self.assertEqual(source.attributes[\"key_value_pairs\"][0][\"key\"], \"foo\")\n self.assertEqual(source.attributes[\"key_value_pairs\"][0][\"value\"], \"bar\")\n self.assertEqual(source.attributes[\"key_value_pairs\"][1][\"key\"], \"quux\")\n self.assertEqual(source.attributes[\"key_value_pairs\"][1][\"value\"], 1337)\n\n # Read again, to ensure that we retrieve what is stored in the database.\n artifact = self.db.ReadArtifact(\"foobar\")\n artifact_registry.Validate(artifact) # Should not raise.\n\n # TODO: Remove once artifact patching is no longer needed.\n def testReadAllArtifactsPatching(self):\n source0 = rdf_artifacts.ArtifactSource()\n source0.type = rdf_artifacts.ArtifactSource.SourceType.PATH\n source0.attributes = {\n b\"paths\": [\"norf/thud\"],\n }\n\n source1 = rdf_artifacts.ArtifactSource()\n source1.type = rdf_artifacts.ArtifactSource.SourceType.COMMAND\n source1.attributes = {\n b\"cmd\": \"quux\",\n b\"args\": [\"foo\", \"bar\"],\n }\n\n artifact = rdf_artifacts.Artifact()\n artifact.name = \"foobar\"\n artifact.sources = [source0, source1]\n\n self.db.WriteArtifact(artifact)\n\n artifacts = self.db.ReadAllArtifacts()\n self.assertLen(artifacts, 1)\n self.assertEqual(artifacts[0].sources[0].attributes[\"paths\"], [\"norf/thud\"])\n self.assertEqual(artifacts[0].sources[1].attributes[\"cmd\"], \"quux\")\n self.assertEqual(artifacts[0].sources[1].attributes[\"args\"], [\"foo\", \"bar\"])\n\n # Should not raise.\n artifacts[0].sources[0].Validate()\n artifacts[0].sources[1].Validate()\n\n\n# This file is a test library and thus does not require a __main__ block.\n","sub_path":"grr/server/grr_response_server/databases/db_artifacts_test.py","file_name":"db_artifacts_test.py","file_ext":"py","file_size_in_byte":8751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"369797644","text":"#leetcode - 45\r\n\r\nclass Solution:\r\n def jump(self, nums) -> int:\r\n\r\n # edge case\r\n if len(nums) in (0, 1):\r\n return 0\r\n # variables\r\n highesh_jump = nums[0]\r\n window_interval_len = nums[0]\r\n # return\r\n jumps = 1 # number of jumps\r\n\r\n # logic\r\n for i in range(len(nums)):\r\n if nums[\r\n i] + i > highesh_jump: # case to find highes jump even in cases when the highestjump in the previous windows exceeds our current elemnt ex [2,3,1,9,4,5,6,7,1,1,1]\r\n highesh_jump = nums[i] + i\r\n if window_interval_len == i and i != len(\r\n nums) - 1: # if end ogf the window interval is reached and end of the nums array is not reached\r\n window_interval_len = highesh_jump # from previous window\r\n jumps += 1\r\n if window_interval_len >= len(nums) - 1: # end of nums is reached\r\n return jumps\r\n\r\n\r\n","sub_path":"prob_136.py","file_name":"prob_136.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"129019366","text":"import asyncio\nimport asyncpg\nfrom fastapi import Depends\nfrom starlette.middleware.cors import CORSMiddleware\nfrom starlette.requests import Request\n\nfrom . import config\n\ndb_pool = None\n\n\nasync def init_db(app):\n global db_pool\n db_pool = await asyncpg.create_pool(database=config.POSTGRES_DB,\n user=config.POSTGRES_USER, host=config.POSTGRES_SERVER, password=config.POSTGRES_PASSWORD)\n\n app.middleware(\"http\")(db_session_middleware)\n\nasync def close_db(app):\n await asyncio.wait_for(db_pool.close(), 2)\n\nasync def get_db_conn(request: Request):\n request.state.db_conn = conn = await db_pool.acquire()\n request.state.db_txn = tr = conn.transaction()\n # print(\"RS\", id(request), request.state.__dict__)\n await tr.start()\n\n return conn\n\n\nDatabase = Depends(get_db_conn)\n\n\nasync def db_session_middleware(request: Request, call_next):\n request.state.db_conn = None\n request.state.db_txn = None\n # print(\"RS2\", id(request), request.state.__dict__)\n try:\n try:\n response = await call_next(request)\n except:\n if request.state.db_txn:\n print(\"txn rollback\")\n await request.state.db_txn.rollback()\n raise\n else:\n if request.state.db_txn:\n print(\"txn commit\")\n await request.state.db_txn.commit()\n finally:\n conn = request.state.db_conn\n if conn:\n print(\"closing conn\")\n await db_pool.release(conn)\n return response\n\n\n","sub_path":"server/kac/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"653916463","text":"# -*- coding: utf-8 -*-\n\"\"\"\nTest vagrant 'build_vm' in the emitted template\n\"\"\"\n\n\n#\n# Imports\n#\n\n# import core\nimport logging\n\n# import third party\nimport pytest\n\nfrom tests.common.cookiecutter_utils import (\n CookieCutterInvoker,\n)\nfrom tests.common.git_utils import (\n prepare_minimal_viable_git_repo,\n)\nfrom tests.common.output_utils import (\n OutputDirectoryManager,\n)\n# this project\nfrom tests.constants import (\n PythonRepoMode,\n PythonVersionMode,\n VagrantBoxMode,\n VagrantVM,\n VagrantVMRole,\n)\nfrom tests.vagrant.common.cookiecutter_utils import (\n mint_extra_context,\n)\nfrom tests.vagrant.common.misc_utils import (\n SpecificTestParams,\n)\nfrom tests.vagrant.common.pytest_utils import (\n convert_specific_params_to_metafunc_arg_id,\n skip_if_no_vagrant_executable,\n)\nfrom tests.vagrant.common.vagrant_utils import (\n invoke_vagrant_command,\n)\n\n#\n# Module variables\n#\n\n# logger\n_LOGGER = logging.getLogger(__name__)\n\n# pytest marker\npytestmark = [pytest.mark.custom_vagrant_test, pytest.mark.custom_build_vm_test]\n\n\n#\n# Pytest hooks\n#\n\ndef pytest_generate_tests(metafunc):\n \"\"\"Metafunc hook for generating parameters for vagrant build vm tests\"\"\"\n\n # bail out if you're not trying to use specific_test_params\n if 'specific_test_params' not in metafunc.funcargnames:\n return\n\n # pick a vm list based on test scenario\n if metafunc.function.__name__ == 'test_make_in_vm':\n vagrant_vms = []\n for vagrant_vm in iter(VagrantVM):\n if vagrant_vm.vm_role == VagrantVMRole.BUILD:\n vagrant_vms.append(vagrant_vm)\n if not vagrant_vms:\n return\n else:\n return\n\n # pick vagrant box modes\n vagrant_box_modes = iter(VagrantBoxMode)\n\n # pick python version modes\n python_version_modes = iter(PythonVersionMode)\n\n # pick repo modes\n python_repo_modes = [PythonRepoMode.PUBLIC_ONLY]\n\n # generate all the combos\n arg_names = 'specific_test_params'\n arg_ids = []\n arg_values = []\n for vagrant_vm in vagrant_vms:\n for vagrant_box_mode in vagrant_box_modes:\n for python_version_mode in python_version_modes:\n for python_repo_mode in python_repo_modes:\n combo = SpecificTestParams(\n python_repo_mode=python_repo_mode,\n python_version_mode=python_version_mode,\n vagrant_vm=vagrant_vm,\n vagrant_box_mode=vagrant_box_mode,\n )\n arg_id = convert_specific_params_to_metafunc_arg_id(combo)\n arg_ids.append(arg_id)\n arg_values.append(combo)\n\n # return via hook\n metafunc.parametrize(arg_names, arg_values, indirect=False, ids=arg_ids, scope=None)\n\n\n#\n# Tests\n#\n\ndef test_make_in_vm(basic_test_params, specific_test_params):\n func_params = locals()\n _LOGGER.debug(\"Begin invoking test with %s\", func_params)\n\n # skip if no vagrant exe\n skip_if_no_vagrant_executable()\n\n # check vm\n vagrant_vm = specific_test_params.vagrant_vm\n if vagrant_vm.vm_role != VagrantVMRole.BUILD:\n pytest.skip(\"Vagrant VM {} not in role {}\".format(vagrant_vm.vm_name, VagrantVMRole.BUILD))\n\n # mint a default context\n extra_context = mint_extra_context(\n basic_test_params.cookiecutter_json_data, specific_test_params)\n\n # setup output directory\n output_dir_manager = OutputDirectoryManager(\n basic_test_params=basic_test_params,\n specific_test_params=specific_test_params,\n prefix=\"build\")\n test_output_path = output_dir_manager.setup()\n\n # call cookiecutter python API entry point (same one used by cli)\n invoker = CookieCutterInvoker(\n repo_root_path=basic_test_params.repo_root_path,\n cookiecutter_config_path=basic_test_params.cookiecutter_config_path)\n invoker.invoke_via_api(\n root_output_path=test_output_path,\n extra_context=extra_context)\n\n # figure out where the test output_path should have ended up\n project_output_path = output_dir_manager.get_project_output_path()\n\n # setup that output project as a minimally viable git repo\n prepare_minimal_viable_git_repo(project_output_path)\n\n # run a test within the vagrant vm\n try:\n invoke_vagrant_command(project_output_path, [\n vagrant_vm.get_status_cmd(),\n vagrant_vm.get_destroy_cmd(),\n vagrant_vm.get_up_cmd(),\n vagrant_vm.get_ssh_cmd('cd ~/cleanroom && make'),\n ])\n except Exception as error:\n _LOGGER.exception(\n \"Fatal error while running ssh commands within vm under test %s\",\n specific_test_params.vagrant_vm)\n pytest.fail(\"Action within vagrant vm {} failed, see logs for details: {}\".format(\n specific_test_params.vagrant_vm.name, error))\n finally:\n _LOGGER.debug(\"tear down vagrant vm under test\")\n invoke_vagrant_command(project_output_path, [vagrant_vm.get_destroy_cmd()])\n\n # done with test\n _LOGGER.debug(\"Finished invoking test with %s\", func_params)\n","sub_path":"testing/tests/vagrant/test_build_vm.py","file_name":"test_build_vm.py","file_ext":"py","file_size_in_byte":5120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"36148921","text":"import collections\n\nclass Solution(object):\n def longestConsecutive(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n maxLength = 0\n\n lengths = collections.Counter()\n \n for i in nums:\n if i not in lengths:\n lengths[ i ] = 1\n left, right = lengths[ i - 1 ], lengths[ i + 1 ]\n l = left + right + 1\n lengths[ i - left ], lengths[ i + right ] = l, l\n maxLength = max( l, maxLength )\n \n return maxLength\n\nclass Solution2(object):\n def longestConsecutive(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n maxLength, length = 0, 0\n counter = collections.Counter( nums )\n \n for i in counter:\n left = i - 1\n if left not in counter:\n length = 1\n\n j = i + 1\n while j in counter:\n length += 1\n j += 1\n maxLength = max( length, maxLength )\n \n return maxLength\n ","sub_path":"128.py","file_name":"128.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"638340284","text":"import sys\nimport string\nfrom itertools import permutations\nfrom graph import Graph\nfrom core import *\n\n\nclass ParseError(Exception):\n pass\n\nclass UndefinedLabel(ParseError):\n pass\n\n\nclass Lexer:\n\n def __init__(self, l):\n self.l = l\n self.ws()\n\n def peek(self):\n if not self.l:\n return self.l\n return self.l[0]\n\n def eol(self):\n return not self.l\n\n def is_punct(self, c):\n return c in \"&|^-+*/%=<>\"\n\n def match(self, tok):\n if not self.l.startswith(tok):\n return False\n\n is_word = tok[0] in string.ascii_letters\n rest = self.l[len(tok):]\n if rest:\n if is_word and rest[0] not in string.whitespace:\n return False\n elif self.is_punct(tok[0]) and self.is_punct(rest[0]):\n return False\n self.l = rest\n self.ws()\n return True\n\n def match_till(self, tok):\n res = \"\"\n while self.l and not self.l.startswith(tok):\n res += self.l[0]\n self.l = self.l[1:]\n return res\n\n def match_bracket(self, open_b, close_b):\n self.expect(open_b)\n level = 1\n res = \"\"\n while self.l and level:\n if self.match(open_b):\n level += 1\n elif self.match(close_b):\n level -= 1\n else:\n res += self.l[0]\n self.l = self.l[1:]\n return res\n\n def expect(self, tok, msg=None):\n if not self.match(tok):\n if msg is None:\n msg = \"Expected: '%s'\" % tok\n raise ParseError(msg, self.l)\n\n def ws(self):\n while self.l and self.l[0] == \" \":\n self.l = self.l[1:]\n\n def rest(self):\n return self.l.rstrip()\n\n def word(self):\n w = \"\"\n while self.l and self.l[0] in (string.ascii_letters + string.digits + \"_.\"):\n w += self.l[0]\n self.l = self.l[1:]\n return w\n\n def isident(self):\n return self.l[0] in string.ascii_letters + \"_\"\n\n def isdigit(self):\n return self.l[0] in string.digits\n\n def ident(self):\n assert self.isident(), repr(self.l)\n w = self.word()\n self.ws()\n return w\n\n def num(self):\n assert self.isdigit(), repr(self.l)\n base = 10\n if self.l.startswith(\"0x\"):\n base = 16\n w = self.word()\n self.ws()\n return int(w, 0), base\n\n def skip_comment(self):\n if self.match(\"/*\"):\n self.match_till(\"*/\")\n self.expect(\"*/\")\n\nclass Parser:\n\n def __init__(self, fname):\n self.fname = fname\n self.expect_line_addr = None\n self.cfg = None\n self.labels = {}\n self.curline = -1\n self.script = []\n self.pass_no = None\n self.lex = None\n\n def error(self, msg):\n print(\"%s:%d: %s\" % (self.fname, self.curline, msg))\n sys.exit(1)\n\n def parse_cond(self, lex):\n self.lex = lex\n lex.expect(\"(\")\n if lex.match(\"!\"):\n arg1 = self.parse_expr()\n cond = \"==\"\n arg2 = VALUE(0, 10)\n else:\n arg1 = self.parse_expr()\n lex.ws()\n if lex.peek() == \"&\":\n lex.expect(\"&\")\n assert lex.ident() == \"BIT\"\n lex.expect(\"(\")\n bit_no = self.parse_expr()\n lex.expect(\")\")\n arg1 = EXPR(\"&\", [arg1, EXPR(\"<<\", [VALUE(1, 10), bit_no])])\n if lex.peek() == \")\":\n cond = \"!=\"\n arg2 = VALUE(0, 10)\n else:\n matched = False\n for cond in (\"==\", \"!=\", \">=\", \"<=\", \">\", \"<\"):\n if lex.match(cond):\n matched = True\n break\n if not matched:\n self.error(\"Expected a comparison operator: \" + lex.l)\n arg2 = self.parse_expr()\n lex.expect(\")\")\n return COND(arg1, cond, arg2)\n\n\n # Get line from a file, expanding any \"macro-like\" features,\n # like \"if (cond) $r0 = $r1\"\n def get_expand_line(self, f):\n while True:\n l = f.readline()\n if not l:\n return [(None, None)]\n self.curline += 1\n l = l.rstrip()\n if not l:\n continue\n\n if l[0] == \"#\":\n if self.pass_no == 1:\n l = l[1:]\n if l.startswith(\"xform: \"):\n self.script.append(l.split(None, 1))\n elif l.startswith(\"xform_bblock: \"):\n self.script.append(l.split(None, 1))\n continue\n\n if self.expect_line_addr is None:\n self.expect_line_addr = self.detect_addr_field(l)\n\n if self.expect_line_addr:\n addr, l = l.split(\" \", 1)\n else:\n addr = str(self.curline)\n l = l.lstrip()\n\n if l.startswith(\"if \"):\n # May need to expand \"if macro\"\n lex = Lexer(l)\n lex.expect(\"if\")\n c = self.parse_cond(lex)\n rest = lex.rest()\n if not lex.match(\"goto\"):\n out = [\n (addr, \"if %s goto %s.1.cond\" % (str(c.neg()), addr)),\n (addr + \".0\", rest),\n (addr + \".1\", addr + \".1.cond:\"),\n ]\n return out\n\n return [(addr, l)]\n\n def parse_labels(self):\n self.pass_no = 1\n self.curline = 0\n with open(self.fname) as f:\n l = \"\"\n while l is not None:\n for addr, l in self.get_expand_line(f):\n if l is None:\n break\n if l[-1] == \":\":\n self.labels[l[:-1]] = addr\n\n def parse_reg(self, lex):\n lex.expect(\"$\")\n return REG(lex.ident())\n\n def parse_arglist(self):\n args = []\n self.lex.expect(\"(\")\n while not self.lex.match(\")\"):\n comm = \"\"\n if self.lex.match(\"/*\"):\n comm = \"/*\" + self.lex.match_till(\"*/\") + \"*/\"\n self.lex.expect(\"*/\")\n a = self.parse_expr()\n assert a, (repr(a), repr(self.lex.l))\n a.comment = comm\n args.append(a)\n if self.lex.match(\",\"):\n pass\n return args\n\n\n def parse_primary(self):\n if self.lex.match(\"*\"):\n self.lex.expect(\"(\", \"Dereference requires explicit pointer cast\")\n type = self.lex.ident()\n self.lex.expect(\"*\")\n self.lex.expect(\")\")\n e = self.parse_primary()\n return MEM(type, e)\n elif self.lex.match(\"(\"):\n e = self.parse_expr()\n self.lex.expect(\")\")\n if is_addr(e):\n # If there was identifier, check it for being a type name\n if e.addr in (\"i8\", \"u8\", \"i16\", \"u16\", \"i32\", \"u32\", \"i64\", \"u64\"):\n tp = e.addr\n e = self.parse_primary()\n return EXPR(\"CAST\", [tp, e])\n return e\n elif self.lex.peek() == \"$\":\n return self.parse_reg(self.lex)\n elif self.lex.isdigit():\n return VALUE(*self.lex.num())\n elif self.lex.match(\"-\"):\n e = self.parse_primary()\n if is_value(e):\n return VALUE(-e.val, e.base)\n return EXPR(\"NEG\", [e])\n elif self.lex.isident():\n id = self.lex.ident()\n if self.lex.peek() == \"(\":\n args = self.parse_arglist()\n return EXPR(\"SFUNC\", [SFUNC(id)] + args)\n else:\n return ADDR(self.labels.get(id, id))\n else:\n self.error(\"Cannot parse\")\n\n def parse_level(self, operators, next_level):\n e = next_level()\n match = True\n while match:\n for op in operators:\n if self.lex.match(op):\n e2 = next_level()\n e = EXPR(op, [e, e2])\n break\n match = False\n return e\n\n def parse_mul(self):\n return self.parse_level((\"*\", \"/\", \"%\"), self.parse_primary)\n\n def parse_add(self):\n e = self.parse_mul()\n while True:\n if self.lex.match(\"+\"):\n e2 = self.parse_mul()\n e = EXPR(\"+\", [e, e2])\n elif self.lex.match(\"-\"):\n e2 = self.parse_mul()\n e = EXPR(\"-\", [e, e2])\n else:\n break\n return e\n\n def parse_shift(self):\n return self.parse_level((\"<<\", \">>\"), self.parse_add)\n\n def parse_band(self):\n return self.parse_level((\"&\",), self.parse_shift)\n def parse_bxor(self):\n return self.parse_level((\"^\",), self.parse_band)\n def parse_bor(self):\n return self.parse_level((\"|\",), self.parse_bxor)\n\n def parse_land(self):\n return self.parse_level((\"&&\",), self.parse_bor)\n def parse_lor(self):\n return self.parse_level((\"||\",), self.parse_land)\n\n def parse_expr(self):\n return self.parse_lor()\n\n\n # If there's numeric value, treat it as address. Otherwise, parse expression.\n def parse_local_addr_expr(self):\n if self.lex.isdigit():\n w = self.lex.word()\n return ADDR(self.labels.get(w, w))\n return self.parse_expr()\n\n def get_label(self, label):\n try:\n return self.labels[label]\n except KeyError:\n raise UndefinedLabel(label)\n\n def label_from_addr(self, addr):\n labels = list(filter(lambda x: x[1] == addr, self.labels.items()))\n if not labels:\n return addr\n return labels[0][0]\n\n def parse_inst(self, l):\n lex = self.lex = Lexer(l)\n if lex.match(\"goto\"):\n return Inst(None, \"goto\", [self.parse_local_addr_expr()])\n if lex.match(\"call\"):\n return Inst(None, \"call\", [self.parse_expr()])\n if lex.match(\"if\"):\n c = self.parse_cond(lex)\n lex.expect(\"goto\")\n return Inst(None, \"if\", [c, ADDR(self.get_label(lex.rest()))])\n if lex.match(\"return\"):\n args = []\n while True:\n lex.skip_comment()\n if lex.eol():\n break\n a = self.parse_expr()\n args.append(a)\n if not lex.eol():\n lex.expect(\",\")\n return Inst(None, \"return\", args)\n\n dest = self.parse_expr()\n if not dest:\n return Inst(None, \"LIT\", [l])\n\n if is_expr(dest) and isinstance(dest.args[0], SFUNC):\n return Inst(None, \"SFUNC\", [dest])\n\n def make_assign_inst(dest, op, args):\n #return Inst(dest, op, args)\n return Inst(dest, \"=\", [EXPR(op, args)])\n\n lex.ws()\n if lex.match(\"&=\"):\n lex.ws()\n src = self.parse_expr()\n return make_assign_inst(dest, \"&\", [dest, src])\n elif lex.match(\"|=\"):\n lex.ws()\n src = self.parse_expr()\n return make_assign_inst(dest, \"|\", [dest, src])\n elif lex.match(\"^=\"):\n lex.ws()\n src = self.parse_expr()\n return make_assign_inst(dest, \"^\", [dest, src])\n elif lex.match(\"+=\"):\n lex.ws()\n src = self.parse_expr()\n return make_assign_inst(dest, \"+\", [dest, src])\n elif lex.match(\"-=\"):\n lex.ws()\n src = self.parse_expr()\n return make_assign_inst(dest, \"-\", [dest, src])\n elif lex.match(\"*=\"):\n lex.ws()\n src = self.parse_expr()\n return make_assign_inst(dest, \"*\", [dest, src])\n elif lex.match(\"/=\"):\n lex.ws()\n src = self.parse_expr()\n return make_assign_inst(dest, \"/\", [dest, src])\n elif lex.match(\"%=\"):\n lex.ws()\n src = self.parse_expr()\n return make_assign_inst(dest, \"%\", [dest, src])\n elif lex.match(\">>=\"):\n lex.ws()\n src = self.parse_expr()\n return make_assign_inst(dest, \">>\", [dest, src])\n elif lex.match(\"<<=\"):\n src = self.parse_expr()\n return make_assign_inst(dest, \"<<\", [dest, src])\n elif lex.match(\"=\"):\n lex.ws()\n src = self.parse_expr()\n assert src, repr(lex.l)\n if isinstance(src, SFUNC):\n args = self.parse_arglist()\n return Inst(dest, \"SFUNC\", [src] + args)\n lex.ws()\n if lex.eol():\n return Inst(dest, \"=\", [src])\n else:\n for op in (\"+\", \"-\", \"*\", \"/\", \"&\", \"|\", \"^\", \"<<\", \">>\"):\n if lex.match(op):\n src2 = self.parse_expr(lex)\n return make_assign_inst(dest, op, [src, src2])\n assert 0\n else:\n assert False, (repr(lex.l), self.curline)\n\n\n def detect_addr_field(self, l):\n # Autodetect whether there's address as first field\n # of line or not.\n self.expect_line_addr = False\n if l[0].isdigit():\n # Can be either label or address\n if l[-1] == \":\":\n if \" \" in l:\n return True\n else:\n return True\n return False\n\n\n def _parse_bblocks(self, f):\n self.cfg = Graph()\n self.cfg.name = None\n block = None\n last_block = None\n\n l = \"\"\n while l is not None:\n for addr, l in self.get_expand_line(f):\n if l is None:\n break\n if self.should_stop(l):\n return\n\n #print(addr, l)\n l = l.split(\";\", 1)[0]\n l = l.strip()\n if not l:\n continue\n\n if l[-1] == \":\":\n # label\n if block is not None:\n last_block = block\n block = BBlock(addr)\n block.cfg = self.cfg\n block.label = l[:-1]\n if self.cfg.name is None:\n # First label is function name\n self.cfg.name = l[:-1]\n self.cfg.add_node(addr, val=block)\n continue\n elif block is None:\n block = BBlock(addr)\n block.cfg = self.cfg\n self.cfg.add_node(addr, val=block)\n\n\n if last_block is not None:\n self.cfg.add_edge(last_block.addr, block.addr)\n #last_block.end.append(addr)\n last_block = None\n\n inst = self.parse_inst(l)\n inst.addr = addr\n\n if inst.op in (\"goto\", \"if\"):\n cond = None\n if inst.op == \"goto\":\n addr = inst.args[0]\n else:\n cond, addr = inst.args\n if not isinstance(addr, ADDR):\n # Skip handling indirect jumps\n block.add(inst)\n continue\n addr = addr.addr\n #print(\"!\", (cond, addr))\n if addr not in self.cfg:\n self.cfg.add_node(addr)\n self.cfg.add_edge(block.addr, addr, cond=cond)\n if cond:\n last_block = block\n else:\n last_block = None\n block.add(inst)\n block = None\n elif inst.op == \"return\":\n block.add(inst)\n block = None\n last_block = None\n else:\n block.add(inst)\n\n if last_block:\n print(\"Warning: function was not properly terminated\")\n self.cfg.add_edge(last_block.addr, block.addr)\n\n def parse_bblocks(self, f):\n self.pass_no = 2\n try:\n self._parse_bblocks(f)\n except ParseError as e:\n print(\"Error: %d: %r\" % (self.curline + 1, e))\n raise\n sys.exit(1)\n # External labels may produce empty CFG nodes during parsing.\n # Make a pass over graph and remove such.\n for node, info in list(self.cfg.iter_nodes()):\n if not info:\n self.cfg.remove_node(node)\n\n\n def parse(self):\n self.parse_labels()\n self.curline = 0\n with open(self.fname) as f:\n self.parse_bblocks(f)\n return self.cfg\n\n def should_stop(self, l):\n return False\n","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":17294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"463507230","text":"# Authors: Tao Huang \n#\n# License: BSD 3 clause\n\nimport numpy as np\n\nfrom sklearn.utils import check_random_state\n\nINT_MAX = np.iinfo(np.int32).max\n\ndef data_generation(n, d, random_state=None):\n '''\n Generate data for linear regression\n '''\n random_state = check_random_state(random_state)\n seed = random_state.randint(0,INT_MAX)\n np.random.seed(seed)\n\n dt_X = np.random.standard_normal((n,d))\n dt_y = np.sum(dt_X * [1,2], axis=1) + np.random.normal(0, 0.5, n)\n\n return dt_X, dt_y\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"155672735","text":"import unittest\nimport os, time\n\nimport OpTestConfiguration\n\nfrom common.OpTestSystem import OpSystemState\nfrom common.OpTestInstallUtil import InstallUtil\n\n\"\"\"\nTHE PLAN:\n\n - assert physical presence\n - clears any existing keys\n - gets the machine in a known state without secureboot\n - enroll a set of PK, KEK, db\n - pregenerated, use secvar sysfs interface\n - reboot, and ensure secure boot is now enabled\n - fail to regular kexec an unsigned kernel\n - fail to load an unsigned kernel\n - fail to load a dbx'd kernel\n - fail to load a signed kernel with unenrolled key\n - successfully load a signed kernel\n - assert physical presence\n - ensure machine is in a non-secure boot state\n\"\"\"\n\n\"\"\"\nGenerating physicalPresence.bin:\n Create an attribute override file with the following contents (not including leading spaces):\n\n CLEAR\n target = k0:s0:\n ATTR_BOOT_FLAGS 0x15000000 CONST\n ATTR_PHYS_PRES_FAKE_ASSERT 0x01 CONST\n # ATTR_PHYS_PRES_REQUEST_OPEN_WINDOW 0x01 CONST\n\n Go to your op-build's //build/hostboot-/obj/genfiles directory\n From that directory run the following:\n\n ./attributeOverride -d \n\n If it is successful, then an attrOverride.bin file will be created in that directory\n\"\"\"\n\n\"\"\"\nGenerating oskeys.tar:\n Keys were generated via the makefile in https://git.kernel.org/pub/scm/linux/kernel/git/jejb/efitools.git.\n NOTE: these tools will currently only build on x86\n Running make generates and assembles a set of openssl keys, ESLs, and signed auth files following the\n commands below.\n Only the auth files are included in the tarball.\n\n Generating keys (PK example):\n openssl req -new -x509 -newkey rsa:2048 -subj \"/CN=PK/\" -keyout PK.key -out PK.crt -days 3650 -nodes -sha256\n\n Generating ESLs (PK example):\n cert-to-efi-sig-list PK.crt PK.esl\n\n Generating Auths:\n sign-efi-sig-list -k PK.key -c PK.crt PK PK.esl PK.auth\n sign-efi-sig-list -k PK.key -c PK.crt KEK KEK.esl KEK.auth\n sign-efi-sig-list -k KEK.key -c KEK.crt db db.esl db.auth\n sign-efi-sig-list -k KEK.key -c KEK.crt dbx dbx.esl dbx.auth\n\n NOTE: dbx.esl is currently generated using a soon-to-be-released internal tool, and will be integrated in this test/documentation\n Normally, dbx.esl would be generated with hash-to-efi-sig-list, however that tool has a dependency on PECOFF which\n is not compatible with POWER.\n NOTE: newPK is signed by the PK to test updating the PK, and deletePK is an empty file signed by newPK\n to test the removal of a PK, which exits secure boot enforcement mode.\n\n\nGenerating oskernels.tar:\n kernel-unsigned - very stripped down kernel built with minimal config options. no signature\n kernel-signed - same kernel as above, signed with the db present in oskeys.tar\n kernel-unenrolled - same kernel, signed with another generated key that is NOT in oskeys.tar\n kernel-dbx - same kconfig, but adjusted version name. signed with the same db key. hash present in oskeys.tar's dbx\n\nSigning kernels:\n Kernels are signed with the `sign-file` utility in the linux source tree, like so:\n ./scripts/sign-file sha256 db.key db.crt vmlinuz kernel-signed\n\n\"\"\"\n\n\n# Variable data after enrollment (located in /sys/firmware/secvar/vars//data should\n# be in the ESL format, WITHOUT the signed update auth header.\n# These hashes are of the ESL data prior to signing the data as an update, and should match the\n# post-enrollment data\n# Future work: generate the full set of key/crt->ESL->auth data as part of this test, and\n# calculate the expected hashes from the generated ESL rather than hardcoding them here.\nesl_hashes = {\n \"PK\": \"91f15df8fc8f80bd0a1bbf2c77a5c5a16d2b189dd6f14d7b7c1e274fedd53f47\",\n \"KEK\": \"1b6e26663bbd4bbb2b44af9e36d14258cdf700428f04388b0c689696450a9544\",\n \"db\": \"480b652075d7b52ce07577631444848fb1231d6e4da9394e6adbe734795a7eb2\",\n \"dbx\": \"2310745cd7756d9bfd8cacf0935a27a7bd1d2f1b1783da03902b5598a0928da6\",\n \"newPK\": \"9a1d186c08c18887b68fadd81be48bca06dd007fa214dfcdb0f4195b5aff996c\",\n}\n\nclass OsSecureBoot(unittest.TestCase):\n def setUp(self):\n conf = OpTestConfiguration.conf\n self.cv_SYSTEM = conf.system()\n self.cv_BMC = conf.bmc()\n self.cv_HOST = conf.host()\n self.cv_IPMI = conf.ipmi()\n self.OpIU = InstallUtil()\n self.URL = conf.args.secvar_payload_url\n self.bmc_type = conf.args.bmc_type\n\n\n def getTestData(self, data=\"keys\"):\n con = self.cv_SYSTEM.console\n self.OpIU.configure_host_ip()\n\n fil = \"os{}.tar\".format(data)\n url = self.URL + \"/\" + fil\n\n con.run_command(\"wget {0} -O /tmp/{1}\".format(url, fil))\n con.run_command(\"tar xf /tmp/{} -C /tmp/\".format(fil))\n\n\n def checkFirmwareSupport(self):\n if \"OpenBMC\" not in self.bmc_type:\n self.skipTest(\"Test only applies for OpenBMC-based machines\")\n\n self.cv_SYSTEM.goto_state(OpSystemState.PETITBOOT_SHELL)\n con = self.cv_SYSTEM.console\n\n output = con.run_command_ignore_fail(\"test -d /sys/firmware/devicetree/base/ibm,opal/secvar || echo no\")\n if \"no\" in \"\".join(output):\n self.skipTest(\"Skiboot does not support secure variables\")\n\n output = con.run_command_ignore_fail(\"test -d /sys/firmware/secvar || echo no\")\n if \"no\" in \"\".join(output):\n self.skipTest(\"Skiroot does not support the secure variables sysfs interface\")\n\n # We only support one backend for now, skip if using an unknown backend\n # NOTE: This file must exist if the previous checks pass, fail the test if not present\n output = con.run_command(\"cat /sys/firmware/secvar/format\")\n if \"ibm,edk2-compat-v1\" not in \"\".join(output):\n self.skipTest(\"Test case only supports the 'ibm,edk2-compat-v1' backend\")\n\n\n def cleanPhysicalPresence(self):\n self.cv_BMC.run_command(\"rm -f /usr/local/share/pnor/ATTR_TMP\")\n self.cv_BMC.run_command(\"rm -f /var/lib/obmc/cfam_overrides\")\n\n # Unset the Key Clear Request sensor\n self.cv_IPMI.ipmitool.run(\"raw 0x04 0x30 0xE8 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00\")\n\n # Reboot to be super sure\n self.cv_SYSTEM.goto_state(OpSystemState.OFF)\n self.cv_SYSTEM.goto_state(OpSystemState.PETITBOOT_SHELL)\n\n\n # Assert physical presence remotely to remove any currently installed OS secure boot keys\n # NOTE: This is NOT something an end-user should expect to do, there is a different process\n # for a physical presence assertion that actually requires physical access on production machines\n # This is included in the test to make sure the machine is in a clean initial state, and also\n # to ensure that skiboot handles physical presence key clear reset requests properly.\n def assertPhysicalPresence(self):\n self.cv_SYSTEM.goto_state(OpSystemState.OFF)\n\n # This file was generated using the settings detailed at the top of this file\n # It should be sufficient for any version of hostboot after these attributes were added\n # This might break if something changes about these attributes, or if these attributes are not\n # used on a later platform.\n # NOTE: This override will NOT work on production firmware\n self.cv_BMC.image_transfer(\"test_binaries/physicalPresence.bin\")\n self.cv_BMC.run_command(\"cp /tmp/physicalPresence.bin /usr/local/share/pnor/ATTR_TMP\")\n\n # Disable security settings on development images, to allow remote physical presence assertion\n self.cv_BMC.run_command(\"echo '0 0x283a 0x15000000' > /var/lib/obmc/cfam_overrides\")\n self.cv_BMC.run_command(\"echo '0 0x283F 0x20000000' >> /var/lib/obmc/cfam_overrides\")\n\n # The rest of this function applies to the physical presence assertion of a production machine,\n # and should behave the same way.\n\n # The \"ClearHostSecurityKeys\" sensor is used on the OpenBMC to keep track of any Key Clear Request.\n # During the (re-)IPL, the values will be sent to Hostboot for processing.\n # This sets the sensor value to 0x40, which indicates KEY_CLEAR_OS_KEYS\n self.cv_IPMI.ipmitool.run(\"raw 0x04 0x30 0xE8 0x00 0x40 0x00 0x00 0x00 0x00 0x00 0x00 0x00\")\n\n # Read back the sensor value.\n # Expected Output is 4 bytes: where the first byte (ZZ) is the sensor value: ZZ 40 00 00\n output = self.cv_IPMI.ipmitool.run(\"raw 0x04 0x2D 0xE8\")\n self.assertTrue(\"40 40 00 00\" in output)\n \n # Special case, powering on this way since there is no appropriate state\n # for the opened physical presence window\n self.cv_SYSTEM.sys_power_on()\n\n raw_pty = self.cv_SYSTEM.console.get_console()\n\n # Check for expected hostboot log output for a success physical presence assertion\n raw_pty.expect(\"Opened Physical Presence Detection Window\", timeout=120)\n raw_pty.expect(\"System Will Power Off and Wait For Manual Power On\", timeout=30)\n raw_pty.expect(\"shutdown complete\", timeout=30)\n\n # Machine is off now, can resume using the state machine\n self.cv_SYSTEM.set_state(OpSystemState.OFF)\n\n # Turn it back on to complete the process\n self.cv_SYSTEM.goto_state(OpSystemState.PETITBOOT_SHELL)\n\n con = self.cv_SYSTEM.console\n\n # After a physical presence, the firmware should NOT be enforcing secure boot as there should be\n # no PK (or other secure boot keys)\n con.run_command(\"test ! -f /sys/firmware/devicetree/base/ibm,secureboot/os-secureboot-enforcing\")\n\n # After a physical presence clear, there should be device tree entries indicating that\n # 1. a physical presence was asserted, and\n con.run_command(\"test -f /sys/firmware/devicetree/base/ibm,secureboot/physical-presence-asserted\")\n # 2. what request was made, in this case clearing of os secureboot keys\n con.run_command(\"test -f /sys/firmware/devicetree/base/ibm,secureboot/clear-os-keys\")\n\n # As mentioned before, no keys should be enrolled, double check to make sure each is empty\n for k in [\"PK\", \"KEK\", \"db\", \"dbx\"]:\n # Size should be ascii \"0\" for each, as each should be empty\n output = con.run_command(\"cat /sys/firmware/secvar/vars/{}/size\".format(k))\n self.assertTrue(\"0\" in output)\n\n # Data should not contain anything\n output = con.run_command(\"cat /sys/firmware/secvar/vars/{}/data | wc -c\".format(k))\n self.assertTrue(\"0\" in output)\n\n\n # Enroll keys to enable secure boot\n # Keys are generated ahead of time, following the process outlined at the top of this file\n # See: \"Generating oskeys.tar\"\n def addSecureBootKeys(self):\n self.cv_SYSTEM.goto_state(OpSystemState.PETITBOOT_SHELL)\n con = self.cv_SYSTEM.console\n\n # Fetch the pregenerated test data containing the signed update files\n # Future work: generate these test files are part of the test case (dependent on efitools/secvarctl)\n self.getTestData()\n\n # Enqueue the PK update first, will enter secure mode and enforce signature\n # checking for the remaining updates below\n con.run_command(\"cat /tmp/PK.auth > /sys/firmware/secvar/vars/PK/update\")\n\n # Enqueue the KEK update\n con.run_command(\"cat /tmp/KEK.auth > /sys/firmware/secvar/vars/KEK/update\")\n\n # Enqueue the db update, this contains the key needed for validating signed kernels\n con.run_command(\"cat /tmp/db.auth > /sys/firmware/secvar/vars/db/update\")\n\n # Enqueue the dbx update, contains a list of denylisted kernel hashes\n con.run_command(\"cat /tmp/dbx.auth > /sys/firmware/secvar/vars/dbx/update\")\n\n # System needs to power fully off to process keys on next reboot\n # Key updates are only processed as skiboot initializes\n self.cv_SYSTEM.goto_state(OpSystemState.OFF) \n self.cv_SYSTEM.goto_state(OpSystemState.PETITBOOT_SHELL)\n\n # If all key updates were processed successfully, then we should have entered secure mode\n # This device tree entry is created if a PK is present, and forces skiroot to only kexec\n # properly signed kernels with a key in the db variable.\n con.run_command(\"test -f /sys/firmware/devicetree/base/ibm,secureboot/os-secureboot-enforcing\")\n\n # Loop through and double check that all the variables now contain data\n for k in [\"PK\", \"KEK\", \"db\", \"dbx\"]:\n # Size should return a nonzero ascii value when enrolled\n output = con.run_command(\"cat /sys/firmware/secvar/vars/{}/size\".format(k))\n self.assertFalse(\"0\" in output)\n\n # Data should contain the ESL data as generated before\n # NOTE: this is NOT the same as the .auth data, the auth header and signature are removed\n # as part of processing the update\n # Future work: compare the /data field against the generated ESL data\n output = con.run_command(\"cat /sys/firmware/secvar/vars/{}/data | wc -c\".format(k))\n self.assertFalse(\"0\" in output)\n\n # Check the integrity of the data by hashing and comparing against an expected hash\n # See top of the file for how these hashes were calculated\n output = con.run_command(\"sha256sum /sys/firmware/secvar/vars/{}/data\".format(k))\n # output is of the form [\" \"], so extract just the hash value to compare\n output = output[0].split(\" \")[0]\n self.assertTrue(esl_hashes[k] == output)\n\n\n # Attempt to kexec load a set of kernels to ensure secure mode is enforced correctly\n def checkKexecKernels(self):\n self.cv_SYSTEM.goto_state(OpSystemState.PETITBOOT_SHELL)\n con = self.cv_SYSTEM.console\n\n # Obtain pregenerated test kernels, see top of file for how these were generated\n self.getTestData(data=\"kernels\")\n\n # Fail regular kexec_load, syscall should be disabled by skiroot when enforcing secure boot\n # Petitboot should automatically use avoid using this syscall when applicable\n output = con.run_command_ignore_fail(\"kexec -l /tmp/kernel-unsigned\")\n self.assertTrue(\"Permission denied\" in \"\".join(output))\n\n # Fail using kexec_file_load with an unsigned kernel\n output = con.run_command_ignore_fail(\"kexec -s /tmp/kernel-unsigned\")\n self.assertTrue(\"Permission denied\" in \"\".join(output))\n\n # Fail loading a kernel whose hash is in the dbx denylist\n output = con.run_command_ignore_fail(\"kexec -s /tmp/kernel-dbx\")\n self.assertTrue(\"Permission denied\" in \"\".join(output))\n\n # Fail loading a properly signed kernel with key that is NOT enrolled in the db\n # Future work: enroll the key used to sign this kernel and try again\n output = con.run_command_ignore_fail(\"kexec -s /tmp/kernel-unenrolled\")\n self.assertTrue(\"Permission denied\" in \"\".join(output))\n\n # Successfully kexec_file_load a kernel signed with a key in the db\n output = con.run_command(\"kexec -s /tmp/kernel-signed\")\n\n # To replace the PK, sign a new PK esl with the previous PK\n # Replacing the PK will not change the secure enforcing status, nor will\n # it remove the other variables\n # To delete the PK, sign an empty file with the PK. The update processing\n # logic will interpret this as a deletion.\n # NOTE: removing the PK DISABLES OS secure boot enforcement, but will NOT\n # clear your other variables.\n def replaceAndDeletePK(self):\n con = self.cv_SYSTEM.console\n\n # Obtain tarball containing a replacement PK\n self.getTestData(data=\"keys\")\n\n # Enqueue an update to the PK\n # New PK updates must be signed with the previous PK\n con.run_command(\"cat /tmp/newPK.auth > /sys/firmware/secvar/vars/PK/update\")\n\n # Reboot the system to process the update\n self.cv_SYSTEM.goto_state(OpSystemState.OFF)\n self.cv_SYSTEM.goto_state(OpSystemState.PETITBOOT_SHELL)\n\n # Confirm we are still enforcing secure boot\n con.run_command(\"test -f /sys/firmware/devicetree/base/ibm,secureboot/os-secureboot-enforcing\")\n\n # Check that the new PK is enrolled now\n output = con.run_command(\"sha256sum /sys/firmware/secvar/vars/PK/data\")\n output = output[0].split(\" \")[0]\n self.assertTrue(esl_hashes[\"newPK\"] == output)\n\n # Obtain tarball containing a PK deletion update\n self.getTestData(data=\"keys\")\n\n # Enqueue a deletion update to the PK\n # This update is a signed empty file, which is interpreted as a deletion action\n con.run_command(\"cat /tmp/deletePK.auth > /sys/firmware/secvar/vars/PK/update\")\n\n # Reboot the system to process the update\n self.cv_SYSTEM.goto_state(OpSystemState.OFF)\n self.cv_SYSTEM.goto_state(OpSystemState.PETITBOOT_SHELL)\n\n # Secure boot enforcement should now be DISABLED\n con.run_command(\"test ! -f /sys/firmware/devicetree/base/ibm,secureboot/os-secureboot-enforcing\")\n\n # PK size should be empty now\n output = con.run_command(\"cat /sys/firmware/secvar/vars/PK/size\")\n self.assertTrue(\"0\" in output)\n\n # PK data should not contain any data\n output = con.run_command(\"cat /sys/firmware/secvar/vars/PK/data | wc -c\")\n self.assertTrue(\"0\" in output)\n\n # Loop through and double check that all the other variables still contain their data\n # This is the same logic as in .addSecureBootKeys()\n for k in [\"KEK\", \"db\", \"dbx\"]:\n output = con.run_command(\"cat /sys/firmware/secvar/vars/{}/size\".format(k))\n self.assertFalse(\"0\" in output)\n\n output = con.run_command(\"cat /sys/firmware/secvar/vars/{}/data | wc -c\".format(k))\n self.assertFalse(\"0\" in output)\n\n output = con.run_command(\"sha256sum /sys/firmware/secvar/vars/{}/data\".format(k))\n output = output[0].split(\" \")[0]\n self.assertTrue(esl_hashes[k] == output)\n\n\n def runTest(self):\n # skip test if the machine firmware doesn't support secure variables\n self.checkFirmwareSupport()\n\n # clean up any previous physical presence attempt\n self.cleanPhysicalPresence()\n\n # start in a clean secure boot state\n self.assertPhysicalPresence()\n self.cleanPhysicalPresence()\n\n # add secure boot keys\n self.addSecureBootKeys()\n\n # attempt to securely boot test kernels\n self.checkKexecKernels()\n\n # replace PK, delete PK\n self.replaceAndDeletePK()\n\n # clean up after, and ensure keys are properly cleared\n self.assertPhysicalPresence()\n self.cleanPhysicalPresence()\n","sub_path":"testcases/OsSecureBoot.py","file_name":"OsSecureBoot.py","file_ext":"py","file_size_in_byte":18807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"411246400","text":"\nfrom engster_manager.core import (\n read_lines,\n lines_to_df,\n combine_eng_kor,\n df_to_csv\n)\nfrom engster_manager.version import __version__\n\nfrom typing import Optional\nimport argparse\nimport sys\nimport os\n\n\ndef command_script():\n def print_version():\n version = __version__\n print('version {}, Kor-Eng Subtitle Manager for Engster (engster.co.kr)'\n .format(version))\n\n parser = argparse.ArgumentParser(\n prog='engster',\n usage='engster [OPTION]... PATH...',\n description='Kor-Eng Subtitle Manager for Engster',\n add_help=False\n )\n parser.add_argument(\n '-v', '--version', action='store_true',\n help='Print version and exit'\n )\n parser.add_argument(\n '-h', '--help', action='store_true',\n help='Print this help message and exit'\n )\n\n # subtitle path (.srt / or .smi)\n parser.add_argument('path', nargs='*', help=argparse.SUPPRESS)\n\n # subtitile path to create combined csv with path in path args\n parser.add_argument('-c', '--combine-path', nargs='*',\n help=\"Combine kor and eng subtitles\")\n\n parser.add_argument('-O', '--output-folder',\n help=\"Set output foldername\")\n\n parser.add_argument('-o', '--output-file', nargs='*',\n help=\"Set output filename\")\n\n args = parser.parse_args()\n path = args.path\n\n if not path:\n parser.print_help()\n sys.exit()\n\n if args.help:\n print_version()\n parser.print_help()\n sys.exit()\n\n if args.version:\n print_version()\n sys.exit()\n\n return args\n\n\ndef get_output(index: int, path: str, output_folder: str, output_files: Optional[str]) -> str:\n if not output_folder:\n output_folder = os.getcwd()\n path = os.path.join(output_folder, path.split('/')[-1])\n\n if output_files:\n output = output_files[index] if output_files else '.'.join(\n path.split('.')[:-1]) + '.csv'\n else:\n output = '.'.join(path.split('.')[:-1]) + '.csv'\n\n return output\n\n\ndef main():\n args = command_script()\n\n paths = args.path\n combine_paths = args.combine_path\n output_folder = args.output_folder\n output_files = args.output_file\n\n if output_files:\n assert len(paths) == len(output_files)\n\n if combine_paths:\n assert len(paths) == len(combine_paths)\n for i, path in enumerate(zip(paths, combine_paths)):\n lines_a = read_lines(path[0])\n lines_b = read_lines(path[1])\n df_a = lines_to_df(lines_a)\n df_b = lines_to_df(lines_b)\n import pandas as pd\n df = combine_eng_kor(df_a, df_b)\n output_path = get_output(i, path[0], output_folder, output_files)\n df_to_csv(df, output_path)\n print(f\"> {output_path}...complete\")\n else:\n for i, path in enumerate(paths):\n lines = read_lines(path)\n df = lines_to_df(lines)\n output_path = get_output(i, path, output_folder, output_files)\n df_to_csv(df, output_path)\n print(f\"> {output_path}...complete\")\n","sub_path":"engster_manager/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":3160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"570824393","text":"import os\nimport csv\nfrom random import shuffle\n\nimport numpy as np\nfrom scipy import ndimage\nimport matplotlib.pyplot as plt\n\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Input,Lambda,Cropping2D,Conv2D,Flatten,Dense,Dropout\nimport sklearn\nfrom sklearn.model_selection import train_test_split\n\ndef nvidia_model():\n model = Sequential()\n # normalize\n model.add(Lambda(lambda x: x/255.0 - 0.5, input_shape=(160,320,3)))\n # cropping\n model.add(Cropping2D(cropping=((70,25),(0, 0))))\n # conv2d\n model.add(Conv2D(24, kernel_size=(5, 5), strides=(2,2), activation=\"relu\"))\n model.add(Conv2D(36, kernel_size=(5, 5), strides=(2,2), activation=\"relu\"))\n model.add(Conv2D(48, kernel_size=(5, 5), strides=(2,2), activation=\"relu\"))\n model.add(Conv2D(64, kernel_size=(3, 3), activation=\"relu\"))\n model.add(Conv2D(64, kernel_size=(3, 3), activation=\"relu\"))\n model.add(Dropout(0.5))\n # fullconnect\n model.add(Flatten())\n model.add(Dense(100))\n model.add(Dense(50))\n model.add(Dense(10))\n model.add(Dense(1))\n return model\n\ndef image_generator(image_dir, samples, sample_size=32):\n steer_offsets = [0.2, 0, -0.2]\n num_samples = len(samples)\n \n while 1: # Loop forever so the generator never terminates\n shuffle(samples)\n for sample_offset in range(0, num_samples, sample_size):\n batch_samples = samples[sample_offset:sample_offset+sample_size]\n\n images = list()\n measurements = list()\n for sample in batch_samples:\n for i,steer_offset in enumerate(steer_offsets): \n source_path = sample[i]\n source_path = source_path.replace(\"\\\\\", \"/\")\n file_name = os.path.basename(source_path)\n image_path = os.path.join(image_dir, \"IMG\", file_name)\n\n # append images.\n image = ndimage.imread(image_path)\n images.append(image)\n \n # append measurements.\n measurement = float(sample[3]) + steer_offset\n measurements.append(measurement)\n \n # add flip data.\n image_flipped = np.fliplr(image)\n images.append(image_flipped)\n measurement_flipped = -measurement\n measurements.append(measurement_flipped)\n \n # trim image to only see section with road\n X_train = np.array(images)\n y_train = np.array(measurements)\n yield sklearn.utils.shuffle(X_train, y_train)\n\ndef save_losses(history):\n plt.plot(history.history['loss'])\n plt.plot(history.history['val_loss'])\n plt.title('model mean squared error loss')\n plt.ylabel('mean squared error loss')\n plt.xlabel('epoch')\n plt.legend(['training set', 'validation set'], loc='upper right')\n plt.savefig( 'loss.png' )\n\ndef train(cvs_path):\n # load samples.\n samples = list()\n with open(csv_path) as csv_file:\n reader = csv.reader(csv_file)\n header = next(reader) \n for line in reader:\n samples.append(line)\n train_samples, validation_samples = train_test_split(samples, test_size=0.2)\n\n # create a nvidia model.\n model = nvidia_model()\n model.compile(loss=\"mse\", optimizer=\"adam\")\n \n # train drives.\n sample_size=32 # batch size is 32*3*2. 3(left,center,right) x 2(flip) \n image_dir = os.path.dirname(csv_path)\n train_generator = image_generator(image_dir, train_samples, sample_size=sample_size)\n validation_generator = image_generator(image_dir, validation_samples, sample_size=sample_size)\n\n history = model.fit_generator(\n train_generator, \n steps_per_epoch=np.ceil(len(train_samples)/sample_size),\n validation_data=validation_generator, \n validation_steps=np.ceil(len(validation_samples)/sample_size),\n epochs=5, verbose=1)\n \n # save results. \n model.save(\"model.h5\")\n save_losses(history)\n\nif __name__==\"__main__\":\n import sys\n csv_path = sys.argv[1]\n \n train(csv_path)\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"193990329","text":"\"\"\"\nThis is the main starting point for project tuva.\nProject tuva is a generalized data fitting application. \nThe primary event loop will be initiated from the main function of this file.\n\nCustom modules will be contained in the folder ./imports\n\nPath to ./imports is added with AddSysPath\n\n\"\"\"\n\n\"\"\"\nImport global modules\n\"\"\"\n\nimport wx\n\n# Debugging\n#import pdb\n\n\"\"\"\nSetup path to custom modules\n\"\"\"\n\ndef AddSysPath(new_path):\n import sys, os\n # standardise\n new_path = os.path.abspath(new_path)\n\n # MS-Windows does not respect case\n if sys.platform == 'win32':\n new_path = new_path.lower()\n\n # disallow bad paths\n do = -1\n if os.path.exists(new_path):\n do = 1\n \n # check against all paths currently available\n for x in sys.path:\n x = os.path.abspath(x)\n if sys.platform == 'win32':\n x = x.lower()\n if new_path in (x, x + os.sep):\n do = 0\n\n # add path if we don't already have it\n if do:\n sys.path.append(new_path)\n pass\n\n\n\nif __name__ == \"__main__\":\n \n \"\"\"\n \n Setup data holding module for cross module data sharing.\n \n data module contains all data and must be imported into any module that will use it.\n \n \"\"\"\n \n AddSysPath('imports')\n \n \n import Data\n import MainWindow as mw\n \n # Import the data\n #Data.currentdata = Data.ImportOld('data/ISWI ATPase No Comp With 161 NCP 5-11-2012.dat')\n #Data.currentdata = Data.ImportOld('data/ISWI ATPase With ATP Gamma S With 161 NCP 5-11-2012.dat')\n Data.currentdata = Data.ImportOld('data/ISWI DNA Binding with ATP Gamma S.dat')\n \n \n # Instantiate the GUI enviornment.\n MainApp = wx.PySimpleApp()\n MainFrame = mw.CoreFrame(None)\n \n \"\"\"\n \n Start GUI\n \n \"\"\"\n \n \"\"\"\n # Inspection Widget this allows tracking of GUI objects when uncommented.\n import wx.lib.inspection\n wx.lib.inspection.InspectionTool().Show()\n \"\"\"\n \n # Startup main GUI Loop\n # Program runs as long as this loop is running\n MainApp.MainLoop()\n","sub_path":"tuva/tuva.py","file_name":"tuva.py","file_ext":"py","file_size_in_byte":2130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"128295027","text":"from winlist import get_win_pct_list_for_hand\nimport csv\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n## Samplesize and data is initialized\nsampleSize = 20000\ndata = np.array([])\n\n## Open in csv (excel)\nwith open('SRP.csv', mode='w') as poker_file: \n \n ## Create csv writer\n poker_writer = csv.writer(poker_file, delimiter=';', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n\n ## Write headerrow (first line)\n poker_writer.writerow(['Card 1', 'Card 2', 'Win Procent']) \n\n ## Create loop over x (card 1)\n for x in range(2,15):\n\n ## List of x constant and y in range 2-15 \n temp_data = []\n\n ## Create loop over y (card 2)\n for y in range(2,15): \n\n ## Number of wins\n win_list_x_y = get_win_pct_list_for_hand(x, y, sampleSize)\n\n ## Winprocent with one decimal (last item of win_list)\n win_pct = round(win_list_x_y[sampleSize - 1],1)\n\n ## Write one row (x,y)\n poker_writer.writerow([x, y, win_pct])\n \n ## Add winpct to tempdata\n temp_data.append(win_pct)\n\n ## Np array\n np_temp_data = np.array([temp_data])\n\n \n if x == 2:\n data = np_temp_data\n else:\n data = np.concatenate((data, np_temp_data))\n\nfig, ax = plt.subplots()\nim = ax.imshow(data)\n\nax.set_xticks(np.arange(13))\nax.set_yticks(np.arange(13))\n\nax.set_xticklabels(np.arange(2,15))\nax.set_yticklabels(np.arange(2,15))\n\nfor i in range(13):\n for j in range(13):\n text = ax.text(j, i, data[i, j],\n ha=\"center\", va=\"center\", color=\"w\", size=7)\n\nplt.show()\n\n\n# plt.ylabel('Win Procent')\n# plt.xlabel('Sample Size')\n# plt.title('Sandsynlighed for at vinde en bestemt hånd i poker')","sub_path":"poker_all_hands.py","file_name":"poker_all_hands.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"391989959","text":"from App.config import getConfiguration, setConfiguration\nfrom Testing import ZopeTestCase\nfrom ftw.builder.testing import BUILDER_LAYER\nfrom ftw.builder.testing import functional_session_factory\nfrom ftw.builder.testing import set_builder_session_factory\nfrom plone import api\nfrom plone.app.testing import FunctionalTesting\nfrom plone.app.testing import IntegrationTesting\nfrom plone.app.testing import PLONE_FIXTURE\nfrom plone.app.testing import PloneSandboxLayer\nfrom plone.app.testing import applyProfile\nfrom plone.app.testing import quickInstallProduct\nfrom plone.testing import z2\nfrom seantis.reservation.tests import builders # init builder config\n\n\ntry:\n from seantis.reservation import test_database\nexcept ImportError:\n from seantis.reservation.utils import ConfigurationError\n msg = 'No test database configured in seantis.reservation.test_database.'\n raise ConfigurationError(msg)\n\n\nclass SqlLayer(PloneSandboxLayer):\n\n defaultBases = (PLONE_FIXTURE, BUILDER_LAYER)\n\n class Session(dict):\n def set(self, key, value):\n self[key] = value\n\n @property\n def dsn(self):\n if not self.get('dsn'):\n self['dsn'] = test_database.testdsn\n\n return self['dsn']\n\n def init_config(self):\n config = getConfiguration()\n if not hasattr(config, 'product_config'):\n config.product_config = {}\n\n config.product_config['seantis.reservation'] = dict(dsn=self.dsn)\n\n setConfiguration(config)\n\n def setUpZope(self, app, configurationContext):\n\n # Set up sessioning objects\n app.REQUEST['SESSION'] = self.Session()\n ZopeTestCase.utils.setupCoreSessions(app)\n\n self.init_config()\n\n import seantis.reservation\n self.loadZCML(package=seantis.reservation)\n\n # treat certain sql warnings as errors\n import warnings\n warnings.filterwarnings('error', 'The IN-predicate.*')\n warnings.filterwarnings('error', 'Unicode type received non-unicode.*')\n\n def setUpPloneSite(self, portal):\n\n quickInstallProduct(portal, 'plone.app.dexterity')\n quickInstallProduct(portal, 'seantis.reservation')\n quickInstallProduct(portal, 'plone.formwidget.datetime')\n quickInstallProduct(portal, 'plone.formwidget.recurrence')\n applyProfile(portal, 'seantis.reservation:default')\n self._configure_default_workflow()\n\n def tearDownZope(self, app):\n z2.uninstallProduct(app, 'seantis.reservation')\n\n def _configure_default_workflow(self):\n \"\"\"Workflows are not configured by default.\n \"\"\"\n\n wftool = api.portal.get_tool(name='portal_workflow')\n wftool.setDefaultChain('simple_publication_workflow')\n\n\nSQL_FIXTURE = SqlLayer()\n\nSQL_INTEGRATION_TESTING = IntegrationTesting(\n bases=(SQL_FIXTURE, ),\n name=\"SqlLayer:Integration\"\n)\n\nSQL_FUNCTIONAL_TESTING = FunctionalTesting(\n bases=(SQL_FIXTURE,\n set_builder_session_factory(functional_session_factory)),\n name=\"SqlLayer:Functional\"\n)\n","sub_path":"seantis/reservation/testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":3031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"4144156","text":"import matplotlib\nimport matplotlib.pyplot as plt\n# matplotlib.use('Agg')\nimport xarray\nimport sys\nimport pandas\nimport numpy as np\n\nfilenames=sys.argv[1:-1]\n\nif sys.argv[-1].endswith('.nc'):\n filenames.append(sys.argv[-1])\n figdir='Mn_output/Figures'\nelse:\n figdir=sys.argv[-1]\n\n\n# result_files = [\n# 'Mn_ph35_saved_2020-08-31.nc',\n# 'Mn_ph40_saved_2020-08-31.nc',\n# 'Mn_ph45_saved_2020-08-31.nc',\n# 'Mn_ph50_saved_2020-08-31.nc',\n# 'Mn_ph55_saved_2020-08-31.nc',\n# ]\n\nleafC_mass_conv=1.0 # For simulations after I started applying the C to dry mass conversion in the sims. Otherwise it should be 0.4\nmolar_volume_birnessite = 251.1700 # Divide by 7 below because birnessite is defined in database as 7 mols of Mn\nMn_molarmass=54.94 #g/mol\n\n\ndef getval_from_str(s,subs,valtype=float):\n return valtype(s[s.index(subs)+len(subs):].partition('_')[0])\n\ndef getgroups(filename):\n import netCDF4\n with netCDF4.Dataset(filename) as d:\n groups=list(d.groups.keys())\n return groups\n\ndef load_data(filenames,chunks={},readgroups=False):\n data_list=[]\n incubation_list=[]\n\n allfilenames=[]\n groupnames=[]\n\n from Manganese_profile import setup_sims,make_gname,molar_mass\n expected_sims=setup_sims()\n expected_sims['simnum']=expected_sims.index\n\n for filenum,filename in enumerate(sorted(filenames)):\n print('Reading file %s'%filename)\n\n if readgroups:\n groups=getgroups(filename)\n else:\n groups=[]\n for n in range(filenum,len(expected_sims),len(filenames)):\n name=make_gname(expected_sims['pH'][n],\n expected_sims['Ndep'][n]*1000/molar_mass['N']/100**2/(365*24*3600),\n expected_sims['warming'][n],expected_sims['anox_freq'][n],expected_sims['anox_len'][n],\n expected_sims['birn_rate'][n])\n groups.append(name )\n # if (expected_sims['Ndep'][n]==0) and (expected_sims['warming'][n]==0) and (expected_sims['anox_len'][n]==0.5):\n # groups.append(name+'_incubation')\n\n for g in groups:\n print(g,flush=True)\n\n d=xarray.open_dataset(filename,group=g,chunks=chunks,decode_times=False)\n if 'soil_pH' not in d:\n d['soil_pH']=getval_from_str(g,'pH')\n d['Ndep']=getval_from_str(g,'Ndep',int)\n d['warming']=getval_from_str(g,'warming')\n d['redox_cycles']=getval_from_str(g,'anox_freq',int)\n d['anox_lenscales']=getval_from_str(g,'anox_len')\n newdims=['soil_pH','Ndep','warming','redox_cycles']\n d=d.expand_dims(newdims).set_coords(newdims)\n if 'birnrate' not in d:\n d['birnrate']=getval_from_str(g,'birnrate')\n d=d.expand_dims('birnrate').set_coords('birnrate')\n if 'incubation' in g:\n incubation_list.append(d)\n else:\n data_list.append(d)\n allfilenames.append(filename)\n groupnames.append(g)\n\n pH_sims=np.array([d['soil_pH'].item() for d in data_list])\n Ndep_sims=np.array([d['Ndep'].item() for d in data_list])\n warming_sims=np.array([d['warming'].item() for d in data_list])\n anox_freq_sims=np.array([d['redox_cycles'].item() for d in data_list])\n anox_len_sims=np.array([d['anox_lenscales'].item() for d in data_list])\n birnrate_sims=np.array([d['birnrate'].item() for d in data_list])\n allsims=pandas.DataFrame({'Ndep':Ndep_sims,'warming':warming_sims,'anox_freq':anox_freq_sims,'anox_len':anox_len_sims,'pH':pH_sims,'birnrate':birnrate_sims})\n\n comp=allsims.merge(expected_sims,how='outer',indicator=True)\n missing=comp[comp['_merge']!='both']\n if len(missing)>0:\n print('Warning: Not all expected sims were found:')\n print(missing)\n print('Generating all nan data for missing simulations.')\n for num in missing.index:\n d=(data_list[0]*np.nan).assign_coords(\n soil_pH=np.atleast_1d(missing.loc[num]['pH']),\n Ndep=np.atleast_1d(missing.loc[num]['Ndep']),\n warming=np.atleast_1d(missing.loc[num]['warming']),\n redox_cycles=np.atleast_1d(missing.loc[num]['anox_freq']),\n anox_lenscales=np.atleast_1d(missing.loc[num]['anox_len']))\n data_list.append(d)\n\n pH_sims=np.array([d['soil_pH'].item() for d in data_list])\n Ndep_sims=np.array([d['Ndep'].item() for d in data_list])\n warming_sims=np.array([d['warming'].item() for d in data_list])\n anox_freq_sims=np.array([d['redox_cycles'].item() for d in data_list])\n anox_len_sims=np.array([d['anox_lenscales'].item() for d in data_list])\n birnrate_sims=np.array([d['birnrate'].item() for d in data_list])\n\n x=(anox_len_sims==1.0)&(anox_freq_sims>0)\n # if len(pH_sims[x])%len(np.unique(pH_sims)) != 0:\n # raise ValueError(\"Simulations don't appear to divide evenly by pH and birnessite rate!\")\n if not x.any():\n raise ValueError('No simulations meet criteria for alldata')\n alldata=xarray.combine_by_coords(data_list[xx] for xx in np.nonzero(x)[0])\n x=(Ndep_sims==0)&(warming_sims==0)&(birnrate_sims.round(5)==4.0)&(pH_sims==5.0)\n if not x.any():\n raise ValueError('No simulations meet criteria for redoxdata')\n redoxdata=xarray.combine_by_coords(data_list[xx] for xx in np.nonzero(x)[0])\n\n print('Finished combining data',flush=True)\n return alldata,redoxdata,incubation_list\n\nif len(filenames)>0:\n alldata,redoxdata,incubation_list=load_data(filenames,chunks={},readgroups=False) # Use chunks={'time':3650} for long datasets\ncontroldata=alldata.isel(Ndep=0,warming=0)\n\ndef getdata(soil_pH,Ndep,warming,redox_cycles=50,anox_lenscale=0.5):\n # return data_list[flatnonzero((pH_sims==soil_pH)&(Ndep_sims==Ndep)&(warming_sims==warming)&(anox_freq_sims==redox_cycles)&(anox_len_sims==anox_lenscale))[0]].squeeze()\n return alldata.sel(soil_pH=soil_pH,Ndep=Ndep,warming=warming,anox_lenscales=anox_lenscale,redox_cycles=redox_cycles)\n\ndef save_one_fig(f,dirname=figdir,format='png',**kwargs):\n fname_fixed=f.get_label().replace('/','-')\n savename='{dirname:s}/{fname:s}.{format}'.format(dirname=dirname,format=format,fname=fname_fixed)\n print(savename)\n f.savefig(savename,**kwargs)\n\ndef letter_label(ax,label=None,x=0.03,y=1.03,title=True,**kwargs):\n from string import ascii_lowercase\n if isinstance(label,int):\n label='('+ascii_lowercase[label]+')'\n if title:\n return ax.set_title(label,loc='left')\n else:\n return ax.text(x,y,label,transform=ax.transAxes,**kwargs)\n\ndt=(controldata['time'][1]-controldata['time'][0]).item()\noneyr=int(365/dt)\n\nanox_baseline_i=0\nanox_baseline=redoxdata['anox_lenscales'][anox_baseline_i].load().item()\nbirnrate_baseline_i=2\n\nf,axs=plt.subplots(num='Figure S1 Saturated time fraction',clear=True)\nO2=redoxdata['Total O2(aq)'].sel(soil_pH=5.0).squeeze()\nsatfrac=(O2Carboxylate-','Carboxylic_acid','H2O','Root_biomass',\n 'Sorption_capacity','Lignin depolymerization','Lignin exposure','Lignin','DOM2 aerobic respiration'],\n font_size='medium',node_size=500,font_color='k',arrowstyle='->',arrowsize=10.0,edge_color='gray',node_alpha=1.0,\n namechanges={'cellulose':'Cellulose','DOM1':'DOM','O2(aq)':'O$_2$(aq)','CH4(aq)':'CH$_4$(aq)','HCO3-':'CO$_2$','DOM2':'Lignin','sorbed_DOM1':'Sorbed DOM',\n 'Fe(OH)2':'Fe(OH)$_2$','Fe(OH)3':'Fe(OH)$_3$','Mn++':r'Mn$^\\mathrm{+\\!\\!+}$','Mn+++':r'Mn$^\\mathrm{+\\!\\!+\\!\\!\\!+}$','Acetate-':'Acetate',\n 'DOM3':'MAOM','Tracer2':'Root uptake','Birnessite2':'Birnessite'},connectionstyle='arc3, rad=0.2')#,pos=pos)\n\nsave_one_fig(networkfig)\n\n######\n# Plot annual decomp for comparison with litter decomposition studies\n#####\n\n\nincubation_data=xarray.combine_by_coords(incubation_list).squeeze()\nincubation_data=controldata.isel(depth=0).squeeze()\nimport pandas\ndatadir='/home/b0u/Mn data/'\nBerg_massloss1=pandas.read_csv(datadir+'Berg et al 2015/Fig 4A.csv')\nBerg_massloss2=pandas.read_csv(datadir+'Berg et al 2015/Fig 4B.csv')\n\nf,axs=plt.subplots(1,1,num='Figure S2 Litter annual mass loss',clear=True,figsize=(8,4.6))\nincubation_length=1\naddyrs=0\nlitter_massloss=(1-(incubation_data['Total Sorbed Lignin']+incubation_data['Total Sorbed Cellulose']).isel(time=slice(oneyr+addyrs*oneyr,None,oneyr*incubation_length))/(incubation_data['Total Sorbed Lignin']+incubation_data['Total Sorbed Cellulose']).isel(time=1+addyrs*oneyr)).to_masked_array().ravel()*100\nlignin_massloss=(1-(incubation_data['Total Sorbed Lignin']).isel(time=slice(oneyr+addyrs*oneyr,None,oneyr*incubation_length),)/(incubation_data['Total Sorbed Lignin']).isel(time=1+addyrs*oneyr)).to_masked_array().ravel()*100\n\n# Mn_conc=incubation_data['litter_Mn'].to_masked_array().ravel().compressed()[1::incubation_length]*leafC_mass_conv\nMn_conc=(incubation_data['Total Mn++']*(incubation_data['Porosity']*incubation_data['saturation']*incubation_data['dz']/100*1e3)*1e3/(.163/.4)).isel(time=slice(1,None,oneyr*incubation_length)).to_masked_array().ravel()\n\nMn_conc=(incubation_data['Total Mn++']*(incubation_data['Porosity']*incubation_data['saturation']*incubation_data['dz']/100*1e3)*1e3/(.163/.4)).coarsen(time=oneyr,boundary='trim').max()\nlignindep=.163*.25/.05/12*1e3\n# lignin_massloss=100-(incubation_data['Total Sorbed Lignin']-incubation_data['Total Sorbed Lignin'].shift(time=oneyr)).isel(time=slice(oneyr*5,oneyr*15,oneyr)).to_masked_array().ravel()/lignindep*100\nlignin=incubation_data['Total Sorbed Lignin']+incubation_data['Total DOM2']*1000*0.5\nlignin_massloss=(lignin.coarsen(time=oneyr,boundary='trim').max()-lignin.coarsen(time=oneyr,boundary='trim').min()).compute()/lignindep*100\n\n# x=np.argsort(Mn_conc)\n# axs[0].plot(Mn_conc[x],litter_massloss[x],'-o',label='Model mass loss')\naxs.plot(Mn_conc[:,:,15:30:4].to_masked_array().ravel(),lignin_massloss[:,:,15:30:4].to_masked_array().ravel(),'o',label='Model lignin mass loss')\n# axs[0].plot(Berg_massloss1['x'],Berg_massloss1['Massloss'],'+',label='Berg multiple species')\naxs.plot(Berg_massloss2['x']/(1e-3*Mn_molarmass),Berg_massloss2['Massloss'],'+',label='Berg et al. (2013) measurements')\n# axs[0].plot(Davey_data['Mn mg-g-1 DM'],Davey_data['Limit value']*(1-exp(-Davey_data['k value']*oneyr*1*100/Davey_data['Limit value'])),'x',label='Davey Oak') \naxs.set_xlabel('Litter Mn concentration (mmol kg$^{-1}$)')\naxs.set_ylabel('Mass loss (%)')\naxs.legend()\naxs.set_title('One year mass loss')\n\nsave_one_fig(f)\n\n# Davey_data=pandas.read_excel(datadir+'Davey et al 2007/Davey et al 2007 table data.xlsx',sheet_name=0)\n\n# axs[1].set_title('Mass loss over time')\n# t=np.linspace(0,1000,20)\n# cmap=plt.get_cmap('viridis')\n# for site in range(len(Davey_data)):\n# m=Davey_data['Limit value'][site]\n# k=Davey_data['k value'][site]\n# davey_line=axs[1].plot(t,m*(1-np.exp(-k*t/(m/100))),c=cmap(Davey_data['Mn mg-g-1 DM'][site]/(1e-3*Mn_molarmass)/Mn_conc.max()),ls=':')\n \n# initial_mass=(incubation_data['Total Sorbed Lignin']+incubation_data['Total Sorbed Cellulose']).isel(time=1) \n# # t=arange(0,oneyr*incubation_length-dt,dt)\n# for ph in range(len(np.atleast_1d(incubation_data.soil_pH))):\n# for birnrate in range(len(np.atleast_1d(incubation_data.birnrate))):\n# for rep in range(len(incubation_data['litter_year'])//incubation_length):\n# massloss=(1-(incubation_data['Total Sorbed Lignin']+incubation_data['Total Sorbed Cellulose']).isel(soil_pH=ph,birnrate=birnrate)[1+oneyr*rep*incubation_length:oneyr*(rep+1)*incubation_length]/initial_mass.isel(soil_pH=ph,birnrate=birnrate))*100\n# mod_line=axs[1].plot(massloss['time']-massloss['time'][0],massloss,c=cmap(incubation_data['litter_Mn'].isel(soil_pH=ph,birnrate=birnrate,litter_year=rep*incubation_length)*leafC_mass_conv/Mn_conc.max()))\n\n# axs[1].set_xlabel('Time (days)')\n# axs[1].set_ylabel('Mass loss (%)')\n# cb=f.colorbar(matplotlib.cm.ScalarMappable(cmap=cmap,norm=plt.Normalize(vmin=0,vmax=Mn_conc.max())),ax=axs[1])\n# cb.set_label('Litter Mn concentration (mmol kg$^{-1}$)')\n# axs[1].legend(handles=davey_line+mod_line,labels=['Davey et al. (2007) measurements','Model'])\n\n# for num in range(axs.size):\n# letter_label(axs.ravel()[num],num)\n\n# save_one_fig(f)\n\nf,axs=plt.subplots(nrows=4,num='Incubation time series',clear=True,figsize=(4,6))\naxs[0].plot(incubation_data['Total Mn++'].isel(birnrate=4,soil_pH=0))\naxs[0].plot(incubation_data['Total Mn++'].isel(birnrate=1,soil_pH=0))\naxs[0].plot(incubation_data['Total Mn++'].isel(birnrate=4,soil_pH=4))\naxs[0].plot(incubation_data['Total Mn++'].isel(birnrate=1,soil_pH=4))\naxs[0].set(title='Mn(II) concentration')\n\naxs[1].plot(incubation_data['Total chelated_Mn+++'].isel(birnrate=4,soil_pH=0))\naxs[1].plot(incubation_data['Total chelated_Mn+++'].isel(birnrate=1,soil_pH=0))\naxs[1].plot(incubation_data['Total chelated_Mn+++'].isel(birnrate=4,soil_pH=4))\naxs[1].plot(incubation_data['Total chelated_Mn+++'].isel(birnrate=1,soil_pH=4))\naxs[1].set(title='Chelated Mn(III) concentration')\n\naxs[2].plot(incubation_data['Total DOM2'].isel(birnrate=4,soil_pH=0))\naxs[2].plot(incubation_data['Total DOM2'].isel(birnrate=1,soil_pH=0))\naxs[2].plot(incubation_data['Total DOM2'].isel(birnrate=4,soil_pH=4))\naxs[2].plot(incubation_data['Total DOM2'].isel(birnrate=1,soil_pH=4))\naxs[2].set(title='DOM2 concentration')\n\naxs[3].plot(incubation_data['Total Sorbed Lignin'].isel(birnrate=4,soil_pH=0))\naxs[3].plot(incubation_data['Total Sorbed Lignin'].isel(birnrate=1,soil_pH=0))\naxs[3].plot(incubation_data['Total Sorbed Lignin'].isel(birnrate=4,soil_pH=4))\naxs[3].plot(incubation_data['Total Sorbed Lignin'].isel(birnrate=1,soil_pH=4))\naxs[3].set_title('Lignin')\n\ndef save_all_figs(dirname,format='png',**kwargs):\n for fname in plt.get_figlabels():\n fname_fixed=fname.replace('/','-')\n print(fname_fixed)\n plt.figure(fname_fixed).savefig('{dirname:s}/{fname:s}.{format}'.format(dirname=dirname,format=format,fname=fname_fixed),**kwargs)\n\n\n\n\n","sub_path":"plot_Mn_sims.py","file_name":"plot_Mn_sims.py","file_ext":"py","file_size_in_byte":51085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"641012497","text":"import mock\nimport json\nimport datetime\nfrom tests.cms.models.test_api import _fetch_tmp_api\nfrom tests.cms.models.test_role import _fetch_tmp_role\n\nheaders = {'Content-Type': 'application/json'}\n\ndef test_attendance_api(app, client, db):\n with mock.patch('cms.resources.gateway.resource.requests') as requests:\n # mock actual GET call\n requests.get.return_value.json.return_value = {}\n with app.app_context():\n someapi = _fetch_tmp_api(db, **{'name': 'attendance_api',\n 'host': 'http://localhost:5000',\n 'endpoint': '/api/attendance/.*'})\n volunteer_role = _fetch_tmp_role(db, **{'name': 'volunteer'})\n someapi.roles.append(volunteer_role)\n db.session.commit()\n today = datetime.date.today()\n res = client.get('/gateway/api/attendance/{}'.format(today.strftime('%d%m%Y')),\n headers=headers)\n print(res.data)\n assert res.status_code == 200\n requests.get.assert_called_with(f\"http://localhost:5000/api/attendance/{today.strftime('%d%m%Y')}\",\n headers=mock.ANY, params=mock.ANY)\n for call in requests.get.call_args_list:\n assert 'headers' in call.kwargs\n assert 'Authorization' in call.kwargs.get('headers')\n \n with mock.patch('cms.resources.gateway.resource.requests') as requests:\n # mock actual POST call\n requests.post.return_value.json.return_value = {}\n post_data = {'student_id': 1,\n 'date': datetime.date.today().isoformat(),\n 'punch_in': datetime.datetime.now().isoformat(),\n 'punch_in_by_id': 1\n }\n res = client.post('/gateway/api/attendance/',\n data=json.dumps(post_data),\n headers=headers)\n print(res.data)\n assert res.status_code == 200\n requests.post.assert_called_with(\"http://localhost:5000/api/attendance/\",\n json=post_data, headers=mock.ANY)\n for call in requests.get.call_args_list:\n assert 'headers' in call.kwargs\n assert 'Authorization' in call.kwargs.get('headers')","sub_path":"tests/cms/resources/test_gateway.py","file_name":"test_gateway.py","file_ext":"py","file_size_in_byte":2321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"345609203","text":"import pickle\nimport random\nfrom dataclasses import dataclass, field\nimport datetime\n\nfrom jspider.JTime import now\nfrom jspider.net import send_request\nimport requests\nimport logging\nfrom pathlib import Path\nfrom sql import proxy_insert, get_proxy_all, proxy_delete\nfrom settings import proxy_log\n\n'''\njshen lib\n'''\nlogging.basicConfig(level=logging.INFO,\n filename=proxy_log,\n filemode='a+')\n\n\ndef format_proxy(ip: str, port: str) -> dict:\n port = str(port)\n ip_port = \"%s:%s\" % (ip.strip(), port.strip())\n proxy = {\n \"http\": ip_port,\n \"https\": ip_port\n }\n return proxy\n\n\ndef is_alive(ip, port):\n \"\"\"\n Check if a proxy is alive or not\n @return: True if alive, False otherwise\n 很费时间,评价某个代理是否可用的标准是 timeout超时\n \"\"\"\n port = str(port)\n proxy = format_proxy(ip, port)\n try:\n sattus_code = requests.get('http://www.baidu.com', proxies=proxy, timeout=3).status_code\n if int(sattus_code) >= 400:\n return False\n except:\n return False\n return True\n\n\ndef _climb_proxy_66ip(url_):\n \"\"\"\n 66代理网页,某一页代理ip的爬取\n http://www.66ip.cn/index.html\n \"\"\"\n soup = send_request(url_)\n center_tag = soup.select('div[align=\"center\"]')[1]\n tr_tag = center_tag.find_all('tr')\n for tr in tr_tag[1::]:\n tmp = tr.find_all('td')[:2:]\n ip = tmp[0].string.strip()\n port = tmp[1].string.strip()\n if is_alive(ip, port):\n # 插入数据库\n proxy_insert(ip, port, True)\n\n\ndef climb_proxys(end_page):\n \"\"\"\n 爬取代理ip\n * 若是每天第一次爬取,先执行 regular_check 删去数据库中已经死掉的代理\n * 66代理网页,\n 这个网站可能会挂,或者网页格式会变化,若出错try,except把错误抛出去\n \"\"\"\n _66ip = \"http://www.66ip.cn/index.html\"\n try:\n _climb_proxy_66ip(_66ip)\n for p in range(2, end_page + 1):\n url_ = f\"http://www.66ip.cn/{p}.html\"\n _climb_proxy_66ip(url_)\n except Exception as e:\n # 异常已经在sql中,捕获了,在此处是没有任何输出的\n pass\n\n\ndef regular_check():\n \"\"\"\n 每天检查一下数据库的代理ip,已经死亡的代理立即删掉\n \"\"\"\n res = get_proxy_all()\n for data in res:\n ip = data.get(\"ip\")\n port = data.get(\"port\")\n if not is_alive(ip, port):\n proxy_delete(ip)\n logging.warning(f\"{str(now())}: {ip} 超时,从mysql中删除\")\n\n\n# 全局代理列表\nproxy_list = []\n\n\n# 获得一个随机可用的代理\ndef get_random_proxy() -> dict:\n \"\"\"\n 从数据库中随机返回一个dict的proxy,可能为None\n \"\"\"\n global proxy_list\n if len(proxy_list) == 0:\n proxy_list = get_proxy_all()\n # None,表示不使用代理,本机也参与爬取数据\n proxy_list.append(None)\n data = random.choice(proxy_list)\n if data is None:\n return None\n return format_proxy(data.get(\"ip\"), data.get(\"port\"))\n\n\n# 检查活着的代理\n\n\n# class ProxyImpl:\n# def __init__(self, grave_obj_path: str):\n# self.__item: dict[str:JProxy] = dict()\n# self.__grave_obj_path = grave_obj_path\n# self.grave: ProxyGrave = load_proxy_grave(grave_obj_path)\n#\n# def __getitem__(self, ip):\n# return self.__item.get(ip)\n#\n# def __iter__(self):\n# return self.__item\n#\n# def add(self, ip: str, proxy_: JProxy) -> None:\n# # 已有的代理,不作处理\n# if ip in self.__item:\n# return\n# # 增加新的代理,没有比对grave中死掉的代理\n# self.__item[ip] = proxy_\n#\n# def get_random_proxy(self) -> dict:\n# \"\"\"\n# 随机获取某个代理,\n# 待处理:如果代理的列表是空,这个异常的处理\n# \"\"\"\n#\n# ip = random.choice(list(self.__item.keys()))\n# return self.get(ip)\n#\n# def get(self, ip) -> dict:\n# \"\"\"\n# 通过ip获取某个指定的代理\n# \"\"\"\n# tmp: JProxy = self.__item[ip]\n# return format_proxy(ip, tmp.port)\n#\n# def push_grave(self, ip):\n# \"\"\"\n# 由于某个代理加入时,不会在grave中检查是否已经存在;\n# 故,当某个这个代理死亡的时候,需要在grave中检测。若端口不一样,用新端口覆盖掉旧端口\n# 字典删除\n# \"\"\"\n# # 删除的元素必须存在\n# if ip in self.__item.keys():\n# self.grave.receive(ip, self.__item[ip])\n# # 立即保存到本地\n# pickle.dump(self.grave, open(self.__grave_obj_path, 'wb'))\n# del self.__item[ip]\n#\n# def __repr__(self):\n# return self.__item.__repr__()\n#\n# def __len__(self):\n# return len(self.__item)\n\n\n# class ProxyGrave:\n# \"\"\"\n# 没有实质上的用处,只是记录使用过的代理和次数\n# 对于死亡的代理,会立即从变量中移除,故需要立刻写入grave文件中,避免程序崩溃造成的数据丢失\n#\n# 未来功能:\n# 从grave中取出代理,有的代理在未来可能可以重新使用\n# \"\"\"\n#\n# def __init__(self):\n# self.__items: dict[str:JProxy] = dict()\n#\n# def __repr__(self):\n# return self.__items.__repr__()\n#\n# def receive(self, ip: str, jp: JProxy):\n# if ip not in self.__items:\n# self.__items[ip] = jp\n# else:\n# # 有的代理可能会更换端口\n# self.__items[ip].port = jp.port\n# # 代理的请求次数加起来\n# self.__items[ip].cnt += jp.cnt\n#\n#\n# def load_proxy_grave(obj_path: str) -> ProxyGrave:\n# \"\"\"\n# 若没有这个文件,那直接创建,返回一个空对象\n# \"\"\"\n# p = Path(obj_path)\n# if not p.exists():\n# p.parent.mkdir(parents=True, exist_ok=True)\n# p.touch()\n# return ProxyGrave()\n# try:\n# return pickle.load(open(p, 'rb'))\n# except:\n# return ProxyGrave()\n\nif __name__ == '__main__':\n # proxy = get_random_proxy()\n # print(proxy)\n # http://search.ccgp.gov.cn/bxsearch?searchtype=1&page_index=1&bidSort=&buyerName=&projectId=&pinMu=&bidType=&dbselect=bidx&kw=%E8%A7%84%E5%88%92&start_time=2022%3A06%3A12&end_time=2022%3A06%3A13&timeType=6&displayZone=&zoneId=&pppStatus=0&agentName=\n regular_check()\n # proxy = get_random_proxy()\n # print(proxy)\n","sub_path":"spider/gov_bx/code/proxyImpl.py","file_name":"proxyImpl.py","file_ext":"py","file_size_in_byte":6594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"386508067","text":"\"\"\"\n# Definition for a Node.\nclass Node(object):\n def __init__(self, val=None, children=None):\n self.val = val\n self.children = children\n\"\"\"\nfrom Queue import Queue\n\n\nclass Solution(object):\n def maxDepth(self, root):\n \"\"\"\n :type root: Node\n :rtype: int\n \"\"\"\n current_count = 1\n next_count = 0\n max_depth = 0\n\n if root is not None:\n q = Queue()\n q.put(root)\n while not q.empty():\n node = q.get()\n next_count += len(node.children)\n current_count -= 1\n for child in node.children:\n q.put(child)\n if current_count == 0:\n current_count = next_count\n next_count = 0\n max_depth += 1\n\n return max_depth\n","sub_path":"559.py","file_name":"559.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"173513186","text":"\"\"\"\"\nYou have volunteered to be the Coordinator for your town’s youth soccer league. As part of your job you need to divide the 18 children who have signed up for the league into three even teams - Dragons, Sharks and Raptors. In years past, the teams have been unevenly matched, so this year you are doing your best to fix that. For each child, you will have the following information: Name, height (in inches), whether or not they have played soccer before, and their guardians’ names. You'll take a list of these children, divide them into teams and output a text file listing the three teams and the players on them. There are three main tasks you'll need to complete to get this done:\n\n In your Python program, read the data from the supplied CSV file. Store that data in an appropriate data type so that it can be used in the next task.\n\n Create logic that can iterate through all 18 players and assign them to teams such that each team has the same number of players. The number of experienced players on each team should also be the same.\n\n Finally, the program should output a text file named -- teams.txt -- that contains the league roster listing the team name, and each player on the team including the player's information: name, whether they've played soccer before and their guardians' names.\n\"\"\"\n\n\n\n\n\nimport csv\n\n\n# Defining functions\ndef read_csv(filename):\n with open(filename, newline='') as csvfile:\n player_reader = csv.DictReader(csvfile, delimiter=',')\n player_league = list(player_reader)\n return player_league\n\n\nif __name__ == \"__main__\":\n # Reading the CSV file\n player_league = read_csv(\"soccer_players.csv\")\n\n # Separate experienced and non-experienced players\n experienced_players = []\n not_experienced_players = []\n for row in player_league:\n if row['Soccer Experience'] == 'YES':\n experienced_players.append(row)\n else:\n not_experienced_players.append(row)\n # setting up teams for experienced and not experienced players into teams\n not_experienced_team_1 = not_experienced_players[0:3]\n not_experienced_team_2 = not_experienced_players[3:6]\n not_experienced_team_3 = not_experienced_players[6:9]\n\n experienced_team_1 = experienced_players[0:3]\n experienced_team_2 = experienced_players[3:6]\n experienced_team_3 = experienced_players[6:9]\n sharks = not_experienced_team_1 + experienced_team_1\n dragons = not_experienced_team_2 + experienced_team_2\n raptors = not_experienced_team_3 + experienced_team_3\n\n # creating \"teams.txt\"\n with open(\"teams.txt\", \"w\") as file:\n file.write(\"Sharks\\n\")\n for player in sharks:\n file.write(\"{Name}, {Soccer Experience}, \"\"{Guardian Name(s)}\\n\".format(**player))\n file.write(\"\\nDragons\\n\")\n for player in dragons:\n file.write(\"{Name}, {Soccer Experience}, \"\"{Guardian Name(s)}\\n\".format(**player))\n file.write(\"\\nRaptors\\n\")\n for player in raptors:\n file.write(\"{Name}, {Soccer Experience}, \"\"{Guardian Name(s)}\\n\".format(**player))\n\n\n","sub_path":"soccer_league.py","file_name":"soccer_league.py","file_ext":"py","file_size_in_byte":3134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"578754762","text":"from functools import wraps\n\nfrom torba.rpc.jsonrpc import RPCError\nfrom torba.server.daemon import Daemon, DaemonError\n\n\ndef handles_errors(decorated_function):\n @wraps(decorated_function)\n async def wrapper(*args, **kwargs):\n try:\n return await decorated_function(*args, **kwargs)\n except DaemonError as daemon_error:\n raise RPCError(1, daemon_error.args[0])\n return wrapper\n\n\nclass LBCDaemon(Daemon):\n @handles_errors\n async def getrawtransaction(self, hex_hash, verbose=False):\n return await super().getrawtransaction(hex_hash=hex_hash, verbose=verbose)\n\n @handles_errors\n async def getclaimbyid(self, claim_id):\n '''Given a claim id, retrieves claim information.'''\n return await self._send_single('getclaimbyid', (claim_id,))\n\n @handles_errors\n async def getclaimsbyids(self, claim_ids):\n '''Given a list of claim ids, batches calls to retrieve claim information.'''\n return await self._send_vector('getclaimbyid', ((claim_id,) for claim_id in claim_ids))\n\n @handles_errors\n async def getclaimsforname(self, name):\n '''Given a name, retrieves all claims matching that name.'''\n return await self._send_single('getclaimsforname', (name,))\n\n @handles_errors\n async def getclaimsfortx(self, txid):\n '''Given a txid, returns the claims it make.'''\n return await self._send_single('getclaimsfortx', (txid,)) or []\n\n @handles_errors\n async def getnameproof(self, name, block_hash=None):\n '''Given a name and optional block_hash, returns a name proof and winner, if any.'''\n return await self._send_single('getnameproof', (name, block_hash,) if block_hash else (name,))\n\n @handles_errors\n async def getvalueforname(self, name):\n '''Given a name, returns the winning claim value.'''\n return await self._send_single('getvalueforname', (name,))\n\n @handles_errors\n async def claimname(self, name, hexvalue, amount):\n '''Claim a name, used for functional tests only.'''\n return await self._send_single('claimname', (name, hexvalue, float(amount)))\n","sub_path":"lbry/lbry/wallet/server/daemon.py","file_name":"daemon.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"62890055","text":"import requests, json, os, sys, getpass\nimport pprint\nfrom .cmdutil import cmdutil\nfrom .cog import cog\nfrom .llog import llog\nimport time\nimport logging\nimport socket\n\n\nErrcode='blank'\n\nInitEElog = True\n\nDebug = True\n#Debug = False\n\ndef dprint(obj):\n if (Debug):\n pp = pprint.PrettyPrinter(indent=4)\n pp.pprint(obj)\n\nclass EarthExplorer(object):\n\n def __init__(self, version='1.4.1'):\n global InitEElog\n self.baseurl = 'https://earthexplorer.usgs.gov/inventory/json/v/%s/' % version\n nameV = 'ee'\n self.logger = logging.getLogger(nameV)\n self.logger.setLevel(logging.DEBUG)\n if InitEElog:\n logfile = '/data/log/' + nameV + '.log'\n fh = logging.FileHandler(logfile)\n fh.setLevel(logging.DEBUG)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n fh.setFormatter(formatter)\n self.logger.addHandler(fh)\n InitEElog=False\n\n #self.logger.debug(\"Logging INIT Earth Explorer\")\n #self.logger.debug(\"Logging INIT Earth Explorer Twice\")\n\n\n\n def _api(self, endpoint='login', body=None):\n global Errcode\n #self.logger.debug(endpoint)\n body = {'jsonRequest': json.dumps(body)} if body else {}\n for retry in range(10):\n r = requests.post(self.baseurl+endpoint, data=body)\n r.raise_for_status()\n dat = r.json()\n if dat.get('error'):\n sys.stderr.write(': '.join([dat.get('errorCode'), dat.get('error')]))\n Errcode = ': '.join([dat.get('errorCode'), dat.get('error')])\n self.logger.error(Errcode)\n self.logger.error(\"Retry %s %s\", retry, endpoint)\n else:\n break\n return dat\n\n @classmethod\n def login(cls, username, password=None):\n if password is None:\n #password = getpass.getpass('Password (%s): ' % username)\n #password = geters('/data/home/.ers')\n password = geters('/opt/dogs/pkg/files/ers.json')\n payload = {'username': username, 'password': password}\n return cls()._api('login', payload).get('data')\n\n @classmethod\n def search(cls, **kwargs):\n return cls()._api('search', kwargs).get('data')\n\n @classmethod\n def download(cls, **kwargs):\n return cls()._api('download', kwargs).get('data')\n\n def grid2ll(self, path, row):\n\n ee_request = '{\"gridType\":\"WRS2\",\"responseShape\":\"point\",\"path\":\"%s\",\"row\":\"%s\"}' % (path,row)\n dprint (ee_request)\n\n body = 'jsonRequest=%s' % ee_request\n url = self.baseurl+'grid2ll?'+body\n dprint(url)\n r = requests.post(url)\n r.raise_for_status()\n dat = r.json()\n if dat.get('error'):\n sys.stderr.write(': '.join([dat.get('errorCode'), dat.get('error')]))\n return dat\n\n def set_bucket(self, bucket):\n self.bucket = bucket;\n\n\n\nclass DogFetch(object):\n \"\"\" DogFetch class for higher level earth explorer searches \n such as Path, Row, Dataset \"\"\"\n\n def __init__(self, dogName):\n\n self.timeLog = TimeLog()\n bd = Breed()\n self.cog_bucket=bd.get_cog_bucket()\n self.redis=bd.get_redis()\n self.data = '/data/tar/'\n cmd1='mkdir -p /data/tar'\n cmd2='mkdir -p /data/log'\n os.system(cmd1)\n os.system(cmd2)\n self.log = llog.Llog(dogName)\n\n def set_defaults(self, data_dir):\n pass\n\n def make_dir_name(self, product):\n dprint(product)\n a = product.split(\"_\")\n pathrow = a[2]\n path = pathrow[0:3]\n row = pathrow[3:7]\n flavor = a[0]\n dir = 'cog/' + path + '/' + row + '/' + flavor + '/'\n dprint(dir)\n return(dir)\n\n def hunt(self, path, row, product):\n\n self.log.logi (\"%s -- PATH %s ROW %s\" % (product, path,row))\n self.gamelist = []\n \n ee=EarthExplorer()\n\n jdata = ee.grid2ll(path, row)\n dprint(jdata)\n\n coord = jdata['data']['coordinates']\n dprint(coord)\n\n c0 = coord[0]\n ll_lat = c0['latitude']\n ll_long = c0['longitude']\n\n\t# just copy these for other corner - cheat\n\n ur_lat = ll_lat\n ur_long = ll_long\n\n spatial = { \"filterType\": \"mbr\",\n \"lowerLeft\": {\n \"latitude\": ll_lat,\n \"longitude\": ll_long\n },\n \"upperRight\": {\n \"latitude\": ur_lat,\n \"longitude\": ll_long\n }\n }\n \n #spatial = '''{ \"filterType\": \"mbr\", \"lowerLeft\": { \"latitude\": %s, \"longitude\": %s }, \"upperRight\": { \"latitude\": %s, \"longitude\": %s } }''' % (ll_lat, ll_long, ur_lat, ur_long)\n\n dprint(spatial)\n\n rcnt=1000\n api_key = EarthExplorer.login(username='tonybutzer')\n scenes = EarthExplorer.search(apiKey=api_key, datasetName=product, spatialFilter=spatial, maxResults=rcnt)\n\n for item in scenes['results']:\n tup = (item['entityId'], item['displayId'])\n self.gamelist.append(tup)\n\n return(self.gamelist)\n\n def get_products(self):\n prod_list = ['LANDSAT_8_C1','LANDSAT_ETM_C1','LANDSAT_TM_C1']\n return(prod_list)\n\n def logi(self, obj):\n self.log.logi(obj)\n\n def fetch(self, entityId, productId, dataset):\n \"\"\" fetch - gets a tar file from eart explorer to /data/tar dir \"\"\"\n\n global Errcode\n t1 = time.time()\n self.log.logi(\"fetch: %s %s %s\" % (entityId, productId, dataset))\n\n ee = EarthExplorer()\n time.sleep(1)\n api_key = ee.login(username='tonybutzer')\n\n junkjson = ee.download(apiKey=api_key, datasetName=dataset, products='STANDARD', entityIds=entityId)\n\n if junkjson == None:\n self.log.logi(Errcode)\n url = Errcode\n else:\n self.log.logd(junkjson[0]['url'])\n url = junkjson[0]['url']\n url = '\\\"' + url + '\\\"'\n\n #self.log.logi(url)\n\n myout = self.data + productId + '.tar.gz'\n cmd = 'wget -q ' + url + ' -O ' + myout\n self.log.logd(cmd)\n os.system(cmd)\n t2 = time.time()\n elapsed = t2 - t1\n timstr = \"fetch time = %.2f seconds\" % elapsed\n self.timeLog.logt(timstr)\n\n def chew(self, bucket, tarfile):\n \"\"\" chew - untars the file and syncs the fiels to a destination bucket \"\"\"\n\n t1 = time.time()\n justtar = tarfile.split('tar/')[1]\n productId = justtar.split('.tar.gz')[0]\n \n dir = self.make_dir_name(product=productId)\n self.log.logi(\"chew: %s %s %s\" % (bucket, dir, tarfile))\n self.log.logi(\"chew-1: %s %s %s\" % (bucket, dir, productId))\n \n\n bucket_location = 's3://' + bucket + '/' + tarfile\n self.log.logi(\"chew-2: %s %s %s\" % (bucket, dir, bucket_location))\n myin = self.data + productId + '.tar.gz'\n \n cmdutil.s3cp(bucket_location, myin)\n\n topdir = '/data/' + productId + '/'\n tmpdir = topdir + dir\n\n print(cmdutil.__file__)\n cmdutil.mkdir(tmpdir)\n os.chdir(tmpdir)\n cmdutil.untarFile(myin)\n t2 = time.time()\n elapsed = t2 - t1\n timstr = \"chew time = %.2f seconds\" % elapsed\n self.timeLog.logt(timstr)\n\n def drop(self, entityId, productId, dataset):\n \"\"\" drop - this takes the tar file and pushes it to s3 \"\"\"\n t1 = time.time()\n self.log.logi(\"drop: %s %s %s\" % (entityId, productId, dataset))\n dir = self.make_dir_name(product=productId)\n\n myout = self.data + productId + '.tar.gz'\n self.log.logd(\"tar: %s\" % (myout))\n bucket = self.cog_bucket\n tofile = 's3://' + bucket + '/tar/' + productId + '.tar.gz'\n self.log.logd(\"s3cp: %s %s\" % (myout, tofile))\n cmdutil.s3cp(myout, tofile)\n cmdutil.rm(myout)\n t2 = time.time()\n elapsed = t2 - t1\n timstr = \"drop time = %.2f seconds\" % elapsed\n self.timeLog.logt(timstr)\n\n def speak(self, fromTrainer):\n \"\"\" speak - simple echo reply\"\"\"\n self.log.logi(\"speak: %s\" % (fromTrainer))\n\n def cog(self, bucket, tarfile):\n justtar = tarfile.split('tar/')[1]\n productId = justtar.split('.tar.gz')[0]\n dir = self.make_dir_name(product=productId)\n self.log.logi(\"cog: %s %s %s\" % (bucket, dir, productId))\n t1 = time.time()\n\n\n topdir = '/data/' + productId + '/'\n tmpdir = topdir + dir\n os.chdir(tmpdir)\n\n listOfFiles = os.listdir('.')\n\n for item in listOfFiles:\n fullFile = tmpdir + item\n self.log.logd(\"cog this %s \" % fullFile)\n if fullFile.endswith('.TIF'):\n cog.build_cog(fullFile)\n\n t2 = time.time()\n elapsed = t2 - t1\n timstr = \"cog time = %.2f seconds\" % elapsed\n self.timeLog.logt(timstr)\n self.log.logi(\"s3sync: %s %s %s\" % (bucket, topdir, productId))\n t1 = time.time()\n cmdutil.s3sync(bucket, topdir)\n os.chdir('/data')\n self.log.logi(\"rmdir: %s\" % (topdir))\n cmdutil.rmdir(topdir)\n t2 = time.time()\n elapsed = t2 - t1\n timstr = \"s3sync time = %.2f seconds\" % elapsed\n self.timeLog.logt(timstr)\n\n\nclass Breed(object):\n \"\"\" Breed holds the config file for the applications\n such as redis and syslog and the cogbucket \"\"\"\n\n def __init__(self):\n wildBreed = '/opt/etc/wildBreed.json'\n if os.path.exists(wildBreed):\n #read json file\n file = wildBreed\n self.breed_file = wildBreed\n with open(file) as data_file:\n data = json.load(data_file)\n ip = data['redis']\n cog = data['cog_bucket']\n sysip = data['syslog']\n else:\n cog=\"dev-usgs-odc-cog-west\"\n self.master = 'redis1'\n self.breed_file = '/opt/dogs/etc/dogBreed.json'\n ip = socket.gethostbyname('redis1')\n if (not \"10.0\" in ip):\n self.master = 'MasterT1'\n masterIp = returnIp(self.master)\n ip = masterIp\n sysip = socket.gethostbyname('syslog1')\n if (not \"10.0\" in ip):\n self.master = 'MasterT1'\n masterIp = returnIp(self.master)\n sysip = masterIp\n\n self.master = ip\n self.redis = ip\n self.syslog = sysip\n self.cog_bucket = cog;\n\n\n def get_redis(self):\n return(self.redis)\n\n def get_cog_bucket(self):\n return(self.cog_bucket)\n\nInitTimeLog = True\n\nclass TimeLog(object):\n \"\"\" opens a timer log \"\"\"\n\n def __init__(self):\n global InitTimeLog\n myName = socket.gethostname()\n nameV = myName + '-T'\n self.logger = logging.getLogger(nameV)\n if (InitTimeLog):\n logserver = llog.get_syslog()\n self.logger.setLevel(logging.DEBUG)\n\n syslogh = logging.handlers.SysLogHandler(address = (logserver,514), facility='local2')\n syslogh.setLevel(logging.INFO)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n syslogh.setFormatter(formatter)\n self.logger.addHandler(syslogh)\n self.logger.info(\"TheTimer Begins\")\n InitTimeLog = False\n\n def logt(self, obj):\n self.logger.info(obj)\n\n\n\ndef geters(file):\n\n with open(file) as data_file: \n data = json.load(data_file)\n return(data['greeting'])\n\n\n\nimport subprocess\n\ndef ec2status():\n #print (\"hello from util\")\n command = 'aws ec2 describe-instances --region=us-west-2'\n try:\n process = subprocess.check_output(command, shell=True)\n except subprocess.CalledProcessError:\n print (\"You are not running in the cloud - bummer!\")\n print (\"You are not running in the cloud - bummer!\")\n exit(0)\n #proc_stdout = process.communicate()[0].strip()\n #stupidBytesObject = proc_stdout\n stupidBytesObject = process\n outStr = (stupidBytesObject.decode(\"utf-8\"))\n #print(outStr)\n return(outStr)\n\ndef ec2start(id):\n print (\"start id %s \" % id)\n command = \"aws ec2 start-instances --instance-ids %s --region=us-west-2\" % id\n process = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True)\n proc_stdout = process.communicate()[0].strip()\n stupidBytesObject = proc_stdout\n outStr = (stupidBytesObject.decode(\"utf-8\"))\n print(outStr)\n return(outStr)\n\ndef ec2stop(id):\n print (\"stop id %s \" % id)\n command = \"aws ec2 stop-instances --instance-ids %s --region=us-west-2\" % id\n process = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True)\n proc_stdout = process.communicate()[0].strip()\n stupidBytesObject = proc_stdout\n outStr = (stupidBytesObject.decode(\"utf-8\"))\n print(outStr)\n return(outStr)\n\n\n\ndef returnIp(tag):\n jsonData = ec2status()\n jsonBlob = json.loads(jsonData)\n mynew = jsonBlob.get(\"Reservations\")\n myip = \"PrivateIpAddress\"\n\n for myDict in mynew:\n ids = myDict[\"Instances\"]\n for id in ids:\n iState = id[\"State\"]\n tagName = get_tag_name(id)\n\n if (tagName == tag):\n realState = iState[\"Name\"]\n if (realState == \"running\"):\n print (id[myip])\n masterIp = id[myip]\n else:\n print (\"ERROR the instance MUST be running to get its IP Address\")\n print(\"MasterT1 IP is %s\" % masterIp)\n return(masterIp)\n\n\n\n\ndef get_tag_name(theId):\n\n tagName='BOGUS1'\n if 'Tags' in theId:\n tags = theId[\"Tags\"]\n for tg in tags:\n if tg[\"Key\"] == \"Name\":\n tagName = tg[\"Value\"]\n else:\n tagName='BOGUS'\n\n return(tagName)\n\n","sub_path":"dogs/dogMaster/llib/earthexplorer.py","file_name":"earthexplorer.py","file_ext":"py","file_size_in_byte":13908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"250291171","text":"from math import *\nimport matplotlib.pyplot as plt\nfrom helper_functions import *\n\n\n\nclass Point:\n def __init__(self, x , y):\n self.x = x\n self.y = y\n\nclass Vector:\n def __init__(self, x , y):\n self.values = (x,y)\n\n def magnitude(self):\n #magnitude of the vector\n (x,y)= self.values\n return math.sqrt(x*x + y*y)\n\n def rotate(self, theta):\n #rotate the vector theta degrees\n theta = math.radians(theta)\n dc, ds = math.cos(theta), math.sin(theta)\n (x, y) = self.values\n (x, y) = dc*x - ds*y, ds*x + dc*y\n return Vector(x, y)\n\npoint = Point(0,0)\npoint1 = Point(0,0)\n\n\n\nclass truck:\n\n def calculateCorners(self, pointFront, th1, th2):\n\n point = self.back_middle_trailer(pointFront, th1, th2)\n\n # hitch joint\n x2 = point.x + (TRAILER_LENGTH + TL_BACK) *cos(th2);\n y2 = point.y + (TRAILER_LENGTH + TL_BACK) *sin(th2);\n\n #print x2, y2\n\n\n #left back\n x4 = point.x - cos(pi/2-th2)*TRAILER_WIDTH/2;\n y4 = point.y + sin(pi/2-th2)*TRAILER_WIDTH/2;\n\n #right back\n x5 = point.x + cos(pi/2-th2)*TRAILER_WIDTH/2;\n y5 = point.y - sin(pi/2-th2)*TRAILER_WIDTH/2;\n\n\n #left back axis\n x12 = x4 + TL_BACK * cos(th2)\n y12 = y4 + TL_BACK * sin(th2)\n\n #right back axis\n x13 = x5 + TL_BACK * cos(th2)\n y13 = y5 + TL_BACK * sin(th2)\n\n\n\n #left joint wheel\n x6 = x2 - cos(pi/2-th1)*HEADER_WIDTH/2;\n y6 = y2 + sin(pi/2-th1)*HEADER_WIDTH/2;\n\n #right joint wheel\n x7 = x2 + cos(pi/2-th1)*HEADER_WIDTH/2;\n y7 = y2 - sin(pi/2-th1)*HEADER_WIDTH/2;\n\n #left front axis\n x8 = x6 + HEADER_FRONTAXIS_TO_JOINT*cos(th1);\n y8 = y6 + HEADER_FRONTAXIS_TO_JOINT*sin(th1);\n\n #right front axis\n x9 = x7 + HEADER_FRONTAXIS_TO_JOINT*cos(th1);\n y9 = y7 + HEADER_FRONTAXIS_TO_JOINT*sin(th1);\n\n\n #left front\n\n x10 = x6 + (HEADER_FRONTAXIS_TO_JOINT + HL_FRONT)*cos(th1);\n y10 = y6 + (HEADER_FRONTAXIS_TO_JOINT + HL_FRONT)*sin(th1);\n\n #right front\n\n x11 = x7 + (HEADER_FRONTAXIS_TO_JOINT + HL_FRONT)*cos(th1);\n y11 = y7 + (HEADER_FRONTAXIS_TO_JOINT + HL_FRONT)*sin(th1);\n\n\n\n return((x8,y8), (x9,y9), (x6,y6), (x7,y7), (x12, y12), (x13, y13), (x10, y10), (x11, y11), (x4, y4), (x5, y5))\n\n def rightbackWheel(self):\n\n point = self.back_middle_trailer()\n\n x5 = point.x + cos(pi/2-th2)*TRAILER_WIDTH/2;\n y5 = point.y - sin(pi/2-th2)*TRAILER_WIDTH/2;\n\n def back_middle_trailer(self, pointFront, th1, th2):\n jpx = pointFront.x - cos(th1) * HEADER_FRONTAXIS_TO_JOINT\n jpy = pointFront.y - sin(th1) * HEADER_FRONTAXIS_TO_JOINT\n\n px = jpx - cos(th2) * (TRAILER_LENGTH + TL_BACK)\n py = jpy - sin(th2) * (TRAILER_LENGTH + TL_BACK)\n return Point(px,py)\n\n\n#if __name__ == '__main__':\n# truck = truck()\n# lista1 =truck.calculateCorners(Point(0,0),1.57, 1.57)\n#\n# plt.plot([point.x],[point.y], 'bo')\n# plt.plot([point1.x],[point1.y], 'go')\n#\n# lista2 =truck.calculateCorners(Point(0,0),1.57, 0.785398)\n#\n# print lista1\n#\n# lx= []\n# ly=[]\n\n# for (x,y) in lista1:\n# lx.append(x)\n# ly.append(y)\n\n# plt.plot(lx, ly, 'go')\n\n\n# lx2= []\n# ly2=[]\n\n# for (x,y) in lista2:\n# lx2.append(x)\n# ly2.append(y)\n\n# plt.plot(lx, ly, 'go')\n# plt.plot(lx2, ly2, 'ro')\n# plt.plot([0],[0], 'bo')\n# plt.plot([point.x],[point.y], 'bo')\n# plt.plot([point1.x],[point1.y], 'go')\n#\n# plt.axis([-100, 150, 150, -100])\n# plt.show()\n\n\n\n\n\n\n\n\n\n#\n","sub_path":"src/path_planning/scripts/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"206517080","text":"# Authors: Samwel Maisiba, Modester Mwangi, Josephine Uwizeye\n# GitHub Handles: Sammyiel, Modester-mw, Josephine-Uwizeye\n\n# We are going to implement the maze game using undirected and unweighted graph\n\nlist1 = []\n\n\ndef traverse_vertices():\n for i in list1:\n print(i, end=' ')\n\n\ndef set_vertices(vertex):\n if vertex not in list1:\n list1.append(vertex)\n\n\nclass Graph:\n\n def __init__(self, current_vertex, pointed_vertex):\n self.current_vertex = current_vertex\n self.pointed_vertex = pointed_vertex\n\n set_vertices(\"A\")\n set_vertices(\"B\")\n set_vertices(\"C\")\n set_vertices(\"D\")\n set_vertices(\"E\")\n set_vertices(\"F\")\n\n\ntraverse_vertices()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"154489179","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri May 7 11:03:36 2021\r\n\r\n@author: kagir\r\n\"\"\"\r\nimport numpy as np\r\nimport cv2\r\nimport glob\r\n\r\n# termination criteria\r\ncriteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)\r\n#checkboard size\r\na = 6\r\nb = 6\r\n# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)\r\nobjp = np.zeros((a*b,3), np.float32)\r\nobjp[:, :2] = np.mgrid[0:a, 0:b].T.reshape(-1,2)\r\n\r\n# Arrays to store object points and image points from all the images.\r\nobjpoints = [] # 3d point in real world space\r\nimgpoints = [] # 2d points in image plane.\r\n\r\nimages = glob.glob(\"*.jpg\")\r\n\r\n\r\n\r\nfor fname in images:\r\n img = cv2.imread(fname)\r\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n inverted = np.array(256 - gray, dtype = 'uint8')\r\n ret, corners = cv2.findChessboardCorners(gray, (a, b), None)\r\n # If found, add object points, image points (after refining them)\r\n if ret:\r\n objpoints.append(objp)\r\n corners2 = cv2.cornerSubPix(gray, corners, winSize=(a,b), zeroZone=(-1,-1), criteria = criteria)\r\n imgpoints.append(corners2)\r\n\r\n # Draw and display the corners\r\n gray = cv2.drawChessboardCorners(img, (a, b), corners2, ret)\r\n cv2.imshow('img', img)\r\n cv2.waitKey(500)\r\n\r\ncv2.destroyAllWindows()\r\nret, K, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, img.shape[1::-1],None,None)\r\n\r\n#img = cv2.imread('left12.jpg')\r\n#h, w = img.shape[:2]\r\n#newcameramtx, roi=cv2.getOptimalNewCameraMatrix(mtx,dist,(w,h),1,(w,h))\r\n## undistort\r\n#dst = cv2.undistort(img, mtx, dist, None, newcameramtx)\r\n#\r\n## crop the image\r\n#x,y,w,h = roi\r\n#dst = dst[y:y+h, x:x+w]\r\n#cv2.imwrite('calibresult.jpg',dst)\r\n\r\n## undistort\r\n#mapx,mapy = cv2.initUndistortRectifyMap(mtx,dist,None,newcameramtx,(w,h),5)\r\n#dst = cv2.remap(img,mapx,mapy,cv2.INTER_LINEAR)\r\n#\r\n## crop the image\r\n#x,y,w,h = roi\r\n#dst = dst[y:y+h, x:x+w]\r\n#cv2.imwrite('calibresult.png',dst)\r\n#\r\n#mean_error = 0\r\n#for i in xrange(len(objpoints)):\r\n# imgpoints2, _ = cv2.projectPoints(objpoints[i], rvecs[i], tvecs[i], mtx, dist)\r\n# error = cv2.norm(imgpoints[i],imgpoints2, cv2.NORM_L2)/len(imgpoints2)\r\n# tot_error += error\r\n#\r\n#print(\"total error: \", mean_error/len(objpoints))","sub_path":"camera_calibration/camera_calibration.py","file_name":"camera_calibration.py","file_ext":"py","file_size_in_byte":2250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"361880719","text":"import uiScriptLocale\n\nITEMBOXWIDTH = 161+2\nITEMBOXHEIGHT = 102+14+2\n\nMAINFOLDER = \"locale/common/ui/mall/\"\nMAINFOLDER = \"locale/common/ui/mall/design_by_lordziege/\"\n\nwindow = {\n\t\"name\" : \"item_box\",\n\n\t\"x\" : SCREEN_WIDTH/2-ITEMBOXWIDTH/2,\n\t\"y\" : SCREEN_HEIGHT /2-ITEMBOXHEIGHT/2,\n\n\t\"style\" : (\"float\",),\n\n\t\"width\" : ITEMBOXWIDTH,\n\t\"height\" : ITEMBOXHEIGHT,\n\n\t\"children\" :\n\t(\n\t\t{\n\t\t\t\"name\" : \"red_sale\",\n\t\t\t\"type\" : \"image\",\n\t\t\t\"style\" : (\"attach\",),\n\n\t\t\t\"x\" : 0,\n\t\t\t\"y\" : 0,\n\n\t\t\t\"image\" : MAINFOLDER + \"sale_button.tga\",\n\t\t},\n\t\t{\n\t\t\t\"name\" : \"time_box\",\n\t\t\t\"x\" : 81+1,\n\t\t\t\"y\" : 102+1,\n\n\t\t\t\"width\":65,\n\t\t\t\"height\":14,\n\n\t\t\t\"children\" :\n\t\t\t(\n\t\t\t\t## Countdown\n\t\t\t\t{\n\t\t\t\t\t\"name\" : \"tx_countdown\",\n\t\t\t\t\t\"type\" : \"text\",\n\t\t\t\t\t\"text\" : \"Xh Xm Xs\",\n\t\t\t\t\t\"text_horizontal_align\" : \"right\",\n\t\t\t\t\t\"horizontal_align\" : \"right\",\n\t\t\t\t\t\"x\" : 3,\n\t\t\t\t\t\"y\" : 0,\n\t\t\t\t},\n\t\t\t),\n\t\t},\n\t\t{\n\t\t\t\"name\" : \"percent_box\",\n\n\t\t\t\"x\" : 17+1,\n\t\t\t\"y\" : 102+1,\n\t\t\t\"width\":64,\n\t\t\t\"height\":14,\n\n\t\t\t\"children\" : \n\t\t\t(\n\t\t\t\t{\n\t\t\t\t\t\"name\" : \"tx_percent\",\n\t\t\t\t\t\"type\" : \"text\",\n\t\t\t\t\t\"text\" : \"10%\",\n\t\t\t\t\t\"text_horizontal_align\" : \"left\",\n\t\t\t\t\t\"horizontal_align\" : \"left\",\n\t\t\t\t\t\"x\" : 3,\n\t\t\t\t\t\"y\" : 0,\n\t\t\t\t},\n\t\t\t),\n\t\t},\n\t\t{\n\t\t\t\"name\" : \"background\",\n\t\t\t\"type\" : \"image\",\n\t\t\t\"style\" : (\"attach\",),\n\n\t\t\t\"x\" : 0+1,\n\t\t\t\"y\" : 0+1,\n\n\t\t\t\"image\" : MAINFOLDER + \"item_box.tga\",\n\n\t\t\t\"children\" :\n\t\t\t(\n\t\t\t\t## Itemname\n\t\t\t\t{\n\t\t\t\t\t\"name\" : \"tx_item_name\",\n\t\t\t\t\t\"type\" : \"text\",\n\t\t\t\t\t\"text\" : \"XXX\",\n\t\t\t\t\t\"x\" : 6,\n\t\t\t\t\t\"y\" : 3,\n\t\t\t\t},\n\t\t\t\t## Item icon\n\t\t\t\t{\n\t\t\t\t\t\"name\" : \"item_icon\",\n\t\t\t\t\t\"type\" : \"image\",\n\t\t\t\t\t\"image\" : MAINFOLDER + \"empty_icon.tga\",\n\t\t\t\t\t\"x\" : 3,\n\t\t\t\t\t\"y\" : 3,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t\"name\" : \"item_price_box\",\n\n\t\t\t\t\t\"x\" : 68,\n\t\t\t\t\t\"y\" : 3,\n\t\t\t\t\t\"width\":90,\n\t\t\t\t\t\"height\":18,\n\n\t\t\t\t\t\"children\" : \n\t\t\t\t\t(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"name\" : \"tx_item_price\",\n\t\t\t\t\t\t\t\"type\" : \"text\",\n\t\t\t\t\t\t\t\"text\" : \"XXX\",\n\t\t\t\t\t\t\t\"x\" : 3,\n\t\t\t\t\t\t\t\"y\" : 3,\n\t\t\t\t\t\t\t\"text_horizontal_align\" : \"left\",\n\t\t\t\t\t\t\t\"horizontal_align\" : \"left\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"name\" : \"tx_item_currency\",\n\t\t\t\t\t\t\t\"type\" : \"text\",\n\t\t\t\t\t\t\t\"text\" : \"COINS\",\n\t\t\t\t\t\t\t\"x\" : 3,\n\t\t\t\t\t\t\t\"y\" : 3,\n\t\t\t\t\t\t\t\"text_horizontal_align\" : \"right\",\n\t\t\t\t\t\t\t\"horizontal_align\" : \"right\",\n\t\t\t\t\t\t},\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t\t\n\t\t\t\t## preview button\n\t\t\t\t{\n\t\t\t\t\t\"name\" : \"btn_preview\", \n\t\t\t\t\t\"type\" : \"button\",\n\t\t\t\t\t\"x\" : 37,\n\t\t\t\t\t\"y\" : 51,\n\t\t\t\t\t\"text\" : \"Preview\",\n\t\t\t\t\t\"text_color\" : 0xffF8BF24,\n\t\t\t\t\t\"default_image\" : MAINFOLDER+\"buy_preview_button_normal.tga\",\n\t\t\t\t\t\"over_image\" : MAINFOLDER+\"buy_preview_button_hover.tga\",\n\t\t\t\t\t\"down_image\" : MAINFOLDER+\"buy_preview_button_down.tga\",\n\t\t\t\t},\n\t\t\t\t## buy button\n\t\t\t\t{\n\t\t\t\t\t\"name\" : \"btn_buy\", \n\t\t\t\t\t\"type\" : \"button\",\n\t\t\t\t\t\"x\" : 37,\n\t\t\t\t\t\"y\" : 76,\n\t\t\t\t\t\"text\" : \"Buy\",\n\t\t\t\t\t\"default_image\" : MAINFOLDER+\"buy_preview_button_normal.tga\",\n\t\t\t\t\t\"over_image\" : MAINFOLDER+\"buy_preview_button_hover.tga\",\n\t\t\t\t\t\"down_image\" : MAINFOLDER+\"buy_preview_button_down.tga\",\n\t\t\t\t},\n\t\t\t\t## amount\n\t\t\t\t{\n\t\t\t\t\t\"name\" : \"amount_box\",\n\t\t\t\t\t\"type\" : \"image\",\n\t\t\t\t\t\"image\": MAINFOLDER + \"item_box_amount.tga\",\n\t\t\t\t\t\"x\" : 37,\n\t\t\t\t\t\"y\" : 23,\n\t\t\t\t\t\"width\" : 90,\t\n\t\t\t\t\t\"height\" : 18,\n\n\t\t\t\t\t\"children\" :\n\t\t\t\t\t(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"name\" : \"ed_amount\",\n\t\t\t\t\t\t\t\"type\" : \"editline\",\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\"width\" : 90,\n\t\t\t\t\t\t\t\"height\" : 18,\n\t\t\t\t\t\t\t\"input_limit\" : 3,\n\t\t\t\t\t\t\t\"enable_codepage\" : 0,\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\"x\" : 32+2,\n\t\t\t\t\t\t\t\"y\" : 3,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"name\" : \"tx_item_amount_text\",\n\t\t\t\t\t\t\t\"type\" : \"text\",\n\t\t\t\t\t\t\t\"text\" : \"pc(s).\",\n\t\t\t\t\t\t\t\"x\" : 32+65,\n\t\t\t\t\t\t\t\"y\" : 3,\n\t\t\t\t\t\t},\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t\t\n\t\t\t),\n\t\t},\n\t),\n}","sub_path":"root/uiscript/mall_design_by_lordziege/partials/itembox.py","file_name":"itembox.py","file_ext":"py","file_size_in_byte":3513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"485694920","text":"import numpy as np\nfrom metagraph import concrete_algorithm, NodeID\nfrom metagraph.plugins import has_scipy\nfrom .types import ScipyEdgeSet, ScipyEdgeMap, ScipyGraph\nfrom .. import has_numba\nimport numpy as np\nfrom typing import Tuple, Callable, Any, Union\n\nif has_numba:\n import numba\n\nif has_scipy:\n import scipy.sparse as ss\n from ..numpy.types import NumpyNodeMap, NumpyNodeSet, NumpyVector\n\n @concrete_algorithm(\"clustering.connected_components\")\n def ss_connected_components(graph: ScipyGraph) -> NumpyNodeMap:\n _, node_labels = ss.csgraph.connected_components(\n graph.edges.value, False, return_labels=True\n )\n return NumpyNodeMap(node_labels, node_ids=graph.edges.node_list)\n\n @concrete_algorithm(\"clustering.strongly_connected_components\")\n def ss_strongly_connected_components(graph: ScipyGraph) -> NumpyNodeMap:\n _, node_labels = ss.csgraph.connected_components(\n graph.edges.value, True, connection=\"strong\", return_labels=True\n )\n return NumpyNodeMap(node_labels, node_ids=graph.edges.node_list)\n\n @concrete_algorithm(\"traversal.all_pairs_shortest_paths\")\n def ss_all_pairs_shortest_paths(\n graph: ScipyGraph,\n ) -> Tuple[ScipyGraph, ScipyGraph]:\n is_directed = ScipyGraph.Type.compute_abstract_properties(\n graph, {\"is_directed\"}\n )[\"is_directed\"]\n lengths, parents = ss.csgraph.dijkstra(\n graph.edges.value, directed=is_directed, return_predecessors=True\n )\n lengths = ss.csr_matrix(lengths)\n parents = ss.csr_matrix(parents)\n parents = parents + 9999 * ss.eye(parents.get_shape()[0])\n parents = parents.astype(graph.edges.value.dtype)\n return (\n ScipyGraph(ScipyEdgeMap(parents, graph.edges.node_list), nodes=graph.nodes),\n ScipyGraph(ScipyEdgeMap(lengths, graph.edges.node_list), nodes=graph.nodes),\n )\n\n @concrete_algorithm(\"cluster.triangle_count\")\n def ss_triangle_count(graph: ScipyGraph) -> int:\n \"\"\"\n Uses the triangle counting method described in\n https://www.sandia.gov/~srajama/publications/Tricount-HPEC.pdf\n \"\"\"\n props = ScipyGraph.Type.compute_abstract_properties(graph, {\"edge_type\"})\n if props[\"edge_type\"] == \"map\":\n # Drop weights before performing triangle count\n m = graph.edges.value.copy()\n m.data = np.ones_like(m.data)\n elif props[\"edge_type\"] == \"set\":\n m = graph.edges.value\n L = ss.tril(m, k=-1).tocsr()\n U = ss.triu(m, k=1).tocsc()\n return int((L @ U.T).multiply(L).sum())\n\n @concrete_algorithm(\"traversal.bfs_iter\")\n def ss_breadth_first_search_iter(\n graph: ScipyGraph, source_node: NodeID, depth_limit: int\n ) -> NumpyVector:\n is_directed = ScipyGraph.Type.compute_abstract_properties(\n graph, {\"is_directed\"}\n )[\"is_directed\"]\n bfs_ordered_incides = ss.csgraph.breadth_first_order(\n graph.edges.value,\n source_node,\n directed=is_directed,\n return_predecessors=False,\n )\n bfs_ordered_nodes = graph.edges.node_list[bfs_ordered_incides]\n return NumpyVector(bfs_ordered_nodes)\n\n def _reduce_sparse_matrix(\n func: np.ufunc, sparse_matrix: ss.spmatrix\n ) -> Tuple[np.ndarray, np.ndarray]:\n keep_mask = np.diff(sparse_matrix.indptr).astype(bool)\n reduceat_indices = sparse_matrix.indptr[:-1][keep_mask]\n reduced_values = func.reduceat(\n sparse_matrix.data, reduceat_indices, dtype=object\n )\n return reduced_values, keep_mask\n\n @concrete_algorithm(\"util.graph.aggregate_edges\")\n def ss_graph_aggregate_edges(\n graph: ScipyGraph,\n func: Callable[[Any, Any], Any],\n initial_value: Any,\n in_edges: bool,\n out_edges: bool,\n ) -> NumpyNodeMap:\n if in_edges or out_edges:\n is_directed = ScipyGraph.Type.compute_abstract_properties(\n graph, {\"is_directed\"}\n )[\"is_directed\"]\n if not is_directed:\n in_edges = True\n out_edges = False\n nrows = graph.edges.value.shape[0]\n num_agg_values = nrows if graph.nodes is None else len(graph.nodes)\n final_position_to_agg_value = np.full(num_agg_values, initial_value)\n if not isinstance(func, np.ufunc):\n func = np.frompyfunc(func, 2, 1)\n matrix_position_to_agg_value = np.full(nrows, initial_value)\n if in_edges:\n csc_matrix = graph.edges.value.tocsc()\n in_edges_aggregated_values, keep_mask = _reduce_sparse_matrix(\n func, csc_matrix\n )\n matrix_position_to_agg_value[keep_mask] = func(\n matrix_position_to_agg_value[keep_mask], in_edges_aggregated_values\n )\n if out_edges:\n csr_matrix = graph.edges.value\n out_edges_aggregated_values, keep_mask = _reduce_sparse_matrix(\n func, csr_matrix\n )\n matrix_position_to_agg_value[keep_mask] = func(\n matrix_position_to_agg_value[keep_mask], out_edges_aggregated_values\n )\n # TODO This doesn't assume sortedness of any node list ; make these other data structures not require sorted node lists as that is expensive for large graphs\n graph_node_ids = (\n graph.edges.node_list if graph.nodes is None else graph.nodes.nodes()\n )\n matrix_position_to_node_id = graph.edges.node_list\n graph_node_ids_position_to_final_position = np.argsort(graph_node_ids)\n final_position_to_graph_node_id = graph_node_ids[\n graph_node_ids_position_to_final_position\n ]\n matrix_position_to_final_position = np.searchsorted(\n final_position_to_graph_node_id, matrix_position_to_node_id\n )\n final_position_to_agg_value[\n matrix_position_to_final_position\n ] = matrix_position_to_agg_value\n # Would we ever want to return a NumpyNodeMap via a mask?\n return NumpyNodeMap(\n final_position_to_agg_value, node_ids=final_position_to_graph_node_id\n )\n\n @concrete_algorithm(\"util.graph.filter_edges\")\n def ss_graph_filter_edges(\n graph: ScipyGraph, func: Callable[[Any], bool]\n ) -> ScipyGraph:\n # TODO consider caching this somewhere or enforcing that only vectorized functions are given\n func_vectorized = numba.vectorize(func) if has_numba else np.vectorize(func)\n # TODO Explicitly handle the CSR case\n result_matrix = (\n graph.edges.value.copy()\n if isinstance(graph.edges.value, ss.coo_matrix)\n else graph.edges.value.tocoo(copy=True)\n )\n result_edge_map = ScipyEdgeMap(\n result_matrix, graph.edges.node_list, graph.edges.transposed\n )\n to_keep_mask = func_vectorized(result_edge_map.value.data)\n if not to_keep_mask.all():\n result_edge_map.value.row = result_edge_map.value.row[to_keep_mask]\n result_edge_map.value.col = result_edge_map.value.col[to_keep_mask]\n result_edge_map.value.data = result_edge_map.value.data[to_keep_mask]\n result_graph_nodes = None if graph.nodes is None else graph.nodes.copy()\n return ScipyGraph(result_edge_map, result_graph_nodes)\n\n @concrete_algorithm(\"util.graph.assign_uniform_weight\")\n def ss_graph_assign_uniform_weight(graph: ScipyGraph, weight: Any) -> ScipyGraph:\n matrix = graph.edges.value.copy()\n matrix.data.fill(weight)\n edge_map = ScipyEdgeMap(\n matrix, node_list=graph.edges.node_list, transposed=graph.edges.transposed\n )\n nodes = None if graph.nodes is None else graph.nodes.copy()\n return ScipyGraph(edge_map, nodes=nodes)\n\n @concrete_algorithm(\"util.graph.build\")\n def ss_graph_build(\n edges: Union[ScipyEdgeSet, ScipyEdgeMap],\n nodes: Union[NumpyNodeSet, NumpyNodeMap, None],\n ) -> ScipyGraph:\n return ScipyGraph(edges, nodes)\n\n @concrete_algorithm(\"util.edge_map.from_edgeset\")\n def ss_edge_map_from_edgeset(\n edgeset: ScipyEdgeSet, default_value: Any,\n ) -> ScipyEdgeMap:\n new_matrix = edgeset.value.copy()\n new_matrix.data.fill(default_value)\n return ScipyEdgeMap(new_matrix, edgeset.node_list.copy(), edgeset.transposed)\n","sub_path":"metagraph/plugins/scipy/algorithms.py","file_name":"algorithms.py","file_ext":"py","file_size_in_byte":8478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"525582325","text":"import os\n\n# calling script\n\ndef windows():\n os.system('python BSCTokenSniper.py')\n\ndef windows_wss():\n os.system('python BSCTokenSniper_wss.py')\n \ndef linux():\n os.system('python BSCTokenSniper_Linux.py')\n \n\ndef linux_wss():\n os.system('python BSCTokenSniper_Linux_wss.py')\n\n \ndef installdep():\n os.system('python -m pip install -r requirements.txt')\n os.system('python -m pip install -U web3')\n os.system('python run.py')\n\n\n## message box\n\ndef print_msg_box(msg, indent=1, width=None, title=None):\n \"\"\"Print message-box with optional title.\"\"\"\n lines = msg.split('\\n')\n space = \" \" * indent\n if not width:\n width = max(map(len, lines))\n box = f'╔{\"═\" * (width + indent * 2)}╗\\n' # upper_border\n if title:\n box += f'║{space}{title:<{width}}{space}║\\n' # title\n box += f'║{space}{\"-\" * len(title):<{width}}{space}║\\n' # underscore\n box += ''.join([f'║{space}{line:<{width}}{space}║\\n' for line in lines])\n box += f'╚{\"═\" * (width + indent * 2)}╝' # lower_border\n print(box)\n\n\n# ---------------------\n\nmsg = \"# Http Version # \\n\" \\\n\"1. Windows \\n\" \\\n\"2. Linux \\n\" \\\n\"# Websocket (Recomended) #\\n\" \\\n\"3. Linux Websocket \\n\" \\\n\"4. Windows Websocket \\n\" \\\n\"#------------------------# \\n\" \\\n\"5. Install Dependency\"\n\nprint_msg_box(msg=msg, indent=2, title='BSC TOKEN SNIPER')\n\n\nchoose = input(\"Please the menu : \")\n\n\n#if int(choose) == 1:\n# print(\"Runing on windows\")\n# windows()\n#else:\n# print(\"runing on linux\")\n# linux()\n\nif int(choose) == 1:\n print(\"Runing on windows\")\n windows()\nelif int(choose) == 2:\n print(\"Runing on Linux\")\n linux()\nelif int(choose) == 3:\n print(\"Runing on Linux websocket version\")\n linux_wss()\nelif int(choose) == 4:\n print(\"Runing on Windows websocket version\")\n windows_wss()\nelif int(choose) == 5:\n print(\"Installing Dependency\")\n installdep()\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"112941304","text":"import configparser\nimport copy\nimport math\n\nfrom collections import Counter\n\nimport os\nfrom hyperconverged.models import *\nfrom base_sizer.solver.attrib import BaseConstants\nfrom .attrib import HyperConstants\nfrom .node_sizing import *\nfrom .wl import *\n\n\nclass UtilizationGenerator(object):\n\n def __init__(self, sizer_instance):\n def define_configs():\n \"\"\"\n Thresholds defined as a python config file in sizer/sizing_config.cfg. Currently assumes numbers,\n no strings.\n \"\"\"\n config = configparser.ConfigParser()\n if 'OPENSHIFT_REPO_DIR' in os.environ:\n from local_settings import BASE_DIR\n else:\n from sizer.local_settings import BASE_DIR\n\n config.read(os.path.join(BASE_DIR, 'sizer/sizing_config.cfg'))\n '''Define version variables for use within the sizer'''\n config_section = 'Versions'\n\n self.sizer_version = config.get(config_section, 'Sizer_Version')\n self.hx_version = config.get(config_section, 'HX_Version')\n\n self.replication = False\n self.sizer_instance = sizer_instance\n self.result_name = sizer_instance.result_name\n self.parts_table = sizer_instance.parts_table\n self.hypervisor = sizer_instance.hypervisor\n define_configs()\n\n def set_RF_String(self):\n\n if self.highest_rf == 2:\n return \"RF2\"\n elif self.highest_rf == 3:\n return \"RF3\"\n else:\n return \"RF3\"\n\n def build_multi_cluster_json(self, cluster_data):\n\n res_json = list()\n\n overall_summary = dict()\n summary_info = dict()\n\n overall_summary['clusters'] = list()\n # Only for fixed_cluster without workload. else this list will be empty\n overall_summary['no_wl_clusters'] = list()\n\n summary_info[BaseConstants.CAPEX] = 0\n summary_info[HyperConstants.OPEX] = 0\n summary_info['num_nodes'] = 0\n summary_info[HyperConstants.RACK_UNITS] = 0\n summary_info[HyperConstants.FAULT_TOLERANCE_COUNT] = 0\n summary_info['total_gpu_price'] = 0\n power_consumption = 0\n num_chassis = 0\n chassis_ru = 0\n\n for cluster_results in cluster_data:\n\n cluster_set_array = list()\n cluster_id = 0\n wl_present = True\n\n for cluster_index in range(0, len(cluster_results)):\n cluster_id += 1\n res = cluster_results[cluster_index][0]\n\n gpu_used = 0\n rack_units = 0\n\n for accessory in res[HyperConstants.ACC]:\n if 'GPU' in accessory[HyperConstants.ACC_NAME]:\n gpu_used = accessory[HyperConstants.ACC_COUNT]\n\n wls = cluster_results[cluster_index][1]\n self.replication = any(wl.attrib.get(HyperConstants.REPLICATION_FLAG, False) for wl in wls)\n\n settings = cluster_results[cluster_index][2]\n\n self.highest_rf = settings[HyperConstants.REPLICATION_FACTOR]\n self.RF_String = self.set_RF_String()\n if wls:\n self.Fault_Tolerance = max(wl.attrib[HyperConstants.FAULT_TOLERANCE] for wl in wls)\n else:\n wl_present = False\n self.Fault_Tolerance = 1\n\n cluster_json = dict()\n stat_list = list()\n web_stat_list = list()\n\n wl_json = list()\n\n self.sizer_instance.hercules = res[HyperConstants.NODE].hercules_on\n\n for wl in wls:\n\n cap_type = 'hercules' if res[HyperConstants.NODE].hercules_on else 'normal'\n\n wl.capsum[cap_type][BaseConstants.IOPS] = 0\n\n for iops_key in wl.original_iops_sum:\n\n if iops_key not in res[HyperConstants.NODE].attrib[BaseConstants.IOPS_CONV_FAC][self.RF_String]:\n\n if iops_key == HyperConstants.CONTAINER:\n #10.x\n if wl.attrib['storage_protocol'] == 'NFS':\n iops_conv_factor = \\\n float(\n res[HyperConstants.NODE].attrib[BaseConstants.IOPS_CONV_FAC][self.RF_String]\n [HyperConstants.VSI][0]) * 0.5\n else:\n iops_conv_factor = \\\n float(\n res[HyperConstants.NODE].attrib[BaseConstants.IOPS_CONV_FAC][self.RF_String]\n [HyperConstants.VSI][1]) * 0.5\n\n if iops_key == HyperConstants.AIML or iops_key == HyperConstants.ANTHOS or iops_key == HyperConstants.ROBO_BACKUP:\n # 10.x\n if wl.attrib['storage_protocol'] == 'NFS':\n iops_conv_factor = \\\n float(\n res[HyperConstants.NODE].attrib[BaseConstants.IOPS_CONV_FAC][self.RF_String]\n [HyperConstants.VSI][0])\n else:\n iops_conv_factor = \\\n float(\n res[HyperConstants.NODE].attrib[BaseConstants.IOPS_CONV_FAC][self.RF_String]\n [HyperConstants.VSI][1])\n else:\n\n if wl.attrib['storage_protocol'] == 'NFS':\n iops_conv_factor = float(\n res[HyperConstants.NODE].attrib[BaseConstants.IOPS_CONV_FAC][self.RF_String][\n iops_key][0])\n\n else:\n iops_conv_factor = float(\n res[HyperConstants.NODE].attrib[BaseConstants.IOPS_CONV_FAC][self.RF_String][\n iops_key][1])\n\n pcnt_increase = 0\n\n # below extra condition is because robo scaling already handles the % increase in performance\n if res[HyperConstants.NODE].attrib[HyperConstants.TYPE] == 'cto' and \\\n res[HyperConstants.NODE].attrib[BaseConstants.SUBTYPE] in [HyperConstants.ROBO_NODE,\n HyperConstants.AF_ROBO_NODE,\n HyperConstants.ROBO_TWO_NODE,\n HyperConstants.AF_ROBO_TWO_NODE,\n HyperConstants.ROBO_240,\n HyperConstants.ROBO_AF_240\n ]:\n\n pass\n\n else:\n\n if res[HyperConstants.NODE].hercules_on:\n pcnt_increase += HyperConstants.HERCULES_IOPS[iops_key]\n\n if res[HyperConstants.NODE].hx_boost_on:\n pcnt_increase += HyperConstants.HX_BOOST_IOPS[iops_key]\n\n iops_conv_factor *= (1 + pcnt_increase / 100.0)\n\n wl.capsum[cap_type][BaseConstants.IOPS] += wl.original_iops_sum[iops_key] / iops_conv_factor\n\n wl.attrib[BaseConstants.IOPS_CONV_FAC] = iops_conv_factor\n\n replication_traffic = getattr(wl, 'replication_traffic', 0)\n\n if self.replication:\n if wl.attrib['storage_protocol'] == 'NFS':\n wl.attrib['replication_iops'] = \\\n replication_traffic / float(res[HyperConstants.NODE].attrib[BaseConstants.IOPS_CONV_FAC]\n [self.RF_String][iops_key][0])\n else:\n wl.attrib['replication_iops'] = \\\n replication_traffic / float(res[HyperConstants.NODE].attrib[BaseConstants.IOPS_CONV_FAC]\n [self.RF_String][iops_key][1])\n\n # Calculating desktops per node for VDI workloads\n if wl.attrib[BaseConstants.WL_TYPE] == HyperConstants.VDI:\n total_nodes = res[HyperConstants.NUM] + res.get(HyperConstants.NUM_COMPUTE, 0)\n wl.attrib['desktops_per_node'] = int(ceil(float(wl.num_inst) / total_nodes))\n\n wl_json.append(wl.to_json())\n\n fault_tolerance_nodes = settings[HyperConstants.FAULT_TOLERANCE]\n\n if wls:\n for j, cap in enumerate(HyperConstants.STAT_LIST):\n util_list, web_util_list = self.generate_utilization_list(res, fault_tolerance_nodes, wls, cap, j, cluster_index)\n web_stat_list.extend(web_util_list)\n stat_list.extend(util_list)\n\n cluster_json['node_info'], new_chassis, new_chassis_ru = self.generate_node_info(res,\n fault_tolerance_nodes,\n str(cluster_id),\n gpu_used)\n\n num_chassis += new_chassis\n chassis_ru += new_chassis_ru\n\n if len(wls) == 1 and wls[0].attrib[BaseConstants.WL_TYPE] == HyperConstants.VDI:\n maxdesktop = self.calculate_maxdesktopVDI(wls[0], res)\n cluster_json['maxdesktop'] = maxdesktop\n\n if any(wl.attrib[HyperConstants.INTERNAL_TYPE] == HyperConstants.RDSH for wl in wls):\n self.rdsh_host_data(wls, res)\n\n for node_info in cluster_json['node_info']:\n rack_units += node_info[HyperConstants.RACK_UNITS]\n power_consumption += node_info[HyperConstants.POWER_CONSUMPTION]\n\n cluster_json[HyperConstants.RACK_UNITS] = rack_units\n cluster_json['wl_list'] = wl_json\n cluster_json['Utilization'] = stat_list if stat_list else list()\n cluster_json['utilization_web'] = web_stat_list if web_stat_list else list()\n cluster_json['settings'] = settings\n cluster_json['accessories'] = res[HyperConstants.ACC]\n cluster_json[BaseConstants.PRICE] = res[BaseConstants.PRICE]\n cluster_json['required_hxdp'] = self.sizer_instance.get_hxdp_version(cluster_json)\n cluster_set_array += [copy.deepcopy(cluster_json)]\n\n for node_info in cluster_json['node_info']:\n\n summary_info[BaseConstants.CAPEX] += \\\n node_info[BaseConstants.CAPEX]['value'][0][HyperConstants.TAG_VAL]\n\n summary_info[HyperConstants.OPEX] += \\\n node_info[HyperConstants.OPEX]['value'][0][HyperConstants.TAG_VAL]\n\n summary_info['num_nodes'] += \\\n node_info[HyperConstants.NUM_NODES]\n\n summary_info[HyperConstants.RACK_UNITS] += cluster_json[HyperConstants.RACK_UNITS]\n\n summary_info[HyperConstants.FAULT_TOLERANCE_COUNT] += fault_tolerance_nodes\n\n if wl_present:\n overall_summary['clusters'] += [cluster_set_array]\n else:\n overall_summary['no_wl_clusters'] += [cluster_set_array]\n\n overall_summary['summary_info'] = summary_info\n\n overall_summary['sizer_version'] = self.sizer_version\n\n overall_summary['hx_version'] = self.hx_version\n\n overall_summary['power_consumption'] = power_consumption\n overall_summary['num_chassis'] = num_chassis\n overall_summary['chassis_ru'] = chassis_ru\n overall_summary['result_name'] = self.result_name\n\n res_json.append(overall_summary)\n\n return res_json\n\n def generate_utilization_list(self, res, fault_tolerance_nodes, wls, cap, j, cluster_index):\n\n wl_total = dict()\n node_total = dict()\n node_total_ft = dict()\n raw_node_total = dict()\n wl_site_ft = dict()\n stat_list = list()\n web_stat_list = list()\n\n wl_type = wls[0].attrib[HyperConstants.INTERNAL_TYPE]\n\n if (cap == BaseConstants.IOPS and wl_type in [HyperConstants.AIML, HyperConstants.ANTHOS]) or \\\n (cap in [BaseConstants.CPU, BaseConstants.RAM, BaseConstants.IOPS] and\n wl_type in [HyperConstants.VEEAM]):\n\n util_dict = {\n HyperConstants.TAG_NAME: HyperConstants.STAT_UNIT_LIST[j],\n HyperConstants.UTIL_STATUS: False\n }\n stat_list.append(util_dict)\n web_stat_list.append(util_dict)\n return stat_list, web_stat_list\n\n dr_workload_types = [HyperConstants.VSI, HyperConstants.DB, HyperConstants.OLTP, HyperConstants.OLAP,\n HyperConstants.ORACLE, HyperConstants.OOLTP, HyperConstants.OOLAP]\n\n threshold_key = cap\n if cap == BaseConstants.HDD:\n if res[HyperConstants.NODE].attrib[BaseConstants.SUBTYPE] in [HyperConstants.ALL_FLASH,\n HyperConstants.ALLNVME_NODE, HyperConstants.ALLNVME_NODE_8TB,\n HyperConstants.ALL_FLASH_7_6TB, HyperConstants.AF_ROBO_NODE,\n HyperConstants.AF_ROBO_TWO_NODE, HyperConstants.ROBO_AF_240]:\n threshold_key = HyperConstants.ALL_FLASH_HDD\n if res[HyperConstants.NODE].attrib[HyperConstants.DISK_CAGE] == HyperConstants.LARGE_FORM_FACTOR:\n threshold_key = HyperConstants.LFF_HDD\n\n if self.replication and wl_type in dr_workload_types and cap in [BaseConstants.CPU, BaseConstants.RAM,\n BaseConstants.IOPS]:\n\n wl_total[cap] = 0\n wl_site_ft[cap] = 0\n\n for wl in wls:\n\n if wl.attrib['replication_type'] == HyperConstants.ANY_CLUSTER:\n wl_total[cap] += self.sizer_instance.get_req(wl, cap)\n\n elif cluster_index and wl.attrib['remote']:\n wl_total[cap] += self.sizer_instance.get_req(wl, cap)\n\n elif not cluster_index and not wl.attrib['remote']:\n wl_total[cap] += self.sizer_instance.get_req(wl, cap)\n\n elif not cluster_index and wl.attrib['remote']:\n if cap == BaseConstants.IOPS:\n wl_total[cap] += wl.attrib['replication_iops']\n wl_site_ft[cap] += self.sizer_instance.get_req(wl, cap)\n\n elif cluster_index and not wl.attrib['remote']:\n if cap == BaseConstants.IOPS:\n wl_total[cap] += wl.attrib['replication_iops']\n wl_site_ft[cap] += self.sizer_instance.get_req(wl, cap)\n\n if cap == BaseConstants.IOPS:\n wl_site_ft[cap] -= wl.attrib['replication_iops']\n else:\n wl_total[cap] = sum(self.sizer_instance.get_req(wl, cap) for wl in wls)\n wl_site_ft[cap] = 0\n\n if cap == BaseConstants.IOPS and wl_type == HyperConstants.CONTAINER:\n\n node_total[cap] = res[HyperConstants.NODE].cap[cap] * \\\n (HyperConstants.MAX_CONTAINER_IOPS_NODES + fault_tolerance_nodes)\n\n raw_node_total[cap] = res[HyperConstants.NODE].raw_cap[cap] * \\\n (HyperConstants.MAX_CONTAINER_IOPS_NODES + fault_tolerance_nodes)\n\n node_total_ft[cap] = HyperConstants.MAX_CONTAINER_IOPS_NODES * res[HyperConstants.NODE].cap[cap]\n\n else:\n\n node_total[cap] = res[HyperConstants.NUM] * res[HyperConstants.NODE].cap[cap]\n\n raw_node_total[cap] = res[HyperConstants.NUM] * res[HyperConstants.NODE].raw_cap[cap]\n\n node_total_ft[cap] = (res[HyperConstants.NUM] - fault_tolerance_nodes) * res[HyperConstants.NODE].cap[cap]\n\n if res.get(HyperConstants.COMPUTE) and res[HyperConstants.COMPUTE]:\n\n node_total[cap] += res[HyperConstants.NUM_COMPUTE] * res[HyperConstants.COMPUTE].cap[cap]\n\n raw_node_total[cap] += res[HyperConstants.NUM_COMPUTE] * res[HyperConstants.COMPUTE].raw_cap[cap]\n\n node_total_ft[cap] += res[HyperConstants.NUM_COMPUTE] * res[HyperConstants.COMPUTE].cap[cap]\n\n if not node_total[cap]:\n node_total[cap] = 1\n if not node_total_ft[cap]:\n node_total_ft[cap] = 1\n\n if cap == BaseConstants.HDD:\n node_total_ft[cap] = node_total[cap]\n\n scaling_factor = 1\n\n if cap == BaseConstants.CPU:\n\n if wl_type in [HyperConstants.VDI, HyperConstants.VDI_INFRA, HyperConstants.VDI_HOME, HyperConstants.RDSH,\n HyperConstants.RDSH_HOME]:\n\n clock_speed_mult = float(self.sizer_instance.base_cpu.speed)\n wl_total[cap] *= clock_speed_mult\n wl_site_ft[cap] *= clock_speed_mult\n raw_node_total[cap] *= clock_speed_mult\n node_total[cap] *= clock_speed_mult\n node_total_ft[cap] *= clock_speed_mult\n op_ratio = 1\n\n else:\n if wl_type in [HyperConstants.EPIC, HyperConstants.ANTHOS]:\n op_ratio = 1\n else:\n ops = Counter(wl.attrib[HyperConstants.VCPUS_PER_CORE] for wl in wls)\n op_ratio = ops.most_common(1)[0][0]\n wl_total[cap] = wl_total[cap] * op_ratio\n wl_site_ft[cap] = wl_site_ft[cap] * op_ratio\n raw_node_total[cap] = raw_node_total[cap] * op_ratio\n node_total[cap] = node_total[cap] * op_ratio\n node_total_ft[cap] = node_total_ft[cap] * op_ratio\n\n elif cap == BaseConstants.HDD:\n\n reduced_total = 0\n original_wl_total = 0\n\n for wl in wls:\n reduced_total += self.sizer_instance.get_req(wl, cap)\n original_wl_total += wl.original_size\n\n if original_wl_total > 0:\n scaling_factor = reduced_total / float(original_wl_total)\n else:\n scaling_factor = 1\n\n op_ratio = 100.0 / scaling_factor - 100\n\n node_total[cap] = node_total[cap] / self.highest_rf\n node_total_ft[cap] = node_total_ft[cap] / self.highest_rf\n raw_node_total[cap] = raw_node_total[cap] / self.highest_rf\n\n else:\n op_ratio = 1\n\n threshold_consumption = node_total[cap] * (1 - self.sizer_instance.get_threshold_value(wl_type, threshold_key))\n\n self.output_intermediate_calculation(res, wl_type, cap, op_ratio, scaling_factor)\n\n node_data = [raw_node_total, node_total, node_total_ft]\n\n wl_total_ft = deepcopy(wl_total)\n if cap == BaseConstants.IOPS and wl_type in [HyperConstants.VDI_INFRA, HyperConstants.VDI]:\n\n vdi_infra = sum(wl.attrib[HyperConstants.INTERNAL_TYPE] == HyperConstants.VDI_INFRA for wl in wls)\n\n additional_iops = vdi_infra * 0.1 * node_total[cap]\n wl_total[cap] += additional_iops\n\n additional_iops = vdi_infra * 0.1 * node_total_ft[cap]\n wl_total_ft[cap] += additional_iops\n\n wl_data = [wl_total, wl_site_ft, threshold_consumption, wl_total_ft]\n util_settings = {\n 'ratio': op_ratio,\n 'scaling_factor': scaling_factor,\n BaseConstants.WL_TYPE: wl_type\n }\n\n util_dict = self.build_result_util_categories(j, cap, wl_data, node_data, util_settings)\n stat_list.append(util_dict)\n web_util_dict ={\n HyperConstants.TAG_NAME: util_dict[HyperConstants.TAG_NAME],\n HyperConstants.WL_UTILIZATION: ceil(util_dict[HyperConstants.WL_UTILIZATION]),\n HyperConstants.FT_UTIL: ceil(util_dict[HyperConstants.FT_UTIL]),\n HyperConstants.SITE_FT_UTIL:ceil(util_dict[HyperConstants.SITE_FT_UTIL]), \n HyperConstants.FREE_UTIL: ceil(util_dict[HyperConstants.FREE_UTIL]),\n HyperConstants.UNITS: util_dict[HyperConstants.UNITS]\n }\n web_stat_list.append(web_util_dict)\n return stat_list, web_stat_list\n\n def output_intermediate_calculation(self, res, wl_type, cap, op_ratio, scaling_factor):\n\n # for cap in CAP_LIST:\n threshold_key = cap\n if cap == BaseConstants.HDD:\n if res[HyperConstants.NODE].attrib[BaseConstants.SUBTYPE] in [HyperConstants.ALL_FLASH,\n HyperConstants.AF_ROBO_NODE, HyperConstants.ALLNVME_NODE,\n HyperConstants.ALLNVME_NODE_8TB, HyperConstants.ALL_FLASH_7_6TB,\n HyperConstants.AF_ROBO_TWO_NODE]:\n threshold_key = HyperConstants.ALL_FLASH_HDD\n if res[HyperConstants.NODE].attrib[HyperConstants.DISK_CAGE] == HyperConstants.LARGE_FORM_FACTOR:\n threshold_key = HyperConstants.LFF_HDD\n\n if cap == BaseConstants.CPU:\n\n raw_cores_total = \\\n (res[HyperConstants.NODE].raw_cap[cap] / res[HyperConstants.NODE].attrib[HyperConstants.SPECLNT]) * \\\n res[HyperConstants.NUM]\n\n raw_cores_adjspeclnt = res[HyperConstants.NODE].raw_cap[cap] * res[HyperConstants.NUM]\n\n cores_total = res[HyperConstants.NODE].cap[cap] * res[HyperConstants.NUM] * op_ratio\n\n if wl_type == HyperConstants.VDI:\n clock_speed_mult = float(res[HyperConstants.NODE].attrib[BaseConstants.CLOCK_SPEED])\n raw_cores_adjspeclnt = raw_cores_adjspeclnt * clock_speed_mult\n cores_total = cores_total * clock_speed_mult\n\n cpu_threshold = self.sizer_instance.get_threshold_value(wl_type, threshold_key)\n cores_total_afterthreshold = cores_total * cpu_threshold\n\n res[HyperConstants.NODE].attrib[HyperConstants.CPU_OPRATIO] = op_ratio\n res[HyperConstants.NODE].attrib[HyperConstants.RAW_CORES_TOTAL] = raw_cores_total\n res[HyperConstants.NODE].attrib[HyperConstants.RAW_CORES_ADJSPECLNT] = raw_cores_adjspeclnt\n res[HyperConstants.NODE].attrib[HyperConstants.CORES_TOTAL_POSTOVERHEAD] = cores_total\n res[HyperConstants.NODE].attrib[HyperConstants.CORES_TOTAL_POSTTHRESHOLD] = cores_total_afterthreshold\n res[HyperConstants.NODE].attrib[HyperConstants.NODE_OVERHEAD] = res[HyperConstants.NODE].overhead\n\n elif cap == BaseConstants.RAM:\n\n raw_memory_size = res[HyperConstants.NODE].raw_cap[cap] * res[HyperConstants.NUM]\n memory_afteroverhead = res[HyperConstants.NODE].cap[cap] * res[HyperConstants.NUM]\n memory_threshold = self.sizer_instance.get_threshold_value(wl_type, threshold_key)\n memory_afterthreshold = memory_afteroverhead * memory_threshold\n\n res[HyperConstants.NODE].attrib[HyperConstants.RAM_OPRATIO] = op_ratio\n res[HyperConstants.NODE].attrib[HyperConstants.RAW_RAM_TOTAL] = raw_memory_size\n res[HyperConstants.NODE].attrib[HyperConstants.RAM_TOTAL_POSTOVERHEAD] = memory_afteroverhead\n res[HyperConstants.NODE].attrib[HyperConstants.RAM_TOTAL_POSTTHRESHOLD] = memory_afterthreshold\n\n elif cap == BaseConstants.HDD:\n\n raw_disk = res[HyperConstants.NODE].raw_cap[cap] * res[HyperConstants.NUM]\n disk_afterRF = raw_disk / self.highest_rf\n disk_afteroverhead = (res[HyperConstants.NODE].cap[cap] * res[HyperConstants.NUM]) / self.highest_rf\n disk_threshold = self.sizer_instance.get_threshold_value(wl_type, threshold_key)\n disk_afterthreshold = disk_afteroverhead * disk_threshold\n\n res[HyperConstants.NODE].attrib[HyperConstants.HDD_OPRATIO] = op_ratio\n res[HyperConstants.NODE].attrib[HyperConstants.RAW_HDD_TOTAL] = raw_disk\n res[HyperConstants.NODE].attrib[HyperConstants.HDD_TOTAL_POSTRF] = disk_afterRF\n res[HyperConstants.NODE].attrib[HyperConstants.HDD_TOTAL_POSTOVERHEAD] = disk_afteroverhead\n res[HyperConstants.NODE].attrib[HyperConstants.HDD_TOTAL_POSTTHRESHOLD] = disk_afterthreshold\n res[HyperConstants.NODE].attrib[HyperConstants.HIGHEST_RF] = self.highest_rf\n res[HyperConstants.NODE].attrib[HyperConstants.THRESHOLD_KEY] = threshold_key\n res[HyperConstants.NODE].attrib[HyperConstants.SCALING_FACTOR] = scaling_factor\n res[HyperConstants.NODE].attrib[HyperConstants.NODE_OVERHEAD] = res[HyperConstants.NODE].overhead\n\n elif cap == BaseConstants.IOPS:\n\n raw_iops = res[HyperConstants.NODE].raw_cap[cap] * res[HyperConstants.NUM]\n iops_afterConversion = res[HyperConstants.NODE].cap[cap] * res[HyperConstants.NUM]\n\n res[HyperConstants.NODE].attrib[HyperConstants.RAW_IOPS_TOTAL] = raw_iops\n res[HyperConstants.NODE].attrib[HyperConstants.IOPS_TOTAL_POSTIOPSCONV] = iops_afterConversion\n\n elif cap == BaseConstants.VRAM:\n\n raw_gpu_size = res[HyperConstants.NODE].raw_cap[cap] * res[HyperConstants.NUM]\n\n res[HyperConstants.NODE].attrib[HyperConstants.RAW_VRAM_TOTAL] = raw_gpu_size\n\n if res.get(HyperConstants.COMPUTE):\n for cap in HyperConstants.CAP_LIST:\n if cap == BaseConstants.CPU:\n\n raw_cores_total = \\\n (res[HyperConstants.COMPUTE].raw_cap[cap] /\n res[HyperConstants.COMPUTE].attrib[HyperConstants.SPECLNT]) * res[HyperConstants.NUM_COMPUTE]\n\n raw_cores_adjspeclnt = res[HyperConstants.COMPUTE].raw_cap[cap] * res[HyperConstants.NUM_COMPUTE]\n\n cores_total = res[HyperConstants.COMPUTE].cap[cap] * res[HyperConstants.NUM_COMPUTE]\n\n if wl_type == HyperConstants.VDI:\n clock_speed_mult = float(res[HyperConstants.COMPUTE].attrib[BaseConstants.CLOCK_SPEED])\n raw_cores_adjspeclnt = raw_cores_adjspeclnt * clock_speed_mult\n cores_total = cores_total * clock_speed_mult\n\n cpu_threshold = self.sizer_instance.get_threshold_value(wl_type, threshold_key)\n cores_total_afterthreshold = cores_total * cpu_threshold\n\n res[HyperConstants.COMPUTE].attrib[HyperConstants.RAW_CORES_TOTAL] = raw_cores_total\n\n res[HyperConstants.COMPUTE].attrib[HyperConstants.RAW_CORES_ADJSPECLNT] = raw_cores_adjspeclnt\n\n res[HyperConstants.COMPUTE].attrib[HyperConstants.CORES_TOTAL_POSTOVERHEAD] = cores_total\n\n res[HyperConstants.COMPUTE].attrib[HyperConstants.CORES_TOTAL_POSTTHRESHOLD] = \\\n cores_total_afterthreshold\n\n res[HyperConstants.COMPUTE].attrib[HyperConstants.NODE_OVERHEAD] = \\\n res[HyperConstants.COMPUTE].overhead\n\n elif cap == BaseConstants.RAM:\n\n raw_memory_size = res[HyperConstants.COMPUTE].raw_cap[cap] * res[HyperConstants.NUM_COMPUTE]\n\n memory_afteroverhead = res[HyperConstants.COMPUTE].cap[cap] * res[HyperConstants.NUM_COMPUTE]\n\n memory_threshold = self.sizer_instance.get_threshold_value(wl_type, threshold_key)\n\n memory_afterthreshold = memory_afteroverhead * memory_threshold\n\n res[HyperConstants.COMPUTE].attrib[HyperConstants.RAW_RAM_TOTAL] = raw_memory_size\n\n res[HyperConstants.COMPUTE].attrib[HyperConstants.RAM_TOTAL_POSTOVERHEAD] = memory_afteroverhead\n\n res[HyperConstants.COMPUTE].attrib[HyperConstants.RAM_TOTAL_POSTTHRESHOLD] = memory_afterthreshold\n\n @staticmethod\n def build_result_util_categories(j, cap, wl_data, node_data, util_settings):\n\n op_ratio = util_settings['ratio']\n scaling_factor = util_settings['scaling_factor']\n wl_type = util_settings[BaseConstants.WL_TYPE]\n\n output_wl_total = dict()\n wl_total = wl_data[0]\n wl_site_ft = wl_data[1]\n threshold_consumption = wl_data[2]\n wl_total_ft = wl_data[3]\n\n raw_node_total = node_data[0][cap]\n node_total = node_data[1][cap]\n ft_node_total = node_data[2][cap]\n\n if not raw_node_total:\n raw_node_total = 1\n if not node_total:\n node_total = 1\n if not ft_node_total:\n ft_node_total = 1\n\n wl_util = wl_total[cap] * 100.0 / node_total\n\n if not wl_util:\n ft_util = 0\n else:\n ft_util = (wl_total_ft[cap] * 100.0 / ft_node_total)\n\n threshold_util = threshold_consumption / node_total * 100.0\n\n site_ft_util = (wl_total[cap] + wl_site_ft[cap]) * 100.0 / ft_node_total\n free_util = 100 - threshold_util - wl_util\n\n util_dict = {\n HyperConstants.UTIL_STATUS: True,\n HyperConstants.TAG_NAME: HyperConstants.STAT_UNIT_LIST[j],\n HyperConstants.WL_UTILIZATION: wl_util,\n HyperConstants.FT_UTIL: ft_util,\n HyperConstants.SITE_FT_UTIL: site_ft_util,\n HyperConstants.THRESHOLD_UTILIZATION: threshold_util,\n HyperConstants.FREE_UTIL: free_util,\n HyperConstants.RATIO: op_ratio\n }\n\n if cap == BaseConstants.IOPS:\n sizing_threshold = ((wl_util + free_util) / 100.0) * node_total\n workload_total = wl_total[cap]\n cap_unit = HyperConstants.STAT_UNITS[j]\n\n elif cap == BaseConstants.HDD or cap == BaseConstants.SSD:\n\n if node_total > 1000:\n output_wl_total[cap] = wl_total[cap] / 1000.0\n raw_output_node_total = node_total / 1000.0\n cap_unit = 'TB'\n raw_output_node_total_binarybyte = raw_output_node_total * HyperConstants.TB_TO_TIB_CONVERSION\n binarybyte_unit = 'TiB'\n scaled_node_total_binarybyte = \\\n raw_output_node_total / scaling_factor * HyperConstants.TB_TO_TIB_CONVERSION\n\n else:\n output_wl_total[cap] = wl_total[cap]\n raw_output_node_total = node_total\n cap_unit = 'GB'\n raw_output_node_total_binarybyte = raw_output_node_total * HyperConstants.GB_TO_GIB_CONVERSION\n binarybyte_unit = 'GiB'\n scaled_node_total_binarybyte = \\\n raw_output_node_total / scaling_factor * HyperConstants.GB_TO_GIB_CONVERSION\n\n scaled_node_total = raw_output_node_total / scaling_factor\n\n sizing_threshold = ((wl_util + free_util) / 100.0) * scaled_node_total\n\n sizing_threshold_binarybyte = ((wl_util + free_util) / 100.0) * scaled_node_total_binarybyte\n\n workload_total = output_wl_total[cap] / scaling_factor\n\n node_total = scaled_node_total\n\n node_total_binarybyte = scaled_node_total_binarybyte\n\n util_dict.update({\n HyperConstants.USABLE_VAL: raw_output_node_total,\n HyperConstants.USABLE_VAL_BINARYBYTE: raw_output_node_total_binarybyte,\n HyperConstants.BINARYBYTE_UNIT: binarybyte_unit,\n BaseConstants.NODE_VAL_BINARYBYTE: node_total_binarybyte,\n BaseConstants.BEST_PRACTICE_BINARYBYTE: sizing_threshold_binarybyte\n })\n else:\n sizing_threshold = ((wl_util + free_util) / 100.0) * ft_node_total\n node_total = ft_node_total\n if wl_type in [HyperConstants.VDI, HyperConstants.VDI_INFRA, HyperConstants.VDI_HOME, HyperConstants.RDSH,\n HyperConstants.RDSH_HOME] and cap == BaseConstants.CPU:\n workload_total = wl_total[cap]\n cap_unit = 'GHz'\n else:\n workload_total = wl_total[cap]\n cap_unit = HyperConstants.STAT_UNITS[j]\n\n util_dict.update({\n BaseConstants.WORKLOAD_VAL: workload_total,\n BaseConstants.NODE_VAL: node_total,\n BaseConstants.TOTAL_NODE_VAL: raw_node_total,\n HyperConstants.UNITS: cap_unit,\n BaseConstants.BEST_PRACTICE: sizing_threshold\n })\n return util_dict\n\n def generate_node_info(self, res, fault_tolerance_nodes, cluster_id, gpu_used):\n\n return_node_info = list()\n num_chassis = 0\n chassis_ru = 0\n\n # First element is HX node, Second is Compute\n for node_type, count in [(HyperConstants.NODE, HyperConstants.NUM), (HyperConstants.COMPUTE,\n HyperConstants.NUM_COMPUTE)]:\n\n node_details = res.get(node_type)\n\n if not node_details:\n continue\n\n node_count = res[count]\n\n capex_list = node_details.get_capex(node_count)\n\n opex_list = node_details.get_opex(node_count, self.sizer_instance.vdi_user)\n\n summary_list = node_details.get_summary(node_count, self.sizer_instance.vdi_user,\n self.sizer_instance.vm_user, self.sizer_instance.db_user,\n self.sizer_instance.raw_user, self.sizer_instance.robo_user,\n self.sizer_instance.oracle_user)\n\n if node_details.attrib.get('use_chassis') and node_type == HyperConstants.COMPUTE:\n\n node_power_consumption = self.parts_table.get_part_attrib(node_details.attrib['chassis_options'],\n HyperConstants.POWER)\n\n individual_ru = \\\n self.parts_table.get_part_attrib(node_details.attrib['chassis_options'], HyperConstants.RACK_SPACE)\n\n compute_clusters = int(ceil(node_count/8.0))\n\n num_chassis += compute_clusters\n\n chassis_ru += individual_ru * compute_clusters\n\n rack_units = chassis_ru\n else:\n node_power_consumption = node_details.attrib[HyperConstants.POWER] * node_count\n rack_units = node_count * node_details.attrib[HyperConstants.RACK_SPACE]\n\n node_config = {\n BaseConstants.DISPLAY_NAME: 'Cluster_' + cluster_id,\n HyperConstants.MODEL_DETAILS: node_details.get_model_details(gpu_used),\n HyperConstants.BOM_MODEL_DETAILS: node_details.get_bom_details(),\n HyperConstants.NUM_NODES: node_count,\n HyperConstants.FAULT_TOLERANCE_COUNT: fault_tolerance_nodes if node_type == HyperConstants.NODE else 0,\n HyperConstants.POWER_CONSUMPTION: node_power_consumption,\n BaseConstants.CAPEX: capex_list,\n HyperConstants.OPEX: opex_list,\n HyperConstants.SUMMARY: summary_list,\n HyperConstants.RACK_UNITS: rack_units,\n HyperConstants.HERCULES_CONF: node_details.hercules_on,\n HyperConstants.HX_BOOST_CONF: node_details.hx_boost_on\n }\n\n mod_lan = node_details.get_mod_lan()\n if mod_lan:\n node_config[HyperConstants.MOD_LAN] = mod_lan\n\n return_node_info.append(node_config)\n return return_node_info, num_chassis, chassis_ru\n\n def calculate_maxdesktopVDI(self, wl, res):\n\n wl_num_inst = wl.num_inst\n\n wl_cpu = self.sizer_instance.get_req(wl, BaseConstants.CPU) / wl_num_inst\n wl_ram = self.sizer_instance.get_req(wl, BaseConstants.RAM) / wl_num_inst\n wl_ssd = self.sizer_instance.get_req(wl, BaseConstants.SSD) / wl_num_inst\n wl_hdd = self.sizer_instance.get_req(wl, BaseConstants.HDD) / wl_num_inst\n wl_vram = self.sizer_instance.get_req(wl, BaseConstants.VRAM) / wl_num_inst\n\n hc_node = res[HyperConstants.NODE]\n\n cpu_threshold = self.sizer_instance.get_threshold_value(HyperConstants.VDI, BaseConstants.CPU)\n\n cpu_overhead = hc_node.overhead[BaseConstants.CPU]\n\n total_cores = ((hc_node.raw_cap[BaseConstants.CPU] * cpu_threshold) - cpu_overhead) * \\\n (res[HyperConstants.NUM] - self.Fault_Tolerance)\n\n if wl_cpu:\n maxvmbycpu = total_cores / wl_cpu\n else:\n maxvmbycpu = 0\n\n ram_threshold = self.sizer_instance.get_threshold_value(HyperConstants.VDI, BaseConstants.RAM)\n\n ram_overhead = hc_node.overhead[BaseConstants.RAM]\n\n total_ram = ((hc_node.raw_cap[BaseConstants.RAM] * ram_threshold) - ram_overhead) * \\\n (res[HyperConstants.NUM] - self.Fault_Tolerance)\n\n if wl_ram:\n maxvmbyram = total_ram / wl_ram\n else:\n maxvmbyram = 0\n\n ssd_threshold = self.sizer_instance.get_threshold_value(HyperConstants.VDI, BaseConstants.SSD)\n\n total_ssd = hc_node.cap[BaseConstants.SSD] * ssd_threshold * (res[HyperConstants.NUM] - self.Fault_Tolerance)\n\n if wl_ssd:\n maxvmbyssd = math.floor(total_ssd / wl_ssd)\n else:\n maxvmbyssd = 0\n\n hdd_threshold = self.sizer_instance.get_threshold_value(HyperConstants.VDI, BaseConstants.HDD)\n\n total_hdd = \\\n (hc_node.cap[BaseConstants.HDD] * hdd_threshold) * res[HyperConstants.NUM] / float(self.highest_rf)\n\n if wl_hdd:\n maxvmbyhdd = math.floor(total_hdd / wl_hdd)\n else:\n maxvmbyhdd = 0\n\n maxvmbyvram = 0\n\n if hc_node.attrib[BaseConstants.VRAM]:\n\n vram_threshold = self.sizer_instance.get_threshold_value(HyperConstants.VDI, BaseConstants.VRAM)\n\n vram_value = hc_node.cap[BaseConstants.VRAM] * vram_threshold\n\n acc_list = res['accessory']\n\n for accessory in acc_list:\n if accessory['type'] == BaseConstants.GPU:\n total_vram = vram_value * accessory['count']\n maxvmbyvram += math.floor(total_vram / wl_vram if wl_vram else 1)\n\n if res.get(HyperConstants.COMPUTE) and res[HyperConstants.COMPUTE]:\n\n compute_node = res[HyperConstants.COMPUTE]\n\n total_cores = compute_node.cap[BaseConstants.CPU] * cpu_threshold * res[HyperConstants.NUM_COMPUTE]\n\n maxvmbycpu += total_cores / wl_cpu\n\n total_ram = compute_node.cap[BaseConstants.RAM] * ram_threshold * res[HyperConstants.NUM_COMPUTE]\n\n maxvmbyram += total_ram / wl_ram\n\n maxvmbycpu = math.floor(maxvmbycpu)\n\n maxvmbyram = math.floor(maxvmbyram)\n\n maxdesktoplist = [maxvmbycpu, maxvmbyram, maxvmbyssd, maxvmbyhdd]\n\n if maxvmbyvram:\n\n maxdesktoplist.append(maxvmbyvram)\n\n maxdesktop = int(min(maxdesktoplist))\n\n return maxdesktop\n\n @staticmethod\n def rdsh_host_data(workloads, result):\n\n hx_count = result[HyperConstants.NUM]\n co_count = result[HyperConstants.NUM_COMPUTE]\n\n total_count = float(hx_count + co_count)\n\n for wl in filter(lambda x: x.attrib[HyperConstants.INTERNAL_TYPE] == HyperConstants.RDSH, workloads):\n\n wl.attrib['users_per_host'] = int(ceil(wl.attrib['total_users'] / total_count))\n wl.attrib['vms_per_host'] = int(ceil(wl.num_vms / total_count))\n","sub_path":"hyperflexsizer-NewVersions/sizer/sizer/hyperconverged/solver/utilization_class.py","file_name":"utilization_class.py","file_ext":"py","file_size_in_byte":40361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"157610247","text":"from cipher.caesar import caesar_get_error, caesar_main\nfrom cipher.vigenère import vigenere_get_error, vigenere_main\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtWidgets import (QApplication, QCheckBox, QComboBox, QFileDialog, QHBoxLayout,\n QMessageBox, QPlainTextEdit, QPushButton, QVBoxLayout, QWidget)\nimport os\nimport sys\n\n\nclass MainWindow(QWidget):\n def __init__(self, **kwargs):\n super(MainWindow, self).__init__(**kwargs)\n self.resize(1080, 640)\n self.setWindowTitle(\"Ciphers\")\n\n self.inputText = QPlainTextEdit()\n self.inputText.setPlaceholderText(\"Input...\")\n\n self.outputText = QPlainTextEdit()\n self.outputText.setReadOnly(True)\n self.outputText.setPlaceholderText(\"Output\")\n\n self.openFileButton = QPushButton(\"File\")\n self.openFileButton.clicked.connect(self.open_file)\n\n self.saveFileButton = QPushButton(\"Save\")\n self.saveFileButton.clicked.connect(self.save_file)\n\n self.cipherBox = QComboBox()\n self.cipherBox.addItems([\"Caesar\", \"Vigenere\"])\n\n self.modeBox = QComboBox()\n self.modeBox.addItems([\"Cipher\", \"Decipher\"])\n\n self.keyText = QPlainTextEdit()\n self.keyText.setPlaceholderText(\"Key...\")\n\n self.clearButton = QPushButton(\"Clear\")\n self.clearButton.clicked.connect(self.clear)\n\n self.clearCheckKey = QCheckBox(\"key\")\n self.clearCheckKey.setChecked(True)\n\n self.swapButton = QPushButton(\"<-- Swap -->\")\n self.swapButton.clicked.connect(self.swap)\n\n self.cipherButton = QPushButton(\"GO\")\n self.cipherButton.clicked.connect(self.cipher)\n\n self.fileLayout = QHBoxLayout()\n self.fileLayout.addWidget(self.openFileButton, alignment=Qt.AlignBaseline)\n self.fileLayout.addWidget(self.saveFileButton, alignment=Qt.AlignBaseline)\n\n self.cipherLayout = QHBoxLayout()\n self.cipherLayout.addWidget(self.cipherBox, alignment=Qt.AlignBaseline)\n self.cipherLayout.addWidget(self.modeBox, alignment=Qt.AlignBaseline)\n\n self.commandLayout = QHBoxLayout()\n self.commandLayout.addWidget(self.clearButton, alignment=Qt.AlignBaseline)\n self.commandLayout.addWidget(self.swapButton, alignment=Qt.AlignBaseline)\n\n self.userLayout = QVBoxLayout()\n self.userLayout.addLayout(self.fileLayout)\n self.userLayout.addLayout(self.cipherLayout)\n self.userLayout.addWidget(self.keyText, alignment=Qt.AlignCenter)\n self.userLayout.addWidget(self.cipherButton, alignment=Qt.AlignBaseline)\n self.userLayout.addLayout(self.commandLayout)\n self.userLayout.addWidget(self.clearCheckKey, alignment=Qt.AlignTop)\n\n self.mainLayout = QHBoxLayout()\n self.mainLayout.addWidget(self.inputText)\n self.mainLayout.addLayout(self.userLayout)\n self.mainLayout.addWidget(self.outputText)\n\n self.setLayout(self.mainLayout)\n\n def cipher(self):\n if self.cipherBox.currentText() == \"Caesar\":\n error, user_key = caesar_get_error(self.keyText.toPlainText())\n if len(error) == 0:\n self.outputText.setPlainText(caesar_main(self.inputText.toPlainText(), user_key, self.modeBox.currentText()))\n else:\n QMessageBox.critical(None, \"An exception was raised\", error)\n if self.cipherBox.currentText() == \"Vigenere\":\n error = vigenere_get_error(self.keyText.toPlainText())\n if len(error) == 0:\n self.outputText.setPlainText(vigenere_main(self.inputText.toPlainText(), self.keyText.toPlainText(), self.modeBox.currentText()))\n else:\n QMessageBox.critical(None, \"An exception was raised\", error)\n\n def swap(self):\n holder = self.inputText.toPlainText()\n self.inputText.setPlainText(self.outputText.toPlainText())\n self.outputText.setPlainText(holder)\n\n def clear(self):\n self.inputText.setPlainText(\"\")\n self.outputText.setPlainText(\"\")\n if self.clearCheckKey.isChecked():\n self.keyText.setPlainText(\"\")\n\n def open_file(self):\n file = QFileDialog.getOpenFileName(None, 'Open file', os.path.dirname(os.path.abspath(__file__)), \"*.txt\")[0]\n try:\n with open(file, 'r') as f:\n self.inputText.setPlainText(f.read())\n except FileNotFoundError:\n pass\n\n def save_file(self):\n file = QFileDialog.getSaveFileName(None, 'Save file', os.path.dirname(os.path.abspath(__file__)), \"*.txt\")[0]\n with open(file, 'w') as f:\n f.write(self.outputText.toPlainText())\n\n\ndef catch_exceptions(t, val, tb):\n QMessageBox.critical(None, 'An exception was raised', 'Exception type: {}'.format(t))\n old_hook(t, val, tb)\n\n\nif __name__ == '__main__':\n old_hook = sys.excepthook\n sys.excepthook = catch_exceptions\n\n app = QApplication(sys.argv)\n window = MainWindow()\n window.show()\n sys.exit(app.exec_())\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"88067199","text":"#NB to use\n# % source /project/projectdirs/desi/software/desi_environment.csh\n#% pip install --user scikit-learn\nfrom sklearn.neural_network import MLPClassifier\nimport scipy.misc\nimport numpy as np\nimport pandas as pd\nimport os\nimport matplotlib.pyplot as plt\nimport readin_HSC as rdHSC\n\nfrom sklearn import cross_validation,datasets,svm\nfrom sklearn.externals import joblib\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.tree import DecisionTreeClassifier\n\n\n# Setup parameters\nnum_labels = 1;\n\nreload(rdHSC)\nmag_flag =2\n# Load Training Data\nTA = rdHSC.sort_data(mag_flag)\nTAall = np.array([TA['g_r'],TA['r_z'],TA['g_z'],TA['g_W1'],TA['r_W1'],\n TA['z_W1'],TA['g_W2'],TA['r_W2'],TA['z_W2'],TA['W1_W2'],TA['r'],TA['y']])\n\nTAall = TAall.transpose()\nX = TAall[:,:-1]\ny = TAall[:,-1:]\n# clf = MLPClassifier(activation='logistic',solver='adam', alpha=1e-2, hidden_layer_sizes=(100, 2), verbose=True, random_state=1)\n# clf.fit(X, y)\nprint('\\n Now test it\\n') \nTD = rdHSC.sort_test_data(mag_flag) \nTDall = np.array([TD['g_r'],TD['r_z'],TD['g_z'],TD['g_W1'],TD['r_W1'],TD['z_W1'],TD['g_W2'],TD['r_W2'],TD['z_W2'],TD['W1_W2'],TD['r'], TD['y']])\nTestData = TDall.transpose() \n# print(TestData.shape) \n# print(\"udated\\n\")\nX_test = TestData[:,:-1] \ny_test = TestData[:,-1]\nnp.random.seed(0)\nTP=[]\nTN=[]\nFP=[]\nFN=[]\nprec=[]\nrecall=[]\nNF=[]\nMDepth=[]\nMLeaf=[]\nNbForests =[10, 20, 100, 500]\nmax_depth = [10,15,50,100]\nmax_ln =[100,1000]\n\nfor NbForest in NbForests:\n for md in max_depth:\n for mln in max_ln:\n print(mln,md,NbForest)\n rf = RandomForestClassifier(n_estimators=NbForest, min_samples_split=2, max_depth=md, max_leaf_nodes=mln) \n rf.fit(X, y.ravel())\n b = rf.predict(X_test)\n yones = y_test[y_test==1]\n yzeros = y_test[y_test==0]\n NNones = b[y_test==1]\n NNzeros = b[y_test==0]\n\n cTP = yones==NNones\n cTN = yzeros=NNzeros\n cFP = sum(NNzeros)\n cFN = len(NNones)-sum(NNones)\n\n TP.append(sum(cTP))\n TN.append(sum(cTN))\n FP.append(cFP)\n FN.append(cFN)\n prec.append(float(sum(cTP))/float(sum(cTP)+ cFP))\n recall.append(float(sum(cTP))/float(sum(cTP)+ cFN))\n NF.append(NbForest)\n MDepth.append(md)\n MLeaf.append(mln)\n \nfileout = 'params_RF_new.txt'\nnp.savetxt(fileout, np.c_[NF,MDepth,MLeaf,TP,TN,FP,FN,prec,recall],fmt='%1.4f')\n\n#plot ROC curve and compute AUC\nfrom sklearn import metrics\nprobs = rf.predict_proba(X_test)\nfpr, tpr, _ = metrics.roc_curve(y_test, probs[:,1])\nimport matplotlib.pyplot as plt\nplt.plot(fpr,tpr)\nplt.fill_between(fpr, 0, tpr,facecolor='powderblue')\nplt.xlabel('fpr')\nplt.ylabel('tpr')\nplt.title('ROC Curve for random forest w/AUC =0.89')\nplt.savefig('ROC_RF.pdf')\nauc = metrics.auc(fpr,tpr)\n'''\n# xdat = rf.predict_proba(X_test)\n# ydat = clf.predict_proba(X_test)\n#histograms of results for both random forest and NN methods\nplt.figure()\nmask_TP = np.zeros(len(y_test), bool) | ((y_test>0) & (bRF >0)) #valnn=0 TP\nmask_FN = np.zeros(len(y_test), bool) | ((y_test==0) & (bRF>0)) #valnn=1 FN\nmask_TN = np.zeros(len(y_test), bool) | ((y_test==0) & (bRF == 0)) #valnn=2 TN\nmask_FP = np.zeros(len(y_test), bool) | ((y_test>0) & (bRF == 0)) #valnn=3 FP\n\nplt.hist(xdat[mask_TP,1], \\\n bins=np.arange(0.-0.02,1. + 0.02, 0.02), \\\n ec='blue', fc='none', lw=1.5, histtype='step', label='TP' )\nplt.hist(xdat[mask_TN,1], \\\n bins=np.arange(0.-0.02,1. + 0.02, 0.02), \\\n ec='red', fc='none', lw=1.5, histtype='step', label='TN' )\nplt.hist(xdat[mask_FP,1], \\\n bins=np.arange(0.-0.02,1. + 0.02, 0.02), \\\n ec='black', fc='none', lw=1.5, histtype='step', label='FP' )\nplt.hist(xdat[mask_FN,1], \\\n bins=np.arange(0.-0.02,1. + 0.02, 0.02), \\\n ec='green', fc='none', lw=1.5, histtype='step', label='FN' )\nplt.legend(loc='upper center') \nplt.ylabel(\"count\")\nplt.title('RF scores') \nplt.savefig('histRF.png')\nplt.figure()\nmask_TP = np.zeros(len(y_test), bool) | ((y_test>0) & (bNN >0)) #valnn=0 TP \nmask_FN = np.zeros(len(y_test), bool) | ((y_test==0) & (bNN>0)) #valnn=1 FN \nmask_TN = np.zeros(len(y_test), bool) | ((y_test==0) & (bNN == 0)) #valnn=2 TN \nmask_FP = np.zeros(len(y_test), bool) | ((y_test>0) & (bNN == 0)) #valnn=3 FP \nplt.hist(ydat[mask_TP,1], \\\n bins=np.arange(0.-0.02,1. + 0.02, 0.02), \\\n ec='blue', fc='none', lw=1.5, histtype='step', label='TP' )\nplt.hist(ydat[mask_TN,1], \\\n bins=np.arange(0.-0.02,1. + 0.02, 0.02), \\\n ec='red', fc='none', lw=1.5, histtype='step', label='TN' )\nplt.hist(ydat[mask_FP,1], \\\n bins=np.arange(0.-0.02,1. + 0.02, 0.02), \\\n ec='black', fc='none', lw=1.5, histtype='step', label='FN' )\nplt.hist(ydat[mask_FN,1], \\\n bins=np.arange(0.-0.02,1. + 0.02, 0.02), \\\n ec='green', fc='none', lw=1.5, histtype='step', label='FP' )\nplt.legend(loc='upper center') \nplt.ylabel(\"count\")\nplt.title('NN scores') \nplt.savefig('histNN.png')\n\n#tests to check which data points were classified the same by both methods \n#shows contour plot of RF prediction[ith data] vs NN prediction[ith data]\n#for subset of data points\n\nimport seaborn as sns\nsns.set(color_codes=True)\nf, ax = plt.subplots(1, 2, figsize=(10, 5), sharex=True, sharey=True)\nax[0].set_ylabel('NN')\nax[0].set_xlabel('RF')\nax[1].set_xlabel('RF')\nsns.kdeplot(xdat[y_test==1,1], ydat[y_test==1,1], cmap=\"Reds\",n_levels=100, ax= ax[0],cbar=True,label='True ELG', legend=True)\nsns.kdeplot(xdat[y_test==0,1], ydat[y_test==0,1], cmap=\"Blues\",n_levels=100, ax=ax[1],cbar=True, label='Not ELG', legend=True)\nsns.set_style(\"ticks\")\nf.tight_layout()\nf.savefig(\"contour.png\")\n\n'''\n'''quick test plot with subset of data\nxrange=xdat[0:10000,1]\nyrange=ydat[0:10000,1]\nyval=y_test[0:10000]\nplt.plot(xrange[yval>0],yrange[yval>0],'ob')\nplt.ylabel('NN_results')\nplt.xlabel('RF_results')\nplt.title('True ELGs')\nplt.savefig('ELG.png')'''","sub_path":"RF_HSC.py","file_name":"RF_HSC.py","file_ext":"py","file_size_in_byte":6489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"110912169","text":"#!/usr/nikola/bin/python\n# \n# File Name : solution.py\n#\n# Description :\n#\n# Usage :\n#\n# Creation Date : 08-01-2015\n# Last Modified : Thu Jan 8 16:07:05 2015\n# Author : Hao Cheng chenghao@uw.edu\n\nimport string\n\nclass Solution:\n # @param s, a string\n # @return an integer\n def titleToNumber(self, s):\n if s == None:\n return None\n if s == '':\n return None\n for elem in s:\n if elem not in string.uppercase:\n return None\n num = 0\n basis = 26\n base_code = ord('A')\n for i in range(len(s) - 1, -1, -1):\n base = len(s) - 1 - i\n cur_num = ord(s[i]) - base_code + 1\n num += (cur_num * basis**base)\n\n return num\n","sub_path":"TitleToNumber/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"174830823","text":"from typing import Union, Tuple\nimport pandas as pd\nimport pathlib\nimport numpy as np\nimport re\nfrom matplotlib import pyplot as plt\n\nclass QuestionnaireAnalysis:\n \"\"\"\n Reads and analyzes data generated by the questionnaire experiment.\n Should be able to accept strings and pathlib.Path objects.\n \"\"\"\n \n def __init__(self, data_fname: Union[pathlib.Path, str]):\n # ...\n if not isinstance(data_fname, pathlib.Path):\n self.data_fname = pathlib.Path(data_fname)\n else:\n self.data_fname = data_fname\n\n if not self.data_fname.exists():\n raise ValueError\n self.data = pd.DataFrame()\n # read_data()\n \n\n def read_data(self):\n \"\"\"\n Reads the json data located in self.data_fname into memory, to\n the attribute self.data.\n \"\"\"\n # ...\n self.data = pd.read_json(str(self.data_fname))\n return\n \n def show_age_distrib(self) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Calculates and plots the age distribution of the participants.\n Returns a tuple containing two numpy arrays:\n The first item being the number of people in a given bin.\n The second item being the bin edges.\n \"\"\"\n bin_edges = np.array([i*10 for i in range(11)])\n age_series = self.data.age.dropna()\n \n # compute number of people in each bin\n people_in_each_bin = [0 for i in range(10)]\n for age in age_series:\n bin = int(age // 10)\n people_in_each_bin[bin] += 1\n\n # plot histogram\n age_series.hist(bins=bin_edges)\n # TODO: comment-out the next row so that test won't stop\n plt.show()\n return np.array(people_in_each_bin), bin_edges\n\n def remove_rows_without_mail(self) -> pd.DataFrame:\n \"\"\"\n Checks self.data for rows with invalid emails, and removes them.\n Returns the corrected DataFrame, i.e. the same table but with\n the erroneous rows removed and the (ordinal) index after a reset.\n \"\"\"\n df = self.data\n ret = df.loc[df['email'].apply(lambda x:self.validate_email(x))]\n ret.reset_index(inplace=True, drop=True)\n return ret\n\n def validate_email(self, email):\n # filter any email not of the form \"*@*.*\"\n email_regex = re.compile(r\"[^@]+@[^@]+\\.[^@]+\")\n if email_regex.match(email):\n return True\n return False\n\n def fill_na_with_mean(self) -> Union[pd.DataFrame, np.ndarray]:\n \"\"\"\n Finds, in the original DataFrame, the subjects that didn't answer\n all questions, and replaces that missing value with the mean of the\n other grades for that student. Returns the corrected DataFrame,\n as well as the row indices of the students that their new grades\n were generated.\n \"\"\"\n df = self.data\n\n # compute NaN indices\n questions_df = df[['q1', 'q2', 'q3', 'q4', 'q5']]\n df_nan = questions_df.isna()\n df_nan_series =df_nan.any(axis=1) \n rows_with_na = np.where(df_nan_series)[0]\n \n # fill in NaN values\n df[['q1', 'q2', 'q3', 'q4', 'q5']] = df[['q1', 'q2', 'q3', 'q4', 'q5']].apply(lambda row: row.fillna(row.mean()), axis=1)\n\n return df, rows_with_na\n\n def correlate_gender_age(self) -> pd.DataFrame:\n\n idx = self.data.set_index([self.data.index, 'age', 'gender'])\n idx_g = idx.loc[:,'q1' : 'q5']\n idx_g['40_plus'] = idx_g.index.get_level_values(1)>40\n return idx_g.groupby(['gender', '40_plus']).mean()\n\nif __name__ == \"__main__\":\n filename = pathlib.Path(\"C:/Users/Nofar/Desktop/python/hw5/hw5_2019/data.json\")\n qa = QuestionnaireAnalysis(filename)\n qa.read_data()\n\n qa.show_age_distrib()\n\n qa.fill_na_with_mean()\n\n df = qa.remove_rows_without_mail()\n\n qa.correlate_gender_age()\n print(df.email)\n","sub_path":"hw5.py","file_name":"hw5.py","file_ext":"py","file_size_in_byte":3925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"141553135","text":"# convert_gui.py\n# Author: Ashley Soderlund\n# Description: Program convert Celsius to Farenheit using a graphical interface\n\nfrom graphics import *\n\ndef main():\n\n win = GraphWin(\"Celsius Converter\", 400, 300)\n win.setCoords(0.0,0.0,3.0,4.0)\n\n Text(Point(1,3),\" Celsius Temperature: \").draw(win)\n Text(Point(1,1),\"Fahrenheit Temperature: \").draw(win)\n inputText = Entry(Point(2.25, 3),5)\n inputText.setText(\"0.0\")\n inputText.draw(win)\n outputText = Text(Point(2.25,1),\" \")\n outputText.draw(win)\n button = Text(Point(1.5,2.0),\"Convert It\")\n button.draw(win)\n Rectangle(Point(1,1.5), Point(2, 2.25)).draw(win)\n\n win.getMouse()\n\n celsius = float(inputText.getText())\n fahrenheit = 9.0/5.0 * celsius + 32\n\n outputText.setText(round(fahrenheit,2))\n button.setText(\"Quit\")\n\n win.getMouse()\n win.close()\n\nmain()\n","sub_path":"ConvertGUI.py","file_name":"ConvertGUI.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"19623638","text":"#!/usr/bin/env python\n\nimport rospy\nfrom visualization_msgs.msg import Marker\nfrom geometry_msgs.msg import Quaternion, Pose, Point, Vector3\nfrom std_msgs.msg import Header, ColorRGBA\nfrom moveit_msgs.msg import *\nfrom moveit_msgs.srv import *\nimport moveit_commander\n\ndef wait_for_time():\n \"\"\"Wait for simulated time to begin.\n \"\"\"\n while rospy.Time().now().to_sec() == 0:\n pass\n\nif __name__ == '__main__':\n rospy.init_node('my_node')\n wait_for_time()\n\n marker_publisher = rospy.Publisher('visualization_marker', Marker, queue_size=100)\n rospy.sleep(0.5)\n\n marker2 = Marker()\n marker2.header.frame_id = \"base_link\"\n marker2.type = marker2.LINE_STRIP\n marker2.action = marker2.MODIFY\n # marker2.pose = Pose(Point(0, 0, 0), Quaternion(0, 0, 0, 1))\n marker2.scale = Vector3(0.008, 0.009, 0.1)\n marker2.color = ColorRGBA(0.0, 1.0, 0.0, 0.8)\n\n marker2.points = []\n first_point = Point()\n first_point = Point(0, 0, 0)\n marker2.points.append(first_point)\n\n second_point = Point()\n second_point = Point(1, 0, 2)\n marker2.points.append(second_point)\n\n third_point = Point()\n third_point = Point(0, 1, 2)\n marker2.points.append(third_point)\n\n marker_publisher.publish(marker2)\n","sub_path":"moveit_tutorials/doc/move_group_interface/src/publish_marker.py","file_name":"publish_marker.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"616595786","text":"from app.models import User\nfrom . import account,userinterface\nfrom django.http import JsonResponse\nfrom django.db import connection\nimport re\nimport json\n\nclass QueryResultSerializable:\n def __init__(self, fields=None, select_=None):\n self.serializable = {'success':False,'fields':[],'tuples':[]}\n self.select_ = select_ or \"*\"\n if(fields is not None):\n self.set_ordered_fields(fields)\n return\n\n def toJsonResponse(self):\n return JsonResponse(self.serializable, safe=False)\n\n def set_success(self,is_success):\n self.serializable['success']= is_success\n \n def is_success(self):\n return self.serializable['success']\n \n def set_ordered_fields(self,orderedFields):\n self.serializable['fields'] = orderedFields\n \n def get_ordered_fields(self, hide_internal=False):\n fields = self.serializable['fields']\n if(hide_internal):\n fields = [x for x in fields if not x['fieldname'].startswith('_')]\n\n return fields\n\n def select_fields(self, u):\n fields = self.get_ordered_fields()\n result = {}\n for field in fields:\n fieldname = field['fieldname']\n if(fieldname in u):\n result[fieldname] = u[fieldname]\n else:\n result[fieldname] = u[fieldname.upper()]\n if(type(result[fieldname])==bytes):\n result[fieldname] = int.from_bytes(result[fieldname], \"big\")\n return result\n \n def clear_tuples(self):\n self.serializable['tuples'] = []\n \n def get_tuples(self):\n return self.serializable['tuples']\n \n def get_tuple_count(self):\n return len(self.serializable['tuples'])\n\n def do_select(self, from_, where_):\n self.clear_tuples()\n if(len(self.get_ordered_fields())==0):\n self.fetch_fieldnames(from_)\n sql_st = f\"SELECT {self.select_} FROM {from_} WHERE {where_}\"\n sql_st = to_safe_sql_select(sql_st)\n print(sql_st)\n try:\n query_result = None\n with connection.cursor() as cursor:\n cursor.execute(sql_st)\n query_result = dictfetchall(cursor)\n self.set_success(True)\n self.get_tuples().extend([self.select_fields(u) for u in query_result])\n return True\n except:\n self.set_success(False)\n return False\n \n def fetch_fieldnames(self, from_):\n sql_st = f\"SHOW COLUMNS FROM {from_};\"\n sql_st = to_safe_sql_show(sql_st)\n try:\n query_result = None\n with connection.cursor() as cursor:\n cursor.execute(sql_st)\n query_result = dictfetchall(cursor)\n fields = [{'fieldname':u['Field'], 'fieldtype':u['Type']} for u in query_result]\n self.set_ordered_fields(fields)\n return True\n except:\n return False\n \n\ndef create_account(id_,pw_,role_):\n new_user = User(id=id_,role=role_)\n new_user.set_password(pw_)\n new_user.save()\n\ndef dictfetchall(cursor):\n \"Return all rows from a cursor as a dict\"\n columns = [col[0] for col in cursor.description]\n return [\n dict(zip(columns, row))\n for row in cursor.fetchall()\n ]\n\ndef to_safe_sql_select(sql_st):\n sql_st = sql_st+';'\n mat = re.match(\"^SELECT .{0,512}?;\", sql_st)\n return mat.group()\n\ndef to_safe_sql_show(sql_st):\n sql_st = sql_st+';'\n mat = re.match(\"^SHOW .{0,512}?;\", sql_st)\n return mat.group()\n\ndef to_safe_sql_create_table(sql_st):\n sql_st = sql_st+';'\n mat = re.match(\"^CREATE TABLE .{0,512}?;\", sql_st)\n return mat.group()\n\ndef to_safe_sql_identifier(fieldname, prefix=\"dyn17_\"):\n fieldname = fieldname.replace(\" \",\"_\")\n fieldname = fieldname.replace(\"\\n\",\"_\")\n fieldname = prefix+fieldname\n mat = re.match(\"^[a-zA-Z_][a-zA-Z_0-9]{0,32}\", fieldname)\n return mat.group()\n\ndef table_exists(tablename):\n if(tablename is None):\n return False\n tables = connection.introspection.table_names()\n return tablename.lower() in tables\n\ndef get_fields(tablename, hide_internal = False):\n if(not table_exists(tablename)):\n return None\n fields = QueryResultSerializable()\n fields.fetch_fieldnames(tablename)\n return fields.get_ordered_fields(hide_internal)\n\n_allowed_fieldtype = ['text','int','real','date','time']\n\ndef get_available_table_name(tablename):\n basename = to_safe_sql_identifier(tablename)\n tablename = basename\n idx = 0\n while(table_exists(tablename)):\n tablename = f\"{basename}_{idx}\"\n idx = idx+1\n return tablename\n\ndef get_available_task_table_name(tablename):\n basename = to_safe_sql_identifier(tablename)\n tablename = basename\n idx = 0\n while(table_exists(tablename) or table_exists(tablename+\"_wait\")):\n tablename = f\"{basename}_{idx}\"\n idx = idx+1\n return tablename\n\ndef create_table(tablename, fields):\n if(table_exists(tablename)):\n return False\n sql_var_definition = \"_id_auto_increment int auto_increment, primary key(_id_auto_increment)\"\n\n for i in range(0,len(fields)):\n fields[i]['fieldname'] = to_safe_sql_identifier(fields[i]['fieldname'],\"\")\n fields[i]['fieldtype'] = fields[i]['fieldtype'].lower()\n if(fields[i]['fieldtype'] not in _allowed_fieldtype):\n fields[i]['fieldtype'] = _allowed_fieldtype[0]\n sql_var_definition = sql_var_definition + f\", {fields[i]['fieldname']} {fields[i]['fieldtype']}\"\n \n sql_create = to_safe_sql_create_table(f\"CREATE TABLE {tablename}({sql_var_definition});\")\n try:\n with connection.cursor() as cursor:\n cursor.execute(sql_create)\n return True\n except:\n return False\n\ndef select_from_where(from_, where_=\"TRUE\", fields=None, select_=None):\n tuples = QueryResultSerializable(fields,select_)\n if(fields is None):\n tuples.fetch_fieldnames(from_)\n \n tuples.do_select(from_,where_)\n return tuples\n\ndef get_count(table_name):\n tuples = select_from_where(table_name)\n return tuples.get_tuple_count()\n\n\ndef to_fields(fieldnames):\n return [{'fieldname':x} for x in fieldnames]","sub_path":"app/utils/dbinterface.py","file_name":"dbinterface.py","file_ext":"py","file_size_in_byte":6224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"608633519","text":"'''\n OBJECTIVE\n Given a complex mesh with animation controls, the program by UI allow:\n\t- to reset changes to the original state\n\t- to save the current state of changes\n\t- to reload changes previously saved\n'''\n\n\nimport maya.cmds as cmds\nimport time\nimport datetime\nfrom collections import OrderedDict\n\n#############################################################\n######### FEATURE: RESET STATE #############################\n#############################################################\ndef reset_attribs(obj):\n #attributi base\n defaultAttrs = cmds.listAttr(obj, keyable=True)\n if defaultAttrs == None: return\n for eachAttr in defaultAttrs:\n if (eachAttr.startswith(\"translate\") or\n eachAttr.startswith(\"rotate\") ):\n cmds.setAttr(obj+\".\"+eachAttr, 0)\n elif eachAttr.startswith(\"scale\"):\n cmds.setAttr(obj+\".\"+eachAttr, 1)\n \n #attributi user defined\n userAttrs = cmds.listAttr(obj, keyable=True, userDefined=True)\n if userAttrs == None: return\n for eachAttr in userAttrs:\n pointer = obj+\".\"+eachAttr\n defaultValue = cmds.addAttr(pointer, query=True,defaultValue=True)\n cmds.setAttr(pointer, defaultValue)\n\ndef reset_controls(): \n ctrls = cmds.ls(['*_ac_*','*_fk_*'], type='nurbsCurve' )\n \n for each_ctrl in ctrls:\n ctrl_parent = cmds.listRelatives(each_ctrl, parent=True)[0]\n reset_attribs(ctrl_parent) \n\n CONTROL_STATES = OrderedDict()\n\n\n\n#############################################################\n######### FEATURE: SAVE STATE ##############################\n#############################################################\ndef save_attribs(obj, state):\n #attributi base\n defaultAttrs = cmds.listAttr(obj, keyable=True)\n if defaultAttrs == None: return\n for eachAttr in defaultAttrs:\n if (eachAttr.startswith(\"translate\") or\n eachAttr.startswith(\"rotate\") or\n eachAttr.startswith(\"scale\") ):\n key = obj+\".\"+eachAttr\n val = cmds.getAttr(key)\n state[key] = val\n #attributi user defined\n userAttrs = cmds.listAttr(obj, keyable=True, userDefined=True)\n if userAttrs == None: return\n for eachAttr in userAttrs:\n key = obj+\".\"+eachAttr\n val = cmds.getAttr(key)\n state[key] = val\n\nCONTROL_STATES = OrderedDict()\ndef save_controls(label): \n ctrls = cmds.ls(['*_ac_*','*_fk_*'], type='nurbsCurve' )\n \n state = {}\n for each_ctrl in ctrls:\n ctrl_parent = cmds.listRelatives(each_ctrl, parent=True)[0]\n save_attribs(ctrl_parent, state) \n CONTROL_STATES[label] = state\n \n#############################################################\n######### FEATURE: LOAD STATE ##############################\n#############################################################\ndef load_controls(aState): \n selectedState = CONTROL_STATES[aState];\n \n for key in selectedState.iterkeys():\n val = selectedState[key]\n cmds.setAttr(key, val)\n \n \n\n#############################################################\n######### FEATURE: UI #################################\n#############################################################\ndef main(): \n cmds.window(title='Zoma Controls')\n \n cmds.columnLayout()\n cmds.button(label='Reset State', command=reset_listener)\n cmds.button(label='Save State', command=save_listener) \n cmds.setParent('..')\n \n cmds.rowLayout(numberOfColumns=2)\n cmds.optionMenu('state_list', label='Load State', changeCommand=load_listener)\n for each in CONTROL_STATES.iterkeys():\n cmds.menuItem( label=each)\n #cmds.button(label='Load', command=load_listener)\n cmds.setParent('..')\n \n cmds.showWindow()\n \ndef save_listener(*args):\n ts = time.time()\n st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')\n save_controls(st)\n cmds.menuItem(label=st, parent='state_list')\n \ndef load_listener(*args):\n selected = cmds.optionMenu('state_list', query=True, value=True)\n load_controls(selected)\n\ndef reset_listener(*args):\n menuItems = cmds.optionMenu('state_list', query=True, itemListLong=True)\n if menuItems:\n cmds.deleteUI(menuItems) \n reset_controls()\n\n#############################################################\n######### TESTING #######################################\n#############################################################\ndef clean(): \n cmds.select(all=True)\n cmds.delete()\n\ndef scenario01():\n cmds.file('C:\\\\_fdf\\\\projects\\\\workspace_aiv\\\\lessons\\\\LEZ47_20180424_MAYA_3_MEL\\\\model__zoma_hi_base_vanilla_rig_v6.ma',open=True, newFile=False, force=True)\n \n ts = time.time()\n st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')\n save_controls(st);\n \n cmds.setAttr(\"zoma_ac_lf_footik.rotateY\", 45)\n ts+=1\n st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')\n save_controls(st);\n \n cmds.setAttr(\"zoma_fk_rt_shoulder.rotateY\", 45)\n ts+=1\n st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')\n save_controls(st);\n\n\nCONTROL_STATES=OrderedDict() \nscenario01()\n\nmain()\n\nclean()\n","sub_path":"py-scripts/02_ui-zuma-reset-load-save.py","file_name":"02_ui-zuma-reset-load-save.py","file_ext":"py","file_size_in_byte":5252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"116149036","text":"\nfrom model import Deck\n\nfrom view import Terminal_Viewer\n\nfrom controller import Dealer, Human_Player, Computer_Opponent, Turn_Result\n\nfrom helpers import get_bool\n\nimport time\n\n\ndef play_racko():\n\n # instantiate objects needed to play\n deck = Deck()\n\n dealer = Dealer()\n\n view = Terminal_Viewer()\n\n player_1 = Human_Player(view)\n player_2 = Computer_Opponent(view)\n\n view.add_deck(deck)\n view.add_human_rack(player_1.rack)\n view.add_computer_rack(player_2.rack)\n\n # shuffle deck, draw cards to see who goes first, shuffle again\n dealer.shuffle(deck)\n\n player_1_draw = deck.take_card_from_draw_pile()\n player_2_draw = deck.take_card_from_draw_pile()\n\n if (player_1_draw > player_2_draw):\n active_player = player_1\n else:\n active_player = player_2\n\n deck.place_card_on_draw_pile(player_1_draw)\n deck.place_card_on_draw_pile(player_2_draw)\n\n dealer.shuffle(deck)\n\n # greet the user\n view.update_text_field('Welcome to Rack-O, the worst game in the world!!!')\n player_1.press_enter_to_continue()\n\n view.update_text_field('Drawing cards to see who goes first...')\n player_1.press_enter_to_continue()\n\n view.update_text_field('Player {} goes first.'.format('1' if active_player == player_1 else '2'))\n player_1.press_enter_to_continue()\n\n view.update_text_field('Shuffling deck.')\n player_1.press_enter_to_continue()\n\n deck.place_card_on_discard_pile(deck.take_card_from_draw_pile())\n\n view.update_deck_field()\n\n # deal out 10 cards to each player\n while (player_1.rack.is_not_full() or player_2.rack.is_not_full()):\n dealer.deal_card(deck, player_1)\n time.sleep(.3)\n view.update_human_player_rack()\n view.render()\n dealer.deal_card(deck, player_2)\n\n # play the game\n while True:\n view.update_deck_field()\n view.update_human_player_rack()\n view.render()\n\n if (active_player.play_turn(deck) == Turn_Result.RACKO): # <- all the playing happens on this line\n view.update_deck_field()\n view.update_human_player_rack()\n view.update_text_field('RACK-O!!!')\n\n if (active_player == player_1):\n view.append_to_text_field('You won, but at what cost?!?')\n else:\n view.append_to_text_field(\"Your best efforts have been found lacking. Ensconce thineself upon the throne of decrepitude, saucy wastrel!\")\n\n view.render()\n player_1.press_enter_to_continue()\n\n view.update_text_field('Do you want to play again? (y or n) ')\n view.render()\n\n if (not get_bool()):\n view.update_text_field('Begone!')\n view.render()\n player_1.press_enter_to_continue()\n quit()\n\n # swap players between turns\n if (active_player == player_1):\n active_player = player_2\n else:\n active_player = player_1\n\n view.update_deck_field()\n view.update_human_player_rack()\n view.render()\n\n\nif __name__ == '__main__':\n play_racko()\n","sub_path":"games/racko/Racko.py","file_name":"Racko.py","file_ext":"py","file_size_in_byte":3120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"46655077","text":"import datetime\nimport usb.core # https://github.com/pyusb/pyusb\nimport struct\nimport os\n\n\ndef usb_safe_cleanup(dev,interface):\n try:\n usb.util.release_interface(dev,interface)\n usb.util.dispose_resources(dev)\n except Exception as e: \n print(e,' failure in usb_safe_cleanup')\n return False\n return True\n \n\n\n#====================================================================\ndef lb_set():\n \"\"\"\n Set Leo Bodnar into a mode where it reports nav-data packets.\n Returns True for success, False for error.\n \"\"\"\n\n status = False\n VENDOR_LB = 0x1DD2 # Leo Bodnar's Vendor ID\n PRODUCT_MGPS = 0x2211 # Mini GPS product ID\n CONFIGURATION_MGPS = 0 # 1-based\n INTERFACE_MGPS = 0 # 0-based\n SETTING_MGPS = 0 # 0-based\n ENDPOINT_MGPS = 0 # 0-based\n\n\n # Magic command to set the LB, courtesy of Simon\n buffer = [8, 6, 1, 8, 0, 0x01, 0x07, 10]\n \n dev = usb.core.find(idVendor=VENDOR_LB, idProduct=PRODUCT_MGPS)\n \n if dev is None:\n print(\"lb_set: failed to find USB device\")\n return status\n \n desconfig = dev[0] #desired config\n\n try:\n dev.reset()\n except:\n print(\"lb_set: failed to reset device\")\n return status\n \n #linux only command to detach kernal:\n try:\n \tif dev.is_kernel_driver_active(INTERFACE_MGPS):\n \t\tdev.detach_kernel_driver(INTERFACE_MGPS)\n except:\n \tprint(\"lb_set: failed to detach kernel driver\")\n \treturn status\n try:\n configuration = dev.get_active_configuration()\n except:\n print(\"lb_set: failed to get configuration\")\n return status\n \n interface = configuration[(INTERFACE_MGPS, SETTING_MGPS)]\n endpoint = interface[ENDPOINT_MGPS]\n \n try:\n usb.util.claim_interface(dev, interface)\n except:\n print(\"lb_set: failed to claim interface\")\n return status\n \n if configuration.bConfigurationValue != desconfig.bConfigurationValue:\n try:\n dev.set_configuration(desconfig)\n except:\n print(\"lb_set: failed to set configuration\")\n #usb.util.release_interface(dev, interface)\n #usb.util.dispose_resources(dev)\n usb_safe_cleanup(dev,interface)\n return status\n \n try:\n ret = dev.ctrl_transfer(0x21, 9, 0x0300, 0, buffer) # ret should be 8\n usb.util.release_interface(dev, interface)\n usb.util.dispose_resources(dev)\n except:\n print(\"lb_set: failed to write to device\")\n #usb.util.release_interface(dev, interface)\n #usb.util.dispose_resources(dev)\n usb_safe_cleanup(dev,interface)\n return status\n\n status = True\n return status\n\n#====================================================================\ndef lb_read(ntry=1000, timeout=1000):\n \"\"\"\n Read GPS time stamp from Leo Bodnar.\n\n ntry: maximum number of read attempts to find nav-data\n timeout: USB read timeout in milliseconds\n\n Returns Linux timestamp, (precision, validity, lon, lat, alt), and datetime object tuple\n \"\"\"\n\n tstamp = None\n auxdat = None\n gpstime = None\n \n VENDOR_LB = 0x1DD2 # Leo Bodnar's Vendor ID\n PRODUCT_MGPS = 0x2211 # Mini GPS product ID\n CONFIGURATION_MGPS = 0 # 1-based\n INTERFACE_MGPS = 0 # 0-based\n SETTING_MGPS = 0 # 0-based\n ENDPOINT_MGPS = 0 # 0-based\n \n dev = usb.core.find(idVendor=VENDOR_LB, idProduct=PRODUCT_MGPS)\n \n if dev is None:\n print(\"lb_read: failed to find USB device\")\n return tstamp, auxdat, gpstime\n \n desconfig = dev[0] #desired config\n \n #linux only command to detach kernal:\n try:\n \tif dev.is_kernel_driver_active(INTERFACE_MGPS):\n \t\tdev.detach_kernel_driver(INTERFACE_MGPS)\n except:\n \tprint(\"lb_read: failed to detach kernel driver\")\n \treturn tstamp, auxdat, gpstime\n try:\n configuration = dev.get_active_configuration()\n except:\n print(\"lb_read: failed to get configuration\")\n return tstamp, auxdat, gpstime\n \n interface = configuration[(INTERFACE_MGPS, SETTING_MGPS)]\n endpoint = interface[ENDPOINT_MGPS]\n \n try:\n usb.util.claim_interface(dev, interface)\n except:\n print(\"lb_read: failed to claim interface\")\n return tstamp, auxdat, gpstime\n\n if configuration.bConfigurationValue != desconfig.bConfigurationValue:\n try:\n dev.set_configuration(desconfig)\n except:\n print(\"lb_read: failed to set configuration\")\n #usb.util.release_interface(dev, interface)\n #usb.util.dispose_resources(dev)\n usb_safe_cleanup(dev,interface)\n return tstamp, auxdat, gpstime \n\n packet = None\n nhead = 4\n offset1 = 10\n offset2 = 46\n \n for j in range(ntry):\n try:\n data = dev.read(0x81, 64, timeout=timeout)\n usb.util.release_interface(dev, interface)\n usb.util.dispose_resources(dev)\n except Exception as e:\n print(\"lb_read: read error\")\n print(e)\n #usb.util.release_interface(dev, interface)\n #usb.util.dispose_resources(dev)\n usb_safe_cleanup(dev,interface)\n lb_set()\n return tstamp, auxdat, gpstime\n \n if len(data) < nhead:\n continue\n # Look for nav-pvt packet somewhere in the line\n for i in range(len(data)-nhead):\n # Look for nav-pvt packet somewhere in the line\n # Skip the bytes for packet id, class id, length, and gps time of week of the nav epoch\n if data[i:i+nhead].tolist() == [0xb5, 0x62, 0x01, 0x07]:\n # Check if nav-pvt packet appears too close to the end\n if len(data) < i+offset2:\n break\n # ...otherwise snarf the bits we care about\n packet = data[i+offset1:i+offset2]\n break\n if packet:\n break\n if packet is None:\n print(\"lb_read: read failed\")\n #usb.util.release_interface(dev, interface)\n #usb.util.dispose_resources(dev)\n usb_safe_cleanup(dev,interface)\n lb_set()\n return tstamp, auxdat, gpstime\n\n try:\n year = struct.unpack('>>:\")\n\n# 判断是否存在该城市\nwhile True:\n if choise in version:\n if choise == 'q':\n break\n\n # 打印当前选项��子城市\n printPlace(version[choise])\n # 输入二级城市\n choise2 = input(\"请继续输入想去的地方:\")\n if choise2 == 'q':\n break\n if choise2 in version[choise]:\n # 输入三级城市\n printPlace(version[choise][choise2]) # 北京,昌平\n choise3 = input(\"请继续输入三级城市>>>:\")\n if choise3 == 'q':\n break\n if choise3 in version[choise][choise2]:\n printPlace(version[choise][choise2][choise3])\n i = input(\"您是否想要退出?是 | 否>>>:\")\n if i == \"是\":\n break\n","sub_path":"day5/景点.py","file_name":"景点.py","file_ext":"py","file_size_in_byte":1911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"472766640","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Feb 11 16:16:56 2019\r\n\r\n@author: Ruifan\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib as mpl\r\nfrom matplotlib import pyplot as plt\r\n\r\nfrom draft_frequency_by_position import df\r\nfrom fcns import playerValueAvgGame\r\n\r\n\r\n###Fill in NaN stats with 0\r\ntoFill = ['G', 'GS', 'QBrec', 'Cmp', 'PaAtt', 'PaYds', 'PaTD', 'PaInt', 'RuAtt', 'RuYds', 'RuTD', 'Rec', 'RecYds', 'RecTD', 'Int', 'Sk' ]\r\nfor i in toFill:\r\n df[i] = df[i].fillna(0)\r\n\r\n###Populate player value column\r\ndf['playerValue'] = df.apply(lambda row: playerValueAvgGame(row['PaYds'], row['PaTD'], row['PaInt'], row['RuYds'], row['RuTD'], row['RecYds'], row['RecTD'], \r\n row['G'], row['GS']), axis = 1)\r\n\r\n##Divide into respective positions\r\ndfQB = df[df['Pos'] == 'QB']\r\ndfQB1 = df[(df['Pos'] == 'QB') & (df['Year'] >= 1985) & (df['Year'] <= 1993)]\r\ndfQB2 = df[(df['Pos'] == 'QB') & (df['Year'] >= 1994) & (df['Year'] <= 2002)]\r\ndfQB3 = df[(df['Pos'] == 'QB') & (df['Year'] >= 2003) & (df['Year'] <= 2011)]\r\ndfQB4 = df[(df['Pos'] == 'QB') & (df['Year'] >= 2012) & (df['Year'] <= 2018)]\r\n\r\ndfRB = df[df['Pos'] == 'RB']\r\ndfRB1 = df[(df['Pos'] == 'RB') & (df['Year'] >= 1985) & (df['Year'] <= 1993)]\r\ndfRB2 = df[(df['Pos'] == 'RB') & (df['Year'] >= 1994) & (df['Year'] <= 2002)]\r\ndfRB3 = df[(df['Pos'] == 'RB') & (df['Year'] >= 2003) & (df['Year'] <= 2011)]\r\ndfRB4 = df[(df['Pos'] == 'RB') & (df['Year'] >= 2012) & (df['Year'] <= 2018)]\r\n\r\ndfWR = df[df['Pos'] == 'WR']\r\ndfWR1 = df[(df['Pos'] == 'WR') & (df['Year'] >= 1985) & (df['Year'] <= 1993)]\r\ndfWR2 = df[(df['Pos'] == 'WR') & (df['Year'] >= 1994) & (df['Year'] <= 2002)]\r\ndfWR3 = df[(df['Pos'] == 'WR') & (df['Year'] >= 2003) & (df['Year'] <= 2011)]\r\ndfWR4 = df[(df['Pos'] == 'WR') & (df['Year'] >= 2012) & (df['Year'] <= 2018)]\r\n\r\n\r\n\r\n\r\ndef getPlayerZScore(df):\r\n stdev = df['playerValue'].std()\r\n mean = df['playerValue'].mean()\r\n df['z_score'] = (df['playerValue'] - mean)/stdev\r\n return;\r\n \r\n###Populates player z score column \r\nfor i in [dfQB, dfQB1, dfQB2, dfQB3, dfQB4, dfRB, dfRB1, dfRB2, dfRB3, dfRB4, dfWR, dfWR1, dfWR2, dfWR3, dfWR4]:\r\n getPlayerZScore(i)\r\n\r\n\r\ndef avgZScore(df, rnd):\r\n df_rnd = df[df['Rnd'] == rnd]\r\n return df_rnd['z_score'].mean()\r\n\r\n#print(\"Overall for QBs, RBs, and WRs\")\r\n#for i in [dfQB, dfRB, dfWR]:\r\n# for j in range(1,8):\r\n# print('Z-score for player chosen in round {}: {}'.format(j, avgZScore(i, j)))\r\n#print('\\n')\r\n#\r\n#print(\"QBs, starting from the most recent era\")\r\n#for i in [dfQB4, dfQB3, dfQB2, dfQB1]:\r\n# for j in range(1,8):\r\n# print('Z-score for player chosen in round {}: {}'.format(j, avgZScore(i, j)))\r\n#print('\\n')\r\n#\r\n#print(\"RBs, starting from the most recent era\")\r\n#for i in [dfRB4, dfRB3, dfRB2, dfRB1]:\r\n# for j in range(1,8):\r\n# print('Z-score for player chosen in round {}: {}'.format(j, avgZScore(i, j)))\r\n#print('\\n')\r\n# \r\n#print(\"WRs, starting from the most recent era\")\r\n#for i in [dfWR4, dfWR3, dfWR2, dfWR1]:\r\n# for j in range(1,8):\r\n# print('Z-score for player chosen in round {}: {}'.format(j, avgZScore(i, j)))\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 \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 ","sub_path":"position_value_by_round.py","file_name":"position_value_by_round.py","file_ext":"py","file_size_in_byte":3472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"393915103","text":"import csv\nimport numpy as np\n\nclass data_reader:\n\n def read(self, dir='vali_data_rev.csv'):\n print('loading ',dir,'...')\n reviews = []\n self.lengths = []\n self.ratings = []\n with open(dir, 'r') as f:\n reader = csv.reader(f, delimiter=',')\n for line in reader:\n id = line[0]\n size = line[1]\n rating = line[2]\n if id != '':\n self.lengths.append(int(size))\n self.ratings.append(int(rating)-1)\n reviews.append(line[3:])\n self.data = np.zeros((len(self.lengths), 100, 300))\n for i in range(len(self.lengths)):\n self.data[i, :] = reviews[i*100: (i+1)*100]\n self.lengths = np.array(self.lengths)\n self.ratings = np.array(self.ratings)\n one_hot = np.zeros((self.ratings.shape[0], 5))\n for i in range(len(self.ratings)):\n one_hot[i, self.ratings[i]] = 1\n self.ratings = one_hot\n\n def next_batch(self, batch_size=10, whole=False):\n if whole == False:\n new_indices = np.random.permutation(self.data.shape[0])\n new_indices = new_indices[:batch_size]\n return self.data[new_indices, :], self.ratings[new_indices], self.lengths[new_indices]\n else:\n return self.data, self.ratings\n\n\n\n# reader = data_reader()\n# reader.read()\n# data, rating, length = reader.next_batch()\n# print(rating, length)\n# data, rating, length = reader.next_batch()\n# print(rating, length)\n# data, rating, length = reader.next_batch()\n# print(rating, length)\n\n\n# a = np.array([[1,2,3],[4,2,3]])\n# b = [0,1]\n# print(a[:,b])\n\n\n\n\n\n","sub_path":"preprocessing/read_data.py","file_name":"read_data.py","file_ext":"py","file_size_in_byte":1691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"299535131","text":"import pandas as pd\nimport numpy as np\nfrom torch.utils.data import Dataset, DataLoader\nfrom sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.feature_selection import SelectFromModel\nfrom sklearn.metrics import confusion_matrix\n\ndef load_data(file_name=\"data.csv\"):\n \n df = pd.read_csv(file_name)\n \n header_x = ['Spherical Degree', 'Cylindrical Degree', 'Axial', 'Brand', 'FK', 'TP', 'DIA', 'Flat K', 'Steep K', '∆K', 'Flat e', 'Steep e', 'Emeam', 'BFS', 'Sag Differential at 8 mm', 'F Weighted AVE']\n \n \n #header_x = ['Spherical Degree', 'Cylindrical Degree', 'Brand', 'FK', 'TP', 'DIA', 'Steep K', '∆K', 'Emeam', 'BFS', 'Sag Differential at 8 mm', 'F Weighted AVE']\n \n header_y = [\"Brand\", \"FK\", \"TP\", \"DIA\"]\n for y in header_y:\n header_x.remove(y)\n x = df[header_x].to_numpy()\n y = df[header_y].to_numpy()\n y[y==\"ED\"] = 0\n y[y==\"DL\"] = 1\n \n for i in range(len(x)):\n \n for j in range(len(x[i])):\n x[i][j] = float(x[i][j])\n for i in range(len(y)):\n for j in range(len(y[i])):\n y[i][j] = float(y[i][j])\n a = 0\n b = 0\n c = 0\n \n for i in range(len(x)):\n flat_k = int(x[i][3]) + np.around(( x[i][3]-int(x[i][3]) )/0.125)*0.125 #int(predict_y[i]) + np.around( ( predict_y[i]-int(predict_y[i]) )/0.125 )*0.125\n FK = y[i][1]\n #FK = int(FK) + np.around(( FK-int(FK) )/0.125)*0.125\n TP = x[i][0] + 0.5*x[i][1]\n DIA = y[i][3]\n if abs(TP - y[i][2]) <=0.125:\n b+=1\n #else:\n #print(TP, y[i][2])\n y[i][1] = x[i][3] - y[i][1]\n #y[i][3] = 10.6 - y[i][3]\n if abs(flat_k - FK) <=0.125:\n a+=1\n if abs(DIA - 10.6) <=0.2:\n c+=1\n \n y = y.astype(np.float)\n '''\n print(a/len(y))\n print(b/len(y))\n print(c/len(y))\n print(np.sum(y[:,0])/len(y))\n print(y.shape)\n '''\n #exit()\n LR = LinearRegression()\n LR.fit(x, y[:,1])\n #print(LR.score(x,y[:,1]))\n #print(LR.coef_)\n DT = DecisionTreeRegressor()\n DT.fit(x, y[:, 1])\n #print(sum(y - clf.predict(x)))\n #print(clf.predict(x)[:5])\n #print(y[:5])\n impt = DT.feature_importances_\n indices = np.argsort(impt)[::-1]\n '''\n print(DT.feature_importances_)\n print(indices)\n print(np.array(header_x)[indices])\n '''\n #exit()\n valid_split = 0.2 #0.1\n seed = 87\n indices = list(range(len(x)))\n split = int(np.floor(valid_split * len(x)))\n np.random.seed(seed)\n np.random.shuffle(indices)\n \n train_indices, valid_indices = indices[split:], indices[:split]\n train_x, train_y = x[train_indices], y[train_indices]\n valid_x, valid_y = x[valid_indices], y[valid_indices]\n max_acc = 0\n '''\n for d in range(1, 5):\n for n in range(1, 200):\n gbr = GradientBoostingClassifier(n_estimators=n, max_depth=d, min_samples_split=2, learning_rate=0.1, verbose=0, validation_fraction=0)\n gbr.fit(train_x, train_y[:, 0])\n if gbr.score(valid_x, valid_y[:, 0]) > max_acc:\n max_acc = gbr.score(valid_x, valid_y[:, 0])\n print(n, d, gbr.score(train_x, train_y[:, 0]), gbr.score(valid_x, valid_y[:, 0]))\n exit()\n '''\n gbr = GradientBoostingClassifier(n_estimators=14, max_depth=3, min_samples_split=2, learning_rate=0.1, verbose=0, validation_fraction=0.1)\n gbr.fit(train_x, train_y[:, 0])\n '''\n print(gbr.score(train_x, train_y[:, 0]), gbr.score(valid_x, valid_y[:, 0]), gbr.score(x, y[:, 0]))\n # print(gbr.predict(train_x)[:5], train_y[:5, 0])\n print(confusion_matrix(gbr.predict(train_x), train_y[:, 0]))\n print(confusion_matrix(gbr.predict(valid_x), valid_y[:, 0]))\n print(confusion_matrix(gbr.predict(x), y[:, 0]))\n impt = gbr.feature_importances_\n #print(impt)\n #exit()\n indices = np.argsort(impt)[::-1]\n print(np.array(header_x)[indices])\n '''\n return x, y\n\n\n\nclass TrainingDataset(Dataset):\n def __init__(self, normalize=False):\n x, y = load_data()\n if normalize:\n self.x_mean = np.mean(x, axis=0)\n self.x_std = np.std(x, axis=0)\n x = (x-self.x_mean)/self.x_std\n self.x = x\n self.y = y#reshape(-1, 1)\n self.l = len(self.x)\n\n #print(x_std)\n\n \n def __getitem__(self, index):\n return self.x[index], self.y[index]\n \n def __len__(self):\n return self.l\n#load_data()\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"39669126","text":"from crate import client\n\n\n#connection = client.connect(\"http://192.168.1.101:4200\", username=\"crate\")\n#cursor = connection.cursor()\n#query = \"CREATE TABLE TH_DATA (MAC_ADD TEXT PRIMARY KEY, TIME timestamp PRIMARY KEY, TEMPERATURE float, HUMIDITY float) WITH (number_of_replicas = 1)\"\n#cursor.execute(query)\n#cursor.close()\n#connection.close()\n\ndef InsertDB(mac_add, time, temperature, humidity):\n query = \"INSERT INTO TH_DATA (MAC_ADD, TIME, TEMPERATURE, HUMIDITY) VALUES ('{}','{}','{}','{}')\".format(mac_add,time,temperature, humidity)\n try:\n connection = client.connect(\"http://localhost:4200\", username=\"crate\")\n cursor = connection.cursor()\n cursor.execute(query)\n cursor.close()\n connection.close()\n except Exception as e:\n print (\"Error: \" + e)\n\n","sub_path":"dbHandler.py","file_name":"dbHandler.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"517968636","text":"import os\nfrom os import listdir\nfrom os.path import isfile, join\nfrom glob import glob\nimport cv2\nimport numpy as np\nimport scipy.misc\nfrom matplotlib import pyplot as plt\n\ndef get_sub_dir(path, ignore=[]):\n sub_directories = []\n list_sub_dir = listdir(path)\n # Removes folder which is in ignore\n for i in ignore:\n list_sub_dir.remove(i)\n \n for sub_dir in list_sub_dir:\n sub_directories.append(glob(os.path.join(path + \"/\" + sub_dir, \"*.jpg\")))\n \n return sub_directories\n\ndef calulate_mean(path_training_img, ignore=[], height=224, width=224):\n mean_img = np.zeros((width, height, 3), dtype=\"float32\")\n numbers_img = 0\n \n sub_dirs = get_sub_dir(path_training_img, ignore)\n\n for sub in sub_dirs:\n for img in sub:\n temp_img = cv2.cvtColor(cv2.imread(img),cv2.COLOR_BGR2RGB)\n mean_img += cv2.resize(temp_img, (width,height), interpolation=cv2.INTER_CUBIC)\n numbers_img += 1\n \n return (mean_img/numbers_img)\n\n##### TEST ####### Calculate mean pr. channel over all pictures\n\ndef calculate_mean_keras(x):\n mean = np.mean(x, axis=(0, 1, 2))\n broadcast_shape = [1, 1, 1]\n broadcast_shape[3 - 1] = x.shape[3]\n mean = np.reshape(mean, broadcast_shape)\n return mean\n\n#################\n\ndef images_to_numpy(images_pot, images_cat, images_tab):\n x = []\n y = []\n \n width = 224\n height = 224\n \n for img_pot in images_pot:\n true_color_img = cv2.cvtColor(cv2.imread(img_pot),cv2.COLOR_BGR2RGB)\n x.append(cv2.resize(true_color_img, (width,height), interpolation=cv2.INTER_CUBIC))\n y.append(0)\n for img_cat in images_cat:\n true_color_img = cv2.cvtColor(cv2.imread(img_cat),cv2.COLOR_BGR2RGB)\n x.append(cv2.resize(true_color_img, (width,height), interpolation=cv2.INTER_CUBIC))\n y.append(1)\n for img_tab in images_tab:\n true_color_img = cv2.cvtColor(cv2.imread(img_tab),cv2.COLOR_BGR2RGB)\n x.append(cv2.resize(true_color_img, (width,height), interpolation=cv2.INTER_CUBIC))\n y.append(2)\n return np.asarray(x), np.asarray(y)\n\ndef images_to_numpy_full_class(image_path, ignore=[], height=224, width=224):\n x = []\n y = []\n\n sub_dirs = get_sub_dir(image_path, ignore)\n for label, classes in enumerate(sub_dirs):\n for img in classes:\n true_color_img = cv2.cvtColor(cv2.imread(img),cv2.COLOR_BGR2RGB)\n x.append(cv2.resize(true_color_img, (width,height), interpolation=cv2.INTER_CUBIC))\n y.append(label)\n x = np.asarray(x)\n x = np.float32(x)\n return x, y\n\ndef images_import(images_pot, images_cat, images_tab):\n x = []\n for img_pot in images_pot:\n x.append(plt.imread(img_pot))\n for img_cat in images_cat:\n x.append(plt.imread(img_cat))\n for img_tab in images_tab:\n x.append(plt.imread(img_tab))\n return np.asarray(x)\n\ndef make_images_mean(X_train, path_from, path_to):\n mean_image = np.mean(X_train, axis=0)\n \n # Imports picture path\n test_pot = glob(os.path.join((path_from + \"/test/potato\"),\"*.jpg\"))\n test_cat = glob(os.path.join((path_from + \"/test/catfood\"),\"*.jpg\"))\n test_tab = glob(os.path.join((path_from + \"/test/table\"), \"*.jpg\"))\n \n train_pot = glob(os.path.join((path_from + \"/train/potato\"),\"*.jpg\"))\n train_cat = glob(os.path.join((path_from + \"/train/catfood\"),\"*.jpg\"))\n train_tab = glob(os.path.join((path_from + \"/train/table\"), \"*.jpg\"))\n \n valid_pot = glob(os.path.join((path_from + \"/valid/potato\"),\"*.jpg\"))\n valid_cat = glob(os.path.join((path_from + \"/valid/catfood\"),\"*.jpg\"))\n valid_tab = glob(os.path.join((path_from + \"/valid/table\"), \"*.jpg\"))\n\n for index, img in enumerate(test_pot):\n img = plt.imread(img) - mean_image\n scipy.misc.imsave(path_to+\"/test/potato/potato\"+str(index)+\".jpg\", img)\n for index, img in enumerate(test_cat):\n img = plt.imread(img) - mean_image\n scipy.misc.imsave(path_to+\"/test/catfood/catfood\"+str(index)+\".jpg\", img)\n for index, img in enumerate(test_tab):\n img = plt.imread(img) - mean_image\n scipy.misc.imsave(path_to+\"/test/table/table\"+str(index)+\".jpg\", img)\n \n for index, img in enumerate(train_pot):\n img = plt.imread(img) - mean_image\n scipy.misc.imsave(path_to+\"/train/potato/potato\"+str(index)+\".jpg\", img)\n for index, img in enumerate(train_cat):\n img = plt.imread(img) - mean_image\n scipy.misc.imsave(path_to+\"/train/catfood/catfood\"+str(index)+\".jpg\", img)\n for index, img in enumerate(train_tab):\n img = plt.imread(img) - mean_image\n scipy.misc.imsave(path_to+\"/train/table/table\"+str(index)+\".jpg\", img)\n \n for index, img in enumerate(valid_pot):\n img = plt.imread(img) - mean_image\n scipy.misc.imsave(path_to+\"/valid/potato/potato\"+str(index)+\".jpg\", img)\n for index, img in enumerate(valid_cat):\n img = plt.imread(img) - mean_image\n scipy.misc.imsave(path_to+\"/valid/catfood/catfood\"+str(index)+\".jpg\", img)\n for index, img in enumerate(valid_tab):\n img = plt.imread(img) - mean_image\n scipy.misc.imsave(path_to+\"/valid/table/table\"+str(index)+\".jpg\", img)\n return mean_image, plt.imread(train_pot[0])\n \n# Downscales and convert image from BGR to RGB into a array\ndef images_to_arr(images):\n x = []\n width = 224\n height = 224\n \n for img in images:\n true_color_img = cv2.cvtColor(cv2.imread(img),cv2.COLOR_BGR2RGB)\n x.append(cv2.resize(true_color_img, (width,height), interpolation=cv2.INTER_CUBIC))\n return x # Makes to numpy array\n\ndef get_data(x_kar, x_kat, x_bord, y_kar=0, y_kat=1, y_bord=2, \n num_training=205, num_validation=100, num_test=100):\n X_total = []\n y_total = []\n \n for kar in x_kar:\n X_total.append(kar)\n y_total.append(y_kar)\n for kat in x_kat:\n X_total.append(kat)\n y_total.append(y_kat)\n for bord in x_bord:\n X_total.append(bord)\n y_total.append(y_bord)\n X_total = np.asarray(X_total) # Make a numpy array\n y_total = np.asarray(y_total)\n X_total = X_total.astype(float)\n X_total = np.divide(X_total,255)\n # Generate X_total.shape[0] num from X_total.shape[0]\n mask = np.random.choice(X_total.shape[0], X_total.shape[0], replace=True) \n mask_train = mask[0:num_training]\n mask_val = mask[num_training:num_training+num_validation]\n mask_test = mask[num_training+num_validation:num_training+num_validation+num_test]\n \n # Creating training, validation and test based on maskes\n X_train = X_total[mask_train]\n y_train = y_total[mask_train]\n X_val = X_total[mask_val]\n y_val = y_total[mask_val]\n X_test = X_total[mask_test]\n y_test = y_total[mask_test]\n \n \n # Normalize the data: subtract the mean image\n mean_image = np.mean(X_train, axis=0)\n X_train -= mean_image\n X_val -= mean_image\n X_test -= mean_image\n \n # Make it into one vector\n X_train = X_train.reshape(num_training, -1)\n X_val = X_val.reshape(num_validation, -1)\n X_test = X_test.reshape(num_test, -1)\n \n return X_train, y_train, X_val, y_val, X_test, y_test\n\ndef get_data_aug(x_kar, x_kat, x_bord, x_kar_aug, x_kat_aug, x_bord_aug, y_kar=0, y_kat=1, y_bord=2, \n num_training=205, num_validation=100, num_test=100):\n X_total = []\n y_total = []\n X_augmented = []\n y_augmented = []\n # Running through source images\n for kar in x_kar:\n X_total.append(kar)\n y_total.append(y_kar)\n for kat in x_kat:\n X_total.append(kat)\n y_total.append(y_kat)\n for bord in x_bord:\n X_total.append(bord)\n y_total.append(y_bord)\n \n # Running through augmented images\n for kar in x_kar_aug:\n X_augmented.append(kar)\n y_augmented.append(y_kar)\n for kat in x_kat_aug:\n X_augmented.append(kat)\n y_augmented.append(y_kat)\n for bord in x_bord_aug:\n X_augmented.append(bord)\n y_augmented.append(y_bord)\n \n # Make a numpy array\n X_total = np.asarray(X_total) \n y_total = np.asarray(y_total)\n \n X_total = X_total.astype(float)\n X_total = np.divide(X_total,255)\n \n # Generate maskes to randomize data selection\n mask_source = np.random.choice(X_total.shape[0], X_total.shape[0], replace=True) \n mask_train = mask_source[0:num_training]\n mask_val = mask_source[num_training:num_training+num_validation]\n mask_test = mask_source[num_training+num_validation:num_training+num_validation+num_test]\n \n # Combining source and augmented images for training data\n X_source_train = X_total[mask_train]\n y_source_train = y_total[mask_train]\n \n for data in X_source_train:\n X_augmented.append(data)\n for data in y_source_train:\n y_augmented.append(data)\n \n X_augmented = np.asarray(X_augmented)\n y_augmented = np.asarray(y_augmented)\n \n X_augmented = X_augmented.astype(float)\n X_augmented = np.divide(X_augmented,255)\n \n mask_augmented = np.random.choice(X_augmented.shape[0], X_augmented.shape[0])\n # Creating training, validation and test based on maskes\n X_train = X_augmented[mask_augmented]\n y_train = y_augmented[mask_augmented]\n X_val = X_total[mask_val]\n y_val = y_total[mask_val]\n X_test = X_total[mask_test]\n y_test = y_total[mask_test]\n\n # Normalize the data: subtract the mean image\n mean_image = np.mean(X_train, axis=0)\n X_train -= mean_image\n X_val -= mean_image\n X_test -= mean_image\n \n # Make it into one vector\n X_train = X_train.reshape(X_augmented.shape[0], -1)\n X_val = X_val.reshape(num_validation, -1)\n X_test = X_test.reshape(num_test, -1)\n \n return X_train, y_train, X_val, y_val, X_test, y_test\n\ndef import_images(path_potato, path_catfood, path_table, augmented=False, path_aug_potato=None, path_aug_catfood=None,\n path_aug_table=None):\n \n x_pot = images_to_arr(path_potato) \n x_cat = images_to_arr(path_catfood)\n x_tab = images_to_arr(path_table)\n if augmented:\n x_aug_pot = images_to_arr(path_aug_potato[0:500])\n x_aug_cat = images_to_arr(path_aug_catfood[0:500])\n x_aug_tab = images_to_arr(path_aug_table[0:500])\n X_train, y_train, X_val, y_val, X_test, y_test = get_data_aug(x_pot, x_cat, x_tab, x_aug_pot, x_aug_cat, x_aug_tab)\n else:\n X_train, y_train, X_val, y_val, X_test, y_test = get_data(x_pot, x_cat, x_tab)\n return X_train, y_train, X_val, y_val, X_test, y_test\n ","sub_path":"Classification/util/image_import.py","file_name":"image_import.py","file_ext":"py","file_size_in_byte":11213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"560196773","text":"'''\n utils.py\n\n Implement helper functions for sampling from corpus.\n'''\n\n##################################################################################\n## FILE I/O AND DATA STRUCTURES\n##################################################################################\n\ndef read_from_archive(path_to_archive, file_to_read=None):\n # quick and dirty method to get type of archive\n archive_type = path_to_archive.split('.')[-1]\n if archive_type == 'zip':\n import zipfile\n zip = zipfile.ZipFile(path_to_archive, 'r')\n data = zip.read(file_to_read)\n elif archive_type == 'tar':\n import tarfile\n tar = tarfile.open(path_to_archive, 'r')\n f = tar.extractfile(file_to_read)\n data = f.read()\n tar.close()\n elif archive_type == 'bz2':\n import bz2\n bz_file = bz2.BZ2File(path_to_archive)\n data = bz_file.readlines(100000000)\n else:\n raise NameError('Only .zip, .tar, and .bz2 formats supported')\n return data\n\ndef write_to_json(data_dict, json_path):\n import json\n with open(json_path, 'w') as f:\n json.dump(data_dict, f, indent=4, sort_keys=True)\n\ndef flatten(l):\n return [item for sublist in l for item in sublist]\n\n##################################################################################\n## TOKENIZING AND TEXT PROCESSING\n##################################################################################\n\nimport nltk\n\ndef not_proper(pos):\n return pos not in ['NNP', 'NNPS', 'FW', 'CD']\n\ndef not_punct(t):\n return t not in [',', '.', '?', '!', '\\\"', '\\'', '\\n']\n\ndef word_tokenize(s, remove_punct=True):\n tokens = nltk.word_tokenize(s.decode('utf8'))\n if remove_punct:\n new_tokens = [t for t in tokens if not_punct(t)]\n return new_tokens\n else:\n return tokens\n\ndef sent_tokenize(t):\n sent_detector = nltk.data.load('tokenizers/punkt/english.pickle')\n return sent_detector.tokenize(t.strip())\n\ndef texts_to_sentences(texts):\n sentences = []\n for t in texts:\n try:\n sentences.append(sent_tokenize(t))\n # ignore encoding errors for now\n except UnicodeDecodeError:\n pass\n sentences = flatten(sentences)\n return sentences\n\ndef sentences_of_length_n(n, token_dict):\n sentences_n = [s for s, tokens in token_dict.items()\n if len(tokens) == n and\n all([not_proper(pos) for token, pos\n in nltk.pos_tag(tokens)])]\n return sentences_n\n","sub_path":"sample/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"462920135","text":"import sys\nfrom PyQt5.QtWidgets import QMainWindow, QApplication, QMessageBox\n\nfrom main_form import Ui_MainWindow\nfrom showDialog import showDialog\n\nimport tela_form2\n\n\nclass form1(QMainWindow):\n def __init__(self, parent=None):\n super(form1, self).__init__()\n self.ui = Ui_MainWindow()\n self.ui.setupUi(self)\n self.connectSignal()\n\n def connectSignal(self):\n self.ui.btnOk.clicked.connect(self.some_action)\n\n def validaCampos(self):\n texto = \"\"\n\n if not (self.ui.nome.text()):\n texto += \"Nome\\n\"\n if not (self.ui.idade.text()):\n texto += \"Idade\\n\"\n if not (self.ui.cpf.text()):\n texto += \"CPF\\n\"\n\n return texto\n\n def some_action(self):\n campos = self.validaCampos()\n if (campos == \"\"):\n showDialog(\"Sucesso\", \"Deu tudo certo\" + campos,\n QMessageBox.Information)\n self.form2 = tela_form2.form2(self.ui.nome.text(),\n self.ui.idade.text(),\n self.ui.cpf.text())\n self.form2.show()\n else:\n showDialog(\n \"Error\",\n \"Todos os campos devem ser preenchidos. Campo(s) a ser(em) preenchido(s):\\n\"\n + campos, QMessageBox.Critical)\n\n\ndef main():\n app = QApplication(sys.argv)\n mw = form1()\n mw.show()\n\n sys.exit(app.exec_())\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"2017/SECOMP/PythonQt/exemplo4/tela_form.py","file_name":"tela_form.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"373462418","text":"\n\nfrom xai.brain.wordbase.nouns._circulation import _CIRCULATION\n\n#calss header\nclass _CIRCULATIONS(_CIRCULATION, ):\n\tdef __init__(self,): \n\t\t_CIRCULATION.__init__(self)\n\t\tself.name = \"CIRCULATIONS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"circulation\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_circulations.py","file_name":"_circulations.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"195476656","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 27 09:25:38 2019\n\n@author: amandaash\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport numpy.random as rand\nimport math\n\ndef x2(x):\n y = x**2\n return y\n\ndef sinx(x):\n y = np.sin(x)\n return y\n\ndef g(x):\n y = 10*(np.cos(0.25*x))**3 \n return y\n\ndef probability_dist_integral(function, N, a, b):\n accepted= []\n rejected = []\n \n #A_square = (np.abs(a) + np.abs(b))*(np.abs(function(a)) + np.abs(function(b)))\n A_square = (np.abs(b-a))*(np.abs(function(b)-function(a)))\n print(A_square)\n x_sample = rand.uniform(a, b, N)\n y_sample = rand.uniform(np.min(function(x_sample)), np.max(function(x_sample)), N)\n points = np.column_stack((x_sample, y_sample))\n \n for coordinate in points:\n if coordinate[1] > 0:\n if coordinate[1] > 0 and coordinate[1] <= function(coordinate[0]):\n accepted.append(coordinate)\n else:\n rejected.append(coordinate)\n else:\n if coordinate[1] < 0 and coordinate[1] >= function(coordinate[0]):\n accepted.append(coordinate)\n else:\n rejected.append(coordinate)\n\n N_accepted = len(accepted) \n \n accepted = np.array(accepted)\n rejected = np.array(rejected)\n plt.plot(accepted[:,0], accepted[:,1], '.')\n plt.plot(rejected[:,0], rejected[:,1], '.')\n plt.show()\n \n numeric_area = (N_accepted/N)*A_square\n return accepted, rejected, numeric_area\n\nplt.title('$x^2$')\naccepted1, rejected1, area1 = probability_dist_integral(x2, 100000, 0, 10)\nprint('I(x^2)~{0}'.format(area1))\nplt.title('sin(x)')\naccepted2, rejected2, area2 = probability_dist_integral(sinx, 100000, 0, 2*np.pi)\nprint('I(sin(x))~{0}'.format(area2))\nplt.title('$(10*cos^2(\\\\frac{x}{4}))^3$')\naccepted3, rejected3, area3 = probability_dist_integral(g, 100000, 1, 50)\nprint('I((10*cos^2(0.25*x))^3)~{0})'.format(area3))\n\n\n","sub_path":"Week 06/E13.py","file_name":"E13.py","file_ext":"py","file_size_in_byte":1973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"576713404","text":"from zope.i18n import translate\nfrom zope.interface import implements\nfrom zope.component import getUtility\n\nfrom Products.statusmessages.interfaces import IStatusMessage\nfrom Products.Five.browser import BrowserView\nfrom plone import api\n\nfrom collective.maildigest.interfaces import IDigestInfo, IDigestUtility\nfrom collective.maildigest import DigestMessageFactory as _\n\n\nclass DigestInfo(BrowserView):\n\n implements(IDigestInfo)\n parent_subscribed = False\n\n def update(self):\n context = self.context\n utility = getUtility(IDigestUtility)\n user = api.user.get_current()\n user_id = user.getId()\n\n self.digest_delays = []\n subscribed_storage, recursive = utility.get_subscription(user_id, context, root=True)\n for name, storage in utility.get_storages(sort=True):\n self.digest_delays.append({\n 'name': name,\n 'selected': subscribed_storage and subscribed_storage.key == name,\n 'label': _('${delay} email',\n mapping={'delay': translate(storage.label,\n context=self.request).lower()\n }),\n })\n\n self.recursive_subscription = recursive\n self.subscribed_nothing = not subscribed_storage\n\n if not subscribed_storage:\n parent_subscribed_storage, recursive = utility.get_subscription(user_id, context)\n if parent_subscribed_storage:\n self.parent_subscribed = True\n\n\nclass DigestSubscribe(BrowserView):\n\n def __call__(self):\n utility = getUtility(IDigestUtility)\n user = api.user.get_current()\n user_id = user.getId()\n subscription = self.request.get('digest-subscription')\n statusmessage = IStatusMessage(self.request)\n recursive = bool(self.request.get('digest-subscription-recursive', False))\n utility.switch_subscription(user_id, self.context, subscription, recursive)\n msg_type = 'info'\n if subscription is None:\n message = _(\"Please select daily or weekly digest.\")\n msg_type = 'error'\n elif subscription == 'cancel-subscription':\n message = _(\"You cancelled your subscription to digest email about activity on this folder\")\n else:\n storage = utility.get_storage(subscription)\n message = _('msg_subscribed_digest',\n default=\"You subscribed to ${delay} digest email about activity on this folder\",\n mapping={'delay': translate(storage.label,\n context=self.request).lower()})\n\n statusmessage.addStatusMessage(message, msg_type)\n return self.context.absolute_url()\n","sub_path":"collective/maildigest/browser/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":2801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"379708705","text":"from django.shortcuts import render,redirect,HttpResponse\nfrom crm import models\n\nenabled_admins = {}\n\nclass BaseAdmin(object):\n list_display = []\n list_filters = []\n search_filter = []\n list_per_page = 10\n ordering = None\n filter_horizontal = []\n actions = [\"delete_selected_objs\"]\n readonly_fields = []\n readonly_table = False\n modelform_exclude_fields = ()\n \n def enroll(self):\n if self.instance.status == 0:\n return '''报名新课程''' % self.instance.id\n else:\n return '''报名''' % self.instance.id\n\n enroll.display_name = \"报名课程\"\n\n\n def default_form_validation(self):\n pass\n # '''\n # 用户自定义表单验证\n # :return:\n # '''\n # content = self.cleaned_data.get(\"content\", \"\")\n # if len(content) < 15:\n # return self.ValidationError(\n # ('Field %(field)s 咨询内容不能少于15个字符'),\n # code='invalid',\n # params = {'field': \"content\"}\n # )\n\n def delete_selected_objs(self, request, querysets):\n '''\n 自定义action,执行对所选择数据集的自定义操作\n :param request: \n :param querysets: \n :return: \n '''\n app_name = self.model._meta.app_label\n table_name = self.model._meta.model_name\n errors = \"\"\n if request.POST.get(\"delete_confirm\") == \"yes\":\n if not self.readonly_table:\n querysets.delete()\n return redirect(\"/common/%s/%s/\" % (app_name, table_name))\n else:\n errors = \"table %s read only!\" % self.model._meta.model_name\n selected_ids = ','.join([str(i.id) for i in querysets])\n return render(request,\"common/table_delete.html\", context={\n \"objs\": querysets,\n \"admin_class\": self,\n \"app_name\": app_name,\n 'table_name': table_name,\n \"selected_ids\": selected_ids,\n \"action\": request._action,\n \"errors\": errors\n })\n\nclass CustomerAdmin(BaseAdmin):\n list_display = ['id', 'qq','name','source','consultant','consult_course','date','status', 'enroll']\n list_filters = ['source','consultant','consult_course','status', 'date']\n search_filter = ['id', 'qq','name']\n list_per_page = 5 #自定义每页显示的页数\n ordering = \"qq\"\n filter_horizontal = ['tags']\n readonly_fields = ['qq', 'consultant', 'tags']\n readonly_table = False\n\n #自定义字段过滤\n def clean_name(self):\n if not self.cleaned_data['name']:\n self.add_error(\"name\", \"不能为空!\")\n\n def default_form_validation(self):\n '''\n 用户自定义表单验证\n :return: \n '''\n content = self.cleaned_data.get(\"content\", \"\")\n if len(content) < 15:\n return self.ValidationError(\n ('Field %(field)s 咨询内容不能少于15个字符'),\n code='invalid',\n params = {'field': \"content\"}\n )\n\nclass CustomerFollowUpAdmin(BaseAdmin):\n list_display = ['id', 'customer', 'content', 'consultant']\n list_filters = ['customer', 'content', 'consultant',]\n search_filter = ['id', 'content',]\n list_per_page =5\n\n\nclass UserProfileAdmin(BaseAdmin):\n list_display = ('email', 'name')\n readonly_fields = ('password')\n filter_horizontal = ('user_permissions', \"groups\")\n modelform_exclude_fields = (\"last_login\",)\n\n\n\nclass CourseRecordAdmin(BaseAdmin):\n list_display = ['from_class', 'day_num', 'teacher', 'has_homework', 'homework_title', 'date']\n\n\n def initialize_studyrecords(self, request, queryset):\n if len(queryset) > 1:\n return HttpResponse(\"不能选择多个班级\")\n new_obj_list = []\n for enroll_obj in queryset[0].from_class.enrollment_set.all():\n new_obj_list.append(\n models.StudyRecord(\n student = enroll_obj,\n course_record = queryset[0],\n attendance = 0,\n socre = 0,\n )\n )\n try:\n #批量创建\n models.StudyRecord.objects.bulk_create(new_obj_list)\n except Exception as e:\n return HttpResponse(\"批量创建失败!\")\n return redirect(\"/common/crm/studyrecord/?course_record=%s\" % queryset[0].id)\n\n #django后台自定义动作名称\n initialize_studyrecords.short_description = \"初始化本节所有学员的上课记录\"\n #django 自定义动作\n actions = ['initialize_studyrecords', ]\n\n\n\nclass StudyRecordAdmin(BaseAdmin):\n list_display = ['student', 'course_record', 'attendance', 'socre', 'date']\n list_filter = ['course_record', 'socre', 'attendance', 'course_record__from_class', 'student']\n #可编辑\n list_editable = ['socre', 'attendance']\n\n\n\n\ndef register(model_class, admin_class=None):\n if model_class._meta.app_label not in enabled_admins:\n enabled_admins[model_class._meta.app_label] = {}\n admin_class.model = model_class\n enabled_admins[model_class._meta.app_label][model_class._meta.model_name] = admin_class\n\nregister(models.Customer, CustomerAdmin)\nregister(models.CustomerFollowUp, CustomerFollowUpAdmin)\nregister(models.UserProfile, UserProfileAdmin)\nregister(models.CourseRecord, CourseRecordAdmin)\nregister(models.StudyRecord, StudyRecordAdmin)","sub_path":"common/common_admin.py","file_name":"common_admin.py","file_ext":"py","file_size_in_byte":5505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"50807798","text":"from keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import LSTM\nfrom keras.layers import Dropout\nfrom keras.models import model_from_json\nimport os\nimport numpy as np\nimport sys\nimport json\nimport argparse\nimport pickle\n\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix\n\nfrom data_generator import DataGenerator\nimport glob\n\ndef parse_args():\n parser = argparse.ArgumentParser(description = 'Read training/test file and run LSTM training or test.')\n parser.add_argument('--infile', dest ='infile', required = True, type = str, help = 'File containing training/test data with labels.')\n parser.add_argument('-rd', '--result-dir', dest ='result_dir', type = str, default = \"/var/scratch2/uji300/OpenKE-results/\",help = 'Output dir.')\n parser.add_argument('--topk', dest = 'topk', required = True, type = int, default = 10)\n parser.add_argument('--units', dest = 'units', type = int, default = 100)\n parser.add_argument('-bs', '--batch-size', dest = 'batch_size', type = int, default=2)\n parser.add_argument('--epochs', dest = 'epochs', type = int, default = 100)\n parser.add_argument('--dropout', dest = 'dropout', type = float, default = 0.5)\n parser.add_argument('--db', required = True, dest = 'db', type = str, default = \"fb15k237\")\n parser.add_argument('--emb-model', required = True, dest = 'emb_model', type = str, default = \"transe\")\n parser.add_argument('--model', required = True, dest = 'model_str', type = str, default = \"lstm\")\n parser.add_argument('--pred', dest ='pred', required = True, type = str, choices = ['head', 'tail'], help = 'Prediction type (head/tail)')\n return parser.parse_args()\n\nargs = parse_args()\n\n# DIM = 200 for each entity/relation\n# Paths\ndb_path = \"./benchmarks/\" + args.db + \"/\"\nresult_dir = args.result_dir + args.db + \"/\"\nos.makedirs(result_dir, exist_ok = True)\n\ninput_file = args.infile\ntopk = int(args.topk)\ntype_prediction = args.pred\nn_units = int(args.units)\ndropout = float(args.dropout)\nmodel_str = args.model_str\nn_epochs = args.epochs\nemb_model = args.emb_model\n\nall_files = glob.glob(input_file + \"*training-topk-\"+str(topk) +\"*\" + type_prediction + \"*.pkl\")\nnum_files = len(all_files)\nnum_valid_files = max((int)(0.05 * num_files), 2)\nmarker = num_files - num_valid_files\n\nprint(\"num_files = \", num_files)\nprint(\"valid_file = \", num_valid_files)\nprint(\"marker = \", marker)\nid_list = np.arange(1, num_files + 1)\n\ntrain_ids = id_list[:marker]\nvalid_ids = id_list[marker:]\n\n#TODO: deduce from data\nN_FEATURES=605\n\nparams = {\n 'db' : args.db,\n 'emb_model' : emb_model,\n 'topk' : topk,\n 'dim_x' : (1000, topk, N_FEATURES),\n 'dim_y' : (1000, topk, 1),\n 'batch_size': int(args.batch_size),\n 'n_classes' : 2,\n 'shuffle' : True\n }\n\npartition = {}\npartition['train'] = train_ids\npartition['valid'] = valid_ids\n\ntraining_generator = DataGenerator(partition['train'], input_file, type_prediction, **params)\nvalid_generator = DataGenerator(partition['valid'], input_file, type_prediction, **params)\n\n# Model\nmodel = Sequential();\nif model_str == \"lstm\":\n model.add(LSTM(n_units, input_shape=(topk, N_FEATURES), batch_input_shape=(1000 * int(args.batch_size), topk, N_FEATURES), return_sequences = True));\n model.add(Dropout(dropout))\n model.add(Dense(1, activation = 'sigmoid'))\nelif model_str == \"mlp\":\n model.add(Dense(n_units, input_shape=(topk, N_FEATURES)));\n model.add(Dropout(dropout))\n model.add(Dense(n_units))\n model.add(Dropout(dropout))\n model.add(Dense(1, activation = 'sigmoid'))\n\n# For classification problem (with 2 classes), binary cross entropy is used.\nmodel.compile(loss = 'binary_crossentropy', optimizer = 'adam', metrics = ['accuracy'])\nprint(model.summary())\n\n\nmodel.fit_generator(generator=training_generator, validation_data = valid_generator, use_multiprocessing = True, epochs = n_epochs, workers = 8)\n\n#Saving of model and weights\njson_model = model.to_json()\n\nbase_name = args.db + \"-\" + args.emb_model + \"-training-topk-\" + str(args.topk)\nmodel_file_name = result_dir + \"models/\" + base_name + \"-\" + type_prediction + \"-model-\"+ model_str + \"-units-\"+str(n_units) + \\\n\"-dropout-\" + str(dropout) +\".json\"\nwith open(model_file_name, 'w') as fout:\n fout.write(json_model)\n\nmodel_weights_file_name = result_dir + \"models/\" + base_name + \"-\" + type_prediction + \"-weights-\"+ model_str + \"-units-\"+str(n_units) + \\\n\"-dropout-\" + str(dropout) +\".h5\"\n\nmodel.save_weights(model_weights_file_name)\nprint(\"Saved model to disk\")\n","sub_path":"train_answer_model_batches.py","file_name":"train_answer_model_batches.py","file_ext":"py","file_size_in_byte":4584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"485316695","text":"#!/usr/bin/env python\n\n\nfrom typing import Sequence\n\nimport pyro\nimport pyro.distributions as dist\nimport pyro.poutine as poutine\nimport torch\nimport torch.nn as nn\n\nfrom drvish.models.modules import Encoder, NBDecoder\n\n\nclass NBVAE(nn.Module):\n r\"\"\"Variational auto-encoder model with negative binomial loss.\n\n :param n_input: Number of input genes\n :param n_latent: Dimensionality of the latent space\n :param encoder_layers: Number and size of hidden layers used for encoder NN\n :param decoder_layers: Number of size of hidden layers for decoder NN.\n If None, uses encoder_layers in reverse order\n :param lib_loc: Mean for prior distribution on library scaling factor\n :param lib_scale: Scale for prior distribution on library scaling factor\n :param scale_factor: For adjusting the ELBO loss\n :param weight_scaling: use Gamma ReLU and weight scaling for linear layers\n \"\"\"\n NAME = \"nbvae\"\n\n def __init__(\n self,\n *,\n n_input: int,\n n_latent: int,\n encoder_layers: Sequence[int],\n decoder_layers: Sequence[int] = None,\n lib_loc: float,\n lib_scale: float,\n scale_factor: float = 1.0,\n weight_scaling: bool = False,\n ):\n super().__init__()\n\n # create the encoder and decoder networks\n self.encoder = Encoder(n_input, n_latent, encoder_layers, weight_scaling)\n if decoder_layers is not None:\n self.decoder = NBDecoder(n_latent, n_input, decoder_layers, weight_scaling)\n else:\n self.decoder = NBDecoder(\n n_latent, n_input, encoder_layers[::-1], weight_scaling\n )\n\n self.register_buffer(\"lib_loc\", torch.as_tensor(lib_loc))\n self.register_buffer(\"lib_scale\", torch.full((1,), lib_scale))\n\n self.n_latent = n_latent\n self.scale_factor = scale_factor\n\n def model(self, x: torch.Tensor):\n # register modules with Pyro\n pyro.module(self.NAME, self)\n\n with pyro.plate(\"data\", len(x)), poutine.scale(scale=self.scale_factor):\n z = pyro.sample(\n \"latent\", dist.Normal(0, x.new_ones(self.n_latent)).to_event(1)\n )\n\n lib = pyro.sample(\n \"library\", dist.Normal(self.lib_loc, self.lib_scale).to_event(1)\n )\n\n log_r, logit = self.decoder(z, lib)\n\n pyro.sample(\n \"obs\",\n dist.NegativeBinomial(\n total_count=torch.exp(log_r), logits=logit\n ).to_event(1),\n obs=x,\n )\n\n return z\n\n # define the guide (i.e. variational distribution) q(z|x)\n def guide(self, x: torch.Tensor):\n pyro.module(self.NAME, self)\n\n with pyro.plate(\"data\", len(x)), poutine.scale(scale=self.scale_factor):\n # use the encoder to get the parameters used to define q(z|x)\n z_loc, z_scale, l_loc, l_scale = self.encoder(x)\n\n # sample the latent code z\n pyro.sample(\"latent\", dist.Normal(z_loc, z_scale).to_event(1))\n pyro.sample(\"library\", dist.Normal(l_loc, l_scale).to_event(1))\n","sub_path":"src/drvish/models/nbvae.py","file_name":"nbvae.py","file_ext":"py","file_size_in_byte":3169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"192482050","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Aug 11 13:15:18 2016\n\n@author: olinero\n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\nx = np.arange(0, 10, 0.2)\ny = np.sin(x)\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.plot(x, y)\nplt.show()\n","sub_path":"test graking messageIn.py","file_name":"test graking messageIn.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"653962151","text":"'''\nsocket编程思路\nTCP服务端:\n1 创建套接字,绑定套接字到本地IP与端口\n # socket.socket(socket.AF_INET,socket.SOCK_STREAM) , s.bind()\n2 开始监听连接 #s.listen()\n3 进入循环,不断接受客户端的连接请求 #s.accept()\n4 然后接收传来的数据,并发送给对方数据 #s.recv() , s.sendall()\n5 传输完毕后,关闭套接字 #s.close()\n\nTCP客户端:\n\n1 创建套接字,连接远端地址\n # socket.socket(socket.AF_INET,socket.SOCK_STREAM) , s.connect()\n2 连接后发送数据和接收数据 # s.sendall(), s.recv()\n3 传输完毕后,关闭套接字 #s.close()\n'''\nimport gevent,time,socket\n\ndef client_side(PORT):\n HOST = 'localhost' #本地 或者localhost\n #PORT = 8888 #服务端端口\n client = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #定义socket类型,网络通信,TCP socket.SOCK_STREAM 这个表示传输协议用的是TCP socket.SOCK_DGRAM指的是UDP\n client.connect((HOST,PORT)) #连接 UDP类型的话是不需要这样连接的\n try:\n while True:\n for i in range(20):\n client.send() #可以传输bety类型的数据 比如:b'Hello'\n #client.sendto(data,(HOST,PORT)) #UDP类型用的是这个发送数据同时发送地址和端口\n data = client.recv(1024) #一次接收1024的数据 循环接收 (按说应该加一个 if not data 的判断 没有数据关闭跳出)\n\n print(\"返回的数据:\",repr(data))\n client.close()\n except Exception as ex:\n print(ex)\n\n finally:\n client.close()\n\nif __name__ == '__main__':\n client_side(8888)","sub_path":"多任务(协程,socket客户)-7.py","file_name":"多任务(协程,socket客户)-7.py","file_ext":"py","file_size_in_byte":1746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"223680862","text":"# 7 편차: 표본 편차\n# 8,9 화면 출력 참고\nimport csv\nimport math\n\ndef get_csv_row_instance(primary_key): #행\n row_instance=[]\n # 내용을 작성하세요.\n row_instance = data[int(primary_key)]\n\n return row_instance\n\ndef get_csv_col_instance(col_name): #열\n col_instance=[]\n # 내용을 작성하세요.\n col_index = data[0].index(col_name)\n\n for row in data[1:]:\n col_instance.append(row[col_index])\n\n col_instance = Convert_Type(col_instance)\n return col_instance\n\ndef Convert_Type(col_instance):\n # 내용을 작성하세요.\n try:\n col_instance = list(map(int,col_instance))\n except ValueError:\n col_instance = list(map(float,col_instance))\n return col_instance\n\ndef My_Sum(data_list):\n My_Sum=0\n # 내용을 작성하세요.\n for data in data_list:\n My_Sum += data\n return My_Sum\n\ndef My_Average(data_list):\n My_Average=0\n # 내용을 작성하세요.\n My_Average = My_Sum(data_list)/len(data_list)\n return My_Average\n\ndef My_Max(data_list):\n My_Max=0\n # 내용을 작성하세요.\n My_Max = data_list[0]\n\n for data in data_list[1:]:\n if data > My_Max:\n My_Max = data\n return My_Max\n\ndef My_Min(data_list):\n My_Min = 0\n # 내용을 작성하세요.\n My_Min = data_list[0]\n\n for data in data_list[1:]:\n if data < My_Min:\n My_Min = data\n return My_Min\n\ndef My_Deviation(data_list): #편차\n My_Deviation=0\n # 내용을 작성하세요.\n print(\"편차(Deviation) 공식 : 표본값 - 평균\\n표본\\t\\t편차\")\n for data in data_list:\n My_Descendant = data - My_Average(data_list)\n print(\"{0}\\t\\t{1}\".format(data,My_Descendant))\n\ndef My_Variance(data_list):#분산\n My_Variance=0\n # 내용을 작성하세요.\n temp = 0\n for data in data_list:\n temp += (data - My_Average(data_list)) ** 2\n\n My_Variance = temp / len(data_list)\n return My_Variance\n\ndef My_Standard_Deviation(data_list):# 표준편차\n Variance=0\n # 내용을 작성하세요.\n Variance = My_Variance(data_list)\n My_Standard_Deviation = math.sqrt(Variance)\n return My_Standard_Deviation\n\ndef My_Ascendant(data_list):#오름차순\n # 내용을 작성하세요.\n data_list = sorted(data_list)\n for data in data_list:\n print(data, end=' ')\n print()\n pass\n\ndef My_Descendant(data_list):#내림차순\n # 내용을 작성하세요.\n data_list = sorted(data_list)\n data_list = reversed(data_list)\n for data in data_list:\n print(data, end=' ')\n print()\n pass\n\ndef print_row(row_instance):\n # 내용을 작성하세요.\n print(\"행 데이터는 아래와 같습니다.\")\n for row_element in row_instance:\n print(row_element, end=' ')\n print()\n pass\n\ndef print_col(col_instance):\n # 내용을 작성하세요.\n print(\"열 데이터는 아래와 같습니다.\")\n\n for col_element in col_instance:\n print(col_element)\n print()\n pass\n\nwith open('Demographic_Statistics_By_Zip_Code.csv',newline='') as infile:\n data=list(csv.reader(infile))\n\n# menu 처리\nwhile True:\n print(\"\")\n print(\"0.종료 1.행 2.열 3.총합 4.평균 5.최대값 6.최소값 7.편차 8.표준편차 9.분산 10.오름차순 정렬 11.내림차순 정렬\")\n menu = int(input(\"메뉴를 선택하세요: \"))\\\n\n if menu == 0:\n exit()\n\n accessKey = input(\"Access Key를 입력하세요: \")\n\n if menu == 1: #행\n row_instance = get_csv_row_instance(accessKey)\n print_row(row_instance)\n elif menu == 2: #열\n col_instance = get_csv_col_instance(accessKey)\n print_col(col_instance)\n elif menu == 3: #총합\n sum = My_Sum(get_csv_col_instance(accessKey))\n print_col(get_csv_col_instance(accessKey))\n print(\"총합: {0}\".format(sum))\n elif menu == 4: #평균\n average = My_Average(get_csv_col_instance(accessKey))\n print_col(get_csv_col_instance(accessKey))\n print(\"평균: {0}\".format(average))\n elif menu == 5: #최대값\n max = My_Max(get_csv_col_instance(accessKey))\n print_col(get_csv_col_instance(accessKey))\n print(\"최대값: {0}\".format(max))\n elif menu == 6: #최소값\n min = My_Min(get_csv_col_instance(accessKey))\n print_col(get_csv_col_instance(accessKey))\n print(\"최소값: {0}\".format(min))\n elif menu == 7: #편차\n My_Deviation(get_csv_col_instance(accessKey))\n elif menu == 8: #표준편차\n standard_Deviation = My_Standard_Deviation(get_csv_col_instance(accessKey))\n print_col(get_csv_col_instance(accessKey))\n print(\"표준편차(Standard Deviation) 공식: √분산\")\n print(\"표준편차: {0}\".format(standard_Deviation))\n elif menu == 9: #분산\n variance = My_Variance(get_csv_col_instance(accessKey))\n print_col(get_csv_col_instance(accessKey))\n print(\"분산(Variance) 공식: ∑(표본-평균)**2/표본수\")\n print(\"분산: {0}\".format(variance))\n elif menu == 10: #오름차순 정렬\n My_Ascendant(get_csv_col_instance(accessKey))\n else: #내림차순 정렬\n My_Descendant(get_csv_col_instance(accessKey))\n\n","sub_path":"03.Data_Science/1.Collection/1.CSV_Handle/3.csv_app_template.py","file_name":"3.csv_app_template.py","file_ext":"py","file_size_in_byte":5271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"153560779","text":"#!/usr/bin/python3\nimport os\nimport re\nimport glob\nimport argparse\nimport numpy as np\nimport pandas as pd\n\n\ndef experimental_data_prep(fit):\n\t\"\"\" Format experimental data.\"\"\"\n\tnp.savetxt(fname=\"./input.files/experimental_data/exp-saxs.dat\", X=fit, fmt=\"%.6E\")\n\treturn\n\n\ndef read_crysol_fit(path_to_file, maxq):\n\t\"\"\" Read CRYSOL .fit output.\"\"\"\n\tfit = pd.read_csv(path_to_file, delim_whitespace=True, skiprows=1, names=[\"q\", \"Iqexp\", \"sigmaexp\", \"fit\"])\n\tfit = fit[fit[\"q\"] <= maxq]\n\treturn fit.values\n\n\ndef format_fits(path_to_fits, maxq, output_dir):\n\t\"\"\" Format theoretical fits for BioEn simulated data input.\"\"\"\n\tfits = glob.glob(path_to_fits)\n\tfits.sort()\n\texp_scattering = read_crysol_fit(fits[0], maxq)[9:, :3]\n\texperimental_data_prep(exp_scattering)\n\tq = exp_scattering[:, :1]\n\tfor fit in fits:\n\t\tfit_idx = re.findall(r\"\\d+\", os.path.basename(fit))[0][:-2]\n\t\ttheoretical_scattering = read_crysol_fit(fit, maxq)[:, 3:]\n\t\tstacked_array = np.hstack((q, theoretical_scattering))\n\t\tprint(output_dir + fit_idx + \".dat\")\n\t\tnp.savetxt(fname=output_dir + fit_idx + \".dat\", X=stacked_array, fmt=\"%.6E\")\n\treturn\n\n\nformat_fits(path_to_fits=\"/fits/*.fit\", maxq=0.20, output_dir=\"./input.files/simulated_data/\")\n","sub_path":"ensembles/bioen/01_data_prep.py","file_name":"01_data_prep.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"75972540","text":"import sys\n\nint(input((\"갯수를 입력하세요 : \")))\n\n\ndata = list(map(int, input().split()))\n\ndata.sort()\nprint(data)\n\n# 데이터 나눠서 입력받기\n\nn, m, k = map(int, input().split())\nprint(n, m, k)\n\n# 문자열 입력 ㅂ다기\n\ndata = sys.stdin.readline().rstrip()\nprint(data)\n\n# 정답 문자열 입력 시 정수 to 문자 형변환\n\ntest_case = 1\nanswer = 10\nprint(\"#\" + str(test_case) + \" \" + str(answer))","sub_path":"python_input.py","file_name":"python_input.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"273572818","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# Copyright: (c) 2019, Hetzner Cloud GmbH \n# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n\nfrom __future__ import absolute_import, division, print_function\n\n__metaclass__ = type\n\nANSIBLE_METADATA = {\n \"metadata_version\": \"1.1\",\n \"status\": [\"preview\"],\n \"supported_by\": \"community\",\n}\n\nDOCUMENTATION = \"\"\"\n---\nmodule: hcloud_datacenter_info\n\nshort_description: Gather info about the Hetzner Cloud datacenters.\n\nversion_added: \"2.8\"\ndescription:\n - Gather info about your Hetzner Cloud datacenters.\n - This module was called C(hcloud_datacenter_facts) before Ansible 2.9, returning C(ansible_facts) and C(hcloud_datacenter_facts).\n Note that the M(hcloud_datacenter_info) module no longer returns C(ansible_facts) and the value was renamed to C(hcloud_datacenter_info)!\n\nauthor:\n - Lukas Kaemmerling (@LKaemmerling)\n\noptions:\n id:\n description:\n - The ID of the datacenter you want to get.\n type: int\n name:\n description:\n - The name of the datacenter you want to get.\n type: str\nextends_documentation_fragment: hcloud\n\"\"\"\n\nEXAMPLES = \"\"\"\n- name: Gather hcloud datacenter info\n hcloud_datacenter_info:\n register: output\n- name: Print the gathered info\n debug:\n var: output\n\"\"\"\n\nRETURN = \"\"\"\nhcloud_datacenter_info:\n description:\n - The datacenter info as list\n - This module was called C(hcloud_datacenter_facts) before Ansible 2.9, returning C(ansible_facts) and C(hcloud_datacenter_facts).\n Note that the M(hcloud_datacenter_info) module no longer returns C(ansible_facts) and the value was renamed to C(hcloud_datacenter_info)!\n returned: always\n type: complex\n contains:\n id:\n description: Numeric identifier of the datacenter\n returned: always\n type: int\n sample: 1937415\n name:\n description: Name of the datacenter\n returned: always\n type: str\n sample: fsn1-dc8\n description:\n description: Detail description of the datacenter\n returned: always\n type: str\n sample: Falkenstein DC 8\n location:\n description: Name of the location where the datacenter resides in\n returned: always\n type: str\n sample: fsn1\n city:\n description: City of the location\n returned: always\n type: str\n sample: fsn1\n\"\"\"\n\nfrom ansible.module_utils.basic import AnsibleModule\nfrom ansible.module_utils._text import to_native\nfrom ansible.module_utils.hcloud import Hcloud\n\ntry:\n from hcloud import APIException\nexcept ImportError:\n pass\n\n\nclass AnsibleHcloudDatacenterInfo(Hcloud):\n def __init__(self, module):\n Hcloud.__init__(self, module, \"hcloud_datacenter_info\")\n self.hcloud_datacenter_info = None\n\n def _prepare_result(self):\n tmp = []\n\n for datacenter in self.hcloud_datacenter_info:\n if datacenter is not None:\n tmp.append({\n \"id\": to_native(datacenter.id),\n \"name\": to_native(datacenter.name),\n \"description\": to_native(datacenter.description),\n \"location\": to_native(datacenter.location.name)\n })\n\n return tmp\n\n def get_datacenters(self):\n try:\n if self.module.params.get(\"id\") is not None:\n self.hcloud_datacenter_info = [self.client.datacenters.get_by_id(\n self.module.params.get(\"id\")\n )]\n elif self.module.params.get(\"name\") is not None:\n self.hcloud_datacenter_info = [self.client.datacenters.get_by_name(\n self.module.params.get(\"name\")\n )]\n else:\n self.hcloud_datacenter_info = self.client.datacenters.get_all()\n\n except APIException as e:\n self.module.fail_json(msg=e.message)\n\n @staticmethod\n def define_module():\n return AnsibleModule(\n argument_spec=dict(\n id={\"type\": \"int\"},\n name={\"type\": \"str\"},\n **Hcloud.base_module_arguments()\n ),\n supports_check_mode=True,\n )\n\n\ndef main():\n module = AnsibleHcloudDatacenterInfo.define_module()\n\n is_old_facts = module._name == 'hcloud_datacenter_facts'\n if is_old_facts:\n module.deprecate(\"The 'hcloud_datacenter_facts' module has been renamed to 'hcloud_datacenter_info', \"\n \"and the renamed one no longer returns ansible_facts\", version='2.13')\n hcloud = AnsibleHcloudDatacenterInfo(module)\n\n hcloud.get_datacenters()\n result = hcloud.get_result()\n if is_old_facts:\n ansible_info = {\n 'hcloud_datacenter_facts': result['hcloud_datacenter_info']\n }\n module.exit_json(ansible_facts=ansible_info)\n else:\n ansible_info = {\n 'hcloud_datacenter_info': result['hcloud_datacenter_info']\n }\n module.exit_json(**ansible_info)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"env/lib/python3.9/site-packages/ansible/modules/cloud/hcloud/hcloud_datacenter_info.py","file_name":"hcloud_datacenter_info.py","file_ext":"py","file_size_in_byte":5232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"425840546","text":"#! /usr/bin/python2.7\n\n# @file chronos_resync.py\n#\n# Project Clearwater - IMS in the Cloud\n# Copyright (C) 2015 Metaswitch Networks Ltd\n#\n# This program is free software: you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation, either version 3 of the License, or (at your\n# option) any later version, along with the \"Special Exception\" for use of\n# the program along with SSL, set forth below. This program is distributed\n# in the hope that it will be useful, but WITHOUT ANY WARRANTY;\n# without even the implied warranty of MERCHANTABILITY or FITNESS FOR\n# A PARTICULAR PURPOSE. See the GNU General Public License for more\n# details. You should have received a copy of the GNU General Public\n# License along with this program. If not, see\n# .\n#\n# The author can be reached by email at clearwater@metaswitch.com or by\n# post at Metaswitch Networks Ltd, 100 Church St, Enfield EN2 6BQ, UK\n#\n# Special Exception\n# Metaswitch Networks Ltd grants you permission to copy, modify,\n# propagate, and distribute a work formed by combining OpenSSL with The\n# Software, or a work derivative of such a combination, even if such\n# copying, modification, propagation, or distribution would otherwise\n# violate the terms of the GPL. You must comply with the GPL in all\n# respects for all of the code used other than OpenSSL.\n# \"OpenSSL\" means OpenSSL toolkit software distributed by the OpenSSL\n# Project and licensed under the OpenSSL Licenses, or a work based on such\n# software and licensed under the OpenSSL Licenses.\n# \"OpenSSL Licenses\" means the OpenSSL License and Original SSLeay License\n# under which the OpenSSL Project distributes the OpenSSL toolkit software,\n# as those licenses appear in the file LICENSE-OPENSSL.\n\nfrom flask import Flask, request\nimport logging\nimport json\nimport requests\nimport threading\nimport os\nimport sys\nimport shutil\nimport signal\nfrom subprocess import Popen\nfrom time import sleep\nfrom collections import namedtuple\nfrom textwrap import dedent\nimport unittest\n\n# Test the resynchronization operations for Chronos.\n# These tests use multiple Chronos processes that run on the same machine.\n# The tests set up a Chronos cluster and add timers to it. They then\n# perform scaling operations, and check that the correct number of\n# timers still pop\nCHRONOS_BINARY = 'build/bin/chronos'\nCONFIG_FILE_PATTERN = 'scripts/log/chronos.livetest.conf%i'\nCLUSTER_CONFIG_FILE_PATTERN = 'scripts/log/chronos.cluster.livetest.conf%i'\nLOG_FILE_DIR = 'scripts/log/'\nLOG_FILE_PATTERN = LOG_FILE_DIR + 'chronos%s'\n\nNode = namedtuple('Node', 'ip port')\nflask_server = Node(ip='127.0.0.10', port='5001')\nchronos_nodes = [\n Node(ip='127.0.0.11', port='7253'),\n Node(ip='127.0.0.12', port='7254'),\n Node(ip='127.0.0.13', port='7255'),\n Node(ip='127.0.0.14', port='7256'),\n]\n\nreceiveCount = 0\nprocesses = []\ntimerCounts = []\n\n# Create log folders for each Chronos process. These are useful for\n# debugging any problems. Running the tests deletes the logs from the\n# previous run\nfor file_name in os.listdir(LOG_FILE_DIR):\n file_path = os.path.join(LOG_FILE_DIR, file_name)\n if os.path.isfile(file_path) and file_path != (LOG_FILE_DIR + '.gitignore'):\n os.unlink(file_path)\n elif os.path.isdir(file_path):\n shutil.rmtree(file_path)\nfor node in chronos_nodes:\n log_path = LOG_FILE_PATTERN % node.port\n os.mkdir(log_path)\n\n# Raise the logging level of the Flask app, to silence it during normal tests\nlog = logging.getLogger('werkzeug')\nlog.setLevel(logging.ERROR)\n\n# Open /dev/null to redirect stdout and stderr of chronos. This avoids spamming\n# the console during tests - comment this out to get the logs when debugging\nFNULL = open(os.devnull, 'w')\n\n# The Flask app. This is used to make timer requests and receive timer pops\napp = Flask(__name__)\n\n\n@app.route('/pop', methods=['POST'])\ndef pop():\n global receiveCount\n receiveCount += 1\n global timerCounts\n timerCounts.append(request.data)\n return 'success'\n\n\ndef run_app():\n app.run(host=flask_server.ip, port=flask_server.port)\n\n\n# Helper functions for the Chronos tests\ndef start_nodes(lower, upper):\n # Start nodes with indexes [lower, upper) and allow them time to start\n for i in range(lower, upper):\n processes.append(Popen([CHRONOS_BINARY, '--config-file',\n CONFIG_FILE_PATTERN % i, '--cluster-config-file',\n CLUSTER_CONFIG_FILE_PATTERN % i], stdout=FNULL, stderr=FNULL))\n\n sleep(2)\n\n\ndef kill_nodes(lower, upper):\n # kill nodes with indexes [lower, upper)\n for p in processes[lower: upper]:\n p.kill()\n\n\ndef node_reload_config(lower, upper):\n # SIGHUP nodes with indexes [lower, upper)\n for p in processes[lower: upper]:\n os.kill(p.pid, signal.SIGHUP)\n sleep(2)\n\n\ndef node_trigger_scaling(lower, upper):\n # SIGHUSR1 nodes with indexes [lower, upper)\n for p in processes[lower: upper]:\n os.kill(p.pid, signal.SIGUSR1)\n sleep(2)\n\n\ndef create_timers(target, num):\n # Create and send timer requests. These are all sent to the first Chronos\n # process which will replicate the timers out to the other Chronos processes\n body_dict = {\n 'timing': {\n 'interval': 10,\n 'repeat_for': 10,\n },\n 'callback': {\n 'http': {\n 'uri': 'http://%s:%s/pop' % (flask_server.ip, flask_server.port),\n 'opaque': 'REPLACE',\n }\n }\n }\n\n # Set the number of the timer in the opaque data - this way we can check we\n # get the correct timers back\n for i in range(num):\n body_dict['callback']['http']['opaque'] = str(i)\n r = requests.post('http://%s:%s/timers' % (target.ip, target.port),\n data=json.dumps(body_dict)\n )\n assert r.status_code == 200, 'Received unexpected status code: %i' % r.status_code\n\n\ndef write_conf(filename, this_node):\n # Create a configuration file for a chronos process. Use a generous token\n # bucket size so we can make lots of requests quickly.\n log_path = LOG_FILE_PATTERN % this_node.port\n with open(filename, 'w') as f:\n f.write(dedent(\"\"\"\\\n [http]\n bind-address = {this_node.ip}\n bind-port = {this_node.port}\n\n [throttling]\n max_tokens = 1000\n\n [logging]\n folder = {log_path}\n level = 5\n \"\"\").format(**locals()))\n\n\ndef write_cluster_conf(filename, this_node, joining, nodes, leaving):\n # Create a configuration file for a chronos process\n with open(filename, 'w') as f:\n f.write(dedent(\"\"\"\\\n [cluster]\n localhost = {this_node.ip}:{this_node.port}\n \"\"\").format(**locals()))\n for node in joining:\n f.write('joining = {node.ip}:{node.port}\\n'.format(**locals()))\n for node in nodes:\n f.write('node = {node.ip}:{node.port}\\n'.format(**locals()))\n for node in leaving:\n f.write('leaving = {node.ip}:{node.port}\\n'.format(**locals()))\n\n\n# Test the resynchronization operations for Chronos.\nclass ChronosLiveTests(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n # Start the flask app in its own thread\n threads = []\n t = threading.Thread(target=run_app)\n t.daemon = True\n threads.append(t)\n t.start()\n sleep(1)\n\n def setUp(self):\n # Track the Chronos processes and timer pops\n global receiveCount\n global processes\n global timerCounts\n receiveCount = 0\n processes = []\n timerCounts = []\n\n def tearDown(self):\n # Kill all the Chronos processes\n kill_nodes(0, len(processes))\n\n def assert_correct_timers_received(self, expected_number):\n # Check that enough timers pop as expected.\n # This should be as many as were added in the first place.\n # Ideally, we'd be checking where the timers popped from, but that's\n # not possible with these tests (as everything looks like it comes\n # from 127.0.0.1)\n self.assertEqual(receiveCount,\n expected_number,\n ('Incorrect number of popped timers: received %i, expected exactly %i' %\n (receiveCount, expected_number)))\n\n for i in range(expected_number):\n assert str(i) in timerCounts, \"Missing timer pop for %i\" % i\n\n def write_config_for_nodes(self, staying, joining=[], leaving=[]):\n # Write configuration files for the nodes\n for num in staying + joining + leaving:\n write_conf(CONFIG_FILE_PATTERN % num,\n chronos_nodes[num])\n write_cluster_conf(CLUSTER_CONFIG_FILE_PATTERN % num,\n chronos_nodes[num],\n [chronos_nodes[i] for i in joining],\n [chronos_nodes[i] for i in staying],\n [chronos_nodes[i] for i in leaving])\n\n def test_scale_up(self):\n # Test that scaling up works. This test creates 2 Chronos nodes,\n # adds 100 timers, scales up to 4 Chronos nodes, then checks that\n # 100 timers pop.\n\n # Start initial nodes and add timers\n self.write_config_for_nodes([0,1])\n start_nodes(0, 2)\n create_timers(chronos_nodes[0], 100)\n\n # Scale up\n self.write_config_for_nodes([0,1], [2,3])\n start_nodes(2, 4)\n node_reload_config(0, 2)\n node_trigger_scaling(0, 4)\n\n # Check that all the timers have popped\n sleep(12)\n self.assert_correct_timers_received(100)\n\n def test_scale_down(self):\n # Test that scaling down works. This test creates 4 Chronos nodes,\n # adds 100 timers, scales down to 2 Chronos nodes, then checks that\n # 100 timers pop.\n\n # Start initial nodes and add timers\n self.write_config_for_nodes([0,1,2,3])\n start_nodes(0, 4)\n create_timers(chronos_nodes[0], 100)\n\n # Scale down\n self.write_config_for_nodes([0,1], [], [2,3])\n node_reload_config(0, 4)\n node_trigger_scaling(0, 4)\n kill_nodes(2, 4)\n\n # Check that all the timers have popped\n sleep(12)\n self.assert_correct_timers_received(100)\n\n def test_scale_up_scale_down(self):\n # Test a scale up and scale down. This test creates 2 Chronos nodes,\n # and adds 100 timers. It then scales up to 4 Chronos nodes, then\n # scales back down to the 2 new Chronos nodes. It then checks that\n # 100 timers pop.\n\n # Start initial nodes and add timers\n self.write_config_for_nodes([0,1])\n start_nodes(0, 2)\n create_timers(chronos_nodes[0], 100)\n\n # Scale up\n self.write_config_for_nodes([0,1], [2,3])\n start_nodes(2, 4)\n node_reload_config(0, 2)\n node_trigger_scaling(0, 4)\n sleep(10)\n\n # Scale down the initial nodes\n self.write_config_for_nodes([2,3], [], [0,1])\n node_reload_config(0, 4)\n node_trigger_scaling(0, 4)\n\n # Check that all the timers have popped\n sleep(12)\n self.assert_correct_timers_received(100)\n\n def test_scale_up_and_kill(self):\n # Test that scaling up definitely moves timers. This test creates 1\n # Chronos node and adds 100 timers. It then scales up to 2 Chronos\n # nodes, then kills the first node. It then checks all 100 timers pop\n\n # Start initial nodes and add timers\n self.write_config_for_nodes([0])\n start_nodes(0, 1)\n create_timers(chronos_nodes[0], 100)\n\n # Scale up\n self.write_config_for_nodes([0], [1])\n start_nodes(1, 2)\n node_reload_config(0, 1)\n node_trigger_scaling(0, 2)\n\n # Now kill the first node\n kill_nodes(0, 1)\n\n # Check that all the timers have popped\n sleep(12)\n self.assert_correct_timers_received(100)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"scripts/chronos_resync.py","file_name":"chronos_resync.py","file_ext":"py","file_size_in_byte":12111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"125598613","text":"from data.states.main_menu import main_menu\nfrom data.states import shop, levels, battle\nfrom . import setup, tools\nfrom . import constants as c\n\n\nTOWN = 'town'\nMAIN_MENU = 'main menu'\nCASTLE = 'castle'\nHOUSE = 'house'\nINN = 'Inn'\nARMOR_SHOP = 'armor shop'\nWEAPON_SHOP = 'weapon shop'\nMAGIC_SHOP = 'magic shop'\nPOTION_SHOP = 'potion shop'\nPLAYER_MENU = 'player menu'\nOVERWORLD = 'overworld'\nBROTHER_HOUSE = 'brotherhouse'\nBATTLE = 'battle'\n\n\ndef main():\n \"\"\"Add states to control here\"\"\"\n run_it = tools.Control(setup.ORIGINAL_CAPTION)\n state_dict = {MAIN_MENU: main_menu.Menu(),\n TOWN: levels.LevelState(TOWN),\n CASTLE: levels.LevelState(CASTLE),\n HOUSE: levels.LevelState(HOUSE),\n OVERWORLD: levels.LevelState(OVERWORLD, True),\n BROTHER_HOUSE: levels.LevelState(BROTHER_HOUSE),\n INN: shop.Inn(),\n ARMOR_SHOP: shop.ArmorShop(),\n WEAPON_SHOP: shop.WeaponShop(),\n MAGIC_SHOP: shop.MagicShop(),\n POTION_SHOP: shop.PotionShop(),\n BATTLE: battle.Battle()\n }\n\n run_it.setup_states(state_dict, c.MAIN_MENU)\n run_it.main()","sub_path":"data/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"508005807","text":"# coding:utf-8\nimport datetime\nimport json\nimport random\nimport re\nimport time\n\nimport chardet\nimport requests\nfrom lxml import etree\nfrom lxml.etree import XMLSyntaxError\nfrom utils.Comm import CommSession\n\n\nclass GuangDa():\n\n def __init__(self):\n self.charset_re = re.compile(r']', flags=re.I)\n self.pragma_re = re.compile(r']', flags=re.I)\n self.index_url = 'https://www.cib.com.cn/cn/index.html'\n self.session = self.instance_session(self.index_url)\n self.base_url = 'http://www.cebbank.com'\n self._url_format = lambda url: self.base_url + url\n\n def _coding(self, response):\n if self.charset_re.findall(response.text):\n response.encoding = self.charset_re.findall(response.text)[0]\n elif self.pragma_re.findall(response.text):\n response.encoding = self.charset_re.findall(response.text)[0]\n else:\n temp = chardet.detect(response.content)\n response.encoding = temp['encoding']\n return response\n\n def _get(self, url, timeout=30, method='get', post_data=None, retry=3):\n \"\"\"\n 网页下载\n :param url:\n :return:resp\n :rtype: requests.Response\n \"\"\"\n time.sleep(random.randint(3, 5))\n if method == 'get':\n for i in range(retry):\n try:\n resp = self.session.get(url=url, timeout=timeout)\n if resp.status_code // 100 == 2:\n return resp\n except requests.Timeout:\n continue\n raise requests.RequestException('requests error {}'.format(url))\n elif method == 'post' and post_data is not None:\n for i in range(retry):\n try:\n resp = self.session.post(url=url, data=post_data, allow_redirects=True, timeout=timeout)\n if resp.status_code == 200:\n return resp\n except requests.Timeout:\n continue\n raise requests.RequestException('requests error {}'.format(url))\n else:\n raise ValueError('func args error')\n\n @staticmethod\n def content2tree(response):\n if isinstance(response, requests.Response):\n return etree.HTML(response.text)\n else:\n try:\n return etree.HTML(response)\n except XMLSyntaxError as error:\n print(error)\n return response\n\n @staticmethod\n def instance_session(index_url=None):\n session = CommSession(verify=True).session(index_url) if index_url else CommSession(verify=True).session()\n return session\n\n @staticmethod\n def products_nature_format(html, data):\n nature = ''.join(''.join(html.xpath('//ul[@class=\\'fdsy_con_nr fl\\']/li[4]/text()')).split())\n if not nature:\n nature = ''.join(''.join(html.xpath('//ul[@class=\\'fdsy_con_nr fl\\']/li[2]/text()')).split())\n data['product_nature'] = nature\n\n @staticmethod\n def next_open_date(html, data):\n next_open_date = ''\n date_str = '%Y年%m月%d日'\n today = datetime.datetime.now().date()\n jzxxykfr1 = html.xpath(\"//*[@id='jzxxykfr1']/@value\") # 开放日_1\n jzxkfr1 = html.xpath(\"//*[@id='jzxkfr1']/@value\") # 开放日_2\n qchkfr1 = html.xpath(\"//*[@id='qchkfr1']/@value\") # 开放日_3\n kfskfr1 = html.xpath(\"//*[@id='kfskfr1']/@value\") # 开放日_4\n kfsxykfr1 = html.xpath(\"//*[@id='kfsxykfr1']/@value\") # 开放日_5\n if jzxxykfr1 and u'年' in jzxxykfr1[0] and datetime.datetime.strptime(jzxxykfr1[0], date_str).date() >= today:\n next_open_date = jzxxykfr1[0]\n elif jzxkfr1 and '年' in jzxkfr1[0] and datetime.datetime.strptime(jzxkfr1[0], date_str).date() >= today:\n next_open_date = jzxkfr1[0]\n elif qchkfr1 and u'年' in qchkfr1[0] and datetime.datetime.strptime(qchkfr1[0], date_str).date() >= today:\n next_open_date = qchkfr1[0]\n elif kfskfr1 and u'年' in kfskfr1[0] and datetime.datetime.strptime(kfskfr1[0], date_str).date() >= today:\n next_open_date = kfskfr1[0]\n elif kfsxykfr1 and u'年' in kfsxykfr1[0] and datetime.datetime.strptime(kfsxykfr1[0], date_str).date() >= today:\n next_open_date = kfsxykfr1[0]\n data['next_open_date'] = next_open_date.replace(u'年', u'-').replace(u'月', '-').replace(u'日', u'')\n\n def parse_detail(self, data):\n # print data.get('url')\n # url = 'http://www.cebbank.com/site/gryw/yglc/lccpsj/yxl94/29834128/index.html'\n html = self.content2tree(self._coding(self._get(data.get('url'), method='get')))\n # html = self.content2tree(self._coding(self._get(url, method='get')))\n self.products_nature_format(html, data)\n data['product_type'] = ''\n file_url = ''.join(html.xpath('//div[2]/div[@class]//p/a/@href'))\n data['file_url'] = self._url_format(file_url) if file_url else ''\n # if not data.get('sales_start_date') or not data.get('sales_start_date'):\n self.next_open_date(html, data)\n # else:\n # data['next_open_date'] = ''\n self._save_data(data)\n\n @staticmethod\n def final_yield_format(tr, data):\n return_yield = ''.join(''.join(tr.xpath('./td[6]/div//text()')).split())\n try:\n final_yield = return_yield[0:return_yield.index('%') + 1] if '.' in return_yield else ''\n except ValueError as e:\n print(e)\n final_yield = return_yield\n if '-' in final_yield:\n data['highest_yield'] = final_yield.split('-')[1] if '-' in final_yield else final_yield\n data['lowest_yield'] = final_yield.split('-')[0] + '%' if '-' in final_yield else final_yield\n else:\n data['highest_yield'] = data['lowest_yield'] = final_yield\n\n @staticmethod\n def date_format(tr, data):\n start_date = ''.join(tr.xpath('./td[3]/text()')[0].split(u':')[1].split())\n data['sales_start_date'] = start_date + ' 00:00:00' if len(start_date) >= 9 else ''\n end_date = ''.join(tr.xpath('./td[3]/text()')[1].split(u':')[1].split())\n data['sales_end_date'] = end_date + ' 00:00:00' if len(end_date) >= 9 else ''\n\n def parse_data(self, response, data):\n html = self.content2tree(response)\n trs = html.xpath('//tr[position()>1]')\n for tr in trs:\n data['product_name'] = ''.join(''.join(tr.xpath('./td[1]//text()')).strip()) # product_name\n self.date_format(tr, data)\n data['value_date'] = ''\n self.final_yield_format(tr, data)\n data['product_term'] = tr.xpath('./td[5]/text()')[0].strip() # product_term\n data['min_purchase_amount'] = tr.xpath('./td[4]/text()')[0].strip() # min_purchase_amount\n data['sales_target'] = ''\n data['sales_area'] = ''\n data['currency'] = tr.xpath('./td[2]/text()')[0].strip()\n data['url'] = self._url_format(''.join(''.join(tr.xpath('./td[1]/a/@href')).strip()))\n self.parse_detail(data)\n\n def get_page_num(self, response):\n res = re.search(pattern='class=\"fl\">(\\d+) /messages',\n 'resource_methods': ['POST'],\n 'item_methods': [],\n 'item_title': 'Messages',\n 'description': 'Messages between users',\n 'schema': {\n 'conversation': {\n 'type': 'objectid',\n 'required': True,\n 'data_relation': {\n 'resource': 'conversations',\n 'embeddable': True\n },\n },\n 'from': {\n 'type': 'string',\n 'required': False\n },\n 'text': {\n 'type': 'string',\n 'required': False\n },\n }\n },\n}\n","sub_path":"api/kiln_share/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":4660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"625906119","text":"from radical.entk import Pipeline, Stage, Task, AppManager\nimport os\nimport traceback\nimport sys\nimport pickle \nfrom glob import glob\nimport radical.utils as ru\nimport shutil\n\n\n\n# ------------------------------------------------------------------------------\n# Set default verbosity\n\nif os.environ.get('RADICAL_ENTK_VERBOSE') == None:\n os.environ['RADICAL_ENTK_VERBOSE'] = 'INFO'\n\ncur_dir = os.path.dirname(os.path.abspath(__file__))\nhostname = os.environ.get('RMQ_HOSTNAME','localhost')\nport = int(os.environ.get('RMQ_PORT',5672))\n\nlogger = ru.Logger(__name__, level='DEBUG')\n\nclass HyperSpacePipeline(Pipeline):\n def __init__(self, name):\n super(HyperSpacePipeline, self).__init__()\n self.name = name \n\n\nclass OptimizationStage(Stage):\n def __init__(self, name):\n super(OptimizationStage, self).__init__()\n self.name = name \n\nclass OptimizationTask(Task):\n def __init__(self, name, results_dir):\n # this task will execute Bayesian optimizations\n \n super(OptimizationTask, self).__init__()\n self.name = name\n self.copy_input_data = []\n self.copy_input_data += ['$SHARED/example.py']\n self.copy_input_data += ['$SHARED/t10k-images-idx3-ubyte.gz']\n self.copy_input_data += ['$SHARED/t10k-labels-idx1-ubyte.gz']\n self.copy_input_data += ['$SHARED/train-images-idx3-ubyte.gz']\n self.copy_input_data += ['$SHARED/train-labels-idx1-ubyte.gz']\n self.pre_exec = []\n self.pre_exec += ['export PATH=\"/home/dakka/miniconda3/bin:$PATH\"']\n self.pre_exec += ['export LD_LIBRARY_PATH=\"/home/dakka/miniconda3/lib:$LD_LIBRARY_PATH\"']\n self.pre_exec += ['module load mpi/gcc_openmpi']\n self.pre_exec += ['source activate ve_hyperspace']\n # self.pre_exec += ['module load mpi/intel_mpi'] \n self.executable = ['python']\n self.arguments = ['example.py', '--results_dir', results_dir]\n self.cpu_reqs = {'processes': 4, 'thread_type': None, 'threads_per_process': 28, 'process_type': 'MPI'}\n\n\nif __name__ == '__main__':\n\n # arguments for AppManager\n\n hparams = 2\n\n p = HyperSpacePipeline(name = 'hyperspace_pipeline')\n\n # Stage 1: single task that spawns n_optimizations using mpirun\n\n s1 = OptimizationStage(name = 'optimizations')\n\n t1 = OptimizationTask(name = 'analysis_1', results_dir = '/pylon5/mc3bggp/dakka/hyperspace_data/results_1/skopt/space4') \n\n s1.add_tasks(t1)\n p.add_stages(s1)\n\n s2 = OptimizationStage(name = 'optimizations')\n\n t2 = OptimizationTask(name = 'analysis_2', results_dir = '/pylon5/mc3bggp/dakka/hyperspace_data/results_2/skopt/space4' )\n\n s2.add_tasks(t2)\n p.add_stages(s2)\n \n\n s3 = OptimizationStage(name = 'optimizations')\n\n t3 = OptimizationTask(name = 'analysis_3', results_dir = '/pylon5/mc3bggp/dakka/hyperspace_data/results_3/skopt/space4')\n\n s3.add_tasks(t3)\n p.add_stages(s3)\n \n\n logger.info('adding stage {} with {} tasks'.format(s1.name, s1._task_count))\n logger.info('adding pipeline {} with {} stages'.format(p.name, p._stage_count))\n\n # Create Application Manager\n appman = AppManager(hostname=hostname, port=port)\n\n res_dict = {\n\n 'resource': 'xsede.bridges',\n 'project' : 'mc3bggp',\n 'queue' : 'RM',\n 'walltime': 90,\n 'cpus': (2**hparams)*28,\n 'access_schema': 'gsissh'\n }\n\n\n # Assign resource manager to the Application Manager\n appman.resource_desc = res_dict\n appman.shared_data = []\n appman.shared_data += ['/home/jdakka/hyperspace/constellation/constellation/gbm/space2/optimize.py']\n appman.shared_data += ['/home/jdakka/hyperspace/constellation/constellation/data/fashion/t10k-images-idx3-ubyte.gz']\n appman.shared_data += ['/home/jdakka/hyperspace/constellation/constellation/data/fashion/t10k-labels-idx1-ubyte.gz']\n appman.shared_data += ['/home/jdakka/hyperspace/constellation/constellation/data/fashion/train-images-idx3-ubyte.gz']\n appman.shared_data += ['/home/jdakka/hyperspace/constellation/constellation/data/fashion/train-labels-idx1-ubyte.gz']\n appman.shared_data += ['%s/binaries/example.py' %cur_dir]\n \n \n # Assign the workflow as a set of Pipelines to the Application Manager\n appman.workflow = [p]\n\n # Run the Application Manager\n appman.run()\n\n","sub_path":"hyperspace_workload/hyperspace-bridges.py","file_name":"hyperspace-bridges.py","file_ext":"py","file_size_in_byte":4383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"511593700","text":"### Challenge: How many drinks do you need to buy to throw a great party? \n# you will have a list of your friends, and their favorite drink. \n# you will also know how many drinks of a certain type are drunk per hour\n\n\n#list of your friends and their favorite drink\nfavorite_drinks = {'Adam':'Gin and Tonic','Angela':'Mate Vodka','Sven':'Whiskey','Alexandra':'Whiskey',\n 'Michael':'White Wine','Ariana':'Gin and Tonic','Thomas':'beer','Eduardo':'White Wine',\n 'Leanne':'Red Wine', 'Karla':'Whiskey', 'Taylor': 'Mate Vodka','Jonathan':'Water'}\n\n\n#types of drinks people drink, with lists of examples\n\nbig_list = [ ['Gin and Tonic', 'Mate Vodka', 'Rum and Coke'], ['beer'], ['Red Wine', 'White Wine'], ['whiskey', 'gin', 'vokda'], ['tea', 'water', 'orange juice']]\n\nfor list in big_list:\n for item in list:\n item.title()\n\n\n# number of drinks per hour people drink, depeneding on the type. \nnumber_of_drinks_per_hour_per_type = {'0':1, '1':3, '2':2,'3':2,'4':3}\n\ndrinks = ['cocktails', 'beers', 'wines', 'liquors', 'nonalcoholic']\n\ndef howmuch(hours):\n amount = [0, 0, 0, 0, 0]\n \n for name, drink in favorite_drinks.items():\n counter = 0\n for beveragetype in big_list:\n if drink in beveragetype:\n amount[counter] += number_of_drinks_per_hour_per_type[str(counter)]\n counter +=1\n counter = 0\n for number in amount:\n number *= hours \n print(drinks[counter],': ', number)\n counter +=1\n \n\nhowmuch(int(input()))\n\n\n\n\n","sub_path":"databases/database_intro.py","file_name":"database_intro.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"604731353","text":"#通过poot获取到将节点信息进行解析\nfrom shutil import rmtree\nfrom xml.dom.minidom import parse\nimport os\nfrom io import StringIO\nfrom ..adb.adb import ADB,ADB_PATH,TEMP_UI_XML_SAVE_PATH\nfrom .uIProxy import Node\nfrom . import NOT_FOUND_UI\nfrom .uIProxy import UiProxy\nfrom . import inforPrint\nfrom . import by as By\nclass Poot():\n @staticmethod\n def getNowConnectDevice():\n adb_path = \"%s\" % ADB_PATH\n str = os.popen('%s devices' % adb_path)\n str = str.read()\n f = StringIO(str)\n deviceList = []\n while True:\n s = f.readline()\n if s == '':\n break\n s = s.split()\n if s != [] and (s[0] != 'List' or s[0]=='*'):\n deviceList.append([s[0],s[1]])\n if deviceList == []:\n return []\n return deviceList\n def __init__(self,device_id:str=None,screenshot_each_action=False):\n self._device_id=device_id #当前设备的连接id\n if not device_id:\n #主动获取device_id\n devices = ADB.getNowConnectDevice()\n if len(devices) > 0:\n self._device_id=devices[0]\n else:\n raise BaseException(\"无设备连接!\")\n pass\n self._is_freeze=False #是否处于冻结ui状态\n self._node=None #ui信息\n self._adb=ADB(self._device_id) #adb 实例\n self._time_out=2#获取ui的超时时间\n self._sleep_spacing=1#单次获取ui睡眠间隔\n self._screenshot_each_action=screenshot_each_action\n\n def __get_sleep_count(self,time_out:int=None):\n if time_out==None:\n return self._time_out/self._sleep_spacing\n else:\n return time_out/self._sleep_spacing\n\n def __get_ui(self):\n '''\n 获取ui\n :return:\n '''\n count=1\n while count<3:\n if not self._adb.getNowUI():\n count+=1\n continue\n xml = \"%s/%s.xml\" % (TEMP_UI_XML_SAVE_PATH, self._device_id)\n if os.path.exists(xml):\n DomTree = parse(xml)\n root_Node = DomTree.documentElement\n node = Node(root_Node)\n rmtree(os.path.dirname(xml))\n self._node=node\n return True\n raise BaseException(\"获取UIxml文件失败\")\n\n def __call__(self,text=None,time_out:int=None,*,resource_id=None,package=None,clazz=None,desc=None,name=None,part_text=None,**kwargs)->UiProxy:\n '''\n :param infor:\n :param by:\n :param time: ui查找时间\n :rtype:UiProxy\n :return:\n '''\n if resource_id:\n kwargs[\"resource_id\"]=resource_id\n if package:\n kwargs[\"package\"]=package\n if clazz:\n kwargs[\"clazz\"]=clazz\n if desc:\n kwargs[\"desc\"]=desc\n if name:\n kwargs[\"name\"]=name\n if text:\n kwargs[\"text\"]=text\n if part_text:\n kwargs[\"part_text\"]=part_text\n if (not self._is_freeze) or (not self._node):\n # 如果ui不是冻结的\n self.__get_ui()\n if kwargs:\n # 返回对应的节点代理ui\n proxy = self.__resolve_node(self._node,self._screenshot_each_action)\n proxy=proxy.offspring(**kwargs)\n if not proxy:\n raise BaseException(NOT_FOUND_UI)\n return proxy\n else:\n # 返回根节点代理ui\n return self.__resolve_node(self._node,self._screenshot_each_action)\n\n def freeze(self):\n self._is_freeze=True\n self.__get_ui()\n return self\n\n def clear_freezed(self):\n self._is_freeze=False\n return self\n\n def unfreeze(self):\n self._is_freeze = False\n return self\n\n def __enter__(self):\n self._is_freeze = True\n self.__get_ui()\n return self\n def __exit__(self, exc_type, exc_val, exc_tb):\n self._is_freeze=False\n def __resolve_node(self,node,screenshot_each_action:bool)->UiProxy:\n #传入xml文件信息,并解析其节点信息存储至node\n return UiProxy(node,self._adb,screenshot_each_action)\n def set_find_ui_timeout(self,timeout):\n '''\n 设置获取ui的超时时间\n :param timeout:\n :return:\n '''\n self._time_out=timeout\n def set_find_ui_time_spacing(self,time_spacing):\n '''\n 设置获取ui睡眠间隔时间\n :param time_spacing:\n :return:\n '''\n self._sleep_spacing=time_spacing\n\n @property\n def device_id(self):\n return self._device_id\n\n @property\n def adb(self):\n return self._adb\n\n def get_ui(self):\n '''\n 返回xml文件内容\n :return:\n '''\n return self().get_tree()\n\n\n @inforPrint(infor=\"返回桌面\")\n def return_home(self,*,infor=None,beforeTime=0,endTime=0):\n '''\n 回到桌面\n :return:\n '''\n self._adb.returnHome()\n\n @inforPrint(infor=\"滚动\")\n def scroll(self, direction='vertical', percent=0.6, duration=2000,*,infor=None,beroeTime=0,endTime=0):\n \"\"\"\n 来自airtest的源代码\n :param direction:滑动方向\n :param percent:滑动百分比\n :param duration:滑动时间 ms\n \"\"\"\n if direction not in ('vertical', 'horizontal'):\n raise ValueError('Argument `direction` should be one of \"vertical\" or \"horizontal\". Got {}'\n .format(repr(direction)))\n x1,x2,y1,y2=0.5,0.5,0.5,0.5\n half_distance = percent / 2\n if direction == 'vertical':\n y1+=half_distance\n y2-=half_distance\n else:\n x1+=half_distance\n x2-=half_distance\n return self.swipe(x1,y1,x2,y2,time=duration)\n\n\n @inforPrint(infor=\"等待UI出现\")\n def wait_ui_appear(self,value,by:By=By.text,wait_time:int=30,*,infor=None,beroeTime=0,endTime=0):\n try:\n ui=self(infor=value,by=by,time_out=wait_time)\n if ui:\n return True\n except:\n return False\n\n @inforPrint(infor=\"滑动\")\n def swipe(self,x1:float,y1:float,x2:float,y2:float,time:int=200,*,infor=None,beroeTime=0,endTime=0):\n '''\n 按照比例进行滑动\n :param x1:\n :param y1:\n :param x2:\n :param y2:\n :param time: 毫秒\n :param infor:\n :param beroeTime:\n :param endTime:\n :return:\n '''\n width, hight = self._adb.get_screen_size()#获得屏幕宽高\n x1,y1=width*x1,hight*y1\n x2,y2=width*x2,hight*y2\n self._adb.swipe(x1,y1,x2,y2,time)\n\n @inforPrint(infor=\"点击\")\n def tap_x_y(self,x:float,y:float,times:int=None,*,infor=None,beroeTime=0,endTime=0):\n '''\n 均按照比例进行点击。\n :param x: 0-1的数\n :param y: 0-1的数\n :param infor:\n :param beroeTime:\n :param endTime:\n :param times:点击时长 毫秒\n :return:\n '''\n width,hight=self._adb.get_screen_size()\n x=width*x\n y=hight*y\n self._adb.tap_x_y(x,y,times)\n\n @inforPrint(infor=\"获得屏幕尺寸\")\n def get_screen_size(self,*,infor=None,beroeTime=0,endTime=0):\n return self._adb.get_screen_size()\n\n @inforPrint(infor=\"输入文字\")\n def input(self,text,*,infor=None,beroeTime=0,endTime=0):\n '''\n 本方法需要先获取输入框的焦点\n :param text:\n :param infor:\n :param beroeTime:\n :param endTime:\n :return:\n '''\n self._adb.input(text)\n","sub_path":"poot/core/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":7728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"348661408","text":"import logging\n\nimport prometheus_redis_client\nfrom django.http import HttpResponse\n\nlogger = logging.getLogger(__name__)\n\n\n\ndef ExportToDjangoView(request):\n \"\"\"Exports /metrics as a Django view.\n\n You can use django_prometheus.urls to map /metrics to this view.\n \"\"\"\n registry = prometheus_redis_client.REGISTRY\n metrics_page = registry.output()\n return HttpResponse(\n metrics_page,\n content_type='text/plain; version=0.0.4; charset=utf-8'\n )","sub_path":"django_redis_prometheus/exports.py","file_name":"exports.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"215045672","text":"import telegram\nfrom telegram.ext import Updater\nfrom django.conf import settings\n\nfrom .botactions import commands, group_updates, schedule\n\nfrom telegram.ext import messagequeue as mq\nfrom telegram.utils.request import Request\n\n\nclass MQBot(telegram.bot.Bot):\n '''A subclass of Bot which delegates send method handling to MQ'''\n def __init__(self, *args, is_queued_def=True, mqueue=None, **kwargs):\n super(MQBot, self).__init__(*args, **kwargs)\n # below 2 attributes should be provided for decorator usage\n self._is_messages_queued_default = is_queued_def\n self._msg_queue = mqueue or mq.MessageQueue()\n\n def __del__(self):\n try:\n self._msg_queue.stop()\n except:\n pass\n super(MQBot, self).__del__()\n\n @mq.queuedmessage\n def send_message(self, *args, **kwargs):\n '''Wrapped method would accept new `queued` and `isgroup`\n OPTIONAL arguments'''\n return super(MQBot, self).send_message(*args, **kwargs)\n\n\n# Starting the bot\n\nimport logging\nlogger = logging.getLogger(__name__)\nif settings.DEBUG:\n logging.basicConfig(level=logging.DEBUG)\nelse:\n logging.basicConfig(level=logging.INFO)\n\ntry:\n BOTS = settings.TELEGRAM_BOT\nexcept AttributeError as e:\n logger.error(\"Bots in settings are not defined\")\n raise e\n\nBOT_SETTINGS = BOTS.get('telegrambot')\nif not BOT_SETTINGS:\n logger.error(\"No settings for telegrambot provided\")\n exit(1)\n# Check token\nTOKEN = BOT_SETTINGS.get('TOKEN')\nif not TOKEN:\n logger.error(\"No token for telegrambot found\")\n exit(1)\n# Set flood limit if specified\n# and create updater with dispatcher\nBURST_LIMIT = BOT_SETTINGS.get('BURST_LIMIT')\nTIME_LIMIT = BOT_SETTINGS.get('TIME_LIMIT')\nif BURST_LIMIT and TIME_LIMIT:\n q = mq.MessageQueue(all_burst_limit=BURST_LIMIT, all_time_limit_ms=TIME_LIMIT)\n # set connection pool size for bot\n request = Request(con_pool_size=8)\n bot = MQBot(TOKEN, request=request, mqueue=q)\n updater = telegram.ext.updater.Updater(bot=bot, use_context=True)\nelse:\n updater = Updater(token=TOKEN, use_context=True)\ndispatcher = updater.dispatcher\n\ndef set_webhook():\n if BOT_SETTINGS.get('WEBHOOK_URL'):\n updater.bot.delete_webhook()\n updater.bot.set_webhook(BOT_SETTINGS.get('WEBHOOK_URL'))\n return True\n return False\n\ncommands.setup_handlers(dispatcher)\ngroup_updates.setup_handlers(dispatcher)\nschedule.setup_handlers(dispatcher)\n","sub_path":"mercury/telegrambot/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":2458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"375475082","text":"\n# LabTools - generic.py\n# Copyright 2019 Luca Arnaboldi\n\nimport inspect\nfrom PIL import Image\nfrom uncertainties import unumpy as unp\nimport numpy as np\n\ndef sprint(obj):\n \"\"\"\n Super Print. Print a variable with its name.\n \"\"\"\n def retrieve_name(var):\n \"\"\"\n Copy-pasted from StackOverflow\n \"\"\"\n callers_local_vars = inspect.currentframe().f_back.f_back.f_locals.items()\n return [var_name for var_name, var_val in callers_local_vars if var_val is var]\n \n obj_name = retrieve_name(obj)[0]\n \n print(\"{0}: {1}\".format(obj_name, obj))\n\ndef decibel(x):\n \"\"\"\n Convert a value in decibel.\n \"\"\"\n return 20. * unp.log10(x)\n\ndef crop_oscilloscope_image(image, result_image = None, area = None):\n \"\"\"\n Crop an acquisition of oscilloscope screen and save it in result_image.\n If result_image is None, the image is overwritten.\n Border define the interesting area. If None the default is used.\n \"\"\"\n AREA = (0, 23, 317, 245)\n \n if result_image is None:\n result_image = image\n if area is None:\n area = AREA\n \n img = Image.open(image)\n cropped_img = img.crop(AREA)\n \n cropped_img.save(result_image)\n \n","sub_path":"LabTools/utils/generic.py","file_name":"generic.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"113001272","text":"# Given an integer, return difference between product of digits and sum of its digits \n\n\ndef sub_prod_sum(n):\n # seperate nums \n n = [int(num) for num in str(n)]\n # calculate product \n p = 1\n for x in n:\n p *= x\n # calculate sum \n s = sum(n)\n # return prod - sum\n return p -s\n\n\nprint(sub_prod_sum(234)) # 15 \nprint(sub_prod_sum(4421)) # 21","sub_path":"interviews.school/subtract_prod_sum.py","file_name":"subtract_prod_sum.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"388537213","text":"#!/usr/bin/python\n\nimport sys\nsys.path.append('./gen-py')\n\nfrom lbs import lbsservice\nfrom thrift import Thrift\nfrom thrift.transport import TSocket\nfrom thrift.transport import TTransport\nfrom thrift.protocol import TBinaryProtocol\nfrom thrift.protocol import TCompactProtocol\nfrom lbs import ttypes\n\ndef main():\n ip = sys.argv[1]\n port = sys.argv[2]\n slng = float(sys.argv[3])\n slat = float(sys.argv[4])\n elng = float(sys.argv[5])\n elat = float(sys.argv[6])\n object_id = int(sys.argv[7])\n update(ip, port, slng, slat, elng, elat, object_id)\n\ndef update(ip,port,slng,slat,elng,elat,object_id):\n\n try:\n transport = TSocket.TSocket(ip, port)\n transport = TTransport.TFramedTransport(transport)\n protocol = TBinaryProtocol.TBinaryProtocol(transport)\n client = lbsservice.Client(protocol)\n transport.open()\n\n update = ttypes.point_pair_update()\n update.object_id = object_id\n update.slat = slat\n update.slng = slng\n update.elat = elat\n update.elng = elng\n # update.frag = \"\"\n update.timeout = 0\n # update.filter_status = -1\n update.coord_type = 2\n # update.speed = 123.00\n # update.accuracy = 321.00\n # update.gps_source = 1\n client.update_coords(\"LBS-GALILEO-ROUTE\", update)\n\n except ttypes.InvalidOperation as tx:\n raise\n\nif __name__ == '__main__':\n main()\n","sub_path":"updatelbs.py","file_name":"updatelbs.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"403766612","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nimport os\nfrom PIL import Image\nimport numpy\n\n\ndef get_size(w, h, trans_matrix):\n p = {}\n q = {}\n p['ll'] = numpy.array([[0, 0, 1]]).transpose()\n p['lr'] = numpy.array([[w-1, 0, 1]]).transpose()\n p['ul'] = numpy.array([[0, h-1, 1]]).transpose()\n p['ur'] = numpy.array([[w-1, h-1, 1]]).transpose()\n for key in p:\n q[key] = trans_matrix * p[key]\n\n x, y = [], []\n for key in p:\n x.append(q[key][0, 0])\n y.append(q[key][1, 0])\n x_min = min(x)\n x_max = max(x)\n y_min = min(y)\n y_max = max(y)\n hh = int(round(y_max - y_min)) + 1\n ww = int(round(x_max - x_min)) + 1\n return ww, hh, x_min, y_min\n\n\ndef affine_transform(image,\n matrix=None,\n scale=(1., 1.),\n shear=(0., 0.),\n rotation=0.\n ):\n \"\"\"\n Parameters\n ----------\n image: PIL image, 'L' mode.\n matrix: numpy matrix\n transformation matrix\n shear: (shx, shy) as array, list or tuple, optional\n Shear factors, 0.2 means 20%.\n rotation: float, optional\n Rotation angle as radians around the image center.\n scale: (sx, sy) as array, list or tuple, optional\n Scale factors.\n\n Result\n ------\n wrap_image: PIL image, 'L' mode.\n scale, shear and rotation.\n trans_matrix: numpy matrix\n transformation matrix\n \"\"\"\n if matrix is None:\n shx, shy = shear\n theta = rotation\n sx, sy = scale\n\n m_shear_x = numpy.matrix([[1, shx, 0], [0, 1, 0], [0, 0, 1]])\n m_shear_y = numpy.matrix([[1, 0, 0], [shy, 1, 0], [0, 0, 1]])\n m_rot = numpy.matrix([[numpy.cos(theta), -numpy.sin(theta), 0],\n [numpy.sin(theta), numpy.cos(theta), 0],\n [0, 0, 1]])\n m_scale = numpy.matrix([[sx, 0, 0], [0, sy, 0], [0, 0, 1]])\n\n trans_matrix = m_rot * m_shear_y * m_shear_x * m_scale\n else:\n trans_matrix = matrix\n\n w, h = image.size\n ww, hh, mnx, mny = get_size(w, h, trans_matrix)\n trans_matrix = numpy.matrix([[1, 0, -mnx],\n [0, 1, -mny],\n [0, 0, 1]]) * trans_matrix\n t_inv = numpy.linalg.inv(trans_matrix)\n t_inv_tuple = (t_inv[0, 0], t_inv[0, 1], t_inv[0, 2],\n t_inv[1, 0], t_inv[1, 1], t_inv[1, 2])\n\n image = image.transpose(Image.FLIP_TOP_BOTTOM)\n wrap_image = image.transform((ww, hh),\n Image.AFFINE, t_inv_tuple,\n resample=Image.BILINEAR)\n wrap_image = wrap_image.transpose(Image.FLIP_TOP_BOTTOM)\n return wrap_image, trans_matrix\n\n\nif __name__ == '__main__':\n os.chdir(os.path.abspath(os.path.dirname(__file__)))\n im = Image.open('lenna.bmp')\n # http://www.cis.rit.edu/~cnspci/courses/common/images/lena.bmp\n im2, A = affine_transform(\n im,\n scale=(2., 1.),\n shear=(0.2, 0.1),\n rotation=numpy.pi / 6.\n )\n im2.save('lenna2.bmp')\n","sub_path":"affinetrans.py","file_name":"affinetrans.py","file_ext":"py","file_size_in_byte":3078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"172904657","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\n\nurlpatterns = patterns('',\n # Examples:\n url(r'^$', 'marketer.views.home', name='home'),\n url(r'^lists/$', 'marketer.views.lists', name='lists'),\n url(r'^campaigns/$', 'marketer.views.campaigns', name='campaigns'),\n url(r'^statistics/$', 'marketer.views.statistics', name='statistics'),\n \n # url(r'^blog/', include('blog.urls')),\n\n url(r'^admin/', include(admin.site.urls)),\n)\n","sub_path":"marketer/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"166867333","text":"import os\r\nfrom os.path import join, exists, splitext\r\nfrom urllib.request import urlretrieve\r\nimport gzip\r\nimport shutil\r\nimport argparse\r\n\r\n\r\n# MNIST Data\r\nbase_url = \"http://yann.lecun.com/exdb/mnist/\"\r\ntrain_imgs = base_url + \"train-images-idx3-ubyte.gz\"\r\ntrain_labels = base_url + \"train-labels-idx1-ubyte.gz\"\r\ntest_imgs = base_url + \"t10k-images-idx3-ubyte.gz\"\r\ntest_labels = base_url + \"t10k-labels-idx1-ubyte.gz\"\r\n\r\n\r\ndef download_zip_file(base_url, user_path):\r\n '''\r\n Args:\r\n base_url: the MNIST data url\r\n user_path: the user's path to save data\r\n '''\r\n filename = base_url.split('/')[-1]\r\n filepath = join(user_path, filename)\r\n\r\n # If there is no user_path directory then make it! \r\n if not exists(user_path):\r\n os.mkdir(user_path)\r\n \r\n unzip = splitext(filepath)[0]\r\n\r\n filepath, _ = urlretrieve(base_url, filepath)\r\n print('\\nSuccessfully Downloaded', filename)\r\n \r\n return unzip, filename, filepath\r\n\r\n\r\ndef unzip_file(unzip, filename, filepath):\r\n '''\r\n Args:\r\n unzip: file without extension\r\n filename: file's name\r\n filepath: user_path/filename\r\n '''\r\n with gzip.open(filepath, 'rb') as f_in, open(unzip, 'wb') as f_out:\r\n print('\\nUnzipping the file ', filename)\r\n shutil.copyfileobj(f_in, f_out)\r\n print('\\nSuccessfully unzipped the file!')\r\n\r\n\r\ndef down_and_unzip(save_dir):\r\n '''\r\n Args:\r\n save_dir: save MNIST Data to 'save_dir'\r\n '''\r\n \r\n # If there is no save_dir directory then make it!\r\n if not exists(save_dir):\r\n os.makedirs(save_dir)\r\n \r\n # Only MNIST Data\r\n train_imgs_out, train_imgs_filename, train_imgs_filepath = download_zip_file(train_imgs, save_dir)\r\n unzip_file(train_imgs_out, train_imgs_filename, train_imgs_filepath)\r\n \r\n train_labels_out, train_labels_filename, train_labels_filepath = download_zip_file(train_labels, save_dir)\r\n unzip_file(train_labels_out, train_labels_filename, train_labels_filepath)\r\n \r\n test_imgs_out, test_imgs_filename, test_imgs_filepath = download_zip_file(test_imgs, save_dir)\r\n unzip_file(test_imgs_out, test_imgs_filename, test_imgs_filepath)\r\n \r\n test_labels_out, test_labels_filename, test_labels_filepath = download_zip_file(test_labels, save_dir) \r\n unzip_file(test_labels_out, test_labels_filename, test_labels_filepath)\r\n \r\n print(\"\\nEvery file had been downloaded as zipped and unzipped files\")\r\n\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser(\"Download MNIST Data automatically for you :) (There's only MNIST Data right now.)\") \r\n save_dir = join('Data', 'MNIST')\r\n parser.add_argument(\"--save_dir\", default=save_dir)\r\n args = parser.parse_args()\r\n down_and_unzip(args.save_dir)\r\n","sub_path":"get_data_1st_step.py","file_name":"get_data_1st_step.py","file_ext":"py","file_size_in_byte":2795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"414670326","text":"import openpyxl\nfrom openpyxl.utils import get_column_letter\nimport operator\nfrom datetime import *\n\nattribute_name = 'CREATE_DATE'\nsearch_date = '1992-12-31 00:00:00'\nstart_hour = time(2, 0)\nend_hour = time(3, 30)\n\ndef sort_table(table, col=0):\n return sorted(table, key=operator.itemgetter(col))\n\ndef get_hours(table, start, end):\n data = []\n for row in table:\n if end >= row[1] and start <= row[1]:\n data.append(row)\n return data\n\ndef main():\n book = openpyxl.load_workbook('example.xlsx')\n book.create_sheet('Sample')\n ws = book.active\n sheet = book.get_sheet_by_name(book.sheetnames[0])\n r = sheet.max_row\n c = sheet.max_column\n rmin = sheet.min_row\n cmin = sheet.min_column\n rmatrix = 1\n cmatrix = 1\n id_cell = 0\n for i in range(rmin, r+1):\n for j in range(cmin, c+1):\n if sheet.cell(row=i, column=j).value == 'ID' and id_cell == 0:\n id_cell = j\n if sheet.cell(row=i, column=j).value == attribute_name:\n rmatrix = i\n cmatrix = j\n i = r+1\n data = []\n aux = 0\n for row in ws.iter_rows(min_row=rmatrix+1, max_col=c, max_row=r):\n if aux != str(row[cmatrix - cmin + 1].value) and aux != 0:\n break\n if str(row[cmatrix - cmin + 1].value) == search_date :\n aux = search_date\n copy_row = []\n for cell in row:\n copy_row.append(cell.value)\n data.append(copy_row)\n book = openpyxl.Workbook()\n sheet = book.active\n for row in sort_table(get_hours(data, start_hour, end_hour), cmatrix - cmin):\n sheet.append(row)\n book.save(\"filtered.xlsx\")\n\nif __name__ == '__main__':\n main()","sub_path":"PruebaGlobal/sort_excel.py","file_name":"sort_excel.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"156816175","text":"# -*- coding: utf-8 -*-\n\nfrom marshmallow import ValidationError as MarshmallowValidationError\ntry:\n from webargs import ValidationError as WebargsValidationError\nexcept ImportError:\n HAS_WEBARGS = False\nelse:\n HAS_WEBARGS = True\n\nif HAS_WEBARGS:\n class ValidationError(WebargsValidationError, MarshmallowValidationError):\n \"\"\"Raised when a validation fails. Inherits from both\n webargs' ``ValidationError`` (if webargs is installed) and marshmallow's\n ``ValidationError`` so that the same validation functions can be used in either library.\n \"\"\"\n def __init__(self, message, *args, **kwargs):\n status_code = kwargs.pop('status_code', 400)\n WebargsValidationError.__init__(self, message, status_code=status_code)\n MarshmallowValidationError.__init__(self, message, *args, **kwargs)\nelse:\n class ValidationError(MarshmallowValidationError):\n \"\"\"Raised when a validation fails. Inherits from both\n webargs' ``ValidationError`` (if webargs is installed) and marshmallow's\n ``ValidationError`` so that the same validation functions can be used in either library.\n \"\"\"\n\n def __init__(self, message, field=None, **_):\n # make the signature compatible with the above impl for when not HAS_WEBARGS\n super(ValidationError, self).__init__(message, field)\n\n\nclass BaseConverter(object):\n \"\"\"Base converter validator that converts a third-party validators into\n marshmallow validators.\n \"\"\"\n\n def __init__(self, validators):\n self.validators = validators\n\n def make_validator(self, validator):\n raise NotImplementedError('Converter must implement make_validator')\n\n def __call__(self, val):\n errors = []\n for vendor_validator in self.validators:\n validator = self.make_validator(vendor_validator)\n try:\n validator(val)\n except ValidationError as err:\n errors.extend(err.messages)\n if errors:\n raise ValidationError(errors)\n","sub_path":"smore/validate/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":2078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"116732245","text":"from selenium import webdriver\nimport time\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\n\ndriver = webdriver.Firefox(executable_path=\"/home/anmol/PycharmProjects/prg1/geckodriver-v0.24.0-linux64/geckodriver\")\nwait = WebDriverWait(driver, 10)\n# driver.implicitly_wait(2)\ndriver.get(\"http://127.0.0.1:8000/admin/login/?next=/admin/\")\ndriver.maximize_window()\nusername = \"demo\"\npassword = \"demo\"\nusername_element = wait.until(EC.element_to_be_clickable((By.XPATH,\"//*[@id='id_username']\")))\nusername_element.send_keys(username)\npassword_element = wait.until(EC.element_to_be_clickable((By.XPATH,\"//*[@id='id_password']\")))\npassword_element.send_keys(password)\nlogin = wait.until(EC.element_to_be_clickable((By.XPATH,'/html/body/div/div[2]/form/div[2]/input')))\nlogin.click()\nassert driver.current_url==\"http://127.0.0.1:8000/admin/\"\n\nblog_posts = wait.until(\n EC.element_to_be_clickable((By.XPATH, '/html/body/div/div[3]/div[1]/ul/li[1]/ul/li[2]/a')))\nblog_posts.click()\ntitle = \"heroku\"\nopen_blog = wait.until(EC.element_to_be_clickable((By.LINK_TEXT, title)))\nopen_blog.click()\ntitle = \"heroku\"\ncontent = \"how to use heroku\"\nblog_title = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id=\"id_title\"]')))\nblog_title.clear()\nblog_title.send_keys(title)\niframe = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id=\"id_content_ifr\"]')))\ndriver.switch_to.frame(iframe)\nblog_content = wait.until(EC.element_to_be_clickable((By.XPATH, '/html/body/p')))\nscript = \"arguments[0].insertAdjacentHTML('afterEnd', arguments[1])\"\ndriver.execute_script(script, blog_content, content)\ndriver.switch_to.default_content()\nblog_save = wait.until(EC.element_to_be_clickable((By.XPATH, '/html/body/div[1]/div[4]/div/form/div/div/input[1]')))\nblog_save.click()\nbodyText = wait.until(EC.element_to_be_clickable((By.TAG_NAME, 'body')))\nassert \"successfully\" in bodyText.text\n\npages = wait.until(EC.element_to_be_clickable((By.XPATH, '/html/body/div/div[3]/div[1]/ul/li[1]/ul/li[1]/a')))\npages.click()\ntitle = \"Change Page Status\"\nopen_page = wait.until(EC.element_to_be_clickable((By.LINK_TEXT, title)))\nopen_page.click()\ntitle = \"Change Page Status\"\ncontent = \"how to use heroku\"\npage_title = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id=\"id_title\"]')))\npage_title.clear()\npage_title.send_keys(title)\niframe = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id=\"id_content_ifr\"]')))\ndriver.switch_to.frame(iframe)\npage_content = wait.until(EC.element_to_be_clickable((By.XPATH, '/html/body/p')))\nscript = \"arguments[0].insertAdjacentHTML('afterEnd', arguments[1])\"\ndriver.execute_script(script, page_content, content)\ndriver.switch_to.default_content()\npage_save = wait.until(EC.element_to_be_clickable((By.XPATH, '/html/body/div[1]/div[4]/div/form/div/div/input[1]')))\npage_save.click()\nbodyText = wait.until(EC.element_to_be_clickable((By.TAG_NAME, 'body')))\nassert \"successfully\" in bodyText.text\n\ndriver.quit()","sub_path":"test/blog_page_edit.py","file_name":"blog_page_edit.py","file_ext":"py","file_size_in_byte":3094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"569009288","text":"# coding: utf-8\n\nfrom flask import views\nfrom flask import Blueprint\nfrom flask import render_template\n\nfrom instub.errors import NotFound\nfrom instub.models import Category\nfrom instub.pager import Pager\n\nblueprint = Blueprint('category_view', __name__)\n\n\nclass CategoryView(views.MethodView):\n\n def get(self, name):\n category = Category.query.filter(Category.name == name).first()\n if not category:\n return NotFound('Category Not Found')\n pager = Pager(category.medias_count(category.id))\n medias = category.medias(category.id, limit=pager.per_page,\n offset=pager.offset)\n return render_template('medias_list.html', pager=pager,\n medias=medias, category=category)\n\n\nblueprint.add_url_rule('/category//',\n view_func=CategoryView.as_view(b'category'),\n endpoint='category')\n","sub_path":"instub/views/category.py","file_name":"category.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"328859088","text":"\nimport sys\nsys.path.append('./src/validation')\n\nfrom path_tools import *\nfrom opt_Kernel import *\nfrom sm_opt_Kernel import *\nfrom AE_validate import *\nfrom AE import *\nfrom AE_RFF import *\nfrom MLP import *\nfrom MLP_RFF import *\nimport numpy as np\nimport pickle\nimport sys\nimport shutil\nimport time\n\n\ndef import_pretrained_network(db, keyVal, stage_name, ignore_in_batch=False):\n\tprint('\\tLoading %s from %s...'%(stage_name, keyVal))\n\tif ignore_in_batch:\n\t\tif 'running_batch_mode' in db: \n\t\t\tprint('\\t\\tFailed...')\n\t\t\treturn False\n\n\tensure_path_exists('./pretrained')\n\tensure_path_exists('./pretrained/' + db['data_name'])\n\tpath_list = ['./pretrained/' + db['data_name'] + '/' + db['data_name'] + '_' + stage_name + '.pk']\n\n\tif path_list_exists(path_list):\n\t\tsaved_networks = pickle.load( open( path_list[0], \"rb\" ) )\n\t\t\n\t\tif keyVal not in db:\n\t\t\ttest1 = True\n\t\t\ttest2 = True\n\t\t\ttest3 = True\n\t\t\ttest4 = True\n\t\telse:\n\t\t\ttest1 = saved_networks.input_size == db[keyVal].input_size\n\t\t\ttest2 = saved_networks.output_dim == db[keyVal].output_dim\n\t\t\ttest3 = saved_networks.net_depth == db[keyVal].net_depth\n\t\t\ttest4 = saved_networks.__class__.__name__ == db[keyVal].__class__.__name__\n\n\t\tif test1 and test2 and test3 and test4:\n\t\t\tdb[keyVal] = saved_networks\n\t\t\tprint('\\t\\tSucessful...')\n\t\t\treturn True\n\t\telse:\n\t\t\tprint('\\t\\tloaded input size : %d, current input size : %d'%(saved_networks.input_size, db[keyVal].input_size))\n\t\t\tprint('\\t\\tloaded output size : %d, current output size : %d'%(saved_networks.output_dim, db[keyVal].output_dim))\n\t\t\tprint('\\t\\tloaded depth : %d, current depth : %d'%(saved_networks.net_depth, db[keyVal].net_depth))\n\t\t\tprint('\\t\\tloaded model : %s, current model: %s'%(saved_networks.__class__.__name__, db[keyVal].__class__.__name__))\n\n\n\tprint('\\t\\tFailed...')\n\treturn False\n\n\ndef export_pretrained_network(db, keyVal, stage_name, ignore_in_batch=False):\n\tif ignore_in_batch:\n\t\tif 'running_batch_mode' in db: return False\n\n\tensure_path_exists('./pretrained')\n\tensure_path_exists('./pretrained/' + db['data_name'])\n\tpth = './pretrained/' + db['data_name'] + '/' + db['data_name'] + '_' + stage_name + '.pk'\n\tpickle.dump( db[keyVal], open(pth, \"wb\" ) )\n\n\ndef load_db(db):\n\tif len(sys.argv) == 1: return db\n\tif sys.argv[1] == 'at_discovery':\n\t\tdb['running_batch_mode'] = True\n\t\treturn db\n\n\tfin = open(sys.argv[1],'r')\n\tcmds = fin.readlines()\n\tfin.close()\n\tdb['running_batch_mode'] = True\n\t\n\tfor i in cmds: \n\t\ttry: exec(i)\n\t\texcept:\n\t\t\tprint('Attempted to execuse command : %s'%i)\n\t\t\timport pdb; pdb.set_trace()\n\treturn db\n\ndef save_to_lowest_end2end(db):\n\tensure_path_exists('./pretrained')\n\tensure_path_exists('./pretrained/' + db['data_name'])\n\tpth = './pretrained/' + db['data_name'] + '/' + db['data_name'] + '_best_' + db['knet'].__class__.__name__ + '.pk'\n\tlowest_error_list = './pretrained/' + db['data_name'] + '/' + 'lowest_error_list.txt'\n\tmutex = './pretrained/' + db['data_name'] + '/' + db['data_name'] + '_best_end2end.writing'\n\ttmp_writing = './pretrained/' + db['data_name'] + '/' + 'tmp.' + str(int(10000000*np.random.rand()))\n\n\tif path_list_exists([pth]):\n\t\tbest_knet = pickle.load( open( pth, \"rb\" ) )\n\t\tif db['knet'].end2end_error < best_knet.end2end_error:\n\t\t\tpickle.dump( db['knet'] , open(tmp_writing, \"wb\" ) )\n\telse:\n\t\tpickle.dump( db['knet'] , open(tmp_writing, \"wb\" ) )\n\n\n\twhile os.path.exists(mutex): \n\t\tprint('waiting .....')\n\t\ttime.sleep(20*np.random.rand())\n\n\tcreate_file(mutex)\n\tfin = open(lowest_error_list,'a')\n\tfin.write('%.4f\\n'%db['knet'].end2end_error)\n\tfin.close()\n\tif os.path.exists(tmp_writing): shutil.move(tmp_writing, pth)\n\tdelete_file(mutex)\n\n\n","sub_path":"src/helper/storage.py","file_name":"storage.py","file_ext":"py","file_size_in_byte":3611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"355287613","text":"from course import Course\nimport plotting as plt\n\nif __name__ == '__main__':\n\n\tsbc = Course(\"Referência\", \"SBC\", \"nucleos/computacao_ref.txt\")\n\ticmc_bcc = Course(\"BCC\", \"ICMC\", \"cursos/BCC_ICMC.txt\", sbc)\n\tufrgs = Course(\"BCC\", \"UFRGS\", \"cursos/BCC_UFRGS.txt\", sbc)\n\n\t#gera um grafico\n\tplt.plotOneBar(icmc_bcc);\n\tplt.plotTwoBar(ufrgs, icmc_bcc);\n\tplt.plotVenn(ufrgs, icmc_bcc);\n\tplt.plotTextList(ufrgs,icmc_bcc);\n","sub_path":"cac_app/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"322237774","text":"import operator\n\nimport torch\nimport torch.multiprocessing as mp\n\nuse_graph = True\n# --------------------------------------------------------------------------------------------------------------------#\n# Run state options\nrun_name = \"compare_test\"\ncontinue_from_last_run = False\ndeterministic_pop_init = True\ndummy_run = False\nmax_num_generations = 30\n\n# --------------------------------------------------------------------------------------------------------------------#\n# nn options\ndevice = 'gpu' # gpu | cpu\nnum_gpus = 1\nnum_workers = 0 # this doesn't work in parallel because daemonic processes cannot spawn children\ndataset = 'cifar10'\ndata_path = ''\nnumber_of_epochs_per_evaluation = 5\nbatch_size = 256\n\n# --------------------------------------------------------------------------------------------------------------------#\n# fully train options\nfully_train = False\n\nnum_epochs_in_full_train = 300\nnum_augs_in_full_train = 1\n# multiplies feature count of every layer by this number to increase or decrease bandwidth\nfeature_multiplier_for_fully_train = 1\n\ntoss_bad_runs = False\ndrop_learning_rate = True\ndrop_period = 30\ndrop_factor = 1.2\nuse_adaptive_learning_rate_adjustment = False\n\n# --------------------------------------------------------------------------------------------------------------------#\n# Multiobjective options\nsecond_objective = '' # network_size | network_size_adjusted | network_size_adjusted_2\nsecond_objective_comparator = operator.lt # lt for minimisation, gt for maximisation\nthird_objective = ''\nthird_objective_comparator = operator.lt\n\nmoo_optimiser = 'cdn' # cdn | nsga\n\n# --------------------------------------------------------------------------------------------------------------------#\n# Data augmentation options\nevolve_data_augmentations = False\n\ncolour_augmentations = True\nallow_da_scheme_ignores = True\nda_ignore_chance = 0.2\ntrain_on_origonal_data = True\nbatch_by_batch = False\n\n# --------------------------------------------------------------------------------------------------------------------#\n# module retention options\nmodule_retention = True\nfitness_aggregation = 'max' # max | avg\n\nallow_species_module_mapping_ignores = True\nallow_cross_species_mappings = False\n# --------------------------------------------------------------------------------------------------------------------#\n# specitation options\nspeciation_overhaul = True\n\nblueprint_nodes_use_representatives = False # section 3.2.4 Sasha's paper\nrep_mutation_chance_early = 0.6\nrep_mutation_chance_late = 0.2\nsimilar_rep_mutation_chance = 0.2 # chance to mutate all of the nodes with the same representative in the same way\nclosest_reps_to_consider = 6\n\nuse_graph_edit_distance = False\nignore_disabled_connections_for_topological_similarity = False\n\nallow_attribute_distance = False\n# --------------------------------------------------------------------------------------------------------------------#\n# mutation extension options\nadjust_species_mutation_magnitude_based_on_fitness = False\nadjust_mutation_magnitudes_over_run = False\nallow_elite_cloning = False\n\nbreed_mutagens = False\nmutagen_breed_chance = 0.5\n\n\n# --------------------------------------------------------------------------------------------------------------------#\n\n\n# --------------------------------------------------------------------------------------------------------------------#\ndef get_device():\n \"\"\"Used to obtain the correct device taking into account multiple GPUs\"\"\"\n\n gpu = 'cuda:'\n gpu += '0' if num_gpus <= 1 else mp.current_process().name\n return torch.device('cpu') if device == 'cpu' else torch.device(gpu)\n\n\ndef is_parallel():\n return not (device == 'cpu' or num_gpus <= 1)\n","sub_path":"src/Config/Config.py","file_name":"Config.py","file_ext":"py","file_size_in_byte":3709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"349209276","text":"from skimage.segmentation import felzenszwalb\nfrom skimage.segmentation import mark_boundaries\nfrom skimage import img_as_float\nfrom sklearn.cluster import KMeans\nfrom colors.colors import load_colors\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport load_data\nimport operator\nimport math\n\n\ndef get_felzenswalb_segment(image):\n\t# Get segments\n\timg = img_as_float(image)\n\tsegments_fz = felzenszwalb(img, scale=100, sigma=0.93, min_size=200)\n\t\n\t# Find largest segment\n\tcounts = {}\n\tflat = segments_fz.flatten()\n\tfor i in range(flat.shape[0]):\n\t\tif flat[i] in counts:\n\t\t\tcounts[flat[i]] += 1\n\t\telse:\n\t\t\tcounts[flat[i]] = 1\n\tsegment = max(counts.iteritems(), key=operator.itemgetter(1))[0]\n\n\treturn segment, counts[segment], segments_fz\n\ndef get_segment_colors(largest_segment, count, segments, image):\n\tcolors = np.zeros(shape=(count, 3))\n\tcount = 0\n\tfor i in range(segments.shape[0]):\n\t\tfor j in range(segments.shape[1]):\n\t\t\tif segments[i][j] == largest_segment:\n\t\t\t\tcolors[count] = image[i][j]\n\t\t\t\tcount += 1\n\treturn colors\n\ndef get_largest_kmeans_cluster(colors):\n\tkmeans = KMeans(n_clusters=8, random_state=0).fit(colors)\n\n\telements_per_cluster = np.bincount(kmeans.labels_)\n\n\t#NOTE: returns the first largest value not all the largest\n\tlargest_pos = np.argmax(elements_per_cluster)\n\tlargest_cluster = kmeans.cluster_centers_[largest_pos] \n\n\treturn largest_cluster\n\ndef get_color(color):\n\t# http://www.rapidtables.com/web/color/RGB_Color.htm\n\t# red (255,0,0)\n\t# orange (255,165,0)\n\t# yellow (255,255,0)\n\t# green (0,255,0)\n\t# light blue (0,255,255)\n\t# blue (0,0,255)\n\t# purple (128,0,128)\n\t# pink (255,0,255)\n\t# dirt laundry (192,192,192)\n\tr = color[0]\n\tg = color[1]\n\tb = color[2]\n\t#colors = {\n\t#\t'red': ((255,0,0), 500),\n\t#\t'orange': ((255,165,0), 500),\n\t#\t'yellow': ((255,255,0), 500),\n\t#\t'green': ((0,255,0), 500),\n\t#\t'light blue': ((0, 255,255), 500),\n\t#\t'blue': ((0,0,255), 500),\n\t#\t'purple': ((128,0,128), 500),\n\t#\t'pink': ((255,0,255), 500),\n\t#\t'dirty laundry': ((192,192,192), 500),\n\t#\t}\n\tcolors = load_colors('colors/data.json')\n\tclosest = ('', 500)\n\tfor color, vals in colors.iteritems():\n\t\t# euclidean distance\n\t\tdistance = math.sqrt(pow(r - vals[0][0], 2) + pow(g - vals[0][1], 2) + pow(b - vals[0][2], 2))\n\t\tcolors[color] = (colors[color][0], distance)\n\t\tif distance < closest[1]:\n\t\t\tclosest = (color, distance)\n\n\treturn closest[0]\n\n\ndef run():\n\til = load_data.ImageLoader('fashion-data')\n\ttest_images = il.get_test_data()\n\n\tfor i in range(100):\n\t\tlargest_segment, count, segments = get_felzenswalb_segment(test_images[i])\n\t\tcolors = get_segment_colors(largest_segment, count, segments, test_images[i])\n\t\t# print(colors)\n\t\tquantized_common_color = get_largest_kmeans_cluster(colors)\n\t\tprint(quantized_common_color)\n\n\t\t# http://gauth.fr/2011/09/get-a-color-name-from-any-rgb-combination/\n\t\tcolor = get_color(quantized_common_color)\n\t\tprint(color)\n\n\t\timgplot = plt.imshow(mark_boundaries(test_images[i], segments))\n\t\tplt.show()\n\n\nif __name__ == '__main__':\n\trun()","sub_path":"kmeans_felzenszwalb.py","file_name":"kmeans_felzenszwalb.py","file_ext":"py","file_size_in_byte":2982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"489475326","text":"#this is a simple code for finding IP Address of any website\n#fun Code on Python\n#Milad Jamali Email : Jamalimilad60@gmail.com\nimport os\nimport socket\nos.system(\"clear\")\nprint(\"\"\"find website IP\"\"\")\nsite = input();\nhostname = site\nIPHOLDER = socket.gethostbyname(hostname)\nprint ('[ADDRESS]',hostname, '-',IPHOLDER)\nprint ('POWERED BY MILAD Jamali')\nquit = input()","sub_path":"IP_Finder.py","file_name":"IP_Finder.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"644894654","text":"#!/usr/bin/env python3\nimport struct\n\nfrom fjm_run import debug_and_run\n\nfrom os.path import isfile, abspath, isdir, join\nfrom defs import *\nfrom glob import glob\nimport argparse\nimport difflib\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Run FlipJump programs.')\n parser.add_argument('file', help=\"the FlipJump file.\")\n parser.add_argument('-s', '--silent', help=\"don't show run times\", action='store_true')\n parser.add_argument('-t', '--trace', help=\"trace the running opcodes.\", action='store_true')\n parser.add_argument('-f', '--flags', help=\"running flags\", type=int, default=0)\n parser.add_argument('-d', '--debug', help='debugging file')\n parser.add_argument('-b', '--breakpoint', help=\"pause when reaching this label\",\n default=[], action='append')\n parser.add_argument('-B', '--any_breakpoint', help=\"pause when reaching any label containing this\",\n default=[], action='append')\n parser.add_argument('--tests', help=\"run all .fjm files in the given folder (instead of specifying a file). \"\n \"Expects an input/expected-output directory. \"\n \"Each *.fjm file will be tested with \"\n \"dir/*.in as input, and its output will be compared to dir/*.out.\")\n args = parser.parse_args()\n\n verbose_set = set() if args.tests else {Verbose.PrintOutput}\n if not args.silent:\n verbose_set.add(Verbose.Time)\n if args.trace:\n verbose_set.add(Verbose.Run)\n\n if args.tests:\n inout_dir = args.tests\n failures = []\n total = 0\n folder = abspath(args.file)\n if not isdir(folder):\n print('Error: The \"file\" argument should contain a folder path.')\n exit(1)\n for file in glob(join(folder, '*.fjm')):\n total += 1\n infile = abspath(str(Path(inout_dir) / f'{Path(file).stem}.in'))\n outfile = abspath(str(Path(inout_dir) / f'{Path(file).stem}.out'))\n if not isfile(infile):\n print(f'test \"{file}\" missing an infile (\"{infile}\").\\n')\n failures.append(file)\n continue\n if not isfile(outfile):\n print(f'test \"{file}\" missing an outfile (\"{outfile}\").\\n')\n failures.append(file)\n continue\n\n print(f'running {Path(file).name}:')\n with open(infile, 'r', encoding='utf-8') as inf:\n test_input = inf.read()\n with open(outfile, 'r', encoding='utf-8') as outf:\n expected_output = outf.read()\n\n try:\n run_time, ops_executed, flips_executed, output, finish_cause = \\\n debug_and_run(file, defined_input=test_input, verbose=verbose_set)\n\n if not args.silent:\n print(f'finished by {finish_cause.value} after {run_time:.3f}s ({ops_executed:,} ops executed, {flips_executed/ops_executed*100:.2f}% flips)')\n\n if output != expected_output:\n print(f'test \"{file}\" failed. here\\'s the diff:')\n print(''.join(difflib.context_diff(output.splitlines(1), expected_output.splitlines(True),\n fromfile=file, tofile=outfile)))\n failures.append(file)\n\n if finish_cause != RunFinish.Looping:\n print(f'test \"{file}\" finished unexpectedly, with {finish_cause.value}.')\n failures.append(file)\n except FJReadFjmException as e:\n print()\n print(e)\n failures.append(file)\n\n print()\n\n print()\n if len(failures) == 0:\n print(f'All tests passed! 100%')\n else:\n print(f'{total-len(failures)}/{total} tests passed ({(total-len(failures))/total*100:.2f}%).')\n print(f'Failed tests:')\n for test in failures:\n print(f' {test}')\n else:\n\n file = abspath(args.file)\n if not isfile(file):\n parser.error(f'file {file} does not exist.')\n if not file.endswith('.fjm'):\n parser.error(f'file {file} is not a .fjm file.')\n\n if args.debug:\n debug_file = abspath(args.debug)\n if not isfile(debug_file):\n parser.error(f'debug-file {debug_file} does not exist.')\n\n breakpoint_set = set(args.breakpoint)\n breakpoint_any_set = set(args.any_breakpoint)\n\n try:\n run_time, ops_executed, flips_executed, output, finish_cause = \\\n debug_and_run(file, debugging_file=args.debug,\n defined_input=None,\n verbose=verbose_set,\n breakpoint_labels=breakpoint_set,\n breakpoint_any_labels=breakpoint_any_set)\n\n if not args.silent:\n print(f'finished by {finish_cause.value} after {run_time:.3f}s ({ops_executed:,} ops executed, {flips_executed/ops_executed*100:.2f}% flips)')\n print()\n except FJReadFjmException as e:\n print()\n print(e)\n exit(1)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/fji.py","file_name":"fji.py","file_ext":"py","file_size_in_byte":5333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"345084587","text":"from __future__ import print_function\n\nimport json\nfrom string import Template\n\nimport requests\n\nfrom frinx_rest import odl_url_base, odl_headers, odl_credentials, parse_response\n\nodl_url_netconf_mount = odl_url_base + \"/config/network-topology:network-topology/topology/topology-netconf/node/\"\n\nmount_template = {\n \"node\": \n {\n \"node-id\": \"\",\n\n \"netconf-node-topology:host\": \"\",\n \"netconf-node-topology:port\": \"\",\n \"netconf-node-topology:keepalive-delay\":\"\",\n \"netconf-node-topology:tcp-only\":\"\",\n \"netconf-node-topology:username\": \"\",\n \"netconf-node-topology:password\": \"\",\n\n }\n}\n\n\ndef execute_mount_netconf(task):\n device_id = task['inputData']['id']\n\n mount_body = mount_template.copy()\n\n mount_body[\"node\"][\"node-id\"] = task['inputData']['id']\n mount_body[\"node\"][\"netconf-node-topology:host\"] = task['inputData']['host']\n mount_body[\"node\"][\"netconf-node-topology:port\"] = task['inputData']['port']\n mount_body[\"node\"][\"netconf-node-topology:keepalive-delay\"] = task['inputData']['keepalive-delay']\n mount_body[\"node\"][\"netconf-node-topology:tcp-only\"] = task['inputData']['tcp-only']\n mount_body[\"node\"][\"netconf-node-topology:username\"] = task['inputData']['username']\n mount_body[\"node\"][\"netconf-node-topology:password\"] = task['inputData']['password']\n\n id_url = odl_url_netconf_mount + device_id\n\n r = requests.put(id_url, data=json.dumps(mount_body), headers=odl_headers, auth=odl_credentials)\n response_code, response_json = parse_response(r)\n\n if response_code == requests.codes.created:\n return {'status': 'COMPLETED', 'output': {'url': id_url,\n 'request_body': mount_body,\n 'response_code': response_code,\n 'response_body': response_json},\n 'logs': [\"Mountpoint with ID %s registered\" % device_id]}\n else:\n return {'status': 'FAILED', 'output': {'url': id_url,\n 'request_body': mount_body,\n 'response_code': response_code,\n 'response_body': response_json},\n 'logs': [\"Unable to register device with ID %s\" % device_id]}\n\n\ndef execute_unmount_netconf(task):\n device_id = task['inputData']['id']\n\n id_url = odl_url_netconf_mount + device_id\n\n r = requests.delete(id_url, headers=odl_headers, auth=odl_credentials)\n response_code, response_json = parse_response(r)\n\n return {'status': 'COMPLETED', 'output': {'url': id_url,\n 'response_code': response_code,\n 'response_body': response_json},\n 'logs': [\"Mountpoint with ID %s removed\" % device_id]}\n\n\ndef execute_check_netconf_id_available(task):\n device_id = task['inputData']['id']\n\n id_url = odl_url_netconf_mount + device_id\n\n r = requests.get(id_url, headers=odl_headers, auth=odl_credentials)\n response_code, response_json = parse_response(r)\n\n if response_code != requests.codes.not_found:\n # Mountpoint with such ID already exists\n return {'status': 'FAILED', 'output': {'url': id_url,\n 'response_code': response_code,\n 'response_body': response_json},\n 'logs': [\"Unable to mount device with ID %s\" % device_id]}\n else:\n return {'status': 'COMPLETED', 'output': {'url': id_url,\n 'response_code': response_code,\n 'response_body': response_json},\n 'logs': [\"Mountpoint with ID %s is available\" % device_id]}\n\n\ndef execute_check_connected_netconf(task):\n device_id = task['inputData']['id']\n\n id_url = odl_url_netconf_mount_oper + device_id\n\n r = requests.get(id_url, headers=odl_headers, auth=odl_credentials)\n response_code, response_json = parse_response(r)\n\n if response_code == requests.codes.ok and response_json[\"node\"][0][\"cli-topology:connection-status\"] == \"connected\":\n return {'status': 'COMPLETED', 'output': {'url': id_url,\n 'response_code': response_code,\n 'response_body': response_json},\n 'logs': [\"Mountpoint with ID %s is connected\" % device_id]}\n else:\n return {'status': 'FAILED', 'output': {'url': id_url,\n 'response_code': response_code,\n 'response_body': response_json},\n 'logs': [\"Mountpoint with ID %s not yet connected\" % device_id]}\n\n\ndef start(cc):\n print('Starting Netconf workers')\n\n cc.start('Netconf_mount_netconf', execute_mount_netconf, False)\n cc.start('Netconf_unmount_netconf', execute_unmount_netconf, False)\n cc.start('Netconf_check_netconf_connected', execute_check_connected_netconf, False)\n cc.start('Netconf_check_netconf_id_available', execute_check_netconf_id_available, False)\n\n","sub_path":"microservices/netinfra_utils/workers/netconf_worker.py","file_name":"netconf_worker.py","file_ext":"py","file_size_in_byte":5299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"569724035","text":"import matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\n\ndef get_corr_matrices(df):\n pearson_r = df.corr(method = 'pearson')\n spearman_r = df.corr(method = 'spearman') \n kendall_r = df.corr(method = 'kendall')\n return({'pearson': pearson_r, 'spearman': spearman_r, 'kendall' : kendall_r})\n\ndef thershold_correlations(corr, threshold = 0.4):\n where_tuple = np.where(abs(corr) > threshold)\n pairs = [(a,b) for a, b in zip(where_tuple[0], where_tuple[1]) if a != b]\n columns_to_show_index = set.union(set([a for a,b in pairs]), set([b for a,b in pairs]))\n columns_to_show = corr.columns[list(columns_to_show_index)]\n return(columns_to_show)\n\ndef visualize_corr_matrix(corr):\n plt.figure(figsize=(12, 10))\n sns.heatmap(corr, xticklabels= corr.columns, yticklabels= corr.columns)\n plt.show()\n \n \n","sub_path":"Homework_8/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"504728814","text":"import io\r\nimport pickle\r\nimport zlib\r\nimport os\r\nimport concurrent.futures\r\nfrom multiprocessing import Lock\r\nimport utils\r\n\r\nclass MapReduce:\r\n def __init__(self, MAX_LINE_IN_FILE = 5000,thread_pool_size = 2,path = 'MapReduceData/', meta_data = {},prev_byte = 0,file_index = 0):\r\n self.meta_data = {}\r\n if len(meta_data) > 0:\r\n self.meta_data = meta_data#{term: [(self.file_index, self.line_number, number_of_lines)]]\r\n self.prev_byte = prev_byte\r\n self.file_index = file_index\r\n self.thread_pool_size = thread_pool_size\r\n self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=thread_pool_size)\r\n self.MAX_IN_FILE = MAX_LINE_IN_FILE\r\n self.update_lock = Lock()\r\n self.path = path\r\n self.meta_data_save = self.path + 'MetaData'\r\n self.number_of_current_thread = 0\r\n self.number_of_current_thread_lock = Lock()\r\n\r\n def wait_untill_finish(self):\r\n while self.number_of_current_thread >= 0:\r\n pass\r\n\r\n def update_meta_data(self, term, number_of_bytes):\r\n # if seen first time create a empty one\r\n if term not in self.meta_data.keys():\r\n self.meta_data[term] = []\r\n self.meta_data[term].append((self.file_index, self.prev_byte, number_of_bytes))\r\n self.prev_byte += number_of_bytes\r\n\r\n def update_files(self):\r\n if self.prev_byte >= self.MAX_IN_FILE:\r\n self.prev_byte = 0\r\n self.file_index += 1\r\n\r\n def write_dict(self, dic):\r\n # self.write_dict_func(dic)\r\n self.number_of_current_thread_lock.acquire()\r\n self.number_of_current_thread += 1\r\n self.number_of_current_thread_lock.release()\r\n self.executor.submit(self.write_dict_func(dic))\r\n\r\n def write_dict_func(self, dic_org):\r\n dic = dic_org.copy()\r\n dic_org.clear()\r\n try:\r\n for key, value in dic.items():\r\n self.write_in(key, value)\r\n finally:\r\n self.number_of_current_thread_lock.acquire()\r\n self.number_of_current_thread -= 1\r\n self.number_of_current_thread_lock.release()\r\n dic.clear()\r\n return True\r\n\r\n def write_in(self, term, data_list):\r\n self.update_lock.acquire()\r\n # file name = (dic location) / the possible file to write in\r\n file_name = self.path + str(self.file_index)\r\n # only one process can update\r\n # add data_list to file_name\r\n number_of_bytes = self.append_line([data_list], file_name)\r\n # save as (file_index,line_number_start,length)\r\n self.update_meta_data(term, number_of_bytes)\r\n # update number of line after add of data_list\r\n self.update_files()\r\n self.update_lock.release()\r\n\r\n def append_line(self, data_list, file_name):\r\n \"\"\"\r\n Gets: file name and data to save\r\n Does: save the data as bytes and compress them\r\n \"\"\"\r\n #add to the file\r\n number_of_bytes = 0\r\n with open(file_name + '.comp', \"ab\") as fd:\r\n if isinstance(data_list,list):\r\n for data_tuple in data_list:\r\n # pickle.dump(data_tuple, fd, pickle.HIGHEST_PROTOCOL)\r\n bytes = io.BytesIO()\r\n # convert data into bytes as Bytes\r\n pickle.dump(data_tuple, bytes)\r\n # zbytes = zlib.compress(bytes.getbuffer())\r\n zbytes = bytes.getbuffer()\r\n number_of_bytes += len(zbytes)\r\n fd.write(zbytes)\r\n # how to add dic\r\n elif isinstance(data_list,dict):\r\n bytes = io.BytesIO()\r\n # convert data into bytes as Bytes\r\n pickle.dump(data_list, bytes)\r\n # compress the byte and insert into zbytes\r\n zbytes = zlib.compress(bytes.getbuffer())\r\n number_of_bytes += len(zbytes)\r\n fd.write(zbytes)\r\n return number_of_bytes\r\n\r\n def read_from(self, term):\r\n \"\"\"We want to return the list of doc with info about the term\"\"\"\r\n future = self.executor.submit(self.read_from_func,term)\r\n return future.result()\r\n\r\n def read_from_func(self, term):\r\n return self.read_from_func_async(term)\r\n\r\n def read_from_func_async(self,term): #async\r\n data_list = []\r\n # {(term: [])} #term=document,docID\r\n #await self.process_semaphore.acquire()\r\n try:\r\n term_meta_data = self.meta_data[term]\r\n # save dic so duplicate will be together\r\n dic_by_file_name = {} # {file_name: list of byte index in file}}\r\n # run and build file and all lines in this file\r\n for file_index, prev_byte,number_of_bytes in term_meta_data:\r\n if file_index not in dic_by_file_name.keys():\r\n dic_by_file_name[file_index] = []\r\n dic_by_file_name[file_index].append((prev_byte,number_of_bytes))\r\n\r\n organize_dic = {} # {(file_index,line_number)}\r\n # read file by file\r\n for file_index,file_byte_lst in dic_by_file_name.items():\r\n # update file name with path\r\n file_name = self.path + str(file_index)\r\n # read\r\n dic_of_current_text_by_line = self.read_line(file_name, file_byte_lst)\r\n for line_index, line_object in dic_of_current_text_by_line.items():\r\n organize_dic[(file_index, line_index)] = line_object\r\n # {term: [(self.file_index, self.line_number, number_of_lines)]]\r\n # build list as organize\r\n for i in range(len(term_meta_data)):\r\n current_file_index, current_line_number, _ = term_meta_data[i]\r\n if isinstance(organize_dic[(current_file_index, current_line_number)],dict):\r\n data_list += (organize_dic[(current_file_index, current_line_number)],0)\r\n else:\r\n data_list += organize_dic[(current_file_index, current_line_number)]\r\n finally:\r\n return data_list\r\n\r\n def read_line(self, file_name,file_byte_lst):\r\n \"\"\"\r\n Gets: set of line to read from fuke\r\n Does: return the original object of file\r\n \"\"\"\r\n # file byte lst = [(prev_byte,number_of_bytes)] [(5,7)]\r\n data = {} #{bytesNumber: obj}\r\n #sort by index\r\n file_byte_lst.sort(key=lambda x:x[0]) #[(fromWhere,numbersOfBytes)]\r\n data_str = {}\r\n if os.path.isfile(file_name + '.comp'):\r\n with open(file_name + '.comp', 'rb') as fd:\r\n prev_bytes = 0\r\n # text = pickle.load(fd)\r\n # run on all file lines\r\n start = -1\r\n for i, line in enumerate(fd):\r\n index = 0\r\n data_to_read_from_line = [] # list of data to read from line i\r\n # line as string\r\n array_line = bytes(line)\r\n done_loop = False\r\n # run and build the set of data in line\r\n data_edit=0\r\n while index < len(file_byte_lst) and not done_loop:\r\n if file_byte_lst[index][0] >= prev_bytes and file_byte_lst[index][0] 0:\r\n\tkey = problems_left[0]\r\n\tpinyin = character_dict[key]\r\n\tchinese_character = key\r\n\t# result = chinese_character.encode('big5').decode('big5')\r\n\tguess = input(\"Guess for \" + chinese_character + \": \")\r\n\tif guess == pinyin:\r\n\t\tprint(\"CORRECT!\", chinese_character, \"==\", pinyin)\r\n\telse:\r\n\t\tif chinese_character in extra_dict:\r\n\t\t\tprint(\"WRONG!\", chinese_character, extra_dict[chinese_character],\"==\", pinyin)\t\t\r\n\t\telse:\r\n\t\t\tprint(\"WRONG!\", chinese_character,\"==\", pinyin)\r\n\t\tfout.write(\"WRONG! \" + chinese_character + \" == \" + pinyin)\r\n\t\tfout.write(\"\\n\")\r\n\t\tincorrect.append(chinese_character)\r\n\t\tproblems_left.append(chinese_character)\r\n\t\tadditional += 1\r\n\tdel problems_left[0]\r\n\r\nprint(\"Here's the ones you got wrong!\")\r\nfor key in incorrect:\r\n\tprint(key, \"--\", character_dict[key])\r\n\tfout.write(key + \" -- \" + character_dict[key])\r\ncorrect_num = len(character_dict) + additional - len(incorrect)\r\nprint(\"ACCURACY:\", correct_num, \"/\", len(character_dict) + additional, \":\", int(100 * correct_num/(len(character_dict) + additional)), \"%\")\r\nfout.write(\"ACCURACY: \" + str(correct_num) + \"/\" + str(len(character_dict) + additional) + \" : \" + str(int(100 * correct_num/(len(character_dict) + additional))) + \"%\")\r\nfout.write(\"-----------------------------\")","sub_path":"guess_pinyin.py","file_name":"guess_pinyin.py","file_ext":"py","file_size_in_byte":1892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"510860068","text":"import dash_html_components as html\nfrom flask import current_app as server\nfrom dash.dependencies import Output, Input\nfrom dash.exceptions import PreventUpdate\n\nfrom .app import app\nfrom .pages import page_not_found, character_counter, page2, page3\nfrom .components import make_nav, fa\nfrom .utils import get_url\n\n\n#\n# The router\n#\n\n# Ordered iterable of routes: tuples of (route, layout), where 'route' is a\n# string corresponding to path of the route (will be prefixed with Dash's\n# 'routes_pathname_prefix' and 'layout' is a Dash Component.\nURLS = (\n (\"\", character_counter.layout),\n (\"character-counter\", character_counter.layout),\n (\"page2\", page2.layout),\n (\"page3\", page3.layout),\n)\n\n\nROUTES = {get_url(route): layout for route, layout in URLS}\n\n\n@app.callback(\n Output(server.config[\"CONTENT_CONTAINER_ID\"], \"children\"),\n [Input(\"url\", \"pathname\")],\n)\ndef router(pathname):\n \"\"\"The router\"\"\"\n default_layout = page_not_found(pathname)\n return ROUTES.get(pathname, default_layout)\n\n\n#\n# The Navbar\n#\n\n# Ordered iterable of navbar items: tuples of `(route, display)`, where `route`\n# is a string corresponding to path of the route (will be prefixed with\n# URL_BASE_PATHNAME) and 'display' is a valid value for the `children` keyword\n# argument for a Dash component (ie a Dash Component or a string).\nNAV_ITEMS = (\n (\"character-counter\", html.Div([fa(\"fas fa-keyboard\"), \"Character Counter\"])),\n (\"page2\", html.Div([fa(\"fas fa-chart-area\"), \"Page 2\"])),\n (\"page3\", html.Div([fa(\"fas fa-chart-line\"), \"Page 3\"])),\n)\n\n\n@app.callback(\n Output(server.config[\"NAVBAR_CONTAINER_ID\"], \"children\"), [Input(\"url\", \"pathname\")]\n)\ndef update_nav(pathname):\n \"\"\"Create the navbar with the current page set to active\"\"\"\n if pathname is None:\n # pathname is None on the first load of the app; ignore this\n raise PreventUpdate(\"Ignoring first url.pathname callback\")\n return make_nav(NAV_ITEMS, pathname)\n","sub_path":"src/slapdash/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"79274703","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 24 23:35:59 2017\n\n@author: Ivan Liu\n\"\"\"\n\nimport backtrader as bt \nfrom PyQuantTrader.indicators import KalmanSignals\n\nclass KalmanFilterStrategy(bt.Strategy):\n params = (\n )\n\n def __init__(self):\n self.ksig = KalmanSignals(self.data0, self.data1)\n\n def next(self):\n size = self.position.size\n if not size:\n if self.ksig.long:\n self.buy()\n elif self.ksig.short:\n self.sell()\n\n elif size > 0:\n if not self.ksig.long:\n self.close()\n elif not self.ksig.short: # implicit size < 0\n self.close()","sub_path":"build/lib/PyQuantTrader/strategy/Kalmanfilter.py","file_name":"Kalmanfilter.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"295292819","text":"import os\r\nimport re\r\n\r\n\r\n#Вроде бы к кириллическим символам знаки препинания и цифры не о��носятся?\r\n\r\ndef folder():\r\n folders = []\r\n for folder in os.listdir():\r\n if os.path.isdir(folder):\r\n dirpath, filename = os.path.split(folder)\r\n r = re.search('[A-Z]|[a-z]|[0-9]|[,—\\[\\]↑№!\\\"\\'«»?.,;:-|/+*{}<>@#$%-^&()]', filename)\r\n if not r:\r\n folders.append(filename)\r\n return folders\r\n \r\ndef num_dir(folders):\r\n print(int(len(folders)))\r\n\r\n#Вообще папки с одинаковым названием не создаются, но на всякий случай делаю попытку этого избежать\r\n\r\ndef no_repeat(folders):\r\n check = []\r\n for i in folders:\r\n if i not in check:\r\n check.append(i)\r\n print('Есть такая папка: ', i)\r\n \r\ndef main():\r\n return num_dir(folder()), no_repeat(folder())\r\n\r\nif __name__ == \"__main__\":\r\n print('Всего папок: ', end='')\r\n main()\r\n\r\n","sub_path":"hw12/hw12.py","file_name":"hw12.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"259946455","text":"from selenium import webdriver\nfrom interfaceTest.config.main import *\nimport requests\nimport json\nimport ddt\nfrom interfaceTest.libext.HTMLTestRunner import *\nfrom interfaceTest.config.config import *\n\n\n@ddt.ddt\nclass test_ramsModel(unittest.TestCase):\n @classmethod\n def setUpClass(cls): # 类中最先执行\n cls.path = '{}/testOutput/interface-sheet.xls'.format(path_dir)\n # create_sheet(cls.path)\n cls.driver = webdriver.Chrome()\n\n cls.driver.maximize_window()\n cls.driver.get(interface_url + '/darams/doc.html')\n time.sleep(2)\n\n @classmethod\n def tearDownClass(cls):\n # cls.driver = driver# 类中最后执行\n cls.driver.quit()\n\n @ddt.file_data('{}/testInput/test_ramsEvaluate_input/test_1_login.json'.format(path_dir))\n def test_1_login(self, username, password):\n # \"\"\"登录接口\"\"\"\n try:\n # f = open('')\n\n driver = self.driver\n driver.refresh()\n\n time.sleep(2)\n # 点击搜索\n\n Method(driver).click('xpath', '//span[contains(text(),\"登录管理\")]')\n time.sleep(1)\n\n # 点击登录\n driver.find_element_by_xpath('//span[text()=\"登录\"]').click()\n time.sleep(1)\n # 获取登录接口的地址\n login_interface_url = driver.find_element_by_xpath('//span[text()=\"接口地址\"]/../code').text\n\n # 访问登录接口,拿到登录校验\n login_send = requests.post(interface_url + login_interface_url,\n data={'username': '{}'.format(username), 'password': '{}'.format(password)})\n login_response = json.loads(login_send.text)\n path = self.path\n url = interface_url + login_interface_url\n params = json.dumps({'username': '{}'.format(username), 'password': '{}'.format(password)})\n if login_send.status_code == 200:\n # 得到登录接口的返回\n if login_response['success'] is True:\n globals()[\"Authorization\"] = login_response['result']\n self.assertEqual(4, 4)\n else:\n globals()[\"Authorization\"] = {}\n\n if 'result' in login_response.keys():\n result = login_response['result']\n del login_response['result']\n\n write_sheet(path, '登录接口', url, params, json.dumps(login_response, ensure_ascii=False),\n json.dumps(result, ensure_ascii=False))\n else:\n write_sheet(path, '登录接口', url, params, json.dumps(login_response, ensure_ascii=False), '')\n self.assertEqual(3, 4)\n else:\n globals()[\"Authorization\"] = {}\n\n write_sheet(path, '登录接口', url, params, '登录接口返回:{}'.format(login_send.status_code), '')\n\n self.assertEqual(3, 4)\n except AssertionError:\n logger.error(AssertionError)\n self.assertEqual(3, 4)\n\n @ddt.file_data('{}/testInput/test_ramsModel_input/test_2_getTrainTypeTree.json'.format(path_dir))\n def test_2_getTrainTypeTree(self,trainNoIds,faultObjectNames):\n \"\"\"查找车型部件数接口\"\"\"\n path = self.path\n if len(globals()[\"Authorization\"]) == 0:\n write_sheet(path, '查找车型部件数接口', '', '', '用户未登录', '')\n self.assertEqual(3, 4)\n else:\n try:\n driver = self.driver\n driver.refresh()\n\n time.sleep(2)\n Method(driver).click('xpath', '//span[contains(text(),\"RAMS模型相关接口\")]')\n time.sleep(1)\n\n Method(driver).circle_click(\"查找车型部件树\")\n time.sleep(2)\n # 获取计算接口的地址\n getTrainTypeTree_interface_url = driver.find_element_by_xpath('//span[text()=\"接口地址\"]/../code').text\n\n # 判断文件中是否存在\n file = '{}/testFile/test_ramsModel/test_getTrainTypeTree/test_getTrainTypeTree_{}.txt'.format(\n path_dir, trainNoIds)\n body = {\n \"trainNoIds\":\"{}\".format(trainNoIds),\n \"faultObjectNames\":\"{}\".format(faultObjectNames)\n }\n\n # 请求计算接口\n getTrainTypeTree_send = requests.post(interface_url + getTrainTypeTree_interface_url,\n headers={\n \"Authorization\": globals()[\"Authorization\"][\n \"Authorization\"],\n \"Content-Type\": \"application/json;charset=UTF-8\"},\n params=body)\n\n url = interface_url + getTrainTypeTree_interface_url\n params = json.dumps(body, ensure_ascii=False)\n\n if os.path.exists(file) is True:\n pass\n else:\n fp = open(file, 'wb')\n fp.write(getTrainTypeTree_send.text.encode())\n fp.close()\n # 判断文件是否有信息\n sz = os.path.getsize(file)\n if not sz:\n fp = open(file, 'wb')\n fp.write(getTrainTypeTree_send.text.encode())\n self.assertEqual(4, 4)\n else:\n fp = open(file, 'r', encoding='UTF-8')\n # 因为每次请求的token值不一样 =所以得删除掉在对比\n dict_fp = json.loads(fp.read())\n dict_getTrainTypeTree = json.loads(getTrainTypeTree_send.text)\n del dict_fp['token']\n del dict_getTrainTypeTree['token']\n if dict_fp == dict_getTrainTypeTree:\n\n self.assertEqual(4, 4)\n else:\n if 'result' in dict_getTrainTypeTree.keys():\n result = dict_getTrainTypeTree['result']\n del dict_getTrainTypeTree['result']\n\n write_sheet(path, '查找车型部件数接口', url, params,\n json.dumps(dict_getTrainTypeTree, ensure_ascii=False),\n json.dumps(result, ensure_ascii=False)[:2000])\n else:\n write_sheet(path, '查找车型部件数接口', url, params,\n json.dumps(dict_getTrainTypeTree, ensure_ascii=False),\n '')\n\n self.assertEqual(3, 4)\n\n fp.close()\n\n except AssertionError:\n logger.error(AssertionError)\n self.assertEqual(3, 4)\n\n @ddt.file_data('{}/testInput/test_ramsModel_input/test_3_getPageFaultPattern.json'.format(path_dir))\n def test_3_getPageFaultPattern(self,data):\n \"\"\"根据部件id查询故障对象接口\"\"\"\n path = self.path\n if len(globals()[\"Authorization\"]) == 0:\n write_sheet(path, '根据部件id查询故障对象接口', '', '', '用户未登录', '')\n self.assertEqual(3, 4)\n else:\n try:\n driver = self.driver\n driver.refresh()\n\n time.sleep(2)\n Method(driver).click('xpath', '//span[contains(text(),\"RAMS模型相关接口\")]')\n time.sleep(1)\n\n Method(driver).circle_click(\"根据部件id查询故障对象\")\n time.sleep(1)\n # 获取计算接口的地址\n getPageFaultPattern_interface_url = driver.find_element_by_xpath('//span[text()=\"接口地址\"]/../code').text\n\n # 判断文件中是否存在\n file = '{}/testFile/test_ramsModel/test_getPageFaultPattern/test_getPageFaultPattern_{}.txt'.format(\n path_dir, data['faultObjectId'])\n body = data\n\n # 请求计算接口\n getPageFaultPattern_send = requests.post(interface_url + getPageFaultPattern_interface_url,\n headers={\n \"Authorization\": globals()[\"Authorization\"][\n \"Authorization\"],\n \"Content-Type\": \"application/json;charset=UTF-8\"},\n params=body)\n\n url = interface_url + getPageFaultPattern_interface_url\n params = json.dumps(body, ensure_ascii=False)\n\n if os.path.exists(file) is True:\n pass\n else:\n fp = open(file, 'wb')\n fp.write(getPageFaultPattern_send.text.encode())\n fp.close()\n # 判断文件是否有信息\n sz = os.path.getsize(file)\n if not sz:\n fp = open(file, 'wb')\n fp.write(getPageFaultPattern_send.text.encode())\n self.assertEqual(4, 4)\n else:\n fp = open(file, 'r', encoding='UTF-8')\n # 因为每次请求的token值不一样 =所以得删除掉在对比\n dict_fp = json.loads(fp.read())\n dict_getPageFaultPattern = json.loads(getPageFaultPattern_send.text)\n del dict_fp['token']\n del dict_getPageFaultPattern['token']\n if dict_fp == dict_getPageFaultPattern:\n\n self.assertEqual(4, 4)\n else:\n if 'result' in dict_getPageFaultPattern.keys():\n result = dict_getPageFaultPattern['result']\n del dict_getPageFaultPattern['result']\n\n write_sheet(path, '根据部件id查询故障对象接口', url, params,\n json.dumps(dict_getPageFaultPattern, ensure_ascii=False),\n json.dumps(result, ensure_ascii=False)[:2000])\n else:\n write_sheet(path, '根据部件id查询故障对象接口', url, params,\n json.dumps(dict_getPageFaultPattern, ensure_ascii=False),\n '')\n\n self.assertEqual(3, 4)\n\n fp.close()\n\n except AssertionError:\n logger.error(AssertionError)\n self.assertEqual(3, 4)\n\n\n\n\n\nif __name__ == '__main__':\n report = r\"{}/Report.html\".format(path_dir) # 定义测试报告的名称(日期+report.html,引用report_name函数实现)\n fp = open(report, 'wb')\n st = unittest.TestSuite()\n # st.addTest(test_ramsInterface('test_1_login'))\n # st.addTest(test_ramsInterface('test_2_ramsEvaluate'))\n # st.addTest(test_ramsInterface('test_3_getModelStatus'))\n # st.addTest(test_ramsInterface('test_4_ramsEvaluate_charts'))\n st.addTest(unittest.makeSuite(test_ramsModel))\n # unittest.main()\n runner = HTMLTestRunner(stream=fp, verbosity=2, title='接口测试报告', description='测试结果如下: ')\n runner.run(st) # 执行测试\n\n fp.close() # 关闭文件流,将HTML内容写进测试报告文件\n","sub_path":"interfaceTest/testCase/test_ramsModel.py","file_name":"test_ramsModel.py","file_ext":"py","file_size_in_byte":12040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"610155133","text":"from pathlib import Path\nimport numpy as np\nfrom scipy import stats\nimport csv\nimport pandas as pd\n\npd.set_option('display.width', 190)\npd.set_option('display.max_columns', None)\n\nbase = Path(__file__).resolve().parents[1] # resolve obtains absolute path and resolves symlinks\ndata = base / 'data'\n\n\ndef prepare_regression_csv(df):\n \"\"\"for products make trendlines for the different cultures, for substrate make different trendlines for different\n cultures and fed number\"\"\"\n df = remove_outliers(df)\n\n with open(data / 'regression.csv', 'w') as fout:\n print(f'exported a csv to: {fout.name}')\n writer = csv.writer(fout)\n writer.writerow(['culture', 'x_name', 'y_name', 'slope', 'intercept', 'r_squared', 'x_values', 'y_values'])\n\n cultures = df.culture.unique()\n for culture in cultures:\n # groupby would be a better solution here\n df_trendline = df[df.culture == culture]\n write_regression(culture, 'productA_umol', df_trendline, writer)\n write_regression(culture, 'productB_umol', df_trendline, writer)\n\n feeding = df_trendline.fed.unique()\n for fed in feeding:\n df_trendline_substrate = df_trendline[df_trendline.fed == fed]\n write_regression(culture, 'substrate_umol', df_trendline_substrate, writer)\n return df\n\n\ndef write_regression(culture, substrate, df, writer):\n day_trendline, substrate_trendline = data_for_trendline(df, 'day', substrate, drop_zero=True)\n if len(day_trendline) < 3: # you don't want a trendline if you have less than 3 points\n return\n try:\n slope, intercept, r_squared = linear_regression(day_trendline, substrate_trendline)\n writer.writerow(\n [culture, 'day', substrate, slope, intercept, r_squared, np2str(day_trendline), np2str(substrate_trendline)])\n return\n except ValueError:\n return\n\n\ndef remove_outliers(df):\n # on these two days productB data is off\n df.loc[df.day == 91, 'productB_umol'] = np.NaN\n df.loc[df.day == 104, 'productB_umol'] = np.NaN\n return df\n\n\ndef np2str(array):\n return np.array2string(array)[1:-1]\n\n\ndef linear_regression(x, y):\n mask = ~np.isnan(x) & ~np.isnan(y) # create mask to remove NANs\n slope, intercept, r_value, p_value, std_err = stats.linregress(x[mask], y[mask])\n return slope, intercept, r_value ** 2\n\n\ndef data_for_trendline(df, x, y, drop_zero = False, outliers = None):\n \"\"\"outliers should be list of two items: first column name and then list of values to remove.\n generally, you don't want to include zero's in a trendline\"\"\"\n df = df.dropna(subset=[y])\n if drop_zero:\n df = df[df[y] != 0]\n if outliers:\n df = df[~df[outliers[0]].isin(outliers[1])]\n return df[x].values, df[y].values\n\n\n","sub_path":"scripts/regression.py","file_name":"regression.py","file_ext":"py","file_size_in_byte":2825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"334020593","text":"import logging\nimport os\nimport tempfile\n\nfrom flask import Flask, request, jsonify, send_file, make_response\nfrom google.cloud import storage\n\napp = Flask(__name__)\nlogging.basicConfig(level=logging.DEBUG)\n\n# Configure this environment variable\nCLOUD_STORAGE_BUCKET = os.environ.get('CLOUD_STORAGE_BUCKET_USER')\n# Configure this environment variable\nCLOUD_STORAGE_BUCKET_CHAT = os.environ.get('CLOUD_STORAGE_BUCKET_CHAT')\n\nheaders = {'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, Authorization',\n 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': '*', 'Access-Control-Max-Age': '3600'}\n\n\n@app.route('/')\ndef index():\n return \"\"\"\n
\n
\n \n
\n\"\"\"\n\n\n@app.route('/file/user', methods=['GET'])\ndef download_user_file():\n\n file_name = request.args.get('name')\n\n if not file_name:\n return jsonify(message=\"Filename cannot be empty\"), 409\n\n try:\n gcp_storage = storage.Client()\n\n bucket = gcp_storage.bucket(CLOUD_STORAGE_BUCKET)\n blob = bucket.blob(file_name)\n\n with tempfile.NamedTemporaryFile() as temp:\n blob.download_to_filename(temp.name)\n return send_file(temp.name, attachment_filename=file_name, as_attachment=True), headers\n\n except Exception as e:\n app.logger.error(e)\n return jsonify(message=\"An error occurred while downloading the file\", error=str(e)), 409\n\n\n@app.route('/file/chat', methods=['GET'])\ndef download_chat_file():\n\n file_name = request.args.get('name')\n\n if not file_name:\n return jsonify(message=\"Filename cannot be empty\"), 409\n\n try:\n gcp_storage = storage.Client()\n\n bucket = gcp_storage.bucket(CLOUD_STORAGE_BUCKET_CHAT)\n blob = bucket.blob(file_name)\n\n with tempfile.NamedTemporaryFile() as temp:\n blob.download_to_filename(temp.name)\n\n return send_file(temp.name, attachment_filename=file_name, as_attachment=True), headers\n\n except Exception as e:\n app.logger.error(e)\n return jsonify(message=\"An error occurred while downloading the file\", error=str(e)), 409, headers\n\n\n@app.route('/file/user', methods=['GET'])\ndef download_blob():\n\n file_name = request.args.get('name')\n\n if not file_name:\n return jsonify(message=\"Filename cannot be empty\"), 409\n\n try:\n gcp_storage = storage.Client()\n\n bucket = gcp_storage.bucket(CLOUD_STORAGE_BUCKET)\n blob = bucket.blob(file_name)\n\n with tempfile.NamedTemporaryFile() as temp:\n blob.download_to_filename(temp.name)\n return send_file(temp.name, attachment_filename=file_name, as_attachment=True)\n\n except Exception as e:\n app.logger.error(e)\n return jsonify(message=\"An error occurred while downloading the file\", error=str(e)), 409,headers\n\n\n@app.route('/files/user', methods=['GET'])\ndef get_all_files():\n try:\n # Initializing GCP storage client\n gcp_storage = storage.Client()\n\n # Fetching the blobs object for the desired bucket\n blobs = gcp_storage.list_blobs(CLOUD_STORAGE_BUCKET)\n\n files = []\n for blob in blobs:\n files.append(blob.name)\n\n app.logger.info(\"Files retrieved from the bucket: {} are: {}\".format(CLOUD_STORAGE_BUCKET, files))\n return jsonify(files=files), 200, headers\n\n except Exception as e:\n app.logger.error(e)\n return jsonify(message=\"An error occurred while uploading the file\", error=str(e)), 409, headers\n\n\n@app.route('/files/chat', methods=['GET'])\ndef get_chat_files():\n try:\n # Initializing GCP storage client\n gcp_storage = storage.Client()\n\n # Fetching the blobs object for the desired bucket\n blobs = gcp_storage.list_blobs(CLOUD_STORAGE_BUCKET_CHAT)\n\n files = []\n for blob in blobs:\n files.append(blob.name)\n\n app.logger.info(\"Chat files retrieved from the bucket: {} are: {}\".format(CLOUD_STORAGE_BUCKET_CHAT, files))\n return jsonify(files=files), 200, headers\n\n except Exception as e:\n app.logger.error(e)\n return jsonify(message=\"An error occurred while uploading the file\", error=str(e)), 409, headers\n\n\n@app.route('/upload', methods=['POST'])\ndef upload_file():\n selected_file = request.files.get('file')\n\n print(selected_file.filename)\n\n if not selected_file:\n return jsonify(error='No file selected for upload.'), 400\n\n app.logger.info(\"File selected for upload {}\".format(selected_file.filename))\n\n try:\n # Initializing GCP storage client\n gcp_storage = storage.Client()\n\n # Getting the bucket URL where the file needs to be uploaded\n bucket = gcp_storage.get_bucket(CLOUD_STORAGE_BUCKET)\n\n # Initializing blob object\n blob = bucket.blob(selected_file.filename)\n\n # Uploading the file\n blob.upload_from_string(\n selected_file.read(),\n content_type=selected_file.content_type\n )\n\n res = \"File: {} has been successfully uploaded to the bucket {}\".format(selected_file.filename\n , CLOUD_STORAGE_BUCKET)\n app.logger.info(res)\n return jsonify(message=\"File has been successfully uploaded\", filename=selected_file.filename), 201 , headers\n except Exception as e:\n app.logger.error(e)\n return jsonify(message=\"An error occurred while uploading the file\", error=str(e)), 409, headers\n\n\n@app.errorhandler(500)\ndef server_error(e):\n app.logger.error('An error occurred during a request.')\n return jsonify(message=\"An internal error occurred\", error=\"{} See logs for full stacktrace.\".format(e)) \\\n , 500\n\n\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0', port=int(os.environ.get('PORT', 8080)))\n","sub_path":"back-end/user-file-management/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"63767895","text":"import cv2 as cv\nimport numpy as np\nimport datetime\n\ncap = cv.VideoCapture(1)\ncap.set(3,1280)\ncap.set(4,1500)\nif cap.isOpened() == False:\n print(\"Error capturing the video\")\nwhile cap.isOpened():\n ret , frame = cap.read()\n if ret == True:\n # text = \"Width: \" + str(cap.get(3)) + \" Height: \" + str(cap.get(4))\n text = str(datetime.datetime.now())\n frame = cv.putText(frame , text , (10,50) , cv.FONT_HERSHEY_SIMPLEX , 2 , (0,0,0), 1 , cv.LINE_AA)\n cv.imshow(\"Camera\",frame)\n if cv.waitKey(25) & 0xFF == ord('q'):\n break\n else:\n break\n\ncap.release()\ncv.destroyAllWindows()","sub_path":"opencv/DateTimeOnVideo.py","file_name":"DateTimeOnVideo.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"375600640","text":"# DDPG taken from\n# https://github.com/nivwusquorum/tensorflow-deepq\n\nimport numpy as np\nimport random\nimport tensorflow as tf\n\nfrom collections import deque\n\nclass ContinuousDeepQLSTMStepped(object):\n def __init__(self, observation_placeholder,\n next_observation_placeholder,\n given_action_placeholder,\n observation_size,\n action_size,\n actor,\n critic,\n optimizer,\n session,\n exploration_sigma=0.05,\n exploration_period=1000,\n store_every_nth=5,\n train_every_nth=5,\n minibatch_size=32,\n discount_rate=0.95,\n max_experience=30000,\n target_actor_update_rate=0.01,\n target_critic_update_rate=0.01,\n summary_writer=None):\n \"\"\"Initialized the Deepq object.\n Based on:\n https://www.cs.toronto.edu/~vmnih/docs/dqn.pdf\n Parameters\n -------\n observation_size : int\n length of the vector passed as observation\n action_size : int\n length of the vector representing an action\n observation_to_actions: dali model\n model that implements activate function\n that can take in observation vector or a batch\n and returns scores (of unbounded values) for each\n action for each observation.\n input shape: [batch_size, observation_size]\n output shape: [batch_size, action_size]\n optimizer: tf.solver.*\n optimizer for prediction error\n session: tf.Session\n session on which to execute the computation\n exploration_sigma: float (0 to 1)\n exploration_period: int\n probability of choosing a random\n action (epsilon form paper) annealed linearly\n from 1 to exploration_sigma over\n exploration_period\n store_every_nth: int\n to further decorrelate samples do not all\n transitions, but rather every nth transition.\n For example if store_every_nth is 5, then\n only 20% of all the transitions is stored.\n train_every_nth: int\n normally training_step is invoked every\n time action is executed. Depending on the\n setup that might be too often. When this\n variable is set set to n, then only every\n n-th time training_step is called will\n the training procedure actually be executed.\n minibatch_size: int\n number of state,action,reward,newstate\n tuples considered during experience reply\n dicount_rate: float (0 to 1)\n how much we care about future rewards.\n max_experience: int\n maximum size of the reply buffer\n target_actor_update_rate: float\n how much to update target critci after each\n iteration. Let's call target_critic_update_rate\n alpha, target network T, and network N. Every\n time N gets updated we execute:\n T = (1-alpha)*T + alpha*N\n target_critic_update_rate: float\n analogous to target_actor_update_rate, but for\n target_critic\n summary_writer: tf.train.SummaryWriter\n writer to log metrics\n \"\"\"\n # memorize arguments\n self.observation_size = observation_size\n self.action_size = action_size\n\n self.actor = actor\n self.critic = critic\n self.optimizer = optimizer\n self.s = session\n\n self.exploration_sigma = exploration_sigma\n self.exploration_period = exploration_period\n self.store_every_nth = store_every_nth\n self.train_every_nth = train_every_nth\n self.minibatch_size = minibatch_size\n self.discount_rate = tf.constant(discount_rate)\n self.max_experience = max_experience\n\n self.target_actor_update_rate = \\\n tf.constant(target_actor_update_rate)\n self.target_critic_update_rate = \\\n tf.constant(target_critic_update_rate)\n\n # deepq state\n self.actions_executed_so_far = 0\n self.experience = deque()\n\n self.iteration = 0\n self.summary_writer = summary_writer\n\n self.number_of_times_store_called = 0\n self.number_of_times_train_called = 0\n\n self.observation = observation_placeholder\n self.next_observation = next_observation_placeholder\n self.given_action = given_action_placeholder\n\n self.create_variables()\n\n @staticmethod\n def linear_annealing(n, total, p_initial, p_final):\n \"\"\"Linear annealing between p_initial and p_final\n over total steps - computes value at step n\"\"\"\n if n >= total:\n return p_final\n else:\n return p_initial - (n * (p_initial - p_final)) / (total)\n\n @staticmethod\n def update_target_network(source_network, target_network, update_rate):\n target_network_update = []\n for v in source_network.variables():\n # this is equivalent to target = (1-alpha) * target + alpha * source\n #print \"source: \" + v.name + \" : \" + str(v.get_shape())\n pass\n for v in target_network.variables():\n # this is equivalent to target = (1-alpha) * target + alpha * source\n #print \"target: \" + v.name + \" : \" + str(v.get_shape())\n pass\n for v_source, v_target in zip(source_network.variables(), target_network.variables()):\n # this is equivalent to target = (1-alpha) * target + alpha * source\n update_op = v_target.assign_sub(update_rate * (v_target - v_source))\n target_network_update.append(update_op)\n return tf.group(*target_network_update)\n\n def concat_nn_lstm_input(self, input1, input2):\n #print \"input1: \" + str(input1)\n #print \"input2: \" + str(input2)\n return tf.concat(2, [input1, input2])\n\n def add_pow_values(self, values):\n #print \"add_pow_values: \" + str (values)\n powed = 0.01 * tf.pow(values, [[2, 2] for i in range(values.get_shape()[1])])\n #print \"powed: \" + str (powed)\n return self.concat_nn_lstm_input(values, powed)\n\n def get_last (self, values):\n val = tf.transpose(values, [1, 0, 2])\n return tf.gather(val, int(val.get_shape()[0]) - 1)\n\n\n def create_variables(self):\n self.target_actor = self.actor.copy(scope=\"target_actor\")\n self.target_critic = self.critic.copy(scope=\"target_critic\")\n\n # FOR REGULAR ACTION SCORE COMPUTATION\n with tf.name_scope(\"taking_action\"):\n# self.observation = tf.placeholder(tf.float32, (None, self.observation_size), name=\"observation\")\n self.actor_val = self.actor(self.observation);\n# self.actor_val = tf.placeholder(tf.float32, (None, 20, 2), name=\"asd\")\n# self.actor_action = tf.identity(self.get_last(self.actor_val), name=\"actor_action\")\n self.actor_action = tf.identity(self.actor.get_last(self.observation), name=\"actor_action\")\n# self.actor_action = tf.identity([[1.1, 1.1]], name=\"actor_action\")\n# tf.histogram_summary(\"actions\", self.actor_action)\n\n # FOR PREDICTING TARGET FUTURE REWARDS\n with tf.name_scope(\"estimating_future_reward\"):\n# self.next_observation = tf.placeholder(tf.float32, (None, self.observation_size), name=\"next_observation\")\n self.next_observation_mask = tf.placeholder(tf.float32, (None,), name=\"next_observation_mask\")\n self.next_action = tf.stop_gradient(self.target_actor(self.next_observation)) # ST\n# print \"next action: \" + str(self.next_action)\n tf.histogram_summary(\"target_actions\", self.next_action)\n self.next_value = tf.stop_gradient(\n tf.reshape(\n self.target_critic(self.concat_nn_lstm_input(self.next_observation, self.add_pow_values(self.next_action))),\n [-1]\n )\n ) # ST\n self.rewards = tf.placeholder(tf.float32, (None,), name=\"rewards\")\n self.future_reward = self.rewards + self.discount_rate * self.next_observation_mask * self.next_value\n\n with tf.name_scope(\"critic_update\"):\n ##### ERROR FUNCTION #####\n# self.given_action = tf.placeholder(tf.float32, (None, self.action_size), name=\"given_action\")\n self.value_given_action = tf.reshape(\n self.critic(self.concat_nn_lstm_input(self.observation, self.add_pow_values(self.given_action))),\n [-1]\n )\n\n tf.scalar_summary(\"value_for_given_action\", tf.reduce_mean(self.value_given_action))\n temp_diff = self.value_given_action - self.future_reward\n\n self.critic_error = tf.identity(tf.reduce_mean(tf.square(temp_diff)), name='critic_error')\n ##### OPTIMIZATION #####\n critic_gradients = self.optimizer.compute_gradients(self.critic_error, var_list=self.critic.variables())\n # Add histograms for gradients.\n for grad, var in critic_gradients:\n tf.histogram_summary('critic_update/' + var.name, var)\n if grad is not None:\n tf.histogram_summary('critic_update/' + var.name + '/gradients', grad)\n self.critic_update = self.optimizer.apply_gradients(critic_gradients, name='critic_train_op')\n tf.scalar_summary(\"critic_error\", self.critic_error)\n\n with tf.name_scope(\"actor_update\"):\n ##### ERROR FUNCTION #####\n self.actor_score = self.critic(self.concat_nn_lstm_input(self.observation, self.add_pow_values(self.actor_val)))\n\n ##### OPTIMIZATION #####\n # here we are maximizing actor score.\n # only optimize actor variables here, while keeping critic constant\n actor_gradients = self.optimizer.compute_gradients(tf.reduce_mean(-self.actor_score), var_list=self.actor.variables())\n # Add histograms for gradients.\n for grad, var in actor_gradients:\n tf.histogram_summary('actor_update/' + var.name, var)\n if grad is not None:\n tf.histogram_summary('actor_update/' + var.name + '/gradients', grad)\n self.actor_update = self.optimizer.apply_gradients(actor_gradients, name='actor_train_op')\n tf.scalar_summary(\"actor_score\", tf.reduce_mean(self.actor_score))\n\n # UPDATE TARGET NETWORK\n with tf.name_scope(\"target_network_update\"):\n self.target_actor_update = ContinuousDeepQLSTMStepped.update_target_network(self.actor, self.target_actor, self.target_actor_update_rate)\n self.target_critic_update = ContinuousDeepQLSTMStepped.update_target_network(self.critic, self.target_critic, self.target_critic_update_rate)\n self.update_all_targets = tf.group(self.target_actor_update, self.target_critic_update, name='target_networks_update')\n\n self.summarize = tf.merge_all_summaries()\n self.no_op1 = tf.no_op()\n\n def action(self, observation, disable_exploration=False):\n \"\"\"Given observation returns the action that should be chosen using\n DeepQ learning strategy. Does not backprop.\"\"\"\n assert len(observation.shape) == 1, \\\n \"Action is performed based on single observation.\"\n\n self.actions_executed_so_far += 1\n noise_sigma = ContinuousDeepQ.linear_annealing(self.actions_executed_so_far,\n self.exploration_period,\n 1.0,\n self.exploration_sigma)\n\n action = self.s.run(self.actor_action, {self.observation: observation[np.newaxis,:]})[0]\n if not disable_exploration:\n action += np.random.normal(0, noise_sigma, size=action.shape)\n action = np.clip(action, -1., 1.)\n\n return action\n\n def store(self, observation, action, reward, newobservation):\n \"\"\"Store experience, where starting with observation and\n execution action, we arrived at the newobservation and got thetarget_network_update\n reward reward\n If newstate is None, the state/action pair is assumed to be terminal\n \"\"\"\n if self.number_of_times_store_called % self.store_every_nth == 0:\n self.experience.append((observation, action, reward, newobservation))\n if len(self.experience) > self.max_experience:\n self.experience.popleft()\n self.number_of_times_store_called += 1\n\n def training_step(self):\n \"\"\"Pick a self.minibatch_size exeperiences from reply buffer\n and backpropage the value function.\n \"\"\"\n if self.number_of_times_train_called % self.train_every_nth == 0:\n if len(self.experience) < self.minibatch_size:\n return\n\n # sample experience (need to be a twoliner, because deque...)\n samples = random.sample(range(len(self.experience)), self.minibatch_size)\n samples = [self.experience[i] for i in samples]\n\n # bach states\n states = np.empty((len(samples), self.observation_size))\n newstates = np.empty((len(samples), self.observation_size))\n actions = np.zeros((len(samples), self.action_size))\n\n newstates_mask = np.empty((len(samples),))\n rewards = np.empty((len(samples),))\n\n for i, (state, action, reward, newstate) in enumerate(samples):\n states[i] = state\n actions[i] = action\n rewards[i] = reward\n if newstate is not None:\n newstates[i] = newstate\n newstates_mask[i] = 1.\n else:\n newstates[i] = 0\n newstates_mask[i] = 0.\n\n _, _, summary_str = self.s.run([\n self.actor_update,\n self.critic_update,\n self.summarize if self.iteration % 100 == 0 else self.no_op1,\n ], {\n self.observation: states,\n self.next_observation: newstates,\n self.next_observation_mask: newstates_mask,\n self.given_action: actions,\n self.rewards: rewards,\n })\n\n self.s.run(self.update_all_targets)\n\n if self.summary_writer is not None and summary_str is not None:\n self.summary_writer.add_summary(summary_str, self.iteration)\n\n self.iteration += 1\n\n self.number_of_times_train_called += 1\n","sub_path":"TensorflowGraph/tf_rl/controller/continnous_deepq_lstm_stepped.py","file_name":"continnous_deepq_lstm_stepped.py","file_ext":"py","file_size_in_byte":15342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"373399840","text":"import os\nimport matplotlib.pyplot as plt\nfrom pylab import *\nmpl.rcParams['font.sans-serif'] = ['SimHei']\n\n\ndef main():\n path = 'E:\\\\工作\\\\新零售\\\\十店\\\\货架互动数据采集\\\\all_test'\n filenames = ['predict_failed_test.txt', 'predict_failed_train.txt']\n all_actions = []\n for filename in filenames:\n actions = start(path, filename)\n all_actions.append(actions)\n draw(all_actions, filenames)\n # print('{}'.format(all_actions[0], all_actions[1]))\n\ndef start(path, filename):\n file_path = os.path.join(path, filename)\n with open(file_path, 'r', encoding='utf-8') as f:\n content = f.readlines()\n result_dict = get_result(content)\n actions = get_actions(result_dict)\n return actions\n\n\n\n\ndef get_result(content):\n failed_dict = {}\n for i in content:\n if '\\t' in i:\n i = i.split('\\t')\n filename = i[0][1:-1]\n else:\n i = i.split(' ')\n while '' in i:\n i.remove('')\n filename = i[0]\n # print(i)\n try:\n predx = float(i[1])\n predy = float(i[2])\n actualx = float(i[3])\n actualy = float(i[4])\n xoffset = float(i[5])\n yoffset = float(i[6])\n xframeoffset = float(i[7])\n yframeoffset = float(i[8])\n left = float(i[9])\n right = float(i[10])\n top = float(i[11])\n bottom = float(i[12])\n result = i[13]\n\n failed_dict[filename] = {\n 'filename': filename,\n 'predx': predx,\n 'predy': predy,\n 'actualx': actualx,\n 'actualy': actualy,\n 'xoffset': xoffset,\n 'yoffset': yoffset,\n 'xframeoffset': xframeoffset,\n 'yframeoffset': yframeoffset,\n 'left': left,\n 'right': right,\n 'top': top,\n 'bottom': bottom,\n 'result': result\n }\n except:\n continue\n return failed_dict\n\n\ndef get_actions(result_dict):\n actions = [0, 0, 0]\n for filename in result_dict:\n if result_dict[filename]['result'] == 'failed':\n file_action = filename.split('-')[12]\n if '左进' in file_action:\n actions[0] += 1\n elif '直进' in file_action:\n actions[1] += 1\n else:\n actions[2] += 1\n return actions\n\n\ndef draw(all_actions, filenames):\n x1 = [x - 0.2 for x in range(1, 4)]\n x2 = [x + 0.2 for x in range(1, 4)]\n print(all_actions)\n plt.rcParams['figure.figsize'] = (6.0, 6.0)\n action_list = ['左进', '直进', '右进']\n plt.subplot(1, 1, 1)\n l1 = plt.bar(x1, all_actions[0], color='g', width=0.4)\n l2 = plt.bar(x2, all_actions[1], color='b', width=0.4)\n action_test= all_actions[0][0] + all_actions[0][1] + all_actions[0][2]\n action_train = all_actions[1][0] + all_actions[1][1] + all_actions[1][2]\n for x1, x2, all_actions[0], all_actions[1] in zip(x1, x2, all_actions[0], all_actions[1]):\n\n plt.text(x1, all_actions[0], '{}, {:.2f}%'.format(all_actions[0], all_actions[0]/action_test*100), ha='center', va='bottom')\n plt.text(x2, all_actions[1], '{}, {:.2f}%'.format(all_actions[1], all_actions[1]/action_train*100), ha='center', va='bottom')\n # plt.xticks(action_list)\n plt.show()\n plt.close()\n\n\nif __name__ == '__main__':\n main()","sub_path":"xy预测/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":3508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"472864521","text":"from collections import defaultdict as dd\nimport pickle as pkl\nimport numpy as np\nimport scipy.sparse as sp\nimport random\n\nlabels = {\"Case_Based\": 5,\n \"Genetic_Algorithms\": 2,\n \"Neural_Networks\": 3,\n \"Probabilistic_Methods\": 4,\n \"Reinforcement_Learning\": 1,\n \"Rule_Learning\": 6,\n \"Theory\": 0}\n\n\ndef one_hot_encoding(size, index):\n y = [0] * size\n y[index] = 1\n return y\n\n\ndef add_index(index, cnt, key):\n \"\"\"\n feed in current cnt, which has not been used\n if key exists, then dont use it and return current cnt\n otherwise, use the current cnt, and add 1\n \"\"\"\n if key in index: return cnt\n index[key] = cnt\n return cnt + 1\n\n\ndef process_data(filename, labels):\n allx, ally, tx, ty, x, y = [], [], [], [], [], []\n index, cnt = {}, 0\n _x = {_: [] for _ in labels}\n _y = {_: 0 for _ in labels}\n with open(filename, 'r') as f:\n lines = f.readlines()\n for i, line in enumerate(lines[:500]):\n inputs = line.strip().split()\n cnt = add_index(index, cnt, inputs[0])\n features = [float(_) for _ in inputs[1:-1]]\n one_hot_label = one_hot_encoding(len(labels), labels[inputs[-1]])\n allx.append(features)\n ally.append(one_hot_label)\n if i < 140:\n x.append(features)\n y.append(one_hot_label)\n _y[inputs[-1]] += 1\n _x[inputs[-1]].append(i)\n # for key in _x:\n # idx = random.sample(_x[key],20)\n # x += [allx[i] for i in idx]\n # y += [ally[i] for i in idx]\n for i, line in enumerate(lines[500:1500]):\n inputs = line.strip().split()\n cnt = add_index(index, cnt, inputs[0])\n tx.append([float(_) for _ in inputs[1:-1]])\n ty.append(one_hot_encoding(len(labels), labels[inputs[-1]]))\n _y[inputs[-1]] += 1\n\n for i, line in enumerate(lines[1500:]):\n inputs = line.strip().split()\n cnt = add_index(index, cnt, inputs[0])\n features = [float(_) for _ in inputs[1:-1]]\n one_hot_label = one_hot_encoding(len(labels), labels[inputs[-1]])\n allx.append(features)\n ally.append(one_hot_label)\n _y[inputs[-1]] += 1\n _x[inputs[-1]].append(i)\n pkl.dump(sp.csr_matrix(np.array(x)), open(\"ind.cora.x\", \"wb\"))\n pkl.dump(sp.csr_matrix(np.array(tx)), open(\"ind.cora.tx\", \"wb\"))\n pkl.dump(sp.csr_matrix(np.array(allx)), open(\"ind.cora.allx\", \"wb\"))\n pkl.dump(np.array(y), open(\"ind.cora.y\", \"wb\"))\n pkl.dump(np.array(ty), open(\"ind.cora.ty\", \"wb\"))\n pkl.dump(np.array(ally), open(\"ind.cora.ally\", \"wb\"))\n return index\n\n\n\n\ndef read_cites(filename, index):\n cites, parents, graph = [], dd(list), dd(list)\n for i, line in enumerate(open(filename)):\n inputs = line.strip().split()\n cites.append((inputs[0], inputs[1]))\n for id1, id2 in cites:\n # cnt = add_index(index, cnt, id1)\n # cnt = add_index(index, cnt, id2)\n i, j = index[id1], index[id2]\n parents[j].append(i)\n graph[i].append(j)\n graph[j].append(i)\n pkl.dump(parents, open(\"ind.cora.parents\", \"wb\"))\n pkl.dump(graph, open(\"ind.cora.graph\", \"wb\"))\n return parents, graph\n\n\n# index = process_data(\"cora.content\",labels)\n# read_cites(\"cora.cites\",index)\n# f = open(\"ind.cora.test.index\",\"w\")\n# a = list(range(500,1500))\n# for i in a:\n# f.write(str(i)+\"\\n\")\n# f.close()\n\nread_content(\"cora\")\n","sub_path":"gcn/data/process_data.py","file_name":"process_data.py","file_ext":"py","file_size_in_byte":3536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"582761136","text":"import uuid\nimport os\n\nfrom flask import Flask, render_template, abort, request, redirect, url_for\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\napp = Flask(__name__)\napp.config[\"SECRET_KEY\"] = os.environ[\"SECRET_KEY\"]\n\n\ndef render_page(name, root=\"templates/example\"):\n try:\n with open(\"{}/{}.txt\".format(root, name), \"r\") as fd:\n code = fd.read()\n except FileNotFoundError:\n abort(404)\n return render_template(\"index.html\", examples=load_examples(), code=code)\n\n\n@app.route(\"/\", methods=(\"GET\", \"POST\"))\ndef index():\n if request.method == \"POST\":\n return custom()\n return render_page(\"print-all-the-ones\")\n\n\n@app.route(\"/example//\", methods=(\"GET\", \"POST\"))\ndef example(name):\n if request.method == \"POST\":\n return custom()\n return render_page(name)\n\n\n@app.route(\"/custom//\", methods=(\"GET\", \"POST\"))\n@app.route(\"/custom/\", methods=(\"GET\", \"POST\"))\ndef custom(id=None):\n if request.method == \"POST\":\n if id is None:\n id = uuid.uuid4()\n with open(\"custom/{}.txt\".format(id), \"w\") as fd:\n fd.write(request.form[\"code\"])\n return redirect(url_for(\"custom\", id=id))\n return render_page(id, root=\"custom\")\n\n\ndef load_examples():\n path = os.path.join(\"templates\", \"example\")\n for f in os.listdir(path):\n with open(os.path.join(path, f), \"r\") as fd:\n for l in fd.readlines():\n if l.startswith(\"name:\"):\n filename, _ = os.path.splitext(f)\n yield {\"name\": l[5:].strip(), \"filename\": filename}\n break\n\n\nif __name__ == \"__main__\":\n app.run(debug=True, host=\"0.0.0.0\")\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"95398847","text":"# Write a function to create a movie where a red circle is moving from the top to the bottom\n# and another item is moving from the bottom to the top.\n\n\n\ndef circleMovie(directory):\n for n in range(1,90):\n canvas = makeEmptyPicture(640,480)\n # ball one\n addOvalFilled(canvas,n+10,n*10,35,35,red) \n # ball two\n addRectFilled(canvas, n+500,getHeight(canvas)-n*10,60,10,blue)\n nString = str(n)\n if n < 10:\n writePictureTo(canvas, directory+'/frame0'+nString+'.jpeg')\n if n >= 10:\n writePictureTo(canvas, directory+'/frame'+nString+'.jpeg')\n circleMovie = makeMovieFromInitialFile(directory+'/frame01.jpeg')\n # return(circleMovie)\n playMovie(circleMovie) ","sub_path":"programs/project/projecta.py","file_name":"projecta.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"187411814","text":"\n#!/usr/bin/env python\n\nimport boto3\n\n# Connect to the Amazon EC2 service\nec2_client = boto3.client('ec2')\n\n# Create a Key Pair\nkey = ec2_client.create_key_pair(KeyName = 'SDK')\n\n# Print the private Fingerprint of the private key\nprint(key.get('KeyFingerprint'))\n","sub_path":"create-keypair.py","file_name":"create-keypair.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"497962801","text":"import tensorflow as tf\nimport collections\n\nimport os\nimport json, xmljson\nfrom lxml.etree import fromstring, tostring\nimport re\n\nfrom tensorflow.python.ops import rnn\nimport datetime\n\nimport numpy as np\n\nimport pdb\n\ndataDir = '../data/one_word.txt'\nwords = []\nskip_window = 2\n\nembedding_size = 32\n\n_WORD_SPLIT = re.compile(\"([.,!?\\\"':;)(])\")\ndef basic_tokenizer(sentence):\n \"\"\"Very basic tokenizer: split the sentence into a list of tokens.\"\"\"\n words = []\n for space_separated_fragment in sentence.strip().split():\n words.extend(re.split(_WORD_SPLIT, space_separated_fragment))\n return [w for w in words if w]\n\ndef clean_data(text):\n\treturn text.translate ({ord(c): \" \" for c in '!@#$%^&*()[]{};:,./<>?\\|`~-=_+\"'})\n\ndef preprocess_data(text):\n\t# text = clean_data(text)\n\ttext = text.lower()\n\treturn text\n\ndef build_dataset(words):\n words += ['UNK','']\n\n dictionary = dict()\n\n for word in words:\n if dictionary.get(word, -1)==-1:\n dictionary[word] = len(dictionary)\n\n reverse_dictionary = dict(zip(dictionary.values(), dictionary.keys()))\n\n return dictionary, reverse_dictionary\n\n# Step 2: Build the dictionary and replace rare words with UNK token.\ndef get_num_words(words):\n return len(words)\n\n\n#read data file; do some preprocessing.\ndef read_data(file_path,skip_window=skip_window):\n\tdata = []\n\n\twith open(file_path, 'r') as f:\n\t\tlines = f.readlines()\n\t\tfor line in lines:\n\t\t\tdata.append(preprocess_data(line))\n\n\treturn data\n\n#read data for wor2vec\n# Read the data into a list of strings\ndef get_words(sentences):\n\twords = []\n\tfor sent in sentences:\n\t\twords += basic_tokenizer(sent)\n\n\treturn words\n\nsentences = read_data(dataDir)\nwords = get_words(sentences)\ndictionary, reverse_dictionary = build_dataset(words)\nvocabulary_size = len(dictionary)\nprint(\"Vocabulary_size\")\nprint(vocabulary_size)\n\n#write the dictionary to a file\nwith open('dictionary_end2end.json', 'w') as f:\n\tjson.dump(dictionary,f,indent=4)\n\n\n#training data preprocessor\nprint('Tokenizing sentences...')\nin_sent_arr = []\nin_token_arr = []\nout_word_arr = []\nout_token_arr = []\nmax_seq_len = 0\nfor index,line in enumerate(sentences):\n\ttokenized = basic_tokenizer(line)\n\t# if index==0:\n\t\t# print(\"tokenized\")\n\t\t# print(tokenized)\n\tif len(tokenized)>max_seq_len:\n\t\tmax_seq_len = len(tokenized)\n\n\tif index%2==0:\n\t\tin_sent_arr.append(line)\n\t\tin_token_arr.append(tokenized)\n\telse:\n\t\tout_word_arr.append(line)\n\t\tout_token_arr.append(tokenized)\nprint(\"Done Tokenizing\")\nprint(\"max_seq_len\")\nprint(max_seq_len)\n\n# window = 10\nseq_len = max_seq_len\nhop = 1\n#prepare the training data\ndef get_training_data(in_sent_arr, out_word_arr, in_token_arr):\n\tinp = []\n\tout = []\n\n\tfor index,sent in enumerate(in_sent_arr):\n\t\ttokenized_in = in_token_arr[index]\n\t\ttokenized_out = out_token_arr[index]\n\t\tassert len(tokenized_out)==1, \"There must be only one output word\"\n\t\tcursor = 0\n\n\t\tpadding_len = (seq_len - len(tokenized_in))\n\t\tassert padding_len>=0, \"padding length must be >= 0\"\n\n\t\ttokenized_in = tokenized_in+['']*padding_len\n\n\t\tseq_in = []\n\t\tfor token in tokenized_in:\n\t\t\t# if index==0:\n\t\t\t# \tprint(\"token\")\n\t\t\t# \tprint(token)\n\t\t\t# \tprint(dictionary.get(token))\n\t\t\tcur_in_token = dictionary.get(token, -1)\n\t\t\tseq_in.append(cur_in_token if cur_in_token>-1 else dictionary[\"UNK\"])\n\t\tcur_out_token = dictionary.get(tokenized_out[0], -1)\n\t\tseq_out = cur_out_token if cur_out_token>-1 else dictionary[\"UNK\"]\n\n\t\t#reverse the sequence of tokens for input\n\t\tinp.append(seq_in[::-1])\n\t\t# out.append([seq_out])\n\t\tout.append([index])\n\n\n\treturn inp, out\n\nNUM_CLASSES = len(out_word_arr)\nprint(\"number of classes\")\nprint(NUM_CLASSES)\ntraining_in_data, training_out_data = get_training_data(in_sent_arr,out_word_arr,in_token_arr)\n\nwith open('../data/training_in_data.txt', 'w') as f:\n\tjson.dump(training_in_data,f,indent=4)\nwith open('../data/training_out_data.txt', 'w') as f:\n\tjson.dump(training_out_data,f,indent=4)\nwith open('../data/training_in_data_text.txt', 'w') as f:\n\tjson.dump(in_sent_arr,f,indent=4)\nwith open('../data/training_out_data_text.txt', 'w') as f:\n\tjson.dump(out_word_arr,f,indent=4)\n\n#define the loas function\ndef getLoss(params):\n\tlogits = None\n\tif params['mode'] == \"train\":\n\t\tloss = tf.nn.nce_loss(\n\t weights=params['weights'],\n\t biases=params['biases'],\n\t labels=params['labels'],\n\t inputs=params['inputs'],\n\t num_sampled=params['num_sampled'],\n\t num_classes=params['num_classes'],\n\t num_true=params['num_true'],\n\t partition_strategy=\"div\")\n\telif params['mode'] == \"eval\":\n\t\tlogits = tf.matmul(params['inputs'], tf.transpose(params['weights']))\n\t\tlogits = tf.nn.bias_add(logits, params['biases'])\n\t\tlabels_reshaped = tf.reshape(params['labels'],[-1])\n\t\tlabels_one_hot = tf.one_hot(labels_reshaped, params['num_classes'])\n\t\tloss = tf.nn.sigmoid_cross_entropy_with_logits(\n\t labels=labels_one_hot,\n\t logits=logits)\n\t\n\t\tloss = tf.reduce_sum(loss, axis=1)\n\n\treturn loss, logits\n\ndef getAccuracy(labels,logits):\n\t# print(\"The shape of labels is {}, but the shpe of logits is {}\".format(len(labels),logits.shape))\n\tassert(len(labels)==logits.shape[0]), \"The number of labels and logits must be the same\"\n\t# print(\"labels\")\n\t# print(labels)\n\t# print(\"logits\")\n\t# print(logits)\n\tlabels_reshaped = np.reshape(labels,[-1])\n\t# print(np.argmax(logits,axis=1))\n\t# print(labels_reshaped)\n\treturn np.sum(np.equal(labels_reshaped,np.argmax(logits,axis=1)))/logits.shape[0]\n\ndef batch_iter(data, batch_size, num_epochs, shuffle=True):\n \"\"\"\n Generates a batch iterator for a dataset.\n \"\"\"\n data = np.array(data)\n data_size = len(data)\n num_batches_per_epoch = int((len(data)-1)/batch_size) + 1\n overflow_size = data_size%batch_size\n padding_size = (batch_size-overflow_size)%batch_size\n\n for epoch in range(num_epochs):\n # Shuffle the data at each epoch\n if shuffle:\n shuffle_indices = np.random.permutation(np.arange(data_size))\n shuffled_data = data[shuffle_indices]\n else:\n shuffled_data = data\n for batch_num in range(num_batches_per_epoch):\n if batch_num == num_batches_per_epoch-1:\n start_index = batch_num * batch_size - padding_size\n else: \n start_index = batch_num * batch_size\n end_index = min((batch_num + 1) * batch_size, data_size)\n yield shuffled_data[start_index:end_index]\n\ndef lstm_cell(lstm_size, output_keep_prob=1.0):\n # return tf.contrib.rnn.BasicLSTMCell(lstm_size)\n encoDecoCell = tf.contrib.rnn.BasicLSTMCell(lstm_size, state_is_tuple=True) # Or GRUCell, LSTMCell(args.hiddenSize)\n #Only for training output_keep_prob is 0.5\n encoDecoCell = tf.contrib.rnn.DropoutWrapper(encoDecoCell, input_keep_prob=1.0, output_keep_prob=output_keep_prob) # TODO: Custom values\n return encoDecoCell\n\ndef train_step(x_batch, y_batch, input_x, input_y, loss, train_step_op, step_num):\n \"\"\"\n A single training step\n \"\"\"\n feed_dict = {\n input_x: x_batch,\n input_y: y_batch,\n }\n\n _, loss = sess.run(\n [train_step_op, loss],\n feed_dict)\n\n loss = np.sum(loss)/loss.shape[0]\n print(\"{}: step, {} loss\".format(step_num, loss))\n\ndef eval_step(x_batch, y_batch, input_x, input_y, eval_loss, logits, step_num):\n \"\"\"\n eval step\n \"\"\"\n feed_dict = {\n input_x: x_batch,\n input_y: y_batch,\n }\n\n loss, logits = sess.run(\n [eval_loss,logits],\n feed_dict)\n print('shape of logits')\n print(logits.shape)\n accuracy = getAccuracy(y_batch,logits)\n print()\n print(\"{}: step, {} accuracy\".format(step_num, accuracy))\n print()\t\n\n\ngraph = tf.Graph()\nnum_epochs = 2000\nsave_every = 100\neval_after = 100\ncheckpoint_dir = \"model\"\ncheckpoint_prefix = os.path.join(checkpoint_dir, \"model\")\nrestore = True\n# model_to_restore_from = os.path.join(checkpoint_dir, \"model-468572.ckpt\")\nwith graph.as_default():\n\tsess = tf.Session(graph=graph)\n\twith sess.as_default():\n\t\tsequence_length = seq_len\n\t\tvocab_size = len(dictionary)\n\t\toutput_keep_prob = 1.0\n\n\t\tbatch_size = 10\n\n\t\thiddenSize = 32\n\n\t\tnum_true = 1\n\t\tnum_sampled = 32\n\t\tnum_classes = NUM_CLASSES\n\n\t\tinput_x_plh = tf.placeholder(tf.int32, shape=(batch_size, sequence_length), name=\"input_x\")\n\t\tinput_y = tf.placeholder(tf.int32, shape=(batch_size,num_true), name=\"input_y\")\n\n\t\tinput_x = tf.Variable(np.zeros((batch_size, sequence_length)), dtype=tf.int32)\n\t\tinput_x = tf.assign(input_x,input_x_plh)\n\n\t\t#This will be the weights variable for the nce loss\n\t\tembedding_var_inp = tf.Variable(\n \ttf.random_uniform([vocabulary_size, embedding_size], minval=-1.0, maxval=1.0),name=\"embedding_inp\")\n\t\tembedding_var_out = tf.Variable(\n \ttf.random_uniform([num_classes, embedding_size], minval=-1.0, maxval=1.0),name=\"embedding_out\")\n\t\t#This will be the bias variable for the nce loss\n\t\tbias_var = tf.Variable(tf.zeros(num_classes),name=\"emb_bias\")\n\n\t\tembedded_chars_x = tf.nn.embedding_lookup(embedding_var_inp, input_x)\n\t\tembedded_chars_x = tf.transpose(embedded_chars_x,perm=[0,2,1])\t\n\t\tembedded_chars_x_list = [tf.reshape(tf.slice(embedded_chars_x,[0,0,i],[batch_size,embedding_size,1]),[batch_size,embedding_size]) for i in range(sequence_length)]\n\n\n\t\tembedded_chars_y = tf.nn.embedding_lookup(embedding_var_out, input_y)\n\t\t# embedded_chars_y = tf.transpose(embedded_chars_y,perm=[0,2,1])\n\t\t# embedded_chars_y_list = [tf.reshape(tf.slice(embedded_chars_y,[0,0,i],[batch_size,embedding_size,1]),[batch_size,embedding_size]) for i in range(sequence_length)]\n\n\n\t\tencoDecoCell1 = lstm_cell(hiddenSize, output_keep_prob=output_keep_prob)\n\t\tencoDecoCell2 = lstm_cell(hiddenSize, output_keep_prob=output_keep_prob)\n\t\tencoDecoCell = tf.contrib.rnn.MultiRNNCell([encoDecoCell1,encoDecoCell2], state_is_tuple=True)\n\t\tsess.run(tf.global_variables_initializer())\n\n\t\tencoder_outputs_x, encoder_state_x = rnn.static_rnn(encoDecoCell, embedded_chars_x_list, dtype=tf.float32)\n\t\t# encoder_outputs_y, encoder_state_y = rnn.static_rnn(encoDecoCell, embedded_chars_y_list,dtype=tf.float32)\n\n\t\ttrain_loss,_ = getLoss({\n\t \t'mode': 'train',\n\t \t'weights': embedding_var_out,\n\t\t\t'biases': bias_var,\n\t\t\t'labels': input_y,\n\t\t\t'inputs': encoder_outputs_x[-1],\n\t\t\t'num_sampled': num_sampled,\n\t\t\t'num_classes': num_classes,\n\t\t\t'num_true': num_true\n \t})\n\t\teval_loss,logits = getLoss({\n\t \t'mode': 'eval',\n\t \t'weights': embedding_var_out,\n\t\t\t'biases': bias_var,\n\t\t\t'labels': input_y,\n\t\t\t'inputs': encoder_outputs_x[-1],\n\t\t\t'num_sampled': num_sampled,\n\t\t\t'num_classes': num_classes,\n\t\t\t'num_true': num_true\n \t})\n\t\t# loss = tf.losses.mean_squared_error(embedded_chars_y,encoder_outputs_x[-1])\n\t\t# train_step_op = tf.train.AdamOptimizer(1e-3).minimize(train_loss)\n\t\toptimizer = tf.train.AdamOptimizer(1e-3)\n\t\tgradients, variables = zip(*optimizer.compute_gradients(loss))\n\t\tgradients = [\n \t\tNone if gradient is None else tf.clip_by_norm(gradient, 5.0)\n \t\tfor gradient in gradients]\n\t\ttrain_step_op = optimizer.apply_gradients(zip(gradients, variables))\n\n\t\tbatches = batch_iter(\n list(zip(training_in_data, training_out_data)), batch_size, num_epochs)\n\n\t\tprint(\"*************Initialising variables*****************\")\n\t\tfor v in tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES):\n\t\t\tprint(\"Initialising \" + v.op.name)\n\t\t\tsess.run(v.initializer)\n\t\tprint(\"Uninitialised varaiables\")\n\t\tprint(tf.report_uninitialized_variables())\n\t\tsaver = tf.train.Saver(max_to_keep=5)\n\n\t\t#restore the model if restore is set to true\n\t\tif restore:\n\t\t\tlatest_checkpoint = tf.train.latest_checkpoint(checkpoint_dir)\n\t\t\tprint('latest_checkpoint')\n\t\t\tprint(latest_checkpoint)\n\t\t\tsaver.restore(sess,latest_checkpoint)\n\t\t\tstart_index_model = latest_checkpoint.rfind('-') + 1\n\t\t\tstep = int(latest_checkpoint[start_index_model:])\n\t\t\tprint('step')\n\t\t\tprint(step)\n\t\telse:\n\t\t\tstep = 0\n\t\ttry:\n\t\t\tfor batch in batches:\n\t\t\t\tx_batch, y_batch = zip(*batch)\n\t\t\t\tfor _ in range(1):\n\t\t\t\t\tstep += 1\n\t\t\t\t\ttrain_step(x_batch,y_batch,input_x,input_y,train_loss,train_step_op,step)\n\t\t\t\t\tif step%save_every == 0:\n\t\t\t\t\t\tsaver.save(sess,checkpoint_prefix,global_step=step)\n\t\t\t\t\t\tprint(\"Saving checkpoint to {}-{}\".format(checkpoint_prefix,step))\n\t\t\t\t\tif step%eval_after==0:\n\t\t\t\t\t\teval_step(x_batch,y_batch,input_x,input_y,eval_loss,logits,step)\n\n\t\t\t\t\t\n\t\texcept KeyboardInterrupt:\n\t\t\tprint(\"***********KeyboardInterrupt******************\")\n\t\t\tsaver.save(sess,checkpoint_prefix,global_step=step)\n\t\t\tprint(\"Saving checkpoint to {}-{}\".format(checkpoint_prefix,step))","sub_path":"ml/train_end2end.py","file_name":"train_end2end.py","file_ext":"py","file_size_in_byte":12470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"422321907","text":"import numpy as np\r\nfrom SynapticDynamics import FiringMask\r\n\r\n\r\nclass Ensemble(object):\r\n def __init__(self, simenv, num_neurons, **ensemble_params):\r\n \"\"\"\r\n\r\n Args:\r\n simenv (Environments.Simulation):\r\n num_neurons (int):\r\n **ensemble_params (dict):\r\n u_rest (numpy.darray): (num_neurons, )\r\n tau_m (numpy.darray): (num_neurons, )\r\n u_threshold (numpy.darray): (num_neurons, )\r\n u_reset (numpy.darray): (num_neurons, )\r\n g_excite_const (numpy.darray): (num_neurons, num_neurons)\r\n tau_excite (numpy.darray): (num_neurons, num_neurons)\r\n g_inhib_const (numpy.darray): (num_neurons, num_neurons)\r\n tau_inhib (numpy.darray): (num_neurons, num_neurons)\r\n E_excite (numpy.darray): (num_neurons, num_neurons)\r\n E_inhib (numpy.darray): (num_neurons, num_neurons)\r\n E_run (float):\r\n E_theta (float)\r\n weights_excite (numpy.darray): (num_neurons, num_neurons)\r\n weights_inhib (numpy.darray): (num_neurons, num_neurons)\r\n \"\"\"\r\n self.num_neurons = num_neurons\r\n self.simenv = simenv\r\n self.ensemble_params = ensemble_params\r\n\r\n # Initialize ensemble\r\n self._initialise_ensembles_params()\r\n\r\n # Initialize synaptic parameters\r\n self.g_excite, self.g_inhib = np.zeros((num_neurons, num_neurons)), np.zeros((num_neurons, num_neurons))\r\n self._initialise_synaptic_current_params()\r\n self.synaptic_currents = np.zeros((num_neurons,)) # spike-input related\r\n\r\n # Firing\r\n self.firing_mask = FiringMask(num_neurons)\r\n\r\n # External input parameters\r\n self.E_run = ensemble_params[\"E_run\"]\r\n self.E_theta = ensemble_params[\"E_theta\"]\r\n\r\n # Weights\r\n self.weights_excite = ensemble_params['weights_excite']\r\n self.weights_inhib = ensemble_params['weights_inhib']\r\n\r\n\r\n def state_update(self):\r\n self._membrane_potential_dyanmics_update()\r\n self._threshold_crossing() # Register which neurons fire and reset potentials\r\n # if np.sum(self.firing_mask.get_mask()) > 0:\r\n # import pdb\r\n # pdb.set_trace()\r\n self._calc_synaptic_current()\r\n self._syn_current_dynamics_update()\r\n self.simenv.increment()\r\n return self.simenv.check_end()\r\n\r\n def _membrane_potential_dyanmics_update(self):\r\n inputs_dict = self.simenv.get_inputs()\r\n du_dt = (self.u_rest-self.u)/self.tau_m \\\r\n + self.synaptic_currents \\\r\n + (self.E_run - self.u) * inputs_dict[\"run\"] \\\r\n + (self.E_theta - self.u) * inputs_dict[\"theta\"]\r\n\r\n self.u += du_dt * self.simenv.get_dt()\r\n\r\n def _threshold_crossing(self):\r\n self.firing_mask.update_mask(self.u, self.u_threshold)\r\n self.u[self.firing_mask.get_mask()] = self.u_reset[self.firing_mask.get_mask()]\r\n\r\n def _calc_synaptic_current(self):\r\n\r\n u_2d = np.repeat(self.u.reshape(1, -1), self.num_neurons, axis=0) # Expand row-wise\r\n current_2d_excite = self.g_excite * (self.E_excite - u_2d) * self.weights_excite\r\n current_2d_inhib = self.g_inhib * (self.E_inhib - u_2d) * self.weights_inhib\r\n current_1d = np.sum(current_2d_excite, axis=1) + np.sum(current_2d_inhib, axis=1)\r\n self.synaptic_currents = current_1d\r\n\r\n def _syn_current_dynamics_update(self):\r\n dg_excite = -self.g_excite/(self.tau_excite+1e-9) + self.g_excite_const * self.firing_mask.get_2d_rows()\r\n dg_inhib = -self.g_inhib/(self.tau_inhib+1e-9) + self.g_inhib_const * self.firing_mask.get_2d_rows()\r\n self.g_excite += dg_excite * self.simenv.get_dt()\r\n self.g_inhib += dg_inhib * self.simenv.get_dt()\r\n\r\n def _initialise_ensembles_params(self):\r\n self.u_rest, self.tau_m, self.u_threshold, self.u_reset = self.ensemble_params[\"u_rest\"],\\\r\n self.ensemble_params[\"tau_m\"],\\\r\n self.ensemble_params[\"u_threshold\"],\\\r\n self.ensemble_params[\"u_reset\"]\r\n self.u = self.u_rest.copy()\r\n\r\n def _initialise_synaptic_current_params(self):\r\n self.g_excite_const, self.tau_excite, self.g_inhib_const, self.tau_inhib = self.ensemble_params[\"g_excite_const\"],\\\r\n self.ensemble_params[\"tau_excite\"],\\\r\n self.ensemble_params[\"g_inhib_const\"],\\\r\n self.ensemble_params[\"tau_inhib\"]\r\n self.E_excite, self.E_inhib = self.ensemble_params[\"E_excite\"], self.ensemble_params[\"E_inhib\"]\r\n\r\n\r\n","sub_path":"Ensembles.py","file_name":"Ensembles.py","file_ext":"py","file_size_in_byte":4984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"12902021","text":"from django import forms\nfrom .models import Usuario, Sector, Tarea, Estadotarea, Nivel, Prioridad, Estadosolicitud, Subtarea, Subtarea2, Solicitud, Tiempo\nfrom betterforms.multiform import MultiModelForm\n\nclass UsuarioForm(forms.ModelForm):\n usuario = forms.CharField(max_length=10, required=True, help_text='*')\n contraseña = forms.CharField(max_length=8, widget=forms.PasswordInput,required=True, help_text='*')\n\n class Meta:\n model = Usuario\n fields = ['usuario','contraseña']\n #labels = {'usuario':'Usuario','contraseña':'Contraseña'}\n\nclass UsuarioForm2(forms.ModelForm):\n contraseña = forms.CharField(max_length=8, widget=forms.PasswordInput, required=True, help_text=\"*\")\n class Meta:\n model = Usuario\n fields = ['usuario','contraseña','id_s']\n labels = {'usuario':'Usuario','contraseña':'Contraseña','id_s':'Sector'}\n\nclass SectorForm(forms.ModelForm):\n\n class Meta:\n model = Sector\n fields = ['sector']\n\nclass TareaForm(forms.ModelForm): # Field# Field name made lowercase.\n #class Meta:#No son campos (IntegerField, CharField, DateTimeField). Son metadatos específicos a la clase (Orden de muestra, nombres).\n #id_n = forms.ModelChoiceField(queryset=Nivel.objects.values())\n #tarea = forms.CharField(max_length=30, required=True)\n #id_e = forms.ModelChoiceField(queryset=Estadotarea.objects.values_list('id_e', flat=True), empty_label=None)\n #id_n = forms.ModelChoiceField(queryset=Nivel.objects.values_list('nivel', flat=True), empty_label=None)\n #id_us = forms.ModelChoiceField(queryset=Usuario.objects.values_list('usuario', flat=True), empty_label=None)\n #id_prioridad = forms.ModelChoiceField(queryset=Prioridad.objects.values_list('prioridad', flat=True), empty_label=None)\n class Meta:\n model = Tarea\n fields = ['tarea', 'id_n','id_prioridad']\n labels = {'tarea':'Nombre', 'id_n':'Nivel','id_prioridad':'Prioridad'}\n #objects.values()Retorna diccionarios.\n #objects.values_list()Retorna tuplas.\n #objects.values_list('', flat(texto plano)=True)Retorna listas.\n# fields = ['tarea', 'id_e', 'id_n', 'id_us', 'id_prioridad']#[] Los corchetes indican la creación de una nueva lista.\n #labels = {'tarea':'Nombre', 'id_e':'Estado', 'id_n':'Nivel', 'id_us':'Usuario', 'id_prioridad':'Prioridad'}\n\nclass EstadoTareaForm(forms.ModelForm):\n\n class Meta:\n model = Estadotarea\n fields = ['id_e','estado']\n\nclass EstadoSolicitudForm(forms.ModelForm):\n\n class Meta:\n model = Estadosolicitud\n fields = ['id_essol','estado']\n\nclass NivelForm(forms.ModelForm):\n\n class Meta:\n model = Nivel\n fields = ['id_n','nivel']\n\nclass PrioridadForm(forms.ModelForm):\n\n class Meta:\n model = Prioridad\n fields = ['id_prioridad','prioridad']\n\nclass SubTareaForm(forms.ModelForm):\n\n class Meta:\n model = Subtarea\n fields = ['id_sub','starea','id_prioridad']\n\nclass SubTarea2Form(forms.ModelForm):\n\n class Meta:\n model = Subtarea2\n fields = ['id_sub2','starea2','id_prioridad']\n\nclass SolicitudForm(forms.ModelForm):\n\n class Meta:\n model = Solicitud\n fields = ['id_sol','solicitud','id_s']\n labels = {'id_s':'Sector'}\n\nclass TiempoForm(forms.ModelForm):\n\n class Meta:\n model = Tiempo\n fields = ['id_tie','tiempoi','tiempof','id_ta']\n","sub_path":"tareas/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"237694413","text":"#!/usr/bin/env python\n#\n###############################################################################\n# Author: Greg Zynda\n# Last Modified: 09/17/2019\n###############################################################################\n# BSD 3-Clause License\n# \n# Copyright (c) 2018, Texas Advanced Computing Center - UT Austin\n# All rights reserved.\n# \n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n# \n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n# \n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n# \n# * Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n# \n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n###############################################################################\n\nimport subprocess as sp\nimport sys, argparse, os, json, logging\nlogger = logging.getLogger(__name__)\nfrom collections import Counter\nfrom threading import Thread, current_thread\nfrom shutil import move\nfrom tqdm import tqdm\nfrom time import sleep\ntry:\n\tfrom Queue import Queue\n\timport urllib2\n\timport cPickle as pickle\n\tpyv = 2\nexcept:\n\tfrom queue import Queue\n\timport urllib.request as urllib2\n\timport pickle\n\tpyv = 3\n\nfrom .version import version as __version__\n\n# Environment\nFORMAT = \"[%(levelname)s - %(funcName)s] %(message)s\"\n\ndef main():\n\tparser = argparse.ArgumentParser(description='rgc - Pulls containers and generates Lmod modulefiles for use on HPC systems')\n\tparser.add_argument('-I', '--imgdir', metavar='PATH', \\\n\t\thelp='Directory used to cache singularity images [%(default)s]', \\\n\t\tdefault='./containers', type=str)\n\tparser.add_argument('-M', '--moddir', metavar='PATH', \\\n\t\thelp='Path to modulefiles [%(default)s]', default='./modulefiles', type=str)\n\tparser.add_argument('-C', '--contact', metavar='STR', \\\n\t\thelp='Contact URL(s) in modules separated by \",\" [%(default)s]', default='https://github.com/TACC/rgc/issues', type=str)\n\tparser.add_argument('-P', '--prefix', metavar='STR', \\\n\t\thelp='Prefix string to image directory for when an environment variable is used - not used by default', \\\n\t\tdefault='', type=str)\n\tparser.add_argument('-r', '--requires', metavar='STR', \\\n\t\thelp='Module prerequisites separated by \",\" [%(default)s]', default='', type=str)\n\tparser.add_argument('--modprefix', metavar='STR', \\\n\t\thelp='Prefix for all module names bwa/1.12 -> bwa/[prefix]-1.12', \\\n\t\tdefault='', type=str)\n\tparser.add_argument('--cachedir', metavar='STR', \\\n\t\thelp='Directory to cache metadata in [~/rgc_cache]', \\\n\t\tdefault=os.path.join(os.path.expanduser('~'),'rgc_cache'), type=str)\n\tparser.add_argument('-L', '--include-libs', action='store_true', help='Include containers of libraries')\n\tparser.add_argument('-p', '--percentile', metavar='INT', \\\n\t\thelp='Exclude programs in >= p%% of images [%(default)s]', default='25', type=int)\n\tparser.add_argument('-S', '--singularity', action='store_true', \\\n\t\thelp='Images are cached as singularity containers - even when docker is present')\n\tparser.add_argument('-f', '--force', action='store_true', \\\n\t\thelp='Force overwrite the cache')\n\tparser.add_argument('-d', '--delete-old', action='store_true', \\\n\t\thelp='Delete unused containers and module files')\n\tparser.add_argument('-t', '--threads', metavar='INT', \\\n\t\thelp='Number of concurrent threads to use for pulling [%(default)s]', default='8', type=int)\n\tparser.add_argument('--version', action='version', version='%(prog)s {version}'.format(version=__version__))\n\tparser.add_argument('-v', '--verbose', action='store_true', help='Enable verbose logging')\n\tparser.add_argument('urls', metavar='URL', type=str, nargs='+', help='Image urls to pull')\n\targs = parser.parse_args()\n\t################################\n\t# Configure logging\n\t################################\n\tif args.verbose:\n\t\tlogging.basicConfig(level=logging.DEBUG, format=FORMAT)\n\telse:\n\t\tlogging.basicConfig(level=logging.INFO, format=FORMAT)\n\tlogger = logging.getLogger(__name__)\n\tif args.verbose: logger.debug(\"DEBUG logging enabled\")\n\t################################\n\t# Create container system\n\t################################\n\tcSystem = ContainerSystem(cDir=args.imgdir, mDir=args.moddir, \\\n\t\tforceImage=args.singularity, prereqs=args.requires, \\\n\t\tthreads=args.threads, verbose=args.verbose)\n\tlogger.info(\"Finished initializing system\")\n\t################################\n\t# Define default URLs\n\t################################\n\tdefaultURLS = ['ubuntu:xenial', 'centos:7', 'ubuntu:bionic', 'continuumio/miniconda:latest', 'biocontainers/biocontainers:latest','gzynda/build-essential:bionic']\n\t################################\n\t# Validate all URLs\n\t################################\n\tcSystem.validateURLs(defaultURLS+args.urls, args.include_libs)\n\tlogger.debug(\"DONE validating URLs\")\n\t################################\n\t# Pull all URLs\n\t################################\n\tcSystem.pullAll(defaultURLS+args.urls, args.delete_old)\n\tlogger.debug(\"DONE pulling all urls\")\n\t################################\n\t# Process all images\n\t################################\n\tlogger.debug(\"Scanning all images\")\n\tcSystem.scanAll()\n\tcSystem.findCommon(p=args.percentile, baseline=defaultURLS)\n\tlogger.debug(\"DONE scanning images\")\n\t################################\n\t# Delete default images\n\t################################\n\tfor url in defaultURLS: cSystem.deleteImage(url)\n\t################################\n\t# Generate module files\n\t################################\n\tcSystem.genModFiles(args.prefix, args.contact, args.modprefix, args.delete_old)\n\tlogger.debug(\"DONE creating Lmod files for all %i containers\"%(len(args.urls)))\n\nclass ContainerSystem:\n\t'''\n\tClass for managing the rgc image cache\n\t\t\n\t# Parameters\n\tcDir (str): Path to output container directory\n\tmDir (str): Path to output module directory\n\tforceImage (bool): Option to force the creation of singularity images\n\tprereqs (str): string of prerequisite modules separated by \":\"\n\tthreads (int): Number of threads to use for concurrent operations\n\tcache_dir (str): Path to rgc cache\n\tforce_cache (bool): Whether to force overwrite the cache\n\tverbose (bool): Whether to enable verbose logging\n\t\n\t# Attributes\n\tsystem (str): Container system\n\tcontainerDir (str): Path to use for containers\n\tmoduleDir (str): Path to use for module files\n\tforceImage (bool): Force singularity image creation\n\tinvalid (set): Set of invalid urls\n\tvalid (set): Set of valid urls\n\timages (dict): Path of singularity image or docker url after pulling\n\tregistry (dict): Registry of origin\n\tprogs (dict): Set of programs in a container\n\tname_tag (dict): (name, tag) tuple of a URL\n\tkeywords (dict): List of keywords for a container\n\tcategories (dict): List of categories for a container\n\thomepage (dict): Original homepage of software in container\n\tdescription (dict): Description of software in container\n\tfull_url (dict): Full URL to container in registry\n\tblocklist (set): Set of programs to be blocked from being output\n\tprog_count (Counter): Occurance count of each program seen\n\tlmod_prereqs (list): List of prerequisite modules\n\tn_threads (int): Number of threads to use for concurrent operations\n\tlogger (logging): Class level logger\n\tcache_dir (str): Location for metadata cache\n\tforce_cache (str): Force the regeneration of the metadata cache\n\t'''\n\tdef __init__(self, cDir='./containers', mDir='./modulefiles', \\\n\t\tforceImage=False, prereqs='', threads=8, \\\n\t\tcache_dir=os.path.join(os.path.expanduser('~'),'rgc_cache'), \\\n\t\tforce_cache=False, verbose=False):\n\t\t'''\n\t\tContainerSystem initializer\n\t\t'''\n\t\t# Init logger\n\t\tFORMAT = \"[%(levelname)s - %(funcName)s] %(message)s\"\n\t\tif verbose:\n\t\t\tlogging.basicConfig(level=logging.DEBUG, format=FORMAT)\n\t\telse:\n\t\t\tlogging.basicConfig(level=logging.INFO, format=FORMAT)\n\t\tself.logger = logging.getLogger(__name__)\n\t\tself.system = self._detectSystem()\n\t\tself.logger.debug(\"Using %s as the container system\"%(self.system))\n\t\tself.containerDir = cDir\n\t\tself.logger.debug(\"Image files will be stored in %s\"%(cDir))\n\t\tself.moduleDir = mDir\n\t\tself.logger.debug(\"Module files will be stored in %s\"%(mDir))\n\t\tself.forceImage = forceImage\n\t\tif forceImage: logger.debug(\"Singularity images will be generated even when using docker\")\n\t\tif 'singularity' in self.system or forceImage:\n\t\t\tself.logger.debug(\"Creating %s for caching images\"%(cDir))\n\t\t\tif not os.path.exists(cDir): os.makedirs(cDir)\n\t\tif not os.path.exists(mDir):\n\t\t\tself.logger.debug(\"Creating %s for modulefiles\"%(mDir))\n\t\t\tos.makedirs(mDir)\n\t\tself.invalid = set([])\n\t\tself.valid = set([])\n\t\tself.images = {}\n\t\tself.registry = {}\n\t\tself.progs = {}\n\t\tself.prog_count = Counter()\n\t\tself.name_tag = {}\n\t\tself.keywords = {}\n\t\tself.categories = {}\n\t\tself.homepage = {}\n\t\tself.description = {}\n\t\tself.full_url = {}\n\t\tself.blocklist = set([])\n\t\tself.lmod_prereqs = prereqs.split(',')\n\t\tself.logger.debug(\"Adding the following prereqs to the module files:\\n - %s\"%('\\n - '.join(self.lmod_prereqs)))\n\t\tself.log_level = logging.getLevelName(logger.getEffectiveLevel())\n\t\tself.n_threads = threads\n\t\tself.logger.debug(\"Asynchronous operations will use %i threads\"%(threads))\n\t\tself.cache_dir = cache_dir\n\t\tself.force_cache = force_cache\n\t\tself.container_exts = set(('simg','sif'))\n\tdef _detectSystem(self):\n\t\t'''\n\t\tLooks for\n\n\t\t 1. docker\n\t\t 2. singularity\n\n\t\tcontainer systems installed and running on\n\t\tthe host.\n\n\t\t# Raises\n\t\t101: if neither docker or singularity is found\n\n\t\t# Returns\n\t\tstr: conainter system\n\t\t'''\n\t\tif not sp.call('docker info &>/dev/null', shell=True):\n\t\t\tself.logger.debug(\"Detected docker for container management\")\n\t\t\treturn 'docker'\n\t\telif not sp.call('singularity help &>/dev/null', shell=True):\n\t\t\tself.logger.debug(\"Detected singularity for container management\")\n\t\t\t#singularity version 3.3.0-1.fc29\n\t\t\t#2.6.0-dist\n\t\t\tsing_version = translate(sp.check_output('singularity --version', shell=True)).rstrip('\\n').split()\n\t\t\tif len(sing_version) > 1:\n\t\t\t\tsing_version = sing_version[2]\n\t\t\telse:\n\t\t\t\tsing_version = sing_version[0]\n\t\t\tsplit_version = sing_version.split('.')\n\t\t\tversion = split_version[0]\n\t\t\tself.point_version = split_version[1]\n\t\t\tself.logger.debug(\"Detected singularity %c.%c\"%(split_version[0], split_version[1]))\n\t\t\treturn 'singularity%c'%(version)\n\t\telse:\n\t\t\tself.logger.error(\"Neither docker nor singularity detected on system\")\n\t\t\tsys.exit(101)\n\tdef _getRegistry(self, url):\n\t\t'''\n\t\tSets self.registry[url] with the registry that tracks the URL\n\n\t\t# Parameters\n\t\turl (str): Image url used to pull\n\t\t'''\n\t\tself.registry[url] = 'dockerhub'\n\t\tif 'quay' in url:\n\t\t\tself.registry[url] = 'quay'\n\tdef validateURL(self, url, include_libs=False):\n\t\t'''\n\t\tAdds url to the self.invalid set when a URL is invalid and\n\t\tself.valid when a URL work.\n\n\t\tBy default, containers designated as libraries on bio.tools\n\t\tare excluded.\n\t\t\n\t\t# Parameters\n\t\turl (str): Image url used to pull\n\t\tinclude_libs (bool): Include containers of libraries\n\n\t\t# Attributes\n\t\tself.valid (set): Where valid URLs are stored\n\t\tself.invalid (set): Where invalid URLs are stored\n\t\t'''\n\t\tname, tag = url.split('/')[-1].split(':')\n\t\tif not include_libs:\n\t\t\t# See if it is a bio lib\n\t\t\tmd_url = \"https://dev.bio.tools/api/tool/%s?format=json\"%(name)\n\t\t\ttry:\n\t\t\t\tresp_json = json.loads(translate(urllib2.urlopen(md_url).read()))\n\t\t\t\ttypes = [v for v in resp_json['toolType']]\n\t\t\t\tif types == ['Library']:\n\t\t\t\t\tself.invalid.add(url)\n\t\t\t\t\tself.logger.debug(\"Excluding %s, which is a library\"%(url))\n\t\t\t\t\treturn\n\t\t\texcept urllib2.HTTPError:\n\t\t\t\tpass\n\t\t\t## Check for pypi lib\n\t\t\t#if name not in set(('ubuntu','singularity','bowtie','centos')):\n\t\t\t#\ttry:\n\t\t\t#\t\tcode = urllib2.urlopen('https://pypi.org/pypi/%s/json'%(name)).getcode()\n\t\t\t#\t\tif int(code) == 200:\n\t\t\t#\t\t\tself.invalid.add(url)\n\t\t\t#\t\t\tself.logger.debug(\"Excluding %s, which is a pypi package\"%(url))\n\t\t\t#\t\t\treturn\n\t\t\t#\texcept urllib2.HTTPError:\n\t\t\t#\t\tpass\n\t\tif tag not in self._getTags(url):\n\t\t\tself.logger.warning(\"%s not found in %s\"%(tag, self._getTags(url)))\n\t\t\tself.invalid.add(url)\n\t\t\tself.logger.warning(\"%s is an invalid URL\"%(url))\n\t\telse:\n\t\t\tself.logger.debug(\"%s is valid\"%(url))\n\t\t\tself.valid.add(url)\n\tdef _cache_load(self, file_name, default_values):\n\t\tcache_file = os.path.join(self.cache_dir, file_name)\n\t\tif not os.path.exists(cache_file) or self.force_cache:\n\t\t\tself.logger.debug(\"Refreshing %s cache\"%(cache_file))\n\t\t\treturn default_values\n\t\twith open(cache_file, 'rb') as OC:\n\t\t\tself.logger.debug(\"Reading %s cache\"%(cache_file))\n\t\t\trv = pickle.load(OC)\n\t\treturn rv\n\tdef _cache_save(self, file_name, value_tuple):\n\t\tcache_file = os.path.join(self.cache_dir, file_name)\n\t\tif not os.path.exists(self.cache_dir):\n\t\t\tos.makedirs(self.cache_dir)\n\t\twith open(cache_file, 'wb') as OC:\n\t\t\tpickle.dump(value_tuple, OC)\n\t\t\tself.logger.debug(\"Updated %s cache\"%(cache_file))\n\tdef validateURLs(self, url_list, include_libs=False):\n\t\t'''\n\t\tAdds url to the self.invalid set and returns False when a URL is invalid\n\t\t\n\t\t# Parameters\n\t\turl_list (list): List of URLs to validate\n\t\tinclude_libs (bool): Include containers of libraries\n\t\t'''\n\t\t# Start from cache\n\t\tcache_file = 'valid.pkl'\n\t\tself.invalid, self.valid = self._cache_load(cache_file, (set(), set()))\n\t\tcached = self.invalid | self.valid\n\t\tto_check = set(url_list) - cached\n\t\tif not include_libs: self.logger.info(\"Validating all URLs and excluding libraries when possible\")\n\t\t# Process using ThreadQueue\n\t\tif self.log_level == 'DEBUG':\t\n\t\t\ttq = ThreadQueue(target=self.validateURL, n_threads=self.n_threads, verbose=True)\n\t\telse:\n\t\t\ttq = ThreadQueue(target=self.validateURL, n_threads=self.n_threads, verbose=False)\n\t\tif to_check:\n\t\t\tself.logger.info(\"Validating all %i URLs using %i threads\"%(len(to_check), self.n_threads))\n\t\t\ttq.process_list([(url, include_libs) for url in to_check])\n\t\ttq.join()\n\t\t# Write to cache\n\t\tself._cache_save(cache_file, (self.invalid, self.valid))\n\tdef _getTags(self, url, remove_latest=False):\n\t\t'''\n\t\tReturns all tags for the image specified with URL\n\t\t\n\t\t# Parameters\n\t\turl (str): Image url used to pull\n\t\tremove_latest (bool): Removes the \"latest\" tag from the return set\n\t\t\n\t\t# Returns\n\t\tset: all tags associated with main image URL\n\t\t'''\n\t\tname = url.split(':')[0]\n\t\tif '/' not in name: name = 'library/'+name\n\t\tif url not in self.registry: self._getRegistry(url)\n\t\tif self.registry[url] == 'quay':\n\t\t\tname = '/'.join(name.split('/')[1:])\n\t\t\tquery = 'https://quay.io/api/v1/repository/%s/tag/'%(name)\n\t\t\tkey = 'tags'\n\t\telse:\n\t\t\tquery = 'https://hub.docker.com/v2/repositories/%s/tags/'%(name)\n\t\t\tkey = 'results'\n\t\ttry:\n\t\t\tresp = json.loads(translate(urllib2.urlopen(query).read()))\n\t\t\tresults = resp[key]\n\t\t\twhile 'next' in resp and resp['next']:\n\t\t\t\tresp = json.loads(translate(urllib2.urlopen(resp['next']).read()))\n\t\t\t\tresults += resp[key]\n\t\texcept urllib2.HTTPError:\n\t\t\tself.logger.debug(\"No response from %s\"%(query))\n\t\t\treturn set([])\n\t\tall_tags = set([t['name'] for t in results])\n\t\tif not all_tags: return set([])\n\t\tmax_len = max(map(len, all_tags))\n\t\ttag_str = '%%%is'%(max_len)\n\t\tdebug_str = ', '.join(['\\n'+tag_str%(tag) if (i) % 3 == 0 else tag_str%(tag) for i, tag in enumerate(all_tags)])\n\t\tif not remove_latest:\n\t\t\treturn all_tags\n\t\tif 'latest' in all_tags:\n\t\t\tself.logger.debug(\"Removing the latest tag from %s\"%(url))\n\t\treturn all_tags-set(['latest'])\n\tdef pullAll(self, url_list, delete_old=False):\n\t\t'''\n\t\tUses worker threads to concurrently pull\n\n\t\t - image\n\t\t - metadata\n\t\t - repository info\n\n\t\tfor a list of urls.\n\n\t\t# Parameters\n\t\turl_list (list): List of urls to pul\n\t\tdelete_old (bool): Delete old images that are no longer used\n\t\t'''\n\t\t# Load cache\n\t\tcache_file = 'metadata.pkl'\n\t\tself.categories, self.keywords, self.description, self.homepage = self._cache_load(cache_file, [dict() for i in range(4)])\n\t\t# Process using ThreadQueue\n\t\tif self.log_level == 'DEBUG':\t\n\t\t\ttq = ThreadQueue(target=self.pull, n_threads=self.n_threads, verbose=True)\n\t\telse:\n\t\t\ttq = ThreadQueue(target=self.pull, n_threads=self.n_threads, verbose=False)\n\t\tself.logger.info(\"Pulling %i containers on %i threads\"%(len(url_list), self.n_threads))\n\t\tfor url in url_list:\n\t\t\t# Create name directory\n\t\t\tif 'singularity' in self.system or self.forceImage:\n\t\t\t\tif url not in self.name_tag: self._getNameTag(url)\n\t\t\t\tsimg_dir = os.path.join(self.containerDir, self.name_tag[url][0])\n\t\t\t\tif not os.path.exists(simg_dir): os.makedirs(simg_dir)\n\t\ttq.process_list(url_list)\n\t\ttq.join()\n\t\t# Write to cache\n\t\tself._cache_save(cache_file, (self.categories, self.keywords, self.description, self.homepage))\n\t\t# Delete unused images\n\t\tif delete_old:\n\t\t\tself.logger.info(\"Deleting unused containers\")\n\t\t\tif 'singularity' in self.system or self.forceImage:\n\t\t\t\tall_files = set((os.path.join(p, f) for p, ds, fs in os.walk(self.containerDir) for f in fs))\n\t\t\t\tto_delete = all_files - set(self.images.values())\n\t\t\t\tfor fpath in to_delete:\n\t\t\t\t\tif fpath.split('.')[-1] in self.container_exts:\n\t\t\t\t\t\tself.logger.info(\"Deleting old container %s\"%(fpath))\n\t\t\t\t\t\tos.remove(fpath)\n\t\t\tif self.system == 'docker':\n\t\t\t\t# TODO finish this section\n\t\t\t\tpass\n\t\t\t\t\n\tdef pull(self, url):\n\t\t'''\n\t\tPulls the following\n\n\t\t - image\n\t\t - metadata\n\t\t - repository info\n\n\t\t# Parameters\n\t\turl (str): Image url used to pull\n\t\t'''\n\t\t#threads = []\n\t\tif url in self.invalid: return\n\t\tif url not in self.valid: ret = self.validateURL(url)\n\t\tif url in self.valid:\n\t\t\tif url not in self.name_tag: self._getNameTag(url)\n\t\t\tself._getMetadata(url)\n\t\t\tself._getFullURL(url)\n\t\t\tself._pullImage(url)\n\t\t\t# Set homepage if to container url if it was not included in metadata\n\t\t\tif not self.homepage[url]:\n\t\t\t\tself.homepage[url] = self.full_url[url]\n\t\telse:\n\t\t\tself.logger.warning(\"Could not find %s. Excluding it future operations\"%(url))\n\tdef _getFullURL(self, url):\n\t\t'''\n\t\tStores the web URL for viewing the specified image in `self.full_url[url]`\n\n\t\t> NOTE: This does not validate the url\n\t\t\n\t\t# Parameters\n\t\turl (str): Image url used to pull\n\t\t'''\n\t\tname = url.split(':')[0]\n\t\tif \"quay\" in url:\n\t\t\tname = '/'.join(name.split('/')[1:])\n\t\t\tbase = 'https://quay.io/repository/%s'\n\t\telse:\n\t\t\tbase = 'https://hub.docker.com/r/%s'\n\t\tself.full_url[url] = base%(name)\n\tdef _getNameTag(self, url):\n\t\t'''\n\t\tStores the container (name, tag) from a url in `self.name_tag[url]`\n\n\t\t# Parameters\n\t\turl (str): Image url used to pull\n\t\t'''\n\t\ttool_tag = 'latest'\n\t\tif ':' in url:\n\t\t\ttool_name, tool_tag = url.split(':')\n\t\t\ttool_name = tool_name.split('/')[-1]\n\t\telse:\n\t\t\ttool_name = url.split('/')[-1]\n\t\tself.name_tag[url] = (tool_name, tool_tag)\n\tdef _retry_call(self, cmd, url, times=3):\n\t\t'''\n\t\tRetries the check_call command\n\n\t\t# Parameters\n\t\tcmd (str): Command to run\n\t\turl (str): Image url used to pull\n\t\ttimes (int): Number of retries allowed\n\n\t\t# Returns\n\t\tbool: Whether the command succeeded or not\n\t\t'''\n\t\tself.logger.debug(\"Running: \"+cmd)\n\t\tFNULL = open(os.devnull, 'w')\n\t\tfor i in range(times):\n\t\t\ttry:\n\t\t\t\tsp.check_call(cmd, shell=True, stdout=FNULL, stderr=FNULL)\n\t\t\texcept KeyboardInterrupt as e:\n\t\t\t\tFNULL.close()\n\t\t\t\tsys.exit()\n\t\t\texcept sp.CalledProcessError:\n\t\t\t\tif i < times-1:\n\t\t\t\t\tself.logger.debug(\"Attempting to pull %s again\"%(url))\n\t\t\t\t\tsleep(2)\n\t\t\t\t\tcontinue\n\t\t\t\telse:\n\t\t\t\t\tFNULL.close()\n\t\t\t\t\treturn False\n\t\t\tbreak\n\t\treturn True\n\t\tFNULL.close()\n\tdef _pullImage(self, url):\n\t\t'''\n\t\tPulls an image using either docker or singularity and\n\t\tsets\n\n\t\t - `self.images[url]`\n\n\t\tas the URL or path for subsequent interactions. Please\n\t\tuse pull over pullImage.\n\n\t\t> NOTE - this image must be valid\n\n\t\t# Parameters\n\t\turl (str): Image url used to pull\n\t\t'''\n\t\tif url in self.invalid:\n\t\t\tself.logger.error(\"%s is not a valid URL\")\n\t\t\tsys.exit(103)\n\t\tif url not in self.name_tag: self._getNameTag(url)\n\t\tname, tag = self.name_tag[url]\n\t\text_dict = {'docker':'simg', 'singularity2':'simg', 'singularity3':'sif'}\n\t\timg_dir = os.path.join(self.containerDir, name)\n\t\tabs_img_dir = img_dir if img_dir[0] == '/' else os.path.join(os.getcwd(), img_dir)\n\t\tsimg = '%s-%s.%s'%(name, tag, ext_dict[self.system])\n\t\timg_out = os.path.join(img_dir, simg)\n\t\timg_set = (os.path.join(img_dir, '%s-%s.%s'%(name, tag, ext)) for ext in ext_dict.values())\n\t\t\t\n\t\tif self.system == 'docker':\n\t\t\tif self.forceImage:\n\t\t\t\tfor p in img_set:\n\t\t\t\t\tif os.path.exists(p):\n\t\t\t\t\t\tself.logger.debug(\"Detected %s for url %s - using this version\"%(p, url))\n\t\t\t\t\t\tself.images[url] = p\n\t\t\t\t\t\treturn\n\t\t\t\tif not os.path.exists(img_dir): os.makedirs(img_dir)\n\t\t\t\tcmd = \"docker run -v %s:/containers --rm gzynda/singularity:2.6.0 bash -c 'cd /containers && singularity pull docker://%s' &>/dev/null\"%(abs_img_dir, url)\n\t\t\t\tif self._retry_call(cmd, url):\n\t\t\t\t\tassert(os.path.exists(img_out))\n\t\t\t\t\tself.images[url] = img_out\n\t\t\t\telse:\n\t\t\t\t\tself._pullError(url)\n\t\t\telse:\n\t\t\t\ttry:\n\t\t\t\t\tsp.check_call('docker pull %s &>/dev/null'%(url), shell=True)\n\t\t\t\t\tself.images[url] = url\n\t\t\t\texcept:\n\t\t\t\t\tself._pullError(url)\n\t\telif 'singularity' in self.system:\n\t\t\tfor p in img_set:\n\t\t\t\tif os.path.exists(p):\n\t\t\t\t\tself.logger.debug(\"Dectect %s for url %s - using this version\"%(p, url))\n\t\t\t\t\tself.images[url] = p\n\t\t\t\t\treturn\n\t\t\tif not os.path.exists(img_dir): os.makedirs(img_dir)\n\t\t\ttmp_dir = translate(sp.check_output('mktemp -d -p /tmp', shell=True)).rstrip('\\n')\n\t\t\ttry:\n\t\t\t\tif self.system == 'singularity2':\n\t\t\t\t\tcmd = 'SINGULARITY_CACHEDIR=%s singularity pull -F docker://%s &>/dev/null'%(tmp_dir, url)\n\t\t\t\t\tself._retry_call(cmd, url)\n\t\t\t\t\ttmp_path = os.path.join(tmp_dir, simg)\n\t\t\t\t\tassert(os.path.exists(tmp_path))\n\t\t\t\t\tmove(tmp_path, img_out)\n\t\t\t\telif self.system == 'singularity3':\n\t\t\t\t\tcmd = 'SINGULARITY_CACHEDIR=%s singularity pull -F %s docker://%s &>/dev/null'%(tmp_dir, img_out, url)\n\t\t\t\t\tself._retry_call(cmd, url)\n\t\t\t\t\tassert(os.path.exists(img_out))\n\t\t\t\telse:\n\t\t\t\t\tself.logger.error(\"Unhandled version of singularity\")\n\t\t\t\t\tsys.exit()\n\t\t\texcept:\n\t\t\t\tself._pullError(url)\n\t\t\tif os.path.exists(tmp_dir):\n\t\t\t\tsp.check_call('rm -rf %s'%(tmp_dir), shell=True)\n\t\t\t\tself.logger.debug(\"Deleted %s\"%(tmp_dir))\n\t\t\tself.images[url] = img_out\n\t\telse:\n\t\t\tself.logger.error(\"Unhandled system\")\n\t\t\tsys.exit(102)\n\t\tself.logger.debug(\"Pulled %s\"%(url))\n\tdef _pullError(self, url):\n\t\tself.logger.error(\"Could not pull %s\"%(url))\n\t\tself.invalid.add(url)\n\t\tself.valid.remove(url)\n\tdef deleteImage(self, url):\n\t\t'''\n\t\tDeletes a cached image\n\n\t\t# Parameters\n\t\turl (str): Image url used to pull\n\t\t'''\n\t\tif url in self.images:\n\t\t\tif self.system == 'docker':\n\t\t\t\tif self.forceImage:\n\t\t\t\t\tos.remove(self.images[url])\n\t\t\t\telse:\n\t\t\t\t\tsp.check_call('docker rmi %s &>/dev/null'%(url), shell=True)\n\t\t\telif 'singularity' in self.system:\n\t\t\t\tos.remove(self.images[url])\n\t\t\t\tcontainer_dir = os.path.dirname(self.images[url])\n\t\t\t\tif not os.listdir(container_dir):\n\t\t\t\t\tos.rmdir(container_dir)\n\t\t\tdel self.images[url]\n\t\t\tself.logger.info(\"Deleted %s\"%(url))\n\t\telse:\n\t\t\tself.logger.info(\"%s didn't exist\"%(url))\n\tdef _getMetadata(self, url):\n\t\t'''\n\t\tAssuming the image is a biocontainer,\n\n\t\t - `self.categories[url]`\n\t\t - `self.keywords[url]`\n\t\t - `self.description[url]`\n\t\t - `self.homepage[url]`\n\n\t\tare set after querying https://dev.bio.tools\n\n\t\t# Parameters\n\t\turl (str): Image url used to pull\n\t\t'''\n\t\tif url in self.description and url in self.keywords and url in self.description:\n\t\t\treturn\n\t\tif url not in self.name_tag: self._getNameTag(url)\n\t\tname = self.name_tag[url][0]\n\t\tself.homepage[url] = False\n\t\ttry:\n\t\t\t# Check dev.bio.tools\n\t\t\tmd_url = \"https://dev.bio.tools/api/tool/%s?format=json\"%(name)\n\t\t\tresp_json = json.loads(translate(urllib2.urlopen(md_url).read()))\n\t\t\ttopics = [topic['term'] for topic in resp_json['topic']]\n\t\t\ttopics = [t for t in topics if t != 'N/A']\n\t\t\tfunctions = [o['term'] for f in resp_json['function'] for o in f['operation']]\n\t\t\tdesc = resp_json['description']\n\t\t\tif 'homepage' in resp_json: self.homepage[url] = resp_json['homepage']\n\t\texcept urllib2.HTTPError:\n\t\t\ttry:\n\t\t\t\t# Check Launchpad\n\t\t\t\tmd_url = \"https://api.launchpad.net/devel/%s\"%(name)\n\t\t\t\tresp_json = json.loads(translate(urllib2.urlopen(md_url).read()))\n\t\t\t\tdesc = resp_json['description']\n\t\t\t\tself.homepage[url] = resp_json['homepage_url']\n\t\t\t\ttopics = [\"Biocontainer\"]\n\t\t\t\tfunctions = [\"Bioinformatics\"]\n\t\t\texcept:\n\t\t\t\t# Default values\n\t\t\t\tself.logger.debug(\"No record of %s on dev.bio.tools\"%(name))\n\t\t\t\tfunctions = [\"Bioinformatics\"]\n\t\t\t\ttopics = [\"Biocontainer\"]\n\t\t\t\tdesc = \"The %s package\"%(name)\n\t\tself.categories[url] = functions\n\t\tself.keywords[url] = topics\n\t\tself.description[url] = desc\n\tdef scanAll(self):\n\t\t'''\n\t\tRuns `self.cachProgs` on all containers concurrently with threads\n\t\t'''\n\t\tcache_file = 'programs.pkl'\n\t\tself.progs, self.prog_count = self._cache_load(cache_file, (dict(), Counter()))\n\t\tto_check = self.valid - set(self.progs.keys())\n\t\t# Process using ThreadQueue\n\t\tif self.log_level == 'DEBUG':\t\n\t\t\ttq = ThreadQueue(target=self.cacheProgs, n_threads=self.n_threads, verbose=True)\n\t\telse:\n\t\t\ttq = ThreadQueue(target=self.cacheProgs, n_threads=self.n_threads, verbose=False)\n\t\tself.logger.info(\"Scanning for programs in all %i containers %i threads\"%(len(self.valid), self.n_threads))\n\t\tif to_check:\n\t\t\ttq.process_list(to_check)\n\t\ttq.join()\n\t\t# Write to cache\n\t\tself._cache_save(cache_file, (self.progs, self.prog_count))\n\tdef _callCMD(self, url, cmd):\n\t\tif self.system == 'docker':\n\t\t\trun = \"docker run --rm -it %s %s\"%(url, cmd)\n\t\telif 'singularity' in self.system:\n\t\t\trun = \"singularity exec %s %s\"%(self.images[url], cmd)\n\t\telse:\n\t\t\tself.logger.error(\"%s system is unhandled\"%(self.system))\n\t\t\tsys.exit(500)\n\t\tself.logger.debug(\"Running\\n%s\"%(run))\n\t\treturn sp.call(run, shell=True)\n\tdef _check_outputCMD(self, url, cmd):\n\t\tif self.system == 'docker':\n\t\t\trun = \"docker run --rm -it %s %s\"%(url, cmd)\n\t\t\tself.logger.debug(\"Running\\n%s\"%(run))\n\t\t\tout = sp.check_output(run, shell=True)\n\t\t\tout_split = translate(out).split('\\r\\n')\n\t\t\treturn [l for l in out_split]\n\t\telif 'singularity' in self.system:\n\t\t\trun = \"singularity exec %s %s\"%(self.images[url], cmd)\n\t\t\tself.logger.debug(\"Running\\n%s\"%(run))\n\t\t\tout = sp.check_output(run, shell=True)\n\t\t\treturn translate(out).split('\\n')\n\t\telse:\n\t\t\tself.logger.error(\"%s system is unhandled\"%(self.system))\n\t\t\tsys.exit(500)\n\tdef cacheProgs(self, url, force=False):\n\t\t'''\n\t\tCrawls all directories on a container's PATH and caches a list of all executable files in\n\n\t\t - `self.progs[url]`\n\t\t\n\t\tand counts the global occurance of each program in\n\n\t\t - `self.prog_count[prog]`\n\n\t\t# Parameters\n\t\turl (str): Image url used to pull\n\t\tforce (bool): Force a re-scan and print results (for debugging only)\n\t\t'''\n\t\tif url in self.invalid: return\n\t\tif url not in self.images and url in self.valid:\n\t\t\tself.logger.debug(\"%s has not been pulled. Pulling now.\"%(url))\n\t\t\tself.pull(url)\n\t\t# Determine env\n\t\tif not self._callCMD(url, '[ -e /bin/busybox ] &>/dev/null'):\n\t\t\tshell = 'busybox'\n\t\telif not self._callCMD(url, '[ -e /bin/bash ] &>/dev/null'):\n\t\t\tshell = 'bash'\n\t\telif not self._callCMD(url, '[ -e /bin/sh ] &>/dev/null'):\n\t\t\tshell = 'sh'\n\t\telse:\n\t\t\tself.logger.error(\"Could not determine container env shell in %s\"%(url))\n\t\t\tsys.exit(501)\n\t\tif url not in self.progs or force:\n\t\t\tself.logger.debug(\"Caching all programs in %s\"%(url))\n\t\t\t# Create find string\n\t\t\tif shell == 'bash':\n\t\t\t\tfindStr = 'export IFS=\":\"; find $PATH -maxdepth 1 \\( -type l -o -type f \\) -executable -exec basename {} \\; | sort -u'\n\t\t\t\tcmd = \"bash -c '%s' 2>/dev/null\"%(findStr)\n\t\t\telif shell in ('sh','busybox'):\n\t\t\t\tfindStr = 'export IFS=\":\"; for dir in $PATH; do [ -e \"$dir\" ] && find $dir -maxdepth 1 \\( -type l -o -type f \\) -perm +111 -exec basename {} \\;; done | sort -u'\n\t\t\t\tcmd = \"sh -c '%s' 2>/dev/null\"%(findStr)\n\t\t\telse:\n\t\t\t\tlogger.error(\"%s shell is unhandled\"%(shell))\n\t\t\t\tsys.exit(502)\n\t\t\tprogList = self._check_outputCMD(url, cmd)\n\t\t\tprogList = list(filter(lambda x: len(x) > 0 and x[0] != '_', progList))\n\t\t\tself.prog_count += Counter(progList)\n\t\t\tself.progs[url] = set(progList)\n\t\t\tlogger.debug(\"%s - %i progs found - %i in set\"%(url, len(progList), len(set(progList))))\n\tdef getProgs(self, url, blocklist=True):\n\t\t'''\n\t\tRetruns a list of all programs on the path of a url that are not blocked\n\n\t\t# Parameters\n\t\turl (str): Image url used to pull\n\t\tblocklist (bool): Filter out blocked programs\n\n\t\t# Returns\n\t\tlist: programs on PATH in container\n\t\t'''\n\t\tif url in self.invalid: return []\n\t\tif url not in self.progs:\n\t\t\tself.logger.debug(\"Programs have not yet been cached for %s\"%(url))\n\t\t\tself.cacheProgs(self, url)\n\t\tif blocklist:\n\t\t\treturn list(self.progs[url]-self.blocklist)\n\t\treturn list(self.progs[url])\n\tdef getAllProgs(self, url):\n\t\t'''\n\t\tReturns a list of all programs on the path of url.\n\n\t\tThis is a shortcut for `self.getProgs(url, blaclist=False)`\n\n\t\t# Parameters\n\t\turl (str): Image url used to pull\n\t\t'''\n\t\treturn self.getProgs(url, blocklist=False)\n\tdef _diffProgs(self, fromURL, newURL):\n\t\t'''\n\t\tCreates a list of programs on the path of newURL that do not exist in fromURL\n\t\t'''\n\t\tfor url in (fromURL, newURL):\n\t\t\tif url in self.invalid:\n\t\t\t\tself.logger.error(\"%s is an invalid URL\"%(url))\n\t\t\t\tsys.exit(110)\n\t\t\tif url not in self.progs: self.cacheProgs(url)\n\t\treturn list(self.progs[newURL].difference(self.progs[fromURL]))\n\tdef findCommon(self, p=25, baseline=[]):\n\t\t'''\n\t\tCreates a blocklist containing all programs that are in at least p% of the images\n\n\t\t - `self.blocklist[url] = set([prog, prog, ...])`\n\n\t\t# Parameters\n\t\tp (int): Percentile of images\n\t\tbaesline (list): Exclude all programs from this list of urls\n\n\t\t# Attributes\n\t\tpermitlist (set): Set of programs that are always included when present\n\t\tblocklist (set): Set of programs to be excluded\n\t\t'''\n\t\tn_images = len(self.progs)\n\t\tn_percentile = p*n_images/100.0\n\t\tself.logger.info(\"Cached %i images and %i unique programs\"%(n_images,len(self.prog_count)))\n\t\tself.logger.info(\"Excluding programs in >= %i%% of images\"%(p))\n\t\tself.logger.info(\"Excluding programs in >= %.2f images\"%(n_percentile))\n\t\tself.blocklist = set([])\n\t\tfor url in baseline:\n\t\t\tif url in self.progs:\n\t\t\t\tself.blocklist |= self.progs[url]\n\t\tself.permitlist = set(['R','Rscript','samtools','bwa','bowtie','bowtie2'])\n\t\tself.blocklist |= set([prog for prog, count in self.prog_count.items() if count >= n_percentile])\n\t\tself.blocklist -= self.permitlist\n\t\tself.logger.info(\"Excluded %i of %i programs\"%(len(self.blocklist), len(self.prog_count)))\n\t\tself.logger.debug(\"Excluding:\\n - \"+'\\n - '.join(sorted(list(self.blocklist))))\n\tdef genModFiles(self, pathPrefix, contact_url, modprefix, delete_old):\n\t\t'''\n\t\tGenerates an Lmod modulefile for every valid image\n\n\t\t# Parameters\n\t\turl (str): Image url used to pull\n\t\tpathPrefix (str): Prefix to prepend to containerDir (think environment variables)\n\t\tcontact_url (list): List of contact urls for reporting issues\n\t\tmodprefix (str): Container module files can be tagged with modprefix-tag for easy stratification from native modules\n\t\tdelete_old (bool): Delete outdated module files\n\t\t'''\n\t\tlogger.info(\"Creating Lmod files for specified all %i images\"%(len(self.images)))\n\t\tfor url in self.images:\n\t\t\tself.genLMOD(url, pathPrefix, contact_url, modprefix)\n\t\tif delete_old:\n\t\t\t# Generate all module names\n\t\t\trecent_modules = set([])\n\t\t\tfor url in self.images:\n\t\t\t\tname, tag = self.name_tag[url]\n\t\t\t\tmodule_tag = '%s-%s'%(modprefix, tag) if modprefix else tag\n\t\t\t\tmodule_file = os.path.join(self.moduleDir, name, '%s.lua'%(module_tag))\n\t\t\t\trecent_modules.add(module_file)\n\t\t\t# Delete extras\n\t\t\tself.logger.info(\"Deleting unused module files\")\n\t\t\tall_files = set((os.path.join(p, f) for p, ds, fs in os.walk(self.moduleDir) for f in fs))\n\t\t\tto_delete = all_files - recent_modules\n\t\t\tfor fpath in to_delete:\n\t\t\t\tif fpath.split('.')[-1] == 'lua':\n\t\t\t\t\tself.logger.info(\"Deleting old container %s\"%(fpath))\n\t\t\t\t\tos.remove(fpath)\n\tdef genLMOD(self, url, pathPrefix, contact_url, modprefix=''):\n\t\t'''\n\t\tGenerates an Lmod modulefile based on the cached container.\n\n\t\t# Parameters\n\t\turl (str): Image url used to pull\n\t\tpathPrefix (str): Prefix to prepend to containerDir (think environment variables)\n\t\tcontact_url (list): List of contact urls for reporting issues\n\t\tmodprefix (str): Container module files can be identified with modprefix-tag for easy stratification from native modules\n\t\t'''\n\t\tif url in self.invalid: return\n\t\tif url not in self.progs: self.cacheProgs(url)\n\t\t#####\n\t\tname, tag = self.name_tag[url]\n\t\tmodule_tag = '%s-%s'%(modprefix, tag) if modprefix else tag\n\t\tfull_url = self.full_url[url]\n\t\tdesc = self.description[url]\n\t\tkeys = self.keywords[url]\n\t\tcats = self.categories[url]\n\t\tprogList = sorted(self.getProgs(url))\n\t\tprogStr = ' - '+'\\n - '.join(progList)\n\t\timg_path = self.images[url].lstrip('./')\n\t\thome = self.homepage[url]\n\t\tcontact_joined = '\\n\\t'.join(contact_url.split(','))\n\t\t#####\n\t\tif not progList:\n\t\t\tself.logger.error(\"No programs detected in %s\"%(url))\n\t\t\tprogStr = \"None - please invoke manually\"\n\t\t#####\n\t\thelp_text = '''local help_message = [[\nThis is a module file for the container %s, which exposes the\nfollowing programs:\n\n%s\n\nThis container was pulled from:\n\n\t%s\n\nIf you encounter errors in %s or need help running the\ntools it contains, please contact the developer at\n\n\t%s\n\nFor errors in the container or module file, please\nsubmit a ticket at\n\n\t%s\n]]'''\n\t\tmodule_text = '''\nhelp(help_message,\"\\\\n\")\n\nwhatis(\"Name: %s\")\nwhatis(\"Version: %s\")\nwhatis(\"Category: %s\")\nwhatis(\"Keywords: %s\")\nwhatis(\"Description: %s\")\nwhatis(\"URL: %s\")\n\n'''\n\t\tfull_text = help_text%(url, progStr, full_url, name, home, contact_joined)\n\t\tfull_text += module_text%(name, module_tag, cats, keys, desc, full_url)\n\t\t# add prereqs\n\t\tif self.lmod_prereqs[0]: full_text += 'prereq(\"%s\")\\n'%('\",\"'.join(self.lmod_prereqs))\n\t\t# add functions\n\t\tif 'singularity' in self.system:\n\t\t\tif pathPrefix:\n\t\t\t\tprefix = 'singularity exec %s'%(os.path.join(pathPrefix, img_path))\n\t\t\telse:\n\t\t\t\tprefix = 'singularity exec %s'%(os.path.join(os.getcwd(), img_path))\n\t\telif self.system == 'docker':\n\t\t\tprefix = 'docker run --rm -it %s'%(img_path)\n\t\telse:\n\t\t\tself.logger.error(\"Unhandled system\")\n\t\t\tsys.exit(102)\n\t\tfor prog in progList:\n\t\t\tbash_string = '%s %s $@'%(prefix, prog)\n\t\t\tcsh_string = '%s %s $*'%(prefix, prog)\n\t\t\tfunc_string = 'set_shell_function(\"%s\",\\'%s\\',\\'%s\\')\\n'%(prog, bash_string, csh_string)\n\t\t\tfull_text += func_string\n\t\t#####\n\t\tmPath = os.path.join(self.moduleDir, name)\n\t\tif not os.path.exists(mPath): os.makedirs(mPath)\n\t\toutFile = os.path.join(mPath, \"%s.lua\"%(module_tag))\n\t\t#print(full_text.encode('utf8'))\n\t\twith open(outFile,'w') as OF: OF.write(full_text)\n\ndef _a_path_exists(path_iter):\n\tfor p in path_iter:\n\t\tif os.path.exists(p):\n\t\t\tlogger.debug(\"Previously pulled image %s exists\"%(p))\n\t\t\treturn True\n\treturn False\n\t#return max(map(os.path.exists, path_iter))\n\ndef translate(s):\n\tif pyv == 3:\n\t\treturn s.decode('utf-8')\n\telif pyv == 2:\n\t\ttry:\n\t\t\treturn s.encode('ascii','ignore')\n\t\texcept:\n\t\t\treturn s.decode('utf8','ignore').encode('ascii','ignore')\n\telse:\n\t\tsys.exit(\"Python version was not detected\")\n\nclass ThreadQueue:\n\tdef __init__(self, target, n_threads=10, verbose=False):\n\t\t'''\n\t\tClass for killable thread pools\n\t\t\n\t\t# Parameters\n\t\ttarget (function): Target function for threads to run\n\t\tn_threads (int): Number of worker threads to use [10]\n\t\tverbose (bool): Enables verbose logging\n\t\t'''\n\t\t# Init logger\n\t\tFORMAT = '[%(levelname)s - %(threadName)s - %(name)s.%(funcName)s] %(message)s'\n\t\tif verbose:\n\t\t\tself.log_level = 'DEBUG'\n\t\t\tlogging.basicConfig(level=logging.DEBUG, format=FORMAT)\n\t\telse:\n\t\t\tself.log_level = 'INFO'\n\t\t\tlogging.basicConfig(level=logging.INFO, format=FORMAT)\n\t\tself.pbar = ''\n\t\tself.logger = logging.getLogger('ThreadQueue')\n\t\tself.n_threads = n_threads\n\t\tself.queue = Queue()\n\t\t# Spawn threads\n\t\tself.threads = [Thread(target=self.worker, args=[target]) for i in range(n_threads)]\n\t\tfor t in self.threads: t.start()\n\t\tself.logger.debug(\"Spawned and started %i threads\"%(n_threads))\n\tdef process_list(self, work_list):\n\t\t'''\n\t\t# Parameters\n\t\twork_list (list): List of argument lists for threads to run\n\t\t'''\n\t\tif self.log_level != 'DEBUG': self.pbar = tqdm(total=len(work_list))\n\t\ttry:\n\t\t\tfor work_item in work_list:\n\t\t\t\tself.queue.put(work_item)\n\t\t\tself.logger.debug(\"Added %i items to the work queue\"%(len(work_list)))\n\t\t\twhile not self.queue.empty():\n\t\t\t\tsleep(0.5)\n\t\t\tself.logger.debug(\"Finished running work list\")\n\t\texcept KeyboardInterrupt as e:\n\t\t\tself.logger.warn(\"Caught KeyboardInterrupt - Killing threads\")\n\t\t\tfor t in self.threads: t.alive = False\n\t\t\tfor t in self.threads: t.join()\n\t\t\tsys.exit(e)\n\tdef join(self):\n\t\t'''\n\t\tWaits until all child threads are joined\n\t\t'''\n\t\ttry:\n\t\t\tfor t in self.threads: self.queue.put('STOP')\n\t\t\tfor t in self.threads:\n\t\t\t\twhile t.is_alive():\n\t\t\t\t\tt.join(0.5)\n\t\t\tif self.log_level != 'DEBUG' and self.pbar:\n\t\t\t\tself.pbar.close()\n\t\t\t\tself.pbar = ''\n\t\t\tself.logger.debug(\"Joined all threads\")\n\t\texcept KeyboardInterrupt as e:\n\t\t\tself.logger.warn(\"Caught KeyboardInterrupt. Killing threads\")\n\t\t\tfor t in self.threads: t.alive = False\n\t\t\tfor t in self.threads: t.join()\n\t\t\tsys.exit(e)\n\tdef worker(self, target):\n\t\t'''\n\t\tWorker for pulling images\n\n\t\t# Parameters\n\t\ttarget (function): Target function for thread to run\n\t\t'''\n\t\tt = current_thread()\n\t\tt.alive = True\n\t\tfor args in iter(self.queue.get, 'STOP'):\n\t\t\tif not t.alive:\n\t\t\t\tself.logger.debug(\"Stopping\")\n\t\t\t\tbreak\n\t\t\tif type(args) is list or type(args) is tuple:\n\t\t\t\tself.logger.debug(\"Running %s%s\"%(target.__name__, str(map(str, args))))\n\t\t\t\ttarget(*args)\n\t\t\telse:\n\t\t\t\tself.logger.debug(\"Running %s(%s)\"%(target.__name__, str(args)))\n\t\t\t\ttarget(args)\n\t\t\tif t.alive and self.log_level != 'DEBUG': self.pbar.update(1)\n\t\t\tself.queue.task_done()\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"rgc/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":38639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"629378150","text":"from flask import Flask, make_response\nfrom flask_restful import reqparse, abort, Api, Resource\nfrom JenkinsClient import *\n\n__author__ = \"Tamas Szabo\"\n__email__ = \"tamas.e.szabo@ericsson.com\"\n\n\napp = Flask(\"AVOP-Jenkins-API-GW\")\napi = Api(app)\n\ndef abort_if_todo_doesnt_exist(todo_id):\n if todo_id not in TODOS:\n abort(404, message=\"Tudo {} doesn't exist\".format(todo_id))\n \nclass Auth(Resource):\n '''\n accepts post, with json payload username=, password=\n regardless of the actual values in the payload, we return a\n also accepts delete, in which case it'll return a 204, unconditionally\n \n this Resouce instance covers IxiaClient '_get_apiKey' and 'logout' methods\n '''\n def __init__(self):\n self.reqparse = reqparse.RequestParser()\n self.reqparse.add_argument('username', type = str, location = 'json')\n self.reqparse.add_argument('password', type = str, location = 'json')\n super(Auth, self).__init__()\n \n def post(self):\n args = self.reqparse.parse_args()\n print(args)\n return {\n \"apiKey\": \"ab1c0d80dc184c1cafd5eb7a0bf142d8\",\n \"sessionName\": \"IXSESSIONID\",\n \"sessionId\": \"c6bcc118-e5e9-477e-99d4-847728780419\",\n \"username\": \"admin\",\n \"userAccountUrl\": \"https://localhost/api/v1/auth/users/1\"\n }, 200\n \n def delete(self):\n return '', 204\n \nclass ViewPorts(Resource):\n '''\n receives a GET and returns the status of all ports.\n '''\n def __init__(self):\n super(ViewPorts, self).__init__()\n \n def get(self):\n return {\n \"portReservationState\": \"{[slot=1,port=1]=1:[reserved=admin,group=1,number=2], [slot=1,port=0]=0:[reserved=admin,group=1,number=1], [slot=1,port=3]=3, [slot=1,port=2]=2}\",\n \"id\": 1,\n \"links\": [\n {\n \"href\": \"https://localhost/api/v1/bps/ports\",\n \"rel\": \"self\"\n },\n {\n \"href\": \"https://localhost/api/v1/bps/ports/operations/reserve\",\n \"method\": \"POST\",\n \"rel\": \"reserve operation\"\n },\n {\n \"href\": \"https://localhost/api/v1/bps/ports/operations/unreserve\",\n \"method\": \"POST\",\n \"rel\": \"unreserve operation\"\n }\n ]\n }, 200\n \nclass ReservePorts(Resource):\n '''\n responds a port-reserving post request with 200, including json showing the port statuses after the update... \n '''\n def __init__(self):\n super(ReservePorts, self).__init__()\n \n def post(self):\n return {\n \"result\": \"Ports reserved successfully: {[slot=1,port=1]=1:[reserved=admin,group=1,number=2], [slot=1,port=0]=0:[reserved=admin,group=1,number=1], [slot=1,port=3]=3:[reserved=admin,group=2,number=2], [slot=1,port=2]=2:[reserved=admin,group=2,number=1]}\"\n }, 200\n\n \nclass UnReservePorts(Resource):\n '''\n responds a port-unreserving post request with 200, including json showing the port statuses after the update... \n '''\n def __init__(self):\n super(UnReservePorts, self).__init__()\n \n def post(self):\n return {\n \"result\": \"Ports unreserved successfully: {[slot=1,port=1]=1:[reserved=admin,group=1,number=2], [slot=1,port=0]=0:[reserved=admin,group=1,number=1], [slot=1,port=3]=3, [slot=1,port=2]=2}\"\n }, 200\n\n \nclass ExecuteTest(Resource):\n '''\n Receives a POST request that has a Json body: {\"modelname\": modelname, \"group\": group, \"neighborhood\": neighborhood}\n \n returns a 200 with iteration number and testid.\n '''\n def __init__(self):\n self.reqparse = reqparse.RequestParser()\n self.reqparse.add_argument('modelname', type = str, location = 'json')\n self.reqparse.add_argument('group', type = str, location = 'json')\n self.reqparse.add_argument('neighborhood', type = str, location = 'json')\n super(ExecuteTest, self).__init__()\n \n def post(self):\n args = self.reqparse.parse_args()\n queue_id = j.start_job(args[\"modelname\"], args[\"neighborhood\"])\n \n test_id = args[\"modelname\"].split('.')[0] + '-' + queue_id\n\n #TODO : error handling: we need to catch JenkinsClientError exception, extract its message and return with a non-ok status code, like 500\n \n return {\n \"iteration\": queue_id,\n \"testid\": test_id\n }, 200\n \nclass GetStatus(Resource):\n '''\n Receives a POST request that has a Json body: {\"runid\": test_id}\n Calls applicable client (e.g. Jenkins) with the test_id. (it should know what to do with it)\n\n returns a 200 with the status of that test. \n '''\n \n def __init__(self):\n self.reqparse = reqparse.RequestParser()\n self.reqparse.add_argument('runid', type = str, location = 'json')\n super(GetStatus, self).__init__()\n \n def post(self):\n args = self.reqparse.parse_args()\n\n status = j.get_status(args[\"runid\"])\n \n if status == \"IN_PROGRESS\":\n return {\n \"result\": \"The test has: incomplete\"\n }, 200\n elif status == \"SUCCESS\":\n return {\n \"result\": \"The test has: passed\"\n }, 200\n else:\n return {\n \"result\": \"The test has: failed\"\n }, 200\n\n \n#serving CSV request with simple Flask method\n@app.route('/api/v1/bps/export/report//csv')\ndef GetCsv(test_id):\n response = make_response(j.get_report(test_id, pretty=True))\n response.headers[\"Content-Type\"] = \"text/plain\"\n return response\n \n#API resource routing\napi.add_resource(Auth, '/api/v1/auth/session')\napi.add_resource(ViewPorts, '/api/v1/bps/ports')\napi.add_resource(ReservePorts, '/api/v1/bps/ports/operations/reserve')\napi.add_resource(UnReservePorts, '/api/v1/bps/ports/operations/unreserve')\napi.add_resource(ExecuteTest, '/api/v1/bps/tests/operations/start')\napi.add_resource(GetStatus,'/api/v1/bps/tests/operations/result')\n\nif __name__ == '__main__':\n context = ('apigw.factory.ericsson.com.cert.pem', 'apigw.factory.ericsson.com.key.pem')\n j = JenkinsClient()\n app.run(host='0.0.0.0', port=443, ssl_context=context, debug=True)\n \n","sub_path":"api_translator_v0.2.py","file_name":"api_translator_v0.2.py","file_ext":"py","file_size_in_byte":6586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"606106223","text":"import re\n\nfrom detect_secrets.core.potential_secret import PotentialSecret\nfrom detect_secrets.plugins.base import RegexBasedDetector\n\n\nclass AWSSSecretAccessKeyDetector(RegexBasedDetector):\n \"\"\"Scans for AWS secret-access-key.\"\"\"\n\n secret_type = 'AWS Secret Access Key'\n disable_flag_text = 'no-aws-secret-access-key-scan'\n\n def analyze_string_content(self, string, line_num, filename):\n output = {}\n\n # stupid false postive catch til rule gets smarter\n if 'yarn.lock' in filename:\n return output\n\n if 'aws' not in string and 'secret' not in string and 'access' not in string:\n return output\n\n match = re.search(r'(? curr_max:\n curr_max = max_diff\n return int(curr_max)\n\n\n\"\"\"\nGiven an array of integers, find the maximal absolute \ndifference between any two of its adjacent elements.\n\nExample\n\nFor inputArray = [2, 4, 1, 0], the output should be\narrayMaximalAdjacentDifference(inputArray) = 3.\n\"\"\"\n\narr = [-1, 4, 10, 3, -2]\nif __name__ == '__main__':\n arrayMaximalAdjacentDifference(arr)\n","sub_path":"CodeSignal/CodeSignal17.py","file_name":"CodeSignal17.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"152947972","text":"import sys\n\nfrom market_maker.market_maker import OrderManager\n\n\nclass CustomOrderManager(OrderManager):\n \"\"\"A sample order manager for implementing your own custom strategy\"\"\"\n\n def place_orders(self) -> None:\n # implement your custom strategy here\n\n\n\n ## Pull books and quote\n\n # Define instruments on Bitmex.com\n #Perp = XBTUSD\n #Sep = XBTU21\n #DEC = XBTZ21\n\n # Perp_Ticker = self.get_ticker(XBTUSD)\n # print('Perp Ticker:')\n # print(Perp_Ticker)\n # print()\n\n # Future_Ticker = self.get_ticker(XBTZ21)\n # print('Future Ticker')\n # print(Future_Ticker)\n # print()\n\n\n\n\n\n\n buy_orders = []\n sell_orders = []\n\n\n\n # populate buy and sell orders, e.g.\n # buy_orders.append({'price': 999.0, 'orderQty': 100, 'side': \"Buy\"})\n # sell_orders.append({'price': 1001.0, 'orderQty': 100, 'side': \"Sell\"})\n\n self.converge_orders(buy_orders, sell_orders)\n\n\n def checkSpread(self, tickers) -> None:\n #return spread of the two tickers, first being the base\n\n\n return (tickers[1] - tickers[0])/tickers[0]\n\ndef run() -> None:\n order_manager = CustomOrderManager()\n\n # Try/except just keeps ctrl-c from printing an ugly stacktrace\n try:\n order_manager.run_loop()\n except (KeyboardInterrupt, SystemExit):\n sys.exit()\n","sub_path":"market_maker/custom_strategy.py","file_name":"custom_strategy.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"39534556","text":"import datetime\nimport logging\n\nfrom storm.monitoring.sensor.api import sensor\nfrom storm.monitoring.sensor.api import metrics\nfrom storm.monitoring.sensor.api import services\nfrom storm.monitoring.sensor.api import measure\nfrom storm.monitoring.sensor.host.mem import mem_check\nfrom storm.monitoring.sensor.api import measures\n\nclass MemSensor(sensor.Sensor):\n\n def __init__(self, hostname, service_types):\n self.logger = logging.getLogger(\"storm_sensor.mem_sensor\")\n self.logger.info(\"creating an instance of MemSensor\")\n\n self.hostname = hostname\n self.metric_type = metrics.Metrics().mem\n for val in service_types:\n if val not in services.Services().get_services():\n msg = 'The specified servive type %s does not exist' % str(val)\n raise services.ServicesError(msg)\n self.service_types = service_types\n self.timestamp = ''\n self.measures = measures.Measures()\n\n def get_hostname(self):\n \"\"\"Return hostname information\"\"\"\n self.logger.info(\"getting hostname\")\n return self.hostname\n\n def run(self):\n \"\"\"Run sensor and save data\"\"\"\n self.logger.info(\"doing run\")\n self.timestamp = datetime.datetime.now()\n output = mem_check.Free()\n self.measures.add_measure(output.get_used())\n self.measures.add_measure(output.get_free())\n self.get_measures()\n\n def get_measures(self):\n \"\"\"Return measures\"\"\"\n self.logger.info(\"getting measures\")\n return self.measures\n\n def get_timestamp(self):\n \"\"\"Return timestamp\"\"\"\n self.logger.info(\"getting timestamp\")\n return self.timestamp\n\n def get_metric_type(self):\n \"\"\"Return metric type\"\"\"\n self.logger.info(\"getting measures\")\n return self.metric_type\n\n def get_storm_service_types(self):\n \"\"\"Return storm service types\"\"\"\n self.logger.info(\"getting storm service types\")\n return self.service_types\n","sub_path":"packages/sensor-host/sources/host/mem/mem_sensor.py","file_name":"mem_sensor.py","file_ext":"py","file_size_in_byte":2006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"167780288","text":"import pandas as pd\r\nfrom budgetreport import BudgetReport\r\n\r\n# Show all df columns in run tool window\r\npd.set_option(\"display.expand_frame_repr\", False)\r\n\r\n\r\ndef main():\r\n\r\n print(\"Importing data...\")\r\n\r\n # Create BudgetReport object holding data needed to produce final output\r\n budget_report = BudgetReport()\r\n\r\n # Create list of Asset objects for which the user wants to budget\r\n assets = budget_report.create_asset_objects()\r\n\r\n print(\"Computing cost to service...\")\r\n\r\n # Create CostCentre objects based on the Asset objects above\r\n budget_report.create_cost_centre_objects(assets, budget_report)\r\n\r\n # Compute asset support hours\r\n budget_report.compute_asset_support_hours()\r\n\r\n print(\"Writing output to Excel...\")\r\n\r\n # Write output to Excel\r\n budget_report.write_output_to_excel()\r\n\r\n input(\"Budget report output successfully generated. Press 'Enter' to close this window.\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n main()\r\n\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"423293059","text":"#!/usr/bin/env python3\nimport time\nimport random\nimport hashlib\nimport json\n\nimport requests\nimport lxml.html\n\nfrom models import session, GameCounter, GameLib\n\n\nclass Githyp(object):\n\n entry_point = {\n # 'most_played': 'https://www.githyp.com/page/{page_num}/?type=steam-player-counts',\n # 'most_watched': 'https://www.githyp.com/page/{page_num}/?type=twitch-viewer-counts',\n 'trending_play': 'https://www.githyp.com/page/{page_num}/?type=steam-player-counts&sort=trending',\n 'trending_watch': 'https://www.githyp.com/page/{page_num}/?type=twitch-viewer-counts&sort=trending',\n # 'release': 'https://www.githyp.com/page/{page_num}/?type=release-date&rsort=pop'\n }\n\n games_cache = {}\n view_count_cache = {}\n\n def __init__(self):\n\n pass\n\n def http_parse(self, url):\n\n default_headers = {\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/74.0.3729.157 Safari/537.36'\n }\n try:\n time.sleep(random.uniform(1, 3))\n r = requests.get(url, headers=default_headers, timeout=15)\n return r\n except Exception as e:\n self.logs(status_code=3, url=url, exc=e)\n return None\n\n @staticmethod\n def logs(status_code, url, exc):\n \"\"\"\n 添加日志文件\n :param status_code:\n :param url:\n :param exc:\n :return:\n \"\"\"\n with open('logs', 'a', encoding='utf8') as g:\n g.write('{}\\t{}\\t{}\\t{}\\n'.format(status_code, url, str(exc), time.ctime()))\n\n def get_all_games(self):\n\n for category, url in self.entry_point.items():\n page_num = 1\n while True:\n request_url = url.format(page_num=page_num)\n response = self.http_parse(request_url)\n\n if response:\n page_num += 1\n print('url->{}'.format(response.url))\n xml = lxml.html.fromstring(response.text)\n game_list = xml.xpath('//div[@class=\"item-inner\"]')\n\n if game_list:\n for game in game_list:\n game_name = game.xpath('./a[2]/div[@class=\"item-main\"]/div[@class=\"item-header\"]/h2/text()')\n game_url = game.xpath('./a[2]/@href')\n game_name = ''.join(game_name).strip()\n game_url = game_url[0].split('?')[0]\n game_id = game_url.split('/')[3]\n # 1 需要频繁更新 / 2 更新不需要很频繁\n if category != 'trending_watch' and category != 'trending_play':\n game_count = game.xpath(\n './a[2]/div[@class=\"item-main\"]/div/div[@class=\"comments-link\"]/div'\n '[@class=\"gamecount\"]/text()')[0].strip()\n flag = 0 if game_count == '0' or game_count == 'N/A' else 1\n # trending分类表示有新增用户,flag必然为1\n else:\n flag = 1\n pk = self.get_primary_key(game_id, game_name)\n self.cache_in_memory(pk, game_name, game_id, game_url, flag)\n\n else:\n print('{} has finished'.format(category))\n break\n\n @staticmethod\n def get_primary_key(game_id, game_name):\n \"\"\"\n 通过计算url+game_name的哈希值作为主键\n :param game_id:\n :param game_name:\n :return:\n \"\"\"\n val = game_id + game_name\n md5_val = hashlib.md5(val.encode('utf8')).hexdigest()\n return md5_val\n\n def get_new_release(self):\n \"\"\"\n 每日获取release中新增的游戏\n :return:\n \"\"\"\n page_num = 0\n release_url = 'https://www.githyp.com/page/{page_num}/?type=release-date&rsort=pop'\n while True:\n request_url = release_url.format(page_num=page_num)\n response = self.http_parse(request_url)\n if response:\n page_num += 1\n print('url->{}'.format(response.url))\n xml = lxml.html.fromstring(response.text)\n game_list = xml.xpath('//div[@class=\"item-inner\"]')\n\n if game_list:\n for game in game_list:\n game_name = game.xpath('./a[2]/div[@class=\"item-main\"]/div[@class=\"item-header\"]/h2/text()')\n game_url = game.xpath('./a[2]/@href')\n game_name = ''.join(game_name).strip()\n game_url = game_url[0].split('?')[0]\n game_id = game_url.split('/')[3]\n flag = 0\n pk = self.get_primary_key(game_id, game_name)\n self.cache_in_memory(pk, game_name, game_id, game_url, flag)\n\n else:\n break\n\n def get_game_counts(self):\n \"\"\"\n 遍历game库,并获得游戏对应的数据,应该从数据库中进行读取\n :return:\n \"\"\"\n headers = {\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/74.0.3729.157 Safari/537.36'\n }\n playload = ['viewer-count', 'player-count']\n game_set = session.query(GameLib).filter_by(flag=1).all()\n for game in game_set:\n item_dict = {\n 'Current Players': '',\n 'Current Players Rank': '',\n 'Share of Steam': '',\n 'Current Viewers': '',\n 'Current Viewers Rank': '',\n 'Share of Twitch': ''\n }\n for p in playload:\n response = requests.get(game.game_url, params={'tab': p}, headers=headers, timeout=15)\n print('url -> {}'.format(response.url))\n xml = lxml.html.fromstring(response.text)\n rows = xml.xpath('//section[@class=\"desktopiconbar\"]/div[@class=\"column\"]/div[@class=\"row\"]')\n for row in rows:\n value_count = row.xpath('./div[contains(@class, \"value-count\")]/text()')\n value_title = row.xpath('./div[@class=\"value-title\"]/text()')\n value_count = value_count[0].strip()\n value_title = value_title[0].strip()\n if value_title in item_dict.keys():\n item_dict[value_title] = value_count\n game_counter = GameCounter(\n game_pk=game.pk,\n current_players=item_dict['Current Players'],\n current_players_rank=item_dict['Current Players Rank'],\n share_of_steam=item_dict['Share of Steam'],\n current_viewers=item_dict['Current Viewers'],\n current_viewers_rank=item_dict['Current Viewers Rank'],\n share_of_twitch=item_dict['Share of Twitch']\n )\n session.add(game_counter)\n session.commit()\n print(json.dumps(item_dict))\n\n def cache_in_memory(self, pk, game_name, game_id, game_url, flag):\n\n temp = {\n 'pk': pk,\n 'game_name': game_name,\n 'game_id': game_id,\n 'game_url': game_url,\n 'flag': flag,\n 'crawl_time': time.ctime()\n }\n # 先将数据放到缓存中,如果该pk存在则不添加\n if not self.games_cache.get(pk, None):\n self.games_cache[pk] = temp\n\n def save2file(self):\n\n with open('GameLib', 'w', encoding='utf8') as g:\n\n if self.games_cache:\n for key, value in self.games_cache.items():\n g.write('{}\\t{}\\t{}\\t{}\\t{}\\n'.format(\n value['pk'],\n value['game_id'],\n value['game_name'],\n value['game_url'],\n value['flag']\n ))\n g.flush()\n print('save file successful~')\n\n def save2mysql(self):\n\n if self.games_cache:\n for key, value in self.games_cache.items():\n game = GameLib(\n pk=value['pk'],\n game_id=value['game_id'],\n game_name=value['game_name'],\n flag=value['flag'],\n game_url=value['game_url']\n )\n session.add(game)\n session.commit()\n\n\nif __name__ == '__main__':\n spider = Githyp()\n spider.get_game_counts()\n # spider.get_all_games()\n # spider.save2file()\n # spider.save2mysql()\n","sub_path":"githyp.py","file_name":"githyp.py","file_ext":"py","file_size_in_byte":8916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"315318502","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport math\nimport os\n\n# The base url for pair download.\n# (The full path for a given app number (e.g. \"1234567\")\n# looks like: http://commondatastorage.googleapis.com/uspto-pair/applications/1234567.zip)\nurl = 'http://commondatastorage.googleapis.com/uspto-pair/applications/'\n\n# Set as global in pypair.py. (Changing the value here would have no effect.)\nworking_dir = None\n\n# Directory where srnt pdf files are kept for converting (single process mode).\ndir = \"/home/roland/pypair/test\"\n\n# Script path.\nscript_path = os.path.dirname(os.path.realpath(__file__)) + '/'\n\ndownload_path = script_path + 'download/'\ndownload_file = download_path + 'bulk_download.txt'\n\n# Decrease or increase \"sensitivity\" of vertical column detection. (For example\n# a document might be skewed.)\n# The point_offset can be thought of as \"tolerance\" parameter.\ncolumn_detection = {\n 'point_offset': 100 # Default 100. (Prev. 25)\n}\n\n# Rows where the average pixel values are below\n# the given threshold are considered as useful.\nrow_threshold = 254.5 # Default: 254.5\n\n# Parameters for canny edge detection.\n# Canny edge detection is used to prepare the image for the probabilistic hough\n# transformation.\n#\n# threshold1 – first threshold for the hysteresis procedure.\n# threshold2 – second threshold for the hysteresis procedure.\n# apertureSize – aperture size for the Sobel() operator.\n# (See: http://docs.opencv.org/modules/imgproc/doc/feature_detection.html#canny)\ncanny = {\n \"threshold1\": 80,\n \"threshold2\": 120,\n \"aperture_size\": 3\n}\n\n# Parameters for the probabilistic hough transformation.\n#\n# rho – Distance resolution of the accumulator in pixels.\n# theta – Angle resolution of the accumulator in radians.\n# threshold – Accumulator threshold parameter. Only those lines are returned that get enough votes ( ).\n# minLineLength – Minimum line length. Line segments shorter than that are rejected.\n# maxLineGap – Maximum allowed gap between points on the same line to link them.\n# (See: http://docs.opencv.org/modules/imgproc/doc/feature_detection.html#houghlinesp)\nhough = {\n \"rho\": 1,\n \"theta\": (math.pi / 2), # Default: math.pi / 2\n \"threshold\": 2, # Default: 2\n \"minLineLength\": 100, # Default: 100\n \"maxLineGap\": 5 # Default: 5\n}\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"644333784","text":"\"\"\"This file contains class for client main window. Based on PyQt5 classes.\"\"\"\n\nimport sys\nimport json\nimport logging\nimport base64\nfrom Crypto.PublicKey import RSA\nfrom Crypto.Cipher import PKCS1_OAEP\nfrom PyQt5.QtWidgets import QMainWindow, qApp, QMessageBox, QApplication, QListView\nfrom PyQt5.QtGui import QStandardItemModel, QStandardItem, QBrush, QColor\nfrom PyQt5.QtCore import pyqtSlot, QEvent, Qt\nfrom client.main_window_conv import Ui_MainClientWindow\nfrom client.add_contact import AddContactDialog\nfrom client.del_contact import DelContactDialog\nfrom client.database import ClientDatabase\nfrom client.transport import ClientTransport\nfrom client.start_dialog import UserNameDialog\nfrom common.errors import ServerError\nfrom client.main_window_conv import Ui_MainClientWindow\nfrom client.add_contact import AddContactDialog\nfrom client.del_contact import DelContactDialog\nfrom client.database import ClientDatabase\nfrom client.transport import ClientTransport\nfrom client.start_dialog import UserNameDialog\nfrom common.errors import ServerError\nfrom common.variables import *\n\n\nsys.path.append('../')\nlogger = logging.getLogger('client')\n\n\nclass ClientMainWindow(QMainWindow):\n \"\"\"Base class. Based on PyQt5 QMainWindow.\"\"\"\n def __init__(self, database, transport, keys):\n \"\"\"Constructor with keys, tabs, bars.\"\"\"\n super().__init__()\n self.database = database\n self.transport = transport\n self.decrypter = PKCS1_OAEP.new(keys)\n self.ui = Ui_MainClientWindow()\n self.ui.setupUi(self)\n\n self.ui.menu_exit.triggered.connect(qApp.exit)\n self.ui.btn_send.clicked.connect(self.send_message)\n self.ui.btn_add_contact.clicked.connect(self.add_contact_window)\n self.ui.menu_add_contact.triggered.connect(self.add_contact_window)\n self.ui.btn_remove_contact.clicked.connect(self.delete_contact_window)\n self.ui.menu_del_contact.triggered.connect(self.delete_contact_window)\n\n self.contacts_model = None\n self.history_model = None\n self.messages = QMessageBox()\n self.current_chat = None\n self.current_chat_key = None\n self.encryptor = None\n self.ui.list_messages.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)\n self.ui.list_messages.setWordWrap(True)\n\n self.ui.list_contacts.doubleClicked.connect(self.select_active_user)\n self.clients_list_update()\n self.set_disabled_input()\n self.show()\n\n def set_disabled_input(self):\n \"\"\"Based function to disable input area while contact isn't chosen.\"\"\"\n self.ui.label_new_message.setText('Double click on name will choose user')\n self.ui.text_message.clear()\n if self.history_model:\n self.history_model.clear()\n self.ui.btn_send.setDisabled(True)\n self.ui.text_message.setDisabled(True)\n self.ui.btn_clear.setDisabled(True)\n\n self.encryptor = None\n self.current_chat = None\n self.current_chat_key = None\n\n def history_list_update(self):\n \"\"\"Updating history function.\"\"\"\n list = sorted(self.database.get_history(self.current_chat), key=lambda item: item[3])\n if not self.history_model:\n self.history_model = QStandardItemModel()\n self.ui.list_messages.setModel(self.history_model)\n self.history_model.clear()\n length = len(list)\n start_index = 0\n if length > 20:\n start_index = length - 20\n for i in range(start_index, length):\n item = list[i]\n if item[1] == 'in':\n mess = QStandardItem(f'Incoming message {item[3].replace(microsecond=0)}:\\n {item[2]}')\n mess.setEditable(False)\n mess.setBackground(QBrush(QColor(255, 213, 213)))\n mess.setTextAlignment(Qt.AlignLeft)\n self.history_model.appendRow(mess)\n else:\n mess = QStandardItem(f'Message from {item[3].replace(microsecond=0)}:\\n {item[2]}')\n mess.setEditable(False)\n mess.setTextAlignment(Qt.AlignRight)\n mess.setBackground(QBrush(QColor(204, 255, 204)))\n self.history_model.appendRow(mess)\n self.ui.list_messages.scrollToBottom()\n\n def select_active_user(self):\n \"\"\"Select user function.\"\"\"\n self.current_chat = self.ui.list_contacts.currentIndex().data()\n self.set_active_user()\n\n def set_active_user(self):\n \"\"\"This function tries to request encrypt key to encode messages from\n chosen user.\"\"\"\n try:\n self.current_chat_key = self.transport.key_request(self.current_chat)\n logger.debug(f'Key has been received for {self.current_chat}')\n if self.current_chat_key:\n self.encryptor = PKCS1_OAEP.new(RSA.import_key(self.current_chat_key))\n except (OSError, json.JSONDecodeError) as ER:\n self.current_chat_key = None\n self.encryptor = None\n logger.debug(f'Failed to load key. {ER}')\n if not self.current_chat_key:\n self.messages.warning(self, 'ERROR', \"Key for this user doesn't exist\")\n return\n\n self.ui.label_new_message.setText(f'Enter your message to {self.current_chat}:')\n self.ui.btn_clear.setDisabled(False)\n self.ui.btn_send.setDisabled(False)\n self.ui.text_message.setDisabled(False)\n self.history_list_update()\n\n def clients_list_update(self):\n \"\"\"Updating contacts list to table.\"\"\"\n contacts_list = self.database.get_contacts()\n self.contacts_model = QStandardItemModel()\n for i in sorted(contacts_list):\n item = QStandardItem(i)\n item.setEditable(False)\n self.contacts_model.appendRow(item)\n self.ui.list_contacts.setModel(self.contacts_model)\n\n def add_contact_window(self):\n\n global select_dialog\n select_dialog = AddContactDialog(self.transport, self.database)\n select_dialog.btn_ok.clicked.connect(lambda: self.add_contact_action(select_dialog))\n select_dialog.show()\n\n def add_contact_action(self, item):\n \"\"\"Adding contact and closing window.\"\"\"\n new_contact = item.selector.currentText()\n self.add_contact(new_contact)\n item.close()\n\n def add_contact(self, new_contact):\n \"\"\"Function tries to adding contact to users contact list.\"\"\"\n try:\n self.transport.add_contact(new_contact)\n except ServerError as err:\n self.messages.critical(self, 'Server Error!', err.text)\n except OSError as err:\n if err.errno:\n self.messages.critical(self, 'ERROR', 'Connection o server has been lost')\n self.close()\n self.messages.critical(self, 'Error', 'Connection time out')\n else:\n self.database.add_contact(new_contact)\n new_contact = QStandardItem(new_contact)\n new_contact.setEditable(False)\n self.contacts_model.appendRow(new_contact)\n logger.info(f'Contact {new_contact} has been added successfully')\n self.messages.information(self, 'Done', 'Contact has been added successfully')\n\n def delete_contact_window(self):\n \"\"\"Delete contact and lose window.\"\"\"\n global remove_dialog\n remove_dialog = DelContactDialog(self.database)\n remove_dialog.btn_ok.clicked.connect(lambda: self.delete_contact(remove_dialog))\n remove_dialog.show()\n\n def delete_contact(self, item):\n \"\"\"Function tries to delete contact.\"\"\"\n selected = item.selector.currentText()\n try:\n self.transport.remove_contact(selected)\n except ServerError as err:\n self.messages.critical(self, 'Server Error', err.text)\n except OSError as err:\n if err.errno:\n self.messages.critical(self, 'Error', 'Connection has bees lost')\n self.close()\n self.messages.critical(self, 'Error', 'Connection time out')\n else:\n self.database.del_contact(selected)\n self.clients_list_update()\n logger.info(f'Contact {selected} has been deleted successfully')\n self.messages.information(self, 'Done', 'Contact has been deleted successfully')\n item.close()\n if selected == self.current_chat:\n self.current_chat = None\n self.set_disabled_input()\n\n def send_message(self):\n \"\"\"Send message function.\"\"\"\n message_text = self.ui.text_message.toPlainText()\n self.ui.text_message.clear()\n if not message_text:\n return\n\n message_text_encrypted = self.encryptor.encrypt(message_text.encode('utf-8'))\n message_text_encrypted_base64 = base64.b64encode(message_text_encrypted)\n\n try:\n self.transport.send_message(self.current_chat, message_text_encrypted_base64.decode('ascii'))\n pass\n except ServerError as err:\n self.messages.critical(self, 'Error', err.text)\n except OSError as err:\n if err.errno:\n self.messages.critical(self, 'Error', 'Connection has been lost')\n self.close()\n self.messages.critical(self, 'Error', 'Connection time out')\n except (ConnectionResetError, ConnectionAbortedError):\n self.messages.critical(self, 'Error', 'Connection has been lost')\n self.close()\n else:\n self.database.save_message(self.current_chat, 'out', message_text)\n logger.debug(f'Message has been send to {self.current_chat}: {message_text}')\n self.history_list_update()\n\n @pyqtSlot(str)\n def message(self, message):\n \"\"\"Receive incoming message and decode it.\"\"\"\n encrypted_message = base64.b64decode(message[MESSAGE_TEXT])\n try:\n decrypted_message = self.decrypter.decrypt(encrypted_message)\n except (ValueError, TypeError) as ER:\n self.messages.warning(self, 'ERROR', 'Failed to decrypt message')\n return\n self.database.save_message(self.current_chat, 'in', decrypted_message.decode('utf-8'))\n sender = message[SENDER]\n if sender == self.current_chat:\n self.history_list_update()\n else:\n if self.database.check_contact(sender):\n if self.messages.question(self, 'New Message',\n f'New message from {sender}, open chat?', QMessageBox.Yes,\n QMessageBox.No) == QMessageBox.Yes:\n self.current_chat = sender\n self.set_active_user()\n else:\n print('NO')\n if self.messages.question(self, 'New Message',\n f'New message from {sender}.\\nUser is not in your contact list\\nAdd to contacts and open chat?',\n QMessageBox.Yes,\n QMessageBox.No) == QMessageBox.Yes:\n self.add_contact(sender)\n self.current_chat = sender\n self.set_active_user()\n\n @pyqtSlot()\n def connection_lost(self):\n \"\"\"Warnings while connection has been interrupted.\"\"\"\n self.messages.warning(self, 'Connection Error', 'Connection has been lost')\n self.close()\n\n @pyqtSlot()\n def sig_205(self):\n \"\"\"Warnings while contact is not online.\"\"\"\n if self.current_chat and not self.database.check_user(self.current_chat):\n self.messages.warning(self, 'Sorry', 'User has been deleted from server')\n self.set_disabled_input()\n self.current_chat = None\n self.clients_list_update()\n\n def make_connection(self, trans_obj):\n trans_obj.new_message.connect(self.message)\n trans_obj.connection_lost.connect(self.connection_lost)\n\n\n\n\"\"\"Some commentary for test 27.07.2020 \"\"\"","sub_path":"client/HeroChatClient/client/main_window.py","file_name":"main_window.py","file_ext":"py","file_size_in_byte":12057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"259512199","text":"import tensorflow as tf\nfrom flask_restful import reqparse\nimport numpy as np\n\nclass CabbageController:\n def __init__(self,avg_tmep,min_temp,max_temp,rain_fall):\n self.avg = avg_tmep\n self.min = min_temp\n self.max = max_temp\n self.rain = rain_fall\n\n def service(self):\n X = tf.placeholder(tf.float32, shape=[None, 4])\n Y = tf.placeholder(tf.float32, shape=[None, 1])\n W = tf.placeholder(tf.random_normal([4, 1]), name='weight')\n b = tf.placeholder(tf.random_normal([1]), name='bias')\n saver = tf.train.Saver()\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n save_path= 'cabbage/data/saved.ckpt'\n saver.restore(sess,save_path)\n data=[[self.avg, self.min, self.maxa, self.rain],]\n arr = np.array(data,dtype=np.float32)\n dict=sess.run(tf.matmul(X,W)+b,{X:arr[0:4]})\n return int(dict[0])\n","sub_path":"cabbage/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"221525646","text":"# Importing the frameworks\n\nfrom modules import *\nfrom flask import *\nimport database\nimport configparser\n\nuser_details = {} # User details kept for us\nsession = {}\npage = {}\n\n# Initialise the application\napp = Flask(__name__)\napp.secret_key = 'aab12124d346928d14710610f'\n\n\n#####################################################\n## INDEX\n#####################################################\n\n@app.route('/')\ndef index():\n # Check if the user is logged in\n if('logged_in' not in session or not session['logged_in']):\n return redirect(url_for('login'))\n page['title'] = 'IssueTracker'\n return render_template('index.html',\n session=session,\n page=page,\n user=user_details)\n\n#####################################################\n## LOGIN\n#####################################################\n\n@app.route('/login', methods=['POST', 'GET'])\ndef login():\n # Check if they are submitting details, or they are just logging in\n if(request.method == 'POST'):\n # submitting details\n login_return_data = check_login(request.form['id'])\n\n # If it's null, saying they have incorrect details\n if login_return_data is None:\n page['bar'] = False\n flash(\"Incorrect id, please try again\")\n return redirect(url_for('login'))\n\n # If there was no error, log them in\n page['bar'] = True\n flash('You have been logged in successfully')\n session['logged_in'] = True\n\n # Store the user details for us to use throughout\n global user_details\n user_details = login_return_data\n return redirect(url_for('index'))\n\n elif(request.method == 'GET'):\n return(render_template('login.html', page=page))\n\n#####################################################\n## LOGOUT\n#####################################################\n\n@app.route('/logout')\ndef logout():\n session['logged_in'] = False\n page['bar'] = True\n flash('You have been logged out')\n return redirect(url_for('index'))\n\n#####################################################\n## LIST ISSUE\n#####################################################\n\n@app.route('/issue', methods=['POST', 'GET'])\ndef list_issue():\n if( 'logged_in' not in session or not session['logged_in']):\n return redirect(url_for('login'))\n # The user is just viewing the page\n if (request.method == 'GET'):\n # First check if specific event\n issue_list = database.all_issue(user_details['member_id'])\n if(issue_list is None):\n issue_list = []\n flash(\"Error, no issue in our system.\")\n page['bar'] = False\n return render_template('issue_list.html', issue=issue_list, session=session, page=page)\n\n # Try to get from the database\n elif(request.method == 'POST'):\n issue_list_find = database.all_issue_find(request.form['search'], user_details['member_id'])\n if(issue_list_find is None):\n issue_list_find = []\n flash(\"Error, issue \\'{}\\' does not exist\".format(request.form['search']))\n page['bar'] = False\n return render_template('issue_list.html', issue=issue_list_find, session=session, page=page)\n\n#####################################################\n## Add Issue\n#####################################################\n\n@app.route('/new-issue' , methods=['GET', 'POST'])\ndef new_issue():\n if( 'logged_in' not in session or not session['logged_in']):\n return redirect(url_for('login'))\n\n # If we're just looking at the 'new issue' page\n if(request.method == 'GET'):\n times = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]\n return render_template('new_issue.html', user=user_details, times=times, session=session, page=page)\n # If we're adding a new issue\n success = database.new_issue(request.form['title'],\n\t\t\t\t request.form['creator'],\n request.form['resolver'],\n request.form['verifier'],\n request.form['description'])\n if(success == True):\n page['bar'] = True\n flash(\"Issue Added!\")\n return(redirect(url_for('index')))\n else:\n page['bar'] = False\n flash(\"There was an error adding new issue.\")\n return(redirect(url_for('new_issue')))\n\t\t\n#####################################################\n## UPDATE ISSUE\n#####################################################\n@app.route('/update_issue/', methods=['GET', 'POST'])\ndef update_issue():\n if( 'logged_in' not in session or not session['logged_in']):\n return redirect(url_for('login'))\n\t\t\n\t# Check the details of the issue\n issue_id = request.args.get('issue_id')\n\t\n #if not issue_id:\n # page['bar'] = False\n # flash(\"Error, no issue was given. URL requires \\'?issue_id=\\'\")\n # return(redirect(url_for('index')))\n\t\n issue_results = get_issue(issue_id,user_details['member_id'])\n\t\n if issue_results is None:\n issue_results = []\n\n # If we're just looking at the 'update issue' page\n if(request.method == 'GET'):\n times = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]\n return render_template('update_issue.html', issueInfo = issue_results, user=user_details, times=times, session=session, page=page)\n # If we're updating an issue\n success = database.update_issue(request.form['title'],\n\t\t\t\t request.form['creator'],\n request.form['resolver'],\n request.form['verifier'],\n request.form['description'],\n\t\t\t\t request.form['issue_id'])\n if(success == True):\n page['bar'] = True\n flash(\"Issue Updated!\")\n return(redirect(url_for('index')))\n else:\n page['bar'] = False\n flash(\"There was an error adding new issue.\")\n return(redirect(url_for('update_issue')))\n\t\t\n\t\t\ndef get_issue(issue_id, member_id):\n print('routes.getIssue')\n for issue in database.all_issue(member_id):\n if issue['issue_id'] == issue_id:\n return [issue]\n return None\t\n\t\ndef check_login(member_id):\n print('routes.check_login')\n user_data = [member_id, '', '']\n tuples = {\n 'member_id': user_data[0],\n\t 'first_name': user_data[1],\n 'family_name': user_data[2],\n }\n return tuples\n","sub_path":"Database_Application_Development/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":6470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"333329691","text":"#import libraries\nimport pandas as pd\nfrom link import lnk\nimport IPython.core.display as d\nimport matplotlib.pyplot as plt\nfrom collections import defaultdict\nfrom pandas import datetime\nfrom datetime import date, timedelta\nimport numpy as np\nimport sys\nsys.path.append('/home/gfield/notebooks')\nimport utility_bg as utility_custom\nfrom csv import DictReader\nfrom sys import argv,exit\n\n# \n\nlookback = 1\nday = datetime.today() - timedelta(days=lookback)\nstart_date = str(day.strftime('%Y-%m-%d'))\nyesterday_str = str(start_date) + ' 00:00:00'\ntoday = datetime.today()\ntoday_str = str(datetime.today().strftime('%Y-%m-%d')) + ' 00:00:00'\n# \n\nVQ = lnk.dbs.vertica\napiMYSQL = lnk.dbs.mprod_api\n\n# \nfilename = sys.argv[1]\nf = open(filename, 'r')\ntag_ids = f.read()\n\n# \n\njpt_tag_query = \"\"\"SELECT DATE(ymdh), \ntag_id,width, height,geo_country,imp_type, SUM(imps) AS total_seen, \nSUM(imps_bid_on) AS imps_bid_on, \nSUM(imps_bid_on)/ SUM(imps) AS bid_on_pct, \nSUM(CASE WHEN is_delivered=1 THEN imps ELSE 0 END) AS 'imps filled', \nSUM(CASE WHEN is_delivered=1 THEN imps ELSE 0 END)/SUM(imps)*100 AS fill_pct \nFROM agg_platform_seller_analytics WHERE tag_id IN (\"\"\"+tag_ids+\"\"\") AND imp_type IN (5,6) AND ymdh>='\"\"\"+yesterday_str+\"\"\"' and ymdh < '\"\"\"+today_str+\"\"\"' GROUP BY 1,2,3,4,5,6 ORDER BY 1 ASC, 2 ASC;\"\"\"\ntag_volumes = VQ.select_dataframe(jpt_tag_query)\n\njpt_name_query = \"\"\"SELECT id,name from api.tinytag WHERE id IN (\"\"\"+tag_ids+\"\"\");\"\"\"\ntag_names = apiMYSQL.select_dataframe(jpt_name_query)\n\nmerged = tag_volumes.merge(tag_names, left_on='tag_id', right_on='id')\nmerged = merged[['date', 'tag_id', 'name', 'width', 'height','geo_country','imp_type','total_seen', 'imps_bid_on', 'bid_on_pct', 'imps filled', 'fill_pct']]\n\nfrom datetime import datetime\nusername= 'gfield'\nsave_loc = \"/home/%s/public\" % username\nday = datetime.today()\ndate = str(day.strftime('%Y_%m_%d'))\nfile_name = \"jpt_stats_%s.csv\"%(date)\nsave_file_location = \"%s/jpt_stats_%s.csv\"%(save_loc,date)\nmerged.to_csv(save_file_location,index=True)\n\n# \n\ncss = \"\"\"\n\"\"\"\n\n# \n\nimport os\nimport sys\nsys.path.append('/home/gfield/public/')\n\n# \n\nhtml_doc = css + \"

See attached for JPT stats

\"\nhtml_doc = html_doc.encode(\"utf-8\", 'replace')\nutility_custom.send_email(['achatfield@appnexus.com','jjacob@appnexus.com','biddrreporting@brealtime.com','acook@cpxi.com','hwenzel@appnexus.com'],'JPT Daily Stats',html_doc,'JPT Stats ',smtpserver=\"mail.adnxs.net\",cc_addr_list=None,attachments=[save_file_location])","sub_path":"JPT_Report.py","file_name":"JPT_Report.py","file_ext":"py","file_size_in_byte":2858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"5075914","text":"import numpy as np\nimport torch\n\n\ntry:\n import nvidia.dali as dali\n import nvidia.dali.plugin.pytorch as to_pytorch\nexcept ImportError:\n dali = None\n\n\nif not torch.cuda.is_available():\n raise RuntimeError(\"DALI requires CUDA support.\")\n\n\nseed = 1549361629\n\n\nclass _DaliImageDecoderPipeline(dali.ops.Pipeline):\n def __init__(self, batch_size: int, num_threads: int, device_id: int):\n super(_DaliImageDecoderPipeline, self).__init__(\n batch_size, num_threads, device_id, seed = seed\n )\n\n self.input = dali.ops.ExternalSource()\n #self.decode = dali.ops.ImageDecoder(\n # device='mixed', output_type=dali.types.RGB\n #)\n self.pos_rng_x = dali.ops.Uniform(range = (0.0, 1.0))\n self.pos_rng_y = dali.ops.Uniform(range = (0.0, 1.0))\n self.decode = dali.ops.ImageDecoderCrop(\n device='mixed', output_type=dali.types.RGB, crop=(64, 64))\n\n @property\n def data(self):\n return self._data\n\n def set_data(self, data):\n self._data = data\n\n def define_graph(self):\n self.jpegs = self.input()\n #images = self.decode(self.jpegs)\n pos_x = self.pos_rng_x()\n pos_y = self.pos_rng_y()\n images = self.decode(self.jpegs, crop_pos_x=pos_x, crop_pos_y=pos_y)\n return images\n\n def iter_setup(self):\n images = self.data\n self.feed_input(self.jpegs, images, layout=\"HWC\")\n\n\nclass _DaliImageDecoder:\n def __init__(self, batch_size: int, num_workers: int, device: torch.device) -> None:\n self._pipe = _DaliImageDecoderPipeline(batch_size, num_workers, device)\n self._pipe.build()\n\n self._device = device\n\n def __call__(self, input):\n # set data and run the pipeline\n self._pipe.set_data(input)\n out_pipe = self._pipe.run()\n\n # retrieve dali tensor\n d_images: nvidia.dali.backend_impl.TensorGPU = out_pipe[0].as_tensor()\n\n # create torch tensor header with expected size\n t_images = torch.empty(\n d_images.shape(), dtype=torch.uint8, device=self._device)\n\n # populate torch tensor with dali tensor\n to_pytorch.feed_ndarray(d_images, t_images)\n t_images = t_images.permute([0, 3, 1, 2])\n\n return t_images\n\n\nclass DaliImageCollateWrapper:\n def __init__(self, batch_size: int, device: torch.device):\n self._decoder = _DaliImageDecoder(batch_size, 8, device.index)\n\n self._device = torch.device(\"cuda:0\")\n\n def __call__(self, input):\n images = [data[0] for data in input]\n labels = [data[1] for data in input]\n \n t_images = self._decoder(images)\n t_labels = torch.tensor(labels, device=t_images.device)\n return t_images, t_labels\n\n\nclass DaliImageReader:\n def __init__(self, device: torch.device, decode: bool = False) -> None:\n self._loader = _DaliImageDecoder(1, 8, device.index)\n self._decode = decode\n\n def __call__(self, image_file: str) -> torch.Tensor:\n f = open(image_file, 'rb')\n np_array = np.frombuffer(f.read(), dtype=np.uint8)\n if self._decode:\n return self._decoder([np_array])\n return np_array\n","sub_path":"kornia/io/dali.py","file_name":"dali.py","file_ext":"py","file_size_in_byte":3189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"550073081","text":"import pandas as pd\r\nfrom itertools import chain\r\nimport numpy as np\r\nimport json\r\n\r\nwith open('Entities.json') as f:\r\n data = json.load(f)\r\n\r\ndf_entity_orginal = pd.DataFrame({'Entity' : []})\r\n# print(len(data))\r\nfor i in range(len(data)):\r\n\tdf_entity_orginal = df_entity_orginal.append({'Entity': data[i][\"name\"]}, ignore_index=True)\r\n\t# print(data[i][\"name\"])\r\nprint(df_entity_orginal)\r\n\r\ndata_topic_map = pd.read_csv(\"Event_Document_Map_k3.csv\", encoding = \"ISO-8859-1\")\r\ndata_entity = pd.read_csv(\"result_NET.csv\", encoding = \"ISO-8859-1\")\r\nfor row in data_topic_map.iterrows():\r\n\t# print(row)\r\n\tdf_empty = pd.DataFrame({'Document' : []})\r\n\tstr1 = row[1]['Document'][1:-1]\r\n\tif \",\" not in str1: \r\n\t\tcontinue\r\n\tlist1 = [x.strip() for x in str1.split(',')]\r\n\t# print(list1)\r\n\tfor i in range(len(list1)):\r\n\t\tdf_empty = df_empty.append({'Document': list1[i]}, ignore_index=True)\r\n\tdf_empty['Document'] = df_empty['Document'].astype(int)\r\n\t# print(df_empty)\r\n\t# print(data_entity.dtypes)\r\n\tdf_empty = df_empty.join(data_entity.set_index('Document'), on='Document')\r\n\tdf_empty = df_empty.loc[df_empty['Entities'] != '[]']\r\n\t# df_empty = df_empty.dropna(subset=['Entities'])\r\n\t# print(df_empty)\r\n\tdf_empty2 = pd.DataFrame({'Entity' : [], 'Event'+str(row[0]): []})\r\n\tfor row1 in df_empty.iterrows():\r\n\t\tstr2 = row1[1]['Entities'][1:-1]\r\n\t\tif \",\" not in str2: \r\n\t\t\tcontinue\r\n\t\tlist1 = [x.strip() for x in str2.split(',')]\r\n\t\tfor i in range(len(list1)):\r\n\t\t\tdf_empty2 = df_empty2.append({'Entity': list1[i], 'Event'+str(row[0]): row[0]}, ignore_index=True)\r\n\t\t# list2.append(list1)\r\n\tdf_empty2['Event'+str(row[0])] = df_empty2['Event'+str(row[0])].astype(int)\r\n\tdf_empty2 = df_empty2.drop_duplicates()\r\n\tprint(df_empty2)\r\n\tdf_entity_orginal = df_entity_orginal.join(df_empty2.set_index('Entity'), on='Entity')\r\n\tdf_entity_orginal['Event'+str(row[0])] = df_entity_orginal['Event'+str(row[0])].fillna(100)\r\n\t# df_entity_orginal['Event'+str(row[0])] = df_entity_orginal['Event'+str(row[0])].astype(int)\r\n# source_col_loc = df_entity_orginal.columns.get_loc('Entity') # column position starts from 0\r\n# df_entity_orginal['Events'] = df_entity_orginal.iloc[:,source_col_loc+1:source_col_loc+45].apply(lambda x: \",\".join(x.astype(str)), axis=1).dropna()\r\n\r\nprint(df_entity_orginal)\r\ndf_empty_final = pd.DataFrame({'Entity' : [], 'Event': []})\r\n# df_entity_orginal.to_csv('Entity_Event.csv', encoding='utf-8')\r\nfor row in df_entity_orginal.iterrows():\r\n\tlist1 = []\r\n\tfor i in range(27):\r\n\t\tif(row[1]['Event'+str(i)]!= 100):\r\n\t\t\tlist1.append(int(row[1]['Event'+str(i)]))\r\n\tprint(list1)\r\n\tdf_empty_final = df_empty_final.append({'Entity': row[1]['Entity'], 'Event': list1}, ignore_index=True)\r\nprint(df_empty_final)\r\ndf_empty_final.to_csv('Entity_Event_k3.csv', encoding='utf-8')\r\n\t# break\r\n","sub_path":"tempdata/K-Values/K3/Entity_Event.py","file_name":"Entity_Event.py","file_ext":"py","file_size_in_byte":2780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"224971648","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n# From: https://oj.leetcode.com/problems/minimum-path-sum/\n# Date: Oct. 1, 2014\n# Status: AC\n\ndef minPathSum(self, grid):\n if not grid:\n return 0\n m = len(grid)\n n = len(grid[0])\n if m == 1:\n return sum(grid[0])\n if n == 1:\n return sum(sum(grid))\n for ix in range(1, m):\n grid[ix][0] = grid[ix-1][0] + grid[ix][0]\n for jx in range(1, n):\n grid[0][jx] += grid[0][jx-1]\n for ix in range(1, m):\n for jx in range(1, n):\n grid[ix][jx] = min(grid[ix-1][jx]) + grid[ix][ix]\n return grid[m-1][n-1]\n","sub_path":"week27/Yao/minimum_path_sum.py","file_name":"minimum_path_sum.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"588422859","text":"import platform\nimport os\nimport subprocess\n\nimport prefect\n\nfrom datateer.tasks.util import get_root_dir\n \nclass SingerTask(prefect.Task):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def run(self, tap=None, target=None, tap_config_path=None, tap_catalog_path=None, tap_state_path=None, target_config_path=None, target_state_path=None) -> int:\n root_dir = get_root_dir()\n\n self.logger.info(f'root_dir: {root_dir}')\n tap_command = [os.path.join(root_dir, f'venv\\\\{tap}\\\\Scripts\\\\{tap}.exe') if platform.system() == 'Windows' else os.path.join(root_dir, f'venv/{tap}/bin/{tap}')]\n \n if tap_catalog_path is not None:\n tap_command.extend(['--catalog', os.path.join(root_dir, tap_catalog_path)])\n\n if tap_config_path is not None:\n tap_command.extend(['--config', os.path.join(root_dir, tap_config_path)])\n \n if tap_state_path is not None:\n tap_command.extend(['--state', os.path.join(root_dir, tap_state_path)])\n\n target_command = [os.path.join(root_dir, f'venv\\\\{target}\\\\Scripts\\\\{target}.exe') if platform.system() == 'Windows' else os.path.join(root_dir, f'venv/{target}/bin/{target}')]\n if target_config_path is not None:\n target_command.extend(['--config', os.path.join(root_dir, target_config_path)])\n\n if target_state_path is not None:\n target_command.extend(['--state', os.path.join(root_dir, target_state_path)])\n\n self.logger.info('Running singer')\n self.logger.info(f'tap command: {tap_command}')\n self.logger.info(f'target command: {target_command}')\n\n try:\n tap_streams = subprocess.Popen(tap_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) # https://stackoverflow.com/questions/2715847/read-streaming-input-from-subprocess-communicate/17698359#17698359\n output = subprocess.check_output(target_command, stdin=tap_streams.stdout) # pass the stdout stream from the tap to the target's stdin\n with tap_streams.stderr:\n for line in tap_streams.stderr:\n self.logger.info(f'SINGER: {line}')\n\n # we use Popen to run the tap. If that encounters a non-zero return code, raise an exception so that we can consistently handle exceptions for the taps (started via Popen) and the targets (started via check_output)\n tap_streams.wait()\n if tap_streams.returncode != 0:\n raise subprocess.CalledProcessError(tap_streams.returncode, cmd=tap_command, output='The tap command encountered a problem. See the surrounding messages for details')\n\n except subprocess.CalledProcessError as exc:\n msg = f'Command failed with exit code {exc.returncode}{os.linesep}{exc.output}'\n self.logger.critical(f'Command failed with exit code {exc.returncode}')\n self.logger.critical(exc.output if type(exc.output) is str else exc.output.decode('utf-8'))\n raise prefect.engine.signals.FAIL(msg) from None\n return output\n \n","sub_path":"datateer/tasks/SingerTask.py","file_name":"SingerTask.py","file_ext":"py","file_size_in_byte":3108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"512416478","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Date : 2019/4/13 21:33\n# @Author: Joy\n# @IDE : PyCharm\n\nclass Solution:\n def longestPalindrome(self, s: str) -> str:\n s_len = s.__len__() - 1\n index, start, end, max_len = 0, 0, 1, 0\n while index < s_len:\n left, right, count, inner_index = index, s_len, 0, 0\n while left <= right:\n if s[left] == s[right]:\n count += 1\n left += 1\n right -= 1\n else:\n inner_index += 1\n left = index\n right = s_len - inner_index\n count = 0\n index += 1\n temp_len = left - count - (right + count + 1)\n if temp_len >= max_len:\n start = left - count\n end = right + count + 1\n max_len = temp_len\n if max_len >= s_len - index + 1:\n break\n return s[start:end]\n\n\nif __name__ == \"__main__\":\n sol = Solution()\n print(sol.longestPalindrome(\"yoyilli\"))\n","sub_path":"test/testAlgorithms.py","file_name":"testAlgorithms.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"313947137","text":"import math\n\n# Python program to print all primes smaller than or equal to\n# n using Sieve of Eratosthenes\n\n\ndef sieve(n):\n\n sieve_list = [True for i in range(n+1)]\n p = 2\n while (p * p <= n):\n if (sieve_list[p] == True):\n for i in range(p * 2, n+1, p):\n sieve_list[i] = False\n p += 1\n\n for p in range(2, n):\n if sieve_list[p]:\n print(p)\n\n\nsieve(30)\n","sub_path":"src/sieve.py","file_name":"sieve.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"449848890","text":"\"\"\" Tests for datastore models in the models.py file. \"\"\"\n\n\n# We need to have our externals.\nimport appengine_config\n\nimport datetime\nimport unittest\n\nfrom google.appengine.ext import testbed\n\nimport models\n\n\n\"\"\" Tests for the Event model. \"\"\"\nclass EventTest(unittest.TestCase):\n def setUp(self):\n self.testbed = testbed.Testbed()\n self.testbed.activate()\n\n self.testbed.init_datastore_v3_stub()\n self.testbed.init_user_stub()\n\n \"\"\" Tests that we can detect conflicts successfully. \"\"\"\n def test_conflict_detection(self):\n # To begin with, create a new event that we can make things conflict with.\n start_time = datetime.datetime(month=1, day=1, year=2015, hour=10, minute=0)\n end_time = start_time + datetime.timedelta(hours=2)\n event = models.Event(name=\"Test Event\", start_time=start_time,\n end_time=end_time, type=\"Meetup\",\n estimated_size=\"10\", setup=15, teardown=15,\n details=\"This is a test event.\", rooms=[\"Classroom\"])\n event.put()\n\n # Putting an event a safe distance before should not conflict.\n new_start_time = start_time - datetime.timedelta(hours=1, minutes=30)\n new_end_time = new_start_time + datetime.timedelta(hours=1)\n self.assertEqual([], models.Event.check_conflict(new_start_time,\n new_end_time, 15, 15, [\"Classroom\"]))\n\n # Putting an event a safe distance after should not conflict.\n new_start_time = end_time + datetime.timedelta(minutes=30)\n new_end_time = new_start_time + datetime.timedelta(hours=1)\n self.assertEqual([], models.Event.check_conflict(new_start_time,\n new_end_time, 15, 15, [\"Classroom\"]))\n\n # Increasing the setup time should be okay until it starts to get into the\n # time alloted for the actual event before it.\n self.assertEqual([], models.Event.check_conflict(new_start_time,\n new_end_time, 30, 15, [\"Classroom\"]))\n\n conflicts = models.Event.check_conflict(new_start_time, new_end_time, 60,\n 15, [\"Classroom\"])\n self.assertEqual(event.key().id(), conflicts[0].key().id())\n\n # We also need at least 30 minutes between consecutive events.\n new_start_time = end_time + datetime.timedelta(minutes=15)\n new_end_time = new_start_time + datetime.timedelta(hours=1)\n conflicts = models.Event.check_conflict(new_start_time, new_end_time, 15,\n 15, [\"Classroom\"])\n self.assertEqual(event.key().id(), conflicts[0].key().id())\n\n # If an event is completely encompassed by another event it should get\n # detected.\n new_start_time = start_time + datetime.timedelta(minutes=30)\n new_end_time = new_start_time + datetime.timedelta(hours=1)\n conflicts = models.Event.check_conflict(new_start_time, new_end_time, 15,\n 15, [\"Classroom\"])\n self.assertEqual(event.key().id(), conflicts[0].key().id())\n\n # If an event exactly overlaps another event, it should get detected.\n conflicts = models.Event.check_conflict(start_time, end_time, 15,\n 15, [\"Classroom\"])\n self.assertEqual(event.key().id(), conflicts[0].key().id())\n\n # If an event overlaps another event not just in setup and teardown on\n # either end, it should get detected.\n new_start_time = start_time - datetime.timedelta(minutes=30)\n new_end_time = new_start_time + datetime.timedelta(hours=1)\n conflicts = models.Event.check_conflict(new_start_time, new_end_time, 15,\n 15, [\"Classroom\"])\n self.assertEqual(event.key().id(), conflicts[0].key().id())\n\n new_start_time = end_time - datetime.timedelta(minutes=30)\n new_end_time = new_start_time + datetime.timedelta(hours=1)\n conflicts = models.Event.check_conflict(new_start_time, new_end_time, 15,\n 15, [\"Classroom\"])\n self.assertEqual(event.key().id(), conflicts[0].key().id())\n","sub_path":"tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":4007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"632162149","text":"from __future__ import unicode_literals, print_function, division\nfrom io import open\nimport unicodedata\nimport string\nimport re\nimport random\nimport os\nimport time\nimport math\n\nimport torch\nimport torch.nn as nn\nfrom torch import optim\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset\nimport numpy as np\n\nfrom sacrebleu import raw_corpus_bleu\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nclass EncoderRNN(nn.Module):\n def __init__(self, input_size, emb_size, hidden_size, pre_zh_emb_matrix):\n super(EncoderRNN, self).__init__()\n self.hidden_size = hidden_size\n self.num_layers = 1\n\n self.embedding = nn.Embedding(input_size, emb_size, padding_idx=0)\n ## Load pretrained emb\n self.embedding.weight.data.copy_(torch.from_numpy(pre_zh_emb_matrix))\n self.gru = nn.GRU(emb_size, hidden_size, self.num_layers, batch_first=True, bidirectional = True)\n\n def forward(self, wordIn, hidden):\n # embedded = self.embedding(input).view(1, 1, -1)\n embedded = self.embedding(wordIn)\n output = embedded\n output, hidden = self.gru(output, hidden)\n # return output.cuda(), hidden.cuda()\n return output.to(device), hidden.to(device)\n\n def initHidden(self, batch_size):\n return torch.zeros(2*self.num_layers, batch_size, self.hidden_size, device=device)\n\nclass Attn(nn.Module):\n def __init__(self, hidden_size, method='concat'):\n super(Attn, self).__init__()\n self.method = method\n self.hidden_size = hidden_size\n # self.emb_size = emb_size\n #self.attn = nn.Linear(self.hidden_size*2, hidden_size)\n self.attn = nn.Linear(self.hidden_size*3, hidden_size)\n self.v = nn.Parameter(torch.rand(hidden_size))\n stdv = 1. / math.sqrt(self.v.size(0))\n self.v.data.normal_(mean=0, std=stdv)\n\n def forward(self, hidden, encoder_outputs):\n '''\n :param hidden:\n previous hidden state of the decoder, in shape (layers*directions,B,H)\n :param encoder_outputs:\n encoder outputs from Encoder, in shape (T,B,H)\n :return\n attention energies in shape (B,T)\n '''\n max_len = encoder_outputs.size(1)\n this_batch_size = encoder_outputs.size(0)\n # print('mLen:{}, batSize:{}'.format(max_len,this_batch_size))\n H = hidden.repeat(max_len,1,1).transpose(0,1)\n #encoder_outputs = encoder_outputs.transpose(0,1) # [B*T*H]\n attn_energies = self.score(H,encoder_outputs) # compute attention score\n return F.softmax(attn_energies, 2).to(device) # normalize with softmax [B*1*T]\n\n def score(self, hidden, encoder_outputs):\n #print('hl size:{}, eo size:{}'.format(hidden.size(), encoder_outputs.size()))\n #energy = F.tanh(self.attn(torch.cat([hidden, encoder_outputs.transpose(0,1)], 2))) # [B*T*2H]->[B*T*H]\n energy = F.tanh(self.attn(torch.cat([hidden, encoder_outputs], 2)))\n energy = energy.transpose(2,1) # [B*H*T]\n v = self.v.repeat(energy.size()[0],1).unsqueeze(0).transpose(0,1) #[1*B*H]\n # print('vSize:{}, energySize:{}'.format(v.size(), energy.size()))\n #print('v size:{}, eng size:{}'.format(v.size(), energy.size()))\n energy = torch.bmm(v,energy) # [B*1*T]\n #return energy.squeeze(1) #[B*T]\n return energy.to(device)\n\nclass BahdanauAttnDecoderRNN(nn.Module):\n def __init__(self, emb_size, hidden_size, output_size, pre_en_emb_matrix, n_layers=2, dropout_p=0.1, max_len = 100):\n super(BahdanauAttnDecoderRNN, self).__init__()\n\n # Define parameters\n self.hidden_size = hidden_size\n self.output_size = output_size\n self.n_layers = n_layers\n self.dropout_p = dropout_p\n self.max_len = max_len\n self.bidirectional = False\n\n # Define layers\n self.embedding = nn.Embedding(output_size, emb_size, padding_idx=0)\n ## Load pretrained emb\n self.embedding.weight.data.copy_(torch.from_numpy(pre_en_emb_matrix))\n\n self.dropout = nn.Dropout(dropout_p)\n # self.attn = nn.Linear(hidden_size, self.max_len)\n self.attn = Attn(hidden_size)\n self.gru = nn.GRU(emb_size + 2*hidden_size, hidden_size, n_layers, batch_first=True, dropout=dropout_p, bidirectional = self.bidirectional) #Multiply 2 here since the encoder is bidirestional\n self.out = nn.Linear((self.bidirectional +1)*hidden_size, output_size)\n\n def forward(self, word_input, last_hidden, encoder_outputs):\n # Note that we will only be running forward for a single decoder time step, but will use all encoder outputs\n\n # Get the embedding of the current input word (last output word)\n #print('wi size:{}'.format(word_input.size()))\n word_embedded = self.embedding(word_input).view(1, word_input.size()[0], -1) # S=1 x B x N\n word_embedded = self.dropout(word_embedded)\n attn_weights = self.attn(last_hidden[-1], encoder_outputs )\n # print('wt size:{}, eo size:{}'.format(attn_weights.size(), encoder_outputs.size()))\n # attn_applied = attn_weights.bmm(encoder_outputs.unsqueeze(0))\n attn_applied = attn_weights.bmm(encoder_outputs)# (B,1,V)\n attn_applied = attn_applied.transpose(0, 1)\n # print('we size:{}, lh size:{}, aa size:{}'.format(word_embedded.size(), last_hidden.size(), attn_applied.size()))\n rnn_input = torch.cat((word_embedded, attn_applied), 2)\n rnn_input = rnn_input.transpose(0, 1)\n #print('rnn_input shape ', rnn_input.shape)\n output, hidden = self.gru(rnn_input, last_hidden)\n\n # Final output layer\n output = output.squeeze(1) # B x N\n #print('output of rnn shape ', output.size())\n output = F.log_softmax(self.out(output))\n\n # Return final output, hidden state, and attention weights (for visualization)\n return output.to(device), hidden.to(device), attn_weights.to(device)\n","sub_path":"Enc_Attn_Dec/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"91465949","text":"from framework.similarity.similarityterms import SimilarityTerms\nfrom framework.similarity.basesimilarity import BaseSimilarity\nimport numpy as np\nimport pandas as pd\nimport math\n\nclass ResourceUsageSimilarity(BaseSimilarity):\n '''\n\n '''\n def __init__(self, data_descriptor, data_window= None,**kwargs):\n super().__init__(SimilarityTerms.USAGE,data_descriptor, data_window)\n self.kwargs = kwargs\n\n def get_information_loss(self, data_originally, data_sanitized, **kwargs):\n stat_gt = self.get_statistics(data_originally)\n stat_sanitized = self.get_statistics(data_sanitized)\n df = stat_gt - stat_sanitized\n df = df.as_matrix()\n err_sum_sqrt = np.mean(np.absolute(df))\n return err_sum_sqrt\n\n def get_statistics_distance(self, sample1, sample2, **kwargs):\n if self.data_descriptor.data_window_size is None:\n if self.data_window is None:\n stat1 = self.compute_total_usage(sample1,kwargs[\"index\"])\n stat2 = self.compute_total_usage(sample2,kwargs[\"index\"])\n else:\n stat1 = self.compute_window_usage(sample1,kwargs[\"index\"], self.data_window)\n stat2 = self.compute_window_usage(sample2,kwargs[\"index\"], self.data_window)\n else:\n stat1 = self.compute_use_data_window_size(sample1,kwargs[\"index\"],self.data_window,self.data_descriptor.data_window_size)\n stat2 = self.compute_use_data_window_size(sample2,kwargs[\"index\"],self.data_window,self.data_descriptor.data_window_size)\n dist = stat1 - stat2\n return dist\n\n def get_statistics(self,data):\n if self.data_window is None:\n stat = self.get_use(data)\n else:\n stat = self.get_window_use(data, self.data_window)\n return stat\n\n def get_use(self,data):\n use_data = data.apply(self.compute_total_usage, axis=1,index=data.columns).to_frame()\n return use_data\n\n def get_window_use(self,data, data_window):\n use_data = data.apply(self.compute_window_usage, axis=1,index=data.columns,window=data_window).to_frame()\n return use_data\n\n def compute_total_usage(self,x,index):\n time_resolution = len(index)\n if isinstance(x,pd.DataFrame):\n x = list(x)\n usage = sum(x) * time_resolution\n return usage\n\n def compute_window_usage(self,x,index,window):\n # time_resolution = index[1]-index[0]\n if isinstance(x,pd.DataFrame):\n x = list(x)\n usage = sum(x[window[0]:window[1]]) #* time_resolution\n return usage\n\n def get_distance(self,data):\n data_copy = data.copy()\n data_copy = data_copy.fillna(0)\n data_copy = data_copy.as_matrix()\n data_size = data_copy.shape[0]\n distance = np.empty((data_size,data_size))\n cols = data.columns\n for i in range(data_size):\n df1 = data_copy[i, :]\n for j in range(data_size):\n df2 = data_copy[j,:]\n if i > j:\n distance[i,j] = distance[j,i]\n continue\n elif i == j:\n distance[i,j] = 0\n continue\n else:\n distance[i,j] = self.get_statistics_distance(df1,df2,index=cols)\n return super().compute_distance(distance,data.index)\n\n def compute_use_data_window_size(self,x,index, window,data_window_size):\n amount_of_colums = x.size\n amount_of_slices = math.floor(amount_of_colums/data_window_size)\n df = None\n for i in range(0,amount_of_slices):\n data_slice = x[data_window_size*i:data_window_size*(i+1)]\n if window is None:\n restult =self.compute_total_usage(data_slice,index)\n else:\n restult =self.compute_window_usage(data_slice,index,window)\n if df is not None:\n df = np.append(df,restult)\n else:\n df = np.array(restult)\n return df","sub_path":"framework/similarity/resourceusagesimilarity.py","file_name":"resourceusagesimilarity.py","file_ext":"py","file_size_in_byte":4038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"153332249","text":"#!/usr/bin/env python3\n\"\"\"\nCalculates id% and cov% for all last hits.\nAdds columns for end coordinate and for positive strand coordinates for Query.\n\"\"\"\n\n__author__ = \"Harald Grove\"\n__version__ = \"0.1.0\"\n__license__ = \"MIT\"\n\nimport argparse\nimport time\nimport sys\nimport pandas as pd\n\n\nclass Last(object):\n\n def __init__(self, lastfile):\n self.lastfile = lastfile\n self.lines = []\n self.header = []\n\n def _calc_seqid(self, score, blocks):\n \"\"\"\n Calculates the sequence identity from the alignment\n \"\"\"\n alnSize = 0\n gaps = 0\n gapSize = 0\n for b in blocks.split(\",\"):\n if \":\" in b:\n gap = max([int(a) for a in b.split(\":\")])\n gaps += gap\n gapSize += 21 + 9 * gap\n else:\n alnSize += int(b)\n mismatch = ((alnSize * 6 - gapSize) - score) / 24\n return 1 - (mismatch + gaps) / (gaps + alnSize)\n\n def read_last(self, idlim=0, covlim=0, lenlim=0):\n \"\"\"\n Reads each alignment from the last-alignment file.\n Calculates and adds sequence identity and coverage.\n :param idlim: Minimum identity, in percent\n :param covlim: Minimum coverage, in percent\n :param lenlim: Minimum alignment length\n \"\"\"\n head = True\n with open(self.lastfile, \"r\") as fin:\n for line in fin:\n # Add all comment lines at start of file to 'header'\n if line.startswith(\"#\"):\n if head:\n self.header.append(line)\n continue\n head = False\n l = line.strip().split()\n if len(l) != 14:\n continue\n score, start1, alnSize1, seqSize1, start2, alnSize2, seqSize2 = [\n int(i) for i in [l[0], l[2], l[3], l[5], l[7], l[8], l[10]]\n ]\n name1, strand1, name2, strand2, blocks, *e = [\n l[1], l[4], l[6], l[9], l[11], l[12:]\n ]\n end1 = start1 + alnSize1\n end2 = start2 + alnSize2\n if strand2 == \"-\":\n start2p = seqSize2 - end2\n end2p = seqSize2 - start2\n else:\n start2p = start2\n end2p = end2\n seqid = 100 * self._calc_seqid(score, blocks)\n if seqSize2 <= seqSize1:\n seqcov = 100 * (alnSize2 / seqSize2)\n else:\n seqcov = 100 * (alnSize1 / seqSize1)\n # Deciding whether to keep the alignment or not\n if seqid < idlim:\n continue\n if alnSize2 < lenlim:\n continue\n if seqcov < covlim:\n continue\n self.lines.append(\n [ score, seqid, seqcov, name1, start1, alnSize1, end1, strand1, seqSize1,\n name2, start2, alnSize2, end2, strand2, seqSize2, blocks,\n start2p, end2p ]\n )\n\n def write_last(self, fout=sys.stdout):\n for line in self.header:\n l = line.strip().split()\n if len(l) > 1 and l[1] == \"score\":\n l.insert(2, \"idpct\")\n l.insert(3, \"covpct\")\n l.insert(7, \"end1\")\n l.insert(13, \"end2\")\n l.append(\"start2+\")\n l.append(\"end2+\")\n else:\n continue\n line = \"{}\\n\".format(\"\\t\".join(l[1:]))\n fout.write(line)\n for line in self.lines:\n output = \"\\t\".join([str(b) for b in line])\n fout.write(\"{}\\n\".format(output))\n\n\ndef main(args):\n last = Last(args.infile)\n idlim, covlim, lenlim = [int(a) for a in args.limits.split(\",\")]\n last.read_last(idlim=idlim, covlim=covlim, lenlim=lenlim)\n if args.outfile is not None:\n last.write_last(open(args.outfile, \"w\"))\n else:\n last.write_last()\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n\n # Required positional argument\n parser.add_argument(\"infile\", help=\"Last alignment file\")\n\n # Optional argument which requires a parameter (eg. -d test)\n parser.add_argument(\"-o\", \"--outfile\", help=\"Output, parsed last alignment.\")\n parser.add_argument(\n \"-c\", \"--limits\", default=\"0,0,0\", help=\"Minimum idpct, covpct and length\"\n )\n # parser.add_argument(\"-n\", \"--name\", action=\"store\", dest=\"name\")\n\n # Optional verbosity counter (eg. -v, -vv, -vvv, etc.)\n parser.add_argument(\n \"-v\", \"--verbose\", action=\"count\", default=0, help=\"Verbosity (-v, -vv, etc)\"\n )\n\n # Specify output of '--version'\n parser.add_argument(\n \"--version\",\n action=\"version\",\n version=\"%(prog)s (version {version})\".format(version=__version__),\n )\n\n args = parser.parse_args()\n main(args)\n","sub_path":"scripts/parseLast.py","file_name":"parseLast.py","file_ext":"py","file_size_in_byte":4986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"61108678","text":"\"\"\"Model.\"\"\"\nimport os\n\nfrom keras import optimizers\nfrom keras.applications.vgg16 import VGG16\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.datasets import cifar10\nfrom keras.layers import Dense\nfrom keras.models import Model\nfrom keras.models import load_model\nimport keras.backend as K\n\nfrom custom_layer_test import CompressedPrototype, get_new_weights\n\n\nDEBUG = True\n\ndef insert_layer_factory(layer):\n old_weights = layer.get_weights()\n new_weights = get_new_weights(old_weights)\n print(\"layer.units and output_dim: {} {}\"\n .format(layer.units, K.int_shape(layer.output)[1]))\n new_layer = CompressedPrototype(layer.units, weights=new_weights)\n # new_layer.set_weights(new_weights)\n return new_layer\n\n\ndef get_data():\n # data\n (x_train, t_train), (x_test, t_test) = cifar10.load_data()\n x_train = x_train.astype('float32') / 255.0\n x_test = x_test.astype('float32') / 255.0\n t_train = t_train.flatten()\n t_test = t_test.flatten()\n return (x_train, t_train), (x_test, t_test)\n\n\ndef get_model(train_data, hidden_units=1024, output_units=10):\n \"\"\"Create a model.\n \"\"\"\n x_train, t_train = train_data\n\n filepath = \"cifar10_vgg16\"\n if os.path.exists(filepath):\n model = load_model(filepath)\n return model\n\n # model\n base_model = VGG16(weights='imagenet',\n include_top=False,\n pooling='avg')\n h = base_model.output\n h = Dense(hidden_units, activation='relu')(h)\n y = Dense(output_units, activation='softmax')(h)\n model = Model(inputs=base_model.input, outputs=y)\n\n # trainable variables\n for layer in base_model.layers:\n layer.trainable = False\n\n # loss and optimizer\n model.compile(loss='sparse_categorical_crossentropy',\n optimizer=optimizers.SGD(lr=0.01),\n metrics=['accuracy'])\n\n callbacks = [ModelCheckpoint(filepath, save_best_only=True)]\n # training\n model.fit(x_train, t_train, epochs=5, batch_size=64, callbacks=callbacks)\n model.save(filepath)\n return model\n\n\ndef modifier(model):\n # prev_out = model.input\n # for layer in model.layers:\n # if isinstance(layer, Dense):\n # print(layer)\n # new_layer = CompressedPrototype(layer.units) \n # for x in layer.input:\n # xA = new_layer(x)\n\n # return model\n # Auxiliary dictionary to describe the network graph\n network_dict = {'input_layers_of': {}, 'new_output_tensor_of': {}}\n\n # Set the input layers of each layer\n for layer in model.layers:\n for node in layer._outbound_nodes:\n layer_name = node.outbound_layer.name\n if layer_name not in network_dict['input_layers_of']:\n network_dict['input_layers_of'].update(\n {layer_name: [layer.name]})\n else:\n network_dict['input_layers_of'][layer_name].append(layer.name)\n\n # Set the output tensor of the input layer\n network_dict['new_output_tensor_of'].update(\n {model.layers[0].name: model.input})\n\n # Iterate over all layers after the input\n for layer in model.layers[1:]:\n\n # Determine input tensors\n layer_input = [network_dict['new_output_tensor_of'][layer_aux]\n for layer_aux in network_dict['input_layers_of'][layer.name]]\n if len(layer_input) == 1:\n layer_input = layer_input[0]\n\n # Insert layer if name matches the regular expression\n if isinstance(layer, Dense):\n x = layer_input\n\n new_layer = insert_layer_factory(layer)\n new_layer.name = layer.name\n x = new_layer(x)\n print('Layer {} inserted after layer {}'.format(new_layer.name,\n layer.name))\n else:\n x = layer(layer_input)\n\n network_dict['new_output_tensor_of'].update({layer.name: x})\n\n return Model(inputs=model.inputs, outputs=x)\n\n\ndef run(get_data, get_model, modifier):\n \"\"\"Run the experiment. This consists of getting the data, creating\n the model (including training) and evaluating the results.\n\n \"\"\"\n train_data, test_data = get_data()\n model = get_model(train_data)\n model = modifier(model)\n print(type(test_data[0]))\n if isinstance(test_data, tuple):\n # spped up\n if DEBUG: test_data = map(lambda t: t[:10], test_data)\n result = model.evaluate(*test_data)\n else:\n msg = 'The test data is of type which can not be' + \\\n ' handeled by the current implementation.'\n raise NotImplementedError(msg)\n return result\n\n\nprint('Results: {}'.format(run(get_data, get_model, modifier)))\n\n# train, val, test = get_data()\n# model = get_model()\n# model.fit(train, val)\n# if modifier:\n# model = modifier(model)\n# results = model.evaluate(data)\n# save(results, model)\n# # later\n# data = analyse(results, model)\n# write_latex_table(data)\n\n# OOR\n\n# train, val, test = get_generators()\n# model = get_model()\n# model.fit_generator(train, val)\n# model.eval_generator(test)\n","sub_path":"src/qiita.py","file_name":"qiita.py","file_ext":"py","file_size_in_byte":5115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"205515148","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nfrom math import cos, sin, pi\n\nVEL = 5.0\nKI = 0\nKII = 0\nHEIGHT = 20\nANGLE = 56\nMASS = 1\n#-------------\nHSIZE = HEIGHT * 2\nWSIZE = VEL * 3\nGV = 9.80666\n\nclass dot(object):\n def __init__(self, h, v, angle, m):\n self.x = 0.0\n self.y = h\n self.velx = v * cos(angle * pi / 180)\n self.vely = v * sin(angle * pi / 180)\n self.accx = 0.0\n self.accy = GV\n self.tau = 0.0\n self.mass = m\n\n def move(self):\n self.x = self.x + self.velx * self.tau + (self.accx * self.tau**2)/2\n self.y = self.y + self.vely * self.tau + (self.accy * self.tau**2)/2\n self.velx = self.velx + self.accx * self.tau\n self.vely = self.vely + self.accy * self.tau\n self.accx = -(KI * self.velx + KII * self.velx**2) / self.mass\n self.accy = -(self.mass * GV - KI * self.vely - KII * self.vely**2) / self.mass\n\n def str(self):\n return f\"xy: ({self.x}, {self.y}), vel: ({self.velx}, {self.vely}), acc: ({self.accx}, {self.accy}), tau: {self.tau}, m: {self.mass}\"\n\ndef animate(i):\n if (dot.y > 0.0):\n dot.tau += 0.0001\n dot.move()\n\n d.set_data(dot.x, dot.y)\n\ndot = dot(HEIGHT, VEL, ANGLE, MASS)\nfig = plt.figure()\nax = plt.axes(xlim = (0, WSIZE), ylim = (0, HSIZE))\nd, = ax.plot(dot.x, dot.y, 'bo')\n\nanim = animation.FuncAnimation(fig, animate, frames = 120, interval = 20)\nplt.show()","sub_path":"mdl/mdl_horizont.py","file_name":"mdl_horizont.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"202262268","text":"\n\n\"\"\"\nFind Excel column name from a given column number\n\nMS Excel columns has a pattern like A, B, C, … ,Z, AA, AB, AC,…. ,AZ, BA, BB, … ZZ, AAA, AAB ….. etc.\nIn other words, column 1 is named as “A”, column 2 as “B”, column 27 as “AA”.\n\nGiven a column number, find its corresponding Excel column name. Following are more examples.\n\nInput Output\n 26 Z\n 51 AY\n 52 AZ\n 80 CB\n 676 YZ\n 702 ZZ\n 705 AAC\n\n\"\"\"\n\n\ndef find_cname(k):\n if not k :\n return\n else :\n\n res = ['0']*50\n if k <= 26 :\n return chr(ord('a')+k-1)\n i = 0\n while k > 0 :\n rem = k%26\n if rem == 0 :\n res[i] = 'z'\n k = k//26 -1\n else :\n res[i] = chr(ord('a')+rem-1)\n k = k//26\n i += 1\n result = res[:i]\n result.reverse()\n return ''.join(result)\n \nif __name__=='__main__':\n test = [25,26,51,52,80,676,702,705]\n for num in test :\n print(find_cname(num))","sub_path":"GeeksForGeeks/Strings/FindExcelColumnName.py","file_name":"FindExcelColumnName.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"579201447","text":"def question_9(limit):\n for b in range(limit // 2):\n for a in range(b):\n c = limit - b - a\n if a ** 2 + b ** 2 == c ** 2:\n return a * b * c\n return None\n\n\nif __name__ == '__main__':\n print(question_9(1000))\n","sub_path":"#9.py","file_name":"#9.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"98130415","text":"import tensorflow as tf\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL']='2' # 去除警告\n\n\"\"\"\n写入example\n\"\"\"\n# 定义cifar的目录, 命令行方式\nFLAGS = tf.app.flags.FLAGS\ntf.app.flags.DEFINE_string(\"cifar_dir\", \"/Users/saicao/Desktop/stu_data/tf_binary/cifar-10-batches-bin/\", \"文件目录\")\n# 指定的是文件\ntf.app.flags.DEFINE_string(\"cifar_tfrecords\", \"/Users/saicao/Desktop/stu_data/tf_records/cifar.tfrecords\", \"存入tfrecords的文件目录\")\n\nclass CifarRead(object):\n \"\"\"\n 读取二进制文件, 写入tfrecords, 读取tfrecords\n \"\"\"\n def __init__(self, filelist):\n # 文件列表\n self.filelist = filelist\n\n # 定义读取的图片的一些属性\n self.height = 32\n self.width = 32\n self.channel = 3\n self.label_bytes = 1\n self.image_bytes = self.height * self.width * self.channel\n self.bytes = self.label_bytes + self.image_bytes\n\n def read_and_decode(self):\n \"\"\"\n 读取二进制文件转换成张量\n :return:\n \"\"\"\n # 1、构造文件队列\n file_queue = tf.train.string_input_producer(self.filelist)\n\n # 2、构造二进制文件读取器, 读取内容\n reader = tf.FixedLengthRecordReader(self.bytes) # 参数: 每个样本的字节数\n\n key, value = reader.read(file_queue)\n\n # 3、解码内容\n label_image = tf.decode_raw(value, tf.uint8) # 返回值: 标签 + 特征值\n\n # 4、分割出图片和标签数据, 切除特征值和目标值\n label = tf.cast(tf.slice(label_image, [0], [self.label_bytes]), tf.int32)\n image = tf.slice(label_image, [self.label_bytes], [self.image_bytes])\n print(label, image)\n\n # 5、可以对图片的特征数据进行形状改变 [3072] -> [32, 32, 3]\n image_reshape = tf.reshape(image, [self.height, self.width, self.channel])\n\n print(label, image_reshape)\n\n # 6、批处理数据\n image_batch, label_batch = tf.train.batch([image_reshape, label], batch_size=10, num_threads=1, capacity=10)\n\n print(image_batch, label_batch)\n\n return image_batch, label_batch\n\n\n def write_to_tfrecords(self, image_batch, label_batch):\n \"\"\"\n 将图片的特征值和目标值存入tfrecords\n :param image_batch: 10张图片的特征值\n :param label_batch: 10张图片的目标值\n :return: None\n \"\"\"\n # 1、建立TFrecords\n writer = tf.python_io.TFRecordWriter(FLAGS.cifar_tfrecords)\n\n # 2、循环将所有样本写入文件, 每张图片样本都要构造example协议\n # eval必须在session里面运行\n for i in range(10):\n # 取出第i个图片数据的特征值和目标值\n image = image_batch[i].eval().tostring()\n label = int(label_batch[i].eval()[0])\n\n # 构造一个样本的example\n example = tf.train.Example(features=tf.train.Features(feature={\n \"image\": tf.train.Feature(bytes_list=tf.train.BytesList(value=[image])),\n \"label\": tf.train.Feature(int64_list=tf.train.Int64List(value=[label]))\n }))\n\n # 写入单独的样本\n writer.write(example.SerializeToString())\n\n # 关闭资源\n writer.close()\n return None\n\nif __name__ == '__main__':\n # 1、找到文件放入列表, 路径+名字 -> 列表\n file_name = os.listdir(FLAGS.cifar_dir)\n filelist = [os.path.join(FLAGS.cifar_dir, file) for file in file_name if file[-3:] == \"bin\"]\n\n cf = CifarRead(filelist)\n image_batch, label_batch = cf.read_and_decode()\n\n with tf.Session() as sess:\n\n sess.run(tf.global_variables_initializer())\n sess.run(tf.local_variables_initializer())\n\n # 定义一个线程协调器 (主线程开启)\n coord = tf.train.Coordinator()\n # 开启读文件的线程, 不开启无法执行上述方法中定义的操作\n threads = tf.train.start_queue_runners(sess, coord=coord)\n\n # 存入tfrecords文件\n print(\"开始存储\")\n\n cf.write_to_tfrecords(image_batch, label_batch) # 里面有eval, 必须在session里面运行\n\n print(\"结束存储\")\n\n # 打印读取的内容\n # print(sess.run([image_batch, label_batch]))\n\n # 回收子线程\n coord.request_stop()\n coord.join(threads)\n","sub_path":"deep_learning/binary_read_tfrecords.py","file_name":"binary_read_tfrecords.py","file_ext":"py","file_size_in_byte":4392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"2055026","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\n\nfrom aiida.cmdline.verdilib import Code\n\nfrom ._input_helper import InputHelper\nfrom .contextmanagers import redirect_stdin, redirect_stdout\n\ndef setup_code(\n label,\n description,\n default_plugin,\n remote_computer,\n remote_abspath,\n local=False,\n prepend_text='',\n append_text=''\n):\n code_input = InputHelper(input=\n [\n label,\n description,\n str(local),\n default_plugin,\n remote_computer,\n remote_abspath\n ] + prepend_text.splitlines() + [None] +\n append_text.splitlines() + [None]\n )\n with open(os.devnull, 'w') as devnull, redirect_stdout(devnull):\n with redirect_stdin(code_input):\n Code().code_setup()\n","sub_path":"aiida_pytest/_code.py","file_name":"_code.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"248645024","text":"\"\"\"Util functions for rating process.\"\"\"\nimport unicodedata\nimport datetime\nfrom datetime import timedelta\nimport os\nfrom os import urandom\n\nfrom integrations.s3.utils.helpers import download_file\nfrom config.settings.base import AWS_ANALYTICAL_MEDIA_LOCATION\nfrom upload.models import AnalyticalDocument\n\nfrom .models.insider_link import RatingDecisionInsiderLink\nfrom .const import (\n ISSUER_EMAIL,\n ISSUER_HEADER,\n ISSUER_EMAIL_HEADER_PASSWORD,\n ISSUER_EMAIL_BODY_PASSWORD\n)\n\nimport PyPDF2\n\nfrom a_helper.mail.tasks import send_email\nfrom a_helper.other.tasks import delete_files_task\n\n\ndef get_public_report(rating_decision_obj):\n \"\"\"Get document reference for external analysis. This is the document\n used internally and sent to the issuer.\n\n :param RatingDecision: rating decision object\n :returns: AnalyticalDocument object\n \"\"\"\n\n return AnalyticalDocument.objects.get(\n issuer=rating_decision_obj.issuer,\n rating_decision=rating_decision_obj,\n document_type__id=10)\n\n\ndef get_public_external_report(rating_decision_obj):\n \"\"\"Get document reference for external analysis. This is the document\n that will be published externally.\n\n :param RatingDecision: rating decision object\n :returns: AnalyticalDocument object\n \"\"\"\n\n return AnalyticalDocument.objects.get(\n issuer=rating_decision_obj.issuer,\n rating_decision=rating_decision_obj,\n document_type__id=15)\n\n\ndef send_public_report(rating_decision_obj):\n \"\"\"\n Download public report from AWS S3 and send to issuer.\n\n :param RatingDecision: rating decision object\n \"\"\"\n target_file = None\n\n # Send this file to the issuer\n # Fetch uploaded files from AWS S3\n document = get_public_report(rating_decision_obj)\n\n try:\n legal_name = rating_decision_obj.issuer.legal_name\n legal_name = str(unicodedata.normalize(\n 'NFKD',\n legal_name).encode('ASCII',\n 'ignore').decode('utf-8'))\n\n target_file = (\n legal_name +\n ' draft report' +\n ' (' + datetime.datetime.today().strftime(\n '%Y-%m-%d, %H%M') + \").pdf\"\n )\n\n filepath = AWS_ANALYTICAL_MEDIA_LOCATION + '/' + str(\n document.upload)\n\n download_file(filepath, target_file)\n\n # Password protect file\n path, filename = os.path.split(target_file)\n output_file = os.path.join(path, \"temp_\" + filename)\n output = PyPDF2.PdfFileWriter()\n input_stream = PyPDF2.PdfFileReader(open(target_file, \"rb\"))\n\n for i in range(0, input_stream.getNumPages()):\n output.addPage(input_stream.getPage(i))\n\n outputStream = open(output_file, \"wb\")\n\n user_password = urandom(16).hex()[:5]\n\n # Set user and owner password to pdf file\n output.encrypt(user_pwd=user_password,\n owner_pwd='owner_pass',\n use_128bit=True)\n output.write(outputStream)\n outputStream.close()\n\n # Rename temporary output file with original filename, this\n # will automatically delete temporary file\n os.rename(output_file, target_file)\n\n attachments = [] # start with an empty list\n\n # add the attachment to the list\n attachments.append(target_file)\n\n contact_list = list(RatingDecisionInsiderLink.objects.filter(\n rating_decision=rating_decision_obj\n ))\n\n to_list = []\n for row in contact_list:\n to_list.append(row.insider.email)\n\n # Send email with link to admin control to editor\n send_email.delay(\n header=ISSUER_HEADER,\n body=ISSUER_EMAIL % (\n rating_decision_obj.issuer.analyst.primary_analyst.\n first_name),\n to=to_list,\n from_sender=None,\n cc=rating_decision_obj.issuer.analyst.primary_analyst.\n email,\n attachments=attachments)\n\n # Send email with password to primary analyst\n send_email.delay(\n header=ISSUER_EMAIL_HEADER_PASSWORD,\n body=ISSUER_EMAIL_BODY_PASSWORD.format(\n target_file,\n user_password,\n rating_decision_obj.issuer.analyst.primary_analyst.\n first_name\n ),\n to=to_list,\n from_sender=None,\n cc=rating_decision_obj.issuer.analyst.primary_analyst.\n email,\n )\n\n # Delete file\n later = datetime.datetime.utcnow() + timedelta(minutes=10)\n files = [os.path.abspath(target_file)]\n delete_files_task.apply_async(files, eta=later)\n\n except AnalyticalDocument.DoesNotExist:\n pass\n\n\ndef value_lambda(internal_score_obj, subfactor, factor):\n \"\"\"Filter rating decision object without hitting the db.\"\"\"\n\n return getattr(list(filter(lambda i: i.subfactor.id == subfactor,\n internal_score_obj))[0], factor)\n\n\ndef generate_rating_dict(issuer_type_id, internal_score_obj, type, version=1):\n \"\"\"Create a json string representing a rating.\n\n :param issuer_type_id: integer representing the type of issuer\n :param internal_score_obj: django queryset\n :param type: decided or proposed\n :return: json with dating data\n \"\"\"\n\n try:\n BOOL_MAP = {\n True: 1,\n False: 0,\n }\n\n hl = internal_score_obj[0].assessment.highestlowest\n\n highest_lowest = {\n 'is_AAA': BOOL_MAP[hl.is_aaa],\n 'is_AA_plus': BOOL_MAP[hl.is_aa_plus],\n 'is_CCC': BOOL_MAP[hl.is_ccc],\n 'is_CC': BOOL_MAP[hl.is_cc],\n 'is_C': BOOL_MAP[hl.is_c],\n }\n\n except Exception:\n\n highest_lowest = {\n 'is_AAA': 0,\n 'is_AA_plus': 0,\n 'is_CCC': 0,\n 'is_CC': 0,\n 'is_C': 0\n }\n\n try:\n if value_lambda(internal_score_obj,\n 6,\n type + '_notch_adjustment') == -1:\n adjustment_liquidity = 'b-'\n else:\n adjustment_liquidity = 0\n except: # noqa E722\n adjustment_liquidity = 0\n\n if issuer_type_id == 1:\n\n # Make dict backwards compatible\n try:\n financial_risk_assessment = {\n 'financial_risk_assessment': {\n 'value': value_lambda(internal_score_obj,\n 5,\n type + '_score')\n }\n }\n except IndexError:\n financial_risk_assessment = {\n 'ratio_analysis': {\n 'value':\n value_lambda(internal_score_obj,\n 27,\n type + '_score')\n },\n 'risk_appetite': {\n 'value':\n value_lambda(internal_score_obj,\n 28,\n type + '_score')\n },\n }\n\n output = {\n 'rating_type': 'corporate',\n 'version': version,\n 'business_risk_assessment':\n {\n 'operating_environment': {\n 'value': value_lambda(internal_score_obj,\n 1,\n type + '_score'),\n },\n 'market_position': {\n 'value': value_lambda(internal_score_obj,\n 2,\n type + '_score')\n },\n 'operating_efficiency': {\n 'value': value_lambda(internal_score_obj,\n 3,\n type + '_score')\n },\n 'size_diversification': {\n 'value': value_lambda(internal_score_obj,\n 4,\n type + '_score')\n }\n },\n 'financial_risk_assessment': financial_risk_assessment,\n 'adjustment_factor': {\n 'liquidity': adjustment_liquidity,\n 'esg': value_lambda(internal_score_obj,\n 7,\n type + '_notch_adjustment'),\n 'peer_comparisons': value_lambda(internal_score_obj,\n 8,\n type + '_notch_adjustment')},\n 'support': {\n 'general': value_lambda(internal_score_obj,\n 9,\n type + '_notch_adjustment')},\n 'highest_lowest': highest_lowest,\n }\n\n elif issuer_type_id == 2:\n\n output = {\n 'rating_type': 'financial',\n 'operating_environment':\n {\n 'national_factors': {\n 'value': value_lambda(internal_score_obj,\n 12,\n type + '_score'),\n 'weight': value_lambda(internal_score_obj,\n 12,\n 'weight'),\n },\n 'regional_cross_border_sector_specific': {\n 'value': value_lambda(internal_score_obj,\n 13,\n type + '_score'),\n 'weight': value_lambda(internal_score_obj,\n 13,\n 'weight'),\n }\n },\n 'risk_appetite': {\n 'capital': {\n 'value': value_lambda(internal_score_obj,\n 14,\n type + '_score'),\n },\n 'funding_liquidity': {\n 'value': value_lambda(internal_score_obj,\n 15,\n type + '_score'),\n },\n 'risk_governance': {\n 'value': value_lambda(internal_score_obj,\n 16,\n type + '_score'),\n },\n 'credit_risk': {\n 'value': value_lambda(internal_score_obj,\n 17,\n type + '_score'),\n 'weight': value_lambda(internal_score_obj,\n 17,\n 'weight'),\n },\n 'market_risk': {\n 'value': value_lambda(internal_score_obj,\n 18,\n type + '_score'),\n 'weight': value_lambda(internal_score_obj,\n 18,\n 'weight'),\n },\n 'other_risk': {\n 'value': value_lambda(internal_score_obj,\n 19,\n type + '_score'),\n }},\n 'competitive_position': {\n 'market_position': {\n 'value': value_lambda(internal_score_obj,\n 20,\n type + '_score'),\n }, },\n 'performance_indicator': {\n 'earnings': {\n 'value': value_lambda(internal_score_obj,\n 21,\n type + '_score'),\n },\n 'loss_performance': {\n 'value': value_lambda(internal_score_obj,\n 22,\n type + '_score'),\n }},\n 'adjustment_factor': {\n 'transitions':\n value_lambda(internal_score_obj,\n 23,\n type + '_notch_adjustment'),\n 'borderline_assessments':\n value_lambda(internal_score_obj,\n 24,\n type + '_notch_adjustment'),\n 'peer_comparisons':\n value_lambda(internal_score_obj,\n 8,\n type + '_notch_adjustment'), },\n 'support': {\n 'ownership':\n value_lambda(internal_score_obj,\n 9,\n type + '_notch_adjustment'),\n 'material_credit_enhancement':\n value_lambda(internal_score_obj,\n 25,\n type + '_notch_adjustment'),\n 'rating_caps':\n value_lambda(internal_score_obj,\n 26,\n type + '_notch_adjustment'), },\n 'highest_lowest': highest_lowest,\n }\n\n elif issuer_type_id == 3:\n\n # Make dict backwards compatible\n try:\n financial_risk_assessment = {\n 'financial_risk_assessment': {\n 'value': value_lambda(internal_score_obj,\n 5,\n type + '_score')\n }\n }\n except IndexError:\n financial_risk_assessment = {\n 'ratio_analysis': {\n 'value':\n value_lambda(internal_score_obj,\n 27,\n type + '_score')\n },\n 'risk_appetite': {\n 'value':\n value_lambda(internal_score_obj,\n 28,\n type + '_score')\n },\n }\n\n output = {\n 'rating_type': 'corporate_re',\n 'version': version,\n 'business_risk_assessment':\n {\n 'operating_environment': {\n 'value': value_lambda(internal_score_obj,\n 1,\n type + '_score'),\n },\n 'market_position_size_diversification': {\n 'value': value_lambda(internal_score_obj,\n 10,\n type + '_score'),\n },\n 'operating_efficiency': {\n 'value': value_lambda(internal_score_obj,\n 3,\n type + '_score'),\n },\n 'portfolio_assessment': {\n 'value': value_lambda(internal_score_obj,\n 11,\n type + '_score'),\n }\n },\n 'financial_risk_assessment': financial_risk_assessment,\n 'adjustment_factor': {\n 'liquidity': adjustment_liquidity,\n 'esg': value_lambda(internal_score_obj,\n 7,\n type + '_notch_adjustment'),\n 'peer_comparisons': value_lambda(internal_score_obj,\n 8,\n type + '_notch_adjustment')},\n 'support': {\n 'general': value_lambda(internal_score_obj,\n 9,\n type + '_notch_adjustment')},\n 'highest_lowest': highest_lowest,\n }\n else:\n output = 'Not implemented'\n\n return output\n","sub_path":"ncr_website/rating_process/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":16715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"177710221","text":"from time import time\nimport pygame\n\nclass Runner():\n def __init__(self):\n self.last = []\n self.lastwarn = 0\n #Init for ability to play sound:\n pygame.init()\n \n def run(self, found):\n self.last.append(found)\n #Clip results to last 50 true/false detection results:\n self.last = self.last[-50:]\n if sum(self.last) > 40 and self.lastwarn + 30 < time():\n print('Oven finished!')\n pygame.mixer.music.load(\"ovenwarning.wav\")\n pygame.mixer.music.play()\n #Do not trigger again until 30s later or more...\n self.lastwarn = time()\n","sub_path":"AudioMonitor/oven2.py","file_name":"oven2.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"186398717","text":"#7568 덩치\n#20200723\n\ndef dung(n, L):\n for i in range(n):\n rank = 0\n my_w = L[i][0]\n my_h = L[i][1]\n\n for j in range(n):\n if i!=j:\n if (L[j][0]>my_w) and (L[j][1]>my_h):\n rank += 1\n\n print(rank+1, end=\" \")\n \n \n \n\n\nn = int(input())\nL = []\nfor i in range(n):\n w,h = input().split()\n w, h = int(w), int(h)\n\n L.append((w,h))\n\ndung(n, L)\n","sub_path":"7568_dung.py","file_name":"7568_dung.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"647428544","text":"import json\nimport os, sys\nimport shutil\nimport urllib.request\nimport zipfile\nimport pickle\n\nid = sys.argv[1]\nop = int(sys.argv[2])\n\nurllib.request.urlretrieve(\n 'http://terminal.c1games.com/api/game/replay/' + id, 'replay.zip')\n\nzip = zipfile.ZipFile('replay.zip')\nzip.extractall('replay')\nzip.close()\nos.remove('replay.zip')\n\npath = None\nfor root, dirs, files in os.walk('replay'):\n for file in files:\n if file.endswith('.replay'):\n path = os.path.join(root, file)\n\nTYPES_WALL = ['FF', 'EF', 'DF']\nTYPES_INFO = ['PI', 'EI', 'SI']\ndeploy_wall = []\ndeploy_info = []\n\nwith open(path, 'r') as f:\n for line in f:\n try:\n frame = json.loads(line)\n spawns = frame['events']['spawn']\n for spawn in spawns:\n [[x, y], t, i, p] = spawn\n if t == 6 or p != op:\n continue\n if op == 2:\n x = 27 - x\n y = 27 - y\n if t < 3: # wall\n deploy_wall.append((TYPES_WALL[t], [x, y]))\n else: # info\n deploy_info.append((TYPES_INFO[t-3], [x, y]))\n except:\n continue\n\nwith open('model/%s.model' % id, 'wb') as f:\n pickle.dump((deploy_wall, deploy_info), f)\n\nshutil.rmtree('replay')\n","sub_path":"C1GamesStarterKit-master/algos/sim-algo/fetch.py","file_name":"fetch.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"320412950","text":"from ..base import GenomeBase, GenomeMeta\nfrom ..base import ReadFileBase, ReadFileMeta\nfrom ..base import _float\nfrom ..util import empty\n\n#-------------------------------- Content Class --------------------------------#\n\nclass SNP(GenomeBase, metaclass = GenomeMeta,\n expand_fields = ('genotype', 'allele_A', 'allele_B',\n 'fwdDepthA', 'rvsDepthA', 'fwdDepthB', 'rvsDepthB',\n 'fraction'),\n type_assert = {\n 'fwdDepthA': int, 'rvsDepthA': int, # forward and reverse depth of allele A\n 'fwdDepthB': int, 'rvsDepthB': int, # forward and reverse depth of allele B\n 'fraction': _float, # fraction of a single locus\n }):\n def estimate_fraction(self, DepthA, DepthB):\n try:\n return {\n 'AA-ab': lambda a, b: b * 2 / (a + b),\n 'AB-aa': lambda a, b: (a-b) / (a + b),\n 'AA-bb': lambda a, b: b / (a + b),\n }[self.genotype.split(':')[0]](DepthA, DepthB)\n except ZeroDivisionError:\n return None\n\n @property\n def is_indel(self):\n return False\n\n @property\n def background_allele(self):\n return {\n 'AA-ab': 'a',\n 'AB-aa': '1b',\n 'AA-bb': '2a',\n }[self.genotype.split(':')[0]]\n\n @property\n def interested_allele(self):\n return {\n 'AA-ab': '1b',\n 'AB-aa': 'a',\n 'AA-bb': '2b',\n }[self.genotype.split(':')[0]]\n\n @property\n def depth(self):\n return self.depth_sum()\n\n def depth_of(self, allele):\n if allele == 'a':\n return self.depth_sum(which='deptha') - self.depth_sum(which='depthb')\n elif allele == '1b':\n return self.depth_sum(which='depthb') * 2\n elif allele == '2b':\n return self.depth_sum(which='depthb')\n elif allele == '2a':\n return self.depth_sum(which='deptha')\n else:\n raise ValueError(f'Invalid argument {allele} for allele. Usage: '\n 'self.depth_of(allele=self.interested_allele) or '\n 'self.depth_of(allele=self.background_allele)')\n\n def check_fraction(self, *, fmin=0, fmax=1):\n return fmin < self.fraction < fmax\n\n def check_depth(self, *, at_least):\n depthA = self.depth_sum('A')\n depthB = self.depth_sum('B')\n less = min(depthA, depthB)\n more = max(depthA, depthB)\n return (less > more / 50) and (less >= at_least)\n\n def get_regionID(self, region_size):\n return int(self.pos / region_size)\n\n def depth_sum(self, which='depth'):\n which = which if which in ('fwd', 'rvs', 'deptha', 'depthb', 'depth') else 'depth'\n return sum([getattr(self, a) for a in self._fields if which in a.lower()])\n\n#------------------------------- Read File Class -------------------------------#\n\nclass ReadSNP(ReadFileBase, metaclass = ReadFileMeta, content_class = SNP):\n pass\n","sub_path":"src/snp_based_method/snp.py","file_name":"snp.py","file_ext":"py","file_size_in_byte":3015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"430144701","text":"import codecs\nimport re\nimport pandas as pd\n\npath=\"D:\\\\google_review_data\\\\users.clean.json\\\\users.clean.json\"\n\nf=codecs.open(path,\"r\",encoding=\"UTF-8\")\n\nCount=0\ntemp=''\ndata=[]\nfor line in f:\n z=line.encode('ascii').decode('unicode-escape')\n z=z.replace(\"u'\",\"'\")\n z=z.replace('u\"',\"'\")\n z=z.replace('\", ',\"', \")\n Count+=1\n\n# Check for the consistency in the data like if the line end with last second character as \"}\" then its a complete line or else there are some Unnecessary line breaks in the data. If there are unnecessary line breaks in the data the code joins such lines by removing those breaks.\n # print(z)\n # if len(z)>1:\n # if z[-2]=='}':\n # temp=temp.strip('\\r\\n') + '' + z\n # # print(temp)\n # # z.write(temp,)\n # temp=\"\"\n # elif z[-2]!='}':\n # temp=temp+z.strip('\\r\\n')\n # print(temp)\n # if(z.find(\"rating\")>=0 and z.find(\"gPlusUserId\")>=0):\n # if Count==50000:\n # break\n\n#Here with the help of regular expression we extract the required data from the raw data file of users.\n\n if(z.find(\"gPlusUserId\")>=0):\n m = re.search(\"'userName': '(.+?)', 'jobs'\", z)\n\n r = re.search(\"'gPlusUserId': '(.+?)'}\", z)\n print(Count)\n try:\n\n output=m.group(1),r.group(1)\n data.append(output)\n except:\n print(z)\n\nusers = pd.DataFrame(data,columns =['UserName','gPlusUserId'])\n\n# \"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n# \"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n# Here we do inner join between the english reviews file and users data extracted. we perform the Inner join on gPlusUserId.\n# we do inner join so that we can get the data of only those users which are present in our sample review file (reviews.csv) Rest all the users whose gPLusUserId is not there in review file will be dropped.\n\nreview=pd.read_csv(\"ReviewEnglishOnly.csv\") #filtered file which has only english observations. filter with lang=='en'\ny=pd.merge(review,users,how='inner',on='gPlusUserId')\n# After performing the join we drop all the duplicate observations of gPlusUserId. by this we get the data of only distinct users repeated gPLusUserId are dropped.\ny=y.drop_duplicates(subset=[\"gPlusUserId\"])\ncolumns=['UserName','gPlusUserId']\ny[columns].to_csv(\"usersfinal.csv\")\n","sub_path":"Code Files/Users_cleaning1.py","file_name":"Users_cleaning1.py","file_ext":"py","file_size_in_byte":2598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"609102104","text":"# Copyright (c) 2016-present, Facebook, Inc.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport unittest\nfrom contextlib import contextmanager\nfrom pathlib import Path\nfrom typing import Generator, Optional\nfrom unittest.mock import MagicMock, call, patch\n\nfrom .. import configuration_monitor, watchman_subscriber\nfrom ..analysis_directory import AnalysisDirectory\nfrom ..commands import stop\nfrom ..commands.tests.command_test import mock_arguments, mock_configuration\n\n\nclass MonitorTest(unittest.TestCase):\n @patch(\"os.fork\")\n @patch(\"os.close\")\n @patch(\"sys.exit\")\n @patch.object(configuration_monitor.ConfigurationMonitor, \"_run\")\n def test_daemonize(\n self, run: MagicMock, _exit: MagicMock, _close: MagicMock, fork: MagicMock\n ) -> None:\n arguments = mock_arguments()\n configuration = mock_configuration()\n analysis_directory = AnalysisDirectory(\"/tmp\")\n project_root = \"/\"\n local_configuration_root = None\n # Ensure that run() only gets called from the child.\n fork.return_value = 1\n original_directory = \"/\"\n configuration_monitor.ConfigurationMonitor(\n arguments,\n configuration,\n analysis_directory,\n project_root,\n original_directory,\n local_configuration_root,\n ).daemonize()\n run.assert_not_called()\n fork.assert_has_calls([call()])\n\n fork.return_value = 0\n configuration_monitor.ConfigurationMonitor(\n arguments,\n configuration,\n analysis_directory,\n project_root,\n original_directory,\n local_configuration_root,\n ).daemonize()\n fork.assert_has_calls([call(), call()])\n run.assert_has_calls([call()])\n _exit.assert_has_calls([call(0)])\n\n run.side_effect = OSError\n configuration_monitor.ConfigurationMonitor(\n arguments,\n configuration,\n analysis_directory,\n project_root,\n original_directory,\n local_configuration_root,\n ).daemonize()\n _exit.assert_has_calls([call(0), call(1)])\n\n @patch(\"os.makedirs\")\n @patch.object(watchman_subscriber, \"acquire_lock\")\n def test_run(self, _lock: MagicMock, _makedirs: MagicMock) -> None:\n @contextmanager\n def yield_once(\n path: str, blocking: bool\n ) -> Generator[Optional[int], None, None]:\n yield\n\n _lock.side_effect = yield_once\n arguments = mock_arguments()\n configuration = mock_configuration()\n analysis_directory = AnalysisDirectory(\"/tmp\")\n project_root = \"/\"\n original_directory = \"/\"\n local_configuration_root = None\n try:\n import pywatchman\n\n with patch.object(pywatchman, \"client\") as pywatchman_client:\n pywatchman_client.side_effect = Exception\n with self.assertRaises(Exception):\n with patch(\"builtins.open\"):\n configuration_monitor.ConfigurationMonitor(\n arguments,\n configuration,\n analysis_directory,\n project_root,\n original_directory,\n local_configuration_root,\n )._run()\n except ImportError:\n pass\n\n @patch.object(stop, \"Stop\")\n def test_handle_response(self, stop_command: MagicMock) -> None:\n arguments = mock_arguments()\n configuration = mock_configuration()\n analysis_directory = AnalysisDirectory(\"/tmp\")\n project_root = \"/\"\n original_directory = \"/\"\n local_configuration_root = None\n monitor_instance = configuration_monitor.ConfigurationMonitor(\n arguments,\n configuration,\n analysis_directory,\n project_root,\n original_directory,\n local_configuration_root,\n )\n\n monitor_instance._project_root_path = Path(\"/ROOT/a/b\")\n monitor_instance._handle_response(\n {\"files\": [\"a/b/.pyre_configuration\"], \"root\": \"/ROOT\"}\n )\n stop_command.assert_called_once()\n\n # Don't consider a .pyre_configuration that is not at the project root.\n stop_command.reset_mock()\n monitor_instance._project_root_path = Path(\"/ROOT/a/b\")\n monitor_instance._handle_response(\n {\"files\": [\"a/b/c/d/.pyre_configuration\"], \"root\": \"/ROOT\"}\n )\n stop_command.assert_not_called()\n\n stop_command.reset_mock()\n monitor_instance._local_configuration_root = \"/ROOT/a/b/c\"\n monitor_instance._handle_response(\n {\"files\": [\"a/b/c/.pyre_configuration.local\"], \"root\": \"/ROOT\"}\n )\n stop_command.assert_called_once()\n\n stop_command.reset_mock()\n monitor_instance._local_configuration_root = \"/ROOT/a/b/c/foo\"\n monitor_instance._handle_response(\n {\"files\": [\"a/b/c/.pyre_configuration.local\"], \"root\": \"/ROOT\"}\n )\n stop_command.assert_not_called()\n\n stop_command.reset_mock()\n monitor_instance._local_configuration_root = \"/ROOT/a\"\n monitor_instance._handle_response(\n {\n \"files\": [\n \"a/b/.pyre_configuration.local\",\n \"c/d/.pyre_configuration.local\",\n \"c/a/b/c/.pyre_configuration.local\",\n ],\n \"root\": \"/ROOT\",\n }\n )\n stop_command.assert_not_called()\n\n @patch.object(\n configuration_monitor.ConfigurationMonitor, \"__init__\", return_value=None\n )\n @patch.object(watchman_subscriber.WatchmanSubscriber, \"_watchman_client\")\n def test_subscriptions(self, watchman_client: MagicMock, init: MagicMock) -> None:\n watchman_client.query.return_value = {\"roots\": [\"/a\", \"/b\"]}\n monitor = configuration_monitor.ConfigurationMonitor(\n MagicMock(), MagicMock(), MagicMock(), MagicMock(), MagicMock(), MagicMock()\n )\n monitor._project_root_path = Path(\"/b/project_two\")\n actual = monitor._subscriptions\n self.assertEqual(len(actual), 1)\n self.assertEqual(actual[0].root, \"/b\")\n self.assertEqual(actual[0].name, \"pyre_monitor_b\")\n\n monitor._project_root_path = Path(\"/a\")\n actual = monitor._subscriptions\n self.assertEqual(len(actual), 1)\n self.assertEqual(actual[0].root, \"/a\")\n self.assertEqual(actual[0].name, \"pyre_monitor_a\")\n\n monitor._project_root_path = Path(\"/c/\")\n actual = monitor._subscriptions\n self.assertEqual(len(actual), 0)\n","sub_path":"client/tests/configuration_monitor_test.py","file_name":"configuration_monitor_test.py","file_ext":"py","file_size_in_byte":6837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"150556296","text":"from typing import Callable, Any\n\nimport biorbd_casadi as biorbd\nfrom biorbd_casadi import (\n GeneralizedCoordinates,\n GeneralizedVelocity,\n GeneralizedTorque,\n GeneralizedAcceleration,\n)\nfrom casadi import SX, MX, vertcat, horzcat, norm_fro\nimport numpy as np\n\nfrom ..misc.utils import check_version\nfrom ..limits.path_conditions import Bounds\nfrom ..misc.mapping import BiMapping, BiMappingList\n\ncheck_version(biorbd, \"1.9.9\", \"1.10.0\")\n\n\ndef _dof_mapping(key, model, mapping: BiMapping = None) -> dict:\n if key == \"q\":\n return _q_mapping(model, mapping)\n elif key == \"qdot\":\n return _qdot_mapping(model, mapping)\n elif key == \"qddot\":\n return _qddot_mapping(model, mapping)\n else:\n raise NotImplementedError(\"Wrong dof mapping\")\n\n\ndef _q_mapping(model, mapping: BiMapping = None) -> dict:\n \"\"\"\n This function returns a standard mapping for the q states if None\n and checks if the model has quaternions\n \"\"\"\n if mapping is None:\n mapping = {}\n if model.nb_quaternions > 0:\n if \"q\" in mapping and \"qdot\" not in mapping:\n raise RuntimeError(\n \"It is not possible to provide a q_mapping but not a qdot_mapping if the model have quaternion\"\n )\n elif \"q\" not in mapping and \"qdot\" in mapping:\n raise RuntimeError(\n \"It is not possible to provide a qdot_mapping but not a q_mapping if the model have quaternion\"\n )\n if \"q\" not in mapping:\n mapping[\"q\"] = BiMapping(range(model.nb_q), range(model.nb_q))\n return mapping\n\n\ndef _qdot_mapping(model, mapping: BiMapping = None) -> dict:\n \"\"\"\n This function returns a standard mapping for the qdot states if None\n and checks if the model has quaternions\n \"\"\"\n if mapping is None:\n mapping = {}\n if \"qdot\" not in mapping:\n mapping[\"qdot\"] = BiMapping(range(model.nb_qdot), range(model.nb_qdot))\n\n return mapping\n\n\ndef _qddot_mapping(model, mapping: BiMapping = None) -> dict:\n \"\"\"\n This function returns a standard mapping for the qddot states if None\n and checks if the model has quaternions\n \"\"\"\n if mapping is None:\n mapping = {}\n if \"qddot\" not in mapping:\n mapping[\"qddot\"] = BiMapping(range(model.nb_qddot), range(model.nb_qddot))\n\n return mapping\n\n\ndef bounds_from_ranges(model, key: str, mapping: BiMapping | BiMappingList = None) -> Bounds:\n \"\"\"\n Generate bounds from the ranges of the model\n\n Parameters\n ----------\n model: bio_model\n such as BiorbdModel or MultiBiorbdModel\n key: str | list[str, ...]\n The variables to generate the bounds from, such as \"q\", \"qdot\", \"qddot\", or [\"q\", \"qdot\"],\n mapping: BiMapping | BiMappingList\n The mapping to use to generate the bounds. If None, the default mapping is built\n\n Returns\n -------\n Bounds\n The bounds generated from the ranges of the model\n \"\"\"\n\n mapping_tp = _dof_mapping(key, model, mapping)[key]\n ranges = model.ranges_from_model(key)\n\n x_min = [ranges[i].min() for i in mapping_tp.to_first.map_idx]\n x_max = [ranges[i].max() for i in mapping_tp.to_first.map_idx]\n return Bounds(key, min_bound=x_min, max_bound=x_max)\n\n\nclass BiorbdModel:\n \"\"\"\n This class allows to define a biorbd model.\n \"\"\"\n\n def __init__(self, bio_model: str | biorbd.Model):\n if not isinstance(bio_model, str) and not isinstance(bio_model, biorbd.Model):\n raise ValueError(\"The model should be of type 'str' or 'biorbd.Model'\")\n\n self.model = biorbd.Model(bio_model) if isinstance(bio_model, str) else bio_model\n\n @property\n def path(self) -> str:\n return self.model.path().relativePath().to_string()\n\n def copy(self):\n return BiorbdModel(self.path)\n\n def serialize(self) -> tuple[Callable, dict]:\n return BiorbdModel, dict(bio_model=self.path)\n\n def set_gravity(self, new_gravity) -> None:\n self.model.setGravity(new_gravity)\n return\n\n @property\n def gravity(self) -> MX:\n return self.model.getGravity().to_mx()\n\n @property\n def nb_segments(self) -> int:\n return self.model.nbSegment()\n\n @property\n def nb_tau(self) -> int:\n return self.model.nbGeneralizedTorque()\n\n def segment_index(self, name) -> int:\n return biorbd.segment_index(self.model, name)\n\n @property\n def nb_quaternions(self) -> int:\n return self.model.nbQuat()\n\n @property\n def nb_q(self) -> int:\n return self.model.nbQ()\n\n @property\n def nb_qdot(self) -> int:\n return self.model.nbQdot()\n\n @property\n def nb_qddot(self) -> int:\n return self.model.nbQddot()\n\n @property\n def nb_root(self) -> int:\n return self.model.nbRoot()\n\n @property\n def segments(self) -> tuple[biorbd.Segment]:\n return self.model.segments()\n\n def homogeneous_matrices_in_global(self, q, reference_index, inverse=False):\n val = self.model.globalJCS(GeneralizedCoordinates(q), reference_index)\n if inverse:\n return val.transpose()\n else:\n return val\n\n def homogeneous_matrices_in_child(self, *args):\n return self.model.localJCS(*args)\n\n @property\n def mass(self) -> MX:\n return self.model.mass().to_mx()\n\n def center_of_mass(self, q) -> MX:\n q_biorbd = GeneralizedCoordinates(q)\n return self.model.CoM(q_biorbd, True).to_mx()\n\n def center_of_mass_velocity(self, q, qdot) -> MX:\n q_biorbd = GeneralizedCoordinates(q)\n qdot_biorbd = GeneralizedVelocity(qdot)\n return self.model.CoMdot(q_biorbd, qdot_biorbd, True).to_mx()\n\n def center_of_mass_acceleration(self, q, qdot, qddot) -> MX:\n q_biorbd = GeneralizedCoordinates(q)\n qdot_biorbd = GeneralizedVelocity(qdot)\n qddot_biorbd = GeneralizedAcceleration(qddot)\n return self.model.CoMddot(q_biorbd, qdot_biorbd, qddot_biorbd, True).to_mx()\n\n def mass_matrix(self, q) -> MX:\n q_biorbd = GeneralizedCoordinates(q)\n return self.model.massMatrix(q_biorbd).to_mx()\n\n def non_linear_effects(self, q, qdot) -> MX:\n q_biorbd = GeneralizedCoordinates(q)\n qdot_biorbd = GeneralizedVelocity(qdot)\n return self.model.NonLinearEffect(q_biorbd, qdot_biorbd).to_mx()\n\n def angular_momentum(self, q, qdot) -> MX:\n q_biorbd = GeneralizedCoordinates(q)\n qdot_biorbd = GeneralizedVelocity(qdot)\n return self.model.angularMomentum(q_biorbd, qdot_biorbd, True).to_mx()\n\n def reshape_qdot(self, q, qdot, k_stab=1) -> MX:\n return self.model.computeQdot(\n GeneralizedCoordinates(q),\n GeneralizedCoordinates(qdot), # mistake in biorbd\n k_stab,\n ).to_mx()\n\n def segment_angular_velocity(self, q, qdot, idx) -> MX:\n q_biorbd = GeneralizedCoordinates(q)\n qdot_biorbd = GeneralizedVelocity(qdot)\n return self.model.segmentAngularVelocity(q_biorbd, qdot_biorbd, idx, True).to_mx()\n\n @property\n def name_dof(self) -> tuple[str, ...]:\n return tuple(s.to_string() for s in self.model.nameDof())\n\n @property\n def contact_names(self) -> tuple[str, ...]:\n return tuple(s.to_string() for s in self.model.contactNames())\n\n @property\n def nb_soft_contacts(self) -> int:\n return self.model.nbSoftContacts()\n\n @property\n def soft_contact_names(self) -> tuple[str, ...]:\n return self.model.softContactNames()\n\n def soft_contact(self, soft_contact_index, *args):\n return self.model.softContact(soft_contact_index, *args)\n\n @property\n def muscle_names(self) -> tuple[str, ...]:\n return tuple(s.to_string() for s in self.model.muscleNames())\n\n @property\n def nb_muscles(self) -> int:\n return self.model.nbMuscles()\n\n def torque(self, tau_activations, q, qdot) -> MX:\n q_biorbd = GeneralizedCoordinates(q)\n qdot_biorbd = GeneralizedVelocity(qdot)\n return self.model.torque(tau_activations, q_biorbd, qdot_biorbd).to_mx()\n\n def forward_dynamics_free_floating_base(self, q, qdot, qddot_joints) -> MX:\n q_biorbd = GeneralizedCoordinates(q)\n qdot_biorbd = GeneralizedVelocity(qdot)\n qddot_joints_biorbd = GeneralizedAcceleration(qddot_joints)\n return self.model.ForwardDynamicsFreeFloatingBase(q_biorbd, qdot_biorbd, qddot_joints_biorbd).to_mx()\n\n @staticmethod\n def reorder_qddot_root_joints(qddot_root, qddot_joints) -> MX:\n return vertcat(qddot_root, qddot_joints)\n\n def forward_dynamics(self, q, qdot, tau, external_forces=None, f_contacts=None) -> MX:\n if external_forces is not None:\n external_forces = biorbd.to_spatial_vector(external_forces)\n\n q_biorbd = GeneralizedCoordinates(q)\n qdot_biorbd = GeneralizedVelocity(qdot)\n tau_biorbd = GeneralizedTorque(tau)\n return self.model.ForwardDynamics(q_biorbd, qdot_biorbd, tau_biorbd, external_forces, f_contacts).to_mx()\n\n def constrained_forward_dynamics(self, q, qdot, tau, external_forces=None) -> MX:\n if external_forces is not None:\n external_forces = biorbd.to_spatial_vector(external_forces)\n\n q_biorbd = GeneralizedCoordinates(q)\n qdot_biorbd = GeneralizedVelocity(qdot)\n tau_biorbd = GeneralizedTorque(tau)\n return self.model.ForwardDynamicsConstraintsDirect(q_biorbd, qdot_biorbd, tau_biorbd, external_forces).to_mx()\n\n def inverse_dynamics(self, q, qdot, qddot, external_forces=None, f_contacts=None) -> MX:\n if external_forces is not None:\n external_forces = biorbd.to_spatial_vector(external_forces)\n\n q_biorbd = GeneralizedCoordinates(q)\n qdot_biorbd = GeneralizedVelocity(qdot)\n qddot_biorbd = GeneralizedAcceleration(qddot)\n return self.model.InverseDynamics(q_biorbd, qdot_biorbd, qddot_biorbd, external_forces, f_contacts).to_mx()\n\n def contact_forces_from_constrained_forward_dynamics(self, q, qdot, tau, external_forces=None) -> MX:\n if external_forces is not None:\n external_forces = biorbd.to_spatial_vector(external_forces)\n\n q_biorbd = GeneralizedCoordinates(q)\n qdot_biorbd = GeneralizedVelocity(qdot)\n tau_biorbd = GeneralizedTorque(tau)\n return self.model.ContactForcesFromForwardDynamicsConstraintsDirect(\n q_biorbd, qdot_biorbd, tau_biorbd, external_forces\n ).to_mx()\n\n def qdot_from_impact(self, q, qdot_pre_impact) -> MX:\n q_biorbd = GeneralizedCoordinates(q)\n qdot_pre_impact_biorbd = GeneralizedVelocity(qdot_pre_impact)\n return self.model.ComputeConstraintImpulsesDirect(q_biorbd, qdot_pre_impact_biorbd).to_mx()\n\n def muscle_activation_dot(self, muscle_excitations) -> MX:\n muscle_states = self.model.stateSet()\n for k in range(self.model.nbMuscles()):\n muscle_states[k].setExcitation(muscle_excitations[k])\n return self.model.activationDot(muscle_states).to_mx()\n\n def muscle_length_jacobian(self, q) -> MX:\n q_biorbd = GeneralizedCoordinates(q)\n return self.model.musclesLengthJacobian(q_biorbd).to_mx()\n\n def muscle_velocity(self, q, qdot) -> MX:\n J = self.muscle_length_jacobian(q)\n return J @ qdot\n\n def muscle_joint_torque(self, activations, q, qdot) -> MX:\n muscles_states = self.model.stateSet()\n for k in range(self.model.nbMuscles()):\n muscles_states[k].setActivation(activations[k])\n q_biorbd = GeneralizedCoordinates(q)\n qdot_biorbd = GeneralizedVelocity(qdot)\n return self.model.muscularJointTorque(muscles_states, q_biorbd, qdot_biorbd).to_mx()\n\n def markers(self, q) -> list[MX]:\n return [m.to_mx() for m in self.model.markers(GeneralizedCoordinates(q))]\n\n @property\n def nb_markers(self) -> int:\n return self.model.nbMarkers()\n\n def marker_index(self, name):\n return biorbd.marker_index(self.model, name)\n\n def marker(self, q, index, reference_segment_index=None) -> MX:\n marker = self.model.marker(GeneralizedCoordinates(q), index)\n if reference_segment_index is not None:\n global_homogeneous_matrix = self.model.globalJCS(GeneralizedCoordinates(q), reference_segment_index)\n marker.applyRT(global_homogeneous_matrix.transpose())\n return marker.to_mx()\n\n @property\n def nb_rigid_contacts(self) -> int:\n \"\"\"\n Returns the number of rigid contacts.\n Example:\n First contact with axis YZ\n Second contact with axis Z\n nb_rigid_contacts = 2\n \"\"\"\n return self.model.nbRigidContacts()\n\n @property\n def nb_contacts(self) -> int:\n \"\"\"\n Returns the number of contact index.\n Example:\n First contact with axis YZ\n Second contact with axis Z\n nb_contacts = 3\n \"\"\"\n return self.model.nbContacts()\n\n def rigid_contact_index(self, contact_index) -> tuple:\n \"\"\"\n Returns the axis index of this specific rigid contact.\n Example:\n First contact with axis YZ\n Second contact with axis Z\n rigid_contact_index(0) = (1, 2)\n \"\"\"\n return self.model.rigidContactAxisIdx(contact_index)\n\n def marker_velocities(self, q, qdot, reference_index=None) -> list[MX]:\n if reference_index is None:\n return [\n m.to_mx()\n for m in self.model.markersVelocity(\n GeneralizedCoordinates(q),\n GeneralizedVelocity(qdot),\n True,\n )\n ]\n\n else:\n out = []\n homogeneous_matrix_transposed = self.homogeneous_matrices_in_global(\n GeneralizedCoordinates(q),\n reference_index,\n inverse=True,\n )\n for m in self.model.markersVelocity(GeneralizedCoordinates(q), GeneralizedVelocity(qdot)):\n if m.applyRT(homogeneous_matrix_transposed) is None:\n out.append(m.to_mx())\n\n return out\n\n def marker_accelerations(self, q, qdot, qddot, reference_index=None) -> list[MX]:\n if reference_index is None:\n return [\n m.to_mx()\n for m in self.model.markerAcceleration(\n GeneralizedCoordinates(q),\n GeneralizedVelocity(qdot),\n GeneralizedAcceleration(qddot),\n True,\n )\n ]\n\n else:\n out = []\n homogeneous_matrix_transposed = self.homogeneous_matrices_in_global(\n GeneralizedCoordinates(q),\n reference_index,\n inverse=True,\n )\n for m in self.model.markersAcceleration(\n GeneralizedCoordinates(q), GeneralizedVelocity(qdot), GeneralizedAcceleration(qddot)\n ):\n if m.applyRT(homogeneous_matrix_transposed) is None:\n out.append(m.to_mx())\n\n return out\n\n def tau_max(self, q, qdot) -> tuple[MX, MX]:\n self.model.closeActuator()\n q_biorbd = GeneralizedCoordinates(q)\n qdot_biorbd = GeneralizedVelocity(qdot)\n torque_max, torque_min = self.model.torqueMax(q_biorbd, qdot_biorbd)\n return torque_max.to_mx(), torque_min.to_mx()\n\n def rigid_contact_acceleration(self, q, qdot, qddot, contact_index, contact_axis) -> MX:\n q_biorbd = GeneralizedCoordinates(q)\n qdot_biorbd = GeneralizedVelocity(qdot)\n qddot_biorbd = GeneralizedAcceleration(qddot)\n return self.model.rigidContactAcceleration(q_biorbd, qdot_biorbd, qddot_biorbd, contact_index, True).to_mx()[\n contact_axis\n ]\n\n def markers_jacobian(self, q) -> list[MX]:\n return [m.to_mx() for m in self.model.markersJacobian(GeneralizedCoordinates(q))]\n\n @property\n def nb_dof(self) -> int:\n return self.model.nbDof()\n\n @property\n def marker_names(self) -> tuple[str, ...]:\n return tuple([s.to_string() for s in self.model.markerNames()])\n\n def soft_contact_forces(self, q, qdot) -> MX:\n q_biorbd = GeneralizedCoordinates(q)\n qdot_biorbd = GeneralizedVelocity(qdot)\n\n soft_contact_forces = MX.zeros(self.nb_soft_contacts * 6, 1)\n for i_sc in range(self.nb_soft_contacts):\n soft_contact = self.soft_contact(i_sc)\n\n soft_contact_forces[i_sc * 6 : (i_sc + 1) * 6, :] = (\n biorbd.SoftContactSphere(soft_contact).computeForceAtOrigin(self.model, q_biorbd, qdot_biorbd).to_mx()\n )\n\n return soft_contact_forces\n\n def reshape_fext_to_fcontact(self, fext: MX) -> biorbd.VecBiorbdVector:\n count = 0\n f_contact_vec = biorbd.VecBiorbdVector()\n for ii in range(self.nb_rigid_contacts):\n n_f_contact = len(self.model.rigidContactAxisIdx(ii))\n idx = [i + count for i in range(n_f_contact)]\n f_contact_vec.append(fext[idx])\n count = count + n_f_contact\n return f_contact_vec\n\n def normalize_state_quaternions(self, x: MX | SX) -> MX | SX:\n quat_idx = self.get_quaternion_idx()\n\n # Normalize quaternion, if needed\n for j in range(self.nb_quaternions):\n quaternion = vertcat(x[quat_idx[j][3]], x[quat_idx[j][0]], x[quat_idx[j][1]], x[quat_idx[j][2]])\n quaternion /= norm_fro(quaternion)\n x[quat_idx[j][0] : quat_idx[j][2] + 1] = quaternion[1:4]\n x[quat_idx[j][3]] = quaternion[0]\n\n return x\n\n def get_quaternion_idx(self) -> list[list[int]]:\n n_dof = 0\n quat_idx = []\n quat_number = 0\n for j in range(self.nb_segments):\n if self.segments[j].isRotationAQuaternion():\n quat_idx.append([n_dof, n_dof + 1, n_dof + 2, self.nb_dof + quat_number])\n quat_number += 1\n n_dof += self.segments[j].nbDof()\n return quat_idx\n\n def contact_forces(self, q, qdot, tau, external_forces: list = None) -> MX:\n if external_forces is not None and len(external_forces) != 0:\n all_forces = MX()\n for i, f_ext in enumerate(external_forces):\n force = self.contact_forces_from_constrained_forward_dynamics(q, qdot, tau, external_forces=f_ext)\n all_forces = horzcat(all_forces, force)\n return all_forces\n else:\n return self.contact_forces_from_constrained_forward_dynamics(q, qdot, tau, external_forces=None)\n\n def passive_joint_torque(self, q, qdot) -> MX:\n q_biorbd = GeneralizedCoordinates(q)\n qdot_biorbd = GeneralizedVelocity(qdot)\n return self.model.passiveJointTorque(q_biorbd, qdot_biorbd).to_mx()\n\n def ligament_joint_torque(self, q, qdot) -> MX:\n q_biorbd = GeneralizedCoordinates(q)\n qdot_biorbd = GeneralizedVelocity(qdot)\n return self.model.ligamentsJointTorque(q_biorbd, qdot_biorbd).to_mx()\n\n def ranges_from_model(self, variable: str):\n q_ranges = []\n qdot_ranges = []\n qddot_ranges = []\n\n for segment in self.segments:\n if variable == \"q\":\n q_ranges += [q_range for q_range in segment.QRanges()]\n elif variable == \"qdot\":\n qdot_ranges += [qdot_range for qdot_range in segment.QDotRanges()]\n elif variable == \"qddot\":\n qddot_ranges += [qddot_range for qddot_range in segment.QDDotRanges()]\n\n if variable == \"q\":\n return q_ranges\n elif variable == \"qdot\":\n return qdot_ranges\n elif variable == \"qddot\":\n return qddot_ranges\n else:\n raise RuntimeError(\"Wrong variable name\")\n\n def _q_mapping(self, mapping: BiMapping = None) -> dict:\n return _q_mapping(self, mapping)\n\n def _qdot_mapping(self, mapping: BiMapping = None) -> dict:\n return _qdot_mapping(self, mapping)\n\n def _qddot_mapping(self, mapping: BiMapping = None) -> dict:\n return _qddot_mapping(self, mapping)\n\n def bounds_from_ranges(self, variables: str | list[str, ...], mapping: BiMapping | BiMappingList = None) -> Bounds:\n return bounds_from_ranges(self, variables, mapping)\n\n def lagrangian(self, q: MX | SX, qdot: MX | SX) -> MX | SX:\n q_biorbd = GeneralizedCoordinates(q)\n qdot_biorbd = GeneralizedVelocity(qdot)\n return self.model.Lagrangian(q_biorbd, qdot_biorbd).to_mx()\n\n @staticmethod\n def animate(\n solution: Any, show_now: bool = True, tracked_markers: list[np.ndarray, ...] = None, **kwargs: Any\n ) -> None | list:\n try:\n import bioviz\n except ModuleNotFoundError:\n raise RuntimeError(\"bioviz must be install to animate the model\")\n\n check_version(bioviz, \"2.3.0\", \"2.4.0\")\n\n states = solution.states\n if not isinstance(states, (list, tuple)):\n states = [states]\n\n if tracked_markers is None:\n tracked_markers = [None] * len(states)\n\n all_bioviz = []\n for idx_phase, data in enumerate(states):\n if not isinstance(solution.ocp.nlp[idx_phase].model, BiorbdModel):\n raise NotImplementedError(\"Animation is only implemented for biorbd models\")\n\n # This calls each of the function that modify the internal dynamic model based on the parameters\n nlp = solution.ocp.nlp[idx_phase]\n\n # noinspection PyTypeChecker\n biorbd_model: BiorbdModel = nlp.model\n\n all_bioviz.append(bioviz.Viz(biorbd_model.path, **kwargs))\n all_bioviz[-1].load_movement(solution.ocp.nlp[idx_phase].variable_mappings[\"q\"].to_second.map(data[\"q\"]))\n\n if tracked_markers[idx_phase] is not None:\n all_bioviz[-1].load_experimental_markers(tracked_markers[idx_phase])\n\n if show_now:\n b_is_visible = [True] * len(all_bioviz)\n while sum(b_is_visible):\n for i, b in enumerate(all_bioviz):\n if b.vtk_window.is_active:\n b.update()\n else:\n b_is_visible[i] = False\n return None\n else:\n return all_bioviz\n\n\nclass MultiBiorbdModel:\n \"\"\"\n This class allows to define multiple biorbd models for the same phase.\n \"\"\"\n\n def __init__(self, bio_model: tuple[str | biorbd.Model | BiorbdModel, ...]):\n self.models = []\n if not isinstance(bio_model, tuple):\n raise ValueError(\"The models must be a 'str', 'biorbd.Model', 'bioptim.BiorbdModel'\" \" or a tuple of those\")\n\n for model in bio_model:\n if isinstance(model, str):\n self.models.append(BiorbdModel(model))\n elif isinstance(model, biorbd.Model):\n self.models.append(BiorbdModel(model))\n elif isinstance(model, BiorbdModel):\n self.models.append(model)\n else:\n raise ValueError(\"The models should be of type 'str', 'biorbd.Model' or 'bioptim.BiorbdModel'\")\n\n def __getitem__(self, index):\n return self.models[index]\n\n def deep_copy(self, *args):\n raise NotImplementedError(\"Deep copy is not implemented yet for MultiBiorbdModel class\")\n\n @property\n def path(self) -> list[str]:\n return [model.path for model in self.models]\n\n def copy(self):\n return MultiBiorbdModel(tuple(self.path))\n\n def serialize(self) -> tuple[Callable, dict]:\n return MultiBiorbdModel, dict(bio_model=tuple(self.path))\n\n def variable_index(self, variable: str, model_index: int) -> range:\n \"\"\"\n Get the index of the variables in the global vector for a given model index\n\n Parameters\n ----------\n variable: str\n The variable to get the index from such as 'q', 'qdot', 'qddot', 'tau', 'contact'\n model_index: int\n The index of the model to get the index from\n\n Returns\n -------\n range\n The index of the variable in the global vector\n \"\"\"\n if variable == \"q\":\n current_idx = 0\n for model in self.models[:model_index]:\n current_idx += model.nb_q\n return range(current_idx, current_idx + self.models[model_index].nb_q)\n elif variable == \"qdot\":\n current_idx = 0\n for model in self.models[:model_index]:\n current_idx += model.nb_qdot\n return range(current_idx, current_idx + self.models[model_index].nb_qdot)\n elif variable == \"qddot\":\n current_idx = 0\n for model in self.models[:model_index]:\n current_idx += model.nb_qddot\n return range(current_idx, current_idx + self.models[model_index].nb_qddot)\n elif variable == \"qddot_joints\":\n current_idx = 0\n for model in self.models[:model_index]:\n current_idx += model.nb_qddot - model.nb_root\n return range(\n current_idx, current_idx + self.models[model_index].nb_qddot - self.models[model_index].nb_root\n )\n elif variable == \"qddot_root\":\n current_idx = 0\n for model in self.models[:model_index]:\n current_idx += model.nb_root\n return range(current_idx, current_idx + self.models[model_index].nb_root)\n elif variable == \"tau\":\n current_idx = 0\n for model in self.models[:model_index]:\n current_idx += model.nb_tau\n return range(current_idx, current_idx + self.models[model_index].nb_tau)\n elif variable == \"contact\":\n current_idx = 0\n for model in self.models[:model_index]:\n current_idx += model.nb_rigid_contacts\n return range(current_idx, current_idx + self.models[model_index].nb_rigid_contacts)\n\n @property\n def gravity(self) -> MX:\n return vertcat(*(model.gravity for model in self.models))\n\n def set_gravity(self, new_gravity) -> None:\n for model in self.models:\n model.set_gravity(new_gravity)\n return\n\n @property\n def nb_tau(self) -> int:\n return sum(model.nb_tau for model in self.models)\n\n @property\n def nb_segments(self) -> int:\n return sum(model.nb_segments for model in self.models)\n\n def segment_index(self, name) -> int:\n raise NotImplementedError(\"segment_index is not implemented for MultiBiorbdModel\")\n\n @property\n def nb_quaternions(self) -> int:\n return sum(model.nb_quaternions for model in self.models)\n\n @property\n def nb_q(self) -> int:\n return sum(model.nb_q for model in self.models)\n\n @property\n def nb_qdot(self) -> int:\n return sum(model.nb_qdot for model in self.models)\n\n @property\n def nb_qddot(self) -> int:\n return sum(model.nb_qddot for model in self.models)\n\n @property\n def nb_root(self) -> int:\n return sum(model.nb_root for model in self.models)\n\n @property\n def segments(self) -> tuple[biorbd.Segment, ...]:\n out = ()\n for model in self.models:\n out += model.segments\n return out\n\n def homogeneous_matrices_in_global(self, q, reference_index, inverse=False):\n raise NotImplementedError(\"homogeneous_matrices_in_global is not implemented for MultiBiorbdModel\")\n\n def homogeneous_matrices_in_child(self, *args) -> tuple:\n raise NotImplementedError(\"homogeneous_matrices_in_child is not implemented for MultiBiorbdModel\")\n\n @property\n def mass(self) -> MX:\n return vertcat(*(model.mass for model in self.models))\n\n def center_of_mass(self, q) -> MX:\n out = MX()\n for i, model in enumerate(self.models):\n q_model = q[self.variable_index(\"q\", i)]\n out = vertcat(out, model.center_of_mass(q_model))\n return out\n\n def center_of_mass_velocity(self, q, qdot) -> MX:\n out = MX()\n for i, model in enumerate(self.models):\n q_model = q[self.variable_index(\"q\", i)]\n qdot_model = qdot[self.variable_index(\"qdot\", i)]\n out = vertcat(\n out,\n model.center_of_mass_velocity(q_model, qdot_model),\n )\n return out\n\n def center_of_mass_acceleration(self, q, qdot, qddot) -> MX:\n out = MX()\n for i, model in enumerate(self.models):\n q_model = q[self.variable_index(\"q\", i)]\n qdot_model = qdot[self.variable_index(\"qdot\", i)]\n qddot_model = qddot[self.variable_index(\"qddot\", i)]\n out = vertcat(\n out,\n model.center_of_mass_acceleration(q_model, qdot_model, qddot_model),\n )\n return out\n\n def mass_matrix(self, q) -> list[MX]:\n out = []\n for i, model in enumerate(self.models):\n q_model = q[self.variable_index(\"q\", i)]\n out += [model.mass_matrix(q_model)]\n return out\n\n def non_linear_effects(self, q, qdot) -> list[MX]:\n out = []\n for i, model in enumerate(self.models):\n q_model = q[self.variable_index(\"q\", i)]\n qdot_model = qdot[self.variable_index(\"qdot\", i)]\n out += [model.non_linear_effects(q_model, qdot_model)]\n return out\n\n def angular_momentum(self, q, qdot) -> MX:\n out = MX()\n for i, model in enumerate(self.models):\n q_model = q[self.variable_index(\"q\", i)]\n qdot_model = qdot[self.variable_index(\"qdot\", i)]\n out = vertcat(\n out,\n model.angular_momentum(q_model, qdot_model),\n )\n return out\n\n def reshape_qdot(self, q, qdot, k_stab=1) -> MX:\n out = MX()\n for i, model in enumerate(self.models):\n q_model = q[self.variable_index(\"q\", i)]\n qdot_model = qdot[self.variable_index(\"qdot\", i)]\n out = vertcat(\n out,\n model.reshape_qdot(q_model, qdot_model, k_stab),\n )\n return out\n\n def segment_angular_velocity(self, q, qdot, idx) -> MX:\n out = MX()\n for i, model in enumerate(self.models):\n q_model = q[self.variable_index(\"q\", i)]\n qdot_model = qdot[self.variable_index(\"qdot\", i)]\n out = vertcat(\n out,\n model.segment_angular_velocity(q_model, qdot_model, idx),\n )\n return out\n\n @property\n def name_dof(self) -> tuple[str, ...]:\n return tuple([dof for model in self.models for dof in model.name_dof])\n\n @property\n def contact_names(self) -> tuple[str, ...]:\n return tuple([contact for model in self.models for contact in model.contact_names])\n\n @property\n def nb_soft_contacts(self) -> int:\n return sum(model.nb_soft_contacts for model in self.models)\n\n @property\n def soft_contact_names(self) -> tuple[str, ...]:\n return tuple([contact for model in self.models for contact in model.soft_contact_names])\n\n def soft_contact(self, soft_contact_index, *args):\n current_number_of_soft_contacts = 0\n out = []\n for model in self.models:\n if soft_contact_index < current_number_of_soft_contacts + model.nb_soft_contacts:\n out = model.soft_contact(soft_contact_index - current_number_of_soft_contacts, *args)\n break\n current_number_of_soft_contacts += model.nb_soft_contacts\n return out\n\n @property\n def muscle_names(self) -> tuple[str, ...]:\n return tuple([muscle for model in self.models for muscle in model.muscle_names])\n\n @property\n def nb_muscles(self) -> int:\n return sum(model.nb_muscles for model in self.models)\n\n def torque(self, tau_activations, q, qdot) -> MX:\n out = MX()\n for i, model in enumerate(self.models):\n tau_activations_model = tau_activations[self.variable_index(\"tau\", i)]\n q_model = q[self.variable_index(\"q\", i)]\n qdot_model = qdot[self.variable_index(\"qdot\", i)]\n out = vertcat(\n out,\n model.torque(\n tau_activations_model,\n q_model,\n qdot_model,\n ),\n )\n return out\n\n def forward_dynamics_free_floating_base(self, q, qdot, qddot_joints) -> MX:\n out = MX()\n for i, model in enumerate(self.models):\n q_model = q[self.variable_index(\"q\", i)]\n qdot_model = qdot[self.variable_index(\"qdot\", i)]\n qddot_joints_model = qddot_joints[self.variable_index(\"qddot_joints\", i)]\n out = vertcat(\n out,\n model.forward_dynamics_free_floating_base(\n q_model,\n qdot_model,\n qddot_joints_model,\n ),\n )\n return out\n\n def reorder_qddot_root_joints(self, qddot_root, qddot_joints):\n out = MX()\n for i, model in enumerate(self.models):\n qddot_root_model = qddot_root[self.variable_index(\"qddot_root\", i)]\n qddot_joints_model = qddot_joints[self.variable_index(\"qddot_joints\", i)]\n out = vertcat(\n out,\n model.reorder_qddot_root_joints(qddot_root_model, qddot_joints_model),\n )\n\n return out\n\n def forward_dynamics(self, q, qdot, tau, external_forces=None, f_contacts=None) -> MX:\n if f_contacts is not None or external_forces is not None:\n raise NotImplementedError(\n \"External forces and contact forces are not implemented yet for MultiBiorbdModel.\"\n )\n\n out = MX()\n for i, model in enumerate(self.models):\n q_model = q[self.variable_index(\"q\", i)]\n qdot_model = qdot[self.variable_index(\"qdot\", i)]\n tau_model = tau[self.variable_index(\"tau\", i)]\n out = vertcat(\n out,\n model.forward_dynamics(\n q_model,\n qdot_model,\n tau_model,\n external_forces,\n f_contacts,\n ),\n )\n return out\n\n def constrained_forward_dynamics(self, q, qdot, tau, external_forces=None) -> MX:\n if external_forces is not None:\n raise NotImplementedError(\"External forces are not implemented yet for MultiBiorbdModel.\")\n\n out = MX()\n for i, model in enumerate(self.models):\n q_model = q[self.variable_index(\"q\", i)]\n qdot_model = qdot[self.variable_index(\"qdot\", i)]\n tau_model = tau[self.variable_index(\"qddot\", i)] # Due to a bug in biorbd\n out = vertcat(\n out,\n model.constrained_forward_dynamics(\n q_model,\n qdot_model,\n tau_model,\n external_forces,\n ),\n )\n return out\n\n def inverse_dynamics(self, q, qdot, qddot, external_forces=None, f_contacts=None) -> MX:\n if f_contacts is not None or external_forces is not None:\n raise NotImplementedError(\n \"External forces and contact forces are not implemented yet for MultiBiorbdModel.\"\n )\n\n out = MX()\n for i, model in enumerate(self.models):\n q_model = q[self.variable_index(\"q\", i)]\n qdot_model = qdot[self.variable_index(\"qdot\", i)]\n qddot_model = qddot[self.variable_index(\"qddot\", i)]\n out = vertcat(\n out,\n model.inverse_dynamics(\n q_model,\n qdot_model,\n qddot_model,\n external_forces,\n f_contacts,\n ),\n )\n return out\n\n def contact_forces_from_constrained_forward_dynamics(self, q, qdot, tau, external_forces=None) -> MX:\n if external_forces is not None:\n raise NotImplementedError(\"External forces are not implemented yet for MultiBiorbdModel.\")\n out = MX()\n for i, model in enumerate(self.models):\n q_model = q[self.variable_index(\"q\", i)]\n qdot_model = qdot[self.variable_index(\"qdot\", i)]\n tau_model = tau[self.variable_index(\"qddot\", i)] # Due to a bug in biorbd\n out = vertcat(\n out,\n model.contact_forces_from_constrained_forward_dynamics(\n q_model,\n qdot_model,\n tau_model,\n external_forces,\n ),\n )\n return out\n\n def qdot_from_impact(self, q, qdot_pre_impact) -> MX:\n out = MX()\n for i, model in enumerate(self.models):\n q_model = q[self.variable_index(\"q\", i)]\n qdot_pre_impact_model = qdot_pre_impact[self.variable_index(\"qdot\", i)]\n out = vertcat(\n out,\n model.qdot_from_impact(\n q_model,\n qdot_pre_impact_model,\n ),\n )\n return out\n\n def muscle_activation_dot(self, muscle_excitations) -> MX:\n out = MX()\n for model in self.models:\n muscle_states = model.model.stateSet() # still call from Biorbd\n for k in range(model.nb_muscles):\n muscle_states[k].setExcitation(muscle_excitations[k])\n out = vertcat(out, model.model.activationDot(muscle_states).to_mx())\n return out\n\n def muscle_joint_torque(self, activations, q, qdot) -> MX:\n out = MX()\n for model in self.models:\n muscles_states = model.model.stateSet() # still call from Biorbd\n for k in range(model.nb_muscles):\n muscles_states[k].setActivation(activations[k])\n q_biorbd = GeneralizedCoordinates(q)\n qdot_biorbd = GeneralizedVelocity(qdot)\n out = vertcat(out, model.model.muscularJointTorque(muscles_states, q_biorbd, qdot_biorbd).to_mx())\n return out\n\n def markers(self, q) -> Any | list[MX]:\n out = []\n for i, model in enumerate(self.models):\n q_model = q[self.variable_index(\"q\", i)]\n out.append(model.markers(q_model))\n return [item for sublist in out for item in sublist]\n\n @property\n def nb_markers(self) -> int:\n return sum(model.nb_markers for model in self.models)\n\n def marker_index(self, name):\n raise NotImplementedError(\"marker_index is not implemented yet for MultiBiorbdModel\")\n\n def marker(self, q, index, reference_segment_index=None) -> MX:\n raise NotImplementedError(\"marker is not implemented yet for MultiBiorbdModel\")\n\n @property\n def nb_rigid_contacts(self) -> int:\n \"\"\"\n Returns the number of rigid contacts.\n Example:\n First contact with axis YZ\n Second contact with axis Z\n nb_rigid_contacts = 2\n \"\"\"\n return sum(model.nb_rigid_contacts for model in self.models)\n\n @property\n def nb_contacts(self) -> int:\n \"\"\"\n Returns the number of contact index.\n Example:\n First contact with axis YZ\n Second contact with axis Z\n nb_contacts = 3\n \"\"\"\n return sum(model.nb_contacts for model in self.models)\n\n def rigid_contact_index(self, contact_index) -> tuple:\n \"\"\"\n Returns the axis index of this specific rigid contact.\n Example:\n First contact with axis YZ\n Second contact with axis Z\n rigid_contact_index(0) = (1, 2)\n \"\"\"\n\n model_selected = None\n for i, model in enumerate(self.models):\n if contact_index in self.variable_index(\"contact\", i):\n model_selected = model\n # Note: may not work if the contact_index is not in the first model\n return model_selected.rigid_contact_index(contact_index)\n\n def marker_velocities(self, q, qdot, reference_index=None) -> list[MX]:\n if reference_index is not None:\n raise RuntimeError(\"marker_velocities is not implemented yet with reference_index for MultiBiorbdModel\")\n\n out = []\n for i, model in enumerate(self.models):\n q_model = q[self.variable_index(\"q\", i)]\n qdot_model = qdot[self.variable_index(\"qdot\", i)]\n out.extend(\n model.marker_velocities(q_model, qdot_model, reference_index),\n )\n return out\n\n def tau_max(self, q, qdot) -> tuple[MX, MX]:\n out_max = MX()\n out_min = MX()\n for i, model in enumerate(self.models):\n q_model = q[self.variable_index(\"q\", i)]\n qdot_model = qdot[self.variable_index(\"qdot\", i)]\n torque_max, torque_min = model.tau_max(q_model, qdot_model)\n out_max = vertcat(out_max, torque_max)\n out_min = vertcat(out_min, torque_min)\n return out_max, out_min\n\n def rigid_contact_acceleration(self, q, qdot, qddot, contact_index, contact_axis) -> MX:\n model_selected = None\n model_idx = -1\n for i, model in enumerate(self.models):\n if contact_index in self.variable_index(\"contact\", i):\n model_selected = model\n model_idx = i\n q_model = q[self.variable_index(\"q\", model_idx)]\n qdot_model = qdot[self.variable_index(\"qdot\", model_idx)]\n qddot_model = qddot[self.variable_index(\"qddot\", model_idx)]\n return model_selected.rigid_contact_acceleration(q_model, qdot_model, qddot_model, contact_index, contact_axis)\n\n @property\n def nb_dof(self) -> int:\n return sum(model.nb_dof for model in self.models)\n\n @property\n def marker_names(self) -> tuple[str, ...]:\n return tuple([name for model in self.models for name in model.marker_names])\n\n def soft_contact_forces(self, q, qdot) -> MX:\n out = MX()\n for i, model in enumerate(self.models):\n q_model = q[self.variable_index(\"q\", i)]\n qdot_model = qdot[self.variable_index(\"qdot\", i)]\n soft_contact_forces = model.soft_contact_forces(q_model, qdot_model)\n out = vertcat(out, soft_contact_forces)\n return out\n\n def reshape_fext_to_fcontact(self, fext: MX) -> biorbd.VecBiorbdVector:\n raise NotImplementedError(\"reshape_fext_to_fcontact is not implemented yet for MultiBiorbdModel\")\n\n def normalize_state_quaternions(self, x: MX | SX) -> MX | SX:\n all_q_normalized = MX()\n for i, model in enumerate(self.models):\n q_model = x[self.variable_index(\"q\", i)] # quaternions are only in q\n q_normalized = model.normalize_state_quaternions(q_model)\n all_q_normalized = vertcat(all_q_normalized, q_normalized)\n idx_first_qdot = self.nb_q # assuming x = [q, qdot]\n x_normalized = vertcat(all_q_normalized, x[idx_first_qdot:])\n\n return x_normalized\n\n def contact_forces(self, q, qdot, tau, external_forces: list = None) -> MX:\n if external_forces is not None:\n raise NotImplementedError(\"contact_forces is not implemented yet with external_forces for MultiBiorbdModel\")\n\n out = MX()\n for i, model in enumerate(self.models):\n q_model = q[self.variable_index(\"q\", i)]\n qdot_model = qdot[self.variable_index(\"qdot\", i)]\n tau_model = tau[self.variable_index(\"tau\", i)]\n\n contact_forces = model.contact_forces(q_model, qdot_model, tau_model, external_forces)\n out = vertcat(out, contact_forces)\n\n return out\n\n def passive_joint_torque(self, q, qdot) -> MX:\n out = MX()\n for i, model in enumerate(self.models):\n q_model = q[self.variable_index(\"q\", i)]\n qdot_model = qdot[self.variable_index(\"qdot\", i)]\n out = vertcat(out, model.passive_joint_torque(q_model, qdot_model))\n return out\n\n def ligament_joint_torque(self, q, qdot) -> MX:\n out = MX()\n for i, model in enumerate(self.models):\n q_model = q[self.variable_index(\"q\", i)]\n qdot_model = qdot[self.variable_index(\"qdot\", i)]\n out = vertcat(out, model.ligament_joint_torque(q_model, qdot_model))\n return out\n\n def ranges_from_model(self, variable: str):\n return [the_range for model in self.models for the_range in model.ranges_from_model(variable)]\n\n def bounds_from_ranges(self, variables: str | list[str, ...], mapping: BiMapping | BiMappingList = None) -> Bounds:\n return bounds_from_ranges(self, variables, mapping)\n\n def _q_mapping(self, mapping: BiMapping = None) -> dict:\n return _q_mapping(self, mapping)\n\n def _qdot_mapping(self, mapping: BiMapping = None) -> dict:\n return _qdot_mapping(self, mapping)\n\n def _qddot_mapping(self, mapping: BiMapping = None) -> dict:\n return _qddot_mapping(self, mapping)\n\n def lagrangian(self):\n raise NotImplementedError(\"lagrangian is not implemented yet for MultiBiorbdModel\")\n\n @staticmethod\n def animate(solution: Any, show_now: bool = True, tracked_markers: list = [], **kwargs: Any) -> None | list:\n raise NotImplementedError(\"animate is not implemented yet for MultiBiorbdModel\")\n","sub_path":"bioptim/interfaces/biorbd_model.py","file_name":"biorbd_model.py","file_ext":"py","file_size_in_byte":45470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"319231585","text":"# -*- coding: utf-8 -*-\n\"\"\"Function for basic model classes\n__author__ = '{Jimmy Yeh}'\n__email__ = '{marrch30@gmail.com}'\n\"\"\"\n\nimport torch\nimport torch.nn as nn\n\ndef Linear_model():\n model = torch.nn.Sequential(\n Flatten(),\n torch.nn.Linear(28*28, 1024),\n torch.nn.ReLU(),\n torch.nn.Linear(1024, 128),\n torch.nn.ReLU(),\n torch.nn.Linear(128, 10),\n # torch.nn.Softmax()\n )\n return model\n\nclass Flatten(torch.nn.Module):\n def forward(self, x):\n x = x.view(x.size(0), -1)\n return x\n\n## 421 half size 311 same size\n\ndef Wide_model(k=5):\n model = nn.Sequential(\n nn.Conv2d(1, 4*k, 4, stride=2, padding=1),\n nn.ReLU(),\n nn.Conv2d(4*k, 8*k, 4, stride=2, padding=1),\n nn.ReLU(),\n Flatten(),\n nn.Linear(8*k*7*7,k*128),\n nn.ReLU(),\n nn.Linear(k*128, 10)\n )\n return model\n\n\ndef Deep_model(k=2):\n def conv_group(inf, outf, N): \n model_list = []\n for i in range(N):\n if i == 0:\n c_in = inf\n c_out = outf\n else:\n c_in = c_out = outf\n\n if i == N-1:\n model_list.append(nn.Conv2d(c_in, c_out, 4, stride=2, padding=1))\n else:\n model_list.append(nn.Conv2d(c_in, c_out, 3, stride=1, padding=1))\n model_list.append(nn.ReLU())\n\n return model_list\n\n conv_group1 = conv_group(1, 8, k)\n conv_group2 = conv_group(8, 16, k)\n\n model = nn.Sequential(\n *conv_group1, \n *conv_group2,\n Flatten(),\n nn.Linear(16*7*7,100),\n nn.ReLU(),\n nn.Linear(100, 10)\n )\n return model\n\n# def VGG():\n\n\n# def ResNet():\n# pass\n\n\n\n\n\n\n\n\n\n\n","sub_path":"past_src/87transfer/past_module/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"332913572","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2018/1/14 18:41\n# @Author : Dicey\n# @Site : Soochow\n# @File : FunctionTest.py\n# @Software: PyCharm\n\n# -*- coding: utf-8 -*-\nimport json\n\nimport urllib, sys\nimport urllib.request\n# from urllib2 import quote\nfrom urllib import parse\nimport random\nimport hashlib\nimport re\n\n\n# import pylibmc\n\n# help\ndef help():\n output = \"1、看段子,输入指令,如:'段子',看搞笑段子。\\n2、天气查询,输入城市+天气,如:'上海天气',查询上海天气。\" \\\n \"\\n3、英汉互译,输入fy+要翻译的内容,如:'fy+hello',翻译'hello'。\" \\\n \"\\n4、调戏小阿狸,输入'ali'即可进入聊天模式,输入'bye'退出聊天模式。\" \\\n \"\\n5、反馈功能,输入fk+要反馈的内容,如:'fk+小阿狸真可爱!'。\" \\\n \"\\n更多功能,敬请期待……\"\n return output\n\n\n# 找段子\ndef joke():\n url_8 = \"http://www.qiushibaike.com/\"\n url_24 = \"http://www.qiushibaike.com/hot/\"\n headers = {\n 'Connection': 'Keep-Alive',\n 'Accept': 'text/html, application/xhtml+xml, */*',\n 'Accept-Language': 'en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko'}\n req_8 = urllib.request.Request(url_8, headers=headers)\n req_24 = urllib.request.Request(url_24, headers=headers)\n opener_8 = urllib.request.urlopen(req_8)\n opener_24 = urllib.request.urlopen(req_24)\n html_8 = opener_8.read()\n html_24 = opener_24.read()\n rex = r'(?<=div class=\"content\">).*?(?= \".join(c[0] for c in cycle)\n\n def dependency(self, node1, node2):\n \"indicate that node1 depends on node2\"\n self.graph.add_node(node1)\n self.graph.add_node(node2)\n self.graph.add_edge(node2, node1)\n\n def add_node(self, node):\n self.graph.add_node(node)\n\n def write_graph(self, outfile: str, manifest: Manifest):\n \"\"\"Write the graph to a gpickle file. Before doing so, serialize and\n include all nodes in their corresponding graph entries.\n \"\"\"\n out_graph = self.graph.copy()\n for node_id in self.graph.nodes():\n data = manifest.expect(node_id).to_dict()\n out_graph.add_node(node_id, **data)\n nx.write_gpickle(out_graph, outfile)\n\n\nclass Compiler:\n def __init__(self, config):\n self.config = config\n\n def initialize(self):\n make_directory(self.config.target_path)\n make_directory(self.config.modules_path)\n\n def _create_node_context(\n self,\n node: NonSourceCompiledNode,\n manifest: Manifest,\n extra_context: Dict[str, Any],\n ) -> Dict[str, Any]:\n context = generate_runtime_model(\n node, self.config, manifest\n )\n context.update(extra_context)\n if isinstance(node, CompiledSchemaTestNode):\n # for test nodes, add a special keyword args value to the context\n jinja.add_rendered_test_kwargs(context, node)\n\n return context\n\n def _get_compiled_model(\n self,\n manifest: Manifest,\n cte_id: str,\n extra_context: Dict[str, Any],\n ) -> NonSourceCompiledNode:\n\n if cte_id not in manifest.nodes:\n raise InternalException(\n f'During compilation, found a cte reference that could not be '\n f'resolved: {cte_id}'\n )\n cte_model = manifest.nodes[cte_id]\n if getattr(cte_model, 'compiled', False):\n assert isinstance(cte_model, tuple(COMPILED_TYPES.values()))\n return cast(NonSourceCompiledNode, cte_model)\n elif cte_model.is_ephemeral_model:\n # this must be some kind of parsed node that we can compile.\n # we know it's not a parsed source definition\n assert isinstance(cte_model, tuple(COMPILED_TYPES))\n # update the node so\n node = self.compile_node(cte_model, manifest, extra_context)\n manifest.sync_update_node(node)\n return node\n else:\n raise InternalException(\n f'During compilation, found an uncompiled cte that '\n f'was not an ephemeral model: {cte_id}'\n )\n\n def _recursively_prepend_ctes(\n self,\n model: NonSourceCompiledNode,\n manifest: Manifest,\n extra_context: Dict[str, Any],\n ) -> Tuple[NonSourceCompiledNode, List[InjectedCTE]]:\n if model.extra_ctes_injected:\n return (model, model.extra_ctes)\n\n if flags.STRICT_MODE:\n if not isinstance(model, tuple(COMPILED_TYPES.values())):\n raise InternalException(\n f'Bad model type: {type(model)}'\n )\n\n prepended_ctes: List[InjectedCTE] = []\n\n for cte in model.extra_ctes:\n cte_model = self._get_compiled_model(\n manifest,\n cte.id,\n extra_context,\n )\n cte_model, new_prepended_ctes = self._recursively_prepend_ctes(\n cte_model, manifest, extra_context\n )\n _extend_prepended_ctes(prepended_ctes, new_prepended_ctes)\n new_cte_name = add_ephemeral_model_prefix(cte_model.name)\n sql = f' {new_cte_name} as (\\n{cte_model.compiled_sql}\\n)'\n _add_prepended_cte(prepended_ctes, InjectedCTE(id=cte.id, sql=sql))\n\n model.prepend_ctes(prepended_ctes)\n\n manifest.update_node(model)\n\n return model, prepended_ctes\n\n def compile_node(\n self, node: NonSourceNode, manifest, extra_context=None\n ) -> NonSourceCompiledNode:\n if extra_context is None:\n extra_context = {}\n\n logger.debug(\"Compiling {}\".format(node.unique_id))\n\n data = node.to_dict()\n data.update({\n 'compiled': False,\n 'compiled_sql': None,\n 'extra_ctes_injected': False,\n 'extra_ctes': [],\n 'injected_sql': None,\n })\n compiled_node = _compiled_type_for(node).from_dict(data)\n\n context = self._create_node_context(\n compiled_node, manifest, extra_context\n )\n\n compiled_node.compiled_sql = jinja.get_rendered(\n node.raw_sql,\n context,\n node)\n\n compiled_node.compiled = True\n\n injected_node, _ = self._recursively_prepend_ctes(\n compiled_node, manifest, extra_context\n )\n\n return injected_node\n\n def write_graph_file(self, linker: Linker, manifest: Manifest):\n filename = graph_file_name\n graph_path = os.path.join(self.config.target_path, filename)\n if flags.WRITE_JSON:\n linker.write_graph(graph_path, manifest)\n\n def link_node(\n self, linker: Linker, node: NonSourceNode, manifest: Manifest\n ):\n linker.add_node(node.unique_id)\n\n for dependency in node.depends_on_nodes:\n if dependency in manifest.nodes:\n linker.dependency(\n node.unique_id,\n (manifest.nodes[dependency].unique_id)\n )\n elif dependency in manifest.sources:\n linker.dependency(\n node.unique_id,\n (manifest.sources[dependency].unique_id)\n )\n else:\n dependency_not_found(node, dependency)\n\n def link_graph(self, linker: Linker, manifest: Manifest):\n for source in manifest.sources.values():\n linker.add_node(source.unique_id)\n for node in manifest.nodes.values():\n self.link_node(linker, node, manifest)\n\n cycle = linker.find_cycles()\n\n if cycle:\n raise RuntimeError(\"Found a cycle: {}\".format(cycle))\n\n def compile(self, manifest: Manifest, write=True) -> Graph:\n linker = Linker()\n\n self.link_graph(linker, manifest)\n\n stats = _generate_stats(manifest)\n\n if write:\n self.write_graph_file(linker, manifest)\n print_compile_stats(stats)\n\n return Graph(linker.graph)\n\n\ndef compile_manifest(config, manifest, write=True) -> Graph:\n compiler = Compiler(config)\n compiler.initialize()\n return compiler.compile(manifest, write=write)\n\n\ndef _is_writable(node):\n if not node.injected_sql:\n return False\n\n if node.resource_type == NodeType.Snapshot:\n return False\n\n return True\n\n\ndef compile_node(adapter, config, node, manifest, extra_context, write=True):\n compiler = Compiler(config)\n node = compiler.compile_node(node, manifest, extra_context)\n\n if write and _is_writable(node):\n logger.debug('Writing injected SQL for node \"{}\"'.format(\n node.unique_id))\n\n node.build_path = node.write_node(\n config.target_path,\n 'compiled',\n node.injected_sql\n )\n\n return node\n","sub_path":"core/dbt/compilation.py","file_name":"compilation.py","file_ext":"py","file_size_in_byte":10432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"243857278","text":"import requests\nfrom bs4 import BeautifulSoup\nimport re\n\nhtml_response = requests.get(\"https://movie.douban.com/top250?start=100&filter=\")\nhtml_response.encoding = html_response.apparent_encoding\nsoup = BeautifulSoup(html_response.text, \"html.parser\")\nmovies_list = soup.find('ol', 'grid_view')\n\nfor per_movie in movies_list.find_all('li'):\n info_dic = {}\n info_dic['rank'] = per_movie.find('em').string\n string_ = ''\n for string in per_movie.find('div', 'info').find('a').stripped_strings:\n string_ += string\n info_dic['name'] = re.sub('\\xa0', ' ', string_)\n # string_ = ''\n # for string in per_movie.find('div', 'bd').find('p').stripped_strings:\n # string_ += string\n # info_dic['intro'] = string_.split('\\xa0')\n info_dic['score'] = per_movie.find('span', 'rating_num').string\n if per_movie.find('span', 'inq'):\n info_dic['quote'] = per_movie.find('span', 'inq').string\n\n print(info_dic)\n\n\n\n","sub_path":"codes/crawl_codes/requests/DoubanMovieTop250.py","file_name":"DoubanMovieTop250.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"44011284","text":"import sys\n\n# 가격 단위, 100이면 100원\nPRICE_UNIT = 100\n\nclass texts:\n title = \"### 클래스 %s 자판기 입니다. ####\"\n product = \"%s:%s(%s원)\"\n insert_coin = \"동전을 넣어주세요. : \"\n n_enough_coin = \"동전이 부족합니다.\\n거스름돈은 %s원 입니다.\"\n select_product = \"원하시는 상품번호를 선택하세요\"\n select_fault = \"잘못누르셨습니다\"\n product_out = \"선택하신 %s입니다. 거스름돈은 %s원 입니다.\\n감사합니다.\"\n\n\nclass Product:\n #제품 종류, 가격을 쉽게 추가, 변경\n productType = []\n productValue = []\n\nclass CoffeeVM(Product):\n _product_info_file = \"coffee.txt\"\n _name = \"커피\"\n\n def __init__(self):\n #자판기 종류를 선택하면 _name 출력\n print(texts.title %self._name)\n\n def set_products(self):\n #제품 종류, 가격 리스트를 초기화함\n Product.productType = []\n Product.productValue = []\n\n with open(self._product_info_file, \"r\") as fd:\n for line in fd:\n #라인 끝에 있는 \\n제거하고 ,로 구분\n list = line.strip('\\n').split(',')\n\n #제품 종류 가격 리스트에 필요한 값을 입력\n Product.productType.append((list[0]+','+list[1]))\n Product.productValue.append((list[0]+','+list[2]))\n\n def run(self):\n self.set_products()\n \n while True:\n try:\n inputCoin = float(input(texts.insert_coin))\n except ValueError:\n print(texts.select_fault)\n else:\n self.selectProduct(inputCoin)\n\n def selectProduct(self, coin):\n #제품 종류를 리스트로 선언하여 코드 변경없이 데이터를 보여줌\n description = ''\n for line in Product.productType:\n list = line.split(',')\n \n price = self.getProductValue(list[0])\n description += list[0] + \":\" + list[1] + \"(\"+str(price)+\"원) \"\n\n print(description)\n inputProduct = input(texts.select_product)\n productValue = self.getProductValue(inputProduct)\n \n if productValue:\n productName = self.getProductName(inputProduct)\n self.payment(coin, productName, productValue)\n else:\n #잘못된 값을 입력했을 경우 에러메세지 출력, 제품선택 메뉴로 이동 \n print(texts.select_fault)\n self.selectProduct(coin)\n\n def getProductValue(self, product):\n returnValue = 0\n for line in Product.productValue:\n list = line.split(',')\n if list[0] == product:\n returnValue = list[1]\n\n return int(returnValue)\n\n def getProductName(self, product):\n for line in Product.productType:\n list = line.split(',')\n if list[0] == product:\n return list[1]\n\n def payment(self, coin, name, value):\n coinValue = coin*PRICE_UNIT\n \n if coinValue >= value:\n balance = coinValue - value\n print(texts.product_out %(name, int(balance)))\n else:\n print(texts.n_enough_coin %int(coinValue))\n\n #지불이 끝나면 초기메뉴로 이동\n self.run()\n\n#커피 클래스를 상속 받음\nclass SnackVM(CoffeeVM):\n _name = \"과자\"\n _product_info_file = \"snack.txt\"\n\nif __name__ == '__main__':\n print(\"1:커피, 2:과자\")\n select_vm = input(\"구동할 자판기를 선택하세요.\").strip()\n\n if select_vm == \"1\":\n vm = CoffeeVM()\n elif select_vm == \"2\":\n vm = SnackVM()\n else:\n print(\"잘못누르셨습니다 다시 실행해주세요\")\n sys.exit(-1)\n try:\n vm.run()\n except KeyboardInterrupt as exc:\n print(\"판매를 종료합니다\")\n","sub_path":"Vending Machine Class/class_vm_file_release.py","file_name":"class_vm_file_release.py","file_ext":"py","file_size_in_byte":3876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"510953373","text":"#\n# import the necessary packages\n#\n\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\n\ndef main():\n\n #\n # load the image.\n #\n\n fn = \"Frame2.png\"\n image = cv2.imread(fn)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # BGR to RGB for right color.\n\n #\n # Convert the image to grayscale, and blur it\n #\n \n grayImage = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\n grayImage = cv2.GaussianBlur(grayImage, (3, 3), 0)\n\n #\n # detect edges in the gray image\n #\n\n edgedImage = cv2.Canny(grayImage, 10, 250)\n #edgedImage = cv2.Canny(grayImage, 10, 20)\n\n #\n # construct and apply a closing kernel to 'close' gaps between 'white'\n # pixels\n #\n\n kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7))\n closedImage = cv2.morphologyEx(edgedImage, cv2.MORPH_CLOSE, kernel)\n\n #\n # find contours (i.e. the 'outlines') in the image and initialize the\n # total number of books found\n #\n\n (_, cnts, _) = cv2.findContours(closedImage.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n total = 0\n\n #\n # loop over the contours\n #\n\n finalImage = image.copy()\n \n maxC = None\n maxApprox = None\n maxAreaSize = 0\n for c in cnts:\n \n #print (\"c = %s\" % c)\n \n #\n # approximate the contour\n #\n \n peri = cv2.arcLength(c, True)\n approx = cv2.approxPolyDP(c, 0.02 * peri, True)\n print (\"len(approx) = \", len(approx))\n\n #\n # if the approximated contour has four points, then assume that the\n # contour is a book -- a book is a rectangle and thus has four vertices\n #\n\n if len(approx) == 4:\n #if len(approx) <= 8:\n areaSize = cv2.contourArea(c)\n if areaSize > maxAreaSize:\n maxAreaSize = areaSize\n maxC = c\n maxApprox = approx\n print (\"It is candidated. areaSize = %d\" % areaSize)\n thin = 5\n cv2.drawContours(finalImage, [approx], -1, (0, 255, 0), thin)\n total += 1\n\n print (\"maxApprox = %s, maxAreaSize = %d\" % (maxApprox, maxAreaSize))\n thin = 20 \n cv2.drawContours(finalImage, [maxApprox], -1, (0, 255, 0), thin)\n\n #\n # Perspective transform.\n #\n\n pts1 = np.float32([maxApprox[0], maxApprox[1], maxApprox[2], maxApprox[3]])\n pts2 = np.float32([\n [300,0],\n [0,0],\n [0,300],\n [300,300]])\n M = cv2.getPerspectiveTransform(pts1, pts2)\n transformedImage = cv2.warpPerspective(image, M, (300, 300))\n \n #\n # Convert the transformed image to grayscale, and blur it.\n #\n \n grayImage = cv2.cvtColor(transformedImage, cv2.COLOR_RGB2GRAY)\n grayImage = cv2.GaussianBlur(grayImage, (3, 3), 0)\n \n #\n # detect edges in the gray image\n #\n\n edgedImage2 = cv2.Canny(grayImage, 10, 250)\n \n #\n # construct and apply a closing kernel to 'close' gaps between 'white'\n # pixels\n #\n\n kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7))\n closedImage2 = cv2.morphologyEx(edgedImage2, cv2.MORPH_CLOSE, kernel)\n \n #\n # find contours (i.e. the 'outlines') in the image and initialize the\n # total number of books found\n #\n\n (_, cnts, _) = cv2.findContours(closedImage2.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n total = 0\n\n #\n # loop over the contours\n #\n\n finalImage2 = transformedImage.copy()\n \n for c in cnts:\n \n #print (\"c = %s\" % c)\n \n #\n # approximate the contour\n #\n \n peri = cv2.arcLength(c, True)\n approx = cv2.approxPolyDP(c, 0.02 * peri, True)\n print (\"len(approx) = \", len(approx))\n\n #\n # if the approximated contour has four points, then assume that the\n # contour is a book -- a book is a rectangle and thus has four vertices\n #\n\n #if len(approx) == 4:\n if len(approx) <= 8:\n print (\"It is candidated. areaSize = %d\" % areaSize)\n thin = 5\n cv2.drawContours(finalImage2, [approx], -1, (0, 255, 0), thin)\n total += 1\n \n # \n # display the output\n #\n\n print (\"I found {0} books in that finalImage\".format(total))\n \n #\n # Save finalImage\n #\n \n cv2.imwrite('finalImage.jpg', finalImage) \n\n #\n # Display image, edgedImage, closedImage, finalImage, transformedImage\n #\n\n\n fig, axes = plt.subplots(\n ncols=4, \n nrows=2,\n figsize=(10, 6))\n\n ax0, ax1, ax2, ax3, ax4, ax5, ax6, ax7 = axes.flat\n\n fontSize = 10\n\n ax0.imshow(image)\n ax0.set_title('Origin', fontsize=fontSize)\n ax0.axis('off') \n\n ax1.imshow(edgedImage)\n ax1.set_title('Edged', fontsize=fontSize)\n ax1.axis('off')\n\n ax2.imshow(closedImage)\n ax2.set_title('Closed', fontsize=fontSize)\n ax2.axis('off')\n \n ax3.imshow(finalImage)\n ax3.set_title('Final', fontsize=fontSize)\n ax3.axis('off') \n \n ax4.imshow(transformedImage)\n ax4.set_title('Transform', fontsize=fontSize)\n ax4.axis('off') \n\n ax5.imshow(edgedImage2)\n ax5.set_title('Edged 2', fontsize=fontSize)\n ax5.axis('off') \n \n ax6.imshow(closedImage2)\n ax6.set_title('Closed 2', fontsize=fontSize)\n ax6.axis('off') \n \n ax7.imshow(finalImage2)\n ax7.set_title('Final 2', fontsize=fontSize)\n ax7.axis('off')\n\n plt.show()\n\nif __name__ == '__main__':\n main()\n","sub_path":"Test15-contour-max-transform-contour.py","file_name":"Test15-contour-max-transform-contour.py","file_ext":"py","file_size_in_byte":5512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"283455526","text":"#!/usr/bin/python\n# coding: utf-8\n#\n# 此文件是此代理程序的配置文件,用于设置获取代理所访问的\n# url地址,测试代理是否可用所访问的地址,验证代理开辟线程\n# 的个数,超时时间等参数\n#\n\n#用于获取静态页面中代理的url及匹配模式\nstatic_target_urls = [\n ('http://blog.sina.com.cn/s/blog_5519064d0100y8nz.html', ':'),\n ('http://www.sooip.cn/zuixindaili/2012-05-15/2807.html', ' '),\n]\n\n#验证代理是否有效所访问的URL\nURL = 'http://news.baidu.com/'\n\n#超时时间\nTIME_OUT = 5\n\n#验证代理是否有效的线程个数\nVALID_THREAD_NUM = 100\n","sub_path":"proxy_getter_config.py","file_name":"proxy_getter_config.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"615662583","text":"'''This project was mediated through Michael Guerzhoy and is not \nto be copy and used for educational purposes which can lead to Academic Integrity'''\n\n# Importing Modules\nfrom pylab import *\nfrom _collections import defaultdict\n\n# Numpy Modules\nimport numpy as np\nfrom numpy.linalg import norm\n\n# Matplotlib Modules\nimport matplotlib.pyplot as plt\nimport matplotlib.cbook as cbook\nimport matplotlib.image as mpimg\n\n# Scipy Modules\nfrom scipy.misc import imread\nfrom scipy.misc import imresize\nfrom scipy.ndimage import filters\nfrom scipy.misc import imsave\n\n# Modules for reading images and for gradient creation\nimport random\nimport time\nimport os\nimport urllib\n\ndef rgb2gray(rgb):\n \n '''Return the grayscale version of the RGB image rgb as a 2D numpy array\n whose range is 0..1\n Arguments:\n rgb -- an RGB image, represented as a numpy array of size n x m x 3. The\n range of the values is 0..255\n '''\n r, g, b = rgb[:,:,0], rgb[:,:,1], rgb[:,:,2]\n gray = 0.2989 * r + 0.5870 * g + 0.1140 * b\n\n return gray/255.\n\n# Two actors used for linear-regression using one decision boundary\nact = ['Bill Hader','Steve Carell'] \n\ndef timeout(func, args=(), kwargs={}, timeout_duration=1, default=None):\n '''From:\n http://code.activestate.com/recipes/473878-timeout-function-using-threading/'''\n import threading\n class InterruptableThread(threading.Thread):\n def __init__(self):\n threading.Thread.__init__(self)\n self.result = None\n\n def run(self):\n try:\n self.result = func(*args, **kwargs)\n except:\n self.result = default\n\n it = InterruptableThread()\n it.start()\n it.join(timeout_duration)\n if it.isAlive():\n return False\n else:\n return it.result\n\ntestfile = urllib.URLopener() \n\n\n#Note: you need to create the uncropped folder first in order \n#for this to work\n\n# Empty arrays for TRAINING,TEST and VALIDATION \nTRAININGSET = {} \nTRAININGSET2 = []\nTESTSET = {}\nTESTSET2 = []\nVALIDATIONSET = {}\nVALIDATIONSET2 = []\n\nfor a in act:\n \n name = a.split()[1].lower()\n i = 0\n TRAININGSET2.append([])\n VALIDATIONSET2.append([]) \n TESTSET2.append([]) \n j = len(TRAININGSET2) - 1 \n \n for line in open(\"faces_subset.txt\"):\n if a in line:\n filename = name+str(i)+'.'+line.split()[4].split('.')[-1]\n \n #A version without timeout (uncomment in case you need to \n #unsupress exceptions, which timeout() does)\n #testfile.retrieve(line.split()[4], \"uncropped/\"+filename)\n #timeout is used to stop downloading images which take too long to download\n #print(line.split()[4])\n\n timeout(testfile.retrieve, (line.split()[4], \"uncropped/\"+filename), {}, 30)\n if not os.path.isfile(\"uncropped/\"+filename):\n continue \n \n try: \n im = imread(\"uncropped/\"+filename) \n k = line.split()[5]\n k2 = k.replace(',',' ')\n \n ''' cropping the image ''' \n \n \n im = im[int(k2.split()[1]):int(k2.split()[3]),int(k2.split()[0]):int(k2.split()[2])]\n im = imresize(im,(32,32))\n im = rgb2gray(im)\n \n imsave(\"cropped/\"+filename,im)\n \n ### MAKING OF TRAINING,TEST AND VAL. SET ###\n \n # TRAINING SET: (100 images per actor)\n \n if (i < 100):\n \n TRAININGSET['filename'] = im\n TRAININGSET2[j] = TRAININGSET2[j] + [np.reshape(TRAININGSET['filename'],(1,1024))]\n \n # VALIDATION SET: (100 images per actor: No image is the same as the Training set)\n elif (100 < i < 111):\n VALIDATIONSET['filename'] = im\n VALIDATIONSET2[j] = VALIDATIONSET2[j] + [np.reshape(VALIDATIONSET['filename'],(1,1024))]\n \n \n # TEST SET: (100 images per actor: No image is the same as Training and Val set)\n elif (111 < i < 122):\n TESTSET['filename'] = im \n TESTSET2[j] = TESTSET2[j] + [np.reshape(TESTSET['filename'],(1,1024))]\n \n else:\n pass \n \n print(filename)\n #print(i) \n #print('TRAININGSET'+ ' ' + name)\n i += 1\n except:\n pass\n\n###\n# Making of x and y and initial theta and alpha values\n\nx_temp = []\nx_tempVAL = []\nx_tempTEST = [] \ny_temp1 = np.ones((100,1))\ny_temp2 = np.zeros((100,1))\nx_p3 = np.array((200,1024))\nx_p3VAL=np.array((20,1024))\nx_p3TEST=np.array((20,1024)) \n\ny_p3 = np.array((200,1)) \ny_p3 = np.vstack((y_temp1,y_temp2))\n\ntheta0 = np.zeros((1,1025))\nh = 1e-4\n\nfor i in range(0,len(TRAININGSET2)):\n for j in range(0,len(TRAININGSET2[i])):\n x_temp = x_temp + [TRAININGSET2[i][j]]\n #print(x_temp) \n\nfor i in range(0,len(VALIDATIONSET2)):\n for j in range(0,len(VALIDATIONSET2[i])):\n x_tempVAL = x_tempVAL + [VALIDATIONSET2[i][j]]\n #print(x_tempVAL) \n\nfor i in range(0,len(TESTSET2)):\n for j in range(0,len(TESTSET2[i])):\n x_tempTEST = x_tempTEST + [TESTSET2[i][j]]\n #print(x_tempTEST) \n\n\n#Matrix of size(200,1024) containing the elements of the images \nx_p3 = np.vstack(x_temp) \nx_p3VAL = np.vstack(x_tempVAL)\nx_p3TEST = np.vstack(x_tempTEST)\nx_ones = np.ones((200,1))\nx_onesVAL = np.ones((20,1)) \nx_onesTEST = np.ones((20,1)) \nx_p3 = np.hstack((x_ones,x_p3))\nx_p3VAL = np.hstack((x_onesVAL,x_p3VAL)) \nx_p3TEST = np.hstack((x_onesTEST,x_p3TEST))\n# Confirming if dimensions is what is needed\n# print(x_p3)\n# print(x_p3.shape)\n# print(x_p3VAL) \n# print(x_p3VAL.shape)\n# print(x_p3TEST)\n# print(x_p3TEST.shape)\n###\n\n#PART 3: COMPARISON BETWEEN BILL HADER AND STEVE CAROLL\ndef f(x, y, theta):\n return (sum( (y.T - dot(theta,x.T)) ** 2)/(2*len(x)))\n\ndef df(x, y, theta):\n return -(1/200.)*sum((y.T-dot(theta, x.T))*x.T, 1)\n\n### \n#Using The Derivative of the Cost Function to Evaluate Grad. Descent To evaluate Theta.\n#J(theta0,...,thetaN) - alpha*grad(J(theta0,...,thetaN)) \n###\n\ndef grad_descent(df, x, y, init_t, alpha):\n '''Evaulating Gradient Descent''' \n EPS = 1e-10 #EPS = 10**(-5)\n prev_t = init_t-10*EPS\n t = init_t.copy()\n max_iter = 30000\n iter = 0\n while norm(t - prev_t) > EPS and iter < max_iter:\n prev_t = t.copy()\n t -= alpha*df(x, y, t)\n #print \"Iter\", iter\n #print \"x = (%.2f, %.2f, %.2f), f(x) = %.2f\" % (t[0], t[1], t[2], f(x, y, t)) \n #print \"Gradient: \", df(x, y, t), \"\\n\"\n iter += 1\n return t\n\ndef classifier(act,x,y,init_t,alpha,df,grad_descent,x_set):\n '''what we want to do is compute the value of the percentage between \n how well the theta was tuned in order for us to obtain the proper actor. \n if the hyptothesis gives a value greater than 0.5, it will be equal to an \n output of one. Otherwise, it will be zero.'''\n \n a = 0\n b = 0 \n theta = grad_descent(df, x, y, init_t, alpha)\n for i in range(0,len(x_set)):\n if i < (len(x_set)/2) and float(dot(theta,x_set[i].T)) > 0.5:\n a += 1 \n else:\n if i > (len(x_set)/2) and float(dot(theta,x_set[i].T)) < 0.5:\n b += 1\n print(act[0], float(a)/(len(x_set)/2))\n print(act[1], float(b)/(len(x_set)/2))\n return\n \n#NOTE: UNCOMMENT THE SECTIONS BELOW TO OBTAIN THE RESULTS FOR THE VALIDATION AND TEST SETS. \n\n# classifier(act,x_p3,y_p3,theta0,h,df,grad_descent,x_p3VAL)\n# classifier(act,x,y,init_t,alpha,df,grad_descent,x_p3TEST)\n \n# #PART 4:\n# #As we already have the theta's stored through the Grad.Descent Function, we will assign the variable \n# #And save the image within the working directory folder named part 4 \n# t_100 = grad_descent(df,x_p3,y_p3,theta0,h)\n# t_100 = np.delete(t_100,0)\n# t_100 = np.reshape(t_100,(32,32)) \n# imsave(\"part4/\"+filename,t_100) \n# #To create the array which contains the four images, two per actor, we will assign it to a\n# #variable called t_2 \n# t_2 = np.array((4,1025))\n# y_p3_2 = np.array((4,1)) \n# t_2 = np.vstack((x_p3[0],x_p3[1],x_p3[100],x_p3[101])) \n# y_temp1_2 = np.ones((2,1))\n# y_temp2_2 = np.zeros((2,1))\n# y_p3_2 = np.vstack((y_temp1_2,y_temp2_2))\n# t_2 = grad_descent(df,t_2,y_p3_2,theta0,h)\n# t_2 = np.delete(t_2,0) \n# t_2 = np.reshape(t_2,(32,32)) \n# imsave(\"part4/\"+filename,t_2) \n\n# PART 5: Demonstration of overfitting \n# First three actors are female (assign value y =1). The remaining three actors are of male \n# assign values y=0 \n\nactP5 =['Fran Drescher', 'America Ferrera', 'Kristin Chenoweth', 'Alec Baldwin', 'Bill Hader', 'Steve Carell']\nact_test = ['Lorraine Bracco', 'Peri Gilpin', 'Angie Harmon','Gerard Butler', 'Daniel Radcliffe', 'Michael Vartan']\n\n\nTRAININGSET_P5 = {} \nTRAININGSET2_P5 = []\nTESTSET_P5 = {}\nTESTSET2_P5 = []\nVALIDATIONSET_P5 = {}\nVALIDATIONSET2_P5 = []\n\nfor a in actP5:\n \n name = a.split()[1].lower()\n i = 0\n TRAININGSET2_P5.append([])\n VALIDATIONSET2_P5.append([]) \n TESTSET2_P5.append([]) \n j = len(TRAININGSET2_P5) - 1 \n \n for line in open(\"faces_subset.txt\"):\n if a in line:\n filename = name+str(i)+'.'+line.split()[4].split('.')[-1]\n \n #A version without timeout (uncomment in case you need to \n #unsupress exceptions, which timeout() does)\n #testfile.retrieve(line.split()[4], \"uncropped/\"+filename)\n #timeout is used to stop downloading images which take too long to download\n #print(line.split()[4])\n\n timeout(testfile.retrieve, (line.split()[4], \"uncropped/\"+filename), {}, 30)\n if not os.path.isfile(\"uncropped/\"+filename):\n continue \n \n try: \n im = imread(\"uncropped/\"+filename) \n k = line.split()[5]\n k2 = k.replace(',',' ')\n \n ''' cropping the image ''' \n \n \n im = im[int(k2.split()[1]):int(k2.split()[3]),int(k2.split()[0]):int(k2.split()[2])]\n im = imresize(im,(32,32))\n im = rgb2gray(im)\n \n ### PART 2: MAKING OF TRAINING,TEST AND VAL. SET ###\n \n # TRAINING SET: (100 images per actor)\n \n if (i < 100):\n TRAININGSET_P5['filename'] = im\n TRAININGSET2_P5[j] = TRAININGSET2_P5[j] + [np.reshape(TRAININGSET_P5['filename'],(1,1024))]\n\n \n # VALIDATION SET: (100 images per actor: (No image is the same as the Training set) \n elif (100 < i < 111):\n VALIDATIONSET_P5['filename'] = im\n VALIDATIONSET2_P5[j] = VALIDATIONSET2_P5[j] + [np.reshape(VALIDATIONSET_P5['filename'],(1,1024))]\n #print(VALIDATIONSET2[j]) \n \n # TESTSET: (100 images per actor: No image is the same as Training and Val set)\n \n elif (111 < i < 122):\n TESTSET_P5['filename'] = im \n TESTSET2_P5[j] = TESTSET2_P5[j] + [np.reshape(TESTSET_P5['filename'],(1,1024))]\n \n else:\n pass \n \n print(filename)\n i += 1\n \n except:\n pass\n\n#making of x and y and initial theta and alpha values\nx_temp_P5 = []\nx_tempVAL_P5 = []\nx_tempTEST_P5 = [] \ny_temp1_P5 = np.ones((300,1))\ny_temp2_P5 = np.zeros((300,1))\nx_p5= np.array((600,1024))\nx_p5VAL=np.array((60,1024))\nx_p5TEST=np.array((60,1024)) \n\ny_p5 = np.array((600,1)) \ny_p5 = np.vstack((y_temp1_P5,y_temp2_P5))\n\ntheta0 = np.zeros((1,1025))\nh = 1e-4\n\nfor i in range(0,len(TRAININGSET2_P5)):\n for j in range(0,len(TRAININGSET2_P5[i])):\n x_temp_P5 = x_temp_P5 + [TRAININGSET2_P5[i][j]]\n #print(x_temp) \n\nfor i in range(0,len(VALIDATIONSET2_P5)):\n for j in range(0,len(VALIDATIONSET2_P5[i])):\n x_tempVAL_P5 = x_tempVAL_P5 + [VALIDATIONSET2_P5[i][j]]\n #print(x_tempVAL) \n\nfor i in range(0,len(TESTSET2_P5)):\n for j in range(0,len(TESTSET2_P5[i])):\n x_tempTEST_P5 = x_tempTEST_P5 + [TESTSET2_P5[i][j]]\n #print(x_tempTEST) \n\n\n#Matrix of size(200,1024) containing the elements of the images \nx_p5 = np.vstack(x_temp_P5) \nx_p5VAL = np.vstack(x_tempVAL_P5)\nx_p5TEST = np.vstack(x_tempTEST_P5)\nx_ones_P5 = np.ones((600,1))\nx_onesVAL_P5 = np.ones((60,1)) \nx_onesTEST_P5 = np.ones((60,1)) \nx_p5 = np.hstack((x_ones_P5,x_p5))\nx_p5VAL = np.hstack((x_onesVAL_P5,x_p5VAL)) \nx_p5TEST = np.hstack((x_onesTEST_P5,x_p5TEST))\nprint(x_p5)\nprint(x_p5.shape)\nprint(x_p5VAL) \nprint(x_p5VAL.shape)\nprint(x_p5TEST)\nprint(x_p5TEST.shape)\n\n#For act_test\nTRAININGSET_P5_2 = {} \nTRAININGSET2_P5_2 = []\nfor a in act_test:\n name = a.split()[1].lower()\n #print(a)\n #print(name)\n i = 0\n TRAININGSET2_P5_2.append([])\n j = len(TRAININGSET2_P5_2) - 1 \n for line in open(\"faces_subsetP5.txt\"):\n if a in line:\n filename = name+str(i)+'.'+line.split()[4].split('.')[-1]\n \n #A version without timeout (uncomment in case you need to \n #unsupress exceptions, which timeout() does)\n #testfile.retrieve(line.split()[4], \"uncropped/\"+filename)\n #timeout is used to stop downloading images which take too long to download\n #print(line.split()[4])\n\n timeout(testfile.retrieve, (line.split()[4], \"uncropped2/\"+filename), {}, 30)\n if not os.path.isfile(\"uncropped2/\"+filename):\n continue \n \n try: \n im = imread(\"uncropped2/\"+filename) \n k = line.split()[5]\n k2 = k.replace(',',' ')\n \n ''' cropping the image ''' \n \n \n im = im[int(k2.split()[1]):int(k2.split()[3]),int(k2.split()[0]):int(k2.split()[2])]\n im = imresize(im,(32,32))\n im = rgb2gray(im)\n \n if (i < 100):\n TRAININGSET_P5_2['filename'] = im\n TRAININGSET2_P5_2[j] = TRAININGSET2_P5_2[j] + [np.reshape(TRAININGSET_P5_2['filename'],(1,1024))]\n #print(TRAININGSET2[j]) \n else:\n pass \n \n print(filename)\n\n i += 1\n except:\n pass\n\nx_temp_P5_2 = []\nx_p5_2= np.array((600,1024))\n\nfor i in range(0,len(TRAININGSET2_P5_2)):\n for j in range(0,len(TRAININGSET2_P5_2[i])):\n x_temp_P5_2 = x_temp_P5_2 + [TRAININGSET2_P5_2[i][j]]\n\nx_p5_2 = np.vstack(x_temp_P5_2) \nx_ones_P5_2 = np.ones((600,1))\nx_p5_2 = np.hstack((x_ones_P5_2,x_p5_2))\n\n\ndef classifier_P5(act,x,y,init_t,alpha,df,grad_descent,x_set):\n '''what we want to do is compute the value of the percentage between \n how well the theta was tuned in order for us to obtain the proper actor. \n if the hyptothesis gives a value greater than 0.5, it will be equal to an \n output of one. Otherwise, it will be zero.'''\n \n a = 0\n b = 0 \n theta = grad_descent(df, x, y, init_t, alpha)\n for i in range(0,len(x_set)):\n if i < (len(x_set)/2) and float(dot(theta,x_set[i].T)) > 0.5:\n a += 1 \n else:\n if i > (len(x_set)/2) and float(dot(theta,x_set[i].T)) < 0.5:\n b += 1\n print(\"female\", float(a)/(len(x_set)/2))\n print(\"male\", float(b)/(len(x_set)/2))\n return\n\n###\n# PART 6: ON HOT ENCODING\n# First we initialize for our output matrix. This will be of identity. \n# We use six actors for this part\n###\n\ny_p6 = np.array((0,0,0,0,0,0))\n\nfor i in range(len(x_p5)): #<----- making the y for part 6\n if i < 2:\n y_p6 = np.vstack((y_p6,[1,0,0,0,0,0]))\n \n elif 2 < i < 4:\n y_p6 = np.vstack((y_p6,[0,1,0,0,0,0]))\n \n elif 4 < i < 6:\n y_p6 = np.vstack((y_p6,[0,0,1,0,0,0]))\n \n elif 6 < i < 8:\n y_p6 = np.vstack((y_p6,[0,0,0,1,0,0]))\n \n elif 8 < i < 10:\n y_p6 = np.vstack((y_p6,[0,0,0,0,1,0]))\n \n else: \n y_p6 = np.vstack((y_p6,[0,0,0,0,0,1]))\n\ny_p6 = y_p6[1:,:]\n\ntheta_p6 = np.zeros((1025,6))\nh_p6 = 1e-6\n\n#h_p6 = 1e-6, eps = 1e-8 for 0.1315\n#h_p6 = 1e-6, eps = 1e-15 for 0.1315\n#h_p6 = 1e-7, eps = 1e-8 for 0.23371\n#h_p6 = 1e-10, eps = 1e-15 for 0.4159\n#h_p6 = 1e-8, eps = 1e-15 for 0.32719\n\ndef cost_matrix(x,y,theta):\n return float(sum(sum( (y.T - dot(theta.T,x.T)) ** 2),0))/(2*len(x))\n\ndef cost_matrix_2(x,y,theta):\n return float(sum(sum( (y.T - dot(theta.T,x.T)) ** 2),0))\n \ndef df_matrix(x,y,theta):\n return 2* dot(x.T,(dot(theta.T,x.T) - y.T).T)\n \ndef finite_difference(df_matrix,cost_matrix2,x,y,theta,h):\n #To evaluate the cost function, we use the fact of computing \n #finite differences: (f(x+h)-f(x))/h, where \"h\" is an arbitrary \n #small constant\n Fdiff = [ ] \n DFreal = (df_matrix(x,y,theta)).T\n for i in range(0,1025):\n Fdiff.append([]) \n for j in range(0,6):\n H = np.zeros((1025,6))\n H[i][j] = h\n Fdiff[i] = Fdiff[i] + [(cost_matrix2(x,y,theta + H) - cost_matrix2(x,y,theta)) / (h)]\n\n \n Fdiffnew = np.asarray(Fdiff)\n Fdiffnew = Fdiffnew.T\n Delta = norm((DFreal - Fdiffnew))\n return Delta\n \n\ndef grad_descent_matrix(df_matrix, x, y, init_t, alpha):\n #Evaulating Gradient Descent \n EPS = 1e-15 #EPS = 10**(-5)\n prev_t = init_t-10*EPS\n t = init_t.copy()\n max_iter = 100000\n iter = 0\n while norm(t - prev_t) > EPS and iter < max_iter:\n prev_t = t.copy()\n t -= alpha*df_matrix(x, y, t)\n #print \"Iter\", iter\n #print \"x = (%.2f, %.2f, %.2f), f(x) = %.2f\" % (t[0], t[1], t[2], f(x, y, t)) \n #print \"Gradient: \", df(x, y, t), \"\\n\"\n iter += 1\n return t\n\n#EPS = 1e-8, h = 1e-8 -> 0.62925\n#EPS = 1e-8, h = 1e-6 -> 0.2176\n\n#Part 7\nt_matrix = grad_descent_matrix(df_matrix, x_p5, y_p6, theta_p6, h_p6)\nt_matrix = t_matrix.T\n\nfor i in range(0,len(t_matrix)):\n t = np.delete(t_matrix[i],0) \n t = np.reshape(t,(32,32)) \n imsave(\"part4/\"+str(i)+filename,t)\n\n\n#Part 8 \ndef classifier_P8(act,x,y,init_t,alpha,df_matrix,grad_descent_matrix,x_set):\n #what we want to do is compute the value of the percentage between \n #how well the theta was tuned in order for us to obtain the proper actor. \n #if the hyptothesis gives a value greater than 0.5, it will be equal to an \n #output of one. Otherwise, it will be zero. \n a = 0\n b = 0\n c = 0 \n d = 0 \n e = 0 \n f = 0 \n theta = grad_descent_matrix(df_matrix, x, y, init_t, alpha)\n \n for i in range(0,len(x_set)):\n THETA_X = (dot(theta.T,x_set[i].T)) \n if (0 < i < 10) and np.amax(THETA_X) == THETA_X[0]:\n a += 1\n elif (10 < i < 20) and np.amax(THETA_X) == THETA_X[1]:\n b += 1 \n elif (20 < i < 30) and np.amax(THETA_X) == THETA_X[2]:\n c += 1\n elif (30 < i < 40) and np.amax(THETA_X) == THETA_X[3]:\n d += 1\n elif (40 < i < 50) and np.amax(THETA_X) == THETA_X[4]:\n e += 1\n elif (50 < i < 60) and np.amax(THETA_X) == THETA_X[5]:\n f += 1\n else:\n pass\n \n print(actP5[0], float(a)/(len(x_set)/len(actP5)))\n print(actP5[1], float(b)/(len(x_set)/len(actP5)))\n print(actP5[2], float(c)/(len(x_set)/len(actP5)))\n print(actP5[3], float(d)/(len(x_set)/len(actP5)))\n print(actP5[4], float(e)/(len(x_set)/len(actP5)))\n print(actP5[5], float(f)/(len(x_set)/len(actP5)))\n \n return\n\n### RESULTS\n\n# cost of 0.072330384\n# On Validation \n# ('Fran Drescher', 0.9)\n# ('America Ferrera', 0.8)\n# ('Kristin Chenoweth', 0.8)\n# ('Alec Baldwin', 0.8)\n# ('Bill Hader', 0.9)\n# ('Steve Carell', 0.7)\n\n# On Test Set\n# ('Fran Drescher', 0.7)\n# ('America Ferrera', 0.5)\n# ('Kristin Chenoweth', 0.8)\n# ('Alec Baldwin', 0.7)\n# ('Bill Hader', 0.6)\n# ('Steve Carell', 0.7)\n\n###\n\n\n\n\n\n\n","sub_path":"faces.py","file_name":"faces.py","file_ext":"py","file_size_in_byte":20258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"279299248","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport datetime\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('civilireports', '0004_auto_20141115_1700'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='report',\n name='date_finished',\n field=models.DateTimeField(null=True, verbose_name=b'date finished', blank=True),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='report',\n name='date_in_progress',\n field=models.DateTimeField(null=True, verbose_name=b'date in progress', blank=True),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='report',\n name='date_of_report',\n field=models.DateTimeField(default=datetime.datetime(2014, 11, 15, 19, 6, 43, 11063), verbose_name=b'date of report'),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='report',\n name='feedback_method',\n field=models.CharField(blank=True, max_length=255, null=True, verbose_name=b'feedback method', choices=[(b'text', b'text message/sms'), (b'call', b'phone call'), (b'email', b'mail')]),\n preserve_default=True,\n ),\n ]\n","sub_path":"civili/civilireports/migrations/0005_auto_20141115_1906.py","file_name":"0005_auto_20141115_1906.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"579679793","text":"# Attempt to test the funky poll patch in modussl_mbedtls, but sadly this works\n# without the patch...\n\ntry:\n import uasyncio as asyncio, ussl as ssl\nexcept ImportError:\n try:\n import asyncio, ssl\n except ImportError:\n print(\"SKIP\")\n raise SystemExit\n\n\n# open a connection and start by reading, not writing\nasync def read_first(host, port):\n reader, writer = await asyncio.open_connection(host, port, ssl=True)\n\n print(\"read something\")\n inbuf = b\"\"\n while len(inbuf) < 20:\n try:\n b = await reader.read(100)\n except OSError as e:\n if e.args[0] < -120:\n print(\"read SSL error -%x : %s\" % (-e.args[0], ssl.errstr(e.args[0])))\n raise OSError(e.args[0], bytes.decode(ssl.errstr(e.args[0])))\n else:\n print(\"read OSError: %d / -%x\" % (e.args[0], -e.args[0]))\n raise\n print(\"read:\", b)\n if b is None:\n continue\n elif len(b) == 0:\n print(\"EOF\")\n break\n elif len(b) > 0:\n inbuf += b\n else:\n raise ValueError(\"negative length returned by recv\")\n\n print(\"close\")\n writer.close()\n await writer.wait_closed()\n print(\"done\")\n\n\nasyncio.run(read_first(\"aspmx.l.google.com\", 25))\n","sub_path":"tests/net_inet/uasyncio_ssl.py","file_name":"uasyncio_ssl.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"365413147","text":"\"\"\"\nDefinition of views.\n\"\"\"\n\nfrom django.contrib import admin\nfrom django.contrib.auth import login, authenticate\nfrom django.core.paginator import Paginator\nfrom django.forms import formset_factory\nfrom django.forms import inlineformset_factory, BaseInlineFormSet, modelformset_factory\nfrom django.http import JsonResponse, HttpResponseRedirect, HttpResponse, HttpRequest\nfrom django.shortcuts import get_object_or_404, render, redirect\nfrom django.template import RequestContext\nfrom django.template.loader import render_to_string\nfrom django.urls import reverse, reverse_lazy\nfrom django.views.generic import ListView, View, DetailView, FormView\nfrom django.views.decorators.csrf import csrf_exempt\nfrom datetime import datetime\n\nfrom doubenfi.settings import APP_PREFIX\nfrom doubenfi.utils import ErrHandle\nfrom doubenfi.finance.models import *\nfrom doubenfi.finance.forms import ProjectForm, OrganizationForm, UploadFileForm, TransGroupForm, TransactionForm, SearchForm, AccountForm\nfrom doubenfi.finance.excel import export_xlsx, export_auditfile, balance_xlsx\n\n# ============================= LOCAL CLASSES ======================================\nerrHandle = ErrHandle()\npaginateEntries = 20\npaginateTgroups = 12 # 12 Transaction Groups in one page\n\n# ============================= Convert complex account string to just number ======\ndef get_account_number(account_in):\n iNumber = -1\n if \":\" in account_in:\n iNumber = int(account_in.split(\":\")[0].strip())\n elif account_in != \"\":\n iNumber = int(account_in)\n return iNumber\n\ndef get_user_project(username):\n \"\"\"Get the project that is currently associated with this user\"\"\"\n\n # Find this user\n if username != None and username != \"\":\n # Find the user\n user = User.objects.filter(username=username).first()\n if user != None:\n # Try to get the personal information of this user\n personal = Personal.objects.filter(user=user).first()\n # Check if there is personal info\n if personal != None:\n # User has project: get it out\n return personal.project.id\n # In all other cases: we did not find the requested information\n return None\n\ndef set_user_project(username, project):\n \"\"\"Associate the user with the project\"\"\"\n\n # Find this user\n if username != None and username != \"\":\n # Find the user\n user = User.objects.filter(username=username).first()\n if user != None:\n # Try to get the personal information of this user\n personal = Personal.objects.filter(user=user).first()\n # Check if there is personal info\n if personal == None:\n personal = Personal(user=user)\n # Set user project\n personal.project = project\n # ANd save it\n personal.save()\n return True\n # In all other cases: we failed\n return False\n\n\n# ============================= Home, Contact, About ===============================\ndef home(request):\n \"\"\"Renders the home page.\"\"\"\n\n # Make sure this is the correct request\n assert isinstance(request, HttpRequest)\n template_name = 'index.html'\n # Figure out who we are\n username = \"\" if request.user == None else request.user.username\n # Try get current project\n project_id = get_user_project(username)\n\n # Create a context\n context = dict(title='Double-Entry Finances', \n year=datetime.now().year, \n pfx=APP_PREFIX, \n project_id=project_id,\n site_url=admin.site.site_url)\n # REturn the response\n return render( request, template_name, context)\n\ndef contact(request):\n \"\"\"Renders the contact page.\"\"\"\n assert isinstance(request, HttpRequest)\n return render( request, 'contact.html',\n {\n 'title':'Contact',\n 'message':'Erwin Komen (app creator)',\n 'year':datetime.now().year,\n }\n )\n\ndef about(request):\n \"\"\"Renders the about page.\"\"\"\n assert isinstance(request, HttpRequest)\n return render( request, 'about.html',\n {\n 'title':'About',\n 'message':'Double Entry Finance utility',\n 'year':datetime.now().year,\n }\n )\n\ndef nlogin(request):\n \"\"\"Renders the not-logged-in page.\"\"\"\n assert isinstance(request, HttpRequest)\n return render(\n request,\n 'nlogin.html',\n {\n 'title':'Not logged in',\n 'message':'Mangoboom Finance utility',\n 'year':datetime.now().year,\n }\n )\n\n\nclass BasicJson(View):\n # Initialisations: \n arErr = [] # errors \n template_name = None # The template to be used\n template_err_view = None\n form_validated = True # Used for POST form validation\n savedate = None # When saving information, the savedate is returned in the context\n add = False # Are we adding a new record or editing an existing one?\n obj = None # The instance of the MainModel\n action = \"\" # The action to be undertaken\n MainModel = None # The model that is mainly used for this form\n form_objects = [] # List of forms to be processed\n formset_objects = [] # List of formsets to be processed\n bDebug = False # Debugging information\n data = {'status': 'ok', 'html': ''} # Create data to be returned \n \n def post(self, request, object_id=None):\n # A POST request means we are trying to SAVE something\n self.initializations(request, object_id)\n\n if self.checkAuthentication(request):\n # Build the context\n context = dict(object_id = object_id, savedate=None)\n # Action depends on 'action' value\n if self.action == \"\" or self.action == \"account_save\" or self.action == \"account_existing\" or \"_save_\" in self.action:\n if self.bDebug: self.oErr.Status(\"BasicJson: action=\" + self.action)\n\n # Some actions require special treatment\n\n # Walk all the forms for preparation of the formObj contents\n for formObj in self.form_objects:\n # Are we SAVING a NEW item?\n if self.add:\n # We are saving a NEW item\n formObj['forminstance'] = formObj['form'](request.POST, prefix=formObj['prefix'])\n else:\n # We are saving an EXISTING item\n # Determine the instance to be passed on\n instance = self.get_instance(formObj['prefix'])\n # Make the instance available in the form-object\n formObj['instance'] = instance\n # Get an instance of the form\n formObj['forminstance'] = formObj['form'](request.POST, prefix=formObj['prefix'], instance=instance)\n\n # Initially we are assuming this just is a review\n context['savedate']=\"reviewed at {}\".format(datetime.now().strftime(\"%X\"))\n\n # Iterate again\n for formObj in self.form_objects:\n prefix = formObj['prefix']\n # Adapt if it is not readonly\n if not formObj['readonly']:\n # Check validity of form\n if formObj['forminstance'].is_valid():\n # Save it preliminarily\n instance = formObj['forminstance'].save(commit=False)\n # The instance must be made available (even though it is only 'preliminary')\n formObj['instance'] = instance\n # Perform actions to this form BEFORE FINAL saving\n bNeedSaving = formObj['forminstance'].has_changed()\n if self.before_save(prefix, request, instance=instance, form=formObj['forminstance'] ):\n bNeedSaving = True\n if formObj['forminstance'].instance.id == None: bNeedSaving = True\n if bNeedSaving:\n # Perform the saving\n instance.save()\n # Set the context\n context['savedate']=\"saved at {}\".format(datetime.now().strftime(\"%X\"))\n # Put the instance in the form object\n formObj['instance'] = instance\n # Store the instance id in the data\n self.data[prefix + '_instanceid'] = instance.id\n # Any action after saving this form\n self.after_save(prefix, instance)\n else:\n self.arErr.append(formObj['forminstance'].errors)\n self.form_validated = False\n\n # Add instance to the context object\n context[prefix + \"Form\"] = formObj['forminstance']\n # Walk all the formset objects\n for formsetObj in self.formset_objects:\n formsetClass = formsetObj['formsetClass']\n prefix = formsetObj['prefix']\n form_kwargs = self.get_form_kwargs(prefix)\n if self.add:\n # Saving a NEW item\n formset = formsetClass(request.POST, request.FILES, prefix=prefix, form_kwargs = form_kwargs)\n else:\n # Saving an EXISTING item\n instance = self.get_instance(prefix)\n qs = self.get_queryset(prefix)\n if qs == None:\n formset = formsetClass(request.POST, request.FILES, prefix=prefix, instance=instance, form_kwargs = form_kwargs)\n else:\n formset = formsetClass(request.POST, request.FILES, prefix=prefix, instance=instance, queryset=qs, form_kwargs = form_kwargs)\n # Process all the forms in the formset\n self.process_formset(prefix, request, formset)\n # Store the instance\n formsetObj['formsetinstance'] = formset\n # Adapt the formset contents only, when it is NOT READONLY\n if not formsetObj['readonly']:\n # Is the formset valid?\n if formset.is_valid():\n # Make sure all changes are saved in one database-go\n with transaction.atomic():\n # Walk all the forms in the formset\n for form in formset:\n # At least check for validity\n if form.is_valid():\n # Should we delete?\n if form.cleaned_data['DELETE']:\n # Delete this one\n form.instance.delete()\n # NOTE: the template knows this one is deleted by looking at form.DELETE\n # form.delete()\n else:\n # Check if anything has changed so far\n has_changed = form.has_changed()\n # Save it preliminarily\n instance = form.save(commit=False)\n # Any actions before saving\n if self.before_save(prefix, request, instance, form):\n has_changed = True\n # Save this construction\n if has_changed: \n # Save the instance\n instance.save()\n # Adapt the last save time\n context['savedate']=\"saved at {}\".format(datetime.now().strftime(\"%X\"))\n # Store the instance id in the data\n self.data[prefix + '_instanceid'] = instance.id\n else:\n self.arErr.append(form.errors)\n else:\n self.arErr.append(formset.errors)\n # Add the formset to the context\n context[prefix + \"_formset\"] = formset\n\n if \"_save_\" in self.action:\n # just return the correct information already gathered\n return JsonResponse(self.data)\n elif self.action == \"delete\":\n # We are supposed to delete this one and then return positively\n transactions = self.obj.group_transactions.all()\n transactions.delete()\n # remove myself\n self.obj.delete()\n self.data['status'] = \"ok\"\n self.data['html'] = \"deleted object\"\n # Return the information\n return JsonResponse(self.data)\n elif self.action == \"delete_obj\":\n # remove myself\n self.obj.delete()\n self.data['status'] = \"ok\"\n self.data['html'] = \"deleted object\"\n # Return the information\n return JsonResponse(self.data)\n elif self.action == \"download\":\n # There is another action\n return self.perform_download()\n elif self.action == \"navigate\":\n # Perform custom navigation\n self.data['id'] = self.get_navigate()\n # Return the information\n return JsonResponse(self.data)\n elif self.action == \"tgroup_next\" or self.action == \"tgroup_prev\":\n ## No need to save -- just return the correct instanceid\n #instanceid = self.get_navigate()\n #self.data['instanceid'] = instanceid\n #self.data['openurl'] = self.get_openurl(instanceid)\n # Return the information\n return JsonResponse(self.data)\n\n # Allow user to add to the context\n context = self.add_to_context(context)\n\n # Make sure we have a list of any errors\n error_list = [str(item) for item in self.arErr]\n context['error_list'] = error_list\n context['errors'] = self.arErr\n if len(self.arErr) > 0:\n self.data['has_errors'] = True\n # self.data['status'] = \"error\"\n else:\n self.data['has_errors'] = False\n # Standard: add request user to context\n context['requestuser'] = request.user\n\n # Get the HTML response\n if len(self.arErr) > 0:\n if self.template_err_view != None:\n # Create a list of errors\n self.data['err_view'] = render_to_string(self.template_err_view, context, request)\n else:\n self.data['err_view'] = error_list\n self.data['html'] = ''\n else:\n self.data['html'] = render_to_string(self.template_name, context, request)\n else:\n self.data['html'] = \"Please log in before continuing\"\n\n # Return the information\n return JsonResponse(self.data)\n \n def get(self, request, object_id=None): \n # Perform the initializations that need to be made anyway\n self.initializations(request, object_id)\n if self.checkAuthentication(request):\n context = dict(object_id = object_id, savedate=None)\n\n if self.action == \"\":\n # Walk all the form objects\n for formObj in self.form_objects: \n # Used to populate a NEW research project\n # - CREATE a NEW research form, populating it with any initial data in the request\n initial = dict(request.GET.items())\n if self.add:\n # Create a new form\n formObj['forminstance'] = formObj['form'](initial=initial, prefix=formObj['prefix'])\n else:\n # Used to show EXISTING information\n instance = self.get_instance(formObj['prefix'])\n # We should show the data belonging to the current Research [obj]\n formObj['forminstance'] = formObj['form'](instance=instance, prefix=formObj['prefix'])\n # Add instance to the context object\n context[formObj['prefix'] + \"Form\"] = formObj['forminstance']\n # Walk all the formset objects\n for formsetObj in self.formset_objects:\n formsetClass = formsetObj['formsetClass']\n prefix = formsetObj['prefix']\n form_kwargs = self.get_form_kwargs(prefix)\n if self.add:\n # - CREATE a NEW formset, populating it with any initial data in the request\n initial = dict(request.GET.items())\n # Creating a NEW item\n formset = formsetClass(initial=initial, prefix=prefix, form_kwargs=form_kwargs)\n else:\n # show the data belonging to the current [obj]\n instance = self.get_instance(prefix)\n qs = self.get_queryset(prefix)\n if qs == None:\n formset = formsetClass(prefix=prefix, instance=instance, form_kwargs=form_kwargs)\n else:\n formset = formsetClass(prefix=prefix, instance=instance, queryset=qs, form_kwargs=form_kwargs)\n # Process all the forms in the formset\n ordered_forms = self.process_formset(prefix, request, formset)\n if ordered_forms:\n context[prefix + \"_ordered\"] = ordered_forms\n # Store the instance\n formsetObj['formsetinstance'] = formset\n # Add the formset to the context\n context[prefix + \"_formset\"] = formset\n elif self.action == \"download\":\n # There is another action\n return self.perform_download()\n elif self.action == \"navigate\":\n # Perform custom navigation\n self.data['id'] = self.get_navigate()\n # Return the information\n return JsonResponse(self.data)\n\n # Allow user to add to the context\n context = self.add_to_context(context)\n # Make sure we have a list of any errors\n error_list = [str(item) for item in self.arErr]\n context['error_list'] = error_list\n context['errors'] = self.arErr\n # Standard: add request user to context\n context['requestuser'] = request.user\n \n # Get the HTML response\n self.data['html'] = render_to_string(self.template_name, context, request)\n # x = context['arg_formset'][0].instance.functionparent.all()[0].parent_id\n else:\n self.data['html'] = \"Please log in before continuing\"\n\n # Return the information\n return JsonResponse(self.data)\n \n def checkAuthentication(self,request):\n # first check for authentication\n if not request.user.is_authenticated:\n # Simply redirect to the home page\n self.data['html'] = \"Please log in to work on a research project\"\n return False\n else:\n return True\n\n def initializations(self, request, object_id):\n # Clear errors\n self.arErr = []\n # COpy the request\n self.request = request\n # Copy any object id\n self.object_id = object_id\n self.add = object_id is None\n # Get the parameters\n if request.POST:\n self.qd = request.POST\n else:\n self.qd = request.GET\n\n # Check if self.qd contains an action\n if 'action' in self.qd and self.action == \"\":\n self.action = self.qd.get('action', '')\n\n # Find out what the Main Model instance is, if any\n if self.add:\n self.obj = None\n # TEST: Perform some custom initialisations\n self.custom_init()\n else:\n # Get the instance of the Main Model object\n self.obj = self.MainModel.objects.filter(pk=object_id).first()\n # NOTE: if the object doesn't exist, we will NOT get an error here\n # Perform some custom initialisations\n self.custom_init()\n\n def get_instance(self, prefix):\n return self.obj\n\n def get_queryset(self, prefix):\n return None\n\n def get_navigate(self):\n return -1\n\n def get_openurl(self, instanceid):\n return \"\"\n\n def perform_download(self):\n # Getting here means that the user has not defined a download\n self.data['html'] = \"Please define a perform_download() function for this view\"\n # Return the information\n return JsonResponse(self.data)\n\n def get_form_kwargs(self, prefix):\n return None\n\n def before_save(self, prefix, request, instance=None, form=None):\n return False\n\n def after_save(self, prefix, instance=None):\n return True\n\n def add_to_context(self, context):\n return context\n\n def process_formset(self, prefix, request, formset):\n return None\n\n def custom_init(self):\n pass\n \n\nclass TransactionListORG(ListView):\n \"\"\"List all the transactions of the indicated year *within its own project*\"\"\"\n\n model = Transaction\n year = '2017'\n acct = None\n person = None\n action = \"\"\n queryset = None\n project = None\n template_name = 'finance/transactions.html'\n paginate_by = paginateEntries\n transcount = 0\n\n def get(self, request, *args, **kwargs):\n # Consider everything that is in [kwargs]\n if 'year' in kwargs:\n self.year = kwargs['year']\n if 'acct' in kwargs:\n self.acct = kwargs['acct']\n # THe [pk] is of the particular PROJECT instance\n if 'pk' in kwargs:\n pk = int(kwargs['pk'])\n self.project = Project.objects.filter(pk=pk).first()\n # Derive the YEAR from this PROJECT\n self.year = self.project.year\n\n # Consider additional information in request.GET\n if 'person' in request.GET:\n person_id = request.GET['person']\n self.person = Person.objects.filter(id=person_id).first()\n if 'action' in request.GET:\n self.action = request.GET['action']\n\n # Perform the default initializations\n return super(TransactionList, self).get(request, *args, **kwargs)\n\n def get_queryset(self):\n \"\"\"Get the transactions for the indicated year\"\"\"\n\n # Get the correct project\n if self.project == None:\n iYear = int(self.year)\n # Use the default organization: mangoboom\n project = Project.get_project(\"De Mangoboom\", iYear)\n self.project = project\n\n # Check if we just need all the transactions or only some\n if self.acct == None:\n if self.project == None:\n # Look at the action\n if self.action == None or self.action == 'xml':\n qs = self.project.transactions.all()\n else:\n # Need to look at all the groups\n qs = self.project.transactions.filter(Q(debet=None) | Q(credit=None)).order_by('tgroup__group', 'tgroup__batch', 'tgroup__date')\n else:\n # Listing all transactions of a person\n qs = self.project.transactions.filter(Q(person=self.person)).order_by('tgroup__group', 'tgroup__batch', 'tgroup__date')\n else:\n qs = self.project.transactions.filter(Q(account__number=self.acct))\n if self.acct == \"1210\":\n qs = qs.order_by('tgroup__date', 'tgroup__doc')\n else:\n qs = qs.order_by('tgroup__date', 'tgroup__batch', \"tgroup__doc\")\n # Make sure the related are available too\n qs = qs.select_related()\n self.transcount = qs.count()\n self.queryset = qs\n return qs\n \n def render_to_response(self, context, **response_kwargs):\n # Make sure we get the user and check the authentication\n currentuser = self.request.user\n context['authenticated'] = currentuser.is_authenticated()\n context['transcount'] = self.transcount\n context['intro_breadcrumb'] = \"{}/{}\".format(self.project.org.name, self.project.year)\n\n if self.acct != None:\n context['account'] = self.project.accounts.filter(Q(number=self.acct)).first()\n\n # What is the action we should take?\n if self.action == \"download\":\n if self.acct == None:\n if self.person == None:\n sFileName = \"{}-{}\".format(self.project.org.name.replace(\" \", \"_\"), self.project.year)\n else:\n sFileName = \"{}-{}-{}\".format(self.project.org.name.replace(\" \", \"_\"), self.project.year, self.person.id)\n else:\n sFileName = \"{}-{}_{}\".format(self.project.org.name.replace(\" \", \"_\"), self.project.year, self.acct)\n return export_xlsx(self.queryset, sFileName, Transaction.get_outputColumns())\n elif self.action == \"checks\":\n sFileName = \"{}-{}_checks\".format(self.project.org.name.replace(\" \", \"_\"), self.project.year)\n return export_xlsx(self.queryset, sFileName, Transaction.get_outputColumns())\n elif self.action == \"xml\":\n # Export as auditfile xml\n sFileName = \"{}-{}\".format(self.project.org.name.replace(\" \", \"_\"), self.project.year)\n return export_auditfile(self.project, self.queryset, sFileName, context)\n else:\n # Just return a rendered response\n return super(TransactionList, self).render_to_response(context, **response_kwargs)\n\n\nclass TransactionList(ListView):\n \"\"\"List all the transactions of the indicated year *within its own project*\"\"\"\n\n model = Transaction\n year = '2017'\n acct = None\n person = None\n action = \"\"\n queryset = None\n project = None\n template_name = 'finance/project_detail.html'\n template_insert = 'finance/transaction_list.html'\n paginate_by = paginateEntries\n transcount = 0\n\n def get(self, request, *args, **kwargs):\n # Consider everything that is in [kwargs]\n if 'year' in kwargs:\n self.year = kwargs['year']\n if 'acct' in kwargs:\n self.acct = kwargs['acct']\n # THe [pk] is of the particular PROJECT instance\n if 'pk' in kwargs:\n pk = int(kwargs['pk'])\n self.project = Project.objects.filter(pk=pk).first()\n # Derive the YEAR from this PROJECT\n self.year = self.project.year\n\n # Consider additional information in request.GET\n if 'person' in request.GET:\n person_id = request.GET['person']\n self.person = Person.objects.filter(id=person_id).first()\n if 'action' in request.GET:\n self.action = request.GET['action']\n\n # Perform the default initializations\n return super(TransactionList, self).get(request, *args, **kwargs)\n\n def get_queryset(self):\n \"\"\"Get the transactions for the indicated year\"\"\"\n\n # Get the correct project\n if self.project == None:\n iYear = int(self.year)\n # Use the default organization: mangoboom\n project = Project.get_project(\"De Mangoboom\", iYear)\n self.project = project\n\n # Check if we just need all the transactions or only some\n if self.acct == None:\n if self.project == None:\n # Look at the action\n if self.action == None or self.action == 'xml':\n qs = self.project.transactions.all()\n else:\n # Need to look at all the groups\n qs = self.project.transactions.filter(Q(debet=None) | Q(credit=None)).order_by('tgroup__group', 'tgroup__batch', 'tgroup__date')\n else:\n # Listing all transactions of a person\n qs = self.project.transactions.filter(Q(person=self.person)).order_by('tgroup__group', 'tgroup__batch', 'tgroup__date')\n else:\n qs = self.project.transactions.filter(Q(account__number=self.acct))\n if self.acct == \"1210\":\n qs = qs.order_by('tgroup__date', 'tgroup__doc')\n else:\n qs = qs.order_by('tgroup__date', 'tgroup__batch', \"tgroup__doc\")\n # Make sure the related are available too\n qs = qs.select_related()\n self.transcount = qs.count()\n self.queryset = qs\n return qs\n \n def render_to_response(self, context, **response_kwargs):\n # Make sure we get the user and check the authentication\n currentuser = self.request.user\n context['authenticated'] = currentuser.is_authenticated()\n context['transcount'] = self.transcount\n context['intro_breadcrumb'] = \"{}/{}\".format(self.project.org.name, self.project.year)\n context['org'] = \"mangoboom\" if (\"mangoboom\" in self.project.org.name.lower()) else \"komen\"\n lGroups = [x.name for x in currentuser.groups.all()]\n context['mayseeproject'] = context['org'] in lGroups\n context['object_id'] = self.project.id\n context['project_id'] = self.obj.id\n\n if self.acct != None:\n context['account'] = self.project.accounts.filter(Q(number=self.acct)).first()\n\n # What is the action we should take?\n if self.action == \"download\":\n if self.acct == None:\n if self.person == None:\n sFileName = \"{}-{}\".format(self.project.org.name.replace(\" \", \"_\"), self.project.year)\n else:\n sFileName = \"{}-{}-{}\".format(self.project.org.name.replace(\" \", \"_\"), self.project.year, self.person.id)\n else:\n sFileName = \"{}-{}_{}\".format(self.project.org.name.replace(\" \", \"_\"), self.project.year, self.acct)\n return export_xlsx(self.queryset, sFileName, Transaction.get_outputColumns())\n elif self.action == \"checks\":\n sFileName = \"{}-{}_checks\".format(self.project.org.name.replace(\" \", \"_\"), self.project.year)\n return export_xlsx(self.queryset, sFileName, Transaction.get_outputColumns())\n elif self.action == \"xml\":\n # Export as auditfile xml\n sFileName = \"{}-{}\".format(self.project.org.name.replace(\" \", \"_\"), self.project.year)\n return export_auditfile(self.project, self.queryset, sFileName, context)\n\n # Getting here means that the action is: list the transactions\n\n # Define other context variables\n context['hitcount'] = context['object_list'].count()\n context['project_transactions'] = render_to_string(self.template_insert, context, self.request)\n\n # Just return a rendered response\n return super(TransactionList, self).render_to_response(context, **response_kwargs)\n\n\nclass TransactionDetails(BasicJson):\n MainModel = Transaction\n template_name = 'finance/transaction_details.html'\n queryset = None\n year = ''\n project = None\n\n def get_object(self, queryset = None):\n self.obj = super(TransactionDetails, self).get_object(queryset)\n self.project = self.obj.project\n self.year = self.obj.project.year\n return self.obj\n\n def render_to_response(self, context, **response_kwargs):\n # Make sure we get the user and check the authentication\n currentuser = self.request.user\n context['authenticated'] = currentuser.is_authenticated()\n context['intro_breadcrumb'] = \"{}/{}\".format(self.project.org.name, context['object'].year)\n context['object_id'] = self.obj.id\n context['project_id'] = self.obj.id\n context['org'] = self.project.org.name\n return super(TransactionDetails, self).render_to_response(context, **response_kwargs)\n\n\nclass ProjectDetailView(DetailView):\n model = Project\n template_name = 'finance/project_detail.html'\n year = '2017'\n queryset = None\n\n def get(self, request, *args, **kwargs):\n if 'year' in kwargs:\n self.year = kwargs['year']\n return super(ProjectDetailView, self).get(request, *args, **kwargs)\n\n def get_object(self, queryset = None):\n # REtrieve the year\n # self.queryset = Project.ojbects.filter(\n self.obj = super(ProjectDetailView, self).get_object(queryset)\n return self.obj\n\n def render_to_response(self, context, **response_kwargs):\n # Make sure we get the user and check the authentication\n currentuser = self.request.user\n context['authenticated'] = currentuser.is_authenticated()\n context['intro_breadcrumb'] = \"{}/{}\".format(context['object'].org.name, context['object'].year)\n context['object_id'] = self.obj.id\n context['project_id'] = self.obj.id\n context['has_synchronisation'] = (self.obj != None and self.obj.vault != None)\n context['import_form'] = UploadFileForm()\n context['org'] = \"mangoboom\" if (\"Mangoboom\" in context['object'].org.name) else \"komen\"\n context['searchForm'] = SearchForm()\n lGroups = [x.name for x in currentuser.groups.all()]\n context['mayseeproject'] = context['org'] in lGroups\n\n # Make sure we associate the user with this project\n if currentuser:\n set_user_project(currentuser.username, self.obj)\n\n return super(ProjectDetailView, self).render_to_response(context, **response_kwargs)\n\n\nclass ProjectBasicJson(BasicJson):\n \"\"\"JSON-producing view for project basics\"\"\"\n\n template_name = 'finance/project_basic.html'\n MainModel = Project\n form_objects = [{'form': ProjectForm, 'prefix': 'project', 'readonly': False},\n {'form': OrganizationForm, 'prefix': 'organization', 'readonly': False}]\n\n def get_instance(self, prefix):\n if prefix == 'project':\n return self.obj\n elif prefix == 'organization':\n return self.obj.org\n\n\nclass ProjectResultJson(BasicJson):\n \"\"\"JSON-producing view for project results\"\"\"\n\n template_name = 'finance/project_result.html' # Die moet ik nog wel aanpassen\n MainModel = Project\n\n def get_instance(self, prefix):\n if prefix == 'project':\n self.project = self.obj\n return self.obj\n\n def add_to_context(self, context):\n # Make sure we have the right project\n self.project = self.obj\n context['project'] = self.project\n\n # Make sure we get the user and check the authentication\n currentuser = self.request.user\n context['authenticated'] = currentuser.is_authenticated()\n\n # Determine start and end date\n context['date_start'] =\"01/01/{}\".format(self.project.year)\n context['date_end'] = \"31/12/{}\".format(self.project.year)\n\n # Determine the assets and liabilities lists\n reservering_list = []\n for list_type in ['assets', 'liabilities']:\n balance = choice_value(BALANCE_TYPE, list_type)\n qs = self.project.accounts.filter(Q(balance=balance)).order_by('number')\n\n item_list = []\n amount_start = 0.0\n amount_end = 0.0\n lstQ = [None, None]\n for account in qs:\n oItem = {}\n oItem['account'] = account\n oItem['balance_start'] = account.saldo\n amount_start += account.saldo\n totaal = account.saldo\n\n # Calculate ending balance\n if list_type == 'assets':\n # For assets: debet minus credit\n qsa = self.project.transactions.filter(Q(account=account) & Q(side='cr'))\n for transaction in qsa:\n totaal -= transaction.amount\n qsa = self.project.transactions.filter(Q(account=account) & Q(side='db'))\n for transaction in qsa:\n totaal += transaction.amount\n elif list_type == \"liabilities\":\n # Calculate the ending balance of liabilities\n # Do this by looking at all the transactions attached to a particular purpose\n reservering = account.reservering\n lstQ = [None]\n # Double check if the purpose has already been treated\n if not reservering in reservering_list:\n # Purpose has not yet been treated: add it to the list\n reservering_list.append(reservering)\n # For liabilities: credit minus debet\n # lstQ[0] = Q(credit__reservering=reservering)\n lstQ[0] = Q(side='cr') & Q(account__reservering=reservering)\n qsl = self.project.transactions.filter(*lstQ)\n for transaction in qsl:\n totaal += transaction.amount\n # lstQ[0] = Q(debet__reservering=reservering)\n lstQ[0] = Q(side='db') & Q(account__reservering=reservering)\n qsl = self.project.transactions.filter(*lstQ)\n for transaction in qsl:\n totaal -= transaction.amount\n\n # Create a list of all *ACCOUNT* that point to this 'reservering'\n qsr = self.project.accounts.filter(Q(reservering=reservering)).order_by(\"number\")\n acct_list = []\n # Create a debit/credit of each account's actions\n for acct in qsr:\n oAcctInfo = {}\n oAcctInfo['account'] = acct\n oAcctInfo['balance_start'] = 0.0\n account_debet = 0.0\n for transaction in self.project.transactions.filter(Q(account=acct) & Q(side='db')):\n account_debet += transaction.amount\n account_credit = 0.0\n for transaction in self.project.transactions.filter(Q(account=acct) & Q(side='cr')):\n account_credit += transaction.amount\n account_result = account_credit - account_debet\n oAcctInfo['debet'] = account_debet\n oAcctInfo['credit'] = account_credit\n oAcctInfo['result'] = account_result\n oAcctInfo['balance_end'] = account_result\n # Only attach accounts if they are non-zero\n if account_result != 0.0:\n acct_list.append(oAcctInfo)\n oItem['acct_list'] = acct_list\n\n oItem['balance_end'] = totaal\n amount_end += totaal\n\n item_list.append(oItem)\n\n # Add the list\n context[list_type+\"_list\"] = item_list\n # Add an item with the totals\n context[list_type+\"_start\"] = amount_start\n context[list_type+\"_end\"] = amount_end\n\n # Determine the profits and loss list (income & expenses)\n bal_inc = choice_value(BALANCE_TYPE, \"income\")\n bal_exp = choice_value(BALANCE_TYPE, \"expenses\")\n balance_list = [{'prefix': \"inc\", 'balance': bal_inc},\n {'prefix': \"exp\", 'balance': bal_exp}]\n # Make a list of expense-lines\n exp_list = [item.exp_line for item in self.project.purposes.all().order_by('exp_line')]\n exp_list = list(set(exp_list))\n exp_line_list = []\n inc_line_list = []\n total_debet = 0.0\n total_credit = 0.0\n for oBalance in balance_list:\n # Provide a prefix\n sPrefix = oBalance['prefix']\n balance = oBalance['balance']\n # Reset the debet/credit for this [oBalance]\n incexp_debet = 0.0\n incexp_credit = 0.0\n for exp_line in exp_list:\n # Figure out which accounts belong to this \n lstQ = []\n lstQ.append(Q(balance=balance))\n lstQ.append(Q(purpose__exp_line=exp_line))\n qs = self.project.accounts.filter(*lstQ).order_by('number')\n\n # Start collecting the information for this expense-line\n oExpLine = {}\n oExpLine['purpose'] = 'Other' if exp_line < 0 else self.project.purposes.filter(Q(exp_line=exp_line)).first()\n oExpLine['account_list'] = []\n extline_debet = 0.0\n extline_credit = 0.0\n for account in qs:\n account_debet = 0.0\n account_credit = 0.0\n \n # Calculate amounts\n for transaction in self.project.transactions.filter(Q(account=account) & Q(side='db')):\n account_debet += transaction.amount\n for transaction in self.project.transactions.filter(Q(account=account) & Q(side='cr')):\n account_credit += transaction.amount\n\n # Determine the class for this line\n acct_type = \"account-pm\" if (account_debet == 0.0 and account_credit == 0.0) else \"account-active\"\n\n # Store the amounts for this line\n oAcctLine = dict(account=account,\n acct_type=acct_type,\n debet = account_debet,\n credit = account_credit,\n result = account_credit - account_debet)\n oExpLine['account_list'].append(oAcctLine)\n\n # Calculate extline amounts\n extline_debet += account_debet\n extline_credit += account_credit\n\n if sPrefix == \"inc\":\n oExpLine['number'] = len(inc_line_list) + 1\n else:\n oExpLine['number'] = len(exp_line_list) + 1\n oExpLine['debet'] = extline_debet\n oExpLine['credit'] = extline_credit\n oExpLine['result'] = extline_credit - extline_debet\n\n # Keep track of the total\n incexp_debet += extline_debet\n incexp_credit += extline_credit\n\n # Add this expense-line information\n if sPrefix == \"inc\":\n inc_line_list.append(oExpLine)\n else:\n exp_line_list.append(oExpLine)\n # Add the debet/credit for this [oBalance]\n context[sPrefix+\"_debet\"] = incexp_debet\n context[sPrefix+\"_credit\"] = incexp_credit\n context[sPrefix+\"_result\"] = incexp_credit - incexp_debet\n # Adapt the total\n total_debet += incexp_debet\n total_credit += incexp_credit\n\n # Make transaction overviews for *all* accounts under this project\n journal_list = []\n for account in self.project.accounts.all().order_by('number'):\n oAccount = {}\n oAccount['account'] = account\n oAccount['transaction_list'] = self.project.transactions.filter(Q(account=account)).select_related().order_by('tgroup__date', 'tgroup__group', 'tgroup__batch')\n # Only add journals with content or with an opening saldo\n if account.saldo > 0.0 or oAccount['transaction_list'].count() > 0:\n journal_list.append(oAccount)\n\n # Set the results in the context variable\n context['inc_line_list'] = inc_line_list\n context['exp_line_list'] = exp_line_list\n context['total_debet'] = total_debet\n context['total_credit'] = total_credit\n context['total_result'] = total_credit - total_debet\n context['journal_list'] = journal_list\n\n\n return context\n\n def perform_download(self):\n # We are going to download\n sFileName = \"{}-{}_Balans\".format(self.project.org.name.replace(\" \", \"_\"), self.project.year)\n return balance_xlsx(context, sFileName)\n\n\nclass AccountField(BasicJson):\n \"\"\"Change, set or delete one field of an Account instance\"\"\"\n\n template_name = 'finance/account_field.html'\n MainModel = Account\n\n def add_to_context(self, context):\n\n # Initialize values for what we return\n context['field-msg'] = \"(no changes)\"\n context['field-status'] = \"\"\n # Find out which field is being processed\n objid = self.obj.id\n field_name = \"obj-fname-{}\".format(objid)\n field_value = \"obj-fvalue-{}\".format(objid)\n\n # Find out what action is needed\n if self.action == \"save\":\n # Get the field name and value\n if field_name in self.qd and field_value in self.qd:\n fname = self.qd[field_name]\n fvalue = self.qd[field_value]\n # If the field_name is 'parent_in', then the field_value needs to be adapted\n if fname == \"parent_in\":\n # We are going to actually change the PARENT\n fname = \"parent\"\n # Find the correct account.id for this field_value\n iNumber = get_account_number(fvalue)\n fvalue = self.obj.project.accounts.filter(number=iNumber).first()\n\n # Save the new value\n if fvalue == \"(none)\":\n setattr(self.obj, fname, None)\n else:\n setattr(self.obj, fname, fvalue)\n self.obj.save()\n context['field_msg'] = \"De wijziging in deze rekening is opgeslagen\"\n context['field_status'] = \"saved\"\n else:\n context['field_msg'] = \"Zorg a.u.b. voor [{}] en [{}]\".format(field_name, field_value)\n context['field_status'] = \"error\"\n elif self.action == \"delete\":\n # Get the field name and value\n if field_name in self.qd:\n # Set this value to null\n fname = self.qd[field_name]\n # If the field_name is 'parent_in', then it needs to be 'parent'\n if fname == \"parent_in\":\n # We are going to actually change the PARENT\n fname = \"parent\"\n # Remove the group from the research project\n setattr(self.obj, fname, None)\n self.obj.save()\n context['field_msg'] = \"De verwijdering is gelukt\"\n context['field_status'] = \"deleted\"\n else:\n context['field_msg'] = \"Zorg a.u.b. voor [{}] en [{}]\".format(field_name, field_value)\n context['field_status'] = \"error\"\n\n return context\n\n\nclass AccountJson(BasicJson):\n \"\"\"Editing and deleting of one account\"\"\"\n\n MainModel = Account\n template_name = 'finance/account_form.html'\n project = None\n form_objects = [{'form': AccountForm, 'prefix': 'account', 'readonly': False}]\n\n def get_instance(self, prefix):\n if prefix == 'account':\n # The self object is the account\n return self.obj\n else:\n return None\n\n def add_to_context(self, context):\n # Make sure we have the right project\n self.project = self.obj.project\n\n # Make sure we get the user and check the authentication\n currentuser = self.request.user\n context['authenticated'] = currentuser.is_authenticated()\n\n # Make sure the project of the account is set\n for oFormObj in self.form_objects:\n if oFormObj['prefix'] == \"account\":\n # We now have the TransGroup form object\n frm = oFormObj['forminstance']\n if frm.fields['acct_project_id'].initial == None and self.project != None:\n frm.fields['acct_project_id'].initial = str(self.project.id)\n oFormObj['forminstance'] = frm\n\n # Make sure to add the id of this PROJECT\n instanceid = None if self.obj == None else self.obj.id\n context['object_id'] = instanceid\n context['project_id'] = self.project.id\n context['save_url'] = reverse(\"account_json\", kwargs={'object_id': instanceid})\n context['account'] = self.obj\n context['project'] = self.project\n\n # Make this context available\n return context\n\n def before_save(self, prefix, request, instance = None, form = None):\n \"\"\"Note: the 'instance' is the ACCOUNT instance\"\"\"\n\n has_changed = False\n if prefix == 'account':\n account = self.obj\n project = self.project if self.project != None else self.obj.project\n\n # Adapt the form\n if form != None:\n # Treat the PARENT account number\n sAccount = form.cleaned_data['parent_in']\n iNumber = get_account_number(sAccount)\n\n if iNumber > 0:\n instance.parent = instance.project.accounts.filter(number=iNumber).first()\n has_changed = True\n\n # Extract information on \n bUseForExp = False if \"useforexp_in\" not in form.cleaned_data else form.cleaned_data['useforexp_in']\n bUseForInc = False if \"useforinc_in\" not in form.cleaned_data else form.cleaned_data['useforinc_in']\n if instance.useforexp != bUseForExp:\n instance.useforexp = bUseForExp\n has_changed = True\n if instance.useforinc != bUseForInc:\n instance.useforinc = bUseForInc\n has_changed = True\n\n # REturn any changes\n return has_changed\n\n\nclass AccountListJson(BasicJson):\n \"\"\"JSON-producing view for accounts per project\"\"\"\n\n MainModel = Project\n template_name = 'finance/project_accounts.html'\n account_count = 0\n project = None\n account = None\n form_objects = [{'form': AccountForm, 'prefix': 'acct', 'readonly': False}]\n\n def get_instance(self, prefix):\n if prefix == 'project':\n self.project = self.obj\n return self.obj\n elif prefix == 'acct':\n return self.account\n else:\n return None\n\n def add_to_context(self, context):\n # helper functions...\n def get_parent_nodeid(glist, instance, groupid):\n \"\"\"Find the parent-group [instance] from glist\"\"\"\n # Obvious case\n if glist == [] or instance == None: return groupid\n # Get the parent of the group\n grp = instance.group() \n # Yes: look for the correct parent\n for g in glist:\n if g['group'] == grp:\n return g['nodeid']\n # Getting here means we haven't found the group\n return groupid\n\n def path_exists(glist, p):\n \"\"\"Check if glist has the group_path p\"\"\"\n for g in glist:\n if g['group_path'] == p:\n return True\n return False\n\n # Make sure we have the right project\n self.project = self.obj\n context['project'] = self.project\n\n # Make sure we get all accounts for this project\n qs = self.project.accounts.all()\n self.account_count = qs.count()\n\n # Make sure we get the user and check the authentication\n currentuser = self.request.user\n context['authenticated'] = currentuser.is_authenticated()\n context['account_count'] = self.account_count\n\n # Divide the accounts over their balance place\n balances = FieldChoice.objects.filter(field__iexact=BALANCE_TYPE)\n\n balance_list = []\n balance_list.append({'balance': 'Balansrekeningen', 'english': 'Assets and liabilities', 'abbrs': ['act', 'pas']})\n balance_list.append({'balance': 'Winst- en verliesrekeningen', 'english': 'Income and expenses', 'abbrs': ['bat', 'las']})\n\n nodeid = 1\n acct_node = {} # Map account number to nodeid\n for bal_group in balance_list:\n # Initialise variables for each group\n sGroup = \"\"\n max_depth = 0\n grp_list = []\n accountgrp_list = []\n lstQ = [] # This is just for the main query\n\n # Construct a queryset that contains all relevant accounts for this bal_group\n for balance in balances:\n if balance.abbr in bal_group['abbrs']:\n lstQ.append(Q(balance=balance.machine_value))\n qs = self.project.accounts.filter(lstQ[0] | lstQ[1])\n\n # Sort them according to their full path\n qs_sorted = sorted(qs, key=lambda x: x.full_path())\n\n # Mark the number of the overall head\n overall = nodeid\n\n # Walk all the items of qs_sorted\n for acct_item in qs_sorted:\n # Each account is a new item\n nodeid += 1\n # Make sure the account ends up in the map\n if str(acct_item.number) not in acct_node:\n acct_node[str(acct_item.number)] = nodeid\n # Get the parent account (if any)\n acct_parent = None if acct_item.parent == None else str(acct_item.parent.number)\n\n # Get the nodeid of the parent\n if acct_parent == None:\n parent = overall\n else:\n if acct_parent in acct_node:\n parent = acct_node[acct_parent]\n parent = int(parent)\n else:\n # This should never happen\n parent = 0\n \n # Get the group path\n grp_path = acct_item.group_path()\n # Get and add the depth\n depth = acct_item.group_depth() + 1\n if depth > max_depth:\n max_depth = depth\n # Which group does this account belong to?\n sAccountGroup = \"\" if acct_item.parent == None else acct_item.parent.group()\n sGroupName = acct_item.group()\n has_children = acct_item.has_children()\n # Create a group\n oGrp = {'group': sGroupName, 'group_path': grp_path, 'acct': acct_item, 'nodeid': nodeid, \n 'childof': parent, 'depth': depth, 'has_children': has_children}\n oGrp['minwidth'] = (oGrp['depth']-1) * 20\n # Add group to list\n accountgrp_list.append(oGrp)\n\n # Add the Remainder into the elements\n for oGrp in accountgrp_list:\n oGrp['remainder'] = max_depth - oGrp['depth'] + 1\n\n bal_group['account_list'] = qs\n bal_group['account_groups'] = accountgrp_list\n bal_group['max_depth'] = max_depth\n\n context['balance_list'] = balance_list\n\n # Make sure the project of the account is set\n for oFormObj in self.form_objects:\n if oFormObj['prefix'] == \"acct\":\n # We now have the TransGroup form object\n frm = oFormObj['forminstance']\n if frm.fields['acct_project_id'].initial == None and self.project != None:\n frm.fields['acct_project_id'].initial = str(self.project.id)\n oFormObj['forminstance'] = frm\n\n # Make sure to add the id of this PROJECT\n context['object_id'] = None if self.obj == None else self.obj.id\n context['account'] = self.account\n context['project'] = self.project\n context['project_id'] = self.project.id\n\n # Note the maximum depth\n acct_list = self.project.accounts.order_by('number').values('id', 'number', 'name')\n context['acct_list'] = acct_list\n\n # Make this context available\n return context\n\n def before_save(self, prefix, request, instance = None, form = None):\n \"\"\"Note: the 'instance' is the ACCOUNT instance\"\"\"\n\n has_changed = False\n if prefix == 'acct':\n project = self.project if self.project != None else self.obj\n if project == None:\n # Unable to do anything further\n pass\n else:\n # Make sure the account gets associated with the correct project\n # Also make sure [parent_in] gets turned into [parent]\n account = None\n parent = None\n for formObj in self.form_objects:\n if formObj['prefix'] == \"acct\":\n # Get the account instance\n account = formObj['instance']\n if account != None and account.project_id == None:\n account.project = project\n account.save()\n has_changed = True\n if self.account == None:\n self.account = account\n\n # Adapt the form\n if form != None:\n # Treat the PARENT account number\n sAccount = form.cleaned_data['parent_in']\n iNumber = get_account_number(sAccount)\n\n if iNumber > 0:\n instance.parent = instance.project.accounts.filter(number=iNumber).first()\n has_changed = True\n\n # Extract information on \n bUseForExp = False if \"useforexp_in\" not in form.cleaned_data else form.cleaned_data['useforexp_in']\n bUseForInc = False if \"useforinc_in\" not in form.cleaned_data else form.cleaned_data['useforinc_in']\n if instance.useforexp != bUseForExp:\n instance.useforexp = bUseForExp\n has_changed = True\n if instance.useforinc != bUseForInc:\n instance.useforinc = bUseForInc\n has_changed = True\n\n # REturn any changes\n return has_changed\n\n\nclass TransGroupDetails(BasicJson):\n template_name = 'finance/project_transgroup.html'\n template_err_view = 'finance/err_view.html'\n MainModel = TransGroup\n project = None\n form_objects = [{'form': TransGroupForm, 'prefix': 'tgroup', 'readonly': False}]\n TransFormSet = inlineformset_factory(TransGroup, Transaction,\n form=TransactionForm, min_num=2, extra=0)\n formset_objects = [{'formsetClass': TransFormSet, 'prefix': 'trans', 'readonly': False}]\n\n def get_instance(self, prefix):\n # Note: the self.obj has the transgroup\n # the self.project must point to the current project\n if prefix == 'tgroup' or prefix == 'trans':\n # Determine the tgroup id\n tgroup = self.obj\n #if tgroup == None:\n # tgroup = TransGroup(project=self.project)\n # tgroup.save()\n return tgroup\n\n def custom_init(self):\n # Determine the project id\n project_id = self.qd.get(\"project_id\", \"\")\n if project_id != \"\":\n self.project = Project.objects.filter(Q(id=project_id)).first()\n elif self.obj != None:\n self.project = self.obj.project\n\n # Make sure the project is established\n self.obj = self.get_instance(\"trans\")\n\n # Make sure 'add' is switched off\n self.add = False\n #if self.project and self.obj:\n # self.add = False\n\n # Determine if there was any action\n action = self.qd.get('action', '')\n\n # Store the action if this is needed\n if \"next\" in action or \"prev\" in action:\n self.action = action\n # Perform calculations\n instanceid = self.get_navigate()\n self.data['instanceid'] = instanceid\n self.data['openurl'] = self.get_openurl(instanceid)\n\n # Return with success\n return True\n\n def get_navigate(self):\n # We need to find and return a 'next' or 'prev' instanceid\n # Initialisations\n instanceid = -1\n current_instanceid = self.obj.id # self.object_id\n direction = \"prev\" if \"prev\" in self.action else \"next\"\n refdescr = self.qd.get(\"refdescr\", \"\")\n account_in = self.qd.get(\"account_in\", None)\n\n # Get the queryset as dictated by the filter\n lstQ = []\n # Apply refdescr\n if refdescr != \"\":\n lstQ.append(Q(description__icontains=refdescr)|Q(doc__icontains=refdescr))\n\n # Apply account_in\n if account_in != None:\n iNumber = get_account_number(account_in)\n if iNumber > 0:\n # Apply it\n lstQ.append(Q(group_transactions__account__number=iNumber))\n\n # Make sure we have a project\n self.project = self.obj.project\n # Get a list of ids\n tgroup_ids = self.project.transgroups.filter(*lstQ).order_by('date', 'group', 'batch').values_list('id', flat=True)\n # Walk the list and find the location of the current instanceid\n for idx, tg_id in enumerate(tgroup_ids):\n if tg_id == current_instanceid:\n break\n if direction == \"next\":\n # Need to get the next one\n if idx < len(tgroup_ids)-1:\n idx = idx + 1\n else:\n # Need to get the previous one\n if idx>0:\n idx = idx-1\n instanceid = tgroup_ids[idx]\n\n # Add some more information in the self.data\n self.data['number'] = idx + 1\n self.data['total'] = len(tgroup_ids)\n\n return instanceid\n\n def get_openurl(self, instanceid):\n ajaxurl = reverse(\"tgroup_edit\", kwargs={'object_id': instanceid})\n return ajaxurl\n\n def add_to_context(self, context):\n # Make sure we are authenticated\n currentuser = self.request.user\n context['authenticated'] = currentuser.is_authenticated()\n\n if self.project == None:\n # Make sure the project is established\n project_id = self.qd.get(\"thisproject_id\", \"\")\n if project_id != \"\":\n self.project = Project.objects.filter(Q(id=project_id)).first()\n elif self.obj != None:\n self.project = self.obj.project\n\n # Make sure the project of the tgroup is set\n for oFormObj in self.form_objects:\n if oFormObj['prefix'] == \"tgroup\":\n # We now have the TransGroup form object\n frm = oFormObj['forminstance']\n if frm.fields['tgroup_project_id'].initial == None and self.project != None:\n frm.fields['tgroup_project_id'].initial = str(self.project.id)\n oFormObj['forminstance'] = frm\n\n\n # Check the trans_formset\n if 'trans_formset' in context:\n trans_formset = context['trans_formset']\n # Walk the forms in the formset\n sides = ['db', 'cr']\n \n for idx, trans_form in enumerate(trans_formset):\n if trans_form.fields['side_in'].initial == None:\n trans_form.initial['side_in'] = sides[idx]\n trans_form.fields['side_in'].initial = sides[idx]\n\n # Replace the formset\n context['trans_formset'] = trans_formset\n\n\n # Make sure to add the id of this transgroup object\n context['object_id'] = None if self.obj == None else self.obj.id\n context['transgroup'] = self.obj\n context['project'] = self.project\n context['project_id'] = self.project.id\n\n # GEt all the transactions in this group\n # trans_in_group = self.obj.group_transactions.all().select_related().order_by('side', 'account')\n\n return context\n\n def before_save(self, prefix, request, instance = None, form = None):\n \"\"\"Note: the 'instance' is the TGROUP instance\"\"\"\n\n has_changed = False\n # When we save a Transgroup, we need to make sure:\n # 1 - that all Trans point to the correct Transgroup and the correct Project\n # 2 - that the TRransgroup points to the correct Project\n if prefix == 'trans':\n # Get the current transgroup and project\n tgroup = self.obj\n project = self.project\n bChanged = False\n # Adapt the form\n if form != None:\n\n # Is the project set?\n if instance.project_id == None or instance.project == None:\n instance.project = project\n bChanged = True\n\n # Is the tgroup set?\n if instance.tgroup_id == None or instance.tgroup == None:\n instance.tgroup = tgroup\n bChanged = True\n\n # Treat the account number\n sAccount = form.cleaned_data['account_in']\n iNumber = -1\n if \":\" in sAccount:\n iNumber = int(sAccount.split(\":\")[0].strip())\n elif sAccount != \"\":\n iNumber = int(sAccount)\n if iNumber > 0:\n instance.account = instance.project.accounts.filter(number=iNumber).first()\n bChanged = True\n\n # Treat the side\n sSide = form.cleaned_data['side_in']\n if instance.side != sSide:\n instance.side = sSide\n bChanged = True\n\n # Treat the PERSON affected (if any)\n sPerson = form.cleaned_data['person_in']\n if sPerson == \"\":\n # Check if the person is being reset to nothing\n if instance.person != None:\n instance.person = None\n bChanged = True\n else:\n # There is a person being set: get its number\n pass\n\n # Save changes if needed\n if bChanged:\n instance.save()\n\n elif prefix == \"tgroup\":\n project = self.project\n if project == None:\n sId = self.form_objects[0]['forminstance']['tgroup_project_id'].data\n project = Project.objects.filter(Q(id=sId)).first()\n self.project = project\n tgroup = None\n for formObj in self.form_objects:\n if formObj['prefix'] == \"tgroup\":\n # Get the tgroup instance\n tgroup = formObj['instance']\n if tgroup != None:\n tgroup.project = project\n tgroup.save()\n has_changed = True\n if self.obj == None:\n self.obj = tgroup\n return has_changed\n\n\nclass TransGroupRemove(BasicJson):\n MainModel = TransGroup\n action = \"delete\"\n\n\nclass ProjectTransactionsJson(BasicJson):\n \"\"\"JSON-producing view for project transactions\"\"\"\n \n template_name = 'finance/project_transactions.html'\n MainModel = Project\n paginate_by = paginateEntries # paginateTgroups # \n page_function = \"dmb.finance.goto_page\" \n page_obj = []\n page = 0\n form_div = \"\"\n form_div_all = \"project_trans_list\"\n form_div_filter = \"trans_search\"\n project = None\n transcount = 0\n account_in = None\n queryset = None\n\n def get_instance(self, prefix):\n if prefix == 'trans':\n self.project = self.obj\n return self.obj\n\n def custom_init(self):\n # Custom initialization -- see Cesar [ResultPart1]\n self.get_queryset('trans')\n # Paging...\n page = self.qd.get('page')\n page = 1 if page == None else int(page)\n # Create a list [page_obj] that contains just the right results\n paginator = Paginator(self.queryset, self.paginate_by)\n transaction_list = paginator.page(page)\n trgoupid_list = [x.tgroup.id for x in transaction_list]\n # Convert transaction list into list of transgroup objects\n tg_list = TransGroup.objects.filter(Q(id__in=trgoupid_list)).select_related().order_by('-date', 'group')\n object_list = []\n bOdd=True\n for item in tg_list:\n # Determine the rowclass\n sRowClass = \"LineLight\" if bOdd else \"LineDark\"\n bOdd = not bOdd\n # Get related transactions\n trans_in_group = item.group_transactions.all().select_related().order_by('side', 'account')\n oGroup = {'count': trans_in_group.count(), \n 'rowclass': sRowClass,\n 'tgroup': item ,\n 'list': trans_in_group}\n object_list.append(oGroup)\n\n # Fix the output\n self.object_list = object_list\n self.page_obj = paginator.page(page)\n self.page = page\n\n # If this is navigation, then set the action\n action = self.qd.get('action', '')\n if action != \"\" and action == \"navigate\":\n self.action = action\n\n def add_to_context(self, context):\n # Specify search form if needed\n\n # Make sure we are authenticated\n currentuser = self.request.user\n context['authenticated'] = currentuser.is_authenticated()\n\n # Determine which ones to show for this particular page\n \n context['page_obj'] = self.page_obj\n context['object_list'] = self.object_list\n context['page_function'] = self.page_function\n context['hitcount'] = self.transcount\n\n context['is_paginated'] = 1 if self.transcount > self.paginate_by else 0\n context['formdiv'] = self.form_div\n\n # Determine what the initial trans view is\n context['transview'] = 'full' if self.account_in == None else 'restricted'\n context['account_in'] = self.account_in\n\n # Calculate the transaction totals or the different accounts\n acct_balance = [] # balance.type is 'act' or 'pas'\n acct_expense = [] # balance.type is 'bat' or 'las'\n total_db = 0.0\n total_cr = 0.0\n\n balance_types = [\"assets\", \"liabilities\"]\n accounts = []\n account_index = {}\n idx = -1\n for balance_type in balance_types:\n bal_num = self.project.get_balance_type(balance_type)\n qs_bal = self.qs.filter(Q(account__balance=bal_num)).order_by('account__number', 'side').values('account__number', 'account__name', 'side', 'amount')\n for trans in qs_bal:\n acctnum = trans['account__number']\n if len(accounts)>0 and accounts[idx]['number'] != acctnum:\n idx = -1\n # Check if the index is in the object\n if acctnum in account_index:\n idx = account_index[acctnum]\n if idx<0:\n # THis is a new account\n acctname = \"{}: {}\".format(acctnum, trans['account__name'])\n idx = len(accounts)\n accounts.append( {'db': 0.0, 'cr': 0.0, 'number': acctnum, 'name': acctname})\n account_index[acctnum] = idx\n # Add to the correct side\n accounts[idx][trans['side']] += trans['amount']\n # Walk through the sums\n for oAccount in accounts:\n oInfo = {}\n oInfo['account'] = oAccount['name']\n oInfo['debet'] = oAccount['db']\n oInfo['credit'] = oAccount['cr']\n oInfo['total'] = oAccount['cr'] - oAccount['db']\n total_db += oAccount['db']\n total_cr += oAccount['cr']\n acct_balance.append(oInfo)\n context['accounts_balance'] = acct_balance\n\n balance_types = [\"income\", \"expenses\"]\n accounts = []\n account_index = {}\n idx = -1\n for balance_type in balance_types:\n bal_num = self.project.get_balance_type(balance_type)\n qs_bal = self.qs.filter(Q(account__balance=bal_num)).order_by('account__number', 'side').values('account__number', 'account__name', 'side', 'amount')\n for trans in qs_bal:\n acctnum = trans['account__number']\n if len(accounts)>0 and accounts[idx]['number'] != acctnum:\n idx = -1\n # Check if the index is in the object\n if acctnum in account_index:\n idx = account_index[acctnum]\n if idx<0:\n # THis is a new account\n acctname = \"{}: {}\".format(acctnum, trans['account__name'])\n idx = len(accounts)\n accounts.append( {'db': 0.0, 'cr': 0.0, 'number': acctnum, 'name': acctname})\n account_index[acctnum] = idx\n # Add to the correct side\n accounts[idx][trans['side']] += trans['amount']\n # Walk through the sums\n for oAccount in accounts:\n oInfo = {}\n oInfo['account'] = oAccount['name']\n oInfo['debet'] = oAccount['db']\n oInfo['credit'] = oAccount['cr']\n oInfo['total'] = oAccount['cr'] - oAccount['db']\n total_db += oAccount['db']\n total_cr += oAccount['cr']\n acct_expense.append(oInfo)\n context['accounts_expense'] = acct_expense\n\n\n oTotal = {}\n oTotal['debet'] = total_db\n oTotal['credit'] = total_cr\n oTotal['total'] = total_cr - total_db\n context['totals'] = oTotal\n\n # Return the adapted context\n return context\n\n def get_queryset(self, prefix):\n # Determine the queryset: all transactions of this project ordered by date\n # NOTE: \n # do not use select_related() here, because that is overkill due to paging...\n if self.project == None:\n self.get_instance(prefix)\n\n lstQ = []\n\n # See if we have a search form content\n refdescr = self.qd.get(\"refdescr\", \"\")\n account_in = self.qd.get(\"account_in\", None)\n\n # Apply refdescr\n if refdescr != \"\":\n lstQ.append(Q(tgroup__description__icontains=refdescr)|Q(tgroup__doc__icontains=refdescr))\n\n # Apply account_in\n if account_in != None:\n iNumber = -1\n if \":\" in account_in:\n iNumber = int(account_in.split(\":\")[0].strip())\n elif account_in != \"\":\n iNumber = int(account_in)\n if iNumber > 0:\n # Apply it\n lstQ.append(Q(account__number=iNumber))\n self.account_in = iNumber\n\n\n # Always do filering\n self.form_div = self.form_div_filter\n\n # NOTE: this provides all the TRANSACTIONS, not the tgroups\n self.queryset = self.project.transactions.filter(*lstQ).select_related().order_by('-tgroup__date', 'tgroup__group', 'tgroup__batch', 'side')\n self.transcount = self.queryset.count()\n self.qs = self.project.transactions.filter(*lstQ).select_related().order_by('-tgroup__date', 'tgroup__group', 'tgroup__batch', 'side')\n return self.queryset\n\n\nclass ProjectTransAcctListJson(ProjectTransactionsJson):\n \"\"\"JSON-producing view for project transactions of one account\"\"\"\n\n def custom_init(self):\n # First figure out my own parameters\n if 'year' in kwargs:\n self.year = kwargs['year']\n if 'acct' in kwargs:\n self.acct = kwargs['acct']\n if 'pk' in kwargs:\n pk = int(kwargs['pk'])\n self.project = Project.objects.filter(pk=pk).first()\n self.year = self.project.year\n\n # Consider additional information in request.GET\n if 'person' in request.GET:\n person_id = request.GET['person']\n self.person = Person.objects.filter(id=person_id).first()\n if 'action' in request.GET:\n self.action = request.GET['action']\n # Then call the actual init\n response = super(ProjectTransAcctListJson, self).custom_init()\n # REturn the result\n return response\n\n\nclass ProjectListView(ListView):\n model = Project\n template_name = 'finance/project_list.xml'\n entrycount = 0\n qs = None\n\n def render_to_response(self, context, **response_kwargs):\n # Make sure we get the user and check the authentication\n currentuser = self.request.user\n context['authenticated'] = currentuser.is_authenticated()\n return super(ProjectListView, self).render_to_response(context, **response_kwargs)\n\n def get_queryset(self):\n self.qs = Project.objects.all().order_by('org__name', 'year')\n return self.qs\n\n\nclass ResultList(ListView):\n \"\"\"List the results of the indicated year\"\"\"\n\n model = Account\n year = '2017'\n template_name = 'finance/results.html'\n paginate_by = paginateEntries\n entrycount = 0\n project = None\n qs = None\n\n def get(self, request, *args, **kwargs):\n # Process all that is in [kwargs]\n if 'year' in kwargs:\n self.year = kwargs['year']\n if 'project_id' in kwargs:\n self.project = Project.objects.filter(id=kwargs['project_id']).first()\n if self.project != None:\n self.year = self.project.year\n return super(ResultList, self).get(request, *args, **kwargs)\n\n def get_queryset(self):\n\n # Determine the current project\n if self.project == None:\n # Get the transactions for this year for the mangoboom\n iYear = int(self.year)\n self.project = Project.get_project(\"De Mangoboom\", iYear)\n\n # Get all the Activa accounts\n balance = choice_value(BALANCE_TYPE, \"assets\")\n lstQ = []\n lstQ.append(Q(balance=balance))\n qs = self.project.accounts.filter(*lstQ).order_by('number')\n self.qs = qs\n\n # Check how many there are and then return\n self.entrycount = qs.count()\n return qs\n \n def render_to_response(self, context, **response_kwargs):\n # Make sure we get the user and check the authentication\n currentuser = self.request.user\n context['authenticated'] = currentuser.is_authenticated()\n context['entrycount'] = self.entrycount\n\n # Calculate the results for all the accounts selected by the queryset\n result_list = []\n for account in self.qs:\n # Calculate the result for this list\n beginsaldo = account.saldo\n # Calculate all debet\n debet = 0.0\n qs = self.project.transactions.filter(Q(debet=account))\n for transaction in qs:\n debet += transaction.amount\n # Calculate all credit\n credit = 0.0\n qs = self.project.transactions.filter(Q(credit=account))\n for transaction in qs:\n credit += transaction.amount\n # Calculate the ending balance\n eindsaldo = beginsaldo + debet - credit\n # COmbine into an object\n oResult = dict(account=account,\n beginsaldo= beginsaldo,\n debet=debet,\n credit=credit,\n eindsaldo=eindsaldo)\n # Add the object to the list\n result_list.append(oResult)\n # Make the list of results available\n context['result_list'] = result_list\n\n # Return \n return super(ResultList, self).render_to_response(context, **response_kwargs)\n\n\nclass ResultOview(DetailView):\n \"\"\"Give the financial overview of the indicated year\"\"\"\n\n model = Project\n year = '2017'\n template_name = 'finance/result_oview.html'\n paginate_by = paginateEntries\n entrycount = 0\n project = None\n action = \"\"\n qs = None\n\n def get(self, request, *args, **kwargs):\n # First process anything that is in [kwargs]\n if 'year' in kwargs:\n self.year = kwargs['year']\n if 'project_id' in kwargs:\n self.project = Project.objects.filter(id=kwargs['project_id']).first()\n if self.project != None:\n self.year = self.project.year\n self.template_name = 'finance/result_project.html'\n\n # If the action is not specified, we are just going to show the result\n # Otherwise the action may be 'download', in which case we are going to download to Excel\n if 'action' in request.GET:\n self.action = request.GET['action']\n\n # Determine the current project\n if self.project == None:\n self.project = Project.objects.filter(org__name=\"De Mangoboom\", year=self.year).first()\n\n # Perform the default action\n return super(ResultOview, self).get(request, *args, **kwargs)\n\n def get_object(self, queryset = None):\n return self.project\n\n def render_to_response(self, context, **response_kwargs):\n # Make sure we get the user and check the authentication\n currentuser = self.request.user\n context['authenticated'] = currentuser.is_authenticated()\n context['entrycount'] = self.entrycount\n context['project'] = self.project\n context['project_id'] = self.project.id\n context['intro_breadcrumb'] = \"Resultatenrekening en balans\"\n\n # Determine start and end date\n context['date_start'] =\"01/01/{}\".format(self.project.year)\n context['date_end'] = \"31/12/{}\".format(self.project.year)\n\n # Determine the assets and liabilities lists\n reservering_list = []\n for list_type in ['assets', 'liabilities']:\n balance = choice_value(BALANCE_TYPE, list_type)\n qs = self.project.accounts.filter(Q(balance=balance)).order_by('number')\n\n item_list = []\n amount_start = 0.0\n amount_end = 0.0\n lstQ = [None, None]\n for account in qs:\n oItem = {}\n oItem['account'] = account\n oItem['balance_start'] = account.saldo\n amount_start += account.saldo\n totaal = account.saldo\n\n # Calculate ending balance\n if list_type == 'assets':\n # For assets: debet minus credit\n qsa = self.project.transactions.filter(Q(credit=account))\n for transaction in qsa:\n totaal -= transaction.amount\n qsa = self.project.transactions.filter(Q(debet=account))\n for transaction in qsa:\n totaal += transaction.amount\n elif list_type == \"liabilities\":\n # Calculate the ending balance of liabilities\n # Do this by looking at all the transactions attached to a particular purpose\n reservering = account.reservering\n lstQ = [None]\n # Double check if the purpose has already been treated\n if not reservering in reservering_list:\n # Purpose has not yet been treated: add it to the list\n reservering_list.append(reservering)\n # For liabilities: credit minus debet\n lstQ[0] = Q(credit__reservering=reservering)\n qsl = self.project.transactions.filter(*lstQ)\n for transaction in qsl:\n totaal += transaction.amount\n lstQ[0] = Q(debet__reservering=reservering)\n qsl = self.project.transactions.filter(*lstQ)\n for transaction in qsl:\n totaal -= transaction.amount\n\n # Create a list of all *ACCOUNT* that point to this 'reservering'\n qsr = self.project.accounts.filter(Q(reservering=reservering)).order_by(\"number\")\n acct_list = []\n # Create a debit/credit of each account's actions\n for acct in qsr:\n oAcctInfo = {}\n oAcctInfo['account'] = acct\n oAcctInfo['balance_start'] = 0.0\n account_debet = 0.0\n for transaction in self.project.transactions.filter(Q(debet=acct)):\n account_debet += transaction.amount\n account_credit = 0.0\n for transaction in self.project.transactions.filter(Q(credit=acct)):\n account_credit += transaction.amount\n account_result = account_credit - account_debet\n oAcctInfo['debet'] = account_debet\n oAcctInfo['credit'] = account_credit\n oAcctInfo['result'] = account_result\n oAcctInfo['balance_end'] = account_result\n # Only attach accounts if they are non-zero\n if account_result != 0.0:\n acct_list.append(oAcctInfo)\n oItem['acct_list'] = acct_list\n\n oItem['balance_end'] = totaal\n amount_end += totaal\n\n item_list.append(oItem)\n\n # Add the list\n context[list_type+\"_list\"] = item_list\n # Add an item with the totals\n context[list_type+\"_start\"] = amount_start\n context[list_type+\"_end\"] = amount_end\n\n # Determine the profits and loss list (income & expenses)\n bal_inc = choice_value(BALANCE_TYPE, \"income\")\n bal_exp = choice_value(BALANCE_TYPE, \"expenses\")\n balance_list = [{'prefix': \"inc\", 'balance': bal_inc},\n {'prefix': \"exp\", 'balance': bal_exp}]\n # Make a list of expense-lines\n exp_list = [item.exp_line for item in self.project.purposes.all().order_by('exp_line')]\n exp_list = list(set(exp_list))\n exp_line_list = []\n inc_line_list = []\n total_debet = 0.0\n total_credit = 0.0\n for oBalance in balance_list:\n # Provide a prefix\n sPrefix = oBalance['prefix']\n balance = oBalance['balance']\n # Reset the debet/credit for this [oBalance]\n incexp_debet = 0.0\n incexp_credit = 0.0\n for exp_line in exp_list:\n # Figure out which accounts belong to this \n lstQ = []\n lstQ.append(Q(balance=balance))\n lstQ.append(Q(purpose__exp_line=exp_line))\n qs = self.project.accounts.filter(*lstQ).order_by('number')\n\n # Start collecting the information for this expense-line\n oExpLine = {}\n oExpLine['purpose'] = 'Other' if exp_line < 0 else self.project.purposes.filter(Q(exp_line=exp_line)).first()\n oExpLine['account_list'] = []\n extline_debet = 0.0\n extline_credit = 0.0\n for account in qs:\n account_debet = 0.0\n account_credit = 0.0\n \n # Calculate amounts\n for transaction in self.project.transactions.filter(Q(debet=account)):\n account_debet += transaction.amount\n for transaction in self.project.transactions.filter(Q(credit=account)):\n account_credit += transaction.amount\n\n # Determine the class for this line\n acct_type = \"account-pm\" if (account_debet == 0.0 and account_credit == 0.0) else \"account-active\"\n\n # Store the amounts for this line\n oAcctLine = dict(account=account,\n acct_type=acct_type,\n debet = account_debet,\n credit = account_credit,\n result = account_credit - account_debet)\n oExpLine['account_list'].append(oAcctLine)\n\n # Calculate extline amounts\n extline_debet += account_debet\n extline_credit += account_credit\n\n if sPrefix == \"inc\":\n oExpLine['number'] = len(inc_line_list) + 1\n else:\n oExpLine['number'] = len(exp_line_list) + 1\n oExpLine['debet'] = extline_debet\n oExpLine['credit'] = extline_credit\n oExpLine['result'] = extline_credit - extline_debet\n\n # Keep track of the total\n incexp_debet += extline_debet\n incexp_credit += extline_credit\n\n # Add this expense-line information\n if sPrefix == \"inc\":\n inc_line_list.append(oExpLine)\n else:\n exp_line_list.append(oExpLine)\n # Add the debet/credit for this [oBalance]\n context[sPrefix+\"_debet\"] = incexp_debet\n context[sPrefix+\"_credit\"] = incexp_credit\n context[sPrefix+\"_result\"] = incexp_credit - incexp_debet\n # Adapt the total\n total_debet += incexp_debet\n total_credit += incexp_credit\n\n # Make transaction overviews for *all* accounts under this project\n journal_list = []\n for account in self.project.accounts.all().order_by('number'):\n oAccount = {}\n oAccount['account'] = account\n oAccount['transaction_list'] = self.project.transactions.filter(Q(debet=account)|Q(credit=account)).select_related().order_by('date', 'group', 'batch')\n # Only add journals with content or with an opening saldo\n if account.saldo > 0.0 or oAccount['transaction_list'].count() > 0:\n journal_list.append(oAccount)\n\n # Set the results in the context variable\n context['inc_line_list'] = inc_line_list\n context['exp_line_list'] = exp_line_list\n context['total_debet'] = total_debet\n context['total_credit'] = total_credit\n context['total_result'] = total_credit - total_debet\n context['journal_list'] = journal_list\n\n # Check what the action is we are going to do: downloading or just visualizing?\n if self.action == \"download\":\n # We are going to download\n sFileName = \"{}-{}_Balans\".format(self.project.org.name.replace(\" \", \"_\"), self.project.year)\n return balance_xlsx(context, sFileName)\n else:\n # We are just visualizing\n return super(ResultOview, self).render_to_response(context, **response_kwargs)\n\n\nclass PersonList(ListView):\n model = Person\n template_name = 'finance/persons.html'\n person_count = 0\n project = None\n qs = None\n\n def get(self, request, *args, **kwargs):\n if 'project_id' in kwargs:\n self.project = Project.objects.filter(id=kwargs['project_id']).first()\n else:\n # Default: get the persons for the first project of the mangoboom\n self.project = Project.objects.filter(org__name=\"De Mangoboom\").first()\n return super(PersonList, self).get(request, *args, **kwargs)\n\n def get_queryset(self):\n self.qs = self.project.org.persons.all().order_by('name')\n self.person_count = self.qs.count()\n return self.qs\n \n def render_to_response(self, context, **response_kwargs):\n # Make sure we get the user and check the authentication\n currentuser = self.request.user\n context['authenticated'] = currentuser.is_authenticated()\n context['person_count'] = self.person_count\n person_list = []\n for person in self.qs:\n oPerson = {}\n oPerson['person'] = person\n oPerson['count'] = self.project.transactions.filter(person=person).count()\n person_list.append(oPerson)\n\n context['person_list'] = person_list\n return super(PersonList, self).render_to_response(context, **response_kwargs)\n \n\nclass AccountList(ListView):\n model = Account\n template_name = 'finance/accounts.html'\n account_count = 0\n project = None\n\n def get(self, request, *args, **kwargs):\n if 'object_id' in kwargs:\n self.project = Project.objects.filter(id=kwargs['object_id']).first()\n else:\n # Default: get the persons for the first project of the mangoboom\n self.project = Project.objects.filter(org__name=\"De Mangoboom\").first()\n return super(AccountList, self).get(request, *args, **kwargs)\n\n def get_queryset(self):\n qs = self.project.accounts.all()\n self.account_count = qs.count()\n return qs\n \n def render_to_response(self, context, **response_kwargs):\n # Make sure we get the user and check the authentication\n currentuser = self.request.user\n context['authenticated'] = currentuser.is_authenticated()\n context['account_count'] = self.account_count\n\n # Divide the accounts over their balance place\n balances = FieldChoice.objects.filter(field__iexact=BALANCE_TYPE)\n balance_list = []\n for balance in balances:\n abbr = balance.abbr\n name = balance.dutch_name\n eng = balance.english_name\n mv = balance.machine_value\n qs = self.project.accounts.filter(balance=mv).order_by('purpose', 'number')\n balance_list.append({'balance': name, 'english': eng, 'account_list': qs})\n context['balance_list'] = balance_list\n return super(AccountList, self).render_to_response(context, **response_kwargs)\n\n\nclass Excel(View):\n \"\"\"Import or Export from/into Excel format\"\"\"\n\n # Initializations\n arErr = [] # errors \n template_name = None # Export template to be used\n action = \"\" # Action that needs to be undertaken\n oErr = ErrHandle()\n\n def post(self, request, object_id=None): \n self.initializations(request, object_id)\n if self.checkAuthentication(request):\n # Build the context\n context = dict(object_id = object_id, savedate=None)\n\n # Our action depends on the action value\n if self.action != \"\" and self.obj != None:\n if self.action == \"import\":\n # We are here to import data from Excel\n pass\n elif self.action == \"export\":\n pass\n\n # Make sure we have a list of any errors\n error_list = [str(item) for item in self.arErr]\n self.data['error_list'] = error_list\n self.data['errors'] = self.arErr\n if len(self.arErr) >0:\n self.data['status'] = \"error\"\n\n # Add items to context\n context['error_list'] = error_list\n context['status'] = self.data['status']\n\n # Get the HTML response\n self.data['html'] = render_to_string(self.template_name, context, request)\n else:\n self.data['html'] = \"Please log in before continuing\"\n\n # Return the information\n return JsonResponse(self.data)\n\n def checkAuthentication(self,request):\n # first check for authentication\n if not request.user.is_authenticated:\n # Simply redirect to the home page\n self.data['html'] = \"Please log in to work on a research project\"\n return False\n else:\n return True\n\n def initializations(self, request, object_id):\n # Clear errors\n self.arErr = []\n self.data['status'] = \"ok\"\n self.data['html'] = \"\"\n self.data['statuscode'] = \"\"\n # COpy the request\n self.request = request\n # Copy any object id\n self.object_id = object_id\n if self.action == \"export\" or self.action == \"download\":\n # Get the instance of the Main Model object\n self.obj = self.MainModel.objects.get(pk=object_id)\n # Get the parameters\n if request.POST:\n self.qd = request.POST\n else:\n self.qd = request.GET\n # Perform some custom initialisations\n self.custom_init()\n\n def custom_init(self):\n pass\n \n\nclass ImportExcel(Excel):\n \"\"\"Import an excel file\"\"\"\n\n MainModel = Project\n action = \"start\"\n template_name = \"finance/import_status.html\"\n\n\nclass ExportExcel(Excel):\n MainModel = Project\n action = \"export\"\n\n\ndef import_excel(request, object_id=None):\n \"\"\"Main entry point for the specification of an Excel import operation\"\"\"\n\n # Initialisations\n template = 'finance/import_excel.html'\n arErr = []\n\n # Check if the user is authenticated\n if not request.user.is_authenticated:\n # Simply redirect to the home page\n return redirect('nlogin')\n\n # Get the 'obj' to this project (or 'None' if it is a new one)\n if object_id is None:\n obj = None\n intro_message = \"Import a whole financial year from a Mangoboom Excel file\"\n intro_breadcrumb = \"New Import\"\n else:\n # Get the instance of this project object\n obj = Project.objects.get(pk=object_id)\n intro_message = \"Finance project: {} of {}\".format(obj.org.name, obj.year)\n intro_breadcrumb = \"[{}]\".format(obj.org.name)\n\n project_list = Project.objects.all()\n\n # Get a list of errors\n error_list = [str(item) for item in arErr]\n\n # Create the context\n context = dict(\n object_id = object_id,\n original=obj,\n project_list=project_list,\n intro_message=intro_message,\n intro_breadcrumb=intro_breadcrumb,\n error_list=error_list\n )\n\n # Open the template that allows Editing an existing or Creating a new research project\n # or editing the existing project\n return render(request, template, context)\n\n@csrf_exempt\ndef import_file(request):\n \"\"\" Just allow importing a file\"\"\"\n arErr = []\n\n if request.method == 'POST':\n form = UploadFileForm(request.POST, request.FILES)\n # form = UploadFileForm(data=request.POST, files=request.FILES)\n if form.is_valid():\n print('valid form')\n content_lines = form.cleaned_data['file_source']\n else:\n print('invalid form')\n print(form.errors)\n\nclass FileUploadView(FormView):\n \"\"\"A class to handle uploading a file\"\"\"\n template_name = \"finance/upload_file.html\"\n form_class = UploadFileForm\n \n def get_context_data(self, **kwargs):\n context = super(FileUploadView, self).get_context_data(**kwargs)\n\n return context\n \n def post(self, *args, **kwargs):\n print(self.request.FILES)\n \n@csrf_exempt\ndef get_accounts(request):\n \"\"\"Get a list of accounts for autocomplete\"\"\"\n\n if request.is_ajax():\n sName = \"\"\n sNumber = \"\"\n q = request.GET.get('term', '')\n p_id = request.GET.get('project_id', -1)\n # The 'term' may contain the name or the number (partly)\n lstQ = []\n lstQ.append(Q(project__id=p_id))\n # Check if there is a : in the name\n arQ = q.split(\":\", 1)\n if len(arQ)>1:\n sName = arQ[1].strip()\n sNumber = arQ[0].strip()\n lstQ.append(Q(name__icontains=sName)|Q(number__icontains=sNumber))\n else:\n lstQ.append(Q(name__icontains=q)|Q(number__icontains=q))\n accounts = Account.objects.filter(*lstQ)\n results = []\n for ac in accounts:\n ac_json = {'combi': \"{}: {}\".format(ac.number, ac.name)}\n results.append(ac_json)\n data = json.dumps(results)\n else:\n data = 'fail'\n mimetype = \"application/json\"\n return HttpResponse(data, mimetype)\n\n@csrf_exempt\ndef get_persons(request):\n \"\"\"Get a list of accounts for autocomplete\"\"\"\n\n if request.is_ajax():\n q = request.GET.get('term', '')\n p_id = request.GET.get('project_id', -1)\n # The 'term' may contain the name or the number (partly)\n lstQ = []\n lstQ.append(Q(org__project__id=p_id))\n lstQ.append(Q(name__icontains=q))\n people = Person.objects.filter(*lstQ)\n results = []\n for person in people:\n person_json = {'combi': \"{}\".format(person.name)}\n results.append(person_json)\n data = json.dumps(results)\n else:\n data = 'fail'\n mimetype = \"application/json\"\n return HttpResponse(data, mimetype)\n\n@csrf_exempt\ndef import_data(request, soort, object_id=None):\n \"\"\"Import data for a project: csv, json etc\"\"\"\n\n # Initialisations\n # NOTE: do not add a breakpoint until *AFTER* form.is_valid\n arErr = []\n error_list = []\n transactions = []\n data = {'status': 'ok', 'html': ''}\n template_name = 'finance/import_data.html'\n obj = None\n data_file = \"\"\n bClean = False\n\n # Check if the user is authenticated and if it is POST\n if not request.user.is_authenticated or request.method == 'POST':\n form = UploadFileForm(request.POST, request.FILES)\n if form.is_valid():\n # NOTE: from here a breakpoint may be inserted!\n print('valid form')\n # Get the contents of the imported file\n data_file = request.FILES['file_source']\n\n person_list = []\n\n # Get the 'obj' to this project (or 'None' if it is a new one)\n if object_id is None:\n # User must first choose a project\n arErr.append(\"First specify a project\")\n else:\n # Get the instance of this project object\n obj = Project.objects.get(pk=object_id)\n\n # Get the source file\n if data_file == None or data_file == \"\":\n arErr.append(\"No source file specified for the selected project\")\n else:\n # Read the data for the selected project\n oResult = obj.read_data(data_file, arErr, sSoort= soort)\n\n if 'trans_list' in oResult:\n result = oResult['trans_list']\n\n if result != None:\n # The 'result' should be all the processed transactions\n transactions = obj.transactions.filter(Q(id__in=result))\n\n # In this case also determine which persons have been added\n person_list = obj.org.persons.filter(Q(sync='false'))\n missing_exp = [] if 'missing_exp' not in oResult else oResult['missing_exp']\n missing_inc = [] if 'missing_inc' not in oResult else oResult['missing_inc']\n\n # Get a list of errors\n error_list = [str(item) for item in arErr]\n\n # Create the context\n context = dict(\n object_id = object_id,\n original=obj,\n transactions=transactions,\n person_list=person_list,\n missing_exp=missing_exp,\n missing_inc=missing_inc,\n error_list=error_list\n )\n\n if len(arErr) == 0:\n # Get the HTML response\n data['html'] = render_to_string(template_name, context, request)\n else:\n data['html'] = \"Please log in before continuing\"\n\n\n else:\n data['html'] = 'invalid form: {}'.format(form.errors)\n data['status'] = \"error\"\n else:\n data['html'] = 'Only use POST and make sure you are logged in'\n data['status'] = \"error\"\n \n # Return the information\n return JsonResponse(data)\n\n\ndef import_excel_data(request, soort, object_id=None):\n \"\"\"Import Excel data for a project\"\"\"\n\n # Initialisations\n arErr = []\n error_list = []\n transactions = []\n data = {'status': 'ok', 'html': ''}\n template_name = 'finance/import_data.html'\n obj = None\n bClean = False\n\n # Check if the user is authenticated\n if not request.user.is_authenticated:\n # Simply redirect to the home page\n return redirect('nlogin')\n\n # Get the 'obj' to this project (or 'None' if it is a new one)\n if object_id is None:\n # User must first choose a project\n arErr.append(\"First specify a project\")\n else:\n # Get the instance of this project object\n obj = Project.objects.get(pk=object_id)\n\n # Get the source file\n source_file = obj.source\n if source_file == None or source_file == \"\":\n arErr.append(\"No source file specified for the selected project\")\n else:\n\n if bClean:\n # Clean if from scratch\n if soort == 'alles':\n obj.clean_transactions()\n obj.clean_persons()\n elif soort == 'in_bank':\n # Only clean some stuff\n obj.clean_transactions(1100, 'debet')\n elif soort == 'in_incas' or soort == 'in_ideal':\n # Only clean some stuff\n obj.clean_transactions(1185, 'debet')\n elif soort == 'in_storn':\n # Only clean some stuff\n obj.clean_transactions(1185, 'credit')\n elif soort == 'uit_bank':\n # Only clean some stuff\n obj.clean_transactions(1100, 'credit')\n elif soort == 'uit_incasso':\n # Only clean some stuff\n pass\n elif soort == 'uit_ong':\n # do not do any cleaning ahead\n pass\n elif soort == 'uit_reizen':\n pass\n elif soort == 'in_spaar':\n pass\n\n # Read the source into this year\n result = obj.read_from_excel(source_file, arErr, sType= '2017', sSoort= soort)\n\n if result:\n # Get all the transactions for this particular project\n transactions = obj.transactions.all()\n\n # Get a list of errors\n error_list = [str(item) for item in arErr]\n\n # Create the context\n context = dict(\n object_id = object_id,\n original=obj,\n transactions=transactions,\n error_list=error_list\n )\n\n if len(arErr) == 0:\n # Get the HTML response\n data['html'] = render_to_string(template_name, context, request)\n else:\n data['html'] = \"Please log in before continuing\"\n\n # Return the information\n return JsonResponse(data)\n\ndef import_excel_2017(request, soort, object_id=None):\n \"\"\"Import the Excel for 2017 of the Mangoboom\"\"\"\n\n # Initialisations\n template = 'finance/import_2017.html'\n arErr = []\n bClean = False\n\n # Check if the user is authenticated\n if not request.user.is_authenticated:\n # Simply redirect to the home page\n return redirect('nlogin')\n\n # Get the 'obj' to this project (or 'None' if it is a new one)\n if object_id is None:\n obj = Project.get_project(\"De Mangoboom\", 2017)\n if obj == None:\n arErr.append(\"Cannot find the 2017 Mangoboom project\")\n else:\n object_id = obj.id\n else:\n # Get the instance of this project object\n obj = Project.objects.get(pk=object_id)\n\n intro_message = \"Transacties voor de Mangoboom van 2017\"\n intro_breadcrumb = \"[{}]\".format(obj.org.name)\n # Get the source file\n source_file = obj.source\n if source_file == None or source_file == \"\":\n arErr.append(\"No source file specified\")\n\n # Debugging: take the test file instead\n source_file = os.path.dirname(source_file) + \"/test.xlsx\"\n\n if bClean:\n # Clean if from scratch\n if soort == 'alles':\n obj.clean_transactions()\n obj.clean_persons()\n elif soort == 'in_bank':\n # Only clean some stuff\n obj.clean_transactions(1100, 'debet')\n elif soort == 'in_incas' or soort == 'in_ideal':\n # Only clean some stuff\n obj.clean_transactions(1185, 'debet')\n elif soort == 'in_storn':\n # Only clean some stuff\n obj.clean_transactions(1185, 'credit')\n elif soort == 'uit_bank':\n # Only clean some stuff\n obj.clean_transactions(1100, 'credit')\n elif soort == 'uit_incasso':\n # Only clean some stuff\n pass\n elif soort == 'uit_ong':\n # do not do any cleaning ahead\n pass\n elif soort == 'uit_reizen':\n pass\n elif soort == 'in_spaar':\n pass\n\n # Read the source into this year\n result = obj.read_from_excel(source_file, arErr, sType= '2017', sSoort= soort)\n\n transactions = []\n if result:\n # Get all the transactions for this particular project\n transactions = obj.transactions.all()\n\n # Get a list of errors\n error_list = [str(item) for item in arErr]\n\n # Create the context\n context = dict(\n object_id = object_id,\n original=obj,\n transactions=transactions,\n intro_message=intro_message,\n intro_breadcrumb=intro_breadcrumb,\n error_list=error_list\n )\n\n # Open the template that allows Editing an existing or Creating a new research project\n # or editing the existing project\n # return render(request, template, context)\n return redirect(reverse('trans_list', kwargs={'year': '2017'}))\n\n\ndef person_repair(request):\n \"\"\"Repair persons for Mangoboom 2017\"\"\"\n\n oErr = ErrHandle()\n context = { \n 'title':'Person Repair',\n 'message':'DoubEnFi repair utility',\n 'year':datetime.now().year, \n 'msg': 'Initial'}\n wijzigingen = 0\n verwijderingen = 0\n try:\n # Get the project we are looking at\n iYear = 2017\n project = Project.get_project(\"De Mangoboom\", iYear)\n # Get a sorted list of all the persons attached to this project\n qsp = project.org.persons.all().order_by('iban', '-name')\n # Walk this list\n iban = \"\"\n last_person = None\n person_list = []\n for person in qsp:\n # Check if the iban of this person is the same as the previous one\n if person.iban == iban:\n # We already had a person with this iban\n # Find all transactions this person is attached to\n qst = project.transactions.filter(person=person)\n with transaction.atomic():\n for trans_this in qst:\n # Adapt the person for this transaction\n trans_this.person = last_person\n # Keep track of the number of changes\n wijzigingen += 1\n # Save the changes\n trans_this.save()\n if project.transactions.filter(person=person).count() == 0:\n # There are no transactions tied to this person, so put it in the list to be removed\n person_list.append(person.id)\n else:\n # Adapt the iban and the last_person\n iban = person.iban\n last_person = person\n # If we have a list of people to be removed, then do that\n if len(person_list) > 0:\n project.org.persons.filter(id__in=person_list).delete()\n verwijderingen = len(person_list)\n\n context['msg'] = \"Wijzigingen: {}. Verwijderingen: {}\".format(wijzigingen, verwijderingen)\n except:\n oErr.DoError(\"person_repair error\")\n context['msg'] = \"SOrry, there was an error\"\n\n # Return a rendered page\n return render( request, 'repair.html', context )\n\n\ndef repair_ong_2017(request):\n \"\"\"Check and repair (dates) of ONG account for Mangoboom 2017\"\"\"\n\n oErr = ErrHandle()\n context = { \n 'title':'ONG Repair',\n 'message':'DoubEnFi repair utility',\n 'year':datetime.now().year, \n 'msg': 'Initial'}\n try:\n # Get the project we are looking at\n iYear = 2017\n project = Project.get_project(\"De Mangoboom\", iYear)\n\n # Get a sessionID\n oVault = project.vault.get_session_id()\n if oVault['status'] == \"ok\" and 'sessionId' in oVault:\n # We have a sessionId an all that is needed -- synchronize now\n oBack = project.vault.repair_ong_2017(project, oVault['sessionId'])\n context['msg'] = oBack['msg']\n\n else:\n context['msg'] = \"Could not open a session with Conscribo\"\n except:\n oErr.DoError(\"sync_prj_start error\")\n context['msg'] = \"sync_prj_start error\"\n\n # Return a rendered page\n return render( request, 'repair.html', context )\n\n\ndef sync_prj_start(request):\n \"\"\"Synchronize a project\"\"\"\n\n oErr = ErrHandle()\n data = {'status': 'starting'}\n try:\n # Get the user\n username = request.user.username\n # Get the synchronisation type parameter\n get = request.GET\n synctype = \"\" if not 'synctype' in get else get['synctype']\n project_id = \"\" if not 'project_id' in get else get['project_id']\n\n if synctype == '':\n # Formulate a response\n data['status'] = 'no sync type specified'\n else:\n # Remove previous status objects for this combination of user/type\n lstQ = []\n lstQ.append(Q(user=username))\n lstQ.append(Q(type=synctype))\n qs = Status.objects.filter(*lstQ)\n qs.delete()\n\n # Create a status object for this combination of synctype/user\n oStatus = Status(user=username, type=synctype, status=\"preparing\")\n oStatus.save()\n \n # Formulate a response\n data['status'] = 'done'\n\n if synctype == \"journal\" or synctype == \"update\":\n # We are synchronizing transactions with the service\n project = Project.objects.filter(id=project_id).first()\n if project == None:\n # No project found\n data['status'] ='error'\n oStatus.set(\"error\", msg=\"Cannot find project with id {}\".format(project_id))\n elif project.vault==None:\n # No project found\n data['status'] ='error'\n oStatus.set(\"error\", msg=\"This project has no Vault {}\".format(project.org.name))\n else:\n # Get a sessionID\n oVault = project.vault.get_session_id()\n oStatus.set(\"authenticated\", msg=\"We are authenticated...\")\n if oVault['status'] == \"ok\" and 'sessionId' in oVault:\n # We have a sessionId an all that is needed \n\n # First try to synchronize the persons\n if project.org.persons.filter(sync='false').count() > 0:\n oRelationsResponse = project.vault.sync_persons(project, oVault['sessionId'], oStatus, synctype)\n if oRelationsResponse == None or not 'status' in oRelationsResponse or oRelationsResponse['status'] != 'ok':\n # Something has gone wrong\n if 'msg' in oRelationsResponse:\n response['msg'] = oRelationsResponse['msg']\n return response\n\n # Make sure to check for new persons - persons may have failed to synchronize in the previous step\n person_list = project.org.persons.filter(sync='false').order_by('id')\n total = person_list.count()\n if total > 0:\n # New persons need to be added\n data['status'] = 'error'\n data['msg'] = 'First add {} new persons manually in Conscribo'.format(total)\n oStatus.set(\"error\", 'First add {} new persons manually in Conscribo and indicate it is synced'.format(total))\n else:\n oBack = project.vault.sync_transactions(project, oVault['sessionId'], oStatus, synctype)\n if oBack['status'] == 'ok':\n data['status'] = \"finished\"\n data['msg'] = oBack['msg']\n else:\n data['status'] = \"error\"\n data['msg'] = oBack['msg']\n else:\n data['status'] ='error'\n oStatus.set(\"error\", msg=\"Getting a sessionid for this project's vault returns: {}\".format(oVault['msg']))\n else:\n oData['status'] = 'error'\n oStatus.set(\"error\", msg=\"Unknown synchronisation type {}\".format(synctype))\n\n except:\n oErr.DoError(\"sync_prj_start error\")\n data['status'] = \"error\"\n\n # Return this response\n return JsonResponse(data)\n\n\ndef sync_prj_progress(request):\n \"\"\"Get the progress on the prj synchronisation\"\"\"\n\n oErr = ErrHandle()\n data = {'status': 'preparing'}\n\n try:\n # Get the user\n username = request.user.username\n # Get the synchronization type\n get = request.GET\n synctype = \"\"\n if 'synctype' in get:\n synctype = get['synctype']\n\n if synctype == '':\n # Formulate a response\n data['status'] = 'error'\n data['msg'] = \"no sync type specified\" \n\n else:\n # Formulate a response\n data['status'] = 'UNKNOWN'\n\n # Get the appropriate status object\n # sleep(1)\n oStatus = Status.objects.filter(user=username, type=synctype).first()\n\n # Check what we received\n if oStatus == None:\n # There is no status object for this type\n data['status'] = 'error'\n data['msg'] = \"Cannot find status for {}/{}\".format(\n username, synctype)\n else:\n # Get the last status information\n data['status'] = oStatus.status\n data['msg'] = \"[no message]\" if oStatus.msg == None else oStatus.msg\n data['count'] = oStatus.count\n\n # Return this response\n return JsonResponse(data)\n except:\n oErr.DoError(\"sync_prj_progress error\")\n data = {'status': 'error'}\n\n # Return this response\n return JsonResponse(data)\n\n","sub_path":"doubenfi/doubenfi/finance/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":120235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"569792240","text":"# import turtle as t\n#\n# polygon = t.Turtle()\n#\n#\n# var1 = input('면의 수는?')\n# var2 = input('면의 길이?')\n#\n# num_sides = int(var1)\n# side_length = int(var2)\n# angle = 360.0 / num_sides\n#\n# for i in range(num_sides):\n# polygon.forward(side_length)\n# polygon.right(angle)\n#\n# t.done()\n\nimport turtle as t\n\nprint('다각형을 그리는 예제입니다.')\nvar1 = input('변의 수를 입력해주세요? [3-8] ')\nvar2 = input('한변의 길이를 입력해주세요? [100-200] ')\n# var2 = str(150)\n\nnum_of_side = int(var1)\nlen_of_side = int(var2)\n\nangle = 360.0 / num_of_side\nc_mod = num_of_side % 3\ncolor = 'red' if c_mod==0 else 'green' if c_mod==1 else 'blue'\n\nt.begin_fill()\nt.color(color)\nt.pensize(5)\n\nfor i in range(num_of_side):\n t.forward(len_of_side)\n t.left(angle)\n\nt.end_fill()\n\nt.done()\n","sub_path":"Sect-A/source/sect00_turtle/PY-C03_for_polygon.py","file_name":"PY-C03_for_polygon.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"60733160","text":"import numpy as np\nfrom typing import Tuple\nfrom scipy.spatial.transform import Rotation\nfrom ..utilities import is_rotation_matrix, convert_angles_to_matrix\nfrom .Camera import Camera\nimport subprocess\nimport cv2\nimport os\n\n\nclass CameraBlenderQuat(Camera):\n file_name: str\n\n def __init__(self, image_shape: Tuple[int], file_name: str) -> None:\n # The image shape must be (rows, cols, channels = 3).\n assert len(image_shape) == 3 and image_shape[2] == 3\n Camera.__init__(self, image_shape)\n self.file_name = file_name\n\n def _render_with_pose(self, R: np.ndarray, t: np.ndarray) -> np.ndarray:\n quat = Rotation.from_matrix(R).as_quat()\n # print(quat)\n\n # Call the blender script.\n temp_image_location = \"tmp_blender_image.png\"\n command = f'blender -b \"{self.file_name}\" -P source/camera/blender_script_quat.py -- {temp_image_location} {self.image_shape[1]} {self.image_shape[0]} {quat[0]} {quat[1]} {quat[2]} {quat[3]} {t[0]} {t[1]} {t[2]}'\n # from IPython import embed; embed()\n process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)\n process.wait()\n\n # Collect the K matrix from stdout.\n # This is really hacky.\n k_matrix_index = None\n k_matrix_elements = []\n for line in iter(process.stdout.readline,''):\n line = str(line)\n if k_matrix_index is not None:\n number = line[2:-4]\n k_matrix_elements.append(float(number))\n k_matrix_index += 1\n if k_matrix_index == 9:\n break\n if \"K MATRIX INCOMING:\" in line:\n k_matrix_index = 0\n \n self.K = np.array(k_matrix_elements).reshape((3, 3))\n\n # Read, remove and return the image.\n image = cv2.imread(temp_image_location)\n os.remove(temp_image_location)\n return image\n\n def _get_K(self) -> np.ndarray:\n assert self.K is not None\n return self.K\n","sub_path":"source/camera/CameraBlenderQuat.py","file_name":"CameraBlenderQuat.py","file_ext":"py","file_size_in_byte":2016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"43262560","text":"# Flask などの必要なライブラリをインポートする\nimport os\nimport glob\nfrom base64 import decodestring\nimport dbreader\nimport tweepy\nimport flask\n\n# 自身の名称を app という名前でインスタンス化する\napp = flask.Flask(__name__)\n# session用のキー\napp.secret_key = \"konokacyankawaii\"\n\n# DB一覧\nfilelist = []\n\n# Twitter認証用キー\nCONSUMER_KEY = \"Z0ZmTzB3cmFQdmV0Ym1KbFdqWWcwWHh1Rg==\"\nCONSUMER_SECRET = \"U3RIcEJYaFhFZFhUV09EaUxCVHd0TkFmT3c5TGtKdGJjZzJJOHZYaTVoNkhJeDlPWm4=\"\nCALLBACK_URL = \"http://localhost:5000/authed\" #実行環境によって変更すること\n\n# ここからウェブアプリケーション用のルーティングを記述\n# index にアクセスしたときの処理\n@app.route('/')\ndef index():\n # index.html をレンダリングする\n global filelist\n filelist = sorted([path.split(os.sep)[1].split('.')[0] for path in glob.glob(\"collect/*.db\")])\n return flask.render_template('index.html', dblist=filelist, select=filelist[-1])\n\n# aboutページ\n@app.route('/about')\ndef about():\n return flask.render_template('about.html')\n\n# twitter認証ページ\n@app.route('/twitter_auth', methods=['GET'])\ndef twitter_oauth():\n # tweepy でアプリのOAuth認証を行う\n key = decodestring(CONSUMER_KEY.encode(\"utf8\")).decode(\"ascii\")\n secret = decodestring(CONSUMER_SECRET.encode(\"utf8\")).decode(\"ascii\")\n auth = tweepy.OAuthHandler(key, secret, CALLBACK_URL)\n\n # 連携アプリ認証用の URL を取得\n redirect_url = auth.get_authorization_url()\n # 認証後に必要な request_token を session に保存\n # 辞書型で保管される\n flask.session['request_token'] = auth.request_token\n\n # リダイレクト\n return flask.redirect(redirect_url)\n\n# twitter認証完了ページ\n@app.route('/authed', methods=['GET'])\ndef twitter_authed():\n return flask.redirect(flask.url_for('index'))\n\n# /list にアクセスしたときの処理\n@app.route('/list', methods=['GET'])\ndef image_list():\n global filelist\n if flask.request.method == 'GET':\n # リクエストフォーム取得して\n date = flask.request.args.get('date')\n # 画像一覧生成\n try:\n images,count = dbreader.get_list(\"collect/\" + date + \".db\")\n except:\n return flask.render_template('error.html')\n # index.html をレンダリングする\n return flask.render_template('list.html',\n dblist=filelist, select=date, filelist=images, count=count)\n else:\n # エラーなどでリダイレクトしたい場合はこんな感じで\n return flask.redirect(flask.url_for('index'))\n\n# /search にアクセスしたとき\n@app.route('/search', methods=['GET'])\ndef image_search():\n global filelist\n if flask.request.method == 'GET':\n # リクエストフォーム取得して\n date = flask.request.args.get('date')\n userid = flask.request.args.get('userid')\n # 画像一覧生成\n try:\n images,count = dbreader.search_db(userid, \"collect/\" + date + \".db\")\n except:\n return flask.render_template('error.html')\n # index.html をレンダリングする\n return flask.render_template('list.html',\n dblist=filelist, select=date, filelist=images, count=count)\n else:\n # エラーなどでリダイレクトしたい場合はこんな感じで\n return flask.redirect(flask.url_for('index'))\n\n# /list/detail にアクセスしたときの処理\n@app.route('/list/detail', methods=['GET'])\ndef image_detail():\n if flask.request.method == 'GET':\n # リクエストフォーム取得して\n image_id = flask.request.args.get('id')\n date = flask.request.args.get('date')\n # 画像情報\n try:\n detail,html,count,idinfo = dbreader.get_detail(int(image_id), \"collect/\"+date+\".db\")\n except:\n return flask.render_template('error.html')\n # index.html をレンダリングする\n return flask.render_template('detail.html', \n data=detail, html=html, date=date, max=count, idcount=idinfo)\n else:\n # エラーなどでリダイレクトしたい場合はこんな感じで\n return flask.redirect(flask.url_for('index'))\n\n# 404エラー\n@app.errorhandler(404)\ndef page_not_found(error):\n return flask.render_template('error.html')\n\nif __name__ == '__main__':\n app.debug = True # デバッグモード有効化\n app.run(host='0.0.0.0') # どこからでもアクセス可能に","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"489466905","text":"\"\"\"\nGiven a singly linked list, determine if it is a palindrome.\n\nExample 1:\n\nInput: 1->2\nOutput: false\nExample 2:\n\nInput: 1->2->2->1\nOutput: true\nFollow up:\nCould you do it in O(n) time and O(1) space?\n\"\"\"\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nimport copy\nclass Solution(object):\n def isPalindrome(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: bool\n \"\"\"\n prev = None\n curr = copy.copy(head)\n length = 0\n while curr:\n length += 1\n temp = copy.copy(curr.next)\n curr.next = prev\n prev = curr\n curr = temp\n \n curr = head\n\n i = 1\n while i <= length/2:\n if curr.val != prev.val:\n return False\n \n curr = curr.next\n prev = prev.next\n i += 1\n \n return True\n","sub_path":"python/leetcode/linkedlist/PalindromeLinkedList.py","file_name":"PalindromeLinkedList.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"272271953","text":"# https://leetcode.com/problems/battleships-in-a-board/#/description\nclass Solution(object):\n def countBattleships(self, board):\n \"\"\"\n :type board: List[List[str]]\n :rtype: int\n \"\"\"\n ships = 0\n for i in range(len(board)):\n for j in range(len(board[0])):\n if board[i][j] == 'X':\n if i == 0 and j == 0:\n ships += 1\n elif i == 0 and board[i][j-1] != 'X':\n ships += 1\n elif j == 0 and board[i-1][j] != 'X':\n ships += 1\n elif board[i-1][j] != 'X' and board[i][j-1] != 'X':\n ships += 1\n return ships","sub_path":"battleships.py","file_name":"battleships.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"555122853","text":"def _binary_copt_transition_impl(settings, attr):\n if attr.set_features:\n # it's a binary\n feats = attr.set_features[:]\n print(attr.name + \": set_features: \" + str(feats))\n elif attr.capabilities:\n if len(attr.capabilities) > 0 and attr.capabilities[0] == \"_no_filter\":\n return {\"//custom_settings:mycopts\": settings[\"//custom_settings:mycopts\"]}\n\n # it's a shared library\n feats = []\n for feat in settings[\"//custom_settings:mycopts\"]:\n if feat in attr.capabilities:\n feats.append(feat)\n print(attr.name + \": Original features: \" + str(settings[\"//custom_settings:mycopts\"]) + \" / New features: \" + str(feats))\n\n return {\"//custom_settings:mycopts\": feats}\n\n_binary_copt_transition = transition(\n implementation = _binary_copt_transition_impl,\n inputs = [\"//custom_settings:mycopts\"],\n outputs = [\"//custom_settings:mycopts\"],\n)\n\ndef _library_copt_transition_impl(settings, attr):\n if len(attr.capabilities) > 0 and attr.capabilities[0] == \"_no_filter\":\n return {\"//custom_settings:mycopts\": settings[\"//custom_settings:mycopts\"]}\n\n feats = []\n for feat in settings[\"//custom_settings:mycopts\"]:\n if feat in attr.capabilities:\n feats.append(feat)\n print(attr.name + \": Original features: \" + str(settings[\"//custom_settings:mycopts\"]) + \" / New features: \" + str(feats))\n\n return {\"//custom_settings:mycopts\": feats}\n\n_library_copt_transition = transition(\n implementation = _library_copt_transition_impl,\n inputs = [\"//custom_settings:mycopts\"],\n outputs = [\"//custom_settings:mycopts\"],\n)\n\n# The implementation of transition_rule: all this does is copy the\n# cc_binary's output to its own output and propagate its runfiles\n# and executable to use for \"$ bazel run\".\n#\n# This makes transition_rule as close to a pure wrapper of cc_binary\n# as possible.\ndef _binary_transition_rule_impl(ctx):\n actual_binary = ctx.attr.actual_binary[0]\n outfile = ctx.actions.declare_file(ctx.label.name)\n cc_binary_outfile = actual_binary[DefaultInfo].files.to_list()[0]\n\n ctx.actions.run_shell(\n inputs = [cc_binary_outfile],\n outputs = [outfile],\n command = \"cp %s %s\" % (cc_binary_outfile.path, outfile.path),\n )\n return [\n DefaultInfo(\n executable = outfile,\n data_runfiles = actual_binary[DefaultInfo].data_runfiles,\n ),\n actual_binary[CcInfo],\n ]\n\ndef _library_transition_rule_impl(ctx):\n actual_library = ctx.attr.actual_library[0]\n return [actual_library[CcInfo]]\n\n# The purpose of this rule is to take a \"set_features\" attribute,\n# invoke a transition that sets --//custom_settings:mycopts to the\n# desired feature, then depend on a cc_binary whose deps will now\n# be able to select() on that feature.\n#\n# You could add a transition_rule directly in your BUILD file. But for\n# convenience we also define a cc_binary macro below so the BUILD can look\n# as close to normal as possible.\nbinary_transition_rule = rule(\n implementation = _binary_transition_rule_impl,\n attrs = {\n # This is where the user can set the feature they want.\n \"capabilities\": attr.string_list(),\n \"set_features\": attr.string_list(default = []),\n \"actual_binary\": attr.label(cfg = _binary_copt_transition),\n \"_whitelist_function_transition\": attr.label(\n default = \"@bazel_tools//tools/whitelists/function_transition_whitelist\",\n ),\n },\n # Making this executable means it works with \"$ bazel run\".\n executable = True,\n)\n\nlibrary_transition_rule = rule(\n implementation = _library_transition_rule_impl,\n fragments = [\"cpp\"],\n attrs = {\n # This is where the user can set the feature they want.\n \"capabilities\": attr.string_list(),\n \"actual_library\": attr.label(cfg = _library_copt_transition),\n \"_whitelist_function_transition\": attr.label(\n default = \"@bazel_tools//tools/whitelists/function_transition_whitelist\",\n ),\n \"_cc_toolchain\": attr.label(\n default = Label(\n \"@rules_cc//cc:current_cc_toolchain\", # copybara-use-repo-external-label\n ),\n ),\n },\n)\n\n# Convenience macro: this instantiates a transition_rule with the given\n# desired features, instantiates a cc_binary as a dependency of that rule,\n# and fills out the cc_binary with all other parameters passed to this macro.\n#\n# The result is a wrapper over cc_binary that \"magically\" gives it a new\n# feature-setting attribute. The only difference for a BUILD user is they need\n# to load() this at the top of the BUILD file.\ndef cc_binary(name, capabilities = [\"_no_filter\"], set_features = [], **kwargs):\n cc_binary_name = \"native_binary_\" + name\n binary_transition_rule(\n name = name,\n actual_binary = \":%s\" % cc_binary_name,\n capabilities = capabilities,\n set_features = set_features,\n )\n native.cc_binary(\n name = cc_binary_name,\n **kwargs\n )\n\ndef cc_library(name, capabilities = [\"_no_filter\"], **kwargs):\n cc_library_name = \"native_library_\" + name\n library_transition_rule(\n name = name,\n actual_library = \":%s\" % cc_library_name,\n capabilities = capabilities,\n )\n native.cc_library(\n name = cc_library_name,\n **kwargs\n )\n","sub_path":"cc_binary_selectable_copts_list/defs.bzl","file_name":"defs.bzl","file_ext":"bzl","file_size_in_byte":5401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"439021869","text":"# Spend all money\n\ndef getMoneySpent():\n list_log = ['getMoneySpent()']\n size = 3\n c = []\n d = []\n b = 72\n keyboards = [10, 2, 3]\n drives = [3, 1]\n\n i = 0\n j = 0\n k = 0\n\n while i < size:\n while j < size:\n val = keyboards[i] + drives[i]\n c.append(val)\n j += 1\n k += 1\n i += 1\n k += 1\n\n i = 0\n while i < len(c):\n if c[i] <= b:\n d.append(c[i])\n elif c[i] > b:\n print(\"-1\")\n i += 1\n\n i = 0\n maxi = 0\n while i < len(d):\n if d[i] == 0:\n maxi = d[0]\n elif d[i] > d[i - 1]:\n maxi = d[i]\n i += 1\n\n print(maxi)\n\n list_log.append(maxi)\n\n return list_log\n\n\n\n\n","sub_path":"JediDays/spendAllMoney.py","file_name":"spendAllMoney.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"594473908","text":"'''\nUsage: nbbo_hfa.py stock-ticker high-freq-threshold quote-file nbbo-dir\nexample: nbbo.py FB 30 hdfs://npatwa91.54310/w251/final/nbbo\nIf high-freq-threshold is not provided, 50 is default.\nIf stock-ticker is not provided, \"AAPL\" is default\nIf quote-file is not provided, \"hdfs://npatwa91:54310/w251/final/taqquote20131218\" is default.\nIf nbbo-dir is not provided, \"hdfs://npatwa91.54310/w251/final/nbbo\" is default\n\nOutput: nbbo //NBBO (ms, (best-bid-price, best-ask-price)) HDFS file \n nbbo_alerts.txt //alerts of HFT, unix file on driver\n nbbo_secsummary //per-second summary of avg best-bid, best-ask and #of crossings, unix file on driver\n\nThis program examines dailyquotes file for a particular stock,\nfinds best bid and best ask every milliseconds, generates an nbbo file in HDFS\nIt then finds average of best bid and best ask every second and then\nfinds #of times within each second the best bid and best ask crosses the average,\nwhich is indicative of high-frequency trading. This count is compared against \nthe threshold and the program prints the seconds during which the number of crossings \nexceed the threshold.\n\n\n\nREF:\nfields of dailyquotes file taqquote\n[0:8]HHMMSSXXX\n[9] text EXCHANGE N Nyse T/Q NASDAQ\n[10:25] text symbol 6+10\n[26:36] bid price 7+4\n[37:43] bid size (units)\n[44:54] ask price 7+4\n[55:61] ask size\n[62] text Condition of quote\n[63:66] market maker\n[67] bid exchange\n[68] ask aexchange\n[69:84] int seqno\n[85] int bbo indicator\n[86] int NASDAQ BBO indocator\n[87] text cancel/correction\n[88] text C=CTA N=UTP\n[90] text Retail interest indicator\n[...]\n'''\n#spark-submit --master spark://npatwa91.softlayer.com:7077 --driver-memory 4G --executor-memory 4G nbbo_npatwa.py\n#spark-submit --master spark://npatwa91.softlayer.com:7077 --conf spark.driver.memory=4G --conf spark.executor.memory=4G \n\nfrom pyspark import SparkContext, SparkConf\n\nconf = SparkConf().setAppName(\"nbbo_hfalert\")\n#conf.set(\"spark.master\", \"spark://npatwa91.softlayer.com:7077\")\n#conf.set(\"spark.driver.memory\", \"4G\")\n#conf.set(\"spark.executor.memory\", \"4G\")\n\nsc = SparkContext(conf = conf)\n\n# P Y S P A R K \n#pyspark --master spark://npatwa91.softlayer.com:7077 --driver-memory 4G --executor-memory 4G\n#----------------------------------------------------------------------------------------------------\n\nimport sys\n\n#defaults\n\nstock = \"AAPL\"\nHFTH = 50\nquotefile = \"hdfs://npatwa91:54310/w251/final/taqquote20131218\"\nnbbo_dir = \"hdfs://npatwa91:54310/w251/final/nbbo\"\n\nif (len(sys.argv) == 5):\n stock = str(sys.argv[1])\n HFTH = int(sys.argv[2])\n quotefile = str(sys.argv[3]) \n nbbo_dir = str(sys.argv[4]) \nif (len(sys.argv) == 4):\n stock = str(sys.argv[1])\n HFTH = int(sys.argv[2])\n quotefile == str(sys.argv[3]) \nif (len(sys.argv) == 3): \n stock = str(sys.argv[1])\n HFTH = int(sys.argv[2])\nelif (len(sys.argv) == 2):\n stock = str(sys.argv[1])\nelse:\n print (\"Using defaults for arguments.\\n\")\n\n\ndef crossings_cnt(mytuple):\n #mytuple: ([(ms1, p1), (ms2, p2)..], avg)\n avg = mytuple[1]\n mylist = mytuple[0]\n edgecnt = 0\n direction = 2 # undefined\n mylistsorted = sorted(mylist, key=lambda rec: rec[0])\n for i in range(len(mylistsorted)):\n price = mylist[i] [1]\n if (price > avg):\n newdir = 1 # upper half\n else:\n newdir = 0 # lower half\n if (direction != 2) and (newdir != direction):\n edgecnt = edgecnt + 1\n direction = newdir\n return(edgecnt)\n\n\n\nRDD = sc.textFile(quotefile)\n\nstockRDD = RDD.filter(lambda line: stock in line)\nrecords = stockRDD.map(lambda line: [line[0:9], line[9], line[10:26].strip(), float(line[26:37])/10000, int(line[37:44]), float(line[44:55])/10000, int(line[55:62]), line[62]])\n# find records for the given stock\napple = records.filter(lambda rec: stock in rec[2])\n\n# create k-v for exchange etc for examining data\n#appleexch = apple.map(lambda rec: (rec[1], rec)) # key is the exchange\n#applesec = apple.map(lambda rec: (rec[0] [0:6], rec)) # key is time in seconds\n#applecond = apple.map(lambda rec: (rec[7], rec)) # key is the condition\n#appleexch.countByKey()\n\n# create k-v with millisecond as the key and bid or ask as value\nbid = apple.map(lambda rec: (rec[0], rec[3]))\nask = apple.map(lambda rec: (rec[0], rec[5]))\n\n# find max bid and min ask for every milli second - they are best bid and best ask\nbestbid = bid.reduceByKey(max) #format: key=millisecond value=max-price\nbestask = ask.reduceByKey(min) #format: key=millisecond, value=min-price\nnbbo = bestbid.join(bestask) #format: key=millisecond, value=(max-bid, min-ask)\n\nnbbo.saveAsTextFile(nbbo_dir)\n\n\n# find average values over a second of best bid and best ask\nbbsec = bestbid.map(lambda rec: (rec[0] [0:6], rec[1])) #key=sec, value=min-price\nbbsecagg = bbsec.mapValues(lambda x: (x, 1)).reduceByKey(lambda x, y: (x[0] + y[0], x[1] + y[1])) #append count and then total\nbbsecavg = bbsecagg.map(lambda rec: (rec[0], (rec[1] [0])/(rec[1] [1])))\n\nbasec = bestask.map(lambda rec: (rec[0] [0:6], rec[1]))\nbasecagg = basec.mapValues(lambda x: (x, 1)).reduceByKey(lambda x, y: (x[0] + y[0], x[1] + y[1]))\nbasecavg = basecagg.map(lambda rec: (rec[0], (rec[1] [0])/(rec[1] [1])))\n\n# go back to bestbid millisecond and create a second key, but maintain millisecond value\n# IMPORTANT: create a list object with tuple inside to allow + operator in reduce function to work\n\nbestbidsec = bestbid.map(lambda rec: (rec[0] [0:6], [(rec[0], rec[1])])) #key=second, value = (ms, value)\nbestasksec = bestask.map(lambda rec: (rec[0] [0:6], [(rec[0], rec[1])]))\nbestbidlist = bestbidsec.reduceByKey(lambda x, y: x + y) #list addition, this will fuse the records\n#bestbidlist = bestbidsec.reduceByKey(lambda x, y: [x[0] + y[0], x[1] + y[1]]) #list addition, this will fuse the records\nbestasklist = bestasksec.reduceByKey(lambda x, y: x + y)\n\n# join so that you get (sec, (best ms, secavg)) \nbbjoin = bestbidlist.join(bbsecavg) # key=second, value = ([(ms1, value1), (ms2, value2), (ms3, value3)], avg)\nbajoin = bestasklist.join(basecavg)\n\n#groupBy is going to collect all values of a key and send them to one node.\n# Spark does not recommend using it, but often one needs sorted value list to operate on.\n# crossingscnt is that task\n#reduceBy/aggregateBy is going to do combining at the source node and then send results to one node. \n# Above works well for aggregate functions that can be done in parallel, e.g. count, min, max\n#combineByKey is more general function. \n#createCombiner\n#mergeValue\n#mergeCombiner\n\n# find number of times each second the best bid and best ask crosses the average\nbbfreq = bbjoin.mapValues(crossings_cnt) # value = #of crossings\nbafreq = bajoin.mapValues(crossings_cnt)\n\n# filter seconds where crossings_count exceed the threshold \nbbfreqgth = bbfreq.filter(lambda rec: rec[1] > HFTH).sortByKey().collect()\nbafreqgth = bafreq.filter(lambda rec: rec[1] > HFTH).sortByKey().collect()\n\nfp = open(\"nbbo_alerts.txt\", 'w')\nprint >>fp, \"Best Buy High Frequency Alerts\\n\"\nfor i in range(len(bbfreqgth)):\n localkey = bbfreqgth[i] [0]\n localfreq = bbfreqgth[i] [1]\n localvalues = bbjoin.lookup(localkey)[0] # get a tuple ([(ms, price), (ms, price), ...], avg)\n localavg = localvalues[1]\n locallist = sorted(localvalues[0], key=lambda rec: rec[0])\n print >>fp, \"Second: \", localkey, \"avg price: \", localavg, \"#of crossings: \", localfreq\n print >>fp, '\\t', \"millisecond\", '\\t', \"price\"\n for j in range(len(locallist)):\n print >>fp, '\\t', locallist[j] [0], '\\t', format(locallist[j] [1], '0.3f') \n\nprint >>fp, \"\\nBest Ask High Frequency Alerts\\n\"\n\nfor i in range(len(bafreqgth)):\n localkey = bafreqgth[i] [0]\n localfreq = bafreqgth[i] [1]\n localvalues = bajoin.lookup(localkey)[0] # get a tuple ([(ms, price), (ms, price), ...], avg)\n localavg = localvalues[1]\n locallist = sorted(localvalues[0], key=lambda rec: rec[0])\n print >>fp, \"Second: \", localkey, \"avg price: \", localavg, \"#of crossings: \", localfreq\n print >>fp, '\\t', \"millisecond\", '\\t', \"price\"\n for j in range(len(locallist)):\n print >>fp, '\\t', locallist[j] [0], '\\t', format(locallist[j] [1], '0.3f') \n\nfp.close()\n\n#if collect was not used, this can be used\n#bbfreqgth.saveAsTextFile(\"hdfs://npatwa91:54310/w251/final/bbfreqgth\")\n#bafreqgth.saveAsTextFile(\"hdfs://npatwa91:54310/w251/final/bafreqgth\")\n\n\n# create a per-second record of NBBO and #of crossings around average\n\nnbbofreq = bbfreq.join(bafreq) # create a value tuple tuple (#of crossings best-bid, #of crossings best-ask)\nnbboavg = bbsecavg.join(basecavg) # average per second of best bid and best ask\nnbbosec = nbboavg.join(nbbofreq) # create a tuple of ((avg-best-bid, avg-best-ask), (#of crossings best-bid, #of crossings best-ask))\nnbbosec = nbbosec.sortByKey() # created sorted list\nnbbo_secsummary = nbbosec.collect()\n\nfp = open(\"nbbo_secsummary.txt\", 'w')\nprint >>fp, \"(second, ((avg best buy, avg best ask), (#crossings best buy, #crossings best ask)))\\n\"\nfor i in range(len(nbbo_secsummary)):\n# nbbo_secsummary[i] [1] [0] [0] = format(nbbo_secsummary[i] [1] [0] [0], '0.3f')\n# nbbo_secsummary[i] [1] [0] [1] = format(nbbo_secsummary[i] [1] [0] [1], '0.3f')\n print >>fp, nbbo_secsummary[i] \n\nfp.close()\n\n#if collect was not used, this an be used\n#nbbosec.saveAsTextFile(\"hdfs://npatwa91:54310/w251/final/nbbosec_avg_freq\")\n","sub_path":"scratch/nbbo_npatwa.py","file_name":"nbbo_npatwa.py","file_ext":"py","file_size_in_byte":9393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"560584304","text":"class Solution:\n\n rank = {}\n graph = defaultdict(list)\n conn_dict = {}\n\n def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]:\n\n self.formGraph(n, connections)\n self.dfs(0, 0)\n\n result = []\n for u, v in self.conn_dict:\n result.append([u, v])\n\n return result\n\n def dfs(self, node: int, discovery_rank: int) -> int:\n\n # That means this node is already visited. We simply return the rank.\n if self.rank[node]:\n return self.rank[node]\n\n # Update the rank of this node.\n self.rank[node] = discovery_rank\n\n # This is the max we have seen till now. So we start with this instead of INT_MAX or something.\n min_rank = discovery_rank + 1\n for neighbor in self.graph[node]:\n\n # Skip the parent.\n if self.rank[neighbor] and self.rank[neighbor] == discovery_rank - 1:\n continue\n\n # Recurse on the neighbor.\n recursive_rank = self.dfs(neighbor, discovery_rank + 1)\n\n # Step 1, check if this edge needs to be discarded.\n if recursive_rank <= discovery_rank:\n del self.conn_dict[(min(node, neighbor), max(node, neighbor))]\n\n # Step 2, update the minRank if needed.\n min_rank = min(min_rank, recursive_rank)\n\n return min_rank\n\n def formGraph(self, n: int, connections: List[List[int]]):\n\n # Reinitialize for each test case\n self.rank = {}\n self.graph = defaultdict(list)\n self.conn_dict = {}\n\n # Default rank for unvisited nodes is \"null\"\n for i in range(n):\n self.rank[i] = None\n\n for edge in connections:\n\n # Bidirectional edges.\n u, v = edge[0], edge[1]\n self.graph[u].append(v)\n self.graph[v].append(u)\n\n self.conn_dict[(min(u, v), max(u, v))] = 1\n\n\n# Time Complexity: O(V + E)O(V+E) where VV represents the number of vertices and EE represents the number of edges in the graph. We process each node exactly once thanks to the rank dictionary also acting as a \"visited\" safeguard at the top of the dfs function. Since the problem statement mentions that the graph is connected, that means E >= VE>=V and hence, the overall time complexity would be dominated by the number of edges i.e. O(E)O(E).\n\n# Space Complexity: O(E)O(E). The overall space complexity is a sum of the space occupied by the connDict dictionary, rank dictionary, and graph data structure. E + V + (V + E)E+V+(V+E) = O(E)O(E).\n\n\n# Tarjan's algorithm\n\n# given an undirected graph and are asked to find the number of bridges in the graoh.\n# a bridge is essentially an edge whose removal would make the graph disconnected.\n# how could we apply existing knowledge of DFS to derive a solution\n# an edge is a critical connection if and only if it is not in a cycle\n\n# Depth first search for cycle detection\n\n# define a functio called dfs that takes in the node and the discoveryRank to be assigned to this node\n# the first step is to build the graph itself, for that we'll be using an adjacency list structure\n# since our algorithm involves discarding edges, we need some efficient data structure that will allow us to do this operation in O(1) time. We'll convert the list of edges into a dictionary for that.\n# name our graph and our connections dictionary as connDict.\n# use an array to keep track of the rank of our nodes. That's something we define in the main function criticalConnections along with all the things explained above.\n# within dfs,check if the node already has a rank assigned; if so, return that value\n# assign the rank of this node to the discoveryRank\n# iterate over all the neighbors of the node and for each of them, make a recursive call and obtain the recursiveRank as the return value and do two things using this value.\n# If this recursiveRank is less than the current discoveryRank, this means the edge is a part of the cycle and can be discarded.\n# second, record the minimum rank till now from amongst all the neighbors.\n# return the minRank\n# call the dfs function using the node 0 and rank 0 and once the search function completes, convert the remaining edges from connDict to a list and return that as the result.\n","sub_path":"2021_problems/1192_criticalconnectionsinanetwork_hard.py","file_name":"1192_criticalconnectionsinanetwork_hard.py","file_ext":"py","file_size_in_byte":4298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"492814843","text":"from unittest import TestCase\n\nfrom pymatgen.util.sequence import get_chunks, PBarSafe\n\n\nclass SequenceUtilsTest(TestCase):\n def setUp(self):\n self.sequence = list(range(100))\n\n def test_get_chunks(self):\n lengths = [len(chunk) for chunk in get_chunks(self.sequence, 30)]\n self.assertTrue(all(length == 30 for length in lengths[:-1]))\n self.assertEqual(lengths[-1], 10)\n\n def test_pbar_safe(self):\n pbar = PBarSafe(len(self.sequence))\n self.assertEqual(pbar.total, len(self.sequence))\n self.assertEqual(pbar.done, 0)\n pbar.update(10)\n self.assertEqual(pbar.done, 10)\n","sub_path":"pymatgen/util/tests/test_sequence.py","file_name":"test_sequence.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"653465967","text":"import settings\nimport uuid\n\n\ndef add_endpoint(path, methods):\n ep = {'id': str(uuid.uuid4()), 'path': path, 'methods': methods}\n ex = settings.mongo.authorization.endpoints.find_one({\"path\": ep.get(\"path\")})\n if not ex:\n settings.mongo.authorization.endpoints.insert_one(ep)\n else:\n print(\"Already exists:\\n{}\".format(ep))\n\n\ndef add_action(name, endpoints=[]):\n ep = {'id': str(uuid.uuid4()), 'name': name, 'endpoints': endpoints}\n ex = settings.mongo.authorization.actions.find_one({\"name\": ep.get(\"name\")})\n if not ex:\n settings.mongo.authorization.actions.insert_one(ep)\n else:\n print(\"Already exists:\\n{}\".format(ep))\n\n\ndef add_role(name, actions=[]):\n ep = {'id': str(uuid.uuid4()), 'name': name, 'actions': actions}\n ex = settings.mongo.authorization.roles.find_one({\"name\": ep.get(\"name\")})\n if not ex:\n settings.mongo.authorization.roles.insert_one(ep)\n else:\n print(\"Already exists:\\n{}\".format(ep))\n\n\ndef add_user(name, roles=[]):\n ep = {'id': str(uuid.uuid4()), 'name': name, 'roles': roles}\n ex = settings.mongo.authorization.users.find_one({\"name\": ep.get(\"name\")})\n if not ex:\n settings.mongo.authorization.users.insert_one(ep)\n else:\n print(\"Already exists:\\n{}\".format(ep))\n\n\ndef add_ships(filename):\n with open(filename, 'r') as fd:\n names = fd.readlines()\n for name in names:\n s = {'id': str(uuid.uuid4()), 'name': name.strip()}\n ex = settings.mongo.inventory.ships.find_one({\"name\": s.get(\"name\")})\n if not ex:\n settings.mongo.inventory.ships.insert_one(s)\n else:\n print(\"Already exists:\\n{}\".format(s))\n\n# add_ships(\"/tmp/tmp.txt\")\n#add_endpoint_to_action(\"3a758226-8831-4d5b-9dc7-592d94f553f6\", \"748d5254-3d45-4b13-8014-48ed9df5f363\")\n#add_endpoint(\"inventory/item/user/\", [\"POST\"])\n#add_action(\"inventory_all\", [\"8d953575-d44c-4e0d-a708-0b4b62431801\", \"df913fa9-1a17-4923-9d7e-9a210d27590c\", \"12b9d481-6615-49dd-8666-1b4ce63a5adf\", \"3a758226-8831-4d5b-9dc7-592d94f553f6\", \"cf570eae-d2ba-4307-a78f-25140f40ab77\"])\n#add_role(\"bot\", [\"cfbc7654-f01b-44c4-bfe0-7c902d6c4202\"])\nadd_user(\"bot\", [\"55ef7e16-9fb8-4e50-9f65-8347cc67c9cb\"])\n","sub_path":"test/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":2226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"233159838","text":"#https://nbviewer.org/github/amanchadha/coursera-deep-learning-specialization/blob/master/C5%20-%20Sequence%20Models/Week%201/Building%20a%20Recurrent%20Neural%20Network%20-%20Step%20by%20Step/Building_a_Recurrent_Neural_Network_Step_by_Step.ipynb\n\n\n#Dimensions of prediction ŷ \n#Similar to the inputs and hidden states, ŷ is a 3D tensor of shape (ny,m,Ty)\n#ny: number of units in the vector representing the prediction\n#m: number of examples in a mini-batch\n#Ty: number of time steps in the prediction\n#For a single time step t, a 2D slice ŷ ⟨t⟩ has shape (ny,m)\n#In the code, the variable names are:\n#y_pred: ŷ \n#yt_pred: ŷ ⟨t⟩\n\n\n\n# pakcage\nimport numpy as np\nfrom rnn_utils import *\nfrom public_tests import *\n\n\n# RNN.png\n\n###########################################\n# exercise 1 - rnn_cell_forward\n#Instructions:\n\n#Compute the hidden state with tanh activation: a⟨t⟩=tanh(Waaa⟨t−1⟩+Waxx⟨t⟩+ba)\n#Using your new hidden state a⟨t⟩, compute the prediction ŷ ⟨t⟩=softmax(Wyaa⟨t⟩+by). (The function softmax is provided)\n#Store (a⟨t⟩,a⟨t−1⟩,x⟨t⟩,parameters) in a cache\n#Return a⟨t⟩ , ŷ ⟨t⟩ and cache\n#Additional Hints\n#A little more information on numpy.tanh\n#In this assignment, there's an existing softmax function for you to use. It's located in the file 'rnn_utils.py' and has already been imported.\n#For matrix multiplication, use numpy.dot\n\n\n\n#Input with nx number of units\n#For a single time step of a single input example, x(i)⟨t⟩ is a one-dimensional input vector\n#Using language as an example, a language with a 5000-word vocabulary could be one-hot encoded into a vector that has 5000 units. So x(i)⟨t⟩ would have the shape (5000,)\n#The notation nx is used here to denote the number of units in a single time step of a single training example\n\n#Time steps of size Tx\n#A recurrent neural network has multiple time steps, which you'll index with t.\n#In the lessons, you saw a single training example x(i) consisting of multiple time steps Tx. In this notebook, Tx will denote the number of timesteps in the longest sequence.\n\n#Batches of size m\n#Let's say we have mini-batches, each with 20 training examples\n#To benefit from vectorization, you'll stack 20 columns of x(i) examples\n#For example, this tensor has the shape (5000,20,10)\n#You'll use m to denote the number of training examples\n\n\n\n\n# ? need to think why we need tanh function\n\n###########################################\n\ndef rnn_cell_forward(xt, a_prev, parameters):\n \"\"\"\n Implements a single forward step of the RNN-cell as described in Figure (2)\n\n Arguments:\n xt -- your input data at timestep \"t\", numpy array of shape (n_x, m).\n a_prev -- Hidden state at timestep \"t-1\", numpy array of shape (n_a, m)\n parameters -- python dictionary containing:\n Wax -- Weight matrix multiplying the input, numpy array of shape (n_a, n_x)\n Waa -- Weight matrix multiplying the hidden state, numpy array of shape (n_a, n_a)\n Wya -- Weight matrix relating the hidden-state to the output, numpy array of shape (n_y, n_a)\n ba -- Bias, numpy array of shape (n_a, 1)\n by -- Bias relating the hidden-state to the output, numpy array of shape (n_y, 1)\n Returns:\n a_next -- next hidden state, of shape (n_a, m)\n yt_pred -- prediction at timestep \"t\", numpy array of shape (n_y, m)\n cache -- tuple of values needed for the backward pass, contains (a_next, a_prev, xt, parameters)\n \"\"\"\n \n # Retrieve parameters from \"parameters\"\n Wax = parameters[\"Wax\"]\n Waa = parameters[\"Waa\"]\n Wya = parameters[\"Wya\"]\n ba = parameters[\"ba\"]\n by = parameters[\"by\"]\n \n ### START CODE HERE ### (≈2 lines)\n # compute next activation state using the formula given above\n a_next = np.tanh(np.dot(Waa,a_prev) + np.dot(Wax,xt) + ba)\n # compute output of the current cell using the formula given above\n yt_pred = softmax( np.dot(Wya,a_next) + by)\n ### END CODE HERE ###\n \n # store values you need for backward propagation in cache\n cache = (a_next, a_prev, xt, parameters)\n \n return a_next, yt_pred, cache\n \n \n # calling rnn_cell_forward\np.random.seed(1)\nxt_tmp = np.random.randn(3, 10)\na_prev_tmp = np.random.randn(5, 10)\nparameters_tmp = {}\nparameters_tmp['Waa'] = np.random.randn(5, 5)\nparameters_tmp['Wax'] = np.random.randn(5, 3)\nparameters_tmp['Wya'] = np.random.randn(2, 5)\nparameters_tmp['ba'] = np.random.randn(5, 1)\nparameters_tmp['by'] = np.random.randn(2, 1)\n\na_next_tmp, yt_pred_tmp, cache_tmp = rnn_cell_forward(xt_tmp, a_prev_tmp, parameters_tmp)\nprint(\"a_next[4] = \\n\", a_next_tmp[4])\nprint(\"a_next.shape = \\n\", a_next_tmp.shape)\nprint(\"yt_pred[1] =\\n\", yt_pred_tmp[1])\nprint(\"yt_pred.shape = \\n\", yt_pred_tmp.shape)\n\n# UNIT TESTS\nrnn_cell_forward_tests(rnn_cell_forward)\n\n\n# rnn_seq.png\n###########################################\n#Exercise 2 - rnn_forward\n#Implement the forward propagation of the RNN described in Figure 3.\n\n#Instructions:\n\n#Create a 3D array of zeros, a of shape (na,m,Tx) that will store all the hidden states computed by the RNN\n#Create a 3D array of zeros, ŷ , of shape (ny,m,Tx) that will store the predictions\n#Note that in this case, Ty=Tx (the prediction and input have the same number of time steps)\n#Initialize the 2D hidden state a_next by setting it equal to the initial hidden state, a0\n#At each time step t:\n#Get x⟨t⟩, which is a 2D slice of x for a single time step t\n#x⟨t⟩ has shape (nx,m)\n#x has shape (nx,m,Tx)\n#Update the 2D hidden state a⟨t⟩ (variable name a_next), the prediction ŷ ⟨t⟩ and the cache by running rnn_cell_forward\n#a⟨t⟩ has shape (na,m)\n#Store the 2D hidden state in the 3D tensor a, at the tth position\n#a has shape (na,m,Tx)\n#Store the 2D ŷ ⟨t⟩ prediction (variable name yt_pred) in the 3D tensor ŷ pred at the tth position\n#ŷ ⟨t⟩ has shape (ny,m)\n#ŷ has shape (ny,m,Tx)\n#Append the cache to the list of caches\n#Return the 3D tensor a and ŷ , as well as the list of caches\n#Additional Hints\n#Some helpful documentation on np.zeros\n#If you have a 3 dimensional numpy array and are indexing by its third dimension, you can use array slicing like this: var_name[:,:,i]\n \n###########################################\ndef rnn_forward(x, a0, parameters):\n \"\"\"\n Implement the forward propagation of the recurrent neural network described in Figure (3).\n\n Arguments:\n x -- Input data for every time-step, of shape (n_x, m, T_x).\n a0 -- Initial hidden state, of shape (n_a, m)\n parameters -- python dictionary containing:\n Waa -- Weight matrix multiplying the hidden state, numpy array of shape (n_a, n_a)\n Wax -- Weight matrix multiplying the input, numpy array of shape (n_a, n_x)\n Wya -- Weight matrix relating the hidden-state to the output, numpy array of shape (n_y, n_a)\n ba -- Bias numpy array of shape (n_a, 1)\n by -- Bias relating the hidden-state to the output, numpy array of shape (n_y, 1)\n\n Returns:\n a -- Hidden states for every time-step, numpy array of shape (n_a, m, T_x)\n y_pred -- Predictions for every time-step, numpy array of shape (n_y, m, T_x)\n caches -- tuple of values needed for the backward pass, contains (list of caches, x)\n \"\"\"\n \n # Initialize \"caches\" which will contain the list of all caches\n caches = []\n \n # Retrieve dimensions from shapes of x and parameters[\"Wya\"]\n n_x, m, T_x = x.shape\n n_y, n_a = parameters[\"Wya\"].shape\n \n ### START CODE HERE ###\n \n # initialize \"a\" and \"y_pred\" with zeros (≈2 lines)\n a = np.zeros((n_a, m, T_x))\n y_pred = np.zeros((n_y, m, T_x))\n \n # Initialize a_next (≈1 line)\n a_next = a0\n \n # loop over all time-steps\n for t in range(T_x):\n # Update next hidden state, compute the prediction, get the cache (≈1 line)\n a_next, yt_pred, cache = rnn_cell_forward(x[:,:,t], a_next, parameters)\n # Save the value of the new \"next\" hidden state in a (≈1 line)\n a[:,:,t] = a_next\n # Save the value of the prediction in y (≈1 line)\n y_pred[:,:,t] = yt_pred\n # Append \"cache\" to \"caches\" (≈1 line)\n caches.append(cache)\n ### END CODE HERE ###\n \n # store values needed for backward propagation in cache\n caches = (caches, x)\n\n return a, y_pred, caches\n\n# calling rnn_forward\nnp.random.seed(1)\nx_tmp = np.random.randn(3, 10, 4)\na0_tmp = np.random.randn(5, 10)\nparameters_tmp = {}\nparameters_tmp['Waa'] = np.random.randn(5, 5)\nparameters_tmp['Wax'] = np.random.randn(5, 3)\nparameters_tmp['Wya'] = np.random.randn(2, 5)\nparameters_tmp['ba'] = np.random.randn(5, 1)\nparameters_tmp['by'] = np.random.randn(2, 1)\n\na_tmp, y_pred_tmp, caches_tmp = rnn_forward(x_tmp, a0_tmp, parameters_tmp)\nprint(\"a[4][1] = \\n\", a_tmp[4][1])\nprint(\"a.shape = \\n\", a_tmp.shape)\nprint(\"y_pred[1][3] =\\n\", y_pred_tmp[1][3])\nprint(\"y_pred.shape = \\n\", y_pred_tmp.shape)\nprint(\"caches[1][1][3] =\\n\", caches_tmp[1][1][3])\nprint(\"len(caches) = \\n\", len(caches_tmp))\n\n#UNIT TEST \nrnn_forward_test(rnn_forward)\n\n#Situations when this RNN will perform better:\n#This will work well enough for some applications, but it suffers from vanishing gradients.\n#The RNN works best when each output ŷ ⟨t⟩ can be estimated using \"local\" context.\n#\"Local\" context refers to information that is close to the prediction's time step t.\n#More formally, local context refers to inputs x⟨t′⟩ and predictions ŷ ⟨t⟩ where t′ is close to t.\n#What you should remember:\n\n#The recurrent neural network, or RNN, is essentially the repeated use of a single cell.\n#A basic RNN reads inputs one at a time, and remembers information through the hidden layer activations (hidden states) that are passed from one time step to the next.\n#The time step dimension determines how many times to re-use the RNN cell\n#Each cell takes two inputs at each time step:\n#The hidden state from the previous cell\n#The current time step's input data\n#Each cell has two outputs at each time step:\n#A hidden state\n#A prediction \n","sub_path":"recurrent_neuron_network.py","file_name":"recurrent_neuron_network.py","file_ext":"py","file_size_in_byte":10242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"200752119","text":"# Uses python3\nclass Node(object):\n\n def __init__(self, val):\n self.value = val\n self.count = 1\n self.left = None\n self.right = None\n\n\ndef search(node: Node, x):\n if node.value == x:\n node.count += 1\n return node\n if x < node.value:\n if node.left == None:\n node.left = Node(x)\n return node.left\n return search(node.left, x)\n if node.right == None:\n node.right = Node(x)\n return node.right\n return search(node.right, x)\n\nif __name__ == '__main__':\n n = int(input())\n half = n / 2\n str = input().split()\n root = Node(int(str[0]))\n for i in range(1, n):\n x = int(str[i])\n node = search(root, x)\n if node.count > half:\n print(1)\n exit()\n print(0)","sub_path":"src/main/python/_1_algorithmic_toolbox/_4_divide_and_conquere/majority_element.py","file_name":"majority_element.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"278018820","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\n\nimport csv\n\n\ndef read_region(path='aem_data/AEMO1213.csv', region_col=2):\n\t\"\"\"\n\topen and read an excel file\n\n\targs:\n\t\t- path: data path of region data\n\t\t- region: string containing region abbreviation\n\n\treturns:\n\t\t- region_data_total: energy output for a specified region in the form of\n\t\t\t\t\t\t\t [day, hour, previous_value, current_value]\n\t\"\"\"\n\n\t# open csv file\n\tcsv_file = pd.read_csv(path, parse_dates=['Date', 'Time'])\n\tcolumn_names = list(csv_file.columns.values)\n\tfarm_name = column_names[region_col]\n\n\t# get the data for the region specified by column\n\t# [day, time, energy_produced]\n\t# then delete first row which contains the column headers\n\tregion_data = csv_file\n\tregion_data = region_data.as_matrix()\n\tregion_data = region_data[:, [0, 1, region_col]]\n\n\t# data is now in format [day, hour, prediction]\n\t# now put it in format [day, hour, prediction, energy_input]\n\t# to do this - shift the predictions down, append a 0, delete the last row\n\t# finally, append then delete first row, since we dont have value from t = -1\n\t# final format is [day, hour, previous_value, current_value]\n\tenergy_input = region_data[:, 2]\n\tenergy_input = np.insert(energy_input, 0, 0)\n\tenergy_input = energy_input[0:-1]\n\tenergy_input = energy_input.reshape(-1, 1)\n\tregion_data = np.concatenate((region_data, energy_input), axis=1)\n\tregion_data = region_data[1:, :]\n\tregion_data[:, [2,3]] = region_data[:, [3,2]]\n\n\t# convert pandas timestamp object to ordinal day of the year\n\t# additionally, convert from hh:mm to some fraction of an hour ie: 4:15 -> 4.25\n\tfor i in range(region_data.shape[0]):\n\t\tregion_data[i, 0] = region_data[i, 0].dayofyear\n\t\thour = region_data[i, 1].hour\n\n\t\t# get the fraction of the hour\n\t\tfraction_of_hour = region_data[i, 1].minute / 60.0\n\t\thour_fraction = hour + fraction_of_hour\n\t\tregion_data[i, 1] = hour_fraction\n\n\t# save data\n\tnp.save('data/'+farm_name, region_data)\n\treturn region_data\n\n\ndef split_data(energy_array, train=0.6, val=0.2, test=0.2):\n\t\"\"\"\n\tsplits data into training, validation, and test sets\n\n\targs:\n\t\t- energy_array: array containing the data\n\t\t- train, val, test: how much of data to put into each set (must add to 1)\n\n\treturns:\n\t\t- energy_train: training data\n\t\t- energy_val: validation data\n\t\t- energy_test: test data\n\t\"\"\"\n\tend_dex_train = int(np.floor(energy_array.shape[0] * train))\n\tstart_dex_val = end_dex_train\n\tend_dex_val = int(np.floor(energy_array.shape[0] * (train + val)))\n\tstart_dex_test = end_dex_val\n\n\t# create train, val, and test sets\n\tenergy_train = energy_array[0:end_dex_train, :]\n\tenergy_val = energy_array[start_dex_val:end_dex_val, :]\n\tenergy_test = energy_array[start_dex_test:, :]\n\n\t# some mild preprocessing by standardizing the data\n\t# ie: subtract by mean and divide by standard deviation\n\tenergy_train_copy = energy_train\n\tenergy_train_copy2 = energy_train\n\tenergy_train_copy2 = energy_train_copy2.astype(float) # prevents some error with std function\n\tenergy_val_copy = energy_val\n\n\t# get training data mean and standard deviation\n\tmean_across_cols = np.mean(energy_train_copy, axis=0)\n\tstd_across_cols = np.std(energy_train_copy2, axis=0)\n\n\t# standardize the data\n\tenergy_train = energy_train - mean_across_cols\n\tenergy_train = energy_train / std_across_cols\n\tenergy_val = energy_val - mean_across_cols\n\tenergy_val = energy_val / std_across_cols\n\n\t# save mean and std\n\tprogram_data = np.array([mean_across_cols[2], std_across_cols[2]])\n\tnp.save('program_data/mean_and_std', program_data)\n\n\t# do not standardize the target data\n\tenergy_train[:, [3]] = energy_train_copy[:, [3]]\n\tenergy_val[:, [3]] = energy_val_copy[:, [3]]\n\n\n\treturn energy_train, energy_val, energy_test\n\n\ndef create_lists_of_data(energy_data, encoder_insize=24 * 12 * 15, decoder_insize=12):\n\t\"\"\"\n\tcreates lists of data, where each array in the list contains the joint encoder and decoder\n\tdata necessary for further computations\n\n\targs:\n\t\t- energy_data: a numpy array of data with columns [day time energy_load]\n\t\t- encoder_insize: how many inputs for encoder, by default it is 4 months\n\t\t- decoder_insize: how many inputs for decoder, by default it is 1 month\n\n\treturns:\n\t\t- enc_dec_list: a list where each entry contains input data for one encode/decode cycle\n\t\"\"\"\n\n\t# create variables to store how many data points one entyr contains, and how many \n\t# entries in the list there are\n\tdata_len = energy_data.shape[0]\n\tlist_entry_size = encoder_insize + decoder_insize\n\tnum_list_entries = data_len // list_entry_size\n\n\t# remove data off the end of the list\n\tenergy_data = energy_data[0 : num_list_entries * list_entry_size]\n\n\t# create a list where each entry contains the data for one encoder/decoder cycle\n\tenc_dec_list = np.split(energy_data, num_list_entries)\n\n\treturn enc_dec_list\n\ndef separate_enc_dec(enc_dec_data, encoder_insize=24 * 12 * 15, decoder_insize=12):\n\t\"\"\"\n\tgiven a tensor of combined encoder decoder inputs, split them apart into two seperate\n\tlists so that they may be processed later on\n\n\tadditionally, the decoder list is properly seperated so that a targets list may also be created\n\n\targs:\n\t\t- enc_dec_data: a tensor containing data for one encoder decoder cycle\n\t\t- encoder_insize: how many inputs for encoder, by default it is 4 months\n\t\t- decoder_insize: how many inputs for decoder, by default it is 1 month\n\n\treturns:\n\t\t- enc_list: a list containing sequentially the encoder inputs\n\t\t- dec_list: a list containing sequentially the decoder inputs\n\t\t- target_list: a list containing sequally the targets corresponding to dec_list\n\n\n\n\t\"\"\"\n\t# load saved std and mean\n\tprogram_data = np.load('program_data/mean_and_std.npy')\n\tmean_across_cols = program_data[0]\n\tstd_across_cols = program_data[1]\n\n\t# split the encoder and decoder data\n\t# be sure to eliminate last column in encoder data (current values, b/c we're trying to\n\t#\t\t\t\t\t\t\t\t\t\t\t\t\tpredict future values)\n\t# target data found in column 3 (numbering starts from 0)\n\tenc_data = enc_dec_data[0 : encoder_insize]\n\tenc_data = enc_data[:, [0,1,2]]\n\tdec_target_data = enc_dec_data[encoder_insize : ]\n\tdec_data = dec_target_data[:, 0 : 2]\n\ttarget_data = dec_target_data[:, 3]\n\n\t# split data into lists\n\tenc_list = np.split(enc_data, enc_data.shape[0])\n\tdec_list = np.split(dec_data, dec_data.shape[0])\n\ttarget_list = np.split(target_data, target_data.shape[0])\n\n\t# reshape entries in target list to size (1,1) for placeholder compatibility\n\tfor i in xrange(len(target_list)):\n\t\ttarget_list[i] = target_list[i].reshape((1,1))\n\n\treturn enc_list, dec_list, target_list\n\n\n# region_data = read_region()\n# print region_data[0:3, :]\n\n# x = np.arange(0, region_data.shape[0])\n# y = region_data[:, 2]\n# plt.plot(x,y)\n# plt.show()\n","sub_path":"data_handler.py","file_name":"data_handler.py","file_ext":"py","file_size_in_byte":6725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"372847038","text":"# File : constantList_KP4_1.py\r\n# Author : Muratet.M\r\n# Date : January 3, 2015\r\n#\r\n# Brief : List of constants for System units of Kernel Panic 4.1.\r\n#\r\n\r\n####################################\r\n# List of available units type ids #\r\n####################################\r\n\r\n# The assembler is a construction unit.\r\n# It can build sockets, but it cannot assist-build. Slow, little health.\r\n# Equipped with a radar to detect mines and other cloacked units.\r\n# See PP_Unit_GetType on pp.py\r\nASSEMBLER = 2\r\n\r\n# A tiny wall, built by Assembler.\r\n# Blocks small units movement. Do not block shots however. Easily removed by the\r\n# Debug or simply crushing them with a Byte.\r\n# See PP_Unit_GetType on pp.py\r\nBADBLOCK = 3\r\n\r\n# Your basic attacking unit.\r\n# Cheap, fast, small, not very much health. Is armed with a SPARCling laser. Can\r\n# be built by a kernel or a socket.\r\n# See PP_Unit_GetType on pp.py\r\nBIT = 4\r\n\r\n# A large, strong, and slow attacking unit.\r\n# Can holds it's own against many bits, as it has lots of health and a powerful\r\n# gun. More armored when closed. Can plow through bad blocks. The byte has an\r\n# alternate firing mode, the mine launcher, which throws 5 mines at the cost of\r\n# much health.\r\n# See PP_Unit_GetType on pp.py\r\nBYTE = 7\r\n\r\n# Main building of System faction.\r\n# It can build all mobile units in the game. Has rapid auto-heal and lots of\r\n# health.\r\n# See PP_Unit_GetType on pp.py\r\nKERNEL = 25\r\n\r\n# A mine.\r\n# It can be built by the Assembler, and also launched by Bytes. It takes out\r\n# Bits in a single blow, has a decent damage radius, and doesn't chain explode.\r\n# Use with care, as the blast hurts your own units too. Limited to 32.\r\n# See PP_Unit_GetType pp.py\r\nLOGIC_BOMB = 26\r\n\r\n# An artillery unit.\r\n# Its normal shot is not so useful against moving units, but can kill kernels\r\n# and sockets pretty quickly. Is slow and has little health, so it needs\r\n# protection. The pointer has an alternate firing mode, the NX Flag, which set\r\n# a wide area ablaze for a minute, causing constant damage to all units, or\r\n# buildings within it's range.\r\n# See PP_Unit_GetType on pp.py\r\nPOINTER = 39\r\n\r\n# A nuclear bomb.\r\n# It is launched by Terminal.\r\n# See PP_Unit_GetType on pp.py\r\nSIGNAL = 44\r\n\r\n# A factory.\r\n# It can only be built on special areas. It can solely build Bits, and slower\r\n# than the Kernel can. It autoheals, and has a decent amount of health.\r\n# See PP_Unit_GetType on pp.py\r\nSOCKET = 45 \r\n\r\n# A missile launcher.\r\n# It can only be built on special areas. It can dispatch a Signal (nuclear\r\n# bomber) once every 90 seconds that will deal about 16000 damage to a large\r\n# target area, i.e. it destroys everything except factories. It does much less\r\n# damage to the Kernel. The bomber can strike any position on the map, there is\r\n# no defense.\r\n# See PP_Unit_GetType on pp.py\r\nTERMINAL = 46\r\n\r\n##########################################################\r\n# List of available order ids depending on unit type ids #\r\n##########################################################\r\n\r\n# Orders available for ASSEMBLER, BIT, BYTE, KERNEL, LOGIC_BOMB, POINTER and\r\n# SOCKET\r\nSTOP = 0 # Stop current action and remove all pending commands.\r\n # See PP_Unit_UntargetedAction on pp.py\r\nWAIT = 5 # Suspend/Unsuspend current action.\r\n # See PP_Unit_UntargetedAction on pp.py\r\nFIRE_STATE = 45 # Defines the fire state and expect 1 parameter:\r\n # 0.0 => Hold fire, the unit doesn't attack automatically\r\n # 1.0 => Return fire, the unit responds if it is attacked\r\n # 2.0 => Fire at will, the unit attacks automatically.\r\n # See PP_Unit_UntargetedAction on pp.py\r\nSELF_DESTRUCTION = 65 # Self destruction of the unit.\r\n # See PP_Unit_UntargetedAction on pp.py\r\nREPEAT = 115 # Defines the repeat mode and expect 1 parameter:\r\n # 0.0 => Repeat off, the unit doesn't repeat pending commands\r\n # 1.0 => Repeat on, the unit repeats pending commands.\r\n # See PP_Unit_UntargetedAction on pp.py\r\n\r\n# Orders available for ASSEMBLER, BIT, BYTE, KERNEL, POINTER and SOCKET\r\nMOVE = 10 # The unit moves to a target.\r\n # See PP_Unit_ActionOnUnit and PP_Unit_ActionOnPosition on pp.py\r\nPATROL = 15 # The unit patrols between its current position and a target.\r\n # See PP_Unit_ActionOnUnit and PP_Unit_ActionOnPosition\r\nFIGHT = 16 # The unit progresses to a target but units will stop to kill enemies\r\n # along the way.\r\n # See PP_Unit_ActionOnUnit and PP_Unit_ActionOnPosition on pp.py\r\nGUARD = 25 # The unit guards a target.\r\n # See PP_Unit_ActionOnUnit and PP_Unit_ActionOnPosition on pp.py\r\nMOVE_STATE = 50 # Defines the move state and expect 1 parameter:\r\n # 0.0 => Hold pos, the unit doesn't move automatically\r\n # 1.0 => Maneuver, the unit stays near from its position\r\n # 2.0 => Roam, the unit is not blocked around its position.\r\n # See PP_Unit_UntargetedAction on pp.py\r\n\r\n# Orders available for BIT, BYTE, KERNEL, LOGIC_BOMB, POINTER and SOCKET\r\nATTACK = 20 # The unit progresses to a target, attacks ennemy units in its line\r\n # of sight but doesn't stop its advance.\r\n # See PP_Unit_ActionOnUnit and PP_Unit_ActionOnPosition on pp.py\r\n\r\n# Orders available for ASSEMBLER\r\nREPAIR = 40 # The unit repairs a target.\r\n # See PP_Unit_ActionOnUnit and PP_Unit_ActionOnPosition on pp.py\r\nBUILD_BADBLOCK = -3 # The unit builds a Bad Block on a target.\r\n # See PP_Unit_ActionOnPosition on pp.py\r\nBUILD_LOGIC_BOMB = -26 # The unit builds a Logic Bomb on a target.\r\n # See PP_Unit_ActionOnPosition\r\nBUILD_SOCKET = -45 # The unit builds a Socket on a target.\r\n # See PP_Unit_ActionOnPosition on pp.py\r\nBUILD_TERMINAL = -46 # The unit builds a Terminal on a target.\r\n # See PP_Unit_ActionOnPosition on pp.py\r\nDEBUG = -35 # The unit builds a Debug on a target (clear an area of all mines\r\n # and walls).\r\n # See PP_Unit_ActionOnPosition\r\n\r\n# Orders available for KERNEL\r\nBUILD_ASSEMBLER = -2 # The unit builds an Assembler.\r\n # See PP_Unit_UntargetedAction and PP_Unit_ActionOnPosition\r\n # on pp.py\r\nBUILD_BYTE = -7 # The unit builds a Byte.\r\n # See PP_Unit_UntargetedAction and PP_Unit_ActionOnPosition on\r\n # pp.py\r\nBUILD_POINTER = -39 # The unit builds a Pointer.\r\n # See PP_Unit_UntargetedAction and PP_Unit_ActionOnPosition\r\n # on pp.py\r\n\r\n# Orders available for KERNEL and SOCKET\r\nBUILD_BIT = -4 # The unit builds a Bit.\r\n # See PP_Unit_UntargetedAction and PP_Unit_ActionOnPosition on\r\n # pp.py\r\nSTOP_BUILDING = -7658 # The unit stops building units.\r\n # See PP_Unit_UntargetedAction on pp.py\r\n\r\n# Orders available for BYTE\r\nLAUNCH_MINE = 33395 # The unit launches mines.\r\n # See PP_Unit_UntargetedAction on pp.py\r\n\r\n# Orders available for POINTER\r\nNX_FLAG = 33389 # The unit launches an NX Flag.\r\n # See PP_Unit_ActionOnUnit and PP_Unit_ActionOnPosition on pp.py\r\n\r\n# Orders available for TERMINAL\r\nSIGTERM = 35126 # The unit launches a Sigterm.\r\n # See PP_Unit_ActionOnUnit and PP_Unit_ActionOnPosition on pp.py\r\n\r\n##################################\r\n# List of available resource ids #\r\n##################################\r\nMETAL = 0 # Not used in Kernel Panic. See PP_GetResource on pp.py\r\nENERGY = 1 # Not used in Kernel Panic. See PP_GetResource on pp.py\r\n","sub_path":"ProgAndPlay_src_2.5.1/Client_Interfaces/python/constantList_KP4_1.py","file_name":"constantList_KP4_1.py","file_ext":"py","file_size_in_byte":7681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"13223232","text":"import argparse\nimport sys\nfrom pathlib import Path\n# from pydmtx.core import\nfrom pydmtx.cli.argparser import ArgParser, SIZE_CHOICES\nfrom pydmtx import plugin_manager, encode\n\ndef check_nonnegative_int(value):\n try:\n integer = int(value)\n except:\n raise argparse.ArgumentTypeError(f\"'{value}' is an invalid int value\")\n\n if integer < 0:\n raise argparse.ArgumentTypeError(f\"'{value}' is an invalid nonnegative int value\")\n\n return integer\n\n\ndef source(value):\n # TODO\n return value\n # https://github.com/python/cpython/blob/master/Lib/argparse.py#L1227\n if value == \"-\" or Path(value).is_file():\n return argparse.FileType(\"rb\")(value).read()\n\n return value\n\n\nparser = ArgParser(\n prog=\"pydmtx\",\n usage=\"%(prog)s [SOURCE] [OPTIONS] [--] [EXPORT_OPTIONS]\",\n description=\"program description\",\n epilog=\"epilog\",\n allow_abbrev=False,\n)\n\nparser.add_argument(\n \"data_to_encode\",\n metavar=\"SOURCE\",\n type=source,\n help=\"when SOURCE is -, then read from stdin\",\n)\n\nparser.add_argument(\n \"-q\",\n \"--quiet-zone\",\n metavar=\"INT\",\n action=\"store\",\n type=check_nonnegative_int,\n default=2,\n help=\"description [default: %(default)s]\",\n)\n\nparser.add_argument(\n \"-s\",\n \"--size\",\n metavar=\"SIZE\",\n action=\"store\",\n type=str,\n choices=SIZE_CHOICES,\n default=\"square\",\n help=\"description [default: %(default)s] [choices: %(choices)s]\"\n)\n\navailable_export_formats = [plugin.format_type for plugin in plugin_manager.find_export_plugins()]\n\nparser.add_argument(\n \"-f\",\n \"--format\",\n metavar=\"FORMAT\",\n action=\"store\",\n choices=available_export_formats,\n default=\"text\",\n help=\"description [default: %(default)s] [choices: %(choices)s]\",\n)\n\nparser.add_argument(\n \"-o\",\n \"--output\",\n action=\"store\",\n type=str,\n help=\"description\",\n)\n\nparser.add_argument(\n \"--stdout\",\n action=\"store_true\",\n help=\"description\",\n)\n\nparser.add_argument(\n \"-p\",\n \"--preview\",\n action=\"store_true\",\n help=\"description\",\n)\n\nparser.add_argument(\n \"--format-help\",\n metavar=\"FORMAT\",\n action=\"store\",\n type=str,\n choices=available_export_formats,\n help=f\"description [choices: %(choices)s]\",\n)\n\nparser.add_argument(\n \"-v\",\n \"--version\",\n action=\"version\",\n version=\"%(prog)s 0.1.0\",\n)\n\ndef main():\n args, export_args = parser.parse_args()\n\n data_to_encode = source(args.data_to_encode)\n\n formatter = plugin_manager.find_export_plugin_by_format_type(args.format)\n raw_symbol = encode(data_to_encode, version=args.size, quiet_zone=args.quiet_zone)\n\n formatter_options = vars(formatter.parser.parse_args(export_args))\n result = raw_symbol.format(formatter, **formatter_options)\n\n if args.output:\n with open(args.output, \"wb\") as f:\n f.write(result)\n elif args.stdout:\n sys.stdout.buffer.write(result)\n\n return 0\n","sub_path":"pydmtx/cli/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"285291032","text":"# -*- coding: utf-8 -*-\nL=input('请输入偏移量:')#L: 询问是否输入偏移量\nmun=\"\"#mun: 偏移量\ncode=\"\"#code: 输入的结果\n\nwith open('readme.txt') as m:\n\tmsg=m.read()#msg:文本信息\n\nif L:\n\tmun=L\nelse:\n mun=3\n\n#加密文本信息\nfor i in msg:\n\tif 'a'<=i<='z':\n\t\tcode += chr( ord('a') + ((ord(i)-ord('a')) + int(mun) )%26 )\n\telif 'A'<=i<='Z':\n\t\tcode += chr( ord('A') + ((ord(i)-ord('A')) + int(mun) )%26 )\n\telse:\n\t\tcode += i\n\nprint(code)\t","sub_path":"jiami/kaisacode3.0.py","file_name":"kaisacode3.0.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"104248245","text":"from abc import ABC, abstractmethod\nimport altair as alt\nimport datetime\nimport logging\nimport numpy as np\nimport pandas as pd\nfrom pathlib import Path\nimport sqlalchemy\nfrom sqlalchemy.sql import select, text, and_\n\nfrom . import util\n\n\nclass AbstractChart(ABC):\n def __init__(self, engine, output_dir,\n output_formats=frozenset(['json'])):\n self.engine = engine\n self.metadata = sqlalchemy.MetaData(engine)\n self.output_dir = output_dir\n self.output_formats = output_formats\n self.name = type(self).__name__\n\n def render(self, bulletin_dates):\n with self.engine.connect() as connection:\n df = self.fetch_data(connection, bulletin_dates)\n logging.info(\"%s dataframe: %s\", self.name, util.describe_frame(df))\n\n logging.info(f'Writing {self.name} charts to {self.output_dir}...')\n for bulletin_date in bulletin_dates:\n self.render_bulletin_date(df, bulletin_date)\n\n def render_bulletin_date(self, df, bulletin_date):\n bulletin_dir = Path(f'{self.output_dir}/{bulletin_date}')\n bulletin_dir.mkdir(exist_ok=True)\n filtered = self.filter_data(df, bulletin_date)\n util.save_chart(self.make_chart(filtered, bulletin_date),\n f\"{bulletin_dir}/{bulletin_date}_{self.name}\",\n self.output_formats)\n\n @abstractmethod\n def make_chart(self, df, bulletin_date):\n pass\n\n @abstractmethod\n def fetch_data(self, connection, bulletin_dates):\n pass\n\n def filter_data(self, df, bulletin_date):\n \"\"\"Filter dataframe according to given bulletin_date. May want to override.\"\"\"\n return df.loc[df['bulletin_date'] == pd.to_datetime(bulletin_date)]\n\n\nclass AbstractMismatchChart(AbstractChart):\n def filter_data(self, df, bulletin_date):\n until = pd.to_datetime(bulletin_date)\n return df.loc[df['bulletin_date'] <= until]\n\n def make_chart(self, df, bulletin_date):\n base = alt.Chart(df).encode(\n x=alt.X('date(bulletin_date):O',\n title=\"Día del mes\", sort=\"descending\",\n axis=alt.Axis(format='%d')),\n y=alt.Y('yearmonth(bulletin_date):O',\n title=None, sort=\"descending\",\n axis=alt.Axis(format='%B')),\n tooltip=['bulletin_date:T', 'value']\n )\n\n heatmap = base.mark_rect().encode(\n color=alt.Color('value:Q', title=None, legend=None,\n scale=alt.Scale(scheme=\"redgrey\", domainMid=0,\n # WORKAROUND: Set the domain manually to forcibly\n # include zero or else we run into\n # https://github.com/vega/vega-lite/issues/6544\n domain=alt.DomainUnionWith(unionWith=[0])))\n )\n\n text = base.mark_text(fontSize=9).encode(\n text=alt.Text('value:Q'),\n color=util.heatmap_text_color(df, 'value')\n )\n\n return (heatmap + text).properties(\n width=575, height=120\n ).facet(\n columns=1,\n facet=alt.Facet('variable', title=None,\n sort=['Confirmados',\n 'Probables',\n 'Muertes'])\n )\n\n\nclass ConsecutiveBulletinMismatch(AbstractMismatchChart):\n def fetch_data(self, connection, bulletin_dates):\n table = sqlalchemy.Table('mismatched_announcement_aggregates', self.metadata,\n schema='quality', autoload=True)\n query = select([table.c.bulletin_date,\n (table.c.cumulative_confirmed_cases\n - table.c.computed_cumulative_confirmed_cases)\\\n .label('confirmed_cases_mismatch'),\n (table.c.cumulative_probable_cases\n - table.c.computed_cumulative_probable_cases)\\\n .label('probable_cases_mismatch'),\n (table.c.cumulative_deaths\n - table.c.computed_cumulative_deaths)\\\n .label('deaths_mismatch'),\n ]).where(table.c.bulletin_date <= max(bulletin_dates))\n df = pd.read_sql_query(query, connection, parse_dates=['bulletin_date'])\n df = df.rename(columns={\n 'confirmed_cases_mismatch': 'Confirmados',\n 'probable_cases_mismatch': 'Probables',\n 'deaths_mismatch': 'Muertes'\n })\n return pd.melt(df, ['bulletin_date']).dropna()\n\n\n\nclass BulletinChartMismatch(AbstractMismatchChart):\n def fetch_data(self, connection, bulletin_dates):\n table = sqlalchemy.Table('mismatched_announcement_and_chart', self.metadata,\n schema='quality', autoload=True)\n query = select([table.c.bulletin_date,\n (table.c.cumulative_confirmed_cases - table.c.sum_confirmed_cases)\\\n .label('confirmed_cases_mismatch'),\n (table.c.cumulative_probable_cases - table.c.sum_probable_cases)\\\n .label('probable_cases_mismatch'),\n (table.c.cumulative_deaths - table.c.sum_deaths)\\\n .label('deaths_mismatch'),\n ]).where(table.c.bulletin_date <= max(bulletin_dates))\n df = pd.read_sql_query(query, connection, parse_dates=['bulletin_date'])\n df = df.rename(columns={\n 'confirmed_cases_mismatch': 'Confirmados',\n 'probable_cases_mismatch': 'Probables',\n 'deaths_mismatch': 'Muertes'\n })\n return pd.melt(df, ['bulletin_date']).dropna()\n\n\nclass AbstractLateness(AbstractChart):\n def fetch_data_for_table(self, connection, table, min_bulletin_date, max_bulletin_date):\n query = select([table.c.bulletin_date,\n table.c.confirmed_cases_additions,\n table.c.probable_cases_additions,\n table.c.deaths_additions]\n ).where(and_(min_bulletin_date <= table.c.bulletin_date,\n table.c.bulletin_date <= max_bulletin_date))\n df = pd.read_sql_query(query, connection,\n parse_dates=[\"bulletin_date\"])\n df = df.rename(columns={\n 'confirmed_cases_additions': 'Confirmados',\n 'probable_cases_additions': 'Probables',\n 'deaths_additions': 'Muertes'\n })\n return pd.melt(df, \"bulletin_date\")\n\n\nclass LatenessDaily(AbstractLateness):\n def make_chart(self, df, bulletin_date):\n sort_order = ['Confirmados',\n 'Probables',\n 'Muertes']\n bars = alt.Chart(df).mark_bar().encode(\n x=alt.X('value', title=\"Rezago estimado (días)\"),\n y=alt.Y('variable', title=None, sort=sort_order, axis=None),\n color=alt.Color('variable', sort=sort_order,\n legend=alt.Legend(orient='bottom', title=None)),\n tooltip=[alt.Tooltip('bulletin_date:T', title='Fecha de boletín'),\n alt.Tooltip('variable:N', title='Variable'),\n alt.Tooltip('value:Q', format=\".1f\", title='Rezago promedio')]\n )\n\n text = bars.mark_text(\n align='right',\n baseline='middle',\n size=12,\n dx=-5\n ).encode(\n text=alt.Text('value:Q', format='.1f'),\n color = alt.value('white')\n )\n\n return (bars + text).properties(\n width=300,\n ).facet(\n columns=2,\n facet=alt.Facet(\"bulletin_date\", sort=\"descending\", title=\"Fecha del boletín\")\n )\n\n\n def fetch_data(self, connection, bulletin_dates):\n table = sqlalchemy.Table('lateness_daily', self.metadata,\n schema='products', autoload=True)\n min_bulletin_date = min(bulletin_dates) - datetime.timedelta(days=8)\n max_bulletin_date = max(bulletin_dates)\n return self.fetch_data_for_table(connection, table, min_bulletin_date, max_bulletin_date)\n\n def filter_data(self, df, bulletin_date):\n since_date = pd.to_datetime(bulletin_date - datetime.timedelta(days=8))\n until_date = pd.to_datetime(bulletin_date)\n return df.loc[(since_date < df['bulletin_date'])\n & (df['bulletin_date'] <= until_date)]\n\n\nclass Lateness7Day(AbstractLateness):\n def make_chart(self, df, bulletin_date):\n sort_order = ['Confirmados',\n 'Probables',\n 'Muertes']\n lines = alt.Chart(df).mark_line(\n strokeWidth=3,\n point=alt.OverlayMarkDef(size=50)\n ).encode(\n x=alt.X('yearmonthdate(bulletin_date):O',\n title=\"Fecha boletín\",\n axis=alt.Axis(format='%d/%m', titlePadding=10)),\n y=alt.Y('value:Q', title=None),\n color = alt.Color('variable', sort=sort_order, legend=None),\n tooltip=[alt.Tooltip('bulletin_date:T', title='Fecha de boletín'),\n alt.Tooltip('variable:N', title='Variable'),\n alt.Tooltip('value:Q', format=\".1f\", title='Rezago promedio')]\n )\n\n text = lines.mark_text(\n align='center',\n baseline='line-top',\n size=15,\n dy=10\n ).encode(\n text=alt.Text('value:Q', format='.1f')\n )\n\n return (lines + text).properties(\n width=600, height=33\n ).facet(\n columns=1,\n facet=alt.Facet('variable', title=None, sort=sort_order)\n )\n\n def fetch_data(self, connection, bulletin_dates):\n table = sqlalchemy.Table('lateness_7day', self.metadata,\n schema='products', autoload=True)\n min_bulletin_date = min(bulletin_dates) - datetime.timedelta(days=8)\n max_bulletin_date = max(bulletin_dates)\n return self.fetch_data_for_table(connection, table, min_bulletin_date, max_bulletin_date)\n\n def filter_data(self, df, bulletin_date):\n since_date = pd.to_datetime(bulletin_date - datetime.timedelta(days=15))\n until_date = pd.to_datetime(bulletin_date)\n return df.loc[(since_date < df['bulletin_date'])\n & (df['bulletin_date'] <= until_date)]\n\n\nclass CurrentDeltas(AbstractChart):\n def make_chart(self, df, bulletin_date):\n base = alt.Chart(df).encode(\n x=alt.X('date(datum_date):O',\n title=\"Día del mes\", sort=\"descending\",\n axis=alt.Axis(format='%d')),\n y=alt.Y('yearmonth(datum_date):O',\n title=None, sort=\"descending\",\n axis=alt.Axis(format='%B')),\n tooltip=[alt.Tooltip('datum_date:T', title='Fecha de muestra o muerte'),\n alt.Tooltip('bulletin_date:T', title='Fecha de boletín'),\n alt.Tooltip('value:Q', title='Casos añadidos (o restados)')]\n )\n\n heatmap = base.mark_rect().encode(\n color=alt.Color('value:Q', title=None, legend=None,\n scale=alt.Scale(scheme=\"redgrey\", domainMid=0,\n # WORKAROUND: Set the domain manually to forcibly\n # include zero or else we run into\n # https://github.com/vega/vega-lite/issues/6544\n domain=alt.DomainUnionWith(unionWith=[0])))\n )\n\n text = base.mark_text(fontSize=9).encode(\n text=alt.Text('value:Q'),\n color=util.heatmap_text_color(df, 'value')\n ).transform_filter(\"(datum.value !== 0) & (datum.value !== null)\")\n\n return (heatmap + text).properties(\n width=580, height=120\n ).facet(\n columns=1,\n facet=alt.Facet('variable', title=None,\n sort=['Confirmados',\n 'Probables',\n 'Muertes'])\n )\n\n def fetch_data(self, connection, bulletin_dates):\n table = sqlalchemy.Table('daily_deltas', self.metadata,\n schema='products', autoload=True)\n query = select([table.c.bulletin_date,\n table.c.datum_date,\n table.c.delta_confirmed_cases,\n table.c.delta_probable_cases,\n table.c.delta_deaths]\n ).where(and_(min(bulletin_dates) <= table.c.bulletin_date,\n table.c.bulletin_date <= max(bulletin_dates)))\n df = pd.read_sql_query(query, connection,\n parse_dates=[\"bulletin_date\", \"datum_date\"])\n df = df.rename(columns={\n 'delta_confirmed_cases': 'Confirmados',\n 'delta_probable_cases': 'Probables',\n 'delta_deaths': 'Muertes'\n })\n return pd.melt(df, [\"bulletin_date\", \"datum_date\"]) \\\n .replace(0, np.nan)\n\n\nclass DailyDeltas(AbstractChart):\n def make_chart(self, df, bulletin_date):\n base = alt.Chart(df).mark_rect().encode(\n x=alt.X('yearmonthdate(datum_date):O',\n title=\"Fecha evento\", sort=\"descending\",\n axis=alt.Axis(format='%d/%m')),\n y=alt.Y('yearmonthdate(bulletin_date):O',\n title=None, sort=\"descending\",\n axis=alt.Axis(format='%d/%m')),\n tooltip=[alt.Tooltip('datum_date:T', title='Fecha de muestra o muerte'),\n alt.Tooltip('bulletin_date:T', title='Fecha de boletín'),\n alt.Tooltip('value:Q', title='Casos añadidos (o restados)')]\n )\n\n heatmap = base.mark_rect().encode(\n color=alt.Color('value:Q', title=None, legend=None,\n scale=alt.Scale(scheme=\"redgrey\", domainMid=0,\n # WORKAROUND: Set the domain manually to forcibly\n # include zero or else we run into\n # https://github.com/vega/vega-lite/issues/6544\n domain=alt.DomainUnionWith(unionWith=[0])))\n )\n\n text = base.mark_text(fontSize=2.75).encode(\n text=alt.Text('value:Q'),\n color=util.heatmap_text_color(df, 'value')\n )\n\n return (heatmap + text).properties(\n width=585, height=120\n ).facet(\n columns=1,\n facet=alt.Facet('variable', title=None,\n sort=['Confirmados',\n 'Probables',\n 'Muertes'])\n )\n\n def fetch_data(self, connection, bulletin_dates):\n table = sqlalchemy.Table('daily_deltas', self.metadata,\n schema='products', autoload=True)\n query = select([table.c.bulletin_date,\n table.c.datum_date,\n table.c.delta_confirmed_cases,\n table.c.delta_probable_cases,\n table.c.delta_deaths]\n ).where(and_(min(bulletin_dates) - datetime.timedelta(days=14) <= table.c.bulletin_date,\n table.c.bulletin_date <= max(bulletin_dates)))\n df = pd.read_sql_query(query, connection,\n parse_dates=[\"bulletin_date\", \"datum_date\"])\n df = df.rename(columns={\n 'delta_confirmed_cases': 'Confirmados',\n 'delta_probable_cases': 'Probables',\n 'delta_deaths': 'Muertes'\n })\n return pd.melt(df, [\"bulletin_date\", \"datum_date\"])\n\n def filter_data(self, df, bulletin_date):\n since_date = pd.to_datetime(bulletin_date - datetime.timedelta(days=14))\n until_date = pd.to_datetime(bulletin_date)\n filtered = df.loc[(since_date < df['bulletin_date'])\n & (df['bulletin_date'] <= until_date)]\\\n .replace(0, np.nan)\\\n .dropna()\n return filtered\n\n\nclass WeekdayBias(AbstractChart):\n def make_chart(self, df, bulletin_date):\n confirmed = self.one_variable(df, 'Confirmados', 'Día muestra', 'oranges')\n probable = self.one_variable(df, 'Probables', 'Día muestra', 'reds')\n deaths = self.one_variable(df, 'Muertes', 'Día muerte', 'teals')\n\n data_date = alt.Chart(df).mark_text(baseline='middle').encode(\n text=alt.Text('bulletin_date',\n type='temporal',\n aggregate='max',\n timeUnit='yearmonthdate',\n format='Datos hasta: %A %d de %B, %Y'),\n ).properties(\n width=330, height=40\n )\n\n row1 = alt.hconcat(confirmed, probable, spacing=20).resolve_scale(\n color='independent'\n )\n\n return alt.vconcat(row1, data_date, deaths, center=True).resolve_scale(\n color='independent'\n )\n\n def one_variable(self, df, variable,\n axis_title,\n color_scheme):\n base = alt.Chart(df).transform_filter(\n alt.datum.variable == variable\n ).transform_filter(\n alt.datum.value > 0\n ).encode(\n color=alt.Color('sum(value):Q', title=None,\n scale=alt.Scale(type='log', base=2, scheme=color_scheme))\n )\n\n heatmap = base.mark_rect().encode(\n x=alt.X('day(datum_date):O', title=axis_title),\n y=alt.Y('day(bulletin_date):O', title='Día boletín'),\n tooltip=[alt.Tooltip('variable:N', title='Variable'),\n alt.Tooltip('day(bulletin_date):O', title='Día de boletín'),\n alt.Tooltip('day(datum_date):O', title='Día de muestra o muerte'),\n alt.Tooltip('value:Q', aggregate='sum', title='Casos')]\n )\n\n right = base.mark_bar().encode(\n x=alt.X('sum(value):Q', title=None, axis=None),\n y=alt.Y('day(bulletin_date):O', title=None, axis=None),\n tooltip=[alt.Tooltip('variable:N', title='Variable'),\n alt.Tooltip('day(bulletin_date):O', title='Día de boletín'),\n alt.Tooltip('value:Q', aggregate='sum', title='Casos')]\n )\n\n top = base.mark_bar().encode(\n x=alt.X('day(datum_date):O', title=None, axis=None),\n y=alt.Y('sum(value):Q', title=None, axis=None),\n tooltip=[alt.Tooltip('variable:N', title='Variable'),\n alt.Tooltip('day(datum_date):O', title='Día de muestra o muerte'),\n alt.Tooltip('value:Q', aggregate='sum', title='Casos')]\n )\n\n heatmap_size = 150\n histogram_size = 40\n return alt.vconcat(\n top.properties(\n width=heatmap_size, height=histogram_size,\n # This title should logically belong to the whole chart,\n # but assigning it to the concat chart anchors it wrong.\n # See: https://altair-viz.github.io/user_guide/generated/core/altair.TitleParams.html\n title=alt.TitleParams(\n text=variable,\n anchor='middle',\n align='center',\n fontSize=14,\n fontWeight='normal'\n )\n ),\n alt.hconcat(\n heatmap.properties(\n width=heatmap_size, height=heatmap_size\n ),\n right.properties(\n width=histogram_size, height=heatmap_size\n ),\n spacing=3),\n spacing=3\n )\n\n def fetch_data(self, connection, bulletin_dates):\n query = text(\"\"\"SELECT \n\tba.bulletin_date,\n\tba.datum_date,\n\tba.delta_confirmed_cases,\n\tba.delta_probable_cases,\n\tba.delta_deaths\nFROM bitemporal_agg ba \nWHERE ba.datum_date >= ba.bulletin_date - INTERVAL '14' DAY\nAND ba.bulletin_date > (\n\tSELECT min(bulletin_date)\n\tFROM bitemporal_agg\n\tWHERE delta_confirmed_cases IS NOT NULL\n\tAND delta_probable_cases IS NOT NULL\n\tAND delta_deaths IS NOT NULL)\nORDER BY bulletin_date, datum_date\"\"\")\n df = pd.read_sql_query(query, connection, parse_dates=['bulletin_date', 'datum_date'])\n df = df.rename(columns={\n 'delta_confirmed_cases': 'Confirmados',\n 'delta_probable_cases': 'Probables',\n 'delta_deaths': 'Muertes'\n })\n return pd.melt(df, ['bulletin_date', 'datum_date']).dropna()\n\n def filter_data(self, df, bulletin_date):\n # We exclude the current bulletin_date because this chart's\n # main use is to compare the current bulletin's data to trends\n # established **before** it.\n cutoff_date = bulletin_date - datetime.timedelta(days=1)\n since_date = pd.to_datetime(cutoff_date - datetime.timedelta(days=21))\n until_date = pd.to_datetime(cutoff_date)\n return df.loc[(since_date < df['bulletin_date'])\n & (df['bulletin_date'] <= until_date)]\n\n\nclass Municipal(AbstractChart):\n REDS = ('#fad1bd', '#ea9178', '#c74643')\n GRAYS = ('#dadada', '#ababab', '#717171')\n DOMAIN=[0, 6]\n\n def make_chart(self, df, bulletin_date):\n base = alt.Chart(df).transform_impute(\n impute='new_cases',\n groupby=['Municipio'],\n key='bulletin_date',\n value=0\n ).mark_area(interpolate='monotone', clip=True).encode(\n x=alt.X('bulletin_date:T', title='Fecha de boletín',\n axis=alt.Axis(format='%d/%m')),\n y=alt.Y('new_cases:Q', title=None, axis=None,\n scale=alt.Scale(domain=self.DOMAIN)),\n color=alt.value(self.REDS[0]),\n tooltip=[alt.Tooltip('bulletin_date:T', title='Fecha de boletín'),\n alt.Tooltip('Municipio:N'),\n alt.Tooltip('new_cases:Q', title='Casos nuevos')]\n )\n\n def make_band(variable, color, calculate):\n return base.transform_calculate(\n as_=variable, calculate=calculate\n ).encode(\n y=alt.Y(f'{variable}:Q'),\n color=alt.value(color)\n )\n\n one_above = make_band('one_above', self.REDS[1],\n alt.datum.new_cases - self.DOMAIN[1])\n two_above = make_band('two_above', self.REDS[2],\n alt.datum.new_cases - 2 * self.DOMAIN[1])\n negative = make_band('negative', self.GRAYS[0], -alt.datum.new_cases)\n one_below = make_band('one_below', self.GRAYS[1],\n -alt.datum.new_cases - self.DOMAIN[1])\n two_below = make_band('two_below', self.GRAYS[2],\n -alt.datum.new_cases - 2 * self.DOMAIN[1])\n\n return (base + one_above + two_above\n + negative + one_below + two_below).properties(\n width=525, height=24\n ).facet(\n row=alt.Row('Municipio:N', title=None,\n header=alt.Header(\n labelAngle=0,\n labelFontSize=10,\n labelAlign='left',\n labelBaseline='top')),\n ).configure_facet(\n spacing=0\n )\n\n def fetch_data(self, connection, bulletin_dates):\n table = sqlalchemy.Table('municipal_agg', self.metadata, autoload=True)\n query = select([table.c.bulletin_date,\n table.c.municipality,\n table.c.new_cases])\\\n .where(and_(table.c.municipality.notin_(['Total']),\n min(bulletin_dates) - datetime.timedelta(days=35) <= table.c.bulletin_date,\n table.c.bulletin_date <= max(bulletin_dates)))\n df = pd.read_sql_query(query, connection,\n parse_dates=[\"bulletin_date\"])\n return df.rename(columns={\n 'municipality': 'Municipio'\n })\n\n def filter_data(self, df, bulletin_date):\n since = pd.to_datetime(bulletin_date - datetime.timedelta(days=35))\n until = pd.to_datetime(bulletin_date)\n return df.loc[(since <= df['bulletin_date']) & (df['bulletin_date'] <= until)]\n\n\nclass MunicipalMap(AbstractChart):\n WIDTH = 600\n\n def make_chart(self, df, bulletin_date):\n new_cases = self.make_cases_chart(df)\n growth = self.make_trend_chart(df)\n return alt.vconcat(new_cases, growth).configure_view(\n strokeWidth=0\n ).configure_concat(\n spacing=40\n ).resolve_scale(\n color='independent'\n )\n\n def make_cases_chart(self, df):\n return self.make_subchart(\n df,\n alt.Color('daily_cases_100k', type='quantitative', sort='descending',\n scale=alt.Scale(type='sqrt', scheme='redgrey', domainMid=0.0,\n # WORKAROUND: Set the domain manually to forcibly\n # include zero or else we run into\n # https://github.com/vega/vega-lite/issues/6544\n domain=alt.DomainUnionWith(unionWith=[0])),\n legend=alt.Legend(orient='top', titleLimit=400, titleOrient='top',\n title='Casos diarios (por 100k de población, promedio 7 días)',\n offset=-15, labelSeparation=10,\n format=',d', gradientLength=self.WIDTH)))\n\n def make_trend_chart(self, df):\n return self.make_subchart(\n df,\n alt.Color('weekly_trend', type='quantitative', sort='descending',\n scale=alt.Scale(type='sqrt', scheme='redgrey',\n domain=[-1.0, 5.0], domainMid=0.0, clamp=True),\n legend=alt.Legend(orient='top', titleLimit=400, titleOrient='top',\n title='Cambio semanal (7 días más recientes vs. 7 anteriores)',\n offset=-15, labelSeparation=10,\n format='+,.0%', gradientLength=self.WIDTH)))\n\n\n def make_subchart(self, df, color):\n return alt.Chart(df).transform_lookup(\n lookup='municipality',\n from_=alt.LookupData(self.geography(), 'properties.NAME', ['type', 'geometry'])\n ).transform_calculate(\n daily_cases=alt.datum.weekly_cases / 7.0,\n daily_cases_100k=alt.datum.weekly_cases_100k / 7.0\n ).mark_geoshape().encode(\n color=color,\n tooltip=[alt.Tooltip(field='bulletin_date', type='temporal', title='Fecha de boletín'),\n alt.Tooltip(field='municipality', type='nominal', title='Municipio'),\n alt.Tooltip(field='popest2019', type='quantitative', format=',d',\n title='Población'),\n alt.Tooltip(field='weekly_cases', type='quantitative', format=',d',\n title='Casos (suma 7 días)'),\n alt.Tooltip(field='daily_cases', type='quantitative', format=',.1f',\n title='Casos (prom. 7 días)'),\n alt.Tooltip(field='daily_cases_100k', type='quantitative', format=',.1f',\n title='Casos/100k (prom. 7 días)'),\n alt.Tooltip(field='weekly_trend', type='quantitative', format='+,.0%',\n title='Cambio semanal')]\n ).properties(\n width=self.WIDTH,\n height=250\n )\n\n\n def geography(self):\n return alt.InlineData(values=util.get_geojson_resource('municipalities.topojson'),\n format=alt.TopoDataFormat(type='topojson', feature='municipalities'))\n\n def fetch_data(self, connection, bulletin_dates):\n table = sqlalchemy.Table('municipal_map', self.metadata,\n schema='products', autoload=True)\n query = select([\n table.c.bulletin_date,\n table.c.municipality,\n table.c.popest2019,\n (table.c.new_7day_cases).label('weekly_cases'),\n (1e5 * table.c.new_7day_cases / table.c.popest2019).label('weekly_cases_100k'),\n (table.c.pct_increase_7day - 1.0).label('weekly_trend')\n ]).where(and_(table.c.municipality.notin_(['Total', 'No disponible', 'Otro lugar fuera de PR']),\n min(bulletin_dates) <= table.c.bulletin_date,\n table.c.bulletin_date <= max(bulletin_dates)))\n return pd.read_sql_query(query, connection, parse_dates=[\"bulletin_date\"])\n\n def filter_data(self, df, bulletin_date):\n return df.loc[df['bulletin_date'] == pd.to_datetime(bulletin_date)]\n\n\nclass ICUsByHospital(AbstractChart):\n \"\"\"Hospitalizations based on HHS data, by hospital\"\"\"\n\n SORT_ORDER = ['Camas', 'Ocupadas', 'COVID']\n COLORS = [\"#a4d86e\", \"#f58518\", \"#d4322c\"]\n COLUMNS = 3\n FACET_WIDTH = 170\n\n def fetch_data(self, connection, bulletin_dates):\n table = sqlalchemy.Table('icus_by_hospital', self.metadata,\n schema='products', autoload=True)\n query = select([\n table.c.week_start,\n table.c.hospital_name,\n table.c.municipality,\n table.c.total_staffed_adult_icu_beds_7_day_lo\n .label('Camas'),\n table.c.staffed_adult_icu_bed_occupancy_7_day_hi\n .label('Ocupadas'),\n table.c.staffed_icu_adult_patients_covid_7_day_hi\n .label('COVID')\n ]).where(table.c.week_start <= max(bulletin_dates))\n df = pd.read_sql_query(query, connection, parse_dates=['week_start'])\n return pd.melt(df, ['week_start', 'hospital_name', 'municipality']).dropna()\n\n def filter_data(self, df, bulletin_date):\n return df.loc[df['week_start'] <= pd.to_datetime(bulletin_date) - pd.DateOffset(days=6)]\n\n def make_chart(self, df, bulletin_date):\n # We want all facets to have an x-axis scale but to have the same\n # domain. So we set resolve = independent for the facets, but set\n # the domain manually on all.\n min_date = df['week_start'].min()\n max_date = df['week_start'].max() + pd.DateOffset(days=7)\n return alt.Chart(df).mark_bar(opacity=0.8).transform_calculate(\n # `week_end` is inclusive endpoint, `next_week` is exclusive endpoint\n week_end=\"timeOffset('day', datum.week_start, 6)\",\n next_week=\"timeOffset('day', datum.week_start, 7)\"\n ).encode(\n x=alt.X('week_start:T', timeUnit='yearmonthdate',\n title=None, axis=alt.Axis(format='%b'),\n scale=alt.Scale(domain=[min_date, max_date])),\n x2=alt.X2('next_week:T'),\n y=alt.Y('value:Q', title=None, stack=None,\n axis=alt.Axis(minExtent=25, labelFlush=True)),\n color=alt.Color('variable:N', title=None, sort=self.SORT_ORDER,\n scale=alt.Scale(range=self.COLORS),\n legend=alt.Legend(orient='top', columns=3, labelLimit=250)),\n tooltip=[\n alt.Tooltip('week_start:T', title='Desde'),\n alt.Tooltip('week_end:T', title='Hasta'),\n alt.Tooltip('hospital_name:N', title='Hospital'),\n alt.Tooltip('municipality:N', title='Municipio'),\n alt.Tooltip('variable:N', title='Categoría'),\n alt.Tooltip('value:Q', format='.1f', title='Promedio 7 días)')\n ]\n ).properties(\n width=self.FACET_WIDTH, height=80\n ).facet(\n columns=self.COLUMNS,\n facet=alt.Facet('hospital_name:N', title=None,\n header=alt.Header(labelLimit=self.FACET_WIDTH, labelFontSize=8))\n ).resolve_scale(\n x='independent', y='independent'\n )\n\n\nclass ICUsByRegion(AbstractChart):\n \"\"\"Hospitalizations based on HHS data, by region\"\"\"\n\n SORT_ORDER = ['Camas', 'Ocupadas', 'COVID']\n COLORS = [\"#a4d86e\", \"#f58518\", \"#d4322c\"]\n COLUMNS = 2\n FACET_WIDTH = 280\n\n def fetch_data(self, connection, bulletin_dates):\n table = sqlalchemy.Table('icus_by_region', self.metadata,\n schema='products', autoload=True)\n query = select([\n table.c.week_start,\n table.c.region,\n table.c.total_staffed_adult_icu_beds_7_day_lo\n .label('Camas'),\n table.c.staffed_adult_icu_bed_occupancy_7_day_hi\n .label('Ocupadas'),\n table.c.staffed_icu_adult_patients_covid_7_day_hi\n .label('COVID')\n ]).where(table.c.week_start <= max(bulletin_dates))\n df = pd.read_sql_query(query, connection, parse_dates=['week_start'])\n return pd.melt(df, ['week_start', 'region']).dropna()\n\n def filter_data(self, df, bulletin_date):\n return df.loc[df['week_start'] <= pd.to_datetime(bulletin_date) - pd.DateOffset(days=6)]\n\n def make_chart(self, df, bulletin_date):\n # We want all facets to have an x-axis scale but to have the same\n # domain. So we set resolve = independent for the facets, but set\n # the domain manually on all.\n min_date = df['week_start'].min()\n max_date = df['week_start'].max() + pd.DateOffset(days=7)\n facet_width = 240\n return alt.Chart(df).mark_bar(opacity=0.8).transform_calculate(\n # `week_end` is inclusive endpoint, `next_week` is exclusive endpoint\n week_end=\"timeOffset('day', datum.week_start, 6)\",\n next_week=\"timeOffset('day', datum.week_start, 7)\"\n ).encode(\n x=alt.X('week_start:T', timeUnit='yearmonthdate',\n title=None, axis=alt.Axis(format='%b'),\n scale=alt.Scale(domain=[min_date, max_date])),\n x2=alt.X2('next_week:T'),\n y=alt.Y('value:Q', title=None, stack=None,\n axis=alt.Axis(minExtent=30, labelFlush=True)),\n color=alt.Color('variable:N', title=None, sort=self.SORT_ORDER,\n scale=alt.Scale(range=self.COLORS),\n legend=alt.Legend(orient='top', columns=3, labelLimit=250)),\n tooltip=[\n alt.Tooltip('week_start:T', title='Desde'),\n alt.Tooltip('week_end:T', title='Hasta'),\n alt.Tooltip('region:N', title='Región'),\n alt.Tooltip('variable:N', title='Categoría'),\n alt.Tooltip('value:Q', format='.1f', title='Promedio 7 días)')\n ]\n ).properties(\n width=self.FACET_WIDTH, height=100\n ).facet(\n columns=self.COLUMNS,\n facet=alt.Facet('region:N', title=None,\n header=alt.Header(labelLimit=self.FACET_WIDTH))\n ).resolve_scale(\n x='independent', y='independent'\n )\n\n\nclass LatenessTiers(AbstractChart):\n def fetch_data(self, connection, bulletin_dates):\n table = sqlalchemy.Table('lateness_tiers', self.metadata,\n schema='products', autoload=True)\n query = select([\n table.c.bulletin_date,\n table.c.tier,\n table.c.tier_order,\n table.c.count\n ]).where(table.c.bulletin_date <= max(bulletin_dates))\n return pd.read_sql_query(query, connection, parse_dates=['bulletin_date'])\n\n def filter_data(self, df, bulletin_date):\n return df.loc[df['bulletin_date'] <= pd.to_datetime(bulletin_date)]\n\n def make_chart(self, df, bulletin_date):\n max_y = df.groupby(['bulletin_date'])['count'].sum()\\\n .rolling(7).mean().max()\n\n base = alt.Chart(df).transform_joinaggregate(\n groupby=['bulletin_date'],\n total='sum(count)'\n ).transform_window(\n groupby=['tier'],\n sort=[{'field': 'bulletin_date'}],\n frame=[-6, 0],\n mean_count='mean(count)',\n mean_total='mean(total)'\n ).transform_calculate(\n percent=alt.datum.count / alt.datum.total,\n mean_percent=alt.datum.mean_count / alt.datum.mean_total\n ).mark_area(opacity=0.85).encode(\n color=alt.Color('tier:N', title='Renglón (días)',\n legend=alt.Legend(orient='top', titleOrient='left', offset=5),\n scale=alt.Scale(scheme='redyellowgreen', reverse=True)),\n order=alt.Order('tier_order:O'),\n tooltip=[alt.Tooltip('bulletin_date:T', title='Fecha de boletín'),\n alt.Tooltip('tier:N', title='Renglón'),\n alt.Tooltip('count:Q', format=\",d\", title='Casos en renglón (crudo)'),\n alt.Tooltip('total:Q', format=\",d\", title='Casos total (crudo)'),\n alt.Tooltip('mean_count:Q', format=\".1f\", title='Casos en renglón (promedio 7)'),\n alt.Tooltip('mean_total:Q', format=\".1f\", title='Casos total (promedio 7)'),\n alt.Tooltip('mean_percent:Q', format=\".1%\", title='% de total (promedio 7)')]\n )\n\n absolute = base.encode(\n x=alt.X('bulletin_date:T', title=None, axis=alt.Axis(ticks=False, labels=False)),\n y=alt.Y('mean_count:Q', title='Casos confirmados (promedio 7 días)',\n scale=alt.Scale(domain=[0, max_y]),\n axis=alt.Axis(labelExpr=\"if(datum.value > 0, datum.label, '')\")),\n ).properties(\n width=575, height=275\n )\n\n normalized = base.encode(\n x=alt.X('bulletin_date:T', timeUnit='yearmonthdate', title='Fecha de boletín',\n axis=alt.Axis(\n labelExpr=\"[timeFormat(datum.value, '%b'),\"\n \" timeFormat(datum.value, '%m') == '01'\"\n \" ? timeFormat(datum.value, '%Y')\"\n \" : '']\")),\n y=alt.Y('mean_count:Q', stack='normalize', title='% renglón',\n axis=alt.Axis(format='%', labelExpr=\"if(datum.value < 1.0, datum.label, '')\"))\n ).properties(\n width=575, height=75\n )\n\n return alt.vconcat(absolute, normalized, spacing=5)\n","sub_path":"src/covid_19_puerto_rico/charts.py","file_name":"charts.py","file_ext":"py","file_size_in_byte":38912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"125384189","text":"from __future__ import print_function, division\nimport os\nimport numpy as np\nfrom keras.layers import Convolution1D, Dense, MaxPooling1D, Flatten, BatchNormalization, Dropout, Activation\nfrom keras.models import Sequential\nfrom keras.utils import plot_model, normalize\n\ndef smc_retrieval(channel_size, filter_length, nb_input_lw, nb_output_smc, \n nb_filter):\n model = Sequential((\n # The first conv layer learns `nb_filter` filters (aka kernels), each of size ``(filter_length, nb_input_series)``.\n # Its output will have shape (None, window_size - filter_length + 1, nb_filter), i.e., for each position in\n # the input timeseries, the activation of each filter at that position.\n \n Convolution1D(nb_filter=nb_filter, filter_length=filter_length, \n activation='relu', input_shape=(channel_size, \n nb_input_lw)),\n MaxPooling1D(), \n Convolution1D(60, filter_length=filter_length, \n activation='relu'),\n MaxPooling1D(),\n Dropout(0.05),\n Flatten(),\n Dense(1000),\n #BatchNormalization(),\n Activation('relu'), \n #BatchNormalization(), \n #Dropout(0.005), \n Dense(nb_output_smc, activation='relu'), # For binary classification, change the activation to 'sigmoid'\n ))\n model.compile(loss='mse', optimizer='adam', metrics=['mae'])\n # To perform (binary) classification instead:\n # model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['binary_accuracy'])\n #plot_model(model, to_file=\"E:\\\\TJC\\\\workspace\\\\shuju\\\\model.png\")\n return model\n\ndef load_save():\n os.chdir(\"E:\\\\TJC\\\\workspace\\\\shuju\\\\\")\n j = 0\n all_csv = np.zeros((177,43,15),dtype=float)\n for i in os.listdir():\n all_csv[:,:,j] = np.loadtxt(open(i,\"rb\"),delimiter=\",\",skiprows=0)\n j = j + 1\n #print(lw_csv)\n #print(lw_csv)\n reall_csv = all_csv.reshape(7611,15)\n #print(relw_csv)\n A = reall_csv.reshape(7611,15,1)\n #smc_csv = np.loadtxt(open(\"E:\\\\TJC\\\\2016LW_NC_ASCII\\\\20160703_smc_region.csv\",\"rb\"),delimiter=\",\",skiprows=0) \n #Y = smc_csv.reshape(12972,1)\n #X_test = X[:3]\n #X_luan = np.random.shuffle(X_test)\n #print(X_luan)\n #print(Y)\n #S = np.zeros((5200,15,1),dtype=float)\n S = np.random.permutation(A)\n X = S[:, :14, :]\n X_NOL = normalize(X, axis=1, order=2)\n Y_L = S[:, 14:, :]\n Y = Y_L.reshape(7611,1)\n #print(Y_L)\n #print(Y)\n return X_NOL,Y\nload_save()\n\ndef test_save():\n os.chdir(\"E:\\\\TJC\\\\workspace\\\\test\\\\\")\n k = 0\n all_csv2 = np.zeros((59,43,14),dtype=float)\n for l in os.listdir():\n all_csv2[:,:,k] = np.loadtxt(open(l,\"rb\"),delimiter=\",\",skiprows=0)\n k = k + 1\n reall_csv2 =all_csv2.reshape(2537,14)\n B = reall_csv2.reshape(2537,14,1)\n X_test = normalize(B,axis=1,order=2)\n print(X_test)\n return X_test\ntest_save()\n\ndef evaluate_train():\n filter_length = 4\n nb_filter = 30\n model = smc_retrieval(channel_size=14, filter_length=filter_length,\n nb_input_lw=1, nb_output_smc=1, nb_filter=nb_filter)\n model.summary()\n \n X_NOL, Y = load_save()\n X_test = test_save()\n #test_size = int(0.1 * 5200)\n X_train, X_val, Y_train, Y_val = X_NOL[:6900], X_NOL[6900:], Y[:6900], Y[6900:]\n model.fit(X_train, Y_train, nb_epoch=20000, batch_size=3000, validation_data=(X_val, Y_val))\n pred = model.predict(X_test)\n f = open(\"log.txt\",\"w\")\n print('retrieval', sep='\\t',file = f)\n for retrieval in pred.squeeze():\n print(retrieval, sep='\\t',file = f)\n #squeeze()有压缩的意思,所以不会全部显示?\n #print(X_test.squeeze(), actual.squeeze(), predicted, sep='\\t')\n #score = model.accuracy_score(actual.squeeze(), predicted)\n #print('Accuracy: %.2f%%' % (score * 100))\n #print('9.13', model.predict(X_test).squeeze(), sep='\\t')\n \ndef main():\n #np.set_printoptions(threshold=1) \n evaluate_train()\n #plot_model(smc_retrieval(), to_file=\"E:\\\\TJC\\\\workspace\\\\shuju\\\\model.png\")\n \nif __name__ == '__main__':\n main()\n","sub_path":"1D_CNN_FOR_AMSR2_30_MAP.py","file_name":"1D_CNN_FOR_AMSR2_30_MAP.py","file_ext":"py","file_size_in_byte":4185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"287731782","text":"import socket # С помощью этой библиотеки определим, по какому адресу подняли сервер\nfrom flask import Flask, request, render_template, redirect, session # Подключаем модули backend-микрофреймворка\n\nimport database # Подключаем свой скрипт с функциями взаимодействия с базами данных\n\n# ------------- #\nlog = open('log.txt', 'w') # Открываем log.txt в режиме записи\nlog.write(socket.gethostbyname(\n socket.gethostname()) + \":27015\") # Записываем в файл ip-адрес компа, на котором запускается сервер (27015 это # порт)\nlog.close() # Сохраняем и закрываем файл\n# ------------- #\n\n# ------------- #\napp = Flask(__name__) # Запускаем приложение\napp.config[\n 'SECRET_KEY'] = \"super_secret_key\" # Это ключ для защиты от подделки межсайтовых запросов, это тут вообще не нужно\napp.config['USERS'] = database.login() # Берём из базы данных Пользователей, записываем в приложение\n# ------------- #\n\n\n@app.errorhandler(404) # Если ошибка на стороне пользователя\n@app.errorhandler(500) # Или ошибка на стороне сервера\ndef error_handler(e): # Запускаем страницу обработчика ошибок\n return \"

Что-то пошло не так

\"\n\n\n@app.route('/', methods=['POST', 'GET']) # Страница авторизации\ndef login():\n if request.method == 'GET': # Просто получаем страницу\n if session.get('is_auth'): # Если мы авторизованы то редирект на страницу пользоавателя\n return redirect(\"/userpage\")\n return render_template(\"login.html\", error_alert=\"\")\n elif request.method == 'POST': # Посылаем Логин и Пароль через форму\n username = request.form.get('username')\n password = request.form.get('password')\n # print(username, password) # Эта строчка использовалась во время разработки и полезна при отладке\n if username and password \\\n and username in set(app.config[\"USERS\"].keys()) \\\n and password in [str(i[1]) for i in app.config[\"USERS\"].values()] \\\n and password == app.config[\"USERS\"][username][-1]: # Проверяем логин и пароль на Валидность\n session[\"is_auth\"] = True # Если проверка прошла то говорим что пользователь авторизован\n session[\"user_id\"] = int(app.config[\"USERS\"][username][0]) # id авторизованного пользователя тоже запомним\n return redirect(\"/main\") # Переадресуем уже авторизованого пользователя на главную\n else: # Если логин и пароль проверку не прошли то загружаем ту же страницу, но с сообщением об ошибке\n return render_template(\"login.html\", error_alert=\"Неверный логин и/или пароль\")\n\n\n@app.route('/main') # главная страница\ndef main_page():\n if not session.get('user_id'): # Если пользователь не регестрировался то у него нет id и действия на сайте не будут работать, поэтому дадим ему нулевой id\n session[\"user_id\"] = 0\n if not session.get('is_auth'):\n userpage = \"Авторизоваться\" # Если не авторизованы, в правом верхнем углу будет эта надпись\n else:\n userpage = \"Моя страница\" # Иначе эта\n return render_template(\"index.html\", a=userpage)\n\n\n@app.route(\"/squads/\") # Переход на страницу Отряда\ndef squad_page(squad):\n squad_num, squad_name, squad_slogan, achivements = database.squads(squad)\n # Получаем из базы данных информацию об отряде, на который перешли, вставляем в страницу\n return render_template(\"squadpage.html\",\n squad_num=squad_num,\n squad_name=squad_name,\n squad_slogan=squad_slogan,\n achivements=achivements,\n info=database.squad_info(squad),\n admin=(\"admin\" in database.userinfo(session.get('user_id'))[\"post\"] and session.get(\n 'is_auth')), )\n\n\n@app.route(\"/userpage\") # Страница пользователя\ndef userpage():\n if not session.get('is_auth'): # Если ты не авторизован то иди авторизуйся\n return redirect(\"/\")\n pioneer_post = ''\n userInfo = database.userinfo(session.get('user_id')) # Пишем в userInfo информацию о пользователе, взятому из базы данных по id\n if userInfo[\"post\"] not in (None, ''): # Должность пишем только для того, у кого она есть\n pioneer_post = f\"Должность: {userInfo['post']}\"\n return render_template(\"userpage.html\",\n name=userInfo[\"name\"],\n firstname=userInfo[\"firstname\"],\n lastname=userInfo[\"lastname\"],\n squad=userInfo[\"squad\"],\n balance=userInfo[\"balance\"],\n post=pioneer_post, info=database.check_fines(session.get('user_id')))\n\n\n@app.route(\"/logout/\") # Сюда мы переадресуем пользователя, решившего выйти из аккаунта\ndef logout():\n session[\"is_auth\"] = False # Тут делаем пользователя неавторизованным\n return redirect(\"/\") # И переадресуем его на страницу авторизации\n\n\n@app.route(\"/edit/\", methods=['POST', 'GET'])\n# Сюда мы переадресуем пользователя-админа для редактирования пользователя\n# (кнопка edit в таблицах отряда хранит id пользователя, которого она редактирует)\ndef edit_user(id): # Передаём id редактируемого пользователя\n\n # -- см. комментарии userPage -- #\n pioneer_post = ''\n userInfo = database.userinfo(id)\n if userInfo[\"post\"] != 'pioner':\n pioneer_post = f\"Должность: {userInfo['post']}\"\n if request.method == 'GET':\n if not (session.get('is_auth') and (\"admin\" in database.userinfo(session.get('user_id'))[\"post\"])):\n return redirect(\"/main\")\n return render_template(\"edit_user.html\",\n id=userInfo[\"id\"],\n name=userInfo[\"name\"],\n firstname=userInfo[\"firstname\"],\n lastname=userInfo[\"lastname\"],\n squad=userInfo[\"squad\"],\n balance=userInfo[\"balance\"],\n post=pioneer_post,\n error_alert='',\n info=database.check_fines(id))\n # ----------------------------- #\n\n # Работа с Формой штрафа/премирования #\n elif request.method == 'POST':\n fine = request.form.get('fine')\n tal = request.form.get('sum')\n comm = request.form.get('comment')\n if tal and comm and str(tal).isdigit():\n if fine:\n tal = -int(tal)\n database.change_balance(id, int(tal), comm)\n print(database.check_fines(id))\n tal = comm = ''\n return redirect(f\"/edit/{id}\")\n else:\n return render_template(\"edit_user.html\",\n id=userInfo[\"id\"],\n name=userInfo[\"name\"],\n firstname=userInfo[\"firstname\"],\n lastname=userInfo[\"lastname\"],\n squad=userInfo[\"squad\"],\n balance=userInfo[\"balance\"],\n post=pioneer_post,\n error_alert='Неверный формат данных', info=database.check_fines(id))\n\n\n@app.route(\"/change//\") # Сюда мы переходим при нажатии кнопки Увеличения и Уменьшения количества побед в мероприятиях\ndef change(squad, digit):\n if not (session.get('is_auth') and (\"admin\" in database.userinfo(session.get('user_id'))[\"post\"])):\n pass # Если сюда пытается перейти не_админ то ничего не изменится\n else: # Если ты админ, то всё меняется соответствующе нажатой кнопке\n if digit == '+':\n database.change_achivements(squad, 1)\n elif digit == '-':\n database.change_achivements(squad, -1)\n return redirect(f\"/squads/{squad}\")\n\n\nif __name__ == '__main__':\n app.run(host=socket.gethostbyname(socket.gethostname()), port=27015)\n # app.run(host='127.0.0.1', port=8000) # раскомменть для дебага\n","sub_path":"bank/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"623408881","text":"import sys\nimport os\nimport warnings\n# warnings.simplefilter(\"ignore\", DeprecationWarning)\nfrom ncclient import manager\nfrom lxml import etree\nimport string\nimport xmltodict\n\n\ndef demo(host, port, user, password):\n \n with manager.connect(host=host, port=port, username=user, hostkey_verify=False, password=password) as m:\n # m.edit_config(target='running', config=xml_1)\n xml_1 = open('../Yang_xml/mplane.xml').read()\n snippet = f\"\"\"\n \n {xml_1}\n \"\"\"\n data = m.edit_config(target='running', config = snippet, default_operation = 'replace')\n print(data)\n interfaces = '''\n \n \n \n \n '''\n\n com = '''\n \n \n '''\n try:\n value_interfaces = m.get(('subtree', interfaces)).data_xml\n # print(value_interfaces)\n except:\n print(\"Can't find the value_interfaces\")\n\n try:\n value_com = m.get(('subtree', com)).data_xml\n # print(value_com)\n except:\n print(\"Can't find the value_com\")\n\n dict_interfaces = xmltodict.parse(str(value_interfaces))\n #print('dict_module :',dict_module)\n dict_com = xmltodict.parse(str(value_com))\n\n print(\"\\n\\n******validation for m-plane-interfaces******\\n\\n\")\n try:\n Searchable_Access_Vlans = dict_interfaces['data'][\n 'mplane-info']['searchable-mplane-access-vlans-info']['searchable-access-vlans']\n if Searchable_Access_Vlans:\n print(\"Searchable_Access_Vlans = %s\" % Searchable_Access_Vlans)\n except:\n print(\n 'Searchable_Access_Vlans not found')\n\n try:\n Lowest_Vlan_id = dict_interfaces['data'][\n 'mplane-info']['searchable-mplane-access-vlans-info']['vlan-range']['lowest-vlan-id']\n if Lowest_Vlan_id:\n print(\"Searchable_Access_Vlans = %s\" % Lowest_Vlan_id)\n except:\n print(\n 'Lowest_Vlan_id not found')\n\n try:\n Highest_Vlan_id = dict_interfaces['data'][\n 'mplane-info']['searchable-mplane-access-vlans-info']['vlan-range']['highest-vlan-id']\n if Highest_Vlan_id:\n print(\"Highest_Vlan_id = %s\" % Highest_Vlan_id)\n except:\n print(\n 'Highest_Vlan_id not found')\n\n try:\n Call_home_ssh_port = dict_interfaces['data'][\n 'mplane-info']['m-plane-interfaces']['m-plane-ssh-ports']['call-home-ssh-port']\n if Call_home_ssh_port:\n print(\"Call_home_ssh_port = %s\" % Call_home_ssh_port)\n except:\n print(\n 'Call_home_ssh_port not found')\n\n try:\n Server_ssh_port = dict_interfaces['data']['mplane-info']['m-plane-interfaces']['m-plane-ssh-ports']['server-ssh-port']\n if Server_ssh_port:\n print(\"Server_ssh_port = %s\" % Server_ssh_port)\n except:\n print(\n 'Server_ssh_port not found')\n\n try:\n Interface_Name = dict_interfaces['data']['mplane-info']['m-plane-interfaces']['m-plane-sub-interfaces']['interface-name']\n if Interface_Name:\n print(\"Interface_Name = %s\" % Interface_Name)\n except:\n print(\n 'Interface_Name not found')\n\n try:\n Sub_Interface = dict_interfaces['data']['mplane-info']['m-plane-interfaces']['m-plane-sub-interfaces']['sub-interface']\n if Sub_Interface:\n print(\"Sub_Interface = %s\" % Sub_Interface)\n except:\n print(\n 'Sub_Interface not found')\n\n\nif __name__ == '__main__':\n # give the input configuration in xml file format\n # xml_1 = open('o-ran-hardware.xml').read()\n # give the input in the format hostname, port, username, password\n demo(\"192.168.1.10\", 830, \"root\", \"root\")\n","sub_path":"Python_Automation_File/o-ran-mplane.py","file_name":"o-ran-mplane.py","file_ext":"py","file_size_in_byte":4228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"212604829","text":"import xml.etree.ElementTree as ET\nimport pprint\nimport re\n\n\ndef extractBookFields(book):\n result={}\n book_fields = ['id','isbn','isbn13','text_reviews_count','title','link','num_pages','publication_day',\n 'publication_year','publication_month','average_rating','ratings_count','published']\n for i in range(0, len(book_fields)):\n fname = book_fields[i]\n x = book.find(fname)\n if x is not None:\n if not (x.text is None):\n result[fname] = x.text\n\n result['author'] = book.find('authors/author/name').text\n\n int_fields = ['text_reviews_count','num_pages','publication_day','publication_year','publication_month',\n 'ratings_count','published']\n for i in range(0, len(int_fields)):\n fname = int_fields[i]\n if result.has_key(fname):\n result[fname] = int(result[fname])\n\n if (result['average_rating'] is not None):\n result['average_rating'] = float(result['average_rating'])\n\n return result\n\ndef extractReviewFields(review):\n result={}\n fields = ['id','rating','votes','started_at','read_at','date_added','date_updated','url']\n\n for i in range(0, len(fields)):\n fname = fields[i]\n x = review.find(fname)\n if x is not None:\n if (x.text is not None):\n result[fname] = x.text\n\n int_fields = ['rating','votes']\n\n for i in range(0, len(int_fields)):\n fname = int_fields[i]\n if result.has_key(fname):\n result[fname] = int(result[fname])\n\n shelves = review.find('shelves')\n if len(shelves) > 0:\n result['shelves']=[]\n for shelf in shelves:\n result['shelves'].append(shelf.attrib['name'])\n\n return result\n\ndef processReview(review):\n result = extractReviewFields(review)\n book = review.find('book')\n book_result = extractBookFields(book)\n result['book_id'] = book_result['id']\n return result\n\ndef parseReviewFile(filename):\n tree = ET.parse(filename)\n root = tree.getroot()\n\n json_reviews = []\n reviews = root.find(\"./reviews\")\n\n i=0\n for review in reviews:\n new_record = processReview(review)\n json_reviews.append(new_record)\n return json_reviews\n\ndef importReviewFile(filename):\n user_id = re.findall(r'\\d+', filename)[0]\n parseReviewFile(filename)\n\n","sub_path":"importLibrary.py","file_name":"importLibrary.py","file_ext":"py","file_size_in_byte":2356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"330589330","text":"# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nSparse coding.\n=============\n\"\"\"\n\nimport functools\nfrom typing import Any\nfrom typing import Callable\nfrom typing import Mapping\nfrom typing import Optional\n\nimport jax\nimport jax.numpy as jnp\nfrom jaxopt import OptaxSolver\nfrom jaxopt import projection\nfrom jaxopt import prox\nfrom jaxopt import ProximalGradient\n\n\ndef dictionary_loss(\n codes: jnp.ndarray,\n dictionary: jnp.ndarray,\n data: jnp.ndarray,\n reconstruction_loss_fun: Callable[[jnp.ndarray, jnp.ndarray],\n jnp.ndarray] = None):\n \"\"\"Computes reconstruction loss between data and dict/codes using loss fun.\n\n Args:\n codes: a n_samples x components array of codes.\n dictionary: a components x dimension array\n data: a n_samples x dimension array\n reconstruction_loss_fun: a callable loss(x, y) -> a real number, where\n x and y are either entries, slices or the matrices themselves.\n Set to 1/2 squared L2 norm of difference by default.\n\n Returns:\n a float, the reconstruction loss.\n \"\"\"\n if reconstruction_loss_fun is None:\n reconstruction_loss_fun = lambda x, y: 0.5 * jnp.sum((x - y)**2)\n pred = codes @ dictionary\n return reconstruction_loss_fun(data, pred)\n\n\ndef make_task_driven_dictionary_learner(\n task_loss_fun: Optional[Callable[[Any, Any, Any, Any], float]] = None,\n reconstruction_loss_fun: Optional[Callable[[jnp.ndarray, jnp.ndarray],\n jnp.ndarray]] = None,\n optimizer = None,\n sparse_coding_kw: Mapping[str, Any] = None,\n **kwargs):\n \"\"\"Makes a task-driven sparse dictionary learning solver.\n\n Returns a jaxopt solver, using either an optax optimizer or jaxopt prox\n gradient optimizer, to compute, given data, a dictionary whose corresponding\n codes minimizes a given task loss. The solver is defined through the task loss\n function, a reconstruction loss function, and an optimizer. Additional\n parameters can be passed on to lower level functions, notably the computation\n of sparse codes and optimizer parameters.\n\n Args:\n task_loss_fun: loss as specified on (codes, dict, task_vars, params) that\n supplements the usual reconstruction loss formulation. If None, only\n dictionary learning is carried out, i.e. that term is assumed to be 0.\n reconstruction_loss_fun: entry (or slice-) wise loss function, set to be\n the Frobenius norm between matrices, || . - . ||^2 by default.\n optimizer: optax optimizer. fall back on jaxopt proxgrad if None.\n sparse_coding_kw: Jaxopt arguments to be passed to the proximal descent\n algorithm computing codes, sparse_coding.\n **kwargs: passed onto _task_sparse_dictionary_learning function.\n\n Returns:\n Function to learn dictionary from data, number of components and\n elastic net regularization, using initialization for dictionary,\n parameters for task and task variables initialization.\n \"\"\"\n def learner(data: jnp.ndarray,\n n_components: int,\n regularization: float,\n elastic_penalty: float,\n task_vars_init: jnp.ndarray = None,\n task_params: jnp.ndarray = None,\n dic_init: Optional[jnp.ndarray] = None):\n\n return _task_sparse_dictionary_learning(data, n_components, regularization,\n elastic_penalty, task_vars_init,\n optimizer,\n dic_init, task_params,\n reconstruction_loss_fun,\n task_loss_fun,\n sparse_coding_kw, **kwargs)\n\n return learner\n\n\ndef _task_sparse_dictionary_learning(\n data: jnp.ndarray,\n n_components: int,\n regularization: float,\n elastic_penalty: float,\n task_vars_init: jnp.ndarray,\n optimizer=None,\n dic_init: Optional[jnp.ndarray] = None,\n task_params: jnp.ndarray = None,\n reconstruction_loss_fun: Callable[[jnp.ndarray, jnp.ndarray],\n jnp.ndarray] = None,\n task_loss_fun: Callable[[Any, Any, Any, Any], float] = None,\n sparse_coding_kw: Mapping[str, Any] = None,\n maxiter: int = 100):\n r\"\"\"Computes task driven dictionary, w. implicitly defined sparse codes.\n\n Given a N x d ``data`` matrix, solves a bilevel optimization problem by\n seeking a dictionary ``dic`` of size ``n_components`` x ``d`` such that,\n defining implicitly\n ``codes = sparse_coding(dic, (data, regularization, elastic_penalty))``\n one has that ``dic`` minimizes\n ``task_loss(codes, dic, task_var, task_params)``,\n if such as ``task_loss`` was passed on. If ``task_loss`` is ``None``, then\n ``task_loss`` is replaced by default by\n ``dictionary_loss(codes, (dic, data))``.\n\n Args:\n data: N x d jnp.ndarray, data matrix with N samples of d features.\n n_components: int, number of atoms in dictionary.\n regularization: regularization strength of elastic penalty.\n elastic_penalty: strength of L2 penalty relative to L1.\n task_vars_init: initializer for task related optimization variables.\n optimizer: If None, falls back on jaxopt proximal gradient (with sphere\n projection for ``dic``). If not ``None``, use that algorithm's method with\n a normalized dictionary.\n dic_init: initialization for dictionary; that returned by SVD by default.\n reconstruction_loss_fun: loss to be applied to compute reconstruction error.\n task_params: auxiliary parameters to define task loss, typically data.\n task_loss_fun: task driven loss for codes and dictionary using task_vars and\n task_params.\n sparse_coding_kw: parameters passed on to jaxopt prox gradient solver to\n compute codes.\n maxiter: maximal number of iterations of the outer loop.\n\n Returns:\n A``n_components x d`` matrix, the ``dic`` solution found by the algorithm,\n as well as task variables if task was provided.\n \"\"\"\n\n if dic_init is None:\n _, _, dic_init = jax.scipy.linalg.svd(data, False)\n dic_init = dic_init[:n_components, :]\n\n has_task = task_loss_fun is not None\n\n # Loss function, dictionary learning in addition to task driven loss\n def loss_fun(params, hyper_params):\n dic, task_vars = params\n coding_params, task_params = hyper_params\n codes = sparse_coding(\n dic,\n coding_params,\n reconstruction_loss_fun=reconstruction_loss_fun,\n sparse_coding_kw=sparse_coding_kw)\n if optimizer is not None:\n dic = projection.projection_l2_sphere(dic)\n\n if has_task:\n loss = task_loss_fun(codes, dic, task_vars, task_params)\n else:\n loss = dictionary_loss(codes, dic, data, reconstruction_loss_fun)\n return loss, codes\n\n def prox_dic(params, hyper, step):\n # Here projection/prox is only applied on the dictionary.\n del hyper, step\n dic, task_vars = params\n return projection.projection_l2_sphere(dic), task_vars\n\n if optimizer is None:\n solver = ProximalGradient(fun=loss_fun, prox=prox_dic, has_aux=True)\n params = (dic_init, task_vars_init)\n state = solver.init_state(params, None)\n\n for _ in range(maxiter):\n params, state = solver.update(\n params, state, None,\n ((data, regularization, elastic_penalty), task_params))\n\n # Normalize dictionary before returning it.\n dic, task_vars = prox_dic(params, None, None)\n\n else:\n solver = OptaxSolver(opt=optimizer, fun=loss_fun, has_aux=True)\n params = (dic_init, task_vars_init)\n state = solver.init_state(params)\n\n for _ in range(maxiter):\n params, state = solver.update(\n params, state,\n ((data, regularization, elastic_penalty), task_params))\n\n # Normalize dictionary before returning it.\n dic, task_vars = prox_dic(params, None, None)\n\n if has_task:\n return dic, task_vars\n return dic\n\n\ndef sparse_coding(dic, params, reconstruction_loss_fun=None,\n sparse_coding_kw=None, codes_init=None):\n \"\"\"Computes optimal codes for data given a dictionary dic using params.\"\"\"\n sparse_coding_kw = {} if sparse_coding_kw is None else sparse_coding_kw\n loss_fun = functools.partial(dictionary_loss,\n reconstruction_loss_fun=reconstruction_loss_fun)\n data, regularization, elastic_penalty = params\n n_components, _ = dic.shape\n n_points, _ = data.shape\n\n if codes_init is None:\n codes_init = jnp.zeros((n_points, n_components))\n\n solver = ProximalGradient(\n fun=loss_fun,\n prox=prox.prox_elastic_net,\n **sparse_coding_kw)\n\n codes = solver.run(codes_init, [regularization, elastic_penalty],\n dic, data).params\n return codes\n","sub_path":"examples/implicit_diff/sparse_coding.py","file_name":"sparse_coding.py","file_ext":"py","file_size_in_byte":9267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"67272444","text":"from preprocess import PreProcess\n\np = PreProcess('./datasets/gistnote_highlights')\nlabels, tensor = p.run_look_up()\nprint(tensor[0])\nwith open('./datasets/gistnote_highlight_7blkup.txt', 'w', encoding='utf8') as f1:\n document_strs = []\n for matrix in tensor:\n char_strs = []\n for vector in matrix:\n char_strs.append(vector)\n document_str = ','.join(char_strs)\n document_strs.append(document_str)\n lines = []\n for i in range(len(document_strs)):\n # if labels[i] != 'Entertainment':\n lines.append(labels[i] + '|l|' + document_strs[i])\n\n print(len(lines))\n f1.write('\\n'.join(lines))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"341533358","text":"\nfrom .base import Node\nfrom ebu_tt_live.documents import EBUTT3DocumentSequence, EBUTTDDocument\nfrom ebu_tt_live.documents.converters import EBUTT3EBUTTDConverter\nfrom ebu_tt_live.strings import DOC_RECEIVED\nfrom ebu_tt_live.clocks.media import MediaClock\nfrom datetime import timedelta\nimport logging\n\n\nlog = logging.getLogger(__name__)\ndocument_logger = logging.getLogger('document_logger')\n\n\nclass SimpleConsumer(Node):\n\n _reference_clock = None\n _sequence = None\n\n def __init__(self, node_id, carriage_impl, reference_clock):\n super(SimpleConsumer, self).__init__(node_id, carriage_impl)\n self._reference_clock = reference_clock\n\n def process_document(self, document):\n if self._sequence is None:\n # Create sequence from document\n log.info('Creating document sequence from first document {}'.format(\n document\n ))\n self._sequence = EBUTT3DocumentSequence.create_from_document(document)\n self._reference_clock = self._sequence.reference_clock\n if document.availability_time is None:\n document.availability_time = self._reference_clock.get_time()\n\n document_logger.info(DOC_RECEIVED.format(\n sequence_number=document.sequence_number,\n sequence_identifier=document.sequence_identifier,\n computed_begin_time=document.computed_begin_time,\n computed_end_time=document.computed_end_time\n ))\n self._sequence.add_document(document)\n\n @property\n def reference_clock(self):\n return self._reference_clock\n\n @reference_clock.setter\n def reference_clock(self, value):\n self._reference_clock = value\n\n\nclass EBUTTDEncoder(SimpleConsumer):\n\n _last_segment_end = None\n _segment_length = None\n _ebuttd_converter = None\n _default_ebuttd_doc = None\n _outbound_carriage_impl = None\n _segment_timer = None\n _discard = None\n\n def __init__(self, node_id, carriage_impl, outbound_carriage_impl, reference_clock,\n segment_length, media_time_zero, segment_timer, discard):\n super(EBUTTDEncoder, self).__init__(\n node_id=node_id,\n carriage_impl=carriage_impl,\n reference_clock=reference_clock\n )\n self._outbound_carriage_impl = outbound_carriage_impl\n # We need clock factory to figure the timesync out\n self._last_segment_end = reference_clock.get_time()\n self._segment_length = timedelta(seconds=segment_length)\n media_clock = MediaClock()\n media_clock.adjust_time(timedelta(), media_time_zero)\n self._ebuttd_converter = EBUTT3EBUTTDConverter(\n media_clock=media_clock\n )\n self._default_ebuttd_doc = EBUTTDDocument(lang='en-GB')\n self._default_ebuttd_doc.validate()\n self._segment_timer = segment_timer\n self._discard = discard\n\n @property\n def last_segment_end(self):\n return self._last_segment_end\n\n @property\n def segment_length(self):\n return self._segment_length\n\n def increment_last_segment_end(self, increment_by):\n self._last_segment_end += increment_by\n return self._last_segment_end\n\n def process_document(self, document):\n sequence_missing = self._sequence is None\n super(EBUTTDEncoder, self).process_document(document)\n # segmentation, conversion... here\n if sequence_missing and self._sequence is not None:\n # Ok we just got a relevant document. Let's call the function\n # that schedules the periodic segmentation.\n self._segment_timer = self._segment_timer(self)\n\n def get_segment(self, begin=None, end=None):\n if self._sequence is not None:\n segment_doc = self._sequence.extract_segment(begin=begin, end=end, discard=self._discard)\n return segment_doc\n return None\n\n def convert_next_segment(self):\n # Figure out begin and end\n ebutt3_doc = self.get_segment(\n begin=self.last_segment_end,\n end=self.last_segment_end + self._segment_length\n )\n if ebutt3_doc is not None:\n ebuttd_bindings = self._ebuttd_converter.convert_element(ebutt3_doc.binding, dataset={})\n ebuttd_doc = EBUTTDDocument.create_from_raw_binding(ebuttd_bindings)\n ebuttd_doc.validate()\n else:\n ebuttd_doc = self._default_ebuttd_doc\n self.increment_last_segment_end(self._segment_length)\n self._outbound_carriage_impl.emit_document(ebuttd_doc)\n","sub_path":"ebu_tt_live/node/consumer.py","file_name":"consumer.py","file_ext":"py","file_size_in_byte":4570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"367720906","text":"from django.http import HttpResponse, HttpResponseRedirect\nfrom django.views.generic import View\nfrom django.shortcuts import render\nfrom django.template.context import RequestContext\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.models import User\nfrom members.models import VideoFav\nfrom datetime import datetime\n\nclass homePage(View):\n def get(self, request):\n if request.user.is_authenticated():\n return HttpResponseRedirect('/members/')\n else:\n pageTitleTag = \"Home\" \n pageHeading = \"Welcome to RedstoneNinja Gaming\" \n\n context = {\"pageTitleTag\": pageTitleTag, \"pageHeading\": pageHeading}\n\n return render(request, \"homePage.html\", context)\n\nclass about(View):\n def get(self, request):\n pageTitleTag = \"About\" \n pageHeading = \"About RedstoneNinja Gaming\" \n \n friends = [ \"Iron_Ninja5 (Minecraft and Roblox)\",\n \"Awesome84_Playz (Roblox)\", \n \"Destroyer2t (Minecraft)\",\n ]\n \n context = {\"pageTitleTag\": pageTitleTag, \"pageHeading\": pageHeading, \"friends\": friends}\n\n return render(request, \"about.html\", context)\n\nclass server(View):\n def get(self, request):\n pageTitleTag = \"Server\" \n pageHeading = \"Gamezone\" \n \n context = {\"pageTitleTag\": pageTitleTag, \"pageHeading\": pageHeading}\n\n return render(request, \"server.html\", context)\n \nclass creation(View):\n def get(self, request):\n pageTitleTag = \"Creations\" \n pageHeading = \"RedstoneNinja Gaming Creations\" \n \n context = {\"pageTitleTag\": pageTitleTag, \"pageHeading\": pageHeading}\n\n return render(request, \"creation.html\", context)\n \nclass loginUser(View):\n def post(self, request):\n \n username = request.POST['username']\n password = request.POST['password']\n user = authenticate(username=username, password=password)\n if user is not None:\n if user.is_active:\n login(request, user)\n # Redirect to a success page.\n return HttpResponseRedirect('/members/')\n else:\n # Return a 'disabled account' error message\n pageTitleTag = \"Login\" \n pageHeading = \"Login to RedstoneNinja Gaming\" \n \n context = {\"pageTitleTag\": pageTitleTag, \"pageHeading\": pageHeading, \"error\": \"disabled\"}\n\n return render(request, \"login.html\", context)\n \n else:\n # Return a 'invalid account' error message\n pageTitleTag = \"Login\" \n pageHeading = \"Login to RedstoneNinja Gaming\" \n\n context = {\"pageTitleTag\": pageTitleTag, \"pageHeading\": pageHeading, \"error\": \"true\"}\n\n return render(request, \"login.html\", context)\n \n def get(self, request):\n pageTitleTag = \"Login\" \n pageHeading = \"Login to RedstoneNinja Gaming\" \n \n context = {\"pageTitleTag\": pageTitleTag, \"pageHeading\": pageHeading}\n\n return render(request, \"login.html\", context)\n \nclass logoutUser(View):\n def get(self, request):\n logout(request)\n \n pageTitleTag = \"Logout\" \n pageHeading = \"You have successfully logged out of RedstoneNinja Gaming\" \n \n context = {\"pageTitleTag\": pageTitleTag, \"pageHeading\": pageHeading}\n\n return render(request, \"logout.html\", context)\n \nclass signup(View):\n def post(self, request):\n \n newUsername = request.POST.get(\"username\")\n newPassword = request.POST.get(\"password\")\n newEmail = request.POST.get(\"email\")\n newFirstName = request.POST.get(\"firstname\")\n newLastName = request.POST.get(\"lastname\")\n \n user = User.objects.create_user(username=newUsername,\n email=newEmail,\n password=newPassword)\n user.firstname=newFirstName\n user.lastname=newLastName\n user.save()\n \n userLogin = authenticate(username=newUsername, password=newPassword)\n if userLogin is not None:\n if userLogin.is_active:\n login(request, userLogin)\n # Redirect to a success page.\n return HttpResponseRedirect('/members/')\n else:\n # Return a 'disabled account' error message\n return HttpResponseRedirect('/login/?status=disabled')\n else:\n # Return an 'invalid login' error message.\n return HttpResponseRedirect('/login/?status=error')\n \n def get(self, request):\n pageTitleTag = \"Sign up\" \n pageHeading = \"Sign up for a RedstoneNinja Gaming account\" \n \n context = {\"pageTitleTag\": pageTitleTag, \"pageHeading\": pageHeading}\n\n return render(request, \"signup.html\", context)\n \nclass videolistmembers(View):\n def get(self, request, userID):\n \n member=User.objects.get(pk=userID)\n \n pageTitleTag = \"Video favs-{0}\".format(member.username) \n pageHeading = \"Video favs-{0}\".format(member.username)\n \n videos = VideoFav.objects.filter(userID_fk=userID)\n \n vidList = []\n for video in videos:\n thisVideo={}\n thisVideo['title'] = video.title\n thisVideo['code'] = video.videoURL.split('=')[1]\n \n vidList.append(thisVideo)\n\n context = {\"pageTitleTag\": pageTitleTag, \"pageHeading\": pageHeading, \"videos\": vidList}\n\n return render(request, \"videos.html\", context)\n \nclass member(View):\n def get(self, request):\n pageTitleTag = \"Oops!\" \n pageHeading = \"Sorry!\" \n\n context = {\"pageTitleTag\": pageTitleTag, \"pageHeading\": pageHeading}\n\n return render(request, \"memberonly.html\", context)\n \nclass response(View):\n def get(self, request):\n pageTitleTag = \"Submit your creation ideas\" \n pageHeading = \"Submit below!\" \n\n context = {\"pageTitleTag\": pageTitleTag, \"pageHeading\": pageHeading}\n\n return render(request, \"response.html\", context)\n\nclass home(View):\n def get(self, request):\n pageTitleTag = \"HomeWorld download\" \n pageHeading = \"About homeworld\" \n\n context = {\"pageTitleTag\": pageTitleTag, \"pageHeading\": pageHeading}\n\n return render(request, \"response.html\", context)\n","sub_path":"redstoneninjagaming/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"591892390","text":"from sklearn.datasets import load_boston\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import Ridge, Lasso\nfrom sklearn.model_selection import train_test_split\nimport pandas as pd #data frame\nimport numpy as np # manipolazione array\nfrom sklearn.metrics import mean_squared_error\n\n\ndef f(x, a, b):\n return a + b*x\n\ndef ridge_regression(alpha, xDataSet, yDataSet, xTest, yTest):\n ret = []\n for a in alpha:\n r = Ridge(alpha=a)\n r.fit(xDataSet, yDataSet)\n pred = r.predict(xTest)\n ret = ret + [mean_squared_error(yTest, pred)]\n\n return ret\n\n# dataset di esempio\ndata = load_boston()\n\ndf = pd.DataFrame(data.data, columns=data.feature_names)\ndfY = pd.Series(data.target)\ndfX = df\n\nprint(dfX.head())\n\ndfX_train, dfX_test, dfY_train, dfY_test = train_test_split(dfX, dfY, test_size=0.25)\n\nalpha = range(0, 100, 1)\nmse = ridge_regression(alpha, dfX_train, dfY_train, dfX_test, dfY_test)\n\nplt.plot(alpha, mse)\nplt.show()","sub_path":"ridge_regression/ridge_regression.py","file_name":"ridge_regression.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"73712643","text":"#!/usr/bin/env python\n\n\"\"\" A script for plotting feature based analysis of hyperparameter optimization performance\n\"\"\"\n\nfrom __future__ import print_function\nimport os\nimport sys\nimport argparse\nimport numpy as np\nimport pickle\nfrom sklearn.decomposition import PCA\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport datetime\nfrom scipy import stats\nimport uuid\nfrom mpl_toolkits.mplot3d import Axes3D\n\n# plt.rcParams['text.usetex'] = True\nfrom matplotlib import rcParams\nrcParams.update({\n 'figure.autolayout': True,\n 'axes.labelsize': 'xx-large',\n 'axes.titlesize' : 'xx-large',\n 'xtick.labelsize': 'x-large',\n 'ytick.labelsize': 'x-large',\n 'legend.fontsize' : 'small',\n 'font.size': 25,\n 'font.family': 'Times New Roman',\n 'font.serif': 'Times',\n 'axes.labelpad': 20,\n 'axes.ymargin' : 0.05,\n 'axes.xmargin' : 0.05\n })\n\ndef _get_feature_from_list(l, feature):\n for x in l:\n if x['name'] == feature:\n return x['value']\n\n raise ValueError(\"Could not find feature with name {} in data list: {}.\".format(feature, str(l)))\n\ndef _get_matrix_from_features(data, features, n_target_components):\n # TODO:\n all_data = []\n for data_point in data:\n concated = np.array([_get_feature_from_list(data_point['params'],feature) for feature in features])\n all_data.append(concated)\n\n X = np.vstack(all_data)\n projected = False\n if n_target_components < len(features):\n pca = PCA(n_components=n_target_components)\n X = pca.fit(X).transform(X)\n projected = True\n\n return X, projected\n\n\nfrom mpl_toolkits.mplot3d.proj3d import proj_transform\nfrom matplotlib.text import Annotation\n\nclass Annotation3D(Annotation):\n '''Annotate the point xyz with text s\n\n From: https://stackoverflow.com/questions/10374930/matplotlib-annotating-a-3d-scatter-plot\n '''\n\n def __init__(self, s, xyz, *args, **kwargs):\n Annotation.__init__(self,s, xy=(0,0), *args, **kwargs)\n self._verts3d = xyz\n\n def draw(self, renderer):\n xs3d, ys3d, zs3d = self._verts3d\n xs, ys, zs = proj_transform(xs3d, ys3d, zs3d, renderer.M)\n self.xy=(xs,ys)\n Annotation.draw(self, renderer)\n\ndef annotate3D(ax, s, *args, **kwargs):\n '''add anotation text s to to Axes3d ax'''\n\n tag = Annotation3D(s, *args, **kwargs)\n ax.add_artist(tag)\n\ndef _get_results_with_name(data, name):\n # TODO:\n\n all_data = []\n for data_point in data:\n concated = np.array([_get_feature_from_list(data_point['results'], name)])\n all_data.append(concated)\n\n Y = np.vstack(all_data)\n\n return Y\n\ndef _null_aware_key_comparator(x):\n\n if x[\"start_time\"] is not None:\n return x[\"start_time\"]\n else:\n return 1\n\ndef main(arguments):\n\n parser = argparse.ArgumentParser(\n description=__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n parser.add_argument('data', type=argparse.FileType('rb'), help=\"Input file as a pickle in Orion format.\")\n parser.add_argument('--loss_interpolation_type', choices=[\"colour\", \"none\"], help=\"How to show the validation loss value if at all.\", default=\"colour\")\n parser.add_argument('--evaluation_metric', help=\"The evaluation metric to use for showing performance of features.\")\n parser.add_argument('--title', default=None, help=\"How would you like to title your plot?\")\n parser.add_argument('--save', action=\"store_true\", default=False, help=\"Save the plot?\")\n parser.add_argument('--fig_size', default=[16,8], nargs=\"+\", help=\"The size of the figure\", type=int)\n parser.add_argument('--best_percent_filter', type=float, default=100.0, help=\"Take only the top 25% of samples according to the evaluation_metric. If negative takes the bottom percent.\")\n parser.add_argument('--lower_better', action=\"store_true\", default=False, help=\"Inverse the colour if lower is better for the evaluation_metric\")\n args = parser.parse_args(arguments)\n print(args)\n\n data = pickle.load(args.data, encoding='bytes')\n data2 = sorted(data, key=_null_aware_key_comparator)\n data = data2\n\n fig = plt.figure(figsize=args.fig_size)\n\n ax = fig.gca()\n\n if args.evaluation_metric:\n Y = _get_results_with_name(data, args.evaluation_metric)\n if args.best_percent_filter < 100.0:\n percentile = np.percentile(Y, np.abs(args.best_percent_filter))\n if args.best_percent_filter < 0:\n Y2 = Y[Y[:,0]<=percentile]\n Y = Y2\n else:\n Y2 = Y[Y[:,0]>=percentile]\n Y = Y2\n\n if args.loss_interpolation_type == \"colour\":\n if args.lower_better:\n cm = plt.cm.get_cmap('RdYlBu')\n else:\n cm = plt.cm.get_cmap('RdYlBu_r')\n cmap=cm\n normalize = matplotlib.colors.Normalize(vmin=np.min(Y), vmax=np.max(Y))\n\n sc = plt.scatter(np.arange(len(Y)), Y.reshape(-1), c=Y.reshape(-1), s=50, alpha=.7, norm=normalize, lw = 0, cmap=cm)\n\n clbar = plt.colorbar(sc)\n\n clbar.set_label(args.evaluation_metric.replace(\"_\", \" \"))\n else:\n sc = plt.scatter(X[:,0], X[:, 1], color=\"teal\", s=50, alpha=.5, lw = 0)\n\n plt.xlabel(\"Trials\")\n plt.ylabel(args.evaluation_metric.replace(\"_\", \" \"))\n ax.autoscale(enable=True, tight=True)\n if args.title:\n plt.title(args.title)\n\n if args.save:\n unique_filename = str(uuid.uuid4())\n fig.savefig(\"{}.pdf\".format(unique_filename), dpi=fig.dpi, bbox_inches='tight')\n print(\"Saved to: {}.pdf\".format(unique_filename))\n else:\n plt.show()\n\n\nif __name__ == '__main__':\n sys.exit(main(sys.argv[1:]))\n\n# 2. specify size of points based on loss\n# ~30min\n# 3. heatmap\n# ~30 min\n# 4. create order labels on heatmap\n# ~30 min\n# 4. script to plot loss against hyperparameter or loss based on resource time with each line being a hyperparameter configuration\n # ~1hr\n# 5. make tree thing\n# convert pbt data to orion format and infer parents by closest possible parent where possible parents are determined by timestamp\n# 2-3hrs\n\n#\n# Script 1\n#\n# Arguments:\n# features : features to use\n# pca : if >2 features can project them into 2d plane\n# dimensions: 2D or 3d projection\n# loss_interpolation : [\"colour\", \"pointsize\" , None] depending how want to indicate better or worse loss\n# interpolate_phylo : interpolate a phylogentic connection if one is not provided (TODO: might be good to get data points to include ancestor references)\n#\n# # possibly just move to another script\n# heatmap: draw a heatmap instead of points\n# heatmap_points: include point labels with heatmap [\"order\", \"x\", None]\n#\n#\n# Script 2\n#\n# Dynamic resource, fig 1b of the Hyperband thing\n#\n# # options, wall clock time or timesteps/checkpoints. validation, train or test loss\n#\n#\n# Data\n#\n# Possibly generate some data to match pbt graphs from here in orion format: https://github.com/bkj/pbt\n","sub_path":"feature_viz/lossovertime.py","file_name":"lossovertime.py","file_ext":"py","file_size_in_byte":6956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"160402370","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\n\nimport copy\nimport json\nimport logging\nimport warnings\nfrom collections import defaultdict\n\nfrom six.moves.urllib.parse import urljoin\nfrom six.moves.http_cookiejar import CookieJar\n\nimport scrapy\nfrom scrapy.exceptions import NotConfigured\nfrom scrapy.http.headers import Headers\nfrom scrapy.http.response.text import TextResponse\nfrom scrapy import signals\n\nfrom scrapy_prerender.responsetypes import responsetypes\nfrom scrapy_prerender.cookies import jar_to_har, har_to_jar\nfrom scrapy_prerender.utils import (\n scrapy_headers_to_unicode_dict,\n json_based_hash,\n parse_x_prerender_saved_arguments_header,\n)\nfrom scrapy_prerender.response import get_prerender_status, get_prerender_headers\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass SlotPolicy(object):\n PER_DOMAIN = 'per_domain'\n SINGLE_SLOT = 'single_slot'\n SCRAPY_DEFAULT = 'scrapy_default'\n\n _known = {PER_DOMAIN, SINGLE_SLOT, SCRAPY_DEFAULT}\n\n\nclass PrerenderCookiesMiddleware(object):\n \"\"\"\n This downloader middleware maintains cookiejars for Prerender requests.\n\n It gets cookies from 'cookies' field in Prerender JSON responses\n and sends current cookies in 'cookies' JSON POST argument instead of\n sending them in http headers.\n\n It should process requests before PrerenderMiddleware, and process responses\n after PrerenderMiddleware.\n \"\"\"\n def __init__(self, debug=False):\n self.jars = defaultdict(CookieJar)\n self.debug = debug\n\n @classmethod\n def from_crawler(cls, crawler):\n return cls(debug=crawler.settings.getbool('PRERENDER_COOKIES_DEBUG'))\n\n def process_request(self, request, spider):\n \"\"\"\n For Prerender requests add 'cookies' key with current\n cookies to ``request.meta['prerender']['args']`` and remove cookie\n headers sent to Prerender itself.\n \"\"\"\n if 'prerender' not in request.meta:\n return\n\n if request.meta.get('_prerender_processed'):\n request.headers.pop('Cookie', None)\n return\n\n prerender_options = request.meta['prerender']\n\n prerender_args = prerender_options.setdefault('args', {})\n if 'cookies' in prerender_args: # cookies already set\n return\n\n if 'session_id' not in prerender_options:\n return\n\n jar = self.jars[prerender_options['session_id']]\n\n cookies = self._get_request_cookies(request)\n har_to_jar(jar, cookies)\n\n prerender_args['cookies'] = jar_to_har(jar)\n self._debug_cookie(request, spider)\n\n def process_response(self, request, response, spider):\n \"\"\"\n For Prerender JSON responses add all cookies from\n 'cookies' in a response to the cookiejar.\n \"\"\"\n from scrapy_prerender import PrerenderJsonResponse\n if not isinstance(response, PrerenderJsonResponse):\n return response\n\n if 'cookies' not in response.data:\n return response\n\n if 'prerender' not in request.meta:\n return response\n\n if not request.meta.get('_prerender_processed'):\n warnings.warn(\"PrerenderCookiesMiddleware requires PrerenderMiddleware\")\n return response\n\n prerender_options = request.meta['prerender']\n session_id = prerender_options.get('new_session_id',\n prerender_options.get('session_id'))\n if session_id is None:\n return response\n\n jar = self.jars[session_id]\n request_cookies = prerender_options['args'].get('cookies', [])\n har_to_jar(jar, response.data['cookies'], request_cookies)\n self._debug_set_cookie(response, spider)\n response.cookiejar = jar\n return response\n\n def _get_request_cookies(self, request):\n if isinstance(request.cookies, dict):\n return [\n {'name': k, 'value': v} for k, v in request.cookies.items()\n ]\n return request.cookies or []\n\n def _debug_cookie(self, request, spider):\n if self.debug:\n cl = request.meta['prerender']['args']['cookies']\n if cl:\n cookies = '\\n'.join(\n 'Cookie: {}'.format(self._har_repr(c)) for c in cl)\n msg = 'Sending cookies to: {}\\n{}'.format(request, cookies)\n logger.debug(msg, extra={'spider': spider})\n\n def _debug_set_cookie(self, response, spider):\n if self.debug:\n cl = response.data['cookies']\n if cl:\n cookies = '\\n'.join(\n 'Set-Cookie: {}'.format(self._har_repr(c)) for c in cl)\n msg = 'Received cookies from: {}\\n{}'.format(response, cookies)\n logger.debug(msg, extra={'spider': spider})\n\n @staticmethod\n def _har_repr(har_cookie):\n return '{}={}'.format(har_cookie['name'], har_cookie['value'])\n\n\nclass PrerenderDeduplicateArgsMiddleware(object):\n \"\"\"\n Spider middleware which allows not to store duplicate Prerender argument\n values in request queue. It works together with PrerenderMiddleware downloader\n middleware.\n \"\"\"\n local_values_key = '_prerender_local_values'\n\n def process_spider_output(self, response, result, spider):\n for el in result:\n if isinstance(el, scrapy.Request):\n yield self._process_request(el, spider)\n else:\n yield el\n\n def process_start_requests(self, start_requests, spider):\n if not hasattr(spider, 'state'):\n spider.state = {}\n spider.state.setdefault(self.local_values_key, {}) # fingerprint => value dict\n\n for req in start_requests:\n yield self._process_request(req, spider)\n\n def _process_request(self, request, spider):\n \"\"\"\n Replace requested meta['prerender']['args'] values with their fingerprints.\n This allows to store values only once in request queue, which helps\n with disk queue size.\n\n Downloader middleware should restore the values from fingerprints.\n \"\"\"\n if 'prerender' not in request.meta:\n return request\n\n if '_replaced_args' in request.meta['prerender']:\n # don't process re-scheduled requests\n # XXX: does it work as expected?\n warnings.warn(\"Unexpected request.meta['prerender']['_replaced_args']\")\n return request\n\n request.meta['prerender']['_replaced_args'] = []\n cache_args = request.meta['prerender'].get('cache_args', [])\n args = request.meta['prerender'].setdefault('args', {})\n\n for name in cache_args:\n if name not in args:\n continue\n value = args[name]\n fp = 'LOCAL+' + json_based_hash(value)\n spider.state[self.local_values_key][fp] = value\n args[name] = fp\n request.meta['prerender']['_replaced_args'].append(name)\n\n return request\n\n\nclass PrerenderMiddleware(object):\n \"\"\"\n Scrapy downloader and spider middleware that passes requests\n through Prerender when 'prerender' Request.meta key is set.\n\n This middleware also works together with PrerenderDeduplicateArgsMiddleware\n spider middleware to allow not to store duplicate Prerender argument values\n in request queue and not to send them multiple times to Prerender\n (the latter requires Prerender 2.1+).\n \"\"\"\n default_prerender_url = 'http://127.0.0.1:8050'\n default_endpoint = \"render.json\"\n prerender_extra_timeout = 5.0\n default_policy = SlotPolicy.PER_DOMAIN\n rescheduling_priority_adjust = +100\n retry_498_priority_adjust = +50\n remote_keys_key = '_prerender_remote_keys'\n\n def __init__(self, crawler, prerender_base_url, slot_policy, log_400):\n self.crawler = crawler\n self.prerender_base_url = prerender_base_url\n self.slot_policy = slot_policy\n self.log_400 = log_400\n self.crawler.signals.connect(self.spider_opened, signals.spider_opened)\n\n @classmethod\n def from_crawler(cls, crawler):\n prerender_base_url = crawler.settings.get('PRERENDER_URL',\n cls.default_prerender_url)\n log_400 = crawler.settings.getbool('PRERENDER_LOG_400', True)\n slot_policy = crawler.settings.get('PRERENDER_SLOT_POLICY',\n cls.default_policy)\n if slot_policy not in SlotPolicy._known:\n raise NotConfigured(\"Incorrect slot policy: %r\" % slot_policy)\n\n return cls(crawler, prerender_base_url, slot_policy, log_400)\n\n def spider_opened(self, spider):\n if not hasattr(spider, 'state'):\n spider.state = {}\n\n # local fingerprint => key returned by prerender\n spider.state.setdefault(self.remote_keys_key, {})\n\n @property\n def _argument_values(self):\n key = PrerenderDeduplicateArgsMiddleware.local_values_key\n return self.crawler.spider.state[key]\n\n @property\n def _remote_keys(self):\n return self.crawler.spider.state[self.remote_keys_key]\n\n def process_request(self, request, spider):\n if 'prerender' not in request.meta:\n return\n\n if request.method not in {'GET', 'POST'}:\n logger.warning(\n \"Currently only GET and POST requests are supported by \"\n \"PrerenderMiddleware; %(request)s will be handled without Prerender\",\n {'request': request},\n extra={'spider': spider}\n )\n return request\n\n if request.meta.get(\"_prerender_processed\"):\n # don't process the same request more than once\n return\n\n prerender_options = request.meta['prerender']\n request.meta['_prerender_processed'] = True\n\n slot_policy = prerender_options.get('slot_policy', self.slot_policy)\n self._set_download_slot(request, request.meta, slot_policy)\n\n args = prerender_options.setdefault('args', {})\n\n if '_replaced_args' in prerender_options:\n # restore arguments before sending request to the downloader\n load_args = {}\n save_args = []\n local_arg_fingerprints = {}\n for name in prerender_options['_replaced_args']:\n fp = args[name]\n # Use remote Prerender argument cache: if Prerender key\n # for a value is known then don't send the value to Prerender;\n # if it is unknown then try to save the value on server using\n # ``save_args``.\n if fp in self._remote_keys:\n load_args[name] = self._remote_keys[fp]\n del args[name]\n else:\n save_args.append(name)\n args[name] = self._argument_values[fp]\n\n local_arg_fingerprints[name] = fp\n\n if load_args:\n args['load_args'] = load_args\n if save_args:\n args['save_args'] = save_args\n prerender_options['_local_arg_fingerprints'] = local_arg_fingerprints\n\n del prerender_options['_replaced_args'] # ??\n\n args.setdefault('url', request.url)\n if request.method == 'POST':\n args.setdefault('http_method', request.method)\n # XXX: non-UTF8 request bodies are not supported now\n args.setdefault('body', request.body.decode('utf8'))\n\n if not prerender_options.get('dont_send_headers'):\n headers = scrapy_headers_to_unicode_dict(request.headers)\n if headers:\n args.setdefault('headers', headers)\n\n body = json.dumps(args, ensure_ascii=False, sort_keys=True, indent=4)\n # print(body)\n\n if 'timeout' in args:\n # User requested a Prerender timeout explicitly.\n #\n # We can't catch a case when user requested `download_timeout`\n # explicitly because a default value for `download_timeout`\n # is set by DownloadTimeoutMiddleware.\n #\n # As user requested Prerender timeout explicitly, we shouldn't change\n # it. Another reason not to change the requested Prerender timeout is\n # because it may cause a validation error on the remote end.\n #\n # But we can change Scrapy `download_timeout`: increase\n # it when it's too small. Decreasing `download_timeout` is not\n # safe.\n\n timeout_requested = float(args['timeout'])\n timeout_expected = timeout_requested + self.prerender_extra_timeout\n\n # no timeout means infinite timeout\n timeout_current = request.meta.get('download_timeout', 1e6)\n\n if timeout_expected > timeout_current:\n request.meta['download_timeout'] = timeout_expected\n\n endpoint = prerender_options.setdefault('endpoint', self.default_endpoint)\n prerender_base_url = prerender_options.get('prerender_url', self.prerender_base_url)\n prerender_url = urljoin(prerender_base_url, endpoint)\n\n headers = Headers({'Content-Type': 'application/json'})\n headers.update(prerender_options.get('prerender_headers', {}))\n new_request = request.replace(\n url=prerender_url,\n method='POST',\n body=body,\n headers=headers,\n priority=request.priority + self.rescheduling_priority_adjust\n )\n self.crawler.stats.inc_value('prerender/%s/request_count' % endpoint)\n return new_request\n\n def process_response(self, request, response, spider):\n if not request.meta.get(\"_prerender_processed\"):\n return response\n\n prerender_options = request.meta['prerender']\n if not prerender_options:\n return response\n\n # update stats\n endpoint = prerender_options['endpoint']\n self.crawler.stats.inc_value(\n 'prerender/%s/response_count/%s' % (endpoint, response.status)\n )\n\n # handle save_args/load_args\n self._process_x_prerender_saved_arguments(request, response)\n if get_prerender_status(response) == 498:\n logger.debug(\"Got HTTP 498 response for {}; \"\n \"sending arguments again.\".format(request),\n extra={'spider': spider})\n return self._498_retry_request(request, response)\n\n if prerender_options.get('dont_process_response', False):\n return response\n\n response = self._change_response_class(request, response)\n\n if self.log_400 and get_prerender_status(response) == 400:\n self._log_400(request, response, spider)\n\n return response\n\n def _change_response_class(self, request, response):\n from scrapy_prerender import PrerenderResponse, PrerenderTextResponse\n if not isinstance(response, (PrerenderResponse, PrerenderTextResponse)):\n # create a custom Response subclass based on response Content-Type\n # XXX: usually request is assigned to response only when all\n # downloader middlewares are executed. Here it is set earlier.\n # Does it have any negative consequences?\n respcls = responsetypes.from_args(headers=response.headers)\n if isinstance(response, TextResponse) and respcls is PrerenderResponse:\n # Even if the headers say it's binary, it has already\n # been detected as a text response by scrapy (for example\n # because it was decoded successfully), so we should not\n # convert it to PrerenderResponse.\n respcls = PrerenderTextResponse\n response = response.replace(cls=respcls, request=request)\n return response\n\n def _log_400(self, request, response, spider):\n from scrapy_prerender import PrerenderJsonResponse\n if isinstance(response, PrerenderJsonResponse):\n logger.warning(\n \"Bad request to Prerender: %s\" % response.data,\n {'request': request},\n extra={'spider': spider}\n )\n\n def _process_x_prerender_saved_arguments(self, request, response):\n \"\"\" Keep track of arguments saved by Prerender. \"\"\"\n saved_args = get_prerender_headers(response).get(b'X-Prerender-Saved-Arguments')\n if not saved_args:\n return\n saved_args = parse_x_prerender_saved_arguments_header(saved_args)\n arg_fingerprints = request.meta['prerender']['_local_arg_fingerprints']\n for name, key in saved_args.items():\n fp = arg_fingerprints[name]\n self._remote_keys[fp] = key\n\n def _498_retry_request(self, request, response):\n \"\"\"\n Return a retry request for HTTP 498 responses. HTTP 498 means\n load_args are not present on server; client should retry the request\n with full argument values instead of their hashes.\n \"\"\"\n meta = copy.deepcopy(request.meta)\n local_arg_fingerprints = meta['prerender']['_local_arg_fingerprints']\n args = meta['prerender']['args']\n args.pop('load_args', None)\n args['save_args'] = list(local_arg_fingerprints.keys())\n\n for name, fp in local_arg_fingerprints.items():\n args[name] = self._argument_values[fp]\n # print('remote_keys before:', self._remote_keys)\n self._remote_keys.pop(fp, None)\n # print('remote_keys after:', self._remote_keys)\n\n body = json.dumps(args, ensure_ascii=False, sort_keys=True, indent=4)\n # print(body)\n request = request.replace(\n meta=meta,\n body=body,\n priority=request.priority+self.retry_498_priority_adjust\n )\n return request\n\n def _set_download_slot(self, request, meta, slot_policy):\n if slot_policy == SlotPolicy.PER_DOMAIN:\n # Use the same download slot to (sort of) respect download\n # delays and concurrency options.\n meta['download_slot'] = self._get_slot_key(request)\n\n elif slot_policy == SlotPolicy.SINGLE_SLOT:\n # Use a single slot for all Prerender requests\n meta['download_slot'] = '__prerender__'\n\n elif slot_policy == SlotPolicy.SCRAPY_DEFAULT:\n # Use standard Scrapy concurrency setup\n pass\n\n def _get_slot_key(self, request_or_response):\n return self.crawler.engine.downloader._get_slot_key(\n request_or_response, None\n )\n","sub_path":"scrapy_prerender/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":18593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"124032847","text":"import os\r\nimport requests\r\nurl = 'https://pic.ibaotu.com/00/51/34/88a888piCbRB.mp4'\r\nroot = \"D://Pythontestpath//\"\r\npath = root + \"getvedio.mp4\"\r\ntry:\r\n if not os.path.exists(root):\r\n os.mkdir(root)\r\n if not os.path.exists(path):\r\n r = requests.get(url, stream=True)\r\n with open(path,'wb') as f:\r\n for chunk in r.iter_content(chunk_size=1024 * 1024):\r\n if chunk:\r\n f.write(chunk)\r\n f.close()\r\n print (\"Success...\")\r\n else:\r\n print(\"File exists...\")\r\nexcept:\r\n print (\"Failed to get..\")\r\n","sub_path":"python基础笔记/爬取视频.py","file_name":"爬取视频.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"312023129","text":"file = open('PyBankOutput.txt', 'w')\n\nprint(\"Financial Analysis\")\nfile.write(\"Financial Analysis\\n\")\nprint(\"----------------------------------\")\nfile.write(\"----------------------------------\\n\")\n\nimport os\nimport csv\n\npybankcsv = 'C:/Users/jessi/Documents/GTATL201808DATA3-master/Homework/03-Python/Instructions/PyBank/Resources/budget_data.csv'\n \n \nwith open(pybankcsv, 'r') as csvfile:\n\n csvreader = csv.reader(csvfile, delimiter=',') \n \n csv_header = next(csvfile)\n \n pybankdata = list(csvreader)\n\n numbermonths = len(pybankdata)\n \n totalprofit = 0\n \n previousrow = None\n sumforaverage = 0\n changemonths = 0\n maxchange = 0\n minchange = 0\n maxchangemonth = 0\n minchangemonth = 0 \n \n for row in pybankdata:\n \n totalprofit += int(row[1])\n \n if previousrow != None:\n changemonths = int(row[1]) - previousrow\n previousrow = int(row[1])\n if changemonths > maxchange:\n maxchange = changemonths\n maxchangemonth = row[0]\n if changemonths < minchange:\n minchange = changemonths\n minchangemonth = row[0]\n \n sumforaverage += changemonths\n \n averagechange = (sumforaverage/(numbermonths - 1))\n roundedaveragechange = round(averagechange, 2)\n \n \n \n \n \n print(f\"Total Months: {numbermonths}\")\n file.write(f\"Total Months: {numbermonths}\\n\") \n print(f\"Total: ${totalprofit}\")\n file.write(f\"Total: ${totalprofit}\\n\")\n print(f\"Average Change: ${roundedaveragechange}\")\n file.write(f\"Average Change: ${roundedaveragechange}\\n\")\n print(f\"Greatest Increase in Profits: {maxchangemonth} (${maxchange})\")\n file.write(f\"Greatest Increase in Profits: {maxchangemonth} (${maxchange})\\n\")\n print(f\"Greatest Decrease in Profits: {minchangemonth} (${minchange})\")\n file.write(f\"Greatest Decrease in Profits: {minchangemonth} (${minchange})\\n\")\n \n \n ","sub_path":"PyBank/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"286370836","text":"# processfiles\n\nimport re\nimport frs_packages\nimport frs_releases\nimport frs_files\nimport config\nimport processdocs\nimport xhtml\nimport time\n\nFirstPart = \"\"\"\n

\n \n \n \n

\n

The files listed are provided for reference purposes only. These files were current when produced, but are no longer maintained and may be outdated. Persons with disabilities needing access to the information in these files may e-mail Application Support for assistance.

\n\"\"\"\n\nLastPart = \"\"\"\n

\n \n \n \n

\n\"\"\"\n\ndef get_files(group_id):\n\n Packages = frs_packages.GetFRSPackages(group_id)\n if Packages == None:\n print(\"No Packages for: \" + config.group_name)\n return\n\n htmlFiles = open('Files.html', 'w')\n htmlFiles.write(FirstPart)\n\n for Package in Packages:\n packagename = processdocs.MangleName(Package[2])\n htmlFiles.write(xhtml.xhtml_h2start(Package[2] + xhtml.xhtml_h2end()))\n\n Releases = frs_releases.GetFRSReleases(Package[0])\n\n if (Releases == None):\n print(\"No Releases for Package: \" + Package[2])\n # htmlFiles.write(xhtml.xhtml_ulend())\n continue\n\n for Release in Releases:\n updateTime = Release[4]\n whenUpdated = time.localtime(updateTime)\n displayDate = time.strftime(\"Release Created: %b %d %Y %H:%M\", whenUpdated)\n\n releasename = processdocs.MangleName(Release[2])\n htmlFiles.write(xhtml.xhtml_h3start(Release[2]) + \" \" + displayDate + xhtml.xhtml_h3end())\n\n Files = frs_files.GetFRSFiles(Release[0])\n if (Files == None):\n print(\"No Files for Release: \" + Release[2])\n htmlFiles.write(xhtml.xhtml_ulend())\n continue\n\n htmlFiles.write(xhtml.xhtml_ul())\n for File in Files:\n filename = processdocs.MangleName(File[1])\n config.numberOfFiles += 1\n print(\"File name path = \" + \"files/\" + config.unix_group_name + \"/\" + packagename + \"/\" + releasename + \"/\" + filename)\n FullHTTPPathname = config.baseFiles + \"/\" + config.unix_group_name + \"/\" + packagename + \"/\" + releasename + \"/\" + filename\n htmlFiles.write(xhtml.xhtml_li(File[1], FullHTTPPathname, \" \"))\n\n htmlFiles.write(xhtml.xhtml_ulend())\n\n htmlFiles.write(LastPart)\n htmlFiles.close()\n\n return\n","sub_path":"processfiles.py","file_name":"processfiles.py","file_ext":"py","file_size_in_byte":2693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"616819100","text":"from abc import abstractmethod\n\n# import keyboard\nimport pygame\nfrom pyglet.window import key\n\nfrom Objects import *\nfrom action import *\n\n\"\"\"\nAll strategies shall implement the abstract class Strategy\n\nA strategy takes in an env state and returns an action\n\nNote that users cannot create new instances of some Strategies.\nThey use the CLASS OBJECT for operations\n\"\"\"\nclass Strategy:\n\n def __init__(self):\n self.move = Move(None) #None means there is no where move to, .resolve will do nothing\n self.auto_aim = True\n self.auto_shoot = False #TODO change for real robot\n self.auto_rotate = False\n\n def move_to(self, target_point, recompute, force_compute = False, backups = []):\n \"\"\"\n :param target_point: point to move to\n :param recompute: whether or not to immediately recalculate A* IF target_point changes,\n false -> keep following old path\n true && target changes-> find new path (does nothing if target_point is null)\n :param force_compute: if true, always recompute path, even if target_point is the same\n \"\"\"\n self.move.set_target_point(target_point, recompute, force_compute=force_compute, backups=backups)\n\n def force_path_recompute(self):\n self.move.path = None\n\n def stay_put(self):\n \"\"\"\n tells the move object to NOT move\n \"\"\"\n self.move_to(None, recompute=True)\n\n def substrat_decide(self, substrat, robot):\n temp = substrat.decide(robot)\n self.move = substrat.move\n return temp\n\n def set_substrat(self, substrat):\n substrat.move = self.move\n\n def decide_with_default(self, robot):\n action = self.decide(robot)\n enemy = robot.get_enemy()\n default = []\n #AUTO ROTATE\n if self.auto_aim:\n default.append(AutoAim(enemy))\n if self.auto_shoot:\n default.append(AutoShootingControl())\n if self.auto_rotate:\n default.append(AutoRotate(enemy, degrees_offset=45))\n if robot.shooting == True:\n default.append(Fire())\n if action:\n if type(action) == list:\n return default + action\n return default + [action]\n return default + [self.move]\n\n @abstractmethod\n def decide(self, robot):\n pass\n\n @classmethod\n def name(cls):\n return cls.__name__\n\n\nclass Patrol(Strategy):\n rhombus = [Point(80, 335), Point(410, 360), Point(720, 165), Point(390, 140)]\n top_line = [Point(600, 350), Point(250, 350)]\n right_line = [Point(750, 350), Point(750, 100)]\n lines = [rhombus, top_line, right_line]\n\n def __init__(self):\n Strategy.__init__(self)\n self.patrol_path = Patrol.rhombus # defualt\n self.pt_num = None\n\n def set_patrol_number(self, patrol_number):\n self.patrol_path = self.lines[patrol_number]\n\n def set_closest_pt_num(self, robot):\n self.pt_num = self.patrol_path.index(min(self.patrol_path, key=lambda x: robot.center.dis(x)))\n\n def decide(self, robot):\n if self.pt_num is None:\n self.set_closest_pt_num(robot)\n\n reorder = self.patrol_path[self.pt_num:]+self.patrol_path[:self.pt_num]\n for pt in reorder:\n if robot.center.float_equals(pt):\n self.pt_num = (self.patrol_path.index(pt) + 1) % len(self.patrol_path)\n\n self.move_to(self.patrol_path[self.pt_num], recompute=True,\n backups=self.patrol_path[self.pt_num+1:]+self.patrol_path[:self.pt_num])\n\n\nclass DoNothing(Strategy):\n\n def decide(self, robot):\n return None\n\n\nclass BreakLine(Strategy):\n\n def __init__(self):\n Strategy.__init__(self)\n self.additional_key_points = []\n\n def decide(self, robot):\n enemy = robot.get_enemy()\n if robot.center.dis(enemy.center) > robot.range or \\\n robot.env.is_blocked(LineSegment(robot.center, enemy.center), [robot, enemy]):\n # print('blocked!')\n return None\n else:\n # print('not blocked!')\n search_pts = sorted(robot.env.network_points + self.additional_key_points, key=lambda x: robot.center.dis(x))\n for i in search_pts:\n if robot.env.is_blocked(LineSegment(enemy.center, i), [robot, enemy]):\n loader = robot.team.loading_zone\n self.move_to(i, recompute=True)\n return None\n\n\nclass SpinAndFire(Strategy):\n\n def decide(self, robot):\n self.auto_rotate = False\n return RotateRight(robot.max_rotation_speed)\n\n\nclass Chase(Strategy):\n\n def __init__(self):\n Strategy.__init__(self)\n self.target_robot = None\n\n def choose_target_robot(self, target_robot):\n self.target_robot = target_robot\n\n def decide(self, robot):\n if self.target_robot is None:\n self.choose_target_robot(robot.get_enemy())\n if robot.center.dis(self.target_robot.center) > robot.range or \\\n robot.env.is_blocked(LineSegment(robot.get_gun_base(), self.target_robot.center), ignore=[robot, self.target_robot]):\n self.move_to(self.target_robot.center, False) # don't need an immediate recompute for chasing\n return None\n if float_equals(robot.angle_to(self.target_robot.center), robot.angle + robot.gun_angle):\n self.stay_put()\n return None\n return [Aim(self.target_robot.center)]\n\n\nclass OnlyReload(Strategy):\n\n def decide(self, robot):\n loader = robot.team.loading_zone\n if loader.aligned(robot):\n if loader.loading():\n return None\n if robot.bullet < robot.bullet_capacity and loader.fills > 0:\n return RefillCommand()\n else:\n return self.move_to(loader.loading_point, recompute=False)\n\n\nclass GetDefenseBuff(Strategy):\n\n def decide(self, robot):\n buff_pts = [z.center for z in robot.env.defense_buff_zones]\n buff_pts = sorted(buff_pts, key=lambda x: robot.center.dis(x))\n return self.move_to(buff_pts[0], recompute=True, backups = [buff_pts[1]])\n\n\nclass Attack(Strategy):\n\n def __init__(self):\n Strategy.__init__(self)\n self.chase_sub_strat = Chase()\n self.set_substrat(self.chase_sub_strat)\n self.chase_sub_strat.move.print_bool = True #TODO REMOVE\n\n def decide(self, robot):\n enemy = robot.get_enemy()\n loader = robot.team.loading_zone\n if loader.aligned(robot):\n if loader.loading():\n return None\n if robot.bullet < robot.bullet_capacity - 100 and loader.fills > 0:\n return RefillCommand()\n if robot.bullet > 0:\n self.chase_sub_strat.choose_target_robot(enemy)\n # return Chase(enemy).decide(robot)\n return self.substrat_decide(self.chase_sub_strat, robot)\n else:\n return self.move_to(loader.loading_point, recompute=True)\n # return Move(loader.loading_point)\n\n\nclass RosListen(Strategy):\n\n def decide(self, robot):\n return self.move_to(robot.env.ros_goal_point, recompute=False)\n\n\nclass AttackWithR(Strategy):\n pass\n\n\n# class KeyboardPyglet(Strategy):\n#\n# def __init__(self, controls, ignore_angle):\n# Strategy.__init__(self)\n# self.controls = controls\n# [self.left, self.down, self.right, self.up, self.turnleft, self.turnright,\n# self.refill] = controls\n# self.shooting = False\n# self.ignore_angle = ignore_angle\n#\n# def decide(self, robot):\n# board_ang = 90\n# if not robot.env.rendering:\n# return\n# window = robot.env.viewer.window\n# actions = []\n#\n# @window.event\n# def on_key_press(symbol, modifier):\n# if symbol == key.R:\n# if robot.team.loading_zone.aligned(robot):\n# RefillCommand().resolve(robot)\n# else:\n# Move(robot.team.loading_zone.center).resolve(robot)\n#\n# if keyboard.is_pressed(self.turnleft):\n# actions.append(RotateLeft(robot.max_rotation_speed))\n# if keyboard.is_pressed(self.turnright):\n# actions.append(RotateRight(robot.max_rotation_speed))\n# if keyboard.is_pressed(self.up):\n# actions.append(MoveForward(board_ang if self.ignore_angle else robot.angle, robot.max_speed))\n# if keyboard.is_pressed(self.down):\n# actions.append(MoveBackward(board_ang if self.ignore_angle else robot.angle, robot.max_speed))\n# if keyboard.is_pressed(self.left):\n# actions.append(MoveLeft(board_ang if self.ignore_angle else robot.angle, robot.max_speed))\n# if keyboard.is_pressed(self.right):\n# actions.append(MoveRight(board_ang if self.ignore_angle else robot.angle, robot.max_speed))\n# return actions\n\n\n# class KeyboardPygame(Strategy):\n#\n# def __init__(self, controls, ignore_angle):\n# Strategy.__init__(self)\n# [self.left, self.down, self.right, self.up, self.turnleft, self.turnright, \\\n# self.refill] = controls\n# self.actions = []\n# self.refilling = False\n# self.ignore_angle = ignore_angle\n#\n# def set_instructions(self, actions):\n# self.actions = actions\n# if self.refilling and self.refill not in actions:\n# self.refilling = False\n#\n# def decide(self, robot):\n# board_ang = 90\n# if not self.actions:\n# return None\n# actions = []\n# if self.turnleft in self.actions:\n# actions.append(RotateLeft(robot.max_rotation_speed))\n# if self.turnright in self.actions:\n# actions.append(RotateRight(robot.max_rotation_speed))\n# if self.up in self.actions:\n# actions.append(MoveForward(board_ang if self.ignore_angle else robot.angle, robot.max_speed))\n# if self.down in self.actions:\n# actions.append(MoveBackward(board_ang if self.ignore_angle else robot.angle, robot.max_speed))\n# if self.left in self.actions:\n# actions.append(MoveLeft(board_ang if self.ignore_angle else robot.angle, robot.max_speed))\n# if self.right in self.actions:\n# actions.append(MoveRight(board_ang if self.ignore_angle else robot.angle, robot.max_speed))\n# if self.refill in self.actions:\n# if not self.refilling:\n# self.refilling = True\n# actions.append(RefillCommand())\n# return actions\n\nclass Joystick(Strategy):\n\n refilled = False\n\n def decide(self, robot):\n j = pygame.joystick.Joystick(0)\n j.init()\n coords = [j.get_axis(0), j.get_axis(1), j.get_axis(3)]\n hat = j.get_hat(0)\n\n if not any(hat):\n self.refilled = False\n\n for i in range(len(coords)):\n if float_equals(coords[i], 0, 0.05):\n coords[i] = 0\n if not any(coords) and not any(hat):\n return None\n\n [right, down, clockwise] = coords\n translation_power, rotation_power = max(abs(right), abs(down)), abs(clockwise)\n\n if translation_power:\n translation_weight = translation_power / (translation_power + rotation_power)\n rotation_weight = 1 - translation_weight\n helper_weight = (right ** 2 + down ** 2) ** 0.5\n right_weight, down_weight = right / helper_weight, down / helper_weight\n else:\n rotation_weight = 1\n\n actions = []\n if right:\n actions.append(MoveRight(robot.angle, robot.max_speed * translation_weight * translation_power * right_weight))\n if down:\n actions.append(MoveBackward(robot.angle, robot.max_speed * translation_weight * translation_power * down_weight))\n if clockwise:\n actions.append(RotateRight(robot.max_rotation_speed * rotation_weight * clockwise))\n if any(hat) and not self.refilled:\n self.refilled = True\n actions.append(RefillCommand())\n\n # translation_angle = (Point(0, 0).angle_to(Point(right, -down)) - 90) % 360\n # print(translation_angle)\n # action = MoveAtAngle(robot.angle, robot.max_speed * translation_weight * translation_power, translation_angle)\n return actions\n","sub_path":"scripts/strategy.py","file_name":"strategy.py","file_ext":"py","file_size_in_byte":12394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"621042054","text":"fig, ax = plt.subplots()\nax.loglog(range(1, 360, 5), range(1, 360, 5))\nax.set_xlabel('frequency [Hz]')\n\ndef invert(x):\n # 1/x with special treatment of x == 0\n x = np.array(x).astype(float)\n near_zero = np.isclose(x, 0)\n x[near_zero] = np.inf\n x[~near_zero] = 1 / x[~near_zero]\n return x\n\n# the inverse of 1/x is itself\nsecax = ax.secondary_xaxis('top', functions=(invert, invert))\nsecax.set_xlabel('Period [s]')\nplt.show()","sub_path":"3.6.0/api/_as_gen/matplotlib-axes-Axes-secondary_xaxis-1.py","file_name":"matplotlib-axes-Axes-secondary_xaxis-1.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"59735220","text":"import pygame, sys, math\n\nclass SlowTime():\n def __init__(self, pos = (0,0)):\n self.type = \"slow time\"\n self.image = pygame.image.load(\"Images/Slow_Time.png\")\n self.rect = self.image.get_rect()\n self.radius = self.rect.width/2\n self.place(pos)\n self.living = True\n self.timer = 60*7\n \n def place(self, pos):\n self.rect.center = pos\n \n def update(self):\n if self.timer > 0:\n self.timer -= 1\n else:\n self.living = False","sub_path":"Slow_Time.py","file_name":"Slow_Time.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"370879785","text":"# -*- coding: utf-8 -*-\n\"\"\"\n Command line entry point.\n\"\"\"\n\nimport os\nimport sys\nimport argparse\n\nfrom .core import Anvil\nfrom .version import get_version\n\nclass Cli(object):\n \"\"\"\n A command line interface backed by an ArgumentParser delegate.\n \"\"\"\n COMMAND_NAME = 'anvil'\n\n def __init__(self, argument_parser=None):\n \"\"\"\n Constructs an interface by registering subcommand parsers to the\n given ArgumentParser.\n :param argument_parser: `ArgumentParser \n `_ that\n arguments and subcommands should be bound to.\n \"\"\"\n self._parser = argument_parser\n self.initArgs()\n self.initSubparsers()\n\n def initArgs(self):\n self._parser.add_argument(\n '--version',\n action='version',\n help='show version information',\n version='{} version {}'.format(Cli.COMMAND_NAME, get_version()))\n\n def initSubparsers(self):\n \"\"\"\n Registers init and version subcommands.\n \"\"\"\n subparsers = self._parser.add_subparsers(\n title='Available subcommands',\n description=None,\n # disable showing subcommands as {cmd1, cmd2, etc}\n metavar='')\n\n # create parser for 'init' subcommand.\n init_parser = subparsers.add_parser(\n 'init', \n help='initialize structure from a template')\n init_parser.add_argument(\n 'input_path', \n help='input template project (e.g. github.com/user/flask-app)')\n init_parser.add_argument(\n 'output_path',\n nargs='?',\n default=os.getcwd(),\n help=('relative path where the generated project should placed'\n '(default: current directory)'))\n init_parser.set_defaults(func=init)\n\n # create parser for 'version' subcommand\n version_parser = subparsers.add_parser(\n 'version',\n help='show version information')\n version_parser.set_defaults(func=version, \n command_name=Cli.COMMAND_NAME)\n\n def __getattr__(self, attr):\n \"\"\"Delegate parse_args(), print_help(), etc.\"\"\"\n return getattr(self._parser, attr)\n\n\nclass AlphabeticalHelpFormatter(argparse.HelpFormatter):\n \"\"\"\n ArgumentParser HelpFormatter, which alphabetizes optional parser \n arguments.\n \"\"\"\n # based on http://stackoverflow.com/questions/12268602\n def add_arguments(self, actions):\n actions = sorted(actions, key=lambda a: a.option_strings)\n super(AlphabeticalHelpFormatter, self).add_arguments(actions)\n\ndef get_command_interface():\n \"\"\"\n Returns a new Cli command line interface.\n \"\"\"\n parser = argparse.ArgumentParser(\n description='Generates project structures from Jinja templates',\n epilog='For subcomamnd help, run `{} -h`'\n .format(Cli.COMMAND_NAME),\n formatter_class=AlphabeticalHelpFormatter)\n return Cli(parser)\n\n\n# Adapter interfaces to command line interface\n\ndef init(namespace):\n \"\"\"\n Command line adapter for creating an Anvil object and invoking\n interactive generation of a new project.\n :param argparse.Namespace namespace: namespace object with \n input_path and output_path attributes, which may be absolute\n paths or paths relative to the current directory\n \"\"\"\n input_path = os.path.abspath(namespace.input_path)\n output_path = os.path.abspath(namespace.output_path)\n anvil = Anvil(input_path, output_path)\n anvil.interactive_generate()\n\ndef version(namespace):\n \"\"\"\n Command line adapter for displaying the version of the Anvil tool.\n :param argparse.Namespace namespace: namespace object with the\n command line interface command_name attribute\n \"\"\"\n version_string='{} version {}'.format(namespace.command_name,\n get_version())\n exit(version_string)\n\n\ndef parse_args(cli, args):\n \"\"\"\n Parses command line arguments and executes the chosen subcommand.\n :param cli: Cli command line interface object\n :param args: list of command line arguments (e.g. sys.argv)\n \"\"\"\n # namespace of arguments and chosen subcommand 'func'\n namespace = cli.parse_args(args)\n # execute the chosen subcommand function\n namespace.func(namespace)\n\n\ndef main():\n \"\"\"\n Creates the command line interface, prints help if no subcommand was\n selected, parses arguments and executes the chosen subcommand.\n \"\"\"\n cli = get_command_interface()\n # If no arguments besides the command name (always passed), show the help\n # interface and exit.\n if len(sys.argv) == 1:\n sys.exit(cli.print_help())\n parse_args(cli, sys.argv[1:])\n\n \n","sub_path":"anvil/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":4774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"12339584","text":"\"\"\"\n\nUsage: dl_vid.py ... [--output]\n\nOptions:\n -o --output Location were downloaded videos will go\n\n\"\"\"\nimport os\nfrom docopt import docopt\nimport requests\nfrom threading import Thread\nfrom humanize import naturalsize\n\ndef download(url, save_as):\n filename = save_as.rsplit('/', 1)[-1]\n stream = requests.get(url, stream=True)\n total_bytes = int(stream.headers['content-length'])\n human_size, unit = naturalsize(total_bytes).split()\n\n print('Downloading {vidname} - [{size} {unit}]'.format(vidname=filename, size=human_size, unit=unit))\n\n with open(save_as, 'wb') as f:\n [f.write(chunk) for chunk in stream.iter_content(chunk_size=255) if chunk]\n\n print('{} complete'.format(filename))\n\ndef main(argv):\n root_dir = save_path = os.path.dirname(os.path.realpath(__file__))\n if argv['--output']: save_path = argv['--output']\n\n for i,url in enumerate(argv['']):\n save_as = '{path}/{vid_name}'.format(path=save_path, vid_name=i)\n \n ext = url.rsplit('.', 1)[-1]\n if ext != url: save_as += '.' + ext\n \n Thread(target=download, args=(url, save_as)).start()\n\nif __name__ == '__main__':\n args = docopt(__doc__)\n main(args)","sub_path":"dl_vid.py","file_name":"dl_vid.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"232053382","text":"import tensorflow as tf\nimport time\nimport os \nimport sys\nimport model_nature as model \n \nbase = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(os.path.join(base,'../../'))\n\nimport datasets.Img2ImgPipeLine as train_dataset\n\nphysical_devices = tf.config.experimental.list_physical_devices(device_type='GPU')\ntf.config.experimental.set_memory_growth(physical_devices[0], True)\n\nfrom tensorflow.keras.mixed_precision import experimental as mixed_precision\npolicy = mixed_precision.Policy('mixed_float16')\nmixed_precision.set_policy(policy)\n\n######################################################################################################\n\n\ntrain_path_A = \"G:\\\\Datasets\\\\Img2Img\\\\horse2zebra\\\\trainA\"\ntrain_path_B = \"G:\\\\Datasets\\\\Img2Img\\\\horse2zebra\\\\trainB\"\n# test_path_A = \"G:\\\\Datasets\\\\Img2Img\\\\horse2zebra\\\\testA\"\n# test_path_B = \"G:\\\\Datasets\\\\Img2Img\\\\horse2zebra\\\\testB\"\ntest_path_A = \"G:\\\\Datasets\\\\Img2Img\\\\horse2zebra\\\\trainA\"\ntest_path_B = \"G:\\\\Datasets\\\\Img2Img\\\\horse2zebra\\\\trainB\"\ntmp_path = \"D:/Work/Codes_tmp/2DCycleGAN-mixed-horse2zebra\"\nout_path = \"D:/Work/Codes_tmp/2DCycleGAN-mixed-horse2zebra/out\"\n\nif not os.path.exists(tmp_path):\n os.makedirs(tmp_path)\nif not os.path.exists(out_path):\n os.makedirs(out_path)\ndef map_func(x):\n # x shape = [batch,2,256,256,3]\n #必须归一化 对应于网络的tanh 但是暂时不知道用什么像素标准去归一化 可能需要遍历所有的值\n A = tf.reshape(x[:,0,:,:,:],[1,256,256,3], name=None)\n A = (A-0.0)/1\n B = tf.reshape(x[:,1,:,:,:],[1,256,256,3], name=None)\n B = (B-0.0)/1\n return A,B\n\nEPOCHES = 200\nBATCH_SIZE = 1\n\n\nnum_threads = 4\ndataset = train_dataset.DataPipeLine(train_path_A,train_path_B)\ndataset = tf.data.Dataset.from_generator(dataset.generator,output_types=tf.float32)\\\n .batch(BATCH_SIZE)\\\n .map(map_func,num_parallel_calls=num_threads)\\\n .prefetch(buffer_size = tf.data.experimental.AUTOTUNE)\n\ntest_set = train_dataset.DataPipeLine(test_path_A,test_path_B)\ntest_set = tf.data.Dataset.from_generator(test_set.generator,output_types=tf.float32)\\\n .batch(BATCH_SIZE)\\\n .map(map_func,num_parallel_calls=num_threads)\\\n .prefetch(buffer_size = tf.data.experimental.AUTOTUNE)\n\n\nmodel = model.CycleGAN(train_set=dataset,\n test_set=test_set,\n loss_name=\"LSGAN\",\n mixed_precision=True,\n learning_rate=2e-4,\n tmp_path=tmp_path,\n out_path=out_path)\nmodel.build(X_shape=[None,256,256,3],Y_shape=[None,256,256,3])\nmodel.test(take_nums=200)","sub_path":"implementations/CycleGAN_2D_nature/test_nature.py","file_name":"test_nature.py","file_ext":"py","file_size_in_byte":2658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"331920700","text":"#!/usr/bin/env python3\n\nimport sys\n\nfns = sys.argv[1:]\n\nERR_COP = 0 # copyright header\nERR_IMP = 1 # import statements\nERR_MOD = 2 # module docstring\nERR_LIN = 3 # line length\nERR_SAV = 4 # ᾰ\n\nexceptions = []\n\nwith open(\"scripts/copy-mod-doc-exceptions.txt\") as f:\n for line in f.readlines():\n fn, _, _, _, _, errno, *_ = line.split()\n if errno == \"ERR_COP\":\n exceptions += [(ERR_COP, fn)]\n if errno == \"ERR_IMP\":\n exceptions += [(ERR_IMP, fn)]\n if errno == \"ERR_MOD\":\n exceptions += [(ERR_MOD, fn)]\n if errno == \"ERR_LIN\":\n exceptions += [(ERR_LIN, fn)]\n if errno == \"ERR_SAV\":\n exceptions += [(ERR_SAV, fn)]\n\nnew_exceptions = False\n\ndef small_alpha_vrachy_check(lines, fn):\n return [ (ERR_SAV, line_nr, fn) for line_nr, line in enumerate(lines) if 'ᾰ' in line ]\n\ndef long_lines_check(lines, fn):\n errors = []\n for line_nr, line in enumerate(lines, 1):\n if \"http\" in line:\n continue\n if len(line) > 101:\n errors += [(ERR_LIN, line_nr, fn)]\n return errors\n\ndef import_only_check(lines, fn):\n import_only_file = True\n errors = []\n in_comment = False\n for line_nr, line in enumerate(lines, 1):\n if \"/-\" in line:\n in_comment = True\n if \"-/\" in line:\n in_comment = False\n continue\n if line == \"\\n\" or in_comment:\n continue\n imports = line.split()\n if imports[0] == \"--\":\n continue\n if imports[0] != \"import\":\n import_only_file = False\n break\n if len(imports) > 2:\n if imports[2] == \"--\":\n continue\n else:\n errors += [(ERR_IMP, line_nr, fn)]\n return (import_only_file, errors)\n\ndef regular_check(lines, fn):\n errors = []\n copy_started = False\n copy_done = False\n copy_start_line_nr = 0\n copy_lines = \"\"\n for line_nr, line in enumerate(lines, 1):\n if not copy_started and line == \"\\n\":\n errors += [(ERR_COP, copy_start_line_nr, fn)]\n continue\n if not copy_started and line == \"/-\\n\":\n copy_started = True\n copy_start_line_nr = line_nr\n continue\n if not copy_started:\n errors += [(ERR_COP, line_nr, fn)]\n if copy_started and not copy_done:\n copy_lines += line\n if line == \"-/\\n\":\n if ((not \"Copyright\" in copy_lines) or\n (not \"Apache\" in copy_lines) or\n (not \"Author\" in copy_lines)):\n errors += [(ERR_COP, copy_start_line_nr, fn)]\n copy_done = True\n continue\n if copy_done and line == \"\\n\":\n continue\n words = line.split()\n if words[0] != \"import\" and words[0] != \"/-!\":\n errors += [(ERR_MOD, line_nr, fn)]\n break\n if words[0] == \"/-!\":\n break\n # final case: words[0] == \"import\"\n if len(words) > 2:\n if words[2] != \"--\":\n errors += [(ERR_IMP, line_nr, fn)]\n return errors\n\ndef format_errors(errors):\n global new_exceptions\n for (errno, line_nr, fn) in errors:\n if (errno, fn) in exceptions:\n continue\n new_exceptions = True\n # filename first, then line so that we can call \"sort\" on the output\n if errno == ERR_COP:\n print(\"{} : line {} : ERR_COP : Malformed or missing copyright header\".format(fn, line_nr))\n if errno == ERR_IMP:\n print(\"{} : line {} : ERR_IMP : More than one file imported per line\".format(fn, line_nr))\n if errno == ERR_MOD:\n print(\"{} : line {} : ERR_MOD : Module docstring missing, or too late\".format(fn, line_nr))\n if errno == ERR_LIN:\n print(\"{} : line {} : ERR_LIN : Line has more than 100 characters\".format(fn, line_nr))\n if errno == ERR_SAV:\n print(\"{} : line {} : ERR_SAV : File contains the character ᾰ\".format(fn, line_nr))\n\ndef lint(fn):\n with open(fn) as f:\n lines = f.readlines()\n errs = long_lines_check(lines, fn)\n format_errors(errs)\n (b, errs) = import_only_check(lines, fn)\n if b:\n format_errors(errs)\n return\n errs = regular_check(lines, fn)\n format_errors(errs)\n\nfor fn in fns:\n lint(fn)\n\n# if \"exceptions\" is empty,\n# we're trying to generate copy-mod-doc-exceptions.txt,\n# so new exceptions are expected\nif new_exceptions and len(exceptions) > 0:\n exit(1)\n","sub_path":"scripts/lint-copy-mod-doc.py","file_name":"lint-copy-mod-doc.py","file_ext":"py","file_size_in_byte":4597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"550337970","text":"from scrapy.spiders import Spider\nfrom scrapy import Request\nfrom spider.items import TransactionItem,SentDetail\n# from scrapy import log\nfrom .value import page\n\n\n\n\n\nclass BittrexSpider(Spider):\n name = 'bittrex'\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36',\n }\n\n def start_requests(self):\n # url = 'https://www.walletexplorer.com/wallet/Bittrex.com'\n url = 'https://www.walletexplorer.com/wallet/Bittrex.com?page=2'\n yield Request(url)\n\n def parse(self, response):\n transactions = response.selector.xpath('//table[@class=\"txs\"]/tr[@class=\"received\" or @class=\"sent\"]')\n for transaction in transactions:\n item = TransactionItem()\n class_value = transaction.xpath('./@class').extract()[0]\n value = class_value\n dates = transaction.xpath('.//td[@class=\"date\"]/text()').extract()\n item['date'] = dates[0]\n item['balance'] = float(transaction.xpath('.//td[@class=\"amount\"]/text()').extract()[0].strip())\n item['txid'] = transaction.xpath('.//td[@class=\"txid\"]/a/@href').extract()[0][6:]\n item['exchange'] = 'bittrex'\n if value == 'received':\n try:\n item['received_from'] = transaction.xpath('.//td[@class=\"inout\"]/table/tr/td[@class=\"walletid\"]/a/@href').extract()[0][8:]\n except Exception:\n # item['received_from'] = transaction.xpath('.//td[@class=\"inout\"]/table/tr/td[@class=\"walletid\"]/b/text()').extract()[0]\n item['received_from'] = \"error\"\n item['received_amount'] = float(transaction.xpath('.//td[@class=\"inout\"]/table/tr/td[@class=\"amount diff\"]/text()').extract()[0][1:].strip())\n item['type'] = 0\n # item['sent_to'] = ' '\n item['sent_amount'] = 0\n\n yield item\n elif value == 'sent':\n item['type'] = 1\n item['received_amount'] = 0\n item['received_from'] = ' '\n # yield item\n senttos = transaction.xpath('.//table[@class=\"empty\"]/tr')\n total_amount = 0.0\n for sent in senttos:\n detail_item = SentDetail()\n detail_item['txid'] = item['txid']\n detail_item['exchange'] = 'bittrex'\n amount = sent.xpath('.//td[@class=\"amount diff\"]/text()').extract()\n if amount :\n walletid = sent.xpath('.//td[@class=\"walletid\"]')[1].xpath('.//a/@href').extract()[0][8:]\n detail_item['sent_to'] = walletid\n if amount[0].startswith('-'):\n single_amount = float(amount[0][1:])\n total_amount += single_amount\n detail_item['sent_amount'] = single_amount\n elif amount[0].startswith('0'):\n single_amount = float(amount[0].strip())\n total_amount += single_amount\n detail_item['sent_amount'] = single_amount\n else:\n detail_item['sent_to'] = 'fee'\n single_amount = float(sent.xpath('.//td[@class=\"amount diff\"]/em/text()').extract()[0].strip()[1:-1][1:])\n detail_item['sent_amount'] = single_amount\n total_amount += single_amount\n yield detail_item\n item['sent_amount'] = total_amount\n item['exchange'] = 'bittrex'\n yield item\n count = 1\n hrefs = response.xpath('.//div[@class=\"paging\"]/a[contains(text(), \"Next\")]/@href').extract()\n next_url = \"https://www.walletexplorer.com\" + hrefs[0]\n limit = next_url[-1]\n if int(limit) < page:\n yield Request(next_url)","sub_path":"spider/spider/spiders/BittrexSpider.py","file_name":"BittrexSpider.py","file_ext":"py","file_size_in_byte":4039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"167320540","text":"import os\nimport shutil\nimport unittest\nfrom src.util import path_util\n\n\nclass TestPathUtil(unittest.TestCase):\n playground_path = os.path.join(os.getcwd(), \"test_playground\", \"path_util\")\n module_name = path_util.__name__\n\n def test_formatted_ext(self):\n pairs = [\n ('file.png', 'png'),\n ('test/file.PNG', 'png'),\n ('test', '')\n ]\n for (input, expected) in pairs:\n output = path_util.get_formatted_ext(input)\n error_msg = f\"{self.module_name}.get_formatted_ext('{input}') returned '{output}'; expected '{expected}'\"\n assert output == expected, error_msg\n\n","sub_path":"tests/util/test_path_util.py","file_name":"test_path_util.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"526302463","text":"# coding=utf-8\n\nimport ast\nfrom src.asdl.asdl import *\nfrom src.asdl.lang.py.py_asdl_helper import *\nfrom src.asdl.lang.py3.py3_transition_system import *\nfrom src.asdl.hypothesis import *\nimport astor\n\nif __name__ == '__main__':\n # read in the grammar specification of Python 2.7, defined in ASDL\n asdl_text = open('py3_asdl.simplified.txt').read()\n grammar = ASDLGrammar.from_text(asdl_text)\n\n py_code = \"\"\"print()\\nprint(sum(row[column] for row in \n data))\\nlst = [Object() for _ in range(100)]\"\"\"\n\n # get the (domain-specific) python AST of the example Python code snippet\n py_ast = ast.parse(py_code)\n # print(astor.dump_tree(py_ast.body[2]))\n\n # convert the python AST into general-purpose ASDL AST used by tranX\n\n for batch_num, b in enumerate(py_ast.body):\n print('-' * 25)\n asdl_ast = python_ast_to_asdl_ast(b, grammar)\n print('String representation of the ASDL AST: \\n%s' % asdl_ast.to_string())\n print('Size of the AST: %d' % asdl_ast.size)\n\n # we can also convert the ASDL AST back into Python AST\n py_ast_reconstructed = asdl_ast_to_python_ast(asdl_ast, grammar)\n\n # initialize the Python transition parser\n parser = Python3TransitionSystem(grammar)\n\n # get the sequence of gold-standard actions to construct the ASDL AST\n actions = parser.get_actions(asdl_ast)\n\n # a hypothesis is an (partial) ASDL AST generated using a sequence of tree-construction\n # actions\n hypothesis = Hypothesis()\n if batch_num == 1:\n actions = [actions[0]] + actions[5:-2]\n elif batch_num ==2:\n pass\n for t, action in enumerate(actions, 1):\n\n # the type of the action should belong to one of the valid continuing types\n # of the transition system\n assert action.__class__ in parser.get_valid_continuation_types(hypothesis)\n\n # if it's an ApplyRule action, the production rule should belong to the\n # set of rules with the same LHS type as the current rule\n if isinstance(action, ApplyRuleAction) and hypothesis.frontier_node:\n assert action.production in grammar[hypothesis.frontier_field.type]\n\n p_t = hypothesis.frontier_node.created_time if hypothesis.frontier_node else -1\n print('t=%d, p_t=%d, Action=%s' % (t, p_t, action))\n hypothesis.apply_action(action)\n\n # get the surface code snippets from the original Python AST,\n # the reconstructed AST and the AST generated using actions\n # they should be the same\n src1 = astor.to_source(py_ast).strip()\n src2 = astor.to_source(py_ast_reconstructed).strip()\n src3 = astor.to_source(asdl_ast_to_python_ast(hypothesis.tree, grammar)).strip()\n print(src3)\n # assert src1 == src2 == src3 == py_code\n","sub_path":"src/asdl/lang/py3/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":2866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"365677353","text":"import os\nimport sys\nimport subprocess\nimport vs_pfm.path_const as pc \nimport tempfile\nimport errno\nimport distutils.spawn\nimport pickle \nimport gzip \n\n\n#def is_tool(name):\n# try:\n## devnull = open(os.devnull)\n## subprocess.Popen([name],stdout=devnull, stderr=devnull).communicate()\n# test = distutils.spawn.find_executable(name)\n# except OSError as e:\n# print(e)\n# if e.errno == errno.ENOENT:\n# return False\n# return True\n\ndef get_tool(name):\n executable = distutils.spawn.find_executable(name)\n if executable:\n return executable\n else:\n try:\n tool = eval('pc.' + name.split('.')[0].upper())\n except:\n tool = None\n raise ValueError('Cannot find ' + name)\n return tool \n\n\ndef convert_format(fname, fname_type, outname,outname_type,delH=False):\n '''\n use obabel to convert structure file format\n :param fname: file name\n :param fname_type: file type\n :param outname: output file name\n :param outname_type: output file format\n :return:\n '''\n #print(not get_tool('test'))\n if not get_tool('obabel'):\n print('obabel is not found!')\n sys.exit()\n\n \n f = open(outname,'w')\n if delH == False:\n subprocess.Popen(['obabel','-i'+fname_type, fname, '-o' + outname_type], stdout=f).communicate()\n else:\n subprocess.Popen (['obabel', '-d','-i' + fname_type, fname, '-o' + outname_type], stdout=f).communicate ( )\n f.close()\n\n\ndef format_convert_to_temp(fname,in_format,out_format):\n '''\n Generate temp file and store the converted format in temp file \n '''\n temp = tempfile.NamedTemporaryFile(delete=False)\n \n convert_format(fname,in_format,temp.name, out_format)\n return temp.name\n\n\ndef pickle_file(fname, obj):\n pickle.dump(obj=obj, file=gzip.open(fname, \"wb\", compresslevel=3), protocol =2)\n\n\ndef unpickle_file(fname):\n return pickle.load(gzip.open(fname, \"rb\"))","sub_path":"vs_pfm/general_functions.py","file_name":"general_functions.py","file_ext":"py","file_size_in_byte":1978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"160559216","text":"print(\"齐天大圣三打白骨精\")\nimport random\nclass a:\n def __init__(self, name):\n self.name = name\n self.lv = 1\n self.max_hp = 100\n self.now_hp = 100\n\n def attack(self):\n hurt = random.randint(0,self.lv*10-1)\n print(f'{self.name}进行攻击!')\n return hurt\n\n def upgrade(self):\n self.max_hp += 10\n self.now_hp = self.max_hp\n self.lv += 1\n print(f'{self.name}升级,当前等级{self.lv},当前生命值{self.now_hp}')\n\nclass Human(a):\n def __init__(self, name):\n super(Human, self).__init__(name)\n self.agile= 0.4\n\n def defense(self, hurt):\n is_hurt = random.random()\n if self.agile < is_hurt:\n self.now_hp -= hurt\n print(f'{self.name}受到{hurt}点伤害,当前生命值 {self.now_hp}')\n else:\n print(f'{self.name}躲避攻击!')\n print(f'{self.name}当前生命值 {self.now_hp}')\n\nclass Hero(a):\n def __init__(self, name):\n super(Hero, self).__init__(name)\n self.agile = 0.6\n\n def defense(self, hurt):\n is_hurt = random.random()\n if self.agile < is_hurt:\n self.now_hp -= hurt\n print(f'{self.name}受到{hurt}点伤害,当前生命值{self.now_hp}')\n else:\n print(f'{self.name}躲避攻击!')\n print(f'{self.name}当前生命值 {self.now_hp}')\n\nclass Monster:\n def __init__(self, name, lv):\n self.name = name\n self.lv = lv\n self.max_hp = int(lv * 10)\n self.now_hp = int(lv * 10)\n\n def attack(self):\n hurt = random.randint(0, self.lv*10-1)\n print(f'{self.name}进行攻击!')\n return hurt\n\n def defense(self, hurt):\n self.now_hp -= hurt\n print(f'{self.name}受到{hurt}点伤害,当前生命值{self.now_hp}')\n\nclass Boss(Monster):\n def __init__(self, name, lv):\n super(Boss, self).__init__(name, lv)\n self.shield = int(self.max_hp * 1.0)\n\n def defense(self, hurt):\n if self.shield - hurt >= 0:\n self.shield -= hurt\n print(f'{self.name}受到{hurt}点伤害,当前护盾值{self.shield},生命值{self.now_hp}')\n else:\n if self.shield > 0:\n self.now_hp -= self.shield\n self.shield = 0\n print(f'{self.name}受到{hurt}点伤害,当前护盾值{self.shield},生命值{self.now_hp}')\n else:\n self.now_hp -= hurt\n print(f'{self.name}受到{hurt}点伤害,当前护盾值{self.shield},生命值{self.now_hp}')\n\n\ndef main():\n hero = Hero('齐天大圣')\n monster1 = Monster(\"白骨精1\", 1)\n monster2 = Monster(\"白骨精2\", 2)\n monster3 = Boss(\"白骨精3\", 3)\n monster_list = [monster1, monster2, monster3]\n round = 1\n while True:\n if monster_list[0].now_hp > 0:\n print(f'Round{round}')\n monster_list[0].defense(hero.attack())\n if monster_list[0].now_hp > 0:\n hero.defense(monster_list[0].attack())\n else:\n hero.upgrade()\n del monster_list[0]\n round+=1\n if len(monster_list) == 0:\n print(f'{hero.name}You Win!')\n break\n if hero.now_hp<=0:\n print(f'{hero.name}You Loss')\n break\n\nif __name__ == '__main__':\n main()","sub_path":"homework8/Group5/hw8_1720378.py","file_name":"hw8_1720378.py","file_ext":"py","file_size_in_byte":3392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"592048188","text":"#Python for kids chapter 12 Exercise 3 Pg 190\n\nimport time\nfrom tkinter import *\ntk = Tk()\ncanvas = Canvas(tk, width=400, height=400)\ncanvas.pack()\nmy_image = PhotoImage(file='C:\\\\Users\\\\Michael\\\\Documents\\\\GitHub\\\\pythonforkids\\\\pinetrees.gif')\ncanvas.create_image(0,0, image=my_image)\n \nfor x in range(0,70):\n canvas.move(1,5,0)\n tk.update()\n time.sleep(0.05)\n \nfor x in range(0,70):\n canvas.move(1,0,5)\n tk.update()\n time.sleep(0.05)\n\nfor x in range(0,70):\n canvas.move(1,-5,0)\n tk.update()\n time.sleep(0.05)\n\n\nfor x in range(0,70):\n canvas.move(1,0,-5)\n tk.update()\n time.sleep(0.05)\n","sub_path":"ch12_Exercise3_Pg190.py","file_name":"ch12_Exercise3_Pg190.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"410286966","text":"from wsgiref.simple_server import make_server\n\n\nimport routes.middleware\nimport webob.dec\nimport webob.exc\nfrom paste.deploy import loadapp\nfrom eventlet import wsgi\nimport eventlet\n\n\nclass Controller:\n\t@webob.dec.wsgify\n\tdef __call__(self,req):\n\t\treturn webob.Response(\"Hello,world\")\n\nclass Container:\n\t@webob.dec.wsgify\n\tdef __call__(self,req):\n\t\tmethod=req.environ['wsgiorg.routing_args'][1]['action']\n\t\tmethod=getattr(self,method)\t\t\n\t\tresponse=webob.Response()\n\t\tmethod(response)\n\t\treturn response\n\tdef index(self,response):\n\t\tresponse.body=\"index\\n\"\t\n\tdef create(self,response):\n\t\tresponse.body=\"create\\n\"\t\n\tdef delete(self,response):\n\t\tresponse.body=\"delete\\n\"\n\nclass Router(object):\n\tdef __init__(self):\n\t\tself._mapper=routes.Mapper()\n\t\tself._mapper.connect(\n\t\t\t\t\t'/home',\n\t\t\t\t\tcontroller=Controller(),\n\t\t\t\t\taction='index',\n\t\t\t\t\tconditions={'method':['GET']}\n\t\t)\n\t\tself._mapper.connect('/v1/containers',\n\t\t\t\t\tcontroller=Container(),\n\t\t\t\t\taction='index',\n\t\t\t\t\tconditions={'method':['GET']}\n\t\t)\n\n\t\tself._mapper.connect('/v1/containers',\n\t\t\t\t\tcontroller=Container(),\n\t\t\t\t\taction='create',\n\t\t\t\t\tconditions={'method':['POST']}\n\t\t)\n\n\t\tself._mapper.connect('/v1/containers/{container_id',\n\t\t\t\t\tcontroller=Container(),\n\t\t\t\t\taction='delete',\n\t\t\t\t\tcondition={'method':['DELETE']}\n\t\t)\n\n\t\tself._router=routes.middleware.RoutesMiddleware(self._dispatch,self._mapper)\n\n\t@classmethod\n\tdef app_factory(cls,global_config,**local_config):\n\t\treturn cls()\n\t\n\t@webob.dec.wsgify\n\tdef __call__(self,req):\n\t\treturn self._router\n\n\t@staticmethod\n\t@webob.dec.wsgify\n\tdef _dispatch(req):\n\t\tmatch=req.environ['wsgiorg.routing_args'][1]\n\t\tif not match:\n\t\t\treturn webob.exc.HTTPNotFound()\n\t\tapp=match['controller']\n\t\treturn app\n\nif __name__ == \"__main__\":\n\tapp=loadapp('config:/home/paste.ini',name='hello')\n\twsgi.server(eventlet.listen(('',8282)),app)\n","sub_path":"loadapp.py","file_name":"loadapp.py","file_ext":"py","file_size_in_byte":1829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"474548738","text":"#!/usr/bin/env python\nfrom GrabSong import GrabSong\nimport curses\nimport locale\nfrom time import time, sleep\n\n\n# Add these to a config file\ndebug = True\nversion = \"0.0.1\"\ninterval = 1\nlocale.setlocale(locale.LC_ALL, \"\")\n# End Add these to a config file\n\nplayer = GrabSong(\"clementine\")\n\ndef validate():\n valid = [\"title\", \"artist\", \"album\"]\n for v in valid:\n if type(v) is str:\n player.metadata[valid] = \"Invalid metadata.\"\n\ndef set_strings(screen):\n status = player.update()\n screen.erase()\n screen.border(1) \n screen.addstr(1, 2, \"pygrab-song %s\" % version, curses.color_pair(1))\n if type(status) is not str:\n# validate()\n if type(player.metadata) is not str:\n screen.addstr(3, 2, \"Title: %s\" % player.metadata[\"title\"])\n screen.addstr(5, 2, \"Artist: %s\" % player.metadata[\"artist\"])\n screen.addstr(7, 2, \"Album: %s\" % player.metadata[\"album\"])\n else:\n screen.addstr(3, 2, player.metadata)\n if debug:\n screen.addstr(9, 2, \"[DEBUG] Time: %s\" % time())\n screen.addstr(10, 2, \"[DEBUG] %s\" % player.song_art)\n else:\n screen.addstr(3, 2, \"This track has invalid metadata.\")\n\n screen.refresh()\n\ndef main(screen):\n curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK)\n while True:\n sleep(interval)\n set_strings(screen)\n curses.endwin()\n\nif __name__ == \"__main__\":\n try:\n curses.wrapper(main)\n except (KeyboardInterrupt, SystemExit):\n curses.endwin()\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"151940060","text":"#\n# Removes Azure resources that have met or exceeded their TTL, and audits the event\n#\nfrom datetime import datetime\nimport json\nimport redis\nimport logging\nimport logging.handlers\nimport sys\nimport subprocess\n\nlogging.basicConfig(level=logging.INFO)\nlog = logging.getLogger('reapor')\nLOG_FILENAME = 'the_reaper.log'\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n\nCONST_TIME_FMT = \"%Y-%m-%d %H:%M:%S.%f\"\n\nCONST_AZURE_STORAGE_ACCOUNT = \"testflightdynamicstorage\"\nCONST_AZURE_STORAGE_ACCOUNT_KEY = \"\\\"kwy1i5Jl4ASk8gjrYSFJp8TcLfnghnx/uyo4qlNFab40iiBYZfS3BlDCmOLE6ql2U0rkIqkQSbiyty9Veo39Pg==\\\"\" # must use quotes to handle the '=' characters\n\n\n\n# Add the log message handler to the logger\nhandler = logging.handlers.RotatingFileHandler(LOG_FILENAME,\n maxBytes=2000000,\n backupCount=50)\nhandler.setFormatter(formatter)\nlog.addHandler(handler)\n\nlog.info(\"Don't fear the reapor\")\n# ensure that the azure system is running in arm mode\n# this command takes 1.5 seconds to run and could be executed before every azure call is issues arise with other processes that set the mode to asm\nsubprocess.Popen('azure config mode arm', shell=True).wait()\n\n\ntry:\n\tr = redis.StrictRedis(host='localhost', port=6379, db=0)\n\n\t# determine which entries have met or exceeded their TTL\n\tfor key in r.scan_iter():\n\t\tdkey = key.decode('utf-8')\n\t\tlog.debug('key: ' + dkey)\n\t\tlog.debug('value: ' + r.get(dkey).decode('utf-8'))\n\t\tobj = r.get(dkey).decode('utf-8')\n\t\tjobj = json.loads(obj)\n\t\tttl = datetime.strptime(jobj['ttl'], CONST_TIME_FMT)\n\t\t\n\t\tif(ttl <= datetime.utcnow()):\n#\t\tif(True):\n\t\t\t# remove appropriate candidates\n\t\t\tlog.info('deleting ' + dkey)\n\t\t\tbashCommand = \"delete.bat \" + dkey\n\t\t\t# the \"delete group\" command blocks, and it can take up to 10 minutes for this command to return\n\t\t\tprocess = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE, cwd=\"c:/github/azure-the_creator/\") \n\t\t\toutput = process.communicate()[0]\n\t\t\t# way to interigate response for failure?\n\t\t\tstr_output = output.decode('UTF-8')\n\t\t\tlog.info(\"result of running azure delete command:\" + str_output)\n\t\t\t\n\t\t\t# clean up extra crap that doesn't get deleted\n\t\t\t# Underlying blobs (VHDs and status files) are not deleted by default when you delete virtual machines\n\n\t\t\trandName_condensed = dkey.replace(\"-\", \"\")\n\t\t\trandName_condensed = randName_condensed[:12]\n\t\t\tfor vmprefix in [\"vm1\", \"vm2\", \"vm3\"]:\n\t\t\t\tbashCommand = \"list_underlying_blobs.bat \" + vmprefix + randName_condensed + \" \" + CONST_AZURE_STORAGE_ACCOUNT + \" \" + CONST_AZURE_STORAGE_ACCOUNT_KEY\n\t\t\t\t# use shell=true and a command string to preserve == characters at end of the account key\n\t\t\t\tprocess = subprocess.Popen(bashCommand, stdout=subprocess.PIPE, shell=True, cwd=\"c:/github/azure-the_creator/\") \n\t\t\t\toutput = process.communicate()[0]\n\t\t\t\tstr_output = output.decode(\"UTF-8\")\n\t\t\t\t# log.info(\"result of running azure list command:\" + str_output)\n\n\t\t\t\tjson_data = json.loads(str_output)\n\t\t\t\tfor blob in json_data:\n\t\t\t\t\tblob_name = blob[\"name\"]\n\t\t\t\t\tlog.info(\"deleting underlying blob: [\" + blob_name + \"]\")\n\t\t\t\t\tbashCommand = \"delete_underlying_blob.bat \" + blob_name + \" \" + CONST_AZURE_STORAGE_ACCOUNT + \" \" + CONST_AZURE_STORAGE_ACCOUNT_KEY\n\t\t\t\t\t# use shell=true and a command string to preserve == characters at end of the account key\n\t\t\t\t\tprocess = subprocess.Popen(bashCommand, stdout=subprocess.PIPE, shell=True, cwd=\"c:/github/azure-the_creator/\") \n\t\t\t\t\toutput = process.communicate()[0]\n\n\t\t\tr.delete(dkey)\nexcept:\n\te = sys.exc_info()\n\tlog.error(e)\n","sub_path":"reapor.py","file_name":"reapor.py","file_ext":"py","file_size_in_byte":3624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"639042691","text":" # IMPORTING\r\nimport tkinter # importing the GUI\r\n\r\n # MAIN WINDOW\r\nroot = tkinter.Tk() # making a window\r\nroot.title(\"Calculator\") # naming the window\r\nroot.configure(bg = \"powder blue\") # configuring the background of the whole window\r\nroot.maxsize(375, 370) # setting the maximum size\r\nroot.minsize(375, 370) # setting the minimum size\r\n\r\n # FUNCTIONS & VARIABLES\r\nops = (\"\") # making a variable that stores everything that will be displayed later\r\n \r\ndef button(numbers): # defining a function\r\n global ops # making a global variable\r\n ops = ops + str(numbers) # adding pressed numbers/signs into the variable\r\n text_input.set(ops) # setting the textbox to display user's input\r\n\r\ndef clear(): # difining a function\r\n global ops # making a global variable\r\n ops = (\"\") # clearing whatever was user input \r\n text_input.set(\"\") # setting the cleared textbox\r\n\r\ndef equal_fnc(): # difining a function\r\n global ops # making a global variable\r\n eql = (str(eval(ops))) # putting the user input into string and than making whatever it says\r\n text_input.set(eql) # setting the textbox to display the result\r\n ops = (\"\") # restarting the variable so when the user starts typing again it disappears\r\n\r\n # TITLE\r\nlabel = tkinter.Label(root, text = \"CALCULATOR\", fg = \"black\", bg = \"powder blue\", font = (\"Fixedsys\", 28, \"bold\")) # creating a text and formating it\r\nlabel.grid(row = 0, column = 0, columnspan = 185) # placing the text\r\n\r\n # TEXTBOX\r\ntext_input = tkinter.StringVar() # creating a displayed string variable\r\ntextbox = tkinter.Entry(root,bg = \"pink\", font = (\"Ariel\", 20, \"bold\"), textvariable = text_input, bd = 30) # creating the textbox and formating it # bd = border\r\ntextbox.grid(row = 1, column = 0, columnspan = 4) # placing the textbox\r\n\r\n # BUTTONS\r\n\r\n# creating buttons, formating and placing them\r\n# lambda is used to pass functions with parameters -> function button has a parameter numbers\r\n \r\n # ROW 1\r\nnumber7 = tkinter.Button(root, text = \"7\", fg = \"black\", bg = \"pink\", font = (\"Ariel\", 12, \"bold\"), width = 8, height = 2, command = lambda:button(7))\r\nnumber7.grid(row = 2, column = 0, padx = 2, pady = 2)\r\nnumber8 = tkinter.Button(root, text = \"8\", fg = \"black\", bg = \"pink\", font = (\"Ariel\", 12, \"bold\"), width = 8, height = 2, command = lambda:button(8))\r\nnumber8.grid(row = 2, column = 1, padx = 2, pady = 2)\r\nnumber9 = tkinter.Button(root, text = \"9\", fg = \"black\", bg = \"pink\", font = (\"Ariel\", 12, \"bold\"), width = 8, height = 2, command = lambda:button(9))\r\nnumber9.grid(row = 2, column = 2, padx = 2, pady = 2)\r\nplus = tkinter.Button(root, text = \"+\", fg = \"black\", bg = \"pink\", font = (\"Ariel\", 12, \"bold\"), width = 8, height = 2, command = lambda:button(\"+\"))\r\nplus.grid(row = 2, column = 3, padx = 2, pady = 2)\r\n\r\n # ROW 2\r\nnumber4 = tkinter.Button(root, text = \"4\", fg = \"black\", bg = \"pink\", font = (\"Ariel\", 12, \"bold\"), width = 8, height = 2, command = lambda:button(4))\r\nnumber4.grid(row = 3, column = 0, padx = 2, pady = 2)\r\nnumber5 = tkinter.Button(root, text = \"5\", fg = \"black\", bg = \"pink\", font = (\"Ariel\", 12, \"bold\"), width = 8, height = 2, command = lambda:button(5))\r\nnumber5.grid(row = 3, column = 1, padx = 2, pady = 2)\r\nnumber6 = tkinter.Button(root, text = \"6\", fg = \"black\", bg = \"pink\", font = (\"Ariel\", 12, \"bold\"), width = 8, height = 2, command = lambda:button(6))\r\nnumber6.grid(row = 3, column = 2, padx = 2, pady = 2)\r\nminus = tkinter.Button(root, text = \"-\", fg = \"black\", bg = \"pink\", font = (\"Ariel\", 12, \"bold\"), width = 8, height = 2, command = lambda:button(\"-\"))\r\nminus.grid(row = 3, column = 3, padx = 2, pady = 2)\r\n\r\n # ROW 3\r\nnumber1 = tkinter.Button(root, text = \"1\", fg = \"black\", bg = \"pink\", font = (\"Ariel\", 12, \"bold\"), width = 8, height = 2, command = lambda:button(1))\r\nnumber1.grid(row = 4, column = 0, padx = 2, pady = 2)\r\nnumber2 = tkinter.Button(root, text = \"2\", fg = \"black\", bg = \"pink\", font = (\"Ariel\", 12, \"bold\"), width = 8, height = 2, command = lambda:button(2))\r\nnumber2.grid(row = 4, column = 1, padx = 2, pady = 2)\r\nnumber3 = tkinter.Button(root, text = \"3\", fg = \"black\", bg = \"pink\", font = (\"Ariel\", 12, \"bold\"), width = 8, height = 2, command = lambda:button(3))\r\nnumber3.grid(row = 4, column = 2, padx = 2, pady = 2)\r\ntimes = tkinter.Button(root, text = \"×\", fg = \"black\", bg = \"pink\", font = (\"Ariel\", 12, \"bold\"), width = 8, height = 2, command = lambda:button(\"*\"))\r\ntimes.grid(row = 4, column = 3, padx = 2, pady = 2)\r\n\r\n # ROW 4\r\nclear = tkinter.Button(root, text = \"C\", fg = \"black\", bg = \"pink\", font = (\"Ariel\", 12, \"bold\"), width = 8, height = 2, command = clear)\r\nclear.grid(row = 5, column = 0, padx = 2, pady = 2)\r\nnumber0 = tkinter.Button(root, text = \"0\", fg = \"black\", bg = \"pink\", font = (\"Ariel\", 12, \"bold\"), width = 8, height = 2, command = lambda:button(0))\r\nnumber0.grid(row = 5, column = 1, padx = 2, pady = 2)\r\nequal = tkinter.Button(root, text = \"=\", fg = \"black\", bg = \"pink\", font = (\"Ariel\", 12, \"bold\"), width = 8, height = 2, command = equal_fnc)\r\nequal.grid(row = 5, column = 2, padx = 2, pady = 2)\r\ndevide = tkinter.Button(root, text = \"÷\", fg = \"black\", bg = \"pink\", font = (\"Ariel\", 12, \"bold\"), width = 8, height = 2, command = lambda:button(\"/\"))\r\ndevide.grid(row = 5, column = 3, padx = 2, pady = 2)\r\n\r\n\r\n\r\n\r\n\r\n \r\n","sub_path":"tkinter calculator - 1. verze.py","file_name":"tkinter calculator - 1. verze.py","file_ext":"py","file_size_in_byte":5512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"507189651","text":"'''\nTorrent-tv.ru Playlist Downloader Plugin\nhttp://ip:port/ttvplaylist\n'''\nimport re\nimport logging\nimport urllib2\nimport time\nfrom PluginInterface import AceProxyPlugin\nimport ttvplaylist_config\n\n\nclass Ttvplaylist(AceProxyPlugin):\n handlers = ('ttvplaylist', )\n\n logger = logging.getLogger('plugin_ttvplaylist')\n url = ttvplaylist_config.url\n host = ttvplaylist_config.host\n playlist = None\n playlisttime = None\n\n def downloadPlaylist(self):\n try:\n Ttvplaylist.logger.debug('Trying to download playlist')\n Ttvplaylist.playlist = urllib2.urlopen(\n Ttvplaylist.url, timeout=10).read()\n Ttvplaylist.playlisttime = int(time.time())\n except:\n Ttvplaylist.logger.error(\"Can't download playlist!\")\n return False\n\n try:\n Ttvplaylist.playlist = re.sub(r',(\\S.+) \\((.+)\\)', r' group-title=\"\\2\",\\1', Ttvplaylist.playlist)\n except Exception as e:\n Ttvplaylist.logger.warning(\"Can't parse playlist groups! \" + repr(e))\n\n try:\n # Add JTV\n Ttvplaylist.playlist = re.sub('#EXTM3U', r'#EXTM3U url-tvg=\"http://www.teleguide.info/download/new3/jtv.zip\"',\n Ttvplaylist.playlist)\n except Exception as e:\n Ttvplaylist.logger.warning(\"Can't add JTV! \" + repr(e))\n\n try:\n Ttvplaylist.playlist = re.sub(r',(\\S.+)', lambda match: ' tvg-name=\"' + match.group(1).replace(' ', '_') + '\",' \\\n + match.group(1), Ttvplaylist.playlist)\n except Exception as e:\n Ttvplaylist.logger.warning(\"Can't add channel JTV name! \" + repr(e))\n\n return True\n\n def handle(self, connection):\n if not Ttvplaylist.playlist or (int(time.time()) - Ttvplaylist.playlisttime > 60 * 60):\n if not self.downloadPlaylist():\n connection.dieWithError()\n return\n\n if Ttvplaylist.host:\n hostport = Ttvplaylist.host + ':' + str(connection.request.getsockname()[1])\n else:\n hostport = connection.request.getsockname()[0] + ':' + str(connection.request.getsockname()[1])\n\n try:\n if connection.splittedpath[2].lower() == 'ts':\n # Adding ts:// after http:// for some players\n hostport = 'ts://' + hostport\n except:\n pass\n\n connection.send_response(200)\n connection.send_header('Content-type', 'application/x-mpegurl')\n connection.end_headers()\n # For .acelive URLs\n playlist = re.sub('^(http.+)$', lambda match: 'http://' + hostport + '/torrent/' + \\\n urllib2.quote(match.group(0), '') + '/stream.mp4', Ttvplaylist.playlist, flags=re.MULTILINE)\n # For PIDs\n playlist = re.sub('^([0-9a-f]{40})$', 'http://' + hostport + '/pid/\\\\1/stream.mp4', playlist, flags=re.MULTILINE)\n connection.wfile.write(playlist)\n","sub_path":"plugins/ttvplaylist_plugin.py","file_name":"ttvplaylist_plugin.py","file_ext":"py","file_size_in_byte":2948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"607657913","text":"from django.test import Client, TestCase\n\nfrom .utils import obtain_api_key, create_admin_account\n\n\nclass UserApiTest(TestCase):\n \"\"\"Test for User API\"\"\"\n\n def setUp(self):\n self.client = Client()\n self.endpoint = '/api'\n self.admin_test_credentials = ('admin', 'admin@taverna.com', 'qwerty123')\n create_admin_account(*self.admin_test_credentials)\n self.header = {\n 'HTTP_X_TAVERNATOKEN': obtain_api_key(\n self.client, *self.admin_test_credentials\n )\n }\n self.first_user = self.create_user('oakeem', 'oatman')['user']\n\n def make_request(self, query, method='GET'):\n if method == 'GET':\n return self.client.get(self.endpoint, data={'query': query}, **self.header).json()\n\n if method == 'POST':\n return self.client.post(self.endpoint, data={'query': query}, **self.header).json()\n\n def create_user(self, username, password):\n query = '''\n mutation{\n createUser(input: {username: \"%s\", password: \"%s\"}){\n user{\n id,\n originalId,\n username\n }\n }\n }\n ''' % (username, password)\n\n return self.make_request(query, 'POST')\n\n def create_multiple_users(self):\n new_users = (\n ('john', 'qwerty123'),\n ('raphael', 'qwerty123'),\n ('samson', 'qwerty123'),\n )\n\n [self.create_user(username, password) for username, password in new_users]\n\n return new_users\n\n def retrieve_user(self, user_id):\n query = 'query {user(id: \"%s\") {username}}' % (user_id)\n\n return self.make_request(query)\n\n def ordering_test_helper(self, ordering_param, users):\n # For ascending ordering\n query = 'query{users(orderBy: \"%s\") {edges{node{username}}}}' % (ordering_param)\n expected = {\n 'users': [\n {\n 'username': users[0]\n },\n {\n 'username': users[1]\n },\n {\n 'username': users[2]\n },\n {\n 'username': users[3]\n },\n {\n 'username': users[4]\n }\n ]\n }\n self.assertEqual(expected, self.make_request(query))\n\n # For descending ordering\n query = 'query {users(orderBy: \"-%s\") {edges{node{username}}}}' % (ordering_param)\n expected['users'].reverse()\n self.assertEqual(expected, self.make_request(query))\n\n def test_creation_of_user_object(self):\n credentials = {\n 'username': 'tom_dick',\n 'password': 'qwerty123'\n }\n\n # For new user record\n response = self.create_user(\n credentials['username'],\n credentials['password']\n )\n created_user = response['user']\n expected = {\n 'user': {\n 'id': created_user['id'],\n 'originalId': created_user['originalId'],\n 'username': created_user['username']\n }\n }\n self.assertEqual(expected, response)\n\n # For existing user record\n response = self.create_user(\n credentials['username'],\n credentials['password']\n )\n self.assertEqual({'user': None}, response)\n\n def test_retrieval_of_one_user_object(self):\n # Retrieve with valid id\n expected = {\n 'user': {\n 'username': self.first_user['username']\n }\n }\n self.assertEqual(expected, self.retrieve_user(self.first_user['id']))\n\n # Retrieve with invalid id\n self.assertEqual({'user': None}, self.retrieve_user(100))\n\n def test_retrieval_of_multiple_user_objects_without_filtering(self):\n new_users = self.create_multiple_users()\n\n query = 'query {users{edges{node{username}}}}'\n\n expected = {\n 'users': [\n {\n 'username': self.admin_test_credentials[0]\n },\n {\n 'username': self.first_user['username']\n },\n {\n 'username': new_users[0][0]\n },\n {\n 'username': new_users[1][0]\n },\n {\n 'username': new_users[2][0]\n }\n ]\n }\n\n self.assertEqual(expected, self.make_request(query))\n\n def test_retrieval_of_multiple_user_objects_filter_by_username(self):\n new_users = self.create_multiple_users()\n\n query = 'query {users(username_Icontains: \"H\") {edges{node{username}}}}'\n\n expected = {\n 'users': [\n {\n 'username': new_users[0][0]\n },\n {\n 'username': new_users[1][0]\n }\n ]\n }\n\n self.assertEqual(expected, self.make_request(query))\n\n def test_retrieval_of_multiple_user_objects_filter_by_is_staff(self):\n self.create_multiple_users()\n\n query = 'query {users(isStaff: true) {edges{node{username}}}}'\n\n expected = {\n 'users': [\n {\n 'username': self.admin_test_credentials[0]\n }\n ]\n }\n\n self.assertEqual(expected, self.make_request(query))\n\n def test_retrieval_of_multiple_user_objects_filter_by_is_active(self):\n self.create_multiple_users()\n\n query = 'query {users(isActive: true) {edges{node{username}}}}'\n\n expected = {\n 'users': [\n {\n 'username': self.admin_test_credentials[0]\n }\n ]\n }\n\n self.assertEqual(expected, self.make_request(query))\n\n def test_retrieval_of_multiple_user_objects_ordering_by_id(self):\n new_users = self.create_multiple_users()\n users = [\n self.admin_test_credentials[0],\n self.first_user['username'],\n new_users[0][0],\n new_users[1][0],\n new_users[2][0]\n ]\n\n self.ordering_test_helper('id', users)\n\n def test_retrieval_of_multiple_user_objects_ordering_by_username(self):\n new_users = self.create_multiple_users()\n users = [\n self.admin_test_credentials[0],\n new_users[0][0],\n self.first_user['username'],\n new_users[1][0],\n new_users[2][0]\n ]\n\n self.ordering_test_helper('username', users)\n\n def test_retrieval_of_multiple_user_objects_ordering_by_date_joined(self):\n new_users = self.create_multiple_users()\n users = [\n self.admin_test_credentials[0],\n self.first_user['username'],\n new_users[0][0],\n new_users[1][0],\n new_users[2][0]\n ]\n\n self.ordering_test_helper('date_joined', users)\n\n def test_update_of_user_object(self):\n # Update with valid id\n query = '''\n mutation{\n updateUser(\n input: {\n id: \"%s\",\n firstName: \"Akeem\",\n lastName: \"Oduola\",\n username: \"oakeem\",\n email: \"akeem.oduola@andela.com\"\n }\n )\n {\n user{\n id,\n originalId,\n username,\n firstName,\n lastName,\n email\n }\n }\n }\n ''' % (self.first_user['id'])\n\n expected = {\n 'user': {\n 'id': self.first_user['id'],\n 'originalId': self.first_user['originalId'],\n 'username': 'oakeem',\n 'firstName': 'Akeem',\n 'lastName': 'Oduola',\n 'email': 'akeem.oduola@andela.com',\n }\n }\n\n self.assertEqual(expected, self.make_request(query, 'POST'))\n\n # Update with invalid id\n query = '''\n mutation{\n updateUser(\n input: {\n id: \"%s\",\n firstName: \"Akeem\",\n lastName: \"Oduola\",\n username: \"oakeem\",\n email: \"akeem.oduola@andela.com\"\n }\n )\n {\n user{\n id,\n originalId,\n username,\n firstName,\n lastName,\n email\n }\n }\n }\n ''' % ('wrong-id')\n self.assertEqual({'user': None}, self.make_request(query, 'POST'))\n\n def test_deletion_of_user_object(self):\n # Delete with valid id\n query = '''\n mutation{\n deleteUser(input: {id: \"%s\"}){\n user{\n username\n }\n }\n }\n ''' % (self.first_user['id'])\n\n expected = {\n 'user': {\n 'username': self.first_user['username']\n }\n }\n\n self.assertEqual(expected, self.make_request(query, 'POST'))\n self.assertEqual({'user': None}, self.retrieve_user(self.first_user['id']))\n\n # Delete with invalid id\n query = '''\n mutation{\n deleteUser(input: {id: \"%s\"}){\n user{\n username\n }\n }\n }\n ''' % ('wrong-id')\n self.assertEqual({'user': None}, self.make_request(query, 'POST'))\n","sub_path":"app/api/tests/test_user_api.py","file_name":"test_user_api.py","file_ext":"py","file_size_in_byte":9987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"439878467","text":"'''Как поэлементно суммировать списки.\n'''\nfrom operator import add\n\n\nlist1=[1, 2, 3]\nlist2=[4, 5, 6]\n\nprint(list(map(add, list1, list2)))\nprint(tuple(sum(x) for x in zip(list1, list2)))\n","sub_path":"Sum_lst.py","file_name":"Sum_lst.py","file_ext":"py","file_size_in_byte":218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"185281354","text":"import pygame\r\nfrom pygame.locals import *\r\nimport random\r\nfrom potion import *\r\n\r\nwalls = []\r\nclass Tile(pygame.sprite.Sprite):\r\n images = []\r\n vis = False\r\n discovered = False\r\n def __init__(self,pos,layer = 2):\r\n self._layer = layer\r\n pygame.sprite.Sprite.__init__(self,self.containers)\r\n self.image = self.images[0]\r\n self.blocked = True\r\n self.pos = pos\r\n x,y = pos\r\n self.rect = Rect(x*35,y*35,self.image.get_width(),self.image.get_height())#self.image.get_rect(pos)\r\n\r\n def update(self):\r\n pass\r\n\r\nclass Wall(Tile):\r\n def __init__(self,pos):\r\n Tile.__init__(self,pos)\r\n self.blockedByTerrain = True\r\n self.blocked = True\r\n self.image = self.images[0]\r\n\r\nclass Floor(Tile):\r\n def __init__(self,pos):\r\n Tile.__init__(self,pos)\r\n self.blockedByTerrain = False\r\n self.vis = True\r\n self.blocked = True\r\n self.image = self.images[4]\r\n\r\nclass Out(Tile):\r\n def __init__(self,pos,layer = 1):\r\n self._layer = -2\r\n Tile.__init__(self,pos)\r\n self.image = self.images[6]\r\n\r\nclass Door(Tile):\r\n def __init__(self,pos):\r\n Tile.__init__(self,pos)\r\n self.blockedByTerrain = True\r\n self.pos = pos\r\n self.closed = True\r\n self.image = self.images[3]\r\n\r\nclass Chest(Tile):\r\n life = 1\r\n def __init__(self,pos):\r\n Tile.__init__(self,pos)\r\n self.blockedByTerrain = True\r\n self.image = self.images[5]\r\n\r\n\r\n def update(self):\r\n if self.life <= 0:\r\n if random.randint(0,2) == 1:\r\n Health((self.rect.centerx-10,self.rect.centery-10))\r\n self.kill()\r\n\r\nclass Exit(Tile):\r\n def __init__(self, pos):\r\n Tile.__init__(self,pos)\r\n self.blockedByTerrain = False\r\n self.image = self.images[1]\r\n\r\n\r\n # def find_placement(self):\r\n # rng = random.Random()\r\n # #this works for the most part but sometimes still has doors next to it, and sometimes it has adjcent walls.\r\n # #checks for if 3 walls are around it. cept this isn't true at all... need to re-think this.\r\n #\r\n # while not (isinstance(walls[self.pos],Floor) and isinstance(walls[self.pos+1],Floor) and isinstance(walls[self.pos-1],Floor) and \\\r\n # isinstance(walls[self.pos-25],Floor) and isinstance(walls[self.pos+25],Floor)):\r\n # # or (isinstance(walls[self.pos],Floor) == False or isinstance(walls[self.pos+1],Floor) == True or isinstance(walls[self.pos-1],Floor) == True or \\\r\n # # isinstance(walls[self.pos-25],Floor) == True or isinstance(walls[self.pos+25],Floor) == False):\r\n # self.pos = rng.randint(0,len(walls)-26)\r\n # print(walls[self.pos],walls[self.pos+1],walls[self.pos-1],walls[self.pos-25], walls[self.pos+25])\r\n # print(\"exit\",walls[self.pos],self.pos)\r\n #\r\n # self.rect.left = ((self.pos)%25) * 35\r\n # self.rect.top = ((self.pos)//25) * 35\r\n","sub_path":"maps.py","file_name":"maps.py","file_ext":"py","file_size_in_byte":3025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"186181932","text":"from django.conf.urls import patterns, url\nimport re\n\nfrom reservations import views\n\nurlpatterns = patterns('',\n\turl(r'^list/?$', views.list),\n url(r'^create/?$', views.create),\n url(r'^edit/(?P\\d+)/$', views.edit),\n url(r'^delete/(?P\\d+)/$', views.delete),\n url(r'^customer/(?P\\d+)/delete/$', views.customer_delete,\n name='customer_delete'),\n url(r'^customer/(?P\\d+)/$', views.customer_edit,\n name='customer_edit'),\n url(r'^customer/$', views.customer_list, name='customer_list'),\n)\n","sub_path":"reservations/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"500804098","text":"# -*- coding: utf-8 -*-\r\nfrom __future__ import absolute_import\r\n\r\nimport datetime\r\nimport graphene\r\n\r\nfrom graphene import Scalar\r\nfrom graphene.utils.str_converters import to_camel_case\r\nfrom graphql.language import ast\r\n\r\ntry:\r\n import iso8601\r\nexcept:\r\n raise ImportError(\r\n \"iso8601 package is required for DateTime Scalar.\\n\"\r\n \"You can install it using: pip install iso8601.\"\r\n )\r\n\r\n\r\nclass Date(Scalar):\r\n '''\r\n The `Date` scalar type represents a Date\r\n value as specified by\r\n [iso8601](https://en.wikipedia.org/wiki/ISO_8601).\r\n '''\r\n epoch_time = '00:00:00'\r\n\r\n @staticmethod\r\n def serialize(date):\r\n if isinstance(date, datetime.datetime):\r\n date = date.date()\r\n\r\n assert isinstance(date, datetime.date), (\r\n 'Received not compatible date \"{}\"'.format(repr(date))\r\n )\r\n return date.isoformat()\r\n\r\n @classmethod\r\n def parse_literal(cls, node):\r\n if isinstance(node, ast.StringValue):\r\n return cls.parse_value(node.value)\r\n\r\n @classmethod\r\n def parse_value1(cls, value):\r\n dt = iso8601.parse_date('{}T{}'.format(value, cls.epoch_time))\r\n return datetime.date(dt.year, dt.month, dt.day)\r\n\r\n @staticmethod\r\n def parse_value(value):\r\n return iso8601.parse_date(value).date()\r\n\r\n\r\ndef object_type_factory(_type, new_model, new_name=None, new_only_fields=(), new_exclude_fields=(),\r\n new_filter_fields=None, new_registry=None, new_skip_registry=False):\r\n\r\n class GenericType(_type):\r\n class Meta:\r\n model = new_model\r\n name = new_name or to_camel_case('{}_Generic_Type'.format(new_model.__name__))\r\n only_fields = new_only_fields\r\n exclude_fields = new_exclude_fields\r\n filter_fields = new_filter_fields\r\n registry = new_registry\r\n skip_registry = new_skip_registry\r\n description = 'Auto generated Type for {} model'.format(new_model._meta.verbose_name)\r\n\r\n return GenericType\r\n\r\n\r\ndef object_list_type_factory(_type, new_model, new_only_fields=(), new_exclude_fields=(), new_results_field_name=None,\r\n new_filter_fields=None, new_name=None, new_pagination=None, new_queryset=None):\r\n\r\n class GenericListType(_type):\r\n class Meta:\r\n model = new_model\r\n name = new_name or to_camel_case('{}_List_Type'.format(new_model.__name__))\r\n only_fields = new_only_fields\r\n exclude_fields = new_exclude_fields\r\n filter_fields = new_filter_fields\r\n results_field_name = new_results_field_name\r\n pagination = new_pagination\r\n queryset = new_queryset\r\n description = 'Auto generated list Type for {} model'.format(new_model._meta.verbose_name)\r\n\r\n return GenericListType\r\n\r\n\r\ndef input_object_type_factory(input_type, new_model, new_input_for, new_name=None, new_only_fields=(),\r\n new_exclude_fields=(), new_filter_fields=None,new_nested_fields=False,\r\n new_registry=None, new_skip_registry=False):\r\n\r\n class GenericInputType(input_type):\r\n class Meta:\r\n model = new_model\r\n name = new_name or to_camel_case('{}_{}_Generic_Type'.format(new_model.__name__, new_input_for))\r\n only_fields = new_only_fields\r\n exclude_fields = new_exclude_fields\r\n filter_fields = new_filter_fields\r\n nested_fields = new_nested_fields\r\n registry = new_registry\r\n skip_registry = new_skip_registry\r\n input_for = new_input_for\r\n description = ' Auto generated InputType for {} model'.format(new_model._meta.verbose_name)\r\n\r\n return GenericInputType\r\n\r\n\r\nclass DjangoListObjectBase(object):\r\n def __init__(self, results, count, results_field_name='results'):\r\n self.results = results\r\n self.count = count\r\n self.results_field_name = results_field_name\r\n\r\n def to_dict(self):\r\n return {\r\n self.results_field_name: [e.to_dict() for e in self.results],\r\n 'count': self.count,\r\n }\r\n\r\n\r\ndef resolver(attr_name, root, instance, info):\r\n if attr_name == 'app_label':\r\n return instance._meta.app_label\r\n elif attr_name == 'id':\r\n return instance.id\r\n elif attr_name == 'model_name':\r\n return instance._meta.model.__name__\r\n\r\n\r\nclass GenericForeignKeyType(graphene.ObjectType):\r\n app_label = graphene.String()\r\n id = graphene.ID()\r\n model_name = graphene.String()\r\n\r\n class Meta:\r\n description = ' Auto generated Type for a model\\'s GenericForeignKey field '\r\n default_resolver = resolver\r\n\r\n\r\nclass GenericForeignKeyInputType(graphene.InputObjectType):\r\n app_label = graphene.Argument(graphene.String, required=True)\r\n id = graphene.Argument(graphene.ID, required=True)\r\n model_name = graphene.Argument(graphene.String, required=True)\r\n\r\n class Meta:\r\n description = ' Auto generated InputType for a model\\'s GenericForeignKey field '\r\n","sub_path":"graphene_django_extras/base_types.py","file_name":"base_types.py","file_ext":"py","file_size_in_byte":5132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"65933828","text":"#!/usr/bin/env python3\nfrom __future__ import print_function\nfrom urdfpy import URDF\nimport argparse\nimport os\nimport math\nimport yaml\n# import stretch_body.hello_utils as hu\n# hu.print_stretch_re_use()\nprint(\"For use with S T R E T C H (TM) RESEARCH EDITION from Hello Robot Inc.\\n\")\n\n########################################################################################\n### The classes below demonstrate how the robot mechanisms are modeled relative to the URDF\n### Currently the stretch_body package relies on Python2.7 and the visualization tool Python3\n### For now we use FakeRobot as a placeholder until stretch_body moves to Python3\n\n#import stretch_body.robot as rb\nclass FakeRobot:\n def __init__(self):\n pass\n\n def startup(self):\n pass\n\n def is_calibrated(self):\n return True\n\n def stop(self):\n pass\n\n def get_status(self):\n return {'arm': {'pos': 0.4},\n 'lift': {'pos': 0.4},\n 'end_of_arm': {'wrist_yaw': {'pos': 0.0},\n 'stretch_gripper': {'pos': 0.0}},\n 'head': {'head_pan': {'pos': 0.0},\n 'head_tilt': {'pos': 0.0}}\n }\n\n\nclass GripperConversion:\n def __init__(self):\n # robotis position values (gripper.py)\n # 0 is very close to closed (fingers almost or barely touching)\n # 50 is maximally open\n # -100 is maximally closed (maximum force applied to the object - might be risky for a large object)\n #\n # aperture is ~12.5 cm wide when open (0.125 m, 125 mm)\n\n self.finger_length_m = 0.17\n\n self.open_aperture_m = 0.125\n self.closed_aperture_m = 0.0\n\n # 0.52 rad ~= 30 deg\n self.open_gripper_rad = 0.52\n self.closed_gripper_rad = 0.0\n\n self.open_robotis = 5.0\n self.closed_robotis = 0.0\n self.max_grip_force_robotis = -1.0\n\n self.robotis_to_aperture_slope = (\n (self.open_aperture_m - self.closed_aperture_m) / (self.open_robotis - self.closed_robotis))\n\n def robotis_to_aperture(self, robotis_in):\n # linear model\n aperture_m = (self.robotis_to_aperture_slope * (robotis_in - self.closed_robotis)) + self.closed_aperture_m\n return aperture_m\n\n def aperture_to_robotis(self, aperture_m):\n # linear model\n robotis_out = ((aperture_m - self.closed_aperture_m) / self.robotis_to_aperture_slope) + self.closed_robotis\n return robotis_out\n\n def aperture_to_finger_rad(self, aperture_m):\n # arc length / radius = ang_rad\n finger_rad = (aperture_m / 2.0) / self.finger_length_m\n return finger_rad\n\n def finger_rad_to_aperture(self, finger_rad):\n aperture_m = 2.0 * (finger_rad * self.finger_length_m)\n return aperture_m\n\n def finger_to_robotis(self, finger_ang_rad):\n aperture_m = self.finger_rad_to_aperture(finger_ang_rad)\n robotis_out = self.aperture_to_robotis(aperture_m)\n return robotis_out\n\n def status_to_all(self, gripper_status):\n aperture_m = self.robotis_to_aperture(gripper_status['pos'])\n finger_rad = self.aperture_to_finger_rad(aperture_m)\n return aperture_m, finger_rad\n\n\nclass StretchState:\n def __init__(self, robot, controller_parameters):\n self.stretch = robot\n self.controller_parameters = controller_parameters.copy()\n self.gripper_conversion = GripperConversion()\n\n def get_urdf_configuration(self, backlash_state=None):\n if backlash_state is None:\n # use default backlash state\n backlash_state = {'wrist_extension_retracted': False,\n 'head_pan_looked_left': False}\n\n stretch_status = self.stretch.get_status()\n\n # set positions of the telescoping joints\n arm_status = stretch_status['arm']\n if backlash_state['wrist_extension_retracted']:\n arm_backlash_correction = self.controller_parameters['arm_retracted_offset']\n else:\n arm_backlash_correction = 0.0\n arm_m = arm_status['pos'] + arm_backlash_correction\n telescoping_link_m = arm_m / 4.0\n\n lift_status = stretch_status['lift']\n lift_m = lift_status['pos']\n\n wrist_yaw_status = stretch_status['end_of_arm']['wrist_yaw']\n wrist_yaw_rad = wrist_yaw_status['pos']\n\n gripper_status = stretch_status['end_of_arm']['stretch_gripper']\n gripper_aperture_m, gripper_finger_rad = self.gripper_conversion.status_to_all(gripper_status)\n\n head_pan_status = stretch_status['head']['head_pan']\n if backlash_state['head_pan_looked_left']:\n pan_backlash_correction = self.controller_parameters['pan_looked_left_offset']\n else:\n pan_backlash_correction = 0.0\n head_pan_rad = head_pan_status['pos'] + self.controller_parameters['pan_angle_offset'] + pan_backlash_correction\n\n head_tilt_status = stretch_status['head']['head_tilt']\n # ignores tilt backlash state\n raw_head_tilt_rad = head_tilt_status['pos']\n if raw_head_tilt_rad > self.controller_parameters['tilt_angle_backlash_transition']:\n tilt_backlash_correction = self.controller_parameters['tilt_looking_up_offset']\n else:\n tilt_backlash_correction = 0.0\n head_tilt_rad = head_tilt_status['pos'] + self.controller_parameters[\n 'tilt_angle_offset'] + tilt_backlash_correction\n\n configuration = {\n 'joint_left_wheel': 0.0,\n 'joint_right_wheel': 0.0,\n 'joint_lift': lift_m,\n 'joint_arm_l0': telescoping_link_m,\n 'joint_arm_l1': telescoping_link_m,\n 'joint_arm_l2': telescoping_link_m,\n 'joint_arm_l3': telescoping_link_m,\n 'joint_wrist_yaw': wrist_yaw_rad,\n 'joint_gripper_finger_left': gripper_finger_rad,\n 'joint_gripper_finger_right': gripper_finger_rad,\n 'joint_head_pan': head_pan_rad,\n 'joint_head_tilt': head_tilt_rad\n }\n\n return configuration\n\n# #######################################################################################\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Python based URDF visualization')\n parser.add_argument(\"--motion\", help=\"Turn motor on\", action=\"store_true\")\n parser.add_argument(\"--fake\", help=\"Show fake robot\", action=\"store_true\")\n args = parser.parse_args()\n\n urdf_file = os.path.join(os.environ['HELLO_FLEET_PATH'], os.environ['HELLO_FLEET_ID'], 'exported_urdf/stretch.urdf')\n controller_parameters_filename = os.path.join(os.environ['HELLO_FLEET_PATH'], os.environ['HELLO_FLEET_ID'], 'exported_urdf/controller_calibration_head.yaml')\n robot_model = URDF.load(urdf_file)\n\n if args.motion:\n cfg_trajectory = {\n 'joint_left_wheel': [0.0, math.pi],\n 'joint_right_wheel': [0.0, math.pi],\n 'joint_lift': [0.9, 0.7],\n 'joint_arm_l0': [0.0, 0.1],\n 'joint_arm_l1': [0.0, 0.1],\n 'joint_arm_l2': [0.0, 0.1],\n 'joint_arm_l3': [0.0, 0.1],\n 'joint_wrist_yaw': [math.pi, 0.0],\n 'joint_gripper_finger_left': [0.0, 0.25],\n 'joint_gripper_finger_right': [0.0, 0.25],\n 'joint_head_pan': [0.0, -(math.pi / 2.0)],\n 'joint_head_tilt': [0.5, -0.5]\n }\n robot_model.animate(cfg_trajectory=cfg_trajectory)\n elif args.fake:\n # stretch = rb.Robot()\n print('WARNING: Not actually visualizing the current state of the robot. Instead, using FakeRobot, since stretch_body.robot does not yet support Python 3.')\n stretch = FakeRobot()\n stretch.startup()\n stretch_calibrated = stretch.is_calibrated()\n if not stretch_calibrated:\n print('Exiting because the robot has not been calibrated')\n exit()\n\n fid = open(controller_parameters_filename, 'r')\n controller_parameters = yaml.load(fid)\n fid.close()\n stretch_state = StretchState(stretch, controller_parameters)\n cfg = stretch_state.get_urdf_configuration()\n robot_model.show(cfg=cfg)\n stretch.stop()\n else:\n robot_model.show()\n","sub_path":"tools_py3/bin/stretch_urdf_show.py","file_name":"stretch_urdf_show.py","file_ext":"py","file_size_in_byte":8265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"147152210","text":"import pytest\n\nfrom tests.test_resources.helper import get_search\nfrom tests.test_resources.test_settings import TEST_USE_STATIC_DATA\n\n# marks all tests as jobsearch and historical\npytestmark = [pytest.mark.jobsearch, pytest.mark.historical]\n\n\n@pytest.mark.skipif(not TEST_USE_STATIC_DATA, reason=\"depends on a fixed set of ads\")\n@pytest.mark.parametrize(\"query, expected\", [\n ('försäljning/marknad', 3),\n ('försäljning marknad', 12),\n ('försäljning / marknad', 28),\n ('lager/logistik', 19),\n ('lager / logistik', 7),\n ('lager logistik', 137),\n ('psykolog/beteendevetare', 20),\n ('psykolog / beteendevetare', 0),\n ('psykolog beteendevetare', 30),\n ('Affärsutvecklare/exploateringsingenjör', 3),\n ('Affärsutvecklare / exploateringsingenjör', 1),\n ('Affärsutvecklare exploateringsingenjör', 11),\n ('Affärsutvecklare/exploateringsingenjörer', 2),\n ('Affärsutvecklare / exploateringsingenjörer', 1),\n ('Affärsutvecklare exploateringsingenjörer', 11),\n ('barnpsykiatri/habilitering', 1),\n ('barnpsykiatri / habilitering', 0),\n ('barnpsykiatri habilitering', 21),\n ('mentor/kontaktlärare', 0),\n ('mentor / kontaktlärare', 0),\n ('mentor kontaktlärare', 0),\n ('Verktygsmakare/Montör', 17),\n ('Verktygsmakare / Montör', 4),\n ('Verktygsmakare Montör', 38),\n ('Kolloledare/specialpedagog', 18),\n ('Kolloledare / specialpedagog', 0),\n ('Kolloledare specialpedagog', 24),\n ('fritidshem/fritidspedagog', 15),\n ('fritidshem / fritidspedagog', 3),\n ('fritidshem fritidspedagog', 17),\n ('UX/UI Designer', 1),\n ('UX / UI Designer', 1),\n ('UX UI Designer', 1),\n])\ndef test_freetext_search_slash(session, query, expected):\n \"\"\"\n Search with terms that are joined by a slash '/' included (x/y)\n with the terms separately (x y)\n and with a slash surrounded by space (x / y)\n \"\"\"\n params = {'q': query, 'limit': '0'}\n assert get_search(session, params=params)['total']['value'] == expected\n\n\n@pytest.mark.skipif(not TEST_USE_STATIC_DATA, reason=\"depends on a fixed set of ads\")\n@pytest.mark.parametrize(\"query, expected\", [\n ('.NET/C#', 13),\n ('.NET / C#', 7),\n ('.NET C#', 63),\n ('.NET /C#', 2),\n ('.NET/ C#', 9),\n ('.NET', 38),\n ('C#/.net', 12),\n ('C# .net', 63),\n ('C# /.net', 9),\n ('C# / .net', 7),\n ('C#', 47),\n ('C#/.net', 12),\n ('C# .net', 63),\n ('C# /.net', 9),\n ('dotnet', 37)\n])\ndef test_freetext_search_dot_hash_slash(session, query, expected):\n \"\"\"\n Search with terms that are joined by a slash '/' included (x/y)\n with the terms separately (x y)\n and with a slash surrounded by space (x / y)\n for words that have . or # (e.g. '.net', 'c#')\n \"\"\"\n params = {'q': query, 'limit': '0'}\n assert get_search(session, params=params)['total']['value'] == expected\n\n\n@pytest.mark.smoke\n@pytest.mark.parametrize(\"query, expected\", [\n ('programmerare', 132),\n ('Systemutvecklare', 132),\n ('Systemutvecklare/Programmerare', 14),\n ('Systemutvecklare Programmerare', 132),\n ('Systemutvecklare / Programmerare', 17)\n])\ndef test_freetext_search_slash_short(session, query, expected):\n params = {'q': query, 'limit': '0'}\n assert get_search(session, params=params)['total']['value'] == expected\n","sub_path":"tests/api_tests/searching/common/test_slash.py","file_name":"test_slash.py","file_ext":"py","file_size_in_byte":3301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"83406803","text":"import numpy as np\nimport platform\nif platform.system() == \"Darwin\":\n import matplotlib\n matplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\n\nimport settings\n\nREPORT_LOG = {\n 'alphas': [],\n 'norm_model': [],\n 'norm_res': [],\n}\n\ndef readraw(filename):\n f = open(settings.FILENAME, \"r\")\n return np.fromfile(f, dtype=np.float32)\n\ndef readmap(filename):\n a = readraw(filename)\n a = a.reshape(settings.NX, settings.NY)\n return a.T\n\nif __name__ == \"__main__\":\n '''\n # plot real velocity\n raw_map = readmap(filename=settings.FILENAME)\n plt.imshow(\n raw_map, cmap='jet',\n extent=[0, settings.DX*settings.NX, settings.DX*settings.NY, 0],\n )\n a = plt.colorbar()\n a.set_label('$v$')\n plt.title(\"Real Velocity\")\n plt.xlabel(\"$x$\")\n plt.ylabel(\"$y$\")\n plt.savefig(\"real_v.png\")\n '''","sub_path":"Lec07/stt.py","file_name":"stt.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"277157872","text":"'''\nPython definitions used to aid with statistical calculations.\n\n*Methods Overview*\n -> normal_distribution(): Create values for a normal distribution\n -> cumulative_distribution(): Integration udner a PDF\n -> empirical_distribution(): Estimates CDF empirically\n'''\n\nimport numpy as np\nimport xarray as xr\nfrom .logging_util import get_slug, debug, info, warn, error\nimport scipy\n\ndef find_maxima(x, y, method='comp', **kwargs):\n '''\n Finds maxima of a time series y. Returns maximum values of y (e.g heights)\n and corresponding values of x (e.g. times). \n **kwargs are dependent on method.\n \n Methods:\n 'comp' :: Find maxima by comparison with neighbouring values.\n Uses scipy.signal.find_peaks. **kwargs passed to this routine\n will be passed to scipy.signal.find_peaks.\n DB NOTE: Currently only the 'comp' method is implemented. Future\n methods include linear interpolation and cublic splines.\n '''\n if method == 'comp':\n peaks, props = scipy.signal.find_peaks(y, **kwargs)\n return x[peaks], y[peaks]\n\ndef doodson_x0_filter(elevation, ax=0):\n ''' \n The Doodson X0 filter is a simple filter designed to damp out the main \n tidal frequencies. It takes hourly values, 19 values either side of the \n central one and applies a weighted average using:\n (1010010110201102112 0 2112011020110100101)/30.\n ( http://www.ntslf.org/files/acclaimdata/gloup/doodson_X0.html )\n \n In \"Data Analaysis and Methods in Oceanography\":\n \n \"The cosine-Lanczos filter, the transform filter, and the\n Butterworth filter are often preferred to the Godin filter,\n to earlier Doodson filter, because of their superior ability\n to remove tidal period variability from oceanic signals.\"\n \n This routine can be used for any dimension input array.\n \n Parameters\n ----------\n elevation (ndarray) : Array of hourly elevation values.\n axis (int) : Time axis of input array. This axis must have >= 39 \n elements\n \n Returns\n -------\n Filtered array of same rank as elevation.\n ''' \n if elevation.shape[ax] < 39:\n print('Doodson_XO: Ensure time axis has >=39 elements. Returning.')\n return\n # Define DOODSON XO weights\n kern = np.array([1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 2, 0, 1, 1, 0, 2, 1, 1, 2, \n 0,\n 2, 1, 1, 2, 0, 1, 1, 0, 2, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1])\n kern = kern/30\n\n # Convolve input array with weights along the specified axis.\n filtered = np.apply_along_axis(lambda m: np.convolve(m, kern, mode=1), \n axis=ax, arr=elevation)\n\n # Pad out boundary areas with NaNs for given (arbitrary) axis.\n # DB: Is this the best way to do this?? Can put_along_axis be used instead\n filtered = filtered.swapaxes(0,ax)\n filtered[:19] = np.nan\n filtered[-19:] = np.nan\n filtered = filtered.swapaxes(0,ax)\n return filtered\n\n\ndef normal_distribution(mu: float=0, sigma: float=1, \n x: np.ndarray=None, n_pts: int=1000):\n \"\"\"Generates a discrete normal distribution.\n\n Keyword arguments:\n x -- Arbitrary array of x-values\n mu -- Distribution mean\n sigma -- Distribution standard deviation\n \n return: Array of len(x) containing the normal values calculated from\n the elements of x.\n \"\"\"\n if x is None:\n x = np.linspace( mu-5*sigma, mu+5*sigma, n_pts)\n debug(f\"Generating normal distribution for {get_slug(x)}\")\n term1 = sigma*np.sqrt( 2*np.pi )\n term1 = 1/term1\n exponent = -0.5*((x-mu)/sigma)**2\n return term1*np.exp( exponent )\n\ndef cumulative_distribution(mu: float=0, sigma: float=1, \n x: np.ndarray=None, cdf_func: str='gaussian'):\n \"\"\"Integrates under a discrete PDF to obtain an estimated CDF.\n\n Keyword arguments:\n x -- Arbitrary array of x-values\n pdf -- PDF corresponding to values in x. E.g. as generated using\n normal_distribution.\n \n return: Array of len(x) containing the discrete cumulative values \n estimated using the integral under the provided PDF.\n \"\"\"\n debug(f\"Estimating CDF using {get_slug(x)}\")\n if cdf_func=='gaussian': #If Gaussian, integrate under pdf\n pdf = normal_distribution(mu=mu, sigma=sigma, x=x)\n cdf = [np.trapz(pdf[:ii],x[:ii]) for ii in range(0,len(x))]\n else: \n raise NotImplementedError\n return np.array(cdf)\n\ndef empirical_distribution(x, sample):\n \"\"\"Estimates a CDF empirically.\n\n Keyword arguments:\n x -- Array of x-values over which to generate distribution\n sample -- Sample to use to generate distribution\n \n return: Array of len(x) containing corresponding EDF values\n \"\"\"\n debug(f\"Estimating empirical distribution with {get_slug(x)}\")\n sample = np.array(sample)\n sample = sample[~np.isnan(sample)]\n sample = np.sort(sample)\n edf = np.zeros(len(x))\n n_sample = len(sample)\n for ss in sample:\n edf[x>ss] = edf[x>ss] + 1/n_sample\n return xr.DataArray(edf)","sub_path":"coast/stats_util.py","file_name":"stats_util.py","file_ext":"py","file_size_in_byte":5156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"566083401","text":"'''SudoSimu - Module techchrcga - technique de résolution \"chiffre/rang-colonne\"\nglobale sur la grille entière pour tous les chiffres.\n\nCe module contient la classe TechChRCgridAll, qui applique par répétition les\ntechniques de résolution \"chiffre/rang-colonne\" sur toute la grille et pour\ntous les chiffres. TechChRCgridAll enchaîne pour chaque chiffre de 1 à 9 la\ntechnique semi-globale réalisée par la classe TechChRCgrid.\n\nLes instances de cette classe représentent des raisonnement systématiques\net itératifs de résolution, qui font globalement partie de la pensée du joueur,\ntout en étant autonomes par leur côté systématique. Le raisonnement évolue étape\npar étape à chaque appel de la méthode apply(), et retourne des demandes\nd'observation de la grille et de placement de chiffres. Au niveau global de la\npensée, c'est la partie AI (classe SudoThinkAI) qui décide d'appliquer une\ntechnique et qui instancie la classe, puis c'est la partie pensée logique\n(classe SudoThinking) qui organise l'enchaînement et appelle la méthode apply().\n\nDernière mise à jour : 11/10/2017\nVérification de complétude des modifications -suppr-mem- et -split-\n'''\n\nif __name__ in (\"__main__\", \"techchrcga\", \"techchrc.techchrcga\"):\n #imports des modules de la simulation\n import sudoui as ui\n import sudorules as rules\n from sudorules import Sudoku_Error\n from sudomemory import SudoMemory\n import sudogridview as gridview\n from sudotest import *\n #import des modules de techniques locales de résolution\n from techchrc.techchrcg import TechChRCgrid\nelif __name__ == \"sudosimu.techchrc.techchrcga\":\n #imports des modules de la simulation\n from sudosimu import sudoui as ui\n from sudosimu import sudorules as rules\n from sudosimu.sudorules import Sudoku_Error\n from sudosimu.sudomemory import SudoMemory\n from sudosimu import sudogridview as gridview\n from sudosimu.sudotest import *\n #import des modules de techniques locales de résolution\n from sudosimu.techchrc.techchrcg import TechChRCgrid\nelse:\n raise Exception(\"Impossible de faire les imports dans le module techchrcga.\")\n\n\nclass TechChRCgridAll():\n '''Classe qui encapsule la technique de résolution \"chiffre/rang-colonne\"\n sur la grille entière et pour tous les chiffres.\n '''\n\n def __init__(self, mem, args=None):\n '''Initialise l'instance en utilisant la mémoire du joueur 'mem'.\n Le paramètre 'args' est inutilisé.\n '''\n TEST.display(\"techchrcgridall\", 3, \"TechChRCgridAll - Dans __init__()\")\n TEST.display(\"techchrcgridall\", 2, \\\n \"\\nNouvelle instance de la technique TechChRCgridAll.\")\n self._mem = mem\n #Initialiser les données en mémoire de la résolution\n self._clear_tech_mem()\n #init contrôle d'exécution (en_cours, finished etc.)\n self._finished = False #uniquement pour éviter une erreur de code\n self._resume = False #indique appel de resume() au lieu de apply()\n self._encours = False\n self._initOk = True\n return\n\n def _clear_tech_mem(self):\n '''Initialise les données d'application de la technique par le joueur\n dans sa mémoire.\n '''\n TEST.display(\"techchrcgridall\", 3, \"TechChRCgridAll - \"\\\n \"Dans _clear_tech_mem()\")\n mem = self._mem\n mem.memorize(\"techchrcgridall_chiffre\", 0, self)\n# mem.memorize(\"techchrcgridall_isqrow\", 0, self)\n# mem.memorize(\"techchrcgridall_isqcol\", 0, self)\n mem.memorize(\"techchrcgridall_techclass\", None, self)\n mem.memorize(\"techchrcgridall_techloc\", None, self)\n mem.memorize(\"techchrcgridall_techlocname\", \"\", self)\n mem.memorize(\"techchrcgridall_nbplctot\", 0, self)\n mem.memorize(\"techchrcgridall_finished\", False, self)\n return True\n\n#### import des fonctions d'étapes successives de l'algorithme d'application\n if __name__ in (\"__main__\", \"techchrcg\", \"techchrc.techchrcga\"):\n from techchrc.techchrcga2 import _start_apply\n from techchrc.techchrcga2 import _apply_techloc\n from techchrc.techchrcga2 import _techloc_end\n from techchrc.techchrcga2 import _next_techloc\n from techchrc.techchrcga2 import _finish_apply\n from techchrc.techchrcga2 import _newGridTechInst\n elif __name__ == \"sudosimu.techchrc.techchrcga\":\n from sudosimu.techchrc.techchrcga2 import _start_apply\n from sudosimu.techchrc.techchrcga2 import _apply_techloc\n from sudosimu.techchrc.techchrcga2 import _techloc_end\n from sudosimu.techchrc.techchrcga2 import _next_techloc\n from sudosimu.techchrc.techchrcga2 import _finish_apply\n from sudosimu.techchrc.techchrcga2 import _newGridTechInst\n else:\n raise Exception(\"Impossible de faire les imports dans le module techchrcga.\")\n####\n \n def apply(self):\n '''Méthode d'application de cette technique. Elle est appelée\n répétitivement pour faire progresser la technique étape par étape.\n '''\n TEST.display(\"techchrcgridall\", 3, \"TechChRCgridAll - Dans apply()\")\n assert self._initOk\n mem = self._mem\n #si la technique est terminée, sortir tout de suite\n if self._finished is True:\n TEST.display(\"techchrcgridall\", 2,\n \"Technique déjà terminée.\")\n return (\"end\", None)\n\n #gérer la répétition de l'exécution\n if self._encours is not True:\n self._encours = True\n TEST.display(\"techchrcgridall\", 1, \"Technique de résolution \"\\\n \"\\'Chiffre/rang-colone\\' sur la grille entière \")\n r = self._start_apply()\n else:\n #déjà une résolution en cours, la continuer\n TEST.display(\"techchrcgridall\", 2, \\\n \"TechChRCgridAll - suite de la même technique\")\n r = self._apply_techloc()\n TEST.display(\"techchrcgridall\", 2, \"TechChRCgridAll - apply() retourne : {0}\" \\\n .format(r))\n return r\n\n def resume(self):\n '''Méthode de résolution alternative appelée par Thinking dans le cas\n où la technique est continuée après une mise en attente du fait\n de l'imbrication d'autres techniques. Permet de faire des vérifications\n de cohérence des données mémorisées pendant la mise en attente,\n avant de reprendre l'application.\n '''\n##ATTENTION : pour le moment, ne fait que répercuter 'resume' au lieu de 'apply'\n##aux appels des techniques locales.\n##Il faudra plus tard modifier cette méthode pour prendre en compte\n##la possibilité réelle d'oubli de l'avancement, si la technique est restée\n##longtemps en standby à cause d'imbrications.\n\n TEST.display(\"techchrcgridall\", 3, \"TechChRCgridAll - dans resume()\")\n assert self._initOk\n assert self._encours #la première itération doit avoir été apply()\n #indique l'état \"resume\" avant de passer à la résolution normale\n self._resume = True\n r = self.apply()\n TEST.display(\"techchrcgridall\", 3, \"TechChRCgridAll - retour à resume()\")\n #remet l'indicateur à zéro pour les prochaines fois\n self._resume = False\n return r\n\n\n def obsFound(self, found):\n '''Transmet le résultat d'observation à la technique locale en cours\n qui a demandé cette observation. Traite le cas particulier où la\n tech. locale retourne \"end\", qu'il faut gérer globalement.\n '''\n TEST.display(\"techchrcgridall\", 3, \"TechChRCgridAll - dans obsFound()\")\n assert self._initOk\n mem = self._mem\n #si la technique est déjà terminée, retourne \"end\"\n if self._finished is True:\n return (\"end\", None)\n TEST.display(\"techchrcgridall\", 3, \"Résultat d'observation : {0}\"\\\n .format(found))\n #transmettre le résultat à la technique locale en cours\n techloc = mem.recall(\"techchrcgridall_techloc\", self)\n r = techloc.obsFound(found)\n TEST.display(\"techchrcgridall\", 3, \"TechChRCgridAll - retour à obsFound()\")\n TEST.display(\"techchrcgridall\", 3, \"TechChRCgridAll - retour de \"\\\n \"obsFound() de la technique {0} : {1}\"\\\n .format(techloc.techName(), r))\n #si la technique locale retourne \"end\", traiter ce cas tout de suite\n if r[0] == \"end\":\n endDetails = r[1]\n TEST.display(\"techchrcgridall\", 3, \"obsFound : la technique locale \"\\\n \"a renvoyé 'end' \")\n r = self._techloc_end(mem, endDetails)\n return r\n \n def placeOk(self, placed=None):\n '''Prend connaissance du succès d'un placement par la technique. Traite\n le cas particulier où la tech. locale retourne \"end\", qu'il faut\n gérer au niveau de cette technique globale\n '''\n TEST.display(\"techchrcgridall\", 3, \"TechChRCgridAll - dans placeOk()\")\n assert self._initOk\n mem = self._mem\n #si la technique est déjà terminée, retourne \"end\"\n if self._finished is True:\n return (\"end\", None)\n TEST.display(\"techchrcgridall\", 3, \"Résultat de placement : {0}\"\\\n .format(placed))\n #transmettre le résultat à la technique locale en cours\n techloc = mem.recall(\"techchrcgridall_techloc\", self)\n r = techloc.placeOk(placed)\n TEST.display(\"techchrgridall\", 3, \"TechChRCgridAll - retour à placeOk()\")\n TEST.display(\"techchrcgridall\", 3, \"TechChRCgridAll - retour de \"\\\n \"placeOk() de la technique {0} : {1}\"\\\n .format(techloc.techName(), r))\n #si la technique locale retourne \"end\", traiter ce cas tout de suite\n if r[0] == \"end\":\n endDetails = r[1]\n TEST.display(\"techchrcgridall\", 3, \"placeOk : la technique locale \"\\\n \"{0} a renvoyé 'end' \".format(techloc.techName()))\n r = self._techloc_end(mem, endDetails)\n return r\n \n def abort(self):\n '''Arrêt d'exécution de la technique avant sa fin et marque la technique\n comme terminée. Il faudra appeler 'reset()' avant de la relancer.\n Retourne le nombre d'actions effectuées avant l'arrêt\n '''\n TEST.display(\"techchrcgridall\", 3, \"TechChRCgridAll - dans abort()\")\n assert self._initOk\n mem = self._mem\n TEST.display(\"techchrcgridall\", 1, \"Abandon de la technique en cours\")\n plctot = mem.recall(\"techchrcgridall_nbplctot\", self)\n TEST.display(\"techchrcgridall\", 1, \\\n \"Nombre total de chiffres placés : {0}\" \\\n .format(plctot))\n self._finish_apply()\n self._finished = True\n self._encours = False\n return (\"abort\", plctot)\n\n def reset(self):\n '''Rénitialise l'instance la technique. Ne devrait pas être utilisé\n en version de production car il faut utiliser à chaque fois une\n nouvelle instance de technique.\n Mais utile en débuggage et tests.\n '''\n TEST.display(\"techchrcgrid\", 3, \"TechChRCgrid - dans reset()\")\n mem = self._mem\n self._clear_tech_mem(mem) #la mémoire du joueur\n self._init_tech(mem) #variables d'exécution de la technique\n self._initOk = True\n return True\n \n def status(self):\n '''Retourne l'état d'avancement de la technique'''\n TEST.display(\"techchrcgridall\", 3, \"Fonction status()\")\n assert self._initOk\n mem = self._mem\n if self._finished is True:\n r = (\"end\", None)\n else:\n if self._encours is False:\n r = (\"inactive\",)\n else:\n chiffre = mem.recall(\"techchrcgridall_chiffre\", self)\n rcs = mem.recall(\"techchrcgridall_rcs\", self)\n isqrow = mem.recall(\"techchrcgridall_isqrow\", self)\n isqcol = mem.recall(\"techchrcgridall_isqcol\", self)\n if rcs == \"row\":\n ibloc = isqrow\n elif rcs == \"col\":\n ibloc = isqcol\n else:\n ibloc = None\n details = ((\"chiffre\", chiffre),\n (\"rcs\", rcs),\n (\"rang/colonne\", ibloc))\n r = (\"active\", details)\n TEST.display(\"techchrcgridall\", 3, \"Statut de la résolution : {0}\" \\\n .format(r) )\n return r\n\n def techName(self):\n return \"TechChRCgridAll\"\n\n @property\n def name(self):\n return self.techName()\n\n def techClassName():\n return \"TechChRCgridAll\"\n \n def instName(self):\n return \"instance de {0}\".format(self.techName())\n\n def __str__(self):\n return \"Technique de résolution 'Chiffre/rang-colonne' sur toute la \"\\\n \"grille et pour tous les chiffres.\"\n\n\n##TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \n##TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \n\nif __name__ == \"__main__\":\n\n import sudotestall\n testlevel = 3\n TEST.levelAll(testlevel)\n ui.display(\"Tous les niveaux de test sont à {0}\".format(testlevel))\n\n #mode GUI\n ui.UImode(ui.GUI)\n TEST.displayUImode(MODE_BOTH, 1)\n\n import sudogrid\n from sudogridview import SudoGridView\n \n ui.display(\"\\nTest du module techrcg.py\")\n ui.display(\"Technique de résolution TechChRCgridAll\")\n ui.display(\"------------------------------------\\n\")\n list9 = [2,5,0,6,8,0,0,3,4]\n ui.display(\"Choisir un fichier de test\")\n fich = ui.sudoNumTestFich()\n if not fich:\n ui.display(\"Abandon\")\n exit()\n ui.display(\"Fichier choisi : {0}\\n\".format(fich))\n vals = ui.sudoFichReadLines(fich)\n ui.display(\"Variable SudoBloc : bl\")\n bl = sudogrid.SudoBloc()\n ui.display(\"Variable SudoGrid : gr\")\n gr = sudogrid.SudoGrid()\n gr.fillByRowLines(vals)\n grid = gr\n ui.display(\"Grille test choisie : gr = \")\n gr.show()\n ui.displayGridAll(grid)\n \n ui.display(\"\\nVariable SudoMemory : mem\")\n mem = SudoMemory()\n ui.display(\"Variable SudoGridView : view\")\n view = SudoGridView(grid)\n ui.display(\"Création de 2 instances de technique de résolution.\")\n ui.display(\"Instance de technique TechChRCgridAll : tech1 et tech2\")\n tech1 = TechChRCgridAll(mem)\n tech2 = TechChRCgridAll(mem)\n ui.display(\"\\nTEST au niveau 3\\n\")\n TEST.test(\"techchrcgridall\",3)\n TEST.test(\"loop\", 3)\n ui.sudoPause()\n\ndef reset():\n '''remet la grille de test dans son état initial et renouvelle les\n instances 'mem' et 'tech'.\n '''\n global mem\n mem = SudoMemory()\n global tech1\n tech1 = TechChRCgridAll(mem)\n global tech2\n tech2 = TechChRCgridAll(mem)\n gr.fillByRowLines(vals)\n gr.fillByRowLines(vals)\n ui.displayGridClear()\n ui.displayGridAll(grid)\n\ndef loopStep(tech):\n '''Exécute une itération de la boucle de pensée ROMA avec l'instance\n de TechChRCgridAll indiquée en argument.\n '''\n if view.isCompleted():\n ui.display(\"loopTech - Grille terminée, c'est gagné !\")\n return \"win\"\n \n r = tech.apply(mem)\n action = r[0]\n TEST.display(\"loop\", 2,\n \"loopStep - Résultat de tech.apply() : {0}\".format(r))\n status = tech.status(mem)\n TEST.display(\"loop\", 3,\n \"loopStep - statut d'avancement de tech: {0}\".format(status))\n if action == \"observe\":\n pattern = r[1]\n found = view.lookup(pattern)\n mem.memorizeObs(found, tech)\n TEST.display(\"loop\", 2,\n \"loopStep - Résultat de view.lookup() : {0}\".format(found))\n tech.obsFound(mem, found)\n elif action == \"place\":\n placement = r[1]\n (row, col, val) = placement\n TEST.display(\"loop\", 1, \"loopStep - Placement de {0} en ({1}, {2})\"\\\n .format(val, row, col))\n valid = view.place(placement)\n TEST.display(\"loop\", 2,\n \"loopStep - Résultat de view.place() : {0}\".format(r))\n tech.placeOk(mem, valid)\n ui.displayGridPlace(grid, row, col)\n TEST.display(\"loop\", 2,\n \"loopStep - Action exécutée par la tech : {0}\".format(action))\n return action\n \ndef loopTech(tech, pause=False):\n '''Applique itérativement la technique indiquée en bouclant loopStep()\n jusqu'à ce que la technique retourne 'end' pour indiquer sa fin. Permet\n de demander une pause clavier à chaque boucle.\n '''\n TEST.display(\"loop\", 1,\n \"Boucle de résolution de TechChRCgridAll sur la grille \"\\\n \"entière et pour tous les chiffres.\")\n global grid\n iter = 0\n while True:\n\n TEST.display(\"loop\", 2, \"\\nloopTech - Début de boucle\")\n if view.isCompleted():\n ui.display(\"loopTech - Grille terminée, c'est gagné !\")\n return\n action = loopStep(tech)\n #éviter une boucle infinie\n iter +=1\n if iter > 200:\n ui.displaySTD(\"loopTech - STOP, plus de 100 itérations de boucle !!!\")\n break\n #fin de la technique\n if action == \"end\":\n break\n #si une pause de boucle est demandée \n if pause:\n r = ui.sudoPause(True)\n if r:\n ui.displaySTD(\"\")\n else: #Ctrl-C ou Ctrl-D\n ui.display(\"Interruption clavier\")\n break\n continue\n\n if view.isCompleted():\n ui.display(\"loopTech - Grille terminée, c'est gagné !\")\n return\n\n","sub_path":"sudosimu/techchrc/techchrcga.py","file_name":"techchrcga.py","file_ext":"py","file_size_in_byte":18012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"546177716","text":"import os\n\nclass Prefs:\n\tdef __init__(self, pref_file):\n\t\tself.prefs = {}\n\t\tself.pref_file = pref_file\n\n\tdef check_prefs(self):\n\t\tif os.path.exists(self.pref_file):\n\t\t\tself.open_prefs()\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\tdef open_prefs(self):\n\t\twith open(self.pref_file, mode = \"r\") as config_file:\n\t\t\tself.raw_config = config_file.read().splitlines()\n\t\tfor line in self.raw_config:\n\t\t\tequals_index = line.index(\"=\")\n\t\t\tself.prefs[line[:equals_index]] = line[equals_index+1:].strip()\n\t\treturn self.prefs\n\n\nif __name__ == \"__main__\":\n\tprefs = Prefs(\"prefs.ini\")\n\tprint(prefs.prefs)","sub_path":"prefs.py","file_name":"prefs.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"229730132","text":"import bpy\n\ndef GetSceneGroups(scene, hasObjects):\n \"\"\"\n Returns all groups that belong to the scene, by searching through all objects belonging in it.\n \"\"\"\n groups = []\n\n for item in scene.objects:\n for group in item.users_group:\n groupAdded = False\n\n for found_group in groups:\n if found_group.name == group.name:\n groupAdded = True\n\n if hasObjects is False or len(group.objects) > 0:\n if groupAdded == False:\n groups.append(group)\n\n return groups\n\ndef GetObjectGroups(objects):\n \"\"\"\n Returns a unique list of all groups that belong to the given object list,\n by searching through all objects belonging in it.\n \"\"\"\n groups_found = []\n groups_found.append(currentGroup)\n\n for item in objects:\n for group in item.users_group:\n groupAdded = False\n\n for found_group in groups_found:\n if found_group.name == group.name:\n groupAdded = True\n\n if groupAdded == False:\n groups_found.append(group)\n\n return groups_found","sub_path":"Capsule/Capsule/tk_utils/groups.py","file_name":"groups.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"356463703","text":"import parser\nimport unittest\nimport json\n\n\nclass NestedClass:\n def __init__(self, inner_objects=None):\n self.inner_objects = inner_objects\n\n\nclass TestParse(unittest.TestCase):\n\n def test_two_way_list(self):\n list = [\"Wow\", None, \"Boom\", 5, False, 4.2]\n\n json = parser.to_json(list)\n restored_list = parser.from_json(json, globals())\n\n self.assertEqual(list, restored_list)\n\n def test_nested_class(self):\n nested_class = NestedClass([NestedClass(), NestedClass()])\n\n json = parser.to_json(nested_class)\n restored_class = parser.from_json(json, globals())\n\n self.assertEqual(len(nested_class.inner_objects),\n len(restored_class.inner_objects))\n\n def test_restore_type(self):\n some_class = NestedClass()\n\n json = parser.to_json(some_class)\n restored_class = parser.from_json(json, globals())\n\n self.assertEqual(type(some_class), type(restored_class))\n\n def test_predefined_json(self):\n some_class = NestedClass()\n\n json = parser.to_json(some_class)\n\n self.assertEqual(\n json, \"{ \\\"py/object\\\": \\\"NestedClass\\\", \\\"inner_objects\\\": null }\")\n\n def test_broken_json(self):\n with self.assertRaises(Exception):\n parser.from_json(\"Not a Json\", globals())\n \n def test_default_dumps_comparison(self):\n some_object = [\"Hello\", False, 4]\n\n default_json = json.dumps(some_object).replace(\" \", \"\")\n my_json = parser.to_json(some_object).replace(\" \", \"\")\n\n self.assertEqual(default_json, my_json)\n\n def test_default_loads_comparison(self):\n some_object = [None, 5, [\"hey\", \"Ouch\"]]\n\n default_json = json.dumps(some_object)\n my_json = parser.to_json(some_object)\n\n default_restored = json.loads(default_json)\n my_restored = parser.from_json(my_json, globals())\n\n self.assertEqual(default_restored, my_restored)\n\n\ndef tests_suite():\n suite = unittest.TestSuite()\n suite.addTest(unittest.makeSuite(TestParse, 'test'))\n return suite\n","sub_path":"Solutions/Task2/853502_Nikita_Andrasovich/JsonParser/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"208937668","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import odeint\nclass DE(object):\n def __init__(self, a, b, eps, s, u0, v0,t,s_t):\n self.a = a\n self.b = b\n self.eps = eps\n self.s = s\n self.s_t = s_t\n self.u0 = u0\n self.v0 = v0\n self.t = t\n 'f(y,t) is dy/dt, where y is a vector, y[0] and y[1]'\n 'each one representing one of the coupled ODEs'\n def Solve(self):\n 'solve for single pulse'\n def s(t):\n if t < 5:\n return 0.06\n else:\n return 0\n def f(y, t):\n 'define ui as du/dt, define vi as dv/dt'\n ui = y[0]\n vi = y[1]\n 'two FH equations'\n f0 = (ui*(ui-self.a)*(1-ui)) - vi + s(t)\n f1 = self.eps*(ui - (self.b*vi))\n return [f0, f1]\n 'make initial condition s into vector'\n y0 = [self.u0, self.v0]\n 'solve the DEs odeint(function, initial vector, timegrid)'\n soln = odeint(f, y0, self.t)\n 'u is soln for y[0], v for y[1]'\n self.u = soln[:, 0]\n self.v = soln[:, 1]\n def Solve2(self):\n 'solve for cells taking s(t) from neighbouring cells'\n def s(t):\n 't is sampled in a weird way, need integer values to get s_t values'\n if type(self.s_t) is list:\n i = int(t)\n 'sometimes i can go out of range, slight fix added here'\n if i >= len(self.t):\n i = len(self.t)-1\n return self.s_t[i]\n else:\n return self.s_t\n def f(y, t):\n 'define ui as du/dt, define vi as dv/dt'\n ui = y[0]\n vi = y[1]\n 'two FH equations'\n f0 = (ui*(ui-self.a)*(1-ui)) - vi + s(t)\n f1 = self.eps*(ui - (self.b*vi))\n return [f0, f1]\n 'make initial condition s into vector'\n y0 = [self.u0, self.v0]\n 'solve the DEs odeint(function, initial vector, timegrid)'\n soln = odeint(f, y0, self.t)\n 'u is soln for y[0], v for y[1]'\n self.u = soln[:, 0]\n self.v = soln[:, 1]\n def Plot(self):\n plt.ion()\n plt.rcParams['figure.figsize'] = 10, 8\n plt.figure()\n plt.plot(self.t, self.u, label='u')\n plt.plot(self.t, self.v, label='v')\n plt.xlabel('Dimensionless Time')\n plt.ylabel('Fitzhugh-Nagumo Variable')\n plt.grid()\n plt.show(block=True)\n","sub_path":"solvePlot.py","file_name":"solvePlot.py","file_ext":"py","file_size_in_byte":2525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"131081482","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: batek\n\"\"\"\n\nimport pandas as pd\n\nclass Sensor(object):\n \n \n def __init__(self, name):\n self._sensorName = name\n self._battery = Battery(100, 1)\n print (\"Sensor \" + name + \" created\")\n \n def SetDictOfData(self, data):\n self._sensorData = data\n \n def GetOutputBasedOnTimestamp(self, timestamp):\n hasBattery = self._battery.dischargePower(timestamp)\n return self._sensorData[timestamp] if hasBattery else \"Battery discharged!\"\n \n def batteryLeft(self):\n return self._battery.capacityLeft()\n \n\nclass ExcelFileImporter(object):\n \n def __init__(self, fileName):\n self._fileName = fileName\n \n '''\n Rturns DataFrame object,\n which is first sheet in given excel file\n '''\n def loadFile(self):\n file = pd.ExcelFile(self._fileName)\n return file.parse(file.sheet_names[0])\n \n \n'''\n\nClass for carrying global data.\nvariables intended to use as static\n'''\nclass DTO(object):\n _times = None\n \n \n \nclass DataInitializer(object):\n \n def __init__(self, excelFileName):\n self._excelFileName = excelFileName\n print (\"Data initialization begins!\")\n \n def LOadDataAndReturnSensors(self):\n \n sensors = []\n excelFile = ExcelFileImporter(self._excelFileName)\n importer = excelFile.loadFile()\n \n '''\n 0 column - index\n 1 column - TimeStamp\n \n 2 ... N - Sensor\n '''\n \n timestamps = importer[importer.columns[1]]\n timestamps = timestamps[1:]\n \n # store defined times for later use\n DTO._times = timestamps\n \n for i in range(2, len(importer.columns)):\n \n nSensor = Sensor(importer.columns[i])\n sensorData = importer[importer.columns[i]]\n \n sensorDict = dict(zip(timestamps, sensorData[1:]))\n \n nSensor.SetDictOfData(sensorDict)\n \n sensors.append(nSensor)\n \n return sensors\n \nclass Battery(object):\n \n def __init__(self, capacity= 100, energyStep= 1):\n self._capacity = capacity\n self._energyStep = energyStep\n self._lastTime = -1\n self._firstTimeCheck = True\n \n # returns true, if there is power left\n def dischargePower(self, time):\n if self._firstTimeCheck:\n self._capacity -= self._energyStep\n self._lastTime = time\n self._firstTimeCheck = False\n else:\n timeDiff = time - self._lastTime\n self._capacity -= self._energyStep\n self._lastTime = time\n return self._capacity > 0\n \n def capacityLeft(self):\n return self._capacity\n \n\nclass RunSimulation(object):\n \n def __init__(self,excelDataPath, verbose = False, toFile=False, fileName=\"\"):\n self._excelDataPath = excelDataPath\n self._verbose = verbose\n self._printToFile = toFile\n self._fileName = fileName\n if self._printToFile:\n if self._fileName is \"\":\n self._fileName = \"sensorOutput.txt\"\n self._file = open(self._fileName, \"w\")\n print(\"simulatin initalized!\")\n \n def printV(self, text):\n if self._verbose:\n if self._printToFile:\n self._file.write(text + \"\\n\") \n else:\n print(text)\n \n def closeFileOutput(self):\n if self._printToFile:\n self._file.close()\n \n \n def runSimulation(self):\n dataIOnitializer = DataInitializer(self._excelDataPath)\n sensorList = dataIOnitializer.LOadDataAndReturnSensors()\n \n for time in DTO._times:\n \n for sensor in sensorList:\n \n self.printV(sensor._sensorName + \";CO2_level:\" + \";battery_left:\" + str(sensor.batteryLeft()))\n \n self.closeFileOutput()\n \n\n##########################################################################################################\nxslPath = r\"C:\\Users\\batiha\\Downloads\\Data for UNI Ostrava\\0010 CO-Sensorvalues on event base.xlsx\"\n\nsimulation = RunSimulation(xslPath, True, True) \n\nsimulation.runSimulation()\n \n \n \n \n \n\n\n\n\n\n\n\n","sub_path":"Simulator.py","file_name":"Simulator.py","file_ext":"py","file_size_in_byte":4407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"426962952","text":"'''\n# Das Ziel des Programms: RSA-AES Encryption Schema\n# Date: 10.Juni 2020\n# Die Sprache des Programms: Python\n'''\nimport sys as sys\nimport re as re\nimport linecache as linecache\nimport sympy as sp\nimport math as math\n'''\nSteps to follow:\n1. Input n\n2. Get f1 and f2 where n = f1 * f2\n3. Get phi_n The Euler Totient function where phi_n = (p-1) * (q-1)\n4. Get Private Key d where e * d mod phi_n = 1\n5. Get the key k where c^d mod n = k\n6. Use k to decrypt the message \n'''\n########################################################################################################################\n# Step 1: Input the basic parameters\ntxt_file = \"/path/to/input/file\"\n\n# Step 1.1: Get the Public RSA Key n value (in int)\npub_rsa_key_n = linecache.getline(txt_file, 1)\npub_rsa_key_n = re.sub('[n=]', '', pub_rsa_key_n) # remove \"n=\" from the text before storing in the string\npub_rsa_key_n = int(pub_rsa_key_n)\nprint(\"Public RSA Key (n): \", pub_rsa_key_n)\n\n# Step 1.2: Get the Public RSA Key e value (in int)\npub_rsa_key_e = linecache.getline(txt_file, 3)\npub_rsa_key_e = re.sub('[e=]', '', pub_rsa_key_e)\npub_rsa_key_e = int(pub_rsa_key_e)\nprint(\"Public RSA Key (e): \", pub_rsa_key_e)\n\n# Step 1.3: Get the Encrypted Session Key s value (in int)\nenc_sess_key = linecache.getline(txt_file, 5)\nenc_sess_key = re.sub('[s=]', '', enc_sess_key)\nenc_sess_key = int(enc_sess_key)\nprint(\"Encrypted session key (s): \", enc_sess_key)\n\n# Step 1.4: Get the Encrypted message c text (in Hex but stored as string)\ncipher_msg = linecache.getline(txt_file, 7)\ncipher_msg = re.sub('[c=]', '', cipher_msg)\nprint(\"Cipher text is: \", cipher_msg)\n########################################################################################################################\n# Step 2: Find the factors f1 and f2 (Prime factors of 'n')\nf1, f2 = sp.ntheory.factorint(pub_rsa_key_n) # returns the two factors\nif (sp.isprime(f1) & sp.isprime(f2)):\n print(\"The two PRIME factors for the given 'n' are: \")\nelse:\n print(\"The two factors for the given 'n' are NOT PRIME. \")\nprint(\"Factor 1:\", f1)\nprint(\"Factor 2:\", f2)\n########################################################################################################################\n# Step 3: Find phi_n (Euler Totient function)\nphi_n = (f1 - 1) * (f2 - 1)\nprint(\"Value of Phi(n) is:\", phi_n)\n########################################################################################################################\n# Step 4: Find Private Key priv_key (using Extended Euclids Algorithm)\n# Here the program written in Julia is called.\n# The Julia program calculates the private key d\n# and stores the value d in j_code_out\n# This part of code was written in Julia because\n# Python was not able to handle big float values\nprint(\"Run the Julia program (finding_d_rsa.jl) to obtain the value of d\")\nd = int(input(\"Enter the value of d obtained from the Julia program: \"))\n########################################################################################################################\n# Step 5: Find key\nkey_dec = pow(enc_sess_key, d, pub_rsa_key_n) # key obtained here is in decimal\nkey_hex = hex(key_dec).split('x')[-1] # converted the key to hex\nprint(\"Private Key:\", key_hex)\n########################################################################################################################\n# Step 6: Using this key, decrypt the text on Cryptool 2\n","sub_path":"rsa_ciffer.py","file_name":"rsa_ciffer.py","file_ext":"py","file_size_in_byte":3409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"187006618","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport sklearn.preprocessing as sk_preprocessing\nimport sklearn.decomposition as sk_decomposition\nimport numpy as np\nimport sklearn.linear_model as sk_linear\nimport sklearn.model_selection as sk_model_selection\n\n\ndiabetes_df = pd.read_csv(\"data/pima-indians-diabetes.csv\")\n\nX = diabetes_df[[\"Pregnancies\", \"Glucose\", \"BloodPressure\", \"SkinThickness\", \"Insulin\", \"BMI\",\n \"DiabetesPedigreeFunction\", \"Age\"]]\ny = diabetes_df[\"Class\"]\n\nstandard_scaler = sk_preprocessing.StandardScaler()\nX = standard_scaler.fit_transform(X)\n\nfor n_components in reversed(range(1, 8)):\n principal_components = sk_decomposition.PCA(n_components=n_components).fit_transform(X)\n cv_diabetes_log_model = sk_linear.LogisticRegression()\n cv_diabetes_log_model_quality = sk_model_selection.cross_val_score(cv_diabetes_log_model, principal_components,\n y, cv=4, scoring=\"accuracy\")\n print(f\"\\nFor {n_components} components quality: \")\n print(np.mean(cv_diabetes_log_model_quality))\n\npca_all_components = sk_decomposition.PCA()\npca_all_components.fit(X)\n\nprint(\"\\nExplained variance ratio:\")\nprint(pca_all_components.explained_variance_ratio_)\n\ncomponents = list(range(1, pca_all_components.n_components_ + 1))\nplt.plot(components, np.cumsum(pca_all_components.explained_variance_ratio_), marker=\"o\")\nplt.xlabel(\"Number of components\")\nplt.ylabel(\"Explained variance\")\nplt.ylim(0, 1.1)\n\nplt.show()\n","sub_path":"bach13_3.py","file_name":"bach13_3.py","file_ext":"py","file_size_in_byte":1521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"599734340","text":"import os\nimport json\nimport yaml\nimport click\n\nfrom mcutk.projects_scanner import find_projects\n\n\n@click.command('scan', short_help='projects scanner')\n@click.argument('path', required=True, type=click.Path(exists=True))\n@click.option('-o', '--output', type=click.Path(exists=False), help='dump scan results to file, file format support: json or yml.')\n@click.option('--dapeng', is_flag=True, default=False, hidden=True, help='dump for dapeng style, casfile.yml')\ndef cli(path, output, dapeng):\n \"\"\"Scan projects from specificed directory and dump to file(json or yml).\"\"\"\n\n projects, count = find_projects(path, True)\n dataset = list()\n\n if output:\n extension = os.path.basename(output).split(\".\")[-1]\n for tname, plist in projects.items():\n for project in plist:\n dataset.append(project.to_dict())\n\n if extension in ('yml', 'yaml'):\n with open(output, 'w') as file:\n yaml.safe_dump(dataset, file, default_flow_style=False)\n else:\n with open(output, 'w') as file:\n json.dump(dataset, file)\n\n # elif format == 'dapeng':\n # for project in projects:\n # if project.path\n # else:\n # pass\n\n click.echo(\"output file: %s\" % output)\n","sub_path":"mcutk/commands/scan.py","file_name":"scan.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"137689996","text":"import datetime, decimal, os\nimport json\nimport authorize\nimport stripe\n\nstripe.api_key = os.getenv('STRIPE_SECRET_KEY') \n\n_PRICE_ID_LIGHT = os.getenv('STRIPE_PRICE_ID_LIGHT')\n_PRICE_ID_PREMIUM = os.getenv('STRIPE_PRICE_ID_PREMIUM')\n\n_EVENT_KEY_PATH_PARAMETER = 'pathParameters'\n_EVENT_KEY_QUERY_STRING_PARAMETER = 'queryStringParameters'\n_EVENT_KEY_HTTP_METHOD = 'httpMethod'\n_CALLBACK_URL = 'callback_url'\n_PARAM_KEY_PRICE_TYPE = 'price_type'\n_PRICE_TYPE_LIGHT = 'light'\n_PRICE_TYPE_PREMIUM = 'premium'\n\n\n_RESPONSE_303 = {\n 'statusCode': 303,\n 'headers': {\n 'Access-Control-Allow-Headers': 'Content-Type',\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'OPTIONS,POST,GET'\n }\n }\n\n_RESPONSE_400 = {\n 'statusCode': 400,\n 'headers': {\n 'Access-Control-Allow-Headers': 'Content-Type',\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'OPTIONS,POST,GET'\n }\n }\n\n_RESPONSE_403 = {\n 'statusCode': 403,\n 'headers': {\n 'Access-Control-Allow-Headers': 'Content-Type',\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'OPTIONS,POST,GET'\n }\n }\n\n\n_RESPONSE_500 = {\n 'statusCode': 500,\n 'headers': {\n 'Access-Control-Allow-Headers': 'Content-Type',\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'OPTIONS,POST,GET'\n }\n }\n\n\ndef create_checkout_session(price_id, callback_url):\n try:\n checkout_session = stripe.checkout.Session.create(\n payment_method_types=[\n 'card',\n ],\n line_items=[\n {\n 'price': price_id,\n 'quantity': 1,\n },\n ],\n mode='subscription',\n success_url=callback_url + '?success=true',\n cancel_url=callback_url + '?canceled=true',\n )\n return checkout_session.url\n except Exception as ex:\n print(ex)\n return None\n\n\ndef lambda_handler(event, context):\n print('event:', event)\n authed = authorize.is_authorized(event)\n if not authed:\n print('returning 403 as not authed.')\n return _RESPONSE_403\n\n query_string_parameters = event[_EVENT_KEY_QUERY_STRING_PARAMETER]\n print(\"query_string_parameters:\", query_string_parameters)\n\n http_method = 'GET'\n if _EVENT_KEY_HTTP_METHOD in event:\n http_method = event[_EVENT_KEY_HTTP_METHOD]\n\n if http_method != 'POST':\n print('returning 400 as the method {m} is not POST.'.format(m = http_method))\n return _RESPONSE_400\n\n price_type = None\n if query_string_parameters:\n if _PARAM_KEY_PRICE_TYPE in query_string_parameters:\n price_type = query_string_parameters[_PARAM_KEY_PRICE_TYPE]\n if price_type is None:\n print('returning 400 as the method price type is not provided.')\n return _RESPONSE_400\n\n if price_type == _PRICE_TYPE_LIGHT:\n price_id = _PRICE_ID_LIGHT\n elif price_type == _PRICE_TYPE_PREMIUM:\n price_id = _PRICE_ID_PREMIUM\n\n callback_url = None\n if query_string_parameters:\n if _CALLBACK_URL in query_string_parameters:\n callback_url = query_string_parameters[_CALLBACK_URL]\n if callback_url is None:\n print('returning 400 as the method callback url is not provided.')\n return _RESPONSE_400\n\n redirect_url = create_checkout_session(price_id, callback_url)\n if not redirect_url:\n print('could not retrieve the redirect url.')\n return _RESPONSE_500\n\n ret = _RESPONSE_303\n ret['headers']['Location'] = redirect_url\n ret['headers']['Access-Control-Allow-Origin'] = '*'\n #return ret\n\n return {\n 'statusCode': 200,\n 'headers': {\n 'Access-Control-Allow-Headers': 'Content-Type',\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'OPTIONS,POST,GET'\n },\n 'body': json.dumps(redirect_url)\n }\n","sub_path":"lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":4120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"184193175","text":"\nimport acm\nimport FAgent\n\ndef OnPrepare( self):\n FAgent.OnPrepare( self)\n \n if self.TradeSource() is None:\n self.TradeSource( acm.Trading.CreateTradeTickerSource(None, self.TradingSession().StoredTrades(), -1, False))\n if self.OrderPositions() is None:\n self.OrderPositions( acm.FOrderPositions( self.TradingSession().Orders())) \n if self.PendingCommands() is None:\n self.PendingCommands( acm.FList())\n if self.PriceMonitors() is None:\n self.PriceMonitors( acm.FDependentArray())\n if self.DoneOrDeletedPriceMonitors() is None:\n self.DoneOrDeletedPriceMonitors(_GetPriceMonitors( self, acm.Filter.SimpleOrQuery( 'FPriceMonitor', ['Order.IsOrderDone', 'Order.IsOrderDeleted'], None, [True, True])))\n if self.BreachedPriceMonitors() is None:\n self.BreachedPriceMonitors( _GetPriceMonitors( self, acm.Filter.SimpleAndQuery('FPriceMonitor', ['Order.IsOrderActive', 'IsOutsideTarget', 'TradingInterface.Status.EnterOrder'], None, [True, True, True])))\n if self.SendablePriceMonitors() is None:\n self.SendablePriceMonitors( _GetPriceMonitors( self, acm.Filter.SimpleAndQuery('FPriceMonitor', ['Order.IsOrderInactive', 'IsTargetValid', 'TradingInterface.Status.EnterOrder'], None, [True, True, True])))\n\ndef OnCommandError(self, command):\n errors = command.Errors()\n for e in errors:\n if e.IsMarketError():\n if e.Type() == 'TimeStamp':\n continue\n self.ErrorHandler().OnError('Fatal', e.AsString())\n \ndef OnOrderDelete(self, order):\n pass\n \n \n\"\"\" xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx Actions xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n\"\"\"\n\ndef DeleteOrders( self, event):\n self.TradingSession().DeleteOrders()\n\ndef HandleDoneOrDeletedPriceMonitors( self, event):\n doneOrDeleted = acm.FArray()\n doneOrDeleted.AddAll(self.DoneOrDeletedPriceMonitors())\n self.PriceMonitors().RemoveAll( doneOrDeleted)\n\ndef HandleErrors( self, event):\n self.ErrorHandler().OnError( 'Fatal', self.ErrorMessage())\n\ndef HandleSendablePriceMonitors( self, event):\n _UpdatePricesAndSend( self, self.SendablePriceMonitors())\n\ndef NotApplicable( self, event):\n self.ErrorHandler().OnError( 'Information', 'Algorithm is not applicable for selected row')\n\ndef ProcessTrade(self, event):\n tradeSource = self.TradeSource()\n filledQty = self.LastFilledQuantity()\n while not tradeSource.IsEmpty():\n filledQty += abs(tradeSource.Get().Quantity())\n self.LastFilledQuantity(filledQty)\n \ndef RemoveProcessedCommand( self, event):\n self.PendingCommands().Remove( self.ProcessedCommand()) \n \ndef UpdateErrorFromCommand( self, event):\n print ('UpdateErrorFromCommand')\n \ndef UpdateOrders(self, event):\n instructions = self.TradingInstructions()\n \n if instructions is None:\n return\n \n instruments = instructions.Instruments()\n orderPositions = self.OrderPositions()\n \n try:\n for instrument in instruments:\n quantity = instructions.GetQuantity(instrument)\n trading = _GetTradingInterface(self, instrument)\n \n if quantity > 0:\n roundQty = trading.NearestRoundLot(quantity)\n _UpdatePosition( self, instrument, 'Buy', roundQty, orderPositions.OrdersIn(instrument), trading)\n elif quantity < 0:\n roundQty = trading.NearestRoundLot(-quantity)\n _UpdatePosition( self, instrument, 'Sell', roundQty, orderPositions.OrdersIn(instrument), trading)\n else:\n _Trace(self, 'No position update in ' + instrument.StringKey()) \n except Exception as e:\n self.ErrorMessage( str( e))\n\ndef UpdatePrices( self, event):\n _UpdatePricesAndSend( self, self.BreachedPriceMonitors())\n\n\n\n\"\"\" xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx Helper functions xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n\"\"\"\ndef _AddPendingCommand( self, cmd): \n self.PendingCommands().Add(cmd) \n \n\ndef _CanEnterOrder(self, trading):\n return trading.Status().EnterOrder()\n \ndef _CreatePriceMonitor( self, trading, order):\n priceFeed = trading.PriceFeed()\n priceType = self.PriceType()\n priceQuantity = _GetDefaultValue(self, trading, 'portfolioHedgerPriceSourceQuantity')\n priceOffsetTicks = None\n \n valueSource = None\n valueSourceQuantity = 0.0\n priceOffset = None\n \n if priceType == 'Join':\n valueSource = order.IsBuy() and priceFeed.AverageBidPrice() or priceFeed.AverageAskPrice()\n priceOffsetTicks = _GetDefaultValue(self, trading, 'portfolioHedgerPriceJoinOffset')\n elif priceType == 'Match':\n valueSource = order.IsBuy() and priceFeed.AverageAskPrice() or priceFeed.AverageBidPrice()\n priceOffsetTicks = _GetDefaultValue(self, trading, 'portfolioHedgerPriceMatchOffset')\n else:\n valueSource = priceFeed.LastPrice()\n priceOffsetTicks = _GetDefaultValue(self, trading, 'portfolioHedgerPriceLastOffset')\n \n if priceQuantity != None:\n valueSourceQuantity = priceQuantity\n \n if priceOffsetTicks != None and priceOffsetTicks != 0:\n priceOffset = acm.FPriceTickOffset( priceOffsetTicks)\n \n monitor = acm.Trading.CreatePriceMonitor( order, valueSource, valueSourceQuantity, priceOffset)\n \n # order book status is used in filters for BreachedPriceMonitors and \n # SendablePriceMonitors so we need a dependency for it.\n status = monitor.TradingInterface().Status()\n status.AddDependent(monitor)\n return monitor\n\ndef _GetDefaultValue( self, owner, name):\n try:\n val = owner.GetDefaultValueEx( name, self.Context())\n if val == '':\n return None\n return val\n except Exception as e:\n _Trace(self, 'Failed to retrieve default value ' + name)\n return None\n\ndef _GetTradingInterface( self, instrument):\n trading = acm.Trading.DefaultTradingInterface( instrument)\n \n if trading != None and self.Smart():\n try:\n smartTrading = acm.FSmartTradingInterface( trading )\n \n if not smartTrading.ImTradingInterface():\n raise Exception('IM order book not found')\n return smartTrading\n \n except Exception as e:\n _Trace(self, 'SMART could not be created for ' + trading.StringKey() + ': ' + str(e))\n\n if trading is None or trading.IsKindOf( 'FAdsTradingInterface'):\n raise Exception('Order book could not be determined for ' + instrument.StringKey())\n \n return trading\n\n \ndef _GetPriceMonitors( self, filter):\n monitors = acm.FFilteredSet( self.PriceMonitors())\n monitors.Filter( filter)\n return monitors\n\n\ndef _SendOrder( self, trading, buyOrSell, quantity):\n order = self.TradingSession().NewOrder( trading)\n \n order.BuyOrSell( buyOrSell)\n \n quantity = trading.NearestRoundLot(quantity) \n \n order.Quantity( quantity)\n order.Account( self.Account())\n order.Reference( self.Reference())\n order.RemoveOnBrokenSession( True)\n order.IsIndependentModifyEnabled( True)\n order.HedgeOrder(True)\n \n if self.Smart():\n order.TradingStrategy( self.TradingStrategy())\n order.SetStartAgent( True)\n \n monitor = _CreatePriceMonitor( self, trading, order)\n self.PriceMonitors().Add( monitor)\n _UpdatePriceAndSend( self, monitor)\n\n \ndef _Trace( self, message):\n if self.IsTraceEnabled():\n log = self.Log()\n if log:\n log.AddStringRecord( message)\n \ndef _UpdatePosition( self, instrument, buyOrSell, quantity, orders, trading): \n \n finalQty = quantity\n \n _Trace(self, 'Position update: ' + str( buyOrSell) + ' ' + str(finalQty) + ' in ' + instrument.StringKey())\n\n if orders:\n for order in orders:\n if acm.Math.AlmostZero( finalQty, 1e-10):\n break\n \n if (order.IsOrderActive() or order.IsOrderInactive()) and order.BuyOrSell() != buyOrSell: \n orderQty = order.Quantity()\n cmd = None \n if orderQty > finalQty: \n finalQty = orderQty - finalQty\n order.Quantity(finalQty)\n if order.IsOrderActive():\n cmd = order.SendOrder()\n finalQty = 0\n else:\n cmd = order.DeleteOrder()\n finalQty = finalQty - orderQty \n \n if cmd is not None:\n _AddPendingCommand( self, cmd)\n \n if finalQty > 0:\n _SendOrder( self, trading, buyOrSell, finalQty)\n\n \ndef _UpdatePriceAndSend( self, monitor):\n if not monitor:\n _Trace(self, 'Received no monitor')\n return False\n if not _CanEnterOrder(self, monitor.TradingInterface()):\n _Trace(self, monitor.TradingInterface().StringKey() + ': Enter order not allowed in current phase')\n return False\n if not monitor.IsTargetValid():\n _Trace(self, monitor.Order().StringKey() + ': Target not valid')\n return False\n \n \n try:\n order = monitor.Order()\n target = monitor.TargetPrice()\n order.Price( target)\n _AddPendingCommand( self, order.SendOrder())\n return True\n except Exception as e:\n _Trace(self, 'Error while updating order price: ' + str(e))\n return False\n\n\ndef _UpdatePricesAndSend( self, monitors):\n for monitor in monitors:\n _UpdatePriceAndSend( self, monitor)\n\ndef onAgentActivateClick(row, col, cell, activate, operation): \n\n if activate: \n context = col.Context()\n tag = cell.GetEvaluator().Tag()\n portfolio = row.Portfolio() \n agentName = 'PortfolioYieldHedger/' + portfolio.Name() + '/' + row.StringKey()\n agent = acm.Trading.CreateAgent(agentName, 'GenericPortfolioHedger', context.Name(), tag) \n if agent:\n agent.InstrumentAndTrades(row)\n agent.Start()\n \n\n \n","sub_path":"Extensions/Default/FPythonCode/GenericPortfolioHedger.py","file_name":"GenericPortfolioHedger.py","file_ext":"py","file_size_in_byte":10416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"48371801","text":"def main():\n filename = input(\"please input a file name (ex: text.txt): \")\n cipher = int(input(\"input a cipher value: \"))\n originalFile = open(filename, \"r\")\n accum = \"\"\n for char in originalFile.read():\n if (char.isalnum()):\n accum += chr(ord(char) + cipher)\n else:\n accum += char \n originalFile.close()\n fo = open(filename + \".enc\", \"w\")\n fo.write(accum)\n fo.close()\nmain()\n","sub_path":"cs110/fileWork/fileCW.py","file_name":"fileCW.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"53762238","text":"'''\nCreated on 05/ott/2012\n\n@author: consultit\n'''\n\n#This command should be executed to reparent all joints to root.\n#The reparented egg files are created in current directory.\n\"\"\"\negg-optchar -d . -p Bone_pelvis, -p Bone_l_foot_heel, -p Bone_r_foot_heel, -p Bone_l_leg_upper, -p Bone_l_leg_lower, -p Bone_r_leg_upper, -p Bone_r_leg_lower, -p Bone_spine_02, -p Bone_l_arm_upper, -p Bone_l_arm_lower, -p Bone_l_hand, -p Bone_r_arm_upper, -p Bone_r_arm_lower, -p Bone_r_hand, -p Bone_spine_05, airbladepilot/pilot*.egg\n\"\"\"\n\n#joint bodies (reparented to root) descriptions\njointBodiesDescr = [\n \"Bone_pelvis\",\n \"Bone_spine_02\",\n \"Bone_spine_05\",\n \"Bone_l_arm_upper\",\n \"Bone_l_arm_lower\",\n \"Bone_l_hand\",\n \"Bone_r_arm_upper\",\n \"Bone_r_arm_lower\",\n \"Bone_r_hand\",\n# \"Bone_skull\",\n# \"Bone_skull_nub\",\n \"Bone_l_leg_upper\",\n \"Bone_l_leg_lower\",\n \"Bone_l_foot_heel\",\n# \"Bone_l_foot_toes\",\n# \"Bone_l_foot_nub\",\n \"Bone_r_leg_upper\",\n \"Bone_r_leg_lower\",\n \"Bone_r_foot_heel\",\n# \"Bone_r_foot_toes\",\n# \"Bone_r_foot_nub\",\n]\n\n#intra joints' bodies descriptions: radius, mass, corrFraction, (swing1, swing2, twist), Pcorr, (radius2, height2), kinematicAlso, kinematic2ndShape\nintraJointsBodyDescr = {\n (\"\", \"Bone_pelvis\"): (2.0, 5.0, 0.99, (90, 90, 360), 0.0, (0.0, 0.0), True, False),\n #left leg\n (\"Bone_pelvis\", \"Bone_l_leg_upper\"): (0.5, 2.5, 0.35, (5, 5, 10), 0.0, (0.0, 0.0), False, False),\n (\"Bone_l_leg_upper\", \"Bone_l_leg_lower\"): (2.5, 1.5, 0.90, (5, 5, 10), 0.0, (2.0, 0.0), True, False),\n (\"Bone_l_leg_lower\", \"Bone_l_foot_heel\"): (1.0, 1.0, 0.60, (50, 10, 10), 0.0, (2.0, 0.0), True, False),\n# (\"Bone_l_foot_heel\", \"Bone_l_foot_toes\"): (0.75, 0.5, 0.80, (30, 30, 10), 0.0, (0.0, 0.0), False, False),\n# (\"Bone_l_foot_toes\", \"Bone_l_foot_nub\"): (1.0, 0.3, 0.80, (5, 5, 10), 0.0, (0.0, 0.0), False, False),\n #right leg\n (\"Bone_pelvis\", \"Bone_r_leg_upper\"): (0.5, 2.5, 0.35, (5, 5, 10), 0.0, (0.0, 0.0), False, False),\n (\"Bone_r_leg_upper\", \"Bone_r_leg_lower\"): (2.5, 1.5, 0.90, (5, 5, 10), 0.0, (2.0, 0.0), True, False),\n (\"Bone_r_leg_lower\", \"Bone_r_foot_heel\"): (1.0, 1.0, 0.60, (50, 10, 10), 0.0, (2.0, 0.0), True, False),\n# (\"Bone_r_foot_heel\", \"Bone_r_foot_toes\"): (0.75, 0.5, 0.80, (5, 5, 10), 0.0, (0.0, 0.0), False, False),\n# (\"Bone_r_foot_toes\", \"Bone_r_foot_nub\"): (1.0, 0.3, 0.80, (5, 5, 10), 0.0, (0.0, 0.0), False, False),\n #trunk\n (\"Bone_pelvis\", \"Bone_spine_02\"): (1.5, 6.0, 0.50, (30, 30, 10), 0.0, (0.0, 0.0), False, False),\n (\"Bone_spine_02\", \"Bone_spine_05\"): (5.0, 20.0, 0.90, (30, 30, 10), 0.0, (3.5, 3.5), True, True),\n #left arm\n (\"Bone_spine_05\", \"Bone_l_arm_upper\"): (0.5, 2.5, 0.30, (5, 5, 10), 0.0, (0.0, 0.0), False, False),\n (\"Bone_l_arm_upper\", \"Bone_l_arm_lower\"): (1.0, 1.0, 0.90, (30, 30, 10), 0.0, (0.0, 0.0), True, False),\n (\"Bone_l_arm_lower\", \"Bone_l_hand\"): (0.5, 0.5, 0.95, (5, 5, 10), 0.0, (0.0, 0.0), True, False),\n #right arm\n (\"Bone_spine_05\", \"Bone_r_arm_upper\"): (0.5, 2.5, 0.30, (5, 5, 10), 0.0, (0.0, 0.0), False, False),\n (\"Bone_r_arm_upper\", \"Bone_r_arm_lower\"): (1.0, 1.0, 0.90, (30, 30, 10), 0.0, (0.0, 0.0), True, False),\n (\"Bone_r_arm_lower\", \"Bone_r_hand\"): (0.5, 0.5, 0.90, (5, 5, 10), 0.0, (0.0, 0.0), True, False),\n# (\"Bone_spine_05\", \"Bone_skull\"): (0.5, 1.0, 0.90, (30, 30, 10), 0.0, (0.0, 0.0), False, False),\n# (\"Bone_skull\", \"Bone_skull_nub\"): (1.0, 1.0, 0.99, (30, 30, 180), 0.0, (0.0, 0.0), False, False),\n}\n","sub_path":"RagDoll/samples_datainput/airbladepilot_datainput.py","file_name":"airbladepilot_datainput.py","file_ext":"py","file_size_in_byte":3568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"246228203","text":"#! /home/ajan/anaconda/bin/python\nfrom pulse import *\nfrom bloch import *\nfrom matmanip import *\nfrom scipy.integrate import ode\nimport matplotlib.pyplot as plt\n\ndef obj_twodot(x, params, ampmaskfunc, phasemaskfunc, optimize):\n\n # unpack x and assign to variables\n param_list = params['mask_params'].param_list\n NOPTS = params['mask_params'].NOPTS\n kwargs = {}\n # create keyword arguments\n for i in range(NOPTS):\n kwargs[param_list[i]] = x[i]\n\n # assign pulse area if it is being optimized\n if 'pulse_area' in kwargs:\n params['pulse_params'].pulse_EO = kwargs['pulse_area']\n\n pulse = Pulse(params)\n pulse.setShape()\n pulse.fft()\n\n # apply mask to pulse\n pulse.applyMask(ampmaskfunc, phasemaskfunc, params, **kwargs)\n pulse.ifft()\n\n # define integration parameters\n rtol = params['rkdp_params'].rkdp_rtol\n atol = params['rkdp_params'].rkdp_atol\n hstart = params['rkdp_params'].rkdp_hstart\n hmax = params['rkdp_params'].rkdp_hmax\n\n t_start = params['run_params'].run_t_start\n t_end = params['run_params'].run_t_end\n t_step = params['rkdp_params'].rkdp_tdep_step\n\n array_len = int((convert(t_end, ARU_TO_FEMTO) - convert(t_start, ARU_TO_FEMTO))/convert(t_step, ARU_TO_FEMTO))\n\n if optimize:\n nsteps = params['rkdp_params'].rkdp_nsteps_opt\n else:\n nsteps = params['rkdp_params'].rkdp_nsteps_tdep\n\n # ---- FIRST DOT ---- #\n # define initial conditions\n initial_dmatrix = state_to_dmatrix(params['qdot_params'].qdot_initial_state)\n rho0_1 = dmatrix_to_array(initial_dmatrix)\n\n # define desired final state\n qdot1_desired_dmatrix = state_to_dmatrix(params['qdot_params'].qdot_desired_state)\n rhod_1 = dmatrix_to_array(qdot1_desired_dmatrix)\n\n # integrate bloch equations\n bloch_1 = BlochEqns(params, pulse.efield, pulse.t, DOT1) # define bloch equations with shaped electric field\n r_1 = ode(bloch_1.operator)\n r_1.set_integrator('dop853', method='adams', rtol=rtol, atol=atol, first_step=hstart)\n r_1.set_initial_value(rho0_1, t_start)\n\n # ---- SECOND DOT ---- #\n # define initial conditions\n qdot2_initial_dmatrix = state_to_dmatrix(params['qdot2_params'].qdot_initial_state)\n rho0_2 = dmatrix_to_array(qdot2_initial_dmatrix)\n\n # define desired final state\n qdot2_desired_dmatrix = state_to_dmatrix(params['qdot2_params'].qdot_desired_state)\n rhod_2 = dmatrix_to_array(qdot2_desired_dmatrix)\n\n # integrate bloch equations\n bloch_2 = BlochEqns(params, pulse.efield, pulse.t, DOT2) # define bloch equations with shaped electric field\n r_2 = ode(bloch_2.operator)\n r_2.set_integrator('dop853', method='adams', rtol=rtol, atol=atol, first_step=hstart)\n r_2.set_initial_value(rho0_2, t_start)\n\n if optimize:\n qdot1_rho_end = r_1.integrate(t_end - t_step)\n qdot2_rho_end = r_2.integrate(t_end - t_step)\n\n else:\n t = numpy.linspace(t_start, t_end, array_len, endpoint=True)\n rho_1 = numpy.zeros([array_len, 16])\n rho_2 = numpy.zeros([array_len, 16])\n\n # integrate the Bloch equations\n i = 0\n while r_1.successful() and r_1.t < t[-1]:\n i += 1\n r_1.integrate(t[i])\n rho_1[i,:] = r_1.y\n qdot1_rho_end = rho_1[-1,:]\n\n # integrate the Bloch equations\n i = 0\n while r_2.successful() and r_2.t < t[-1]:\n i += 1\n r_2.integrate(t[i])\n rho_2[i,:] = r_2.y\n qdot2_rho_end = rho_2[-1,:]\n\n # plot the results\n if params['run_params'].show_plot:\n plt.subplot(2,2,1)\n pulse.plotIntensity()\n plt.subplot(2,2,2)\n plt.plot(convert(t, ARU_TO_FEMTO), rho_1[:,0], 'b-')\n plt.plot(convert(t, ARU_TO_FEMTO), rho_1[:,1], 'g-')\n plt.plot(convert(t, ARU_TO_FEMTO), rho_1[:,2], 'r-')\n plt.plot(convert(t, ARU_TO_FEMTO), rho_1[:,3], 'k-')\n plt.plot(convert(t, ARU_TO_FEMTO), rho_2[:,0], 'b--')\n plt.plot(convert(t, ARU_TO_FEMTO), rho_2[:,1], 'g--')\n plt.plot(convert(t, ARU_TO_FEMTO), rho_2[:,2], 'r--')\n plt.plot(convert(t, ARU_TO_FEMTO), rho_2[:,3], 'k--')\n plt.xlabel('time (fs)')\n plt.ylabel('occupation')\n plt.grid(True)\n plt.axis('tight')\n plt.subplot(2,2,3)\n #pulse.plotEfieldAmp()\n plt.xlim(1.0, 1.15)\n plt.subplot(2,2,4)\n pulse.plotEfieldPhase()\n plt.xlim(1.0, 1.15)\n #plt.ylim(0.0, 50.0)\n plt.show()\n\n # write pulse data to file\n pulse.intensityAC()\n pulse.writePulse()\n\n # calculate the fidelity for dot 1\n qdot1_final_dmatrix = array_to_dmatrix(qdot1_rho_end)\n fidelity_1 = numpy.trace(numpy.dot(qdot1_final_dmatrix, qdot1_desired_dmatrix)).real\n \n\n # calculate the fidelity for dot 2\n qdot2_final_dmatrix = array_to_dmatrix(qdot2_rho_end)\n fidelity_2 = numpy.trace(numpy.dot(qdot2_final_dmatrix, qdot2_desired_dmatrix)).real\n\n # calculate the overall fidelity for the gate\n dp_state_physical = numpy.kron(qdot1_final_dmatrix, qdot2_final_dmatrix)\n dp_state_desired = numpy.kron(qdot1_desired_dmatrix, qdot2_desired_dmatrix)\n fidelity = numpy.trace(numpy.dot(dp_state_physical, dp_state_desired)).real\n \n if optimize:\n # prevent pulse area from going negative (not sure why this happens)\n if params['pulse_params'].pulse_EO < params['mask_params'].x_bounds[3][0] or params['pulse_params'].pulse_EO > params['mask_params'].x_bounds[3][1]:\n fidelity = 0.0\n return 1.0 - fidelity\n else:\n data = {\"fidelity\": fidelity, \"fidelity dot1\": fidelity_1, \"fidelity dot2\": fidelity_2, \"t\": convert(t, ARU_TO_FEMTO), \"rho_1\": rho_1, \"rho_2\": rho_2, \"pulse_data\": pulse.data(), \"rho0_1\": rho0_1, \"rhod_1\": rhod_1, \"rho0_2\": rho0_2, \"rhod_2\": rhod_2}\n return data\n\n\n\n\n\n\n\n\n\n","sub_path":"obj_twodot.py","file_name":"obj_twodot.py","file_ext":"py","file_size_in_byte":5988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"475137482","text":"import game_functions as gf\nimport pygame\nfrom button import Button\nfrom game_stats import GameStats\nfrom pygame.sprite import Group\nfrom settings import Settings\nfrom ship import Ship\nfrom scoreboard import Scoreboard\n\n\ndef run_game():\n pygame.init()\n settings = Settings()\n stats = GameStats(settings)\n screen = pygame.display.set_mode((settings.screen_width, settings.screen_height))\n pygame.display.set_caption('SpaceShips')\n play_button = Button(settings, screen, 'Play')\n sb = Scoreboard(settings, screen, stats)\n ship = Ship(settings, screen)\n aliens = Group()\n bullets = Group()\n\n gf.create_fleet(settings, screen, ship, aliens)\n\n while True:\n gf.check_events(settings, screen, stats, play_button, ship, aliens, bullets)\n if stats.game_active:\n ship.update()\n gf.update_bullets(settings, screen, stats, sb, ship, aliens, bullets)\n gf.update_aliens(settings, stats, screen, ship, aliens, bullets)\n\n gf.update_screen(settings, screen, stats, sb, ship, aliens, bullets, play_button)\n\n\nrun_game()\n","sub_path":"alien_invasion/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"291802323","text":"'''\n\nUse of classes. Starting with Class turtle.\n\n'''\n\nimport turtle\n\n\ndef square():\n \n background = turtle.Screen()\n \n background.bgcolor(\"red\")\n \n brad = turtle.Turtle()\n \n brad.shape(\"turtle\")\n \n brad.color(\"yellow\")\n \n brad.speed(5)\n \n for i in range(0,4):\n brad.forward(100) # without the screen. the output doesn't persist.\n brad.right(90)\n \n background.exitonclick()\n\n \ndef circle():\n\n angie = turtle.Turtle()\n \n angie.shape(\"turtle\")\n \n angie.color(\"blue\")\n \n angie.speed(5)\n \n angie.circle(200)\n \n \ndef triangle():\n\n trin = turtle.Turtle()\n \n trin.shape(\"triangle\")\n \n trin.color(\"green\")\n \n trin.speed(5)\n \n trin.backward(100)\n trin.left(60)\n trin.forward(100)\n trin.right(60)\n trin.forward(100)\n \n \nsquare() \n\ncircle()\n\ntriangle()","sub_path":"KUNAL's Practise/Classes-Turtles.py","file_name":"Classes-Turtles.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"570728066","text":"# -*- coding: utf-8 -*-\nfrom concurrent.futures import ThreadPoolExecutor\nimport os\nimport win32serviceutil\nimport config\nimport win32service\nimport win32con\n\n__author__ = 'vitsukaev'\n\ncfg = config.Config\n\n\nclass serviceClass():\n def __init__(self, serviceTuple):\n self.name = serviceTuple[0]\n self.description = serviceTuple[1]\n self.status = serviceTuple[2]\n\n def stopService(self):\n if win32serviceutil.QueryServiceStatus(self.name)[1] == 4:\n win32serviceutil.StopService(self.name)\n\n def startService(self):\n if win32serviceutil.QueryServiceStatus(self.name)[1] == 1:\n win32serviceutil.StartService(self.name)\n\n def restartService(self):\n if win32serviceutil.QueryServiceStatus(self.name)[1] == 4:\n win32serviceutil.RestartService(self.name)\n\n\nclass servicesClass():\n def __init__(self, mask=''):\n self.__statusMap__ = {1: 'Stopped',\n 2: 'Starting',\n 3: 'Stopping',\n 4: 'Started',\n 6: 'Pausing',\n 7: 'Paused'}\n self.mask = mask\n self.setServiceList()\n\n def getServiceList(self):\n self.setServiceList()\n return self.serviceList\n\n def setServiceList(self):\n\n result = []\n accessSCM = win32con.GENERIC_READ\n\n # Open Service Control Manager\n hscm = win32service.OpenSCManager(None, None, accessSCM)\n\n # Enumerate Service Control Manager DB\n typeFilter = win32service.SERVICE_WIN32\n stateFilter = win32service.SERVICE_STATE_ALL\n\n services = win32service.EnumServicesStatus(hscm, typeFilter, stateFilter)\n for serviceName, description, status in services:\n if serviceName.startswith(self.mask):\n result.append(serviceClass([serviceName, description, self.__statusMap__.get(status[1])]))\n self.serviceList = result\n\n @staticmethod\n def stopService(name):\n if serviceClass(['', '', '']).__class__ == name.__class__:\n name = name.name\n if win32serviceutil.QueryServiceStatus(name)[1] == 4:\n try:\n win32serviceutil.StopService(name)\n except Exception:\n print(Exception)\n\n def stopServiceAll(self):\n with ThreadPoolExecutor(100) as executor:\n for _ in executor.map(self.stopService, self.serviceList):\n pass\n # for i in self.serviceList:\n # self.stopService(i.name)\n\n @staticmethod\n def startService(name):\n if serviceClass(['', '', '']).__class__ == name.__class__:\n name = name.name\n if win32serviceutil.QueryServiceStatus(name)[1] == 1:\n win32serviceutil.StartService(name)\n\n def startServiceAll(self):\n with ThreadPoolExecutor(100) as executor:\n for _ in executor.map(self.startService, self.serviceList):\n pass\n # for i in self.serviceList:\n # self.startService(i.name)\n\n @staticmethod\n def restartService(name):\n if serviceClass(['', '', '']).__class__ == name.__class__:\n name = name.name\n if win32serviceutil.QueryServiceStatus(name)[1] == 4:\n win32serviceutil.RestartService(name)\n\n def restartServiceAll(self):\n with ThreadPoolExecutor(100) as executor:\n for _ in executor.map(self.restartService, self.serviceList):\n pass\n # for i in self.serviceList:\n # self.restartService(i.name)\n\n def getServiceStatus(self, name):\n for i in self.getServiceList():\n if i.name == name:\n return i.status\n return ('не найден сервис ' + name)\n\ndef getColoringServices(text):\n res = text.replace('Stopped', 'Stopped')\n res = res.replace('Running', 'Running')\n return res\n\ndef getColoringStatus(service):\n red = ''\n green = ''\n end = ''\n startLink = links.get('start', service.name, True)\n stopLink = links.get('stop', service.name, True)\n restartLink = links.get('restart', service.name, True)\n\n startIcon = links.startIcon\n stopIcon = links.stopIcon\n restartIcon = links.restartIcon\n\n if service.status == 'Started':\n result = '' \\\n '' + green + service.status + end\n elif service.status == 'Stopped':\n result = '' + red + service.status + end\n else:\n result = service.status\n\n return result\n\ndef makeServHtmlTable(serviceList):\n startIcon = links.startIcon\n stopIcon = links.stopIcon\n restartIcon = links.restartIcon\n\n startLinkAll = links.get('start')\n stopLinkAll = links.get('stop')\n restartLinkAll = links.get('restart')\n\n res = '' \\\n '' \\\n ' - запустить/перезапустить/остановить все сервисы

'\n\n res += '\\n'\n for row in serviceList:\n statusLinks = getColoringStatus(row)\n res += '\\n'\n res += '\\n'\n res += '
' + statusLinks + '' + row.name + '' + row.description + ''\n res += '
'\n return res\n\ndef makeHtmlTable(\n serviceList): # todo сделать один метод для преобразования листа и листа листов в таблицу html. использовать для списка логов и сервисов\n res = ''\n res += '\\n'\n for row in serviceList:\n res += '\\n'\n res += '\\n'\n res += '
' + row[0] + '' + row[1] + '' + row[\n 2] + '' # последний нужен ли ?\n res += '
'\n return res\n\ndef makeHtmlTableNew(list):\n midleList = []\n for row in list:\n midleList.append('' + ''.join(row) + '')\n return '\\n\\n' + '\\n\\n'.join(midleList) + '\\n
\\n'\n\nclass links():\n startIcon = 'static/play.png'\n stopIcon = 'static/stop.png'\n restartIcon = 'static/restart.png'\n\n def get(act, name='', redirect=True):\n if act == 'start':\n result = '/services?act=start'\n if act == 'restart':\n result = '/services?act=restart'\n if act == 'stop':\n result = '/services?act=stop'\n if name != '':\n result += '&name=' + name\n if not redirect:\n result += '&redirect=false'\n else:\n result += '&redirect=true'\n return result\n\n # serv = servicesClass()\n # serv.stopServiceAll()\n # makeServHtmlTable(serv.getServiceList())\n # a = 1\n","sub_path":"RunningServices.py","file_name":"RunningServices.py","file_ext":"py","file_size_in_byte":7452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"17689641","text":"class Solution:\n def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n # Mark entrance visited\n x, y = entrance\n maze[x][y] = '+'\n queue = []\n queue.append(entrance)\n direction = [[0, 1], [1, 0], [0, -1], [-1, 0]]\n rows, cols = len(maze), len(maze[0])\n ans = 1\n while queue:\n for _ in range(len(queue)):\n [i, j] = queue.pop(0)\n for l in range(4):\n x = i + direction[l][0]\n y = j + direction[l][1]\n if(x < 0 or y < 0 or x >= rows or y >= cols or maze[x][y] == '+'):\n continue\n elif(x == 0 or y == 0 or x == rows -1 or y == cols -1 ):\n return ans\n maze[x][y] = '+'\n queue.append([x,y])\n ans += 1\n\n return -1\n\n#Another solution\nclass Solution:\n def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n x, y = entrance\n queue = []\n queue.append([x, y, 0])\n DIRECTION = [0, -1, 0, 1, 0]\n rows, cols = len(maze), len(maze[0])\n while queue:\n i, j , move = queue.pop(0)\n if ((x != i or y != j) and (i == 0 or j == 0 or i == rows - 1 or j == cols - 1)):\n return move\n for d in range(4):\n di = i + DIRECTION[d]\n dj = j + DIRECTION[d+1]\n if (di >= 0 and dj >= 0 and di < rows and dj < cols and maze[di][dj] == '.'):\n maze[di][dj] = '+'\n queue.append([di, dj, move+1])\n return -1\n","sub_path":"src/Graph/1926.py","file_name":"1926.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"187111496","text":"\"\"\"Makefile dependency rule output plugin\n\n\"\"\"\n\nimport optparse\nimport sys\nimport os.path\n\nfrom pyang import plugin\nfrom pyang import error, statements\n\n\ndef pyang_plugin_init():\n plugin.register_plugin(ListFeaturePlugin())\n\n\nclass ListFeaturePlugin(plugin.PyangPlugin):\n def add_opts(self, optparser):\n optlist = [\n optparse.make_option(\"--is-type-only\",\n action=\"store_true\",\n dest=\"typeonly\",\n default=False,\n help=\"Return 'True' if module only defines types\"\n \"and 'False' if module contains leafs\"),\n ]\n g = optparser.add_option_group(\"Feature output specific options\")\n g.add_options(optlist)\n\n def add_output_format(self, fmts):\n self.multiple_modules = True\n fmts['listfeature'] = self\n\n def emit(self, ctx, modules, fd):\n\n # cannot do this unless everything is ok for our module\n modulenames = [m.arg for m in modules]\n for (epos, etag, eargs) in ctx.errors:\n if ((epos.top is None or epos.top.arg in modulenames) and\n error.is_error(error.err_level(etag))):\n raise error.EmitError(\"%s contains errors\" % epos.top.arg)\n emit_depend(ctx, modules, fd)\n\n\ndef emit_depend(ctx, modules, fd):\n for module in modules:\n if ctx.opts.typeonly is False:\n for feature in module.i_features:\n fd.write('%s\\n' % feature)\n else:\n is_bool = True\n for kid in module.i_children:\n if type(kid) == statements.ListStatement or \\\n type(kid) == statements.ContainerStatement or \\\n type(kid) == statements.LeafLeaflistStatement:\n is_bool = False\n break\n fd.write('%s\\n' % is_bool)\n","sub_path":"pyang/plugins/listfeatures.py","file_name":"listfeatures.py","file_ext":"py","file_size_in_byte":1943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"448198453","text":"# -*- coding: utf-8 -*-\n\n# Copyright 2018, IBM.\n#\n# This source code is licensed under the Apache License, Version 2.0 found in\n# the LICENSE.txt file in the root directory of this source tree.\n\n# pylint: disable=invalid-name,missing-docstring,broad-except\n\n\"\"\"Test IBMQ online qasm simulator.\nTODO: Must expand tests. Re-evaluate after Aer.\"\"\"\n\nfrom qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister\nfrom qiskit import transpiler\nfrom qiskit.backends.ibmq import IBMQProvider\nfrom .common import requires_qe_access, QiskitTestCase\n\n\nclass TestIbmqQasmSimulator(QiskitTestCase):\n \"\"\"Test IBM Q Qasm Simulator.\"\"\"\n\n @requires_qe_access\n def test_execute_one_circuit_simulator_online(self, qe_token, qe_url):\n \"\"\"Test execute_one_circuit_simulator_online.\n\n If all correct should return correct counts.\n \"\"\"\n provider = IBMQProvider(qe_token, qe_url)\n backend = provider.get_backend('ibmq_qasm_simulator')\n qr = QuantumRegister(1)\n cr = ClassicalRegister(1)\n qc = QuantumCircuit(qr, cr)\n qc.h(qr[0])\n qc.measure(qr[0], cr[0])\n qobj = transpiler.compile(qc, backend, seed=73846087)\n shots = qobj.config.shots\n job = backend.run(qobj)\n result = job.result()\n counts = result.get_counts(qc)\n target = {'0': shots / 2, '1': shots / 2}\n threshold = 0.04 * shots\n self.assertDictAlmostEqual(counts, target, threshold)\n\n @requires_qe_access\n def test_execute_several_circuits_simulator_online(self, qe_token, qe_url):\n \"\"\"Test execute_several_circuits_simulator_online.\n\n If all correct should return correct counts.\n \"\"\"\n provider = IBMQProvider(qe_token, qe_url)\n backend = provider.get_backend('ibmq_qasm_simulator')\n qr = QuantumRegister(2)\n cr = ClassicalRegister(2)\n qc1 = QuantumCircuit(qr, cr)\n qc2 = QuantumCircuit(qr, cr)\n qc1.h(qr)\n qc2.h(qr[0])\n qc2.cx(qr[0], qr[1])\n qc1.measure(qr[0], cr[0])\n qc1.measure(qr[1], cr[1])\n qc2.measure(qr[0], cr[0])\n qc2.measure(qr[1], cr[1])\n shots = 1024\n qobj = transpiler.compile([qc1, qc2], backend, seed=73846087, shots=shots)\n job = backend.run(qobj)\n result = job.result()\n counts1 = result.get_counts(qc1)\n counts2 = result.get_counts(qc2)\n target1 = {'00': shots / 4, '01': shots / 4,\n '10': shots / 4, '11': shots / 4}\n target2 = {'00': shots / 2, '11': shots / 2}\n threshold = 0.04 * shots\n self.assertDictAlmostEqual(counts1, target1, threshold)\n self.assertDictAlmostEqual(counts2, target2, threshold)\n\n @requires_qe_access\n def test_online_qasm_simulator_two_registers(self, qe_token, qe_url):\n \"\"\"Test online_qasm_simulator_two_registers.\n\n If all correct should return correct counts.\n \"\"\"\n provider = IBMQProvider(qe_token, qe_url)\n backend = provider.get_backend('ibmq_qasm_simulator')\n q1 = QuantumRegister(2)\n c1 = ClassicalRegister(2)\n q2 = QuantumRegister(2)\n c2 = ClassicalRegister(2)\n qc1 = QuantumCircuit(q1, q2, c1, c2)\n qc2 = QuantumCircuit(q1, q2, c1, c2)\n qc1.x(q1[0])\n qc2.x(q2[1])\n qc1.measure(q1[0], c1[0])\n qc1.measure(q1[1], c1[1])\n qc1.measure(q2[0], c2[0])\n qc1.measure(q2[1], c2[1])\n qc2.measure(q1[0], c1[0])\n qc2.measure(q1[1], c1[1])\n qc2.measure(q2[0], c2[0])\n qc2.measure(q2[1], c2[1])\n shots = 1024\n qobj = transpiler.compile([qc1, qc2], backend, seed=8458, shots=shots)\n job = backend.run(qobj)\n result = job.result()\n result1 = result.get_counts(qc1)\n result2 = result.get_counts(qc2)\n self.assertEqual(result1, {'00 01': 1024})\n self.assertEqual(result2, {'10 00': 1024})\n","sub_path":"test/python/test_ibmq_qasm_simulator.py","file_name":"test_ibmq_qasm_simulator.py","file_ext":"py","file_size_in_byte":3926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"231998988","text":"import asyncio\nimport discord\n\nimport db.wsgi\nfrom guild.models import *\n\nclass Signals:\n \"\"\"\n Catches signals and does things with them\n \"\"\"\n def __init__(self, bot):\n self.bot = bot\n bot.loop.create_task(self.populate_info())\n\n async def on_guild_join(self, guild):\n try:\n g = self.get_guild(guild)\n DiscordSettings.objects.get_or_create(guild=g)\n for channel in guild.channels:\n self.get_channel(g, channel)\n except Exception as e:\n print(e)\n\n async def on_guild_update(self, before, after):\n self.get_guild(after)\n\n async def on_guild_remove(self, guild):\n try:\n g = self.get_guild(guild)\n channels = DiscordChannel.objects.filter(guild=g)\n channels.delete()\n g.delete()\n except Exception as e:\n print(e)\n\n async def on_guild_channel_create(self, channel):\n g = self.get_guild(channel.guild)\n c = self.get_channel(g, channel)\n \n async def on_guild_channel_update(self, before, after):\n g = self.get_guild(after.guild)\n c = self.get_channel(g, after)\n\n async def on_guild_channel_delete(self, channel):\n g = self.get_guild(channel.guild)\n c = self.get_channel(g, channel)\n if c:\n c.delete()\n \n async def on_guild_role_create(self, role):\n g = self.get_guild(role.guild)\n r = self.get_role(g, role)\n \n async def on_guild_role_update(self, before, after):\n g = self.get_guild(after.guild)\n r = self.get_role(g, after)\n \n async def on_guild_role_delete(self, role):\n g = self.get_guild(role.guild)\n r = self.get_role(g, role)\n if r:\n r.delete()\n\n async def on_guild_channel_update(self, before, after):\n g = self.get_guild(after.guild)\n c = self.get_channel(g, after)\n\n async def populate_info(self):\n \"\"\" Populate all users and guilds \"\"\"\n while not self.bot.is_ready():\n await asyncio.sleep(1)\n try:\n deleted_guilds = DiscordGuild.objects.all()\n for guild in self.bot.guilds:\n g = self.get_guild(guild)\n deleted_guilds = deleted_guilds.exclude(pk=g.id)\n deleted_channels = DiscordChannel.objects.filter(guild=g)\n deleted_roles = DiscordRole.objects.filter(guild=g)\n for channel in guild.channels:\n c = self.get_channel(g, channel)\n deleted_channels = deleted_channels.exclude(id=channel.id)\n for role in guild.roles:\n r = self.get_role(g, role)\n deleted_roles = deleted_roles.exclude(id=role.id)\n deleted_roles.delete()\n deleted_channels.delete()\n deleted_guilds.delete()\n except Exception as e:\n print(e)\n\n def get_channel(self, guild, channel):\n if type(channel) != discord.channel.TextChannel:\n return\n c, created = DiscordChannel.objects.get_or_create(id=channel.id, guild=guild)\n try:\n c.name = channel.name\n c.save()\n except Exception as e:\n print(e)\n finally:\n return c\n\n def get_guild(self, guild):\n g, created = DiscordGuild.objects.get_or_create(id=guild.id)\n try:\n g.name = guild.name\n g.save()\n except Exception as e:\n print(e)\n finally:\n return g\n\n def get_role(self, guild, role):\n r, created = DiscordRole.objects.get_or_create(id=role.id, guild=guild)\n try: \n r.name = role.name\n r.save()\n except Exception as e:\n print(e)\n finally:\n return r\n\n async def on_ready(self):\n \"\"\"\n Bot is loaded\n \"\"\"\n pass\n\ndef setup(bot):\n bot.add_cog(Signals(bot))\n","sub_path":"cogs/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":3985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"222269688","text":"# Класс - объект\n\n# Доступ к объекту с экземпляра\n\nclass Object_class(object):\n meta_data = None\n\n\nex = Object_class()\nex_v2 = Object_class()\n\nprint(ex.__class__) # \nprint(ex.meta_data)\nex_v2.meta_data = '0x0000100'\n\n# Недо \"static\" метод\n\nObject_class.meta_data = 'x237623tebz3g'\n\nprint('New data - top to bottom {}'.format(ex.meta_data)) # x237623tebz3g\n# Если метод не был перезаписан экземпляром, то этот экземпляр получит новые данные сверху вниз!\n\n# Статические методы класса\n# Ключевое слово @staticmethod перед функией*\n# Функция* не принимает self\n\nclass Some_class(object):\n id = 'sd723d2sg2702s3d'\n call_counter = 0\n\n @staticmethod # перед статик. функции\n def zeroing():\n print('ZERO ZERO ZERO!') \n\n def __init__(self, name):\n self.name = name\n\n\nbob = Some_class('Bob')\nprint(bob.__dict__)\n \n# К статическому методу класса можно обратится через экземпляр - но в JavaScript нельзя!\n# и через сам к��асс\nSome_class.zeroing()\nbob.zeroing()","sub_path":"source/classes/class_is_object.py","file_name":"class_is_object.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"509393832","text":"import torch\nfrom torch import nn\nfrom generators.learning.utils.sampler_utils import get_indices_to_delete\nimport pickle\nimport numpy as np\n\n\nclass BaseModel(nn.Module):\n def __init__(self, atype, region, problem_name):\n nn.Module.__init__(self)\n self.atype = atype\n self.region = region\n self.problem_name = problem_name\n if 'two_arm' in problem_name:\n key_configs, _ = pickle.load(open('prm.pkl'))\n if 'pick' in atype:\n self.dim_pose_ids = 8 + 2\n self.dim_konf = 2\n self.konf_indices = get_indices_to_delete('home_region', key_configs)\n else:\n self.dim_pose_ids = 8 + 2\n self.dim_konf = 4\n if 'home' in self.region:\n # get home indices\n self.konf_indices = get_indices_to_delete('loading_region', key_configs)\n elif 'loading' in self.region:\n self.konf_indices = get_indices_to_delete('home_region', key_configs)\n else:\n raise NotImplementedError\n if 'home' in self.region or 'pick' in self.atype:\n self.dim_cnn_features = 2688\n else:\n self.dim_cnn_features = 2624\n else:\n key_configs = np.array(pickle.load(open('one_arm_key_configs.pkl'))['konfs'])\n if 'pick' in atype:\n self.dim_pose_ids = 4\n self.dim_konf = 2\n self.konf_indices = np.array(range(len(key_configs)))\n else:\n self.dim_pose_ids = 4\n self.dim_konf = 4\n self.konf_indices = np.array(range(len(key_configs)))\n\n self.n_hidden = 32\n self.n_konfs = len(self.konf_indices)\n\n def forward(self, action, konf, pose):\n raise NotImplementedError\n\n def filter_data_according_to_cases(self, konf, pose_ids):\n if 'two_arm' in self.problem_name:\n if 'pick' in self.atype:\n target_obj_pose = pose_ids[:, 0:4]\n robot_curr_pose_and_id = pose_ids[:, -6:]\n pose_ids = torch.cat([target_obj_pose, robot_curr_pose_and_id], -1)\n konf = konf[:, :, 0:2, :]\n else:\n target_obj_pose = pose_ids[:, 0:4]\n robot_curr_pose_and_id = pose_ids[:, -6:]\n pose_ids = torch.cat([target_obj_pose, robot_curr_pose_and_id], -1)\n else:\n # Input: konf collisions + target object pose\n if 'pick' in self.atype:\n target_obj_pose = pose_ids[:, 0:4] # only use object_pose\n pose_ids = target_obj_pose\n konf = konf[:, :, 0:2, :]\n else:\n target_obj_pose = pose_ids[:, 0:4]\n pose_ids = target_obj_pose\n konf = konf[:, self.konf_indices, :, :]\n return konf, pose_ids\n","sub_path":"generators/learning/learning_algorithms/torch_wgangp_models/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"89569726","text":"#!/usr/bin/python\n\"\"\"\nThis module tests the specific class method from PacificaModel.\n\nSpecifically, available_hash_list and get_primary_keys from\nPacificaModel since they both require primary\nkeys and the PacificaModel doesn't have any...\n\"\"\"\nfrom peewee import SqliteDatabase\nfrom playhouse.test_utils import test_database\nfrom metadata.orm.test.base import TestBase\nfrom metadata.orm.keys import Keys\nfrom metadata.orm.user_group import UserGroup\n\n\nclass TestKeysHashList(TestBase):\n \"\"\"Test the available hash with sample keys.\"\"\"\n\n def test_primary_keys_with_keys(self):\n \"\"\"Test the method to check primary keys with Keys.\"\"\"\n check_list = Keys.get_primary_keys()\n self.assertTrue(isinstance(check_list, list))\n self.assertTrue(len(check_list) == 1)\n self.assertTrue('id' in check_list)\n\n def test_primary_keys_user_group(self):\n \"\"\"Test the primary keys method with user group.\"\"\"\n check_list = UserGroup.get_primary_keys()\n self.assertTrue(isinstance(check_list, list))\n self.assertTrue(len(check_list) == 2)\n self.assertTrue('person' in check_list)\n self.assertTrue('group' in check_list)\n\n def test_hash_list_with_keys(self):\n \"\"\"Test method to check the results of available hash list.\"\"\"\n sample_key1 = {\n '_id': 127,\n 'key': 'proposal',\n 'encoding': 'UTF8'\n }\n sample_key2 = {\n '_id': 128,\n 'key': 'proposal',\n 'encoding': 'UTF8'\n }\n sample_key3 = {\n '_id': 130,\n 'key': 'proposal',\n 'encoding': 'UTF8'\n }\n with test_database(SqliteDatabase(':memory:'), [Keys]):\n self.base_create_obj(Keys, sample_key1)\n self.base_create_obj(Keys, sample_key2)\n self.base_create_obj(Keys, sample_key3)\n third_obj = Keys()\n hash_list, hash_dict = third_obj.available_hash_list()\n self.assertTrue(len(hash_list) == 3)\n # some sanity checking for the layout of the two objects\n for hashed_key in hash_list:\n self.assertTrue(hashed_key in hash_dict)\n obj_key_meta = hash_dict[hashed_key]\n self.assertTrue('index_hash' in obj_key_meta)\n self.assertTrue('key_list' in obj_key_meta)\n self.assertTrue('id' in obj_key_meta['key_list'])\n self.assertTrue(hashed_key == obj_key_meta['index_hash'])\n","sub_path":"metadata/orm/test/test_available_hash_list.py","file_name":"test_available_hash_list.py","file_ext":"py","file_size_in_byte":2505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"451856755","text":"from bangtal import *\n\nsetGameOption(GameOption.MESSAGE_BOX_BUTTON, False)\n\nscene1 = Scene('스파게티 게임', 'Images/food-1932466_1920.jpg')\nscene2 = Scene('요리사 킹카의 설명!', 'Images/wood-2142241_1920.jpg')\nscene3 = Scene('마트에 도착했어!', 'Images/123.png')\nscene4 = Scene('마트에 도착했어!', 'Images/123.png')\nscene5 = Scene('마트에 도착했어!', 'Images/123.png')\nscene6 = Scene('마트에 도착했어!', 'Images/123.png')\nscene7 = Scene('마트에 도착했어!', 'Images/123.png')\nscene8 = Scene('계산을 할거야!!', 'Images/apples-1841132_1920.jpg')\nscene9 = Scene('집에 도착했어!!', 'Images/kitchen-2165756_1920.jpg')\nscene10 = Scene('완성했어!!', 'Images/spaghetti-1392266_1920.jpg')\n\nsound1 = Sound(\"Audios/namnam.mp3\")\nsound2 = Sound(\"Audios/Tales.mp3\")\n\nsound2.play(loop = True)\n\nstartButton = Object('Images/pngegg.png')\nstartButton.setScale(0.5)\nstartButton.locate(scene1, 50, 80)\nstartButton.show()\n\nsoundon = Object('Images/soundon.png')\nsoundon.setScale(0.3)\nsoundon.locate(scene1,1070,220)\nsoundon.show()\n\nsoundoff = Object('Images/soundoff.png')\nsoundoff.setScale(0.2)\nsoundoff.locate(scene1,1070,190)\n\n\n\nFLAG = Object('Images/게임!.png')\nFLAG.locate(scene1, 590, 20)\nFLAG.show()\n\nDaddy = Object('Images/5-1.png')\nDaddy.locate(scene1, 50, 150)\nDaddy.show()\n\nKINGKA = Object('Images/5-2.png')\nKINGKA.locate(scene2,0,100)\nKINGKA.show()\n\nNINGKA = Object('Images/5-4.png')\nNINGKA.locate(scene9,0,100)\nNINGKA.show()\n\nQueenKA = Object('Images/5-3.png')\nQueenKA.setScale(1.5)\nQueenKA.locate(scene8,150,10)\nQueenKA.show()\n\ntomatoma = Object('Images/1.png')\ntomatoma.setScale(1.0)\ntomatoma.locate(scene9,500,300)\n\nknife = Object('Images/hiclipart.png')\nknife.setScale(1.0)\nknife.locate(scene9, 300, 250)\n\nSaying = Object('Images/323123.png')\nSaying.locate(scene2,470,50)\nSaying.show()\n\nNextButton = Object('Images/clipart529527.png')\nNextButton.setScale(0.1)\nNextButton.locate(scene2,1120,20)\nNextButton.show()\n\nNextButton2 = Object('Images/clipart529527.png')\nNextButton2.setScale(0.1)\nNextButton2.locate(scene3,1120,20)\nNextButton2.show()\n\nNextButton3 = Object('Images/clipart529527.png')\nNextButton3.setScale(0.1)\nNextButton3.locate(scene4,1120,20)\nNextButton3.show()\n\nNextButton4 = Object('Images/clipart529527.png')\nNextButton4.setScale(0.1)\nNextButton4.locate(scene5,1120,20)\nNextButton4.show()\n\nNextButton5 = Object('Images/clipart529527.png')\nNextButton5.setScale(0.1)\nNextButton5.locate(scene6,1120,20)\nNextButton5.show()\n\nNextButton6 = Object('Images/clipart529527.png')\nNextButton6.setScale(0.1)\nNextButton6.locate(scene7,1120,20)\nNextButton6.show()\n\nNoodle = Object('Images/6.png')\nNoodle.setScale(0.4)\nNoodle.locate(scene3,330,290)\nNoodle.show()\n\nSoy = Object('Images/7.png')\nSoy.setScale(0.6)\nSoy.locate(scene3,530,245)\nSoy.show()\n\nGarlic = Object('Images/8.png')\nGarlic.setScale(0.7)\nGarlic.locate(scene3,810,195)\nGarlic.show()\n\nMeat = Object('Images/9.png')\nMeat.setScale(0.4)\nMeat.locate(scene4,270,265)\nMeat.show()\n\nBananakick = Object('Images/10.png')\nBananakick.setScale(0.4)\nBananakick.locate(scene4,610,265)\nBananakick.show()\n\ngodung = Object('Images/11.png')\ngodung.setScale(0.5)\ngodung.locate(scene4,790,230)\ngodung.show()\n\nnam = Object('Images/nam.png')\nnam.setScale(1.0)\nnam.locate(scene9,300,0)\n\nMush = Object('Images/12.png')\nMush.setScale(0.2)\nMush.locate(scene5,270,265)\nMush.show()\n\nOil = Object('Images/13.png')\nOil.setScale(0.2)\nOil.locate(scene5,610,275)\nOil.show()\n\nOnion = Object('Images/14.png')\nOnion.setScale(0.2)\nOnion.locate(scene5,800,265)\nOnion.show()\n\nSalt = Object('Images/15.png')\nSalt.setScale(0.2)\nSalt.locate(scene6,270,265)\nSalt.show()\n\nTomato1 = Object('Images/16.png')\nTomato1.setScale(0.5)\nTomato1.locate(scene9, 570, 245)\n\nchocolate = Object('Images/pngwingcom.png')\nchocolate.setScale(0.15)\nchocolate.locate(scene6,610,275)\nchocolate.show()\n\ntomato = Object('Images/16.png')\ntomato.setScale(0.19)\ntomato.locate(scene6,850,265)\ntomato.show()\n\nBacon = Object('Images/17.png')\nBacon.setScale(0.4)\nBacon.locate(scene7,270,265)\nBacon.show()\n\nket = Object('Images/023.png')\nket.setScale(0.4)\nket.locate(scene7,610,275)\nket.show()\n\nButter = Object('Images/19.png')\nButter.setScale(0.5)\nButter.locate(scene7,850,265)\nButter.show()\n\nPrice = Object('Images/28000원.png')\nPrice.setScale(0.7)\nPrice.locate(scene8,100,150)\nPrice.show()\n\nPrice2 = Object('Images/29000원.png')\nPrice2.setScale(0.7)\nPrice2.locate(scene8,100,300)\nPrice2.show()\n\nPrice3 = Object('Images/30000원.png')\nPrice3.setScale(0.7)\nPrice3.locate(scene8,100,450)\nPrice3.show()\n\nPrice4 = Object('Images/31000원.png')\nPrice4.setScale(0.7)\nPrice4.locate(scene8,800,150)\nPrice4.show()\n\nPrice5 = Object('Images/32000원.png')\nPrice5.setScale(0.7)\nPrice5.locate(scene8,800,300)\nPrice5.show()\n\nPrice6 = Object('Images/33000원.png')\nPrice6.setScale(0.7)\nPrice6.locate(scene8,800,450)\nPrice6.show()\n\nNoNo = Object('Images/22.png')\nNoNo.setScale(0.8)\nNoNo.locate(scene9,330,90)\n\nhey = 0\nhed = 0\ngray = 1\ntotomama=0\ntotal=0\n\ntimer = Timer(10.)\n\npot = Object('Images/nana.png')\npot.setScale(1.0)\npot.locate(scene9,450,90)\n\ndef soundon_onMouseAction(x,y,action):\n sound2.stop()\n soundon.hide()\n soundoff.show()\nsoundon.onMouseAction = soundon_onMouseAction\n\ndef soundoff_onMouseAction(x,y,action):\n sound2.play()\n soundon.show()\n soundoff.hide()\nsoundoff.onMouseAction = soundoff_onMouseAction\n\ndef pot_onMouseAction(x,y,action):\n global total\n if NoNo.inHand():\n NoNo.drop()\n NoNo.hide()\n total = total + 1\n if tomatoma.inHand():\n tomatoma.drop()\n tomatoma.hide()\n total = total + 1\n if knife.inHand():\n showMessage('칼도 넣으려고?ㅋㅋ')\n if Butter.inHand():\n Butter.drop()\n Butter.hide()\n total = total + 1\n if ket.inHand():\n ket.drop()\n ket.hide()\n total = total + 1\n if Bacon.inHand():\n Bacon.drop()\n Bacon.hide()\n total = total + 1\n if Salt.inHand():\n Salt.drop()\n Salt.hide()\n total = total + 1\n if Onion.inHand():\n Onion.drop()\n Onion.hide()\n total = total + 1\n if Oil.inHand():\n Oil.drop()\n Oil.hide()\n total = total + 1\n if Mush.inHand():\n Mush.drop()\n Mush.hide()\n total = total + 1\n if Garlic.inHand():\n Garlic.drop()\n Garlic.hide()\n total = total + 1\n if total == 10:\n global hed\n hed = hed + 1\n timer.set(20.)\n sound1.play(True)\n timer.start()\npot.onMouseAction = pot_onMouseAction\n\ndef nam_onMouseAction(x,y,action):\n if Noodle.inHand():\n sound1.play(True)\n Noodle.drop()\n Noodle.hide()\n NoNo.show()\n showTimer(timer)\n timer.set(10.)\n timer.start()\n global hey\n hey=hey + 1\nnam.onMouseAction = nam_onMouseAction\n\ndef timer_onTimeout():\n global hey\n global hed\n if hey == 1:\n showMessage('면이 다 끓었어! 면을 꺼내주자')\n sound1.stop()\n global gray\n gray=gray-1\n hey=False\n if hed == 1:\n sound1.stop()\n showMessage('스파게티가 완성되었어! 맛있게 먹자!')\n scene10.enter()\ntimer.onTimeout = timer_onTimeout\n\ndef NoNo_onMouseAction(x,y,action):\n if gray==0:\n NoNo.pick()\n nam.hide()\n pot.show()\n showMessage('이제 남은 재료들을 다 use item 해서 냄비에 넣자!')\nNoNo.onMouseAction = NoNo_onMouseAction\ndef tomatoma_onMouseAction(x,y,action):\n tomatoma.pick()\n nam.show()\n showMessage('이제 사온 면을 Use item하고 팬에 넣자!')\ntomatoma.onMouseAction = tomatoma_onMouseAction\n\ndef Tomato1_onMouseAction(x,y,action):\n if knife.inHand():\n global totomama\n totomama = totomama +1\n if totomama==10:\n tomato.drop()\n tomato.hide()\n Tomato1.hide()\n tomatoma.show()\n showMessage('잘했어! 이제 토마토를 집어')\nTomato1.onMouseAction = Tomato1_onMouseAction\n\ndef knife_onMouseAction(x,y,action):\n knife.pick()\n showMessage('칼을들고 토마토를 연타하면 다져질거야')\nknife.onMouseAction = knife_onMouseAction\n\ndef Price_onMouseAction(x, y, action):\n showMessage('틀렸습니다!')\nPrice.onMouseAction = Price_onMouseAction\n\ndef Price2_onMouseAction(x, y, action):\n showMessage('틀렸습니다!')\nPrice2.onMouseAction = Price2_onMouseAction\n\ndef Price3_onMouseAction(x, y, action):\n showMessage('틀렸습니다!')\nPrice3.onMouseAction = Price3_onMouseAction\n\ndef Price5_onMouseAction(x, y, action):\n showMessage('틀렸습니다!')\nPrice5.onMouseAction = Price5_onMouseAction\n\ndef Price6_onMouseAction(x, y, action):\n showMessage('틀렸습니다!')\nPrice6.onMouseAction = Price6_onMouseAction\n\ndef Price4_onMouseAction(x, y, action):\n scene9.enter()\n showMessage('정답입니다! 집에 도착!')\nPrice4.onMouseAction = Price4_onMouseAction\n\ndef startButton_onMouseAction(x,y,action):\n scene2.enter()\nstartButton.onMouseAction = startButton_onMouseAction\n\ndef NextButton_onMouseAction(x,y,action):\n scene3.enter()\nNextButton.onMouseAction = NextButton_onMouseAction\n\ndef Noodle_onMouseAction(x, y, action):\n Noodle.pick()\n Noodle.picked=True\n showMessage('스파게티 면은 2000원이야!')\nNoodle.onMouseAction = Noodle_onMouseAction\n\ndef Soy_onMouseAction(x, y, action):\n showMessage('토마토 스파게티에 간장...? 별난친구네')\nSoy.onMouseAction = Soy_onMouseAction\n\ndef Bananakick_onMouseAction(x, y, action):\n showMessage('토마토 스파게티에 바나나킥...? 별난친구네')\nBananakick.onMouseAction = Bananakick_onMouseAction\n\ndef Meat_onMouseAction(x, y, action):\n showMessage('토마토 스파게티에 목살...? 별난친구네')\nMeat.onMouseAction = Meat_onMouseAction\n\ndef godung_onMouseAction(x, y, action):\n showMessage('토마토 스파게티에 고등어...? 별난친구네')\ngodung.onMouseAction = godung_onMouseAction\n\ndef chocolate_onMouseAction(x, y, action):\n showMessage('토마토 스파게티에 초콜릿...? 별난친구네')\nchocolate.onMouseAction = chocolate_onMouseAction\n\ndef Garlic_onMouseAction(x, y, action):\n Garlic.pick()\n Garlic.picked=True\n showMessage('다진마늘은 1500원이야!')\nGarlic.onMouseAction = Garlic_onMouseAction\n\ndef Mush_onMouseAction(x, y, action):\n Mush.pick()\n Mush.picked=True\n showMessage('버섯은 1500원이야!')\nMush.onMouseAction = Mush_onMouseAction\n\nNINGKA.picked=False\ndef NINGKA_onMouseAction(x, y, action):\n if NINGKA.picked==False:\n showMessage('요리를 시작할거야! 칼을 사용해서 토마토를 다져봐!')\n Tomato1.show()\n knife.show()\n NINGKA.picked=True\nNINGKA.onMouseAction = NINGKA_onMouseAction\n\ndef Oil_onMouseAction(x, y, action):\n Oil.pick()\n Oil.picked=True\n showMessage('올리브오일은 9500원이야!')\nOil.onMouseAction = Oil_onMouseAction\n\ndef Onion_onMouseAction(x, y, action):\n Onion.pick()\n Onion.picked=True\n showMessage('양파는 1500원이야!')\nOnion.onMouseAction = Onion_onMouseAction\n\ndef Salt_onMouseAction(x, y, action):\n Salt.pick()\n Salt.picked=True\n showMessage('소금는 1500원이야!')\nSalt.onMouseAction = Salt_onMouseAction\n\ndef tomato_onMouseAction(x, y, action):\n tomato.pick()\n tomato.picked=True\n showMessage('토마토는 4500원이야!')\ntomato.onMouseAction = tomato_onMouseAction\n\ndef Butter_onMouseAction(x, y, action):\n Butter.pick()\n Butter.picked=True\n showMessage('버터는 3500원이야!')\nButter.onMouseAction = Butter_onMouseAction\n\ndef Bacon_onMouseAction(x, y, action):\n Bacon.pick()\n Bacon.picked=True\n showMessage('베이컨은 4000원이야!')\nBacon.onMouseAction = Bacon_onMouseAction\n\ndef ket_onMouseAction(x, y, action):\n ket.pick()\n ket.picked=True\n showMessage('케첩은 1500원이야!')\nket.onMouseAction = ket_onMouseAction\n\ndef NextButton_onMouseAction(x,y,action):\n scene3.enter()\nNextButton.onMouseAction = NextButton_onMouseAction\n\ndef NextButton2_onMouseAction(x,y,action):\n if Noodle.picked==True and Garlic.picked==True:\n scene4.enter()\n else:\n showMessage('필요한걸 아직 사지 않았어!')\nNextButton2.onMouseAction = NextButton2_onMouseAction\n\ndef NextButton3_onMouseAction(x,y,action):\n scene5.enter()\nNextButton3.onMouseAction = NextButton3_onMouseAction\n\ndef NextButton4_onMouseAction(x,y,action):\n if Mush.picked==True and Oil.picked==True and Onion.picked==True:\n scene6.enter()\n else:\n showMessage('필요한걸 아직 사지 않았어!')\nNextButton4.onMouseAction = NextButton4_onMouseAction\n\ndef NextButton5_onMouseAction(x,y,action):\n if Salt.picked==True and tomato.picked==True:\n scene7.enter()\n else:\n showMessage('필요한걸 아직 사지 않았어!')\nNextButton5.onMouseAction = NextButton5_onMouseAction\n\ndef NextButton6_onMouseAction(x,y,action):\n if Butter.picked==True and Bacon.picked==True and ket.picked==True:\n scene8.enter()\n showMessage('산 물건을 계산할거에요! 자 얼마죠?')\n else:\n showMessage('필요한걸 아직 사지 않았어!')\nNextButton6.onMouseAction = NextButton6_onMouseAction\n\nstartGame(scene1)\n\n","sub_path":"MakingPasta/MakingPasta.py","file_name":"MakingPasta.py","file_ext":"py","file_size_in_byte":13320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"610032327","text":"from .fizz_buzz_tree import fizz_buzz_tree\n\nfrom .tree.binary_tree import BST\n\nimport pytest\n\n\n@pytest.fixture\ndef fizz_tree():\n \"\"\" tree with node values that match fizzbuzz \"\"\"\n tree = BST([5, 3, 15])\n return tree\n\n\n@pytest.fixture\ndef no_fizz_tree():\n \"\"\" tree with no nodes that match fizzbuzz \"\"\"\n tree = BST([2, 1, 4])\n return tree\n\n\ndef test_value_changes(fizz_tree):\n \"\"\" tests values before and after fizzbuzz function with nodes that match\n each condition \"\"\"\n assert fizz_tree.root.value == 5\n assert fizz_tree.root.left_child.value == 3\n assert fizz_tree.root.right_child.value == 15\n fizz_buzz_tree(fizz_tree)\n assert fizz_tree.root.value == 'Buzz'\n assert fizz_tree.root.left_child.value == 'Fizz'\n assert fizz_tree.root.right_child.value == 'FizzBuzz'\n\n\ndef test_no_value_changes(no_fizz_tree):\n \"\"\" tests values before and after with no nodes that match condition \"\"\"\n assert no_fizz_tree.root.value == 2\n assert no_fizz_tree.root.left_child.value == 1\n assert no_fizz_tree.root.right_child.value == 4\n fizz_buzz_tree(no_fizz_tree)\n assert no_fizz_tree.root.value == 2\n assert no_fizz_tree.root.left_child.value == 1\n assert no_fizz_tree.root.right_child.value == 4\n\n\ndef test_empty_tree():\n \"\"\" tests with empty tree \"\"\"\n tree = BST()\n assert tree.root is None\n fizz_buzz_tree(tree)\n assert tree.root is None\n\n\ndef test_wrong_input():\n \"\"\" tests that exception is raised when non-tree given as arg \"\"\"\n with pytest.raises(TypeError):\n fizz_buzz_tree('hello')\n","sub_path":"challenges/fizz_buzz_tree/test_fizz_buzz_tree.py","file_name":"test_fizz_buzz_tree.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"418115414","text":"# Django settings for dogwalk project.\nimport os\nimport sys\nimport json\n\nPROJECT_PATH = os.path.dirname(os.path.realpath(__file__))\n\nSTATIC_ROOT = os.path.join(PROJECT_PATH, '../staticfiles')\nSTATIC_URL = '/static/'\nMEDIA_ROOT = os.path.join(PROJECT_PATH, 'media')\nMEDIA_URL = '/media/'\n\nDEBUG = True\nTEMPLATE_DEBUG = DEBUG\n\nADMINS = (\n # ('Your Name', 'your_email@example.com'),\n)\n\nMANAGERS = ADMINS\n\nDATABASES = {\n 'default': {\n 'ENGINE': '', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.\n 'NAME': 'dogwalk', # Or path to database file if using sqlite3.\n # The following settings are not used with sqlite3:\n 'USER': '',\n 'PASSWORD': '',\n 'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.\n 'PORT': '', # Set to empty string for default.\n }\n}\n\n# Hosts/domain names that are valid for this site; required if DEBUG is False\n# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts\nALLOWED_HOSTS = []\n\n# Local time zone for this installation. Choices can be found here:\n# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name\n# although not all choices may be available on all operating systems.\n# In a Windows environment this must be set to your system time zone.\nUSE_TZ = False\nTIME_ZONE = 'America/New_York'\n\n# Language code for this installation. All choices can be found here:\n# http://www.i18nguy.com/unicode/language-identifiers.html\nLANGUAGE_CODE = 'en-us'\n\nSITE_ID = 1\n\n# If you set this to False, Django will make some optimizations so as not\n# to load the internationalization machinery.\nUSE_I18N = True\n\n# If you set this to False, Django will not format dates, numbers and\n# calendars according to the current locale.\nUSE_L10N = True\n\n# If you set this to False, Django will not use timezone-aware datetimes.\nUSE_TZ = False\n\n# Absolute filesystem path to the directory that will hold user-uploaded files.\n# Example: \"/var/www/example.com/media/\"\n\n# URL that handles the media served from MEDIA_ROOT. Make sure to use a\n# trailing slash.\n# Examples: \"http://example.com/media/\", \"http://media.example.com/\"\n\n# Absolute path to the directory static files should be collected to.\n# Don't put anything in this directory yourself; store your static files\n# in apps' \"static/\" subdirectories and in STATICFILES_DIRS.\n# Example: \"/var/www/example.com/static/\"\n\n# URL prefix for static files.\n# Example: \"http://example.com/static/\", \"http://static.example.com/\"\n\n# Additional locations of static files\nSTATICFILES_DIRS = (\n # Put strings here, like \"/home/html/static\" or \"C:/www/django/static\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n)\n\n# List of finder classes that know how to find static files in\n# various locations.\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n# 'django.contrib.staticfiles.finders.DefaultStorageFinder',\n)\n\n# Make this unique, and don't share it with anybody.\nSECRET_KEY = ')-rbjy9n*dybxz)^lf5tk_cdgm)j17%q2a+46x-f3o8vmn0%03'\n\n# List of callables that know how to import templates from various sources.\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n# 'django.template.loaders.eggs.Loader',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n #'django.middleware.csrf.CsrfViewMiddleware', #FIXTHIS\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n # Uncomment the next line for simple clickjacking protection:\n # 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nROOT_URLCONF = 'dogwalk.urls'\n\n# Python dotted path to the WSGI application used by Django's runserver.\nWSGI_APPLICATION = 'dogwalk.wsgi.application'\n\nTEMPLATE_DIRS = (\n os.path.join(PROJECT_PATH, '../templates'),\n)\n\nINSTALLED_APPS = (\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django.contrib.admin',\n 'django_extensions',\n 'fixture_magic',\n 'south',\n 'dogwalk',\n 'dog',\n 'graph',\n 'schedule'\n)\n\n# A sample logging configuration. The only tangible logging\n# performed by this configuration is to send an email to\n# the site admins on every HTTP 500 error when DEBUG=False.\n# See http://docs.djangoproject.com/en/dev/topics/logging for\n# more details on how to customize your logging configuration.\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'formatters': {\n 'verbose': {\n 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'\n },\n 'MA': {\n 'format': '%(levelname)s\\t%(time).16s\\t%(walker).6s\\t%(node).12s\\t%(carrying).80s\\t%(message)s'\n },\n 'MS': {\n 'format': '%(message)s'\n },\n 'MV': {\n 'format': '%(levelname)s\\t%(start).16s\\t%(end).16s\\t\\t%(dog).6s\\t%(days)d\\t%(events)d\\t%(cancellations)s\\t%(message)s'\n }\n },\n 'handlers': {\n 'MA': {\n 'level': 'DEBUG',\n 'class': 'logging.FileHandler',\n 'filename': 'MA.log',\n 'formatter': 'MA'\n },\n 'MS': {\n 'level': 'DEBUG',\n 'class': 'logging.FileHandler',\n 'filename': 'MS.log',\n 'formatter': 'MS'\n },\n 'MV': {\n 'level': 'DEBUG',\n 'class': 'logging.FileHandler',\n 'filename': 'MV.log',\n 'formatter': 'MV'\n }\n },\n 'loggers': {\n 'MA': {\n 'handlers': ['MA'],\n 'level': 'DEBUG',\n 'propagate': True,\n },\n 'MS': {\n 'handlers': ['MS'],\n 'level': 'DEBUG',\n 'propagate': True,\n },\n 'MV': {\n 'handlers': ['MV'],\n 'level': 'DEBUG',\n 'propagate': True,\n }\n }\n}\n\n# Honor the 'X-Forwarded-Proto' header for request.is_secure()\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n\n# Parse database configuration from $DATABASE_URL\ndb = {'username': 'postgres',\n 'password': 'beffy44',\n 'name': 'dogwalk',}\n\nimport dj_database_url\nDATABASES['default'] = dj_database_url.config(\n default='postgres://%s:%s@localhost:5432/%s' % (\n db['username'], \n db['password'], \n db['name'])\n )\n\n#if 'test' in sys.argv:\n# DATABASES['default'] = {'ENGINE': 'django.db.backends.sqlite3'}\n\nSOUTH_TESTS_MIGRATE = False\nTEST_RUNNER = 'ignoretests.DjangoIgnoreTestSuiteRunner'\n\nIGNORE_TESTS = (\n 'django_extensions',\n)\n\n\n","sub_path":"dogwalk/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":7089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"288958287","text":"from flask import Flask, request, redirect, render_template, flash\nfrom mysqlconnection import MySQLConnector\nimport re\n\napp = Flask(__name__)\napp.secret_key = 'ThisIsSecret'\nmysql = MySQLConnector(app, 'semi_restful_usersdb')\n# regex to test whether inputted email is valid\nemail_regex = re.compile(r'^[a-zA-Z0-9\\.\\+_-]+@[a-zA-Z0-9\\._-]+\\.[a-zA-z]*$')\n\n# displays all users stored in the database\n@app.route('/users')\ndef index():\n query = 'SELECT id, CONCAT(first_name, \" \", last_name) AS name,\\\n email, DATE_FORMAT(created_at, \"%M %D, %Y\") AS created_at\\\n FROM users ORDER BY id'\n users = mysql.query_db(query)\n return render_template('index.html', users=users)\n\n# displays page with form allowing new users to be added into the database\n@app.route('/users/new')\ndef new():\n return render_template('new.html')\n\n# displays page with form allowing users to edit a particular, existing user\n# given a specific id\n@app.route('/users//edit')\ndef edit(id):\n query = 'SELECT * FROM users WHERE id = :id'\n data = {\n 'id': id\n }\n user = mysql.query_db(query, data)\n return render_template('edit.html', user=user[0])\n\n# displays information for a user given a specific id\n@app.route('/users/')\ndef show(id):\n query = 'SELECT id, CONCAT(first_name, \" \", last_name) AS name,\\\n email, DATE_FORMAT(created_at, \"%M %D, %Y\") AS created_at\\\n FROM users WHERE id = :id'\n data = {\n 'id': id\n }\n user = mysql.query_db(query, data)\n return render_template('show.html', user=user[0])\n\n# stores information about a new user into the database\n@app.route('/users/create', methods=['POST'])\ndef create():\n # tests whether inputted email address is valid\n if not email_regex.match(request.form['email']):\n flash(\"Invalid Email Address!\")\n else:\n query = 'INSERT INTO users (first_name, last_name, email, created_at, updated_at)\\\n VALUES (:first_name, :last_name, :email, NOW(), NOW())'\n data = {\n 'first_name': request.form['first_name'],\n 'last_name': request.form['last_name'],\n 'email': request.form['email']\n }\n mysql.query_db(query, data)\n return redirect('/users')\n\n# deletes information from the database related to a user given a specific id\n@app.route('/users//destroy')\ndef destroy(id):\n query = 'DELETE FROM users WHERE id = :id'\n data = {\n 'id': id\n }\n mysql.query_db(query, data)\n return redirect('/users')\n\n# updates information in the database related to a specific user with a given id\n@app.route('/users/', methods=['POST'])\ndef update(id):\n query = 'UPDATE users\\\n SET first_name = :first_name, last_name = :last_name, email = :email,\\\n updated_at = NOW()\\\n WHERE id = :id'\n data = {\n 'first_name': request.form['first_name'],\n 'last_name': request.form['last_name'],\n 'email': request.form['email'],\n 'id': id\n }\n mysql.query_db(query, data)\n return redirect('/users')\n\napp.run(debug=True)\n","sub_path":"Flask_MySQL/semi_restful_users/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"30321564","text":"#! /usr/bin/env python3\n\n# Write a program to convert an list of digits into a 8 segment display read out.\n# Eg, given [3, 4, 5, 6], output is:\n#\n# _ _ _\n# _| |_| |_ |_\n# _| | _| |_|\n\n# Hint: Store the 7-segment representation of each digit in a list of 3 strings\n# with each string representing one line of the number.\n#\n# eg: three = [ \" _ \", \" _|\", \" _|\" ]\n#\n\nimport sys\nscan_lines = [\n [ \" _ \", \"| |\", \"|_|\" ], # 0\n [ \" \", \" |\", \" |\" ], # 1\n [ \" _ \", \" _|\", \"|_ \" ], # 2\n [ \" _ \", \" _|\", \" _|\" ], # 3\n [ \" \", \"|_|\", \" |\" ], # 4\n [ \" _ \", \"|_ \", \" _|\" ], # 5\n [ \" _ \", \"|_ \", \"|_|\" ], # 6\n [ \" _ \", \" |\", \" |\" ], # 7\n [ \" _ \", \"|_|\", \"|_|\" ], # 8\n [ \" _ \", \"|_|\", \" |\" ], # 9\n]\n\ninput = int(sys.argv[1])\ndef int_to_digits(input):\n if input == 0:\n return []\n else:\n last_digit = input%10\n remaining_number = int(input/10)\n remaining_digits = int_to_digits(remaining_number)\n return remaining_digits + [last_digit]\n\nprint(int_to_digits(input))\nfor line_number in range(0, 3):\n for digit in int_to_digits(input):\n print(scan_lines[digit][line_number], end=\"\")\n print(\"\")\n","sub_path":"exercises/03-seven-segment-display.py","file_name":"03-seven-segment-display.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"619882999","text":"# Copyright 2014 Symantec Corporation.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport unittest\nimport mock\nfrom magnetodb.common.middleware import rate_limit\n\n\nclass TestRateLimit(unittest.TestCase):\n \"\"\"Unit tests for rate limiting.\"\"\"\n\n _DEFAULT_TENANT_ID = \"default_tenant\"\n\n def test_get_tenant_id(self):\n expected_tenant_id = self._DEFAULT_TENANT_ID\n path = (rate_limit.MDB_DATA_API_URL_PREFIX +\n expected_tenant_id +\n \"/tables\")\n tenant_id = rate_limit.get_tenant_id(path)\n\n self.assertEqual(expected_tenant_id, tenant_id)\n\n def setUp(self):\n self.ratelimit_middleware = rate_limit.RateLimitMiddleware(\n None,\n dict(rps_per_tenant=1))\n self.request = mock.Mock()\n\n def test_process_request_get_tenant_id_from_path(self):\n self.request.path = (rate_limit.MDB_DATA_API_URL_PREFIX +\n self._DEFAULT_TENANT_ID +\n \"/tables\")\n self.ratelimit_middleware.process_request(self.request)\n self.assertIn(self._DEFAULT_TENANT_ID,\n self.ratelimit_middleware.last_time)\n\n def test_process_request_get_tenant_id_from_header(self):\n self.request.path = None\n self.request.headers = {\n 'X-Tenant-Id': self._DEFAULT_TENANT_ID\n }\n self.ratelimit_middleware.process_request(self.request)\n self.assertIn(self._DEFAULT_TENANT_ID,\n self.ratelimit_middleware.last_time)\n","sub_path":"magnetodb/tests/unittests/common/middleware/test_ratelimit.py","file_name":"test_ratelimit.py","file_ext":"py","file_size_in_byte":2053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"13561412","text":"#compiler.py\n\n#init logger\nfrom utils import logger_util\nimport inspect\n\n#init jinja\nfrom jinja2 import Environment, FileSystemLoader\ntemplates_path = None\ntemplates_functions = None\n\n#init compiler (set jinja globals and logging level)\ndef init(templates_path,templates_functions, logging_level=None):\n if logging_level == \"INFO\" or \"DEBUG\":\n logger_util._logging_level = logging_level\n globals()['templates_path'] = templates_path\n globals()['templates_functions'] = templates_functions\n\n#compile jinja template (logger decorator)\n@logger_util.logger_func(__name__, __file__, inspect.currentframe().f_lineno)\ndef compile(type, metadata):\n logger_util._caller = inspect.stack()[2][1]\n logger_util._line = inspect.stack()[2][2]\n env = Environment(loader=FileSystemLoader(templates_path))\n dt = env.get_template(type)\n for template_function in templates_functions:\n dt.globals[template_function] = globals()[template_function]\n return dt.render(metadata)\n\n\n#TESTING\n#passing functions to jinja templates (for Resmi's package)\ndef k8s2adt1(key):\n dict1 = {\"var1\":1,\"var2\":2,\"var3\":3}\n dict2 = {\"var3\": 1, \"var4\": 2, \"var5\": 3}\n if key == 1: return dict1\n if key == 2: return dict2\ndef k8s2adt2(key):\n dict3 = {\"var11\":11,\"var22\":22,\"var33\":33}\n dict4 = {\"var33\": 33, \"var44\": 44, \"var55\": 55}\n if key == 3: return dict3\n if key == 4: return dict4\n\n\n","sub_path":"compiler/compiler.py","file_name":"compiler.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"30819738","text":"import sys\n\ndef vcf_complete(input_path, output_path):\n\n reduced = []\n with open(input_path, 'r') as input,\\\n open(output_path, 'w+') as output:\n\n for line in input:\n if line.startswith('#'):\n continue\n fields = line.split('\\t')\n aligned = fields[4]\n if aligned != '<*>':\n\n # Write and append only if alignment is associate to complete information\n output.write(line)\n reduced.append(line)\n\n return reduced\n\n\ndef vcf_indel(reduced_vcf, output_path):\n\n indel_vcf = []\n with open(output_path, 'w+') as f:\n for line in reduced_vcf:\n fields = line.split('\\t')\n if fields[7].startswith('INDEL'):\n indel_vcf.append(line)\n f.write(line)\n\n\nif __name__ == '__main__':\n args = sys.argv[1:]\n input_path = args[0]\n reduced_output = args[1]\n indel_output = args[2]\n\n reduced_vcf = vcf_complete(input_path, reduced_output)\n indel_vcf = vcf_indel(reduced_vcf, indel_output)\n","sub_path":"Exam/LAB3/a1.py","file_name":"a1.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"486615777","text":"import urllib\nimport json\nimport sys\nimport pprint\nimport string\n\nclass archive_searcher:\n\tdef __init__(self,maxResults):\n\t\tself.maxResults\t\t= maxResults\n\t\tself.urlAvailable\t= \"https://archive.org/advancedsearch.php?q=%s&mediatype=&rows=1&page=1&output=json&save=no#raw\"\n\t\tself.urlGetTitles\t= \"https://archive.org/advancedsearch.php?q=%s&mediatype=&rows=%d&page=1&output=json&save=no#raw\"\n\t\tself.urlGetURL\t\t= \"https://archive.org/details/%s&output=json&callback=IAE.favorite\"\n\t\tself.engine\t\t\t= \"archive\"\n\n\tdef _find_available(self,extension):\n\t\t'''\n\t\tSearcher._find_available(\"exe\")\n\t\treturns number of files of given type\n\t\tavailable for download\n\t\t'''\n\t\tself.extension\t\t= extension\n\t\tself.numberFound\t= json.loads(\n\t\t\turllib.urlopen(self.urlAvailable%self.extension).read()\n\t\t\t)[\"response\"][\"numFound\"]\n\t\treturn self.numberFound\n\n\tdef _get_titles(self):\n\t\t'''\n\t\tSearcher._get_titles()\n\t\treturns a list of titles for files which\n\t\tis required for final query to download file\n\t\t'''\n\t\tqueryNum\t\t\t= min(self.maxResults,self.numberFound)\t\t\t# only return the max results we want\n\t\tdata\t\t\t\t= json.loads(\n\t\t\turllib.urlopen(self.urlGetTitles%(self.extension,queryNum)).read()\n\t\t\t)\n\n\t\tresults = []\n\t\tfor i in xrange(self.numberFound -1):\n\t\t\ttry:\n\t\t\t\t# to prevent multiple lookups:\n\t\t\t\td = data[\"response\"][\"docs\"][i][\"title\"]\n\n\t\t\t\t# file ends with correct extension?\n\t\t\t\tif d.lower().endswith(\".%s\"%self.extension.lower()):\n\n\t\t\t\t\t# all characters in filename printable?\n\t\t\t\t\tif all(c in string.printable for c in d):\n\n\t\t\t\t\t\t# replace spaces with underscores\n\t\t\t\t\t\tif \" \" in d:\n\t\t\t\t\t\t\tresults.append(d.replace(\" \",\"_\"))\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tresults.append(d)\n\t\t\texcept:\n\t\t\t\tpass\n\n\t\t\t# stop collecting filenames if we hit max result threshold\n\t\t\tif (len(results) == (self.maxResults)):\n\t\t\t\treturn results\n\t\treturn results\n\n\tdef _get_urls(self,filenames):\n\t\t'''\n\t\tSearcher._get_urls(fileNameList[])\n\t\treturns a list of links to download files,\n\t\tgiven a list of filenames from the \n\t\t_get_titles method\n\t\t'''\n\t\tresults = []\n\t\tfor filename in filenames:\n\t\t\ttry:\n\t\t\t\tdata = json.loads(\n\t\t\t\t\t# json response is encapsulated by IAE.favorite( ... ), hence the [13:-1] crop\n\t\t\t\t\turllib.urlopen(self.urlGetURL % filename).read()[13:-1]\n\t\t\t\t\t)\n\t\t\t\tlink = \"https://%s%s/%s\"%( data[\"server\"], data[\"dir\"],data[\"dir\"].split(\"/\")[-1])\n\t\t\t\tresults.append(link)\n\t\t\texcept:\n\t\t\t\tpass\n\t\treturn results\n\n","sub_path":"archive_searcher.py","file_name":"archive_searcher.py","file_ext":"py","file_size_in_byte":2374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"331173124","text":"#!/usr/bin/python3\n# -*- coding:utf-8 -*-\n\"\"\"\n@Author: billx\n@Date: 2018/9/4\n@Descript:\n\"\"\"\nimport threading\nimport queue\nimport random\nimport time\n\n\nclass Worker(threading.Thread):\n def __init__(self, q):\n threading.Thread.__init__(self)\n self.q = q\n self.sentinel = object()\n\n def run(self):\n\n for i in range(10):\n self._maker()\n self.q.put(self.sentinel)\n\n def _maker(self):\n stuff = random.randint(1000, 5000)\n if not q.full():\n print('[IN] maker:', stuff, 'que:', q.qsize(), 'thread:', threading.current_thread().getName())\n self.q.put(stuff)\n time.sleep(0.3)\n else:\n print('{} wait..'.format(threading.current_thread().getName()))\n time.sleep(2)\n\n\nclass User(threading.Thread):\n def __init__(self, q, end_flag):\n threading.Thread.__init__(self)\n self.q = q\n self.end_flag = end_flag\n\n def run(self):\n while 1:\n if self._user() is False:\n break\n\n def _user(self):\n if not q.empty():\n stuff = self.q.get()\n if stuff != self.end_flag:\n print('[OUT] user:', stuff, 'que:', q.qsize(), 'thread:', threading.current_thread().getName())\n time.sleep(1)\n else:\n # 你不能把结束FLAG据为己有,其他线程干等着?\n self.q.put(stuff)\n return False\n else:\n # 队列空了就等一会\n print('{} wait..'.format(threading.current_thread().getName()))\n time.sleep(2)\n\n\nq = queue.Queue(maxsize=10)\npool = set()\nwork1 = Worker(q)\nuser1 = User(q, work1.sentinel)\nuser2 = User(q, work1.sentinel)\n# 可以添加到线程池,方便start和join\npool.add(work1)\npool.add(user1)\npool.add(user2)\n\nfor t in pool:\n t.start()\n\nfor t in pool:\n t.join()\n\n# 上面不join的话,下面的程序并不会等线程执行完执行,而是直接自己一个人玩去了\nprint('done.')\n\n\n\n","sub_path":"day16_multi_proccess.py","file_name":"day16_multi_proccess.py","file_ext":"py","file_size_in_byte":2028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"405321837","text":"import pandas as pd\nimport datetime\nfrom datetime import date\nimport plotly.express as px\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\nimport sqlite3\nimport numpy as np\nimport boto3\n\n# # Module 1 Pubmed Crawler ####################################################################################\n# Pubmed crawler module tht can collect paper title, author list, publication time, and abstract from PUBMED for a given keyword (i.e., COVID-19 Vaccine) within a specified time window.\n\n#get date ranges to use in pubmed query\ntoday = date.today()\ncur_date = today.strftime(\"%Y/%m/%d\")\n\nlast_week = (today-datetime.timedelta(days=7)).strftime(\"%Y/%m/%d\")\nprint(cur_date, last_week)\n\n\n#write Pubmed search query\nfrom Bio import Entrez\n\n#returns list of article ids that contain keyword \ndef search(query):\n Entrez.email = 'bdbacik@gmail.com'\n handle = Entrez.esearch(db='pubmed',\n sort='relevance',\n retmax='100000',\n retmode='xml',\n datetype='pdat',\n mindate=last_week,\n maxdate=cur_date,\n term=query)\n search_results = Entrez.read(handle)\n return search_results\n\n#users article ids as input and returns dictionary with article details\ndef fetch_details(id_list):\n ids = ','.join(id_list)\n Entrez.email = 'bdbacik@gmail.com'\n handle = Entrez.efetch(db='pubmed',\n retmode='xml',\n id=ids)\n fetch_results = Entrez.read(handle)\n return fetch_results\n\n\nif __name__ == '__main__':\n search_results = search('COVID-19 vaccine')\n id_list = search_results['IdList']\n fetch_results = fetch_details(id_list)\n\n\nprint('length of esearch output: ', len([item for item in search_results['IdList']]))\nprint('length of efetch output: ', len([key for key in fetch_results['PubmedArticle']]))\n\n\n#pull relevant fields from query into pandas dataframe\nsearchoutput = {\"Title\":[], \"Keywords\":[], \"PublicationDate\": [], \"Authors\": [], \n \"Abstract\": [], 'Country':[]}\nfor i, paper in enumerate(fetch_results['PubmedArticle']): \n try:\n Title = paper['MedlineCitation']['Article']['ArticleTitle']\n Keywords = paper['MedlineCitation']['KeywordList']\n PublicationDate = paper['MedlineCitation']['Article']['Journal']['JournalIssue']['PubDate']#['Month']\n Authors = paper['MedlineCitation']['Article']['AuthorList']\n Abstract = paper['MedlineCitation']['Article']['Abstract']['AbstractText'][0]\n Country = paper['MedlineCitation']['MedlineJournalInfo']['Country']\n except KeyError as e:\n continue\n searchoutput[\"Title\"].append(Title)\n searchoutput[\"Keywords\"].append(Keywords)\n searchoutput[\"PublicationDate\"].append(PublicationDate)\n searchoutput[\"Authors\"].append(Authors)\n searchoutput[\"Abstract\"].append(str(Abstract))\n searchoutput[\"Country\"].append(Country)\n\ndf = pd.DataFrame(searchoutput)\n\n#get publication date in YYYYMM \ndf['Pub_Year'] = [str(d.get('Year')) for d in df['PublicationDate']]\ndf['Pub_Month'] = [str(d.get('Month')) for d in df['PublicationDate']]\ndf[\"Pub_Month\"] = df[\"Pub_Month\"].replace([\"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\"Jun\",\"Jul\",\"Aug\",\"Sep\",\"Oct\",\"Nov\",\"Dec\"],[\"01\",\"02\",\"03\",\"04\",\"05\",\"06\",\"07\",\"08\",\"09\",\"10\",\"11\",\"12\"])\ndf['Pub_Date'] = pd.to_datetime(df.Pub_Year+'-'+df.Pub_Month, errors='ignore')\ndf = df.drop(columns=['PublicationDate','Pub_Year','Pub_Month'])\n\n#make separate df with multi value attribute columns \nkeywords = df.explode('Keywords').explode('Keywords').iloc[:,:2]\nkeywords['Keywords'] = keywords['Keywords'].str.lower()\n\n\n#create new dataframe with columns for first and last name of each author of each paper\nauthors = df.explode('Authors')['Authors'].apply(pd.Series).loc[:,['LastName','ForeName','AffiliationInfo']]\nauthors[\"Author\"] = authors[\"ForeName\"].str.cat(authors[\"LastName\"], sep=\" \")\n#merge original df and df2 with author names\ndf3 = pd.merge(df,authors,left_index=True,right_index=True)\ndf3 = df3[[\"Title\", \"Author\", 'AffiliationInfo']]\ndf3['AffiliationInfo'] = df3['AffiliationInfo'].astype(str)\ndf3['AffiliationInfo'] = df3.apply(lambda x: x['AffiliationInfo'].split('Affiliation')[-1], axis=1).str[3:-2]\n\n#remove duplicate columns from main df\ndf = df.drop(columns=['Keywords','Authors'])\n\n\n# # Module 2 - Database Development ####################################################################\n# 1. Builds SQLite database to store our pubmed crawler output. \n# 2. Create SQL tables to represent data from module 1.\n# 3. Query tables to get key statistics and setup for visualization.\n\n# ## Create database\nconn = sqlite3.connect('pubmed.db') # create a new database or connect to database if already exists\nc = conn.cursor() # create connection object\n\n\n# ## Create tables and add data to them\n# We have three tables in the database:\n# 1. pub_info - this contains the main information about the publication, including author, abstract, country published in, and publication date\n# 2. authors - this table contains author name and affiliaition, with title as foreign key\n# 3. keywords - this table contains keywords for each article, with title as foreign key\n\n# Create pub_info table\ntry:\n c.execute('''CREATE TABLE pub_info\n ([Title] text, [Abstract] text, [Country] text, [Pub_Date] text)''')\n conn.commit()\n print('SQL table created successfully!')\n\nexcept:\n print('SQL table already exists!')\n\n#add data to sql table from our pandas dataframe\ndf.to_sql('pub_info', conn, if_exists='append', index=False)\n\n#query database to get the number of publications by country\npubs_by_country = c.execute('''SELECT DISTINCT Country, count() OVER(PARTITION BY Country) as Num_Publications\n FROM pub_info \n ORDER BY Num_Publications DESC \n ''').fetchall()\n\n#query database to get the number of publications by month\npubs_by_month = c.execute('''SELECT Pub_date, count(Pub_Date) as Pubs_by_month\n FROM pub_info \n GROUP BY Pub_date\n ORDER BY Pubs_by_month DESC \n ''').fetchall()\n\n# Create authors table\ntry:\n c.execute('''CREATE TABLE authors\n ([Title] text, [Author] text, [AffiliationInfo] text)''')\n conn.commit()\n print('SQL table created successfully!')\n\nexcept:\n print('SQL table already exists!')\n\n\n#add data to sql table from our pandas dataframe\ndf3.to_sql('authors', conn, if_exists='append', index=False)\n\n\n#query database to find top 10 authors by number of publications\ntop_authors = c.execute('''SELECT DISTINCT Author, count(Author) as Count, AffiliationInfo\n FROM authors \n WHERE Author IS NOT NULL\n GROUP BY Author\n ORDER BY Count DESC \n LIMIT 10''').fetchall()\n\n# Create keywords table\ntry:\n c.execute('''CREATE TABLE keywords\n ([Title] text, [Keywords] text)''')\n conn.commit()\n print('SQL table created successfully!')\n\nexcept:\n print('SQL table already exists!')\n\n\n#add data to sql table from our pandas dataframe\nkeywords.to_sql('keywords', conn, if_exists='append', index=False)\n\n\n#query database to find top 10 keywords\ntop_keywords = c.execute('''SELECT Keywords, count(Keywords) as Count\n FROM keywords\n GROUP BY Keywords\n ORDER BY Count DESC \n LIMIT 20''').fetchall()\ntop_keywords[0:20]\n\n\n# # Module 3 - Visualization ################################################################################\n# Use SQL query output to produce a dashboard summarizing key statistics related to publications\n\n# ## 1. Publications by month\n#convert SQL query output to pandas df for visualization\ndf_pubs_by_month = pd.DataFrame(pubs_by_month, columns=['Pub_Date', 'Count'])\ndf_pubs_by_month['Pub_Date'] = df_pubs_by_month['Pub_Date'].astype(str)\ndf_pubs_by_month.head()\n\n\n# ## 2. Publications by country\n#convert SQL query output to pandas df for visualization\ndf_pubs_by_country = pd.DataFrame(pubs_by_country, columns=['Country', 'Num_Publications'])\ntotal_pubs = df_pubs_by_country['Num_Publications'].sum()\nprint(total_pubs)\ndf_pubs_by_country['Percent_Pubs'] = df_pubs_by_country['Num_Publications']/total_pubs\ndf_pubs_by_country.head()\n\n\n# ## 3. Publications by author\ndf_top_authors = pd.DataFrame(top_authors,columns=['Author', 'Count', 'Affiliation'])\ndf_top_authors.head()\n\n\n# ## Create Dashboard\n# using plotly\n\n#create dashboard to visualize publications by month, trend over time, and summary statistics\n\n#define subplot figure contents\nfig = make_subplots(\n rows=3, cols=1,\n subplot_titles=(\"Publications by Month\", \"Publications by Country\", \"Top Authors by Number of Publications\"),\n shared_xaxes=False,\n vertical_spacing=0.1,\n specs=[[{\"type\": \"bar\"}],\n [{\"type\": \"bar\"}],\n [{\"type\": \"table\"}]])\n\n#create histogram in first row\nfig.add_trace(go.Bar(x=df_pubs_by_month.loc[:12,'Pub_Date'], y=df_pubs_by_month.loc[:12,'Count'],text=df_pubs_by_month.loc[:12,'Count'],\n textposition='auto',name='Publications by Month'), row=1, col=1 )\nfig.update_xaxes(\n dtick=1,\n tick0=1,\n tickformat=\"%m\\n%Y\", type='category')\n#fig.update_layout(xaxis = dict(tickformat=\"%b\\n%Y\" ))\n\n#create boxplot in second row\nfig.add_trace(go.Bar(x=df_pubs_by_country.loc[:10,'Country'], y=df_pubs_by_country.loc[:10,'Num_Publications'],text=df_pubs_by_country.loc[:10,'Num_Publications'],\n textposition='auto',name='Publications by Country'), row=2, col=1 )\nfig.update_layout(xaxis = dict(tickmode = 'linear',tick0 = 1,dtick = 1 ))\n\n#create summary statistics table in thirs row\nfig.add_trace(go.Table(header=dict(values=['Author', 'Publications', 'Affiliations']), \n cells=dict(values=[df_top_authors.loc[:2,'Author'], df_top_authors.loc[:2,'Count'], \n df_top_authors.loc[:2,'Affiliation']])), row=3, col=1)\n\n#define layout\nfig.update_layout(\n height=1000,\n showlegend=False,\n title_text=\"PubMed Publications for Research Related to Covid-19 Vaccine\")\n\nfig.show()\n\n#save image to local machine\nfig.write_image(\"pubmed_dashboard2.png\", scale=1, width=1200, height=1200)\n\n#upload image to AWS\ns3 = boto3.resource('s3')\ns3.meta.client.upload_file('pubmed_dashboard2.png', 'pubmedcrawler', 'pubmed_dashboard2.png', \n ExtraArgs={'ACL':'public-read'})\n\n\n\n\n","sub_path":"Pubmed_Crawler.py","file_name":"Pubmed_Crawler.py","file_ext":"py","file_size_in_byte":10704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"532599726","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nfrom __future__ import division\n\n'''here we will place some *function* for generally use.'''\n\nimport os,sys\nimport logging\n\nfrom expython.exceptions import NotIntegerError\nfrom expython.compat import ispy35\nimport errno\nfrom pathlib import Path\n\ndef mkdirs(path,mode=0o777):\n '''\n Recursive directory creation function base on os.makedirs with a little error handling.\n\n and also create a alias name : *makedirs*\n '''\n try:\n os.makedirs(path,mode=mode)\n except OSError as e:\n if e.errno != errno.EEXIST:#File exists\n raise\n\n\ndef normalized_path(path='.'):\n '''\n for better path operation, normalized path,input str type(or Path type),output Path type\n you can use p.is_absolute() check if it is a absolute path, here we donot\n do the conversion. you can use Path(os.path.abspath(str(Path))) get it, if\n you really need it..\n\n which default support the '~'\n\n>>> normalized_path()\nPosixPath('.')\n>>> normalized_path('what')\nPosixPath('what')\n>>> normalized_path(Path('test'))\nPosixPath('test')\n>>> normalized_path(123)\nTraceback (most recent call last):\nTypeError\n\n '''\n\n if isinstance(path,Path):\n if ispy35:\n return path.expanduser()\n else:\n return Path(os.path.expanduser(str(path)))\n elif isinstance(path,str):\n if path.startswith('~'):###\n path = os.path.expanduser(path)\n return Path(path)### we do not convert it to absolute path form\n else:\n raise TypeError\n\n\n\ndef is_even(n):\n '''is this number is even, required input n is a integer.\n\n>>> is_even(0)\nTrue\n>>> is_even(-1)\nFalse\n>>> is_even(-2)\nTrue\n\n '''\n if not isinstance(n, int):\n raise NotIntegerError\n\n if n % 2 ==0:\n return True\n else:\n return False\n\ndef is_odd(n):\n '''is this number is odd, required input n is a integer.'''\n return not is_even(n)\n\n\n\ndef humanize_bytes(n, precision=1):\n # Author: Doug Latornell\n # Licence: MIT\n # URL: http://code.activestate.com/recipes/577081/\n \"\"\"Return a humanized string representation of a number of bytes.\n\n Assumes `from __future__ import division`.\n\n>>> humanize_bytes(1)\n'1 B'\n>>> humanize_bytes(1024)\n'1.0 KiB'\n>>> humanize_bytes(1024 * 123)\n'123.0 KiB'\n>>> humanize_bytes(1024 * 12342)\n'12.1 MiB'\n>>> humanize_bytes(1024 * 12342, 2)\n'12.05 MiB'\n>>> humanize_bytes(1024 * 1234, 2)\n'1.21 MiB'\n>>> humanize_bytes(1024 * 1234 * 1111, 2)\n'1.31 GiB'\n>>> humanize_bytes(1024 * 1234 * 1111 * 1024)\n'1.3 TiB'\n>>>\n\n \"\"\"\n abbrevs = [\n (1 << 80, 'YiB'),\n (1 << 70, 'ZiB'),\n (1 << 60, 'EiB'),\n (1 << 50, 'PiB'),\n (1 << 40, 'TiB'),\n (1 << 30, 'GiB'),\n (1 << 20, 'MiB'),\n (1 << 10, 'KiB'),\n (1, 'B')\n ]\n\n if n == 1:\n return '1 B'\n\n for factor, suffix in abbrevs:\n if n >= factor:\n break\n\n return '%.*f %s' % (precision, n / factor, suffix)\n\n\ndef gen_dict_strset(d):\n s = set()\n for k,v in d.items():\n item = str(k) + ':' + str(v)\n s.add(item)\n return s\n\ndef compare_dict_include(d,include={}):\n '''\n <= compare two dict object include or contained relationship\n return True : d totally contain the include with the same content\n\n>>> compare_dict_include({'a':1},{})\nTrue\n>>> compare_dict_include({'a':1},{'a':2})\nFalse\n>>> compare_dict_include({'a':1},{'a':1})\nTrue\n>>> compare_dict_include({'a':1,'b':2},{'a':1})\nTrue\n>>> compare_dict_include({'a':1,'b':2},{'b':2})\nTrue\n\n\n '''\n if include == {}:### always True\n return True\n\n ds_set = gen_dict_strset(d)\n includes_set = gen_dict_strset(include)\n if includes_set.issubset(ds_set):\n return True\n else:\n return False\n\ndef check_dict_has(d,has=[]):\n '''\n does the dict object has some keys\n\n>>> check_dict_has({'a':1,'b':2},[])\nTrue\n>>> check_dict_has({'a':1,'b':2},['a'])\nTrue\n>>> check_dict_has({'a':1,'b':2},['a','c'])\nFalse\n>>> check_dict_has({'a':1,'b':2},['a','b'])\nTrue\n\n '''\n if has == []:###always True\n return True\n\n if set(has).issubset(set(d.keys())):\n return True\n else:\n return False\n\n\n\ndef is_language_en(string):\n '''a very basic function for get the input string's unicode range.\n right now i just want get a unicode range like set(\\uaaaa,.....) for check\n does the string is english or zhongwen, because the english is a very small\n unicode language, and if not we think the string language is zhongwen.\n\n>>> is_language_en('乙醇')\nFalse\n>>> is_language_en('hello world')\nTrue\n\n '''\n BasicLatinSet = set()\n for i in range(0x00,0x7f):\n BasicLatinSet.add(i)\n\n charset = set()\n for s in string:\n charset.add(ord(s))\n\n return charset.issubset(BasicLatinSet)\n\n\n\ndef del_list(lst,indexs):\n '''\n del list base a index list\n\n>>> del_list([0,1,2,3,4,5],[2,3])\n[0, 1, 4, 5]\n>>> lst = list(range(6))\n>>> lst\n[0, 1, 2, 3, 4, 5]\n>>> del_list(lst,[2,3])\n[0, 1, 4, 5]\n>>> lst\n[0, 1, 4, 5]\n>>> del_list(lst,[0,2])\n[1, 5]\n>>> lst\n[1, 5]\n\n '''\n count = 0\n for index in sorted(indexs):\n index = index - count\n del lst[index]\n count += 1\n return lst\n\ndef group_list(lst,n=1):\n '''\n group a list, in some case, it is maybe useful.\n\n>>> list(group_list(list(range(10)),0))\nTraceback (most recent call last):\nAssertionError\n>>> list(group_list(list(range(10)),1))\n[[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]\n>>> list(group_list(list(range(10)),2))\n[[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]\n>>> list(group_list(list(range(10)),3))\n[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]\n>>> list(group_list(list(range(10)),4))\n[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9]]\n\n '''\n assert n > 0\n for i in range(0,len(lst),n):\n yield lst[i:i+n]\n\nimport chardet\ndef detect_encoding(bstring,confidence=0.9):\n '''\n detect the input bstring encoding\n the confidence default must >= 0.9 otherwise , will return None\n '''\n result = chardet.detect(bstring)\n if result['confidence'] >= confidence:\n return result['encoding']\n else:\n logging.warning('language detect confidence is smaller than {}'.format(confidence))\n return None\n\n\nfrom chardet.universaldetector import UniversalDetector\ndef detect_fileEncoding(infile,confidence=0.9):\n '''\n test file encoding\n '''\n detector = UniversalDetector()\n\n with open(infile,'rb') as f:\n for line in f.readlines():\n detector.feed(line)\n if detector.done:\n break\n detector.close()\n result = detector.result\n logging.info(result)\n\n if result['confidence'] > confidence:\n return result['encoding']\n else:\n logging.warning('language detect confidence is smaller than {}'.format(confidence))\n return None\n\n\ndef beep(a,b):\n '''make a sound , ref: http://stackoverflow.com/questions/16573051/python-sound-alarm-when-code-finishes\n you need install ``apt-get install sox``\n\n :param a: frenquency\n :param b: duration\n\n create a background thread,so this function does not block the main program\n '''\n if sys.platform == \"win32\":\n import winsound\n def _beep(a,b):\n winsound.Beep(a,b*1000)\n elif sys.platform == 'linux':\n def _beep(a,b):\n import os\n os.system('play --no-show-progress --null --channels 1 synth %s sine %f' % (b,a))\n from threading import Thread\n thread = Thread(target=_beep,args=(a,b))\n thread.daemon = True\n thread.start()\n\n\n\ndef randip():\n '''\n get a random ip like '77.80.42.249' , type str.\n ref: http://stackoverflow.com/questions/21014618/python-randomly-generated-ip-address-of-the-string\n '''\n import random\n import socket\n import struct\n return socket.inet_ntoa(struct.pack('>I', random.randint(1, 0xffffffff)))\n\n\n######### path\nimport re\ndef gen_filetree(startpath='.',filetype=\"\"):\n '''\n 利用os.walk 遍历某个目录,收集其内的文件,返回\n (文件路径列表, 本路径下的文件列表)\n 比如:\n (['shortly'], ['shortly.py'])\n(['shortly', 'templates'], ['shortly.py'])\n(['shortly', 'static'], ['shortly.py'])\n\n 第一个可选参数 startpath 默认值 '.'\n 第二个参数 filetype 正则表达式模板 默认值是\"\" 其作用是只选择某些文件\n 如果是空值,则所有的文件都将被选中。比如 \"html$|pdf$\" 将只选中 html和pdf文件。\n '''\n for root, dirs, files in os.walk(startpath):\n filelist = []\n for f in files:\n fileName,fileExt = os.path.splitext(f)\n if filetype:\n if re.search(filetype,fileExt):\n filelist.append(f)\n else:\n filelist = files\n if filelist:#空文件夹不加入\n dirlist = root.split(os.path.sep)\n dirlist = dirlist[1:]\n if dirlist:\n yield (dirlist, filelist)\n else:\n yield (['.'], filelist)\n\ndef gen_allfile(startpath='.',filetype=\"\"):\n '''\n 利用os.walk 遍历某个目录,收集其内的文件,返回符合条件的文件路径名\n 是一个生成器。\n 第一个可选参数 startpath 默认值 '.'\n 第二个参数 filetype 正则表达式模板 默认值是\"\" 其作用是只选择某些文件\n 如果是空值,则所有的文件都将被选中。比如 \"html$|pdf$\" 将只选中 html和pdf文件。\n '''\n\n for dirlist,filelist in gen_filetree(startpath = startpath,filetype=filetype):\n for f in filelist:\n filename = os.path.join(os.path.join(*dirlist),f)\n yield filename\n\nimport ast\ndef str2pyobj(val):\n '''\n str to python obj or not changed\n\n test is on test_gfun\n '''\n assert isinstance(val,str)\n try:\n val = ast.literal_eval(val)\n except Exception:\n pass\n return val\n\ndef str2num(val):\n '''\n str to int or float or raise a Exception. in some case maybe you just want\n to do some number type transform.\n '''\n assert isinstance(val,str)\n try:\n return int(val)\n except ValueError:\n try:\n return float(val)\n except Exception as e:\n raise e\n\n######\ndef flatten(inlst):\n '''\n 将 **多层** 列表或元组变成一维 **列表**\n>>> flatten((1,2,(3,4),((5,6))))\n[1, 2, 3, 4, 5, 6]\n>>> flatten([[1,2,3],[[4,5],[6]]])\n[1, 2, 3, 4, 5, 6]\n\n '''\n lst = []\n for x in inlst:\n if not isinstance(x, (list,tuple)):\n lst.append(x)\n else:\n lst += flatten(x)\n return lst\n\n__all__ = [\n 'beep',\n 'check_dict_has',\n 'compare_dict_include',\n 'del_list',\n 'detect_encoding',\n 'detect_fileEncoding',\n 'flatten',\n 'gen_allfile',\n 'gen_filetree',\n 'group_list',\n 'humanize_bytes',\n 'is_language_en',\n 'is_even',\n 'is_odd',\n 'mkdirs',\n 'normalized_path',\n 'randip',\n 'str2num',\n 'str2pyobj',\n ]\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n","sub_path":"lib/python3.4/site-packages/expython/gfun.py","file_name":"gfun.py","file_ext":"py","file_size_in_byte":11176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"323187094","text":"#!/usr/bin/env python2\n\n# matveev.a.s@yandex.ru\n# 2018 Anton Matveev\n\nimport numpy as np\nfrom functools import reduce\n\nclass Beamline():\n def __init__(self, geo, varElements, values=None):\n self.geo = geo\n self.varElements = varElements\n self.values = values\n\n def length(self):\n return sum(el.L for el in self.geo)\n\n def _set_values(self, values):\n if values is not None:\n for el, value in zip(self.varElements, values):\n el.set_var(value)\n\n if self.values is not None:\n for el, value in zip(self.varElements, self.values):\n el.set_var(value)\n\n def M(self, values=None):\n self._set_values(values)\n return reduce(np.dot, [el.M() for el in reversed(self.geo)])\n\n def twM(self, values=None):\n self._set_values(values)\n return reduce(np.dot, [el.twM() for el in reversed(self.geo)])\n\n def tw_transform(self, m1, m2):\n i1 = self.geo.index(m1)\n i2 = self.geo.index(m2)\n\n if i2 > i1:\n return np.dot( reduce( np.dot, [el.twM() for el in \\\n reversed(self.geo[i1:i2])] ), m1.tw)\n else:\n return np.dot( reduce( np.dot, [el.twM() for el in \\\n self.geo[i2:i1]]), m1.tw * np.array([1,-1,1,1,-1,1]))\n\n def beta_full(self, m):\n index = self.geo.index(m)\n if index == 0:\n tw = m.tw\n else:\n rev = np.array([1.,-1.,1.,1.,-1.,1.])\n tw = np.dot(reduce(np.dot, [el.twM() for el in self.geo[:index]]), \\\n m.tw * rev) * rev\n\n bx = np.zeros(1+len(self.geo))\n by = np.zeros(1+len(self.geo))\n s = np.zeros(1+len(self.geo))\n bx[0] = tw[0]\n by[0] = tw[3]\n s[0] = 0.\n\n for i, el in enumerate(self.geo):\n s[i+1] = s[i]+el.L\n tw = np.dot(el.twM(), tw) \n bx[i+1] = tw[0]\n by[i+1] = tw[3]\n \n\n return s, bx, by\n","sub_path":"optics/beamline.py","file_name":"beamline.py","file_ext":"py","file_size_in_byte":1980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"376902881","text":"import os\nimport pymongo\nif os.path.exists(\"env.py\"):\n import env\n\nMONGO_URI = os.environ.get(\"MONGO_URI\")\nDATABASE = \"myFirstDB\"\nCOLLECTION = \"celebrities\"\n\n\ndef mongo_connect(url):\n try:\n conn = pymongo.MongoClient(url)\n print(\"Mongo is connected\")\n return conn\n except pymongo.errors.ConnectionFailure as e:\n print(\"Could not connect MongoDB: %s\") % e\n\n\nconn = mongo_connect(MONGO_URI)\n\ncoll = conn[DATABASE][COLLECTION]\n\n# new_docs = [{\"first\": \"Mickey\", \"last\": \"Pay\"},\n# {\"first\": \"sheila\", \"last\": \"Murphy\"}]\n# coll.insert_many(new_docs)\n\n\n# documents = coll.find()\n\n# for doc in documents:\n# print(doc)\n#\n\n\n# coll.remove({\"first\": \"sheila\"})\n\n\n# coll.update_one({\"first\": \"blue\"},\n# {\"$set\": {\"dob\": \"20/09/1948\"}})","sub_path":"mongo.py","file_name":"mongo.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"399377674","text":"import math\nimport clr\nclr.AddReference(\"System.Windows.Forms\")\nfrom System.Windows.Forms import *\nclr.AddReference (\"System.Drawing\")\nfrom System.Drawing import Size\n \ndef getCos(sender,e):\n frm=sender.Tag\n a=frm.textBox1.Text\n frm.textBox2.Text='nepotrebno'\n b=math.cos(float(a))\n frm.textBox3.Text=str(b)\n\ndef Dodaj(frm):\n opt=ToolStripMenuItem(Text='Cosinus',Name='cos',Size=Size(104, 20))\n opt.Tag=frm\n opt.Click += getCos\n frm.addedOperationsToolStripMenuItem.DropDownItems.Add(opt)\n","sub_path":"IronPythonApplication2/Cosinus.py","file_name":"Cosinus.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"225792041","text":"\r\n\r\n#Exercise 16.5. Rewrite increment using time_to_int and int_to_time.\r\n#In some ways, converting from base 60 to base 10 and back is harder than just dealing with\r\n#times. Base conversion is more abstract; our intuition for dealing with time values is better.\r\n#But if we have the insight to treat times as base 60 numbers and make the investment of\r\n#writing the conversion functions (time_to_int and int_to_time), we get a program that\r\n#is shorter, easier to read and debug, and more reliable.\r\n\r\nimport copy\r\n\r\n\r\nclass Time(object):\r\n \"\"\" represents the time of day.\r\n attributes: hour, minute, second\"\"\"\r\n\r\ntime = Time()\r\ntime.hour = 11\r\ntime.minute = 59\r\ntime.second = 30\r\n\r\n\r\ndef time_to_int(time):\r\n minutes = time.hour * 60 + time.minute\r\n seconds = minutes * 60 + time.second\r\n return seconds\r\n\r\n\r\ndef int_to_time(seconds):\r\n new_time = Time()\r\n minutes, new_time.second = divmod(seconds, 60)\r\n time.hour, time.minute = divmod(minutes, 60)\r\n return time\r\n\r\n\r\ndef increment(time, seconds):\r\n new_time = copy.deepcopy(time)\r\n new_time = time_to_int(new_time) + seconds\r\n new_time = int_to_time(new_time)\r\n print (\"New time is: %.2d:%.2d:%.2d\"\r\n % (new_time.hour, new_time.minute, new_time.second))\r\n\r\nincrement(time, 300)\r\n\r\n\r\n","sub_path":"chapter-16/16.5.py","file_name":"16.5.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"372305867","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# from django.conf.urls.defaults import patterns, include, url\n#\n# # Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n#\n# urlpatterns = patterns('',\n# # Examples:\n# # url(r'^$', 'mysite.views.home', name='home'),\n# # url(r'^mysite/', include('mysite.foo.urls')),\n#\n# # Uncomment the admin/doc line below to enable admin documentation:\n# # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n#\n# # Uncomment the next line to enable the admin:\n# # url(r'^admin/', include(admin.site.urls)),\n# )\n\n# urlpatterns = patterns('',\n# # Examples:\n# # url(r'^$', 'mysite.views.home', name='home'),\n# # url(r'^mysite/', include('mysite.foo.urls')),\n#\n# # Uncomment the admin/doc line below to enable admin documentation:\n# # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n#\n# # Uncomment the next line to enable the admin:\n# # url(r'^admin/', include(admin.site.urls)),\n# )\n\n####################################################################################################\n# from django.conf.urls.defaults import *\nfrom django.conf.urls.defaults import url, include, patterns\n# from django.conf.urls import url\n# from django.conf.urls import include\n# from django.conf.urls import patterns\nfrom django.views.generic.simple import direct_to_template\nfrom django.views.generic import list_detail\n\nfrom django.views.generic import TemplateView\nfrom django.views.generic import ListView\n\nfrom mysite.my_views import hello\nfrom mysite.my_views import hi\nfrom mysite.views.books import AboutView\nfrom mysite.views.books import AuthorView\n\nfrom mysite.books.models import Author\n\n# urlpatterns should be a list of django.conf.urls.url() instances.\n# url(regex, view, kwargs=None, name=None, prefix='')\n# 关于 捕捉值 额外参数 的优先级:\n# 当冲突出现的时候,URLconf 的 额外参数 优先于 捕捉值。\n# 也就是说,如果URLconf捕捉到的一个命名组变量和一个额外URLconf参数包含的变量同名时,额外URLconf参数的值会被使用。\n\nurlpatterns = patterns(\n '',\n # 视图函数使用 函数对象方法 好处:\n # 更容易对视图函数进行包装(wrap)。\n # 更 Pythonic,就是说,更符合 Python 的传统,如把函数当成对象传递。\n\n ('^hello/$', hello),\n (r'^hi/$',hi),\n\n # 视图函数使用 字符串方法 好处:\n # 更紧凑,因为不需要你导入视图函数。\n # 如果你的视图函数存在于几个不同的 Python 模块的话,它可以使得 URLconf 更易读和管理。\n\n # Django 提供了另一种方法可以在 URLconf 中为某个特别的模式指定视图函数:\n # 传入一个包含模块名和函数名的字符串(带引号!),而不是函数对象本身:\n # 使用这个技术,就不必导入视图函数了;\n # Django 会在第一次需要它时根据字符串所描述的视图函数的名字和路径,导入合适的视图函数。\n (r'^db/$','mysite.books.views.db'),\n (r'^db_update/$','mysite.books.views.db_update'),\n (r'^db_filter/$','mysite.books.views.db_filter'),\n (r'^db_order/$','mysite.books.views.db_order'),\n (r'^db_filter_order/$','mysite.books.views.db_filter_order'),\n\n url(r'^test_save/$', 'mysite.books.views.test_save', name='test_save'),\n url(r'^test_read/$', 'mysite.books.views.test_read', name='test_read'),\n\n # [django.conf.urls.include()]\n # Whenever Django encounters include() (django.conf.urls.include()),\n # it chops off whatever part of the URL matched up to that point\n # and sends the remaining string to the included URLconf for further processing.\n # 一个被包含的 URLconf 接收任何来自 parent URLconf 的被捕获的参数\n # 被捕获的变量将传递给被包含的 URLconf,进而传递给那个 URLconf 中的 每一个 视图函数。\n # 你可以传递额外的URLconf选项到 include() , 就像你可以通过字典传递额外的URLconf选项到普通的视图。\n # 当你这样做的时候,被包含URLconf的每一行都会收到那些额外的参数。\n url(r'^api/', include('api.urls')),\n\n # 对于视图函数,\n # 如果用简单的正则捕获,将按顺序位置传参数;\n # 如果用命名的正则捕获,将按关键字传参数值;\n\n # 关键字参数调用\n # 需要指定参数的名字和传入的值。\n # 在解析URLconf时,请求方法(GET,POST)并不会被考虑。\n # 换而言之,对于相同的URL的所有请求方法将被导向到相同的函数中。\n # 根据请求方法来处理分支是视图函数的责任。\n url(r'^add$', 'mysite.my_views.add', name='add'),\n\n # 位置参数调用\n # 只需要传入参数,不需要明确指明哪个参数与哪个值对应,它们的对应关系隐含在参数的顺序中。\n url(r'^add_int/(\\d+)/(\\d+)/$', 'mysite.my_views.add_int', name='add_int'),\n url(r'^add_str/(\\d+)/(\\d+)/$', 'mysite.my_views.add_str', name='add_str'),\n\n # 使用命名组(正则表达式组)\n # (?Ppattern)\n #\n # 如果不带命名组,请求 /add_num/11/22/ 将会等同于这样的函数调用:\n # add_num(request, '11', '22')\n # 如果使用命名组,请求 /add_num/11/22/ 将会等同于这样的函数调用:\n # add_num(request, aaa='11', bbb='22')\n # 不论哪种方式,都和使用位置参数一样,\n # 要求: 视图函数必须要有跟命名组变量同名的形参 !!!\n # [1] 非命名组\n # url(r'^add_num/(\\d+)/(\\d+)/$', 'mysite.views.add_num', name='add_num'),\n # [2] 命名组\n url(r'^add_num/(?P\\d+)/(?P\\d+)/$', 'mysite.my_views.add_num', name='add_num'),\n\n\n # 使用通用视图(基于函数的通用视图)\n # (function-based generic view)\n url(r'^about/$', direct_to_template, {'template':'about.html'}),\n\n # 使用通用视图(基于类的通用视图)\n # (class-based generic view)\n # 在urls.py中使用类视图,需要调用它的 .as_view() 方法:\n url(r'^about_page/', TemplateView.as_view(template_name=\"about_page.html\")),\n\n # 使用通用视图(基于类的通用视图)\n # (class-based generic view)\n # 在urls.py中使用类视图,需要调用它的 .as_view() 方法:\n # AboutView 类继承 TemplateView 类,并覆盖了基类的 template_name 属性\n url(r'^about_view/', AboutView.as_view()),\n\n\n)\n\n\n# 使用通用视图呈现 Author 列表\n# [1] 基于函数的通用视图\n#\n# 通用视图就是Python函数。\n# 和其他的视图函数一样,通用视图也是接受一些参数并返回 HttpResponse 对象。\n#\n# 要使用通用视图酷酷的特性,\n# 只需要修改参数字典并传递给通用视图函数。\n#\n# All the cool features of generic views come from\n# changing the “info” dictionary passed to the generic view.\n#\n# django.views.generic.list_detail.object_lilst()\n# def object_list(request, queryset, paginate_by=None, page=None,\n# allow_empty=True, template_name=None, template_loader=loader,\n# extra_context=None, context_processors=None, template_object_name='object',\n# mimetype=None):\n#\n# queryset 参数,告诉视图要显示对象的集合;\n# template_name 参数,告诉视图要使用的模板;\nauthor_info = {\n 'queryset': Author.objects.all(),\n 'template_name': 'author_list_page.html'\n}\nurlpatterns += patterns(\n '',\n url(r'^author/$', list_detail.object_list, author_info),\n)\n\n# 使用通用视图呈现 Author 列表\n# [2] 基于类的通用视图\n#\n# URLConf 的逻辑:\n# “给一个可调用对象传入 HttpRequest ,并期待其返回一个 HttpResponse”\n# 所以对于类视图,必须设计一个可调用的接口。这就是类视图的 as_view() 方法。\n#\n# as_view() 方法:\n# 接受 request,并实例化类视图,接着调用实例的 dispatch() 方法。\n#\n# dispatch() 方法:\n# 依据 request 的请求类型再去调用实例的对应同名方法,并把 request 传过去,\n# 如果没有对应的方法,就引发一个 HttpResponseNotAllowed 异常。\n#\n# django 提供了一系列现成的类视图,他们都继承自一个 View 基类(django.views.generic.base.View)。\n# 在这个基类里实现了:\n# 与 URLs 的接口(as_view)\n# 请求方法匹配(dispatch)\n# 和一些其他的基本功能。\n# (比如 RedirectView 实现了一个简单的 HTTP 重定向,TemplateView 给 View 添加了一个渲染模板的功能。)\n\nurlpatterns += patterns(\n '',\n # model = Author\n # 等价于\n # queryset = Author.objects.all()\n # 但是通过使用 queryset 来定义一个过滤的对象列表\n # 可以更加详细的指定哪些对象将会被显示的视图(view)中\n url(r'^author_view/$', ListView.as_view(model=Author,\n template_name='author_list_page.html')),\n url(r'^author_view_filter/$', ListView.as_view(queryset=Author.objects.filter(first_name__contains='A'),\n template_name='author_list_page.html')),\n\n # 利用位置参数实现动态过滤\n url(r'author_view_filter/(\\w+)/$', AuthorView.as_view()),\n)\n\n\n# 启用管理网站\n# ID: vagrant\n# PW: vagrant\nurlpatterns += patterns('',\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n url(r'^admin/', include(admin.site.urls)),\n)\n\n# APP: polls\nurlpatterns += patterns('',\n url(r'^polls/', include('polls.urls')),\n)\n\n\n\n# RSS Feed\nfrom rss.views import RssFeedView\nurlpatterns += patterns(\n '',\n # url(r'^rss/$', RssFeedView(), name='rss_view'),\n url(r'^rss/(?P\\d+)/$', RssFeedView(), name='rss_view_patametered'),\n)\n\n# myapp\n# books\nurlpatterns += patterns(\n '',\n url(r'^app/', include('myapp.urls', namespace='app')),\n url(r'^book/', include('books.urls', namespace='book')),\n)\n\n\n# test cookie session\nfrom mysite.views.test_cookie_session import CookieView, SessionView, CookieTestView\nurlpatterns += patterns(\n '',\n # url(r'^cookie/$', CookieTestView.as_view(), name='test_cookie'),\n url(r'^cookie/$', CookieView.as_view(), name='test_cookie'),\n url(r'^session/$', SessionView.as_view(), name='test_session'),\n)\n\n# mytest\nurlpatterns += patterns(\n '',\n url(r'^test/', include('mytest.urls', namespace='mytest')),\n)\n","sub_path":"urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":10388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"394086102","text":"import streamlit as st\nimport pandas as pd\nimport time\nfrom Data_app import Data\n\nclass Search(Data):\n\n def run_search():\n st.title('多品类合并查询')\n catelist=pd.read_csv('files/category__.csv')\n category = st.multiselect('品类名称:',catelist['category_name'])\n ci=catelist[catelist['category_name'].isin(category)]['category_id'].apply(lambda x:str(x)) \n\n st.markdown(f'#### 已选中 **{category}** , 品类ID: **{ci}**')\n\n data = None\n while data is None:\n data_load_state=st.text('正在加载数据')\n data=Search.rank_load_data(ci)\n st.write(data)\n\n ci=catelist[catelist['category_name'].isin(category)]['category_id'].values \n newdate=st.multiselect('日期',data[(data['category_id'].isin(ci))].date.unique()) \n asin=st.multiselect('ASIN',data[data['category_id'].isin(ci)&(data['date'].isin(newdate))].asin.unique())\n newtable=data[(data['category_id'].isin(ci))&(data['asin'].isin(asin))&(data['date'].isin(newdate))]\n st.write(newtable[['category_id','category_name','asin','ranking','date']])\n\n data_load_state.success('✔️ 数据加载完成')\n time.sleep(1)\n data_load_state.text('') \n \nif __name__=='__main__':\n Search.run_search()\n","sub_path":"Streamlit/search_app.py","file_name":"search_app.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"27036596","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('/', views.room, name='room'),\n path('server/list/', views.ServerListView.as_view(), name='list_server'),\n path('server/detail//', views.ServerDetailView.as_view(), name='detail_server')\n]\n","sub_path":"api-server/src/gci/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"574062916","text":"\"\"\"\nThis is a ported version of a MATLAB example from the signal processing\ntoolbox that showed some difference at one time between Matplotlib's and\nMATLAB's scaling of the PSD.\npsd 方法分为以下几类:\n1.非参数类\n 基于傅里叶的周期图法、Welch估计(未实现,参见pylab.psd)、multigapering pmtm\n 非基于傅里叶的最小方差pminvar, 特征值 pmusic,最大熵MEM\n 2. 自回归估计,来自于自回归AR参数\n Yule-Walker pyule 自相关序列\n Burg pburg 反射系数\n pcovar 自相关或协方差\n pmodcovar 修改的协方差\n 此外还有parma pma\n url = https://pyspectrum.readthedocs.io/en/latest/spectral_analysis.html\n\"\"\"\nimport matplotlib\nmatplotlib.use('Qt5Agg')\nimport numpy as np\nfrom Tools.Class_Figure import Psd\n\ndata = np.load('data/Station.npz')\n# data = scio.loadmat('data/ua.mat')\nuar = data['u_tar'].squeeze()\nvar = data['v_tar'].squeeze()\nuvar = np.sqrt(uar ** 2 + var ** 2)\n\nuoc = data['u_toc'].squeeze()\nvoc = data['v_toc'].squeeze()\nuvoc = np.sqrt(uoc ** 2 + voc ** 2)\n\nPsd.psds(uvar, uvoc, 'uvar', 'uvoc', alpha=1, lat=57,\n show=0, save=1, Fs=288,NFFT=4096 * 2, dpi=300)\nPsd.fig_psd(uvar, uvoc, 'uvar','uvoc',Fs=288,save=1,NFFT=4096*2)\n# 将uva的值进行小时平均,也就是每12个数平均一次\nFs=24\nuvar.shape = [12, -1]\nmuvar = np.mean(uvar, axis=0)\nuvoc.shape = [12, -1]\nmuvoc = np.mean(uvoc, axis=0)\n\n# Psd.fig_psd(muvar, muvoc, 'uvar','uvoc',Fs=Fs,save=1,NFFT=4096*2)\n# Psd.fig_psd(muvar, muvoc, 'uvar','uvoc',method='pma',save=1,NFFT=4096*2)\n\n# Psd.fig_psd(uvar, uvoc, 'uvar','uvoc',Fs=288,save=1,NFFT=4096*2)\n# 对比不同的psd方法\n","sub_path":"Station_psd.py","file_name":"Station_psd.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"178287674","text":"import pygame as pg\nimport gameFunc\n\n\nclass Item(pg.sprite.Sprite):\n def __init__(self, jpg, xxx, yyy, screen_rect):\n pg.sprite.Sprite.__init__(self)\n self.screen_rect = screen_rect\n self.image = gameFunc.load_image(jpg, True).convert()\n self.image.set_colorkey((255, 0, 255))\n self.transformed_image = pg.transform.rotate(self.image, 0)\n self.rect = self.image.get_rect(center=(xxx, yyy))\n self.name = jpg\n","sub_path":"ExamTime - Game/Item.py","file_name":"Item.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"561409677","text":"from django.contrib import admin\nfrom django.urls import path, include\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nfrom drf_spectacular.views import (\n SpectacularAPIView, \n SpectacularRedocView, \n SpectacularSwaggerView\n)\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('api/schema/', SpectacularAPIView.as_view(), name='schema'),\n path('api/schema/swagger-ui/', SpectacularSwaggerView.as_view(url_name='schema'), name='swagger-ui'),\n path('api/schema/redoc/', SpectacularRedocView.as_view(url_name='schema'), name='redoc'),\n path('accounts/', include('accounts.urls')),\n path('api/v1/', include('shop.urls')),\n]\n\nif settings.DEBUG:\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n\n\n\n","sub_path":"ecommerce_dns/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"360910545","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Date : 2017-12-09 10:02:51\n# @Author : Lebhoryi@gmail.com\n# @Link1 : http://blog.csdn.net/xuan_zizizi/article/details/77815986\n# @Link2 : https://morvanzhou.github.io/tutorials/machine-learning/tensorflow/3-1-add-layer/\n# @Version : tensorflow添加函数\n\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef add_layer(inputs,in_size,out_size,activation_function = None):\n# 定义一个添加层,输入值,输入尺寸,输出尺寸,以及激励函数,此处None默认为线性的激励函数\n\tWeights = tf.Variable(tf.random_normal([in_size,out_size]))\n\t# 定义权值矩阵,in_size行,out_size列,随机初始权值\n\tbiases = tf.Variable(tf.zeros([1, out_size]) + 0.1)\n\t# 定义一个列表,一行,out_size列,值全部为0.1\n\tWx_plus_b = tf.add(tf.matmul(inputs,Weights),biases)\n\t# inputs*Weights + biases,预测值,未激活\n\tif activation_function is None:\n\t\toutputs = Wx_plus_b\n\t\t# 结果为线性输出,激活结果\n\telse:\n\t\toutputs = activation_function(Wx_plus_b)\n\t\t# 激励函数处理\n\treturn outputs\n\n# 定义数据集\nx_data = np.linspace(-1,1,300)[:,np.newaxis]\nnoise = np.random.normal(0,0.05,x_data.shape) # 噪声均值为0,方差为0.05,与x_data格式相同\ny_data = np.square(x_data) - 0.5 + noise\n\nxs = tf.placeholder(tf.float32,[None,1])\nys = tf.placeholder(tf.float32,[None,1])\n\n# add hidden layer\nl1 = add_layer(xs,1,10,activation_function=tf.nn.relu)\n# 隐含层输入层input(1个神经元):输入1个神经元,隐藏层10个神经元\n\n# add output layer\nprediction = add_layer(l1,10,1,activation_function=None)\n# 输出层也是1个神经元:隐藏层10个神经元,输出1个神经元\n\nloss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),\n\t\t\t\t\treduction_indices=[1]))\n# tf.reduce_mean(input_tensor, axis=None, keep_dims=False, name=None, reduction_indices=None)\n# 先求误差平方和的和求平均,reduce_sum表示对矩阵求和,reduction_indices=[1]方向\n\noptimizer = tf.train.GradientDescentOptimizer(0.1)\ntrain_step = optimizer.minimize(loss)\ninit = tf.initialize_all_variables()\nsess = tf.Session()\nsess.run(init)\n\n# 可视化结果\nfig = plt.figure() # 生成图片框\nax = fig.add_subplot(1,1,1)\nax.scatter(x_data,y_data)\nplt.ion()\nplt.show()\n\nfor i in range(1000):\n\t# trianing\n\tsess.run(train_step,feed_dict={xs:x_data,ys:y_data})\n\tif i%50 == 0:\n\t\t# print(sess.run(loss,feed_dict={xs:x_data,ys:y_data}))\n\t\ttry:\n\t\t\tax.lines.remove(lines[0])\n\t\texcept Exception:\n\t\t\tpass\n\t\tprediction_value = sess.run(prediction,feed_dict = {xs:x_data})\n\t\t# 画出预测\n\t\tlines = ax.plot(x_data,prediction_value,'r-',lw=5)\n\t\tplt.pause(0.1)\n\n","sub_path":"TensorFlow_learn/tensorflow_莫烦/add_layer.py","file_name":"add_layer.py","file_ext":"py","file_size_in_byte":2699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"282106482","text":"import sys, pdb, csv\nimport pylab as pl\nfrom os import listdir, mkdir\nfrom os.path import isfile, join, isdir\nimport itertools\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nimport matplotlib\nmatplotlib.style.use('ggplot')\n\n# PATH to the filtered CSV\nPATH = sys.argv[1]\nOP_PATH = sys.argv[2]\n\nreader = csv.reader(open(PATH))\n\n# Skip the first 3 lines [ Find a better way to do this ]\nreader.next()\nreader.next()\nreader.next()\n\n\nYEARS = map(str, range(2006, 2017))\nREGIONS = map(str, range(1, 14))\nDATA = { }\n\n# Initializing DICT\nfor r in REGIONS:\n DATA[r] = { }\n for y in YEARS:\n DATA[r][y] = [ ]\n\nCOLUMNS = ['AOD_Mean_Dust','AOD_Mean_Smoke','AOD_Mean_Polluted_Dust','AOD_Mean']\nPCOLUMNS = ['AOD_Mean_Dust','AOD_Mean_Smoke','AOD_Mean_Polluted_Dust','AOD_Mean']\nOPERATIONS = ['min', 'max', 'sum', 'mean', 'median']\n\nFIELDS = map(lambda c: c[0] + '-' + c[1],itertools.product(COLUMNS, OPERATIONS))\n\nfor row in reader:\n DATA[row[0]][row[1]] = {}\n\n for f in range(len(FIELDS)):\n DATA[row[0]][row[1]][FIELDS[f]] = row[f+2]\n\ndef safeMakeDir(path):\n if not isdir(path):\n mkdir(path)\n\ndef plotGraph(region, operation):\n getVals = lambda column: map(lambda y: DATA[region][y][column + \"-\" + operation], DATA[region])\n data = map(lambda c: getVals(c), PCOLUMNS)\n\n plt.figure()\n df2 = pd.DataFrame(zip(*data), columns=PCOLUMNS)\n df2 = df2.astype(float)\n df2.plot.bar(stacked=True)\n plt.savefig(join(OP_PATH, region, operation + \".png\"), dpi=200)\n plt.close('all')\n\n\nfor r in REGIONS:\n safeMakeDir(join(OP_PATH, r))\n\n for o in OPERATIONS:\n plotGraph(r, o)\n\n\n\n\n\n\n\n\n","sub_path":"analytics/caliop2_plot.py","file_name":"caliop2_plot.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"96899102","text":"from flask import Flask, render_template, request\nimport soundcloud\n\napp = Flask(__name__)\napp.config.from_envvar('APP_SETTINGS')\n\n@app.route('/')\ndef index():\n client = _new_client()\n authorize_url = client.authorize_url()\n return render_template('index.html', url=authorize_url)\n\n@app.route('/callback')\ndef callback():\n client = _new_client()\n code = request.args.get('code', '')\n access_token = client.exchange_token(code)\n return render_template('callback.html', token=access_token)\n\ndef _new_client():\n return soundcloud.Client(\n client_id=app.config['SOUNDCLOUD_CLIENT_ID'],\n client_secret=app.config['SOUNDCLOUD_CLIENT_SECRET'],\n redirect_uri=app.config['SOUNDCLOUD_REDIRECT_URI'],\n )\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"152737368","text":"import random\nimport copy\nfrom collections import deque, namedtuple\n\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nfrom models import Actor, Critic\n\n\n\nseed = 3298\nrandom.seed(seed)\ntorch.manual_seed(seed)\n\nDEVICE = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\nExperience = namedtuple('Experience', 'state action reward next_state done')\n\nclass Replay:\n def __init__(self, action_size, buffer_size, batch_size):\n self.action_size = action_size\n self.buffer = deque(maxlen=buffer_size)\n self.batch_size = batch_size\n\n def add(self, state, action, reward, next_state, done):\n experience = Experience(state, action, reward, next_state, done)\n self.buffer.append(experience)\n\n def sample(self):\n experiences = random.sample(self.buffer, k=self.batch_size)\n\n states = torch.from_numpy(np.vstack([e.state for e in experiences])).float().to(DEVICE)\n actions = torch.from_numpy(np.vstack([e.action for e in experiences])).float().to(DEVICE)\n rewards = torch.from_numpy(np.vstack([e.reward for e in experiences])).float().to(DEVICE)\n next_states = torch.from_numpy(np.vstack([e.next_state for e in experiences])).float().to(DEVICE)\n dones = torch.from_numpy(np.vstack([e.done for e in experiences]).astype(np.uint8)).float().to(DEVICE)\n\n return states, actions, rewards, next_states, dones\n\n def __len__(self):\n return len(self.buffer)\n\n\nclass Agent:\n def __init__(self, state_size, action_size):\n\n self.discount = 0.99\n self.target_mix = 1e-3\n\n self.online_actor = Actor(state_size, action_size, fc1_units=256, fc2_units=256).to(DEVICE)\n self.target_actor = Actor(state_size, action_size, fc1_units=256, fc2_units=256).to(DEVICE)\n self.actor_opt = optim.Adam(self.online_actor.parameters(), lr=3e-4)\n\n self.online_critic = Critic(state_size, action_size, fc1_units=256, fc2_units=256).to(DEVICE)\n self.target_critic = Critic(state_size, action_size, fc1_units=256, fc2_units=256).to(DEVICE)\n self.critic_opt = optim.Adam(self.online_critic.parameters(), lr=3e-4)\n\n self.noise = OrnsteinUhlenbeck(action_size, mu=0., theta=0.15, sigma=0.05)\n self.replay = Replay(action_size, buffer_size=int(1e6), batch_size=128)\n\n def step(self, state, action, reward, next_state, done):\n self.replay.add(state, action, reward, next_state, done)\n\n if len(self.replay) > self.replay.batch_size:\n self.learn()\n\n def act(self, state, add_noise=True):\n state = torch.from_numpy(state).float().to(DEVICE)\n\n self.online_actor.eval()\n\n with torch.no_grad():\n action = self.online_actor(state).cpu().data.numpy()\n\n self.online_actor.train()\n\n if add_noise:\n action += self.noise.sample()\n\n return np.clip(action, -1, 1)\n\n def reset(self):\n self.noise.reset()\n\n def learn(self):\n states, actions, rewards, next_states, dones = self.replay.sample()\n\n # Update online critic model\n # Predict actions for the next states with the target actor model\n target_next_actions = self.target_actor(next_states)\n # Compute Q values for the next states and actions with the target critic model\n target_next_qs = self.target_critic(next_states, target_next_actions)\n # Compute target Q values for the current states using the Bellman equation\n target_qs = rewards + (self.discount * target_next_qs * (1 - dones))\n # Compute Q values for the current states and actions with the online critic model\n online_qs = self.online_critic(states, actions)\n # Compute and minimize the online critic loss\n critic_loss = F.mse_loss(online_qs, target_qs)\n self.critic_opt.zero_grad()\n critic_loss.backward()\n torch.nn.utils.clip_grad_norm_(self.online_critic.parameters(), 1)\n self.critic_opt.step()\n\n # Update online actor model\n # Predict actions for current states from the online actor model\n online_actions = self.online_actor(states)\n # Compute and minimize the online actor loss\n actor_loss = -self.online_critic(states, online_actions).mean()\n self.actor_opt.zero_grad()\n actor_loss.backward()\n self.actor_opt.step()\n\n # Update target critic and actor models\n self.soft_update(self.online_critic, self.target_critic)\n self.soft_update(self.online_actor, self.target_actor)\n\n def soft_update(self, online_model, target_model):\n for target_param, online_param in zip(target_model.parameters(), online_model.parameters()):\n target_param.data.copy_(self.target_mix * online_param.data + (1.0 - self.target_mix) * target_param.data)\n\n\nclass OrnsteinUhlenbeck:\n def __init__(self, size, mu, theta, sigma):\n self.state = None\n self.mu = mu * np.ones(size)\n self.theta = theta\n self.sigma = sigma\n self.reset()\n\n def reset(self):\n self.state = copy.copy(self.mu)\n\n def sample(self):\n x = self.state\n dx = self.theta * (self.mu - x) + self.sigma * np.array([random.random() for _ in range(len(x))])\n self.state = x + dx\n return self.state\n\n\n","sub_path":"agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":5340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"343162520","text":"\"\"\"\nRequirements:\nA virtualenv is highly recommended.\n\nIf you don't have the required imports installed it will error. \n`pip install` as needed. See text_analysis.py for more details.\n\nPossibly useful: https://spacy.io/usage/\nhttps://valiancesolutions.com/whitepapers/automated-tagging-of-articles-using-unsupervised-learning/\nhttps://pypi.org/project/topia.termextract/\n\nNote: this is for an example only. To meaningfully extract phrases you'd need a more complex set of chunker \nrules, and you'd have to better train it. See the NLTK docs for more details. \n\n\"\"\"\nimport operator\nimport PyPDF2\n\n\nimport nltk\nfrom nltk import FreqDist\nfrom nltk.corpus import stopwords\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.stem.porter import PorterStemmer\nfrom nltk.tokenize import word_tokenize\n\nimport matplotlib\n# In some cases you may run into some weirdness in installed \n# python versions, matplotlib and a \"not installed as a framework\" error.\n# If so, the command below resolves the backend.\n# Note that it MUST be run before any further imports.\nmatplotlib.use('TkAgg')\n# You may now continue importing\nimport matplotlib.pyplot as plt\n\n# make sure NLTK modules are loaded\n# If you've done this recently, these can be safely commented out.\n# nltk.download('punkt')\n# nltk.download('stopwords')\n# nltk.download('wordnet')\n# nltk.download('averaged_perceptron_tagger')\n\ngrammar = r\"\"\"\n NBAR:\n {*} # Nouns and Adjectives, terminated with Nouns\n \n NP:\n {}\n {} # Above, connected with in/of/etc...\n \"\"\"\nchunker = nltk.RegexpParser(grammar)\n\n\ndef extract_text(pd_file=None):\n \"\"\"\n Given a PDF or text file, extract the text from it.\n Be sure to set the `pd_file` and `pd_directory` variables as needed.\n \"\"\"\n if not pd_file:\n pd_file = '2892-10 AIRCRAFT ELECTRICIAN.pdf'\n pd_directory = 'pd_files/'\n pd_file_path = pd_directory + pd_file\n \n # determine the file type and read accordingly.\n try:\n suffix = pd_file_path.rsplit('.', 1)[1].lower()\n except IndexError:\n print(\"No suffix: We don't know what the file type is.\")\n return\n if suffix == 'pdf':\n # Open and read the file into pyPDF2\n pd_file = open(pd_file_path,'rb')\n pd = PyPDF2.PdfFileReader(pd_file)\n\n #Iterate through PDF pages and extract\n pd_text = ''\n for page in pd.pages:\n pd_text += page.extractText()\n elif suffix == \"txt\":\n pd_file = open(pd_file_path,'r')\n pd_text = pd_file.read()\n else:\n print(\"Unknown file type. Please use PDF or TXT files\")\n return\n return clean_text(pd_text)\n\n\ndef clean_text(text):\n \"\"\"\n Given a block of text, clean it to remove unwanted characters other cruft.\n This will:\n 1. Strip newlines - we don't care about them for word counts, \n 2. Cast to lowercase for consistency.\n 3. Replace / with a space, retaining the words on either side of the /\n 4. Replace \"smart\" quotes and apostrophes with dumb ones.\n \"\"\"\n text = text.replace('\\n', '').lower()\n text = text.replace('/', \" \")\n text = text.replace('’', \"'\")\n return text\n\n\ndef clean_tokens(tokens):\n \"\"\"\n Given a list of word tokens generated by `nltk.word_tokenize`, \n cleans out unwanted punctuation and stopwords.\n \"\"\"\n punctuation = ['(', ')', ';', ':', '[', ']', ',', '.', '#', '%', \"'s\", \"’\", '!', '``']\n stop_words = stopwords.words('english')\n tokens = [word for word in tokens if not word in stop_words and not word in punctuation]\n stemmer = PorterStemmer()\n stemmed_words = [stemmer.stem(word) for word in tokens]\n lemmatizer = WordNetLemmatizer()\n lem_words = [lemmatizer.lemmatize(word) for word in stemmed_words]\n # and now a second pass to pick up any verbs remaining\n keywords = [lemmatizer.lemmatize(word, pos='v') for word in lem_words]\n return keywords\n\n\n\ndef tag_sentences(pd_text):\n \"\"\"\n Returns tokenized words, broken down by sentence, \n and tagged by part of speech.\n See https://www.nltk.org/book/ch07.html\n \"\"\"\n tagged_sentences = []\n sentences = nltk.sent_tokenize(pd_text)\n # We need to tokenize, clean and tag parts of speech for the words in each sentence. \n # For clarity, we'll do it in a loop instead of a list comprehension\n # so it's easier to see each step.\n for sentence in sentences:\n token_list = nltk.word_tokenize(sentence)\n cleaned = clean_tokens(token_list)\n tagged = nltk.pos_tag(cleaned)\n tagged_sentences.append(tagged)\n return tagged_sentences\n\n\ndef tag_words(pd_text):\n \"\"\"\n Returns simple list of tokenized words, cleaned and tagged by part of speech.\n See https://www.nltk.org/book/ch07.html\n \"\"\"\n tokens = nltk.word_tokenize(pd_text)\n tokens = clean_tokens(tokens)\n return nltk.tag.pos_tag(tokens)\n\n\ndef extract_phrases(pd_text=None):\n if not pd_text:\n pd_text = extract_text()\n tagged_sentences = tag_sentences(pd_text)\n leaves = []\n \"\"\"Find NP (nounphrase) leaf nodes of the chunk tree.\"\"\"\n for sentence in tagged_sentences:\n tree = chunker.parse(sentence)\n for subtree in tree.subtrees(filter=lambda t: t.label() == 'NP'):\n leafwords = [ w for w,t in subtree.leaves() ]\n leaves.append(' '.join(leafwords))\n return leaves\n\n\ndef get_keyword_frequency():\n \"\"\"\n Given a block of text from a document, get the keywords.\n \"\"\"\n # extract and clean the keyword tokens with NLTK\n keywords = extract_phrases()\n freq = nltk.FreqDist(keywords)\n\n for k, v in freq.most_common(50):\n print(f'{k:<20} {v}')\n\n\nif __name__ == \"__main__\":\n # execute only if run as a script\n get_keyword_frequency()","sub_path":"examples/text_extraction.py","file_name":"text_extraction.py","file_ext":"py","file_size_in_byte":5798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"200378312","text":"class Solution(object):\n def __init__(self):\n self.buffer = [None] * 4\n self.offset = 0\n self.bufsize = 0\n def read(self, buf, n):\n readBytes, endOfFile = 0, False\n while not endOfFile and readBytes < n:\n if self.bufsize == 0:\n self.bufsize = read4(self.buffer)\n endOfFile = self.bufsize < 4\n bytes = min(n - readBytes, self.bufsize)\n for i in range(bytes):\n buf[readBytes + i] = self.buffer[self.offset + i]\n self.offset = (self.offset + bytes) % 4\n self.bufsize -= bytes\n readBytes += bytes\n return readBytes\n\n","sub_path":"Read_N_Characters_Given_Read4_II/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"19969140","text":"from django.urls import path\n\nfrom user.views import *\n\napp_name = 'user'\nurlpatterns = [\n path('', LoginView.as_view(), name='login'),\n path('logout/', LogoutView.as_view(), name='logout'),\n path('register/', RegisterView.as_view(), name='register')\n]\n","sub_path":"user/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"586224094","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jul 17 21:50:09 2020\n\n@author: Dr. Tang\n\"\"\"\n\nimport numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n\n\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets('./datasets', validation_size=0)\n\n\nimg = mnist.train.images[2]\nnoisy_img = img + 0.3 * np.random.randn(*img.shape)\nnoisy_img = np.clip(noisy_img, 0., 1.)\nplt.imshow(img.reshape((28, 28)), cmap='Greys_r')\n\nencoding_dim1 = 100\nepochs = 100\nbatch_size = 200\nnoise_factor = 0.5\n\nimage_size = mnist.train.images.shape[1]\ntf.reset_default_graph()\n\ninputs_ = tf.placeholder(tf.float32, (None, image_size), name='inputs')\ntargets_ = tf.placeholder(tf.float32, (None, image_size), name='targets')\n# Output of hidden layer\n\n#1.0\n#weight_input_to_hidden=tf.Variable(tf.random_normal([image_size,encoding_dim1]))\n#bias=tf.Variable(tf.zeros([encoding_dim1]))\n#encoded=tf.matmul(inputs_,weight_input_to_hidden)+bias\n#encoded=tf.nn.relu(encoded)\n#2.0\nencoded = tf.layers.dense(inputs_, encoding_dim1, activation=tf.nn.relu)\n\n# Output layer logits\nlogits = tf.layers.dense(encoded, image_size, activation=None)\n# Sigmoid output from\ndecoded = tf.nn.sigmoid(logits, name='output1')\n#loss=tf.losses.mean_squared_error(decoded,targets_)\nloss = tf.nn.sigmoid_cross_entropy_with_logits(labels=targets_, logits=logits)\ncost = tf.reduce_mean(loss)\nopt=tf.train.GradientDescentOptimizer(0.1).minimize(cost)\nsess = tf.Session()\n\n\nsess.run(tf.global_variables_initializer())\nfor e in range(epochs):\n \n for ii in range(mnist.train.num_examples//batch_size):\n batch = mnist.train.next_batch(batch_size)\n# noisy_imgs = batch[0]+noise_factor * np.random.randn(*batch[0].shape)\n# noisy_imgs = np.clip(noisy_imgs, 0., 1.)\n\n imgs=batch[0]\n feed = {inputs_: imgs, targets_: imgs}\n batch_cost, _ = sess.run([cost, opt], feed_dict=feed)\n\n print(\"Epoch: {}/{}...\".format(e+1, epochs),\n \"Training loss: {:.4f}\".format(batch_cost))\n \n \nfig, axes = plt.subplots(nrows=2, ncols=10, sharex=True, sharey=True, figsize=(20,4))\nin_imgs = mnist.test.images[:10]\nreconstructed, compressed = sess.run([decoded, encoded], feed_dict={inputs_: in_imgs})\n#noisy_imgs = in_imgs + noise_factor * np.random.randn(*in_imgs.shape)\n#noisy_imgs = np.clip(noisy_imgs, 0., 1.)\nfor images, row in zip([in_imgs, reconstructed], axes):\n \n\n for img, ax in zip(images, row):\n ax.imshow(img.reshape((28, 28)), cmap='Greys_r')\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n\n","sub_path":"笔记本电脑的东西/神经网络/16自编码器和图像恢复/autoencoder/autoencoder.py","file_name":"autoencoder.py","file_ext":"py","file_size_in_byte":2593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"293036016","text":"# coding: utf-8\n\nfrom enum import Enum\nfrom six import string_types, iteritems\nfrom bitmovin_api_sdk.common.poscheck import poscheck_model\nfrom bitmovin_api_sdk.models.bitmovin_resource import BitmovinResource\nimport pprint\nimport six\n\n\nclass KubernetesCluster(BitmovinResource):\n @poscheck_model\n def __init__(self,\n id_=None,\n name=None,\n description=None,\n created_at=None,\n modified_at=None,\n custom_data=None,\n online=None,\n connected=None,\n agent_deployment_download_url=None):\n # type: (string_types, string_types, string_types, datetime, datetime, dict, bool, bool, string_types) -> None\n super(KubernetesCluster, self).__init__(id_=id_, name=name, description=description, created_at=created_at, modified_at=modified_at, custom_data=custom_data)\n\n self._online = None\n self._connected = None\n self._agent_deployment_download_url = None\n self.discriminator = None\n\n if online is not None:\n self.online = online\n if connected is not None:\n self.connected = connected\n if agent_deployment_download_url is not None:\n self.agent_deployment_download_url = agent_deployment_download_url\n\n @property\n def openapi_types(self):\n types = {}\n\n if hasattr(super(KubernetesCluster, self), 'openapi_types'):\n types = getattr(super(KubernetesCluster, self), 'openapi_types')\n\n types.update({\n 'online': 'bool',\n 'connected': 'bool',\n 'agent_deployment_download_url': 'string_types'\n })\n\n return types\n\n @property\n def attribute_map(self):\n attributes = {}\n\n if hasattr(super(KubernetesCluster, self), 'attribute_map'):\n attributes = getattr(super(KubernetesCluster, self), 'attribute_map')\n\n attributes.update({\n 'online': 'online',\n 'connected': 'connected',\n 'agent_deployment_download_url': 'agentDeploymentDownloadUrl'\n })\n return attributes\n\n @property\n def online(self):\n # type: () -> bool\n \"\"\"Gets the online of this KubernetesCluster.\n\n Shows if the Bitmovin Agent is alive (required)\n\n :return: The online of this KubernetesCluster.\n :rtype: bool\n \"\"\"\n return self._online\n\n @online.setter\n def online(self, online):\n # type: (bool) -> None\n \"\"\"Sets the online of this KubernetesCluster.\n\n Shows if the Bitmovin Agent is alive (required)\n\n :param online: The online of this KubernetesCluster.\n :type: bool\n \"\"\"\n\n if online is not None:\n if not isinstance(online, bool):\n raise TypeError(\"Invalid type for `online`, type has to be `bool`\")\n\n self._online = online\n\n @property\n def connected(self):\n # type: () -> bool\n \"\"\"Gets the connected of this KubernetesCluster.\n\n Shows if the Kubernetes cluster is accessible by the Bitmovin Agent (required)\n\n :return: The connected of this KubernetesCluster.\n :rtype: bool\n \"\"\"\n return self._connected\n\n @connected.setter\n def connected(self, connected):\n # type: (bool) -> None\n \"\"\"Sets the connected of this KubernetesCluster.\n\n Shows if the Kubernetes cluster is accessible by the Bitmovin Agent (required)\n\n :param connected: The connected of this KubernetesCluster.\n :type: bool\n \"\"\"\n\n if connected is not None:\n if not isinstance(connected, bool):\n raise TypeError(\"Invalid type for `connected`, type has to be `bool`\")\n\n self._connected = connected\n\n @property\n def agent_deployment_download_url(self):\n # type: () -> string_types\n \"\"\"Gets the agent_deployment_download_url of this KubernetesCluster.\n\n\n :return: The agent_deployment_download_url of this KubernetesCluster.\n :rtype: string_types\n \"\"\"\n return self._agent_deployment_download_url\n\n @agent_deployment_download_url.setter\n def agent_deployment_download_url(self, agent_deployment_download_url):\n # type: (string_types) -> None\n \"\"\"Sets the agent_deployment_download_url of this KubernetesCluster.\n\n\n :param agent_deployment_download_url: The agent_deployment_download_url of this KubernetesCluster.\n :type: string_types\n \"\"\"\n\n if agent_deployment_download_url is not None:\n if not isinstance(agent_deployment_download_url, string_types):\n raise TypeError(\"Invalid type for `agent_deployment_download_url`, type has to be `string_types`\")\n\n self._agent_deployment_download_url = agent_deployment_download_url\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n if hasattr(super(KubernetesCluster, self), \"to_dict\"):\n result = super(KubernetesCluster, self).to_dict()\n for attr, _ in six.iteritems(self.openapi_types):\n value = getattr(self, attr)\n if value is None:\n continue\n if isinstance(value, list):\n if len(value) == 0:\n continue\n result[self.attribute_map.get(attr)] = [y.value if isinstance(y, Enum) else y for y in [x.to_dict() if hasattr(x, \"to_dict\") else x for x in value]]\n elif hasattr(value, \"to_dict\"):\n result[self.attribute_map.get(attr)] = value.to_dict()\n elif isinstance(value, Enum):\n result[self.attribute_map.get(attr)] = value.value\n elif isinstance(value, dict):\n result[self.attribute_map.get(attr)] = {k: (v.to_dict() if hasattr(v, \"to_dict\") else v) for (k, v) in value.items()}\n else:\n result[self.attribute_map.get(attr)] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, KubernetesCluster):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n","sub_path":"bitmovin_api_sdk/models/kubernetes_cluster.py","file_name":"kubernetes_cluster.py","file_ext":"py","file_size_in_byte":6553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"140703451","text":"from random import randint\nfrom task_3_1 import ISBN_Check_Digit\nfrom task_3_5 import Hash_Key\n \ndef Insert_Book(isbn):\n outfile = open('LIBRARY.txt', 'r+')\n\n address, jump = Hash_Key(isbn)\n jump_value = jump\n isbn = isbn.ljust(13, '#')\n\n location = (address-1)*13\n outfile.seek(location)\n if not outfile.read(1).isdigit():\n outfile.seek(location)\n outfile.write(isbn)\n else:\n outfile.seek(jump*13)\n while outfile.read(1).isdigit():\n jump += jump_value\n if jump > 349:\n jump = jump_value\n outfile.seek(jump*13)\n outfile.seek(jump*13)\n outfile.write(isbn)\n outfile.close()\n\n\ndef generate_ISBN(years):\n ISBNs = list()\n num_books = round(200 * (1.1**years))\n \n while len(ISBNs) <= num_books:\n\n #choose ISBN10 Or ISBN13\n option = randint(0, 1)\n if option == 0:\n isbn = ''\n for _ in range(9):\n isbn += str(randint(0, 9))\n\n elif option == 1:\n isbn = ''\n for _ in range(12):\n isbn += str(randint(0, 9))\n\n check_digit = ISBN_Check_Digit(isbn)\n isbn += str(check_digit)\n\n if isbn not in ISBNs:\n ISBNs.append(isbn)\n \n outfile = open('LIBRARY.txt','w')\n outfile.close()\n for isbn in ISBNs:\n Insert_Book(isbn)\n \n \ndef Lookup_Book(isbn):\n infile = open('LIBRARY.txt','r+')\n\n address, jump = Hash_Key(isbn)\n jump_value = jump\n isbn = isbn.ljust(13, '#')\n \n location = (address-1) * 13\n infile.seek(location)\n\n if outfile.read(13) == isbn:\n print('{0} found without collision at position {1}'.format(isbn, address))\n else: #collision\n limit = 349\n infile.seek(jump*13)\n while infile.read(1).isdigit():\n jump += jump_value\n if jump > limit:\n print('{0} not found'.format(isbn))\n return\n outfile.seek(jump*13)\n print('{0} found with collision at position {1}'.format(isbn, jump))\n \n infile.close()\n\ngenerate_ISBN(3)\n\n \n \n \n \n \n\n \n","sub_path":"Revision Papers/02 Dunman 2015 Prelim/task_3/task_3_6.py","file_name":"task_3_6.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"131710851","text":"##The number 3797 has an interesting property. Being prime itself, it is\n##possible to continuously remove digits from left to right, and remain\n##prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right\n##to left: 3797, 379, 37, and 3.\n##\n##Find the sum of the only eleven primes that are both truncatable from left\n##to right and right to left.\n##\n##NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.\n\n## prime code copied from p27.py\nfrom binary_search import *\nimport time\n\nstart = time.time()\n\nf = open(\"primes.txt\", 'r')\n\nprimes = []\nfor line in f:\n primes.append(int(line))\n\n\nprime_tree = make_binary_tree(primes)\n\ndef get_truncated(n):\n trunc_list = []\n num_str = str(n)\n for i in range(1, len(num_str)):\n trunc_list.append(int(num_str[i:]))\n trunc_list.append(int(num_str[:len(num_str)-i]))\n return trunc_list\n\nprimes.remove(2)\nprimes.remove(3)\nprimes.remove(5)\nprimes.remove(7)\n\ntotal = 0\nfor number in primes:\n state = True\n for n in get_truncated(number):\n if not binary_search(prime_tree, n):\n state = False\n break\n if state:\n total += number\n\nprint(total)\nfinish = time.time()\n\nprint(finish-start)\n\n \n","sub_path":"code/Python/old/Euler/p37.py","file_name":"p37.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"535622724","text":"\"\"\"\n Title: Project 1 (Disassembler)\n Authors: Henry Ruiz: h_r32@txstate.edu\n Alexander Gonzalez: a_g1593@txstate.edu\n Class: Computer Architecture\n Class #: CS 3339.\n Description: This program is used to decode files filled with binary code\n into ARMv8 proper assembly sim_instructionss, disassembler.\n\"\"\"\nimport sys\nimport os\n\n\"\"\"Masks\"\"\"\nspcialMask = 0x1FFFFF\nrnMask = 0x3E0\nrmMask = 0x1F0000\nrdMask = 0x1F\nimMask = 0x3FFc00\nshmtMask = 0xFC00 # ARM ShAMT\naddrMask = 0x1FF000\naddr2Mask = 0xFFFFE0\nimsftMask = 0x600000 # shift for IM format\nimdataMask = 0x1FFFE0 # data for IM type\n\n\"\"\"These variables are going to be used to store the bits from the input file\"\"\"\nopcode = [] # Storing decimal representation of an opcode\ninstrSpaced = [] # : ['0 01000 00000 00001 00000 00000 001010', '1 01000 00000 00001 00000 00000 001010',...]\narg1 = [] # : [0, 0, 0, 0, 0, 1, 1, 10, 10, 0, 3, 4, 152, 4, 10, 1, 0, 112, 0]\narg2 = [] # : [0, 1, 1, 0, 1, 0, 10, 3, 4, 5, 0, 5, 0, 5, 6, 1, 1, 0, 0]\narg3 = [] # : [0, 10, 264, 0, 264, 48, 2, 172, 216, 260, 8, 6, 0, 6, 172, -1, 264, 0, 0]\n\n\"\"\"Theses variable are going to be used inside the methods/functions to compare \"\"\"\nopcodeStr = [] # : ['Invalid sim_instructions', 'ADDI', 'SW', 'Invalid sim_instructions', 'LW', 'BLTZ', 'SLL',...]\narg1Str = [] # : ['', '\\tR1', '\\tR1', '', '\\tR1', '\\tR1', '\\tR10', '\\tR3', '\\tR4', .....]\narg2Str = [] # : ['', ', R0', ', 264', '', ', 264', ', #48', ', R1', ', 172', ', 216', ...]'\narg3Str = [] # : ['', ', #10', '(R0)', '', '(R0)', '', ', #2', '(R10)', '(R10)', '(R0)',...]\nmem = [] # : [-1, -2, -3, 1, 2, 3, 0, 0, 5, -5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]\nbinMem = [] # : ['11111111111111111111111111111111', '11111111111111111111111111111110', ...]\noffset = []\n\nPC = 96 # First address\ncounter = 0\n# -------------------------------------------------------------------------------------------------------------------- #\n# Start of Class #\n# Purpose of this class is to disassemble file filled with ARM (binary code) sim_instructionss #\n# -------------------------------------------------------------------------------------------------------------------- #\n\nclass Dissasembler:\n def __init__(self):\n return None\n\n def run(self):\n global opcodeStr\n global arg1\n global arg2\n global arg3\n global arg1Str\n global arg2Str\n global arg3Str\n global mem\n global binMem\n global opcode\n global PC\n\n\n def immBitTo32BitConverter(num, bitsize):\n #need to read in 12 or 16 or 26 bit offset then convert it too 32 big\n if bitsize == 19:\n negBitMask = 0x800\n extendMask = 0xFFFFF000\n neg = (num & negBitMask) >> 18\n\n if neg == 0:\n return num\n else:\n return (num ^ extendMask)\n\n elif bitsize == 26:\n negBitMask = 0x2000000\n extendMask = 0xFC00000\n neg = (num & negBitMask) >> 25\n\n if neg == 0:\n return num\n else:\n return (num ^ extendMask)\n\n def imm32BitUnsignedTo32BitSignedConverter(num):\n return num\n\n def immSignedToTwosConverter(num):\n return num\n\n def bin_to_str_R(s):\n spacedStr = s[0:11] + \" \" + s[11:16] + \" \" + s[16:22] + \" \" + s[22:27] + \" \" + s[27:32]\n return spacedStr\n\n def bin_to_str_B(s):\n spacedStr = s[0:6] + \" \" + s[6:32] + \" \"\n return spacedStr\n\n def bin_to_str_I(s):\n spacedStr = s[0:10] + \" \" + s[10:22] + \" \" + s[22:27] + \" \" + s[27:32] + \" \"\n return spacedStr\n\n def bin_to_str_D(s):\n spacedStr = s[0:11] + \" \" + s[11:20] + \" \" + s[20:22] + \" \" + s[22:27] + \" \" + s[27:32] + \" \"\n return spacedStr\n\n def bin_to_str_CB(s):\n spacedStr = s[0:8] + \" \" + s[8:27] + \" \" + s[27:32] + \" \"\n return spacedStr\n\n def bin_to_str_IM(s):\n spacedStr = s[0:9] + \" \" + s[9:11] + \" \" + s[11:27] + \" \" + s[27:32] + \" \"\n return spacedStr\n\n def bin_to_str_Break(s):\n spacedStr = s[0:8] + \" \" + s[8:11] + \" \" + s[11:16] + \" \" + s[16:21] + \" \" + s[21:26] + \" \" + s[26:32] + \" \"\n return spacedStr\n\n def bin_to_str_data(s):\n spacedStr = s[0:32] + \" \"\n return spacedStr\n\n def twosCompSigned(num):\n inint = int(\"{0:b}\".format(num))\n flip = ~inint\n flip += 1\n intFlipped = int(str(flip), 2)\n return abs(intFlipped)\n\n if __name__ == \"__main__\":\n\n \"\"\" Reading in system arguments from terminal\"\"\"\n for i in range(len(sys.argv)):\n if (sys.argv[i] == '-i' and i < (len(sys.argv) - 1)):\n inputFileName = sys.argv[i + 1]\n print (inputFileName)\n elif (sys.argv[i] == '-o' and i < (len(sys.argv) - 1)):\n outputFileName = sys.argv[i + 1]\n\n \"\"\" Opening file test3_bin.txt\"\"\"\n sim_instructionss = [line.rstrip() for line in open(inputFileName, 'rb')]\n numberOfsim_instructionss = int(len(sim_instructionss))\n\n \"\"\"Iterating through the file to be saved in their respected list\"\"\"\n for i in range(len(sim_instructionss)):\n opcode.append(int(sim_instructionss[i][0:11], 2)) # opcode 11 bits\n\n if opcode[i] == 1112:\n opcodeStr.append(\"ADD\")\n arg1.append((int(sim_instructionss[i], base=2) & rnMask) >> 5)\n arg2.append((int(sim_instructionss[i], base=2) & rmMask) >> 16)\n arg3.append((int(sim_instructionss[i], base=2) & rdMask) >> 0)\n arg1Str.append(\"R\" + str(arg3[i]))\n arg2Str.append(\", R\" + str(arg1[i]))\n arg3Str.append(\", R\" + str(arg2[i]))\n instrSpaced.append(bin_to_str_R(sim_instructionss[i]))\n\n elif opcode[i] == 1624:\n opcodeStr.append(\"SUB\")\n arg1.append((int(sim_instructionss[i], base=2) & rnMask) >> 5)\n arg2.append((int(sim_instructionss[i], base=2) & rmMask) >> 16)\n arg3.append((int(sim_instructionss[i], base=2) & rdMask) >> 0)\n arg1Str.append(\"R\" + str(arg3[i]))\n arg2Str.append(\", R\" + str(arg1[i]))\n arg3Str.append(\", R\" + str(arg2[i]))\n instrSpaced.append(bin_to_str_R(sim_instructionss[i]))\n\n elif opcode[i] == 1104:\n opcodeStr.append(\"AND\")\n arg1.append((int(sim_instructionss[i], base=2) & rnMask) >> 5)\n arg2.append((int(sim_instructionss[i], base=2) & rmMask) >> 16)\n arg3.append((int(sim_instructionss[i], base=2) & rdMask) >> 0)\n arg1Str.append(\"R\" + str(arg3[i]))\n arg2Str.append(\", R\" + str(arg1[i]))\n arg3Str.append(\", R\" + str(arg2[i]))\n instrSpaced.append(bin_to_str_R(sim_instructionss[i]))\n\n elif opcode[i] == 1360:\n opcodeStr.append(\"ORR\")\n arg1.append((int(sim_instructionss[i], base=2) & rnMask) >> 5)\n arg2.append((int(sim_instructionss[i], base=2) & rmMask) >> 16)\n arg3.append((int(sim_instructionss[i], base=2) & rdMask) >> 0)\n arg1Str.append(\"R\" + str(arg3[i]))\n arg2Str.append(\", R\" + str(arg1[i]))\n arg3Str.append(\", R\" + str(arg2[i]))\n instrSpaced.append(bin_to_str_R(sim_instructionss[i]))\n\n # B , CB & I USE SIGNED VALUE\n elif 160 <= opcode[i] <= 190:\n opcodeStr.append(\"B\")\n # need to change this to extender and then grab that binary and convert too decimal\n # arg1.append('{:032b}'.format(int(sim_instructionss[i][6:32], base=2 & shmtMask)))\n arg1.append(twosCompSigned(int(sim_instructionss[i][6:32], base=2 & spcialMask)))\n arg2.append(' ')\n arg3.append(' ')\n arg1Str.append('#' + str(arg1[i]))\n arg2Str.append(' ')\n arg3Str.append(' ')\n instrSpaced.append(bin_to_str_B(sim_instructionss[i]))\n\n elif 1160 <= opcode[i] <= 1161:\n opcodeStr.append(\"ADDI\")\n arg1.append((int(sim_instructionss[i], base=2) & rnMask) >> 5)\n arg2.append((int(sim_instructionss[i], base=2) & imMask) >> 10)\n arg3.append((int(sim_instructionss[i], base=2) & rdMask) >> 0)\n arg1Str.append(\"R\" + str(arg3[i]))\n arg2Str.append(\", R\" + str(arg1[i]))\n arg3Str.append(\", #\" + str(arg2[i]))\n instrSpaced.append(bin_to_str_I(sim_instructionss[i]))\n\n elif 1672 <= opcode[i] <= 1673:\n opcodeStr.append(\"SUBI\")\n arg1.append((int(sim_instructionss[i], base=2) & rnMask) >> 5)\n arg2.append((int(sim_instructionss[i], base=2) & imMask) >> 10)\n arg3.append((int(sim_instructionss[i], base=2) & rdMask) >> 0)\n arg1Str.append(\"R\" + str(arg3[i]))\n arg2Str.append(\", R\" + str(arg1[i]))\n arg3Str.append(\", #\" + str(arg2[i]))\n instrSpaced.append(bin_to_str_I(sim_instructionss[i]))\n\n elif opcode[i] == 1986:\n opcodeStr.append(\"LDUR\")\n arg1.append((int(sim_instructionss[i], base=2) & rnMask) >> 5)\n arg2.append((int(sim_instructionss[i], base=2) & imMask) >> 12)\n arg3.append((int(sim_instructionss[i], base=2) & rdMask) >> 0)\n arg1Str.append(\"R\" + str(arg3[i]))\n arg2Str.append(\", [R\" + str(arg1[i]))\n arg3Str.append(\", #\" + str(arg2[i]) + \"]\")\n instrSpaced.append(bin_to_str_D(sim_instructionss[i]))\n\n elif opcode[i] == 1984:\n opcodeStr.append(\"STUR\")\n arg1.append((int(sim_instructionss[i], base=2) & rnMask) >> 5)\n arg2.append((int(sim_instructionss[i], base=2) & imMask) >> 12)\n arg3.append((int(sim_instructionss[i], base=2) & rdMask) >> 0)\n arg1Str.append(\"R\" + str(arg3[i]))\n arg2Str.append(\", [R\" + str(arg1[i]))\n arg3Str.append(\", #\" + str(arg2[i]) + \"]\")\n instrSpaced.append(bin_to_str_D(sim_instructionss[i]))\n\n elif 1440 <= opcode[i] <= 1447:\n opcodeStr.append(\"CBZ\")\n arg1.append((int(sim_instructionss[i], base=2) & addr2Mask) >> 5)\n arg2.append((int(sim_instructionss[i], base=2) & rmMask) >> 16)\n arg3.append((int(sim_instructionss[i], base=2) & rdMask) >> 0)\n arg1Str.append(\"R\" + str(arg3[i]))\n arg2Str.append(\", #\" + str(immBitTo32BitConverter(arg1[i], 19)))\n arg3Str.append(\" \")\n instrSpaced.append(bin_to_str_CB(sim_instructionss[i]))\n\n elif 1448 <= opcode[i] <= 1455:\n opcodeStr.append(\"CBNZ\")\n arg1.append((int(sim_instructionss[i], base=2) & addr2Mask) >> 5)\n arg2.append((int(sim_instructionss[i], base=2) & rmMask) >> 16)\n arg3.append((int(sim_instructionss[i], base=2) & rdMask) >> 0)\n arg1Str.append(\"R\" + str(arg3[i]))\n arg2Str.append(\", #\" + str(immBitTo32BitConverter(arg1[i], 19)))\n arg3Str.append(\" \")\n instrSpaced.append(bin_to_str_CB(sim_instructionss[i]))\n\n elif 1684 <= opcode[i] <= 1687:\n opcodeStr.append(\"MOVZ\")\n arg1.append((int(sim_instructionss[i], base=2) & imdataMask) >> 5)\n arg2.append(((int(sim_instructionss[i], base=2) & imsftMask) >> 21) * 16)\n arg3.append((int(sim_instructionss[i], base=2) & rdMask) >> 0)\n arg1Str.append(\"R\" + str(arg3[i]))\n arg2Str.append(\", \" + str(arg1[i]))\n arg3Str.append(\", LSL \" + str(arg2[i]))\n instrSpaced.append(bin_to_str_IM(sim_instructionss[i]))\n\n elif 1940 <= opcode[i] <= 1943:\n opcodeStr.append(\"MOVK\")\n arg1.append((int(sim_instructionss[i], base=2) & imdataMask) >> 5)\n arg2.append(((int(sim_instructionss[i], base=2) & imsftMask) >> 21) * 16)\n arg3.append((int(sim_instructionss[i], base=2) & rdMask) >> 0)\n arg1Str.append(\"R\" + str(arg3[i]))\n arg2Str.append(\", \" + str(arg1[i]))\n arg3Str.append(\", LSL \" + str(arg2[i]))\n instrSpaced.append(bin_to_str_IM(sim_instructionss[i]))\n\n elif opcode[i] == 1690:\n opcodeStr.append(\"LSR\")\n arg1.append((int(sim_instructionss[i], base=2) & rnMask) >> 5)\n arg2.append((int(sim_instructionss[i], base=2) & imMask) >> 10)\n arg3.append((int(sim_instructionss[i], base=2) & rdMask) >> 6)\n arg1Str.append(\"R\" + str(arg3[i]))\n arg2Str.append(\", R\" + str(arg1[i]))\n arg3Str.append(\", #\" + str(arg2[i]))\n instrSpaced.append(bin_to_str_R(sim_instructionss[i]))\n\n elif opcode[i] == 1691:\n opcodeStr.append(\"LSL\")\n arg1.append((int(sim_instructionss[i], base=2) & rnMask) >> 5)\n arg2.append((int(sim_instructionss[i], base=2) & imMask) >> 19)\n arg3.append((int(sim_instructionss[i], base=2) & rdMask) >> 6)\n arg1Str.append(\"R\" + str(arg3[i]))\n arg2Str.append(\", R\" + str(arg1[i]))\n arg3Str.append(\", #\" + str(arg2[i]))\n instrSpaced.append(bin_to_str_R(sim_instructionss[i]))\n\n# AFTER BREAK IS PRINTED WE MUST START PROCESSING DATA\n elif opcode[i] == 2038:\n opcodeStr.append(\"BREAK\")\n arg1.append((int(sim_instructionss[i], base=2) & rnMask) >> 5)\n arg2.append((int(sim_instructionss[i], base=2) & rmMask) >> 16)\n arg3.append((int(sim_instructionss[i], base=2) & rdMask) >> 0)\n arg1Str.append(\" \")\n arg2Str.append(\" \")\n arg3Str.append(\" \")\n instrSpaced.append(bin_to_str_Break(sim_instructionss[i]))\n True\n\n elif opcode[i] == 2047:\n counter -= 1\n opcodeStr.append(counter)\n arg1.append((int(sim_instructionss[i], base=2) & rnMask) >> 32)\n arg2.append((int(sim_instructionss[i], base=2) & rmMask) >> 16)\n arg3.append((int(sim_instructionss[i], base=2) & rdMask) >> 0)\n arg1Str.append(\" \")\n arg2Str.append(\" \")\n arg3Str.append(\" \")\n instrSpaced.append(bin_to_str_data(sim_instructionss[i]))\n\n # for i in range(numberOfsim_instructionss, len(sim_instructionss)):\n # mem.append(imm32BitUnsignedTo32BitSignedConverter(int(sim_instructionss[i], base=2)))\n # binMem.append(sim_instructionss[i])\n\n \"\"\" Writing to file test13_out.txt\"\"\"\n with open(outputFileName, 'w') as of:\n for x in range(len(instrSpaced)):\n of.write(str(instrSpaced[x]))\n of.write(\"\\t\")\n of.write(str(PC + x * 4))\n of.write(\"\\t\")\n of.write(str(opcodeStr[x]))\n of.write(\"\\t\")\n of.write(str(arg1Str[x]))\n of.write(str(arg2Str[x]))\n of.write(str(arg3Str[x]))\n of.write(\"\\n\")\n\n # for i in range(len(data)):\n # of.write(binMem[i])\n # of.write(\"\\t\" + str(mem[(len(mem) - len(data)) + i]))\n # of.write(\"\\t\" +str(data[i]))\n # of.write(\"\\n\")\n\n\ndissasemble = Dissasembler()\ndissasemble.run()\n\n\n\n","sub_path":"Dissassembler/team13_project1.py","file_name":"team13_project1.py","file_ext":"py","file_size_in_byte":15456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"}