diff --git "a/1974.jsonl" "b/1974.jsonl" new file mode 100644--- /dev/null +++ "b/1974.jsonl" @@ -0,0 +1,738 @@ +{"seq_id":"525725450","text":"def square(a):\r\n print(f\"The square of {a} is {a*a}\")\r\n\r\nif True:\r\n q1=int(input(\"Q1. What is 2 added to 2: \"))\r\nif q1== 4:\r\n print(\"Correct answer\")\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"modules check.py","file_name":"modules check.py","file_ext":"py","file_size_in_byte":184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"33472362","text":"# -*- coding: utf-8 -*-\nfrom django.test import TestCase\n\nfrom mysqlapi.api.database import Connection\nfrom mysqlapi.api.models import DatabaseManager\n\n\nclass DatabaseTestCase(TestCase):\n\n @classmethod\n def setUpClass(cls):\n cls.conn = Connection(hostname=\"localhost\", username=\"root\")\n cls.conn.open()\n cls.cursor = cls.conn.cursor()\n\n @classmethod\n def tearDownClass(cls):\n cls.conn.close()\n\n def test_create_database_with_custom_hostname(self):\n db = DatabaseManager(\"newdatabase\", host=\"127.0.0.1\")\n db.create_database()\n self.cursor.execute(\"select SCHEMA_NAME from information_schema.SCHEMATA where SCHEMA_NAME = 'newdatabase'\")\n row = self.cursor.fetchone()\n self.assertEqual(\"newdatabase\", row[0])\n db.drop_database()\n\n def test_create(self):\n db = DatabaseManager(\"newdatabase\")\n db.create_database()\n self.cursor.execute(\"select SCHEMA_NAME from information_schema.SCHEMATA where SCHEMA_NAME = 'newdatabase'\")\n row = self.cursor.fetchone()\n self.assertEqual(\"newdatabase\", row[0])\n db.drop_database()\n\n def test_drop(self):\n db = DatabaseManager(\"otherdatabase\")\n db.create_database()\n db.drop_database()\n self.cursor.execute(\"select SCHEMA_NAME from information_schema.SCHEMATA where SCHEMA_NAME = 'otherdatabase'\")\n row = self.cursor.fetchone()\n self.assertFalse(row)\n\n def test_create_user(self):\n db = DatabaseManager(\"wolverine\")\n db.create_user(\"wolverine\", \"localhost\")\n self.cursor.execute(\"select User, Host FROM mysql.user WHERE User='wolverine' AND Host='localhost'\")\n row = self.cursor.fetchone()\n self.assertEqual(\"wolverine\", row[0])\n self.assertEqual(\"localhost\", row[1])\n db.drop_user(\"wolverine\", \"localhost\")\n\n def test_create_user_should_generate_an_username_when_username_length_is_greater_than_16(self):\n db = DatabaseManager(\"usernamegreaterthan16\")\n username, password = db.create_user(\"usernamegreaterthan16\", \"localhost\")\n self.cursor.execute(\"select User, Host FROM mysql.user WHERE User like 'usernamegrea%' AND Host='localhost'\")\n row = self.cursor.fetchone()\n self.assertEqual(\"usernamegrea\", row[0][:12])\n db = DatabaseManager(row[0])\n db.drop_user(username, \"localhost\")\n\n def test_drop_user(self):\n db = DatabaseManager(\"magneto\")\n db.create_user(\"magneto\", \"localhost\")\n db.drop_user(\"magneto\", \"localhost\")\n self.cursor.execute(\"select User, Host FROM mysql.user WHERE User='wolverine' AND Host='localhost'\")\n row = self.cursor.fetchone()\n self.assertFalse(row)\n\n def test_export(self):\n db = DatabaseManager(\"magneto\")\n db.create_database()\n db.create_user(\"magneto\", \"localhost\")\n self.cursor.execute(\"create table magneto.foo ( test varchar(255) );\")\n expected = \"\"\"/*!40101 SET @saved_cs_client = @@character_set_client */;\n/*!40101 SET character_set_client = utf8 */;\nCREATE TABLE `foo` (\n `test` varchar(255) DEFAULT NULL\n) ENGINE=MyISAM DEFAULT CHARSET=utf8;\n/*!40101 SET character_set_client = @saved_cs_client */;\n\"\"\"\n result = db.export()\n self.assertEqual(expected, result.replace(\"InnoDB\", \"MyISAM\"))\n db.drop_database()\n db.drop_user(\"magneto\", \"localhost\")\n\n def test_is_up_return_True_if_everything_is_ok_with_the_connection(self):\n db = DatabaseManager(\"wolverine\")\n self.assertTrue(db.is_up())\n\n def test_is_up_return_False_something_is_not_ok_with_the_connection(self):\n db = DatabaseManager(\"wolverine\", host=\"unknownhost.absolute.impossibru.moc\")\n self.assertFalse(db.is_up())\n","sub_path":"mysqlapi/api/tests/test_database_manager.py","file_name":"test_database_manager.py","file_ext":"py","file_size_in_byte":3770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"438422405","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jun 27 10:35:27 2017\r\n\r\n@author: 代码医生 qq群:40016981,公众号:xiangyuejiqiren\r\n@blog:http://blog.csdn.net/lijin6249\r\n\"\"\"\r\nimport tensorflow as tf\r\ntf.reset_default_graph()\r\nw1 = tf.get_variable('w1', shape=[2])\r\nw2 = tf.get_variable('w2', shape=[2])\r\n\r\nw3 = tf.get_variable('w3', shape=[2])\r\nw4 = tf.get_variable('w4', shape=[2])\r\n\r\ny1 = w1 + w2+ w3\r\ny2 = w3 + w4\r\n\r\na = w1+w2\r\na_stoped = tf.stop_gradient(a)\r\ny3= a_stoped+w3\r\n\r\ngradients = tf.gradients([y1, y2], [w1, w2, w3, w4], grad_ys=[tf.convert_to_tensor([1.,2.]),\r\n tf.convert_to_tensor([3.,4.])])\r\n \r\ngradients2 = tf.gradients(y3, [w1, w2, w3], grad_ys=tf.convert_to_tensor([1.,2.])) \r\nprint(gradients2) \r\n \r\ngradients3 = tf.gradients(y3, [ w3], grad_ys=tf.convert_to_tensor([1.,2.])) \r\n \r\nwith tf.Session() as sess:\r\n sess.run(tf.global_variables_initializer())\r\n print(sess.run(gradients))\r\n #print(sess.run(gradients2))#报错\r\n print(sess.run(gradients3))\r\n ","sub_path":"Tensorflow(原理、实践)/codes/8-16__gradients2.py","file_name":"8-16__gradients2.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"121289683","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Sep 6 23:03:53 2020\r\n\r\n@author: Speedy Gonzàlez\r\n\"\"\"\r\n\r\n\r\nimport numpy as np\r\nfrom scipy.integrate import odeint\r\nimport matplotlib.pylab as plt\r\nfrom sys import argv\r\nimport xml\r\nimport xml.etree.ElementTree as ET\r\nfrom numpy import zeros\r\nimport datetime as dt\r\n\r\nG = 6.67 * (10**(-11)) #nm^2/kg^2\r\nkm = 1000 #metros\r\nJ2 = 1.75553*(10**10)*1000**5\r\nJ3 = -2.61913*(10**11)*1000**6\r\nminutos = 60\r\nhora = minutos* 60\r\nomega = 2*np.pi/(24*3600) #rad/s\r\ntime=24*3600\r\nmasaTierra = 5.972 * 10 ** 24 \r\nradioAtmosfera = (6371+80)*km\r\nR = np.eye(3,dtype = int)\r\ndR_dt = np.eye(3,dtype = int)\r\ndR2_dt2 = np.eye(3,dtype = int)\r\n\r\n#omega = 2*sp.pi/86400\r\necMovimiento = np.zeros(3)\r\n\r\ndef utc2time(utc, ut1, EOF_datetime_format = \"%Y-%m-%dT%H:%M:%S.%f\"):\r\n\tt1 = dt.datetime.strptime(ut1,EOF_datetime_format)\r\n\tt2 = dt.datetime.strptime(utc,EOF_datetime_format)\r\n\treturn (t2 - t1).total_seconds()\r\n\r\ndef leer_eof(fname):\r\n\ttree = ET.parse(fname)\r\n\troot = tree.getroot()\r\n\r\n\tData_Block = root.find(\"Data_Block\")\t\t\r\n\tList_of_OSVs = Data_Block.find(\"List_of_OSVs\")\r\n\r\n\tcount = int(List_of_OSVs.attrib[\"count\"])\r\n\r\n\tt = zeros(count)\r\n\tx = zeros(count)\r\n\ty = zeros(count)\r\n\tz = zeros(count)\r\n\tvx = zeros(count)\r\n\tvy = zeros(count)\r\n\tvz = zeros(count)\r\n\r\n\tset_ut1 = False\r\n\tfor i, osv in enumerate(List_of_OSVs):\r\n\t\tUTC = osv.find(\"UTC\").text[4:]\r\n\t\t\r\n\t\tx[i] = osv.find(\"X\").text #conversion de string a double es implicita\r\n\t\ty[i] = osv.find(\"Y\").text\r\n\t\tz[i] = osv.find(\"Z\").text\r\n\t\tvx[i] = osv.find(\"VX\").text\r\n\t\tvy[i] = osv.find(\"VY\").text\r\n\t\tvz[i] = osv.find(\"VZ\").text\r\n\r\n\t\tif not set_ut1:\r\n\t\t\tut1 = UTC\r\n\t\t\tset_ut1 = True\r\n\r\n\t\tt[i] = utc2time(UTC, ut1)\r\n\r\n\treturn t, x, y, z, vx, vy, vz\r\n\r\n\r\n \r\ndef satelite(z,t):\r\n #parámetros\r\n zp = np.zeros(6)\r\n #sin = np.sin(omega*t)\r\n #cos = np.cos(omega*t)\r\n z1 = z[0:3]\r\n r2 = np.dot(z1,z1)\r\n r = np.sqrt(r2)\r\n J2 = 1.75553*(10**10)*1000**5\r\n J3 = -2.61913*(10**11)*1000**6\r\n u = z[0]#x\r\n v = z[1]#y\r\n w = z[2]#z\r\n \r\n \r\n Fx_J2 = J2*(u/r**7)*(6*w**2-3/2*(u**2+v**2))\r\n Fy_J2 = J2*(v/r**7)*(6*w**2-3/2*(u**2+v**2))\r\n Fz_J2 = J2*(w/r**7)*(3*w**2-9/2*(u**2+v**2))\r\n\r\n \r\n Fx_J3 = J3*u*w/r**9*(10*w**2-15/2*(u**2+v**2))\r\n Fy_J3 = J3*v*w/r**9*(10*w**2-15/2*(u**2+v**2))\r\n Fz_J3 = J3/r**9*(4*w**2*(w**2-3*(u**2+v**2))+3/2*(u**2+v**2)**2)\r\n\r\n \r\n\r\n R=np.array([[np.cos(omega*t),-np.sin(omega*t),0],[np.sin(omega*t),np.cos(omega*t), 0],[0.,0.,1]])\r\n dR_dt=np.array([[-np.sin(omega*t),-np.cos(omega*t),0],[np.cos(omega*t),-np.sin(omega*t), 0],[0.,0.,0.]])*omega\r\n dR2_dt2=np.array([[-np.cos(omega*t),np.sin(omega*t), 0],[-np.sin(omega*t),-np.cos(omega*t),0],[0.,0.,0]])*omega**2\r\n \r\n fg = (-G*masaTierra/r**2)*(R@(z1/r))\r\n zp[3:6]=R.T@(fg-(2*(dR_dt@z[3:6])+(dR2_dt2@z[0:3])))\r\n \r\n zp[0:3] = z[3:6] \r\n\r\n \r\n zp[3] = zp[3] + Fx_J2 + Fx_J3\r\n zp[4] = zp[4] + Fy_J2 + Fy_J3\r\n zp[5] = zp[5] + Fz_J2 + Fz_J3\r\n \r\n return zp\r\n\r\neof_out = argv[1]\r\n# SI NO FUNCIONA DESDE LA CONSOLA DESCOMENTAR LA FILA DE ABAJO Y COMENTAR LA DE ARRIBA, GRACIAS!\r\n#eof_out = \"S1B_OPER_AUX_POEORB_OPOD_20200811T110756_V20200721T225942_20200723T005942.EOF\"\r\n\r\npred = eof_out.replace('.EOF','.PRED')\r\nt, x, y, z, vx, vy, vz = leer_eof(eof_out) \r\nz0 = np.array([x[0],y[0],z[0],vx[0],vy[0],vz[0]])\r\nzf= np.array([x[-1],y[-1],z[-1],vx[-1],vy[-1],vz[-1]])\r\n\r\nsol = odeint(satelite,z0,t)\r\nx_sol = sol[:,0];y_sol = sol[:,1];z_sol = sol[:,2]\r\nvx_sol = sol[:,3]; vy_sol = sol[:,4]; vz_sol = sol[:,5]\r\n\r\nwith open(eof_out,'w') as fout:\r\n fout.write('\\n'\r\n'\\n'\r\n' \\n'\r\n' \\n'\r\n' S1A_OPER_AUX_POEORB_OPOD_20200816T120754_V20200726T225942_20200728T005942\\n'\r\n' Precise Orbit Ephemerides (POE) Orbit File\\n'\r\n' \\n'\r\n' Sentinel-1A\\n'\r\n' OPER\\n'\r\n' AUX_POEORB\\n'\r\n' \\n'\r\n' UTC=2020-07-26T22:59:42\\n'\r\n' UTC=2020-07-28T00:59:42\\n'\r\n' \\n'\r\n' 0001\\n'\r\n' \\n'\r\n' OPOD\\n'\r\n' OPOD\\n'\r\n' 0.0\\n'\r\n' UTC=2020-08-16T12:07:54\\n'\r\n' \\n'\r\n' \\n'\r\n' \\n'\r\n' EARTH_FIXED\\n'\r\n' UTC\\n'\r\n' \\n'\r\n' \\n'\r\n'\\n'\r\n' \\n')\r\n Nt=len(t) \r\n for i in range(Nt):\r\n Dia1 = dt.datetime(2020,7,26,23,00,29,000000)\r\n Dia2 = dt.datetime(2020,7,26,22,59,52,000000)\r\n Dia3 = dt.datetime(2020,7,26,22,59,51,787522)\r\n dias1 = (Dia1 + dt.timedelta(seconds=t[i])).strftime('%Y-%m-%dT%H:%M:%S.%f')\r\n dias2 = (Dia2 + dt.timedelta(seconds=t[i])).strftime('%Y-%m-%dT%H:%M:%S.%f')\r\n dias3 = (Dia3 + dt.timedelta(seconds=t[i])).strftime('%Y-%m-%dT%H:%M:%S.%f')\r\n fout.write(' \\n'\r\nf' TAI={dias1}\\n'\r\nf' UTC={dias2}\\n'\r\nf' UT1={dias3}\\n'\r\nf' +226632\\n'\r\nf' {x_sol[i]}\\n'\r\nf' {y_sol[i]}\\n'\r\nf' {z_sol[i]}\\n'\r\nf' {vx_sol[i]}\\n'\r\nf' {vy_sol[i]}\\n'\r\nf' {vz_sol[i]}\\n'\r\n' NOMINAL\\n'\r\n' \\n')\r\n\r\n'\\n'\r\n'\\n'\r\n","sub_path":"Entrega final/Entrega_Final.py","file_name":"Entrega_Final.py","file_ext":"py","file_size_in_byte":5810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"102494408","text":"# coding=utf-8\nimport logging\nimport re\nfrom os import path\nimport pprint\nimport decimal\nimport typing as t\n\nfrom beancount.core import amount\nfrom beancount.core import account\nfrom beancount.core import data # pylint:disable=E0611\nfrom beancount.core import flags\nfrom beancount.ingest import importer\nfrom beancount.ingest import cache\n\nfrom fp_bc.utils import CsvUnicodeReader\nfrom fp_bc import utils\n\n\n__version__ = \"2.0.0\"\n\n\ndef short(account_name: str) -> str:\n if account.leaf(account_name) == \"Caisse\":\n return \"Caisse\"\n if account.leaf(account_name) == \"Cash\":\n return \":\".join(account_name.split(\":\")[-2:])\n if account_name.split(\":\")[0] in (\"Expenses\", \"Income\", \"Equity\"):\n return \":\".join(account_name.split(\":\")[1:])\n return account.leaf(account_name)\n\n\nNoneType = type(None)\nbc_directives = t.Union[\n data.Open,\n data.Close,\n data.Commodity,\n data.Balance,\n data.Pad,\n data.Transaction,\n data.Note,\n data.Event,\n data.Query,\n data.Price,\n data.Document,\n data.Custom,\n]\n\n\nclass ImporterSG(importer.ImporterProtocol):\n def __init__(self, currency: str, account_root: str, account_id: str, account_cash: t.Union[str, NoneType], tiers_update: t.List = None) -> None:\n self.logger = logging.getLogger(__file__) # pylint: disable=W0612\n self.currency = currency\n self.account_root = account_root\n self.account_id = account_id\n self.account_cash = account_cash\n self.tiers_update = tiers_update\n\n def name(self) -> str:\n # permet d'avoir deux comptes et de pouvoir les differenciers au niveau de la config\n return \"{}.{}\".format(self.__class__.__name__, self.account_id)\n\n def identify(self, file: t.IO) -> t.Optional[t.Match[str]]:\n return re.match(f\"{self.account_id}.*.csv\", path.basename(file.name))\n\n def file_account(self, _: t.IO) -> str:\n return self.account_root\n\n def check_before_add(self, entry: data.Transaction) -> None:\n try:\n data.sanity_check_types(entry)\n for posting in entry.postings:\n if posting.account is None:\n raise AssertionError(\"problem\")\n except AssertionError as exp:\n self.logger.error(f\"error , problem assertion {pprint.pformat(exp)} in the transaction {pprint.pformat(entry)}\")\n\n def tiers_update_verifie(self, tiers: str) -> str:\n if self.tiers_update:\n for regle_tiers in self.tiers_update:\n if re.search(regle_tiers[0], tiers, re.UNICODE | re.IGNORECASE):\n tiers = regle_tiers[1]\n tiers = tiers.capitalize()\n return tiers\n\n def extract(self, file: cache._FileMemo, existing_entries: t.Optional[t.List[bc_directives]] = None) -> t.List[bc_directives]:\n # Open the CSV file and create directives.\n entries: t.List[bc_directives] = []\n error = False\n with open(file.name, \"r\", encoding=\"windows-1252\") as fichier:\n for index, row in enumerate(\n CsvUnicodeReader(fichier,\n champs=[\"date\", \"libelle\", \"detail\", \"montant\", \"devise\"],\n ligne_saut=2,\n champ_detail=\"detail\"),\n start=4\n ):\n tiers = None\n narration = \"\"\n cpt2 = None\n meta = data.new_metadata(file.name, index)\n meta[\"comment\"] = row.detail.strip()\n flag = flags.FLAG_WARNING\n try:\n montant = utils.to_decimal(row.row[\"montant\"])\n montant_releve = amount.Amount(montant, self.currency)\n except decimal.InvalidOperation:\n error = True\n self.logger.error(f\"montant '{row.row['montant']}' invalide pour operation ligne {index}\")\n continue\n date_releve = utils.strpdate(row.row[\"date\"], \"%d/%m/%Y\")\n if \"RETRAIT DAB\" in row.detail: # retrait espece\n regex_retrait = re.compile(r\"CARTE \\S+ RETRAIT DAB(?: ETRANGER| SG)? (?P\\d\\d/\\d\\d)\")\n retour = regex_retrait.match(row.detail)\n if not retour:\n self.logger.error(f\"attention , probleme regex_retrait pour operation ligne {index}\")\n error = True\n continue\n posting_1 = data.Posting(account=self.account_root, units=montant_releve, cost=None, flag=None, meta=None, price=None,)\n if self.account_cash:\n if montant < 0:\n narration = \"%s => %s\" % (short(self.account_root), short(self.account_cash))\n else:\n narration = \"%s => %s\" % (short(self.account_cash), short(self.account_root))\n posting_2 = data.Posting(\n account=self.account_cash,\n units=amount.Amount(montant * decimal.Decimal(\"-1\"), self.currency),\n cost=None,\n flag=None,\n meta=None,\n price=None,\n )\n transac = data.Transaction(\n meta=meta,\n date=date_releve,\n flag=flag,\n payee=\"Retrait\",\n narration=narration,\n tags=data.EMPTY_SET,\n links=data.EMPTY_SET,\n postings=[posting_1, posting_2],\n )\n else:\n if montant < 0:\n narration = \"retrait %s\" % short(self.account_root)\n else:\n narration = \"dépôt %s\" % short(self.account_root)\n transac = data.Transaction(\n meta=meta,\n date=date_releve,\n flag=flag,\n payee=\"Retrait\",\n narration=narration,\n tags=data.EMPTY_SET,\n links=data.EMPTY_SET,\n postings=[posting_1, ],\n )\n self.check_before_add(transac)\n entries.append(transac)\n continue\n # virement interne\n if \"GENERATION VIE\" in row.detail:\n cpt2 = \"Assets:Titre:Generation-vie:Cash\"\n if \"CPT 000304781\" in row.detail:\n cpt2 = \"Assets:Titre:SG-LivretA\"\n if \"CPT 000341517\" in row.detail:\n cpt2 = \"Assets:Titre:SG-LDD\"\n if row.in_detail(r\"PREL VERST VOL\", row.champ_detail) and row.in_detail(r\"DE: SG\", row.champ_detail):\n cpt2 = \"Assets:Titre:PEE:Cash\"\n if cpt2: # VIREMENT interne\n posting_1 = data.Posting(account=self.account_root, units=montant_releve, cost=None, flag=None, meta=None, price=None,)\n posting_2 = data.Posting(\n account=cpt2,\n units=amount.Amount(montant * decimal.Decimal(\"-1\"), self.currency),\n cost=None,\n flag=None,\n meta=None,\n price=None,\n )\n tiers = \"Virement\"\n if montant < 0:\n narration = \"%s => %s\" % (short(self.account_root), short(cpt2))\n else:\n narration = \"%s => %s\" % (short(cpt2), short(self.account_root))\n links = data.EMPTY_SET\n transac = data.Transaction(\n meta=meta,\n date=date_releve,\n flag=flag,\n payee=tiers.strip(),\n narration=narration,\n tags=data.EMPTY_SET,\n links=links,\n postings=[posting_1, posting_2],\n )\n entries.append(transac)\n continue\n if row.in_detail(r\"^CARTE \\w\\d\\d\\d\\d(?! RETRAIT)\"): # cas general de la visa\n reg_visa = r\"(?:CARTE \\w\\d\\d\\d\\d) (?:REMBT )?(?P\\d\\d\\/\\d\\d) (?P.*?)(?:\\d+,\\d\\d|COMMERCE ELECTRONIQUE|$|\\s\\d+IOPD)\"\n retour = re.search(reg_visa, row.detail, re.UNICODE | re.IGNORECASE)\n if retour:\n tiers = self.tiers_update_verifie(retour.group(\"desc\"))\n if date_releve < utils.strpdate(f\"{retour.group('date')}/{date_releve.year}\", \"%d/%m/%Y\"):\n date_visa = utils.strpdate(f\"{retour.group('date')}/{date_releve.year - 1}\", \"%d/%m/%Y\")\n else:\n date_visa = utils.strpdate(f\"{retour.group('date')}/{date_releve.year}\", \"%d/%m/%Y\")\n if not tiers:\n error = True\n self.logger.error(\"attention , probleme regex visa pour operation ligne %s\", index)\n self.logger.error(f\"{row.detail}\")\n continue\n else:\n error = True\n self.logger.error(\"attention , probleme regex visa pour operation ligne %s\", index)\n self.logger.error(f\"{row.detail}\")\n continue\n posting_1 = data.Posting(account=self.account_root, units=montant_releve, cost=None, flag=None, meta=None, price=None,)\n transac = data.Transaction(\n meta=meta,\n date=date_visa,\n flag=flag,\n payee=tiers,\n narration=\"\",\n tags=data.EMPTY_SET,\n links=data.EMPTY_SET,\n postings=[posting_1, ],\n )\n self.check_before_add(transac)\n entries.append(transac)\n else:\n # c'est un virement non transfert\n regex_virement = r\"VIR EUROPEEN EMIS \\s* LOGITEL POUR: (.*?)(?: \\d\\d \\d\\d BQ \\d+ CPT \\S+)*? REF:\"\n recherche = re.search(regex_virement, row.detail, re.UNICODE | re.IGNORECASE)\n if recherche:\n tiers_1 = recherche.group(1)\n tiers = self.tiers_update_verifie(tiers_1)\n if \"VIR EUROPEEN EMIS\" in row.detail and not tiers:\n error = True\n self.logger.error(f\"attention , probleme regex pour operation ligne {index}\")\n continue\n # prelevement\n if \"PRELEVEMENT EUROPEEN\" in row.detail or \"PRLV EUROPEEN ACC\" in row.detail:\n tiers_1 = row.in_detail(r\"DE:(.+?) ID:\")\n if isinstance(tiers_1, str) and tiers_1 is not None:\n tiers_1 = tiers_1.strip()\n tiers = self.tiers_update_verifie(tiers_1)\n else:\n error = True\n self.logger.error(f\"attention , probleme regex pour operation ligne {index}\")\n continue\n else:\n if \"VIR RECU\" in row.detail and not tiers:\n tiers_1 = row.in_detail(r\" DE: (.+?) (?:(?:MOTIF|REF):) \")\n if isinstance(tiers_1, str) and tiers_1 is not None:\n tiers = self.tiers_update_verifie(tiers_1)\n else:\n tiers_1 = row.in_detail(r\" DE: (.+)\")\n if isinstance(tiers_1, str) and tiers_1 is not None:\n tiers = self.tiers_update_verifie(tiers_1)\n else:\n error = True\n self.logger.error(f\"attention , probleme regex pour operation ligne {index}\")\n continue\n if row.in_detail(\"ECHEANCE PRET\"):\n tiers = \"Sg\"\n if not tiers:\n tiers = self.tiers_update_verifie(row.row[\"libelle\"].capitalize())\n transac = data.Transaction(\n meta=meta,\n date=date_releve,\n flag=flags.FLAG_WARNING,\n payee=tiers,\n narration=narration,\n tags=data.EMPTY_SET,\n links=data.EMPTY_SET,\n postings=[data.Posting(account=self.account_root, units=montant_releve, cost=None, flag=None, meta=None, price=None,)],\n )\n self.check_before_add(transac)\n entries.append(transac)\n if error:\n raise Exception(\"au moins une erreur\")\n return entries\n","sub_path":"fp_bc/importers/sg.py","file_name":"sg.py","file_ext":"py","file_size_in_byte":13520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"510219291","text":"import alabaster\nfrom sprockets.mixins.mediatype import __version__\n\nneeds_sphinx = '1.0'\nextensions = ['sphinx.ext.autodoc',\n 'sphinx.ext.viewcode',\n 'sphinx.ext.intersphinx',\n 'sphinxcontrib.autohttp.tornado']\nsource_suffix = '.rst'\nmaster_doc = 'index'\nproject = 'sprockets.mixins.mediatype'\ncopyright = '2015-2016, AWeber Communications'\nrelease = __version__\nversion = '.'.join(release.split('.')[0:1])\n\npygments_style = 'sphinx'\nhtml_theme = 'alabaster'\nhtml_style = 'custom.css'\nhtml_static_path = ['static']\nhtml_theme_path = [alabaster.get_path()]\nhtml_sidebars = {\n '**': ['about.html', 'navigation.html'],\n}\nhtml_theme_options = {\n 'github_user': 'sprockets',\n 'github_repo': 'sprockets.mixins.media_type',\n 'description': 'Content-Type negotation mix-in',\n 'github_banner': True,\n 'travis_button': True,\n 'sidebar_width': '230px',\n 'codecov_button': True,\n}\n\nintersphinx_mapping = {\n 'python': ('https://docs.python.org/3', None),\n 'requests': ('https://requests.readthedocs.org/en/latest/', None),\n 'sprockets': ('https://sprockets.readthedocs.org/en/latest/', None),\n 'tornado': ('http://tornadoweb.org/en/latest/', None),\n}\n","sub_path":"docs/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"167445833","text":"#!/usr/bin/env python\n# Authors: Huy Pham, Emile Shehada, Shane Stahlheber\n# Date: July 11, 2017\n# Bacterial Growth Simulation Project\n\nfrom __future__ import print_function\n\nimport argparse\nimport os\nimport sys\nimport time\nfrom multiprocessing import Lock, cpu_count\n\n# To prevent crashing during a keyboard interrupt (must be before numpy/scipy)\nos.environ['FOR_DISABLE_CONSOLE_CTRL_HANDLER'] = '1'\n\nimport cv2\nimport numpy as np\nfrom scipy import misc\n\nfrom constants import Config, Globals\nfrom findconsistentpaths import create_consistent\nfrom helperMethods import (collision_matrix, deepcopy_list, find_k_best_moves,\n generate_image_edge_cv2, generate_universes,\n get_frames, improve, init_space, process_init,\n write_state)\nfrom mphelper import InterruptablePool, kwargs\n\n\n__version__ = \"2.2\"\n\n\ndef main():\n\n default_processes = max(cpu_count() // 2, 1)\n\n parser = argparse.ArgumentParser(description=\"Cell-Universe Cell Tracker.\")\n\n parser.add_argument(\"-f\", \"--frames\",\n metavar=\"DIR\",\n type=str,\n default='frames',\n help=\"directory of the frames (default: 'frames')\")\n\n parser.add_argument(\"-v\", \"--version\",\n action=\"version\",\n version=\"%(prog)s {}\".format(__version__))\n\n parser.add_argument(\"-s\", \"--start\",\n metavar=\"FRAME\",\n type=int,\n default=0,\n help=\"start from specific frame (default: 0)\")\n\n parser.add_argument(\"-p\", \"--processes\",\n metavar=\"COUNT\",\n type=int,\n default=default_processes,\n help=\"number of concurrent processes to run \"\n \"(default: {})\".format(default_processes))\n\n parser.add_argument(\"-o\", \"--output\",\n metavar=\"OUTDIR\",\n type=str,\n default=\"Output\",\n help=\"directory of output states and images \"\n \"(default: 'Output')\")\n\n parser.add_argument(\"initial\",\n type=str,\n help=\"initial properties file ('example.init.txt')\")\n\n cli_args = parser.parse_args()\n\n # get starting frame\n t = cli_args.start\n frames_dir = cli_args.frames\n output_dir = cli_args.output\n frames = get_frames(frames_dir, t)\n\n # Initialize the Space S\n with open(cli_args.initial, 'r') as file:\n S = init_space(t, file)\n\n # Creating directories\n image_dirs = []\n state_dirs = []\n for i in range(Config.K):\n image_dirs.append(os.path.join(output_dir, Config.images_dir, str(i)))\n if not os.path.exists(image_dirs[i]):\n os.makedirs(image_dirs[i])\n\n state_dirs.append(os.path.join(output_dir, Config.states_dir, str(i)))\n if not os.path.exists(state_dirs[i]):\n os.makedirs(state_dirs[i])\n\n # Creating a pool of processes\n lock = Lock()\n pool = InterruptablePool(cli_args.processes,\n initializer=process_init,\n initargs=(lock,\n Globals.image_width,\n Globals.image_height,\n cli_args.initial))\n\n # Processing\n for frame in frames:\n print(\"Processing frame {}...\".format(t))\n sys.stdout.flush()\n\n start = time.time()\n frame_array = (cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY) > 0)*np.int16(1)\n\n # generate the list of arguments for find_k_best_moves_mapped\n args = []\n for index, U in enumerate(S):\n\n # calculate U's matrix for collision detection\n M = collision_matrix(U)\n\n for bacterium_index in range(len(U)):\n args.append(kwargs(\n U=deepcopy_list(U), # deep copy of universes\n frame_array=frame_array, # current image\n index=index, # index of universe\n i=bacterium_index, # index of bacterium\n count=len(S), # number of universes\n M=M, # the collision matrix\n start=start)) # start time for current frame\n\n # Find best moves for each bacterium in each universe\n moves_list = pool.map(find_k_best_moves, args)\n\n # initialize the best move lists\n best_moves = [[None for _ in universe] for universe in S]\n\n # organize the best move dictionary into a list\n for moves in moves_list:\n best_moves[moves[0]][moves[1]] = moves[2]\n\n # generate the list of arguments for generate_universes\n args = []\n for index, U in enumerate(S):\n args.append(kwargs(\n U=deepcopy_list(U), # deepcopy of universes\n frame_array=frame_array, # current image\n index=index, # index of universe\n count=len(S), # number of universes\n best_moves=best_moves[index], # list of best moves\n start=start)) # start time for current frame\n\n # Generate future universes from S\n new_S = pool.map(generate_universes, args)\n\n # flatten new_S in to a list of universes's (S)\n S = [universe for universe_list in new_S for universe in universe_list]\n\n # Pulling stage\n S.sort(key=lambda x: x[0])\n\n # improve the top 3K universes\n k3 = min(3*Config.K, len(S))\n args = []\n for index in range(k3):\n args.append(kwargs(\n Si=S[i],\n frame_array=frame_array,\n index=index,\n count=k3,\n start=start))\n S = pool.map(improve, args)\n\n # pick the K best universes\n S.sort(key=lambda x: x[0])\n S = S[:Config.K]\n\n # Combine all best-match bacteria into 1 new universe\n # best_U = best_bacteria(S, frame_array)\n # S.append(best_U)\n\n # Output to files\n # runtime = str(int(time.time() - start))\n for i, (c, U, index, _) in enumerate(S):\n new_frame = np.array(frame)\n # TODO: change the name of the output images and place this info\n # somewhere else.\n # file_name = \"{}{} - {} - {} - {}.png\".format(image_dirs[i],\n # str(t),\n # str(c),\n # str(index),\n # runtime)\n image_filename = \"{}.png\".format(t)\n image_path = os.path.join(image_dirs[i], image_filename)\n generate_image_edge_cv2(U, new_frame)\n misc.imsave(image_path, new_frame)\n\n state_filename = \"{}.txt\".format(t)\n state_path = os.path.join(state_dirs[i], state_filename)\n write_state(state_path, index, U)\n\n S = [U for _, U, _, _ in S[:Config.K]]\n\n # next frame\n t += 1\n\n # make consistent\n print(\"Making consistent universes...\")\n create_consistent(cli_args.start, t-1, output_dir)\n\n # finished\n print(\"Finished!\")\n parser.exit(0)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"celluniverse.py","file_name":"celluniverse.py","file_ext":"py","file_size_in_byte":7641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"619085403","text":"from flask import Flask\nfrom flask import jsonify\nfrom flask import request, session, url_for, redirect, make_response\nfrom flask_pymongo import PyMongo\nfrom flask_login import LoginManager, current_user, login_user, logout_user, login_required, UserMixin\nfrom bson.objectid import ObjectId\nimport bson.json_util\nimport json\nimport pymongo\nimport random\nimport datetime\nimport string\nfrom ast import literal_eval\nfrom flask_cors import CORS, cross_origin\nimport data_structs\nfrom solver import *\nfrom flask_bcrypt import Bcrypt\nfrom flask_jwt_extended import JWTManager\nfrom flask_jwt_extended import (create_access_token, create_refresh_token, jwt_required, jwt_refresh_token_required, get_jwt_identity, get_raw_jwt)\nfrom flask_mail import Mail, Message\nsite_url = 'http://localhost:3000/'\n\n\napp = Flask(__name__)\ncors = CORS(app, resources={r\"/*\":{\"origins\": site_url}})\n\n\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\nlogin_manager.login_view = 'login'\napp.testing=False\napp.config['MONGO_DBNAME'] = 'language_allocation_database'\napp.config['MONGO_URI'] = 'mongodb://localhost:27017/language_allocation_database'\napp.config['SECRET_KEY'] = '6Cb4CTv46t39GYncwkmTEbcjs9415fskfnR'\napp.config['JWT_BLACKLIST_ENABLED'] = True\napp.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access', 'refresh']\napp.config['CORS_HEADERS'] = 'Content-Type'\napp.config['JWT_SECRET_KEY'] = 'WkDHlzbF3d6kWOGQcZvKudFjsJNeSOFY'\n\napp.config['MAIL_SERVER'] = 'smtp.gmail.com'\napp.config['MAIL_PORT'] = 465\napp.config['MAIL_USE_SSL'] = True\napp.config['MAIL_USERNAME'] = '3071go.nathan@gmail.com'\napp.config['MAIL_PASSWORD'] = 'youhou95'\nmongo = PyMongo(app)\nblacklist = set()\nbcrypt = Bcrypt(app)\njwt = JWTManager(app)\nmail = Mail(app)\n\ndef generate_token():\n return ''.join(random.choices(string.ascii_uppercase +string.ascii_lowercase+ string.digits, k=35))\n\n@jwt.token_in_blacklist_loader\ndef check_if_token_in_blacklist(decrypted_token):\n jti = decrypted_token['jti']\n return jti in blacklist\n\n\n@app.route('/admin/login', methods=['POST'])\n@cross_origin(origin=site_url, headers=['Content-Type','Authorization'], supports_credentials=True)\ndef login():\n users = mongo.db.users\n email = request.get_json(force=True)['email']\n password = request.get_json(force=True)['password']\n result = \"\"\n\n response = users.find_one({'type': 'admin', 'email' : email})\n\n if response:\n if bcrypt.check_password_hash(response['password'], password):\n access_token = create_access_token(identity = {\n\t\t\t 'name': response['first_name'],\n\t\t\t\t'email': response['email']}\n\t\t\t\t)\n\n result = jsonify({\"token\":access_token})\n else:\n result = jsonify({\"error\":\"Invalid username and password\"})\n else:\n result = jsonify({\"error\":\"No results found\"})\n return result\n\n@app.route('/admin/logout', methods=[\"DELETE\"])\n@cross_origin(origin=site_url,headers=['Content-Type','Authorization'], supports_credentials=True)\n@jwt_required\ndef logout():\n jti = get_raw_jwt()['jti']\n blacklist.add(jti)\n return jsonify({\"msg\": \"Successfully logged out\"}), 200\n\n\n@app.route('/admin/check-auth', methods=['GET'])\n@cross_origin(origin=site_url,headers=['Content-Type','Authorization'], supports_credentials=True)\n@jwt_required\ndef check_auth():\n return jsonify({\"state\":\"true\"})\n\n@app.route('/admin/register', methods=['POST'])\n@cross_origin(origin=site_url, headers=['Content-Type','Authorization'], supports_credentials=True)\ndef register():\n users = mongo.db.users\n first_name = request.get_json(force=True)['first_name']\n last_name = request.get_json(force=True)['last_name']\n email = request.get_json(force=True)['email']\n password = bcrypt.generate_password_hash(request.get_json(force=True)['password']).decode('utf-8')\n\n user_id = users.insert({\n\t'first_name' : first_name,\n\t'last_name' : last_name,\n\t'email' : email,\n\t'password' : password,\n 'type' : \"admin\"\n\t})\n new_user = users.find_one({'_id' : user_id})\n\n result = {'email' : new_user['email'] + ' registered'}\n\n return jsonify({'result' : result})\n\n\n\n@login_manager.user_loader\ndef load_user(user_id):\n return User(user_id)\n\n\ndef get_max_collection_id(collection):\n max_column = collection.find_one(sort=[(\"id\", -1)])\n if max_column==None:\n return 0\n return int(max_column[\"id\"])\n\n\n\n@app.route('/courses/', methods=['GET'])\n@cross_origin(origin=site_url,headers=['Content-Type','Authorization'], supports_credentials=True)\ndef get_all_courses():\n courses = mongo.db.courses\n all_courses = courses.find()\n if all_courses:\n Output = []\n for course in all_courses:\n output={}\n output[\"id\"] = course[\"id\"]\n output[\"name\"] = course[\"name\"]\n output[\"language\"] = course[\"language\"]\n output[\"creneaux\"] = course[\"creneaux\"]\n output[\"min_students\"] = course[\"min_students\"]\n output[\"max_students\"] = course[\"max_students\"]\n Output.append(output)\n html_code = 200\n else:\n output = \"No courses\"\n html_code = 400\n return jsonify({'result': Output}), html_code\n\n\n\n@app.route('/courses/', methods=['GET'])\n@cross_origin(origin=site_url,headers=['Content-Type','Authorization'], supports_credentials=True)\ndef get_course_by_id(course_id):\n courses = mongo.db.courses\n course = courses.find_one({\"id\": int(course_id)})\n if course:\n output={}\n output[\"id\"] = course[\"id\"]\n output[\"name\"] = course[\"name\"]\n output[\"language\"] = course[\"language\"]\n output[\"creneaux\"] = course[\"creneaux\"]\n output[\"min_students\"] = course[\"min_students\"]\n output[\"max_students\"] = course[\"max_students\"]\n html_code = 200\n else:\n output = \"No matching course for id \" + str(course_id)\n html_code = 400\n return jsonify({'result': output}), html_code\n\n\n@app.route('/courses/by-language/', methods=['GET'])\n@cross_origin(origin=site_url,headers=['Content-Type','Authorization'])\ndef get_course_by_language(language):\n courses = mongo.db.courses\n courses_of_language = courses.find({\"language\": language})\n if courses_of_language:\n Output = []\n for course in courses_of_language:\n output={}\n output[\"id\"] = course[\"id\"]\n output[\"name\"] = course[\"name\"]\n output[\"language\"] = course[\"language\"]\n output[\"creneaux\"] = course[\"creneaux\"]\n output[\"min_students\"] = course[\"min_students\"]\n output[\"max_students\"] = course[\"max_students\"]\n Output.append(output)\n html_code = 200\n else:\n Output = \"No matching course for language \" + str(language)\n html_code = 400\n return jsonify({'result': Output}), html_code\n\n@app.route('/courses/not-english/', methods=['GET'])\n@cross_origin(origin=site_url,headers=['Content-Type','Authorization'], supports_credentials=True)\ndef get_course_not_english():\n courses = mongo.db.courses\n Output = []\n for course in courses_of_language:\n if course[\"language\"] != \"Anglais\":\n output={}\n output[\"id\"] = course[\"id\"]\n output[\"name\"] = course[\"name\"]\n output[\"language\"] = course[\"language\"]\n output[\"creneaux\"] = course[\"creneaux\"]\n output[\"min_students\"] = course[\"min_students\"]\n output[\"max_students\"] = course[\"max_students\"]\n Output.append(output)\n html_code = 200\n return jsonify({'result': Output}), html_code\n\n\n@app.route('/courses/', methods=['POST'])\n@cross_origin(origin=site_url,headers=['Content-Type','Authorization'], supports_credentials=True)\ndef update_course(course_id):\n courses = mongo.db.courses\n new_name = request.get_json(force=True)['name']\n new_language = request.get_json(force=True)['language']\n new_creneaux = request.get_json(force=True)['creneaux']\n new_min_students = request.get_json(force=True)['min_students']\n new_max_students = request.get_json(force=True)['max_students']\n course_update = courses.update({\"id\":int(course_id)}, {\"id\":int(course_id),\n \"name\":new_name,\n \"language\":new_language,\n \"creneaux\":new_creneaux,\n \"min_students\":new_min_students,\n \"max_students\":new_max_students})\n if course_update:\n output = \"Course with id \"+course_id+\" updated successfully\"\n html_code = 200\n else:\n output = \"No matching course for id \" + str(course_id)\n html_code = 400\n return jsonify({'result': output}), html_code\n\n\n@app.route('/courses/', methods=['PUT'])\n@cross_origin(origin=site_url,headers=['Content-Type','Authorization'], supports_credentials=True)\ndef add_course():\n courses = mongo.db.courses\n id = get_max_collection_id(courses)+1\n new_name = request.get_json(force=True)['name']\n new_language = request.get_json(force=True)['language']\n new_creneaux = request.get_json(force=True)['creneaux']\n new_min_students = request.get_json(force=True)['min_students']\n new_max_students = request.get_json(force=True)['max_students']\n course_inserted = courses.insert({\"id\":int(id),\n \"name\":new_name,\n \"language\":new_language,\n \"creneaux\":new_creneaux,\n \"min_students\":new_min_students,\n \"max_students\":new_max_students})\n if course_inserted:\n output = {\"id\":id}\n html_code = 200\n else:\n output = \"Could not add course\"\n html_code = 400\n return jsonify({'result': output}), html_code\n\n\n@app.route('/courses/', methods=['DELETE'])\n@cross_origin(origin=site_url,headers=['Content-Type','Authorization'], supports_credentials=True)\ndef remove_course(course_id):\n courses = mongo.db.courses\n course_removed = courses.remove({\"id\":int(course_id)})\n if course_removed:\n output = \"Course successfully removed\"\n html_code = 200\n else:\n output = \"Could not remove course\"\n html_code = 400\n return jsonify({'result': output}), html_code\n\n\n\n@app.route('/creneaux/', methods=['GET'])\n@cross_origin(origin=site_url,headers=['Content-Type','Authorization'])\ndef get_all_creneaux():\n creneaux = mongo.db.creneaux\n all_creneaux = creneaux.find()\n Output = []\n for creneau in all_creneaux:\n output={}\n output[\"id\"] = creneau[\"id\"]\n output[\"day\"] = creneau[\"day\"]\n output[\"begin\"] = creneau[\"begin\"]\n output[\"end\"] = creneau[\"end\"]\n output[\"type\"] = creneau[\"type\"]\n Output.append(output)\n html_code = 200\n return jsonify({'result': Output}), html_code\n\n\n@app.route('/creneaux/', methods=['GET'])\n@cross_origin(origin=site_url,headers=['Content-Type','Authorization'])\ndef get_creneau_by_id(creneau_id):\n creneaux = mongo.db.creneaux\n creneau = creneaux.find_one({\"id\": int(creneau_id)})\n if creneau:\n output={}\n output[\"id\"] = creneau[\"id\"]\n output[\"day\"] = creneau[\"day\"]\n output[\"begin\"] = creneau[\"begin\"]\n output[\"end\"] = creneau[\"end\"]\n output[\"type\"] = creneau[\"type\"]\n html_code = 200\n else:\n output = \"No matching creneau for id \" + str(course_id)\n html_code = 400\n return jsonify({'result': output}), html_code\n\n@app.route('/creneaux/by-promotion/', methods=['GET'])\n@cross_origin(origin=site_url,headers=['Content-Type','Authorization'])\ndef get_creneau_by_promo(promo):\n creneaux = mongo.db.creneaux.find({\"type\" : {'$regex': promo}})\n Output = []\n for creneau in creneaux:\n if promo in creneau[\"type\"]:\n output={}\n output[\"id\"] = creneau[\"id\"]\n output[\"day\"] = creneau[\"day\"]\n output[\"begin\"] = creneau[\"begin\"]\n output[\"end\"] = creneau[\"end\"]\n output[\"type\"] = creneau[\"type\"]\n Output.append(output)\n html_code = 200\n return jsonify({'result': Output}), html_code\n\n\n@app.route('/creneaux/', methods=['POST'])\n@cross_origin(origin=site_url,headers=['Content-Type','Authorization'])\ndef update_creneau(creneau_id):\n creneaux = mongo.db.creneaux\n new_day = request.get_json(force=True)['day']\n new_begin = request.get_json(force=True)['begin']\n new_end = request.get_json(force=True)['end']\n new_type = request.get_json(force=True)['type']\n creneau_updated = courses.update({\"id\":int(creneau_id)}, {\"id\":int(creneau_id),\n \"day\":new_day,\n \"begin\":new_begin,\n \"end\":new_end,\n \"type\":new_type})\n if creneau_updated:\n output = \"Creneau with id \"+creneau_id+\" updated successfully\"\n html_code = 200\n else:\n output = \"No matching creneau for id \" + str(creneau_id)\n html_code = 400\n return jsonify({'result': output}), html_code\n\n\n@app.route('/creneaux/', methods=['PUT'])\n@cross_origin(origin=site_url,headers=['Content-Type','Authorization'])\ndef add_creneau():\n creneaux = mongo.db.creneaux\n id = get_max_course_id()+1\n new_day = request.get_json(force=True)['day']\n new_begin = request.get_json(force=True)['begin']\n new_end = request.get_json(force=True)['end']\n new_type = request.get_json(force=True)['type']\n creneau_inserted = courses.insert({\"id\":int(creneau_id),\n \"day\":new_day,\n \"begin\":new_begin,\n \"end\":new_end,\n \"type\":new_type})\n if course_inserted:\n output = {\"id\":id}\n html_code = 200\n else:\n output = \"Could not add course\"\n html_code = 400\n return jsonify({'result': output}), html_code\n\n\n@app.route('/creneaux/', methods=['DELETE'])\n@cross_origin(origin=site_url,headers=['Content-Type','Authorization'])\ndef remove_creneau(creneau_id):\n creneaux = mongo.db.creneaux\n creneau_removed = creneaux.remove({\"id\":int(creneau_id)})\n if creneau_removed:\n output = \"Creneau successfully removed\"\n html_code = 200\n else:\n output = \"Could not remove creneau\"\n html_code = 400\n return jsonify({'result': output}), html_code\n\n@app.route('/users/students/', methods=['GET'])\n@cross_origin(origin=site_url,headers=['Content-Type','Authorization'])\ndef get_student_by_id(student_id):\n users = mongo.db.users\n student = users.find_one({\"type\": \"student\", \"id\": int(student_id)})\n if student:\n output={}\n output[\"id\"] = student[\"id\"]\n output[\"name\"] = student[\"name\"]\n output[\"email\"] = student[\"email\"]\n output[\"vows\"] = student[\"vows\"]\n html_code = 200\n else:\n output = \"No matching student for id \" + str(student_id)\n html_code = 400\n return jsonify({'result': output}), html_code\n\n@app.route('/users/students/', methods=['GET'])\n@cross_origin(origin=site_url,headers=['Content-Type','Authorization'], supports_credentials=True)\n@jwt_required\ndef get_all_students():\n users = mongo.db.users\n students = users.find({\"type\": \"student\"})\n if students:\n Output = []\n for student in students:\n if student['email']!='':\n output={}\n output[\"id\"] = student[\"id\"]\n output[\"first_name\"] = student[\"name\"].split(' ')[0]\n output[\"last_name\"] = student[\"name\"].split(' ')[1]\n output[\"email\"] = student[\"email\"]\n output[\"token\"] = student[\"token\"]\n Output.append(output)\n html_code = 200\n else:\n Output = \"No student found\"\n html_code = 400\n return jsonify({'result': Output}), html_code\n\n@app.route('/users/students/get-courses', methods=['GET'])\n@cross_origin(origin=site_url,headers=['Content-Type','Authorization'], supports_credentials=True)\n@jwt_required\ndef get_courses_allocation():\n users = mongo.db.users\n students = users.find({\"type\": \"student\"})\n if students:\n Output = []\n for student in students:\n if student['email']!='':\n output={}\n output[\"name\"]=student[\"name\"]\n output[\"email\"]=student[\"email\"]\n output[\"courses\"]=student[\"courses\"]\n Output.append(output)\n html_code = 200\n else:\n Output = \"No student found\"\n html_code = 400\n return jsonify({'result': Output}), html_code\n\n@app.route('/users/students/', methods=['POST'])\n@cross_origin(origin=site_url,headers=['Content-Type','Authorization'], supports_credentials=True)\ndef send_all_students():\n users = mongo.db.users\n students = users.find({\"type\": \"student\"})\n if students:\n Output = []\n for student in students:\n if student['email']!='':\n msg = Message(\"Veuillez remplir le questionnaire langues au lien suivant\",\n sender=\"no-reply@questionnaire-DLC.com\",\n recipients=[student['email']])\n msg.body = \"Voici votre lien personnalisé : \\n\" + site_url+ \"login?token=\"+student['token']\n mail.send(msg)\n html_code = 200\n else:\n Output = \"No student found\"\n html_code = 400\n return jsonify({'result': Output}), html_code\n\n@app.route('/users/students/send-affect', methods=['POST'])\n@cross_origin(origin=site_url,headers=['Content-Type','Authorization'], supports_credentials=True)\ndef send_affectations():\n users = mongo.db.users\n students = users.find({\"type\": \"student\"})\n courses = mongo.db.courses\n if students:\n Output = []\n for student in students:\n if student['email']!='':\n msg = Message(\"Résultats de l'affectation des cours de langues\",\n sender=\"no-reply@questionnaire-DLC.com\",\n recipients=[student['email']])\n msg.body = \"Vous êtes inscrits aux cours suivants : \\n\"\n for course_id in student.courses:\n current = courses.find({'id': course_id})\n msg.body+=current.name+\"\\n\"\n mail.send(msg)\n html_code = 200\n else:\n Output = \"No student found\"\n html_code = 400\n return jsonify({'result': Output}), html_code\n\n@app.route('/admin/students/', methods=['PUT'])\n@cross_origin(origin=site_url,headers=['Content-Type','Authorization'], supports_credentials=True)\n@jwt_required\ndef update_all_students():\n users = mongo.db.users\n students = users.find({\"type\": \"student\"})\n data = request.get_json(force=True)\n print(data)\n for new_student in data:\n\n if 'token' not in new_student or new_student['token']=='':\n new_student['token'] = generate_token()\n empty=False\n for v in new_student.values():\n if v=='':\n print(new_student)\n empty=True\n if empty:\n continue\n\n student_updated = users.update_one({\"email\":new_student[\"email\"]}, {\"$set\" : {\n \"id\":get_max_collection_id(users)+1,\n \"name\":new_student['first_name']+\" \"+new_student['last_name'],\n \"email\":new_student['email'],\n \"type\":\"student\",\n \"vows\":[],\n \"courses\":[],\n \"token\":new_student['token']}}, upsert=True)\n print(student_updated)\n\n if not student_updated:\n users.insert({\"id\":get_max_collection_id(users)+1,\n \"name\":new_student['first_name']+\" \"+new_student['last_name'],\n \"email\":new_student['email'],\n \"type\":\"student\",\n \"vows\":[],\n \"courses\":[],\n \"token\":new_student['token']})\n for student in students:\n still_belongs = False\n for new_student in data:\n if student[\"email\"] == new_student[\"email\"]:\n still_belongs = True\n if not still_belongs:\n users.delete_one({\"email\":student[\"email\"]})\n\n\n\n\n return jsonify({'result': \"done\"}), 200\n\n@app.route('/users/students/', methods=['PUT'])\n@cross_origin(origin=site_url,headers=['Content-Type','Authorization'], supports_credentials=True)\ndef add_student():\n users = mongo.db.users\n id = get_max_collection_id(users)+1\n new_name = request.get_json(force=True)['name']\n new_email = request.get_json(force=True)['email']\n new_token = ''.join(random.choices(string.ascii_uppercase +string.ascii_lowercase+ string.digits, k=35))\n student_inserted = users.insert({\"id\":int(id),\n \"name\":new_name,\n \"email\":new_email,\n \"token\":new_token,\n \"vows\":[],\n \"courses\":[],\n \"type\":\"student\"})\n if student_inserted:\n output = {\"id\":id}\n html_code = 200\n else:\n output = \"Could not add student\"\n html_code = 400\n return jsonify({'result': output}), html_code\n\n@app.route('/users/students/', methods=['POST'])\n@cross_origin(origin=site_url,headers=['Content-Type','Authorization'])\ndef update_student(student_id):\n users = mongo.db.users\n new_name = request.get_json(force=True)['name']\n new_email = request.get_json(force=True)['email']\n new_vows = request.get_json(force=True)['vows']\n student_updated = users.update_one({\"id\":int(student_id)}, {\"$set\" : {\"id\":int(student_id),\n \"name\":new_name,\n \"email\":new_email,\n \"vows\":new_vows}})\n if student_updated:\n output = {}\n output[\"id\"] = student_id\n html_code = 200\n else:\n output = \"Could not add student\"\n html_code = 400\n return jsonify({'result': output}), html_code\n\n\n@app.route('/users/students/vows/', methods=['POST'])\n@cross_origin(origin=site_url,headers=['Content-Type','Authorization'], supports_credentials=True)\ndef update_student_vows(student_token):\n users = mongo.db.users\n new_vows = request.get_json(force=True)['vows']\n student = users.find_one({\"token\":student_token})\n student_updated = users.update_one({\"token\":student_token}, {\"$set\" : {\"vows\":new_vows}})\n if student_updated:\n output = {}\n output[\"token\"] = student_token\n html_code = 200\n msg = Message(\"Voeux enregistrés\",\n sender=\"no-reply@questionnaire-DLC.com\",\n recipients=[student['email']])\n mail.send(msg)\n else:\n output = \"Could not add student's vows\"\n html_code = 400\n return jsonify({'result': output}), html_code\n\n\n@app.route('/login/')\n@cross_origin(origin=site_url,headers=['Content-Type','Authorization'])\ndef login_service(token):\n users = mongo.db.users\n student = users.find_one({\"token\" : token})\n if student:\n output = student[\"id\"]\n html_code = 200\n return get_student_by_id(output)\n else:\n output = \"No matching student for this token\"\n html_code = 400\n return jsonify({\"result\":output}),html_code\n\n\n\n\n\n\n@app.route('/admin/solve-courses/', methods=['POST'])\n@cross_origin(origin=site_url,headers=['Content-Type','Authorization'], supports_credentials=True)\ndef solve_courses():\n students_from_db = mongo.db.users.find({\"type\" : \"student\"})\n students = []\n for student_from_db in students_from_db:\n current_student = data_structs.student(id = student_from_db[\"id\"])\n current_vows = []\n for vow_from_db in student_from_db[\"vows\"]:\n current_vow = data_structs.vow()\n print(vow_from_db)\n current_vow.from_dict(vow_from_db)\n current_student.vows.append(current_vow)\n\n current_student.name = student_from_db[\"name\"]\n current_student.id = student_from_db[\"id\"]\n students.append(current_student)\n courses_from_db = mongo.db.courses.find()\n courses = []\n for course_from_db in courses_from_db:\n course = data_structs.course(course_from_db[\"id\"],\n course_from_db[\"name\"],\n course_from_db[\"language\"],\n course_from_db[\"creneaux\"],\n course_from_db[\"min_students\"],\n course_from_db[\"max_students\"])\n courses.append(course)\n solve(courses, students)\n for student in students:\n mongo.db.users.update_one({\"id\" : student.id}, {\"$set\":{\"courses\" : [c.to_dict() for c in student.courses]}})\n return jsonify(students), 200\n\n\n\n\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":26316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"308819055","text":"from tkinter import *\n\nwindow = Tk()\nwindow.title(\"My First GUI Program\")\nwindow.minsize(width=800, height=600)\n\n# Creating a label\nmy_label = Label(text=\"I am a Label\", font=(\"Arial\", 15, \"bold\"))\nmy_label.pack()\n\n# Creating a button\n\n\ndef button_clicked():\n new_text = user_input.get()\n my_label.config(text=new_text)\n\n\nmy_button = Button(text=\"Click me!\", command=button_clicked)\nmy_button.pack()\n\n# Creating an entry form\nuser_input = Entry(width=25)\n\n# This code includes some text to begin with\nuser_input.insert(END, \"Type something...\")\nuser_input.pack()\n\n# Textbox\n\ntext = Text(height=10, width=30)\ntext.insert(END, \"This is a textbox\")\n\n# To get the value in text box, from line 1 character 0\nprint(text.get(\"1.0\", END))\ntext.pack()\n\n# Spinbox\n\n\ndef spinbox_used():\n # gets the current value in spinbox.\n print(spinbox.get())\n\n\nspinbox = Spinbox(from_=0, to=10, width=5, command=spinbox_used)\nspinbox.pack()\n\n# Scale\n# Called with current scale value.\n\n\ndef scale_used(value):\n print(value)\n\n\nscale = Scale(from_=0, to=100, command=scale_used)\nscale.pack()\n\n# Checkbutton\n\n\ndef checkbutton_used():\n # Prints 1 if On button checked, otherwise 0.\n print(checked_state.get())\n\n\n# variable to hold on to checked state, 0 is off, 1 is on.\nchecked_state = IntVar()\ncheckbutton = Checkbutton(text=\"Is On?\", variable=checked_state, command=checkbutton_used)\nchecked_state.get()\ncheckbutton.pack()\n\n# Radiobutton\n\n\ndef radio_used():\n print(radio_state.get())\n\n\n# Variable to hold on to which radio button value is checked.\nradio_state = IntVar()\nradiobutton1 = Radiobutton(text=\"Option1\", value=1, variable=radio_state, command=radio_used)\nradiobutton2 = Radiobutton(text=\"Option2\", value=2, variable=radio_state, command=radio_used)\nradiobutton1.pack()\nradiobutton2.pack()\n\n\n# Listbox\n\n\ndef listbox_used(event):\n # Gets current selection from listbox\n print(listbox.get(listbox.curselection()))\n\n\nlistbox = Listbox(height=4)\nfruits = [\"Apple\", \"Pear\", \"Orange\", \"Banana\"]\nfor item in fruits:\n listbox.insert(fruits.index(item), item)\nlistbox.bind(\"<>\", listbox_used)\nlistbox.pack()\nwindow.mainloop()\n\n\n","sub_path":"Day27/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"165381830","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/sanhehu/Documents/GitHub/troposphere_mate-project/troposphere_mate/accessanalyzer.py\n# Compiled at: 2020-02-12 18:15:55\n# Size of source mod 2**32: 2686 bytes\n\"\"\"\nThis code is auto generated from troposphere_mate.code_generator.__init__.py scripts.\n\"\"\"\nimport sys\nif sys.version_info.major >= 3:\n if sys.version_info.minor >= 5:\n from typing import Union, List, Any\nimport troposphere.accessanalyzer\nfrom troposphere.accessanalyzer import ArchiveRule as _ArchiveRule, Filter as _Filter, Tags as _Tags\nfrom troposphere import Template, AWSHelperFn\nfrom troposphere_mate.core.mate import preprocess_init_kwargs, Mixin\nfrom troposphere_mate.core.sentiel import REQUIRED, NOTHING\n\nclass Filter(troposphere.accessanalyzer.Filter, Mixin):\n\n def __init__(self, title=None, Property=REQUIRED, Contains=NOTHING, Eq=NOTHING, Exists=NOTHING, Neq=NOTHING, **kwargs):\n processed_kwargs = preprocess_init_kwargs(title=title, \n Property=Property, \n Contains=Contains, \n Eq=Eq, \n Exists=Exists, \n Neq=Neq, **kwargs)\n (super(Filter, self).__init__)(**processed_kwargs)\n\n\nclass ArchiveRule(troposphere.accessanalyzer.ArchiveRule, Mixin):\n\n def __init__(self, title=None, Filter=REQUIRED, RuleName=REQUIRED, **kwargs):\n processed_kwargs = preprocess_init_kwargs(title=title, \n Filter=Filter, \n RuleName=RuleName, **kwargs)\n (super(ArchiveRule, self).__init__)(**processed_kwargs)\n\n\nclass Analyzer(troposphere.accessanalyzer.Analyzer, Mixin):\n\n def __init__(self, title, template=None, validation=True, Type=REQUIRED, AnalyzerName=NOTHING, ArchiveRules=NOTHING, Tags=NOTHING, **kwargs):\n processed_kwargs = preprocess_init_kwargs(title=title, \n template=template, \n validation=validation, \n Type=Type, \n AnalyzerName=AnalyzerName, \n ArchiveRules=ArchiveRules, \n Tags=Tags, **kwargs)\n (super(Analyzer, self).__init__)(**processed_kwargs)","sub_path":"pycfiles/troposphere_mate-0.0.14-py2.py3-none-any/accessanalyzer.cpython-36.py","file_name":"accessanalyzer.cpython-36.py","file_ext":"py","file_size_in_byte":2146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"357137589","text":"\"\"\"Default constants.\"\"\"\n\n\nJINJA2_ENGINE = \"jinja2\"\n\"\"\"Jinja2 template engine.\"\"\"\n\nM4_ENGINE = \"m4\"\n\"\"\"M4 template engine.\"\"\"\n\nDEFAULT_ENGINE = JINJA2_ENGINE\n\"\"\"Default engine, used if engine not selected, or cannot be initialized.\"\"\"\n\nFEDORA_ID = \"fedora\"\n\"\"\"Fedora OS release ID.\"\"\"\n\nCENTOS_ID = \"centos\"\n\"\"\"Centos IS release ID. Centos 6 has no /etc/os-release config.\"\"\"\n\nGENTOO_ID = \"gentoo\"\n\"\"\"Gentoo OS release ID.\"\"\"\n\nSUPPORTED_OS_IDS = [\n FEDORA_ID,\n CENTOS_ID,\n GENTOO_ID,\n]\n\"\"\"All supported OS IDs. Can be extended via confo's config.\"\"\"\n","sub_path":"confo/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"225997061","text":"import discord\r\nfrom discord.ext import commands\r\nimport urllib\r\nimport urllib.parse\r\nimport asyncio\r\nimport ctypes.util\r\nfrom discord.ext import commands\r\nfrom datetime import datetime\r\nfrom info.db import *\r\n\r\n\r\nclass _help(commands.Cog):\r\n def __init__(self, bot: commands.Bot):\r\n self.bot = bot\r\n\r\n @commands.group(name=\"명령어\", aliases=['help', '도움말', 'commands'])\r\n async def _help(self, ctx):\r\n embedhelp=(\r\n discord.Embed(\r\n title=\"로위 도움말\", \r\n description=\"BOT Commands help\",\r\n color=0xabcee9\r\n )\r\n .add_field(\r\n name=\"!명령어 뮤직\",\r\n value=\"뮤직 관련 명령어\"\r\n )\r\n .add_field(\r\n name=\"!명령어 학교\",\r\n value=\"학교 관련 명령어\"\r\n )\r\n .add_field(\r\n name=\"!명령어 타로\",\r\n value=\"24시간마다 뽑을수 있는 타로 관련 명령어를 확인해요! \\n이것은 봇이 랜덤으로 뽑는것으로 타로관련 상담은 상담원을 이용해주세요!\"\r\n )\r\n .add_field(\r\n name=\"!명령어 기타\",\r\n value=\"기�� 추가된 명령어\"\r\n )\r\n )\r\n if ctx.invoked_subcommand is None:\r\n await ctx.send(\r\n embed=embedhelp\r\n )\r\n @_help.command(name=\"기타\", aliases=[\"etc\"])\r\n async def _helpetc(self, ctx):\r\n embedetc=(\r\n discord.Embed(\r\n title=\"기타 명령어\", \r\n description=\"etc. Command\",\r\n color=0xabcee9\r\n )\r\n .add_field(\r\n name=\"!서버\",\r\n value=\"현재 서버컴퓨터 자원 사용량을 확인합니다\"\r\n )\r\n .add_field(\r\n name=\"!ping\",\r\n value=\"봇 레이턴시를 확인합니다.\"\r\n )\r\n )\r\n await ctx.send(\r\n embed=embedetc\r\n )\r\n \r\n @_help.command(name=\"학교\", aliases=[\"school\"])\r\n async def _helpschool(self, ctx):\r\n embedschool=(\r\n discord.Embed(\r\n title=\"학교관련 명령어\", \r\n description=\"school about Command\",\r\n color=0xabcee9\r\n )\r\n .add_field(\r\n name=\"!급식\",\r\n value=\"전국 학교 급식을 조회합니다\"\r\n )\r\n .add_field(\r\n name=\"!시간표 < 학교 >\",\r\n value=\"해당 학교를 시간표를 조회 합니다.\"\r\n )\r\n )\r\n await ctx.send(\r\n embed=embedschool\r\n )\r\n \r\n @_help.command(name=\"뮤직\", aliases=[\"music\"])\r\n async def _music(self, ctx):\r\n embedmusic=(\r\n discord.Embed(\r\n title=\"뮤직 명령어\", \r\n description=\"music about Command\",\r\n color=0xabcee9\r\n )\r\n .add_field(\r\n name=\"해당 서비스 준비중이에요!\",\r\n value=\"q(≧▽≦q)\"\r\n )\r\n )\r\n await ctx.send(\r\n embed=embedmusic\r\n )\r\n \r\n @commands.command(name=\"개발\", aliases=[\"개발자, 디벨로퍼\"])\r\n async def _dev(self, ctx):\r\n await ctx.send(\r\n \"<@!263670454701522955>\"\r\n )\r\n @commands.command(name='출석체크', aliases=['출석'])\r\n async def _testpoint(self, ctx):\r\n conn, cur = ctypes.util.Connection.getConnetion()\r\n sql = f\"SELECT * FROM daycheck WHERE did=%s\"\r\n cur.execute(sql, ctx.send.author.id)\r\n rs = cur.fetchone()\r\n today = datetime.now().strftime('%Y-%m-%d')\r\n\r\n #이미출석완료\r\n if rs is not None and str(rs.get('date')) == today:\r\n await ctx.send.delete()\r\n await ctx.send(f'**{ctx.send.author.display_name}**님 **{today}** 출석체크가 이미 처리되었습니다')\r\n return\r\n # 처음 출첵\r\n\r\n if rs is None:\r\n sql = 'INSERT INTO daycheck (did, count, date) values (%s, %s, %s)'\r\n cur.execute(sql, (ctx.send.autoir.id, 1, today))\r\n conn.commit()\r\n else:\r\n sql = 'UPDATE daycheck SET count=%s, date=%s WHERE did=%s'\r\n cur.execute(sql, (rs['count']+1, today, ctx.send.author.id))\r\n conn.commit()\r\n await ctx.send(f'**{ctx.send.author.display_name}**님 **{today}** 출석체크 완료되었습니다')","sub_path":"command/etc/_help.py","file_name":"_help.py","file_ext":"py","file_size_in_byte":4582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"295419536","text":"import turtle\nimport os\nimport math\nimport random\n\nwn=turtle.Screen()\nwn.bgcolor(\"black\")\nwn.title(\"Space Invaders\")\n\n#draw border\nborder_pen=turtle.Turtle()\nborder_pen.speed(0) # 0 is the fastest speed here\nborder_pen.color(\"white\")\nborder_pen.penup() # here if now we move the turtle in this program\n# it will not draw anything as the pen is upward and is not writing anything\n# visualise in 3d\nborder_pen.setposition(-300,-300)\nborder_pen.pendown()\nborder_pen.pensize(3)\nfor side in range(4):\n \tborder_pen.forward(600)\n \tborder_pen.left(90)\nborder_pen.hideturtle()\n\n# SET THE SCORES TO 0\nscore=0\n\n# Draw the score\nscore_pen= turtle.Turtle()\nscore_pen.speed(0)\nscore_pen.color(\"white\")\nscore_pen.penup()\nscore_pen.setposition(-290,275)\nscorestring = \"Score: %s\"%score\nscore_pen.write(scorestring, False, align=\"left\",font=(\"Arial\",14,\"normal\"))\nscore_pen.hideturtle()\n#create the player turtle\nplayer=turtle.Turtle()\nplayer.color(\"blue\")\nplayer.shape(\"triangle\")\nplayer.penup()\nplayer.speed(0)\nplayer.setposition(0,-250)\nplayer.setheading(90)\n\nplayerspeed=20\n\n\n#Choose a number of enemies\nnumber_of_enemies = 5\n#Create an empty list of enemies\nenemies= []\n\n#Add enemies to list\nfor i in range(number_of_enemies):\n\t#Create the enemies\n\tenemies.append(turtle.Turtle())\n\n#creating the enemy\n#enemy=turtle.Turtle()\nfor enemy in enemies:\n\tenemy.color(\"red\")\n\tenemy.shape(\"circle\")\n\tenemy.penup()\n\tenemy.speed(0)\n\tx=random.randint(-200,200)\n\ty=random.randint(100,250)\n\tenemy.setposition(x,y)\n\nenemyspeed = 2\n#Create the player's bullet\nbullet=turtle.Turtle()\nbullet.color(\"yellow\")\nbullet.shape(\"circle\")\nbullet.penup()\nbullet.speed(0)\nbullet.setheading(90)\nbullet.shapesize(0.4,0.4)\nbullet.hideturtle()\n\nbulletspeed=25\n\n#Define bullet state\n#ready- ready to fire\n#fire - bullet is firing\nbulletstate= \"ready\"\n\n\ndef move_left():\n\tx= player.xcor()\n\tx-=playerspeed\n\tif x<-280:\n\t\tx=-280\n\tplayer.setx(x)\n\ndef move_right():\n\tx= player.xcor()\n\tx+=playerspeed\n\tif x>280:\n\t\tx=280\n\tplayer.setx(x)\n\ndef fire_bullet():\n\t#declare bullet state as global if it needs change#create keyboard bindings\n\tglobal bulletstate\n\tif bulletstate== \"ready\":\n\t\tbulletstate=\"fire\"\t\n\t\t#Move the bullet to the just above the player\n\t\tx=player.xcor()\n\t\ty=player.ycor()+10\n\t\tbullet.setposition(x,y)\n\t\tbullet.showturtle()\n\ndef iscollision(t1,t2):\n\tdistance= math.sqrt(math.pow(t1.xcor()-t2.xcor(),2)+math.pow(t1.ycor()-t2.ycor(),2))\n\tif distance<15:\n\t\treturn True\n\telse:\n\t\treturn False\n\n\n#Create keyboard bindings\nturtle.listen()\nturtle.onkey(move_left,\"Left\")\nturtle.onkey(move_right,\"Right\")\nturtle.onkey(fire_bullet,\"space\") #space in this case is a small space instead of a capital one\n\n#Main game loop\nwhile True:# infinite loop\n\t\n\tfor enemy in enemies:\n\t\t# Move the enemy\n\t\tx= enemy.xcor()\n\t\tx+=enemyspeed\n\t\tenemy.setx(x)\n\n\t\t# Move the enemy back and down\n\t\tif enemy.xcor()>280:\n\t\t\t# Moves all the enemies down\n\t\t\tfor e in enemies:\n\t\t\t\ty=e.ycor()\n\t\t\t\ty-=40\n\t\t\t\te.sety(y)\n\t\t\t# Change enemies direction\n\t\t\tenemyspeed *= -1\n\t\t\n\t\tif enemy.xcor() < -280:\n\t\t\t# Move all enemies down\n\t\t\tfor e in enemies:\n\t\t\t\ty=e.ycor()\n\t\t\t\ty -= 40\n\t\t\t\te.sety(y)\n\t\t\t# Change enemy direction\t \n\t\t\tenemyspeed *= -1\n\n\t\t\t#Check for a collision between the bullet and they enemy\n\t\tif iscollision(bullet,enemy):\n\t\t\t#Reset the bullet\n\t\t\tbullet.hideturtle()\n\t\t\tbulletstate=\"ready\"\n\t\t\tbullet.setposition(0,-400)\n\t\t\t#Reset the enemy\n\t\t\t# it will again go to a random spot now\n\t\t\tx=random.randint(-200,200) \n\t\t\ty=random.randint(100,250)\n\t\t\tenemy.setposition(x,y) \n\t\t\t# Update the score\n\t\t\tscore += 5\n\t\t\tscorestring= \"Score: %s\"%score\n\t\t\tscore_pen.clear()\n\t\t\tscore_pen.write(scorestring, False, align=\"left\",font=(\"Arial\",14,\"normal\"))\n\n\t\tif iscollision(player,enemy):\n\t\t\tplayer.hideturtle()\n\t\t\tenemy.hideturtle()\n\t\t\tprint(\"GAME OVER...\")\n\t\t\tbreak\n\n\n\n\t#Move the bullet\n\tif bulletstate==\"fire\":\n\t\ty = bullet.ycor()\n\t\ty += bulletspeed\n\t\tbullet.sety(y)\n\n\t#Check to see if the bullet has gone to the top\n\tif bullet.ycor()>275:\n\t\tbullet.hideturtle()\n\t\tbulletstate=\"ready\"\n\n\t\n\n\n\n\n\n","sub_path":"spacegame.py","file_name":"spacegame.py","file_ext":"py","file_size_in_byte":4008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"600708657","text":"# -*- coding: utf-8 -*-\n\nimport random\nimport sys\n\nWORDS = [\n 'account',\n 'achiever',\n 'actor',\n 'addition',\n 'adjustment',\n 'advertisement',\n 'advice',\n 'aftermath',\n 'agreement',\n 'airplane',\n 'airport',\n 'alarm',\n 'amount',\n 'amusement',\n 'angle',\n 'animal',\n 'answer',\n 'ant',\n 'apparatus',\n 'apparel',\n 'apple',\n 'appliance',\n 'approval',\n 'arch',\n 'argument',\n 'arithmetic',\n 'arm',\n 'army',\n 'art',\n 'attack',\n 'attempt',\n 'attention',\n 'attraction',\n 'aunt',\n 'authority',\n 'baby',\n 'back',\n 'badge',\n 'bag',\n 'bait',\n 'balance',\n 'ball',\n 'balloon',\n 'banana',\n 'band',\n 'base',\n 'baseball',\n 'basket',\n 'basketball',\n 'bat',\n 'bath',\n 'battle',\n 'bead',\n 'beam',\n 'bean',\n 'bear',\n 'beast',\n 'bed',\n 'bedroom',\n 'bee',\n 'beef',\n 'beetle',\n 'beggar',\n 'beginner',\n 'behavior',\n 'belief',\n 'believe',\n 'bell',\n 'berry',\n 'bike',\n 'bird',\n 'birth',\n 'birthday',\n 'bit',\n 'bite',\n 'blade',\n 'blood',\n 'blow',\n 'board',\n 'boat',\n 'body',\n 'bomb',\n 'bone',\n 'book',\n 'boot',\n 'border',\n 'bottle',\n 'boundary',\n 'box',\n 'boy',\n 'brain',\n 'brake',\n 'branch',\n 'brass',\n 'bread',\n 'breakfast',\n 'breath',\n 'brick',\n 'bridge',\n 'brother',\n 'brush',\n 'bubble',\n 'bucket',\n 'building',\n 'bulb',\n 'bun',\n 'burn',\n 'burst',\n 'business',\n 'butto',\n 'cabbage',\n 'cable',\n 'cactus',\n 'cake',\n 'cakes',\n 'calculator',\n 'calendar',\n 'camera',\n 'camp',\n 'can',\n 'cannon',\n 'canvas',\n 'cap',\n 'caption',\n 'car',\n 'card',\n 'carpenter',\n 'carriage',\n 'cart',\n 'cast',\n 'cat',\n 'cattle',\n 'cause',\n 'cave',\n 'celery',\n 'cellar',\n 'cemetery',\n 'cent',\n 'chain',\n 'chair',\n 'chalk',\n 'chance',\n 'change',\n 'channel',\n 'cheese',\n 'cherry',\n 'chess',\n 'chicken',\n 'children',\n 'chin',\n 'church',\n 'circle',\n 'clam',\n 'clock',\n 'cloth',\n 'cloud',\n 'clover',\n 'club',\n 'coach',\n 'coal',\n 'coast',\n 'coat',\n 'cobweb',\n 'coil',\n 'collar',\n 'color',\n 'comb',\n 'comfort',\n 'committee',\n 'company',\n 'competition',\n 'condition',\n 'connection',\n 'control',\n 'cook',\n 'copper',\n 'copy',\n 'cord',\n 'cork',\n 'corn',\n 'cough',\n 'country',\n 'cover',\n 'cow',\n 'crack',\n 'cracker',\n 'crate',\n 'crayon',\n 'cream',\n 'creator',\n 'creature',\n 'credit',\n 'crib',\n 'crime',\n 'crook',\n 'crow',\n 'crowd',\n 'crown',\n 'crush',\n 'cry',\n 'cub',\n 'cup',\n 'current',\n 'curtain',\n 'curve',\n 'cushion',\n 'dad',\n 'daughter',\n 'day',\n 'death',\n 'debt',\n 'decision',\n 'deer',\n 'degree',\n 'design',\n 'desire',\n 'desk',\n 'destruction',\n 'detail',\n 'development',\n 'digestion',\n 'dime',\n 'dinner',\n 'dinosaurs',\n 'direction',\n 'dirt',\n 'discovery',\n 'discussion',\n 'disease',\n 'disgust',\n 'distance',\n 'distribution',\n 'division',\n 'dock',\n 'doctor',\n 'dog',\n 'dogs',\n 'doll',\n 'donkey',\n 'door',\n 'downtown',\n 'drain',\n 'drawer',\n 'dress',\n 'drink',\n 'driving',\n 'drop',\n 'drug',\n 'drum',\n 'duck',\n 'dust',\n]\n\nPHRASES = {\n \"class %%%(%%%):\": \"Make a class named %%% that is-a %%%.\",\n \"class %%%(object):\\n\\tdef __init__(self, ***)\": \"class %%% has-a __init__ that takes self and *** parameters.\",\n \"class %%%(object):\\n\\tdef ***(self, @@@)\": \"class has-a function named *** that takes self and @@@ parameters.\",\n \"*** = %%%()\": \"Set *** to an instance of class %%%.\",\n \"***.***(@@@)\": \"From *** get the *** function, and call it with parameters self, @@@.\",\n \"***.*** = '***'\": \"From *** get the *** attribute and set it to '***'.\"\n}\n\n# do the want to drill phrases first\nPHRASE_FIRST = False\nif len(sys.argv) == 2 and sys.argv[1] == \"english\":\n PHRASE_FIRST = True\n\n# load up the words from the website\n\n\ndef convert(snippet, phrase):\n class_names = [w.capitalize() for w in random.sample(WORDS, snippet.count(\"%%%\"))]\n other_names = random.sample(WORDS, snippet.count('***'))\n results = []\n param_names = []\n\n for i in range(0, snippet.count(\"@@@\")):\n param_count = random.randint(1, 3)\n param_names.append(', '.join(random.sample(WORDS, param_count)))\n\n for sentence in snippet, phrase:\n result = sentence[:]\n\n # fake class names\n for word in class_names:\n result = result.replace(\"%%%\", word, 1)\n\n # fake other names\n for word in other_names:\n result = result.replace(\"***\", word, 1)\n\n # fake parameter lists\n for word in param_names:\n result = result.replace(\"@@@\", word, 1)\n\n results.append(result)\n\n return results\n\n\n# keep going nutil the hit CTRL-D\ntry:\n while True:\n snippets = [i for i in PHRASES.keys()]\n random.shuffle(snippets)\n\n for snippet in snippets:\n phrase = PHRASES[snippet]\n question, answer = convert(snippet, phrase)\n if PHRASE_FIRST:\n question, answer = answer, question\n\n print(question)\n a = input(\"> \")\n while a != 'submit':\n a = input()\n print(\"ANSWER: %s\" % answer)\n print('=' * 99)\n print(\"\\n\")\nexcept EOFError:\n print(\"\\nByek\")\n\n","sub_path":"1-lpthw/ex41.py","file_name":"ex41.py","file_ext":"py","file_size_in_byte":5661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"124228619","text":"from PIL import Image\nimport numpy as np\nimport gzip\nimport io\nimport os\n\nPATH_TO_FASHION_MNIST = 'C:\\\\Users\\\\Jay Patel\\\\OneDrive\\\\Desktop\\\\ImageTesting'\n\ntrain_idx3 = os.path.join(PATH_TO_FASHION_MNIST, 'train-images-idx3-ubyte (1).gz')\nx_train= gzip.open(train_idx3)\n\ntrain_idx1=os.path.join(PATH_TO_FASHION_MNIST, 'train-labels-idx1-ubyte (1).gz')\ny_train=gzip.open(train_idx1)\n\n\ntest_idx3=os.path.join(PATH_TO_FASHION_MNIST, 't10k-images-idx3-ubyte (1).gz')\nx_test=gzip.open(test_idx3)\n\n\ntest_idx1=os.path.join(PATH_TO_FASHION_MNIST, 't10k-labels-idx1-ubyte (1).gz')\ny_test=gzip.open(test_idx1)\n\ndef convert_outside_image(img):\n pixel_matrix=np.asarray(img)\n new_img=[]\n for e in pixel_matrix:\n \n new_img+=list(e)\n return [new_img]\n\ndef byte_to_int(n):\n return int.from_bytes(n,'big')\n\ndef getimgarr(f,max_img,oustideIMG=False):\n\n if oustideIMG:\n return convert_outside_image(f) #Outside images need to be converted to pixel arrays seperately b/c of formatting\n \n _=f.read(4)\n total_images=byte_to_int(f.read(4))\n row=byte_to_int(f.read(4))\n col=byte_to_int(f.read(4))\n \n\n images=[]\n for i in range(min(total_images,max_img)):\n curr_img=[]\n for j in range(row*col):\n \n single_pixel=byte_to_int(f.read(1))\n curr_img.append(single_pixel)\n \n images.append(curr_img)\n return images\n \n\ndef calc_distances(x_train,curr_img):\n distances=[]\n \n for i in range(len(x_train)):\n sample=x_train[i]\n dist=0\n for j in range(len(sample)):\n x,y=sample[j],curr_img[j]\n dist+=(x-y)**2\n dist=(dist)**0.5\n distances.append([i,dist]) #Find distance of each test sample from the current image, with its index\n return distances\n\n\n\ndef knn(x_train,curr_img,y_train,k):\n \n distances=calc_distances(x_train,curr_img)\n\n distances.sort(key=lambda x: x[1])\n possible_answers={}\n for j in range(k):\n idx,dist=distances[j]\n\n ans=y_train[idx]\n if ans not in possible_answers:\n possible_answers[ans]=0\n possible_answers[ans]+=1\n ans=max(possible_answers,key=possible_answers.get) \n return ans\n\n\n\n \ndef getlabelarr(y_train,max_labels,outsideLABEL=False):\n\n _=y_train.read(4)\n total_labels=byte_to_int(y_train.read(4))\n \n labels=[]\n for i in range(min(max_labels,total_labels)):\n \n labels.append((int.from_bytes(y_train.read(1),'big')))\n \n return labels\n\ndef main(x_train,y_train,x_test,y_test):\n\n x_train=getimgarr(x_train,60000)\n y_train=getlabelarr(y_train,60000)\n x_test=getimgarr(x_test,10000,False) #Last input is for outside images\n y_test=getlabelarr(y_test,10000) \n # If it is an outside image, manually insert a list of labels\n articles={ 0: \"T-shirt/top\",\n 1:\t\"Trouser\",\n 2:\t\"Pullover\",\n 3:\"Dress\",\n 4:\t\"Coat\",\n 5:\t\"Sandal\",\n 6:\t\"Shirt\",\n 7:\t\"Sneaker\",\n 8:\t\"Bag\",\n 9:\t\"Ankle boot\" }\n total,correct=0,0\n for i in range(len(x_test)):\n img=x_test[i]\n my_ans=knn(x_train,img,y_train,191)\n actual_ans=y_test[i]\n if actual_ans==my_ans:\n correct+=1 \n total+=1\n print(\"My Guess: \" + articles[my_ans] + \", Label: \"+ articles[actual_ans]+ \", Accuracy: \"+ str(correct/total*100))\n\nmain(x_train,y_train,x_test,y_test)\n\n\n\n\n\n\n\n\n\n \n\n\n\n\n\n","sub_path":"KNN.py","file_name":"KNN.py","file_ext":"py","file_size_in_byte":3570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"543206660","text":"#from SimpleCV import Image, Camera\n#cam = Camera()\n#img = cam.getImage()\n#img.save('tmp.jpg')\n\nfrom cv2 import *\n# initialize the camera\ncam = VideoCapture(0) # 0 -> index of camera\nnamedWindow(\"cam-test\",CV_WINDOW_AUTOSIZE)\n\nwhile True:\n s, img = cam.read()\n if s: # frame captured without any errors\n imshow(\"cam-test\",img)\n waitKey(0)\n destroyWindow(\"cam-test\")\n imwrite(\"filename.jpg\",img) #save image\n","sub_path":"screenshot.py","file_name":"screenshot.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"148727120","text":"import torch\nimport torch.nn as nn\nimport torchvision\nclass CategoryLoss(nn.Module):\n def __init__(self, category_num):\n super(CategoryLoss, self).__init__()\n emb = nn.Embedding(category_num, category_num)\n emb.weight.data = torch.eye(category_num)\n self.emb = emb\n self.loss = nn.BCEWithLogitsLoss()\n\n def forward(self, category_logits, labels):\n target = self.emb(labels)\n return self.loss(category_logits, target)\n\n\nclass BinaryLoss(nn.Module):\n def __init__(self, real):\n super(BinaryLoss, self).__init__()\n self.bce = nn.BCEWithLogitsLoss()\n self.real = real\n\n def forward(self, logits):\n if self.real:\n labels = torch.ones(logits.shape[0], 1)\n else:\n labels = torch.zeros(logits.shape[0], 1)\n if logits.is_cuda:\n labels = labels.cuda()\n return self.bce(logits, labels)\n\nclass VGGPerceptualLoss(nn.Module):\n\n def __init__(self, resize=True):\n super(VGGPerceptualLoss, self).__init__()\n blocks = []\n blocks.append(torchvision.models.vgg16(pretrained=True).features[:4].eval())\n blocks.append(torchvision.models.vgg16(pretrained=True).features[4:9].eval())\n blocks.append(torchvision.models.vgg16(pretrained=True).features[9:16].eval())\n blocks.append(torchvision.models.vgg16(pretrained=True).features[16:23].eval())\n for bl in blocks:\n for p in bl:\n p.requires_grad = False\n self.blocks = torch.nn.ModuleList(blocks)\n self.transform = torch.nn.functional.interpolate\n self.mean = torch.nn.Parameter(torch.tensor([0.485, 0.456, 0.406]).view(1,3,1,1))\n self.std = torch.nn.Parameter(torch.tensor([0.229, 0.224, 0.225]).view(1,3,1,1))\n self.resize = resize\n\n def forward(self, input, target):\n if input.shape[1] != 3:\n input = input.repeat(1, 3, 1, 1)\n target = target.repeat(1, 3, 1, 1)\n input = (input-self.mean) / self.std\n target = (target-self.mean) / self.std\n if self.resize:\n input = self.transform(input, mode='bilinear', size=(224, 224), align_corners=False)\n target = self.transform(target, mode='bilinear', size=(224, 224), align_corners=False)\n loss = 0.0\n x = input\n y = target\n for block in self.blocks:\n x = block(x)\n y = block(y)\n loss += torch.nn.functional.l1_loss(x, y)\n return loss","sub_path":"model/losses.py","file_name":"losses.py","file_ext":"py","file_size_in_byte":2503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"21944917","text":"# usage:\n# h5_filenames\n\n# how to run on the big screen directory\n# pwd=${PWD}; for f in seed*step*; do cd ${pwd}; cd $f; python3 ~/dishtiny/script/CalcGenerationInfo.py *.h5 &; while [ $(jobs -r | wc -l) -gt 16 ]; do sleep 1; done; done\n\nimport numpy as np\nimport h5py\nimport sys\nfrom tqdm import tqdm\nimport seaborn as sns\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport os\nfrom keyname import keyname as kn\nfrom fileshash import fileshash as fsh\nfrom joblib import delayed, Parallel\nfrom natsort import natsorted\n\nfilenames = sys.argv[1:]\n\nprint(filenames)\n\n# check all data is from same software source\nassert len({kn.unpack(filename)['_source_hash'] for filename in filenames}) == 1\n\ndef CalcMeanCellGen(filename):\n file = h5py.File(filename, 'r')\n nlev = int(file.attrs.get('NLEV'))\n upd_key = natsorted(\n [key for key in file['Live']]\n )[-1]\n\n return [\n np.mean([\n cgen\n for cgen, live in zip(\n np.array(\n file['CellGen']['lev_'+str(lev)][upd_key]\n ).flatten(),\n np.array(\n file['Live'][upd_key]\n ).flatten()\n )\n if live\n ])\n for lev in range(nlev+1)\n ]\n\ndef SafeCalcMeanCellGen(filename):\n try:\n return CalcMeanCellGen(filename)\n except Exception as e:\n print(\"warning: corrupt or incomplete data file... skipping\")\n print(\" \", filename)\n print(\" \", e)\n return None\n\ndf = pd.DataFrame.from_dict([\n {\n 'Generations Elapsed' : res,\n 'Level' : lev,\n }\n for filename, cellgen in zip(\n filenames,\n Parallel(n_jobs=-1)(\n delayed(SafeCalcMeanCellGen)(filename)\n for filename in tqdm(filenames)\n )\n )\n if cellgen is not None\n for lev, res in enumerate(cellgen)\n])\n\nprint(\"num files:\" , len(filenames))\n\noutfile = kn.pack({\n 'title' : 'elapsedgenerations',\n '_data_hathash_hash' : fsh.FilesHash().hash_files(filenames),\n '_script_fullcat_hash' : fsh.FilesHash(\n file_parcel=\"full_parcel\",\n files_join=\"cat_join\"\n ).hash_files([sys.argv[0]]),\n '_source_hash' :kn.unpack(filenames[0])['_source_hash'],\n 'ext' : '.csv',\n})\n\ndf.to_csv(outfile, index=False)\n\nprint('Output saved to', outfile)\n","sub_path":"old/script/GenerationInfoPrep.py","file_name":"GenerationInfoPrep.py","file_ext":"py","file_size_in_byte":2410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"18517153","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 15 13:29:00 2018\n\n@author: Administrator\n\"\"\"\n\nimport matplotlib.pyplot as plt\nfrom scipy.special import comb\n\ndef f(d):\n s1 = 8**d\n s2 = 0\n for l in range(d+1):\n for m in range(d+1):\n for k in range(d+1):\n if(l > m + k + 1):\n s2 += comb(d, l) * comb(d, m) * comb(d, k)\n return 1 - s2 / s1\n\nD = range(10, 61, 5)\nP = [f(d) for d in D]\n\nplt.plot(D, P)","sub_path":"Chapter9/Exercise 9.5.py","file_name":"Exercise 9.5.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"376344595","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 ]\n\n operations = [\n migrations.CreateModel(\n name='Coin',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('value', models.IntegerField(choices=[(b'1', '1p'), (b'2', '2p'), (b'5', '5p'), (b'10', '10p'), (b'20', '20p'), (b'50', '50p'), (b'100', '1gbp'), (b'200', '2gbp')])),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Item',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=200)),\n ('amount', models.IntegerField()),\n ('description', models.TextField()),\n ('volume_or_mass', models.IntegerField()),\n ('cost', models.IntegerField()),\n ('available_for_sale', models.BooleanField(default=False)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='ItemType',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=150)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Producer',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('display_name', models.CharField(max_length=200)),\n ('url_address', models.URLField()),\n ('address_line1', models.CharField(max_length=200)),\n ('address_line2', models.CharField(max_length=200)),\n ('city', models.CharField(max_length=200)),\n ('post_code', models.CharField(max_length=200)),\n ('country', models.CharField(max_length=200)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Unit',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=100)),\n ('shortcut', models.CharField(max_length=10)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='item',\n name='producer',\n field=models.ForeignKey(to='vending_app.Producer'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='item',\n name='type',\n field=models.ForeignKey(to='vending_app.ItemType'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='item',\n name='volume_or_mass_unit',\n field=models.ForeignKey(to='vending_app.Unit'),\n preserve_default=True,\n ),\n ]\n","sub_path":"vending_app/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":3425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"24514304","text":"#nota = []\nnota_final = 0\nfor n in range(0,4):\n if n == 0:\n palavra = \"primeira\"\n elif n == 1:\n palavra = \"segunda\"\n elif n == 2:\n palavra = \"terceira\"\n else:\n palavra = \"quarta\"\n nota = input(\"Digite a \" + palavra +\" nota: \")\n nota_final += int(nota)\nprint(\"A média aritmética é\", nota_final/4)\n #nota[n] = print(\"Digite a nota\", n)\n","sub_path":"semana-2/exercicios/medias.py","file_name":"medias.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"343162002","text":"import random\nimport time\nfrom datetime import datetime, timedelta\nimport sys\nfrom collections import Counter\nsys.path.append('/Users/nezmi/Projects/yeznable_projects')\n\nfrom LAB.Data_collection import functions_for_db\nfrom personal import id_pw_classes\n\n# DB에 연결해놓기\n# 로그인 정보들 숨길 필요가 있음\nmysql_user = id_pw_classes.mysql()\n\nhost = '127.0.0.1'\nuser = mysql_user.id_yeznable\npassword = mysql_user.pw_yeznable\ndb = 'KAWS_instagram'\n\nconnection = functions_for_db.get_connection(host,user,password,db)\ncursor = connection.cursor()\nprint('DB connected...')\n\n# DB 커서를 생성해서 수집되어있는 링���와 포스팅 정보들을 받아옴\nquery_select_collected_postings_instances = \"SELECT Link, Number_of_like, PostDate, PP_Posting FROM POSTINGS ORDER BY PostDate DESC\"\ncursor.execute(query_select_collected_postings_instances)\ntuple_collected_postings_instances = cursor.fetchall() # ((Link, Number_of_like, PostDate, Posting), ...)\n\nquery_select_target_links_instances = \"SELECT Link FROM POSTINGS_COMMENTS\"\ncursor.execute(query_select_target_links_instances)\ntuple_collected_target_links_instances = cursor.fetchall() # ((Link), ...)\n\n\n# 활용하기 좋게 dictionary 만들기\ndic_collected_postings_instances = {} # gonna be { link: [Number_of_like, PostDate, PP_Posting], ...}\nfor item in tuple_collected_postings_instances:\n dic_collected_postings_instances[item[0]] = list(item[1:])\n # break\n# print(dic_collected_postings_instances)\nprint('dic_collected_postings_instances is made')\n\n# # Term_from_Last\n# for instance in dic_collected_postings_instances.values():\n# PostDate = instance[1]\n\n# # NumLike, LengthPost, PostedYear\n# dic_link_Nums = {} # gonna be { link: [NumLike, LengthPost, PostedYear], ...}\n# for target_link in tuple_collected_target_links_instances:\n# for link in dic_collected_postings_instances.keys():\n# if link == target_link[0]:\n# NumLike = dic_collected_postings_instances[link][0]\n# LengthPost = len(dic_collected_postings_instances[link][2])\n# PostedYear = str(dic_collected_postings_instances[link][1]).split('-')[0]\n#\n# dic_link_Nums[link] = [NumLike, LengthPost, int(PostedYear)]\n# else:\n# continue\n# # break\n# # print(dic_link_Nums)\n#\n# for link in dic_link_Nums.keys():\n# query_update_instance_RP2PC = f\"UPDATE POSTINGS_COMMENTS SET NumLike = {dic_link_Nums[link][0]}, LengthPost = {dic_link_Nums[link][1]}, PostedYear = {dic_link_Nums[link][2]} WHERE Link = '{link}'\"\n# cursor.execute(query_update_instance_RP2PC)\n# connection.commit()\n# # print(query_update_instance_RP2PC)\n# # break\n# connection.close()\n\n# P_NumTag, P_NumCall\ndic_link_Nums = {} # gonna be { link: [P_NumTag, P_NumCall], ...}\nfor target_link in tuple_collected_target_links_instances:\n for link in dic_collected_postings_instances.keys():\n if link == target_link[0]:\n count = Counter(dic_collected_postings_instances[link][2])\n P_NumTag = count[\"#\"]\n P_NumCall = count[\"@\"]\n\n dic_link_Nums[link] = [P_NumTag, P_NumCall]\n else:\n continue\n # break\n\nfor link in dic_link_Nums.keys():\n query_update_instance_RP2PC = f\"UPDATE POSTINGS_COMMENTS SET P_NumTag = {dic_link_Nums[link][0]}, P_NumCall = {dic_link_Nums[link][1]} WHERE Link = '{link}'\"\n cursor.execute(query_update_instance_RP2PC)\n connection.commit()\n # print(query_update_instance_RP2PC)\n # break\nconnection.close()","sub_path":"데청캠/small_project/preprocessing/RP_to_PC.py","file_name":"RP_to_PC.py","file_ext":"py","file_size_in_byte":3560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"566351300","text":"# method_1\nclass Solution:\n def spiralOrder(self, matrix: List[List[int]]) -> List[int]:\n if matrix == []: return []\n low = 0\n high = len(matrix)-1\n left = 0\n right = len(matrix[0])-1\n ans = []\n\n while True:\n # →\n for i in range(left,right+1):\n ans.append(matrix[low][i])\n low += 1\n if low > high:\n break\n # ↓\n for i in range(low,high+1):\n ans.append(matrix[i][right])\n right -= 1\n if right < left:\n break\n # ←\n for i in range(right,left-1,-1):\n ans.append(matrix[high][i])\n high -= 1\n if high < low:\n break\n # ↑\n for i in range(high,low-1,-1):\n ans.append(matrix[i][left])\n left += 1\n if left > right:\n break\n\n return ans\n\n# method_2\nclass Solution:\n def spiralOrder(self, matrix: List[List[int]]) -> List[int]:\n return matrix and [*matrix.pop(0)] + self.spiralOrder([*zip(*matrix)][::-1])\n\n","sub_path":"Qustion Code/54. 螺旋矩阵.py","file_name":"54. 螺旋矩阵.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"202070838","text":"from CSVPackage import CSVPackage\nfrom CSVConnection import CSVConnection\n\nclass CSVCapture:\n \n def __init__(self, filename):\n \n self.cnlist = []\n \n fi = open(filename)\n line = fi.readline()\n while True:\n line = fi.readline()\n if line == '': break\n pk = CSVPackage(line)\n for conn in self.cnlist:\n if conn.isOnConnection(pk):\n conn.add(pk)\n break;\n else:\n if (pk.getSourcePort() != None\\\n and pk.getDesPort() != None):\n newconn = CSVConnection()\n newconn.add(pk)\n self.cnlist.append(newconn)\n \n fi.close()\n pass\n \n\n \n def getConnectionList(self):\n '''\n tra ve tat cac cac connection trong file vua load ra\n '''\n return self.cnlist\n \n \n def getConnection(self, index):\n '''\n lay 1 connect o vi tri index \n '''\n return self.cnlist[0]\n \n def len(self):\n return len(self.cnlist)\n\n#from pprint import pprint\n\n#cap = CSVCapture('../data/short.csv')\n\n\n#for conn in cap.getConnectionList():\n #print conn.menuName()","sub_path":"csvreader/CSVCapture.py","file_name":"CSVCapture.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"378707252","text":"#!/usr/bin/python\n\nimport subprocess\nimport sys\n\nif len(sys.argv) > 1:\n bk_dir = sys.argv[1]\nelse:\n bk_dir = 'background'\n\nnum_files = subprocess.check_output('ls *_p[0-9][0-9][0-9][0-9] | grep -v w00 | wc -l', shell=True).rstrip('\\n')\n\nnum_background_files = subprocess.check_output('ls ' + bk_dir + '/*_p[0-9][0-9][0-9][0-9] | grep -v w00 | wc -l', shell=True).rstrip('\\n')\n\nprint (\"\\n num_files = \" + num_files)\nprint (\"num_background_files = \" + num_background_files)\nprint (\"\\n%.0f %% done\" % (100 * float(num_background_files) / float(num_files)))\n","sub_path":"python/bkgnd_perc.py","file_name":"bkgnd_perc.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"1654442","text":"import itertools\n\nimport numpy as np\n\n\nclass System:\n\n def __init__(\n self,\n box_lo=None,\n box_hi=None,\n atom_data=None,\n molecule_data=None,\n relation_data=None\n ):\n if box_lo is not None:\n self._box_lo = box_lo\n else:\n self._box_lo = np.zeros(3)\n if box_hi is not None:\n self._box_hi = box_hi\n else:\n self._box_hi = np.zeros(3)\n if atom_data is not None:\n self._atom_data = atom_data\n else:\n self._atom_data = []\n if molecule_data is not None:\n self._molecule_data = molecule_data\n else:\n self._molecule_data = []\n if relation_data is not None:\n self._relation_data = relation_data\n else:\n self._relation_data = {}\n self._ids_up_to_date = False\n\n # noinspection PyProtectedMember\n def __add__(self, other):\n return System(\n box_lo=np.minimum(self._box_lo, other._box_lo),\n box_hi=np.maximum(self._box_hi, other._box_hi),\n atom_data=self._atom_data+other._atom_data,\n molecule_data=self._molecule_data+other._molecule_data,\n relation_data=dict(itertools.chain(\n self._relation_data.items(), other._relation_data.items())\n )\n )\n\n def _update_atom_ids(self):\n for i, atom in enumerate(self._atom_data):\n atom.id = i\n\n def _update_molecule_ids(self):\n for i, molecule in enumerate(self._molecule_data):\n for atom in molecule:\n atom.molecule_id = i\n\n def _ensure_ids(self):\n if not self._ids_up_to_date:\n self._update_atom_ids()\n self._update_molecule_ids()\n self._ids_up_to_date = True\n\n def save_lammps(self, path, type_mappings):\n\n self._ensure_ids()\n\n with open(path, 'w', encoding='utf-8') as f:\n print('LAMMPS data file generated by the Capsid Project', file=f)\n print(file=f)\n print('{} atoms'.format(len(self._atom_data)), file=f)\n if 'bond' in self._relation_data:\n print('{} bonds'.format(\n len(self._relation_data['bond'])\n ), file=f)\n if 'dihedral' in self._relation_data:\n print('{} dihedrals'.format(\n len(self._relation_data['dihedral'])\n ), file=f)\n print('{} atom types'.format(len(type_mappings['atom'])), file=f)\n if 'bond' in self._relation_data:\n print('{} bond types'.format(\n len(type_mappings['bond'])\n ), file=f)\n if 'dihedral' in self._relation_data:\n print('{} dihedral types'.format(\n len(type_mappings['dihedral'])\n ), file=f)\n print(file=f)\n print('{} {} xlo xhi'.format(\n self._box_lo[0], self._box_hi[0]\n ), file=f)\n print('{} {} ylo yhi'.format(\n self._box_lo[1], self._box_hi[1]\n ), file=f)\n print('{} {} zlo zhi'.format(\n self._box_lo[2], self._box_hi[2]\n ), file=f)\n print(file=f)\n print('Atoms', file=f)\n print(file=f)\n for atom in self._atom_data:\n print('{0} {1} {2} {3[0]} {3[1]} {3[2]}'.format(\n atom.id+1,\n atom.molecule_id+1,\n type_mappings['atom'].index(atom.type)+1,\n atom.position\n ), file=f)\n try:\n self._atom_data[0].velocity\n except AttributeError:\n pass\n else:\n print(file=f)\n print('Velocities', file=f)\n print(file=f)\n for atom in self._atom_data:\n print('{0} {1[0]} {1[1]} {1[2]}'.format(\n atom.id+1, atom.velocity\n ), file=f)\n if 'bond' in self._relation_data:\n print(file=f)\n print('Bonds', file=f)\n print(file=f)\n for i, bond in enumerate(self._relation_data['bond']):\n atom_1, atom_2 = bond.data[0]\n print('{} {} {} {}'.format(\n i+1,\n type_mappings['bond'].index(bond.type)+1,\n atom_1.id+1,\n atom_2.id+1\n ), file=f)\n if 'dihedral' in self._relation_data:\n print(file=f)\n print('Dihedrals', file=f)\n print(file=f)\n for i, dihedral in enumerate(\n self._relation_data['dihedral']):\n atom_1, atom_4 = dihedral.data[0]\n atom_2, atom_3 = dihedral.data[1]\n print('{} {} {} {} {} {}'.format(\n i+1,\n type_mappings['dihedral'].index(dihedral.type)+1,\n atom_1.id+1,\n atom_2.id+1,\n atom_3.id+1,\n atom_4.id+1\n ), file=f)\n","sub_path":"biomodel/system.py","file_name":"system.py","file_ext":"py","file_size_in_byte":5307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"194042261","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('randint/', views.randint, name='randint'),\n path('lottery/', views.lottery, name='lottery'),\n path('group/', views.group, name='group'),\n]","sub_path":"rand/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":"31"} +{"seq_id":"577742937","text":"class Solution(object):\n def solveNQueens(self, n):\n \"\"\"\n :type n: int\n :rtype: List[List[str]]\n \"\"\"\n self.res = []\n self.dfs(0, 0, 0, 0, [], n)\n return [['.' * j + 'Q' + '.' * (n - j - 1) for j in i] for i in self.res]\n\n def dfs(self, level, col, pie, na, queens, n):\n if level == n:\n self.res.append(queens)\n return\n bits = (~(col | pie | na) & ((1 << n) - 1))\n while bits:\n p = bits & - bits\n bits &= (bits - 1)\n site = bin(p - 1)[2:].count('1')\n self.dfs(level + 1, col | p, (pie | p) << 1, (na | p) >> 1, queens + [site], n)","sub_path":"Week_08/51. N 皇后.py","file_name":"51. N 皇后.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"270478988","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.5 (3350)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/pybot/pybot_main.py\n# Compiled at: 2016-07-13 16:56:07\n# Size of source mod 2**32: 4770 bytes\nimport sys, threading, json, os\nos.chdir(os.path.dirname(__file__) or '.')\nfrom pybot.data import *\nfrom pybot.irc import irc\nfrom pybot.pybotextra import *\nfrom pybot.features.raffle import Raffle\nfrom pybot.features.commands import Commands\nfrom pybot.features.points import Points\nfrom pybot.features.linkgrabber import Linkgrabber\nfrom pybot.features.quotes import Quotes\nfrom pybot.web import pybot_web\nimport pybot.globals as globals\nPYBOT_VERSION = {'status': 'BETA', 'version': 0, 'build': 121}\nPWD = os.getcwd()\n\ndef main():\n settings = globals.settings\n pybotPrint('PYBOT %s VERSION %s BUILD %s' % (PYBOT_VERSION['status'], PYBOT_VERSION['version'], PYBOT_VERSION['build']), 'usermsg')\n if len(json.loads(settings.config['filters']['activeFilters'])) <= 0:\n pybotPrint('[pybot.main] Running with no filters', 'log')\n con = irc(feed)\n globals.con = con\n cmds = Commands(con)\n if toBool(settings.config['points']['enabled']):\n points = Points(con, con.chatters, settings, data)\n if toBool(settings.config['features']['linkgrabber']):\n linkgrabber = Linkgrabber(con)\n if toBool(settings.config['features']['quotes']):\n quotes = Quotes(con)\n threading.Thread(target=con.connect).start()\n if toBool(settings.config['web']['enabled']):\n web = pybot_web.pybot_web(con)\n threading.Thread(target=web.startWebService).start()\n while con.isClosed() == False:\n if con.connected:\n inp = input('')\n if inp:\n con.msg(inp)\n\n pybotPrint('[PYBOT] connection ended', 'log')\n exit()\n\n\ndef feed(con, msg, event):\n if event == 'server_cantchannel' or event == 'server_lost':\n pybotPrint('Lost connection')\n con.retry()\n else:\n if event == 'nick_taken':\n pybotPrint('Nick has been taken!')\n con.retry()\n else:\n if event == 'user_join':\n name = msg.replace(':', '').split('!')[0].replace('\\n\\r', '')\n if name != con.nick:\n joins = getUserData(name)\n setUserData(name, joins + 1)\n else:\n if event == 'user_privmsg':\n name = msg.replace(':', '').split('!')[0].replace('\\n\\r', '')\n text = msg.split('PRIVMSG')[1].replace('%s :' % con.channel, '')\n if con.isMod(name) == False and name != 'jtv':\n con.filter(name, text)\n if checkIfCommand(text, '!raffle'):\n if toBool(globals.settings.config['features']['raffle']):\n texsplit = text.replace('!raffle', '').split(' ')\n raffle = Raffle(con, con.data, texsplit)\n globals.data.raffles.append(raffle)\n else:\n if checkIfCommand(text, '!leave'):\n if con.isMod(name):\n con.msg('Bye!')\n con.close()\n else:\n con.msg('%s, you do not have access to this command.' % name)\n else:\n if checkIfCommand(text, '!permit'):\n cmd_args = text.split(' ')\n if con.isMod(name):\n con.msg('%s can post a link' % cmd_args[2])\n con.addMode(cmd_args[2], '+permit')\n else:\n con.msg('%s, you do not have access to this command.' % name)\n if con.isMod(name):\n pybotPrint('%s : %s' % (name, text), 'usermsg-mod')\n else:\n pybotPrint('%s : %s' % (name, text), 'usermsg')\n elif event == 'user_mode':\n name = msg.split(' ')[4].replace('\\n\\r', '')\n pybotPrint('%s is mode %s' % (name, con.getMode(name)))\n\n\ndef setUserData(user, data):\n return 0\n\n\ndef getUserData(user):\n return 0\n\n\nif __name__ == '__main__':\n main()","sub_path":"pycfiles/Twitch_Pybot-0.1.4-py3.5/pybot_main.cpython-35.py","file_name":"pybot_main.cpython-35.py","file_ext":"py","file_size_in_byte":4458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"155762382","text":"\r\n\r\ndef cluster_purity(cluster_labels:list, real_labels:list):\r\n assert(len(cluster_labels) == len(real_labels))\r\n cluster_dict = dict()\r\n real_dict = dict()\r\n for i in range(len(cluster_labels)):\r\n # 构造聚类结果字典\r\n cluster_label = cluster_labels[i]\r\n if cluster_label not in cluster_dict:\r\n cluster_dict[cluster_label] = set()\r\n cluster_dict[cluster_label].add(i)\r\n # 构造真实分类字典\r\n real_label = real_labels[i]\r\n if real_label not in real_dict:\r\n real_dict[real_label] = set()\r\n real_dict[real_label].add(i)\r\n \r\n inter_sum = 0\r\n for cluster_key in cluster_dict:\r\n cluster_set = cluster_dict[cluster_key]\r\n max_intersize = 0\r\n for real_key in real_dict:\r\n inter_set = cluster_set.intersection(real_dict[real_key])\r\n inter_size = len(inter_set)\r\n if inter_size > max_intersize:\r\n max_intersize = inter_size\r\n assert(max_intersize > 0 and max_intersize <= len(cluster_set))\r\n inter_sum += max_intersize\r\n \r\n return inter_sum / len(cluster_labels)\r\n\r\n\r\ndef cluster_RI(cluster_labels:list, real_labels:list):\r\n assert(len(cluster_labels) == len(real_labels))\r\n data_size = len(cluster_labels)\r\n a = 0\r\n b = 0\r\n c = 0\r\n d = 0\r\n for i in range(data_size):\r\n for j in range(data_size):\r\n if real_labels[i] == real_labels[j]:\r\n if cluster_labels[i] == cluster_labels[j]:\r\n a += 1\r\n else:\r\n b += 1\r\n else:\r\n if cluster_labels[i] == cluster_labels[j]:\r\n c += 1\r\n else:\r\n d += 1\r\n\r\n return (a + d) / (a + b + c + d)\r\n\r\n\r\ndef evaluate(cluster_labels:list, real_labels:list, verbose=True):\r\n print(\"# cluster evaluate.\")\r\n # 统计真实标签和聚类标签\r\n def get_descent_count(labels:list):\r\n label_set = set(labels)\r\n label_counts = sorted([(labels.count(key), key) for key in label_set], reverse=True)\r\n assert(sum([x[0] for x in label_counts]) == len(labels))\r\n return label_counts\r\n cluster_count_result = get_descent_count(cluster_labels)\r\n real_count_result = get_descent_count(real_labels)\r\n print(\" CLUSTER_COUNT: \", cluster_count_result)\r\n print(\" REAL_COUNT: \", real_count_result)\r\n purity = cluster_purity(cluster_labels, real_labels)\r\n print(\" purity: %f\" % purity)\r\n ri = cluster_RI(cluster_labels, real_labels)\r\n print(\" ri: %f\" % ri)\r\n return purity, ri\r\n\r\n\r\ndef calc_SSE(data:list, cluster:list):\r\n # 算出所有的中心\r\n elem_len = len(data[0])\r\n clusterset = set(cluster)\r\n count_dict = {key:0 for key in clusterset}\r\n center_dict = {key:[0 for _ in range(elem_len)] for key in clusterset}\r\n for elem, idx in zip(data, cluster):\r\n count_dict[idx] += 1\r\n for i in range(elem_len):\r\n center_dict[idx][i] += elem[i]\r\n for key in center_dict:\r\n for i in range(elem_len):\r\n center_dict[key][i] /= count_dict[key]\r\n # 求和求出SSE\r\n sse = 0\r\n for elem, idx in zip(data, cluster):\r\n for i in range(elem_len):\r\n sse += (elem[i] - center_dict[idx][i])**2\r\n return sse\r\n ","sub_path":"part2/util/evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":3352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"647189743","text":"def keyOK(n,offset):\n return 2 <= n and 0 <= offset <= 2*n-3\t#Retourne vrai uniquement si les deux conditions sont vérifiées (clé valide)\n\ndef computeCoordinates(n,l,offset):\n list = []\n j = 0\n i = offset\n if offset < n:\t#Commencer à la bonne ligne selon l'offset\n i = offset\n else:\n i = n-(offset-n+1)-1\n while j < l:\t#Tant que la longueur du texte n'est pas atteinte\n if offset < n:\n while i < (n-1):\t#Sens descendant\n list.append((i,j))\n j += 1\n i += 1\n if j == l:\n break\n while j != l:\t\t\t#Sens montant\n offset = 0\n list.append((i,j))\n j += 1\n i -= 1\n if j == l or i ==0:\n break\n return list\n\ndef init(n,l,coordinates):\t#Créé une dictionnaire vide\n dict = {}\n for i in range(l):\n dict[coordinates[i]] = None\t#Les clés sont les coordonnées des lettres et elles contiennent 'none'\n return dict\n\ndef convertLetter(text):\n listAlphabet = [\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\",\"h\",\"i\",\"j\",\"k\",\"l\",\"m\",\"n\",\"o\",\"p\",\"q\",\"r\",\"s\",\"t\",\"u\",\"v\",\"w\",\"x\",\"y\",\"z\",\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"H\",\"I\",\"J\",\"K\",\"L\",\"M\",\"N\",\"O\",\"P\",\"Q\",\"R\",\"S\",\"T\",\"U\",\"V\",\"W\",\"X\",\"Y\",\"Z\"]\n aAccent = [\"â\",\"ä\",\"à\",\"ã\"]\n eAccent = [\"é\",\"è\",\"ê\",\"ë\"]\n iAccent = [\"î\",\"ï\"]\n oAccent = [\"ô\",\"ö\"]\n uAccent = [\"û\",\"ü\"]\n list = []\n for i in range(len(text)):\n if text[i] in listAlphabet:\t\t#On ajoute le caracttère seulement si il est compris dans listAlphabet\n list.append(text[i])\n elif text[i] in aAccent:\t\t#Pour supprimer les accents\n list.append(\"a\")\n elif text[i] in eAccent:\n list.append(\"e\")\n elif text[i] in iAccent:\n list.append(\"i\")\n elif text[i] in oAccent:\n list.append(\"o\")\n elif text[i] in uAccent:\n list.append(\"u\")\n text = \"\".join(list).upper()\t\t#Transforme le liste en string et en majuscule\n return text\n\ndef fullDictionaryCipher(text,l,coordinates,dictionary):\n for i in range(l):\n dictionary[coordinates[i]]=text[i]\t#Pour chaque coordonnée, associe une lettre du texte\n\ndef fullDictionaryDecipher(text,n,l,coordinates,dictionary):\n for i in range(l):\n e = 0\n for i in range(n):\n for j in range(l):\n if (i,j) == coordinates[j]:\t#Si la coordonnée est présente dans le dictionnaire, ajoute la lettre correspondante dans text\n dictionary[(i,j)]=text[e]\n e += 1\n\ndef fullDictionary(text,n,l,coordinates,dictionary,cipher):\n if cipher:\n fullDictionaryDecipher(text,n,l,coordinates,dictionary)\t\t#Appelle fullDictionaryDecipher si texte chiffré\n else:\n fullDictionaryCipher(text,l,coordinates,dictionary)\t\t\t#Appelle fullDictionaryCipher si texte non chiffré\n\ndef displayDictionary(n,l,coordinates,dictionary):\t\t#Affiche le dictionnaire sous forme de vagues\n for i in range(n):\n for j in range(l):\n if (i,j) in dictionary:\n print(dictionary[i,j],end=\"\")\n else:\n print(\" \",end=\"\")\n print(\"\\n\")\n\ndef dictionaryToStringCipher(n,l,coordinates,dictionary):\t#Utilise le dictionnaire pour renvoyer le texte chiffré\n text = \"\"\n for i in range(n):\n for j in range(l):\n if (i,j) in dictionary:\n text += dictionary[i,j]\n return text\n\ndef dictionaryToStringDecipher(l,coordinates,dictionary):\t#Utilise le dictionnaire pour renvoyer un texte déchiffré\n text = \"\"\n for i in range(l):\n for j in range(n):\n if (j, i) in dictionary:\n text += dictionary[j,i]\n return text\n\ndef dictionaryToString(n,l,coordinates,dictionary,cipher):\n if cipher:\n return dictionaryToStringDecipher(l,coordinates,dictionary)\t\t#Appelle dictionaryToStringDecipher si texte chiffré\n else:\n return dictionaryToStringCipher(n,l,coordinates,dictionary)\t\t#Appelle dictionaryToStringDecipher si texte chiffré\n\ndef algorithm2(text,n,offset,cipher,display):\n fullDictionary(text,n,l,coordinates,dictionary,cipher)\t\t#Créé le dictionnaire en fonction du texte chiffré ou non\n text = dictionaryToString(n,l,coordinates,dictionary,cipher)\t#Stocke dans text le retour du dictionnaire\n if display:\n displayDictionary(n,l,coordinates,dictionary) #Affiche ou non le dictionnaire\n return text\n\ndef cipher(): #Demande si le texte est codé\n while True:\n cipher = input(\"Le texte est-il codé ? (y/n) \")\n if cipher == \"y\":\n cipher = True\n break\n elif cipher == \"n\":\n cipher = False\n break\n return cipher\n\ndef display(): #Demande si l'utilisateur veut afficher le dictionnaire\n while True:\n display = input(\"Voulez-vous afficher le dictionnaire ? (y/n) \")\n if display == \"y\":\n display = True\n break\n elif display == \"n\":\n display = False\n break\n return display\n\n#Début du programme\ntext = convertLetter(input(\"Entrez le texte : \"))\nl = len(text)\nwhile True:\n n = int(input(\"Entrez n : \"))\n offset = int(input(\"Entrez le offset : \"))\n if keyOK(n,offset):\n break\n else:\n print(\"La clé est invalide\")\n\ncipher = cipher() #Stocke dans cipher la valeur que l'utilisateur a répondu si texte chiffré ou non\ndisplay = display() #Stocke dans display la valeur que l'utilisateur a répondu si affichage du dictionnaire ou non\ncoordinates = computeCoordinates(n,l,offset) #Stocke dans coordinates les coordonnées des lettres en fonction de l'offset et de la taille\ndictionary = init(n,l,coordinates) #Initialise le dictionnaire\ntext = algorithm2(text,n,offset,cipher,display) #Utilise l'algorithme2 pour le chiffrage/déchiffrage\nprint(text)\n\n# HANHARYMTPTLAYNCIPSITTITNOWRIOEFHOAEALOWIDIIGTNOSATTNSDOATNSSOEGSHLEFTTAMTODAGGITHSGTIDYTGEETSSSTETMOILJINNWGSNIEEISNAISTKNUELIYSYENNAUAAEILGYLTMUGNMUOASOGRNBTENMGNSWFIRBAJIJMEIGHIOTR\n# n = 7\n# offset = 8\n# WATCHINGGIRLSGOPASSINGBYITAINTTHELATESTTHINGIMJUSTSTANDINGINADOORWAYIMJUSTTRYINGTOMAKESOMESENSEOUTOFTHESEGIRLSGOPASSINGBYTHETALESTHEYTELLOFMENIMNOTWAITINGONALADYIMJUSTWAITINGONAFRIEND\n\n# Je suis ton père\n# n = 6\n# offset = 9\n# ERJSEEUPINSOT","sub_path":"DEUXIEME ALGORITHME.py","file_name":"DEUXIEME ALGORITHME.py","file_ext":"py","file_size_in_byte":6369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"51766551","text":"horizontalPiece = \" ---\"\nverticalPieceLead = \"| \"\nverticalPieceTrail = \" | \"\nlineBreak = \"\\n\"\nplayer1Turn = True\nplayer2Turn = False\nturnCount = 1\nplayer1Winner = False\nplayer2Winner = False\np1WinCondition = bool\np2WinCondition = bool\n\ngameBoard = [[\"*\", \"*\", \"*\",], [\"*\", \"*\", \"*\"], [\"*\", \"*\", \"*\"]]\n\ndef didplayer1win(gameBoard, p1WinCondition):\n\tif gameBoard[0][0] == \"X\" and gameBoard[1][0] == \"X\" and gameBoard[2][0] == \"X\":\n\t\tp1WinCondition = True\n\telif gameBoard[0][1] == \"X\" and gameBoard[1][1] == \"X\" and gameBoard[2][1] == \"X\":\n\t\tp1WinCondition = True\n\telif gameBoard[0][2] == \"X\" and gameBoard[1][2] == \"X\" and gameBoard[2][2] == \"X\":\n\t\tp1WinCondition = True\n\telif gameBoard[0][0] == \"X\" and gameBoard[0][1] == \"X\" and gameBoard[0][2] == \"X\":\n\t\tp1WinCondition = True\n\telif gameBoard[1][0] == \"X\" and gameBoard[1][1] == \"X\" and gameBoard[1][2] == \"X\":\n\t\tp1WinCondition = True\n\telif gameBoard[2][0] == \"X\" and gameBoard[2][1] == \"X\" and gameBoard[2][2] == \"X\":\n\t\tp1WinCondition = True\n\telif gameBoard[0][0] == \"X\" and gameBoard[1][1] == \"X\" and gameBoard[2][2] == \"X\":\n\t\tp1WinCondition = True\n\telif gameBoard[0][2] == \"X\" and gameBoard[1][1] == \"X\" and gameBoard[2][0] == \"X\":\n\t\tp1WinCondition = True\n\telse:\n\t\tp1WinCondition = False\n\treturn p1WinCondition;\n\ndef didplayer2win(gameBoard, p2WinCondition):\n\tif gameBoard[0][0] == \"O\" and gameBoard[1][0] == \"O\" and gameBoard[2][0] == \"O\":\n\t\tp2WinCondition = True\n\telif gameBoard[0][1] == \"O\" and gameBoard[1][1] == \"O\" and gameBoard[2][1] == \"O\":\n\t\tp2WinCondition = True\n\telif gameBoard[0][2] == \"O\" and gameBoard[1][2] == \"O\" and gameBoard[2][2] == \"O\":\n\t\tp2WinCondition = True\n\telif gameBoard[0][0] == \"O\" and gameBoard[0][1] == \"O\" and gameBoard[0][2] == \"O\":\n\t\tp2WinCondition = True\n\telif gameBoard[1][0] == \"O\" and gameBoard[1][1] == \"O\" and gameBoard[1][2] == \"O\":\n\t\tp2WinCondition = True\n\telif gameBoard[2][0] == \"O\" and gameBoard[2][1] == \"O\" and gameBoard[2][2] == \"O\":\n\t\tp2WinCondition = True\n\telif gameBoard[0][0] == \"O\" and gameBoard[1][1] == \"O\" and gameBoard[2][2] == \"O\":\n\t\tp2WinCondition = True\n\telif gameBoard[0][2] == \"O\" and gameBoard[1][1] == \"O\" and gameBoard[2][0] == \"O\":\n\t\tp2WinCondition = True\n\telse: \n\t\tp2WinCondition = False\n\treturn p2WinCondition;\n\n\n\nprint((3 * horizontalPiece) + lineBreak + verticalPieceLead + str(gameBoard[0][0]) + verticalPieceTrail + str(gameBoard[0][1]) + verticalPieceTrail + str(gameBoard[0][2]) + verticalPieceTrail \\\n\t+ lineBreak + (3 * horizontalPiece) + lineBreak + verticalPieceLead + str(gameBoard[1][0]) + verticalPieceTrail + str(gameBoard[1][1]) + verticalPieceTrail + str(gameBoard[1][2]) + verticalPieceTrail \\\n\t+ lineBreak + (3 * horizontalPiece) + lineBreak + verticalPieceLead + str(gameBoard[2][0]) + verticalPieceTrail + str(gameBoard[2][1]) + verticalPieceTrail + str(gameBoard[2][2]) + verticalPieceTrail \\\n\t+ lineBreak + (3 * horizontalPiece))\n\nprint(\"\\nLets play tic-tac-toe! Place marks by entering co-ordinates as 'row,column'\\n(eg. 1,3 would place a mark in the top right)\")\n\n\nwhile turnCount <= 9 and player1Winner == False and player2Winner == False:\n\tif player2Turn == True and player1Winner == False and player2Winner == False:\n\t\tplayer2Input = input(\"Player 2, please place your 'O': \")\n\t\tplayer2InputList = player2Input.split(\",\")\n\t\tplayer2Row = int(player2InputList[0]) - 1\n\t\tplayer2Column = int(player2InputList[1]) - 1\n\t\tif player2Row <= 2 and player2Column <=2:\n\t\t\tif gameBoard[player2Row][player2Column] == \"*\":\n\t\t\t\tgameBoard[player2Row][player2Column] = \"O\"\n\t\t\t\tturnCount+=1\n\t\t\t\tplayer2Turn = False\n\t\t\t\tplayer1Turn = True\n\t\t\t\tprint((3 * horizontalPiece) + lineBreak + verticalPieceLead + str(gameBoard[0][0]) + verticalPieceTrail + str(gameBoard[0][1]) + verticalPieceTrail + str(gameBoard[0][2]) + verticalPieceTrail \\\n\t\t\t\t\t+ lineBreak + (3 * horizontalPiece) + lineBreak + verticalPieceLead + str(gameBoard[1][0]) + verticalPieceTrail + str(gameBoard[1][1]) + verticalPieceTrail + str(gameBoard[1][2]) + verticalPieceTrail \\\n\t\t\t\t\t+ lineBreak + (3 * horizontalPiece) + lineBreak + verticalPieceLead + str(gameBoard[2][0]) + verticalPieceTrail + str(gameBoard[2][1]) + verticalPieceTrail + str(gameBoard[2][2]) + verticalPieceTrail \\\n\t\t\t\t\t+ lineBreak + (3 * horizontalPiece))\n\t\t\t\tplayer2Winner = didplayer2win(gameBoard, p2WinCondition)\t\t\t\t\t\n\t\t\telse:\n\t\t\t\tprint(\"There is already a mark there. Pick another spot\")\n\t\telse:\n\t\t\tprint(\"That co-ordinate is not on the board. Try again.\")\n\t\t\t\n\telif player1Turn == True and player1Winner == False and player2Winner == False:\n\t\tplayer1Input = input(\"Player 1, please place your 'X': \")\n\t\tplayer1InputList = player1Input.split(\",\")\n\t\tplayer1Row = int(player1InputList[0]) - 1\n\t\tplayer1Column = int(player1InputList[1]) - 1\n\t\tif player1Row <= 2 and player1Column <= 2:\n\t\t\tif gameBoard[player1Row][player1Column] == \"*\":\n\t\t\t\tgameBoard[player1Row][player1Column] = \"X\"\n\t\t\t\tturnCount+=1\n\t\t\t\tplayer1Turn = False\n\t\t\t\tplayer2Turn = True\n\t\t\t\tprint((3 * horizontalPiece) + lineBreak + verticalPieceLead + str(gameBoard[0][0]) + verticalPieceTrail + str(gameBoard[0][1]) + verticalPieceTrail + str(gameBoard[0][2]) + verticalPieceTrail \\\n\t\t\t\t\t+ lineBreak + (3 * horizontalPiece) + lineBreak + verticalPieceLead + str(gameBoard[1][0]) + verticalPieceTrail + str(gameBoard[1][1]) + verticalPieceTrail + str(gameBoard[1][2]) + verticalPieceTrail \\\n\t\t\t\t\t+ lineBreak + (3 * horizontalPiece) + lineBreak + verticalPieceLead + str(gameBoard[2][0]) + verticalPieceTrail + str(gameBoard[2][1]) + verticalPieceTrail + str(gameBoard[2][2]) + verticalPieceTrail \\\n\t\t\t\t\t+ lineBreak + (3 * horizontalPiece))\n\t\t\t\tplayer1Winner = didplayer1win(gameBoard, p2WinCondition)\n\t\t\telse:\n\t\t\t\tprint(\"There is already a mark there. Pick another spot\")\n\t\telse:\n\t\t\tprint(\"That co-ordinate is not on the board\")\n\nif player1Winner == True:\n\tprint(\"Player 1 has won the game\")\nelif player2Winner == True:\n\tprint(\"Player 2 has won the game\")\nelse:\n\tprint(\"The game is a tie\")\n\n","sub_path":"Beginner-Python/Tic Tac Toe/TicTacToeFork.py","file_name":"TicTacToeFork.py","file_ext":"py","file_size_in_byte":5920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"207181000","text":"from tkinter.constants import RIGHT\nfrom typing import List\nimport PySimpleGUI as sg\nfrom PySimpleGUI.PySimpleGUI import WINDOW_CLOSED\n\nclass Calculator:\n __value: str\n __value_stack: List\n __for_reset: bool\n\n def __init__(self) -> None:\n self.__button_reset()\n\n def __str__(self) -> str:\n return self.__value\n\n def button_press(self, event):\n if event in ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'):\n self.__button_digit(event)\n elif event == '.':\n self.__button_comma()\n elif event == 'CE':\n self.__button_reset()\n elif event == '+/-':\n self.__button_sign()\n elif event in ('+', '-', '*', '/', '%'):\n self.__button_operator(event)\n elif event == '=':\n self.__calculate_value_stack()\n\n def __button_comma(self):\n if not '.' in self.__value:\n self.__value += '.'\n \n def __button_digit(self, input):\n if self.__value == '0' or self.__for_reset:\n self.__value = input\n else:\n self.__value += input\n self.__for_reset = False\n \n def __button_sign(self):\n if float(self.__value) > 0:\n self.__value = '-' + self.__value\n else:\n self.__value = self.__value[1:]\n\n def __button_operator(self, operator):\n self.__calculate_value_stack()\n self.__value_stack.append(self.__value)\n self.__value_stack.append(operator)\n self.__for_reset = True\n \n def __calculate_value_stack(self):\n self.__value_stack.append(self.__value)\n if len(self.__value_stack) >= 3:\n value2 = self.__value_stack.pop()\n operator = self.__value_stack.pop()\n value1 = self.__value_stack.pop()\n\n if operator == '+':\n self.__value_stack.append(f'{float(value1) + float(value2)}')\n elif operator == '-':\n self.__value_stack.append(f'{float(value1) - float(value2)}')\n elif operator == '*':\n self.__value_stack.append(f'{float(value1) * float(value2)}')\n elif operator == '/':\n self.__value_stack.append(f'{float(value1) / float(value2)}')\n elif operator == '%':\n self.__value_stack.append(f'{(float(value1)/100) * float(value2)}')\n\n self.__value = self.__value_stack.pop()\n \n def __button_reset(self):\n self.__value = '0'\n self.__value_stack = []\n self.__for_reset = False\n\ndef main():\n calculator = Calculator()\n\n layout = [\n [sg.Text('Calculator 1.0 PySimpeGUI')],\n [sg.Column([[sg.Text(calculator, key='-INPUT-', size=(23, 1), background_color='#FFF', text_color='#000', justification=RIGHT)]])],\n [sg.Column([[sg.Button('CE', size=(4, 2)), sg.Button('+/-', size=(4, 2)), sg.Button('%', size=(4, 2)), sg.Button('/', size=(4, 2))]])],\n [sg.Column([[sg.Button('7', size=(4, 2)), sg.Button('8', size=(4, 2)), sg.Button('9', size=(4, 2)), sg.Button('*', size=(4, 2))]])],\n [sg.Column([[sg.Button('4', size=(4, 2)), sg.Button('5', size=(4, 2)), sg.Button('6', size=(4, 2)), sg.Button('-', size=(4, 2))]])],\n [sg.Column([[sg.Button('1', size=(4, 2)), sg.Button('2', size=(4, 2)), sg.Button('3', size=(4, 2)), sg.Button('+', size=(4, 2))]])],\n [sg.Column([[sg.Button('0', size=(4, 2)), sg.Button('.', size=(4, 2)), sg.Button('=', size=(4, 2))]], element_justification=RIGHT)]\n ]\n\n window = sg.Window('Calculator', layout, size=(235, 350))\n\n while True:\n event, values = window.read()\n if event == WINDOW_CLOSED:\n break\n \n calculator.button_press(event)\n window['-INPUT-'].update(calculator)\n\n window.close()\n\nif __name__ == '__main__':\n main()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"575300840","text":"import random\nimport classes\nimport pygame\n\n#--------------------\n\npygame.init()\nclock = pygame.time.Clock()\n\nplay = True\n\n#Loop for repeated play\n\nwhile play:\n\n # Variables\n\n score = 0\n s_w = 500\n s_h = 750\n i_w = 50\n i_h = 50\n half = s_h/2\n score = 0\n lvl = 0\n interval = 50\n counter = 0\n difficulty = 10\n more = False\n\n\n # Screen/background details\n\n screen = pygame.display.set_mode((s_w, s_h))\n pygame.display.set_caption(\"Monkey Jump\")\n\n font1 = pygame.font.Font(None, 50)\n font2 = pygame.font.Font(None, 32)\n\n background = pygame.image.load(\"images/bg.png\")\n\n game = True\n\n\n player = classes.Character(s_w,s_h,i_w,i_h)\n platforms = []\n\n # Create initial platforms\n\n for y in range(0, 700, interval):\n x = random.randint(0, s_w - 60)\n p = classes.Platforms(x, y,difficulty)\n platforms.append(p)\n\n # Main game loop\n\n while game:\n clock.tick(40)\n screen.fill((62,128,0))\n\n # Create background grid(51,102,0)\n for i in range(0,750,15):\n pygame.draw.line(screen,(51,102,0),(0,i),(s_w,i))\n for i in range(0,500,15):\n pygame.draw.line(screen,(51,102,0),(i,0),(i,s_h))\n\n # Basic event calling (62,128,0)\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n game = False\n play = False\n\n\n keys = pygame.key.get_pressed()\n player.motion(keys,s_w,s_h,half)\n\n # Testing collision between player and platforms\n\n for p in platforms:\n if p.type == 2:\n p.rectangle.move_ip(p.vx, 0)\n if p.rectangle.x >= s_w - 60:\n p.vx *= -1\n if p.rectangle.x <= 0:\n p.vx *= -1\n\n p.display(screen)\n\n # Testing collision between player and platforms\n\n if player.rectangle.colliderect(p.rectangle):\n if player.gravity and (player.rectangle.bottom - 20) <= p.rectangle.y and not p.hide \\\n and player.rectangle.bottom <= s_h:\n if p.type == 1:\n p.hide = True\n else:\n player.jump = 20\n player.gravity = 0\n\n\n # Shifting the platform\n # Generating more platforms\n\n if player.shift > 0:\n score += player.shift\n lvl += player.shift\n for p in platforms:\n p.rectangle.move_ip(0, player.shift)\n counter += player.shift\n if counter > interval:\n for y in range(-interval, counter-interval, interval):\n x = random.randint(0, s_w - 80)\n p = classes.Platforms(x, y, difficulty)\n platforms.append(p)\n if p.type == 1:\n more = True\n while more:\n x = random.randint(0, s_w - 80)\n #if x not in range(p.rectangle.left -80, p.rectangle.right+20) and x <= s_w - 70:\n if (x >= p.rectangle.x + 80 or x <= p.rectangle.x -80) and x <= s_w - 70:\n p = classes.Platforms(x , y-20, difficulty)\n if p.type == 3:\n more = False\n platforms.append(p)\n counter -= interval\n player.shift = 0\n\n # Increasing difficulty\n\n if lvl >= 2000:\n lvl = 0\n if interval < 200:\n difficulty += 5\n interval += 10\n\n\n # Displaying on screen\n\n text = font2.render(str(score), True, (77,40,0))\n screen.blit(text, (420,20))\n player.display(screen)\n pygame.display.flip()\n\n # Test if game over\n\n if player.rectangle.y >= s_h:\n loop = True\n game = False\n\n # Game over screen\n\n while loop:\n screen.fill((0, 0, 0))\n text = font1.render('Game Over!', True, (255, 255, 255))\n text2 = font1.render('Score: ' + str(score), True, (255, 255, 255))\n screen.blit(text, (150,300))\n screen.blit(text2, (150,400))\n pygame.display.flip()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n loop = False\n play = False\n\n if event.type == pygame.MOUSEBUTTONDOWN or event.type == pygame.KEYDOWN:\n loop = False\n\npygame.quit()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"141916019","text":"from simplemostmeals.celery import app\nfrom django.conf import settings\n\nfrom gitlab_logging.helpers import GitlabIssuesHelper\n\n@app.task\ndef task_log_gitlab_issue_open(issue_title, issue_content, trace_raw):\n \"\"\"\n Proceed the issue opening task\n \"\"\"\n gl = GitlabIssuesHelper.gitlab()\n\n print(\"Opening issue: %s...\" % issue_title)\n gitlab_issue_labels = \"\"\n gitlab_issue_title_prefix = \"\"\n # New Feature: Allows configuration of assigning a\n # prefix to issues created with this module.\n if hasattr(settings, 'GITLAB_ISSUE_TITLE_PREFIX'):\n gitlab_issue_title_prefix = settings.GITLAB_ISSUE_TITLE_PREFIX\n\n issue_title = gitlab_issue_title_prefix + issue_title\n\n if hasattr(settings,'GITLAB_ISSUE_LABELS'):\n gitlab_issue_labels = settings.GITLAB_ISSUE_LABELS\n\n # Create issue with python-gitlab\n response = gl.project_issues.create({\n 'title': issue_title,\n 'description': issue_content,\n 'labels': gitlab_issue_labels\n }, project_id=settings.GITLAB_PROJECT_ID)\n\n if response:\n issue_id = response.id\n\n if issue_id:\n print(\"Issue opened: %s [ID: %s]\" % (issue_title, issue_id))\n\n GitlabIssuesHelper.store_issue(trace_raw, settings.GITLAB_PROJECT_ID, response.id)\n else:\n print(\"Issue could not be opened: %s\" % issue_title)\n\n\n@app.task\ndef task_log_gitlab_issue_reopen(issue_id):\n \"\"\"\n Proceed the issue re-opening task\n \"\"\"\n print(\"Re-opening issue [ID: %s]\" % issue_id)\n\n gl = GitlabIssuesHelper.gitlab()\n\n # Update issue with python-gitlab\n issue = gl.project_issues.get(issue_id, project_id=settings.GITLAB_PROJECT_ID)\n\n issue.state_event = 'reopen'\n response = issue.save()\n\n if response:\n print(\"Issue re-opened [ID: %s]\" % response.id)\n else:\n print(\"Issue could not be re-opened [ID: %s]\" % issue_id)\n","sub_path":"gitlab_logging/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"447742713","text":"import re\r\nimport pandas as pd\r\nimport sys\r\nimport serial\r\nimport glob\r\nfrom PyQt5 import QtCore, QtGui, QtWidgets, uic\r\nfrom datetime import datetime as Date\r\n\r\nimport time\r\nimport matplotlib\r\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\r\nfrom matplotlib.figure import Figure\r\nmatplotlib.use('QT5Agg')\r\n\r\nisRecord = False\r\nconnectionStatus = False\r\n\r\n\r\nclass MplCanvas(FigureCanvas):\r\n\r\n def __init__(self, parent=None, width=5, height=4, dpi=100):\r\n fig = Figure(figsize=(width, height), dpi=dpi)\r\n self.axes = fig.add_subplot(111)\r\n self.axes.set_ylim(bottom=-1, top=1)\r\n super(MplCanvas, self).__init__(fig)\r\n\r\n\r\nclass ConnectSerial(QtCore.QObject):\r\n end = QtCore.pyqtSignal()\r\n\r\n def __init__(self, serial):\r\n super().__init__()\r\n self.ser = serial\r\n\r\n def run(self):\r\n self.ser.open()\r\n start_time = Date.now()\r\n\r\n confirmString = ''\r\n global connectionStatus\r\n connectionStatus = True\r\n while not '.c.' in confirmString:\r\n if (self.ser.inWaiting() > 0):\r\n confirmString += self.ser.read(1).decode('utf-8')\r\n time_delta = Date.now() - start_time\r\n if time_delta.total_seconds() >= 5:\r\n connectionStatus = False\r\n break\r\n self.end.emit()\r\n\r\n\r\nclass Worker(QtCore.QObject):\r\n finished = QtCore.pyqtSignal()\r\n progress = QtCore.pyqtSignal(str, Date)\r\n updatePlot = QtCore.pyqtSignal(str)\r\n\r\n def __init__(self, serial):\r\n super().__init__()\r\n self.ser = serial\r\n\r\n def run(self):\r\n global isRecord\r\n data = \"\"\r\n self.ser.flushInput()\r\n self.ser.flushOutput()\r\n while (isRecord):\r\n if (self.ser.isOpen() and self.ser.inWaiting() > 0):\r\n data = self.ser.readline().decode('utf-8')\r\n if ('.s.' in data):\r\n isRecord = False\r\n break\r\n stripData = data.rstrip(\"\\r\\n\")\r\n self.progress.emit(stripData, Date.now())\r\n self.updatePlot.emit(stripData)\r\n self.finished.emit()\r\n\r\n\r\nclass MyWindow(QtWidgets.QMainWindow):\r\n def __init__(self):\r\n super(MyWindow, self).__init__()\r\n uic.loadUi(\"resource/mainQt.ui\", self)\r\n\r\n # test data\r\n self.canvas = MplCanvas(self, width=10, height=8, dpi=100)\r\n self.lay = QtWidgets.QVBoxLayout(self.content_plot)\r\n self.lay.addWidget(self.canvas)\r\n self.initialGraph()\r\n\r\n # set default variable\r\n self.csv_log = pd.DataFrame(columns=['No', 'Value', 'Time', 'Date'])\r\n self.setToleranceValue()\r\n self.previousTime = Date.now()\r\n\r\n self.ser = serial.Serial()\r\n\r\n # setup callback function\r\n self.scanBtn.clicked.connect(self.scanClick)\r\n self.connectBtn.clicked.connect(self.connectClick)\r\n self.disconnectBtn.clicked.connect(self.disconnectClick)\r\n self.comboPort.currentTextChanged.connect(self.comboPortChange)\r\n self.comboBaudRate.currentTextChanged.connect(self.comboBaudRateChange)\r\n self.startBtn.clicked.connect(self.startClick)\r\n self.stopBtn.clicked.connect(self.stopClick)\r\n self.clearBtn.clicked.connect(self.clearClick)\r\n self.exportBtn.clicked.connect(self.exportClick)\r\n self.inputPd.returnPressed.connect(self.insertPicthDiameter)\r\n self.inputGearTeeth.returnPressed.connect(self.insertGearTeeth)\r\n self.inputFi.returnPressed.connect(self.insertRadialComposite)\r\n self.input_fi.returnPressed.connect(self.insertToothToTooth)\r\n self.inputFr.returnPressed.connect(self.insertRunoutError)\r\n\r\n def initialGraph(self):\r\n n_data = 60\r\n self.x_angles = list(range(n_data))\r\n self.y_values = [0.0 for i in range(n_data)]\r\n self._plot_ref = None\r\n self.update_plot(0.0)\r\n\r\n def update_plot(self, getData):\r\n self.y_values = self.y_values[1:] + [float(getData)]\r\n if (self._plot_ref is None):\r\n plot_refs = self.canvas.axes.plot(\r\n self.x_angles, self.y_values, 'r')\r\n self._plot_ref = plot_refs[0]\r\n else:\r\n self._plot_ref.set_ydata(self.y_values)\r\n self.canvas.draw()\r\n\r\n def addDataTable(self, data, datetime):\r\n rowPosition = self.tableData.rowCount()\r\n self.tableData.insertRow(rowPosition)\r\n\r\n self.tableData.setItem(\r\n rowPosition, 0, QtWidgets.QTableWidgetItem(data))\r\n self.tableData.setItem(\r\n rowPosition, 1, QtWidgets.QTableWidgetItem(datetime.strftime('%H:%M:%S')))\r\n self.tableData.setItem(\r\n rowPosition, 2, QtWidgets.QTableWidgetItem(datetime.strftime('%d/%m/%Y')))\r\n self.tableData.scrollToBottom()\r\n\r\n fdata = float(data)\r\n\r\n self.maximumData = fdata if fdata > self.maximumData else self.maximumData\r\n self.minimumData = fdata if fdata < self.minimumData else self.minimumData\r\n self.sumData = round(self.sumData + fdata, 2)\r\n self.fiTotResult.setText('{:.3f}'.format(self.maximumData))\r\n self.fiResult.setText('{:.3f}'.format(\r\n self.maximumData-self.minimumData))\r\n self.frResult.setText('{:.3f}'.format(\r\n self.sumData/float(self.tableData.rowCount())))\r\n\r\n def scanClick(self):\r\n portlist = self.getComPort()\r\n if (len(portlist) > 0):\r\n self.comboPort.addItems(portlist)\r\n else:\r\n self.errorPopup('Warning !!!', 'Com port not detected')\r\n\r\n def serialConnected(self):\r\n if (connectionStatus):\r\n self.iconStatus.setPixmap(\r\n QtGui.QPixmap('resource/images/Green.png'))\r\n self.labelStatus.setText('Status : Connected')\r\n self.setToleranceValue()\r\n self.fiResult.setText('0.000')\r\n self.fiTotResult.setText('0.000')\r\n self.frResult.setText('0.000')\r\n self.scanBtn.setEnabled(False)\r\n self.disconnectBtn.setEnabled(True)\r\n self.startBtn.setEnabled(True)\r\n else:\r\n self.ser.close()\r\n self.connectBtn.setEnabled(True)\r\n self.errorPopup('Connection fail!!!', 'Request time-out')\r\n QtWidgets.QApplication.restoreOverrideCursor()\r\n\r\n def connectClick(self):\r\n QtWidgets.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)\r\n self.connectBtn.setEnabled(False)\r\n # initial thread\r\n self.threadConnect = QtCore.QThread()\r\n self.connectSerial = ConnectSerial(self.ser)\r\n self.connectSerial.moveToThread(self.threadConnect)\r\n\r\n self.threadConnect.started.connect(self.connectSerial.run)\r\n self.connectSerial.end.connect(self.threadConnect.quit)\r\n self.connectSerial.end.connect(self.connectSerial.deleteLater)\r\n self.threadConnect.finished.connect(self.threadConnect.deleteLater)\r\n\r\n # start thread\r\n self.threadConnect.start()\r\n\r\n self.threadConnect.finished.connect(self.serialConnected)\r\n\r\n def disconnectClick(self):\r\n self.iconStatus.setPixmap(QtGui.QPixmap('resource/images/Red.png'))\r\n self.disconnectBtn.setEnabled(False)\r\n self.ser.close()\r\n while self.ser.isOpen():\r\n pass\r\n self.labelStatus.setText('Status : Disconnect')\r\n self.connectBtn.setEnabled(True)\r\n self.scanBtn.setEnabled(True)\r\n self.startBtn.setEnabled(False)\r\n if (isRecord):\r\n self.stopClick()\r\n\r\n def comboPortChange(self):\r\n self.ser.port = self.comboPort.currentText()\r\n self.comboBaudRate.clear()\r\n self.comboBaudRate.addItems(['300', '1200', '2400', '4800', '9600', '19200', '38400', '57600',\r\n '74880', '115200', '230400', '250000', '500000', '1000000', '2000000'])\r\n self.comboBaudRate.setCurrentIndex(4)\r\n self.connectBtn.setEnabled(True)\r\n\r\n def comboBaudRateChange(self):\r\n self.ser.baudrate = int(self.comboBaudRate.currentText())\r\n\r\n def startClick(self):\r\n self.clearClick()\r\n self.inputGearTeeth.setDisabled(True)\r\n if ('Waiting..' not in self.gearTeethResult.text()):\r\n self.motor_pulse = round(self.gearTeethValue * 30240 / (55*360))\r\n command = 'setTeeth {}\\n'.format(self.motor_pulse)\r\n self.ser.write(bytes(command, encoding='utf-8'))\r\n # initial thread\r\n self.thread = QtCore.QThread()\r\n self.worker = Worker(self.ser)\r\n self.worker.moveToThread(self.thread)\r\n\r\n self.thread.started.connect(self.worker.run)\r\n self.worker.finished.connect(self.thread.quit)\r\n self.worker.finished.connect(self.worker.deleteLater)\r\n self.thread.finished.connect(self.thread.deleteLater)\r\n self.worker.progress.connect(self.addDataTable)\r\n self.worker.updatePlot.connect(self.update_plot)\r\n\r\n # start thread\r\n self.ser.write(b'start\\n')\r\n time.sleep(.1)\r\n global isRecord\r\n isRecord = True\r\n self.thread.start()\r\n\r\n # Final resets\r\n self.recordIconStatus.setPixmap(\r\n QtGui.QPixmap('resource/images/Green.png'))\r\n self.startBtn.setEnabled(False)\r\n self.stopBtn.setEnabled(True)\r\n self.thread.finished.connect(self.stopClick)\r\n\r\n def stopClick(self):\r\n self.ser.write(b'stop\\n')\r\n self.recordIconStatus.setPixmap(\r\n QtGui.QPixmap('resource/images/Red.png'))\r\n self.startBtn.setEnabled(True)\r\n self.stopBtn.setEnabled(False)\r\n self.inputGearTeeth.setDisabled(False)\r\n\r\n def clearClick(self):\r\n self.setToleranceValue()\r\n self.fiResult.setText('0.000')\r\n self.fiTotResult.setText('0.000')\r\n self.frResult.setText('0.000')\r\n self.tableData.setRowCount(0)\r\n n_data = 60\r\n self.x_angles = list(range(n_data))\r\n self.y_values = [0.0 for i in range(n_data)]\r\n self.update_plot(0.0)\r\n\r\n def exportClick(self):\r\n rowCount = self.tableData.rowCount()\r\n columnCount = self.tableData.columnCount()\r\n for row in range(rowCount):\r\n rowData = [row+1]\r\n for column in range(columnCount):\r\n rowData.append(self.tableData.item(row, column).text(\r\n ) if column != 0 else float(self.tableData.item(row, column).text()))\r\n self.csv_log.loc[row] = rowData\r\n pathName = QtWidgets.QFileDialog.getSaveFileName(\r\n self, 'Choose location to save csv file', filter=\"CSV Files (*.csv)\")\r\n if (pathName[1] != ''):\r\n resultPath = pathName[0][:pathName[0].rfind('.')] + '.csv'\r\n self.csv_log.to_csv(\r\n resultPath, index=False, header=True)\r\n\r\n def insertPicthDiameter(self):\r\n if (checkFloat(self.inputPd.text())):\r\n self.pdValue = float(self.inputPd.text())\r\n self.pdResult.setText(str(self.pdValue))\r\n self.inputPd.clear()\r\n\r\n def setToleranceValue(self, maximun=-8192.00, minimun=8192.00, summary=0.00):\r\n self.maximumData = maximun\r\n self.minimumData = minimun\r\n self.sumData = summary\r\n\r\n def insertGearTeeth(self):\r\n if (checkFloat(self.inputGearTeeth.text())):\r\n self.gearTeethValue = float(self.inputGearTeeth.text())\r\n self.gearTeethResult.setText(str(self.gearTeethValue))\r\n self.inputGearTeeth.clear()\r\n if (self.ser.is_open):\r\n self.motor_pulse = round(self.gearTeethValue * 30240 / (55*360))\r\n command = 'setTeeth {}\\n'.format(self.motor_pulse)\r\n self.ser.write(bytes(command, encoding='utf-8'))\r\n\r\n\r\n def insertRadialComposite(self):\r\n if (checkFloat(self.inputFi.text())):\r\n self.fiValue = float(self.inputFi.text())\r\n self.fiRef.setText(str(self.fiValue))\r\n self.inputFi.clear()\r\n\r\n def insertToothToTooth(self):\r\n if (checkFloat(self.input_fi.text())):\r\n self.fiTotValue = float(self.input_fi.text())\r\n self.fiTotRef.setText(str(self.fiTotValue))\r\n self.input_fi.clear()\r\n\r\n def insertRunoutError(self):\r\n if (checkFloat(self.inputFr.text())):\r\n self.frValue = float(self.inputFr.text())\r\n self.frRef.setText(str(self.frValue))\r\n self.inputFr.clear()\r\n\r\n def errorPopup(self, title, text):\r\n error_dialog = QtWidgets.QMessageBox()\r\n error_dialog.setIcon(QtWidgets.QMessageBox.Critical)\r\n error_dialog.setWindowTitle(title)\r\n error_dialog.setText(text)\r\n error_dialog.setStandardButtons(QtWidgets.QMessageBox.Ok)\r\n\r\n error_dialog.exec_()\r\n\r\n def getComPort(self):\r\n if sys.platform.startswith('win'):\r\n ports = ['COM%s' % (i + 1) for i in range(256)]\r\n elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):\r\n # this excludes your current terminal \"/dev/tty\"\r\n ports = glob.glob('/dev/tty[A-Za-z]*')\r\n elif sys.platform.startswith('darwin'):\r\n ports = glob.glob('/dev/tty.*')\r\n else:\r\n self.errorPopup('Error !!!', 'Unsupported platform')\r\n raise EnvironmentError('Unsupported platform')\r\n\r\n result = []\r\n for port in ports:\r\n try:\r\n s = serial.Serial(port)\r\n s.close()\r\n result.append(port)\r\n except (OSError, serial.SerialException):\r\n pass\r\n return result\r\n\r\n\r\ndef checkFloat(inputData):\r\n return re.search(r'^[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)$', inputData)\r\n\r\n\r\nif __name__ == '__main__':\r\n try:\r\n app = QtWidgets.QApplication(sys.argv)\r\n window = MyWindow()\r\n window.show()\r\n sys.exit(app.exec_())\r\n except Exception as err:\r\n print(err)\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":13972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"562260643","text":"import json\nimport multiprocessing\nimport random\nimport string\nfrom functools import partial\n\nimport os\nfrom os import listdir\nfrom os.path import isfile, join\nimport matplotlib.pyplot as plt\n\nfrom utils import DataLabel\n\n\nclass DataSetHandler(object):\n def __init__(self, store_images=False):\n self.train = DataLabel()\n self.test = DataLabel()\n self.val = DataLabel()\n self.amt_classes = None\n self.classes_name = None\n self.width = 100\n self.dpi = 50\n self.store_images = store_images\n self.input_path = join(os.getcwd(), 'data', 'ndjson')\n self.output_path = join(os.getcwd(), 'data', 'quick_draw_images')\n\n def build_data_set(self):\n files = [file for file in listdir(self.input_path) if isfile(join(self.input_path, file))\n and file != '.gitignore']\n for index, file in enumerate(files):\n self.build_one_class_dataset(file)\n\n def build_one_class_dataset(self, file):\n amt_train_images = 10000\n amt_test_images = 1000\n amt_val_images = 1000\n amt_tot = amt_train_images + amt_test_images + amt_val_images\n\n file_name = os.path.splitext(file)[0]\n class_name = file_name.split('_')[-1]\n\n path = join(self.output_path, class_name)\n if os.path.exists(path):\n return\n\n os.mkdir(path)\n\n drawings_strokes = []\n with open(os.path.join(self.input_path, file)) as f:\n for line_index, line in enumerate(f):\n threshold = 2 * amt_tot\n if line_index >= threshold:\n break\n json_line = json.loads(line)\n drawings_strokes.append(json_line['drawing'])\n\n pool = multiprocessing.Pool(processes=4)\n func = partial(self.strokes_to_ndarray, class_name)\n pool.map(func, drawings_strokes)\n pool.close()\n pool.join()\n\n def strokes_to_ndarray(self, class_name, strokes):\n fig = plt.figure(\n figsize=(self.width / self.dpi, self.width / self.dpi), dpi=self.dpi, frameon=False)\n ax = plt.Axes(fig, [0., 0., 1., 1.])\n ax.set_axis_off()\n fig.add_axes(ax)\n for stroke in strokes:\n x = stroke[0]\n y = stroke[1]\n plt.plot(x, y, c='k')\n\n plt.gca().invert_yaxis()\n path = join(self.output_path, class_name)\n file_name = ''.join(random.choices(string.ascii_letters + string.digits, k=16))\n plt.savefig(os.path.join(path, file_name), bbox_inches='tight', pad_inches=0, dpi=self.dpi)\n plt.close()\n return\n","sub_path":"quickdrawdatasethandler.py","file_name":"quickdrawdatasethandler.py","file_ext":"py","file_size_in_byte":2626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"80871366","text":"import pandas as pd\nimport numpy as np\nfrom numpy import *\ndef sigmoid(X):\n return (1.0 / (1 + exp(-X)))\ndef list_add(A,B):\n ret = []\n for i in range(len(A)):\n ret.append(A[i]+B[i])\n return ret\ndef list_div(A,B):\n ret = []\n for i in range(len(A)):\n if(B[i]!=0):\n ret.append(A[i]/B[i])\n else:\n ret.append(1)\n return ret\ndef list_mean(A):\n sum = 0;\n for i in range(len(A)):\n sum += A[i]\n return sum/len(A)\n\nclass Logistic_Regression:\n def __init__(self, max_iter):\n self.max_iter = max_iter;\n return\n\n\n def train(self, alpha, X, y):\n self.w = np.zeros(X.shape[1])\n self.alpha = alpha\n GD = np.zeros(X.shape[1])\n predicted_y = np.zeros(X.shape[0])\n error = np.zeros(X.shape[0])\n for _ in range(self.max_iter):\n #print(X.shape,\" \",self.w.shape)\n predicted_y = sigmoid(np.dot(X , self.w))\n #print(y.shape,\" \", predicted_y.shape)\n error = y - predicted_y\n GD = np.dot(X.transpose() , error)\n #print(GD.shape)\n self.w = self.w + self.alpha * GD\n return\n\n def predict(self, X):\n return np.dot(X , self.w)\n\n print(len(TP), len(FP), len(FN), len(TN))\nclass Multi_class:\n def __init__(self, class_num, max_iter, X, Y):\n self.class_num = class_num\n self.X = X\n self.Y = Y\n self.model = []\n self.max_iter = max_iter\n for i in range(self.class_num):\n self.model.append(Logistic_Regression(self.max_iter)) \n return\n\n def train(self, alpha):\n self.alpha = alpha\n for i in range(self.class_num):\n y = np.copy(self.Y)\n for j in range(len(y)):\n if(y[j]==i+1):\n y[j] = 1\n else:\n y[j] = 0\n self.model[i].train(self.alpha, self.X, y )\n return\n\n def predict(self, X):\n #print(X)\n y = np.zeros(X.shape[0])\n for i in range(len(X)):\n predicted = []\n for j in range(self.class_num):\n predicted.append(self.model[j].predict(X.iloc[i]))\n y[i] = (predicted.index(max(predicted)) + 1)\n return y\n \n def evaluate(self, X, Y):\n TP = []\n FP = []\n FN = []\n TN = []\n for i in range(self.class_num):\n TP_counter = 0\n FP_counter = 0\n FN_counter = 0\n TN_counter = 0\n y = self.model[i].predict(X)\n for j in range(len(Y)):\n if(Y[j]==i+1 and y[j]>=0.5):\n TP_counter = TP_counter + 1\n if(Y[j]!=i+1 and y[j]>=0.5):\n FP_counter = FP_counter + 1\n if(Y[j]==i+1 and y[j]<0.5):\n FN_counter = FN_counter + 1\n if(Y[j]!=i+1 and y[j]<0.5):\n TN_counter = TN_counter + 1\n if(TP_counter + FN_counter == 0):\n print(i+1)\n TP.append(TP_counter)\n FP.append(FP_counter)\n FN.append(FN_counter)\n TN.append(TN_counter)\n #print(TP)\n #print(FP)\n #print(FN)\n #print(TN)\n P = list_div(TP, list_add(TP,FP) )\n R = list_div(TP, list_add(TP,FN) )\n macro_P = list_mean(P)\n macro_R = list_mean(R)\n macro_F1 = (2 * macro_P * macro_R) / (macro_P + macro_R)\n micro_P = list_mean(TP) / (list_mean(TP) + list_mean(FP))\n micro_R = list_mean(TP) / (list_mean(TP) + list_mean(FN))\n micro_F1 = 2 * micro_P * micro_R / (micro_P + micro_R)\n print(\"micro Precission = \", micro_P)\n print(\"micro Recall = \", micro_R)\n print(\"micro F1 = \", micro_F1)\n print(\"macro Precission = \", macro_P)\n print(\"macro Recall = \", macro_R)\n print(\"macro F1 = \", macro_F1)\n return\n\n\ndef accuracy(y1, y2):\n counter = 0\n for i in range(len(y1)):\n if(y1[i] == y2[i]):\n counter = counter + 1\n return counter/len(y1)\ndef Standardlization(train, test):\n for i in range(train.shape[1]):\n mymean = train.iloc[:, i].mean()\n mystd = train.iloc[:, i].std()\n train.iloc[:, i] = (train.iloc[:, i] - mymean) / ( mystd )\n test.iloc[:, i]= (test.iloc[:, i] - mymean) / ( mystd)\n return [train, test]\n\n \nif __name__==\"__main__\":\n df_train = pd.read_csv(\"train_set.csv\")\n df_test = pd.read_csv(\"test_set.csv\")\n #print(df.shape)\n #print(df_train.iloc[0])\n X_train = df_train.iloc[ : , 0:16 ]\n Y_train = df_train.iloc[ : , 16]\n\n X_test = df_test.iloc[ : , 0:16 ]\n Y_test = df_test.iloc[ : , 16]\n\n [X_train, X_test] = Standardlization(X_train, X_test)\n X_train.insert(16, \"b\", 1)\n X_test.insert(16, \"b\", 1)\n #print(X_train)\n #X_train = np.c_[X_train, np.ones(X_train.shape[0])]\n #X_test = np.c_[X_test, np.ones(X_test.shape[0])]\n #print(X_train[0])\n #print(X_train.iloc[0])\n \n max_acc = 0\n best_alpha = 0\n best_iter = 0\n for j in range(1,21): \n for i in range(1,200):\n model = Multi_class(26, j*200, X_train, Y_train)\n model.train(i/100)\n results = model.predict(X_test)\n acc = accuracy(Y_test, results)\n if(acc>max_acc):\n max_acc = acc\n best_alpha = i/100\n best_iter = j*200\n\n print(max_acc, \" \", best_alpha, \" \", best_iter)\n model = Multi_class(26,3000, X_train, Y_train)\n model.train(0.1)\n results = model.predict(X_test)\n print(\"accuracy = \",accuracy(Y_test, results))\n model.evaluate(X_test, Y_test)\n\n","sub_path":"tmp/LR_main.py","file_name":"LR_main.py","file_ext":"py","file_size_in_byte":5686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"243712927","text":"\"\"\"ArcFaceHead, ArcFaceModel & MultiLabelArcFaceModel with TensorFlow\"\"\"\n\n\nfrom typing import Any, Callable, Dict, Iterable, Tuple, Union\nimport tensorflow as tf\n\n\n# TODO: check L2 normalization axes for ArcFace x + kernel\nclass ArcFaceHead(tf.keras.layers.Layer):\n \"\"\"ArcFace head for modified-cross entropy computation.\"\"\"\n\n def __init__(\n self,\n n_classes: int,\n scale: float = 30,\n margin: float = 0.5,\n return_logits: bool = True,\n kernel_initializer: Union[str, Callable] = \"glorot_uniform\",\n kernel_regularizer: Union[str, Callable] = None,\n kernel_constraint: Union[str, Callable] = None,\n **kwargs,\n ):\n super().__init__(**kwargs)\n self.n_classes = n_classes\n self.scale = scale\n self.margin = margin\n self._return_logits = return_logits\n\n self._reshape_target = False\n\n self.kernel_initializer = tf.keras.initializers.get(kernel_initializer)\n self.kernel_regularizer = tf.keras.regularizers.get(kernel_regularizer)\n self.kernel_constraint = tf.keras.constraints.get(kernel_constraint)\n\n def build(self, input_shape: Iterable[tf.TensorShape]):\n feature_shape = tf.TensorShape(input_shape[0])\n if len(feature_shape) != 2:\n raise ValueError(\"Input tensor must have shape (BATCH_SIZE, FEATURE_DIM)\")\n\n feature_dim = feature_shape[-1]\n\n target_shape = tf.TensorShape(input_shape[-1])\n if len(target_shape) > 2:\n raise ValueError(\n \"\"\"Valid input shapes include (BATCH_SIZE, FEATURE_DIM), (BATCH_SIZE,) \n or (BATCH_SIZE, 1)\n \"\"\"\n )\n elif len(target_shape) == 2:\n if target_shape[-1] != self.n_classes:\n self._reshape_target = True\n else: # case len(target_shape) = 1\n self._reshape_target = True\n\n self.kernel = self.add_weight(\n name=\"kernel\",\n shape=[feature_dim, self.n_classes],\n initializer=self.kernel_initializer,\n regularizer=self.kernel_regularizer,\n constraint=self.kernel_constraint,\n trainable=True,\n )\n super().build(input_shape)\n\n def call(self, inputs: Iterable[tf.Tensor]) -> tf.Tensor:\n x, y = inputs\n\n if self._reshape_target:\n y = tf.one_hot(y, depth=self.n_classes)\n\n # L2 Normalization\n x = tf.math.l2_normalize(x, axis=1) # (B, D)\n kernel = tf.math.l2_normalize(self.kernel, axis=0) # (D, n_classes)\n\n # Get angle then compute ArcFace logit\n cosinus = tf.einsum(\"ab,bc->ac\", x, kernel) # (B, n_classes)\n angles = tf.math.acos(cosinus)\n logits = self.scale * tf.cos(self.margin * y + angles)\n\n if self._return_logits:\n return logits\n\n return tf.nn.softmax(logits)\n\n def get_config(self) -> Dict[str, Any]:\n config = super().get_config()\n config.update(\n {\n \"n_classes\": self.n_classes,\n \"scale\": self.scale,\n \"margin\": self.margin,\n \"return_logits\": self._return_logits,\n \"kernel_initializer\": tf.keras.initializers.serialize(\n self.kernel_initializer\n ),\n \"kernel_regularizer\": tf.keras.regularizers.serialize(\n self.kernel_regularizer\n ),\n \"kernel_constraint\": tf.keras.constraints.serialize(\n self.kernel_constraint\n ),\n }\n )\n return config\n\n @classmethod\n def from_config(cls, config: Dict[str, Any]):\n config[\"kernel_initializer\"] = tf.keras.initializers.deserialize(\n config[\"kernel_initializer\"]\n )\n config[\"kernel_regularizer\"] = tf.keras.regularizers.deserialize(\n config[\"kernel_regularizer\"]\n )\n config[\"kernel_constraint\"] = tf.keras.constraints.deserialize(\n config[\"kernel_constraint\"]\n )\n return cls(**config)\n\n\nclass ArcFaceModel(tf.keras.Model):\n \"\"\"General ArcFace model, encapsulates any backbone model.\"\"\"\n\n def __init__(\n self,\n backbone: tf.keras.Model,\n n_classes: int,\n scale: float = 30,\n margin: float = 0.5,\n return_logits: bool = True,\n **kwargs,\n ):\n super().__init__(**kwargs)\n self.backbone = backbone\n\n self.n_classes = n_classes\n self.scale = scale\n self.margin = margin\n self.return_logits = return_logits\n\n self.arcface = ArcFaceHead(\n n_classes=self.n_classes,\n scale=self.scale,\n margin=self.margin,\n return_logits=self.return_logits,\n )\n\n def call(\n self,\n inputs: Union[tf.Tensor, Tuple[tf.Tensor]],\n training: bool = None,\n arcface_output: bool = False,\n mask: tf.Tensor = None,\n ) -> tf.Tensor:\n if training or arcface_output:\n x, y = inputs\n x = self.backbone(x, training, mask)\n\n return self.arcface((x, y))\n\n return self.backbone(inputs, training, mask)\n\n def compile(\n self,\n optimizer: Callable,\n metrics: Iterable[Callable] = None,\n loss_weights: Union[Iterable[float], Dict[str, float]] = None,\n weighted_metrics: Iterable[Callable] = None,\n run_eagerly: bool = None,\n steps_per_execution: int = None,\n jit_compile: bool = None,\n **kwargs,\n ):\n loss = tf.keras.losses.CategoricalCrossentropy(\n from_logits=self.from_logits, name=\"arcface_categorical_crossentropy\"\n )\n super().compile(\n optimizer=optimizer,\n loss=loss,\n metrics=metrics,\n loss_weights=loss_weights,\n weighted_metrics=weighted_metrics,\n run_eagerly=run_eagerly,\n steps_per_execution=steps_per_execution,\n jit_compile=jit_compile,\n **kwargs,\n )\n\n def test_step(self, data):\n x, y, sample_weight = tf.keras.utils.unpack_x_y_sample_weight(data)\n\n # y_pred = self.arcface((self.backbone(x, training=False), y))\n y_pred = self((x, y), training=False, arcface_output=True)\n # Updates stateful loss metrics.\n self.compute_loss(x, y, y_pred, sample_weight)\n return self.compute_metrics(x, y, y_pred, sample_weight)\n\n def train_step(self, data: Iterable[tf.Tensor]) -> Dict[str, tf.Tensor]:\n # x has shape (B, H, W, C) or (B, C, H, W)\n # y has shape (B,) or (B, 1) or (B, n_classes)\n x, y, sample_weight = tf.keras.utils.unpack_x_y_sample_weight(data)\n\n # Forward pass\n with tf.GradientTape() as tape:\n y_pred = self((x, y), training=True)\n loss = self.compute_loss(x, y, y_pred, sample_weight)\n self._validate_target_and_loss(y, loss)\n\n # Backpropagation: backwards pass\n self.optimizer.minimize(loss, self.trainable_variables, tape=tape)\n return self.compute_metrics(x, y, y_pred, sample_weight)\n\n def get_config(self, backbone_serialize: Callable = None) -> Dict[str, Any]:\n config = super().get_config()\n\n if (backbone_serialize is not None) and callable(backbone_serialize):\n backbone_config = backbone_serialize(self.backbone)\n config[\"backbone\"] = backbone_config\n else:\n config[\"backbone\"] = None\n print(\n \"\"\"Valid callable `backbone_serialize` arg is missing, you won't be able\n to create back this ArcFaceModel instance from the output config\n and `from_config` class method.\n \"\"\"\n )\n\n config.update(\n {\n \"n_classes\": self.n_classes,\n \"scale\": self.scale,\n \"margin\": self.margin,\n \"return_logits\": self.return_logits,\n }\n )\n return config\n\n @classmethod\n def from_config(cls, config: Dict[str, Any], backbone_deserialize: Callable = None):\n if callable(backbone_deserialize) and (\n config.get(\"backbone\", None) is not None\n ):\n config[\"backbone\"] = backbone_deserialize(config[\"backbone\"])\n return cls(**config)\n else:\n print(\n \"\"\"Valid callable `backbone_deserialize` arg is needed to instantiate\n an ArcFaceModel with this config.\"\"\"\n )\n\n\nclass MultiLabelArcFaceModel(tf.keras.Model):\n \"\"\"Multi-label ArcFace model, inspired from GrokNet. For more details, see:\n `GrokNet: Unified Computer Vision Model Trunk and Embeddings For Commerce`.\n \"\"\"\n\n def __init__(\n self,\n backbone: tf.keras.Model,\n n_classes_mapping: Dict[str, int],\n scale: float = 30,\n margin: float = 0.5,\n return_logits: bool = True,\n **kwargs,\n ):\n super().__init__(**kwargs)\n self.backbone = backbone\n\n if isinstance(n_classes_mapping, dict):\n self.n_classes_mapping = n_classes_mapping\n else:\n raise TypeError(\n \"\"\"`n_classes_mapping` must be a dict with output names as keys \n and the numbers of classes as values for each output label.\n \"\"\"\n )\n\n self.scale = scale\n self.margin = margin\n self.return_logits = return_logits\n\n for output in self.n_classes_mapping:\n setattr(\n self,\n f\"{output}_arcface\",\n ArcFaceHead(\n n_classes=self.n_classes_mapping[output],\n scale=self.scale,\n margin=self.margin,\n return_logits=self.return_logits,\n name=f\"{output}_arcface\",\n ),\n )\n\n def call(\n self,\n inputs: tf.Tensor,\n training: bool = None,\n arcface_output: bool = False,\n mask: tf.Tensor = None,\n ) -> tf.Tensor:\n if training or arcface_output:\n x, y = inputs\n\n if not isinstance(y, dict):\n raise ValueError(\n \"\"\"`y_pred` should be a dict mapping of valid output names and tensors\n \"\"\"\n )\n else:\n x = self.backbone(x, training, mask)\n outputs = {\n output: getattr(self, f\"{output}_arcface\")((x, y[output]))\n for output in self.n_classes_mapping\n }\n return outputs\n\n return self.backbone(inputs, training, mask)\n\n def compile(\n self,\n optimizer: Callable,\n metrics: Iterable[Callable] = None,\n loss_weights: Union[Iterable[float], Dict[str, float]] = None,\n weighted_metrics: Iterable[Callable] = None,\n run_eagerly: bool = None,\n steps_per_execution: int = None,\n jit_compile: bool = None,\n **kwargs,\n ):\n losses = {\n output: tf.keras.losses.CategoricalCrossentropy(\n from_logits=self.from_logits,\n name=f\"{output}_arcface_categorical_crossentropy\",\n )\n for output in self.n_classes_mapping\n }\n\n if isinstance(loss_weights, dict):\n weights = {\n output: loss_weights.get(output, 1.0)\n for output in self.n_classes_mapping\n }\n\n super().compile(\n optimizer=optimizer,\n loss=losses,\n metrics=metrics,\n loss_weights=weights,\n weighted_metrics=weighted_metrics,\n run_eagerly=run_eagerly,\n steps_per_execution=steps_per_execution,\n jit_compile=jit_compile,\n **kwargs,\n )\n\n def test_step(self, data):\n x, y, sample_weight = tf.keras.utils.unpack_x_y_sample_weight(data)\n\n # y_pred = self.arcface((self.backbone(x, training=False), y))\n y_pred = self((x, y), training=False, arcface_output=True)\n # Updates stateful loss metrics.\n self.compute_loss(x, y, y_pred, sample_weight)\n return self.compute_metrics(x, y, y_pred, sample_weight)\n\n def train_step(self, data: Iterable[tf.Tensor]) -> Dict[str, tf.Tensor]:\n # x has shape (B, H, W, C) or (B, C, H, W)\n # y has shape (B,) or (B, 1) or (B, n_classes)\n x, y, sample_weight = tf.keras.utils.unpack_x_y_sample_weight(data)\n\n # Forward pass\n with tf.GradientTape() as tape:\n y_pred = self((x, y), training=True)\n loss = self.compute_loss(x, y, y_pred, sample_weight)\n self._validate_target_and_loss(y, loss)\n\n # Backpropagation: backwards pass\n self.optimizer.minimize(loss, self.trainable_variables, tape=tape)\n return self.compute_metrics(x, y, y_pred, sample_weight)\n\n def get_config(self, backbone_serialize: Callable = None) -> Dict[str, Any]:\n config = super().get_config()\n\n if (backbone_serialize is not None) and callable(backbone_serialize):\n backbone_config = backbone_serialize(self.backbone)\n config[\"backbone\"] = backbone_config\n else:\n config[\"backbone\"] = None\n print(\n \"\"\"Valid callable `backbone_serialize` arg is missing, you won't be able\n to create back this MultiLabelArcFaceModel instance from the output config\n and `from_config` class method.\n \"\"\"\n )\n\n config.update(\n {\n \"n_classes_mapping\": self.n_classes_mapping,\n \"scale\": self.scale,\n \"margin\": self.margin,\n \"return_logits\": self.return_logits,\n }\n )\n return config\n\n @classmethod\n def from_config(cls, config: Dict[str, Any], backbone_deserialize: Callable = None):\n if callable(backbone_deserialize) and (\n config.get(\"backbone\", None) is not None\n ):\n config[\"backbone\"] = backbone_deserialize(config[\"backbone\"])\n return cls(**config)\n else:\n print(\n \"\"\"Valid callable `backbone_deserialize` arg is needed to instantiate\n a MultiLabelArcFaceModel with this config.\"\"\"\n )\n","sub_path":"src/arcface.py","file_name":"arcface.py","file_ext":"py","file_size_in_byte":14416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"498633","text":"# coding:utf-8\nfrom __future__ import print_function\nimport os, re\nfrom lib.core.common import *\nfrom lib.core.ip.ip import *\nfrom subprocess import Popen, PIPE\n\n\n# 作者:咚咚呛\n# 配置安全类检测\n# 1、dns配置检测\n# 2、防火墙配置检测\n# 3、hosts配置检测\n\nclass Config_Analysis:\n def __init__(self):\n self.config_suspicious = []\n self.ip_re = r'(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'\n self.name = u'Config_Analysis'\n\n # 检测dns设置\n def check_dns(self):\n suspicious, malice = False, False\n try:\n if os.path.exists('/etc/resolv.conf'):\n shell_process = os.popen(\n 'cat /etc/resolv.conf 2>/dev/null| grep -E -o \"([0-9]{1,3}[\\.]){3}[0-9]{1,3}\"').read().splitlines()\n for ip in shell_process:\n if not check_ip(ip): continue\n if ip == '8.8.8.8': continue\n malice_result(self.name, u'DNS security configuration', u'/etc/resolv.conf', '', u'DNS setting oversea IP: %s' % ip,\n u'[1]cat /etc/resolv.conf', u'suspicious', programme=u'vi /etc/resolv.conf #delete or change DNS oversea setting')\n suspicious = True\n return suspicious, malice\n except:\n return suspicious, malice\n\n # 检测防火墙设置\n def check_iptables(self):\n suspicious, malice = False, False\n try:\n if not os.path.exists('/etc/sysconfig/iptables'): return suspicious, malice\n with open('/etc/sysconfig/iptables') as f:\n for line in f:\n if len(line) < 5: continue\n if line[0] != '#' and 'ACCEPT' in line:\n malice_result(self.name, u'firewall security configuration IPtable check', u'/etc/sysconfig/iptables', '',\n u'exist iptables ACCEPT rule: %s' % line, u'[1]cat /etc/sysconfig/iptables', u'suspicious',\n programme=u'vi /etc/sysconfig/iptables #delete or change ACCEPT setting')\n suspicious = True\n return suspicious, malice\n except:\n return suspicious, malice\n\n # 检测hosts配置信息\n def check_hosts(self):\n suspicious, malice = False, False\n try:\n if not os.path.exists(\"/etc/hosts\"): return suspicious, malice\n p1 = Popen(\"cat /etc/hosts 2>/dev/null\", stdout=PIPE, shell=True)\n p2 = Popen(\"awk '{print $1}'\", stdin=p1.stdout, stdout=PIPE, shell=True)\n for ip_info in p2.stdout.read().splitlines():\n if not re.search(self.ip_re, ip_info): continue\n if not check_ip(ip_info.strip().replace('\\n', '')): continue\n malice_result(self.name, u'HOSTS setting', u'/etc/hosts', '', u'exist oversea IP : %s' % ip_info,\n u'[1]cat /etc/hosts', u'suspicious', programme=u'vi /etc/hosts #delete or change oversea hosts setting')\n suspicious = True\n return suspicious, malice\n except:\n return suspicious, malice\n\n def run(self):\n print(u'\\n begin DNS Firewall hosts setting scan')\n file_write(u'\\n begin DNS Firewall hosts setting scan\\n')\n\n string_output(u' [1] DNS settig scan')\n suspicious, malice = self.check_dns()\n result_output_tag(suspicious, malice)\n\n string_output(u' [2] firewall setting scan ')\n suspicious, malice = self.check_iptables()\n result_output_tag(suspicious, malice)\n\n string_output(u' [3] hosts setting scan')\n suspicious, malice = self.check_hosts()\n result_output_tag(suspicious, malice)\n\n # 检测结果输出到文件\n result_output_file(self.name)\n\n\nif __name__ == '__main__':\n infos = Config_Analysis()\n infos.run()\n","sub_path":"lib/plugins/Config_Analysis.py","file_name":"Config_Analysis.py","file_ext":"py","file_size_in_byte":3952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"650628345","text":"import json\nimport logging\nimport lzma\nimport os\nimport pickle\nimport re\nfrom pathlib import Path\nfrom typing import Any, Mapping, List, Tuple, Dict\nfrom unittest import mock\n\nimport numpy\nfrom absl import logging as absl_logging\nfrom alphafold.model.features import FeatureDict\nfrom alphafold.model.model import RunModel\nfrom alphafold.model.tf import utils\n\nfrom colabfold.batch import run\nfrom colabfold.colabfold import run_mmseqs2\nfrom colabfold.download import download_alphafold_params\n\n# Copy the original method before mocking\noriginal_run_model = RunModel.predict\n\n\nclass MockRunModel:\n \"\"\"Mocks FeatureDict -> prediction\n\n msa_feat is a) large and b) has some variance between machines, so we ignore it\n \"\"\"\n\n known_inputs: List[Tuple[FeatureDict, Mapping[str, Any]]]\n fixtures: Path\n\n def __init__(self, fixtures: Path):\n self.fixtures = fixtures\n self.known_inputs = []\n for prediction_file in fixtures.glob(\"*/*_prediction_result.pkl.xz\"):\n input_fix_file = prediction_file.with_name(\n prediction_file.name.replace(\"prediction_result\", \"input_fix\")\n )\n with lzma.open(input_fix_file) as input_fix_fp, lzma.open(\n prediction_file, \"rb\"\n ) as prediction_fp:\n input_fix = pickle.load(input_fix_fp)\n self.known_inputs.append((input_fix, pickle.load(prediction_fp)))\n\n def predict(\n self, model_runner: RunModel, feat: FeatureDict\n ) -> Tuple[Mapping[str, Any], Tuple[Any, Any]]:\n \"\"\"feat[\"msa\"] or feat[\"msa_feat\"] for normal/complexes is non-deterministic, so we remove it before storing,\n but add it back before prediction or returning, as we need it for plotting\"\"\"\n is_complex = False\n if \"msa_feat\" in feat.keys():\n msa_feat = feat[\"msa_feat\"]\n # noinspection PyUnresolvedReferences\n del feat[\"msa_feat\"]\n elif \"msa\" in feat.keys():\n msa_feat = feat[\"msa\"]\n # noinspection PyUnresolvedReferences\n del feat[\"msa\"]\n is_complex = True\n else:\n raise AssertionError(\"neither msa nor msa_feat in feat\")\n\n for input_fix, prediction in self.known_inputs:\n try:\n numpy.testing.assert_equal(feat, input_fix)\n # TODO: Also mock (recycles,tol) from the patches\n if is_complex:\n # noinspection PyUnresolvedReferences\n feat[\"msa\"] = msa_feat\n else:\n # noinspection PyUnresolvedReferences\n feat[\"msa_feat\"] = msa_feat\n return prediction, (None, None)\n except AssertionError:\n continue\n\n if os.environ.get(\"UPDATE_SNAPSHOTS\"):\n print(\"Running new prediction\")\n # This is real hacky and you'll have to rename the stuff yourself, sorry\n counter = 0\n while self.fixtures.joinpath(str(counter)).is_dir():\n counter += 1\n folder = self.fixtures.joinpath(str(counter))\n folder.mkdir(exist_ok=True, parents=True)\n with lzma.open(folder.joinpath(f\"model_input_fix.pkl.xz\"), \"wb\") as fp:\n pickle.dump(feat, fp)\n # Put msa_feat back, we need it for the prediction\n if is_complex:\n # noinspection PyUnresolvedReferences\n feat[\"msa\"] = msa_feat\n else:\n # noinspection PyUnresolvedReferences\n feat[\"msa_feat\"] = msa_feat\n prediction, (_, _) = original_run_model(model_runner, feat)\n self.known_inputs.append((feat, prediction))\n with lzma.open(\n folder.joinpath(f\"model_prediction_result.pkl.xz\"), \"wb\"\n ) as fp:\n pickle.dump(prediction, fp)\n return prediction, (None, None)\n else:\n for input_fix, prediction in self.known_inputs:\n try:\n numpy.testing.assert_equal(feat, input_fix)\n return prediction, (None, None)\n except AssertionError as e:\n print(e)\n raise AssertionError(\"input not stored\")\n\n\ndef split_lines(x):\n \"\"\"Split each files into a list of lines\"\"\"\n if isinstance(x, list):\n return [split_lines(i) for i in x]\n elif isinstance(x, str):\n return x.splitlines()\n else:\n raise TypeError(f\"{type(x)} {str(x)[:20]}\")\n\n\ndef join_lines(x):\n \"\"\"Inverse of split_lines\"\"\"\n if all(isinstance(i, str) for i in x):\n return \"\\n\".join(x)\n elif all(isinstance(i, list) for i in x):\n return [join_lines(i) for i in x]\n else:\n raise TypeError(f\"{[type(i) for i in x]} {str(x)[:20]}\")\n\n\nclass MMseqs2Mock:\n \"\"\"Mocks out the call to the mmseqs2 api\n\n Each test has its own json file which contains the run_mmseqs2 input data in the\n config field and the saved response. To update responses or to add new tests,\n set the UPDATE_SNAPSHOTS env var (e.g. `UPDATE_SNAPSHOTS=1 pytest`\n \"\"\"\n\n data_file: Path\n saved_responses: List[Dict[str, Any]]\n\n def __init__(self, rootpath: Path, name: str):\n self.data_file = rootpath.joinpath(f\"test-data/mmseqs-api-reponses/{name}.json\")\n if os.environ.get(\"UPDATE_SNAPSHOTS\") and not self.data_file.is_file():\n self.data_file.write_text(\"[]\")\n with self.data_file.open() as fp:\n self.saved_responses = []\n for saved_response in json.load(fp):\n # Join lines we've split before\n response = join_lines(saved_response[\"response\"])\n self.saved_responses.append(\n {\"config\": saved_response[\"config\"], \"response\": response}\n )\n\n def mock_run_mmseqs2(\n self,\n query,\n prefix,\n use_env=True,\n use_filter=True,\n use_templates=False,\n filter=None,\n use_pairing=False,\n host_url=\"https://a3m.mmseqs.com\",\n ):\n assert prefix\n config = {\n \"query\": query,\n \"use_env\": use_env,\n \"use_filter\": use_filter,\n \"use_templates\": use_templates,\n \"filter\": filter,\n \"use_pairing\": use_pairing,\n }\n\n for saved_response in self.saved_responses:\n if saved_response[\"config\"] == config:\n return saved_response[\"response\"]\n\n if os.environ.get(\"UPDATE_SNAPSHOTS\"):\n print(f\"\\nrun_mmseqs2 with {config}\")\n response = run_mmseqs2(\n x=config[\"query\"],\n prefix=prefix,\n use_env=config[\"use_env\"],\n use_filter=config[\"use_filter\"],\n use_templates=config[\"use_templates\"],\n filter=config[\"filter\"],\n use_pairing=config[\"use_pairing\"],\n host_url=host_url,\n )\n # Split lines so we get a readable json file\n response = split_lines(response)\n self.saved_responses.append({\"config\": config, \"response\": response})\n self.data_file.write_text(json.dumps(self.saved_responses, indent=2))\n else:\n assert False, config\n\n\ndef prepare_prediction_test(caplog):\n caplog.set_level(logging.INFO)\n # otherwise jax will tell us about its search for devices\n absl_logging.set_verbosity(\"error\")\n # We'll also want to mock that out later\n download_alphafold_params(True)\n download_alphafold_params(False)\n # alphafold uses a method called `make_random_seed`, which deterministically starts with a seed\n # of zero and increases it by one for each protein. This means the input features would become\n # dependent on the number and order of tests. Here we just reset the seed to 0\n utils.seed_maker = utils.SeedMaker()\n\n\ndef test_batch(pytestconfig, caplog, tmp_path):\n prepare_prediction_test(caplog)\n\n queries = [(\"5AWL_1\", \"YYDPETGTWY\", None), (\"6A5J\", \"IKKILSKIKKLLK\", None)]\n\n mock_run_model = MockRunModel(pytestconfig.rootpath.joinpath(\"test-data/batch\"))\n mock_run_mmseqs = MMseqs2Mock(pytestconfig.rootpath, \"batch\").mock_run_mmseqs2\n with mock.patch(\n \"alphafold.model.model.RunModel.predict\",\n lambda model_runner, feat: mock_run_model.predict(model_runner, feat),\n ), mock.patch(\"colabfold.batch.run_mmseqs2\", mock_run_mmseqs):\n run(\n queries,\n tmp_path,\n use_templates=False,\n use_amber=False,\n msa_mode=\"MMseqs2 (UniRef+Environmental)\",\n num_models=1,\n num_recycles=3,\n model_order=[1, 2, 3, 4, 5],\n is_complex=False,\n keep_existing_results=False,\n rank_mode=\"auto\",\n pair_mode=\"unpaired+paired\",\n stop_at_score=100,\n )\n\n assert caplog.messages == [\n \"Found 5 citations for tools or databases\",\n \"Query 1/2: 5AWL_1 (length 10)\",\n \"Running model_1\",\n \"model_1 took 0.0s with pLDDT 94.2\",\n \"reranking models based on avg. predicted lDDT\",\n \"Query 2/2: 6A5J (length 13)\",\n \"Running model_1\",\n \"model_1 took 0.0s with pLDDT 90.8\",\n \"reranking models based on avg. predicted lDDT\",\n \"Done\",\n ]\n\n # Very simple test, it would be better to check coordinates\n assert (\n len(\n tmp_path.joinpath(\"5AWL_1_unrelaxed_model_1_rank_1.pdb\")\n .read_text()\n .splitlines()\n )\n == 96\n )\n assert (\n len(\n tmp_path.joinpath(\"6A5J_unrelaxed_model_1_rank_1.pdb\")\n .read_text()\n .splitlines()\n )\n == 112\n )\n assert tmp_path.joinpath(\"config.json\").is_file()\n\n\ndef test_single_sequence(pytestconfig, caplog, tmp_path):\n prepare_prediction_test(caplog)\n\n queries = [(\"5AWL_1\", \"YYDPETGTWY\", None)]\n\n mock_run_model = MockRunModel(pytestconfig.rootpath.joinpath(\"test-data/batch\"))\n mock_run_mmseqs = MMseqs2Mock(pytestconfig.rootpath, \"batch\").mock_run_mmseqs2\n with mock.patch(\n \"alphafold.model.model.RunModel.predict\",\n lambda model_runner, feat: mock_run_model.predict(model_runner, feat),\n ), mock.patch(\"colabfold.batch.run_mmseqs2\", mock_run_mmseqs):\n run(\n queries,\n tmp_path,\n use_templates=False,\n use_amber=False,\n msa_mode=\"single_sequence\",\n num_models=1,\n num_recycles=3,\n model_order=[1, 2, 3, 4, 5],\n is_complex=False,\n keep_existing_results=False,\n rank_mode=\"auto\",\n pair_mode=\"unpaired+paired\",\n stop_at_score=100,\n )\n\n assert caplog.messages == [\n \"Found 2 citations for tools or databases\",\n \"Query 1/1: 5AWL_1 (length 10)\",\n \"Running model_1\",\n \"model_1 took 0.0s with pLDDT 94.2\",\n \"reranking models based on avg. predicted lDDT\",\n \"Done\",\n ]\n\n # Very simple test, it would be better to check coordinates\n assert (\n len(\n tmp_path.joinpath(\"5AWL_1_unrelaxed_model_1_rank_1.pdb\")\n .read_text()\n .splitlines()\n )\n == 96\n )\n assert tmp_path.joinpath(\"config.json\").is_file()\n\n\ndef test_complex(pytestconfig, caplog, tmp_path):\n prepare_prediction_test(caplog)\n\n pdb_3g50_A = \"MRILPISTIKGKLNEFVDAVSSTQDQITITKNGAPAAVLVGADEWESLQETLYWLAQPGIRESIAEADADIASGRTYGEDEIRAEFGVPRRPH\"\n pdb_3g50_B = \"MPYTVRFTTTARRDLHKLPPRILAAVVEFAFGDLSREPLRVGKPLRRELAGTFSARRGTYRLLYRIDDEHTTVVILRVDHRADIYRR\"\n queries = [(\"3G5O_A_3G5O_B\", [pdb_3g50_A, pdb_3g50_B], None)]\n\n mock_run_model = MockRunModel(pytestconfig.rootpath.joinpath(\"test-data/complex\"))\n mock_run_mmseqs2 = MMseqs2Mock(pytestconfig.rootpath, \"complex\").mock_run_mmseqs2\n with mock.patch(\n \"alphafold.model.model.RunModel.predict\",\n lambda model_runner, feat: mock_run_model.predict(model_runner, feat),\n ), mock.patch(\"colabfold.batch.run_mmseqs2\", mock_run_mmseqs2):\n run(\n queries,\n tmp_path,\n use_templates=False,\n use_amber=False,\n msa_mode=\"MMseqs2 (UniRef+Environmental)\",\n num_models=1,\n num_recycles=3,\n model_order=[1, 2, 3, 4, 5],\n is_complex=True,\n keep_existing_results=False,\n rank_mode=\"auto\",\n pair_mode=\"unpaired+paired\",\n stop_at_score=100,\n )\n\n messages = list(caplog.messages)\n # noinspection PyUnresolvedReferences\n messages[3] = re.sub(r\"\\d+\\.\\d+s\", \"0.0s\", messages[3])\n assert messages == [\n \"Found 5 citations for tools or databases\",\n \"Query 1/1: 3G5O_A_3G5O_B (length 180)\",\n \"Running model_1\",\n \"model_1 took 0.0s with pLDDT 94.4\",\n \"reranking models based on avg. predicted lDDT\",\n \"Done\",\n ]\n\n\ndef test_complex_monomer(pytestconfig, caplog, tmp_path):\n prepare_prediction_test(caplog)\n\n A = \"PIAQIHILEGRSDEQKETLIREVSEAISRSLDAPLTSVRVIITEMAKGHFGIGGELASK\"\n queries = [(\"A_A\", [A, A], None)]\n\n mock_run_model = MockRunModel(\n pytestconfig.rootpath.joinpath(\"test-data/complex_monomer\")\n )\n mock_run_mmseqs2 = MMseqs2Mock(\n pytestconfig.rootpath, \"complex_monomer\"\n ).mock_run_mmseqs2\n with mock.patch(\n \"alphafold.model.model.RunModel.predict\",\n lambda model_runner, feat: mock_run_model.predict(model_runner, feat),\n ), mock.patch(\"colabfold.batch.run_mmseqs2\", mock_run_mmseqs2):\n run(\n queries,\n tmp_path,\n use_templates=False,\n use_amber=False,\n msa_mode=\"MMseqs2 (UniRef+Environmental)\",\n num_models=1,\n num_recycles=3,\n model_order=[1, 2, 3, 4, 5],\n is_complex=True,\n keep_existing_results=False,\n rank_mode=\"auto\",\n pair_mode=\"unpaired+paired\",\n stop_at_score=100,\n )\n\n messages = list(caplog.messages)\n # noinspection PyUnresolvedReferences\n messages[3] = re.sub(r\"\\d+\\.\\d+s\", \"0.0s\", messages[3])\n assert messages == [\n \"Found 5 citations for tools or databases\",\n \"Query 1/1: A_A (length 118)\",\n \"Running model_1\",\n \"model_1 took 0.0s with pLDDT 95.3\",\n \"reranking models based on avg. predicted lDDT\",\n \"Done\",\n ]\n","sub_path":"tests/test_colabfold.py","file_name":"test_colabfold.py","file_ext":"py","file_size_in_byte":14516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"246107312","text":"from setuptools import setup, find_packages\n\nimport universum\n\n\ndef readme():\n with open('README.md', encoding=\"utf-8\") as f:\n return f.read()\n\n\np4 = ('pip>=19', 'p4python>=2019.1')\n\ngit = 'gitpython>=3.0.5'\n\ngithub = (git, 'cryptography', 'pygithub')\n\nvcs = p4 + github\n\ndocs = ('sphinx', 'sphinx-argparse', 'sphinx_rtd_theme') # This extra is required for RTD to generate documentation\n\nsetup(\n name=universum.__title__,\n version=universum.__version__,\n description='Unifier of Continuous Integration',\n long_description=readme(),\n long_description_content_type='text/markdown',\n author='Ivan Keliukh , Kateryna Dovgan ',\n license='BSD',\n packages=find_packages(exclude=['tests', 'tests.*']),\n py_modules=['universum'],\n python_requires='>=3.6',\n install_requires=[\n 'glob2',\n 'requests',\n 'sh',\n 'lxml',\n 'typing-extensions',\n 'ansi2html',\n 'pyyaml==6.0'\n ],\n extras_require={\n 'p4': [p4],\n 'git': [git],\n 'github': [github],\n 'docs': [docs],\n 'test': [\n vcs,\n docs,\n 'docker',\n 'httpretty',\n 'mock',\n 'pytest',\n 'pylint',\n 'pytest-pylint',\n 'teamcity-messages',\n 'pytest-cov',\n 'coverage',\n 'mypy',\n 'types-requests',\n 'selenium==3.141',\n 'urllib3==1.26.15', # This is required for selenium-3.141 to work correctly\n 'types-PyYAML==6.0'\n ]\n },\n package_data={'': ['*.css', '*.js']}\n)\n\n\nif __name__ == \"__main__\":\n print(\"Please use 'sudo pip install .' instead of launching this script\")\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"547490576","text":"\"\"\"\n ODROID GO display\n\n https://github.com/loboris/MicroPython_ESP32_psRAM_LoBo/wiki/display\n\"\"\"\n\nimport sys\nimport time\n\nimport display\nimport machine\nimport odroidgo\nfrom machine import SPI, Pin\nfrom micropython import const\n\n\nclass Display(display.TFT):\n \"\"\"\n Expand loboris TFT class\n \"\"\"\n\n def __init__(self, **init_kwargs):\n super().__init__()\n\n try:\n self.init(**init_kwargs)\n except OSError as err:\n # e.g.: Error initializing display\n sys.print_exception(err)\n for i in range(3, 0, -1):\n print(\"Hard reset in %i Sek!\" % i)\n time.sleep(1)\n machine.reset()\n\n self.width, self.height = self.screensize()\n self.reset()\n\n def reset(self):\n self.resetwin() # Reset active display window to full screen size\n self.clear(self.BLACK)\n self.set_default_font()\n self.text(0, 0, \"\", self.BLACK)\n self.text_next_y=0\n\n def set_default_font(self):\n self.set_font(self.FONT_Default)\n\n def get_fonts(self):\n fonts = [(attr_name, getattr(self, attr_name)) for attr_name in dir(self) if attr_name.startswith(\"FONT_\")]\n fonts.sort(key=lambda i: i[1])\n return tuple(fonts)\n\n def set_font(self, font_id, rotate=0):\n self.font(font_id, rotate=rotate)\n self.font_width, self.font_height = self.fontSize()\n\n def print(self, text, align=0, color=None, transparent=False):\n if color is None:\n color = self.WHITE\n\n if self.text_next_y >= self.height:\n self.text_next_y = 0\n \n self.text(align, self.text_next_y, text, color, transparent=transparent)\n self.text_next_y = self.text_y() + self.font_height\n \n def echo(self, text, **kwargs):\n print(text)\n self.print(text)\n\n\nclass OdroidGoDisplay(Display):\n \"\"\"\n ODROID GO TFT\n\n usage e.g.:\n\n screen = OdroidGoDisplay()\n screen.print(\"All existing fonts:\", align=screen.CENTER, color=screen.CYAN)\n\n fonts = screen.get_fonts()\n for font_name, font_id in fonts:\n text = \"%i - %s\" % (font_id, font_name)\n print(text)\n screen.set_font(font_id)\n screen.print(text, transparent=True)\n\n screen.deinit()\n \"\"\"\n\n def __init__(self):\n super().__init__(\n type=self.ILI9341,\n width=odroidgo.TFT_WIDTH,\n height=odroidgo.TFT_HEIGHT,\n speed=odroidgo.TFT_SPEED,\n miso=odroidgo.TFT_MISO_PIN,\n mosi=odroidgo.TFT_MOSI_PIN,\n clk=odroidgo.TFT_SCLK_PIN,\n cs=odroidgo.TFT_CS_PIN,\n spihost=SPI.VSPI,\n dc=odroidgo.TFT_DC_PIN,\n bgr=True,\n rot=self.LANDSCAPE_FLIP,\n )\n\n\n# Display instance for global usage:\nscreen = OdroidGoDisplay()","sub_path":"odroidgo/screen.py","file_name":"screen.py","file_ext":"py","file_size_in_byte":2888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"594823404","text":"import setuptools\n\nwith open(\"README.md\", \"r\", encoding=\"utf-8\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name='from_ge_to_allure_mapper',\n version='0.0.1',\n author='Bogdan Volodarskiy',\n author_email='hesherus@gmail.com',\n description='Package for mapping test report format from Great Expectations to Allure',\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url='https://github.com/',\n license='MIT',\n packages=['from_ge_to_allure_mapper'],\n install_requires=['great_expectations'],\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"264676199","text":"import threading\r\nfrom threads import thrd\r\n\r\n\r\nclass Auto:\r\n\r\n\tdef __init__(self,missionFun,stopFun,missionArgs=None,stopArgs=None):\r\n\t\tself.stopAutoFlag=threading.Event()\t# For stopping the autonomous flight at any time\r\n\r\n\t\tself.missionFun=missionFun\r\n\t\tself.stopFun=stopFun\r\n\r\n\t\tif missionArgs!=None: self.missionArgs=missionArgs\r\n\t\tif stopArgs!=None: self.stopArgs=stopArgs\r\n\r\n\r\n\tdef fly(self):\r\n\t\t\r\n\t\tdef flyThrd():\r\n\t\t\twhile not self.stopAutoFlag.isSet():\r\n\t\t\t\ttry:\r\n\t\t\t\t\tself.missionArgs\r\n\t\t\t\texcept:\r\n\t\t\t\t\tself.missionFun\r\n\t\t\t\telse:\r\n\t\t\t\t\tself.missionFun(*self.missionArgs)\r\n\r\n\t\tflyClass=thrd(flyThrd)\r\n\t\tflyClass.name=\"flyClass\"\r\n\t\tflyClass.start()\r\n\r\n\r\n\tdef stop(self):\r\n\r\n\t\tdef stopThrd():\r\n\t\t\twhile not self.stopAutoFlag.isSet():\r\n\t\t\t\ttry:\r\n\t\t\t\t\tself.stopArgs\r\n\t\t\t\texcept:\r\n\t\t\t\t\tif self.stopFun: self.stopAutoFlag.set()\r\n\t\t\t\telse:\r\n\t\t\t\t\tif self.stopFun(self.stopArgs): self.stopAutoFlag.set()\r\n \r\n\t\tstopClass=thrd(stopThrd)\r\n\t\tstopClass.name=\"stopClass\"\r\n\t\tstopClass.start()\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"Dronekit/moveForward/auto.py","file_name":"auto.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"636745337","text":"#coding:utf-8\n\nfrom django.shortcuts import render\nfrom joygame.common import *\nfrom joygame.api import zabbix_query,aliyun_api,qcloud_api,aliyun_cdn\nfrom tasks import *\nfrom models import *\n\nBASE_DIR = os.path.abspath(os.path.dirname(__file__))\nyun_dir = os.path.join(os.path.dirname(BASE_DIR),\"static\")\n\n\n\n@login_required\n@juge_user\ndef faq(request):\n\tnav = \"文档记录\"\n\taction = request.GET.get(\"action\")\n\tlog = request.GET.get(\"log\")\n\tif action == \"query\":\n\t\ttag = request.GET.get(\"tag\")\n\t\tmenu = Faq_docment.objects.filter(tag__icontains=\"%s\"%tag)\n\telse:\n\t\tmenu = Faq_docment.objects.all()\n\treturn render_to_response(\"issue/faq.html\",locals(),context_instance=RequestContext(request))\n@login_required\n@juge_user\ndef add_faq(request):\n\tnav = \"文档记录\"\n\ttip = \"添加新文档\"\n\treturn render_to_response(\"issue/add_faq.html\",locals(),context_instance=RequestContext(request))\n@login_required\n@juge_user\ndef faq_process(request):\n\taction = request.GET.get(\"action\")\n\tif action == \"add\":\n\t\ttitle = request.POST.get(\"title\")\n\t\tcontent = request.POST.get(\"content\")\n\t\ttag = request.POST.get(\"tag\")\n\t\tusername = request.session[\"username\"]\n\t\tuser_id = User.objects.get(username=\"%s\"%username)\n\t\tif tag:\n\t\t\tobj,create = Faq_docment.objects.get_or_create(title=\"%s\"%title,content=\"%s\"%content,create_user=user_id,create_time=time.strftime(\"%Y-%m-%d %H:%M:%S\"),tag=\"%s\"%tag)\n\t\telse:\n\t\t\tobj,create = Faq_docment.objects.get_or_create(title=\"%s\"%title,content=\"%s\"%content,create_user=user_id,create_time=time.strftime(\"%Y-%m-%d %H:%M:%S\"))\n\t\tif create:\n\t\t\tobj.save()\n\t\tlog = \"添加成功\"\n\telif action == \"delete\":\n\t\tfaq_id = request.GET.get(\"id\")\n\t\tmenu = Faq_docment.objects.filter(id=int(faq_id))\n\t\tmenu.delete()\n\t\tlog = \"删除成功\"\n\telif action == \"edit\":\n\t\tnav = \"文档记录\"\n\t\ttip = \"编辑文档\"\n\t\tfaq_id = request.GET.get(\"id\")\n\t\tmenu = Faq_docment.objects.get(id=int(faq_id))\n\t\treturn render_to_response(\"issue/faq_edit.html\",locals(),context_instance=RequestContext(request))\n\telif action == \"update\":\n\t\tfaq_id = request.GET.get(\"id\")\n\t\ttitle = request.POST.get(\"title\")\n\t\tcontent = request.POST.get(\"content\")\n\t\ttag = request.POST.get(\"tag\")\n\t\tusername = request.session[\"username\"]\n\t\tuser_id = User.objects.get(username=\"%s\"%username)\n\t\tmenu = Faq_docment.objects.filter(id=int(faq_id))\n\t\tif tag:\n\t\t\tmenu.update(title=\"%s\"%title,content=\"%s\"%content,tag=\"%s\"%tag)\n\t\telse:\n\t\t\tmenu.update(title=\"%s\"%title,content=\"%s\"%content)\n\t\treturn HttpResponseRedirect(\"/issue/docment_history/faq_detail/?id=%s\"%faq_id)\n\treturn HttpResponseRedirect(\"/issue/docment_history/faq/?log=%s\"%log)\n@login_required\n@juge_user\ndef faq_detail(request):\n\tnav = \"文档记录\"\n\ttip = \"详细文档\"\n\tfaq_id = request.GET.get(\"id\")\n\tmenu = Faq_docment.objects.get(id=int(faq_id))\n\treturn render_to_response(\"issue/faq_detail.html\",locals(),context_instance=RequestContext(request))\n@login_required\n@juge_user\ndef add_like(request):\n\tfaq_id = request.GET.get(\"id\")\n\tlike_count = Faq_docment.objects.get(id=int(faq_id)).like\n\tmenu = Faq_docment.objects.filter(id=int(faq_id))\n\tif not like_count:\n\t\tlike_count = 0\n\tmenu.update(like=like_count+1)\n\treturn HttpResponse(json.dumps({\"like_count\":like_count+1}), content_type='application/json')\n\t","sub_path":"mysite/issue/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"493050582","text":"# Simple tests for an adder module\nimport cocotb\nfrom cocotb.triggers import Timer, RisingEdge, ReadOnly\nfrom cocotb.result import TestFailure\nfrom cocotb.drivers import BusDriver \nfrom adder_model import adder_model\nimport random\nfrom test_drv import test_drv\n\n\nclass test_drvTB(object):\n\tdef __init__(self, dut, debug=True):\n\t\tself.dut = dut\n\t\tself.test_in = test_drv(dut, \"\", dut.clock )\n\t\t#self.dut.log.info(\"test_drvTB init\")\n\n\t@cocotb.coroutine\n\tdef reset(self, duration=10000):\n\t\t#self.dut.log.debug(\"Resetting DUT\")\n\t\tself.dut.resetn <= 0\n\n\t\tyield Timer(duration)\n\t\tyield RisingEdge(self.dut.clock)\n\t\tself.dut.resetn <= 1\n\t\t#self.dut.log.debug(\"Out of reset\")\n\n\n@cocotb.test()\n#@cocotb.coroutine\ndef run_test(dut):\n\n\tcocotb.fork(clock_gen(dut.clock))\n\n\tyield RisingEdge(dut.clock)\n\ttb = test_drvTB(dut)\n\n\tyield tb.reset()\n\n\tfor i in range(5):\n\t\tyield tb.test_in.write(i,3,dut.clock)\n\t\tyield Timer(100)\n\n\tyield RisingEdge(dut.clock)\n\t#for i in range(5):\n\t#dut.log.info(\"DUT\")\n\n@cocotb.coroutine\ndef clock_gen(signal):\n\twhile True:\n\t\tsignal <= 0\n\t\tyield Timer(5000)\n\t\tsignal <= 1\n\t\tyield Timer(5000)\n\n\n","sub_path":"examples/test_a/tests/test_adder.py","file_name":"test_adder.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"77059239","text":"import pygame\nimport time\nimport random\n\n# intialise the pygame module\npygame.init()\n\ncrash_sound = pygame.mixer.Sound(\"Crash.wav\")\npygame.mixer.music.load(\"Jazz_In_Paris.wav\")\n\n# dynamic screen resolution\ndisplay_width = 800\ndisplay_height = 600\n\n# color definitions\nblack = (0,0,0)\nwhite = (255,255,255)\nblock_color = (53, 115, 255)\n\nred = (200,0,0)\ngreen = (0,200,0)\nblue = (0,0,255)\n\nbright_red = (255, 0,0)\nbright_green = (0,255,0)\n\ncar_width = 73\n\npause = False\n\n# creates a display / frame / window for the game\n# with single parameter (tuple of dimensions)\ngameDisplay = pygame.display.set_mode((display_width,display_height))\n# setting up the caption for the window\npygame.display.set_caption('A bit Racey')\n# setting clock of the game\nclock = pygame.time.Clock()\n\ncarImg = pygame.image.load('racecar.png')\n\n# setting up the icon of the game\npygame.display.set_icon(carImg)\n\ndef things_dodged(count):\n\tfont = pygame.font.SysFont('comicsansms', 25)\n\ttext = font.render(\"Dodged: \"+str(count), True, black)\n\tgameDisplay.blit(text, (0,0))\n\ndef things(thingx, thingy, thingw, thingh, color):\n\tpygame.draw.rect(gameDisplay, color, [thingx, thingy, thingw, thingh])\n\ndef car(x,y):\n\t# draws image on the window\n\tgameDisplay.blit(carImg, (x,y))\n\ndef text_objects(msg, font):\n\ttextSurface = font.render(msg, True, black)\n\treturn textSurface, textSurface.get_rect()\n\ndef message_display(msg):\n\tlargeText = pygame.font.SysFont('comicsansms', 115)\n\tTextSurf, TextRect = text_objects(msg, largeText)\n\tTextRect.center = ((display_width/2), (display_height/2))\n\tgameDisplay.blit(TextSurf, TextRect)\n\n\tpygame.display.update()\n\n\ttime.sleep(2)\n\tgame_loop()\n\ndef crash():\n\n\tpygame.mixer.music.stop()\n\tpygame.mixer.Sound.play(crash_sound)\n\n\tlargeText = pygame.font.SysFont('comicsansms', 115)\n\tTextSurf, TextRect = text_objects(\"You Crashed\", largeText)\n\tTextRect.center = ((display_width/2), (display_height/2))\n\tgameDisplay.blit(TextSurf, TextRect)\n\t\n\twhile True:\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\tpygame.quit()\n\t\t\t\tquit()\n\n\t\t# gameDisplay.fill(white)\n\n\t\tbutton(\"Play Again\",150,450,100,50,green,bright_green,game_loop)\n\t\tbutton(\"Quit\",550,450,100,50,red,bright_red,quitgame)\n\n\t\tpygame.display.update()\n\t\tclock.tick(15)\n\ndef quitgame():\n\tpygame.quit()\n\tquit()\n\ndef unpaused():\n\tglobal pause\n\tpygame.mixer.music.unpause()\n\tpause = False\n\ndef paused():\n\n\tpygame.mixer.music.pause()\n\n\tlargeText = pygame.font.SysFont('comicsansms', 115)\n\tTextSurf, TextRect = text_objects(\"Paused\", largeText)\n\tTextRect.center = ((display_width/2), (display_height/2))\n\tgameDisplay.blit(TextSurf, TextRect)\n\t\n\twhile pause:\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\tpygame.quit()\n\t\t\t\tquit()\n\n\t\t# gameDisplay.fill(white)\n\n\t\tbutton(\"Continue\",150,450,100,50,green,bright_green,unpaused)\n\t\tbutton(\"Quit\",550,450,100,50,red,bright_red,quitgame)\n\n\t\tpygame.display.update()\n\t\tclock.tick(15)\n\n# ic = inactive color, ac = active color\ndef button(msg,x,y,w,h,ic,ac, action=None):\n\tmouse = pygame.mouse.get_pos()\n\t# (l,m,r) = left, middle, right button click on mouse\n\tclick = pygame.mouse.get_pressed()\n\t# add buttons and interaction\n\t# lighten up the buttons\n\tif x+w>mouse[0]>x and y+h>mouse[1]>y:\n\t\tpygame.draw.rect(gameDisplay, ac, (x,y,w,h))\n\t\tif click[0] == 1 and action!=None:\n\t\t\taction()\n\telse:\n\t\tpygame.draw.rect(gameDisplay, ic, (x,y,w,h)) \n\n\t# text on button\n\tsmallText = pygame.font.SysFont('comicsansms',20)\n\ttextSurf, textRect = text_objects(msg,smallText)\n\ttextRect.center = (x+(w/2), y+(h/2))\n\tgameDisplay.blit(textSurf, textRect)\n\n\ndef game_intro():\n\tintro = True\n\twhile intro:\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\tpygame.quit()\n\t\t\t\tquit()\n\n\t\tgameDisplay.fill(white)\n\t\tlargeText = pygame.font.SysFont('comicsansms', 115)\n\t\tTextSurf, TextRect = text_objects(\"A Bit Racey\", largeText)\n\t\tTextRect.center = ((display_width/2), (display_height/2))\n\t\tgameDisplay.blit(TextSurf, TextRect)\n\n\t\tbutton(\"GO!\",150,450,100,50,green,bright_green,game_loop)\n\t\tbutton(\"Quit\",550,450,100,50,red,bright_red,quitgame)\n\n\t\tpygame.display.update()\n\t\tclock.tick(15)\n\n\ndef game_loop():\n\tglobal pause\n\n\tpygame.mixer.music.play(-1)\n\n\n\n\tx = display_width * 0.45\n\ty = display_height * 0.8\n\tx_change = 0\n\t\n\t# things' measurements\n\tthing_starty = -600\n\tthing_speed = 7\n\tthing_width = 100\n\tthing_height = 100\n\tthing_startx = random.randrange(0, (display_width-thing_width)//1)\n\n\t# score\n\tdodged = 0\n\tthing_count = 1\n\n\t# variable that handles the running and closing state of the game\n\tgame_exit = False\n\n\t# GAME LOOP\n\twhile not game_exit:\n\t\t# pygame.event.get() gives the list of all the events that occured per frame per second\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\tgame_exit = True\n\t\t\t\tpygame.quit()\n\t\t\t\tquit()\n\n\t\t\t# key is pressed\n\t\t\tif event.type == pygame.KEYDOWN:\n\t\t\t\tif event.key == pygame.K_LEFT:\n\t\t\t\t\tx_change = -5\n\t\t\t\tif event.key == pygame.K_RIGHT:\n\t\t\t\t\tx_change = 5\n\t\t\t\tif event.key == pygame.K_p:\n\t\t\t\t\tpause = True\n\t\t\t\t\tpaused()\n\n\n\t\t\t# key is released\n\t\t\tif event.type == pygame.KEYUP:\n\t\t\t\tif event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:\n\t\t\t\t\tx_change = 0\n\n\t\tx += x_change\n\n\t\t# fills the window with white\n\t\tgameDisplay.fill(white)\n\n\t\t# things generation\n\t\tthings(thing_startx, thing_starty, thing_width, thing_height, block_color)\n\t\tthing_starty += thing_speed\n\t\tcar(x,y)\n\t\tthings_dodged(dodged)\n\n\t\tif x>display_width-car_width or x<0:\n\t\t\tcrash()\n\n\t\t# to create a new thing as soon as one goes out of the window\n\t\tif thing_starty > display_height:\n\t\t\tthing_starty = 0- thing_height\n\t\t\tthing_startx = random.randrange(0, (display_width-thing_width)//1)\n\t\t\tdodged += 1\n\t\t\tthing_speed += 1\n\t\t\tthing_width += (dodged * 1.2)\n\n\t\t# y crossover\n\t\tif ything_startx-car_width and x int:\n pass\n\n @classmethod\n def solve_1(cls, graph: List[List[int]]) -> int:\n \"\"\"\n 假设status是一个三位矩阵,表示状态转移。\n 1、status[i][j][0] 表示老鼠在i位置,猫在j位置,并且此时轮到老鼠行动\n 2、status[i][j][1] 表示老鼠在i位置,猫在j位置,并且次数轮到猫行动\n 3、status[i][j][k] 的值,如果是0,则本剧游戏是平局。如果是1则代表老鼠胜。如果是2则代表猫胜利。\n 默认情况下\n status[0][j][k] = 1,此时老鼠在洞里,老鼠肯定赢。\n status[i][i][k] = 2,当i不等于0的时候,老鼠和猫是同一位置,则猫肯定能赢。\n \"\"\"\n length = len(graph)\n color = [[[0] * 3 for _ in range(length)] for _ in range(length)]\n q = []\n for i in range(1, length):\n for t in range(1, 3):\n color[0][i][t] = 1 # 老鼠胜利\n q.append((0, i, t))\n color[i][i][t] = 2 # 猫胜利\n q.append((i, i, t))\n while q:\n cur_status = q.pop(0)\n mouse, cat, turn = cur_status\n for pre_status in cls.find_prev_status(graph, cur_status):\n pre_mouse, pre_cat, pre_turn = pre_status\n if color[pre_mouse][pre_cat][pre_turn] != 0:\n continue\n if color[mouse][cat][turn] == pre_turn:\n color[pre_mouse][pre_cat][pre_turn] = pre_turn\n q.append(pre_status)\n else:\n # 默认color[cat][mouse][turn]==turn\n if turn == 2:\n # color[cat][mouse][2]=2如果color[cat][pre_mouse][1]=1 全部color[cat][next_pre_mouse][2]=2\n flag = True\n for next_pre_mouse in graph[pre_mouse]:\n if color[next_pre_mouse][pre_cat][turn] != turn:\n flag = False\n break\n if flag:\n color[pre_mouse][pre_cat][pre_turn] = turn\n q.append(pre_status)\n else:\n flag = True\n for next_pre_cat in graph[pre_cat]:\n if next_pre_cat == 0:\n continue\n if color[pre_mouse][next_pre_cat][turn] != turn:\n flag = False\n break\n if flag:\n color[pre_mouse][pre_cat][pre_turn] = turn\n q.append(pre_status)\n return color[1][2][1]\n\n @classmethod\n def find_prev_status(cls, graph, cur_status):\n ret = []\n mouse, cat, turn = cur_status\n if turn == 1:\n for pre_cat in graph[cat]:\n if pre_cat == 0:\n continue\n ret.append((mouse, pre_cat, 2))\n else:\n for pre_mouse in graph[mouse]:\n # 则上一轮pre_mouse,pre_cat=cat,pre_turn=1,找出能到mouse的点,就是graph[mouse]中的点。\n ret.append((pre_mouse, cat, 1))\n return ret\n","sub_path":"algorithm/LeetCode_913_猫和老鼠.py","file_name":"LeetCode_913_猫和老鼠.py","file_ext":"py","file_size_in_byte":4548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"576379125","text":"from pandac.PandaModules import *\nfrom direct.gui.DirectGui import *\nimport random\n\nclass LoadingScreen(NodePath):\n\tdef __init__(self):\n\t\tNodePath.__init__(self, 'LoadingScreen')\n\t\tself.__expectedCount = 0\n\t\tself.__count = 0\n\t\tself.loadingBackground = loader.loadModel('phase_3/models/gui/progress-background.bam')\n\t\tself.loadingBackground.reparentTo(aspect2d)\n\t\tself.waitBar = DirectWaitBar(guiId='LoadingScreenScreenWaitBar', parent=self.loadingBackground, frameSize=(-1.06, 1.06, -0.03, 0.03), pos=(0, 0, -0.85), text='')\n\n\tdef tickWaitBar(self, value):\n\t\tif value > 0:\n\t\t\tself.__count = self.__count + value\n\n\t\tself.__count = self.__count + 1\n\t\tself.waitBar.update(self.__count)\n\n\tdef deleteLoadingScreen(self):\n\t\tself.loadingBackground.removeNode()\n\t\tself.waitBar.removeNode()\n\n\t\tdel self.loadingBackground\n\t\tdel self.waitBar\t","sub_path":"toontown/base/LoadingScreen.py","file_name":"LoadingScreen.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"181212737","text":"from tkinter import *\n\n\n# noinspection PyAttributeOutsideInit,PyUnusedLocal\nclass CustomScrollbar(Canvas):\n def __init__(self, parent, **kwargs):\n \"\"\"\n Custom scrollbar, using canvas. It can be configured with fg, bg and command\n\n :param parent:\n :param kwargs:\n \"\"\"\n\n self.command = kwargs.pop(\"command\", None)\n kw = kwargs.copy()\n bd = 0\n hlt = 0\n if \"fg\" in kw.keys():\n del kw[\"fg\"]\n if \"bd\" in kw.keys():\n bd = kw.pop(\"bd\")\n if \"border\" in kw.keys():\n bd = kw.pop(\"border\")\n if \"highlightthickness\" in kw.keys():\n hlt = kw.pop(\"highlightthickness\")\n Canvas.__init__(self, parent, **kw, highlightthickness=hlt, border=bd, bd=bd)\n if \"fg\" not in kwargs.keys():\n kwargs[\"fg\"] = \"darkgray\"\n\n # coordinates are irrelevant; they will be recomputed\n # in the 'set' method\\\n self.old_y = 0\n self._id = self.create_rectangle(0, 0, 1, 1, fill=kwargs[\"fg\"], outline=kwargs[\"fg\"], tags=(\"thumb\",))\n self.bind(\"\", self.on_press)\n self.bind(\"\", self.on_release)\n\n def configure(self, cnf=None, **kwargs):\n command = kwargs.pop(\"command\", None)\n self.command = command if command is not None else self.command\n kw = kwargs.copy()\n if \"fg\" in kw.keys():\n del kw[\"fg\"]\n super().configure(**kw, highlightthickness=0, border=0, bd=0)\n if \"fg\" not in kwargs.keys():\n kwargs[\"fg\"] = \"darkgray\"\n self.itemconfig(self._id, fill=kwargs[\"fg\"], outline=kwargs[\"fg\"])\n\n def config(self, cnf=None, **kwargs):\n self.configure(cnf, **kwargs)\n\n def redraw(self, event):\n # The command is presumably the `yview` method of a widget.\n # When called without any arguments it will return fractions\n # which we can pass to the `set` command.\n self.set(*self.command())\n\n def set(self, first, last):\n first = float(first)\n last = float(last)\n height = self.winfo_height()\n x0 = 2\n x1 = self.winfo_width() - 1\n y0 = max(int(height * first), 0)\n y1 = min(int(height * last), height)\n self._x0 = x0\n self._x1 = x1\n self._y0 = y0\n self._y1 = y1\n\n self.coords(\"thumb\", x0, y0, x1, y1)\n\n def on_press(self, event):\n self.bind(\"\", self.on_click)\n self.pressed_y = event.y\n self.on_click(event)\n\n def on_release(self, event):\n self.unbind(\"\")\n\n def on_click(self, event):\n y = event.y / self.winfo_height()\n y0 = self._y0\n y1 = self._y1\n a = y + ((y1 - y0) / -(self.winfo_height() * 2))\n self.command(\"moveto\", a)\n\n\n# noinspection PyUnusedLocal\nclass ScrolledWindow(Frame):\n \"\"\"\n 1. Master widget gets scrollbars and a canvas. Scrollbars are connected\n to canvas scrollregion.\n\n 2. self.scrollwindow is created and inserted into canvas\n\n Usage Guideline:\n Assign any widgets as children of .scrollwindow\n to get them inserted into canvas\n\n __init__(self, parent, canv_w = 400, canv_h = 400, *args, **kwargs)\n docstring:\n Parent = master of scrolled window\n canv_w - width of canvas\n canv_h - height of canvas\n\n \"\"\"\n\n def __init__(self, parent, canv_w=400, canv_h=400, expand=False, fill=None, height=None, width=None, *args,\n scrollcommand=lambda: None, scrollbarbg=None, scrollbarfg=\"darkgray\", **kwargs):\n \"\"\"Parent = master of scrolled window\n canv_w - width of canvas\n canv_h - height of canvas\n\n \"\"\"\n super().__init__(parent, height=canv_h, width=canv_w, *args, **kwargs)\n\n self.parent = parent\n self.scrollCommand = scrollcommand\n\n # creating a scrollbars\n\n if width is None:\n __width = 0\n else:\n __width = width\n\n if height is None:\n __height = 0\n else:\n __height = width\n\n self.canv = Canvas(self.parent, bg='#FFFFFF', width=canv_w, height=canv_h,\n scrollregion=(0, 0, __width, __height), highlightthickness=0)\n\n self.vbar = CustomScrollbar(self.parent, width=10, command=self.canv.yview, bg=scrollbarbg, fg=scrollbarfg, bd=1)\n self.canv.configure(yscrollcommand=self.vbar.set)\n\n self.vbar.pack(side=\"right\", fill=\"y\")\n self.canv.pack(side=\"left\", fill=fill, expand=expand)\n\n # creating a frame to inserto to canvas\n self.scrollwindow = Frame(self.parent, height=height, width=width)\n\n self.scrollwindow2 = self.canv.create_window(0, 0, window=self.scrollwindow, anchor='nw', height=height,\n width=width)\n\n self.canv.config( # xscrollcommand=self.hbar.set,\n yscrollcommand=self.vbar.set,\n scrollregion=(0, 0, canv_h, canv_w))\n\n self.scrollwindow.bind('', self._configure_window)\n self.scrollwindow.bind('', self._bound_to_mousewheel)\n self.scrollwindow.bind('', self._unbound_to_mousewheel)\n\n return\n\n def _bound_to_mousewheel(self, event):\n self.canv.bind_all(\"\", self._on_mousewheel)\n\n def _unbound_to_mousewheel(self, event):\n self.canv.unbind_all(\"\")\n\n def _on_mousewheel(self, event):\n self.canv.yview_scroll(int(-1 * (event.delta / 120)), \"units\")\n # self.scrollCommand(int(-1 * (event.delta / 120)), self.scrollwindow.winfo_reqheight(), self.vbar.get(),\n # self.vbar)\n\n def _configure_window(self, event):\n # update the scrollbars to match the size of the inner frame\n size = (self.scrollwindow.winfo_reqwidth(), self.scrollwindow.winfo_reqheight() + 1)\n self.canv.config(scrollregion='0 0 %s %s' % size)\n # if self.scrollwindow.winfo_reqwidth() != self.canv.winfo_width():\n # # update the canvas's width to fit the inner frame\n # # self.canv.config(width=self.scrollwindow.winfo_reqwidth())\n # if self.scrollwindow.winfo_reqheight() != self.canv.winfo_height():\n # # update the canvas's width to fit the inner frame\n # # self.canv.config(height=self.scrollwindow.winfo_reqheight())\n","sub_path":"qbubbles/special.py","file_name":"special.py","file_ext":"py","file_size_in_byte":6360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"433004128","text":"import logging\n\nfrom ..application import status\nfrom ..base import OpenStackBase\nfrom .resolver import compute_resolver\n\nLOG = logging.getLogger(__name__)\n\n\n@compute_resolver.datasource()\nclass ComputeServers(OpenStackBase):\n\n catalog_name = 'compute'\n resource_name = 'ComputeServer'\n\n async def fetchServers(self, region=None):\n url = self.get_service_url(region, 'servers/detail')\n resp = await self.get(url)\n servers = resp.servers\n for server in servers:\n server.region = region\n return servers\n\n async def fetchLimits(self):\n east_url = self.get_service_url('us-east', 'limits')\n resp = await self.get(east_url)\n return resp.servers\n\n\n@compute_resolver.resolver('Query')\nasync def computeServers(source, info, region):\n return await info.context.ComputeServers.fetchServers(region)\n\n\n@compute_resolver.resolver('ComputeServer')\nasync def appStatus(server, info):\n return status.Status(\n label=server.status,\n )\n","sub_path":"examples/cloud/resolvers/compute/servers.py","file_name":"servers.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"578882020","text":"\"\"\"\nCreated by Sam Henly on 26 Feb 2017\n\nSeries of functions used to manage stats projects with sklearn module.\n\nNotes on random seed selection:\n 1453: fall of Byzantium\n 8859: ISO encoding\n\n\nScheme:\n\n 1. Project names identify a subdirectory in /Carsomyr/projects/.\n\n 2. Data sets saved in under the same subdirectory.\n a. This, to avoid space use on git and to protect confidentiality.\n b. Data sets saved as pickled objects, including pre-constructed transformation objects\n\n 3. Permit straightforward construction of ensemble model from models in a given project.\n\n 4. Some basic functions with matplotlib to facilitate model evaluation. (to be implemented)\n\n\"\"\"\n\nimport sys\nsys.path.append('/home/sam/thesisOutput/')\n\nimport pandas as pd\n#import matplotlib as mp\nimport sklearn.metrics as skm\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import PolynomialFeatures, StandardScaler\nfrom sklearn import svm, linear_model\nimport sklearn.ensemble as ske\nimport os, pickle, utility\nimport numpy as np\nfrom scipy import optimize\n\n\"\"\"\nPart 0: Directories, etc\n\"\"\"\n\ndef rs(rsNo = 0):\n\n randomStates = [8859,\n 1453]\n\n return randomStates[rsNo]\n\ndef base_directory():\n return '/Carsomyr/projects/'\n\ndef project_directory(projectName):\n return check_directory('%s%s/' % (base_directory(), projectName))\n\ndef data_path(projectName):\n return '%sdata.pickle' % project_directory(projectName)\n\ndef model_directory(projectName):\n return check_directory('%smodels/' % project_directory(projectName))\n\ndef model_path(projectName, modelName):\n return '%s%s.pickle' % (model_directory(projectName), modelName)\n\ndef check_directory(path):\n \"\"\"\n Check path exists, then return path.\n \"\"\"\n\n if not os.path.exists(path):\n os.mkdir(path)\n\n return path\n\n\"\"\"\nPart 1: Dataset processing\n\"\"\"\n\nclass Dataset:\n \"\"\"\n Object containing a prepared data set, assembled from components,\n an input dictionary.\n\n To do: add some methods to summarize datasets.\n \"\"\"\n\n def __init__(self, inX, iny, projectName, projectDescription, subsets,\n yScaler, XScaler, pcaX):\n\n self.X = inX\n self.y = iny\n self.projectName = projectName\n self.projectDescription = projectDescription\n\n self.XScaler = XScaler\n self.yScaler = yScaler\n self.pcaX = pcaX\n\n # start with a 'base' subset defining the whole dataset\n self.subsets = {'base': [[], '']}\n\n # add additional subsets as specified during creation\n if subsets:\n self.subsets.update(subsets)\n\n def define_subset(self, subsetX, yColumn, subsetName, saveSelf = 0):\n \"\"\"\n Define a subset for particular regressions. Optionally, autopickle\n the dataset with this subset recorded for future use.\n \"\"\"\n\n self.subsets[subsetName] = [subsetX, yColumn]\n\n if saveSelf:\n self.autopickle()\n\n def subset(self, subsetName, segment, interact):\n \"\"\"\n Retrieve subset described by subsetName and return\n the appropriate segment (train/test typically).\n return subset\n \"\"\"\n\n subsetX, yColumn = self.subsets[subsetName]\n if not subsetX:\n subsetX = self.X[segment].columns\n if yColumn:\n y = self.y[segment][yColumn]\n else:\n y = self.y[segment]\n\n if not interact:\n return self.X[segment][subsetX], y\n\n pF = PolynomialFeatures(interact)\n\n # case 0: no scalar\n if not 'scaler' in self.X.keys():\n return pd.DataFrame(pF.fit_transform(self.X[segment][subsetX])), y\n\n # else . . .\n pX = pF.fit_transform(self.X['train'][subsetX])\n if type(self.X['scaler']) == StandardScaler:\n pS = StandardScaler()\n pX = pS.fit_transform(pX)\n else:\n # write formal flag later, or add more types\n pS = None\n\n # case 1: training data\n if segment == 'train':\n return pd.DataFrame(pX), y\n # case 2: test data\n else:\n return pd.DataFrame(pS.transform(pF.transform(self.X[segment][subsetX]))), y\n\n def print_description(self):\n\n open('%sdescription.txt' % project_directory(self.projectName),'w').write(self.projectDescription)\n\n def autopickle(self):\n\n self.print_description()\n pickle.dump(self, open(data_path(self.projectName), 'wb'))\n\ndef prepare_dataset(inX, iny, projectName,\n projectDescription,\n XScaler = None,\n yScaler = None,\n pcaX = None,\n testSize = 0.2,\n randomState = rs(),\n subsets = None,\n interactions = 0):\n \"\"\"\n Generate data set and save.\n\n :param inX:\n :param iny:\n :param projectName:\n :param projectDescription:\n :param XScaler:\n :param yScaler:\n :param pcaX:\n :param testSize:\n :param randomState:\n :param subsets:\n :param interactions:\n :return:\n \"\"\"\n\n def transform_data(inData, scaler):\n \"\"\"\n Transform all portions of a dataset using specified scalar\n \"\"\"\n\n if scaler:\n scaler = scaler()\n inData['train'] = scaler.fit_transform(inData['train'])\n if 'test' in inData.keys():\n inData['test'] = scaler.transform(inData['test'])\n\n return scaler\n\n yCols, XCols = (list(iny.columns), list(inX.columns))\n\n # will contain train, test\n if testSize:\n X, y = {}, {}\n X['train'], X['test'], y['train'], y['test'] = train_test_split(inX, iny,\n test_size = testSize,\n random_state = randomState)\n # alternative if no split required\n else:\n X = {'train': inX}\n y = {'train': iny}\n\n # standardize variables if scalers specified\n yScaler = transform_data(y, yScaler)\n XScaler = transform_data(X, XScaler)\n\n for segment in X.keys():\n if type(X[segment]) == np.ndarray and not interactions:\n X[segment] = pd.DataFrame(X[segment], columns = XCols)\n y[segment] = pd.DataFrame(y[segment], columns = yCols)\n elif type(X[segment]) == np.ndarray:\n X[segment] = pd.DataFrame(X[segment])\n y[segment] = pd.DataFrame(y[segment])\n\n # create and dump dataset\n ds = Dataset(X, y, projectName, projectDescription, subsets, yScaler, XScaler, pcaX)\n ds.autopickle()\n\ndef load_dataset(projectName):\n \"\"\"\n Load prepared dataset from pickle on Carsomyr.\n :param projectName:\n :return:\n \"\"\"\n\n return pickle.load(open(data_path(projectName), 'rb'))\n\n\ndef load_model(projectName, modelName):\n \"\"\"\n Load pre-fit model from pickle on Carsomyr.\n \"\"\"\n\n return pickle.load(open(model_path(projectName, modelName), 'rb'))\n\n\n\"\"\"\nPart 2: Training and evaluation\n\"\"\"\n\nclass ProjectModel:\n \"\"\"Class to hold model and some extra information.\"\"\"\n\n def __init__(self, model, projectName, modelName, modelType, subsetName, interactions,\n yScaler, XScaler, pcaX):\n\n self.model = model\n self.projectName = projectName\n self.modelName = modelName\n self.modelType = modelType\n self.subset = subsetName\n self.interact = interactions\n self.fit_notes = {}\n self.yScaler = yScaler\n self.XScaler = XScaler\n self.pcaX = pcaX\n\n if modelType == 'regressor' or hasattr(model,'predict_proba'):\n self.predict_continuous = True\n else:\n self.predict_continuous = False\n\n self.predict_m = False # contrast with combined model special feature\n if modelType in ['classifier', 'cluster']:\n self.predict_discrete = True\n else:\n self.predict_discrete = False\n\n # get fit notes and autopickle\n self.get_fit_notes()\n self.autopickle()\n\n def get_fit_notes(self):\n\n self.fit_notes = evaluate_model(self.projectName,\n self.modelName,\n self,\n returnResults=True)\n\n def print_fit(self):\n\n fit_names = list(self.fit_notes.keys())\n fit_names.sort()\n\n print('Fit notes for model {0} of project {1}, subset {2}:'.format(self.modelName,\n self.projectName,\n self.subset))\n for name in fit_names:\n print('{0}: {1!s}'.format(name, self.fit_notes[name]))\n\n def predict_c(self, X = None, segment = None, rawDataSet = None, group = 1):\n\n if X is None and rawDataSet is None:\n X = load_dataset(self.projectName).subset(self.subset, segment, self.interact)[0]\n elif X is None:\n X = rawDataSet.subset(self.subset, segment, self.interact)[0]\n\n if self.modelType == 'classifier':\n return self.model.predict_proba(X)[:, group]\n\n return self.model.predict(X)\n\n def predict_d(self, X = None, segment = None, rawDataSet = None):\n\n if X is None and rawDataSet is None:\n X = load_dataset(self.projectName).subset(self.subset, segment, self.interact)[0]\n elif X is None:\n X = rawDataSet.subset(self.subset, segment, self.interact)[0]\n\n return self.model.predict(X)\n\n def autopickle(self):\n\n pickle.dump(self, open(model_path(self.projectName, self.modelName),'wb'))\n\ndef train_model(projectName, modelFn, modelName, modelType,\n subsetName = 'base',\n interactions = 0,\n modelArgs = None):\n \"\"\"\n Fit a model for a given project and save.\n \"\"\"\n\n # load data and subset\n dataSet = load_dataset(projectName)\n X, y = dataSet.subset(subsetName, 'train', interact = interactions)\n XScaler = dataSet.XScaler\n yScaler = dataSet.yScaler\n pcaX = dataSet.pcaX\n\n # set modelArgs to dict if not given\n if not modelArgs:\n modelArgs = {}\n\n # if CV search function specified, set up; else just send parameters to model\n if not 'searchFn' in modelArgs.keys():\n model = modelFn(**modelArgs)\n else:\n model = modelArgs['searchFn'](modelFn, modelArgs['paramSearchDict'], **modelArgs['searchArgs'])\n\n # fit\n model.fit(X, y)\n\n # create ProjectModel object (autopickles in __init__)\n ProjectModel(model, projectName, modelName, modelType, subsetName, interactions,\n yScaler, XScaler, pcaX)\n\n\ndef evaluate_model(projectName, modelName,\n model = None,\n segment='test',\n metrics=None,\n returnResults = False):\n \"\"\"\n Load data and evaluate model on the test set.\n \"\"\"\n\n def metrics_function_names():\n \"\"\"\n Returns dictionary of metrics functions keyed to names for feedback.\n :return:\n \"\"\"\n\n metricsDict = {skm.mean_squared_error: 'Mean squared error',\n skm.mean_absolute_error: 'Mean absolute error',\n skm.r2_score: 'R^2',\n skm.roc_auc_score: 'ROC AUC',\n skm.accuracy_score: 'Accuracy',\n skm.precision_score: 'Precision',\n skm.recall_score: 'Recall'}\n return metricsDict\n\n def needs_continuous_input():\n \"\"\"Return whether metrict demands discrete or continuous input.\"\"\"\n mDict = {skm.mean_squared_error: True,\n skm.mean_absolute_error: True,\n skm.r2_score: True,\n skm.roc_auc_score: True,\n skm.accuracy_score: False,\n skm.precision_score: False,\n skm.recall_score: False}\n\n return mDict\n\n def get_metrics_list():\n \"\"\"\n Return list of \"standard\" metrics to be computed for evaluation\n of a given model type.\n \"\"\"\n metricsDict = {'regressor': [skm.mean_squared_error,\n skm.mean_absolute_error,\n skm.r2_score],\n 'classifier': [skm.roc_auc_score,\n skm.accuracy_score,\n skm.precision_score,\n skm.recall_score],\n 'cluster': []}\n\n return metricsDict\n\n if model is None:\n model = load_model(projectName, modelName)\n X, y = load_dataset(projectName).subset(model.subset, segment, model.interact)\n\n # if not list of functions fed in, use standard set\n # indicated by standardMetrics function\n if not metrics:\n metrics = get_metrics_list()[model.modelType]\n\n yHatC, yHatD = None, None\n if hasattr(model,\"predict_m\") and model.predict_m:\n yHatC = model.predict_m(X, toInt = False)\n yHatD = model.predict_m(X, toInt = True)\n else:\n if model.predict_continuous:\n yHatC = model.predict_c(X)\n if model.predict_discrete:\n yHatD = model.predict_d(X)\n\n resultDict = {}\n\n print('\\nPrinting scores for %s (%s subset, %s segment) using model %s.' % (projectName, model.subset,\n segment, modelName))\n for metric in metrics:\n if needs_continuous_input()[metric] and (yHatC is not None):\n metricVal = metric(y, yHatC)\n print('{0}: {1!s}'.format(metrics_function_names()[metric], metricVal))\n resultDict[metrics_function_names()[metric]] = metricVal\n elif (not needs_continuous_input()[metric]) and (yHatD is not None):\n metricVal = metric(y, yHatD)\n print('{0}: {1!s}'.format(metrics_function_names()[metric], metric(y, yHatD)))\n resultDict[metrics_function_names()[metric]] = metricVal\n\n if returnResults:\n return resultDict\n\n\"\"\"\nPart 3: Combined modeling\n\"\"\"\n\nclass CombinedWeightedModels:\n \"\"\"\n A ProjectModel-style object that takes multiple ProjectModel\n objects and combines their predictions using OLS (constraining\n coefficients to sum to 1 and each falling between 0 and 1).\n\n Not quite a child of ProjectModel class.\n \"\"\"\n\n def __init__(self, projectName, modelName,\n subModelNames,\n modelType,\n subset='base',\n interact = 0):\n\n self.modelName = modelName # name for model\n self.projectName = projectName # name for project\n self.subset = subset # data subset used for project\n self.modelType = modelType # classifier, regressor, etc\n self.interact = interact\n\n self.subModels = {name: load_model(projectName, name)\n for name in subModelNames}\n # pre-trained model objects in dictionary.\n # {name : model object}\n\n self.check_submodels() # make sure submodels appropriate\n\n self.cweights = self.fit(wSet = 'continuous')\n self.dweights = self.fit(wSet = 'discrete')\n self.mweights = self.fit(wSet = 'mixed')\n\n self.fit_notes = {}\n\n if self.cweights:\n self.predict_continuous = True\n if self.dweights:\n self.predict_discrete = True\n if self.mweights:\n self.predict_mixed = True\n\n self.get_fit_notes()\n self.autopickle()\n\n\n def check_submodels(self):\n \"\"\"Reject submodels that are of wrong subset or modelType.\"\"\"\n\n for model in list(self.subModels.keys()):\n if self.subModels[model].modelType != self.modelType or self.subModels[model].subset != self.subset:\n del self.subModels[model]\n print('Deleted submodel %s! Bad subset or modelType.' % model)\n\n def fit(self, wSet = None):\n \"\"\"\n Load models if necessary, then fit using scipy optimize.\n \"\"\"\n\n def sum_square_errors(betaVector, yi, Xi):\n \"\"\"\n Objective function.\n NB, np is not doing a bang-up job with matrix multiplication :(\n Dividing by len(y) because of MemoryError --maybe helping?\n \"\"\"\n\n yHat = np.dot(Xi, betaVector.reshape(len(betaVector), 1)).flatten()\n error = yi - yHat\n return sum(error ** 2)\n\n def get_submodel_names(subModels, wSet):\n subModelNameList = None\n if wSet == 'continuous':\n subModelNameList = [modelName for modelName in subModels.keys()\n if subModels[modelName].predict_continuous]\n elif wSet == 'mixed':\n subModelNameList = [modelName for modelName in subModels.keys()]\n elif wSet == 'discrete':\n subModelNameList = [modelName for modelName in subModels.keys()\n if subModels[modelName].predict_discrete]\n return subModelNameList\n\n def get_submodel_predictions(names, subModels, wSet):\n yHatList = []\n for smName in names:\n if (wSet == 'continuous') or (wSet == 'mixed' and subModels[smName].predict_continuous):\n yHatList.append(subModels[smName].predict_c(rawDataSet=rawDataSet, segment='train'))\n else:\n yHatList.append(subModels[smName].predict_d(rawDataSet=rawDataSet, segment='train'))\n\n return np.array(yHatList).transpose()\n\n def get_optimal_weights(targetFn, names, optimizeArgs):\n\n # optimize\n constraints = [{'type': 'eq', 'fun': lambda x: sum(x) - 1},\n {'type': 'ineq', 'fun': lambda x: min(x)},\n {'type': 'ineq', 'fun': lambda x: 1 - max(x)}]\n\n betaCoefs = optimize.minimize(targetFn, np.ones(len(names)) / len(names),\n args=optimizeArgs, constraints=constraints,\n method='SLSQP').x\n\n return {names[i]: betaCoefs[i] for i in range(len(names))}\n\n # get subModels with appropriate predict capability\n subModelNames = get_submodel_names(self.subModels, wSet)\n\n # if no subModelNames, return None\n if not subModelNames:\n return None\n\n # otherwise, continue. load raw data sets\n rawDataSet = load_dataset(self.projectName)\n X, y = rawDataSet.subset(self.subset, 'train', self.interact)\n\n # get predictions for each sub-model\n yHats = get_submodel_predictions(subModelNames, self.subModels, wSet)\n\n return get_optimal_weights(sum_square_errors, subModelNames, (y,yHats,))\n\n\n def predict_c(self, X):\n \"\"\"Predict Y by combining models.\"\"\"\n\n yHats = np.zeros(X.shape[0])\n for modelName in self.cweights.keys():\n yHats = yHats + (self.cweights[modelName] * self.subModels[modelName].predict_c(X))\n\n return yHats\n\n def predict_d(self, X):\n\n yHats = np.zeros(X.shape[0])\n for modelName in self.dweights.keys():\n yHats = yHats + (self.dweights[modelName] * self.subModels[modelName].predict_d(X))\n\n return yHats\n\n def predict_m(self, X, toInt = False):\n\n yHats = np.zeros(X.shape[0])\n for modelName in self.mweights.keys():\n model = self.subModels[modelName]\n if model.predict_c:\n yHats = yHats + (self.mweights[modelName] * model.predict_c(X))\n else:\n yHats = yHats + (self.mweights[modelName] * model.predict_d(X))\n\n if toInt:\n return yHats.round().astype('int64')\n\n return yHats\n\n def get_fit_notes(self):\n\n self.fit_notes = evaluate_model(self.projectName,\n self.modelName,\n self,\n returnResults=True)\n def print_fit(self):\n\n fit_names = list(self.fit_notes.keys())\n fit_names.sort()\n\n print('Fit notes for model {0} of project {1}, subset {2}:'.format(self.modelName,\n self.projectName,\n self.subset))\n for name in fit_names:\n print('{0}: {1!s}'.format(name, self.fit_notes[name]))\n\n def autopickle(self):\n \"\"\"Save self.\"\"\"\n\n outString = model_path(self.projectName, self.modelName)\n pickle.dump(self, open(outString, 'wb'))\n\n\"\"\"\nPart 4: Some baseline, quick-and-dirty modeling options\n\"\"\"\n\ndef qd_model(projectName, subsetName, interactions,\n modelFn, modelArgs, modelType, modelAbbrev):\n \"\"\"General function for default function options.\"\"\"\n\n modelName = 'qd_%s%s_%s' % (modelAbbrev,\n modelType.capitalize(),\n subsetName)\n\n train_model(projectName, modelFn, modelName, modelType.lower(),\n subsetName, interactions, modelArgs)\n\ndef qd_random_forest_classifier(projectName, subsetName, interactions = 0):\n \"\"\"Random forest classifier with tweaked default options.\"\"\"\n\n modelArgs = {'oob_score': True,\n 'n_jobs': max(1, utility.get_thread_capacity()-1),\n 'random_state': rs(1),\n 'n_estimators': 3500}\n qd_model(projectName, subsetName, interactions,\n ske.RandomForestClassifier, modelArgs, 'classifier', 'rf')\n\ndef qd_svm_classifier(projectName, subsetName, interactions = 0):\n\n modelArgs = {'probability': True,\n 'cache_size': 10000,\n 'random_state': rs(1),\n 'decision_function_shape': 'ovr'}\n\n qd_model(projectName, subsetName, interactions,\n svm.SVC, modelArgs, 'classifier','svmC')\n\ndef qd_logit(projectName, subsetName, interactions = 0):\n\n modelArgs = {'cv': 10,\n 'solver': 'sag',\n 'n_jobs': max(1, utility.get_thread_capacity()-1),\n 'refit': True,\n 'random_state': rs(1)}\n\n qd_model(projectName, subsetName, interactions,\n linear_model.LogisticRegressionCV, modelArgs, 'classifier','logitCV')\n\ndef qd_sgd(projectName, subsetName, interactions = 0):\n\n modelArgs = {'loss': 'modified_huber',\n 'penalty': 'elasticnet',\n 'n_iter': 250,\n 'random_state': rs(1),\n 'n_jobs': max(1, utility.get_thread_capacity()-1),\n }\n\n qd_model(projectName, subsetName, interactions,\n linear_model.SGDClassifier, modelArgs, 'classifier','sdgC')\n\ndef qd_gradiant_boost(projectName, subsetName, interactions = 0):\n\n modelArgs = {'learning_rate': 0.3,\n 'n_estimators': 3000,\n 'max_features': 'sqrt',\n 'random_state': rs(1)}\n\n qd_model(projectName, subsetName, interactions,\n ske.GradientBoostingClassifier, modelArgs, 'classifier','gbC')\n\n\"\"\"\nPart 5: Some special case estimators\n\"\"\"\n\ndef test_constrained_adaboost(projectName, subsetName,\n modelName = None,\n interactions = 0,\n adaArgs = None):\n \"\"\"Adaboost implementation constraining overfitting with test set.\"\"\"\n\n # default values for parameters\n # default to some nice decision tree settings\n # if baseArgs is None:\n # baseArgs = {'max_features': 'sqrt',\n # 'random_state': 8859}\n # default adaArg settings\n # learn a bit slowly, lots of estimators\n if adaArgs is None:\n adaArgs = {'n_estimators': 300,\n 'learning_rate': .5,\n 'random_state': rs(1)}\n\n if modelName is None:\n modelName = 'tc_adaBoost_%s' % subsetName\n\n # load train and test sets\n\n dataSet = load_dataset(projectName)\n trainX, trainy = dataSet.subset(subsetName, 'train', interactions)\n testX, testy = dataSet.subset(subsetName, 'test', interactions)\n XScaler = dataSet.XScaler\n yScaler = dataSet.yScaler\n pcaX = dataSet.pcaX\n\n # fit estimator\n model = ske.AdaBoostClassifier(**adaArgs)\n model.fit(trainX, trainy)\n\n # find max test accuracy\n # can generalize later if needed\n adaAccuracy = list(np.zeros(adaArgs['n_estimators']).astype('int64'))\n for i, yHat in enumerate(model.staged_predict(testX)):\n adaAccuracy[i] = skm.accuracy_score(testy, yHat)\n\n # just refit the fucking thing to use the default functions\n adaArgs['n_estimators'] = adaAccuracy.index(max(adaAccuracy))\n model = ske.AdaBoostClassifier(**adaArgs)\n model.fit(trainX, trainy)\n\n ProjectModel(model, projectName, modelName,\n 'classifier', subsetName, interactions,\n yScaler, XScaler, pcaX)\n","sub_path":"stats/stat_management.py","file_name":"stat_management.py","file_ext":"py","file_size_in_byte":25268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"147198435","text":"from planet import api\nimport sys\nclient = api.ClientV1(\"18272744a851407eb14b599ce28ad2eb\")\n\n# https://tiles.planet.com/data/v1/item-types/PSScene3Band/items/20160223_174714_0c72/thumb?api_key=18272744a851407eb14b599ce28ad2eb\n\naoi = {\n \"type\": \"Polygon\",\n \"coordinates\": [\n [\n [\n 34.1015625,\n 7.36246686553575\n ],\n [\n 81.9140625,\n 7.36246686553575\n ],\n [\n 81.9140625,\n 37.996162679728116\n ],\n [\n 34.1015625,\n 37.996162679728116\n ],\n [\n 34.1015625,\n 7.36246686553575\n ]\n ]\n ]\n}\n\n# build a filter for the AOI\nquery = api.filters.and_filter(\n api.filters.geom_filter(aoi),\n api.filters.range_filter('cloud_cover', gt=0), \n api.filters.date_range('acquired', gt='2020-06-13T00:00:00Z', lte=\"2020-06-16T00:00:00Z\"),\n api.filters.permission_filter('assets:download')\n)\n\n# we are requesting PlanetScope 4 Band imagery\nitem_types = ['PSScene4Band']\nrequest = api.filters.build_search_request(query, item_types)\n\n# this will cause an exception if there are any API related errors\nresults = client.quick_search(request)\ndd = api.downloader.create(client, mosaic=False, order=False, **kw)\n\n# items_iter returns an iterator over API response pages\nfor item in results.items_iter(10):\n # each item is a GeoJSON feature\n print(\"ID -> \", item[\"id\"], \"DATE -> \", item[\"properties\"][\"acquired\"])\n assets = client.get_assets(item).get()\n # activation = client.activate(assets['analytic'])\n # wait for activation\n # assets = client.get_assets(item).get()\n # callback = api.write_to_file()\n # body = client.download(assets['analytic'], callback=callback)\n # body.await()","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"557418847","text":"#!/usr/bin/env python\nfrom pg_catalog.test import *\n \nclass TestCase(TestCase):\n def test(self):\n for r in self.db.query(\n pg_amop\n ).options(map(\n lambda c:undefer(c.key),\n pg_amop.__table__.columns\n )).all():\n is_(r,pg_amop)\n is_int(r.oid) # oid\n is_int(r.amopfamily) # amopfamily\n is_int(r.amoprighttype) # amoprighttype\n is_int(r.amopstrategy) # amopstrategy\n is_text(r.amoppurpose) # amoppurpose\n is_int(r.amopopr) # amopopr\n is_int(r.amopmethod) # amopmethod\n is_int(r.amopsortfamily) # amopsortfamily\n\nif __name__ == \"__main__\":\n main()","sub_path":"tests/pg_amop.py","file_name":"pg_amop.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"593796730","text":"import os; path = os.getcwd()\nimport pandas as pd\n\nfor strategy in [\"Loser\", \"Small\"]:\n for limit in range(0, 501, 10):\n file_name = \" \".join([strategy, str(limit)])\n data = pd.read_csv(path + \"\\\\Contrarian Result\\\\%s.csv\" % file_name, index_col=[0])\n data.index = pd.to_datetime(data.index, format=\"%Y-%m-%d\").strftime('%Y-%m')\n data.index = pd.to_datetime(data.index, format='%Y-%m')\n data.to_csv(path + \"\\\\Contrarian Result\\\\%s.csv\" % file_name)\n\nfor limit in range(100, 201, 20):\n for method in [\"intersection\", \"market_capital\", \"profit\"]:\n if method == \"intersection\":\n file_name = \" \".join([\"Loser\", \"Small\", str(limit), \"intersection\"])\n else:\n file_name = \" \".join([\"Loser\", \"Small\", str(limit), method, \"2\"])\n data = pd.read_csv(path + \"\\\\Contrarian Result\\\\%s.csv\" % file_name, index_col=[0])\n data.index = pd.to_datetime(data.index, format=\"%Y-%m-%d\").strftime('%Y-%m')\n data.index = pd.to_datetime(data.index, format='%Y-%m')\n data.to_csv(path + \"\\\\Contrarian Result\\\\%s.csv\" % file_name)","sub_path":"Codes/Debug/Different Month.py","file_name":"Different Month.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"564975023","text":"def check_is_anagram():\n firstInput, secondInput = input().split(' ')\n firstArray = list(firstInput.lower())\n secondArray = list(secondInput.lower())\n for elem in firstArray:\n if elem not in secondArray:\n return 'NOT_ANAGRAMS'\n else:\n secondArray.remove(elem)\n if secondArray != []:\n return 'NOT_ANAGRAMS'\n return 'ANAGRAMS'\n'''\nprint(check_is_anagram())\n'''\n\ndef to_digits(n):\n res=[int(d) for d in str(n)]\n return res\n\ndef sum_of_digits(n):\n s = 0\n if n < 0:\n n=-n\n while n != 0:\n s+=n%10\n n=n//10\n return s\n\ndef is_credit_card_valid(number):\n listOfDigits=to_digits(number)\n oddIndexesNumbers = []\n evenIndexesNumbers = []\n for i in range(0,len(listOfDigits)):\n if i % 2 == 0:\n evenIndexesNumbers.append(listOfDigits[i])\n else:\n oddIndexesNumbers.append(listOfDigits[i])\n\n oddIndexesNumbers = [sum_of_digits(d*2) for d in oddIndexesNumbers]\n\n sumOfEven = sum(evenIndexesNumbers)\n sumOfOdd = sum(oddIndexesNumbers)\n\n if (sumOfEven+sumOfOdd) % 10 == 0:\n return 'valid'\n else:\n return 'invalid'\n'''\nprint(is_credit_card_valid(79927398713))\nprint(is_credit_card_valid(79927398715))\n'''\n\ndef is_prime(n):\n i = 2\n if n == 0 or n == 1:\n return False\n while i*i<=n:\n if n % i == 0:\n return False\n else:\n i+=1\n return True\n\n\ndef goldbach(n):\n i = 2\n listOfTuples = []\n while i <= n/2:\n remainder = n - i\n if is_prime(i) and is_prime(remainder):\n listOfTuples.append((i,remainder))\n i += 1\n return listOfTuples\n\n'''\nprint(goldbach(4))\nprint(goldbach(6))\nprint(goldbach(8))\nprint(goldbach(10))\nprint(goldbach(100))\n'''\ndef checkCoords(col,row,n,m):\n return (col >= 0 and row >= 0) and (col <= n-1 and row <= m-1)\n\ndef matrix_bombing_plan(m):\n sumOfAllElements = 0\n for i in range(len(m)):\n for j in range(len(m[0])):\n sumOfAllElements += m[i][j]\n\n myDict = {}\n remainingSum = sumOfAllElements\n\n for i in range(len(m)):\n for j in range(len(m[0])):\n if checkCoords(i-1,j-1,len(m),len(m[0])):\n if m[i-1][j-1] - m[i][j] >= 0:\n remainingSum -= m[i][j]\n else:\n remainingSum -= m[i-1][j-1]\n\n if checkCoords(i-1,j+1,len(m),len(m[0])):\n if m[i-1][j+1] - m[i][j] >= 0:\n remainingSum -= m[i][j]\n else:\n remainingSum -= m[i-1][j+1]\n\n if checkCoords(i+1,j-1,len(m),len(m[0])):\n if m[i+1][j-1] - m[i][j] >= 0:\n remainingSum -= m[i][j]\n else:\n remainingSum -= m[i+1][j-1]\n\n if checkCoords(i+1,j+1,len(m),len(m[0])):\n if m[i+1][j+1] - m[i][j] >= 0:\n remainingSum -= m[i][j]\n else:\n remainingSum -= m[i+1][j+1]\n\n if checkCoords(i,j-1,len(m),len(m[0])):\n if m[i][j-1] - m[i][j] >= 0:\n remainingSum -= m[i][j]\n else:\n remainingSum -= m[i][j-1]\n\n if checkCoords(i,j+1,len(m),len(m[0])):\n if m[i][j+1] - m[i][j] >= 0:\n remainingSum -= m[i][j]\n else:\n remainingSum -= m[i][j+1]\n\n if checkCoords(i-1,j,len(m),len(m[0])):\n if m[i-1][j] - m[i][j] >= 0:\n remainingSum -= m[i][j]\n else:\n remainingSum -= m[i-1][j]\n\n if checkCoords(i+1,j,len(m),len(m[0])):\n if m[i+1][j] - m[i][j] >= 0:\n remainingSum -= m[i][j]\n else:\n remainingSum -= m[i+1][j]\n\n print(remainingSum)\n myDict[(i,j)] = remainingSum\n remainingSum = sumOfAllElements\n \n return myDict\n\nm = [[1,2,3],[4,5,6],[7,8,9]]\nprint(matrix_bombing_plan(m))\n\n","sub_path":"Week1/week1_3_solutions.py","file_name":"week1_3_solutions.py","file_ext":"py","file_size_in_byte":3802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"610733002","text":"import os\nimport re\nimport sys\nimport subprocess\n\nfrom signal import SIGTERM, SIG_DFL\n\n\"\"\"\n\nCreate simple ssh tunnel with ssh client programm.\n\nTODO: Run with out full path to ssh\n\n\"\"\"\nclass SSHTun:\n tunnel_command_template = \"/usr/bin/ssh -l %s -i %s -f -n -N -q -o 'ExitOnForwardFailure yes' -o 'PasswordAuthentication no' -L 127.0.0.1:%d:localhost:%d %s\"\n tunnel_command = None\n lport = None\n rport = None\n rhost = None\n user = None\n keyfile = None\n pid = None\n min_pid = 300 # From kernel/pid.c see RESERVED_PIDS\n max_pid = 0\n\n #XXX: Add params check here\n def __init__(self, user, keyfile, lport, rport, rhost):\n self.user = user\n self.keyfile = keyfile\n self.lport = lport\n self.rport = rport\n self.rhost = rhost\n\n self.tunnel_command = self.tunnel_command_template % (self.user, self.keyfile, self.lport, self.rport, self.rhost)\n\n def start(self):\n\n t = subprocess.Popen(self.tunnel_command, stderr=subprocess.PIPE, shell=True, close_fds=True, stdout=subprocess.PIPE)\n t.wait()\n\n if t.returncode == 0:\n self.pid = self.__find_pid(t.pid)\n else:\n ## Kill previos tunnel\n #os.kill(self.__find_pid(), SIGTERM)\n #self.pid = self.start()\n\n # Try to find existing tunnel\n self.pid = self.__find_pid()\n\n if self.pid == None:\n raise Exception(\"Can't create new ssh tunnel\")\n\n return self.pid\n\n \"\"\"\n\n subprocess.Popen creates sheel and then ssh process.\n Popen object returns pid of that shell, not pid of ssh\n But ssh's pid can be pedicted as shell pid plus some small N number\n It works fine if new ssh tunnel was started without errors (Popen.returncode is zero)\n\n But ssh tunnel can ramain from previos run,\n and in this case all process should be checked to match ssh tunnel with same options\n\n XXX: Should i kill previos tunnel and create new one?\n\n \"\"\"\n def __find_pid(self, pid_start_from = None):\n\n if pid_start_from == None:\n pid_start_from = self.min_pid\n\n # Find pid range on this system\n try:\n with open('/proc/sys/kernel/pid_max', 'r') as f:\n self.max_pid = int(f.readline())\n\n except Exception as e:\n raise Exception(\"Can't get pid_max from proc: %s\" % e.args)\n\n # get all processes from /proc\n proc_arr = []\n for dir in os.listdir('/proc'):\n if re.search('^[0-9]+$', dir):\n proc_arr.append(int(dir))\n\n # search for process\n pid_to_check = pid_start_from + 1\n\n # search for process from predicted pid\n for i in range(self.min_pid, self.max_pid):\n\n if pid_to_check >= self.max_pid:\n pid_to_check = self.min_pid\n\n if pid_to_check in proc_arr:\n\n try:\n with open('/proc/%d/cmdline' % pid_to_check, 'r') as f:\n cmdline = f.readline().replace('\\x00', ' ').rstrip('\\n').strip()\n\n if cmdline == self.tunnel_command.replace(\"'\",''):\n return pid_to_check\n except:\n pass\n\n pid_to_check += 1\n\n return None\n\n def is_alive(self):\n try:\n os.kill(self.pid, SIG_DFL)\n except:\n return None\n\n return True\n\n def stop(self):\n if not self.pid:\n self.pid = self.__find_pid()\n\n if self.pid:\n os.kill(self.pid, SIGTERM)\n\n def restart(self):\n self.stop()\n return self.start()\n\n def get_pid(self):\n return self.pid\n","sub_path":"sshtun.py","file_name":"sshtun.py","file_ext":"py","file_size_in_byte":3690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"495640156","text":"from bookreviewfunctions import *\r\nimport time\r\nfrom sklearn import linear_model\r\nfrom sklearn import svm\r\nfrom sklearn.ensemble import ExtraTreesRegressor\r\nfrom sklearn.neighbors import KNeighborsRegressor\r\nfrom sklearn.linear_model import RidgeCV\r\n\r\nstarttime = time.time()\r\nlocation = 'Bookreview.csv'\r\nsplitreview, splitreviewdetail, rating = getsplitreview(location)\r\nprint(len(splitreview))\r\nmyVocablist = createVocabList(splitreview, 3)\r\nprint('my vocablist is', myVocablist)\r\nmybinarylist = []\r\nprint('the length of myVocabliast is',len(myVocablist))\r\nfor postinDoc in splitreviewdetail:\r\n mybinarylist.append(bagOfWords2Vec(myVocablist, postinDoc))\r\nprint('the length of mybinarylist is',len(mybinarylist))\r\n\r\nX = np.array(mybinarylist)\r\ny = np.array(rating)/5\r\ntrain_X = X[:-10]\r\ntrain_y = y[:-10]\r\ntest_X = X[-10:]\r\ntest_y = y[-10:]\r\n\r\nlibrary = {\r\n 'linear': linear_model.LinearRegression(fit_intercept=False),\r\n 'Bay': linear_model.BayesianRidge(fit_intercept=False),\r\n 'ARD': linear_model.ARDRegression(fit_intercept=False),\r\n 'Elastic': linear_model.ElasticNet(fit_intercept=False),\r\n 'LassoCV': linear_model.LassoCV(fit_intercept=False),\r\n 'Ridge':linear_model.Ridge(alpha= 0.4, fit_intercept=False),\r\n 'SGD': linear_model.SGDRegressor(fit_intercept=False),\r\n 'clf': svm.SVR(),\r\n \"Extra trees\": ExtraTreesRegressor(n_estimators=10, max_features=32,\r\n random_state=0),\r\n \"K-nn\": KNeighborsRegressor(),\r\n \"Ridge\": RidgeCV(),\r\n}\r\n\r\nfor method in library.values():\r\n method.fit(train_X,train_y)\r\n predict = method.predict(test_X)\r\n predictminus = predict - test_y\r\n currentsquare = std(predictminus)\r\n print('-'*20)\r\n print('now using', str(method))\r\n print('the prediction is', predict)\r\n print('the real number is', test_y )\r\n print('standard deviation is', currentsquare)\r\n print('Training duration (s) : ', time.time()-starttime)\r\n print('-'*20)","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"468342357","text":"# Dada uma sequência de caracteres, determinar quantas letras minúsculas\n# e maiúsculas aparecem na sequência. Considere apenas os caracteres ASCII.\n# Exemplo, para a frase: \"Em terra de CEGO quem tem um olho e caolho\":\n# Número de minúsculas: 28\n# Número de maiúsculas: 5\n# Total de caracteres no texto: 42\n\n\ndef conta_minusculas(texto):\n qtd = 0\n for c in texto:\n if 'a' <= c <= 'z':\n qtd += 1\n return qtd\n\n\ndef conta_maiusculas(texto):\n qtd = 0\n for c in texto:\n if 'A' <= c <= 'Z':\n qtd += 1\n return qtd\n\n\n# input(\"Digite um texto: \") # Suponha que o usuário digitou a frase do exemplo\nfrase = \"Em terra de CEGO quem tem um olho e caolho\"\n\nnmai = conta_maiusculas(frase)\nnmin = conta_minusculas(frase)\n\nprint(\"Número de minúsculas: %d\" % nmin)\nprint(\"Número de maiúsculas: %d\" % nmai)\nprint(\"Total de caracteres no texto: %d\" % (len(frase)))\n","sub_path":"programacao_estruturada/20192_166/ritomar/exercicios_repeticao_02/Q5.py","file_name":"Q5.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"401751036","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport seaborn as sns\nsns.set()\nimport time\nfrom datetime import datetime\nimport re\nimport os\nimport glob\n\n\nst = time.time()\n\nfiles = glob.glob(\"*.out\")\nprint(files)\n\nwith open(files[1], 'r') as file:\n first_file_string = file.read()#.replace('\\n', '')\n file.close()\nfirst_file_string = re.sub(r'(\\d{1}.\\d{4})(-\\d{3})', r'\\1E\\2', first_file_string)\n#The above searches for \"#.####-###\" and replaces them with \"#.####E-###\"\ngroups = re.split(r'in\\ curies\\ for\\ case\\ \\Sirrad\\S|in\\ curies\\ for\\ case\\ \\Sdecay\\S', \\\n first_file_string, flags=re.MULTILINE)\n# groups = re.split(r'(?<=in\\ curies\\ for\\ case)\\w+', first_file_string, flags=re.MULTILINE)\ngroups = groups[1:]\n\n\n\nall_times = list()\n\nAll_LE = pd.Series()\nAll_AC = pd.Series()\nAll_FP = pd.Series()\nfor case in groups: #####################################################################\n # Handle the last table from each split section\n #################################\n tester = re.sub(r'\\s{2,}(?=\\d+)',\" \", case)\n tester = re.sub(r'^[.]\\s*|^\\s{2}',\"\", tester, flags = re.MULTILINE)\n # tester = re.sub(r'\\s{2}',\", \", tester)\n # print(tester)\n # tester = re.sub(r'^.+\\)',\"\", tester, flags = re.MULTILINE)\n # tester = re.split(\"\\n\",tester)\n # print(tester)\n tester = re.split(r'he-3', tester)\n header_handling = re.split(r\"d(.+)\",tester[0], flags = re.MULTILINE) #Splitting the first \n #portion of list by the the first occuring d\n #################################\n times = header_handling[1].split('d') #Splitting string to list for numpy to use\n# print(times)\n start_time = times[1] #We have two cases of the first time. The index list must be the right length, so we append.\n #This is an artifact of using the first 'd' to split our header\n times.insert(1,start_time)\n times = np.array(times[1:-1]).astype(float) #The first and last objects are empty strings. Numpy no likey\n all_times.append(times)\n first_table = header_handling[2].split('\\n') \n df = pd.DataFrame(first_table)\n df = df[0].str.split(\" * \", expand = True)\n df.iloc[0] = df.iloc[0].shift(1)\n df = df.transpose()\n header = df.iloc[0]\n for number, head in enumerate(header):\n if number > 0:\n header[number] = re.sub(r'\\-', \"\", head)\n new_df = df[2:]\n new_df.columns = header\n new_df = new_df.set_index(times)\n new_df\n print(new_df.shape)\n\n #####################################################################\n first_table = tester[1].split('\\n')\n df = pd.DataFrame(first_table)\n df = df[0].str.split(\" * \", expand = True)\n df.iloc[0] = df.iloc[0].shift(1)\n df = df.transpose()\n header = df.iloc[0]\n for number, head in enumerate(header):\n if number > 0:\n header[number] = re.sub(r'\\-', \"\", head)\n header = pd.concat([pd.Series([\"LE\"]),header[1:]])\n new_df = df[2:]\n new_df.columns = header\n new_df = new_df.set_index(times)\n LE_df_final = new_df\n print(\"LE (light elements) shape\",new_df.shape)\n\n #####################################################################\n save_1 = new_df\n first_table = tester[2].split('\\n')\n df = pd.DataFrame(first_table)\n df = df[0].str.split(\" * \", expand = True)\n df.iloc[0] = df.iloc[0].shift(1)\n df = df.transpose()\n header = df.iloc[0]\n for number, head in enumerate(header):\n if number > 0:\n header[number] = re.sub(r'\\-', \"\", head)\n header = pd.concat([pd.Series([\"AC\"]),header[1:]])\n new_df = df[2:]\n new_df.columns = header\n new_df = new_df.set_index(times)\n AC_df_final = new_df\n print(\"AC (actinides) shape\",new_df.shape)\n\n #####################################################################\n # Handle the last table from each split section\n #################################\n FP_handling = re.split(r\"\\-{6,}\",tester[3])\n #################################\n first_table = FP_handling[0].split('\\n')\n df = pd.DataFrame(first_table)\n df = df[0].str.split(\" * \", expand = True)\n df.iloc[0] = df.iloc[0].shift(1)\n df = df.transpose()\n header = df.iloc[0]\n for number, head in enumerate(header):\n if number > 0:\n header[number] = re.sub(r'\\-', \"\", head)\n header = pd.concat([pd.Series([\"FP\"]),header[1:]])\n new_df = df[2:]\n new_df.columns = header\n new_df = new_df.set_index(times)\n FP_df_final = new_df\n print(\"FP (Fission Products) shape\",new_df.shape)\n \n All_LE = pd.concat([All_LE,LE_df_final],sort = True)\n All_AC = pd.concat([All_AC,AC_df_final],sort = True)\n All_FP = pd.concat([All_FP,FP_df_final],sort = True)\nprint(all_times)\n\nprint(time.time() - st)\n\nAll_FP.index = pd.to_numeric(All_FP.index, downcast=\"float\")\nprint('Here I am')\nfor column in All_AC:\n name = All_AC[column].name\n# print(name)\n All_AC[All_AC[column].name] = pd.to_numeric(All_AC[All_AC[column].name], downcast=\"float\")\nfor column in All_FP:\n name = All_FP[column].name\n# print(name)\n All_FP[All_FP[column].name] = pd.to_numeric(All_FP[All_FP[column].name], downcast=\"float\")\nfor column in All_LE:\n name = All_LE[column].name\n# print(name)\n All_LE[All_LE[column].name] = pd.to_numeric(All_LE[All_LE[column].name], downcast=\"float\")\n\nAll_LE['Unnamed: 0'] = All_LE.index\nAll_FP['Unnamed: 0'] = All_FP.index\nAll_AC['Unnamed: 0'] = All_AC.index\n \nprint(All_LE.head(5))\nNU = All_AC\nLEU = All_FP\n \n# plt.plot(All_FP.index,All_FP['mo-99'])\n# plt.xlabel(\"Time (Days)\")\n# plt.ylabel(\"Activity, mo-99 (Cu)\")\n# plt.show()","sub_path":"Scripts/ORIGEN Output File Reading/Output File Reading/.ipynb_checkpoints/Sorter-checkpoint.py","file_name":"Sorter-checkpoint.py","file_ext":"py","file_size_in_byte":5712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"650621922","text":"import threading\nimport os, logging, sys\nLOG_FILE = 'log.log'\nENV = \"DJANGO\"\ntry:\n from django.conf import settings\n try:\n LOG_FILE = settings.LOG_FILE\n except Exception:\n try:\n from paste.deploy.converters import asbool\n from pylons import config\n ENV = \"PYLONS\"\n except ImportError:\n ENV = \"OTHER\"\nexcept ImportError:\n try:\n from paste.deploy.converters import asbool\n from pylons import config\n ENV = \"PYLONS\"\n LOG_FILE = config['logfile']\n except (ImportError,KeyError):\n ENV = \"OTHER\"\n LOG_FILE = 'log.log'\n\ndef setup_logging():\n \"\"\"\n http://docs.pylonshq.com/configuration.html#id4\n\n logging.basicConfig(filename=logfile, mode='at+',\n level=logging.DEBUG,\n format='%(asctime)s, %(name)s %(levelname)s %(message)s',\n datefmt='%b-%d %H:%M:%S')\n \"\"\"\n if ENV == \"PYLONS\" or ENV == 'OTHER':\n return\n if LOG_FILE == 'STDOUT': # send to output\n logging.basicConfig(stream=sys.stdout, level=logging.DEBUG,\n #format='%(name)s %(levelname)s %(message)s',\n #format='%(asctime)s,%(msecs)d %(levelname)s %(message)s',\n format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',\n datefmt='%H:%M:%S')\n else:\n hdlr = logging.FileHandler(LOG_FILE)\n formatter = logging.Formatter('[%(asctime)s]%(levelname)-8s\"%(message)s\"','%Y-%m-%d %a %H:%M:%S') \n hdlr.setFormatter(formatter)\n logger = logging.getLogger()\n logger.addHandler(hdlr)\n logger.setLevel(logging.NOTSET)\n \"\"\"logdir = os.path.dirname(os.path.abspath(LOG_FILE))\n if not os.path.exists(logdir):\n os.makedirs(logdir)\n logging.basicConfig(format='%(datefmt)s, %(name)s %(levelname)s %(message)s',\n datefmt='%H:%M:%S')\n logging.getLogger('sqlalchemy').setLevel(logging.WARNING)\n \"\"\"\n \n\nsetup_logging()\n \n\n\n","sub_path":"demisaucepy/trunk/demisaucepy/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":2002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"544142729","text":"# -*- coding: utf-8 -*-\r\n'''Helper utilities and decorators.'''\r\nfrom flask import flash\r\n\r\ndef flash_errors(form, category=\"warning\"):\r\n '''Flash all errors for a form.'''\r\n for field, errors in form.errors.items():\r\n for error in errors:\r\n flash(\"{0} - {1}\"\r\n .format(getattr(form, field).label.text, error), category)\r\n\r\ndef oxford_commatize(sl):\r\n \"\"\"A function for enforcing the sacred Oxford Comma\r\n\r\n Takes a listed description, that does not respect the Oxford Comma,\r\n and MAKES IT RESPECT THE OXFORD FUCKING COMMA.\r\n\r\n Args:\r\n sl (List[str] or str): String list. That which must respect THE comma \r\n\r\n Returns:\r\n str: An oxford comma'd string. (Eg. 'x,y,z' -> 'x, y, and z')\r\n \"\"\"\r\n if hasattr(sl, \"split\"):\r\n # Splits text by commas, and makes sure there is no preceding spaces\r\n sl = [x.lstrip() for x in sl.split(\",\")]\r\n sl.insert(-1, \"and\")\r\n comma_part = \", \".join(sl[:-2]) if len(sl[:-2]) > 1 else sl[:-2][0] \r\n return comma_part + \", \" + \" \".join(sl[-2:])\r\n","sub_path":"roodkamer/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"38514276","text":"\"\"\"\ngraphpaper.py\n\nPrint \"+\", \"-\", \"|\", \" \" to draw a graph.\n\n\"\"\"\n\nimport sys\n\ndef getInt(ask):\n assert isinstance(ask, str)\n while True:\n try:\n inputvalue = input(ask)\n except EOFError:\n sys.exit(0)\n\n try:\n i = int(inputvalue)\n except ValueError:\n print(\"Sorry,\", inputvalue, \"is not an integer.\")\n continue #Go back up to the word \"while\"\n\n return i\n\n\nr = getInt(\"How many rows of boxes?\\t\")\nc = getInt(\"How many columns of boxes?\\t\")\nrb = getInt(\"How many rows of blanks in each boxes?\\t\")\ncb = getInt(\"How many columns of blanks in each boxes?\\t\")\n\nplus = (\"+\")\ndash = (\"-\")\nbar = (\"|\")\nspace = (\" \")\n\nh = 1\nwhile h <= c:\n \n j = 1\n while j <= r:\n print(plus, end=\"\")\n print(cb*dash, end=\"\")\n j += 1\n print(plus)\n\n l = 1\n while l <= rb:\n i = 1\n while i <= r:\n print(bar, end=\"\")\n print(cb*space, end=\"\")\n i += 1\n print(bar)\n l += 1\n h += 1\n\nm = 1\nwhile m <= r:\n print(plus, end=\"\")\n print(cb*dash, end=\"\")\n m += 1\nprint(plus)\n \nsys.exit(0)\n","sub_path":"week2_graphpaper.py","file_name":"week2_graphpaper.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"117645247","text":"# GFF parser adapted from https://techoverflow.net/2013/11/30/a-simple-gff3-parser-in-python/\n\nfrom collections import namedtuple\nimport gzip\nimport json\n# import urllib.request, urllib.parse, urllib.error\n\ngff_info_fields = [\"contig\", \"source\", \"type\", \"start\", \"end\", \"score\", \"strand\", \"phase\", \"attributes\"]\nclass GTFRecord(namedtuple(\"GTFRecord\", gff_info_fields)):\n @property\n def length(self):\n return self.end - self.start + 1\n\n def __repr__(self):\n row = [self.contig, self.source, self.type, self.start, self.end, self.score, self.strand, self.phase, encode_gtf_attributes(self.attributes)]\n row = [elem if elem else '.' for elem in row]\n return '\\t'.join(map(str, row))\n\n def is_coding(self):\n if self.attributes['gene_type'] != 'protein_coding':\n return False\n if (self.type != 'gene') and (self.attributes['transcript_type'] != 'protein_coding'):\n return False\n return True\n\n def contain_position(self, pos):\n return self.start <= pos <= self.end\n\n def in_upstream_of(self, pos):\n if self.strand == '+':\n return self.end < pos\n elif self.strand == '-':\n return pos < self.start\n\n def in_downstream_of(self, pos):\n if self.strand == '+':\n return pos < self.start\n elif self.strand == '-':\n return self.end < pos\n\ndef encode_gtf_attributes(attributes):\n if not attributes:\n return '.'\n attr_strings = [f'{k} {json.dumps(v)};' for k,v in attributes.items()]\n return ' '.join(attr_strings)\n\ndef parse_gtf(filename, attributes_filter=lambda x: x):\n \"\"\"\n A minimalistic GTF format parser.\n Yields objects that contain info about a single GTF feature.\n\n Supports transparent gzip decompression.\n \"\"\"\n # Parse with transparent decompression\n open_func = gzip.open if filename.endswith(\".gz\") else open\n with open_func(filename, \"rt\", encoding='utf-8') as infile:\n for line in infile:\n if line.startswith(\"#\"): continue\n parts = line.strip().split(\"\\t\")\n # If this fails, the file format is not standard-compatible\n assert len(parts) == len(gff_info_fields)\n assert parts[0] != '.' # contig\n assert parts[2] != '.' # type\n assert parts[3] != '.' # start\n assert parts[4] != '.' # end\n assert parts[6] in {'+', '-'}\n # Normalize data\n normalized_info = {\n \"contig\": parts[0],\n \"source\": None if parts[1] == \".\" else parts[1],\n \"type\": parts[2],\n \"start\": int(parts[3]), # 1-based\n \"end\": int(parts[4]), # 1-based\n \"score\": None if parts[5] == \".\" else float(parts[5]),\n \"strand\": parts[6],\n \"phase\": None if parts[7] == \".\" else parts[7],\n \"attributes\": attributes_filter(parse_gtf_attributes(parts[8]))\n }\n # Alternatively, you can emit the dictionary here, if you need mutability:\n # yield normalizedInfo\n yield GTFRecord(**normalized_info)\n\ndef parse_gtf_attributes(attribute_string):\n \"\"\"Parse the GTF attribute column and return a dict\"\"\"\n if attribute_string == \".\":\n return {}\n ret = {}\n multivalue_keys = {'tag', 'ont'}\n for attribute in attribute_string.strip().rstrip(\";\").split(\";\"):\n key, value = attribute.strip().split(\" \")\n\n if value[0] == '\"':\n val = value[1:-1]\n else:\n val = int(value)\n\n if key not in multivalue_keys:\n if key not in ret:\n ret[key] = val\n else:\n raise Exception(f'Key `{key}` already in attributes')\n else:\n if key not in ret:\n ret[key] = []\n ret[key].append(val)\n return ret\n","sub_path":"gtf_parser.py","file_name":"gtf_parser.py","file_ext":"py","file_size_in_byte":3917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"233336445","text":"import math\nimport numpy as np\nfrom collections import Counter\n# Note: please don't add any new package, you should solve this problem using only the packages above.\n#-------------------------------------------------------------------------\n'''\n Part 1: Decision Tree (with Discrete Attributes) -- 40 points --\n In this problem, you will implement the decision tree method for classification problems.\n You could test the correctness of your code by typing `nosetests -v test1.py` in the terminal.\n'''\n \n#-----------------------------------------------\nclass Node:\n '''\n Decision Tree Node (with discrete attributes)\n Inputs: \n X: the data instances in the node, a numpy matrix of shape p by n.\n Each element can be int/float/string.\n Here n is the number data instances in the node, p is the number of attributes.\n Y: the class labels, a numpy array of length n.\n Each element can be int/float/string.\n i: the index of the attribute being tested in the node, an integer scalar \n C: the dictionary of attribute values and children nodes. \n Each (key, value) pair represents an attribute value and its corresponding child node.\n isleaf: whether or not this node is a leaf node, a boolean scalar\n p: the label to be predicted on the node (i.e., most common label in the node).\n '''\n def __init__(self,X,Y, i=None,C=None, isleaf= False,p=None):\n self.X = X\n self.Y = Y\n self.i = i\n self.C = C\n self.isleaf = isleaf\n self.p = p\n\n#-----------------------------------------------\nclass Tree(object):\n '''\n Decision Tree (with discrete attributes). \n We are using ID3(Iterative Dichotomiser 3) algorithm. So this decision tree is also called ID3.\n '''\n #--------------------------\n @staticmethod\n def entropy(Y):\n '''\n Compute the entropy of a list of values.\n Input:\n Y: a list of values, a numpy array of int/float/string values.\n Output:\n e: the entropy of the list of values, a float scalar\n Hint: you could use collections.Counter.\n '''\n #########################################\n ## INSERT YOUR CODE HERE\n label = Counter(Y)\n value = []\n for k,v in label.items():\n value.append(v)\n sum_v = sum(value)\n raw_e = float()\n if sum_v == 0:\n e = 0\n else:\n for v in value:\n raw_e += - v*math.log(v/sum_v, 2)\n\n e = raw_e/sum_v\n #########################################\n return e \n \n \n \n #--------------------------\n @staticmethod\n def conditional_entropy(Y,X):\n '''\n Compute the conditional entropy of y given x. The conditional entropy H(Y|X) means average entropy of children nodes, given attribute X. Refer to https://en.wikipedia.org/wiki/Information_gain_in_decision_trees\n Input:\n X: a list of values , a numpy array of int/float/string values. The size of the array means the number of instances/examples. X contains each instance's attribute value. \n Y: a list of values, a numpy array of int/float/string values. Y contains each instance's corresponding target label. For example X[0]'s target label is Y[0]\n Output:\n ce: the conditional entropy of y given x, a float scalar\n '''\n #########################################\n ## INSERT YOUR CODE HERE\n\n label = Counter(X)\n child_dict = {}\n for k,v in label.items():\n child_dict[k] = []\n for i in range(len(X)):\n child_dict[X[i]].append(Y[i])\n ce = 0\n for k in child_dict:\n child_e = Tree.entropy(child_dict[k])\n ce += len(child_dict[k]) * child_e / len(Y)\n #########################################\n return ce \n \n \n \n #--------------------------\n @staticmethod\n def information_gain(Y,X):\n '''\n Compute the information gain of y after spliting over attribute x\n InfoGain(Y,X) = H(Y) - H(Y|X) \n Input:\n X: a list of values, a numpy array of int/float/string values.\n Y: a list of values, a numpy array of int/float/string values.\n Output:\n g: the information gain of y after spliting over x, a float scalar\n '''\n #########################################\n ## INSERT YOUR CODE HERE\n g = Tree.entropy(Y) - Tree.conditional_entropy(Y,X)\n #########################################\n return g\n\n\n #--------------------------\n @staticmethod\n def best_attribute(X,Y):\n '''\n Find the best attribute to split the node. \n Here we use information gain to evaluate the attributes. \n If there is a tie in the best attributes, select the one with the smallest index.\n Input:\n X: the feature matrix, a numpy matrix of shape p by n. \n Each element can be int/float/string.\n Here n is the number data instances in the node, p is the number of attributes.\n Y: the class labels, a numpy array of length n. Each element can be int/float/string.\n Output:\n i: the index of the attribute to split, an integer scalar\n '''\n #########################################\n ## INSERT YOUR CODE HERE\n max_gain = 0\n i = 0\n for j in range(len(X)):\n test_j = X[j,:]\n current_gain = Tree.information_gain(test_j, Y)\n if current_gain > max_gain:\n max_gain = current_gain\n i = j\n #########################################\n return i\n\n \n #--------------------------\n @staticmethod\n def split(X,Y,i):\n '''\n Split the node based upon the i-th attribute.\n (1) split the matrix X based upon the values in i-th attribute\n (2) split the labels Y based upon the values in i-th attribute\n (3) build children nodes by assigning a submatrix of X and Y to each node\n (4) build the dictionary to combine each value in the i-th attribute with a child node.\n \n Input:\n X: the feature matrix, a numpy matrix of shape p by n.\n Each element can be int/float/string.\n Here n is the number data instances in the node, p is the number of attributes.\n Y: the class labels, a numpy array of length n.\n Each element can be int/float/string.\n i: the index of the attribute to split, an integer scalar\n Output:\n C: the dictionary of attribute values and children nodes. \n Each (key, value) pair represents an attribute value and its corresponding child node.\n '''\n #########################################\n ## INSERT YOUR CODE HERE\n C = dict()\n label = Counter(X[i])\n all_attr = []\n for attr,times in label.items():\n all_attr.append(attr)\n for k in all_attr:\n child_mat = []\n child_label = []\n for j in range(len(X[i])):\n if X[i][j] == k:\n child_mat.append(X[:,j])\n child_label.append(Y[j])\n C[k] = Node(X = np.transpose(np.array(child_mat)), Y = np.array(child_label))\n\n #########################################\n return C\n\n #--------------------------\n @staticmethod\n def stop1(Y):\n '''\n Test condition 1 (stop splitting): whether or not all the instances have the same label. \n \n Input:\n Y: the class labels, a numpy array of length n.\n Each element can be int/float/string.\n Output:\n s: whether or not Conidtion 1 holds, a boolean scalar. \n True if all labels are the same. Otherwise, false.\n '''\n #########################################\n ## INSERT YOUR CODE HERE\n label = Counter(np.array(Y))\n s = False\n if len(label) == 1:\n s = True\n\n\n \n #########################################\n return s\n \n #--------------------------\n @staticmethod\n def stop2(X):\n '''\n Test condition 2 (stop splitting): whether or not all the instances have the same attribute values. \n Input:\n X: the feature matrix, a numpy matrix of shape p by n.\n Each element can be int/float/string.\n Here n is the number data instances in the node, p is the number of attributes.\n Output:\n s: whether or not Conidtion 2 holds, a boolean scalar. \n '''\n #########################################\n ## INSERT YOUR CODE HERE\n s = True\n for i in range(len(X)):\n if not Tree.stop1(X[i]):\n s = False\n\n \n #########################################\n return s\n \n \n #--------------------------\n @staticmethod\n def most_common(Y):\n '''\n Get the most-common label from the list Y. \n Input:\n Y: the class labels, a numpy array of length n.\n Each element can be int/float/string.\n Here n is the number data instances in the node.\n Output:\n y: the most common label, a scalar, can be int/float/string.\n '''\n #########################################\n ## INSERT YOUR CODE HERE\n label = Counter(Y)\n max_counter = 0\n for k,v in label.items():\n if v > max_counter:\n max_counter = v\n y = k\n #########################################\n return y\n \n \n \n #--------------------------\n @staticmethod\n def build_tree(t):\n '''\n Recursively build tree nodes.\n Input:\n t: a node of the decision tree, without the subtree built.\n t.X: the feature matrix, a numpy float matrix of shape n by p.\n Each element can be int/float/string.\n Here n is the number data instances, p is the number of attributes.\n t.Y: the class labels of the instances in the node, a numpy array of length n.\n t.C: the dictionary of attribute values and children nodes. \n Each (key, value) pair represents an attribute value and its corresponding child node.\n '''\n #########################################\n ## INSERT YOUR CODE HERE\n t.p = Tree.most_common(t.Y)\n if Tree.stop1(t.Y):\n t.isleaf = True\n elif Tree.stop2(t.X):\n t.isleaf = True\n else:\n t.i = Tree.best_attribute(t.X, t.Y)\n t.C = Tree.split(t.X, t.Y, t.i)\n for child in t.C.values():\n Tree.build_tree(child)\n #########################################\n \n \n #--------------------------\n @staticmethod\n def train(X, Y):\n '''\n Given a training set, train a decision tree. \n Input:\n X: the feature matrix, a numpy matrix of shape p by n.\n Each element can be int/float/string.\n Here n is the number data instances in the training set, p is the number of attributes.\n Y: the class labels, a numpy array of length n.\n Each element can be int/float/string.\n Output:\n t: the root of the tree.\n '''\n #########################################\n ## INSERT YOUR CODE HERE\n t = Node(X= X, Y= Y)\n Tree.build_tree(t)\n #########################################\n return t\n \n \n \n #--------------------------\n @staticmethod\n def inference(t,x):\n '''\n Given a decision tree and one data instance, infer the label of the instance recursively.\n Input:\n t: the root of the tree.\n x: the attribute vector, a numpy vectr of shape p.\n Each att ribute value canbe int/float/string.\n Output:\n y: the class labels, a numpy array of length n.\n Each element can be int/float/string.\n '''\n #########################################\n ## INSERT YOUR CODE HERE\n current_node = t\n while 1:\n y = current_node.p\n if current_node.isleaf == True or x[current_node.i] not in current_node.C.keys():\n break\n else:\n current_node = current_node.C[x[current_node.i]]\n #########################################\n return y\n \n #--------------------------\n @staticmethod\n def predict(t,X):\n '''\n Given a decision tree and a dataset, predict the labels on the dataset. \n Input:\n t: the root of the tree.\n X: the feature matrix, a numpy matrix of shape p by n.\n Each element can be int/float/string.\n Here n is the number data instances in the dataset, p is the number of attributes.\n Output:\n Y: the class labels, a numpy array of length n.\n Each element can be int/float/string.\n '''\n #########################################\n ## INSERT YOUR CODE HERE\n raw_y = []\n for i in range(len(X[0])):\n y = Tree.inference(t, X[:,i])\n raw_y.append(y)\n Y = np.array(raw_y)\n\n\n\n #########################################\n return Y\n\n\n\n #--------------------------\n @staticmethod\n def load_dataset(filename = 'data1.csv'):\n '''\n Load dataset 1 from the CSV file: 'data1.csv'. \n The first row of the file is the header (including the names of the attributes)\n In the remaining rows, each row represents one data instance.\n The first column of the file is the label to be predicted.\n In remaining columns, each column represents an attribute.\n Input:\n filename: the filename of the dataset, a string.\n Output:\n X: the feature matrix, a numpy matrix of shape p by n.\n Each element can be int/float/string.\n Here n is the number data instances in the dataset, p is the number of attributes.\n Y: the class labels, a numpy array of length n.\n Each element can be int/float/string.\n '''\n #########################################\n ## INSERT YOUR CODE HERE\n\n with open(filename, 'r') as f:\n head_flag = True\n raw_x = []\n raw_y = []\n for line in f:\n elements = line.strip().split(',')\n if head_flag == True:\n head_flag = False\n head = np.array(elements)\n continue\n raw_y.append(elements[0])\n raw_x.append(elements[1:])\n X = np.transpose(np.array(raw_x))\n Y = np.array(raw_y)\n #########################################\n return X,Y","sub_path":"cs539-machine learning course/simple_project/decision_tree/decision_tree.py","file_name":"decision_tree.py","file_ext":"py","file_size_in_byte":15618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"146204051","text":"from jedi.models.consts import ClassType\nfrom jedi.libs.course import get_all_lesson_ids\nfrom jedi.libs.course import fetch_lesson_info\nfrom jedi.libs.course import RequestCourseAPIError\n\n\ndef validate_create_onlineclass_request(request):\n course_id = request.course_id\n lesson_id = request.lesson_id\n student_id = request.student_id\n timeslot_id = request.timeslot_id\n period = request.period\n\n params = [course_id, student_id, timeslot_id]\n if lesson_id:\n params.append(lesson_id)\n\n for para in params:\n p = int(para)\n if p <= 0:\n raise ValueError\n\n period = int(period)\n if period < 0:\n raise ValueError\n\n provider = request.provider\n\n if provider is None:\n raise ValueError\n\n type_ = request.type\n\n if type_ in (ClassType.none.value, ClassType.open_class.value):\n raise ValueError\n\n\ndef validate_lesson_info(course_id, lesson_id):\n try:\n fetched_lesson_ids = get_all_lesson_ids(course_id)\n if not fetched_lesson_ids:\n return False\n if str(lesson_id) not in fetched_lesson_ids:\n return False\n fetch_lesson_info(lesson_id)\n except RequestCourseAPIError:\n return False\n return True\n","sub_path":"jedi/jedi/grpc/service/validator.py","file_name":"validator.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"32846808","text":"'''\nDescripttion: \nversion: \nAuthor: Liang Anqing\nDate: 2020-08-09 16:42:38\nLastEditors: Liang Anqing\nLastEditTime: 2020-08-09 17:01:22\n'''\n'''\n题目描述\n在你面前有一个n阶的楼梯(n>=100且n<500),你一步只能上1阶或3阶。\n请问计算出你可以采用多少种不同的方式爬完这个楼梯(到最后一层为爬完)。\n(注意超大数据)\n输入描述:\n\n一个正整数,表示这个楼梯一共有多少阶\n\n输出描述:\n\n一个正整数,表示有多少种不同的方式爬完这个楼梯\n\n示例1\n输入\n复制\n\n100\n\n输出\n复制\n\n24382819596721629\n\n'''\ndef solution(n):\n dp=[0 for i in range(n+1)]\n if n<=3:\n return 1 if b<=2 else 2\n dp[1]=1\n dp[2]=1\n dp[3]=2\n for i in range(4,n+1):\n dp[i]=dp[i-1]+dp[i-3]\n return dp[n]\nif __name__=='__main__':\n n=int(input())\n print(solution(n))","sub_path":"XM37.爬楼梯2.py","file_name":"XM37.爬楼梯2.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"107436812","text":"#!/usr/bin/python\n\nfrom ConfigParser import RawConfigParser\nfrom email.mime.base import MIMEBase\nimport email\nimport email.message\nimport re\nimport GnuPG\nimport smtplib\nimport sys\nimport syslog\n\n# Read configuration from /etc/gpg-mailgate.conf\n_cfg = RawConfigParser()\n_cfg.read('/etc/gpg-mailgate.conf')\ncfg = dict()\nfor sect in _cfg.sections():\n\tcfg[sect] = dict()\n\tfor (name, value) in _cfg.items(sect):\n\t\tcfg[sect][name] = value\n\ndef log(msg):\n\tif cfg.has_key('logging') and cfg['logging'].has_key('file'):\n\t\tif cfg['logging']['file'] == \"syslog\":\n\t\t\tsyslog.syslog(syslog.LOG_INFO | syslog.LOG_MAIL, msg)\n\t\telse:\n\t\t\tlogfile = open(cfg['logging']['file'], 'a')\n\t\t\tlogfile.write(msg + \"\\n\")\n\t\t\tlogfile.close()\n\nverbose=cfg.has_key('logging') and cfg['logging'].has_key('verbose') and cfg['logging']['verbose'] == 'yes'\n\n# Read e-mail from stdin\nraw = sys.stdin.read()\nraw_message = email.message_from_string( raw )\nfrom_addr = raw_message['From']\nto_addrs = sys.argv[1:]\nif verbose:\n\tlog(\"to_addrs: '%s'\" % \"', '\".join(to_addrs))\n\nencrypted_to_addrs = list()\nif raw_message.has_key('X-GPG-Encrypt-Cc'):\n\tencrypted_to_addrs.extend( [e[1] for e in email.utils.getaddresses([raw_message['X-GPG-Encrypt-Cc']])] )\n\tdel raw_message['X-GPG-Encrypt-Cc']\n\ndef send_msg( message, recipients = None ):\n\tif recipients == None:\n\t\trecipients = to_addrs\n\tlog(\"Sending email to: <%s>\" % '> <'.join( recipients ))\n\trelay = (cfg['relay']['host'], int(cfg['relay']['port']))\n\tsmtp = smtplib.SMTP(relay[0], relay[1])\n\tsmtp.sendmail( from_addr, recipients, message.as_string() )\n\ndef encrypt_payload( payload, gpg_to_cmdline ):\n\traw_payload = payload.get_payload(decode=True)\n\tif \"-----BEGIN PGP MESSAGE-----\" in raw_payload and \"-----END PGP MESSAGE-----\" in raw_payload:\n\t\treturn payload\n\tgpg = GnuPG.GPGEncryptor( cfg['gpg']['keyhome'], gpg_to_cmdline, payload.get_content_charset() )\n\tgpg.update( raw_payload )\n\tpayload.set_payload( gpg.encrypt() )\n\tif payload['Content-Disposition']:\n\t\tpayload.replace_header( 'Content-Disposition', re.sub(r'filename=\"([^\"]+)\"', r'filename=\"\\1.pgp\"', payload['Content-Disposition']) )\n\tif payload['Content-Type']:\n\t\tpayload.replace_header( 'Content-Type', re.sub(r'name=\"([^\"]+)\"', r'name=\"\\1.pgp\"', payload['Content-Type']) )\n\t\tif 'name=\"' in payload['Content-Type']:\n\t\t\tpayload.replace_header( 'Content-Type', re.sub(r'^[a-z/]+;', r'application/octet-stream;', payload['Content-Type']) )\n\t\t\tpayload.set_payload( \"\\n\".join( filter( lambda x:re.search(r'^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$',x), payload.get_payload().split(\"\\n\") ) ) )\n\treturn payload\n\ndef encrypt_all_payloads( payloads, gpg_to_cmdline ):\n\tencrypted_payloads = list()\n\tif type( payloads ) == str:\n\t\tmsg = email.message.Message()\n\t\tmsg.set_payload( payloads )\n\t\treturn encrypt_payload( msg, gpg_to_cmdline ).as_string()\n\tfor payload in payloads:\n\t\tif( type( payload.get_payload() ) == list ):\n\t\t\tencrypted_payloads.append( encrypt_all_payloads( payload.get_payload(), gpg_to_cmdline ) )\n\t\telse:\n\t\t\tencrypted_payloads.append( [encrypt_payload( payload, gpg_to_cmdline )] )\n\treturn sum(encrypted_payloads, [])\n\ndef get_msg( message ):\n\tif not message.is_multipart():\n\t\treturn message.get_payload()\n\treturn '\\n\\n'.join( [str(m) for m in message.get_payload()] )\n\nkeys = GnuPG.public_keys( cfg['gpg']['keyhome'] )\ngpg_to = list()\nungpg_to = list()\nfor enc in encrypted_to_addrs:\n\tdomain = enc.split('@')[1]\n\tif domain in cfg['default']['domains'].split(','):\n\t\tif enc in keys:\n\t\t\tgpg_to.append( (enc, enc) )\n\t\telif cfg.has_key('keymap') and cfg['keymap'].has_key(enc):\n\t\t\tgpg_to.append( (enc, cfg['keymap'][enc]) )\n\t\telse:\n\t\t\tungpg_to.append(enc);\n\t\t\t\nfor to in to_addrs:\n\tdomain = to.split('@')[1]\n\tif domain in cfg['default']['domains'].split(','):\n\t\tif to in keys:\n\t\t\tif verbose:\n\t\t\t\tlog(\"Found public key for '%s' on keyring.\" % to)\n\t\t\tgpg_to.append( (to, to) )\n\t\telif cfg.has_key('keymap') and cfg['keymap'].has_key(to):\n\t\t\tif verbose:\n\t\t\t\tlog(\"Found public key for '%s' in keymap (%s).\" % (to, cfg['keymap'][to]))\n\t\t\tgpg_to.append( (to, cfg['keymap'][to]) )\n\t\telse:\n\t\t\tif verbose:\n\t\t\t\tlog(\"Found no public key for '%s'.\" % to)\n\t\t\tungpg_to.append(to);\n\telse:\n\t\tif verbose:\n\t\t\tlog(\"Recipient (%s) not in domain list.\" % to)\n\t\tungpg_to.append(to)\n\nif gpg_to == list():\n\tif cfg['default'].has_key('add_header') and cfg['default']['add_header'] == 'yes':\n\t\traw_message['X-GPG-Mailgate'] = 'Not encrypted, public key not found'\n\tif verbose:\n\t\tlog(\"No encrypted recipients.\")\n\tsend_msg( raw_message )\n\texit()\n\nif ungpg_to != list():\n\tsend_msg( raw_message, ungpg_to )\n\nlog(\"Encrypting email to: %s\" % ' '.join( map(lambda x: x[0], gpg_to) ))\n\nif cfg['default'].has_key('add_header') and cfg['default']['add_header'] == 'yes':\n\traw_message['X-GPG-Mailgate'] = 'Encrypted by GPG Mailgate'\n\ngpg_to_cmdline = list()\ngpg_to_smtp = list()\nfor rcpt in gpg_to:\n\tgpg_to_smtp.append(rcpt[0])\n\tgpg_to_cmdline.extend(rcpt[1].split(','))\n\nencrypted_payloads = encrypt_all_payloads( raw_message.get_payload(), gpg_to_cmdline )\nraw_message.set_payload( encrypted_payloads )\n\nsend_msg( raw_message, gpg_to_smtp )\n","sub_path":"gpg-mailgate.py","file_name":"gpg-mailgate.py","file_ext":"py","file_size_in_byte":5123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"202887603","text":"import torch\nimport random\nimport numpy as np\nimport networkx as nx\nfrom torch_geometric_temporal.nn import ChebConvAtt\nfrom torch_geometric.transforms import LaplacianLambdaMax\nfrom torch_geometric.data import Data\n\ndef create_mock_data(number_of_nodes, edge_per_node, in_channels):\n \"\"\"\n Creating a mock feature matrix and edge index.\n \"\"\"\n graph = nx.watts_strogatz_graph(number_of_nodes, edge_per_node, 0.5)\n edge_index = torch.LongTensor(np.array([edge for edge in graph.edges()]).T)\n X = torch.FloatTensor(np.random.uniform(-1, 1, (number_of_nodes, in_channels)))\n return X, edge_index\n\ndef create_mock_edge_weight(edge_index):\n \"\"\"\n Creating a mock edge weight tensor.\n \"\"\"\n return torch.FloatTensor(np.random.uniform(0, 1, (edge_index.shape[1])))\n\ndef create_mock_target(number_of_nodes, number_of_classes):\n \"\"\"\n Creating a mock target vector.\n \"\"\"\n return torch.LongTensor([random.randint(0, number_of_classes-1) for node in range(number_of_nodes)])\n\nnode_count = 307\nnum_classes = 10\nedge_per_node = 15\n\n\nlen_input = 12\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nnode_features = 2\nK = 3\nnb_chev_filter = 64\nbatch_size = 32\n\nx, edge_index = create_mock_data(node_count, edge_per_node, node_features)\nmodel = ChebConvAtt(node_features, nb_chev_filter, K)\nspatial_attention = torch.rand(batch_size,node_count,node_count)\nspatial_attention = torch.nn.functional.softmax(spatial_attention, dim=1)\nmodel.train()\nT = len_input\nx_seq = torch.zeros([batch_size,node_count, node_features,T]).to(device)\ntarget_seq = torch.zeros([batch_size,node_count,T]).to(device)\nfor b in range(batch_size):\n for t in range(T):\n x, edge_index = create_mock_data(node_count, edge_per_node, node_features)\n x_seq[b,:,:,t] = x\n target = create_mock_target(node_count, num_classes)\n target_seq[b,:,t] = target\nshuffle = True\ntrain_dataset = torch.utils.data.TensorDataset(x_seq, target_seq)\n\ntrain_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=shuffle)\nfor batch_data in train_loader:\n encoder_inputs, labels = batch_data\n data = Data(edge_index=edge_index, edge_attr=None, num_nodes=node_count)\n lambda_max = LaplacianLambdaMax()(data).lambda_max\n outputs = []\n for time_step in range(T):\n outputs.append(torch.unsqueeze(model(encoder_inputs[:,:,:,time_step], edge_index, spatial_attention, lambda_max = lambda_max), -1))\n spatial_gcn = torch.nn.functional.relu(torch.cat(outputs, dim=-1)) # (b,N,F,T) # (b,N,F,T)","sub_path":"examples/chebconvatt_example.py","file_name":"chebconvatt_example.py","file_ext":"py","file_size_in_byte":2563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"5454227","text":"# copy from https://github.com/riantkb/typical90_python\n\nimport sys\n\ninput = sys.stdin.readline\n\n\n\ndef main():\n a,b,c = map(int, input().split())\n print(\"Yes\" if a < c **b else \"No\")\n\nif __name__ == '__main__':\n main()","sub_path":"typical90_20.py","file_name":"typical90_20.py","file_ext":"py","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"277418325","text":"# cf. book 7.7 exercises 11-13\r\n\r\ndef yearLength(year):\r\n if year % 400 == 0:\r\n return 366\r\n elif year % 100 == 0:\r\n return 365\r\n elif year % 4 == 0:\r\n return 366\r\n else:\r\n return 365\r\n\r\ndef monthLength(year,month):\r\n if month == 2 and yearLength(year) == 366:\r\n return 29\r\n elif month == 2:\r\n return 28\r\n elif month in [4,6,9,11]:\r\n return 30\r\n else:\r\n return 31\r\n\r\ndef dateDays(year,month,day):\r\n days = 0\r\n for y in range(year):\r\n days = days + yearLength(y)\r\n for m in range(1,month):\r\n days = days + monthLength(year,m)\r\n return days + day\r\n\r\ndef dateDiff(year1,month1,day1,year2,month2,day2):\r\n diff = dateDays(year2,month2,day2) - dateDays(year1,month1,day1)\r\n return diff\r\n\r\n#### new stuff added for Lecture 6\r\n\r\ndef checkDate(year,month,day):\r\n return (0 < month <= 12) and (0 < day <= monthLength(year,month))\r\n\r\ndef checkDate_modified(year,month,day,hour):\r\n return (0 < month <= 12) and (0 < day <= monthLength(year,month)) and (1 <= hour <= 24)\r\n\r\ndef inputDate(prompt):\r\n date = (input(prompt + \", format år,månad,dag: \")).split(',')\r\n if len(date) == 3 and date[0].isdigit() and date[1].isdigit() and date[2].isdigit():\r\n year,month,day = int(date[0]),int(date[1]),int(date[2])\r\n if checkDate(year,month,day):\r\n return year,month,day\r\n else:\r\n print(\"ogiltigt datum\")\r\n return inputDate(prompt)\r\n else:\r\n print(\"försök igen, tre tal\")\r\n return inputDate(prompt)\r\n\r\n# Modifierad för QA6\r\ndef input_date_modified(prompt):\r\n date = (input(prompt + \", format år,månad,dag,timme: \")).split(',')\r\n if len(date) == 4 and date[0].isdigit() and date[1].isdigit() and date[2].isdigit() and date[3].isdigit():\r\n year,month,day,hour = int(date[0]),int(date[1]),int(date[2]),int(date[3])\r\n if checkDate_modified(year,month,day,hour):\r\n return year,month,day,hour\r\n else:\r\n print(\"ogiltigt datum\")\r\n return input_date_modified(prompt)\r\n else:\r\n print(\"försök igen, fyra tal\")\r\n return input_date_modified(prompt)\r\n\r\n#### end new stuff\r\n\r\n### old versions step by step, not used in the actual main()\r\ndef inputDate1(date):\r\n year,month,day = eval(input(\"Ange \" + date + \" i format år,månad,dag: \"))\r\n return year,month,day\r\n\r\ndef inputDate2(prompt):\r\n year,month,day = input(prompt+\": \").split(',')\r\n return int(year),int(month),int(day)\r\n\r\ndef inputDate3(prompt):\r\n date = (input(prompt + \": \")).split(',')\r\n if len(date) == 3:\r\n return int(date[0]),int(date[1]),int(date[2])\r\n else:\r\n print(\"ogiltigt datum\")\r\n return inputDate3(prompt)\r\n\r\ndef inputDate4(prompt):\r\n date = (input(prompt + \": \")).split(',')\r\n if (len(date) == 3\r\n and date[0].isdigit()\r\n and date[1].isdigit()\r\n and date[2].isdigit()):\r\n return int(date[0]),int(date[1]),int(date[2])\r\n else:\r\n print(\"ogiltigt datum\")\r\n return inputDate4(prompt)\r\n##########\r\n\r\n\r\ndef main():\r\n try:\r\n #year1,month1,day1 = inputDate(\"startdatum\")\r\n #year2,month2,day2 = inputDate(\"slutdatum\")\r\n #print(\"Skillnaden är\", dateDiff(year1,month1,day1,year2,month2,day2))\r\n year1,month1,day1,hour1 = input_date_modified(\"startdatum\")\r\n year2,month2,day2,hour2 = input_date_modified(\"slutdatum\")\r\n print(\"Skillnaden är {}\".format(dateDiff(year1,month1,day1,year2,month2,day2)*24+(hour2-hour1))) # Ger skillnaden i timmar\r\n except KeyboardInterrupt:\r\n print()\r\n print(\"om du vill lämna programmet, tryck ^D\")\r\n main()\r\n except:\r\n print()\r\n print(\"Ok, hejdå\")\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"summer-2020/QAs_Victor/QA6/datediff.py","file_name":"datediff.py","file_ext":"py","file_size_in_byte":3822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"64982275","text":"def find_duplicates(lst):\n \"\"\"\n Function to find duplicates in a given lst\n :param lst: A list of integers\n :return: A list of duplicate integers with no repetition\n \"\"\"\n\n result = set() # A list to store duplicates\n\n # Write your code here!\n visited = set()\n for n in lst:\n if n in visited:\n result.add(n)\n visited.add(n)\n result = list(result)\n return result\n","sub_path":"Python/Easy/findDuplicates.py","file_name":"findDuplicates.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"224388448","text":"from os import environ\n\nfrom troposphere import GetAtt, Ref, Tags, Template, Join\nfrom troposphere.ec2 import (Route, VPCGatewayAttachment, SubnetRouteTableAssociation, Subnet, RouteTable, VPC,\n InternetGateway, EIP, NatGateway, VPCEndpoint)\n\nfrom libs.general import connect, validate_template, push_cloudformation\n\nenviron[\"http_proxy\"] = \"\"\nenviron[\"https_proxy\"] = \"\"\n\nref_region = Ref('AWS::Region')\nref_stack_name = Ref('AWS::StackName')\ncost_allocation_tag = 'Base infrastructure'\n\nt = Template()\nt.add_description('Test VPC')\nt.add_version('2010-09-09')\n\nVPC = t.add_resource(\n VPC(\n 'VPC',\n CidrBlock='10.0.0.0/16',\n EnableDnsHostnames=True,\n EnableDnsSupport=True,\n Tags=Tags(\n Cost_allocation=cost_allocation_tag)))\n\npublic_subnet_1 = t.add_resource(\n Subnet(\n 'PublicSubnet1',\n CidrBlock='10.0.0.0/24',\n AvailabilityZone='eu-central-1a',\n VpcId=Ref(VPC),\n MapPublicIpOnLaunch=True,\n Tags=Tags(\n Cost_allocation=cost_allocation_tag)))\n\npublic_subnet_2 = t.add_resource(\n Subnet(\n 'PublicSubnet2',\n CidrBlock='10.0.1.0/24',\n AvailabilityZone='eu-central-1b',\n VpcId=Ref(VPC),\n MapPublicIpOnLaunch=True,\n Tags=Tags(\n Cost_allocation=cost_allocation_tag)))\n\nprivate_subnet_1 = t.add_resource(\n Subnet(\n 'PrivateSubnet1',\n CidrBlock='10.0.2.0/24',\n AvailabilityZone='eu-central-1a',\n VpcId=Ref(VPC),\n MapPublicIpOnLaunch=False,\n Tags=Tags(\n Cost_allocation=cost_allocation_tag)))\n\nprivate_subnet_2 = t.add_resource(\n Subnet(\n 'PrivateSubnet2',\n CidrBlock='10.0.3.0/24',\n AvailabilityZone='eu-central-1b',\n VpcId=Ref(VPC),\n MapPublicIpOnLaunch=False,\n Tags=Tags(\n Cost_allocation=cost_allocation_tag)))\n\ninternet_gateway = t.add_resource(\n InternetGateway(\n 'InternetGateway',\n Tags=Tags(\n Cost_allocation=cost_allocation_tag)))\n\nattachment_internet_gateway = t.add_resource(\n VPCGatewayAttachment(\n 'VPCGatewayAttachment',\n VpcId=Ref(VPC),\n InternetGatewayId=Ref(internet_gateway)))\n\nnat_gateway_eip_1 = t.add_resource(EIP(\n 'NATGatewayEIP1',\n Domain=\"VPC\",\n))\n\nnat_gateway_eip_2 = t.add_resource(EIP(\n 'NATGatewayEIP2',\n Domain=\"VPC\",\n))\n\nnat_gateway_1 = t.add_resource(NatGateway(\n 'NATGateway1',\n AllocationId=GetAtt(nat_gateway_eip_1, 'AllocationId'),\n SubnetId=Ref(public_subnet_1),\n))\n\nnat_gateway_2 = t.add_resource(NatGateway(\n 'NATGateway2',\n AllocationId=GetAtt(nat_gateway_eip_2, 'AllocationId'),\n SubnetId=Ref(public_subnet_2),\n))\n\npublic_route_table = t.add_resource(RouteTable(\n 'PublicRouteTable',\n VpcId=Ref(VPC),\n Tags=Tags(\n Cost_allocation=cost_allocation_tag)\n))\n\npublic_route_association_1 = t.add_resource(SubnetRouteTableAssociation(\n 'PublicRouteAssociation1',\n SubnetId=Ref(public_subnet_1),\n RouteTableId=Ref(public_route_table),\n\n))\n\npublic_route_association_2 = t.add_resource(SubnetRouteTableAssociation(\n 'PublicRouteAssociation2',\n SubnetId=Ref(public_subnet_2),\n RouteTableId=Ref(public_route_table),\n))\n\ndefault_public_route = t.add_resource(Route(\n 'PublicDefaultRoute',\n RouteTableId=Ref(public_route_table),\n DestinationCidrBlock='0.0.0.0/0',\n GatewayId=Ref(internet_gateway),\n))\n\nprivate_route_table_1 = t.add_resource(RouteTable(\n 'PrivateRouteTable1',\n VpcId=Ref(VPC),\n Tags=Tags(\n Cost_allocation=cost_allocation_tag)\n))\n\nprivate_route_table_2 = t.add_resource(RouteTable(\n 'PrivateRouteTable2',\n VpcId=Ref(VPC),\n Tags=Tags(\n Cost_allocation=cost_allocation_tag)\n))\n\nprivate_route_association_1 = t.add_resource(SubnetRouteTableAssociation(\n 'PrivateRouteToSubnet1',\n SubnetId=Ref(private_subnet_1),\n RouteTableId=Ref(private_route_table_1),\n))\n\nprivate_route_association_2 = t.add_resource(SubnetRouteTableAssociation(\n 'PrivateRouteToSubnet2',\n SubnetId=Ref(private_subnet_2),\n RouteTableId=Ref(private_route_table_2),\n))\n\nnat_route_1 = t.add_resource(Route(\n 'NATRoute1',\n RouteTableId=Ref(private_route_table_1),\n DestinationCidrBlock='0.0.0.0/0',\n NatGatewayId=Ref(nat_gateway_1),\n))\n\nnat_route_2 = t.add_resource(Route(\n 'NATRoute2',\n RouteTableId=Ref(private_route_table_2),\n DestinationCidrBlock='0.0.0.0/0',\n NatGatewayId=Ref(nat_gateway_2),\n))\n\ns3_endpoint = t.add_resource(VPCEndpoint(\n \"S3VpcEndpoint\",\n RouteTableIds=[Ref(private_route_table_1), Ref(private_route_table_2)],\n ServiceName=Join(\"\", [\"com.amazonaws.\", Ref(\"AWS::Region\"), \".s3\"]),\n VpcId=Ref(VPC),\n))\n\ntemplate = t.to_json()\nclient = connect('eu-central-1')\nvalidate_template(client, template)\npush_cloudformation(client, template, 'MyTestVPC')\n","sub_path":"vpc.py","file_name":"vpc.py","file_ext":"py","file_size_in_byte":4592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"479299484","text":"# Pendulum - Index 1 DAE\r\nfrom gekko import GEKKO\r\nimport numpy as np\r\n\r\nmass = 1\r\ng = 9.81\r\ns = 1\r\n\r\nm = GEKKO()\r\nx = m.Var(0)\r\ny = m.Var(-s)\r\nv = m.Var(1)\r\nw = m.Var(0)\r\nlam = m.Var(mass*(1+s*g)/2*s**2)\r\n\r\nm.Equation(mass*(v**2+w**2-g*y)-2*lam*(x**2+y**2)==0)\r\nm.Equation(x.dt()==v)\r\nm.Equation(y.dt()==w)\r\nm.Equation(mass*v.dt()==-2*x*lam)\r\nm.Equation(mass*w.dt()==-mass*g - 2*y*lam)\r\n\r\nm.time = np.linspace(0,2*np.pi,100)\r\nm.options.IMODE=4\r\nm.options.NODES=3\r\nm.solve(disp=False)\r\n\r\nimport matplotlib.pyplot as plt\r\nplt.figure(figsize=(10,5))\r\nplt.subplot(3,1,1)\r\nplt.plot(m.time,x.value,label='x')\r\nplt.plot(m.time,y.value,label='y')\r\nplt.ylabel('Position')\r\nplt.legend(); plt.grid()\r\nplt.subplot(3,1,2)\r\nplt.plot(m.time,v.value,label='v')\r\nplt.plot(m.time,w.value,label='w')\r\nplt.ylabel('Velocity')\r\nplt.legend(); plt.grid()\r\nplt.subplot(3,1,3)\r\nplt.plot(m.time,lam.value,label=r'$\\lambda$')\r\nplt.legend(); plt.grid()\r\nplt.xlabel('Time')\r\nplt.savefig('index1.png',dpi=600)\r\nplt.show()\r\n\r\n\r\n\r\n","sub_path":"examples/pend1.py","file_name":"pend1.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"478338871","text":"#!/usr/bin/env python3\n# For the definition of the metric, see https://en.wikipedia.org/wiki/Variation_of_information\nfrom __future__ import print_function\nimport argparse\nimport math\nimport sys\ndef find(x, parents):\n while parents[x] != x:\n parent = parents[x]\n parents[x] = parents[parent]\n x = parent\n return x\ndef union(x, y, parents, sizes):\n # Get the representative for their sets\n x_root = find(x, parents)\n y_root = find(y, parents)\n # If equal, no change needed\n if x_root == y_root:\n return\n # Otherwise, merge them\n if sizes[x_root] > sizes[y_root]:\n parents[y_root] = x_root\n sizes[x_root] += sizes[y_root]\n else:\n parents[x_root] = y_root\n sizes[y_root] += sizes[x_root]\ndef union_find(nodes, edges):\n # Make sets\n parents = {n:n for n in nodes}\n sizes = {n:1 for n in nodes}\n for edge in edges:\n union(edge[0], edge[1], parents, sizes)\n clusters = {}\n for n in parents:\n clusters.setdefault(find(n, parents), set()).add(n)\n cluster_list = list(clusters.values())\n return cluster_list\ndef calc_link_num(edges):\n num = 0\n for key in edges.keys():\n for source in edges[key]:\n num += len(edges[key][source])\n return num\ndef link_prediction_result(gedges,aedges):\n tp,fp,tn,fn = 0,0,0,0\n self_link = 0\n true_predict_self_link = 0\n predict_self_link = 0\n g_link_num = calc_link_num(gedges)\n a_link_num = calc_link_num(aedges)\n for key in aedges.keys():\n for source in aedges[key]:\n for item in aedges[key][source]:\n if item == source:\n predict_self_link +=1\n for key in gedges.keys():\n for source in gedges[key]:\n for item in gedges[key][source]:\n if item == source:\n self_link +=1\n if key in aedges and source in aedges[key]:\n if item in aedges[key][source]:\n tp += 1\n if item == source:\n true_predict_self_link +=1\n recall = tp/g_link_num\n precision = tp/a_link_num\n s_p = true_predict_self_link/predict_self_link\n s_r = true_predict_self_link/self_link\n print(self_link/g_link_num)\n print(\"precison:%f,recall:%f\"%(precision,recall))\n print(\"self_link_precison:%f,recall:%f,total:%f\"%(s_p,s_r,self_link))\n return aedges,gedges\ndef read_data(filenames):\n clusters = {}\n graphs = {}\n all_points = set()\n for filename in filenames:\n nodes = {}\n edges = {}\n for line in open(filename):\n if line.startswith(\"#\") or line.startswith(\"%\") or line.startswith(\"/\"):\n continue\n cfile = filename\n if ':' in line:\n cfile, line = line.split(':')\n cfile = cfile.split('/')[-1]\n parts = [int(v) for v in line.strip().split() if v != '-']\n assert len(parts) == 2\n source = max(parts)\n nodes.setdefault(cfile, set()).add(source)\n parts.remove(source)\n for num in parts:\n edges.setdefault(cfile, []).append((source, num))\n nodes.setdefault(cfile, set()).add(num)\n graphs.setdefault(cfile, {}).setdefault(source, set()).add(num)\n for cfile in nodes:\n for cluster in union_find(nodes[cfile], edges[cfile]):\n vals = {v for v in cluster if v >= 1000}\n clusters.setdefault(cfile, []).append(vals)\n for val in vals:\n all_points.add(\"{}:{}\".format(cfile, val))\n return clusters, all_points, graphs\ndef clusters_to_contingency(gold, auto):\n # A table, in the form of:\n # https://en.wikipedia.org/wiki/Rand_index#The_contingency_table\n table = {}\n for filename in auto:\n for i, acluster in enumerate(auto[filename]):\n aname = \"auto.{}.{}\".format(filename, i)\n current = {}\n table[aname] = current\n for j, gcluster in enumerate(gold[filename]):\n gname = \"gold.{}.{}\".format(filename, j)\n count = len(acluster.intersection(gcluster))\n if count > 0:\n current[gname] = count\n counts_a = {}\n for filename in auto:\n for i, acluster in enumerate(auto[filename]):\n aname = \"auto.{}.{}\".format(filename, i)\n counts_a[aname] = len(acluster)\n counts_g = {}\n for filename in gold:\n for i, gcluster in enumerate(gold[filename]):\n gname = \"gold.{}.{}\".format(filename, i)\n counts_g[gname] = len(gcluster)\n return table, counts_a, counts_g\ndef variation_of_information(contingency, row_sums, col_sums):\n total = 0.0\n for row in row_sums:\n total += row_sums[row]\n H_UV = 0.0\n I_UV = 0.0\n for row in contingency:\n for col in contingency[row]:\n num = contingency[row][col]\n H_UV -= (num / total) * math.log(num / total, 2)\n I_UV += (num / total) * math.log(num * total / (row_sums[row] * col_sums[col]), 2)\n H_U = 0.0\n for row in row_sums:\n num = row_sums[row]\n H_U -= (num / total) * math.log(num / total, 2)\n H_V = 0.0\n for col in col_sums:\n num = col_sums[col]\n H_V -= (num / total) * math.log(num / total, 2)\n max_score = math.log(total, 2)\n VI = H_UV - I_UV\n scaled_VI = VI / max_score\n print(\"{:5.2f} 1 - Scaled VI\".format(100 - 100 * scaled_VI))\ndef adjusted_rand_index(contingency, row_sums, col_sums):\n # See https://en.wikipedia.org/wiki/Rand_index\n rand_index = 0.0\n total = 0.0\n for row in contingency:\n for col in contingency[row]:\n n = contingency[row][col]\n rand_index += n * (n-1) / 2.0\n total += n\n sum_row_choose2 = 0.0\n for row in row_sums:\n n = row_sums[row]\n sum_row_choose2 += n * (n-1) / 2.0\n sum_col_choose2 = 0.0\n for col in col_sums:\n n = col_sums[col]\n sum_col_choose2 += n * (n-1) / 2.0\n random_index = sum_row_choose2 * sum_col_choose2 * 2.0 / (total * (total - 1))\n max_index = 0.5 * (sum_row_choose2 + sum_col_choose2)\n adjusted_rand_index = (rand_index - random_index) / (max_index - random_index)\n print('{:5.2f} Adjusted rand index'.format(100 * adjusted_rand_index))\ndef exact_match(gold, auto):\n # P/R/F over complete clusters\n total_gold = 0\n total_matched = 0\n for filename in gold:\n for cluster in gold[filename]:\n if len(cluster) == 1:\n continue\n total_gold += 1\n matched = False\n for ocluster in auto[filename]:\n if len(ocluster.symmetric_difference(cluster)) == 0:\n matched = True\n break\n if matched:\n total_matched += 1\n total_auto = 0\n for filename in auto:\n for cluster in auto[filename]:\n if len(cluster) == 1:\n continue\n total_auto += 1\n p, r, f = 0.0, 0.0, 0.0\n if total_auto > 0:\n p = 100 * total_matched / total_auto\n if total_gold > 0:\n r = 100 * total_matched / total_gold\n if total_matched > 0:\n f = 2 * p * r / (p + r)\n print(\"{:5.2f} Matched clusters precision\".format(p))\n print(\"{:5.2f} Matched clusters recall\".format(r))\n print(\"{:5.2f} Matched clusters f-score\".format(f))\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Calculate cluster / thread / conversation metrics.')\n parser.add_argument('--gold', help='File(s) containing the gold clusters, one per line. If a line contains a \":\" the start is considered a filename', required=True, nargs=\"+\")\n parser.add_argument('--auto', help='File(s) containing the system clusters, one per line. If a line contains a \":\" the start is considered a filename', required=True, nargs=\"+\")\n parser.add_argument('--metric', nargs=\"+\", choices=['vi', 'rand', 'ex', 'all'], default=['all'])\n args = parser.parse_args()\n gold, gpoints, gedges = read_data(args.gold)\n auto, apoints, aedges = read_data(args.auto)\n issue = False\n for filename in auto:\n if filename not in gold:\n print(\"Gold is missing file {}\".format(filename), file=sys.stderr)\n issue = True\n for filename in gold:\n if filename not in auto:\n print(\"Auto is missing file {}\".format(filename), file=sys.stderr)\n issue = True\n if issue:\n sys.exit(0)\n if len(apoints.symmetric_difference(gpoints)) != 0:\n print('wrong')\n print(apoints.difference(gpoints))\n print(gpoints.difference(apoints))\n raise Exception(\"Set of lines does not match: {}\".format(apoints.symmetric_difference(gpoints)))\n aedges,gedges = link_prediction_result(gedges,aedges)\n contingency, row_sums, col_sums = None, None, None\n if 'vi' in args.metric or 'rand' in args.metric or 'all' in args.metric:\n contingency, row_sums, col_sums = clusters_to_contingency(gold, auto)\n if 'vi' in args.metric or 'all' in args.metric:\n variation_of_information(contingency, row_sums, col_sums)\n if 'rand' in args.metric or 'all' in args.metric:\n adjusted_rand_index(contingency, row_sums, col_sums)\n if 'ex' in args.metric or 'all' in args.metric:\n exact_match(gold, auto)","sub_path":"task-4-evaluation.py","file_name":"task-4-evaluation.py","file_ext":"py","file_size_in_byte":9442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"184960282","text":"\r\n\r\ndef pixel_between_two_points(x1, x2, y1, y2):\r\n two_points_list=[]\r\n x_distance = (x2 - x1)\r\n y_distance = (y2 - y1)\r\n a=0\r\n b=0\r\n if x_distance>0:\r\n a=1\r\n else:\r\n a=-1\r\n if y_distance>0:\r\n b=1\r\n else:\r\n b=-1\r\n\r\n if abs(y_distance) < abs(x_distance):\r\n\r\n div_1 = y_distance / x_distance\r\n\r\n for i in range(0, x_distance,a):\r\n pixel = [x1 + i, y1 + round(i * div_1)]\r\n #print(pixel)\r\n two_points_list.append(pixel)\r\n lenth_of_list = len(two_points_list)\r\n\r\n else:\r\n div_1 = x_distance / y_distance\r\n\r\n for i in range(0, y_distance,b):\r\n pixel = [x1 + round(i * div_1), y1 + i]\r\n #print(pixel)\r\n two_points_list.append(pixel)\r\n lenth_of_list=len(two_points_list)\r\n\r\n return two_points_list\r\n\r\ntest=pixel_between_two_points(168, 132,\r\n 179, 150)\r\n\r\n\r\n","sub_path":"pixelbetweenpoints.py","file_name":"pixelbetweenpoints.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"126854862","text":"import tkinter as tk\nfrom tkinter import *\nfrom tkinter import ttk, filedialog\nimport split\nimport Threads\nimport time\nimport os\nimport glob\nimport socket\nimport threading\n\npassword = 'masterbigdata218'\nfsp = split.FileSplitter()\nfilesPart = []\ndirectory = ['temp/','client/']\nconnecter = False\n\nfor f in glob.glob(\"temp/*.*\"):\n\tos.remove(f)\n\nfor d in directory:\n\tif not os.path.exists(d):\n\t os.makedirs(d)\n\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n \t\ndef dialogfile():\n\tglobal filename\n\tfilename = filedialog.askopenfilename(initialdir=\"/\", title=\"Select file :\",\n filetype=((\"jpeg\", \"*.jpg\"), (\"All Files\", \"*.*\")))\n\tfilename_label = ttk.Label(fram_file, text=filename).grid(row=1)\n\tlabel_message.insert(END,'File Added')\n\ndef uploadThread():\n\tthreading.Thread(target=upload).start()\n\ndef downloadThread():\n\tthreading.Thread(target=download).start()\n\ndef upload():\n\tglobal filename\n\tglobal fsp\n\tglobal password\n\n\n\tprogressbar.start()\n\tlabel_message.insert(END,'File Splited : '+filename)\n\tt0 = Threads.splitThread(fsp, filename)\n\n\tt0.start()\n\ttime.sleep(2)\n\n\tlabel_message.insert(END,'Files Encrypting :')\n\n\tlabel_message.insert(END, ' -->' + t0.filesPart[0])\n\tt1 = Threads.encryptThread(password,t0.filesPart[0])\n\n\tlabel_message.insert(END, ' -->' + t0.filesPart[1])\n\tt2 = Threads.encryptThread(password,t0.filesPart[1])\n\n\tt1.start()\n\tt2.start()\n\n\tt1.join()\n\tt2.join()\n\n\ttime.sleep(5)\n\n\tprint (t0.filesPart)\n\tfilename1 = str.encode('filename**'+t0.filesPart[0].replace('temp/','')+'.inc')\n\tfilename2 = str.encode('filename**'+t0.filesPart[1].replace('temp/','')+'.inc')\n\tprint(filename1)\n\tif connecter:\n\t\ti = 0\n\t\tfor f in t0.filesPart:\n\t\t\twith open(f+'.inc', 'rb') as fs:\n\t\t\t\tif i == 0:\n\t\t\t\t\tlabel_message.insert(END, '-> Send File 1')\n\t\t\t\t\ts.send(filename1)\n\t\t\t\telse:\n\t\t\t\t\tlabel_message.insert(END, '-> Send File 2')\n\t\t\t\t\ts2.send(filename2)\n\t\t\t\twhile True:\n\t\t\t\t\tdata = fs.read(1024)\n\t\t\t\t\tif(i == 0):\n\t\t\t\t\t\ts.send(data)\n\t\t\t\t\telse:\n\t\t\t\t\t\ts2.send(data)\n\t\t\t\t\tif not data:\n\t\t\t\t\t\tbreak\n\t\t\t\tif i == 0:\n\t\t\t\t\ts.send(b'ENDED')\n\t\t\t\telse:\n\t\t\t\t\ts2.send(b'ENDED')\n\t\t\t\tfs.close()\n\t\t\t\ti = i + 1 \n\tprogressbar.stop()\n\n\ndef download():\n\tif connecter:\n\t\ti = 0\n\t\twhile(i < 2):\n\t\t\tif i == 0:\n\t\t\t\tfilenamedownload = str.encode('downloadfile**'+filedownload.get()+'-1.inc')\n\t\t\t\ts.send(filenamedownload)\n\t\t\t\twith open('temp/'+filedownload.get()+'-1.inc', \"wb\") as fw:\n\t\t\t\t\twhile True:\n\t\t\t\t\t\tdata = s.recv(1024)\n\t\t\t\t\t\tif data == b'ENDED':\n\t\t\t\t\t\t\tprint(\"END recv\")\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tfw.write(data)\n\t\t\t\t\tfw.close()\n\t\t\t\t\ti = i + 1\n\t\t\telif i == 1:\n\t\t\t\tfilenamedownload = str.encode('downloadfile**'+filedownload.get()+'-2.inc')\n\t\t\t\ts2.send(filenamedownload)\n\t\t\t\twith open('temp/'+filedownload.get()+'-2.inc', \"wb\") as fw:\n\t\t\t\t\twhile True:\n\t\t\t\t\t\tdata = s2.recv(1024)\n\t\t\t\t\t\tif data == b'ENDED':\n\t\t\t\t\t\t\tprint(\"END recv\")\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tfw.write(data)\n\t\t\t\t\tfw.close()\n\t\t\t\t\ti = i +1\n\t\tt1 = Threads.decryptThread(password,'temp/'+filedownload.get()+'-1.inc')\n\t\tt2 = Threads.decryptThread(password,'temp/'+filedownload.get()+'-2.inc')\n\t\tt1.start()\n\t\tt2.start()\n\t\ttime.sleep(2)\n\t\tt3 = Threads.combineThread(fsp,'temp/'+filedownload.get()+'-1','temp/'+filedownload.get()+'-2')\n\t\tt3.start()\n\ndef connecter():\n\tglobal serverStatu\n\ts.connect((adresse.get(),int(port.get())))\n\tlabel_message.insert(END, ' --> connected to server1')\n\ts2.connect((a2.get(),int(p2.get())))\n\tlabel_message.insert(END, ' --> connected to server2')\n\tconnecter = True\n\nroot = Tk()\nroot.title(\"Client\")\nroot.geometry('440x600')\n\nadresse = StringVar()\nport = StringVar()\n\na2 = StringVar()\np2 = StringVar()\n\nfram_connection = ttk.LabelFrame(root, text=\"Connection :\")\nfram_connection.pack()\nfram_connection.config(padding=10)\n\nconnection = tk.Button(fram_connection, text=\"Connecter\",command=connecter)\nconnection.grid(row=4, column=2, pady=10)\n\nserver1 = tk.Label(fram_connection, text=\"SERVER 1 :\")\nserver1.grid(row=0, column=0)\n\nlabelAdress1 = tk.Label(fram_connection, text=\"Adresse :\").grid(row=1, column=0)\nadresse1 = tk.Entry(fram_connection,textvariable=adresse).grid(row=1, column=1)\n\nlabelPort1 = tk.Label(fram_connection, text=\"Prot :\").grid(row=1, column=3)\nport1 = tk.Entry(fram_connection,textvariable=port).grid(row=1, column=4)\n\nserver2 = tk.Label(fram_connection, text=\"SERVER 2 :\").grid(row=2, column=0)\n\nlabelAdress2 = tk.Label(fram_connection, text=\"Adresse :\").grid(row=3, column=0)\nadresse2 = tk.Entry(fram_connection, textvariable=a2).grid(row=3, column=1)\n\nlabelPort2 = tk.Label(fram_connection, text=\"Port :\").grid(row=3, column=3)\nport2 = tk.Entry(fram_connection, textvariable=p2).grid(row=3, column=4)\n\nfram_file = ttk.LabelFrame(root, text=\"File :\")\nfram_file.pack()\nfram_file.config(padding=10)\n\nfilename = tk.StringVar()\n\nopenfile = tk.Button(fram_file, text=\"Select file\", command=dialogfile, padx=10).grid(row=0, padx=160, pady=10)\n\nframe_crypto = ttk.LabelFrame(root, text = \"Telechargement :\")\nframe_crypto.pack()\nframe_crypto.config(padding=10)\n\nfiledownload = tk.StringVar()\n\ndownloadEntry = tk.Entry(frame_crypto,width=50,textvariable=filedownload).grid(row=0,column=0)\ndownloadButton = tk.Button(frame_crypto,text='Download',command=downloadThread).grid(row=0,column=1)\n\n\nframe_send = ttk.LabelFrame(root, text = \"Send :\")\nframe_send.pack()\nframe_send.config(padding=20)\n\nprogressbar = ttk.Progressbar(frame_send, orient=tk.HORIZONTAL, length= 200)\nprogressbar.grid(row=0, column=0)\nprogressbar.config(mode= 'indeterminate')\nprogressbar.stop()\n\n\nespace = tk.Label(frame_send, text=\" \").grid(row=0,column=1)\nsend = tk.Button(frame_send, text=\"Upload\", padx=20, command=uploadThread).grid(row=0, column=2)\n\nframe_message = ttk.LabelFrame(root, text = \"Log :\")\nframe_message.pack(fill=BOTH)\nframe_message.config(padding=5)\n\nlabel_message = tk.Listbox(frame_message,bg='black',fg='green')\nlabel_message.pack(fill=BOTH)\nlabel_message.configure()\nroot.mainloop()\n\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":5980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"653502807","text":"#!/bin/env python\n\n'''\n--------------------------------------------------------------------------------\n\nAnnokey: a NCBI Gene Database Keyword Search Tool\n-------------------------------------------------\n\nAuthors: Daniel Park, Sori Kang, Bernie Pope, Tu Nguyen-Dumont.\nCopyright: 2013\nWebsite: https://github.com/bjpop/annokey\nLicense: BSD, see LICENCE file in source distribution. \n\nThis program searches NCBI database for genes of interest\nbased on concept-keyword search.\n\nThis program supports both online search and offline search.\nIf the option --online is on, this program downloads gene database in xml\nformat from the NCBI server and search keywords. The option --saveCache allows\nthe downloaded information to be saved int the user's directory.\n\nFor offline search, there is the option --loadCache, which\naccepts an xml file for gene information. \n\nThe search results are appended at the end of column of the\ninput gene file with the information about the keyword hit,\nthe keyword rank, and the section where the keyword hit.\n\nRequired inputs:\n\n --keys FILENAME a text file of search keywords/keyphrases. One\n term per line.\n\n --genes FILENAME a text file of gene information, one gene per line.\n Format is tab separated. Must contain at least one\n column of gene names.\n\n--------------------------------------------------------------------------------\n'''\n\nimport sys\nimport csv\nimport os\nimport glob\nfrom argparse import ArgumentParser\nfrom Bio import Entrez\nfrom lxml import etree\nfrom StringIO import StringIO\nimport itertools\nimport cPickle as pickle\nimport logging\n\nfrom process_xml import GeneParser, Hit\n\n\n#NCBI access rate limit\n#http://www.ncbi.nlm.nih.gov/books/NBK25497/\n#In order not to overload the E-utility servers, NCBI recommends that users\n#post no more than three URL requests per second and limit large jobs to either\n#weekends or between 9:00 PM and 5:00 AM Eastern time during weekdays. Failure\n#to comply with this policy may result in an IP address being blocked from\n#accessing NCBI. If NCBI blocks an IP address, service will not be restored\n#unless the developers of the software accessing the E-utilities register values\n#of the tool and email parameters with NCBI. The value of tool should be a\n#string with no internal spaces that uniquely identifies the software producing\n#the request. The value of email should be a complete and valid e-mail address\n#of the software developer and not that of a third-party end user. The value of\n#email will be used only to contact developers if NCBI observes requests that\n#violate our policies, and we will attempt such contact prior to blocking\n#access. In addition, developers may request that the value of email be added\n#to the E-utility mailing list that provides announcements of software updates,\n#known bugs and other policy changes affecting the E-utilities. To register tool\n#and email values, simply send an e-mail to eutilities@ncbi.nlm.nih.gov\n#including the desired values along with the name of either a developer or the\n#organization creating the software. Once NCBI establishes communication with a\n#developer, receives values for tool and email and validates the e-mail address\n#in email, the block will be lifted. Once tool and email values are registered,\n#all subsequent E-utility requests from that software package should contain\n#both values. Please be aware that merely providing values for tool and email\n#in requests is not sufficient to comply with this policy; these values must be\n#registered with NCBI. Requests from any IP that lack registered values for tool\n#and email and that violate the above usage policies may be blocked. Software\n#developers may register values of tool and email at any time, and are\n#encouraged to do so.\n\n\ndef genefile_reader(csvfile):\n # try to detect the csv format from the (up to)\n # first three lines of the file\n sample = ''\n for n, line in enumerate(csvfile):\n if n >= 3:\n break\n else:\n sample += line \n sniffer = csv.Sniffer()\n dialect = sniffer.sniff(sample)\n csvfile.seek(0)\n reader = csv.reader(csvfile, dialect)\n if sniffer.has_header:\n header = next(reader)\n else:\n header = None\n return header, reader, dialect\n\n\n# read each gene name from the gene file at a given column\ndef get_gene_names(genefilename, column):\n with open(genefilename, 'rb') as file:\n header, reader, dialect = genefile_reader(file)\n for row in reader:\n name = row[column]\n yield name\n\n\ndef get_gene_ids(genefilename, column, organism='Homo sapiens'):\n\n def chunk_gene_names(genefilename, chunk_size):\n names = []\n numbered_gene_names = enumerate(get_gene_names(genefilename, column))\n for n, name in numbered_gene_names:\n names.append(name.strip())\n if (n+1) % chunk_size == 0:\n yield names\n names = []\n yield names\n\n # Send request to server for every 100 genes.\n gene_ids = set()\n\n for names in chunk_gene_names(genefilename, chunk_size=100):\n terms = ' OR '.join(['%s[sym]' % name for name in names])\n search_term = '{0}[organism] AND ({1})'.format(organism, terms)\n request = Entrez.esearch(db='gene', term=search_term, retmax=10000)\n result = Entrez.read(request)\n gene_ids.update(result['IdList'])\n return gene_ids\n\n\n# For each gene in genesfile we read PubMedIds using genecache.\ndef get_pubmed_ids(args):\n pubmed_ids = set()\n \n with open(args.genes) as genesfile:\n header, reader, dialect = genefile_reader(genesfile)\n for row in reader:\n genename = row[args.genecol].strip()\n for gene_xml in lookup_gene_cache_iter(args, genename):\n pubmed_ids.update(GeneParser.pubmed_ids(gene_xml))\n\n return pubmed_ids\n\n\ndef fetch_and_save_pubmed_records(cachedir, organism, ids):\n # XXX Fetch all records here regardless of existing pubmed cache.\n # We may be able to skip the records that already exist if\n # the records are not updated.\n # XXX As the number of pubmed ids is usually large,\n # save XML file in cache right after fetching them.\n idString = ','.join(ids)\n postRequest = Entrez.epost(db='pubmed', id=idString)\n postResult = Entrez.read(postRequest)\n webEnv = postResult['WebEnv']\n queryKey = postResult['QueryKey']\n retstart = 0\n chunk_size = 10000\n\n while retstart < len(ids):\n try:\n fetch_request = Entrez.efetch(db='pubmed',\n webenv=webEnv,\n query_key=queryKey,\n retmode='xml',\n retmax=chunk_size,\n retstart=retstart)\n pubmed_result = fetch_request.read()\n # XXX What should we do on exception? Try again? Sleep? Quit?\n except Exception as e:\n print(\"fetch failed with: {} {}\".format(e, type(e)))\n break\n\n save_pubmed_cache(cachedir, pubmed_result)\n retstart += chunk_size\n\n\ndef lookup_pubmed_ids(ids):\n not_cached_ids = []\n # search for all the cached pubmed ids first, and\n # collect the non-cached ones.\n for id in ids:\n cache_result = lookup_pubmed_cache(id)\n if cache_result is not None:\n #print(\"found {} in cache:\".format(id))\n yield cache_result\n else:\n print(\"did not find {} in cache:\".format(id))\n not_cached_ids.append(id)\n\n # I don't think we should do the chunking here, but instead\n # rely on the Entrz history.\n # fetch the non-cached ids from NCBI\n\n if len(not_cached_ids) == 0:\n return\n\n idString = ','.join(not_cached_ids)\n postRequest = Entrez.epost(db='pubmed', id=idString)\n postResult = Entrez.read(postRequest)\n webEnv = postResult['WebEnv']\n queryKey = postResult['QueryKey']\n retstart = 0\n chunk_size = 10000\n\n while retstart < len(not_cached_ids):\n try:\n fetch_request = Entrez.efetch(db='pubmed',\n webenv=webEnv,\n query_key=queryKey,\n retmode='xml',\n retmax=chunk_size,\n retstart=retstart)\n pubmed_result = fetch_request.read()\n # XXX What should we do on exception? Try again? Sleep? Quit?\n except Exception as e:\n print(\"fetch failed with: {} {}\".format(e, type(e)))\n break \n\n content = etree.iterparse(StringIO(pubmed_result), events=('end',), tag='PubmedArticle')\n for event, pubmed_entry in content:\n # XXX we should cache this result possibly\n yield get_pubmed_content(pubmed_entry)\n # Clear node references\n pubmed_entry.clear()\n while pubmed_entry.getprevious() is not None:\n del pubmed_entry.getparent()[0]\n del content\n retstart += chunk_size\n\n\n# assume input is a set\ndef fetch_records_from_ids(ids):\n\n db = 'gene'\n\n # Before posting, make a list of unique Ids\n #uniqIds = make_unique_list(ids)\n idString = ','.join(list(ids))\n postRequest = Entrez.epost(db=db, id=idString)\n postResult = Entrez.read(postRequest)\n webEnv = postResult['WebEnv']\n queryKey = postResult['QueryKey']\n fetchRequest = Entrez.efetch(db=db,\n webenv=webEnv,\n query_key=queryKey,\n retmode='xml')\n return fetchRequest.read()\n\n\ndef merge_geneContent(geneContent, values):\n '''Merge gene information.\n\n Args:\n geneContent: dict containing gene information.\n values to be merged into this geneContent.\n values: a list of tuple containing gene information.\n It is to be merged into geneContent.\n Returns:\n A dict containing gene information.\n '''\n\n for key, value in values:\n geneContent[key] += value \n return geneContent\n# return '(kw: {}, rank: {}, ncbi id: {}, fields: {})'.format(self.keyword, self.rank, self.database_record_id, ';'.join(self.fields))\n\n\ndef search_keywords(args):\n\n # build a list of all the keywords in the order that they\n # appear in the keywords file\n keywords = []\n with open(args.keys) as keysfile:\n for line in keysfile:\n keywords.append(line.strip())\n\n if len(keywords) > 0:\n with open(args.genes) as genesfile:\n header, reader, dialect = genefile_reader(genesfile)\n writer = csv.writer(sys.stdout, dialect=dialect)\n if header:\n writer.writerow(header)\n # for each row in the genes file, find hits for the gene\n # print the row out with the hits annoated on the end\n for row in reader:\n genename = row[args.genecol].strip()\n for hit in search_keywords_gene_iter(args, genename, keywords):\n row.append(str(hit))\n writer.writerow(row)\n\n\n# Search for each keyword in the XML file for a gene. A hit is yielded for\n# each keyword. If a gene has multiple files, we search each one separately.\n# This means it is possible to get multiple hits for the same keyword\n# but from different files. XXX we should annotate each hit with the database\n# file ID\ndef search_keywords_gene_iter(args, gene_name, keywords):\n for gene_xml in lookup_gene_cache_iter(args, gene_name):\n for hit in GeneParser.keyword_hit(gene_xml, keywords, args.pubmedcache):\n yield hit\n\n\ndef lookup_gene_cache_iter(args, gene_name):\n gene_cache_dir = make_gene_cache_dirname(args.genecache, args.organism, gene_name)\n try:\n dir_contents = os.listdir(gene_cache_dir)\n except OSError:\n logging.info(\"Could not find cache entry for {}\".format(gene_name))\n return\n for filename in os.listdir(gene_cache_dir):\n #if filename.endswith('.xml'):\n file = '%s/%s' % (gene_cache_dir, filename)\n file = open(file)\n yield file\n file.close()\n\n\n#def search_keywords_inDict(dbEntry, keywords):\n# '''Search top N ranking keywords from dbEntry.\n# dbEntry is a dictionary which contains information of each field.\n# The value of each key is a list.\n# e.g) {'AlterName' : ['abc', 'def'], ...}\n# Returns a list of tuples containging\n# the keyword hitted,\n# the rank of keyword, and\n# the fields where the keyword hitted.\n# '''\n# keysFound = []\n# fields = []\n# for n, keyword in enumerate(keywords):\n# for field, content in dbEntry.iteritems():\n# if field == 'GeneRIFs':\n# hit = [keyword in item for item in content]\n# if sum(hit) > 0:\n# fields.append('%s(%s/%s)' %\n# (field, sum(hit), len(content)))\n# else:\n# for item in content:\n# if keyword in item and field not in fields:\n# fields.append(field)\n# if len(fields) > 0:\n# keysFound.append((keyword, n+1, fields))\n# fields = []\n#\n# return keysFound\n#\n#\n#def search_keywords_inPubMed(pubmedContent, keywords):\n# '''Search keywords from pubmedContent.'''\n# # Only interested in article title and abstract\n# content = ''\n# try:\n# content += pubmedContent['Article Title']\n# content += ';' + pubmedContent['Abstract']\n# except KeyError:\n# pass\n#\n# return search_keywords_inString(content, keywords)\n#\n#\n#def search_keywords_inString(dbEntry, keywords):\n# '''Searche keyword in the order (according to the rank) and\n# return the keyword and its rank (position in the list).\n# If fail to search, (python) returns None.\n# dbEntry is a string.\n# '''\n# keysFound = []\n# for n, item in enumerate(keywords):\n# if item in dbEntry:\n# keysFound.append((item, n+1))\n# return keysFound\n\n\ndef make_pubmed_cache_dirname(cachedir, pubmed_id):\n hash_dir = hash(pubmed_id) % 256\n return os.path.join(cachedir, str(hash_dir))\n\ndef make_gene_cache_dirname(cachedir, organism, gene_name):\n organism_cache_dir = os.path.join(cachedir, organism, 'gene')\n hash_dir = hash(gene_name) % 256\n return os.path.join(organism_cache_dir, str(hash_dir), gene_name)\n\ndef save_pubmed_cache(cachedir, pubmed_records_xml):\n # Read each \"PubMedArticle\" record in the input XML and \n # write it out to a cache file. We store each article entry in a file\n # based on its PubMed ID.\n \n parser = etree.iterparse(StringIO(pubmed_records_xml), events=('end',), tag='PubmedArticle')\n for event, pubmed_entry in parser:\n # Find pubmed id\n pubmed_id = pubmed_entry.find('.//MedlineCitation/PMID').text\n pubmed_cache_dir = make_pubmed_cache_dirname(cachedir, pubmed_id)\n if not os.path.exists(pubmed_cache_dir):\n os.makedirs(pubmed_cache_dir)\n pubmed_cache_filename = os.path.join(pubmed_cache_dir, pubmed_id)\n with open(pubmed_cache_filename, 'w') as cache_file:\n cache_file.write(etree.tostring(pubmed_entry))\n # free up memory used by the XML iterative parser\n pubmed_entry.clear()\n while pubmed_entry.getprevious() is not None:\n del pubmed_entry.getparent()[0]\n\n\ndef save_gene_cache(cachedir, organism, gene_records_xml):\n\n #cachedir = args.genecache\n #organism = args.organism\n\n # create a cache directory for this organism if it doesn't already exist\n # for example human would go in:\n # cachedir/human/gene/\n # the reason for \"gene\" is because we also cache ncbi entries in \"ncbi\"\n #organism_cache_dir = os.path.join(cachedir, organism, 'gene')\n\n # read each \"Entrezgene\" record in the input XML and write it out to\n # a cache file. Sometimes one gene will have multiple entries. We store\n # each gene entry in a file based on its database ID.\n parser = etree.iterparse(StringIO(gene_records_xml), events=('end',), tag='Entrezgene')\n\n for event, elem in parser:\n # find the official name of the gene\n gene_name = elem.find('.//Gene-ref_locus').text\n # find the database id of the gene\n gene_id = elem.find('.//Gene-track_geneid').text\n # hash the name of the gene into an integer in the range [0, 255]\n #hash_dir = hash(gene_name) % 256\n # if it doesn't already exist, create a directory in the cache for\n # this gene\n #gene_cache_dir = os.path.join(organism_cache_dir, str(hash_dir), gene_name)\n gene_cache_dir = make_gene_cache_dirname(cachedir, organism, gene_name)\n if not os.path.exists(gene_cache_dir):\n os.makedirs(gene_cache_dir)\n # Write a single 'Entrezgene' entry to a file in the cache using the\n # database ID for the file name\n gene_cache_filename = os.path.join(gene_cache_dir, gene_id)\n with open(gene_cache_filename, 'w') as cache_file:\n cache_file.write(etree.tostring(elem))\n # free up memory used by the XML iterative parser\n elem.clear()\n while elem.getprevious() is not None:\n del elem.getparent()[0]\n\n\ndef fetch_records(args):\n # fetch gene records and pubmed records and save them in cache.\n\n # read each gene name from the gene file at a given column\n gene_ids = get_gene_ids(args.genes, args.genecol, args.organism)\n # fetch the corresponding XML records for the identified genes\n gene_records_xml = fetch_records_from_ids(gene_ids)\n # Cache the gene entries in the XML file\n save_gene_cache(args.genecache, args.organism, gene_records_xml)\n\n # pubmed records\n # get pubmed ids from each gene records\n pubmed_ids = get_pubmed_ids(args)\n # fetch the corresponding XML records for pubmed ids\n # cache the pubmed records\n fetch_and_save_pubmed_records(args.pubmedcache, args.organism, pubmed_ids)\n\n\ndef parse_args():\n parser = ArgumentParser(description='Search NCBI for genes of interest, '\n 'based on concept-keyword search.')\n\n parser.add_argument('--online',\n action='store_true',\n help='Search gene information from online (NCBI).')\n\n parser.add_argument('--genecol',\n metavar='INT',\n type=int,\n default=0,\n required=True,\n help='The position of the column containing gene name. (0 base)')\n\n parser.add_argument('--skipheader',\n action='store_true',\n help='The first line of the gene file is a header which'\n 'should be skipped over')\n\n parser.add_argument('--organism',\n type=str,\n default='human',\n help='Name of the organism to search')\n\n parser.add_argument('--email',\n metavar='EMAIL_ADDRESS',\n type=str,\n help='Your email address. This is required by'\n 'NCBI for online queries. You do not need'\n 'to supply an email address for cached queries.')\n\n parser.add_argument('--genecache',\n metavar='DIR',\n type=str,\n default='genecache',\n help='Save a cache of the downloaded results '\n 'from NCBI gene into this directory')\n\n parser.add_argument('--pubmedcache',\n metavar='DIR',\n type=str,\n default='pubmedcache',\n help='Save a cache of the downloaded results '\n 'from NCBI pubmed into this directory')\n\n parser.add_argument('--keys',\n metavar='FILE',\n type=str,\n required=True,\n help='The tab separated file containing '\n 'the keywords to be searched.')\n\n parser.add_argument('--genes',\n metavar='FILE',\n type=str,\n required=True,\n help='The tab separated file containing '\n 'the gene information including '\n 'name of the gene, one gene name per line.')\n\n parser.add_argument('--log', metavar='FILENAME', type=str, required=True,\n help='log progress in FILENAME')\n\n\n return parser.parse_args()\n\ndef main():\n args = parse_args()\n\n logging.basicConfig(filename=args.log,\n level=logging.DEBUG,\n filemode='w',\n format='%(asctime)s %(message)s',\n datefmt='%m/%d/%Y %H:%M:%S')\n logging.info('program started')\n logging.info('command line: {0}'.format(' '.join(sys.argv)))\n\n if args.online:\n # Get gene information online.\n\n if args.email:\n Entrez.email = args.email\n else:\n exit('An email address is required for online queries, use the --email flag')\n\n # fetch gene and pubmed records and save them in cache. \n fetch_records(args)\n\n # Get gene information from cache.\n search_keywords(args)\n\nif __name__ == '__main__':\n main()\n","sub_path":"annokey.py","file_name":"annokey.py","file_ext":"py","file_size_in_byte":21869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"605924388","text":"import json\nfrom collections import OrderedDict\nimport pandas as pd\nfrom datetime import datetime\nfrom evaluator import Evaluator\nfrom pyomo.environ import Var\n\n#from utils import eval_function\n\nclass WaterSystem(object):\n\n def __init__(self, starttime, conn, name, network, template, attrs, timesteps, timestep_format):\n self.starttime = starttime\n self.conn = conn\n self.name = name\n self.template = template\n self.timesteps = timesteps\n self.timestep_format = timestep_format\n self.attrs = attrs\n \n self.evaluator = Evaluator(self.conn, dates=timesteps)\n\n # prepare data - we could move some of this to elsewhere \n\n template_id = template.id\n\n # extract info about nodes & links\n self.network = network\n self.nodes = []\n self.links = []\n self.types = {'node': {}, 'link': {}, 'network': {}}\n self.res_attrs = {}\n self.link_nodes = {}\n \n for tt in template.types:\n ttype_name = tt.name.replace(' ', '').replace('/', '')\n self.types[tt.resource_type.lower()][ttype_name] = []\n \n # organize basic network information\n features = network\n #features['networks'] = [network]\n for rt in ['node', 'link']:\n for f in features['{}s'.format(rt)]:\n if rt == 'node':\n idx = f.id\n self.nodes.append(idx)\n elif rt == 'link':\n idx = (f.node_1_id, f.node_2_id)\n self.links.append(idx)\n self.link_nodes[f.id] = idx\n\n # a dictionary of template_type to node_id\n for t in f.types:\n if t.template_id == template_id:\n type_name = t.name.replace(' ', '').replace('/', '')\n if type_name not in self.types[rt]:\n self.types[rt][type_name] = []\n self.types[rt][type_name].append(idx)\n\n\n # general resource attribute information \n for ra in f.attributes:\n self.res_attrs[ra.id] = {\n 'name': attrs[ra.attr_id]['name'],\n 'type': rt,\n 'data_type': 'timeseries',\n 'is_var': ra.attr_is_var\n }\n\n # initialize dictionary of parameters\n self.scalars = {feature_type: {} for feature_type in ['node', 'link', 'net']}\n\n self.ra_node = {} # res_attr to node lookup\n for node in network.nodes:\n for ra in node.attributes:\n self.ra_node[ra.id] = node.id\n\n self.ra_link = {} # res_attr to link lookup\n for link in network.links:\n for ra in link.attributes:\n self.ra_link[ra.id] = link.id\n\n #ra_net = dict() # res_attr to network lookup\n #for link in network.links:\n #for res_attr in link.attributes:\n #ra_link[res_attr.id] = link.id\n\n def init_scenario(self, scenario_ids):\n\n #self.scenario = scenario\n self.timeseries = {}\n self.variables = {}\n self.block_params = ['Value', 'Demand']\n self.blocks = {'node': {}, 'link': {}}\n self.results = {}\n self.res_scens = {}\n \n #self.current_res_scens = {rs.resource_attr_id: rs for rs in scenario.resourcescenarios}\n \n self.collect_source_data(scenario_ids)\n \n def collect_source_data(self, base_ids):\n self.base_scenarios = []\n self.source_scenarios = {}\n \n # collect source IDs\n source_ids = []\n for i, base_id in enumerate(base_ids):\n source = [s for s in self.network.scenarios if s.id == base_id][0]\n self.base_scenarios.append(source)\n self.source_scenarios[base_id] = source\n \n this_chain = [source.id]\n \n while source['layout']['parent'] if 'parent' in source['layout'] else None:\n parent_id = source['layout']['parent']\n if parent_id not in source_ids: # prevent adding in Baseline twice, which would overwrite options\n this_chain.append(parent_id)\n source = self.conn.call('get_scenario', {'scenario_id': parent_id})\n self.source_scenarios[source.id] = source\n this_chain.reverse()\n source_ids.extend(this_chain)\n \n # collect source data\n for source_id in source_ids:\n \n self.evaluator.scenario_id = source_id \n \n source = self.source_scenarios[source_id]\n\n for rs in source.resourcescenarios: \n \n if self.res_attrs[rs.resource_attr_id]['is_var'] == 'Y':\n continue # this is a dependent (output) variable \n \n # create a dictionary to lookup resourcescenario by resource attribute ID\n self.res_scens[rs.resource_attr_id] = rs\n \n # load the metadata\n metadata = json.loads(rs.value.metadata)\n \n # get identifiers\n if rs.resource_attr_id in self.ra_node:\n resource_type = 'node'\n idx = self.ra_node[rs.resource_attr_id]\n elif rs.resource_attr_id in self.ra_link:\n resource_type = 'link'\n idx = self.link_nodes[self.ra_link[rs.resource_attr_id]]\n #elif rs.resource_attr_id in self.ra_net:\n #resource_type = 'net'\n #fid = self.ra_net[rs.resource_attr_id]\n \n # identify as function or not\n is_function = metadata['use_function'] == 'Y' if 'use_function' in metadata else False \n \n # get attr name\n attr_name = self.res_attrs[rs.resource_attr_id]['name']\n \n # get data type\n data_type = rs.value.type\n \n # update data type\n self.res_attrs[rs.resource_attr_id]['data_type'] = data_type\n \n # default blocks\n has_blocks = (attr_name in self.block_params) or metadata.get('has_blocks', 'N') == 'Y'\n blocks = [0]\n \n param_name = '{rt}{name}'.format(rt=resource_type, name=attr_name.replace(' ', ''))\n \n #value = rs.value.value\n self.evaluator.data_type = data_type\n value = self.evaluator.eval_data(value=rs.value, do_eval=False, flavor='pandas')\n \n if data_type == 'scalar':\n if param_name not in self.variables:\n self.variables[param_name] = {}\n \n #if is_function:\n #function = metadata['function']\n #if len(function) == 0:\n #continue\n #value = eval_function(function, self.timesteps[0])\n #value = evaluator.eval_data(value=rs.value, do_eval=False) \n self.variables[param_name][idx] = float(value)\n \n elif data_type == 'descriptor': # this could change later\n if param_name not in self.variables:\n self.variables[param_name] = {} \n self.variables[param_name][idx] = value\n \n elif data_type == 'timeseries':\n values = value\n function = None\n \n if is_function:\n dtype = 'function'\n function = metadata['function']\n if len(function) == 0:\n continue\n if has_blocks:\n blocks = range(value.columns.size)\n \n else:\n dtype = 'timeseries'\n values = pd.read_json(rs.value.value)\n \n if has_blocks:\n blocks = list(range(values.columns.size))\n \n if param_name not in self.timeseries:\n self.timeseries[param_name] = {} \n self.timeseries[param_name][idx] = {\n 'dtype': dtype,\n 'values': values,\n 'function': function,\n 'has_blocks': has_blocks\n }\n \n if idx in self.blocks[resource_type]:\n n_existing = len(self.blocks[resource_type][idx])\n n_new = len(blocks)\n blocks = range(max([n_existing, n_new]))\n self.blocks[resource_type][idx] = blocks\n \n \n def prepare_params(self):\n \n self.params = {}\n \n for ttype in self.template.types:\n \n rt = ttype['resource_type']\n \n for ta in ttype.typeattrs:\n \n dt = ta['data_type']\n nm = ta['attr_name']\n \n # create a unique parameter name\n param_name = '{rt}{name}'.format(rt=rt.lower(), name=nm.replace(' ', ''))\n \n # IMPORTANT! rt-name combinations should be unique! This can be resolved in two ways:\n # 1. append the dimension to the param name, or\n # 2. use a unique internal name for all variables (e.g., reservoir_demand, urban_demand)\n # then use this unique internal name instead of the rt-name scheme.\n # Number two is var preferable\n if param_name in self.params:\n continue # already added\n \n param_definition = None\n\n initial_values = self.variables[param_name] if param_name in self.variables else None\n\n if ta['is_var'] == 'N':\n \n mutable = True # assume all variables are mutable\n default = 0\n \n if dt == 'scalar':\n param_definition = 'm.{rt}s'\n #if nm in ['Initial Storage']:\n #mutable = True\n elif dt == 'timeseries':\n if nm in ['Demand', 'Value']: # should define this elsewhere\n param_definition = 'm.{rt}Blocks, m.TS'\n else:\n param_definition = 'm.{rt}s, m.TS'\n #mutable = True\n elif dt == 'array':\n continue # placeholder\n else:\n continue\n param_definition += ', default={}, mutable={}'.format(default, mutable)\n if initial_values is not None:\n param_definition += ', initialize=initial_values'\n \n param_definition = param_definition.format(rt=rt.title())\n\n expression = 'm.{param_name} = Param({param_definition})'.format(\n param_name=param_name,\n param_definition=param_definition\n )\n \n self.params[param_name] = {\n 'name': nm,\n 'type_attr': ta,\n 'is_var': ta['is_var'],\n 'resource_type': rt.lower(),\n 'initial_values': initial_values,\n 'expression': expression\n }\n \n def update_initial_conditions(self):\n\n # we should provide a list of pairs to map variable to initial conditions (storage, groundwater storage, etc.)\n for j in self.model.Reservoir:\n getattr(self.model, 'nodeInitialStorage')[j] = getattr(self.model, 'nodeStorage')[j,0].value\n\n def update_variables(self, timesteps, initialize=False):\n \"\"\"Update variables. If initialize is True, this will create a variables object for use in creating the model. Otherwise, it will update the model instance.\"\"\"\n\n for param_name, param in self.timeseries.items():\n for idx, p in param.items():\n if p['dtype'] == 'function':\n self.evaluator.timesteps = timesteps\n returncode, errormsg, df = self.evaluator.eval_function(p['function'], flavor='pandas', counter=0)\n else:\n df = p['values']\n \n for j, c in enumerate(df.columns):\n\n # update values variable\n for i, datetime in enumerate(timesteps):\n \n val = df.loc[datetime, c]\n \n # create key\n key = list(idx) + [i] if type(idx) == tuple else [idx,i]\n if p['has_blocks']:\n key.insert(-1, j)\n key = tuple(key)\n \n if initialize:\n if param_name not in self.variables:\n self.variables[param_name] = {} \n self.variables[param_name][key] = val\n\n else: # just update the parameter directly\n getattr(self.model, param_name)[key] = val \n\n def collect_results(self, timesteps, include_all=False):\n \n # loop through all the model variables\n for i, v in enumerate(self.model.component_objects(Var, active=True)):\n \n if 'Block' in v.name:\n continue # skip for now\n \n if v.name not in self.results:\n self.results[v.name] = {}\n \n # collect to results \n for idx, val in v.get_values().items(): # loop through parameter values\n \n if idx[-1]==0 or include_all: # index[-1] is time\n if idx[:-1] not in self.results[v.name]: # idx[:-1] is node/link + block, if any\n self.results[v.name][idx[:-1]] = {} \n ts = timesteps[idx[-1]].strftime(self.timestep_format) # date/time name\n ts = self.OAtHPt[ts]\n \n self.results[v.name][idx[:-1]][ts] = val\n \n def save_results(self):\n\n res_scens = []\n\n # look for existing option-scenario combination\n source_names = []\n source_ids = []\n tags = []\n for s in self.base_scenarios:\n source_ids.append(s.id)\n source_names.append(s.name)\n if 'tags' in s.layout:\n tags.extend(s.layout.tags)\n \n base_name = ' - '.join(source_names)\n \n results_scenario_name = '{}; {}'.format(base_name, self.starttime.strftime('%Y-%m-%d %H:%M:%S'))\n results_scenario = {\n 'id': -1,\n 'name': results_scenario_name,\n 'description': '',\n 'network_id': self.network.id,\n 'layout': {'class': 'results', 'sources': source_ids, 'tags': tags}\n }\n #result = self.conn.call('add_scenario', {'network_id': self.network.id, 'scen': results_scenario})\n \n # save variable data to database\n for param_name, param_values in self.results.items():\n if param_name not in self.params:\n continue # it's probably an internal variable/parameter\n for idx, values in param_values.items():\n idx = list(idx)\n rt = self.params[param_name]['resource_type']\n if rt == 'link':\n n = 2\n fid = tuple(idx[:n])\n else:\n n = 1\n fid = idx[:n] # get the feature id\n del idx[:n] # delete the feature id (what's left are the blocks; there shouldn't be any, but this can be retained just in case)\n \n # define the dataset value\n dataset_value = json.dumps({'0': values}) \n \n ta = self.params[param_name]['type_attr']\n fid_name = tuple(fid + [ta['attr_name']])\n if fid_name not in self.conn.res_attr_lookup:\n continue\n ra_id = self.conn.res_attr_lookup[fid_name]\n attr_id = ta['attr_id']\n attr = self.conn.attrs[rt][attr_id]\n dataset_name = '{} - {} - {} [{}]'.format(\n self.network.name, param_name, attr['name'], results_scenario_name\n )\n \n # create the dataset\n dataset = {\n 'type': attr['dtype'],\n 'name': dataset_name,\n 'unit': attr['unit'],\n 'dimension': attr['dim'],\n 'value': dataset_value\n }\n \n res_scen = {\n 'resource_attr_id': ra_id,\n 'attr_id': attr_id,\n 'dataset_id': None,\n 'value': dataset \n }\n res_scens.append(res_scen)\n \n # save results to database\n scenario = self.conn.call('add_scenario', {'network_id': self.network.id, 'scen': results_scenario})\n scenario['resourcescenarios'].extend(res_scens)\n result = self.conn.call('update_scenario', {'scen': scenario})\n\n ","sub_path":"model/systems.py","file_name":"systems.py","file_ext":"py","file_size_in_byte":18207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"548582799","text":"class Solution(object):\n def canAttendMeetings(self, intervals):\n if not intervals:\n return True\n intervals.sort(key=lambda val: val.start)\n end = intervals[0].end\n for index in range(1, len(intervals)):\n if intervals[index].start < end:\n return False\n end = max(end, intervals[index].end)\n return True\n","sub_path":"252/252.meeting-rooms.156181042.Accepted.leetcode.py","file_name":"252.meeting-rooms.156181042.Accepted.leetcode.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"568054131","text":"import languagemodel as lm\n\ndef buildModel(data, lmda, k, outputfile):\n vocab = lm.getVocab(data, k)\n counts = lm.getCounts(data, vocab, 3)\n context_counts = lm.getCounts(data, vocab, 2)\n for trigram, count in counts.items():\n t_split = trigram.split()\n context_count = context_counts[\"{} {}\".format(t_split[0], t_split[1])]\n p = lm.calcProbability(count, context_count, lmda, len(vocab))\n outputfile.write(\"{} {}\\n\".format(trigram, p))\n\n\ndef main():\n output = open(\"models/trigram.txt\", \"w\")\n data = lm.getLines(\"data/train.txt\", 3)\n buildModel(data, 1, 2, output)\n\nif __name__ == '__main__':\n \n main()\n\n\n","sub_path":"trigram.py","file_name":"trigram.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"433851423","text":"\"\"\"\nrun-cont.py\nMarley Samways\n\nThis script is to run GCMC/MD on a simulation box of pure water, sampling the entire system.\nThis is not how GCMC/MD would normally be run, but this is done in order to assess whether\nthe system will sample the correct density, where fluctuations in density arise from changes\nin the number of particles as the volume is held constant.\n\nThis script is intended to continue a stopped simulation\n\"\"\"\n\nimport numpy as np\nimport argparse\nfrom simtk.openmm.app import *\nfrom simtk.openmm import *\nfrom simtk.unit import *\n\nfrom openmmtools.integrators import BAOABIntegrator\n\nimport grand\n\n\ndef read_moves(filename):\n with open(filename, 'r') as f:\n lines = f.readlines()\n\n n_completed = int(lines[-1].split()[4])\n n_accepted = int(lines[-1].split()[7].strip('('))\n\n return n_completed, n_accepted\n\n\n# Check which run this is\nparser = argparse.ArgumentParser()\nparser.add_argument('-r', '--run', type=int, default=2,\n help='Which leg this represents in the full simulation')\nargs = parser.parse_args()\n\n# Loading some old variables\nn_moves, n_accepted = read_moves('density-{}.log'.format(args.run-1))\nghosts = grand.utils.read_ghosts_from_file('ghosts-{}.txt'.format(args.run-1))[-1]\n\n# Load in the .pdb water box (including ghosts) to get the topology\npdb = PDBFile('water-ghosts.pdb')\n\n# Load in the .rst7 to get the checkpointed positions and velocities\nrst7 = AmberInpcrdFile('restart-{}.rst7'.format(args.run - 1))\n\n# Load force field and create system\nff = ForceField('tip3p.xml')\nsystem = ff.createSystem(pdb.topology,\n nonbondedMethod=PME,\n nonbondedCutoff=12.0*angstroms,\n switchDistance=10.0*angstroms,\n constraints=HBonds)\n\n# Make sure the LJ interactions are being switched\nfor f in range(system.getNumForces()):\n force = system.getForce(f)\n if 'NonbondedForce' == force.__class__.__name__:\n force.setUseSwitchingFunction(True)\n force.setSwitchingDistance(1.0*nanometer)\n\n# Create GCMC sampler object\ngcmc_mover = grand.samplers.StandardGCMCSystemSampler(system=system,\n topology=pdb.topology,\n temperature=298*kelvin,\n excessChemicalPotential=-6.09*kilocalorie_per_mole,\n standardVolume=30.345*angstroms**3,\n boxVectors=np.array(pdb.topology.getPeriodicBoxVectors()),\n log='density-{}.log'.format(args.run),\n ghostFile='ghosts-{}.txt'.format(args.run),\n rst='restart-{}.rst7'.format(args.run),\n overwrite=False)\n\n# Langevin integrator\nintegrator = BAOABIntegrator(298*kelvin, 1.0/picosecond, 0.002*picoseconds)\n\n# Define platform\nplatform = Platform.getPlatformByName('CUDA')\nplatform.setPropertyDefaultValue('Precision', 'mixed')\n\n# Set up system\nsimulation = Simulation(pdb.topology, system, integrator, platform)\nsimulation.context.setPositions(rst7.getPositions()) # Load positions from checkpoint\nsimulation.context.setVelocities(rst7.getVelocities()) # Load velocities from checkpoint\nsimulation.context.setPeriodicBoxVectors(*pdb.topology.getPeriodicBoxVectors())\n\n# Initialise the Sampler\ngcmc_mover.initialise(simulation.context, ghosts)\n# Set the number of moves to that left off at\ngcmc_mover.n_moves = n_moves\ngcmc_mover.n_accepted = n_accepted\n\n# Run simulation - want to run 50M GCMC moves total, walltime may limit this, so we write checkpoints\nwhile gcmc_mover.n_moves < 50000000:\n # Carry out 125 GCMC moves per 250 fs of MD\n simulation.step(125)\n gcmc_mover.move(simulation.context, 125)\n \n # Write data out every 0.5 ns\n if gcmc_mover.n_moves % 250000 == 0:\n gcmc_mover.report(simulation)\n \n\n","sub_path":"water-density/gcmc-md/sim-params/run-cont.py","file_name":"run-cont.py","file_ext":"py","file_size_in_byte":4113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"615055082","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nProvide routines to import DPLA project data set into list of lists format.\n& do a query & filter by one of the 4 fields\n\nFields wanted:\n 1. Search Term\n 2. ID\n 3. Ingest Date\n 4. Data Provider\n\nPARAMETERS\n &fields=id,dataProvider,ingestDate # there is an issue with ingestDate and it does not work like this\n &sort_order= 'asc' or 'desc'\n # SORT ON BY ID\n &sort_by= 'id' or 'dataProvider' or 'ingestDate'\n &api_key\n\nthings to consider:\nhow to handle an error when reading a file ?\n\nFor each item, the parent object docs contains information about how that item was imported into the database: for example, ingestDate and other context about the record (see @context).\nDown in the sourceResource object, there’s information about the title and subject of the work. Here, the enumerated subject name: \"Weasels\" probably accounts for this being the first result.\n\n\"\"\"\n\n\nimport json\nimport csv\nimport urllib.request\nimport argparse\nfrom operator import itemgetter\n\n\nparser = argparse.ArgumentParser(description='DPLA api call')\n#make the below necessary\n#type check!\nparser.add_argument('-f', required=True,action='store',help='filename of input')\nparser.add_argument('-o', action='store',help='filename of output')\nparser.add_argument('--resource',required=True,action='store',help='the resource_type',choices=['items','collections'])\nparser.add_argument('-s',action='store',required=True,help='the field to sort on', choices=['id','dataProvider','ingestDate'])\nparser.add_argument('--asc',action=\"store_true\",help='sort by the specified field, smallest to largest')\nparser.add_argument('--desc',action=\"store_true\",help='sort by the specified field, largest to smallest')\nargs = vars(parser.parse_args())\n\n# change these for other api calls\nbase_URL = 'https://api.dp.la/v2/'\napi_key = 'bd42082e8bd7b7eedf534a0256da1b6d'\nfields = ['id','dataProvider','ingestDate']\nstringfields = ','.join(fields)\n\nclass get_json:\n def __init__(self, url, api_key):\n self.url = url\n self.key = '&api_key='+api_key # i would like to make this individual to me\n ## need to be set ##\n self.qterm = ''\n self.resource =None\n ## not required ##\n self.sort_by= '' #'&sort_by=' #single field\n self.sort_order = '' #'&sort_order=' #asecending or descending\n ## assumed ##\n self.fields = '&fields=' + stringfields # hard-coded - not ideal\n\n # Method for setting query\n def set_query(self,query=None):\n if not query:\n raise NameError('Provide a term to query for the API!')\n else:\n self.qterm=query\n\n # Method for setting query\n def set_resource(self,resource=None):\n if not resource:\n raise NameError('Provide a term to resource for the API!')\n else:\n self.resource = resource\n\n def set_sort(self, sort_by=None, sort_order='asc'):\n #ascending or descending ?\n if not sort_by:\n raise NameError('Provide a field to sort by : search_term, ID, ingest_date, data_provider')\n elif sort_by not in fields:\n raise NameError('Provide a proper field to sort by : search_term, ID, ingest_date, data_provider')\n else:\n #typecheck that its in the fields !\n self.sort_by = sort_by\n if sort_order == 'desc':\n self.sort_order ='desc'\n else:\n self.sort_order ='asc'\n\n # Extract data from json api\n def get_data(self):\n if self.resource == None or self.qterm == 'q=': # must have self.resource .qterm and key filled out.\n raise( 'set a qterm and resource before you call the api')\n else: #+ ' &fields='+self.fields +'&sort_by=' +self.sort_by + '&sort_order='+self.sort_order\n url = self.url + self.resource +'?'+ 'q='+self.qterm + self.key\n ## ideally url would = self.url + self.resource +'?'+ self.qterm + self.fields + self.sort_by + self.sort_order+ self.key\n ## however, i was having an issue with ingestDate as a field so i am pulling the full query and then\n print(url)\n with urllib.request.urlopen(url) as url:\n data = json.loads(url.read().decode())\n count = data['count'] # total number of items that match that query\n #max number of objects returned per page is 500. if not specified 10 are given.\n #url = self.url + self.resource +'?'+ 'q='+self.qterm +page_size=500 + self.key\n if count > 500:\n pages = count // 500\n if count % 500 != 0 : pages +=1\n else: #otherwise we have less than 500 objects so one page will suffice\n pages = 1\n print(\"pages\",pages,\"count\",count)\n final_data = []\n for i in range(1,pages+1):# now pull for each page.\n url = self.url + self.resource +'?'+ 'q='+self.qterm +'&page_size=500&page='+str(i) + self.key\n print(url,\"\\n\")\n with urllib.request.urlopen(url) as url:\n data = json.loads(url.read().decode())\n dataset = data['docs']\n keys = {'id','dataProvider','ingestDate'}\n filtered_data= list(map(lambda x: {k:v for k, v in x.items() if k in keys}, dataset)) # reduces to the 3 fields we want\n filtered_data = [dict(item, **{'query':self.qterm}) for item in filtered_data] # adds the query as a field\n final_data += filtered_data\n print(\"did we get all objects?: \", count==len(final_data)) # just to check we have everything\n\n # sorting if specified - reverse=True is descending\n if self.sort_by:\n if self.sort_order == 'desc':\n final_data = sorted(final_data, key=itemgetter(self.sort_by), reverse=True)\n else: #defaults to ascending\n final_data = sorted(final_data, key=itemgetter(self.sort_by))\n return final_data\n\n def write_to_csv(self,data,file_name):\n #file_name must be a string\n if file_name == None:\n file_name = 'results'\n with open( file_name +'.csv', 'w', newline='') as csvfile:\n header = data[0].keys()\n writer = csv.DictWriter(csvfile, fieldnames=header)\n writer.writeheader()\n for i in range(0,len(data)):\n writer.writerow(data[i])\n\n\nif __name__ == '__main__':\n # dpla = get_json(base_URL)\n print(args,\"\\n\") # example = {'f': 'sample_input.txt', 'o': 'results', 'resource': 'items', 's': 'id', 'asc': True, 'desc': False}\n with open(args['f']) as f:\n queries = f.read().splitlines()\n dpla = get_json(base_URL,api_key)\n dpla.set_resource(args['resource'])\n if args['desc'] == False:\n dpla.set_sort(args['s'],'asc')\n else:\n dpla.set_sort(args['s'],'desc')\n results = []\n for q in queries:\n dpla.set_query(q) # this will be varied\n dataset = dpla.get_data()#['docs']\n results += dataset\n dpla.write_to_csv(results,args['o'])\n\n\n ##### HARD CODED EXAMPLE #####\n #queries = ['kittens','kitten','cat']\n #dpla = get_json(base_URL,api_key)\n #dpla.set_resource('items')\n #dpla.set_sort('id','asc')\n #results = []\n #for q in queries:\n # dpla.set_query('kittens') # this will be varied\n # dataset = dpla.get_data()#['docs']\n # results += dataset\n #dpla.write_to_csv(results,'kittens')\n","sub_path":"JSON_API/data_set_importer.py","file_name":"data_set_importer.py","file_ext":"py","file_size_in_byte":7423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"114708411","text":"\nimport pickle\nfrom flask import Flask\nfrom flask import request, jsonify\n\napp = Flask(\"churn\")\n\nC = 1.0\noutput_file = f'model_C={C}.bin'\n\n# Load the model \nwith open(output_file, 'rb') as f_in:\n dv, model = pickle.load(f_in)\n\n@app.route('/predict', methods=[\"POST\"])\ndef predict():\n customer = request.get_json()\n x = dv.transform([customer])\n pred = model.predict_proba(x)[0,1]\n\n churn = pred >= 0.5\n\n result = {\n 'churn probability':float(pred),\n 'churn': bool(churn)\n }\n \n return jsonify(result) \n\nif __name__ == \"__main__\":\n app.run(debug=True, host='0.0.0.0', port=9696)\n\n","sub_path":"course-zoomcamp/05-deployment/code/predict_v1.py","file_name":"predict_v1.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"361014467","text":"'''\n\nA perfect number is a number for which the sum of its proper divisors is exactly equal to the number. \nFor example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.\n\nA number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.\n\nAs 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. \nBy mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. \nHowever, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number \nthat cannot be expressed as the sum of two abundant numbers is less than this limit.\n\nFind the sum of all the positive integers which cannot be written as the sum of two abundant numbers.\n\n'''\n\n'''\n\nFor mathematical explication of the solution, see:\n\nhttps://mathschallenge.net/index.php?section=faq&ref=number/sum_of_divisors\n\n'''\n\ndef getPrimes(N):\n\tprimeArray = [2,3] # 2 and 3 are primes\n\tmaxNumber = int(N/2) + 1\n\tfor number in range(5,maxNumber,2):\n\t\tif isPrime(number,primeArray):\n\t\t\tprimeArray.append(number)\n\treturn primeArray\n\ndef isPrime(n,primeArray):\n\tfor prime in primeArray:\n\t\tif n % prime == 0:\n\t\t\treturn False\n\t\tif prime*prime > n:\n\t\t\treturn True\n\treturn True\n\ndef getSumDivisors(number,primeArray):\n\tsumDivisors = 1\n\tfor prime in primeArray:\n\t\tif prime > number:\n\t\t\tbreak\n\t\tif number % prime == 0:\n\t\t\ta = 1\n\t\t\twhile True:\n\t\t\t\tif number % prime**(a+1) == 0:\n\t\t\t\t\ta += 1\n\t\t\t\telse:\n\t\t\t\t\tbreak\n\t\t\tsumDivisors *= (prime**(a+1) - 1) / (prime - 1)\n\treturn sumDivisors - number\n\ndef notSum(N,abundantNumbers):\n\tarray = []\n\tfor number in range(1,N):\n\t\tfor i in abundantNumbers:\n\t\t\tif not abundantNumbers[i]:\n\t\t\t\tcontinue\n\t\t\tif 2*i > number:\n\t\t\t\tarray.append(number)\n\t\t\t\tbreak\n\t\t\ta = number-i\n\t\t\tif abundantNumbers[a]:\n\t\t\t\tbreak\n\treturn(array)\n\n\nif __name__ == '__main__':\n\tN = 28123\n\tprimeArray = getPrimes(N)\n\tabundantNumbers = {}\n\tfor i in range(1,N+1):\n\t\tabundantNumbers[i] = getSumDivisors(i,primeArray) > i\n\tprint(sum(notSum(N,abundantNumbers)))\n\n\n\n\n","sub_path":"Problem23.py","file_name":"Problem23.py","file_ext":"py","file_size_in_byte":2223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"74353703","text":"#List các document\ndocuments = []\ndocuments.append(\"the quick brown fox jumps over the lazy dog and\")\ndocuments.append(\"never jump over the lazy dog quickly\")\n#['the quick brown fox jumps over the lazy dog and',\n# 'never jump over the lazy dog quickly']\n\n#List các từ trong mỗi document sau khi split\nbow = []\nfor doc in documents:\n bow.append(set(doc.split(\" \")))\n# [{'jumps', 'quick', 'and', 'brown', 'dog', 'fox', 'over', 'lazy', 'the'},\n# {'quickly', 'jump', 'never', 'dog', 'over', 'lazy', 'the'}]\n\n#List các tất cả từ đã split\nword_dict = set()\nfor word in bow:\n word_dict = word_dict.union(word)\n#{'lazy', 'fox', 'brown', 'and', 'over', 'dog', 'jump',\n# 'never', 'quick', 'jumps', 'the', 'quickly'}\n\ncount_word=[] #Số lần xuất hiện mỗi từ, chứa mỗi document với các từ đã split\n#Đếm số lần xuất hiện mỗi từ trong 1 document\nfor doc in documents:\n senc=doc.split(\" \")\n # print(senc)\n list_word={}\n for w in senc:\n try:\n list_word[w] += 1\n except:\n list_word[w] = 1\n count_word.append(list_word)\n#[{'the': 2, 'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1,\n# 'over': 1,'lazy': 1, 'dog': 1, 'and': 1},\n# {'never': 1, 'jump': 1, 'over': 1, 'the': 1, 'lazy': 1, 'dog': 1, 'quickly': 1}]\n\n# Tìm những từ không xuất hiện trong 1 document và gán = 0\nfor word in word_dict:\n for sentence in count_word:\n try:\n if sentence[word]!=0:\n pass\n except:\n sentence[word]=0\n#count_word:\n#[\n # {'the': 2, 'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1, 'over': 1, 'lazy': 1,\n # 'dog': 1, 'and': 1, 'never': 0, 'quickly': 0, 'jump': 0\n # },\n\n # {'never': 1, 'jump': 1, 'over': 1, 'the': 1, 'lazy': 1, 'dog': 1, 'quickly': 1,\n # 'and': 0, 'brown': 0, 'fox': 0, 'jumps': 0, 'quick': 0\n # }\n# ]\n\n# word_dictX = []\n# for word in word_dict:\n# word_dictX.append(dict.fromkeys(word_dict, 0))\n# # print(word_dictX)\n\n\ndef compute_TF(word_dict, bow):\n tf_dict = {}\n bow_count = len(bow)\n for word, count in word_dict.items():\n tf_dict[word] = count/float(bow_count)\n return tf_dict\ntf_bow = []\nfor i in range(len(count_word)):\n tf_bow.append(compute_TF(count_word[i], bow[i]))\n#tf_bow:\n#[\n # {'the': 0.2222222222222222, 'quick': 0.1111111111111111,\n # 'brown': 0.1111111111111111, 'fox': 0.1111111111111111,\n # 'jumps': 0.1111111111111111, 'over': 0.1111111111111111,\n # 'lazy': 0.1111111111111111, 'dog': 0.1111111111111111,\n # 'and': 0.1111111111111111, 'jump': 0.0, 'never': 0.0,\n # 'quickly': 0.0\n # },\n # {'never': 0.14285714285714285,\n # 'jump': 0.14285714285714285, 'over': 0.14285714285714285,\n # 'the': 0.14285714285714285, 'lazy': 0.14285714285714285,\n # 'dog': 0.14285714285714285, 'quickly': 0.14285714285714285,\n # 'quick': 0.0, 'and': 0.0, 'jumps': 0.0,\n # 'fox': 0.0, 'brown': 0.0\n # }\n# ]\n\ndef computeIDF(docList):\n import math\n idfDict = {}\n N = len(docList)\n\n idfDict = dict.fromkeys(docList[0].keys(), 0)\n for doc in docList:\n for word, val in doc.items():\n if val > 0:\n idfDict[word] += 1\n\n for word, val in idfDict.items():\n idfDict[word] = math.log(N / float(val))\n\n return idfDict\n\nidf_bow = computeIDF(count_word)\n# idf_bow:\n# {'the': 0.0, 'quick': 0.6931471805599453,\n# 'brown': 0.6931471805599453, 'fox': 0.6931471805599453,\n# 'jumps': 0.6931471805599453, 'over': 0.0,\n# 'lazy': 0.0, 'dog': 0.0,\n# 'and': 0.6931471805599453, 'quickly': 0.6931471805599453,\n# 'jump': 0.6931471805599453, 'never': 0.6931471805599453\n# }\n\ndef computeTFIDF(tfBow, idfs):\n tfidf = {}\n for word, val in tfBow.items():\n tfidf[word] = val * idfs[word]\n return tfidf\n\ntf_idf_bow = []\nfor i in range(len(tf_bow)):\n tf_idf_bow.append(computeTFIDF(tf_bow[i], idf_bow))\nprint('='*100 + f'\\n{tf_idf_bow}')\n\n#Export to Dataframe\nimport pandas as pd\n\n#From DF\ndfTotal=pd.DataFrame()\nfor tfbow in range (len(tf_bow)):\n df = pd.DataFrame([tf_bow[tfbow]])\n dfTotal = dfTotal.append(df)\nprint('='*100 + f'\\nDF:\\n {dfTotal}\\n')\nexport_csv = dfTotal.to_csv('df_CSV.csv', index=True, header=True)\n\n#From IDF\nidfTotal=pd.DataFrame([idf_bow])\nprint('='*100 + f'\\nIDF:\\n {idfTotal}\\n')\nexport_csv = idfTotal.to_csv('idf_CSV.csv', index=True, header=True)\n\n#From TF_IDF\ntf_idfTotal=pd.DataFrame()\nfor t_i_bow in range (len(tf_idf_bow)):\n df = pd.DataFrame([tf_idf_bow[t_i_bow]])\n tf_idfTotal = tf_idfTotal.append(df)\nprint('='*100 + f'\\nTF_IDF:\\n {tf_idfTotal}\\n')\nexport_csv = dfTotal.to_csv('tf_idf_CSV.csv', index=True, header=True)\n","sub_path":"TF_IDF_TFIDF.py","file_name":"TF_IDF_TFIDF.py","file_ext":"py","file_size_in_byte":4713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"156036041","text":"# -*- coding: utf-8 -*-\n# 实例65:构建多层双向RNN对MNIST数据集分类\n\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n\n# (1)分析图片的特点\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\nprint(\"训练数据集的shape:\", mnist.train.images.shape)\nprint(\"测试数据集的shape: \", mnist.test.images.shape)\n\n# (2)定义占位符\n# 定义时间序列的个数\ntime_steps = 28\n# 定义每一个序列的维度\ninput_dim = 28\n# 定义隐藏层的节点个数\nhidden_dim = 128\n# 定义输出层的分类个数(0-9数字)\nclasses_dim = 10\n\nx = tf.placeholder(\"float\", [None, time_steps, input_dim])\ny = tf.placeholder(\"float\", [None, classes_dim])\n\n# (3)构建模型\n# x的shape是[None, time_steps, input_dim]\n# x_unstack是list类型,其对应的“shape”是(time_steps, None, input_dim)\nx_unstack = tf.unstack(x, axis=1)\n\n# 多层循环神经网络\nstacked_basic_rnn_cell_fw = []\nstacked_basic_rnn_cell_bw = []\nfor i in range(3):\n stacked_basic_rnn_cell_fw.append(tf.contrib.rnn.BasicRNNCell(hidden_dim))\n stacked_basic_rnn_cell_bw.append(tf.contrib.rnn.BasicRNNCell(hidden_dim))\n\n# 静态多层双向循环神经网络\n# tf.contrib.rnn.stack_bidirectional_rnn()返回(outputs,output_state_fw,output_state_bw)\noutputs, _, _ = tf.contrib.rnn.stack_bidirectional_rnn(stacked_basic_rnn_cell_fw, stacked_basic_rnn_cell_bw, x_unstack, dtype=tf.float32)\n# 定义学习率\nlearning_rate = 0.001\n# 全连接层:预测\n# outputs[-1]的shape为(None,hidden_dim)\n# pred的shape为(None. classes_dim)\npred = tf.contrib.layers.fully_connected(outputs[-1], classes_dim, activation_fn=None)\n# 损失值\ncost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=pred, labels=y))\n# 优化器\noptimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)\n\n# 正确率\ncorrect_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n\n# 训练次数\ntraining_epochs = 1000\n# 每一次训练的图片数量\nbatch_size = 128\n# 每次训练将中间状态显示出来(损失值和准确率)\ndisplay_step = 100\n\n# 训练\nwith tf.Session() as sess:\n # 初始化session\n sess.run(tf.global_variables_initializer())\n for epoch in range(training_epochs):\n # 获得训练图片,每一幅图片是1行784列(28*28)\n # batch_x的shape为[batch_size, 784]=[128, 784]\n # batch_y的shape为[batch_size, classes_dim]=[128, 10]\n batch_x, batch_y = mnist.train.next_batch(batch_size)\n # 重构训练图片矩阵,shape为[batch_size, time_steps, input_dim]=[128, 28, 28]\n batch_x = batch_x.reshape((batch_size, time_steps, input_dim))\n # 训练\n sess.run(optimizer, feed_dict={x: batch_x, y: batch_y})\n # 训练的损失值和损失值\n if epoch % display_step == 0:\n # 准确率\n accuracy_value = sess.run(accuracy, feed_dict={x: batch_x, y: batch_y})\n # 损失值\n cost_value = sess.run(cost, feed_dict={x: batch_x, y: batch_y})\n print(\"训练\" + str(epoch + 100) + \"次,\"\n + \"损失值cost = {:.6f},\".format(cost_value)\n + \"准确率accuracy = {:.5f}\".format(accuracy_value))\n\n test_size = 128\n test_data = mnist.test.images[:test_size].reshape((-1,time_steps, input_dim))\n test_label = mnist.test.labels[:test_size]\n test_accuracy_value = sess.run(accuracy, feed_dict={x: test_data, y:test_label})\n print(\"测试-准确率accuracy = {:.5f}\".format(test_accuracy_value))","sub_path":"tf09/example65.py","file_name":"example65.py","file_ext":"py","file_size_in_byte":3631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"583737330","text":"import logging\nimport os.path\n\nfrom nosedjango.plugins.base_plugin import Plugin\n\n\nclass PstatPlugin(Plugin):\n name = 'pstat'\n\n def beforeTestSetup(self, settings, setup_test_environment, connection):\n logging.getLogger().setLevel(logging.WARNING)\n switched_settings = {\n 'DOCUMENT_IMPORT_STORAGE_DIR': 'document_import%(token)s',\n 'DOCUMENT_SETTINGS_STORAGE_DIR': 'document_settings%(token)s',\n 'ATTACHMENT_STORAGE_PREFIX': 'attachments%(token)s',\n 'MAILER_LOCKFILE': 'send_mail%(token)s',\n }\n settings.DOCUMENT_PRINTING_CACHE_ON_SAVE = False\n\n token = self.get_unique_token()\n for key, value in switched_settings.items():\n setattr(settings, key, value % {'token': token})\n settings.CACHES['default']['BACKEND'] = 'django.core.cache.backends.locmem.LocMemCache' # noqa\n settings.DISABLE_QUERYSET_CACHE = True\n\n def beforeFixtureLoad(self, settings, test):\n \"\"\"\n Need to wait until after beforeTestSetup is called in case the\n NoseDjango FileStoragePlugin is being used to give us an isolated\n media directory.\n\n Every test needs a new unique folder to avoid collisions.\n \"\"\"\n from django.core.cache import cache\n cache.clear()\n\n self.change_storage_settings(settings)\n\n def change_storage_settings(self, settings):\n \"\"\"\n Update all of the file storage paths to use our test directory and to\n be served from the proper URL.\n \"\"\"\n from django.core.files.storage import default_storage\n\n from pstat.printing.conf import settings as print_settings\n from pstat.document_backup.conf import settings as backup_settings\n from django.core.files.storage import FileSystemStorage\n\n # Can't use the normal switched_settings dict because these settings\n # live outside of the django default settings\n token = self.get_unique_token()\n if print_settings.PDF_STORAGE_BACKEND is FileSystemStorage:\n # Update the storage settings to use absolute paths or urls\n # relative to the current media settings\n storage_dir = 'pdf_cache/'\n storage_dir = os.path.abspath(\n os.path.join(default_storage.location, storage_dir))\n print_settings.PDF_STORAGE_DIR = storage_dir\n else:\n # Boto and other non-filesystem don't need absolute paths and urls\n # They do need a unique subdirectory path though, because the\n # NoseDjango FileStoragePlugin can't reliably empty a directory on\n # S3\n storage_dir = 'pdf_cache%s/' % token\n print_settings.PDF_STORAGE_DIR = storage_dir\n\n if backup_settings.STORAGE_BACKEND is FileSystemStorage:\n storage_dir = 'document_backup/'\n storage_dir = os.path.abspath(\n os.path.join(default_storage.location, storage_dir))\n backup_settings.STORAGE_DIR = storage_dir\n else:\n # Boto and other non-filesystem don't need absolute paths and urls\n # They do need a unique subdirectory path though, because the\n # NoseDjango FileStoragePlugin can't reliably empty a directory on\n # S3\n storage_dir = 'document_backup%s/' % token\n backup_settings.STORAGE_DIR = storage_dir\n","sub_path":"pstat_plugin.py","file_name":"pstat_plugin.py","file_ext":"py","file_size_in_byte":3404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"497020664","text":"from mpilot.libraries.eems.exceptions import MixedArrayShapes\n\n\nclass SameArrayShapeMixin(object):\n def validate_array_shapes(self, arrays, lineno=None):\n if len(arrays) == 1:\n return\n\n shape = arrays[0].shape\n\n for arr in arrays:\n if arr.shape != shape:\n raise MixedArrayShapes(shape, arr.shape, lineno)\n","sub_path":"mpilot/libraries/eems/mixins.py","file_name":"mixins.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"60302119","text":"import django\nfrom django.conf.urls import include, url\nfrom django.contrib import admin\n\n\nurlpatterns = [\n (\n url(r\"^admin/\", include(admin.site.urls))\n if django.VERSION < (2, 0)\n else url(r\"^admin/\", admin.site.urls)\n ),\n url(r\"^chaining/\", include(\"smart_selects.urls\")),\n]\n","sub_path":"test_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"404789356","text":"from django.shortcuts import render,redirect\nfrom django.contrib.auth.forms import UserCreationForm\nfrom .forms import UserRegistrationForm\nfrom django.contrib import messages\n\ndef register(request):\n\tif request.method==\"POST\":\n\t\t#form=UserCreationForm(request.POST)\n\t\tform=UserRegistrationForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tform.save()\n\t\t\tusername=form.cleaned_data.get('username')\n\t\t\tmessages.success(request,f'Account create for user {username}!')\n\t\t\treturn redirect('home')\n\telse:\t\n\t\t#form=UserCreationForm()\n\t\tform=UserRegistrationForm()\n\ttemplate=\"users/register.html\"\n\tcontext={'form':form,}\n\treturn render(request,template,context)\n\ndef home(request):\n\treturn render(request,'users/base.html',{})","sub_path":"registration_project/users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"285614656","text":"import cv2\nfrom random import randint\n\nclass Circle:\n\tdef __init__(self, x, y, thickness):\n\t\tself.x = x\n\t\tself.y = y\n\t\tself.r = 1\n\t\tself.growing = True\n\t\tself.thickness = thickness\n\t\tself.colour = (randint(50, 255), randint(50, 255), randint(50, 255))\n\n\tdef draw(self, img):\n\t\tcv2.circle(img, (self.x, self.y), self.r, self.colour, self.thickness, cv2.LINE_AA)\n\n\tdef grow(self):\n\t\tself.r += 1\n\t\tif self.r > 10:\n\t\t\tself.growing = False","sub_path":"Python/Circle Packing/circles.py","file_name":"circles.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"606644981","text":"import bs4 as bs\nimport urllib.request\nimport filter as filthy\nimport db\nATTRS = ('modell',\n\t'kilometer',\n\t'ps',\n\t'leergewicht',\n\t'getriebeart',\n\t'hubraum',\n\t'antriebsart',\n\t'anzahl türen',\n\t'anzahl sitze',\n\t'kraftstoff',\n\t'verbrauch')\n\t\ndef function(type):\n\ty = \"\"\n\tfor x in type:\n\t\ty += str(x.text)\n\ty+=\";\"\n\treturn(y)\n\ndef lister(tolist,whichitem=0):\n\tretlist = []\n\ttry:\n\t\tfor cont in tolist:\n\t\t\tretlist.append(''.join(cont.findAll(text=True)))\n\t\treturn retlist\n\texcept:\n\t\treturn False\n\t\ndef getcont(text):\n\tpermitls = ['1','2','3','4','5','6','7','8','9','0']\n\tretls = filter(lambda x:x in permitls,str(text))\n\tretls = list(retls)\n\tretstr = \"\"\n\tfor x in retls:\n\t\tretstr += x\n\ttry:return int(retstr)\n\texcept: return(\"-\")\nclass run():\n\tdef __init__(self,link):\n\t\tself.quitit = False\n\t\tprint(link)\n\t\tself.findict = dict()\n\t\tliste = []\n\t\tstringlist = \"\"\n\t\ttry:sauce = urllib.request.urlopen(link)\n\t\texcept:\n\t\t\tself.quitit=True\n\t\tif not self.quitit:\n\t\t\tsoup = bs.BeautifulSoup(sauce, 'lxml')\n\t\t\ttry:self.price = lister(soup.find('div',{'class':'price mdl-typography--font-light'}))[1]\n\t\t\texcept: self.price = False\n\t\t\tif self.price:\n\t\t\t\tself.price = getcont(self.price)\n\t\t\t\ttry:arttitle = lister(soup.find('div',{'class':'title'}))[0]\n\t\t\t\texcept: arttitle=lister(soup.find('div',{'class':'titleContainer--1koNs'}))[0]\n\t\t\t\tself.brand = filthy.getbrand(arttitle)\n\t\t\t\tmodel = filthy.getmodel(self,arttitle)\n\t\t\t\tself.findict['brand'] = self.brand\n\t\t\t\tself.findict['price'] = self.price\n\t\t\t\tself.findict['modell']= model\n\t\t\t\ttry:km = lister(soup.find('div',{'class':'mileage item'}))[1]\n\t\t\t\texcept: km = 0\n\t\t\t\tkm = getcont(km)\n\t\t\t\tself.findict['kilometer']=km\n\t\t\t\ttry:hp = lister(soup.find('div',{'class':'power item'}))[1]\n\t\t\t\texcept: hp = 'Unknown'\n\t\t\t\thp = getcont(hp)\n\t\t\t\tself.findict['ps'] = hp\n\t\t\t\tprop = soup.find_all('span', {'class' : 'jss170 jss172'})\n\n\t\t\t\tvalue = soup.find_all('span', {'class' : 'jss172'})\n\n\t\t\t\tif len(prop) == 0:\n\t\t\t\t\tprop = soup.find_all('span', {'class' : 'label'})\n\t\t\t\t\tvalue = soup.find_all('span', {'class' : 'value'})\n\t\t\t\tprop=lister(prop)\n\t\t\t\tvalue=lister(value)\n\t\t\t\tself.comblist = []\n\t\t\t\tfor x in range(len(prop)):\n\t\t\t\t\tself.comblist.append((prop[x],value[x]))\n\t\t\t\tfor x in self.comblist:\n\t\t\t\t\tif x[0].lower() in ATTRS:\n\t\t\t\t\t\tself.findict[x[0].lower()]=x[1]\n\t\t\telse:\n\t\t\t\tself.quitit = True\n\n\n","sub_path":"ReMake/Ricardo/ricardo_scraping_1.py","file_name":"ricardo_scraping_1.py","file_ext":"py","file_size_in_byte":2325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"149968803","text":"from django.db import models\nfrom django.utils import timezone\nfrom slugify import UniqueSlugify\nfrom .post import Post\nfrom django.db.models import Sum\nimport uuid\nfrom .profile import Profile\n\nclass Comment(models.Model):\n \"\"\"A comment over a post or reply to a comment.\n\n Args:\n models ([type]): [description]\n \"\"\"\n post = models.ForeignKey(Post,related_name='comments',on_delete=models.CASCADE)\n reply = models.ForeignKey('Comment',related_name='replies',on_delete=models.CASCADE,null=True,blank=True) \n\n uid = models.UUIDField(default = uuid.uuid4, editable = False,unique=True)\n profile = models.ForeignKey(Profile,related_name='comments',on_delete=models.CASCADE)\n text = models.TextField(blank=True,max_length=500)\n upvoted_by = models.ManyToManyField(Profile, related_name='upvoted_comments', blank=True)\n downvoted_by = models.ManyToManyField(Profile, related_name='downvoted_comments',blank=True)\n \n active = models.BooleanField(default=True)\n score = models.FloatField(default=0.0)\n\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n # Efficiency\n efficientMode = models.BooleanField(default=False)\n upvotes_count = models.IntegerField(default=1)\n downvotes_count = models.IntegerField(default=0)\n comments_count = models.IntegerField(default=0)\n\n def save(self, *args, **kwargs):\n super(Comment, self).save(*args, **kwargs)\n if(not self.efficientMode):\n self.upvotes_count=self.upvoted_by.count()\n self.downvotes_count=self.downvoted_by.count()\n n = self.replies.aggregate(Sum('comments_count'))['comments_count__sum']\n if(n!=None):\n self.comments_count=self.replies.count() + n\n super(Comment, self).save(*args, **kwargs)\n #update parent comment\n if(self.reply!=None):\n self.reply.save()\n #update post\n if(self.post!=None):\n if(not self.post.efficientMode):\n self.post.save()\n\n def __str__(self):\n return self.text\n\n def set_score(self):\n \"\"\"Calculates the rank score of a comment.\"\"\"\n GRAVITY = 1.2\n time_delta = timezone.now() - self.created\n post_hour_age = time_delta.total_seconds()\n post_points = self.upvotes_count - 1\n self.score = post_points / pow((post_hour_age + 2), GRAVITY)\n self.save()\n\n","sub_path":"forum/models/comment.py","file_name":"comment.py","file_ext":"py","file_size_in_byte":2476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"144154625","text":"import Queue\nimport collections\n\n\nclass Task(object):\n\n taskid = 0\n\n def __init__(self, target, uid, cmd):\n Task.taskid += 1\n self.tid = Task.taskid\n self.target = target\n self.uid = uid\n self.cmd = cmd\n self.sysret = None\n\n def syscall_ret(self, value):\n self.sysret = value\n\n def run_until_next_syscall(self):\n return self.target.send(self.sysret)\n\n\nclass KTaskd(object):\n def __init__(self):\n self.ready_task_queue = Queue.Queue()\n self.task_map = {}\n self.wait_map = collections.defaultdict(list)\n\n def new_task(self, func, uid=0, cmd=''):\n task = Task(func(), uid, cmd)\n self.task_map[task.tid] = task\n self.ready_task_queue.put(task)\n return task.tid\n\n def del_task(self, task):\n del self.task_map[task.tid]\n for waitting_task in self.wait_map.pop(task.tid, []):\n self.ready_task(waitting_task)\n\n def ready_task(self, task):\n self.ready_task_queue.put(task)\n\n def wait_for(self, task, tid):\n if tid in self.task_map:\n self.wait_map[tid].append(task)\n return True\n else:\n return False\n\n def main_loop(self):\n while self.task_map:\n task = self.ready_task_queue.get()\n try:\n syscall = task.run_until_next_syscall()\n if syscall:\n syscall.do(task, self) # let syscall make task ready\n else:\n self.ready_task(task)\n except StopIteration:\n self.del_task(task)\n","sub_path":"pyos/ktaskd.py","file_name":"ktaskd.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"17183880","text":"from pyspark.sql import SparkSession\nimport pyspark.sql.functions as F\nimport pyspark.sql.types as T\nimport databricks.koalas as ks\nimport numpy as np\nimport os\nimport traceback\nfrom collections import Mapping\nfrom math import isclose\nSEED = 102\nTASK_NAMES = ['task_' + str(i) for i in range(1, 9)]\nEXT = '.json'\nMASTER_IP = 'spark://0.0.0.0:7077'\n\n\nclass data_cat:\n review_filename = '/dsc102-pa2-public/dataset/user_reviews_train.csv'\n product_filename = '/dsc102-pa2-public/dataset/metadata_header.csv'\n product_processed_filename = '/dsc102-pa2-public/dataset/product_processed.csv'\n ml_features_train_filename = '/dsc102-pa2-public/dataset/ml_features_train.parquet'\n ml_features_test_filename = '/dsc102-pa2-public/dataset/ml_features_test.parquet'\n test_results_root = '/dsc102-pa2-public/test_results'\n\n\ndef quantile(rdd, p, sample=None, seed=SEED):\n \"\"\"Compute a quantile of order p ∈ [0, 1]\n :rdd a numeric rdd\n :p quantile(between 0 and 1)\n :sample fraction of and rdd to use. If not provided we use a whole dataset\n :seed random number generator seed to be used with sample\n \"\"\"\n assert 0 <= p <= 1\n assert sample is None or 0 < sample <= 1\n\n rdd = rdd if sample is None else rdd.sample(False, sample, seed)\n\n rddSortedWithIndex = (rdd.sortBy(lambda x: x).zipWithIndex().map(\n lambda x: (x[1], x[0])).cache())\n\n n = rddSortedWithIndex.count()\n h = (n - 1) * p\n\n rddX, rddXPlusOne = (rddSortedWithIndex.lookup(x)[0][0]\n for x in int(np.floor(h)) + np.array([0, 1]))\n return rddX + (h - np.floor(h)) * (rddXPlusOne - rddX)\n\n\ndef test_deco(f):\n def f_new(*args, test_dict=None, **kwargs):\n count = test_dict['count']\n failures = test_dict['failures']\n total_count = test_dict['total_count']\n test_name = test_dict['test_name']\n count += 1\n print ('Test {}/{} : {} ... '.format(count, total_count, test_name), end='') # noqa\n try:\n f(*args, **kwargs)\n print('Pass')\n except Exception as e:\n failures.append(e)\n print('Fail: {}'.format(e))\n traceback.print_exc()\n return count\n return f_new\n\n\nclass PA2Test(object):\n def __init__(self, spark, test_results_root):\n self.spark = spark\n self.test_results_root = test_results_root\n self.dict_res = {}\n for task_name in TASK_NAMES:\n try:\n df = self.spark.read.json(\n os.path.join(test_results_root, task_name + EXT), )\n self.dict_res[task_name] = df.collect()[0].asDict()\n except Exception as e:\n print(e)\n traceback.print_exc()\n self.dict_res['task_0'] = {\n 'count_total': 9430000, 'mean_price': 34.93735609456491}\n\n def test(self, res, task_name):\n row = 79\n start_msg = 'tests for {} '.format(task_name)\n comp_row = max(0, row - len(start_msg))\n comp_dashes = ''.join(['-' * comp_row])\n print (start_msg + comp_dashes)\n failures = []\n count = 0\n ref_res = self.dict_res[task_name]\n total_count = len(ref_res)\n test_dict = {\n 'count': count,\n 'failures': failures,\n 'total_count': total_count,\n 'test_name': None\n }\n if task_name in ['task_1', 'task_2', 'task_3', 'task_4']:\n for k, v in ref_res.items():\n test_name = k\n test_dict['test_name'] = test_name\n test_dict['count'] = count\n count = self.identical_test(\n test_name, res[k], v, test_dict=test_dict)\n elif task_name in ['task_7', 'task_8']:\n for k, v in ref_res.items():\n test_name = k\n test_dict['test_name'] = test_name\n test_dict['count'] = count\n count = self.identical_test(\n test_name, res[k], v, rel_tol=0.0, abs_tol=0.1, test_dict=test_dict)\n elif task_name == 'task_5':\n total_length = 10\n test_dict['total_count'] = 8\n at_least = 1\n ref_res_identical = {\n k: v\n for k, v in ref_res.items()\n if k in ['count_total', 'size_vocabulary']\n }\n\n for k, v in ref_res_identical.items():\n test_name = k\n test_dict['test_name'] = test_name\n test_dict['count'] = count\n count = self.identical_test(\n test_name, res[k], v, test_dict=test_dict)\n\n for k in ['word_0_synonyms', 'word_1_synonyms', 'word_2_synonyms']:\n res_v = dict(res[k])\n res_r = dict(map(tuple, ref_res[k]))\n test_name = '{}-length'.format(k)\n test_dict['test_name'] = test_name\n test_dict['count'] = count\n count = self.identical_length_test(\n k, res_v, list(range(total_length)), test_dict=test_dict)\n\n test_name = '{}-correctness'.format(k)\n test_dict['test_name'] = test_name\n test_dict['count'] = count\n count = self.synonyms_test(\n res_v, res_r, total_length, at_least, test_dict=test_dict)\n\n elif task_name == 'task_6':\n total_count = 9\n test_dict = {\n 'count': count,\n 'failures': failures,\n 'total_count': total_count,\n 'test_name': None\n }\n ref_res_identical = {\n k: v\n for k, v in ref_res.items() if k in ['count_total']\n }\n for k, v in ref_res_identical.items():\n test_name = k\n test_dict['test_name'] = test_name\n test_dict['count'] = count\n count = self.identical_test(\n test_name, res[k], v, test_dict=test_dict)\n for k in ['meanVector_categoryOneHot', 'meanVector_categoryPCA']:\n res_v = np.abs(res[k])\n res_r = np.abs(ref_res[k])\n test_name = '{}-length'.format(k)\n test_dict['test_name'] = test_name\n test_dict['count'] = count\n count = self.identical_length_test(\n k, res_v, res_r, test_dict=test_dict)\n\n for fname, fns in zip(('sum', 'mean', 'variance'),\n (np.sum, np.mean, np.var)):\n test_name = '{}-{}'.format(k, fname)\n test_dict['test_name'] = test_name\n test_dict['count'] = count\n vv = fns(res_v)\n vr = fns(res_r)\n count = self.identical_test(\n test_name, vv, vr, test_dict=test_dict)\n\n print('{}/{} passed'.format(total_count - len(failures), total_count))\n print (''.join(['-' * row]))\n return len(failures) == 0\n\n @test_deco\n def identical_length_test(self, k, v1, v2):\n size1 = len(v1)\n size2 = len(v2)\n assert size1 == size2, \\\n 'Length of {} must be {}, but got {} instead'.format(\n k, size2, size1)\n\n @test_deco\n def identical_test(self, k, v1, v2, rel_tol=1e-2, abs_tol=0.0):\n assert isclose(\n v1, v2, rel_tol=rel_tol, abs_tol=abs_tol), \\\n 'Value of {} should be close enough to {}, but got {} instead'.format(\n k, v2, v1)\n\n @test_deco\n def synonyms_test(self, res_v, res_r, total, at_least):\n if sum(res_v.values()) / len(res_v) < 0.9:\n print(\n \"WARNING: your top synonyms have an average score less than 0.9, this might indicate errors\"\n )\n correct = len(set(res_v.keys()).intersection(set(res_r.keys())))\n assert correct >= at_least, \\\n 'At least {} synonyms out of {} should overlap with our answer, got only {} instead'. \\\n format(at_least, total, correct)\n\n\ndef spark_init(pid):\n spark = SparkSession.builder.master(\"spark://spark-master:7077\")\\\n .config(\"spark.dynamicAllocation.enabled\", 'false')\\\n .config(\"spark.sql.crossJoin.enabled\", \"true\")\\\n .config(\"spark.memory.fraction\", \"0.90\")\\\n .config(\"spark.executor.memory\", \"18G\")\\\n .config(\"spark.driver.memory\", \"3G\")\\\n .config(\"spark.driver.extraLibraryPath\", \"/opt/hadoop/lib/native\")\\\n .config(\"spark.driver.port\", \"20002\")\\\n .config(\"spark.blockManager.port\", \"50002\")\\\n .config(\"spark.fileserver.port\", \"6002\")\\\n .config(\"spark.broadcast.port\", \"60003\")\\\n .config(\"spark.replClassServer.port\", \"60004\")\\\n .config(\"spark.port.maxRetries\", \"1\")\\\n .appName(pid)\\\n .getOrCreate()\n return spark\n\n\nclass PA2Data(object):\n review_schema = T.StructType([\n T.StructField('reviewerID', T.StringType(), False),\n T.StructField('asin', T.StringType(), False),\n T.StructField('overall', T.FloatType(), False)\n ])\n product_schema = T.StructType([\n T.StructField('asin', T.StringType()),\n T.StructField('salesRank', T.StringType()),\n T.StructField('categories', T.StringType()),\n T.StructField('title', T.StringType()),\n T.StructField('price', T.FloatType()),\n T.StructField('related', T.StringType())\n ])\n product_processed_schema = T.StructType([\n T.StructField('asin', T.StringType()),\n T.StructField('title', T.StringType()),\n T.StructField('category', T.StringType())\n ])\n salesRank_schema = T.MapType(T.StringType(), T.IntegerType())\n categories_schema = T.ArrayType(T.ArrayType(T.StringType()))\n related_schema = T.MapType(T.StringType(), T.ArrayType(T.StringType()))\n schema = {\n 'review': review_schema,\n 'product': product_schema,\n 'product_processed': product_processed_schema\n }\n metadata_schema = {\n 'salesRank': salesRank_schema,\n 'categories': categories_schema,\n 'related': related_schema\n }\n\n def __init__(self,\n spark,\n path_dict,\n output_root,\n deploy,\n input_format='dataframe'\n ):\n self.spark = spark\n self.path_dict = path_dict\n self.output_root = output_root\n self.deploy = deploy\n self.input_format = input_format\n\n def load(self, name, path, infer_schema=False):\n if name in ['ml_features_train', 'ml_features_test']:\n data = self.spark.read.parquet(path)\n else:\n schema = self.schema[name] if not infer_schema else None\n data = self.spark.read.csv(\n path,\n schema=schema,\n escape='\"',\n quote='\"',\n inferSchema=infer_schema,\n header=True\n )\n if name == 'product':\n for column, column_schema in self.metadata_schema.items():\n if column in data.columns:\n data = data.withColumn(column, F.from_json(\n F.col(column), column_schema))\n return data\n\n def load_all(self, input_format='dataframe', no_cache=False):\n self.input_format = input_format\n print (\"Loading datasets ...\", end='') # noqa\n data_dict = {}\n count_dict = {}\n for name, path in self.path_dict.items():\n\n data = self.load(name, path)\n if input_format == 'rdd':\n data = data.rdd\n elif input_format == 'koalas':\n data = data.to_koalas()\n if self.deploy and not no_cache:\n data = data.cache()\n data_dict[name] = data\n count_dict[name] = data.count() if not no_cache else None\n print (\"Done\")\n return data_dict, count_dict\n\n def cache_switch(self, data_dict, part):\n count_dict = {}\n if self.input_format == 'koalas':\n print('cache_switch() has no effect on Koalas')\n else:\n part_1_data = ['product', 'review', 'product_processed']\n part_2_data = ['ml_features_train', 'ml_features_test']\n if part == 'part_1':\n data_dict, count_dict = self.switch(data_dict, part_1_data, part_2_data)\n elif part == 'part_2':\n data_dict, count_dict = self.switch(data_dict, part_2_data, part_1_data)\n else:\n raise ValueError\n return data_dict, count_dict\n\n def switch(self, data_dict, to_persist, to_unpersist):\n count_dict = {}\n for name in to_unpersist:\n try:\n data_dict[name].unpersist()\n except Exception as e:\n pass\n for name in to_persist:\n data_dict[name] = data_dict[name].cache()\n count_dict[name] = data_dict[name].count()\n return data_dict, count_dict\n\n def save(self, res, task_name, filename=None):\n if task_name in TASK_NAMES or task_name in ['task_0', 'summary']:\n if not filename:\n filename = task_name\n if isinstance(res, Mapping):\n df = self.spark.createDataFrame([res])\n else:\n df = self.spark.createDataFrame(res)\n output_path = 'file://' + os.path.join(\n self.output_root, filename + EXT)\n df.coalesce(1).write.mode('overwrite').json(output_path)\n else:\n raise ValueError\n","sub_path":"utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":13644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"206706262","text":"import httplib2, http, asyncio\nfrom apiclient.http import MediaFileUpload\nfrom apiclient.errors import HttpError\n\nimport os\nimport time\nimport asyncio\n\nclass MaxRetryExceeded(Exception):\n pass\nclass UploadFailed(Exception):\n pass\n\nclass Youtube:\n\n MAX_RETRIES = 10\n\n RETRIABLE_EXCEPTIONS = (httplib2.HttpLib2Error, IOError,\n http.client.NotConnected,\n http.client.IncompleteRead,\n http.client.ImproperConnectionState,\n http.client.CannotSendRequest,\n http.client.CannotSendHeader,\n http.client.ResponseNotReady,\n http.client.BadStatusLine)\n\n RETRIABLE_STATUS_CODES = [500, 502, 503, 504]\n\n def __init__(self, auth, chunksize=-1):\n self.youtube = auth\n self.request = None\n self.chunksize = chunksize\n self.response = None\n self.error = None\n self.retry = 0\n\n\n\n\n async def upload_video(self, video, properties, progress=None):\n self.progress = progress\n self.video = video\n self.properties = properties\n\n body = dict(\n snippet=dict(\n title = self.properties.get('title'),\n description = self.properties.get('description'),\n tags = self.properties.get('tags'),\n categoryId = self.properties.get('category')\n ),\n status=dict(\n privacyStatus=self.properties.get('privacyStatus')\n )\n )\n\n media_body = MediaFileUpload(self.video, chunksize = self.chunksize,\n resumable = True, mimetype=\"application/octet-stream\"\n )\n\n\n self.request = self.youtube.videos().insert(part = ','.join(body.keys()), body=body, media_body=media_body)\n\n self.method = \"insert\"\n \n loop = asyncio.get_running_loop()\n \n await loop.run_in_executor(None, self._resumable_upload)\n \n return self.response\n\n def _resumable_upload(self):\n response = None\n while response is None:\n try:\n status, response = self.request.next_chunk()\n if response is not None:\n if('id' in response):\n self.response = response\n else:\n self.response = None\n raise UploadFailed(\"The file upload failed with an unexpected response:{}\".format(response))\n except HttpError as e:\n if e.resp.status in self.RETRIABLE_STATUS_CODES:\n self.error = \"A retriable HTTP error {} occurred:\\n {}\".format(e.resp.status, e.content)\n else:\n raise\n except self.RETRIABLE_EXCEPTIONS as e:\n self.error = \"A retriable error occurred: {}\".format(e)\n\n if self.error is not None:\n print(self.error)\n self.retry += 1\n\n if self.retry > self.MAX_RETRIES:\n raise MaxRetryExceeded(\"No longer attempting to retry.\")\n\n max_sleep = 2 ** self.retry\n sleep_seconds = random.random() * max_sleep\n\n print(\"Sleeping {} seconds and then retrying...\".format(sleep_seconds))\n time.sleep(sleep_seconds)\n\n\nasync def print_response(response):\n for key, value in response.items():\n print(key, \" : \", value, '\\n\\n')\n","sub_path":"youtube_upload/youtube.py","file_name":"youtube.py","file_ext":"py","file_size_in_byte":3483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"153124430","text":"import re\nfrom datetime import timedelta\n\nregex = re.compile(r'((?P\\d+?)hr)?((?P\\d+?)m)?((?P\\d+?)s)?')\n\ndef parse_time(time_str):\n parts = regex.match(time_str)\n if not parts:\n return\n parts = parts.groupdict()\n time_params = {}\n for (name, param) in parts.items():\n if param:\n time_params[name] = int(param)\n return timedelta(**time_params)\n\n\ndef verbose_timedelta(delta):\n hours, remainder = divmod(delta.seconds, 3600)\n minutes, seconds = divmod(remainder, 60)\n dstr = \"%s day%s\" % (delta.days, \"s\"[delta.days==1:])\n hstr = \"%s hour%s\" % (hours, \"s\"[hours==1:])\n mstr = \"%s minute%s\" % (minutes, \"s\"[minutes==1:])\n sstr = \"%s second%s\" % (seconds, \"s\"[seconds==1:])\n dhms = [dstr, hstr, mstr, sstr]\n for x in range(len(dhms)):\n if not dhms[x].startswith('0'):\n dhms = dhms[x:]\n break\n dhms.reverse()\n for x in range(len(dhms)):\n if not dhms[x].startswith('0'):\n dhms = dhms[x:]\n break\n dhms.reverse()\n return ', '.join(dhms)\n","sub_path":"sm/libary/timeparser.py","file_name":"timeparser.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"44587160","text":"# Usage: \n#\tpython 1.5.combineCollapsedFiles.py \n\n# Where:\n#\t\t\t\tlocation of data\n#\t\t\t\toutput file name (no directory; eg _merged.txt)\n# \t\t\thowever many input files you wish to input\n\nimport sys\n\ndataDir=sys.argv[1]\noutputFileName=sys.argv[2]\ninputFileNames=sys.argv[3:]\nseqs={}\n\nfor fn in inputFileNames:\n\tfor line in open(fn):\n\t\ta=line.rstrip().split(\"\\t\")\n\t\tif a[0] in seqs:\n\t\t\tseqs[a[0]]+=int(a[1])\n\t\telse:\n\t\t\tseqs[a[0]]=int(a[1])\n\nline_out=\"\"\nfor seq in seqs:\n\tline_out+=seq+\"\\t\"+str(seqs[seq])+\"\\n\"\n\nopen(dataDir+outputFileName+\"_merged.txt\",\"w\").write(line_out)\n","sub_path":"DNA_library/1.5.combineCollapsedFiles.py","file_name":"1.5.combineCollapsedFiles.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"211287286","text":"import os\nimport psutil\nimport datetime\n\ndef get_common_system_state():\n mem_usage = psutil.virtual_memory()\n disk_usage = psutil.disk_usage('/')\n cpu_usage = psutil.cpu_percent(interval = 1.0)\n system_info = \"\"\n\n system_info += \"Memory usage: \" + str(mem_usage[2]) + \"%\" + \"\\n\"\n system_info += \"CPU usage: \" + str(cpu_usage) + \"%\" + \"\\n\" \n system_info += \"Disk usage: \" + str(disk_usage[3]) + \"%\" + \"\\n\"\n system_info += \"Boot time: \" + datetime.datetime.fromtimestamp(psutil.boot_time()).strftime(\"%Y-%m-%d %H:%M:%S\")\n return system_info\n","sub_path":"src/stats/system.py","file_name":"system.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"570939034","text":"import argparse\nimport multiprocessing\nimport os\n\nimport falcon\nfrom falcon_swagger_ui import register_swaggerui_app\nfrom waitress import serve\n\nimport path_to_output\nfrom prot_graph_exception import ProtGraphException\nfrom query_weight import mono_weight_query as wq\n\napp = application = falcon.API()\n\n\ndef parse_args():\n # Arguments for Parser\n parser = argparse.ArgumentParser(\n description=\"Graph-Generator-REST-API for generated Graphs of Proteins and Peptides\"\n )\n # Needed Arguments for parsing (and additional information for it)\n parser.add_argument(\n \"base_folder\", type=str,\n help=\"The base folder containing the generated exported graph files, which can be read by igraph.\"\n )\n parser.add_argument(\n \"--mass_dict_factor\", \"-mdf\", type=float, default=1000000000,\n help=\"Set the factor for the masses which was used to generate the graphs. \"\n \"The default is set to 1 000 000 000, so that each mass can be converted into integers.\"\n )\n\n args = parser.parse_args()\n\n return dict(\n base_folder=args.base_folder,\n mass_dict_factor=args.mass_dict_factor\n )\n\n\ndef generic_error_handler(ex, req, resp, params):\n \"\"\" Set the generic ErrorHandler for the exception: ProtGraphException\"\"\"\n if isinstance(ex, ProtGraphException):\n resp.status = ex.status\n resp.body = ex.body\n for x, y in ex.headers.items():\n resp.set_header(x, y)\n else:\n raise ex\n\n\nif __name__ == '__main__':\n GLOABL_ARGS = parse_args()\n\n app.add_error_handler(ProtGraphException, generic_error_handler)\n\n # Add resources folder to:\n app.add_static_route('/resources', os.path.join(\n os.path.dirname(os.path.abspath(__file__)),\n \"resources\"\n )\n )\n\n register_swaggerui_app(\n app, \"/swagger\", \"/resources/openapi.yaml\",\n page_title=\"Swagger for ProtGraphREST\"\n )\n\n app.add_route(\"/{accession}/path_to_peptide\", path_to_output.PathToPeptide(GLOABL_ARGS[\"base_folder\"]))\n app.add_route(\"/{accession}/path_to_fasta\", path_to_output.PathToFasta(GLOABL_ARGS[\"base_folder\"]))\n\n # Routes for weight queries\n app.add_route(\n \"/{accession}/top_sort/query_mono_weight\",\n wq.QueryWeight(GLOABL_ARGS[\"base_folder\"], GLOABL_ARGS[\"mass_dict_factor\"], wq.ALGORITHMS[\"top_sort\"])\n )\n app.add_route(\n \"/{accession}/bfs_fifo/query_mono_weight\",\n wq.QueryWeight(GLOABL_ARGS[\"base_folder\"], GLOABL_ARGS[\"mass_dict_factor\"], wq.ALGORITHMS[\"bfs_fifo\"])\n )\n app.add_route(\n \"/{accession}/bfs_filo/query_mono_weight\",\n wq.QueryWeight(GLOABL_ARGS[\"base_folder\"], GLOABL_ARGS[\"mass_dict_factor\"], wq.ALGORITHMS[\"bfs_filo\"])\n )\n app.add_route(\n \"/{accession}/dfs/query_mono_weight\",\n wq.QueryWeight(GLOABL_ARGS[\"base_folder\"], GLOABL_ARGS[\"mass_dict_factor\"], wq.ALGORITHMS[\"dfs\"])\n )\n app.add_route(\n \"/{accession}/top_sort_attrs/query_mono_weight\",\n wq.QueryWeight(GLOABL_ARGS[\"base_folder\"], GLOABL_ARGS[\"mass_dict_factor\"], wq.ALGORITHMS[\"top_sort_attrs\"])\n )\n app.add_route(\n \"/{accession}/top_sort_attrs_limit_var/query_mono_weight\",\n wq.QueryWeight(GLOABL_ARGS[\"base_folder\"], GLOABL_ARGS[\"mass_dict_factor\"], wq.ALGORITHMS[\"top_sort_attrs_limit_var\"])\n )\n\n # Example call for a query via weight\n # http://localhost:8000/A0A4S5AXF8/top_sort/query_mono_weight?unit=ppm&mono_weight=3394.719&mass_tolerance=5\n # http://localhost:8000/P04637/top_sort/query_mono_weight?unit=ppm&mono_weight=1000.719&mass_tolerance=5&timeout=10\n\n # Example call for getting a peptide:\n # http://localhost:8000/A0A4S5AXF8/path_to_fasta?path=0,24,25,9\n serve(app, listen=\"*:8000\", threads=multiprocessing.cpu_count())\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"380121219","text":"import sys\nimport pandas as pd\nfrom sklearn import tree\nfrom sklearn import ensemble\nfrom pandas import DataFrame\nimport csv\n\n# Tolerance is the # of yards we can be off (+ & -)\n#tolerance = 0\n\nlabels = pd.read_csv('./data/labels.csv')\ndata = pd.read_csv('./data/scaled.csv')\n\ntrain_data = data[:24805]\ntrain_labels = labels[:24805]['Yards']\n\ntest_data = data[24805:]\ntest_labels = labels[24805:]['Yards']\n\nresults = {}\nfor tolerance in range(0,4):#0,4\n for est in range(18,22):#90-110\n print('\\nClassifying w/', est * 5, 'estimators')\n classifier = ensemble.RandomForestClassifier(n_estimators = est * 5)\n classifier.fit(train_data, train_labels)\n\n correct = 0\n incorrect = 0\n\n i = 0\n\n for index, rowdata in test_data.iterrows():\n val = test_labels[index]\n prediction = classifier.predict([rowdata])[0]\n if abs(prediction - val) <= tolerance:\n correct = correct + 1\n else:\n incorrect = incorrect + 1\n i += 1\n results[est] = {\n 'tolerance': tolerance,\n 'correct': correct,\n 'total': i,\n 'percentage': correct / i,\n 'estimators': est * 5,\n }\n print('Results\\nTolerance:', tolerance, 'yards\\nCorrect:', correct, 'plays\\nTotal:', i, 'plays\\nPercentage:', correct / i)\n\nwith open('./data/random_forest_results.csv', 'w') as csv_file:\n writer = csv.writer(csv_file)\n for key, value in results.items():\n writer.writerow([key, value])\n","sub_path":"random_forest.py","file_name":"random_forest.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"13144653","text":"# conding: utf-8\n\ngoogle_fonts = [\n u'ABeeZee',\n u'Abel',\n u'Abril Fatface',\n u'Aclonica',\n u'Acme',\n u'Actor',\n u'Adamina',\n u'Advent Pro',\n u'Aguafina Script',\n u'Akronim',\n u'Aladin',\n u'Aldrich',\n u'Alef',\n u'Alegreya',\n u'Alegreya SC',\n u'Alegreya Sans',\n u'Alegreya Sans SC',\n u'Alex Brush',\n u'Alfa Slab One',\n u'Alice',\n u'Alike',\n u'Alike Angular',\n u'Allan',\n u'Allerta',\n u'Allerta Stencil',\n u'Allura',\n u'Almendra',\n u'Almendra Display',\n u'Almendra SC',\n u'Amarante',\n u'Amaranth',\n u'Amatic SC',\n u'Amethysta',\n u'Anaheim',\n u'Andada',\n u'Andika',\n u'Angkor',\n u'Annie Use Your Telescope',\n u'Anonymous Pro',\n u'Antic',\n u'Antic Didone',\n u'Antic Slab',\n u'Anton',\n u'Arapey',\n u'Arbutus',\n u'Arbutus Slab',\n u'Architects Daughter',\n u'Archivo Black',\n u'Archivo Narrow',\n u'Arimo',\n u'Arizonia',\n u'Armata',\n u'Artifika',\n u'Arvo',\n u'Asap',\n u'Asset',\n u'Astloch',\n u'Asul',\n u'Atomic Age',\n u'Aubrey',\n u'Audiowide',\n u'Autour One',\n u'Average',\n u'Average Sans',\n u'Averia Gruesa Libre',\n u'Averia Libre',\n u'Averia Sans Libre',\n u'Averia Serif Libre',\n u'Bad Script',\n u'Balthazar',\n u'Bangers',\n u'Basic',\n u'Battambang',\n u'Baumans',\n u'Bayon',\n u'Belgrano',\n u'Belleza',\n u'BenchNine',\n u'Bentham',\n u'Berkshire Swash',\n u'Bevan',\n u'Bigelow Rules',\n u'Bigshot One',\n u'Bilbo',\n u'Bilbo Swash Caps',\n u'Bitter',\n u'Black Ops One',\n u'Bokor',\n u'Bonbon',\n u'Boogaloo',\n u'Bowlby One',\n u'Bowlby One SC',\n u'Brawler',\n u'Bree Serif',\n u'Bubblegum Sans',\n u'Bubbler One',\n u'Buda',\n u'Buenard',\n u'Butcherman',\n u'Butterfly Kids',\n u'Cabin',\n u'Cabin Condensed',\n u'Cabin Sketch',\n u'Caesar Dressing',\n u'Cagliostro',\n u'Calligraffitti',\n u'Cambay',\n u'Cambo',\n u'Candal',\n u'Cantarell',\n u'Cantata One',\n u'Cantora One',\n u'Capriola',\n u'Cardo',\n u'Carme',\n u'Carrois Gothic',\n u'Carrois Gothic SC',\n u'Carter One',\n u'Caudex',\n u'Cedarville Cursive',\n u'Ceviche One',\n u'Changa One',\n u'Chango',\n u'Chau Philomene One',\n u'Chela One',\n u'Chelsea Market',\n u'Chenla',\n u'Cherry Cream Soda',\n u'Cherry Swash',\n u'Chewy',\n u'Chicle',\n u'Chivo',\n u'Cinzel',\n u'Cinzel Decorative',\n u'Clicker Script',\n u'Coda',\n u'Coda Caption',\n u'Codystar',\n u'Combo',\n u'Comfortaa',\n u'Coming Soon',\n u'Concert One',\n u'Condiment',\n u'Content',\n u'Contrail One',\n u'Convergence',\n u'Cookie',\n u'Copse',\n u'Corben',\n u'Courgette',\n u'Cousine',\n u'Coustard',\n u'Covered By Your Grace',\n u'Crafty Girls',\n u'Creepster',\n u'Crete Round',\n u'Crimson Text',\n u'Croissant One',\n u'Crushed',\n u'Cuprum',\n u'Cutive',\n u'Cutive Mono',\n u'Damion',\n u'Dancing Script',\n u'Dangrek',\n u'Dawning of a New Day',\n u'Days One',\n u'Dekko',\n u'Delius',\n u'Delius Swash Caps',\n u'Delius Unicase',\n u'Della Respira',\n u'Denk One',\n u'Devonshire',\n u'Dhurjati',\n u'Didact Gothic',\n u'Diplomata',\n u'Diplomata SC',\n u'Domine',\n u'Donegal One',\n u'Doppio One',\n u'Dorsa',\n u'Dosis',\n u'Dr Sugiyama',\n u'Droid Sans',\n u'Droid Sans Mono',\n u'Droid Serif',\n u'Duru Sans',\n u'Dynalight',\n u'EB Garamond',\n u'Eagle Lake',\n u'Eater',\n u'Economica',\n u'Ek Mukta',\n u'Electrolize',\n u'Elsie',\n u'Elsie Swash Caps',\n u'Emblema One',\n u'Emilys Candy',\n u'Engagement',\n u'Englebert',\n u'Enriqueta',\n u'Erica One',\n u'Esteban',\n u'Euphoria Script',\n u'Ewert',\n u'Exo',\n u'Exo 2',\n u'Expletus Sans',\n u'Fanwood Text',\n u'Fascinate',\n u'Fascinate Inline',\n u'Faster One',\n u'Fasthand',\n u'Fauna One',\n u'Federant',\n u'Federo',\n u'Felipa',\n u'Fenix',\n u'Finger Paint',\n u'Fira Mono',\n u'Fira Sans',\n u'Fjalla One',\n u'Fjord One',\n u'Flamenco',\n u'Flavors',\n u'Fondamento',\n u'Fontdiner Swanky',\n u'Forum',\n u'Francois One',\n u'Freckle Face',\n u'Fredericka the Great',\n u'Fredoka One',\n u'Freehand',\n u'Fresca',\n u'Frijole',\n u'Fruktur',\n u'Fugaz One',\n u'GFS Didot',\n u'GFS Neohellenic',\n u'Gabriela',\n u'Gafata',\n u'Galdeano',\n u'Galindo',\n u'Gentium Basic',\n u'Gentium Book Basic',\n u'Geo',\n u'Geostar',\n u'Geostar Fill',\n u'Germania One',\n u'Gidugu',\n u'Gilda Display',\n u'Give You Glory',\n u'Glass Antiqua',\n u'Glegoo',\n u'Gloria Hallelujah',\n u'Goblin One',\n u'Gochi Hand',\n u'Gorditas',\n u'Goudy Bookletter 1911',\n u'Graduate',\n u'Grand Hotel',\n u'Gravitas One',\n u'Great Vibes',\n u'Griffy',\n u'Gruppo',\n u'Gudea',\n u'Gurajada',\n u'Habibi',\n u'Halant',\n u'Hammersmith One',\n u'Hanalei',\n u'Hanalei Fill',\n u'Handlee',\n u'Hanuman',\n u'Happy Monkey',\n u'Headland One',\n u'Henny Penny',\n u'Herr Von Muellerhoff',\n u'Hind',\n u'Holtwood One SC',\n u'Homemade Apple',\n u'Homenaje',\n u'IM Fell DW Pica',\n u'IM Fell DW Pica SC',\n u'IM Fell Double Pica',\n u'IM Fell Double Pica SC',\n u'IM Fell English',\n u'IM Fell English SC',\n u'IM Fell French Canon',\n u'IM Fell French Canon SC',\n u'IM Fell Great Primer',\n u'IM Fell Great Primer SC',\n u'Iceberg',\n u'Iceland',\n u'Imprima',\n u'Inconsolata',\n u'Inder',\n u'Indie Flower',\n u'Inika',\n u'Irish Grover',\n u'Istok Web',\n u'Italiana',\n u'Italianno',\n u'Jacques Francois',\n u'Jacques Francois Shadow',\n u'Jim Nightshade',\n u'Jockey One',\n u'Jolly Lodger',\n u'Josefin Sans',\n u'Josefin Slab',\n u'Joti One',\n u'Judson',\n u'Julee',\n u'Julius Sans One',\n u'Junge',\n u'Jura',\n u'Just Another Hand',\n u'Just Me Again Down Here',\n u'Kalam',\n u'Kameron',\n u'Kantumruy',\n u'Karla',\n u'Karma',\n u'Kaushan Script',\n u'Kavoon',\n u'Kdam Thmor',\n u'Keania One',\n u'Kelly Slab',\n u'Kenia',\n u'Khand',\n u'Khmer',\n u'Khula',\n u'Kite One',\n u'Knewave',\n u'Kotta One',\n u'Koulen',\n u'Kranky',\n u'Kreon',\n u'Kristi',\n u'Krona One',\n u'La Belle Aurore',\n u'Laila',\n u'Lakki Reddy',\n u'Lancelot',\n u'Lato',\n u'League Script',\n u'Leckerli One',\n u'Ledger',\n u'Lekton',\n u'Lemon',\n u'Libre Baskerville',\n u'Life Savers',\n u'Lilita One',\n u'Lily Script One',\n u'Limelight',\n u'Linden Hill',\n u'Lobster',\n u'Lobster Two',\n u'Londrina Outline',\n u'Londrina Shadow',\n u'Londrina Sketch',\n u'Londrina Solid',\n u'Lora',\n u'Love Ya Like A Sister',\n u'Loved by the King',\n u'Lovers Quarrel',\n u'Luckiest Guy',\n u'Lusitana',\n u'Lustria',\n u'Macondo',\n u'Macondo Swash Caps',\n u'Magra',\n u'Maiden Orange',\n u'Mako',\n u'Mallanna',\n u'Mandali',\n u'Marcellus',\n u'Marcellus SC',\n u'Marck Script',\n u'Margarine',\n u'Marko One',\n u'Marmelad',\n u'Marvel',\n u'Mate',\n u'Mate SC',\n u'Maven Pro',\n u'McLaren',\n u'Meddon',\n u'MedievalSharp',\n u'Medula One',\n u'Megrim',\n u'Meie Script',\n u'Merienda',\n u'Merienda One',\n u'Merriweather',\n u'Merriweather Sans',\n u'Metal',\n u'Metal Mania',\n u'Metamorphous',\n u'Metrophobic',\n u'Michroma',\n u'Milonga',\n u'Miltonian',\n u'Miltonian Tattoo',\n u'Miniver',\n u'Miss Fajardose',\n u'Modern Antiqua',\n u'Molengo',\n u'Molle',\n u'Monda',\n u'Monofett',\n u'Monoton',\n u'Monsieur La Doulaise',\n u'Montaga',\n u'Montez',\n u'Montserrat',\n u'Montserrat Alternates',\n u'Montserrat Subrayada',\n u'Moul',\n u'Moulpali',\n u'Mountains of Christmas',\n u'Mouse Memoirs',\n u'Mr Bedfort',\n u'Mr Dafoe',\n u'Mr De Haviland',\n u'Mrs Saint Delafield',\n u'Mrs Sheppards',\n u'Muli',\n u'Mystery Quest',\n u'NTR',\n u'Neucha',\n u'Neuton',\n u'New Rocker',\n u'News Cycle',\n u'Niconne',\n u'Nixie One',\n u'Nobile',\n u'Nokora',\n u'Norican',\n u'Nosifer',\n u'Nothing You Could Do',\n u'Noticia Text',\n u'Noto Sans',\n u'Noto Serif',\n u'Nova Cut',\n u'Nova Flat',\n u'Nova Mono',\n u'Nova Oval',\n u'Nova Round',\n u'Nova Script',\n u'Nova Slim',\n u'Nova Square',\n u'Numans',\n u'Nunito',\n u'Odor Mean Chey',\n u'Offside',\n u'Old Standard TT',\n u'Oldenburg',\n u'Oleo Script',\n u'Oleo Script Swash Caps',\n u'Open Sans',\n u'Open Sans Condensed',\n u'Oranienbaum',\n u'Orbitron',\n u'Oregano',\n u'Orienta',\n u'Original Surfer',\n u'Oswald',\n u'Over the Rainbow',\n u'Overlock',\n u'Overlock SC',\n u'Ovo',\n u'Oxygen',\n u'Oxygen Mono',\n u'PT Mono',\n u'PT Sans',\n u'PT Sans Caption',\n u'PT Sans Narrow',\n u'PT Serif',\n u'PT Serif Caption',\n u'Pacifico',\n u'Paprika',\n u'Parisienne',\n u'Passero One',\n u'Passion One',\n u'Pathway Gothic One',\n u'Patrick Hand',\n u'Patrick Hand SC',\n u'Patua One',\n u'Paytone One',\n u'Peddana',\n u'Peralta',\n u'Permanent Marker',\n u'Petit Formal Script',\n u'Petrona',\n u'Philosopher',\n u'Piedra',\n u'Pinyon Script',\n u'Pirata One',\n u'Plaster',\n u'Play',\n u'Playball',\n u'Playfair Display',\n u'Playfair Display SC',\n u'Podkova',\n u'Poiret One',\n u'Poller One',\n u'Poly',\n u'Pompiere',\n u'Pontano Sans',\n u'Port Lligat Sans',\n u'Port Lligat Slab',\n u'Prata',\n u'Preahvihear',\n u'Press Start 2P',\n u'Princess Sofia',\n u'Prociono',\n u'Prosto One',\n u'Puritan',\n u'Purple Purse',\n u'Quando',\n u'Quantico',\n u'Quattrocento',\n u'Quattrocento Sans',\n u'Questrial',\n u'Quicksand',\n u'Quintessential',\n u'Qwigley',\n u'Racing Sans One',\n u'Radley',\n u'Rajdhani',\n u'Raleway',\n u'Raleway Dots',\n u'Ramabhadra',\n u'Ramaraja',\n u'Rambla',\n u'Rammetto One',\n u'Ranchers',\n u'Rancho',\n u'Ranga',\n u'Rationale',\n u'Ravi Prakash',\n u'Redressed',\n u'Reenie Beanie',\n u'Revalia',\n u'Ribeye',\n u'Ribeye Marrow',\n u'Righteous',\n u'Risque',\n u'Roboto',\n u'Roboto Condensed',\n u'Roboto Slab',\n u'Rochester',\n u'Rock Salt',\n u'Rokkitt',\n u'Romanesco',\n u'Ropa Sans',\n u'Rosario',\n u'Rosarivo',\n u'Rouge Script',\n u'Rozha One',\n u'Rubik Mono One',\n u'Rubik One',\n u'Ruda',\n u'Rufina',\n u'Ruge Boogie',\n u'Ruluko',\n u'Rum Raisin',\n u'Ruslan Display',\n u'Russo One',\n u'Ruthie',\n u'Rye',\n u'Sacramento',\n u'Sail',\n u'Salsa',\n u'Sanchez',\n u'Sancreek',\n u'Sansita One',\n u'Sarina',\n u'Sarpanch',\n u'Satisfy',\n u'Scada',\n u'Schoolbell',\n u'Seaweed Script',\n u'Sevillana',\n u'Seymour One',\n u'Shadows Into Light',\n u'Shadows Into Light Two',\n u'Shanti',\n u'Share',\n u'Share Tech',\n u'Share Tech Mono',\n u'Shojumaru',\n u'Short Stack',\n u'Siemreap',\n u'Sigmar One',\n u'Signika',\n u'Signika Negative',\n u'Simonetta',\n u'Sintony',\n u'Sirin Stencil',\n u'Six Caps',\n u'Skranji',\n u'Slabo 13px',\n u'Slabo 27px',\n u'Slackey',\n u'Smokum',\n u'Smythe',\n u'Sniglet',\n u'Snippet',\n u'Snowburst One',\n u'Sofadi One',\n u'Sofia',\n u'Sonsie One',\n u'Sorts Mill Goudy',\n u'Source Code Pro',\n u'Source Sans Pro',\n u'Source Serif Pro',\n u'Special Elite',\n u'Spicy Rice',\n u'Spinnaker',\n u'Spirax',\n u'Squada One',\n u'Sree Krushnadevaraya',\n u'Stalemate',\n u'Stalinist One',\n u'Stardos Stencil',\n u'Stint Ultra Condensed',\n u'Stint Ultra Expanded',\n u'Stoke',\n u'Strait',\n u'Sue Ellen Francisco',\n u'Sunshiney',\n u'Supermercado One',\n u'Suranna',\n u'Suravaram',\n u'Suwannaphum',\n u'Swanky and Moo Moo',\n u'Syncopate',\n u'Tangerine',\n u'Taprom',\n u'Tauri',\n u'Teko',\n u'Telex',\n u'Tenali Ramakrishna',\n u'Tenor Sans',\n u'Text Me One',\n u'The Girl Next Door',\n u'Tienne',\n u'Timmana',\n u'Tinos',\n u'Titan One',\n u'Titillium Web',\n u'Trade Winds',\n u'Trocchi',\n u'Trochut',\n u'Trykker',\n u'Tulpen One',\n u'Ubuntu',\n u'Ubuntu Condensed',\n u'Ubuntu Mono',\n u'Ultra',\n u'Uncial Antiqua',\n u'Underdog',\n u'Unica One',\n u'UnifrakturCook',\n u'UnifrakturMaguntia',\n u'Unkempt',\n u'Unlock',\n u'Unna',\n u'VT323',\n u'Vampiro One',\n u'Varela',\n u'Varela Round',\n u'Vast Shadow',\n u'Vesper Libre',\n u'Vibur',\n u'Vidaloka',\n u'Viga',\n u'Voces',\n u'Volkhov',\n u'Vollkorn',\n u'Voltaire',\n u'Waiting for the Sunrise',\n u'Wallpoet',\n u'Walter Turncoat',\n u'Warnes',\n u'Wellfleet',\n u'Wendy One',\n u'Wire One',\n u'Yanone Kaffeesatz',\n u'Yellowtail',\n u'Yeseva One',\n u'Yesteryear',\n u'Zeyada',\n]\n\ngoogle_font_choices = [(font, font) for font in google_fonts]\n\n","sub_path":"src/admin/accounts/src/google_fonts.py","file_name":"google_fonts.py","file_ext":"py","file_size_in_byte":13247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"471661852","text":"'''\n3 People following each other with steplegth of half the distance to the followed person\n'''\n\nfrom turtle import Screen, Turtle\nimport time\nfrom math import sqrt\n\nscreen = Screen()\nscreen.setup(800, 800)\nt1 = Turtle()\nt2 = Turtle()\nt3 = Turtle()\nt1.hideturtle()\nt2.hideturtle()\nt3.hideturtle()\n\ndef setup(sidelength):\n h = sqrt(sidelength**2 - (sidelength/2)**2)\n a = ((sidelength/2)**2 + h**2)/(2*h)\n t1.penup()\n t2.penup()\n t3.penup()\n t1.right(30)\n t1.forward(a)\n t1.setheading(270)\n t1.forward(100)\n t2.right(150)\n t2.forward(a)\n t2.setheading(270)\n t2.forward(100)\n t3.right(270)\n t3.forward(a)\n t3.setheading(270)\n t3.forward(100)\n t1.pendown()\n t2.pendown()\n t3.pendown()\n\n\ndef follow():\n t1pos = t1.position()\n t2pos = t2.position()\n t3pos = t3.position()\n print(t1pos, t2pos, t3pos)\n t1.setheading(t1.towards(t2pos))\n t2.setheading(t2.towards(t3pos))\n t3.setheading(t3.towards(t1pos))\n t1.fd(t1.distance(t2pos)/2)\n t2.fd(t2.distance(t3pos)/2)\n t3.fd(t3.distance(t1pos)/2)\n screen.update()\n\n\ndef run():\n setup(750)\n for i in range(100000):\n screen.update()\n follow()\n time.sleep(1)\n\nscreen.tracer(False)\nrun()\nscreen.tracer(True)\nscreen.mainloop()\n","sub_path":"following_half_distance.py","file_name":"following_half_distance.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"456402782","text":"from django.conf import settings\nfrom oauth_hook import OAuthHook\nimport requests\n\nENDPOINT = \"http://api.yelp.com/v2/search\"\n\nBASE_CATEGORIES = \"active,arts,food,nightlife,restaurants\"\n\nMETERS_PER_MILE = 1609\n\noauth_hook = OAuthHook(\n settings.YELP['TOKEN'],\n settings.YELP['TOKEN_SECRET'],\n settings.YELP['CONSUMER_KEY'],\n settings.YELP['CONSUMER_SECRET'])\n\nhttp = requests.session(hooks={'pre_request': oauth_hook})\n\ndefault_filters = {\n 'limit': 20,\n 'sort': 2, # highest rated\n 'radius_filter': METERS_PER_MILE * 3, # in meters, roughly 3 miles\n}\n\n\ndef nearby(lat, lon, categories=None, radius=None, limit=None):\n\n filters = default_filters.copy()\n filters['ll'] = \"%s,%s\" % (lat, lon)\n\n if categories:\n filters['category_filter'] = categories\n\n if radius:\n filters['radius_filter'] = radius\n\n if limit:\n filters['limit'] = limit\n\n resp = http.get(ENDPOINT, params=filters)\n\n data = resp.json\n return data['businesses'] if data and 'businesses' in data else []\n\n\ndef test():\n\n lat = \"39.138765\"\n lon = \"-77.197970\"\n\n # recommended\n nearby(lat, lon, categories=BASE_CATEGORIES)\n\n # local flavor\n ten_miles = METERS_PER_MILE * 10\n nearby(lat, lon, categories='localflavor', radius=ten_miles)\n","sub_path":"sitegeist/data/yelp.py","file_name":"yelp.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"151053832","text":"from model import Critic, Actor\nimport torch as th\nimport torch.nn.functional as F\nfrom copy import deepcopy\nfrom memory import ReplayMemory, Experience\nfrom torch.optim import Adam\nimport torch.nn as nn\nimport numpy as np\nfrom params import scale_reward\nfrom torch.autograd import Variable\nfrom torch.distributions import Categorical\nimport os\n\n\n\ndef soft_update(target, source, t):\n for target_param, source_param in zip(target.parameters(),\n source.parameters()):\n target_param.data.copy_(\n (1 - t) * target_param.data + t * source_param.data)\n\n\ndef hard_update(target, source):\n for target_param, source_param in zip(target.parameters(),\n source.parameters()):\n target_param.data.copy_(source_param.data)\n\n\nclass MADDPG:\n def __init__(self, n_agents, dim_obs, dim_act, batch_size,\n capacity, episodes_before_train):\n self.actors = [Actor(dim_obs, dim_act) for i in range(n_agents)]\n self.critics = [Critic(n_agents, dim_obs,\n dim_act) for i in range(n_agents)]\n # target actors和target critics使用deepcopy 被复制对象完全再复制一遍作为独立的新个体单独存在。所以改变原有被复制对象不会对已经复制出来的新对象产生影响。\n self.actors_target = deepcopy(self.actors)\n self.critics_target = deepcopy(self.critics)\n\n self.n_agents = n_agents\n self.n_states = dim_obs\n self.n_actions = dim_act\n self.memory = ReplayMemory(capacity)\n self.batch_size = batch_size\n self.use_cuda = th.cuda.is_available()\n self.episodes_before_train = episodes_before_train\n\n self.GAMMA = 0.95\n self.tau = 0.01\n\n # self.var = [1.0 for i in range(n_agents)]\n self.critic_optimizer = [Adam(x.parameters(),\n lr=0.001) for x in self.critics]\n self.actor_optimizer = [Adam(x.parameters(),\n lr=0.0001) for x in self.actors]\n\n # 使用cuda加速\n if self.use_cuda:\n for x in self.actors:\n x.cuda()\n for x in self.critics:\n x.cuda()\n for x in self.actors_target:\n x.cuda()\n for x in self.critics_target:\n x.cuda()\n\n self.steps_done = 0\n # episode_done用来计算已经跑过了多少回合,来确定是否结束预训练\n self.episode_done = 0\n\n def update_policy(self):\n # do not train until exploration is enough\n if self.episode_done <= self.episodes_before_train:\n return None, None\n\n ByteTensor = th.cuda.ByteTensor if self.use_cuda else th.ByteTensor\n FloatTensor = th.cuda.FloatTensor if self.use_cuda else th.FloatTensor\n\n # actor Loss\n c_loss = []\n # critic Loss\n a_loss = []\n # 循环,对于每一个agent提取transitions\n for agent in range(self.n_agents):\n # 提取过渡态\n transitions = self.memory.sample(self.batch_size)\n # 利用*号操作符,可以将元组解压为列表. *transitions将transtions解压为列表\n # zip(*transitions) 得到的结果是[(state1, state2), (action1, action2), (next_state1, next_state2), (reward1, reward2)] \n # batch = Experience(states=(1, 5), actions=(2, 6), next_states=(3, 7), rewards=(4, 8))\n batch = Experience(*zip(*transitions))\n # 是否终止状态\n # list(map(...))返回的数值: [True, True]\n # ByteTensor后返回的数值tensor([1, 1], dtype=torch.uint8)\n non_final_mask = ByteTensor(list(map(lambda s: s is not None,\n batch.next_states)))\n # state_batch: batch_size x n_agents x dim_obs\n state_batch = Variable(th.stack(batch.states).type(FloatTensor))\n action_batch = Variable(th.stack(batch.actions).type(FloatTensor))\n reward_batch = Variable(th.stack(batch.rewards).type(FloatTensor))\n # : (batch_size_non_final) x n_agents x dim_obs\n non_final_next_states = Variable(th.stack(\n [s for s in batch.next_states\n if s is not None]).type(FloatTensor))\n\n # for current agent\n # 使用view重新塑形\n # whole_state的格式为([batch_size, n_agents ✖ dim_obs])\n whole_state = state_batch.view(self.batch_size, -1)\n whole_action = action_batch.view(self.batch_size, -1)\n\n # 把critic优化器梯度置零,也就是把loss关于weight的导数变成0\n self.critic_optimizer[agent].zero_grad()\n # 当前的Q值, 使用当前critic来进行评估\n current_Q = self.critics[agent](whole_state, whole_action)\n \n non_final_next_actions = [\n self.actors_target[i](non_final_next_states[:,\n i,\n :]) for i in range(\n self.n_agents)]\n non_final_next_actions = th.stack(non_final_next_actions)\n # transpose: 交换维度0和1,即转置\n # contiguous操作保证张量是连续的,方便后续的view操作\n non_final_next_actions = (\n non_final_next_actions.transpose(0,\n 1).contiguous())\n\n # TODO: 对此处代码不深究,涉及到数学内容,直接套用\n # target_Q初始化\n target_Q = th.zeros(\n self.batch_size).type(FloatTensor)\n \n\n target_Q[non_final_mask] = self.critics_target[agent](\n non_final_next_states.view(-1, self.n_agents * self.n_states),\n non_final_next_actions.view(-1,\n self.n_agents * self.n_actions)\n ).squeeze()\n # scale_reward: to scale reward in Q functions\n\n target_Q = (target_Q.unsqueeze(1) * self.GAMMA) + (\n reward_batch[:, agent].unsqueeze(1) * scale_reward)\n\n loss_Q = nn.MSELoss()(current_Q, target_Q.detach())\n loss_Q.backward()\n self.critic_optimizer[agent].step()\n\n self.actor_optimizer[agent].zero_grad()\n state_i = state_batch[:, agent, :]\n action_i = self.actors[agent](state_i)\n ac = action_batch.clone()\n ac[:, agent, :] = action_i\n whole_action = ac.view(self.batch_size, -1)\n actor_loss = -self.critics[agent](whole_state, whole_action)\n actor_loss = actor_loss.mean()\n actor_loss.backward()\n self.actor_optimizer[agent].step()\n c_loss.append(loss_Q)\n a_loss.append(actor_loss)\n\n if self.steps_done % 100 == 0 and self.steps_done > 0:\n for i in range(self.n_agents):\n soft_update(self.critics_target[i], self.critics[i], self.tau)\n soft_update(self.actors_target[i], self.actors[i], self.tau)\n\n return c_loss, a_loss\n\n def select_action(self, state_batch, eps=None, min_eps=None):\n for i in range(self.n_agents):\n sb = state_batch[i, :].detach()\n policy = self.actors[i](sb.unsqueeze(0)).squeeze()\n\n\n # state_batch: n_agents x state_dim\n argmax_acs = th.LongTensor(\n self.n_agents,\n 1)\n rand_acs = th.LongTensor(\n self.n_agents,\n 1)\n LongTensor = th.cuda.LongTensor if self.use_cuda else th.LongTensor\n FloatTensor = th.cuda.FloatTensor if self.use_cuda else th.FloatTensor\n for i in range(self.n_agents):\n sb = state_batch[i, :].detach()\n actor = self.actors[i]\n policy = Variable(actor(sb).squeeze(), requires_grad=False)\n prob = F.softmax(policy)\n argmax_acs[i] = th.argmax(prob).clone().detach()\n rand_acs[i] = Categorical(prob).sample().type(LongTensor)\n argmax_acs = argmax_acs.squeeze()\n rand_acs = rand_acs.squeeze()\n if eps == 0.0:\n return argmax_acs\n # TODO:此处的steps_done待定啥时候用\n self.steps_done += 1\n return th.stack([argmax_acs[i] if r > eps else rand_acs[i] for i, r in\n enumerate(th.rand(self.n_agents))])\n\n\n def save(self, model_dir, train_step, save_cycle, time_now):\n \"\"\"\n Save trained parameters of all agents into one file\n \"\"\"\n num = str(train_step // save_cycle)\n model_dir = './model/' + time_now\n if not os.path.exists(model_dir):\n os.makedirs(model_dir)\n for i in range(9):\n w = str(num)\n q = str(i)\n th.save(self.actors[i].state_dict(), model_dir + '/' + w + '_'+ q + 'actor_params.pkl')\n th.save(self.actors_target[i].state_dict(), model_dir + '/' + w + '_'+ q + 'actor_target_params.pkl')\n th.save(self.critics[i].state_dict(), model_dir + '/' + w + '_'+ q + 'critic_params.pkl')\n th.save(self.critics_target[i].state_dict(), model_dir + '/'+ w + '_' + q + 'critic_target_params.pkl')","sub_path":"MADDPG.py","file_name":"MADDPG.py","file_ext":"py","file_size_in_byte":9432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"156859384","text":"import sqlite3\n\n\nclass PhoneBookDB:\n\n conn = sqlite3.connect('dbphone.sqlite')\n\n def __init__(self):\n self.phone_book = {}\n\n def __iter__(self):\n for name, phone_number in self.phone_book.items():\n yield name, phone_number\n\n def load_dictionary(self):\n pass\n\n\n def create_table(self):\n cursor = self.conn.cursor()\n cursor.execute('CREATE TABLE dbphone(name varchar(30), phone_number varchar(20))')\n self.conn.commit()\n\n def create_phone_book(self):\n while True:\n if \"Start\":\n name = input(\"Enter name user: \")\n phone_number = input(\"Enter phone number: \")\n if name and phone_number:\n val_str = \"'{}', '{}'\".format(name, phone_number)\n sql_str = \"INSERT INTO dbphone (name, Phone_number) VALUES ({});\".format(val_str)\n self.conn.execute(sql_str)\n self.conn.commit()\n print(\"New user? Yes/No\")\n new_user = input('')\n if new_user == \"Yes\":\n continue\n else:\n break\n # return self.conn.total_changes\n\n def read_phone_book(self):\n sql_str = \"SELECT * from dbphone\"\n cursor = self.conn.execute(sql_str)\n rows = cursor.fetchall()\n\n return print(rows)\n\n def update_phone_book(self):\n name = input(\"Enter name user: \")\n phone_number = input(\"Enter phone number: \")\n val_str = \"'{}', '{}'\".format(name, phone_number)\n print(val_str)\n sql_str = \"UPDATE dbphone SET (name, phone_number) WHERE name={}\".format(val_str)\n self.conn.execute(sql_str)\n self.conn.commit()\n # return self.conn.total_changes\n\n def delete_user_phone(self,):\n name = input(\"Enter change name\")\n sql_str = \"DELETE FROM dbphone WHERE name='{}'\".format(name)\n self.conn.execute(sql_str)\n self.conn.commit()\n # return self.conn.total_changes\n\nCreate = PhoneBookDB()\n\nwhile True:\n print(\"\"\"Make your choice:\n 0. Ctable\n 1. Create\n 2. Read\n 3. Update\n 4. Delete\"\"\")\n choice = input(\"\")\n choice_menu = {'Ctable': Create.create_table,\n 'Create': Create.create_phone_book,\n 'Read': Create.read_phone_book,\n 'Update': Create.update_phone_book,\n 'Delete': Create.delete_user_phone}\n if choice not in choice_menu.keys():\n print(\"Enter you choice\")\n else:\n choice_menu[choice]()\n\n","sub_path":"PhoneBookDB.py","file_name":"PhoneBookDB.py","file_ext":"py","file_size_in_byte":2622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"110186909","text":"def get_middle(s):\n len_s = len(s)\n print(len_s)\n return_value = \"\"\n if(len(s))==0:\n return(\"\")\n elif(len_s%2 ==0):\n\n index_m = len(s)//2\n index_low = index_m - 1\n index_high = index_m + 1\n return_value = s[index_low:index_high]\n elif(len(s)%2==1):\n return_value = s[len(s)//2]\n print(return_value)\n return(return_value)\n\nget_middle(\"test\")#,\"es\")\nget_middle(\"testing\")#,\"t\")\nget_middle(\"middle\")#,\"dd\")\nget_middle(\"A\")#,\"A\")#\nget_middle(\"of\")#,\"of\")","sub_path":"get_middle.py","file_name":"get_middle.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"9508046","text":"import pyautogui\n\nsize = pyautogui.size()\npoint = pyautogui.position()\n\nrst = pyautogui.onScreen(100, 100)\n\nprint(size, point, rst)\n\npyautogui.moveTo(10, 10, 2)\npyautogui.moveTo(size.width/2, size.height/2, 2)\npyautogui.moveRel(100, 0, 2)","sub_path":"autoGui/move.py","file_name":"move.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"637604160","text":"import pytest\nfrom django.urls import reverse\nfrom rest_framework import status\n\nfrom members.models import Profile\n\n\n@pytest.mark.django_db\nclass TestProfileAPI:\n pytestmark = pytest.mark.django_db\n\n def test_profile_list_create(self, api_client, create_user, create_icon_category_and_icon):\n url = reverse('members:profile-list-create-view')\n user, token = create_user(email='test@test.com')\n icon_list = create_icon_category_and_icon()\n data = {\n \"profile_name\": \"example\",\n \"profile_icon\": icon_list[0].pk,\n\n }\n\n api_client.credentials(HTTP_AUTHORIZATION=f'TOKEN {token.key}')\n response = api_client.post(url, data)\n\n assert response.status_code == status.HTTP_201_CREATED\n\n response = api_client.get(url)\n\n assert response.status_code == status.HTTP_200_OK\n assert len(response.data) == 1\n\n def test_profile_retrieve_update_destroy(self, api_client, create_user, create_profile):\n user, token = create_user(email='test@test.com')\n profile_list = create_profile(user=user)\n\n assert profile_list.union(Profile.objects.all(), all=False).count() == Profile.objects.count()\n api_client.credentials(HTTP_AUTHORIZATION=f'TOKEN {token.key}')\n\n # profile_retrieve test\n for profile in profile_list:\n url = reverse('members:profile-detail-update-destroy-view', kwargs={'pk': profile.pk})\n\n response = api_client.get(url)\n assert response.status_code == status.HTTP_200_OK\n assert response.data.get('profile_name') == profile.profile_name\n\n # profile_update test\n for profile in profile_list:\n url = reverse('members:profile-detail-update-destroy-view', kwargs={'pk': profile.pk})\n\n data = {\n 'profile_name': 'test'\n }\n response = api_client.patch(url, data)\n assert response.status_code == status.HTTP_200_OK\n assert response.data.get('profile_name') == 'test'\n\n # profile_delete test\n for profile in Profile.objects.all():\n url = reverse('members:profile-detail-update-destroy-view', kwargs={'pk': profile.pk})\n\n response = api_client.delete(url)\n assert response.status_code == status.HTTP_204_NO_CONTENT\n\n\n\n","sub_path":"app/members/tests/test_profile.py","file_name":"test_profile.py","file_ext":"py","file_size_in_byte":2341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"158154576","text":"from sqlalchemy.orm import Session\n\nfrom app.db.models.port import Port\n\nfrom app.db.models.port_forward import MethodEnum\nfrom tasks.functions.base import AppConfig\n\n\nclass EhcoConfig(AppConfig):\n method = MethodEnum.EHCO\n\n def __init__(self):\n super().__init__()\n self.app_name = \"ehco\"\n\n\n def apply(self, db: Session, port: Port):\n self.local_port = port.num\n self.app_command = self.get_app_command(port)\n self.update_app = not port.server.config.get(\"ehco\")\n self.applied = True\n return self\n\n def get_app_command(self, port: Port):\n transport_type = port.forward_rule.config.get(\"transport_type\", \"raw\")\n args = (\n f\"--web_port '' \"\n f\"-l 0.0.0.0:{port.num} \"\n f\"--lt {port.forward_rule.config.get('listen_type', 'raw')} \"\n f\"-r {'wss://' if transport_type.endswith('wss') else ('ws://' if transport_type != 'raw' else '')}\"\n f\"{port.forward_rule.config.get('remote_address')}:{port.forward_rule.config.get('remote_port')} \"\n f\"--tt {port.forward_rule.config.get('transport_type', 'raw')}\"\n )\n return f\"/usr/local/bin/ehco {args}\"\n\n @property\n def playbook(self):\n return \"app.yml\"\n","sub_path":"tasks/functions/ehco.py","file_name":"ehco.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"408661030","text":"# The DAG object; we'll need this to instantiate a DAG\nfrom airflow import DAG\n# Operators; we need this to operate!\nfrom airflow.operators.bash_operator import BashOperator\nfrom airflow.operators.docker_operator import DockerOperator\nfrom airflow.operators.email_operator import EmailOperator\nfrom airflow.utils.dates import days_ago\nfrom datetime import timedelta\n# These args will get passed on to each operator\n# You can override them on a per-task basis during operator initialization\ndefault_args = {\n 'owner': 'airflow',\n 'depends_on_past': False,\n 'start_date': days_ago(2),\n 'email': ['binh.nt@teko.vn'],\n 'email_on_failure': True,\n 'email_on_retry': True,\n 'retries': 1,\n 'retry_delay': timedelta(minutes=5),\n 'queue': 'queue2',\n # 'pool': 'backfill',\n # 'priority_weight': 10,\n # 'end_date': datetime(2016, 1, 1),\n # 'wait_for_downstream': False,\n # 'dag': dag,\n # 'sla': timedelta(hours=2),\n # 'execution_timeout': timedelta(seconds=300),\n # 'on_failure_callback': some_function,\n # 'on_success_callback': some_other_function,\n # 'on_retry_callback': another_function,\n # 'sla_miss_callback': yet_another_function,\n # 'trigger_rule': 'all_success'\n}\ndag = DAG(\n 'test_docker_image',\n default_args=default_args,\n description='Test run docker image',\n schedule_interval=timedelta(days=1),\n)\ndag.doc_md = __doc__\n\n# Define checking tasks\ncheck_commands = \"\"\"\n{% for i in range(5) %}\n echo \"{{ ds }}\"\n echo \"{{ macros.ds_add(ds, 7)}}\"\n echo \"{{ params.my_param }}\"\n{% endfor %}\n\"\"\"\ncheck_task = BashOperator(\n task_id='checking',\n depends_on_past=False,\n bash_command=check_commands,\n params={'my_param': 'Parameter I passed in queue default'},\n dag=dag\n)\n\n# Define main docker tasks\nmain_task = DockerOperator(\n task_id='main_docker_task',\n image='teko_spark_env:latest',\n api_version='auto',\n depends_on_past=False,\n auto_remove=True,\n environment= {\n },\n command=['/bin/sh', '-c', 'echo','\"hello world\"' ],\n docker_url=\"unix://var/run/docker.sock\",\n network_mode=\"bridge\",\n tty=True,\n dag=dag,\n)\n\n# Define after finishing tasks\nfinish_commands = \"\"\"\n{% for i in range(5) %}\n echo \"{{ ds }}\"\n echo \"{{ macros.ds_add(ds, 7)}}\"\n echo \"{{ params.my_param }}\"\n{% endfor %}\n\"\"\"\nfinish_task = BashOperator(\n task_id='finishing',\n depends_on_past=False,\n bash_command=finish_commands,\n params={'my_param': 'Parameter I passed in queue default'},\n dag=dag\n)\nemail = EmailOperator(\n task_id='send_email',\n to='binh.nt@teko.vn',\n subject='Finished Task',\n html_content=\"\"\"

Finished Task

\"\"\",\n dag=dag\n)\ncheck_task >> main_task >> finish_task >> email\n","sub_path":"example_dags/example_docker.py","file_name":"example_docker.py","file_ext":"py","file_size_in_byte":2755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"167496129","text":"#!/usr/bin/python\n# -*- coding:utf-8 -*-\n\nfrom .HAT.Raspi_PWM_Servo_Driver import PWM\n\n############################\n# 用于控制坦克云台部分功能\n############################\n\"\"\"用于控制坦克云台部分\"\"\"\n\n\nclass Turret():\n # Initialise the PWM device using the default address\n # bmp = PWM(0x40, debug=True)\n pwm = PWM(0x6F)\n pwm.setPWMFreq(60) # Set frequency to 60 Hz\n\n # 此为偏航舵机的角度参数\n servoMin_yaw = 300 # Min pulse length out of 4096\n servoMid_yaw = 375\n servoMax_yaw = 630 # Max pulse length out of 4096\n # 此为俯仰舵机的角度参数(60HZ时)\n servoMin_pitch = 220 # Min pulse length out of 4096\n servoMid_pitch = 380\n servoMax_pitch = 630 # Max pulse length out of 4096\n servoYawNum = 0\n servoPitchNum = 1\n\n def ServoUpdate(channel, pulse):\n self.pwm.setPWM(channel, 0, pulse)\n\n # 俯仰 0-180 对应220到630\n def pitch(self, angle):\n if (angle <= 0):\n angle = 0\n elif (angle >= 180):\n angle = 180\n else:\n angle = angle\n\n # 求出每度角度对应的脉冲\n perAnglePulse = (self.servoMax_pitch - self.servoMin_pitch) / 180\n # 采用四舍五入的方式得到角度对应需要发送的脉冲宽度\n sendPulse = self.servoMin_pitch + round(angle * perAnglePulse)\n # 发送脉冲\n self.ServoUpdate(self.servoPitchNum, sendPulse)\n\n # 偏航\n def yaw(self, angle):\n if angle <= 0:\n angle = 0\n elif angle >= 180:\n angle = 180\n else:\n angle = angle\n # 求出每度角度对应的脉冲\n perAnglePulse = (self.servoMax_yaw - self.servoMin_yaw) / 180\n # 采用四舍五入的方式得到角度对应需要发送的脉冲宽度\n sendPulse = self.servoMin_yaw + round(angle * perAnglePulse)\n # 发送脉冲\n self.ServoUpdate(self.servoPitchNum, sendPulse)\n\n # 云台进入收藏状态\n def turret_off(self):\n self.pitch(0)\n self.yaw(90)\n","sub_path":"V1.0-PiTankP3/PiTankProject/Turret.py","file_name":"Turret.py","file_ext":"py","file_size_in_byte":2069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"376380651","text":"# -*- coding: utf-8 -*-\n'''\nSalt module to manage Kubernetes cluster\n\n.. versionadded:: 2016.3.0\n\nRoadmap:\n\n* Add (auto)scalling\n\n'''\n\nfrom __future__ import absolute_import\n\nimport os\nimport re\nimport logging\nimport random\nimport json\nimport copy\nimport base64\nimport hashlib\nimport tempfile\nimport time\nfrom urllib import basejoin as urljoin\nfrom salt.ext.six.moves.urllib.parse import urlparse as _urlparse # pylint: disable=no-name-in-module\nimport salt.ext.six as six\nimport yaml\n\nimport salt.utils.http as http\nfrom salt.utils import dictdiffer, traverse_dict\nfrom salt.utils.dictupdate import update as dictupdate\nfrom salt.utils.dictupdate import merge as dictmerge\n\n__virtualname__ = 'k8s'\n\n# Setup the logger\nlog = logging.getLogger(__name__)\n\nHASH_ANNOTATION = \"salt/sha1\"\nFORBIDDEN_ANNOTATION = \"salt/failing\"\n\n\ndef __virtual__():\n '''Load module'''\n return __virtualname__\n\n\nclass Kubernetes(object):\n\n def __init__(self, kubeconfig=\"\", context_name=\"\"):\n self.context_name = context_name\n self.kubeconfig = kubeconfig\n self.client_crt = tempfile.mktemp()\n self.client_key = tempfile.mktemp()\n self.ca = tempfile.mktemp()\n self.known_namespaces = []\n self.get_auth()\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n for i in [self.client_crt, self.client_key, self.ca]:\n try:\n os.unlink(i)\n except OSError:\n pass\n except Exception as e:\n log.info('could not cleanup tmp file %s due to error %s', i, e)\n\n def guess_api_version(self, kind):\n kind = self.kind(kind)\n if kind == 'replicationcontrollers':\n return 'v1'\n else:\n return 'extensions/v1beta1'\n\n @staticmethod\n def load_manifest(filename):\n \"\"\" load manifest in yaml or json format into the dictionary or array of dictionaries\n support multiple documents in single file \"\"\"\n data = []\n if not filename:\n return {}\n if not os.path.isfile(filename):\n log.error(\"path %s is not file\", filename)\n return {}\n log.debug(\"loading manifest %s\", filename)\n with open(filename, 'r') as f:\n try:\n for i in yaml.safe_load_all(f):\n if isinstance(i, six.string_types):\n log.error(\"expected manifest data, but got plaintext: %s\", i)\n else:\n data.append(i)\n except yaml.YAMLError as exc:\n log.error(\"yaml can't be loaded due to error: [%s]\", exc)\n except:\n try:\n for line in f:\n while True:\n try:\n jobj = json.loads(line)\n break\n except ValueError:\n # Not yet a complete JSON value\n line += next(f)\n data.append(jobj)\n except:\n log.error(\"manifest file %s is neither yaml nor json file or format is wrong\", filename)\n if len(data) == 1:\n return data[0]\n else:\n return data\n\n def _get_context(self):\n \"\"\"\n Get the context info such as:\n cluster info\n user info\n from kubeconfig file, if context_name is not set,\n current-context will be used automatically.\n \"\"\"\n config = self.load_manifest(self.kubeconfig)\n\n if not self.context_name:\n self.context_name = config.get('current-context')\n log.debug('context name is: %s', self.context_name)\n\n for i in config.get('contexts', []):\n if i.get('name', '') == self.context_name:\n context = i.get('context')\n break\n else:\n return {}\n\n cluster_name = context.get('cluster')\n user_name = context.get('user')\n\n for i in config.get('clusters', []):\n if i.get('name', '') == cluster_name:\n cluster = i.get('cluster', {})\n log.trace(\"cluster info: %s\", cluster)\n break\n else:\n return {}\n\n for i in config.get('users', []):\n if i.get('name', '') == user_name:\n user = i.get('user', {})\n log.trace(\"user info: %s\", cluster)\n break\n else:\n return {}\n\n return dictmerge(cluster, user)\n\n def get_context_name(self):\n return self.context_name\n\n @staticmethod\n def get_names(kobj):\n \"\"\" get names out of any object received by kubernetes or array of objects\"\"\"\n log.trace(\"got kubernetes object: %s\", kobj)\n names = []\n if \"items\" in kobj:\n for i in kobj.get(\"items\", []):\n name = traverse_dict(i, \"metadata:name\", None)\n if name:\n names.append(name)\n elif traverse_dict(kobj, \"metadata:name\", None):\n names.append(traverse_dict(kobj, \"metadata:name\", None))\n log.trace(\"got names: %s\", names)\n return names\n\n @staticmethod\n def get_labels(kobj, label_name=None):\n '''Get all labels from a kube object.'''\n if label_name:\n return traverse_dict(kobj, \"metadata:labels:{0}\".format(label_name), None)\n return traverse_dict(kobj, \"metadata:labels\", None)\n\n def get_auth(self):\n context = self._get_context()\n self.auth = {}\n\n self.api_server = context.get('server', 'http://127.0.0.1:8080')\n\n if 'client-certificate-data' in context and 'client-key-data' in context:\n # we have client certification auth\n log.trace('client-certificate-data %s', context.get('client-certificate-data', \"\"))\n with open(self.client_crt, 'w') as crt:\n crt.write(base64.decodestring(context.get('client-certificate-data', \"\")))\n log.trace('client-key-data %s', context.get('client-key-data', \"\"))\n with open(self.client_key, 'w') as key:\n key.write(base64.decodestring(context.get('client-key-data', \"\")))\n self.auth['cert'] = (self.client_crt, self.client_key)\n\n if self.api_server.startswith('https'):\n log.trace('certificate-authority-data %s', context.get('certificate-authority-data', \"\"))\n with open(self.ca, 'w') as ca:\n ca.write(base64.decodestring(context.get('certificate-authority-data', \"\")))\n self.auth['ca_bundle'] = self.ca\n self.auth['verify_ssl'] = True\n\n # token and username/password are mutually exclusive\n if 'token' in context:\n self.auth.setdefault('header_dict', {})['Authorization'] = 'Bearer {0}'.format(context.get('token'))\n elif 'username' in context and 'password' in context:\n self.auth['username'] = context.get('username')\n self.auth['password'] = context.get('password')\n\n log.trace('kubernetes login information: %s', self.auth)\n return self.auth\n\n def url(self, path):\n log.debug(\"generated url: %s\", urljoin(self.api_server, path))\n return urljoin(self.api_server, path)\n\n @staticmethod\n def kind(kind):\n \"\"\" generate normalized kind name out of user defined ones: \"\"\"\n # format is 0 element is \"expected\" by k8s the rest is aliases\n kinds = {\n \"pods\": [\"pod\", \"po\"],\n \"services\": [\"service\", \"svc\", \"svcs\"],\n \"deployments\": [\"deployment\"],\n \"replicasets\": [\"rs\"],\n \"replicationcontrollers\": [\"rc\", \"rcs\", \"replicationcontroller\"],\n \"nodes\": [\"no\", \"node\", ],\n \"events\": [\"ev\", \"event\", \"evs\"],\n \"limitranges\": [\"limitrange\", \"limit\", \"limits\"],\n \"persistentvolumes\": [\"pv\", \"persistentvolume\", \"pvs\"],\n \"persistentvolumeclaims\": [\"pvc\", \"persistentvolumeclaim\", \"pvcs\"],\n \"resourcequotas\": [\"resourcequota\", \"quota\", \"quotas\"],\n \"namespaces\": [\"namespace\", \"ns\"],\n \"serviceaccounts\": [],\n \"ingresses\": [\"ing\"],\n \"horizontalpodautoscalers\": [\"hpa\"],\n \"daemonsets\": [\"ds\"],\n \"configmaps\": [\"configmap\"],\n \"componentstatuses\": [\"cs\"],\n \"endpoints\": [\"ep\", \"endpoint\"],\n \"secrets\": [\"secret\"]\n }\n\n log.trace(\"Got object for normalization: %s\", kind)\n if isinstance(kind, bool):\n # for some reason k8s.get no produces False as input\n kind = \"nodes\"\n else:\n kind = kind.lower()\n for k, v in kinds.iteritems():\n if kind == k or kind in v:\n kind = k\n break\n\n log.trace(\"normalized object is: %s\", kind)\n return kind\n\n @staticmethod\n def is_dns_subdomain(name):\n ''' Check that name is DNS subdomain: One or more lowercase rfc1035/rfc1123\n labels separated by '.' with a maximum length of 253 characters '''\n\n dns_subdomain = re.compile(r\"\"\"^[a-z0-9\\.-]{1,253}$\"\"\")\n return bool(dns_subdomain.match(name))\n\n def get_path(self, kind, namespace=\"\", name=\"\", api=\"\"):\n \" generate URL based on values \"\n kind = self.kind(kind)\n\n if api == 'extensions/v1beta1' or api == '/apis/extensions/v1beta1':\n api = '/apis/extensions/v1beta1'\n else:\n api = '/api/v1'\n\n if kind == 'namespaces':\n if namespace:\n return '{api}/namespaces/{namespace}'.format(api=api, namespace=namespace)\n elif name:\n return '{api}/namespaces/{namespace}'.format(api=api, namespace=name)\n\n if name and namespace:\n return '{api}/namespaces/{namespace}/{kind}/{name}'.format(api=api, namespace=namespace, kind=kind, name=name)\n elif kind == 'nodes' and namespace and not name:\n return '{api}/{kind}/{name}'.format(api=api, kind=kind, name=namespace)\n elif namespace:\n return '{api}/namespaces/{namespace}/{kind}'.format(api=api, namespace=namespace, kind=kind)\n elif name:\n return '{api}/{kind}/{name}'.format(api=api, kind=kind, name=name)\n else:\n return '{api}/{kind}'.format(api=api, kind=kind)\n\n def get(self, path, data=None):\n ''' get any object from kubernetes based on URL '''\n\n # Make request\n try:\n ret = http.query(self.url(path), method='GET', params=data, raise_error=False, **self.auth)\n except Exception as exp:\n log.error(\"Can't make request due to error: %s\", exp)\n raise Exception(str(exp))\n\n log.trace(\"GET got a reply: %s\", ret)\n\n try:\n body = json.loads(ret.get('body'))\n except TypeError as exp:\n # body is None\n log.info(\"could not load json from body due to [%s], input is [%s]\", exp, ret)\n body = {}\n if body.get('kind') == 'Status' and body.get('status') == 'Failure':\n if body.get('code') == 404:\n raise LookupError\n else:\n raise Exception(body)\n return body\n\n def delete(self, path, data=None):\n ''' delete any object from kubernetes based on URL '''\n\n # Make request\n try:\n ret = http.query(self.url(path), method='DELETE',\n data=json.dumps(data), raise_error=False, **self.auth)\n except Exception as exp:\n log.error(\"Can't make request due to error: %s\", exp)\n raise exp\n\n log.trace(\"DELETE got a reply: %s\", ret)\n\n body = json.loads(ret.get('body'))\n if body.get('kind') == 'Status' and body.get('status') == 'Failure':\n raise Exception(body)\n return body\n\n def post(self, path, data):\n ''' create any object in kubernetes based on URL '''\n\n auth = copy.copy(self.auth)\n\n # Prepare headers\n header = {\"Content-Type\": \"application/json\"}\n auth['header_dict'] = dictmerge(header, auth.get('header_dict', {}))\n # Make request\n try:\n ret = http.query(self.url(path), method='POST', data=json.dumps(data), raise_error=False, **auth)\n except Exception as exp:\n log.error(\"Can't make request due to error: %s\", exp)\n raise exp\n\n # Check requests status\n log.trace(\"POST got a reply: %s\", ret)\n\n body = json.loads(ret.get('body'))\n if body.get('kind') == 'Status' and body.get('status') == 'Failure':\n raise Exception(body)\n return body\n\n def put(self, path, data):\n ''' put any object in kubernetes based on URL '''\n auth = copy.copy(self.auth)\n\n # Prepare headers\n header = {\"Content-Type\": \"application/json\"}\n auth['header_dict'] = dictmerge(header, auth.get('header_dict', {}))\n # Make request\n try:\n ret = http.query(self.url(path), method='PUT', data=json.dumps(data), **auth)\n except Exception as exp:\n log.error(\"Can't make request due to error: %s\", exp)\n raise exp\n\n # Check requests status\n log.trace(\"PUT got a reply: %s\", ret)\n\n body = json.loads(ret.get('body'))\n if body.get('kind') == 'Status' and body.get('status') == 'Failure':\n raise Exception(body)\n return body\n\n def patch(self, path, data, patch_mode=\"json\"):\n ''' patch any object in kubernetes based on URL '''\n\n auth = copy.copy(self.auth)\n log.trace(\"patch operations are %s\", data)\n\n # Prepare headers\n # Prepare headers\n if patch_mode == \"merge\":\n # RFC7386\n header = {\"Content-Type\": \"application/merge-patch+json\"}\n elif patch_mode == \"k8s\":\n # Kubernetes custom implementation of merge-patch\n header = {\"Content-Type\": \"application/strategic-merge-patch+json\"}\n else:\n # RFC6902\n header = {\"Content-Type\": \"application/json-patch+json\"}\n\n auth['header_dict'] = dictmerge(header, auth.get('header_dict', {}))\n # Make request\n try:\n ret = http.query(self.url(path), method='PATCH', data=json.dumps(data), **auth)\n except Exception as exp:\n log.error(\"Can't make request due to error: %s\", exp)\n raise exp\n\n body = json.loads(ret.get('body'))\n if body.get('kind') == 'Status' and body.get('status') == 'Failure':\n raise Exception(body)\n return body\n\n\ndef _get_filename(source, saltenv):\n \"\"\" get filename out from source definition which can be one of:\n salt://path, file:///path or even http://path\n \"\"\"\n try:\n source_url = _urlparse(source)\n except TypeError:\n return '', {}, ('Invalid format for source parameter')\n\n protos = ('salt', 'http', 'https', 'ftp', 'swift', 's3', 'file')\n\n log.trace(\"parsed source looks like: %s\", source_url) # pylint: disable=no-member\n if not source_url.scheme or source_url.scheme == 'file':\n # just a regular file\n filename = os.path.abspath(source_url.path)\n log.debug(\"Source is a regular local file: %s\", source_url.path)\n else:\n if source_url.scheme in protos:\n # The source is a file on a server\n filename = __salt__['cp.cache_file'](source, saltenv)\n if not filename:\n log.warn(\"Source file: %s can not be retrieved\", source)\n return \"\"\n return filename\n\n\ndef label_folder_absent(kind, namespace=\"\", name=\"\", var=\"\", kubeconfig=\"\", context_name=\"\", k8s=None):\n '''\n .. versionadded:: 2016.3.0\n\n Delete label folder to the current node\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' k8s.label_folder_absent hw\n salt '*' k8s.label_folder_absent hw/ kube-node.cluster.local http://kube-master.cluster.local\n\n '''\n folder = var.strip(\"/\") + \"/\"\n ret = {'name': folder, 'result': True, 'comment': '', 'changes': {}}\n\n if not k8s:\n with Kubernetes(kubeconfig, context_name) as k8s:\n return label_folder_absent(kind=kind, namespace=namespace,\n name=name, var=var,\n kubeconfig=kubeconfig,\n context_name=context_name, k8s=k8s)\n old_labels = get(kind, namespace, name, k8s=k8s, labels_only=True)\n if not isinstance(old_labels, dict):\n ret[\"result\"] = False\n ret[\"comment\"] = old_labels\n return ret\n\n # Prepare a temp labels dict\n for key in old_labels.keys():\n if key.startswith(folder):\n label(kind, namespace, name, var=key, k8s=k8s)\n return ret\n\n\ndef get(kind, namespace=\"\", name=\"\", kubeconfig=\"\", context_name=\"\", k8s=None,\n names_only=False, labels_only=False, label_selector={}, field_selector={}):\n \"\"\"\n Get k8s kind\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' k8s.get [object_type] [namespace=default] [obj_name] [apiserver_url] [names_only=False}\n\n\n Object type can be one of the:\n nodes\n secrets\n pods\n replicationcontrollers\n services\n serviceaccounts\n limitranges\n podtemplates\n proxy\n persistentvolumeclaims\n resourcequotas\n\n Examples:\n\n .. code-block:: bash\n\n salt '*' k8s.get namespaces\n salt '*' k8s.get secrets namespace_name secret_name http://kube-master.cluster.local\n salt '*' k8s.get pods namespace_name pod_name http://kube-master.cluster.local\n salt '*' k8s.get rc namespace_name rc_name\n\n \"\"\"\n data = {}\n if label_selector:\n data['labelSelector'] = _prepare_selector(label_selector)\n if field_selector:\n data['fieldSelector'] = _prepare_selector(field_selector)\n log.debug(\"label selector is [%s], field selector is [%s]\", data.get('labelSelector'), data.get('fieldSelector'))\n # Make request\n if not data:\n data = None\n\n if not k8s:\n with Kubernetes(kubeconfig, context_name) as k8s:\n return get(kind=kind, namespace=namespace, name=name,\n kubeconfig=kubeconfig, context_name=context_name, k8s=k8s,\n names_only=names_only, label_selector=label_selector,\n field_selector=field_selector)\n else:\n url = k8s.get_path(kind, namespace, name)\n try:\n ret = k8s.get(url, data)\n except LookupError:\n ret = {}\n except Exception as exp:\n log.error(\"get was not successful due to: %s\", exp)\n ret = {}\n\n if names_only:\n return k8s.get_names(ret)\n elif labels_only and 'items' not in ret:\n return k8s.get_labels(ret)\n else:\n return ret\n\n\ndef delete(kind=\"\", namespace=\"\", name=\"\", kubeconfig=\"\", context_name=\"\",\n cascade=False, grace_period=0, k8s=None):\n \"\"\"\n Delete k8s object\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' k8s.delete [object_type] [namespace=default] [obj_name] [apiserver_url]\n\n\n Object type can be one of the:\n secrets\n pods\n replicationcontrollers\n services\n serviceaccounts\n limitranges\n podtemplates\n proxy\n persistentvolumeclaims\n resourcequotas\n\n Examples:\n\n .. code-block:: bash\n\n salt '*' k8s.delete namespace\n salt '*' k8s.delete secrets namespace_name secret_name http://kube-master.cluster.local\n salt '*' k8s.delete pods namespace_name pod_name http://kube-master.cluster.local\n salt '*' k8s.delete rc namespace_name rc_name\n\n \"\"\"\n ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}\n\n if not namespace:\n return {'name': namespace, 'result': False, 'comment': 'No namespace defined', 'changes': {}}\n\n # we don't want to copy/paste logic for k8s object available and not, but we\n # do need destructor to be called after the Kubernetes class exists so we\n # use recursion here :(\n if not k8s:\n with Kubernetes(kubeconfig, context_name) as k8s:\n return delete(kind=kind, namespace=namespace, name=name, cascade=cascade, grace_period=grace_period, k8s=k8s)\n else:\n kind = k8s.kind(kind)\n url = k8s.get_path(kind, namespace, name)\n if kind == 'replicationcontrollers' and cascade:\n annotate(\"rc\", namespace, name, \"salt/next-action\", int(time.time() + 60))\n scale(kind, namespace, name, 0, k8s=k8s)\n rc = get('rc', namespace, name, k8s=k8s)\n selector = traverse_dict(rc, \"spec:selector\", {\"fakeselector\": \"+1\"})\n while get(\"pods\", namespace, names_only=True, label_selector=selector, k8s=k8s):\n time.sleep(3)\n\n request_body = {\n \"kind\": \"DeleteOptions\",\n \"apiVersion\": \"v1\",\n \"gracePeriodSeconds\": grace_period\n }\n # Make request\n try:\n if grace_period:\n k8s.delete(url, request_body)\n else:\n k8s.delete(url)\n ret['comment'] = \"Removed {0} {1} in {2} namespace\".format(kind, name, namespace)\n ret['changes'][' '.join([kind, name])] = '{0} {1} removed'.format(kind, name)\n except Exception as e:\n ret['comment'] = \"Could not remove due to error: {0}\".format(e)\n ret['result'] = False\n return ret\n\n\n# Namespaces\ndef create_namespace(name, kubeconfig=\"\", context_name=\"\", k8s=None):\n '''\n .. versionadded:: 2016.3.0\n\n Create kubernetes namespace from the name, similar to the functionality added to kubectl since v.1.2.0:\n .. code-block:: bash\n\n kubectl create namespaces namespace-name\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' k8s.create_namespace namespace_name\n\n salt '*' k8s.create_namespace namespace_name kubeconfig context_name\n\n '''\n ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}\n # Prepare data\n data = {\n \"kind\": \"Namespace\",\n \"apiVersion\": \"v1\",\n \"metadata\": {\n \"name\": name,\n }\n }\n log.trace(\"namespace creation requests: %s\", data) # pylint: disable=no-member\n # Make request\n if not k8s:\n with Kubernetes(kubeconfig, context_name) as k8s:\n return create_namespace(name=name, k8s=k8s)\n try:\n k8s.get(k8s.get_path('namespaces', name))\n log.debug(\"Namespace %s is already present\", name)\n ret['comment'] = \"Namespace {0} is already present\".format(name)\n except LookupError:\n try:\n k8s.post(k8s.get_path('namespaces'), data)\n log.info(\"Successfully created namespace %s\", name)\n ret['changes'][name] = \"namespace created\"\n except Exception as exp:\n log.error(\"Could not create namespace due to error [%s]\", exp)\n ret['result'] = False\n ret['comment'] = \"Could not create namespace due to error [{0}]\".format(exp)\n return ret\n\n\n# Secrets\ndef _update_secret(namespace, name, data, k8s):\n '''Replace secrets data by a new one'''\n # Prepare URL\n ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}\n\n # Prepare data\n data = [{\"op\": \"replace\", \"path\": \"/data\", \"value\": data}]\n # Make request\n try:\n url = k8s.get_path(\"secrets\", namespace, name)\n k8s.patch(url, data)\n ret['changes'][name] = 'updated'\n log.info('secret %s is updated on %s namespace', name, namespace)\n except Exception as exp:\n ret['result'] = False\n ret['comment'] = str(exp)\n log.error('secret %s could not be updated on %s namespace due to: [%s]', name, namespace, exp)\n return ret\n\n\ndef _create_secret(namespace, name, data, k8s):\n ''' create namespace on the defined k8s cluster '''\n ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}\n # Prepare URL\n url = k8s.get_path('secrets', namespace)\n # Prepare data\n request = {\n \"apiVersion\": \"v1\",\n \"kind\": \"Secret\",\n \"metadata\": {\n \"name\": name,\n \"namespace\": namespace,\n },\n \"data\": data\n }\n # Make request\n try:\n k8s.post(url, request)\n ret['changes'][name] = 'created'\n log.info('secret %s created on %s namespace', name, namespace)\n except Exception as exp:\n ret['result'] = False\n ret['comment'] = str(exp)\n log.error('secret %s could not be created on %s namespace due to: [%s]', name, namespace, exp)\n return ret\n\n\ndef _is_valid_secret_file(filename):\n \"\"\" checks that secret file is actually a file and it is exists \"\"\"\n if os.path.exists(filename) and os.path.isfile(filename):\n log.debug(\"File: %s is valid secret file\", filename)\n return True\n log.warn(\"File: %s does not exists or not file\", filename)\n return False\n\n\ndef _file_encode(filename):\n \"\"\" encode file into base64 format \"\"\"\n log.trace(\"Encoding secret file: %s\", filename) # pylint: disable=no-member\n with open(filename, \"rb\") as fd:\n data = fd.read()\n return base64.b64encode(data)\n\n\ndef decode_secrets(namespace, name=\"\", kubeconfig=\"\", context_name=\"\", k8s=None):\n '''\n Get k8s secret with already decoded data\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' k8s.decode_secrets namespace_name\n salt '*' k8s.decode_secrets namespace_name secret_name http://kube-master.cluster.local\n\n '''\n\n if not k8s:\n with Kubernetes(kubeconfig, context_name) as k8s:\n return decode_secrets(namespace=namespace, name=name,\n kubeconfig=kubeconfig,\n context_name=context_name, k8s=k8s)\n\n secrets = get(\"secrets\", namespace, name=name, k8s=k8s)\n\n items = secrets.get(\"items\", [])\n if items:\n for i, secret in enumerate(items):\n log.trace(i, secret) # pylint: disable=no-member\n for k, v in secret.get(\"data\", {}).iteritems():\n items[i]['data'][k] = base64.b64decode(v)\n secrets[\"items\"] = items\n return secrets\n else:\n for k, v in secrets.get(\"data\", {}).iteritems():\n secrets['data'][k] = base64.b64decode(v)\n return secrets\n\n\ndef _source_encode(source, saltenv):\n \"\"\" encode files with base64 to use it inside secrets \"\"\"\n try:\n source_url = _urlparse(source)\n except TypeError:\n return '', {}, ('Invalid format for source parameter')\n\n protos = ('salt', 'http', 'https', 'ftp', 'swift', 's3', 'file')\n\n log.trace(\"parsed source looks like: %s\", source_url) # pylint: disable=no-member\n if not source_url.scheme or source_url.scheme == 'file':\n # just a regular file\n filename = os.path.abspath(source_url.path)\n sname = os.path.basename(filename)\n log.debug(\"Source is a regular local file: %s\", source_url.path)\n if Kubernetes.is_dns_subdomain(sname) and _is_valid_secret_file(filename):\n return sname, _file_encode(filename)\n else:\n log.error(\"Data name %s is not valid for secret, it must be dns subdomain\", sname)\n else:\n if source_url.scheme in protos:\n # The source is a file on a server\n filename = __salt__['cp.cache_file'](source, saltenv)\n if not filename:\n log.warn(\"Source file: %s can not be retrieved\", source)\n return \"\", \"\"\n return os.path.basename(filename), _file_encode(filename)\n return \"\", \"\"\n\n\ndef _get_secrets_data(sources, saltenv='base', force=True):\n data = {}\n for source in sources:\n log.debug(\"source is: %s\", source)\n if isinstance(source, dict):\n # format is array of dictionaries:\n # [{public_auth: salt://public_key}, {test: \"/tmp/test\"}]\n log.trace(\"source is dictionary: %s\", source) # pylint: disable=no-member\n for k, v in source.iteritems():\n sname, encoded = _source_encode(v, saltenv)\n if not encoded:\n log.warning(\"Source file %s is missing or name is incorrect\", v)\n if not force:\n raise \"Source file {0} is missing or name is incorrect\".format(v)\n data[k] = encoded\n elif isinstance(source, six.string_types):\n # expected format is array of filenames\n sname, encoded = _source_encode(source, saltenv)\n if not encoded:\n log.warning(\"Source file %s is missing or name is incorrect\", v)\n if not force:\n raise \"Source file {0} is missing or name is incorrect\".format(v)\n data[sname] = encoded\n return data\n\n\ndef create_secret(namespace, name, sources, kubeconfig=\"\", context_name=\"\", force=False, update=False, do_not_create=False, saltenv='base', k8s=None):\n '''\n .. versionadded:: 2016.3.0\n\n Create k8s secrets in the defined namespace from the list of files\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' k8s.create_secret namespace_name secret_name sources\n\n salt '*' k8s.create_secret namespace_name secret_name sources\n http://kube-master.cluster.local\n\n sources are either array of dictionary pairs [{name: path}, {name1: path}] or array of strings defining paths.\n\n Example of paths array:\n\n .. code-block:: bash\n\n ['/full/path/filename', \"salt://secret/storage/file.txt\", \"http://user:password@securesite.com/secret-file.json\"]\n\n Example of dictionaries:\n\n .. code-block:: bash\n\n [{\"nameit\": '/full/path/fiename'}, {name2: \"salt://secret/storage/file.txt\"}]\n\n it also accepts mixed format such as array of dictionaries and strings\n\n optional parameters accepted:\n\n update=[false] default value is false\n if set to false, and secret is already present on the cluster - warning will\n be returned no changes to the secret will be done.\n In case it is set to \"true\" and secret is present but data is differ - secret will be updated.\n\n force=[true] default value is true\n if the to False, secret will not be created in case one of the files is not\n valid kubernetes secret. e.g. capital letters in secret name or _\n in case force is set to True, wrong files will be skipped but secret will be created any way.\n\n saltenv=['base'] default value is base\n in case 'salt://' path is used, this parameter can change the visibility of files\n\n '''\n ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}\n\n if not sources:\n ret['result'] = False\n ret['comment'] = 'No source available'\n return ret\n\n if not k8s:\n with Kubernetes(kubeconfig, context_name) as k8s:\n return create_secret(namespace=namespace, name=name,\n sources=sources, kubeconfig=kubeconfig,\n context_name=context_name, force=force, update=update,\n do_not_create=do_not_create, saltenv=saltenv, k8s=k8s)\n if force:\n create_namespace(name=namespace, k8s=k8s)\n\n log.info(\"creating secret %s out of %s\", name, sources)\n # we need namespace to create secret in it\n\n try:\n secret = get(\"secrets\", namespace, name, k8s=k8s)\n except LookupError as exp:\n secret = {}\n if secret and not update:\n log.info(\"Secret %s is already present on %s\", name, namespace)\n return {'name': name, 'result': True,\n 'comment': 'Secret {0} is already present'.format(name),\n 'changes': {}}\n\n try:\n data = _get_secrets_data(sources, saltenv, force)\n except Exception as exp:\n ret['result'] = False\n ret['comment'] = str(exp)\n return ret\n\n log.trace(\"secret data is: %s\", data) # pylint: disable=no-member\n\n if update and do_not_create and not secret:\n log.info(\"I've instructed to don't create new secrets, but %s \"\n \"doesn't exists yet on namespace %s\", name, namespace)\n ret['result'] = False\n ret['comment'] = \"I've instructed to don't create new secrets, but {0} doesn't exists yet on namespace {1}\".format(name, namespace)\n elif secret and data != secret.get('data', \"\") and update:\n log.info(\"updating secret %s\", name)\n ret = _update_secret(namespace=namespace, name=name, data=data, k8s=k8s)\n elif not secret:\n log.info(\"creating secret %s\", name)\n ret = _create_secret(namespace=namespace, name=name, data=data, k8s=k8s)\n return ret\n\n\n# LimitRange\n# https://github.com/kubernetes/kubernetes/blob/release-1.2/docs/design/admission_control_limit_range.md\ndef _normalize_limits(limits):\n \"\"\" k8s wants us to omit values if they are empty\n that is why I have to check each of them and create if needed\"\"\"\n normalized_limits = []\n limit_categories = ['type', 'min', 'max', 'default', 'defaultRequest', 'maxLimitRequestRatio']\n\n if isinstance(limits, (tuple, list)):\n for i in limits:\n normalized = {}\n for j in [j for j in limit_categories if j in i.keys()]:\n if j == 'type' and i.get(\"type\") in [\"Container\", \"Pod\"]:\n normalized[\"type\"] = i.get(\"type\")\n continue\n for k, v in i.get(j).iteritems():\n if k in [\"cpu\", \"memory\"]:\n normalized.setdefault(j, {})[k] = str(v)\n normalized_limits.append(normalized)\n\n return normalized_limits\n\n\ndef _get_limit_changes(limit_obj, configured_limits):\n \"\"\"\n get limit object from kubernetes and normalized limits from the create_limit_range compare them,\n if there is a change - generate \"patch\" operation to replace limits with the normalized values\n \"\"\"\n log.trace(\"Cluster limit object is: %s\", limit_obj)\n log.trace(\"Configured limit object is: %s\", configured_limits)\n limits = limit_obj.get(\"spec\", {})\n diff = dictdiffer.DictDiffer({\"limits\": configured_limits}, limits)\n if diff.added() or diff.changed() or diff.removed():\n return [{\"op\": \"replace\", \"path\": \"/spec/limits\", \"value\":\n configured_limits}]\n else:\n return None\n\n\ndef create_limit_range(namespace, limits, name=\"limits\", kubeconfig=\"\",\n context_name=\"\", force=True, update=True, k8s=None):\n \"\"\"\n .. versionadded:: 2016.3.0\n\n Manages limit ranges for kubernetes namespace. Requires LimitRanger admission controller to work.\n\n Validation:\n\n Min (if specified) <= DefaultRequest (if specified) <= Default (if specified) <= Max (if specified)\n\n Kubernetes expects following request:\n .. code-block:: bash\n\n apiVersion: \"v1\"\n kind: \"LimitRange\"\n metadata:\n name: \"limits\"\n namespace: default\n spec:\n limits:\n - type: \"Container\"\n defaultRequests:\n cpu: \"100m\"\n\n limits is a array of dictionaries\n [{\"type\": \"Container\", \"defaultRequests\": {\"cpu\": \"100m\", \"memory\": \"250Mi\"}}}]\n\n accepted type values are \"Container\" and \"Pod\"\n\n accepted constraint values are:\n\n min - minimum requested value of the type\n max - maximum\n default - default limit\n defaultRequest - default requests\n maxLimitRequestRatio - ratio between requests and limit possible\n\n There are 2 possible limits you can set: \"cpu\" and \"memory\"\n\n \"\"\"\n ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}\n\n if not k8s:\n with Kubernetes(kubeconfig, context_name) as k8s:\n return create_limit_range(namespace, limits, name=name,\n kubeconfig=kubeconfig,\n context_name=context_name, force=force,\n update=update, k8s=k8s)\n\n normalized_limits = _normalize_limits(limits)\n if not normalized_limits:\n return {'name': name, 'result': False, 'comment': 'Limits format is not recognized', 'changes': {}}\n\n try:\n limit_range = k8s.get(k8s.get_path(\"limits\", namespace, name))\n log.info(\"limit range %s is available on %s namespace\", name, namespace)\n if not update:\n log.info(\"I was instructed to don't update %s limit range on namespace %s\", name, namespace)\n return {'name': name, 'result': False, 'comment': 'Limit is already present', 'changes': {}}\n changes = _get_limit_changes(limit_range, normalized_limits)\n if changes:\n try:\n k8s.patch(k8s.get_path(\"limitranges\", namespace), changes)\n log.info(\"limit range %s updated, changes are [%s]\", name, changes)\n ret['comment'] = \"Limits updated\"\n ret['changes'][name] = normalized_limits\n except Exception as exp:\n log.error(\"can't update limit range %s due to error %s\", name, exp)\n ret['comment'] = str(exp)\n ret['result'] = False\n except LookupError:\n request = {\n \"apiVersion\": \"v1\",\n \"kind\": \"LimitRange\",\n \"metadata\": {\n \"name\": name,\n \"namespace\": namespace\n },\n \"spec\": {\n \"limits\": normalized_limits\n }\n }\n\n log.trace(\"limit range create requests: %s\", request) # pylint: disable=no-member\n try:\n k8s.post(k8s.get_path(\"limitranges\", namespace), request)\n log.info(\"created limit range %s on namespace %s\", name, namespace)\n ret['comment'] = \"Limits created\"\n ret['changes'][name] = normalized_limits\n except Exception as exp:\n log.error(\"could not create limit range %s due to %s\", name, exp)\n ret['comment'] = \"Could not create limits: {0}\".format(str(exp))\n ret['result'] = False\n return ret\n\n\n# Resource quotas\n# https://github.com/kubernetes/kubernetes/blob/release-1.2/docs/design/admission_control_resource_quota.md\ndef _get_quota_changes(quota, normalized):\n \"\"\" get PATCH string out from quota object and defined normalized value \"\"\"\n quotas = quota.get(\"spec\", {}).get(\"hard\", {})\n diff = dictdiffer.DictDiffer(normalized, quotas)\n if diff.changed() or diff.added() or diff.removed():\n return [{\"op\": \"replace\", \"path\": \"/spec/hard\", \"value\": normalized}]\n else:\n return None\n\n\ndef _normalize_quotas(quota):\n \"\"\" k8s wants us to omit values if they are empty\n that is why I have to check each of them and create if defined but omit if\n they are empy \"\"\"\n normalized = {}\n\n valid_quotas = [\"cpu\", \"memory\", \"persistentvolumeclaims\", \"pods\",\n \"replicationcontrollers\", \"resourcequotas\", \"secrets\",\n \"services\"]\n\n if isinstance(quota, dict):\n for i in [i for i in valid_quotas if i in quota]:\n normalized[i] = str(quota.get(i))\n elif isinstance(quota, (tuple, list)):\n for i in quota:\n k, v = i.items()[0]\n if k in valid_quotas:\n normalized[k] = str(v)\n return normalized\n\n\ndef create_resource_quota(namespace, quota, name=\"quota\", update=True,\n force=True, kubeconfig=\"\", context_name=\"\", k8s=None):\n\n ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}\n\n if not k8s:\n with Kubernetes(kubeconfig, context_name) as k8s:\n return create_resource_quota(namespace, quota, name=name,\n update=update, force=force,\n kubeconfig=kubeconfig,\n context_name=context_name, k8s=k8s)\n\n # we need namespace to create quotas\n if force:\n create_namespace(namespace, k8s=k8s)\n\n normalized = _normalize_quotas(quota)\n if not normalized:\n log.error(\"could not understand your quotas definition for %s\", name)\n return {'name': name, 'result': False,\n 'comment': \"Could not understand your quota's definition\", 'changes': {}}\n\n try:\n quota = k8s.get(k8s.get_path(\"quotas\", namespace, name))\n if not update:\n log.info(\"Resource Quota %s is already exists on %s namespace\", name, namespace)\n return {'name': name, 'result': False, 'comment': 'Quota is already present', 'changes': {}}\n else:\n changes = _get_quota_changes(quota, normalized)\n if changes:\n k8s.patch(k8s.get_path(\"quotas\", namespace, name), changes)\n ret['changes'][name] = changes\n ret['comment'] = 'Quota is updated'\n log.info(\"updated quota %s\", name)\n except LookupError:\n # create new one\n request = {\n \"apiVersion\": \"v1\",\n \"kind\": \"ResourceQuota\",\n \"metadata\": {\n \"name\": name,\n \"namespace\": namespace\n },\n \"spec\": {\n \"hard\": normalized\n }\n }\n\n try:\n k8s.post(k8s.get_path(\"quotas\", namespace), request)\n ret['comment'] = \"Quotas are created\"\n ret['changes'][name] = \"quotas are created\"\n log.info(\"created quota %s\", name)\n except Exception as exp:\n ret['comment'] = \"Could cont create quotas due to {0}\".format(exp)\n ret['result'] = False\n log.error(\"could not create quota %s\", exp)\n except Exception as exp:\n ret[\"result\"] = False\n ret['comment'] = str(exp)\n log.error(\"could not create quota %s\", exp)\n return ret\n\n\n# Label\ndef label(kind, namespace=\"\", name=\"\", var=\"\", val=None, kubeconfig=\"\", context_name=\"\", k8s=None):\n \"\"\"\n .. versionadded:: 2016.3.0\n\n Manage labels of the kubernetes objects such as:\n secrets\n pods\n replicationcontrollers\n services\n serviceaccounts\n limitranges\n podtemplates\n proxy\n persistentvolumeclaims\n resourcequotas\n\n Format:\n .. code-block:: bash\n\n k8s.label kubernetes_object namespace obj_name label_name [label_value]\n\n Example:\n .. code-block:: bash\n\n salt '*' k8s.label service default kubernetes test123 12345\n\n Following example will set label test123 to value 12345 for the service\n inside default namespace.\n\n \"\"\"\n ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}\n\n if not k8s:\n with Kubernetes(kubeconfig, context_name) as k8s:\n return label(kind, namespace=namespace, name=name, var=var, val=val, k8s=k8s)\n\n url = k8s.get_path(kind, namespace, name)\n try:\n kind_item = k8s.get(url)\n except LookupError:\n ret['result'] = False\n ret['comment'] = 'Could not find {0} {1} at namespace {2}'.format(kind, name, namespace)\n return ret\n\n label_value = k8s.get_labels(kind_item, var)\n\n log.debug('current value of label %s is %s', var, label_value)\n # value must be either string or null\n try:\n if val:\n val = str(val)\n else:\n val = None\n except Exception:\n val = None\n\n if val and val == label_value:\n log.info(\"label %s is set properly\", var)\n ret[\"comment\"] = \"Label is set properly already\"\n return ret\n elif not label_value and not val:\n log.info(\"label %s is removed already\", var)\n ret[\"comment\"] = \"You already removed this label\"\n return ret\n\n data = {\n \"metadata\": {\n \"labels\": {\n str(var): val\n }\n }\n }\n\n try:\n k8s.patch(url, data, patch_mode=\"k8s\")\n if val:\n log.info(\"set value %s to label name %s\", val, var)\n ret[\"comment\"] = \"set label {0} with value {1}\".format(var, val)\n ret[\"changes\"][\"label {0}\".format(var)] = val\n else:\n log.info(\"removed label %s\", var)\n ret[\"comment\"] = \"removed label {0}\".format(var)\n ret[\"changes\"][\"label {0}\".format(var)] = \"removed\"\n except Exception as exp:\n log.error(\"There is an error: [%s]\", exp)\n ret['result'] = False\n ret['comment'] = exp\n return ret\n\n\n# Annotate\ndef annotate(kind, namespace, name, var, val=None, kubeconfig=\"\", context_name=\"\", k8s=None):\n \"\"\"\n .. versionadded:: 2016.3.0\n\n Manage annotations of the kubernetes objects such as:\n secrets\n pods\n replicationcontrollers\n services\n serviceaccounts\n limitranges\n podtemplates\n proxy\n persistentvolumeclaims\n resourcequotas\n\n Format:\n .. code-block:: bash\n\n k8s.annotate kubernetes_object namespace obj_name annotation_name [annotation_value]\n\n Example:\n .. code-block:: bash\n\n salt '*' k8s.annotate service default kubernetes test123 12345\n\n Following example will set annotation test123 to value 12345 for the service\n inside default namespace.\n\n \"\"\"\n ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}\n\n if not k8s:\n with Kubernetes(kubeconfig, context_name) as k8s:\n return annotate(kind=kind, namespace=namespace, name=name, var=var, val=val,\n kubeconfig=kubeconfig, context_name=context_name, k8s=k8s)\n\n try:\n k8s_item = get(kind, namespace, name, k8s=k8s)\n annotation = _get_annotation(k8s_item, var)\n if val:\n val = str(val)\n if val != annotation:\n data = {\n \"metadata\": {\n \"annotations\": {\n str(var): val\n }\n }\n }\n try:\n k8s.patch(k8s.get_path(kind, namespace, name), data, patch_mode=\"k8s\")\n if val:\n ret[\"comment\"] = \"annotated {0} with value {1}\".format(var, val)\n log.info(\"annotated %s with value\", var, val)\n else:\n ret[\"comment\"] = \"removed annotation {0}\".format(var)\n log.info(\"annotation %s removed\", var)\n ret[\"changes\"] = {str(var): val}\n except Exception as exp:\n log.error(\"annotation failed due to: %s\", exp)\n ret['result'] = False\n ret['comment'] = str(exp)\n except LookupError:\n log.warning(\"could not find resource to annotate\")\n ret[\"result\"] = False\n ret[\"comment\"] = \"could not find resource to annotate\"\n except Exception as exp:\n log.error(\"could annotate due to %s\", exp)\n ret['result'] = False\n ret['comment'] = str(exp)\n\n return ret\n\n\ndef _get_annotation(obj_dict, annotation, default=None):\n \"\"\" get annotation value out from cluster object dictionary \"\"\"\n if annotation:\n path = \"metadata:annotations:{0}\".format(annotation)\n else:\n path = \"metadata:annotations\"\n return traverse_dict(obj_dict, path, default)\n\n\ndef get_annotation(kind, namespace, name, annotation, kubeconfig=\"\",\n context_name=\"\", k8s=None):\n \"\"\"\n .. versionadded:: 2016.3.0\n\n Get annotations of the kubernetes objects such as:\n secrets\n pods\n replicationcontrollers\n services\n serviceaccounts\n limitranges\n podtemplates\n proxy\n persistentvolumeclaims\n resourcequotas\n\n Format:\n .. code-block:: bash\n\n k8s.get_annotation kubernetes_object namespace obj_name annotation_name\n\n Example:\n .. code-block:: bash\n\n salt '*' k8s.get_annotation service default kubernetes test123\n\n Following example will get annotation test123 for the service inside default namespace.\n\n \"\"\"\n ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}\n\n if not k8s:\n with Kubernetes(kubeconfig, context_name) as k8s:\n return get_annotation(kind=kind, namespace=namespace, name=name,\n annotation=annotation, kubeconfig=kubeconfig,\n context_name=context_name, k8s=k8s)\n\n try:\n k8s_item = k8s.get(k8s.get_path(kind, namespace, name))\n return _get_annotation(k8s_item, annotation, {})\n except LookupError:\n ret[\"result\"] = False\n ret[\"comment\"] = \"could not find {0} {1} on {2} namespace\".format(kind, name, namespace)\n except Exception as exp:\n log.error(\"get annotation failed due to %s\", exp)\n ret[\"result\"] = False\n ret[\"comment\"] = str(exp)\n return ret\n\n\n# Services\ndef _get_service_changes(service, manifest):\n \"\"\" get PATCH string out from service object and configured manifest \"\"\"\n change_ops = []\n svc_spec = service.get(\"spec\", {})\n m_spec = manifest.get(\"spec\", {})\n svc_meta = service.get(\"metadata\", {})\n m_meta = manifest.get(\"metadata\", {})\n\n spec = dictdiffer.DictDiffer(m_spec, svc_spec)\n changes = spec.changed() | spec.added() | spec.removed()\n log.trace(\"service changes are: %s\", changes)\n for change in changes:\n if change != \"clusterIP\" and m_spec.get(change):\n change_ops.append({\"op\": \"replace\",\n \"path\": \"/spec/{0}\".format(change),\n \"value\": m_spec.get(change)})\n\n # In case labels are changed - we must update them also\n meta = dictdiffer.DictDiffer(m_meta, svc_meta)\n meta_changes = meta.changed() | meta.added() | spec.removed()\n if 'labels' in meta_changes:\n change_ops.append({\"op\": \"replace\",\n \"path\": \"/metadata/labels/\",\n \"value\": m_meta.get(\"labels\", {})})\n return change_ops\n\n\ndef _needs_recreation(service, manifest):\n \"\"\" check for read only fields, if they are changed \"\"\"\n service = service.get(\"spec\", {})\n manifest = manifest.get(\"spec\", {})\n\n # clusterIP can't be changed during runtime, so we can't actually update it\n if \"clusterIP\" in manifest:\n diff = dictdiffer.DictDiffer(service, manifest)\n return 'clusterIP' in diff.changed()\n else:\n return False\n\n\ndef create_service(namespace, source, name=\"\", labels=None, force=True,\n update=False, saltenv='base', replace_name=True,\n replace_namespace=True, kubeconfig=\"\", context_name=\"\", k8s=None):\n ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}\n\n if not k8s:\n with Kubernetes(kubeconfig, context_name) as k8s:\n return create_service(namespace=namespace, source=source, name=name,\n labels=labels, force=force, update=update,\n saltenv=saltenv, replace_name=replace_name,\n replace_namespace=replace_namespace,\n kubeconfig=kubeconfig, context_name=context_name, k8s=k8s)\n\n if force:\n create_namespace(name=namespace, k8s=k8s)\n\n # we support either dictionary or filename in yaml or json format\n if isinstance(source, six.string_types):\n manifest = _get_filename(source, saltenv)\n data = k8s.load_manifest(manifest)\n elif isinstance(source, dict):\n data = source\n else:\n ret[\"result\"] = False\n ret[\"comment\"] = \"Could not load manifest file\"\n return ret\n\n if name and replace_name:\n data.setdefault(\"metadata\", {})[\"name\"] = name\n else:\n name = data.get(\"metadata\", {}).get(\"name\")\n\n if replace_namespace:\n data.setdefault(\"metadata\", {})[\"namespace\"] = namespace\n else:\n namespace = data.get(\"metadata\", {}).get(\"namespace\")\n\n url = k8s.get_path(\"services\", namespace)\n try:\n service = k8s.get(k8s.get_path(\"services\", namespace, name))\n if not update:\n ret[\"result\"] = False\n ret[\"comment\"] = \"Service {0} already exists, not instructed to update\".format(name)\n log.info(\"Service %s is already exists, not going to update\", name)\n else:\n if _needs_recreation(service, data) and force:\n try:\n k8s.delete(k8s.get_path(\"services\", namespace, name))\n data = _set_data_hash(data)\n k8s.post(url, data)\n log.info(\"recreated service %s on namespace %s\", name, namespace)\n ret['changes'][name] = \"recreated\"\n except Exception as exp:\n ret['result'] = False\n ret['comment'] = str(exp)\n return ret\n\n data_hash = _gen_data_hash(data)\n service_hash = _get_annotation(service, HASH_ANNOTATION)\n\n if not service_hash:\n annotate(\"services\", namespace, name, HASH_ANNOTATION, data_hash)\n ret[\"chages\"] = \"prepared for salt management\"\n elif data_hash != service_hash:\n changes = _get_service_changes(service, data)\n try:\n k8s.patch(k8s.get_path(\"services\", namespace, name), changes)\n ret['changes'] = changes\n ret['comment'] = \"Service is updated\"\n annotate(\"svc\", namespace, name, HASH_ANNOTATION, data_hash)\n except Exception as exp:\n ret['comment'] = \"Could not update service due to {0}\".format(str(exp))\n ret['result'] = False\n except LookupError:\n # new service creation\n data = _set_data_hash(data)\n try:\n k8s.post(url, data)\n ret['comment'] = \"Service is created\"\n ret['changes'][name] = 'created'\n except Exception as exp:\n ret['comment'] = \"Could not create service due to error {0}\".format(str(exp))\n ret['result'] = False\n except Exception as exp:\n ret['result'] = False\n ret['comment'] = str(exp)\n\n return ret\n\n\n# Replication Controllers\ndef _get_replicas(rc):\n \" get replicas out from replication controller\"\n return int(traverse_dict(rc, \"spec:replicas\", 0))\n\n\ndef _needs_scaling(rc, data):\n \" checks that replication controller needs scaling \"\n old_replicas = _get_replicas(rc)\n new_replicas = _get_replicas(data)\n\n next_action_time = _get_annotation(rc, \"salt/next-action\", 0)\n if float(next_action_time) > time.time():\n return False\n\n if _get_annotation(rc, \"kubernetes.io/update-partner\"):\n return False\n return old_replicas != new_replicas\n\n\ndef scale(kind, namespace, name, replicas, kubeconfig=\"\", context_name=\"\", k8s=None):\n \"\"\"\n .. versionadded:: 2016.3.0\n\n scale replication controller to the replicas value\n Format:\n .. code-block:: bash\n\n k8s.scale namespace rc_name replicas [apiserver_url]\n\n Example:\n .. code-block:: bash\n\n salt '*' k8s.scale kube-system kube-dns 2\n\n Following example will scale kube-dns replication controller on kube-system\n names to 2 replicas.\n\n \"\"\"\n ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}\n\n if not k8s:\n with Kubernetes(kubeconfig, context_name) as k8s:\n return scale(kind=kind, namespace=namespace, name=name, replicas=replicas,\n kubeconfig=kubeconfig, context_name=context_name, k8s=k8s)\n data = {\n \"spec\": {\"replicas\": replicas}\n }\n try:\n url = k8s.get_path(kind, namespace, name, api=k8s.guess_api_version(kind))\n item = k8s.get(url)\n if _get_replicas(item) != replicas:\n k8s.patch(url, data, patch_mode=\"k8s\")\n ret[\"changes\"] = {\"kind\": kind, \"replicas\": replicas}\n log.info(\"scaled %s %s on %s namespace to %s\", kind, name, namespace, replicas)\n except LookupError:\n ret[\"result\"] = False\n ret[\"comment\"] = \"could not find {0} {1} on {2} namespace to scale\".format(kind, name, namespace)\n log.warning(\"could not find %s %s on %s namespace to scale\", kind, name, namespace)\n except Exception as exp:\n ret[\"result\"] = False\n ret[\"comment\"] = str(exp)\n log.error(\"%s\", exp)\n return ret\n\n\ndef _set_zero_replicas(rc, replicas):\n \" set initial replicas count to 0, but annotate desired replicas \"\n log.trace(\"replicas set to %s\", replicas)\n\n data = {\n \"metadata\": {\n \"annotations\": {\n \"kubernetes.io/desired-replicas\": str(replicas)\n }\n },\n \"spec\": {\n \"replicas\": 0\n }\n }\n\n return dictupdate(rc, data)\n\n\ndef _gen_data_hash(data):\n \" generate hash out of replication controller data \"\n tmp = copy.deepcopy(data)\n # prevent rolling-update for scaling requests\n tmp.get(\"spec\", {}).pop(\"replicas\", None)\n return hashlib.sha1(json.dumps(tmp, sort_keys=True)).hexdigest()\n\n\ndef _set_data_hash(rc, data_hash=None):\n \" set data hash of the replication controller \"\n if _get_annotation(rc, HASH_ANNOTATION):\n return rc\n\n if not data_hash:\n data_hash = _gen_data_hash(rc)\n\n data = {\n \"metadata\": {\n \"annotations\": {\n HASH_ANNOTATION: data_hash\n }\n }\n }\n\n return dictupdate(rc, data)\n\n\ndef _set_deployment_label(rc, rc_hash):\n data = {\n \"spec\": {\n \"template\": {\n \"metadata\": {\n \"labels\": {\n \"kubernetes.io/deployment\": str(rc_hash)\n }\n }\n },\n \"selector\": {\n \"kubernetes.io/deployment\": str(rc_hash)\n }\n }\n }\n\n return dictupdate(rc, data)\n\n\ndef _set_rc_selector(namespace, name, old_hash, k8s):\n\n rc = get(\"rc\", namespace, name, k8s=k8s)\n if traverse_dict(rc, \"spec:selector:kubernetes.io/deployment\", \"\") != str(old_hash) \\\n or traverse_dict(rc, \"spec:template:metadata:labels:kubernetes.io/deployment\", \"\") != str(old_hash):\n data = {\n \"spec\": {\n \"template\": {\n \"metadata\": {\n \"labels\": {\n \"kubernetes.io/deployment\": str(old_hash)\n }\n }\n },\n \"selector\": {\n \"kubernetes.io/deployment\": str(old_hash)\n }\n }\n }\n\n return k8s.patch(k8s.get_path('replicationcontrollers', namespace, name), data, patch_mode=\"k8s\")\n return True\n\n\ndef _rollout(namespace, old_rc, next_rc, k8s, batch=1):\n \"\"\" increase replicas for next and decrease old by batch value \"\"\"\n old_name = k8s.get_names(old_rc)[0]\n next_name = k8s.get_names(next_rc)[0]\n\n desired_replicas = int(_get_annotation(next_rc,\n \"kubernetes.io/desired-replicas\",\n traverse_dict(old_rc, \"spec:replicas\", 0)))\n\n next_replicas = int(traverse_dict(next_rc, \"spec:replicas\", 0))\n old_replicas = int(traverse_dict(old_rc, \"spec:replicas\", 0))\n\n # prevent race conditions\n next_action_time = _get_annotation(old_rc, \"salt/next-action\", time.time())\n if float(next_action_time) > time.time():\n return False\n\n if old_replicas - batch <= 0:\n old_final = 0\n else:\n old_final = old_replicas - batch\n scale(\"replicationcontrollers\", namespace, old_name, old_final, k8s=k8s)\n log.info(\"scaling %s to %s replicas\", old_name, old_final)\n\n if desired_replicas > next_replicas:\n next_final = next_replicas + batch\n elif desired_replicas < next_replicas:\n if next_replicas - batch <= 0:\n next_final = 0\n else:\n next_final = next_replicas - batch\n else:\n next_final = desired_replicas\n log.info(\"scaling %s to %s replicas\", next_name, next_final)\n scale(\"replicationcontrollers\", namespace, next_name, next_final, k8s=k8s)\n\n return old_final, next_final\n\n\ndef _get_original_rc_data(next_rc):\n metadata = next_rc.get(\"metadata\", {})\n spec = next_rc.get(\"spec\", {})\n\n metadata.get(\"annotations\", {}).pop(\"kubernetes.io/desired-replicas\", None)\n metadata.get(\"annotations\", {}).pop(\"kubernetes.io/deployment\", None)\n metadata.get(\"labels\", {}).pop(\"kubernetes.io/deployment\", None)\n for i in (\"selfLink\", \"resourceVersion\", \"uid\", \"creationTimestamp\", \"generation\", \"\"):\n metadata.pop(i, None)\n\n spec.get(\"template\", {}).get(\"metadata\", {}).get(\"labels\", {}).pop(\"kubernetes.io/deployment\", None)\n spec.get(\"selector\", {}).pop(\"kubernetes.io/deployment\", None)\n next_rc['metadata'] = metadata\n next_rc['spec'] = spec\n next_rc.pop(\"status\", None)\n\n return next_rc\n\n\ndef _prepare_selector(labels):\n return ','.join([\"{0}={1}\".format(k, v) for k, v in labels.iteritems()])\n\n\ndef rolling_update(namespace, name, source, kubeconfig=\"\", context_name=\"\",\n one_change_only=True, saltenv=\"base\", create_new=True,\n update_period=0, poll_interval=3, batch=1, k8s=None):\n \"\"\" perform replication controller rolling update \"\"\"\n ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}\n\n if not k8s:\n with Kubernetes(kubeconfig, context_name) as k8s:\n return rolling_update(namespace=namespace, name=name, source=source,\n kubeconfig=kubeconfig,\n context_name=context_name,\n one_change_only=one_change_only,\n saltenv=saltenv, create_new=create_new,\n update_period=update_period,\n poll_interval=poll_interval, batch=batch,\n k8s=k8s)\n\n if isinstance(source, six.string_types):\n manifest = _get_filename(source, saltenv)\n data = k8s.load_manifest(manifest)\n elif isinstance(source, dict):\n data = source\n\n if not data:\n ret[\"result\"] = False\n ret['comment'] = \"data is empty, nothing to do\"\n return ret\n\n # preparation\n full_data_hash = _gen_data_hash(data)\n log.debug(\"full data hash is: %s\", full_data_hash)\n data_hash = hashlib.sha1(json.dumps(data.get(\"spec\"), sort_keys=True)).hexdigest()[:16]\n log.debug(\"data hash is %s:\", data_hash)\n\n try:\n old_rc = get('rc', namespace, name, k8s=k8s)\n log.debug(\"old replication controller %s is present\", name)\n except LookupError:\n log.debug(\"old replication controller %s is not present\", name)\n if create_new:\n data = _set_data_hash(data, full_data_hash)\n log.debug(\"creating new rc from rolling update\")\n return create_rc(namespace, data, name, k8s=k8s)\n else:\n ret['comment'] = 'could not find replication controller {0}'.format(name)\n ret['result'] = False\n return ret\n except Exception as exp:\n ret['result'] = False\n ret['comment'] = \"no rolling update possible: {0}\".format(str(exp))\n log.error(\"no rolling update possible %s\", exp)\n return ret\n\n next_name = traverse_dict(old_rc, \"metadata:annotations:kubernetes.io/update-partner\",\n \"{0}-{1}\".format(name, data_hash))\n\n log.debug(\"next name defined is %s\", next_name)\n try:\n log.debug(\"entered next_rc creation\")\n next_rc = k8s.get(k8s.get_path('replicationcontrollers', namespace, next_name))\n if _get_annotation(old_rc, FORBIDDEN_ANNOTATION) == full_data_hash:\n _rollback(namespace, old_rc, k8s=k8s)\n return ret\n log.debug(\"it is not in FORBIDDEN\")\n if _get_annotation(old_rc, HASH_ANNOTATION) == full_data_hash:\n # the same data present on old and new rc\n delete(\"rc\", namespace, next_name, k8s=k8s)\n ret['comment'] = \"rolling update is finished\"\n return ret\n log.debug(\"it is no the same\")\n except LookupError:\n log.debug(\"did not find %s\", next_name)\n if _get_annotation(old_rc, FORBIDDEN_ANNOTATION) == full_data_hash:\n ret[\"result\"] = False\n ret[\"comment\"] = \"We already tried this one, and it failed, remove annotation {0} to try again\".format(FORBIDDEN_ANNOTATION)\n log.info(\"we tried to do rolling update for %s with hash %s but it\"\n \"failed, please remove %s to try once again\", name, full_data_hash, FORBIDDEN_ANNOTATION)\n return ret\n log.debug(\"No replication controller %s present, creating one\", next_name)\n # create next rc and do rollout\n data = _set_zero_replicas(data, data.get(\"spec\", {}).get(\"replicas\"))\n data = _set_deployment_label(data, data_hash)\n data = _set_data_hash(data, full_data_hash)\n log.debug(\"creating new rc %s\", next_name)\n create_rc(namespace, data, next_name, k8s=k8s, replace_name=True, update=False, force=False)\n next_rc = data\n # mark old rc with our name\n annotate('rc', namespace, name, \"kubernetes.io/update-partner\", next_name, k8s=k8s)\n except Exception as exp:\n log.debug(\"some exception\")\n log.error(\"%s\", exp)\n\n log.debug(\"doing actual rolling out for %s and %s\", name, next_name)\n next_action_time = _get_annotation(old_rc, \"salt/next-action\", time.time())\n if float(next_action_time) > time.time():\n return {'name': name, 'result': True, 'changes': {},\n 'comment': 'it is too early, wait for {0} seconds and try again'.format(int(next_action_time) - int(time.time()))}\n\n old_deploy_hash = traverse_dict(old_rc, \"metadata:labels:kubernetes.io/deployment\", None)\n old_selector_hash = traverse_dict(old_rc, \"spec:selector:kubernetes.io/deployment\", None)\n old_hash = hashlib.sha1(json.dumps(old_rc.get(\"spec\"), sort_keys=True)).hexdigest()[:16]\n old_selector = traverse_dict(old_rc, \"spec:selector\", {})\n\n if not old_deploy_hash:\n # both replication controllers must have deployment labels\n # we just begin the rolling update\n log.debug(\"No deployment hash assigned to old RC\")\n label('rc', namespace, name, \"kubernetes.io/deployment\", data_hash, k8s=k8s)\n\n if not old_selector_hash:\n # we must mark old pods with the new labels to fit selector of old rc\n log.info(\"Assigning deployment selector %s to pods from rc %s\", old_hash, k8s.get_names(old_rc)[0])\n for pod in get(\"pods\", namespace, label_selector=old_selector, k8s=k8s).get('items', []):\n log.debug(\"assigning label %s to kubernetes.io/deployment for pod %s\", old_hash, k8s.get_names(pod)[0])\n # selector of old rc match (we own this pod)\n label(\"pods\", namespace, k8s.get_names(pod)[0], \"kubernetes.io/deployment\", old_hash)\n\n # we must add some deployment key as a selector, which is different from\n # next's selector\n annotate(\"rc\", namespace, name, \"kubernetes.io/update-partner\", next_name, k8s=k8s)\n _set_rc_selector(namespace, name, old_hash, k8s=k8s)\n\n log.debug(\"checking that we need a rollback\")\n if _needs_rollback(namespace, next_rc, k8s=k8s):\n log.debug(\"we need a rollback\")\n _rollback(namespace, old_rc, k8s=k8s)\n return ret\n else:\n log.debug(\"we doing a rollout\")\n old_replicas, next_replicas = _rollout(namespace, old_rc, next_rc, k8s, batch)\n log.info(\"after manipulations %s has %s replicas, %s: %s\", name, old_replicas, next_name, next_replicas)\n\n # update to prevent race condition\n if not update_period:\n update_period = calculate_safe_timeout(next_rc)\n timestamp = int(time.time()) + update_period\n log.info(\"set next action time to +%s seconds\", update_period)\n annotate(\"rc\", namespace, name, \"salt/next-action\", str(timestamp), k8s=k8s)\n\n # cleanup\n desired_replicas = int(_get_annotation(next_rc, \"kubernetes.io/desired-replicas\",\n traverse_dict(old_rc, \"spec:replicas\", 0)))\n\n # we want to wait for one more cycle before the removal\n next_replicas = int(traverse_dict(next_rc, \"spec:replicas\", 0))\n log.debug(\"desired replicas of next rc: %s\", desired_replicas)\n if desired_replicas == next_replicas and old_replicas == 0:\n original_data = _get_original_rc_data(next_rc)\n log.debug(\"next rc data: %s\", original_data)\n delete('rc', namespace, name, k8s=k8s)\n # cleanup\n res = create_rc(namespace, original_data, name, k8s=k8s)\n if res.get(\"result\") is False:\n return res\n delete(\"rc\", namespace, next_name, k8s=k8s)\n\n return ret\n\n\ndef create_rc(namespace, source, name=\"\", labels={}, kubeconfig=\"\",\n context_name=\"\", force=True, update=False, saltenv='base', replace_name=True,\n replace_namespace=True, patch_labels=[], one_change_only=False, k8s=None):\n\n ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}\n\n if not k8s:\n with Kubernetes(kubeconfig, context_name) as k8s:\n return create_rc(namespace=namespace, source=source, name=name,\n labels=labels, kubeconfig=kubeconfig,\n context_name=context_name, force=force,\n update=update, saltenv=saltenv,\n replace_name=replace_name,\n replace_namespace=replace_namespace,\n patch_labels=patch_labels,\n one_change_only=one_change_only, k8s=k8s)\n\n if force:\n create_namespace(namespace, k8s=k8s)\n\n if isinstance(source, six.string_types):\n manifest = _get_filename(source, saltenv)\n data = k8s.load_manifest(manifest)\n elif isinstance(source, dict):\n data = source\n\n if not data:\n ret[\"result\"] = False\n return ret\n\n if name and replace_name:\n data.setdefault(\"metadata\", {})[\"name\"] = name\n else:\n name = data.get(\"metadata\", {}).get(\"name\")\n\n if namespace and replace_namespace:\n data.setdefault(\"metadata\")[\"namespace\"] = namespace\n else:\n namespace = data.get(\"metadata\", {}).get(\"namespace\")\n\n log.trace(\"replication controller data is: %s\", data)\n\n try:\n rc = k8s.get(k8s.get_path(\"replicationcontrollers\", namespace, name))\n\n replicas = _get_replicas(data)\n if _needs_scaling(rc, data):\n return scale(\"replicationcontrollers\", namespace, name, replicas, k8s=k8s)\n\n if not update:\n ret[\"comment\"] = \"\"\"Replication controller {0} already exists and I've been instructed not to update it\"\"\".format(name)\n else:\n data_hash = _gen_data_hash(data)\n rc_hash = _get_annotation(rc, HASH_ANNOTATION)\n\n if not rc_hash:\n # RC is was not managed by salt\n annotate(\"rc\", namespace, name, HASH_ANNOTATION, data_hash, k8s=k8s)\n ret[\"comment\"] = \"\"\"prepared rc for management from salt\"\"\"\n elif rc_hash != data_hash:\n # rolling update required\n log.debug('rolling update of %s required', name)\n ret = rolling_update(namespace, name, data, one_change_only=one_change_only, k8s=k8s)\n except LookupError:\n # there is no such RC\n log.debug(\"replication controller %s not found, need to create one\", name)\n data = _set_data_hash(data)\n try:\n k8s.post(k8s.get_path(\"replicationcontrollers\", namespace), data)\n ret[\"changes\"][name] = \"created replication controller on namespace {0}\".format(namespace)\n log.info(\"created replication controller %s on namespace %s\", name, namespace)\n except Exception as exp:\n ret['result'] = False\n ret['comment'] = str(exp)\n except Exception as exp:\n ret['result'] = False\n ret['comment'] = str(exp)\n return ret\n\n\ndef _needs_rollback(namespace, next_rc, k8s):\n answer = False\n selector = traverse_dict(next_rc, \"spec:selector\", {})\n pods = {}\n if selector:\n try:\n pods = get(\"pods\", namespace, label_selector=selector, k8s=k8s)\n except LookupError:\n pass\n except Exception as exp:\n log.error(\"%s\", exp)\n for pod in pods.get(\"items\", []):\n pod_name = k8s.get_names(pod)[0]\n pod_uid = traverse_dict(pod, \"metadata:uid\", \"-12\")\n field_selector = {\n \"involvedObject.name\": pod_name,\n \"involvedObject.namespace\": namespace,\n \"involvedObject.uid\": pod_uid\n }\n events = get(\"events\", namespace, field_selector=field_selector, k8s=k8s)\n for event in events.get(\"items\"):\n log.debug(\"cheking even for pod %s: %s\", pod_name, events)\n if event.get(\"reason\", \"\").lower() in [\"failedsync\", \"backoff\", \"unhealthy\"]:\n log.info(\"have to rollback due to pod %s with reason %s\", pod_name, event.get(\"reason\"))\n return True\n return answer\n\n\ndef _rollback(namespace, target, k8s, batch=1):\n \"\"\" perform rollback of failed rolling update \"\"\"\n if isinstance(target, six.string_types):\n # it is just name\n old_rc = get('rc', namespace, target, k8s=k8s)\n name = target\n else:\n old_rc = target\n name = k8s.get_names(target)[0]\n\n partner = _get_annotation(old_rc, \"kubernetes.io/update-partner\")\n next_rc = get('rc', namespace, partner, k8s=k8s)\n desired_replicas = _get_annotation(next_rc, \"kubernetes.io/desired-replicas\")\n data_hash = _get_annotation(next_rc, HASH_ANNOTATION)\n\n # mark deployment as forbidden\n annotate(\"rc\", namespace, name, FORBIDDEN_ANNOTATION, data_hash, k8s=k8s)\n annotate(\"rc\", namespace, name, \"kubernetes.io/desired-replicas\", desired_replicas, k8s=k8s)\n\n next_replicas, old_replicas = _rollout(namespace, next_rc, old_rc, k8s, batch)\n if int(old_replicas) == int(desired_replicas) and int(next_replicas) == 0:\n delete(\"rc\", namespace, partner, cascade=True, k8s=k8s)\n\n\ndef calculate_safe_timeout(resource):\n \"\"\" calculate timeout based on containers liveness and readiness\n probe information \"\"\"\n containers = []\n if isinstance(resource, dict):\n # we have just rc\n containers = traverse_dict(resource, \"spec:template:spec:containers\", [])\n else:\n containers = resource\n\n timeouts = [60] # minimum value is 60 seconds the same as kubectl value\n secure_margin = random.randint(5, 20)\n\n for container in containers:\n for probe_type in (\"livenessProbe\", \"readinessProbe\"):\n probe = container.get(probe_type)\n if probe:\n probe_timeout = (\n int(probe.get(\"initialDelaySeconds\", 0))\n + int(probe.get(\"timeoutSeconds\", 1)) * int(probe.get(\"failureThreshold\", 1))\n + int(probe.get(\"periodSeconds\", \"20\")) * int(probe.get(\"failureThreshold\", 1))\n )\n log.debug(\"calculated safe timeout based on probe %s data: %s\", probe_type, probe_timeout)\n timeouts.append(probe_timeout)\n return max(timeouts) + secure_margin\n\n\ndef create(source, namespace=\"\", kubeconfig=\"\", context_name=\"\", force=True,\n replace_namespace=True, update=True, saltenv='base', k8s=None):\n\n ret = {'name': \"create\", 'result': True, 'comment': '', 'changes': {}}\n\n if not k8s:\n with Kubernetes(kubeconfig, context_name) as k8s:\n return create(source=source, namespace=namespace, kubeconfig=kubeconfig, context_name=context_name,\n force=force, replace_namespace=replace_namespace, update=update, saltenv=saltenv, k8s=k8s)\n\n log.debug(\"source is [%s], namespace is [%s] \"\n \"kubeconfig is [%s]\", source, namespace, kubeconfig)\n if isinstance(source, six.string_types):\n log.info(\"manifest file is: %s\", source)\n manifest = _get_filename(source, saltenv)\n mdata = k8s.load_manifest(manifest)\n log.debug(\"data is %s\", mdata)\n elif isinstance(source, dict):\n mdata = source\n\n # we unify format to deal with array of dicts\n if isinstance(mdata, dict):\n mdata = [mdata]\n\n origin_namespace = namespace\n\n for data in mdata:\n log.trace(\"created data: %s\", data)\n if not data:\n ret[\"result\"] = False\n continue\n kind = data.get(\"kind\", \"\").lower()\n api = data.get(\"apiVersion\", \"\").lower()\n name = traverse_dict(data, \"metadata:name\", \"\")\n\n log.debug(\"kind: [%s], api: [%s], name: [%s]\", kind, api, name)\n\n # in case of multiple manifests, we need to start over\n if origin_namespace != namespace:\n namespace = origin_namespace\n\n if namespace and replace_namespace:\n data = dictupdate(data, {\"metadata\": {\"namespace\": namespace}})\n elif traverse_dict(data, \"metadata:namespace\", None):\n namespace = traverse_dict(data, \"metadata:namespace\", \"\")\n else:\n namespace = \"default\"\n\n log.debug(\"after manipulations namespace is set to %s\", namespace)\n\n kind = k8s.kind(kind)\n if kind == \"replicationcontrollers\":\n log.debug(\"got replication controller\")\n ret = create_rc(namespace, data, update=update, force=force, replace_namespace=replace_namespace, k8s=k8s)\n elif kind == \"services\":\n log.debug(\"got service\")\n ret = create_service(namespace, data, update=update, force=force, replace_namespace=replace_namespace, k8s=k8s)\n elif kind == \"resourcequotas\":\n log.debug(\"got resource quota\")\n ret = create_resource_quota(namespace, data, update=update, force=force, k8s=k8s)\n elif kind == \"limitranges\":\n log.debug(\"got limits range\")\n ret = create_limit_range(namespace, data, force=force, update=update, k8s=k8s)\n else:\n log.debug(\"using default create method for %s\", kind)\n try:\n kobj = k8s.get(k8s.get_path(kind, namespace, name, api=api))\n log.info(\"%s %s is already existing on %s\", kind, name, namespace)\n continue\n except LookupError:\n if force:\n create_namespace(namespace, k8s=k8s)\n url = k8s.get_path(kind, namespace, api=api)\n try:\n log.debug(\"creating resource %s with name %s\", kind, name)\n data = _set_data_hash(data)\n k8s.post(url, data)\n log.info(\"created resource %s with name %s\", kind, name)\n ret['changes'][\"{0} {1}\".format(kind, name)] = \"created\"\n except Exception as exp:\n log.error(\"could not create %s %s due to: %s\", kind, name, exp)\n ret['comment'] = str(exp)\n ret['result'] = False\n log.error(str(exp))\n except Exception as exp:\n log.error(\"could not create %s %s due to: %s\", kind, name, exp)\n ret['comment'] = str(exp)\n ret['result'] = False\n log.error(str(exp))\n return ret\n\n\ndef drain(node, grace_period=None, kubeconfig=\"\", context_name=\"\", k8s=None):\n ret = {'name': \"drain\", 'result': True, 'comment': '', 'changes': {}}\n if not k8s:\n with Kubernetes(kubeconfig, context_name) as k8s:\n return drain(node=node, kubeconfig=kubeconfig, context_name=context_name, k8s=k8s)\n try:\n log.info(\"draining node %s\", node)\n for pod in get(\"pods\", field_selector={\"spec.nodeName\": node}, k8s=k8s).get('items'):\n namespace = traverse_dict(pod, \"metadata:namespace\", \"default\")\n name = traverse_dict(pod, \"metadata:name\", \"default\")\n ret['changes'].setdefault(namespace, {})[name] = \"pod deleted\"\n delete(\"pods\", namespace, name, grace_period=grace_period, k8s=k8s)\n except Exception as exp:\n log.error(\"oops drain of the node failed due to %s\", exp)\n ret['result'] = False\n ret['comment'] = str(exp)\n return ret\n\n\ndef cordon(node, kubeconfig=\"\", context_name=\"\", k8s=None):\n ret = {'name': \"cordon\", 'result': True, 'comment': '', 'changes': {}}\n if not k8s:\n with Kubernetes(kubeconfig, context_name) as k8s:\n return cordon(node=node, kubeconfig=kubeconfig, context_name=context_name, k8s=k8s)\n\n data = {'spec': {'unschedulable': True}}\n try:\n log.info(\"patching %s to cordon\", node)\n k8s.patch(k8s.get_path('nodes', name=node), data, patch_mode=\"k8s\")\n log.info(\"finished patching %s cordon\", node)\n ret[\"changes\"][node] = \"node cordoned\"\n except Exception as exp:\n log.error(\"oops can't cordon due to %s\", exp)\n ret['result'] = False\n ret['comment'] = str(exp)\n return ret\n return ret\n\n\ndef uncordon(node, kubeconfig=\"\", context_name=\"\", k8s=None):\n ret = {'name': \"uncordon\", 'result': True, 'comment': '', 'changes': {}}\n if not k8s:\n with Kubernetes(kubeconfig, context_name) as k8s:\n return uncordon(node=node, kubeconfig=kubeconfig, context_name=context_name, k8s=k8s)\n\n data = {'spec': {'unschedulable': None}}\n try:\n node_data = get('nodes', name=node, k8s=k8s)\n log.info(\"current cordon state is: %s\", traverse_dict(node_data, \"spec:unschedulable\", False))\n if traverse_dict(node_data, \"spec:unschedulable\", None):\n k8s.patch(k8s.get_path('nodes', name=node), data, patch_mode=\"k8s\")\n ret[\"changes\"][node] = \"node uncordoned\"\n except Exception as exp:\n log.error(\"oops, can't uncordong due to %s\", exp)\n ret['result'] = False\n ret['comment'] = str(exp)\n return ret\n","sub_path":"salt/roots/_modules/k8s.py","file_name":"k8s.py","file_ext":"py","file_size_in_byte":82191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"318736848","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Utilities for getting and initializing KGE models.\"\"\"\n\nfrom typing import Dict\n\nfrom torch.nn import Module\n\nfrom pykeen.constants import (\n CONV_E_NAME, DISTMULT_NAME, ERMLP_NAME, KG_EMBEDDING_MODEL_NAME, RESCAL_NAME, SE_NAME, TRANS_D_NAME, TRANS_E_NAME,\n TRANS_H_NAME, TRANS_R_NAME, UM_NAME,\n)\nfrom pykeen.kge_models import (\n ConvE, DistMult, ERMLP, RESCAL, StructuredEmbedding, TransD, TransE, TransH, TransR, UnstructuredModel,\n)\n\n__all__ = [\n 'KGE_MODELS',\n 'get_kge_model',\n]\n\nKGE_MODELS = {\n TRANS_E_NAME: TransE,\n TRANS_H_NAME: TransH,\n TRANS_D_NAME: TransD,\n TRANS_R_NAME: TransR,\n SE_NAME: StructuredEmbedding,\n UM_NAME: UnstructuredModel,\n DISTMULT_NAME: DistMult,\n ERMLP_NAME: ERMLP,\n RESCAL_NAME: RESCAL,\n CONV_E_NAME: ConvE,\n}\n\n\ndef get_kge_model(config: Dict) -> Module:\n \"\"\"Get an instance of a knowledge graph embedding model with the given configuration.\"\"\"\n kge_model_name = config[KG_EMBEDDING_MODEL_NAME]\n kge_model_cls = KGE_MODELS.get(kge_model_name)\n\n if kge_model_cls is None:\n raise ValueError(f'Invalid KGE model name: {kge_model_name}')\n\n return kge_model_cls(config=config)\n","sub_path":"src/pykeen/kge_models/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"205124457","text":"\"\"\" Imaging the MeasurementSet sim-2.ms\n\n\"\"\"\nimport sys\nimport numpy\n\nfrom rascil.data_models import PolarisationFrame, rascil_path\n\nfrom rascil.processing_components import create_blockvisibility_from_ms, export_image_to_fits, qa_image,\\\n deconvolve_cube, restore_cube, create_image_from_visibility, convert_blockvisibility_to_visibility,\\\n convert_visibility_to_stokes\n\nfrom rascil.workflows import invert_list_serial_workflow\n\nimport logging\nlog = logging.getLogger(__name__)\n\nlog.setLevel(logging.DEBUG)\nlog.addHandler(logging.StreamHandler(sys.stdout))\nlog.addHandler(logging.StreamHandler(sys.stderr))\n\nif __name__ == '__main__':\n results_dir = rascil_path('test_results')\n\n bvt = create_blockvisibility_from_ms(rascil_path('data/vis/sim-2.ms'), start_chan=35, end_chan=39)[0]\n bvt.configuration.diameter[...] = 35.0\n vt = convert_blockvisibility_to_visibility(bvt)\n vt = convert_visibility_to_stokes(vt)\n\n a2r = numpy.pi / (180.0 * 3600.0)\n\n model = create_image_from_visibility(vt, cellsize=20.0 * a2r, npixel=512,\n polarisation_frame=PolarisationFrame('stokesIQUV'))\n dirty, sumwt = invert_list_serial_workflow([vt], [model], context='2d')[0]\n psf, sumwt = invert_list_serial_workflow([vt], [model], context='2d', dopsf=True)[0]\n export_image_to_fits(dirty, '%s/rascil_imaging_sim_2_dirty.fits' % (results_dir))\n export_image_to_fits(psf, '%s/rascil_imaging_sim_2_psf.fits' % (results_dir))\n\n # Deconvolve using msclean\n comp, residual = deconvolve_cube(dirty, psf, niter=10000, threshold=0.001,\n fractional_threshold=0.001,\n algorithm='msclean',\n window_shape='quarter', gain=0.7,\n scales=[0, 3, 10, 30])\n\n restored = restore_cube(comp, psf, residual)\n\n print(qa_image(restored))\n export_image_to_fits(restored, '%s/rascil_imaging_sim_2_restored.fits' % (results_dir))\n export_image_to_fits(residual, '%s/rascil_imaging_sim_2_residual.fits' % (results_dir))\n","sub_path":"examples/scripts/imaging_sim2.py","file_name":"imaging_sim2.py","file_ext":"py","file_size_in_byte":2109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"391444513","text":"import unittest\r\n\r\nclass BashQuoteTests(unittest.TestCase):\r\n\r\n\r\n def test_bash_quote_special(self):\r\n # noinspection PyUnresolvedReferences\r\n from argv_quote import BASH_RESERVED_WORDS, bash_quote\r\n\r\n\r\n for word in BASH_RESERVED_WORDS:\r\n self.assertEqual(\"\\\\\" + word, bash_quote(word))\r\n\r\n for char in ('\\t',\r\n ' ', '!', '\"', '#',\r\n '$', '&', \"'\", '(',\r\n ')', '*', ':', ';',\r\n '<', '>', '?', '@',\r\n '[', ']', '^', '`',\r\n '{', '|', '}', '~'):\r\n self.assertEqual(\"\\\\\" + char, bash_quote(char))\r\n\r\n def test_bash_quote_strings(self):\r\n # noinspection PyUnresolvedReferences\r\n from argv_quote import bash_quote\r\n\r\n self.assertEqual(\"'this is a simple path with spaces'\",\r\n bash_quote('this is a simple path with spaces'))\r\n\r\n self.assertEqual(\"don\\\\'t\", bash_quote(\"don't\"))\r\n self.assertEqual('\"don\\'t do it\"', bash_quote(\"don't do it\"))\r\n\r\n\r\nclass WindowsQuoteTests(unittest.TestCase):\r\n\r\n def testEmbeddedSpace(self):\r\n # noinspection PyUnresolvedReferences\r\n from argv_quote import win_concact_quote, win_quote\r\n self.assertEqual( 'x x x \"z z\"', win_concact_quote('x x x', 'z z'))\r\n\r\n self.assertEqual('x y \"z z\" zed', win_quote('x', 'y', 'z z', 'zed'))\r\n\r\n def testBackslashes(self):\r\n import argv_quote\r\n self.assertEqual(r'\"C:\\Program Files\\my program\\thing.exe\" \"\\\\someserver\\funny share\\path\\\\\" \"a\\\"quote\\\"here\"',\r\n argv_quote.win_quote(r'C:\\Program Files\\my program\\thing.exe',\r\n '\\\\\\\\someserver\\\\funny share\\\\path\\\\',\r\n 'a\"quote\"here'))\r\n\r\nclass OsDefinedQuoteTests(unittest.TestCase):\r\n\r\n def testOsSelection(self):\r\n import sys\r\n # noinspection PyUnresolvedReferences\r\n from argv_quote import quote\r\n if sys.platform == 'win32':\r\n self.assertEqual('\"I am\" Windows not bash', quote('I am', 'Windows', 'not', 'bash'))\r\n else:\r\n self.assertEqual(\"'I am' in \\\\bash\", quote('I am', 'in', 'bash'))\r\n","sub_path":"configure_machine/helpers/test_helpers.py","file_name":"test_helpers.py","file_ext":"py","file_size_in_byte":2219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"549554664","text":"import MapReduce\nimport sys\n\n\"\"\"\nJOIN in the Simple Python MapReduce Framework\n\"\"\"\n\nmr = MapReduce.MapReduce()\n\n# =============================\n# Do not modify above this line\n\n# Implement the MAP function\ndef mapper(myList):\n id = myList[1]\n mr.emit_intermediate(id, myList)\n\n# Implement the REDUCE function\ndef reducer(id, myList):\n \n\n for item in myList:\n if item[0] == \"order\":\n for item2 in myList:\n if item2[0] == \"line_item\":\n \n temp = \"\"\n tempList = []\n tempList = item + item2\n mr.emit((tempList))\n \n \n \n\n# Do not modify below this line\n# =============================\nif __name__ == '__main__':\n inputdata = open(sys.argv[1])\n mr.execute(inputdata, mapper, reducer)\n","sub_path":"HW3/join.py","file_name":"join.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"609227617","text":"import os\nimport sys\nsource_path = os.path.dirname(os.path.abspath(sys.argv[0])) + \"/3Dpredictor/source\"\nsource_path2 = os.path.dirname(os.path.abspath(sys.argv[0])) + \"/3Dpredictor/nn/source\"\nsource_path3 = os.path.dirname(os.path.abspath(sys.argv[0])) + \"/source\"\nsys.path.append(source_path)\nsys.path.append(source_path2)\nsys.path.append(source_path3)\n\nfrom find_gaps import generate_gaps\nimport logging\nlogging.basicConfig(format='%(asctime)s %(name)s: %(message)s', datefmt='%I:%M:%S', level=logging.INFO)\n\nchr_list = ['2L', '2R', '3L', '3R', 'X']\ngenerate_gaps(chr_list=chr_list, cool_file = \"/mnt/scratch/ws/psbelokopytova/202101241522data/nn_anopheles/input/coolers/Acol_4096.cool\",\n output_gap_folder=\"/mnt/scratch/ws/psbelokopytova/202101241522data/nn_anopheles/input/genomes/Acol_4096_\")","sub_path":"generate_gap_files.py","file_name":"generate_gap_files.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"555174981","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n#########################################################\n# Author: Author \n# Book : Book \n#########################################################\n# File : helloworld.py\n# Description: Utitlizando a biblote pygame para imprimir\n# uma imgem na tela...\n\nbackground_image_filename = 'distro.jpg'\nmouse_image_filename = 'logo.png'\n\n# Importa os pacotes do pygame\nimport pygame\nfrom pygame.locals import *\nfrom sys import exit\n\n# Inicializa os modulos do pygame, que poderão carregar drivers e consultar\n# hardware...\npygame.init()\n\n# Cria uma superfície de display, podendo ser uma janela ou a tela toda,\n# sempre retornando um objeto surface que é o janela impressa na tela...\n# O *.display.set_mode aceita três paramentros; somente o primeiro é obrigatorio, que\n# deverá ser uma tupla contendo altura e largura... set_mode é um valor que contem as \n# flags usadas para criação do diplay, utilizamos o valor defauld '0'. O próximo parâmetro\n# especifica a profundidade (depth) da superfície do display, que é a quantidade de bits\n# usada para armazenar as cores do display '32' bits foi utilizado. \nscreen = pygame.display.set_mode((640, 480), 0, 32)\n# *.set_caption do modulo diplay define o nome da janela...\npygame.display.set_caption(\"Olá, Mundo!!!\")\n# A função load de pygame.image é responsavel em carregar as imagens de fundo e curso do \n# mouse, a função load lê um arquivo local (hd) e retorna uma superfície contendo as informações\n# das imagens...\nbackground = pygame.image.load(background_image_filename).convert()\nmouse_cursor = pygame.image.load(mouse_image_filename).convert_alpha()\n# O loop while é repedido em cada atualização da tela\nwhile True:\n\t# O loop for será responsavel em capturar os eventos, as informações\n\t# de teclas e mouse ou qualquer ação referente ao jogo (programa) \n\tfor event in pygame.event.get():\n\t\tif event.type == QUIT:\n\t\t\tpygame.quit()\n\t\t\texit()\n\t\tif event.type == KEYDOWN:\n\t\t\tif event.key == K_UP: # Tecla configurada para sair fullscreen\n\t\t\t\tpygame.quit()\n\t\t\t\texit()\n\t# A proxima linha faz o blit da imagem de background (blitting - copiar de uma imagem para\n\t# outra), a função blit do objeto de tela surface, recebe a imgem contida no variável background\n\t# e uma tupla contendo a posição de destino, a coordenada (0,0), indicando para cobrir toda a \n\t# tela da janela do pygame\n\tscreen.blit(background, (0,0))\n\t# Desenhando o mouse cursor, o módulo pygame.mouse contém tudo de que é preciso para \n\t# tabalhar com o mouse:\n\tx, y = pygame.mouse.get_pos()\t\t# retorna uma tupla contendo as coordenadas do mouse\n\tx -= mouse_cursor.get_width() / 2\t# Ajusta para a metade de sua largura no cursor do mouse\n\ty -= mouse_cursor.get_height() / 2\t# Ajusta para a metade de sua altura no cursor do mouse..\n\tscreen.blit(mouse_cursor, (x, y))\t# A imgem centralizado no cursor da imagem e carregada na tela\n\t\t\t\t\t\t\t\t\t\t# do pygame..\n\t# Imagem é atualizada na tela \t\t\t\t\t\t\t\t\t\n\tpygame.display.update()\n","sub_path":"cap03/listagem31.py","file_name":"listagem31.py","file_ext":"py","file_size_in_byte":3018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"462991297","text":"#!/usr/bin/env python\n\nimport commands\n\ndef post_slack(message, slack_channel_name, slack_webhook_url):\n command_str = ('curl -X POST --data-urlencode \"payload={\\\\\"channel\\\\\": \\\\\"%s\\\\\", \\\\\"text\\\\\": \\\\\"%s\\\\\"}\" \\'%s\\'' % (slack_channel_name, message, slack_webhook_url))\n print('command_str : ' + command_str + ' )')\n commands.getstatusoutput(command_str)\n print('post to slack ( message : ' + message + ' )')\n\n\n","sub_path":"post_slack.py","file_name":"post_slack.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"496337615","text":"import re\ndef parseGslistFile(gene, file):\n # smplist = [] \n smps = \"\"\n with(open(file)) as f:\n line = f.readline()\n while line:\n ptn = gene + \"\\t\"\n if re.match(ptn, line):\n smps = line.strip().split(\"\\t\",1)[1].split(\";\")\n break \n line = f.readline()\n return smps\n","sub_path":"projFocus/ceRNA/model/pynotebook/parseGslistFile.py","file_name":"parseGslistFile.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"367990303","text":"\"\"\"Downloads images from an item_profile csv data file.\n\nLink to lomus query: https://lumos.idata.shopee.com/superset/sqllab?savedQueryId=60928\n\nRequires pandas.\n\"\"\"\nimport argparse\nimport urllib\n\nimport pandas as pd\n\n\n####################\n# HELPER_FUNCTIONS #\n####################\ndef tidy_split(df, column, sep=\"|\", keep=False):\n \"\"\"\n Split the values of a column and expand so the new DataFrame has one split\n value per row. Filters rows where the column is missing.\n\n Params\n ------\n df : pandas.DataFrame\n dataframe with the column to split and expand\n column : str\n the column to split and expand\n sep : str\n the string used to split the column's values\n keep : bool\n whether to retain the presplit value as it's own row\n\n Returns\n -------\n pandas.DataFrame\n Returns a dataframe with the same columns as `df`.\n \"\"\"\n indexes = list()\n new_values = list()\n df = df.dropna(subset=[column])\n for i, presplit in enumerate(df[column].astype(str)):\n values = presplit.split(sep)\n if keep and len(values) > 1:\n indexes.append(i)\n new_values.append(presplit)\n for value in values:\n indexes.append(i)\n new_values.append(value)\n new_df = df.iloc[indexes, :].copy()\n new_df[column] = new_values\n return new_df\n\n\ndef preprocess_item_profile(file_path: str) -> pd.DataFrame:\n \"\"\"Takes in csv file path, and splits the images column,\n making each observation a single image url.\n \"\"\"\n df = pd.read_csv(file_path)\n # Split the images column\n df = tidy_split(df, \"images\", sep=\",\")\n\n def form_url(row):\n country = row[\"country\"].lower()\n if country in [\"th\", \"id\"]:\n country = \"co.\" + country\n elif country in [\"my\", \"br\"]:\n country = \"com.\" + country\n\n img = row[\"images\"]\n\n return f\"https://cf.shopee.{country}/file/{img}\"\n\n # Form the full url\n df[\"img_url\"] = df.agg(form_url, axis=1)\n\n return df\n\n\n########\n# MAIN #\n########\ndef main(args):\n df = preprocess_item_profile(args.data_file)\n\n print(f\"{len(df)} images to download.\")\n\n # Download image files\n for _, row in df.iterrows():\n url = row[\"img_url\"]\n name = url.split(\"/\")[-1]\n country = row[\"country\"].lower()\n output_path = f\"{args.output}/{country}_{name}.jpg\"\n\n try:\n urllib.request.urlretrieve(url, output_path)\n except Exception as e:\n print(e)\n print(f\"Error for {url}\")\n else:\n print(f\"Downloaded {output_path}\")\n\n print(\"Download complete.\")\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=\"Download images from item_profile csv data\"\n )\n\n parser.add_argument(\"--data-file\", help=\"path to csv file\")\n parser.add_argument(\n \"--output\", help=\"path to output directory to store downloaded images\"\n )\n args = parser.parse_args()\n\n main(args)\n","sub_path":"projects/FashionNet/scripts/dl_item_profile_imgs.py","file_name":"dl_item_profile_imgs.py","file_ext":"py","file_size_in_byte":3016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"190284846","text":"import sys\nimport string\n\nfilename = sys.argv[1] \n\nfieldnames=[]\ndb=[]\nline=[]\n\n\nfh = open(filename,\"r\")\nfieldnames = fh.readline().rstrip().split(\",\")\n\nfor li in fh:\n db.append(dict(zip(fieldnames, li.rstrip().split(\",\"))))\n\t\nfh.close()\n\nprint(db)\n \nerg=[]\nk=\"ort\"\nv=\"muenchen\"\nfor row in db:\n if row[k]==v: erg.append(row)\n\nprint()\nprint(erg)\n\n# Join als inverse operation zum split\nsep=\",\"\nfh = open(\"d:/TMP/adr_out.csv\",\"w\")\nprint(sep.join(fieldnames),file=fh)\nfor row in db:\n lst=[]\n for k in fieldnames:\n lst.append(row[k])\n print(sep.join(lst),file=fh)\n\t\nfh.close()","sub_path":"Schulung/parsen_csv.py","file_name":"parsen_csv.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"192383287","text":"from tkinter import Tk, StringVar, Message, Button, Frame, Entry, Label\r\nimport math\r\n\r\n# frequency search function\r\ndef search(arr, UL, LL): # Linear search\r\n count = 0\r\n for x in range(LL, UL + 1, 1):\r\n for ele in arr:\r\n if ele <= UL:\r\n if x == ele:\r\n count += 1\r\n else: break\r\n return count\r\n# End\r\n# DOWNLOADED FROM INTERNET (QUICKSORT)\r\n# https://www.geeksforgeeks.org/quick-sort/\r\ndef partition(arr,low,high): \r\n i = ( low-1 ) # index of smaller element \r\n pivot = arr[high] # pivot \r\n for j in range(low , high): \r\n # If current element is smaller than or equal to pivot \r\n if arr[j] <= pivot: \r\n # increment index of smaller element \r\n i = i+1 \r\n arr[i],arr[j] = arr[j],arr[i] \r\n arr[i+1],arr[high] = arr[high],arr[i+1] \r\n return ( i+1 ) \r\n# \r\ndef quickSort(arr,low,high): \r\n if low < high: \r\n # pi is partitioning index, arr[p] is now at right place \r\n pi = partition(arr,low,high) \r\n # Separately sort elements before partition and after partition \r\n quickSort(arr, low, pi-1) \r\n quickSort(arr, pi+1, high)\r\n#\r\ndef display(LL, UL, f, x, TCB1, TCB2, CF1, CF2, RF, r, k, i, fx, m, xm, fxm, md):\r\n # Print all the value\r\n h1 = '+-------------------------------+------------+------------+--------------------------+------------+------------+------------+-------------+-----------+------------------+\\n'\r\n h2 = '|\\tClass \\t| f \\t | x \\t |\\tTCB \\t | CF \\t | %RF \\t | fx \\t | (x - ẍ) | f(x - ẍ) |\\n'\r\n h3 = '+-------------------------------+------------+------------+--------------------------+------------+------------+------------+-------------+-----------+------------------+\\n'\r\n a = ''\r\n for ix in range(k):\r\n a += '| '+str(LL[ix])+' - '+str(UL[ix])+'\\t\\t| '+str(f[ix])+'\\t| '+str('%g'%x[ix])+'\\t| '+str(TCB1[ix])+' - '+str(TCB2[ix])+'\\t| '+str(CF1[ix])+'\\t| '+str(CF2[ix])+'\\t| '+str('%.2g'%RF[ix])+'\\t| '+str('%g'%fx[ix])+'\\t| '+str('%.4g'%xm[ix])+'\\t| '+str('%.4g'%fxm[ix])+'\\t|\\n'\r\n hn = '+-------------------------------+------------+------------+--------------------------+------------+------------+------------+-------------+-----------+------------------+'\r\n to = '\\n|\\t\\t| '+str(sum(f))+'\\t|\\t|\\t\\t|\\t|\\t|\\t| '+str('%.5g'%m)+'\\t|\\t| '+str('%.5g'%md)+'\\t|'\r\n sv = '\\n\\nRange Value (RV=HV-LV):\\t\\t'+str(r)+'\\nClass Interval (k=1+3.33log(n)):\\t'+str(k)+'\\nClass Size (i=RV/k):\\t\\t'+str(i)\r\n fdt.set(h1+h2+h3+a+hn+to+sv)\r\n#\r\ndef main():\r\n new_data = ''\r\n input_data = inpt.get()\r\n if ',' in input_data:\r\n new_data = input_data.split(',')\r\n elif ' ' in input_data:\r\n new_data = input_data.split()\r\n # SAVE THE DATA IN ARRAY\r\n array = []\r\n try:\r\n for element in new_data:\r\n array.append(int(element))\r\n n = len(array)\r\n # SORT THE DATA\r\n quickSort(array, 0, n-1)\r\n # get the lowest Value(LV) and High Value(HV) from the array\r\n LV = array[0]; HV = array[n-1]\r\n # ==========COMPUTATION===========\r\n # Compute for the RANGE (r)\r\n r = HV - LV\r\n # Compute for the class interval (k)\r\n k = round(1 + 3.33*math.log10(n))\r\n # Compute for the class size (i)\r\n i = round(r/k)\r\n # ============END=================\r\n # Get the LL and the UL\r\n arr_LL = []; arr_UL = []\r\n arr_LL.append(LV)\r\n UL = LV + i - 1\r\n arr_UL.append(UL)\r\n for b in range(k - 1):\r\n LL = UL + 1\r\n arr_LL.append(LL)\r\n UL = LL + i - 1\r\n arr_UL.append(UL)\r\n # Get the frequency of data (f)\r\n f = []\r\n for c in range(k):\r\n fcount = search(array, arr_UL[c], arr_LL[c])\r\n f.append(fcount)\r\n # class mark (x) average of ((LL + UL)/2), then x += i\r\n x = []\r\n cmark = float((arr_UL[0] + arr_LL[0])/2)\r\n x.append(cmark)\r\n for d in range(k-1):\r\n cmark += i\r\n x.append(cmark)\r\n # MEAN fx\r\n fx = []\r\n for d2 in range(k):\r\n fxh = f[d2]*x[d2]\r\n fx.append(round(fxh, 4))\r\n mean = sum(fx)/n\r\n # (x - ẍ)\r\n xm = []\r\n for d3 in range(k):\r\n mnx = abs(x[d3] - mean)\r\n xm.append(mnx)\r\n # f(x - ẍ)\r\n fxm = []\r\n for d4 in range(k):\r\n fmnx = f[d4] * xm[d4]\r\n fxm.append(fmnx)\r\n mad = sum(fxm)/n\r\n # TCB -0.5 +0.5\r\n TCB1 = []; TCB2 = []\r\n for e in arr_LL:\r\n tcb1 = e - 0.5\r\n TCB1.append(tcb1)\r\n for j in arr_UL:\r\n tcb2 = j + 0.5\r\n TCB2.append(tcb2)\r\n # CF=CF-f\r\n CF1 = []; CF2 = []\r\n cf1 = f[0]\r\n CF1.append(cf1)\r\n cf2 = n\r\n CF2.append(cf2)\r\n for g in range(1, k, 1):\r\n cf1 += f[g]\r\n CF1.append(cf1)\r\n for h in range(k):\r\n cf2 -= f[h]\r\n CF2.append(cf2)\r\n # Relative Frequency (RF) = f/n*100\r\n RF = []\r\n for l in f:\r\n rf = l/n*100\r\n RF.append(rf)\r\n # display the table, sorted array and stem leaf\r\n display(arr_LL, arr_UL, f, x, TCB1, TCB2, CF1, CF2, RF, r, k, i, fx, mean, xm, fxm, mad)\r\n # plotline(f, x)\r\n # plotpie(RF)\r\n # plotbar(f, TCB1, TCB2)\r\n except:\r\n fdt.set('Invalid data set!\\n' + input_data)\r\n \r\nparent = Tk()\r\nparent.title(\"Frequency Distributon Table PYTHON TKINTER\")\r\n#win.iconbitmap(\"czero.ico\")\r\nparent.resizable(0,0)\r\n# WIDGET\r\nfdt = StringVar()\r\ninpt = StringVar()\r\nwindow = Frame(parent).pack()\r\ntitle = Message(window, font = ('arial', 13),\r\n text = 'FREQUENCY DISTRIBUTION TABLE\\n\\tCreated by: Bishop', width = 600).pack(pady = 5)\r\nlbl = Label(window, font = ('arial', 11),\r\n text = 'Input the Data here [separated by space or a comma]:').pack(anchor = 'w', padx = 5)\r\ninp = Entry(window, font = ('arial', 15, 'bold'),\r\n fg = 'black', bg = 'lightgray', width = 70, textvariable = inpt).pack(pady = 4, padx = 5, anchor = 'w')\r\nbutton = Button(window, font = ('arial', 10),\r\n bg = 'blue', bd = 5, text = 'Compute', command = lambda : main()).pack(anchor = 'w', padx = 5)\r\nfdttable = Label(window, font = ('arial', 10),\r\n fg = 'black', bg = 'lightgray', width = 97, height = 35, textvariable = fdt, anchor = 'n').pack(pady = 4)\r\n# MASTER/PARENT WINDOW SIZE\r\nparent.minsize(width = 800, height = 600)\r\nparent.mainloop()\r\n","sub_path":"FDT-gui_pack.pyw","file_name":"FDT-gui_pack.pyw","file_ext":"pyw","file_size_in_byte":7124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"535753967","text":"import numpy as np\n\ndef main():\n\n npixels=128\n\n data = np.loadtxt('data.txt')\n data = np.reshape(data, (data.shape[0]/npixels,npixels,npixels))\n for i in range(0,data.shape[0]):\n data[i] = np.flipud(data[i])\n data = np.reshape(data, (data.shape[0],npixels,npixels,1))\n np.save('data', data)\n\n labels = np.loadtxt('labels.txt')\n np.save('labels', labels)\n\nif __name__ == \"__main__\":\n\n main()\n","sub_path":"Deep_Learning_Vertexing/scripts/txttonpy.py","file_name":"txttonpy.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"462152941","text":"from flask import Flask,render_template\n\napp = Flask(__name__)\n\n@app.route('/')\n\ndef seseki():\n\tlist={\"英語\":87, \"数学\":90, \"国語\":45, \"理科\":76, \"社会\":31}\n\treturn render_template('seseki.html',list = list)\n\nif __name__ == '__main__':\n\tapp.debug = True\n\tapp.run()","sub_path":"課題提出済み/3-2.py","file_name":"3-2.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"638730427","text":"'''\npath\n\nA library designed to work with vector paths, \nor continuous paths in space\n'''\nimport numpy as np\nimport networkx as nx\n\nfrom shapely.geometry import Polygon, Point\nfrom copy import deepcopy\nfrom collections import deque\n\nfrom .simplify import simplify\nfrom .polygons import polygons_enclosure_tree, is_ccw\nfrom .constants import *\nfrom ..geometry import plane_fit, plane_transform, transform_points\nfrom ..grouping import unique_rows\n\nclass Path:\n '''\n A Path object consists of two things:\n vertices: (n,[2|3]) coordinates, stored in self.vertices\n entities: geometric primitives (lines, arcs, and circles)\n that reference indices in self.vertices\n '''\n def __init__(self, \n entities = [], \n vertices = [],\n metadata = None):\n '''\n entities:\n Objects which contain things like keypoints, as \n references to self.vertices\n vertices:\n (n, (2|3)) list of vertices\n '''\n self.entities = np.array(entities)\n self.vertices = np.array(vertices)\n self.metadata = dict()\n\n if metadata.__class__.__name__ == 'dict':\n self.metadata.update(metadata)\n\n self._cache = {}\n\n def _cache_verify(self):\n ok = 'entity_count' in self._cache\n ok = ok and (len(self.entities) == self._cache['entity_count'])\n if not ok: \n self._cache = {'entity_count': len(self.entities)}\n self.process()\n\n def _cache_get(self, key):\n self._cache_verify()\n if key in self._cache: \n return self._cache[key]\n return None\n\n def _cache_put(self, key, value):\n self._cache_verify()\n self._cache[key] = value\n\n @property\n def paths(self):\n return self._cache_get('paths')\n\n @property\n def polygons(self):\n return self._cache_get('polygons')\n\n @property\n def root(self):\n return self._cache_get('root')\n\n @property\n def enclosure(self):\n return self._cache_get('enclosure')\n\n @property\n def discrete(self):\n return self._cache_get('discrete')\n\n def scale(self):\n return np.max(np.ptp(self.vertices, axis=0))\n \n def bounds(self):\n return np.vstack((np.min(self.vertices, axis=0),\n np.max(self.vertices, axis=0)))\n\n def box_size(self):\n return np.diff(self.bounds, axis=0)[0]\n \n def area(self):\n sum_area = 0.0\n for path_index in self.paths:\n sign = ((path_index in self.root)*2) - 1\n sum_area += (sign * self.polygons[path_index].area)\n return sum_area\n \n def transform(self, transform):\n self._cache = {}\n self.vertices = transform_points(self.vertices, transform)\n\n def rezero(self):\n self._cache = {}\n self.vertices -= self.vertices.min(axis=0)\n \n def merge_vertices(self):\n '''\n Merges vertices which are identical and replaces references\n '''\n unique, inverse = unique_rows(self.vertices, digits=TOL_MERGE_DIGITS)\n self.vertices = self.vertices[unique]\n for entity in self.entities: \n entity.points = inverse[entity.points]\n\n def replace_vertex_references(self, replacement_dict):\n for entity in self.entities: entity.rereference(replacement_dict)\n\n def remove_entities(self, entity_ids):\n '''\n Remove entities by their index.\n '''\n if len(entity_ids) == 0: return\n kept = np.setdiff1d(np.arange(len(self.entities)), entity_ids)\n self.entities = np.array(self.entities)[kept]\n\n def remove_duplicate_entities(self):\n entity_hashes = np.array([i.hash() for i in self.entities])\n unique, inverse = unique_rows(entity_hashes)\n if len(unique) != len(self.entities):\n self.entities = np.array(self.entities)[unique]\n\n def vertex_graph(self, return_closed=False):\n return vertex_graph(self.entities, return_closed)\n\n def generate_closed_paths(self):\n '''\n Paths are lists of entity indices.\n We first generate vertex paths using graph cycle algorithms, \n and then convert them to entity paths using \n a frankly worrying number of loops and conditionals...\n \n This will also change the ordering of entity.points in place, so that\n a path may be traversed without having to reverse the entity\n '''\n paths = generate_closed_paths(self.entities, self.vertices)\n self._cache_put('paths', paths)\n\n def referenced_vertices(self):\n referenced = deque()\n for entity in self.entities: \n referenced.extend(entity.points)\n return np.array(referenced)\n \n def remove_unreferenced_vertices(self):\n '''\n Removes all vertices which aren't used by an entity\n Reindexes vertices from zero, and replaces references\n '''\n referenced = self.referenced_vertices()\n unique_ref = np.int_(np.unique(referenced))\n replacement_dict = dict()\n replacement_dict.update(np.column_stack((unique_ref, \n np.arange(len(unique_ref)))))\n self.replace_vertex_references(replacement_dict)\n self.vertices = self.vertices[[unique_ref]] \n \n def discretize_path(self, path):\n '''\n Return a (n, dimension) list of vertices. \n Samples arcs/curves to be line segments\n '''\n discrete = discretize_path(self.entities, self.vertices, path)\n return discrete\n\n def to_dict(self):\n export_entities = [e.to_dict() for e in self.entities]\n export_object = {'entities' : export_entities, \n 'vertices' : self.vertices.tolist()}\n return export_object\n \n def process(self):\n tic = deque([time_function()])\n label = deque()\n for process_function in self.process_functions():\n process_function() \n tic.append(time_function())\n label.append(process_function.__name__)\n log.debug('%s processed %d entities in %0.4f seconds',\n self.__class__.__name__,\n len(self.entities),\n tic[-1] - tic[0])\n log.debug('%s', str(np.column_stack((label, np.diff(tic)))))\n return self\n\n def __add__(self, other):\n new_entities = deepcopy(other.entities)\n for entity in new_entities:\n entity.points += len(self.vertices)\n new_entities = np.append(deepcopy(self.entities), new_entities)\n \n new_vertices = np.vstack((self.vertices, other.vertices))\n new_meta = deepcopy(self.metadata)\n new_meta.update(other.metadata)\n\n new_path = self.__class__(entities = new_entities,\n vertices = new_vertices,\n metadata = new_meta)\n return new_path\n \nclass Path3D(Path):\n def process_functions(self): \n return [self.merge_vertices,\n self.remove_duplicate_entities,\n self.remove_unreferenced_vertices,\n self.generate_closed_paths,\n self.generate_discrete]\n \n def generate_discrete(self):\n discrete = list(map(self.discretize_path, self.paths))\n self._cache_put('discrete', discrete)\n\n def to_planar(self, normal=None, transform=None, check=True):\n '''\n Check to see if current vectors are all coplanar.\n \n If they are, return a Path2D and a transform which will \n transform the 2D representation back into 3 dimensions\n '''\n \n if transform is None:\n C, N = plane_fit(self.vertices)\n if normal is not None:\n N *= np.sign(np.dot(N, normal))\n to_planar = plane_transform(C,N)\n else:\n to_planar = transform\n\n vertices = transform_points(self.vertices, to_planar)\n \n if check and np.any(np.std(vertices[:,2]) > TOL_MERGE):\n raise NameError('Points aren\\'t planar!')\n \n vector = Path2D(entities = deepcopy(self.entities), \n vertices = vertices)\n to_3D = np.linalg.inv(to_planar)\n\n return vector, to_3D\n\n def show(self, entities=False):\n if entities: self.plot_entities(show=True)\n else: self.plot_discrete(show=True)\n\n def plot_discrete(self, show=False):\n import matplotlib.pyplot as plt\n from mpl_toolkits.mplot3d import Axes3D\n fig = plt.figure()\n axis = fig.add_subplot(111, projection='3d')\n for discrete in self.discrete:\n axis.plot(*discrete.T)\n if show: plt.show()\n\n def plot_entities(self, show=False):\n import matplotlib.pyplot as plt\n from mpl_toolkits.mplot3d import Axes3D\n fig = plt.figure()\n axis = fig.add_subplot(111, projection='3d')\n for entity in self.entities:\n vertices = self.vertices[entity.points]\n axis.plot(*vertices.T) \n if show: plt.show()\n\nclass Path2D(Path):\n def process_functions(self): \n return [self.merge_vertices,\n self.remove_duplicate_entities,\n self.generate_closed_paths,\n self.generate_discrete,\n self.generate_enclosure_tree]\n \n @property\n def body_count(self):\n return len(self.root)\n\n def generate_discrete(self):\n '''\n Turn a vector path consisting of entities of any type into polygons\n Uses shapely.geometry Polygons to populate self.polygons\n '''\n def path_to_polygon(path):\n discrete = discretize_path(self.entities, self.vertices, path)\n return Polygon(discrete)\n polygons = np.array(list(map(path_to_polygon, self.paths)))\n self._cache_put('polygons', polygons)\n\n def generate_enclosure_tree(self):\n root, enclosure = polygons_enclosure_tree(self.polygons)\n self._cache_put('root', root)\n self._cache_put('enclosure', enclosure.to_undirected())\n\n @property\n def polygons_full(self):\n cached = self._cache_get('polygons_full')\n if cached: return cached\n result = [None] * len(self.root)\n for index, root in enumerate(self.root):\n hole_index = self.connected_paths(root, include_self=False)\n holes = [p.exterior.coords for p in self.polygons[hole_index]]\n shell = self.polygons[root].exterior.coords\n result[index] = Polygon(shell = shell,\n holes = holes)\n self._cache_put('polygons_full', result)\n return result\n \n def connected_paths(self, path_id, include_self = False):\n if len(self.root) == 1:\n path_ids = np.arange(len(self.paths))\n else:\n path_ids = nx.node_connected_component(self.enclosure, path_id)\n if include_self: \n return np.array(path_ids)\n return np.setdiff1d(path_ids, [path_id])\n \n def simplify(self):\n self._cache = {}\n simplify(self)\n\n def split(self):\n '''\n If the current Path2D consists of n 'root' curves,\n split them into a list of n Path2D objects\n '''\n if len(self.root) == 1:\n return [deepcopy(self)]\n result = [None] * len(self.root)\n for i, root in enumerate(self.root):\n connected = self.connected_paths(root, include_self=True)\n new_root = np.nonzero(connected == root)[0]\n new_entities = deque()\n new_paths = deque()\n new_metadata = {'split_2D' : i}\n new_metadata.update(self.metadata)\n\n for path in self.paths[connected]:\n new_paths.append(np.arange(len(path)) + len(new_entities))\n new_entities.extend(path)\n \n result[i] = Path2D(entities = deepcopy(self.entities[new_entities]),\n vertices = deepcopy(self.vertices))\n result[i]._cache = {'entity_count' : len(new_entities),\n 'paths' : np.array(new_paths),\n 'polygons' : self.polygons[connected],\n 'metadata' : new_metadata,\n 'root' : new_root}\n return result\n\n def show(self):\n import matplotlib.pyplot as plt\n self.plot_discrete(show=True)\n \n def plot_discrete(self, show=False, transform=None):\n import matplotlib.pyplot as plt\n plt.axes().set_aspect('equal', 'datalim')\n def plot_transformed(vertices, color='g'):\n if transform is None: \n plt.plot(*vertices.T, color=color)\n else:\n transformed = transform_points(vertices, transform)\n plt.plot(*transformed.T, color=color)\n for i, polygon in enumerate(self.polygons):\n color = ['g','r'][i in self.root]\n plot_transformed(np.column_stack(polygon.boundary.xy), color=color)\n if show: plt.show()\n\n def plot_entities(self, show=False):\n import matplotlib.pyplot as plt\n plt.axes().set_aspect('equal', 'datalim')\n eformat = {'Line0': {'color':'g', 'linewidth':1}, \n 'Arc0': {'color':'r', 'linewidth':1}, \n 'Arc1': {'color':'b', 'linewidth':1}}\n for entity in self.entities:\n discrete = entity.discrete(self.vertices)\n e_key = entity.__class__.__name__ + str(int(entity.closed))\n plt.plot(discrete[:,0], \n discrete[:,1], \n **eformat[e_key])\n if show: plt.show()\n\n def identifier(self):\n polygons = self.polygons_full\n if len(polygons) != 1: \n raise NameError('Identifier only valid for single body')\n return [polygons[0].area, \n polygons[0].length, \n polygons[0].__hash__()*1e-5]\n\ndef vertex_graph(entities, return_closed=False):\n graph = nx.Graph()\n closed = deque()\n for index, entity in enumerate(entities):\n if return_closed and entity.closed: \n closed.append(index)\n else: \n graph.add_edges_from(entity.nodes(), \n entity_index = index)\n if return_closed:\n return graph, np.array(closed)\n return graph\n\ndef generate_closed_paths(entities, vertices):\n '''\n Paths are lists of entity indices.\n We first generate vertex paths using graph cycle algorithms, \n and then convert them to entity paths using \n a frankly worrying number of loops and conditionals...\n\n This will also change the ordering of entity.points in place, so that\n a path may be traversed without having to reverse the entity\n '''\n def entity_direction(a,b):\n if a[0] == b[0]: return 1\n elif a[0] == b[1]: return -1\n elif a[1] == b[1]: return 1\n elif a[1] == b[0]: return -1\n else: raise NameError('Can\\'t determine direction, noncontinous path!')\n\n graph, closed = vertex_graph(entities, return_closed=True)\n paths = deque() \n paths.extend(np.reshape(closed, (-1,1)))\n\n vertex_paths = np.array(nx.cycles.cycle_basis(graph))\n \n #all of the following is for converting vertex paths to entity paths\n for idx, vertex_path in enumerate(vertex_paths): \n #we have removed all closed entities, so paths MUST have more than 2 vertices\n if len(vertex_path) < 2: continue\n # vertex path contains 'nodes', which are always on the path,\n # regardless of entity type. \n # this is essentially a very coarsely discretized polygon\n # thus it is valid to compute if the path is counter-clockwise on these\n # vertices relatively cheaply, and reverse the path if it is clockwise\n ccw_dir = is_ccw(vertices[[np.append(vertex_path, vertex_path[0])]])*2 - 1\n current_entity_path = deque()\n\n for i in range(len(vertex_path)+1):\n path_pos = np.mod(np.arange(2) + i, len(vertex_path))\n vertex_index = np.array(vertex_path)[[path_pos]]\n entity_index = graph.get_edge_data(*vertex_index)['entity_index']\n if ((len(current_entity_path) == 0) or \n ((current_entity_path[-1] != entity_index) and \n (current_entity_path[0] != entity_index))):\n entity = entities[entity_index]\n endpoints = entity.end_points() \n direction = entity_direction(vertex_index, endpoints) * ccw_dir\n current_entity_path.append(entity_index)\n entity.points = entity.points[::direction]\n paths.append(list(current_entity_path)[::ccw_dir])\n paths = np.array(paths)\n return paths\n\ndef discretize_path(entities, vertices, path):\n '''\n Return a (n, dimension) list of vertices. \n Samples arcs/curves to be line segments\n '''\n pathlen = len(path)\n if pathlen == 0: raise NameError('Cannot discretize empty path!')\n if pathlen == 1: return np.array(entities[path[0]].discrete(vertices))\n discrete = deque()\n for i, entity_id in enumerate(path):\n last = (i == (pathlen - 1))\n current = entities[entity_id].discrete(vertices)\n slice = (int(last) * len(current)) + (int(not last) * -1)\n discrete.extend(current[:slice])\n return np.array(discrete) \n","sub_path":"trimesh/path/path.py","file_name":"path.py","file_ext":"py","file_size_in_byte":17692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"58630600","text":"# 2015.02.05 17:20:02 IST\nfrom onep.core.util.Enum import enum\n\nclass RouteOperation(object):\n \"\"\"\n This abstract class is the parent class of L3UnicastRouteOperation and \n in the future for L3MulticastRouteOperation, L2UnicastRouteOperation,\n L2MulticastRouteOperation, etc.\n \n This class represents the operation to be performed on a route.\n \"\"\"\n\n _op_type = int()\n RouteOperationType = enum('ADD', 'REMOVE', 'REPLACE')\n\n def __init__(self, opType):\n \"\"\"\n Constructor\n \n @param opType: The operation type.\n @type opType: L{Enum}\n \"\"\"\n super(RouteOperation, self).__init__()\n self._op_type = opType\n\n\n\n def _get_op_type(self):\n return self._op_type\n\n\n _doc = 'The operation type.\\n @type: L{Enum}\\n '\n op_type = property(_get_op_type, None, None, _doc)\n\n\n# decompiled 1 files: 1 okay, 0 failed, 0 verify failed\n# 2015.02.05 17:20:02 IST\n","sub_path":"onepk_without_pyc/build/lib.linux-x86_64-2.7/onep/routing/RouteOperation.py","file_name":"RouteOperation.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"377090697","text":"# Tic Tac Toe par Nouguier Clément, Romain Scohy et Gaël Foppolo\n\nimport random\n\n# Fonction d'affichage des instructions\n#\n# données : aucune\n# résultats : les instructions qui expliquent le fonctionnement du programme\n# stratégie : on appelle cette fonction uniquement au premier lancement du programme\n\ndef instructions():\n print (\"Bienvenue sur le plus grand challenge de tout les temps : le Tic-Tac-Toe.\\n\")\n print (\"Principe du jeu :\")\n print (\"Vous allez vous affronter sur un plateau de 3x3 cases.\")\n print (\"A chaque tour vous devez remplir une case de la grille, avec le symbole qui vous a été attribué en début de partie.\")\n print (\"La partie est gagnée quand un des joueurs a réussi à aligner 3 symboles de façon horizontale, verticale ou en diagonale.\")\n print (\"Deux modes possible : un contre un ou contre l'ordinateur.\\n\")\n print (\"Vous ferez votre placement en entrant un nombre, 1 - 9. Le nombre correspond à la case du tableau comme illustré :\\n\")\n print (\" 7 | 8 | 9\")\n print (\" -----------\")\n print (\" 4 | 5 | 6\")\n print (\" -----------\")\n print (\" 1 | 2 | 3\\n\")\n print (\"Préparez-vous, humains. L'utltime combat va commencer.\\n\")\n return()\n\n# Fonction d'affichage du plateau de jeu\n#\n# données : le numéro de la case si case vide, sinon X ou O\n# résultats : les instructions qui expliquent le fonctionnement du programme\n# stratégie : on appelle cette fonction avant de demander le placement d'un pion, pour que le joueur est un meilleure visibilité du plateau\n\ndef plateauDeJeu():\n print (\"\")\n print (\" %s | %s | %s\" % (plateau[6],plateau[7],plateau[8]))\n print (\" -----------\")\n print (\" %s | %s | %s\" % (plateau[3],plateau[4],plateau[5]))\n print (\" -----------\")\n print (\" %s | %s | %s\" % (plateau[0],plateau[1],plateau[2]))\n print (\"\")\n return()\n\n# Fonction de vérification \"placement gagnant\"\n#\n# données : la variable test (soit X, soit O) et le tableau \"plateau\"\n# résultats : si coup gagant, on retourne vrai sinon on retourne faux\n# stratégie : on compare pour chaque colonne (3), chaque ligne (3) et chaque diagonale (2)\n# si les trois valeurs du tableau sont égales à la variable test. Si c'est le cas on retourne vrai, sinon on retourne faux.\n# On appelle cette fonction après le placement d'un pion pour vérifier si celui-ci fait gagner la partie ou non.\n\ndef fini(test):\n if plateau[0] == test and plateau[1] == test and plateau[2] == test:\n return (True)\n if plateau[3] == test and plateau[4] == test and plateau[5] == test:\n return (True)\n if plateau[6] == test and plateau[7] == test and plateau[8] == test:\n return (True)\n if plateau[0] == test and plateau[3] == test and plateau[6] == test:\n return (True)\n if plateau[1] == test and plateau[4] == test and plateau[7] == test:\n return (True)\n if plateau[2] == test and plateau[5] == test and plateau[8] == test:\n return (True)\n if plateau[0] == test and plateau[4] == test and plateau[8] == test:\n return (True)\n if plateau[6] == test and plateau[4] == test and plateau[2] == test:\n return (True)\n return (False)\n\n# Programme\n\ninstructions() # Affichage des instructions\nscoreJ1 = 0 # Initialisation des compteurs du score pour les deux joueurs \nscoreJ2 = 0\njeu = True \nplateau = [\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\"] # Création du tableau \"plateau\" avec les cases pré-remplies par les numéros (attention, on va de la case 0 à 8 mais contenant de 1 à 9)\njoueur1 = input(\"Nom du joueur 1 ? \") \njoueur2 = input(\"Nom du joueur 2 ? (tapez 'ordinateur' pour jouer contre l'ordinateur) \")\n\nwhile (jeu == True): # Tant que ce booléen est vrai le jeu continue\n plateau = [\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\"] # Création du tableau \"plateau\" avec les cases pré-remplies par les numéros car si ce n'est pas la première partie, il y aura encore le tableau de la partie précédente\n tour = 0 # Intialisation du compteur de tours\n tourJoueur = random.randint(0,1) # Intialisation de cette variable qui sert pour déterminer le tour du joueur. Si 1, c'est au joueur 1, si 0 c'est au joueur 20. Choisis au hasard 0 ou 1 pour que ce ne soit pas toujours le même qui commence la partie.\n gagner = False # Intialisation à False (normal, on a pas encore commencer :p)\n while (tour < 9): # Comme il n'y a que 9 cases, il ne peut y avoir que 9 tours maximum. Quand on arrive à 9, on renvoie à l'égalité.\n plateauDeJeu() \n if tourJoueur == 1: \n placement = input(\"Votre placement %s ? \" % (joueur1)) \n if plateau[(int(placement)-1)] == placement: # Comparaison de la valeur rentrée par l'utilisateur et celle du numéro -1 (car on commence à 0 et non pas à 1) de la case du tableau (exemple : pour 5 rentrée on compare au contenue de la case 5-1=4). Si égal, on rentre dans la boucle sinon on redemande la placement au joueur.\n plateau[(int(placement)-1)] = \"X\" # Placement de la croix dans la case du tableau demandée\n if fini(\"X\"): # On vérifie si on a effectué un coup gagnant en appelant la fonction fini\n gagner = True # Si c'est le cas, on affecte vrai à gagner (sans blague :p)\n gagnant = joueur1 # Le gagnant est le joueur 1\n scoreJ1 = scoreJ1+1 # Et on incrément son score de 1\n break # On sort de la boucle\n tourJoueur = 0 # Sinon, si ce n'est pas un coup gagant, on change le tour pour que ce soit au joueur 2\n tour = tour+1 # Et on incrémente de 1 le compteur de tour\n else:\n print (\"La case est déjà prise\") # Message si la case est déjà prise. On revient au if.\n else: # Si tourJoueur est différent de 1\n if joueur2.lower() == \"ordinateur\": # Si on a choisit de jouer contre l'ordinateur\n placement = str(random.randrange(1,9)) # Le placement se fait au hasard\n print (\"Le placement de l'ordinateur est %s \" % (placement)) \n else: # Sinon on joue contre le joueur 2, même code que pour le joueur 1\n placement = input(\"Votre placement %s ? \" % (joueur2))\n if plateau[(int(placement)-1)] == placement:\n plateau[(int(placement)-1)] = \"0\"\n if fini(\"0\"):\n gagner = True\n gagnant = joueur2\n scoreJ2 = scoreJ2+1\n break\n tourJoueur = 1\n tour = tour+1\n else:\n print (\"La case est déjà prise\")\n if gagner: # Si gagner, on affiche le nom du gagant et les scores\n print (\"Bravo %s, tu as gagné la partie !\" % gagnant)\n print (\"Le score est de \",scoreJ1,\" pour \",joueur1,\"et de\",scoreJ2,\" pour\",joueur2,)\n else: # Sinon (égalitée), on affiche un pat et les scores\n print (\"Damn %s, la partie avec %s est un pat...\" % (joueur1,joueur2))\n print (\"Le score est de \",scoreJ1,\" pour \",joueur1,\"et de\",scoreJ2,\" pour\",joueur2,)\n \n if input(\"Voulez-vous jouez encore ? (O ou N) \").lower() == 'n': # On demande si les joueurs veulent continuer la partie\n jeu = False # Un refus signifie une affectation False à jeu, c'est à dire la fin du programme\n \nprint (\"Au revoir !\")\n","sub_path":"final_projet.py","file_name":"final_projet.py","file_ext":"py","file_size_in_byte":9698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"391161432","text":"#!/usr/bin/env python3\n\nimport sfml as sf\nfrom newback import Background\nfrom particle import Particle\nfrom goal import Goal\nimport random\nimport math\nimport colorsys\n\nclass Startup():\n\n def __init__(self):\n self.window = sf.RenderWindow(sf.VideoMode(800,600), \"NotDoodleJump\")\n self.window.framerate_limit=60\n try: \n self.font = sf.Font.from_file(\"Ubuntu-R.ttf\")\n self.ground1 = sf.Texture.from_file(\"images/ground1.png\")\n self.plattform = sf.Texture.from_file(\"images/plattform.png\")\n self.goal_texture = sf.Texture.from_file(\"images/goal.png\")\n except IOError: exit(1)\n self._goal = Goal()\n \tself.goal = sf.Sprite(self.goal_texture)\n self.colors = [sf.Color(255,0,0),sf.Color(255,128,0),sf.Color(255,255,0),sf.Color(128,255,0),sf.Color(0,255,0),sf.Color(0,255,128),sf.Color(0,255,255),sf.Color(0,128,255),sf.Color(0,0,255)]\n self._background = Background(self.window,self.colors)\n self.backhsv = 340\n self.spawnpoint = sf.Vector2(400,390)\n self.dead = False\n self.deadcount = 0\n self.points = 0\n self.higth = 0\n self.deadcounttext = sf.Text(\"death \" + str(self.deadcount) + \"\\n\" + \"points \" + str(self.points) + \"\\n\" + \"higth \" + str(self.higth))\n self.deadcounttext.font = self.font\n self.deadcounttext.character_size = 15\n self.deadcounttext.position = (0,0)\n self.deadcounttext.style = sf.Text.BOLD\n self.deadcounttext.color = sf.Color.BLACK\n self.respawntime = sf.Clock()\n self.respawntext = sf.Text(\"BLA\")\n self.respawntext.font = self.font\n self.respawntext.character_size = 60\n self.respawntext.position = (250,250)\n self.respawntext.style = sf.Text.BOLD\n self.respawntext.color = sf.Color.BLACK\n self.goal_placed = False\n \n self.level = []\n self.ground = sf.Sprite(self.ground1)\n self.ground.position = sf.Vector2(-1000, 0)\n self.level.append(self.ground)\n\n self.rec = sf.RectangleShape()\n self.rec.position = self.spawnpoint\n self.x , self.y = self.rec.position\n self.rec.size = (20,20)\n self.rec.fill_color = sf.Color.RED\n self.keysDown = { 0: False, 3: False, 15: False, 17: False, 18: False, 22: False, 57: False }\n self.jump_speed = 8\n self.gravity = .5\n self.move_speed = 4\n self.in_air = True\n self.jumping = False\n self.falling = False\n self.power = False\n self.powercost = 500\n self.coll = sf.Rectangle(self.rec.position, self.rec.size)\n self.ex_particle = []\n self.point_factor = 0\n \n self.rainbow = []\n self.colorpos = 0\n self.high = 1000\n\n \n \n \n\n \n \n\n\n def handlePressedKeys(self):\n if self.keysDown[0]:\n self.rec.position -= (self.move_speed, 0)\n if self.keysDown[3]:\n self.rec.position += (self.move_speed, 0)\n if self.keysDown[17]:\n \tself.__init__()\n \tself.run()\n if self.keysDown[15] and self.points >= self.powercost and not self.power:\n self.jump_speed=16\n self.points = int(self.points - self.powercost)\n self.power = True\n self.in_air = True\n self.jumping = True\n if self.keysDown[22] or self.keysDown[57]:\n self.in_air = True\n self.jumping = True\n if self.in_air:\n if self.jumping:\n self.rec.position -= (0, self.jump_speed)\n self.jump_speed -= self.gravity\n else:\n self.rec.position += (0, 8 * self.gravity)\n if self.rec.position.y < 300:\n self.moveScreen()\n if self.rec.position.x < 0:\n self.rec.position = (800,self.rec.position.y)\n if self.rec.position.x > 800:\n self.rec.position = (0,self.rec.position.y)\n if self.rec.position.y > 600:\n self.explode()\n self.jump_speed = 8\n self.in_air = False\n self.jumping = False\n self.falling = False\n self.power = False\n self.coll.position = self.rec.position\n \n\n def moveScreen(self):\n plattform1 = sf.Sprite(self.plattform)\n plattform2 = sf.Sprite(self.plattform)\n middlelist = [175,350,525] \n middle = middlelist[random.randint(0,2)]\n plattform1.position = sf.Vector2(random.randint(0,middle),-50)\n plattform2.position = sf.Vector2(random.randint(middle+100,700),-50)\n self.level.append(plattform1)\n self.level.append(plattform2)\n if self.higth > 20000 and not self.goal_placed:\n \tp = random.randint(0,600)\n \tif p > 500:\n \t\tself.goal.position = sf.Vector2(random.randint(0,620),-50)\n \t\tself.goal_placed = True\n if self.goal_placed and self.goal.position.y > 600:\n \tself.goal_placed = False\n for x in self.level:\n x.position += sf.Vector2(0,75)\n self.rec.position += sf.Vector2(0,75)\n self.goal.position += sf.Vector2(0,75)\n self.high += 75\n for x in self.rainbow:\n x.position += sf.Vector2(0,75)\n self.backhsv = (self.backhsv - 5) %359\n self.points +=int(100*(1-(1/20*(self.point_factor)))*(1+self.higth/1000))\n self.higth += 75\n if self.higth >1000: self.powercost = self.higth/2\n self.deadcounttext.string = \"death \" + str(self.deadcount) + \"\\n\" + \"points \" + str(self.points) + \"\\n\" + \"higth \" + str(self.higth)\n \n\n def groundPlayer(self):\n self.keysDown[22] = False\n self.keysDown[57] = False\n self.keysDown[15] = False\n self.in_air = False\n self.jumping = False\n self.falling = False\n self.power = False\n self.jump_speed = 8\n if (self.rec.position.y - self.high) > 150:\n self.explode()\n self.high = self.rec.position.y\n\n def collision(self,objekt):\n inter = self.coll.intersects(objekt)\n if inter and (inter.width > (self.coll.width / 10)):\n if (self.coll.bottom - objekt.top) > 1 and (self.coll.bottom - objekt.top) < objekt.size.y:\n return \"bottom\"\n if (objekt.bottom - self.coll.top) > 1 and (objekt.bottom - self.coll.top) < objekt.size.y:\n return \"top\"\n \n \n\n # def collision(self,objekt):\n # if self.coll.bottom > objekt.top and ((self.coll.left > objekt.left and self.coll.left < objekt.right) or (self.coll.right > objekt.left and self.coll.right < objekt.right)):\n # return True\n\n\n\n def explode(self):\n x,y=self.rec.position\n self.dead = True\n self.respawntime.restart()\n self.rainbow = []\n self.deadcount +=1\n if self.deadcount < 21: self.point_factor = self.deadcount\n self.deadcounttext.string = \"death \" + str(self.deadcount) + \"\\n\" + \"points \" + str(self.points) + \"\\n\" + \"higth \" + str(self.higth)\n for n in range(150):\n particle = Particle(x, y, 10, self.colors[random.randint(0,8)])\n particle.speed = 5\n particle.angle = (n*10)%359\n self.ex_particle.append(particle)\n\n\n\n def run(self):\n for x in range(7):\n self.moveScreen()\n self.rec.position = self.spawnpoint\n self.points = 0\n self.higth = 0\n self.deadcounttext.string = \"death \" + str(self.deadcount) + \"\\n\" + \"points \" + str(self.points) + \"\\n\" + \"higth \" + str(self.higth)\n while self.window.is_open:\n for event in self.window.events:\n if type(event) is sf.CloseEvent:\n self.window.close()\n elif type(event) is sf.KeyEvent and event.code in self.keysDown and event.pressed and not self.keysDown[event.code]:\n self.keysDown[event.code] = True\n elif type(event) is sf.KeyEvent and event.code in self.keysDown and event.released and event.code is not sf.Keyboard.SPACE and event.code is not sf.Keyboard.W and event.code is not sf.Keyboard.P:\n self.keysDown[event.code] = False\n\n \n if not self.dead:\n\n\n self.handlePressedKeys()\n\n for x in self.level:\n side = self.collision(x.global_bounds)\n if side == \"bottom\" and self.in_air:\n self.rec.position = (self.rec.position.x,x.global_bounds.top-20)\n self.coll.position = self.rec.position\n self.groundPlayer()\n elif side == \"top\" and self.in_air:\n self.jumping = False\n self.jump_speed = 0\n self.rec.position = (self.rec.position.x,x.global_bounds.bottom+1)\n else:\n self.in_air = True\n\n \n rainbow = sf.RectangleShape()\n rainbow.fill_color = self.colors[self.colorpos]\n self.colorpos = (self.colorpos +1) %8\n rainbow.position = self.rec.position\n rainbow.size = self.rec.size\n if len(self.rainbow) > 35:\n self.rainbow.pop(0)\n if (self.rec.position.y > self.rainbow[30].position.y) and (self.rainbow[30].position.y < self.rainbow[27].position.y):\n self.high = self.rec.position.y\n\n self.rainbow.append(rainbow)\n\n\n if self.dead and self.respawntime.elapsed_time.seconds >= 5:\n self.dead = False\n self.ex_particle = []\n self.rainbow = []\n self.rec.position = sf.Vector2(random.randint(100,700),random.randint(350,400))\n\n #self.window.clear(self.colors[(self.colorpos%2)*4])\n self.bcr,self.bcg,self.bcb = colorsys.hsv_to_rgb(self.backhsv/360,1.,1.)\n self.backcolor = sf.Color(self.bcr*255,self.bcg*255,self.bcb*255)\n self.window.clear(self.backcolor)\n self._background.draw(self.window)\n for x in self.level:\n self.window.draw(x)\n if self.goal_placed:\n \tself.window.draw(self.goal)\n \tif self._goal.reached(self.coll, self.goal.position):\n \t\tself.respawntext.string = \"Congratulations\\n\"\n \t\tself.window.draw(self.respawntext)\n if not self.dead:\n #self.window.draw(self.rec)\n for y in self.rainbow:\n self.window.draw(y)\n \n for particle in self.ex_particle:\n particle.move()\n particle.bounce(self.window)\n particle.display(self.window)\n if self.dead:\n self.respawntext.string = \"CONTINUE\\n \" + str(5-int(self.respawntime.elapsed_time.seconds))\n self.window.draw(self.respawntext)\n for x in self.keysDown:\n self.keysDown[x] = False\n \n \n\n\n self.window.draw(self.deadcounttext)\n self.window.display()\n\nStartup().run()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"25194375","text":"# https://www.hackerrank.com/challenges/alphabet-rangoli/problem?isFullScreen=true\r\n\r\n# Input Format\r\n# Only one line of input containing N, the size of the rangoli.\r\n\r\n# Constraints\r\n# 0 < N < 27\r\n\r\n# Output Format\r\n# Print the alphabet rangoli in the format explained above.\r\n\r\n# Sample Input\r\n# 5\r\n\r\n# Sample Output\r\n# --------e--------\r\n# ------e-d-e------\r\n# ----e-d-c-d-e----\r\n# --e-d-c-b-c-d-e--\r\n# e-d-c-b-a-b-c-d-e\r\n# --e-d-c-b-c-d-e--\r\n# ----e-d-c-d-e----\r\n# ------e-d-e------\r\n# --------e--------\r\n\r\n\r\ndef print_rangoli(size):\r\n # your code goes here\r\n\r\n alphabets = \"abcdefghijklmnopqrstuvwxyz\"\r\n maxLength = (size*2-1) + (size-1)*2\r\n #eqn for max length\r\n #(3*2-1) + (3-1)*2 # 5+4=9\r\n #(10*2-1) + (10-1)*2 #19+18=37\r\n \r\n rangoliList = []\r\n\r\n### slicing version(shorter)\r\n for _ in range(size):\r\n rangoli = \"-\".join(alphabets[_:size])\r\n rangoliList.append((rangoli[::-1] + rangoli[1:]).center(maxLength,\"-\"))\r\n\r\n print(\"\\n\".join(rangoliList[::-1]+rangoliList[1:]))\r\n\r\n### slicing version\r\n # print first half\r\n # for _ in range(size-1, 0, -1):\r\n # rangoli = \"-\".join(alphabets[_:size])\r\n # print((rangoli[::-1] + rangoli[1:]).center(maxLength,\"-\"))\r\n \r\n # print second half\r\n # for _ in range(size):\r\n # rangoli = \"-\".join(alphabets[_:size])\r\n # print((rangoli[::-1] + rangoli[1:]).center(maxLength,\"-\"))\r\n\r\n### initial version\r\n # print first half\r\n # for _ in range(size):\r\n # rangoli = \"\"\r\n # for bits in range(_+1):\r\n # rangoli += alphabets[size - 1 - bits]\r\n # if bits+1 == maxLength:\r\n # break\r\n # rangoli += \"-\" \r\n # for bits in range(_, 0, -1):\r\n # rangoli += alphabets[size - bits]\r\n # if bits == 1:\r\n # break\r\n # rangoli += \"-\"\r\n # print(rangoli.center(maxLength,\"-\"))\r\n \r\n # print second half \r\n # for _ in range(size-1, 0, -1):\r\n # rangoli = \"\"\r\n # for bits in range(_):\r\n # rangoli += alphabets[size - 1 - bits]\r\n # rangoli += \"-\"\r\n # for bits in range(_-1, 0, -1):\r\n # rangoli += alphabets[size - bits]\r\n # if bits == 1:\r\n # break\r\n # rangoli += \"-\"\r\n\r\n # print(rangoli.center(maxLength,\"-\"))\r\n\r\nif __name__ == '__main__':\r\n n = int(input())\r\n print_rangoli(n)","sub_path":"0_reference/Hackerrank/Practice Python/Strings/Alphabet Rangoli.py","file_name":"Alphabet Rangoli.py","file_ext":"py","file_size_in_byte":2432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"310772374","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\nimport numpy as np\nimport pandas as pd\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.utils import to_categorical\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\n\nimport sklearn.metrics\nimport gc\n\nNB_SAMPLES = 1500000\n\n# In[2]:\n\ntrain = pd.read_csv('../input/train.csv')\ntest = pd.read_csv('../input/test.csv')\n\n\n# In[3]:\n\nprint ('The train data has {} rows and {} columns'.format(train.shape[0],train.shape[1]))\nprint ('The test data has {} rows and {} columns'.format(test.shape[0],test.shape[1]))\n\n\n# In[4]:\n\ntrain.head()\n\n\n# In[5]:\n\n# imputing missing values\ntrain['siteid'].fillna(-999, inplace=True)\ntest['siteid'].fillna(-999, inplace=True)\n\ntrain['browserid'].fillna(\"None\",inplace=True)\ntest['browserid'].fillna(\"None\", inplace=True)\n\ntrain['devid'].fillna(\"None\",inplace=True)\ntest['devid'].fillna(\"None\",inplace=True)\n\n\n# In[7]:\n\n# create timebased features\n\ntrain['datetime'] = pd.to_datetime(train['datetime'])\ntest['datetime'] = pd.to_datetime(test['datetime'])\n\ntrain['tweekday'] = train['datetime'].dt.weekday\ntest['tweekday'] = test['datetime'].dt.weekday\n\ntrain['thour'] = train['datetime'].dt.hour\ntest['thour'] = test['datetime'].dt.hour\n\ntrain['tminute'] = train['datetime'].dt.minute\ntest['tminute'] = test['datetime'].dt.minute\n\n\n# In[141]:\n\n# create aggregate features\nsite_offer_count = train.groupby(['siteid','offerid']).size().reset_index()\nsite_offer_count.columns = ['siteid','offerid','site_offer_count']\n\nsite_offer_count_test = test.groupby(['siteid','offerid']).size().reset_index()\nsite_offer_count_test.columns = ['siteid','offerid','site_offer_count']\n\nsite_cat_count = train.groupby(['siteid','category']).size().reset_index()\nsite_cat_count.columns = ['siteid','category','site_cat_count']\n\nsite_cat_count_test = test.groupby(['siteid','category']).size().reset_index()\nsite_cat_count_test.columns = ['siteid','category','site_cat_count']\n\nsite_mcht_count = train.groupby(['siteid','merchant']).size().reset_index()\nsite_mcht_count.columns = ['siteid','merchant','site_mcht_count']\n\nsite_mcht_count_test = test.groupby(['siteid','merchant']).size().reset_index()\nsite_mcht_count_test.columns = ['siteid','merchant','site_mcht_count']\n\n\n# In[158]:\n\n# joining all files\nagg_df = [site_offer_count,site_cat_count,site_mcht_count]\nagg_df_test = [site_offer_count_test,site_cat_count_test,site_mcht_count_test]\n\nfor x in agg_df:\n train = train.merge(x)\n \nfor x in agg_df_test:\n test = test.merge(x)\n\n\n# In[28]:\n\n# Label Encoding\nfrom sklearn.preprocessing import LabelEncoder\nfor c in list(train.select_dtypes(include=['object']).columns):\n if c != 'ID':\n lbl = LabelEncoder()\n lbl.fit(list(train[c].values) + list(test[c].values))\n train[c] = lbl.transform(list(train[c].values))\n test[c] = lbl.transform(list(test[c].values)) \n\n\n# In[163]:\n\n# sample 10% data - to avoid memory troubles\n# if you have access to large machines, you can use more data for training\n\nprint('Selecting random {} samples'.format(NB_SAMPLES))\nrows = np.random.choice(train.index.values, NB_SAMPLES)\nsampled_train = train.loc[rows]\n\n\n# In[164]:\n\n# select columns to choose\ncols_to_use = [x for x in sampled_train.columns if x not in list(['ID','datetime','click'])]\n\n\n# In[165]:\n\n# standarise data before training\nscaler = StandardScaler().fit(sampled_train[cols_to_use])\n\nstrain = scaler.transform(sampled_train[cols_to_use])\nstest = scaler.transform(test[cols_to_use])\n\n\n# In[167]:\n\n# train validation split\nX_train, X_valid, Y_train, Y_valid = train_test_split(strain, sampled_train.click, test_size = 0.5, random_state=2017)\n\n\n# In[168]:\n\nprint (X_train.shape)\nprint (X_valid.shape)\nprint (Y_train.shape)\nprint (Y_valid.shape)\n\n\n# In[169]:\n\n# model architechture\ndef keras_model(train):\n \n input_dim = train.shape[1]\n classes = 2\n \n model = Sequential()\n model.add(Dense(100, activation = 'relu', input_shape = (input_dim,))) #layer 1\n model.add(Dense(30, activation = 'relu')) #layer 2\n model.add(Dense(classes, activation = 'sigmoid')) #output\n model.compile(optimizer = 'adam', loss='binary_crossentropy',metrics = ['accuracy'])\n\n print(model.summary)\n\n return model\n\n# ### Now, let's understand the architechture of this neural network:\n# \n# 1. We have 13 input features. \n# 2. We connect these 13 features with 100 neurons in the first hidden layer (call layer 1).\n# 3. Visualise in mind this way: The lines connecting input to neurons are assigned a weight (randomly assigned).\n# 4. The neurons in layer 1 receive a weighted sum (bias + woxo + w1x1...) of inputs while passing through `relu` activation function.\n# 5. Relu works this way: If the value of weighted sum is less than zero, it sets it to 0, if the value of weighted sum of positive, it considers the value as is.\n# 6. The output from layer 1 is input to layer 2 which has 30 neurons. Again, the input passes through `relu` activation function. \n# 7. Finally, the output of layer 2 is fed into the final layer which has 2 neurons. The output passes through `sigmoid` function. `Sigmoid` functions makes sure that probabilities stays within 0 and 1 and we get the output predictions.\n\n# In[171]:\n\n# one hot target columns\nY_train = to_categorical(Y_train)\nY_valid = to_categorical(Y_valid)\n\nids = np.copy(test.ID.values)\n\ndel sampled_train\ndel train\ndel test\ngc.collect()\n\n# In[173]:\n\nearly_stopping = EarlyStopping(monitor='val_loss', patience=30, verbose=1, mode='auto')\n\nmodel_checkpoint = ModelCheckpoint('../data/nn.model', monitor='val_loss',\n verbose=1, save_best_only=True, mode='auto')\n\n# train model\nmodel = keras_model(X_train)\nmodel.fit(X_train,\n Y_train,\n batch_size=1000,\n epochs=500,\n callbacks=[early_stopping,model_checkpoint],\n validation_data=(X_valid, Y_valid),\n shuffle=True)\n\nmodel.load_weights('../data/nn.model')\n\n# In[177]:\n\n# check validation accuracy\nvpreds = model.predict_proba(X_valid)[:,1]\ntest_loss = sklearn.metrics.log_loss( y_true=Y_valid[:,1], y_pred=vpreds)\ntest_aucroc = sklearn.metrics.roc_auc_score(y_true = Y_valid[:,1], y_score=vpreds)\nprint('\\ntest_logloss={} test_aucroc={}'.format(test_loss,test_aucroc))\n\n# In[178]:\n\n# predict on test data\ntest_preds = model.predict_proba(stest)[:,1]\n\n\n# In[180]:\n\n# create submission file\nsubmit = pd.DataFrame({'ID':ids, 'click':test_preds})\nsubmit.to_csv('../submissions/nn_loss={:<7.5f}_aucroc={:<7.5f}.csv'.format(test_loss,test_aucroc), index=False)\n\n\n# In[ ]:\n\n\n\n","sub_path":"3/nn0.py","file_name":"nn0.py","file_ext":"py","file_size_in_byte":6710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"296555441","text":"from django.urls import path,re_path\n\nfrom authorize import views\n\n\nurlpatterns = [\n re_path('^hrule/list', views.auth_index,name='auth_list'),\n re_path('^hrule/add', views.auth_add,name='hrule_add'),\n re_path('^hrule/edit/(?P[\\w|\\-]+)/', views.auth_edit,name='hrule_edit'),\n re_path('^hrule/del/', views.auth_del,name='hrule_del'),\n\n re_path('^hrule/authorize/(?P[\\w|\\-]+)/',views.auth_group_authorize,name='hrule_authorize'),\n\n re_path('^arule/index$',views.arule_index,name='arule_index'), # 主机授权首页\n\n re_path('^arule/ugrant/list/$',views.arule_user_grant_list,name='arule_user_grant_list'), # 用户授权列表\n re_path('^arule/ugrant/edit/(?P[\\w|\\-]+)/$',views.arule_user_grant,name='arule_user_grant_edit'), # 用户授权详情\n\n re_path('^arule/dgrant/list/$',views.arule_depart_grant_list,name='arule_depart_grant_list'), # 用户授权列表'\n re_path('^arule/dgrant/edit/(?P[\\w|\\-]+)/$',views.arule_depart_grant_edit,name='arule_depart_grant_edit'), # 用户授权列表'\n\n\n\n\n\n\n\n]\n\n","sub_path":"authorize/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"310259444","text":"import datetime\nimport os\nimport json\n\nfrom flask import Flask, jsonify, abort, render_template, send_from_directory\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_migrate import Migrate\n\nfrom sqlalchemy.orm import joinedload\n\nfrom sqlalchemy.sql import func\nfrom elasticapm.contrib.flask import ElasticAPM\n\nfrom logging.config import dictConfig\n\ndictConfig({\n 'version': 1,\n 'formatters': {'default': {\n 'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',\n }},\n 'handlers': {'wsgi': {\n 'class': 'logging.StreamHandler',\n 'stream': 'ext://flask.logging.wsgi_errors_stream',\n 'formatter': 'default'\n }},\n 'root': {\n 'level': 'INFO',\n 'handlers': ['wsgi']\n }\n})\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\n\nSQLITE_DB_PATH = 'sqlite:///' + os.path.abspath(os.path.join(BASE_DIR, 'demo', 'db.sql'))\n\n\napp = Flask(__name__, static_folder=os.path.join(\"opbeans\", \"static\", \"build\" ,\"static\"), template_folder=\"templates\")\napp.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL', SQLITE_DB_PATH)\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\napp.config['ELASTIC_APM'] = {\n 'SERVICE_NAME': os.environ.get('ELASTIC_APM_SERVICE_NAME', 'opbeans-flask'),\n 'SERVER_URL': os.environ.get('ELASTIC_APM_SERVER_URL', 'http://localhost:8200'),\n 'SERVER_TIMEOUT': \"10s\",\n 'DEBUG': True,\n}\n\ndb = SQLAlchemy(app)\nmigrate = Migrate(app, db)\napm = ElasticAPM(app)\n\n#tracing = FlaskTracing(opentracing_tracer, trace_all_requests=True, app=app)\n\n\nclass Customer(db.Model):\n __tablename__ = 'opbeans_flask_customer'\n id = db.Column(db.Integer, primary_key=True)\n full_name = db.Column(db.String(1000))\n company_name = db.Column(db.String(1000))\n email = db.Column(db.String(1000))\n address = db.Column(db.String(1000))\n postal_code = db.Column(db.String(1000))\n city = db.Column(db.String(1000))\n country = db.Column(db.String(1000))\n\n\nclass Order(db.Model):\n __tablename__ = 'opbeans_flask_order'\n id = db.Column(db.Integer, primary_key=True)\n customer_id = db.Column(db.Integer, db.ForeignKey('opbeans_flask_customer.id'), nullable=False)\n customer = db.relationship('Customer', backref=db.backref(\"opbeans_order\", lazy=True))\n created_at = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow)\n products = db.relationship('Product', secondary='opbeans_flask_orderline')\n\n\nclass ProductType(db.Model):\n __tablename__ = 'opbeans_flask_producttype'\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(1000), unique=True)\n\n def __str__(self):\n return self.name\n\n\nclass Product(db.Model):\n __tablename__ = 'opbeans_flask_product'\n id = db.Column(db.Integer, primary_key=True)\n sku = db.Column(db.String(1000), unique=True)\n name = db.Column(db.String(1000))\n description = db.Column(db.Text)\n product_type_id = db.Column('product_type_id', db.Integer, db.ForeignKey('opbeans_flask_producttype.id'), nullable=False)\n product_type = db.relationship('ProductType', backref=db.backref('opbeans_flask_product', lazy=True))\n stock = db.Column(db.Integer)\n cost = db.Column(db.Integer)\n selling_price = db.Column(db.Integer)\n orders = db.relationship('Order', secondary='opbeans_flask_orderline')\n\n\nclass OrderLine(db.Model):\n __tablename__ = 'opbeans_flask_orderline'\n product_id = db.Column(db.Integer, db.ForeignKey('opbeans_flask_product.id'), primary_key=True)\n product = db.relationship('Product')\n\n order_id = db.Column(db.Integer, db.ForeignKey('opbeans_flask_order.id'), primary_key=True)\n order = db.relationship('Order')\n\n amount = db.Column(db.Integer)\n\n\n@app.route('/api/products')\ndef products():\n product_list = Product.query.order_by(\"id\").all()\n data = []\n for p in product_list:\n data.append({\n 'id': p.id,\n 'sku': p.sku,\n 'name': p.name,\n 'stock': p.stock,\n 'type_name': p.product_type.name\n })\n return jsonify(data)\n\n\n@app.route('/api/products/top')\ndef top_products():\n sold_amount = func.sum(OrderLine.amount).label('sold')\n product_list = db.session.query(\n Product.id,\n Product.sku,\n Product.name,\n Product.stock,\n sold_amount\n ).outerjoin(OrderLine).group_by(Product.id).order_by(sold_amount.desc()).limit(3)\n return jsonify([{\n 'id': p.id,\n 'sku': p.sku,\n 'name': p.name,\n 'stock': p.stock,\n 'sold': p.sold,\n } for p in product_list])\n\n\n@app.route('/api/products/')\ndef product(pk):\n product = Product.query.options(joinedload(Product.product_type)).get(pk)\n if not product:\n abort(404)\n return jsonify({\n \"id\": product.id,\n \"sku\": product.sku,\n \"name\": product.name,\n \"description\": product.description,\n \"stock\": product.stock,\n \"cost\": product.cost,\n \"selling_price\": product.selling_price,\n \"type_id\": product.product_type_id,\n \"type_name\": product.product_type.name\n })\n\n\n@app.route(\"/api/products//customers\")\ndef product_customers(pk):\n customers = Customer.query.join(Order).join(OrderLine).join(Product).filter(Product.id == pk).order_by(Customer.id).all()\n return jsonify([{\n \"id\": cust.id,\n \"full_name\": cust.full_name,\n \"company_name\": cust.company_name,\n \"email\": cust.email,\n \"address\": cust.address,\n \"postal_code\": cust.postal_code,\n \"city\": cust.city,\n \"country\": cust.country,\n } for cust in customers])\n\n\n@app.route('/api/types')\ndef product_types():\n types_list = ProductType.query.all()\n data = []\n for t in types_list:\n data.append({\n 'id': t.id,\n 'name': t.name,\n })\n return jsonify(data)\n\n\n@app.route('/api/types/')\ndef product_type(pk):\n product_type = ProductType.query.filter_by(id=pk)[0]\n products = Product.query.filter_by(product_type=product_type)\n return jsonify({\n \"id\": product_type.id,\n \"name\": product_type.name,\n \"products\": [{\n \"id\": product.id,\n \"name\": product.name,\n } for product in products]\n })\n\n\n@app.route(\"/api/customers\")\ndef customers():\n customers = Customer.query.all()\n data = []\n for customer in customers:\n data.append({\n \"id\": customer.id,\n \"full_name\": customer.full_name,\n \"company_name\": customer.company_name,\n \"email\": customer.email,\n \"address\": customer.address,\n \"postal_code\": customer.postal_code,\n \"city\": customer.city,\n \"country\": customer.country,\n })\n return jsonify(data)\n\n\n@app.route(\"/api/customers/\")\ndef customer(pk):\n try:\n customer_obj = Customer.query.filter_by(id=pk)[0]\n except IndexError:\n app.logger.warning('Customer with ID %s not found', pk, exc_info=True)\n abort(404)\n return jsonify({\n \"id\": customer_obj.id,\n \"full_name\": customer_obj.full_name,\n \"company_name\": customer_obj.company_name,\n \"email\": customer_obj.email,\n \"address\": customer_obj.address,\n \"postal_code\": customer_obj.postal_code,\n \"city\": customer_obj.city,\n \"country\": customer_obj.country,\n })\n\n@app.route(\"/api/stats\")\ndef stats():\n return jsonify({\n \"products\": Product.query.count(),\n \"customers\": Customer.query.count(),\n \"orders\": Order.query.count(),\n \"numbers\":{\n \"revenue\": 0,\n \"cost\": 0,\n \"profit\": 0,\n }\n })\n\n\n@app.route('/images/')\ndef image(path):\n return send_from_directory(os.path.join(\"opbeans\", \"static\", \"build\", \"images\"), path)\n\n\n@app.route('/', defaults={'path': ''})\n@app.route('/')\ndef index(path):\n\n return render_template(\"index.html\", **rum_settings())\n\n\nRUM_CONFIG = None\n\ndef rum_settings():\n global RUM_CONFIG\n if RUM_CONFIG:\n return RUM_CONFIG\n url = os.environ.get('ELASTIC_APM_JS_SERVER_URL')\n if not url:\n url = apm.client.config.server_url\n package_json_file = os.path.join('opbeans', 'static', 'package.json')\n if os.path.exists(package_json_file):\n with open(package_json_file) as f:\n package_json = json.load(f)\n else:\n package_json = {}\n service_name = os.environ.get('ELASTIC_APM_JS_SERVICE_NAME', package_json.get('name', \"opbeans-rum\"))\n service_version = os.environ.get('ELASTIC_APM_JS_SERVICE_VERSION', package_json.get('version', None))\n RUM_CONFIG = {\n \"RUM_SERVICE_NAME\": service_name,\n \"RUM_SERVICE_VERSION\": service_version,\n \"RUM_SERVER_URL\": url\n }\n return RUM_CONFIG\n\n\nif __name__ == '__main__':\n app.run(debug=True, port=5000)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"23031858","text":"import tak.ptn\nimport tak.proto\n\nimport attr\nimport csv\nimport os\nimport struct\n\nimport numpy as np\n\n@attr.s(frozen=True)\nclass Instance(object):\n proto = attr.ib(\n validator = attr.validators.instance_of(tak.proto.Position))\n\n position = attr.ib(\n validator = attr.validators.instance_of(tak.Position))\n move = attr.ib(\n validator = attr.validators.instance_of(tak.Move))\n\n\n@attr.s(frozen=True)\nclass Dataset(object):\n size = attr.ib()\n instances = attr.ib()\n\n def minibatches(self, batch_size):\n perm = np.random.permutation(len(self.instances[0]))\n i = 0\n while i < len(self.instances):\n yield [o[perm[i:i+batch_size]] for o in self.instances]\n i += batch_size\n\n def __len__(self):\n return len(self.instances[0])\n\ndef xread(fh, n):\n b = fh.read(n)\n if len(b) == 0:\n raise EOFError\n\n if len(b) != n:\n raise IOError(\"incomplete read ({0}/{1} at off={2})\".format(\n len(b), n, fh.tell()))\n return b\n\ndef load_proto(path):\n positions = []\n with open(path, 'rb') as f:\n while True:\n try:\n rlen, = struct.unpack(\">L\", xread(f, 4))\n positions.append(tak.proto.Position.FromString(xread(f, rlen)))\n except EOFError:\n break\n return positions\n\ndef load_csv(path):\n positions = []\n\n with open(path) as f:\n reader = csv.reader(f)\n for row in reader:\n p = tak.proto.Position()\n p.tps = row[0]\n p.move = row[1]\n if len(row) > 2 and row[2]:\n p.value = float(row[2])\n if len(row) > 3:\n p.day = row[3]\n if len(row) > 4:\n p.id = int(row[4])\n if len(row) > 5:\n p.ply = int(row[5])\n if len(row) > 6:\n p.plies = int(row[6])\n\n positions.append(p)\n return positions\n\ndef write_csv(path, positions):\n with open(path, 'w') as f:\n w = csv.writer(f)\n for rec in positions:\n w.writerow((rec.tps, rec.move, rec.value,\n rec.day, rec.id, rec.ply, rec.plies,\n ))\n\ndef write_proto(path, positions):\n with open(path, 'wb') as f:\n for rec in positions:\n data = rec.SerializeToString()\n f.write(struct.pack(\">L\", len(data)))\n f.write(data)\n\ndef parse(positions, add_symmetries=False):\n out = []\n for p in positions:\n position = tak.ptn.parse_tps(p.tps),\n move = tak.ptn.parse_move(p.move),\n\n if add_symmetries:\n for sym in tak.symmetry.SYMMETRIES:\n sp = tak.symmetry.transform_position(sym, position)\n sm = tak.symmetry.transform_move(sym, move)\n out.append(Instance(\n proto = p,\n position = sp,\n move = sm))\n else:\n out.append(Instance(\n proto = p,\n position = position,\n move = move))\n return out\n\ndef to_features(positions, add_symmetries=False):\n p = tak.ptn.parse_tps(positions[0].tps)\n size = p.size\n feat = tak.train.Featurizer(size)\n\n count = len(positions)\n if add_symmetries:\n count *= 8\n xs = np.zeros((count,) + feat.feature_shape())\n ys = np.zeros((count, feat.move_count()))\n\n for i, pos in enumerate(positions):\n p = tak.ptn.parse_tps(pos.tps)\n m = tak.ptn.parse_move(pos.move)\n if add_symmetries:\n feat.features_symmetries(p, out=xs[8*i:8*(i+1)])\n for j,sym in enumerate(tak.symmetry.SYMMETRIES):\n ys[8*i + j][feat.move2id(tak.symmetry.transform_move(sym, m, size))] = 1\n else:\n feat.features(p, out=xs[i])\n ys[i][tak.train.move2id(m, size)] = 1\n return Dataset(size, (xs, ys))\n\ndef raw_load(dir):\n if os.path.isfile(os.path.join(dir, 'train.csv')):\n return (\n load_csv(os.path.join(dir, 'train.csv')),\n load_csv(os.path.join(dir, 'test.csv')),\n )\n else:\n return (\n load_proto(os.path.join(dir, 'train.dat')),\n load_proto(os.path.join(dir, 'test.dat')),\n )\n\ndef load_corpus(dir, add_symmetries=False):\n train, test = raw_load(dir)\n return (\n parse(train, add_symmetries = add_symmetries),\n parse(test, add_symmetries = add_symmetries))\n\ndef load_features(dir, add_symmetries=False):\n train, test = raw_load(dir)\n return (\n to_features(train, add_symmetries),\n to_features(test, add_symmetries))\n\n__all__ = ['Instance', 'Dataset',\n 'load_csv', 'load_proto',\n 'write_csv', 'write_proto',\n 'load_corpus', 'load_features']\n","sub_path":"python/tak/train/corpus.py","file_name":"corpus.py","file_ext":"py","file_size_in_byte":4273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"278309606","text":"#!/usr/bin/python\n\nimport Tkinter as tk\nimport tkMessageBox as msg\nfrom math import pi\nfrom math import atan2\nfrom time import sleep\nfrom random import random\n\nCANVAS_SIZE = 600\nCANVAS_AREA = CANVAS_SIZE * 90 / 100\nCANVAS_BORDER = (CANVAS_SIZE - CANVAS_AREA) / 2\nNO_POINTS_TO_SOLVE = \\\n\"\"\"You need to first generate points in order to solve their convex hull.\"\"\"\nNOT_INTEGER_DELAY = \\\n\"\"\" does not seem to be a positive integer.\"\"\"\nNOT_ENOUGH_POINTS = \\\n\"\"\"The minimum number of points is three.\"\"\"\nPLEASE_CLEAN_CANVAS = \\\n\"\"\"The graph has already been solved.\nPlease use [Redraw points] to clear the solution.\nThe points will remain.\"\"\"\nCURRENTLY_RUNNING = \\\n\"\"\"The convex hull is currently being solved. \\\nIf you don't want to wait, reduce the delay.\"\"\"\n\nclass Point():\n\tdef __init__(self, x=0, y=0):\n\t\tself.x = x\n\t\tself.y = y\n\t\tself.angle = None\n\n\tdef get_angle_from_zero(self, point):\n\t\tdx = self.x - point.x\n\t\tdy = self.y - point.y\n\t\tangle = atan2(dy, dx)\n\t\t# Convert to positive angle\n\t\tif angle < 0:\n\t\t\tangle += 2 * pi\n\t\treturn angle\n\nclass Application(tk.Frame):\n\tdef __init__(self, master=None):\n\t\ttk.Frame.__init__(self, master)\n\t\tself.grid()\n\t\tself.initialise_delay_variable()\n\t\tself.initialise_num_points_variable()\n\t\tself.points = []\n\t\tself.ready = False\n\t\tself.running = False\n\t\tself.create_widgets()\n\n\tdef mainloop(self):\n\t\ttk.Frame.mainloop(self)\n\n\tdef initialise_delay_variable(self):\n\t\tself.delay = 500\n\t\tself.delay_string = tk.StringVar(value=str(self.delay))\n\t\tself.delay_string.trace('w', self.validate_delay)\n\n\tdef initialise_num_points_variable(self):\n\t\tself.num_points = 50\n\t\tself.num_points_string = tk.StringVar(value=str(self.num_points))\n\t\tself.num_points_string.trace('w', self.validate_num_points)\n\n\tdef validate_delay(self, *args):\n\t\tdelay_candidate = self.delay_string.get()\n\t\tif delay_candidate.isdigit():\n\t\t\tself.delay = int(delay_candidate)\n\t\telse:\n\t\t\tmsg.showerror(\"What is \" + delay_candidate + \"?\",\n\t\t\t delay_candidate + NOT_INTEGER_DELAY)\n\t\t\tself.delay_string.set(str(self.delay))\n\n\tdef validate_num_points(self, *args):\n\t\tnum_points_candidate = self.num_points_string.get()\n\t\tif num_points_candidate.isdigit():\n\t\t\tcandidate_as_int = int(num_points_candidate)\n\t\t\tif candidate_as_int < 3:\n\t\t\t\tmsg.showerror(\"Number of points < 3\",\n\t\t\t\t NOT_ENOUGH_POINTS)\n\t\t\telse:\n\t\t\t\tself.num_points = candidate_as_int\n\t\telse:\n\t\t\tmsg.showerror(\"What is \" + num_points_candidate + \"?\",\n\t\t\t num_points_candidate + NOT_INTEGER_DELAY)\n\t\t\tself.num_points_string.set(str(self.delay))\n\n\tdef create_widgets(self):\n\t\ttk.Grid.columnconfigure(self, 3, weight=1)\n\n\t\t# Row 0\n\t\tself.canvas = tk.Canvas(self, bg='white',\n\t\t width=CANVAS_SIZE, height=CANVAS_SIZE)\n\t\tself.canvas.grid(row=0, column=0, columnspan=5)\n\n\t\t# Row 1\n\t\tw1 = tk.Button(self, text=\"Generate points\", command=self.create_points)\n\t\tw2 = tk.Button(self, text=\"Redraw points\", command=self.redraw_points)\n\t\tw3 = tk.Label (self, text=\"Number of points\")\n\t\tw4 = tk.Entry (self, textvar=self.num_points_string, width=5)\n\t\tw1.grid(row=1, column=0)\n\t\tw2.grid(row=1, column=1)\n\t\tw3.grid(row=1, column=3, sticky=tk.E)\n\t\tw4.grid(row=1, column=4)\n\n\t\t# Row 2\n\t\tw1 = tk.Button(self, text=\"Graham Scan\", command=self.graham_scan)\n\t\tw2 = tk.Button(self, text=\"Gift Wrap\", command=self.gift_wrap)\n\t\tw3 = tk.Button(self, text=\"Combined\")\n\t\tw4 = tk.Label (self, text=\"Step delay (ms)\")\n\t\tw5 = tk.Entry (self, textvar=self.delay_string, width=5)\n\t\tw1.grid(row=2, column=0, sticky=tk.E+tk.W)\n\t\tw2.grid(row=2, column=1, sticky=tk.E+tk.W)\n\t\tw3.grid(row=2, column=2, sticky=tk.E+tk.W)\n\t\tw4.grid(row=2, column=3, sticky=tk.E)\n\t\tw5.grid(row=2, column=4, sticky=tk.E, padx=10)\n\n\tdef create_points(self):\n\t\tself.points = []\n\t\tfor i in range(self.num_points):\n\t\t\tpoint_x = CANVAS_BORDER + CANVAS_AREA * random()\n\t\t\tpoint_y = CANVAS_BORDER + CANVAS_AREA * random()\n\t\t\tself.points.append(Point(point_x, point_y))\n\t\tself.redraw_points()\n\n\tdef draw_points(self):\n\t\tfor p in self.points:\n\t\t\tself.canvas.create_oval(p.x - 1, p.y - 1, p.x + 1, p.y + 1, fill='black')\n\t\tself.ready = True\n\n\tdef redraw_points(self):\n\t\tif self.running:\n\t\t\tmsg.showerror(\"Running\", CURRENTLY_RUNNING)\n\t\t\treturn\n\t\tself.canvas.delete(\"all\")\n\t\t# TODO: It would be great to handle these in another way.\n\t\t# self.pop('key', None) doesn't work.\n\t\ttry:\n\t\t\tdel self['stack']\n\t\texcept:\n\t\t\tpass\n\t\ttry:\n\t\t\tdel self['starter_point']\n\t\texcept:\n\t\t\tpass\n\t\tself.draw_points()\n\n\tdef graham_scan(self):\n\t\tif not self.ready:\n\t\t\tmsg.showerror(\"Canvas is dirty\", PLEASE_CLEAN_CANVAS)\n\t\telif len(self.points):\n\t\t\tself.ready = False\n\t\t\tself.running = True\n\t\t\tself.after(self.delay, self.graham_get_starter_point)\n\t\telse:\n\t\t\tmsg.showerror(\"No points\", NO_POINTS_TO_SOLVE)\n\n\tdef gift_wrap(self):\n\t\tif not self.ready:\n\t\t\tmsg.showerror(\"Canvas is dirty\", PLEASE_CLEAN_CANVAS)\n\t\telif len(self.points):\n\t\t\tself.ready = False\n\t\t\tmsg.showinfo(\"Not yet implemented.\", \"Not yet implemented.\")\n\t\telse:\n\t\t\tmsg.showerror(\"No points\", NO_POINTS_TO_SOLVE)\n\n\tdef graham_get_starter_point(self):\n\t\tself.starter_point = min(self.points, key=lambda p: p.y)\n\t\tself.circle_point(self.starter_point)\n\t\tself.stack = [self.starter_point]\n\t\tself.draw_horizontal_line(self.starter_point)\n\t\tself.after(self.delay, self.graham_sort_by_angle)\n\n\tdef graham_sort_by_angle(self):\n\t\tfor point in self.points:\n\t\t\tpoint.angle = point.get_angle_from_zero(self.starter_point)\n\t\tself.points.sort(key=lambda p: p.angle)\n\t\tself.after(self.delay, self.graham_process_point, (1))\n\n\tdef graham_process_point(self, index):\n\t\tpoint = self.starter_point\n\t\tif index < len(self.points):\n\t\t\tpoint = self.points[index]\n\t\t\tself.circle_point(point)\n\t\t\tself.graham_check_and_remove_if_concave(point)\n\t\t\tself.stack.append(point)\n\t\t\tself.after(self.delay, self.graham_process_point, (index + 1))\n\t\telse:\n\t\t\tself.connect_with_line(self.starter_point, self.stack[-1])\n\t\t\tself.running = False\n\n\tdef circle_point(self, p, color='purple'):\n\t\tself.canvas.create_oval(p.x - 5, p.y - 5, p.x + 5, p.y + 5, outline=color)\n\n\tdef graham_check_and_remove_if_concave(self, current_point):\n\t\tprev_point = self.stack[-1]\n\t\tcurrent_point.angle_from_prev \\\n\t\t\t= prev_point.get_angle_from_zero(current_point)\n\t\tif len(self.stack) > 1:\n\t\t\tangle_last_to_current = current_point.get_angle_from_zero(prev_point)\n\t\t\ttotal_internal_angle = prev_point.angle_from_prev - angle_last_to_current\n\t\t\tif pi < total_internal_angle or -pi < total_internal_angle < 0:\n\t\t\t\tself.circle_point(self.stack.pop(), 'red')\n\t\t\t\tself.disconnect_line(self.stack[-1], prev_point)\n\t\t\t\tself.graham_check_and_remove_if_concave(current_point)\n\t\tself.connect_with_line(current_point, self.stack[-1])\n\n\tdef connect_with_line(self, a, b):\n\t\tself.canvas.create_line(a.x, a.y, b.x, b.y)\n\n\tdef disconnect_line(self, a, b):\n\t\tself.canvas.create_line(a.x, a.y, b.x, b.y, fill='white', dash=(5,5))\n\n\tdef draw_horizontal_line(self, point):\n\t\tself.canvas.create_line(0, point.y, CANVAS_SIZE, point.y)\n\n\napp = Application()\napp.master.title(\"Convex Region from points\")\napp.mainloop()\n","sub_path":"convex_hull.py","file_name":"convex_hull.py","file_ext":"py","file_size_in_byte":7026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"112080451","text":"from django.contrib.auth import get_user_model\nfrom django.http import Http404\nfrom rest_framework import generics\nfrom rest_framework import status\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nfrom sportparken.dataset.models import (\n Huurder,\n HuurderObjectRelation,\n Sportpark,\n SportparkObjectGeometry,\n SportparkObject,\n SportparkGeometry,\n Ondergrond\n )\nfrom sportparken.api.serializers import (\n HuurderListSerializer,\n HuurderDetailSerializer,\n RelationListSerializer,\n SportparkListSerializer,\n SportparkDetailSerializer,\n SportparkObjectListSerializer,\n SportparkObjectDetailSerializer,\n SportparkGeomDetailSerializer,\n SportparkObjectGeomDetailSerializer,\n RelationPostRemoveSerializer,\n UserLoginSerializer,\n OndergrondListSerializer\n)\n\nUser = get_user_model()\n\n\nclass HuurderListApi(generics.ListCreateAPIView):\n queryset = Huurder.objects.all()\n serializer_class = HuurderListSerializer\n\n def get_queryset(self):\n queryset = Huurder.objects.all()\n spid = self.request.query_params.get('sp', None)\n if spid is not None:\n queryset = queryset.filter(ho_set__sportpark_object__sportpark__tid=spid).distinct()\n return queryset\n\n\nclass HuurderDetailApi(generics.RetrieveUpdateDestroyAPIView):\n queryset = Huurder.objects.all()\n serializer_class = HuurderDetailSerializer\n\n\nclass SportparkListApi(generics.ListAPIView):\n queryset = Sportpark.objects.all()\n serializer_class = SportparkListSerializer\n\n\nclass SportparkDetailApi(generics.RetrieveAPIView):\n queryset = Sportpark.objects.all()\n serializer_class = SportparkDetailSerializer\n\n\nclass SportparkObjectListApi(generics.ListAPIView):\n\n serializer_class = SportparkObjectListSerializer\n\n def get_queryset(self):\n queryset = SportparkObject.objects.all()\n spid = self.request.query_params.get('sp', None)\n if spid is not None:\n queryset = queryset.filter(sportpark__tid=spid)\n return queryset\n\n\nclass SportparkObjectDetailApi(generics.RetrieveUpdateAPIView):\n queryset = SportparkObject.objects.all()\n serializer_class = SportparkObjectDetailSerializer\n\n\nclass SportparkGeomDetailApi(generics.RetrieveAPIView):\n queryset = SportparkGeometry.objects.all()\n serializer_class = SportparkGeomDetailSerializer\n\nclass OndergrondListApi(generics.ListAPIView):\n queryset = Ondergrond.objects.all()\n serializer_class = OndergrondListSerializer\n\n# class SportparkObjectGeomDetailApi(generics.RetrieveAPIView):\n# queryset = SportparkObjectGeometry.objects.all()\n# serializer_class = SportparkObjectGeomDetailSerializer\n\nclass SportparkObjectGeomDetailApi(APIView):\n\tdef get_object(self, pk):\n\t\ttry:\n\t\t\treturn SportparkObjectGeometry.objects.get(pk=pk)\n\t\texcept SportparkObjectGeometry.DoesNotExist:\n\t\t\traise Http404\n\n\tdef get(self, request, pk, format=None):\n\t\tsnippet = self.get_object(pk)\n\t\tserializer = SportparkObjectGeomDetailSerializer(snippet)\n\t\treturn Response(serializer.data)\n\n\tdef put(self, request, pk, format=None):\n\t\tsnippet = self.get_object(pk)\n\t\tserializer = SportparkObjectGeomDetailSerializer(snippet, data=request.data)\n\t\tif serializer.is_valid():\n\t\t\tserializer.save()\n\t\t\treturn Response(serializer.data)\n\t\treturn Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass RelatieListApi(generics.ListCreateAPIView):\n serializer_class = RelationListSerializer\n\n def get_queryset(self):\n queryset = HuurderObjectRelation.objects.all()\n\n spid = self.request.query_params.get('sp', None)\n hid = self.request.query_params.get('hid', None)\n\n if spid:\n queryset = queryset.filter(sportpark_object__sportpark__tid=spid)\n\n if hid:\n queryset = queryset.filter(huurder__tid=hid)\n\n return queryset\n\n def post(self, request, format=None):\n relation = RelationPostRemoveSerializer(data=request.data)\n if relation.is_valid():\n relation.save()\n return Response(relation.data, status=status.HTTP_201_CREATED)\n\n return Response(relation.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass RelatieDetailApi(generics.RetrieveDestroyAPIView):\n serializer_class = RelationPostRemoveSerializer\n queryset = HuurderObjectRelation.objects.all()\n\n\nclass UserLoginApi(APIView):\n # permission_classes = [AllowAny]\n serializer_class = UserLoginSerializer\n \n def post(self, request, *args, **kwargs):\n data = request.data\n serializer = UserLoginSerializer(data=data)\n if serializer.is_valid(raise_exception=True):\n new_data = serializer.data\n return Response(new_data, status=status.HTTP_200_OK)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n","sub_path":"web/sportparken/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"328303638","text":"import numpy as np\n\n\ndef distance_eclud(a, b):\n diff = a - b\n\n return np.linalg.norm(diff, ord=2)\n\n\ndef random_centroids(data, k):\n num_points, _ = data.shape\n idx = np.random.choice(num_points, k, replace=False)\n\n return data[idx, :]\n\n\ndef Kmeans(data, k, dist_measure=distance_eclud,\n create_centroids=random_centroids, max_iterations=100):\n num_points, dim = data.shape\n centroids = create_centroids(data, k)\n cluster_assignment = np.zeros(num_points, dtype=int)\n cluster_changed = False\n iterations = max_iterations\n\n for it in range(max_iterations):\n cluster_changed = False\n for i in range(num_points):\n min_distance = np.inf\n min_indx = -1\n for j in range(k):\n distance = distance_eclud(data[i, :], centroids[j, :])\n if (distance < min_distance):\n min_distance = distance\n min_indx = j\n if (min_indx != cluster_assignment[i]):\n cluster_changed = True\n cluster_assignment[i] = min_indx\n\n for i in range(k):\n cluster_data = data[cluster_assignment == i, :]\n centroids[i, :] = np.mean(cluster_data, axis=0)\n\n if (not cluster_changed):\n iterations = it\n break\n\n return centroids, cluster_assignment, iterations\n","sub_path":"Kmeans/kmeans.py","file_name":"kmeans.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"111167967","text":"import inspect\nfrom unittest import TestCase\nfrom source_settings import SPIDER_SETTINGS\n\n\nclass TestColumnsInSettings(TestCase):\n \"\"\"\n Testing the official id, tracker_col col exists in items.py\n for the spiders that have those fields\n \"\"\"\n\n def test_col_in_settings(self):\n \"\"\"\n For each spider setting get all the classes in the items.py\n file and check if the items have fields that match official_id_col\n or tracker_col in the scraper settings.\n \"\"\"\n for scraper_settings in SPIDER_SETTINGS:\n if 'official_id_col' in scraper_settings:\n self.has_item_field(scraper_settings['official_id_col'],\n scraper_settings)\n\n if 'tracker_col' in scraper_settings:\n self.has_item_field(scraper_settings['tracker_col'],\n scraper_settings)\n\n def has_item_field(self, field_name, scraper_settings):\n \"\"\"\n For the given field name in the scraper settings\n check if the settings exist\n \"\"\"\n spider_items = __import__(scraper_settings['package'],\n globals(), locals(),\n [\"items\"], -1)\n items_module = getattr(spider_items, \"items\")\n\n # Ignore these classes when importing item since they are default\n # classes or the scrapy classes that will exists\n ignore_cls = ['BaseItem', 'Field', 'Item', \n 'EKAgencyItem', 'RegGovCommentsItem']\n\n all_classes = inspect.getmembers(items_module, inspect.isclass)\n valid_classes = [class_[0] for class_ in all_classes\n if class_[0] not in ignore_cls]\n\n for itm_cls in valid_classes:\n itm_cls = getattr(items_module, itm_cls)\n self.assertIn(field_name, itm_cls.fields.keys(),\n msg=\"%s is missing field '%s' in its items class\" %(items_module, field_name))\n","sub_path":"tests/test_col_in_settings.py","file_name":"test_col_in_settings.py","file_ext":"py","file_size_in_byte":2006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"88816717","text":"from typing import List\n\n# 买股票 卖完了有一天一冷冻期\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n if len(prices) < 2:\n return 0\n dp_i_0, dp_i_1, dp_prev_0 = 0, -prices[0], 0\n for i in range(1, len(prices)):\n temp = dp_i_0\n dp_i_0 = max(dp_i_0, dp_i_1 + prices[i])\n dp_i_1 = max(dp_i_1, dp_prev_0 - prices[i])\n dp_prev_0 = temp\n return dp_i_0\n\n\nif __name__ == '__main__':\n print(Solution().maxProfit([7, 2, 9, 4, 7, 6]))\n","sub_path":"leetcode/num/309.best-time-to-buy-and-sell-stock-with-cooldown.py","file_name":"309.best-time-to-buy-and-sell-stock-with-cooldown.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"221729882","text":"from conans import ConanFile, CMake, tools\nimport os, io, re, platform\nclass Test(ConanFile):\n generators = \"virtualenv\"\n\n def build_requirements(self):\n if tools.which(\"cmake\") is None:\n self.build_requires(\"cmake_installer/3.16.0@conan/stable\")\n else:\n output = io.StringIO()\n self.run(\"cmake --version\",output=output)\n version = re.search( \"cmake version (?P\\S*)\", output.getvalue())\n if tools.Version( version.group(\"version\") ) < \"3.12.0\":\n self.build_requires(\"cmake_installer/3.16.0@conan/stable\")\n\n def build(self):\n cmake = CMake(self)\n cmake.configure()\n cmake.build()\n\n def test(self):\n if platform.system() == \"Windows\":\n self.run(\".\\Debug\\example.exe\")\n else:\n self.run(\"./example\")\n","sub_path":"recipes/libField/all/test_package/conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"54981747","text":"import random\nimport csv\nimport pyexcel as pe\nfrom csv import reader\nimport os, sys\nfrom osgeo import gdal\nimport cv2\nimport numpy as np\nfrom geopy.distance import geodesic\nimport csv\nimport glob\nfrom osgeo import gdal\nfrom pyproj import Transformer\n#from yolo_object_detection import *\n#from check_sum import *\n#from slicing import *\n\ncwd = os.getcwd()\nprint(cwd + \"\\\\Object_detection\\\\yolov3_training8_last.weights\")\ndef slicing(in_file):\n\n dset = gdal.Open(in_file) \n\n\n width = dset.RasterXSize\n height = dset.RasterYSize\n tile_size_x = 5000\n tile_size_y = 5000\n\n input_filename = in_file\n output = in_file.split(\"\\\\\")\n output_filename = output[-1]\n\n out_path = cwd + \"\\\\Object_detection\\\\processes\\\\main_slices\\\\\"\n print(out_path)\n output_filename = \"5\"\n\n\n for i in range(0, width, tile_size_x):\n for j in range(0, height, tile_size_y):\n com_string = \"gdal_translate -of GTiff -srcwin \" + str(i)+ \", \" + str(j) + \", \" + str(tile_size_x) + \", \" + str(tile_size_y) + \" \" +str(input_filename) + \" \" + str(out_path) + str(output_filename) + str(i) + \"_\" + str(j) + \".tif\"\n os.system(com_string)\n\n\n\ndef check():\n \n #find if point falls in rectangle BOX\n def rectContains(rect,pt):\n logic = rect[0] < pt[0] < rect[0]+rect[2] and rect[1] < pt[1] < rect[1]+rect[3]\n return logic\n\n \n\n with open( cwd +'\\\\Object_detection\\\\processes\\\\csv_data\\\\all_objects.csv') as rbox:\n csv_reader = reader(rbox)\n header = next(csv_reader)\n if header != None:\n for row in csv_reader:\n # row variable is a list that represents a row in csv\n #print(row)\n center = row[4:]\n pt_x = int(center[0])\n pt_y = int(center[1])\n pt = [pt_x,pt_y]\n\n with open( cwd + '\\\\Object_detection\\\\processes\\\\csv_data\\\\bbox.csv') as bbox:\n csv_read = reader(bbox)\n header = next(csv_read)\n if header != None:\n for col in csv_read:\n x,y,w,h = int(col[0]),int(col[1]),int(col[2]),int(col[3])\n #print(col[0],col[1],col[2],col[3])\n rect=[x,y,w,h]\n if rectContains(rect,pt):\n with open(cwd + '\\\\Object_detection\\\\processes\\\\csv_data\\\\final_ships.csv','a',newline='') as yo:\n writer=csv.writer(yo)\n text = \"Length:\" + str(row[2])+\" & \" + \"Width:\" + str(row[3])\n writer.writerow([row[0],row[1],text])\n\ndef obj_detection(file):\n weight_path = cwd + \"\\\\Object_detection\\\\yolov3_training8_last.weights\"\n cfg_path = cwd + \"\\\\Object_detection\\\\yolov3_testing1.cfg\"\n # Load Yolo\n #net = cv2.dnn.readNet(cwd + \"\\\\Object_detection\\\\yolov3_training8_last.weights\", cwd + \"\\\\Object_detection\\\\yolov3_testing1.cfg\")\n net = cv2.dnn.readNet(weight_path, cfg_path)\n\n # Name custom object\n classes = [\"\"]\n\n # Images path\n images_path = glob.glob(file)\n #images_path = glob.glob(r\"ship.png\")\n\n\n layer_names = net.getLayerNames()\n output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]\n colors = np.random.uniform(0, 255, size=(len(classes), 3))\n\n # Insert here the path of your images\n random.shuffle(images_path)\n\n\n \n # loop through all the images\n for img_path in images_path:\n # Loading image\n img = cv2.imread(img_path)\n #img = cv2.resize(img, None, fx= 0.15, fy= 0.15)\n height, width, channels = img.shape\n\n # Detecting objects\n blob = cv2.dnn.blobFromImage(img, 0.00392, (512,512), (0, 0, 0), True, crop=False)\n\n net.setInput(blob)\n outs = net.forward(output_layers)\n\n # Showing informations on the screen\n class_ids = [0]\n confidences = []\n boxes = []\n for out in outs:\n for detection in out:\n scores = detection[5:]\n class_id = np.argmax(scores)\n confidence = scores[class_id]\n if confidence > 0.5:\n # Object detected\n #print(class_id)\n center_x = int(detection[0] * width)\n center_y = int(detection[1] * height)\n w = int(detection[2] * width)\n h = int(detection[3] * height)\n\n # Rectangle coordinates\n x = int(center_x - w / 2)\n y = int(center_y - h / 2)\n\n boxes.append([x, y, w, h])\n #print(boxes)\n confidences.append(float(confidence))\n class_ids.append(class_id)\n\n\n ###########Append X,Y,W,H in txt#######################\n with open(cwd + '\\\\Object_detection\\\\processes\\\\csv_data\\\\bbox.csv', mode='a') as file_:\n file_.write(\"{},{},{},{}\".format(x,y,w,h))\n file_.write(\"\\n\")\n \n indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)\n #print(indexes)\n font = cv2.FONT_HERSHEY_PLAIN\n for i in range(len(boxes)):\n if i in indexes:\n x, y, w, h = boxes[i]\n label = str(classes[class_ids[i]])\n color = colors[class_ids[i]]\n cv2.rectangle(img, (x, y), (x + w, y + h), color, 2)\n cv2.putText(img, label, (x, y + 30), font, 3, color, 2)\n\n dst_file = img_path.split(\"\\\\\")\n dst_file = dst_file[-1]\n dst_path = cwd + \"\\\\Object_detection\\\\processes\\\\detected_ships\\\\\"+str(dst_file)\n cv2.imwrite(dst_path, img)\n key = cv2.waitKey(0)\n\n #cv2.imwrite(\"1.jpg\", img)\n\n cv2.destroyAllWindows()\n\ndef pixel2coord(file,center):\n transformer = Transformer.from_crs(\"epsg:3857\" , \"epsg:4326\")\n x,y = center[0],center[1]\n # Open tif file\n ds = gdal.Open(file)\n # GDAL affine transform parameters, According to gdal documentation xoff/yoff are image left corner, a/e are pixel wight/height and b/d is rotation and is zero if image is north up. \n xoff, a, b, yoff, d, e = ds.GetGeoTransform()\n\n xp = a * x + b * y + xoff\n yp = d * x + e * y + yoff\n xp,yp = transformer.transform(xp , yp)\n return(yp, xp)\n\ndef main_detection(in_file):\n if in_file:\n slicing(in_file)\n #input dir path\n file = cwd + \"\\\\Object_detection\\\\processes\\\\main_slices\\\\\"\n \n #for yolo bbox\n with open(cwd + '\\\\Object_detection\\\\processes\\\\csv_data\\\\bbox.csv','w') as f:\n f.write('x,y,w,h\\n') # TRAILING NEWLINE\n f.close()\n\n #for All Ships data\n with open(cwd + '\\\\Object_detection\\\\processes\\\\csv_data\\\\final_ships.csv','w') as f:\n f.write('lan,lon,text\\n') # TRAILING NEWLINE\n f.close()\n\n\n #for contour \n with open(cwd + '\\\\Object_detection\\\\processes\\\\csv_data\\\\all_objects.csv','w') as f:\n f.write('lat,lon,length,width,center_x,center_y\\n') # TRAILING NEWLINE\n \n file_path = glob.glob(file + \"*.tif\")\n #print(file_path)\n for i in range(len(file_path)):\n file = file_path[i]\n img = cv2.imread(file,0)\n ret,thresh = cv2.threshold(img,70,255,cv2.THRESH_BINARY)\n contours,hierarchy = cv2.findContours(thresh, 1, 2)\n \n img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\n lol = False\n for i in range(len(contours)):\n cnt = contours[i]\n #print(i)\n if len(cnt)>17 and len(cnt)<70:\n lol = True\n print(\".\",end=\"\")\n rect = cv2.minAreaRect(cnt)\n box = cv2.boxPoints(rect)\n box = np.int0(box)\n image = cv2.drawContours(img,[box],0,(0,255,0),1)\n\n \n len1 = (box[0] + box[1])//2\n len2 = (box[2] + box[3])//2\n\n wid1 = (box[0] + box[3])//2\n wid2 = (box[1] + box[2])//2\n\n \n #Find Center point of the each box store its lat long\n center = int((len1[0]+len2[0])*0.5) , int((len1[1]+len2[1])*0.5)\n\n \n center_geocoord = list(pixel2coord(file,[center[0],center[1]]))\n #center_geocoord = [long,lat]\n cent_lat = center_geocoord[1]\n cent_long = center_geocoord[0]\n\n \n # length\n length_p1 = list(pixel2coord(file,[len1[0],len1[1]]))\n length_p2 = list(pixel2coord(file,[len2[0],len2[1]]))\n\n coords_1 = (length_p1[1], length_p1[0])#lat, long\n coords_2 = (length_p2[1], length_p2[0])#lat,long\n\n length = geodesic(coords_1, coords_2).meters\n\n # width\n width_p1 = list(pixel2coord(file,[wid1[0],wid1[1]]))\n width_p2 = list(pixel2coord(file,[wid2[0],wid2[1]]))\n\n coords_3 = (width_p1[1], width_p1[0])#lat, long\n coords_4 = (width_p2[1], width_p2[0])#lat,long\n\n width = geodesic(coords_3, coords_4).meters\n\n\n #image=cv2.circle(image,center, 2, (0,0,255), -1)\n #image=cv2.circle(image,(len1[0],len1[1]), 2, (0,0,255), -1)\n ################## ######################################################\n\n if width > length:\n length,width = float(\"{:.2f}\".format(width)),float(\"{:.2f}\".format(length))\n else:\n width,length = float(\"{:.2f}\".format(width)),float(\"{:.2f}\".format(length))\n \n\n\n with open(cwd + '\\\\Object_detection\\\\processes\\\\csv_data\\\\all_objects.csv','a',newline='') as f:\n writer=csv.writer(f)\n\n writer.writerow([cent_lat,cent_long,length,width,center[0],center[1]])\n\n\n \n #######################################################################\n\n ##############################Draw len1 len2 wid1 wid2 on BOX##########\n #lengh of the ship\n image=cv2.circle(img,(len1[0],len1[1]), 1, (0,0,255), 1)\n image=cv2.circle(img,(len2[0],len2[1]), 1, (0,0,255), 1)\n\n #width of the ship\n image=cv2.circle(img,(wid1[0],wid1[1]), 1, (0,0,255), 1)\n image=cv2.circle(img,(wid2[0],wid2[1]), 1, (0,0,255), 1)\n #######################################################################\n if lol:\n dst_file = file.split(\"\\\\\")\n dst_file = dst_file[-1]\n dst_path = cwd + \"\\\\Object_detection\\\\processes\\\\detected_con\\\\\"+str(dst_file)\n cv2.imwrite(dst_path, image)\n\n #Perform YOLO object detection\n obj_detection(dst_path)\n #perform check_sum\n check()\n print(\"Done\")\n\nimport sys\nfilename = str(sys.argv[1])\nmain_detection(filename)\n","sub_path":"Object_detection/main_program.py","file_name":"main_program.py","file_ext":"py","file_size_in_byte":11106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"572703944","text":"array = [5, 7, 9, 0, 3, 1, 6, 2, 4, 8]\n\n\ndef quick_sort(array, start, end):\n # start와 end값이 같다는건 배열에 남아있는 값이 1개라는 뜻 [ 정렬이 모두 끝남 ]\n if start >= end:\n return\n # pivot을 시작점으로 한다\n pivot = start\n\n # pivot보다 큰 값을 찾기위한 left\n left = start + 1\n\n # pivot보다 작은 값을 찾기위한 right\n right = end\n\n # left가 right보다 작아야 실행한다 [ right가 더 큰 경우는 left와 right가 엇갈린 경우 ]\n while left <= right:\n # 피벗이 큰 데이터를 찾을 때 까지 반복\n while left <= end and array[left] <= array[pivot]:\n left += 1\n\n # 피벗보다 작은 데이터를 찾을 때 까지 반복\n while right > start and array[right] >= array[pivot]:\n right -= 1\n\n # left와 right가 엇갈린 경우\n if left > right:\n array[right], array[pivot] = array[pivot], array[right]\n\n # 엇갈리지 않고 실행 한 경우\n else:\n array[left], array[right] = array[right], array[left]\n\n # 분할 이후, pivot을 기점으로 왼쪽과 오른쪽에서 정렬 재실행\n quick_sort(array, start, right - 1)\n quick_sort(array, right + 1, end)\n\n\nquick_sort(array, 0, len(array)-1)\n\nprint(array)","sub_path":"6. 정렬/QuickSort [퀵 정렬].py","file_name":"QuickSort [퀵 정렬].py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"81032883","text":"# -*- coding:utf-8 -*-\nfrom flask import Blueprint, render_template, request, jsonify, g\n\nfrom database.sqllite_operate import session\nfrom gz_yct_pynex import Iter_Task\n\ngengzong = Blueprint('gengzong', __name__)\n\n\n@gengzong.route('/action', methods=['GET'])\ndef gengzong_run():\n '''运行跟踪'''\n res = dict(request.args)\n Iter = Iter_Task()\n if '手动' in res:\n import time\n time.sleep(10)\n '''调用手动函数'''\n result = Iter.breadth_first(STATE='手动')\n if result:\n return jsonify({'msg': 'success_gz', 'code': 0})\n elif not result:\n return jsonify({'msg': 'session_expire', 'code': 1})\n\n\njinru = Blueprint('jinru', __name__)\n\n\n@jinru.route('/', methods=['GET'])\ndef index():\n '''进入界面'''\n if request.args.get('state') == 'finsh':\n try:\n session.execute(\n 'update yctjdugip set state=\"unuse\"')\n except Exception as e:\n session.rollback()\n raise e\n else:\n text = '\"已完成跟踪任务,成功退出,谢谢!\"'\n return render_template('unable.html', text=text)\n if g.result:\n vnc_url = 'http://116.228.76.163:3240/yct_vnc.html?path=?token=yuanqu2016'\n # vnc_url = 'http://192.168.130.27:5000/yct_vnc.html?path=?token=yuanqu2016'\n try:\n session.execute(\n 'update yctjdugip set state=\"used\"')\n except Exception as e:\n session.rollback()\n raise e\n return render_template('JsBasePage.html', vnc_url=vnc_url)\n else:\n text = '\"进度跟踪机器正在使用中,请稍后再试,谢谢!\"'\n return render_template('unable.html', text=text)\n","sub_path":"programe/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"183220728","text":"from ConfigParser import NoSectionError, NoOptionError\n\nfrom . import config\nfrom .app import app\nfrom .entrypoint import get_core_task_modules, get_plugin_task_modules\n\n\ndef main():\n try:\n include_core_tasks = config.getboolean(\n 'girder_worker', 'core_tasks')\n except (NoSectionError, NoOptionError):\n include_core_tasks = True\n\n if include_core_tasks:\n app.conf.update({\n 'CELERY_IMPORTS': get_core_task_modules()\n })\n\n app.conf.update({\n 'CELERY_INCLUDE': get_plugin_task_modules()\n })\n app.worker_main()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"girder_worker/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"605475571","text":"from django.shortcuts import render\n\nfrom dor.DTO.StuDorLog import PayLogModel\nfrom dor.models import Activity, ActvityApplyment,MeetingRoomOrderTime,MeetingRoom,MeetingRoomApplymentRecord,DorCostRecord, StuPayRecord, Student,DorBookInf\nfrom dor.DTO.MeetingLog import MeetingLogModel\nfrom dor.student_handle.device_repair_applyment import repair\nfrom dor.student_handle.resource_applyment import resource\n\ndef show_stu_activity(request):\n data=Activity.objects.filter()\n try:\n sno = request.session['userno']\n except Exception as err:\n return render(request,\"index.html\")\n sname=request.session['username']\n test = Student.objects.get(sno=sno)\n activity_log=ActvityApplyment.objects.filter(sno=sno)\n return render(request, \"student/activity.html\",\n {'sno':sno,'sname':sname,'activity':data,'sname': test.sname, 'college': test.college, 'major': test.major, 'room_no': test.room_no,\n 'stu_phone': test.stu_phone, 'email': test.email,'activity_log':activity_log})\n\n\ndef show_stu_repair(request):\n try:\n sno = request.session['userno']\n except Exception as err:\n return render(request,\"index.html\")\n sname=request.session['username']\n return repair(request)\n\ndef show_stu_pay(request):\n sname = request.session['username']\n data = DorCostRecord.objects.all()\n pay_list = []\n for i in range(0, len(data)):\n p = PayLogModel()\n test = StuPayRecord.objects.get(bill_no=data[i].cost_no)\n p.cost_no = data[i].cost_no\n p.item = data[i].item\n p.fee = data[i].fee\n p.time = data[i].time\n p.dor_no = test.dor_no\n p.status = test.check_paied\n pay_list.append(p)\n\n return render(request, \"student/payment.html\", {'paylog': pay_list,'username':sname})\n\ndef show_stu_resource(request):\n try:\n sno = request.session['userno']\n except Exception as err:\n return render(request,\"index.html\")\n sname=request.session['username']\n return resource(request)\n\ndef show_stu_meeting_room(request):\n try:\n sno = request.session['userno']\n except Exception as err:\n return render(request,\"index.html\")\n sname = request.session['username']\n # 转化成列表\n room_list = list(MeetingRoom.objects.all().values())\n for i in room_list:\n if i['include_medium_device'] == 1:\n i['include_medium_device'] = '有'\n elif i['include_medium_device'] == 0:\n i['include_medium_device'] = '无'\n\n base_stu_meeting_log = MeetingRoomApplymentRecord.objects.filter(sno=sno)\n stu_meeting_log = []\n\n for i in range(0, len(base_stu_meeting_log)):\n order_time_start = list(\n MeetingRoomOrderTime.objects.filter(meeting_room_order_time_no=base_stu_meeting_log[i].time_no_1).values())\n if base_stu_meeting_log[i].time_no_4 is not None:\n order_time_end = list(MeetingRoomOrderTime.objects.filter(\n meeting_room_order_time_no=base_stu_meeting_log[i].time_no_4).values())\n elif base_stu_meeting_log[i].time_no_3 is not None:\n order_time_end = list(MeetingRoomOrderTime.objects.filter(\n meeting_room_order_time_no=base_stu_meeting_log[i].time_no_3).values())\n elif base_stu_meeting_log[i].time_no_2 is not None:\n order_time_end = list(MeetingRoomOrderTime.objects.filter(\n meeting_room_order_time_no=base_stu_meeting_log[i].time_no_2).values())\n else:\n order_time_end = list(MeetingRoomOrderTime.objects.filter(\n meeting_room_order_time_no=base_stu_meeting_log[i].time_no_1).values())\n\n newModel = MeetingLogModel()\n newModel.sno = base_stu_meeting_log[i].sno\n newModel.meeting_room_no = base_stu_meeting_log[i].meeting_room_no\n newModel.book_date = base_stu_meeting_log[i].book_date.strftime('%Y-%m-%d')\n newModel.apply_time = base_stu_meeting_log[i].apply_time.strftime('%Y-%m-%d %H:%M:%S')\n newModel.start_time = order_time_start[0]['start_time'].strftime('%H:%M:%S')\n newModel.end_time = order_time_end[0]['end_time'].strftime('%H:%M:%S')\n if base_stu_meeting_log[i].check_apply_success == 1:\n newModel.check_apply_success = '申请已通过'\n elif base_stu_meeting_log[i].check_apply_success == 0:\n newModel.check_apply_success = '待审核'\n elif base_stu_meeting_log[i].check_apply_success == 2:\n newModel.check_apply_success = '失败'\n\n stu_meeting_log.append(newModel)\n #print(stu_meeting_log)\n\n return render(request, \"student/meeting.html\", {'username': sname, 'userno': sno, 'roomList': room_list,\n 'stuMeetingLog': stu_meeting_log})\n\n\ndef show_stu_book(request):\n try:\n sno = request.session['userno']\n except Exception as err:\n return render(request,\"index.html\")\n sname = request.session['username']\n book_sum = DorBookInf.objects.all().count()\n book_list = DorBookInf.objects.all().values()\n book_borrow_list = DorBookInf.objects.filter(book_borrowman=sname)\n book_share_list = DorBookInf.objects.filter(book_share_man=\"1\", book_borrowman=sname)\n\n return render(request, \"student/book.html\", {'username': sname, 'userno': sno,\n 'book_list': book_list,\n 'book_borrow_list': book_borrow_list,\n 'book_share_list': book_share_list,\n 'book_sum': book_sum})","sub_path":"dor/student_handle/show_stu_all_index.py","file_name":"show_stu_all_index.py","file_ext":"py","file_size_in_byte":5638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"418706410","text":"#!/usr/bin/python\nimport sys\nimport os, os.path\nimport time\nfrom datetime import datetime\n\n\nimport logging\nimport logging.config\n\n\n\nclass aLog(object):\n\n\tdef __init__(self):\n\t\t# log to the console\n\t\tself.log = logging.getLogger('reco')\n\t\tself.log.propagate = False\n\t\tself.log.setLevel(logging.DEBUG)\n\t\tformatter = logging.Formatter('[%(levelname)s]: %(message)s')\n\t\thandler_stream = logging.StreamHandler()\n\t\thandler_stream.setFormatter(formatter)\n\t\thandler_stream.setLevel(logging.DEBUG)\n\t\tself.log.addHandler(handler_stream)\n\n\t\t# log to a file\n\t\tlog_path = \"logs/\"\n\t\tflname = log_path + \"reconews-%s.log\"%datetime.now().strftime('%Y-%m-%d-%I:%M:%S')\n\t\tformatter = logging.Formatter('[LOG]: %(message)s')\n\t\thandler_file = logging.FileHandler(flname)\n\t\thandler_file.setFormatter(formatter)\n\t\thandler_file.setLevel(logging.INFO)\n\t\tself.log.addHandler(handler_file)\n\n###################################################################\n##########################MODULE TESTING###########################\n\n\tdef record(self):\n\t\tself.log.debug('something is terribly wrong')\n\t\tself.log.info('this is a log')\n\t\tself.log.warn('warning. mostly ignored.')\n\t\tself.log.error('Error happened!')\n\t\tself.log.critical('critical')\n\n###################################################################\n###################################################################\n\nalogger = aLog()\n\n\nif __name__ == \"__main__\":\n\n###################################################################\n##########################MODULE TESTING###########################\n\talogger.record()\n###################################################################\n###################################################################","sub_path":"a_logger.py","file_name":"a_logger.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"398651771","text":"\"\"\"\nModification of the docutils \".. include\" directive to make it\nfail gracefully if the included file does not exist.\nThe original code is taken from docutils source:\n\n https://sourceforge.net/p/docutils/code/HEAD/tree/trunk/docutils/docutils/parsers/rst/directives/misc.py \n\"\"\"\n\n# TODO: implement SoftInclude directive\n\nimport sys\nimport os.path\nimport re\nimport time\nfrom docutils import io, nodes, statemachine, utils\nfrom docutils.utils.error_reporting import SafeString, ErrorString\nfrom docutils.utils.error_reporting import locale_encoding\nfrom docutils.parsers.rst import Directive, convert_directive_function\nfrom docutils.parsers.rst import directives, roles, states\nfrom docutils.parsers.rst.directives.body import CodeBlock, NumberLines\nfrom docutils.parsers.rst.roles import set_classes\nfrom docutils.transforms import misc\n\n\nclass Include(Directive):\n\n \"\"\"\n Include content read from a separate source file.\n\n Content may be parsed by the parser, or included as a literal\n block. The encoding of the included file can be specified. Only\n a part of the given file argument may be included by specifying\n start and end line or text to match before and/or after the text\n to be used.\n \"\"\"\n\n required_arguments = 1\n optional_arguments = 0\n final_argument_whitespace = True\n option_spec = {'literal': directives.flag,\n 'code': directives.unchanged,\n 'encoding': directives.encoding,\n 'tab-width': int,\n 'start-line': int,\n 'end-line': int,\n 'start-after': directives.unchanged_required,\n 'end-before': directives.unchanged_required,\n # ignored except for 'literal' or 'code':\n 'number-lines': directives.unchanged, # integer or None\n 'class': directives.class_option,\n 'name': directives.unchanged}\n\n standard_include_path = os.path.join(os.path.dirname(states.__file__),\n 'include')\n\n def run(self):\n \"\"\"Include a file as part of the content of this reST file.\"\"\"\n if not self.state.document.settings.file_insertion_enabled:\n raise self.warning('\"%s\" directive disabled.' % self.name)\n source = self.state_machine.input_lines.source(\n self.lineno - self.state_machine.input_offset - 1)\n source_dir = os.path.dirname(os.path.abspath(source))\n path = directives.path(self.arguments[0])\n if path.startswith('<') and path.endswith('>'):\n path = os.path.join(self.standard_include_path, path[1:-1])\n path = os.path.normpath(os.path.join(source_dir, path))\n path = utils.relative_path(None, path)\n path = nodes.reprunicode(path)\n encoding = self.options.get(\n 'encoding', self.state.document.settings.input_encoding)\n e_handler=self.state.document.settings.input_encoding_error_handler\n tab_width = self.options.get(\n 'tab-width', self.state.document.settings.tab_width)\n try:\n self.state.document.settings.record_dependencies.add(path)\n include_file = io.FileInput(source_path=path,\n encoding=encoding,\n error_handler=e_handler)\n except UnicodeEncodeError as error:\n raise self.severe(u'Problems with \"%s\" directive path:\\n'\n 'Cannot encode input file path \"%s\" '\n '(wrong locale?).' %\n (self.name, SafeString(path)))\n except IOError as error:\n raise self.severe(u'Problems with \"%s\" directive path:\\n%s.' %\n (self.name, ErrorString(error)))\n startline = self.options.get('start-line', None)\n endline = self.options.get('end-line', None)\n try:\n if startline or (endline is not None):\n lines = include_file.readlines()\n rawtext = ''.join(lines[startline:endline])\n else:\n rawtext = include_file.read()\n except UnicodeError as error:\n raise self.severe(u'Problem with \"%s\" directive:\\n%s' %\n (self.name, ErrorString(error)))\n # start-after/end-before: no restrictions on newlines in match-text,\n # and no restrictions on matching inside lines vs. line boundaries\n after_text = self.options.get('start-after', None)\n if after_text:\n # skip content in rawtext before *and incl.* a matching text\n after_index = rawtext.find(after_text)\n if after_index < 0:\n raise self.severe('Problem with \"start-after\" option of \"%s\" '\n 'directive:\\nText not found.' % self.name)\n rawtext = rawtext[after_index + len(after_text):]\n before_text = self.options.get('end-before', None)\n if before_text:\n # skip content in rawtext after *and incl.* a matching text\n before_index = rawtext.find(before_text)\n if before_index < 0:\n raise self.severe('Problem with \"end-before\" option of \"%s\" '\n 'directive:\\nText not found.' % self.name)\n rawtext = rawtext[:before_index]\n\n include_lines = statemachine.string2lines(rawtext, tab_width,\n convert_whitespace=True)\n if 'literal' in self.options:\n # Convert tabs to spaces, if `tab_width` is positive.\n if tab_width >= 0:\n text = rawtext.expandtabs(tab_width)\n else:\n text = rawtext\n literal_block = nodes.literal_block(rawtext, source=path,\n classes=self.options.get('class', []))\n literal_block.line = 1\n self.add_name(literal_block)\n if 'number-lines' in self.options:\n try:\n startline = int(self.options['number-lines'] or 1)\n except ValueError:\n raise self.error(':number-lines: with non-integer '\n 'start value')\n endline = startline + len(include_lines)\n if text.endswith('\\n'):\n text = text[:-1]\n tokens = NumberLines([([], text)], startline, endline)\n for classes, value in tokens:\n if classes:\n literal_block += nodes.inline(value, value,\n classes=classes)\n else:\n literal_block += nodes.Text(value, value)\n else:\n literal_block += nodes.Text(text, text)\n return [literal_block]\n if 'code' in self.options:\n self.options['source'] = path\n codeblock = CodeBlock(self.name,\n [self.options.pop('code')], # arguments\n self.options,\n include_lines, # content\n self.lineno,\n self.content_offset,\n self.block_text,\n self.state,\n self.state_machine)\n return codeblock.run()\n self.state_machine.insert_input(include_lines, path)\n return []\n\n","sub_path":"sphinxutils/softinclude.py","file_name":"softinclude.py","file_ext":"py","file_size_in_byte":7586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"12979981","text":"# coding: utf-8\n\nfrom django.contrib.auth.models import User, Group\nfrom django.shortcuts import get_object_or_404, render_to_response, render\nfrom django.contrib.auth.decorators import login_required\nfrom django.template import RequestContext\nfrom django.http import HttpResponse\nfrom django.core.mail import send_mail\n\nfrom .forms import *\n\nfrom models import *\nfrom Login.models import Usuario\n\nfrom random import randint\n\nimport datetime\n\n# Create your views here.\n\ndef checkAdmin(user):\n\tif user.groups.filter(name='administradores').exists():\n\t\treturn True\n\telse:\n\t\treturn False\n\n@login_required\ndef index(request):\n\tadmin = checkAdmin(request.user)\n\n\tusuario = Usuario.objects.get(user=request.user)\n\teventos = Evento.objects.all().order_by('-created')[:20]\n\tusuarios = User.objects.all().order_by('-date_joined')[:20]\n\n\ttimeline = []\n\n\t#Cria lista de tuplas (Object, Data)\n\tfor e in eventos:\n\t\ttimeline.append((e, e.created))\n\n\tfor u in usuarios:\n\t\ttimeline.append((u, u.date_joined))\n\n\t#Faz o sort por datas e depois deixa só os Objetos na lista\n\ttimeline = sorted(timeline, key=lambda tup: tup[1], reverse=True)\n\ttimeline = [x[0] for x in timeline]\n\n\ttimeline = timeline[:15]\n\ttimeline_new = []\n\n\t#Transforma a lista novamente em tuplas do tipo (Object, 'tipo')\n\tfor item in timeline:\n\t\tif isinstance(item, User):\n\t\t\ttimeline_new.append((item, 'user'))\n\t\telif isinstance(item, Evento):\n\t\t\ttimeline_new.append((item, 'evento'))\n\n\treturn render(request, 'index.html', \n\t\t{'administrador': admin, \n\t\t'usuario': usuario,\n\t\t'timeline': timeline_new, \n\t\t'date_now': datetime.datetime.now(), })\n\n@login_required\ndef exibirEventos(request):\n\tadmin = checkAdmin(request.user)\n\n\teventos = Evento.objects.all();\n\n\tusuario = Usuario.objects.get(user=request.user)\n\n\treturn render(request, 'eventos.html',\n\t\t{'administrador': admin, \n\t\t'eventos': eventos, \n\t\t'usuario': usuario, })\n\n@login_required\ndef exibirEvento(request, pk):\n\tevento = get_object_or_404(Evento, pk=pk)\n\treturn render(request, 'evento.html', \n\t\t{'evento': evento, })\n\n@login_required\ndef deletarEvento(request, pk):\n\tadmin = checkAdmin(request.user)\n\tevento = get_object_or_404(Evento, pk=pk)\n\ttext = \"O evento \" + evento.nome + \" foi deletado com sucesso.\";\n\treturn render(request, 'index.html', \n\t\t{'modal':True, \n\t\t'modal_header': 'Evento deletado', \n\t\t'text': text })\n\n@login_required\ndef novoEvento(request):\n\tadmin = checkAdmin(request.user)\n\tif admin:\n\t\tif request.method == 'POST':\n\t\t\tform = NovoEventoForm(request.POST, request.FILES)\n\t\t\tif form.is_valid():\n\t\t\t\tnovo_evento = Evento.objects.create(nome=form.cleaned_data['nome'],\n\t\t\t\t\tdescricao=form.cleaned_data['descricao'],\n\t\t\t\t\tlocal=form.cleaned_data['local'],\n\t\t\t\t\tdata=form.cleaned_data['data'],\n\t\t\t\t\thora=form.cleaned_data['hora'], )\n\n\t\t\t\tusuario = Usuario.objects.get(user=request.user)\n\t\t\t\tnovo_evento.criado_por = usuario\n\t\t\t\tnovo_evento.save()\n\n\t\t\t\treturn render(request, 'index.html', \n\t\t\t\t\t{'administrador': admin, \n\t\t\t\t\t'modal':True, \n\t\t\t\t\t'modal_header': 'Cadastro de Evento', \n\t\t\t\t\t'text':'Evento cadastrado com sucesso!'})\n\t\t\telse:\n\t\t\t\treturn render(request, 'novoevento.html', \n\t\t\t\t\t{'administrador': admin, 'form': form, })\n\t\telse:\n\t\t\tform = NovoEventoForm()\n\t\t\treturn render(request, 'novoevento.html', \n\t\t\t\t{'administrador': admin, 'form': form, })\n\telse: # caso não seja administrador\n\t\treturn render(request, 'errorpage.html', \n\t\t\t{'error': 'Você não tem permissão para acessar essa página'})\n\n\n@login_required\ndef novaChaveUsuario(request):\n\tadmin = checkAdmin(request.user)\n\tif admin:\t\t\n\t\tif request.method == 'POST':\n\t\t\tform = NovaChaveUsuarioForm(request.POST, request.FILES)\n\t\t\tif form.is_valid():\n\t\t\t\t#Caso já exista\n\t\t\t\tif User.objects.filter(email=form.cleaned_data['email']).exists() or ChaveUsuario.objects.filter(email=form.cleaned_data['email']).exists():\n\t\t\t\t\treturn render(request, 'errorpage.html', \n\t\t\t\t\t\t{'error': 'Usuário já existe ou já tem uma chave de registro.'})\n\n\t\t\t\telse: #Gerar chave e enviar email caso não exista\n\t\t\t\t\tkey = gerarChave()\n\t\t\t\t\tnovaChave = ChaveUsuario.objects.create(email=form.cleaned_data['email'],\n\t\t\t\t\t\tchave=key)\n\t\t\t\t\tnovaChave.save()\n\n\t\t\t\t\tsend_mail('Convite SisGIM', \n\t\t\t\t\t\t'Olá, \\n' \n\t\t\t\t\t\t+ 'Você foi convidado para se cadastrar no sistema do GIM, '\n\t\t\t\t\t\t+ 'para tanto, siga para o site de registro e utilize o seguinte código: \\n' \n\t\t\t\t\t\t+ key + '\\n' \n\t\t\t\t\t\t+ 'Obrigado por fazer parte do GIM.',\n\t\t\t\t\t\t'[SisGIM] Convite', \n\t\t\t\t\t\t[form.cleaned_data['email']],\n\t\t\t\t\t\tmakeHtmlMessage(key))\n\t\t\t\t\treturn render(request, 'index.html', {'modal':True, 'text':'Chave enviada com sucesso!'})\n\n\t\telse: # caso o request.method não seja POST\n\t\t\tform = NovaChaveUsuarioForm()\n\t\t\treturn render(request, 'novachaveusuario.html', \n\t\t\t\t{'administrador': admin, 'form': form})\n\n\telse: # caso não seja administrador\n\t\treturn render(request, 'errorpage.html', \n\t\t\t{'error': 'Você não tem permissão para acessar essa página'})\n\ndef gerarChave():\n\tp1 = str(randint(0,9)) + chr(randint(ord('a'), ord('z')))\n\tp2 = str(randint(0,9)) + chr(randint(ord('A'), ord('Z')))\n\tp3 = str(randint(0,9)) + chr(randint(ord('a'), ord('z')))\n\tp4 = str(randint(0,9)) + chr(randint(ord('A'), ord('Z')))\n\treturn p1 + p2 + p3 + p4\n\ndef makeHtmlMessage(key):\n\treturn '

Olá,

Você foi convidado para se cadastrar no sistema do GIM, para tanto, siga para o site de registro e utilize o seguinte código:

' + key + '

Obrigado por fazer parte do GIM.

'\n\n","sub_path":"Sistema/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"446750743","text":"\n\"\"\"\n# @Time : 2019-10-11 09:50\n# @Author : Function\n# @FileName : table_write.py\n# @Software: PyCharm\n\n\"\"\"\ndef get_length(ts):\n ls = []\n hs = ts['head']\n for h in hs:\n ls.append(len(h))\n bs = ts['body']\n for b in bs:\n for i in range(len(ls)):\n li = len(b[i])\n if ls[i] < li:\n ls[i] = li\n return ls\ndef out_line(ts):\n rs = '+'\n ls = get_length(ts)\n for l in ls:\n rs += '-'*(l+2)+'+'\n rs += '\\n'\n return rs\n\ndef out_head(ts):\n rs = '|'\n ls = get_length(ts)\n hs = ts['head']\n for i in range(len(ls)):\n rs += ''+hs[i]+''*(ls[i]-len(hs[i]))+' |'\n rs += '\\n'\n return rs\n\ndef out_body(ts):\n rs = ''\n ls = get_length(ts)\n bs = ts['body']\n for i in bs:\n r ='|'\n for j in range(len(ls)):\n r += ''+i[j]+''*(ls[j]-len(i[j]))+' |'\n rs += r + '\\n'\n return rs\ndef out_table(ts):\n rs = out_line(ts)\n rs += out_head(ts)\n rs += out_line(ts)\n rs += out_body(ts)\n rs += out_line(ts)\n return rs\n\nif __name__ == '__main__':\n T = {\n 'head':['用例总数','成功数','失败数','成功率','失败率'],\n 'body':[\n ['100','50', '50', '20%','80%']\n ]\n }\n print(out_table(T),end='')\n print('-------------------')\n print(out_table(T))\n","sub_path":"AutoUI/Util/table_write.py","file_name":"table_write.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"435035505","text":"import torch\nfrom torch import autograd\nimport pandas as pd\nfrom mnist_model import ConvNN\n\n\ndef main():\n test_data = pd.read_csv('./test.csv').values\n X = test_data.reshape((-1, 28, 28))\n model = ConvNN()\n model.load_state_dict(torch.load('./mnist-model.pt'))\n model.eval()\n x = autograd.Variable(torch.Tensor(X))\n max_, y_hat = torch.max(model(x), dim=1)\n output_df = pd.DataFrame(y_hat.numpy())\n output_df.index += 1\n output_df.index.name = 'ImageId'\n output_df.to_csv('./sample-output.csv', header=['Label'])\n\nif __name__ == '__main__':\n main()\n","sub_path":"evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"47343327","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# \n# Copyright (c) 2017 Nothing, Inc. All Rights Reserved\n# \n\n\"\"\"\nFile: sum1-100.py\nAuthor: guyu(dsgdtc@163.com)\nDate: 2018/12/28 15:19\n\"\"\"\nimport sys\ndef sum_cycle(n):\n '''\n 1 to n,The sum function\n '''\n sum = 0\n for i in range(1,n + 1):\n sum += i\n return sum\n\ndef sum_recu(n):\n '''\n 1 to n,The sum function\n '''\n if n > 0:\n res = n + sum_recu(n - 1)\n input(\"etc...\")\n print(res)\n print(\"---before return do sth\")\n return res\n else:\n return 0\nprint(\"循环求和:\",sum_cycle(5))\nprint(\"递归求和:\",sum_recu(5))","sub_path":"leetcode/lc-all-solutions-master/022.generate-parentheses/sum1-100.py","file_name":"sum1-100.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"411072065","text":"def multiplicar(matrizA, matrizB):\n linhasA = len(matrizA)\n linhasB = len(matrizB)\n colunasA = len(matrizA[0])\n colunasB = len(matrizB[0])\n\n matrizC = []\n\n for linha in range(linhasA):\n matrizC.append([])\n for coluna in range(colunasB):\n matrizC[linha].append(0)\n for i in range(colunasA):\n matrizC[linha][coluna] += matrizA[linha][i] * matrizB[i][coluna]\n\n for i in range(len(matrizC)):\n for j in range(len(matrizC[i])):\n if j != len(matrizC[i])-1:\n print(matrizC[i][j], end=' ')\n else:\n print(matrizC[i][j])\n\n\ndados = input().split()\n\nquantidadeLinhasMatrizA = int(dados[0])\nquantidadeColunasMatrizA = int(dados[1])\nquantidadeLinhasMatrizB = int(dados[1])\nquantidadeColunasMatrizB = int(dados[2])\n\nmatrizA = []\nmatrizB = []\n\nfor i in range(quantidadeLinhasMatrizA):\n matrizA.append([int(x) for x in input().split()])\n\nfor i in range(quantidadeLinhasMatrizB):\n matrizB.append([int(x) for x in input().split()])\n\nmultiplicar(matrizA, matrizB)","sub_path":"Exercícios Resolvidos/The Huxley/746 - Multiplicação de Matrizes - 2.py","file_name":"746 - Multiplicação de Matrizes - 2.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"353846315","text":"# 앙상블 모델로 리뉴얼하시오.\nimport numpy as np\nfrom keras.models import Sequential, Model\nfrom keras.layers import Dense, LSTM, Input\nfrom keras.callbacks import EarlyStopping\nfrom keras.layers import concatenate\nearly = EarlyStopping(monitor = 'loss', mode = 'min', patience = 10)\n\n# 1. 데이터 구성\nx1 = np.array([[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6],\n [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10],\n [9, 10, 11], [10, 11, 12],\n [20, 30, 40], [30, 40, 50], [40, 50, 60]])\nx2 = np.array([[10, 20, 30], [20, 30, 40], [30, 40, 50], [40, 50, 60],\n [50, 60, 70], [60, 70, 80], [70, 80, 90], [80, 90, 100],\n [90, 100, 110], [100, 110, 120],\n [2, 3, 4], [3, 4, 5], [4, 5, 6]])\n\ny = np.array([4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 50, 60, 70])\n\nx1_predict = np.array([55, 65, 75])\nx2_predict = np.array([65, 75, 85])\n\nprint(\"x1.shape : \", x1.shape) # res : (13, 3)\nprint(\"x2.shape : \", x2.shape) # res : (13, 3)\nprint(\"y.shape : \", y.shape) # res : (13, )\n\n'''\nx1 = x1.reshape(x1.shape[0], x1.shape[1], 1)\n# 13 3 1\n\nx2 = x2.reshape(x2.shape[0], x2.shape[1], 1)\n# 13 3 1\n# print(x1.shape)\n# print(x2.shape)\n\n\n# 2. 모델 구성\n# 2-1. 인풋 레이어\ninput1 = Input(shape = (3, 1))\ndense1 = LSTM(150)(input1)\ndense1_1 = Dense(81)(dense1)\ndense1_2 = Dense(88)(dense1_1)\ndense1_3 = Dense(98)(dense1_2)\ndense1_4 = Dense(48)(dense1_3)\ndense1_5 = Dense(86)(dense1_4)\n\n# 2-2 인풋 레이어\ninput2 = Input(shape = (3, 1))\ndense2 = LSTM(194)(input2)\ndense2_1 = Dense(488)(dense2)\ndense2_2 = Dense(815)(dense2_1)\ndense2_3 = Dense(128)(dense2_2)\ndense2_4 = Dense(83)(dense2_3)\ndense2_5 = Dense(88)(dense2_4)\n\n# 2-3. 레이어 병합\nmerge1 = concatenate([dense1_5, dense2_5])\nmiddle1 = Dense(51)(merge1)\nmiddle2 = Dense(95)(middle1)\nmiddle3 = Dense(58)(middle2)\nmiddle4 = Dense(54)(middle3)\n\n# 2-4. 아웃풋 레이어\noutput1 = Dense(50)(middle4)\noutput2 = Dense(148)(output1)\noutput3 = Dense(16)(output2)\noutput4 = Dense(168)(output3)\noutput5 = Dense(1)(output4)\n\n# 2-5. 모델링\nmodel = Model(inputs = [input1, input2],\n outputs = output5)\n\nmodel.summary()\n\n\n\n# 3. 실행\nmodel.compile(loss = 'mse', optimizer = 'adam', metrics = ['mse'])\nmodel.fit([x1, x2], y,\n epochs = 1000, batch_size = 32)\n # callbacks = [early])\n\nx1_predict = x1_predict.reshape(1, 3, 1)\nx2_predict = x2_predict.reshape(1, 3, 1)\n\n\n# 4. 평가 및 예측\nprint(x1_predict)\nprint(x2_predict)\n\ny_predict = model.predict([x1_predict, x2_predict])\n\nprint(y_predict)\n'''\n'''\n[[[55]\n [65]\n [75]]]\n[[[65]\n [75]\n [85]]]\n[[84.22178]]\n\n[[84.29394]]\n\n[[82.02529]]\n\n[[83.22624]]\n\n[[79.748474]]\n'''","sub_path":"keras/keras33_lstm_ensemble.py","file_name":"keras33_lstm_ensemble.py","file_ext":"py","file_size_in_byte":2775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"78138192","text":"# -*- coding: utf-8 -*-\n\"\"\"\nYou are given two non-empty linked lists representing two non-negative integers. \nThe digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.\n\nYou may assume the two numbers do not contain any leading zero, except the number 0 itself.\n\"\"\"\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution:\n def addTwoNumbers(self, l1, l2):\n carry = 0\n head = node = ListNode('#')\n \n while l1 or l2 or carry:\n num1 = l1.val if l1 else 0\n num2 = l2.val if l2 else 0\n \n carry, newsum = divmod(carry + num1 + num2, 10)\n # divmod (13, 10) = (1, 3)\n # divmod (3, 10) = (0, 3)\n \n node.next = ListNode(newsum)\n node = node.next\n \n l1 = l1.next if l1 else None\n l2 = l2.next if l2 else None\n \n return head.next","sub_path":"Leetcode/2_Add_Two_Numbers.py","file_name":"2_Add_Two_Numbers.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"601239444","text":"from tripy.article.article import ALL_ARTICLES, SENTIMENT\r\nfrom tripy.geo.locations import INDEX_BY_NAME, NAME_BY_INDEX\r\nimport numpy as np \r\nimport json\r\nimport os\r\nimport plotly.graph_objects as go\r\n\r\nclass Sentiment_graph:\r\n def __init__(self):\r\n self.sentiment = SENTIMENT\r\n\r\n def plot_graph(self):\r\n n = len(self.sentiment)\r\n x, y = zip(*self.sentiment.items())\r\n x1 = list(x)\r\n for i in range(len(x)):\r\n x1[i] = NAME_BY_INDEX[x[i]]\r\n\r\n width=[0.35]*n\r\n\r\n fig = go.Figure(data=[\r\n go.Bar(x=x1, y=y, text=y, textposition='outside', texttemplate='%{text:.4f}',width=width)\r\n ])\r\n fig.update_layout(title_text='Sentiment Score of All Country', barmode='group', yaxis=dict(range=[min(y)-1,max(y)+1]))\r\n fig.write_html(os.getcwd()+f'{os.sep}tripy{os.sep}assets{os.sep}datas{os.sep}'+'sentiment.html')\r\n\r\n\r\n\r\nclass Probability_distribution:\r\n def __init__(self, routes, country):\r\n self._routes = routes\r\n self._country = country\r\n\r\n\r\n def plot_graph(self):\r\n\r\n n = len(self._routes)\r\n lists = sorted(self._routes.items(), reverse=True)\r\n width = [0.35]*n\r\n y, x = zip(*lists)\r\n total_score = sum(y)\r\n\r\n y = [i/total_score for i in y]\r\n\r\n x1 = list(x)\r\n for i in range(len(x1)):\r\n for j in range(len(x1[i])):\r\n for k in range(len(x1[i][j])):\r\n x1[i][j][k] = NAME_BY_INDEX[x[i][j][k]]\r\n x1[i][j] = '
'.join(x1[i][j])\r\n x1[i] = ','.join(x1[i])\r\n\r\n fig = go.Figure(data=[\r\n go.Bar(x=x1, y=y, text=y, textposition='outside', texttemplate='%{text:0.4f}',width=width)\r\n ])\r\n fig.update_layout(title_text='Probability Distribution of '+self._country, barmode='group', yaxis=dict(range=[0,1]))\r\n fig.write_html(os.getcwd()+f'{os.sep}tripy{os.sep}assets{os.sep}datas{os.sep}'+self._country+'probability.html')\r\n \r\n \r\n\r\nclass Graph:\r\n def __init__(self, country):\r\n self._articles = ALL_ARTICLES[INDEX_BY_NAME[country]]\r\n self._total_words = []\r\n self._country = country\r\n self._neg_words = []\r\n self._pos_words = []\r\n self._stop_words = []\r\n self._total_total_word = 0\r\n self._total_neg_word = 0\r\n self._total_pos_word = 0\r\n self._total_stop_word = 0\r\n for i in range(len(self._articles)):\r\n self._total_words.append(self._articles[i].get_total_word())\r\n self._total_total_word += self._total_words[i]\r\n self._stop_words.append(self._articles[i].get_stopword_freq())\r\n self._total_stop_word += self._stop_words[i]\r\n self._pos_words.append(self._articles[i].get_pos_freq())\r\n self._total_pos_word += self._pos_words[i]\r\n self._neg_words.append(self._articles[i].get_neg_freq())\r\n self._total_neg_word += self._neg_words[i]\r\n\r\n\r\n def plot_all_graph(self):\r\n x1 = [\"Article 1\",\"Article 2\",\"Article 3\",\"Article 4\",\"Article 5\"]\r\n fig = go.Figure(data=[\r\n go.Bar(x=x1, y=self._total_words, name='Total words', text=self._total_words, textposition='auto'),\r\n go.Bar(x=x1, y=self._stop_words, name='Stop words', text=self._stop_words, textposition='auto'),\r\n go.Bar(x=x1, y=self._pos_words, name='Positive words', text=self._pos_words, textposition='auto'),\r\n go.Bar(x=x1, y=self._neg_words, name='Negative words', text=self._neg_words, textposition='auto')\r\n ])\r\n fig.update_layout(title_text='Total Words in '+self._country+' articles', barmode='group')\r\n fig.write_html(os.getcwd()+f'{os.sep}tripy{os.sep}assets{os.sep}datas{os.sep}'+self._country+'graph.html')\r\n","sub_path":"tripy/article/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":3799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"92476295","text":"#! python\r\n# coding: utf-8\r\n\t\r\nimport math\t\r\n\r\ndata = list(map(float, input('Дай тр�� дійсні числа\\r\\n').split()))\r\n\r\na = data[0]\r\nb = data[1]\r\nc = data[2]\r\n\r\nif (c == 0.0):\r\n\tprint('На нуль ділиті нізя таваріщ')\r\n\t\r\nf = (1/(c*math.sqrt(2*math.pi)))*math.exp(((-1)*(a-b)**2)/(2*c**2))\r\n\r\nprint(str(f))","sub_path":"lab4_2.py","file_name":"lab4_2.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"3048832","text":"from django.shortcuts import render\n\n# Create your views here.\n\n\n\nposts = [ \t\t\t\t\t\t\t\t#gia na perasoume dedomena sthn selida dynamikos(gai thn wra)\n {\n 'author': 'CoreyMS',\n 'title': 'Blog Post 1',\n 'content': 'First post content',\n 'date_posted': 'August 27, 2018'\n },\n {\n 'author': 'Jane Doe',\n 'title': 'Blog Post 2',\n 'content': 'Second post content',\n 'date_posted': 'August 28, 2018'\n }\n]\n\n\ndef home(request):\n\tcontext = {\t\t\t\t\t\t#create dictionary that willtake posts dictionary with the parakatw tropo\n\t\t'posts' : posts \t\t\t#'key':value value=dictionary post\n\n\t}\n\treturn render(request, 'homescreen/home.html', context) #it shows the home.html render(request,path html,emfanisi dedomenwn) \n\n\ndef about(request):\n return render(request, 'homescreen/about.html', {'title':'about'}) #it shows the about.html render(request,path html)\n","sub_path":"homescreen/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"188247013","text":"#\r\n# @lc app=leetcode.cn id=3 lang=python3\r\n#\r\n# [3] 无重复字符的最长子串\r\n#\r\n# https://leetcode.cn/problems/longest-substring-without-repeating-characters/description/\r\n#\r\n# algorithms\r\n# Medium (38.99%)\r\n# Likes: 8116\r\n# Dislikes: 0\r\n# Total Accepted: 2M\r\n# Total Submissions: 5M\r\n# Testcase Example: '\"abcabcbb\"'\r\n#\r\n# 给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。\r\n# \r\n# \r\n# \r\n# 示例 1:\r\n# \r\n# \r\n# 输入: s = \"abcabcbb\"\r\n# 输出: 3 \r\n# 解释: 因为无重复字符的最长子串是 \"abc\",所以其长度为 3。\r\n# \r\n# \r\n# 示例 2:\r\n# \r\n# \r\n# 输入: s = \"bbbbb\"\r\n# 输出: 1\r\n# 解释: 因为无重复字符的最长子串是 \"b\",所以其长度为 1。\r\n# \r\n# \r\n# 示例 3:\r\n# \r\n# \r\n# 输入: s = \"pwwkew\"\r\n# 输出: 3\r\n# 解释: 因为无重复字符的最长子串是 \"wke\",所以其长度为 3。\r\n# 请注意,你的答案必须是 子串 的长度,\"pwke\" 是一个子序列,不是子串。\r\n# \r\n# \r\n# \r\n# \r\n# 提示:\r\n# \r\n# \r\n# 0 <= s.length <= 5 * 10^4\r\n# s 由英文字母、数字、符号和空格组成\r\n# \r\n# \r\n#\r\n\r\n# @lc code=start\r\nclass Solution:\r\n def lengthOfLongestSubstring(self, s: str) -> int:\r\n w = {}\r\n res = l = r = 0\r\n while r < len(s):\r\n rt = s[r]\r\n r += 1\r\n w[rt] = w.get(rt, 0) + 1\r\n while w[rt] > 1:\r\n lt = s[l]\r\n l += 1\r\n w[lt] -= 1\r\n res = max(res, r - l)\r\n return res\r\n\r\n# @lc code=end\r\n\r\n","sub_path":"pkm/lbld/3.无重复字符的最长子串.py","file_name":"3.无重复字符的最长子串.py","file_ext":"py","file_size_in_byte":1550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"79420153","text":"# Copyright 2019 Red Hat, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# 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\"\"\"\nUtility functions for blackbox testing.\n\"\"\"\n# isort: STDLIB\nimport os\nimport random\nimport string\nfrom subprocess import PIPE, Popen\nfrom tempfile import NamedTemporaryFile\n\n# isort: THIRDPARTY\nimport psutil\n\n\ndef random_string(length=4):\n \"\"\"\n Generates a random string\n :param length: Length of random string\n :return: String\n \"\"\"\n return \"{0}\".format(\n \"\".join(random.choice(string.ascii_uppercase) for _ in range(length))\n )\n\n\ndef process_exists(name):\n \"\"\"\n Look through processes, using their pids, to find one matching 'name'.\n Return None if no such process found, else return the pid.\n :param name: name of process to check\n :type name: str\n :return: pid or None\n :rtype: int or NoneType\n \"\"\"\n for proc in psutil.process_iter([\"name\"]):\n try:\n if proc.name() == name:\n return proc.pid\n except psutil.NoSuchProcess:\n pass\n\n return None\n\n\ndef exec_command(cmd):\n \"\"\"\n Executes the specified infrastructure command.\n\n :param cmd: command to execute\n :type cmd: list of str\n :returns: standard output\n :rtype: str\n :raises RuntimeError: if exit code is non-zero\n \"\"\"\n exit_code, stdout_text, stderr_text = exec_test_command(cmd)\n\n if exit_code != 0:\n raise RuntimeError(\n \"exec_command: non-zero exit code: %d\\nSTDOUT=%s\\nSTDERR=%s\"\n % (exit_code, stdout_text, stderr_text)\n )\n return stdout_text\n\n\ndef exec_test_command(cmd):\n \"\"\"\n Executes the specified test command\n :param cmd: Command and arguments as list\n :type cmd: list of str\n :returns: (exit code, std out text, std err text)\n :rtype: triple of int * str * str\n \"\"\"\n process = Popen(cmd, stdout=PIPE, stderr=PIPE, close_fds=True, env=os.environ)\n result = process.communicate()\n return (\n process.returncode,\n bytes(result[0]).decode(\"utf-8\"),\n bytes(result[1]).decode(\"utf-8\"),\n )\n\n\nclass RandomKeyTmpFile:\n \"\"\"\n Generate a random passphrase and put it in a temporary file.\n \"\"\"\n\n def __init__(self, key_bytes=32):\n \"\"\"\n Initializer\n\n :param int key_bytes: the desired length of the key in bytes\n \"\"\"\n self._tmpfile = NamedTemporaryFile(\"wb\")\n with open(\"/dev/urandom\", \"rb\") as urandom_f:\n random_bytes = urandom_f.read(key_bytes)\n self._tmpfile.write(random_bytes)\n self._tmpfile.flush()\n\n def tmpfile_name(self):\n \"\"\"\n Get the name of the temporary file.\n \"\"\"\n return self._tmpfile.name\n\n def close(self):\n \"\"\"\n Close and delete the temporary file.\n \"\"\"\n self._tmpfile.close()\n\n def __enter__(self):\n \"\"\"\n For use with the \"with\" keyword.\n\n :return str: the path of the file with the random key\n \"\"\"\n return self._tmpfile.name\n\n def __exit__(self, exc_type, exc_value, traceback):\n try:\n self._tmpfile.close()\n except Exception as error:\n if exc_value is None:\n raise error\n\n raise error from exc_value\n","sub_path":"tests/blackbox/testlib/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"534852996","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\nimport os\nimport uuid\nfrom typing import List\n\nservice_name = os.getenv('SW_AGENT_NAME') or 'Python Service Name' # type: str\nservice_instance = os.getenv('SW_AGENT_INSTANCE') or str(uuid.uuid1()).replace('-', '') # type: str\ncollector_address = os.getenv('SW_AGENT_COLLECTOR_BACKEND_SERVICES') or '127.0.0.1:11800' # type: str\nprotocol = (os.getenv('SW_AGENT_PROTOCOL') or 'grpc').lower() # type: str\nauthentication = os.getenv('SW_AGENT_AUTHENTICATION') # type: str\nlogging_level = os.getenv('SW_AGENT_LOGGING_LEVEL') or 'INFO' # type: str\ndisable_plugins = (os.getenv('SW_AGENT_DISABLE_PLUGINS') or '').split(',') # type: List[str]\nmysql_trace_sql_parameters = True if os.getenv('SW_MYSQL_TRACE_SQL_PARAMETERS') and \\\n os.getenv('SW_MYSQL_TRACE_SQL_PARAMETERS') == 'True' else False # type: bool\nmysql_sql_parameters_max_length = int(os.getenv('SW_MYSQL_SQL_PARAMETERS_MAX_LENGTH') or '512') # type: int\nignore_suffix = os.getenv('SW_IGNORE_SUFFIX') or '.jpg,.jpeg,.js,.css,.png,.bmp,.gif,.ico,.mp3,' \\\n '.mp4,.html,.svg ' # type: str\nflask_collect_http_params = True if os.getenv('SW_FLASK_COLLECT_HTTP_PARAMS') and \\\n os.getenv('SW_FLASK_COLLECT_HTTP_PARAMS') == 'True' else False # type: bool\nhttp_params_length_threshold = int(os.getenv('SW_HTTP_PARAMS_LENGTH_THRESHOLD') or '1024') # type: int\ndjango_collect_http_params = True if os.getenv('SW_DJANGO_COLLECT_HTTP_PARAMS') and \\\n os.getenv('SW_DJANGO_COLLECT_HTTP_PARAMS') == 'True' else False # type: bool\ncorrelation_element_max_number = int(os.getenv('SW_CORRELATION_ELEMENT_MAX_NUMBER') or '3') # type: int\ncorrelation_value_max_length = int(os.getenv('SW_CORRELATION_VALUE_MAX_LENGTH') or '128') # type: int\n\n\ndef init(\n service: str = None,\n instance: str = None,\n collector: str = None,\n protocol_type: str = 'grpc',\n token: str = None,\n):\n global service_name\n service_name = service or service_name\n\n global service_instance\n service_instance = instance or service_instance\n\n global collector_address\n collector_address = collector or collector_address\n\n global protocol\n protocol = protocol_type or protocol\n\n global authentication\n authentication = token or authentication\n","sub_path":"skywalking/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"233196500","text":"# coding=utf-8\r\nimport xlrd\r\nimport xlsxwriter\r\nimport datetime\r\n\r\nWorkbook_In = xlrd.open_workbook(\"data.xlsx\") # 打开数据表格\r\nSheet_In = Workbook_In.sheet_by_name(\"Sheet1\") # 注意sheet的名称\r\nTitle = Sheet_In.row(0) # 表头\r\nOrder_Number = Sheet_In.nrows # 订单个数\r\nMachine_Number = 1 # 机器个数\r\nOrder_List = [] # 订单列表\r\nMachine_Name = [] # 机器名称列表\r\n\r\n#读取数据表\r\nfor i in range(1,Order_Number):\r\n data = Sheet_In.row(i)\r\n dic = {}\r\n for j in range(Sheet_In.ncols):\r\n cell = data[j]\r\n if j == 5 and cell.ctype == 2:\r\n val = xlrd.xldate_as_datetime(cell.value, 0)\r\n else:\r\n val = cell.value\r\n dic[Title[j].value] = val\r\n if j == 0:\r\n if i == 1:\r\n Machine_Name.append(val)\r\n elif val != Machine_Name[Machine_Number-1]:\r\n Machine_Name.append(val)\r\n Machine_Number = Machine_Number + 1\r\n # print(dic)\r\n Order_List.append(dic)\r\n\r\nOrder_Number = Order_Number - 1 # 除去表头行\r\n# print(Order_List)\r\n# print(Machine_Name)\r\n# print(Machine_Number)\r\n# print(Order_Number)\r\n\r\n#比较时间先后函数\r\ndef Compare (Date_1 , Date_2):\r\n Val_1 = Date_1.year * 13 * 32 + Date_1.month * 32 + Date_1.day\r\n Val_2 = Date_2.year * 13 * 32 + Date_2.month * 32 + Date_2.day\r\n # print(Val_1,\"+\",Val_2)\r\n return Val_1 < Val_2\r\n \r\nFind = 0\r\nCost = [] # 各订单总耗时\r\n\r\n#寻找最早开始时间\r\nfor i in range(Order_Number):\r\n Now_Order = Order_List[i]\r\n Cost.append(Now_Order[\"总量(万个)\"] / Now_Order[\"效率(万个/班)\"])\r\n if(Now_Order[\"开始日期\"] != \"\"):\r\n if(Find == 0):\r\n First_Day = Now_Order[\"开始日期\"]\r\n Find = 1\r\n elif Compare(Now_Order[\"开始日期\"] , First_Day) == 1:\r\n First_Day = Now_Order[\"开始日期\"]\r\n\r\n#时间自增函数\r\ndef Next_Day (Dat):\r\n Y = Dat.year\r\n M = Dat.month\r\n D = Dat.day\r\n R = 0\r\n if Y % 400 == 0:\r\n R = 1\r\n elif Y % 4 == 0 and Y % 100 != 0:\r\n R = 1\r\n if M==2:\r\n if R == 1 and D == 29:\r\n M = 3\r\n D = 1\r\n elif R == 0 and D == 28:\r\n M = 3\r\n D = 1\r\n else:\r\n D = D + 1\r\n elif M == 1 or M == 3 or M == 5 or M == 7 or M == 8 or M == 10 or M == 12:\r\n if D == 31:\r\n D = 1\r\n if M == 12:\r\n Y = Y + 1\r\n M = 1\r\n else:\r\n M = M + 1\r\n else:\r\n D = D + 1\r\n else:\r\n if D == 30:\r\n M = M + 1\r\n D = 1\r\n else:\r\n D = D + 1\r\n return datetime.datetime(Y,M,D)\r\n # print(New_Date,\" \",New_Date.strftime(\"%w\"))\r\n # if New_Date.strftime(\"%w\") == 0:\r\n # return Next_Day(New_Date)\r\n # else:\r\n # return New_Date\r\n \r\nNow_Date = First_Day\r\nLast_Day = First_Day\r\nSchedule_Dic = {} # 各订单的时间和机器安排\r\n\r\n# for i in range(300):\r\n# print(Now_Date)\r\n# Now_Date = Next_Day(Now_Date)\r\n\r\nfor i in range(Machine_Number):\r\n Find = 0\r\n for j in range(Order_Number):\r\n Now_Order = Order_List[j]\r\n if Now_Order[\"机器\"] == Machine_Name[i]:\r\n lst = []\r\n if Find == 0:\r\n Find = 1\r\n Left = 3\r\n if Now_Order[\"开始日期\"] == \"\":\r\n Now_Date = First_Day\r\n else:\r\n Now_Date = Now_Order[\"开始日期\"]\r\n elif Now_Order[\"开始日期\"] != \"\" and Compare(Now_Date,Now_Order[\"开始日期\"]) == 1:\r\n Now_Date = Now_Order[\"开始日期\"]\r\n Left = 3\r\n if Now_Date.strftime(\"%w\") == 0:\r\n Now_Date = Next_Day(Now_Date)\r\n Left = 3\r\n while Cost[j] != 0:\r\n if Cost[j] >= Left:\r\n Cost[j] = Cost[j] - Left\r\n lst.append({\"日期\" : Now_Date , \"机器\" : Machine_Name[i] , \"数量\" : Left * Now_Order[\"效率(万个/班)\"]})\r\n Now_Date = Next_Day(Now_Date)\r\n if Now_Date.strftime(\"%w\") == \"0\":\r\n # print(Now_Date)\r\n Now_Date = Next_Day(Now_Date)\r\n # print(Now_Date)\r\n Left = 3\r\n else:\r\n Left = Left - Cost[j]\r\n lst.append({\"日期\" : Now_Date , \"机器\" : Machine_Name[i] , \"数量\" : Cost[j] * Now_Order[\"效率(万个/班)\"]})\r\n Cost[j] = 0\r\n Schedule_Dic[j] = lst\r\n if Compare(Last_Day , Now_Date) == 1:\r\n Last_Day = Now_Date\r\n\r\n# print(First_Day)\r\n# print(Last_Day)\r\n# for i in range(Order_Number):\r\n# print(Schedule_Dic[i])\r\n# print(\"---------------------\")\r\n\r\nYea = First_Day.strftime(\"%Y年\")\r\nFir = First_Day.strftime(\"(%m.%d\")\r\nLas = Last_Day.strftime(\"~%m.%d)\")\r\nTitlename = Yea + \"生产计划预排\" + Fir + Las\r\nFilename = Titlename + \".xlsx\"\r\n\r\nWorkbook_Out = xlsxwriter.Workbook(Filename) # 建立输出表格\r\nSheet_Out = Workbook_Out.add_worksheet(\"排产\") # 建立Sheet\r\n\r\n#初始化格式\r\nTitle_Style = Workbook_Out.add_format({\r\n 'bold' : True , # 是否加粗\r\n 'font' : \"华文中宋\" , # 字体设置\r\n 'font_size' : 16 , # 文字大小设置\r\n 'align' : \"center\" , # 水平位置设置:居中\r\n\t'valign' : \"vcenter\" , # 垂直位置设置:居中\r\n 'font_color' : \"black\" , # 文字颜色设置\r\n 'fg_color' : \"white\" , # 单元格背景颜色设置\r\n 'text_wrap' : True , # 是否自动换行\r\n 'border' : 5 # 框线宽度\r\n})\r\n\r\nMachine_Style = Workbook_Out.add_format({\r\n 'bold' : True ,\r\n 'font' : \"宋体\" ,\r\n 'font_size' : 10 ,\r\n 'align' : \"center\" ,\r\n\t'valign' : \"vcenter\" ,\r\n 'font_color' : \"black\" ,\r\n 'fg_color' : \"#D8E4BC\" ,\r\n 'text_wrap' : True ,\r\n 'border' : 1\r\n})\r\n\r\nDate_Style = Workbook_Out.add_format({\r\n 'bold' : False ,\r\n 'font' : \"宋体\" ,\r\n 'font_size' : 10 ,\r\n 'align' : \"center\" ,\r\n\t'valign' : \"vcenter\" ,\r\n 'font_color' : \"black\" ,\r\n 'fg_color' : \"white\" ,\r\n 'text_wrap' : True ,\r\n 'border' : 1\r\n})\r\n\r\nDate_Style_Sunday = Workbook_Out.add_format({\r\n 'bold' : False ,\r\n 'font' : \"宋体\" ,\r\n 'font_size' : 10 ,\r\n 'align' : \"center\" ,\r\n\t'valign' : \"vcenter\" ,\r\n 'font_color' : \"black\" ,\r\n 'fg_color' : \"yellow\" ,\r\n 'text_wrap' : True ,\r\n 'border' : 1\r\n})\r\n\r\nNormal_Style = Workbook_Out.add_format({\r\n 'bold' : False ,\r\n 'font' : \"宋体\" ,\r\n 'font_size' : 10 ,\r\n\t'valign' : \"vcenter\" ,\r\n 'font_color' : \"black\" ,\r\n 'fg_color' : \"white\" ,\r\n 'text_wrap' : True ,\r\n 'border' : 1\r\n})\r\n\r\nCross_Style = Workbook_Out.add_format({\r\n 'bold' : False ,\r\n 'font' : \"宋体\" ,\r\n 'font_size' : 10 ,\r\n\t'valign' : \"vcenter\" ,\r\n 'font_color' : \"black\" ,\r\n 'fg_color' : \"#ADD8E6\" ,\r\n 'text_wrap' : True ,\r\n 'border' : 1\r\n})\r\n\r\nLight_Line = Workbook_Out.add_format({'border' : 1})\r\n\r\nHeavy_Line = Workbook_Out.add_format({'border' : 5})\r\n\r\nYellow = Workbook_Out.add_format({\r\n 'fg_color' : \"yellow\" ,\r\n 'border' : 1\r\n})\r\n\r\n#写表头\r\nSheet_Out.set_row(0 , 40)\r\nSheet_Out.merge_range(0 , 0 , 0 , 3 * Machine_Number , \"Merged Cells\")\r\nSheet_Out.write(0 , 0 , Titlename , Title_Style) # 第1行写标题\r\nSheet_Out.set_row(1 , 25)\r\nSheet_Out.set_column(0 , 0 , 8)\r\nSheet_Out.write(1 , 0 , \"机台\" , Machine_Style) # 第2行写机器名称\r\nfor i in range(Machine_Number):\r\n Sheet_Out.write(0 , 3 * i + 1 , \"\" , Heavy_Line)\r\n Sheet_Out.write(0 , 3 * i + 2 , \"\" , Heavy_Line)\r\n Sheet_Out.write(0 , 3 * i + 3 , \"\" , Heavy_Line)\r\n Sheet_Out.write(1 , 3 * i + 2 , \"\" , Light_Line)\r\n Sheet_Out.write(1 , 3 * i + 3 , \"\" , Light_Line)\r\n Sheet_Out.merge_range(1 , 3 * i + 1 , 1 , 3 * i + 3 , \"Merged Cells\")\r\n Sheet_Out.write(1 , 3 * i + 1 , Machine_Name[i] , Machine_Style)\r\n Sheet_Out.set_column(3 * i + 1 , 3 * i + 2 , 15)\r\n Sheet_Out.set_column(3 * i + 3 , 3 * i + 3 , 8)\r\n\r\nSheet_Out.write(2 , 0 , \"日期\" , Date_Style) # 表头各项信息栏\r\nfor i in range(Machine_Number):\r\n Sheet_Out.write(2 , 3 * i + 1 , \"品牌\" , Date_Style)\r\n Sheet_Out.write(2 , 3 * i + 2 , \"工单号\\n(备注)\" , Date_Style)\r\n Sheet_Out.write(2 , 3 * i + 3 , \"日产量(万印)\" , Date_Style)\r\n\r\n#写入生产计划\r\nNow_Date = First_Day\r\ncnt = 0\r\nwhile(True):\r\n cnt = cnt + 1\r\n Form_Date = Now_Date.strftime(\"%m月%d日\")\r\n if Now_Date.strftime(\"%w\") == \"0\":\r\n Sheet_Out.write(cnt + 2 , 0 , Form_Date , Date_Style_Sunday)\r\n else:\r\n Sheet_Out.write(cnt + 2 , 0 , Form_Date , Date_Style)\r\n for i in range(Machine_Number):\r\n str1 = \"\"\r\n str2 = \"\"\r\n str3 = \"\"\r\n for j in range(Order_Number):\r\n Now_Order = Order_List[j]\r\n if Now_Order[\"机器\"] == Machine_Name[i]:\r\n lst = Schedule_Dic[j]\r\n for Dic in lst:\r\n if Dic[\"日期\"] == Now_Date:\r\n if str1 == \"\":\r\n str1 = Now_Order[\"产品名称\"]\r\n else:\r\n str1 = str1 + \" +\" + Now_Order[\"产品名称\"]\r\n if Now_Order[\"工单号\"] != \"\":\r\n if str2 == \"\":\r\n str2 = Now_Order[\"工单号\"]\r\n else:\r\n str2 = str2 + \" +\" + Now_Order[\"工单号\"]\r\n if Now_Order[\"产品名称\"] != \"换牌\" and Now_Order[\"产品名称\"] != \"月保\" and Now_Order[\"产品名称\"] != \"周保\":\r\n if str3 == \"\":\r\n str3 = str(round(Dic[\"数量\"],2))\r\n else:\r\n str3 = str3 + \" +\" + str(round(Dic[\"数量\"],2))\r\n Sheet_Out.write(cnt + 2 , 3 * i + 1 , str1 , Normal_Style)\r\n Sheet_Out.write(cnt + 2 , 3 * i + 2 , str2 , Normal_Style)\r\n Sheet_Out.write(cnt + 2 , 3 * i + 3 , str3 , Normal_Style)\r\n if Now_Date.strftime(\"%w\") == \"0\":\r\n for i in range(Machine_Number):\r\n Sheet_Out.write(cnt + 2 , 3 * i + 1 , \"\" , Yellow)\r\n Sheet_Out.write(cnt + 2 , 3 * i + 2 , \"\" , Yellow)\r\n Sheet_Out.write(cnt + 2 , 3 * i + 3 , \"\" , Yellow)\r\n if Now_Date == Last_Day:\r\n break\r\n Now_Date = Next_Day(Now_Date)\r\n\r\nWorkbook_Out.close() # 保存文件\r\n\r\n# Made by 中国飞鱼","sub_path":"Transform1.1.py","file_name":"Transform1.1.py","file_ext":"py","file_size_in_byte":10562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"365814575","text":"\"\"\"\n CREATE TABLE makes (\n id INTEGER PRIMARY KEY,\n description TEXT\n )\n CREATE TABLE colors (\n id INTEGER PRIMARY KEY,\n description TEXT\n )\n CREATE TABLE models (\n id INTEGER PRIMARY KEY,\n description TEXT,\n make_id INTEGER\n )\n CREATE TABLE models-colors (\n models_id INTEGER,\n colors_id INTEGER\n )\n\"\"\"\n\nmakes = (\n (1, \"Toyota\"), (2, \"Nissan\"),\n (3, \"Ford\"), (4, \"Mini\"),\n (5, \"Honda\"), (6, \"Dodge\"),\n)\n\nmakes = {k: v for k, v in makes}\n\nmodels = (\n (1, \"Altima\", 2), (2, \"Thunderbird\", 3),\n (3, \"Dart\", 6), (4, \"Accord\", 5),\n (5, \"Prius\", 1), (6, \"Countryman\", 4),\n (7, \"Camry\", 1), (8, \"F150\", 3),\n (9, \"Civic\", 5), (10, \"Ram\", 6),\n (11, \"Cooper\", 4), (12, \"Pilot\", 5),\n (13, \"Xterra\", 2), (14, \"Sentra\", 2),\n (15, \"Charger\", 6)\n)\n\ncolors = (\n (1, \"Black\" ), (2, \"Charcoal\" ), (3, \"Red\" ), (4, \"Brick\" ),\n (5, \"Blue\" ), (6, \"Navy\" ), (7, \"White\" ), (8, \"Ivory\" )\n)\n\ncolors = {k: v for k, v in colors}\n\navailable_car_colors = (\n (1, 1), (1, 2), (1, 7), \n (2, 1), (2, 3), (2, 7), \n (3, 2), (3, 3), (3, 7), \n (4, 3), (4, 5), (4, 8),\n (5, 2), (5, 4), (5, 8), \n (6, 2), (6, 6), (6, 7), \n (7, 1), (7, 3), (7, 7), \n (8, 1), (8, 5), (8, 8),\n (9, 1), (9, 6), (9, 7), \n (10, 2), (10, 5), (10, 7), \n (11, 3), (11, 6), (11, 8), \n (12, 1), (12, 4), (12, 7),\n (13, 2), (13, 6), (13, 8), \n (14, 2), (14, 5), (14, 8), \n (15, 1), (15, 4), (15, 7)\n)\n\ncolors_available = {}\n\nfor car, color in available_car_colors:\n if car in colors_available:\n colors_available[car].append(colors[color])\n else:\n colors_available[car] = [colors[color]]\n\nmodels_by_make = {k: {} for k in makes.values()}\n\nfor car_id, name, make_id in models:\n make = makes[make_id]\n car = models_by_make[make].get(name, [])\n car.append(colors_available[car_id])\n models_by_make[make][name] = car\n\n\nif __name__ == '__main__':\n for make, models_and_colors in models_by_make.items():\n print(\"\\n{0}\\n---------------------------------------------\".format(make, models_and_colors))\n for model, colors in models_and_colors.items():\n print(\"{0} available in {1}, {2}, {3}\".format(model, *colors[0]))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"cars.py","file_name":"cars.py","file_ext":"py","file_size_in_byte":2183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"557491","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@Author: tushushu\n@Date: 2021-07-18 16:46:54\n@Last Modified by: tushushu\n@Last Modified time: 2021-07-18 16:46:54\n\"\"\"\n\n\nclass Solution:\n def numDecodings(self, s: str) -> int:\n \"\"\"\n F(n) = F(n - 1) + F(n - 2) * can decode(s[n - 1], s[n])\n \"\"\"\n if s[0] == \"0\":\n return 0\n if len(s) == 1:\n return 1\n codes = set([str(x) for x in range(1, 27)])\n dp = [0] * len(s)\n dp[0] = 1\n\n if s[0:2] in codes:\n if s[1] == \"0\":\n dp[1] = 1\n else:\n dp[1] = 2\n else:\n if s[1] == \"0\":\n return 0\n dp[1] = 1\n for i in range(2, len(s)):\n if s[i - 1:i + 1] in codes:\n if s[i] == \"0\":\n dp[i] = dp[i - 2]\n else:\n dp[i] = dp[i - 2] + dp[i - 1]\n else:\n if s[i] == \"0\":\n return 0\n dp[i] = dp[i - 1]\n return dp[-1]\n","sub_path":"python/091. 解码方法.py","file_name":"091. 解码方法.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"98141118","text":"import os\nfrom unittest.mock import Mock, patch\nimport pytest\nfrom battenberg.errors import InvalidRepositoryException\nfrom battenberg.utils import open_repository, open_or_init_repository, construct_keypair\n\n\n@pytest.fixture\ndef Repository() -> Mock:\n with patch('battenberg.utils.Repository') as Repository:\n yield Repository\n\n\n@pytest.fixture\ndef discover_repository() -> Mock:\n with patch('battenberg.utils.discover_repository') as discover_repository:\n yield discover_repository\n\n\n@pytest.fixture\ndef init_repository() -> Mock:\n with patch('battenberg.utils.init_repository') as init_repository:\n yield init_repository\n\n\n@pytest.fixture\ndef Keypair() -> Mock:\n with patch('battenberg.utils.Keypair') as Keypair:\n yield Keypair\n\n\ndef test_open_repository():\n path = 'test-path'\n with pytest.assertRaises(ValueError) as e:\n open_repository(path)\n\n assert str(e.value) == f'{path} is not a valid repository path.'\n\n\ndef test_open_repository(Repository: Mock, discover_repository: Mock):\n path = 'test-path'\n assert open_repository(path) == Repository.return_value\n Repository.assert_called_once_with(discover_repository.return_value)\n discover_repository.assert_called_once_with(path)\n\n\ndef test_open_repository_raises_on_invalid_path():\n path = 'test-path'\n with pytest.raises(InvalidRepositoryException) as e:\n open_repository(path)\n\n assert str(e.value) == f'{path} is not a valid repository path.'\n\n\ndef test_open_or_init_repository_opens_repo(Repository: Mock, discover_repository: Mock):\n path = 'test-path'\n template = 'test-template'\n assert open_or_init_repository(path, template) == Repository.return_value\n Repository.assert_called_once_with(discover_repository.return_value)\n discover_repository.assert_called_once_with(path)\n\n\ndef test_open_or_init_repository_initializes_repo(init_repository: Mock, Repository: Mock,\n discover_repository: Mock):\n discover_repository.side_effect = Exception('No repo found')\n\n path = 'test-path'\n template = 'test-template'\n initial_branch = 'test-initial_branch'\n repo = init_repository.return_value\n assert open_or_init_repository(path, template, initial_branch) == repo\n init_repository.assert_called_once_with(path, initial_head=initial_branch)\n init_repository.return_value.create_commit.assert_called_once_with(\n 'HEAD',\n repo.default_signature,\n repo.default_signature,\n 'Initialized repository',\n repo.index.write_tree.return_value,\n []\n )\n\n\n@patch('battenberg.utils.subprocess')\ndef test_open_or_init_repository_initializes_repo_with_inferred_initial_branch(subprocess: Mock,\n init_repository: Mock, Repository: Mock, discover_repository: Mock):\n initial_branch = 'refs/heads/main'\n subprocess.run.return_value.stdout = f'ref: {initial_branch} HEAD'\n discover_repository.side_effect = Exception('No repo found')\n\n path = 'test-path'\n template = 'test-template'\n repo = init_repository.return_value\n assert open_or_init_repository(path, template) == repo\n repo.references['HEAD'].set_target.assert_called_once_with(initial_branch)\n\n\n@pytest.mark.parametrize('stdout', ('', 'invalid-symref'))\n@patch('battenberg.utils.subprocess')\ndef test_open_or_init_repository_initializes_repo_with_invalid_remote_branches(subprocess: Mock,\n init_repository: Mock, Repository: Mock, discover_repository: Mock, stdout: str):\n subprocess.run.return_value.stdout = stdout\n discover_repository.side_effect = Exception('No repo found')\n\n path = 'test-path'\n template = 'test-template'\n repo = init_repository.return_value\n assert open_or_init_repository(path, template) == repo\n\n\ndef test_construct_keypair_defaults(Keypair: Mock):\n construct_keypair()\n user_home = os.path.expanduser('~')\n Keypair.assert_called_once_with('git', f'{user_home}/.ssh/id_rsa.pub',\n f'{user_home}/.ssh/id_rsa', '')\n\n\ndef test_construct_keypair(Keypair: Mock):\n public_key_path = 'test-public_key_path'\n private_key_path = 'test-private_key_path'\n passphrase = 'test-passphrase'\n construct_keypair(public_key_path, private_key_path, passphrase)\n Keypair.assert_called_once_with('git', public_key_path, private_key_path, passphrase)\n","sub_path":"tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":4342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"387100528","text":"import threading\nimport queue\nimport time\nimport pyupbit\nimport datetime\nfrom collections import deque\nTICKER = \"KRW-EOS\"\n\nclass Consumer(threading.Thread):\n def __init__(self, q):\n super().__init__()\n self.q = q\n self.ticker = TICKER\n\n self.ma5 = deque(maxlen=5)\n self.ma10 = deque(maxlen=10)\n self.ma15 = deque(maxlen=15)\n self.ma50 = deque(maxlen=50)\n self.ma120 = deque(maxlen=120)\n\n df = pyupbit.get_ohlcv(self.ticker, interval=\"minute1\")\n self.ma5.extend(df['close'])\n self.ma10.extend(df['close'])\n self.ma15.extend(df['close'])\n self.ma50.extend(df['close'])\n self.ma120.extend(df['close'])\n\n\n def run(self):\n price_curr = None # 현재 가격\n hold_flag = False # 보유 여부\n wait_flag = False # 대기 여부\n\n with open(\"key/upbit_key.txt\", \"r\") as f:\n access = f.readline().strip()\n secret = f.readline().strip()\n\n upbit = pyupbit.Upbit(access, secret)\n cash = upbit.get_balance() # 2개 이상 종목 돌릴 시 모든 cash 코드 임의 설정\n print(\"보유현금:\", cash)\n\n i = 0\n\n while True:\n try:\n if not self.q.empty():\n if price_curr != None:\n self.ma5.append(price_curr)\n self.ma10.append(price_curr)\n self.ma15.append(price_curr)\n self.ma50.append(price_curr)\n self.ma120.append(price_curr)\n\n curr_ma5 = sum(self.ma5) / len(self.ma5)\n curr_ma10 = sum(self.ma10) / len(self.ma10)\n curr_ma15 = sum(self.ma15) / len(self.ma15)\n curr_ma50 = sum(self.ma50) / len(self.ma50)\n curr_ma120 = sum(self.ma120) / len(self.ma120)\n\n price_open = self.q.get()\n if hold_flag == False:\n price_buy = price_open * 1.005\n price_sell = price_open * 1.015\n wait_flag = False\n\n price_curr = pyupbit.get_current_price(self.ticker)\n if price_curr == None:\n continue\n\n if hold_flag == False and wait_flag == False and \\\n price_curr >= price_buy and curr_ma5 >= curr_ma10 and \\\n curr_ma10 >= curr_ma15 and curr_ma15 >= curr_ma50 and \\\n curr_ma50 >= curr_ma120 and curr_ma15 <= curr_ma50 * 1.03:\n # 0.05%\n while True:\n ret = upbit.buy_market_order(self.ticker, cash * 0.9995)\n if ret == None or \"error\" in ret:\n print(\"<< 매수 주문 Error >>\")\n time.sleep(0.5)\n continue\n print(\"매수 주문\", ret)\n break\n\n while True:\n order = upbit.get_order(ret['uuid'])\n if order != None and len(order['trades']) > 0:\n print(\"<< 매수 주문이 체결되었습니다 >>\\n\", order)\n break\n else:\n print(\"매수 주문 대기 중...\")\n time.sleep(0.5)\n\n while True:\n volume = upbit.get_balance(self.ticker)\n if volume != None and volume != 0:\n break\n print(\"보유량 계산중...\")\n time.sleep(0.5)\n\n while True:\n price_sell = pyupbit.get_tick_size(price_sell)\n ret = upbit.sell_limit_order(self.ticker, price_sell, volume)\n if ret == None or 'error' in ret:\n print(\"<< 지정가 매도 주문 Error >>\")\n time.sleep(0.5)\n else:\n print(\"<< 지정가 매도주문이 접수되었습니다 >>\\n\", ret)\n hold_flag = True\n break\n \n cash = upbit.get_balance()\n\n if hold_flag == True:\n uncomp = upbit.get_order(self.ticker)\n\n if (price_curr / price_buy) <= 0.98: # 2% 하락시 손절 매도\n while True:\n upbit.cancel_order(uncomp[0]['uuid'])\n if len(upbit.get_order(self.ticker)) == 0:\n print(\"<< 지정가 매도주문이 취소되었습니다 >>\\n\", ret)\n break\n\n upbit.sell_market_order(self.ticker, volume)\n while True:\n volume = upbit.get_balance(self.ticker)\n if volume == 0:\n print(\"<< 손절 주문(-2%)이 완료되었습니다 >>\")\n cash = upbit.get_balance()\n hold_flag = False\n wait_flag = True\n break\n else:\n print(\"손절 주문(-2%) 대기중...\")\n time.sleep(0.5)\n\n elif uncomp != None and len(uncomp) == 0:\n cash = upbit.get_balance()\n if cash == None:\n continue\n print(\"<< 지정가 매도가 체결되었습니다 >>\")\n hold_flag = False\n wait_flag = True\n\n # 10 seconds\n if i == (5 * 10):\n print(f\"[{datetime.datetime.now()}]\")\n print(f\"{TICKER} 보유량:{upbit.get_balance_t(self.ticker)}, 보유KRW: {cash}, hold_flag= {hold_flag}, wait_flag= {wait_flag} signal = {curr_ma5 >= curr_ma10 and curr_ma10 >= curr_ma15 and curr_ma15 >= curr_ma50 and curr_ma50 >= curr_ma120 and curr_ma15 <= curr_ma50 * 1.03}\")\n print(f\"현재: {price_curr}, 매수 목표: {int(price_buy)}, 지정 매도: {price_sell}, 손절 예상: {int(price_buy * 0.98)}\")\n i = 0\n i += 1\n except:\n print(\"error\")\n\n time.sleep(0.2)\n\nclass Producer(threading.Thread):\n def __init__(self, q):\n super().__init__()\n self.q = q\n\n def run(self):\n while True:\n price = pyupbit.get_current_price(TICKER)\n self.q.put(price)\n time.sleep(60)\n\nnow = datetime.datetime.now()\nprint(f'환영합니다 -- Upbit Auto Trading -- [{now.year}-{now.month}-{now.day} {now.hour}:{now.minute}:{now.second}]')\nprint('트레이딩 대기중...')\nwhile True:\n now = datetime.datetime.now()\n if now.second == 1: # 대기 후 1초에 시작\n q = queue.Queue()\n Producer(q).start()\n Consumer(q).start()\n break\n","sub_path":"realtime_1percent_gap/realtime_1percent.py","file_name":"realtime_1percent.py","file_ext":"py","file_size_in_byte":7211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"117136784","text":"#!/usr/bin/env python \n\n\nfrom enthought.traits.api import *\nfrom enthought.traits.ui.api import *\nfrom enthought.pyface.api import FileDialog, OK\n\nfrom .selection import RectangleSelection\nfrom numpy import indices, zeros\nfrom . import base_fit\nimport pickle\n\ndef _get(object,name):\n d = getattr(object, 'parameters')\n return d.get(name)\n \ndef _set(object,name,value):\n d = getattr(object, 'parameters')\n d[name] = value\n setattr(object,'parameters',d)\n\nResultsProperty = Property(_get, _set, trait =Float, depends_on = 'parameters')\n\n\ndef results_view_item(name):\n cname = 'is_' + name + '_constant'\n return HGroup(\n Item(\n name, \n label = name,\n springy = True,\n enabled_when = cname + '!= True'), \n Item(cname, label = 'constant'),\n springy = True)\n\ndef results_view(names):\n group = list(map(results_view_item, names))\n return View(HGroup(Group(*group, springy = True), \n \n # Group(Item('excluded_parameters', show_label = False,style = 'custom'), label = 'Excluded from fit')\n ))\n\n\n\n\n\nclass Results(HasTraits):\n \"\"\" Object used to display and store fit results.\n Dynamically filled with traits\n >>> r = Results()\n >>> r.add_parameters(a = 1., b = 3.)\n \"\"\"\n view = Instance(View)\n \n #parameters which are specified as conmstant\n constant_parameters = Property(depends_on = 'is_+')\n \n iteration_index = Int(0)\n \n parameters = List(Str)\n \n @cached_property\n def _get_constant_parameters(self):\n p = [name for name in self.parameters if getattr(self, 'is_' + name + '_constant', None) == True ]\n return tuple(p)\n\n \n def default_traits_view(self):\n return self.view\n \n def add_parameters(self, **parameters):\n for name, value in list(parameters.items()):\n self.add_trait(name,Float)\n self.add_trait('is_' + name + '_constant', Bool)\n setattr(self,name,value)\n self.add_trait('is_' + name + '_constant', Bool)\n self.parameters = list(parameters.keys())\n self.view = results_view(sorted(parameters.keys()))\n\n def get_parameters(self):\n return self.get(*self.parameters)\n\n def set_parameters(self, **parameters):\n return self.set(**parameters) \n \n def set_constant_parameters(self, *names):\n for name in self.parameters:\n if name in names:\n setattr(self,'is_' + name + '_constant', True)\n else:\n setattr(self,'is_' + name + '_constant', False)\n \nclass Statistics(HasTraits):\n \"\"\" Object used to display the statistics.\n \"\"\"\n mean = CFloat\n max = CFloat\n min = CFloat\n std = CFloat\n sum = CFloat\n view = View('min', 'max', 'sum', 'mean', 'std')\n \n \nclass Fit(HasTraits):\n results = Instance(Results,transient = True)\n \n\n \n function = Instance(base_fit.Function)\n function_str = Str('n+a/s/2/pi*exp(-((x-x0)**2+(y-y0)**2)/2/s**2)', \n enter_set = True, \n auto_set = False,\n label = 'Fit Function')\n #fit function name\n name = Trait('gauss2D', {'gauss2D': 'n+a/s/2/pi*exp(-((x-x0)**2+(y-y0)**2)/2/s**2)',\n 'custom' : ''})\n \n is_fitting = Bool(True, label = 'Fit') \n\n message = Str\n \n view = View(\n Group(\n HGroup('is_fitting',\n Item('name', show_label = False, springy = True, enabled_when = 'is_fitting')),\n Item('function_str', show_label = False, springy = True, enabled_when = 'is_fitting == True and name == \"custom\"'),\n \n Group(Item('results', style = 'custom', show_label = False),\n show_border = True, label = 'Fit parameters', enabled_when = 'is_fitting', \n ), \n\n Item('message', show_label = False, style = 'readonly')\n )\n )\n \n @on_trait_change('results.[+]')\n def update_function(self):\n self.function.SetConstant(*self.results.constant_parameters)\n self.function.SetParameters(**self.results.get(*self.results.parameters))\n \n def _function_str_changed(self, new):\n self.function = base_fit.Function(self.function_str)\n self.results = self._results_default()\n \n def _function_default(self):\n return base_fit.Function(self.function_str)\n \n def _results_default(self):\n r = Results()\n r.add_parameters(**self.function.parDict)\n return r\n \n def _name_changed(self,value):\n if value != 'custom':\n self.function_str = self.name_\n \n \n def fit(self, image, ind):\n \"\"\"\n Fit image based on indices\n \"\"\"\n try:\n results = base_fit.fit(self.function, image, ind)\n except:\n self.message = 'fit error'\n raise\n return\n if results:\n self.results.trait_set(**results)\n self.message = ''\n else:\n self.message = 'Not converged!'\n \nclass AnalysisOld(HasTraits):\n \"\"\"\n Object to display analysis settings and statistics and fit results\n \"\"\"\n selection = Instance(RectangleSelection)\n statistics = Instance(Statistics, transient = True)\n #fit_results must be transient = True, because it is only used as an interface to fit_function parameters\n # fit_results are actually stored in fit_function\n fit_results = Instance(Results,transient = True)\n \n\n \n fit_function = Instance(base_fit.Function)\n fit_function_str = Str('n+a*exp(-((x-x0)**2+(y-y0)**2)/2/s**2)', \n enter_set = True, \n auto_set = False,\n label = 'Fit Function')\n \n fit_name = Trait('gauss2D', {'gauss2D': 'n+a*exp(-((x-x0)**2+(y-y0)**2)/2/s**2)',\n 'custom' : ''})\n \n is_fitting = Bool(True, label = 'Fit')\n name = Str\n message = Str\n \n view = View(\n Group(\n Group(\n Item('selection', style = 'custom', show_label = False),\n show_border = True, label = 'Selection'\n ),\n Group(Item('statistics', style = 'custom', show_label = False),\n show_border = True, label = 'Statistics'\n ),\n\n HGroup('is_fitting',\n Item('fit_name', show_label = False, springy = True, enabled_when = 'is_fitting')),\n Item('fit_function_str', show_label = False, springy = True, enabled_when = 'is_fitting == True and fit_name == \"custom\"'),\n \n Group(Item('fit_results', style = 'custom', show_label = False),\n show_border = True, label = 'Fit parameters', enabled_when = 'is_fitting', \n ), \n\n Item('message', show_label = False, style = 'readonly')\n )\n )\n \n def _constants_default(self):\n return []\n \n def _statistics_default(self):\n return Statistics()\n \n def _selection_default(self):\n return RectangleSelection()\n \n @on_trait_change('fit_results.[+]')\n def update_fit_function(self):\n self.fit_function.SetConstant(*self.fit_results.constant_parameters)\n self.fit_function.SetParameters(**self.fit_results.get(*self.fit_results.parameters))\n \n def _fit_function_str_changed(self, new):\n self.fit_function = base_fit.Function(self.fit_function_str)\n self.fit_results = self._fit_results_default()\n \n def _fit_function_default(self):\n return base_fit.Function(self.fit_function_str)\n \n def _fit_results_default(self):\n r = Results()\n r.add_parameters(**self.fit_function.parDict)\n return r\n \n def _fit_name_changed(self,value):\n if value != 'custom':\n self.fit_function_str = self.fit_name_\n \n \n def fit(self, image):\n im = self.selection.slice_image(image)\n ind = self.selection.slice_indices(indices(image.shape))\n try:\n results = base_fit.fit(self.fit_function, im, ind)\n except:\n self.message = 'fit error'\n raise\n return\n if results:\n self.fit_results.trait_set(**results)\n self.message = ''\n else:\n self.message = 'not converged'\n \n def calc_statistics(self, image):\n \"\"\"\n Calculates image statistics on a predefined selection\n \"\"\"\n im = self.selection.slice_image(image)\n self.statistics.mean = im.mean()\n self.statistics.std = im.std()\n self.statistics.max = im.max()\n self.statistics.min = im.min()\n self.statistics.sum = im.sum()\n\nclass Analysis(HasTraits):\n \"\"\"\n Object to display analysis settings and statistics and fit results\n \"\"\"\n selection = Instance(RectangleSelection)\n statistics = Instance(Statistics, transient = True)\n fitting = Instance(Fit)\n \n name = Str\n \n view = View(\n Group(\n Group(\n Item('selection', style = 'custom', show_label = False),\n show_border = True, label = 'Selection'\n ),\n Group(Item('statistics', style = 'custom', show_label = False),\n show_border = True, label = 'Statistics'\n ),\n \n Item('fitting', style = 'custom', show_label = False)\n )\n )\n \n def _statistics_default(self):\n return Statistics()\n \n def _selection_default(self):\n return RectangleSelection()\n \n def _fitting_default(self):\n return Fit()\n\n def fit(self, image):\n im = self.selection.slice_image(image)\n ind = self.selection.slice_indices(indices(image.shape))\n self.fitting.fit(im,ind)\n \n def calc_statistics(self, image):\n \"\"\"\n Calculates image statistics on a predefined selection\n \"\"\"\n im = self.selection.slice_image(image)\n self.statistics.mean = im.mean()\n self.statistics.std = im.std()\n self.statistics.max = im.max()\n self.statistics.min = im.min()\n self.statistics.sum = im.sum()\n\n\n\nPOINTS = [Analysis(name = 'point 0')]\n\n#class ListView(HasTraits):\n# data_name = Str('data')\n# _data = Property()\n# \n# view = Instance(View)\n# add = Button()\n# load = Button()\n# save = Button()\n# \n# index_high = Property(Int,depends_on = 'points',transient = True) \n# index = Property(Int, depends_on = 'analysis,index_high',transient = True)\n# \n# def _get__data(self):\n# return getattr(self, self.data_name)\n# \n# def _set__data(self, value):\n# return setattr(self, self.data_name, value) \n# \n# def default_traits_view(self):\n# return self.view \n# \n# def __init__(self, data, **kw):\n# super(ListView, self).__init__(**kw)\n# klass = data[0].__class__\n# self.add_trait(self.data_name, List(klass))\n# self.add_trait('selected', Instance(klass, transient = True))\n# setattr(self, self.data_name, data)\n# self.view = View(\n# Item('index' ,\n# editor = RangeEditor( low = 0,\n# high_name = 'index_high',\n# is_float = False,\n# mode = 'spinner' )),\n# HGroup(\n# Item('add', show_label = False, springy = True),\n# Item('load', show_label = False, springy = True),\n# Item('save', show_label = False, springy = True),\n# ),\n# '_',\n# VGroup( \n# Item( self.data_name + '@',\n# id = 'notebook',\n# show_label = False,\n# editor = ListEditor( use_notebook = True, \n# deletable = True,\n# selected = 'selected',\n# export = 'DockWindowShell',\n# page_name = '.name' \n# )\n# ), \n# ),\n# id = 'enthought.traits.ui.demo.Traits UI Demo.Advanced.'\n# 'List_editor_notebook_selection_demo',\n# dock = 'horizontal' , resizable = True, height = -0.5) \n#\n# def _load_fired(self):\n# f = FileDialog(action = 'open', \n# title = 'Load state',\n# default_path = self.filename, \n# wildcard = '*.state')\n# if f.open() == OK:\n# self.filename = f.path\n# self.from_file()\n#\n# def _save_fired(self):\n# f = FileDialog(action = 'save as', \n# title = 'Save state',\n# default_path = self.filename, \n# wildcard = '*.state')\n# if f.open() == OK:\n# self.filename = f.path\n# self.to_file() \n#\n# \n# def _get_index_high(self):\n# return len(self._data)-1\n# \n# def _add_fired(self):\n# data = (self._data[self.index]).clone_traits()\n# data.name = self.data_name + str(len(self._data)) \n# self._data.append(data)\n# self.selected = self._data[-1]\n# \n# @on_trait_change('_data[]') \n# def _update_names(self):\n# #update point names\n# for i, d in enumerate(self._data):\n# d.name = 'data ' + str(i)\n#\n# def _get_index(self):\n# try:\n# return self._data.index(self.selected)\n# except:\n# return self.index_high\n#\n# def _set_index(self, value):\n# self.selected = self._data[value]\n# \n# def from_file(self):\n# with open(self.filename, 'rb') as f:\n# self._data = pickle.load(f) \n# self.index = 0\n# \n# def to_file(self):\n# with open(self.filename, 'wb') as f:\n# pickle.dump(self._data, f)\n\n\nclass Experiment(HasTraits):\n \"\"\" Object used to store analysis objects in List of points\n \"\"\"\n points = List(Analysis)\n analysis = Instance(Analysis,transient = True)\n \n #default filename for points load, save\n filename = File()\n \n add_point = Button()\n load = Button()\n save = Button()\n \n index_high = Property(Int,depends_on = 'points',transient = True) \n index = Property(Int, depends_on = 'analysis,index_high',transient = True)\n\n view = View(\n Item('index' ,\n editor = RangeEditor( low = 0,\n high_name = 'index_high',\n is_float = False,\n mode = 'spinner' )),\n HGroup(\n Item('add_point', show_label = False, springy = True),\n Item('load', show_label = False, springy = True),\n Item('save', show_label = False, springy = True),\n ),\n '_',\n VGroup( \n Item( 'points@',\n id = 'notebook',\n show_label = False,\n editor = ListEditor( use_notebook = True, \n deletable = True,\n selected = 'analysis',\n export = 'DockWindowShell',\n page_name = '.name' \n )\n ), \n ),\n id = 'enthought.traits.ui.demo.Traits UI Demo.Advanced.'\n 'List_editor_notebook_selection_demo',\n dock = 'horizontal' , resizable = True, height = -0.5) \n\n\n def _load_fired(self):\n f = FileDialog(action = 'open', \n title = 'Load points',\n default_path = self.filename, \n wildcard = '*.points')\n if f.open() == OK:\n self.filename = f.path\n self.from_file()\n\n def _save_fired(self):\n f = FileDialog(action = 'save as', \n title = 'Save points',\n default_path = self.filename, \n wildcard = '*.points')\n if f.open() == OK:\n self.filename = f.path\n self.to_file() \n \n def _analysis_default(self):\n return self.points[0]\n \n def _get_index_high(self):\n return len(self.points)-1\n \n def _add_point_fired(self):\n point = (self.points[self.index]).clone_traits()\n point.name = 'point' + str(len(self.points)) \n self.points.append(point)\n self.analysis = self.points[-1]\n \n def _points_default(self):\n return POINTS\n \n @on_trait_change('points[]') \n def _update_names(self):\n #update point names\n for i, point in enumerate(self.points):\n point.name = 'point ' + str(i)\n\n def _get_index(self):\n try:\n return self.points.index(self.analysis)\n except:\n return self.index_high\n\n def _set_index(self, value):\n self.analysis = self.points[value]\n \n def from_file(self):\n with open(self.filename, 'rb') as f:\n self.points = pickle.load(f) \n self.index = 0\n \n def to_file(self):\n with open(self.filename, 'wb') as f:\n pickle.dump(self.points, f)\n\nif __name__ == '__main__':\n c = Experiment()\n #c = ListView([Analysis(name = 'point 0')])\n c.configure_traits()\n","sub_path":"labtools/analysis/npimage/experiment.py","file_name":"experiment.py","file_ext":"py","file_size_in_byte":17977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"354947771","text":"n = int(input())\n\nfor i in range(2*n):\n if i < n:\n print(' ' * i , end='')\n print('* '*(n-i))\n elif i == n:\n continue\n else:\n print(' ' * (2*n-i-1) , end='')\n print('* '*((i-n+1)))","sub_path":"Python-dev/task1/08.py","file_name":"08.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"489434829","text":"# -*- coding: utf-8 -*-\n__author__= \"姜维洋\"\nimport random\nimport time\n\nfrom NingNuo.settings import User_agent\nclass RandomUserAgentMiddleware(object):\n def process_request(self,request,spider):\n useragent = random.choice(User_agent)\n request.headers[\"User-Agent\"] = useragent\n\n\nclass RandomDelayMiddleware(object):\n def __init__(self, delay):\n self.delay = delay\n\n @classmethod\n def from_crawler(cls, crawler):\n delay = crawler.spider.settings.get(\"RANDOM_DELAY\", 10)\n if not isinstance(delay, int):\n raise ValueError(\"RANDOM_DELAY need a int\")\n return cls(delay)\n\n def process_request(self, request, spider):\n delay = random.randint(0, self.delay)\n print(f\"---------延时时间:{delay}-----------\")\n time.sleep(delay)\n","sub_path":"previous_version/NingNuo/middlewares.py","file_name":"middlewares.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"621544037","text":"from torchvision import transforms\r\nimport torch.nn as nn\r\nimport torchvision.models as models\r\n\r\nclass FeatureExtractor():\r\n def __init__(self):\r\n resnet18 = models.resnet18(pretrained=True)\r\n modules = list(resnet18.children())[:-1]\r\n self.resnet18 = nn.Sequential(*modules)\r\n for p in self.resnet18.parameters():\r\n p.requires_grad = False\r\n self.transform = transforms.Compose([\r\n transforms.Resize((224,224)),\r\n transforms.ToTensor(),\r\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])]\r\n )\r\n self.flatten = nn.Flatten()\r\n\r\n\r\n def extract_features(self, img):\r\n feat = self.resnet18(self.transform(img).unsqueeze(0))\r\n feat = self.flatten(feat).squeeze(0)\r\n return feat\r\n","sub_path":"PAL/resnet.py","file_name":"resnet.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"595094965","text":"\nimport os, random\nimport numpy as np\nimport pandas as pd\nimport bloscpack as bp\nfrom sklearn.model_selection import StratifiedKFold\nfrom iterstrat.ml_stratifiers import MultilabelStratifiedKFold\n\nfrom sklearn.metrics import recall_score\n\nimport imgaug as ia\nimport imgaug.augmenters as iaa\n\nimport torch\nfrom torch.utils.data.dataloader import DataLoader\nfrom torch.nn.utils import clip_grad_value_\nimport torch.nn.functional as F\nfrom torch.optim.lr_scheduler import ReduceLROnPlateau, CosineAnnealingLR\n\n# from apex import amp\n\n# from optim import Over9000\nfrom torch.optim import SGD, Adam\n\nfrom data import Bengaliai_DS\nfrom models_mg import mdl_sext50\nfrom mixup_pytorch_utils import *\n# from loss import CenterLoss, AngularPenaltySMLoss\nfrom senet_mod import SENetMod\n\nimport utils\n\n\n# =========================================================================================================================\n\nSEED = 19550423\n\ndef seed_everything(seed):\n random.seed(seed)\n os.environ['PYTHONHASHSEED'] = str(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = True\n\nseed_everything(SEED)\n\n\n# =========================================================================================================================\n\n# augs = iaa.SomeOf(\n# (0, 2),\n# [\n# iaa.OneOf(\n# [\n# iaa.Affine(\n# scale={\"x\": (0.8, 1.1), \"y\": (0.8, 1.1)},\n# rotate=(-15, 15),\n# shear={'x': (-15, 15), 'y': (-15, 15)},\n# ),\n# iaa.PerspectiveTransform(scale=.09, keep_size=True),\n# ]\n# ),\n# ],\n# random_order=True,\n# )\n\naugs = iaa.Affine(\n scale={\"x\": (0.9, 1.1), \"y\": (0.9, 1.1)},\n rotate=(-15, 15),\n shear={'x': (-10, 10), 'y': (-10, 10)},\n)\n\n# =========================================================================================================================\n\npdf = pd.read_csv('../input/train.csv')\nunique_grapheme = pdf['grapheme'].unique()\ngrapheme_code = dict([(g, c) for g, c in zip(unique_grapheme, np.arange(unique_grapheme.shape[0]))])\npdf['grapheme_code'] = [grapheme_code[g] for g in pdf['grapheme']]\n\nskf = MultilabelStratifiedKFold(n_splits=5, shuffle=True, random_state=19550423)\nfor fold, (trn_ndx, vld_ndx) in enumerate(skf.split(pdf['image_id'].values.reshape(-1, 1), pdf.loc[:, ['grapheme_root', 'vowel_diacritic', 'consonant_diacritic']].values)):\n if fold == 0:\n break\n \nimgs = bp.unpack_ndarray_from_file('../features/train_images_size128_pad8_max_noclean.bloscpack')\nlbls = pd.read_csv('../input/train.csv').iloc[:, 1:4].values\n\ntrn_imgs = imgs[trn_ndx]\ntrn_lbls = lbls[trn_ndx]\nvld_imgs = imgs[vld_ndx]\nvld_lbls = lbls[vld_ndx]\n\n\ntraining_set = Bengaliai_DS(trn_imgs, trn_lbls, transform=augs, split_label=True, RGB=True)\nvalidation_set = Bengaliai_DS(vld_imgs, vld_lbls, split_label=True, RGB=True)\n\nbatch_size = 64\n\ntraining_loader = DataLoader(training_set, batch_size=batch_size, num_workers=4, shuffle=True)\nvalidation_loader = DataLoader(validation_set, batch_size=batch_size, num_workers=4, shuffle=False)\n\n# =========================================================================================================================\n\nN_EPOCHS = 150\n\ncheckpoint_name = 'purepytorch_wtf_sext50_lessaug_mucu_sgd_cosanneal_fld0'\n\n# =========================================================================================================================\n\nclassifier = mdl_sext50().cuda()\nclassifier.load_state_dict(torch.load('purepytorch_wtf_sext50_lessaug_mucu_sgd_cosanneal_fld0_0.pth')['model'])\noptimizer = Adam(classifier.parameters(), lr=.0005, weight_decay=0.0)\n\nlr_scheduler = CosineAnnealingLR(optimizer, T_max=N_EPOCHS, eta_min=.00001)\n\n# =========================================================================================================================\n\nlogger = utils.csv_logger(['training_loss', 'validation_loss', 'GRAPHEME_Recall', 'VOWEL_Recall', 'CONSONANT_Recall', 'Final_Recall'])\n\nfor i in range(N_EPOCHS):\n logger.new_epoch()\n # train\n classifier.train()\n \n epoch_trn_loss = []\n epoch_vld_loss = []\n epoch_vld_recall_g, epoch_vld_recall_v, epoch_vld_recall_c, epoch_vld_recall_all = [], [], [], []\n \n for j, (trn_imgs_batch, trn_lbls_batch) in enumerate(training_loader):\n \n optimizer.zero_grad()\n \n # pre-process before mixup\n trn_lbls_oh_batch = [to_onehot(l, c) for l, c in zip(trn_lbls_batch, (168, 11, 7))]\n \n # mixup\n trn_imgs_batch_mixup, trn_lbls_oh_batch_mixup, _ = Mu_InnerPeace(trn_imgs_batch, trn_lbls_oh_batch)\n \n # move to device\n trn_imgs_batch_mixup_device = trn_imgs_batch_mixup.cuda()\n trn_lbls_oh_batch_mixup_device = [l.cuda() for l in trn_lbls_oh_batch_mixup]\n \n # forward pass\n logits = classifier(trn_imgs_batch_mixup_device)\n\n losses = criterion(logits, trn_lbls_oh_batch_mixup_device)\n \n total_trn_loss = .8*losses[0] + .1*losses[1] + .1*losses[2]\n \n total_trn_loss.backward()\n optimizer.step()\n \n # record\n epoch_trn_loss.append(total_trn_loss.item())\n \n utils.display_progress(len(training_loader), j+1, {'training_loss': epoch_trn_loss[-1]})\n \n # validation\n classifier.eval()\n \n with torch.no_grad():\n for k, (vld_imgs_batch, vld_lbls_batch) in enumerate(validation_loader):\n \n # move to device\n vld_imgs_batch_device = vld_imgs_batch.cuda()\n vld_lbls_batch_device = [l.cuda() for l in vld_lbls_batch]\n vld_lbls_batch_numpy = [l.detach().cpu().numpy() for l in vld_lbls_batch]\n \n # forward pass\n logits = classifier(vld_imgs_batch_device)\n \n # loss\n vld_lbls_batch_oh = [to_onehot(l, c) for l, c in zip(vld_lbls_batch_device, (168, 11, 7))]\n losses = criterion(logits, vld_lbls_batch_oh)\n \n total_vld_loss = .8*losses[0] + .1*losses[1] + .1*losses[2]\n # record\n epoch_vld_loss.append(total_vld_loss.item())\n \n # metrics\n pred_g = logits[0].argmax(axis=1).detach().cpu().numpy()\n pred_v = logits[1].argmax(axis=1).detach().cpu().numpy()\n pred_c = logits[2].argmax(axis=1).detach().cpu().numpy()\n epoch_vld_recall_g.append(recall_score(pred_g, vld_lbls_batch_numpy[0], average='macro', zero_division=0))\n epoch_vld_recall_v.append(recall_score(pred_v, vld_lbls_batch_numpy[1], average='macro', zero_division=0))\n epoch_vld_recall_c.append(recall_score(pred_c, vld_lbls_batch_numpy[2], average='macro', zero_division=0))\n \n # display progress\n utils.display_progress(len(validation_loader), k+1, {'validation_loss': epoch_vld_loss[-1]})\n \n epoch_vld_recall_g, epoch_vld_recall_v, epoch_vld_recall_c = np.mean(epoch_vld_recall_g), np.mean(epoch_vld_recall_v), np.mean(epoch_vld_recall_c)\n final_recall = np.average([epoch_vld_recall_g, epoch_vld_recall_v, epoch_vld_recall_c], weights=[2, 1, 1])\n \n entry = {\n 'training_loss': np.mean(epoch_trn_loss),\n 'validation_loss': np.mean(epoch_vld_loss),\n 'GRAPHEME_Recall': epoch_vld_recall_g,\n 'VOWEL_Recall': epoch_vld_recall_v,\n 'CONSONANT_Recall': epoch_vld_recall_c,\n 'Final_Recall': final_recall,\n }\n \n utils.display_progress(N_EPOCHS, i+1, entry, postfix='Epochs', persist=True)\n \n # ----------------------------------\n # save model\n if entry['validation_loss'] < np.nan_to_num(logger.log['validation_loss'].min(), nan=100.):\n print('Saving new best weight.')\n torch.save(\n {\n 'epoch': i,\n 'model': classifier.state_dict(),\n 'optimizer': optimizer.state_dict(),\n }, \n os.path.join('./', checkpoint_name + '.pth'),\n )\n \n # ----------------------------------\n # log\n logger.enter(entry)\n logger.save('./{}.csv'.format(checkpoint_name))\n lr_scheduler.step()\n\n","sub_path":"code/script_purepytorch_wtf.py","file_name":"script_purepytorch_wtf.py","file_ext":"py","file_size_in_byte":8305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"303253859","text":"'''\nThis module provides some tests of the integrator to known integrals.\n\nNote, these are not the transformations, just the plain integrals, :math:`\\int_0^\\infty f(x) J_\\nu(x) dx`\n\nThere is a corresponding notebook in devel/ that runs each of these functions through a grid of N and h,\nshowing the pattern of accuracy. This could be useful for finding the correct numbers to choose for these\nfor other unknown functions.\n'''\n\nimport numpy as np\nimport inspect\nimport os\nLOCATION = \"/\".join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))).split(\"/\")[:-1])\nimport sys\nsys.path.insert(0, LOCATION)\n\nfrom scipy.special import k0, gamma, gammainc, gammaincc\n\ngammainc_ = lambda a,x : gamma(a)*gammainc(a,x)\ngammaincc_ = lambda a,x : gamma(a)*gammaincc(a,x)\n\nfrom hankel import HankelTransform\n\n\nclass TestAnalyticIntegrals_Order0(object):\n\n def test_f_unity(self):\n \"\"\"\n Test f(x) = 1, nu=0\n\n This test is done in the Ogata (2005) paper, section 5\"\n \"\"\"\n\n ht = HankelTransform(nu=0, N=50, h=0.1)\n ans = ht.integrate(lambda x: 1, False, False)\n print(\"Numerical Result: \", ans, \" (required %s)\"%1)\n assert np.isclose(ans,1,rtol=1e-3)\n\n def test_f_x_on_x2(self):\n \"\"\"\n Test f(x) = x/(x**2 + 1), nu=0\n\n This test is done in the Ogata (2005) paper, section 5\"\n \"\"\"\n ht = HankelTransform(nu=0, N=50, h=10**-1.5)\n\n\n ans = ht.integrate(lambda x: x/(x**2+1), False, False)\n print(\"Numerical Result: \", ans, \" (required %s)\"%k0(1))\n assert np.isclose(ans,k0(1),rtol=1e-3)\n\n # The following tests follow from the table on Wikipedia\n def test_x2(self):\n \"\"\"\n Test f(x) = x^2, nu=0\n \"\"\"\n ht = HankelTransform(nu=0, N=100, h=10**-1.5)\n\n ans = ht.integrate(lambda x: x**2, False, False)\n print(\"Numerical Result: \", ans, \" (required -1)\")\n assert np.isclose(ans,-1,rtol=1e-3)\n\n def test_x4(self):\n ht = HankelTransform(nu=0, N=150, h=10**-1.5)\n ans = ht.integrate(lambda x: x**4, False, False)\n print(\"Numerical Result: \", ans, \" (required 9)\")\n assert np.isclose(ans,9,rtol=1e-3)\n\n def test_1_on_sqrt_x(self):\n ## NOTE: this is REALLY finnicky!! (check devel/)\n ht = HankelTransform(nu=0, N=160, h=10**-3.5)\n ans = ht.integrate(lambda x: 1./np.sqrt(x), False, False)\n m = -1.5\n anl = 2**(m+1)*gamma(m/2+1)/gamma(-m/2)\n\n print(\"Numerical Result: \", ans, \" (required %s)\"%anl)\n assert np.isclose(ans,anl,rtol=1e-3)\n\n def test_x_on_sqrt_x2_pz2(self):\n # Note that the number required is highly dependent on z .... smaller z is harder.\n ht = HankelTransform(nu=0, N=50, h=10**-1.3)\n\n z = 1\n ans = ht.integrate(lambda x: x/np.sqrt(x**2+z**2), False, False)\n anl = np.exp(-z)\n print(\"Numerical Result: \", ans, \" (required %s)\"%anl)\n assert np.isclose(ans,anl,rtol=1e-3)\n\n def test_gauss(self):\n z = 2\n ht = HankelTransform(nu=0, N=50, h=0.01)\n\n ans = ht.integrate(lambda x: x*np.exp(-0.5*z**2*x**2), False, False)\n anl = 1./z**2 * np.exp(-0.5/z**2)\n print(\"Numerical Result: \", ans, \" (required %s)\"%anl)\n assert np.isclose(ans,anl,rtol=1e-3)\n\n\nclass TestAnalyticIntegrals_VaryingOrder(object):\n def powerlaw(self,s,nu,N,h):\n ht = HankelTransform(nu=nu, N=N, h=h)\n\n ans = ht.integrate(lambda x: x**(s+1), False, False)\n anl = 2**(s+1)*gamma(0.5*(2+nu+s))/gamma(0.5*(nu-s))\n\n print(\"Numerical Result: \", ans, \" (required %s)\"%anl)\n assert np.isclose(ans,anl,rtol=1e-3)\n\n def test_powerlaw(self):\n trials = [[0, 1, 50, 0.05],\n [0, 2, 50, 0.05],\n [0.5, 1, 50, 0.05],\n [-2, 2, 600, 10**-2.6], # This is pretty finnicky\n [-0.783, 1, 50, 0.05]]\n\n for s,nu,N,h in trials:\n yield self.powerlaw, s,nu,N,h\n\n def gamma_mod(self,s,nu,N,h):\n ht = HankelTransform(nu=nu, N=N, h=h)\n\n ans = ht.integrate(lambda x: x**(nu-2*s + 1)*gammainc_(s,x**2), False, False)\n anl = 0.5 ** (2*s-nu-1) * gammaincc_(1-s+nu,0.25)\n\n print(\"Numerical Result: \", ans, \" (required %s)\"%anl)\n assert np.isclose(ans,anl,rtol=1e-3)\n\n def test_gamma_mod(self):\n trials = [[0, 1, 50, 0.05],\n [0, 2, 50, 0.05],\n [0.5, 1, 50, 0.05],\n [-2, 2, 600, 10**-2.6], # This is pretty finnicky\n [-0.783, 1, 50, 0.05],\n [1.0, 0.5, 150, 0.05],\n [-1., 0.5, 50, 0.05],]\n\n for s,nu,N,h in trials:\n yield self.powerlaw, s,nu,N,h","sub_path":"tests/test_known_integrals.py","file_name":"test_known_integrals.py","file_ext":"py","file_size_in_byte":4728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"401357710","text":"import docker, pytest\n\n@pytest.yield_fixture(scope='session') \ndef redis_port():\n docker_client = docker.Client(version='auto') \n download_image_if_missing(docker_client)\n container_id, redis_port = start_redis_container(docker_client) \n yield redis_port\n docker_client.remove_container(container_id, force=True)\n\n@pytest.fixture(scope='function')\ndef our_service(our_service_session, ext_service_impostor):\n return our_service\n\n ","sub_path":"tests/unit/test_001.py","file_name":"test_001.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"179235728","text":"#coding=utf-8\nfrom sys import argv\nimport string\n\n#Strutture dati Globali\nvocali = ('a','e','i','o','u')\nmesi = ('a','b','c','d','e','h','l','m','p','r','s','t')\ncomuni = {'udine':'l483', 'verona':'l781', 'legnago': 'e512', 'negrar':'f861', 'bassano del grappa': 'a703'}\n\n#CODICI DI CONTROLLO\nregole_pari = {}\nalfabeto = string.ascii_lowercase\nfor i in xrange (0,10):\n regole_pari[str(i)] = i\nfor i in xrange (0,26):\n regole_pari[alfabeto[i]] = i\n\nregole_dispari = {}\ntemp_tuple = (1,0,5,7,9,13,15,17,19,21)\nfor i in xrange(0,10):\n regole_dispari[str(i)] = temp_tuple[i]\n regole_dispari[alfabeto[i]] = temp_tuple[i]\n\ntemp_tuple2 = (2,4,18,20,11,3,6,8,12,14,16,10,22,25,24,23)\nindex = 0\nfor i in xrange(10,26):\n regole_dispari[alfabeto[i]] = temp_tuple2[index]\n index += 1\n\nregole_resto = [alfabeto[i] for i in xrange(0,26)]\n\n#------------------------------\n\ndef estrai_cognome(aString):\n if (' ' in aString):\n aString = aString[:aString.find(' ')] + aString[aString.find(' ')+1:]\n if (\"'\" in aString):\n aString = aString[:aString.find(\"'\")] + aString[aString.find(\"'\")+1:]\n temp_string = ''\n\n temp_string = ''\n for aChar in aString:\n if not aChar in vocali:\n temp_string += aChar\n\n if len(temp_string) >= 3:\n break\n\n if (len(temp_string)<3):\n for aChar in aString:\n if aChar in vocali: #prendo le vocali\n temp_string += aChar #aggiungo la vocale\n if len(temp_string) >= 3:\n break\n if (len(temp_string) < 3): #aggiungo le x nel caso in cui la stringa non è 3\n temp_string += 'x'*(3-(len(temp_string)))\n\n return temp_string\n\ndef estrai_nome(aString):\n if (' ' in aString):\n aString = aString[:aString.find(' ')] + aString[aString.find(' ')+1:]\n temp_string = ''\n\n n_consonanti = 0\n for aChar in aString:\n if not aChar in vocali:\n n_consonanti+=1 #incremnto il numero di consonanti del nome\n\n if (n_consonanti <= 3): #quindi prendo tutti e tre le consonanti\n for aChar in aString:\n if not aChar in vocali:\n temp_string += aChar\n if len(temp_string) >= 3:\n break\n\n if (len(temp_string)<3): #prendo le vocali e le aggiungo\n for aChar in aString:\n if aChar in vocali:\n temp_string += aChar\n if (len(temp_string)>=3):\n break\n if (len(temp_string)<3):\n temp_string += 'x'*(3-(len(temp_string)))\n\n else: #caso se ho tante consonanti\n for aChar in aString:\n if not aChar in vocali:\n temp_string += aChar\n if (len(temp_string)>3):\n break\n #togliamo la consonante in posizione due\n temp_string = temp_string[:1] + temp_string[2:]\n\n return temp_string\n\ndef genera_mese(unMese):\n return mesi[int(unMese)-1]\n\n\ndef codice_comune(comune):\n return comuni[comune]\n\n\ndef genera_giorno(unGiorno, unSesso):\n if int(unGiorno) in xrange(1,31):\n if unSesso == 'm':\n return unGiorno\n elif unSesso == 'f':\n return str(int(unGiorno)+40)\n\n\ndef genera_codice_controllo(aCodiceFiscale):\n parita = 1\n temp_dispari = 0\n temp_pari = 0\n\n for aChar in aCodiceFiscale:\n if parita:\n temp_dispari += int(regole_dispari.get(aChar))\n parita = 0\n else:\n temp_pari += int(regole_pari.get(aChar))\n parita = 1\n\n return regole_resto[(temp_dispari+temp_pari) % 26]\n\ndef main(): #pragma: no cover\n nome = raw_input(\"Nome: \").lower()\n cognome = raw_input(\"Cognome: \").lower()\n data_nascita = raw_input(\"Data di nascita (gg/mm/aaaa): \").lower()\n comune = raw_input(\"Comune di nascita: \").lower()\n sesso = raw_input(\"Sesso (m/f): \").lower()\n #cognome = string.lower(argv[1])\n #nome = string.lower(argv[2])\n #data_nascita = string.lower(argv[3])\n #comune = string.lower(argv[4])\n #sesso = string.lower(argv[5])\n\n nomeCF = estrai_nome(nome)\n cognomeCF = estrai_cognome(cognome)\n\n data_nascitaCF = data_nascita.split(\"/\")\n anno_nascitaCF = data_nascitaCF[2][2:]\n\n mese_nascitaCF = genera_mese(data_nascitaCF[1])\n giorno_nascitaCF = genera_giorno(data_nascitaCF[0], sesso)\n\n codice_fiscale = cognomeCF + nomeCF + anno_nascitaCF + mese_nascitaCF + giorno_nascitaCF + codice_comune(comune.lower())\n\n codiceCF = genera_codice_controllo(codice_fiscale)\n\n codice_fiscale += codiceCF\n\n print (codice_fiscale)\n\nif __name__ == \"__main__\": #pragma: no cover\n main()\n","sub_path":"1/CodiceFiscale.py","file_name":"CodiceFiscale.py","file_ext":"py","file_size_in_byte":4716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"203505519","text":"# -*- coding: utf-8 -*-\nimport time\nimport json\nimport requests\nimport urllib3\nimport xml.etree.ElementTree as ET\nimport logging\nfrom logging.handlers import RotatingFileHandler\nimport re\nimport socket\nimport sys\nimport uuid\nimport os\nimport socketio\nfrom datetime import datetime\nimport configparser\nimport sqlite3\nfrom apscheduler.schedulers.background import BackgroundScheduler\nfrom apscheduler.triggers.interval import IntervalTrigger\nfrom threading import Thread\n\n\n\n##############logging#############\n#logging.basicConfig(filename='sender.log', level=logging.DEBUG) #настраиваем логирование\nlogging.getLogger(\"urllib3\").setLevel(logging.WARNING) # Прогоняем debug сообщения от urllib\nlogger = logging.getLogger('my_logger')\nlogging.basicConfig(handlers=[RotatingFileHandler('RkeeperInfo.log', maxBytes=2000000, backupCount=10)],\n format = u'[%(asctime)s] %(levelname)s %(message)s')\n#-------------------------------------------- Config----------------------------------------------\nconfig = configparser.ConfigParser()\nconfig.read('VideoSender.cfg')\nconnected = False\ntry:\n VideoServer = config['Settings']['videoserver']\n ListenPort = config['Settings']['listenport']\n ListenIP = config['Settings']['listenip']\n XMLInterface = config['Settings']['xmlinterface']\n GUIDInterface = config['Settings']['guidinterface']\n try:\n LogLevel = int(config['Settings']['loglevel'])\n except:\n logger.critical('No loglevel in config, using CRITICAL')\n LogLevel = 0\n\nexcept Exception as e:\n logger.critical(str(e))\n logger.critical('Config file is missing or incorrect?')\n# -----------------------------Получаем GUID от сервера и сохраняем его в cfg------------------------------\n# Если не получится забрать guid - будет использоваться старое значение из cfg-----------------------------\ntry:\n guid = requests.get(GUIDInterface).text\n config['Settings']['GUID'] = guid\n with open('VideoSender.cfg', 'w') as configfile:\n config.write(configfile)\n print(guid)\nexcept:\n logger.debug('No connection to GUID server')\n\nif LogLevel == 1:\n logger.setLevel(logging.DEBUG)\nelif LogLevel == 0:\n logger.setLevel(logging.CRITICAL)\n\nProductGUID = config['Settings']['guid'] # Забираем guid из cfg\n\nsio = socketio.Client(logger=True,engineio_logger=True)\nfirstConnection = True # При первом подключении передаём authobject\nsuccess = False # Отслеживаем успешный ответ\n\n\n\n\n############Создание талиц############\ndef init(tablename, labels):\n db = sqlite3.connect('rk_item.db') # обращение к базе sqlite\n cursor = db.cursor()\n full_labels = ''\n for x in labels:\n x += ' text,'\n full_labels += x\n querytext = ('''CREATE TABLE %s (%s)''') % (tablename, full_labels[:-1])\n cursor.execute(querytext)\n\n##########указываем количество байт для чтения##########\ndef recvall():\n BUFF_SIZE = 1024 # 4 KiB\n data = b''\n sock.listen(1)\n conn, addr = sock.accept()\n while True:\n part = conn.recv(BUFF_SIZE)\n data += part\n length = len(part)\n if length < BUFF_SIZE:\n break\n try:\n logger.debug(data.decode())\n except:\n logger.debug('!!!!!!!!!!!!!!!!!!Can not wtite xml to log!!!!!!!!!!!!!!!!!!')\n return data\n\n\n\n\n\n\n\n\n# -----------------------------события для SocketIO-----------------------------------\ndef connector(limit=1):\n global connected\n if 'connected' not in globals():\n connected = False\n while connected == False:\n limit -= 1\n if limit < 0:\n logger.critical(\"Dropped packed due to server inactivity\")\n break\n try:\n sio.connect(VideoServer)\n sio.sleep(3)\n sio.emit('authentication', authObject)\n sio.sleep(3)\n\n except Exception as e:\n logger.debug('No connection to sio sever %s' % e)\n sio.disconnect()\n sio.sleep(7)\n\n\n@sio.event\ndef connect():\n global firstConnection\n global connected\n logger.debug('connection established')\n connected = True\n if firstConnection == True:\n #authObject = info_station() ####################### ToDo: COMMENT ME !!!!!!!!!!!!!!!!!!!!!!\n authObject['IsCashServer'] = True\n firstConnection = False\n else:\n authObject['IsCashServer'] = 'False'\n authObject['TerminalName'] = \"R-Keeper_pos\"\n\n@sio.event\ndef authenticated(data):\n global connected\n logger.debug('R-Keeper backup server Plugin authenticated')\n connected = True\n\n@sio.event\ndef responseOrder(data):\n global success\n logger.debug('responseOrder')\n success = True\n\n@sio.event\ndef auth_confirmation(data):\n logger.debug('auth_confirmation')\n\n@sio.event\ndef authentication_error(data):\n logger.debug('authentication_error')\n\n@sio.event\ndef disconnect():\n global connected\n connected = False\n logger.debug('R-Keeper has been disconnected')\n sio.disconnect()\n time.sleep (5)\n\n\n\n\n\n\n\n\n\n################################################################################################\n############################### Sending data scheduller ########################################\n################################################################################################\ndef sendOrder(in_contents): # Sending order every 2 seconds, while \"responceOrder\" received\n global success\n global connected\n success = False\n contents = json.loads(in_contents)\n if sio.connected ==True:\n while success == False:\n #connector()\n sio.emit('posOrder', contents)\n sio.sleep(2)\n if success == True:\n toSend.remove(in_contents)\n\n else:\n connected = False\n print ('Something wrong, reconnecting')\n trys = 5 # Количество попыток\n connector(1)\n while success == False:\n trys -=1\n sio.emit('posOrder', contents)\n sio.sleep(2)\n if trys <=0:\n break\n\ntoSend=[] # This variable stores all checks than was not sent yet\n\ndef sender():\n if len (toSend) > 0:\n toSend2 = toSend\n for i in toSend2:\n try:\n sendOrder(i)\n logger.debug('Sending')\n except Exception as e:\n logger.critical(\"!!!!!!!!!!!!!!!Failed to Send %s !!!!!!!!!!!!!!!!!!!!\" % (e))\n toSend.remove(i)\n\n\njob_defaults = {\n 'coalesce': False,\n 'max_instances': 1\n}\nsched = BackgroundScheduler(daemon=True,job_defaults=job_defaults)\nsched.add_job(sender,IntervalTrigger(seconds=30), id='autosender', replace_existing=True)\nsched.start()\n\n################################################################################################\n######################################End sending data scheduller###############################\n################################################################################################\n\n\n\n##########Читаем файл с XML запросом#########\ndef CashPlansToSql():\n try:\n headers = {'Content-Type': 'application/xml', 'Accept-Encoding': 'identity'}\n urllib3.disable_warnings() #отключаем ошибку orllib3\n xml_1 = '''\n \n \n ''' #столы\n xml_2 = '''\n \n \n ''' #перечень планов зала и столы\n xml_3 = '''\n \n \n ''' #имя кассы и план зала по умолчанию\n xml_4 = '''\n \n \n ''' #меню\n xml_5 = '''\n \n \n ''' #цены\n host = XMLInterface\n MenuItem1 = requests.post(host, verify=False, data=xml_1, headers=headers, auth=('HTTP', '1')).text #столы\n MenuItem2 = requests.post(host, verify=False, data=xml_2, headers=headers, auth=('HTTP', '1')).text #перечень планов зала и столы\n MenuItem3 = requests.post(host, verify=False, data=xml_3, headers=headers, auth=('HTTP', '1')).text #имя кассы и план зала по умолчанию\n MenuItem4 = requests.post(host, verify=False, data=xml_4, headers=headers, auth=('HTTP', '1')).text #меню\n MenuItem5 = requests.post(host, verify=False, data=xml_5, headers=headers, auth=('HTTP', '1')).text #цены\n root1 = ET.fromstring(MenuItem1) #столы\n root2 = ET.fromstring(MenuItem2) #перечень планов зала и столы\n root3 = ET.fromstring(MenuItem3) #имя кассы и план зала по умолчанию\n root4 = ET.fromstring(MenuItem4) #меню\n root5 = ET.fromstring(MenuItem5) #цены\n global cashes, all_tables, all_halls, itemsAttribs, prices\n itemsAttribs = [x.attrib for x in root4.findall('RK7Reference')[0].findall('Items')[0].findall('Item')] #элементы меню\n cashes = [x.attrib for x in root3.findall('RK7Reference')[0].findall('Items')[0].findall('Item')] #все кассы(тут берём инфу по станции, её ID и ID плана зала)\n all_tables = [x.attrib for x in root1.findall('RK7Reference')[0].findall('Items')[0].findall('Item')] #все столы(тут имя стола, его Guid и ID плана зала)\n all_halls = [x.attrib for x in root2.findall('RK7Reference')[0].findall('Items')[0].findall('Item')] #все планы залов(ID)\n prices = [x.attrib for x in root5.findall('RK7Reference')[0].findall('Items')[0].findall('Item')] #все цены\n\n #########connect_hall.db########\n if os.path.exists('rk_item.db'): # проверяем наличие rk_item.db, если нет базы, то создаём\n pass\n else:\n new_item = list([x for x in itemsAttribs[0]])\n init('menuitems', new_item)\n new_item = list([x for x in cashes[0]])\n init('hall', new_item)\n new_item = list([x for x in all_tables[0]])\n init('tables', new_item)\n new_item = list([x for x in all_halls[0]])\n init('hallplans', new_item)\n new_item = list([x for x in prices[0]])\n init('prices', new_item)\n\n db = sqlite3.connect('rk_item.db') # обращение к базе sqlite\n cursor = db.cursor()\n clear = \"DELETE FROM hall\" #очищаем таблицу с планами зала и столами\n cursor.execute(clear)\n clear2 = \"DELETE FROM hallplans\" #очищаем таблицу с названием кассы и планом зала по умолчанию\n cursor.execute(clear2)\n clear3 = \"DELETE FROM tables\" #очищаем таблицу со столами\n cursor.execute(clear3)\n clear4 = \"DELETE FROM menuitems\" #очищаем таблицу с меню\n cursor.execute(clear4)\n clear5 = \"DELETE FROM prices\" #очищаем таблицу с ценами\n cursor.execute(clear5)\n db.commit()\n for attrib in cashes:\n toSql = str(list(attrib.values()))# Преобразуем список значений словаря в строку - так надо для записи в SQL\n toSql = re.sub(r'\\[|\\]','',toSql)# Убираем все дурацкие символы, которые не любит SQL\n cursor.execute('''INSERT INTO hall VALUES ('''+ toSql + ''' )''')# Пишем в SQL\n for attrib in all_halls:\n toSql = str(list(attrib.values()))\n toSql = re.sub(r'\\[|\\]','',toSql)\n cursor.execute('''INSERT INTO hallplans VALUES ('''+ toSql + ''' )''')\n for attrib in all_tables:\n toSql = str(list(attrib.values()))\n toSql = re.sub(r'\\[|\\]','',toSql)\n cursor.execute('''INSERT INTO tables VALUES ('''+ toSql + ''' )''')\n for attrib in itemsAttribs:\n toSql = str(list(attrib.values()))\n toSql = re.sub(r'\\[|\\]', '', toSql)\n cursor.execute('''INSERT INTO menuitems VALUES (''' + toSql + ''' )''')\n for attrib in prices:\n if list(attrib.values())[6] == '1025352' and list(attrib.values())[5] == 'psDish': #price type\n toSql = str(list(attrib.values()))\n toSql = re.sub(r'\\[|\\]', '', toSql)\n cursor.execute('''INSERT INTO prices VALUES (''' + toSql + ''' )''')\n db.commit()\n except Exception as e:\n logger.critical('Failed to get cashplans to sql')\n logger.critical(e)\n\n##############получаем план зала, столы и guid#################\ndef RequestNameInHall(hall_ident):\n try:\n db = sqlite3.connect('rk_item.db') # обращение к базе sqlite\n cursor = db.cursor()\n dishRequestByCode2 = (\"\"\"SELECT t.NAME NAME, t.GUIDString GUID, hp.Name HALL_NAME \n FROM hall h\n INNER JOIN hallplans hp ON h.DEFHALLPLANID = hp.Ident\n INNER JOIN tables t ON h.DEFHALLPLANID = t.HALL\n WHERE h.DEFHALLPLANID = ?\"\"\")\n cursor.execute(dishRequestByCode2,(str(hall_ident),))\n dishdetails = cursor.fetchall()\n global plans\n plans = []\n for x in dishdetails:\n plans.append({'Number': x[0], 'Id': re.sub(r'\\{|\\}','',x[1])})\n for y in dishdetails: # ToDO Зачем здесь итерация?\n hall = {'Name': y[2]} # ToDO hall перезапишется последним значением из итерации\n hall['Tables'] = plans\n return hall\n except Exception as e:\n logger.critical('Failed to Request Name from Hall')\n logger.critical(e)\n\n\n########получаем всё меню#######\ndef RequestAllMenu():\n try:\n db = sqlite3.connect('rk_item.db') # обращение к базе sqlite\n cursor = db.cursor()\n products = []\n logger.info('Start func ' + ' RequestAllMenu ' + time.strftime('%H:%M:%S %d.%m.%y', time.localtime()) + '\\n')\n dishRequestByCode = (\"\"\"SELECT m.Ident, m.GUIDString, m.Code, m.Name, p.Value as Price\n FROM menuitems m\n INNER JOIN prices p ON m.ItemIdent = p.ObjectID\n WHERE m.Status='rsActive'\"\"\")\n cursor.execute(dishRequestByCode) # Запрашиваем все элементы блюда с определённым кодом\n logger.info('End func ' + ' RequestMenu ' + time.strftime('%H:%M:%S %d.%m.%y', time.localtime()) + '\\n')\n dishdetails = cursor.fetchall()\n for item in dishdetails:\n price = str(int(item[4]) / 100) #приводим в правильный вид цену\n products.append({'Price': price, 'Type': 'Dish', 'Name': item[3], 'Code': item[2], 'Id': re.sub(r'\\{|\\}','',item[1])})\n return products\n except Exception as e:\n logger.critical('Failed to RequestAllMenu')\n logger.critical(e)\n##############конвертируем текущий формат даты#############\ndef DtimeConvert():\n JavaDtime = datetime.now().strftime('%Y-%m-%dT%H:%M:%S.%f+03:00')\n return JavaDtime\n##############конвертируем заданны формат даты#############\ndef OrdertimeConvert(dtime):\n OrderDtime = (datetime.strptime(dtime, '%d.%m.%Y %H:%M:%S')).strftime('%Y-%m-%dT%H:%M:00.%f+03:00')\n return OrderDtime\n###########получаем информацию о планах зала, столах и меню##########\ndef info_station():\n try:\n id_hall = child.attrib['HallPlanID']\n myHallPlans = RequestNameInHall(id_hall)\n menuItems = RequestAllMenu()\n output = {\n \"IsCashServer\": True,\n \"IsBackup\": False,\n \"Password\": \"randomString\",\n \"TerminalName\": child.attrib['StationName'],\n \"TerminalGroup\": {\n \"Name\": child.attrib['StationName'],\n \"MaxCourseNumber\": 4,\n \"Id\": re.sub(r'\\{|\\}', '', child.attrib['StationGuid'])\n },\n \"Sections\": [myHallPlans]\n }\n menu = {'Groups': '', 'ProductCategories': '', 'Products': [menuItems]}\n output['Menu'] = menu\n info = output\n output = json.dumps(output, ensure_ascii=False, indent=1)\n return info\n except Exception as e:\n logger.critical('Failed to get InfoStation')\n logger.critical(e)\n\n\n\n# ----------------------------------- Main Loop --------------------------------------\ntry:\n sock = socket.socket()\n sock.bind((ListenIP, int(ListenPort))) # Слушаем нужный порт, указанный в конфиге\n logger.info('Сервер запущен')\nexcept:\n logger.debug(\"WARNING! Something already stolen this Cash_Port, choose another one. Exiting!\")\n logger.critical('Не могу запустить сервер')\n sys.exit()\n\ntry:\n CashPlansToSql()\nexcept:\n logger.critical(\"No connection to R-Keeper XML\")\n sys.exit()\nstatus = False #используется для того чтобы каждый раз не переписывать order_full при login\nlogger.info('MainLoop Started.')\nwhile True:\n try:\n data = '\\n'\n dat2 = recvall()\n dat2 = dat2.decode()\n data += str(dat2)\n data += '\\n'\n\n\n except Exception as e:\n logger.critical('Can not convert RK data to string, may be wrong encoding')\n logger.debug(e)\n data =''\n try:\n root = ET.fromstring(data)\n except Exception as e:\n root = ''\n logger.debug(\"!!!!!!!!!!!!Can't parse xml!!!!!!!!!!!!!!\")\n logger.debug(e)\n for child in root:\n inside = child.attrib\n if child.tag == 'LogIn': # Login посылается всего один раз. Передаются планы залов, столы и меню\n if status == False:\n authObject = info_station()# Получаем authObject\n connector(1)\n status = True\n logger.debug('Starting connection to SIO')\n if child.tag == 'NewOrder':\n StatusOrder = \"New\"\n else:\n StatusOrder = \"Open\"\n if child.tag == 'ScreenCheck':\n try:\n all_items = root[0].findall('CheckLines')[0].findall('CheckLine')\n Waiter = {\n 'Name': child.attrib['WaiterName'],\n 'Id': re.sub(r'\\{|\\}', '', child.attrib['WaiterGuid'])\n }\n Tables = []\n try:\n Table = {\n 'Number': int(child.attrib['TableName']),\n 'Id': re.sub(r'\\{|\\}', '', child.attrib['TableGuid'])\n }\n except:\n logger.critical('Table %s is not Integer value!!' % child.attrib['TableName'])\n Table = {\n 'Number': child.attrib['TableName'],\n 'Id': re.sub(r'\\{|\\}', '', child.attrib['TableGuid'])\n }\n Tables.append(Table)\n Products = []\n for x in all_items:\n Amount = x.attrib['Qnt']\n if Amount == '0.00':\n Deleted = True\n else:\n Deleted = False\n Product = {\n 'Id': str(uuid.uuid4()),\n 'ProductId': re.sub(r'\\{|\\}', '', x.attrib['Guid']),\n 'Name': x.attrib['Name'],\n 'Price': float(x.attrib['Price']),\n 'ResultSum': float(child.attrib['FullSum']), # todo исправить\n 'Amount': float(x.attrib['Qnt']),\n \"Comment\": \"\",\n 'Deleted': Deleted,\n \"DeletionMethod\": None,\n 'PrintTime':OrdertimeConvert(x.find('Packet').attrib['WasPrinted']),\n \"ServeTime\": None,\n \"Modifiers\": []\n }\n if re.sub(r'\\{|\\}', '', x.attrib['Guid']) == ProductGUID:\n Products.append(Product)\n Guests = []\n guests = {\n 'Id': str(uuid.uuid4()),\n 'Name': child.attrib['GuestName'],\n 'Products': Products\n }\n Guests.append(guests)\n Order = {\n 'Id': re.sub(r'\\{|\\}', '', child.attrib['OrderGuid']),\n \"OrderTypeId\": None,\n \"Status\": StatusOrder,\n 'ResultSum': float(child.attrib['FullSum']),\n 'FullSum': float(child.attrib['FullSum']),\n 'OpenTime': OrdertimeConvert(child.attrib['OpenTime']),\n \"BillTime\": None,\n \"CloseTime\": None,\n 'Number': datetime.today().timestamp(),\n 'Waiter': Waiter,\n \"Cashier\": None,\n 'Tables': Tables,\n \"IsBanquetOrder\": False,\n 'Guests': Guests,\n \"PaymentItems\": []\n }\n randomOrder = {\n 'Type': \"PrintedProductsChanged\",\n 'Order': Order,\n \"Idempotency_key\": None\n }\n if Product['Deleted'] == True: #если полностью удалён\n output = json.dumps(randomOrder, ensure_ascii=False, indent=1)\n orderObject = output\n #sendOrder(orderObject)\n if randomOrder['Order']['Guests'][0]['Products']:\n toSend.append(orderObject) #\n else:\n logger.debug ('Order with other than choosen GUID')\n except Exception as e:\n logger.critical('Failed parsing ScreenCheck')\n logger.critical(e)\n\n if child.tag == 'StoreCheck': # Сохранение заказа\n try:\n output = json.dumps(randomOrder, ensure_ascii=False, indent=1)\n orderObject = output\n #sendOrder(orderObject)\n if randomOrder['Order']['Guests'][0]['Products']:\n toSend.append(orderObject)\n else:\n logger.debug('Order with other than choosen GUID')\n ##############################\n all_items = root[0].findall('CheckLines')[0].findall('CheckLine')\n Waiter = {\n 'Name': child.attrib['WaiterName'],\n 'Id': re.sub(r'\\{|\\}', '', child.attrib['WaiterGuid'])\n }\n Tables = []\n try:\n Table = {\n 'Number': int(child.attrib['TableName']),\n 'Id': re.sub(r'\\{|\\}', '', child.attrib['TableGuid'])\n }\n except:\n logger.critical('Table %s is not Integer value!!' % child.attrib['TableName'])\n Table = {\n 'Number': child.attrib['TableName'],\n 'Id': re.sub(r'\\{|\\}', '', child.attrib['TableGuid'])\n }\n Tables.append(Table)\n Products = []\n for x in all_items:\n Amount = x.attrib['Qnt']\n if Amount == '0.00':\n Deleted = True\n else:\n Deleted = False\n print_time = OrdertimeConvert(x.find('Packet').attrib['WasPrinted'])\n Product = {\n 'Id': str(uuid.uuid4()),\n 'ProductId': re.sub(r'\\{|\\}', '', x.attrib['Guid']),\n 'Name': x.attrib['Name'],\n 'Price': float(x.attrib['Price']),\n 'ResultSum': float(child.attrib['FullSum']), # todo исправить\n 'Amount': float(x.attrib['Qnt']),\n \"Comment\": \"\",\n 'Deleted': Deleted,\n \"DeletionMethod\": None,\n 'PrintTime': print_time,\n \"ServeTime\": None,\n \"Modifiers\": []\n }\n if re.sub(r'\\{|\\}', '', x.attrib['Guid']) == ProductGUID:\n Products.append(Product)\n Guests = []\n guests = {\n 'Id': str(uuid.uuid4()),\n 'Name': child.attrib['GuestName'],\n 'Products': Products\n }\n Guests.append(guests)\n Order = {\n 'Id': re.sub(r'\\{|\\}', '', child.attrib['OrderGuid']),\n \"OrderTypeId\": None,\n \"Status\": StatusOrder,\n 'ResultSum': float(child.attrib['FullSum']),\n 'FullSum': float(child.attrib['FullSum']),\n 'OpenTime': OrdertimeConvert(child.attrib['OpenTime']),\n \"BillTime\": None,\n \"CloseTime\": None,\n 'Number': datetime.today().timestamp(),\n 'Waiter': Waiter,\n \"Cashier\": None,\n 'Tables': Tables,\n \"IsBanquetOrder\": False,\n 'Guests': Guests,\n \"PaymentItems\": []\n }\n randomOrder2 = {\n 'Type': \"PrintedProductsChanged\",\n 'Order': Order,\n \"Idempotency_key\": None\n }\n if randomOrder['Order']['Id'] != randomOrder2['Order']['Id']:\n output = json.dumps(randomOrder2, ensure_ascii=False, indent=1)\n orderObject = output\n try:\n logger.debug('========================OrderObject Begin==================')\n logger.debug(str(orderObject))\n logger.debug('========================OrderObject End====================')\n except:\n logger.debug(\"Can't write orderObject\")\n #sendOrder(orderObject)\n if randomOrder['Order']['Guests'][0]['Products']:\n toSend.append(orderObject)\n else:\n logger.debug ('Order with other than choosen GUID')\n except Exception as e:\n logger.critical('Failed parsing StoreCheck')\n logger.critical(e)\n","sub_path":"RKeeperInfo0312.py","file_name":"RKeeperInfo0312.py","file_ext":"py","file_size_in_byte":27742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"622308237","text":"import argparse\nimport time\nimport math\nimport os\nimport shutil\n\nimport torch\nimport torch.nn as nn\nimport numpy as np\n\nfrom hidden import data\nfrom hidden import utils\nfrom hidden import modelling\n\n\ndef main():\n parser = argparse.ArgumentParser(description='PyTorch Wikitext-2 RNN/LSTM Language Model')\n parser.add_argument('--split_dir', type=str, default='data/raw/ELTeC-eng',\n help='location of the data corpus')\n parser.add_argument('--model', type=str, default='LSTM',\n help='type of recurrent net (RNN_TANH, RNN_RELU, LSTM, GRU)')\n parser.add_argument('--min_char_freq', type=int, default=100,\n help='size of word embeddings')\n parser.add_argument('--emsize', type=int, default=64,\n help='size of embeddings')\n parser.add_argument('--nhid', type=int, default=256,\n help='number of hidden units per layer')\n parser.add_argument('--nlayers', type=int, default=1,\n help='number of layers')\n parser.add_argument('--lr', type=float, default=0.001,\n help='initial learning rate')\n parser.add_argument('--temperature', type=float, default=0.3,\n help='initial learning rate')\n parser.add_argument('--clip', type=float, default=30,\n help='gradient clipping')\n parser.add_argument('--epochs', type=int, default=10,\n help='upper epoch limit')\n parser.add_argument('--batch_size', type=int, default=24, metavar='N',\n help='batch size')\n parser.add_argument('--bptt', type=int, default=75,\n help='sequence length')\n parser.add_argument('--dropout', type=float, default=0.0,\n help='dropout applied to layers (0 = no dropout)')\n parser.add_argument('--seed', type=int, default=1111,\n help='random seed')\n parser.add_argument('--cuda', action='store_true',\n help='use CUDA')\n parser.add_argument('--reverse', default=False, action='store_true',\n help='backwards LM')\n parser.add_argument('--log-interval', type=int, default=100, metavar='N',\n help='report interval')\n parser.add_argument('--model_dir', type=str, default='data/lm_models',\n help='path to save the final model')\n\n args = parser.parse_args()\n print(args)\n\n torch.manual_seed(args.seed)\n if torch.cuda.is_available() and not args.cuda:\n print('WARNING: You have a CUDA device, so you should probably run with --cuda')\n \n if not os.path.exists(args.model_dir):\n os.mkdir(args.model_dir)\n\n args.model_prefix = f'{args.model_dir}/{os.path.basename(args.split_dir)}'\n if not args.reverse:\n try:\n shutil.rmtree(args.model_prefix)\n except FileNotFoundError:\n pass\n os.mkdir(args.model_prefix)\n\n dictionary = data.Dictionary(min_freq=args.min_char_freq)\n with open(os.sep.join((args.split_dir, 'train.txt')), 'r') as f:\n dictionary.fit(f.read())\n dictionary.dump(args.model_prefix + '/chardict.json')\n del dictionary\n\n if not args.reverse:\n model_path = args.model_prefix + '/lm_model.pt'\n else:\n model_path = args.model_prefix + '/rev_lm_model.pt'\n \n dictionary = data.Dictionary.load(args.model_prefix + '/chardict.json')\n\n print('char vocab:', dictionary.idx2char)\n\n with open(os.sep.join((args.split_dir, 'train.txt')), 'r') as f:\n train = f.read()[:100000]\n if args.reverse:\n train = train[::-1]\n train = torch.LongTensor(dictionary.transform(train))\n with open(os.sep.join((args.split_dir, 'dev.txt')), 'r') as f:\n dev = f.read()[:10000]\n if args.reverse:\n dev = dev[::-1]\n dev = torch.LongTensor(dictionary.transform(dev))\n with open(os.sep.join((args.split_dir, 'test.txt')), 'r') as f:\n test = f.read()[:10000]\n if args.reverse:\n test = test[::-1]\n test = torch.LongTensor(dictionary.transform(test))\n\n print(f'# of characters in train: {len(train)}')\n print(f'# of characters in dev: {len(dev)}')\n print(f'# of characters in test: {len(test)}')\n\n device = torch.device('cuda' if args.cuda else 'cpu')\n\n train = utils.batchify(train, args.batch_size)\n dev = utils.batchify(dev, args.batch_size)\n test = utils.batchify(test, args.batch_size)\n\n # set up model\n vocab_size = len(dictionary)\n lm = modelling.RNNModel(args.model, vocab_size, args.emsize,\n args.nhid, args.nlayers, args.dropout).to(device)\n optimizer = torch.optim.Adam(lm.parameters(), lr=args.lr, weight_decay=1e-5)\n criterion = nn.CrossEntropyLoss()\n print(lm)\n\n def epoch():\n lm.train()\n\n total_loss = 0.\n start_time = time.time()\n hidden = None\n\n for batch, i in enumerate(range(0, train.size(0) - 1, args.bptt)):\n data, targets = utils.get_batch(train, i, args.bptt)\n\n data = data.to(device)\n targets = targets.to(device)\n\n lm.zero_grad()\n output, hidden = lm(data, hidden)\n loss = criterion(output.view(-1, vocab_size), targets)\n\n loss.backward()\n torch.nn.utils.clip_grad_norm_(lm.parameters(), args.clip)\n optimizer.step()\n\n total_loss += loss.item()\n hidden = modelling.repackage_hidden(hidden)\n\n if batch % args.log_interval == 0 and batch > 0:\n cur_loss = total_loss / args.log_interval\n elapsed = time.time() - start_time\n print('| epoch {:3d} | {:5d}/{:5d} batches | lr {:02.6f} | ms/batch {:5.2f} | '\n 'loss {:5.6f} | ppl {:8.2f}'.format(\n epoch_idx, batch * args.batch_size, len(train) // args.bptt * args.batch_size, lr,\n elapsed * 1000 / args.log_interval, cur_loss, math.exp(cur_loss)))\n total_loss = 0\n start_time = time.time()\n\n with torch.no_grad():\n hid_ = None\n in_ = torch.randint(vocab_size, (1, 1), dtype=torch.long).to(device)\n\n for i in range(100):\n output, hid_ = lm(in_, hid_)\n char_weights = output.squeeze().div(args.temperature).exp().cpu()\n char_idx = torch.multinomial(char_weights, 1)[0]\n in_.fill_(char_idx)\n char = dictionary.idx2char[char_idx]\n print(char, end='')\n\n print('\\n')\n\n def evaluate(data_source):\n lm.eval()\n total_loss = 0.\n hidden = None\n\n with torch.no_grad():\n for i in range(0, data_source.size(0) - 1, args.bptt):\n data, targets = utils.get_batch(data_source, i, args.bptt)\n data = data.to(device)\n targets = targets.to(device)\n output, hidden = lm(data, hidden)\n output_flat = output.view(-1, vocab_size)\n total_loss += len(data) * criterion(output_flat, targets).item()\n hidden = modelling.repackage_hidden(hidden)\n\n return total_loss / len(data_source)\n\n lr = args.lr\n best_val_loss = None\n\n try:\n for epoch_idx in range(1, args.epochs+1):\n epoch_start_time = time.time()\n epoch()\n val_loss = evaluate(dev)\n\n print('-' * 89)\n print('| end of epoch {:3d} | time: {:5.2f}s | valid loss {:5.2f} | '\n 'valid ppl {:8.6f}'.format(epoch_idx, (time.time() - epoch_start_time),\n val_loss, math.exp(val_loss)))\n print('-' * 89)\n\n if not best_val_loss or val_loss < best_val_loss:\n with open(model_path, 'wb') as f:\n torch.save(lm, f)\n print('>>> saving model') \n best_val_loss = val_loss\n elif val_loss >= best_val_loss:\n lr *= 0.5\n print(f'>>> lowering learning rate to {lr}')\n for g in optimizer.param_groups:\n g['lr'] = lr\n\n except KeyboardInterrupt:\n print('-' * 89)\n print('Exiting from training early')\n\n with open(model_path, 'rb') as f:\n lm = torch.load(f)\n lm.rnn.flatten_parameters()\n\n test_loss = evaluate(test)\n print('=' * 89)\n print('| End of training | test loss {:5.6f} | test ppl {:8.2f}'.format(\n test_loss, math.exp(test_loss)))\n print('=' * 89)\n\nif __name__ == '__main__':\n main()","sub_path":"train_lm.py","file_name":"train_lm.py","file_ext":"py","file_size_in_byte":8798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"535356503","text":"class Solution(object):\n def isAnagram(self, s, t):\n if len(s) != len(t):\n return False\n\n originalWordCount = {}\n anagramWordCount = {}\n\n for char in set(s):\n originalWordCount[char] = s.count(char)\n for char in set(t):\n anagramWordCount[char] = t.count(char)\n\n if originalWordCount == anagramWordCount:\n return True\n else:\n return False\n","sub_path":"242-ValidAnagram.py","file_name":"242-ValidAnagram.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"477335353","text":"import streamlit as st\r\nfrom Bio.Seq import Seq\r\nfrom Bio import SeqIO\r\nimport neatbio.sequtils as utils\r\nfrom collections import Counter\r\n\r\n\r\n\r\n#new added line\r\nimport io\r\nst.set_option('deprecation.showPyplotGlobalUse', False)\r\n\r\n\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib\r\nmatplotlib.use(\"Agg\")\r\nimport numpy as np\r\n\r\n\r\n\r\ndef delta(x,y):\r\n return 0 if x == y else 1\r\n\r\n\r\ndef M(seq1,seq2,i,j,k):\r\n return sum(delta(x,y) for x,y in zip(seq1[i:i+k],seq2[j:j+k]))\r\n\r\n\r\ndef makeMatrix(seq1,seq2,k):\r\n n = len(seq1)\r\n m = len(seq2)\r\n return [[M(seq1,seq2,i,j,k) for j in range(m-k+1)] for i in range(n-k+1)]\r\n\r\n\r\ndef plotMatrix(M,t, seq1, seq2, nonblank = chr(0x25A0), blank = ' '):\r\n print(' |' + seq2)\r\n print('-'*(2 + len(seq2)))\r\n for label,row in zip(seq1,M):\r\n line = ''.join(nonblank if s < t else blank for s in row)\r\n print(label + '|' + line)\r\n\r\n\r\ndef dotplot(seq1,seq2,k = 1,t = 1):\r\n M = makeMatrix(seq1,seq2,k)\r\n plotMatrix(M, t, seq1,seq2) #experiment with character choice\r\n\r\n\r\ndef dotplotx(seq1,seq2):\r\n plt.imshow(np.array(makeMatrix(seq1,seq2,1)))\r\n # on x-axis list all sequences of seq 2\r\n xt=plt.xticks(np.arange(len(list(seq2))),list(seq2))\r\n # on y-axis list all sequences of seq 1\r\n yt=plt.yticks(np.arange(len(list(seq1))),list(seq1))\r\n plt.show()\r\n\r\n\r\n\r\ndef main():\r\n \"\"\"Bioinformatics Genome analysis web app\"\"\"\r\n\r\n\r\n st.title(\"DNA Genome analysis and Cosine Similarity Analysis web application\")\r\n menu= [\"Introduction\",\"DNA sequence Analysis\",\"Dotplot Analysis\",\"About us\"]\r\n choice= st.sidebar.selectbox(\"Select Option\",menu)\r\n\r\n if choice==\"Introduction\":\r\n st.subheader(\"Welcome to our Sequence Analysis Application :)\")\r\n elif choice==\"DNA sequence Analysis\":\r\n st.subheader(\"DNA sequence Analysis will be done here.\")\r\n seq_file=st.file_uploader(\"Upload the .FASTA file for any DNA analysis of the considered Genome.\", type=[\"fasta\",\"fa\"])\r\n\r\n if seq_file is not None:\r\n byte_str =seq_file.read()\r\n text_obj=byte_str.decode('UTF-8')\r\n dna_record= SeqIO.read(io.StringIO(text_obj),\"fasta\")\r\n #st.write(dna_record)\r\n dna_seq= dna_record.seq\r\n\r\n details= st.radio(\"Details of the DNA as provided by NCBI database:\",(\"DNA Record description\", \"Sequence\"))\r\n if details==\"DNA Record description\":\r\n st.write(dna_record.description)\r\n elif details==\"Sequence\":\r\n st.write(dna_record.seq)\r\n\r\n #Nucleotide\r\n st.subheader(\"Nucleotide Frequency :\")\r\n dna_freq=Counter(dna_seq)\r\n st.write(dna_freq)\r\n adenine_color=st.color_picker(\"Toggle the Adenine Colour \")\r\n guanine_color=st.color_picker(\"Toggle the Guanine Colour \")\r\n thymine_color=st.color_picker(\"Toggle the Thymine Colour \")\r\n cytosine_color=st.color_picker(\"Toggle the Cytosine Colour \")\r\n\r\n\r\n if st.button(\"Plot frequency\"):\r\n barlist=plt.bar(dna_freq.keys(),dna_freq.values())\r\n barlist[0].set_color(adenine_color)\r\n barlist[1].set_color(guanine_color)\r\n barlist[2].set_color(thymine_color)\r\n barlist[3].set_color(cytosine_color)\r\n st.pyplot()\r\n\r\n\r\n st.subheader(\"DNA complete Composition\")\r\n\r\n gc_score= utils.gc_content(str(dna_seq))\r\n at_score=utils.at_content(str(dna_seq))\r\n st.json({\"GC Content(for heat stability)\": gc_score,\"AT Content\":at_score })\r\n\r\n #protein synthesis\r\n st.subheader(\"Protein Synthesis operations on the DNA :\")\r\n p1=dna_seq.translate()\r\n aa_freq= Counter(str(p1))\r\n if st.checkbox(\"Transcription :\"):\r\n st.write(dna_seq.transcribe())\r\n elif st.checkbox(\"Translation :\"):\r\n st.write(dna_seq.translate())\r\n elif st.checkbox(\"Complement :\"):\r\n st.write(dna_seq.complement())\r\n elif st.checkbox(\"Amino Acid frequency :\"):\r\n st.write(aa_freq)\r\n\r\n elif st.checkbox(\"Plot the Amino Acid frequency :\"):\r\n aa_color=st.color_picker(\"Pick the Amino acid color:\")\r\n #barlist= plt.bar(aa_freq.keys(),aa_freq.values(),color=aa_color)\r\n #barlist[2].set_color(aa_color)\r\n plt.bar(aa_freq.keys(),aa_freq.values(),color=aa_color)\r\n st.pyplot()\r\n\r\n elif st.checkbox(\"The complete Amino acid name is given as\"):\r\n aa_name= str(p1).replace(\"*\",\"\")\r\n aa3= utils.convert_1to3(aa_name)\r\n st.write(aa_name)\r\n st.write(\"========================\")\r\n st.write(aa3)\r\n\r\n\r\n\r\n st.write(\"========================\")\r\n st.write(utils.get_acid_name(aa3))\r\n\r\n\r\n\r\n\r\n\r\n #Top most amino acids\r\n\r\n\r\n\r\n\r\n\r\n\r\n elif choice==\"Dotplot Analysis\":\r\n st.subheader(\"Generate Dotplot for the comparision between two DNA sequences here.\")\r\n seq_file1=st.file_uploader(\"Upload the first .FASTA file for any DNA analysis of the considered Genome.\", type=[\"fasta\",\"fa\"])\r\n seq_file2=st.file_uploader(\"Upload the second .FASTA file for any DNA analysis of the considered Genome.\", type=[\"fasta\",\"fa\"])\r\n\r\n\r\n if seq_file1 and seq_file2 is not None:\r\n byte_str1 =seq_file1.read()\r\n text_obj1=byte_str1.decode('UTF-8')\r\n dna_record1= SeqIO.read(io.StringIO(text_obj1),\"fasta\")\r\n\t\t\t\r\n byte_str2 =seq_file2.read()\r\n text_obj2=byte_str2.decode('UTF-8')\r\n dna_record2= SeqIO.read(io.StringIO(text_obj2),\"fasta\")\t\t\t\r\n\r\n #st.write(dna_record)\r\n dna_seq1= dna_record1.seq\r\n dna_seq2= dna_record2.seq\r\n\r\n details= st.radio(\"Details of the DNA as provided by NCBI database:\",(\"Record details from the NCBI database\", \"Gene Sequence\"))\r\n if details==\"Record details from the NCBI database\":\r\n st.write(dna_record1.description)\r\n st.write(\"===And the other Record is decribed as :===\")\r\n st.write(dna_record2.description)\r\n\r\n elif details==\"Gene Sequence\":\r\n st.write(dna_record1.seq)\r\n st.write(\"===And the other sequence can be given as: ===\")\r\n st.write(dna_record2.seq)\r\n\r\n\r\n display_limit=st.number_input(\"Select maximum number of Nucleotides\",10,200,50)\r\n if st.button(\"Push here for Dotplot :)\"):\r\n st.write(\"Comparing the first {} nucleotide of the two sequences\".format(display_limit))\r\n dotplotx(dna_seq1[0:display_limit],dna_seq2[0:display_limit])\r\n st.pyplot()\r\n\r\n\r\n\r\n elif choice==\"About us\":\r\n st.subheader(\"About the application and about us :)\")\r\n\r\nif __name__=='__main__':\r\n\tmain()\r\n\r\n\r\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"212428147","text":"from datetime import datetime, date, time, timedelta\nimport locale\nimport platform\nimport pymorphy2\n\nfrom bs4 import BeautifulSoup\n\nfrom webapp.db import db\nfrom webapp.news.models import News\nfrom webapp.news.parsers.utils import get_html, save_news\n\n\n# Тут зададим региональный параметр для любой ОС\nif platform.system() == 'Windows':\n locale.setlocale(locale.LC_ALL, 'russian')\nelse:\n locale.setlocale(locale.LC_TIME, 'ru_RU')\n\n\ndef parse_habr_date(date_str):\n if 'сегодня' in date_str:\n today = datetime.now()\n date_str = date_str.replace('сегдня', today.strftime('%d %B %Y'))\n elif 'вчера' in date_str:\n yesterday = datetime.now() - timedelta(days=1)\n date_str = date_str.replace('вчера', yesterday.strftime('%d %B %Y'))\n try:\n m = pymorphy2.MorphAnalyzer()\n day, month, year, qw2ewq, qwe2eewq = date_str.split(' ')\n # прео��разуем название месяца в именительный падеж с заглавной буквы\n new_month = m.parse(month)[0].inflect({'nomn'}).word.title()\n return datetime.strptime(' '.join([day, new_month, year]), '%d %B %Y')\n except ValueError:\n return datetime.now()\n\n\ndef get_news_snippets():\n html = get_html(\"https://habr.com/ru/search/?target_type=posts&q=python&order_by=date\")\n if html:\n soup = BeautifulSoup(html, 'html.parser') # Бреобразует наш HTML в дерево элементов с которым удобнее работать фунциям этой библиотеки\n all_news = soup.find(\"ul\", class_=\"content-list_posts\").findAll('li', class_='content-list__item_post') # Делаем выборку элементов страницы при помощи поиска\n #result_news = []\n for news in all_news:\n title = news.find('a', class_=\"post__title_link\").text # Выбираем текст заголовка\n url = news.find('a', class_=\"post__title_link\")[\"href\"] # Выбираем ссылку заголовка (к атрибутам обращаемся как к элементам славаря)\n published = news.find('span', class_=\"post__time\").text # Выбираем время\n published = parse_habr_date(published)\n save_news(title, url, published) # После формирования, вызываем запись в базу\n\n\ndef get_news_content():\n news_without_texh = News.query.filter(News.text.is_(None))\n for news in news_without_texh:\n html = get_html(news.url)\n if html:\n soup = BeautifulSoup(html, 'html.parser')\n # .decode_contents() позволяет получить html вместо текста\n article = soup.find('div', class_='post__text-html').decode_contents()\n if article:\n news.text = article\n db.session.add(news)\n db.session.commit()\n","sub_path":"webapp/news/parsers/habr.py","file_name":"habr.py","file_ext":"py","file_size_in_byte":3040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"60144120","text":"# -*- encoding: utf-8 -*-\nclass Solution:\n \"\"\"\n @param prices: Given an integer array\n @return: Maximum profit\n \"\"\"\n def maxProfit(self, prices):\n # write your code here\n B = []\n profit = 0\n for i in range(1,len(prices)):\n b = prices[i]-prices[i-1]\n if b > 0:\n profit += b\n return profit\n\n# 我的练习\nclass Solution2:\n \"\"\"\n @param prices: Given an integer array\n @return: Maximum profit\n \"\"\"\n def maxProfit(self, prices):\n # write your code here\n # edge case:\n if prices is None or len(prices) == 0:\n return 0\n\n le = len(prices)\n profit = []\n for i in range(1,le):\n profit.append(prices[i] - prices[i-1])\n max_profit = 0\n for i in range(len(profit)):\n if profit[i]>0:\n max_profit += profit[i]\n return max_profit\n\n\n","sub_path":"lintcode/Array/150 Best Time to Buy and Sell Stock II.py","file_name":"150 Best Time to Buy and Sell Stock II.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"285192222","text":"# !/usr/bin/env python\n# -*- coding:utf-8 -*-\n\"\"\"\nWindow's custom title bar.\n\"\"\"\n__author__ = \"jeremyjone\"\n__datetime__ = \"2019/4/30 18:08\"\n__all__ = [\"TitleWidget\"]\n\nimport os, sys\nimport PySide.QtGui as QtGui\nimport PySide.QtCore as QtCore\n\nfrom widget import UILoader\nfrom config.conModel import CONFIG\n\n\nclass TitleWidget(QtGui.QWidget):\n windowMinimumed = QtCore.Signal()\n # windowMaximumed = QtCore.Signal()\n # windowNormaled = QtCore.Signal()\n windowClosed = QtCore.Signal()\n windowMoved = QtCore.Signal(QtCore.QPoint)\n windowReleased = QtCore.Signal()\n\n def __init__(self, parent=None):\n super(TitleWidget, self).__init__(parent)\n self.mPos = None\n self.initUI()\n\n def initUI(self):\n win = UILoader(\"./Resource/ui/title.ui\", \"./Resource/css/title.css\")\n\n l = win.findChild(QtGui.QLayout, \"gridLayout\")\n self.setLayout(l)\n self.setStyleSheet(win.styleSheet())\n self.setFixedHeight(win.height())\n\n self.APPNameLabel = self.findChild(QtGui.QLabel, \"APPNameLabel\")\n self.titleTextLabel = self.findChild(QtGui.QLabel, \"titleTextLabel\")\n self.setWindowTitle()\n\n iconLabel = self.findChild(QtGui.QLabel, \"iconLabel\")\n iconLabel.setPixmap(QtGui.QPixmap(\"./Resource/icon/ffm_main.png\"))\n\n self.titleWidget = self.findChild(QtGui.QWidget, \"titleWidget\")\n # _palette = QtGui.QPalette()\n # _pixmap = QtGui.QPixmap(\"./Resource/image/background_title_2.png\").scaled(\n # self.titleWidget.width(), self.titleWidget.height(),\n # QtCore.Qt.KeepAspectRatioByExpanding, QtCore.Qt.SmoothTransformation)\n # _palette.setBrush(QtGui.QPalette.Background, QtGui.QBrush(_pixmap))\n # self.titleWidget.setPalette(_palette)\n\n self.minWinBtn = self.findChild(QtGui.QPushButton, \"minWinBtn\")\n self.minWinBtn.setToolTip(u\"最小化\")\n self.closeWinBtn = self.findChild(QtGui.QPushButton, \"closeWinBtn\")\n self.minWinBtn.clicked.connect(lambda : self.windowMinimumed.emit())\n\n self.showMinButton()\n\n if CONFIG.Window.CloseButtonExit:\n self.closeWinBtn.clicked.connect(lambda: sys.exit(0))\n self.closeWinBtn.setToolTip(u\"退出\")\n else:\n self.closeWinBtn.clicked.connect(lambda: self.windowClosed.emit())\n self.closeWinBtn.setToolTip(u\"关闭窗口\")\n\n def setWindowTitle(self, *args, **kwargs):\n if CONFIG.Window.ShowNameOnTitle:\n self.APPNameLabel.setText(CONFIG.Main.Name)\n self.titleTextLabel.setText(\" - \" + \"Jz\")\n else:\n self.APPNameLabel.setText(\"\")\n self.titleTextLabel.setText(\"\")\n\n def showMinButton(self):\n if not CONFIG.Window.ShowMinimizeButton:\n self.minWinBtn.hide()\n else:\n self.minWinBtn.show()\n\n def mousePressEvent(self, event):\n if event.button() == QtCore.Qt.LeftButton:\n self.mPos = event.pos()\n event.accept()\n # It cannot be moved when the window is maximized or full screen.\n self._canMove = not self.isMaximized() or not self.isFullScreen()\n\n def mouseReleaseEvent(self, event):\n self.mPos = None\n event.accept()\n self._canMove = False\n self.windowReleased.emit()\n\n def mouseMoveEvent(self, event):\n if event.buttons() == QtCore.Qt.LeftButton and self.mPos and self._canMove:\n self.windowMoved.emit(self.mapToGlobal(event.pos() - self.mPos))\n event.accept()\n\n def enterEvent(self, event):\n self.setCursor(QtCore.Qt.ArrowCursor)\n super(TitleWidget, self).enterEvent(event)\n\n\nif __name__ == \"__main__\":\n app = QtGui.QApplication(sys.argv)\n t = TitleWidget()\n t.show()\n sys.exit(app.exec_())\n","sub_path":"widget/titleWidget.py","file_name":"titleWidget.py","file_ext":"py","file_size_in_byte":3798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"303955038","text":"from PyQt5.QtWidgets import QApplication, QDialog\nfrom PyQt5.QtCore import Qt, pyqtSignal, QObject, QTimer\nfrom PyQt5.QtGui import QMovie\nfrom time import time\nfrom threading import Timer\nfrom datetime import datetime\n\n\n#get the UI from here\nfrom screen_saver_ui import Ui_ScreenSaverDialog\n\n\n#################################################\n# FirstDialog Class - to get the system running #\n#################################################\nclass ScreenSaverDialog(QDialog):\n\n # signal to update in 10 second\n ten_seconds_signal = pyqtSignal()\n\n def __init__(self):\n super(ScreenSaverDialog, self).__init__()\n\n # Setup the user interface from Designer.\n self.ui = Ui_ScreenSaverDialog()\n self.ui.setupUi(self)\n\n # Setup signals\n self.ui.doneButton.clicked.connect(self.accept)\n\n self.ui.doneButton.setStyleSheet(\"background-color: rgba(255, 255, 255, 0); \\\n border: 0px\");\n\n self.which_movie = 'RK'\n self.movie = QMovie(':/screen_saver/resources/Rk69.gif')\n self.ui.gifLabel.setMovie(self.movie)\n self.movie.start()\n \n # to start 10 seconds timer\n self.t10seg = QTimer()\n self.t10seg.timeout.connect(self.TimerTenSecs)\n self.t10seg.start(10000)\n\n #SIGNALS\n # connect the timer signal to the Update\n self.ten_seconds_signal.connect(self.UpdateTenSecs)\n\n\n \"\"\" QTimer callback emit a signal to not upset the timer interval \"\"\"\n def TimerTenSecs(self):\n self.ten_seconds_signal.emit()\n\n\n def UpdateTenSecs (self):\n # do a UI update if its necessary\n if self.which_movie == 'RK':\n self.movie = QMovie(':/screen_saver/resources/UIBJ.gif')\n self.ui.gifLabel.setMovie(self.movie)\n self.movie.start()\n\n self.which_movie = 'UIBJ'\n elif self.which_movie == 'UIBJ':\n self.movie = QMovie(':/screen_saver/resources/1LFE.gif')\n self.ui.gifLabel.setMovie(self.movie)\n self.movie.start()\n\n self.which_movie = '1LFE'\n elif self.which_movie == '1LFE':\n self.movie = QMovie(':/screen_saver/resources/Rk69.gif')\n self.ui.gifLabel.setMovie(self.movie)\n self.movie.start()\n\n self.which_movie = 'RK'\n\n\n \n\n\n \n### end of file ###\n","sub_path":"rpi_base/screen_saver/screen_saver_cls.py","file_name":"screen_saver_cls.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"15449855","text":"#!/bin/python\n# -*- coding: utf-8 -*-\n#\n# author : alex pokrov \n# 10/5/17 10:10 PM\n\narr = [2,3,4,5,4,3,2,3,4,2,3]\nx = 0\ni = 0\nprint(arr)\nfor element in arr:\n if arr[i] == 2 and x == 0:\n x = x+1\n elif arr[i] == 2 and x > 0:\n arr[i]+=1;\n i = i+1\n\nprint(arr)\n","sub_path":"array/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"366588646","text":"import json\nimport matplotlib.pyplot as plt\nimport requests\n\nsave = []\nmethod = 'network' # change the method where you want to get data\n\nif method == 'network':\n url = \"https://think.cs.vt.edu/corgis/json/aids/aids.json\"\n data = requests.get(url).json()\nelse:\n with open(\"aids.json\", 'r') as fr:\n data = json.load(fr)\n\nfor x in data:\n print(x['Data'].keys())\n res = x['Data']['HIV Prevalence']['Adults']\n save.append(res)\n\nplot_data = save[:100]\nprint(plot_data)\n\ny = range(len(plot_data))\n\nplt.figure()\nplt.plot(y, plot_data)\nplt.savefig(\"line plot.png\")\nplt.show()\nplt.close()\n\nplt.figure()\nplt.scatter(y, plot_data)\nplt.savefig(\"scatter plot.png\")\nplt.show()\nplt.close()\n\nplt.figure()\nplt.boxplot(y, plot_data)\nplt.savefig(\"scatter plot.png\")\nplt.show()\nplt.close()\n\n\nm = sum(plot_data) / len(plot_data)\nprint(\"mean of data:{}\".format(m))\n\nplot_data.sort()\nmedian = plot_data[len(plot_data) // 2]\nprint(\"median:{}\".format(median))\n","sub_path":"project_1028/twistedFate_500/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"338105834","text":"import os\nimport psycopg2\nfrom flask import Flask, render_template, request, session, redirect, url_for\nimport urllib.parse as urlparse\nfrom datetime import datetime\nfrom src.db import Database\nfrom src.models import Host, Application, Scan, Owner\n\napp = Flask(__name__)\napp.secret_key = 's3cret'\napp.debug = True\n\nurl = urlparse.urlparse(os.environ.get('DATABASE_URL'))\ndb = \"dbname=%s user=%s password=%s host=%s \" % (url.path[1:], url.username, url.password, url.hostname)\n\ndef exec_file(sql_file):\n conn = psycopg2.connect(db)\n cursor = conn.cursor()\n\n with open(sql_file, 'r') as sql_stm:\n statements = sql_stm.read()\n statements = statements.split('\\n\\n')\n \n for statement in statements:\n cursor.execute(statement)\n\n conn.commit()\n cursor.close()\n conn.close()\n\nexec_file(\"sql/drop_tables.sql\")\nexec_file(\"sql/create_tables.sql\")\nexec_file(\"sql/test_data.sql\")\n\n@app.route('/')\ndef index():\n return render_template('intro.html')\n\n@app.route('/hosts')\ndef hosts():\n session['logged_in'] = True\n \n conn = psycopg2.connect(db)\n cursor = conn.cursor()\n cursor.execute('SELECT * FROM host;')\n\n host_list = []\n for row in cursor.fetchall():\n host = {}\n host[\"id\"] = row[0]\n host[\"owner_id\"] = row[1]\n host[\"hostname\"] = row[2]\n host[\"ip\"] = row[3]\n host[\"platform\"] = row[4]\n host[\"date_added\"] = row[5]\n\n host_list.append(host)\n\n cursor.close()\n conn.close()\n\n return render_template('hosts.html', hosts=host_list, session=session)\n\n@app.route('/add_host', methods=['POST'])\ndef add_host():\n i = len(host_db)\n owner = Owner(i, \"owner%d\" % (i), \"type%d\" % (i))\n host = Host(i, \"owner\", request.form['ip'], request.form['hostname'], request.form['platform'], datetime.now())\n host_db.append(host)\n return redirect(url_for('hosts'))\n\n@app.route('/remove_host', methods=['POST'])\ndef remove_host():\n to_remove = None\n for host in host_db:\n if host.id == int(request.form['host_id']):\n to_remove = host\n\n if to_remove:\n host_db.remove(to_remove)\n\n return redirect(url_for('hosts'))\n\n@app.route('/database_connection')\ndef db_connect():\n try:\n conn = psycopg2.connect(db)\n cur = conn.cursor()\n db_test = DB_test(\"name\", cur)\n tables = db_test.getTables()\n\n except:\n print(\"error\")\n\n return render_template('db_test.html', tables=tables)\n\nif __name__ == '__main__':\n if os.sys.argv[1] == \"drop\":\n db.exec_file(\"sql/drop_tables.sql\")\n print(\"dropped tables\")\n\n port = int(os.environ.get('PORT', 5000))\n app.run(host='0.0.0.0', port=port, debug=True)\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"340889351","text":"import sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QAxContainer import *\n\nclass MyWindow(QMainWindow):\n def __init__(self):\n super().__init__()\n\n self.kiwoom = QAxWidget(\"KHOPENAPI.KHOpenAPICtrl.1\")\n self.kiwoom.dynamicCall(\"CommConnect()\")\n\n self.kiwoom.OnReceiveTrData.connect(self.receive_trdata)\n\n self.setWindowTitle(\"Python Home Trading System by bsjeon\")\n self.setGeometry(300, 300, 300, 150)\n\n btn1 = QPushButton(\"Show\", self)\n btn1.move(190, 10)\n btn1.clicked.connect(self.btn1_clicked)\n\n self.listWidget = QListWidget(self)\n self.listWidget.setGeometry(10, 10, 170, 130)\n\n def btn1_clicked(self):\n # SetInputValue\n code = \"000030\"\n startDate = \"20160101\"\n self.kiwoom.dynamicCall(\"SetInputValue(QString, QString)\", \"종목코드\", code)\n self.kiwoom.dynamicCall(\"SetInputValue(QString, QString)\", \"시작일자\", startDate)\n\n # CommRqData\n self.kiwoom.dynamicCall(\"CommRqData(QString, QString, int, QString)\", \"opt10015_req\", \"opt10015\", 0, \"0101\")\n\n def receive_trdata(self, screen_no, rqname, trcode, recordname, prev_next, data_len, err_code, msg1, msg2):\n if rqname == \"opt10015_req\":\n name = self.kiwoom.dynamicCall(\"CommGetDataEx(QString, QString, QString, int, QString)\", trcode, \"\", rqname,\n 0, \"일자\")\n volume = self.kiwoom.dynamicCall(\"CommGetData(QString, QString, QString, int, QString)\", trcode, \"\", rqname,\n 0, \"종가\")\n print(name)\n dateClosingPriceList = []\n dateClosingPriceList.append(name.strip())\n dateClosingPriceList.append(volume.strip())\n self.listWidget.addItems(dateClosingPriceList)\n # ret = self.kiwoom.dynamicCall(\"GetCodeListByMarket(QString)\", [\"0\"])\n # kospi_code_list = ret.split(';')\n # kospi_code_name_list = []\n #\n # for x in kospi_code_list:\n # name = self.kiwoom.dynamicCall(\"GetMasterCodeName(QString)\", [x])\n # kospi_code_name_list.append(x + \" : \" + name)\n #\n # self.listWidget.addItems(kospi_code_name_list)\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n myWindow = MyWindow()\n myWindow.show()\n sys.exit(app.exec_())","sub_path":"SimpleHTS.py","file_name":"SimpleHTS.py","file_ext":"py","file_size_in_byte":2399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"248241847","text":"\"\"\" A collection of image similarity metrics. \"\"\"\n\nimport collections\n\nimport numpy as np\nfrom scipy import ndimage\n\n# Container for registration methods:\n\nMethod = collections.namedtuple('method', 'jacobian error update')\n\n\ndef gradient(image, variance=0.1):\n \"\"\" Computes the image gradient \"\"\"\n grad = np.gradient(image)\n\n dIx = ndimage.gaussian_filter(grad[1], variance).flatten()\n dIy = ndimage.gaussian_filter(grad[0], variance).flatten()\n\n return dIx, dIy\n\n# ==============================================================================\n# Forwards additive:\n# ==============================================================================\n\n\ndef forwardsAdditiveJacobian(image, template, model, p):\n \"\"\"\n Computes the jacobian dP/dE.\n\n Parameters\n ----------\n model: deformation model\n A particular deformation model.\n warpedImage: nd-array\n Input image after warping.\n p : optional list\n Current warp parameters\n\n Returns\n -------\n jacobian: nd-array\n A jacobain matrix. (m x n)\n | where: m = number of image pixels,\n | p = number of parameters.\n \"\"\"\n\n dIx, dIy = gradient(image)\n\n dPx, dPy = model.jacobian(template.coords, p)\n\n J = np.zeros_like(dPx)\n for index in range(0, dPx.shape[1]):\n J[:, index] = (dPx[:, index] * dIx) + (dPy[:, index] * dIy)\n return J\n\n\ndef forwardsAdditiveError(image, template):\n \"\"\" Compute the forwards additive error \"\"\"\n return (template - image).flatten()\n\n\ndef forwardsAdditiveUpdate(p, deltaP, model=None):\n \"\"\" Compute the forwards additive error \"\"\"\n return p + deltaP\n\n# Define the forwards additive approach:\n\nforwardsAdditive = Method(\n forwardsAdditiveJacobian,\n forwardsAdditiveError,\n forwardsAdditiveUpdate\n )\n\n# ==============================================================================\n# Forwards compositional.\n# ==============================================================================\n\n\ndef forwardsCompositionalError(image, template):\n \"\"\" Compute the forwards additive error \"\"\"\n return (template - image).flatten()\n\n\ndef forwardsCompositionalUpdate(p, deltaP, tform):\n \"\"\" Compute the forwards additive error \"\"\"\n return tform.vector(np.dot(tform.matrix(p), tform.matrix(deltaP)))\n\n\nforwardsCompositional = Method(\n forwardsAdditiveJacobian,\n forwardsCompositionalError,\n forwardsCompositionalUpdate\n )\n\n\n# ==============================================================================\n# Inverse compositional.\n# ==============================================================================\n\n\ndef inverseCompositionalJacobian(image, template, model, p):\n \"\"\"\n Computes the jacobian dP/dE.\n\n Parameters\n ----------\n model: deformation model\n A particular deformation model.\n warpedImage: nd-array\n Input image after warping.\n p : optional list\n Current warp parameters\n\n Returns\n -------\n jacobian: nd-array\n A jacobain matrix. (m x n)\n | where: m = number of image pixels,\n | p = number of parameters.\n \"\"\"\n\n dIx, dIy = gradient(template.data, variance=1.5)\n\n dPx, dPy = model.jacobian(template.coords, p)\n\n J = np.zeros_like(dPx)\n for index in range(0, dPx.shape[1]):\n J[:, index] = (dPx[:, index] * dIx) + (dPy[:, index] * dIy)\n return J\n\n\ndef inverseCompositionalError(image, template):\n \"\"\" Compute the inverse additive error \"\"\"\n return (image - template).flatten()\n\n\ndef inverseCompositionalUpdate(p, deltaP, tform):\n \"\"\" Compute the inverse compositional error \"\"\"\n\n return tform.vector(\n np.dot(tform.matrix(p), np.linalg.inv(tform.matrix(deltaP)))\n )\n\n\ninverseCompositional = Method(\n inverseCompositionalJacobian,\n inverseCompositionalError,\n inverseCompositionalUpdate\n )\n\n","sub_path":"imreg/metric.py","file_name":"metric.py","file_ext":"py","file_size_in_byte":3880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"67837775","text":"import json\r\nimport requests\r\nimport tkinter as tk\r\nfrom tkinter import *\r\nfrom tkinter import ttk\r\n\r\n# Making a list of currencies. You can add more items (currencies) to the list\r\ncurrencyList = ['AED', 'AUD', 'BHD', 'BRL', 'CAD', 'CNY', 'EUR', 'HKD', 'INR', 'USD']\r\n\r\n# Defining CreateWidgets() to create necessary widgets for the GUI\r\ndef CreateWidgets():\r\n inputAMT_Label = Label(root, text = \"AMOUNT:\", bg = \"darkolivegreen4\")\r\n inputAMT_Label.grid(row = 1, column = 0, padx = 5, pady = 5)\r\n inputAMT_Entry = Entry(root, width = 20, textvariable = getAMT)\r\n inputAMT_Entry.grid(row = 1, column = 1, padx = 5, pady = 5)\r\n\r\n fromLabel = Label(root, text = \"FROM:\", bg = \"darkolivegreen4\")\r\n fromLabel.grid(row = 2, column = 0, padx = 5, pady = 5)\r\n root.fromCombo = ttk.Combobox(root, values = currencyList)\r\n root.fromCombo.grid(row = 2, column = 1, padx = 5, pady = 5)\r\n\r\n toLabel = Label(root, text = \"TO:\", bg = \"darkolivegreen4\")\r\n toLabel.grid(row=3, column = 0, padx = 5, pady=5)\r\n root.toCombo = ttk.Combobox(root, values = currencyList)\r\n root.toCombo.grid(row = 3, column = 1, padx = 5, pady = 5)\r\n\r\n convertButton = Button(root, text = \"CONVERT\", width = 25, command = Convert)\r\n convertButton.grid(row = 4, column = 0, columnspan = 2, padx = 5, pady = 5)\r\n\r\n exrateLabel = Label(root, text = \"EXCHANGE RATE:\",bg = \"darkolivegreen4\")\r\n exrateLabel.grid(row = 5, column = 0, padx = 5, pady = 30)\r\n root.exchangerateLabel = Label(root, font = ('',20),bg = \"darkolivegreen4\")\r\n root.exchangerateLabel.grid(row = 5, column = 1, padx = 5, pady = 30)\r\n\r\n outputLabel = Label(root, text = \"CONVERTED AMOUNT:\", bg = \"darkolivegreen4\")\r\n outputLabel.grid(row = 6, column = 0,padx = 5, pady = 20)\r\n root.outputAMT_Label = Label(root, font = ('',20),bg = \"darkolivegreen4\")\r\n root.outputAMT_Label.grid(row = 6, column = 1, padx = 5, pady = 20)\r\n\r\n# Defining Convert() function for converting the curreny\r\ndef Convert():\r\n # Converting user-input amount which is a string into float type\r\n inputAmt = float(getAMT.get())\r\n fromCur = root.fromCombo.get()\r\n toCur = root.toCombo.get()\r\n apiKey = \"YOUR API KEY\"\r\n # Storing the base URL\r\n baseURL = r\"https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE\"\r\n # Storing the complete URL\r\n inputURL = baseURL+\"&from_currency=\"+fromCur+\"&to_currency=\"+toCur+\"&apikey=\"+apiKey\r\n\r\n # Sending the request to URL & Fetching and Storing the response in response variable\r\n response = requests.get(inputURL)\r\n # Returning the JSON object of the response and storing it in result\r\n result = response.json()\r\n print(json.dumps(result, indent=2))\r\n\r\n # Getting the exchange rate (Required Information)\r\n exchangeRate = float(result[\"Realtime Currency Exchange Rate\"]['5. Exchange Rate'])\r\n # Displaying exchange rate in respective label after rounding to 2 decimal places\r\n root.exchangerateLabel.config(text=str(round(exchangeRate, 2)))\r\n\r\n # Calculating the converted amount and rounding the decimal to 2 places\r\n calculateAmt = round(inputAmt * exchangeRate, 2)\r\n # Displaying the converted amount in the respective label\r\n root.outputAMT_Label.config(text=str(calculateAmt))\r\n\r\n# Creating object of tk class\r\nroot = tk.Tk()\r\nroot.geometry(\"400x350\")\r\nroot.resizable(False, False)\r\nroot.title(\"PyCurrenyConverter\")\r\nroot.config(bg = \"darkolivegreen4\")\r\n\r\n# Creating tkinter variables\r\ngetAMT = StringVar()\r\n\r\n# Calling the CreateWidgets() function\r\nCreateWidgets()\r\n\r\n# Defining infinite loop to run application\r\nroot.mainloop()\r\n","sub_path":"curr.py","file_name":"curr.py","file_ext":"py","file_size_in_byte":3614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"623011356","text":"# -*- coding: utf-8 -*-\n# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nevaluate wordseg for LAC and other open-source wordseg tools\n\"\"\"\nfrom __future__ import print_function\nfrom __future__ import division\n\nimport sys\nimport os\nimport io\n\n\ndef to_unicode(string):\n \"\"\" string compatibility for python2 & python3 \"\"\"\n if sys.version_info.major == 2 and isinstance(string, str):\n return string.decode(\"utf-8\")\n else:\n return string\n\n\ndef to_set(words):\n \"\"\" cut list to set of (string, off) \"\"\"\n off = 0\n s = set()\n for w in words:\n if w:\n s.add((off, w))\n off += len(w)\n return s\n\n\ndef cal_fscore(standard, result, split_delim=\" \"):\n \"\"\" caculate fscore for wordseg\n Param: standard, list of str, ground-truth labels , e.g. [\"a b c\", \"d ef g\"]\n Param: result, list of str, predicted result, e.g. [\"ab c\", \"d e fg\"]\n \"\"\"\n assert len(standard) == len(result)\n std, rst, cor = 0, 0, 0\n for s, r in zip(standard, result):\n s = to_set(s.rstrip().split(split_delim))\n r = to_set(r.rstrip().split(split_delim))\n std += len(s)\n rst += len(r)\n cor += len(s & r)\n p = 1.0 * cor / rst\n r = 1.0 * cor / std\n f = 2 * p * r / (p + r)\n\n print(\"std, rst, cor = %d, %d, %d\" % (std, rst, cor))\n print(\"precision = %.5f, recall = %.5f, f1 = %.5f\" % (p, r, f))\n #print(\"| | %.5f | %.5f | %.5f |\" % (p, r, f))\n print(\"\")\n\n return p, r, f\n\n\ndef load_testdata(datapath=\"./data/test_data/test_part\"):\n \"\"\"none\"\"\"\n sentences = []\n sent_seg_list = []\n for line in io.open(datapath, 'r', encoding='utf8'):\n sent, label = line.strip().split(\"\\t\")\n sentences.append(sent)\n\n sent = to_unicode(sent)\n label = label.split(\" \")\n assert len(sent) == len(label)\n\n # parse segment\n words = []\n current_word = \"\"\n for w, l in zip(sent, label):\n if l.endswith(\"-B\"):\n if current_word != \"\":\n words.append(current_word)\n current_word = w\n elif l.endswith(\"-I\"):\n current_word += w\n elif l.endswith(\"-O\"):\n if current_word != \"\":\n words.append(current_word)\n words.append(w)\n current_word = \"\"\n else:\n raise ValueError(\"wrong label: \" + l)\n if current_word != \"\":\n words.append(current_word)\n sent_seg = \" \".join(words)\n sent_seg_list.append(sent_seg)\n print(\"got %d lines\" % (len(sent_seg_list)))\n return sent_seg_list, sentences\n\n\ndef get_lac_result():\n \"\"\"\n get LAC predicted result by:\n `sh run.sh | tail -n 100 > result.txt`\n \"\"\"\n sent_seg_list = []\n for line in io.open(\"./result.txt\", 'r', encoding='utf8'):\n line = line.strip().split(\" \")\n words = [pair.split(\"/\")[0] for pair in line]\n labels = [pair.split(\"/\")[1] for pair in line]\n sent_seg = \" \".join(words)\n sent_seg = to_unicode(sent_seg)\n sent_seg_list.append(sent_seg)\n return sent_seg_list\n\n\ndef get_jieba_result(sentences):\n \"\"\"\n Ref to: https://github.com/fxsjy/jieba\n Install by `pip install jieba`\n \"\"\"\n import jieba\n preds = []\n for sentence in sentences:\n sent_seg = \" \".join(jieba.lcut(sentence))\n sent_seg = to_unicode(sent_seg)\n preds.append(sent_seg)\n return preds\n\n\ndef get_thulac_result(sentences):\n \"\"\"\n Ref to: http://thulac.thunlp.org/\n Install by: `pip install thulac`\n \"\"\"\n import thulac\n preds = []\n lac = thulac.thulac(seg_only=True)\n for sentence in sentences:\n sent_seg = lac.cut(sentence, text=True)\n sent_seg = to_unicode(sent_seg)\n preds.append(sent_seg)\n return preds\n\n\ndef get_pkuseg_result(sentences):\n \"\"\"\n Ref to: https://github.com/lancopku/pkuseg-python\n Install by: `pip3 install pkuseg`\n You should noticed that pkuseg-python only support python3\n \"\"\"\n import pkuseg\n seg = pkuseg.pkuseg()\n preds = []\n for sentence in sentences:\n sent_seg = \" \".join(seg.cut(sentence))\n sent_seg = to_unicode(sent_seg)\n preds.append(sent_seg)\n return preds\n\n\ndef get_hanlp_result(sentences):\n \"\"\"\n Ref to: https://github.com/hankcs/pyhanlp\n Install by: pip install pyhanlp\n (Before using pyhanlp, you need to download the model manully.)\n \"\"\"\n from pyhanlp import HanLP\n preds = []\n for sentence in sentences:\n arraylist = HanLP.segment(sentence)\n sent_seg = \" \".join(\n [term.toString().split(\"/\")[0] for term in arraylist])\n sent_seg = to_unicode(sent_seg)\n preds.append(sent_seg)\n return preds\n\n\ndef get_nlpir_result(sentences):\n \"\"\"\n Ref to: https://github.com/tsroten/pynlpir\n Install by `pip install pynlpir`\n Run `pynlpir update` to update License\n \"\"\"\n import pynlpir\n pynlpir.open()\n preds = []\n for sentence in sentences:\n sent_seg = \" \".join(pynlpir.segment(sentence, pos_tagging=False))\n sent_seg = to_unicode(sent_seg)\n preds.append(sent_seg)\n return preds\n\n\ndef get_ltp_result(sentences):\n \"\"\"\n Ref to: https://github.com/HIT-SCIR/pyltp\n 1. Install by `pip install pyltp`\n 2. Download models from http://ltp.ai/download.html\n \"\"\"\n from pyltp import Segmentor\n segmentor = Segmentor()\n model_path = \"./ltp_data_v3.4.0/cws.model\"\n if not os.path.exists(model_path):\n raise IOError(\"LTP Model do not exist! Download it first!\")\n segmentor.load(model_path)\n preds = []\n for sentence in sentences:\n sent_seg = \" \".join(segmentor.segment(sentence))\n sent_seg = to_unicode(sent_seg)\n preds.append(sent_seg)\n segmentor.release()\n\n return preds\n\n\ndef print_array(array):\n \"\"\"print some case\"\"\"\n for i in [1, 10, 20, 30, 40]:\n print(\"case \" + str(i) + \": \\t\" + array[i])\n\n\ndef evaluate_all():\n \"\"\"none\"\"\"\n standard, sentences = load_testdata()\n print_array(standard)\n\n # evaluate lac\n preds = get_lac_result()\n print(\"lac result:\")\n print_array(preds)\n cal_fscore(standard=standard, result=preds)\n\n # evaluate jieba\n preds = get_jieba_result(sentences)\n print(\"jieba result\")\n print_array(preds)\n cal_fscore(standard=standard, result=preds)\n\n # evaluate thulac\n preds = get_thulac_result(sentences)\n print(\"thulac result\")\n print_array(preds)\n cal_fscore(standard=standard, result=preds)\n\n # evaluate pkuseg, but pyuseg only support python3\n if sys.version_info.major == 3:\n preds = get_pkuseg_result(sentences)\n print(\"pkuseg result\")\n print_array(preds)\n cal_fscore(standard=standard, result=preds)\n\n # evaluate HanLP\n preds = get_hanlp_result(sentences)\n print(\"HanLP result\")\n print_array(preds)\n cal_fscore(standard=standard, result=preds)\n\n # evaluate NLPIR\n preds = get_nlpir_result(sentences)\n print(\"NLPIR result\")\n print_array(preds)\n cal_fscore(standard=standard, result=preds)\n\n # evaluate LTP\n preds = get_ltp_result(sentences)\n print(\"LTP result\")\n print_array(preds)\n cal_fscore(standard=standard, result=preds)\n\n\nif __name__ == \"__main__\":\n evaluate_all()\n","sub_path":"PaddleNLP/lexical_analysis/compare.py","file_name":"compare.py","file_ext":"py","file_size_in_byte":7889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"115946444","text":"import pandas as pd\n\nimport datetime\nimport time\nimport math\ndf1=pd.read_csv('e://123//testgps1.csv')\ndf1['h']=pd.to_datetime(df1['b'],format='%H:%M:%S')\nfor index, row in df1.iterrows():\n #print (index)\n if index == 0 :\n df1.ix[index,'ang']=0\n oldlat=row['f']\n oldlong=row['e']\n else:\n utf1 = row['h'].strftime('%H%M%S')\n #print((df1['f'] * 100))\n curlat1=row['f']\n curlong1=row['e']\n a1 = (curlong1 - oldlong)\n b1 = (curlat1 - oldlat)\n if a1 > 0 and b1 > 0:\n slope1 = 90.0 - math.atan(abs(b1 / a1)) * 180 / 3.14\n elif a1 > 0 and b1 < 0:\n slope1 = 90.0 + math.atan(abs(b1 / a1)) * 180 / 3.14\n elif a1 < 0 and b1 > 0:\n slope1 = 270.0 + math.atan(abs(b1 / a1)) * 180 / 3.14\n elif a1 < 0 and b1 < 0:\n slope1 = 270.0 - math.atan(abs(b1 / a1)) * 180 / 3.14\n\n #print ('angle '+ str(slope1))\n lat = (row['f'] * 100)\n long = (row['e'] * 100)\n df1.ix[index, 'ang'] =10\n #print(utf1)\n str1 = '$GNRMC,' + utf1 + '.00,A,' + str(lat) + ',N,' + str(long) + ',E,35,'+ str(int(slope1)) +',180917,,,A*6E'\n print(str1)\n oldlat=row['f']\n oldlong=row['e']\n #print (df1[['e','f','h']])\n\n#print ( df1)\n#print (df1['h'][10].strftime('%M'))\n#print (df1['h'][10].strftime('%S'))\n#utf2=df1['h'][10].strftime('%Y%m%d')\n\n\n\n","sub_path":"corp_sr/line/gps_check/testgps1.py","file_name":"testgps1.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"404200472","text":"from typing import cast\n\nfrom . import base\nfrom .classification import (\n DawidSkene,\n GLAD,\n GoldMajorityVote,\n KOS,\n MACE,\n MajorityVote,\n MMSR,\n OneCoinDawidSkene,\n Wawa,\n ZeroBasedSkill\n)\nfrom .multilabel import BinaryRelevance\nfrom .embeddings import (\n ClosestToAverage,\n HRRASA,\n RASA,\n)\nfrom .image_segmentation import (\n SegmentationEM,\n SegmentationRASA,\n SegmentationMajorityVote\n)\nfrom .pairwise import (\n BradleyTerry,\n NoisyBradleyTerry\n)\nfrom .texts import (\n TextRASA,\n TextHRRASA,\n ROVER\n)\n\n__all__ = [\n 'base',\n\n 'BradleyTerry',\n 'ClosestToAverage',\n 'DawidSkene',\n 'OneCoinDawidSkene',\n 'GLAD',\n 'GoldMajorityVote',\n 'HRRASA',\n 'KOS',\n 'MACE',\n 'MMSR',\n 'MajorityVote',\n 'NoisyBradleyTerry',\n 'RASA',\n 'ROVER',\n 'SegmentationEM',\n 'SegmentationMajorityVote',\n 'SegmentationRASA',\n 'TextHRRASA',\n 'TextRASA',\n 'Wawa',\n 'ZeroBasedSkill',\n 'BinaryRelevance'\n]\n\n\ndef is_arcadia() -> bool:\n try:\n import __res\n return cast(bool, __res == __res)\n except ImportError:\n return False\n","sub_path":"crowdkit/aggregation/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"351276692","text":"import copy\nimport xml.etree.ElementTree as ET\nfrom typing import List\n\nimport openpyxl\nimport csv\nfrom qualitytools import list_of_dictionaries\n\n\nclass Section (object):\n \"\"\"An XML element.\n\n This class is the reference implementation of the Element docbook.\n # https://stackoverflow.com/questions/2358045/how-can-i-implement-a-tree-in-python-are-there-any-built-in-data-structures-in\n \"\"\"\n\n def __init__(self,title=\"\",children=None):\n self._title = title\n self._text = \"\"\n\n # a section can contain a list\n self._list=[]\n self.tables = [] # list of tables (or list of List_of_dictionaries)\n\n self._children = []\n if children is not None:\n for child in children:\n self.add_child(child)\n\n def append_text(self, new_text):\n\n # add text without leading and trailing spaces\n self._text += new_text.strip()\n\n def _set__title(self, new_title):\n self._title = new_title\n\n def _set__list(self, new_list):\n self._list.append(copy.deepcopy(new_list))\n\n def append_sub_section(self, sub_section):\n # new_section = sub section objects\n assert isinstance(sub_section, Section)\n self._children.append(sub_section)\n\n def print_list (self):\n joined_string = \"\"\n if (self._list):\n joined_string = '\\n'.join(self._list)\n return joined_string\n\n def append_table(self,new_table):\n assert isinstance(new_table, list_of_dictionaries.List_of_dictionaries)\n self.tables.append(copy.deepcopy(new_table))\n\n def print_tables (self):\n\n joined_string = \"\"\n for table in self.tables:\n joined_head = '|' + '|'.join(table._head) + '|'\n joined_body = \"\"\n for row in table._body: # table._body = list of dictionaries (row = dict)\n joined_body = joined_body + '\\n' + '|' + '|'.join(row.values()) + '|'\n joined_string = joined_string + joined_head + joined_body + '\\n'\n\n return joined_string\n\n def __str__(self, level=0):\n ret = \"\\t\"*level+repr(self._title)+\"\\n\"\n for child in self._children:\n ret += child.__str__(level+1)\n return ret\n\n def __repr__(self):\n return ''\n\n def get_leaves(self):\n leafs = []\n\n def _get_leaf_nodes(node):\n if node is not None:\n if len(node._children) == 0:\n leafs.append(node)\n for n in node._children:\n _get_leaf_nodes(n)\n\n _get_leaf_nodes(self)\n return leafs\n\n\ndef get_text_from_element_and_childs (element):\n \"\"\"Returns the text found in the current element and also in the child elements\n :element: node (elementTree)\n :return: string = text concanenated in the elment and child elements\n \"\"\"\n text=\"\"\n if len(element) == 0:\n text = element.text.replace('\\n', ' ')\n else:\n for child in element:\n text = text + ' ' + get_text_from_element_and_childs(child)\n\n strip_text=text.strip(' \\t') # remove leading and trailing text\n #strip_text = ' '.join(text.split())\n\n return strip_text\n\n\ndef get_list_from_itemizedlist (element):\n \"\"\"Returns the values of the list \"itemizedlist\"\n :element: node (elementTree)\n :return:\n list = list of the test values\n \"\"\"\n # < itemizedlist > < listitem > < para > item 1 < /listitem > < /itemizedlist >\n my_list=[]\n for item in element:\n item_value = item.find('para').text.replace('\\n', ' ')\n my_list.append(item_value)\n return my_list\n\n\ndef append_table_from_informaltable (element):\n \"\"\"Returns the header columns and the values of the table\n :element: node (elementTree)\n :return:\n table_head = list of the header columns\n table_body = 2 dimentional array = table[i][j] = value matrix element of the line i andcolumn j\n \"\"\"\n for t in element.iter('informaltable'):\n table_head = []\n for row_head in t.findall('.tgroup/thead/row/entry'):\n text=get_text_from_element_and_childs (row_head)\n table_head.append(text)\n\n table_body = []\n table_line = []\n nb_head_columns=len(table_head)\n no_column=0\n no_row=0\n for row_body in t.findall('./tgroup/tbody/row/entry'):\n text = get_text_from_element_and_childs(row_body)\n table_line.append(text)\n no_column += 1\n if no_column == nb_head_columns:\n no_row +=1\n no_column = 0\n table_body.append(copy.deepcopy(table_line))\n table_line.clear()\n if no_column != 0:\n raise ValueError (\"Error reading the table, which headers are :\", table_head)\n return table_head,table_body\n\ndef append_free_table_from_informaltable (element):\n \"\"\"\n Returns the values of the table, whatever the book xml notation (i.e. head and body data)\n :param element: node (elementTree)\n :return: able_body = 2 dimentional array = table[i][j] = value matrix element of the line i andcolumn j\n \"\"\"\n for t in element.iter('informaltable'):\n table_body = []\n for row_head in t.findall('.tgroup/thead/row/entry'):\n text=get_text_from_element_and_childs (row_head)\n table_body.append(text)\n for row_body in t.findall('.tgroup/tbody/row/entry'):\n text=get_text_from_element_and_childs (row_body)\n table_body.append(text)\n if len(table_body) == 0:\n raise ValueError (\"Error reading the table, found empty \")\n return table_body\n\ndef build_section (element,header_description):\n \"\"\"\n Returns the section with childs\n section = parent section\n element = parent element (elementTree)\n :param element:\n :param header_description: dictionary : head_key:head_value to catch in the table\n :return:\n \"\"\"\n\n section = Section()\n for child_element in element:\n if (child_element.tag == 'title'): # section title\n section._title = child_element.text.replace('\\n', ' ') if child_element.text else \"\"\n elif (child_element.tag == 'para'):\n section.append_text (child_element.text)\n elif (child_element.tag == 'itemizedlist'):\n element_list = []\n element_list = get_list_from_itemizedlist(child_element)\n section._list = copy.deepcopy(element_list)\n elif (child_element.tag == 'informaltable'):\n # add a new table_head and table_body\n\n new_table=list_of_dictionaries.List_of_dictionaries()\n if 'orientation' in header_description:\n if header_description['orientation'] == \"horizontal\":\n (element_head, element_body) = append_table_from_informaltable(child_element)\n new_table.import_table(element_head,element_body)\n elif header_description['orientation'] == \"vertical\":\n (element_head, element_body) = append_table_from_informaltable(child_element)\n new_table.import_table_with_vertical_header (element_head, element_body)\n elif header_description['orientation'] == \"free\":\n element_body = append_free_table_from_informaltable(child_element)\n new_table.import_table_with_no_header(element_body,header_description)\n section.append_table(copy.deepcopy(new_table))\n pass\n\n elif (child_element.tag == 'section'):\n child_section = build_section (child_element,header_description)\n section.append_sub_section(child_section)\n return section\n\ndef parse_section (section):\n column={}\n column.clear()\n column['name'] = section._title\n leaves = section.get_leaves()\n for leaf in leaves:\n column_name = leaf._title\n column_cell = leaf._text\n\n # add the section internal list to the section text\n if (leaf._list):\n text = leaf.print_list()\n column_cell += text\n # add the section internal list to the section text\n if (leaf.tables):\n text = leaf.print_tables()\n column_cell += text\n\n column[column_name] = column_cell\n return column\n\ndef find_section (element_parent,Xpath_pattern,header_description,sub_sections=False):\n \"\"\"\n\n :param element_parent:\n :param Xpath_pattern:\n :param header_description: dictionary : head_key:head_value to catch in the table\n :param sub_sections:\n :return:\n \"\"\"\n\n section_found=None\n element=element_parent.find (Xpath_pattern)\n if element:\n if element.tag == 'section':\n if not sub_sections:\n section_found = build_section (element,header_description)\n print (section_found)\n else:\n section_found=Section()\n for sub_section in element.findall('section'):\n child_section = build_section(sub_section,header_description)\n section_found.append_sub_section(child_section)\n else:\n raise ValueError(\"section {} not found\".format(Xpath_pattern))\n return section_found\n\ndef get_first_table_from_sections (docbook, Xpath_pattern, header_description=None, table_title_key=None):\n \"\"\"\n browse all the sub-sections and grab their table\n :param element_parent:\n :param Xpath_pattern:\n :param header_description: dictionary : head_key:head_value to catch in the table\n :param table_title_key:\n :return: table gathered all the tables of the sub-sections browsed\n \"\"\"\n\n # let's assume that the table has an horizontal header\n if header_description is None:\n header_description = {}\n header_description['orientation'] = \"horizontal\"\n\n final_table = list_of_dictionaries.List_of_dictionaries(\"Section from pattern \" + Xpath_pattern)\n tables = get_tables_from_sections(docbook.node, Xpath_pattern, header_description, table_title_key, sub_sections=True)\n for table in tables:\n final_table.body = table.body\n return final_table\n\ndef get_sections_with_one_table (docbook, Xpath_pattern,header_description,table_title_key=None, sub_sections=False):\n \"\"\"\n parse all the sections and,for each section, take its (first) table\n :param docbook: xml docbook (yet parsed with elementTree)\n :param Xpath_pattern:\n :param header_description: dictionary : head_key:head_value to catch in the table\n :param table_title_key:\n :param sub_sections: id set to True, browse sub-sections\n :return:\n \"\"\"\n\n # first_table = list_of_dictionaries.List_of_dictionaries(\"Section from pattern \" + Xpath_pattern)\n first_table = get_tables_from_sections(docbook.node, Xpath_pattern, header_description, table_title_key, sub_sections)\n return first_table\n\ndef merge_tables (section_tables, table_title_key, section_title=None):\n \"\"\"\n In a given section (or sub-section), merge all its tables\n :param section_tables: list of the tables\n :param table_title_key: add a key-value in each table recorded\n :param section_title: value of the key above (eg name of the section containing the tables)\n :return: List_of_dictionaries : merged tables\n \"\"\"\n\n\n merged_table = list_of_dictionaries.List_of_dictionaries()\n for table in section_tables:\n listofdict = list_of_dictionaries.List_of_dictionaries()\n listofdict.body = table._body\n if table_title_key is not None:\n if table_title_key == 'section_name':\n # listofdict = list with a unique line of dictionary (index 0).\n # Add a nex key:value in this line 'section_name':section_title\n listofdict._body[0]['section_name'] = section_title\n else:\n # title of the table = value of a specific key in the table\n table_title = table._body[0][table_title_key]\n listofdict.title = table_title\n # TODO: add/merge several tables (not only one !!)\n merged_table.body = listofdict._body\n merged_table.title = listofdict.title\n return merged_table\n\ndef get_tables_from_sections (element_parent, Xpath_pattern, header_description, table_title_key=None, sub_sections=False):\n \"\"\"\n find the top-level section from a Xpath pattern\n gather the tables below this section and its sub-sections\n Avoid the top-level section if if sub_sections is set\n Record the tables depending its \"orientation\" (heads horizontal or not)\n :param element_parent: top-level section\n :param Xpath_pattern: paatern to select the section above\n :param header_description: dictionary : head_key:head_value to catch in the table\n :param table_title_key: add a key-value in each table recorded\n :param sub_sections: Avoid the top-level section if if sub_sections is set\n :return: list of dictionary : all the tables merged of all the sub-sections browsed\n \"\"\"\n\n full_table = list_of_dictionaries.List_of_dictionaries()\n try:\n section = find_section(element_parent,Xpath_pattern,header_description,sub_sections)\n except ValueError as error:\n print(\"\\nWarning:\",error)\n return full_table\n if not sub_sections:\n # merge tables only in the current section\n full_table = merge_tables(section.tables, table_title_key)\n else:\n # merge tables in each sub-section browsed (section._children X)\n # i.e children[X].table[0]._body (=list of dict), children[X].table[1]._body...)\n for children in section._children:\n # get in a list of dictionary all the sub tables\n merged_tables = merge_tables(children.tables, table_title_key, children._title)\n full_table.body = merged_tables._body\n full_table.title = merged_tables.title\n\n return full_table\n\n\ndef get_chapter (docbook, Xpath_pattern,table_description):\n \"\"\"\n parse all the sections\n :param docbook: xml docbook (yet parsed with elementTree)\n :param Xpath_pattern: Xpath request\n :return: list_of_dictionaries: text contents of the chapter indexed by section name\n table[no_line]['my_section'] = text founded in the section\n \"\"\"\n\n table = list_of_dictionaries.List_of_dictionaries (\"Chapter from pattern \"+Xpath_pattern)\n try:\n chapter = find_section(docbook.node, Xpath_pattern, table_description)\n except ValueError as error:\n print(\"\\nWarning: \",error)\n return table\n\n for section_of_chapter in chapter._children:\n column_dict = parse_section(section_of_chapter)\n table.body = [ column_dict ]\n column_dict.clear()\n\n return table\n\ndef get_section_with_one_table_by_subsection (docbook, Xpath_pattern,table_description):\n \"\"\"\n configuration:\n - a chapter is composed of sub-sections.\n - each subsection is browsed and each of its vertical table is recorded in a single full table\n goal is to record a final list of dictionary, where head columns come from the heads of the tables of the subsections\n\n :param docbook: xml docbook (yet parsed with elementTree)\n :param Xpath_pattern: Xpath pattern to find the chapter\n :param table_description: dictionary : head_key:head_value to catch in the table\n :return: the final list of dictionary above\n \"\"\"\n # table_title_key='section_name' : it is assumed that each table of each subsection will contain the name of the subsection\n # horizontal_header=False : it is assumed here that the tables are \"vertical\" (heads = first column on the left)\n # sub_sections = True : brows only sub-sections of the chapter (i.e. do not take in account the chapter top section)\n table = get_tables_from_sections(docbook.node, Xpath_pattern, table_description, table_title_key='section_name', sub_sections=True)\n return table\n\ndef get_tables_from_section (docbook, Xpath_pattern,table_description):\n \"\"\"\n configuration:\n - a chapter is composed of sub-sections.\n - each subsection is browsed and each of its vertical table is recorded in a single full table\n goal is to record a final list of dictionary, where head columns come from the heads of the tables of the subsections\n\n :param docbook: xml docbook (yet parsed with elementTree)\n :param Xpath_pattern: Xpath pattern to find the chapter\n :param table_description: dictionary : head_key:head_value to catch in the table\n :return: the final list of dictionary above\n \"\"\"\n # table_title_key='section_name' : it is assumed that each table of each subsection will contain the name of the subsection\n # horizontal_header=False : it is assumed here that the tables are \"vertical\" (heads = first column on the left)\n # sub_sections = True : brows only sub-sections of the chapter (i.e. do not take in account the chapter top section)\n table = get_tables_from_sections(docbook.node, Xpath_pattern, table_description, table_title_key='section_name', sub_sections=False)\n return table\n\ndef get_section_with_one_free_table_by_subsection (docbook, Xpath_pattern, table_description):\n \"\"\"\n configuration:\n - a chapter is composed of sub-sections.\n - each subsection is browsed and each of its table without header is recorded in a single full table\n goal is to record a final list of dictionary, where head columns come from the heads of the tables of the subsections\n\n :param docbook: xml docbook (yet parsed with elementTree)\n :param Xpath_pattern: Xpath pattern to find the chapter\n :param table_description: dictionary : head_key:head_value to catch in the table\n :return: the final list of dictionary above\n \"\"\"\n\n # table_title_key='section_name' : it is assumed that each table of each subsection will contain the name of the subsection\n # horizontal_header=False : it is assumed here that the tables are \"vertical\" (heads = first column on the left)\n # sub_sections = True : brows only sub-sections of the chapter (i.e. do not take in account the chapter top section)\n table = get_tables_from_sections(docbook.node, Xpath_pattern, table_description, table_title_key='section_name', sub_sections=True)\n return table\n\ndef copy_csv_file_into_new_xl_workbook (csv_input_filename):\n \"\"\"\n read text CSV file and copy its contents into a new created workbook file\n Parameters\n ----------\n csv_input_filename: string: input text file (csv, delimiter is \";\")\n\n Returns\n -------\n (wb,ws) : openpyxl workbook and worksheet created objects\n \"\"\"\n wb = openpyxl.Workbook()\n ws = wb.active\n f = open(csv_input_filename)\n reader = csv.reader(f, delimiter=';')\n for row in reader:\n ws.append(row)\n f.close()\n return (wb,ws)\n\ndef insert_columns_and_save_xl_file (xl_filename, column_heads, workbook, sheet):\n \"\"\"\n insert empty columns in the worksheet (from column 2). First line of each column is set with the column_heads strings\n\n Parameters\n ----------\n xl_filename: string: workbook file name\n column_heads: list of strings\n workbook: openpyxl file object\n sheet: openpyxl sheet object\n \"\"\"\n for head in column_heads:\n # this statement inserts a column before column 2\n # TODO: avoid hard coded value\n sheet.insert_cols(2)\n sheet['B1'] = head\n try:\n workbook.save(xl_filename)\n except PermissionError as error:\n raise\n\n\n\ndef read_csv_file_and_create_xl_workbook(csv_filename,xl_filename,new_columns):\n \"\"\"\n create an Excel workbook from a CSV file and creating new (empty) columns with headers\n \"\"\"\n\n (wb, ws) = copy_csv_file_into_new_xl_workbook(csv_filename)\n insert_columns_and_save_xl_file(xl_filename, new_columns, wb, ws)\n\n","sub_path":"qualitytools/book_parsed.py","file_name":"book_parsed.py","file_ext":"py","file_size_in_byte":19811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"573312381","text":"def file_check(address):\n import os\n if address == \"\" or address == \" \":\n return True\n return os.path.exists(address)\n\n\ndef copy_in_str(string1, string2):\n ret_str = \"\"\n i = 0\n while i != len(string1):\n if string1[i] != string2[i]:\n ret_str += \"-\"\n if string1[i] == string2[i]:\n ret_str += string1[i]\n i += 1\n return ret_str\n\n\ndef check_exit(inp_str):\n inp_str = inp_str.lower()\n if inp_str == \"exit\":\n exit()\n\n\ndef find_protospacers(spacer, fag_seq):\n if spacer not in fag_seq:\n return False\n else:\n return fag_seq.find(spacer)\n\n\ndef read_file_with_spacers(spacers_filename):\n with open(spacers_filename, \"r\") as f:\n spacers = f.read()\n spacers = spacers.replace(\" \", \"\")\n spacers = spacers.split(\"\\n\")\n return spacers\n\n\ndef read_file_with_fag(fag_filename):\n with open(fag_filename, \"r\") as f:\n warn = f.readline()\n text = f.read()\n text = text.replace(\"\\n\", \"\")\n text = text.replace(\" \", \"\")\n return text\n\n\ndef print_pam_predictor():\n print(\"\"\"\n███████████████████████████████████████████████████████████████████████\n█____██____██_███__██████____██____██___██____███____██___██____██____█\n█_██_██_██_██__█___██████_██_██_██_██_████_██__██_██_███_███_██_██_██_█\n█____██____██_█_█__█___██____██____██___██_██__██____███_███_██_██____█\n█_█████_██_██_███__██████_█████_█_███_████_██__██_██_███_███_██_██_█_██\n█_█████_██_██_███__██████_█████_█_███___██____███_██_███_███____██_█_██\n███████████████████████████████████████████████████████████████████████\n\"\"\")\n\n\ndef main():\n right = []\n left = []\n fag_filename = []\n print_pam_predictor()\n\n spacer_filename = input(\"Enter file name with spacers : \")\n # УБРАТЬ В СЛУЧАЕ ОШИБКИ СВЯЗЯННОЙ С КОДИРОВКОЙ\n check_exit(spacer_filename)\n if file_check(spacer_filename) is False:\n print(\"\"\"\\n!!!This file is not in the directory.!!!\\n\n Please place the file being processed in a directory.\\n\"\"\")\n exit()\n\n while True:\n input_filename = input(\"Enter filename seq backteriophage or exit: \")\n check_exit(input_filename)\n if file_check(input_filename) is False:\n print(\"\"\"\\n!!!This file is not in the directory.!!!\\n\n Please place the file being processed in a directory.\\n\"\"\")\n exit()\n if input_filename == \"\":\n break\n fag_filename.append(input_filename)\n\n spacers = read_file_with_spacers(spacer_filename)\n print(\"SPACERS: \", spacers)\n for j in fag_filename:\n for i in spacers:\n text = read_file_with_fag(j)\n if find_protospacers(i, text) is not False:\n pos = find_protospacers(i, text)\n right.append(text[pos + len(i):pos + len(i) + 10])\n left.append(text[pos - 10:pos])\n try:\n save_l = left[0]\n save_r = right[0]\n for i in range(len(right)):\n save_r = copy_in_str(right[i], save_r)\n for i in range(len(left)):\n save_l = copy_in_str(left[i], save_l)\n except:\n print(\"Few spacers or bacteriophages...\")\n exit()\n print(\"LEFT : \", left)\n print(\"RIGHT : \", right)\n print(\"Possible PAM in right : \", save_r)\n print(\"Possible PAM in left : \", save_l)\n input(\"Enter...\")\nmain()\n","sub_path":"example/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"431185508","text":"import scrapy\nfrom scrapy.spiders import Rule\nfrom scrapy.http import Request\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapy.crawler import CrawlerProcess\nimport logging\n\n# DEFAULT OPTIONS\nDELAY = 0.125\nALLOWED_DOMAINS = ['hard.rozetka.com.ua']\nSTART_URLS = ['https://hard.rozetka.com.ua/computers/c80095/filter/producer=msi/']\nCURRENT_BRAND = 'msi'\nTABLE_NAME = 'product'\nALLOW_PAGE_RULE = (r'\\/msi-.+',)\nALLOW_ITEM_RULE = (r'\\/msi_.+',)\nDENY_PAGE_RULE = (r'comments',)\nDENY_ITEM_RULE = (r'comments',)\nDATABASE_PIPELINE = 'spider.spider.pipelines.MySqlPipeline'\n\n\nclass Product(scrapy.Item):\n title = scrapy.Field()\n code = scrapy.Field()\n price = scrapy.Field()\n images = scrapy.Field()\n attrs = scrapy.Field()\n\n\nclass RozetkaSpider(scrapy.Spider):\n name = 'rozetka'\n custom_settings = {'ITEM_PIPELINES': {DATABASE_PIPELINE: 400}}\n\n def __init__(self, options, **kwargs):\n super().__init__(name=self.name, **kwargs)\n self.allowed_domains = options.get('ALLOWED_DOMAINS') if options.get('ALLOWED_DOMAINS') else ALLOWED_DOMAINS\n self.start_urls = options.get('START_URLS') if options.get('START_URLS') else START_URLS\n self.table_name = options.get('TABLE_NAME') if options.get('TABLE_NAME') else TABLE_NAME\n\n allow_page_rule = options.get('ALLOW_PAGE_RULE') if options.get('ALLOW_PAGE_RULE') else ALLOW_PAGE_RULE\n allow_item_rule = options.get('ALLOW_ITEM_RULE') if options.get('ALLOW_ITEM_RULE') else ALLOW_ITEM_RULE\n deny_page_rule = options.get('DENY_PAGE_RULE') if options.get('DENY_PAGE_RULE') else DENY_PAGE_RULE\n deny_item_rule = options.get('DENY_ITEM_RULE') if options.get('DENY_ITEM_RULE') else DENY_ITEM_RULE\n\n self.rules = (\n Rule(LinkExtractor()),\n Rule(LinkExtractor(allow=allow_page_rule, deny=deny_page_rule), callback='parse_page'),\n Rule(LinkExtractor(allow=allow_item_rule, deny=deny_item_rule), callback='parse_item'),)\n\n def is_br(self, selector):\n if selector.css('br'):\n return True\n return False\n\n def join_br(self, selector, css_value):\n total = []\n for row in selector.css(css_value):\n total.append(self.format(row.extract()))\n return total\n\n def format(self, string):\n if string:\n return string.strip()\n\n def get_images(self, response):\n product_images = []\n for image in response.css('a img::attr(src)').extract():\n if 'goods' in image and 'images' in image:\n product_images.append(image)\n\n return product_images\n\n def parse(self, response):\n pages = response.css('#navigation_block').css('a::attr(href)').extract()\n # Parse first page(start page)\n yield Request(response.url, callback=self.parse_page)\n\n # parse other pages\n for page in pages:\n yield Request(page, callback=self.parse_page)\n\n def parse_page(self, response):\n urls = response.css('#catalog_goods_block').css('a::attr(href)').extract()\n\n for url in urls:\n # work around for deny\n if 'comments' not in url:\n yield Request(url, callback=self.parse_item, dont_filter=False)\n\n def parse_item(self, response):\n title = response.css('h1::text').extract_first()\n title = self.format(title)\n logging.warning(title)\n\n code = response.css('span.detail-code-i::text').extract_first()\n code = self.format(code)\n logging.warning(code)\n\n price = response.css('#price_container > div > div > meta::attr(content)').extract_first()\n price = self.format(price)\n logging.warning(price)\n\n names = response.css('dl').css('div').css('dt')\n values = response.css('dl').css('div').css('dd')\n\n attrs = {}\n for name, attr in zip(names, values):\n if self.is_br(attr):\n attr = self.join_br(attr, 'dd::text')\n else:\n attr = attr.css('dd::text').extract_first()\n attr = self.format(attr)\n\n name = name.css('dt::text').extract_first()\n name = self.format(name)\n logging.warning(name + ': ' + str(attr))\n attrs.update({name: attr})\n\n images = self.get_images(response)\n product = Product(title=title, code=code, price=price, images=images, attrs=attrs)\n yield product\n\n\nif __name__ == \"__main__\":\n process = CrawlerProcess()\n process.crawl(RozetkaSpider)\n process.start() # the script will block here until the crawling is finished\n pass\n","sub_path":"spider/spider/spiders/rozetka.py","file_name":"rozetka.py","file_ext":"py","file_size_in_byte":4609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"468873899","text":"# -*- coding: utf-8 -*-\nimport re\nimport Levenshtein\nimport csv\n\n# 가정: database D는 aux A에 순서에 의해 정렬되어 있으며, 정돈되어 있음.\n# 가정: 10대, 20대... 로 표시된 경우 '대'를 제거\n# 가정: 문자열에는 '~'가 없어야 한다. (있어도 되지만 결과의 정확도가 조금 떨어질 수 있음.)\n# 가정: 각 Database 공통적인 정보만을 남기고 열을 삭제한다. 이 떄, 원본 DB는 남겨놔야 이후 매칭이 가능. (이는 개선가능성이 있다.)\n\nclass Reidentify(object):\n def __init__(self):\n database = []\n aux_array = []\n # open input files. f1=releasedD. f2=auxD\n f1 = open('./넷플릭스(Real).csv', 'r')\n f2 = open('./IMDB(Real).csv', 'r')\n self.readinput(f1, database)\n self.readinput(f2, aux_array)\n f1.close()\n f2.close()\n # score array = array for N by M\n score = [[1 for col in range(len(aux_array))] for row in range(len(database))]\n self.score(database, aux_array, score)\n alpha = 0.1\n # matching set is the dictation array which will contain (candidate, possibility)\n matching = [dict() for row in range(len(database))]\n self.matching_set(score, alpha, matching)\n self.print_candidate_name(database, aux_array, matching)\n\n # print the candidate\n def print_candidate_name(self, database, aux_array, matching):\n f = open('./result.txt', 'w')\n for row in range(len(database)):\n f.write(str(database[row])+'\\n')\n for key in matching[row].keys():\n f.write('=> ' + str(aux_array[key]) + ': ' + str(matching[row][key]) + '\\n')\n f.write('\\n')\n f.close()\n\n def readinput(self, file_handler, output_matrix):\n csv_reader = csv.reader(file_handler)\n iter_csv = iter(csv_reader)\n next(iter_csv)\n for row in csv_reader:\n output_matrix.append(row)\n\n def sim(self, aux, record):\n # 속성값이 10,000~20,000 처럼 범위형으로 들어오고 , \\과 같은 특수문자가 들어온다면 제거해준다.\n aux_pure = re.sub('[\\$, ]', '', aux)\n record_pure = re.sub('[\\$, ]', '', record)\n # 10000~20000 등과 같을 때 1차원 배열 ( 10000 20000 ) 으로 문자를 치환 [~ => 띄어쓰기]\n aux_pure = re.sub('~', ' ', aux_pure)\n record_pure = re.sub('~', ' ', record_pure)\n # split by space\n aux_pure = aux_pure.split()\n record_pure = record_pure.split()\n # 애초에 space가 없었다면 배열은 원소를 하나만을 가진다. 이를 체크해서 원소가 두개이도록 모두 바꾼다.\n # (1) 입력이 (10~20)으로 들어왔다면 split 단계 이후에는 (10,20)과 같은 원소 2개의 배열 형태\n # (2) 입력이 애초에 (10~20)으로 들어온게 아니라 (10)과 같이 숫자 하나로 들어왔다면, split 단계까지 진행되었을 때 원소를 (10)만 가지게 된다.\n # 입력 인자에 통일성을 주기 위해 (2)번과 같은 경우에는 (10) => (10,10)으로 변경해준다.\n if len(aux_pure) == 1:\n aux_pure.append(aux_pure[0])\n if len(record_pure) == 1:\n record_pure.append(record_pure[0])\n\n # 배열의 원소가 숫자라면 이를 숫자로 인식하도록 int 함수를 적용.\n # 만일 두 비교대상 중 하나라도 숫자가 아니라면 문자열 vs 문자열로 비교해야하므로 is_string이라는 flag로 문자열인지 체크를 해준다.\n # 하나라도 문자열이라면 밑에 case string 을 수행하고 return\n # 모두 숫자라면 case number 를 수행\n is_string = 0\n try:\n for i in range(len(aux_pure)):\n aux_pure[i] = int(aux_pure[i])\n except ValueError:\n is_string = 1\n try:\n for i in range(len(record_pure)):\n record_pure[i] = int(record_pure[i])\n except ValueError:\n is_string = 1\n\n # case string\n # 어느 하나라도 string 이라면 Levenshtein algorithm 을 수행한다.\n # 유사도 = 1 - (다른 문자 갯수 / 긴 문자열의 길이)\n if is_string == 1:\n error = Levenshtein.distance(str(record_pure[0]), str(aux_pure[0]))\n length = len(str(record_pure[0])) if len(str(record_pure[0])) > len(str(aux_pure[0])) else len(str(aux_pure[0]))\n return 1 - (error / length)\n\n # case number\n # releaseD 의 범위 내에 aux 의 값이 포함되어있는지, 포함되어있다면 다음과 같이 유사도를 낸다.\n # 유사도 = (포함되는 수 개수 / 더 넓은 숫자범위)\n match = 0\n for i in range(record_pure[0], record_pure[1] + 1):\n if i in range(aux_pure[0], aux_pure[1] + 1):\n match += 1\n length = (record_pure[1] - record_pure[0] + 1) if (record_pure[1] - record_pure[0]) > (record_pure[1] - record_pure[0]) else (record_pure[1] - record_pure[0] + 1)\n return match / length\n\n def score(self, database, aux_array, output):\n f = open('./output.txt', 'w')\n f2 = open('./output2.txt', 'w')\n for record in range(len(database)):\n for aux in range(len(aux_array)):\n minimum = 1\n for attribute in range(len(aux_array[aux])):\n res = self.sim(aux_array[aux][attribute], database[record][attribute])\n if minimum > res:\n output[record][aux] = round(res, 4)\n minimum = round(res, 4)\n # f.writelines(str(database[record]))\n # f.writelines(str(aux_array[aux]))\n # f.writelines(str(output[record]))\n f2.write(str(record + 1) + ': ' + str(database[record]) + '\\n')\n f2.write(str(output[record]) + '\\n')\n f.close()\n f2.close()\n\n def matching_set(self, input_array, alpha, output_array):\n for row in range(len(input_array)):\n for col in range(len(input_array[row])):\n if input_array[row][col] >= alpha:\n output_array[row][col] = input_array[row][col]\n # print(row, output_array[row])\n\n def setting_alpha(self):\n pass\n\n\nif __name__ == '__main__':\n re = Reidentify()","sub_path":"src/alg_min.py","file_name":"alg_min.py","file_ext":"py","file_size_in_byte":6393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"426693847","text":"#from skimage.morphology import skeletonize\nfrom skimage import draw\nimport numpy as np\nimport Segments\nimport Quantization\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport scipy.ndimage as ndi\nimport EuclidMST\n\ndef smooth_with_function_and_mask(image, function, mask):\n bleed_over = function(mask.astype(float))\n masked_image = np.zeros(image.shape, image.dtype)\n masked_image[mask] = image[mask]\n smoothed_image = function(masked_image)\n output_image = smoothed_image / (bleed_over + np.finfo(float).eps)\n return output_image\n\ndef skeletonize(image):\n \"\"\"Return the skeleton of a binary image.\n\n Thinning is used to reduce each connected component in a binary image\n to a single-pixel wide skeleton.\n\n Parameters\n ----------\n image : numpy.ndarray\n A binary image containing the objects to be skeletonized. '1'\n represents foreground, and '0' represents background. It\n also accepts arrays of boolean values where True is foreground.\n\n Returns\n -------\n skeleton : ndarray\n A matrix containing the thinned image.\n\n See also\n --------\n medial_axis\n\n Notes\n -----\n The algorithm [1] works by making successive passes of the image,\n removing pixels on object borders. This continues until no\n more pixels can be removed. The image is correlated with a\n mask that assigns each pixel a number in the range [0...255]\n corresponding to each possible pattern of its 8 neighbouring\n pixels. A look up table is then used to assign the pixels a\n value of 0, 1, 2 or 3, which are selectively removed during\n the iterations.\n\n Note that this algorithm will give different results than a\n medial axis transform, which is also often referred to as\n \"skeletonization\".\n\n References\n ----------\n .. [1] A fast parallel algorithm for thinning digital patterns,\n T. Y. ZHANG and C. Y. SUEN, Communications of the ACM,\n March 1984, Volume 27, Number 3\n\n\n Examples\n --------\n >>> X, Y = np.ogrid[0:9, 0:9]\n >>> ellipse = (1./3 * (X - 4)**2 + (Y - 4)**2 < 3**2).astype(np.uint8)\n >>> ellipse\n array([[0, 0, 0, 1, 1, 1, 0, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 1, 1, 1, 1, 1, 0, 0],\n [0, 0, 0, 1, 1, 1, 0, 0, 0]], dtype=uint8)\n >>> skel = skeletonize(ellipse)\n >>> skel\n array([[0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8)\n\n \"\"\"\n # look up table - there is one entry for each of the 2^8=256 possible\n # combinations of 8 binary neighbours. 1's, 2's and 3's are candidates\n # for removal at each iteration of the algorithm.\n lut = [0, 0, 0, 1, 0, 0, 1, 3, 0, 0, 3, 1, 1, 0, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 3, 0, 3, 3,\n 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 3, 0, 2, 2,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 2, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 3, 0, 2, 0,\n 0, 1, 3, 1, 0, 0, 1, 3, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,\n 3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 2, 3, 1, 3, 0, 0, 1, 3, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 2, 3, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 0, 1, 0, 0, 0, 0, 2, 2, 0, 0, 2, 0, 0, 0]\n\n # convert to unsigned int (this should work for boolean values)\n skeleton = np.array(image).astype(np.uint8)\n\n # check some properties of the input image:\n # - 2D\n # - binary image with only 0's and 1's\n if skeleton.ndim != 2:\n raise ValueError('Skeletonize requires a 2D array')\n if not np.all(np.in1d(skeleton.flat, (0, 1))):\n raise ValueError('Image contains values other than 0 and 1')\n\n # create the mask that will assign a unique value based on the\n # arrangement of neighbouring pixels\n mask = np.array([[1, 2, 4],\n [128, 0, 8],\n [64, 32, 16]], np.uint8)\n\n pixelRemoved = True\n while pixelRemoved:\n pixelRemoved = False;\n\n # assign each pixel a unique value based on its foreground neighbours\n neighbours = ndi.correlate(skeleton, mask, mode='nearest')\n\n # ignore background\n neighbours *= skeleton\n\n # use LUT to categorize each foreground pixel as a 0, 1, 2 or 3\n codes = np.take(lut, neighbours)\n\n # pass 1 - remove the 1's and 3's\n code_mask = (codes == 1)\n if np.any(code_mask):\n pixelRemoved = True\n skeleton[code_mask] = 0\n code_mask = (codes == 3)\n if np.any(code_mask):\n pixelRemoved = True\n skeleton[code_mask] = 0\n\n # pass 2 - remove the 2's and 3's\n neighbours = ndi.correlate(skeleton, mask, mode='nearest')\n neighbours *= skeleton\n codes = np.take(lut, neighbours)\n code_mask = (codes == 2)\n if np.any(code_mask):\n pixelRemoved = True\n skeleton[code_mask] = 0\n code_mask = (codes == 3)\n if np.any(code_mask):\n pixelRemoved = True\n skeleton[code_mask] = 0\n\n return skeleton\n\n\nclass Skeleton:\n\n def count_neighbors(self):\n k = np.array([[1,1,1],\n [1,0,1],\n [1,1,1]])\n\n m = ndi.filters.convolve(self.skeleton,k,mode='constant',cval=0)\n nc = np.multiply(m,self.skeleton)\n self.neighbor_count = nc\n\n def euclidMstOrder(self):\n emst2 = EuclidMST.EuclidMST(self.segments.segmentList) # TODO fix\n emst2.segmentOrdering()\n self.segments.segmentList = emst2.newSegmentTree # TODO fix\n\n\n\n def __init__(self, image_matrix, sigma=0.5):\n\n if sigma >= 0.:\n mask = np.ones(image_matrix.shape, dtype=bool)\n fsmooth = lambda x: ndi.gaussian_filter(x, sigma, mode='constant')\n self.imin = smooth_with_function_and_mask(image_matrix, fsmooth, mask)\n else:\n self.imin = image_matrix\n\n self.centroids = Quantization.measCentroid(self.imin, 2)\n\n nq = np.array([[x * 255] for x in range(0, 2)])\n self.imin = Quantization.quantMatrix(self.imin, nq, self.centroids)\n plt.imshow(self.imin, cmap=cm.gray)\n plt.savefig(\"figStartOrig.png\")\n plt.clf()\n\n self.ibin = np.zeros(self.imin.shape, dtype=np.uint8)\n x0,y0 = np.where(self.imin == 0)\n self.ibin[x0,y0] = 1\n\n skel = skeletonize(self.ibin)\n self.skeleton = skel.astype(np.uint8)\n plt.imshow(self.skeleton, cmap=cm.gray)\n plt.savefig(\"figStartSkel.png\")\n plt.clf()\n\n self.segments = Segments.Segments()\n\n\n for neighbor_limit in range(1,5):\n while True:\n self.count_neighbors()\n for internal_limit in range(1,neighbor_limit+1):\n startx, starty = np.where(self.neighbor_count == internal_limit)\n if len(startx) > 0:\n break\n if len(startx) == 0:\n break\n for (x,y) in zip(startx, starty):\n if self.skeleton[x,y] == 1:\n self.follow_line(x,y)\n print(np.sum(self.skeleton))\n print(np.sum(self.neighbor_count))\n print(np.max(self.neighbor_count))\n assert (np.sum(self.neighbor_count) == 0)\n\n def follow_line(self,x,y):\n X,Y = self.skeleton.shape\n segment = [[x, y]]\n self.skeleton[x, y] = 0\n while True:\n # search for neighbor\n # decrement neighbor counts\n adjacent_counter = self.neighbor_count[x, y]\n done = adjacent_counter > 1 or adjacent_counter == 0\n self.neighbor_count[x, y] = 0\n\n for (i, j) in [(-1, 0), (0, -1), (1, 0), (0, 1), (1, 1), (1, -1), (-1, 1), (-1, -1)]:\n x_n = x + i\n y_n = y + j\n\n if (x_n < 0) or (y_n < 0) or (x_n >= X) or (y_n >= Y):\n continue\n if self.skeleton[x_n, y_n] == 1:\n self.neighbor_count[x_n, y_n] -= 1\n x_save, y_save = x_n, y_n\n\n if not done:\n segment.append([x_save, y_save])\n x, y = x_save, y_save\n self.skeleton[x, y] = 0\n else:\n break\n if len(segment) > 1:\n self.segments.append(segment)\n\n\n\n\n\n","sub_path":"Skeleton.py","file_name":"Skeleton.py","file_ext":"py","file_size_in_byte":9115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"394962232","text":"#-*- coding:utf-8 -*-\n\"\"\"\n@Author: Jeff Zhang\n@Time: 17-8-31 上午9:29\n@File: NaiveBayes.py\n\"\"\"\n\n\nimport numpy as np\n\n\nclass NaiveBayes(object):\n def __init__(self):\n pass\n\n def setOfWordsToVecTor(self, vocabularyList, smsWords):\n \"\"\"\n SMS内容匹配预料库,标记预料库的词汇出现的次数\n :param vocabularyList:\n :param smsWords:\n :return:\n \"\"\"\n vocabMarked = [0] * len(vocabularyList)\n for smsWord in smsWords:\n if smsWord in vocabularyList:\n vocabMarked[vocabularyList.index(smsWord)] += 1\n return vocabMarked\n\n def setOfWordsListToVecTor(self, vocabularyList, smsWordsList):\n \"\"\"\n 将文本数据的二维数组标记\n :param vocabularyList:\n :param smsWordsList:\n :return:\n \"\"\"\n vocabMarkedList = []\n for i in range(len(smsWordsList)):\n vocabMarked = self.setOfWordsToVecTor(vocabularyList, smsWordsList[i])\n vocabMarkedList.append(vocabMarked)\n return vocabMarkedList\n\n def fit(self, trainMarkedWords, trainCategory):\n numTrainDoc = len(trainMarkedWords)\n numWords = len(trainMarkedWords[0])\n pSpam = sum(trainCategory) / float(numTrainDoc)\n wordsInSpamNum = np.ones(numWords)\n wordsInHealthNum = np.ones(numWords)\n SpamWordsNum = 2.0\n HealthWordsNum = 2.0\n for i in range(0, numTrainDoc):\n if trainCategory[i] == 1:\n wordsInSpamNum += trainMarkedWords[i]\n SpamWordsNum += sum(trainMarkedWords[i]) # 统计Spam中语料库中词汇出现的总次数\n if trainCategory[i] == 0:\n wordsInHealthNum += trainMarkedWords[i]\n HealthWordsNum += sum(trainMarkedWords[i])\n\n pWordsSpamicity = np.log(wordsInSpamNum / SpamWordsNum)\n pWordsHealthy = np.log(wordsInHealthNum / HealthWordsNum)\n\n self.pWordsHealthy_, self.pWordsSpamicity_, self.pSpam_ = pWordsHealthy, pWordsSpamicity, pSpam\n return self\n\n\n\n def predict(self, vocabularyList, testWords):\n testWordsCount = self.setOfWordsToVecTor(vocabularyList, testWords)\n testWordsMarkedArray = np.array(testWordsCount)\n # 计算P(Ci|W),W为向量。P(Ci|W)只需计算P(W|Ci)P(Ci)\n p1 = sum(testWordsMarkedArray * self.pWordsSpamicity_) + np.log(self.pSpam_)\n p0 = sum(testWordsMarkedArray * self.pWordsHealthy_) + np.log(1 - self.pSpam_)\n if p1 > p0:\n return 1\n else:\n return 0","sub_path":"SupervisedLearning/NaiveBayes.py","file_name":"NaiveBayes.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"435737426","text":"# Copyright 2019 GreenWaves Technologies, SAS\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# http://www.apache.org/licenses/LICENSE-2.0\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport sys\nfrom typing import Sequence\n\nimport numpy as np\n\nfrom graph.types import (ActivationParameters, Conv2DParameters, FcParameters,\n InputParameters, OutputParameters, PadParameters,\n PoolingParameters, SoftMaxParameters, ReshapeParameters,\n MatrixAddParameters, ConcatParameters, TransposeParameters)\nfrom quantization.quantization_record import (FilterQuantizationRecord,\n QuantizationRecord)\n\nfrom .kernels.conv2d import conv2d\nfrom .kernels.linear import linear\nfrom .kernels.misc import activation, concat, softmax, reshape, add, transpose\nfrom .kernels.pool import av_pool, max_pool\nfrom .kernels.utils import pad\n\n\nclass Executer():\n\n @classmethod\n def execute(cls, node, in_tensors, qrec=False):\n execute_switch = {\n Conv2DParameters: cls.execute_conv2d,\n FcParameters: cls.execute_linear,\n PoolingParameters: cls.execute_pooling,\n InputParameters: cls.execute_input,\n OutputParameters: cls.execute_output,\n ActivationParameters: cls.execute_activation,\n PadParameters: cls.execute_pad,\n SoftMaxParameters: cls.execute_softmax,\n ReshapeParameters: cls.execute_reshape,\n MatrixAddParameters: cls.execute_add,\n ConcatParameters: cls.execute_concat,\n TransposeParameters: cls.execute_transpose\n }\n func = execute_switch.get(node.__class__)\n if func:\n return func(node, in_tensors, qrec)\n raise NotImplementedError(\"kernel for node %s is not implemented\" % node.__class__)\n\n @staticmethod\n def execute_transpose(node: TransposeParameters,\n in_tensors: Sequence[np.array],\n qrec: QuantizationRecord = None):\n\n return [transpose(node, node.in_dims, node.out_dims, in_tensors[0], qrec)], None\n\n @staticmethod\n def execute_reshape(node: ReshapeParameters,\n in_tensors: Sequence[np.array],\n qrec: QuantizationRecord = None):\n\n return [reshape(node, node.in_dims, node.out_dims, in_tensors[0], qrec)], None\n\n @staticmethod\n def execute_softmax(node: SoftMaxParameters,\n in_tensors: Sequence[np.array],\n qrec: QuantizationRecord = None):\n\n return [softmax(node, node.in_dims, node.out_dims, in_tensors[0], qrec)], None\n\n @staticmethod\n def execute_pad(node: PadParameters,\n in_tensors: Sequence[np.array],\n qrec: QuantizationRecord = None):\n del qrec\n\n return [pad(in_tensors[0], node.in_dims[0], node.padding, \"zero\")], None\n\n @staticmethod\n def execute_concat(node: ConcatParameters,\n in_tensors: Sequence[np.array],\n qrec: QuantizationRecord = None):\n # TODO - check quantization\n # This assumes that the input tensors have been transposed to the correct\n # order for the concat\n del qrec\n return [concat(node, node.in_dims, node.out_dims[0], in_tensors)], None\n\n @staticmethod\n def execute_add(node: MatrixAddParameters,\n in_tensors: Sequence[np.array],\n qrec: QuantizationRecord = None):\n return [add(node, node.in_dims, node.out_dims, in_tensors, qrec)], None\n\n @staticmethod\n def execute_activation(node: ActivationParameters,\n in_tensors: Sequence[np.array],\n qrec: QuantizationRecord = None):\n\n return [activation(node, node.in_dims[0], node.out_dims[0], in_tensors[0], qrec)], None\n\n @staticmethod\n def execute_input(node: InputParameters,\n in_tensors: Sequence[np.array],\n qrec: QuantizationRecord = None):\n value = in_tensors[node.index]\n if qrec:\n value = qrec.out_qs[0].quantize(value)\n\n # ensure that the shape of the input is correct\n try:\n value = value.reshape(node.dims.shape)\n except ValueError as ex:\n trace_back = sys.exc_info()[2]\n raise ValueError(\n \"Input data dimensions are not compatible with graph input: {!s}\".format(ex)\n ).with_traceback(trace_back)\n if node.transpose_out:\n value = np.transpose(value, node.transpose_out)\n return [value], None\n\n @staticmethod\n def execute_output(node: OutputParameters,\n in_tensors: Sequence[np.array],\n qrec: QuantizationRecord = None):\n del qrec\n result = in_tensors[0]\n if node.transpose_in:\n result = np.transpose(result, node.transpose_in)\n\n return [result], None\n\n @staticmethod\n def execute_pooling(node: PoolingParameters,\n in_tensors: Sequence[np.array],\n qrec: QuantizationRecord = None):\n if node.pool_type == \"max\":\n val = max_pool(node, node.in_dims[0], node.out_dims[0], in_tensors[0], qrec)\n elif node.pool_type == \"average\":\n val = av_pool(node, node.in_dims[0], node.out_dims[0], in_tensors[0], qrec)\n else:\n raise ValueError(\"Incorrect pooling type: %s\" % node.pool_type)\n\n return [val], None\n\n @staticmethod\n def execute_linear(node: FcParameters,\n in_tensors: Sequence[np.array],\n qrec: FilterQuantizationRecord = None):\n if qrec:\n weights = qrec.weights_q.quantize(node.weights)\n biases = qrec.biases_q.quantize(node.biases)\n else:\n weights = node.weights\n biases = node.biases\n\n details = {}\n res = linear(node,\n node.in_dims[0],\n node.out_dims[0],\n in_tensors[0],\n weights,\n biases,\n qrec=qrec,\n details=details)\n return [res], details\n\n @staticmethod\n def execute_conv2d(node: Conv2DParameters,\n in_tensors: Sequence[np.array],\n qrec: FilterQuantizationRecord = None):\n\n if qrec:\n weights = qrec.weights_q.quantize(node.weights)\n biases = qrec.biases_q.quantize(node.biases)\n else:\n weights = node.weights\n biases = node.biases\n\n details = {}\n res = conv2d(node,\n node.in_dims[0],\n node.out_dims[0],\n in_tensors[0],\n weights,\n biases,\n qrec=qrec,\n details=details)\n return [res], details\n","sub_path":"tools/nntool/execution/executer.py","file_name":"executer.py","file_ext":"py","file_size_in_byte":7428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"200346355","text":"from setuptools import setup\n\nVERSION = \"2.2.3\"\n\nsetup(\n name=\"nhltv\",\n version=VERSION,\n description=\"Download NHL games from game center\",\n url=\"https://github.com/cmaxwe/dl-nhltv\",\n license=\"None\",\n keywords=\"NHL GAMECENTER\",\n packages=[\"nhltv_lib\", \"nhltv_lib.alembic\", \"nhltv_lib.alembic.versions\"],\n data_files=[\n (\"extras\", [\"nhltv_lib/extras/black.mkv\", \"nhltv_lib/alembic.ini\"])\n ],\n include_package_data=True,\n entry_points={\"console_scripts\": [\"nhltv=nhltv_lib.main:main\"]},\n install_requires=[\n \"requests==2.22.0\",\n \"alembic==1.3.3\",\n \"SQLAlchemy==1.3.12\",\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"463533699","text":"import numpy as np\nimport pandas as pd\nimport bs4\nfrom urllib.request import urlopen as uReq\nfrom bs4 import BeautifulSoup as soup\n\nmy_url ='https://www.newegg.com/Product/ProductList.aspx?Submit=ENE&DEPA=0&Order=BESTMATCH&Description=graphics+card&ignorear=0&N=-1&isNodeId=1'\nuClient = uReq(my_url)\n\npage_html = uClient.read()\nuClient.close()\npage_soup = soup(page_html , \"html.parser\")\ncontainers = page_soup.findAll(\"div\", {\"class\" : \"item-container\"})\n\nfile_name = \"products.csv\"\nf = open(file_name, \"w\")\nheaders = \"brand, Product_name, shipping\\n\"\nf.write(headers)\nfor container in containers:\n brand = container.div.div.a.img[\"title\"]\n \n title_container = container.findAll(\"a\", {\"class\" : \"item-title\"})\n product_name = title_container[0].text\n \n shipping_container = container.findAll(\"li\", {\"class\" : \"price-ship\"})\n shipping = shipping_container[0].text.strip()\n \n# print(\"brand : \" + brand)\n# print(\"product_name : \" + product_name)\n# print(\"shipping : \" + shipping)\n# print(\"\")\n \n f.write(brand + \",\" + product_name.replace(\",\", \"|\") + \",\" + shipping + \"\\n\")\nf.close()\n\ntrain_df = pd.read_csv(\"products.csv\")","sub_path":"Homeworks/Homework_5/WebScraping.py","file_name":"WebScraping.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"126924685","text":"import pygame\nimport sounds\nfrom screen import screen\nfrom hindernise import feld\nfrom time import time\nfrom KlasseHarpyie import Harpyie\n\nhintergrundLevel2 = pygame.image.load(\"Bilder\\Karte\\Level2.png\")\ntor = pygame.Rect(3*feld+ feld/2, feld, 5, 5) #Ziel in Level 2\n\nmonster1 = Harpyie(200,150,3,feld,feld,2,\"Harpyie\",time())\nmonster2 = Harpyie(300,200,3,feld,feld,2,\"Harpyie\",time())\n\ndef Level2(spieler):\n screen.blit(hintergrundLevel2, (0, 0))\n spieler.steuerung()\n\n if monster1.mLaufen(spieler) or monster2.mLaufen(spieler): #!!! versuche grade das Sterben einzuführen !!!\n pygame.display.update()\n pygame.time.wait(1000)\n monster1.reset()\n monster2.reset()\n gameOver = 4\n return gameOver\n\n if spieler.obenKollision.colliderect(tor):\n spieler.x = 582\n spieler.y = 476\n pygame.mixer.Sound.play(sounds.soundTor())\n sounds.soundBoss()\n pygame.time.wait(500)\n monster1.reset()\n monster2.reset()\n level = 3\n spieler.level = 3\n return level\n else:\n level = 2\n return level","sub_path":"Pygame/Beleg/DungeonVer3/Level2.py","file_name":"Level2.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"198364546","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 20 23:45:58 2017\n\n@author: manish\n\"\"\"\nimport pandas as pd\nimport cv2\nimport numpy as np\nimport os\nfrom random import shuffle\nfrom tqdm import tqdm\n\nTRAIN_DIR = '/home/manish/Manish/Machine_Learning/Kaggle/Cifar-10/train'\nTEST_DIR = '/home/manish/Manish/Machine_Learning/Kaggle/Cifar-10/test'\nIMG_SIZE = 32\nLR = 0.001\n\nMODEL_NAME = 'cifar_10-{}-{}.model'.format(LR, '6-conv-basic')\n\nlabels_df = pd.read_csv('/home/manish/Manish/Machine_Learning/Kaggle/Cifar-10/trainLabels.csv')\nlabels_arr = []\nfor i in range(0, len(labels_df)):\n labels_arr += [[labels_df.iloc[i,0], labels_df.iloc[i,1]]]\n\ndef label_image(img):\n label_no = int(img.split('.')[0])\n if labels_arr[label_no-1][1] == 'airplane':\n return [1,0,0,0,0,0,0,0,0,0]\n elif labels_arr[label_no-1][1] == 'automobile':\n return [0,1,0,0,0,0,0,0,0,0]\n elif labels_arr[label_no-1][1] == 'bird':\n return [0,0,1,0,0,0,0,0,0,0]\n elif labels_arr[label_no-1][1] == 'cat':\n return [0,0,0,1,0,0,0,0,0,0]\n elif labels_arr[label_no-1][1] == 'deer':\n return [0,0,0,0,1,0,0,0,0,0]\n elif labels_arr[label_no-1][1] == 'dog':\n return [0,0,0,0,0,1,0,0,0,0]\n elif labels_arr[label_no-1][1] == 'frog':\n return [0,0,0,0,0,0,1,0,0,0]\n elif labels_arr[label_no-1][1] == 'horse':\n return [0,0,0,0,0,0,0,1,0,0]\n elif labels_arr[label_no-1][1] == 'ship':\n return [0,0,0,0,0,0,0,0,1,0]\n elif labels_arr[label_no-1][1] == 'truck':\n return [0,0,0,0,0,0,0,0,0,1]\n \ndef create_train_set():\n training_data = []\n for img in tqdm(os.listdir(TRAIN_DIR)):\n label = label_image(img)\n path = os.path.join(TRAIN_DIR, img)\n img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)\n img = cv2.resize(img, (IMG_SIZE, IMG_SIZE))\n training_data.append([np.array(img), np.array(label)])\n shuffle(training_data)\n np.save('train_data.npy', training_data)\n return training_data\n\ndef create_test_set():\n test_data = []\n for img in tqdm(os.listdir(TEST_DIR)):\n path = os.path.join(TEST_DIR, img)\n img_num = img.split('.')[0]\n img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)\n img = cv2.resize(img, (IMG_SIZE, IMG_SIZE))\n test_data.append([np.array(img), img_num])\n shuffle(test_data)\n np.save('test_data.npy', test_data)\n return test_data\n\n#train_data = create_train_set() #Saved the data\n\ntrain_data = np.load('train_data.npy')\n\n\nimport tflearn\nfrom tflearn.layers.conv import conv_2d, max_pool_2d\nfrom tflearn.layers.core import input_data, dropout, fully_connected\nfrom tflearn.layers.estimator import regression\n\nconvnet = input_data(shape=[None, IMG_SIZE, IMG_SIZE, 1], name='input')\n\nconvnet = conv_2d(convnet, 32, 5 , activation = 'relu')\nconvnet = max_pool_2d(convnet, 5)\n\nconvnet = conv_2d(convnet, 64, 5, activation = 'relu')\nconvnet = max_pool_2d(convnet, 5)\n\nconvnet = conv_2d(convnet, 128, 5, activation='relu')\nconvnet = max_pool_2d(convnet, 5)\n\nconvnet = conv_2d(convnet, 64, 5, activation='relu')\nconvnet = max_pool_2d(convnet, 5)\n\nconvnet = conv_2d(convnet, 32, 5, activation='relu')\nconvnet = max_pool_2d(convnet, 5)\n\nconvnet = fully_connected(convnet, 1024, activation='relu')\nconvnet = dropout(convnet,0.8)\n\nconvnet = fully_connected(convnet, 10, activation='softmax')\nconvnet = regression(convnet, optimizer= 'adam', learning_rate = LR, loss= 'categorical_crossentropy',name='targets')\n\nmodel = tflearn.DNN(convnet, tensorboard_dir = 'log')\n\nif os.path.exists('/home/manish/Manish/Machine_Learning/Kaggle/DogvsCats/{}.meta'.format(MODEL_NAME)):\n model.load(MODEL_NAME)\n print('Model Loaded')\n \n \ntrain = train_data[:-1200]\ntest = train_data[-1200:]\n\nX = np.array([i[0] for i in train]).reshape(-1,IMG_SIZE, IMG_SIZE, 1)\nY = [i[1] for i in train]\n\ntest_x = np.array([i[0] for i in test]).reshape(-1, IMG_SIZE, IMG_SIZE, 1)\ntest_y = [i[1] for i in test]\n\nmodel.fit({'input':X}, {'targets' : Y}, n_epoch = 3, validation_set= ({'input':test_x},{'targets':test_y}), snapshot_step =500, show_metric = True, run_id= MODEL_NAME)\n\nmodel.save(MODEL_NAME)\n\n#test_data = create_test_set()\ntest_data = np.load('test_data.npy')\n\nlabels = {0: 'airplane', 1: 'automobile', 2: 'bird', 3: 'cat', 4: 'deer', 5: 'dog', 6:'frog', 7:'horse', 8:'ship', 9: 'truck'}\n\n\nimport matplotlib.pyplot as plt\nfig = plt.figure()\nfor num, data in enumerate(test_data[:12]):\n img_num = data[1]\n img_data = data[0]\n \n y = fig.add_subplot(3,4,num+1)\n orig = img_data\n data = img_data.reshape(IMG_SIZE, IMG_SIZE, 1)\n \n model_out = model.predict([data])[0]\n \n str_label = labels[np.argmax(model_out)]\n \n y.imshow(orig)\n plt.title(str_label)\n y.axes.get_xaxis().set_visible(False)\n y.axes.get_yaxis().set_visible(False)\n \nplt.show()\n\n\nwith open('submission_file.csv', 'w') as f:\n f.write('id,label\\n')\n \nwith open('submission_file.csv', 'a') as f:\n for data in tqdm(test_data):\n img_num = data[1]\n img_data = data[0]\n orig = img_data\n data = img_data.reshape(IMG_SIZE, IMG_SIZE, 1)\n model_out = model.predict([data])[0]\n str_label = labels[np.argmax(model_out)]\n f.write(\"{},{}\\n\".format(img_num, str_label))\n ","sub_path":"nnmodel.py","file_name":"nnmodel.py","file_ext":"py","file_size_in_byte":5287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"538666808","text":"import boto3\nimport json\nimport pytest\nfrom moto import mock_lambda, mock_logs, mock_s3, mock_sqs\nfrom moto.core import DEFAULT_ACCOUNT_ID as ACCOUNT_ID\nfrom tests.markers import requires_docker\nfrom tests.test_awslambda.utilities import (\n get_test_zip_file_print_event,\n get_role_name,\n wait_for_log_msg,\n)\nfrom uuid import uuid4\n\n\nREGION_NAME = \"us-east-1\"\n\n\n@mock_lambda\n@mock_logs\n@mock_s3\n@pytest.mark.parametrize(\n \"match_events,actual_event\",\n [\n ([\"s3:ObjectCreated:Put\"], \"ObjectCreated:Put\"),\n ([\"s3:ObjectCreated:*\"], \"ObjectCreated:Put\"),\n ([\"s3:ObjectCreated:Post\"], None),\n ([\"s3:ObjectCreated:Post\", \"s3:ObjectCreated:*\"], \"ObjectCreated:Put\"),\n ],\n)\n@requires_docker\ndef test_objectcreated_put__invokes_lambda(match_events, actual_event):\n s3_res = boto3.resource(\"s3\", region_name=REGION_NAME)\n s3_client = boto3.client(\"s3\", region_name=REGION_NAME)\n lambda_client = boto3.client(\"lambda\", REGION_NAME)\n\n # Create S3 bucket\n bucket_name = str(uuid4())\n s3_res.create_bucket(Bucket=bucket_name)\n\n # Create AWSLambda function\n function_name = str(uuid4())[0:6]\n fn_arn = lambda_client.create_function(\n FunctionName=function_name,\n Runtime=\"python3.7\",\n Role=get_role_name(),\n Handler=\"lambda_function.lambda_handler\",\n Code={\"ZipFile\": get_test_zip_file_print_event()},\n )[\"FunctionArn\"]\n\n # Put Notification\n s3_client.put_bucket_notification_configuration(\n Bucket=bucket_name,\n NotificationConfiguration={\n \"LambdaFunctionConfigurations\": [\n {\n \"Id\": \"unrelated\",\n \"LambdaFunctionArn\": f\"arn:aws:lambda:us-east-1:{ACCOUNT_ID}:function:n/a\",\n \"Events\": [\"s3:ReducedRedundancyLostObject\"],\n },\n {\n \"Id\": \"s3eventtriggerslambda\",\n \"LambdaFunctionArn\": fn_arn,\n \"Events\": match_events,\n },\n ]\n },\n )\n\n # Put Object\n s3_client.put_object(Bucket=bucket_name, Key=\"keyname\", Body=\"bodyofnewobject\")\n\n # Find the output of AWSLambda\n expected_msg = \"FINISHED_PRINTING_EVENT\"\n log_group = f\"/aws/lambda/{function_name}\"\n msg_showed_up, all_logs = wait_for_log_msg(expected_msg, log_group, wait_time=10)\n\n if actual_event is None:\n # The event should not be fired on POST, as we've only PUT an event for now\n assert not msg_showed_up\n return\n\n # If we do have an actual event, verify the Lambda was invoked with the correct event\n assert msg_showed_up, (\n expected_msg\n + \" was not found after sending an SQS message. All logs: \"\n + str(all_logs)\n )\n\n records = [line for line in all_logs if line.startswith(\"{'Records'\")][0]\n records = json.loads(records.replace(\"'\", '\"'))[\"Records\"]\n\n records.should.have.length_of(1)\n records[0].should.have.key(\"awsRegion\").equals(REGION_NAME)\n records[0].should.have.key(\"eventName\").equals(actual_event)\n records[0].should.have.key(\"eventSource\").equals(\"aws:s3\")\n records[0].should.have.key(\"eventTime\")\n records[0].should.have.key(\"s3\")\n records[0][\"s3\"].should.have.key(\"bucket\")\n records[0][\"s3\"][\"bucket\"].should.have.key(\"arn\").equals(\n f\"arn:aws:s3:::{bucket_name}\"\n )\n records[0][\"s3\"][\"bucket\"].should.have.key(\"name\").equals(bucket_name)\n records[0][\"s3\"].should.have.key(\"configurationId\").equals(\"s3eventtriggerslambda\")\n records[0][\"s3\"].should.have.key(\"object\")\n records[0][\"s3\"][\"object\"].should.have.key(\"eTag\").equals(\n \"61ea96c3c8d2c76fc5a42bfccb6affd9\"\n )\n records[0][\"s3\"][\"object\"].should.have.key(\"key\").equals(\"keyname\")\n records[0][\"s3\"][\"object\"].should.have.key(\"size\").equals(15)\n\n\n@mock_logs\n@mock_s3\ndef test_objectcreated_put__unknown_lambda_is_handled_gracefully():\n s3_res = boto3.resource(\"s3\", region_name=REGION_NAME)\n s3_client = boto3.client(\"s3\", region_name=REGION_NAME)\n\n # Create S3 bucket\n bucket_name = str(uuid4())\n s3_res.create_bucket(Bucket=bucket_name)\n\n # Put Notification\n s3_client.put_bucket_notification_configuration(\n Bucket=bucket_name,\n NotificationConfiguration={\n \"LambdaFunctionConfigurations\": [\n {\n \"Id\": \"unrelated\",\n \"LambdaFunctionArn\": f\"arn:aws:lambda:us-east-1:{ACCOUNT_ID}:function:n/a\",\n \"Events\": [\"s3:ObjectCreated:Put\"],\n }\n ]\n },\n )\n\n # Put Object\n s3_client.put_object(Bucket=bucket_name, Key=\"keyname\", Body=\"bodyofnewobject\")\n\n # The object was persisted successfully\n resp = s3_client.get_object(Bucket=bucket_name, Key=\"keyname\")\n resp.should.have.key(\"ContentLength\").equal(15)\n resp[\"Body\"].read().should.equal(b\"bodyofnewobject\")\n\n\n@mock_s3\n@mock_sqs\ndef test_object_copy__sends_to_queue():\n s3_res = boto3.resource(\"s3\", region_name=REGION_NAME)\n s3_client = boto3.client(\"s3\", region_name=REGION_NAME)\n sqs_client = boto3.client(\"sqs\", region_name=REGION_NAME)\n\n # Create S3 bucket\n bucket_name = str(uuid4())\n s3_res.create_bucket(Bucket=bucket_name)\n\n # Create SQS queue\n queue_url = sqs_client.create_queue(QueueName=str(uuid4())[0:6])[\"QueueUrl\"]\n queue_arn = sqs_client.get_queue_attributes(\n QueueUrl=queue_url, AttributeNames=[\"QueueArn\"]\n )[\"Attributes\"][\"QueueArn\"]\n\n # Put Notification\n s3_client.put_bucket_notification_configuration(\n Bucket=bucket_name,\n NotificationConfiguration={\n \"QueueConfigurations\": [\n {\n \"Id\": \"queue_config\",\n \"QueueArn\": queue_arn,\n \"Events\": [\"s3:ObjectCreated:Copy\"],\n }\n ]\n },\n )\n\n # We should have received a test event now\n messages = sqs_client.receive_message(QueueUrl=queue_url)[\"Messages\"]\n messages.should.have.length_of(1)\n message = json.loads(messages[0][\"Body\"])\n message.should.have.key(\"Service\").equals(\"Amazon S3\")\n message.should.have.key(\"Event\").equals(\"s3:TestEvent\")\n message.should.have.key(\"Time\")\n message.should.have.key(\"Bucket\").equals(bucket_name)\n\n # Copy an Object\n s3_client.put_object(Bucket=bucket_name, Key=\"keyname\", Body=\"bodyofnewobject\")\n s3_client.copy_object(\n Bucket=bucket_name, CopySource=f\"{bucket_name}/keyname\", Key=\"key2\"\n )\n\n # Read SQS messages - we should have the Copy-event here\n resp = sqs_client.receive_message(QueueUrl=queue_url)\n resp.should.have.key(\"Messages\").length_of(1)\n records = json.loads(resp[\"Messages\"][0][\"Body\"])[\"Records\"]\n\n records.should.have.length_of(1)\n records[0].should.have.key(\"awsRegion\").equals(REGION_NAME)\n records[0].should.have.key(\"eventName\").equals(\"ObjectCreated:Copy\")\n records[0].should.have.key(\"eventSource\").equals(\"aws:s3\")\n records[0].should.have.key(\"eventTime\")\n records[0].should.have.key(\"s3\")\n records[0][\"s3\"].should.have.key(\"bucket\")\n records[0][\"s3\"][\"bucket\"].should.have.key(\"arn\").equals(\n f\"arn:aws:s3:::{bucket_name}\"\n )\n records[0][\"s3\"][\"bucket\"].should.have.key(\"name\").equals(bucket_name)\n records[0][\"s3\"].should.have.key(\"configurationId\").equals(\"queue_config\")\n records[0][\"s3\"].should.have.key(\"object\")\n records[0][\"s3\"][\"object\"].should.have.key(\"eTag\").equals(\n \"61ea96c3c8d2c76fc5a42bfccb6affd9\"\n )\n records[0][\"s3\"][\"object\"].should.have.key(\"key\").equals(\"key2\")\n records[0][\"s3\"][\"object\"].should.have.key(\"size\").equals(15)\n\n\n@mock_s3\n@mock_sqs\ndef test_object_put__sends_to_queue__using_filter():\n s3_res = boto3.resource(\"s3\", region_name=REGION_NAME)\n s3_client = boto3.client(\"s3\", region_name=REGION_NAME)\n sqs = boto3.resource(\"sqs\", region_name=REGION_NAME)\n\n # Create S3 bucket\n bucket_name = str(uuid4())\n s3_res.create_bucket(Bucket=bucket_name)\n\n # Create SQS queue\n queue = sqs.create_queue(QueueName=f\"{str(uuid4())[0:6]}\")\n queue_arn = queue.attributes[\"QueueArn\"]\n\n # Put Notification\n s3_client.put_bucket_notification_configuration(\n Bucket=bucket_name,\n NotificationConfiguration={\n \"QueueConfigurations\": [\n {\n \"Id\": \"prefixed\",\n \"QueueArn\": queue_arn,\n \"Events\": [\"s3:ObjectCreated:Put\"],\n \"Filter\": {\n \"Key\": {\"FilterRules\": [{\"Name\": \"prefix\", \"Value\": \"aa\"}]}\n },\n },\n {\n \"Id\": \"images_only\",\n \"QueueArn\": queue_arn,\n \"Events\": [\"s3:ObjectCreated:Put\"],\n \"Filter\": {\n \"Key\": {\n \"FilterRules\": [\n {\"Name\": \"prefix\", \"Value\": \"image/\"},\n {\"Name\": \"suffix\", \"Value\": \"jpg\"},\n ]\n }\n },\n },\n ]\n },\n )\n\n # Read the test-event\n resp = queue.receive_messages()\n [m.delete() for m in resp]\n\n # Create an Object that does not meet any filter\n s3_client.put_object(Bucket=bucket_name, Key=\"bb\", Body=\"sth\")\n messages = queue.receive_messages()\n messages.should.have.length_of(0)\n [m.delete() for m in messages]\n\n # Create an Object that does meet the filter - using the prefix only\n s3_client.put_object(Bucket=bucket_name, Key=\"aafilter\", Body=\"sth\")\n messages = queue.receive_messages()\n messages.should.have.length_of(1)\n [m.delete() for m in messages]\n\n # Create an Object that does meet the filter - using the prefix + suffix\n s3_client.put_object(Bucket=bucket_name, Key=\"image/yes.jpg\", Body=\"img\")\n messages = queue.receive_messages()\n messages.should.have.length_of(1)\n [m.delete() for m in messages]\n\n # Create an Object that does not meet the filter - only the prefix\n s3_client.put_object(Bucket=bucket_name, Key=\"image/no.gif\", Body=\"img\")\n messages = queue.receive_messages()\n messages.should.have.length_of(0)\n [m.delete() for m in messages]\n\n # Create an Object that does not meet the filter - only the suffix\n s3_client.put_object(Bucket=bucket_name, Key=\"nonimages/yes.jpg\", Body=\"img\")\n messages = queue.receive_messages()\n messages.should.have.length_of(0)\n [m.delete() for m in messages]\n","sub_path":"tests/test_s3/test_s3_lambda_integration.py","file_name":"test_s3_lambda_integration.py","file_ext":"py","file_size_in_byte":10568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"100061660","text":"from flask import render_template, redirect, request, session, redirect, url_for, escape\r\nfrom app import app, models, db\r\nfrom .forms import TravelerForm, TravelForm\r\nfrom .models import *\r\n# Access the models file to use SQL functions\r\n\r\n@app.route('/')\r\n@app.route('/index')\r\ndef index():\r\n username = ''\r\n if 'username' in session:\r\n username = escape(session['username'])\r\n return redirect('/travelers')\r\n else:\r\n return render_template('login.html')\r\n\r\n@app.route('/login', methods=['GET', 'POST'])\r\ndef login():\r\n form=TravelerForm\r\n if request.method=='POST':\r\n username = request.form.get(\"username\")\r\n if verify(username):\r\n session['username'] = request.form.get(\"username\")\r\n return redirect('/travelers')\r\n else:\r\n return render_template('not_authorized.html')\r\n\r\n@app.route('/signup_click', methods=['GET', 'POST'])\r\ndef signup_click():\r\n return render_template('signup.html')\r\n\r\n@app.route('/signup', methods=['GET', 'POST'])\r\ndef signup():\r\n form=TravelerForm\r\n if request.method=='POST':\r\n username = request.form.get(\"username\")\r\n if verify(username):\r\n return render_template('alreadyregistered.html')\r\n else:\r\n sign_up(username)\r\n session['username'] = request.form.get(\"username\")\r\n return redirect('/travelers')\r\n\r\n@app.route('/delete_travel/', methods=['GET', 'POST'])\r\ndef delete_travel(value):\r\n form = TravelForm(obj=value)\r\n delete_travels(value)\r\n return redirect('/travelers')\r\n\r\n@app.route('/logout')\r\ndef logout():\r\n session.pop('username', None)\r\n return redirect(url_for('index'))\r\n\r\n@app.route('/travelers')\r\ndef display_traveler():\r\n #Retreive data from database to display\r\n travels = retrieve_travels()\r\n travels2 = retrieve_travels2()\r\n username = escape(session['username'])\r\n return render_template('home.html',\r\n travels=travels, travels2=travels2, name=username)\r\n\r\n@app.route('/create_travel/', methods=['GET', 'POST'])\r\ndef create_travel(value):\r\n # Get data from the form\r\n # Send data from form to Database\r\n form = TravelForm(obj=value)\r\n username = escape(session['username'])\r\n if form.validate_on_submit():\r\n trip_name = form.trip_name.data\r\n destination = form.destination.data\r\n friend = form.friend.data\r\n insert_travels(trip_name, destination, friend, username)\r\n return redirect('/travelers')\r\n return render_template('travel.html', form=form, name=username)\r\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"31"} +{"seq_id":"635953004","text":"__author__ = 'tomislav'\nfrom django.conf.urls import url\nfrom django.contrib.auth.decorators import login_required\n\nfrom . import views\n\nurlpatterns = (\n url(r\"^$\", views.LoginRegistrationView.as_view(), name='login_glarus'),\n url(r\"^validate/(?P.*)/$\", views.validate_email),\n url(r\"^membership/$\", login_required(views.MembershipView.as_view()), name='membership'),\n url(r'logout/?$',views.logout_glarus,name='logout_glarus'),\n url(r\"^buy/(?P