diff --git "a/5304.jsonl" "b/5304.jsonl" new file mode 100644--- /dev/null +++ "b/5304.jsonl" @@ -0,0 +1,670 @@ +{"seq_id":"581729454","text":"import os\nimport utils\nimport logging\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom bagel.data import KPI\nfrom datetime import datetime\nfrom matplotlib.figure import Figure, Axes\n\n\ndef _plot_abnormal(kpi: KPI, ax: Axes, series: np.ndarray, color: str):\n split_index = np.where(np.diff(series) != 0)[0] + 1\n points = np.vstack((kpi.timestamps, kpi.values)).T.reshape(-1, 2)\n segments = np.split(points, split_index)\n for i in range(len(segments) - 1):\n segments[i] = np.concatenate([segments[i], [segments[i + 1][0]]])\n if series[0] == 1:\n segments = segments[0::2]\n else:\n segments = segments[1::2]\n for line in segments:\n ax.plot([datetime.fromtimestamp(timestamp) for timestamp in line[:, 0]], line[:, 1], color)\n\n\ndef _plot_kpi(kpi: KPI, fig: Figure):\n ax: Axes = fig.add_subplot()\n ax.plot([datetime.fromtimestamp(timestamp) for timestamp in kpi.timestamps], kpi.values)\n _plot_abnormal(kpi=kpi, ax=ax, series=kpi.labels, color='red')\n _plot_abnormal(kpi=kpi, ax=ax, series=kpi.missing, color='orange')\n ax.set_title(kpi.name)\n ax.set_ylim(-7.5, 7.5)\n\n\ndef main():\n utils.mkdirs(OUTPUT)\n file_list = utils.list_file(INPUT)\n progress = utils.ProgressLogger(len(file_list))\n\n fig: Figure = plt.figure(figsize=(16, 4))\n for file in file_list:\n kpi = utils.load_kpi(file)\n progress.log(kpi=kpi.name)\n kpi, _, _ = kpi.standardize()\n\n _plot_kpi(kpi=kpi, fig=fig)\n fig.savefig(os.path.join(OUTPUT, kpi.name + '.png'))\n fig.clear()\n\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.INFO, format='[%(asctime)s [%(levelname)s]] %(message)s')\n\n INPUT = 'data'\n OUTPUT = 'out/plot'\n\n main()\n","sub_path":"sample/plot_kpi.py","file_name":"plot_kpi.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"230832445","text":"#!/usr/bin/env python\n\"\"\"Test script.\"\"\"\nimport sys\nfrom datetime import datetime\n\nfrom pyskyqremote.classes.media import MediaDecoder\nfrom pyskyqremote.const import APP_EPG, SKY_STATE_OFF, SKY_STATE_STANDBY\nfrom pyskyqremote.skyq_remote import SkyQRemote\n\n# from pyskyqremote.device import DeviceDecoder\n# from pyskyqremote.channel import ChannelDecoder\n# from pyskyqremote.programme import ProgrammeDecoder, RecordedProgrammeDecoder\n\n\n# Run ./bash_sky.py \n# example: ./bash_sky_test.py 192.168.0.9\n# Note: you may need to modify top line change python3 to python, depending on OS/setup. this is works for me on my mac\ncountry = None\ntest_channel = None\nqueryDate = datetime.utcnow()\nif len(sys.argv) > 2:\n if sys.argv[2] != \"None\":\n country = sys.argv[2]\nif len(sys.argv) > 3:\n test_channel = sys.argv[3]\nif len(sys.argv) > 4:\n queryDate = datetime.utcfromtimestamp(int(sys.argv[4]))\n\nsky = SkyQRemote(sys.argv[1])\nsky.setOverrides(overrideCountry=country, test_channel=test_channel)\n\nprint(\"----------- Power status\")\nprint(sky.powerStatus())\n\nif sky.powerStatus != SKY_STATE_OFF:\n print(\"----------- DeviceInfo\")\n print(sky.getDeviceInformation().as_json())\n # print(\"----------- DeviceInfo Decoded\")\n # print(DeviceDecoder(sky.getDeviceInformation().as_json()))\n\nprint(\"----------- Current status\")\ncurrentState = sky.getCurrentState()\nprint(sky.getCurrentState())\nif currentState == SKY_STATE_STANDBY:\n exit()\n\nprint(\"----------- Active Application\")\napp = sky.getActiveApplication()\nprint(str(app))\nif app != APP_EPG:\n exit()\n\nprint(\"----------- Current Media\")\ncurrentMedia = sky.getCurrentMedia().as_json()\nprint(currentMedia)\n\nmedia = MediaDecoder(currentMedia)\nif not media.live:\n print(\"----------- Recording\")\n print(sky.getRecording(media.pvrId).as_json())\n\nif test_channel:\n sid = test_channel\nelse:\n sid = media.sid\n\nprint(f\"----------- Programme from Epg - {queryDate} - {sid}\")\nprint(sky.getProgrammeFromEpg(sid, queryDate, queryDate).as_json())\n\nprint(f\"----------- Current Live TV - {sid}\")\nprint(sky.getCurrentLiveTVProgramme(sid).as_json())\n\nprint(\"----------- Get Channel Info - 101\")\nprint(sky.getChannelInfo(\"101\").as_json())\n\n# print(\"----------- Channel list\")\n# print(sky.getChannelList().as_json())\n\n# print(\"----------- Today's EPG\")\n# print(sky.getEpgData(sid, queryDate).as_json())\n","sub_path":"tests/bash_sky_test.py","file_name":"bash_sky_test.py","file_ext":"py","file_size_in_byte":2372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"46329656","text":"import unittest\nimport json\n\nfrom opencricket.chart.sentence_parser import SentenceParser\n\n\nclass TestMostX(unittest.TestCase):\n\n def setUp(self):\n self.input_sixes = 'who has the most sixes'\n self.expected_sixes = '{\"most_x\": {\"word_most\": \"most\", \"who_player\": {\"word_who\": \"who\"}, \"metric\": {\"metric1\": \"sixes\" }, \"word_the\": \"the\", \"word_has\": \"has\"}}'\n\n self.input_not_outs = 'who has the highest not outs'\n self.expected_not_outs = '{\"most_x\": {\"word_most\": \"highest\", \"who_player\": {\"word_who\": \"who\"}, \"metric\": {\"metric1\": \"not\", \"metric2\": \"outs\" }, \"word_the\": \"the\", \"word_has\": \"has\"}}'\n\n self.input_bowling_strike_rate = 'who has the best bowling strike rate'\n self.expected_bowling_strike_rate = '{\"most_x\": {\"word_most\": \"best\", \"who_player\": {\"word_who\": \"who\"}, \"metric\": {\"metric1\": \"bowling\", \"metric2\": \"strike\", \"metric3\": \"rate\" }, \"word_the\": \"the\", \"word_has\": \"has\"}}'\n\n self.input_match_type = 'who has the most fours in ODI'\n self.expected_match_type = '{\"most_x\": {\"word_the\": \"the\", \"word_has\": \"has\", \"word_in\": \"in\", \"match_type\": \"odi\", \"who_player\": {\"word_who\": \"who\"}, \"metric\": {\"metric1\": \"fours\" }, \"word_most\": \"most\"}}'\n\n self.input_which_player = 'which player has the most sixes'\n self.expected_which_player = '{\"most_x\": {\"word_the\": \"the\", \"word_has\": \"has\", \"who_player\": {\"word_player\": \"player\", \"word_which\": \"which\"}, \"word_most\": \"most\", \"metric\": {\"metric1\": \"sixes\" }}}'\n\n self.input_ground = 'which player has the most sixes in Chennai'\n self.expected_ground = '{\"most_x\": {\"word_the\": \"the\", \"word_has\": \"has\", \"word_in\": \"in\", \"who_player\": {\"word_player\": \"player\", \"word_which\": \"which\"}, \"word_most\": \"most\", \"metric\": {\"metric1\": \"sixes\" }, \"ground\": {\"ground1\": \"chennai\"}}}'\n\n # Title case not to be detected as Ground\n self.input_series_year = 'which player has the most sixes in World Cup in 2011'\n self.expected_series_year = '{\"most_x\": {\"metric\": {\"metric1\": \"sixes\" }, \"word_the\": \"the\", \"word_has\": \"has\", \"word_in\": \"in\", \"series\": {\"series2\": \"cup\", \"series1\": \"world\"}, \"word_most\": \"most\", \"year\": \"2011\", \"who_player\": {\"word_player\": \"player\", \"word_which\": \"which\"}}}'\n\n self.input_match_type_year = 'which player has the most runs in 2011 in test'\n self.expected_match_type_year = '{\"most_x\": {\"year\": \"2011\", \"metric\": {\"metric1\": \"runs\" }, \"word_in\": \"in\", \"match_type\": \"test\", \"word_most\": \"most\", \"word_the\": \"the\", \"word_has\": \"has\", \"who_player\": {\"word_player\": \"player\", \"word_which\": \"which\"}}}'\n\n self.input_year_match_type = 'who has the most runs in t20 in 2014'\n self.expected_year_match_type = '{\"most_x\": {\"year\": \"2014\", \"metric\": {\"metric1\": \"runs\" }, \"word_in\": \"in\", \"match_type\": \"t20\", \"word_most\": \"most\", \"word_the\": \"the\", \"word_has\": \"has\", \"who_player\": {\"word_who\": \"who\"}}}'\n\n self.input_team_player = 'which Indian player has the most runs in World Cup in Australia'\n self.expected_team_player = '{\"most_x\": {\"ground\": {\"ground1\": \"australia\"}, \"metric\": {\"metric1\": \"runs\" }, \"word_in\": \"in\", \"series\": {\"series2\": \"cup\", \"series1\": \"world\"}, \"word_most\": \"most\", \"word_the\": \"the\", \"word_has\": \"has\", \"who_player\": {\"word_player\": \"player\", \"word_which\": \"which\", \"teamplayer\": {\"team_player1\": \"indian\"}}}}'\n\n def test_search_sixes(self):\n parser = SentenceParser(self.input_sixes)\n self.assertEqual(json.loads(self.expected_sixes), json.loads(parser.parse_sentence()))\n\n def test_search_not_outs(self):\n parser = SentenceParser(self.input_not_outs)\n self.assertEqual(json.loads(self.expected_not_outs), json.loads(parser.parse_sentence()))\n\n def test_search_bowling_strike_rate(self):\n parser = SentenceParser(self.input_bowling_strike_rate)\n self.assertEqual(json.loads(self.expected_bowling_strike_rate), json.loads(parser.parse_sentence()))\n\n def test_search_match_type(self):\n parser = SentenceParser(self.input_match_type)\n self.assertEqual(json.loads(self.expected_match_type), json.loads(parser.parse_sentence()))\n\n def test_search_which_player(self):\n parser = SentenceParser(self.input_which_player)\n self.assertEqual(json.loads(self.expected_which_player), json.loads(parser.parse_sentence()))\n\n def test_search_ground(self):\n parser = SentenceParser(self.input_ground)\n self.assertEqual(json.loads(self.expected_ground), json.loads(parser.parse_sentence()))\n\n def test_search_series_year(self):\n parser = SentenceParser(self.input_series_year)\n self.assertEqual(json.loads(self.expected_series_year), json.loads(parser.parse_sentence()))\n\n def test_search_match_type_year(self):\n parser = SentenceParser(self.input_match_type_year)\n self.assertEqual(json.loads(self.expected_match_type_year), json.loads(parser.parse_sentence()))\n\n def test_year_match_type(self):\n parser = SentenceParser(self.input_year_match_type)\n self.assertEqual(json.loads(self.expected_year_match_type), json.loads(parser.parse_sentence()))\n\n def test_team_player(self):\n parser = SentenceParser(self.input_team_player )\n self.assertEqual(json.loads(self.expected_team_player), json.loads(parser.parse_sentence()))\n\nif __name__ == '__main__':\n unittest.main()\n\n","sub_path":"tests/test_most_x.py","file_name":"test_most_x.py","file_ext":"py","file_size_in_byte":5382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"272041368","text":"#!/usr/bin/python3\n\n'''\nThe map of the ray from the origin with argument pi/4, by f(z) = exp(z). Grows very fast. Use ANIM = True to get an animated version stating far away, zooming in to the origin. If CIRC = True, then you get a map of the unit circle under exp(z)\n'''\n\nimport scipy, scipy.stats\nimport matplotlib.pyplot as plt\n# okay...\nimport matplotlib\nfrom matplotlib.backends.backend_pgf import FigureCanvasPgf\nmatplotlib.backend_bases.register_backend('pdf', FigureCanvasPgf)\npgf_with_pdflatex={\n \"pgf.texsystem\":\"pdflatex\",\n \"pgf.preamble\":[\n r\"\\usepackage[utf8x]{inputenc}\",\n r\"\\usepackage[T1]{fontenc}\",\n r\"\\usepackage{cmbright}\",\n ]\n}\nmatplotlib.rcParams.update(pgf_with_pdflatex)\n\nimport numpy as np\nimport cmath\n\nRAY = True\nCIRC = False\nANIM = True\n\nif RAY:\n import pdb\n x = np.arange(0,4*np.pi, .05)\n #y = np.arange(0,2*np.pi, .05)\n y1 = np.arange(0,2*np.pi, .05)\n y2 = np.arange(0,2*np.pi, .05)\n y = np.append(y1, y2)\n xx = np.zeros(x.size)\n yy = np.zeros(x.size)\n\n size = x.size\n fig = plt.figure()\n lim = np.exp(x[size-1])\n ax = plt.axes(ylim = (-lim,lim), xlim=(-lim,lim))\n line, = ax.plot([],[], lw=2)\n for i in range(size):\n xx[i] = np.exp(x[i])*np.cos(y[i])\n yy[i] = np.exp(x[i])*np.sin(y[i]) \n\n def init():\n plt.plot(x, y)\n plt.plot(xx, yy)\n\n def animate(i):\n newlim = lim*np.exp(-i*.05)\n #print(\"i: \", i, \"newlim: \", newlim)\n line.set_data(xx,yy)\n ax.set_xlim(-newlim, newlim)\n ax.set_ylim(-newlim, newlim)\n \n if ANIM:\n from matplotlib.animation import FuncAnimation\n anim = FuncAnimation(fig, animate, init_func=init,\n frames=x.size+10, interval=60, blit=False)\n\n else:\n init()\n plt.grid()\n plt.show()\n \n \n\nif CIRC:\n mag = 1\n arg = np.arange(0, 2*np.pi, .01)\n # {x_k,y_k} is the set of points on the unit circle, the pre-image\n x = np.zeros(arg.size)\n y = np.zeros(arg.size)\n\n # {xx_k,yy_k} is the set of points under the map exp(z), the image\n xx = np.zeros(arg.size)\n yy = np.zeros(arg.size)\n\n # set up the pre-image arrays\n for i in range(arg.size):\n x[i] = mag*np.cos(arg[i])\n y[i] = mag*np.sin(arg[i])\n \n # apply the function exp(z)\n for i in range(arg.size):\n complex_num = complex(x[i], y[i])\n complex_exp = complex(np.exp(x[i])*(np.cos(y[i])), np.exp(x[i])*(np.sin(y[i])))\n xx[i] = complex_exp.real\n yy[i] = complex_exp.imag\n\n p1 = plt.plot(x,y, label=\"The pre-image\", color=\"red\", alpha = .4, lw=3)\n p2 = plt.plot(xx,yy, label=\"The image under $e^z$\", lw = 3)\n plt.legend(fontsize=10, loc=2)\n plt.grid()\n plt.show()\n","sub_path":"exp_spiral.py","file_name":"exp_spiral.py","file_ext":"py","file_size_in_byte":2768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"471392555","text":"from django.contrib.staticfiles.testing import StaticLiveServerTestCase\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom django.core.exceptions import ValidationError\nfrom django.test import TestCase\nfrom selenium.webdriver.support.wait import WebDriverWait\n\nfrom .models import Flight, Crew, CrewMembership\nfrom django.test import LiveServerTestCase\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.select import Select\nimport selenium.webdriver.support.ui as ui\nfrom selenium.webdriver.common.by import By\n\n\nclass CrewTestCase(StaticLiveServerTestCase):\n\n def setUp(self):\n # tutaj trzeba zmienic sciezke do drivera\n path_to_webdriver = \"C:/Users/Piotr Dudko/Documents/chromedriver_win32/chromedriver.exe\"\n self.selenium1 = webdriver.Chrome(path_to_webdriver)\n self.selenium2 = webdriver.Chrome(path_to_webdriver)\n\n @staticmethod\n def check_crew_members():\n try:\n for cm in CrewMembership.objects.all():\n cm.clean()\n return True\n except ValidationError:\n return False\n\n @staticmethod\n def check_flights():\n try:\n for f in Flight.objects.all():\n f.clean()\n return True\n except ValidationError:\n return False\n\n @staticmethod\n def check_crews():\n try:\n for c in Crew.objects.all():\n c.clean()\n return True\n except ValidationError:\n return False\n\n def test_register_crew_and_everyting(self):\n selenium1 = self.selenium1\n selenium2 = self.selenium2\n # pierwsze dodanie:\n selenium1.get('http://localhost:8000/static/rest.html')\n WebDriverWait(self.selenium1, 10).until(\n EC.text_to_be_present_in_element((By.ID, \"status\"), \"online\")\n )\n origins1 = Select(selenium1.find_element_by_id('origins'))\n destinations1 = Select(selenium1.find_element_by_id('destinations'))\n dates1 = Select(selenium1.find_element_by_id('dates'))\n\n origins1.select_by_visible_text(\"Londyn\")\n destinations1.select_by_visible_text(\"Madryt\")\n dates1.select_by_visible_text('2018-02-01T10:29:13Z')\n selenium1.find_element_by_id('show').click()\n\n # #drugie dodanie\n selenium2.get('http://localhost:8000/static/rest.html')\n WebDriverWait(self.selenium2, 10).until(\n EC.text_to_be_present_in_element((By.ID, \"status\"), \"online\")\n )\n origins2 = Select(selenium2.find_element_by_id('origins'))\n destinations2 = Select(selenium2.find_element_by_id('destinations'))\n dates2 = Select(selenium2.find_element_by_id('dates'))\n origins2.select_by_visible_text('Moskwa')\n destinations2.select_by_visible_text('Paryż')\n dates2.select_by_visible_text('2018-02-01T10:51:53Z')\n selenium2.find_element_by_id('show').click()\n\n WebDriverWait(selenium1, 10).until(\n EC.text_to_be_present_in_element((By.ID, \"status\"), \"loaded\")\n )\n WebDriverWait(selenium2, 10).until(\n EC.text_to_be_present_in_element((By.ID, \"status\"), \"loaded\")\n )\n\n # wybieramy te sama zaloge\n Select(selenium1.find_element_by_id('crews'))\n Select(selenium2.find_element_by_id('crews'))\n\n\n # wciskamy przyciski zmian zalogi\n selenium1.find_element_by_id(\"edit\").click()\n WebDriverWait(self.selenium1, 10).until(\n EC.alert_is_present()\n )\n selenium1.switch_to.alert.accept()\n WebDriverWait(self.selenium1, 10).until(\n EC.text_to_be_present_in_element((By.ID, \"status\"), \"refresh crew to see changes\")\n )\n\n selenium2.find_element_by_id(\"edit\").click()\n WebDriverWait(self.selenium2, 10).until(\n EC.alert_is_present()\n )\n selenium2.switch_to.alert.accept()\n WebDriverWait(self.selenium2, 10).until(\n EC.text_to_be_present_in_element((By.ID, \"status\"), \"crew changes failed\")\n )\n\n # ten test ma obrazowac, ze dodanie tej samej zalogi dla dwoch roznych lotow\n # w tym samym czasie nie powiedzie sie dla jednego z tych lotow\n\n selenium1.implicitly_wait(10)\n selenium2.implicitly_wait(10)\n\n # teraz przechodzimy sie po calej bazie i sprawdzamy, czy wszystkie loty i\n # zalogi sa poprawnie zapisane\n\n assert self.check_crews() is True\n print(\"crews fine\")\n assert self.check_crew_members() is True\n print(\"crew members fine\")\n assert self.check_flights() is True\n print(\"flights fine\")\n\n\n\n","sub_path":"flights/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":4699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"199437822","text":"#!/usr/bin/env python\n# coding=utf-8\n#\n# Author: Lucas\n# Date: 2019-07-09 21:17:35\n\n\nclass Solution:\n def _dfs(self, matrix, visited, i, j):\n if visited[i][j]:\n return\n visited[i][j] = True\n for x, y in [(i+1, j), (i-1, j), (i, j+1), (i, j-1)]:\n if x < 0 or y < 0 or x >= len(matrix) or y >= len(matrix[0]):\n continue\n if matrix[x][y] < matrix[i][j]:\n continue\n self._dfs(matrix, visited, x, y)\n\n def pacificAtlantic(self, matrix: List[List[int]]) -> List[List[int]]:\n h = len(matrix)\n if h == 0:\n return []\n w = len(matrix[0])\n\n pacific = [[False] * w for _ in range(h)]\n for i in range(h):\n self._dfs(matrix, pacific, i, 0)\n for j in range(1, w):\n self._dfs(matrix, pacific, 0, j)\n\n atlantic = [[False] * w for _ in range(h)]\n for i in range(h):\n self._dfs(matrix, atlantic, i, w - 1)\n for j in range(w):\n self._dfs(matrix, atlantic, h - 1, j)\n\n ans = []\n for i in range(h):\n for j in range(w):\n if pacific[i][j] and atlantic[i][j]:\n ans.append([i, j])\n return ans\n","sub_path":"401-500/417_PacificAtlanticWaterFlow/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"292647045","text":"#!/usr/local/bin/python\n\"\"\"\n File: itertextfile\n \n Description: Returns each line of a file\n \n Creation Date: 2014.10.28\n\"\"\"\nimport sys\nimport os\n__author__ = 'raduw'\n\ndef iterate_text_file( *file_names):\n \"\"\"\n Returns each line of a file\n \"\"\"\n currentDir = os.getcwd()\n for file_name in file_names:\n if not os.path.isabs(file_name):\n file_name = os.path.join(currentDir,file_name)\n f = open(file_name)\n while True:\n line = f.readline()\n if line:\n yield line\n else:\n return\n\nif __name__ == '__main__':\n if sys.argv > 1:\n for line in iterate_text_file(*sys.argv[1:]):\n sys.stdout.write(line)\n","sub_path":"shellwepy/itertextfile.py","file_name":"itertextfile.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"535681008","text":"def life():\n while True:\n namefile = input(\"Enter input file name: \")\n try:\n inFile = open(namefile, \"r\")\n break\n except:\n print(\"No such file. Try again.\")\n while True:\n numgenerations = input(\"How many new generations would you like to print?\")\n if numgenerations.isdigit() is not True:\n print(\"Not a valid number.\")\n else:\n break\n\n lst = inFile.readlines()\n count = 0\n while (count <= len(numgenerations)):\n print(\"Generation:\", count)\n for i in range(0, len(lst)):\n for j in range(0, len(lst[0])-1):\n if lst[i][j] == \"0\":\n print(\".\", end = \" \")\n else:\n print(\"*\", end = \" \")\n print()\n lst = nextGen(lst)\n count = count + 1\n tinyglider = []\n for i in range(1, lst-1):\n newrow = []\n for j in range(1, lst-1):\n newrow.append(lst[i][j])\n tinyglider.append(newrow) \n count = 0\n while (count <= int(numgenerations)):\n print(\"Generation: \", count)\n length = readlines(inFile) \n for i in range(1, lst-1):\n for j in range(1, lst[0]-1):\n if lst[i][j] == 0:\n print(\".\", end = \" \") \n \n \n \n \n \n \n \n \n\n \n\n \ndef nextGen(glider):\n \" \" \" Function computes a new grid given the initial grid called glider based on the rules of the Game of Life which determine whether a particular position in a specific row and column will contain a 0 or 1 based on whether its neighboring positions contain a 0 or 1 as well \" \" \"\n gen_new = [[0 for col in glider [0]]for row in glider]\n p = len(glider)\n for l in range(1, p-1):\n q = len(glider[l])\n for m in range(1, q-1):\n initial = []\n initial.append(glider[l][m+1])\n initial.append(glider[l+1][m])\n initial.append(glider[l-1][m+1])\n initial.append(glider[l+1][m-1])\n initial.append(glider[l+1][m+1])\n initial.append(glider[l-1][m-1])\n initial.append(glider[l][m-1])\n initial.append(glider[l-1][m])\n total_value = sum(initial)\n if glider[l][m] == 0:\n if total_value == 3:\n gen_new[l][m] = 1\n elif total_value <= 1:\n gen_new[l][m] = 0\n elif total_value >= 4:\n gen_new[l][m] = 0\n elif total_value <= 2:\n gen_new[l][m] = 0\n\n if glider[l][m] == 1:\n if total_value == 3:\n gen_new[l][m] = 1\n elif total_value >= 4:\n gen_new[l][m] = 0\n elif total_value <= 1:\n gen_new[l][m] = 0\n elif total_value == 2:\n gen_new[l][m] = 1\n return gen_new \n","sub_path":"GameOfLife2.py","file_name":"GameOfLife2.py","file_ext":"py","file_size_in_byte":2981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"4017257","text":"import numpy as np\n\nimport tensorflow as tf\nfrom tensorflow import keras as K\n\nfrom tensorflow.keras.layers import Conv2D, Flatten, Dense, Add, Input, ZeroPadding2D, MaxPooling2D, Dropout, BatchNormalization, Concatenate, ReLU, DepthwiseConv2D\nfrom tensorflow.keras.models import Model\n\ndef AlexNet():\n input = Input(shape=(227, 227, 3))\n\n x = input\n\n x = Conv2D(96, (11, 11), strides=(4, 4), padding=\"valid\", activation=\"relu\", name=\"conv_1\")(x)\n x = MaxPooling2D((2, 2), strides=(2, 2), name=\"pool_1\")(x)\n\n x = Conv2D(256, (11, 11), padding=\"valid\", activation=\"relu\", name=\"conv_2\")(x)\n x = MaxPooling2D((2, 2), strides=(2, 2), name=\"pool_2\")(x)\n\n x = Conv2D(384, (3, 3), padding=\"valid\", activation=\"relu\", name=\"conv_3\")(x)\n\n x = Conv2D(384, (3, 3), padding=\"valid\", activation=\"relu\", name=\"conv_4\")(x)\n\n x = Conv2D(256, (3, 3), padding=\"valid\", activation=\"relu\", name=\"conv_5\")(x)\n x = MaxPooling2D((2, 2), strides=(2, 2), name=\"pool_5\")(x)\n\n x = Flatten()(x)\n\n x = Dense(4096, activation=\"relu\", name=\"dense_1\")(x)\n x = Dropout(0.4)(x)\n\n x = Dense(4096, activation=\"relu\", name=\"dense_2\")(x)\n x = Dropout(0.4)(x)\n\n x = Dense(1000, activation=\"relu\", name=\"dense_3\")(x)\n\n x = Dense(1, activation=\"sigmoid\", name=\"output\")(x)\n\n model = Model(input, x)\n\n return model\n","sub_path":"models/alexnet.py","file_name":"alexnet.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"120658034","text":"class Cat:\n name = \"\"\n age = 0\n registered = False\n\n def __init__(self, input_n, input_age):\n self.name = input_n\n self.age = input_age\n\n if input_age > 2:\n self.registered = True\n\n def meow(self, number_times):\n for m in range (number_times):\n print(\"Meow\")\n\n def meow(self, number_time, phrase=\"\"):\n for m in range (number_time):\n print(\"Meow\" + phrase)\n\nc1 = Cat (\"Jack\", 2)\nc2 = Cat (\"Samantha\", 9)\n\nprint (\"Cat c1 registration is \" + str(c1.registered))\nprint(\"Cat c2 registration is \" + str(c2.registered))\n\nc1.meow(5, \" Test\")","sub_path":"Day 10/cat.py","file_name":"cat.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"171892546","text":"import requests\nimport json\nimport csv\n\nFPL_URL = \"https://fantasy.premierleague.com/drf/\"\nCURRENT_GAMEWEEK = 23\n\n# Daniel, Jayden, James\nPLAYER_NAMES = [\"Gameweek\", \"Daniel\", \"Jayden\", \"James\", \"Crissie\"]\nPLAYER_IDS = [2085875, 294233, 101090, 2843275]\n\ndef getDataForGameweek(player_id, gameweek):\n r = requests.get(FPL_URL + \"entry/\" + str(player_id) + \"/event/\" + str(gameweek) + \"/picks\")\n jsonResponse = r.json()\n\n data = []\n data.append(jsonResponse[\"entry_history\"][\"points\"])\n data.append(jsonResponse[\"entry_history\"][\"total_points\"])\n data.append(jsonResponse[\"entry_history\"][\"points_on_bench\"])\n\n return data\n\ndef getDataObjectForSeason(player_id):\n data_for_player = []\n for i in range(1, CURRENT_GAMEWEEK):\n data_for_player.append(getDataForGameweek(player_id, i))\n return data_for_player\n\ndef getData(data_object, index):\n pointsList = []\n for player_index in range(0, PLAYER_IDS.len()):\n temp = []\n for i in range(0, CURRENT_GAMEWEEK):\n temp.append(data_object[player_index][i][index])\n pointsList.append(temp)\n \n return pointsList\n\ndef getGameweekPoints(data_object):\n return getData(data_object, 0)\n\ndef getCumulativeGameweekPoints(data_object):\n return getData(data_object, 1)\n\ndef getBenchGameweekPoints(data_object):\n return getData(data_object, 2)\n\ndef getCombinedGameweekAndBenchPoints(data_object):\n gameweek_points = getGameweekPoints(data_object)\n bench_points = getBenchGameweekPoints(data_object)\n\n pointsList = []\n for player_index in range(0, PLAYER_IDS.len()):\n temp = []\n for i in range(0, CURRENT_GAMEWEEK):\n temp.append(gameweek_points[player_index][i] + bench_points[player_index][i])\n pointsList.append(temp)\n \n return pointsList\n\ndef transposeData(gwpoints_allplayers):\n gw_points = []\n gw_points.append(PLAYER_NAMES)\n for gw in range(0, CURRENT_GAMEWEEK):\n temp_list = []\n for player in range(0, PLAYER_IDS.len() + 1):\n if (player == 0):\n temp_list.append(gw + 1)\n else:\n temp_list.append(gwpoints_allplayers[player - 1][gw])\n gw_points.append(temp_list)\n return gw_points\n\n# Main Script\ndata_object = []\n\nprint(\"Scraping data\")\n\nfor player_id in PLAYER_IDS:\n temp = []\n for i in range(0, CURRENT_GAMEWEEK):\n temp.append(getDataForGameweek(player_id, i+1))\n pob_cumulative = 0\n data_object.append(temp)\n print(\"Finished: \" + str(player_id))\n\nprint(\"Scraped all data\")\n\nwith open(\"data/gameweek_points.csv\", \"w\") as output:\n writer = csv.writer(output, lineterminator='\\n')\n writer.writerows(transposeData(getGameweekPoints(data_object)))\n\nwith open(\"data/gameweek_cumulative_points.csv\", \"w\") as output:\n writer = csv.writer(output, lineterminator='\\n')\n writer.writerows(transposeData(getCumulativeGameweekPoints(data_object)))\n\nwith open(\"data/gameweek_bench_points.csv\", \"w\") as output:\n writer = csv.writer(output, lineterminator='\\n')\n writer.writerows(transposeData(getBenchGameweekPoints(data_object)))\n\nwith open(\"data/gameweek_combined_points.csv\", \"w\") as output:\n writer = csv.writer(output, lineterminator='\\n')\n writer.writerows(transposeData(getCombinedGameweekAndBenchPoints(data_object)))\n\nprint(\"Printed to file\")\n","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":3345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"214703203","text":"from contextlib import suppress\nfrom functools import wraps\nfrom http.client import IncompleteRead\nimport json\nimport logging\nfrom multiprocessing import Pool\nfrom pathlib import Path\nimport signal\nfrom ssl import SSLError\nfrom typing import (\n Dict, List, Tuple, Any, Callable, Iterator, Iterable, TypeVar, cast\n)\n\nimport pandas as pd\nimport requests\n\n\nLOGGER = logging.getLogger(__name__)\nFunction = TypeVar('Function', bound=Callable[..., Any])\n\nNULL_PATH = Path('/dev/null')\nLANGUAGES_FILENAME = 'languages.json'\nCHUNK_SIZE = 1024\nTIMEOUT = 30\n\n\nclass File:\n \"\"\"Cache files.\"\"\"\n COMPRESSED_DATASET = '01_repositories_dataset.tar.gz'\n DATASET = '02_repositories_dataset.csv'\n SHRUNK_DATASET = '03_shrunk_repositories_dataset.csv'\n ALTERED_DATASET = '04_altered_repositories_dataset.csv'\n\n SELECTED_REPOSITORIES = '05_selected_repositories.csv'\n PREPARED_REPOSITORIES = '06_prepare_repositories_to_download.csv'\n DOWNLOADED_REPOSITORIES = '07_downloaded_repositories.csv'\n\n AVAILABLE_FILES = '08_available_files.csv'\n FILES_SPLIT_BY_USAGE = '09_files_split_by_usage.csv'\n EXTRACTED_FILES = '10_extracted_files.csv'\n\n\nclass Config:\n \"\"\"Runtime configuration.\"\"\"\n nb_train_files_per_language = 0\n nb_valid_files_per_language = 0\n nb_test_files_per_language = 0\n nb_repositories_per_language = 0\n cache_dir = ''\n\n max_files_per_repository_per_language = 1000\n bypass_cache = False\n languages: Dict[str, List[str]] = {}\n step = 100\n repositories_dir = NULL_PATH\n extracted_files_dir = NULL_PATH\n\n @classmethod\n def setup(\n cls,\n cache_dir: str,\n nb_repositories: int,\n nb_train: int,\n nb_valid: int,\n nb_test: int,\n ) -> None:\n \"\"\"Set configuration.\"\"\"\n cls.nb_train_files_per_language = nb_train\n cls.nb_valid_files_per_language = nb_valid\n cls.nb_test_files_per_language = nb_test\n cls.nb_repositories_per_language = nb_repositories\n cls.cache_dir = cache_dir\n cls.repositories_dir = absolute('repositories')\n cls.extracted_files_dir = absolute('files')\n\n Path(cls.cache_dir).mkdir(exist_ok=True)\n Path(cls.repositories_dir).mkdir(exist_ok=True)\n Path(cls.extracted_files_dir).mkdir(exist_ok=True)\n\n root_path = Path(__file__).parent\n languages_path = root_path.joinpath('data', LANGUAGES_FILENAME)\n with languages_path.open() as languages_file:\n cls.languages = json.load(languages_file)\n\n\ndef absolute(*path_parts: str) -> Path:\n \"\"\"Create an absolute path.\"\"\"\n return Path(Config.cache_dir, *path_parts).absolute()\n\n\ndef cached(location: str) -> Callable[[Function], Function]:\n \"\"\"Decorator: run a function only if the cache file doesn't exist.\"\"\"\n\n def wrapper(func: Function) -> Function:\n\n @wraps(func)\n def wrapped(*args: Any, **kw: Any) -> Any:\n\n if not Config.cache_dir:\n raise RuntimeError('Cache directory not set')\n\n path = absolute(location)\n if Config.bypass_cache:\n _remove_from_cache(path)\n\n if path.exists():\n LOGGER.info('Found in the cache: %s', path)\n return\n\n Config.bypass_cache = True\n try:\n result = func(*args, **kw)\n LOGGER.info('Created cache file: %s', path)\n return result\n except (Exception, KeyboardInterrupt):\n _remove_from_cache(path)\n raise\n\n return cast(Function, wrapped)\n\n return wrapper\n\n\ndef requires(location: str) -> Callable[[Function], Function]:\n \"\"\"Decorator: run a function only if the cache file doesn't exist.\"\"\"\n\n def wrapper(func: Function) -> Function:\n\n @wraps(func)\n def wrapped(*args: Any, **kw: Any) -> Any:\n\n path = absolute(location)\n if not path.exists():\n LOGGER.error('Cache file missing: %s', path)\n raise RuntimeError(f'Requires cache file {path}')\n\n LOGGER.info('Found in the cache: %s', path)\n result = func(*args, **kw)\n return result\n\n return cast(Function, wrapped)\n\n return wrapper\n\n\ndef _remove_from_cache(path: Path) -> None:\n if path.is_file():\n path.unlink()\n LOGGER.info('Removed cache file: %s', path)\n\n\ndef download_file(url: str, destination: Path) -> Tuple[bool, int]:\n \"\"\"Download a file.\"\"\"\n\n response = requests.get(url, stream=True, timeout=TIMEOUT)\n if not response.ok:\n LOGGER.warning('Cannot download %s: %s', url, response.status_code)\n return False, response.status_code\n\n try:\n with destination.open('wb') as repo_file:\n for chunk in response.iter_content(chunk_size=CHUNK_SIZE):\n repo_file.write(chunk)\n except (IncompleteRead, SSLError) as error:\n LOGGER.warning('Download cancelled %s: %s', url, error)\n _remove_if_possible(destination)\n return False, -2\n except requests.RequestException as error:\n LOGGER.warning('Download failed %s: %s', url, error)\n _remove_if_possible(destination)\n return False, -1\n except (Exception, KeyboardInterrupt):\n _remove_if_possible(destination)\n raise\n\n return True, response.status_code\n\n\ndef _remove_if_possible(path: Path) -> None:\n with suppress(IOError):\n path.unlink()\n\n\ndef load_csv(filename: str) -> pd.DataFrame:\n \"\"\"Load a CSV file.\"\"\"\n\n fullname = absolute(filename)\n return pd.read_csv(fullname)\n\n\ndef save_csv(df: pd.DataFrame, filename: str) -> None:\n \"\"\"Save a DataFrame to a CSV file.\"\"\"\n\n fullname = absolute(filename)\n df.to_csv(fullname, index=False)\n\n\ndef pool_imap(\n method: Function,\n items: Iterable[Any],\n *method_args: Any,\n **method_kw: Any,\n) -> Iterator[Any]:\n \"\"\"Run a function with multiprocessing.\"\"\"\n\n iterable = ((method, item, method_args, method_kw) for item in items)\n with Pool(initializer=_initializer) as pool:\n for result in pool.imap(_apply, iterable):\n yield result\n\n\ndef _apply(\n composite: Tuple[Function, Any, Tuple[Any, ...], Dict[str, Any]]\n) -> Any:\n \"\"\"Generic function wrapper\"\"\"\n method, item, other_args, keywords = composite\n return method(item, *other_args, **keywords)\n\n\ndef _initializer() -> None:\n signal.signal(signal.SIGINT, signal.SIG_IGN)\n\n\ndef backup(filename: str) -> None:\n \"\"\"Create a backup of a given file\"\"\"\n\n current_path = absolute(filename)\n backup_path = absolute(f'{filename}.bkp')\n\n with suppress(IOError):\n backup_path.unlink()\n\n current_path.replace(backup_path)\n LOGGER.info('Backup: %s to %s', current_path, backup_path)\n","sub_path":"guesslangtools/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":6770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"333584179","text":"import logging\n\ndef setup_custom_logger(handle_name, filename, level):\n # logging.basicConfig(filename=filename, encoding='utf-8', level=level, filemode=\"w\")\n formatter = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(module)s - %(message)s')\n handler = logging.FileHandler('latest_logs.log', mode=\"w\")\n logging.StreamHandler(stream=None)\n handler.setFormatter(formatter)\n\n logger = logging.getLogger(handle_name)\n logger.setLevel(level)\n logger.addHandler(handler)\n logger.propagate = False\n return logger","sub_path":"log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"339585458","text":"import logging\r\n\r\nfrom custom_components.doorman.yale.device import Device\r\n\r\nclass Door(Device):\r\n \"\"\"Representation of a Yale Doorman lock.\"\"\"\r\n\r\n STATE_ENUM = {\r\n \"1816\": \"device_status.lock\", # Locked after a failed lock\r\n \"1815\": \"device_status.unlock\", # Failed to lock\r\n \"1807\": \"device_status.lock\", # Auto-relocked\r\n \"1801\": \"device_status.unlock\", # Unlock from inside\r\n \"1802\": \"device_status.unlock\", # Unlock from outside, token or keypad,\r\n }\r\n\r\n NON_LOCK_EVENT = {\"1602\": \"device_status.lock\"} # Periodic test\r\n\r\n LOCK_STATE = \"device_status.lock\"\r\n UNLOCK_STATE = \"device_status.unlock\"\r\n FAILED_STATE = \"failed\"\r\n\r\n def __init__(self, yale_hub, device_id, name, area, zone):\r\n \"\"\"Initialize the lock.\"\"\"\r\n\r\n super().__init__(\r\n yale_hub=yale_hub,\r\n device_id=device_id,\r\n name=name,\r\n area=area,\r\n zone=zone)\r\n\r\n self._LOGGER = logging.getLogger(__name__)\r\n self.state = Door.FAILED_STATE\r\n self.report_ids = []\r\n\r\n def update_state(self):\r\n data = self.yale_hub.get_state(self.device_id)\r\n state = data.get(\"status_open\")[0]\r\n self.state = state\r\n\r\n @property\r\n def is_locked(self):\r\n \"\"\"Return True if the lock is currently locked, else False.\"\"\"\r\n return self.state == Door.LOCK_STATE\r\n\r\n def lock(self):\r\n \"\"\"Lock the device.\"\"\"\r\n if self.is_locked is False:\r\n self.yale_hub.yale_api.lock(self.area, self.zone)\r\n\r\n def unlock(self, pincode):\r\n \"\"\"Unlock the device.\"\"\"\r\n if self.is_locked is True:\r\n self.yale_hub.yale_api.unlock(self.area, self.zone, pincode)\r\n","sub_path":"custom_components/doorman/yale/door.py","file_name":"door.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"1926112","text":"#自然数Nをコマンドライン引数などの手段で受け取り,入力のファイルを行単位でN分割せよ.同様の処理をsplitコマンドで実現せよ.\n\nN = input()\nN = int(N) \npath = r\"\\Users\\Koya\\Documents\\Lab\\100knock2019\\Eguchi\\chapter02\"\n\nwith open(path + \"\\hightemp.txt\", \"r\",encoding=\"utf-8\") as file:\n readfile = file.read()\n file.seek(0)\n listfile = readfile.split(\"\\n\")\n file.seek(0)\n filenumber = len(file.readlines())\n\ncount = 0\nans = [[0]*100]*100\n\nlim = int(filenumber / N)\n\nfor i in range(N):\n for j in range(lim):\n ans[i][j] = listfile[count]\n count+=1\n\n\n\nfor i in range(N):\n print(\"【分割第%d】\" %(i+1))\n for j in range(lim):\n print(ans[i][j])","sub_path":"Eguchi/chapter02/knock16.py","file_name":"knock16.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"455370691","text":"# Import required modules\nimport pandas as pd\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom keras import Sequential\nfrom keras.layers import Dense\n\n# Import training and testing data\ntraining = pd.read_csv('../../Datasets/train.csv')\ntesting = pd.read_csv('../../Datasets/test.csv')\n\n\n# Obtaining feature and target values of training data\ntrain_features = []\nfor i in range(300):\n\ttrain_features.append(str(i))\nxtrain = training[train_features]\nytrain = training['target']\nsc = StandardScaler()\nxtrain = sc.fit_transform(xtrain)\n\n# Obtaining feature values of testing data\ntest_features = []\nfor i in range(300):\n\ttest_features.append(str(i))\nxtest = testing[test_features]\nsc = StandardScaler()\nxtest = sc.fit_transform(xtest)\n\n# Define ANN Model\nclassifier = Sequential()\nclassifier.add(Dense(4, activation = 'relu', kernel_initializer = 'random_normal', input_dim = 300))\nclassifier.add(Dense(1, activation = 'sigmoid', kernel_initializer = 'random_normal'))\n\n# Compile the ANN Model\nclassifier.compile(optimizer = 'adam',loss = 'binary_crossentropy', metrics = ['accuracy'])\n\n# Fit the ANN Model to test data\nclassifier.fit(xtrain,ytrain, batch_size = 5, epochs = 250)\n\n# Test the model\nytest = classifier.predict(xtest)\nytest = [1 if i > 0.60 else 0 for i in ytest]\n\n# Export result values to a csv file to test on kaggle\nid = []\nfor i in range(250, 20000):\n\tid.append(i)\nresult = {'id': id, 'target': ytest}\nresult = pd.DataFrame(result)\nresult.to_csv(\"result.csv\", index = False)\n","sub_path":"Classification Models/9/9.py","file_name":"9.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"74633672","text":"def summary():\n try:\n with open('numbers_5.txt', 'w+') as f_obj:\n line = input('Введите цифры через пробел \\n')\n f_obj.writelines(line)\n numb = line.split()\n\n print(f'Сумма введённых вами сисле равна {sum(map(int, numb))}')\n except IOError:\n print('Ошибка в файле')\n except ValueError:\n print('Неправильно набран номер. Ошибка ввода-вывода')\nsummary()\n","sub_path":"lesson_5/lesson_5_5.py","file_name":"lesson_5_5.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"636403297","text":"import numpy as np\nfrom lsst.sims.maf.stackers import BaseStacker\nfrom lsst.sims.maf.stackers import wrapRA, wrapDec\n\nclass SingleFieldDitherStacker(BaseStacker):\n \"\"\"\n Repurpose LSST to only look at one field - 'dither' all pointings to single RA/Dec value.\n \"\"\"\n def __init__(self, fixedRA=0.0, fixedDec=0.0):\n \"\"\"\n fixedRA and fixedDec are the RA/Dec values for the new columns (in radians).\n \"\"\"\n self.fixedRA = fixedRA\n self.fixedDec = fixedDec\n # Required lines:\n # List of the names of the columns generated by the Stacker.\n self.colsAdded = ['fixedRA', 'fixedDec']\n # List of the names of the columns required from the database (to generate the Stacker columns).\n self.colsReq = []\n # Optional: provide a list of units for the columns defined in colsAdded.\n self.units = ['rad', 'rad']\n\n def run(self, simData):\n # Add new columns defined by self.colsAdded to simData\n # (this is where we'll put our new data)\n simData = self._addStackers(simData)\n # Calculate the values for your columns\n simData['fixedRA'] = self.fixedRA\n simData['fixedDec'] = self.fixedDec\n # Return the updated simData array\n return simData\n\n\nclass YearlyDitherStacker(BaseStacker):\n \"\"\"\n Add a dither of half the FOV depending on the year of the survey.\n \"\"\"\n def __init__(self, expMJDCol='expMJD', raCol='fieldRA', decCol='fieldDec'):\n # Names of columns we want to add.\n self.colsAdded = ['yearlyDitherRA', 'yearlyDitherDec']\n # Names of columns we need from database.\n self.colsReq = [expMJDCol, raCol, decCol]\n # List of units for our new columns.\n self.units = ['rad', 'rad']\n # Set our dither offset.\n self.ditherOffset = 1.75/180.*np.pi\n # And save the column names.\n self.expMJDCol = expMJDCol\n self.raCol = raCol\n self.decCol = decCol\n \n def run(self, simData):\n # Add new columns to simData.\n simData = self._addStackers(simData)\n # What 'year' is each visit in?\n year = np.floor((simData[self.expMJDCol] - simData[self.expMJDCol][0]) / 365.25)\n # Define dither based on year. \n ditherRA = np.zeros(len(simData[self.raCol]))\n ditherDec = np.zeros(len(simData[self.decCol]))\n # In y1, y3, y5, y6, y8 & y10 ra dither = 0.\n # In y2 & y7, ra dither = +ditherOffset\n # In y4 & y9, ra dither = -ditherOffset \n condition = ((year == 2) | (year == 7))\n ditherRA[condition] = self.ditherOffset\n condition = ((year == 4) | (year == 9))\n ditherRA[condition] = -1.*self.ditherOffset\n simData['yearlyDitherRA'] = wrapRA(simData[self.raCol] + ditherRA)\n # In y1, y2, y4, y6, y7 & y9, dec dither = 0\n # In y3 & y8, dec dither = -ditherOffset\n # In y5 & y10, dec dither = ditherOffset\n condition = ((year == 3) | (year == 8))\n ditherDec[condition] = -1.*self.ditherOffset\n condition = ((year == 5) | (year == 10))\n ditherDec[condition] = self.ditherOffset\n simData['yearlyDitherDec'] = wrapDec(simData[self.decCol] + ditherDec)\n return simData\n \n\n","sub_path":"examples/workshop/exampleNewStacker.py","file_name":"exampleNewStacker.py","file_ext":"py","file_size_in_byte":3306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"320169132","text":"#!/usr/bin/python3\n\nimport os\nimport shutil\nimport subprocess\nimport json\n\n\nRELEASE_DIR = 'verible_release'\nRELEASE_INFO_FILE = 'verible_release_info.json'\nGET_RELEASES_CMD = 'curl -s https://api.github.com/repos/google/verible/releases/latest | jq -r \".assets[].name\"'\nGET_TAG_CMD = 'curl -s https://api.github.com/repos/google/verible/releases/latest | grep -oP \\'\"tag_name\": \"\\K(.*)(?=\")\\''\n\n\nreleases = subprocess.check_output(\n GET_RELEASES_CMD, shell=True).decode('utf8').strip().split('\\n')\ntag = subprocess.check_output(GET_TAG_CMD, shell=True).decode('utf8').strip()\nif os.path.exists(RELEASE_DIR):\n shutil.rmtree(RELEASE_DIR)\nos.mkdir(RELEASE_DIR)\nrelease_subdirs = [item[8 + len(tag) + 1:-7] for item in releases]\nfor index, item in enumerate(releases):\n download_url = 'https://github.com/google/verible/releases/download/' + tag + '/' + item\n item_dir = release_subdirs[index]\n os.mkdir(os.path.join(RELEASE_DIR, item_dir))\n download_command = 'wget -c ' + download_url + \\\n ' -O - | tar -xz -C ' + os.path.join(RELEASE_DIR, item_dir) + ' '\n result = subprocess.check_output(\n download_command, shell=True).decode('utf8').strip()\n print(download_command)\n\nrelease_info = {\n 'tag': tag,\n 'release_subdirs': release_subdirs,\n}\n\nwith open(RELEASE_INFO_FILE, 'w') as output_file:\n output_file.write(json.dumps(release_info, indent=4))\n","sub_path":"scripts/update_dependencies.py","file_name":"update_dependencies.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"114984149","text":"# IEEE 802.1X tests\n# Copyright (c) 2013-2015, Jouni Malinen \n#\n# This software may be distributed under the terms of the BSD license.\n# See README for more details.\n\nimport binascii\nimport hmac\nimport logging\nimport time\n\nimport hostapd\nimport hwsim_utils\n\nlogger = logging.getLogger()\n\ndef test_ieee8021x_wep104(dev, apdev):\n \"\"\"IEEE 802.1X connection using dynamic WEP104\"\"\"\n params = hostapd.radius_params()\n params[\"ssid\"] = \"ieee8021x-wep\"\n params[\"ieee8021x\"] = \"1\"\n params[\"wep_key_len_broadcast\"] = \"13\"\n params[\"wep_key_len_unicast\"] = \"13\"\n hapd = hostapd.add_ap(apdev[0]['ifname'], params)\n\n dev[0].connect(\"ieee8021x-wep\", key_mgmt=\"IEEE8021X\", eap=\"PSK\",\n identity=\"psk.user@example.com\",\n password_hex=\"0123456789abcdef0123456789abcdef\",\n scan_freq=\"2412\")\n hwsim_utils.test_connectivity(dev[0], hapd)\n\ndef test_ieee8021x_wep40(dev, apdev):\n \"\"\"IEEE 802.1X connection using dynamic WEP40\"\"\"\n params = hostapd.radius_params()\n params[\"ssid\"] = \"ieee8021x-wep\"\n params[\"ieee8021x\"] = \"1\"\n params[\"wep_key_len_broadcast\"] = \"5\"\n params[\"wep_key_len_unicast\"] = \"5\"\n hapd = hostapd.add_ap(apdev[0]['ifname'], params)\n\n dev[0].connect(\"ieee8021x-wep\", key_mgmt=\"IEEE8021X\", eap=\"PSK\",\n identity=\"psk.user@example.com\",\n password_hex=\"0123456789abcdef0123456789abcdef\",\n scan_freq=\"2412\")\n hwsim_utils.test_connectivity(dev[0], hapd)\n\ndef test_ieee8021x_open(dev, apdev):\n \"\"\"IEEE 802.1X connection using open network\"\"\"\n params = hostapd.radius_params()\n params[\"ssid\"] = \"ieee8021x-open\"\n params[\"ieee8021x\"] = \"1\"\n hapd = hostapd.add_ap(apdev[0]['ifname'], params)\n\n id = dev[0].connect(\"ieee8021x-open\", key_mgmt=\"IEEE8021X\", eapol_flags=\"0\",\n eap=\"PSK\", identity=\"psk.user@example.com\",\n password_hex=\"0123456789abcdef0123456789abcdef\",\n scan_freq=\"2412\")\n hwsim_utils.test_connectivity(dev[0], hapd)\n\n logger.info(\"Test EAPOL-Logoff\")\n dev[0].request(\"LOGOFF\")\n ev = dev[0].wait_event([\"CTRL-EVENT-DISCONNECTED\"])\n if ev is None:\n raise Exception(\"Did not get disconnected\")\n if \"reason=23\" not in ev:\n raise Exception(\"Unexpected disconnection reason\")\n\n dev[0].request(\"LOGON\")\n dev[0].connect_network(id)\n hwsim_utils.test_connectivity(dev[0], hapd)\n\ndef test_ieee8021x_static_wep40(dev, apdev):\n \"\"\"IEEE 802.1X connection using static WEP40\"\"\"\n params = hostapd.radius_params()\n params[\"ssid\"] = \"ieee8021x-wep\"\n params[\"ieee8021x\"] = \"1\"\n params[\"wep_key0\"] = '\"hello\"'\n hapd = hostapd.add_ap(apdev[0]['ifname'], params)\n\n dev[0].connect(\"ieee8021x-wep\", key_mgmt=\"IEEE8021X\", eap=\"PSK\",\n identity=\"psk.user@example.com\",\n password_hex=\"0123456789abcdef0123456789abcdef\",\n wep_key0='\"hello\"', eapol_flags=\"0\",\n scan_freq=\"2412\")\n hwsim_utils.test_connectivity(dev[0], hapd)\n\ndef test_ieee8021x_proto(dev, apdev):\n \"\"\"IEEE 802.1X and EAPOL supplicant protocol testing\"\"\"\n params = hostapd.radius_params()\n params[\"ssid\"] = \"ieee8021x-open\"\n params[\"ieee8021x\"] = \"1\"\n hapd = hostapd.add_ap(apdev[0]['ifname'], params)\n bssid = apdev[0]['bssid']\n\n dev[1].request(\"SET ext_eapol_frame_io 1\")\n dev[1].connect(\"ieee8021x-open\", key_mgmt=\"IEEE8021X\", eapol_flags=\"0\",\n eap=\"PSK\", identity=\"psk.user@example.com\",\n password_hex=\"0123456789abcdef0123456789abcdef\",\n scan_freq=\"2412\", wait_connect=False)\n id = dev[0].connect(\"ieee8021x-open\", key_mgmt=\"IEEE8021X\", eapol_flags=\"0\",\n eap=\"PSK\", identity=\"psk.user@example.com\",\n password_hex=\"0123456789abcdef0123456789abcdef\",\n scan_freq=\"2412\")\n ev = dev[1].wait_event([\"CTRL-EVENT-EAP-STARTED\"], timeout=5)\n\n start = dev[0].get_mib()\n\n tests = [ \"11\",\n \"11223344\",\n \"020000050a93000501\",\n \"020300050a93000501\",\n \"0203002c0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\",\n \"0203002c0100000000000000000000000000000000000000000000000000000000000000000000000000000000000000\",\n \"0203002c0100050000000000000000000000000000000000000000000000000000000000000000000000000000000000\",\n \"02aa00050a93000501\" ]\n for frame in tests:\n res = dev[0].request(\"EAPOL_RX \" + bssid + \" \" + frame)\n if \"OK\" not in res:\n raise Exception(\"EAPOL_RX to wpa_supplicant failed\")\n dev[1].request(\"EAPOL_RX \" + bssid + \" \" + frame)\n\n stop = dev[0].get_mib()\n\n logger.info(\"MIB before test frames: \" + str(start))\n logger.info(\"MIB after test frames: \" + str(stop))\n\n vals = [ 'dot1xSuppInvalidEapolFramesRx',\n 'dot1xSuppEapLengthErrorFramesRx' ]\n for val in vals:\n if int(stop[val]) <= int(start[val]):\n raise Exception(val + \" did not increase\")\n\ndef test_ieee8021x_eapol_start(dev, apdev):\n \"\"\"IEEE 802.1X and EAPOL-Start retransmissions\"\"\"\n params = hostapd.radius_params()\n params[\"ssid\"] = \"ieee8021x-open\"\n params[\"ieee8021x\"] = \"1\"\n hapd = hostapd.add_ap(apdev[0]['ifname'], params)\n bssid = apdev[0]['bssid']\n\n hapd.set(\"ext_eapol_frame_io\", \"1\")\n try:\n dev[0].request(\"SET EAPOL::startPeriod 1\")\n dev[0].request(\"SET EAPOL::maxStart 1\")\n dev[0].connect(\"ieee8021x-open\", key_mgmt=\"IEEE8021X\", eapol_flags=\"0\",\n eap=\"PSK\", identity=\"psk.user@example.com\",\n password_hex=\"0123456789abcdef0123456789abcdef\",\n scan_freq=\"2412\", wait_connect=False)\n held = False\n for i in range(30):\n pae = dev[0].get_status_field('Supplicant PAE state')\n if pae == \"HELD\":\n held = True\n break\n time.sleep(0.25)\n if not held:\n raise Exception(\"PAE state HELD not reached\")\n dev[0].wait_disconnected()\n finally:\n dev[0].request(\"SET EAPOL::startPeriod 30\")\n dev[0].request(\"SET EAPOL::maxStart 3\")\n\ndef test_ieee8021x_held(dev, apdev):\n \"\"\"IEEE 802.1X and HELD state\"\"\"\n params = hostapd.radius_params()\n params[\"ssid\"] = \"ieee8021x-open\"\n params[\"ieee8021x\"] = \"1\"\n hapd = hostapd.add_ap(apdev[0]['ifname'], params)\n bssid = apdev[0]['bssid']\n\n hapd.set(\"ext_eapol_frame_io\", \"1\")\n try:\n dev[0].request(\"SET EAPOL::startPeriod 1\")\n dev[0].request(\"SET EAPOL::maxStart 0\")\n dev[0].request(\"SET EAPOL::heldPeriod 1\")\n dev[0].connect(\"ieee8021x-open\", key_mgmt=\"IEEE8021X\", eapol_flags=\"0\",\n eap=\"PSK\", identity=\"psk.user@example.com\",\n password_hex=\"0123456789abcdef0123456789abcdef\",\n scan_freq=\"2412\", wait_connect=False)\n held = False\n for i in range(30):\n pae = dev[0].get_status_field('Supplicant PAE state')\n if pae == \"HELD\":\n held = True\n break\n time.sleep(0.25)\n if not held:\n raise Exception(\"PAE state HELD not reached\")\n\n hapd.set(\"ext_eapol_frame_io\", \"0\")\n for i in range(30):\n pae = dev[0].get_status_field('Supplicant PAE state')\n if pae != \"HELD\":\n held = False\n break\n time.sleep(0.25)\n if held:\n raise Exception(\"PAE state HELD not left\")\n ev = dev[0].wait_event([ \"CTRL-EVENT-CONNECTED\",\n \"CTRL-EVENT-DISCONNECTED\" ], timeout=10)\n if ev is None:\n raise Exception(\"Connection timed out\")\n if \"CTRL-EVENT-DISCONNECTED\" in ev:\n raise Exception(\"Unexpected disconnection\")\n finally:\n dev[0].request(\"SET EAPOL::startPeriod 30\")\n dev[0].request(\"SET EAPOL::maxStart 3\")\n dev[0].request(\"SET EAPOL::heldPeriod 60\")\n\ndef send_eapol_key(dev, bssid, signkey, frame_start, frame_end):\n zero_sign = \"00000000000000000000000000000000\"\n frame = frame_start + zero_sign + frame_end\n hmac_obj = hmac.new(binascii.unhexlify(signkey))\n hmac_obj.update(binascii.unhexlify(frame))\n sign = hmac_obj.digest()\n frame = frame_start + binascii.hexlify(sign) + frame_end\n dev.request(\"EAPOL_RX \" + bssid + \" \" + frame)\n\ndef test_ieee8021x_eapol_key(dev, apdev):\n \"\"\"IEEE 802.1X connection and EAPOL-Key protocol tests\"\"\"\n params = hostapd.radius_params()\n params[\"ssid\"] = \"ieee8021x-wep\"\n params[\"ieee8021x\"] = \"1\"\n params[\"wep_key_len_broadcast\"] = \"5\"\n params[\"wep_key_len_unicast\"] = \"5\"\n hapd = hostapd.add_ap(apdev[0]['ifname'], params)\n bssid = apdev[0]['bssid']\n\n dev[0].connect(\"ieee8021x-wep\", key_mgmt=\"IEEE8021X\", eap=\"VENDOR-TEST\",\n identity=\"vendor-test\", scan_freq=\"2412\")\n\n # Hardcoded MSK from VENDOR-TEST\n encrkey = \"1111111111111111111111111111111111111111111111111111111111111111\"\n signkey = \"2222222222222222222222222222222222222222222222222222222222222222\"\n\n # EAPOL-Key replay counter does not increase\n send_eapol_key(dev[0], bssid, signkey,\n \"02030031\" + \"010005\" + \"0000000000000000\" + \"056c22d109f29d4d9fb9b9ccbad33283\" + \"02\",\n \"1c636a30a4\")\n\n # EAPOL-Key too large Key Length field value\n send_eapol_key(dev[0], bssid, signkey,\n \"02030031\" + \"010021\" + \"ffffffffffffffff\" + \"056c22d109f29d4d9fb9b9ccbad33283\" + \"02\",\n \"1c636a30a4\")\n\n # EAPOL-Key too much key data\n send_eapol_key(dev[0], bssid, signkey,\n \"0203004d\" + \"010005\" + \"ffffffffffffffff\" + \"056c22d109f29d4d9fb9b9ccbad33283\" + \"02\",\n 33*\"ff\")\n\n # EAPOL-Key too little key data\n send_eapol_key(dev[0], bssid, signkey,\n \"02030030\" + \"010005\" + \"ffffffffffffffff\" + \"056c22d109f29d4d9fb9b9ccbad33283\" + \"02\",\n \"1c636a30\")\n\n # EAPOL-Key with no key data and too long WEP key length\n send_eapol_key(dev[0], bssid, signkey,\n \"0203002c\" + \"010020\" + \"ffffffffffffffff\" + \"056c22d109f29d4d9fb9b9ccbad33283\" + \"02\",\n \"\")\n","sub_path":"tests/hwsim/test_ieee8021x.py","file_name":"test_ieee8021x.py","file_ext":"py","file_size_in_byte":10403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"511026432","text":"#!/usr/bin/env python3\nfrom librip.gens import field, gen_random\n\ngoods = [\n {'title': 'Ковер', 'price': 2000, 'color': 'green'},\n {'title': 'Диван для отдыха', 'price': 5300, 'color': 'black'},\n {'title': 'Стелаж', 'price': 7000, 'color': 'white'},\n {'title': 'Вешалка для одежды', 'price': 800, 'color': 'white'}\n]\n\n\ndef print_func(func):\n print(str(list(func))[1:-1])\n\n\nprint_func(field(goods, 'title', 'price'))\nprint_func(gen_random(1, 5, 5))\n\n# Реализация задания 1\n","sub_path":"ex_1.py","file_name":"ex_1.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"181543303","text":"import sys\r\ninput = sys.stdin.readline \r\n\r\nn = int(input())\r\nnums = list(map(int,input().split()))\r\n\r\ndef lower_bound(arr, key):\r\n left, right = 0,len(arr)-1\r\n \r\n while (left < right):\r\n mid = left + (right - left) // 2\r\n\r\n if arr[mid] < key:\r\n left = mid+1\r\n else:\r\n right = mid \r\n\r\n return right \r\n\r\nanswer = []\r\nanswer.append(nums[0])\r\n\r\nfor i in range(1,n):\r\n if nums[i] > answer[-1]:\r\n answer.append(nums[i])\r\n else:\r\n idx = lower_bound(answer,nums[i])\r\n answer[idx] = nums[i]\r\n\r\nprint(len(answer))","sub_path":"백준/Gold/12015. 가장 긴 증가하는 부분 수열 2/가장 긴 증가하는 부분 수열 2.py","file_name":"가장 긴 증가하는 부분 수열 2.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"293837237","text":"# -*- coding=UTF-8 -*-\nu\"\"\"Convert phrases between different cases. \"\"\"\n__version__ = u'0.1.1'\n\nASCII_UPPERCASE = u'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\nSEPERATORS = u'-_ '\n\n\ndef snake(v, seperator=u'_'):\n u\"\"\"Convert phrases case to snake case.\n\n Args:\n v (str): Phrases to convert.\n seperator (str, optional): phrase seperator. Defaults to '_'.\n\n Returns:\n str: Converted Phrases.\n\n >>> snake('space case')\n 'space_case'\n >>> snake('snake_case')\n 'snake_case'\n >>> snake('hyphen-case')\n 'hyphen_case'\n >>> snake('camelCase')\n 'camel_case'\n >>> snake('PascalCase')\n 'pascal_case'\n \"\"\"\n ret = u''\n for char in v:\n if char in ASCII_UPPERCASE:\n ret += seperator\n ret += char.lower()\n elif char in SEPERATORS:\n ret += seperator\n else:\n ret += char\n if ret[0] in SEPERATORS:\n ret = ret[1:]\n return ret\n\n\ndef _split(v, delimiters=SEPERATORS):\n ret = []\n pos = 0\n for index, i in enumerate(v + delimiters[0]):\n if i in delimiters:\n if index > pos:\n ret.append(v[pos:index])\n pos = index + 1\n return ret\n\n\ndef pascal(v):\n u\"\"\"Convert text to pascal case.\n\n Args:\n v (str): Phrases to convert.\n\n Returns:\n str: Converted Phrases.\n\n >>> pascal('space case')\n 'SpaceCase'\n >>> pascal('snake_case')\n 'SnakeCase'\n >>> pascal('hyphen-case')\n 'HyphenCase'\n >>> pascal('camelCase')\n 'CamelCase'\n >>> pascal('PascalCase')\n 'PascalCase'\n \"\"\"\n return u''.join(x[0].title() + x[1:] for x in _split(v))\n\n\ndef camel(v):\n u\"\"\"Convert text to camel case.\n\n Args:\n v (str): Phrases to convert.\n\n Returns:\n str: Converted Phrases.\n\n >>> camel('space case')\n 'spaceCase'\n >>> camel('snake_case')\n 'snakeCase'\n >>> camel('hyphen-case')\n 'hyphenCase'\n >>> camel('camelCase')\n 'camelCase'\n >>> camel('PascalCase')\n 'pascalCase'\n \"\"\"\n\n ret = pascal(v)\n if ret:\n ret = ret[0].lower() + ret[1:]\n return ret\n\n\ndef space(v):\n u\"\"\"Shortcut for snake(v, seperator=' ')\n\n Args:\n v (str): Phrases to convert.\n\n Returns:\n str: Converted Phrases.\n\n >>> space('space case')\n 'space case'\n >>> space('snake_case')\n 'snake case'\n >>> space('hyphen-case')\n 'hyphen case'\n >>> space('camelCase')\n 'camel case'\n >>> space('PascalCase')\n 'pascal case'\n \"\"\"\n return snake(v, seperator=u' ')\n\n\ndef hyphen(v):\n u\"\"\"Shortcut for snake(v, seperator='-')\n\n Args:\n v (str): Phrases to convert.\n\n Returns:\n str: Converted Phrases.\n\n >>> hyphen('space case')\n 'space-case'\n >>> hyphen('snake_case')\n 'snake-case'\n >>> hyphen('hyphen-case')\n 'hyphen-case'\n >>> hyphen('camelCase')\n 'camel-case'\n >>> hyphen('PascalCase')\n 'pascal-case'\n \"\"\"\n return snake(v, seperator=u'-')\n","sub_path":"phrases_case/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"25227062","text":"# -------------------------------------------------------------------------------\n# Copyright IBM Corp. 2016\n# \n# Licensed under the Apache License, Version 2.0 (the 'License');\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an 'AS IS' BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# -------------------------------------------------------------------------------\n\nfrom .mpld3ChartDisplay import Mpld3ChartDisplay\nfrom pyspark.sql import functions as F\n \nclass PieChartDisplay(Mpld3ChartDisplay):\n def doRenderMpld3(self, handlerId, figure, axes, keyFields, keyFieldValues, keyFieldLabels, valueFields, valueFieldValues):\n agg = self.options.get(\"aggregation\", \"count\")\n displayColName = self.getPieColInfo(agg != \"count\")\n if not displayColName:\n self._addHTML(\"Unable to find a suitable column in the dataframe\")\n return\n\n pand = self.handleUIOptions(displayColName)\n x = pand[\"agg\"].dropna().tolist()\n labels=pand[displayColName].tolist()\n\n # The default startangle is 0. With startangle=90, everything is rotated counter-clockwise by 90 degrees\n axes.pie(x, labels=labels, explode=None, autopct='%1.1f%%', startangle=90)\n\n\n # numerical used as a boolean flag for truth table\n def getPieColInfo(self, numerical):\n # If user selects a column in dialog box, give it to them\n keyFields = self.options.get(\"keyFields\")\n if keyFields is not None:\n return keyFields\n\n schema = self.entity.schema\n default=None\n for field in schema.fields:\n # Ignore unique ids\n if field.name.lower() != 'id' and ( not numerical or isNum(field.dataType.__class__.__name__) ):\n # Find a good column to display in pie ChartDisplay\n default = default or field.name\n count = self.entity.count()\n sample = self.entity.sample(False, (float(200) / count)) if count > 200 else self.entity\n orderedSample = sample.groupBy(field.name).agg(F.count(field.name).alias(\"agg\")).orderBy(F.desc(\"agg\")).select(\"agg\")\n if orderedSample.take(1)[0][\"agg\"] > 10:\n return field.name\n # Otherwise, return first non-id column\n return default\n\n\n # Handle user-defined aggregate functions\n def handleUIOptions(self, displayColName):\n agg = self.options.get(\"aggregation\")\n valFields = self.options.get(\"valueFields\")\n\n if agg == 'COUNT':\n return self.entity.groupBy(displayColName).agg(F.count(displayColName).alias(\"agg\")).toPandas()\n elif agg == 'SUM':\n return self.entity.groupBy(displayColName).agg(F.sum(valFields).alias(\"agg\")).toPandas()\n elif agg == 'AVG':\n return self.entity.groupBy(displayColName).agg(F.avg(valFields).alias(\"agg\")).toPandas()\n elif agg == 'MIN':\n return self.entity.groupBy(displayColName).agg(F.min(valFields).alias(\"agg\")).toPandas()\n elif agg == 'MAX':\n return self.entity.groupBy(displayColName).agg(F.max(valFields).alias(\"agg\")).toPandas()\n elif agg == 'MEAN':\n return self.entity.groupBy(displayColName).agg(F.mean(valFields).alias(\"agg\")).toPandas()\n else:\n return self.entity.groupBy(displayColName).agg(F.count(displayColName).alias(\"agg\")).toPandas()\n\n\n def isNum(type):\n if ( type ==\"LongType\" or type == \"IntegerType\" ):\n return true\n else:\n return false","sub_path":"pixiedust/display/chart/pieChartDisplay.py","file_name":"pieChartDisplay.py","file_ext":"py","file_size_in_byte":3898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"647535294","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport matplotlib\n\nfrom itertools import product\nfrom math import floor\n\nfrom matplotlib.colors import BoundaryNorm\nfrom matplotlib.ticker import MaxNLocator\nfrom scipy.interpolate import griddata\n\nfrom temperations import *\nfrom hearing import Pair\n\nharmonic_major_temperation = map(float, HARMONIC_INTERVALS)\nharmonic_temperation = map(float, CHROMATIC_TEMPERATION_BY_TONAL[DO])\n\nfig = plt.figure()\n\nax1 = fig.add_subplot(111)\n\n\nXNOTES = NOTES13\n\nHARMONICS_COUNT = 19\nHARMONICS = np.arange(HARMONICS_COUNT, dtype=np.float64) + 1.\n\n\n# Интервалы в тональных темперациях\nax1.vlines(\n CHROMATIC_INTERVALS,\n 1, HARMONICS_COUNT,\n colors=[.7, .7, .7]\n)\n\n# Равномерно-темперированные вертикльные линии\nax1.vlines(\n FLAT_TEMPERATION,\n 1, HARMONICS_COUNT,\n colors=[.5, .0, .5], linestyles='-', linewidths=[1.5]\n)\n\n# Гармонично-темперированные вертикльные линии\nax1.vlines(\n [interval_of(nota, DO) for nota in XNOTES],\n 1, HARMONICS_COUNT,\n colors=[0, .4, 1], linestyles='--', linewidths=[2]\n)\n\n\nXS = np.array(sorted(set(np.hstack([\n FLAT_TEMPERATION,\n CHROMATIC_INTERVALS,\n]))))\n\n# Кривые гармоник при увеличении частоты основного тона вдоль октавы\nharmonic_lines = []\n\nfor h in HARMONICS:\n xy = [\n (x, y)\n for x, y in [\n (x, h * x)\n for x in list(XS) + [HARMONICS_COUNT / float(h)]\n ]\n if x <= XS[-1] and y <= HARMONICS_COUNT\n ]\n\n ax1.plot(*zip(*xy), color=[0.1, 0.1, .5])\n\n harmonic_lines.append(xy)\n\n\n# Точки пересечений\ncross_points = sorted(set([\n pair\n for line in harmonic_lines\n for pair in line\n]))\n\n\n# Цвета созвучий\ndef equisonans(y):\n lower = floor(y)\n\n closest_harmonic = min(\n lower, lower + 1,\n key=lambda h: abs(h - y)\n )\n\n fh = closest_harmonic\n\n return Pair(fh, y).equisonans\n\n\nPRECISION_CALC = 200\nPRECISION_PLOT = 200\n\npoints = sorted(set(cross_points + list(product(\n np.linspace(min(XS), max(XS), PRECISION_CALC),\n np.linspace(min(HARMONICS), max(HARMONICS), PRECISION_CALC),\n))))\n\nxs, ys = zip(*points)\n\nzy = {y: equisonans(y) for y in ys}\nzs = [zy[y] for x, y in points]\n\nxi = np.linspace(min(xs), max(xs), PRECISION_PLOT)\nyi = np.linspace(min(ys), max(ys), PRECISION_PLOT)\n\nzi = griddata((xs, ys), zs, (xi[None,:], yi[:,None]), method='cubic')\n\nlevels = MaxNLocator(nbins=100).tick_values(zi.min(), zi.max())\n\ncdict = {\n 'red': (\n (0.0, 0.6, 0.6),\n\n (0.5, 0.0, 0.0),\n\n (0.8, 0.99, 0.99),\n (1.0, 0.99, 0.99),\n ),\n 'green': (\n (0.0, 0.6, 0.6),\n\n (0.5, 0.5, 0.5),\n\n (0.8, 0.99, 0.99),\n (1.0, 0.4, 0.4),\n ),\n 'blue': (\n (0.0, 0.6, 0.6),\n\n (0.5, 0.0, 0.0),\n\n (0.8, 0.99, 0.99),\n (1.0, 0.0, 0.0),\n )\n}\ncmap = matplotlib.colors.LinearSegmentedColormap('my_colormap',cdict,256)\n# cmap = plt.get_cmap('PuOr')\n\nnorm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)\n\nplt.contourf(xi, yi, zi, levels=levels, cmap=cmap)\n\n# plt.colorbar()\n\n\n# Точки пересечений\nax1.scatter(*zip(*cross_points), marker='o', c='b', s=5)\n\n\n# Оси\nxticks = [\n interval_of(nota, DO)\n for nota in XNOTES if nota % 12 in MAJOR_GAMMA\n]\n\nxticklabels = [\n NOTES_NAMES[nota]\n for nota in XNOTES\n if nota % 12 in MAJOR_GAMMA\n]\n\nax1.set_xscale('log')\nax1.set_xbound(min(xticks) / 1.02, max(xticks) * 1.02)\nax1.set_xticks(xticks)\nax1.set_xticklabels(xticklabels)\n\nax1.set_yticks(HARMONICS)\nax1.set_ybound(1 - .3, HARMONICS_COUNT + .3)\n\nax1.axis([1, 2, 1, HARMONICS_COUNT])\nax1.grid(axis='y')\n\nmatplotlib.rcParams['font.size'] = 8.0\n\nfig.set_tight_layout(True)\n\nplt.show()\n","sub_path":"plot_harmony.py","file_name":"plot_harmony.py","file_ext":"py","file_size_in_byte":3916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"246950966","text":"import numpy as np\nimport cv2\nimport glob\n\ncam = cv2.VideoCapture(0)\ncam.set(3,1280)\ncam.set(4,720)\n\n# Get the width and height of the camera image\nret, frame = cam.read()\nh, w = frame.shape[:2]\n\n\nupperLeftCorner = None\nlowerRightCorner = None\n\n# mouse callback function\ndef mouse_click(event,x,y,flags,param):\n global upperLeftCorner\n global lowerRightCorner\n if event == cv2.EVENT_LBUTTONDOWN:\n print(\"Mouse down at location \", x,y)\n upperLeftCorner = (x,y)\n if event == cv2.EVENT_LBUTTONUP:\n print(\"Mouse up at location \", x,y)\n lowerRightCorner = (x,y)\n\n# Create a black image, a window and bind the function to window\n\n\n\nwhile True:\n ret, frame = cam.read()\n frame = cv2.flip(cv2.flip(frame,1),-1)\n if upperLeftCorner is not None and lowerRightCorner is not None:\n newFrame = frame[upperLeftCorner[1]:lowerRightCorner[1], upperLeftCorner[0]:lowerRightCorner[0]]\n else:\n newFrame = frame\n cv2.imshow(\"Raw Image\", newFrame)\n cv2.setMouseCallback('Raw Image', mouse_click)\n\n key = cv2.waitKey(33)\n if key == 1048689: # q\n break\n elif key != -1:\n print(key)\n\ncv2.destroyAllWindows()\ncam.release()","sub_path":"trimVideo.py","file_name":"trimVideo.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"133704558","text":"##############################################################################\n#\n# Copyright (c) 2004 Zope Corporation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"Browser Views for IMessageBoard\n\n$Id$\n\"\"\"\nimport os\nfrom zope.proxy import removeAllProxies\n\nfrom zope.app import zapi\nfrom zope.app.registration.interfaces import ActiveStatus\nfrom zope.app.site.interfaces import ISite\nfrom zope.app.site.service import SiteManager, ServiceRegistration\nfrom zope.app.utility.utility import LocalUtilityService, UtilityRegistration\nfrom zope.app.workflow.interfaces import IProcessDefinitionImportHandler\nfrom zope.app.workflow.interfaces import IProcessInstanceContainer\nfrom zope.app.workflow.stateful.contentworkflow import ContentWorkflowsManager\nfrom zope.app.workflow.stateful.definition import StatefulProcessDefinition\nfrom zope.app.workflow.stateful.interfaces import IContentWorkflowsManager\nfrom zope.app.workflow.stateful.interfaces import IStatefulProcessDefinition\n\nimport book.messageboard\nfrom book.messageboard.interfaces import IMessage\n\n\nclass AddMessageBoard(object):\n \"\"\"Add a message board.\"\"\"\n \n def createAndAdd(self, data):\n content = super(AddMessageBoard, self).createAndAdd(data)\n \n if self.request.get('workflow'):\n folder = removeAllProxies(zapi.getParent(content))\n if not ISite.providedBy(folder):\n sm = SiteManager(folder)\n folder.setSiteManager(sm)\n default = zapi.traverse(folder.getSiteManager(), 'default')\n \n # Create Local Utility Service\n default['Utilities'] = LocalUtilityService()\n rm = default.getRegistrationManager()\n registration = ServiceRegistration(zapi.servicenames.Utilities,\n 'Utilities', rm)\n key = rm.addRegistration(registration)\n zapi.traverse(rm, key).status = ActiveStatus\n\n # Create the process definition\n default['publish-message'] = StatefulProcessDefinition()\n pd_path = zapi.getPath(default['publish-message'])\n registration = UtilityRegistration(\n 'publish-message', IStatefulProcessDefinition, pd_path)\n pd_id = rm.addRegistration(registration)\n zapi.traverse(rm, pd_id).status = ActiveStatus\n\n import_util = IProcessDefinitionImportHandler(\n default['publish-message'])\n \n xml = os.path.join(\n os.path.dirname(book.messageboard.__file__), 'workflow.xml')\n \n import_util.doImport(open(xml, mode='r').read())\n \n # Create Content Workflows Manager\n default['ContentWorkflows'] = ContentWorkflowsManager()\n cm_path = zapi.getPath(default['ContentWorkflows'])\n registration = UtilityRegistration(\n 'wfcontentmgr', IContentWorkflowsManager, cm_path)\n cm_id = rm.addRegistration(registration)\n zapi.traverse(rm, cm_id).status = ActiveStatus\n\n contentmgr = default['ContentWorkflows']\n contentmgr.register(IMessage, 'publish-message')\n\n return content\n\n\nclass ReviewMessages:\n \"\"\"Workflow: Review all pending messages\"\"\"\n\n def getPendingMessages(self, pmsg):\n \"\"\"Get all pending messages recursively.\"\"\"\n msgs = []\n for name, msg in pmsg.items():\n if IMessage.providedBy(msg):\n if hasMessageStatus(msg, 'pending'):\n msgs.append(msg)\n msgs += self.getPendingMessages(msg)\n return msgs\n\n def getPendingMessagesInfo(self):\n \"\"\"Get all the display info for pending messages\"\"\"\n msg_infos = []\n for msg in self.getPendingMessages(self.context):\n info = {}\n info['title'] = msg.title\n info['url'] = zapi.getView(\n msg, 'absolute_url', self.request)() + '/@@workflows.html'\n msg_infos.append(info)\n return msg_infos\n\n\ndef hasMessageStatus(msg, status, workflow='publish-message'):\n \"\"\"Check whether a particular message matches a given status\"\"\"\n adapter = IProcessInstanceContainer(msg)\n if adapter:\n # No workflow is defined, so the message is always shown.\n if not adapter.keys():\n return True\n for item in adapter.values():\n if item.processDefinitionName != workflow:\n continue\n if item.status == status:\n return True\n\n return False\n","sub_path":"book/trunk/messageboard/step10/browser/messageboard.py","file_name":"messageboard.py","file_ext":"py","file_size_in_byte":5021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"555308803","text":"\"\"\"\n给定一个 N 叉树,返回其节点值的后序遍历。\n\n例如,给定一个 3叉树 :\n\n\n\n\n\n\n\n返回其后序遍历: [5,6,3,2,4,1].\n\"\"\"\n# 后序遍历树\n\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val, children):\n self.val = val\n self.children = children\n\"\"\"\nclass Solution:\n def postorder(self, root: 'Node') -> List[int]:\n S1 = []\n S2 = []\n if root:\n S1.append(root)\n while S1:\n node = S1.pop()\n S2.append(node)\n if node.children:\n S1.extend(node.children)\n while S2:\n node = S2.pop()\n S1.append(node.val)\n return S1\n","sub_path":"tree/560.py","file_name":"560.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"321159890","text":"class Solution(object):\n def partition(self, s):\n \"\"\"\n :type s: str\n :rtype: List[List[str]]\n \"\"\"\n if not any(s):\n return [[]]\n self.res = []\n self.find_partition(s, [])\n return self.res\n\n def find_partition(self, s, path):\n if not s:\n self.res.append(path)\n return\n for i in range(len(s)):\n part_s = s[:i+1]\n if part_s == part_s[::-1]:\n if i < 1:\n path.append(part_s)\n else:\n path[-1] = part_s\n self.find_partition(s[i+1:], path[::])\n return\n\n\nS = Solution()\nprint(S.partition('aabaa'))","sub_path":"131 - Palindrome Partitioning.py","file_name":"131 - Palindrome Partitioning.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"77876576","text":"print(\"\\tWelcome to the 'Three-Year-Old Simulator'\\n\")\nprint(\"This program simulates a conversation with a three-year-old child.\")\nprint(\"Try to stop the madness.\\n\")\ncounter=0\nwhile counter <= 10:\n print (counter)\n counter += 1\n\nresponse = \"\"\nwhile response != \"Because.\":\n response = input(\"Why?\\n\")\nprint(\"Oh. Okay.\")\ninput(\"\\n\\nPress the enter key to exit.\")\n\ncount = 0\nwhile True:\n count += 1\n if count > 10:\n break\n if count == 5:\n continue\n print(count)\n","sub_path":"wy_while.py","file_name":"wy_while.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"49979125","text":"# Copyright (C) 2016 The Android Open Source Project\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\r\n'''Module that contains the test TestBreakpointCoordinate.'''\r\n\r\nfrom __future__ import absolute_import\r\n\r\nfrom harness.test_base_remote import TestBaseRemote\r\nfrom harness.decorators import (\r\n wimpy,\r\n ordered_test,\r\n cpp_only_test,\r\n)\r\nfrom harness.assert_mixins import CoordinateAssertionsMixin\r\n\r\n\r\nclass TestBreakpointCoordinate(TestBaseRemote, CoordinateAssertionsMixin):\r\n '''Tests breaking on a specific kernel invocation.\r\n\r\n Uses the -c option to specify the coordinate.\r\n '''\r\n\r\n bundle_target = {\r\n 'java': 'Allocations',\r\n 'jni': 'JNIAllocations',\r\n 'cpp': 'CppAllocations'\r\n }\r\n\r\n def setup(self, android):\r\n '''This test requires to be run on one thread.\r\n\r\n Args:\r\n android: The android_util module.\r\n '''\r\n android.push_prop('debug.rs.max-threads', 1)\r\n\r\n def teardown(self, android):\r\n '''Reset the number of RS threads to the previous value.\r\n\r\n Args:\r\n android: The android_util module.\r\n '''\r\n android.pop_prop('debug.rs.max-threads')\r\n\r\n @wimpy\r\n @ordered_test(0)\r\n def test_breakpoint_coordinate_2d_swizzle_kernel(self):\r\n # pylint: disable=line-too-long\r\n\r\n # test conditional coordinate in two dimensions\r\n # breakpoint 1\r\n self.assert_coord_bp_set('swizzle_kernel', 3, 7)\r\n\r\n # we will delete this breakpoint before we hit it.\r\n # breakpoint 2\r\n self.assert_coord_bp_set('swizzle_kernel', 199, 190)\r\n\r\n self.assert_coord_stop('allocs', 'swizzle_kernel', x=3, y=7)\r\n\r\n # check breakpoints that have been hit are disabled\r\n self.try_command(\r\n 'breakpoint list',\r\n [\r\n \"1: RenderScript kernel breakpoint for 'swizzle_kernel', locations = 1 Options: disabled\",\r\n \"2: RenderScript kernel breakpoint for 'swizzle_kernel', locations = 1\"\r\n ]\r\n )\r\n\r\n # delete breakpoint on 199,199,0\r\n self.try_command('breakpoint delete 2', ['1 breakpoints deleted'])\r\n\r\n # check breakpoints that have been hit are disabled\r\n self.try_command(\r\n 'breakpoint list',\r\n [\"1: RenderScript kernel breakpoint for 'swizzle_kernel', locations = 1 Options: disabled\"]\r\n )\r\n\r\n # test conditional coordinate in a single dimension\r\n # breakpoint 3\r\n self.assert_coord_bp_set('square_kernel', 8)\r\n\r\n # check breakpoints that have been hit are disabled\r\n self.try_command(\r\n 'breakpoint list',\r\n [\r\n \"1: RenderScript kernel breakpoint for 'swizzle_kernel', locations = 1 Options: disabled\",\r\n \"3: RenderScript kernel breakpoint for 'square_kernel', locations = 1\"\r\n ]\r\n )\r\n\r\n self.assert_coord_stop('allocs', 'square_kernel', x=8)\r\n\r\n # check breakpoints that have been hit are disabled\r\n self.try_command(\r\n 'breakpoint list',\r\n [\r\n \"1: RenderScript kernel breakpoint for 'swizzle_kernel', locations = 1 Options: disabled\",\r\n \"3: RenderScript kernel breakpoint for 'square_kernel', locations = 1 Options: disabled\"\r\n ]\r\n )\r\n\r\n @wimpy\r\n @ordered_test(1)\r\n def test_breakpoint_coordinate_3d_add_half_kernel(self):\r\n # test conditional coordinate in three dimensions\r\n # breakpoint 4\r\n self.assert_coord_bp_set('add_half_kernel', 0, 0, 1)\r\n # test we can set more than one conditional kernel breakpoint\r\n # and both will be hit;\r\n # breakpoint 5\r\n self.assert_coord_bp_set('add_half_kernel', 0, 1, 2)\r\n\r\n # Now assert that the next two continue/stop cycles hit our conditionals\r\n self.assert_coord_stop('allocs', 'add_half_kernel', x=0, y=0, z=1)\r\n self.assert_coord_stop('allocs', 'add_half_kernel', x=0, y=1, z=2)\r\n\r\n # check we can see the coordinate from a function invoked by the kernel\r\n # breakpoint 6\r\n self.try_command(\r\n 'break set -n half_helper',\r\n ['librs.allocs.so`half_helper']\r\n )\r\n\r\n # continue till we hit breakpoint 6\r\n self.assert_coord_stop('allocs', 'half_helper', x=0, y=1, z=2)\r\n\r\n self.try_command(\r\n 'breakpoint list',\r\n [\r\n \"1: RenderScript kernel breakpoint for 'swizzle_kernel', locations = 1 Options: disabled\",\r\n \"3: RenderScript kernel breakpoint for 'square_kernel', locations = 1 Options: disabled\",\r\n \"4: RenderScript kernel breakpoint for 'add_half_kernel', locations = 1 Options: disabled\",\r\n \"5: RenderScript kernel breakpoint for 'add_half_kernel', locations = 1 Options: disabled\",\r\n \"6: name = 'half_helper', locations = 1, resolved = 1, hit count = 1\"\r\n ]\r\n )\r\n\r\n self.try_command('breakpoint delete 3', ['1 breakpoints deleted'])\r\n\r\n self.try_command(\r\n 'breakpoint list',\r\n [\r\n \"1: RenderScript kernel breakpoint for 'swizzle_kernel', locations = 1 Options: disabled\",\r\n \"4: RenderScript kernel breakpoint for 'add_half_kernel', locations = 1 Options: disabled\",\r\n \"5: RenderScript kernel breakpoint for 'add_half_kernel', locations = 1 Options: disabled\",\r\n \"6: name = 'half_helper', locations = 1, resolved = 1, hit count = 1\"\r\n ]\r\n )\r\n\r\n self.try_command('breakpoint delete 6', ['1 breakpoints deleted'])\r\n\r\n self.try_command(\r\n 'breakpoint list',\r\n [\r\n \"1: RenderScript kernel breakpoint for 'swizzle_kernel', locations = 1 Options: disabled\",\r\n \"4: RenderScript kernel breakpoint for 'add_half_kernel', locations = 1 Options: disabled\",\r\n \"5: RenderScript kernel breakpoint for 'add_half_kernel', locations = 1 Options: disabled\"\r\n ]\r\n )\r\n\r\n @cpp_only_test()\r\n @ordered_test('last')\r\n def test_cpp_cleanup(self):\r\n self.try_command('breakpoint delete 4', ['1 breakpoints deleted'])\r\n self.try_command('breakpoint delete 5', ['1 breakpoints deleted'])\r\n self.try_command('process continue', ['exited with status = 0'])\r\n","sub_path":"rs/tests/lldb/tests/testcases/test_breakpoint_coordinate.py","file_name":"test_breakpoint_coordinate.py","file_ext":"py","file_size_in_byte":6911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"267096362","text":"from nonebot import on_command, CommandSession\nimport requests as reqs\nimport json\nimport datetime\nfrom collections import Counter\nfrom .data_source import *\n\n\n@on_command('pcr', aliases=('公主链接台服'))\nasync def pcr(session: CommandSession):\n # 获取op\n op = session.get('op', prompt='你想pcr执行哪些操作?')\n # 获取返回\n msg = await handleOp(op)\n # 发送消息\n if type(msg) is list:\n text = ''\n flag = True\n for m in msg:\n if (len(text) + len(m)) > 200:\n await session.send(text)\n flag = True\n text = m\n else:\n flag = False\n text += m\n print(len(text))\n await session.send(text)\n \n else:\n await session.send(msg)\n \n\n\n@pcr.args_parser\nasync def _(session: CommandSession):\n stripped_arg = session.current_arg_text.strip()\n \n # 该命令第一次运行(第一次进入命令会话)\n if session.is_first_run:\n if stripped_arg:\n # 第一次运行参数不为空,意味着用户直接将城市名跟在命令名后面,作为参数传入\n # 例如用户可能发送了:pcr 活动\n session.state['op'] = stripped_arg\n return\n \n if not stripped_arg:\n # 用户没有发送有效操作\n # 这里 session.pause() 将会发送消息并暂停当前会话(该行后面的代码不会被运行)\n session.pause('操作不能为空,请重新输入')\n \n session.state[session.current_key] = stripped_arg\n\n\n","sub_path":"awesome/plugins/pcr/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"633226240","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n\tpath('',views.index, name = 'index'),\n\tpath('1/',views.page1, name = 'page1'),\n\tpath('2y/',views.page2, name = 'page2'),\n\tpath('3y/',views.page3, name = 'page3'),\n\tpath('4y/',views.page4, name = 'page4'),\n\tpath('5y/',views.page5, name = 'page5'),\n\n\tpath('2/',views.page2n, name = 'page2n'),\n\tpath('3/',views.page3n, name = 'page3n'),\n\tpath('4/',views.page4n, name = 'page4n'),\n\tpath('5/',views.page5n, name = 'page5n'),\n\n]","sub_path":"myfirst/apps/minigame/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"123968345","text":"#coding:utf-8\r\n\r\nimport os\r\nimport shutil\r\nimport time\r\nimport queue\r\nimport ctypes\r\n\r\nwhnd = ctypes.windll.kernel32.GetConsoleWindow() \r\nif whnd != 0: \r\n ctypes.windll.user32.ShowWindow(whnd, 0) \r\n ctypes.windll.kernel32.CloseHandle(whnd) \r\n\r\n\r\ndoc = ['doc','docx','xls','xlsx','txt','pdf','zip','rar']\r\nmaxsize = 50 #MB\r\nlistendisk = 'F:\\\\'\r\nsavepath = 'D:\\\\disk\\\\'\r\nwhile True:\r\n if os.path.exists(listendisk): \r\n try:\r\n newpath = savepath+time.strftime(\"%Y-%m-%d-%H-%M-%S\", time.localtime())+'\\\\'\r\n os.makedirs(newpath)\r\n dirqueue = queue.Queue()\r\n for f in os.listdir(listendisk):\r\n #print f\r\n if os.path.isfile(listendisk+f) and f.split('.')[-1].lower() in doc and os.path.getsize(listendisk+f) <= maxsize*1024*1024:\r\n shutil.copyfile(listendisk+f,newpath+f)\r\n #print listendisk+f,newpath+f\r\n elif os.path.isdir(listendisk+f):\r\n dirqueue.put(f+'\\\\')\r\n \r\n while not dirqueue.empty():\r\n d = dirqueue.get()\r\n path = listendisk+d\r\n #print path\r\n for f in os.listdir(path):\r\n #print f\r\n if os.path.isfile(path+f):\r\n if f.split('.')[-1].lower() in doc and os.path.getsize(path+f) <= maxsize*1024*1024:\r\n if not os.path.exists(newpath+d):\r\n os.makedirs(newpath+d)\r\n shutil.copyfile(path+f,newpath+d+f)\r\n elif os.path.isdir(path+f):\r\n dirqueue.put(d+f+'\\\\')\r\n except:\r\n pass\r\n while os.path.exists(listendisk):\r\n time.sleep(1)\r\n time.sleep(1)\r\n","sub_path":"copy.py","file_name":"copy.py","file_ext":"py","file_size_in_byte":1824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"358521786","text":"\nimport sys\nfrom data_provider import DbConnectionError, QueryExecutionError\n\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog\nfrom PyQt5.QtCore import Qt\n\nfrom window import Ui_MainWindow\nfrom model import ResultTableModel\n\n\nclass MainWindow(QMainWindow, Ui_MainWindow):\n\n createSql = 'select * from customer'\n selectSql = 'select * from users'\n\n def __init__(self, parent=None):\n QMainWindow.__init__(self)\n Ui_MainWindow.__init__(self)\n self.setupUi(self)\n\n self.executeBtn.clicked.connect(self.executeQuery)\n self.openBtn.clicked.connect(self.openFile)\n self.resultTable.verticalHeader().hide()\n self.queryTextEdit.setText(self.createSql)\n self.connectionStringLineEdit.setText(':memory:')\n self.outputTextView.setReadOnly(True)\n\n def openFile(self):\n options = QFileDialog.Options()\n options |= QFileDialog.DontUseNativeDialog\n fileName, _ = QFileDialog.getOpenFileName(\n self,\n 'Open database',\n '',\n 'SQLite database files (*.db *.sqlite *.db3 *.sqlite3)',\n options=options)\n if fileName:\n self.connectionStringLineEdit.setText(fileName)\n\n def fetched(self, items):\n self.rowCountLabel.setText('\\nFetched: %s' % str(len(items)))\n\n def executeQuery(self):\n con_string = str(self.connectionStringLineEdit.text())\n query = str(self.queryTextEdit.toPlainText())\n\n if self.resultTable.model():\n self.resultTable.model().clear()\n else:\n self.resultTable.setModel(ResultTableModel())\n self.resultTable.model().fetched.connect(self.fetched)\n\n model = self.resultTable.model()\n try:\n model.execute_query(con_string, query)\n self.outputTextView.append('\\n%s\\nSuccess.\\n' % (query))\n\n except DbConnectionError as ce:\n self.outputTextView.append(\n '\\n%s\\nConnection error: %s\\n' % (query, ce)\n )\n except QueryExecutionError as ee:\n self.outputTextView.append(\n '\\n%s\\nExecution error: %s\\n' % (query, ee)\n )\n except Exception as e:\n self.outputTextView.append(\n '\\n%s\\nUndefined error: %s\\n' % (query, e)\n )\n self.outputTextView.ensureCursorVisible()\n\n def closeEvent(self, event):\n self.resultTable.model().close()\n event.accept()\n\n def keyPressEvent(self, e):\n if e.key() == Qt.Key_F5:\n self.executeQuery()\n\n\ndef app_main(args):\n app = QApplication(sys.argv)\n view = MainWindow()\n view.show()\n return app.exec_()\n\n\nif __name__ == '__main__':\n sys.exit(app_main(sys.argv))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"600179560","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 19 17:40:39 2021\n\n@author: hello python\n\"\"\"\n\n # 使用递归编写一个 power() 函数模拟内建函数 pow(),即 power(x, y) 为计算并返回 x 的 y 次幂的值。\ndef power(x, y):\n if y:\n return x*power(x,y-1)\n else:\n return 1\n\n \npower(4,6) ","sub_path":"code2.py","file_name":"code2.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"32260210","text":"from bs4 import BeautifulSoup, Comment\r\nimport requests\r\n\r\ndef el_is_visible(element):\r\n try:\r\n if element.parent.name in ['style', 'script', 'head', 'title', 'meta', '[document]']:\r\n return False\r\n if isinstance(element, Comment):\r\n return False\r\n return True\r\n except:\r\n return False\r\n\r\ndef get_visible_text(soup):\r\n try:\r\n text = soup.findAll(text=True)\r\n text = ' '.join([t.strip() for t in text if el_is_visible(t)])\r\n return text\r\n except:\r\n return ''\r\n \r\n\r\ndef parseLink(query, adress, SE):\r\n file=open(adress,'r')\r\n while(True):\r\n link = file.readline()\r\n if (link==\"\"):\r\n break\r\n l=len(link)\r\n link=link[:l-1]\r\n print(link)\r\n if(link.find(\".pdf\")!=-1):\r\n continue\r\n x=link[l-4:l-1]\r\n if(x==\"pdf\"):\r\n continue\r\n try:\r\n headers={\r\n 'User-Agent':'Pankaj',\r\n 'From':'pcnitp@gmail.com'}\r\n #page = requests.get(link)\r\n page=requests.get(link,headers=headers)\r\n soup = BeautifulSoup(page.text,'html.parser')\r\n except:\r\n continue\r\n\r\n text=get_visible_text(soup)\r\n text=re.sub(r'([^\\s\\w]|_)+', '', text)\r\n text=re.sub(r'[^\\x00-\\x7F]+',' ',text )\r\n #writing content of each page to a text file\r\n file1 =open(\"C:\\\\Users\\\\DELL\\\\Desktop\\\\Project\\\\\"+SE+\"\\\\paragraph1\\\\\"+query+\".txt\", 'a',encoding=\"utf-8\")\r\n file1.write(text)\r\n \r\n \r\n \r\nfile=open(\"C:\\\\Users\\\\DELL\\\\Desktop\\\\Project\\\\query_lists.txt\",'r')\r\ni=0\r\nwhile(True):\r\n query=file.readline()\r\n if(query==\"\"):\r\n break\r\n l=len(query)\r\n query=query[:l-1]\r\n \r\n address=\"C:\\\\Users\\\\DELL\\\\Desktop\\\\Project\\\\Google\\\\QueryLinks\\\\\"+query+\".txt\"\r\n parseLink(query, address, \"Google\")\r\n \r\n address=\"C:\\\\Users\\\\DELL\\\\Desktop\\\\Project\\\\Bing\\\\QueryLinks\\\\\"+query+\".txt\"\r\n parseLink(query, address, \"Bing\")\r\n \r\n address=\"C:\\\\Users\\\\DELL\\\\Desktop\\\\Project\\\\Duckduckgo\\\\QueryLinks\\\\\"+query+\".txt\"\r\n parseLink(query, address, \"Duckduckgo\")\r\n \r\n","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":2188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"441400588","text":"import requests\nimport pandas as pd\n\ndef weather_func(day):\n url1 = \"https://goweather.herokuapp.com/weather/india\"\n\n json_data = requests.get(url1).json()\n today_temp = json_data['temperature'] \n print(json_data)\n forecast = json_data['forecast']\n print(forecast)\n\n if(day == \"Today\" or day == \"today\"):\n return {'day': 'today', 'temperature' : today_temp}\n elif(day.split(\" \")[1]== '1' or day.split(\" \")[1] == 1):\n return forecast[0]\n elif(day.split(\" \")[1]== '2' or day.split(\" \")[1] == 2):\n return forecast[1]\n elif(day.split(\" \")[1]== '3' or day.split(\" \")[1] == 3):\n return forecast[2]\n else:\n return {'day':'No data', 'temperature': 'No data'}\n","sub_path":"actions/weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"503060114","text":"teen_code={\"vk\": \"vo\", \"ck\": \"chong\", \"hok\": \"khong\", \"hoy\": \"thooi\", \"clgt\": \"cu lac gion tan\"}\nloop=True\nwhile loop:\n word=input(\"Nhap tu teencode ban muon tra\")\n if word in teen_code:\n print(word, \"co nghia la\", teen_code[word])\n else:\n ans=input(\"tu tren khong co trong tu dien, ban co muon bo xung khong?(y/n)\").lower()# chu y hoa hay chu y thuong\n if ans==\"y\":\n new_word=input(\"moi ban nhap nghia cua tu moi\")\n teen_code[word]=new_word\n elif ans==\"n\":\n print(\"bye bye\") \n loop=False","sub_path":"buoi5.py/chuabai.py","file_name":"chuabai.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"479812782","text":"from django.shortcuts import render\nfrom django.shortcuts import redirect\n\nfrom crud_app.forms import FilmForm\nfrom crud_app.models import Film\n\n\ndef create(request):\n if request.method == \"POST\":\n form = FilmForm(request.POST)\n if form.is_valid():\n try:\n form.save()\n return redirect('/read')\n except: \n pass\n else:\n form = FilmForm()\n return render(request,'index.html',{'form':form})\n\ndef read(request):\n fid = request.GET.get('id')\n\n if fid is not None:\n films = [Film.objects.get(id=fid)]\n else:\n n = request.GET.get('n')\n\n films = list(Film.objects.all())\n\n if n is not None:\n n = int(n)\n if n < len(films) and n > 0:\n films = films[-n:]\n\n return render(request,\"show.html\",{'films':films})\n\ndef update(request, id):\n film = Film.objects.get(id=id)\n\n if request.method == \"POST\":\n form = FilmForm(request.POST, instance=film)\n if form.is_valid():\n form.save()\n return redirect(\"/read\")\n\n for field in form:\n print(\"Field Error:\", field.name, field.errors)\n else:\n form = FilmForm()\n\n return render(request,'edit.html', {'film':film, 'form': form})\n\ndef delete(request, id):\n film = Film.objects.get(id=id)\n\n film.delete()\n return redirect(\"/read\")\n","sub_path":"crud_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"184410952","text":"import pyhsm_msgs.msg as msgs\nimport rospy\nfrom std_msgs.msg import String\n\nfrom .. import introspection\nfrom . import GObject\n\n__all__ = [\"StateNode\", \"RootStateNode\", \"DummyStateNode\"]\n\n\nclass StateNode(GObject.GObject):\n \"\"\"A node representing a state in a HSM\"\"\"\n\n __slots__ = [slot for slot in msgs.HsmState.__slots__ if slot != \"path\"]\n\n def __init__(self, msg, root):\n \"\"\"Initialize a state node from the given ``HsmState`` message\n\n :type msg: msgs.HsmState\n \"\"\"\n GObject.GObject.__init__(self)\n assert isinstance(root, RootStateNode)\n self.root = root\n self._path = self.root.prefix + msg.path\n\n # store all slots from msg as instance properties\n for slot in self.__slots__:\n self.__setattr__(slot, getattr(msg, slot))\n\n # HSM-related methods\n\n @property\n def path(self):\n \"\"\"Return the (full) path of this node, including a prefix from a root state\"\"\"\n return self._path\n\n def update(self, msg):\n \"\"\"Update all msg slots and return True if there were any changes\"\"\"\n changed = False\n for slot in self.__slots__:\n value = getattr(msg, slot)\n if getattr(self, slot) != value:\n setattr(self, slot, value)\n changed = True\n return changed\n\n\nclass RootStateNode(StateNode):\n \"\"\"A node representing the root state of a HSM.\"\"\"\n\n def __init__(self, msg, prefix, server_name):\n \"\"\"Initialize a state node from the given ``HsmState`` message and other meta information.\"\"\"\n self._prefix = prefix\n # Ensure _prefix has a trailing slash\n if self._prefix and self._prefix[-1] != \"/\":\n self._prefix += \"/\"\n StateNode.__init__(self, msg, self) # initialize after _prefix!\n self._server_name = server_name\n self._transition_publisher = rospy.Publisher(\n server_name + introspection.TRANSITION_TOPIC, String, queue_size=1\n )\n self.current = None\n\n # HSM-related methods\n\n @property\n def prefix(self):\n return self._prefix\n\n @property\n def server_name(self):\n return self._server_name\n\n @property\n def transition_publisher(self):\n return self._transition_publisher\n\n\nclass DummyStateNode(StateNode):\n \"\"\"A node representing an unknown path\"\"\"\n\n def __init__(self, path):\n \"\"\"Initialize a dummy state node with the given path.\"\"\"\n GObject.GObject.__init__(self)\n # Do NOT StateNode.__init__ to ensure that slots remain undefined\n self._path = path\n self.root = None\n","sub_path":"src/hsm/viewer/state_node.py","file_name":"state_node.py","file_ext":"py","file_size_in_byte":2621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"527629092","text":"import pandas as pd \nimport numpy as np\nimport plotly.express as px\nimport plotly.graph_objects as go\nimport sys\n\n# # wywołanie ma argumenty: \n# 1 = nazwa pliku z sygnałem, \n# 2 - cutoff na confidence\n\ndf = pd.read_csv(sys.argv[1])\n\n\n# odfiltruj niskie confi\nif sys.argv[2] != .6:\n\tcutoff = float(sys.argv[2])\nelse:\n\tcutoff = .6\n\ndf.loc[df['confidence'] < cutoff, 'diameter'] = np.nan\n\n# zrób minima i maksima\nmin_obs = df.diameter.min()\nmax_obs = df.diameter.max()\n\n# zrób wykres\nplot_title = 'eye ' + sys.argv[2] + ' (' + sys.argv[1] + ')'\nfig = px.line(df, x=\"time\", y=\"diameter\", color='eye_id', title= plot_title)\nfig.update_layout(\n shapes=[\n # Line Vertical\n go.layout.Shape(\n type=\"line\",\n x0=120,\n y0=min_obs,\n x1=120,\n y1=max_obs,\n line=dict(\n color=\"Red\",\n width=2\n )\n ), \n # Line Vertical\n go.layout.Shape(\n type=\"line\",\n x0=240,\n y0=min_obs,\n x1=240,\n y1=max_obs,\n line=dict(\n color=\"Green\",\n width=2\n )\n ), \n ])\nfig.write_html('plot_'+sys.argv[1]+'.html', auto_open=True)","sub_path":"analiza_kb/plot_signal.py","file_name":"plot_signal.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"259047204","text":"# coding: utf-8\n\"\"\" Database工具。\n\"\"\"\n\nimport redis\nimport tornadoredis\nfrom torndb import Connection\n\nfrom bkmfc.config import configs\n\n\n_SYNC_REDIS_ = {}\n_ASYNC_REDIS_ = {}\n\n\ndef get_sync_redis(id):\n if id in _SYNC_REDIS_:\n return _SYNC_REDIS_[id]\n _SYNC_REDIS_[id] = conn = redis.StrictRedis(**configs['redis'][id])\n return conn\n\n\ndef get_async_redis(id, exclusive=False, io_loop=None):\n params = configs['redis'][id].copy()\n params['selected_db'] = params.pop('db', 0)\n if exclusive:\n conn = tornadoredis.Client(io_loop=io_loop, **params)\n conn.connect()\n return conn\n if id in _ASYNC_REDIS_:\n return _ASYNC_REDIS_[id]\n _ASYNC_REDIS_[id] = conn = tornadoredis.Client(\n io_loop=io_loop, **params)\n conn.connect()\n return conn\n\n\n############################################################\n\n\n_SYNC_MYSQL_ = {}\n\n\ndef get_sync_mysql(db_id):\n if db_id in _SYNC_MYSQL_:\n return _SYNC_MYSQL_[db_id]\n _SYNC_MYSQL_[db_id] = db = Connection(**configs['mysql'][db_id])\n db._db_args.pop('init_command', None)\n db.execute(\"SET TIME_ZONE = 'SYSTEM'\")\n return db\n\nget_conn = get_sync_mysql\n\n","sub_path":"src/lib/bkmfc/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"243006097","text":"# -*- coding: utf-8 -*-\n\nfrom parser.metric import Metric\n\nimport torch\nimport torch.nn as nn\n\n\nclass Model(object):\n\n def __init__(self, vocab, parser):\n super(Model, self).__init__()\n\n self.vocab = vocab\n self.parser = parser\n self.criterion = nn.CrossEntropyLoss()\n\n def train(self, loader):\n self.parser.train()\n\n for words, tags, arcs, rels in loader:\n self.optimizer.zero_grad()\n\n mask = words.ne(self.vocab.pad_index)\n # ignore the first token of each sentence\n mask[:, 0] = 0\n s_arc, s_rel = self.parser(words, tags)\n s_arc, s_rel = s_arc[mask], s_rel[mask]\n gold_arcs, gold_rels = arcs[mask], rels[mask]\n\n loss = self.get_loss(s_arc, s_rel, gold_arcs, gold_rels)\n loss.backward()\n nn.utils.clip_grad_norm_(self.parser.parameters(), 5.0)\n self.optimizer.step()\n self.scheduler.step()\n\n @torch.no_grad()\n def evaluate(self, loader, punct=False):\n self.parser.eval()\n\n loss, metric = 0, Metric()\n\n for words, tags, arcs, rels in loader:\n mask = words.ne(self.vocab.pad_index)\n # ignore the first token of each sentence\n mask[:, 0] = 0\n # ignore all punctuation if not specified\n if not punct:\n puncts = words.new_tensor(self.vocab.puncts)\n mask &= words.unsqueeze(-1).ne(puncts).all(-1)\n s_arc, s_rel = self.parser(words, tags)\n s_arc, s_rel = s_arc[mask], s_rel[mask]\n gold_arcs, gold_rels = arcs[mask], rels[mask]\n pred_arcs, pred_rels = self.decode(s_arc, s_rel)\n\n loss += self.get_loss(s_arc, s_rel, gold_arcs, gold_rels)\n metric(pred_arcs, pred_rels, gold_arcs, gold_rels)\n loss /= len(loader)\n\n return loss, metric\n\n @torch.no_grad()\n def predict(self, loader):\n self.parser.eval()\n\n all_arcs, all_rels = [], []\n for words, tags in loader:\n mask = words.ne(self.vocab.pad_index)\n # ignore the first token of each sentence\n mask[:, 0] = 0\n lens = mask.sum(dim=1).tolist()\n s_arc, s_rel = self.parser(words, tags)\n s_arc, s_rel = s_arc[mask], s_rel[mask]\n pred_arcs, pred_rels = self.decode(s_arc, s_rel)\n\n all_arcs.extend(torch.split(pred_arcs, lens))\n all_rels.extend(torch.split(pred_rels, lens))\n all_arcs = [seq.tolist() for seq in all_arcs]\n all_rels = [self.vocab.id2rel(seq) for seq in all_rels]\n\n return all_arcs, all_rels\n\n def get_loss(self, s_arc, s_rel, gold_arcs, gold_rels):\n s_rel = s_rel[torch.arange(len(s_rel)), gold_arcs]\n\n arc_loss = self.criterion(s_arc, gold_arcs)\n rel_loss = self.criterion(s_rel, gold_rels)\n loss = arc_loss + rel_loss\n\n return loss\n\n def decode(self, s_arc, s_rel):\n pred_arcs = s_arc.argmax(dim=-1)\n pred_rels = s_rel[torch.arange(len(s_rel)), pred_arcs].argmax(dim=-1)\n\n return pred_arcs, pred_rels\n","sub_path":"parser/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"249184827","text":"from sklearn.datasets import load_iris\niris = load_iris()\n\ndata = iris.data\ntarget = iris.target\n\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(data, target, random_state=0)\n\nfrom sklearn.neighbors import KNeighborsClassifier\nknn = KNeighborsClassifier(n_neighbors=1)\n\nknn.fit(X_train, y_train)\n\ny_pred = knn.predict(X_test)\n\nprint(knn.score(X_test, y_test))","sub_path":"SimpleML.py","file_name":"SimpleML.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"178477709","text":"# -*- coding: utf-8 -*-\nimport math\n\n#comece abaixo\ndef media(lista):\n cont=0\n for i in range(0,len(lista),1):\n soma=soma+lista[i]\n resultado=soma/len(lista)\n return resultado\ndef dp(lista):\n soma=0\n for i in range(0,len(lista),1):\n soma=soma+lista[i]\n resultado=soma/len(lista)\n sdq=0\n for i in range(0,len(lista),1):\n v=v+((lista[i]-media(lista))**2)\n sdq=sdq+v\n d=(v/(len(lista)-1))**0.5\n return d\na=[]\nn=int(input('n:'))\nfor i in range(0,n,1):\n valor=int(input('valor:'))\n a.append(valor)\nprint('%.2f'%a[0])\nprint('%.2f'%a[len(a)-1])\nprint('%.2f'%media(a))\nprint('%.2f'%dp(a))\n\n\n\n\n\n\n","sub_path":"moodledata/vpl_data/95/usersdata/231/58128/submittedfiles/desvpad.py","file_name":"desvpad.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"79214875","text":"\"\"\"\ncryptography.py\nAuthor: Matthew\nCredit: Robbie\n\nAssignment:\n\nWrite and submit a program that encrypts and decrypts user data.\n\nSee the detailed requirements at https://github.com/HHS-IntroProgramming/Cryptography/blob/master/README.md\n\"\"\"\nassociations = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 .,:;'\\\"/\\\\<>(){}[]-=_+?!\"\n\n\n\n\n\nCoding = True\nwhile Coding:\n start = input(\"Enter e to encrypt, d to decrypt, or q to quit: \")\n if start != \"q\":\n if start == \"e\":\n a = []\n b = []\n f = []\n m = input(\"Message: \")\n for c in m:\n n = (associations.find(c))\n a.append(n) #converting message to #'s\n k = input(\"Key: \")\n for c in k:\n j = (associations.find(c))\n b.append(j) #converting key to #'s\n p = b*20 \n for l in range(len(m)):\n q = a[l] + p[l] #adding key's #'s to message #'s\n if q >= 85:\n o = q-85\n f.append(o)\n else:\n f.append(q)\n \n for h in f:\n wow = associations[h] #Converting letters back into #'s\n print(wow, end=\"\") #Printing result\n print()\n elif start == \"d\":\n u = []\n z = []\n w = []\n m = input(\"Message: \")\n for c in m:\n n = (associations.find(c))\n w.append(n) #converting message to #'s\n k = input(\"Key: \")\n for c in k:\n j = (associations.find(c))\n z.append(j) #converting key to #'s\n p = z*20 \n for l in range(len(m)):\n q = w[l] - p[l] #adding key's #'s to message #'s\n if q < 0:\n o = q + 85\n u.append(o)\n else:\n u.append(q)\n \n for h in u:\n wow = associations[h] #Converting letters back into #'s\n print(wow, end=\"\") #Printing result\n print()\n else:\n print(\"Did not understand command, try again.\")\n else:\n print(\"Goodbye!\")\n Coding = False\n \n \n \n\n \n","sub_path":"cryptography.py","file_name":"cryptography.py","file_ext":"py","file_size_in_byte":2306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"246616418","text":"# 체스판 다시 칠하기 - 브루트 \n'''\nhttps://www.acmicpc.net/problem/1018\n\n'''\n\n# Python 3.6\ndef InputToIntList():\n temp = input().split(' ')\n relist = []\n for i in temp:\n relist.append(int(i))\n return relist\n\n\ndef check8by8(grid): # assume grid is 8 by 8\n correct_b = 0\n correct_w = 0\n for i in range(8): # Black case\n for j in range(8):\n if (i+j) % 2 == 0 and grid[i][j] == 'B':\n correct_b += 1\n if (i+j) % 2 == 1 and grid[i][j] == 'W':\n correct_b += 1\n\n for i in range(8): # White case\n for j in range(8):\n if (i+j) % 2 == 0 and grid[i][j] == 'W':\n correct_w += 1\n if (i+j) % 2 == 1 and grid[i][j] == 'B':\n correct_w += 1\n\n return max(correct_b, correct_w)\n\n(N, M) = InputToIntList()\ngrid = []\nfor i in range(N):\n grid.append(str(input()))\n\ncorrects = []\nfor n in range(N-7):\n for m in range(M-7):\n subgrid = []\n for k in range(8):\n subgrid.append(grid[n+k][m:m+8])\n tmp = check8by8(subgrid)\n corrects.append(tmp)\n\nprint(64- max(corrects))\n","sub_path":"023_Problem_1018.py","file_name":"023_Problem_1018.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"171118980","text":"# Thomas Roux\n# 28/05/2019\n# Creates 3 sets of numbers between 1 and 1000: first all divisible by 3, second all divisible by 7, third all divisible by 11\n# From these, creates sets that are divisble by: 3,7,11; 3,7, but not 11; not 3,7, or 11\n\n# Create variables\ns1 = set()\ns2 = set()\ns3 = set()\nsall = set()\n\n# Create sets\nfor i in range(1,1001):\n sall.add(i)\n if i % 3 == 0:\n s1.add(i)\n if i % 7 == 0:\n s2.add(i)\n if i % 11 == 0:\n s3.add(i)\n\n# Set of numbers divisible by 3,7, and 11\ndivall = (s1.intersection(s2)).intersection(s3)\n\n# Set of numbers divisble by 3 and 7, but not 11\ndivsome = (s1.intersection(s2)).difference(s3)\n\n# Set of numbers not divisible by 3, 7 or 11\ndivnone = ((sall.difference(s1)).difference(s2)).difference(s3)\n\n\n","sub_path":"ex14_2.py","file_name":"ex14_2.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"143239318","text":"n=int(input(\"Enter number of Natural numbers: \"))\r\ni=1\r\nlst=[]\r\nwhile i<=n:\r\n if i%2==0:\r\n print(i)\r\n lst.append(i)\r\n i+=1 \r\n else:\r\n i+=1\r\nprint('sum of all numbers:',sum(lst))\r\n \r\n","sub_path":"EvenSumass4.py","file_name":"EvenSumass4.py","file_ext":"py","file_size_in_byte":237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"131199640","text":"import sys\nimport six\nimport collections\nimport os\nimport sys\nif six.PY2:\n reload(sys)\n sys.setdefaultencoding('utf-8')\n\n\ndef word_count(input_file, word_freq=None):\n \"\"\"\n compute word count from corpus\n \"\"\"\n if word_freq is None:\n word_freq = collections.defaultdict(int)\n\n for l in input_file:\n for w in l.strip().split():\n word_freq[w] += 1\n\n return word_freq\n\n\ndef build_dict(min_word_freq=0, train_dir=\"\", test_dir=\"\"):\n \"\"\"\n Build a word dictionary from the corpus, Keys of the dictionary are words,\n and values are zero-based IDs of these words.\n \"\"\"\n word_freq = collections.defaultdict(int)\n files = os.listdir(train_dir)\n for fi in files:\n with open(os.path.join(train_dir, fi), \"r\") as f:\n word_freq = word_count(f, word_freq)\n files = os.listdir(test_dir)\n for fi in files:\n with open(os.path.join(test_dir, fi), \"r\") as f:\n word_freq = word_count(f, word_freq)\n\n word_freq = [x for x in six.iteritems(word_freq) if x[1] > min_word_freq]\n word_freq_sorted = sorted(word_freq, key=lambda x: (-x[1], x[0]))\n words, _ = list(zip(*word_freq_sorted))\n word_idx = dict(list(zip(words, six.moves.range(len(words)))))\n return word_idx\n\n\ndef write_paddle(word_idx, train_dir, test_dir, output_train_dir,\n output_test_dir):\n files = os.listdir(train_dir)\n if not os.path.exists(output_train_dir):\n os.mkdir(output_train_dir)\n for fi in files:\n with open(os.path.join(train_dir, fi), \"r\") as f:\n with open(os.path.join(output_train_dir, fi), \"w\") as wf:\n for l in f:\n l = l.strip().split()\n l = [word_idx.get(w) for w in l]\n for w in l:\n wf.write(str(w) + \" \")\n wf.write(\"\\n\")\n\n files = os.listdir(test_dir)\n if not os.path.exists(output_test_dir):\n os.mkdir(output_test_dir)\n for fi in files:\n with open(os.path.join(test_dir, fi), \"r\") as f:\n with open(os.path.join(output_test_dir, fi), \"w\") as wf:\n for l in f:\n l = l.strip().split()\n l = [word_idx.get(w) for w in l]\n for w in l:\n wf.write(str(w) + \" \")\n wf.write(\"\\n\")\n\n\ndef text2paddle(train_dir, test_dir, output_train_dir, output_test_dir,\n output_vocab):\n vocab = build_dict(0, train_dir, test_dir)\n with open(output_vocab, \"w\", encoding='utf-8') as wf:\n wf.write(str(len(vocab)) + \"\\n\")\n #wf.write(str(vocab))\n write_paddle(vocab, train_dir, test_dir, output_train_dir, output_test_dir)\n\n\ntrain_dir = sys.argv[1]\ntest_dir = sys.argv[2]\noutput_train_dir = sys.argv[3]\noutput_test_dir = sys.argv[4]\noutput_vocab = sys.argv[5]\ntext2paddle(train_dir, test_dir, output_train_dir, output_test_dir,\n output_vocab)\n","sub_path":"PaddleRec/tagspace/text2paddle.py","file_name":"text2paddle.py","file_ext":"py","file_size_in_byte":2958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"541312558","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 28 22:11:15 2018\n\n@author: sarac\n\"\"\"\n\nfrom EURUSDagent import DQNAgent\nimport datetime\nimport numpy as np\nimport pandas as pd \nimport matplotlib.pyplot as plt \n\n# init conts.\n############################################\n\nEPISODES = 1\nMARGIN = 1000\nstate_size = 60\n\n###########################################\n\n#start_index = 45 #2010.01.01 00:00\n#end_index = 3161+1 #2011.12.30 20:00\n\nstart_index = 8322+1 # 2011.12.16 16:00 start at 2012.01.02 00:00\nend_index = 11423+1 #2012.12.30 16:00\ndataset = pd.read_csv('EURUSD_4H.csv')\ntrain_data = dataset.iloc[start_index:end_index,5:6]\n\ntrain_data = np.array(train_data)\nstate_size = 60\nX_train = [] \nall_index = end_index-start_index\nfor i in range(state_size, all_index):\n X_train.append(train_data[i-state_size:i,0])\nX_train = np.array(X_train)\n\n\nclass TrainEnvironment:\n def __init__(self, data, num_index):\n self.train_data = data\n self.train_index = 0 \n self.end_index = num_index-1\n self.loss_limit = 0.3 # force sell \n \n self.profit = 0\n self.reward = 0\n self.mem_reward = 0\n \n # portfolio \n self.cost_price = 0 \n self.mem_action = 0\n \n def reset(self):\n self.train_index = 0 \n self.profit = 0\n self.reward = 0 \n self.cost_price = 0 \n self.mem_action = 0\n self.mem_reward = 0\n \n return [self.train_data[self.train_index]]\n \n def get_action(self,action):\n if action == 0 :\n # buy \n return 1\n elif action == 1 : \n # sell \n return -1\n else : \n # noaction \n return 0 \n \n def calculate_reward(self, action):\n action = self.get_action(action)\n current_price = self.train_data[self.train_index,59:60]\n if action == self.mem_action :\n self.profit = action*(current_price - self.cost_price)\n self.reward = self.mem_reward + self.profit\n else : \n if action == 0 : \n self.profit = self.mem_action*(current_price - self.cost_price) \n else :\n self.profit = current_price*(-0.001) + self.mem_action*(current_price - self.cost_price)\n self.reward = self.profit + self.mem_reward\n self.mem_reward = self.reward \n self.cost_price = current_price\n self.mem_action = action\n\n def done_check(self):\n if self.cost_price != 0 : \n loss = -self.loss_limit*self.cost_price\n else : \n loss = -self.loss_limit*self.train_data[self.train_index,59:60]\n if self.train_index + 1 == self.end_index :\n if self.reward > 0 : \n if self.reward <= 0.05*self.train_data[self.train_index,59:60]:\n self.reward = -1\n print('Full End !')\n return True \n elif self.reward <= loss : \n print('------------------------------------------------------------')\n print('loss limit: ', loss)\n print('reward : ', self.reward)\n print('Cut Loss !')\n self.reward = -3\n return True\n else :\n return False\n \n def step(self,action):\n skip = 6\n self.train_index += skip\n if self.train_index >= self.end_index-1 : \n self.train_index = self.end_index-1 \n ns = [self.train_data[self.train_index]]\n self.calculate_reward(action)\n done = self.done_check()\n return ns, self.reward*MARGIN, done\n\n#########################################################################################################\n# Train \n######################################################################################################### \ndef watch_result(episode ,s_time, e_time, c_index, all_index, action, reward, profit):\n print('-------------------- Check -------------------------')\n print('start time: ' + s_time) \n print('counter : ', c_index,'/', all_index,' of episode : ', episode, '/', EPISODES)\n print('action : ', action)\n print('current profit : ', profit*MARGIN)\n print('reward (all profit): ', reward)\n print('end_time: ' + e_time)\n print('-------------------End Check -----------------------')\n\n \nif __name__ == \"__main__\":\n \n agent = DQNAgent(state_size)\n agent.load(\"agent_model.h5\")\n num_index = all_index - state_size\n env = TrainEnvironment(X_train, num_index)\n batch_size = 10\n test_profit = []\n test_action = [] \n \n for e in range(EPISODES):\n state = env.reset()\n state = np.reshape(state, (1, state_size, 1))\n test_profit = []\n test_action = [] \n for t in range(end_index-start_index):\n start_time = str(datetime.datetime.now().time())\n action = agent.act(state, False) # test \n next_state, reward, done = env.step(action)\n next_state = np.reshape(next_state, (1,state_size,1))\n agent.remember(state, action, reward, next_state, done)\n state = next_state \n if done:\n agent.update_target_model()\n print('----------------------------- Episode Result -----------------------')\n print(\"episode: {}/{}, time: {}, e: {:.2}\"\n .format(e, EPISODES, t, agent.epsilon))\n print('----------------------------- End Episode --------------------------')\n break\n \n if len(agent.memory) > batch_size:\n agent.replay(batch_size)\n \n end_time = str(datetime.datetime.now().time())\n \n watch_result(e , start_time, end_time, env.train_index, end_index-start_index, env.get_action(action), reward ,env.profit) \n \n test_profit.append(env.reward*1000)\n test_action.append(action)\n test_profit = np.array(test_profit)\n test_action = np.array(test_action)\n \n # agent.save(\"agent_model.h5\")\n plt.plot(test_profit, color = 'blue', label = 'Profit')\n plt.plot(test_action, color = 'red', label = 'Actions')\n plt.title('Profit&Action')\n plt.xlabel('Time')\n plt.ylabel('Profit')\n plt.legend()\n plt.show()\n\n \n ","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":6355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"173090678","text":"#\n#\nimport typing\n\nfrom pyshacl.consts import SH\nfrom pyshacl.rules.shacl_rule import SHACLRule\n\nfrom .js_executable import JSExecutable\n\n\nif typing.TYPE_CHECKING:\n from pyshacl.shape import Shape\n from pyshacl.shapes_graph import ShapesGraph\n\nSH_JSRule = SH.term('JSRule')\n\n\nclass JSRule(SHACLRule):\n __slots__ = ('js_exe',)\n\n def __init__(self, shape: 'Shape', rule_node):\n super(JSRule, self).__init__(shape, rule_node)\n shapes_graph = shape.sg # type: ShapesGraph\n self.js_exe = JSExecutable(shapes_graph, rule_node)\n\n def apply(self, data_graph):\n focus_nodes = self.shape.focus_nodes(data_graph) # uses target nodes to find focus nodes\n applicable_nodes = self.filter_conditions(focus_nodes, data_graph)\n sets_to_add = []\n for a in applicable_nodes:\n args_map = {\"this\": a}\n results = self.js_exe.execute(data_graph, args_map, mode=\"construct\")\n triples = results['_result']\n if triples is not None and isinstance(triples, (list, tuple)):\n set_to_add = set()\n for t in triples:\n s, p, o = t[:3]\n set_to_add.add((s, p, o))\n sets_to_add.append(set_to_add)\n for s in sets_to_add:\n for t in s:\n data_graph.add(t)\n return\n","sub_path":"pyshacl/extras/js/rules.py","file_name":"rules.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"540316919","text":"#\nimport ShareYourSystem as SYS\n#\n\n#\nclass InstancerClass(\n\t\t\t\t\tSYS.ObjectClass\n\t\t\t\t):\n\n\t#\n\tdef initAfterWithInstancer(self):\n\n\t\t#\n\t\tself.InstancedVariable=None\n\t\tself.InstancingTypeString=\"\"\n\t\tself.InstancingDict={}\n\t\tself.InstancingTuplesList=[]\n\t\t#\n\n\n\tdef callAfterWithInstancer(self,_CallString,*_ArgsList,**_KwargsDict):\n\n\t\tif _CallString==\"Instance\":\n\n\t\t\t#Instancify\n\t\t\tself.InstancedVariable=SYS.getTypedVariableWithVariableAndTypeString(\n\t\t\t\tself.InstancedVariable,\n\t\t\t\tself.InstancingTypeString\n\t\t\t)\n\n\t\t\t#Check if it is ok\n\t\t\tif self.InstancedVariable==None:\n\t\t\t\tprint(\"WARNING in Instancer : didn't find an Instance like \"+self.InstancingTypeString)\n\t\t\telse:\n\t\t\t\t#Give him the InstancingDict\n\t\t\t\tself.InstancedVariable.update(self.InstancingTuplesList)\n\n\t\t\t\t#Give him the InstancingDict\n\t\t\t\tself.InstancedVariable.update(self.InstancingDict)\n\n\t\t#Return self\n\t\treturn self\n\n\t#\n\n\t#\n\tdef bindInstancedVariableAfterWithInstancer(self):\n\n\t\t#Bind with InstancingTypeString setting\n\t\tself.InstancingTypeString=self.InstancedVariable.TypeString\n\t\n\tdef bindInstancingDictAfterWithInstancer(self):\n\n\t\t#Bind with InstancedVariable setting\n\t\tif self.InstancedVariable!=None:\n\t\t\tself.InstancedVariable.update(self.InstancingDict)\n\n\tdef bindInstancingTuplesListAfterWithInstancer(self):\n\n\t\t#Bind with InstancedVariable setting\n\t\tif self.InstancedVariable!=None:\n\t\t\tself.InstancedVariable.update(self.InstancingTuplesList)\n\t#\n\n\t#\n\t#\n\n#\n","sub_path":"Modules/Init/Drafts/_ModulesAncien/01c_Instancer/Instancer.py","file_name":"Instancer.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"57540659","text":"from trac.core import Component, implements\nfrom trac.util.compat import sorted\n\nfrom announcerplugin.api import IAnnouncementAddressResolver\n\nclass SessionEmailResolver(Component):\n implements(IAnnouncementAddressResolver)\n \n def get_address_for_name(self, name, authenticated):\n db = self.env.get_db_cnx()\n cursor = db.cursor()\n cursor.execute(\"\"\"\n SELECT value\n FROM session_attribute\n WHERE sid=%s\n AND authenticated=%s\n AND name=%s\n \"\"\", (name, authenticated and 1 or 0, 'email'))\n result = cursor.fetchone()\n if result:\n return result[0]\n return None\n","sub_path":"announcerplugin/tags/0.11.1/announcerplugin/resolvers/sessionemail.py","file_name":"sessionemail.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"156659718","text":"__all__ = ['CmdError']\n\nclass CmdError(Exception):\n \"\"\" A exception due to commands sent to the ICC. Anything can throw one, passing a one line\n error message. The top-level event loop will close/cleanup/destroy any running command\n and return the error message on distxt.\n \"\"\"\n\n def __init__(self, error, details=None):\n \"\"\" Create a CmdError.\n\n Args:\n error - one line of text, intended for users. Will be returned on distxt.\n details - optional text, intended for operators/programmers. Will be returned on diserrtxt.\n \"\"\"\n\n Exception.__init__(self)\n\n self.error = error\n self.details = details\n if details:\n self.args = (error, details)\n else:\n self.args = error\n","sub_path":"CPL/Exceptions/CmdError.py","file_name":"CmdError.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"148152301","text":"import os, wave\nimport numpy as np\nimport scipy.io.wavfile as wav\nfrom sklearn.cluster import KMeans\nfrom python_speech_features import fbank\nfrom pandas import DataFrame\n\n\ndef hfd(X, Kmax):\n try:\n L = []\n x = []\n N = len(X)\n for k in range(1, Kmax):\n Lk = []\n for m in range(0, k):\n Lmk = 0\n for i in range(1, int(np.floor((N - m) / k))):\n Lmk += abs(X[m + i * k] - X[m + i * k - k])\n Lmk = Lmk * (N - 1) / np.floor((N - m) / float(k)) / k\n Lk.append(Lmk)\n L.append(np.log(np.mean(Lk)))\n x.append([np.log(float(1) / k), 1])\n (p, r1, r2, s) = np.linalg.lstsq(x, L)\n return p[0]\n except Exception as e:\n print('Excepton: ' + str(e));\n return 0;\n\n\ndef feature_extraction(infile,path, label):\n root, dirs, files = next(os.walk(path))\n sr = []\n x = []\n xf = []\n file_index=1\n for file in files:\n if file.lower().endswith('.wav'):\n sr_value, x_value = wav.read(root + '/' + file, 'r')\n sr.append(sr_value)\n x.append(x_value)\n f = []\n length = len(x_value)\n window_hop_length = 0.02 # 2ms = 0.02\n overlap = int(sr_value * window_hop_length)\n window_size = 0.05 # 5 ms = 0.05\n framesize = int(window_size * sr_value)\n number_of_frames = int(length / overlap)\n frames = np.ndarray((number_of_frames, framesize))\n\n # Signal Framing and Transfer To Fractal Dimension\n for k in range(0, number_of_frames):\n for i in range(0, framesize):\n if (k * overlap + i) < length:\n frames[k][i] = x_value[k * overlap + i]\n else:\n frames[k][i] = 0\n # f.append(hfd(frames[k], 6))\n MFCC = fbank(frames[k], sr_value)\n f.append(MFCC[1].mean())\n\n xf.append(f)\n print('FileName: ' + file + ' Row: ' + str(file_index) + ' Of ' + str(len(files)))\n file_index = file_index + 1\n\n features = DataFrame()\n vector_index = 1\n for vector in xf:\n try:\n km = KMeans(n_clusters=100, random_state=42).fit(DataFrame(vector))\n features = features.append(DataFrame(km.cluster_centers_).transpose())\n print('Vector Cluster is Success: ' + str(vector_index) + ' Vector Length: ' + str(len(vector)))\n vector_index = vector_index + 1\n except Exception as e:\n print('Exception in Clustering:' + str(e))\n\n # Add Label Column\n features['label'] = label\n\n # Export Data frame To CSV\n features.to_csv(infile, mode='a', header=False, index=False)\n\n\nif __name__ == '__main__':\n csv_filename = 'D:\\\\Databases\\\\PDA\\\\CSV\\\\feature(Energy-70-30-1400b).csv'\n feature_extraction(csv_filename, 'D:\\\\Databases\\\\PDA\\\\Normal', 0)\n feature_extraction(csv_filename, 'D:\\\\Databases\\\\PDA\\\\StegHide', 1)\n","sub_path":"ReadWaves.py","file_name":"ReadWaves.py","file_ext":"py","file_size_in_byte":3066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"156314250","text":"#!/usr/bin/python\n\n# set battery\nfrom psutil import sensors_battery\n\npercent = round(sensors_battery().percent)\ncharging = sensors_battery().power_plugged\n\nif percent <= 20 and not charging:\n import gi\n gi.require_version('Notify', '0.7')\n from gi.repository import Notify\n Notify.init(\"BAT\")\n notify = Notify.Notification.new(\n \"Low battery\",\n \"Only \"+str(percent)+\"% left\",\n \"BAT\")\n notify.show()\nelif percent >= 95 and charging:\n import gi\n gi.require_version('Notify', '0.7')\n from gi.repository import Notify\n Notify.init(\"BAT\")\n notify = Notify.Notification.new(\n \"Full battery\",\n \"Charged more than \"+str(percent)+\"%\",\n \"BAT\")\n notify.show()\n","sub_path":"checkbat.py","file_name":"checkbat.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"332328133","text":"import struct\nfrom abc import ABC, abstractmethod\n\nclass Processor(ABC):\n \n def __init__(self, raw_data: list):\n self.data = raw_data\n self.final_data = dict()\n \n @abstractmethod\n def process_data(self):\n \"\"\"\n Reads in the data from a file and stores it in a formatted JSON object.\n \"\"\"\n pass\n\n\nclass BinaryProcessor:\n \n def __init__(self, header: dict, raw_data: list):\n \"\"\"\n The Processor class reads in the file header and raw data, \n extracts key readings from the data, and then formats it in JSON.\n \n Args:\n header (dictionary): a file's header information (every RSP file contains a header)\n raw_data (list): a file's extracted data, formatted into a list of dictionaries\n\n Attributes:\n header (dictionary): a file's header information (every RSP file contains a header)\n raw_data (list): a file's extracted data, formatted into a list of dictionaries\n final_data (dictionary): a file's processed data, formatted into a JSON object. \n Concatenation of the header and the scan data.\n\n Note:\n Final data format is as follows:\n {\n 'header':\n {\n 'experiment': experiment,\n etc.\n },\n \n 'data':\n [\n {\n 'scan_id': scan_id,\n 'scan_count': scan_count,\n 'temperature_error': temp_error\n 'temperatures': temps,\n 'voltages': volts\n },\n {\n 'scan_id': scan_id,\n 'scan_count': scan_count,\n 'temperature_error': temp_error\n 'temperatures': temps,\n 'voltages': volts\n },\n etc.\n \n ]\n }\n \"\"\"\n \n self.header = header\n self.data = raw_data\n self.scans = list()\n \n self.final_data = dict()\n \n def process_data(self) -> None:\n \"\"\"\n Processes every piece of information found in a scan, and \n begins to build a list of scans. Once the list is complete,\n it prepares the JSON object for exporting.\n\n A single scan format is as follows:\n {\n 'scan_id': scan_id,\n 'scan_count': scan_count,\n 'temperature_error': temp_error\n 'temperatures': temps,\n 'voltages': volts\n }\n \"\"\"\n for data in self.data:\n # Create empty scan\n scan = dict()\n # Fill with data\n scan[\"scan_id\"] = data[\"scan_id\"]\n scan[\"scan_count\"] = data[\"scan_count\"]\n scan[\"temperature_error\"] = data[\"instrument_housekeeping\"][0] / (-84.38) + 245.2 - 150.7\n # Calculate temperatures\n scan[\"temperatures\"] = self.calc_temps(data[\"instrument_temp\"])\n # Calculate voltages\n scan[\"voltages\"] = self.calc_volts(data[\"instrument_housekeeping\"])\n self.scans.append(scan)\n \n # Format properly\n self.prep_json()\n\n def calc_temps(self, data: dict) -> list:\n \"\"\"\n Calculates the different temperature measurements and returns them in a list.\n\n Args:\n data (list): the list of raw temperature readings\n\n Returns:\n temps (list): the list of processed temperatures\n \"\"\"\n temps = list()\n\n temps.append([data[0] / (-54.34) + 417.2 - 2.0,\n data[1] / (-54.34) / 1.037 + 417.2 - 4.6,\n data[2] / (-54.34) / 1.0294 + 417.2 - 2.9,\n data[3] / (-54.34) / 1.033 + 417.2 - 4.5,\n data[4] / (-54.34) / 1.0294 + 417.2 - 1.5,\n data[5] / (-54.34) / 1.037 + 417.2 - 1.6,\n data[6] / (-65.37) + 343.8,\n data[7] / (-65.37) + 343.8 - 273.16 + 5.3,\n data[8] / (-65.37) + 343.8 - 273.16 + 4.0])\n \n return temps\n \n def calc_volts(self, data: dict) -> list:\n \"\"\"\n Calculates the different temperature measurements and returns them in a list.\n\n Args:\n data (list): the list of raw voltages\n\n Returns:\n temps (list): the list of processed voltages\n\n Voltages are as follows:\n 1) unknown\n 2) +12V\n 3) -12V\n 4) +5V \n 5) -5V \n 6) +5DIG \n 7) ADC8(dn)\n 8) ADC9(dn)\n \"\"\"\n volts = list()\n\n volts.append([data[1] - 3618,\n data[2] / 44.6 - 17.36,\n data[3] / (-212.0) + 48.58,\n data[4] / 44.6 - 17.71,\n data[5] / (-212.0) + 48.55,\n data[6] / 44.6 - 17.03,\n data[7],\n data[8]])\n\n return volts\n \n def prep_json(self) -> None:\n \"\"\"\n Final step in the processing: formats it to make sure data is JSON compliant.\n \"\"\"\n self.final_data[\"header\"] = self.header\n self.final_data[\"data\"] = self.scans\n\n \nclass SimpleProcessor(Processor):\n \n def __init__(self, raw_data: list):\n super().__init__(raw_data)\n\n def process_data(self):\n self.final_data = self.data\n","sub_path":"rsp_data_extractor/classes/processor.py","file_name":"processor.py","file_ext":"py","file_size_in_byte":5490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"118183541","text":"\"\"\"\nMIT License\n\nCopyright (c) 2019 Ali Mert Ceylan, Adopted from original resources provided\nby Korhan Karabulut for COMP 5658 Modern Heuristics Course\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\n\nfrom typing import List\nfrom math import sqrt\nfrom Genome import Genome\n\nclass ZDTOne:\n\n def values(self, genome:Genome)->List[float]:\n objectives:List[float] = [.0 for i in range(genome.nobjectives)]\n objectives[0] = genome.variable(0)\n\n sumv:float = 0\n for i in range(genome.nvariables):\n sumv+=genome.variable(i)\n g = 1 + (9.0 / (genome.nvariables -1)) * sumv\n objectives[1] = g*(1-sqrt(objectives[0]/g))\n\n return objectives\n","sub_path":"MO/ZDT.py","file_name":"ZDT.py","file_ext":"py","file_size_in_byte":1673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"305505026","text":"# Author: Brittany Guilbert\n# TCSS 372 Project 1\n# Due: 11/15/19\n\n# This class has the current status of variables that need to be accessed by the front and backend,\n# it is a singleton so that there is only one\n\nclass CurrentStatus():\n\n __instance = None\n @staticmethod \n def getInstance():\n \"\"\" Static access method. \"\"\"\n if CurrentStatus.__instance == None:\n CurrentStatus()\n return CurrentStatus.__instance\n \n def __init__(self):\n self.myCurrentFilename = ''\n self.myRegisterList = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\n self.myDisplayAssembly = ''\n self.myRegisterNames= ['$zero', '$v0', '$v1', '$a0', '$a1','$a2','$a3','$t0','$t1','$t2',\n '$t3','$t4','$t5','$t6','$t7','$s0','$s1','$s2','$s3','$s4','$s5',\n '$s6','$s7','$t8','$t9','$k0','$k1','$gp','$sp','$fp','$ra','pc','hi','lo']\n\n self.myRunLineNum = 0\n self.myStepBool = True\n self.myListOfErrors=[\"No Errors yet\"]\n self.lengthOfUploadedFile=0\n self.mipssimulatorRunIsComplete= True\n self.myCurrentFilepath =''\n self.myAddresses= []\n self.myNumberOfAddresses=0\n self.myAddressInstructions=[]\n \n \"\"\" Virtually private constructor. \"\"\"\n if CurrentStatus.__instance != None:\n raise Exception(\"This class is a singleton!\")\n else:\n CurrentStatus.__instance = self\n","sub_path":"gui/currentStatus.py","file_name":"currentStatus.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"236512296","text":"import numpy as np\nimport scipy.optimize as optimize\n\nfrom bet.strategy import Strategy\n\ndef kelly_function(params, odds, probabilities):\n a, b, c = params\n o1, o2, o3 = odds\n p1, p2, p3 = probabilities\n return -(p1 * np.log(1 + o1*a - b - c) + p2 * np.log(1 + o2*b - a - c) + p3*np.log(1 + o3*c - a - b))\n\ndef kelly_function_deriv(params, odds, probabilities):\n a, b, c = params\n o1, o2, o3 = odds\n p1, p2, p3 = probabilities\n dfda = -(p1 * o1)/(o1*a-b-c+1) + p2/(o2*b-a-c+1) + p3/(o3*c-b-a+1)\n dfdb = p1/(o1*a-b-c+1) - (p2 * o2)/(o2*b-a-c+1) + p3/(o3*c-b-a+1)\n dfdc = p1/(o1*a-b-c+1) + p2/(o2*b-a-c+1) - (p3*o3)/(o3*c-b-a+1)\n return np.array([dfda, dfdb, dfdc])\n\ndef constraint(x):\n return 1.00000001 - (x[0]+x[1]+x[2])\n\nclass KellyStrategy(Strategy):\n def __init__(self, outcomes, initial_capital=64):\n super().__init__(initial_capital=initial_capital)\n self.outcomes = outcomes\n self.max_iterations = 20\n\n self.opf = []\n\n def get_optimal_fractions(self, odds, probabilities):\n args = (odds, probabilities)\n bounds = ((0.0, 1.0), (0.0, 1.0), (0.0, 1.0))\n cons = {'type': 'ineq', 'fun': constraint}\n for i in range(self.max_iterations):\n initial_guess = [0.05, 0.05, 0.05]\n result = optimize.minimize(\n kelly_function,\n initial_guess,\n bounds=bounds,\n constraints=cons,\n args=args,\n jac=kelly_function_deriv\n )\n\n if result.success:\n break\n else:\n initial_guess = np.random.uniform(low=0.005, high=0.1, size=3)\n if i + 1 == self.max_iterations:\n return [0.0, 0.0, 0.0]\n\n fs = result.x\n for i, f in enumerate(fs):\n if f < 0.0001:\n fs[i] = 0\n return fs\n\n def get_odds_probabilities_and_fractions(self):\n return self.opf\n\n def run(self, odds, probabilities, coef=0.3):\n for _, (match_odds, match_probabilities, outcome) in enumerate(zip(odds, probabilities, self.outcomes)):\n net_match_odds = match_odds - 1\n bet_fractions = self.get_optimal_fractions(net_match_odds, match_probabilities)\n\n self.opf.append(list(zip(match_odds, match_probabilities, bet_fractions)))\n\n cost = 0\n returns = 0\n for k, (odd, fraction) in enumerate(zip(match_odds, bet_fractions)):\n bet_size = self.balance * fraction * coef\n if bet_size < 0.1:\n bet_size = 0\n cost += bet_size\n if outcome == 1 - k:\n returns += bet_size * odd\n self.update_balance(returns - cost)\n self.store_cost(cost)\n","sub_path":"bet/kelly_strategy.py","file_name":"kelly_strategy.py","file_ext":"py","file_size_in_byte":2814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"572778788","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nLoad raw bus route data\nThis function loads a specified file and returns a dictionary of pandas\ndataframes where the items are the time and GPS coordinates of one bus\nrunning along a route.\n\nParameters\n----------\n first : filename\n name of the .npz file to open (including extension)\n second : year\n Year when data was genereated\n third : month\n Month when data was generated\n fourth : day\n Day when data was generate\n\nReturns\n-------\n dfDict\n A dictionary containing pandas arrays with the timestamps and GPS\n data (zero-padded so they're uniform size)\n \nRaises\n------\n IOError\n When file not found\n \n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport time\nfrom datetime import date\n\n\ndef loadRawData(filename,year,month,day):\n # First let's load the data into numpy arrays\n dataIn = np.load(filename)\n \n # Copy it into a less shitty format (not a NpzFile class)\n newDataIn = dict(dataIn)\n \n # Get the (Unix) timestamp for this day's data:\n d = date(year, month, day)\n t0 = time.mktime(d.timetuple())\n \n # Bus stop we care about (kind of...):\n # 45.538254 -73.601215\n # 0.0005\n \n \n dfDict = dict()\n \n # Zero the timestamps, save to dictionary of dataframes:\n i = 0\n for key in newDataIn.keys():\n newDataIn[key][:,0] -= t0\n dfDict[i] = pd.DataFrame(newDataIn[key],columns = ['Time','Lat','Long'])\n i += 1\n \n # Get the longest one:\n longestRun = max(len(dfDict[key]) for key in dfDict.keys())\n stDevRuns = np.std([len(dfDict[key]) for key in dfDict.keys()])\n \n dfZeroPad = pd.DataFrame([[0,0,0]],columns = ['Time','Lat','Long'])\n for key in dfDict.keys():\n if(len(dfDict[key]) < longestRun-2*stDevRuns):\n del dfDict[key] # Purge anything way out-of-whack\n elif(len(dfDict[key]) 0.1 and aspect_ratio < 1 and area >= 650 and equi_diametro >= 32 and extension >= 0.1):\n (x, y, w, h) = cv2.boundingRect(cnt)\n #cv2.drawContours(img,[cnt],0,(0,0,255),-1,4)\n cv2.rectangle(img, (x,y), (x+w,y+h), (255, 0, 0), 2)\n solidez = float(area)/hull_area\n \n \n Plate = img[y:y+h,x:x+w] \n caracteres.append(img[y:y+h,x:x+w])\n \n \n numero += 1 \n print (i)\n print (numero ,'\\n')\n print(\"X: \", x ,'\\n' \n \"Y: \", y, '\\n'\n \"W: \", w , '\\n'\n \"H: \", h, '\\n'\n \"Y+H: \",y+h, '\\n'\n 'X+W: ',x+w, '\\n' \n \"area: \",area ,'\\n'\n 'aspect_ratio...1: ',aspect_ratio, '\\n'\n 'Extension: ',extension, '\\n'\n 'Solidez: ',solidez, '\\n'\n 'Diametro: ',equi_diametro, '\\n'\n 'PIXEL: ',len(pixelpoints), '\\n' \n \"-------------------------------------------------------\",'\\n')\n \n \n print ('caracteres: ',len(caracteres), '\\n')\n \n \n \n cv2.namedWindow('img', cv2.WINDOW_NORMAL)\n cv2.imshow('img', img)\n cv2.waitKey()\n\n \n \n '''cv2.namedWindow('img4', cv2.WINDOW_NORMAL)\n cv2.imshow('img4', edge)\n cv2.waitKey()'''\n \n\n \n \n\n \n cv2.destroyAllWindows()","sub_path":"este fue.py","file_name":"este fue.py","file_ext":"py","file_size_in_byte":3002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"58319512","text":"import logging\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom sklearn.metrics import roc_auc_score, average_precision_score\r\nimport config\r\nimport model\r\n\r\n\r\nclass SBM:\r\n def __init__(self, data_graph):\r\n self.data_graph = data_graph\r\n self.sbm_mat = self.data_graph.get_sbm_matrix()\r\n\r\n def test(self, pos_edge_index, neg_edge_index):\r\n\r\n pos_y = np.ones(pos_edge_index.size(1))\r\n neg_y = np.zeros(neg_edge_index.size(1))\r\n y = np.hstack([pos_y, neg_y])\r\n\r\n pos_pred = self.sbm_mat[pos_edge_index[0], pos_edge_index[1]]\r\n neg_pred = self.sbm_mat[neg_edge_index[0], pos_edge_index[1]]\r\n pred = np.hstack([pos_pred, neg_pred])\r\n\r\n mae_pos = np.sum(np.ones(len(pos_pred)) - pos_pred) / len(pos_pred)\r\n mae_neg = np.sum(neg_pred - np.zeros(len(neg_pred))) / len(neg_pred)\r\n\r\n return roc_auc_score(y, pred), average_precision_score(y, pred), (mae_pos + mae_neg) / 2\r\n\r\n def run(self):\r\n auc, ap, mae = self.test(self.data_graph.test_pos_edge_index, self.data_graph.get_test_neg_edge())\r\n return (pd.DataFrame([], columns=['AUC', 'AP', 'MAE', 'TYPE', 'EPOCH']),\r\n pd.DataFrame([[auc, ap, mae, 'test', 0]], columns=['AUC', 'AP', 'MAE', 'TYPE', 'EPOCH']))\r\n\r\n\r\ndef run(rnd_seed=123):\r\n config.DISTANCE_CONSTRAINT = False # distance constrains are not used here\r\n return model.run(SBM, rnd_seed)\r\n\r\n\r\nif __name__ == '__main__':\r\n logging.basicConfig(level=logging.CRITICAL, datefmt=\"%H-%M-%S\", format=\"%(asctime)s %(message)s\")\r\n datasets = [\"Cora\", \"Pubmed\", \"Citeseer\", \"WikiCS\", \"Actor\", \"Cornell\", \"Texas\", \"Wisconsin\"]\r\n for dataset in datasets:\r\n config.DATASET = dataset\r\n all_best_metric = pd.DataFrame()\r\n for seed in range(10):\r\n _metric, _best_metric = run(seed)\r\n all_best_metric = all_best_metric.append(_best_metric)\r\n print(dataset)\r\n print(all_best_metric.mean())\r\n print(all_best_metric.std())\r\n","sub_path":"sbm.py","file_name":"sbm.py","file_ext":"py","file_size_in_byte":2001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"362154208","text":"import functools\nimport json\nimport logging\n\nfrom django.conf import settings\nfrom django import http\nfrom django.utils import decorators\n\nfrom sparkbench import exceptions as own_exceptions\n\nlog = logging.getLogger(__name__)\n\nhttp_errors = (http.Http404, own_exceptions.Http400)\n\n\nclass _RestResponse(http.HttpResponse):\n @property\n def json(self):\n content_type = self['Content-Type']\n if content_type != 'application/json':\n raise ValueError(\"content type is %s\" % content_type)\n body = self.content.decode('utf-8')\n return json.loads(body)\n\n\nclass CreatedResponse(_RestResponse):\n def __init__(self, location, data=None):\n if data is not None:\n content = json.dumps(data, sort_keys=settings.DEBUG)\n content_type = 'application/json'\n else:\n content = ''\n content_type = None\n super(CreatedResponse, self).__init__(status=201, content=content,\n content_type=content_type)\n self['Location'] = location\n\n\nclass JSONResponse(_RestResponse):\n def __init__(self, data, status=200, json_encoder=json.JSONEncoder):\n if status == 204:\n content = ''\n else:\n content = json.dumps(data, sort_keys=settings.DEBUG,\n cls=json_encoder)\n\n super(JSONResponse, self).__init__(\n status=status,\n content=content,\n content_type='application/json',\n )\n\n\ndef ajax(data_required=False,\n json_encoder=json.JSONEncoder):\n\n def decorator(function, data_required=data_required):\n @functools.wraps(function,\n assigned=decorators.available_attrs(function))\n def _wrapped(self, request, *args, **kw):\n if not request.is_ajax():\n return JSONResponse('request must be AJAX', 400)\n\n # decode the JSON body if present\n request.DATA = None\n request_body = request.read()\n if request_body:\n try:\n request.DATA = json.loads(request_body)\n except (TypeError, ValueError) as e:\n return JSONResponse('malformed JSON request: %s' % e, 400)\n\n if data_required:\n if not request.DATA:\n return JSONResponse('request requires JSON body', 400)\n\n # invoke the wrapped function, handling exceptions sanely\n try:\n data = function(self, request, *args, **kw)\n if isinstance(data, http.HttpResponse):\n return data\n elif data is None:\n return JSONResponse('', status=204)\n return JSONResponse(data, json_encoder=json_encoder)\n except http_errors as e:\n # exception was raised with a specific HTTP status\n if hasattr(e, 'http_status'):\n http_status = e.http_status\n elif hasattr(e, 'code'):\n http_status = e.code\n else:\n log.exception('HTTP exception with no status/code')\n return JSONResponse(str(e), 500)\n return JSONResponse(str(e), http_status)\n except Exception as e:\n log.exception('error invoking apiclient')\n return JSONResponse(str(e), 500)\n\n return _wrapped\n return decorator\n","sub_path":"sparkbench/api/rest/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"359843001","text":"#!/usr/bin/env python\nfrom __future__ import print_function\nimport os, numpy, logging\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # no info output from tensorflow\nimport AliMLLoader, AliMLModels, AliMLHelpers, AliMLAnalysisTools, AliMLManager\nimport AliMLTreeInput\n\nnumpy.random.seed(7331) # for reproducibility\n\n#######################################################################################################\n#### SETTINGS\n\ngNumEpochs = 50 # number of training epochs\ngNumEventsTraining = 50000 # training events per class\ngNumEventsValidation = 10000 # validation events per class\ngEventChunkSize = 50000 # event chunk size\ngEventOffset = 0 # offset after which the events are used for training\n\n\n########## OPTIONS\ngLoadModel = False # load model\ngDoTraining = True # Train the model\ngDoUserAnalysis = False # User analysis\n\n# User defined schemes that will be used\ngSchemes = ['SimpleModel'] \n\n\ngUserModule = AliMLTreeInput\ngDataGenerator = gUserModule.GetGenerator()\n\ngDataset = 0\n\n#######################################################################################################\ndef Run():\n \"\"\"Main control function\"\"\"\n\n if gDoTraining or gDoUserAnalysis:\n for scheme in gSchemes:\n model = gUserModule.GetModel(scheme, gLoadModel)\n dataset = gUserModule.GetDataset(gDataset)\n if gDoTraining:\n AliMLManager.DoTraining(model, dataset, gDataGenerator, gNumEpochs, gNumEventsTraining, gNumEventsValidation, gEventChunkSize, gEventOffset)\n if gDoUserAnalysis:\n DoUserAnalysis(model, dataset)\n\n\n#######################################################################################################\ndef DoUserAnalysis(model, dataset):\n \"\"\"Place analysis etc. here\"\"\"\n logging.info('User-defined analysis done.')\n\n\n#######################################################################################################\n\ntry:\n Run()\nexcept:\n AliMLHelpers.NotifyError()\n raise\nelse:\n AliMLHelpers.NotifyDone()\n","sub_path":"AliMLRunAnalysisExample.py","file_name":"AliMLRunAnalysisExample.py","file_ext":"py","file_size_in_byte":2156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"560982085","text":"# Open File in Read Mode\nfile_1 = open('file.txt', 'r')\nfile_2 = open('file1.txt', 'r')\n \nprint(\"Comparing files \", \" @ \" + 'file.txt', \" # \" + 'file1.txt', sep='\\n')\n \nfile_1_line = file_1.readline()\nfile_2_line = file_2.readline()\n \n# Use as a COunter\nline_no = 1\n \nprint()\n \nwith open('file.txt') as file1: \n with open('file1.txt') as file2:\n same = set(file1).intersection(file2)\n \nprint(\"Common Lines in Both Files\")\n\nfor line in same:\n print(line, end='')\n print('\\n')\nprint(\"Difference Lines in Both Files\")\nwhile file_1_line != '' or file_2_line != '':\n # Removing whitespaces\n file_1_line = file_1_line.rstrip()\n file_2_line = file_2_line.rstrip()\n \n # Compare the lines from both file\n if file_1_line != file_2_line:\n \n # otherwise output the line on file1 and use @ sign\n if file_1_line == '':\n print(\"@\", \"Line-%d\" % line_no, file_1_line)\n else:\n print(\"@-\", \"Line-%d\" % line_no, file_1_line)\n \n # otherwise output the line on file2 and use # sign\n if file_2_line == '':\n print(\"#\", \"Line-%d\" % line_no, file_2_line)\n else:\n print(\"#+\", \"Line-%d\" % line_no, file_2_line)\n \n # Print a empty line\n print()\n \n # Read the next line from the file\n file_1_line = file_1.readline()\n file_2_line = file_2.readline()\n \n line_no += 1\n \nfile_1.close()\nfile_2.close()","sub_path":"check_string.py","file_name":"check_string.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"538845813","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport datetime as dt\n\n\n\n# import and normalize data - remove null with 0\ndf=pd.read_csv('india_newcase_newdeath.csv')\ndf['Daily new cases'] = df['Daily new cases'].fillna(0)\ndf['Daily new deaths'] = df['Daily new deaths'].fillna(0)\n\nnewCase = df['Daily new cases']\nnewDeath = df['Daily new deaths']\n\nsumNewCase = df['Daily new cases'].sum()\nsumNewDeath = df['Daily new deaths'].sum()\n\npercentageNewCase = df['Daily new cases']*100/sumNewCase\npercentageNewDeath = df['Daily new deaths']*100/sumNewDeath\n\n\n\n\n\nwindowSize = 7\n\n# modify data\n# 7-day moving average\ndateData = df['Date'][6:]\n\n# newCase\nnewCaseSeries = pd.Series(percentageNewCase)\n\nwindowsNewCase = newCaseSeries.rolling(windowSize)\n\nmovingAvrNewCase = windowsNewCase.mean()\nprint(movingAvrNewCase)\nmovingAvrNewCaseList = movingAvrNewCase.tolist()\n\navrNewCaseWithNoNaN = movingAvrNewCaseList[windowSize - 1:]\n\n# newDeath\nnewDeathSeries = pd.Series(percentageNewDeath)\n\nwindowsNewDeath = newDeathSeries.rolling(windowSize)\n\nmovingAvrNewDeath = windowsNewDeath.mean()\n\nmovingAvrNewDeathList = movingAvrNewDeath.tolist()\n\navrNewDeathWithNoNaN = movingAvrNewDeathList[windowSize - 1:]\n\n\n\n# Line plot\n#multiple lines plot\nfig=plt.figure(figsize=(10,6))\nx_date = [dt.datetime.strptime(d, '%d/%m/%Y').date() for d in dateData]\nplt.plot(x_date, avrNewCaseWithNoNaN, label=\"New Cases\")\nplt.plot(x_date, avrNewDeathWithNoNaN, label=\"New Deaths\")\n\n\nplt.ylabel('Percentage of Total (each type) (%)')\nplt.legend()\n\n# show graph\nplt.show()\n\n\n\n","sub_path":"BTVN/Lab 01/18120211_18120238_18120246_18120254_Lab01/Code/LineMovingAverage.py","file_name":"LineMovingAverage.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"639280748","text":"#To select data from a collection in MongoDB, we can use the find_one() method\r\nimport pymongo\r\n\r\nmyclient = pymongo.MongoClient(\"mongodb://localhost:27017/\")\r\nmydb = myclient[\"mydatabase\"]\r\nmycol = mydb[\"customers\"]\r\n\r\n\"\"\"x = mycol.find_one()\r\nprint(x)\"\"\"\r\n#The find() method returns all occurrences in the selection\r\n\"\"\"for x in mycol.find():\r\n print(x)\"\"\"\r\n#Return Only Some Fields\r\n#Return only the names and addresses, not the _ids\r\n\"\"\"for x in mycol.find({},{ \"_id\": 0, \"name\": 1, \"address\": 1 }):\r\n print(x) \"\"\"\r\n#You are not allowed to specify both 0 and 1 values in the same object \r\n\r\n\r\n#This example will exclude \"address\" from the result\r\n\"\"\"for x in mycol.find({},{ \"address\": 0 }):\r\n print(x)\"\"\"\r\n\r\n#You get an error if you specify both 0 and 1 values in the same object (except if one of the fields is the _id field):\r\nfor x in mycol.find({},{ \"name\": 1, \"address\": 0 }):\r\n print(x)","sub_path":"ppendterm/MongoDB/find.py","file_name":"find.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"270516248","text":"# Use API to get the jobseach results\nfrom serpapi import GoogleSearch\nimport json\n\n\n\n\nparams = {\n \"engine\": \"google_jobs\",\n \"q\": \"data analysis\",\n \"hl\": \"en\",\n \"api_key\": \"a463df1e2c78e577d9220ceeba3d0f6cc418db1a445ed7520d0fc6b0c62ab95a\",\n \"location_requested\": \"Austin,Texas,United States\"\n}\nclient = GoogleSearch(params)\nresults = client.get_dict()\nresults = results['jobs_results']\n\n\nwith open('job-results.json', 'w') as fp:\n json.dump(results, fp)\n\n\n\n\nCACHE_FILE_NAME = 'job-results.json'\n\ndef load_cache():\n try:\n cache_file = open(CACHE_FILE_NAME,'r')\n cache_file_contents = cache_file.read()\n cache = json.loads(cache_file_contents)\n cache_file.close()\n except:\n cache = {}\n return cache\n \ndef save_cache(cache):\n cache_file = open(CACHE_FILE_NAME,'w')\n contents_to_write = json.dumps(cache)\n cache_file.write(contents_to_write)\n cache_file.close()\n \ndef make_url_request_using_cache(results):\n cache = load_cache()\n l = []\n for i in results:\n if i in cache:\n dic = {}\n dic['job'] = i['title']\n dic['company_name'] = i['title']\n l.append(dic)\n print('Using cache')\n print(dic)\n print('----------------------------------------------------------')\n \n else:\n save_cache(i)\n dic = {}\n dic['job'] = i['title']\n dic['company_name'] = i['title']\n l.append(dic)\n print('Fetching')\n\n return l\n\n \n \n \n\n","sub_path":"API.py","file_name":"API.py","file_ext":"py","file_size_in_byte":1576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"198394032","text":"from apiclient import discovery\nfrom oauth2client import client\nfrom oauth2client import tools\nfrom oauth2client.file import Storage\nimport os\nimport httplib2\nimport json\nimport time\n\ntry:\n import argparse\n flags = argparse.ArgumentParser(parents=[tools.argparser],description='').parse_args()\nexcept ImportError:\n flags = None\n\nFilepath='./OAuth/'\n\ndef get_credentials():\n \"\"\"\n Gets valid user credentials from storage.\n\n If nothing has been stored, or if the stored credentials are invalid,\n the OAuth2 flow is completed to obtain the new credentials.\n\n Returns:\n Credentials, the obtained credential.\n \"\"\"\n #home_dir = os.path.expanduser('~')\n\n credential_dir = os.path.join(Filepath, '.credentials')\n\n CLIENT_SECRET_FILE='./OAuth/client_secret.json'\n\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir,'drive-python-quickstart.json')\n\n if not os.path.exists(CLIENT_SECRET_FILE):\n print('**Not find Client_Secret_FIle**')\n else: \n SCOPES = ['https://www.googleapis.com/auth/youtube.force-ssl']\n store = Storage(credential_path)\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\n if flags:\n credentials = tools.run_flow(flow, store, flags)\n else: \n credentials = tools.run_flow(flow, store)\n print('Storing credentials to ' + credential_path)\n \n return credentials\n\nif __name__ == \"__main__\":\n get_credentials()","sub_path":"OldVersion/OAuth/APIOAuth.py","file_name":"APIOAuth.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"247892625","text":"import sys\nfrom collections import defaultdict\n\nfilename = sys.argv[1]\npref = defaultdict(int)\n\nwith open(filename) as f:\n line = f.readline()\n while line:\n pref[line.split()[0]] += 1\n line = f.readline()\n\nfor k, v in sorted(pref.items(), key=lambda x: x[1], reverse=True):\n print(k, v)\n","sub_path":"unixCmd/freq.py","file_name":"freq.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"423560435","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Author: Arne Neumann \n\nimport argparse\nimport json\nimport logging\nfrom pathlib import Path\nimport sys\n\nimport pytest\nimport requests\n\nfrom stagedp.parser_wrapper import load_parser, parse_text\n\nREPO_ROOT_PATH = Path(__file__).parent.parent # root directory of the repo\nREPO_PACKAGE_PATH = REPO_ROOT_PATH.joinpath('src/stagedp')\nFIXTURES_PATH = REPO_ROOT_PATH.joinpath('tests/fixtures')\n\nRST_PARSER, CORE_NLP, ANNOTATION_FUNC, BROWN_CLUSTERS = load_parser()\n\n\ndef test_rst_short():\n input_text = FIXTURES_PATH.joinpath('input_short.neuraleduseg.inline').read_text()\n expected_output = FIXTURES_PATH.joinpath('output_short.txt').read_text()\n result = parse_text(input_text, rst_parser=RST_PARSER, annotate_func=ANNOTATION_FUNC, brown_clusters=BROWN_CLUSTERS)\n assert result == expected_output\n\ndef test_rst_long():\n input_text = FIXTURES_PATH.joinpath('input_long.neuraleduseg.inline').read_text()\n expected_output = FIXTURES_PATH.joinpath('output_long.txt').read_text()\n result = parse_text(input_text, rst_parser=RST_PARSER, annotate_func=ANNOTATION_FUNC, brown_clusters=BROWN_CLUSTERS)\n assert result == expected_output\n\ndef test_rst_eurostar():\n input_text = FIXTURES_PATH.joinpath('input_eurostar.neuraleduseg.inline').read_text()\n expected_output = FIXTURES_PATH.joinpath('output_eurostar.txt').read_text()\n result = parse_text(input_text, rst_parser=RST_PARSER, annotate_func=ANNOTATION_FUNC, brown_clusters=BROWN_CLUSTERS)\n assert result == expected_output\n","sub_path":"tests/test_cli.py","file_name":"test_cli.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"178273858","text":"from random import randint as rd\n\ndef generar_dic(n):\n res = {}\n for i in range(n):\n res.update({f\"jugador{i+1}\": rd(0, 20)})\n return res\n\ndef generar_list(dic):\n res = []\n for i in dic:\n res.append({i: dic[i]})\n return res\n\ndef bubble_sort(arr):\n for i in range(len(arr) - 1, 0, -1):\n for j in range(i):\n if arr[j][list(arr[j].keys())[0]] > arr[j+1][list(arr[j+1].keys())[0]]:\n arr[j], arr[j+1] = arr[j+1], arr[j]\n\ndef binary_search(arr, n):\n if len(arr) == 1:\n return \"No se encuentra\"\n\n mid = len(arr)//2\n if arr[mid][list(arr[mid].keys())[0]] == n:\n return arr[mid]\n\n elif arr[mid][list(arr[mid].keys())[0]] < n:\n return binary_search(arr[mid:], n)\n\n elif arr[mid][list(arr[mid].keys())[0]] > n:\n return binary_search(arr[:mid], n)\n\nnum = int(input(\"Ingrese N: \"))\n\ndic = generar_dic(num)\nlista = generar_list(dic)\nprint(lista)\n\npuntuacion = int(input(\"Ingrese dato a buscar: \"))\n\nbubble_sort(lista)\nprint(lista)\n\nres = binary_search(lista, puntuacion)\n\nprint(\"Respuesta: \")\nprint(res)\n","sub_path":"2021-1/s16/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"473797551","text":"#!/usr/bin/python3\nimport numpy\nimport pandas as pd\n\n# Set working directory\nimport os\nos.chdir(\"/home/suvar/github/dap/DATA/Wine_classification/\")\n\n# Import from keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.utils import np_utils\n\n# Import data\nwine = pd.read_csv('Wine.txt', sep='\\t', header=0)\nwine.head()\n\nwine['Desired1(3)'].value_counts(normalize=True)\n\n# Split predictors and response\n# Response - group variable - vector y\ny = wine['Desired1(3)']\n# Predictors - table X\nX = wine.drop('Desired1(3)', axis=1)\n\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=12345, test_size=0.33)\n\nX_train.head()\nX_test.head()\ny_train.head()\ny_test.head()\n\n# Transform pandas pandas dataframe to numpy array\nX_train = X_train.values\nX_test = X_test.values\ny_train = y_train.values\ny_test = y_test.values\n\n# Check if works\ny_train_bin.head()\n\ny_train_bin[0:5]\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense\n\n# Creating a model\nmodel = Sequential()\nmodel.add(Dense(9, input_dim=13, activation='relu'))\nmodel.add(Dense(10, activation='relu', ))\nmodel.add(Dense(3, activation='softmax'))\n\n# Compiling model\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n\n# Training a model\nmodel.fit(X_train, y_train_bin, epochs=300, batch_size=10)\n\n# evaluate the model\nscores = model.evaluate(X_test, y_test_bin)\nprint(\"\\nAccuracy: %.2f%%\" % (scores[1]*100))\n\n# calculate predictions\npredictions = model.predict(X_test)\n# round predictions\n# rounded = [round(x[0]) for x in predictions]\n# print(rounded)","sub_path":"011_NN_01.py","file_name":"011_NN_01.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"542003737","text":"# Python 3 program for Elo Rating \nimport math \nimport pandas as pd\nfrom math import log\n\ndf = pd.read_csv(\"match_results_1995_to_2018_ELO.csv\")\n\n\n# Function to calculate the Probability \ndef Probability(teamhome, teamaway): \n \n return 1.0 * 1.0 / (1 + 1.0 * math.pow(10, 1.0 * (teamaway - teamhome) / 400)) \n\n# Function to calculate Elo rating \n# K is a constant.\n# d determines whether \n# Home team wins or Away team. \ndef EloRating(Ratinghome, Ratingaway, diff, K, d): \n\n # To calculate the Winning \n # Probability of away team \n\n Ratinghome = Ratinghome + 75\n Paway = Probability(Ratingaway, Ratinghome) \n \n # To calculate the Winning \n # Probability of home team \n Phome = Probability(Ratinghome, Ratingaway) \n Ratinghome = Ratinghome - 75\n\n mov = log(abs(diff) + 1)\n #mov = 1\n cor = 2.2 / ((Phome - Paway)*.001 + 2.2)\n #cor = 1\n \n # Case -1 When Home team wins \n # Updating the Elo Ratings \n if (d == 1) : \n Ratinghome = Ratinghome + cor * mov * K * (1 - Phome) \n Ratingaway = Ratingaway + cor * mov * K * (0 - Paway) \n \n # Case -2 When Away team wins \n # Updating the Elo Ratings \n elif (d == 0) : \n Ratinghome = Ratinghome + cor * mov * K * (0 - Phome) \n Ratingaway = Ratingaway + cor * mov * K * (1 - Paway) \n\n # Case -3 When draw \n # Updating the Elo Ratings \n elif (d == .5) :\n Ratinghome = Ratinghome + cor * mov * K * (0.5 - Phome) \n Ratingaway = Ratingaway + cor * mov * K * (0.5 - Paway) \n\n return (round(Ratinghome, 6),round(Ratingaway, 6),round(Phome, 3),round(Paway, 3))\n\n#print(EloRating(2174.159085, 1907.279527, 5, 40, 1))\n\ntot = []\nfor x in range(0,4000,10):\n newhome, newaway, homeprob, awayprob= EloRating(x, 2000, 10, 40, 1)\n bufscore = x - 2000\n bufprob = homeprob\n tot.append((bufscore,bufprob))\n\n\nWinPer = pd.DataFrame()\nWinPer[\"score\"] = \"\"\nWinPer[\"Prob\"] = \"\"\nfor x in range(len(tot)):\n WinPer.loc[x,\"score\"] = tot[x][0]\n WinPer.loc[x,\"Prob\"] = tot[x][1]\n\n#WinPer.to_csv(\"percentages.csv\")\n\n\n# Driver code \n\n# Ratinghome and Ratingaway are current ELO ratings \n\nteams = ['New Zealand', 'France', 'Wales', 'Scotland', 'South Africa', 'Australia', 'England', 'Ireland', 'Lions', 'Italy', 'Argentina']\n\ndf[\"Home_Away_Draw\"] = \"\"\ndf[\"Prob_Home\"] = \"\"\ndf[\"Prob_Away\"] = \"\"\n\nfor i in range(len(df)):\n\n try:\n df.loc[i,'Home_Score'] = int(df.Home_Score[i])\n df.loc[i,'Away_Score'] = int(df.Away_Score[i])\n except:\n df.drop(i, inplace=True)\ndf = df.reset_index(drop=True)\n\n\nfor x in range(len(df)):\n\n \n print(str(x) + \" - \" + str(len(df)))\n\n Ratinghome = df.Home_Rating[x]\n Ratingaway = df.Away_Rating[x]\n diff = abs(df.Margin[x])\n \n if int(df.Home_Score[x]) is not None and int(df.Away_Score[x]) is not None:\n if int(df.Home_Score[x]) > int(df.Away_Score[x]):\n d = 1\n elif int(df.Home_Score[x]) < int(df.Away_Score[x]):\n d = 0\n elif int(df.Home_Score[x]) == int(df.Away_Score[x]):\n d = .5\n\n\n df.loc[x,'Home_Away_Draw'] = d\n\n K = 40\n\n\n Home_Rating_Updated, Away_Rating_Updated, Prob_Home, Prob_Away= EloRating(Ratinghome, Ratingaway, diff, K, d)\n\n df.set_value(x, 'Home_Rating_Updated', Home_Rating_Updated)\n df.set_value(x, 'Away_Rating_Updated', Away_Rating_Updated)\n df.set_value(x, 'Prob_Home', Prob_Home)\n df.set_value(x, 'Prob_Away', Prob_Away)\n\n counthome = 0\n countaway = 0\n\n\n for i in range(x+1, len(df)): #entire DF\n if counthome == 0: #repeat once\n#HOME TEAM NEW RANKING\n if df.Home_Team[i] == df.Home_Team[x] or df.Away_Team[i] == df.Home_Team[x]:\n \n #enter the loop and check case\n if df.Home_Team[i] == df.Home_Team[x]:\n #For each new year, adjust the rating\n if df.Year[i] != df.Year[x]:\n df.loc[i,'Home_Rating'] = df.Home_Rating_Updated[x]\n else:\n df.loc[i,'Home_Rating'] = df.Home_Rating_Updated[x]\n counthome = 1\n\n elif df.Away_Team[i] == df.Home_Team[x]:\n if df.Year[i] != df.Year[x]:\n df.loc[i,'Away_Rating'] = df.Home_Rating_Updated[x]\n else:\n df.loc[i,'Away_Rating'] = df.Home_Rating_Updated[x]\n counthome = 1\n\n if countaway == 0:\n#AWAY TEAM NEW RANKING\n if df.Home_Team[i] == df.Away_Team[x] or df.Away_Team[i] == df.Away_Team[x]:\n #enter the loop and check case\n if df.Home_Team[i] == df.Away_Team[x]:\n if df.Year[i] != df.Year[x]:\n df.loc[i,'Home_Rating'] = df.Away_Rating_Updated[x]\n else:\n df.loc[i,'Home_Rating'] = df.Away_Rating_Updated[x]\n countaway = 1\n\n elif df.Away_Team[i] == df.Away_Team[x]:\n if df.Year[i] != df.Year[x]:\n df.loc[i,'Away_Rating'] = df.Away_Rating_Updated[x]\n else:\n df.loc[i,'Away_Rating'] = df.Away_Rating_Updated[x]\n countaway = 1\n\ndf.to_csv(\"match_results_1995_to_2018_ELO_all.csv\")\ndf.to_csv(\"D3/match_results_1995_to_2018_ELO_all.csv\")\n","sub_path":"old_files/ELO_update.py","file_name":"ELO_update.py","file_ext":"py","file_size_in_byte":5358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"453472600","text":"from Resources import config\n\nfrom PyCode.Visualisations import LogVisualisations as lv\n\nimport csv\n\npathwaynodesList = []\n\n\ndef runVisualisation(population):\n\n getNodeList()\n\n lv.showDefaultLogVisualisations(population)\n\ndef getNodeList():\n\n if config.nodesListFile:\n filepath = config.nodesListFile\n else:\n filepath = 'Resources/Files/Visualisations/NodesList.csv'\n\n with open(filepath) as infile:\n reader = csv.reader(infile)\n for line in reader:\n if len(line) >= 2:\n pathwaynodesList.append(line[0] + ':' + line[1])\n\n\n","sub_path":"PyCode/Visualisations/Visualisation.py","file_name":"Visualisation.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"452745556","text":"from sure import this\nfrom unittest import TestCase\n\nfrom datetime import datetime\nfrom dateutil.tz import tzoffset\n\nfrom coinbase import CoinbaseAmount, CoinbaseContact, CoinbaseTransaction\nfrom . import account_setup\nfrom .http_mocking import *\n\n\n@with_http_mocking\nclass SendBtcToEmailTest(TestCase):\n\n def setUp(self):\n mock_http('POST https://coinbase.com/api/v1/transactions/send_money',\n response_body)\n\n def test_send_btc_to_email_address_with_key(self):\n account = account_setup.with_key()\n tx = account.send(\n to_address='bob@example.com',\n amount=CoinbaseAmount('0.1', 'BTC'),\n )\n this(last_request_json()).should.equal(expected_request_json)\n this(last_request_params()).should.equal({\n 'api_key': [account_setup.api_key],\n })\n this(tx).should.equal(expected_transaction)\n\n def test_send_btc_to_email_address_with_oauth(self):\n account = account_setup.with_oauth()\n tx = account.send(\n to_address='bob@example.com',\n amount=CoinbaseAmount('0.1', 'BTC'),\n )\n this(last_request_json()).should.equal(expected_request_json)\n this(last_request_params()).should.equal({})\n this(tx).should.equal(expected_transaction)\n\n\nexpected_request_json = {\n 'transaction': {\n 'to': 'bob@example.com',\n 'amount': '0.1',\n 'notes': '',\n }\n}\n\n\nresponse_body = \"\"\"\n{\n \"success\": true,\n \"transaction\": {\n \"amount\": {\n \"amount\": \"-0.10000000\",\n \"currency\": \"BTC\"\n },\n \"created_at\": \"2013-03-31T15:02:58-07:00\",\n \"hsh\": null,\n \"id\": \"69ab532bde59cfba595c5738\",\n \"notes\": \"\",\n \"idem\": \"\",\n \"recipient\": {\n \"email\": \"bob@example.com\",\n \"id\": \"72370bd60efa506c6596d56e\",\n \"name\": \"Bob\"\n },\n \"recipient_address\": \"bob@example.com\",\n \"request\": false,\n \"sender\": {\n \"email\": \"alice@example.com\",\n \"id\": \"016bde60ac5603bde5300011\",\n \"name\": \"alice@example.com\"\n },\n \"status\": \"pending\"\n }\n}\n\"\"\"\n\n\nexpected_transaction = CoinbaseTransaction(\n id='69ab532bde59cfba595c5738',\n created_at=datetime(2013, 3, 31, 15, 2, 58,\n tzinfo=tzoffset(None, -25200)),\n notes='',\n amount=CoinbaseAmount('-0.1', 'BTC'),\n status=CoinbaseTransaction.Status.pending,\n request=False,\n sender=CoinbaseContact(\n id='016bde60ac5603bde5300011',\n email='alice@example.com',\n name='alice@example.com',\n ),\n recipient=CoinbaseContact(\n id='72370bd60efa506c6596d56e',\n email='bob@example.com',\n name='Bob',\n ),\n recipient_address='bob@example.com',\n recipient_type='coinbase',\n)\n","sub_path":"treasure_share/coinbase/tests/test_send_btc_to_email.py","file_name":"test_send_btc_to_email.py","file_ext":"py","file_size_in_byte":2830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"340985120","text":"var=100\ndef func1():\n var1=10\n print(\"var1 in func1:\",var1)\n def func2():\n nonlocal var1\n var1=var1+20 # it will give error if we wont mention nonlocal in the above\n print(\"func2 in :\",var1)\n return\n func2()\n\nfunc1()\nprint(\"global var:\",var)","sub_path":"var_nonLocal_var.py","file_name":"var_nonLocal_var.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"248127237","text":"input_file = 'comments_batch_0.out'\nlimit = 5000\nout_file = input_file + '.'+str(limit) + '.cat'\n\nwith open(input_file, 'r') as infile, open(out_file, 'w') as outfile:\n lines = infile.readlines()\n for idx, line in enumerate(lines):\n if idx == limit:\n break\n outfile.write(line)\n\n\n","sub_path":"github_issues/cat.py","file_name":"cat.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"350305684","text":"#Uses python3\n\nimport sys\n#https://www.python.org/doc/essays/graphs/\ndef find_path(graph, start, end, path=[]):\n #print(\"find_path\",graph,start,end)\n path = path + [start]\n if start == end:\n return path\n\n if not (start in graph):\n return None\n\n for node in graph[start]:\n if node not in path:\n newpath = find_path(graph, node, end, path)\n if newpath: return newpath\n return None\n\ndef make_graph(adj):\n d = {}\n for i in range(len(adj)):\n d[i]=adj[i]\n #print(\"d\",d)\n return d\n\ndef reach(adj, x, y):\n #write your code here\n #adj is an arr[i] is an array of [xj...] indicating node xj+1 is adj to node i+1\n d_graph=make_graph(adj)\n\n d_path = find_path(d_graph,x,y)\n\n #print(\"reach: \",d_path)\n\n if (d_path==None):\n return(0)\n else:\n return(1)\n\n\n\nif __name__ == '__main__':\n input = sys.stdin.read()\n data = list(map(int, input.split()))\n n, m = data[0:2]\n data = data[2:]\n edges = list(zip(data[0:(2 * m):2], data[1:(2 * m):2]))\n x, y = data[2 * m:]\n adj = [[] for _ in range(n)]\n x, y = x - 1, y - 1\n for (a, b) in edges:\n adj[a - 1].append(b - 1)\n adj[b - 1].append(a - 1)\n print(reach(adj, x, y))\n","sub_path":"UCSDX-ALGS202x/week01/pc0101/reachability.py","file_name":"reachability.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"27534211","text":"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\n\n\ndriver = webdriver.Chrome()\ndriver.get(\"http://duckduckgo.com\")\nelem = elem = driver.find_element_by_name(\"q\")\nelem.clear()\nelem.send_keys(\"the biggest python software house\")\nelem.send_keys(Keys.RETURN)\nelem1 = driver.find_element_by_xpath(\"//*[@id='r1-0']/div/h2/a[1]\")\nelem1.click()\nassert \"STX Next\" in driver.title\n\n\nif __name__ == '__main__':\n driver = webdriver.Chrome()\n driver.get(\"http://minify.mobi/results/stxnext.com\")\n\n","sub_path":"zadania/zadania.py","file_name":"zadania.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"303259940","text":"# Copyright 2019, OpenCensus Authors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport collections\nimport mock\nimport requests\nimport unittest\n\nfrom opencensus.ext.azure.metrics_exporter import standard_metrics\nfrom opencensus.trace import execution_context\n\nORIGINAL_FUNCTION = requests.Session.request\n\n\nclass TestStandardMetrics(unittest.TestCase):\n def setUp(self):\n standard_metrics.dependency.dependency_map.clear()\n requests.Session.request = ORIGINAL_FUNCTION\n standard_metrics.dependency.ORIGINAL_REQUEST = ORIGINAL_FUNCTION\n\n @mock.patch('opencensus.ext.azure.metrics_exporter'\n '.standard_metrics.register_metrics')\n def test_producer_ctor(self, avail_mock):\n standard_metrics.AzureStandardMetricsProducer()\n\n self.assertEqual(len(avail_mock.call_args_list), 1)\n\n def test_producer_get_metrics(self):\n producer = standard_metrics.AzureStandardMetricsProducer()\n metrics = producer.get_metrics()\n\n self.assertEqual(len(metrics), 5)\n\n def test_register_metrics(self):\n registry = standard_metrics.register_metrics()\n\n self.assertEqual(len(registry.get_metrics()), 5)\n\n def test_get_available_memory_metric(self):\n metric = standard_metrics.AvailableMemoryMetric()\n gauge = metric()\n\n self.assertEqual(gauge.descriptor.name, '\\\\Memory\\\\Available Bytes')\n\n @mock.patch('psutil.virtual_memory')\n def test_get_available_memory(self, psutil_mock):\n memory = collections.namedtuple('memory', 'available')\n vmem = memory(available=100)\n psutil_mock.return_value = vmem\n mem = standard_metrics.AvailableMemoryMetric.get_value()\n\n self.assertEqual(mem, 100)\n\n def test_get_process_private_bytes_metric(self):\n metric = standard_metrics.ProcessMemoryMetric()\n gauge = metric()\n\n # TODO: Refactor names to be platform generic\n self.assertEqual(gauge.descriptor.name,\n '\\\\Process(??APP_WIN32_PROC??)\\\\Private Bytes')\n\n def test_get_process_private_bytes(self):\n with mock.patch('opencensus.ext.azure.metrics_exporter' +\n '.standard_metrics.process.PROCESS') as process_mock:\n memory = collections.namedtuple('memory', 'rss')\n pmem = memory(rss=100)\n process_mock.memory_info.return_value = pmem\n mem = standard_metrics.ProcessMemoryMetric.get_value()\n\n self.assertEqual(mem, 100)\n\n @mock.patch('opencensus.ext.azure.metrics_exporter'\n '.standard_metrics.process.logger')\n def test_get_process_private_bytes_exception(self, logger_mock):\n with mock.patch('opencensus.ext.azure.metrics_exporter' +\n '.standard_metrics.process.PROCESS') as process_mock:\n process_mock.memory_info.side_effect = Exception()\n standard_metrics.ProcessMemoryMetric.get_value()\n\n logger_mock.exception.assert_called()\n\n def test_get_processor_time_metric(self):\n metric = standard_metrics.ProcessorTimeMetric()\n gauge = metric()\n\n self.assertEqual(gauge.descriptor.name,\n '\\\\Processor(_Total)\\\\% Processor Time')\n\n def test_get_processor_time(self):\n with mock.patch('psutil.cpu_times_percent') as processor_mock:\n cpu = collections.namedtuple('cpu', 'idle')\n cpu_times = cpu(idle=94.5)\n processor_mock.return_value = cpu_times\n processor_time = standard_metrics.ProcessorTimeMetric.get_value()\n\n self.assertEqual(processor_time, 5.5)\n\n def test_get_process_cpu_usage_metric(self):\n metric = standard_metrics.ProcessCPUMetric()\n gauge = metric()\n\n self.assertEqual(gauge.descriptor.name,\n '\\\\Process(??APP_WIN32_PROC??)\\\\% Processor Time')\n\n @mock.patch('opencensus.ext.azure.metrics_exporter'\n '.standard_metrics.process.psutil')\n def test_get_process_cpu_usage(self, psutil_mock):\n with mock.patch('opencensus.ext.azure.metrics_exporter'\n '.standard_metrics.process.PROCESS') as process_mock:\n process_mock.cpu_percent.return_value = 44.4\n psutil_mock.cpu_count.return_value = 2\n cpu_usage = standard_metrics.ProcessCPUMetric.get_value()\n\n self.assertEqual(cpu_usage, 22.2)\n\n @mock.patch('opencensus.ext.azure.metrics_exporter'\n '.standard_metrics.process.logger')\n def test_get_process_cpu_usage_exception(self, logger_mock):\n with mock.patch('opencensus.ext.azure.metrics_exporter'\n '.standard_metrics.process.psutil') as psutil_mock:\n psutil_mock.cpu_count.return_value = None\n standard_metrics.ProcessCPUMetric.get_value()\n\n logger_mock.exception.assert_called()\n\n def test_dependency_patch(self):\n map = standard_metrics.dependency.dependency_map\n standard_metrics.dependency.ORIGINAL_REQUEST = lambda x: None\n session = requests.Session()\n execution_context.set_is_exporter(False)\n result = standard_metrics.dependency.dependency_patch(session)\n\n self.assertEqual(map['count'], 1)\n self.assertIsNone(result)\n\n def test_dependency_patch_exporter_thread(self):\n map = standard_metrics.dependency.dependency_map\n standard_metrics.dependency.ORIGINAL_REQUEST = lambda x: None\n session = mock.Mock()\n execution_context.set_is_exporter(True)\n result = standard_metrics.dependency.dependency_patch(session)\n\n self.assertIsNone(map.get('count'))\n self.assertIsNone(result)\n\n def test_get_dependency_rate_metric(self):\n metric = standard_metrics.DependencyRateMetric()\n gauge = metric()\n\n self.assertEqual(gauge.descriptor.name,\n '\\\\ApplicationInsights\\\\Dependency Calls/Sec')\n\n def test_get_dependency_rate_first_time(self):\n rate = standard_metrics.DependencyRateMetric.get_value()\n\n self.assertEqual(rate, 0)\n\n @mock.patch('opencensus.ext.azure.metrics_exporter'\n '.standard_metrics.dependency.time')\n def test_get_dependency_rate(self, time_mock):\n time_mock.time.return_value = 100\n standard_metrics.dependency.dependency_map['last_time'] = 98\n standard_metrics.dependency.dependency_map['count'] = 4\n rate = standard_metrics.DependencyRateMetric.get_value()\n\n self.assertEqual(rate, 2)\n\n @mock.patch('opencensus.ext.azure.metrics_exporter'\n '.standard_metrics.dependency.time')\n def test_get_dependency_rate_error(self, time_mock):\n time_mock.time.return_value = 100\n standard_metrics.dependency.dependency_map['last_result'] = 5\n standard_metrics.dependency.dependency_map['last_time'] = 100\n result = standard_metrics.DependencyRateMetric.get_value()\n\n self.assertEqual(result, 5)\n","sub_path":"contrib/opencensus-ext-azure/tests/test_azure_standard_metrics.py","file_name":"test_azure_standard_metrics.py","file_ext":"py","file_size_in_byte":7477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"277789949","text":"# imports\nfrom glob import glob\nimport sys\n\nimport numpy as np\n\nfrom .data_reader import main as data_reader\nfrom .params import *\n\n\n# main func\ndef main():\n # print settings\n np.set_printoptions(linewidth=np.inf)\n\n # retriving data file directories\n if len(sys.argv) > 1:\n datadir_l = sys.argv[1:]\n else:\n datadir_l = glob(REGEXDIR)\n datadir_l.sort()\n\n for data_dir in datadir_l:\n # print(f'working on: {data_dir}')\n\n for ampmstr in [AMSTR]:#, PMSTR]:\n # print(f'coeff for {ampmstr}hrs')\n # reading data\n df_l = data_reader(data_dir, ampmstr)\n\n # computing coefficients\n exec(f'from .data_fitters import {FITTER} as data_fitter', globals())\n coeff_l, descrip_l = data_fitter(df_l)\n\n # printing coefficients\n for i, descrip in enumerate(descrip_l):\n if i != 1:\n continue\n # print(descrip)\n print(coeff_l[i])\n # print('\\n')\n\n # print('\\n\\n')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"__main__present.py","file_name":"__main__present.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"402608962","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import r2_score\nfrom sklearn.preprocessing import StandardScaler, RobustScaler\nfrom scipy.spatial import distance\n\n\n# 出力フォルダ作成関数\ndef make_new_folder(folder_name):\n if os.path.exists(folder_name)==False:\n os.mkdir(folder_name)\n return True\n else:\n return False\n \n# 予測結果表示\ndef plot_pred(true, pred, margin_rate=0.1, s_rate=0.3, alpha=0.5):\n margin = (np.max(true) - np.min(true)) * margin_rate\n plt.plot(true, true, c=\"r\", alpha=alpha)\n plt.scatter(true, pred, s=plt.rcParams['lines.markersize']**2 * s_rate, alpha=alpha)\n plt.title(\"r2 : \"+str(r2_score(true, pred)))\n plt.grid()\n plt.xlim([np.min(true)-margin, np.max(true)+margin])\n plt.ylim([np.min(true)-margin, np.max(true)+margin])\n plt.xlabel(\"true\")\n plt.ylabel(\"pred\")\n plt.show()\n\n\n#離散判定\ndef check_discrete(df_data, tol=10):\n # ユニーク数tol以下を離散とする\n return (df_data.nunique() <= tol) & (df_data.dtypes!=\"float64\")\n\n\n# 四分位範囲が0より大きい連���データを取得\ndef check_large_q_cont(df_data, upper_q=.75, lower_q=.25, comparison=\"excess\"):\n # 連続データを識別\n is_continuous = df_data.dtypes==\"float64\"\n \n # 四分位範囲を計算\n quantile_ranges = df_data.quantile(upper_q) - df_data.quantile(lower_q)\n \n # 四分位範囲が0より大きいかを識別\n if comparison==\"excess\":\n mask = (quantile_ranges > 0) & is_continuous\n else:\n mask = (quantile_ranges == 0) & is_continuous\n \n #return df_data_cont.columns[mask]\n return mask\n\n\ndef _calc_mah_dis(y, x):\n tmp_df = pd.DataFrame(np.hstack((y, x)))\n mean = np.mean(tmp_df, axis=0)\n cov = np.cov(tmp_df.T)\n mah_dis = tmp_df.apply(distance.mahalanobis, v=mean, VI=np.linalg.pinv(cov), axis=1)\n return mah_dis\n\n# 各特徴量と目的変数とのマハラノビス距離計算\ndef make_df_mah_dis(y_train, X_train):\n # 標準化\n y_train_str = StandardScaler().fit_transform(y_train)\n X_train_str = StandardScaler().fit_transform(X_train)\n \n #start = time.time()\n #df_mah_dis = pd.concat([_calc_mah_dis(y_train_str, X_train_str[:,[i]]) for i in range(100)], axis=1)\n #elapsed_time = time.time() - start\n #print (\"elapsed_time:{0}\".format(elapsed_time) + \"[sec]\")\n \n # 各特徴量と目的変数とのマハラノビス距離計算\n df_mah_dis = pd.concat([_calc_mah_dis(y_train_str, X_train_str[:,[i]]) for i in range(X_train_str.shape[1])], axis=1)\n\n return df_mah_dis","sub_path":"python/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"432028650","text":"import boto3\nimport json\nimport os\n\nsession = boto3.Session(region_name=\"ap-southeast-2\")\nathena_client = session.client('athena')\nglue_client = boto3.client('glue')\n\nworkflowName = 'Athena-cross-region-wf'\nworkflow = glue_client.get_workflow(Name=workflowName)\nworkflow_params = workflow['Workflow']['LastRun']['WorkflowRunProperties']\nworkflowRunId = workflow['Workflow']['LastRun']['WorkflowRunId']\nDATABASE = workflow_params['SYDNEY_DATABASE_NAME']\n# The S3 bucket\\folder\\ location where you would like query results saved.\nOUTPUT = workflow_params['SYDNEY_OUTPUT_LOCATION']\n\nresponse = athena_client.start_query_execution(\n QueryString='''INSERT INTO \"nyctaxi-data-db-sydney\".\"sydney_yellow_aggregated\" \n SELECT vendor_name, sum(trip_distance) as \"total_distance\" ,\n substr(\"pickup_datetime\",9,2) AS \"day\"\n FROM \"nyctaxi-data-db-sydney\".\"yellow\" \n GROUP BY vendor_name, substr(\"pickup_datetime\",9,2) LIMIT 100;''',\n QueryExecutionContext={\n 'Database': DATABASE\n },\n ResultConfiguration={\n 'OutputLocation': 's3://'+OUTPUT\n }\n)\n\nqueryExecutionId = response['QueryExecutionId']\n\nworkflow_params['joinQueryExecutionIdSyd'] = queryExecutionId\nglue_client.put_workflow_run_properties(Name=workflowName, RunId=workflowRunId, RunProperties=workflow_params)\nworkflow_params = glue_client.get_workflow_run_properties(Name=workflowName,\n RunId=workflowRunId)[\"RunProperties\"]\n\nprint('Query execution id: ' + workflow_params['joinQueryExecutionIdSyd'])","sub_path":"jobs/startAggregateQuerySydney.py","file_name":"startAggregateQuerySydney.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"98995369","text":"from pathlib import Path\n\n# ------------------------------------------------\n# 1. 경로의 상태보기\nprint(Path.cwd())\nprint(Path.home())\n\np1 = Path('Ex03_createPath.py')\nprint(p1.stat())\n# ----------------------------------------------------\n# 2. 경로(파일) 생성시간 알아보기\np1 = Path('Ex03_createPath.py')\ntm = p1.stat().st_ctime\nprint(tm)\nfrom datetime import datetime\nz = datetime.fromtimestamp(tm)\nprint(z)\n# ------------------------------------------------\n# 3. 디렉토리 생성\n# p = Path('imsi2')\n# p.mkdir(exist_ok=True) #없으면 만들어\n#\n# p2 = Path('temp/test/imsi3')\n# p2.mkdir(parents=True) # /안먹히는걸 가능하게\n\n# ------------------------------------------------\n# 4. 파일 생성\nf = Path('imsi/3.text')\nf.write_text('홍길동 안녕', encoding='utf-8')\n\n#f.rename('imsi/zzzzz.txt')\nf.replace('imsi/aaaaa.txt')\n\nf2 =Path('imsi/2.txt')\nf2.touch()\n\n# ------------------------------------------------\n# 5. 경로 제거\n\n# f = Path('imsi/2.txt')\n# f.unlink()\n#\n# f = Path('imsi2')\n# f.rmdir() #폴더가 비어있지 않으면 안지워짐\n\nimport shutil\nshutil.rmtree('imsi')","sub_path":"pythonBasic/f_path_class/Ex03_createPath.py","file_name":"Ex03_createPath.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"438588296","text":"# coding=utf-8\nfrom typing import Dict, List\n\nimport pygame\n\nfrom src.states.state import State\n\n\nclass StateMachine:\n def __init__(self):\n self.state: State = None\n self.state_dict: Dict[str, State] = {}\n self.quit: bool = False\n self.clock: pygame.time.Clock = pygame.time.Clock()\n self.fps = 60\n self.screen = pygame.display.get_surface()\n\n def init_states(self, state_dict: Dict[str, State], start_state: str):\n self.state_dict = state_dict\n self.state = self.state_dict[start_state]\n self.state.startup({})\n\n def check_quit(self, events: List[pygame.event.Event]):\n for event in events:\n if event.type == pygame.QUIT:\n self.quit = True\n\n def update(self):\n if self.state.quit:\n self.quit = True\n elif self.state.done:\n self.next_state()\n self.state.update()\n self.state.draw(self.screen)\n\n def next_state(self):\n persist = self.state.cleanup()\n # print(persist)\n next_state_name = self.state.next\n self.state = self.state_dict[next_state_name]\n self.state.startup(persist)\n\n def main(self):\n\n while not self.quit:\n self.clock.tick(self.fps)\n events = pygame.event.get()\n self.check_quit(events)\n self.state.event_process(events)\n\n self.update()\n pygame.display.flip()\n","sub_path":"src/state_machine.py","file_name":"state_machine.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"152730530","text":"from hypr import Provider, filter\nimport json\n\n\nclass Root(Provider):\n\n propagation_rules = {\n 'rule0': ('Resource', '/rule0'),\n 'rule1': ('Resource', '/rule1'),\n 'rule2': ('Resource', '/rule2'),\n 'rule3': ('Resource', '/rule3')\n }\n\n @filter(key='always')\n def always_filter(self, value):\n return value\n\n @filter(key='rule0', scope='rule0')\n def rule0_filter(self, value):\n return value\n\n @filter(key='rule1', scope='rule1')\n def rule1_filter(self, value):\n return value\n\n @filter(key='multi', scope=('rule0', 'rule2'))\n def multi_filter(self, value):\n return value\n\n def get(self, value):\n return value\n\n\nclass TestScopedFilter:\n\n providers = {\n 'Root': '/root/',\n 'Resource': '/resource'\n }\n\n def test_always_only(self, app):\n\n with app.test_client() as client:\n\n resp = client.get('/root/1/rule3')\n assert resp.status == 200\n assert json.loads(resp.text) == {'always': 1}\n\n def test_specific(self, app):\n\n with app.test_client() as client:\n\n resp = client.get('/root/1/rule1')\n assert resp.status == 200\n assert json.loads(resp.text) == {'always': 1, 'rule1': 1}\n\n\n def test_multi(self, app):\n\n with app.test_client() as client:\n\n resp = client.get('/root/1/rule2')\n assert resp.status == 200\n assert json.loads(resp.text) == {'always': 1, 'multi': 1}\n\n\n def test_multi_and_specific(self, app):\n\n with app.test_client() as client:\n\n resp = client.get('/root/1/rule0')\n assert resp.status == 200\n assert json.loads(resp.text) == {'always': 1,\n 'multi': 1,\n 'rule0': 1}\n","sub_path":"tests/security/filters/test_scoped_filters.py","file_name":"test_scoped_filters.py","file_ext":"py","file_size_in_byte":1858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"393454741","text":"\"\"\"\nReproduce moist versions of figures 8 and 9 from SB08 using data from the updated ap_2 run. \nUse Emanuel 1995 (On Thermally Direct Circulations...) angular momentum conserving equivalent \npotential temperature (12/11/2018)\n\"\"\"\n\nimport xarray as xr\nimport sh\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom data_handling_updates import gradients as gr, model_constants as mc, make_sym\nfrom climatology import precip_centroid\nfrom hadley_cell import get_edge_psi\nfrom pylab import rcParams\nfrom hadley_cell import mass_streamfunction\n\n \ndef get_latmax(data_in):\n data_max = data_in.max('lat')\n data_max_lat = data_in.lat.values[data_in.argmax('lat').values]\n data_max_lat = xr.DataArray(data_max_lat, coords=[data_in.xofyear], dims=['xofyear'])\n return data_max, data_max_lat\n \ndef fig_8_moist(run, ax, pentad=45, rotfac=1., dayfac=5.):\n\n data = xr.open_dataset('/disca/share/rg419/Data_moist/climatologies/' + run + '.nc')\n \n heating = data.dt_tg_condensation + data.dt_tg_convection + data.dt_tg_diffusion + data.tdt_rad\n hum_tend = data.dt_qg_condensation + data.dt_qg_convection + data.dt_qg_diffusion\n \n convTtotheta=(1000./data.pfull)**mc.kappa\n theta = data.temp*convTtotheta\n heating_theta = heating*convTtotheta\n heating_equiv_theta = heating_theta + mc.L/mc.cp_air * hum_tend/(1-data.sphum)**2. * convTtotheta\n \n sinphi = np.sin(data.lat * np.pi/180.)\n cosphi = np.cos(data.lat * np.pi/180.)\n \n theta_850 = theta.sel(pfull=850.).mean('lon')\n \n theta_equiv = (data.temp + mc.L/mc.cp_air * data.sphum/(1-data.sphum)) * convTtotheta\n theta_equiv_850 = theta_equiv.sel(pfull=850.).mean('lon')\n \n lats = [data.lat[i] for i in range(len(data.lat)) if data.lat[i] >= -10. and data.lat[i] <= 10.]\n \n Tt = (data.temp.sel(pfull=150.).mean(('lon'))*cosphi).sel(lat=lats).sum('lat')/cosphi.sel(lat=lats).sum('lat')\n Ts = (data.t_surf.mean(('lon'))*cosphi).sel(lat=lats).sum('lat')/cosphi.sel(lat=lats).sum('lat')\n \n dthetady_equiv = gr.ddy(theta_equiv.mean('lon'), vector=False)\n dthetadp_equiv = gr.ddp(theta_equiv.mean('lon'))\n dthetadt_equiv = gr.ddt(theta_equiv.mean('lon'))\n vdthetady_mean = data.vcomp.mean('lon') * dthetady_equiv\n wdthetadp_mean = data.omega.mean('lon') * dthetadp_equiv\n adv_heating_equiv = -1. *(vdthetady_mean + wdthetadp_mean)\n \n w_850 = data.omega.sel(pfull=850.).mean('lon')\n w_max, w_max_lat = get_latmax(-1.*w_850)\n \n theta_max, theta_max_lat = get_latmax(theta_equiv_850)\n cosphimax = np.cos(theta_max_lat * np.pi/180.)\n chi = (rotfac * mc.omega)**2 * mc.a**2./mc.cp_air/(Ts - Tt)\n theta_m_equiv = theta_max * np.exp(-1.* chi * (cosphimax**2.-cosphi**2.)**2./cosphi**2.)\n\n def adj_theta(theta_in, adj_by, dayfac=dayfac):\n if 'lon' in adj_by.coords:\n return theta_in + adj_by.sel(pfull=850.).mean('lon') * 86400. * dayfac\n else:\n return theta_in + adj_by.sel(pfull=850.) * 86400. * dayfac\n \n theta_equiv_rc = adj_theta(theta_equiv_850, heating_equiv_theta, dayfac=dayfac)\n theta_equiv_adv = adj_theta(theta_equiv_850, adv_heating_equiv, dayfac=dayfac)\n theta_equiv_net = adj_theta(theta_equiv_850, dthetadt_equiv, dayfac=dayfac*3.)\n \n lats = [data.lat[i] for i in range(len(data.lat)) if data.lat[i] >= -60. and data.lat[i] <= 60.]\n \n theta_m_equiv.sel(xofyear=pentad, lat=lats).plot(ax=ax, color='0.7')\n theta_equiv_rc.sel(xofyear=pentad, lat=lats).plot(ax=ax, color='k', linestyle='--')\n theta_equiv_adv.sel(xofyear=pentad, lat=lats).plot(ax=ax, color='k', linestyle='-.')\n theta_equiv_850.sel(xofyear=pentad, lat=lats).plot(ax=ax, color='C0')\n theta_equiv_net.sel(xofyear=pentad, lat=lats).plot(ax=ax, color='C2')\n ax.plot([w_max_lat.sel(xofyear=pentad),w_max_lat.sel(xofyear=pentad)], [300.,380.], color='0.7', linestyle=':')\n ax.set_title('')\n ax.set_xlabel('')\n ax.set_ylim(300.,380.)\n ax.set_xlim(-35.,35.)\n ax.grid(True,linestyle=':')\n ax.set_ylabel('$\\Theta$, K')\n\n\ndef plot_bs_fig_8_moist(run, pentads=[35,40,45,50], rotfac=1.):\n \n plot_dir = '/scratch/rg419/plots/paper_2_figs/revisions/heatbudg_moist/'\n mkdir = sh.mkdir.bake('-p')\n mkdir(plot_dir)\n rcParams['figure.figsize'] = 5.5, 7.\n rcParams['font.size'] = 14\n \n data = xr.open_dataset('/disca/share/rg419/Data_moist/climatologies/' + run + '.nc')\n data['precipitation'] = make_sym(data.precipitation)\n precip_centroid(data) # Locate precipitation centroid\n dpcentdt = gr.ddt(data.p_cent) * 86400.\n p_cent_pos = np.abs(data.p_cent.where(dpcentdt>=0.))\n \n eq_time = p_cent_pos.xofyear[p_cent_pos.argmin('xofyear').values]\n peak_rate_time = dpcentdt.xofyear[dpcentdt.argmax('xofyear').values]\n max_lat_time = data.p_cent.xofyear[data.p_cent.argmax('xofyear').values]\n \n edge_loc, psi_max, psi_max_loc = get_edge_psi(data, lev=850., thresh=0., intdown=True)\n \n fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, sharex=True)\n axes = [ax1,ax2,ax3,ax4]\n pentads = [eq_time.values, peak_rate_time.values, np.floor((peak_rate_time.values + max_lat_time.values)/2.), max_lat_time.values]\n \n for i in range(4):\n edge = edge_loc.sel(xofyear=pentads[i])\n fig_8_moist(run, ax=axes[i], pentad=pentads[i], rotfac=rotfac)\n axes[i].plot([edge, edge], [300., 380.], 'k:')\n axes[i].text(20, 375., 'Pentad ' + str(int(pentads[i])))\n \n ax4.set_xlabel('Latitude')\n \n #ax1.text(20, 315., 'a)')\n #ax2.text(20, 315., 'b)')\n #ax3.text(2, 315., 'c)')\n #ax4.text(-55, 315., 'd)')\n \n plt.subplots_adjust(left=0.15, right=0.95, top=0.97, bottom=0.1)\n plt.savefig(plot_dir+'sb08_fig8_moist_' + run + '.pdf', format='pdf')\n plt.close()\n \n\n\ndef fig_9_moist(run, ax, pentad=40):\n\n data = xr.open_dataset('/disca/share/rg419/Data_moist/climatologies/' + run + '.nc')\n \n convTtotheta=(1000./data.pfull)**mc.kappa\n \n heating = data.dt_tg_condensation + data.dt_tg_convection + data.dt_tg_diffusion + data.tdt_rad\n hum_tend = data.dt_qg_condensation + data.dt_qg_convection + data.dt_qg_diffusion\n \n heating_theta_equiv = ((heating + mc.L/mc.cp_air * hum_tend/(1-data.sphum)**2.)*convTtotheta).mean('lon')\n \n theta_equiv = (data.temp + mc.L/mc.cp_air * data.sphum/(1-data.sphum)) * convTtotheta\n \n dthetady_equiv = gr.ddy(theta_equiv.mean('lon'), vector=False)\n dthetadp_equiv = gr.ddp(theta_equiv.mean('lon'))\n dthetadt_equiv = gr.ddt(theta_equiv.mean('lon'))\n \n vcomp_theta_equiv = (data.vcomp_temp + mc.L/mc.cp_air * data.sphum_v)*convTtotheta\n vcomp_theta_eddy_equiv = vcomp_theta_equiv.mean('lon') - data.vcomp.mean('lon')*theta_equiv.mean('lon')\n \n vdthetady_mean_equiv = data.vcomp.mean('lon') * dthetady_equiv\n wdthetadp_mean_equiv = data.omega.mean('lon') * dthetadp_equiv\n \n def column_int(var_in):\n var_int = mc.cp_air * var_in.sum('pfull')*5000./mc.grav\n return var_int\n \n vdtdy_mean_int_equiv = -1. * column_int(vdthetady_mean_equiv)\n wdtdp_mean_int_equiv = -1. * column_int(wdthetadp_mean_equiv)\n \n vt_eddy_int_equiv = -1. * column_int(vcomp_theta_eddy_equiv)\n div_vt_eddy_int_equiv = gr.ddy(vt_eddy_int_equiv, vector=True)\n \n heating_theta_int_equiv = column_int(heating_theta_equiv)\n dthetadt_int_equiv = column_int(dthetadt_equiv)\n \n lats = [data.lat[i] for i in range(len(data.lat)) if data.lat[i] >= -60. and data.lat[i] <= 60.]\n \n w_850 = data.omega.sel(pfull=850.).mean('lon')\n w_max, w_max_lat = get_latmax(-1.*w_850)\n \n dthetadt_int_equiv.sel(xofyear=pentad, lat=lats).plot(ax=ax, color='C2')\n heating_theta_int_equiv.sel(xofyear=pentad, lat=lats).plot(ax=ax, color='k', linestyle='--')\n (vdtdy_mean_int_equiv + wdtdp_mean_int_equiv ).sel(xofyear=pentad, lat=lats).plot(ax=ax, color='k', linestyle='-.')\n #(vdtdy_mean_int_equiv + wdtdp_mean_int_equiv + heating_theta_int_equiv + div_vt_eddy_int_equiv).sel(xofyear=pentad, lat=lats).plot(ax=ax, color='k', linestyle=':')\n div_vt_eddy_int_equiv.sel(xofyear=pentad, lat=lats).plot(ax=ax, color='k', linestyle=':')\n ax.plot([w_max_lat.sel(xofyear=pentad),w_max_lat.sel(xofyear=pentad)], [-250.,250.], color='0.7', linestyle=':')\n ax.set_title('')\n ax.set_xlabel('')\n ax.set_ylim(-250.,250.)\n ax.set_xlim(-35.,35.)\n ax.grid(True,linestyle=':')\n ax.set_ylabel('Heating rate, W/m$^2$')\n \n\n\ndef plot_bs_fig_9_moist(run, pentads=[35,40,45,50], rotfac=1.):\n \n plot_dir = '/scratch/rg419/plots/paper_2_figs/revisions/heatbudg_moist/'\n mkdir = sh.mkdir.bake('-p')\n mkdir(plot_dir)\n rcParams['figure.figsize'] = 5.5, 7.\n rcParams['font.size'] = 14\n \n data = xr.open_dataset('/disca/share/rg419/Data_moist/climatologies/' + run + '.nc')\n data['precipitation'] = make_sym(data.precipitation)\n precip_centroid(data) # Locate precipitation centroid\n dpcentdt = gr.ddt(data.p_cent) * 86400.\n p_cent_pos = np.abs(data.p_cent.where(dpcentdt>=0.))\n \n eq_time = p_cent_pos.xofyear[p_cent_pos.argmin('xofyear').values]\n peak_rate_time = dpcentdt.xofyear[dpcentdt.argmax('xofyear').values]\n max_lat_time = data.p_cent.xofyear[data.p_cent.argmax('xofyear').values]\n \n edge_loc, psi_max, psi_max_loc = get_edge_psi(data, lev=850., thresh=0., intdown=True)\n \n fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, sharex=True)\n axes = [ax1,ax2,ax3,ax4]\n pentads = [eq_time.values, peak_rate_time.values, np.floor((peak_rate_time.values + max_lat_time.values)/2.), max_lat_time.values]\n \n for i in range(4):\n fig_9_moist(run, ax=axes[i], pentad=pentads[i])\n edge = edge_loc.sel(xofyear=pentads[i])\n axes[i].plot([edge, edge], [-250., 250.], 'k:') \n axes[i].text(20, 240., 'Pentad ' + str(int(pentads[i])))\n \n ax4.set_xlabel('Latitude')\n \n #ax1.text(-55, 315., 'a)')\n #ax2.text(-55, 315., 'b)')\n #ax3.text(-55, 315., 'c)')\n #ax4.text(-55, 315., 'd)')\n \n plt.subplots_adjust(left=0.15, right=0.95, top=0.97, bottom=0.1)\n plt.savefig(plot_dir+'sb08_fig9_moist_' + run + '.pdf', format='pdf')\n plt.close()\n \n\nplot_bs_fig_8_moist('mld_2.5_heatbudg')\nplot_bs_fig_8_moist('mld_5_heatbudg')\nplot_bs_fig_8_moist('mld_15_heatbudg')\nplot_bs_fig_8_moist('mld_20_heatbudg')\n\nplot_bs_fig_9_moist('mld_2.5_heatbudg')\nplot_bs_fig_9_moist('mld_5_heatbudg')\nplot_bs_fig_9_moist('mld_15_heatbudg')\nplot_bs_fig_9_moist('mld_20_heatbudg')\n \n#plot_bs_fig_8_moist('sn_1.000_evap_fluxes_heattrans')\n#plot_bs_fig_8_moist('rt_2.000_heatbudg', rotfac=2.)\n#plot_bs_fig_8_moist('rt_0.500_heatbudg', rotfac=0.5)\n#plot_bs_fig_8_moist('rt_0.750_heatbudg', rotfac=0.75)\n#plot_bs_fig_8_moist('rt_1.250_heatbudg', rotfac=1.25)\n#plot_bs_fig_8_moist('rt_1.500_heatbudg', rotfac=1.5)\n#plot_bs_fig_8_moist('rt_1.750_heatbudg', rotfac=1.75)\n\n#plot_bs_fig_9_moist('sn_1.000_evap_fluxes_heattrans')\n#plot_bs_fig_9_moist('rt_2.000_heatbudg')\n#plot_bs_fig_9_moist('rt_0.500_heatbudg')\n#plot_bs_fig_9_moist('rt_0.750_heatbudg')\n#plot_bs_fig_9_moist('rt_1.250_heatbudg')\n#plot_bs_fig_9_moist('rt_1.500_heatbudg')\n#plot_bs_fig_9_moist('rt_1.750_heatbudg')","sub_path":"paper_2_figs/bs_heatbudg_moist.py","file_name":"bs_heatbudg_moist.py","file_ext":"py","file_size_in_byte":11200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"262468008","text":"#!/usr/bin/env python3\n\"\"\"\nIgDiscover computes V/D/J gene usage profiles and discovers novel V genes\n\n- Run IgBLAST in parallel (wrapper inspired by igblastwrp).\n- Parse IgBLAST output into a tab-separated table\n- Group sequences by barcode\n- Plot V gene usage\n- Discover new V genes given more than one dataset\n\"\"\"\nimport sys\nimport logging\nimport pkgutil\nimport importlib\nfrom argparse import ArgumentParser, RawDescriptionHelpFormatter\nimport matplotlib as mpl\nimport warnings\nimport resource\n\nimport igdiscover.cli as cli_package\nfrom igdiscover.cli import CommandLineError\n\nfrom . import __version__\n\n__author__ = \"Marcel Martin\"\n\nmpl.use('Agg')\nwarnings.filterwarnings('ignore', 'axes.color_cycle is deprecated and replaced with axes.prop_cycle')\nwarnings.filterwarnings('ignore', 'The `IPython.html` package')\nwarnings.filterwarnings('ignore', 'Widget registration using a string name has been deprecated')\nwarnings.filterwarnings('ignore', 'Traits should be given as instances, not types')\nwarnings.filterwarnings('ignore', 'pandas.util.testing is deprecated.')\n\nlogger = logging.getLogger(__name__)\n\n\nclass HelpfulArgumentParser(ArgumentParser):\n \"\"\"An ArgumentParser that prints full help on errors.\"\"\"\n\n def __init__(self, *args, **kwargs):\n if 'formatter_class' not in kwargs:\n kwargs['formatter_class'] = RawDescriptionHelpFormatter\n super().__init__(*args, **kwargs)\n\n def error(self, message):\n self.print_help(sys.stderr)\n args = {'prog': self.prog, 'message': message}\n self.exit(2, '%(prog)s: error: %(message)s\\n' % args)\n\n\ndef format_duration(seconds):\n h = int(seconds // 3600)\n seconds -= h * 3600\n m = int(seconds // 60)\n seconds -= m * 60\n return '{:02d}:{:02d}:{:04.1f}'.format(h, m, seconds)\n\n\ndef main(arguments=None):\n logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')\n parser = HelpfulArgumentParser(description=__doc__, prog='igdiscover')\n parser.add_argument('--profile', default=False, action='store_true',\n help='Save profiling information to igdiscover.prof')\n parser.add_argument('--version', action='version', version='%(prog)s ' + __version__)\n\n show_cpustats = dict()\n subparsers = parser.add_subparsers()\n\n # Import each module that implements a subcommand and add a subparser for it.\n # Each subcommand is implemented as a module in the cli subpackage.\n # It needs to implement an add_arguments() and a main() function.\n modules = pkgutil.iter_modules(cli_package.__path__)\n for _, module_name, _ in modules:\n module = importlib.import_module(\".\" + module_name, cli_package.__name__)\n subparser = subparsers.add_parser(module_name,\n help=module.__doc__.split('\\n')[1], description=module.__doc__)\n subparser.set_defaults(func=module.main)\n module.add_arguments(subparser)\n if hasattr(module, 'do_not_show_cpustats'):\n show_cpustats[module.main] = False\n\n args = parser.parse_args(arguments)\n do_profiling = args.profile\n del args.profile\n if hasattr(args, 'func'):\n subcommand = args.func\n del args.func\n else:\n parser.error('Please provide the name of a subcommand to run')\n if do_profiling:\n import cProfile as profile\n to_run = lambda: profile.runctx('subcommand(args)', globals(), dict(subcommand=subcommand, args=args), filename='igdiscover.prof')\n logger.info('Writing profiling data to igdiscover.prof')\n else:\n to_run = lambda: subcommand(args)\n try:\n to_run()\n except CommandLineError as e:\n logger.error(e)\n sys.exit(1)\n if sys.platform == 'linux' and show_cpustats.get(subcommand, True):\n rself = resource.getrusage(resource.RUSAGE_SELF)\n rchildren = resource.getrusage(resource.RUSAGE_CHILDREN)\n memory_kb = rself.ru_maxrss + rchildren.ru_maxrss\n cpu_time = rself.ru_utime + rself.ru_stime + rchildren.ru_utime + rchildren.ru_stime\n cpu_time_s = format_duration(cpu_time)\n logger.info('CPU time {}. Maximum memory usage {:.3f} GB'.format(\n cpu_time_s, memory_kb / 1E6))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/igdiscover/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":4209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"100267552","text":"import turtle\n\n# vegeta = turtle.Turtle()\n# gohan = turtle.Turtle()\n\n# def square(t, length):\n# for i in range(10):\n# t.fd(100)\n# t.fd(length)\n# t.lt(90)\n# square(vegeta, 100)\n# square(gohan)\n\n\ngothen = turtle.Turtle()\n\ndef polygon(t, n, length):\n angle = 360 / n\n for i in range(n):\n t.fd(length)\n t.lt(angle)\npolygon(gothen, 10 ,70)","sub_path":"aulas/encapsulamento.py","file_name":"encapsulamento.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"184317886","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Nov 12 10:32:50 2019\n\n@author: Jon Emrich\n\"\"\"\n\nimport shutil\nimport subprocess\nimport os\n\ndef main():\n v_path = 'visualization.py'\n if os.path.exists(v_path):\n os.unlink(v_path)\n print('Deleting file at path: %s' % v_path)\n utils_path = 'utils.py'\n if os.path.exists(utils_path):\n os.unlink(utils_path)\n print('Deleting file at path: %s' % utils_path)\n config_path = 'dist/config.json'\n if os.path.exists(config_path):\n os.unlink(config_path)\n print('Deleting file at path: %s' % config_path)\n videos_path = 'dist/videos'\n if os.path.exists(videos_path):\n shutil.rmtree(videos_path)\n print('Deleting folder at path: %s' % videos_path) \n print('Copying visualization.py')\n shutil.copy('../nauto-ai/models/distraction/keras/bmw-demo/visualization.py','.')\n print('Copying utils.py')\n shutil.copy('../nauto-ai/models/distraction/keras/bmw-demo/utils.py','.')\n print('Building EXE')\n cmd = ['pyinstaller','--onefile','BMWDemo_setup.spec']\n subprocess.Popen(cmd,shell=True).wait()\n print('Copying videos')\n shutil.copytree('videos', 'dist/videos')\n print('Copying config.json')\n shutil.copy('config.json','dist/config.json')\n print('Zipping directory')\n shutil.make_archive('zip/BMWDemo','zip','dist')\n print('Complete')\n \nif __name__ == '__main__':\n main()","sub_path":"build_demo.py","file_name":"build_demo.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"442502287","text":"\n# coding: utf-8\n\n# In[9]:\n\nimport sqlite3\nimport numpy as np\nimport time, datetime\n\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn import neighbors, tree, naive_bayes\nfrom sklearn.cross_validation import train_test_split\nimport math\n\n\n\ntoday = datetime.date.today() \ntoday = today.strftime(\"%Y-%m-%d\")\n\ncon = sqlite3.connect('C:\\\\NBA\\\\nba.db')\ncur = con.cursor()\ncur2 = con.cursor()\ncur3 = con.cursor()\n\nplayer_list = []\ncur.execute('''\n SELECT DISTINCT player_id\n FROM \n (\n SELECT player_id, COUNT(*)\n FROM records\n GROUP BY player_id\n HAVING COUNT(*) > 4\n ) tab \n ''')\nfor player in cur:\n player_list.append(player[0])\n \n\nfor p in player_list:\n cur2.execute(\"SELECT * FROM records WHERE player_id = '\" + p + \"'\")\n\n player_records = [] # initiate empty list to eventually hold the palyer records as a numpy array\n\n for record in cur2:\n record = list(record)\n record = record[2:] # omit the player_id and game_id\n player_records.append(record)\n\n player_records = np.asarray(player_records)\n\n # define numerical tagets\n assists = player_records[:,0] # first column\n rebounds = player_records[:,1]\n points = player_records[:,2]\n steals = player_records[:,3]\n blocks = player_records[:,4]\n turnovers = player_records[:,5]\n made_threes = player_records[:,6]\n\n\n # define categorical targets\n assists_str = [\"%.0f\" % asst for asst in assists]\n rebounds_str = [\"%.0f\" % reb for reb in rebounds]\n points_str = [\"%.0f\" % point for point in points]\n steals_str = [\"%.0f\" % steal for steal in steals]\n blocks_str = [\"%.0f\" % block for block in blocks]\n turnovers_str = [\"%.0f\" % turnover for turnover in turnovers]\n made_threes_str = [\"%.0f\" % made_three for made_three in made_threes]\n\n # drop targets from array\n player_records = np.delete(player_records, 0, 1) # remove assists\n player_records = np.delete(player_records, 0, 1) # remove rebounds\n player_records = np.delete(player_records, 0, 1) # remove points\n player_records = np.delete(player_records, 0, 1) # remove steals\n player_records = np.delete(player_records, 0, 1) # remove blocks\n player_records = np.delete(player_records, 0, 1) # remove turnovers\n player_records = np.delete(player_records, 0, 1) # remove made_three\n \n for target in [assists_str,rebounds_str,points_str,steals_str,blocks_str,turnovers_str,made_threes_str]:\n if np.array_equal(target, assists_str):\n stat = 'assists'\n elif np.array_equal(target, rebounds_str):\n stat = 'rebounds'\n elif np.array_equal(target, points_str):\n stat = 'points'\n elif np.array_equal(target, steals_str):\n stat = 'steals'\n elif np.array_equal(target, blocks_str):\n stat = 'blocks'\n elif np.array_equal(target, turnovers_str):\n stat = 'turnovers'\n elif np.array_equal(target, made_threes_str):\n stat = 'made_threes'\n \n # split the data into randomized 80% 20% training and test split\n train, test, target_train, target_test = train_test_split(player_records, target, test_size=0.2, random_state=33)\n \n nbclf = naive_bayes.GaussianNB()\n nbclf = nbclf.fit(train, target_train)\n nbpreds_test = nbclf.predict(test)\n\n target_test = np.asarray(target_test)\n target_test_float = target_test.astype(np.float)\n nbpreds_test_float = nbpreds_test.astype(np.float)\n\n MSE = math.sqrt(sum((nbpreds_test_float - target_test_float)**2)) / nbpreds_test_float.shape[0]\n \n\n result = [p,today,'naivebayes',stat,MSE,0,'Not Applicable']\n result = tuple(result)\n result = tuple(result)\n cur3.execute('INSERT INTO model_results VALUES(?' + ',?'*6 + ')',result)\n con.commit()\n\ncon.close()\n\n\n# In[ ]:\n\n\n\n","sub_path":"MODELS/NaiveBayes.py","file_name":"NaiveBayes.py","file_ext":"py","file_size_in_byte":3959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"429386153","text":"#包文件导入区\nimport pickle\nfrom zipfile import ZipFile\nfrom tqdm import tqdm\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.utils import shuffle\nimport tensorflow as tf\nimport matlab.engine\n\n#自己的包定义区\nimport Support\n\n#%%数据文件导入区\nFileName = './traffic-signs-data.zip'\nzipf = ZipFile(FileName)\n# 长生一个zip内文件名集合\nfilenames_pbar = tqdm(zipf.namelist(), unit='files')\n# 循环读取ZIP文件内所有数据\nfor filename in filenames_pbar:\n # 检查是否是目录,防止有其他东西\n if not filename.endswith('/'):\n image_file = zipf.open(filename)\n #按照需要打开文件\n if filename == 'test.p':\n test = pickle.load(image_file) \n if filename == 'train.p':\n train = pickle.load(image_file)\n if filename == 'valid.p':\n valid = pickle.load(image_file)\n image_file.close()\nzipf.close()\nX_train, y_train = train['features'], train['labels']\nX_valid, y_valid = valid['features'], valid['labels']\nX_test, y_test = test['features'], test['labels']\n\n#%%训练数据\n#显示统计数据\n#训练集的个数\nn_train = np.shape(y_train)[0]\n\n#验证集的个数\nn_validation = np.shape(y_valid)[0]\n\n#测试集的个数\nn_test = np.shape(y_test)[0]\n\n#交通标志图像的大小\nimage_shape = np.shape(X_train)[1::]\n\n#不同标志的个数\nn_classes = np.max(y_train)+1\n\nprint(\"Number of training examples =\", n_train)\nprint(\"Number of testing examples =\", n_test)\nprint(\"Image data shape =\", image_shape)\nprint(\"Number of classes =\", n_classes)\n\n#%%训练图像处理过程\n#随机排列图像\nX_train, y_train = shuffle(X_train, y_train)\n\n\n#将数据转移到Matlab做再处理\n#Support.FigureDataToMatlab(X_valid,0,4410,'X_valid')\n#Support.FigureDataToMatlab(y_valid,0,4410,'y_valid')\n\nSupport.FigureDataToMatlab(X_test,0,12630,'X_test')\nSupport.FigureDataToMatlab(y_test,0,12630,'y_test')\n'''\nSupport.FigureDataToMatlab(X_train,0,34799,'X_train')\nSupport.FigureDataToMatlab(y_train,0,34799,'y_train')\n'''\n\n","sub_path":"SendDataToMatlab.py","file_name":"SendDataToMatlab.py","file_ext":"py","file_size_in_byte":2055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"30595135","text":"from __future__ import absolute_import, division, print_function\n\nimport codecs\nimport re\n\n\n__version__ = '0.2.0'\n__author__ = 'Hynek Schlawack'\n__license__ = 'MIT'\n__copyright__ = 'Copyright 2014 Hynek Schlawack'\n\n\nclass _Base(object):\n def __init__(self, _pem_str):\n self.pem_str = _pem_str\n\n def __str__(self):\n return self.pem_str\n\n def __repr__(self):\n return '<{0}(pem_str={1!r})>'.format(\n self.__class__.__name__, self.pem_str\n )\n\n\nclass Certificate(_Base):\n pass\n\n\nclass Key(_Base):\n pass\n\n\nclass RSAPrivateKey(Key):\n pass\n\n\n_PEM_TO_CLASS = {\n 'CERTIFICATE': Certificate,\n 'RSA PRIVATE KEY': RSAPrivateKey,\n}\n_PEM_RE = re.compile(u\"\"\"-----BEGIN ({0})-----\n.+?\n-----END \\\\1-----\n\"\"\".format('|'.join(_PEM_TO_CLASS.keys())), re.DOTALL)\n\n\ndef parse(pem_str):\n \"\"\"\n Extract PEM objects from *pem_str*.\n \"\"\"\n return [_PEM_TO_CLASS[match.group(1)](match.group(0))\n for match in _PEM_RE.finditer(pem_str)]\n\n\ndef parse_file(file_name):\n \"\"\"\n Read *file_name* and parse PEM objects from it.\n \"\"\"\n with codecs.open(file_name, 'rb', encoding='ascii') as f:\n return parse(f.read())\n\n\ndef certificateOptionsFromFiles(*pemFiles, **kw):\n \"\"\"\n Read all *pemFiles*, find one key, use the first certificate as server\n certificate and the rest as chain.\n \"\"\"\n from twisted.internet import ssl\n\n pems = []\n for pemFile in pemFiles:\n pems += parse_file(pemFile)\n keys = [key for key in pems if isinstance(key, Key)]\n if not len(keys):\n raise ValueError('Supplied PEM file(s) do *not* contain a key.')\n if len(keys) > 1:\n raise ValueError('Supplied PEM file(s) contain *more* than one key.')\n certs = [cert for cert in pems if isinstance(cert, Certificate)]\n if not len(certs):\n raise ValueError('*At least one* certificate is required.')\n cert = ssl.PrivateCertificate.loadPEM(str(keys[0]) + str(certs[0]))\n chain = [ssl.Certificate.loadPEM(str(certPEM)).original\n for certPEM in certs[1:]]\n\n fakeEDHSupport = \"dhParameters\" in kw and not _DH_PARAMETERS_SUPPORTED\n if fakeEDHSupport:\n dhParameters = kw.pop(\"dhParameters\")\n\n ctxFactory = ssl.CertificateOptions(\n privateKey=cert.privateKey.original,\n certificate=cert.original,\n extraCertChain=chain,\n **kw)\n\n if fakeEDHSupport:\n return _DHParamContextFactory(ctxFactory, dhParameters)\n else:\n return ctxFactory\n\n\nclass _DHParamContextFactory(object):\n \"\"\"\n A wrapping context factory that gets a context from a different\n context factory and then sets temporary DH params on it. This\n enables PFS ciphersuites using DHE.\n \"\"\"\n def __init__(self, ctxFactory, dhParameters):\n self.ctxFactory = ctxFactory\n self.dhParameters = dhParameters\n\n def getContext(self):\n ctx = self.ctxFactory.getContext()\n ctx.load_tmp_dh(self.dhParameters._dhFile.path)\n return ctx\n\n\nclass _DiffieHellmanParameters(object):\n \"\"\"\n A representation of key generation parameters that are required for\n Diffie-Hellman key exchange.\n \"\"\"\n def __init__(self, parameters):\n self._dhFile = parameters\n\n @classmethod\n def fromFile(cls, filePath):\n \"\"\"\n Load parameters from a file.\n\n Such a file can be generated using the C{openssl} command line tool as\n following:\n\n C{openssl dhparam -out dh_param_1024.pem -2 1024}\n\n Please refer to U{OpenSSL's C{dhparam} documentation\n } for further details.\n\n @param filePath: A file containing parameters for Diffie-Hellman key\n exchange.\n @type filePath: L{FilePath }\n\n @return: A instance that loads its parameters from C{filePath}.\n @rtype: L{DiffieHellmanParameters\n }\n \"\"\"\n return cls(filePath)\n\n\ntry: # pragma: nocover\n from twisted.internet.ssl import DiffieHellmanParameters\n _DH_PARAMETERS_SUPPORTED = True\nexcept ImportError:\n DiffieHellmanParameters = _DiffieHellmanParameters\n _DH_PARAMETERS_SUPPORTED = False\n","sub_path":"pem.py","file_name":"pem.py","file_ext":"py","file_size_in_byte":4256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"348439714","text":"import psycopg2\r\nfrom psycopg2 import Error\r\n\r\n\r\n# this function is based on the tutorial at: https://pynative.com/python-postgresql-tutorial/\r\ndef connect_to_db(username='postgres', password='Password', host='127.0.0.1', port='5432', database='BillyBooks'):\r\n try:\r\n # Connect to an existing database\r\n connection = psycopg2.connect(user=username,\r\n password=password,\r\n host=host,\r\n port=port,\r\n database=database)\r\n\r\n # Create a cursor to perform database operations\r\n cursor = connection.cursor()\r\n #print(\"connected to the database\")\r\n\r\n return cursor, connection\r\n\r\n except (Exception, Error) as error:\r\n print(\"Error while connecting to PostgreSQL\", error)\r\n\r\n\r\ndef disconnect_from_db(connection, cursor):\r\n if (connection):\r\n cursor.close()\r\n connection.close()\r\n #print(\"PostgreSQL connection is closed.TESTING\")\r\n else:\r\n print(\"Connection does not work.\")\r\n\r\n# run_sql(cursor,\"select from;\")\r\ndef run_and_fetch_sql(cursor, sql_string=\"\"):\r\n try:\r\n # Executing a SQL query\r\n # cursor.execute(\"SELECT version();\")\r\n # cursor.execute(\"SELECT * from customer;\")\r\n cursor.execute(sql_string)\r\n # Fetch result\r\n # record = cursor.fetchone()\r\n # print(\"You are connected to - \", record, \"\\n\")\r\n record = cursor.fetchall()\r\n # print(\"Here are the first 5 rows\", record[:5])\r\n return record\r\n except (Exception, Error) as error:\r\n print(\"Errors while executes the code: \", error)\r\n return -1\r\n\r\ndef runSQL(cursor, sql_string=\"\"):\r\n try:\r\n cursor.execute(sql_string)\r\n return 1\r\n except (Exception, Error) as error:\r\n print(\"Errors while executes the code: \", error)\r\n return -1\r\n\r\ndef genreAssign(num):\r\n if num == 0:\r\n return \"history, historical fiction, biography\"\r\n elif num == 1:\r\n return \"fiction\"\r\n elif num==2:\r\n return \"fantasy, paranormal\"\r\n elif num==3:\r\n return \"mystery, thriller, crime\"\r\n elif num==4:\r\n return \"poetry\"\r\n elif num==5:\r\n return \"romance\"\r\n elif num==6:\r\n return \"non-fiction\"\r\n elif num==7:\r\n return \"children\"\r\n elif num==8:\r\n return \"young-adult\"\r\n elif num==9:\r\n return \"comics, graphic\"\r\n\r\ndef runnerSQL(cursor, sql_string=\"\"):\r\n cursor.execute(sql_string)\r\n return\r\n\r\n\r\n\r\n\r\nclass DatabaseConnection:\r\n def __init__(self, username, password, host, port, database):\r\n self.username = username\r\n self.password = password\r\n self.host = host\r\n self.port = port\r\n self.database = database\r\n print(self.username)\r\n self.connection = psycopg2.connect(user=self.username,\r\n password=self.password,\r\n host=self.host,\r\n port=self.port,\r\n database=self.database)\r\n \r\n # Create the tables in the database if they don't already exist.\r\n def setup_database(self):\r\n print(\"============================\")\r\n \r\n with self.getCursor() as cur:\r\n cur.execute(\"\"\"\r\n SELECT table_name FROM information_schema.tables\r\n WHERE table_schema = 'public'\r\n \"\"\")\r\n records = cur.fetchall()\r\n if len(records) == 0:\r\n # Create the tables that we need.\r\n # TODO: ADD THE REST OF OUR TABLES.\r\n cur.execute(\"\"\"\r\n CREATE TABLE users (\r\n id serial PRIMARY KEY,\r\n username varchar(255) UNIQUE NOT NULL,\r\n password varchar(255) NOT NULL\r\n )\r\n \"\"\")\r\n self.connection.commit()\r\n print(\"Created new table\")\r\n else:\r\n # List the tables that exist\r\n print(f\"Table exists already(count): {len(records)}\")\r\n for record in records:\r\n print(record)\r\n print(\"============================\")\r\n\r\n def getCursor(self):\r\n return self.connection.cursor()\r\n\r\n def runSQL(self, sql_string):\r\n try:\r\n with self.getCursor() as cur:\r\n cur.execute(sql_string)\r\n return True\r\n except Exception as e:\r\n print(\"Errors while executes the code: \", e)\r\n return False\r\n\r\n def runAndCommitSQL(self, sql_string):\r\n try:\r\n with self.getCursor() as cur:\r\n cur.execute(sql_string)\r\n self.connection.commit()\r\n return True\r\n except Exception as e:\r\n print(\"Errors while executes the code: \", e)\r\n return False\r\n\r\n def runAndFetchSQL(self, sql_string):\r\n try:\r\n with self.getCursor() as cur:\r\n cur.execute(sql_string)\r\n record = cur.fetchall()\r\n return record\r\n except (Exception, Error) as error:\r\n print(\"Errors while executes the code: \", error)\r\n return None\r\n","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":5379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"188381636","text":"#####################################################3\n#Creating a parsed file for the extraction of features for the original dataset.\n\n#library imports\n#import os \n#import numpy as np\n#import scipy as sp\n\n\n# Load the data from file.\nfname = open('membrane-alpha.3line.txt', 'r+')\nout_ids = open('id_list.txt', 'w')\nout_ids_seq = open('id_seq_list.fasta', 'w')\nout_seq = open('seqlist.txt', 'w')\nout_ids_feat = open('id_feat_list.txt', 'w')\nout_feat = open('feat_list.txt', 'w')\n\nout_both = open('both_list.txt', 'w')\n\n\n#creating Lists for Ids sequences and features\nmain_dict = {}\ntemp_list = []\nidslist = []\nseqlist = []\nfeat_list = []\n\n#iterating through the file and separating the id label, sequences and topology\n\nfor counter, line in enumerate(fname):\n line = line.strip()\n \n if counter % 3 == 0:\n line = line.split('\\n')\n line = line[0]\n #print(line)\n idslist.append(line)\n \n #Printing the 3 lists to a text file \n out_ids.write(line + '\\n')\n out_ids_seq.write(line + '\\n')\n out_ids_feat.write(line + '\\n')\n \n ######Sequence####################### \n elif counter % 3 == 1:\n line = line.split('\\n')\n line = line[0]\n #print(line)\n seqlist.append(line)\n \n #Printing the 3 lists to a text file \n out_seq.write(line + '\\n')\n out_ids_seq.write(line + '\\n')\n out_both.write(line + '\\n')\n \n ######Topology###########\n else:\n line = line.split('\\n')\n line = line[0]\n feat_list.append(line)\n \n #Printing the 3 lists to a text file \n out_feat.write(line + '\\n') \n out_ids_feat.write(line + '\\n')\n out_both.write(line + '\\n')\n \t\t\t\n#Printing the 3 lists to a text file \n\n#Closing the files which were opened\n\n\nfname.close()\nout_ids.close()\nout_seq.close()\nout_feat.close()\nout_both.close()\nout_ids_feat.close()\nout_ids_seq.close()","sub_path":"data/2017-02-28/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"216872834","text":"\"\"\"\n.. module:: tests.settings_test\n\t:synopsis: \n.. moduleauthor:: Alexander Groden \n\"\"\"\n\nimport unittest\nimport settings\n\n\nclass SettingsTest(unittest.TestCase):\n\tdef setUp(self):\n\t\tself.settings = settings.get_settings_for(\"test\")\n\t\tself.settings2 = settings.get_settings_for(\"test2\")\n\t\tself.cols = ('col1', 'col2', 'col3')\n\t\tself.settings3 = settings.get_settings_for(\"test3\", columns = self.cols)\n\n\tdef test_multiple_categories(self):\n\t\tself.settings['key1'] = 'value1'\n\t\tself.settings['key2'] = 1\n\t\tself.settings2['key2'] = 'value2'\n\t\tself.settings3['key3'] = ('one', 'two', 3)\n\t\tself.settings3['key4'] = {'col1': 'first'}\n\t\tself.settings3['key5'] = 42\n\t\tself.settings3['key6'] = ('first', 'second')\n\t\tself.assertEqual('value1', self.settings['key1'])\n\t\tself.assertEqual('1', self.settings['key2'])\n\t\tself.assertEqual(1, self.settings.get('key2', formatter=int))\n\t\tself.assertEqual('value2', self.settings2['key2'])\n\t\tself.assertSequenceEqual(self.settings3['key3'], (u'one', u'two', u'3'))\n\t\tself.assertSequenceEqual(\n\t\t\tself.settings3.get('key3', formatter=(str, str, int)), \n\t\t\t('one', 'two', 3))\n\t\tself.assertSequenceEqual(\n\t\t\tself.settings3.get('key3', formatter=(str, str)), \n\t\t\t('one', 'two', u'3'))\n\t\tself.assertSequenceEqual(\n\t\t\tself.settings3.get('key3', formatter=str), \n\t\t\t('one', u'two', u'3'))\n\t\tself.assertSequenceEqual(\n\t\t\tself.settings3.get('key3', formatter={'col3': int}), \n\t\t\t('one', u'two', 3))\n\t\tself.assertSequenceEqual(\n\t\t\tself.settings3.get('key6', formatter=str),\n\t\t\t('first', 'second', 'None'))\n\t\tself.assertSequenceEqual(self.settings3['key5'], (u'42', u'42', u'42'))\n\t\tself.assertSequenceEqual(\n\t\t\tself.settings3.get('key1', 'failure', (str, str, int)), \n\t\t\t'failure')\n\t\tself.assertSequenceEqual(self.settings3['key4'], ('first', None, None))\n\t\tself.assertSequenceEqual(self.settings3['key6'], ('first', 'second', None))\n\t\twith self.assertRaises(KeyError):\n\t\t\tself.settings['failkey']\n\t\twith self.assertRaises(KeyError):\n\t\t\tself.settings2['failkey']\n\t\twith self.assertRaises(KeyError):\n\t\t\tself.settings3['failkey']\n\t\twith self.assertRaises(ValueError):\n\t\t\tself.settings3.get('key3', formatter=(int, int, int))\n\t\twith self.assertRaises(ValueError):\n\t\t\tself.settings3.get('key3', formatter={'failcol': int})\n\n\tdef test_get_and_set(self):\n\t\tself.settings['key1'] = 'value1'\n\t\tself.settings['nonekey'] = None\n\t\tself.assertEqual('value1', self.settings['key1'])\n\t\tself.assertEqual(None, self.settings['nonekey'])\n\t\twith self.assertRaises(KeyError):\n\t\t\tself.settings[\"failkey\"]\n\t\tself.assertEqual(\"default\", self.settings.get(\"failKey\", \"default\"))\n\t\tself.assertEqual(\"value1\", self.settings.get(\"key1\", \"default\"))\n\n\tdef test_length(self):\n\t\tself.settings['0'] = 0\n\t\tself.settings['1'] = 1\n\t\tself.settings['2'] = 2\n\t\tself.settings3[0] = 'zero'\n\t\tself.settings3[1] = 'one' \n\t\tself.assertTrue(len(self.settings) is 3)\n\t\tself.settings['3'] = 3\n\t\tself.assertTrue(len(self.settings) is 4)\n\n\tdef test_iter(self):\n\t\tnums = dict([(x,x) for x in range(0, 11)])\n\t\tfor key, value in nums.iteritems():\n\t\t\tself.settings[key] = value\n\t\t# each key value should be equal\n\t\tfor key, value in self.settings.iteritems():\n\t\t\tself.assertEqual(key, value)\n\t\t# each value for both dicts should be equal\n\t\tfor key in self.settings:\n\t\t\tself.assertEqual(self.settings[key], str(nums[int(key)]))\n\t\t# make changes during iteration\n\t\tevens = dict([(x, x) for x in range(0, 14, 2)])\n\t\tfor key in self.settings:\n\t\t\tif int(key) % 2 is not 0: # remove all odd numbers\n\t\t\t\tdel self.settings[key]\n\t\tself.settings[12] = 12\n\t\t# all values should be even\n\t\tfor value in self.settings.itervalues():\n\t\t\tself.assertTrue(int(value) % 2 is 0)\n\t\t# each value in the evens dict should be equal\n\t\tfor key in self.settings:\n\t\t\tself.assertEqual(self.settings[key], str(evens[int(key)]))\n\n\tdef test_delete(self):\n\t\tself.settings['delkey'] = \"delete me\"\n\t\tself.settings3['delkey'] = ('one', 'two', 3)\n\t\tself.assertEqual(\"delete me\", self.settings['delkey'])\n\t\tself.assertSequenceEqual((u'one', u'two', u'3'), self.settings3['delkey'])\n\t\tdel self.settings['delkey']\n\t\tdel self.settings3['delkey']\n\t\twith self.assertRaises(KeyError):\n\t\t\tself.settings['delkey']\n\t\twith self.assertRaises(KeyError):\n\t\t\tself.settings3['delkey']\n\n\n\tdef test_clear(self):\n\t\tself.settings['clearkey'] = \"clear me\"\n\t\tself.settings['clearkey2'] = \"clear me 2\"\n\t\tself.settings3['clearkey'] = ('clear', 'me', 3)\n\t\tself.assertEqual(\"clear me\", self.settings['clearkey'])\n\t\tself.assertEqual(\"clear me 2\", self.settings['clearkey2'])\n\t\tself.assertEqual((u'clear', u'me', u'3'), self.settings3['clearkey'])\n\t\tself.settings.clear()\n\t\tself.settings3.clear()\n\t\twith self.assertRaises(KeyError):\n\t\t\tself.settings['clearkey']\n\t\twith self.assertRaises(KeyError):\n\t\t\tself.settings['clearkey2']\n\t\twith self.assertRaises(KeyError):\n\t\t\tself.settings3['clearkey']\n\n\tdef tearDown(self):\n\t\tself.settings.delete()\n\t\tself.settings2.delete()\n\t\tself.settings3.delete()\n\n\nif __name__ == '__main__':\n\tunittest.main()","sub_path":"tests/settings_test.py","file_name":"settings_test.py","file_ext":"py","file_size_in_byte":4971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"389139309","text":"\"\"\"\nGiven a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length of s is 1000.\n\"\"\"\nclass Solution1:\n\t\"\"\"\n\t@parameters s: input string\n\t@ return : the longest palindromic subsequence\n\t\"\"\"\n\tdef longesrPalindramic(self,s):\n\t\tif not s:\n\t\t\treturn False\n\t\tself.left = 0\n\t\tself.maxLength = 0\n\t\tfor middle in range(len(s)):\n\t\t\tself.find_longest_palindrome_from(s,middle,middle)\n\t\t\tself.find_longest_palindrome_from(s,middle,middle+1)\n\n\t\treturn s[self.left:self.left+self.maxLength-1]\n\n\tdef find_longest_palindrome_from(self, s, left, right):\n\t\twhile (left >= 0 and right < len(s) and s[left] == s[right]): \n\t\t# 这里很神奇, 如果写错 while (s[left] == s[right] and left >= 0 and right < len(s)),会出现out of string的错误,所以要先对指针进行下检查\n\t\t\tleft -= 1\n\t\t\tright += 1\n\t\tif self.maxLength < right - left + 1:\n\t\t\tself.maxLength = right - left + 1\n\t\t\tself.left = left + 1","sub_path":"Python Version/String/Longest Palindromic Subsequence.py","file_name":"Longest Palindromic Subsequence.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"473221400","text":"\nixpfree = 0\n\nxp = list() # shared horizontal positions\n\nclass Xpos:\n Width_min = 1.0\n\n def __init__(self):\n self.type = None\n self.next = None\n self.prev = None\n self.elon = 0\n self.p = None\n self.time = None\n self.dur = None\n self.wl = 0\n self.wr = 0\n self.space = 1\n self.shrink = 1\n self.stretch = 1\n self.tfac = 0\n self.x = 0.0\n\n def __add__(self):\n pass\n\n def set_position(self):\n n = 0\n v = ivc0\n xp_current = xp[0]\n for i in range(len(voice.syms)):\n n += 1\n xp_prev = xp[n-1]\n xp_next = xp[n+1]\n symbols[v][i].p = n\n","sub_path":"abctab/positions.py","file_name":"positions.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"54523678","text":"# coding: utf-8\nfrom collections import OrderedDict\n\nimport requests\nimport time\n\nfrom .exceptions import HasOffersException, MaxRetriesExceeded\nfrom .logging import get_logger\nfrom .models import MODEL_MANAGERS\nfrom .utils import prepare_query_params\n\n\ndef is_empty(data):\n return isinstance(data, bool) or not data\n\n\ndef is_paginated(data):\n return 'pageCount' in data\n\n\ndef retry(method):\n \"\"\"\n Allows to retry method execution few times.\n \"\"\"\n\n def inner(self, *args, **kwargs):\n attempt_number = 1\n while attempt_number < self.retries:\n try:\n return method(self, *args, **kwargs)\n except HasOffersException as exc:\n if not 'API usage exceeded rate limit' in str(exc):\n raise exc\n self.logger.debug('Retrying due: %s', exc)\n time.sleep(self.retry_timeout)\n attempt_number += 1\n raise MaxRetriesExceeded\n\n return inner\n\n\nclass HasOffersAPI:\n \"\"\"\n Client to communicate with HasOffers API.\n \"\"\"\n\n def __init__(self, endpoint=None, network_token=None, network_id=None, verify=True, retries=3, retry_timeout=3,\n verbosity=0):\n self.endpoint = endpoint\n self.network_token = network_token\n self.network_id = network_id\n self.verify = verify\n self.retries = retries\n self.retry_timeout = retry_timeout\n self.logger = get_logger(verbosity)\n self.setup_managers()\n\n def setup_managers(self):\n \"\"\"\n Allows to access manager by model name - it is convenient, because HasOffers returns model names in responses.\n \"\"\"\n self._managers = {}\n for manager_class in MODEL_MANAGERS:\n instance = manager_class(self)\n setattr(self, instance.name, instance)\n if instance.model:\n self._managers[instance.model.__name__] = instance\n\n def __str__(self):\n return '%s: %s / %s' % (self.__class__.__name__, self.network_token, self.network_id)\n\n def __repr__(self):\n return '<%s>' % self\n\n @property\n def session(self):\n if not hasattr(self, '_session'):\n self._session = requests.Session()\n return self._session\n\n @retry\n def _call(self, target, method, single_result=True, raw=False, **kwargs):\n \"\"\"\n Low-level call to HasOffers API.\n \"\"\"\n params = prepare_query_params(\n NetworkToken=self.network_token,\n NetworkId=self.network_id,\n Target=target,\n Method=method,\n **kwargs\n )\n self.logger.debug('Request parameters: %s', params)\n response = self.session.get(self.endpoint, params=params, verify=self.verify)\n self.logger.debug('Response [%s]: %s', response.status_code, response.text)\n response.raise_for_status()\n data = response.json(object_pairs_hook=OrderedDict)\n return self.handle_response(data, target=target, single_result=single_result, raw=raw)\n\n def handle_response(self, content, target=None, single_result=True, raw=False):\n \"\"\"\n Parses response, checks it.\n \"\"\"\n response = content['response']\n\n self.check_errors(response)\n\n data = response.get('data')\n\n if is_empty(data):\n return data\n elif is_paginated(data):\n if not data['count']:\n return data['data']\n data = data['data']\n\n if raw:\n return data\n return self.init_all_objects(data, target=target, single_result=single_result)\n\n def check_errors(self, response):\n errors = response.get('errors')\n if errors:\n raise HasOffersException(errors)\n\n def init_all_objects(self, data, target=None, single_result=True):\n \"\"\"\n Initializes model instances from given data.\n Returns single instance if single_result=True.\n \"\"\"\n if single_result:\n return self.init_target_object(target, data)\n return list(self.expand_models(target, data))\n\n def init_target_object(self, target, data):\n \"\"\"\n Initializes target object and assign extra objects to target as attributes\n \"\"\"\n target_object = self.init_single_object(target, data.pop(target))\n for key, item in data.items():\n setattr(target_object, key.lower(), self.init_single_object(key, item))\n return target_object\n\n def init_single_object(self, target, data):\n if data:\n return self._managers[target].init_instance(data)\n\n def expand_models(self, target, data):\n \"\"\"\n Generates all objects from given data.\n \"\"\"\n if isinstance(data, dict):\n data = data.values()\n for chunk in data:\n if target in chunk:\n yield self.init_target_object(target, chunk)\n else:\n for key, item in chunk.items():\n yield self.init_single_object(key, item)\n","sub_path":"pyoffers/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":5042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"214791241","text":"\"\"\"\n Copyright (c) 2020 Intel Corporation\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\"\"\"\n\nimport cv2\nimport os\nimport numpy as np\n\nfrom postprocessor import RetinaFacePostprocessor\n\nclass Detector(object):\n def __init__(self, ie, model_path, face_prob_threshold, device='CPU'):\n model = ie.read_network(model_path, os.path.splitext(model_path)[0] + '.bin')\n\n assert len(model.input_info) == 1, \"Expected 1 input blob\"\n assert len(model.outputs) == 12 or len(model.outputs) == 9, \"Expected 12 or 9 output blobs\"\n\n self._input_layer_name = next(iter(model.input_info))\n self._output_layer_names = model.outputs\n _, channels, self.input_height, self.input_width = model.input_info[self._input_layer_name].input_data.shape\n assert channels == 3, \"Expected 3-channel input\"\n\n self._detect_masks = len(model.outputs) == 12\n self.face_prob_threshold = face_prob_threshold\n\n self._ie = ie\n self._exec_model = self._ie.load_network(model, device)\n\n self.infer_time = -1\n\n def infer(self, image):\n t0 = cv2.getTickCount()\n output = self._exec_model.infer(inputs={self._input_layer_name: image})\n self.infer_time = (cv2.getTickCount() - t0) / cv2.getTickFrequency()\n return output\n\n def detect(self, image):\n height, width = image.shape[:2]\n image = cv2.resize(image, (self.input_width, self.input_height))\n image = np.transpose(image, (2, 0, 1))\n image = np.expand_dims(image, axis=0)\n output = self.infer(image)\n scale_x = self.input_width/width\n scale_y = self.input_height/height\n postprocessor = RetinaFacePostprocessor(self._detect_masks)\n detections = postprocessor.process_output(output, scale_x, scale_y, self.face_prob_threshold)\n return detections, self._detect_masks\n","sub_path":"demos/python_demos/object_detection_demo_retinaface/detector.py","file_name":"detector.py","file_ext":"py","file_size_in_byte":2351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"198350739","text":"#!/usr/bin/env python3\n\nimport re\nimport glob\n\ndef read_test_results(filename):\n res = []\n with open(filename, 'r') as f:\n for line in f:\n\n match = re.match('^#([0-9]+/[pu])(.*)\\\\b(OK|SKIP|FAIL)\\\\b', line)\n if match:\n testid = match[1]\n desc = match[2]\n result = match[3]\n res.append((testid, desc, result))\n else:\n assert not line.startswith('#'), line\n return res\n\n\ndef filter(d, result):\n return {x for x in d if x[2] == result}\n\nres = {}\n\nfor name in glob.glob('*.log'):\n res[name.split('.')[0]] = read_test_results(name)\n\n","sub_path":"rv32-linux/test_verifier/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"448005764","text":"import discord\nfrom discord.ext import commands\n\n\nclass Admin:\n def __init__(self, bot):\n self.bot = bot\n\n @commands.has_role(\"memelord supreme\")\n @commands.guild_only()\n @commands.command()\n async def xdchannel(self, ctx, xd_channel: discord.TextChannel):\n \"\"\"Sets the xd channel for the current server.\"\"\"\n self.bot._xd_channel = xd_channel.id\n await ctx.send(\"yep now <#{}> is the xd channel\".format(xd_channel.id))\n\n @commands.has_role(\"memelord supreme\")\n @commands.guild_only()\n @commands.command()\n async def blacklist(self, ctx, operator, user: discord.User):\n \"\"\"Changes a user's blacklist status.\"\"\"\n if operator == \"+\":\n if user.id in bot._blacklist:\n await ctx.send(\"error: user already in blacklist\")\n return\n self.bot._blacklist.append(user.id)\n elif operator == \"-\":\n if user.id not in bot._blacklist:\n await ctx.send(\"error: user not in blacklist\")\n return\n self.bot._blacklist.remove(user.id)\n\n @blacklist.error\n async def blacklist_error(self, ctx, error):\n if isinstance(error, commands.MissingRequiredArgument):\n await ctx.send(\"error: must have operator + or -/must have user\")\n elif isinstance(error, commands.BadArgument):\n await ctx.send(\"error: invalid user/user not found\")\n\n @commands.has_role(\"memelord supreme\")\n @commands.command()\n async def changegame(self, ctx, new_game):\n \"\"\"Change the current \"playing\" message; use quotes.\"\"\"\n await self.bot.change_presence(game=discord.Game(name=new_game))\n\n\ndef setup(bot):\n bot.add_cog(Admin(bot))\n","sub_path":"cogs/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"104557402","text":"from abc import abstractmethod\nimport multiprocessing as mp\nfrom src import IterToolsHectoc\nimport time\n\n\nclass HectocStrategy:\n \"\"\"\n An abstract strategy providing solving capabilities for a hectoc problem\n \"\"\"\n def solve_hectoc_puzzle(self, input_numbers: [int], number_threads: int):\n raise NotImplementedError(\"This is the abstract superclass, use the implemented subclasses instead\")\n\n def split_in_pieces(self, options: [str], number_threads: int):\n \"\"\"\n Splits array into subarrays for multithreading\n :param options: aray to split\n :param number_threads: number of buckets\n :return: array with splits\n \"\"\"\n option_array = []\n len_opt = len(options)\n step_size = len_opt // number_threads + 1\n if step_size == 0:\n return options\n for i in range(1, number_threads + 1):\n sub_array = options[(i - 1) * step_size: min(i * step_size, len_opt)]\n option_array.append(sub_array)\n return option_array\n\n def run_in_parallel(self, candidates, number_threads):\n processes = []\n options_split = self.split_in_pieces(candidates, number_threads)\n ctx = mp.get_context('spawn')\n for candidate in options_split:\n p = ctx.Process(target=IterToolsHectoc.solve, args=(candidate,))\n processes.append(p)\n p.start()\n for process in processes:\n process.join()\n\n\nclass BruteForceStrategy(HectocStrategy):\n @abstractmethod\n def solve_hectoc_puzzle(self, input_numbers: [int], number_threads: int):\n\n allPermutations = self.find_permutations_of_numbers_and_operators(input_numbers)\n\n candidates = self.find_all_parantheses(allPermutations)\n\n self.run_in_parallel(candidates, number_threads)\n\n def find_all_parantheses(self, allPermutations):\n cand_start = time.time()\n candidates = IterToolsHectoc.find_all_paranthesized_options(allPermutations)\n cand_end = time.time()\n print(\"Finding all paranthesis in: \" + str(cand_end - cand_start) + \" seconds\")\n print(\"Resulting: \" + str(len(candidates)) + \" solution candidates\")\n return candidates\n\n def find_permutations_of_numbers_and_operators(self, input_numbers):\n per_start = time.time()\n allPermutations = IterToolsHectoc.get_all_concatenated_combinations_with_operators(input_numbers, ['+', '-', '*', '/', '^'])\n per_end = time.time()\n print(\n \"Finding \" + str(len(allPermutations)) + \" operator and number combinations in: \" + str(per_end - per_start) + \" seconds\")\n return allPermutations\n\n\nclass CloseToHundredStrategy(HectocStrategy):\n @abstractmethod\n def solve_hectoc_puzzle(self, input_numbers: [int], number_threads: int):\n raise NotImplementedError(\"Not yet implemented\")\n\n\nclass WorkWithFourStrategy(HectocStrategy):\n @abstractmethod\n def solve_hectoc_puzzle(self, input_numbers: [int], number_threads: int):\n raise NotImplementedError(\"Not yet implemented\")\n\n\nclass WorkWithFiveStrategy(HectocStrategy):\n @abstractmethod\n def solve_hectoc_puzzle(self, input_numbers: [int], number_threads: int):\n raise NotImplementedError(\"Not yet implemented\")\n\n\nclass WorkWithTenStrategy(HectocStrategy):\n @abstractmethod\n def solve_hectoc_puzzle(self, input_numbers: [int], number_threads: int):\n raise NotImplementedError(\"Not yet implemented\")\n","sub_path":"src/HectocStrategy.py","file_name":"HectocStrategy.py","file_ext":"py","file_size_in_byte":3469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"424002511","text":"import sys\nsys.stdin = open('input.txt', 'r')\n\n\ndr = [0, 0, 1, -1]\ndc = [1, -1, 0, 0]\ndef dfs(r, c, cnt, tmp):\n if cnt == 6:\n result.add(tmp)\n else:\n for i in range(4):\n nr = r + dr[i]\n nc = c + dc[i]\n if 0 <= nr < 4 and 0 <= nc < 4:\n dfs(nr, nc, cnt + 1, tmp + matrix[nr][nc])\n\n\nfor tc in range(1, int(input()) + 1):\n matrix = [input().split() for tc in range(4)]\n result = set()\n for i in range(4):\n for j in range(4):\n dfs(i, j, 0, matrix[i][j])\n\n print('#{} {}'.format(tc, len(result)))","sub_path":"SWEA/2819.격자판의숫자이어붙이기.py","file_name":"2819.격자판의숫자이어붙이기.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"584080731","text":"import pygame\nfrom pygame.locals import *\n\n\n\n\nblack = (0, 0, 0)\nwhite = (255, 255, 255)\ngreen = (0, 255, 0)\nred = (255, 0, 0)\npygame.mixer.pre_init(44100,16,2,4096)\npygame.init()\n\n\n#The Ring What get put where on the Ring\nwidth = 512\nheight = 448\n\n#Back Ground Image\n# Location of background image x, y\n\n# pick background image change with enemy maybe\nbackground1 = pygame.image.load(\"background_mini.png\")\n# Set the width and height of the screen [width, height]\nsize = (512, 448)\nscreen = pygame.display.set_mode(size)\nfont = pygame.font.Font(None, 32)\npygame.display.set_caption(\"Timer Test\")\n\n\n#play background music\n\npygame.mixer.music.load(\"greatfighting.ogg\")\npygame.mixer.music.set_volume(0.5)\npygame.mixer.music.play(1)\n\n# Loop until the user clicks the close button.\ndone = False\n# Used to manage how fast the screen updates\nclock = pygame.time.Clock()\nframe_count = 0\nframe_rate = 60\nstart_time = 180\n# -------- Main Program Loop -----------\nwhile not done:\n for event in pygame.event.get(): # User did something\n if event.type == pygame.QUIT: # If user clicked close\n done = True # Flag that we are done so we exit this loop\n # Set the screen background\n screen.fill(white)\n # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT\n # --- Timer going up ---\n # Calculate total seconds\n total_seconds = frame_count // frame_rate\n # Divide by 60 to get total minutes\n minutes = total_seconds // 60\n # Use modulus (remainder) to get seconds\n seconds = total_seconds % 60\n # Use python string formatting to format in leading zeros\n output_string = \"{0:02}:{1:02}\".format(minutes, seconds)\n # Blit to the screen\n screen.blit(background1, [0, 0])\n text = font.render(output_string, True, white)\n screen.blit(text, [420, 38])\n # --- Timer going down ---\n # Blit to the screen\n # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT\n frame_count += 1\n # Limit to 20 frames per second\n clock.tick(frame_rate)\n # Go ahead and update the screen with what we've drawn.\n pygame.display.flip()\n# Be IDLE friendly. If you forget this line, the program will 'hang'\n# on exit.\npygame.quit()\n","sub_path":"background_sound_demo/sound_test_timer.py","file_name":"sound_test_timer.py","file_ext":"py","file_size_in_byte":2167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"614824914","text":"# Copyright notice:\n# Copyright Members of the EMI Collaboration, 2013.\n#\n# See www.eu-emi.eu for details on the copyright holders\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\ndef do_connect(config, map):\n \"\"\"\n Base urls\n \"\"\"\n # Root\n map.connect('/', controller='misc', action='api_version')\n\n # Whoami\n map.connect('/whoami', controller='misc', action='whoami')\n map.connect('/whoami/certificate', controller='misc', action='certificate')\n\n # Delegation\n map.connect('/delegation/{dlg_id}', controller='delegation', action='view',\n conditions=dict(method=['GET']))\n map.connect('/delegation/{dlg_id}', controller='delegation', action='delete',\n conditions=dict(method=['DELETE']))\n map.connect('/delegation/{dlg_id}/request', controller='delegation', action='request',\n conditions=dict(method=['GET']))\n map.connect('/delegation/{dlg_id}/credential', controller='delegation', action='credential',\n conditions=dict(method=['PUT', 'POST']))\n map.connect('/delegation/{dlg_id}/voms', controller='delegation', action='voms',\n conditions=dict(method=['POST']))\n\n # Delegation HTML view\n map.connect('/delegation', controller='delegation', action='delegation_page',\n conditions=dict(method=['GET']))\n\n # Jobs\n map.connect('/jobs', controller='jobs', action='index',\n conditions=dict(method=['GET']))\n map.connect('/jobs/', controller='jobs', action='index',\n conditions=dict(method=['GET']))\n map.connect('/jobs/{job_id}', controller='jobs', action='get',\n conditions=dict(method=['GET']))\n map.connect('/jobs/{job_id}/files', controller='jobs', action='get_files',\n conditions=dict(method=['GET']))\n map.connect('/jobs/{job_id}/files/{file_id}/retries', controller='jobs', action='get_file_retries',\n conditions=dict(method=['GET']))\n map.connect('/jobs/{job_id}/{field}', controller='jobs', action='get_field',\n conditions=dict(method=['GET']))\n map.connect('/jobs/{job_id_list}', controller='jobs', action='cancel',\n conditions=dict(method=['DELETE']))\n map.connect('/jobs', controller='jobs', action='submit',\n conditions=dict(method=['PUT', 'POST']))\n\n map.connect('/jobs/{job_id}', controller='jobs', action='job_options',\n conditions=dict(method=['OPTIONS']))\n map.connect('/jobs', controller='jobs', action='options',\n conditions=dict(method=['OPTIONS']))\n\n # Archive\n map.connect('/archive', controller='archive', action='index',\n conditions=dict(method=['GET']))\n map.connect('/archive/', controller='archive', action='index',\n conditions=dict(method=['GET']))\n map.connect('/archive/{job_id}', controller='archive', action='get',\n conditions=dict(method=['GET']))\n map.connect('/archive/{job_id}/{field}', controller='archive',\n action='get_field',\n conditions=dict(method=['GET']))\n\n # Schema definition\n map.connect('/api-docs/schema/submit', controller='api', action='submit_schema')\n map.connect('/api-docs', controller='api', action='api_docs')\n map.connect('/api-docs/{resource}', controller='api', action='resource_doc')\n\n # Configuration audit\n map.connect('/config/audit', controller='config', action='audit')\n\n # Optimizer\n map.connect('/optimizer', controller='optimizer', action='is_enabled')\n map.connect('/optimizer/evolution', controller='optimizer',\n action='evolution')\n\n # GFAL2 bindings\n map.connect('/dm/list', controller='datamanagement', action='list')\n map.connect('/dm/stat', controller='datamanagement', action='stat')\n map.connect('/dm/mkdir', controller='datamanagement', action='mkdir', conditions=dict(method=['POST']))\n map.connect('/dm/unlink', controller='datamanagement', action='unlink', conditions=dict(method=['POST']))\n map.connect('/dm/rmdir', controller='datamanagement', action='rmdir', conditions=dict(method=['POST']))\n map.connect('/dm/rename', controller='datamanagement', action='rename', conditions=dict(method=['POST']))\n\n # Snapshot\n map.connect('/snapshot', controller='snapshot', action='snapshot')\n\n # Banning\n map.connect('/ban/se', controller='banning', action='ban_se', conditions=dict(method=['POST']))\n map.connect('/ban/se', controller='banning', action='unban_se', conditions=dict(method=['DELETE']))\n map.connect('/ban/dn', controller='banning', action='ban_dn', conditions=dict(method=['POST']))\n map.connect('/ban/dn', controller='banning', action='unban_dn', conditions=dict(method=['DELETE']))\n","sub_path":"src/fts3rest/fts3rest/config/routing/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":5287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"629974218","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Date : 2017-07-18 14:47:58\n# @Author : Li Hao (howardlee_h@outlook.com)\n# @Link : https://github.com/SAmmer0\n# @Version : $Id$\n'''\n因子查询模块\n\n__version__ = 1.0.0\n修改日期:2017-07-19\n修改内容:\n 添加add_abs_path\n\n修改日期:2017-07-27\n修改内容:\n 给query函数添加fillna参数选项\n'''\n__version__ = '1.0.0'\n\nfrom datatoolkits import load_pickle\nfrom ..const import FACTOR_DICT_FILE_PATH\nfrom .. import database\n\n# --------------------------------------------------------------------------------------------------\n# 常量\n\n# --------------------------------------------------------------------------------------------------\n# 函数\n\n\ndef query(factor_name, time, codes=None, fillna=None):\n '''\n 接受外部的请求,从数据库中获取对应因子的数据\n\n Parameter\n ---------\n factor_name: str\n 需要查询的因子名称\n time: type that can be converted by pd.to_datetime or tuple of that\n 单一的参数表示查询横截面的数据,元组(start_time, end_time)表示查询时间序列数据\n codes: list, default None\n 需要查询数据的股票代码,默认为None,表示查询所有股票的数据\n fillna: int or float, default\n 是否给NA值进行填充,默认为None,即不需要填充,如果需要填充则将填充值传给fillna参数\n Return\n ------\n out: pd.DataFrame\n 查询结果数据,index为时间,columns为股票代码,如果未查询到符合要求的数据,则返回None\n '''\n factor_dict = load_pickle(FACTOR_DICT_FILE_PATH)\n if factor_dict is None:\n raise ValueError('Dictionary file needs initialization...')\n assert factor_name in factor_dict, \\\n 'Error, factor name \"{pname}\" is'.format(pname=factor_name) +\\\n ' not valid, valid names are {vnames}'.format(vnames=list(factor_dict.keys()))\n abs_path = factor_dict[factor_name]\n db = database.DBConnector(abs_path)\n data = db.query(time, codes)\n if fillna is not None:\n data = data.fillna(fillna)\n return data\n","sub_path":"fmanager/factors/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":2145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"424546909","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 25 13:45:36 2014\n\n@author: Kyle\nI found another library which performs a nearly identical function after I wrote this. It is located in https://github.com/ZhuangLab/storm-analysis/blob/master/sa_library/gaussfit.py\n\"\"\"\nimport numpy as np\nfrom leastsqbound import leastsqbound\n\n\ndef cosd(degrees):\n return np.cos(np.radians(degrees))\n\n\ndef sind(degrees):\n return np.sin(np.radians(degrees))\n\n\ndef fitGaussian(I=None, p0=None, bounds=None):\n \"\"\"\n SYMETRICAL GAUSSIAN\n Takes an nxm matrix and returns an nxm matrix which is the gaussian fit\n of the first. p0 is a list of parameters [xorigin, yorigin, sigma,amplitude]\n 0-19 should be [-.2889 -.3265 -.3679 -.4263 -.5016 -.6006 ... -.0228 .01913]\n \"\"\"\n\n x=np.arange(I.shape[0])\n y=np.arange(I.shape[1])\n X=[x,y]\n p0=[round(p,3) for p in p0] \n p, cov_x, infodic, mesg, ier = leastsqbound(err, p0,args=(I,X),bounds = bounds, maxfev=100, full_output=True)\n # xorigin, yorigin, sigma, amplitude=p\n I_fit=gaussian(x[:,None], y[None,:],*p)\n return p, I_fit, I_fit\n\n \ndef gaussian(x, y, xorigin, yorigin, sigma, amplitude):\n \"\"\" xorigin, yorigin, sigma, amplitude \"\"\"\n return amplitude*(np.exp(-(x-xorigin)**2/(2.*sigma**2))*np.exp(-(y-yorigin)**2/(2.*sigma**2)))\n\n\ndef generate_gaussian(mx, sigma=1.15):\n assert mx % 2 == 1 # mx must be odd\n x = np.arange(mx)\n y = np.arange(mx)\n xorigin = int(np.floor(mx / 2.))\n yorigin = xorigin\n amplitude = 1\n I = gaussian(x[:, None], y[None, :], xorigin, yorigin, sigma, amplitude)\n I = I - (np.sum(I) / mx ** 2)\n return I\n \ndef gaussian_1var(p, x):\n \"\"\" xorigin, yorigin, sigma, amplitude \"\"\"\n xorigin,yorigin,sigma,amplitude= p\n x0=x[0]\n x1=x[1]\n x0=x0[:,None]\n x1=x1[None,:]\n return amplitude*(np.exp(-(x0-xorigin)**2/(2.*sigma**2))*np.exp(-(x1-yorigin)**2/(2.*sigma**2)))\n \n \ndef err(p, y, x):\n \"\"\"\n p is a tuple contatining the initial parameters. p = (xorigin, yorigin, sigma, amplitude)\n y is the data we are fitting to (the dependent variable)\n x is the independent variable\n \"\"\"\n remander = y - gaussian_1var(p, x)\n remander = remander**2\n return remander.ravel()\n \n\n \n \n \n \n \n\n","sub_path":"pynsight/gaussianFitting 2.py","file_name":"gaussianFitting 2.py","file_ext":"py","file_size_in_byte":2279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"293114142","text":"import urllib.request\nimport json\nimport dml\nimport prov.model\nimport datetime\nimport uuid\nfrom math import *\nimport random\n\n#find the correlation between crimerate and distance to closest police stations.\nclass policeCrimeCorrelation(dml.Algorithm):\n contributor = 'ashleyyu_bzwtong_xhug'\n reads = ['ashleyyu_bzwtong_xhug.crimerate']\n writes = ['ashleyyu_bzwtong_xhug.policeCrimeCorrelation']\n\n\n def avg(x): # Average\n return sum(x)/len(x)\n \n def correlation(x, y):\n assert len(x) == len(y)\n n = len(x)\n assert n > 0\n avg_x = policeCrimeCorrelation.avg(x)\n avg_y = policeCrimeCorrelation.avg(y)\n diffprod = 0\n xdiff2 = 0\n ydiff2 = 0\n for idx in range(n):\n xdiff = x[idx] - avg_x\n ydiff = y[idx] - avg_y\n diffprod += xdiff * ydiff\n xdiff2 += xdiff * xdiff\n ydiff2 += ydiff * ydiff\n \n return diffprod / sqrt(xdiff2 * ydiff2)\n \n #takes two coordinates and calcualtes the distance between them in kilometers\n def distanceToPolice(coord1,coord2):\n def haversin(x):\n return sin(x/2)**2 \n return 2 * asin(sqrt(\n haversin(radians(coord2[0])-radians(coord1[0])) +\n cos(radians(coord1[0])) * cos(radians(coord2[0])) * haversin(radians(coord2[1])-radians(coord1[1]))))*6371\n\n \n @staticmethod\n def execute(trial):\n\n startTime = datetime.datetime.now()\n\n client = dml.pymongo.MongoClient()\n repo = client.repo\n repo.authenticate('ashleyyu_bzwtong', 'ashleyyu_bzwtong')\n\n #get locations of all crime incidents. In trial mode only get 50 incidents\n crimedata = repo['ashleyyu_bzwtong.crimerate'].find()\n if (trial == True):\n locations = [tuple(row['Location'].replace('(', '').replace(')', '').split(',')) \n \t\t\t\tfor row in crimedata if row['Location'] != '(0.00000000, 0.00000000)' \n \t\t\t\tand row['Location'] != '(-1.00000000, -1.00000000)' ][:200]\n else:\n locations = [tuple(row['Location'].replace('(', '').replace(')', '').split(',')) \n \t\t\t\tfor row in crimedata if row['Location'] != '(0.00000000, 0.00000000)' \n \t\t\t\tand row['Location'] != '(-1.00000000, -1.00000000)' ]\n locations = [(float(lat), float(lon)) for (lat, lon) in locations]\n\n #get locations of Boston Police Departments\n url = 'http://datamechanics.io/data/ashleyyu_bzwtong/cityOfBostonPolice.json'\n response = urllib.request.urlopen(url).read().decode(\"utf-8\")\n police = json.loads(response)\n policeStation = police['data']['fields'][3]['statistics']['values']\n coordinates = []\n for i in policeStation:\n \t\tcoordinates.append((i['lat'],i['long']))\n\n #for each crime location, calculate its distance to the closest police station\n distanceToCops = []\n for crime in locations:\n #print('crime ',type(crime),crime)\n dis = 100\n for station in coordinates:\n #print('station ',type(station),station)\n dist = policeCrimeCorrelation.distanceToPolice(crime,station)\n if dist < dis:\n dis = dist\n distanceToCops.append(dis)\n #print(max(distanceToCops),min(distanceToCops))\n \n #group distances into different ranges\n #distanceRangeCount: (in the area of less than 0.5km away from police stations, x number of crime happened),\n #(in the area of 0.5~1km away from police stations, y number of crime happened), (1~1.5km away)......\n distanceRangeCount = [[0.5,0],[1,0],[1.5,0],[2,0],[2.5,0],[3,0],[3.5,0],[4,0],[4.5,0],[5,0],[5.5,0]]\n\n #count the crime frequency for each distance range\n for i in distanceToCops:\n index = int(i//0.5)\n if index>10: index = 10\n distanceRangeCount[index][1]+=1\n #print(distanceRangeCount)\n\n #calculate correlation coefficient\n rangeCountTuples = [(a,b) for [a,b] in distanceRangeCount]\n x_distance = [a for (a,b) in rangeCountTuples]\n y_frequency = [b for (a,b) in rangeCountTuples]\n\n coefficient = round(policeCrimeCorrelation.correlation(x_distance,y_frequency),3)\n\n print('correlation coefficient between distance to police station and crimerate is ', coefficient)\n\n repo.logout()\n \n endTime = datetime.datetime.now()\n \n return {\"start\":startTime, \"end\":endTime}\n \n @staticmethod\n def provenance(doc = prov.model.ProvDocument(), startTime = None, endTime = None):\n '''\n Create the provenance document describing everything happening\n in this script. Each run of the script will generate a new\n document describing that invocation event.\n '''\n\n # Set up the database connection.\n client = dml.pymongo.MongoClient()\n repo = client.repo\n repo.authenticate('ashleyyu_bzwtong', 'ashleyyu_bzwtong')\n doc.add_namespace('alg', 'http://datamechanics.io/algorithm/') # The scripts are in # format.\n doc.add_namespace('dat', 'http://datamechanics.io/data/') # The data sets are in # format.\n doc.add_namespace('ont', 'http://datamechanics.io/ontology#') # 'Extension', 'DataResource', 'DataSet', 'Retrieval', 'Query', or 'Computation'.\n doc.add_namespace('log', 'http://datamechanics.io/log/') # The event log.\n \n this_script = doc.agent('alg:ashleyyu_bzwtong_xhug#policeCrimeCorrelation', {prov.model.PROV_TYPE:prov.model.PROV['SoftwareAgent'], 'ont:Computation':'py'})\n resource_properties= doc.entity('dat:ashleyyu_bzwtong_xhug#policeCrimeCorrelation', {'prov:label':'MongoDB', prov.model.PROV_TYPE:'ont:DataResource'})\n get_policeCrimeCorrelation = doc.activity('log:uuid'+str(uuid.uuid4()), startTime, endTime)\n doc.wasAssociatedWith(get_policeCrimeCorrelation, this_script)\n doc.usage(get_policeCrimeCorrelation, resource_properties, startTime, None,\n {prov.model.PROV_TYPE:'ont:Retrieval'})\n \n policeCrimeCorr = doc.entity('dat:ashleyyu_bzwtong_xhug#policeCrimeCorrelation', {prov.model.PROV_LABEL:'Calculated Correlations', prov.model.PROV_TYPE:'ont:DataSet'})\n doc.wasAttributedTo(policeCrimeCorr, this_script)\n doc.wasGeneratedBy(policeCrimeCorr, get_policeCrimeCorrelation, endTime)\n doc.wasDerivedFrom(policeCrimeCorr, resource_properties, get_policeCrimeCorrelation, get_policeCrimeCorrelation, get_policeCrimeCorrelation)\n\n repo.logout()\n \n return doc\n\npoliceCrimeCorrelation.execute(False)\ndoc = policeCrimeCorrelation.provenance()\nprint(doc.get_provn())\nprint(json.dumps(json.loads(doc.serialize()), indent=4))\n","sub_path":"ashleyyu_bzwtong_xhug/policeCrimeCorrelation.py","file_name":"policeCrimeCorrelation.py","file_ext":"py","file_size_in_byte":6820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"111012748","text":"\"\"\"\r\nEX1\r\n\"\"\"\r\ndef media(n1,n2):\r\n m = (n1+n2)/2\r\n return m\r\n\r\n\"\"\"\r\nEX.:2\r\n\"\"\"\r\nlista = []\r\nwith open('series.csv', 'r') as arq1:\r\n\r\n for linha in arq1.readlines():\r\n a = linha.split(',')\r\n lista.append(a)\r\n \r\n \r\nwith open('series_novas.csv', 'r') as arq2:\r\n\r\n for linha in arq2.readlines():\r\n a =linha.split(',')\r\n lista.append(a)\r\n\r\n \r\n\r\n \r\nprint(lista[2][0])\r\n\r\n\"\"\"\r\nEX.: 4\r\n\"\"\"\r\n\"\"\"\r\nnota1 = lista[5]\r\nnota2 = lista[6]\r\ndic = {lista[0]:media(int(nota1),int(nota2))}\r\nprint(dic)\r\n\"\"\"\r\narq3 = open('series_aprovadas.csv', 'w')\r\n\"\"\"\r\nfor k in lista:\r\n if lista[k][0] == 'Narcos':\r\n print(lista[k])\r\n\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n\r\n","sub_path":"P2LIC.py","file_name":"P2LIC.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"181111777","text":"import random\r\n\r\nfrom openpyxl import Workbook\r\nfrom openpyxl.styles import Font, Color, Alignment, PatternFill\r\nbook = Workbook()\r\n\r\nsheet = book.active\r\nsheet.title = \"Data\"\r\n\r\n#styling begins\r\n\r\nsheet.row_dimensions[1].fill = PatternFill(\"solid\", fgColor=\"DAE1F1\")\r\nsheet.row_dimensions[1].font = Font(bold=True)\r\nsheet['A1'] = \"Name\"\r\nsheet['B1'] = \"Age\"\r\nsheet['C1'] = \"Score\"\r\nsheet['E1'] = \"Average Score\"\r\n\r\nfor cell in sheet['B2:C100002']:\r\n cell = Alignment(horizontal=\"right\")\r\n \r\nfor r in range(3,100002,2):\r\n sheet.row_dimensions[r].font = Font(color=\"839B77\")\r\n \r\n#styling ends\r\n\r\nnames = ['Ivan','Valentina','George','Ivelina','Peter','Gergana','Christian','Maria','Alexander','Stefka']\r\n\r\nsumScores = 0\r\n\r\nfor R in range(2,100002):\r\n sheet['A' + str(R)] = names[random.randint(0,9)]\r\n sheet['B' + str(R)] = random.randint(20,80)\r\n sheet['C' + str(R)] = random.randint(0,100)\r\n if R <= 101:\r\n sumScores += sheet['C' + str(R)].value\r\n \r\nsheet['E2'] = sumScores / 100\r\n \r\nbook.save(\"scores.xlsx\")","sub_path":"task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"488713471","text":"from fastai.vision import *\nfrom fastai.distributed import *\nfrom fastai.callbacks import *\n\nfrom wong.core import *\nfrom wong.resnetx import *\nfrom wong.resnetx2 import *\nfrom wong.config import cfg, assert_cfg\n\nimport argparse\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--local_rank\", type=int)\nargs = parser.parse_args()\ntorch.cuda.set_device(args.local_rank)\ntorch.distributed.init_process_group(backend='nccl', init_method='env://')\n\npath = untar_data(URLs.CIFAR)\nprint(path)\n\nbs = 32\nds_tfms = ([*rand_pad(4, 32), flip_lr(p=0.5)], [])\ndata = ImageDataBunch.from_folder(path, valid='test', ds_tfms=ds_tfms, bs=bs, \n device=defaults.device).normalize(cifar_stats)\n\ndata.path = '.'\n\nStem = conv_bn\nUnit = mbconv\nni = 64\nbottle_scale = 1\ntail_all = True\n\n\nnodes = 24\nfor fold in (11,): #2,3,4,5,6,7,8,9,10,11\n num_nodes = [nodes*1,nodes*1+1,nodes*1+1,nodes*1+1]\n folds = [fold] * 4\n\n model = ResNetX2(Stem=conv_bn, Unit=mbconv, folds=folds, ni=ni, num_nodes=num_nodes, bottle_scale=bottle_scale, tail_all=tail_all, ks=3, c_out=data.c, zero_bn=True)\n params = num_params(model)\n filename = 'mbconv_folds_{}_nodes_{}_ni_{}_scale_{}_params_{}'.format('_'.join(map(str, folds)), \n '_'.join(map(str, num_nodes)), ni, bottle_scale, params)\n print(filename)\n learn = Learner(data, model, metrics=accuracy, callback_fns=[partial(callbacks.CSVLogger, filename=filename, append=True)]).to_fp16().to_distributed(args.local_rank)\n learn.model_dir = '.' \n# learn.load(filename)\n# learn.validate()\n learn.fit_one_cycle(40, 1e-2, callbacks=[SaveModelCallback(learn, every='improvement', monitor='accuracy', name='model')]) # , tot_epochs=40, start_epoch=0\n learn.save(filename)\n\n\n\n","sub_path":"nbs/cifar10.py","file_name":"cifar10.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"51262109","text":"#-----------------------------\n# Twitter- Gendered Reaction to International Conflict\n#-----------------------------\n\n#Set up\n #pip install tweepy ==3.7\n #conda install -c conda-forge geopy\n\n#Authentication with Tweepy\nimport tweepy\nimport key\nimport pandas as pd\nauth = tweepy.OAuthHandler(key.consumer_key,\n key.consumer_secret)\nauth.set_access_token(key.access_token,\n key.access_token_secret)\napi = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)\n\n#Querying the Tweets\nfrom tweetutilities import print_tweets\nquery = 'Iran OR iran'\nmax_tweets = 1000\niran_tweets = [status for status in tweepy.Cursor(api.search, q=query).items(max_tweets)]\niran_tweets =[]\nlast_id = -1\nwhile len(iran_tweets) < max_tweets:\n count = max_tweets - len(iran_tweets)\n try:\n newIran_tweets = api.search(q = query, count = count, max_id = str(last_id - 1))\n if not newIran_tweets:\n break\n iran_tweets.extend(newIran_tweets)\n last_id = newIran_tweets[-1].id\n except tweepy.TweepError as e:\n break \ndf = pd.DataFrame(data = iran_tweets)","sub_path":"tweetpull.py","file_name":"tweetpull.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"182130575","text":"import random\nimport uuid\n\nfrom datetime import datetime\nfrom jsonschema_serialize_fork import NO_DEFAULT\nfrom pyramid.path import DottedNameResolver\nfrom pyramid.threadlocal import get_current_request\nfrom snovault.schema_utils import server_default\nfrom string import digits, ascii_uppercase\n\n\nACCESSION_FACTORY = __name__ + ':accession_factory'\nACCESSION_PREFIX = '4DN'\nACCESSION_TEST_PREFIX = 'TST'\n\n\ndef includeme(config):\n accession_factory = config.registry.settings.get('accession_factory')\n if accession_factory:\n factory = DottedNameResolver().resolve(accession_factory)\n else:\n factory = enc_accession\n config.registry[ACCESSION_FACTORY] = factory\n\n\n# XXX: This stuff is all added based on the serverDefault identifier in the schemas\n# removing it altogether will totally break our code\n\n\n@server_default\ndef userid(instance, subschema): # args required by jsonschema-serialize-fork\n return _userid()\n\n\ndef _userid():\n request = get_current_request()\n for principal in request.effective_principals:\n if principal.startswith('userid.'):\n return principal[7:]\n return NO_DEFAULT\n\n\n@server_default\ndef now(instance, subschema): # args required by jsonschema-serialize-fork\n return utc_now_str()\n\n\ndef utc_now_str():\n # from jsonschema_serialize_fork date-time format requires a timezone\n return datetime.utcnow().isoformat() + '+00:00'\n\n\n@server_default\ndef uuid4(instance, subschema):\n return str(uuid.uuid4())\n\n\n@server_default\ndef accession(instance, subschema):\n if 'external_accession' in instance:\n return NO_DEFAULT\n request = get_current_request()\n factory = request.registry[ACCESSION_FACTORY]\n # With 17 576 000 options\n ATTEMPTS = 10\n for attempt in range(ATTEMPTS):\n new_accession = factory(subschema['accessionType'])\n if new_accession in request.root:\n continue\n return new_accession\n raise AssertionError(\"Free accession not found in %d attempts\" % ATTEMPTS)\n\n\ndef get_userid():\n \"\"\" Wrapper for the server_default 'userid' above so it is not called through SERVER_DEFAULTS in our code \"\"\"\n return _userid()\n\n\ndef get_now():\n \"\"\" Wrapper for the server_default 'now' above so it is not called through SERVER_DEFAULTS in our code \"\"\"\n return utc_now_str()\n\n\ndef add_last_modified(properties, userid=None):\n \"\"\"\n Uses the above two functions to add the last_modified information to the item\n May have no effect\n Allow someone to override the request userid (none in this case) by passing in a different uuid\n \"\"\"\n try:\n last_modified = {\n 'modified_by': get_userid(),\n 'date_modified': get_now(),\n }\n except AttributeError: # no request in scope ie: we are outside the core application.\n if userid:\n last_modified = {\n 'modified_by': userid,\n 'date_modified': get_now(),\n }\n properties['last_modified'] = last_modified\n else:\n # get_userid returns NO_DEFAULT if no userid\n if last_modified['modified_by'] != NO_DEFAULT:\n properties['last_modified'] = last_modified\n\n\n#FDN_ACCESSION_FORMAT = (digits, digits, digits, ascii_uppercase, ascii_uppercase, ascii_uppercase)\nFDN_ACCESSION_FORMAT = ['ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789']*7\n\ndef enc_accession(accession_type):\n random_part = ''.join(random.choice(s) for s in FDN_ACCESSION_FORMAT)\n return ACCESSION_PREFIX + accession_type + random_part\n\n\nTEST_ACCESSION_FORMAT = (digits, ) * 7\n\n\ndef test_accession(accession_type):\n \"\"\" Test accessions are generated on test.encodedcc.org\n \"\"\"\n random_part = ''.join(random.choice(s) for s in TEST_ACCESSION_FORMAT)\n return 'TST' + accession_type + random_part\n","sub_path":"src/encoded/server_defaults.py","file_name":"server_defaults.py","file_ext":"py","file_size_in_byte":3802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"117100828","text":"#!/bin/python3\r\nimport random\r\nimport urllib\r\nimport re\r\nfrom bs4 import BeautifulSoup\r\n\r\nnumber = random.randint(100000,999999)\r\nm = \"https://vk.com/id{}\".format(number)\r\nsoup = BeautifulSoup(urllib.request.urlopen(m), 'lxml')\r\nfor img in soup.find_all('img'):\r\n\tif img.get('alt'):\r\n\t\tprint(img.get('alt'))\r\n\t\tif \".jpg\" in (img.get('src')):\r\n\t\t\tprint(img.get('src'))\r\n\t\telse:\r\n\t\t\tprint('Too stubborn to show a photo')\r\n\t\tbreak\r\n\telse:\r\n\t\tprint(\"Doesn`t exist.\")\r\n\t\tbreak\r\nprint(number)\r\nurllib.request.urlretrieve(url=m, filename='Account.html')\r\ninfile = open('Account.html')\r\nlines = infile.readlines()\r\nfor i in range(len(lines)):\r\n\tline = lines[i]\r\n\tif 'div class=\"pp_last_activity\"' in line:\r\n\t\ttime = lines[i]\r\n\t\tif 'Online' in time:\r\n\t\t\tprint('Online')\r\n\t\telse:\r\n\t\t\tprint('Offline')\r\n\tif 'div class=\"pp_status\"' in line:\r\n\t\tstatus = lines[i].strip('
').strip('
')\r\n\t\tprint(status)\r\n\telse:\r\n\t\tprint('The victim has no status')\r\n\t\tbreak","sub_path":"asd.py","file_name":"asd.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"65595818","text":"import os\n\ndebug = True\n\n# path\nPWD = os.path.dirname(os.path.realpath(__file__))\npages_path = os.path.join(PWD, \"pages\")\n\nstatic_path = os.path.join(PWD, \"static\")\nsessions_path = os.path.join(PWD, 'sessions')\ntmp_path = os.path.join(PWD, \"tmp\")\ntemplates_path = os.path.join(PWD, \"templates\")\n\n\n# cache, default 1 minute\ncache_update_interval = 60\n\n# pagination\npage_limit = 50\nsearch_page_limit = 100\n\n\n# UI functions \nshow_full_path = 0\nauto_toc = 1\nhighlight = 1\n\n# a.k.a. 'navigation bar' on top\nshow_quick_links = 1\n\nbutton_mode_path = 1\nreader_mode = 1\nshow_source_button = 1\n\n\n# ACL\nreadonly = 1\n\n\n# debug log\n#error_log_path = os.path.join(PWD, \"tmp\", \"error_log.txt\")\nerror_log_path = None\n\n\n# bio/info\nmaintainer_email = \"shuge.lee@gmail.com\"\nrepository_url = \"git://github.com/shuge/zbox_wiki.git\"\n\nif maintainer_email:\n splits = maintainer_email.split(\"@\")\n maintainer_email_prefix = splits[0]\n maintainer_email_suffix = splits[1]\n","sub_path":"zbox_wiki/default_conf.py","file_name":"default_conf.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"140648410","text":"'''\nGiven a binary tree. Check whether it is a BST or not.\n\n\nhttps://www.geeksforgeeks.org/a-program-to-check-if-a-binary-tree-is-bst-or-not/\n\n'''\n\nclass Node:\n def __init__(self, data): \n self.data = data \n self.left = None\n self.right = None\n \nINT_MAX = 4294967296\nINT_MIN = -4294967296\n\n# O(n) time complexity and O(n) space complexity\ndef isBST(node):\n return isBSTUtil(node, INT_MIN, INT_MAX)\n\ndef isBSTUtil(node, mini, maxi):\n \n if(node is None):\n return True\n \n if(node.data < mini or node.data > maxi):\n return False\n \n return (isBSTUtil(node.left, mini, node.data - 1) and isBSTUtil(node.right, node.data + 1, maxi))\n\nroot = Node(4) \nroot.left = Node(2) \nroot.right = Node(5) \nroot.left.left = Node(1) \nroot.left.right = Node(3) \n\nprint(isBST(root))","sub_path":"geeksforgeeks/binary_search_tree/14_check_for_BST.py","file_name":"14_check_for_BST.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"93766458","text":"# Copyright (c) [2022] Huawei Technologies Co.,Ltd.ALL rights reserved.\n# This program is licensed under Mulan PSL v2.\n# You can use it according to the terms and conditions of the Mulan PSL v2.\n# http://license.coscl.org.cn/MulanPSL2\n# THIS PROGRAM IS PROVIDED ON AN \"AS IS\" BASIS, WITHOUT WARRANTIES OF ANY KIND,\n# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,\n# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.\n# See the Mulan PSL v2 for more details.\n####################################\n# @Author :\n# @email :\n# @Date :\n# @License : Mulan PSL v2\n#####################################\n\nfrom flask import jsonify, render_template, make_response, current_app\nfrom flask_restful import Resource\nfrom flask_pydantic import validate\n\nfrom server.utils.auth_util import auth\nfrom server.utils.response_util import response_collect, RET\nfrom server.model.milestone import Milestone, TestReport\nfrom server.utils.db import Select\nfrom server.schema.milestone import (\n MilestoneBaseSchema,\n MilestoneCreateSchema,\n MilestoneQuerySchema,\n MilestoneUpdateSchema,\n GiteeMilestoneQuerySchema,\n SyncMilestoneSchema,\n MilestoneStateEventSchema,\n IssueRateFieldSchema,\n GenerateTestReport,\n QueryTestReportFile,\n)\nfrom server.utils.permission_utils import GetAllByPermission\nfrom server import casbin_enforcer\nfrom server.apps.milestone.handler import (\n IssueStatisticsHandlerV8,\n MilestoneOpenApiHandler,\n MilestoneHandler,\n CreateMilestone,\n DeleteMilestone,\n GenerateVersionTestReport,\n)\n\n\n\nclass OrgMilestoneEventV1(Resource):\n @auth.login_required()\n @response_collect\n @validate()\n def get(self, org_id, query: MilestoneQuerySchema):\n filter_params = [\n Milestone.org_id == org_id\n ]\n return MilestoneHandler.get_milestone(query, filter_params)\n\n\nclass GroupMilestoneEventV1(Resource):\n @auth.login_required()\n @response_collect\n @validate()\n def get(self, group_id, query: MilestoneQuerySchema):\n filter_params = [\n Milestone.group_id == group_id\n ]\n return MilestoneHandler.get_milestone(query, filter_params)\n\n\nclass MilestoneEventV2(Resource):\n @auth.login_required()\n @response_collect\n @validate()\n def post(self, body: MilestoneCreateSchema):\n return CreateMilestone.run(body.__dict__)\n\n\n @auth.login_required()\n @response_collect\n @validate()\n def get(self, query: MilestoneQuerySchema):\n filter_params = GetAllByPermission(Milestone).get_filter()\n return MilestoneHandler.get_milestone(query, filter_params)\n\n\nclass MilestoneItemEventV2(Resource):\n @auth.login_required()\n @response_collect\n @validate()\n @casbin_enforcer.enforcer\n def put(self, milestone_id, body: MilestoneUpdateSchema):\n milestone = Milestone.query.filter_by(id=milestone_id).first()\n if not milestone:\n return jsonify(\n error_code=RET.NO_DATA_ERR,\n error_msg=\"milestone {} not exist\".format(milestone_id),\n )\n\n if milestone.is_sync is True:\n _data = body.__dict__\n if _data.get(\"start_time\"):\n _data[\"start_time\"] = _data.get(\n \"start_time\").strftime(\"%Y-%m-%d\")\n if _data.get(\"end_time\"):\n _data[\"end_time\"] = _data.get(\"end_time\").strftime(\"%Y-%m-%d\")\n return MilestoneOpenApiHandler(_data).edit(milestone.gitee_milestone_id)\n else:\n _body = body.__dict__\n for key, value in _body.items():\n if value is not None:\n setattr(milestone, key, value)\n milestone.add_update(Milestone, \"/milestone\")\n return jsonify(\n error_code=RET.OK,\n error_msg=\"OK.\"\n )\n\n @auth.login_required()\n @response_collect\n @casbin_enforcer.enforcer\n def delete(self, milestone_id):\n return DeleteMilestone.single(milestone_id)\n\n @auth.login_required()\n @response_collect\n @validate()\n @casbin_enforcer.enforcer\n def get(self, milestone_id):\n return Select(Milestone, {\"id\": milestone_id}).single()\n\n\nclass MilestonePreciseEvent(Resource):\n @auth.login_required()\n @validate()\n def get(self, query: MilestoneBaseSchema):\n return GetAllByPermission(Milestone).precise(query.__dict__)\n\n\nclass GenerateTestReportEvent(Resource):\n @auth.login_required()\n @response_collect\n @validate()\n def get(self, milestone_id, query: GenerateTestReport):\n milestone = Milestone.query.filter_by(id=milestone_id).first()\n if not milestone:\n return jsonify(\n error_code=RET.NO_DATA_ERR,\n error_msg=\"milestone {} not exist\".format(milestone_id),\n )\n return GenerateVersionTestReport().generate_update_test_report(milestone_id, query.uri)\n\n\nclass TestReportFileEvent(Resource):\n @auth.login_required()\n @response_collect\n @validate()\n def get(self, milestone_id, query: QueryTestReportFile):\n _test_report = TestReport.query.filter_by(milestone_id=milestone_id).first()\n if not _test_report:\n return jsonify(\n error_code=RET.NO_DATA_ERR,\n error_msg=\"no test report.\",\n )\n\n tmp_folder = current_app.template_folder\n current_app.template_folder = current_app.config.get(\"TEST_REPORT_PATH\")\n if query.file_type == \"md\":\n resp = make_response(render_template(_test_report.md_file))\n else:\n resp = make_response(render_template(_test_report.html_file))\n current_app.template_folder = tmp_folder\n return resp\n\n\nclass TestReportEvent(Resource):\n @auth.login_required()\n @response_collect\n @validate()\n def get(self, milestone_id):\n _test_report = TestReport.query.filter_by(milestone_id=milestone_id).first()\n if not _test_report:\n return jsonify(\n error_code=RET.NO_DATA_ERR,\n error_msg=\"no test report.\",\n )\n\n return jsonify(\n error_code=RET.OK,\n error_msg=\"OK\",\n data=_test_report.to_json()\n )\n\n\nclass GiteeIssuesStatisticsByMilestone(Resource):\n @auth.login_required\n @validate()\n def get(self, milestone_id):\n return IssueStatisticsHandlerV8.get_rate_by_milestone(milestone_id)\n\n\nclass UpdateGiteeIssuesStatistics(Resource):\n @auth.login_required\n @response_collect\n def get(self):\n return IssueStatisticsHandlerV8.update_issue_rate()\n\n\nclass UpdateMilestoneIssueRateByField(Resource):\n @auth.login_required\n @response_collect\n @validate()\n def put(self, milestone_id, body: IssueRateFieldSchema):\n return IssueStatisticsHandlerV8.update_milestone_issue_rate_by_field(milestone_id, body.field)\n\n\nclass GiteeMilestoneEventV2(Resource):\n @auth.login_required\n @response_collect\n @validate()\n def get(self, query: GiteeMilestoneQuerySchema):\n return MilestoneOpenApiHandler().get_milestones(params=query.__dict__)\n\n\nclass SyncMilestoneItemEventV2(Resource):\n @auth.login_required()\n @response_collect\n @validate()\n @casbin_enforcer.enforcer\n def put(self, milestone_id, body: SyncMilestoneSchema):\n milestone = Milestone.query.filter_by(id=milestone_id).first()\n if not milestone:\n return jsonify(\n error_code=RET.NO_DATA_ERR,\n error_msg=\"milestone {} not exist\".format(milestone_id),\n )\n\n milestone.gitee_milestone_id = body.gitee_milestone_id\n milestone.is_sync = True\n milestone.add_update(Milestone, \"/milestone\")\n\n return jsonify(\n error_code=RET.OK,\n error_msg=\"OK\",\n )\n\n\nclass MilestoneItemStateEventV2(Resource):\n @auth.login_required\n @response_collect\n @validate()\n @casbin_enforcer.enforcer\n def put(self, milestone_id, body: MilestoneStateEventSchema):\n milestone = Milestone.query.filter_by(id=milestone_id).first()\n if not milestone:\n return jsonify(\n error_code=RET.NO_DATA_ERR,\n error_msg=\"milestone {} not exist\".format(milestone_id),\n )\n _body = body.__dict__\n if _body.get(\"state_event\"):\n state_event = _body.pop(\"state_event\")\n if state_event == \"activate\":\n _body.update({\"state\": \"active\"})\n else:\n _body.update({\"state\": \"closed\"})\n\n if milestone.state == _body.get(\"state\"):\n return jsonify(\n error_code=RET.DATA_EXIST_ERR,\n error_msg=\"State event cannot transition when {}\".format(\n milestone.state),\n )\n\n if milestone.is_sync is True:\n return MilestoneOpenApiHandler(body.__dict__).edit_state_event(milestone.gitee_milestone_id)\n\n milestone.state = _body.get(\"state\")\n milestone.add_update()\n return jsonify(error_code=RET.OK, error_msg=\"OK.\")\n","sub_path":"radiaTest-server/server/apps/milestone/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":9117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"353662537","text":"# baseline.py\n# Leonardo Losno Velozo\n\nimport os\nfrom collections import Counter\nfrom performance import getResultaten, getScorers\nfrom ranking.mainFuncties import relClubs, getTUSelecties, getClubDict\n\n\ndef uBLPerf(voorspellingList):\n\tresultaten = getResultaten()\n\tt = 0\n\tg = 0\n\tf = 0\n\tvergelijkU = []\n\tfor r in resultaten:\n\t\tt +=1\n\t\tvoorspelling = [v for v in voorspellingList if r[0][0] == v[0]]\n\t\tif voorspelling[0][1] == r[1]:\n\t\t\tg +=1\n\t\t\tvergelijkU.append([r[0][0], 'Goed', voorspelling[0][1], r[1]])\n\t\t\t\n\t\telse: \n\t\t\tf +=1\n\t\t\tvergelijkU.append([r[0][0], 'Fout', voorspelling[0][1], r[1]])\n\taccuracyU = [t,g,f,float(g) / float(t) *100]\n\treturn vergelijkU, accuracyU\n\t\ndef uitslagBL():\n\t\"\"\" Voorspelt de meest voorkomende uitslag van het seizoen \"\"\"\n\tpath = os.getcwd()\n\twSchema = open(path+'/data/wedstrijdschema', 'r')\n\tuitslagList = []\n\tfor line in wSchema:\n\t\tuitslag = \"-\".join([u.strip() for u in line.split('|')][3].split(' : '))\n\t\tuitslagList.append(uitslag)\n\t\t\n\tcntUitslagen = Counter(uitslagList)\n\tmstCmn = cntUitslagen.most_common(1)\n\tresultaten = getResultaten()\n\tvList = []\n\tfor r in resultaten:\n\t\tvList.append((r[0][0], mstCmn[0][0]))\n\treturn vList\n\t\ndef sBLPerf(voorspellingList):\n\tcheckList = getScorers()\n\tg = 0\n\tf = 0\n\tt = 0\n\tvergelijkS = []\n\tfor wedstrijd in checkList:\n\t\tvoorspelling = [v for v in voorspellingList if wedstrijd[0][0] == v[0]][0]\n\t\tfor i, sD in enumerate(wedstrijd[1]):\n\t\t\tt+=1\n\t\t\tif sD == voorspelling[1][i]:\n\t\t\t\tg +=1\n\t\t\t\tvergelijkS.append([wedstrijd[0][0], 'Goed', voorspelling[1][i][0], voorspelling[1][i][1], sD[0],sD[1]])\n\t\t\telse:\n\t\t\t\tf +=1\n\t\t\t\tvergelijkS.append([wedstrijd[0][0], 'Fout', voorspelling[1][i][0], voorspelling[1][i][1], sD[0],sD[1]])\n\taccuracyS = [t,g,f,float(g) / float(t) *100]\n\treturn vergelijkS, accuracyS\n\n\t\ndef scorersBL():\n\t\"\"\" Voorspelt de club topscorer voor alle doelpunten die de club maakt \"\"\"\n\tpath = os.getcwd()\n\tscorersFile = open(path+'/data/topscorers.txt', 'r')\n\tfirstLine = True\n\tclubTopS = []\n\tclubList = []\n\tfor topscorers in scorersFile:\n\t\tif firstLine == False:\n\t\t\ttopScorer = [tS.strip() for tS in topscorers.split('\\t')][:2]\n\t\t\tif topScorer[1] == 'PSV Eindhoven':\n\t\t\t\ttopScorer[1] = 'PSV'\n\t\t\tif topScorer[1] == 'AZ Alkmaar':\n\t\t\t\ttopScorer[1] = 'AZ'\n\t\t\tif topScorer[1] == 'SC Heracles Almelo':\n\t\t\t\ttopScorer[1] = 'Heracles Almelo'\t\n\t\t\t\t\n\t\t\tif topScorer[1] not in clubList:\n\t\t\t\tclubTopS.append(topScorer)\n\t\t\t\tclubList.append(topScorer[1])\n\t\tfirstLine = False\n\n\tpath = os.getcwd()\n\twSchema = open(path+'/data/wedstrijdschema', 'r')\n\twedSList = []\n\tfor line in wSchema:\n\t\twedstrijd = [u.strip() for u in line.split('|')][2].split(' - ')\n\t\tscorers = [u.strip() for u in line.split('|')][4:][:-1]\n\t\ttussenstand = [0,0]\n\t\tscorerList = []\n\t\tfor dS in scorers:\n\t\t\tdoelpunt, scorer = dS.split(' - ')\n\t\t\tif doelpunt.split('-')[1] == str(tussenstand[1]):\n\t\t\t\tdMaker = [s[0] for s in clubTopS if wedstrijd[0] == s[1]]\n\t\t\t\ttussenstand[0] = str(int(tussenstand[0])+1)\n\t\t\t\tdMaker = \" \".join(dMaker[0].split(' ')[1:])\n\t\t\t\tscorerList.append((dMaker, doelpunt))\n\t\t\telif doelpunt.split('-')[0] == str(tussenstand[0]):\n\t\t\t\tdMaker = [s[0] for s in clubTopS if wedstrijd[1] == s[1]]\n\t\t\t\ttussenstand[1] = str(int(tussenstand[1])+1)\n\t\t\t\tdMaker = \" \".join(dMaker[0].split(' ')[1:])\n\t\t\t\tscorerList.append((dMaker, doelpunt))\n\t\t\telse: \n\t\t\t\t# Uitzondering (SC Heerenveen - FC Utrecht), door verkeerde doelpunten volgorde in wSchema\n\t\t\t\tdMaker = [s[0] for s in clubTopS if wedstrijd[0] == s[1]]\n\t\t\t\tdMaker = \" \".join(dMaker[0].split(' ')[1:])\n\t\t\t\tscorerList.append((dMaker, doelpunt))\n\t\t\t\t\n\t\twedSList.append([\"-\".join(wedstrijd),scorerList])\n\treturn wedSList\n\ndef main():\n\tuitslagVsp = uitslagBL()\n\tuVergLijst, uAccuracy = uBLPerf(uitslagVsp)\n\tprint('{:<30}{:<6}{:<15}{:<10}'.format('Wedstrijd', 'G/F', 'Voorspelling', 'Uitslag'))\n\tfor uitslag in uVergLijst:\n\t\tif uitslag[1] == 'Goed':\n\t\t\tprint('{:<30}{:<10}{:<13}{:<10}'.format(uitslag[0], uitslag[1], uitslag[2], uitslag[3]))\n\tprint('Baseline uitslag. Totaal: {:<5} Goed: {:<5} Fout: {:<5} Accuracy {:<5.2f}'.format(uAccuracy[0],uAccuracy[1],uAccuracy[2],uAccuracy[3]))\n\tprint('')\n\t\n\tscorersVsp = scorersBL()\n\tsVergLijst, sAccuracy = sBLPerf(scorersVsp)\n\tprint('{:<30}{:<10}{:<20}{}'.format('Wedstrijd', 'G/F', 'Voorspelling', 'Waarneming'))\n\tfor scorer in sVergLijst:\n\t\tif scorer[1] == 'Goed':\n\t\t\tprint('{:<30}{:<10}{:<5}{:<15}{:<5}{}'.format(scorer[0],scorer[1],scorer[3],scorer[2],scorer[5],scorer[4]))\n\tprint('Baseline scorer. Totaal: {:<5} Goed: {:<5} Fout: {:<5} Accuracy {:<5.2f}'.format(sAccuracy[0],sAccuracy[1],sAccuracy[2],sAccuracy[3]))\n\t\t\nmain()\n","sub_path":"baseline.py","file_name":"baseline.py","file_ext":"py","file_size_in_byte":4567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"258614840","text":"# The goal is to extract individual news and store these feeds as JSON files by date. The JSON\n# file should contain fields such as current_date, story_date, story_time, body, title, source,\n# story_id\n\nimport newspaper\nimport datetime\nimport tldextract\nimport time\nimport logging\nimport concurrent.futures\n\nfrom .db import get_collection, check_duplicate\n\n\ndef manage_newsfeed(filename):\n\tlinks = [line.rstrip('\\n') for line in open(filename)]\n\twith concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:\n\t\t\n\t\tfutures=[executor.submit(extract_news, link) for link in links]\n\t\t# print(futures)\n\t\tfor future in as_completed(futures):\n\t\t\tprint(future.result())\n\t\n # for future in as_completed(futures):\n # print(future.result())\n \t\t# r = executor.map(extract_news, links)\n \t\t# print(r.result())\n \t\t# input()\n\n\t\n\ndef extract_news(link):\n\tprint(link)\n\tcoll = get_collection(collection_name=\"feeds\")\n\tnews = newspaper.build(link)\n\tsource_count = 0\n\tfor category in news.category_urls():\t\n\t\tcat_paper = newspaper.build(category)\t\n\t\tfor article in cat_paper.articles:\n\t\t\ttry:\n\t\t\t\tfeed = newspaper.Article(article.url)\n\t\t\t\tfeed.download()\n\n\t\t\texcept Exception as e:\n\t\t\t\tprint(\"Timeout occured while downloading \"+article.url+\" retrying\")\n\t\t\t\tfeed.download()\n\t\t\t\ttime.sleep(2)\n\t\t\t\tsource_count+=1\n\t\t\t\tcontinue\n\t\t\t\t\n\t\t\tparsed_feed, source = parse_data(feed, link)\n\t\t\tfeed_json, insert_flag = build_json(parsed_feed, i, source, category)\n\t\t\tif insert_flag == False:\n\t\t\t\tcoll.insert(feed_json)\n\t\t\tsource_count+=1\n\tprint(source_count)\n\treturn source_count\t\t\n\ndef parse_data(feed, source_link):\n\tfeed.parse()\n\tfeed.nlp()\n\tfeed.text.replace(\"\\n\",\"\")\t\n\ttemp = tldextract.extract(source_link)\n\tsource = temp.domain\n\treturn feed, source\n\ndef build_json(feed, i, source, category):\n\n\tfeed_json = {\n\t\"story_id\" : i,\n\t\"current_date_time\": datetime.datetime.now(),\n\t\"authors\": feed.authors,\n\t\"story_date_time\": feed.publish_date,\n\t\"title\": feed.title,\n\t\"body\": feed.text,\n\t\"source\": source,\n\t\"category\" : category,\n\t\"video_link\": feed.movies,\n\t\"summary\": feed.summary,\n\t\"topics\": feed.keywords,\n\t}\n\tinsert_flag = check_duplicate(feed.title, feed.publish_date)\t\n\treturn feed_json, insert_flag\t\t\n\n\nif __name__ == '__main__':\n\t\n\tmanage_newsfeed(\"./links.txt\")\n\t","sub_path":"manage_newsfeed/manage_newsfeed.py","file_name":"manage_newsfeed.py","file_ext":"py","file_size_in_byte":2269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"228886645","text":"#!/usr/bin/env python3\nimport time\ntry:\n num=int(input(\"number:>\"))\n result=100/num\nexcept (ValueError,ZeroDivisionError):\n print(\"\\033[31mInvalid input\\033[0m\")\n time.sleep(3)\nexcept (KeyboardInterrupt, EOFError):\n print(\"\\nBye-bye\")\nelse:\n print(result) # bu fa sheng yi chang zhi xing de yu ju\nfinally:\n print(\"Done\") # bu guan fa bu fa sheng yi chang , dou zhi xing","sub_path":"n2_python/day01/no5_killerror.py","file_name":"no5_killerror.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"650202788","text":"from flask_restful import Resource, reqparse\nfrom flask_jwt_extended import (\n jwt_required,\n get_jwt_claims,\n get_jwt_identity,\n jwt_optional,\n fresh_jwt_required\n)\nfrom models.book import BookModel\n\nclass Book(Resource):\n\n parser = reqparse.RequestParser()\n parser.add_argument('author',\n type=str,\n required=False,\n help=\"Book must have an Author\"\n )\n parser.add_argument('amazon_url',\n type=str,\n required=False,\n help=\"Book must have an amazon URL\"\n )\n parser.add_argument('book_genre',\n type=str,\n required=False,\n help=\"Book must have a genre\"\n )\n @jwt_required\n def get(self, title):\n book = BookModel.find_by_title(title)\n if book:\n return book.json()\n return {\"message\" : \"Book with title'{}'was not found\".format(title)}, 404\n \n @fresh_jwt_required\n def post(self, title):\n if BookModel.find_by_title(title=title):\n return {\"message\": \"Book with title'{}' already exsist\".format(title)}\n\n data = Book.parser.parse_args()\n \n book = BookModel(title,**data)\n\n try:\n book.save_to_db()\n except:\n return {\"message\": \"An Error ocurred while inseting the book\"}, 500\n\n return book.json(), 201\n \n @jwt_required\n def delete(self,title):\n book = BookModel.find_by_title(title)\n if book:\n book.delete_from_db()\n return {\"message\": \"Book has been deleted\"}\n\n return {\"message\": \"Book Not Found in database\"}, 404\n\n\n @jwt_required\n def put(self,title):\n data = Book.parser.parse_args()\n book = BookModel.find_by_title(title)\n if book:\n book.author = data['author'] if data['author'] else book.author \n book.amazon_url = data['amazon_url'] if data['amazon_url'] else book.amazon_url\n book.book_genre = data['book_genre'] if data['book_genre'] else book.book_genre\n else:\n book = BookModel(title, **data)\n \n book.save_to_db()\n\n return book.json()","sub_path":"code/resources/book.py","file_name":"book.py","file_ext":"py","file_size_in_byte":2324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"246764971","text":"import ctypes\r\nimport os\r\nimport shutil\r\nimport random\r\nimport time\r\nimport queue\r\n\r\n#to auto launch, copy shortcut to startup folder\r\n#C:\\Users\\Josh\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\r\n\r\n'''param_data = open(\"param_data.txt\", \"r\")\r\nmainFolder = \"E:\\\\Users\\\\Josh\\\\Google Drive\\\\random\"\r\n\r\nsec = int((param_data.readline().split()[1]))\r\nmin = int((param_data.readline().split()[1]))\r\nhour = int((param_data.readline().split()[1]))\r\nblacklistSize = int((param_data.readline().split()[1]))\r\nparam_data.close()'''\r\n\r\nmainFolder = \"E:\\\\Users\\\\Josh\\\\Google Drive\\\\random\"\r\n\r\nsec = 0\r\nmin = 0\r\nhour = 3\r\nblacklistSize = 20\r\n\r\ninterval = sec + 60*min + 3600*hour #in seconds\r\nblacklist = queue.Queue(blacklistSize)\r\n\r\n#need to write first time write\r\ndef save_blacklist(name):\r\n bFile = open(\"blacklist.txt\", \"w\")\r\n list = blacklist.queue\r\n for i in range(0, blacklist.qsize()):\r\n bFile.write(list[i] + '\\n')\r\n bFile.close()\r\n \r\ndef load_blacklist():\r\n bFile = open(\"blacklist.txt\", \"r\")\r\n for line in bFile:\r\n blacklist.put(line.rstrip(\"\\n\\r\"))\r\n\r\ndef add_blacklist(name):\r\n if blacklist.full():\r\n blacklist.get()\r\n blacklist.put(name)\r\n\r\ndef check_blacklist(name):\r\n testList = blacklist.queue\r\n #print(testList)\r\n if name in testList:\r\n return True\r\n return False\r\n \r\ndef change_Background(imgCount):\r\n\r\n imageName = os.listdir(mainFolder)[random.randint(0,imgCount)]\r\n imageRoot, imageExt = os.path.splitext(mainFolder + \"\\\\\" + imageName)\r\n if (imageExt == \".png\" or imageExt == \".jpg\"):\r\n if (check_blacklist(imageName) == False):\r\n print(imageName)\r\n add_blacklist(imageName)\r\n save_blacklist(imageName)\r\n SPI_SETDESKWALLPAPER = 20 \r\n ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, imageRoot + imageExt, 0)\r\n else:\r\n change_Background(imgCount)\r\n \r\n\r\ndef get_Image_Count():\r\n imgCount = 0\r\n \r\n for file in os.listdir(mainFolder):\r\n imgCount += 1\r\n \r\n print(\"Detected \" + str(imgCount) + \" images.\")\r\n return imgCount\r\n\r\n \r\n \r\n#########################\r\nstarttime=time.time()\r\ntotalCount = get_Image_Count()\r\n\r\nbCheck = os.path.exists(\"blacklist.txt\")\r\nif bCheck:\r\n load_blacklist()\r\nelse:\r\n newfile = open(\"blacklist.txt\", \"w\")\r\n newfile.close()\r\n\r\nwhile True:\r\n print(\" \")\r\n print(\"switching to...\")\r\n change_Background(totalCount)\r\n time.sleep(interval)\r\n\r\n\r\n\r\n \r\n","sub_path":"Dynamic Background.pyw","file_name":"Dynamic Background.pyw","file_ext":"pyw","file_size_in_byte":2545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"104251122","text":"import sys,argparse\nimport serial\n\n# resources:\n# argparse - https://docs.python.org/2/library/argparse.html#module-argparse\n# pyserial - https://github.com/pyserial/pyserial\n\n\ndef main(argv):\n parser = argparse.ArgumentParser(description='Dali Serial script-interpreter')\n parser.add_argument('--com', metavar='COMx', help='select com port for serial interface')\n parser.add_argument('--input', metavar='Filename', help='select input script')\n \n args = parser.parse_args();\n \n \n if args.com is None:\n print(\"com port not defined!\")\n sys.exit()\n else:\n print(args.com)\n\n\n if args.input is None:\n print(\"input file not defined!\")\n sys.exit()\n else:\n print(args.input)\n\n\n # connect to serial port\n # 38400Baud, 8Datenbits, kein Paritätsbit, 1 Stopbit (38400,8,n,1) \n ser = serial.Serial()\n ser.baudrate = 38400\n ser.port = args.com\n\n try:\n ser.open()\n except serial.SerialException as e:\n sys.stderr.write('Could not open serial port {}: {}\\n'.format(ser.name, e))\n sys.exit(1)\n else:\n print(\"Port \" + args.com +\" Open!\")\n\n \n \n \n \n \nif __name__ == \"__main__\":\n main(sys.argv[1:])\n \n\n","sub_path":"pyDaliSerial.py","file_name":"pyDaliSerial.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"285059495","text":"\n'''\nCalcular la utilidad que un trabajador recibe en el\nreparto anual de utilidades si este se le asigna como\nun porcentaje de su salario mensual que depende de su\nantigüedad en la empresa de acuerdo con la siguiente\nTabla:\n\n------------------------------------------------------------\nTiempo Utilidad\n------------------------------------------------------------\nMenos de 1 año 5% del salario\n1 año o más y menos de 2 años 7% del salario\n2 años o más y menos de 5 años 10% del salario\n5 años o más y menos de 10 años 15% del salario\n10 años o más 20% del salario\n-----------------------------------------------------------\n\nALGORITMO\n\nInicio\n sm,antig: Entero\n LEER sm, antig\n Si antig < 1 entonces\n util = sm * 0.05\n Si No\n Si (antg >= 1) and (antig < 2) entonces\n util = sm * 0.07\n Si no\n Si (antig >= 2) and (antig < 5) entonces\n util = sm * 0.10\n Si no\n Si (antig >= 5) and (antig < 10) entonces\n util = sm * 0.15\n Si no\n util = sm * 0.20\n Fin Si\n Fin Si\n Fin Si\n Fin Si\n imprimir “La utilidad es: ”,util\nFin\n\n'''\n\nsm = int(input(\"Digite Salario Mensual: \"))\n\nantig = int(input(\"Digitar años de antiguedad en la empresa: \"))\n\nif antig < 1:\n util = sm * 0.05\nelse:\n if (antig >= 1) and (antig < 2):\n util = sm * 0.07\n else:\n if (antig >= 2) and (antig < 5):\n util = sm * 0.10\n else:\n if (antig >= 5) and (antig < 10):\n util = sm * 0.15\n else:\n util = sm * 0.20\nprint(\"La utilidad es: \", util)\n\n","sub_path":"condicional_multiple_anidadas_1.py","file_name":"condicional_multiple_anidadas_1.py","file_ext":"py","file_size_in_byte":2062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"542732232","text":"# This code is written for plotting degree distribution for the top nodes\r\nimport numpy as np\r\n#import pylab as plt\r\n#import networkx as nx\r\nimport matplotlib.pyplot as plt\r\n#from numpy.random import uniform\r\n#from randomgraph_epinions import calcProp\r\n#f = open('input_1.txt')\r\n#triplets=f.read().split()\r\n#for i in range(0,len(triplets)): triplets[i]=triplets[i].split(',')\r\n#B=np.array(triplets, dtype=np.uint8)\r\n#A=B.reshape(160,2)\r\n#print A\r\n#Biadjacency=np.zeros((136,5), dtype=np.int)\r\n#print Biadjacency\r\n#for i in range(1,137):\r\n# for j in range(1,6):\r\n# for k in range(0,160):\r\n# if (A[k][0]==i and A[k][1]==j):\r\n# Biadjacency[i-1][j-1] =1\r\n#print Biadjacency\r\nf=open('Graph_Adj.txt')\r\ntriplets=f.read().split()\r\nfor i in range(0,len(triplets)): triplets[i]=triplets[i].split(',')\r\nB=np.array(triplets, dtype=np.uint8)\r\nBiadjacency=B.reshape(65, 4667)\r\ncount=0\r\nDegree=[0]*65\r\n#print(Degree)\r\nfor i in range(1,66):\r\n for j in range(1,4668):\r\n if (Biadjacency[i-1][j-1] ==1):\r\n count=count+1\r\n Degree[i-1]=count\r\n count=0\r\n#print(Degree)\r\n#print (max(Degree))\r\nCountDegree=[0]*max(Degree)\r\nprobability=[0]*max(Degree)\r\nfor j in range(1, max(Degree)+1):\r\n for i in range(0, len(Degree)):\r\n if j==Degree[i]:\r\n CountDegree[j-1]=CountDegree[j-1]+1\r\n#print(CountDegree)\r\nfor j in range(1, max(Degree)+1):\r\n probability[j-1]=float(CountDegree[j-1])/65\r\n#print(probability)\r\nMaxdegree=[0]*max(Degree)\r\nfor i in range(1, max(Degree)+1):\r\n Maxdegree[i-1]=i\r\n#print(Maxdegree)\r\nprint('Epinions Top')\r\nfont = {'family': 'serif',\r\n 'color': 'darkblue',\r\n 'weight': 'normal',\r\n 'size': 16,\r\n }\r\nplt.xlabel ('Degree Value',fontdict=font)\r\nplt.ylabel('Probability (Pk)',fontdict=font)\r\nplt.loglog(Maxdegree,probability,'.',color='m')\r\nplt.axis([0, 100, 0, 0.04])\r\n#plt.grid(True,which='both')\r\nplt.show()\r\n","sub_path":"Epinions/Bipartite_Graph_Top_top.py","file_name":"Bipartite_Graph_Top_top.py","file_ext":"py","file_size_in_byte":1918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"72930784","text":"import struct\r\nfrom multiprocessing import Process\r\nimport multiprocessing as mp\r\nimport time\r\nimport threading\r\nfrom socket import *\r\nfrom Crypto.Cipher import AES\r\nfrom Crypto.Util.Padding import pad\r\nfrom Crypto.Util.Padding import unpad\r\nimport os\r\nimport json\r\nfrom os.path import join, isfile, getmtime, getsize, exists\r\nimport argparse\r\n\r\n\r\n\r\n\r\n\r\n######################## Nomal #######################\r\ndef traverse1(dir_path): # check the current directory and ignore the .lefting files\r\n file_list = []\r\n file_folder_list = os.listdir(dir_path)\r\n for file_folder_name in file_folder_list:\r\n if isfile(join(dir_path, file_folder_name)):\r\n if len(file_folder_name)>8:\r\n if file_folder_name[-8:] == '.lefting':\r\n pass\r\n else:\r\n file_list.append(join(dir_path, file_folder_name))\r\n else:\r\n file_list.append(join(dir_path, file_folder_name))\r\n else:\r\n file_list.extend(traverse1(join(dir_path, file_folder_name)))\r\n return file_list # return the file list\r\n\r\ndef traverse2(dir_path): # check if the current directory has .lefting files\r\n file_list= []\r\n file_folder_list= os.listdir(dir_path)\r\n for file_folder_name in file_folder_list:\r\n if isfile(join(dir_path, file_folder_name)):\r\n if len(file_folder_name)>8:\r\n if file_folder_name[-8:] == '.lefting':\r\n file_list.append(join(dir_path, file_folder_name))\r\n else:\r\n file_list.extend(traverse2(join(dir_path, file_folder_name)))\r\n return file_list # return the file list\r\n\r\ndef makeFileDic(file): # make a dictionary for a single file\r\n dict = {'filename': file,\r\n 'mtime': getmtime(file),\r\n 'filesize': getsize(file)}\r\n return dict\r\n\r\ndef makeDictionary(file_list): # make a dictionary list for a file list\r\n file_dict = []\r\n for f in file_list:\r\n dict = {'filename': f,\r\n 'mtime': getmtime(f),\r\n 'filesize': getsize(f)}\r\n file_dict.append(dict)\r\n return file_dict\r\n\r\ndef send_dic(socket, sign, dict): # send a file dictionary list to the peer\r\n dict_json = json.dumps(dict) # change the dictionsry list to json tpye\r\n dict_bytes = dict_json.encode() # change into binary\r\n header = {'sign': sign,\r\n 'size': len(dict_bytes)}\r\n header_json = json.dumps(header) # change the header to json tpye\r\n header_bytes = header_json.encode()\r\n headerlen = struct.pack('i', len(header_bytes))\r\n # send header length\r\n socket.send(headerlen)\r\n # send header\r\n socket.send(header_bytes)\r\n # send dictionary list\r\n socket.send(dict_bytes)\r\n\r\ndef _argparse():\r\n parser = argparse.ArgumentParser(description=\"This is description\")\r\n parser.add_argument('--ip', action = 'store', required = True, dest = 'ip', help = 'ip address of peers')\r\n parser.add_argument('--encryption', action='store', required=False, dest='e', help='encryption')\r\n return parser.parse_args()\r\n\r\ndef savedict(dict, filename):\r\n d = []\r\n for k in dict:\r\n d.append(k)\r\n dict_json = json.dumps(d)\r\n dict_bytes = dict_json.encode()\r\n with open(filename,'wb') as f:\r\n f.write(dict_bytes)\r\n\r\ndef encryptfile(filename):\r\n nf = open(filename, 'rb')\r\n data = nf.read()\r\n key = b'feimax_zuishai!!'\r\n iv = b'qwertyuiopasdfgh'\r\n cipher = AES.new(key, AES.MODE_CBC, iv=iv)\r\n encrypted_data = cipher.encrypt(pad(data, AES.block_size))\r\n ef = open(filename + '.lefting', 'wb')\r\n ef.write(encrypted_data)\r\n nf.close()\r\n ef.close()\r\n\r\n\r\ndef decryptfile(filename):\r\n key = b'feimax zuishai!!'\r\n iv = b'qwertyuiopasdfgh'\r\n with open(filename, 'rb') as f:\r\n encrypted_data = f.read()\r\n cipher = AES.new(key, AES.MODE_CBC, iv=iv)\r\n decrypted_data = unpad(cipher.decrypt(encrypted_data), AES.block_size)\r\n with open(filename, 'wb') as f:\r\n f.write(decrypted_data)\r\n\r\n######################## Scanner #######################\r\n\r\ndef scanner(local_dict, open_dict, server_port, peer):\r\n print('I an scanning...')\r\n while True:\r\n news = []\r\n file_list1 = traverse1('share')\r\n new_dict1 = makeDictionary(file_list1).copy()\r\n time.sleep(0.1)\r\n file_list2 = traverse1('share')\r\n new_dict2 = makeDictionary(file_list2).copy()\r\n\r\n # compare with local_dict, if news, add the new files\r\n if new_dict1 == new_dict2:\r\n for f in new_dict2:\r\n if f not in local_dict:\r\n news.append(f)\r\n if len(news) == 0: # if the length of news is 0, there are no new files\r\n time.sleep(0.1)\r\n else:\r\n print('have new files!!', news)\r\n socket1 = socket(AF_INET, SOCK_STREAM)\r\n socket2 = socket(AF_INET, SOCK_STREAM)\r\n try: # try to connect with peer1, and send news\r\n socket1.connect((peer[0], server_port))\r\n send_dic(socket1, 'news', news)\r\n socket1.close()\r\n except ConnectionRefusedError:\r\n print('connection1 fail')\r\n try: # try to connect with peer2, and send news\r\n socket2.connect((peer[1], server_port))\r\n send_dic(socket2, 'news', news)\r\n socket2.close()\r\n except ConnectionRefusedError:\r\n print('connection2 fail')\r\n for d1 in new_dict2: # update the local_dict\r\n local_dict.append(d1)\r\n savedict(local_dict, 'local_dict.log')\r\n for d2 in news: # update the open_dict\r\n open_dict.append(d2)\r\n savedict(open_dict, 'open_dict.log')\r\n time.sleep(0.5)\r\n\r\n\r\n\r\n######################## Listener #######################\r\ndef listener(open_dict, ticket, server_port, encryption):\r\n server_socket = socket(AF_INET, SOCK_STREAM)\r\n server_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)\r\n server_socket.bind(('', server_port))\r\n server_socket.listen(30)\r\n print('I am listening...')\r\n while True: # listen new requested connections, if there is connection, put it to a new thread\r\n connection_socket, client_address = server_socket.accept()\r\n print('Connect with ', client_address)\r\n thd = threading.Thread(target=subfunc, args=(connection_socket, open_dict, ticket, encryption))\r\n thd.daemon = True\r\n thd.start()\r\n\r\ndef subfunc(connection_socket, open_dict, ticket, encryption):\r\n # reveice and check the sign\r\n obj = connection_socket.recv(4)\r\n header_size = struct.unpack('i', obj)[0]\r\n header_bytes = connection_socket.recv(header_size)\r\n header_json = header_bytes.decode()\r\n header = json.loads(header_json)\r\n sign = header['sign']\r\n data_size = header['size']\r\n dict_bytes = connection_socket.recv(data_size)\r\n dict_json = dict_bytes.decode()\r\n dict = json.loads(dict_json)\r\n\r\n if sign == 'hello':\r\n print('received Hello !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!',dict)\r\n recv_hello(connection_socket, dict, open_dict, ticket)\r\n elif sign == 'news':\r\n print('received news !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!',dict)\r\n recv_news(dict, open_dict, ticket)\r\n elif sign == 'get_file':\r\n print('received get_file !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!',dict)\r\n get_file(connection_socket, dict, open_dict, encryption)\r\n connection_socket.close()\r\n\r\n\r\ndef recv_hello(connection_socket, dict, open_dict, ticket):\r\n print('recv_hello open_dict: ',open_dict)\r\n d = []\r\n for k in open_dict:\r\n d.append(k)\r\n send_dic(connection_socket, 'news', d)\r\n for d in dict:\r\n if d not in open_dict:\r\n ticket.append(d)\r\n\r\ndef recv_news(dict, open_dict, ticket):\r\n for d in dict:\r\n if d not in open_dict:\r\n ticket.append(d)\r\n\r\ndef get_file(connection_socket, dict, open_dict, encryption):\r\n if dict not in open_dict:\r\n header = struct.pack('i', 1)\r\n connection_socket.send(header)\r\n connection_socket.close()\r\n else:\r\n header = struct.pack('i', 0)\r\n connection_socket.send(header)\r\n b = 0\r\n BUFFER_SIZE = 20480\r\n restsize = dict['filesize']\r\n f = open(dict['filename'], 'rb')\r\n while restsize >= BUFFER_SIZE:\r\n data = f.read(BUFFER_SIZE)\r\n connection_socket.sendall(data)\r\n restsize = restsize - BUFFER_SIZE\r\n b += 1\r\n print('send: ',dict['filename'],' block: ', b, ' rest_size: ', restsize)\r\n data = f.read(restsize)\r\n connection_socket.sendall(data)\r\n f.close()\r\n connection_socket.close()\r\n\r\n######################## Downloader #######################\r\n\r\ndef downloader(local_dict, open_dict, ticket, server_port, peer, encryption):\r\n print('Downloader is ready...')\r\n while True:\r\n if len(ticket) != 0: # check if there is a ticket\r\n dict = ticket[0]\r\n print('downloader, the first ticket: ', dict)\r\n if dict in open_dict:\r\n ticket.remove(ticket[0])\r\n else:\r\n # make a new file to store the received data\r\n socket1 = socket(AF_INET, SOCK_STREAM)\r\n socket2 = socket(AF_INET, SOCK_STREAM)\r\n sign = [1]\r\n sign[0] = 0\r\n BUFFER_SIZE = 20480\r\n file = dict['filename']\r\n a = file.split('/')\r\n path = os.path.abspath('share')+'/'+a[1]############!!!!!!!!!\r\n if len(a) == 2:\r\n f = open(path+'.lefting', 'wb')\r\n else:\r\n folder = exists(path)\r\n if not folder:\r\n os.makedirs(path)########################!!!!!!!!!!!!\r\n f = open(path+'/'+a[2]+'.lefting', 'wb')\r\n if sign[0] == 0: # connect with peer1 to get the file\r\n try: ###############!!!!!!!!!!!\r\n socket1.connect((peer[0], server_port))\r\n send_dic(socket1, 'get_file', dict)\r\n obj = socket1.recv(4)\r\n sign[0] = struct.unpack('i', obj)[0]\r\n if sign[0] == 0:\r\n recv_size = 0\r\n b = 0\r\n filesize = dict['filesize']\r\n print('file size: ', filesize) #\r\n while True:\r\n data = socket1.recv(BUFFER_SIZE)\r\n recv_size = recv_size + len(data)\r\n f.write(data)\r\n if recv_size == filesize:\r\n break\r\n b = b + 1\r\n print('filename: ', dict['filename'],' block: ', b, ' recv_size: ', recv_size)\r\n print('rsize:', recv_size,' tsize:', dict['filesize'])\r\n socket1.close()\r\n except:\r\n print('connection1 fail')\r\n sign[0] = 1\r\n\r\n if sign[0] == 1: # if peer1 does not have the file, connect with peer2\r\n try: ###############!!!!!!!!!!!\r\n socket2.connect((peer[1], server_port))\r\n send_dic(socket2, 'get_file', dict)\r\n obj = socket2.recv(4)\r\n sign[0] = struct.unpack('i', obj)[0]\r\n if sign[0] == 0:\r\n recv_size = 0\r\n b = 0\r\n filesize = dict['filesize']\r\n print('file size: ', filesize) #\r\n while True:\r\n data = socket2.recv(BUFFER_SIZE)\r\n recv_size = recv_size + len(data)\r\n f.write(data)\r\n if recv_size == filesize:\r\n break\r\n b = b + 1\r\n print('filename: ', dict['filename'],' block: ', b, ' recv_size: ', recv_size)\r\n print('rsize:', recv_size,' tsize:', dict['filesize'])\r\n socket2.close()\r\n except:\r\n print('connection2 fail')\r\n\r\n if sign[0] == 0:\r\n f.close()\r\n open_dict.append(ticket[0])\r\n dic = makeFileDic(dict['filename'] + '.lefting')\r\n dic['filename'] = dict['filename']##################改顺序\r\n local_dict.append(dic)\r\n\r\n print('start rename ' + dict['filename'] + '.lefting ---> ' + dict['filename']) #\r\n os.renames(dict['filename'] + '.lefting', dict['filename'])\r\n print('rename finished') #\r\n\r\n savedict(open_dict, 'open_dict.log')\r\n savedict(local_dict, 'local_dict.log')\r\n ticket.remove(ticket[0])\r\n else:\r\n time.sleep(0.1)\r\n\r\n######################## Say_Hello #######################\r\ndef Say_Hello():\r\n socket1 = socket(AF_INET, SOCK_STREAM)\r\n socket2 = socket(AF_INET, SOCK_STREAM)\r\n try: # try to connect with peer1\r\n socket1.connect((peer[0], server_port))\r\n print('successfully connect with ', peer[0])\r\n d = []\r\n for k in open_dict:\r\n d.append(k)\r\n send_dic(socket1, 'hello', d)\r\n obj = socket1.recv(4)\r\n header_size = struct.unpack('i', obj)[0]\r\n header_bytes = socket1.recv(header_size)\r\n header_json = header_bytes.decode()\r\n header = json.loads(header_json)\r\n data_size = header['size']\r\n dict_bytes = socket1.recv(data_size)\r\n dict_json = dict_bytes.decode()\r\n dict = json.loads(dict_json)\r\n recv_news(dict, open_dict, ticket)\r\n socket1.close()\r\n except:\r\n print('connection1 fail')\r\n try: # try to connect with peer2\r\n socket2.connect((peer[1], server_port))\r\n print('successfully connect with ', peer[1])\r\n d = []\r\n for k in open_dict:\r\n d.append(k)\r\n send_dic(socket2, 'hello', d)\r\n obj = socket2.recv(4)\r\n header_size = struct.unpack('i', obj)[0]\r\n header_bytes = socket2.recv(header_size)\r\n header_json = header_bytes.decode()\r\n header = json.loads(header_json)\r\n data_size = header['size']\r\n dict_bytes = socket2.recv(data_size)\r\n dict_json = dict_bytes.decode()\r\n dict = json.loads(dict_json)\r\n recv_news(dict, open_dict, ticket)\r\n socket2.close()\r\n except:\r\n print('connection2 fail')\r\n\r\n\r\n######################## Main ########################\r\nif __name__ == '__main__':\r\n parse = _argparse()\r\n encryption = parse.e\r\n peer = parse.ip.split(',')\r\n server_port = 22122\r\n\r\n # if there is no 'share' folder, make one\r\n if not exists('share'):\r\n os.makedirs('share')\r\n\r\n # if there are no local_dict.log and open_dict.log, make them\r\n if exists('local_dict.log') and exists('open_dict.log'):\r\n with open('local_dict.log','rb') as f1:\r\n dict_bytes = f1.read()\r\n dict_json = dict_bytes.decode()\r\n local_dict = json.loads(dict_json)\r\n with open('open_dict.log','rb') as f2:\r\n dict_bytes = f2.read()\r\n dict_json = dict_bytes.decode()\r\n open_dict = json.loads(dict_json)\r\n # if they exist, scan them and store the data in local_dict and open_dict\r\n else:\r\n initial_file_list = traverse1('share')\r\n local_dict = makeDictionary(initial_file_list).copy()\r\n open_dict = local_dict.copy()\r\n savedict(local_dict,'local_dict.log')\r\n savedict(open_dict, 'open_dict.log')\r\n\r\n # if there are lefting files, remove them\r\n leftingfiles = traverse2('share')\r\n for leftfile in leftingfiles:\r\n os.remove(leftfile)\r\n\r\n local_dict = mp.Manager().list(local_dict)\r\n open_dict = mp.Manager().list(open_dict)\r\n ticket = mp.Manager().list()\r\n\r\n Say_Hello()\r\n p1 = Process(target=listener, args=(open_dict, ticket, server_port, encryption))\r\n p2 = Process(target=scanner, args=(local_dict, open_dict, server_port, peer))\r\n p3 = Process(target=downloader, args=(local_dict, open_dict, ticket, server_port, peer, encryption))\r\n p1.start()\r\n p2.start()\r\n p3.start()\r\n\r\n\r\n p3.join()\r\n p2.join()\r\n p1.join()","sub_path":"LEFT_file_sharing_app/Code/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":16876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"99895294","text":"from rest_framework import permissions\n\nclass BasicDefaultPermission(permissions.BasePermission):\n \"\"\"\n Global permission check to ensure that only GET, HEAD and POST\n are allowed to ilp_auth_user and everything else is disabled\n \"\"\"\n def has_permission(self, request, view):\n user = request.user\n print(\"user is: \", user.first_name)\n user.groups.filter(name='ilp_auth_user').exists()\n if request.user.is_authenticated and request.method in ('POST', 'GET', 'OPTIONS'):\n print(\"User is authenticated.PERMIT POST, GET AND HEAD\")\n return True\n else:\n print(\"User is anonymous. PERMIT GET AND HEAD\")\n return False","sub_path":"apps/permissions/api_views.py","file_name":"api_views.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"62659193","text":"from openerp import models, fields, api\nfrom openerp.exceptions import ValidationError\n\n\nclass EbSetting(models.Model):\n _name = 'eb.setting'\n _description = 'Setting'\n\n name = fields.Char(required=True)\n eb_32_acquirer_institution = fields.Char(required=True, size=6)\n eb_33_agency_code = fields.Char(required=True, size=3)\n eb_34_cashier = fields.Char(required=True, size=16)\n eb_37_acquirer_sequence = fields.Char(required=True, size=12)\n eb_41_terminal = fields.Char(required=True, size=16)\n\n _order = 'name'\n\n _sql_constraints = [\n ('name_uk', 'unique(name)', 'Setting must be unique'),\n ]\n\n @api.one\n @api.constrains('eb_32_acquirer_institution','eb_33_agency_code','eb_37_acquirer_sequence')\n def _check_num(self):\n if self.eb_32_acquirer_institution and self.eb_33_agency_code and self.eb_37_acquirer_sequence:\n try:\n int(self.eb_32_acquirer_institution)\n except ValueError:\n raise ValidationError(\"NAN \" + self.eb_32_acquirer_institution +\n \" -> \" + self._fields['eb_32_acquirer_institution']._column_string)\n try:\n int(self.eb_33_agency_code)\n except ValueError:\n raise ValidationError(\"NAN \" + self.eb_33_agency_code +\n \" -> \" + self._fields['eb_33_agency_code']._column_string)\n try:\n int(self.eb_37_acquirer_sequence)\n except ValueError:\n raise ValidationError(\"NAN \" + self.eb_37_acquirer_sequence +\n \" -> \" + self._fields['eb_37_acquirer_sequence']._column_string)\n\n @api.one\n @api.constrains('eb_34_cashier','eb_41_terminal')\n def _check_al_num(self):\n if self.eb_34_cashier:\n if not self.eb_34_cashier.isalnum():\n raise ValidationError(\"NAALN \" + self.eb_34_cashier +\n \" -> \" + self._fields['eb_34_cashier']._column_string)\n if self.eb_41_terminal:\n if not self.eb_41_terminal.isalnum():\n raise ValidationError(\"NAALN \" + self.eb_41_terminal +\n \" -> \" + self._fields['eb_41_terminal']._column_string)\n\n @api.one\n @api.onchange('eb_32_acquirer_institution','eb_33_agency_code','eb_37_acquirer_sequence')\n def _fill_zeros(self):\n if self.eb_32_acquirer_institution:\n self.eb_32_acquirer_institution = self.eb_32_acquirer_institution.zfill(6)\n if self.eb_33_agency_code:\n self.eb_33_agency_code = self.eb_33_agency_code.zfill(3)\n if self.eb_37_acquirer_sequence:\n self.eb_37_acquirer_sequence = self.eb_37_acquirer_sequence.zfill(12)\n\n @api.one\n def copy(self, default=None):\n default = dict(default or {})\n copied_count = self.search_count(\n [('name', '=like', u\"Copy of {}%\".format(self.name))])\n if not copied_count:\n new_name = u\"Copy of {}\".format(self.name)\n else:\n new_name = u\"Copy of {} ({})\".format(self.name, copied_count)\n default['name'] = new_name\n return super(EbSetting, self).copy(default)\n","sub_path":"models/setting.py","file_name":"setting.py","file_ext":"py","file_size_in_byte":3237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"10864225","text":"#######################################################################\n# library\n#######################################################################\nimport pandas as pd #loading data in table form \nimport seaborn as sns #visualisation \nimport matplotlib.pyplot as plt #visualisation\nimport numpy as np # linear algebra\n\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix\n\n\n\n#######################################################################\n# iris\n#######################################################################\n\n#Reading data \ndata = pd.read_csv(\"D:\\\\01_Data_Science\\\\DataSet\\\\iris.CSV\")\n\n# Seperating the data into dependent and independent variables\nX = data.iloc[:, :-1].values\ny = data.iloc[:, -1].values\n\n# Splitting the dataset into the Training set and Test set\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)\n\nfrom sklearn.tree import DecisionTreeClassifier\n\nclassifier = DecisionTreeClassifier()\n\nclassifier.fit(X_train, y_train)\n\ny_pred = classifier.predict(X_test)\n\n# Summary of the predictions made by the classifier\nprint(classification_report(y_test, y_pred))\nprint(confusion_matrix(y_test, y_pred))\n# Accuracy score\nfrom sklearn.metrics import accuracy_score\nprint('accuracy is',accuracy_score(y_pred,y_test))\n\n\n#######################################################################\n# BigMartSales\n#######################################################################\n\n#Read files \ntrain_BigMartSales = pd.read_csv(\"D:\\\\01_Data_Science\\\\DataAnalysis\\\\Projects\\\\001_Big Mart Sales\\\\BigMartSales_Train.CSV\")\nprint(train_BigMartSales.apply(lambda x:sum(x.isnull())))\n\n## Impute mode function\nfrom scipy.stats import mode\n# Determing the mode for each\noutlet_size_mode = train_BigMartSales.pivot_table(values='Outlet_Size',columns='Outlet_Type',aggfunc=lambda x: x.mode().iat[0])\nmiss_bool = train_BigMartSales['Outlet_Size'].isnull() \ntrain_BigMartSales.loc[miss_bool,'Outlet_Size'] = train_BigMartSales.loc[miss_bool,'Outlet_Type'].apply(lambda x: outlet_size_mode[x])\n\n# Impute data and check missing values before and after imputation to confirm\nmiss_bool = train_BigMartSales['Item_Weight'].isnull() \ntrain_BigMartSales.loc[miss_bool,'Item_Weight'] = train_BigMartSales['Item_Weight'].mean()\n\n#Impute 0 values with mean visibility of that product:\nmiss_bool = (train_BigMartSales['Item_Visibility'] == 0)\ntrain_BigMartSales.loc[miss_bool,'Item_Visibility'] = train_BigMartSales['Item_Visibility'].mean()\n\n# Modify categories of Item_Fat_Content\ntrain_BigMartSales['Item_Fat_Content'] = train_BigMartSales['Item_Fat_Content'].replace({'LF':'Low Fat','reg':'Regular','low fat':'Low Fat'})\n#print (train_BigMartSales['Item_Fat_Content'].value_counts())\n\n# Recheck data\n# Check missing values\nprint(train_BigMartSales.apply(lambda x:sum(x.isnull())))\n# Numerical variables: Basic statistic for numerical variables\nprint(train_BigMartSales.describe())\n# Categorical variables: number of unique values\nprint(train_BigMartSales.apply(lambda x:len(x.unique())))\n\n# Numerical and One-Hot Coding of Categorical variables\n#Import library:\nfrom sklearn.preprocessing import LabelEncoder\nle = LabelEncoder()\n#New variable for outlet\nvar_mod = ['Item_Fat_Content','Outlet_Location_Type','Outlet_Size','Outlet_Type','Item_Type']\nle = LabelEncoder()\nfor i in var_mod:\n train_BigMartSales[i] = le.fit_transform(train_BigMartSales[i])\n#One Hot Coding:\ntrain_BigMartSales = pd.get_dummies(train_BigMartSales, columns=['Item_Fat_Content','Outlet_Location_Type','Outlet_Size','Outlet_Type','Item_Type'])\n\ntarget = 'Item_Outlet_Sales'\nIDcol = ['Item_Identifier','Outlet_Identifier']\npredictors = [x for x in train_BigMartSales.columns if x not in [target]+IDcol]\n# ['Item_MRP', 'Item_Visibility', 'Item_Weight', 'source', 'Outlet_Years', 'Item_Fat_Content_0', 'Item_Fat_Content_1', 'Item_Fat_Content_2', 'Outlet_Location_Type_0', 'Outlet_Location_Type_1', 'Outlet_Location_Type_2', 'Outlet_Size_0', 'Outlet_Size_1', 'Outlet_Size_2', 'Outlet_Type_0', 'Outlet_Type_1', 'Outlet_Type_2', 'Outlet_Type_3', 'Item_Type_Combined_0', 'Item_Type_Combined_1', 'Item_Type_Combined_2', 'Outlet_0', 'Outlet_1', 'Outlet_2', 'Outlet_3', 'Outlet_4', 'Outlet_5', 'Outlet_6', 'Outlet_7', 'Outlet_8', 'Outlet_9']\nprint(predictors)\nX_train = train_BigMartSales[predictors] \nY_train = train_BigMartSales[target]\nX_test = train_BigMartSales[predictors] \nY_test = train_BigMartSales[target] \n\n#----------------------------------------------------------------------\n# Decision Tree\n#----------------------------------------------------------------------\nfrom sklearn.tree import DecisionTreeRegressor\nalg3 = DecisionTreeRegressor(max_depth=15, min_samples_leaf=100)\nalg3.fit(X_train,Y_train)\nprint(alg3.feature_importances_)\ncoef3 = pd.Series(alg3.feature_importances_, predictors).sort_values(ascending=False)\ncoef3.plot(kind='bar', title='Feature Importances')\n# Predict training set\ny_pred3 = alg3.predict(X_train)\nplt.show()\n\npredictors = ['Item_MRP','Outlet_Type_0','Outlet_Location_Type_0','Outlet_Establishment_Year']\nX_train = train_BigMartSales[predictors] \nalg4 = DecisionTreeRegressor(max_depth=8, min_samples_leaf=150)\nalg4.fit(X_train,Y_train)\ncoef4 = pd.Series(alg4.feature_importances_, predictors).sort_values(ascending=False)\ncoef4.plot(kind='bar', title='Feature Importances')\n# Predict training set\ny_pred4 = alg4.predict(X_train)\nplt.show()\n\n# Calculating MSE\nfrom sklearn import metrics\nprint (\"RMSE : %.4g\" % np.sqrt(metrics.mean_squared_error(Y_train, y_pred3)))\nprint(\"R: $.2g\" % metrics.r2_score(Y_train,y_pred3))\nprint (\"RMSE : %.4g\" % np.sqrt(metrics.mean_squared_error(Y_train, y_pred4)))\n\n\n#######################################################################\n# Decision Tree\n#######################################################################\n# Create data set with X as predictors and y as the response\nfrom sklearn.datasets import make_blobs\nfrom sklearn.cluster.tests.test_k_means import n_samples\nfrom matplotlib.pyplot import clim\n\nX, y = make_blobs(n_samples=300, centers=4, random_state=0, cluster_std=1.0 )\nprint(X[1:10,])\nprint(y[1:10])\nplt.scatter(X[:,0],X[:,1],c=y,s=50,cmap='rainbow')\n\n# Fitting a decision tree \nfrom sklearn.tree import DecisionTreeClassifier\ntree = DecisionTreeClassifier().fit(X,y)\n# Visualize the tree\ndef visualize_classifier(model, X, y, ax=None,cmap='rainbow'):\n ax = ax or plt.gca()\n # Plot the training points\n ax.scatter(X[:,0],X[:,1],c=y,s=30,cmap=cmap,clim=(y.min(),y.max()),zorder=3)\n ax.axis('tight')\n ax.axis('off')\n xlim = ax.get_xlim()\n ylim = ax.get_ylim()\n # fit the estimator\n model.fit(X,y)\n xx, yy = np.meshgrid(np.linspace(*xlim,num=200),np.linspace(*ylim, num=200))\n Z = model.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape)\n # Create a color plot with the results\n n_classes = len(np.unique(y))\n contours = ax.contourf(xx, yy, Z, alpha=0.3,\n levels=np.arange(n_classes + 1) - 0.5,\n cmap=cmap, clim=(y.min(), y.max()),\n zorder=1)\n\n ax.set(xlim=xlim, ylim=ylim)\n plt.show()\n \nvisualize_classifier(DecisionTreeClassifier(), X, y)\n\n\n\n\n\n","sub_path":"08_DecisionTree.py","file_name":"08_DecisionTree.py","file_ext":"py","file_size_in_byte":7298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"495492563","text":"from collections import defaultdict\nfrom collections import deque\n\n\ndef insert(part_trie, word):\n copy_trie = part_trie\n q = deque(list(word))\n while q:\n char = q.popleft()\n if char not in copy_trie:\n copy_trie[char] = [0, {}]\n copy_trie[char][0] += 1\n copy_trie = copy_trie[char][1]\n\n\ndef find(trie, query):\n cnt = 0\n copy_trie = trie\n if len(copy_trie) == 0:\n return 0\n\n q = deque(list(query))\n\n while q:\n char = q.popleft()\n if char == \"?\":\n return cnt\n else:\n if char not in copy_trie:\n return 0\n cnt = copy_trie[char][0]\n copy_trie = copy_trie[char][1]\n\n return cnt\n\n\ndef solution(words, queries):\n answer = []\n # 트라이 자료구조 활용하기!\n trie = defaultdict(dict)\n reversed_trie = defaultdict(dict)\n\n # !!!쿼리가 모두 물음표인 경우 시간 초과가 발생하므로, 문자 길이에 따라 갯수 저장\n length_list = [0] * 10001\n\n # trie 만들기\n for word in words:\n length_word = len(word)\n length_list[length_word] += 1\n\n insert(trie[length_word], word)\n insert(reversed_trie[length_word], word[::-1])\n for key,value in trie.items():\n print(key, value)\n # 찾기\n for query in queries:\n length_query = len(query)\n\n if query.count('?') == length_query: # 쿼리가 모두 물음표인 경우\n answer.append(length_list[length_query])\n continue\n if query[0] == \"?\": # 물음표로 시작하는 쿼리\n answer.append(find(reversed_trie[length_query], query[::-1]))\n else:\n answer.append(find(trie[length_query], query))\n\n return answer\n\n\nqqq = [\n [[\"frodo\", \"front\", \"frost\", \"frozen\", \"frame\", \"kakao\",], [\"fro??\", \"????o\", \"fr???\", \"fro???\", \"pro?\"]]\n]\nfor q1, q2 in qqq:\n print(solution(q1, q2))\n","sub_path":"프로그래머스/2020 KAKAO BLIND RECRUITMENT/가사 검색.py","file_name":"가사 검색.py","file_ext":"py","file_size_in_byte":1935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"188558262","text":"\"\"\"ViewSets for the analytics app.\"\"\"\n\nfrom django.db.models.query import F\nfrom django.db.models.fields import DecimalField\n\nfrom django.db.models.expressions import OuterRef, Case\nfrom django.db.models.expressions import Subquery, When\nfrom django.db.models.expressions import ExpressionWrapper\n\nfrom django.db.models.functions import Now\nfrom django.db.models.aggregates import Avg, Sum\n\nfrom rest_framework.mixins import ListModelMixin\nfrom rest_framework.viewsets import GenericViewSet\n\nfrom analytics.serializers import CompanyChartSerializer\n\nfrom companies.models import Company\nfrom activities.models import Session\n\n\nclass CompanyChartsViewSet(GenericViewSet, ListModelMixin):\n queryset = Company.objects.annotate(\n __session_average=Subquery(\n Session.objects.filter(\n company=OuterRef(\"id\")\n ).annotate(\n value=ExpressionWrapper(\n Avg(\"answered_questions__value\")\n *\n F(\"set__weight\"),\n output_field=DecimalField(\n max_digits=3,\n decimal_places=2,\n )\n )\n ).values(\"value\")\n )\n ).annotate(\n date=Case(\n When(\n sessions__until__lte=Now(),\n then=F(\"sessions__until\")\n ),\n default=Now()\n ),\n data=ExpressionWrapper(\n Sum(\"__session_average\")\n *\n F(\"sessions__theme__weight\"),\n\n output_field=DecimalField(decimal_places=2, max_digits=3)\n )\n ).values(\"data\", \"date\")\n\n serializer_class = CompanyChartSerializer\n\n def filter_queryset(self, queryset):\n return queryset.filter(id=self.request.user.member.company_id)\n\n\nclass SessionChartsViewSet(GenericViewSet, ListModelMixin):\n queryset = Session.objects.annotate(\n data=Avg(\"answered_questions__value\") * F(\"set__weight\"),\n date=Case(\n When(until__lte=Now(), then=F(\"until\")),\n default=Now()\n ),\n )\n\n def filter_queryset(self, queryset):\n return queryset.filter(id=self.request.user.member.company_id)\n","sub_path":"backend/analytics/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"59208607","text":"from django.conf.urls import patterns, include, url\n\n# Uncomment the next two lines to enable the admin:\n# from django.contrib import admin\n# admin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'myproject.views.home', name='home'),\n url(r'^getdata/', 'metaurl.views.getdata'),\n\n url(r'^$', 'metaurl.views.showform'), \n url(r'^showdata/','metaurl.views.getdata'),\n url(r'^newurl/','metaurl.views.showform'),\n\n\n # Uncomment the next line to enable the admin:\n # url(r'^admin/', include(admin.site.urls)),\n)\n","sub_path":"myproject/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"143110793","text":"import lightgbm as lgb\nimport pandas as pd\nimport copy\n\nfrom sub.field_class import *\n\n'''\nmain_collectData.pyで作成したシミュレーション結果を元に、ゲームをクリアするモデルを作成する。\n本モデルでは、現在のすべてのマスの状態とそのときに開けるマスを説明変数として、結果を被説明変数とする。\n(汎用性はない)\n'''\n\nx,y,bom = 3,3,3 # x:横のマス数 y:縦のマス数 bom:bomの数\nx_input_init, y_input_init = 0,0 #1回目にどのマスを開けるか\n\ndf = pd.read_csv('random_simulation_kekka.csv')\ndf.loc[(df.return_val==1), 'return_val'] = 0 #1(クリア)を0(継続)に統一する。\ndf.loc[(df.return_val==-1), 'return_val'] = 1 #-1(bom)を1に\n\nprint(df.head())\n\nX_df =df.iloc[:,:-1]\ny_df = df.loc[:,['return_val']]\nX_train = X_df.iloc[:int(len(y_df)*0.8), :]\ny_train = y_df.iloc[:int(len(y_df)*0.8), :]\nX_test = X_df.iloc[int(len(y_df)*0.8):, :]\ny_test = y_df.iloc[int(len(y_df)*0.8):, :]\n\n# LGBMモデルのパラメータ\nnum_leaves_ = 100\nlearning_rate_ = 0.05\nmax_bin_ = 255 #初期値255\ntest_size_ =0.2 #モデル作成時の値\n\n# LightGBM のハイパーパラメータ\nlgbm_params = {\n 'objective': 'binary',\n 'metric':'auc',\n 'verbosity':-1, #学習の途中経過をprintするかどうか。デフォはする、-1はしない\n 'num_leaves':num_leaves_,\n 'learning_rate':learning_rate_,\n 'max_bin':max_bin_ \n}\n\n# データセットを生成する\nlgb_train = lgb.Dataset(X_train, y_train)\nlgb_eval = lgb.Dataset(X_test, y_test, reference=lgb_train)\n\n# 上記のパラメータでモデルを学習する\nmodel = lgb.train(lgbm_params, lgb_train, valid_sets=lgb_eval,\n num_boost_round=1500,early_stopping_rounds=30,\n verbose_eval=4\n )\n\nimport pickle\nwith open('model_lgbm.pkl', mode='wb') as fp:\n pickle.dump(model, fp)\n\nprint(model.predict(X_train))\n","sub_path":"main_makeModel.py","file_name":"main_makeModel.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"463239138","text":"\"\"\"Project1 URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('',include('home.urls')),\n path('myapp/',include('myapp.urls')),\n path('blogs/',include('blogs.urls')),\n path('music/',include('music.urls')),\n path('todolist/',include('todolist.urls')),\n path('quotes/',include('quotes.urls')),\n path('tts/',include('tts.urls')),\n path('translate/',include('translate.urls')),\n path('visualization/',include('visualization.urls')),\n path('s2t/',include('s2t.urls')),\n path('quiz/',include('quiz.urls')),\n path('tweet/',include('tweet.urls')),\n]\n\nif settings.DEBUG:\n urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT)\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)","sub_path":"Project1/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"194749499","text":"board = []\nboard.append([\" \", \"_\", \"_\", \"_\", \"_\", \" \", \" \"])\nfor x in range(6):\n board.append([\" \", \"|\", \" \", \" \", \" \", \" \", \" \"])\nboard.append([\"X\"] * 7)\nboard.append([\" \"] * 7)\n\n# instellen\nsecret_word = \"boeken\"\nsecret_word_l = list(secret_word)\nturn = 1\nerror = 0\nguessed_letters = [\"\"]\nguessed_word = [\"_\"] * len(secret_word)\nboard.append(guessed_word)\n\n\ndef print_board(board):\n # print(\"\\n\"*30)\n for row in board:\n print(\" \".join(row))\n print(\"\")\n guessed_letters.sort()\n guessed = \"\".join(guessed_letters)\n print(\"Guessed: {}\".format(guessed))\n print(\"\")\n\ndef hang_it(x):\n if x == 1:\n board[1] = [\" \", \"|\", \" \", \" \", \"|\", \" \", \" \"]\n if x == 2:\n board[2] = [\" \", \"|\", \" \", \" \", \"O\", \" \", \" \"]\n if x == 3:\n board[3] = [\" \", \"|\", \" \", \" \", \"|\", \" \", \" \"]\n if x == 4:\n board[3] = [\" \", \"|\", \" \", \"\\\\\", \"|\", \" \", \" \"]\n if x == 5:\n board[3] = [\" \", \"|\", \" \", \"\\\\\", \"|\", \"/\", \" \"]\n if x == 6:\n board[4] = [\" \", \"|\", \" \", \" \", \"|\", \" \", \" \"]\n if x == 7:\n board[5] = [\" \", \"|\", \" \", \"/\", \" \", \" \", \" \"]\n if x == 8:\n board[5] = [\" \", \"|\", \" \", \"/\", \" \", \"\\\\\", \" \"]\n\n\ndef game_over():\n print_board(board)\n print(\"Game over!\")\n exit()\n\n\ndef inputting():\n global turn\n guess = input(\"Which letter? \")\n if guess == \"quit\": exit()\n turn += 1\n if guess.isalpha() & len(guess) == 1:\n if guess in guessed_letters:\n print(\"You guessed {} already! Try again.\".format(guess))\n print(\"Try again\")\n if turn > 26: game_over()\n return False\n # inputting()\n else:\n guessed_letters.append(guess)\n return guess\n else:\n return False\n\n\n# find indeces for guessed letter in secret word\n# indices = [i for i, x in enumerate(secret_word_l) if x == guess]\n\nprint(\"Let's play HangMan!\")\nprint_board(board)\nprint(\"\")\n\n# control flow\nwhile True:\n print(\"Turn %s: \" % turn)\n guess = inputting()\n if guess not in secret_word_l and guess != False:\n error += 1\n hang_it(error)\n if error == 8: game_over()\n\n indices = [i for i, x in enumerate(secret_word_l) if x == guess]\n for i in indices:\n board[9][i] = guess\n print_board(board)\n if guessed_word == secret_word_l:\n print(\"You win!\")\n exit()\n","sub_path":"hangman.py","file_name":"hangman.py","file_ext":"py","file_size_in_byte":2358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"636805845","text":"import tf_cnn_siamese.configurations as conf\nimport tensorflow as tf\nimport numpy as np\n\n\ndef construct_cnn(x, conv_weights, conv_biases, fc_weights, fc_biases,\n dropout = False):\n \"\"\"\n constructs the convolution graph for one image\n :param x: input node\n :param conv_weights: convolution weights\n :param conv_biases: relu biases for each convolution\n :param fc_weights: fully connected weights, only one set should be used here\n :param fc_biases: fully connected biases, only one set should be used here\n :param dropout: whether to add a dropout layer for the fully connected layer\n :return: output node\n \"\"\"\n k = conf.NUM_POOL\n for i in range(conf.NUM_CONVS):\n x = tf.nn.conv2d(x, conv_weights[i], strides=[1, 1, 1, 1], padding='SAME',\n data_format=conf.DATA_FORMAT)\n x = tf.nn.relu(tf.nn.bias_add(x, conv_biases[i],\n data_format=conf.DATA_FORMAT))\n if k > 0:\n x = tf.nn.max_pool(x, ksize=conf.POOL_KDIM,strides=conf.POOL_KDIM,\n padding='VALID', data_format=conf.DATA_FORMAT)\n k -= 1\n # Reshape the feature map cuboids into vectors for fc layers\n features_shape = x.get_shape().as_list()\n n = features_shape[0]\n m = features_shape[1] * features_shape[2] * features_shape[3]\n features = tf.reshape(x, [n, m])\n # last fc_weights determine output dimensions\n fc = tf.nn.sigmoid(tf.matmul(features, fc_weights[0]) + fc_biases[0])\n # for actual training\n if dropout:\n fc = tf.nn.dropout(fc, conf.DROP_RATE)\n return fc\n\n\ndef construct_logits_model(x_1, x_2, conv_weights, conv_biases, fc_weights,\n fc_biases, dropout=False):\n \"\"\"\n constructs the logit node before the final sigmoid activation\n :param x_1: input image node 1\n :param x_2: input image node 2\n :param conv_weights: nodes for convolution weights\n :param conv_biases: nodes for convolution relu biases\n :param fc_weights: nodes for fully connected weights\n :param fc_biases: nodes for fully connected biases\n :param dropout: whether to include dropout layers\n :return: logit node\n \"\"\"\n with tf.name_scope(\"twin_1\"):\n twin_1 = construct_cnn(x_1, conv_weights, conv_biases,\n fc_weights, fc_biases, dropout)\n with tf.name_scope(\"twin_2\"):\n twin_2 = construct_cnn(x_2, conv_weights, conv_biases,\n fc_weights, fc_biases, dropout)\n # logits on squared difference\n sq_diff = tf.squared_difference(twin_1, twin_2)\n logits = tf.matmul(sq_diff, fc_weights[1]) + fc_biases[1]\n return logits\n\n\ndef construct_full_model(x_1, x_2, conv_weights, conv_biases,fc_weights,\n fc_biases):\n \"\"\"\n constructs the graph for the neural network without loss node or optimizer\n :param x_1: input image node 1\n :param x_2: input image node 2\n :param conv_weights: nodes for convolution weights\n :param conv_biases: nodes for convolution relu biases\n :param fc_weights: nodes for fully connected weights\n :param fc_biases: nodes for fully connected biases\n :return: sigmoid output node\n \"\"\"\n logits = construct_logits_model(x_1, x_2, conv_weights, conv_biases,\n fc_weights, fc_biases, dropout=False)\n return tf.nn.sigmoid(logits)\n\n\ndef construct_loss_optimizer(x_1, x_2, labels, conv_weights, conv_biases,\n fc_weights, fc_biases, dropout=False,\n lagrange=False):\n \"\"\"\n constructs the neural network graph with the loss and optimizer node\n :param x_1: input image node 1\n :param x_2: input image node 2\n :param labels: expected output\n :param conv_weights: nodes for convolution weights\n :param conv_biases: nodes for convolution relu biases\n :param fc_weights: nodes for fully connected weights\n :param fc_biases: nodes for fully connected biases\n :param dropout: whether to use dropout\n :param lagrange: whether to apply constraints\n :return: the node for the optimizer as well as the loss\n \"\"\"\n logits = construct_logits_model(x_1, x_2, conv_weights, conv_biases,\n fc_weights, fc_biases, dropout)\n # cross entropy loss on sigmoids of joined output and labels\n loss_vec = tf.nn.sigmoid_cross_entropy_with_logits(labels=labels,\n logits=logits)\n loss = tf.reduce_mean(loss_vec)\n if lagrange:\n # constraints on sigmoid layers\n regularizers = (tf.nn.l2_loss(fc_weights[0]) + tf.nn.l2_loss(fc_biases[0]) +\n tf.nn.l2_loss(fc_weights[1]) + tf.nn.l2_loss(fc_biases[1]))\n loss += conf.LAMBDA * regularizers\n # setting up the optimization\n batch = tf.Variable(0, dtype=conf.DTYPE)\n\n # vanilla momentum optimizer\n # accumulation = momentum * accumulation + gradient\n # every epoch: variable -= learning_rate * accumulation\n # batch_total = labels.shape[0]\n # learning_rate = tf.train.exponential_decay(\n # conf.BASE_LEARNING_RATE,\n # batch * conf.BATCH_SIZE, # Current index into the dataset.\n # batch_total,\n # conf.DECAY_RATE, # Decay rate.\n # staircase=True)\n # trainer = tf.train.MomentumOptimizer(learning_rate, conf.MOMENTUM)\\\n # .minimize(loss, global_step=batch)\n\n # adaptive momentum estimation optimizer\n # default params: learning_rate=0.001, beta1=0.9, beta2=0.999, epsilon=1e-08\n trainer = tf.train.AdamOptimizer().minimize(loss, global_step=batch)\n return trainer, loss\n\n\ndef construct_joined_model(twin_1, twin_2, fc_weights, fc_biases):\n \"\"\"\n constructs joined model for two sets of extracted features\n :param twin_1: features node extracted from first image\n :param twin_2: features node extracted from second image\n :param fc_weights: nodes for fully connected weights\n :param fc_biases: nodes for fully connected biases\n :return: logit node\n \"\"\"\n # logits on squared difference\n sq_diff = tf.squared_difference(twin_1, twin_2)\n logits = tf.matmul(sq_diff, fc_weights[1]) + fc_biases[1]\n return tf.nn.sigmoid(logits)\n\n\ndef initialize_weights():\n \"\"\"\n initializes the variable tensors to be trained in the neural network, decides\n network dimensions\n :return: nodes for the variables\n \"\"\"\n # twin network convolution and pooling variables\n conv_weights = []\n conv_biases = []\n fc_weights = []\n fc_biases = []\n for i in range(conf.NUM_CONVS):\n if i == 0:\n inp = conf.NUM_CHANNELS\n else:\n inp = conf.NUM_FILTERS[i - 1]\n out = conf.NUM_FILTERS[i]\n conv_dim = [conf.FILTER_LEN, conf.FILTER_LEN, inp, out]\n weight_name = \"twin_conv\" + str(i + 1) + \"_weights\"\n bias_name = \"twin_conv\" + str(i + 1) + \"_biases\"\n conv_weights.append(tf.Variable(tf.truncated_normal(conv_dim, stddev=0.1,\n seed=conf.SEED, dtype=conf.DTYPE),\n name=weight_name))\n conv_biases.append(tf.Variable(tf.zeros([out], dtype=conf.DTYPE),\n name=bias_name))\n # twin network fullly connected variables\n inp = conf.FEATURE_MAP_SIZE\n out = conf.NUM_FC_NEURONS\n fc_weights.append(tf.Variable(tf.truncated_normal([inp, out], stddev=0.1,\n seed=conf.SEED, dtype=conf.DTYPE),\n name=\"twin_fc_weights\"))\n fc_biases.append(tf.Variable(tf.constant(0.1, shape=[out], dtype=conf.DTYPE),\n name=\"twin_fc_biases\"))\n # joined network fully connected variables\n inp = conf.NUM_FC_NEURONS\n out = 1\n fc_weights.append(tf.Variable(tf.truncated_normal([inp, out], stddev=0.1,\n seed=conf.SEED, dtype=conf.DTYPE),\n name=\"joined_fc_weights\"))\n fc_biases.append(tf.Variable(tf.constant(0.1, shape=[out], dtype=conf.DTYPE),\n name=\"joined_fc_biases\"))\n return conv_weights, conv_biases, fc_weights, fc_biases\n\n\ndef num_params():\n \"\"\"\n calculates the number of parameters in the model\n :return: m, number of parameters\n \"\"\"\n m = 0\n for i in range(conf.NUM_CONVS):\n if i == 0:\n inp = conf.NUM_CHANNELS\n else:\n inp = conf.NUM_FILTERS[i - 1]\n out = conf.NUM_FILTERS[i]\n conv_dim = [conf.FILTER_LEN, conf.FILTER_LEN, inp, out]\n m += np.prod(conv_dim) + np.prod(out)\n inp = conf.FEATURE_MAP_SIZE\n out = conf.NUM_FC_NEURONS\n m += inp * out + out\n inp = conf.NUM_FC_NEURONS\n out = 1\n m += inp * out + out\n return m\n\n\nif __name__ == \"__main__\":\n print(\"Number of Parameters: \" + str(num_params()))\n","sub_path":"tf_cnn_siamese/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":8501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"366585221","text":"# -*- coding: utf8 -*-\nimport sys\nimport socket\nimport time\nimport json\nimport os\n\nstart_time = time.time()\n\nsock = socket.socket()\nsock.bind(('', 50123))\nsock.listen(1)\nconn, addr = sock.accept()\n\nprint (start_time)\nprint ('connected:', addr)\n\nwhile True:\n data = conn.recv(2048)\n if not data:\n break\n\n to_file_data = json.loads(data.decode(\"utf-8\"))\n print(to_file_data)\n\n setting_file = open(\"setupfile.json\", \"w\")\n setting_file.write(to_file_data)\n\n setting_file.close()\n\n conn.send(to_file_data.encode(\"utf-8\"))\n\nconn.close()\n\ntime.sleep(2)\nos.system('sudo shutdown -r now')\n\n# v 0.1.2\n# сервер должен закрываться через 120 с после старта, если нет клиента\n# должна аутентификация клиента (log, pas)\n#\n\n\n\"\"\" work_time = time.time() - start_time\n if start_time > 10.0:\n print(work_time)\n break \"\"\"","sub_path":"ClientOrange/initServer.py","file_name":"initServer.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"215728616","text":"from __future__ import annotations\n\nimport os\nfrom abc import ABC\n\nfrom selenium import webdriver\nfrom selenium.webdriver.remote.webdriver import WebDriver\nfrom selenium.webdriver.remote.webelement import WebElement\nfrom textx import textx_isinstance\nfrom textx.metamodel import TextXMetaModel\n\nfrom wash_lang_prototype.core.exceptions import WashError\nfrom wash_lang_prototype.core.options import WashOptions\nfrom wash_lang_prototype.lang.wash import *\n\n\ndef create_executor_instance(script: str, options: WashOptions, metamodel: TextXMetaModel,\n model: WashScript, debug=False, **kwargs):\n from wash_lang_prototype.core.configuration_handler import ChromeConfigurationHandler, \\\n FirefoxConfigurationHandler, EdgeConfigurationHandler, OperaConfigurationHandler\n\n root_handler = ChromeConfigurationHandler()\n firefox_handler = FirefoxConfigurationHandler()\n edge_handler = EdgeConfigurationHandler()\n opera_handler = OperaConfigurationHandler()\n # TODO: default_configuration_handler = DefaultConfigurationHandler()\n\n root_handler.set_next(firefox_handler)\\\n .set_next(edge_handler)\\\n .set_next(opera_handler)\n # TODO: .set_next(default_configuration_handler)\n\n configuration_handling_result = root_handler.handle(configuration=model.configuration)\n\n return configuration_handling_result.executor_type(\n browser_options=configuration_handling_result.browser_options,\n **dict(kwargs, script=script, options=options,\n metamodel=metamodel, model=model, debug=debug,\n implicit_wait_value=configuration_handling_result.implicit_wait_value))\n\n\nclass WashExecutor(ABC):\n \"\"\"\n Main class that handles execution logic of WASH scripts. This is an abstract class and should not be instantiated.\n \"\"\"\n\n def __init__(self, **kwargs):\n self._options = kwargs.pop('options') # type: WashOptions\n self.__script = kwargs.pop('script') # type: str\n self.__metamodel = kwargs.pop('metamodel') # type: TextXMetaModel\n self.__model = kwargs.pop('model') # type: WashScript\n self.__debug = kwargs.pop('debug') # type: bool\n self._time_to_wait = kwargs.pop('implicit_wait_value') # type: int\n\n def execute(self) -> ExecutionResult:\n \"\"\"\n Executes a WASH script and returns an ExecutionResult instance.\n \"\"\"\n document_location = self.__extract_document_location(self.__model.open_statement)\n try:\n webdriver_instance = self._start_webdriver_instance(url=document_location)\n\n execution_result = self.__execute_internal(webdriver_instance=webdriver_instance)\n\n wash_result = ExecutionResult(\n parent=None,\n start_url=document_location,\n current_url=webdriver_instance.current_url,\n execution_result=execution_result)\n\n if self.__debug:\n wash_result.add_attributes(**{'script': self.__script})\n\n return wash_result\n except Exception:\n raise\n finally:\n webdriver_instance.quit()\n\n @abstractmethod\n def _start_webdriver_instance(self, url: str) -> WebDriver:\n \"\"\"\n Starts a new webdriver instance on the given URL.\n \n Args:\n url(str): URL of the page the webdriver instance should load.\n \"\"\"\n pass\n\n def __is(self, object_instance: WashBase, rule_class) -> bool:\n \"\"\"\n Determines whether a WASH object is an instance of a specific WASH class supported by the metamodel.\n \n Args:\n object_instance: The object to be checked.\n rule_class: The class to be used for checking.\n Returns:\n True if object_instance is an instance of rule_class, otherwise False.\n \"\"\"\n return textx_isinstance(object_instance, self.__metamodel[rule_class])\n\n def __extract_document_location(self, open_statement):\n \"\"\"\n Extracts the location value of the document that should be used for execution,\n and returns it in a format acceptable by the WebDriver class.\n \n Args:\n open_statement: Statement from the parsed model that contains location value for opening a HTML file.\n \"\"\"\n if self.__is(open_statement, OpenURLStatement.__name__):\n return open_statement.url\n elif self.__is(open_statement, OpenFileStatement.__name__):\n return 'file:///' + open_statement.file_path\n elif self.__is(open_statement, OpenStringStatement.__name__):\n return 'data:text/html;charset=utf-8,' + open_statement.html\n else:\n raise WashError(f'Unexpected object \"{open_statement}\" of type \"{type(open_statement)}\"')\n \n def __execute_internal(self, webdriver_instance: WebDriver) -> ExecutionResult:\n \"\"\"\n Runs the actual execution of the current WASH script and returns an ExecutionResult instance.\n\n Args:\n webdriver_instance(WebDriver): WebDriver instance to be used for script execution.\n \"\"\"\n for expression in self.__model.expressions:\n if self.__is(expression, DynamicExpression.__name__):\n expression.execute(execution_context=webdriver_instance)\n elif self.__is(expression, StaticExpression.__name__):\n root_context = self.__prepare_context(execution_context=webdriver_instance, queries=expression.queries)\n\n context_expression = expression.context_expression if expression.context_expression \\\n else expression.context_expression_ref.context_expression\n\n result = self.__execute_context_expression(context=root_context, context_expression=context_expression)\n self.__model.execution_result.add_attributes(**{expression.result_key: result})\n else:\n raise WashError(f'Unsupported expression type: {expression.__class__}')\n\n return self.__model.execution_result\n\n def __execute_context_expression(self, context: list[WebElement],\n context_expression: ContextExpression, parent=None) -> ExecutionResult:\n \"\"\"\n Recursively executes the given context_expression using the given context.\n\n A context represents the current part(s) of the document (i.e. DOM tree) that is/are used for execution.\n In other words, contexts represent the execution result of the queries in the parent context.\n The root context is always the document that is currently being processed.\n \"\"\"\n execution_result = []\n for context_item in context: # Each web element in current context\n context_item_execution_result = ExecutionResult(parent=parent)\n for expression in context_expression.expressions: # Each expression to be executed on\n expression_result = None\n if expression.context_expression:\n sub_context = self.__prepare_context(execution_context=context_item, queries=expression.queries)\n expression_result = self.__execute_context_expression(sub_context, expression.context_expression,\n parent=execution_result)\n else:\n for query in expression.queries:\n if expression_result:\n expression_result = query.execute(execution_context=expression_result)\n else:\n expression_result = query.execute(execution_context=context_item)\n\n context_item_execution_result.add_attributes(**{expression.result_key: expression_result})\n execution_result.append(context_item_execution_result)\n\n return execution_result[0] if len(execution_result) == 1 else execution_result\n\n @staticmethod\n def __prepare_context(execution_context: [WebElement or WebDriver], queries: list[Query]) -> list[WebElement]:\n \"\"\"\n Executes a list of queries against a given execution_context and returns the result\n in form of a list of WebElement instances which represent a new context.\n\n A context represents the current part(s) of the document (i.e. DOM tree) that is/are used for execution.\n In other words, contexts represent the execution result of the queries in the parent context.\n The root context is always the document that is currently being processed.\n \"\"\"\n\n query_result = None\n for query in queries:\n query_result = query.execute(execution_context=execution_context) \\\n if not query_result else query.execute(execution_context=query_result)\n\n return query_result\n\n\nclass ChromeExecutor(WashExecutor):\n \"\"\"\n WASH script executor that uses Chrome browser.\n \"\"\"\n def __init__(self, browser_options, **kwargs):\n super(ChromeExecutor, self).__init__(**kwargs)\n self.__chrome_options = browser_options\n\n def _start_webdriver_instance(self, url: str):\n if not self._options.chrome_webdriver_path:\n raise WashError('Current WASH configuration uses Chrome WebDriver,'\n ' but the path was not specified in options.')\n elif not os.path.exists(self._options.chrome_webdriver_path):\n raise FileNotFoundError('Unable to find Chrome WebDriver on specified path: \"{}\"'\n .format(self._options.chrome_webdriver_path))\n\n webdriver_instance = webdriver.Chrome(options=self.__chrome_options,\n executable_path=self._options.chrome_webdriver_path)\n webdriver_instance.implicitly_wait(time_to_wait=self._time_to_wait)\n webdriver_instance.get(url)\n\n return webdriver_instance\n\n\nclass FirefoxExecutor(WashExecutor):\n \"\"\"\n WASH script executor that uses Firefox browser.\n \"\"\"\n def __init__(self, browser_options, **kwargs):\n super(FirefoxExecutor, self).__init__(**kwargs)\n self.__firefox_options = browser_options\n\n def _start_webdriver_instance(self, url: str):\n if not self._options.firefox_webdriver_path:\n raise WashError('Current WASH configuration uses Firefox WebDriver,'\n ' but the path was not specified in options.')\n elif not os.path.exists(self._options.firefox_webdriver_path):\n raise FileNotFoundError('Unable to find Firefox WebDriver on specified path: \"{}\"'\n .format(self._options.firefox_webdriver_path))\n\n webdriver_instance = webdriver.Firefox(options=self.__firefox_options,\n executable_path=self._options.firefox_webdriver_path)\n webdriver_instance.implicitly_wait(time_to_wait=self._time_to_wait)\n webdriver_instance.get(url)\n\n return webdriver_instance\n\n\nclass EdgeExecutor(WashExecutor):\n \"\"\"\n WASH script executor that uses Edge browser.\n \"\"\"\n def __init__(self, browser_options, **kwargs):\n super(EdgeExecutor, self).__init__(**kwargs)\n self.__edge_options = browser_options\n\n def _start_webdriver_instance(self, url: str):\n\n # TODO (fivkovic): Use additional library to set options\n # https://stackoverflow.com/questions/65171183/how-to-run-microsoft-edge-headless-with-selenium-python\n\n if not self._options.edge_webdriver_path:\n raise WashError('Current WASH configuration uses Edge WebDriver,'\n ' but the path was not specified in options.')\n elif not os.path.exists(self._options.edge_webdriver_path):\n raise FileNotFoundError('Unable to find Edge WebDriver on specified path: \"{}\"'\n .format(self._options.edge_webdriver_path))\n\n webdriver_instance = webdriver.Edge(executable_path=self._options.edge_webdriver_path)\n webdriver_instance.implicitly_wait(time_to_wait=self._time_to_wait)\n webdriver_instance.get(url)\n\n return webdriver_instance\n\n\nclass OperaExecutor(WashExecutor):\n \"\"\"\n WASH script executor that uses Opera browser.\n \"\"\"\n def __init__(self, browser_options, **kwargs):\n super(OperaExecutor, self).__init__(**kwargs)\n self.__opera_options = browser_options\n\n def _start_webdriver_instance(self, url: str):\n if not self._options.opera_webdriver_path:\n raise WashError('Current WASH configuration uses Opera WebDriver,'\n ' but the path was not specified in options.')\n elif not os.path.exists(self._options.opera_webdriver_path):\n raise FileNotFoundError('Unable to find Opera WebDriver on specified path: \"{}\"'\n .format(self._options.opera_webdriver_path))\n\n webdriver_instance = webdriver.Opera(options=self.__opera_options,\n executable_path=self._options.opera_webdriver_path)\n webdriver_instance.implicitly_wait(time_to_wait=self._time_to_wait)\n webdriver_instance.get(url)\n\n return webdriver_instance\n\n\nclass SafariExecutor(WashExecutor):\n \"\"\"\n WASH script executor that uses Safari browser.\n \"\"\"\n def __init__(self, browser_options, **kwargs):\n super(SafariExecutor, self).__init__(**kwargs)\n self.__safari_options = browser_options\n\n def _start_webdriver_instance(self, url: str):\n\n # TODO (fivkovic): Safari still does not support headless mode in 2021. Disable support for now.\n # Reference: https://github.com/SeleniumHQ/selenium/issues/5985\n\n if not self._options.safari_webdriver_path:\n raise WashError('Current WASH configuration uses Safari WebDriver,'\n ' but the path was not specified in options.')\n elif not os.path.exists(self._options.safari_webdriver_path):\n raise FileNotFoundError('Unable to find Safari WebDriver on specified path: \"{}\"'\n .format(self._options.safari_webdriver_path))\n\n webdriver_instance = webdriver.Safari(executable_path=self._options.safari_webdriver_path)\n webdriver_instance.implicitly_wait(time_to_wait=self._time_to_wait)\n webdriver_instance.get(url)\n\n return webdriver_instance\n","sub_path":"wash_lang_prototype/core/executor.py","file_name":"executor.py","file_ext":"py","file_size_in_byte":14648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"361017219","text":"from flask import Flask\nimport json\nimport plotly\nimport pandas as pd\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.tokenize import word_tokenize\nimport joblib\nfrom joblib import load\nfrom flask import render_template, request, jsonify\nfrom plotly.graph_objs import Bar\nimport pickle\n\napplication = Flask(__name__)\n\ndef tokenize(text):\n tokens = word_tokenize(text)\n lemmatizer = WordNetLemmatizer()\n\n clean_tokens = []\n for tok in tokens:\n clean_tok = lemmatizer.lemmatize(tok).lower().strip()\n clean_tokens.append(clean_tok)\n\n return clean_tokens\n\n# load data\ndf = pd.read_csv('data/messages_response.csv')\n\n# load model\nmodel = joblib.load(\"models/classifier.joblib\")\n\n#with open(\"models/classifier.pkl\", 'rb') as pickleFile:\n # model = pickle.load(pickleFile)\n@application.route('/')\n@application.route('/index')\ndef index():\n # extract data needed for visuals\n genre_counts = df.groupby('genre').count()['message']\n genre_names = list(genre_counts.index)\n categories = df[df.columns[4:]]\n category_counts = (categories.mean() * categories.shape[0]).sort_values(ascending=False)\n category_names = list(category_counts.index)\n\n # render web page with plotly graphs\n return render_template('master.html')\n\n\n# web page that handles user query and displays model results\n@application.route('/go')\ndef go():\n # save user input in query\n query = request.args.get('query', '')\n\n # use model to predict classification for query\n classification_labels = model.predict([query])[0]\n classification_results = dict(zip(df.columns[4:], classification_labels))\n\n # This will render the go.html Please see that file.\n return render_template(\n 'go.html',\n query=query,\n classification_result=classification_results\n )\n\nif __name__ == '__main__':\n application.run()","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":1854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"14643913","text":"from numpy import sin, cos, pi, arange\r\nfrom numpy.random import randint\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\n\r\nfs = 1e6\r\nTs = 1/fs\r\nt_end = 50e-3\r\n\r\nt = arange(0,t_end-Ts,Ts)\r\n\r\nf1 = 1.8e3\r\nf2 = 1.9e3\r\nf3 = 2e3\r\nf4 = 1.85e3\r\nf5 = 1.87e3\r\nf6 = 1.94e3\r\nf7 = 1.92e3\r\n\r\ninfo_signal = 2.5*cos(2*pi*f1*t) + 1.75*cos(2*pi*f2*t) + 2*cos(2*pi*f3*t) + 2*cos(2*pi*f4*t) + 1*cos(2*pi*f5*t) + 1*cos(2*pi*f6*t) + 1.5*cos(2*pi*f7*t)\r\n\r\nN = 25\r\nmy_sum = 0\r\n\r\nfor i in range(N+1):\r\n noise_amp = 0.075*randint(-10,10,size=(1,1))\r\n noise_freq = randint(-1e6,1e6,size=(1,1))\r\n noise_signal = my_sum + noise_amp * cos(2*pi*noise_freq*t)\r\n my_sum = noise_signal\r\n\r\nf6 = 50e3 #50kHz\r\nf7 = 49.9e3\r\nf8 = 51e3\r\n\r\npwr_supply_noise = 1.5*sin(2*pi*f6*t) + 1.25*sin(2*pi*f7*t) + 1*sin(2*pi*f8*t)\r\n\r\nf9 = 60\r\n\r\nlow_freq_noise = 1.5*sin(2*pi*f9*t)\r\n\r\ntotal_signal = info_signal + noise_signal + pwr_supply_noise + low_freq_noise\r\ntotal_signal = total_signal.reshape(total_signal.size)\r\n\r\n# plt.figure(figsize=(12,8))\r\n# plt.subplot(3,1,1)\r\n# plt.plot(t,info_signal)\r\n# plt.grid(True)\r\n# plt.subplot(3,1,2)\r\n# plt.plot(t,info_signal+pwr_supply_noise)\r\n# plt.grid(True)\r\n# plt.subplot(3,1,3)\r\n# plt.plot(t,total_signal)\r\n# plt.grid(True)\r\n# plt.show()\r\n\r\ndf = pd.DataFrame({'0':t,\r\n '1':total_signal})\r\n\r\ndf.to_csv('NoisySignal.csv')\r\n\r\n\r\n#################################################\r\n\r\n\r\n\r\n","sub_path":"final.py","file_name":"final.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"55540016","text":"# 011 Equality Comparisons\r\nprint(2 < 3)\r\nprint(21 < 3)\r\nprint(7 * 3 < 21)\r\nprint(7 * 3 == 21)\r\n\r\n\r\n# 012 If Statement\r\n# Define a procedure, bigger, that takes in two numbers as inputs, and returns the greater of the two inputs.\r\ndef bigger(a, b):\r\n if a > b:\r\n r = a\r\n else:\r\n r = b\r\n return r\r\n\r\n\r\nprint(bigger(2, 7))\r\nprint(bigger(3, 1))\r\nprint(bigger(6, 6))\r\n\r\n\r\n# 013 Is Friend\r\n# Define a procedure, is_friend, that takes a string as its input,\r\n# and returns a Boolean indicating if the input string is the name of a friend.\r\n# Assume I am friends with everyone whose name starts with E and no one else.\r\n# You do not need to check for the lower case 'e'.\r\ndef is_friend(name):\r\n if name[0] == 'E':\r\n return True\r\n else:\r\n return False\r\n\r\n\r\nprint(is_friend('Erin'))\r\nprint(is_friend('Irene'))\r\n\r\n\r\n# 014 More Friend\r\n# Define a procedure, more_friend, that takes a string as its input,\r\n# and returns a Boolean indicating if the input string is the name of a friend.\r\n# Assume I am friends with everyone whose name starts with either 'J' or 'S', but no one else.\r\n# You do not need to check for lower case 'J' or 's'\r\ndef more_friend(name):\r\n if name[0] == 'J':\r\n return True\r\n if name[0] == 'S':\r\n return True\r\n else:\r\n return False\r\n\r\n\r\nprint(more_friend('July'))\r\nprint(more_friend('Summer'))\r\nprint(more_friend('Bank_of_America'))\r\n\r\n\r\n# 015 Biggest\r\n# Define a procedure, biggest, that takes three numbers as inputs and returns the largest of those three numbers.\r\ndef biggest(a, b, c):\r\n if a > b:\r\n if a > c:\r\n return a\r\n else:\r\n return c\r\n else:\r\n if b > c:\r\n return b\r\n else:\r\n return c\r\n\r\n\r\nprint(biggest(1, 3, 5))\r\nprint(biggest(2, 4, 6))\r\nprint(biggest(300, 200, 100))\r\nprint(biggest(40, 60, 50))\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"Practice#0011-0015.py","file_name":"Practice#0011-0015.py","file_ext":"py","file_size_in_byte":1889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"614275448","text":"#!/usr/bin/env python3\n\"\"\"\nCompute inter-editor volume differences for aseg and aparc labels\n\nRequirements:\nStrict edited subject naming convention: -\nExamples :\n sub-CC0016_core1-MikeT\n sub-CC0016_core1-DoritK\n sub-CC0006_core2-MikeT\n\nAuthors\n----\nMike Tyszka, Caltech Brain Imaging Center\n\nMIT License\n\nCopyright (c) 2020 Mike Tyszka\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\n\nimport os\nimport sys\nimport argparse\nimport shutil\nimport numpy as np\nimport pandas as pd\nfrom datetime import datetime as dt\n\nfrom nibabel.freesurfer.io import (read_geometry, write_morph_data)\nfrom scipy.spatial.distance import directed_hausdorff\nfrom sklearn.metrics import pairwise_distances_argmin_min\n\nimport multiprocessing as mp\nimport psutil\n\nfrom glob import glob\n\n\ndef main():\n\n # Parse command line arguments\n parser = argparse.ArgumentParser(description='Compute inter-editor label volume differences')\n parser.add_argument('-sd', '--subjdir', required=True, help='Freesurfer edited subjects directory')\n parser.add_argument('-o', '--outdir', required=True, help='Output directory')\n\n # Parse command line arguments\n args = parser.parse_args()\n\n if args.subjdir:\n subjects_dir = args.subjdir\n else:\n subjects_dir = os.getenv('SUBJECTS_DIR')\n\n # Create output directory\n if not os.path.isdir(args.outdir):\n os.makedirs(args.outdir, exist_ok=True)\n\n # Parse subject directory listing for unique subjects and editors\n subjects, editors = parse_subj_dirs(subjects_dir)\n n_editors = len(editors)\n\n # Hemisphere and surface names\n hemis = ['lh', 'rh']\n surfnames = ['pial', 'white']\n\n # Multiprocessing setup\n n_cpu = psutil.cpu_count(logical=False)\n print('Creating pool of {} processes'.format(n_cpu))\n pool = mp.Pool(n_cpu)\n\n compare_args = []\n for subject in subjects:\n for hemi in hemis:\n for surfname in surfnames:\n\n # Upper triangle loop for editor pairs\n for ic in range(0, n_editors-1):\n for jc in range(ic+1, n_editors):\n\n editor1 = editors[ic]\n editor2 = editors[jc]\n\n compare_args.append((subjects_dir, args.outdir, subject, editor1, editor2, hemi, surfname))\n\n # Submit jobs\n # result : list of [subject, editor1, editor2, hemi, surfname, d12, d21, dsym] for each job\n result = pool.starmap(compare_editors, compare_args)\n\n # Close pool for additional jobs and wait for completion\n pool.close()\n pool.join()\n\n # Save results list\n results_csv = os.path.join(args.outdir, 'Hausdorff_Distances.csv')\n print('Saving Hausdorff Distances to {}'.format(results_csv))\n df = pd.DataFrame(result, columns=['Subject', 'Editor1', 'Editor2', 'Hemisphere', 'Surface', 'D12', 'D21', 'DSYM'])\n df.to_csv(results_csv, sep=',', index=False)\n\n print('Done')\n\ndef parse_subj_dirs(subjects_dir):\n\n print('Scanning {} for subjects and editors'.format(subjects_dir))\n\n # Get list of sub-* subdirectories of FS subjects directory\n dir_list = glob(os.path.join(subjects_dir, 'sub-CC*'))\n\n # Init running subject ID and editor name lists\n subject_list = []\n editor_list = []\n\n # Get full list of subject IDs and editor names with duplication\n for dname in dir_list:\n\n base_dname = os.path.basename(dname)\n\n # Split directory name at last '-'\n subject, editor = base_dname.rsplit('-', 1)\n\n subject_list.append(subject)\n editor_list.append(editor)\n\n # Boil down to unique subjects and editors\n subjects = np.unique(subject_list)\n editors = np.unique(editor_list)\n\n return subjects, editors\n\n\ndef compare_editors(subjects_dir, outdir, subject, editor1, editor2):\n\n subj_dir1 = os.path.join(subjects_dir, '{}-{}'.format(subject, editor1))\n subj_dir2 = os.path.join(subjects_dir, '{}-{}'.format(subject, editor2))\n\n # asge, lh and rh aparc label volumes and cortical thicknesses\n aseg_fname = os.path.join('stats', 'aseg.stats')\n aparc_lh_fname = os.path.join('stats', 'lh.aparc.a2009s.stats')\n aparc_rh_fname = os.path.join('stats', 'rh.aparc.a2009s.stats')\n\n # Editor specific stats files\n aseg_editor1_fname = os.path.join(subj_dir1, aseg_fname)\n aseg_editor2_fname = os.path.join(subj_dir2, aseg_fname)\n aparc_lh_editor1_fname = os.path.join(subj_dir1, aparc_lh_fname)\n aparc_rh_editor1_fname = os.path.join(subj_dir1, aparc_rh_fname)\n aparc_lh_editor2_fname = os.path.join(subj_dir2, aparc_lh_fname)\n aparc_rh_editor2_fname = os.path.join(subj_dir2, aparc_rh_fname)\n\n # Init continuation flag\n keep_going = True\n coords1 = np.zeros([1,])\n coords2 = np.zeros([1,])\n\n if not os.path.isfile(surf1_fname):\n print('* Subject 1 surface file {} does not exist - exiting'.format(surf1_fname))\n keep_going = False\n\n if not os.path.isfile(surf2_fname):\n print('* Subject 2 surface file {} does not exist - exiting'.format(surf2_fname))\n keep_going = False\n\n # Load surfaces\n try:\n coords1, faces1 = read_geometry(surf1_fname)\n except IOError:\n print('* Problem loading surface from {}'.format(surf1_fname))\n keep_going = False\n\n try:\n coords2, faces2 = read_geometry(surf2_fname)\n except IOError:\n print('* Problem loading surface from {}'.format(surf2_fname))\n keep_going = False\n\n if keep_going:\n\n print('{}-{}-{}-{} mesh has {} points'.format(subject, editor1, hemi, surfname, coords1.shape[0]))\n print('{}-{}-{}-{} mesh has {} points'.format(subject, editor2, hemi, surfname, coords2.shape[0]))\n\n # Fast pairwise Euclidean distances between nodes of surface 1 and 2\n # If coords1 is N x 3 and coords2 is M x 3, distmin is N x M\n print('Computing pairwise distances ({} to {})'.format(editor1, editor2))\n t0 = dt.now()\n _, dmin12 = pairwise_distances_argmin_min(coords1, coords2)\n delta = dt.now() - t0\n print('Done in {:0.3f} seconds'.format(delta.total_seconds()))\n\n # Calculate forward Hausdorff distance from pairwise distance results\n d12 = np.max(dmin12)\n\n # Fast Hausdorff distances between nodes of surface 1 and 2\n print('Computing Fast Hausdorff Distances')\n t0 = dt.now()\n d21, _, _ = directed_hausdorff(coords2, coords1)\n delta = dt.now() - t0\n print('Done in {:0.3f} seconds'.format(delta.total_seconds()))\n\n # Symmetric Hausdorff distance (max(d12, d21))\n dsym = max(d12, d21)\n\n print('Forward Hausdorff Distance : {:0.3f} mm'.format(d12))\n print('Reverse Hausdorff Distance : {:0.3f} mm'.format(d21))\n print('Symmetric Hausdorff Distance : {:0.3f} mm'.format(dsym))\n\n # Save closest distances as a morphometry/curv file\n dist_fname = os.path.join(outdir, '{}-{}-{}-{}-{}.dist'.format(subject, editor1, editor2, hemi, surfname))\n print('Saving intersurface distances to {}'.format(dist_fname))\n write_morph_data(dist_fname, dmin12)\n\n # Copy subject 1 surface to output directory for use with distance annotation in Freeview\n surf1_bname = os.path.basename(surf1_fname)\n surf1_outname = '{}-{}-{}'.format(subject, editor1, surf1_bname)\n print('Copying {} to {}'.format(surf1_bname, surf1_outname))\n shutil.copy(surf1_fname, os.path.join(outdir, surf1_outname))\n\n return subject, editor1, editor2, hemi, surfname, d12, d21, dsym\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"fs_inter_editor_volumes.py","file_name":"fs_inter_editor_volumes.py","file_ext":"py","file_size_in_byte":8574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"273809747","text":"\n\n#calss header\nclass _APPREHEND():\n\tdef __init__(self,): \n\t\tself.name = \"APPREHEND\"\n\t\tself.definitions = [u'to catch and arrest someone who has not obeyed the law: ', u'to understand something']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_apprehend.py","file_name":"_apprehend.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"152189226","text":"# Given an array, find the contiguous subarray with the largest sum. \n# In the array below, the largest sum subarray starts at index 3 and \n# ends at 6, and with the largest sum being 12.\n# [-4,2,-5,1,2,3,6,-5,1]\n\n# localMax[i] = max (A[i], A[i] + local_max[i-1])\n\ndef find_max_sum_sub_array(A):\n if len(A) < 1:\n return 0\n\n curr_max = A[0]\n global_max = A[0]\n lengthA = len(A)\n for i in range(1, lengthA):\n if curr_max < 0:\n curr_max = A[i]\n else:\n curr_max += A[i]\n\n if global_max < curr_max:\n global_max = curr_max\n\n return global_max\n\ndef kadane(arr):\n if len(arr) < 1:\n return 0\n \n currMax = arr[0]\n globalMax = arr[0]\n lengthA = len(arr)\n\n for i in range(1, lengthA):\n if currMax < 0:\n currMax = arr[i]\n else:\n currMax += arr[i]\n \n if globalMax < currMax:\n globalMax = currMax\n \n return globalMax\n\ndef find_max_sum_sub_array_2(A):\n \n if len(A) < 1:\n return 0\n \n result = []\n currentSum = A[0]\n globalSum = A[0]\n lengthArray = len(A)\n\n for i in range(1, lengthArray):\n if currentSum < 0:\n result.clear()\n result.append(A[i])\n currentSum = A[i]\n else: \n currentSum += A[i]\n \n if globalSum < currentSum:\n result.append(A[i])\n globalSum = currentSum\n \n print (result)\n return globalSum\n\ndef max_subarray(array):\n max_so_far = array[0]\n max_now = array[0]\n for i in range(1, len(array)):\n max_now = max(array[i], max_now + array[i])\n max_so_far = max(max_so_far, max_now)\n return max_so_far\n\n\ndef max_subarray2(arr):\n current_max = arr[0]\n global_max = arr[0]\n for i in range(1, len(arr)):\n current_max = max(arr[i], current_max + arr[i])\n global_max = max(current_max, global_max)\n return global_max\n\n\n# v = [-4,2,-5,1,2,3,6,-5,1]\nv = [5,-4,-2]\nsum0 = find_max_sum_sub_array(v)\nsum1 = kadane(v)\nsum2 = find_max_sum_sub_array_2(v)\nsum3 = max_subarray(v)\nsum4 = max_subarray2(v)\nprint(\"Sum of largest subarray: \" + str(sum0))\nprint(\"Sum of largest subarray: \" + str(sum1))\nprint(\"Sum of largest subarray: \" + str(sum2))\nprint(\"Sum of largest subarray: \" + str(sum3))\nprint(\"Sum of largest subarray: \" + str(sum4))","sub_path":"Leetcode/dp/largest_subarray.py","file_name":"largest_subarray.py","file_ext":"py","file_size_in_byte":2180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"616132181","text":"import pandas as pd\nimport numpy as np\nimport pprint\nimport copy\nfrom function import helper\nfrom function.data_processing_analysis import preprocessing_constrctur_feature_vectors\nfrom statistics import mean \nfrom scipy.stats import entropy\n\nfrom sklearn.preprocessing import OneHotEncoder,MaxAbsScaler\nfrom sklearn.metrics.pairwise import cosine_similarity, cosine_distances\n\npp = pprint.PrettyPrinter(indent=4)\n\ndef calculate_dissimilarity_between_two_sets_of_vectors (user_listened_songs_vectors, crit_item_vectors):\n all_pairs_dissimilarity_list = cosine_distances(user_listened_songs_vectors, crit_item_vectors)\n mean_dissimilarity_between_two_sets = np.ravel(all_pairs_dissimilarity_list).mean()\n return mean_dissimilarity_between_two_sets\n\n\ndef calculate_dissimilarity_between_two_sets(user_listened_songs_info_df, crit_item_info_df,combined_songs_info_df, categorical_attributes, numerical_attributes):\n # Step 1: Preprocessing -> construct feature vectors\n user_listened_songs_vectors, crit_item_vectors = preprocessing_constrctur_feature_vectors(user_listened_songs_info_df, crit_item_info_df,combined_songs_info_df, categorical_attributes, numerical_attributes)\n\n # Step 2: Dissimilarity Calculation\n dissimilarity_between_two_sets = calculate_dissimilarity_between_two_sets_of_vectors (user_listened_songs_vectors, crit_item_vectors)\n\n return dissimilarity_between_two_sets\n\ndef entropy_for_one_attribute(attribute_df):\n attribute_value_prob = attribute_df.value_counts(normalize=True).to_dict()\n entropy_attribute_value = entropy(list(attribute_value_prob.values()))\n return entropy_attribute_value\n\ndef calculate_entropy_for_set(combined_songs_info_df, categorical_attributes, numerical_attributes):\n songs_info_df = copy.deepcopy(combined_songs_info_df)\n # Step 1: Preprocessing -> discretization for numerical data\n for attribute in numerical_attributes:\n attribute_intervalindex, interval_label = helper.get_numerical_attribute_intervalindex(attribute)\n songs_info_df[attribute] = pd.cut(songs_info_df[attribute], attribute_intervalindex,right=False, labels = interval_label)\n\n # Step 2: Calculate the entropy\n entropy_dict = {}\n for attribute in categorical_attributes:\n entropy_dict[attribute] = entropy_for_one_attribute(songs_info_df[attribute])\n\n for attribute in numerical_attributes:\n entropy_dict[attribute] = entropy_for_one_attribute(songs_info_df[attribute])\n \n # pp.pprint(entropy_dict)\n entropy_set = sum(entropy_dict.values())\n\n return entropy_set\ndef calculate_unexpectedness_based_on_user_listened_songs(user_listened_songs_vectors, crit_item_vectors):\n\n all_pairs_dissimilarity_list = cosine_distances(crit_item_vectors, user_listened_songs_vectors)\n unexpectedness_hausdorff_distance_list = []\n for one_item_dissimilarity_list in all_pairs_dissimilarity_list:\n unexpectedness_hausdorff_distance_list.append(min(one_item_dissimilarity_list))\n \n set_unexpectedness_hausdorff_distance = mean(unexpectedness_hausdorff_distance_list)\n\n return set_unexpectedness_hausdorff_distance\n\ndef calculate_unexpectedness_for_set(user_listened_songs_info_df, crit_item_info_df,combined_songs_info_df, categorical_attributes, numerical_attributes):\n # Step 1: Preprocessing -> construct feature vectors\n user_listened_songs_vectors, crit_item_vectors = preprocessing_constrctur_feature_vectors(user_listened_songs_info_df, crit_item_info_df,combined_songs_info_df, categorical_attributes, numerical_attributes)\n \n # Step 2: Unexpectedness Calculation\n unexpectedness_for_set = calculate_unexpectedness_based_on_user_listened_songs (user_listened_songs_vectors, crit_item_vectors)\n\n return unexpectedness_for_set","sub_path":"backend/function/diversity_calculation.py","file_name":"diversity_calculation.py","file_ext":"py","file_size_in_byte":3767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"288986572","text":"# -*- coding: utf-8 -*-\nimport json\n\nimport scrapy\nfrom bs4 import BeautifulSoup\nfrom scrapy.http import Request\nfrom datetime import datetime\nfrom lianjia_spider.items import LianjiaSpiderItem\nimport requests\nimport re\n\n\nclass LianjiaSpider(scrapy.Spider):\n name = \"lianjia\"\n allowed_domains = [\"sh.lianjia.com\"]\n start_urls = ['http://sh.lianjia.com/']\n\n def start_requests(self):\n yield Request('http://sh.lianjia.com/zufang/')\n\n def parse(self, response): # 接收start_requests传来的response\n max_page = 3183 # 最多3183页\n bashurl = str(response.url) # 就是http://sh.lianjia.com/zufang/\n for page_num in range(1500, 2500):\n url = bashurl + 'd' + str(page_num)\n print('=====正在抓第' + str(page_num) + '页===========')\n yield Request(url, callback=self.get_house_url) # 请求每一页的数据,给get_name处理\n\n def get_house_url(self, response): # 把每一页中的房源信息的url提取出来\n a_tags = BeautifulSoup(response.text, 'lxml').find_all('a', {'name': 'selectDetail', 'class': 'rent'})\n for a_tag in a_tags:\n each_house_href = a_tag['href'] # 源代码中是相对地址 /zufang/shz3750054.html\n each_house_url = 'http://sh.lianjia.com' + each_house_href # 需要把前缀http://sh.lianjia.com加上\n yield Request(each_house_url, callback=self.get_house_info)\n\n def get_house_info(self, response):\n house_id = BeautifulSoup(response.text, 'lxml').find('span', {'class': 'houseNum'}).get_text()[5:]\n title = BeautifulSoup(response.text, 'lxml').find('h1', {'class': 'main'}).get_text()\n scratch_time = datetime.now()\n address = BeautifulSoup(response.text, 'lxml').find_all('p', {'class': 'addrEllipsis'})[1]['title']\n room_type = BeautifulSoup(response.text, 'lxml').find('div', {'class': 'room'}).get_text().strip()\n area = BeautifulSoup(response.text, 'lxml').find('div', {'class': 'area'}).get_text().strip()\n floor = BeautifulSoup(response.text, 'lxml').find('table', {'class': 'aroundInfo'}).find('tr').find_all('td')[1].get_text()\n direction = BeautifulSoup(response.text, 'lxml').find('table', {'class': 'aroundInfo'}).find('tr').find_all('td')[3].get_text().strip()\n district = BeautifulSoup(response.text, 'lxml').find('table', {'class': 'aroundInfo'}).find_all('tr')[1].find_all('td')[1].get_text()\n shelf_time = BeautifulSoup(response.text, 'lxml').find('table', {'class': 'aroundInfo'}).find_all('tr')[1].find_all('td')[3].get_text()\n community = BeautifulSoup(response.text, 'lxml').find_all('p', {'class': 'addrEllipsis'})[0]['title']\n rental = BeautifulSoup(response.text, 'lxml').find('div', {'class': 'price'}).find('div').get_text()[:-3]\n # 看房记录\n seen_record = None\n seen_record_raw = BeautifulSoup(response.text, 'lxml').find('div', {'class': 'panel'})\n if seen_record_raw:\n seen_record = seen_record_raw.find_all('div')[2].find('span').get_text()\n tel = BeautifulSoup(response.text, 'lxml').find_all('div', {'class': 'phone'})[0].get_text().strip().replace('\\n', '').replace(' ','')\n # 爬图片链接 ↓\n img_url = None\n img_url_raw = BeautifulSoup(response.text, 'lxml').find('div', {'id': 'album-view-wrap'})\n if img_url_raw:\n img_url_tags = img_url_raw.find_all('img')\n img_url = {item['img-title']: item['data-large'] for item in img_url_tags}\n # 爬户型分间 ↓\n json_url = 'http://sh.lianjia.com/api/house/getCells.json?houseId=' + house_id[3:] + '&type=zufang'\n details_json = requests.get(json_url).json() # 请求户型分间json数据\n details_list = details_json.get('cellInfoList')\n details = None\n if details_list:\n details = {item['name']: item['area'] for item in details_list} # 取出name和area字段\n # 爬地铁距离,用手机端网页获取↓\n mobile_url = response.url.replace('http://', 'http://m.') # 换成手机��地址\n subway_station = None\n distance = None\n subway_info = BeautifulSoup(requests.get(mobile_url).text, 'lxml').find('p', {'class': 'd-value'})\n if subway_info:\n subway_info = subway_info.get_text()\n subway = subway_info.split('站')\n distance = subway[1][:-1]\n subway_station = subway[0][2:] + '站'\n # 小区信息页面中爬建造时间和挂牌均价 ↓\n community_href = BeautifulSoup(response.text, 'lxml').find_all('p', {'class': 'addrEllipsis'})[0].find('a')['href']\n community_url = 'http://sh.lianjia.com' + community_href\n built_year = BeautifulSoup(requests.get(community_url).text, 'lxml').find_all('span', {'class': 'other'})[1].get_text().strip()[:-1]\n housing_price_test = BeautifulSoup(requests.get(community_url).text, 'lxml').find('span', {'class': 'p'})\n housing_price = None\n if housing_price_test:\n housing_price = housing_price_test.get_text().strip()\n\n # print('【标 题】' + title)\n # print('【房源编号】' + house_id)\n # print('【地 址】' + address)\n # print('【户 型】' + room_type)\n # print('【面 积】' + area)\n # print('【楼 层】' + floor)\n # print('【朝 向】' + direction)\n # print('【区 域】' + district)\n # print('【上架时间】' + shelf_time)\n # print('【小 区】' + community)\n # print('【地 铁 站】' + subway_station)\n # print('【距离地铁】' + distance)\n # print('【租 金】' + rental + ' 元/每月')\n # print('【看房记录】' + seen_record)\n # print('【户型分间】' + str(details))\n # print('【图片链接】' + str(img_url))\n # print('【挂牌均价】' + str(housing_price))\n # print('【建造年份】' + built_year)\n # print('【联系电话】' + tel)\n # print('【采集时间】' + str(scratch_time))\n\n item = LianjiaSpiderItem()\n item['house_id'] = house_id\n item['title'] = title\n item['address'] = address\n item['room_type'] = room_type\n item['area'] = area\n item['floor'] = floor\n item['direction'] = direction\n item['district'] = district\n item['shelf_time'] = shelf_time\n item['community'] = community\n item['subway_station'] = subway_station\n item['distance'] = distance\n item['rental'] = rental\n item['seen_record'] = seen_record\n item['details'] = str(details)\n item['img_url'] = str(img_url)\n item['housing_price'] = housing_price\n item['built_year'] = built_year\n item['tel'] = tel.replace('\\t', '')\n item['scratch_time'] = scratch_time\n print(item)\n return item\n\n\n","sub_path":"lianjia_spider/spiders/lianjia.py","file_name":"lianjia.py","file_ext":"py","file_size_in_byte":6998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"200196755","text":"class Skaut_Cipher:\n def __init__(self, text: str, direction: str=\"E\") -> None:\n \"\"\"\n direction: E -> for encryption - default\n direction: D -> for decryption\n \"\"\"\n self.direction = direction\n self.input_text = text.upper() if self.direction == \"E\" else \"\"\n self.text_encrypted = text.upper() if self.direction == \"D\" else \"\"\n self.text_decrypted = \"\"\n self.cipher_types = (\"GP\", \"MC\")\n self.cipher_type = None\n self.cipher_ok = False\n self.codes_enc_gp = (\"G\", \"D\", \"R\", \"P\", \"L\", \"K\")\n self.codes_dec_gp = (\"A\", \"E\", \"Y\", \"O\", \"U\", \"I\")\n self.codes_enc_mc = (\"M\", \"T\", \"L\", \"C\", \"D\", \"K\")\n self.codes_dec_mc = (\"O\", \"Y\", \"E\", \"U\", \"A\", \"I\")\n\n def change_letters(self, text: str, codes_in: tuple, codes_out: tuple)-> str:\n returned_text = \"\"\n for letter in text:\n if letter in codes_in:\n pos = codes_in.index(letter)\n letter = codes_out[pos]\n elif letter in codes_out:\n pos = codes_out.index(letter)\n letter = codes_in[pos]\n returned_text += letter\n return returned_text\n\n\n def encrypt(self, cipher: str) -> bool:\n self.cipher_type = cipher\n self.cipher_ok = self.cipher_type in self.cipher_types\n if not self.cipher_ok:\n return False\n if self.direction != \"E\":\n return False\n if self.cipher_type == \"GP\":\n self.text_encrypted = self.change_letters(self.input_text, self.codes_enc_gp, self.codes_dec_gp)\n elif self.cipher_type == \"MC\":\n self.text_encrypted = self.change_letters(self.input_text, self.codes_enc_mc, self.codes_dec_mc)\n return True\n\n def decrypt(self, cipher: str) -> bool:\n self.cipher_type = cipher\n self.cipher_ok = self.cipher_type in self.cipher_types\n if not self.cipher_ok:\n return False\n if self.direction != \"D\":\n return False\n if self.cipher_type == \"GP\":\n self.text_decrypted = self.change_letters(self.text_encrypted, self.codes_dec_gp, self.codes_enc_gp)\n elif self.cipher_type == \"MC\":\n self.text_decrypted = self.change_letters(self.text_encrypted, self.codes_dec_mc, self.codes_enc_mc)\n return True\n\n\n def output(self) -> None:\n print(f\"Input: {self.input_text}\")\n print(f\"Encrypted: {self.text_encrypted}\")\n print(f\"Decrypted: {self.text_decrypted}\")\n\n def return_encrypted(self) -> str:\n return self.text_encrypted\n\n def return_decrypted(self) -> str:\n return self.text_decrypted\n\n\n# przykładowe wywołanie:\n#\nt1 = Skaut_Cipher(\"G D R P L K - A B C\")\nt1.encrypt(\"GP\")\nt1.output()\nt1.decrypt(\"GP\")\nt1.output()\nprint(f\"Encrypted text: {t1.return_encrypted()}\")\nprint(f\"Decrypted text: {t1.return_decrypted()}\")\nprint(\"--------------------------------------------\")\nt2 = Skaut_Cipher(\"A E Y O U I - G B C\", \"D\")\nt2.encrypt(\"GP\")\nt2.output()\nt2.decrypt(\"GP\")\nt2.output()\nprint(f\"Encrypted text: {t2.return_encrypted()}\")\nprint(f\"Decrypted text: {t2.return_decrypted()}\")\n\n\n#\n# Input: G D R P L K - A B C\n# Encrypted: A E Y O U I - G B C\n# Decrypted:\n# Input: G D R P L K - A B C\n# Encrypted: A E Y O U I - G B C\n# Decrypted:\n# Encrypted text: A E Y O U I - G B C\n# Decrypted text:\n# --------------------------------------------\n# Input:\n# Encrypted: A E Y O U I - G B C\n# Decrypted:\n# Input:\n# Encrypted: A E Y O U I - G B C\n# Decrypted: G D R P L K - A B C\n# Encrypted text: A E Y O U I - G B C\n# Decrypted text: G D R P L K - A B C\n","sub_path":"SPP/Modul_05/przestawieniowe.py","file_name":"przestawieniowe.py","file_ext":"py","file_size_in_byte":3626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"206309687","text":"import argparse\nimport os\nimport sys\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n\ndef get_chrome_caps(browser_args):\n chrome_options = Options()\n if browser_args:\n for arg in browser_args:\n chrome_options.add_argument(\"--\" + arg)\n return chrome_options.to_capabilities()\n \ndef get_firefox_caps(profile_dir):\n raise NotYetImplemented()\n\nparser = argparse.ArgumentParser(description='RWD client for single URL measurements')\n\nparser.add_argument('--server-url', required=True)\nparser.add_argument('--test-url', required=True)\nparser.add_argument('--browser', choices=['chrome', 'firefox', 'ie'], required=True)\nparser.add_argument('--screenshot', default='screenshot.png')\nparser.add_argument('--firefox-profile-dir')\nparser.add_argument('browser_args', nargs='*')\n\nargs = parser.parse_args()\n\nbrowser = args.browser.lower()\n\ndesired_capabilities = None\nif browser == \"chrome\":\n desired_capabilities = get_chrome_caps(args.browser_args)\nelif browser == \"firefox\":\n desired_capabilities = get_firefox_caps(args.firefox_profile_dir)\nelse:\n raise UnSupportedBrowser(browser);\n\ndesired_capabilities['name'] = 'Single URL snapshot: %s' % args.test_url\ndesired_capabilities['lockStep'] = \"true\"\n\nprint(\"Connecting to RWD server: \" + args.server_url)\ndriver = webdriver.Remote(desired_capabilities=desired_capabilities,\n command_executor=args.server_url)\n\ndriver.implicitly_wait(10)\n\nprint(\"Requesting URL: \" + args.test_url)\ndriver.get(args.test_url)\n\nprint(\"Done.\")\ndriver.quit()\n","sub_path":"singleurl.py","file_name":"singleurl.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"549063325","text":"import featdataprocess.FeatdataProcess as fp\nimport rawdataprocess.MySQL_helper as mh # 数据库帮助类库\nimport numpy as np\nfrom numpy import linalg as la\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\nimport os\nfrom datetime import datetime,timedelta\n\n#排列组合#----------------------------------------------------------- \ndef stationID_select(list_stationID):\n n = len(list_stationID)\n l = []\n for i in range(n):\n for j in range(i+1,n):\n l.append(list_stationID[i])\n l.append(list_stationID[j])\n return l\n\ndef choose_2_stationID(all_choices):\n n = len(all_choices)-1\n l = []\n for i in range(0,n,2):\n l.append(all_choices[i:i+2])\n return l \n#--------------------------------------------------------------------\n\n#数据获取#----------------------------------------------------------- \ndef AETA_data(StationID_1): \n \n data1 = eq.get_final_data(stationID = StationID_1 , signalType='finaldata_lowfreq_magn',\n featureType_list=['average'], time_range=time_range)\n \n #台站名----------------------------------------------------------\n a = eq.get_station()\n title1 = a[a['StationID']==StationID_1]['Title'].values.tolist()\n title1.append(StationID_1)\n \n# title_list=[str(title1[1])+title1[0]+' & '+str(title2[1])+title2[0],str(title2[1])+title2[0]+' & '+str(title3[1])+title3[0],str(title3[1])+title3[0]+' & '+str(title1[1])+title1[0]]\n #-------------------------------------------------------------------- \n \n #初始化FeatdataProcessorNew类:\n data_1 = fp.FeatdataProcessorNew(data=data1, time_range=time_range, interval=600)\n #注意:如果不需要对数据作图,仅仅是处理数据,可以不提供stationID\n \n #数据绘图\n #test.plot(is_eq=True, auto_scale=True)\n \n ##查看数据描述\n# data_1.describe()\n \n# data_1.plot()\n \n # 因为这个时间段的数据包括2种采样频率,所以我们先对数据进行统一降采样\n data_1 = data_1.down_sampling(interval=600)\n \n #数据补全\n compensate_data_1 = data_1.compensate(interval=None, bias=300)\n \n #降采样\n down_sample_data_1 = compensate_data_1.down_sampling(interval=3600, method='mean') # 以均值方式每1小时采样1个点\n \n# down_sample_data_1.plot()\n# down_sample_data_2.plot()\n \n# ###dataframe改成list ####必做-------------------(‘data_station_’必有)\n# data_station1 = list(down_sample_data_1.data['average'].values)\n\n# #操作一:选取数据的时间段\n## selected_data1 = compensate_data.select_range_data(hour_range=['00:00','04:00']) # 选择每天0点到4点的数据\n# selected_data1 = down_sample_data_1.select_range_data(hour_range=['00:00','04:00'])\n\n# #dataframe改成list\n# data_station1 = list(selected_data1.data['average'].values)\n\n \n# 操作二:归一化 (method='z-score')\n norm_data_1 = down_sample_data_1.scaling(method='z-score')\n# #dataframe改成list\n data_station1 = list(norm_data_1.data['average'].values) \n# norm_data_1.plot()\n \n time_start = list(down_sample_data_1.data['Timestamp'].values)\n \n return data_station1,title1,time_start\n \n#--------------------------------------------------------------------\n\n#LOCO#----------------------------------------------------------- \ndef LocoScore_XY(data_station1,data_station2,months):\n \n w = 24 #每天24个数,那这个窗口就是7x24=168\n N = int(720*months-1*(w-1)) #去掉首(或尾),总共得到的Locoscore数量\n \n# Beta = 0.9\n\n X = data_station1\n Y = data_station2\n #先做x,矩阵的协方差是矩阵的各个向量间的协方差。cij = cov(xi,xj)得到一个数\n LocoScore_XY=[]\n Cwx = np.arange(576,dtype='float64').reshape(24,24)\n Cwy = np.arange(576,dtype='float64').reshape(24,24)\n for n in range(N):\n \n for i in range(w): \n \n Cwx[:,i] = X[i+n:i+w+n]\n \n ACX = np.cov(Cwx)\n \n Ux,sigma,VT = la.svd(ACX)\n Ux_new = Ux[:,[0,1,2,3]]\n \n vector_Ux = Ux_new[:,0]\n \n for i in range(w):\n Cwy[:,i] = Y[i+n:i+w+n]\n ACY = np.cov(Cwy)\n \n Uy,sigma,VT = la.svd(ACY)\n Uy_new = Uy[:,[0,1,2,3]]\n \n vector_Uy = Uy_new[:,0]\n \n vector_proj1 = np.dot(Ux_new.T,vector_Uy) #最大特征值的特征向量uy 在UXnew特征空间上投影产生 投影向量1\n cos1 = np.linalg.norm(vector_proj1)/np.linalg.norm(vector_Uy) # 余弦值,norm函数可以轻松求出一个向量的模。\n \n vector_proj2 = np.dot(Uy_new.T,vector_Ux) #最大特征值的特征向量uy 在UXnew特征空间上投影产生 投影向量1\n cos2 = np.linalg.norm(vector_proj2)/np.linalg.norm(vector_Ux) # 余弦值,norm函数可以轻松求出一个向量的模。\n \n LocoScore_XY.append((cos1+cos2)/2)\n \n return LocoScore_XY \n\n# 取主特征向量时候,一般取前4个 即可。\n#\n# [U S V]=svd(c) 即可做奇异值分解,好简单\n# 最后一步 得到向量在矩阵空间上的投影 求其大小除以原来向量,即可得到余弦值。\n# 例如 U=[1,2,3,4; 4,5,6,7] v=[1,2,3,4]' U_new=U*v 得到一个向量;\n# 计算这个向量的大小除以原来向量v的大小5.47 即可得到余弦值。\n\n\n\ndef pic_plot(LocoScore,StationID_1,StationID_2,months):\n eq_list_Time = eq_list['Timestamp'].values.tolist()\n eq_list_Magnitude = eq_list['Magnitude'].values.tolist()\n xlist=eq_list_Time\n ylist_min=[]\n for i in range(len(eq_list_Magnitude)):\n ylist_min.append(1-0.5/8*eq_list_Magnitude[i])\n ylist_max=[1]*len(ylist_min)\n\n #画图#----------------------------------------------------------\n time_start = AETA_data(StationID_1)[2]\n# time_start = list(selected_data1.data['Timestamp'].values)\n \n plot_start=int(time_start[25])\n plot_end=int(time_start[int(720*months)])\n \n xlist=list(range(plot_start,plot_end,3600))\n xlist.insert(0,xlist[0]-3600)\n xlist.append(xlist[-1]+3600)\n# print(xlist)\n plt.ylim(0,1.1)\n ytl=np.arange(0,1.1,0.5)\n plt.yticks(ytl,ytl)\n xtick_list=list(range(plot_start,plot_end,86400))\n xtick_list.append(xtick_list[-1]+86400)\n \n xname_list=[datetime.strftime(datetime.fromtimestamp(i),'%d') for i in xtick_list]\n\n\n plt.plot(xlist,LocoScore)\n plt.xticks(xtick_list,xname_list,rotation=0)\n plt.rcParams['font.sans-serif']=['SimHei'] #windows汉字显示\n plt.rcParams['axes.unicode_minus']=False\n plt.title('LCT('+str(StationID_1)+AETA_data(StationID_1)[1][0]+' & '+str(StationID_2)+AETA_data(StationID_2)[1][0]+')')\n plt.vlines(eq_list_Time,ylist_min,ylist_max,color='red')\n\n #--------------------------------------------------------------------\n\n\nif __name__==\"__main__\":\n eq = mh.EqMySql()\n# time_range = ['2017-07-14', '2018-10-13']\n months = 1\n \n# time_end='2017-8-10'\n# time_end='2017-8-13'\n time_end='2019-7-21'\n# time_end='2019-4-20'\n# time_end='2018-6-26' #第一组\n# time_end='2018-10-22' #第二组\n t2=datetime.strptime(time_end,'%Y-%m-%d')\n t1=t2-timedelta(days=30*months)\n time_range=[datetime.strftime(item,format='%Y-%m-%d') for item in [t1,t2]]\n \n# list_stationID = [90,121,129,43,75,105,38,93,125]\n# list_stationID = [43,90,121,129,116]\n# list_stationID = [75,246,240,38,129,121,122,131]\n# list_stationID = [122,43,48,38,116,240,121,246] #4.18台湾6.7级\n# list_stationID = [121,116,150,129] #第一组\n# list_stationID = [38,240,75,48] #第二组\n# list_stationID = [75,246,240,38,129,121,122,131]\n list_stationID = [129,90,43,116,121,240]\n# list_stationID = [131,75,122,121,246,129,38,48,240] ###近期四川2019.03.14\n# stations_title_list = [AETA_data(i)[1][0] for i in list_stationID]\n eq_list = eq.get_earthquake(time_range= time_range, distance_range=(75, 129, 22, 40), min_mag=4.5, update=True) #(73, 135, 13, 54) (97, 109, 26, 35)\n# eq_list = eq.get_earthquake(time_range= time_range, distance_range=(73, 145, -53, 54), min_mag=5, update=True) #(73, 135, 13, 54) (97, 109, 26, 35)\n stations_amount = len(list_stationID)\n stations_title = [str(list_stationID[i])+str(AETA_data(list_stationID[i])[1][0]) for i in range(stations_amount)]\n \n \n all_choices = stationID_select(list_stationID)\n every_two_stations_choices = choose_2_stationID(all_choices)\n plt.figure()\n plt.suptitle(time_range[0]+'至'+time_range[1])\n for i in range(0,len(every_two_stations_choices)):\n StationID_1 = every_two_stations_choices[i][0]\n StationID_2 = every_two_stations_choices[i][1] \n# print(StationID_1)\n# print(StationID_2) \n\n LocoScore = LocoScore_XY(AETA_data(StationID_1)[0],AETA_data(StationID_2)[0],months)\n plt.subplots_adjust(left=None,bottom=0.2,right=None,top=0.86,wspace=None,hspace=2) \n fig=plt.gcf()\n fig.set_size_inches(9*months,len(every_two_stations_choices)+2)\n plt.subplot(len(every_two_stations_choices),1,i+1) \n pic_plot(LocoScore,StationID_1,StationID_2,months)\n plt.show() \n \n path = 'Only LCT'+time_range[0]+'至'+time_range[1]\n if not os.path.isdir(path):\n os.mkdir(path)\n fig.savefig(path+\"/\"+time_range[0]+'至'+time_range[1]+str(stations_title),dpi=200)\n\n# fig.savefig() \n print(\" \")\n print(eq_list) \n print(\" \")\n print(len(every_two_stations_choices))\n print(\" \")\n print('done!')\n# print(every_two_stations_choices)\n ","sub_path":"LCT.py","file_name":"LCT.py","file_ext":"py","file_size_in_byte":9662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"463851476","text":"import os\nimport csv\nimport pathlib\nimport re\nimport random\nimport requests\nfrom bs4 import BeautifulSoup\n\nspecial_words = [\"Mr\", \"Mrs\", \"St\", \"gs\", \"Dr\"]\nspecial_symbols = (\n \"[!\\\"#$%&'\\\\\\\\()*+,-./:;<=>?@[\\\\]^_`’‘{|}~「」〔〕“”〈〉『』【】&*・()$#@。、?!`+¥%]\"\n)\n\n# 特殊記号を抜く\ncode_regex = re.compile(special_symbols)\n\n# http://gutenberg.org/files/62606/62606-h/62606-h.htm\n\n# 問題文を作る\ndef create_questions(raw_data):\n word_data = set()\n sentences = []\n questions = []\n noa_miss_count = 0\n len_short_miss_count = 0\n len_long_miss_count = 0\n cap_miss_count = 0\n ans_miss_count = 0\n\n for p in raw_data:\n # 改行をなくす\n new_p = re.sub(r\"(? 1:\n if new_p[0] == '\"':\n new_p = new_p[1:]\n if new_p[-1] == '\"':\n new_p = new_p[:-1]\n\n # 一文辺り取り出す\n sentence = \"\"\n quote_count = 0\n for c in new_p:\n\n # 全角ダブルクオテーシ��ン対策\n if c == \"“\" or c == \"”\":\n c = '\"'\n\n sentence += c\n\n if c == '\"':\n quote_count += 1\n\n # 文の終わりの場合\n if c == \".\" or c == \"?\" or c == \"!\":\n flag = True\n # Mr, Mrsなどの単語のチェック\n for sw in special_words:\n if sw in sentence[-4:]:\n flag = False\n # 最後の文字が大文字、数字であるかのチェック\n if len(sentence) > 2:\n if len(re.findall(\"[A-Z0-9\\u2160-\\u217F_]\", sentence[-2])) > 0:\n flag = False\n if quote_count % 2 == 1:\n continue\n\n # いずれでもなければ文章の終わりと判定\n if flag:\n sentences.append(sentence)\n sentence = \"\"\n quote_count = 0\n\n for s in sentences:\n words = []\n word = \"\"\n\n # 最初の空白を削除\n s = s.lstrip()\n\n # 最初の[\" ]を削除\n if len(s) > 1:\n if s[0] == '\"' and s[1] == \" \":\n s = s[2:]\n\n # 最初の文字が大文字でなければ削除\n if len(s) > 0:\n if len(re.findall('[A-Z\"]', s[0])) != 1:\n cap_miss_count += 1\n continue\n\n # 単語を取り出す\n for c in s:\n if len(re.findall(special_symbols, c)) > 0:\n continue\n if c == \" \":\n words.append(word)\n word = \"\"\n elif c == \".\":\n if word in special_words:\n word += c\n elif len(word) > 0:\n if len(re.findall(\"[A-Z0-9\\u2160-\\u217F_]\", word[-1])) > 0:\n word += c\n else:\n words.append(word)\n word = \"\"\n else:\n words.append(word)\n word = \"\"\n else:\n word += c\n\n # 短すぎる問題と長すぎる問題は削除\n if len(words) <= 3:\n len_short_miss_count += 1\n continue\n if len(words) > 50:\n len_long_miss_count += 1\n continue\n\n # 答えを決める\n answer_count = 0\n while True:\n answer_index = random.randint(1, len(words) - 1)\n answer = words[answer_index]\n\n answer_count += 1\n if (\n len(re.findall(special_symbols, answer)) == 0\n and any(c.isdigit() for c in answer) == False\n and answer.islower()\n ):\n break\n if answer_count > 50:\n noa_miss_count += 1\n break\n if answer_count > 50:\n continue\n\n # 答えを抜き出す (don'tなどに対応できていない)\n new_sentence = s.replace(\" \" + answer + \" \", \" * \", 1)\n\n if new_sentence.count(\"*\") == 0:\n new_sentence = new_sentence.replace(\" \" + answer + \",\", \" *,\", 1)\n\n if new_sentence.count(\"*\") == 0:\n new_sentence = new_sentence.replace(\" \" + answer + \".\", \" *.\", 1)\n\n if new_sentence.count(\"*\") == 0:\n new_sentence = new_sentence.replace(\" \" + answer + \";\", \" *;\", 1)\n\n if new_sentence.count(\"*\") != 1:\n ans_miss_count += 1\n continue\n\n # カンマを抜き出す\n new_sentence = new_sentence.replace(\",\", \"_\")\n\n # 単語から特殊記号を抜き取る\n new_words = []\n for w in words:\n # 不要な記号を含んでいないか\n if len(re.findall(special_symbols, w)) > 0:\n continue\n\n # 大文字を含まないか\n if w.islower() == False:\n continue\n\n # 数値を含まないか\n if any(c.isdigit() for c in w):\n continue\n\n # 適切な言葉であれば選択肢に追加する\n new_words.append(code_regex.sub(\"\", w))\n\n answer = code_regex.sub(\"\", answer)\n\n questions.append([new_sentence, answer])\n word_data |= set(new_words)\n\n data_size = len(word_data)\n data_list = list(word_data)\n\n # 選択肢追加\n for q in questions:\n choices = []\n for i in range(3):\n while True:\n choice = data_list[random.randint(0, data_size - 1)]\n\n # 被りがないかをチェック\n flag = True\n for j in range(1, i + 1):\n if questions[j] == choice:\n flag = False\n\n # チェックを通過すれば採用\n if flag:\n choices.append(choice)\n break\n q += choices\n\n print(f\"noa: {noa_miss_count}\")\n print(f\"len_short: {len_short_miss_count}\")\n print(f\"len_long: {len_long_miss_count}\")\n print(f\"cap: {cap_miss_count}\")\n print(f\"ans: {ans_miss_count}\")\n return questions\n\n\nurl = input(\"URLを入力: \")\nwhile True:\n file_name = input(\"ファイル名を入力: \")\n file_name += \".csv\"\n path = os.path.join(os.getcwd(), \"csv\", file_name)\n\n if os.path.exists(path) == False:\n break\n else:\n print(\"入力したファイル名はすでに存在しています。他のファイル名を入力してください。\")\n\n# レスポンス取得\nprint(\"URLのサイトにアクセスしています...\")\nresponse = requests.get(url)\n\nif response.status_code != 200:\n print(\n f\"\"\"レスポンスを正常に取得できませんでした。\n処理を終了します。\nurl: {url}\nstatus code: {response.status_code}\"\"\"\n )\n exit()\n\nprint(\"正常にレスポンスを取得しました。\")\n\n# ファイル作成\ncsv_file = pathlib.Path(path)\ncsv_file.touch()\nprint(\"ファイルが作成されました。\")\n\n# BeautifulSoupの設定\nprint(\"データをフォーマットしています。\")\nsoup = BeautifulSoup(response.content, \"html.parser\")\n[x.extract() for x in soup.findAll(\"span\")]\n[x.extract() for x in soup.findAll(\"a\")]\n\nraw_data = soup.find_all(\"p\", class_=\"\")\n\n# HTMLタグを削除する\nraw_data = [x.text for x in raw_data]\n\nprint(\"問題を作成しています\")\nquestions = create_questions(raw_data)\n\nwith open(path, \"w\") as f:\n writer = csv.writer(f, quoting=csv.QUOTE_NONE, escapechar=\"\\\\\")\n writer.writerows(questions)\n\nprint(\n f\"\"\"問題を作成しました。\n作成したファイルの場所: {path}\n問題数: {len(questions)}\"\"\"\n)\n\nfor q in questions:\n if len(q) != 5:\n print(f\"エラーの文章: {q}\")\n","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":7951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"375353204","text":"from dash.dependencies import Input, Output\nimport dash_design_kit as ddk\nimport dash_html_components as html\nimport dash_core_components as dcc\nfrom app import app\nimport plotly.express as px\n\ndf = px.data.iris() # sample dataset\n\nlayout = html.Div([\n\n ddk.Block(\n width=30,\n children=ddk.ControlCard(\n width=100,\n children=[\n ddk.ControlItem(\n label='Species',\n children=dcc.Dropdown(\n id='species',\n options=[\n {'label': i, 'value': i}\n for i in df['species_id'].unique()\n ],\n value=df['species_id'].unique()[0]\n )\n ),\n ]\n\n )\n ),\n\n ddk.Block(\n width=70,\n children=[\n ddk.Card(\n width=100,\n children=ddk.Graph(id='splom', style={'height': '800px'})\n ),\n ddk.Card(\n width=50,\n children=ddk.Graph(id='scatter')\n ),\n ddk.Card(\n width=50,\n children=ddk.Graph(id='density')\n ),\n ]\n )\n\n])\n\n\n\n@app.callback(\n [Output('splom', 'figure'), Output('scatter', 'figure'), Output('density', 'figure')],\n [Input('species', 'value')])\ndef update_graph(value):\n dff = df[df['species_id'] == value]\n splom = px.scatter_matrix(\n df,\n dimensions=[\"sepal_width\", \"sepal_length\", \"petal_width\", \"petal_length\"]\n )\n\n scatter = px.scatter(\n dff, x=\"sepal_width\", y=\"sepal_length\",\n marginal_y=\"violin\", marginal_x=\"violin\")\n\n density = px.density_contour(dff, x=\"sepal_width\", y=\"sepal_length\")\n\n return [splom, scatter, density]\n","sub_path":"dash-app/pages/home.py","file_name":"home.py","file_ext":"py","file_size_in_byte":1837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"464866428","text":"import cv2\nimport numpy\n\n\nif __name__ == '__main__':\n image = cv2.imread(\"2019-07-01-08-38-45-789.bmp\")\n image = cv2.resize(image, None, fx=0.25, fy=0.25)\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n ret1, th1 = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU) # 方法选择为THRESH_OTSU\n cv2.imshow('', th1)\n cv2.waitKey()\n cv2.imwrite('threshhold_ostu.jpg', th1)\n\n","sub_path":"cv_py/threshhold_ostu.py","file_name":"threshhold_ostu.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"606792772","text":"def solution(H):\n stack = []\n block_count = 0 # The number of needing blocks\n\n for height in H:\n while len(stack) != 0 and height < stack[-1]:\n # If the height of current block is less than\n # the previous ones, the previous ones have\n # to end before current point. They have no\n # chance to exist in the remaining part.\n # So the previous blocks are completely finished.\n stack.pop()\n block_count += 1\n\n if len(stack) == 0 or height > stack[-1]:\n # If the height of current block is greater than\n # the previous one, a new block is needed for\n # current position.\n stack.append(height)\n\n # Else (the height of current block is same as that\n # of previous one), they should be combined to\n # one block.\n\n # Some blocks with different heights are still in the stack.\n block_count += len(stack)\n\n return block_count","sub_path":"codility/stone_wall.py","file_name":"stone_wall.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"400524841","text":"class StatusCode(int):\n def __str__(self):\n if has_code(self):\n return __code_to_message[self]\n else:\n return str(unknown_error)\n\ndef has_code(code):\n return code in _code_to_message\n\nsuccess = StatusCode(200)\nunknown_error = StatusCode(501)\ninternal_error = StatusCode(502)\nparam_missing = StatusCode(408)\nparam_illegal = StatusCode(409)\ninvalid_data = StatusCode(410)\nbiz_error = StatusCode(503)\n\n_code_to_message = {\n success: 'success',\n internal_error: 'internal_error',\n param_missing: 'param_missing',\n param_illegal: 'param_illegal',\n unknown_error: 'unknown_error',\n biz_error: 'biz_error',\n invalid_data: 'invalid_data',\n}","sub_path":"utils/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"632500920","text":"class Test(object):\n @classmethod\n def solution1(cls, s: str) -> str:\n res = s[0] if s else s\n dict = {}\n for index, value in enumerate(s):\n if value in dict:\n dict[value].append(index)\n for val in dict[value]:\n aim = s[val: index + 1]\n reAim = aim[::-1]\n if aim == reAim and len(aim) >= len(res):\n res = aim\n break\n dict.setdefault(value, [index])\n return res\n\n @classmethod\n def solution2(cls, s: str) -> str:\n if not s:\n return \"\"\n lon, res = 0, 0\n for i in range(len(s)):\n for j in range(i, len(s)):\n if s[i:j + 1] == s[i:j + 1][::-1]:\n if len(s[i:j + 1]) >= lon:\n lon = len(s[i:j + 1])\n res = s[i:j + 1]\n return res\n\n @classmethod\n def solution3(cls, s: str) -> str:\n def judgeStr(x):\n return x == x[::-1]\n\n dict = {}\n flag, res = 0, 0\n l, r, left, right = 0, 0, 0, 0\n for index, value in enumerate(s):\n if value in dict:\n dict[value].append(index)\n for i, v in enumerate(dict[value]):\n for j in range(i, len(dict[value])):\n if judgeStr(s[dict[value][i]:dict[value][j] + 1]):\n l, r = dict[value][i], dict[value][j]\n if (r - l) >= res:\n res = r - l\n left, right = l, r\n dict.setdefault(value, [index])\n return s[left:right + 1]\n\n @classmethod\n def solution4(cls, s: str) -> str:\n res = s[0] if s else s\n dict = {}\n for index, value in enumerate(s):\n if value in dict:\n dict[value].append(index)\n print('111',value,dict[value])\n for val in dict[value]:\n string = s[val: index + 1]\n reString = string[::-1]\n if string == reString and len(string) >= len(res):\n print(string, val, index + 1)\n res = string\n break\n dict.setdefault(value, [index])\n print(dict)\n return res\n\ntestSet = {\"str\":\"adacada\", \"res\":\"adacada\"}\n\nif __name__ == \"__main__\":\n # res = \"babadada\"\n # res = \"adacada\"\n # res = 'a'\n res = 'ac'\n print(Test.solution1(res))\n","sub_path":"leetcode/4-最长回文子串.py","file_name":"4-最长回文子串.py","file_ext":"py","file_size_in_byte":2584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"104527627","text":"from collections import defaultdict\ndef kosaraju(V,g):\n def end_time(graph, u, stack, visited):\n visited.add(u)\n # print(graph[15])\n for v in g[u]:\n if v not in visited:\n end_time(graph, v, stack, visited)\n stack.append(u)\n\n def dfs_util(graph, u, visited):\n visited.add(u)\n print(graph)\n for v in g[u]:\n print(u, g[u])\n if v not in visited:\n dfs_util(graph, v, visited)\n \n \n def reverse_graph():\n g_prime = defaultdict(list)\n for u, v_s in g.items():\n for v in v_s:\n g_prime[v].append(u)\n return g_prime\n \n visited = set()\n stack = []\n l = list(g.keys()).copy()\n for item in l:\n # print(len(g))\n if item not in visited:\n end_time(g, item, stack, visited)\n \n g_prime = reverse_graph()\n visited = set()\n result = 0\n print(stack, g_prime)\n while stack:\n item = stack.pop()\n print(item, visited)\n if item not in visited:\n dfs_util(g_prime, item, visited)\n result += 1\n print (\"here\", result)\n return result\n \nd = defaultdict(list)\nd[0] = [-1]\nd[1] = [0]\nd[2] = [3]\nd[-1] = [1,2]\nkosaraju(5, d)","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"492650438","text":"import pytest\n\nfrom .scans import DeltaScan, PING_SWEEP\n\n\ndef test_create_delta_scan(dbsession, fake_wan_scanners, fake_wan_routers):\n scanner_a, scanner_b, *_ = (scanner.name for scanner in fake_wan_scanners)\n scan = DeltaScan.create(\n session=dbsession, parameters=PING_SWEEP,\n scanner_names=(scanner_a, scanner_b,), targets=('10.1.0.1',))\n subscan_targets = {\n target.target\n for subscan in scan.subscans\n for target in subscan.targets\n }\n assert subscan_targets == {'10.1.0.1/32'}\n\n\ndef test_create_delta_scan_errors_on_no_targets(dbsession, fake_wan_scanners):\n scanner_names = tuple(scanner.name for scanner in fake_wan_scanners)\n with pytest.raises(ValueError):\n DeltaScan.create(\n session=dbsession, parameters=PING_SWEEP,\n scanner_names=scanner_names, targets=())\n","sub_path":"wanmap/deltascan_test.py","file_name":"deltascan_test.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"364454660","text":"from collections import namedtuple\n\nif __name__ == \"__main__\":\n tup = tuple()\n tup1 = ('crack',)\n tup2 = tuple('crack') # interpreted as tuple of list (string)\n print(tup, tup1, tup2)\n record = namedtuple(\"Computer_Science\", \"name id score\")\n record1 = record('Bob', id=12345, score=56)\n print(record1)","sub_path":"Sequences/tuple_.py","file_name":"tuple_.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"538717777","text":"import queue\nimport timeit\nfrom collections import deque\nfrom time import sleep\nfrom concurrent.futures import ThreadPoolExecutor\n\n\nFIFO = queue.Queue()\nLIFO = queue.LifoQueue()\n\n# FIFO.task_done()\n\nPQ = queue.PriorityQueue()\nPQ.put((1, 'eat'))\n# PQ.join()\nPQ.get()\nPQ.task_done()\n\ng = deque()\ng.append(2)\ng.appendleft(3)\ng.pop()\ng.popleft()\ng.insert(2, 5)\ng.extend(range(1, 5))\nprint(g)\ng.rotate(2) # right\nprint(g)\ng.rotate(-3) # left\nprint(g)\n\nt = timeit.default_timer()\n\n\ndef func_1():\n print(\"func_1 executing\")\n sleep(2)\n print(\"func_1 Completed\")\n\n\nt1 = timeit.Timer(\"func_1()\", setup=\"from __main__ import func_1\")\nprint(t1)\ntimes = t1.repeat(repeat=2, number=1)\n# \"repeat\" to determine how many times we want to time our code\n# \"number\" to determine how many times we want to run these tests.\nprint(times)\n\n\nclass Timer:\n\n def __init__(self, verbose=False):\n self.verbose = verbose\n self.timer = timeit.default_timer\n\n def __enter__(self):\n self.start = self.timer()\n return self\n\n def __exit__(self, *args):\n end = self.timer()\n self.elapsed_sec = end - self.start\n self.elapsed = self.elapsed_sec * 1000 # milliseconds\n if self.verbose:\n print(f\"elapsed time {self.elapsed_sec}\")\n\n\nwith Timer(verbose=True):\n func_1()\n\nexecutor = ThreadPoolExecutor(max_workers=2)\ntask1 = executor.submit(Timer)\n","sub_path":"Hacker/cmd_ref.py","file_name":"cmd_ref.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"518483288","text":"from decimal import getcontext\nimport math\n\nfrom coral.models import CoralSurveyEvent, CoralSpecies, CoralSurveyEventData\n\ngetcontext().prec = 20\n\ndef extract_lat(location):\n\n return str(location).split(\" \")[0]\n\ndef extract_long(location):\n\n return str(location).split(\" \")[1]\n\n\ndef get_csv(sites):\n \"\"\"\n get_csv queries all fish data for a provided sequence of sites.\n\n :param sites:\n :return: a list of lists\n \"\"\"\n\n # This is the required order for the column headers\n metadata = [u'Date', u'Unique Site ID', u'Local Name', u'Reef Type', u'Island',\n u'X', u'Y', u'Map Datum', u'Observer',\n u'Quadrat size', u'Max Quadrat Number', u'Quadrat Number', u'X', u'Y',\n u'Species', u'Family', u'Genus', u'Genus Growth Form', u'Geometric Diameter',\n u'Area', u'% Cover', u'Population Density',\n u'0 to 2', u'2 to 4', u'4 to 8', u'8 to 16', u'16 to 32', u'32 to 64', u'>64']\n\n surveys = CoralSurveyEvent.objects.filter(site__in=sites)\n\n # make a map of all species in memory for fast access\n species = CoralSpecies.objects.all()\n\n species_map = dict()\n\n for specie in species:\n species_map[specie.name.lower()] = specie\n\n survey_data = CoralSurveyEventData.objects.filter(surveyEvent__in=surveys)\n\n # accumulated values for report\n write_values = []\n\n # For each site:\n for site in sites:\n\n # for each survey in each site:\n for survey in surveys.filter(site__exact=site):\n\n # meta data values\n survey_meta = [survey.eventDate, site.site_id, site.local_name, site.reef_type.name, site.subRegion.name,\n extract_lat(survey.site.location), extract_long(survey.site.location), survey.site.map_datum, survey.observer,\n survey.quadrat_size, survey.max_replicate]\n\n data = survey_data.filter(surveyEvent__exact=survey).values()\n\n for a in [x['data'] for x in data]:\n # it seems like i should be able to do this in one line but...\n for d in a:\n quadrat_number = d['replicate']\n x = d['x']\n y = d['y']\n spec = d['species']\n species = species_map[spec.lower()]\n family = species.family.name\n genus = species.genus.name\n growth_form = species.genus.growth_from\n diameter = math.sqrt(x * y)\n # =PI()*((P5/2)^2)\n area = math.pi * pow(diameter / 2, 2)\n # =((Q5/H5)*(100/10000))\n perc_cover = (area / float(survey.max_replicate)) * (100.0 / 10000.0)\n population_density = 1 / (survey.quadrat_size * survey.max_replicate)\n lt2 = 1 if diameter < 2 else 0\n twotofour = 1 if 2 <= diameter < 4 else 0\n fourtoeight = 1 if 4 <= diameter < 8 else 0\n eighttosixteen = 1 if 8 <= diameter < 16 else 0\n sixteentothirtytwo = 1 if 16 <= diameter < 32 else 0\n thirtytwotosixtyfour = 1 if 32 <= diameter < 64 else 0\n gt64 = 1 if diameter >= 64 else 0\n\n coral_values = [quadrat_number, x, y, species, family, genus, growth_form, diameter, area,\n perc_cover,\n population_density, lt2, twotofour, fourtoeight, eighttosixteen, sixteentothirtytwo,\n thirtytwotosixtyfour, gt64]\n write_values.append(survey_meta + coral_values)\n\n return [metadata] + write_values\n","sub_path":"coral/excel.py","file_name":"excel.py","file_ext":"py","file_size_in_byte":3740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"382563323","text":"import sqlite3\n\nclass sqlite3manager():\n\n def __init__(self):\n self.conn = sqlite3.connect('database.sqlite3')\n self.c = self.conn.cursor()\n\n def db_create(self):\n query = \"\"\"\n CREATE TABLE IF NOT EXISTS ac_submission(\n id integer,\n problem_id integer,\n user_id string,\n language string\n )\n \"\"\"\n self.c.execute(query)\n self.conn.commit()\n query = \"\"\"\n CREATE TABLE IF NOT EXISTS resister_user(\n id integer,\n user_id string\n )\n \"\"\"\n self.c.execute(query)\n self.conn.commit()\n\n def db_manipulate(self, query, fetch=False, commit=False):\n self.c.execute(query)\n if fetch:\n res = self.c.fetchall()\n return res\n elif commit:\n self.conn.commit()\n\n","sub_path":"src/db_manager.py","file_name":"db_manager.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"235219983","text":"# Python program to explain os.pipe() method\n\n# importing os module\nimport os\n\n\n# Create a pipe\nr, w = os.pipe()\n\n# The returned file descriptor r and w\n# can be used for reading and\n# writing respectively.\n\n# We will create a child process\n# and using these file descriptor\n# the parent process will write\n# some text and child process will\n# read the text written by the parent process\n\n# Create a child process\npid = os.fork()\n\n# pid greater than 0 represents\n# the parent process\nif pid > 0:\n\n\t# This is the parent process\n\t# Closes file descriptor r\n\tos.close(r)\n\n\t# Write some text to file descriptor w\n\tprint(\"Parent process is writing\")\n\ttext = b\"Hello child process\"\n\tos.write(w, text)\n\tprint(\"Written text:\", text.decode())\n\n\t\nelse:\n\n\t# This is the parent process\n\t# Closes file descriptor w\n\tos.close(w)\n\n\t# Read the text written by parent process\n\tprint(\"\\nChild Process is reading\")\n\tr = os.fdopen(r)\n\tprint(\"Read text:\", r.read())\n\n","sub_path":"tutorial_orchestrator.py","file_name":"tutorial_orchestrator.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"483191464","text":"from django.contrib.auth import get_user_model\nfrom django.test import TestCase\n\nfrom posts.models import Group, Post\n\nUser = get_user_model()\n\n\nclass PostModelTest(TestCase):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n cls.author = User.objects.create_user(username=\"J.Tribbiani\")\n cls.group = Group.objects.create(title=\"Friends\")\n cls.post = Post.objects.create(\n text=\"Everybody needs Friends!\",\n author=cls.author,\n group=cls.group,\n )\n\n def test_verbose_name(self):\n post = PostModelTest.post\n group = PostModelTest.group\n fields = {\n post._meta.get_field(\"text\"): \"Текст\",\n group._meta.get_field(\"title\"): \"Группа\"\n }\n for field, expected in fields.items():\n with self.subTest(field=field):\n value = field.verbose_name\n self.assertEqual(value, expected)\n\n def test_help_text(self):\n post = PostModelTest.post\n group = PostModelTest.group\n fields = {\n post._meta.get_field(\"text\"): \"Введите текст вашего сообщения\",\n group._meta.get_field(\"title\"): \"Название группы\"\n }\n for field, expected in fields.items():\n with self.subTest(field=field):\n value = field.help_text\n self.assertEqual(value, expected)\n\n def test_object_name(self):\n post = PostModelTest.post\n group = PostModelTest.group\n fields = {\n post: post.text[:15],\n group: group.title\n }\n for expected, value in fields.items():\n with self.subTest(expected=str(expected)):\n self.assertEqual(value, str(expected))\n","sub_path":"posts/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":1806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"582184181","text":"import requests\n\n# In general, HTTP methods are used when dealing with API.\n# For example, 'GET' request corresponds to retreiving resource.\n# 'Post' request to creating new resource.\n# And to easily use that HTTP methods in Python, you can use a 'requests' library.\n\ndef main():\n # res just stands for response\n res = requests.get(\"https://google.com\")\n print(res, '\\n')\n print(res.status_code, '\\n')\n print(res.text, '\\n')\n\nif __name__ == \"__main__\":\n main()","sub_path":"code_examples/python/APIs/google.py","file_name":"google.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"210726399","text":"#!/usr/bin/env python\n\nimport time\nfrom datetime import datetime\nimport csv\nimport os, shutil, configparser\nimport statistics\n\nfrom Bird_Scale_Modbus import modbus_com as Mod_Com\n\ndesktop_file = \"/home/pi/Desktop/Bird_Scale_SCT20\"\nprogram_file = \"/home/pi/Pi_Repository/Programs/Bird_Scale/SCT20_V1-0/Wireless_Bird_Scale\"\n\ncurrdir = desktop_file + '/RAW_History'\nconfig_dir = desktop_file + '/Config'\nuser_config = config_dir + \"/user_scale_config.ini\"\navg_Weight_Store = desktop_file + \"/RAW_History/Bird_Scale_AVG.csv\"\nDay_Reset = 0\n\nif not os.path.isfile(desktop_file):\n os.makedirs(desktop_file, exist_ok=True)\nif not os.path.isfile(currdir):\n os.makedirs(currdir, exist_ok=True)\nif not os.path.isfile(config_dir):\n os.makedirs(config_dir, exist_ok=True)\n \nos.chdir(desktop_file)\n\nfile_AVG = open(avg_Weight_Store, \"a\")\nif os.stat(avg_Weight_Store).st_size == 0:\n file_AVG.write(\"Time,Rec Weight,Average Weight,Num Weights,STD Weight,Min Cutoff,Max Cutoff\\n\")\n file_AVG.flush()\n file_AVG.close()\n\n \n# Initialize Config File Management\nconfig = configparser.ConfigParser()\n\n## Create Config Data\nconfig.add_section('section')\nconfig['section']['Stable_Count'] = '0'\nconfig['section']['Avg_Weight'] = '0'\nconfig['section']['Last_Avg_Weight'] = '0'\nconfig['section']['AVG_Difference'] = '0'\nconfig['section']['Avg_Total'] = '0'\nconfig['section']['Scale_Offset'] = '-6.25'\nconfig['section']['Running_Total'] = '0'\nconfig['section']['Acceptable_Range'] = '30'\nconfig['section']['STD_Weight'] = '1.850'\nconfig['section']['Min_Cutoff'] = '0'\nconfig['section']['Max_Cutoff'] = '0'\nconfig['section']['Num_Weights'] = '0'\nconfig['section']['Running_AVG'] = '0'\nconfig['section']['Filter_Num'] = '10'\nconfig['section']['Stability'] = '0.01'\nconfig['section']['Record_Avg'] = '0'\nconfig['section']['Uniformity'] = '0'\nconfig['section']['Uniform_Percent'] = '10'\nconfig['section']['CV_Value'] = '0'\n\n# Store Current Directory\nos.chdir(config_dir)\n \n# Store Default Data and Create User Data If None\nwith open(\"default_scale_config.ini\", 'w') as f:\n config.write(f)\nif not os.path.isfile(user_config):\n os.makedirs(currdir, exist_ok=True)\n shutil.copyfile(\"default_scale_config.ini\", user_config)\n\n\ndef deleteContent(fName):\n with open(fName, \"w\"):\n pass\n\n \ndef coeffVar(X):\n try:\n return statistics.stdev(X)/statistics.mean(X)*100\n except ZeroDivisionError:\n raise StatsError('mean is zero')\n\n \n\ndef scale_weights(Day_Reset):\n \n\n desktop_file = \"/home/pi/Desktop/Bird_Scale_SCT20\"\n program_file = \"/home/pi/Pi_Repository/Programs/Bird_Scale/SCT20_V1.0/Wireless_Bird_Scale\"\n\n currdir = desktop_file + '/RAW_History'\n config_dir = desktop_file + '/Config'\n user_config = config_dir + \"/user_scale_config.ini\"\n avg_Weight_Store = desktop_file + \"/RAW_History/Bird_Scale_AVG.csv\"\n \n file_AVG = open(avg_Weight_Store, \"a\")\n if os.stat(avg_Weight_Store).st_size == 0:\n file_AVG.write(\"Time,Rec Weight,Average Weight,Num Weights,STD Weight,Min Cutoff,Max Cutoff,Uniformity,CV Value\\n\")\n file_AVG.flush()\n file_AVG.close()\n \n now = datetime.now()\n if Day_Reset == 1:\n Save_Today_File = currdir+'/'+str(now)+'.csv'\n shutil.copyfile(avg_Weight_Store, Save_Today_File)\n deleteContent(avg_Weight_Store)\n \n \n # Store Current Directory\n os.chdir(config_dir)\n\n # Initialize Config File Management\n config = configparser.ConfigParser()\n config.read(user_config)\n \n\n try:\n # Initialize/Reload Store Values\n Stable_Count = int(config.get('section','Stable_Count'))\n Avg_Weight = float(config.get('section','Avg_Weight'))\n Last_Avg_Weight = float(config.get('section','Last_Avg_Weight'))\n AVG_Difference = float(config.get('section','AVG_Difference'))\n Avg_Total = float(config.get('section','Avg_Total'))\n Scale_Offset = float(config.get('section','Scale_Offset'))\n Running_Total = float(config.get('section','Running_Total'))\n Acceptable_Range = int(config.get('section','Acceptable_Range'))\n STD_Weight = float(config.get('section','STD_Weight'))\n Min_Cutoff = float(config.get('section','Min_Cutoff'))\n Max_Cutoff = float(config.get('section','Max_Cutoff'))\n Num_Weights = int(config.get('section','Num_Weights'))\n Running_AVG = float(config.get('section','Running_AVG'))\n Filter_Num = int(config.get('section','Filter_Num'))\n Stability = float(config.get('section','Stability'))\n Record_Avg = float(config.get('section','Record_Avg'))\n Uniformity = float(config.get('section','Uniformity'))\n Uniform_Percent = float(config.get('section','Uniform_Percent'))\n CV_Value = float(config.get('section','CV_Value'))\n except:\n shutil.copyfile(\"default_scale_config.ini\", user_config)\n\n # Calculate Cutoff Weights\n Min_Cutoff = STD_Weight-(STD_Weight*Acceptable_Range/100)\n Max_Cutoff = STD_Weight+(STD_Weight*Acceptable_Range/100)\n\n # Get Scale Data\n Status,Data = Mod_Com()\n Data = Data+Scale_Offset\n\n # Check if Weight is Stable then Add to Average ELSE Reset Stable AVG\n if Stable_Count == 0:\n Avg_Weight = Data\n Avg_Total = 0\n if Data < (Avg_Weight+Stability) and Data > (Avg_Weight-Stability):\n Stable_Count = Stable_Count+1\n Avg_Total = Data+Avg_Total\n Avg_Weight = (Avg_Total+Data)/(Stable_Count+1)\n else:\n Stable_Count = 0\n Avg_Total = 0\n Avg_Weight = Data\n \n\n\n counter = 0\n counter2 = 0\n array_x = [0]*1000\n array_y = [0]*1000\n\n # Calculate Unifority\n unif_acc_low = Running_AVG-(Running_AVG*Uniform_Percent/100)\n unif_acc_high = Running_AVG+(Running_AVG*Uniform_Percent/100)\n uniform_count = 0\n i = 0\n \n # Capture Stable Weight and Reset Stable AVG/Count\n if Stable_Count >= Filter_Num:\n Stable_Count = 0\n Avg_Total = 0\n AVG_Difference = Last_Avg_Weight-Avg_Weight\n\n # If Weight in Range Store and calculate new average\n if AVG_Difference < 0:\n AVG_Difference = AVG_Difference*-1\n if AVG_Difference > Min_Cutoff and AVG_Difference < Max_Cutoff:\n Record_Avg = AVG_Difference\n Running_Total = Running_Total+Record_Avg\n Num_Weights = Num_Weights+1\n Running_AVG = Running_Total/Num_Weights \n now = datetime.now()\n file_AVG = open(avg_Weight_Store, \"a\")\n file_AVG.write(str(now)+\",\"+str(Record_Avg)+\",\"+str(Running_AVG)+\",\"+str(Num_Weights)+\",\"+str(STD_Weight)+\",\"+str(Min_Cutoff)+\",\"+str(Max_Cutoff)+\",\"+str(Uniformity)+\",\"+str(CV_Value)+\"\\n\")\n file_AVG.flush()\n file_AVG.close()\n # CV Calcualtion\n Unif_File = open(avg_Weight_Store, 'r')\n for row in csv.reader(Unif_File):\n if row[0] != 'Time' and row[0] != '0':\n counter = counter+1 \n Num_Weights = counter\n CV_Store = [0] * Num_Weights\n counter = 1\n Unif_File.close()\n # Graph Data Grab\n Unif_File = open(avg_Weight_Store, 'r') \n for row in csv.reader(Unif_File):\n if row[0] != 'Time' and row[0] != '0':\n recorded_avg = float(row[1])\n if counter < 1000:\n array_x[counter] = recorded_avg\n array_y[counter] = counter \n counter = counter+1\n if recorded_avg >= unif_acc_low and recorded_avg <= unif_acc_high:\n uniform_count = uniform_count+1\n CV_Store[i] = recorded_avg\n i = i+1\n Unif_File.close() \n # Uniformity Calculation\n if Num_Weights > 0:\n Uniformity = uniform_count/Num_Weights*100\n else:\n Uniformity = 0\n # Read CV Value\n if Num_Weights > 1:\n if CV_Store[0] != 0:\n CV_Value = coeffVar(CV_Store)\n\n\n \n Last_Avg_Weight = Avg_Weight\n\n\n # Day Reset Function\n if Day_Reset == 1:\n Running_AVG = 0\n Num_Weights = 0\n Record_Avg = 0\n Running_Total = 0\n Uniformity = 0\n CV_Value = 0\n \n # Store Values\n config['section']['Stable_Count'] = str(Stable_Count)\n config['section']['Avg_Weight'] = str(Avg_Weight)\n config['section']['Last_Avg_Weight'] = str(Last_Avg_Weight)\n config['section']['AVG_Difference'] = str(AVG_Difference)\n config['section']['Avg_Total'] = str(Avg_Total)\n config['section']['Scale_Offset'] = str(Scale_Offset)\n config['section']['Running_Total'] = str(Running_Total)\n config['section']['Acceptable_Range'] = str(Acceptable_Range)\n config['section']['STD_Weight'] = str(STD_Weight)\n config['section']['Min_Cutoff'] = str(Min_Cutoff)\n config['section']['Max_Cutoff'] = str(Max_Cutoff)\n config['section']['Num_Weights'] = str(Num_Weights)\n config['section']['Running_AVG'] = str(Running_AVG)\n config['section']['Filter_Num'] = str(Filter_Num)\n config['section']['Stability'] = str(Stability)\n config['section']['Record_Avg'] = str(Record_Avg)\n config['section']['Uniformity'] = str(Uniformity)\n config['section']['Uniform_Percent'] = str(Uniform_Percent)\n config['section']['CV_Value'] = str(CV_Value)\n \n with open(user_config, 'w') as user_config_w:\n config.write(user_config_w)\n \n return Avg_Weight,Running_AVG,Record_Avg,Num_Weights,STD_Weight,Min_Cutoff,Max_Cutoff,AVG_Difference,Last_Avg_Weight,Uniformity,unif_acc_low,unif_acc_high,CV_Value,array_x,array_y,counter\n","sub_path":"Programs/Bird_Scale/SCT20_V1-0/Wireless_Bird_Scale/Programs/Bird_Scale_Weights.py","file_name":"Bird_Scale_Weights.py","file_ext":"py","file_size_in_byte":9801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"315459473","text":"from functools import wraps\n\n\n# 继承实现単例---------------------------------------------------\nclass Singleton(object):\n _instance = None\n\n def __new__(cls, *args, **kwargs):\n if not cls._instance:\n cls._instance = super(Singleton, cls).__new__(cls)\n return cls._instance\n\n\nclass MyClass(Singleton):\n a = 1\n\n\n# --------------------------------------------------------------\n\n\n# 装饰器实现単例--------------------------------------------------\ndef singleton(cls):\n instance = {}\n\n @wraps(cls)\n def getinstance(*args, **kwargs):\n if cls not in instance:\n instance[cls] = cls(*args, **kwargs)\n return instance[cls]\n\n return getinstance\n\n\n@singleton\nclass TestClass(object):\n b = 1\n\n\n# --------------------------------------------------------------\n\n# metaclass(元类)------------------------------------------------\nclass Singleton2(type):\n _instances = {}\n\n def __call__(cls, *args, **kwargs):\n if cls not in cls._instances:\n cls._instances[cls] = super(Singleton2, cls).__call__()\n return cls._instances[cls]\n\n\nclass TestClass2(object):\n __metaclass__ = Singleton2\n b = 1\n\n\nif __name__ == '__main__':\n one = MyClass()\n two = MyClass()\n oneT = TestClass()\n twoT = TestClass()\n bool1 = bool(one == two)\n bool2 = bool(oneT == twoT)\n id1 = (id(one), id(two))\n id2 = (id(oneT), id(twoT))\n print(bool1, id1)\n print(bool2, id2)\n","sub_path":"SingletonMode(单例模式)/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"642043473","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2013 Ruoyan Wong(@saipanno).\n#\n# Created at 2013/07/29.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\nimport json\nimport requests\nfrom fabric.api import hide, execute\n\nfrom backend.logger import logger\nfrom backend.libs.basic_local_runner import base_local_runner\n\n\ndef ping_connectivity_detecting(operation, config):\n \"\"\"\n :Return:\n\n 0: 执行中\n 1: 已完成\n 2: 内部错误\n\n \"\"\"\n\n ID = operation.get('OPT_ID', 0)\n API_URL = '%s/operation/%s' % (config.get('SETTINGS_API_BASIC_URL', None), ID)\n\n COMMAND = 'ping -c%s -W%s {{ address }}' % \\\n (config.get('SETTINGS_PING_COUNT', 4), config.get('SETTINGS_PING_TIMEOUT', 5))\n\n if API_URL is not None:\n with hide('everything'):\n result = execute(base_local_runner, COMMAND,\n hosts=operation.get('OPT_SERVER_LIST', '').split())\n\n data = json.dumps(dict(id=ID, status=1, result=result), ensure_ascii=False)\n\n response = requests.put(API_URL, data=data, headers={'content-type': 'application/json'})\n\n if response.status_code != requests.codes.ok:\n message = response.json.get('message', 'unknown errors')\n logger.error(u'UPDATE OPERATION FAILS|Operation ID is %s, Message is %s' % (ID, message))\n\n else:\n logger.error(u'CONFIG FAILS|Message is can\\'t get API url from config')","sub_path":"backend/operations/ping_connectivity_detecting.py","file_name":"ping_connectivity_detecting.py","file_ext":"py","file_size_in_byte":2476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"326710315","text":"import logging\nfrom typing import Optional, Tuple, Dict, Type\n\nfrom opentrons.hardware_control import ThreadManager\n\nfrom robot_server.service.session.errors import SessionCreationException\nfrom robot_server.service.session.session_types.base_session import BaseSession\nfrom robot_server.service.session.configuration import SessionConfiguration\nfrom robot_server.service.session.models import IdentifierType, SessionType\nfrom robot_server.service.session.session_types import NullSession, \\\n CheckSession, SessionMetaData, TipLengthCalibration\n\nlog = logging.getLogger(__name__)\n\nSessionTypeToClass: Dict[SessionType, Type[BaseSession]] = {\n SessionType.null: NullSession,\n SessionType.calibration_check: CheckSession,\n SessionType.tip_length_calibration: TipLengthCalibration\n}\n\n\nclass SessionManager:\n \"\"\"Manager of session instances\"\"\"\n\n def __init__(self, hardware: ThreadManager):\n self._sessions: Dict[IdentifierType, BaseSession] = {}\n self._active_session_id: Optional[IdentifierType] = None\n # Create object supplied to all sessions\n self._session_common = SessionConfiguration(\n hardware=hardware,\n is_active=self.is_active\n )\n\n async def add(self, session_type: SessionType) -> BaseSession:\n \"\"\"Add a new session\"\"\"\n cls = SessionTypeToClass.get(session_type)\n if not cls:\n raise SessionCreationException(\n f\"'{session_type}' is not supported\"\n )\n session = await cls.create(configuration=self._session_common,\n instance_meta=SessionMetaData())\n self._active_session_id = session.meta.identifier\n self._sessions[session.meta.identifier] = session\n log.debug(f\"Added new session: {session}\")\n return session\n\n async def remove(self, identifier: IdentifierType) \\\n -> Optional[BaseSession]:\n \"\"\"Remove a session\"\"\"\n session = self.deactivate(identifier)\n if session:\n del self._sessions[session.meta.identifier]\n await session.clean_up()\n log.debug(f\"Removed session: {session}\")\n return session\n\n def get_by_id(self, identifier: IdentifierType) \\\n -> Optional[BaseSession]:\n \"\"\"Get a session by identifier\"\"\"\n return self._sessions.get(identifier, None)\n\n def get(self, session_type: SessionType = None) -> Tuple[BaseSession, ...]:\n \"\"\"\n Get all the sessions with optional filter\n\n :param session_type: Optional session type filter\n \"\"\"\n return tuple(session for session in self._sessions.values()\n if not session_type\n or session.session_type == session_type)\n\n def get_active(self) -> Optional[BaseSession]:\n \"\"\"Get the active session\"\"\"\n return self.get_by_id(self._active_session_id) if \\\n self._active_session_id else None\n\n def is_active(self, identifier: IdentifierType) -> bool:\n \"\"\"Check if session identifier is active\"\"\"\n return identifier == self._active_session_id\n\n def activate(self, identifier: IdentifierType) -> Optional[BaseSession]:\n \"\"\"Activate a session\"\"\"\n session = self.get_by_id(identifier)\n if session:\n self._active_session_id = identifier\n return session\n\n def deactivate(self, identifier: IdentifierType) \\\n -> Optional[BaseSession]:\n \"\"\"Deactivate a session\"\"\"\n if identifier == self._active_session_id:\n self._active_session_id = None\n return self.get_by_id(identifier)\n","sub_path":"robot-server/robot_server/service/session/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":3632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"33494086","text":"import os\nimport sys\n\nimport requests\n\n\ndef main():\n port = os.getenv('PORT', 8000)\n res = requests.get(f'http://127.0.0.1:{port}/')\n if res.status_code >= 400:\n sys.exit(1)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"healthcheck.py","file_name":"healthcheck.py","file_ext":"py","file_size_in_byte":230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"441924981","text":"# Released under Apache 2.0; refer to LICENSE.txt\n\nfrom collections import Counter\nfrom fractions import Fraction\nfrom itertools import product\n\nimport numpy\nimport pytest\n\nfrom discrete_sampling.matrix import make_ddg_matrix\nfrom discrete_sampling.matrix import make_hamming_matrix\nfrom discrete_sampling.matrix import make_hamming_vector\nfrom discrete_sampling.packing import pack_tree\nfrom discrete_sampling.tree import make_ddg_tree\n\nfrom discrete_sampling.sample import sample_fdr\nfrom discrete_sampling.sample import sample_inversion_bernoulli\nfrom discrete_sampling.sample import sample_ky_encoding\nfrom discrete_sampling.sample import sample_ky_matrix\nfrom discrete_sampling.sample import sample_ky_matrix_cached\n\nfrom discrete_sampling.flip import BitStream\nfrom discrete_sampling.utils import frac_to_bits_rat\nfrom discrete_sampling.utils import get_bitstrings\n\nfrom discrete_sampling.tests.utils import get_chisquare_pval\n\n@pytest.mark.parametrize('seed', [10, 20, 100123])\ndef test_deterministic(seed):\n rng = numpy.random.RandomState(seed)\n\n Ms, k, l = [0, 31], 5, 0\n P, kp, lp = make_ddg_matrix(Ms, k, l)\n root = make_ddg_tree(P, kp, lp)\n encoding = {}\n pack_tree(encoding, root, 0)\n\n bits = BitStream(kp, rng)\n N_sample = 10000\n samples_mat = [sample_ky_matrix(P, kp, lp, bits) for _i in range(N_sample)]\n samples_enc = [sample_ky_encoding(encoding, bits) for _i in range(N_sample)]\n assert Counter(samples_mat)[1] == N_sample\n assert Counter(samples_enc)[1] == N_sample\n\n@pytest.mark.parametrize('seed', [10, 20, 100123])\ndef test_nondetermistic(seed):\n rng = numpy.random.RandomState(seed)\n\n Ms, k, l = [3, 12], 4, 0\n P, kp, lp = make_ddg_matrix(Ms, k, l)\n root = make_ddg_tree(P, kp, lp)\n encoding = {}\n pack_tree(encoding, root, 0)\n\n bits = BitStream(kp, rng)\n N_sample = 10000\n samples_mat = [sample_ky_matrix(P, kp, lp, bits) for _i in range(N_sample)]\n samples_enc = [sample_ky_encoding(encoding, bits) for _i in range(N_sample)]\n\n pval_mat = get_chisquare_pval([3/15, 12/15], samples_mat)\n assert 0.05 < pval_mat\n\n pval_enc = get_chisquare_pval([3/15, 12/15], samples_enc)\n assert 0.05 < pval_enc\n\ndef test_sample_ky_matrix_cached():\n Ms, k, l = [3, 2, 1, 7, 2, 1], 4, 4\n P, kp, lp = make_ddg_matrix(Ms, k, l)\n h = make_hamming_vector(P)\n T = make_hamming_matrix(P)\n\n samples = []\n bitstrings = get_bitstrings(4)\n for bits in bitstrings:\n result0 = sample_ky_matrix(P, kp, lp, (int(b) for b in bits))\n result1 = sample_ky_matrix_cached(kp, lp, h, T, (int(b) for b in bits))\n assert result0 == result1\n samples.append(result0)\n\n counter = Counter(samples)\n assert counter[1] == 3\n assert counter[2] == 2\n assert counter[3] == 1\n assert counter[4] == 7\n assert counter[5] == 2\n assert counter[6] == 1\n\nfractions = [\n Fraction(1, 2),\n Fraction(3, 8),\n Fraction(2, 13),\n Fraction(19, 21),\n]\nseeds = [2, 10, 131]\nargs = list(product(fractions, seeds))\n@pytest.mark.parametrize('p, seed', args)\ndef test_inversion_bernoulli(p, seed):\n rng = numpy.random.RandomState(seed)\n bits = BitStream(10, rng)\n N = 200000\n (a, M) = (p.numerator, p.denominator)\n samples = [sample_inversion_bernoulli(a, M, bits) for i in range(N)]\n pval = get_chisquare_pval([1-p, p], samples)\n assert 0.05 < pval\n\n@pytest.mark.parametrize('n', range(2, 20, 2))\ndef test_fdr(n):\n rng = numpy.random.RandomState(2)\n bits = BitStream(n, rng)\n N_sample = 10000\n samples = [sample_fdr(n, bits) for i in range(N_sample)]\n pval = get_chisquare_pval([1/n]*n, samples)\n assert pval > 0.05\n","sub_path":"tests/test_sample.py","file_name":"test_sample.py","file_ext":"py","file_size_in_byte":3669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"194918663","text":"# https://leetcode.com/problems/basic-calculator\n#\n# Implement a basic calculator to evaluate a simple expression string.\n#\n# The expression string may contain open ( and closing parentheses ), the\n# plus + or minus sign -, non-negative integers and empty spaces .\n#\n# You may assume that the given expression is always valid.\n#\n# \"1 + 1\" = 2\n# \" 2-1 + 2 \" = 3\n# \"(1+(4+5+2)-3)+(6+8)\" = 23\n\ndef shift_add(num, c):\n a = num if num != None else 0\n b = int(c)\n return a * 10 + b\n\ndef compute(l, r, op):\n if op == '+':\n return l + r\n elif op == '-':\n return l - r\n else:\n return r\n\ndef my_eval(expr):\n sub = [] # subexpressions\n left = right = op = None\n for c in expr:\n if c == ' ': # ignore spaces\n pass\n elif c in '0123456789': # parse number\n right = shift_add(right, c)\n elif c in '+-':\n left = compute(left, right, op)\n right = None\n op = c\n elif c == '(':\n sub.append((left,op))\n left = op = None\n elif c == ')':\n left = compute(left, right, op)\n right = left\n left, op = sub.pop()\n left = compute(left, right, op)\n print('\"{0}\" = {1}'.format(expr, left))\n\n# Tests\n##############\nmy_eval('')\nmy_eval('2 + 2')\nmy_eval('2 + 2 - 1')\nmy_eval('2 + (2 - 1)')\nmy_eval('(1+(4+5+2)-3)+(6+8)')\nmy_eval('(2) + 2')\n","sub_path":"basic-calculator-2.py","file_name":"basic-calculator-2.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"156771369","text":"\"\"\"\nВыведите таблицу размером n×nn×n, заполненную числами от 11 до n2n2 по спирали,\nвыходящей из левого верхнего угла и закрученной по часовой стрелке.\n\n\"\"\"\n\nn=int(input())\n\n\n\n#Заполняем\n\nl=k=1\nd=r=u=x=y=0\n\nmax_n=n-1\nmin_n=0\n\n\nwhile k <= (n*n):\n#если начало и конец совпадают\n\tif min_n==max_n:\n\t\tprint (\"центр:\",y,x,k)\n\t\tk+=1\n#право\n\telif l==1:\n\t\tl=0\n\t\td=1\n\t\twhile xmin_n:\n\t\t\tprint (\"вл:\",y,x,k)\n\t\t\tk+=1\n\t\t\tx-=1\n\t\t\n\t\t\n\n#вверх\n\telif u==1:\n\t\tu=0\n\t\tl=1\n\t\twhile y>min_n:\n\t\t\tprint (\"вв:\",y,x,k)\n\t\t\tk+=1\n\t\t\ty-=1\n\t\tmax_n-=1\n\t\tmin_n+=1\n\t\tx=y=min_n\n\t\n\t\t\n\t\t\n\n\n\n\n\n\n\n","sub_path":"program30_6w.py","file_name":"program30_6w.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"405650253","text":"# 导入函数库\n# import jqdata\nimport math\nimport pandas as pd\nimport datetime\n\n\n# 初始化函数,设定要操作的股票、基准等等\ndef initialize(account):\n # 设定沪深300作为基准\n set_benchmark('000300.SH')\n # 设定选股条件\n get_iwencai('股票市场类型是a股,上市天数>200,交易状态包含交易,所属同花顺行业是银行')\n # 开启动态复权模式(真实价格)\n #set_option('use_real_price', True)\n # set_commission(PerShare(open_cost=0.0003,close_cost=0.0013, close_today_cost=0, type='stock'))#设置期货交易手续费\n # set_slippage(PriceSlippage(0.02))\n # set_log_level('info')\n g.buyframe = pd.DataFrame()\n account.signal = False # 空仓信号\n account.b = True # 买入信号\n # try:\n # g.buyframe=pd.read_csv('银行翻倍选股结果.csv',index_col=0)\n # except:\n # g.buyframe=pd.DataFrame()\n\n run_monthly(handle, 1) # date_rules.month_start(1))\n\n\n# 每个单位时间(如果按天回测,则每天调用一次,如果按分钟,则每分钟调用一次)调用一次\ndef handle(account, data):\n if account.signal != 'PB_long': # 如果不在PB长空仓期\n # 检测空仓信号\n period, account.signal = MarketSignal(account)\n # 如果有空仓信号\n if account.signal != False:\n # 更改买入信号为False\n account.b = False\n # 计算空仓结束时间\n account.date = get_datetime() + datetime.timedelta(days=period)\n # 执行空仓\n for stock in list(account.positions.keys()):\n order_target_value(stock, 0)\n # 输出信号\n log.info('空仓信号在' + get_datetime().strftime('%Y-%m-%d') +\n '触发,空仓' + str(period)[:-1] + '天')\n\n # 如果买入信号为假,现在日期大于空仓停止日期\n if account.b == False and get_datetime() > account.date:\n # 空仓期结束\n account.b = True # 买入\n account.signal = False # 无信号\n\n if account.b == True: # 买入信号为真\n buylist = BankDoubleTimeFilter(account)\n for hold in list(account.positions):\n if hold not in (list(buylist)):\n order_target_value(hold, 0)\n # 根据目标持仓权重,逐一委托下单\n for stock in buylist:\n order_target_percent(stock, 1.0/(len(buylist)))\n else:\n # 如果在空仓期,时间未结束\n pass\n\n\ndef BankDoubleTimeFilter(account, overflow=0):\n \"\"\"\n 根据银行翻倍期选股的函数。\n \"\"\"\n # 获取a股上市天数>200、可交易的银行股,这些条件在initialize函数中进行了设置\n stock_list = account.iwencai_securities\n # 前一天的日期\n yesterday = get_last_datetime().strftime('%Y%m%d')\n # 设置需要得到的因子,具体如何设置可参考Mindgo的API。\n # 此处需要获取的因子有股票代码、基本EPS、PB、单季ROE,\n # filter中设置了股票池为上面声明的stock_list,order_by\n # 中设置了得到的dataframe根据股票代码来排序。\n q = query(valuation.symbol, valuation.pb, profit_one_season.roe, growth_one_season.net_profit_growth_ratio).filter(\n valuation.symbol.in_(stock_list)).order_by(valuation.symbol)\n df = get_fundamentals(q, date=yesterday)\n df = df.set_index(df['valuation_symbol'])\n\n # 选取单季ROE大于-1的股票\n df = df[df['profit_one_season_roe'] > -1]\n # 筛选净利润同比增长率大于0的股票\n df = df[df['growth_one_season_net_profit_growth_ratio'] > 0]\n\n # 计算翻倍期\n df['double_time'] = df.apply(lambda row: round(math.log(\n 2.0*row['valuation_pb'], (1.0+row['profit_one_season_roe']/100)), 2),\n axis=1)\n # 选取翻倍期前5个最短的股票\n df_double = df.sort_values('double_time', ascending=True)\n df_double = df_double[:5]\n buylist = list(df_double['valuation_symbol'].values)\n # 输出选股信息\n log.info(get_datetime().strftime('%Y-%m-%d') +\n ' 选股为 ' + str(buylist)[1:-1])\n return buylist\n\n\ndef MarketSignal(account):\n yesterday = get_last_datetime().strftime('%Y-%m-%d')\n stock_list = list((get_all_securities('stock').index))\n df = get_fundamentals(query(valuation.symbol, valuation.pb).filter(\n valuation.symbol.in_(stock_list)), date=yesterday)\n factor_quantiles = df.dropna().quantile([0.8])\n PB = factor_quantiles.iloc[0].values\n\n if PB >= 10:\n # if account.current_date.strftime('%Y-%m-%d') in ['2008-01-02', '2015-06-01']:\n # 后续运行可以把时间存为列表,节省回测时间\n return 240, 'PB_long' # 长空仓\n else:\n return 0, False\n","sub_path":"bank.py","file_name":"bank.py","file_ext":"py","file_size_in_byte":4768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"637884656","text":"from dobpy import dob\n\ndatabase = dob.mount(\"./test.dob\")\n\ndatabase.append(\"Hello World!\",[])\ndatabase.stack(\"This post has data values\", [\"dob\",\"is\",\"cool\"])\n\nprint(database.raw())\nprint(database.parse())\n\n# or\n\nprint(\n dob.parsedob(\n database.raw()\n )\n)\nprint(\n dob.dobify(\n database.parse()\n )\n)","sub_path":"python/test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"540974645","text":"\"\"\"This module interfaces with the TOI data.\"\"\"\nimport glob\nimport logging\nimport os\nimport re\nfrom typing import List, Optional\n\nimport pandas as pd\n\nfrom tess_atlas.data.exofop import EXOFOP_DATA\nfrom tess_atlas.logger import LOGGER_NAME\n\nlogger = logging.getLogger(LOGGER_NAME)\n\n\ndef __get_completed_toi_pe_results_paths(outdir: str) -> pd.DataFrame:\n \"\"\"Get the paths to the netcdf files for all completed TOIs\"\"\"\n search_path = os.path.join(outdir, \"toi_*_files/*.netcdf\")\n netcdf_files = glob.glob(search_path)\n logger.info(f\"Searching {search_path} --> {len(netcdf_files)} files found\")\n regex = \"toi_(\\d+)_files\"\n tois = [int(re.search(regex, f).group(1)) for f in netcdf_files]\n return pd.DataFrame(dict(TOI=tois, path=netcdf_files))\n\n\ndef get_unprocessed_toi_numbers(toi_numbers: List, outdir: str) -> List[int]:\n \"\"\"Filter toi_numbers to only include those that have not been processed\"\"\"\n processed_tois = set(\n __get_completed_toi_pe_results_paths(outdir).TOI.values\n )\n tois = set(toi_numbers)\n return list(tois.difference(processed_tois))\n\n\ndef parse_toi_numbers(toi_csv: str, toi_number: int, outdir: str) -> List[int]:\n if toi_csv and toi_number is None: # get TOI numbers from CSV\n toi_numbers = __read_csv_toi_numbers(toi_csv)\n elif toi_csv is None and toi_number: # get single TOI number\n toi_numbers = [toi_number]\n elif toi_csv is None and toi_number is None: # get all TOIs\n toi_numbers = __make_toi_csv(os.path.join(outdir, \"tois.csv\"))\n else:\n raise ValueError(f\"Cannot pass both toi-csv and toi-number\")\n return toi_numbers\n\n\ndef __read_csv_toi_numbers(toi_csv: str) -> List[int]:\n return list(pd.read_csv(toi_csv).toi_numbers.values)\n\n\ndef __make_toi_csv(\n fname: str, toi_numbers: Optional[List[int]] = []\n) -> List[int]:\n if len(toi_numbers) == 0:\n toi_numbers = EXOFOP_DATA.get_toi_list(\n category=None, remove_toi_without_lk=True\n )\n toi_numbers = list(set([int(i) for i in toi_numbers]))\n data = pd.DataFrame(dict(toi_numbers=toi_numbers))\n data.to_csv(fname, index=False)\n return __read_csv_toi_numbers(fname)\n","sub_path":"src/tess_atlas/slurm_job_generator/slurm_toi_data_interface.py","file_name":"slurm_toi_data_interface.py","file_ext":"py","file_size_in_byte":2178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"25767704","text":"def evalRec(env, rec):\n \"\"\"Has Damaging Predictions\"\"\"\n\n if (rec.Severity > 2):\n return True\n\n # 2.a.\tPresent in ClinVar Path, Likely Path, VUS (worst annotation).\n clinvar_clinically_significant = (rec.Clinvar_Benign == False) \\\n and (rec.Clinvar_Trusted_Benign in {False, \"No data\"})\n if (clinvar_clinically_significant):\n return True\n\n # Include Splice Altering variants\n if (rec.splice_ai_dsmax > 0.2):\n return True\n\n if len(rec.Polyphen &\n {\"possibly_damaging\", \"probably_damaging\"}) > 0:\n return True\n if (len(rec.Polyphen_2_HVAR) > 0 and\n len(rec.Polyphen_2_HVAR - {\"P\", \"D\"}) == 0):\n return True\n if (len(rec.Polyphen_2_HDIV) > 0 and\n len(rec.Polyphen_2_HDIV - {\"P\", \"D\"}) == 0):\n return True\n return len(rec.SIFT &\n {\"deleterious\", \"tolerated_low_confidence\"}) > 0\n","sub_path":"app/search/hot_eval/polyphen_check.py","file_name":"polyphen_check.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"574876201","text":"#!/usr/bin/python3\n# get lines of text from serial port, save them to a file\n\n# AWJ Logan (http://awjlogan.wordpress.com)\n# April 2015\n\n# adapted from jbeale:\n# https://www.raspberrypi.org/forums/viewtopic.php?f=44&t=64545\n\n# from __future__ import print_function\nimport serial, io\nimport time, datetime\n\naddr = '/dev/ttyAMA0' # serial port to read data from\nbaud = 9600 # baud rate for serial port\n\nwith serial.Serial(addr,9600) as pt:\n spb = io.TextIOWrapper(io.BufferedRWPair(pt,pt,1),\n encoding='ascii', errors='ignore', newline='\\r',line_buffering=True)\n spb.readline() # throw away first line; likely to start mid-sentence (incomplete)\n \n while (1):\n # get data and parse\n serialLine = spb.readline() \n readList = serialLine.split(',')\n # print(serialLine,end='')\n \n # check if data are from CC unit\n if 'cc' in readList[0]:\n fname = './data/' + datetime.date.today().strftime('%b%Y') + '_' + readList[0].lstrip('c') + '.csv'\n \n # format and write out data\n outLine = time.time() + ',' + readList[0].lstrip('c')\n for i in range(2,len(readList)):\n outLine = outLine + ',' + readList[i]\n\n with open(fname, 'a') as f:\n f.write(outLine + '\\n')\n f.flush()","sub_path":"Data/serial_logger.py","file_name":"serial_logger.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"449847518","text":"from skills_ml.algorithms.occupation_classifiers.classifiers import NearestNeighbors, Classifier\nfrom skills_utils.s3 import upload\n\nimport gensim\nfrom gensim.similarities.index import AnnoyIndexer\n\nimport os\nfrom moto import mock_s3_deprecated\nfrom mock import patch\nimport boto\nimport logging\nlogging.getLogger('boto').setLevel(logging.CRITICAL)\n\nimport tempfile\n\nimport json\n\nimport pytest\n\ndocs = \"\"\"licensed practical nurse licensed practical and licensed\nvocational nurses licensed practical nurse department family\nbirthing center schedule part time shift hr day night rotation\nhours hrs pp wknd rot holidays minimum salary minimum requisition\nnumber job details provides direct nursing care for individual\npatients undergoing cesarean section under the direction of the\nsurgeon also is involved with assisting with vaginal deliveries\nrecovery and transferring of newly delivered patient and their\nfamilies under the direction of the registered nurse to achieve\nthe hospital mission of competent christian holistic care patients\ncared for include childbearing women and newborn infants the licensed\npractical nurse can be responsible for newborn testing such as hearing\nscreening and car seat testing implements and abides by customer\nservice standards supports and implements patient safety and other\nsafety practices as appropriate supports and demonstrates family centered\ncare principles when interacting with patients and their families and\nwith coworkers education graduate of an approved school of practical\nnursing required experience previous lpn experience preferred special\nrequirements current licensure as practical nurse lpn in the state of\nminnesota required current american heart association aha bls healthcare\nprovider card required prior to completion of unit orientation eeo aa\ngraduate of an approved school of practical nursing required,29,29-2061.00\"\"\"\n\ndef get_corpus(num):\n lines = [docs]*num\n for line in lines:\n yield line\n\nclass FakeCorpusGenerator(object):\n def __init__(self , num=5):\n self.num = num\n self.lookup = {}\n def __iter__(self):\n k = 1\n corpus_memory_friendly = get_corpus(num=100)\n for data in corpus_memory_friendly:\n data = gensim.utils.to_unicode(data).split(',')\n words = data[0].split()\n label = [str(k)]\n self.lookup[str(k)] = data[2]\n yield gensim.models.doc2vec.TaggedDocument(words, label)\n k += 1\n\n@mock_s3_deprecated\ndef test_occupation_classifier():\n s3_conn = boto.connect_s3()\n bucket_name = 'fake-bucket'\n bucket = s3_conn.create_bucket(bucket_name)\n\n model_name = 'doc2vec_gensim_test'\n s3_prefix_model = 'fake-bucket/cache/embedding/'\n\n classifier_id = 'ann_0614'\n classifier_name = classifier_id + '.index'\n\n fake_corpus_train = FakeCorpusGenerator(num=10)\n\n model = gensim.models.Doc2Vec(size=500, min_count=1, iter=5, window=4)\n\n with tempfile.TemporaryDirectory() as td:\n model.build_vocab(fake_corpus_train)\n model.train(fake_corpus_train, total_examples=model.corpus_count, epochs=model.iter)\n model.save(os.path.join(td, model_name + '.model'))\n upload(s3_conn, os.path.join(td, model_name + '.model'), os.path.join(s3_prefix_model, model_name))\n\n with tempfile.TemporaryDirectory() as td:\n lookup = fake_corpus_train.lookup\n lookup_name = 'lookup_' + model_name + '.json'\n with open(os.path.join(td, lookup_name), 'w') as handle:\n json.dump(lookup, handle)\n upload(s3_conn, os.path.join(td, lookup_name), os.path.join(s3_prefix_model, model_name))\n\n nn_classifier = NearestNeighbors(\n model_name=model_name,\n s3_path=s3_prefix_model,\n s3_conn=s3_conn,\n )\n model = nn_classifier.model\n model.init_sims()\n ann_index = AnnoyIndexer(model, 10)\n ann_classifier = NearestNeighbors(\n model_name=model_name,\n s3_path=s3_prefix_model,\n s3_conn=s3_conn,\n )\n ann_classifier.indexer = ann_index\n\n\n clf_top = Classifier(\n classifier_id=classifier_id,\n s3_conn=s3_conn,\n s3_path=s3_prefix_model,\n classifier=ann_classifier,\n classify_kwargs={'mode': 'top'}\n )\n clf_common = Classifier(\n classifier_id=classifier_id,\n s3_conn=s3_conn,\n s3_path=s3_prefix_model,\n classifier=ann_classifier,\n classify_kwargs={'mode': 'common'}\n )\n\n\n assert nn_classifier.model_name == model_name\n assert nn_classifier.indexer != clf_top.classifier.indexer\n assert nn_classifier.predict_soc(docs, 'top')[0] == clf_top.classify(docs)[0]\n assert nn_classifier.predict_soc(docs, 'common')[0] == clf_common.classify(docs)[0]\n\n","sub_path":"tests/algorithms/test_occupation_classifiers.py","file_name":"test_occupation_classifiers.py","file_ext":"py","file_size_in_byte":4746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"227936863","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom .models import Topic, Post, Comment\nfrom django.template import loader\nfrom .forms import CommentForm\n\n\ndef index(request):\n form = CommentForm(request.POST or None)\n if form.is_valid():\n\n form.save()\n form = CommentForm()\n\n allTopics = Topic.objects.all()\n allComments = Comment.objects.all()\n context = {\n 'allComments' : allComments,\n 'allTopics' : allTopics,\n 'form' : form\n\n }\n return render(request, 'blog.html', context)\n\n\n\n\n\ndef detail(request, topic, postId=None):\n if postId:\n text = request.POST['text']\n post = Post.objects.get(id=int(postId))\n post.comment_set.create(name='dan', commentText=text)\n\n\n\n allTopics = Topic.objects.all()\n topic = Topic.objects.get(id = topic)\n allPosts = topic.post_set.all()\n allComments = []\n\n for eachPost in allPosts:\n allComments.append(eachPost.comment_set.all())\n\n\n context = {\n 'allTopics' : allTopics,\n 'topicId' : topic.id,\n 'allPosts' : allPosts,\n 'allComments' : allComments,\n 'range': range(len(allComments)),\n\n\n }\n\n return render(request, 'blog.html', context)\n\n\n\n\ndef cv(request):\n context = {\n }\n return render(request, 'cv.html', context)\n\n\n# Create your views here.\n","sub_path":"blog/Posts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"440747620","text":"from jinja2 import Template\nfrom flask import Flask, render_template_string, request, render_template\n\napp = Flask(__name__)\napp.config['FLAG'] = 'DISCCTF{Fl4Sk_C0n_J1nJ4_}'\n\n@app.route(\"/\", methods=[\"GET\"])\ndef index():\n\treturn render_template('template1.html')\n\n@app.route(\"/pdf\", methods=[\"POST\"])\ndef exploit():\n\tusername = request.form['username']\n\tcodigo = request.form['codigo']\n\tcorreo = request.form['correo']\n\trendered = render_template('template2.html', username = username, codigo=codigo, correo=correo)\n\treturn render_template_string(rendered)\n\n\nif __name__ == '__main__':\n\tapp.run(debug=True)\n\n","sub_path":"Web/[Web 06] SSTI/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"54647216","text":"import sys\nimport subprocess\n# Python version\nvsn=sys.version\nprint(\"Using Python version: {}\".format(vsn.split(\"\\n\")[0]))\nif vsn[0] != \"3\":\n print(\"You are currently not using Python3. Change your Python version from the configuration file.\")\n\n#FFMPEG version\nffmpeg = subprocess.check_output([\"ffmpeg\",\"-version\"])\ntry:\n\tprint(ffmpeg[0:20].decode(\"utf-8\"))\nexcept:\n\tprint(\"No ffmpeg installation detected. Run \\\"pip install ffmpeg\\\" or visit https://www.ffmpeg.org/download.html\")\n#Check packages \nrequired=[\"lxml\",\"pandas\",\"pydub\"]\ntry:\n\treqs = subprocess.check_output([sys.executable, '-m', 'pip', 'freeze'])\nexcept subprocess.CalledProcessError as e:\n print(\"No version of pip installed.\")\n sys.exit()\ninstalled_packages = [r.decode().split('==')[0] for r in reqs.split()]\nfor pckg in required:\n\tif pckg not in installed_packages:\n\t\tprint(\"Missing package: {}\".format(pckg))\n","sub_path":"installation_check.py","file_name":"installation_check.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"453233488","text":"#!/usr/bin/env python\n\nimport treexml\nimport errors\nimport filters\n\nclass Handler:\n def __init__(self, site, response, method, query, args):\n self.site = site\n self.response = response\n self.method = method\n self.query = query\n self.type = None\n self.name = None\n self.tgt_type = None\n self.tgt_name = None\n self.resource = None\n for arg in args:\n val = args[arg]\n # There must be an elegant way to do this\n if arg == 'type': self.type = val\n elif arg == 'name': self.name = val\n elif arg == 'tgt_type': self.tgt_type = val\n elif arg == 'tgt_name': self.tgt_name = val\n elif arg == 'resource': self.resource = val\n elif arg == 'postdata': self.data = val\n if self.type and self.name:\n treexml.insert_node(self.response, self.type, {'id':[self.name]})\n if self.tgt_type and self.tgt_name:\n treexml.insert_node(self.response, 'target_%s' % self.tgt_type, {'id':[self.tgt_name]})\n #if self.resource:\n # treexml.insert_node(self.response, 'resource', {'id':[self.resource]})\n if self.name:\n if not self.type:\n raise(errors.UnknownError)\n try:\n self.name = filters.check_identifier(self.name, 32)\n except filters.Error:\n raise(errors.IdError)\n if self.tgt_name:\n if not self.tgt_type:\n raise(errors.UnknownError)\n try:\n self.tgt_name = filters.check_identifier(self.tgt_name, 32)\n except filters.Error:\n raise(errors.IdError)\n \n def run(self):\n # This is just scaffolding\n pass\n\n def debug(self, text):\n treexml.insert_node(self.response, 'debug', str(text))\n","sub_path":"scripts/res/generic.py","file_name":"generic.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"280315375","text":"import socket, argparse, sys\n\ndef Main(ip, port):\n print('-' * 120)\n print(f'Scanning target: {args.ip}')\n print(f'Checking port: {args.port}')\n print('-' * 120)\n\n try:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.settimeout(0.15)\n result = s.connect_ex((args.ip, args.port))\n if result == 0:\n print(f'Open Port: {args.port}')\n else:\n print(f'Port: {args.port} closed')\n s.close()\n except KeyboardInterrupt:\n print('\\nExiting program.')\n sys.exit()\n except socket.gaierror:\n print('Hostname could not be resolved.')\n sys.exit()\n except socket.timeout:\n print('Connection timed out.')\n sys.exit()\n except socket.error:\n print(\"Couldn't connect to server.\")\n sys.exit()\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Scan a port on given hostname or ip')\n ap = argparse.ArgumentParser(prog='port_scanner.py', usage='%(prog)s [options] -ip \"ip or hostname\" -port \"port to scan\"')\n ap.add_argument('-ip', required=True, type=str, help='ip or hostname')\n ap.add_argument('-port', required=True, type=int, help='Port to scan')\n args = ap.parse_args()\n ip = args.ip\n port = args.port\n Main(ip, port)\n","sub_path":"port_scanner.py","file_name":"port_scanner.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"278506960","text":"import os,sys,time,re\nsys.path.append('../DBbase')\nfrom db_func import *\nfrom mail_func import *\n\nwarning_receivers = ['xuechen.han@weicheche.cn', 'fengxin.jiang@weicheche.cn']\n\ndef watchdog_a():\n SQL_watchdog_one = \"\"\"\n SELECT batch_date,count(1) counts,count(DISTINCT %(dis_col)s) dis__%(dis_col)ss\n FROM profile.%(table_name)s\n where batch_date = %(yesterday)s\n GROUP BY batch_date\n \"\"\"\n \n table_col = {'pr_groups_order_other_': 'mer_id',\n 'pr_platforms_order_other_': 'mer_id',\n 'pr_stations_order_other_': 'mer_id',\n 'pr_groups_user_dis_': 'mer_id',\n 'pr_platforms_user_dis_': 'mer_id',\n 'pr_stations_user_dis_': 'mer_id',\n 'pr_stations_user_dis2_': 'mer_id',\n 'pr_coupon_user_coupons': 'uid',\n 'pr_level_user_tag': 'uid',\n 'pr_crma_stations_couponstat': 'uid',\n 'pr_crma_groups_couponstat': 'uid',\n }\n para = {'yesterday': day_forpast(d=-1)}\n dw = my_(config.MYSQL_BI_RW_ENV)\n # dfr = {}\n ress = ''\n for x, v in table_col.items():\n para.update({'table_name': x, 'dis_col': v})\n df = dw.to_dataframe(SQL_watchdog_one %para)\n if len(df):\n continue\n dfs = df.drop('batch_date', 1).to_json(orient='records')\n # dfr[x] = df\n ress += 'profile.%-36s: %s \\n' % (x, dfs)\n \n if ress:\n print(ress)\n subject = 'profile更新信息提示_' + para['yesterday']\n send_email_exqq(warning_receivers, subject, content=ress, filepaths=None)\n else:\n send_wechat_warning('每日数据检查OK!-——data_shield(watchdog_a)')\n\n\ndef watchdog_b():\n para = {'yesterday': day_forpast(d=-1)}\n table_names = ['mid_cos_dyn_%(yesterday)s' %para, 'mid_cos_dyn_%(yesterday)s' %para]\n dw = my_(config.MYSQL_BI_RW_ENV)\n ress = ''\n for x in table_names:\n df = dw.to_dataframe('select count(1) counts from data_center.%s' % x)\n if len(df):\n continue\n dfs = df.to_json(orient='records')\n ress += 'data_center.%-36s: %s \\n' % (x, dfs)\n\n if ress:\n print(ress)\n subject = 'data_center中间表更新信息提示_' + para['yesterday']\n send_email_exqq(warning_receivers, subject, content=ress, filepaths=None)\n else:\n send_wechat_warning('每日数据检查OK!-——data_shield(watchdog_b)')\n\n\ndef watchdog_c():\n check_sql = 'SELECT * FROM bimodels.bm_ea_apirecords_pickup where status=1'\n dw = my_(config.MYSQL_BI_RW_ENV)\n df = dw.to_dataframe(check_sql)\n if len(df):\n ress = 'bimodels.bm_ea_apirecords_pickup 出现了不应该有的情况(status=1)'\n send_email_exqq(warning_receivers, 'watchdog_c发现异常', content=ress, filepaths=None)\n else:\n send_wechat_warning('每日数据检查OK!-——data_shield(watchdog_c)')\n\n\nif __name__ == \"__main__\":\n watchdog_a()\n watchdog_b()\n watchdog_c()","sub_path":"Shield/data_shield.py","file_name":"data_shield.py","file_ext":"py","file_size_in_byte":3012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"98940370","text":"from panda3d.core import *\nfrom panda3d.core import LVector3f\nfrom panda3d.ai import *\nfrom direct.showbase import PythonUtil\nfrom direct.distributed.ClockDelta import globalClockDelta\nfrom direct.interval.IntervalGlobal import *\nfrom direct.directnotify import DirectNotifyGlobal\nfrom direct.task import Task\nfrom otp.movement.PyVec3 import PyVec3\n\nimport random\nimport __builtin__\n\nclass Mover():\n notify = DirectNotifyGlobal.directNotify.newCategory('Mover')\n SerialNum = 0\n Profile = 0\n render = NodePath('render')\n nullTargetNodePath = NodePath('nullTargetNodepath')\n\n def __init__(self, objNodePath, fwdSpeed = 1, rotSpeed = 1):\n print (\"Initalizng pet\")\n\n self.serialNum = Mover.SerialNum\n Mover.SerialNum += 1\n self.VecType = Vec3\n self.impulses = {}\n\n # NEW VARIABLES\n self.petNodePath = objNodePath\n self.targetNodePath = NodePath('targetNodepath')\n\n self.petLocked = False\n self.petMode = 'unstick'\n self._sadMult = 0.3\n self.fwdSpeed = fwdSpeed\n self.sadFwdSpeed = self.fwdSpeed * self._sadMult\n\n # Temporary garbage\n self.taskOn = 0\n\n self.setAI()\n\n\n def destroy(self):\n for name, impulse in self.impulses.items():\n Mover.notify.debug('removing impulse: %s' % name)\n self.removeImpulse(name)\n\n\n\n def addImpulse(self, name, impulse):\n self.impulses[name] = impulse\n impulse._setMover(self)\n\n\n\n def removeImpulse(self, name):\n if name not in self.impulses:\n Mover.notify.warning(\"Mover.removeImpulse: unknown impulse '%s'\" % name)\n return\n self.impulses[name]._clearMover(self)\n del self.impulses[name]\n\n\n\n def processImpulses(self, dt = 1):\n self.dt = dt\n if self.dt == -1.0:\n time = globalClockDelta.getRealNetworkTime()\n self.dt = time - dt\n\n for impulse in self.impulses.values():\n impulse._process(self.dt)\n\n\n\n def getCollisionEventName(self):\n return 'moverCollision-%s' % self.serialNum\n\n\n\n def move(self, dt = -1, profile = 0):\n if Mover.Profile and not profile:\n\n def func(doMove = self.move):\n for i in xrange(10000):\n doMove(dt, profile=1)\n\n self.processImpulses(dt)\n self.integrate()\n\n\n\n def integrate(self):\n try:\n # Do this once\n if self.taskOn == 0:\n taskMgr.add(self.AIUpdate,\"AIUpdate\")\n self.taskOn = 1\n \n except:\n pass\n\n def AIUpdate(self, task):\n try:\n self.AIworld.update()\n self.petCollisions()\n self.petRotationFix()\n except:\n pass\n\n\n return Task.cont\n\n\n\n def petCollisions(self):\n try:\n # This piece of code is to check the distance between the toon and pet,\n # in order to make sure the doodle does not collide with the toon.\n xToon = int(self.targetNodePath.getX())\n xPet = int(self.petNodePath.getX())\n yToon = int(self.targetNodePath.getY())\n yPet = int(self.petNodePath.getY())\n\n xDifference = abs(xToon - xPet) # Get the absolute value because we don't care about exact position in the environment\n yDifference = abs(yToon - yPet)\n\n stopDistance = 2 # Distance the pet should stop before reaching toon\n\n if xDifference <= stopDistance and yDifference <= stopDistance: # If the distance between toon and pet is 2; stop moving\n self.AIbehaviors.pauseAi('all') # Stop the pet from moving\n\n except:\n pass\n\n\n def petRotationFix(self):\n if self.petMode != 'stick':\n currentHPet = self.petNodePath.getH()\n correctedHPet = currentHPet - 180\n self.petNodePath.setH(correctedHPet)\n\n\n\n def setAI(self):\n #Creating AI World\n\n self.AIworld = AIWorld(Mover.render)\n \n self.AIchar = AICharacter(\"petNodePath\", self.petNodePath, 50, 10, 25)\n self.AIworld.addAiChar(self.AIchar)\n self.AIbehaviors = self.AIchar.getAiBehaviors()\n\n\n\n def setPetAIMode(self, petMode, target = nullTargetNodePath):\n self.petMode = petMode\n self.targetNodePath = target # This is in case we need to do something else with the target later\n\n self.AIbehaviors.pauseAi('all') # Before we do any state changes, pause the AI\n\n if self.petMode == 'stick': # Locks pet and doesn't allow movement\n self.petLocked = True\n self.AIbehaviors.pauseAi('all')\n\n elif self.petMode == 'unstick':\n self.petLocked = False\n\n elif self.petMode == 'chase' and self.petLocked == False: # This makes the pet continue to follow a moving object\n self.AIbehaviors.pursue(target)\n\n elif self.petMode == 'static_chase' and self.petLocked == False: # This makes the pet go to a single spot\n self.AIbehaviors.seek(target)\n\n elif self.petMode == 'wander' and self.petLocked == False:\n self.AIbehaviors.wander(10, 0, 50, 1.0)\n\n elif self.petMode == 'flee' and self.petLocked == False:\n self.AIbehaviors.flee(chaser, 20, 20)\n\n\n\n # Pet's walking speed\n def setFwdSpeed(self, speed):\n self.fwdSpeed = speed\n self.AIchar.setMaxForce(self.fwdSpeed) \n\n\n","sub_path":"otp/movement-OLD/Mover.py","file_name":"Mover.py","file_ext":"py","file_size_in_byte":5422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"468255985","text":"\ndef findsubarray(arr,givensum):\n left = 0\n right = 0\n currrent_sum = 0\n\n\n while(currrent_sum != givensum):\n#step1)increase right pointer towards right and keep left pointer stable \n if currrent_sum < givensum:\n currrent_sum = currrent_sum +arr[right]\n\n if currrent_sum python demo.py\n\nleft is 2\nright is 4\nFor givensum = 33 Subarray is [20, 3, 10]\n\n\n\n\n\n'''","sub_path":"mycodes/arrays/p13/p13.py","file_name":"p13.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"383471343","text":"# imports\nimport math\nimport numbers\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\"\"\"\nClass ConvGRU_cell\n \n Creates a single Convolutional Gated Recurrent Unit cell\n \n Args:\n inpt_dim (inpt_dim) : number of channels in input\n hidden_dim (int) : dimension of cell's hidden state \n kernel_i (int, tuple) : size of filter aplied to input to cell\n stride_i (int, tuple) : stride aplied to input convolution\n kernel_h (int, tuple) : size of filter aplied to the previous hidden state\n stride_h (int, tuple) : stride aplied to hidden state convolution\n padding_i (int) : padding aplied around input\n padding_h (int) : padding aplied to previous hidden state\n bias (boolean) : True to include bias terms in convolution\n\"\"\"\nclass ConvGRU_cell(nn.Module):\n \n def __init__(self, \n inpt_dim, hidden_dim, \n kernel_i, stride_i, padding_i,\n kernel_h, stride_h, padding_h, \n bias = True):\n \n super(ConvGRU_cell, self).__init__()\n \n self.hidden_dim = hidden_dim\n \n self.conv_in = nn.Conv2d(\n in_channels = inpt_dim, \n out_channels = 3*hidden_dim, \n kernel_size = kernel_i, \n stride = stride_i, \n padding = padding_i, \n bias = bias \n )\n \n self.conv_h = nn.Conv2d(\n in_channels = hidden_dim, \n out_channels = 3*hidden_dim, \n kernel_size = kernel_h, \n stride = stride_h, \n padding = padding_h, \n bias = bias \n )\n \n def forward(self, x, h_prev):\n \n x = self.conv_in(x)\n h = self.conv_h(h_prev)\n x_z, x_r, x_n = torch.split(x, self.hidden_dim, dim=1)\n h_z, h_r, h_n = torch.split(h, self.hidden_dim, dim=1)\n \n # GRU logic\n z = F.sigmoid(x_z + h_z)\n r = F.sigmoid(x_r + h_r)\n n = F.tanh(x_n + r*h_n)\n h_t = (1-z)*n + z*h_prev\n return h_t\n \n \n def init_hidden(self, b_s, h, w):\n if torch.cuda.is_available():\n h = torch.zeros(b_s, self.hidden_dim, h, w ).cuda()\n else:\n h = torch.zeros(b_s, self.hidden_dim, h, w)\n return h ","sub_path":"Video-Comp/Models/ConvGRU.py","file_name":"ConvGRU.py","file_ext":"py","file_size_in_byte":2500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"211394528","text":"\"\"\"\nSubject: Introducción a la física computacional en python\nNombre: Ejercicios 2.4, 2.5, 2.6\nAutores: Adrián Felipe Hernández Borda\n Eider David Torres Mesa cod 201811831\n Daniel Felipe Angarita Abril\n\"\"\"\n\n\"\"\"\nspaceship travels from Earth in a straight line at relativistic speed v to\nanother planet x light years away. Write a program to ask the user for the value of x\nand the speed v as a fraction of the speed of light c, then print out the time in years that\nthe spaceship takes to reach its destination (a) in the rest frame of an observer on Earth\nand (b) as perceived by a passenger on board the ship. Use your program to calculate\nthe answers for a planet 10 light years away with v 0.99c.\n\"\"\"\n\"\"\"\nExercise: 2.4\nPurpose: Compute the time interval respect to earth and respect to a spaceship\n required by a spaceship that travels with velocity v from earth to any\n distant planet x lightyears away\n \n\"\"\"\n# load numpy module and pyplot from matplotlib library\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\n\n# define function to find time in earth or spacecraft frame for any especific value of v\n\ndef compute_time(x,v):\n \n global t_spaceship, t_earth\n\n # compute time for both of reference frames\n \n t_earth = np.abs(x/v)\n t_spaceship = np.abs(x / v) * np.sqrt(1 - (v**2))\n # print out the time in the selected frame\n \n print(f'the time measured in earth reference frame is:\\nt = {t_earth:1.2f} years')\n print(f'the time measured in spaceship reference frame is:\\nt = {t_spaceship:1.2f} years')\n\n# define function to plot t in spaceship reference frame\n\ndef plot_time(x,v_s,t_rest,t_moving):\n \n # using numpy define de domain set for velocities\n # linspace function returns a vector with equally spaced numbers between an interval\n \n v = np.linspace(0.001,0.999,200)\n \n # create a range set using time equations\n \n t_s = np.abs(x / v) * np.sqrt(1 - (v**2))\n t_e = np.abs(x/v)\n \n # Create a pyplot figure for plotting\n \n fig = plt.figure()\n # two subfigures are shown in a two columns arrange\n \n # create a subplot in fig for plotting time interval in spacecraft depending on its velocity\n # first subplot, right column\n \n ax = fig.add_subplot(111)\n # title\n ax.set_title(f'Time for traveling to {x:1.2f} light\\nyears away planet.')\n # x and y labels\n ax.set(xlabel=r'$\\beta=\\frac{v}{c}$',ylabel=r'$\\Delta t$ [years]')\n # limits for x and y axis\n ax.set_xlim(0, 1)\n ax.set_ylim(0, t_moving*1e2)\n \n# ax1.set_aspect('equal')\n # Show a grid \n ax.grid(True)\n # \n ax.plot(v, t_s,'k-',label=r\"$\\Delta t' (v)$\")\n ax.plot([v_s],[t_moving],'+k',label=r\"$\\Delta t' = $\" + str(round(t_moving,2)) + r'y for $v = $' + str(round(v_s,2)) + 'c')\n ax.plot(v,t_e,'r-',label=r\"$\\Delta t (v)$\")\n ax.plot([v_s],[t_rest],'+r',label=r\"$\\Delta t = $\" + str(round(t_rest,2)) + r'y for $v = $' + str(round(v_s,2)) + 'c')\n plt.tight_layout()\n plt.legend()\n plt.show() \n\n# main program\n\n# short exlpanation about what this program does\n\nprint(\"This program allows you to find the time dilatation for a spaceship that travels with speed 'v' a fraction of speed of light\")\n\n# enter x and v as floating point variables\n\nx = float(input(\"Enter the distance 'x' in light year \\nx = \"))\nv = float(input(\"Enter the fraction of speed of light 'v', between (0,1)\\nv = \"))\n\n# next line guarantees that user has to enter a number between (0,1) for speed v\n\nwhile np.abs(v) >= 1:\n v = float(input(\"Enter the fraction of speed of light 'v', between (0,1)\\nv = \"))\n\n# call functions to main program\n\ncompute_time(x,v)\nplot_time(x,v,t_earth,t_spaceship)\n","sub_path":"Exercise_2.4.py","file_name":"Exercise_2.4.py","file_ext":"py","file_size_in_byte":3806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"652481550","text":"#!/usr/bin/env python\n\nimport operator\nimport sys\nfrom math import sin, cos, sqrt\n\nops = { '+': operator.add,\n '*': operator.mul,\n '/': operator.truediv,\n 'v': sqrt,\n 'sin': sin,\n 'cos': cos\n\n}\n\ndef calculate(tokens):\n for token in tokens:\n if set(token).issubset(set(\"0123456789.\")):\n stack.append(float(token))\n elif token in ops: # if arithmetic operator is argument\n if expression in ['v', 'sin', 'cos']:\n c = stack.pop()\n op = ops[token]\n stack.append(op(c))\n else:\n if len(stack) < 2:\n raise ValueError('Must have at least two parameters to perform op')\n else:\n a = stack.pop() # get item from top of the stack\n b = stack.pop()\n op = ops[token]\n stack.append(op(b,a))\n elif expression == 'p':\n print(stack[-1])\n elif isinstance(expression,str):\n stack.append(expression.split())\n else:\n raise ValueError(\"Oops! Not valid expression\")\n return(stack)\n\n\nif __name__ == '__main__':\n stack = []\n if len(sys.argv) > 1:\n for i in sys.argv[1:]:\n expression = i\n stack = calculate(expression.split())\n else:\n while True:\n expression = input('> ')\n if expression in ['quit','q','exit']:\n exit()\n elif expression in ['clear','empty']:\n stack = []\n continue\n elif len(expression)==0:\n continue\n stack = calculate(expression.split())\n print(stack)","sub_path":"INF4331/assignment3/rpn.py","file_name":"rpn.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"564103455","text":"# -*- coding: utf-8 -*-\nfrom model.address import Address\nimport allure\n\n\n@allure.story(\"Добавление адреса\")\ndef test_add_address(app, db, json_address, check_ui):\n address = json_address\n old_address = db.get_address_list()\n app.address.create(address)\n # так как было добавление, то количество адресов увеличелось на 1\n assert len(old_address) + 1 == app.address.count()\n # забираем сптсок адресов.\n new_address = db.get_address_list()\n # теперь ручками добавим наши данные в старый список\n old_address.append(address)\n # и он должен совпадать с новым\n assert sorted(old_address, key=Address.id_or_max) == sorted(new_address, key=Address.id_or_max)\n # нужна проверка на UI?\n if check_ui:\n assert sorted(new_address, key=Address.id_or_max) == sorted(app.address.get_address_list(), key=Address.id_or_max)\n\n\n\n","sub_path":"test/test_add_address.py","file_name":"test_add_address.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"562624852","text":"import time\nimport pandas as pd\nimport numpy as np\n\nCITY_DATA = { 'chicago': 'chicago.csv',\n 'new york city': 'new_york_city.csv',\n 'washington': 'washington.csv' }\n\n\"\"\"Get user input - ask for the city the user wants to explore. Ask if they want to filter by month or day of week.\"\"\"\ndef get_filters():\n while True:\n cities = ['chicago', 'new york city', 'washington']\n city = input('What city would you like to know more about: Chicago, New York City or Washington? ')\n if city.lower() in cities:\n break\n else:\n print('Please enter city as shown.')\n while True:\n months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun']\n month = input('Would you like to filter by month? If not, enter: all. If you would like data by month, enter: Jan, Feb, Mar, Apr, May or Jun (as shown). ')\n if month.lower() in months:\n break\n else:\n print('Please enter month as shown.')\n while True:\n days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']\n day = input('Would you like to filter by day of week? If not, enter: all. If you would like data by day, enter: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday or Sunday (as shown). ')\n if day.lower() in days:\n break\n else:\n print('Please enter day as shown.')\n\n print('Great! Let\\'s learn more about {}!'.format(city.title()))\n\n print('-'*40)\n return city, month, day\n\n\"\"\"Read data from csv files and create month, day and hour columns from 'Start Time' column. Filters by month and day if applicable.\"\"\"\ndef load_data(city, month, day):\n df = pd.read_csv(CITY_DATA[city])\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n df['month'] = df['Start Time'].dt.month\n df['day'] = df['Start Time'].dt.weekday_name\n df['hour'] = df['Start Time'].dt.hour\n\n if month != 'all':\n months = ['jan','feb','mar','apr','may','jun']\n month = months.index(month) + 1\n df = df[df['month'] == month]\n\n if day != 'all':\n df = df[df['day'] == day.title()]\n\n return df\n\n\"\"\"Display statistics on the most frequent times of travel - most common month, day of week and hour.\"\"\"\ndef time_stats(df):\n print('\\nCalculating The Most Frequent Times of Travel...\\n')\n start_time = time.time()\n\n popular_month = df['month'].mode()[0]\n print('The most popular month is: ', popular_month)\n\n popular_day = df['day'].mode()[0]\n print('The most popular day is: ', popular_day)\n\n popular_hour = df['hour'].mode()[0]\n print('The most popular hour is: ', popular_hour)\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\"\"\"Display the most commonly used start station, end station and trip. Trip is a new field by concatenating start and end station.\"\"\"\ndef station_stats(df):\n print('\\nCalculating The Most Popular Stations and Trip...\\n')\n start_time = time.time()\n\n popular_start = df['Start Station'].mode()[0]\n print('The most popular start station is: ', popular_start)\n\n popular_end = df['End Station'].mode()[0]\n print('The most popular end station is: ', popular_end)\n\n df['Trip'] = df['Start Station'] + ' to ' + df['End Station']\n popular_trip = df['Trip'].mode()[0]\n print('The most popular trip is: ', popular_trip)\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\"\"\"Display the total and mean travel time.\"\"\"\ndef trip_duration_stats(df):\n print('\\nCalculating Trip Duration...\\n')\n start_time = time.time()\n\n total_travel = df['Trip Duration'].sum()\n print('Total travel time is: ', total_travel)\n\n mean_travel = df['Trip Duration'].mean()\n print('Average travel time is: ', mean_travel)\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\"\"\"Display counts of users types, gender and earliest, latest and most common birth year.\"\"\"\ndef user_stats(df):\n print('\\nCalculating User Stats...\\n')\n start_time = time.time()\n\n user_types = df['User Type'].value_counts()\n print('The number of users per user type is: ', user_types)\n\n while True:\n if 'Gender' in df.columns:\n gender = df['Gender'].value_counts()\n print('The breakdown of gender is: ', gender)\n break\n else:\n break\n while True:\n if 'Birth Year' in df.columns:\n earliest_yob = df['Birth Year'].min()\n most_recent_yob = df['Birth Year'].max()\n most_common_yob = df['Birth Year'].mode()[0]\n print('For this subset of data, birth years of users are between {} and {}. The most common birth year is {}.'.format(earliest_yob, most_recent_yob, most_common_yob))\n break\n else:\n break\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\"\"\"Ask the user if they would like to see the first 5 rows and data. If yes, display first 5 rows. If no, move on.\"\"\"\ndef viewable_df(df):\n while True:\n raw_data = input('\\nTo better understand the data behind these statistics, would you like to see the first 5 rows of raw data? Enter yes or no.\\n')\n if raw_data.lower() == 'yes':\n print(df.head())\n break\n else:\n break\n\n\"\"\"Main code block - run each definition as defined above. Then ask user if they would like to restart the program.\"\"\"\ndef main():\n while True:\n city, month, day = get_filters()\n df = load_data(city, month, day)\n\n time_stats(df)\n station_stats(df)\n trip_duration_stats(df)\n user_stats(df)\n viewable_df(df)\n\n restart = input('\\nWould you like to restart? Enter yes or no.\\n')\n if restart.lower() != 'yes':\n break\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"bikeshare.py","file_name":"bikeshare.py","file_ext":"py","file_size_in_byte":5898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"96069555","text":"import os\nfrom experiment_sd_add import *\n\nos.environ.update(\n OMP_NUM_THREADS = '1',\n OPENBLAS_NUM_THREADS = '1',\n NUMEXPR_NUM_THREADS = '1',\n MKL_NUM_THREADS = '1',\n)\n\nprint(SPLITNS)\n\nimport pandas as pd\nfrom multiprocessing import Pool, cpu_count\nfrom itertools import product\n\n\ndef exp_not_done():\n allexp = pd.DataFrame(product(SPLITNS, DNAMES, DSIZES))\n allexp.columns = ['splitn','dname', 'dsize']\n allexp = allexp.astype({'splitn': 'int32', 'dname' : 'string', 'dsize' : 'int32'})\n WHERE = 'registrysd/'\n _, _, filenames = next(os.walk(WHERE))\n terminated = []\n for i in filenames:\n if not \"times\" in i:\n extra = i.split(\".\")[0].split(\"_\")\n terminated.append([extra[1], extra[0], extra[2]])\n terminated = pd.DataFrame(terminated, columns=['splitn','dname', 'dsize'])\n terminated = terminated.astype({'splitn': 'int32', 'dname' : 'string', 'dsize' : 'int32'})\n notdone = allexp.merge(terminated, how = 'outer', indicator = True).\\\n loc[lambda x : x['_merge'] == 'left_only'][['splitn','dname', 'dsize']]\n print(notdone)\n pool = Pool(32)\n pool.starmap_async(experiment_bi, notdone.itertuples(index = False, name = None))\n pool.close()\n pool.join()\n\nif __name__ == \"__main__\":\n exp_not_done()\n\n","sub_path":"experiment_sd_add_notdone.py","file_name":"experiment_sd_add_notdone.py","file_ext":"py","file_size_in_byte":1291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"181242859","text":"import cv2\nimport numpy as np\nfrom utils.constant import KEY_FRECT, KEY_LABEL, KEY_RECT, KEY_CONFIDENCE, KEY_DWELLING_FRAMES, \\\n ROI_TRACK_AREA, ROI_CROSS_LINE, ROI_ORDER_AREA_1, ROI_ORDER_POINT_1, ROI_ORDER_AREA_2, ROI_ORDER_POINT_2\n\n\nimport utils.logger as logger\n\n# draw utils\nSHOW_IMG_WIDTH = 2000\n\n# grid setting\nGRID_LINE_COLOR = (200, 200, 200)\nGRID_LINE_THICK = 3\n\nCOLR_RECT_FILL = (255, 125, 0)\nCOLR_RECT_BORDER = (0, 0, 255)\nCOLR_TEXT = (255, 255, 0)\n\n\nclass DrawUtils:\n def __init__(self, b_log=True):\n self.b_log = b_log\n\n @staticmethod\n def show_objects(img, objects, offset=(0, 0)):\n ofst_x, ofst_y = offset\n show_img = img.copy()\n img_h, img_w = img.shape[:2]\n\n for obj in objects:\n (x, y, x2, y2) = (obj[KEY_FRECT] * np.array([img_w, img_h, img_w, img_h])).astype(np.int)\n label = obj[KEY_LABEL]\n confidence = float(obj[KEY_CONFIDENCE])\n str_label = \"{}: {:.1f}%\".format(label, confidence * 100)\n # str_label = \"{}\".format(label)\n\n if 0 < x < x2 < img_w and 0 < y < y2 < img_h:\n cv2.rectangle(show_img, (x + ofst_x, y + ofst_y), (x2 + ofst_x, y2 + ofst_y),\n COLR_RECT_BORDER, 2)\n cv2.putText(show_img, str_label, (x + ofst_x, y + ofst_y), cv2.FONT_HERSHEY_SIMPLEX, 0.5,\n COLR_TEXT, 1)\n\n return show_img\n\n def show_trackers(self, trk_img, trackers, mode=\"rect\", fps=25.0, offset=(0, 0)):\n ofst_x, ofst_y = offset\n show_img = trk_img.copy()\n img_h, img_w = trk_img.shape[:2]\n\n for tid in trackers.keys():\n color = COLR_RECT_BORDER\n try:\n [t_x, t_y, t_w, t_h] = trackers[tid][KEY_RECT]\n t_x2 = t_x + t_w\n t_y2 = t_y + t_h\n\n if 0 < t_x < t_x + t_w < img_w and 0 < t_y < t_y + t_h < img_h:\n if mode == \"point\":\n cv2.circle(show_img, (int(t_x + t_w / 2 + ofst_x), int(t_y + t_h / 2 + ofst_y)), 5, color, -1)\n else: # \"rect\"\n cv2.rectangle(show_img, (int(t_x + ofst_x), int(t_y + ofst_y)),\n (int(t_x2 + ofst_x), int(t_y2 + ofst_y)), (0, 0, 255), 2)\n\n str_lbl = \"{}_{}\".format(tid,\n round(trackers[tid][KEY_DWELLING_FRAMES]/fps, 1),\n # round(trackers[tid][KEY_SPEED][0] + trackers[tid][KEY_SPEED][1], 1)\n )\n cv2.putText(show_img, str_lbl, (int(t_x + ofst_x), int(t_y + ofst_y)), cv2.FONT_HERSHEY_SIMPLEX,\n 0.5, (255, 0, 0), 2)\n except Exception as e:\n if self.b_log:\n logger.warn(\"{}_tid:{}\".format(e, tid))\n return show_img\n\n @staticmethod\n def show_roi(img, roi_objs):\n bck = np.zeros_like(img)\n for key in [ROI_TRACK_AREA, ROI_CROSS_LINE, ROI_ORDER_AREA_1, ROI_ORDER_POINT_1, ROI_ORDER_AREA_2,\n ROI_ORDER_POINT_2]:\n roi = roi_objs[key]\n if key == ROI_TRACK_AREA:\n cv2.drawContours(bck, [roi], -1, (0, 255, 0), -1)\n elif key == ROI_CROSS_LINE:\n cv2.line(bck, (roi[0][0], roi[0][1]), (roi[1][0], roi[1][1]), (255, 0, 0), 3)\n elif key == ROI_ORDER_AREA_1:\n cv2.drawContours(bck, [roi], -1, (0, 0, 255), -1)\n elif key == ROI_ORDER_POINT_1:\n cv2.circle(bck, (roi[0][0], roi[0][1]), 3, (255, 0, 0), -1)\n elif key == ROI_ORDER_AREA_2:\n cv2.drawContours(bck, [roi], -1, (0, 0, 255), -1)\n elif key == ROI_ORDER_POINT_2:\n cv2.circle(bck, (roi[0][0], roi[0][1]), 3, (255, 0, 0), -1)\n\n return cv2.addWeighted(img, 0.8, bck, 0.2, 0)\n","sub_path":"src/cv/draw/draw_utils.py","file_name":"draw_utils.py","file_ext":"py","file_size_in_byte":3962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"423092136","text":"\nimport turtle\n\nt = turtle.Turtle()\nt.color('blue')\nt.width(5)\n\ndef line(size):\n\tt.lt(90)\n\tt.fd(size)\n\n\nl = list(map(int, input().split()))\nl.sort(reverse=True)\n\nfor s in l:\n\tx = t.xcor()\n\ty = t.ycor()\n\n\tline(s)\n\n\tt.pu()\n\tt.goto(x,y)\n\n\tt.rt(90)\n\tt.fd(50)\n\tt.pd()\n\t\n\n\n\nturtle.done()\n","sub_path":"2018_2019/____MIPT___/сортировка_черепаха/zadacha_2.py","file_name":"zadacha_2.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"79762848","text":"#!/usr/bin/env python\n\nimport pygtk\nimport gtk\nimport notify2\nimport sys\n\nclass ShitButton():\n def __init__(self):\n notify2.init(\"Multi Action Test\", mainloop='glib')\n\n server_capabilities = notify2.get_server_caps()\n\n n = notify2.Notification(\"Low disk space\",\n \"You can free up some disk space by \" +\n \"emptying the trash can.\")\n n.set_urgency(notify2.URGENCY_CRITICAL)\n n.set_category(\"device\")\n if ('actions' in server_capabilities) or OVERRIDE_NO_ACTIONS:\n #n.add_action(\"one\", \"One\", self.one_cb)\n n.add_action(\"update\", \"Update\", self.update_cb)\n n.add_action(\"redraw\", \"Redraw\", self.redraw_cb)\n n.add_action(\"update_redraw\", \"UpdateRedraw\", self.update_redraw_cb)\n n.connect('closed', self.closed_cb)\n\n n.show()\n\n def one_cb(self, n, action):\n assert action == \"one\"\n print(\"[X] You clicked One\")\n n.update(\"foo\", \"bar\", \"bazz\")\n n.add_action(\"oneone\", \"OneOne\", self.one_cb)\n n.show()\n\n def update_cb(self, n, action):\n assert action == \"update\"\n print(\"[X] update clicked\")\n n.update(\"Updated Summary\", \"Updated Message\")\n n.show()\n\n def redraw_cb(self, n, action):\n assert action == \"redraw\"\n print(\"[X] redraw clicked\")\n nn = notify2.Notification(\"Redrawn Summary\", \"Redrawn Message\")\n nn.add_action(\"redraw\", \"Redraw\", self.redraw_cb)\n nn.show\n\n def update_redraw_cb(self, n, action):\n assert action == \"update_redraw\"\n print(\"[X] update_redraw clicked\")\n nn = notify2.Notification(\"Updated And Redrawn Summary\", \"New Message\")\n nn.add_action(\"update_redraw\", \"UpdateRedraw\", self.update_redraw_cb)\n nn.show\n nn.update(\"N Summary\", \"N Message\")\n nn.show\n\n def closed_cb(self, n):\n print(\"Notification closed\")\n gtk.main_quit()\n\ndef main():\n ShitButton()\n gtk.main()\n\nif __name__ == '__main__':\n main()\n","sub_path":"bin/sendnotification.py","file_name":"sendnotification.py","file_ext":"py","file_size_in_byte":2070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"358573867","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.home, name='home'),\n path('about/', views.about, name='about'),\n path('index/', views.index, name='index'),\n path('plant//', views.sort, name= 'sort'),\n path('recipes/', views.recipes, name='recipes'),\n path('login/', views.login_user, name='login'),\n path('accounts/signup/', views.signup, name='signup'),\n path('addrecipe/new', views.recipe_new, name='newrecipe'),\n path('recipe_add', views.recipe_create, name='create'),\n]","sub_path":"main_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"532549324","text":"from tkinter import *\nfrom tkinter import filedialog\nfrom tkinter import messagebox\n\nfrom src.directory import Directory\nfrom src.fileAssistant import exists_path\n\n# Global variables\n\nroot = None\n\n# Main function\n\ndef main():\n\tglobal root\n\n\troot = root_setup()\n\tload_components(root)\n\n\troot.mainloop()\n\n# GUI functions\n\ndef root_setup():\n\troot = Tk()\n\n\troot.title('Comparador de directorios')\n\troot.resizable(0, 0)\n\n\treturn root\n\ndef load_components(root):\n\t# Vars declaration\n\n\ttextL1 = StringVar()\n\ttextL2 = StringVar()\n\n\tfiling = BooleanVar()\n\tsubdirling = BooleanVar() \n\n\t# Principal frame setup\n\n\tpframe = Frame(root, width=750)\n\tpframe.pack(fill='both', expand=1)\n\n\t# Title and instructions\n\n\tLabel(pframe, text='OSK', font=('Purisa', 22)).pack()\n\tLabel(pframe, text='Selecciona los dos directorios a comparar y personaliza tus opciones').pack()\n\n\t# Secondary frames setup\n\n\tsframe1 = Frame(pframe)\n\tsframe1.pack(fill='x')\n\tsframe1.config(padx=10, pady=10)\n\n\tsframe2 = Frame(pframe)\n\tsframe2.pack(fill='x')\n\tsframe2.config(padx=10, pady=10)\n\n\tsframe3 = Frame(pframe)\n\tsframe3.pack(fill='x')\n\tsframe3.config(padx=10, pady=10)\n\n\tsframe4 = Frame(pframe)\n\tsframe4.pack(fill='x')\n\tsframe4.config(padx=10, pady=10)\n\n\t# Label declaration\n\n\tlabel1 = Label(sframe1)\n\tlabel2 = Label(sframe2)\n\n\t# Buttons setup\n\n\tButton(sframe1, text='Seleccionar directorio', command=ef('open_dir', sv=textL1, lb=label1)).pack(side='left')\n\tButton(sframe2, text='Seleccionar directorio', command=ef('open_dir', sv=textL2, lb=label2)).pack(side='left')\n\n\t# Labels setup\n\n\tlabel1.pack(side='left')\n\tlabel1.config(textvar=textL1, padx=10)\n\tlabel2.pack(side='left')\n\tlabel2.config(textvar=textL2, padx=10)\n\n\t# Checkbuttons setup\n\n\t# Checkbutton(sframe3, text='Escanear subdirectorios', variable=subdirling, onvalue=True, offvalue=False).pack(anchor='w')\n\t# Checkbutton(sframe3, text='Escanear archivos', variable=filing, onvalue=True, offvalue=False).pack(anchor='w')\n\n\tButton(sframe4, text='Comparar', pady=7, command=ef('comparate', path1=textL1, path2=textL2, frame=pframe)).pack()\n\ndef load_process(frame, path1, path2):\n\tglobal root\n\n\tdir1 = Directory(path1)\n\tdir2 = Directory(path2)\n\n\teyepath = 'images/eye.png'\n\teye = PhotoImage(eyepath)\n\n\tframe.pack_forget()\n\n\t# Final frame setup\n\n\tfframe_width = 750\n\n\tfframe = Frame(root, padx=10, pady=10)\n\n\tfframe.pack()\n\n\t# Final secondary frames setup\n\n\tfsframe1 = Frame(fframe)\n\tfsframe1.pack(side='left')\n\tfsframe1.config(padx=10, pady=5, bg='pink')\n\n\tfsframe2 = Frame(fframe)\n\tfsframe2.pack(side='left')\n\tfsframe2.config(padx=10, pady=5, bg='lightblue')\n\n\tfsframe3 = Frame(fframe)\n\tfsframe3.pack(side='bottom')\n\tfsframe3.config(padx=10, pady=5, bg='grey')\n\n\t# Labels setup\n\n\tLabel(fsframe1, image=eye).pack()\n\tLabel(fsframe1, text=dir1.path, fg='blue').pack()\n\n\t\"\"\"for item in dir1.getContent():\n\t\tif isinstance(item, Directory):\n\t\t\tLabel(fsframe1, text=item.getDirectoryName()).pack()\n\t\telse:\n\t\t\tLabel(fsframe1, text=item.getFileName()).pack()\"\"\"\n\n\tLabel(fsframe2, text=dir2.path, fg='blue').pack()\n\n\t\"\"\"for item in dir2.getContent():\n\t\tif isinstance(item, Directory):\n\t\t\tLabel(fsframe2, text=item.getDirectoryName()).pack()\n\t\telse:\n\t\t\tLabel(fsframe2, text=item.getFileName()).pack()\"\"\"\n\n\t# Buttons setup\n\n\tButton(fsframe3, text='Ver diferencias').pack()\n\n# Event functions\n\ndef ef(function, **opts):\n\n\tdef open_directory():\n\t\tpath = filedialog.askdirectory()\n\n\t\tif path:\n\t\t\tif not exists_path(path):\n\t\t\t\topts.get('lb').config(fg='red')\n\t\t\telse:\n\t\t\t\topts.get('lb').config(fg='green')\n\t\t\t\n\t\t\topts.get('sv').set(path)\t\t\t\n\n\tdef comparate():\n\t\tif not exists_path(opts.get('path1').get()):\n\t\t\tmessagebox.showerror('Ruta inválida', 'La primera ruta no es válida, por favor asegurate de que exista')\n\t\telif not exists_path(opts.get('path2').get()):\n\t\t\tmessagebox.showerror('Ruta inválida', 'La segunda ruta no es válida, por favor asegurate de que exista')\n\t\telse:\n\t\t\tload_process(opts.get('frame'), opts.get('path1').get(), opts.get('path2').get())\n\n\tif function == 'open_dir':\n\t\treturn open_directory\n\telif function == 'comparate':\n\t\treturn comparate","sub_path":"src/principal.py","file_name":"principal.py","file_ext":"py","file_size_in_byte":4076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"199259785","text":"'''\nCreated on 17/07/2017\n\n@author: Mk Eng: Francisco Javier Gonzalez Lopez.\n\nThis script allow create a data base of human postures associated with the mood\nand emotions. \n\nThe data type is eulerian angles gotten using the Kinect Sensor and computing \nthe skeleton tracking, then are created .avi and .csv files that have the same\nname defined by the user.\n\nThe Script works with a GUI developed to save new postures and replay the \npostures saved previously, also the GUI show the angles value of each joint.\n'''\n#coding: iso-8859-1\n\n# The wrappers necessaries are imported.\nfrom PyQt4 import uic, QtCore, QtGui # Wrappers that allow used the GUI created.\nfrom pykinect2 import PyKinectV2, PyKinectRuntime # Wrapper used to used the Kinect Sensor.\nimport pygame\nimport ctypes\nimport time\nimport cv2\nimport numpy as np\nfrom cmath import pi\nimport transformations as tf # Wrapper used to handle matrices.\nimport pandas as pd\n\nimport sys \nif sys.hexversion >= 0x03000000:\n import _thread as thread\nelse:\n import thread\n\n# Function that show correctly the text in the GUI.\ntry:\n Encoding = QtGui.QApplication.UnicodeUTF8\n def Translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, Encoding)\nexcept AttributeError:\n def Translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\n# Is defined a vector that has the parameters to draw the skeleton.\nSkeletonColors = [pygame.color.THECOLORS[\"green\"],\n pygame.color.THECOLORS[\"red\"]]\n\n# Are created lists to save the angles of each joint that describe the body posture.\nHeadYawList = list(); HeadRollList = list(); HeadPitchList = list() # Lists for head angles.\nRShoulderRollList = list(); RShoulderPitchList = list() # Lists for right shoulder angles.\nRElbowYawList = list(); RElbowRollList = list() # Lists for right elbow angles.\nRWristYawList = list() # List for right wrist angles.\nRHandList = list() # List for right hand state.\nLShoulderRollList = list(); LShoulderPitchList = list() # Lists for left shoulder angles.\nLElbowYawList = list(); LElbowRollList = list() # Lists for left elbow angles.\nLWristYawList = list() # List for left wrist angles.\nLHandList = list() # List for left hand state.\nWaistRollList = list(); WaistPitchList = list() # Lists for waist angles.\nRHipRollList = list(); RHipPitchList = list() # Lists for right hip angles.\nRKneeYawList = list(); RKneeRollList = list() # Lists for right knee angles.\nLHipRollList = list(); LHipPitchList = list() # Lists for left hip angles.\nLKneeYawList = list(); LKneeRollList = list() # Lists for left knee angles.\n\nEmotion = list() # List used to save the emotion that represent each posture.\n\n# Is created a list with the header of each column used to create a .csv file.\nHeader = ['Head Yaw','Head Roll','Head Pitch',\n 'Right Shoulder Roll','Right Shoulder Pitch',\n 'Right Elbow Yaw','Right Elbow Roll',\n 'Right Wrist Yaw',\n 'Right Hand',\n 'Left Shoulder Roll','Left Shoulder Pitch',\n 'Left Elbow Yaw','Left Elbow Roll',\n 'Left Wrist Yaw',\n 'Left Hand',\n 'Waist Roll', 'Waist Pitch',\n 'Right Hip Roll', 'Right Hip Pitch',\n 'Right Knee Yaw', 'Right Knee Roll',\n 'Left Hip Roll', 'Left Hip Pitch',\n 'Left Knee Yaw', 'Left Knee Roll',\n 'Emotion']\n\nENABLE_WRIST = True # Is activated the tracking of the wrist.\n\ndef add_angles(alpha, beta):\n '''\n This function return the add of two angles, getting the result\n into the interval [-pi,pi]\n '''\n Add = alpha + beta\n\n while np.abs(Add) > (2*pi):\n if Add > 0:\n Add -= 2*pi\n else:\n Add += 2*pi \n\n if Add > pi:\n return Add - (2*pi) \n elif Add < -pi:\n return Add + (2*pi) \n else:\n return Add \n \nclass HumanPostureAndEmotion(QtGui.QWidget):\n '''\n Main class that allow the operation of the system using the GUI created, to\n show the image gotten using the Kinect Sensor, and compute the skeleton \n tracking to get the body posture.\n '''\n def __init__(self):\n '''\n Function that initialize the GUI parameters and connect them with the\n corresponding functions.\n '''\n super(HumanPostureAndEmotion, self).__init__()\n \n # Is loaded the file that get the GUI. \n self.MyGUI = uic.loadUi('...\\Emotions Data Base Creator\\DataBaseCreatorHumanPostureGUI.ui', self)\n\n # Are associated the different options that have the GUI with its corresponding functions.\n self.connect(self.Btn_Kinect, QtCore.SIGNAL(\"clicked()\"), self.InitKinect)\n self.connect(self.Btn_REC, QtCore.SIGNAL(\"clicked()\"), self.Recording)\n self.connect(self.Btn_Save, QtCore.SIGNAL(\"clicked()\"), self.SavePosture)\n self.connect(self.Btn_Load, QtCore.SIGNAL(\"clicked()\"), self.LoadPosture)\n self.connect(self.Btn_End, QtCore.SIGNAL(\"clicked()\"), self.EndProgram)\n self.connect(self.Btn_Select_Emotion, QtCore.SIGNAL(\"clicked()\"), self.SelectEmotion) \n \n # Are created timers to have interruptions that allow execute functions.\n self.Timer = QtCore.QTimer(self.MyGUI) # Timer that control the image tracking.\n self.Timer.timeout.connect(self.ShowFrame) # The timer active the Tracking function.\n \n self.Timer1 = QtCore.QTimer(self.MyGUI) # Timer that control the playing of .avi file.\n self.Timer1.timeout.connect(self.ShowVideo) # The timer active the playing of .avi file.\n \n # Is created a pixel map to put in the GUI the image get with the Kinect Sensor.\n self.pixmap = QtGui.QPixmap()\n \n self.StartEnd = 1 # Flag to start or end the Kinect Sensor. \n\n self.MyGUI.show()\n \n def InitKinect(self):\n '''\n Function that start or End the Kinect Sensor.\n '''\n # Connect Kinect.\n if self.StartEnd == 1:\n # Are configured the parameters to use the Kinect Sensor.\n pygame.init()\n self.Clock = pygame.time.Clock()\n self.Kinect = PyKinectRuntime.PyKinectRuntime(PyKinectV2.FrameSourceTypes_Color | PyKinectV2.FrameSourceTypes_Body)\n self.FrameSurface = pygame.Surface((self.Kinect.color_frame_desc.Width, self.Kinect.color_frame_desc.Height), 0, 32)\n \n self.Bodies = None # Variable used to saved the bodies detected.\n \n self.Box_Emotion_Selector.setEnabled(True) # Enabled the emotions selection.\n self.Text_Save.setText(\"Digit File Name\") # Indicate to the user that put the .avi and .cvs files names.\n self.Btn_Kinect.setText(\"Desconect Kinect\") # Change the text in the GUI button.\n \n self.StartEnd = 0 # Change flag's value to end the Kinect Sensor. \n self.StartRec = 0 # Change flag's value to end the recording.\n \n # Disconnect Kinect. \n else:\n try:\n self.Box_Emotion_Selector.setEnabled(False) # Disabled the emotions selection.\n \n self.Text_Save.setEnabled(False) # Disabled the text box to put the .avi and .csv files names. \n \n self.Text_Save.setText(\"Digit File Name\") # Indicate to the user that put the .avi and .cvs files names.\n \n self.Btn_Kinect.setText(\"Conect Kinect\") # Change the text in the GUI button.\n \n self.Btn_REC.setText(\"REC\") # Change the text in the GUI button.\n \n self.StartEnd = 1 # Change flag's value to start the Kinect Sensor.\n \n self.Kinect.close() # End the Kinect Sensor.\n \n pygame.quit()\n\n self.VideoFile.release() # End the creation of .avi file. \n except:\n pass\n \n def Recording(self):\n '''\n Function that allow the recording of the boy posture in a limited time.\n '''\n # Start recording.\n if self.StartRec == 0:\n self.Btn_REC.setText(\"STOP\") # Change the text in the GUI button.\n self.Btn_Save.setEnabled(False) # Disabled the option that allow save .avi and .csv files.\n self.Text_Save.setEnabled(False) # Disabled the option to put the name of the .avi and .csv files. \n self.Text_Load.setEnabled(False) # Disabled the option to that allow load .avi and .csv files.\n self.Btn_Load.setEnabled(False) # Disabled the option to put the name to select .avi and .csv files saved.\n self.frame_2.setEnabled(True) # Enabled the joint angles information.\n \n self.CreateAviFile() # Is created the .avi file.\n \n # Are imported like global the lists used to save the information. \n global HeadYawList, HeadRollList, HeadPitchList\n \n global RShoulderRollList, RShoulderPitchList\n global RElbowYawList, RElbowRollList\n global RWristYawList\n global RHandList\n \n global LShoulderRollList, LShoulderPitchList\n global LElbowYawList, LElbowRollList\n global LWristYawList\n global LHandList\n \n global WaistRollList, WaistPitchList\n \n global RHipRollList, RHipPitchList \n global RKneeYawList, RKneeRollList\n \n global LHipRollList, LHipPitchList \n global LKneeYawList, LKneeRollList\n \n global Emotion\n \n # Are cleared the lists used to save the information.\n HeadYawList = []; HeadRollList = []; HeadPitchList = []\n \n RShoulderRollList = []; RShoulderPitchList = []\n RElbowYawList = []; RElbowRollList = []\n RWristYawList = []\n RHandList = []\n \n LShoulderRollList = []; LShoulderPitchList = []\n LElbowYawList = []; LElbowRollList = []\n LWristYawList = []\n LHandList = []\n \n WaistRollList = []; WaistPitchList = []\n \n RHipRollList = []; RHipPitchList = []\n RKneeYawList = []; RKneeRollList = []\n \n LHipRollList = []; LHipPitchList = []\n LKneeYawList = []; LKneeRollList = []\n \n Emotion = []\n \n time.sleep(2) # Delay used to leave the user prepare him.\n \n self.Segundos = 0 # Counter that limit the recording.\n \n self.Timer.start(1) # Activate the interruption that get the skeleton tracking.\n \n self.StartRec = 1 # Change the flag's value to end the recording.\n \n # Stop recording.\n else:\n self.Timer.stop() # Deactivate the interruption that get the skeleton tracking. \n\n try: # End the creation of the .avi file.\n self.VideoFile.release()\n except AttributeError:\n pass\n\n self.Btn_REC.setText(\"REC\") # Indicate the user that can start the recording.\n self.Btn_Save.setEnabled(True) # Enabled the button that allow save the .avi and .csv files.\n self.Text_Save.setEnabled(True) # Enabled the option to put the name of the .avi and .csv files.\n self.Box_Emotion_Selector.setEnabled(True) # Enabled the emotions selection.\n self.frame_2.setEnabled(False) # Disabled the joint angles information.\n self.Text_Load.setEnabled(True) # Enabled the text box to select with the name a .csv file saved.\n self.Btn_Load.setEnabled(True) # Enabled the option to load a a .avi and .csv file saved.\n\n self.StartRec = 0 # Change the flag's value to start the recording.\n \n def SavePosture(self):\n '''\n Function that verify the saved angles value and create the .csv file.\n '''\n # The current lines verify each angle searching for a \"None\", if it is \n # found is changed for the previous correct angle value in each array; \n # The waist angles are not verify because the logic used in the function:\n # Angles.\n for M in range(0,len(WaistRollList)):\n \n # Head.\n if HeadPitchList[M] == None and HeadYawList[M] == None and HeadRollList[M] == None:\n HeadYawList[M] = HeadYawList[M-1]\n HeadPitchList[M] = HeadPitchList[M-1]\n HeadRollList[M] = HeadRollList[M-1]\n \n # Right shoulder.\n if RShoulderPitchList[M] == None and RShoulderRollList[M] == None:\n RShoulderPitchList[M] = RShoulderPitchList[M-1]\n RShoulderRollList[M] = RShoulderRollList[M-1]\n \n # Right elbow.\n if RElbowYawList[M] == None and RElbowRollList[M] == None:\n RElbowYawList[M] = RElbowYawList[M-1]\n RElbowRollList[M] = RElbowRollList[M-1]\n \n # Right wrist.\n if RWristYawList[M] == None:\n RWristYawList[M] = RWristYawList[M-1]\n \n # Right hand.\n if RHandList[M] == None:\n RHandList[M] = RHandList[M-1]\n \n # Left shoulder.\n if LShoulderPitchList[M] == None and LShoulderRollList[M] == None:\n LShoulderPitchList[M] = LShoulderPitchList[M-1]\n LShoulderRollList[M] = LShoulderRollList[M-1]\n \n # Left elbow.\n if LElbowYawList[M] == None and LElbowRollList[M] == None:\n LElbowYawList[M] = LElbowYawList[M-1]\n LElbowRollList[M] = LElbowRollList[M-1]\n \n # Left wrist.\n if LWristYawList[M] == None:\n LWristYawList[M] = LWristYawList[M-1]\n \n # Left hand.\n if LHandList[M] == None:\n [M] = LHandList[M-1]\n\n # Right hip.\n if RHipRollList[M] == None and RHipPitchList[M] == None:\n RHipRollList[M] = RHipRollList[M-1]\n RHipPitchList[M] = RHipPitchList[M-1]\n\n # Right knee.\n if RKneeRollList[M] == None and RKneeYawList[M] == None:\n RKneeRollList[M] = RKneeRollList[M-1]\n RKneeYawList[M] = RKneeYawList[M-1]\n\n # Left hip.\n if LHipRollList[M] == None and LHipPitchList[M] == None:\n LHipRollList[M] = LHipRollList[M-1]\n LHipPitchList[M] = LHipPitchList[M-1]\n\n # Left knee.\n if LKneeRollList[M] == None and LKneeYawList[M] == None:\n LKneeRollList[M] = LKneeRollList[M-1]\n LKneeYawList[M] = LKneeYawList[M-1]\n \n # Is saved the name of the .csv file.\n FileName = str(\"...\\Emotions Data Base Creator\\Motion sequences\\ \" + str(self.Text_Save.text()) + \".csv\")\n \n # Is created the .csv file.\n File = open(FileName, 'w') \n \n # Is saved the header in the .csv file.\n for M in range(0,len(Header)):\n File.write(str(Header[M]))\n if M < len(Header)-1:\n File.write(\",\")\n \n File.write(\"\\n\")\n \n # Are saved in the .csv file the joint angles.\n for M in range(0,len(WaistPitchList)):\n \n File.write(str(HeadYawList[M])); File.write(\",\"); File.write(str(HeadRollList[M])); File.write(\",\"); File.write(str(HeadPitchList[M])); File.write(\",\")\n \n File.write(str(RShoulderRollList[M])); File.write(\",\"); File.write(str(RShoulderPitchList[M])); File.write(\",\")\n File.write(str(RElbowYawList[M])); File.write(\",\"); File.write(str(RElbowRollList[M])); File.write(\",\")\n File.write(str(RWristYawList[M])); File.write(\",\") \n File.write(str(RHandList[M])); File.write(\",\");\n \n File.write(str(LShoulderRollList[M])); File.write(\",\"); File.write(str(LShoulderPitchList[M])); File.write(\",\")\n File.write(str(LElbowYawList[M])); File.write(\",\"); File.write(str(LElbowRollList[M])); File.write(\",\")\n File.write(str(LWristYawList[M])); File.write(\",\") \n File.write(str(LHandList[M])); File.write(\",\") \n\n File.write(str(WaistRollList[M])); File.write(\",\"); File.write(str(WaistPitchList[M])); File.write(\",\") \n \n File.write(str(RHipRollList[M])); File.write(\",\"); File.write(str(RHipPitchList[M])); File.write(\",\")\n File.write(str(RKneeYawList[M])); File.write(\",\"); File.write(str(RKneeRollList[M])); File.write(\",\")\n \n File.write(str(LHipRollList[M])); File.write(\",\"); File.write(str(LHipPitchList[M])); File.write(\",\") \n File.write(str(LKneeYawList[M])); File.write(\",\"); File.write(str(LKneeRollList[M])); File.write(\",\")\n \n File.write(str(Emotion[M]))\n \n File.write(\"\\n\")\n \n File.close() # Close the .csv file.\n \n self.Text_Save.setText(\"\") # Cleared the text box to put a new name to .csv file.\n self.Btn_Save.setEnabled(False) # Disabled the option to create a new .csv file.\n \n def LoadPosture(self):\n '''\n Function that allow load a .avi and .csv file to be played.\n '''\n # Is disconnected the Kinect Sensor.\n try:\n self.Kinect.close()\n pygame.quit()\n except AttributeError:\n pass \n \n self.StartEnd = 1 # Change the flag's value to start the skeleton tracking.\n \n self.Btn_Kinect.setText(\"Conect Kinect\") # Change the text in the GUI button.\n self.Btn_REC.setEnabled(False) # Disabled the recording option.\n \n # Are imported like global the lists used to save the information. \n global HeadYawList, HeadRollList, HeadPitchList\n \n global RShoulderRollList, RShoulderPitchList\n global RElbowYawList, RElbowRollList\n global RWristYawList\n global RHandList\n \n global LShoulderRollList, LShoulderPitchList\n global LElbowYawList, LElbowRollList\n global LWristYawList\n global LHandList\n \n global WaistRollList, WaistPitchList\n \n global RHipRollList, RHipPitchList \n global RKneeYawList, RKneeRollList\n \n global LHipRollList, LHipPitchList \n global LKneeYawList, LKneeRollList\n \n # Are cleared the lists used to save the information.\n HeadYawList = []; HeadRollList = []; HeadPitchList = []\n \n RShoulderRollList = []; RShoulderPitchList = []\n RElbowYawList = []; RElbowRollList = []\n RWristYawList = []\n RHandList = []\n \n LShoulderRollList = []; LShoulderPitchList = []\n LElbowYawList = []; LElbowRollList = []\n LWristYawList = []\n LHandList = []\n \n WaistRollList = []; WaistPitchList = []\n \n RHipRollList = []; RHipPitchList = []\n RKneeYawList = []; RKneeRollList = []\n \n LHipRollList = []; LHipPitchList = []\n LKneeYawList = []; LKneeRollList = []\n \n # Are loaded the .avi and .csv files\n try: \n # .csv file.\n FileName = str(\"...\\Emotions Data Base Creator\\Motion sequences\\ \" + str(self.Text_Load.text()) + \".csv\")\n File = pd.read_csv(FileName, header = 0)\n\n # .avi file.\n VideoName = str(\"...\\Emotions Data Base Creator\\Motion sequences\\ \" + str(self.Text_Load.text()) + \".avi\")\n self.Video = cv2.VideoCapture(VideoName)\n\n FileLoad = 1 # Check the correct load.\n \n except:\n FileLoad = 0 # Check the incorrect load.\n pass\n \n # If the .avi and .csv files are loaded correctly:\n # the information of each angle is saved in the corresponding list, and \n # then is played the .avi file while are showed the angles in the GUI.\n if FileLoad == 1:\n self.Text_Load.setText(\"\") # Cleared the text box to put the name of the .avi and .csv files.\n \n # Head angles.\n HeadYawList = File['Head Yaw']; HeadRollList = File['Head Roll']; HeadPitchList = File['Head Pitch']\n\n # Right arm angles.\n RShoulderRollList = File['Right Shoulder Roll']; RShoulderPitchList = File['Right Shoulder Pitch']\n RElbowYawList = File['Right Elbow Yaw']; RElbowRollList = File['Right Elbow Roll']\n RWristYawList = File['Right Wrist Yaw']\n RHandList = File['Right Hand']\n\n # Left arm angles.\n LShoulderRollList = File['Left Shoulder Roll']; LShoulderPitchList = File['Left Shoulder Pitch']\n LElbowYawList = File['Left Elbow Yaw']; LElbowRollList = File['Left Elbow Roll']\n LWristYawList = File['Left Wrist Yaw']\n LHandList = File['Left Hand']\n \n # Waist angles.\n WaistRollList = File['Waist Roll']; WaistPitchList = File['Waist Pitch']\n \n # Right leg angles.\n RHipRollList = File['Right Hip Roll']; RHipPitchList = File['Right Hip Pitch']\n RKneeYawList = File['Right Knee Yaw']; RKneeRollList = File['Right Knee Roll']\n \n # Left leg angles.\n LHipRollList = File['Left Hip Roll']; LHipPitchList = File['Left Hip Pitch']\n LKneeYawList = File['Left Knee Yaw']; LKneeRollList = File['Left Knee Roll']\n \n # Time limit to played the .avi file.\n if len(HeadYawList) < 30: \n self.Limit = 27\n else:\n self.Limit = len(HeadPitchList) - 1\n\n self.Sec = 0 # Counter used to play the .avi file.\n \n self.Timer1.start(1) # Activate the interruption that show the .avi frames in the GUI.\n \n # Is the .avi and .csv files load is not correct.\n else:\n self.Text_Load.setText(\"Put a valid name\") # The user is informed that the .avi and .csv files names are incorrect.\n \n self.Btn_Save.setEnabled(False) # Disabled the option to create a new .csv file.\n \n def EndProgram(self):\n '''\n Function that end the tracking and close the program.\n '''\n try:\n self.Kinect.Stop_Kinect() # Stop Kinect V2 Camera.\n pygame.quit() # End visualization of kinect's image.\n\n sys.exit() # Close the GUI. \n except:\n sys.exit() # Close the GUI. \n \n def SelectEmotion(self):\n '''\n Function that allow select the emotion that the user goes to represent.\n '''\n if self.RadioBtn_Happy.isChecked():\n self.EmotionAsocieted = \"Happy\"\n\n if self.RadioBtn_Sad.isChecked():\n self.EmotionAsocieted = \"Sad\"\n\n if self.RadioBtn_Angry.isChecked():\n self.EmotionAsocieted = \"Angry\"\n \n if self.RadioBtn_Surprised.isChecked():\n self.EmotionAsocieted = \"Surprised\"\n \n if self.RadioBtn_Reflexive.isChecked():\n self.EmotionAsocieted = \"Reflexive\"\n \n if self.RadioBtn_Insecure.isChecked():\n self.EmotionAsocieted = \"Insecure\"\n \n if self.RadioBtn_Trusted.isChecked():\n self.EmotionAsocieted = \"Trusted\"\n \n if self.RadioBtn_Normal.isChecked():\n self.EmotionAsocieted = \"Normal\"\n \n self.Text_Save.setEnabled(False) # Disabled the option to put a name for .avi and .csv files.\n self.Box_Emotion_Selector.setEnabled(False) # Disabled the emotion selection.\n self.Btn_REC.setEnabled(True) # Enabled the recording option.\n \n def ShowVideo(self):\n '''\n Function that allow show in the GUI the frames loaded from the .avi file\n and also show the angles information loaded from the .csv file.\n '''\n Image = self.Video.read()[1] # Load a frame from the .avi file. \n \n # Create a pixel map from the Kinect's image.\n Image = QtGui.QImage(Image, 1080, 630, 3240 , QtGui.QImage.Format_RGB888)\n self.pixmap.convertFromImage(Image.rgbSwapped())\n self.KinectFrame.setPixmap(self.pixmap) # Show the Kinect's image in the GUI.\n \n # Show the angles information loaded from the .csv file in the GUI.\n self.Text_Hip_Pitch.setText(str(\"%.3f\" %(WaistPitchList[self.Sec])))\n self.Text_Hip_Roll.setText(str(\"%.3f\" %(WaistRollList[self.Sec])))\n \n self.Text_RHip_Pitch.setText(str(\"%.3f\" %(RHipPitchList[self.Sec])))\n self.Text_RHip_Roll.setText(str(\"%.3f\" %(RHipRollList[self.Sec])))\n \n self.Text_RKnee_Roll.setText(str(\"%.3f\" %(RKneeRollList[self.Sec])))\n self.Text_RKnee_Yaw.setText(str(\"%.3f\" %(RKneeYawList[self.Sec])))\n \n self.Text_LHip_Pitch.setText(str(\"%.3f\" %(LHipPitchList[self.Sec])))\n self.Text_LHip_Roll.setText(str(\"%.3f\" %(LHipRollList[self.Sec])))\n \n self.Text_LKnee_Roll.setText(str(\"%.3f\" %(LKneeRollList[self.Sec])))\n self.Text_LKnee_Yaw.setText(str(\"%.3f\" %(LKneeYawList[self.Sec])))\n \n self.Text_Head_Pitch.setText(str(\"%.3f\" %(HeadPitchList[self.Sec])))\n self.Text_Head_Roll.setText(str(\"%.3f\" %(HeadRollList[self.Sec])))\n self.Text_Head_Yaw.setText(str(\"%.3f\" %(HeadYawList[self.Sec])))\n \n self.Text_RShoulder_Pitch.setText(str(\"%.3f\" %(RShoulderPitchList[self.Sec])))\n self.Text_RShoulder_Roll.setText(str(\"%.3f\" %(RShoulderRollList[self.Sec])))\n \n self.Text_RElbow_Yaw.setText(str(\"%.3f\" %(RElbowYawList[self.Sec])))\n self.Text_RElbow_Roll.setText(str(\"%.3f\" %(RElbowRollList[self.Sec])))\n \n self.Text_RWrist_Yaw.setText(str(\"%.3f\" %(RWristYawList[self.Sec])))\n \n self.Text_RHand.setText(RHandList[self.Sec])\n \n self.Text_LShoulder_Pitch.setText(str(\"%.3f\" %(LShoulderPitchList[self.Sec])))\n self.Text_LShoulder_Roll.setText(str(\"%.3f\" %(LShoulderRollList[self.Sec])))\n \n self.Text_LElbow_Yaw.setText(str(\"%.3f\" %(LElbowYawList[self.Sec])))\n self.Text_LElbow_Roll.setText(str(\"%.3f\" %(LElbowRollList[self.Sec])))\n \n self.Text_LWrist_Yaw.setText(str(\"%.3f\" %(LWristYawList[self.Sec])))\n \n self.Text_LHand.setText(LHandList[self.Sec])\n\n # End the playing of the .avi and .csv file.\n if self.Sec == self.Limit:\n self.Timer1.stop()\n self.Video.release()\n\n self.Sec += 1\n\n def ShowFrame(self):\n '''\n Main function that allow the skeleton tracking and get the body posture\n to save the joint angles and then create the .avi and .cvs files.\n '''\n self.Segundos += 1\n \n # Deactive the timer in the limit time.\n if self.Segundos == 29:\n self.Timer.stop() # Deactivate the interruption that get the skeleton tracking. \n \n try: # End the creation of the .avi file.\n self.VideoFile.release()\n except AttributeError:\n pass\n \n self.Btn_REC.setText(\"REC\") # Indicate the user that can start the recording.\n self.Btn_Save.setEnabled(True) # Enabled the button that allow save the .avi and .csv files.\n self.Text_Save.setEnabled(True) # Enabled the option to put the name of the .avi and .csv files.\n self.Box_Emotion_Selector.setEnabled(True) # Enabled the emotions selection.\n self.frame_2.setEnabled(False) # Disabled the joint angles information.\n self.Text_Load.setEnabled(True) # Enabled the text box to select with the name a .csv file saved.\n self.Btn_Load.setEnabled(True) # Enabled the option to load a a .avi and .csv file saved.\n \n self.StartRec = 0 # Change the flag's value to start the recording.\n \n return\n\n # Is reshape the Kinect's image in the format that allow cv2.\n self.Image = pygame.surfarray.array3d(self.FrameSurface) # Pygame's surface is converted in an array. \n self.Image = np.rollaxis(self.Image, 0, 2) # Reform the structure of the array.\n \n # Is reformat and reshape the Image to be put in the GUI.\n self.Image = cv2.cvtColor(self.Image, cv2.COLOR_RGB2BGR)\n self.Image = cv2.resize(self.Image,(1080,630), interpolation = cv2.INTER_CUBIC)\n \n if self.Kinect.has_new_color_frame():\n Frame = self.Kinect.get_last_color_frame() # Save the image get with the Kinect V2 Camera.\n self.DrawColorFrame(Frame, self.FrameSurface) \n Frame = None\n \n if self.Kinect.has_new_body_frame(): \n self.Bodies = self.Kinect.get_last_body_frame() # Save the bodies present in the image.\n\n if self.Bodies is not None:\n Body = self.SelectNearestBody() # Select the nearest body.\n\n if Body is not None: # Draw and compute the body's joint angles.\n Joints = Body.joints\n JointsPoints = self.Kinect.body_joints_to_color_space(Joints)\n Orientations = Body.joint_orientations \n self.DrawBody(Joints, JointsPoints, SkeletonColors)\n self.Angles(Joints, Orientations, Body) \n \n # Is the .avi file option is selected.\n if self.CreateVideoFile == 1:\n self.VideoFile.write(self.Image) # Save a new frame in the .avi file.\n \n # Create a pixel map from the Kinect's image.\n self.Image = QtGui.QImage(self.Image, 1080, 630, 3240 , QtGui.QImage.Format_RGB888)\n self.pixmap.convertFromImage(self.Image.rgbSwapped()) # Specify a RGB format.\n self.KinectFrame.setPixmap(self.pixmap) # Show the Kinect's image in the GUI.\n \n self.Clock.tick(60)\n\n def CreateAviFile(self):\n '''\n Function that create .avi file with the format selected.\n '''\n # Is saved the name of the .avi file\n VideoFilePath = str(\"...\\Emotions Data Base Creator\\Motion sequences\\ \" + str(self.Text_Save.text()) + \".avi\")\n \n # Is defined the format of the file.\n VideoFileType = cv2.VideoWriter_fourcc('M','J','P','G') \n \n # Is created the .avi file.\n self.VideoFile = cv2.VideoWriter(VideoFilePath, VideoFileType, 10.0, (1080,630))\n\n def DrawColorFrame(self, Frame, TargetSurface):\n '''\n Function that decode the image get with the Kinect Sensor and \n convert it in a compatible color image puting it in a pygame's surface.\n '''\n TargetSurface.lock()\n address = self.Kinect.surface_as_array(TargetSurface.get_buffer()) # Function that get the color image and save the frame.\n ctypes.memmove(address, Frame.ctypes.data, Frame.size) # C function that return a compatible color image.\n del address\n TargetSurface.unlock()\n\n def SelectNearestBody(self):\n '''\n Function that determined the nearest body in the image get with the \n Kinect Sensor and return the information of that body.\n '''\n NearestBody = None\n NearestDistance = float('inf')\n \n for i in range(0, self.Kinect.max_body_count):\n Body = self.Bodies.bodies[i] \n if not Body.is_tracked: \n continue\n \n Spine = Body.joints[PyKinectV2.JointType_SpineBase].Position # Spine coordinates.\n Distance = np.sqrt((Spine.x**2)+(Spine.y**2)+(Spine.z**2)) # Compute the eucledian distance of the body to the Kinect Sensor.\n\n if Distance < NearestDistance:\n NearestDistance = Distance\n NearestBody = Body\n \n return NearestBody \n\n def DrawBody(self, Joints, JointsPoints, Color):\n '''\n Function that send the parameters get with the Kinect Sensor\n to draw the skeleton.\n '''\n # Torso\n self.DrawBodyBones(Joints, JointsPoints, Color, PyKinectV2.JointType_Head, PyKinectV2.JointType_Neck)\n self.DrawBodyBones(Joints, JointsPoints, Color, PyKinectV2.JointType_Neck, PyKinectV2.JointType_SpineShoulder)\n self.DrawBodyBones(Joints, JointsPoints, Color, PyKinectV2.JointType_SpineShoulder, PyKinectV2.JointType_SpineMid)\n self.DrawBodyBones(Joints, JointsPoints, Color, PyKinectV2.JointType_SpineMid, PyKinectV2.JointType_SpineBase)\n self.DrawBodyBones(Joints, JointsPoints, Color, PyKinectV2.JointType_SpineShoulder, PyKinectV2.JointType_ShoulderRight)\n self.DrawBodyBones(Joints, JointsPoints, Color, PyKinectV2.JointType_SpineShoulder, PyKinectV2.JointType_ShoulderLeft)\n self.DrawBodyBones(Joints, JointsPoints, Color, PyKinectV2.JointType_SpineBase, PyKinectV2.JointType_HipRight)\n self.DrawBodyBones(Joints, JointsPoints, Color, PyKinectV2.JointType_SpineBase, PyKinectV2.JointType_HipLeft)\n \n # Right Arm\n self.DrawBodyBones(Joints, JointsPoints, Color, PyKinectV2.JointType_ShoulderRight, PyKinectV2.JointType_ElbowRight)\n self.DrawBodyBones(Joints, JointsPoints, Color, PyKinectV2.JointType_ElbowRight, PyKinectV2.JointType_WristRight)\n self.DrawBodyBones(Joints, JointsPoints, Color, PyKinectV2.JointType_WristRight, PyKinectV2.JointType_HandRight)\n self.DrawBodyBones(Joints, JointsPoints, Color, PyKinectV2.JointType_HandRight, PyKinectV2.JointType_HandTipRight)\n self.DrawBodyBones(Joints, JointsPoints, Color, PyKinectV2.JointType_WristRight, PyKinectV2.JointType_ThumbRight)\n\n # Left Arm\n self.DrawBodyBones(Joints, JointsPoints, Color, PyKinectV2.JointType_ShoulderLeft, PyKinectV2.JointType_ElbowLeft)\n self.DrawBodyBones(Joints, JointsPoints, Color, PyKinectV2.JointType_ElbowLeft, PyKinectV2.JointType_WristLeft)\n self.DrawBodyBones(Joints, JointsPoints, Color, PyKinectV2.JointType_WristLeft, PyKinectV2.JointType_HandLeft)\n self.DrawBodyBones(Joints, JointsPoints, Color, PyKinectV2.JointType_HandLeft, PyKinectV2.JointType_HandTipLeft)\n self.DrawBodyBones(Joints, JointsPoints, Color, PyKinectV2.JointType_WristLeft, PyKinectV2.JointType_ThumbLeft)\n\n # Right Leg\n self.DrawBodyBones(Joints, JointsPoints, Color, PyKinectV2.JointType_HipRight, PyKinectV2.JointType_KneeRight);\n self.DrawBodyBones(Joints, JointsPoints, Color, PyKinectV2.JointType_KneeRight, PyKinectV2.JointType_AnkleRight);\n self.DrawBodyBones(Joints, JointsPoints, Color, PyKinectV2.JointType_AnkleRight, PyKinectV2.JointType_FootRight);\n\n # Left Leg\n self.DrawBodyBones(Joints, JointsPoints, Color, PyKinectV2.JointType_HipLeft, PyKinectV2.JointType_KneeLeft);\n self.DrawBodyBones(Joints, JointsPoints, Color, PyKinectV2.JointType_KneeLeft, PyKinectV2.JointType_AnkleLeft);\n self.DrawBodyBones(Joints, JointsPoints, Color, PyKinectV2.JointType_AnkleLeft, PyKinectV2.JointType_FootLeft);\n\n def Angles(self, Joints, Orientations, Body):\n '''\n Function that calculated the joint's angles of the skeleton get with the\n Kinect Sensor, getting the quaternion matrix and then calculating the\n eulerian angles.\n \n If the skeleton tracking is not correct, complete or parcial, the \n corresponding angles are define like \"None\"; after that the angle are \n verified, they are saved in the corresponding lists.\n \n The angles are showed in the GUI.\n ''' \n # Hip angles.\n if (Joints[PyKinectV2.JointType_SpineShoulder].TrackingState == 2) and (Joints[PyKinectV2.JointType_SpineBase].TrackingState == 2):\n Emotion.append(self.EmotionAsocieted) # Save the name of the emotion that is represented. \n \n ChestQuat = self.Quaternion(Orientations, PyKinectV2.JointType_SpineBase) \n HipAngles = tf.euler_from_quaternion(ChestQuat, 'syzx') \n \n WaistPitch = HipAngles[2]; self.Text_Hip_Pitch.setText(str(\"%.3f\" %(WaistPitch)))\n WaistRoll = HipAngles[1]; self.Text_Hip_Roll.setText(str(\"%.3f\" %(WaistRoll)))\n \n WaistPitchList.append(WaistPitch) \n WaistRollList.append(WaistRoll)\n \n # Right leg angles.\n if (Joints[PyKinectV2.JointType_HipRight].TrackingState == 2) and (Joints[PyKinectV2.JointType_KneeRight].TrackingState == 2):\n LegQuat = self.Quaternion(Orientations, PyKinectV2.JointType_KneeRight, PyKinectV2.JointType_HipRight )\n LegAngles = tf.euler_from_quaternion(LegQuat, 'syzx')\n \n RHipPitch = LegAngles[2]; self.Text_RHip_Pitch.setText(str(\"%.3f\" %(RHipPitch)))\n RHipRoll = LegAngles[1]; self.Text_RHip_Roll.setText(str(\"%.3f\" %(RHipRoll)))\n \n # Right knee angles.\n if (Joints[PyKinectV2.JointType_AnkleRight].TrackingState == 2):\n KneeQuat = self.Quaternion(Orientations, PyKinectV2.JointType_AnkleRight, PyKinectV2.JointType_KneeRight)\n KneeAngles = tf.euler_from_quaternion(KneeQuat, 'syzx')\n \n RKneeRoll = KneeAngles[1]; self.Text_RKnee_Roll.setText(str(\"%.3f\" %(RKneeRoll)))\n RKneeYaw = KneeAngles[0]; self.Text_RKnee_Yaw.setText(str(\"%.3f\" %(RKneeYaw)))\n \n else:\n RKneeRoll = None\n RKneeYaw = None\n \n else:\n RKneeRoll = None\n RKneeYaw = None\n\n RHipPitch = None\n RHipRoll = None \n \n RKneeRollList.append(RKneeRoll)\n RKneeYawList.append(RKneeYaw)\n \n RHipPitchList.append(RHipPitch)\n RHipRollList.append(RHipRoll)\n\n # Left leg angles.\n if (Joints[PyKinectV2.JointType_HipLeft].TrackingState == 2) and (Joints[PyKinectV2.JointType_KneeLeft].TrackingState == 2):\n LegQuat = self.Quaternion(Orientations, PyKinectV2.JointType_KneeLeft, PyKinectV2.JointType_HipLeft)\n LegAngles = tf.euler_from_quaternion(LegQuat, 'syzx')\n \n LHipPitch = LegAngles[2]; self.Text_LHip_Pitch.setText(str(\"%.3f\" %(LHipPitch)))\n LHipRoll = LegAngles[1]; self.Text_LHip_Roll.setText(str(\"%.3f\" %(LHipRoll)))\n \n # Left knee angles.\n if (Joints[PyKinectV2.JointType_AnkleLeft].TrackingState == 2):\n KneeQuat = self.Quaternion(Orientations, PyKinectV2.JointType_AnkleLeft, PyKinectV2.JointType_KneeLeft)\n KneeAngles = tf.euler_from_quaternion(KneeQuat, 'syzx')\n \n LKneeRoll = KneeAngles[1]; self.Text_LKnee_Roll.setText(str(\"%.3f\" %(LKneeRoll)))\n LKneeYaw = KneeAngles[0]; self.Text_LKnee_Yaw.setText(str(\"%.3f\" %(LKneeYaw)))\n \n else:\n LKneeRoll = None\n LKneeYaw = None\n \n else:\n LKneeRoll = None\n LKneeYaw = None\n\n LHipPitch = None\n LHipRoll = None \n \n LKneeRollList.append(LKneeRoll)\n LKneeYawList.append(LKneeYaw)\n \n LHipPitchList.append(LHipPitch)\n LHipRollList.append(LHipRoll)\n \n # Head angles.\n if (Joints[PyKinectV2.JointType_Neck].TrackingState == 2) and (Joints[PyKinectV2.JointType_Head].TrackingState == 2):\n NeckPos = Joints[PyKinectV2.JointType_Neck].Position\n HeadPos = Joints[PyKinectV2.JointType_Head].Position\n Diference = np.array([(HeadPos.x - NeckPos.x), (HeadPos.y - NeckPos.y), (HeadPos.z - NeckPos.z)])\n \n Pitch = np.arctan2(-Diference[2], Diference[1]); self.Text_Head_Pitch.setText(str(\"%.3f\" %(Pitch)))\n Roll = 0; self.Text_Head_Roll.setText(str(\"%.3f\" %(Roll)))\n Yaw = 0; self.Text_Head_Yaw.setText(str(\"%.3f\" %(Yaw)))\n \n else:\n Pitch = None\n Roll = None\n Yaw = None\n \n HeadPitchList.append(Pitch)\n HeadYawList.append(Yaw)\n HeadRollList.append(Roll)\n \n # Right shoulder angles.\n if (Joints[PyKinectV2.JointType_ShoulderRight].TrackingState == 2) and (Joints[PyKinectV2.JointType_ElbowRight].TrackingState == 2):\n ElbowRQuat = self.Quaternion(Orientations, PyKinectV2.JointType_ElbowRight, PyKinectV2.JointType_SpineShoulder) \n ShoulderRAngles = tf.euler_from_quaternion(ElbowRQuat, 'syzx')\n \n RShoulderPitch = add_angles(-np.pi/2, ShoulderRAngles[2]); self.Text_RShoulder_Pitch.setText(str(\"%.3f\" %(RShoulderPitch)))\n RShoulderRoll = -ShoulderRAngles[1]; self.Text_RShoulder_Roll.setText(str(\"%.3f\" %(RShoulderRoll)))\n \n # Right elbow angles.\n if Joints[PyKinectV2.JointType_WristRight].TrackingState == 2:\n WristRQuat = self.Quaternion(Orientations, PyKinectV2.JointType_WristRight, PyKinectV2.JointType_ElbowRight) \n ElbowRAngles = tf.euler_from_quaternion(WristRQuat, 'syzx') \n \n RElbowYaw = -add_angles(np.pi, -ShoulderRAngles[0]); self.Text_RElbow_Yaw.setText(str(\"%.3f\" %(RElbowYaw)))\n RElbowRoll = ElbowRAngles[1]; self.Text_RElbow_Roll.setText(str(\"%.3f\" %(RElbowRoll)))\n \n # Right wrist angle.\n if ENABLE_WRIST:\n WristQuat = self.Quaternion(Orientations, PyKinectV2.JointType_WristRight)\n WristAngles = tf.euler_from_quaternion(WristQuat, 'syzx')\n \n RWristYaw = WristAngles[0]; self.Text_RWrist_Yaw.setText(str(\"%.3f\" %(RWristYaw)))\n \n else:\n RWristYaw = None\n \n # Right hand state.\n if (Joints[PyKinectV2.JointType_HandTipRight].TrackingState == 2) and (Joints[PyKinectV2.JointType_ThumbRight].TrackingState == 2):\n if Body.hand_right_state == 3:\n HandR = 2 # Hand closed.\n elif Body.hand_right_state == 2:\n HandR = 1 # Hand opened.\n else:\n HandR = 3 # Unknown state.\n \n self.Text_RHand.setText(str(\"%.3f\" %(HandR)))\n \n else:\n HandR = None\n\n else:\n RElbowYaw = None\n RElbowRoll = None\n\n RWristYaw = None\n \n HandR = None\n \n else:\n RShoulderPitch = None\n RShoulderRoll = None\n \n RElbowYaw = None\n RElbowRoll = None\n\n RWristYaw = None\n \n HandR = None\n \n RShoulderPitchList.append(RShoulderPitch)\n RShoulderRollList.append(RShoulderRoll)\n \n RElbowRollList.append(RElbowRoll)\n RElbowYawList.append(RElbowYaw)\n\n RWristYawList.append(RWristYaw)\n \n RHandList.append(HandR)\n\n # Left shoulder angles.\n if (Joints[PyKinectV2.JointType_ShoulderLeft].TrackingState == 2) and (Joints[PyKinectV2.JointType_ElbowLeft].TrackingState == 2):\n ElbowLQuat = self.Quaternion(Orientations, PyKinectV2.JointType_ElbowLeft, PyKinectV2.JointType_SpineShoulder) \n ShoulderLAngles = tf.euler_from_quaternion(ElbowLQuat, 'syzx') \n \n LShoulderPitch = add_angles(-np.pi/2, ShoulderLAngles[2]); self.Text_LShoulder_Pitch.setText(str(\"%.3f\" %(LShoulderPitch)))\n LShoulderRoll = -ShoulderLAngles[1]; self.Text_LShoulder_Roll.setText(str(\"%.3f\" %(LShoulderRoll)))\n\n # Left elbow angles.\n if Joints[PyKinectV2.JointType_WristLeft].TrackingState == 2:\n WristLQuat = self.Quaternion(Orientations, PyKinectV2.JointType_WristLeft, PyKinectV2.JointType_ElbowLeft) \n ElbowLAngles = tf.euler_from_quaternion(WristLQuat, 'syzx') \n \n LElbowYaw = -add_angles(np.pi, -ShoulderLAngles[0]); self.Text_LElbow_Yaw.setText(str(\"%.3f\" %(LElbowYaw)))\n LElbowRoll = ElbowLAngles[1]; self.Text_LElbow_Roll.setText(str(\"%.3f\" %(LElbowRoll)))\n \n # Left wrist angle.\n if ENABLE_WRIST:\n WristQuat = self.Quaternion(Orientations, PyKinectV2.JointType_WristLeft)\n WristAngles = tf.euler_from_quaternion(WristQuat, 'syzx')\n \n LWristYaw = WristAngles[0]; self.Text_LWrist_Yaw.setText(str(\"%.3f\" %(LWristYaw)))\n \n else:\n LWristYaw = None\n\n # Left hand state.\n if (Joints[PyKinectV2.JointType_HandTipLeft].TrackingState == 2) and (Joints[PyKinectV2.JointType_ThumbLeft].TrackingState == 2):\n if Body.hand_left_state == 3:\n HandL = 2 # Hand closed.\n elif Body.hand_left_state == 2:\n HandL = 1 # Hand opened\n else:\n HandL = 3 # Unknown state.\n \n self.Text_LHand.setText(str(\"%.3f\" %(HandL)))\n \n else:\n HandL = None\n \n else:\n LElbowYaw = None\n LElbowRoll = None\n \n LWristYaw = None\n \n HandL = None\n \n else:\n LShoulderPitch = None\n LShoulderRoll = None\n\n LElbowYaw = None\n LElbowRoll = None\n \n LWristYaw = None\n\n HandL = None\n \n LShoulderPitchList.append(LShoulderPitch)\n LShoulderRollList.append(LShoulderRoll)\n \n LElbowRollList.append(LElbowRoll)\n LElbowYawList.append(LElbowYaw)\n \n LWristYawList.append(LWristYaw)\n \n LHandList.append(HandL)\n\n def DrawBodyBones(self, Joints, JointsPoints, Color, Joint0, Joint1):\n '''\n Function that draw the skeleton in a frame.\n '''\n Joint0State = Joints[Joint0].TrackingState;\n Joint1State = Joints[Joint1].TrackingState;\n\n # If is not correct the tracking:\n if (Joint0State == PyKinectV2.TrackingState_NotTracked) or (Joint1State == PyKinectV2.TrackingState_NotTracked): \n return\n\n if (Joint0State == PyKinectV2.TrackingState_Inferred) and (Joint1State == PyKinectV2.TrackingState_Inferred):\n return\n\n # If the skeleton tracking is correct:\n Start = (JointsPoints[Joint0].x, JointsPoints[Joint0].y) # Start point coordinates.\n End = (JointsPoints[Joint1].x, JointsPoints[Joint1].y) # Final point coordinates.\n\n # Draw a line with start and final points.\n try:\n if (Joint0State == PyKinectV2.TrackingState_Inferred) or (Joint1State == PyKinectV2.TrackingState_Inferred):\n pygame.draw.line(self.FrameSurface, Color[1], Start, End, 8)\n \n else:\n pygame.draw.line(self.FrameSurface, Color[0], Start, End, 8)\n \n except: \n pass\n\n def Quaternion(self, Orientations, Joint, ParentJoint = None):\n '''\n Function that computes the quaternion matrix using the coordinates of\n each joint get with the Kinect Sensor.\n ''' \n Quat = Orientations[Joint].Orientation \n QArray = np.array([Quat.w, Quat.x, Quat.y, Quat.z]) \n \n # Quat matrix with two joints.\n if ParentJoint is not None:\n QuatParent = Orientations[ParentJoint].Orientation \n QuatArrayParent = np.array([QuatParent.w, QuatParent.x, QuatParent.y, QuatParent.z]) \n QuatRelativ = tf.quaternion_multiply(tf.quaternion_inverse(QuatArrayParent), QArray) # Compute the relative quat.\n \n return QuatRelativ\n \n else: \n return QArray\n \nif __name__ == '__main__':\n \n App = QtGui.QApplication(sys.argv)\n GUI = HumanPostureAndEmotion()\n sys.exit(App.exec_())\n","sub_path":"Emotions Data Base Creator/DataBaseCreatorHumanPosture.py","file_name":"DataBaseCreatorHumanPosture.py","file_ext":"py","file_size_in_byte":53980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"416567417","text":"\n\n## Server names\nSERVERS = ['APP1','APP2','APP3','APP4','APP5','APP6','APP7']\nserverNow = -1\n\ndef get_server():\n global serverNow\n serverNow +=1\n if serverNow == len(SERVERS):\n serverNow = 0\n \n \n return SERVERS[serverNow]\n\n\n## Testing the function\n\nif __name__ == \"__main__\" :\n for i in range(9):\n print (get_server())\n\n","sub_path":"Train/LoadBalancer/LoadBalancer/LoadBalancer.py","file_name":"LoadBalancer.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"200007620","text":"import logging\n\nfrom django.core.management.base import BaseCommand\nfrom requests.exceptions import ConnectTimeout\n\nfrom vimeors.models import Video, User, Like, Comment\nfrom vimeors.management.commands._vimeoclient import client\nfrom vimeors.management.commands._utils import get\n\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger('vimeors')\n\n\nclass Command(BaseCommand):\n help = 'Populate database with data from the Vimeo API'\n\n def handle(self, *args, **kwargs):\n tag = 'awesome'\n videos = { 'page': 1, 'total': 10 }\n videos_url = '/tags/%s/videos?per_page=50' % tag\n\n while videos['page'] < videos['total'] and videos['page'] < 100:\n logger.info('Getting page %d of videos tagged \"%s\".'\n % (videos['page'], tag))\n connection_retries = 3\n while connection_retries > 0:\n try:\n videos = client.get(videos_url).json()\n break\n except ConnectTimeout:\n connection_retries -= 1\n logger.info('Connection timed out. Retrying (%d left).'\n % connection_retries)\n videos_url = videos['paging']['next']\n source = get(videos, 'data', [])\n\n logger.info('Got %d videos.' % len(source))\n [User.objects.create(i['user']) for i in source]\n\n users = User.objects.all()\n for user in users:\n logger.info('Getting videos liked by user \"%s\".' % user.name)\n videos_url = '%s/likes?per_page=50' % user.uri\n connection_retries = 3\n while connection_retries > 0:\n try:\n videos = get(client.get(videos_url).json(), 'data', [])\n break\n except ConnectTimeout:\n connection_retries -= 1\n logger.info('Connection timed out. Retrying (%d left).'\n % connection_retries)\n\n logger.info('Got %d videos.' % len(videos))\n for video in videos:\n video = Video.objects.create(video)\n Like.objects.create(user=user, video=video)\n\n logger.info('Getting comments for video \"%s\".' % video.name)\n comments_url = '%s/comments?per_page=50' % video.uri\n connection_retries = 3\n while connection_retries > 0:\n try:\n comments = get(client.get(comments_url).json(),\n 'data', [])\n break\n except ConnectTimeout:\n connection_retries -= 1\n logger.info('Connection timed out. Retrying (%d left).'\n % connection_retries)\n\n logger.info('Got %d comments.' % len(comments))\n [Comment.objects.create(video, i) for i in comments]\n\n logger.info('Finished gathering data.')\n","sub_path":"vimeors/management/commands/_gatherdata.py","file_name":"_gatherdata.py","file_ext":"py","file_size_in_byte":3031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"442216216","text":"\"\"\"empty message\n\nRevision ID: 175235720f56\nRevises: 61fd7b1a6054\nCreate Date: 2020-12-14 13:59:25.369944\n\n\"\"\"\nimport sqlalchemy as sa\nfrom alembic import op\n\n# revision identifiers, used by Alembic.\nrevision = '175235720f56'\ndown_revision = '61fd7b1a6054'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('estacao', sa.Column('created_on', sa.DateTime(), nullable=True))\n op.add_column('estacao', sa.Column('updated_on', sa.DateTime(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('estacao', 'updated_on')\n op.drop_column('estacao', 'created_on')\n # ### end Alembic commands ###\n","sub_path":"prototipo/migrations/versions/175235720f56_.py","file_name":"175235720f56_.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"43879246","text":"import bpy\nimport sdl2\nfrom bpy.props import IntProperty\nfrom ..LiveEditingBaseNode import LiveEditingBaseNode\n\n# Initialize SDL2 joysticks\nsdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK)\n\nclass JoystickNode(LiveEditingBaseNode):\n \"\"\"Joystick Node\"\"\"\n bl_idname = 'JoystickNode'\n bl_label = 'JoystickNode'\n bl_icon = 'GAME'\n\n idProperty = IntProperty(\n name=\"Id\",\n description=\"Joystick ID\",\n default=0, min=0, max=15\n )\n\n deadZoneProperty = IntProperty(\n name=\"Dead zone\",\n description=\"Joystick dead zone\",\n default=0, min=0, max=32768\n )\n\n joysticks = {}\n\n def draw_buttons(self, context, layout):\n layout.prop(self, \"idProperty\")\n layout.prop(self, \"deadZoneProperty\")\n\n def preRun(self):\n super().preRun()\n\n sdl2.SDL_PumpEvents()\n\n joyId = self.idProperty\n joystick = JoystickNode.joysticks.get(joyId)\n if joystick is None:\n joystick = sdl2.SDL_JoystickOpen(joyId)\n JoystickNode.joysticks[joyId] = joystick\n\n numAxes = sdl2.SDL_JoystickNumAxes(joystick)\n numButtons = sdl2.SDL_JoystickNumButtons(joystick)\n numHats = sdl2.SDL_JoystickNumHats(joystick)\n numBalls = sdl2.SDL_JoystickNumBalls(joystick)\n\n if numAxes + numButtons != len(self.outputs):\n self.outputs.clear()\n\n for axis in range(numAxes):\n name = \"Axis_\" + str(axis)\n socket = self.outputs.get(name)\n if socket is None:\n socket = self.outputs.new('NodeSocketInt', name)\n value = sdl2.SDL_JoystickGetAxis(joystick, axis)\n if abs(value) > self.deadZoneProperty:\n socket.default_value = value\n else:\n socket.default_value = 0\n\n for ball in range(numBalls):\n name = \"Ball\" + str(ball)\n socket = self.outputs.get(name)\n if socket is None:\n socket = self.outputs.new('NodeSocketInt', name)\n socket.default_value = sdl2.SDL_JoystickGetBall(joystick, ball)\n\n for button in range(numButtons):\n name = \"Button_\" + str(button)\n socket = self.outputs.get(name)\n if socket is None:\n socket = self.outputs.new('NodeSocketBool', name)\n socket.default_value = sdl2.SDL_JoystickGetButton(joystick, button)\n\n for hat in range(numHats):\n name = \"Hat_\" + str(hat)\n socket = self.outputs.get(name)\n if socket is None:\n socket = self.outputs.new('NodeSocketInt', name)\n socket.default_value = sdl2.SDL_JoystickGetHat(joystick, hat)\n","sub_path":"blender-addon-live-editing/live-editing/nodes/joystick/JoystickNode.py","file_name":"JoystickNode.py","file_ext":"py","file_size_in_byte":2674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"179476460","text":"import multiprocessing as mp\nimport os\nimport shutil\nimport time\nimport traceback\nimport warnings\nfrom glob import glob\nfrom pathlib import Path\n\nimport pandas\nimport ujson\nfrom PIL import ImageFile\n\nimport crawlingathome_client as cah\n\nImageFile.LOAD_TRUNCATED_IMAGES = True # https://stackoverflow.com/a/47958486\n\nwarnings.filterwarnings('ignore')\n\n\ndef upload(source: str, client_type: str):\n client_type = client_type.upper()\n target = 'gpujobs' if client_type == 'CPU' else 'CAH'\n options = '-rsh' if client_type == 'CPU' else '-zh'\n return os.system(f'rsync {options} {source} archiveteam@88.198.2.17::{target}')\n\n\ndef download(url, name, debug, isnotebook):\n while True:\n try:\n client = cah.init(\n url=url, nickname=name, type='gpu'\n )\n\n start_dl = time.time()\n\n client.newJob()\n client.downloadShard()\n\n end_dl = time.time()\n\n uid = client.shard.split('rsync', 1)[-1].strip()\n if len(glob(f'{uid}/*.csv')) == 0:\n print(f'[crawling@home] Marking job {uid} as invalid')\n client.invalidURL()\n for file in glob(f'{uid}/*_parsed.csv') + glob(f'{uid}/*_unfiltered.csv'):\n shutil.move(file, 'stats/')\n\n print(f'[crawling@home] Downloaded job {uid} in {end_dl-start_dl}')\n\n with open(f'{uid}/client.json', 'w') as f:\n ujson.dump(client.dump(), f)\n if isnotebook:\n time.sleep(25)\n except (cah.errors.InvalidURLError, cah.errors.ZeroJobError):\n try:\n if client.isAlive():\n client.bye()\n except:\n pass\n time.sleep(5)\n except KeyboardInterrupt:\n if client.isAlive():\n client.bye()\n except Exception as ex:\n print(f'[crawling@home] DLERROR: {ex}')\n if debug:\n traceback.print_exc()\n if client.isAlive():\n try:\n client.log('Error, restarting job')\n except:\n print(\"[crawling@home] Couldn't log to client:\")\n\n\npool = None\n\n\ndef downloader(name, url, debug, isnotebook, workers):\n pool = mp.Pool(workers)\n pool.starmap_async(\n download, [(url, name, debug, isnotebook) for _ in range(1)])\n\n\ndef old_main(name, url, debug, isnotebook, workers, isdocker):\n\n if not Path('stats').exists():\n os.mkdir('stats')\n\n print('[crawling@home] loading clip')\n from clip_filter import run_inference\n print('\\n[crawling@home] clip loaded\\n')\n\n def _worker(client_dict):\n while True:\n try:\n client = cah.load(**client_dict)\n output_folder = f\"./{client.shard.split('rsync', 1)[-1].strip()}/\"\n\n start = time.time()\n\n first_sample_id = int(client.start_id)\n last_sample_id = int(client.end_id)\n shard_of_chunk = client.shard_piece\n\n out_fname = \\\n f'FIRST_SAMPLE_ID_IN_SHARD_{first_sample_id}_LAST_SAMPLE_ID_IN_SHARD_{last_sample_id}_{shard_of_chunk}'\n print(\n f'[crawling@home] shard identification {out_fname}'\n ) # in case test fails, we need to remove bad data\n\n dlparse_df = pandas.read_csv(\n f'{output_folder}{out_fname}.csv', sep='|')\n dlparse_df['PATH'] = dlparse_df.apply(\n lambda x: output_folder + x['PATH'].strip('save/'), axis=1)\n\n client.log('Dropping NSFW keywords')\n\n filtered_df_len = run_inference(\n dlparse_df, output_folder, out_fname)\n\n client.log('Uploading Results')\n\n upload(f'{output_folder}/*{out_fname}*', client.type)\n\n client.completeJob(filtered_df_len)\n client.bye()\n end = time.time()\n print(\n f'[crawling@home] job completed in {round(end - start)} seconds')\n print(\n f'[crawling@home] job efficiency {filtered_df_len / (end - start)} pairs/sec')\n shutil.rmtree(output_folder)\n break\n except Exception as ex:\n print(f'[crawling@home] ERROR: {ex}')\n if debug:\n traceback.print_exc()\n if client.isAlive():\n try:\n client.log('Error, restarting job')\n except:\n print(\"[crawling@home] Couldn't log to client\")\n try:\n if client.isAlive():\n client.bye()\n except:\n pass\n pass\n\n print('start download')\n downloader(name, url, debug, isnotebook, workers)\n print('download started')\n\n while True:\n try:\n for client_dump in glob('./*/client.json'):\n with open(client_dump, 'r') as f:\n print(client_dump)\n try:\n client_dict = ujson.load(f)\n except ValueError:\n continue\n print(client_dict)\n _worker(client_dict)\n continue\n except KeyboardInterrupt:\n print('[crawling@home] stopping worker')\n if hasattr(pool, 'terminate'):\n print('terminating pool')\n pool.terminate()\n print('joining pool')\n pool.join()\n print('[crawling@home] stopped worker, cleaning workspace')\n break\n except Exception as ex:\n try:\n print(f'[crawling@home] ERROR: {ex}')\n if debug:\n traceback.print_exc()\n except:\n break\n time.sleep(10) # wait for in-progress rsync job to complete\n for client in glob('./*/client.json'):\n with open(client) as f:\n client = cah.load(**ujson.load(f))\n client.bye()\n for folder in glob('./*'):\n if 'crawlingathome_client' in folder or 'venv' in folder or 'stats' in folder:\n continue\n path = Path(folder)\n if path.is_dir():\n shutil.rmtree(folder)\n print('[crawling@home] cleaned workspace')\n\n\ndef main(*_):\n import warnings\n warnings.filterwarnings('default')\n warnings.warn(\n 'This worker is deprecated, use this repo: https://github.com/rvencu/crawlingathome-gpu-hcloud', DeprecationWarning)\n","sub_path":"gpu.py","file_name":"gpu.py","file_ext":"py","file_size_in_byte":6620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"107139191","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\nimport configparser\nfrom collections import OrderedDict\nfrom fabric.tasks import Task\nfrom fabric.colors import green, cyan\nfrom fabric.api import task, env, sudo\nfrom fabric.operations import put, prompt\n\n#\n# Tasks\n#\n\n\n@task\ndef setconfig(key, value):\n \"\"\"\n Add or edit a key-value pair in the .env configuration file.\n \"\"\"\n # Get the existing config\n cp = configparser.SafeConfigParser()\n cp.read(env.config_file)\n\n # if the config file section is not there, add it\n if not cp.has_section(env.config_section):\n cp.add_section(env.config_section)\n\n # Set the value provided by the user\n cp.set(env.config_section, key, value)\n\n # Write to the .env file\n with open(env.config_file, 'w') as f:\n cp.write(f)\n\n\n@task\ndef createconfig():\n \"\"\"\n Prompt users for settings to be stored in .env file\n \"\"\"\n # Kick it off\n print('')\n print('Configuration')\n print('=================')\n print('')\n\n # Request data from the user\n config = OrderedDict()\n config['AWS_ACCESS_KEY_ID'] = prompt('Your AWS access key:')\n config['AWS_SECRET_ACCESS_KEY'] = prompt('Your AWS secret key:')\n config['AWS_REGION_NAME'] = prompt(\n 'Your AWS region name:',\n default='us-west-2',\n )\n config['KEY_NAME'] = prompt('Your AWS key name:', default='my-key-pair')\n config['DB_HOST'] = prompt('Database host:', default=\"localhost\")\n config['DB_NAME'] = prompt('Database name:', default='calaccess_website')\n config['DB_USER'] = prompt('Database user:', default=env.app_user)\n config['DB_PASSWORD'] = prompt('Database user password:')\n config['S3_ARCHIVED_DATA_BUCKET'] = prompt(\n 'Name of the S3 bucket for archived data:',\n default='django-calaccess-dev-data-archive',\n )\n config['S3_BAKED_CONTENT_BUCKET'] = prompt(\n 'Name of the S3 bucket for baked content:',\n default='django-calaccess-dev-baked-content',\n )\n config['CLOUDFRONT_ARCHIVED_DATA_DISTRIBUTION'] = prompt(\n 'Name of the Cloudfront distribution for archived data',\n )\n config['EMAIL_USER'] = prompt('E-mail user:')\n config['EMAIL_PASSWORD'] = prompt('E-mail password:')\n config['EC2_HOST'] = prompt('EC2 host:')\n config['NEW_RELIC_LICENSE_KEY'] = prompt(\"New Relic license key:\")\n config['COMPRESS_ENABLED'] = prompt('Compression enabled:', default=False)\n\n # Save it to the configuration file\n [setconfig(k, v) for k, v in config.items()]\n\n # Tell the user they are done\n print('')\n print(green('That\\'s it. All set up!'))\n print('Configuration saved in {0}'.format(env.config_file))\n print('')\n\n\n@task\ndef printconfig():\n \"\"\"\n Print out the configuration settings for the local environment.\n \"\"\"\n # Loop through the current configuration\n for k, v in getconfig().items():\n # Print out each setting\n print(\"{}:{}\".format(cyan(k), v))\n\n\n@task\ndef printenv():\n \"\"\"\n Print out the Fabric env settings.\n \"\"\"\n # Load settings from the config file\n loadconfig()\n\n # Loop through the Fabric env\n for k, v in sorted(env.items()):\n # Print out each setting\n print(\"{}:{}\".format(k, v))\n\n\n@task\ndef copyconfig():\n \"\"\"\n Copy current configurations in local .env file to the ec2 instance.\n \"\"\"\n # Load settings from the config file\n loadconfig()\n\n # Push it to the remote environment\n put(env.config_file, env.repo_dir, use_sudo=True)\n\n # Set the proper file permissions\n sudo('chown {}:{} {}'.format(\n env.app_user,\n env.app_group,\n os.path.join(env.repo_dir, '.env'))\n )\n\n\n#\n# Helpers\n#\n\ndef getconfig():\n \"\"\"\n Return a dict of the vars currently in the config_file\n \"\"\"\n print(\"Loading {} configuration settings from {}\".format(\n cyan(env.config_section),\n cyan(env.config_file)\n ))\n\n # Open the configuration file\n cp = configparser.SafeConfigParser()\n cp.read(env.config_file)\n\n # Grab the section we're seeking and uppercase the settings\n d = dict((k.upper(), v) for k, v in cp.items(env.config_section))\n\n # Pass it out\n return d\n\n\ndef loadconfig():\n \"\"\"\n Load configuration settings into the Fabric env\n \"\"\"\n # If the config file doesn't exist, force its creation\n if not os.path.isfile(env.config_file):\n createconfig()\n\n # Load all of the configuration settings\n config = getconfig()\n for k, v in config.items():\n env[k] = v\n\n # If there is an EC2_HOST set, patch it onto the Fabric env object\n if hasattr(env, 'EC2_HOST'):\n env.hosts = [env.EC2_HOST]\n env.host = env.EC2_HOST\n env.host_string = env.EC2_HOST\n\n # If there is a KEY_NAME set, path it onto the Fabric env object\n if hasattr(env, 'KEY_NAME'):\n key_path = os.path.join(env.key_file_dir, \"%s.pem\" % env.KEY_NAME)\n env.key_filename = (key_path,)\n\n\nclass ConfigTask(Task):\n \"\"\"\n A custom Fabric @task that loads settings from an external configuration\n file before execution.\n \"\"\"\n def __init__(self, func, *args, **kwargs):\n super(ConfigTask, self).__init__(*args, **kwargs)\n self.func = func\n\n def __call__(self):\n self.run()\n\n def run(self, *args, **kwargs):\n loadconfig() # <-- the action\n return self.func(*args, **kwargs)\n","sub_path":"fabfile/configure.py","file_name":"configure.py","file_ext":"py","file_size_in_byte":5390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"184381265","text":"amount = int(input('Enter Amount to Draw :'))\nif(amount%5 == 0):\n dem=[{2000:''},{500:''},{200:''},{100:''},{50:''},{20:''},{10:''},{5:''}]\n totalNotes = 0;\n for i in range(0,len(dem)):\n key=dem[i].keys()[0]\n value = amount//key\n amount %= key\n dem[i][key ] = value\n totalNotes +=value\n print ('Total denomination :',dem, '\\n' ,'Total Notes : ',totalNotes)\nelse:\n print('Please Enter Valid Amount')\n","sub_path":"PY10/sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"474070067","text":"import torch\nimport torch.nn.functional as F\n\ndef save_checkpoint(state, filename):\n torch.save(state, filename)\n\nclass DummyScheduler(torch.optim.lr_scheduler._LRScheduler):\n def get_lr(self):\n lrs = []\n for param_group in self.optimizer.param_groups:\n lrs.append(param_group['lr'])\n \n return lrs\n\n def step(self, epoch=None):\n pass\n\ndef tocuda(data):\n if type(data) is list:\n if len(data) == 1:\n return data[0].cuda()\n else:\n return [x.cuda() for x in data]\n else:\n return data.cuda()\n'''\ndef net_grad_norm_max(model, p):\n grad_norms = [x.grad.data.norm(p).item() for x in model.parameters()]\n return max(grad_norms)\n'''\n\ndef clone_parameters(model):\n assert isinstance(model, torch.nn.Module), 'Wrong model type'\n\n params = model.named_parameters()\n\n f_params_dict = {}\n f_params = []\n for idx, (name, param) in enumerate(params):\n new_param = torch.nn.Parameter(param.data.clone())\n f_params_dict[name] = idx\n f_params.append(new_param)\n\n return f_params, f_params_dict\n\n# target differentiable version of F.cross_entropy \ndef soft_cross_entropy(logit, pseudo_target, reduction='mean'):\n loss = -(pseudo_target * F.log_softmax(logit, -1)).sum(-1)\n if reduction == 'mean':\n return loss.mean()\n elif reduction == 'none':\n return loss\n elif reduction == 'sum':\n return loss.sum()\n else:\n raise NotImplementedError('Invalid reduction: %s' % reduction)\n\n\n# test code for soft_cross_entropy\nif __name__ == '__main__':\n K = 100\n for _ in range(10000):\n y = torch.randint(K, (100,))\n y_onehot = F.one_hot(y, K).float()\n logits = torch.randn(100, K)\n\n l1 = F.cross_entropy(logits, y)\n l2 = soft_cross_entropy(logits, y_onehot)\n\n print (l1.item(), l2.item(), '%.5f' %(l1-l2).abs().item())\n \n","sub_path":"mlc_utils.py","file_name":"mlc_utils.py","file_ext":"py","file_size_in_byte":1954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"159273197","text":"# 实现的是双层注意力机制,没有用到batchnormalization\n\nimport numpy as np\nimport pandas as pd\nfrom collections import defaultdict\nimport re\n\nimport sys\nimport os\n\n\nfrom keras.layers import Dense, Input, multiply\nfrom keras.layers import GRU, Bidirectional, TimeDistributed, Dropout, BatchNormalization, LSTM\nfrom keras.models import Model\nfrom keras.preprocessing.sequence import TimeseriesGenerator\nfrom keras.optimizers import Adam\n\nfrom keras import backend as K\nfrom keras.engine.topology import Layer, InputSpec\nfrom Attention import AttLayer\n# 加载数据\nfrom data_processing import load_data\ntrain, train_label, test, test_label, name = load_data()\n\nMAX_SENTS = 2 # 句子数量,即多少个时间步的\nWORD_LENTTH = 1\nMAX_SENT_LENGTH = 196 # 即多少个特征值\n\n# 利用TimesereisGenerator生成序列数据\ntime_steps = MAX_SENTS\nbatch_size = 1024\n# 先把训练集划分出一部分作为验证集\ntrain = train[:(172032+time_steps), :] # 4096 * 42 = 172032\ntrain = train.reshape(-1, MAX_SENT_LENGTH)\ntrain_label = train_label[:(172032+time_steps), ]\ntest = test[:(81920+time_steps), :] # 4096 * 20 = 81920\ntest = test.reshape(-1, MAX_SENT_LENGTH)\ntest_label = test_label[:(81920+time_steps), ]\n# 数据集生成器 需要检查一下是否正确,主要是TimeseriesGenerator的使用情况\ntrain_label_ = np.insert(train_label, 0, 0, axis=0)\ntest_label_ = np.insert(test_label, 0, 0, axis=0)\ntrain_generator = TimeseriesGenerator(train, train_label_[:-1], length=time_steps, sampling_rate=1, batch_size=batch_size)\ntest_generator = TimeseriesGenerator(test, test_label_[:-1], length=time_steps, sampling_rate=1, batch_size=batch_size)\n\n\nsentence_input = Input(shape=(MAX_SENT_LENGTH, ))\nattention_probs = Dense(MAX_SENT_LENGTH, activation='softmax', name='attention_vec')(sentence_input)\nattention_mul = multiply([sentence_input, attention_probs])\n# ATTENTION PART FINISHES HERE\n\nsentEncoder = Model(sentence_input, attention_mul)\nprint('Encoder句子summary: ')\nsentEncoder.summary()\n\n\nreview_input = Input(shape=(MAX_SENTS, MAX_SENT_LENGTH)) # 文档级别输入\nreview_encoder = TimeDistributed(sentEncoder)(review_input) # 对每一个文档中的每一个句子进行句子级别的特征表示操作\n\nl_lstm_sent_0 = Bidirectional(GRU(32, return_sequences=True, activation='tanh', recurrent_dropout=0.1))(review_encoder) # 对映射后的文档进行操作\nlstm_drop_0 = Dropout(0.5)(l_lstm_sent_0)\n\nl_lstm_sent_1 = Bidirectional(GRU(12, return_sequences=True, activation='tanh', recurrent_dropout=0.1))(lstm_drop_0) # 对映射后的文档进行操作\nlstm_drop_1 = Dropout(0.5)(l_lstm_sent_1)\n# l_lstm_sent_2 = Bidirectional(GRU(16, return_sequences=True, activation='tanh'))(l_lstm_sent_1) # 对映射后的文档进行操作\n\nl_att_sent = AttLayer(MAX_SENTS)(lstm_drop_1) # 文档级别的注意力机制 64, 16, 8, 1 能到98.5%,没有dropout\n\ndense_2 = Dense(6, activation='relu')(l_att_sent)\n\npreds = Dense(1, activation='sigmoid')(dense_2)\n\nmodel = Model(review_input, preds)\nprint('Encoder文档summary: ')\nmodel.summary()\noptimize = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=10e-8)\n\nmodel.compile(loss='binary_crossentropy',\n optimizer=optimize,\n metrics=['acc'])\n\n\n# 进行训练\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau, TensorBoard\nprint(\"model fitting - Hierachical attention network\")\nsave_dir = os.path.join(os.getcwd(), 'hierarchical_attention')\nfilepath=\"hierarchical_test_10.hdf5\"\ncheckpoint = ModelCheckpoint(os.path.join(save_dir, filepath), monitor='val_acc', verbose=1, save_best_only=True, mode='max')\ntbCallBack = TensorBoard(log_dir='./logs', histogram_freq=0, write_graph=True, write_grads=True,\n write_images=True, embeddings_freq=0, embeddings_layer_names=None, embeddings_metadata=None)\nreduc_lr = ReduceLROnPlateau(monitor='val_acc', patience=10, mode='max', factor=0.2, min_delta=0.000001)\nhistory = model.fit_generator(train_generator, epochs=210, verbose=2, steps_per_epoch=168,\n callbacks=[checkpoint, tbCallBack, reduc_lr],\n validation_data=test_generator, shuffle=0, validation_steps=80)\n\nprint(history.history.keys())\n\n# plot\nimport matplotlib.pyplot as plt\nnp.save('lr_0.05_loss_2_0310.npy', history.history['loss'])\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('Hierachical Attention Model Loss')\nplt.ylabel('Loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper right')\nplt.show()","sub_path":"plot_loss.py","file_name":"plot_loss.py","file_ext":"py","file_size_in_byte":4593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"195035632","text":"'''\n#first understand how the k value is given then solve the poblem\nclass Node:\n def __init__(self, val, k):\n self.right = None\n self.data = val\n self.left = None\n self.key = k\n'''\n# your task is to complete this function\n# function should return kth smallest element from the BST\ndef k_smallest_element(root, n):\n # Code here\n T = 1\n while T:\n if n == root.key+1:\n #print(root.data)\n return (root.data)\n elif n > root.key+1:\n n = n-(root.key+1)\n root = root.right\n \n else:\n root = root.left\n","sub_path":"BST/find-k-th-smallest-element-in-bst.py","file_name":"find-k-th-smallest-element-in-bst.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"432331747","text":"# -*- coding: utf-8 -*-\n\"\"\" main.py \"\"\"\n\nfrom configs.config import CFG\nfrom model.unet import UNet\n\n\ndef run():\n \"\"\"Builds model, loads data, trains and evaluates\"\"\"\n model = UNet(CFG)\n model.load_data()\n model.build()\n model.train()\n model.evaluate()\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"Project_Structure/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"561915653","text":"from tkinter import *\nimport subprocess # required for redirecting stdout to GUI\nimport main_module # the script file that is redirected\nimport string\nimport tkinter.font as tkFont\nimport tkinter as tk\nimport pickle\nfrom tkinter import ttk\nimport mysql.connector\nimport textwrap\nimport webbrowser\nfrom colour import Color\nfrom PIL import ImageTk,Image\n\nresultdata={}\n\ndef redirect(module,sel,Dkey=\"default\"):\n path=\"data\\\\RawData.txt\"\n# proc= subprocess.check_output(\"python -c import import main_module;main_module.main(ss) , shell = False\")\n proc= subprocess.check_output(\"python main_module.py \" +path +\" \"+str(sel)+\" \"+Dkey, shell = False)\n return proc.strip()\n\ndef OnDoubleClick(event):\n \n cell_value=''\n curItem = tree.item(tree.focus())\n col = tree.identify_column(event.x)\n# print ('curItem = ', curItem)\n# print ('col = ', col)\n\n if col == '#0':\n item = tree.identify(\"item\", event.x, event.y)\n# print (\"you clicked on\", tree.item(item)[\"values\"])\n cell_value = tree.item(item)[\"values\"][0]\n webbrowser.open('{}'.format(\"http://endoscmeng01.endo.strykercorp.com:8080/browse/\"+cell_value))\n# \n\ndef wrap(string, lenght=60):\n return '\\n'.join(textwrap.wrap(string, lenght))\n\ndef process_result():\n# root_pic1 = Image.open(\"images\\\\read_more.png\") \n \n tree.delete(*tree.get_children())\n with open(\"data\\\\RawDataResult\", \"rb\") as file:\n resultdata=pickle.load(file)\n \n if(resultdata==\"Invalid entry.\"):\n message.set(\"Incorrect Defect Id format / Not found.\")\n \n else:\n for index,values in resultdata.items():\n \n summ,state= get_data_defectkey(index)\n summinfo = (summ[:70] + '..') if len(summ) > 70 else summ\n values=float(values)*int(100)\n value=str(values)\n value=str(value[:4])\n tree.insert('','end',image=img, values=(str(index),value,state,summinfo))\n# tree.insert('','end', values=(str(index),value,state,summinfo,img))\n \ndef get_data_defectkey(dkey):\n print(dkey)\n cnx = mysql.connector.connect(user='root',password='root', database='defectsdata')\n cursor = cnx.cursor()\n \n query = (\"SELECT Summary , State FROM jira_defect_info where DefectKey= %s\")\n cursor.execute(query, (dkey,))\n \n row=cursor.fetchone()\n \n summ=row[0]\n state=row[1]\n# summ,state=str(row).strip().split(',', 1)\n \n cnx.commit()\n cnx.close() \n \n return summ,state\n \n \n\ndef put_in_txt(module):\n message.set('')\n \n \n '''Puts the redirected string in a text.'''\n if(v.get()==1):\n inputValue= entry1.get()\n if(inputValue==''):\n message.set(\"Defect ID cannot be blank.\")\n else:\n print(inputValue)\n redirect(module,1,inputValue)\n process_result()\n# txt2.configure(state=\"normal\")\n# txt2.insert('1.0', redirect(module,1,inputValue))\n# txt2.configure(state=\"disabled\")\n elif(v.get()==2):\n \n inputValue=txt1.get(\"1.0\",\"end-1c\")\n print(inputValue)\n if(inputValue==''):\n message.set(\"Description cannot be blank.\")\n else:\n with open('data\\RawData.txt', 'w') as file:\n file.write(inputValue)\n # query_text_clean()\n redirect(module,2)\n process_result()\n \n else:\n message.set(\"Defect ID/Description cannot be blank.\")\n# txt2.configure(state=\"normal\")\n# txt2.insert('1.0', redirect(module,2))\n# txt2.configure(state=\"disabled\")\n \n \n \n\n \n \ndef enableInput2():\n txt1.delete('1.0',END)\n entry1.delete(0,END)\n txt1.configure(state=\"normal\")\n entry1.configure(state=\"disabled\")\n \ndef enableInput1():\n txt1.delete('1.0',END)\n entry1.delete(END)\n entry1.configure(state=\"normal\")\n txt1.configure(state=\"disabled\")\n \ndef combine_funcs(*funcs):\n def combined_func(*args, **kwargs):\n for f in funcs:\n f(*args, **kwargs)\n return combined_func\n \ndef clear_results():\n tree.delete(*tree.get_children())\n\n\nroot = tk.Tk()\nroot.geometry(\"800x600\")\nroot.resizable(width=False,height=False)\nroot.title('Find Related Defects')\n\nCustomfont = tkFont.Font(size=10)\nv = tk.IntVar()\n\nrad1= tk.Radiobutton(root, \n text=\"Enter Defect ID\", padx=20,pady=8,\n variable=v,\n value=1,anchor=W,command=combine_funcs(enableInput1,clear_results),font=Customfont, fg='black').grid(row=0,column=0,sticky=W)\n\nentry1= tk.Entry(rad1,width=40)\nentry1.grid(row=0, column=0, padx=20)\nentry1.configure(state=\"disabled\")\n\nrad2= tk.Radiobutton(root, \n text=\"Describe the Defect\", padx=20,pady=8,\n variable=v, \n value=2,command=combine_funcs(enableInput2,clear_results),font=Customfont,fg='black').grid(row=3,column=0,sticky=W)\ntxt1= tk.Text(root, width=60 ,height=12, padx=20)\nvsb = tk.Scrollbar(root, orient=\"vertical\")\n\ntxt1.configure(yscrollcommand=vsb.set)\nvsb.configure(command=txt1.yview)\n\nvsb.grid(row=5, column=1, sticky=\"ns\")\ntxt1.grid(row=5, column=0, sticky=\"nsew\",padx=20)\n\ntxt1.configure(state=\"disabled\")\n#root.grid_rowconfigure(0, weight=1)\n#root.grid_columnconfigure(0, weight=1)\n\nbtn = tk.Button(root, text=\"Search\",width=13, height = 1,font=Customfont,foreground='black')\n#btn = tk.Button(root, text=\"Search\",width=12, height = 2,font=Customfont ,bg='gray',relief='flat')\nbtn['command'] = lambda module=main_module : put_in_txt(module)\nbtn.grid(row=7,column=0,pady=10)\n\nw1 = tk.Label(root, text=\"Results\",font=Customfont,foreground='black').grid(row=8 , column=0,sticky=W,padx=23)\n\nimg= Image.open(\"images\\\\more.png\")\n\nimwidth=25#the new width you want \n\n#the next three lines of codes are used to keep the aspect ration of the image\nwpersent=(imwidth/float(img.size[0]))\nhsize=int(float(img.size[1])*float(wpersent))#size[1] means the height and the size[0] means the width you can read more about this in th PIL documentation\nimg=ImageTk.PhotoImage(img.resize((imwidth,hsize),Image.ANTIALIAS))# set the width and put it back in the chromelogo variable\n#img=ImageTk.PhotoImage(img)\ntree = ttk.Treeview(root, columns = (1,2,3,4), height = 6,selectmode=\"extended\")\ntree.heading('#0', text='JIRA')\ntree.heading('#1', text='Defect ID')\ntree.heading('#2', text='Similarity (%)')\ntree.heading('#3', text='State')\ntree.heading('#4', text='Summary')\n\n \ntree.column('#0', minwidth = 60, width =60, stretch = False,anchor=tk.W )\ntree.column('#1', minwidth = 90, width =90, stretch = False, )\ntree.column('#2', minwidth = 80, width = 80, stretch = False)\ntree.column('#3', minwidth = 90, width = 90, stretch = False)\ntree.column('#4', minwidth = 100, width = 100, stretch =True )\n \ntree.grid(in_=root,row=10,padx=20,pady=8,sticky='we')\ntree.image=img\ntree.bind(\"\", OnDoubleClick)\nroot.grid_columnconfigure(0, weight=1)\n\nstyle = ttk.Style(root) \nstyle.configure('Treeview', rowheight=30)\nstyle.configure(\".\", font=('Helvetica', 9), foreground=\"white\")\nstyle.configure(\"Treeview\", foreground='green')\nstyle.configure(\"Treeview.Heading\", foreground='black')\n\nvsb2 = Scrollbar(root, orient=\"vertical\")\ntree.configure(yscrollcommand=vsb2.set)\nvsb2.configure(command=tree.yview)\nvsb2.grid(row=10, column=1, sticky=\"ns\")\n\nmessage = tk.StringVar()\nStatuslbl = tk.Label(root, text=\"\",font=Customfont,foreground='Red',textvariable=message).grid(row=13 , column=0,padx=23)\n\nroot.mainloop()\n\n\n \n","sub_path":"maingui.py","file_name":"maingui.py","file_ext":"py","file_size_in_byte":7497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"542034744","text":"import numpy as np\nfrom numpy_allocation_tracking.decorators import assert_mem_usage_factor\nfrom DVIDSparkServices.sparkdvid.CompressedNumpyArray import CompressedNumpyArray\n\nclass TestCompressedNumpyArray(object):\n \n def test_c_contiguous(self):\n original = np.random.random((100,100,100)).astype(np.float32)\n assert original.flags['C_CONTIGUOUS']\n\n # RAM is allocated for the lz4 buffers, but there should be 0.0 numpy array allocations\n compress = assert_mem_usage_factor(0.0)(CompressedNumpyArray)\n compressed = compress( original )\n\n # No new numpy arrays needed for deserialization except for the resut itself. \n uncompress = assert_mem_usage_factor(1.0, comparison_input_arg=original)(compressed.deserialize) \n uncompressed = uncompress()\n\n assert uncompressed.flags['C_CONTIGUOUS']\n assert (uncompressed == original).all()\n\n def test_f_contiguous(self):\n original = np.random.random((100,100,100)).astype(np.float32)\n original = original.transpose()\n assert original.flags['F_CONTIGUOUS']\n \n # RAM is allocated for the lz4 buffers, but there should be 0.0 numpy array allocations\n compress = assert_mem_usage_factor(0.0)(CompressedNumpyArray) \n compressed = compress( original )\n \n # No new numpy arrays needed for deserialization except for the resut itself. \n uncompress = assert_mem_usage_factor(1.0, comparison_input_arg=original)(compressed.deserialize) \n uncompressed = uncompress()\n\n assert uncompressed.flags['F_CONTIGUOUS']\n assert (uncompressed == original).all()\n\n def test_non_contiguous(self):\n original = np.random.random((100,100,100)).astype(np.float32)\n original = original.transpose(1,2,0)\n assert not original.flags.contiguous\n \n # Since this array isn't contiguous, we need *some* overhead as the data is copied.\n # But it should only be 1 slice's worth.\n compress = assert_mem_usage_factor(0.01)(CompressedNumpyArray) \n compressed = compress( original )\n\n # But decompression still requires no numpy allocations beyond the result itself. \n uncompress = assert_mem_usage_factor(1.0, comparison_input_arg=original)(compressed.deserialize) \n uncompressed = uncompress()\n\n assert (uncompressed == original).all()\n\n def test_1d_array(self):\n \"\"\"\n A previous version of CompressedNumpyArray didn't support 1D arrays.\n Now it is supported as a special case.\n \"\"\"\n original = np.random.random((1000,)).astype(np.float32)\n\n # RAM is allocated for the lz4 buffers, but there should be 0.0 numpy array allocations\n compress = assert_mem_usage_factor(0.0)(CompressedNumpyArray)\n compressed = compress( original )\n\n # No new numpy arrays needed for deserialization except for the resut itself.\n uncompress = assert_mem_usage_factor(1.0, comparison_input_arg=original)(compressed.deserialize)\n uncompressed = uncompress()\n\n assert (uncompressed == original).all()\n\nif __name__ == \"__main__\":\n import sys\n import nose\n sys.argv.append(\"--nocapture\") # Don't steal stdout. Show it on the console as usual.\n sys.argv.append(\"--nologcapture\") # Don't set the logging level to DEBUG. Leave it alone.\n nose.run(defaultTest=__file__)\n","sub_path":"unit_tests/test_compressed_numpy_array.py","file_name":"test_compressed_numpy_array.py","file_ext":"py","file_size_in_byte":3462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"237704297","text":"from django.conf.urls import patterns, url\n\nurlpatterns = patterns('apiserver.views',\n # Api\n url(r'^apicanciones/$', 'lista_canciones'),\n url(r'^apicanciones/(?P[0-9]+)/$', 'detalle_cancion'),\n\n url(r'^apiscores/$', 'lista_scores'),\n url(r'^apiscores/(?P[0-9]+)/$', 'detalle_score'),\n)","sub_path":"creativitytools/apiserver/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"182561632","text":"#-*- coding: UTF-8 -*- \nfrom PIL import Image\nimport numpy as np\nimport torch\n#import torchvision.transforms\nimport matplotlib.pyplot as plt\n\ndef to_gray(tensor):\n R = tensor[0]\n G = tensor[1]\n B = tensor[2]\n img_tensor=0.299*R+0.587*G+0.114*B\n #img_tensor = img_tensor.view(1,tensor.shape[1],tensor.shape[2]) \n return img_tensor\n\ndef to_grad_x(tensor):\n h = tensor.shape[0]\n w = tensor.shape[1]\n img_tensor_x = tensor[0:h-1,:] - tensor[1:h,:]\n print(img_tensor_x.shape)\n return torch.abs(img_tensor_x)\n\ndef to_grad_y(tensor):\n h = tensor.shape[0]\n w = tensor.shape[1]\n img_tensor_y = tensor[:,0:w-1] - tensor[:,1:w]\n print(img_tensor_y.shape)\n return torch.abs(img_tensor_y)\n\ndef get_image(path):\n #获取图片\n img = Image.open(path)\n img = img.convert('RGB')\n img_tensor = torch.ByteTensor(torch.ByteStorage.from_buffer(img.tobytes()))\n img_tensor = img_tensor.view(img.size[1],img.size[0],3)\n img_tensor = img_tensor.transpose(0, 1).transpose(0, 2).contiguous()\n img_tensor = img_tensor.float().div(255)\n img_gray = to_gray(img_tensor)\n imt_grad = to_grad_y(img_gray)\n return imt_grad\n\n#to_pil_image = transforms.ToPILImage()\n\ndef show_image(img_tensor):\n # 方法1:Image.show() \n # # transforms.ToPILImage()中有一句 \n # # npimg = np.transpose(pic.numpy(), (1, 2, 0)) \n # # 因此pic只能是3-D Tensor,所以要用image[0]消去batch那一维 \n # img = to_pil_image(image[0]) \n # img.show() \n # # 方法2:plt.imshow(ndarray) img = image[0] \n # # plt.imshow()只能接受3-D Tensor,所以也要用image[0]消去batch那一维 \n img = img_tensor.numpy()\n # FloatTensor转为ndarray \n #img = np.transpose(img, (1,2,0)) \n # 把channel那一维放到最后 \n # 显示图片 \n plt.imshow(img,cmap=\"gray\") \n plt.show()\n\nimg = get_image(\"chongzi.jpeg\")\nprint(type(img))\nprint(img.shape)\nprint(img)\nprint(img.size())\nshow_image(img)","sub_path":"Data Scripts/testPytorchGray.py","file_name":"testPytorchGray.py","file_ext":"py","file_size_in_byte":1964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"256080750","text":"import os\nimport sys\nfrom os.path import isfile, join\nfrom django.core.management import call_command\nfrom django.core.wsgi import get_wsgi_application\n\n# path = \"/Users/shabandi/Desktop/All photos/Shikharji Bandi Family Oct. 2019\"\npath = sys.argv[1]\n\n\ndef modify_file(value):\n file_name = join(os.getcwd(), 'DjangoServer/settings.py')\n replacement_text = \"MEDIA_ROOT = \\\"\" + value + \"\\\"\";\n readFile = open(file_name)\n lines = readFile.readlines()\n readFile.close()\n w = open(file_name, 'w')\n w.writelines([item for item in lines[:-1]])\n w.writelines(replacement_text)\n w.close()\n\n\nmodify_file(path)\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"DjangoServer.settings\")\napplication = get_wsgi_application()\ncall_command('runserver', '127.0.0.1:8000')\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"491861684","text":"import pandas as pd\nfrom cycler import cycler\nimport matplotlib.pyplot as plt\nimport numpy as np\nplt.rc('lines', linewidth=2)\nplt.rc('axes', prop_cycle=(cycler('color', ['#e41a1c','#377eb8','#4daf4a','#984ea3']))) # line colors\n\n\nclass encodeStates(object):\n def __init__(self, observation_space, num_green_phases, max_green, delta_time):\n self.num_green_phases = num_green_phases\n self.max_green = max_green\n self.delta_time = delta_time\n self.radix_factors = [s.n for s in observation_space.spaces]\n\n def encode(self, state):\n phase = state[:self.num_green_phases].index(1)\n elapsed = self.discretize_elapsed_time(state[self.num_green_phases])\n density_queue = [self.discretize_density(d) for d in state[self.num_green_phases + 1:]]\n encoded_state = self.radix_encode([phase, elapsed] + density_queue)\n return encoded_state\n\n def discretize_density(self, density):\n if density < 0.1:\n return 0\n elif density < 0.2:\n return 1\n elif density < 0.3:\n return 2\n elif density < 0.4:\n return 3\n elif density < 0.5:\n return 4\n elif density < 0.6:\n return 5\n elif density < 0.7:\n return 6\n elif density < 0.8:\n return 7\n elif density < 0.9:\n return 8\n else:\n return 9\n\n def discretize_elapsed_time(self, elapsed):\n elapsed *= self.max_green\n for i in range(self.max_green // self.delta_time):\n if elapsed <= self.delta_time + i * self.delta_time:\n return i\n return self.max_green // self.delta_time - 1\n\n def radix_encode(self, values):\n res = 0\n for i in range(len(self.radix_factors)):\n res = res * self.radix_factors[i] + values[i]\n return int(res)\n\ndef save_csv(metrics, out_csv_name):\n if out_csv_name is not None:\n df = pd.DataFrame(metrics)\n out_filename = out_csv_name\n df.to_csv(out_filename + '.csv', index=False)\n\ndef fig():\n fig = 1\n while True:\n yield fig\n fig += 1\nfig_gen = fig()\n\ndef moving_average(interval, window_size):\n if window_size == 1:\n return interval\n window = np.ones(int(window_size))/float(window_size)\n return np.convolve(interval, window, 'same')\n\ndef plot_figure(figsize=(12, 9), x_label='', y_label='', title=''):\n plt.figure(next(fig_gen), figsize=figsize)\n plt.rcParams.update({'font.size': 20})\n ax = plt.subplot()\n plt.grid(axis='y')\n ax.spines[\"top\"].set_visible(False)\n ax.spines[\"right\"].set_visible(False)\n ax.get_xaxis().tick_bottom()\n ax.get_yaxis().tick_left()\n plt.title(title)\n plt.xlabel(x_label)\n plt.ylabel(y_label)\n\n\ndef plot(out_file):\n csv_file = out_file+'.csv'\n result_file = out_file+'.png'\n plot_figure(x_label='Time Step (s)', y_label='Total Waiting Time of Vehicles (s)')\n df = pd.read_csv(csv_file)\n main_df = df\n\n window = 5\n steps = main_df.groupby('step_time').total_stopped.mean().keys()\n mean = moving_average(main_df.groupby('step_time').mean()['total_wait_time'], window_size=window)\n std = moving_average(main_df.groupby('step_time').std()['total_wait_time'], window_size=window)\n\n plt.plot(steps, mean)\n plt.fill_between(steps, mean + std, mean - std, alpha=0.3)\n\n plt.savefig(result_file, bbox_inches=\"tight\")","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"568692079","text":"# -*- coding: utf-8 -*-\n\"\"\"\nreguest.views\n\"\"\"\nfrom google.appengine.api.taskqueue import taskqueue\nfrom google.appengine.ext import db\nfrom kay.utils import render_to_response, url_for\nfrom apps.reguest.forms import RegistrationRequestForm\nfrom apps.reguest.models import RegistrationRequest\nfrom string import lower\n\n\ndef reg_request(request):\n form = RegistrationRequestForm()\n if request.method == 'POST' and form.validate(request.form):\n reg_req = RegistrationRequest()\n reg_req.name = form['name']\n reg_req.organization = form['organization']\n reg_req.address = form['address']\n reg_req.telephone = form['telephone']\n reg_req.email = lower(form['email'])\n reg_req.put()\n def txn():\n taskqueue.add(url=url_for('reguest/admins/send_request_to_manager',\n request_id=reg_req.key.id()),\n transactional=True)\n db.run_in_transaction(txn)\n return render_to_response('reguest/thx.html', {\n 'name':reg_req.name, 'email':reg_req.email\n })\n return render_to_response('reguest/reg_request.html', {\n 'form': form.as_widget()\n })\n","sub_path":"apps/reguest/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"20708894","text":"# -*- coding: utf-8 -*-\n# file: BERT_SPC.py\n# author: songyouwei \n# Copyright (C) 2019. All Rights Reserved.\nimport torch\nimport torch.nn as nn\nfrom layers.squeeze_embedding import SqueezeEmbedding\nfrom layers.attention import Attention\nimport ipdb\n\n\nclass BertPooler(nn.Module):\n def __init__(self):\n super(BertPooler, self).__init__()\n self.dense = nn.Linear(768, 768)\n self.activation = nn.Tanh()\n\n def forward(self, hidden_states):\n # We \"pool\" the model by simply taking the hidden state corresponding\n # to the first token.\n first_token_tensor = hidden_states[:, 0]\n pooled_output = self.dense(first_token_tensor)\n pooled_output = self.activation(pooled_output)\n return pooled_output\n\n\nclass BERT_SPC(nn.Module):\n def __init__(self, bert, opt):\n super(BERT_SPC, self).__init__()\n # self.squeeze_embedding = SqueezeEmbedding()\n self.bert = bert\n self.dropout = nn.Dropout(opt.dropout)\n self.dense = nn.Linear(opt.bert_dim, opt.polarities_dim)\n self.att = Attention(opt.bert_dim,score_function='mlp')\n self.pool = BertPooler()\n self.conv = nn.MaxPool1d(12)\n\n def forward(self, inputs):\n text_bert_indices, bert_segments_ids,text_bert_mask = inputs[0], inputs[1], inputs[2]\n \n # text_bert_len = torch.sum(text_bert_indices != 0, dim=-1)\n # text_bert_indices = self.squeeze_embedding(text_bert_indices, text_bert_len)\n # bert_segments_ids = self.squeeze_embedding(bert_segments_ids, text_bert_len)\n encoded_layers, pooled_output = self.bert(text_bert_indices, bert_segments_ids,text_bert_mask, output_all_encoded_layers=True)\n # cls_all_layers = torch.stack([i[:,0,:] for i in encoded_layers],dim=1)\n # cls_att, score = self.att(cls_all_layers,pooled_output)\n # cls_att = cls_att.squeeze(1)\n # ipdb.set_trace()\n # cls_all = torch.stack([i[:,-1,:] for i in encoded_layers],dim=1).permute(0,2,1)\n # cls_single = self.conv(cls_all).squeeze(-1)\n pooled_output = self.dropout(pooled_output)\n logits = self.dense(pooled_output)\n return logits\n\n\n\n\n","sub_path":"models/bert_spc.py","file_name":"bert_spc.py","file_ext":"py","file_size_in_byte":2201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"20411731","text":"from sudoku import SudokuGrid, SudokuGridInput, SudokuSolver\n\n\ndef main():\n file_data = SudokuGridInput()\n path_to_puzzle = input(\"Enter the path to txt file containing the puzzle: \")\n try:\n file_data.read_txt_file(path_to_puzzle)\n except ValueError:\n print(f\"[ERR]: \\\"{path_to_puzzle}\\\" - Input file does not contain sudoku puzzle in the right format!\")\n print(\"Try Again :-( \")\n return\n except IOError as exception_here:\n print(exception_here)\n print(\"Try Again :-( \")\n return\n\n puz = SudokuGrid()\n puz.source_grid_from(file_data)\n\n print(\"PUZZLE:\")\n print(puz)\n\n my_solver = SudokuSolver(puz)\n print(\"\\nsolving puzzle....\\n\")\n answer = my_solver.solve()\n\n print(\"SOLUTION:\")\n print(answer)\n\n wanna_save = input(\"Do you want to save solution to a file? [y/N]\")\n if wanna_save == 'y':\n error = True\n while error:\n output_file = input(\"Enter output filename: \")\n try:\n answer.save_grid_to_txt(output_file)\n except FileExistsError:\n print(\"File already exists!...Try again\")\n else:\n error = False\n else:\n return\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"78793874","text":"import tkinter as tk\n\n# root = tk.Tk()\n#\n#\n# def print_name(event):\n# print(\"Hello, my name is Arthur\")\n#\n#\n# button1 = tk.Button(root, text=\"What is your name\")\n# button1.bind(\"\", print_name)\n# button1.pack()\n# root.mainloop()\nroot = tk.Tk()\n\n\ndef left_click(event):\n print(\"left\")\n\n\ndef right_click(event):\n print(\"right\")\n\n\nframe = tk.Frame(root, width=300, height=250)\nframe.bind(\"\", left_click)\nframe.bind(\"\", right_click)\nframe.pack()\n\nroot.mainloop()\n","sub_path":"module/Tkinter/bindingFunction.py","file_name":"bindingFunction.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"330238536","text":"from __future__ import with_statement\n\ntry:\n import MySQLdb\n from MySQLdb.cursors import DictCursor\nexcept ImportError:\n import pymysql as MySQLdb\n from pymysql.cursors import DictCursor\n\nfrom flask import (\n Flask, request, redirect, session, url_for, abort,\n render_template, _app_ctx_stack, Response,\n after_this_request,\n)\n\nimport memcache\nfrom flask_memcache_session import Session\nfrom werkzeug.contrib.fixers import ProxyFix\n\n# git clone https://github.com/dart-lang/py-gfm.git\n# cd py-gfm\n# python setup.py install\nfrom markdown import markdown\n\nimport json, os, hashlib, tempfile, subprocess\nconfig = {}\n\napp = Flask(__name__, static_url_path='')\napp.cache = memcache.Client(['unix:/tmp/memcached.sock'], debug=0)\napp.session_interface = Session()\napp.session_cookie_name = \"isucon_session\"\napp.wsgi_app = ProxyFix(app.wsgi_app)\n\n# log\nimport logging\nlogging.basicConfig(filename='log.txt')\n#logging.basicConfig(filename='log.txt', level=logging.DEBUG)\n\ndef load_config():\n global config\n print(\"Loading configuration\")\n env = os.environ.get('ISUCON_ENV') or 'local'\n with open('../config/' + env + '.json') as fp:\n config = json.load(fp)\n\ndef connect_db():\n global config\n host = config['database']['host']\n port = config['database']['port']\n username = config['database']['username']\n password = config['database']['password']\n dbname = config['database']['dbname']\n db = MySQLdb.connect(host=host, port=port, db=dbname, user=username, passwd=password, cursorclass=DictCursor, charset=\"utf8\")\n return db\n\n\ndef get_user():\n user_id = session.get('user_id')\n user_username = session.get('user_username')\n user = {'id':user_id, 'username':user_username}\n if not user_id:\n user = None\n #if user_id:\n # cur = get_db().cursor()\n # cur.execute(\"SELECT * FROM users WHERE id=%s\", user_id)\n # user = cur.fetchone()\n # cur.close()\n if user:\n @after_this_request\n def add_header(response):\n response.headers['Cache-Control'] = 'private'\n return response\n\n return user\n\ndef anti_csrf():\n if request.form['sid'] != session['token']:\n abort(400)\n\n\ndef require_user(user):\n if not user:\n redirect(url_for(\"top_page\"))\n abort()\n\n\ndef gen_markdown(memo_id, md):\n mid = \"memo_content_\" + str(memo_id)\n html = app.cache.get(mid)\n if html == None:\n html = markdown(md)\n app.cache.set(mid, html)\n return html\n\ndef get_db():\n top = _app_ctx_stack.top\n if not hasattr(top, 'db'):\n top.db = connect_db()\n return top.db\n\n\n@app.teardown_appcontext\ndef close_db_connection(exception):\n top = _app_ctx_stack.top\n if hasattr(top, 'db'):\n top.db.close()\n\n\n@app.route(\"/\")\ndef top_page():\n user = get_user()\n\n cur = get_db().cursor()\n cur.execute('SELECT count(1) AS c FROM public_memos')\n total = cur.fetchone()['c']\n\n cur.execute(\"SELECT memo_inf.id, memo_inf.content, memo_inf.created_at, usr.username FROM (SELECT id, user, title as content,created_at , is_private FROM memos where is_private = 0 ORDER BY created_at DESC, id DESC LIMIT 100) as memo_inf inner join users usr on memo_inf.user = usr.id\")\n memos = cur.fetchall()\n cur.close()\n\n return render_template(\n 'index.html',\n total=total,\n memos=memos,\n page=0,\n user=user\n )\n\n@app.route(\"/recent/\")\ndef recent(page):\n user = get_user()\n\n cur = get_db().cursor()\n cur.execute('SELECT count(1) AS c FROM public_memos')\n total = cur.fetchone()['c']\n\n cur.execute(\"SELECT memo_inf.id, memo_inf.user, memo_inf.title as content, memo_inf.created_at, usr.username FROM memos as memo_inf inner join users usr on memo_inf.user = usr.id inner join (SELECT memo FROM public_memos WHERE id BETWEEN \" + str(page * 100 + 1) + \" and \" + str(page * 100 + 100) + \") as memo_order on memo_inf.id = memo_order.memo\")\n\n #cur.execute(\"SELECT memo_inf.id, memo_inf.user, memo_inf.content, memo_inf.created_at, usr.username FROM (SELECT id,user, title as content,created_at , is_private FROM memos where is_private = 0 and id >= \" + str(page * 100) + \" ORDER BY created_at DESC, id DESC LIMIT 100 ) as memo_inf inner join users usr on memo_inf.user = usr.id\")\n memos = cur.fetchall()\n if len(memos) == 0:\n abort(404)\n\n cur.close()\n\n return render_template(\n 'index.html',\n total=total,\n memos=memos,\n page=page,\n user=user\n )\n\n\n@app.route(\"/mypage\")\ndef mypage():\n user = get_user()\n require_user(user)\n\n cur = get_db().cursor()\n cur.execute(\"SELECT id, title as content, is_private, created_at, updated_at FROM memos WHERE user=%s ORDER BY created_at DESC\", user[\"id\"])\n memos = cur.fetchall()\n cur.close()\n\n return render_template(\n 'mypage.html',\n user=user,\n memos=memos,\n )\n\n@app.route(\"/signin\", methods=['GET','HEAD'])\ndef signin():\n user = get_user()\n return render_template('signin.html', user=user)\n\n\n@app.route(\"/signin\", methods=['POST'])\ndef signin_post():\n\n db = get_db()\n cur = db.cursor()\n username = request.form['username']\n password = request.form['password']\n cur.execute('SELECT id, username, password, salt FROM users WHERE username=%s', username)\n user = cur.fetchone()\n if user and user[\"password\"] == hashlib.sha256(bytes(user[\"salt\"] + password, 'UTF-8')).hexdigest():\n session[\"user_id\"] = user[\"id\"]\n session[\"user_username\"] = user[\"username\"]\n session[\"token\"] = hashlib.sha256(os.urandom(40)).hexdigest()\n set_mem(user[\"id\"]) # for memcached\n #cur.execute(\"UPDATE users SET last_access=now() WHERE id=%s\", user[\"id\"])\n cur.close()\n db.commit()\n return redirect(url_for(\"mypage\"))\n else:\n return render_template('signin.html', user=None)\n\n\n@app.route(\"/signout\", methods=['POST'])\ndef signout():\n anti_csrf()\n session.clear()\n\n @after_this_request\n def remove_cookie(response):\n response.set_cookie(app.session_cookie_name, \"\", expires=0)\n return response\n\n return redirect(url_for(\"top_page\"))\n\n@app.route(\"/memo/\")\ndef memo(memo_id):\n user = get_user()\n\n cur = get_db().cursor()\n #cur.execute('SELECT id, user, content, is_private, created_at, updated_at FROM memos WHERE id=%s', memo_id)\n cur.execute(\"SELECT memo.id, memo.user, memo.content, memo.is_private, memo. created_at, memo.updated_at, usr.username FROM (SELECT id, user, content, is_private, created_at, updated_at FROM memos WHERE id=\" + str(memo_id) + \") memo inner join users usr on memo.user = usr.id\")\n memo = cur.fetchone()\n if not memo:\n abort(404)\n\n if memo[\"is_private\"] == 1:\n if not user or user[\"id\"] != memo[\"user\"]:\n abort(404)\n\n #cur.execute('SELECT username FROM users WHERE id=%s', memo[\"user\"])\n #memo[\"username\"] = cur.fetchone()[\"username\"]\n memo[\"content_html\"] = gen_markdown(memo_id, memo[\"content\"])\n #memo[\"content_html\"] = markdown(memo[\"content\"])\n if user and user[\"id\"] == memo[\"user\"]:\n cond = \"\"\n mem_index = \"list_memo_pri_\" + str(memo[\"user\"]) # e.g. list_memo_pri_80\n logging.debug(\"get private\")\n else:\n cond = \"AND is_private=0\"\n mem_index = \"list_memo_\" + str(memo[\"user\"]) # e.g. list_memo_80\n logging.debug(\"get public\")\n memos = []\n older = None\n newer = None\n # save memcached\n if app.cache.get(mem_index) == None:\n # 1st\n list_memo = [] # memcached\n logging.debug(\"mem_index is not exist\")\n cur.execute(\"SELECT id FROM memos WHERE user=%s \" + cond + \" ORDER BY created_at\", memo[\"user\"])\n memos = cur.fetchall()\n for i in range(len(memos)):\n list_memo.append(memos[i][\"id\"]) #memcached\n #cur.close()\n app.cache.set(mem_index, list_memo)\n str_res = app.cache.get(mem_index)\n else:\n # after 2nd \n logging.debug(\"mem_index is exist\")\n str_res = app.cache.get(mem_index)\n if str_res != \"\":\n res = list(map(int, str_res.split(','))) # String to list\n now = res.index(memo[\"id\"])\n older = {'id': res[ now - 1 ]}\n if res[ now ] != res[-1]:\n newer = {'id': res[ now + 1 ]}\n #cur.execute(\"SELECT id FROM memos WHERE user=%s \" + cond + \" ORDER BY created_at\", memo[\"user\"])\n #memos = cur.fetchall()\n #for i in range(len(memos)):\n # if memos[i][\"id\"] == memo[\"id\"]:\n # if i > 0:\n # older = memos[i - 1]\n # if i < len(memos) - 1:\n # newer = memos[i + 1]\n cur.close()\n\n return render_template(\n \"memo.html\",\n user=user,\n memo=memo,\n older=older,\n newer=newer,\n )\n\n@app.route(\"/memo\", methods=['POST'])\ndef memo_post():\n user = get_user()\n require_user(user)\n anti_csrf()\n\n db = get_db()\n cur = db.cursor()\n cur.execute(\n \"INSERT INTO memos (user, content, is_private, created_at, title) VALUES (%s, %s, %s, now(), %s)\",\n ( user[\"id\"],\n request.form[\"content\"],\n int(request.form.get(\"is_private\") or 0),\n\t request.form[\"content\"].split('\\n')[0]\n )\n )\n memo_id = db.insert_id()\n logging.debug(memo_id)\n\n if request.form.get(\"is_private\") != 1:\n cur.execute(\n \"INSERT INTO public_memos (memo) VALUES (%s)\",\n (memo_id)\n )\n cur.close()\n db.commit()\n\n #pri\n mem_key_pri = \"list_memo_pri_\" + str(user[\"id\"]) # e.g. list_memo_pri_80\n if len(app.cache.get(mem_key_pri)) > 0:\n app.cache.append(mem_key_pri, ',' + str(memo_id))\n else:\n app.cache.add(mem_key_pri, str(memo_id))\n\n #public\n mem_key_pub = \"list_memo_\" + str(user[\"id\"]) # e.g. list_memo_pri_80\n if len(app.cache.get(mem_key_pub)) > 0:\n app.cache.append(mem_key_pub, ',' + str(memo_id))\n else:\n app.cache.add(mem_key_pub, str(memo_id))\n\n return redirect(url_for('memo', memo_id=memo_id))\n\n\ndef set_mem(user_id):\n cur = get_db().cursor()\n #private\n cur.execute(\"SELECT id FROM memos WHERE user=%s ORDER BY created_at\", user_id)\n memo_pri = cur.fetchall()\n list_memo_pri = []\n for i in range(len(memo_pri)):\n list_memo_pri.append(memo_pri[i][\"id\"]) #memcached\n # list to String\n str_memo_pri=','.join(map(str, list_memo_pri))\n app.cache.set(\"list_memo_pri_\" + str(user_id), str_memo_pri)\n # sample list to String\n #str_memo_pri=','.join(map(str, list_memo_pri))\n # String to list\n #test_memo_pri= list(map(int, str_memo_pri.split(',')))\n # sample end\n #public\n cur.execute(\"SELECT id FROM memos WHERE user=%s AND is_private=0 ORDER BY created_at\", user_id)\n memo_pub = cur.fetchall()\n list_memo_pub = []\n for i in range(len(memo_pub)):\n list_memo_pub.append(memo_pub[i][\"id\"]) #memcached\n str_memo_pub=','.join(map(str, list_memo_pub))\n app.cache.set(\"list_memo_\" + str(user_id), str_memo_pub)\n cur.close()\n\nif __name__ == \"__main__\":\n load_config()\n port = int(os.environ.get(\"PORT\", '5000'))\n app.run(debug=1, host='0.0.0.0', port=port)\nelse:\n load_config()\n","sub_path":"python/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":11221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"435557961","text":"import pytest\nimport numpy as np\nimport pandas as pd\n\n\n\n@pytest.fixture(params=[['cpr_name','loc_zip'],[]])\ndef dims_name(request):\n return request.param\n\n@pytest.fixture\ndef target_name():\n return 'sum'\n\n@pytest.fixture\ndef func():\n return np.median\n\n@pytest.fixture\ndef train_data():\n df = pd.DataFrame({'cpr_name':['a1','a2','a3','a4','a5'],\n 'loc_zip' :['1','2','3','4','5'],\n 'sum' :[1,2,3,4,5]}) \n return df\n\n\n\ndef test_Single_aggr(dims_name, target_name, func, train_data):\n from gp_prediction.aggregation_forest import Single_aggr, Aggr_forest\n single_aggr = Single_aggr(train_data, dims_name, target_name, func)\n assert single_aggr.dims_name == dims_name\n\n if dims_name != []:\n assert single_aggr.aggr.equals(train_data.groupby(dims_name).agg([func]))\n assert np.isnan(single_aggr.predict(())) == True\n assert np.isnan(single_aggr.predict(('a6','1'))) == True\n assert single_aggr.predict(('a5','5')) == 5\n\n # Global average table\n if dims_name == []:\n assert single_aggr.aggr == np.median([1,2,3,4,5])\n assert single_aggr.predict(()) == single_aggr.aggr\n assert single_aggr.predict(('a6','6')) == single_aggr.aggr\n assert single_aggr.predict(('a5','5')) == single_aggr.aggr\n\n\ndef test_Aggr_forest_with_initial_weight(train_data, dims_name, target_name, func):\n from gp_prediction.aggregation_forest import Single_aggr, Aggr_forest\n\n if dims_name != []:\n initial_weight_vector = [0.1,0.2,0.3,0.4]\n aggr_forest = Aggr_forest(train_data, dims_name, target_name, func, initial_weight_vector)\n\n assert aggr_forest.full_dims_name == dims_name\n assert aggr_forest.weights == initial_weight_vector\n assert aggr_forest.all_dims_combi == [[],['cpr_name'],['loc_zip'],['cpr_name','loc_zip']]\n\n assert abs(aggr_forest.unipredict(('a1','1')) - 1.2) < 0.0001\n assert abs(aggr_forest.unipredict(('a1','2')) - 11/float(6)) < 0.0001\n assert abs(aggr_forest.unipredict(('a6','a6')) -3) < 0.0001\n assert abs(aggr_forest.unipredict(('a1','6')) -5/float(3)) < 0.0001\n\n\n mixed = aggr_forest.predict_without_mixing(pd.DataFrame({'cpr_name':['a1','a1','a6'], \n 'loc_zip':['1','2','a6']}))\n\n np.testing.assert_array_almost_equal(mixed, np.asarray([[3,1,1,1],\n [3,1,2, np.nan],\n [3, np.nan, np.nan, np.nan]]))\n\n # test robustness against 0 weight\n if dims_name != []:\n initial_weight_vector = [0, 0.1, 0.2, 0.7]\n assert abs(aggr_forest.unipredict(('a6','a6')) -3) < 0.0001\n\n\n # contains only global average table\n if dims_name == []:\n initial_weight_vector = [1]\n aggr_forest = Aggr_forest(train_data, dims_name, target_name, func, initial_weight_vector)\n\n assert aggr_forest.full_dims_name == dims_name\n assert aggr_forest.weights == initial_weight_vector\n assert aggr_forest.all_dims_combi == [[]]\n\n assert aggr_forest.unipredict(('a1','1')) == 3\n assert aggr_forest.unipredict(('a1','2')) == 3\n assert aggr_forest.unipredict(('a6','a6')) == 3\n\n\n\n\"\"\"\nTest case initial_weight_vector is None\n\"\"\"\ndef test_Aggr_forest_without_initial_weight(train_data, dims_name, target_name, func):\n from gp_prediction.aggregation_forest import Single_aggr, Aggr_forest\n initial_weight_vector = None\n\n aggr_forest = Aggr_forest(train_data, dims_name, target_name, func, initial_weight_vector)\n assert aggr_forest.weights == None\n","sub_path":"gp_prediction/tests/test_aggregation_forest.py","file_name":"test_aggregation_forest.py","file_ext":"py","file_size_in_byte":3697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"245163942","text":"import os \nfrom flask import Flask \nfrom flaskr.db import get_db\nimport click\nimport json\n\ndef create_app(test_config = None) : \n app = Flask(__name__, instance_relative_config=True)\n app.config.from_mapping(\n SECRET_KEY = \"dev\", \n DATABASE = os.path.join(app.instance_path, 'flaskr.sqlite')\n\n )\n\n if test_config is None : \n app.config.from_pyfile(\"config.py\", silent = True )\n else : \n app.config.from_mapping(test_config)\n \n try :\n os.mkdir(app.instance_path)\n except OSError : \n pass\n\n @app.route(\"/hello\")\n def hello(): \n #inst = get_db().execute(\n # \"SELECT password FROM users WHERE username = 'mihir'\"\n # #\"SELECT * FROM users\"\n \n #).fetchall()\n #click.echo(inst)\n return \"hello\"\n\n from . import db, myPage, auth\n \n db.connectApp2db(app)\n app.register_blueprint(myPage.bp)\n app.register_blueprint(auth.bp)\n #app.register_blueprint(home.bp)\n #app.add_url_rule(\"/\", endpoint=\"index\")\n return app \nif __name__ == '__init__':\n app = create_app()\n app.run() \n","sub_path":"Deprecated/RoutingEngineAlgo/flaskr/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"610206479","text":"\"\"\"\nModule for the joint statistical\nanalysis of images\n\"\"\"\n\nimport esmraldi.imzmlio as imzmlio\nimport numpy as np\nimport cv2 as cv\nfrom sklearn import metrics\nfrom sklearn.decomposition import PCA\nfrom sklearn.decomposition import NMF\nfrom sklearn.cluster import KMeans, AffinityPropagation\nfrom sklearn.manifold import TSNE\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics.pairwise import cosine_similarity, cosine_distances\nfrom sklearn.preprocessing import StandardScaler\n\ndef clustering_affinity(X_r):\n \"\"\"\n Clustering by affinity propagation\n\n Based on scikit module\n\n Parameters\n ----------\n X_r: np.ndarray\n fitted data (e.g. by PCA)\n\n Returns\n ----------\n np.ndarray\n clustered data\n\n \"\"\"\n af = AffinityPropagation(preference=-50).fit(X_r)\n return af\n\ndef clustering_kmeans(X_r):\n \"\"\"\n Clustering by kmeans\n\n Based on scikit module\n\n Parameters\n ----------\n X_r: np.ndarray\n fitted data (e.g. by PCA)\n\n Returns\n ----------\n np.ndarray\n clustered data\n\n \"\"\"\n kmeans = KMeans(n_clusters=5, random_state=0).fit(X_r)\n return kmeans\n\ndef flatten(image_maldi, is_spectral=False):\n \"\"\"\n Preprocess for reduction : flattens\n a stack image with OpenCV\n\n Parameters\n ----------\n image_maldi: numpy.ndarray\n input image\n\n Returns\n ----------\n numpy.ndarray\n normalized image\n\n \"\"\"\n shape = image_maldi.shape\n\n if is_spectral:\n flatten_first_dims = np.prod(shape[:-1])\n norm_img = np.zeros(shape=(flatten_first_dims, shape[-1]), dtype=image_maldi.dtype)\n for index in range(image_maldi.shape[-1]):\n norm_img[..., index] = image_maldi[..., index].flatten()\n else:\n flatten_first_dims = np.prod(shape)\n norm_img = np.zeros(shape=(flatten_first_dims, 1), dtype=image_maldi.dtype)\n norm_img[..., 0] = image_maldi.flatten()\n\n norm_img = norm_img.transpose()\n return norm_img\n\n\ndef pca(image, n=5):\n \"\"\"\n Performs PCA on image array.\n\n Each image is represented as a point after fitting.\n\n Based on scikit module\n\n Parameters\n ----------\n image: np.ndarray\n collection of images\n n: int\n number of components\n\n Returns\n ----------\n sklearn.decomposition.PCA\n pca object\n \"\"\"\n pca = PCA(n_components=n)\n fit_pca = pca.fit(image)\n return fit_pca\n\ndef nmf(image, n=5):\n \"\"\"\n Performs NMF on image array.\n\n Each image is represented as a point after fitting.\n\n Based on scikit module\n\n Parameters\n ----------\n image: np.ndarray\n collection of images\n n: int\n number of components\n\n Returns\n ----------\n sklearn.decomposition.NMF\n nmf object\n \"\"\"\n nmf_obj = NMF(n_components=n, init='nndsvda', solver='mu', random_state=0, beta_loss=\"kullback-leibler\")\n fit_nmf = nmf_obj.fit(image)\n return fit_nmf\n\n\ndef post_processing(pca_maldi, pca_mri):\n \"\"\"\n Computes t-SNE from dimension reduction data.\n\n Based on scikit module\n\n Parameters\n ----------\n pca_maldi: np.ndarray\n PCA coordinates for the MALDI images\n pca_mri: np.ndarray\n PCA coordinates for the MRI image\n\n Returns\n ----------\n np.ndarray\n tSNE coordinates for MALDI\n np.ndarray\n tSNE coordinates for MRI\n \"\"\"\n size_train = pca_maldi.shape[0]\n X = np.vstack((pca_maldi,pca_mri))\n X_tsne = TSNE(n_components=2, random_state=0).fit_transform( X )\n X_train_tsne = X_tsne[0:size_train,:]\n X_test_tsne = X_tsne[size_train:,:]\n return X_train_tsne, X_test_tsne\n\ndef weighted_distance(X, weights):\n \"\"\"\n Weighted euclidean distance\n for similarity measure\n\n Parameters\n ----------\n X: np.ndarray\n coordinates\n weights: list\n weights for each coordinate\n\n \"\"\"\n return np.sqrt(np.sum(X**2 * weights))\n\ndef select_images(images, point_mri, centers, weights, mzs, labels, top=1):\n \"\"\"\n Sort the (MALDI) images according to their proximity to\n the MRI image\n\n Parameters\n ----------\n images: np.ndarray\n MALDI images\n centers: np.ndarray\n MALDI images (reduced)\n point_mri: np.ndarray\n MRI image (reduced)\n weights: list\n weights for each coordinate\n mzs: list\n m/z ratios\n labels: np.ndarray\n clustering labels (optional)\n top: int\n number of images to extract\n\n Returns\n ----------\n np.ndarray\n sorted MALDI images based on proximity to RI\n np.ndarray\n sorted mzs based on proximity to MRI\n np.ndarray\n metric values used to sort MALDI\n \"\"\"\n norm_factor = point_mri.copy()\n norm_factor[norm_factor == 0] = 1e-14\n print(norm_factor)\n diff_norm = np.array([np.abs(center-point_mri)/norm_factor for center in centers])\n distances = np.array([weighted_distance(d, weights) for d in diff_norm])\n indices = [i for i in range(len(distances))]\n indices.sort(key=lambda x: distances[x])\n if top is None:\n similar_images = images[..., indices]\n similar_mzs = mzs[indices]\n distances = distances[indices]\n else:\n indices = np.array(indices)\n condition = np.any(np.array([labels == indices[i] for i in range(top)]), axis=0)\n similar_images = images[..., condition]\n similar_mzs = mzs[condition]\n return similar_images, similar_mzs, distances\n\ndef extract_ratio_images(image, mzs):\n \"\"\"\n Extracts ratio images : image_n / image_{n-x}, x > 0\n\n Computing (n**2-n)/2 images\n\n Parameters\n ----------\n image: np.ndarray\n array of input images\n mzs: list\n associated labels (e.g. m/z ratios)\n \"\"\"\n z = image.shape[-1]\n c = 0\n new_mzs = np.zeros(((z**2-z)//2,), dtype='object')\n ratio_images = np.zeros(image.shape[:-1] + ((z**2-z)//2, ), dtype=np.uint8)\n for i in range(z-1, 0, -1):\n for j in range(i):\n first_image = image[..., i].astype(np.float64)\n second_image = image[..., j].astype(np.float64)\n divided = np.zeros_like(first_image, dtype=np.float64)\n np.divide(first_image, second_image, out=divided, where=second_image!=0)\n divided = np.uint8(cv.normalize(divided, None, 0, 255, cv.NORM_MINMAX))\n if np.all((divided == divided.min()) | (divided == divided.max())):\n continue\n ratio_images[..., c] = divided\n current_ratio = mzs[i] + \"/\" + mzs[j]\n new_mzs[c] = current_ratio\n c += 1\n return ratio_images, new_mzs\n\n\ndef get_score(model, data, scorer=metrics.explained_variance_score):\n \"\"\"\n Estimate performance of the model on the data\n\n Parameters\n ----------\n model: sklearn.decomposition\n matrix-factorization technique\n data: np.ndarray\n matrix used to estimate performance\n scorer: sklearn.metrics\n metric\n\n Returns\n ----------\n float\n performance metric\n\n \"\"\"\n prediction = model.inverse_transform(model.transform(data))\n return scorer(data, prediction)\n\n\ndef reconstruct_image_from_components(components, weights):\n \"\"\"\n Synthetic image from a vector and components\n from a dimension reduction method\n\n Parameters\n ----------\n components: np.ndarray\n Component images\n weights: np.ndarray\n point\n\n Returns\n ----------\n np.ndarray\n synthetic image\n \"\"\"\n return np.sum([components[..., i].T * weights[i] for i in range(len(weights))], axis=0)\n\ndef closest_pixels_cosine(image1, image2):\n \"\"\"\n Find closest pixels using cosine measure\n Spatial localization\n\n Parameters\n ----------\n image1: np.ndarray\n image 1\n image2: np.ndarray\n image 2\n\n Returns\n ----------\n np.ndarray\n indices of pixels ordered by similarity\n \"\"\"\n indices = np.where((image1 != 0) & (image2 != 0))[0]\n image1_positive = np.float64(image1[indices])\n image2_positive = np.float64(image2[indices])\n image1_positive /= np.linalg.norm(image1_positive.flatten())\n image2_positive /= np.linalg.norm(image2_positive.flatten())\n abs_diff = np.abs(image1_positive - image2_positive)\n indices_abs_diff = [i for i in range(len(indices))]\n indices_abs_diff.sort(key=lambda x:abs_diff[x], reverse=False)\n return indices[indices_abs_diff]\n\ndef cosine_neighborhood(image1, image2, r):\n \"\"\"\n Cosine similarity taking a neighborhood into account\n\n Parameters\n ----------\n image1: np.ndarray\n image 1\n image2: np.ndarray\n image 2\n r: int\n radius of neighborhood\n\n Returns\n ----------\n float\n local cosine similarity\n\n \"\"\"\n size = (2*r+1)**2\n shape = np.prod(image1.shape[:-1])*size\n image1_neighborhood = np.zeros((image1.shape[-1], shape))\n image2_neighborhood = np.zeros((1, shape))\n for k in range(image1.shape[-1]):\n for index in np.ndindex(image1.shape[:-1]):\n image1_index = index + (k,)\n values_im1 = np.array([image1[image1_index]] * size)\n\n flat_index = np.ravel_multi_index(index, image1.shape[:-1])\n flat_index *= size\n image1_neighborhood[k, flat_index:flat_index+size] = values_im1\n if k == 0:\n values_im2 = image2[index[0]-r:index[0]+r+1, index[1]-r:index[1]+r+1].copy().flatten()\n if not values_im2.any():\n values_im2 = np.zeros((size,))\n image2_neighborhood[k, flat_index:flat_index+size] = values_im2\n\n sim = cosine_similarity(image1_neighborhood, image2_neighborhood)\n return sim\n\n\ndef explaining_eigenvector(image_eigenvectors, weights_target, weights_reference):\n \"\"\"\n Finding the most contributing eigenvector\n (or component image) in the target\n\n Parameters\n ----------\n image_eigenvectors: np.ndarray\n component images\n weights_target: np.ndarray\n weight vector of target (NMF coordinates)\n weights_reference: np.ndarray\n weight vector of reference (NMF coordinates)\n\n Returns\n ----------\n np.ndarray\n the component image which explains target w.r.t reference\n \"\"\"\n diff_w = np.abs(weights_target - weights_reference)/np.minimum(weights_target, weights_reference)\n sorted_index = diff_w.argsort()\n reconstruction = np.zeros_like(image_eigenvectors[..., 0])\n previous_variance = np.inf\n for i in range(image_eigenvectors.shape[-1]):\n index = sorted_index[i]\n current_image = weights_target[index] * image_eigenvectors[..., index]\n reconstruction += current_image\n reconstruction_pos = reconstruction[reconstruction>0]\n variance = np.var(reconstruction_pos)/np.mean(reconstruction_pos)\n if variance > previous_variance:\n return current_image\n elif i > image_eigenvectors.shape[-1]//2:\n return image_eigenvectors[..., sorted_index[0]]\n previous_variance = variance\n return image_eigenvectors[..., sorted_index[0]]\n\ndef closest_reconstruction(image, image1, image2, image_eigenvectors, image_eigenvectors_2=None):\n \"\"\"\n Find proximities based on the similarity between projection images.\n\n Parameters\n ----------\n image: np.ndarray\n None\n image1: np.ndarray\n reference image\n image2: np.ndarray\n target image\n image_eigenvectors: np.ndarray\n component images associated to image 1\n image_eigenvectors_2: np.ndarray\n component images associated to image 2, if different\n\n Returns\n ----------\n np.ndarray\n average differences between reconstructions for each image\n \"\"\"\n if image_eigenvectors_2 is None:\n image_eigenvectors_2 = image_eigenvectors\n w_2 = image2 / np.sum(image2)\n reconstructed_image2 = reconstruct_image_from_components(image_eigenvectors_2, w_2.T)\n reconstructed_image2 = imzmlio.normalize(reconstructed_image2)\n diff = np.zeros((image1.shape[0],))\n for index in range(image1.shape[0]):\n w = image1[index, ...] / np.sum(image1[index, ...])\n reconstructed_image = reconstruct_image_from_components(image_eigenvectors, w.T)\n reconstructed_image = imzmlio.normalize(reconstructed_image)\n diff[index] = np.mean(np.abs(reconstructed_image2 - reconstructed_image))\n return diff\n\ndef remove_indices(image):\n \"\"\"\n Utility function to remove images\n with only 0 intensities of if the median value\n is the maximum value\n\n Parameters\n ----------\n image: np.ndarray\n image\n\n Returns\n ----------\n list\n indices to remove\n \"\"\"\n to_remove = []\n for i in range(image.shape[-1]):\n current_image = image[..., i]\n obj_image = current_image[current_image > 0]\n if not obj_image.any() or np.median(obj_image) == current_image.max():\n to_remove.append(i)\n return to_remove\n","sub_path":"esmraldi/fusion.py","file_name":"fusion.py","file_ext":"py","file_size_in_byte":12934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"165042539","text":"import numpy as np\nimport itertools\n\nMAX_DISTANCE = 250\n\ndef distanceMatrix():\n return np.matrix([\n [0, 10, 20, 5, 18],\n [10, 0, 15, 32, 10],\n [20, 15, 0, 25, 16],\n [5, 32, 25, 0, 35],\n [18, 10, 16, 35, 0],\n ])\n\ndef path(state):\n path = []\n for colIdx in range(state.shape[1]):\n path.append(np.argmax(state[:,colIdx]))\n return path\n\n\ndef pathDistance(distanceMatrix, path):\n distance = 0\n for index in range(len(path))[1:]:\n distance += distanceMatrix[path[index - 1], path[index]]\n return distance\n\n\ndef isPathValid(state):\n # count the number of times a city was visited, each city should be\n duplicateVisits = 0\n dupRowIdx = None\n for rowIdx in range(state.shape[0]):\n timesVisited = np.sum(state[rowIdx, :])\n\n # visiting a city 1 or 2 times are the only numbers which are valid\n if timesVisited != 1 and timesVisited != 2:\n return False\n\n # it is permissible (and expected) to visit the starting city twice\n if timesVisited == 2:\n duplicateVisits += 1\n dupRowIdx = rowIdx\n\n # ensure that there is only one duplicate visit\n if duplicateVisits != 1:\n return False\n\n # ensure that it is exactly the first and last node that are duplicates\n if state[dupRowIdx,0] != 1 or state[dupRowIdx,-1] != 1:\n return False\n\n # it is never valid to visit muliple cities simultaneously\n for colIdx in range(state.shape[1]):\n citiesVisitedAtOnce = np.sum(state[:, colIdx])\n if citiesVisitedAtOnce != 1:\n return False\n\n return True\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"300272048","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 8 12:22:32 2022\n\n@author: alex\n\"\"\"\n\"\"\"EXTERNAL IMPORTS\"\"\"\nimport keras_tuner as kt\nfrom tensorflow import keras\nimport re\nimport argparse\nimport importlib\nimport numpy as np\nimport os\nfrom tensorflow.python.client import device_lib\nprint(device_lib.list_local_devices())\n\n#%%\n\"\"\"REPRODUCIBILITY\"\"\"\nseed_value=42\n# 1. Set `PYTHONHASHSEED` environment variable at a fixed value\nos.environ['PYTHONHASHSEED']=str(seed_value)\n# Disable GPU\n# os.environ['CUDA_VISIBLE_DEVICES'] = ''\n# 2. Set `python` built-in pseudo-random generator at a fixed value\nimport random\nrandom.seed(seed_value)\n# 3. Set `numpy` pseudo-random generator at a fixed value\nnp.random.seed(seed_value)\n# 4. Set `tensorflow` pseudo-random generator at a fixed value\nimport tensorflow as tf\ntf.random.set_seed(seed_value) # tensorflow 2.x\n# 5. Configure a new global `tensorflow` session\n# session_conf = tf.compat.v1.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=3,allow_soft_placement=True)\n# sess = tf.compat.v1.Session(graph=tf.compat.v1.get_default_graph(), config=session_conf)\n# tf.compat.v1.keras.backend.set_session(sess)\n#%%\n\"\"\" OUR ARGUMENTS AND IMPORTS \"\"\"\nparser = argparse.ArgumentParser(description='Train neural regression and save model')\nparser.add_argument('chosen_config', type=str,\n help='The name of the config file (without .py), which must be located in configurations/cluster.')\nparser.add_argument('experiment',\n help='The name of the experiment config file (without .py), which must be located in configurations.')\n\nparser.add_argument('--model-name', metavar='model_name',type=str, default=argparse.SUPPRESS,\n help='Custom model name to save (provide without extension nor directory)')\n\nargs, unknown = parser.parse_known_args()\nexperiment='configurations.'+args.experiment\nimportlib.invalidate_caches()\n\n\"\"\"THIS EMULATES 'from experiment import *' USING IMPORTLIB \ninfo: \n https://stackoverflow.com/questions/43059267/how-to-do-from-module-import-using-importlib\n\"\"\"\nmdl=importlib.import_module(experiment,package='estratificacion')\n# is there an __all__? if so respect it\nif \"__all__\" in mdl.__dict__:\n names = mdl.__dict__[\"__all__\"]\nelse:\n # otherwise we import all names that don't begin with _\n names = [x for x in mdl.__dict__ if not x.startswith(\"_\")]\nglobals().update({k: getattr(mdl, k) for k in names}) #brings everything into namespace\n\nfrom configurations.default import *\n\nif args.experiment!=experiment:#required arg\n EXPERIMENT=args.experiment #OVERRIDE (this is the only variable from the imported experiment module that needs to be changed, because it creates moddel and prediction directories)\nMODELPATH=MODELSPATH+EXPERIMENT+'/'\nUSEDCONFIGPATH+=EXPERIMENT+'/'\nALGORITHM='neuralNetworkSimple'\nCONFIGNAME='neuralNetworkSimple.py'\nPREDPATH=os.path.join(OUTPATH,EXPERIMENT)\nFIGUREPATH=os.path.join(ROOTPATH,'figures',EXPERIMENT)\nMETRICSPATH=os.path.join(METRICSPATH,EXPERIMENT)\n\nTRACEBACK=True\n\nseed_sampling= args.seed_sampling if hasattr(args, 'seed_sampling') else SEED #imported from default configuration\nseed_hparam= args.seed_hparam if hasattr(args, 'seed_hparam') else SEED\nmodel_name= args.model_name if hasattr(args,'model_name') else ALGORITHM\n\n\"\"\" DEFINITION OF THE HYPERPARAMETER SPACE \"\"\"\n\ndef build_model(hp):\n \n # BUILD MODEL\n model = keras.Sequential()\n #input layer\n \n hp_units = hp.Int('units', min_value=32, max_value=512, step=32)\n n_hidden= hp.Int('n_hidden', min_value=1, max_value=4, step=1)\n activ=hp.Choice('activ', values=['elu','relu'])\n hidden_units={f\"units_{i}\":hp.Int(f\"units_{i}\", min_value=32, max_value=512, step=32) for i in range(1,n_hidden+1)}\n model.add(keras.layers.Dense(units=hp_units, activation=activ))\n \n # Tune the learning rate for the optimizer\n # Choose an optimal value from 0.01, 0.001, or 0.0001\n hp_learning_rate = hp.Choice('learning_rate', values=[1e-5, 1e-3, 1e-4])\n\n #hidden layers\n for i in range(1,n_hidden+1):\n model.add(\n keras.layers.Dense(\n # Tune number of units separately.\n units=hidden_units[f\"units_{i}\"],\n activation=activ))\n #output layer\n model.add(keras.layers.Dense(1, activation='sigmoid',name='output',\n kernel_initializer=keras.initializers.he_uniform(seed=42)))\n\n \n model.compile(\n optimizer=keras.optimizers.Adam(learning_rate=hp_learning_rate ), \n loss=\"binary_crossentropy\",metrics=[keras.metrics.AUC()])\n \n \n return model\n\n","sub_path":"configurations/cluster/neuralNetworkSimple.py","file_name":"neuralNetworkSimple.py","file_ext":"py","file_size_in_byte":4615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"193687899","text":"from config import Config\nfrom mimic3models import common_utils\nfrom mimic3models.preprocessing import Discretizer, Normalizer\nfrom mimic3benchmark.readers import InHospitalMortalityReader\nfrom mimic3models.in_hospital_mortality import utils as ihm_utils\n'''\nIn intensive care units, where patients come in with a wide range of health conditions, \ntriaging relies heavily on clinical judgment. ICU staff run numerous physiological tests, \nsuch as bloodwork and checking vital signs, \nto determine if patients are at immediate risk of dying if not treated aggressively.\n'''\n\nimport utils\nimport tensorflow as tf\nfrom tensorflow.contrib import rnn\nimport pickle\nimport numpy as np\nimport sys\nimport random\nimport os\n\ntf.logging.set_verbosity(tf.logging.INFO)\ntf.logging.info(\"*** Loaded Data ***\")\n\nconf = utils.get_config()\nargs = utils.get_args()\nlog = utils.get_logger(args['log_file'])\nvectors, word2index_lookup = utils.get_embedding_dict(conf)\nlookup = utils.lookup\n# let's set pad token to zero padding instead of random padding.\n# might be better for attention as it will give minimum value.\nif conf.padding_type == 'Zero':\n tf.logging.info(\"Zero Padding..\")\n vectors[lookup(word2index_lookup, '')] = 0\n\ntf.logging.info(str(vars(conf)))\ntf.logging.info(str(args))\n\nnumber_epoch = int(args['number_epoch'])\nbatch_size = int(args['batch_size'])\n\nX = tf.placeholder(shape=(None, 48, 76), dtype=tf.float32, name='X') # B*48*76\ny = tf.placeholder(shape=(None), dtype=tf.float32, name='y')\ntext = tf.placeholder(shape=(None, None), dtype=tf.int32, name='text') # B*L\ndropout_keep_prob = tf.placeholder(dtype=tf.float32, name='dropout_kp')\nT = tf.placeholder(dtype=tf.int32)\nN = tf.placeholder(dtype=tf.int32)\n\nW_place = tf.placeholder(tf.float32, shape=vectors.shape, name='W_place')\nW = tf.Variable(W_place, name=\"W\", trainable=False, shape = vectors.shape)\n# W = tf.get_variable(name=\"W\", shape=vectors.shape, initializer=tf.constant_initializer(vectors), trainable=False)\nembeds = tf.nn.embedding_lookup(W, text)\n\nhidden_units = vectors.shape[1]\n\n#avg_word_embedding_mode = bool(int(args['avg_we_model']))\n#baseline = bool(int(args['baseline']))\n\nmodel_name = args['model_name']\nassert model_name in ['baseline', 'avg_we', 'transformer', 'cnn', 'text_only']\nif model_name != 'baseline':\n if model_name == 'avg_we':\n tf.logging.info(\"Average Word Embeddings Model!\")\n text_embeddings = tf.math.reduce_mean(embeds, axis=1, keepdims=False)\n elif model_name == 'transformer':\n tf.logging.info(\"Transformer Encoder Based Model!\")\n key_masks = tf.expand_dims(\n tf.sign(tf.reduce_sum(tf.abs(embeds), axis=-1)), -1)\n embeds += utils.positional_encoding(text, T, N, num_units=hidden_units,\n zero_pad=False, scale=False, scope=\"enc_pe\")\n embeds *= key_masks\n\n # Dropout\n embeds = tf.nn.dropout(embeds, keep_prob=dropout_keep_prob)\n enc = embeds\n # Blocks\n for i in range(conf.num_blocks):\n with tf.variable_scope(\"num_blocks_{}\".format(i)):\n # Multihead Attention\n enc = utils.multihead_attention(queries=enc,\n keys=embeds,\n num_units=hidden_units,\n num_heads=10,\n dropout_rate=dropout_keep_prob,\n causality=False)\n\n # Feed Forward\n enc = utils.feedforward(enc, num_units=[\n 4*hidden_units, hidden_units])\n text_embeddings = tf.reduce_mean(enc, axis=1)\n else:\n tf.logging.info(\"1D Convolution Model\")\n sizes = range(2, 5)\n result_tensors = []\n for ngram_size in sizes:\n # 256 -> 2,3 best yet.\n text_conv1d = tf.layers.conv1d(inputs=embeds, filters=256, kernel_size=ngram_size,\n strides=1, padding='same', dilation_rate=1,\n activation='relu', name='Text_Conv_1D_N{}'.format(ngram_size),\n kernel_regularizer=tf.contrib.layers.l2_regularizer(scale=0.01))\n text_conv1d = tf.reduce_max(text_conv1d, axis=1, keepdims=False)\n result_tensors.append(text_conv1d)\n text_embeddings = tf.concat(result_tensors, axis=1)\n text_embeddings = tf.nn.dropout(\n text_embeddings, keep_prob=dropout_keep_prob)\n\nrnn_cell = rnn.LSTMCell(num_units=256)\nrnn_outputs, _ = tf.nn.dynamic_rnn(rnn_cell, X,\n time_major=False,\n dtype=tf.float32)\n\n#mean_rnn_outputs = tf.math.reduce_mean(rnn_outputs, axis=1, keepdims=False)\nmean_rnn_outputs = rnn_outputs[:, -1, :]\nif model_name == 'baseline':\n logit_X = mean_rnn_outputs\nelif model_name == 'text_only':\n logit_X = text_embeddings\nelse:\n logit_X = tf.concat([text_embeddings, mean_rnn_outputs], axis=1)\n\nlogits_regularizer = tf.contrib.layers.l2_regularizer(scale=0.01)\nlogits = tf.layers.dense(inputs=logit_X, units=1, activation=None, use_bias=False,\n kernel_initializer=tf.contrib.layers.xavier_initializer(), kernel_regularizer=logits_regularizer)\n\n# logits = tf.layers.dense(inputs=mean_rnn_outputs,\n# units=1, activation=None, use_bias=False)\nlogits = tf.squeeze(logits)\nloss = tf.math.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(\n labels=y, logits=logits) + tf.losses.get_regularization_loss(), name='celoss')\nprobs = tf.math.sigmoid(logits)\n\nwith tf.name_scope('train'):\n optimizer = tf.train.AdamOptimizer(learning_rate=conf.learning_rate)\n train_op = optimizer.minimize(\n loss=loss,\n global_step=tf.train.get_global_step())\n\nwith tf.name_scope('train_metric'):\n aucroc, update_aucroc_op = tf.metrics.auc(labels=y, predictions=probs)\n aucpr, update_aucpr_op = tf.metrics.auc(labels=y, predictions=probs,\n curve=\"PR\")\n\nwith tf.name_scope('valid_metric'):\n val_aucroc, update_val_aucroc_op = tf.metrics.auc(\n labels=y, predictions=probs)\n val_aucpr, update_val_aucpr_op = tf.metrics.auc(labels=y, predictions=probs,\n curve=\"PR\")\n\n# Build readers, discretizers, normalizers\ntrain_reader = InHospitalMortalityReader(dataset_dir=os.path.join(conf.ihm_path, 'train'),\n listfile=os.path.join(conf.ihm_path, 'train_listfile.csv'), period_length=48.0)\n\ndiscretizer = Discretizer(timestep=float(conf.timestep),\n store_masks=True,\n impute_strategy='previous',\n start_time='zero')\n\ndiscretizer_header = discretizer.transform(\n train_reader.read_example(0)[\"X\"])[1].split(',')\ncont_channels = [i for (i, x) in enumerate(\n discretizer_header) if x.find(\"->\") == -1]\n\n# choose here which columns to standardize\nnormalizer = Normalizer(fields=cont_channels)\nnormalizer_state = conf.normalizer_state\nif normalizer_state is None:\n normalizer_state = 'ihm_ts{}.input_str:{}.start_time:zero.normalizer'.format(\n conf.timestep, conf.imputation)\n normalizer_state = os.path.join(\n os.path.dirname(__file__), normalizer_state)\nnormalizer.load_params(normalizer_state)\n\nnormalizer = None\ntrain_raw = ihm_utils.load_data(\n train_reader, discretizer, normalizer, conf.small_part, return_names=True)\n\nprint(\"Number of train_raw_names: \", len(train_raw['names']))\n\ntext_reader = utils.TextReader(conf.textdata_fixed, conf.starttime_path)\n\ntrain_text = text_reader.read_all_text_concat_json(train_raw['names'], 48)\ndata = utils.merge_text_raw(train_text, train_raw)\n\ndata_X = data[0]\ndata_y = data[1]\ndata_text = data[2]\ndel data\ndel train_raw\ndel train_text\n\neval_reader = InHospitalMortalityReader(dataset_dir=os.path.join(conf.ihm_path, 'train'),\n listfile=os.path.join(\n conf.ihm_path, 'val_listfile.csv'),\n period_length=48.0)\neval_raw = ihm_utils.load_data(eval_reader, discretizer,\n normalizer, conf.small_part, return_names=True)\n\neval_text = text_reader.read_all_text_concat_json(eval_raw['names'], 48)\ndata = utils.merge_text_raw(eval_text, eval_raw)\n\neval_data_X = data[0]\neval_data_y = data[1]\neval_data_text = data[2]\ndel data\ndel eval_raw\ndel eval_text\n\nif args['mode'] == 'test':\n test_reader = InHospitalMortalityReader(dataset_dir=os.path.join(conf.ihm_path, 'test'),\n listfile=os.path.join(\n conf.ihm_path, 'test_listfile.csv'),\n period_length=48.0)\n test_raw = ihm_utils.load_data(test_reader, discretizer,\n normalizer, conf.small_part, return_names=True)\n text_reader_test = utils.TextReader(\n conf.test_textdata_fixed, conf.test_starttime_path)\n test_text = text_reader_test.read_all_text_concat_json(\n test_raw['names'], 48)\n data = utils.merge_text_raw(test_text, test_raw)\n\n test_data_X = data[0]\n test_data_y = data[1]\n test_data_text = data[2]\n\n del data\n del test_raw\n del test_text\n\n\ndef generate_tensor_text(t, w2i_lookup):\n t_new = []\n max_len = -1\n for text in t:\n tokens = list(map(lambda x: lookup(w2i_lookup, x), str(text).split()))\n if conf.max_len > 0:\n tokens = tokens[:conf.max_len]\n t_new.append(tokens)\n max_len = max(max_len, len(tokens))\n pad_token = w2i_lookup['']\n for i in range(len(t_new)):\n if len(t_new[i]) < max_len:\n t_new[i] += [pad_token] * (max_len - len(t_new[i]))\n return np.array(t_new)\n\n\ndef generate_padded_batches(x, y, t, bs, w2i_lookup):\n batches = []\n begin = 0\n while begin < len(t):\n end = min(begin+batch_size, len(t))\n x_slice = np.stack(x[begin:end])\n y_slice = np.stack(y[begin:end])\n t_slice = generate_tensor_text(t[begin:end], w2i_lookup)\n batches.append((x_slice, y_slice, t_slice))\n begin += batch_size\n return batches\n\n\ndef validate(data_X_val, data_y_val, data_text_val, batch_size, word2index_lookup,\n sess, saver, last_best_val_aucpr, loss, val_aucpr, val_aucroc,\n update_val_aucpr_op, update_val_aucroc_op, save):\n val_batches = generate_padded_batches(\n data_X_val, data_y_val, data_text_val, batch_size, word2index_lookup)\n loss_list = []\n aucpr_obj = utils.AUCPR()\n #sess.run(tf.variables_initializer([v for v in tf.local_variables() if 'valid_metric' in v.name]))\n sess.run(tf.local_variables_initializer())\n for v_batch in val_batches:\n fd = {X: v_batch[0], y: v_batch[1],\n text: v_batch[2], dropout_keep_prob: 1,\n T: v_batch[2].shape[1],\n N: v_batch[2].shape[0],\n W_place: vectors}\n loss_value, _, _, probablities = sess.run(\n [loss, update_val_aucpr_op, update_val_aucroc_op, probs], fd)\n loss_list.append(loss_value)\n aucpr_obj.add(probablities, v_batch[1])\n\n final_aucpr = sess.run(val_aucpr)\n final_aucroc = sess.run(val_aucroc)\n\n tf.logging.info(\"Validation Loss: %f - AUCPR: %f - AUCPR-SKLEARN: %f - AUCROC: %f\" %\n (np.mean(loss_list), final_aucpr, aucpr_obj.get(), final_aucroc))\n\n # aucpr_obj.save()\n changed = False\n if final_aucpr > last_best_val_aucpr:\n changed = True\n if save:\n save_path = saver.save(sess, args['checkpoint_path'])\n tf.logging.info(\n \"Best Model saved in path: %s\" % save_path)\n return max(last_best_val_aucpr, final_aucpr), changed\n\n\ninit = tf.group(tf.global_variables_initializer(),\n tf.local_variables_initializer())\nprint(len(tf.local_variables()))\nsaver = tf.train.Saver()\nlast_best_val_aucpr = -1\n\n\ngpu_config = tf.ConfigProto(device_count={'GPU': 1})\n\nwith tf.Session(config=gpu_config) as sess:\n sess.run(init)\n\n if bool(int(args['load_model'])):\n saver.restore(sess, args['checkpoint_path'])\n last_best_val_aucpr, _ = validate(eval_data_X, eval_data_y, eval_data_text,\n batch_size, word2index_lookup, sess, saver, last_best_val_aucpr,\n loss, val_aucpr, val_aucroc, update_val_aucpr_op, update_val_aucroc_op, False)\n\n if args['mode'] == 'eval':\n assert bool(int(args['load_model']))\n tf.logging.info('Just Evaluating Mode.')\n last_best_val_aucpr, _ = validate(eval_data_X, eval_data_y, eval_data_text,\n batch_size, word2index_lookup, sess, saver, last_best_val_aucpr,\n loss, val_aucpr, val_aucroc, update_val_aucpr_op, update_val_aucroc_op, False)\n sys.exit(0)\n\n if args['mode'] == 'test':\n assert bool(int(args['load_model']))\n tf.logging.info('Testing Mode.')\n last_best_val_aucpr, _ = validate(test_data_X, test_data_y, test_data_text,\n batch_size, word2index_lookup, sess, saver, last_best_val_aucpr,\n loss, val_aucpr, val_aucroc, update_val_aucpr_op, update_val_aucroc_op, False)\n sys.exit(0)\n\n early_stopping = 0\n for epoch in range(number_epoch):\n tf.logging.info(\"Started training for epoch: %d\" % epoch)\n data = list(zip(data_X, data_y, data_text))\n random.shuffle(data)\n data_X, data_y, data_text = zip(*data)\n\n loss_list = []\n\n del data\n\n batches = generate_padded_batches(\n data_X, data_y, data_text, batch_size, word2index_lookup)\n\n tf.logging.info(\"Generated batches for the epoch!\")\n\n for ind, batch in enumerate(batches):\n # train the batch and update parameters.\n fd = {X: batch[0], y: batch[1],\n text: batch[2], dropout_keep_prob: conf.dropout,\n T: batch[2].shape[1],\n N: batch[2].shape[0],\n W_place: vectors}\n _, loss_value, aucpr_value, aucroc_value = sess.run(\n [train_op, loss, update_aucpr_op, update_aucroc_op], fd)\n loss_list.append(loss_value)\n\n # if ind % 200 == 0:\n # tf.logging.info(\n # \"Processed Batch: %d for Epoch: %d\" % (ind, epoch))\n\n current_aucroc = sess.run(aucroc)\n current_aucpr = sess.run(aucpr)\n\n tf.logging.info(\"Loss: %f - AUCPR: %f - AUCROC: %f\" %\n (np.mean(loss_list), current_aucpr, current_aucroc))\n\n # reset aucroc and aucpr local variables\n # sess.run(tf.variables_initializer(\n # [v for v in tf.local_variables() if 'train_metric' in v.name]))\n sess.run(tf.local_variables_initializer())\n loss_list = []\n\n del batches\n tf.logging.info(\"Started Evaluation After Epoch : %d\" % epoch)\n last_best_val_aucpr, changed = validate(eval_data_X, eval_data_y, eval_data_text,\n batch_size, word2index_lookup, sess, saver, last_best_val_aucpr,\n loss, val_aucpr, val_aucroc, update_val_aucpr_op, update_val_aucroc_op, True)\n if changed == False:\n early_stopping += 1\n tf.logging.info(\"Didn't improve!: \" + str(early_stopping))\n else:\n early_stopping = 0\n\n if early_stopping >= 15:\n tf.logging.info(\n \"AUCPR didn't change from last 15 epochs, early stopping\")\n break\n tf.logging.info(\"*End of Epoch.*\\n\")\n","sub_path":"models/ihm_model.py","file_name":"ihm_model.py","file_ext":"py","file_size_in_byte":15986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"26283252","text":"import pyrealsense2 as rs\nimport numpy as np\nimport open3d as o3d\nimport matplotlib.pyplot as plt\n# import cv2\n\ndef show_img(img, dep_img):\n fig, axes = plt.subplots(1, 2, figsize=(10, 6))\n\n for axe, image in zip(axes, [img, dep_img]):\n axe.imshow(image)\n plt.show()\n plt.close()\n\n# ストリーム(Depth/Color)の設定\nconfig = rs.config()\nconfig.enable_stream(rs.stream.color, 640, 480, rs.format.rgb8, 30)\nconfig.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)\n\n# ストリーミング開始\npipeline = rs.pipeline()\nprofile = pipeline.start(config)\n\n# Alignオブジェクト生成\nalign_to = rs.stream.color\nalign = rs.align(align_to)\n\ntry:\n while True:\n # フレーム待ち(Color & Depth)\n frames = pipeline.wait_for_frames()\n aligned_frames = align.process(frames)\n color_frame = aligned_frames.get_color_frame()\n depth_frame = aligned_frames.get_depth_frame()\n\n if not depth_frame or not color_frame:\n continue\n\n img = np.array(color_frame.get_data())\n dep_img = np.array(depth_frame.get_data())\n\n # 取得画像の表示\n # show_img(img, dep_img)\n # print(\"choose command:\")\n # command = input()\n # if command == 'q':\n # exit()\n # else:\n # continue\n \n\nfinally:\n # ストリーミング停止\n pipeline.stop()","sub_path":"realsense/get_face_scann.py","file_name":"get_face_scann.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"358687801","text":"import sys\r\nimport torch\r\nimport torch.nn as nn\r\nfrom torch.nn import init\r\nimport functools\r\nfrom torch.autograd import Variable\r\nimport numpy as np\r\n###############################################################################\r\n# Functions\r\n###############################################################################\r\n\r\n\r\ndef weights_init(m):\r\n\tclassname = m.__class__.__name__\r\n\tif classname.find('Conv') != -1:\r\n\t\tm.weight.data.normal_(0.0, 0.02)\r\n\t\tif hasattr(m.bias, 'data'):\r\n\t\t\tm.bias.data.fill_(0)\r\n\telif classname.find('BatchNorm2d') != -1:\r\n\t\tm.weight.data.normal_(1.0, 0.02)\r\n\t\tm.bias.data.fill_(0)\r\n\r\ndef get_norm_layer(norm_type='instance'):\r\n\tif norm_type == 'batch':\r\n\t\tnorm_layer = functools.partial(nn.BatchNorm2d, affine=True)\r\n\telif norm_type == 'instance':\r\n\t\tnorm_layer = functools.partial(nn.InstanceNorm2d, affine=False)\r\n\telse:\r\n\t\traise NotImplementedError('normalization layer [%s] is not found' % norm_type)\r\n\treturn norm_layer\r\n\r\ndef define_coarse_SR_Encoder(norm_layer):\r\n\tcoarse_SR_Encoder = [nn.ReflectionPad2d(1),\r\n\t\t\t\t\t\t\tnn.Conv2d(3, 64, kernel_size=3, stride=1, padding=0, bias=False),\r\n\t\t\t\t\t\t\tnorm_layer(64),\r\n\t\t\t\t\t\t\tnn.ReLU(True)]\r\n\tfor i in range(3):\r\n\t\tcoarse_SR_Encoder += [ResnetBlock(64, 'reflect', norm_layer, False, False)]\r\n\tcoarse_SR_Encoder += [nn.ReflectionPad2d(1),\r\n\t\t\t\t\t\t\tnn.Conv2d(64, 3, kernel_size=3, stride=1, padding=0, bias=False),\r\n\t\t\t\t\t\t\tnn.Tanh()]\r\n\tcoarse_SR_Encoder = nn.Sequential(*coarse_SR_Encoder)\r\n\treturn coarse_SR_Encoder\r\n\r\ndef define_fine_SR_Encoder(norm_layer):\r\n\tfine_SR_Encoder = [nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1, bias=False),\r\n\t\t\t\t\t\tnorm_layer(64),\r\n\t\t\t\t\t\tnn.ReLU(True)]\r\n\tfor i in range(12):\r\n\t\tfine_SR_Encoder += [ResnetBlock(64, 'reflect', norm_layer, False, False)]\r\n\tfine_SR_Encoder += [nn.ReflectionPad2d(1),\r\n\t\t\t\t\t\tnn.Conv2d(64, 64, kernel_size=3, stride=1, padding=0, bias=False),\r\n\t\t\t\t\t\tnn.Tanh()]\r\n\tfine_SR_Encoder = nn.Sequential(*fine_SR_Encoder)\r\n\treturn fine_SR_Encoder\r\n\r\ndef define_prior_Estimation_Network(norm_layer):\r\n\tprior_Estimation_Network = [nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False),\r\n\t\t\t\t\t\t\t\tnorm_layer(64),\r\n\t\t\t\t\t\t\t\tnn.ReLU(True)]\r\n\tprior_Estimation_Network += [Residual(64, 128)]\r\n\tfor i in range(2):\r\n\t\tprior_Estimation_Network += [ResnetBlock(128, 'reflect', norm_layer, False, False)]\r\n\tfor i in range(2):\r\n\t\tprior_Estimation_Network += [HourGlassBlock(128, 3, norm_layer)]\r\n\tprior_Estimation_Network += [nn.Conv2d(128, 11, kernel_size=1, stride=1),\r\n\t\t\t\t\t\t\t\t\tnorm_layer(11),\r\n\t\t\t\t\t\t\t\t\tnn.ReLU(True)]\r\n\r\n\tprior_Estimation_Network = nn.Sequential(*prior_Estimation_Network)\r\n\treturn prior_Estimation_Network\r\n\r\ndef define_fine_SR_Decoder(norm_layer):\r\n\tfine_SR_Decoder = [nn.Conv2d(75, 64, kernel_size=3, stride=1, padding=1, bias=False),\r\n\t\t\t\t\t\tnorm_layer(64),\r\n\t\t\t\t\t\tnn.ReLU(True)]\r\n\tfine_SR_Decoder += [nn.ConvTranspose2d(64, 64, kernel_size=3, stride=2, padding=1, output_padding=1, bias=False),\r\n\t\t\t\t\t\tnorm_layer(64),\r\n\t\t\t\t\t\tnn.ReLU(True)]\r\n\tfor i in range(3):\r\n\t\tfine_SR_Decoder += [ResnetBlock(64, 'reflect', norm_layer, False, False)]\r\n\tfine_SR_Decoder += [nn.ReflectionPad2d(1),\r\n\t\t\t\t\t\tnn.Conv2d(64, 3, kernel_size=3, stride=1, padding=0, bias=False),\r\n\t\t\t\t\t\tnn.Tanh()]\r\n\tfine_SR_Decoder = nn.Sequential(*fine_SR_Decoder)\r\n\treturn fine_SR_Decoder\r\n\r\ndef define_G(input_nc, output_nc, ngf, norm='batch', use_dropout=False, gpu_ids=[], use_parallel=True, learn_residual=False):\r\n\tnetG = None\r\n\tuse_gpu = len(gpu_ids) > 0\r\n\tnorm_layer = get_norm_layer(norm_type=norm)\r\n\r\n\tif use_gpu:\r\n\t\tassert(torch.cuda.is_available())\r\n\r\n\tnetG = Generator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=9, gpu_ids=gpu_ids, use_parallel=use_parallel, learn_residual=learn_residual)\r\n\t\r\n\tif len(gpu_ids) > 0:\r\n\t\tnetG.cuda(gpu_ids[0])\r\n\tnetG.apply(weights_init)\r\n\treturn netG\r\n\r\n\r\ndef define_D(input_nc, ndf, which_model_netD,\r\n\t\t\t n_layers_D=3, norm='batch', use_sigmoid=False, gpu_ids=[], use_parallel = True):\r\n\tnetD = None\r\n\tuse_gpu = len(gpu_ids) > 0\r\n\tnorm_layer = get_norm_layer(norm_type=norm)\r\n\r\n\tif use_gpu:\r\n\t\tassert(torch.cuda.is_available())\r\n\tif which_model_netD == 'basic':\r\n\t\tnetD = NLayerDiscriminator(input_nc, ndf, n_layers=3, norm_layer=norm_layer, use_sigmoid=use_sigmoid, gpu_ids=gpu_ids, use_parallel=use_parallel)\r\n\telif which_model_netD == 'n_layers':\r\n\t\tnetD = NLayerDiscriminator(input_nc, ndf, n_layers_D, norm_layer=norm_layer, use_sigmoid=use_sigmoid, gpu_ids=gpu_ids, use_parallel=use_parallel)\r\n\telse:\r\n\t\traise NotImplementedError('Discriminator model name [%s] is not recognized' %\r\n\t\t\t\t\t\t\t\t which_model_netD)\r\n\tif use_gpu:\r\n\t\tnetD.cuda(gpu_ids[0])\r\n\tnetD.apply(weights_init)\r\n\treturn netD\r\n\r\n\r\ndef print_network(net):\r\n\tnum_params = 0\r\n\tfor param in net.parameters():\r\n\t\tnum_params += param.numel()\r\n\tprint(net)\r\n\tprint('Total number of parameters: %d' % num_params)\r\n\r\n\r\n##############################################################################\r\n# Classes\r\n##############################################################################\r\n\r\n\r\n# Defines the generator that consists of Resnet blocks between a few\r\n# downsampling/upsampling operations.\r\n# Code and idea originally from Justin Johnson's architecture.\r\n# https://github.com/jcjohnson/fast-neural-style/\r\n\r\nclass Generator(nn.Module):\r\n\tdef __init__(self, input_nc, output_nc, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False, n_blocks=6, gpu_ids=[], use_parallel=True, learn_residual=False, padding_type='reflect'):\r\n\t\tassert(n_blocks >= 0)\r\n\t\tsuper(Generator, self).__init__()\r\n\t\tself.input_nc = input_nc\r\n\t\tself.output_nc = output_nc\r\n\t\tself.ngf = ngf\r\n\t\tself.gpu_ids = gpu_ids\r\n\t\tself.use_parallel = use_parallel\r\n\t\tself.learn_residual = learn_residual\r\n\t\tif type(norm_layer) == functools.partial:\r\n\t\t\tuse_bias = norm_layer.func == nn.InstanceNorm2d\r\n\t\telse:\r\n\t\t\tuse_bias = norm_layer == nn.InstanceNorm2d\r\n\r\n\t\tself.coarse_SR_Encoder = define_coarse_SR_Encoder(norm_layer)\r\n\t\tself.fine_SR_Encoder = define_fine_SR_Encoder(norm_layer)\r\n\t\tself.prior_Estimation_Network = define_prior_Estimation_Network(norm_layer)\r\n\t\tself.fine_SR_Decoder = define_fine_SR_Decoder(norm_layer)\r\n\r\n\tdef forward(self, input, is_hr=False):\r\n\t\tif self.gpu_ids and isinstance(input.data, torch.cuda.FloatTensor) and self.use_parallel:\r\n\t\t\tif is_hr == True:\r\n\t\t\t\theatmaps = nn.parallel.data_parallel(self.prior_Estimation_Network, input, self.gpu_ids)\r\n\t\t\t\treturn heatmaps\r\n\t\t\telse:\r\n\t\t\t\tcoarse_HR = nn.parallel.data_parallel(self.coarse_SR_Encoder, input, self.gpu_ids)\r\n\t\t\t\tparsing = nn.parallel.data_parallel(self.fine_SR_Encoder, coarse_HR, self.gpu_ids)\r\n\t\t\t\theatmaps = nn.parallel.data_parallel(self.prior_Estimation_Network, coarse_HR, self.gpu_ids)\r\n\t\t\t\tconcatenation = torch.cat((parsing, heatmaps), 1)\r\n\t\t\t\toutput = nn.parallel.data_parallel(self.fine_SR_Decoder, concatenation, self.gpu_ids)\r\n\t\telse:\r\n\t\t\tif is_hr == True:\r\n\t\t\t\theatmaps = self.prior_Estimation_Network(input)\r\n\t\t\t\treturn heatmaps\r\n\t\t\telse:\r\n\t\t\t\tcoarse_HR = self.coarse_SR_Encoder(input)\r\n\t\t\t\tparsing = self.fine_SR_Encoder(coarse_HR)\r\n\t\t\t\theatmaps = self.prior_Estimation_Network(coarse_HR)\r\n\t\t\t\tconcatenation = torch.cat((parsing, heatmaps), 1)\r\n\t\t\t\toutput = self.fine_SR_Decoder(concatenation)\r\n\r\n\t\tif self.learn_residual:\r\n\t\t\toutput = input + output\r\n\t\t\toutput = torch.clamp(output, min = -1, max = 1)\r\n\t\treturn coarse_HR, heatmaps, output\r\n\r\nclass NLayerDiscriminator(nn.Module):\r\n\tdef __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d, use_sigmoid=False, gpu_ids=[], use_parallel = True):\r\n\t\tsuper(NLayerDiscriminator, self).__init__()\r\n\t\tself.gpu_ids = gpu_ids\r\n\t\tself.use_parallel = use_parallel\r\n\t\tif type(norm_layer) == functools.partial:\r\n\t\t\tuse_bias = norm_layer.func == nn.InstanceNorm2d\r\n\t\telse:\r\n\t\t\tuse_bias = norm_layer == nn.InstanceNorm2d\r\n\r\n\t\tkw = 4\r\n\t\tpadw = int(np.ceil((kw-1)/2))\r\n\t\tsequence = [\r\n\t\t\tnn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw),\r\n\t\t\tnn.LeakyReLU(0.2, True)\r\n\t\t]\r\n\r\n\t\tnf_mult = 1\r\n\t\tnf_mult_prev = 1\r\n\t\tfor n in range(1, n_layers):\r\n\t\t\tnf_mult_prev = nf_mult\r\n\t\t\tnf_mult = min(2**n, 8)\r\n\t\t\tsequence += [\r\n\t\t\t\tnn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult,\r\n\t\t\t\t\t\t kernel_size=kw, stride=2, padding=padw, bias=use_bias),\r\n\t\t\t\tnorm_layer(ndf * nf_mult),\r\n\t\t\t\tnn.LeakyReLU(0.2, True)\r\n\t\t\t]\r\n\r\n\t\tnf_mult_prev = nf_mult\r\n\t\tnf_mult = min(2**n_layers, 8)\r\n\t\tsequence += [\r\n\t\t\tnn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult,\r\n\t\t\t\t\t kernel_size=kw, stride=1, padding=padw, bias=use_bias),\r\n\t\t\tnorm_layer(ndf * nf_mult),\r\n\t\t\tnn.LeakyReLU(0.2, True)\r\n\t\t]\r\n\r\n\t\tsequence += [nn.Conv2d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw)]\r\n\r\n\t\tif use_sigmoid:\r\n\t\t\tsequence += [nn.Sigmoid()]\r\n\r\n\t\tself.model = nn.Sequential(*sequence)\r\n\r\n\tdef forward(self, input):\r\n\t\tif len(self.gpu_ids) and isinstance(input.data, torch.cuda.FloatTensor) and self.use_parallel:\r\n\t\t\treturn nn.parallel.data_parallel(self.model, input, self.gpu_ids)\r\n\t\telse:\r\n\t\t\treturn self.model(input)\r\n\r\n##############################################################################\r\n# Basic Structure Unit\r\n##############################################################################\r\n\r\n#Define a hourglass block\r\nclass HourGlassBlock(nn.Module):\r\n\tdef __init__(self, dim, n, norm_layer):\r\n\t\tsuper(HourGlassBlock, self).__init__()\r\n\t\tself._dim = dim\r\n\t\tself._n = n\r\n\t\tself._norm_layer = norm_layer\r\n\t\tself._init_layers(self._dim, self._n, self._norm_layer)\r\n\r\n\tdef _init_layers(self, dim, n, norm_layer):\r\n\t\tsetattr(self, 'res'+str(n)+'_1', Residual(dim, dim))\r\n\t\tsetattr(self, 'pool'+str(n)+'_1', nn.MaxPool2d(2,2))\r\n\t\tsetattr(self, 'res'+str(n)+'_2', Residual(dim, dim))\r\n\t\tif n > 1:\r\n\t\t\tself._init_layers(dim, n-1, norm_layer)\r\n\t\telse:\r\n\t\t\tself.res_center = Residual(dim, dim)\r\n\t\tsetattr(self,'res'+str(n)+'_3', Residual(dim, dim))\r\n\t\tsetattr(self,'unsample'+str(n), nn.Upsample(scale_factor=2))\r\n\r\n\tdef _forward(self, x, dim, n):\r\n\t\tup1 = x\r\n\t\tup1 = eval('self.res'+str(n)+'_1')(up1)\r\n\t\tlow1 = eval('self.pool'+str(n)+'_1')(x)\r\n\t\tlow1 = eval('self.res'+str(n)+'_2')(low1)\r\n\t\tif n > 1:\r\n\t\t\tlow2 = self._forward(low1, dim, n-1)\r\n\t\telse:\r\n\t\t\tlow2 = self.res_center(low1)\r\n\t\tlow3 = low2\r\n\t\tlow3 = eval('self.'+'res'+str(n)+'_3')(low3)\r\n\t\tup2 = eval('self.'+'unsample'+str(n)).forward(low3)\r\n\t\tout = up1 + up2\r\n\t\treturn out\r\n\r\n\tdef forward(self, x):\r\n\t\treturn self._forward(x, self._dim, self._n)\r\n\r\nclass Residual(nn.Module):\r\n def __init__(self, ins, outs):\r\n super(Residual, self).__init__()\r\n self.convBlock = nn.Sequential(\r\n nn.BatchNorm2d(ins),\r\n nn.ReLU(inplace=True),\r\n nn.Conv2d(ins,outs//2,1),\r\n nn.BatchNorm2d(outs//2),\r\n nn.ReLU(inplace=True),\r\n nn.Conv2d(outs//2,outs//2,3,1,1),\r\n nn.BatchNorm2d(outs//2),\r\n nn.ReLU(inplace=True),\r\n nn.Conv2d(outs//2,outs,1)\r\n )\r\n if ins != outs:\r\n self.skipConv = nn.Conv2d(ins,outs,1)\r\n self.ins = ins\r\n self.outs = outs\r\n def forward(self, x):\r\n residual = x\r\n x = self.convBlock(x)\r\n if self.ins != self.outs:\r\n residual = self.skipConv(residual)\r\n x += residual\r\n return x\r\n\r\n# Define a resnet block\r\nclass ResnetBlock(nn.Module):\r\n\tdef __init__(self, dim, padding_type, norm_layer, use_dropout, use_bias, updimension=False):\r\n\t\tsuper(ResnetBlock, self).__init__()\r\n\t\tself.conv_block = self.build_conv_block(dim, padding_type, norm_layer, use_dropout, use_bias, updimension)\r\n\r\n\tdef build_conv_block(self, dim, padding_type, norm_layer, use_dropout, use_bias, updimension):\r\n\t\tconv_block = []\r\n\t\tp = 0\r\n\t\tif padding_type == 'reflect':\r\n\t\t\tconv_block += [nn.ReflectionPad2d(1)]\r\n\t\telif padding_type == 'replicate':\r\n\t\t\tconv_block += [nn.ReplicationPad2d(1)]\r\n\t\telif padding_type == 'zero':\r\n\t\t\tp = 1\r\n\t\telse:\r\n\t\t\traise NotImplementedError('padding [%s] is not implemented' % padding_type)\r\n\t\tin_chan = dim\r\n\t\tif updimension == True:\r\n\t\t\tout_chan = in_chan * 2\r\n\t\telse:\r\n\t\t\tout_chan = dim\r\n\t\tconv_block += [nn.Conv2d(in_chan, out_chan, kernel_size=3, padding=p, bias=use_bias),\r\n\t\t\t\t\t\tnorm_layer(dim),\r\n\t\t\t\t\t\tnn.ReLU(True)]\r\n\r\n\t\tif use_dropout:\r\n\t\t\tconv_block += [nn.Dropout(0.5)]\r\n\r\n\t\tp = 0\r\n\t\tif padding_type == 'reflect':\r\n\t\t\tconv_block += [nn.ReflectionPad2d(1)]\r\n\t\telif padding_type == 'replicate':\r\n\t\t\tconv_block += [nn.ReplicationPad2d(1)]\r\n\t\telif padding_type == 'zero':\r\n\t\t\tp = 1\r\n\t\telse:\r\n\t\t\traise NotImplementedError('padding [%s] is not implemented' % padding_type)\r\n\t\tconv_block += [nn.Conv2d(in_chan, out_chan, kernel_size=3, padding=p, bias=use_bias),\r\n\t\t\t\t\t norm_layer(dim)]\r\n\r\n\t\treturn nn.Sequential(*conv_block)\r\n\r\n\tdef forward(self, x):\r\n\t\tout = x + self.conv_block(x)\r\n\t\treturn out\r\n\r\n","sub_path":"model/FSRNet.py","file_name":"FSRNet.py","file_ext":"py","file_size_in_byte":12739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"167308362","text":"import fileinput\ndef leadGame(scores):\n scores.append({'S':0,'T':0})\n best = {'W':0,'L':0}\n for index,score in enumerate(scores):\n previous = scores[index-1]\n scores[index] = {'S':score['S']+previous['S'], 'T':score['T']+previous['T']}\n lead = scores[index]['S'] - scores[index]['T']\n if abs(lead) > best['L']:\n best = {'W': 1 if lead>0 else 2,'L':abs(lead)}\n return best\n\ndef parseStdIn():\n scores = [];\n for line in fileinput.input():\n if not(fileinput.isfirstline()):\n S,T = line.split()\n scores.append({'S':int(S),'T':int(T)})\n return scores\n\nbest = leadGame(parseStdIn())\nprint(repr(best['W']) + \" \" + repr(best['L']),end='')","sub_path":"leadgame/lead.game.py","file_name":"lead.game.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"121918101","text":"import unittest\nimport importlib, importlib.util\n\ndef dump(game):\n \"\"\"\n Prints a human-readable representation of the game\n \"\"\"\n lines = [\"dimensions: {}\".format(game[\"dimensions\"]),\n \"board: {}\".format(\"\\n \".join(map(str, game[\"board\"]))),\n \"mask: {}\".format(\"\\n \".join(map(str, game[\"mask\"]))),\n \"state: {}\".format(game[\"state\"]),\n ]\n print(\"\\n\".join(lines))\n\ndef board_maker(num_rows, num_cols, val):\n \"\"\"\n Return: a mono-value board with the proper dimensions\n \"\"\"\n return [[val for c in range(num_cols)] for r in range(num_rows)]\n\ndef new_game(num_rows, num_cols, bombs):\n \"\"\"\n Return: new game state dictionary, with the \"dimensions\", \"state\", \"board\" and\n \"mask\" fields initialized based on the num_rows, num_cols, \n bombs (list given in (row, col) pairs)\n \"\"\"\n\n dimensions = [num_rows, num_cols]\n board = board_maker(num_rows, num_cols, 0)\n for b in bombs:\n r,c = b\n board[r][c] = \".\"\n ds = [(dr, dc) for dr in (-1, 0, 1) for dc in (-1, 0, 1)]\n for c in range(num_cols):\n for r in range(num_rows):\n for dr, dc in ds:\n if board[r][c] != '.' and (r, c) != (r + dr, c + dc):\n board[r][c] += is_bomb(r + dr, c + dc, board)\n mask = board_maker(num_rows, num_cols, False)\n return {\"dimensions\": dimensions, \n \"board\" : board, \n \"mask\" : mask, \n \"state\": \"ongoing\"}\n\ndef within_board(r, c, game):\n \"\"\"\n Return: if (r, c) is within the board\n \"\"\"\n rows, cols = game[\"dimensions\"]\n return (0 <= r < rows and 0 <= c < cols and game[\"board\"][r][c] != '.')\n\ndef is_bomb(r, c, board):\n \"\"\"\n Return: if (r, c) is a bomb\n \"\"\"\n return (0 <= r < len(board) and 0<= c < len(board[0]) and board[r][c] == '.')\n\ndef reveal_squares(game, row, col):\n \"\"\"\n Recursively reveals squares until there are none left to show. \n\n Return: count of cells revealed\n \"\"\"\n deltas = [(dr, dc) for dr in (-1, 0, 1) for dc in (-1, 0, 1)]\n revealed = 0\n if not game[\"mask\"][row][col]:\n revealed += 1\n game[\"mask\"][row][col] = True\n if game[\"board\"][row][col] == 0:\n for dr,dc in deltas:\n r, c = row+dr, col+dc\n if within_board(r, c, game) and not is_bomb(r, c, game[\"board\"]):\n revealed += reveal_squares(game, r, c) #Recusive call to reveal neighbors\n return revealed\n\ndef winning_mask_maker(game):\n \"\"\"\n Return: winning mask for the given board\n \"\"\"\n rows, cols = game[\"dimensions\"]\n return [[game[\"board\"][r][c] != '.' for c in range(cols)] for r in range(rows)]\n\ndef won_game(game):\n \"\"\"\n Return: if game is in a winning state\n \"\"\"\n return (game[\"mask\"] == winning_mask_maker(game))\n\ndef dig(game, row, col):\n \"\"\"\n Recursively dig up (row, col) and neighboring squares.\n\n Return: an integer indicating how many new squares were revealed.\n \"\"\"\n count = 0\n if game[\"state\"] in (\"victory\", \"defeat\"):\n return count\n elif is_bomb(row, col, game[\"board\"]):\n game[\"mask\"][row][col] = True\n count += 1\n game[\"state\"] = \"defeat\"\n return count\n elif won_game(game):\n game[\"state\"] = \"victory\"\n return count\n elif game[\"board\"][row][col] != 0:\n game[\"mask\"][row][col] = True\n count += 1 \n if won_game(game):\n game[\"state\"] = \"victory\" \n else:\n game[\"state\"] = \"ongoing\"\n return count\n count = reveal_squares(game, row, col)\n game[\"state\"] = \"victory\" if won_game(game) else \"ongoing\"\n return count\n\ndef render(game, xray=False):\n \"\"\"Prepare a game for display.\n\n Return: 2D array (list of lists) of \"_\" (hidden squares), \".\" (bombs), \n \" \" (empty squares), or \"1\", \"2\", etc. (squares neighboring bombs).\n \"\"\"\n result = []\n rows, cols = game['dimensions']\n for r in range(rows):\n row = []\n for c in range(cols):\n if xray or game['mask'][r][c]:\n if game['board'][r][c] == 0:\n row.append(' ')\n else:\n row.append(str(game['board'][r][c]))\n else:\n row.append('_')\n result.append(row)\n return result\n\ndef render_ascii(game, xray=False):\n \"\"\"\n Return: render a game as ASCII repersentation\n \"\"\"\n array_result = render(game, xray)\n str_result = \"\"\n for r in array_result:\n for c in r:\n str_result += str(c)\n str_result += \"\\n\"\n return str_result[:-1]\n\nclass TestMinesImplementation(unittest.TestCase):\n \"\"\"\n This class defines testing methods for each of the behaviors described in\n the lab handout. In the methods below, mines_imp will be the module you\n are testing. For example, to call the \"dig\" function from the\n implementation being tested, you can use:\n\n mines_imp.dig(game, r, c)\n\n You are welcome to use your methods from above as a \"gold standard\" to\n compare against, or to manually construct test cases, or a mix of both.\n \"\"\"\n dim = (2, 4)\n bombs= [(0, 0), (1,0), (1,1)]\n\n def test_newgame_dimensions(self):\n \"\"\"\n Tests that the dimensions of the game are initialized correctly.\n \"\"\"\n result = mines_imp.new_game(self.dim[0], self.dim[1], self.bombs)\n expected = new_game(self.dim[0], self.dim[1], self.bombs)\n self.assertEqual(result[\"dimensions\"], expected[\"dimensions\"])\n\n def test_newgame_board(self):\n \"\"\"\n Tests that the board is initialized correctly.\n \"\"\"\n result = mines_imp.new_game(self.dim[0], self.dim[1], self.bombs)\n expected = new_game(self.dim[0], self.dim[1], self.bombs)\n self.assertEqual(result[\"board\"], expected[\"board\"])\n\n def test_newgame_mask(self):\n \"\"\"\n Tests that the mask is initialized correctly (so that, if used with a\n working implementation of the dig function, it would behave as expected\n in all cases.\n \"\"\"\n result = mines_imp.new_game(self.dim[0], self.dim[1], self.bombs)\n expected = new_game(self.dim[0], self.dim[1], self.bombs)\n self.assertEqual(result[\"mask\"], expected[\"mask\"])\n dig(result, 0, 0)\n dig(expected, 0, 0)\n self.assertEqual(result[\"mask\"], expected[\"mask\"])\n\n def test_newgame_state(self):\n \"\"\"\n Tests that the state of a new game is always \"ongoing\".\n \"\"\"\n result = mines_imp.new_game(self.dim[0], self.dim[1], self.bombs)\n self.assertEqual(result[\"state\"], \"ongoing\")\n\n def test_dig_mask(self):\n \"\"\"\n Tests that, in situations that should modify the game, dig affects the\n mask, and not the board. (NOTE that this should not test for the\n correctness of dig overall, just that it modifies mask and does not\n modify board.)\n \"\"\"\n result = new_game(self.dim[0], self.dim[1], self.bombs)\n expected = new_game(self.dim[0], self.dim[1], self.bombs)\n mines_imp.dig(result, 1, 3)\n dig(expected, 1, 3)\n #self.assertNotEqual(result[\"mask\"], expected[\"mask\"])\n #self.assertEqual(result[\"board\"], expected[\"board\"])\n self.assertEqual(render(result), render(expected))\n\n def test_dig_reveal(self):\n \"\"\"\n Tests that dig reveals the square that was dug.\n \"\"\"\n result = new_game(self.dim[0], self.dim[1], self.bombs)\n self.assertNotEqual(result[\"mask\"][1][3], True)\n mines_imp.dig(result, 1, 3)\n self.assertEqual(result[\"mask\"][1][3], True)\n\n def test_dig_neighbors(self):\n \"\"\"\n Tests that dig properly reveals other squares when appropriate (if a 0\n is revealed during digging, all of its neighbors should automatically\n be revealed as well).\n \"\"\"\n result = new_game(self.dim[0], self.dim[1], self.bombs)\n expected = new_game(self.dim[0], self.dim[1], self.bombs)\n mines_imp.dig(result, 1, 2)\n dig(expected, 1, 2)\n# self.assertEqual(dug_1, dug_2)\n self.assertEqual(result[\"mask\"], expected[\"mask\"])\n\n def test_completed_dig_nop(self):\n \"\"\"\n Tests that dig does nothing when performed on a game that is not\n ongoing.\n \"\"\"\n result = new_game(self.dim[0], self.dim[1], self.bombs)\n expected = new_game(self.dim[0], self.dim[1], self.bombs)\n dig(result, 0, 0)\n dig(expected, 0, 0)\n self.assertEqual(result, expected)\n mines_imp.dig(result, 1, 3)\n dig(expected, 1, 3)\n self.assertEqual(result, expected)\n\n def test_multiple_dig_nop(self):\n \"\"\"\n Tests that dig does nothing when performed on a square that has already\n been dug.\n \"\"\"\n result = mines_imp.new_game(self.dim[0], self.dim[1], self.bombs)\n dig(result, 0, 0)\n expected = mines_imp.new_game(self.dim[0], self.dim[1], self.bombs)\n dig(expected, 0, 0)\n dig(expected, 0, 0)\n self.assertEqual(result, expected)\n\n def test_dig_count(self):\n \"\"\"\n Tests that dig returns the number of squares that were revealed (NOTE\n this that should always report the number that were revealed, even if\n that is different from the number that should have been revealed).\n \"\"\"\n result = new_game(self.dim[0], self.dim[1], self.bombs)\n dig(result, 1, 2)\n mask_before = [row[:] for row in result[\"mask\"]]\n count = mines_imp.dig(result, 1, 3)\n count_changed = 0\n for i in range(len(mask_before)):\n for b, a in zip(mask_before[i], result[\"mask\"][i]):\n if a != b:\n count_changed += 1\n self.assertEqual(count, count_changed)\n\n def test_defeat_state(self):\n \"\"\"\n Tests that the game state switches to \"defeat\" when a mine is dug, and\n not in other situations.\n \"\"\"\n result_1 = new_game(self.dim[0], self.dim[1], self.bombs)\n mines_imp.dig(result_1, 0, 0)\n self.assertEqual(result_1[\"state\"], \"defeat\")\n\n def test_victory_state(self):\n \"\"\"\n Tests that the game state switches to \"victory\" when there are no more\n safe squares to dig, and not in other situations.\n \"\"\"\n local_dim = [2, 2]\n local_bombs = [(0, 1), (1, 0)]\n result = new_game(local_dim[0], local_dim[1], local_bombs)\n mines_imp.dig(result, 0, 0)\n self.assertNotEqual(result[\"state\"], \"victory\")\n mines_imp.dig(result, 1, 1)\n self.assertEqual(result[\"state\"], \"victory\")\n\nclass TestResult6009(unittest.TestResult):\n \"\"\" \n Extension of 6.009 unit test class\n \"\"\"\n def __init__(self, *args, **kwargs):\n \"\"\" \n Keep track of test successes, in addition to failures and errors \n \"\"\"\n self.successes = []\n super().__init__(*args, **kwargs)\n\n def addSuccess(self, test):\n \"\"\" \n If a test succeeds, add it to successes \n \"\"\"\n self.successes.append((test,))\n\n def results_dict(self):\n \"\"\" \n Report out names of tests that succeeded as 'correct', and those that\n either failed (e.g., a self.assert failure) or had an error (e.g., an uncaught\n exception during the test) as 'incorrect'.\n \"\"\"\n return {'correct': [test[0]._testMethodName for test in self.successes],\n 'incorrect': [test[0]._testMethodName for test in self.errors + self.failures]}\n\ndef run_implementation_tests(imp):\n \"\"\"\n Test whether an implementation of the mines game correctly implements\n all the desired behaviors.\n\n Return: a dictionary with two keys: 'correct' and 'incorrect'. \n 'correct' - list of the behaviors that were implemented correctly\n 'incorrect' - list of the behaviors that were implemented incorrectly\n \"\"\"\n global mines_imp\n spec = importlib.util.spec_from_file_location(imp, \"resources/%s.py\" % imp)\n mines_imp = importlib.util.module_from_spec(spec)\n spec.loader.exec_module(mines_imp)\n suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestMinesImplementation)\n res = unittest.TextTestRunner(resultclass=TestResult6009,verbosity=1).run(suite).results_dict()\n return {'correct': [tag[5:] for tag in res['correct']],\n 'incorrect': [tag[5:] for tag in res['incorrect']]}\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()","sub_path":"lab3/lab.py","file_name":"lab.py","file_ext":"py","file_size_in_byte":12574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"631521762","text":"\"\"\"\r\nModule that provides various reshapers.\r\n\r\nEach reshaper class should provide a function called 'reshape' with the following signature:\r\n reshape(x)\r\nwhere x is a numpy ndarray (len(x.shape) should be equal to 1), and should return an ndarray\r\nthat contains the reshaped version of x.\r\n\"\"\"\r\nfrom abc import ABC, abstractmethod\r\nfrom typing import List\r\n\r\nimport numpy as np\r\n\r\nfrom dataset.template.commons import PureAbstractError\r\nfrom utilities.numpyutils import is_numpy_2d_vector\r\nfrom utilities.typingutils import is_typed_list\r\n\r\n\r\nclass BaseReshaper(ABC):\r\n \"\"\"\r\n Base class for reshapers.\r\n \"\"\"\r\n\r\n @abstractmethod\r\n def get_output_shape(self) -> List[int]:\r\n raise PureAbstractError()\r\n\r\n @abstractmethod\r\n def reshape(self, x: np.ndarray) -> np.ndarray:\r\n raise PureAbstractError()\r\n\r\n\r\nclass DefaultReshaper(BaseReshaper):\r\n \"\"\"\r\n A reshaper that ensures that 1D arrays are in fact 2D with the second dimension being equal to 1.\r\n \"\"\"\r\n\r\n def __init__(self, input_length: List[int] = None):\r\n assert is_typed_list(input_length, int) or input_length is None\r\n\r\n self._input_length: List[int] = input_length\r\n\r\n def get_output_shape(self) -> List[int]:\r\n return self._input_length + [1]\r\n\r\n def reshape(self, x: np.ndarray) -> np.ndarray:\r\n assert isinstance(x, np.ndarray)\r\n\r\n if len(x.shape) == 1:\r\n x = x.reshape(x.shape[0], 1)\r\n elif len(x.shape) == 2:\r\n assert x.shape[1] == 1\r\n else:\r\n raise ValueError(\"Incompatible shape for x\")\r\n\r\n return x\r\n\r\n\r\nclass BufferReshaper(BaseReshaper):\r\n \"\"\"\r\n A reshaper that reshapes a 1D window to an array of sub-windows (similar to MATLAB's buffer function).\r\n \"\"\"\r\n\r\n def __init__(self, input_length: int, wsize: int, wstep: int):\r\n \"\"\"\r\n Create a reshaper that buffers the input window.\r\n\r\n :param input_length: The size (length) of the input window.\r\n :param wsize: The size (length) of the sub-windows.\r\n :param wstep: The step for the sub-windows.\r\n \"\"\"\r\n assert isinstance(input_length, int)\r\n assert isinstance(wsize, int)\r\n assert isinstance(wstep, int)\r\n\r\n self._input_length = input_length\r\n self._wsize = wsize\r\n self._wstep = wstep\r\n\r\n self._start_idxs = np.arange(0, input_length - wsize + 1, wstep, dtype=int)\r\n self._noof_windows = len(self._start_idxs)\r\n\r\n def get_output_shape(self) -> List[int]:\r\n return [self._noof_windows, self._wsize]\r\n\r\n def reshape(self, x: np.ndarray) -> np.ndarray:\r\n assert is_numpy_2d_vector(x)\r\n\r\n y = np.empty((self._noof_windows, self._wsize, 1))\r\n for i, idx in enumerate(self._start_idxs):\r\n y[i, :] = x[idx:idx + self._wsize]\r\n\r\n return y\r\n","sub_path":"src/dataset/reshapers.py","file_name":"reshapers.py","file_ext":"py","file_size_in_byte":2856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"97804527","text":"from glob import glob\n\nimport numpy as np\nimport pandas as pd\n\n\ndef extract_params_from_agent_csv(file_path: str) -> np.ndarray:\n parameter_function = lambda data_frame: data_frame[\"EvacTime[s]\"].max()\n agent_data_frame = pd.read_csv(file_path, decimal=\",\")\n value_vector = parameter_function(agent_data_frame)\n return value_vector\n\n\nfor simulation_dir in sorted(glob(\"tested_output_data/test*\")):\n single_simulation_results = [extract_params_from_agent_csv(f\"{single_simulation_dir}/Stat#Lev0_agentSummary.csv\")\n for single_simulation_dir in glob(f\"{simulation_dir}/Simulation*\")]\n print(np.mean(single_simulation_results))\n","sub_path":"src/models/9_3_odczyt_danych_z_csv.py","file_name":"9_3_odczyt_danych_z_csv.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"333379693","text":"\ndef bingap(x):\n\tnum1 = '0'\n\n\ty = bin(x)\n\ty1 = y[2:len(y)]\n\td = '-1'\n\tk = 0\n\trez = 0\n\tfor i in y1:\n\t\td = i\n\t\tif i == d and i == num1:\n\t\t\tk +=1\n\t\telse:\n\t\t\tif k > rez:\n\t\t\t\trez = k\n\t\t\tk = 0\n\treturn rez\n\ndef solution(A):\n # write your code in Python 3.6\n size = len(A)\n if size == 1:\n return A[0]\n A.sort()\n print(A)\n d = A[0]\n k = 0\n for i in range(1,size):\n if A[i] == d:\n k+=1\n else:\n if k == 0 or k%2 == 1:\n return A[i-1]\n d = A[i]\n k = 0\n\n return A[size-1]\n\n\n\n# o = 32\n# print(bin(o))\n\n# o1 = bingap(o)\n# print(o1)\n# print(s%2)\ns = [1,2,3]\n\n\nprint(sum(s))\n\n","sub_path":"Snake_with_A_star/bingap.py","file_name":"bingap.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"146412392","text":"from domain.providers.billpay.PreauthorizeRequest import CompanyDetails, PreauthorizeRequest, CustomerDetails, Total, Article\nfrom domain.providers.billpay.CaptureRequest import CaptureRequest\nfrom domain.providers.billpay.BillpayClient import BillpayClient\nfrom domain.providers.billpay.InvoiceCreatedRequest import InvoiceCreatedRequest\nfrom domain.providers.billpay.CancelRequest import CancelRequest\nimport os\nimport sys\nimport time\n\nmanager = BillpayClient(\n mid=os.environ['BILLPAY_MERCHANT_ID'],\n pid=os.environ['BILLPAY_BUSINESS_PORTAL_ID'],\n password_hash=os.environ['BILLPAY_BUSINESS_PASSWORD_HASH'],\n url=os.environ['BILLPAY_API_URL'],\n)\ncustomer_reference = str(int(time.time())) + \"TEST\"\nprint(\"Reference used: {}\".format(customer_reference))\n\nobj = PreauthorizeRequest()\nobj.type_capture = PreauthorizeRequest.CAPTURE_MANUAL\n\ncustomer_details = CustomerDetails()\ncustomer_details.customer_id = 123456\ncustomer_details.customer_type = CustomerDetails.EXISTING_CUSTOMER\ncustomer_details.salutation = \"Herr\"\ncustomer_details.first_name = \"Thomas\"\ncustomer_details.last_name = \"Testkunde\"\ncustomer_details.street = \"Teststr.\"\ncustomer_details.street_no = \"11\"\ncustomer_details.zip = \"10115\"\ncustomer_details.city = \"Berlin\"\ncustomer_details.country = \"DEU\"\ncustomer_details.email = \"anyone@anymail.de\"\ncustomer_details.phone = \"0302333453\"\ncustomer_details.cell_phone = \"01775112383\"\ncustomer_details.birthday = \"19740419\"\ncustomer_details.language = \"de\"\ncustomer_details.ip = \"85.214.7.10\"\ncustomer_details.customer_group = CustomerDetails.GROUP_BUSINESS\nobj.customer_details = customer_details\n\ncompany_details = CompanyDetails()\ncompany_details.name = \"Testfirma\"\ncompany_details.legal_form = \"Gmbh\"\ncompany_details.register_number = \"HRB 122 029 B\"\ncompany_details.holder_name = \"Testinhaber\"\ncompany_details.tax_number = \"DE268874183\"\nobj.company_details = company_details\n\ntotal = Total()\ntotal.shipping_name = \"Express-Versand\"\ntotal.shipping_price_net = 500\ntotal.shipping_price_gross = 650\ntotal.rebate_net = 0\ntotal.rebate_gross = 0\ntotal.order_amount_net = 1250\ntotal.order_amount_gross = 1475\ntotal.currency = \"EUR\"\ntotal.reference = customer_reference\nobj.total = total\n\narticle = Article()\narticle.article_id = \"1234\"\narticle.article_name = \"test1\"\narticle.article_type = \"0\"\narticle.article_quantity = \"1\"\narticle.article_price_net = \"250\"\narticle.article_price_gross = \"275\"\nobj.add_article(article)\n\narticle2 = Article()\narticle2.article_id = \"2345\"\narticle2.article_name = \"test2\"\narticle2.article_type = \"0\"\narticle2.article_quantity = \"2\"\narticle2.article_price_net = \"250\"\narticle2.article_price_gross = \"275\"\nobj.add_article(article2)\n\nresponse = manager.preauthorise(obj)\nprint(\"\\nThe response:\\n{}\".format(response))\n\nif response.is_successful() is not True:\n print(\"Ending the test\")\n sys.exit()\n\nobj = CaptureRequest(response.transaction_id, 1475, \"EUR\", customer_reference)\n\nresponse = manager.capture(obj)\nprint(\"\\nThe response:\\n{}\".format(response))\n\nif response.is_successful() is not True:\n print(\"Ending the test\")\n sys.exit()\n\nobj = InvoiceCreatedRequest(1475, \"EUR\", customer_reference, 1)\nobj.invoice_amount_net = 1250\nobj.invoice_amount_gross = 1475\nobj.shipping_name = \"Express-Versand\"\nobj.shipping_price_net = 500\nobj.shipping_price_gross = 650\n\nresponse = manager.create_invoice(obj)\nprint(\"\\nThe response:\\n{}\".format(response))\n\nif response.is_successful() is not True:\n print(\"Ending the test\")\n sys.exit()\n\nobj = CancelRequest(customer_reference, 1475, \"EUR\")\nresponse = manager.cancel(obj)\nprint(\"\\nThe response:\\n{}\".format(response))","sub_path":"functional-test-b2b.py","file_name":"functional-test-b2b.py","file_ext":"py","file_size_in_byte":3622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"151337350","text":"import weakref\nimport os\nimport glob\nimport abc\nimport numpy as np\nimport pathlib\n\nfrom psana.dgrammanager import DgramManager\n\nfrom psana.psexp import PrometheusManager, SmdReaderManager\nfrom psana.psexp.tools import Logging as logging\nimport threading\nfrom psana import dgram\n\nfrom psana.detector import detectors\nimport psana.pscalib.calib.MDBWebUtils as wu\n\nclass InvalidDataSourceArgument(Exception): pass\n\nclass DsParms(object):\n def __init__(self, batch_size=1, max_events=0, filter=0, destination=0, prom_man=None, max_retries=0):\n self.batch_size = batch_size\n self.max_events = max_events\n self.filter = filter\n self.destination = destination \n self.prom_man = prom_man\n self.calibconst = {}\n self.max_retries = max_retries\n\n def set_det_class_table(self, det_classes, xtc_info, det_info_table):\n self.det_classes, self.xtc_info, self.det_info_table = det_classes, xtc_info, det_info_table\n\nclass DataSourceBase(abc.ABC):\n filter = 0 # callback that takes an evt and return True/False.\n batch_size = 1 # length of batched offsets\n max_events = 0 # no. of maximum events\n detectors = [] # user-selected detector names\n exp = None # experiment id (e.g. xpptut13)\n runnum = None # run no. \n live = False # turns live mode on/off \n dir = None # manual entry for path to xtc files\n files = None # xtc2 file path\n shmem = None\n destination = 0 # callback that returns rank no. (used by EventBuilder)\n monitor = False # turns prometheus monitoring client of/off\n\n def __init__(self, **kwargs):\n \"\"\"Initializes datasource base\"\"\"\n if kwargs is not None:\n self.smalldata_kwargs = {}\n keywords = ('exp', \n 'dir', \n 'files', \n 'shmem', \n 'filter', \n 'batch_size', \n 'max_events', \n 'detectors', \n 'det_name',\n 'destination',\n 'live',\n 'smalldata_kwargs', \n 'monitor')\n \n for k in keywords:\n if k in kwargs:\n setattr(self, k, kwargs[k])\n\n if self.destination != 0:\n self.batch_size = 1 # reset batch_size to prevent L1 transmitted before BeginRun (FIXME?: Mona)\n\n if 'run' in kwargs:\n setattr(self, 'runnum', kwargs['run'])\n\n if 'files' in kwargs:\n if isinstance(self.files, str):\n self.files = [self.files]\n\n max_retries = 0\n if self.live: max_retries = 3 \n\n assert self.batch_size > 0\n \n self.prom_man = PrometheusManager(os.environ['PS_PROMETHEUS_JOBID'])\n self.dsparms = DsParms(self.batch_size, self.max_events, self.filter, self.destination, self.prom_man, max_retries) \n\n @abc.abstractmethod\n def runs(self):\n return\n\n # to be added at a later date...\n #@abc.abstractmethod\n #def steps(self):\n # retur\n \n def _setup_run_files(self, runnum):\n smd_dir = os.path.join(self.xtc_path, 'smalldata')\n smd_files = glob.glob(os.path.join(smd_dir, '*r%s-s*.smd.xtc2'%(str(runnum).zfill(4))))\n \n xtc_files = [os.path.join(self.xtc_path, \\\n os.path.basename(smd_file).split('.smd')[0] + '.xtc2') \\\n for smd_file in smd_files \\\n if os.path.isfile(os.path.join(self.xtc_path, \\\n os.path.basename(smd_file).split('.smd')[0] + '.xtc2'))]\n self.smd_files = smd_files\n self.xtc_files = xtc_files\n\n def _setup_runnum_list(self):\n \"\"\"\n Requires:\n 1) exp\n 2) exp, run=N or [N, M, ...]\n \n Build runnum_list for the experiment.\n \"\"\"\n\n if not self.exp:\n raise InvalidDataSourceArgument(\"Missing exp or files input\")\n \n if self.dir:\n self.xtc_path = self.dir\n else:\n xtc_dir = os.environ.get('SIT_PSDM_DATA', '/reg/d/psdm')\n self.xtc_path = os.path.join(xtc_dir, self.exp[:3], self.exp, 'xtc')\n \n if self.runnum is None:\n run_list = [int(os.path.splitext(os.path.basename(_dummy))[0].split('-r')[1].split('-')[0]) \\\n for _dummy in glob.glob(os.path.join(self.xtc_path, '*-r*.xtc2'))]\n assert run_list\n run_list = list(set(run_list))\n run_list.sort()\n self.runnum_list = run_list\n elif isinstance(self.runnum, list):\n self.runnum_list = self.runnum\n elif isinstance(self.runnum, int):\n self.runnum_list = [self.runnum]\n else:\n raise InvalidDataSourceArgument(\"run accepts only int or list. Leave out run arugment to process all available runs.\")\n\n def smalldata(self, **kwargs):\n self.smalldata_obj.setup_parms(**kwargs)\n return self.smalldata_obj\n\n def _start_prometheus_client(self, mpi_rank=0):\n if not self.monitor:\n logging.info('ds_base: RUN W/O PROMETHEUS CLENT')\n else:\n logging.info('ds_base: START PROMETHEUS CLIENT (JOBID:%s RANK: %d)'%(self.prom_man.jobid, mpi_rank))\n self.e = threading.Event()\n self.t = threading.Thread(name='PrometheusThread%s'%(mpi_rank),\n target=self.prom_man.push_metrics,\n args=(self.e, mpi_rank),\n daemon=True)\n self.t.start()\n\n def _end_prometheus_client(self, mpi_rank=0):\n if not self.monitor:\n return\n\n logging.info('ds_base: END PROMETHEUS CLIENT (JOBID:%s RANK: %d)'%(self.prom_man.jobid, mpi_rank))\n self.e.set()\n\n def _apply_detector_selection(self):\n if self.detectors:\n s1 = set(self.detectors)\n xtc_files = []\n smd_files = []\n smd_fds = []\n configs = []\n for i, config in enumerate(self._configs):\n if s1.intersection(set(config.__dict__.keys())):\n if self.xtc_files: xtc_files.append(self.xtc_files[i])\n if self.smd_files: \n smd_files.append(self.smd_files[i])\n smd_fds.append(self.smd_fds[i])\n configs.append(config)\n print(f\"self.xtc_files={self.xtc_files}\")\n print(f\"xtc_files={xtc_files}\")\n print(f\"self.smd_files={self.smd_files}\")\n print(f\"smd_files={smd_files}\")\n if not (self.smd_files==smd_files and self.xtc_files==xtc_files):\n print(\"update all files\")\n self.xtc_files = xtc_files\n self.smd_files = smd_files\n self.smd_fds = np.array(smd_fds, dtype=np.int32)\n self.smdr_man = SmdReaderManager(self.smd_fds, self.dsparms, configs=configs)\n self._configs = configs \n\n \n def _setup_det_class_table(self):\n \"\"\"\n this function gets the version number for a (det, drp_class) combo\n maps (dettype,software,version) to associated python class and\n detector info for a det_name maps to dettype, detid tuple.\n \"\"\"\n det_classes = {'epics': {}, 'scan': {}, 'normal': {}}\n\n xtc_info = []\n det_info_table = {}\n\n # loop over the dgrams in the configuration\n # if a detector/drp_class combo exists in two cfg dgrams\n # it will be OK... they should give the same final Detector class\n\n for cfg_dgram in self._configs:\n for det_name, det_dict in cfg_dgram.software.__dict__.items():\n # go find the class of the first segment in the dict\n # they should all be identical\n first_key = next(iter(det_dict.keys()))\n det = det_dict[first_key]\n\n if det_name not in det_classes:\n det_class_table = det_classes['normal']\n else:\n det_class_table = det_classes[det_name]\n\n\n dettype, detid = (None, None)\n for drp_class_name, drp_class in det.__dict__.items():\n\n # collect detname maps to dettype and detid\n if drp_class_name == 'dettype':\n dettype = drp_class\n continue\n\n if drp_class_name == 'detid':\n detid = drp_class\n continue\n\n # FIXME: we want to skip '_'-prefixed drp_classes\n # but this needs to be fixed upstream\n if drp_class_name.startswith('_'): continue\n\n # use this info to look up the desired Detector class\n versionstring = [str(v) for v in drp_class.version]\n class_name = '_'.join([det.dettype, drp_class.software] + versionstring)\n xtc_entry = (det_name,det.dettype,drp_class_name,'_'.join(versionstring))\n if xtc_entry not in xtc_info:\n xtc_info.append(xtc_entry)\n if hasattr(detectors, class_name):\n DetectorClass = getattr(detectors, class_name) # return the class object\n det_class_table[(det_name, drp_class_name)] = DetectorClass\n else:\n pass\n\n det_info_table[det_name] = (dettype, detid)\n\n self.dsparms.set_det_class_table(det_classes, xtc_info, det_info_table)\n\n def _set_configinfo(self):\n \"\"\" From configs, we generate a dictionary lookup with det_name as a key.\n The information stored the value field contains:\n \n - configs specific to that detector\n - sorted_segment_ids\n used by Detector cls for checking if an event has correct no. of segments\n - detid_dict\n has segment_id as a key\n - dettype\n - uniqueid\n \"\"\"\n self.dsparms.configinfo_dict = {}\n\n for _, det_class in self.dsparms.det_classes.items(): # det_class is either normal or envstore\n for (det_name, _), _ in det_class.items():\n # Create a copy of list of configs for this detector\n det_configs = [dgram.Dgram(view=config) for config in self._configs \\\n if hasattr(config.software, det_name)]\n sorted_segment_ids = []\n # a dictionary of the ids (a.k.a. serial-number) of each segment\n detid_dict = {}\n dettype = \"\"\n uniqueid = \"\"\n for config in det_configs:\n seg_dict = getattr(config.software, det_name)\n sorted_segment_ids += list(seg_dict.keys())\n for segment, det in seg_dict.items():\n detid_dict[segment] = det.detid\n dettype = det.dettype\n \n sorted_segment_ids.sort()\n \n uniqueid = dettype\n for segid in sorted_segment_ids:\n uniqueid += '_'+detid_dict[segid]\n\n self.dsparms.configinfo_dict[det_name] = type(\"ConfigInfo\", (), {\\\n \"configs\": det_configs, \\\n \"sorted_segment_ids\": sorted_segment_ids, \\\n \"detid_dict\": detid_dict, \\\n \"dettype\": dettype, \\\n \"uniqueid\": uniqueid})\n \n def _setup_run_calibconst(self):\n \"\"\"\n note: calibconst is set differently in RunParallel (see node.py: BigDataNode)\n \"\"\"\n runinfo = self._get_runinfo()\n if not runinfo:\n return\n expt, runnum, _ = runinfo\n \n self.dsparms.calibconst = {}\n for det_name, configinfo in self.dsparms.configinfo_dict.items():\n if expt: \n if expt == \"cxid9114\": # mona: hack for cctbx\n det_uniqueid = \"cspad_0002\"\n elif expt == \"xpptut15\":\n det_uniqueid = \"cspad_detnum1234\"\n else:\n det_uniqueid = configinfo.uniqueid\n calib_const = wu.calib_constants_all_types(det_uniqueid, exp=expt, run=runnum)\n \n # mona - hopefully this will be removed once the calibconst\n # db all use uniqueid as an identifier\n if not calib_const:\n calib_const = wu.calib_constants_all_types(det_name, exp=expt, run=runnum)\n self.dsparms.calibconst[det_name] = calib_const\n else:\n print(f\"ds_base: Warning: cannot access calibration constant (exp is None)\")\n self.dsparms.calibconst[det_name] = None\n \n def _get_runinfo(self):\n if not self.beginruns : return\n\n beginrun_dgram = self.beginruns[0]\n if hasattr(beginrun_dgram, 'runinfo'): # some xtc2 do not have BeginRun\n expt = beginrun_dgram.runinfo[0].runinfo.expt \n runnum = beginrun_dgram.runinfo[0].runinfo.runnum\n timestamp = beginrun_dgram.timestamp()\n return expt, runnum, timestamp\n\n def _close_opened_smd_files(self):\n # Make sure to close all smd files opened by previous run\n if self.smd_fds is not None:\n txt = \"ds_base: \"\n for fd in self.smd_fds:\n os.close(fd)\n txt += f' close smd fd:{fd}'\n logging.info(txt)\n\n\n","sub_path":"psana/psana/psexp/ds_base.py","file_name":"ds_base.py","file_ext":"py","file_size_in_byte":13757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"383673787","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 4 19:52:17 2022\n\n@author: Codey Sivley\nFor Software Engineering Midterm\nDr Maxwell Fall 2022\n\"\"\"\n##################### read text into array\nnums = []\nnumbles = open(\"inputFile.txt\", 'r')\nfor each in numbles:\n nums.append(int(each))\n\nprint(\"The numbers are: \" + str(nums))\n\n##################### sum first 14 numbers\nnumSum = 0\nfor i in range(len(nums) - 1):\n numSum += nums[i]\n\nprint(\"The sum of the first \" + (str((len(nums)) - 1)) + \" is: \" + str(numSum))\nprint(\"The final number is \" + str(nums[-1]))\n##################### divide by last one\nresult = numSum / nums[-1]\n\n##################### print result\nprint(\"The result is: \" + str(result))","sub_path":"SoftwareEngineeringMidterm/ReadThenDivide.py","file_name":"ReadThenDivide.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"557170707","text":"import numpy as np\nimport os\nimport nibabel as nib\nimport pydicom\nimport h5py\nimport json\n\nfrom copy import deepcopy\nfrom warnings import warn\nfrom glob import glob\n\nimport tensorflow\nif tensorflow.__version__ >= '2':\n from tensorflow.keras.models import load_model\nelse:\n from keras.models import load_model\n\nfrom pymirc.image_operations import aff_transform\nfrom pymirc.viewer import ThreeAxisViewer\nfrom pymirc.fileio import DicomVolume, write_3d_static_dicom\n\nfrom .preprocessing import preprocess_volumes\n\nimport matplotlib as mpl\nif os.getenv('DISPLAY') is None: mpl.use('Agg')\nimport matplotlib.pyplot as py\n\n# imports for old predictors\nfrom time import time\nfrom .generators import PatchSequence\n\n#--------------------------------------------------------------------------------------\n\ndef predict(pet_input,\n mr_input,\n model_name,\n input_format = 'dicom',\n odir = None,\n model_dir = os.path.join('..','trained_models'),\n perc = 99.99,\n verbose = False,\n clip_neg = True,\n ReconstructionMethod = 'CNN Bowsher',\n coreg = True,\n seriesdesc = None,\n affine = None,\n crop_mr = False,\n patchsize = (128,128,128),\n overlap = 8,\n output_on_pet_grid = False,\n mr_ps_fwhm_mm = None,\n model_custom_objects = None,\n debug_mode = False):\n\n if seriesdesc is None:\n SeriesDescription = 'CNN Bowsher beta = 10 ' + model_name.replace('.h5','')\n else:\n SeriesDescription = seriesdesc\n \n if affine is None:\n if input_format == 'dicom':\n if isinstance(pet_input, list):\n regis_affine_file = os.path.dirname(pet_input[0]) + '_coreg_affine.txt'\n else:\n regis_affine_file = os.path.dirname(pet_input) + '_coreg_affine.txt'\n else:\n regis_affine_file = pet_input + '_coreg_affine.txt'\n\n else:\n regis_affine_file = affine\n\n # generate the output directory\n if odir is None:\n if input_format == 'dicom':\n if isinstance(pet_input, list):\n odir = os.path.join(os.path.dirname(os.path.dirname(pet_input[0])), \n 'cnn_bow_' + model_name.replace('.h5',''))\n else:\n odir = os.path.join(os.path.dirname(os.path.dirname(pet_input)), \n 'cnn_bow_' + model_name.replace('.h5',''))\n else:\n odir = os.path.join(os.path.dirname(pet_input), 'cnn_bow_' + model_name.replace('.h5',''))\n \n # check if output directory already exists, if so add a counter to prevent overwriting\n o_suf = 1\n if os.path.isdir(odir):\n while os.path.isdir(odir + '_' + str(o_suf)):\n o_suf += 1\n odir = odir + '_' + str(o_suf)\n \n # load the model\n model = load_model(os.path.join(model_dir,model_name), custom_objects = model_custom_objects)\n \n # read the input data\n if input_format == 'dicom':\n # read the MR dicoms\n if verbose: print('\\nreading MR dicoms')\n if isinstance(mr_input, list):\n mr_files = deepcopy(mr_input)\n else:\n mr_files = glob(mr_input)\n mr_dcm = DicomVolume(mr_files)\n mr_vol = mr_dcm.get_data()\n mr_affine = mr_dcm.affine\n \n # read the PET dicoms\n if verbose: print('\\nreading PET dicoms')\n if isinstance(pet_input, list):\n pet_files = deepcopy(pet_input)\n else:\n pet_files = glob(pet_input)\n pet_dcm = DicomVolume(pet_files)\n pet_vol = pet_dcm.get_data()\n pet_affine = pet_dcm.affine\n\n elif input_format == 'nifti':\n if verbose: print('\\nreading MR nifti')\n mr_nii = nib.load(mr_input)\n mr_nii = nib.as_closest_canonical(mr_nii)\n mr_vol_ras = mr_nii.get_data()\n mr_affine_ras = mr_nii.affine\n # the closest canonical orientation of nifti is RAS\n # we have to convert that into LPS (dicom standard)\n mr_vol = np.flip(np.flip(mr_vol_ras, 0), 1)\n mr_affine = mr_affine_ras.copy()\n mr_affine[0,-1] = (-1 * mr_nii.affine @ np.array([mr_vol.shape[0]-1,0,0,1]))[0]\n mr_affine[1,-1] = (-1 * mr_nii.affine @ np.array([0,mr_vol.shape[1]-1,0,1]))[1]\n\n if verbose: print('\\nreading PET nifti')\n pet_nii = nib.load(pet_input)\n pet_nii = nib.as_closest_canonical(pet_nii)\n pet_vol_ras = pet_nii.get_data()\n\n pet_affine_ras = pet_nii.affine\n # the closest canonical orientation of nifti is RAS\n # we have to convert that into LPS (dicom standard)\n pet_vol = np.flip(np.flip(pet_vol_ras, 0), 1)\n pet_affine = pet_affine_ras.copy()\n pet_affine[0,-1] = (-1 * pet_nii.affine @ np.array([pet_vol.shape[0]-1,0,0,1]))[0]\n pet_affine[1,-1] = (-1 * pet_nii.affine @ np.array([0,pet_vol.shape[1]-1,0,1]))[1]\n else:\n raise TypeError('Unsupported input data format')\n\n # read the internal voxel size that was used during training from the model header\n if os.path.isdir(os.path.join(model_dir,model_name)):\n with open(os.path.join(model_dir,model_name,'config.json')) as f:\n cfg = json.load(f)\n training_voxsize = cfg['internal_voxsize']*np.ones(3)\n else:\n model_data = h5py.File(os.path.join(model_dir,model_name))\n\n if 'header/internal_voxsize' in model_data:\n training_voxsize = model_data['header/internal_voxsize'][:] \n else:\n # in the old models the training (internal) voxel size is not in the header\n # but it was always 1x1x1 mm^3\n training_voxsize = np.ones(3)\n \n\n ################################################################\n ############ data preprocessing ################################\n ################################################################\n\n pet_vol_mr_grid_interpolated, mr_vol_interpolated, mr_affine, pet_max, mr_max = \\\n preprocess_volumes(pet_vol, mr_vol, pet_affine, mr_affine, training_voxsize,\n perc = perc, coreg = coreg, crop_mr = crop_mr, \n mr_ps_fwhm_mm = mr_ps_fwhm_mm, verbose = verbose)\n \n ################################################################\n ############# make the actual prediction #######################\n ################################################################\n \n if verbose: print('\\npredicting the bowsher')\n\n if patchsize is None:\n # case of predicting the whole volume in one big chunk\n # bring the input volumes in the correct shape for the model\n x = [np.expand_dims(np.expand_dims(pet_vol_mr_grid_interpolated,0),-1), np.expand_dims(np.expand_dims(mr_vol_interpolated,0),-1)]\n predicted_bow = model.predict(x).squeeze() \n else:\n # case of doing the prediction in multiple smaller 3D chunks (patches)\n predicted_bow = np.zeros(pet_vol_mr_grid_interpolated.shape, dtype = np.float32)\n\n for i in range(pet_vol_mr_grid_interpolated.shape[0]//patchsize[0] + 1):\n for j in range(pet_vol_mr_grid_interpolated.shape[1]//patchsize[1] + 1):\n for k in range(pet_vol_mr_grid_interpolated.shape[2]//patchsize[2] + 1):\n istart = max(i*patchsize[0] - overlap, 0)\n jstart = max(j*patchsize[1] - overlap, 0)\n kstart = max(k*patchsize[2] - overlap, 0)\n\n ioffset = i*patchsize[0] - istart\n joffset = j*patchsize[1] - jstart\n koffset = k*patchsize[2] - kstart\n\n iend = min(((i+1)*patchsize[0] + overlap), pet_vol_mr_grid_interpolated.shape[0])\n jend = min(((j+1)*patchsize[1] + overlap), pet_vol_mr_grid_interpolated.shape[1])\n kend = min(((k+1)*patchsize[2] + overlap), pet_vol_mr_grid_interpolated.shape[2])\n\n pet_patch = pet_vol_mr_grid_interpolated[istart:iend,jstart:jend,kstart:kend]\n mr_patch = mr_vol_interpolated[istart:iend,jstart:jend,kstart:kend]\n \n # make the prediction\n x = [np.expand_dims(np.expand_dims(pet_patch,0),-1), np.expand_dims(np.expand_dims(mr_patch,0),-1)]\n tmp = model.predict(x).squeeze() \n\n ntmp0 = min((i+1)*patchsize[0], pet_vol_mr_grid_interpolated.shape[0]) - i*patchsize[0]\n ntmp1 = min((j+1)*patchsize[1], pet_vol_mr_grid_interpolated.shape[1]) - j*patchsize[1]\n ntmp2 = min((k+1)*patchsize[2], pet_vol_mr_grid_interpolated.shape[2]) - k*patchsize[2]\n \n predicted_bow[i*patchsize[0]:(i*patchsize[0] + ntmp0),j*patchsize[1]:(j*patchsize[1] + ntmp1), k*patchsize[2]:(k*patchsize[2]+ntmp2)] = tmp[ioffset:(ioffset+ntmp0),joffset:(joffset+ntmp1),koffset:(koffset+ntmp2)]\n\n if clip_neg: np.clip(predicted_bow, 0, None, predicted_bow)\n \n # unnormalize the data\n if verbose: print('\\nunnormalizing the images')\n mr_vol_interpolated *= mr_max\n pet_vol_mr_grid_interpolated *= pet_max\n predicted_bow *= pet_max\n\n print('\\n\\n------------------------------------------')\n print('------------------------------------------')\n print('\\nCNN prediction finished')\n\n\n ##############################################################\n ########## write the output as nifti, png, dcm ###############\n ##############################################################\n\n # write output pngs\n pmax = np.percentile(pet_vol_mr_grid_interpolated, 99.99)\n mmax = np.percentile(mr_vol_interpolated, 99.99)\n imshow_kwargs = [{'cmap':py.cm.Greys_r, 'vmin':0, 'vmax':mmax},\n {'cmap':py.cm.Greys, 'vmin':0, 'vmax':pmax},\n {'cmap':py.cm.Greys, 'vmin':0, 'vmax':pmax}]\n\n vi = ThreeAxisViewer([mr_vol_interpolated, pet_vol_mr_grid_interpolated, predicted_bow], \n imshow_kwargs = imshow_kwargs, ls = '')\n vi.fig.savefig(odir + '.png')\n py.close(vi.fig)\n py.close(vi.fig_cb)\n py.close(vi.fig_sl)\n\n #---------------------------------------------------------------\n # generate the output affines\n if output_on_pet_grid:\n output_affine = pet_affine.copy()\n predicted_bow = aff_transform(predicted_bow, np.linalg.inv(pet_mr_interp_aff), \n pet_vol.shape, cval = pet_vol.min()) \n else:\n output_affine = mr_affine.copy()\n for i in range(3): output_affine[i,:-1] *= training_voxsize[i]/np.sqrt((output_affine[i,:-1]**2).sum())\n\n # create the output affine in RAS orientation to save niftis\n output_affine_ras = output_affine.copy()\n output_affine_ras[0,-1] = (-1 * output_affine @ np.array([predicted_bow.shape[0]-1,0,0,1]))[0]\n output_affine_ras[1,-1] = (-1 * output_affine @ np.array([0,predicted_bow.shape[1]-1,0,1]))[1]\n \n # safe the input volumes in case of debug mode \n if debug_mode: \n nib.save(nib.Nifti1Image(np.flip(np.flip(mr_vol_interpolated,0),1), output_affine_ras), odir + '_debug_mr.nii')\n nib.save(nib.Nifti1Image(np.flip(np.flip(pet_vol_mr_grid_interpolated,0),1), output_affine_ras), odir + '_debug_pet.nii')\n\n #------------------------------------------------------------\n # write a simple nifti as fall back in case the dicoms are not working\n # keep in mind that nifti used RAS internally\n nib.save(nib.Nifti1Image(np.flip(np.flip(predicted_bow,0),1), output_affine_ras), odir + '.nii')\n print('\\nWrote nifti:') \n print(odir + '.nii\\n')\n \n #------------------------------------------------------------\n # write the dicoms\n if input_format == 'dicom': \n # read the reference PET dicom file to copy some header tags\n refdcm = pydicom.read_file(pet_files[0])\n dcm_kwargs = {}\n # copy the following tags if present in the reference dicom \n pet_keys_to_copy = ['AcquisitionDate',\n 'AcquisitionTime',\n 'ActualFrameDuration',\n 'AccessionNumber',\n 'DecayCorrection',\n 'DecayCorrectionDateTime',\n 'DecayFactor',\n 'DoseCalibrationFactor',\n 'FrameOfReferenceUID',\n 'FrameReferenceTime',\n 'InstitutionName',\n 'ManufacturerModelName',\n 'OtherPatientIDs',\n 'PatientAge',\n 'PatientBirthDate',\n 'PatientID',\n 'PatientName',\n 'PatientPosition',\n 'PatientSex',\n 'PatientWeight',\n 'ProtocolName',\n 'RadiopharmaceuticalInformationSequence',\n 'RescaleType',\n 'SeriesDate',\n 'SeriesTime',\n 'StudyDate',\n 'StudyDescription',\n 'StudyID',\n 'StudyInstanceUID',\n 'StudyTime',\n 'Units']\n \n for key in pet_keys_to_copy:\n try:\n dcm_kwargs[key] = getattr(refdcm,key)\n except AttributeError:\n warn('Cannot copy tag ' + key)\n \n # write the dicom volume \n write_3d_static_dicom(predicted_bow, odir, affine = output_affine,\n ReconstructionMethod = ReconstructionMethod, SeriesDescription = SeriesDescription,\n **dcm_kwargs)\n print('\\nWrote dicom folder:')\n print(odir,'\\n')\n\n print('------------------------------------------')\n print('------------------------------------------')\n\n#--------------------------------------------------------------------------------------\n\ndef predict_single_case(model, input_fnames, verbose = False, **kwargs):\n \"\"\"\n predict a single case using an apetnet model\n\n inputs\n ------\n\n model ... a keras apetnet model \n\n inputfile_list ... (list) of input channels passed to PathSequence\n [input_channel_1, input_channel_2, ...]\n\n\n Keyword arguments\n -----------------\n\n verbose ... print verbose output \n\n **kwargs ... passed to PatchSequence\n \"\"\"\n\n ps = PatchSequence([input_fnames], **kwargs)\n \n x = [np.expand_dims(z,0) for z in ps.input_vols[0][:len(model.input_shape)]]\n\n t_start = time()\n prediction = model.predict(x).squeeze()\n t_stop = time()\n\n if verbose: print('\\ntime needed for prediction (s): ', t_stop - t_start, '\\n')\n\n # undo the normalization\n prediction *= ps.slopes[0][0]\n prediction += ps.intercepts[0][0]\n \n ps.unnormalize()\n\n return (ps, prediction)\n\n#--------------------------------------------------------------------------------------\n\ndef predict_eval_single_case(models, input_fnames, target_fname, verbose = False, **kwargs):\n \"\"\"\n predict a single case using an apetnet model\n\n inputs\n ------\n\n models ... a list of keras models\n\n inputfile_list ... (list) of input channels passed to PathSequence\n [input_channel_1, input_channel_2, ...]\n\n target_fname ... name of reference (target) file\n\n Keyword arguments\n -----------------\n\n verbose ... print verbose output \n\n **kwargs ... passed to PatchSequence\n \"\"\"\n\n ps = PatchSequence([input_fnames], [target_fname], **kwargs)\n \n x = [np.expand_dims(z,0) for z in ps.input_vols[0][:len(models[0].input_shape)]]\n\n predictions = []\n\n for model in models:\n t_start = time()\n prediction = model.predict(x).squeeze()\n t_stop = time()\n\n if verbose: print('\\ntime needed for prediction (s): ', t_stop - t_start, '\\n')\n\n # undo the normalization\n prediction *= ps.slopes[0][0]\n prediction += ps.intercepts[0][0]\n \n predictions.append(prediction)\n\n ps.unnormalize()\n\n return (ps, predictions)\n\n\n","sub_path":"pyapetnet/predictors.py","file_name":"predictors.py","file_ext":"py","file_size_in_byte":15603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"362880842","text":"#By construction of grid, we only have kz>0, but we can extrapolate the rest because of conjugate symmetry\r\nimport numpy as np\r\nimport math\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib\r\nfrom matplotlib import rcParams\r\nimport os\r\nos.environ['PATH'] = os.environ['PATH'] + ':/usr/texbin'\r\nrcParams['ps.fonttype'] = 42\r\nrcParams['ps.useafm']=True\r\nrcParams['pdf.use14corefonts']=True\r\nrcParams['text.usetex']=True\r\n\r\nmatplotlib.rcParams['legend.fontsize'] = 12.0\r\n\r\nn = 16\r\nn2 = int(n/2)\r\n\r\n#Get data\r\nfil_nam = 'grid'+str(n)+'.npy'\r\nK_grid = np.load(fil_nam)\r\n\r\n\r\n#Assign length values to grid points\r\nkmin = 0.01\r\nkmax = .2\r\nk_val = np.array(np.linspace(kmin,kmax,n2))\r\nk_val = np.concatenate((k_val,-k_val))\r\n\r\n#Trispectrum Bin parameters\r\nn_lenk = 5 #how many k bins do we want\r\nkbin = (3**.5*kmax*1.2-3**.5*kmin)/n_lenk #because kx,ky,kz!=0\r\nmubin = 0.2\r\nk_len = np.arange(3**.5*kmin,3**.5*kmax,kbin)\r\nmu_len = np.arange(-1,1,mubin)\r\n\r\n#Binning of k s and mu s such that we have a 2d array of vectors with the different observations\r\n\r\ndef bin_func(kx,ky,kz):\r\n len_k1 = (kx**2+ky**2+kz**2)**(.5)\r\n len_k1_bin = int((len_k1-kmin)/kbin)\r\n mu1_bin = int((kz/len_k1+1)/mubin)\r\n return len_k1_bin, mu1_bin\r\n\r\nkmu_P_mat = np.zeros((len(k_len),len(mu_len)),dtype = object) #matrix of observations of power of k,mu bin\r\nfor i in range(len(k_len)):\r\n for j in range(len(mu_len)):\r\n kmu_P_mat[i,j] = []\r\n\r\n\r\nfor i in range(n):\r\n for j in range(n):\r\n for k in range(n2):\r\n #kz>0\r\n kx1, ky1, kz1 = k_val[i], k_val[j], k_val[k]\r\n k_pos, mu_pos = bin_func(kx1, ky1, kz1)\r\n kmu_P_mat[k_pos,mu_pos].append(abs(K_grid[i,j,k])**2)\r\n \r\n #kz<0\r\n i1 = (i+n2)%n\r\n j1 = (j+n2)%n\r\n kx1, ky1, kz1 = k_val[i1], k_val[j1], -k_val[k]\r\n k_pos, mu_pos = bin_func(kx1, ky1, kz1)\r\n kmu_P_mat[k_pos,mu_pos].append(abs(K_grid[i1,j1,k])**2)\r\n\r\n\"\"\"\r\n#Check that every value is binned\r\nsum = 0\r\nfor i in range(5):\r\n for j in range(10):\r\n print(k_len[i],mu_len[j],len(kmu_P_mat[i,j]))\r\n sum += len(kmu_P_mat[i,j])\r\nprint(sum,n**3)\r\n\"\"\"\r\n \r\n#Save this matrix\r\nfil_name = 'kmubin'+str(n)+'.npy'\r\nnp.save(fil_name,kmu_P_mat)\r\nfil_name = 'kmubin'+str(n)+'var.npz'\r\nnp.savez(fil_name,k = k_len, mu = mu_len)\r\n\r\n\r\n","sub_path":"kmu_bin.py","file_name":"kmu_bin.py","file_ext":"py","file_size_in_byte":2413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"639885990","text":"import requests\nimport argparse\nfrom threading import *\ndef bucket_tracker(i):\n\t\n\tresult = requests.head(i)\n\tif result.status_code == 200:\n\t\tprint (\"%s is accessible\" % i)\n\t\nparser = argparse.ArgumentParser(description='Pass a domain to emumerate s3 buckets')\nparser.add_argument('-d', '--domain', help='Domain Name', required = True)\nargs = parser.parse_args()\ndomain = args.domain.strip(\".com\")\nwith open('permutation.txt', 'r') as f:\n a=[]\n for line in f:\n x = \"http://\" + line.strip() % (domain, 's3.amazonaws.com' )\n a.append(x)\n \n for i in a:\n \n t=Thread(target=bucket_tracker,args=(i,))\n t.daemon=True\n t.start()\n","sub_path":"s3.py","file_name":"s3.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"379234761","text":"from django.core.management.base import BaseCommand\nfrom django.conf import settings\nimport os\n# import glob\nfrom pathlib import Path\n\n# calm\nBASE_DIR = Path(__file__).resolve().parent.parent.parent.parent\n\n# genre_app = os.path.join(BASE_DIR / \"genres/migrations/\")\nauth_app = os.path.join(BASE_DIR / \"authentication/migrations/\")\n\napp_list = [\n # genre_app,\n auth_app\n]\n\n\nclass bcolors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKCYAN = '\\033[96m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\n\nclass Command(BaseCommand):\n help = \"Command information\"\n\n def handle(self, *args, **kwargs):\n # Greeting\n print(f\"{bcolors.BOLD}{bcolors.OKGREEN}\\nStarted cleaning...\\n{bcolors.ENDC}\")\n\n # Looping in apps\n for app in app_list:\n\n # Taking only files from directory (not folders)\n onlyfiles = [f for f in os.listdir(\n app) if os.path.isfile(os.path.join(app, f))]\n\n # If files more than one (__init.py__)\n if len(onlyfiles) > 1:\n print(\n f\"{bcolors.BOLD}{bcolors.WARNING}Deleting in - {bcolors.ENDC} {app} \\n\")\n # Looping all files\n for clenup in onlyfiles:\n # Do not delete __init__.py\n if not clenup.endswith(\"__init__.py\"):\n print(\n f\"{bcolors.FAIL}{bcolors.BOLD}Deleted - {clenup}{bcolors.ENDC}\")\n # Delete file\n os.remove(os.path.join(f\"{app}/{clenup}\"))\n # Delete db\n db = os.path.join(BASE_DIR / \"db.sqlite3\")\n if os.path.exists(db):\n os.remove(db)\n print(\n f\"{bcolors.WARNING}{bcolors.BOLD}\\nDeleted - Database{bcolors.ENDC}\")\n # Ended\n print(f\"{bcolors.BOLD}{bcolors.OKGREEN}\\nEnded cleaning...\\n{bcolors.ENDC}\")\n","sub_path":"authentication/management/commands/cleanup.py","file_name":"cleanup.py","file_ext":"py","file_size_in_byte":1994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"189058945","text":"\"\"\"\nThis file builds patient wise datasets i.e. all the images for a patient are under\na single idx i. This is suitable for our final training.\nFor UNet, we do not need patient wse training yet, as we are not performing volumetric\ntraining.\n\"\"\"\n\nimport os\nimport h5py\nimport math\nimport numpy as np\nfrom skimage import io\nfrom tqdm import tqdm\nimport argparse\nimport pandas as pd\nimport SimpleITK as sitk\nimport matplotlib.pyplot as plt\nfrom tempfile import TemporaryFile\n\n\nparser = argparse.ArgumentParser(description='')\nparser.add_argument('--output_path', type=str, default='./data_all_no_empty_mask', help='custom data path')\nparser.add_argument('--src', type=str, default='', help='custom data path')\nparser.add_argument('--mode', type=str, default='Train', help='train or test mode')\nparser.add_argument('--h5_filename', type=str, default='lits_train.h5', help='combined h5 filename')\nparser.add_argument('--max_hu_val', type=int, default=250)\nparser.add_argument('--min_hu_val', type=int, default=-200)\nparser.add_argument('--train_test_split', type=float, default=0.8, help='specify the train test ratio')\nparser.add_argument('--seed', type=int, default=23, help='seed for random choice')\nparser.add_argument('--remove_empty_mask', type=int, default=0, help='remove empty mask? 1(yes), 0(no)')\n#---------- data_two changes start-----#\n#parser.add_argument('--output_path', type=str, default='./data_two_no_empty_mask', help='custom data path')\n#---------- data_two changes end-----#\nargs = parser.parse_args()\n\n\nsrc_path = args.src\nmax_window_value = args.max_hu_val\nmin_window_value = args.min_hu_val\ntrain_test_ratio = args.train_test_split\ntrain_str = args.mode\nsave_path = args.output_path\nh5_filename = args.h5_filename\nseed = args.seed\n\nmax_window_value = 250\nmin_window_value = -200\nsrc_path = '../../data/LiTS/'\n\n\n# if the mode is 'Train' then create the h5 file out of train volumes\n# else if it is in Test mode then create the h5 file out of test \n# volumes(which do not have corresponding segmentation)\n\nif train_str in 'Train':\n num_patients = 131\nelif train_str in 'Test':\n num_patients = 70\n\n# do the train-test split our of the 131 volumes\ntrain_set_len = math.floor(num_patients * train_test_ratio)\n# randomly pick train_set_len elements from the set of all indicesnp.\n\n#---------- data_two changes start-----#\n#num_patients = 2\n#train_set_len = math.floor(num_patients * train_test_ratio)\n#---------- data_two changes end-----#\n\nnp.random.seed(seed)\ntrain_set = np.random.choice(num_patients, train_set_len, replace=False)\n# take the remainng patients in test list\ntest_set = list(set(np.arange(num_patients)).difference(train_set))\n\n#---------- data_two changes start-----#\nprint('train_set', train_set)\nprint('test_set', test_set)\n#---------- data_two changes end-----#\n\nos.makedirs(save_path, exist_ok=True)\ntrain_h5_filepath = save_path + '/' + 'train.h5'\ntest_h5_filepath = save_path + '/' + 'test.h5'\n\ntrain_dataset = h5py.File(train_h5_filepath, 'w')\ntest_dataset = h5py.File(test_h5_filepath, 'w')\n\ndef create_h5(dataset, patients=None):\n cnt = 0 # cnt of total number of images(= segmentations) in the Train set including data from\n # all the volumes\n dataset.create_group('CT')\n for k in range(len(patients)):\n i = patients[k]\n print('in the loop')\n # get the volume \n src = sitk.ReadImage(src_path + train_str + '/volume-' + str(i) + '.nii')\n # get the numpy array from the volumes\n src_img = sitk.GetArrayFromImage(src)\n print(src_img)\n # perform Hounsfield windowing on source images(only)\n src_img[src_img > max_window_value] = max_window_value\n src_img[src_img < min_window_value] = min_window_value\n \n # similar processing on segmentation nii file \n if train_str in 'Train':\n seg = sitk.ReadImage(src_path + train_str + '/segmentation-' + str(i) + '.nii')\n seg_img = sitk.GetArrayFromImage(seg)\n # the labels legend: 0: background, 1: liver, 2: liver tumor\n # since we are only interested in the liver we convert\n # tumor labels into liver label as the tumor is part of the liver region\n # we do not need the tumor segmentation and hence\n # converting the tumor labels to liver labels\n seg_img[seg_img == 2] = 1 \n \n # get the src image shape to see how many slices(=depth or #channels) are present. \n # extract the slices as these need to go inside the volume individually\n d, h, w = src_img.shape\n print(d)\n for idx in range(d):\n '''\n img_slice = src_img[idx, :, :]\n img_slice = img_slice.squeeze()\n dataset.create_dataset('CT/img/{:d}'.format(cnt), data=img_slice)\n '''\n #dataset.create_dataset('img/{:d}'.format(cnt), data=img_slice)\n if train_str in 'Train':\n seg_slice = seg_img[idx, :, :]\n # if the segmentation contains anything other than background\n if len(np.unique(seg_slice)) > 1:\n seg_slice = seg_slice.squeeze()\n dataset.create_dataset('CT/seg/{:d}'.format(cnt), data=seg_slice)\n #dataset.create_dataset('seg/{:d}'.format(cnt), data=seg_slice)\n \n img_slice = src_img[idx, :, :]\n img_slice = img_slice.squeeze()\n dataset.create_dataset('CT/img/{:d}'.format(cnt), data=img_slice)\n \n cnt += 1 #increment cnt as a new slice has been added to dataset\n dataset.close()\n\ncreate_h5(train_dataset, train_set)\ncreate_h5(test_dataset, test_set)\n","sub_path":"dataset_builder_unet_no_empty_mask.py","file_name":"dataset_builder_unet_no_empty_mask.py","file_ext":"py","file_size_in_byte":5730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"319570625","text":"import os\r\nimport json\r\nimport traceback\r\n\r\nimport bpy\r\nimport mathutils\r\n\r\nfrom . import livebuild_helper as lh\r\n\r\n# Operators --------------------------------------\r\n\r\nclass ImportPanel(bpy.types.Panel):\r\n bl_space_type = 'VIEW_3D'\r\n bl_region_type = 'TOOLS'\r\n bl_label = 'Import'\r\n bl_context = 'objectmode'\r\n bl_category = 'Elfin'\r\n\r\n def draw(self, context):\r\n layout = self.layout\r\n row = layout.row(align=True)\r\n col = row.column()\r\n col.operator('elfin.import', text='Import design')\r\n\r\n# Operators --------------------------------------\r\n\r\nclass ImportOperator(bpy.types.Operator):\r\n bl_idname = 'elfin.import'\r\n bl_label = 'Import elfin-solver output (#imp)'\r\n bl_options = {'REGISTER', 'UNDO'}\r\n\r\n filepath = bpy.props.StringProperty(subtype=\"FILE_PATH\")\r\n\r\n def invoke(self, context, event):\r\n self.filepath = os.path.splitext(bpy.data.filepath)[0] + '.json'\r\n context.window_manager.fileselect_add(self)\r\n return {'RUNNING_MODAL'}\r\n\r\n def execute(self, context):\r\n \"\"\"Import elfin-solver JSON output into scene.\r\n \"\"\"\r\n with open(self.filepath, 'r') as file:\r\n es_out = json.load(file)\r\n\r\n err_msg = materialize(es_out)\r\n\r\n if len(err_msg) > 0:\r\n self.report({'ERROR'}, err_msg);\r\n return {'FINISHED'}\r\n else:\r\n return {'FINISHED'}\r\n\r\n# Helpers ----------------------------------------\r\ndef materialize(es_out):\r\n # Reads elfin-solver output JSON and projects modules into the scene.\r\n\r\n err_msg = \"\"\r\n for pgn_name in es_out:\r\n pg_network = es_out[pgn_name]\r\n\r\n # for solution in pg_network:\r\n print('------------------------------------------')\r\n print('---------------IMPORT LOGS----------------')\r\n print('------------------------------------------')\r\n\r\n if len(pg_network) == 0:\r\n err_msg += 'ERROR: {} has no decimated parts.\\n'.format(pgn_name)\r\n continue\r\n\r\n for dec_name, dec_solutions in pg_network.items():\r\n first_node = True\r\n solution_nodes = []\r\n\r\n print('Displaying best solution for {}:{}' \\\r\n .format(pgn_name, dec_name));\r\n if not dec_solutions:\r\n err_msg += 'ERROR: {}:{} has no solutions.\\n' \\\r\n .format(pgn_name, dec_name)\r\n continue\r\n\r\n sol = dec_solutions[0]\r\n for node in sol['nodes']:\r\n print('Materialize: ', node['name'])\r\n\r\n if first_node:\r\n first_node = False\r\n\r\n # Add first module.\r\n new_mod = lh.add_module(\r\n node['name'],\r\n color=lh.ColorWheel().next_color(),\r\n follow_selection=False)\r\n\r\n solution_nodes.append(new_mod)\r\n\r\n # Project node.\r\n tx = mathutils.Matrix(node['rot']).to_4x4()\r\n tx.translation = [f/lh.blender_pymol_unit_conversion for f in node['tran']]\r\n new_mod.matrix_world = tx * new_mod.matrix_world\r\n\r\n else:\r\n src_term = prev_node['src_term'].lower()\r\n src_chain_name = prev_node['src_chain_name']\r\n dst_chain_name = prev_node['dst_chain_name']\r\n\r\n selector = lh.module_enum_tuple(\r\n node['name'], \r\n extrude_from=src_chain_name, \r\n extrude_into=dst_chain_name,\r\n direction=src_term)[0]\r\n\r\n imported, _ = lh.extrude_terminus(\r\n which_term=src_term,\r\n selector=selector,\r\n sel_mod=new_mod,\r\n color=lh.ColorWheel().next_color(),\r\n reporter=None)\r\n\r\n assert(len(imported) == 1)\r\n\r\n new_mod = imported[0]\r\n solution_nodes.append(new_mod)\r\n\r\n prev_node = node\r\n\r\n # Name network and select all nodes.\r\n if solution_nodes:\r\n solution_nodes[0].parent.name = ':'.join([pgn_name, dec_name])\r\n\r\n for node in solution_nodes:\r\n node.select = True\r\n\r\n return err_msg","sub_path":"All_In_One/addons/elfin/import.py","file_name":"import.py","file_ext":"py","file_size_in_byte":4414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"218909282","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright 2019, Data61\n# Commonwealth Scientific and Industrial Research Organisation (CSIRO)\n# ABN 41 687 119 230.\n#\n# This software may be distributed and modified according to the terms of\n# the BSD 2-Clause license. Note that NO WARRANTY is provided.\n# See \"LICENSE_BSD2.txt\" for details.\n#\n# @TAG(DATA61_BSD)\n#\n\n\"\"\"\nThis script is a quick way to execute the tests for all capdl-python modules.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, \\\n unicode_literals\nfrom concurrencytest import ConcurrentTestSuite, fork_for_tests\n\nimport argparse, multiprocessing, os, sys, unittest\n\nME = os.path.abspath(__file__)\n\n\ndef main(argv):\n parser = argparse.ArgumentParser(prog=argv[0],\n description='Run capdl tests')\n parser.add_argument('--verbosity', '-v', default=1, type=int,\n help=\"Verbosity to run tests. 0 = quiet. 1 = default. 2 = verbose\")\n options = parser.parse_args(argv[1:])\n\n # load the tests we want to run\n loader = unittest.TestLoader()\n test_suite = unittest.TestSuite()\n print(\"Looking for tests in {0}\".format(os.path.dirname(ME)))\n test_suite.addTests(loader.discover(os.path.dirname(ME), pattern=\"*.py\"))\n\n concurrent_suite = ConcurrentTestSuite(test_suite, fork_for_tests(multiprocessing.cpu_count()))\n runner = unittest.TextTestRunner(verbosity=options.verbosity)\n result = runner.run(concurrent_suite)\n if result.wasSuccessful():\n return 0\n return 1\n\n\nif __name__ == '__main__':\n sys.exit(main(sys.argv))","sub_path":"python-capdl-tool/tests/runall.py","file_name":"runall.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"43537895","text":"# coding: UTF-8\nimport json\nimport numpy as np\n\n#画像は正方形を仮定\ndef get_branch(layer_json_value,img_size):\n #ノードの数は画像のピクセル数 (= 縦 * 横 * 入力画像のチャネル数)\n number_of_node = img_size * img_size * layer_json_value[\"input_channels\"]\n #kernel_size * kernel_sizeだけそのピクセルは参照される それがout_channels(=フィルターの数と等価)だけ繰り返される\n node_branch = layer_json_value[\"kernel_size\"] * layer_json_value[\"kernel_size\"] * layer_json_value[\"out_channels\"]\n if layer_json_value[\"skip_connection\"] > 0:\n raise Exception('Error!:cnn_output_branch do not get skip_connection more than 0')\n #np.full(10, 3) なら array([3, 3, 3, 3, 3, 3, 3, 3, 3, 3])\n return np.full(number_of_node, node_branch)","sub_path":"forward/get_branch/cnn/cnn_output_branch.py","file_name":"cnn_output_branch.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"591365762","text":"from __future__ import division\n\nfrom gwcinstance import GWC_TASK_STATUS\n\ndef tasks_to_str(pending_array):\n \"\"\" Pretty print GWC instances pending tasks array \"\"\"\n s = 'Total Tasks running: {}\\n'.format(len(pending_array))\n for task in pending_array:\n processed, total, remaining, task_id, task_status = task\n progress = (processed/total) * 100 if total > 0 else -1\n s += \"Task ID: {} Status: {} Total: {} Processed: {} Remaining: {} Progress: {}% \\n\".format(\n task_id,\n GWC_TASK_STATUS[task_status],\n total,\n processed,\n remaining,\n round(progress,2)\n )\n return s\n","sub_path":"geowebcache/Python/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"238076865","text":"from functools import wraps\n\n\nclass Log:\n def __init__(self, logger):\n self.logger = logger\n\n @staticmethod\n def _create_message(result=None, *args, **kwargs):\n message = ''\n if args:\n message += 'args: {} '.format(args)\n if kwargs:\n message += 'kwargs: {} '.format(kwargs)\n if result:\n message += '= {}'.format(result)\n return message\n\n def __call__(self, func):\n @wraps(func)\n def decorated(*args, **kwargs):\n result = func(*args, **kwargs)\n message = Log._create_message(result, *args, **kwargs)\n self.logger.info('{} - {} - {}'.format(message, decorated.__name__, decorated.__module__))\n return result\n return decorated","sub_path":"log/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"148969326","text":"import maya.cmds as mc\r\n\r\nbtns=[('shirt',(1,0,0,0)),('pant',(0,1,0,0)),('color',(0,0,1,0)),('body',(1,0,0,1)),('hair',(0,1,0,1)),('shoe',(0,0,1,1)),('test01',(1,0,1,0)),('test02',(0,1,1,0)),('test03',(1,1,0,0))]\r\n\r\nif mc.window(\"rgbMaker\",ex=True):\r\n mc.deleteUI(\"rgbMaker\")\r\n\r\nif mc.windowPref(\"rgbMaker\",ex=True):\r\n mc.windowPref(\"rgbMaker\",r=True)\r\n\r\nmc.window(\"rgbMaker\",wh=(150,300))\r\nmc.columnLayout(adj=True)\r\nfor btn,ca in btns:\r\n mc.button(btn,l=btn)\r\nmc.showWindow(\"rgbMaker\")","sub_path":"makeCBs.py","file_name":"makeCBs.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"310113185","text":"from BinaryTreeNode import BinaryTreeNode\n\nr = BinaryTreeNode(4)\nr.insertLeft(2)\nr.insertRight(5)\nr.getLeft().insertLeft(1)\nr.getLeft().insertRight(3)\n#r.getLeft().getLeft().insertLeft(0)\n#r.getLeft().getRight().insertRight(2)\n\n\nt = BinaryTreeNode(2)\nt.insertLeft(1)\nt.insertRight(3)\n\nclass Solution(object):\n def isSubtree(self, s, t):\n \"\"\"\n :type s: TreeNode\n :type t: TreeNode\n :rtype: bool\n \"\"\"\n if not s or not t:\n return False\n\n stack = [s]\n\n while stack != []:\n curr = stack.pop()\n if curr == t:\n return True\n if curr.left:\n stack.append(curr.left)\n if curr.right:\n stack.append(curr.right)\n return False\n\nprint(Solution().isSubtree(r, t))\n\n\n\n\n\n","sub_path":"LeetCode/Trees/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"641168913","text":"from django.http import HttpResponse\n\n\n\n# def index(request):\n# return HttpResponse(\"Hello, world. You're at the polls index.\")\n\n\n# def index(request):\n# response=HttpResponse(\n# \"Hello,world.You're at the polls index.\")\n# return response\n#\n\ndef bye(request):\n response = HttpResponse(\n \"Bye Bye\"\n )\n return response\n\n\n\ndef index(request):\n response = HttpResponse(\n \"\"\"\n

HELLO

\n World\n
\n
\n
\n
\n Salam \n \"\"\",\n status=404\n )\n return response\n","sub_path":"helloworld/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"77368487","text":"import numpy as np\nfrom proj1_helpers import load_csv_data\n\ndef row_cleaner(data):\n '''Function to remove all rows containing any values equal to -999\n \n INPUT VARIABLES:\n - data Data set with the jet number column and other \"bad\" columns removed\n OUTPUT VARIABLES:\n - data The array tX with all rows removed which contained at least one entry equal to -999\n '''\n\n #Finding the modal values\n modes = np.mean(data, 1)\n\n # Removing all rows where there are any entries equal to -999\n data = data[np.where(np.all(data != -999, 1))]\n\n return data\n\n\ndef data_maker(DATA_PATH, DATA_SAVE_PATH, verbose=False, length=None):\n ''' Function to read, concatenate, and clean the data before writing it to a file.\n \n INPUT VARIABLES:\n - DATA_PATH Path to the file containing the relevant data\n - DATA_SAVE_PATH Location to which the processed data is to be saved\n - verbose If verbose == True then the program will print updates during data cleaning\n \n OUTPUT VARIABLES:\n - None The cleaned data is written to a file but there is no other output\n \n '''\n \n y, tX, ids = load_csv_data(DATA_PATH)\n\n # Abbreviating length to make a short dataset if desired\n if length:\n y = y[:length]\n tX = tX[:length]\n ids = ids[:length]\n \n # Reshaping y and ids to be column vectors\n y = np.reshape(y, (len(y), 1))\n ids = np.reshape(ids, (len(ids), 1))\n \n # Removing the column with the jet numbers and the columns where all entries for jet numbers 0 and 1 equal -999\n # -> These columns where found by consulting the Cern documentation for the data\n # -> The column with the jet numbers has index 22\n # -> The columns with many -999 entries are those with indices 4, 5, 6, 12, 23, 24, 25, 26, 27, and 28\n \n tX = np.hstack((tX[:,:4], tX[:,7:12], tX[:,13:22], tX[:,29:]))\n\n # Concatenating tX, y, and ids (in that order) such that the same rows will be removed in all of them\n\n data = np.hstack((ids, y, tX))\n\n # Removing all rows with corrupted (-999) entries in them\n \n data_no999 = row_cleaner(data)\n\n # Regressing the column corresponding to DER_mass_vis and the one corresponding to DER_mass_MMC\n a = np.hstack((np.ones((len(data_no999),1)), np.reshape(data_no999[:,4], (len(data_no999),1))))\n b = data_no999[:,0]\n weights = np.linalg.lstsq(a, b)[0]\n\n # Finding -999 values in the first column (only column left with faulty values) and replacing them with regressed values\n locations = np.argwhere(tX[:,0]==-999)\n new_values = np.hstack((np.ones((len(locations),1)), np.reshape(data[locations,4], (len(locations),1)))) @ weights\n\n data[locations, 2] = np.reshape(new_values, (len(new_values),1))\n \n # Writing the data to the file. The order of the data in the original file is preserved (the entries are in the order ids - y - tX)\n # NOTE: the y are now directly in the numerical format [-1, 1]\n\n with open(DATA_SAVE_PATH, 'w') as f:\n for row in data:\n for item in row:\n f.write(\"%s,\" % item)\n f.write(\"\\n\")\n if verbose:\n print(\"file_written\")\n\n return None\n\ndata_maker(\"../data/train.csv\", \"../data/clean_train_data.csv\", True)\ndata_maker(\"../data/train.csv\", \"../data/clean_short_train.csv\", True, 10000)\n\ndata_maker(\"../data/test.csv\", \"../data/clean_test_data.csv\", True)\ndata_maker(\"../data/test.csv\", \"../data/clean_short_test.csv\", True, 10000)","sub_path":"scripts/data_cleaner.py","file_name":"data_cleaner.py","file_ext":"py","file_size_in_byte":3585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"121327963","text":"from nezha import exception\nfrom nezha import test\n\n\nclass NezhaExceptionTestCase(test.TestCase):\n def test_default_error_msg(self):\n class FakeNezhaException(exception.NezhaException):\n msg_fmt = \"default message\"\n\n exc = FakeNezhaException()\n self.assertEquals(unicode(exc), 'default message')\n\n def test_error_msg(self):\n self.assertEquals(unicode(exception.NezhaException('test')),\n 'test')\n\n def test_default_error_msg_with_kwargs(self):\n class FakeNezhaException(exception.NezhaException):\n msg_fmt = \"default message: %(code)s\"\n\n exc = FakeNezhaException(code=500)\n self.assertEquals(unicode(exc), 'default message: 500')\n self.assertEquals(exc.message, 'default message: 500')\n\n def test_error_msg_exception_with_kwargs(self):\n class FakeNezhaException(exception.NezhaException):\n msg_fmt = \"default message: %(mispelled_code)s\"\n\n exc = FakeNezhaException(code=500, mispelled_code='blah')\n self.assertEquals(unicode(exc), 'default message: blah')\n self.assertEquals(exc.message, 'default message: blah')\n\n def test_default_error_code(self):\n class FakeNezhaException(exception.NezhaException):\n code = 404\n\n exc = FakeNezhaException()\n self.assertEquals(exc.kwargs['code'], 404)\n\n def test_error_code_from_kwarg(self):\n class FakeNezhaException(exception.NezhaException):\n code = 500\n\n exc = FakeNezhaException(code=404)\n self.assertEquals(exc.kwargs['code'], 404)\n\n def test_cleanse_dict(self):\n kwargs = {'foo': 1, 'blah_pass': 2, 'zoo_password': 3, '_pass': 4}\n self.assertEquals(exception._cleanse_dict(kwargs), {'foo': 1})\n\n kwargs = {}\n self.assertEquals(exception._cleanse_dict(kwargs), {})\n\n def test_format_message_local(self):\n class FakeNezhaException(exception.NezhaException):\n msg_fmt = \"some message\"\n\n exc = FakeNezhaException()\n self.assertEquals(unicode(exc), exc.format_message())\n\n def test_format_message_remote(self):\n class FakeNezhaException_Remote(exception.NezhaException):\n msg_fmt = \"some message\"\n\n def __unicode__(self):\n return u\"print the whole trace\"\n\n exc = FakeNezhaException_Remote()\n self.assertEquals(unicode(exc), u\"print the whole trace\")\n self.assertEquals(exc.format_message(), \"some message\")\n","sub_path":"nezha/tests/test_exception.py","file_name":"test_exception.py","file_ext":"py","file_size_in_byte":2502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"187716542","text":"def readhtml(filepath):\n import urllib\n from bs4 import BeautifulSoup\n import os\n htmlf=open(filepath,'r',encoding=\"utf-8\")\n htmlcont=htmlf.read()\n soup = BeautifulSoup(htmlcont, \"html.parser\")#实例化一个BeautifulSoup对象\n [s.extract() for s in soup('script')]\n if hasattr(soup.body,\"body\"):\n bodyx=soup.body.body.div.div\n contentsx= bodyx.contents\n #print (contentsx)\n return contentsx\n else:\n print(soup.attrs)\n\ndef htmltomd(dir,file_name,contentsx):\n file = dir + \"\\\\\" + file_name[:-5]+\".md\"\n if os.path.exists(dir):\n if os.path.exists(file):\n print(file + \"已存在\")\n return\n else:\n realhtmltomd(file, contentsx)\n print(file + \"转换成功\")\n else:\n os.mkdir(dir)\n realhtmltomd(file, contentsx)\n print(file + \"转换成功\")\n\ndef realhtmltomd(file,contentsx):\n if contentsx is None:\n print(file +\"is none\")\n return\n with open(file, 'a+') as f:\n for child in contentsx:\n if hasattr(child, 'name'):\n if child.name==\"h1\":\n #print( \"===\"+str(type(child))+str(child))\n #print( child)\n f.write(\"# \"+str(child.string.replace('\\n', '').encode(\"utf-8\"))[2:-1]+'\\n')\n elif child.name==\"h2\":\n #print( child)\n f.write('\\n'+\"## \"+str(child.string.replace('\\n', '').encode(\"utf-8\"))[2:-1]+'\\n')\n elif child.name==\"h3\":\n #print( child)\n f.write('\\n'+\"### \"+str(child.get_text().replace('\\n', '').encode(\"utf-8\"))[2:-1]+'\\n')\n elif child.name==\"p\":\n #print( child)\n f.write(str(child.get_text().replace('\\n', '').encode(\"utf-8\"))[2:-1]+'\\n')\n #\n elif child.name==\"div\":\n if \"class\" in child.attrs:\n if str(child[\"class\"])==\"[\\'next\\']\":\n #title = child.get_text()\n #print(child.get_text())\n f.write(str(child.get_text().replace('\\n', '').encode(\"utf-8\"))[2:-1]+'\\n')\n\n\nimport os.path\nrootdir = 'content'\nlist_dir = os.listdir(rootdir) # 列出文件夹下所有的目录与文件\nfor i in range(0, len(list_dir)):\n path = os.path.join(rootdir, list_dir[i])\n if os.path.isfile(path):\n dirs = list_dir[i][:-4]\n print(\"====目录 \" + dirs+\" ==================================\")\n list_dir2 = os.listdir(dirs.strip())\n print(len(list_dir2))\n for i in range(0, len(list_dir2)):\n dirs2 =list_dir2[i]\n #print(dirs2)\n path2 = os.path.join(dirs,dirs2)\n if os.path.isfile(path2):\n filename = list_dir2[i]\n print(\"=======文件 \" + filename +\" ===path:\"+path2)\n contentsx=readhtml(path2)\n htmltomd(dirs+\"_1\",filename,contentsx)","sub_path":"htmltomd.py","file_name":"htmltomd.py","file_ext":"py","file_size_in_byte":3142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"150231485","text":"from datetime import date\nfrom datetime import timedelta\nfrom opengever.activity import notification_center\nfrom opengever.activity.model import Activity\nfrom opengever.activity.model import Notification\nfrom opengever.dossier.activities import DossierOverdueActivity\nfrom opengever.dossier.activities import DossierOverdueActivityGenerator\nfrom opengever.dossier.behaviors.dossier import IDossier\nfrom opengever.ogds.base.actor import SYSTEM_ACTOR_ID\nfrom opengever.testing import IntegrationTestCase\n\n\nclass TestDossierOverdueActivity(IntegrationTestCase):\n\n features = ('activity', )\n\n def _get_watcher_ids(self, obj):\n watchers = notification_center().get_watchers(self.dossier)\n return [watcher.actorid for watcher in watchers]\n\n def test_dossier_overdue_activity_is_from_system_user(self):\n self.login(self.dossier_manager)\n DossierOverdueActivity(self.dossier, self.request).record()\n activity = Activity.query.filter(\n Activity.kind == DossierOverdueActivity.kind).first()\n\n self.assertEqual(SYSTEM_ACTOR_ID, activity.actor_id)\n\n def test_register_resonsible_as_watcher_on_activity_creation(self):\n self.login(self.dossier_manager)\n IDossier(self.dossier).responsible = self.regular_user.getId()\n DossierOverdueActivity(self.dossier, self.request).record()\n\n activity_query = Activity.query.filter(\n Activity.kind == DossierOverdueActivity.kind)\n\n self.assertEqual(1, activity_query.count())\n\n notifications = activity_query.first().notifications\n self.assertEqual(\n [self.regular_user.getId()],\n [notification.userid for notification in notifications])\n\n def test_update_dossier_overdue_watcher_on_activity_recreation(self):\n self.login(self.dossier_manager)\n\n self.assertEqual([], self._get_watcher_ids(self.dossier))\n\n IDossier(self.dossier).responsible = self.regular_user.getId()\n DossierOverdueActivity(self.dossier, self.request).record()\n\n self.assertEqual([self.regular_user.getId()],\n self._get_watcher_ids(self.dossier))\n self.assertEqual(1, Notification.query.count())\n\n IDossier(self.dossier).responsible = self.dossier_manager.getId()\n DossierOverdueActivity(self.dossier, self.request).record()\n\n self.assertEqual([self.dossier_manager.getId()],\n self._get_watcher_ids(self.dossier))\n self.assertEqual(2, Notification.query.count())\n\n\nclass TestDossierOverdueActivityGenerator(IntegrationTestCase):\n\n features = ('activity', )\n\n def test_returns_the_number_of_generated_activities(self):\n self.login(self.dossier_manager)\n\n self.assertEqual(0, DossierOverdueActivityGenerator()())\n\n IDossier(self.dossier).end = date.today() - timedelta(days=1)\n self.dossier.reindexObject()\n\n self.assertEqual(1, DossierOverdueActivityGenerator()())\n\n def test_generates_an_activity_for_each_overdue_dossier(self):\n self.login(self.dossier_manager)\n IDossier(self.dossier).end = date.today() - timedelta(days=1)\n self.dossier.reindexObject()\n DossierOverdueActivityGenerator()()\n\n self.assertEqual(1, Activity.query.count())\n\n def test_do_not_fail_if_no_overdue_dossier_is_available(self):\n self.assertEqual(0, DossierOverdueActivityGenerator()())\n","sub_path":"opengever/dossier/tests/test_activities.py","file_name":"test_activities.py","file_ext":"py","file_size_in_byte":3412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"605451156","text":"\nclass Vehicle:\n def __init__(self, id, position, velocity):\n self.id = id\n self.x = position[0]\n self.y = position[1]\n self.z = position[2]\n self.vx = velocity[0]\n self.vy = velocity[1]\n self.vz = velocity[2]\n self.traj = []\n self.vmax = 6\n self.vmin = 3\n self.dt = 0.1\n\n def UpdateState(self):\n self.x = self.x + self.vx * self.dt\n self.y = self.y + self.vy * self.dt\n self.z = self.z + self.vz * self.dt\n\n def UpdateControl(self, vx, vy, vz):\n self.vx = vx\n self.vy = vy\n self.vz = vz\n\n def UpdateLog(self,log):\n position = (self.x,self.y,self.z)\n self.traj.append(position)\n\n if self.id in log.keys():\n log[self.id].append(position)\n else:\n log[self.id] = []\n log[self.id].append(position)","sub_path":"Vehicle.py","file_name":"Vehicle.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"78969754","text":"class Student:\n def __init__(self):\n self.stuid=None\n self.age=None\n self.marks=None\n def setter(self):\n self.stuid=input(\"enter student id\")\n self.age=int(input(\"age:\"))\n self.marks=int(input(\"marks in exam:\" ))\n def validate_marks(self):\n if (self.marks>0 and self.marks<=100):\n return True\n else:\n return False\n def validate_age(self):\n if (self.age>20):\n return True\n else:\n return False\n def check_qualification(self):\n if(self.validate_marks() and self.validate_age()):\n if(self.marks>= 65):\n return True\n else:\n return False\n else:\n return False\n def getter(self):\n print(\"student Id:\",self.stuid)\n print(\"age:\",self.age)\n print(\"marks:\",self.marks)\n if(s1.check_qualification()):\n print(\"student is elgible for university\")\n else:\n print(\"not eligible for university\")\n \ns1=Student()\ns1.setter()\ns1.getter()\n\n \n","sub_path":"university.py","file_name":"university.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"331239137","text":"# -*- coding: utf-8 -*-\nfrom flask_wtf import FlaskForm\nfrom wtforms import StringField, validators\nfrom wtforms.fields.html5 import EmailField\nfrom wtforms.validators import DataRequired, Length\n\n\nclass ContactForm(FlaskForm):\n user_name = StringField('user_name',validators=[\n DataRequired('Votre Nom et Prénom sont nécessaires')\n ])\n email = EmailField('email', [\n validators.DataRequired('L\\'addresse Email est nécessaire'),\n validators.Email('L\\'addresse Email doit être valide')\n ])\n phone_number = StringField('phone_number', validators=[\n validators.DataRequired('Le numéro de téléphone est nécessaire'),\n Length(max=14, message=\"Le numéro téléphone doit être < 14 numéro\")\n ])\n body = StringField('body', validators=[\n validators.DataRequired('Le message est nécessaire !!'),\n Length(max=1000, message=\"Le message doit être < 1000 caractères\")\n ])\n","sub_path":"app/contact/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"601909051","text":"\ndef write_arff(path, relation, attributes, data,\n\tclasses=None, classifications=None):\n\n\tf = open(path, 'w')\n\n\tf.write('@relation %s\\n' % relation)\n\tf.write('\\n')\n\n\tfor attribute in attributes:\n\t\tf.write('@attribute %s %s\\n' % attribute)\n\tif classes != None:\n\t\tf.write('@attribute %s %s\\n' % classes)\n\tf.write('\\n')\n\n\tf.write('@data\\n')\n\tfor i, row in enumerate(data):\n\t\trow = [str(x) for x in row]\n\t\tif classifications != None:\n\t\t\trow.append(str(classifications[i]))\n\t\tf.write(','.join(row))\n\t\tf.write('\\n')\n\n\tf.close()\n","sub_path":"weka/arff.py","file_name":"arff.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"334058062","text":"# -*- coding: utf-8 -*-\n\n# Description: Subclass of QToolButton to allow drag and drop\n# Author: \n# Maintainer: \n# Created: Fri Jun 14 14:24:11 2013 (+0530)\n\nimport sys\nfrom PyQt5 import QtGui, QtCore\nfrom PyQt5.QtWidgets import QToolButton, QToolBar, QMainWindow\nfrom PyQt5.QtWidgets import QApplication, QTextBrowser\nfrom PyQt5.Qt import Qt\n\nimport logging\nlogger_ = logging.getLogger('mtoolbutton')\n\nclass MToolButton(QToolButton):\n \"\"\"\n QToolButton subclass with dragEvent reimplemented. It sends the\n text of the ToolButton as the mimedata.\n\n \"\"\"\n def __init__(self, *args):\n QToolButton.__init__(self, *args)\n self.dragStartPosition = QtCore.QPoint(0,0)\n\n def mousePressEvent(self, event):\n if event.buttons() & Qt.LeftButton:\n self.dragStartPosition = event.pos()\n\n def mouseMoveEvent(self, event): \n if not (event.buttons() & Qt.LeftButton):\n return \n if (event.pos() - self.dragStartPosition).manhattanLength() < QApplication.startDragDistance():\n return\n drag = QtGui.QDrag(self)\n mimeData = QtCore.QMimeData()\n mimeData.setText(self.text())\n drag.setMimeData(mimeData)\n drag.exec_(Qt.CopyAction)\n\n\nclass MyWidget(QTextBrowser):\n \"\"\"Class for testing the drag and drop ability of MToolButton\"\"\"\n def __init__(self, *args):\n QTextBrowser.__init__(self, *args)\n self.dropCount = 0\n self.setPlainText('Drops: %d' % (self.dropCount))\n self.setAcceptDrops(True)\n \n\n def dragEnterEvent(self, event):\n print(('2222', event.mimeData().text()))\n if event.mimeData().hasFormat('text/plain'):\n event.acceptProposedAction()\n print('3333 accepted ')\n\n def dragMoveEvent(self, event):\n \"\"\"This must be reimplemented to accept the event in case of\n QTextBrowser. Not needed in QWidgets in general.\"\"\"\n print('4444')\n event.acceptProposedAction()\n\n def dropEvent(self, event):\n print(('5555', event.mimeData().text()))\n self.dropCount += 1\n self.setPlainText('`%s` dropped: %d times' % (event.mimeData().text(), self.dropCount))\n event.acceptProposedAction()\n QTextBrowser.dropEvent(self, event)\n\ndef test_main():\n \"\"\"Test main: see if drag and drop is working\"\"\"\n app = QApplication(sys.argv)\n mainwin = QMainWindow()\n mainwin.setWindowTitle('MTooButton')\n toolbar = QToolBar()\n mainwin.addToolBar(toolbar)\n button = MToolButton()\n button.setText('test')\n toolbar.addWidget(button)\n browser = MyWidget(mainwin)\n print((browser.acceptDrops()))\n mainwin.setCentralWidget(browser)\n mainwin.show()\n sys.exit(app.exec_())\n\nif __name__ == '__main__':\n test_main()\n\n# \n# mtoolbutton.py ends here\n","sub_path":"moosegui/mtoolbutton.py","file_name":"mtoolbutton.py","file_ext":"py","file_size_in_byte":2809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"344792114","text":"from typing import List\nimport numpy as np\nimport time\nfrom agents.BaseAgent import BaseAgent\nfrom agents.Decision import Decision\n\nfrom environment.Battlesnake.model.GameInfo import GameInfo\nfrom environment.Battlesnake.model.MoveResult import MoveResult\nfrom environment.Battlesnake.model.Position import Position\nfrom environment.Battlesnake.model.Snake import Snake\nfrom environment.Battlesnake.model.board_state import BoardState\nfrom environment.Battlesnake.model.grid_map import GridMap\nfrom environment.Battlesnake.model.Occupant import Occupant\n\n\nclass KILabAgent(BaseAgent):\n\n def __init__(self):\n self.food_path: List[Position] = []\n self.Decision = Decision()\n self.first = True\n\n def get_name(self):\n return 'Jürgen'\n\n def start(self, game_info: GameInfo, turn: int, board: BoardState, you: Snake):\n # read ea csv\n self.food_path: List[Position] = []\n self.Decision = Decision()\n self.Decision.set_up_automats(you, board.snakes)\n self.Decision.set_default_board(board.width, board.height)\n\n def move(self, game_info: GameInfo, turn: int, board: BoardState, you: Snake) -> MoveResult:\n if you.latency:\n print(\"Latency\", you.latency)\n start_time = time.time()\n grid_map: GridMap[Occupant] = board.generate_grid_map()\n\n self.Decision.set_round(turn)\n next_action = self.Decision.decide(you, board, grid_map)\n\n if not next_action:\n possible_actions = you.possible_actions()\n for action in possible_actions:\n next_position = you.get_head().advanced(action)\n for snake in board.snakes:\n if next_position == snake.get_tail() and snake.health != 100:\n next_action = action\n if not next_action:\n next_action = np.random.choice(possible_actions)\n print(\"Move-DAUER: \", time.time() - start_time)\n return MoveResult(direction=next_action)\n\n def end(self, game_info: GameInfo, turn: int, board: BoardState, you: Snake):\n self.food_path = []\n self.first = True\n","sub_path":"agents/KILabAgent.py","file_name":"KILabAgent.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"170411531","text":"# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n nmea_mainDialog\n A QGIS plugin\n load nmea file to qgis\n -------------------\n begin : 2013-05-11\n copyright : (C) 2013 by Maciej Olszewski\n email : mackoo@opoczta.pl\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program is free software; you can redistribute it and/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\nfrom PyQt4 import QtCore, QtGui\nfrom ui_nmea_main import Ui_nmea_main\nfrom ui_nmea import Ui_nmea\nfrom ui_settings import Ui_Dialog\nimport PyQt4.Qwt5 as Qwt\n\n# create the dialog for zoom to point\n\n\n\nclass nmea_Dialog(QtGui.QDialog):\n def __init__(self):\n QtGui.QDialog.__init__(self)\n # Set up the user interface from Designer.\n self.ui = Ui_nmea()\n self.ui.setupUi(self)\n\n\n\n##\n##\n## sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)\n#### sizePolicy.setHorizontalStretch(0)\n#### sizePolicy.setVerticalStretch(0)\n#### sizePolicy.setHeightForWidth(self.plot.sizePolicy().hasHeightForWidth())\n## self.plot.setSizePolicy(sizePolicy)\n## self.plot.setMinimumSize(QtCore.QSize(0,0))\n## self.plot.setAutoFillBackground(False)\n## #Decoration\n##\n## self.plot.plotLayout().setAlignCanvasToScales(True)\n## zoomer = Qwt.QwtPlotZoomer(Qwt.QwtPlot.xBottom, Qwt.QwtPlot.yLeft, Qwt.QwtPicker.DragSelection, Qwt.QwtPicker.AlwaysOff, self.plot.canvas())\n## zoomer.setRubberBandPen(QtGui.QPen(QtCore.Qt.blue))\n\n\n\n\n## self.plot.setCanvasBackground(QtCore.Qt.white)\n\nclass nmea_mainDialog(QtGui.QDialog):\n def __init__(self):\n QtGui.QDialog.__init__(self)\n # Set up the user interface from Designer.\n self.ui = Ui_nmea_main()\n self.ui.setupUi(self)\n\nclass nmea_settDialog(QtGui.QDialog):\n def __init__(self):\n QtGui.QDialog.__init__(self)\n # Set up the user interface from Designer.\n self.ui = Ui_Dialog()\n #QtCore.QObject.connect(self.ui.utcCheck, SIGNAL('stateChanged(int)'),nmea_Dialog.ui.utcCheck.setCheckState(True))\n\n self.ui.setupUi(self)","sub_path":"nmea_dialog.py","file_name":"nmea_dialog.py","file_ext":"py","file_size_in_byte":2840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"194150382","text":"#!/usr/bin/env python3.5\n\nimport glob, os\nimport eos_starter_lib as esl\nfrom concurrent.futures import ThreadPoolExecutor\nimport subprocess, shlex\n\n#id_folders = glob.glob(\"/user/HS204/m09113/my_project_folder/CASIA_webface/landmarks/*\")\n#id_folders = glob.glob(\"/user/HS204/m09113/my_project_folder/PaSC/video/data_CCR/*\")\n#id_folders = glob.glob(\"/user/HS204/m09113/my_project_folder/PaSC/still/data_CCR/0246*\")\n#id_folders = glob.glob(\"/user/HS204/m09113/my_project_folder/IJB_A/input_org/*\")\n#id_folders = glob.glob(\"/user/HS204/m09113/my_project_folder/IJB_A/input_org/frame/*.pts\")\n\n#id_folders = glob.glob(\"/user/HS204/m09113/my_project_folder/CASIA_webface/landmarks/180180*\")\n#images_base = '/vol/vssp/datasets/still/CASIA-WebFace/CASIA-WebFace/'\n\n#OUTPUTBASE = \"/user/HS204/m09113/my_project_folder/CASIA_webface/face_boxes/\"\n#OUTPUTBASE = \"/user/HS204/m09113/my_project_folder/PaSC/video/face_boxes/\"\n#OUTPUTBASE = \"/user/HS204/m09113/my_project_folder/IJB_A/multi_iter75_reg30/\"\n\n#print (id_folders)\n\n\n#def read_pts(filename):\n#\t\"\"\"A helper function to read ibug .pts landmarks from a file.\"\"\"\n#\tlines = open(filename).read().splitlines()\n#\tlines = lines[3:71]\n#\n#\tlandmarks = []\n#\tfor l in lines:\n#\t\tcoords = l.split()\n#\t\tlandmarks.append([float(coords[0]), float(coords[1])])\n#\n#\treturn landmarks\n#\n#def run (message, exe_list):\n#\tif not message=='':\n#\t\tprint (message)\n#\t#subprocess.run(exe_list, timeout=timeout_sec, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n#\tcompleted = subprocess.run(exe_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n#\terr = completed.stderr.decode('utf-8')\n#\tstd = completed.stdout.decode('utf-8')\n#\tif not err == '':\n#\t\tprint ('err',err)\n#\n#\n#\n#\n#with ThreadPoolExecutor(max_workers=30) as executor:\n#\tfor n in range(0,len(id_folders)):\n#\t\tid_folder = id_folders[n]\n\t#\n#\t\t# make absolute\n#\t\tid_folder = os.path.abspath(id_folder)\t\n#\n#\t\t#print (id_folder)\n\t\t#\n\t#\n#\t\t# check if it's a folder\n#\t\tif (not os.path.isdir(id_folder)):\n#\t\t\tcontinue;\t\t\n\t#\n#\t\ttry:\n\t\t#\n#\t\t\t# create outputfolder\n#\t\t\t#outputfolder = OUTPUTBASE + os.path.basename(id_folder)+\"/\"\n#\t\t\t#if (not os.path.exists(outputfolder)):\n#\t\t\t#\tprint('ohohoh', outputfolder)\n#\t\t\t\t#os.mkdir(outputfolder)\t\n#\n#\t\t\t#exit(0)\n#\t\t\tmessage = \"video \"+os.path.basename(id_folder) +\" (\"+str(n)+\" of \"+str(len(id_folders))+\" )\"\n#\n#\t\t\t# gather lm and img files\n#\t\t\tlms = glob.glob(id_folder+\"/*.pts\")\n#\t\t\t#lms = [id_folder]\n#\t\t\t#imgs = [] #esl.find_imgs_to_lms (lms, \".jpg\")\t\n#\t\t\timgs = esl.find_imgs_to_lms (lms, \".jpg\")\t\n#\t\t\t#imgs = esl.find_imgs_to_lms (lms, \".*[!pts]\")\n#\t\t\tfor i in range(len(lms)):\n#\t\t\t\t#img_source = images_base+lms[i][-15:-3]+'jpg'\n#\t\t\t\t#img_dest = OUTPUTBASE+lms[i][-15:-3]+'jpg'\n#\t\t\t\timg_source = imgs[i]\n#\t\t\t\t#img_dest = img_source.replace('data_CCR', 'face_boxes')\n#\t\t\t\timg_dest = img_source.replace('input_org', 'face_boxes')\n#\n#\t\t\t\t#print (img_source)\n#\t\t\t\t#print (img_dest)\n\t\t\t\t#\n#\t\t\t\tlandmarks = read_pts(lms[i])\n#\t\t\t\theight_delta = abs(landmarks[28-1][1]-landmarks[9-1][1])*2.5\n#\t\t\t\theight_offset = landmarks[28-1][1]-height_delta/2.5*1.2\n#\t\t\t\twidth_delta = height_delta\n#\t\t\t\twidth_offset = (landmarks[28-1][0]+landmarks[9-1][0])/2-width_delta/2\n#\n#\t\t\t\texe_list = ['convert', img_source, '-crop', str(width_delta)+'x'+str(height_delta)+'+'+str(width_offset)+'+'+str(height_offset), '-resize', '512x512', img_dest]\n#\t\t\t\texecutor.submit(run,message, exe_list)\n#\t\t\t\tmessage = ''\n#\t\t\t\t#exit(0)\n#\t\texcept Exception as e:\n#\t\t\tprint(\"ERROR on \" + message + \": \" + str(e))\t\n\t\t\t\t#\nimport cv2\nimport numpy as np\n\ndef fix_img (img_path):\n\timg = cv2.imread(img_path)\n\twidth, height, _ = img.shape\n\tif width != 512 and height==512:\n\t\tprint ('adding rows to', img_path)\n\t\tzeros = np.zeros((512-width, 512,3))\n\t\t#print (img.shape)\n\t\t#print (zeros.shape)\n\t\tnew = np.concatenate((zeros, img), axis=0)\n\t\t#print (new.shape)\n\t\tcv2.imwrite(img_path, new)\n\telif height != 512 and width==512:\n\t\tprint ('adding cols to', img_path)\n\t\tzeros = np.zeros((512, 512-height,3))\n\t\t#print (img.shape)\n\t\t#print (zeros.shape)\n\t\tnew = np.concatenate((zeros, img), axis=1)\n\t\t#print (new.shape)\n\t\tcv2.imwrite(img_path, new)\n\telif width != 512 and height != 512:\n\t\tprint ('adding rows and cols to', img_path)\n\t\tzeros1 = np.zeros((512-width, height,3))\n\t\ttmp = np.concatenate((zeros1, img), axis=0)\n\t\tzeros2 = np.zeros((512, 512-height,3))\n\t\tnew = np.concatenate((zeros2, tmp), axis=1)\n\t\t#cv2.imwrite(img_path.replace('.jpg','_new.jpg'), new)\n\t\t#exit(0)\n\t\tcv2.imwrite(img_path, new)\n\n\n\n\n\n\n#images = glob.glob(\"/user/HS204/m09113/my_project_folder/PaSC/video/face_boxes/*/*\")\nimages = glob.glob(\"/user/HS204/m09113/my_project_folder/CASIA_webface/face_boxes/*/*\")\n#images = glob.glob(\"/user/HS204/m09113/my_project_folder/IJB_A/face_boxes/*/*\")\nprint ('number of found files', len(images))\n#index = images.index('/user/HS204/m09113/my_project_folder/PaSC/video/face_boxes/06051d661/06051d661-217.jpg')\n#print ('index:',index)\n#exit(0)\n\nwith ThreadPoolExecutor(max_workers=35) as executor:\n\tfor img_path in images:\n\t\texecutor.submit(fix_img,img_path)\n\t\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"crop_facebox.py","file_name":"crop_facebox.py","file_ext":"py","file_size_in_byte":5054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"259565087","text":"from flask import flash, redirect, render_template, request, url_for\nfrom flask_login import current_user, login_required\nfrom werkzeug.utils import secure_filename\n\nfrom wedding_gallery import app\nfrom wedding_gallery.models import core, DBSession\n\n\n@login_required\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in ['png', 'jpg', 'jpeg', 'gif']\n\n\n@app.route('/upload', methods=['GET', 'POST'])\n@login_required\ndef upload():\n if request.method == 'POST':\n if 'file' not in request.files:\n flash('No file part')\n return redirect(request.url)\n files = [f for f in request.files.getlist('file') if f and f.filename]\n if not files:\n flash('No selected file')\n return redirect(request.url)\n for file in files:\n if allowed_file(file.filename):\n filename = secure_filename(file.filename)\n path = url_for('static', filename=filename)\n file.save('wedding_gallery' + path)\n photo = core.Photo(link=path, user_id=current_user.id)\n DBSession.add(photo)\n DBSession.commit()\n flash(f'{len(files)} photos uploaded!')\n return redirect(url_for('upload'))\n\n template_args = {\n 'title': 'Upload Photos'\n }\n return render_template('upload.html', **template_args)\n","sub_path":"wedding_gallery/controllers/upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"326197377","text":"\r\n\r\ndef inversao():\r\n\tlista=[]\r\n\r\n\tlistaf=[]\r\n\r\n\ty=0\r\n\r\n\tlista = input(\"Digite uma palavra pra ser invertida: \")\r\n\r\n\tfor x in range(len(lista)-1,-1,-1):\r\n \r\n\t\tlistaf.append(lista[x])\r\n \r\n\t\ty=y+1\r\n\treturn(listaf)\r\n\r\n\tprint(listaf)\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"30381610","text":"'''判断回文数'''\r\n\r\n#第一种方法 二分依次比较字符是否相等\r\na = input(\"input a number: \")\r\nb = str(a)\r\nflag = True\r\nfor i in range(int(len(a)/2)):\r\n if a[i] != a[-i-1]:\r\n flag = False\r\n break\r\nif flag:\r\n print( a,\"是一个回文数\")\r\nelse:\r\n print(a,\"不是回文数\")\r\n\r\n#第二种方法 比较前后两个数是否相等\r\nx = input(\"请输入数字: \")\r\nstr_x = str(x)\r\nstr_y = \"\"\r\nfor i in str_x:\r\n str_y = i + str_y\r\n\r\nif str_x == str_y:\r\n print(\"是回文\")\r\nelse:\r\n print(\"不是回文\")","sub_path":"lizi/huiwenshu.py","file_name":"huiwenshu.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"69983249","text":"from cs50 import get_int\nfrom sys import exit\n\nwhile True:\n n = get_int(\"Enter Integer between 1 and 8: \")\n if n < 1 or n > 8:\n print(\"Invalid Input, please try again\")\n else:\n break\n\n# For loop:\nfor i in range(n):\n d = i+1 # Calculate blocks per line\n h = n-i-1 # Calculate spaces per line\n print(\" \" * h, end=\"\") # Print spaces\n print(\"#\" * d, end=\"\\n\") # Print blocks","sub_path":"pset6/mario/less/mario.py","file_name":"mario.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"382624792","text":"from mock.mock import Mock\nfrom base import GAETestCase\n\nfrom web import listar\n\n\nfrom usuario.model import Usuario\nimport json\n\nclass RestTests(GAETestCase):\n \n def test_listar(self):\n usuario = Usuario(nome='teste', email='teste@teste.tst', google_id=123)\n usuario.put()\n usuarios = Usuario.query().fetch()\n lista_dict = [{\"nome\": usu.nome, \"email\": usu.email, \"google_id\": usu.google_id, \"id\": usu.key.id()} for usu in usuarios]\n resposta_mock = Mock()\n listar.listar(resposta_mock)\n json_str = json.dumps(lista_dict)\n resposta_mock.write.assert_called_once_with(json_str)\n\n def test_salvar(self):\n resp = Mock()\n rest.salvar(resp, 'teste', 'teste@teste.com', 1234)\n lista = Usuario.query().fetch()\n self.assertEquals(1, len(lista))\n usuario = lista[0]\n self.assertEqual('teste', usuario.firstname)\n self.assertEqual('teste@teste.com', usuario.email)","sub_path":"backend/test/rest_tests.py","file_name":"rest_tests.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"206175513","text":"import os\nimport numpy as np\nimport nibabel as nib\nfrom fetal_net.prediction import run_validation_cases_from_image_simple\nfrom tqdm import tqdm\n\nmodel_file_path = r\"/datadrive/configs/20200404_single_resolution_iter3/fetal_net_model-epoch15-loss202.728-acc0.922.h5\" #'path/trained/model'\nimages_dir = r\"/data/home/Shai/side_data_dir\" # 'path/scans/folder'\noutput_dir_path = r\"/data/home/Shai/simple_results\" #'path/results'\n\n# Load all inference images\n# Assumes structure of: images_dir -> subject ids folders -> image saved as 'volume.nii', but change as you please\nsubject_id_folders = os.listdir(images_dir)\nvolume_filename = 'volume.nii'\nvolumes_list = []\noutput_folders_path = []\nfor subject_id in subject_id_folders:\n cur_volume_path = os.path.join(images_dir, subject_id, volume_filename)\n volumes_list.append(nib.load(cur_volume_path).get_data())\n output_folders_path.append(os.path.join(output_dir_path, subject_id))\n\n\n# Normalize - currently 'hard coded' for my existing normalization\ndef norm_image(image_as_np):\n m = image_as_np.mean(axis=(-1, -2, -3))\n s = image_as_np.std(axis=(-1, -2, -3))\n image_as_np = np.subtract(image_as_np, m, out=image_as_np, casting='unsafe')\n image_as_np = np.divide(image_as_np, s, out=image_as_np, casting='unsafe')\n return image_as_np\n\n\nfor i, im in enumerate(volumes_list):\n volumes_list[i] = norm_image(im)\n\n# create output folders\nfor output_path in output_folders_path:\n os.makedirs(output_path, exist_ok=True)\n\n# run prediction\npredictions, predictions_paths = run_validation_cases_from_image_simple(volumes_list, model_file_path,\n output_folders_path, patch_shape=[64, 64, 5],\n overlap_factor=0.8)\n","sub_path":"scripts/simple_predict.py","file_name":"simple_predict.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"457210632","text":"from toontown.toonbase.ToontownBattleGlobals import *\nfrom toontown.toonbase import ToontownGlobals\nfrom direct.fsm import StateData\nfrom direct.directnotify import DirectNotifyGlobal\nfrom toontown.battle import BattleBase\nfrom direct.gui.DirectGui import *\nfrom pandac.PandaModules import *\nfrom toontown.toonbase import TTLocalizer\n\nclass TownBattleChooseAvatarPanel(StateData.StateData):\n \"\"\"TownBattleChooseAvatarPanel\n This is the panel used for choosing a avatar to attack.\n \"\"\"\n notify = DirectNotifyGlobal.directNotify.newCategory('ChooseAvatarPanel')\n\n def __init__(self, doneEvent, toon):\n self.notify.debug(\"Init choose panel...\")\n StateData.StateData.__init__(self, doneEvent)\n # How many avatars in the battle?\n self.numAvatars = 0\n # Which was picked?\n self.chosenAvatar = 0\n # Is this for toons? (or suits?)\n self.toon = toon\n return\n\n def load(self):\n gui = loader.loadModel(\"phase_3.5/models/gui/battle_gui\")\n self.frame = DirectFrame(\n relief = None,\n image = gui.find(\"**/BtlPick_TAB\"),\n image_color = Vec4(1,0.2,0.2,1),\n )\n self.frame.hide()\n\n self.statusFrame = DirectFrame(\n parent = self.frame,\n relief = None,\n image = gui.find(\"**/ToonBtl_Status_BG\"),\n image_color = Vec4(0.5,0.9,0.5,1),\n pos = (0.611, 0, 0),\n )\n \n self.textFrame = DirectFrame(\n parent = self.frame,\n relief = None,\n image = gui.find(\"**/PckMn_Select_Tab\"),\n image_color = Vec4(1,1,0,1),\n text = \"\",\n text_fg = Vec4(0,0,0,1),\n text_pos = (0,-0.025,0),\n text_scale = 0.08,\n pos = (-0.013, 0, 0.013),\n )\n if self.toon:\n self.textFrame['text'] = TTLocalizer.TownBattleChooseAvatarToonTitle\n else:\n self.textFrame['text'] = TTLocalizer.TownBattleChooseAvatarCogTitle\n \n self.avatarButtons = []\n for i in range(4):\n button = DirectButton(\n parent = self.frame,\n relief = None,\n image = (gui.find(\"**/PckMn_Arrow_Up\"),\n gui.find(\"**/PckMn_Arrow_Dn\"),\n gui.find(\"**/PckMn_Arrow_Rlvr\")),\n command = self.__handleAvatar,\n extraArgs = [i],\n )\n if self.toon:\n button.setScale(1,1,-1)\n button.setPos(0,0,-0.2)\n else:\n button.setScale(1,1,1)\n button.setPos(0,0,0.2)\n self.avatarButtons.append(button)\n \n self.backButton = DirectButton(\n parent = self.frame,\n relief = None,\n image = (gui.find(\"**/PckMn_BackBtn\"),\n gui.find(\"**/PckMn_BackBtn_Dn\"),\n gui.find(\"**/PckMn_BackBtn_Rlvr\")),\n pos = (-0.647, 0, 0.006),\n scale = 1.05,\n text = TTLocalizer.TownBattleChooseAvatarBack,\n text_scale = 0.05,\n text_pos = (0.01,-0.012),\n text_fg = Vec4(0,0,0.8,1),\n command = self.__handleBack,\n )\n\n gui.removeNode()\n\n return\n\n def unload(self):\n \"\"\"unload(self)\n \"\"\"\n self.frame.destroy()\n del self.frame\n del self.statusFrame\n del self.textFrame\n del self.avatarButtons\n del self.backButton\n return\n\n def enter(self, numAvatars, localNum=None, luredIndices=None, trappedIndices=None, track=None):\n # Show the panel\n self.frame.show()\n # Place the buttons\n # Suits that are lured should not be available to select for\n # certain attacks\n invalidTargets = []\n if not self.toon:\n if (len(luredIndices) > 0):\n # You can't place a trap in front of a suit that is already lured\n if (track == BattleBase.TRAP or track == BattleBase.LURE): \n invalidTargets += luredIndices\n if (len(trappedIndices) > 0):\n # You can't place a trap in front of a suit that is already trapped\n if (track == BattleBase.TRAP):\n invalidTargets += trappedIndices\n self.__placeButtons(numAvatars, invalidTargets, localNum)\n # Force chat balloons to the margins while this is up.\n # NametagGlobals.setOnscreenChatForced(1)\n return\n\n def exit(self):\n # Hide the panel\n self.frame.hide()\n # NametagGlobals.setOnscreenChatForced(0)\n return\n\n def __handleBack(self):\n doneStatus = {'mode' : 'Back'}\n messenger.send(self.doneEvent, [doneStatus])\n return\n \n def __handleAvatar(self, avatar):\n doneStatus = {'mode' : 'Avatar',\n 'avatar' : avatar}\n messenger.send(self.doneEvent, [doneStatus])\n return\n\n def adjustCogs(self, numAvatars, luredIndices, trappedIndices, track):\n # Suits that are lured should not be available to select for\n # certain attacks\n invalidTargets = []\n if (len(luredIndices) > 0):\n # You can't place a trap in front of a suit that is already lured\n if (track == BattleBase.TRAP or track == BattleBase.LURE): \n invalidTargets += luredIndices\n if (len(trappedIndices) > 0):\n # You can't place a trap in front of a suit that is already trapped\n if (track == BattleBase.TRAP):\n invalidTargets += trappedIndices\n self.__placeButtons(numAvatars, invalidTargets, None)\n return\n\n def adjustToons(self, numToons, localNum):\n self.__placeButtons(numToons, [], localNum)\n return\n\n def __placeButtons(self, numAvatars, invalidTargets, localNum):\n # Place the buttons. NOTE: Remember, from the toons point of view\n # the avatars are numbered from right to left.\n for i in range(4):\n # Only show the button if this avatar is in the battle\n # and he is not in the invalidTargets list\n if ((numAvatars > i) and (i not in invalidTargets) and (i != localNum)):\n self.avatarButtons[i].show()\n else:\n self.avatarButtons[i].hide()\n\n # Evenly positions the buttons on the bar\n if numAvatars == 1:\n self.avatarButtons[0].setX(0)\n elif numAvatars == 2:\n self.avatarButtons[0].setX(0.2)\n self.avatarButtons[1].setX(-0.2)\n elif numAvatars == 3:\n self.avatarButtons[0].setX(0.4)\n self.avatarButtons[1].setX(0.0)\n self.avatarButtons[2].setX(-0.4)\n elif numAvatars == 4:\n self.avatarButtons[0].setX(0.6)\n self.avatarButtons[1].setX(0.2)\n self.avatarButtons[2].setX(-0.2)\n self.avatarButtons[3].setX(-0.6)\n else:\n self.notify.error(\"Invalid number of avatars: %s\" % numAvatars)\n\n return None\n\n \n","sub_path":"toontown/src/town/TownBattleChooseAvatarPanel.py","file_name":"TownBattleChooseAvatarPanel.py","file_ext":"py","file_size_in_byte":7133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"451696598","text":"\nfrom coqr.parsing.RParser import RParser\n\nfrom coqr.parsing.RListener import RListener\n\n\nclass LineExpListener(RListener):\n\n def __init__(self, stream) -> None:\n super().__init__()\n self.exps = []\n self.token_stream = stream\n\n def enterProg(self, ctx: RParser.ProgContext):\n for expr in ctx.expr():\n start_index = expr.start.tokenIndex\n stop_index = expr.stop.tokenIndex\n # In order to get spaces and newlines correctly\n text = self.token_stream.getText(interval=(start_index, stop_index))\n self.exps.append((expr.start.line, text))\n","sub_path":"coqr/parsing/LineExpListener.py","file_name":"LineExpListener.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"512213615","text":"# Michael J Seth - A History of Korea: From Antiquity to the Present\n# Henry J. Amen - Korean for Beginners: Mastering Conversational Korean\n# Suki Kim - Without You, There is No Us\n\nclass Book:\n # constructor method:\n def __init__(self, name, copies=50):\n self.name = name\n self.copies = copies\n\n # behavior methods:\n def increase_copies(self, how_many):\n self.copies += how_many\n\n def decrease_copies(self, how_many):\n self.copies -= how_many\n\n\nhistory_of_korea = Book('A History of Korea: From Antiquity to the Present', 30)\nkorean_for_beginners = Book('Korean for Beginners: Mastering Conversational Korean')\nwithout_you = Book('Without You, There is No Us', 60)\n\nprint(history_of_korea.name, history_of_korea.copies)\nprint(korean_for_beginners.name, korean_for_beginners.copies)\nprint(without_you.name, without_you.copies)\n\nkorean_for_beginners.increase_copies(10)\nwithout_you.decrease_copies(20)\n\nprint(history_of_korea.name, history_of_korea.copies)\nprint(korean_for_beginners.name, korean_for_beginners.copies)\nprint(without_you.name, without_you.copies)\n\n\n\n","sub_path":"Python-by-in28minutes/02-OOP-project/book.py","file_name":"book.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"69479969","text":"import time\nimport threading\nimport platform\nimport datetime\nimport os\nimport sys\n\nsys.path.insert(0,\"../\")\n\nfrom tqsdk import TqApi, TqAccount\n\nif platform.system() == \"Linux\":\n import readline\n\ndef cls():\n if platform.system() == \"Linux\":\n print(\"\\033[2J\")\n else:\n os.system(\"cls\")\n\naccount = \"432\"\npassword = \"234\"\n\n#if len(sys.argv) >= 3:\n# account = sys.argv[1]\n# password = sys.argv[2]\n#else:\n# import login\n# account = login.account\n# password = login.password\n\napi = TqApi(TqAccount(account, password))\n\nl = []\nmquote = {}\nmposition = {}\nschdules = []\n\ntoday = datetime.date.today()\ncurrent_year = today.year\ncurrent_month = today.month\nm2name = {}\nmonth2long = {}\n\nfor j in range(current_month,current_month+12):\n i = j\n if i > 12:\n i = i - 12\n month = \"{0:02d}\".format(i)\n name = \"DCE.jd\" + str(current_year-2000) + month\n month2long[month] = str(current_year-2000)+month\n quote = api.get_quote(name)\n if quote.expired == True:\n name = \"DCE.jd\" + str(current_year-1999) + \"{0:02d}\".format(i)\n quote = api.get_quote(name)\n month2long[month] = str(current_year-1999)+month\n mquote[month] = quote\n position = api.get_position(name)\n mposition[month] = position\n l.append(month)\n m2name[month] = name\n\ndef ask_price(quote):\n try:\n return int(quote.ask_price1)\n except:\n return int(quote.upper_limit)\n\ndef bid_price(quote):\n try:\n return int(quote.bid_price1)\n except:\n return int(quote.lower_limit)\n\ndef print_tl_price(name1,name2):\n price1 = str(ask_price(mquote[name1]) - bid_price(mquote[name2]))\n price2 = str(bid_price(mquote[name1]) - ask_price(mquote[name2]))\n print(name1+\"-\"+name2+\"\\t\"+price2+\"\\t\"+price1)\n\ndef show():\n print(\"==============show==============\")\n for i in l:\n quote = mquote[i]\n print(i,\"\\t\",bid_price(quote),\"\\t\",ask_price(quote),\"\\t\",quote.highest,\"\\t\",quote.lowest,\"\\t\",quote.open_interest-quote.pre_open_interest)\n print(\"\")\n print_tl_price(\"04\",\"05\")\n print_tl_price(\"05\",\"06\")\n print_tl_price(\"05\",\"07\")\n print_tl_price(\"06\",\"07\")\n print_tl_price(\"06\",\"08\")\n print_tl_price(\"07\",\"08\")\n print_tl_price(\"08\",\"09\")\n print_tl_price(\"09\",\"10\")\n print_tl_price(\"09\",\"01\")\n\ndef help():\n print(\"============help================\")\n print(\"help\")\n print(\"show\")\n print(\"position\")\n print(\"order\")\n print(\"kd 09 1 4100\")\n print(\"kk 05 1 3100\")\n print(\"pd 09 1 4300\")\n print(\"pk 05 1 2800\")\n print(\"zt 09 01 1\")\n print(\"pzt 09 01 1\")\n print(\"ft 05 06 1\")\n print(\"pft 05 06 1\")\n print(\"auto zt 07 08 -700 -650 1\")\n print(\"auto ft 12 01 0 200 1\")\n print(\"auto kd 09 4100 4300 1\")\n print(\"auto kk 09 4300 4100 1\")\n print(\"auto show\")\n print(\"cancel order_id(get from order)\")\n print(\"\")\n\ndef position():\n print(\"============position================\")\n for i in l:\n p = mposition[i]\n if p.pos_long > 0 or p.pos_short > 0:\n print(i,\"long:\",p.pos_long,\"\\t\",p.open_price_long,\"\\t short:\",p.pos_short,\"\\t\",p.open_price_short)\n\norder_cache = []\ndef order():\n print(\"============order================\")\n order_cache.clear()\n orders = api.get_order()\n for name in orders:\n o = api.get_order(name)\n# print(o)\n if o.status == \"ALIVE\":\n print(len(order_cache)+1,o.order_id,o.instrument_id,o.direction,o.offset,o.limit_price,o.volume_orign,o.volume_left)\n order_cache.append(o.order_id)\n\ndef insert_order(month,direction,offset,volume,price=None):\n print(\"============insert_order================\")\n if month in m2name:\n symbol = m2name[month]\n else:\n ss = month.split(\"&\")\n symbol = \"DCE.SP jd\" + month2long[ss[0]] + \"&jd\" + month2long[ss[1]]\n if price is None:\n return api.insert_order(symbol, direction=direction.upper(), offset=offset.upper(), volume=volume)\n return api.insert_order(symbol, direction=direction.upper(), offset=offset.upper(), volume=volume,limit_price=price)\n\ndef zt(month1,month2,volume):\n order1 = api.insert_order(symbol=m2name[month1], direction=\"BUY\", offset=\"OPEN\", volume=volume)\n order2 = api.insert_order(symbol=m2name[month2], direction=\"SELL\", offset=\"OPEN\", volume=volume)\n return (order1,order2)\n\ndef pzt(month1,month2,volume):\n order1 = api.insert_order(symbol=m2name[month1], direction=\"SELL\",offset=\"CLOSE\", volume=volume)\n order2 = api.insert_order(symbol=m2name[month2], direction=\"BUY\", offset=\"CLOSE\", volume=volume)\n return (order1,order2)\n\ndef ft(month1,month2,volume):\n order1 = api.insert_order(symbol=m2name[month1], direction=\"SELL\", offset=\"OPEN\", volume=volume)\n order2 = api.insert_order(symbol=m2name[month2], direction=\"BUY\", offset=\"OPEN\", volume=volume)\n return (order1,order2)\n\ndef pft(month1,month2,volume):\n order1 = api.insert_order(symbol=m2name[month1], direction=\"BUY\", offset=\"CLOSE\", volume=volume)\n order2 = api.insert_order(symbol=m2name[month2], direction=\"SELL\", offset=\"CLOSE\", volume=volume)\n return (order1,order2)\n\ndef cancel_order(id):\n print(\"============cancel_order================\")\n if len(id) <= 5:\n api.cancel_order(order_cache[int(id)-1])\n else:\n api.cancel_order(id)\n\ndef tl_auto(type, month1,month2,open_price,close_price,volume,max_times=1):\n schdules.append({\n \"type\" : type,\n \"name1\" : month1,\n \"name2\" : month2,\n \"open_price\" : open_price,\n \"close_price\" : close_price,\n \"volume\" : volume,\n \"status\" : \"ready\",\n \"times\" : 0,\n \"max_times\" : max_times\n })\n\ndef db_auto(type, month,open_price,close_price,volume,max_times=1):\n schdules.append({\n \"type\" : type,\n \"name\" : month,\n \"open_price\" : open_price,\n \"close_price\" : close_price,\n \"volume\" : volume,\n \"status\" : \"ready\",\n \"times\" : 0,\n \"max_times\" : max_times\n })\n\ndef show_auto():\n for s in schdules:\n print(\"---------------\")\n print(\"type:\",s[\"type\"])\n if \"name\" in s:\n print(\"name:\",s[\"name\"])\n else:\n print(\"name1:\",s[\"name1\"])\n print(\"name2:\",s[\"name2\"])\n print(\"open_price:\",s[\"open_price\"])\n print(\"close_price:\",s[\"close_price\"])\n print(\"volume:\",s[\"volume\"])\n print(\"status:\",s[\"status\"])\n if \"open_order1\" in s:\n print(\"open_order1:\",s[\"open_order1\"])\n if \"open_order2\" in s:\n print(\"open_order2:\",s[\"open_order2\"])\n if \"close_order1\" in s:\n print(\"close_order1:\",s[\"close_order1\"])\n if \"close_order2\" in s:\n print(\"close_order2:\",s[\"close_order2\"])\n\nclose = False\n\nclass WorkingThread(threading.Thread):\n def run(self):\n while True:\n api.wait_update()\n if close:\n api.close()\n break\n for v in schdules:\n if v[\"status\"] == \"ready\":\n if v[\"type\"] == \"zt\" and ask_price(mquote[v[\"name1\"]]) - bid_price(mquote[v[\"name2\"]]) <= v[\"open_price\"]:\n o = zt(v[\"name1\"],v[\"name2\"],v[\"volume\"])\n v[\"open_order1\"] = o[0]\n v[\"open_order2\"] = o[1]\n v[\"status\"] = \"opening\"\n \n if v[\"type\"] == \"ft\" and bid_price(mquote[v[\"name1\"]]) - ask_price(mquote[v[\"name2\"]]) >= v[\"open_price\"]:\n o = ft(v[\"name1\"],v[\"name2\"],v[\"volume\"])\n v[\"open_order1\"] = o[0]\n v[\"open_order2\"] = o[1]\n v[\"status\"] = \"opening\"\n\n if v[\"type\"] == \"kd\":\n o = insert_order(v[\"name\"],\"buy\",\"open\",v[\"volume\"],v[\"open_price\"])\n v[\"open_order1\"] = o\n v[\"status\"] = \"opening\"\n \n if v[\"type\"] == \"kk\":\n o = insert_order(v[\"name\"],\"sell\",\"open\",v[\"volume\"],v[\"open_price\"])\n v[\"open_order1\"] = o\n v[\"status\"] = \"opening\"\n\n elif v[\"status\"] == \"opening\":\n open_order1 = v[\"open_order1\"]\n if open_order1.volume_left > 0:\n continue\n if \"open_order2\" in v:\n open_order2 = v[\"open_order2\"]\n if open_order2.volume_left > 0:\n continue\n v[\"status\"] = \"opened\"\n elif v[\"status\"] == \"opened\":\n if v[\"type\"] == \"zt\" and bid_price(mquote[v[\"name1\"]]) - ask_price(mquote[v[\"name2\"]]) >= v[\"close_price\"]:\n o = pzt(v[\"name1\"],v[\"name2\"],v[\"volume\"])\n v[\"close_order1\"] = o[0]\n v[\"close_order2\"] = o[1]\n v[\"status\"] = \"closing\"\n\n if v[\"type\"] == \"ft\" and ask_price(mquote[v[\"name1\"]]) - bid_price(mquote[v[\"name2\"]]) <= v[\"close_price\"]:\n o = pft(v[\"name1\"],v[\"name2\"],v[\"volume\"])\n v[\"close_order1\"] = o[0]\n v[\"close_order2\"] = o[1]\n v[\"status\"] = \"closing\"\n if v[\"type\"] == \"kd\":\n o = insert_order(v[\"name\"],\"sell\",\"close\",v[\"volume\"],v[\"close_price\"])\n v[\"close_order1\"] = o\n v[\"status\"] = \"closing\"\n if v[\"type\"] == \"kk\":\n o = insert_order(v[\"name\"],\"buy\",\"close\",v[\"volume\"],v[\"close_price\"])\n v[\"close_order1\"] = o\n v[\"status\"] = \"closing\"\n elif v[\"status\"] == \"closing\":\n close_order1 = v[\"close_order1\"]\n if close_order1.volume_left > 0:\n continue\n if \"close_order2\" in v:\n close_order2 = v[\"close_order2\"]\n if close_order2.volume_left > 0:\n continue\n v [\"times\"] = v[\"times\"] + 1\n if v[\"times\"] < v[\"max_times\"]:\n v[\"status\"] = \"ready\"\n else:\n v[\"status\"] = \"done\"\n\nwt = WorkingThread()\nwt.start()\n\nhelp()\n\nwhile True:\n line = input(\"command:\")\n args = line.split(\" \")\n cmd = args[0]\n if cmd == \"help\" or cmd == \"h\":\n help()\n elif cmd == \"show\" or cmd == \"s\":\n show()\n elif cmd == \"position\" or cmd == \"p\":\n position()\n elif cmd == \"order\" or cmd == \"o\":\n order()\n elif cmd == \"kd\":\n if len(args) >= 4:\n insert_order(args[1],\"buy\",\"open\",int(args[2]),int(args[3]))\n else:\n insert_order(args[1],\"buy\",\"open\",int(args[2]))\n elif cmd == \"kk\":\n if len(args) >= 4:\n insert_order(args[1],\"sell\",\"open\",int(args[2]),int(args[3]))\n else:\n insert_order(args[1],\"sell\",\"open\",int(args[2]))\n elif cmd == \"pd\":\n if len(args) >= 4:\n insert_order(args[1],\"sell\",\"close\",int(args[2]),int(args[3]))\n else:\n insert_order(args[1],\"sell\",\"close\",int(args[2]))\n elif cmd == \"pk\":\n if len(args) >= 4:\n insert_order(args[1],\"buy\",\"close\",int(args[2]),int(args[3]))\n else:\n insert_order(args[1],\"buy\",\"close\",int(args[2])) \n elif cmd == \"zt\":\n zt(args[1],args[2],int(args[3]))\n elif cmd == \"pzt\":\n pzt(args[1],args[2],int(args[3]))\n elif cmd == \"ft\":\n ft(args[1],args[2],int(args[3]))\n elif cmd == \"pft\":\n pft(args[1],args[2],int(args[3]))\n elif cmd == \"cancel\" or cmd == \"c\":\n cancel_order(str(line[len(cmd)+1:]))\n elif cmd == \"auto\":\n if args[1] == \"zt\":\n tl_auto(\"zt\",args[2],args[3],int(args[4]),int(args[5]),int(args[6]))\n elif args[1] == \"ft\":\n tl_auto(\"ft\",args[2],args[3],int(args[4]),int(args[5]),int(args[6]))\n elif args[1] == \"kd\":\n if len(args) >= 7:\n db_auto(\"kd\",args[2],int(args[3]),int(args[4]),int(args[5]),int(args[6]))\n else:\n db_auto(\"kd\",args[2],int(args[3]),int(args[4]),int(args[5]))\n elif args[1] == \"kk\":\n if len(args) >= 7:\n db_auto(\"kk\",args[2],int(args[3]),int(args[4]),int(args[5]),int(args[6]))\n else:\n db_auto(\"kk\",args[2],int(args[3]),int(args[4]),int(args[5]))\n elif args[1] == \"show\":\n show_auto()\n elif cmd == \"cls\":\n cls()\n elif cmd == \"quit\":\n close = True\n break\n\ntime.sleep(1)\n\n","sub_path":"python/jd_console/console.py","file_name":"console.py","file_ext":"py","file_size_in_byte":12791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"599764503","text":"import idautils\nimport idc\nimport ida_search\n\ndef make_date_ref():\n ea = 0x9561C\n max_ea = ida_ida.inf_get_max_ea()\n min_ea = ida_ida.inf_get_min_ea()\n\n while True:\n ea = ida_search.find_unknown(ea, idc.SEARCH_DOWN | idc.SEARCH_NEXT)\n if ea > max_ea:\n break\n size = idc.get_item_size(ea)\n print(hex(ea))\n\n val = idc.get_wide_dword(ea)\n # if 0xfff38 < val < 0x188544 or 0x1f000000 < val < 0x1ffa3fd9 or 0x20000000 < val < 0x2001ffff:\n # idc.OpOff(ea, 0, 0)\n if min_ea < val < max_ea:\n idc.op_plain_offset(ea,0,0)\n\n\n\n\nif __name__ == '__main__':\n make_date_ref()","sub_path":"script/do_off.py","file_name":"do_off.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"253162858","text":"#!/usr/bin/env python\nimport pprint\nimport pyeapi\n\n\ndef main():\n\n \n pynet_sw4 = pyeapi.connect_to(\"pynet-sw4\")\n show_int = pynet_sw4.enable(\"show interfaces\")\n\n pprint.pprint(show_int)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"week7/w7e1.py","file_name":"w7e1.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"130816175","text":"from sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.preprocessing import PolynomialFeatures\r\nimport pickle\r\nimport numpy as np\r\nimport dataProc\r\n\r\n\r\ndef RFClassifier(X_train, y_train, X_test, y_test):\r\n num_feat = len(X_train[0])\r\n num_tree = [x for x in range(10, 1010, 10)]\r\n\r\n cost = 0.0\r\n bestDFeatTrees = []\r\n fp = './output/RF_test.txt'\r\n f = open(fp, 'w')\r\n f.write('d\\tfeatures\\ttrees\\taccu\\n')\r\n for d in range(3, 4):\r\n poly = PolynomialFeatures(d)\r\n X_train_poly = poly.fit_transform(X_train)\r\n scaled_X_train, scaler = dataProc.standardize_X(X_train_poly)\r\n X_test_poly = poly.fit_transform(X_test)\r\n scaled_X_test = scaler.transform(X_test_poly)\r\n\r\n for feat in range(1, num_feat+1):\r\n for tree in num_tree:\r\n clf = RandomForestClassifier(n_estimators=tree, max_features=feat)\r\n clf = clf.fit(scaled_X_train, y_train)\r\n y_predict = clf.predict(scaled_X_test)\r\n\r\n y_test = np.array(y_test)\r\n\r\n sample_num = 0\r\n accu = 0.0\r\n\r\n for index, i in enumerate(y_test):\r\n sample_num += 1\r\n if y_test[index] == y_predict[index]:\r\n accu += 1\r\n\r\n accu = accu/sample_num\r\n\r\n print(\"(d = {0}, features = {1}, trees = {2} is {3})\".format(d, feat, tree, accu))\r\n f.write(str(d)+'\\t'+str(feat)+'\\t'+str(tree)+'\\t'+str(accu)+'\\n')\r\n if accu > cost:\r\n bestDFeatTrees = [d, feat, tree]\r\n cost = accu\r\n\r\n print(bestDFeatTrees, cost)\r\n f.flush()\r\n f.close()\r\n\r\n'''\r\nfilepath = './mydata/FNNR/FNNR_trainingdata.txt'\r\nX, y = dataProc.readdata(filepath, \"GRID_CODE\")\r\n\r\nX_train, X_test, y_train, y_test = dataProc.split_data(X, y)\r\n'''\r\n\r\nX_train = pickle.load(open('X_train.p'))\r\nX_test = pickle.load(open('X_test.p'))\r\ny_train = pickle.load(open('y_train.p'))\r\ny_test = pickle.load(open('y_test.p'))\r\nRFClassifier(X_train, y_train, X_test, y_test)","sub_path":"RF.py","file_name":"RF.py","file_ext":"py","file_size_in_byte":2099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"533780302","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 23 13:36:28 2017\n\n@author: owen\n\"\"\"\n\n# Given a non-empty array of integers, return the k most frequent elements.\n\n # You may assume k is always valid, 1 ≤ k ≤ number of unique elements.\n # Your algorithm's time complexity must be better than O(n log n), where n is the array's size.\n\n# 没说打平手怎么办\n\n# min heap, time O((n + k) log k), space O(k)\n# max heap, time O((n + k) log n), space O(n)\n# one cnt counter, one freq counter, sort freq counter, time O(n log n), space O(n)\n# use bucket record freq, find top k from right to left, time O(n), space O(n)\n\n\n# import heapq\n# import collections\nclass Solution:\n def topKFrequent(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: List[int]\n \"\"\"\n # min heap, time O(n log k + k log k), space O(k)\n cnt = collections.Counter(nums)\n hp = []\n for num, freq in cnt.items():\n heapq.heappush(hp, (freq, num))\n if len(hp) > k:\n heapq.heappop(hp)\n \n hp.sort(key = lambda x: -x[0])\n return [num for __, num in hp]\n\n\nclass Solution:\n def topKFrequent(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: List[int]\n \"\"\"\n # max heap, time O((n + k) log n), space O(n)\n cnt = collections.Counter(nums)\n hp = []\n for num, freq in cnt.items():\n heapq.heappush(hp, (-freq, num))\n \n res = []\n for __ in range(k):\n __, num = heapq.heappop(hp)\n res.append(num)\n \n return res\n\n\nclass Solution:\n def topKFrequent(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: List[int]\n \"\"\"\n # two counter + sort, time O(n log n), space O(n),实际用的空间不大\n cnt = collections.Counter(nums) # num -> frequency\n freq = collections.defaultdict(list) # freq -> num list\n for num, f in cnt.items():\n freq[f].append(num)\n \n res = []\n most_freq = sorted(freq.keys(), reverse = True)\n for f in most_freq:\n res.extend(freq[f])\n if len(res) >= k:\n break\n \n return res[:k]\n\n\nclass Solution:\n def topKFrequent(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: List[int]\n \"\"\"\n # bucket sort, time O(n), space O(n),空间大\n cnt = collections.Counter(nums) # num -> frequency\n n = len(nums)\n freq = [[] for __ in range(n + 1)] # freq -> num list\n for num, f in cnt.items():\n freq[f].append(num)\n \n res = []\n for f in range(n, -1, -1): # traverse from the end, record the most frequenct\n res.extend(freq[f]) # if freq[f] is empty, res is unchanged\n if len(res) >= k:\n break\n \n return res[:k]\n\n\n#import collections\n#class Solution(object):\n# def topKFrequent(self, nums, k):\n# \"\"\"\n# :type nums: List[int]\n# :type k: int\n# :rtype: List[int]\n# \"\"\"\n# # Heap+hash, time O(n log k)\n# topK=collections.Counter(nums).most_common(k)\n# return [k[0] for k in topK]\n\n \n\nif __name__==\"__main__\":\n nums=[4,5,4,5,4,5,5,6,7,7,6,6,8]\n print(Solution().topKFrequent(nums, 3))","sub_path":"347. Top K Frequent Elements.py","file_name":"347. Top K Frequent Elements.py","file_ext":"py","file_size_in_byte":3507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"610476354","text":"from ipaddress import IPv4Address, IPv4Network\n\nfrom flask import request, _request_ctx_stack, current_app, g\nfrom notifications_python_client.authentication import decode_jwt_token, get_token_issuer\nfrom notifications_python_client.errors import TokenDecodeError, TokenExpiredError, TokenIssuerError\nfrom sqlalchemy.exc import DataError\nfrom sqlalchemy.orm.exc import NoResultFound\n\nfrom app.dao.services_dao import dao_fetch_service_by_id_with_api_keys\nfrom flask import jsonify\n\n\nclass AuthError(Exception):\n def __init__(self, message, code):\n self.message = {\"token\": [message]}\n self.short_message = message\n self.code = code\n\n def to_dict_v2(self):\n return {\n 'status_code': self.code,\n \"errors\": [\n {\n \"error\": \"AuthError\",\n \"message\": self.short_message\n }\n ]\n }\n\n\ndef get_auth_token(req):\n auth_header = req.headers.get('Authorization', None)\n if not auth_header:\n raise AuthError('Unauthorized, authentication token must be provided', 401)\n\n auth_scheme = auth_header[:7].title()\n\n if auth_scheme != 'Bearer ':\n raise AuthError('Unauthorized, authentication bearer scheme must be used', 401)\n\n return auth_header[7:]\n\n\ndef requires_no_auth():\n pass\n\n\ndef check_route_secret():\n # Check route of inbound sms (Experimental)\n # Custom header for route security\n auth_error_msg = ''\n if request.headers.get(\"X-Custom-Forwarder\"):\n route_secret_key = request.headers.get(\"X-Custom-Forwarder\")\n\n if route_secret_key is None:\n # Not blocking at the moment\n # raise AuthError('invalid secret key', 403)\n auth_error_msg = auth_error_msg + 'invalid secret key, '\n else:\n\n key_1 = current_app.config.get('ROUTE_SECRET_KEY_1')\n key_2 = current_app.config.get('ROUTE_SECRET_KEY_2')\n\n if key_1 == '' and key_2 == '':\n # Not blocking at the moment\n # raise AuthError('X-Custom-Forwarder, no secret was set on server', 503)\n auth_error_msg = auth_error_msg + 'no secret was set on server, '\n else:\n\n key_used = None\n route_allowed = False\n if route_secret_key == key_1:\n key_used = 1\n route_allowed = True\n elif route_secret_key == key_2:\n key_used = 2\n route_allowed = True\n\n if not key_used:\n # Not blocking at the moment\n # raise AuthError('X-Custom-Forwarder, wrong secret', 403)\n auth_error_msg = auth_error_msg + 'wrong secret'\n\n current_app.logger.info({\n 'message': 'X-Custom-Forwarder',\n 'log_contents': {\n 'passed': route_allowed,\n 'key_used': key_used,\n 'error': auth_error_msg\n }\n })\n return jsonify(key_used=key_used), 200\n\n\ndef restrict_ip_sms():\n check_route_secret()\n\n # Check IP of SMS providers\n if request.headers.get(\"X-Forwarded-For\"):\n # X-Forwarded-For looks like \"203.0.113.195, 70.41.3.18, 150.172.238.178\"\n # Counting backwards and look at the IP at the 3rd last hop - hence, hop(end-3)\n ip_route = request.headers.get(\"X-Forwarded-For\")\n ip_list = ip_route.split(',')\n\n current_app.logger.info(\"Inbound sms ip route list {}\"\n .format(ip_route))\n if len(ip_list) >= 3:\n inbound_ip = IPv4Address(ip_list[len(ip_list) - 3].strip())\n\n # IP whitelist\n allowed_ips = current_app.config.get('SMS_INBOUND_WHITELIST')\n\n allowed = any(\n inbound_ip in IPv4Network(allowed_ip)\n for allowed_ip in allowed_ips\n )\n\n current_app.logger.info({\n 'message': 'Inbound sms ip address',\n 'log_contents': {\n 'passed': allowed,\n 'ip_address': inbound_ip\n }\n })\n\n if allowed:\n return\n else:\n raise AuthError('Unknown source IP address from the SMS provider', 403)\n\n raise AuthError('Traffic from unknown source or route', 403)\n\n\ndef requires_admin_auth():\n auth_token = get_auth_token(request)\n client = __get_token_issuer(auth_token)\n\n if client == current_app.config.get('ADMIN_CLIENT_USER_NAME'):\n g.service_id = current_app.config.get('ADMIN_CLIENT_USER_NAME')\n return handle_admin_key(auth_token, current_app.config.get('ADMIN_CLIENT_SECRET'))\n else:\n raise AuthError('Unauthorized, admin authentication token required', 401)\n\n\ndef requires_auth():\n auth_token = get_auth_token(request)\n client = __get_token_issuer(auth_token)\n\n try:\n service = dao_fetch_service_by_id_with_api_keys(client)\n except DataError:\n raise AuthError(\"Invalid token: service id is not the right data type\", 403)\n except NoResultFound:\n raise AuthError(\"Invalid token: service not found\", 403)\n\n if not service.api_keys:\n raise AuthError(\"Invalid token: service has no API keys\", 403)\n\n if not service.active:\n raise AuthError(\"Invalid token: service is archived\", 403)\n\n for api_key in service.api_keys:\n try:\n get_decode_errors(auth_token, api_key.secret)\n except TokenDecodeError:\n continue\n\n if api_key.expiry_date:\n raise AuthError(\"Invalid token: API key revoked\", 403)\n\n g.service_id = api_key.service_id\n _request_ctx_stack.top.authenticated_service = service\n _request_ctx_stack.top.api_user = api_key\n\n return\n else:\n # service has API keys, but none matching the one the user provided\n raise AuthError(\"Invalid token: signature, api token is not valid\", 403)\n\n\ndef __get_token_issuer(auth_token):\n try:\n client = get_token_issuer(auth_token)\n except TokenIssuerError:\n raise AuthError(\"Invalid token: iss field not provided\", 403)\n except TokenDecodeError as e:\n raise AuthError(\"Invalid token: signature, api token is not valid\", 403)\n return client\n\n\ndef handle_admin_key(auth_token, secret):\n try:\n get_decode_errors(auth_token, secret)\n return\n except TokenDecodeError as e:\n raise AuthError(\"Invalid token: signature, api token is not valid\", 403)\n\n\ndef get_decode_errors(auth_token, unsigned_secret):\n try:\n decode_jwt_token(auth_token, unsigned_secret)\n except TokenExpiredError:\n raise AuthError(\"Invalid token: expired, check that your system clock is accurate\", 403)\n","sub_path":"app/authentication/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":6800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"311251725","text":"from __future__ import (absolute_import, division, print_function)\n\nfrom ansible.errors import AnsibleError, AnsibleParserError\nfrom ansible.module_utils._text import to_native\nfrom ansible.plugins.action import ActionBase\nimport re\n\n\nDBUS_RE = re.compile('failed.*d-?bus', re.I|re.U|re.M)\n\n__metaclass__ = type\n\n\nclass ActionModule(ActionBase):\n\n TRANSFERS_FILES = True\n\n UNUSED_PARAMS = {\n 'systemd': ['pattern', 'runlevel', 'sleep', 'arguments', 'args'],\n 'service': ['daemon_reload'],\n 'upstart': ['daemon_reload'],\n }\n\n def run(self, tmp=None, task_vars=None, *args, **kw):\n '''.'''\n if task_vars is None:\n task_vars = dict()\n\n result = super(ActionModule, self).run(tmp, task_vars)\n\n module = self._task.args.get('use', 'auto').lower()\n\n if module == 'auto':\n try:\n if self._task.delegate_to: # if we delegate, we should use delegated host's facts\n module = self._templar.template(\"{{hostvars['%s']['ansible_service_mgr']}}\" % self._task.delegate_to)\n else:\n module = self._templar.template('{{ansible_service_mgr}}')\n except:\n pass # could not get it from template!\n\n if module == 'auto':\n facts = self._execute_module(module_name='setup', module_args=dict(gather_subset='!all', filter='ansible_service_mgr'), task_vars=task_vars)\n self._display.debug(\"Facts %s\" % facts)\n if 'ansible_facts' in facts and 'ansible_service_mgr' in facts['ansible_facts']:\n module = facts['ansible_facts']['ansible_service_mgr']\n\n if not module or module == 'auto' or module not in self._shared_loader_obj.module_loader:\n module = 'service'\n\n if module != 'auto':\n new_module_args = self._task.args.copy()\n if module == 'systemd':\n margs = (self._task,\n self._connection,\n self._play_context,\n self._loader,\n self._templar,\n self._shared_loader_obj)\n self._ah = self._shared_loader_obj.action_loader.get(\n 'cops_actionhelper', *margs)\n ret = self._ah.exec_command(\n 'systemctl --no-pager is-system-running')\n # if connection to dbus is possible, systemd is running somehow\n if DBUS_RE.search(ret['stderr']):\n module = 'cops_systemd'\n # run the 'service' module\n if 'use' in new_module_args:\n del new_module_args['use']\n\n # for backwards compatibility\n if 'state' in new_module_args and new_module_args['state'] == 'running':\n new_module_args['state'] = 'started'\n\n if module in self.UNUSED_PARAMS:\n for unused in self.UNUSED_PARAMS[module]:\n if unused in new_module_args:\n del new_module_args[unused]\n self._display.warning('Ignoring \"%s\" as it is not used in \"%s\"' % (unused, module))\n\n self._display.vvvv(\"Running %s\" % module)\n result.update(self._execute_module(module_name=module, module_args=new_module_args, task_vars=task_vars))\n else:\n result['failed'] = True\n result['msg'] = 'Could not detect which service manager to use. Try gathering facts or setting the \"use\" option.'\n return result\n","sub_path":"action_plugins/cops_service.py","file_name":"cops_service.py","file_ext":"py","file_size_in_byte":3549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"570772572","text":"#!/usr/bin/env python3\nimport numpy as np\nimport sys\n\ndef read_result(ifn):\n with open(ifn,'r') as f:\n pred,true = [],[]\n for line in f.readlines():\n line = line.strip()\n tp = line.split('\\t')[0]\n tt = line.split('\\t')[1]\n tpred = tp.split(',')\n ttrue = tt.split(',')\n for i in range(len(tpred)):\n tpred[i] = float(tpred[i])\n ttrue[i] = float(ttrue[i])\n pred.append(tpred)\n true.append(ttrue)\n pred1 = np.array(pred)\n true1 = np.array(true)\n return(pred1,true1)\n\ndef evalres(pred,true,ofn1,ofn2,ofn3,ofn4,ofn5,ofn6):\n sn = len(pred)\n pred_drug, pred_manu,pred_batch = pred[:,0:4], pred[:,4:6], pred[:,6:9]\n true_drug, true_manu,true_batch = true[:,0:4], true[:,4:6], true[:,6:9]\n\n #drug\n fpr_drug,tpr_drug = [],[]\n f3 = open(ofn3,'a')\n f3.write('threshold' + '\\t' + 'accuracy' + '\\t' + 'precision' + '\\t' + 'recall' + '\\t' + 'f1-score' + '\\n')\n for n in range(102):\n th = n/100\n TTP,TTN,TFP,TFN = 0,0,0,0\n for i in range(sn):\n TP,TN,FP,FN = 0,0,0,0\n for j in range(len(pred_drug[i])):\n if(pred_drug[i][j] >= th and true_drug[i][j] == 1):\n TP += 1\n if(pred_drug[i][j] < th and true_drug[i][j] == 1):\n FN += 1\n if(pred_drug[i][j] >= th and true_drug[i][j] == 0):\n FP += 1\n if(pred_drug[i][j] < th and true_drug[i][j] == 0):\n TN += 1\n TTP += TP\n TTN += TN\n TFP += FP\n TFN += FN\n TPR = TTP/sn\n FPR = TFP/(3*sn)\n fpr_drug.append(FPR)\n tpr_drug.append(TPR)\n accuracy = (TTP + TTN)/(TTP + TTN + TFP + TFN)\n pr = precision = TTP/(TTP+TFP+0.00001)\n rc = recall = TTP/(TTP+TFN)\n f1score = 2*pr*rc/(pr + rc+0.00001)\n f3.write(str(th) + '\\t' + str(accuracy) + '\\t' + str(pr) + '\\t' + str(rc) + '\\t' + str(f1score) + '\\n')\n f3.close()\n f1 = open(ofn1,'a')\n for i in range(len(fpr_drug)):\n f1.write(str(fpr_drug[i]) + '\\t' + str(tpr_drug[i]) + '\\n')\n f1.close()\n\n #manu\n fpr_manu,tpr_manu = [],[]\n f4 = open(ofn4,'a')\n f4.write('threshold' + '\\t' + 'accuracy' + '\\t' + 'precision' + '\\t' + 'recall' + '\\t' + 'f1-score' + '\\n')\n\n for n in range(102):\n th = n/100\n TTP,TTN,TFP,TFN = 0,0,0,0\n for i in range(sn):\n TP,TN,FP,FN = 0,0,0,0\n for j in range(len(pred_manu[i])):\n if(pred_manu[i][j] >= th and true_manu[i][j] == 1):\n TP += 1\n if(pred_manu[i][j] < th and true_manu[i][j] == 1):\n FN += 1\n if(pred_manu[i][j] >= th and true_manu[i][j] == 0):\n FP += 1\n if(pred_manu[i][j] < th and true_manu[i][j] == 0):\n TN += 1\n TTP += TP\n TTN += TN\n TFP += FP\n TFN += FN\n TPR = TTP/sn\n FPR = TFP/sn\n fpr_manu.append(FPR)\n tpr_manu.append(TPR)\n accuracy = (TTP + TTN)/(TTP + TTN + TFP + TFN)\n pr = precision = TTP/(TTP+TFP+0.00001)\n rc = recall = TTP/(TTP+TFN)\n f1score = 2*pr*rc/(pr + rc+0.00001)\n f4.write(str(th) + '\\t' + str(accuracy) + '\\t' + str(pr) + '\\t' + str(rc) + '\\t' + str(f1score) + '\\n')\n f4.close()\n\n f2 = open(ofn2,'a')\n for i in range(len(fpr_manu)):\n f2.write(str(fpr_manu[i]) + '\\t' + str(tpr_manu[i]) + '\\n')\n f2.close()\n\n #batch\n fpr_batch,tpr_batch = [],[]\n f6 = open(ofn6,'a')\n f6.write('threshold' + '\\t' + 'accuracy' + '\\t' + 'precision' + '\\t' + 'recall' + '\\t' + 'f1-score' + '\\n')\n\n for n in range(102):\n th = n/100\n TTP,TTN,TFP,TFN = 0,0,0,0\n for i in range(sn):\n TP,TN,FP,FN = 0,0,0,0\n for j in range(len(pred_batch[i])):\n if(pred_batch[i][j] >= th and true_batch[i][j] == 1):\n TP += 1\n if(pred_batch[i][j] < th and true_batch[i][j] == 1):\n FN += 1\n if(pred_batch[i][j] >= th and true_batch[i][j] == 0):\n FP += 1\n if(pred_batch[i][j] < th and true_batch[i][j] == 0):\n TN += 1\n TTP += TP\n TTN += TN\n TFP += FP\n TFN += FN\n TPR = TTP/sn\n FPR = TFP/(2*sn)\n fpr_batch.append(FPR)\n tpr_batch.append(TPR)\n accuracy = (TTP + TTN)/(TTP + TTN + TFP + TFN)\n pr = precision = TTP/(TTP+TFP+0.00001)\n rc = recall = TTP/(TTP+TFN)\n f1score = 2*pr*rc/(pr + rc+0.00001)\n f6.write(str(th) + '\\t' + str(accuracy) + '\\t' + str(pr) + '\\t' + str(rc) + '\\t' + str(f1score) + '\\n')\n f6.close()\n\n f5 = open(ofn5,'a')\n for i in range(len(fpr_batch)):\n f5.write(str(fpr_batch[i]) + '\\t' + str(tpr_batch[i]) + '\\n')\n f5.close()\n\n\ndef main():\n pred,true = read_result(sys.argv[1])\n evalres(pred,true,sys.argv[2],sys.argv[3],sys.argv[4],sys.argv[5],sys.argv[6],sys.argv[7])\n \nmain()\n","sub_path":"scripts/evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":4558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"243695325","text":"# coding: utf-8\n\nclass Tasks():\n def __init__(self, vk, sql):\n self.vk = vk\n self.sql = sql\n \n def show(self, user_id, task_id, mode):\n task = self.sql.fetchOne('SELECT * FROM rus WHERE id = %d' % task_id)\n text = ''\n \n if mode == 2 and task_id == 81:\n text += 'Вы начали режим РТ!\\nЧто бы выйти, напишите \"стоп\".\\n\\n'\n \n text += '*id0(%s) (%d). %s\\n\\n' % (task[1],task[0],task[2])\n \n n = 3\n \n if task[4]:\n for i in range(5):\n if n == 7: text += '%d) %s.\\n' % (i+1,task[n])\n else: text += '%d) %s;\\n' % (i+1,task[n])\n n += 1\n else:\n text += '%s.\\n' % task[3]\n \n if not mode == 5:\n text += '\\nОтвет (цифры, через запятую):'\n self.sql.ex('UPDATE users SET `tmp_test` = \\'%d\\', `tmp_type` = \\'%s\\', `tmp_cor` = \\'%s\\', `mode` = \\'%d\\' WHERE `user_id` = \\'%d\\';' % (task_id, task[1], task[8], mode, user_id))\n elif mode == 5:\n text += '\\nОтвет: *id0(%s)' % task[8]\t\t\n\n self.vk.sendMessage(user_id, text)\n \n def getCorrect(self, user_id, user, answer):\n\t\t\n true = ''\n false = ''\n score = 0\n\t\n if user[3] == answer:\n if user[8] == 0: \n self.vk.sendMessage(user_id, 'Верно!\\nВведите РУС чтобы продолжить.')\n aT = 'tests + 1'\n \n elif user[8] == 1:\n self.vk.sendMessage(user_id, 'Верно!')\n \n elif user[8] == 2:\n true = user[6] + ', '\n score = 4\n\t\t\t\n else:\n if user[8] == 0:\n string = 'Неверно!\\nПравильный ответ: *id0(%s)\\nВведите РУС чтобы продолжить.' % user[3]\n self.vk.sendMessage(user_id, string)\n aT = 'tests'\n \n elif user[8] == 1: \n string = 'Неверно!\\nПравильный ответ: *id0(%s)' % user[3]\n self.vk.sendMessage(user_id, string)\n \n elif user[8] == 2:\n false = user[6] + ', '\n \n if user[8] == 0: sql = 'UPDATE users SET tmp_test = 0, tmp_cor = 0, tmp_type = \\'\\', all_tests = all_tests+1, mode = 0, tests = %s WHERE user_id = %d;' % (aT, user_id)\n elif user[8] == 1: sql = 'UPDATE users SET tmp_test = 0, tmp_type = \\'\\', tmp_cor = 0, mode = 0 WHERE user_id = %d;' % user_id\n elif user[8] == 2: sql = 'UPDATE users SET mode_true = CONCAT(`mode_true`, \\'%s\\'), mode_false = CONCAT(`mode_false`, \\'%s\\'), mode_score = mode_score + %d WHERE user_id = %d' % (true, false, score, user_id)\n \n self.sql.ex(sql)\n \n if user[8] == 2 and user[2] < 107: self.show(user_id, user[2]+1, 2)\n elif user[8] == 2 and user[2] == 107:\n info = self.sql.fetchOne('SELECT mode_true, mode_false, mode_score FROM users WHERE user_id = %d' % user_id)\n text = 'Ваш результат: *id0(%d баллов) из 100\\n\\n' % info[2]\n \n if len(info[0]) > 0:\n true = info[0]\n true = true[:-2]\n text += 'Верные ответы: %s.\\n' % true\n \n if len(info[1]) > 0:\n false = info[1]\n false = false[:-2]\n text += 'Неверные ответы: %s.' % false\n \n self.sql.ex('UPDATE users SET tmp_test = 0, tmp_type = \\'\\', tmp_cor = 0, mode = 0, mode_true = \\'\\', mode_false = \\'\\', mode_score = 0 WHERE user_id = %d;' % user_id)\n \n self.vk.sendMessage(user_id, text)\n \n def convertAns(self, answer, user_id, user):\n arr = answer.replace(' ', '').split(',')\n if self.checkInt(arr[0]):\n arr.sort()\n correct = ''\n \n for ans in arr:\n if self.checkInt(ans): correct += ans + ','\n \n correct = correct[0:-1]\n \n self.getCorrect(user_id, user, correct)\n else:\n return False\n \n def checkInt(self, s):\n try: \n int(s)\n return True\n except ValueError:\n return False \n \n","sub_path":"main/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":4421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"527240314","text":"from django.shortcuts import render\nfrom bs4 import BeautifulSoup\nimport requests\nimport re\nimport time\nfrom reports import models\n\nflag = False\n\ndef home_view(request):\n return render(request, 'home.html')\n\ndef get_soup(url):\n headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:10.0) Gecko/20100101 Firefox/10.0'}\n response = requests.get(url, headers=headers).text\n soup = BeautifulSoup(response, 'html.parser')\n souptext = soup.get_text()\n return souptext\n\ndef extract_swellnet_data(souptext):\n swell_data = []\n swell_data.append(re.findall(r'Surf: \\w+ \\d*-*\\d\\w+ \\w+', souptext)[0])\n swell_data.append(re.findall(r'Winds: \\w+ \\w+', souptext)[0])\n swell_data.append(re.findall(r'Weather: \\w+', souptext)[0])\n swell_data.append(re.findall(r'Updated: \\d+-\\d+-\\d+ \\d+:\\d+:\\d+', souptext)[0])\n swell_data.append(re.findall(r'rimary:\\s+\\d+.?\\d+?\\s*\\w+?\\s+\\W+\\d+.?\\d+?\\w+?\\s*\\w*', souptext)[0].replace(\"\\n\",\" \"))\n return swell_data\n\ndef extract_wind(souptext):\n wind = re.findall(r'Now\\s+\\d+.?\\d+?km/h\\s+[a-zA-Z]+', souptext) #adding a ? after the fullstop and the following digit selector to allow for whole numbers\n wind_data = re.findall(r'\\d+.?\\d+?km/h\\s+[a-zA-Z]+', wind[0]) #added the same escape characters to wind_data\n return wind_data\n\ndef extract_tide_data(souptext):\n\n tide_list = []\n type_list = []\n height_list = []\n tide_data = re.findall(r'\"tides\":.{600}', souptext)\n tide_times = re.findall(r'\\d+:\\d+[a-z]+', tide_data[0])\n tide_types = re.findall(r'\"type\":\"\\w+\"', tide_data[0])\n\n for x in range(len(tide_types)):\n if 'High' in tide_types[x]:\n type_list.append('High')\n if 'Low' in tide_types[x]:\n type_list.append('Low')\n\n tide_heights = re.findall(r'\"height\":\"\\d+.\\d+\"', tide_data[0])\n for x in tide_heights:\n height_list.append(re.findall(r'\\d+.\\d+', x)[0])\n\n for x in range(len(tide_times)):\n tide_list.append(((type_list[x]),(str(tide_times[x])),(str(height_list[x]))))\n\n return tide_list\n\ndef show_forecast(request):\n flag = True\n while flag:\n mornington_report_swellnet = extract_swellnet_data(get_soup('http://www.swellnet.com/reports/australia/victoria/mornington-peninsula'))\n mornington_report_wind = extract_wind(get_soup('http://wind.willyweather.com.au/vic/mornington-peninsula/mornington.html'))\n mornington_report_tide = extract_tide_data(get_soup('http://www.swellnet.com/reports/australia/victoria/mornington-peninsula'))\n\n wave_size = re.findall(r'\\d*-\\d*', mornington_report_swellnet[0])\n swell_size_period = re.findall(r'\\d+\\.*\\d*',mornington_report_swellnet[4]) #by index, 0: swell size(m), 1: period(s)\n wind_speed = re.findall(r'\\d+.?\\d+?', mornington_report_wind[0])\n wind_direction = re.findall(r'[A-Z]+', mornington_report_wind[0])\n swell_direction = re.findall(r'[A-Z]+',mornington_report_swellnet[4])\n\n t = models.Tide()\n t.first_tide = mornington_report_tide[0]\n t.second_tide = mornington_report_tide[1]\n t.third_tide = mornington_report_tide[2]\n if mornington_report_tide[3]:\n t.fourth_tide = mornington_report_tide[3]\n t.save()\n\n r = models.Report()\n r.swell_direction = swell_direction[0]\n r.swell_size = swell_size_period[0]\n r.swell_period = swell_size_period[1]\n r.wave_size = wave_size[0]\n r.wind_direction = wind_direction[0]\n r.wind_speed = wind_speed[0]\n r.save()\n time.sleep(10)\n\n return render(request, 'home.html')\n'''\ndef show_forecast(request):\n mornington_report_swellnet = extract_swellnet_data(get_soup('http://www.swellnet.com/reports/australia/victoria/mornington-peninsula'))\n mornington_report_wind = extract_wind(get_soup('http://wind.willyweather.com.au/vic/mornington-peninsula/mornington.html'))\n\n wave_size = re.findall(r'\\d*-\\d*', mornington_report_swellnet[0])\n swell_size_period = re.findall(r'\\d+\\.*\\d*',mornington_report_swellnet[4]) #by index, 0: swell size(m), 1: period(s)\n wind_speed = re.findall(r'\\d+.?\\d+?', mornington_report_wind[0])\n wind_direction = re.findall(r'[A-Z]+', mornington_report_wind[0])\n swell_direction = re.findall(r'[A-Z]+',mornington_report_swellnet[4])\n\n r = models.Report()\n r.swell_direction = swell_direction[0]\n r.swell_size = swell_size_period[0]\n r.swell_period = swell_size_period[1]\n r.wave_size = wave_size[0]\n r.wind_direction = wind_direction[0]\n r.wind_speed = wind_speed[0]\n r.save()\n\n return render(request, 'home.html')\n'''\n","sub_path":"surf_api_3/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"437524323","text":"# 백준 15989번 1, 2, 3 더하기 4\n# 실버 1\n\nT = int(input())\nfor _ in range(T):\n n = int(input())\n num_3 = n // 3\n count = 0\n for i in range(num_3 + 1):\n count += (n - 3*i) // 2 + 1\n print(count)\n","sub_path":"Dongyeon/15989.py","file_name":"15989.py","file_ext":"py","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"404239735","text":"from PIL import Image \nimport os.path\nimport glob \n\nINPUT_DATA_DIR = './dataset/orl_faces'\nOUTPUT_DATA_DIR = './dataset/orl_faces_png'\n\n#将pgm格式转化为png格式,以便提供给tensorflow进行处理\n\ndef pgm2png(in_dir, out_dir): \n if not os.path.exists(out_dir): \n print(out_dir, 'is not existed.') \n os.mkdir(out_dir) \n if not os.path.exists(in_dir): \n print(in_dir, 'is not existed.') \n return -1 \n\n for sub_dir in glob.glob(in_dir+'/*'): \n #sub_dir:各个子文件夹\n print(\"processing:\", sub_dir)\n #out_sub_dir:转存的各个子文件夹,文件从sub_dir中读取,存储到out_sub_dir中\n out_sub_dir=os.path.join(out_dir,os.path.basename(sub_dir))\n print(\"out_sub_dir:\",out_sub_dir)\n #创建相应的文件夹\n if not os.path.exists(out_sub_dir): \n print(out_sub_dir, 'is not existed.') \n os.mkdir(out_sub_dir)\n for files in glob.glob(sub_dir+'/*.'+'pgm'): \n #读取每个文件夹,得到路径、文件名、后缀,进行分割,从而组合得到输出文件相对路径\n filepath, filename = os.path.split(files) \n outfile, _ = os.path.splitext(filename)\n outfile = outfile+'.png'\n #out:./dataset/orl_faces/s32 ----- 5.pgm ------> 5.jpg\n print(filepath,'-----',filename,'------>',outfile)\n img = Image.open(files) \n new_path = os.path.join(out_sub_dir, outfile) \n img.save(new_path) \n print(\"--------------\") \n\nif __name__=='__main__': \n pgm2png(INPUT_DATA_DIR, OUTPUT_DATA_DIR) \n","sub_path":"pgm2png.py","file_name":"pgm2png.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"561952747","text":"def gcd(a,b):\n \"\"\"\n Compute Greatest Common divisor (GCD) of a and b\n :param a:\n :param b:\n :return:\n \"\"\"\n factor_list = []\n # common factor is the factor of n than can be square rooted\n # gcd is the product of the common factors\n n = a*b\n n_temp = n\n while n_temp > 1:\n i = 2 #1 is always a factor\n factor_found = False\n while not factor_found:\n if n_temp % i == 0:\n factor_list.append(i)\n n_temp /= i\n print(i)\n factor_found = True\n i += 1\n\n # find if factor has a duplicate\n # (you will always get a prime result since the factor that is larger than prime will not be encountered)\n # Therefore, we don't have to worry about duplicated number being divisible (e.g. 4*4)\n factor_list_dup = []\n while len(factor_list) > 0:\n dup_found = False\n #while not dup_found:\n\ndef gcd_easier(a,b):\n # you don't have to decompose!!\n if a > b:\n test = a\n else:\n test = b\n gcd_found = False\n while test > 0 and not gcd_found:\n if(a % test == 0 and b % test == 0):\n gcd_found = True\n return test\n test -= 1\n\nprint(gcd_easier(4,8))\n","sub_path":"2LabWork-FIT2004/Week2/W2t5.py","file_name":"W2t5.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"514586547","text":"import torch\nfrom wave_2d_fd_perf.propagators import VPytorch\n\nclass VPytorch3(VPytorch):\n\n def __init__(self, model, dx, dt=None, align=None):\n pad = 0\n super(VPytorch3, self).__init__(model, pad, dx, dt, align)\n\n def step(self, nt, source_amplitude, sources_x, sources_y):\n\n source_amplitude = torch.tensor(source_amplitude)\n sources_x = torch.tensor(sources_x).long()\n sources_y = torch.tensor(sources_y).long()\n\n for i in range(nt):\n lap = (torch.nn.functional.conv2d(self.wfc[..., :self.nx],\n self.kernel1d.view(1, 1, 1, -1),\n padding=(0, 8)) +\n torch.nn.functional.conv2d(self.wfc[..., :self.nx],\n self.kernel1d.view(1, 1, -1, 1),\n padding=(8, 0)))\n self.wfp[0, 0, :, :self.nx] = \\\n (self.model[0, 0, :, :self.nx] * lap[0, 0]\n + 2 * self.wfc[0, 0, :, :self.nx]\n - self.wfp[0, 0, :, :self.nx])\n\n self.wfp[0, 0, sources_y, sources_x] += \\\n (source_amplitude[:, i]\n * self.model[0, 0, sources_y, sources_x])\n\n self.wfc, self.wfp = self.wfp, self.wfc\n\n return self.wfc[0, 0, :, :self.nx].numpy()\n","sub_path":"wave_2d_fd_perf/vpytorch3.py","file_name":"vpytorch3.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"496078136","text":"from django.contrib.auth import authenticate, login\nfrom django.shortcuts import render, redirect\nfrom django.urls import reverse\nfrom .models import Profile\nfrom .forms import LoginForm, AccountEditForm\nfrom django.core.files.storage import FileSystemStorage as _FileSystemStorage\nimport os\nfrom datetime import datetime\nfrom django.utils.functional import cached_property\nfrom django.utils.datastructures import MultiValueDictKeyError\n\nclass FileSystemStorage(_FileSystemStorage):\n @cached_property\n def base_location(self):\n BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n MEDIA_ROOT = os.path.join(BASE_DIR, 'img')\n path_suffix ='profiles'\n path_year = datetime.today().strftime('%Y')\n path_month = datetime.today().strftime('%m')\n path_day = datetime.today().strftime('%d')\n filepath = os.path.join(MEDIA_ROOT, path_suffix, path_year, path_month, path_day)\n return self._value_or_setting(self._location, filepath)\n\nclass NoPhoto():\n url = '/media/profiles/unknown.png'\n\ndef redirect_to_main(request):\n if request.user.is_authenticated:\n id = request.user.id\n return redirect(reverse('profile', kwargs={'id': id}))\n else:\n return render(request, 'main.html', {})\n\n\ndef main(request, **kwargs):\n template = 'main.html'\n context = {}\n if request.user.is_authenticated:\n user_data = Profile.objects.get(id=kwargs['id'])\n context['email'] = user_data.email\n context['nick'] = user_data.nick_name\n context['full_name'] = user_data.full_name\n context['country'] = user_data.country\n context['city'] = user_data.city\n context['birth'] = user_data.date_of_birth\n context['about_me'] = user_data.about_me\n context['page_id'] = int(kwargs['id'])\n context['user_id'] = request.user.id\n if user_data.photo:\n context['photo'] = user_data.photo\n else:\n no_photo = NoPhoto()\n context['photo'] = no_photo\n return render(request, template, context)\n\ndef edit_account(request):\n user_data = Profile.objects.get(email=request.user)\n if request.method == 'POST':\n form = AccountEditForm(request.POST, request.FILES)\n if form.is_valid():\n edited_details = form.cleaned_data\n if edited_details['full_name']:\n user_data.full_name = edited_details['full_name']\n if edited_details['nick_name']:\n user_data.nick_name = edited_details['nick_name']\n if edited_details['date_of_birth']:\n user_data.date_of_birth = edited_details['date_of_birth']\n if edited_details['about_me']:\n user_data.about_me = edited_details['about_me']\n if edited_details['city']:\n user_data.city = edited_details['city']\n if edited_details['country']:\n user_data.country = edited_details['country']\n try:\n if edited_details['photo']:\n avatar = edited_details['photo']\n fs = FileSystemStorage()\n filename = fs.save(avatar.name, avatar)\n filepath = os.path.join(fs.location, filename)\n user_data.photo = filepath\n except MultiValueDictKeyError:\n pass\n user_data.save()\n return redirect(redirect_to_main)\n template = 'edit_account.html'\n form = AccountEditForm()\n if user_data.full_name:\n form.fields['full_name'].widget.attrs['placeholder'] = user_data.full_name\n if user_data.nick_name:\n form.fields['nick_name'].widget.attrs['placeholder'] = user_data.nick_name\n if user_data.date_of_birth:\n form.fields['date_of_birth'].widget.attrs['placeholder'] = user_data.date_of_birth.strftime('%d.%m.%Y')\n if user_data.about_me:\n form.fields['about_me'].widget.attrs['placeholder'] = user_data.about_me\n if user_data.city:\n form.fields['city'].widget.attrs['placeholder'] = user_data.city\n if user_data.country:\n form.fields['country'].widget.attrs['placeholder'] = user_data.country\n context = {'edit_account_form': form}\n return render(request, template, context)\n\n\ndef search(request):\n template = 'search.html'\n context = {}\n if request.method == 'POST':\n query = request.POST['query']\n result = Profile.objects.filter(nick_name=query)\n context['results'] = result\n return render(request, template, context)\n\n\ndef login_user(request):\n template = 'login.html'\n if request.method == 'POST':\n form = LoginForm(request.POST)\n if form.is_valid():\n form_data = form.cleaned_data\n username = form_data['email'].lower()\n password = form_data['password']\n user = authenticate(username=username, password=password)\n if user is not None:\n login(request, user)\n return redirect(redirect_to_main)\n else:\n invalid_login = True\n return render(request, template, {'login_form': form, 'invalid_login': invalid_login})\n print(form)\n form = LoginForm()\n return render(request, template, {'login_form': form})\n\ndef empty_view(request):\n template = 'empty.html'\n context = {}\n return render(request=request, template_name=template, context=context)\n\n# Create your views here.\n","sub_path":"accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"608772642","text":"#!/usr/bin/env python\n\n\"\"\"\nUsage: transform [FILE] --function FILE [--help]\n\n -f --function FILE File with a function. It must be called 'transform'\n -h --help Show this screen.\n\n Example:\n def transform(line):\n cells = line.split(',')\n cells[1] = round(float(cells[1]), 2)\n cells[2] = round(float(cells[2]), 2)\n return cells\n\"\"\"\n\nfrom docopt import docopt\nimport importlib\nimport sys\nimport csv\n\ndef find_source(args):\n if args['FILE']:\n source = open(args['FILE'], 'rb')\n else:\n if not sys.stdin.isatty():\n source = sys.stdin\n else:\n print(__doc__)\n return None\n return source\n\ndef import_job(args):\n relative_path = args['--function']\n path_parts = relative_path.split('/')\n\n if len(path_parts) > 1:\n function_folder = '/'.join(path_parts[:-1])\n sys.path.append(function_folder)\n else:\n sys.path.append('.')\n\n module_name = path_parts[-1].split('.')[0]\n return importlib.import_module(module_name)\n\ndef main(args):\n source = find_source(args)\n if not source: return\n\n job = import_job(args)\n if not hasattr(job, 'transform'): return\n\n writer = csv.writer(sys.stdout)\n\n for line in source:\n cells = job.transform(line.rstrip())\n if cells:\n writer.writerow(cells)\n\nif __name__ == '__main__':\n arguments = docopt(__doc__)\n main(arguments)\n","sub_path":"src/transform/src/transform.py","file_name":"transform.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"409151944","text":"import json\nimport os\nimport requests\n\nENDPOINT = 'https://tequila-api.kiwi.com'\nAPI_LOCATIONS = '/locations/query'\nAPI_SEARCH = '/v2/search'\nAPI_KEY = os.environ['TEQUILA_API_KEY']\nAFFILL_ID = os.environ['TEQUILA_AFFILL_ID']\n\n\nclass FlightSearch:\n def __init__(self, api_call, endpoint, params):\n self.endpoint = f'{endpoint}{api_call}'\n self.params = params\n self.data = self._get_data()\n\n def _get_data(self):\n response = requests.get(self.endpoint, self.params)\n return response.json()\n\n def search_locations(self, key, value, city):\n for location in self.data['locations']:\n if location[key] == value:\n return location[city]\n","sub_path":"Day040/Capstone_Project/flight_search.py","file_name":"flight_search.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"388940739","text":"##Libraries\r\n\r\nimport numpy as np\r\nimport requests as req\r\nfrom astropy.time import Time\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.optimize import curve_fit\r\n\r\n\r\n\r\ndirtmp='C:\\\\Users\\\\cleme\\\\Desktop\\\\APC_2021\\\\tmp\\\\' #chemin du directory\r\ndir='C:\\\\Users\\\\cleme\\\\Desktop\\\\APC_2021\\\\'\r\n\r\n##preprocess les données des profils slow et fast 1B/C\r\nfilename='SN1BC_article'\r\nevent=np.array(open(dirtmp+filename+'.txt','r').read().split('\\n')) #list de nom des évènements\r\n\r\nexec(open(dir+'Light_curves.py','r').read()) #execute le code Light_curves.py\r\n\r\n##effectue un fit et la moyenne en bande U,B,V,R,I\r\nbandstr='U'\r\nLC=bandstr+'.txt'\r\n\r\nexec(open(dir+'article.py','r').read()) #execute le code Light_curves.py\r\n\r\n\r\n##preprocess les données de 89 SN1BC\r\nfilename='SN1bc'\r\nevent=np.array(open(dirtmp+filename+'.txt','r').read().split('\\n')) #list de nom des évènements\r\n\r\nexec(open(dir+'Light_curves.py','r').read()) #execute le code Light_curves.py\r\n\r\n##définie la distribution en magnitude pour la bande donnée\r\nexec(open(dir+'mag_histo.py','r').read())\r\n\r\n##défini la distibution des distances\r\nexec(open(dir+'distance_distrib.py','r').read())\r\n\r\n## prévois une courbe de lumière en bande U,B,V,R,I\r\nexec(open(dir+'random.py','r').read())","sub_path":"old/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"643996174","text":"import viz\r\nimport viztask\r\nviz.go()\r\n\r\n#task\r\n#subtask\r\n#other task\r\n#event within task\r\n\r\n\r\nviz.add( 'court.ive' )\r\n\r\n#Add a matrix of dots.\r\ndots = []\r\nfor x in range(-2,3):\r\n\tfor z in range(1,4):\r\n\t\tdot = viz.add('white_ball.wrl')\r\n\t\tdot.collideSphere()\r\n\t\tdot.disable( viz.DYNAMICS )\r\n\t\tdot.setPosition( x, 1.8, z )\r\n\t\tdots.append( dot )\r\n\r\n#Add a text field.\r\ntext = viz.addText('', viz.SCREEN )\r\ntext.setPosition( .5,.5 )\r\ntext.setScale( .5,.5)\r\ntext.alignment( viz.TEXT_CENTER_BASE )\r\ntext.alpha( 0 )\r\n\r\n#Set up a scoreboard.\r\n\r\n\r\n#Node for our head.\r\nhead = viz.add('white_ball.wrl')\r\nhead.collideSphere()\r\nhead.enable( viz.COLLIDE_NOTIFY )\r\nhead.disable( viz.RENDERING )\r\nhead.disable( viz.DEPTH_WRITE )\r\nviz.link( viz.MainView, head )\r\n\r\ndef game_task():\r\n\twhile True:\r\n\t\tcollision_data = viz.Data()\r\n\t\tyield viztask.waitEvent( viz.COLLIDE_BEGIN_EVENT, collision_data )\r\n\t\tcollision_data.data[0].obj2.visible( viz.OFF )\r\nviz.phys.enable()\r\n\r\n\r\ndef overview_task():\r\n\t#Get ready screen.\r\n\ttext.alpha(1)\r\n\ttext.message( 'Press s to begin' )\r\n\t#Wait for player to hit 's' key.\r\n\tyield viztask.waitKeyDown( 's' )\r\n\t#Provide the game instructions in a subtask.\r\n\tyield game_instructions() \r\n\t#Begin the game.\r\n\tgame = viztask.schedule( game_task() )\r\n\t#Wait for time to pass.\r\n\tyield viztask.waitTime( 10 )\r\n\t#End game.\r\n\tgame.kill()\r\n\ttext.alpha( 1 )\r\n\ttext.message( 'GAME OVER' )\r\n\r\nviztask.schedule( overview_task() )\r\n#timer event\r\n#keyboard event\r\n#collision event\r\n#action begin event\r\n#button event\r\n\r\n\r\n","sub_path":"Vizard/teacher in a book code snippets (R4)/viztask example.py","file_name":"viztask example.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"365486987","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/sutekh/base/gui/SutekhDialog.py\n# Compiled at: 2019-12-11 16:37:48\n\"\"\"Dialog wrapper and functions for Sutekh\"\"\"\nimport logging, sys, traceback, gtk\nfrom gobject import markup_escape_text\nfrom sutekh.SutekhInfo import SutekhInfo as AppInfo\nfrom ..Utility import get_database_url\n\nclass SutekhDialog(gtk.Dialog):\n \"\"\"wrapper class for gtk.Dialog\"\"\"\n\n def __init__(self, sTitle, oParent=None, iFlags=0, oButtons=None):\n super(SutekhDialog, self).__init__(sTitle, oParent, iFlags, oButtons)\n self.set_name('Sutekh.dialog')\n\n def add_first_button(self, sText, iResponse):\n \"\"\"Abuse add_button and action_area to insert a button at the\n head of the list.\"\"\"\n oButton = self.add_button(sText, iResponse)\n self.action_area.reorder_child(oButton, 0)\n\n\ndef do_complaint(sMessage, oDialogType, oButtonType, bMarkup=False):\n \"\"\"Wrapper function for gtk.MessageDialog.\n\n Create the dialog, run it, and return the result. If bMarkup is true,\n the string is interpreted as markup, other, just as plain text\n \"\"\"\n if bMarkup:\n oComplaint = gtk.MessageDialog(None, 0, oDialogType, oButtonType, None)\n oComplaint.set_markup(sMessage)\n else:\n oComplaint = gtk.MessageDialog(None, 0, oDialogType, oButtonType, sMessage)\n oComplaint.set_name('Sutekh.dialog')\n iResponse = oComplaint.run()\n oComplaint.destroy()\n return iResponse\n\n\ndef do_complaint_buttons(sMessage, oType, aButtonInfo, bMarkup=False):\n \"\"\"Wrapper function for gtk.MessageDialog, using add_button to create\n custom button layouts.\n\n Create the dialog, run it, and return the result. If bMarkup is true,\n the string is interpreted as markup, other, just as plain text.\n \"\"\"\n if bMarkup:\n oComplaint = gtk.MessageDialog(None, 0, oType, gtk.BUTTONS_NONE, None)\n oComplaint.set_markup(sMessage)\n else:\n oComplaint = gtk.MessageDialog(None, 0, oType, gtk.BUTTONS_NONE, sMessage)\n for oItem, oResponse in zip(aButtonInfo[0::2], aButtonInfo[1::2]):\n oComplaint.add_button(oItem, oResponse)\n\n oComplaint.set_name('Sutekh.dialog')\n iResponse = oComplaint.run()\n oComplaint.destroy()\n return iResponse\n\n\ndef do_complaint_error(sMessage):\n \"\"\"Error dialog with close button\"\"\"\n return do_complaint(sMessage, gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE, False)\n\n\ndef do_complaint_warning(sMessage):\n \"\"\"Warning dialog with OK and CANCEL buttons\"\"\"\n return do_complaint(sMessage, gtk.MESSAGE_WARNING, gtk.BUTTONS_OK_CANCEL, False)\n\n\nclass DetailDialog(SutekhDialog):\n \"\"\"Message dialog with a details expander\"\"\"\n\n def __init__(self, sMessage, sDetails):\n super(DetailDialog, self).__init__('%s has encounterd an error' % AppInfo.NAME, oButtons=(\n gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE))\n oHBox = gtk.HBox(False, 2)\n oMessageBox = gtk.VBox(False, 2)\n oImage = gtk.Image()\n oImage.set_from_stock(gtk.STOCK_DIALOG_ERROR, gtk.ICON_SIZE_DIALOG)\n oImage.set_alignment(0, 0)\n oHBox.pack_start(oImage, expand=False)\n oInfo = gtk.Label()\n oInfo.set_markup('%s' % markup_escape_text(sMessage))\n oInfo.set_alignment(0, 0)\n oInfo.set_selectable(True)\n oMessageBox.pack_start(oInfo, expand=False)\n oExpander = gtk.Expander('Details')\n oFrame = gtk.Frame()\n oDetails = gtk.Label(sDetails)\n oDetails.set_selectable(True)\n oFrame.add(oDetails)\n oExpander.add(oFrame)\n oMessageBox.pack_start(oExpander)\n oHBox.pack_start(oMessageBox)\n self.vbox.pack_start(oHBox)\n oExpander.set_expanded(False)\n self.show_all()\n self.set_name('Sutekh.dialog')\n\n\ndef format_app_info():\n \"\"\"Format the application details nicely for the error dialogs.\"\"\"\n return '%s version %s\\nDatabase: %s\\n\\n' % (AppInfo.NAME,\n AppInfo.VERSION_STR,\n get_database_url())\n\n\ndef do_complaint_error_details(sMessage, sDetails):\n \"\"\"Popup an details dialog for an error\"\"\"\n oComplaint = DetailDialog(sMessage, ('\\n').join([format_app_info(),\n sDetails]))\n iResponse = oComplaint.run()\n oComplaint.destroy()\n return iResponse\n\n\ndef do_exception_complaint(sMessage):\n \"\"\"Handle an exception - log the details for verbose info, and popup\n a detailed dialog with the info.\"\"\"\n oType, oValue, oTraceback = sys.exc_info()\n aTraceback = traceback.format_exception(oType, oValue, oTraceback, limit=30)\n logging.error('%s:\\n%s', sMessage, ('').join(aTraceback))\n do_complaint_error_details(sMessage, ('').join(aTraceback))\n\n\ndef exception_handler(oType, oValue, oTraceback):\n \"\"\"sys.excepthook wrapper around do_complaint_error_details.\"\"\"\n if oType == KeyboardInterrupt:\n return\n sMessage = '%s reported an unhandled exception:\\n%s\\n' % (AppInfo.NAME,\n str(oValue))\n aTraceback = traceback.format_exception(oType, oValue, oTraceback)\n sDetails = ('').join(aTraceback)\n logging.error('%s:\\n%s', sMessage, ('\\n').join([format_app_info(),\n sDetails]))\n do_complaint_error_details(sMessage, sDetails)\n\n\nclass NotebookDialog(SutekhDialog):\n \"\"\"Dialog with a notebook widget.\"\"\"\n\n def __init__(self, sTitle, oParent=None, iFlags=0, oButtons=None):\n super(NotebookDialog, self).__init__(sTitle, oParent, iFlags, oButtons)\n self._oNotebook = gtk.Notebook()\n self._oNotebook.set_scrollable(True)\n self._oNotebook.popup_enable()\n self.vbox.pack_start(self._oNotebook)\n\n notebook = property(fget=lambda self: self._oNotebook, doc='Notebook Widget')\n\n def add_widget_page(self, oWidget, sTabText, sMenuText=None, bMarkup=False):\n \"\"\"Add a widget to the notebook as a page, specifying tab header.\n\n sMenuText can be used to control the text of the popup menu\n item.\n If bMarkup is True, the header text is interpreted as a markup\n string.\"\"\"\n oHeader = gtk.Label()\n if bMarkup:\n oHeader.set_markup(sTabText)\n else:\n oHeader.set_text(sTabText)\n if sMenuText:\n oMenuLabel = gtk.Label(sMenuText)\n oMenuLabel.set_alignment(0.0, 0.5)\n self._oNotebook.append_page_menu(oWidget, oHeader, oMenuLabel)\n else:\n self._oNotebook.append_page(oWidget, oHeader)\n\n def get_cur_widget(self):\n \"\"\"Get the main widget of the current page.\"\"\"\n iPage = self._oNotebook.get_current_page()\n return self._oNotebook.get_nth_page(iPage)\n\n def iter_all_page_widgets(self):\n \"\"\"Iterator over all the pages in the notebook, returning\n the main widget of each page.\"\"\"\n for iPage in range(self._oNotebook.get_n_pages()):\n yield self._oNotebook.get_nth_page(iPage)","sub_path":"pycfiles/Sutekh-1.0.0-py2.7/SutekhDialog.py","file_name":"SutekhDialog.py","file_ext":"py","file_size_in_byte":7009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"206426047","text":"import got\nimport codecs\n\n\ntry:\n tweetCriteria = got.manager.TweetCriteria()\n outputFileName = \"output_got_greve.csv\"\n\n outputFile = codecs.open(outputFileName, \"w+\", \"utf-8\")\n outputFile.write(\n 'username;date;retweets;favorites;text;geo;mentions;hashtags;id;permalink')\n\n print('Searching...\\n')\n\n def receiveBuffer(tweets):\n for t in tweets:\n outputFile.write(('\\n%s;%s;%d;%d;\"%s\";%s;%s;%s;\"%s\";%s' % (t.username, t.date.strftime(\n \"%Y-%m-%d %H:%M\"), t.retweets, t.favorites, t.text, t.geo, t.mentions, t.hashtags, t.id, t.permalink)))\n outputFile.flush()\n print('More %d saved on file...\\n' % len(tweets))\n\n tweetCriteria = got.manager.TweetCriteria().setQuerySearch(\n 'greve').setSince(\"2019-05-14\").setUntil(\"2019-05-16\").setMaxTweets(5)\n\n got.manager.TweetManager.getTweets(tweetCriteria, receiveBuffer)\nfinally:\n outputFile.close()\n print('Done. Output file generated \"%s\".' % outputFileName)\n# print got.manager.TweetManager.getTweets(tweetCriteria)\n\n# for tweet in got.manager.TweetManager.getTweets(tweetCriteria):\n# print tweet._json\n#tweet = got.manager.TweetManager.getTweets(tweetCriteria)[0]\n# print tweet.text\n","sub_path":"collect_by_date.py","file_name":"collect_by_date.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"645202509","text":"# This program creates 500 files with the iteration number as the filename and the contents of the file\n# After creating each file, it is uploaded to an S3 Bucket\n\nimport boto3\nimport logging\n\ns3 = boto3.resource(\"s3\")\nboto3.set_stream_logger('boto3.resources', logging.INFO)\n\nfor x in range(0, 500):\n my_str = str(x)\n s3.Object(\"alex-shared\",\"python-test/\" + my_str + \".txt\").copy_from(CopySource=\"alex-shared/\" + my_str + \".txt\")\n s3.Object(\"alex-shared\",my_str + \".txt\").delete()\n\nprint(\"Done!\")\n","sub_path":"env1/ex3.py","file_name":"ex3.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"45040930","text":"from icecream import ic\nimport warnings\nimport numpy as np\nimport pandas as pd\nfrom time import time\n\nfrom sklearn.datasets import load_breast_cancer\n\nfrom sklearn.model_selection import KFold, cross_val_score, train_test_split, GridSearchCV\nfrom sklearn.metrics import accuracy_score\n\n# KFold, Cross_Validation\n\nfrom sklearn.ensemble import RandomForestClassifier\n\nwarnings.filterwarnings('ignore') # 오류구문 무시\n\n\ndataset = pd.read_csv('../_data/winequality-white.csv', sep=';', index_col=None, header=0)\nprint(dataset)\n\nprint(dataset.shape)\nprint(dataset.info())\nprint(dataset.describe())\n\n# wine의 quailty를 y로 잡음\n\ny = dataset['quality'].to_numpy()\nx = dataset.drop(columns='quality')\n\nprint(x.shape, y.shape) # (150, 4) (150,)\n\nx_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.8, shuffle=True, random_state=41)\n\n# Model\n\nkfold = KFold(n_splits=5, shuffle=True, random_state=41)\n\nparameters = [\n {'n_estimators' : [100, 200],\n 'max_depth' : [6, 8, 10, 12],\n 'min_samples_leaf' : [3, 5, 7, 10],\n 'min_samples_split' : [2, 3, 5, 10],\n 'n_jobs' : [-1, 2, 4]}\n]\n\n'''\nparameters = [\n {'n_estimators' : [100, 200],\n 'max_depth' : [6, 8, 10, 12],\n 'min_samples_leaf' : [3, 5, 7, 10],\n 'min_samples_split' : [2, 3, 5, 10],\n 'n_jobs' : [-1, 2, 4]}\n]\n-> 연산 수 -> 5 * {2 * 4 * 4 * 4 * 3} = 1920\n-> 원판(7-5) 대비 연산량이 85 -> 1920으로 20배 이상 증가함, 엄청 오래 걸림\n'''\n\n# GridSearchCV로 감싸기\n\nstart_time = time()\n\nmodel = GridSearchCV(RandomForestClassifier(), parameters, cv=kfold, verbose=1)\n\n\nmodel.fit(x_train, y_train)\n\nic(model.best_estimator_)\n\nic(model.best_score_)\n\nic(model.score(x_test, y_test))\n\ny_predict = model.predict(x_test)\nprint('정답률 : ', accuracy_score(y_test, y_predict))\n\nelapsed_time = time() - start_time\n\nic(elapsed_time)\n\n'''\nic| model.best_estimator_: RandomForestClassifier(n_jobs=2)\nic| model.best_score_: 0.670248195063466\nic| model.score(x_test, y_test): 0.6857142857142857\n정답률 : 0.6857142857142857\n'''","sub_path":"machine_learning/ml07_5_grid_wine_2.py","file_name":"ml07_5_grid_wine_2.py","file_ext":"py","file_size_in_byte":2048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"213198215","text":"#marked with comment(#) is the original value\n\n#class Garden(object):\n# def __init__(self, diagram, students):\n# pass\n\nclass Garden(object):\n students_def = ['Alice', 'Bob', 'Charlie', \n 'David', 'Eve', 'Fred', \n 'Ginny', 'Harriet', 'Ileana', \n 'Joseph', 'Kincaid', 'Larry']\n\n def __init__(self, diagram, students=students_def):\n self.diagram = diagram.splitlines()\n self.students = sorted(students)\n \n def plants(self, student):\n plants = {'G': 'Grass', 'C': 'Clover', 'R': 'Radishes', 'V': 'Violets'}\n student_idx = self.students.index(student)\n row1a = plants[self.diagram[0][(student_idx*2)]]\n row1b = plants[self.diagram[0][(student_idx*2+1)]]\n row2a = plants[self.diagram[1][(student_idx*2)]]\n row2b = plants[self.diagram[1][(student_idx*2+1)]]\n return [row1a, row1b, row2a, row2b]","sub_path":"kindergarten_garden.py","file_name":"kindergarten_garden.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"68488762","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nfrom django.conf import settings\nfrom feincms import urls as feincms_urls\n\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n url(r'^admin/', include(admin.site.urls)),\n # url(r'^$', 'views.home', name='home'),\n # url(r'^gallery/', include('gallery.urls')),\n url(r'', include(feincms_urls)),\n)\n\nif settings.DEBUG:\n urlpatterns += patterns('',\n url(r'^media/(?P.*)$', 'django.views.static.serve',\n {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),\n url(r'', include('django.contrib.staticfiles.urls')),\n )\n","sub_path":"pkgrover/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"332042369","text":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function\nimport csv\nimport unicodedata as ud\n\nimport xml.etree.cElementTree as ET\nimport lxml.etree as LXML_ET\n\n\nclass Abstract:\n \"\"\"Stores information about title, content, authors and track of the abstract.\"\"\"\n\n def __init__(self, title, content, authors, track):\n \"\"\"Class constructor.\"\"\"\n self.title = title\n self.content = content\n self.authors = authors\n self.track = track\n\n\nclass Person:\n \"\"\"Stores information about first name, family name, email and affiliation\n of a person.\"\"\"\n\n def __init__(self, first_name, family_name, email, affiliation, is_primary_author):\n \"\"\"Class constructor.\"\"\"\n self.first_name = first_name\n self.family_name = family_name\n self.email = email\n self.affiliation = affiliation\n self.is_primary_author = is_primary_author\n\ndef create_dict_standarts(csv_file):\n \"\"\"Creates a dictionary from CSV file.\"\"\"\n standarts = {}\n with open(csv_file, encoding='utf-8') as f_obj:\n reader = csv.DictReader(f_obj, delimiter=':')\n for line in reader:\n key = line[\"old_affiliation\"]\n value = line[\"new_affiliation\"]\n standarts[key] = value\n return standarts\n\n\ndef parse_abstracts_xml(abstracts_xmlfilename, csv_file):\n \"\"\" Method for getting structured list containing all the abstracts from XML.\n Every abstract in the list is an object of Abstract class.\n It contains 4 main components:\n 1. Track of abstract\n 2. Title\n 3. List of authors. Every author is an object of Person class\n 4. Abstract itself (content)\n \"\"\"\n tree_abstracts = ET.parse(abstracts_xmlfilename)\n root_abstracts = tree_abstracts.getroot()\n doc_abstracts = LXML_ET.parse(abstracts_xmlfilename)\n count_abstracts = doc_abstracts.xpath('count(//abstract)')\n\n track = \"\"\n title = \"\"\n content = \"\"\n flag = False\n authors = []\n abstracts_list = []\n unknown_affiliations = []\n\n affiliation_standarts = create_dict_standarts(csv_file)\n\n print(\"1. Parsing all abstracts from XML\")\n for i in range(1, int(count_abstracts) + 1):\n for child in root_abstracts[i]:\n if child.tag == \"Title\":\n title = child.text.strip()\n continue\n\n if child.tag == \"Content\":\n content = child.text.strip()\n continue\n\n if child.tag == \"PrimaryAuthor\" or child.tag == \"Co-Author\":\n # Bringing different affiliations to the same standard\n affiliation = str(child[3].text).strip()\n # If affiliation is in standards - bring affiliation to standard\n if affiliation in affiliation_standarts:\n affiliation = affiliation_standarts[affiliation]\n else:\n unknown_affiliations.append(affiliation)\n\n\n primary_author = Person(first_name=str(child[0].text),\n family_name=str(child[1].text),\n email=str(child[2].text),\n affiliation=affiliation,\n is_primary_author=True if child.tag == \"PrimaryAuthor\" else False)\n authors.append(primary_author)\n continue\n\n if child.tag == \"Track\" and not flag:\n track = child.text\n flag = True\n continue\n\n abstract = Abstract(title, content, authors, track)\n abstracts_list.append(abstract)\n authors = []\n flag = False\n\n # Print unknown affiliations\n unknown_affiliations = list(set(unknown_affiliations))\n print(\"2. The following affiliations are unknown. Please add them to CSV file with standards.\")\n for affiliation in unknown_affiliations:\n print(affiliation)\n print(\"==============================================\")\n\n return abstracts_list\n\ndef get_language_of_string(input_string):\n # Threshold to determine language\n # If the ratio of one symbols required to define language.\n THRESHOLD = 0.6\n\n alphabet = {\n 'LATIN': 0,\n 'CYRILLIC': 0\n }\n\n for symbol in input_string:\n try:\n if 'LATIN' in ud.name(symbol):\n alphabet['LATIN'] += 1\n if 'CYRILLIC' in ud.name(symbol):\n alphabet['CYRILLIC'] += 1\n except ValueError:\n # If it is TAB\n if ord(symbol) == 9:\n continue\n # If it is New Line\n if ord(symbol) == 10:\n continue\n print(str(symbol) + \"symbol not found. Code: \" + str(ord(symbol)))\n\n if alphabet['LATIN'] == 0 and alphabet['CYRILLIC'] == 0:\n return \"NONE\"\n\n if alphabet['LATIN'] / (alphabet['CYRILLIC'] + alphabet['LATIN'])> THRESHOLD:\n return \"LATIN\"\n\n if alphabet['CYRILLIC'] / (alphabet['CYRILLIC'] + alphabet['LATIN'])> THRESHOLD:\n return \"CYRILLIC\"\n\n return \"MIXED\"\n\ndef check_abstracts_consistency(abstracts):\n for abstract in abstracts:\n\n # Check language consistency\n languages = {}\n languages['Title'] = get_language_of_string(abstract.title)\n languages['Content'] = get_language_of_string(abstract.content)\n for i in range(len(abstract.authors)):\n languages['Author' + str(i) + \"_Name\"] = get_language_of_string(abstract.authors[i].first_name + abstract.authors[i].family_name)\n languages['Author' + str(i) + \"_Affiliation\"] = get_language_of_string(abstract.authors[i].affiliation)\n\n languages_set = set(languages.values())\n if 'NONE' in languages_set:\n languages_set.remove('NONE')\n if len(languages_set) != 1:\n print(\"More than one language is used in abstract: \" + abstract.title)\n from pprint import pprint as pp\n pp(languages)\n","sub_path":"src/abstracts.py","file_name":"abstracts.py","file_ext":"py","file_size_in_byte":5968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"4448116","text":"import os\nfrom collections import namedtuple\nfrom typing import Any, Callable, Optional, Tuple\nfrom torch.utils.data import Dataset\nfrom PIL import Image\n\n\nclass Cityscapes(Dataset):\n \"\"\"`\n Cityscapes Dataset http://www.cityscapes-dataset.com/\n Labels based on https://github.com/mcordts/cityscapesScripts/blob/master/cityscapesscripts/helpers/labels.py\n \"\"\"\n CityscapesClass = namedtuple('CityscapesClass', ['name', 'id', 'train_id', 'category', 'category_id',\n 'has_instances', 'ignore_in_eval', 'color'])\n\n labels = [\n CityscapesClass('unlabeled', 0, 255, 'void', 0, False, True, (0, 0, 0)),\n CityscapesClass('ego vehicle', 1, 255, 'void', 0, False, True, (0, 0, 0)),\n CityscapesClass('rectification border', 2, 255, 'void', 0, False, True, (0, 0, 0)),\n CityscapesClass('out of roi', 3, 255, 'void', 0, False, True, (0, 0, 0)),\n CityscapesClass('static', 4, 255, 'void', 0, False, True, (0, 0, 0)),\n CityscapesClass('dynamic', 5, 255, 'void', 0, False, True, (111, 74, 0)),\n CityscapesClass('ground', 6, 255, 'void', 0, False, True, (81, 0, 81)),\n CityscapesClass('road', 7, 0, 'flat', 1, False, False, (128, 64, 128)),\n CityscapesClass('sidewalk', 8, 1, 'flat', 1, False, False, (244, 35, 232)),\n CityscapesClass('parking', 9, 255, 'flat', 1, False, True, (250, 170, 160)),\n CityscapesClass('rail track', 10, 255, 'flat', 1, False, True, (230, 150, 140)),\n CityscapesClass('building', 11, 2, 'construction', 2, False, False, (70, 70, 70)),\n CityscapesClass('wall', 12, 3, 'construction', 2, False, False, (102, 102, 156)),\n CityscapesClass('fence', 13, 4, 'construction', 2, False, False, (190, 153, 153)),\n CityscapesClass('guard rail', 14, 255, 'construction', 2, False, True, (180, 165, 180)),\n CityscapesClass('bridge', 15, 255, 'construction', 2, False, True, (150, 100, 100)),\n CityscapesClass('tunnel', 16, 255, 'construction', 2, False, True, (150, 120, 90)),\n CityscapesClass('pole', 17, 5, 'object', 3, False, False, (153, 153, 153)),\n CityscapesClass('polegroup', 18, 255, 'object', 3, False, True, (153, 153, 153)),\n CityscapesClass('traffic light', 19, 6, 'object', 3, False, False, (250, 170, 30)),\n CityscapesClass('traffic sign', 20, 7, 'object', 3, False, False, (220, 220, 0)),\n CityscapesClass('vegetation', 21, 8, 'nature', 4, False, False, (107, 142, 35)),\n CityscapesClass('terrain', 22, 9, 'nature', 4, False, False, (152, 251, 152)),\n CityscapesClass('sky', 23, 10, 'sky', 5, False, False, (70, 130, 180)),\n CityscapesClass('person', 24, 11, 'human', 6, True, False, (220, 20, 60)),\n CityscapesClass('rider', 25, 12, 'human', 6, True, False, (255, 0, 0)),\n CityscapesClass('car', 26, 13, 'vehicle', 7, True, False, (0, 0, 142)),\n CityscapesClass('truck', 27, 14, 'vehicle', 7, True, False, (0, 0, 70)),\n CityscapesClass('bus', 28, 15, 'vehicle', 7, True, False, (0, 60, 100)),\n CityscapesClass('caravan', 29, 255, 'vehicle', 7, True, True, (0, 0, 90)),\n CityscapesClass('trailer', 30, 255, 'vehicle', 7, True, True, (0, 0, 110)),\n CityscapesClass('train', 31, 16, 'vehicle', 7, True, False, (0, 80, 100)),\n CityscapesClass('motorcycle', 32, 17, 'vehicle', 7, True, False, (0, 0, 230)),\n CityscapesClass('bicycle', 33, 18, 'vehicle', 7, True, False, (119, 11, 32)),\n CityscapesClass('license plate', -1, -1, 'vehicle', 7, False, True, (0, 0, 142)),\n ]\n\n \"\"\"Normalization parameters\"\"\"\n mean = (0.485, 0.456, 0.406)\n std = (0.229, 0.224, 0.225)\n\n \"\"\"Useful information from labels\"\"\"\n ignore_in_eval_ids, label_ids, train_ids, train_id2id = [], [], [], [] # empty lists for storing ids\n color_palette_train_ids = [(0, 0, 0) for i in range(256)]\n for i in range(len(labels)):\n if labels[i].ignore_in_eval and labels[i].train_id not in ignore_in_eval_ids:\n ignore_in_eval_ids.append(labels[i].train_id)\n for i in range(len(labels)):\n label_ids.append(labels[i].id)\n if labels[i].train_id not in ignore_in_eval_ids:\n train_ids.append(labels[i].train_id)\n color_palette_train_ids[labels[i].train_id] = labels[i].color\n train_id2id.append(labels[i].id)\n num_label_ids = len(set(label_ids)) # Number of ids\n num_train_ids = len(set(train_ids)) # Number of trainIds\n id2label = {label.id: label for label in labels}\n train_id2label = {label.train_id: label for label in labels}\n\n def __init__(self, root: str = \"/home/datasets/cityscapes/\", split: str = \"val\", mode: str = \"gtFine\",\n target_type: str = \"semantic_train_id\", transform: Optional[Callable] = None,\n predictions_root: Optional[str] = None) -> None:\n \"\"\"\n Cityscapes dataset loader\n \"\"\"\n self.root = root\n self.split = split\n self.mode = 'gtFine' if \"fine\" in mode.lower() else 'gtCoarse'\n self.transform = transform\n self.images_dir = os.path.join(self.root, 'leftImg8bit', self.split)\n self.targets_dir = os.path.join(self.root, self.mode, self.split)\n self.predictions_dir = os.path.join(predictions_root, self.split) if predictions_root is not None else \"\"\n self.images = []\n self.targets = []\n self.predictions = []\n\n for city in os.listdir(self.images_dir):\n img_dir = os.path.join(self.images_dir, city)\n target_dir = os.path.join(self.targets_dir, city)\n pred_dir = os.path.join(self.predictions_dir, city)\n for file_name in os.listdir(img_dir):\n target_name = '{}_{}'.format(file_name.split('_leftImg8bit')[0],\n self._get_target_suffix(self.mode, target_type))\n self.images.append(os.path.join(img_dir, file_name))\n self.targets.append(os.path.join(target_dir, target_name))\n self.predictions.append(os.path.join(pred_dir, file_name.replace(\"_leftImg8bit\", \"\")))\n\n def __getitem__(self, index: int) -> Tuple[Any, Any]:\n image = Image.open(self.images[index]).convert('RGB')\n if self.split in ['train', 'val']:\n target = Image.open(self.targets[index])\n else:\n target = None\n if self.transform is not None:\n image, target = self.transform(image, target)\n return image, target\n\n def __len__(self) -> int:\n return len(self.images)\n\n @staticmethod\n def _get_target_suffix(mode: str, target_type: str) -> str:\n if target_type == 'instance':\n return '{}_instanceIds.png'.format(mode)\n elif target_type == 'semantic_id':\n return '{}_labelIds.png'.format(mode)\n elif target_type == 'semantic_train_id':\n return '{}_labelTrainIds.png'.format(mode)\n elif target_type == 'color':\n return '{}_color.png'.format(mode)\n else:\n print(\"'%s' is not a valid target type, choose from:\\n\" % target_type +\n \"['instance', 'semantic_id', 'semantic_train_id', 'color']\")\n exit()\n","sub_path":"src/dataset/cityscapes.py","file_name":"cityscapes.py","file_ext":"py","file_size_in_byte":7253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"335308703","text":"\"\"\"\nThis module implements a LSTM model in PyTorch.\nYou should fill in code into indicated sections.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport torch\nimport torch.nn as nn\n\nclass LSTM(nn.Module):\n\n def __init__(self, seq_length, input_dim, hidden_dim, num_classes,\n batch_size, device):\n\n super(LSTM, self).__init__()\n ########################\n # PUT YOUR CODE HERE #\n #######################\n self._seq_length = seq_length\n self._hidden_dim = hidden_dim\n self._batch_size = batch_size\n self._device = device\n\n embedding_size = 10 # as a starting point\n self.embed = nn.Embedding(input_dim, embedding_size)\n\n # weights\n self.W_gx = nn.Parameter(torch.empty(hidden_dim, embedding_size)) \n self.W_ix = nn.Parameter(torch.empty(hidden_dim, embedding_size)) \n self.W_fx = nn.Parameter(torch.empty(hidden_dim, embedding_size)) \n self.W_ox = nn.Parameter(torch.empty(hidden_dim, embedding_size)) \n\n self.W_gh = nn.Parameter(torch.empty(hidden_dim, hidden_dim)) \n self.W_ih = nn.Parameter(torch.empty(hidden_dim, hidden_dim)) \n self.W_fh = nn.Parameter(torch.empty(hidden_dim, hidden_dim)) \n self.W_oh = nn.Parameter(torch.empty(hidden_dim, hidden_dim)) \n\n self.W_ph = nn.Parameter(torch.empty(num_classes, hidden_dim))\n \n # biases\n self.b_g = nn.Parameter(torch.zeros(hidden_dim, 1))\n self.b_i = nn.Parameter(torch.zeros(hidden_dim, 1))\n self.b_f = nn.Parameter(torch.zeros(hidden_dim, 1))\n self.b_o = nn.Parameter(torch.zeros(hidden_dim, 1))\n\n self.b_p = nn.Parameter(torch.zeros(1, num_classes))\n\n # non-linearity\n self.tanh = nn.Tanh()\n self.sigmoid = nn.Sigmoid()\n\n self.init_weights()\n ########################\n # END OF YOUR CODE #\n #######################\n\n def init_weights(self):\n for name, param in self.named_parameters():\n if name.startswith(\"W_\"):\n nn.init.kaiming_normal_(param, nonlinearity=\"linear\")\n\n def init_states(self): \n self.c = torch.zeros(self._batch_size, self._hidden_dim).to(self._device)\n self.h = torch.zeros(self._batch_size, self._hidden_dim).to(self._device)\n\n def forward(self, x):\n ########################\n # PUT YOUR CODE HERE #\n #######################\n x = x.squeeze() # we don't need the featuer dim, it will always be 1\n self.init_states() # initialise states each time\n\n embed_x = self.embed(x.long())\n\n for t in range(self._seq_length):\n # Eq 4\n x_t = embed_x[:, t]\n g = self.tanh(x_t@self.W_gx.T + self.h@self.W_gh.T + self.b_g)\n # Eq 5\n i = self.sigmoid(x_t@self.W_ix.T + self.h@self.W_ih.T + self.b_i)\n # Eq 6\n f = self.sigmoid(x_t@self.W_fx.T + self.h@self.W_fh.T + self.b_f)\n # Eq 7\n o = self.sigmoid(x_t@self.W_ox.T + self.h@self.W_oh.T + self.b_o)\n\n # Eq 8\n self.c = g * i + self.c * f\n # Eq 9\n self.h = self.tanh(self.c) * o\n\n # Eq 10\n y = self.h@self.W_ph.T + self.b_p\n\n return y # no need for log softmax since using cross entropy\n ########################\n # END OF YOUR CODE #\n #######################\n","sub_path":"assignment_2/2_recurrentnns_gnns/code/Part 1/lstm.py","file_name":"lstm.py","file_ext":"py","file_size_in_byte":3493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"287138259","text":"def process_input_data(input_data, ext, include_list=None, exclude_list=None, output_file=None):\n \"\"\"\n [Unpack directories], validate CL arguments, pass mgen file(s) for further processing, write processed data to file.\n Called from main()\n :param input_data: String representation of either a directory structure containing mgen files or a single mgen file\n :param ext: Optional string representation specifying extension of mgen file(s) to process\n :param include_list: Optional string set of specifications for flow inclusion\n :param exclude_list: Optional string set of specifications for flow exclusion\n :param output_file: Optional string representation specifying the path and filename of the output data\n :returns: Nothing\n \"\"\"\n json_dicts = []\n\n # Check if directory, and validate path if True\n if '/' in input_data:\n validate_input_path(input_data)\n\n # Create the output file if none was specified, otherwise validate what was specified\n if output_file is None:\n output_file = create_output_file(input_data)\n else:\n validate_output_file(output_file)\n\n # Validate exclude list\n if exclude_list is None:\n pass\n else:\n try:\n if not validate_exclude_list(exclude_list):\n raise ValueError(\"Please review --exclude arguments.\")\n except ValueError as errMsg:\n print(errMsg)\n return False\n\n # Validate include list\n if include_list is None:\n pass\n else:\n try:\n if not validate_include_list(include_list):\n raise ValueError(\"Please review --include arguments.\")\n except ValueError as errMsg:\n print(errMsg)\n return False\n\n # Case 1: A single mgen file to be processed was specified\n if os.path.isfile(input_data):\n validate_input_file(input_data)\n # Create a list of dictionaries from mgen file\n json_list = process_mgen_file(input_data, include_list, exclude_list)\n # Merge new list of dictionaries with empty initialization list\n json_dicts = json_dicts + json_list\n # Case 2: A directory structure containing mgen files to be processed was specified\n elif os.path.isdir(input_data):\n subdirs = os.listdir(input_data)\n for d in subdirs:\n for f in glob.glob(\"%s/%s/*%s\" % (input_data, d, ext)):\n if validate_input_file(f):\n # Create a list of dictionaries from mgen file\n json_list = process_mgen_file(f, include_list, exclude_list)\n # Merge new list of dictionaries with previous list of dictionaries\n json_dicts = json_dicts + json_list\n else:\n report_message = (\"File {} was not processed. Please check the error log for more information.\\n\\n\"\n .format(f))\n create_report(report_message)\n continue\n\n # De-duplicate list of merged lists\n json_dicts = deduplicate_json_dicts(json_dicts)\n # Sort json_dicts by ascending ip address\n json_dicts = sorted(json_dicts, key=lambda k: k[\"name\"])\n\n # If json objects were created and the list of dictionaries is not empty, write the list to the output file\n if json_dicts:\n with open(output_file, 'a') as g:\n g.write(json.dumps(json_dicts))\n\n","sub_path":"process_input_data.py","file_name":"process_input_data.py","file_ext":"py","file_size_in_byte":3419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"229834392","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom particles import state_space_models as ssm\nfrom particles import distributions as dists\nimport particles\nimport seaborn as sb\nimport src.features.paris_law_analytical as pla\nfrom particles import smc_samplers as ssp\nimport dill\nfrom datetime import datetime\n\n#delta_N = 1e7\ndelta_N =5.4e7\naf = 5\n\n\ndef get_measurements(true_c,true_m,true_a0,plot = False):\n obj = pla.Cracked_Gear_Tooth(true_a0,true_c,true_m,\"dum\")\n\n cyc_to_fail = obj.cycles_to_failure(true_a0, af)\n\n sol = obj.crack_length_for_cycles(delta_N,cyc_to_fail)\n\n\n N_range = sol[\"t\"]\n a_range = sol[\"y\"][0]\n\n if plot:\n plt.figure()\n plt.scatter(N_range,a_range)\n plt.xlabel(\"Number of cycles\")\n plt.ylabel(\"Crack length [mm]\")\n\n return a_range\n\nclass ParisLaw(ssm.StateSpaceModel):\n \"\"\"\n The state space mode that defines the Paris law\n \"\"\"\n #default_parameters = {'c': 8.5e-11, 'm': 2.7, \"a0\": 1}\n\n def PX0(self): # Distribution of X_0\n return dists.Dirac(loc=self.a0)\n\n def PX(self, t, xp): # Distribution of X_t given X_{t-1}=xp (p=past)\n return dists.Dirac(loc=self.a(self.c, self.m, xp))\n # normally distributed?\n\n def PY(self, t, xp, x): # Distribution of Y_t given X_t=x (and possibly X_{t-1}=xp)\n return dists.Normal(loc=x, scale=self.v)\n\n def a(self, cp, mp, ap):\n delta_a = delta_N*cp*(self.delta_K(ap))**mp\n return ap + delta_N*cp*(self.delta_K(ap+delta_a/2))**mp\n\n def delta_K(self, ap):\n return pla.Stess_Intensity(ap)\n\nrerun_simulation = False# If the simulation in not rerun, an older simulation is simply loaded\nif rerun_simulation:\n # Generate data for the true model parameters\n true_c = 9.12e-11\n true_m = 1.4354\n true_a0 = 0.1\n true_v = 0.05 # Standard deviation of measurement model\n true_model = ParisLaw(c=true_c, m=true_m, a0=true_a0,v=true_v) # actual model, theta = [mu, rho, sigma]\n\n # Simulate from the model 10 data points\n # true_states, data = true_model.simulate(4)\n # data = np.array(data).flatten()\n true_states = get_measurements(true_c,true_m,true_a0)\n print(\"number of measured states \", len(true_states))\n print(\"true EOL \", true_states[-1])\n data = np.random.normal(loc = true_states, scale = true_v)\n data = data#[0:6]#[0:]\n\n # Define a prior\n # This prior has the true parameters as mean\n # prior_dict = {'c': dists.Normal(loc=9.12e-11,scale=1e-11),\n # 'm': dists.Normal(loc = 1.4353, scale = 1e-1),\n # 'a0':dists.Gamma(1/2, 2), # Chi squared with k=1\n # \"v\":dists.Gamma(1/2,2)} # This is chi squared with k=1\n\n # This prior is not exactly the same as the true parameter\n prior_dict = {'c': dists.Normal(loc=8e-11,scale=2e-11),\n 'm': dists.Normal(loc = 1.5, scale = 1e-1),\n 'a0':dists.Gamma(1/2, 2), # Chi squared with k=1\n \"v\":dists.Gamma(1/2,2)} # This is chi squared with k=1\n\n # # This prior is significantly different from the true parameters\n # prior_dict = {'c': dists.Normal(loc=8e-11,scale=1e-11),\n # 'm': dists.Normal(loc = 1.5, scale = 5e-1),\n # 'a0':dists.Gamma(1/2, 2), # Chi squared with k=1\n # \"v\":dists.Gamma(1/2,2)} # This is chi squared with k=1\n\n my_prior = dists.StructDist(prior_dict)\n\n # Run the smc2 inference\n # fk_smc2 = ssp.SMC2(ssm_cls=ParisLaw, data=data, prior=my_prior, init_Nx=1000)#, ar_to_increase_Nx=0.1)\n fk_smc2 = ssp.SMC2(ssm_cls=ParisLaw, data=data, prior=my_prior, init_Nx=5000)#, ar_to_increase_Nx=0.1) #Pf\n # particles\n alg_smc2 = particles.SMC(fk=fk_smc2, N=5000, store_history=True, verbose=True) # Theta_particles\n alg_smc2.run()\n\n alg_smc2.true_model = true_model # Save the true model so it can be used in post processing\n alg_smc2.true_states = true_states # Save the true states so RUL's can be calculated\n\n # Save the result\n with open('run_20201105transe.pkl', 'wb') as f:\n dill.dump(alg_smc2, f)\n\n\n# Load the previously computed data\nwith open('run_20201105transe.pkl', 'rb') as f:\n alg_smc2 = dill.load(f)\n\n\nclass ProcessSmc2Obj(object):\n def __init__(self, smc2obj):\n self.smc2obj = smc2obj\n self.data = self.smc2obj.fk.data\n self.n_data_points = len(self.data)\n self.time_steps = np.arange(self.n_data_points)\n self.Xhist = self.smc2obj.hist.X\n self.true_states = self.smc2obj.true_states\n self.true_model = self.smc2obj.true_model\n self.af = 0.4 # This is the critical crack length\n\n self.pf_particles, self.pf_weights = self.extract_state_particles_and_weights()\n self.kde_status = True\n\n def plot_data(self):\n plt.figure()\n #plt.plot(range(len(self.data)), self.data)\n n_cycles = self.time_steps*delta_N\n plt.scatter(n_cycles, self.data,c=\"k\",marker=\"x\")\n #plt.scatter(range(len(self.data)), self.data,c=\"k\",marker=\"x\")\n plt.xlabel(\"Number of cycles\")\n plt.ylabel(\"Crack length [mm]\")\n plot_sim = False\n if plot_sim:\n true_c = 9.12e-11\n true_m = 1.4354\n true_a0 = 0.1\n true_v = 0.05 # Standard deviation of measurement model\n true_model = ParisLaw(c=true_c, m=true_m, a0=true_a0, v=true_v) # actual model, theta = [mu, rho, sigma]\n true_states, data = true_model.simulate(len(n_cycles))\n data = np.array(data).flatten()\n plt.scatter(n_cycles,data)\n\n self.save_plot_to_directory(\"measured_data\")\n return\n\n def plot_theta_dists(self):\n for parameter in [\"m\",\"c\",\"a0\",\"v\"]:\n plt.figure()\n plt.xlabel(parameter)\n plt.ylabel(\"Probability density\")\n for i in range(self.n_data_points):\n #plt.hist(self.Xhist[i].theta[\"m\"], label=str(i), bins=20, density=True) # Check if this should perhaps\n sb.distplot(self.Xhist[i].theta[parameter],hist_kws={\"density\":True},label = str(i+1),\n kde=self.kde_status)#\n # include weights?\n plt.legend()\n if parameter==\"a0\":\n plt.xlim(0,self.true_model.a0*5)\n plt.axvline(x=self.true_model.a0, color=\"gray\", linestyle=\"--\")\n if parameter==\"v\":\n plt.xlim(0,self.true_model.v*5)\n plt.axvline(x=self.true_model.v, color=\"gray\", linestyle=\"--\")\n plt.xlabel(r\"$\\nu$\")\n if parameter==\"c\":\n plt.axvline(x=self.true_model.c, color=\"gray\", linestyle=\"--\")\n if parameter==\"m\":\n plt.axvline(x=self.true_model.m, color=\"gray\", linestyle=\"--\")\n self.save_plot_to_directory(\"theta_update_\" + parameter)\n return\n\n def extract_state_particles_and_weights(self):\n \"\"\"\n Extract all the particles for the particle filter runs at each timestep and combine them\n :return:\n \"\"\"\n state_particles = []\n state_weights = []\n for i in self.time_steps:\n all_particles_for_timestep = np.array([pf_run.X for pf_run in alg_smc2.hist.X[i].pfs.l]).flatten()\n all_weights_for_timestep = np.array([pf_run.W for pf_run in alg_smc2.hist.X[i].pfs.l]).flatten()\n state_particles.append(all_particles_for_timestep)\n state_weights.append(all_weights_for_timestep)\n\n return np.array(state_particles), np.array(state_weights)\n\n def plot_state_dists(self):\n plt.figure()\n for i in self.time_steps:\n # plt.hist(self.pf_particles[i], bins=20,weights=self.pf_weights[i], density=False, label=str(i))\n ax = sb.distplot(self.pf_particles[i],hist_kws={\"density\":True},label = str(i+1), kde=self.kde_status) # \"\n # weights are not included?\n\n plt.axvline(x=self.true_states[i],color=\"grey\",linestyle=\"--\")\n # using the weights.\n # Should I be\n # using them\n # kde takes long therefore set to False for now\n plt.xlabel(\"Crack length, a [mm]\")\n plt.ylabel(\"Posterior probability density\")\n plt.xlim(0,self.true_states[-1]*1.1)\n plt.legend()\n self.save_plot_to_directory(\"posterior_states\")\n return\n\n def plot_state_estimates_with_time(self):\n state_aves = np.array([np.mean(self.pf_particles[i]) for i in self.time_steps])\n state_sds= np.array([np.std(self.pf_particles[i]) for i in self.time_steps])\n n_cycles = self.time_steps*delta_N\n plt.figure()\n plt.scatter(n_cycles,self.data, marker=\"x\", label=\"Measurements\")\n plt.scatter(n_cycles,self.true_states, marker=\".\", label=\"True crack length\")\n\n plt.plot(n_cycles, state_aves, label=\"Average crack length estimate\")\n factor = 1\n top = state_aves + state_sds*factor\n bot = state_aves - state_sds*factor\n\n plt.fill_between(n_cycles, bot, top, alpha= 0.3, label=\"1 standard deviation\")\n plt.legend()\n plt.xlabel(\"Number of cycles\")\n plt.ylabel(\"crack length (mm)\")\n self.save_plot_to_directory(\"mean_and_sd_states_with_time\")\n\n return\n\n def save_plot_to_directory(self, plot_name):\n path = \"C:\\\\Users\\\\douwm\\\\repos\\\\Hybrid_Approach_To_Planetary_Gearbox_Prognostics\\\\reports\\\\masters_report\" \\\n \"\\\\5_model_callibration\\\\Images\"\n plt.savefig(path + \"\\\\\" + plot_name + datetime.today().strftime('%Y%m%d')+ \"trans.pdf\")\n\n def get_rul_pred_samples(self,t):\n m = self.Xhist[t].theta[\"m\"]\n c = self.Xhist[t].theta[\"c\"]\n a0 = self.Xhist[t].theta[\"a0\"]\n\n n_theta_particles = len(m)\n\n # Randomly select particles (same number as there are theta particles) from the posterior\n a_t = np.random.choice(self.pf_particles[t], n_theta_particles)\n return m, c, a_t\n\n def estimate_rul(self,t):\n # pl = ParisLaw() # Initialize paris law object so SIF's can be computed\n m,c,a_t = self.get_rul_pred_samples(t)\n # print(\"m\",np.average(m))\n # print(\"c\",np.average(c))\n # print(\"a_t\", np.average(a_t))\n\n #delta_K = pl.delta_K(a_t)\n #print(\"dK\", np.average(delta_K))\n #return self.cycles_to_failure(m,c,a_t,delta_K)\n return self.cycles_to_failure(m,c,a_t)\n\n def dadN(self,a,c,m):\n return c*pla.Stess_Intensity(a)**m\n\n def dNda(self, a,c,m):\n return 1/self.dadN(a,c,m)\n\n def cycles_to_failure(self, m, c, a):\n increms = int(1e3) # This gives a good trade off between accuracy and speed\n af = self.true_states[-1] # Actual final crack length\n a_range = np.logspace(np.log10(a), np.log10(af), increms)# Using a non-linear time scale helps with accuracy\n N = 1\n #\n Nlist = [N]\n for i in range(len(a_range) - 1):\n delta_a = a_range[i + 1] - a_range[i] # Calculates the length of the integration increment\n a = a_range[i]\n N = N + self.dNda(a,c,m) * delta_a\n # Nlist.append(N)\n #return a_range, np.array(Nlist)\n return N\n\n def plot_RUL_dists(self):\n \"\"\" Used to show how the RUL posteriors update as more measurements become available\"\"\"\n plt.figure()\n rul_aves = []\n rul_sds = []\n for t in self.time_steps:\n # Estimate the RULs\n # rul_dist = proc_obj.estimate_rul(t)\n rul_dist = self.estimate_rul(t)\n rul_dist = rul_dist[~np.isnan(rul_dist)] # Remove NaNs\n rul_aves.append(np.average(rul_dist))\n rul_sds.append(np.std(rul_dist))\n\n # The the histograms of the RULs\n # plt.hist(rul_dist, label = str(t))#, density=True)\n sb.distplot(rul_dist, hist_kws={\"density\": True}, label=str(t+1), kde=self.kde_status) #\n\n plt.xlabel(\"Cycles to failure\")\n plt.xlim(0,delta_N*len(self.true_states)*1.1)\n plt.ylabel(\"RUL probability density\")\n plt.legend()\n self.save_plot_to_directory(\"rul_dists\")\n\n # # Plot the mean and variance Rul vs actual\n rul_aves = np.array(rul_aves)\n rul_sds = np.array(rul_sds)\n plt.figure()\n n_cycles = self.time_steps*delta_N\n plt.plot(n_cycles, rul_aves, label = \"mean RUL\")\n top = rul_aves + rul_sds\n bot = rul_aves - rul_sds\n plt.fill_between(n_cycles, bot, top, alpha=0.3, label = \"1 standard \\n deviation \\n from mean\")\n\n #Plot the actual RUL\n plt.plot(n_cycles,-n_cycles+ n_cycles[-1],label= \"true RUL\")\n plt.legend()\n plt.xlabel(\"Number of cycles applied\")\n plt.ylabel(\"Remaining number of cycles\")\n self.save_plot_to_directory(\"rul_mean_and_variance\")\n return\n\nproc_obj = ProcessSmc2Obj(alg_smc2)\nproc_obj.plot_data()\nproc_obj.plot_state_dists()\nproc_obj.plot_theta_dists()\nproc_obj.plot_state_estimates_with_time()\nproc_obj.plot_RUL_dists()\n\n# cyc = proc_obj.estimate_rul(3)\n# plt.figure()\n# plt.hist(cyc)\n\n#################\n","sub_path":"notebooks/11_particles_smc2_updated_sifs_and_transition_2020-11-05.py","file_name":"11_particles_smc2_updated_sifs_and_transition_2020-11-05.py","file_ext":"py","file_size_in_byte":13138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"130404886","text":"\"\"\"\nThe canvas is class for storing the 2d grid of colours for tiles. The canvas is\nusually the colours across multiple tiles and then the TileApplier is able to\nextract each tile from the canvas\n\"\"\"\nfrom photons_themes.theme import ThemeColor\n\nimport random\n\n\ndef color_weighting(distances):\n \"\"\"\n Return an array of colors where there is more of a color the closest it is.\n\n distances\n An array of ``(distance, color)`` where distance is a number representing\n how far away the color is.\n \"\"\"\n if not distances:\n return\n\n greatest_distance = max(dist for dist, _ in distances)\n\n for dist, color in distances:\n if dist == 0:\n for _ in range(int(greatest_distance)):\n yield color\n else:\n for _ in range(int(greatest_distance / dist)):\n yield color\n\n\ndef shuffle_point(i, j):\n \"\"\"\n Return a new (i, j) value that is the current (i, j) value plus or minus\n a random amount\n \"\"\"\n newX = random.randint(i - 3, i + 3)\n newY = random.randint(j - 3, j + 3)\n return newX, newY\n\n\nclass Canvas:\n \"\"\"\n This is just a collection of points with methods for interacting with those\n points.\n\n The points are stored as (i, j) in a dictionary. Ideally the points values\n are ``photons_themes.theme.ThemeColor`` objects.\n \"\"\"\n\n def __init__(self):\n self.points = {}\n self.color_func = None\n self.default_color_func = None\n\n def set_color_func(self, color_func):\n \"\"\"\n Add a color func to the canvas\n\n This will override any points that are on the canvas\n on getting those points.\n \"\"\"\n self.color_func = color_func\n\n def set_default_color_func(self, default_color_func):\n \"\"\"\n Add a default color func to the canvas\n\n This will be used when getting points on the canvas that aren't filled.\n \"\"\"\n self.default_color_func = default_color_func\n\n @property\n def width(self):\n \"\"\"\n The distance between the left most x value in the points and the right\n most x value.\n \"\"\"\n if not self.points:\n return 0\n return int(self.max_x - self.min_x + 1)\n\n @property\n def height(self):\n \"\"\"\n The distance between the left most y value in the points and the right\n most y value.\n \"\"\"\n if not self.points:\n return 0\n return int(self.max_y - self.min_y + 1)\n\n @property\n def center(self):\n if not self.points:\n return (0, 0)\n return (int(self.width / 2) + self.min_x, int(self.height / 2) + self.min_y)\n\n @property\n def max_x(self):\n if not self.points:\n return 0\n return max([x for (x, y) in self.points])\n\n @property\n def min_x(self):\n if not self.points:\n return 0\n return min([x for (x, y) in self.points])\n\n @property\n def max_y(self):\n if not self.points:\n return 0\n return max([y for (x, y) in self.points])\n\n @property\n def min_y(self):\n if not self.points:\n return 0\n return min([y for (x, y) in self.points])\n\n def set_all_points_for_tile(self, left_x, top_y, tile_width, tile_height, get_color):\n \"\"\"\n Translates x, y points relative to a single tile to the tile position on the canvas\n\n So let's say a tile is at (10, 2) then get_color will be called with (x, y) from\n 0 to tile_width, 0 to tile_height and those points get translated to start from (10, 2)\n\n NOTE: get_color gets y where higher y means moving down, whereas the coordinates on the canvas\n is higher y means moving up.\n\n So let's say you have a 4 by 4 tile, get_color will be called with the following points:\n\n .. code-block:: none\n\n (0, 0) (1, 0) (2, 0) (3, 0)\n (0, 1) (1, 1) (2, 1) (3, 1)\n (0, 2) (1, 2) (2, 2) (3, 2)\n (0, 3) (1, 3) (2, 3) (3, 3)\n\n And if you have left_x, top_y of (10, 4), it'll set the following points on the canvas:\n\n .. code-block:: none\n\n (10, 4) (11, 4) (12, 4) (13, 4)\n (10, 3) (11, 3) (12, 3) (13, 3)\n (10, 2) (11, 2) (12, 2) (13, 2)\n (10, 1) (11, 1) (12, 1) (13, 1)\n\n if get_color returns None, then no point is set for that turn\n \"\"\"\n for j in range(top_y, top_y - tile_height, -1):\n for i in range(left_x, left_x + tile_width):\n color = get_color(i - left_x, (tile_height - 1) - (j - top_y + tile_height - 1))\n if color is not None:\n self[(i, j)] = color\n\n def add_points_for_tile(self, left_x, top_y, tile_width, tile_height, theme):\n \"\"\"\n Create points on the canvas around where a tile is.\n\n We create an area that's half the tile width/height beyond the boundary\n of the tile.\n\n We also spread the points out in a random manner and try to avoid having\n points next to each other.\n\n Multiple calls to this function will not override existing points on the\n canvas\n \"\"\"\n from_x = int(left_x - tile_width * 1.5)\n to_x = int(left_x + tile_width * 1.5)\n from_y = int(top_y - tile_height * 1.5)\n to_y = int(top_y + tile_height * 1.5)\n\n i = from_x\n while i < to_x:\n j = from_y\n while j < to_y:\n if (i, j) not in self.points:\n if not self.has_neighbour(i, j):\n self[(i, j)] = theme.random()\n j += random.choice([i + 1 for i in range(3)])\n i += random.choice([i + 1 for i in range(3)])\n\n def surrounding_colors(self, i, j):\n \"\"\"\n Return the colors that surround this (i, j) point.\n\n This will only return points that exist.\n \"\"\"\n return [self[(x, y)] for x, y in self.surrounding_points(i, j) if (x, y) in self]\n\n def surrounding_points(self, i, j):\n \"\"\"Return the co-ordinates that are neighbours of this point\"\"\"\n return [\n (i - 1, j + 1),\n (i, j + 1),\n (i + 1, j + 1),\n (i - 1, j),\n (i + 1, j),\n (i - 1, j - 1),\n (i, j - 1),\n (i + 1, j - 1),\n ]\n\n def has_neighbour(self, i, j):\n \"\"\"Return whether there are any points around this (i, j) position\"\"\"\n return any(self.surrounding_colors(i, j))\n\n def shuffle_points(self):\n \"\"\"\n Take all the points and move them around a random amount\n \"\"\"\n new_points = {}\n for (i, j), color in self.points.items():\n new_points[shuffle_point(i, j)] = color\n\n self.points = new_points\n\n def blur(self):\n \"\"\"\n For each point, find the average colour of that point plus all surrounding\n points.\n \"\"\"\n new_points = {}\n for (i, j), original in self:\n colors = [original for _ in range(2)]\n for color in self.surrounding_colors(i, j):\n colors.append(color)\n new_points[(i, j)] = ThemeColor.average(colors)\n self.points = new_points\n\n def blur_by_distance(self):\n \"\"\"\n Similar to blur but will find the 8 closest points as opposed to the 8\n surrounding points.\n \"\"\"\n new_points = {}\n for (i, j), original in self:\n distances = self.closest_points(i, j, 8)\n weighted = list(color_weighting(distances))\n new_points[(i, j)] = ThemeColor.average(weighted)\n self.points = new_points\n\n def points_for_tile(self, left_x, top_y, tile_width, tile_height):\n \"\"\"\n Return a list of 64 hsbk values for this tile\n\n For any point on the tile that doesn't have a corresponding point on the\n canvas return a grey value. This is useful for when we tell the applier\n to not fill in the gaps.\n \"\"\"\n result = []\n grey = ThemeColor(0, 0, 0.3, 3500)\n\n for j in range(top_y, top_y - tile_height, -1):\n for i in range(left_x, left_x + tile_width):\n result.append(self.get((i, j), grey))\n\n return result\n\n def fill_in_points(self, canvas, left_x, top_y, tile_width, tile_height):\n \"\"\"\n Fill in the gaps on this canvas by blurring the points on the provided\n canvas around where our tile is.\n\n We blur by finding the 4 closest points for each point on our tile and\n averaging them.\n \"\"\"\n for j in range(top_y, top_y - tile_height, -1):\n for i in range(left_x, left_x + tile_width):\n distances = canvas.closest_points(i, j, 4)\n weighted = list(color_weighting(distances))\n self[(i, j)] = ThemeColor.average(weighted)\n\n def closest_points(self, i, j, consider):\n \"\"\"\n Return ``[(distance, color), ...]`` for ``consider`` closest points to (i, j)\n \"\"\"\n distances = []\n\n for (x, y), color in self:\n distances.append(((x - i) ** 2 + (y - j) ** 2, color))\n\n def get_key(dc):\n return (dc[0], (dc[1].hue, dc[1].saturation, dc[1].brightness, dc[1].kelvin))\n\n distances = sorted(distances, key=get_key)\n return distances[:consider]\n\n def __iter__(self):\n \"\"\"Yield ``((i, j), color)`` pairs for all our points\"\"\"\n for pair in self.points.items():\n yield pair\n\n def __len__(self):\n \"\"\"Return how many points are in the canvas\"\"\"\n return len(self.points)\n\n def get(self, point, dflt=None):\n \"\"\"\n Get a point or the passed in ``dflt`` value if the point doesn't exist\n\n If this canvas has a default_color_func then dflt is ignored and the\n default_color_func is used instead\n \"\"\"\n if self.color_func:\n return self.color_func(*point)\n if point not in self.points and self.default_color_func:\n return self.default_color_func(*point)\n return self.points.get(point, dflt)\n\n def __getitem__(self, point):\n \"\"\"Return the color at ``point`` where ``point`` is ``(i, j)``\"\"\"\n if self.color_func:\n return self.color_func(*point)\n if point not in self.points and self.default_color_func:\n return self.default_color_func(*point)\n return self.points[point]\n\n def __setitem__(self, key, color):\n \"\"\"Set the color at ``point`` where ``point`` is ``(i, j)``\"\"\"\n self.points[key] = color\n\n def __delitem__(self, key):\n \"\"\"Remove a key from our points\"\"\"\n del self.points[key]\n\n def __contains__(self, point):\n \"\"\"Return whether this ``point`` has a color where ``point`` is ``(i, j)``\"\"\"\n return point in self.points\n","sub_path":"modules/photons_themes/canvas.py","file_name":"canvas.py","file_ext":"py","file_size_in_byte":10868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"14340008","text":"from tkinter import *\nimport random\nimport time\n\nWIDTH = 800\nHEIGHT = 600\n\n# color_lst = ['red', 'blue', 'green', 'yellow', 'orange',\n# 'purple', 'cyan', 'magenta', 'pink']\n\ncolors = ['red', 'blue', 'green', 'yellow',\n 'orange', 'pink', 'cyan', 'magenta',\n 'black', 'brown', 'gold', 'violet',\n 'goldenrod', 'powder blue', 'steel blue']\n\ntk = Tk()\ncanvas = Canvas(tk, width=WIDTH, height=HEIGHT)\ntk.title(\"Motion\")\ncanvas.pack()\n\nclass Ball:\n def __init__(self, x, y, radius, xspeed, yspeed, color):\n self.shape = canvas.create_oval(x-radius, y-radius, x+radius, y+radius, fill=color)\n self.xspeed = xspeed\n self.yspeed = yspeed\n self.color = color\n\n def move(self):\n pos = canvas.coords(self.shape)\n if pos[3] >= HEIGHT or pos[1] <= 0:\n self.yspeed *= -1\n canvas.itemconfig(self.shape, fill=random.choice(colors))\n if pos[0] <= 0 or pos[2] >= WIDTH:\n self.xspeed *= -1\n canvas.itemconfig(self.shape, fill=random.choice(colors))\n\n canvas.move(self.shape, self.xspeed, self.yspeed)\n\n\nballs = []\nfor i in range(150):\n ball = Ball(random.randrange(100, WIDTH-100),\n random.randrange(100, HEIGHT-100),\n random.randrange(10, 40),\n random.randrange(-5,5),\n random.randrange(-5,5),\n random.choice(colors))\n\n balls.append(ball)\n\nwhile True:\n for b in balls:\n b.move()\n # 'pos' is a list of four coordinates: first two for the upper left\n # corner of the bounding box of the canvas and the last two for\n # the lower right corner of the canvas bounding box.\n\n tk.update()\n time.sleep(0.01)\n\ncanvas.mainloop()\n","sub_path":"Python/tkinter_example_3.py","file_name":"tkinter_example_3.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"361962582","text":"import pygame\r\nfrom logica.LogicaCamino import LogicaCamino\r\nfrom logica.LogicaJugador import LogicaJugador\r\nfrom logica.LogicaDificultad import LogicaDificultad\r\nfrom logica.LogicaObstaculo import LogicaObstaculo\r\nfrom logica.LogicaBillete import LogicaBillete\r\nfrom logica.LogicaPuntaje import LogicaPuntaje\r\n\r\nclass Graficos(object):\r\n\t\r\n\t\"\"\" Esta clase controla toda la parte grafica del juego\"\"\"\r\n\tpygame.init()\r\n\t\r\n\tventana = pygame.display.set_mode((640,384))\r\n\r\n\t\"\"\" Objetos \"\"\"\r\n\tLogicaCamino = LogicaCamino(0)\r\n\tLogicaJugador = LogicaJugador(16)\r\n\tLogicaObstaculo = LogicaObstaculo()\r\n\tLogicaBillete = LogicaBillete()\r\n\tLogicaPuntaje = LogicaPuntaje()\r\n\r\n\t\"\"\"Fuentes\"\"\"\r\n\tFUENTE = pygame.font.Font(\"recursos/fuentes/orange_juice.ttf\",40)\r\n\tFUENTE2 = pygame.font.Font(\"recursos/fuentes/Jelly_Crazies.ttf\",15)\r\n\tFUENTE3 = pygame.font.Font(\"recursos/fuentes/Jelly_Crazies.ttf\",30)\r\n\r\n\tPERDISTE = FUENTE3.render('PERDISTE', True, (200,100,100))\r\n\tPUNTAJE = FUENTE2.render('PUNTAJE', True, (250,250,250))\r\n\tPUNTAJEMAX = FUENTE2.render('TU RECORD', True, (250,250,250))\r\n\r\n\t\"\"\" Imagenes que va a utilizar el juego\"\"\"\r\n\tLOGO = pygame.image.load(\"recursos/botones/logo.png\")\r\n\tVACIO = pygame.image.load(\"recursos/botones/vacio.png\")\r\n\tCONFIGURAR = pygame.image.load(\"recursos/botones/configurar.png\")\r\n\tPAUSA = pygame.image.load(\"recursos/botones/pausa.png\")\r\n\tTRANSPARENTE = pygame.image.load(\"recursos/fondo/gris.png\")\r\n\r\n\tJUGADOR_1 = pygame.image.load(\"recursos/personaje/1.png\")\r\n\tJUGADOR_2 = pygame.image.load(\"recursos/personaje/2.png\")\r\n\tJUGADOR_3 = pygame.image.load(\"recursos/personaje/3.png\")\r\n\tJUGADOR_4 = pygame.image.load(\"recursos/personaje/4.png\")\r\n\tJUGADOR_5 = pygame.image.load(\"recursos/personaje/5.png\")\r\n\tJUGADOR_6 = pygame.image.load(\"recursos/personaje/6.png\")\r\n\tJUGADOR_7 = pygame.image.load(\"recursos/personaje/7.png\")\r\n\tJUGADOR_8 = pygame.image.load(\"recursos/personaje/8.png\")\r\n\r\n\tFONDO = pygame.image.load(\"recursos/fondo/fondo.png\")\r\n\tCAMINO = pygame.image.load(\"recursos/fondo/camino.png\")\r\n\r\n\tBARRERA = pygame.image.load(\"recursos/obstaculos/barrera.png\")\r\n\tCONO = pygame.image.load(\"recursos/obstaculos/cono.png\")\r\n\r\n\tBILLETE_1 = pygame.image.load(\"recursos/billete/1.png\")\r\n\tBILLETE_2 = pygame.image.load(\"recursos/billete/2.png\")\r\n\tBILLETE_3 = pygame.image.load(\"recursos/billete/3.png\")\r\n\tBILLETE_4 = pygame.image.load(\"recursos/billete/4.png\")\r\n\tBILLETE_5 = pygame.image.load(\"recursos/billete/5.png\")\r\n\t\r\n\tdef __init__(self, estado):\r\n\t\tself.estado = estado\r\n\t\tself.sprites_Jugador = [Graficos.JUGADOR_1,Graficos.JUGADOR_2,Graficos.JUGADOR_3,Graficos.JUGADOR_4,Graficos.JUGADOR_5,Graficos.JUGADOR_6,Graficos.JUGADOR_7,Graficos.JUGADOR_8]\r\n\t\tself.sprites_Billete = [Graficos.BILLETE_1,Graficos.BILLETE_2,Graficos.BILLETE_3,Graficos.BILLETE_4,Graficos.BILLETE_5,Graficos.BILLETE_4,Graficos.BILLETE_3,Graficos.BILLETE_2]\r\n\t\tself.sprites_Logo = [Graficos.LOGO, Graficos.VACIO]\r\n\t\tself.obstaculos = [(640,296)]\r\n\t\tself.billetes = [(650,140)]\r\n\t\tself.puntaje = 0\r\n\t\tself.maxpuntaje = 0\r\n\t\tself.spr = 0\r\n\t\tself.sprvel = 30\r\n\t\tself.colisionObstaculo = False\r\n\t\tself.colisionBillete = False\r\n\t\r\n\tdef pintarLogo(self, click):\r\n\t\tif click:\r\n\t\t\tsprite = self.sprite()\r\n\t\t\tGraficos.ventana.blit(self.sprites_Logo[sprite],(192,128))\t\r\n\t\telse:\r\n\t\t\tGraficos.ventana.blit(self.sprites_Logo[0],(192,128))\r\n\t\t\r\n\t\tGraficos.ventana.blit(Graficos.CONFIGURAR,(600,8))\r\n\r\n\tdef sprite(self):\r\n\t\tif self.sprvel == 0:\r\n\t\t\tif self.spr == 0:\r\n\t\t\t\tself.spr += 1\r\n\t\t\telif self.spr == 1:\r\n\t\t\t\tself.spr = 0\r\n\t\t\tself.sprvel = 30\r\n\t\telse:\r\n\t\t\tself.sprvel -= 1\r\n\r\n\t\treturn self.spr\r\n\r\n\tdef pintarFondo(self):\r\n\t\tGraficos.ventana.blit(Graficos.FONDO,(0,-100))\r\n\r\n\tdef\tpintarCamino(self):\r\n\t\tif self.estado == 1:\r\n\t\t\tposX = Graficos.LogicaCamino.getPos()\r\n\t\t\tGraficos.ventana.blit(Graficos.CAMINO,(posX[0],128))\r\n\t\t\tGraficos.ventana.blit(Graficos.CAMINO,(posX[1],128))\r\n\r\n\t\telif self.estado == 2:\r\n\t\t\tposX = Graficos.LogicaCamino.getPos()\r\n\t\t\tGraficos.ventana.blit(Graficos.CAMINO,(posX[0],128))\r\n\t\t\tGraficos.ventana.blit(Graficos.CAMINO,(posX[1],128))\r\n\r\n\t\telif self.estado == 3:\r\n\t\t\tGraficos.ventana.blit(Graficos.CAMINO,(0,128))\r\n\r\n\tdef pintarPuntaje(self):\r\n\t\tself.puntaje, self.maxpuntaje = Graficos.LogicaPuntaje.getPuntaje(self.colisionObstaculo)\r\n\t\tscore = Graficos.FUENTE2.render(str(self.puntaje), True, (255,255,255))\r\n\t\tGraficos.ventana.blit(score,(10,10))\r\n\r\n\tdef pintarPersonaje(self, saltar):\r\n\t\tif saltar == False:\r\n\t\t\tsprite = Graficos.LogicaJugador.getSprite()\r\n\t\t\tGraficos.ventana.blit(self.sprites_Jugador[sprite], (32,200))\r\n\t\telif saltar == True:\r\n\t\t\tsalto = Graficos.LogicaJugador.getSalto()\r\n\t\t\tGraficos.ventana.blit(self.sprites_Jugador[5], (32,salto[0]))\r\n\t\t\treturn salto[1]\r\n\r\n\tdef pintarObstaculo(self):\r\n\t\t\"\"\" Llama al metodo de la clase LogicaObstaculo y crear una tupla con la posicion en 'x' y 'y' y se agrega a una lista con todas las posiciones de cada obstaculo\"\"\"\r\n\t\tself.obstaculos = Graficos.LogicaObstaculo.crearObstaculo(self.obstaculos)\r\n\r\n\t\t\"\"\"Este ciclo se encarga de recorrer la lista e imprimir el obstaculo\"\"\"\r\n\t\tfor element in self.obstaculos:\r\n\t\t\tGraficos.ventana.blit(Graficos.CONO,element)\r\n\r\n\t\t\"\"\"Se modifica la lista restandole a la posicion en 'x' de cada tupla y hace que el obstaculo se mueva\"\"\"\r\n\t\tself.obstaculos = Graficos.LogicaObstaculo.moverObstaculo(self.obstaculos)\r\n\r\n\t\t\"\"\"Se encarga de eliminar los obtaculos cuya posicion en 'x' se pasa del limite\"\"\"\r\n\t\tself.obstaculos = Graficos.LogicaObstaculo.borrarObstaculo(self.obstaculos)\r\n\r\n\r\n\tdef pintarBillete(self):\r\n\t\tsprite = Graficos.LogicaBillete.getSprite()\r\n\r\n\t\tself.billetes = Graficos.LogicaBillete.crearBillete(self.billetes)\r\n\r\n\t\tfor element in self.billetes:\r\n\t\t\tGraficos.ventana.blit(self.sprites_Billete[sprite],element)\r\n\r\n\t\tself.billetes = Graficos.LogicaBillete.moverBillete(self.billetes)\r\n\r\n\t\tself.billetes = Graficos.LogicaBillete.borrarBillete(self.billetes)\r\n\r\n\tdef colisiones(self):\r\n\t\tself.colisionObstaculo = Graficos.LogicaJugador.colisionObstaculo(self.obstaculos)\r\n\r\n\t\tif self.colisionObstaculo:\r\n\t\t\treturn True\r\n\t\telse:\r\n\t\t\treturn False\r\n\r\n\tdef pintarFiltro(self):\r\n\t\tGraficos.ventana.blit(Graficos.TRANSPARENTE,(0,0))\r\n\r\n\tdef pintarPerdiste(self):\r\n\t\tGraficos.ventana.blit(Graficos.PERDISTE,(150,80))\r\n\r\n\tdef puntajeFinal(self):\r\n\t\tscore = Graficos.FUENTE3.render(str(self.puntaje), True, (255,255,255))\r\n\t\tscoremax = Graficos.FUENTE3.render(str(self.maxpuntaje), True, (255,255,255))\r\n\r\n\t\tGraficos.ventana.blit(Graficos.PUNTAJE,(240,160))\r\n\t\tGraficos.ventana.blit(score,(295,190))\r\n\t\tGraficos.ventana.blit(Graficos.PUNTAJEMAX,(220,280))\r\n\t\tGraficos.ventana.blit(scoremax,(295,310))\r\n\r\n","sub_path":"graficos/Graficos.py","file_name":"Graficos.py","file_ext":"py","file_size_in_byte":6626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"289994672","text":"# Start visualization\n\n# Pickled default dict mapping locations (dbpedia links ) to latitude/longitude\n\n# Load default dict locations\n\nfrom collections import defaultdict\nimport pickle\nimport os\n\n\n\ndef set_locations(data_dir):\n\n\t\"\"\"\n\tInput:\n\tname of a directory containing a tsv file with places (str)\n\t\n\tadds all dbpedia links of locations to a set\n\t\n\tOutput:\n\tset of dbpedia links (set)\n\t\"\"\"\n\t\n\tcwd = os.getcwd()\n\tpath_to_data_dir = os.path.join(cwd, data_dir)\n\tpath_to_data_file = os.path.join(path_to_data_dir, 'places.txt.count.tsv')\n\t\n\n\n\n\tlink_set = set()\n\n\twith open (path_to_data_file, 'r', encoding = 'utf-8') as infile:\n\t\tfor number, line in enumerate(infile.readlines()):\n\t\t\tline = line.strip()\n\t\t\tline_list = line.split('\\t')\n\t\t\tlink = line_list[1]\n\t\t\tlink_set.add(link)\n\t\t\t\n\n\treturn link_set\n\n\n\t\t\n# Write tsv file mapping locations to lat and long:\n\ndef get_locations_data(locations_set):\n\n\t\"\"\"\n\tInput:\n\tset of dbpedia links to locations (set)\n\t\n\tloads a pickled default dict mapping locations to coordinates\n\tcreates a new dictionary containing only the locations in the set and their coordinates\n\t(if a link from the set is not in the pickled dictionary, it is excluded)\n\t\n\tOutput: dictionary mapping links to locations to their coordinates (dict{str: [float, float]})\n\t\n\t\"\"\"\n\t\n\twith open ('cache_entities.bin', 'rb') as infile:\n\t\t\tdict_locations = pickle.load(infile)\n\t\t\n\tmy_locations_dict = dict()\n\t\n\tfor link in locations_set:\n\t\tif link in dict_locations.keys():\n\n\t\t\tdata = dict_locations[link]\n\t\t\n\t\t\tmy_locations_dict[link] = data\n\t\n\treturn my_locations_dict\n\n\n\ndef write_kml(target_dir, locations_dict):\n\n\t\"\"\"\n\tInput:\n\tname of the directory in which the kml file should be saved (str)\n\tdictionary containing dbpedia links to locations and their coordinates (dict{str: [float, float]})\n\t\n\tWrites each dictionary entry to a kml file as an element called 'Placemark'. \n\tSliced the dbpedia links to location names (under )\n\twrites the coordinates under \n\t\n\tOutput: \n\tabsolute path to the kml file (str)\n\t\"\"\"\n\n\tcwd = os.getcwd()\n\ttarget_dir_path = os.path.join(cwd, target_dir)\n\ttarget_file_path = os.path.join(target_dir_path, 'places.kml')\n\t\n\twith open (target_file_path, 'w', encoding = 'utf-8') as kmlfile:\n\t\tkmlfile.write('')\n\t\t\n\t\tkmlfile.write('\\n')\n\t\t\n\t\tfor location, data in locations_dict.items():\n\t\t\tif location.startswith('http://dbpedia.org/resource/'):\n\t\t\t\tlocation = location[28:]\n\t\t\telif location.startswith('http://nl.dbpedia.org/resource/'):\n\t\t\t\tlocation = location[31:]\n\t\t\tlat = str(data[0])\n\t\t\tlong = str(data[1])\n\t\t\tkmlfile.write('\\n')\n\t\t\tkmlfile.write(''+location+'\\n')\n\t\t\tkmlfile.write(''+long+','+lat+',0\\n')\n\t\t\tkmlfile.write('\\n')\n\t\t\n\t\tkmlfile.write('\\n')\n\t\tkmlfile.write('')\n\t\treturn target_file_path\n\n\t\t\n#write_kml('arch_results')\n\ndef compile_kml_file():\n\n\t\"\"\"\n\tInput:\n\t--\n\t\n\tAsks the user to enter the name of the directory containing a tsv file with locations\n\tcompiles a kml file with the locations and their coordinates\n\tAsks the user if they would like to continue (if yes, the user can compile another kml file, \n\totherwise the program is stopped)\n\tPrints the absolute path to the kml file\n\t\n\tOutput:\n\t--\n\t\n\t\"\"\"\n\tcontinue_kml = 'yes'\n\t\n\twhile continue_kml == 'yes':\n\t\n\t\tdata_directory = input('''Please enter the name of the direcotory containing the \n\t\tlocations of the MA program you would like to visualize (to test: eg 'test_program_results'\n\t\t(depending on what you chose earlier ), check if the kml file appears in you results directory. ''')\n\t\t\n\t\tpath_data = os.path.join(os.getcwd(), data_directory)\n\t\tprint(path_data)\n\t\tpath_locations = os.path.join(path_data, 'places.txt.count.tsv')\n\t\tprint(path_locations)\n\t\t\n\t\n\t\t\n\t\t\n\t\tlocations_set = set_locations(data_directory)\n\t\tlocations_dict = get_locations_data(locations_set)\n\t\tprint(write_kml(data_directory, locations_dict))\n\t\t\n\t\tcontinue_kml = input('Would you like to continue? ')\n\t\ncompile_kml_file()\t\n","sub_path":"locations.py","file_name":"locations.py","file_ext":"py","file_size_in_byte":4085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"112262453","text":"# -*- coding: utf-8 -*-\nfrom __future__ import division\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\n\n\"\"\"\npython-aselect\n~~~~~~~~~~~\nImplements A-Select API support for Python\n\n:copyright: (c) 2013 by Jonas Teuwen\n:license: BSD, see LICENSE for more details.\n\n\n===TODO===\n - Do we need the properties on the objects?\n E.g., kill_ticket on User or Ticket objects.\n\"\"\"\nfrom flask import (current_app,\n session,\n redirect)\nfrom werkzeug.local import LocalProxy\nfrom werkzeug.datastructures import ImmutableDict\n\n\nfrom flask.ext.aselect.aselectapi import config\nimport logging\nlogger = logging.getLogger('ASelectAPI')\n\nfrom flask.ext.aselect.aselectapi import utils\n\ntry:\n from urllib.parse import urlencode\nexcept ImportError:\n from urllib import urlencode\n\nimport hashlib\nimport simplejson as json\nimport base64\nfrom datetime import datetime\nimport six\n\nRESULT_CODE = {\n '0000':\"Success\", # Implemented\n '0101':\"Internal error; the A-Select Agent could not handle the request due to an internal error. The system logging should contain detailed messages indicating the error.\", # 0\n '0102':\"Agent session expired; the retrieved session ID corresponds to a session that has expired. This error occurs when a request is issued to the A-Select Agent containing a RID corresponding to a session that has already been cleaned.\", # 0\n '0109':\"User's ticket is not valid. This error occurs when the submitted user id and/or organization ID do not match the user and/or organization in the Agent ticket context.\", # 0\n # '010a':\"User's ticket has expired. This error occurs if the submitted ticket has been expired at the Agent. Note: This error is currently not supported because the A-Select Agent does not make a difference between tickets that have been removed and tickets that are unknown. In both cases the A-Select Agent returns the \\\"010b\\\" error code.\",\n '010b':\"Unknown ticket. This error occurs if the A-Select Agent does not know the submitted ticket.\", # 0\n '010c':\"A-Select Agent could not reach A-Select Server. This is a commonly used error for communication problems the A-Select Server.\", # 0\n '010d':\"Maximum number of issued tickets has been reached. This error is returned when the A-Select Agent has reached the maximum of tickets.\", # 0\n '010e':\"Attributes mismatch. This error occurs during the verify ticket request when the received attributes do not match stored attributes.\", # Implemented\n '0130':\"This error occurs when an invalid request is sent to the A-Select Agent.\", # 0\n '0140':\"Indicates that a user is not authorized to access the application the user is authenticated for.\", # 0\n '0141':\"Indicates that A-Select Authorization is not enabled in the Agent.\" # 0\n}\n\nREQUESTS_RETURN_USER = [\n u'verify_credentials',\n u'attributes',\n]\nFAILED_REQUESTS = [\n '0101', '0102',\n '0109', '010b',\n '010c', '010d',\n '0130', '0140',\n '0141'\n]\n# Set authorization rules not implemented\n\nclass ASelectAPIError(Exception):\n \"\"\"Base application error class.\"\"\"\n\n def __init__(self, msg):\n self.msg = msg\n\nclass ASelectAgentError(Exception):\n \"\"\"Raise when an error in the A-Select agent occurs.\"\"\"\n\n def __init__(self, errors=None):\n self.errors = errors\n\n\n\"\"\"\nclass ASelectAPI: Class to filter requests to A-Select Agent\n\n===parameters===\n:param app_id: Application ID that has been registered\n with the A-Select Server.\n\"\"\"\nclass ASelectAPI(object):\n def __init__(self):\n self.logger = logging.getLogger('ASelectAPI')\n self.logger.debug('ASelectAPI initialized')\n\n\n \"\"\"\n auth_user(): Request an authentication of a user\n\n ===parameters===\n :param app_url: Full URL to redirect to after authentication\n has succeeded.\n :param user_id: (Optional) User name to authenticate with. If\n supplied, the A-Select user form is omitted.\n :param forced_logon: (Optional) Either true/false.\n True if authentication must be forced.\n\n ===return values===\n :ret as_url: URL to the A-Select Server to redirect to.\n :ret rid: Request identifier. Appended to as_url.\n\n Warning: param remote_organization for cross\n authentication is not implemented.\n \"\"\"\n def auth_user(self, app_id, app_url, aselect_id=None, forced_logon='true'):\n self.logger.debug(\"ASelectAPI.auth_user()\")\n if not app_id:\n raise ASelectAPIError('auth_user(): app_id not set')\n if not app_url:\n raise ASelectAPIError('auth_user(): app_url not set')\n request = Request()\n # Initialize request\n request.aselect_request = 'authenticate'\n request.input_data['app_id'] = app_id\n # Request parameters for authentication\n request.input_data['app_url'] = app_url\n\n # Try/assert\n if aselect_id:\n request.input_data['aselect_id'] = aselect_id\n if forced_logon in ['true', 'false']:\n request.input_data['forced_logon'] = forced_logon\n else:\n raise ASelectAPIError('auth_user(): forced_logon bad input')\n response = request.get_response()\n if not response.status:\n raise ASelectAgentError(\n 'auth_user(): A-Select Agent returned fail.')\n data = response.data\n # Process reply\n if data.get('rid') and data.get('a-select-server'):\n params = {'rid': data.pop('rid'),\n 'a-select-server': data.pop('a-select-server')}\n # urlencode() safe quotes key, value already so no\n # need to do that.\n authenticate_url = data.pop('as_url') + '&' + \\\n urlencode(params)\n if data:\n raise ASelectAPIError('auth_user(): too many keys in data')\n return authenticate_url\n else:\n raise ASelectAPIError(\n 'auth_user(): no rid and/or a-select-server in data')\n\n \"\"\"\n verify_credentials(): Verify user credentials with A-Select Agent.\n If successful, will provide a ticket.\n\n ===parameters===\n :param rid: Request identifier.\n :param credentials: The user's A-Select credentials.\n\n ===return values===\n :ret ticket: The ticket which was issued by the A-Select\n server. Instance of .\n :ret attributes: (Optional) Complete set of attributes.\n Instance of .\n :ret organization: The organization the user belongs to.\n :ret authsp_level: Numeric level of the authentication mechanism\n that the user was authenticated with.\n\n Note: If no attributes are available the attributes\n are set as `None`.\n Warning: Reply stripped of asp_level\n and asp as these are only use for backwards\n compatibility with A-Select 1.4\n \"\"\"\n def verify_credentials(self, rid, aselect_cred):\n self.logger.debug(\"ASelectAPI.verify_credentials()\")\n if not (rid and aselect_cred):\n raise ASelectAPIError(\n 'verify_credentials(): rid and aselect_cred must both be set.')\n\n\n request = Request()\n request.aselect_request = 'verify_credentials'\n request.input_data['rid'] = rid\n request.input_data['aselect_credentials'] = aselect_cred\n\n response = request.get_response()\n return response\n\n \"\"\"\n request_attributes(): Request the complete set of attributes\n for the user.\n\n ===parameters===\n :param ticket: A-Select application ticket that was issued\n to the user.\n :param user_id: User name which is authenticated against.\n :param organization: The organization the user belongs to.\n\n ===return values===\n :ret ticket: The ticket which was issued by the A-Select\n server. Instance of .\n :ret attributes: (Optional) Complete set of attributes.\n Instance of .\n :ret organization: The organization the user belongs to.\n :ret authsp:\t Name of the authentication service provider\n that authenticated the user.\n :ret authsp_level: Numeric level of the authentication mechanism\n that the user was authenticated with.\n\n Note: If no attributes are available the attributes\n are set as `None`.\n Warning: Reply stripped of asp_level\n and asp as these are only use for backwards\n compatibility with A-Select 1.4\n \"\"\"\n def request_attributes(self, ticket, aselect_id, aselect_org):\n request = Request()\n request.aselect_request = 'attributes'\n self.logger.debug(\"ASelectAPI.request_attributes()\")\n try:\n request.input_data['ticket'] = ticket.encode('ascii')\n request.input_data['user_id'] = aselect_id\n request.input_data['organization'] = aselect_org\n except:\n # Reset message\n request.input_data = None\n raise ASelectAPIError(\n 'ASelectAPI.get_attributes(): Invalid request, ticket,\\\n use_id and organization must all be set.')\n\n # Get response\n response = request.get_response()\n return response\n\n \"\"\"\n verify_ticket(): Request validation of a ticket.\n\n ===parameters===\n :param aselect_id: User name which is authenticated against.\n :param ticket: The ticket which was issued by the A-Select\n server. Instance of .\n :param aselect_org: The organization the user belongs to.\n :param attr_hash: SHA1 hash over previously received \n urlencoded attributes.\n Will give 010e error when not provided\n and available.\n :param ip: (Optional) IP address of the user whose\n ticket is verified.\n :param request_url: (Optional) URI used for authorizing a user.\n\n ===return values===\n :ret attributes: (Optional) Complete set of attributes.\n Instance of .\n Note: :ip: This can be an IPv4 or IPv6 address. If send,\n the IP address is added to the authorization\n attributes.\n Note: :request_url: Only authorization rules conform with this\n URI and rules without a URI are evaluated.\n If omitted, the authorization rules with URI\n are ignored.\n\n On error: When response succesful, the user credentials\n are still valid. On error, application should\n take measures.\n Note: Only if attr_hash verification failed, this\n parameter contains the complete set of\n attributes. Instance of\n .\n \"\"\"\n def verify_ticket(self, aselect_id, ticket, aselect_org, attr_hash):\n request = Request()\n request.aselect_request = 'verify_ticket'\n self.logger.debug(\"ASelectAPI.verify_ticket()\")\n try:\n request.input_data['uid'] = aselect_id\n request.input_data['ticket'] = ticket.encode('ascii')\n request.input_data['organization'] = aselect_org\n except:\n raise ASelectAPIError('ASelectAPI.verify_ticket(): ticket, aselect_id and \\\n aselect_org must all be set.')\n # Not implemented\n pcURI = ''\n pcRemoteIP = ''\n\n # Verify if proper hash?\n\n # Attributes should be _ENCODED_ here as input, but no b64 (?)\n request.input_data['attributes_hash'] = attr_hash\n request.input_data['request_uri'] = pcURI\n request.input_data['ip'] = pcRemoteIP\n\n # Send request\n response = request.get_response()\n # this only returns true of false (?), so need result code.\n return response\n\n \"\"\"\n kill_ticket(): Destroys a user's ticket\n\n ===parameters===\n :param user_id: User name which is authenticated against.\n :param ticket: The ticket which was issued by the A-Select\n server. Instance of .\n\n ===return values===\n :ret bool: Returns true/false on succes/fail.\n Instance of .\n On error: When unsuccesful, the application should\n take measures.\n \"\"\"\n def kill_ticket(self, ticket):\n self.logger.debug(\"ASelectAPI.kill_ticket()\")\n \n request = Request()\n # Initialize request\n request.aselect_request = 'kill_ticket'\n request.input_data['ticket'] = ticket.encode('ascii')\n response = request.get_response()\n if not response.status:\n raise ASelectAPIError('kill_ticket(): could not kill.')\n \n return response.status\n\n def __repr__(self):\n return \"\" % ('None')\n\n\nclass BaseRequest(object):\n def __init__(self):\n self.__input_data = {}\n self.__aselect_request = None\n\n @property\n def aselect_request(self):\n return self.__aselect_request\n\n @aselect_request.setter\n def aselect_request(self, aselect_request_input):\n try:\n assert isinstance(aselect_request_input, six.string_types)\n except:\n raise ASelectAPIError('Request not allowed')\n if utils.allowed_request(aselect_request_input):\n self.__aselect_request = aselect_request_input\n else:\n raise ASelectAPIError('Request not allowed')\n\n @property\n def input_data(self):\n return self.__input_data\n\n @input_data.setter\n def input_data(self, input_data_input):\n self.__input_data = input_data_input\n\n\nclass Request(BaseRequest):\n def __init__(self):\n self.logger = logging.getLogger('ASelectRequest')\n super(Request, self).__init__()\n\n def get_response(self):\n response = Response()\n response.input_data = self.input_data\n response.aselect_request = self.aselect_request\n agent_response = response.call_agent()\n return agent_response\n\n\nclass BaseResponse(object):\n def __init__(self):\n self.__result_code = None\n self.__aselect_request = None\n self.__input_data = None\n\n @property\n def aselect_request(self):\n return self.__aselect_request\n\n @aselect_request.setter\n def aselect_request(self, aselect_request_):\n self.__aselect_request = aselect_request_\n\n @property\n def input_data(self):\n return self.__input_data\n\n @input_data.setter\n def input_data(self, input_data_):\n self.__input_data = input_data_\n\n @property\n def result_code(self):\n return self.__result_code\n \n @result_code.setter\n def result_code(self, result_code):\n self.__result_code = result_code\n\n @property\n def status(self):\n # Three states: 0 (False), 1 (True) or 2.\n # Self-explanatory, except that 2 has extra data attribute.\n if self.result_code == '0000':\n return 1\n\n if self.result_code in FAILED_REQUESTS:\n return 0\n\n if self.result_code == '010e':\n return 2\n \n # Can be more fine grained, not just fail?\n\n\nclass Response(BaseResponse):\n def __init__(self):\n self.logger = logging.getLogger('ASelectResponse')\n super(Response, self).__init__()\n\n def call_agent(self):\n agent_response = utils.call_agent(self.input_data, self.aselect_request)\n self.result_code = agent_response.pop('result_code', None)\n\n if not self.result_code == '0000':\n # Can depend on code what to respond\n logger.debug('Response(): Result code is %s' % self.result_code)\n\n aselect_id = agent_response.pop('uid', None)\n if self.aselect_request in REQUESTS_RETURN_USER and aselect_id:\n return self.init_user(agent_response, aselect_id)\n # Request: verify_ticket\n # Response: Verified object.\n if self.aselect_request == 'verify_ticket':\n # If attributes incorrect will return attributes\n # In this case result_code: 010e\n verified = Verified(data=agent_response, \\\n result_code=self.result_code)\n return verified\n\n self.data = agent_response\n return self\n\n def init_user(self, agent_response, _aselect_id):\n # This can be really nasty if one forgets that this can occur\n # when the user types their netid not in lowercase as the server\n # just returns the caps to our agent.\n # Inane, some things seem to be case sensitive\n aselect_id = _aselect_id\n _user = User(aselect_id, self.aselect_request)\n\n # If User call above works, this should not be needed.\n _user.result_code = self.result_code\n\n # A-Select credentials are combination of:\n # - uid\n # - ticket\n # - organization\n aselect_org = agent_response.pop('organization')\n _user.aselect_org = aselect_org\n\n # Ticket\n ticket = (agent_response.pop('ticket')).encode('ascii')\n ticket_issued = float(agent_response.pop('ticket_start_time'))\n ticket_lifetime = float(agent_response.pop('ticket_exp_time')) - ticket_issued\n\n # Build ticket immutable dictionary.\n aselect_ticket = ImmutableDict({\n 'ticket': ticket,\n 'ticket_issued': int(ticket_issued/1000), #datetime.fromtimestamp(ticket_issued),\n 'ticket_lifetime': int(ticket_lifetime/1000) #datetime.fromtimestamp(ticket_lifetime)\n })\n _user.aselect_ticket = aselect_ticket\n\n # User credentials\n aselect_cred = {\n 'aselect_id': aselect_id,\n 'aselect_ticket': aselect_ticket,\n 'aselect_org': aselect_org,\n }\n\n # Attributes are optional\n aselect_attr_raw = agent_response.pop('attributes', None)\n if aselect_attr_raw:\n aselect_attr, aselect_attr_hash = \\\n utils.attributes_sha1(aselect_attr_raw)\n aselect_attr = utils.attributes_decode(aselect_attr)\n _user.aselect_mail = aselect_attr.pop('mail').lower()\n _user.aselect_attr = ImmutableDict(aselect_attr)\n\n # Add attr_hash to credentials\n aselect_cred.update({'aselect_attr_hash': aselect_attr_hash})\n _user.aselect_cred = ImmutableDict(aselect_cred)\n\n\n # Information not useful for authentication. Could be interesting to log.\n _user.data = agent_response\n return _user\n\n\n# Try to avoid racing conditions. Check state?\nclass User(BaseResponse):\n def __init__(self, aselect_id=None, aselect_request=None):\n self.logger = logging.getLogger('ASelectUser')\n if not (aselect_id and aselect_request):\n self.logger.debug('Bad request, one of aselect_id or \\\n aselect_request not set.')\n return None\n super(User, self).__init__()\n\n self.aselect_id = aselect_id.encode('utf-8')\n self.aselect_request = aselect_request\n\n self.aselect_ticket = None\n self.aselect_cred = None\n\n self.__aselect_org = None\n\n @property\n def aselect_org(self):\n return self.__aselect_org\n\n @aselect_org.setter\n def aselect_org(self, _aselect_org):\n self.__aselect_org = _aselect_org.encode('ascii')\n\n @property\n def aselect_ticket(self):\n return self.__aselect_ticket\n\n @aselect_ticket.setter\n def aselect_ticket(self, _aselect_ticket):\n self.__aselect_ticket = _aselect_ticket\n\n @property\n def aselect_mail(self):\n return self.__email\n \n @aselect_mail.setter\n def aselect_mail(self, _email):\n self.__email = _email.lower()\n\n @property\n def profile(self):\n profile = ImmutableDict({'aselect_mail': self.aselect_mail,\n 'aselect_attributes': self.aselect_attr\n })\n\n return profile\n\n def __repr__(self):\n return '' % (self.aselect_id, self.aselect_mail)\n\n\nclass Verified(BaseResponse):\n def __init__(self, data, result_code):\n super(Verified, self).__init__()\n self.data = data\n self.result_code = result_code\n\n def __repr__(self):\n return '' % (self.status)\n\n","sub_path":"flask_aselect/aselectapi/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":21292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"542244831","text":"import torch\n\ndtype = torch.float\ndevice = torch.device(\"cpu\")\n# device = torch.device(\"cuda:0\") # Uncomment this to run on GPU\n\n# N:batcH size(样本数量)\n# D_in:输入层神经元数量(特征维数)\n# H:隐藏层神经元数量\n# D_out:输出层神经元数量\nN, D_in, H, D_out = 64, 1000, 100, 10\n\n# 输入特征矩阵\nx = torch.randn(N, D_in, device=device, dtype=dtype)\n# 输出结果矩阵\ny = torch.randn(N, D_out, device=device, dtype=dtype)\n\n# 第0层到第1层的权重矩阵\nw1 = torch.randn(D_in, H, device=device, dtype=dtype)\n# 第1层到第2层的权重矩阵\nw2 = torch.randn(H, D_out, device=device, dtype=dtype)\n\n# 学习率\nlearning_rate = 1e-6\n\n# 迭代次数\nfor t in range(500):\n '''前向计算'''\n # 隐藏层的输入\n h = x.mm(w1)\n # 隐藏层的输出\n h_relu = h.clamp(min=0)\n # 输出层的输入/输出\n y_pred = h_relu.mm(w2)\n\n '''平方误差损失函数'''\n loss = (y_pred - y).pow(2).sum().item()\n if t % 100 == 99:\n print(t, loss)\n\n '''反向传播计算损失关于权重的梯度'''\n # loss关于Y_pred的梯度\n grad_y_pred = 2.0 * (y_pred - y)\n # loss关于W2的梯度\n grad_w2 = h_relu.t().mm(grad_y_pred)\n # loss关于H_relu的梯度\n grad_h_relu = grad_y_pred.mm(w2.t())\n # loss关于H的梯度\n grad_h = grad_h_relu.clone()\n grad_h[h < 0] = 0\n # loss关于W1的梯度\n grad_w1 = x.t().mm(grad_h)\n\n '''更新权重'''\n w1 -= learning_rate * grad_w1\n w2 -= learning_rate * grad_w2\n","sub_path":"深度学习/Pytorch示例/code/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"270182091","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.ndimage import gaussian_filter\n\nfrom iccpy.gadget import load_snapshot\nfrom iccpy.gadget.labels import cecilia_labels\nfrom iccpy.gadget.subfind import SubfindCatalogue\nfrom iccpy.utils import match\n\nfrom functions import PCA_matrix, Vcm, grid_maker_SPH, V_i_grid, get_massive\n\n\n# path = '/home/luis/Documents/simus/Aq5/outputs'\npath = '/media/luis/82A8355FA83552C1/CLUES_Gustavo/outputs'\n\nsnap_num = 76 # number of the snapshot to be loaded\nsnap = load_snapshot(directory = path, snapnum = snap_num, label_table = cecilia_labels)\ncat = SubfindCatalogue(path, snap_num, SAVE_MASSTAB=True) # get a catalogue of subhaloes\nnum = 0 #subhalo number (0 for main subhalo)\n# massives = get_massive(snap, cat, 1e11)\n# subh = massives[num]\nsubh = cat.subhalo[num]\n\nsigma = 1\t# standard deviation for gaussian filter\nresolution = 50\nbox_size = .050\n\nV_res = 30 # The resolution for the velocity arrows\narrow_grid = np.arange(-box_size/2, box_size/2, box_size/V_res)\n\nsmooth = 'n' # input('Do you want to smooth? (y / n)\t\t')\nsave = 'n' #input('Do you want to save the projections? (y / n)\t\t')\ncolormap = 'jet'\n\n\n# We make a list for each grid containing the component and the 2 axis:\n# gas_xy, gas_xz, gas_y_z, stars_xy, stars_xz, stars_yz\nprojections = [\n\t\t[0, 1, 0],\n\t\t[0, 2, 0],\n\t\t[0, 2, 1],\n\t\t[4, 1, 0],\n\t\t[4, 2, 0],\n\t\t[4, 2, 1],\n]\n\naxis_labels = [\n\t\t\t'x (kpc)',\n\t\t\t'y (kpc)',\n\t\t\t'z (kpc)',\n]\n\nfig, axes = plt.subplots(2, 3, dpi=300, figsize=(19.2, 12.8))\nimages = []\n\nfor proj, ax in zip(projections, np.concatenate(axes)):\n # Mass projection in solar masses:\n subfind = False\n rho = grid_maker_SPH(snap, subh, 'MASS', proj[0], proj[1], proj[2], box_size, resolution, subfind)\n # Turn into solar masses per kpc^2:\n rho = rho / (box_size**2 / resolution**2)\n\n if smooth == 'y':\n \trho = gaussian_filter(rho, sigma)\n rho = np.log10(rho)\n # We fix null densities (-inf logarithms):\n rho[rho < -10000] = np.min(rho[rho > -10000])\n # We make the velocity arrows (X and Y stand for the axis1 and axis2 in this particular projection, not actually for x and y):\n X, Y = np.meshgrid(arrow_grid, arrow_grid)\n vel_stars_X = V_i_grid(snap, subh, proj[0], proj[1], proj[2], box_size, V_res, proj[2])\n vel_stars_Y = V_i_grid(snap, subh, proj[0], proj[1], proj[2], box_size, V_res, proj[1])\n\n vmax = np.max(rho) # Stars reach higher densities\n # vmin = vmax - 5\n vel_max = np.max(np.sqrt(vel_stars_X**2 + vel_stars_Y**2))\n\n\n ax.imshow(rho, cmap = colormap, extent=(-box_size/2, box_size/2, -box_size/2, box_size/2), vmax=vmax)\n ax.set_xlabel(axis_labels[proj[2]])\n ax.set_ylabel(axis_labels[proj[1]])\n # ax.quiver(X, Y, vel_stars_X, vel_stars_Y, scale=5*box_size/V_res * vel_max)\n\nplt.tight_layout()\n\nplt.show()\n\n\n\"\"\"\nif save == 'y':\n\tif smooth == 'y':\n\t\tplt.savefig('/home/luis/Pictures/Tesis/Aq_subh0_rho%s_smoothed.png' %component, bbox_inches='tight')\n\telse:\n\t\tplt.savefig('/home/luis/Pictures/Tesis/Aq_subh0_rho%s.png' %component, bbox_inches='tight')\n\"\"\"\n#plt.savefig('/home/luis/Pictures/Tesis/Aq_subh0_rho_both.png', bbox_inches='tight')\n\n# plt.figure()\n\n# plt.colorbar(im4, orientation='horizontal')\n# plt.xlabel(r'$log(\\rho)\\ [M_{\\odot}\\ /\\ kpc^2]$', fontsize=20)\n# plt.tight_layout()\n\n# plt.show()\n","sub_path":"plot_rho_proj.py","file_name":"plot_rho_proj.py","file_ext":"py","file_size_in_byte":3321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"119009058","text":"#!/usr/bin/env python\nimport cv2\nimport glob\nimport random\nimport argparse\nimport numpy as np\n\nparser = argparse.ArgumentParser(description='Crop a sheildbox from a picture of a Powerboard')\nparser.add_argument('input' ,help='Path to images of Powerboards')\nparser.add_argument('output',help='Path where the results will be saved')\n\nargs = parser.parse_args()\n\nread_path = f\"{args.input}/*.JPG\"\n\nfor x in glob.glob(read_path):\n\n image = cv2.imread(x)\n (b, g, r) = cv2.split(image)\n lst = [b, g, r]\n channels = ['b', 'g', 'r']\n images = []\n for c in lst:\n scale_percent = 70 # percent of original size\n width = int(c.shape[1] * scale_percent / 100)\n height = int(c.shape[0] * scale_percent / 100)\n dim = (width, height)\n # resize image\n image = cv2.resize(c, dim, interpolation = cv2.INTER_AREA)\n #_, image = cv2.threshold(b,125,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)\n images.append(image)\n\n #for i in range(len(images)):\n #cv2.imshow(channels[i] + \"_thresh\", images[i])\n\n _, b_thresh = cv2.threshold(images[0],125,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)\n _, g_thresh = cv2.threshold(images[1],125,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)\n _, r_thresh = cv2.threshold(images[2],125,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)\n\n print(r_thresh)\n print('b_thresh:')\n print(b_thresh)\n rb = np.bitwise_or(r_thresh, b_thresh)\n\n #grayscaled = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)\n #_, threshold = cv2.threshold(grayscaled, 10, 255, cv2.THRESH_BINARY)\n #th = cv2.adaptiveThreshold(grayscaled, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 115, 1)\n #_,threshold2 = cv2.threshold(grayscaled,125,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)\n\n thresh = [b_thresh, g_thresh, r_thresh]\n \n for i in range(len(images)):\n cv2.imshow(channels[i] + \"_thresh\", thresh[i])\n\n cv2.imshow(\"rb_thresh\", rb)\n\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n #n = random.randint(0, 1000000)\n #write_add = f\"{args.output}/{n}.JPG\"\n #cv2.imwrite(write_add, b_thresh)\n","sub_path":"thresh_test.py","file_name":"thresh_test.py","file_ext":"py","file_size_in_byte":2088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"635604560","text":"# Clone in parallel\n# https://stackoverflow.com/questions/26023395/how-to-speed-up-parallelize-downloads-of-git-submodules-using-git-clone-recu/34762036#34762036\n# See https://pymotw.com/2/multiprocessing/communication.html\n# Update repos if necessary\n# May use fixed revisions but discouraged\n\nimport multiprocessing\nimport yaml\n\nfrom compat import *\n\nimport git_manage\n\nDEFAULT_TARGETS_FILE = 'default-mw-targets.yaml'\n\nwith open(DEFAULT_TARGETS_FILE, 'r') as f:\n middleware_targets = yaml.safe_load(f)\n\n_packages = []\n\nfor item in middleware_targets['common_middlewares']:\n _packages.append(\n {'url': item['url'],\n 'folder_name': \"hybris/%s\" % item['url'].split('/')[-1]}\n )\n\nif __name__ == '__main__':\n # Establish communication queues\n tasks = multiprocessing.JoinableQueue()\n results = multiprocessing.Queue()\n\n # Start consumers\n #num_consumers = multiprocessing.cpu_count() * 2\n # Better throttle a bit since Github's not happy with many clones at once\n num_consumers = 4\n consumers = [git_manage.Consumer(tasks, results)\n for i in range(num_consumers)]\n for w in consumers:\n w.start()\n\n # Enqueue jobs\n num_jobs = len(_packages)\n for i in range(num_jobs):\n tasks.put(git_manage.ManageRepoTask(_packages[i]))\n\n # Add a poison pill for each consumer\n for i in range(num_consumers):\n tasks.put(None)\n\n # Wait for all of the tasks to finish\n tasks.join()\n\n # Start printing results\n while num_jobs:\n result = results.get()\n num_jobs -= 1\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"156452917","text":"#1/usr/bin/env python3\n\nfrom euler18 import NumberTriangle\nimport utils.graph as g\n\n\ndef euler67():\n tri = NumberTriangle('triangle2.txt')\n dist, prev = g.shortest_path(tri, tri.root, False)\n\n print(sorted(dist.values(), reverse=True)[0])\n\n\nif __name__ == '__main__':\n euler67()\n","sub_path":"python/euler67.py","file_name":"euler67.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"500824678","text":"import os\nfrom flask import Flask, Response\nfrom flask import render_template,request\nfrom flask_pymongo import PyMongo\nfrom flask_mail import Mail, Message\nfrom methods import top_parent_id, find_matching_ids, find_matching_elements, unique_id, mongo_to_json, formatted_def, get_themrole_fields, full_class_hierarchy_tree, get_pred_fields, get_constant_fields, get_verb_specific_fields, remove_object_ids, colored_pb_example, vn_sanitized_class, get_themrole_fields_undefined\nfrom methods import sort_by_char, sort_by_id\n\nimport json\n\nfrom bson import json_util\nimport configparser\n\nconfigs = configparser.ConfigParser()\nconfigs.read('configs.ini')\n\nmail_settings = {\n\t\"MAIL_SERVER\": \"smtp.gmail.com\",\n\t\"MAIL_PORT\": 465,\n\t\"MAIL_USE_TLS\": False,\n\t\"MAIL_USE_SSL\": True,\n\t# Set environment variables for more security\n\t\"MAIL_USERNAME\": configs['MAIL_SETUP']['MAIL_USERNAME'],\n\t\"MAIL_PASSWORD\": configs['MAIL_SETUP']['MAIL_PASSWORD']\n}\napp = Flask(__name__)\n\n#generate SECRET_KEY randomly on startup\napp.config['SECRET_KEY'] = os.urandom(16)\napp.config['MONGO_DBNAME'] = 'new_corpora'\napp.config[\"MONGO_URI\"] = \"mongodb://localhost:27017/\" + app.config['MONGO_DBNAME']\napp.config.update(mail_settings)\nmongo = PyMongo(app)\nmail = Mail(app)\n\ndef sort_key(predicate):\n\t## Key will be returned with the assumption that there's only oneword per entry in the list\n\treturn str.lower(list(predicate.keys())[0])\n\n@app.context_processor\ndef context_methods():\n\treturn dict(top_parent_id=top_parent_id, unique_id=unique_id, mongo_to_json=mongo_to_json, formatted_def=formatted_def, \\\n\t\tfull_class_hierarchy_tree=full_class_hierarchy_tree, get_themrole_fields=get_themrole_fields, get_pred_fields=get_pred_fields, \\\n\t\tget_constant_fields=get_constant_fields, get_verb_specific_fields=get_verb_specific_fields, remove_object_ids=remove_object_ids, \\\n\t\tcolored_pb_example=colored_pb_example, vn_sanitized_class=vn_sanitized_class, get_themrole_fields_undefined=get_themrole_fields_undefined)\n\n@app.route('/uvi_search')\ndef uvi_search():\n\tprocess_query()\n\t\n\tgen_themroles = sorted(list(mongo.db.verbnet.references.gen_themroles.find({}, {'_id':0})), key=sort_key)\n\tpredicates = sorted(list(mongo.db.verbnet.references.predicates.find({}, {'_id':0})), key=sort_key)\n\tvs_features = sorted(list(mongo.db.verbnet.references.vs_features.find({}, {'_id':0})), key=sort_key)\n\tsyn_res = sorted(list(mongo.db.verbnet.references.syn_restrs.find({}, {'_id':0})), key=sort_key)\n\tsel_res = sorted(list(mongo.db.verbnet.references.sel_restrs.find({}, {'_id':0})), key=sort_key)\n\t\n\treturn render_template('uvi_search.html',\n\t\tgen_themroles=gen_themroles, predicates=predicates, vs_features=vs_features, syn_res=syn_res, sel_res=sel_res\n\t)\n\n@app.route('/download_json', methods=['GET', 'POST'])\ndef download_json():\n\tform_keys = list(request.form.keys())\n\tif not form_keys:\n\t\treturn render_template('applications.html')\n\tresources = {}\n\tif 'down_vn' in form_keys:\n\t\tresources['VerbNet'] = list(mongo.db.verbnet.find({}, {'_id':0}))\n\tif 'down_fn' in form_keys:\n\t\tresources['FrameNet'] = list(mongo.db.framenet.find({}, {'_id':0}))\n\tif 'down_pb' in form_keys:\n\t\tresources['PropBank'] = list(mongo.db.propbank.find({}, {'_id':0}))\n\tif 'down_on' in form_keys:\n\t\tresources['OntoNotes'] = list(mongo.db.ontonotes.find({}, {'_id':0}))\n\treturned_json = json_util.dumps(resources, indent=4)\n\treturn Response(returned_json, mimetype='application/json', headers={'Content-Disposition':'attachment;filename=uvi_export.json'})\n\n@app.route('/', methods=['GET','POST'])\ndef index():\n\tgen_themroles = sorted(list(mongo.db.verbnet.references.gen_themroles.find({}, {'_id':0})), key=sort_key)\n\tpredicates = sorted(list(mongo.db.verbnet.references.predicates.find({}, {'_id':0})), key=sort_key)\n\tvs_features = sorted(list(mongo.db.verbnet.references.vs_features.find({}, {'_id':0})), key=sort_key)\n\tvs_features_freq = sorted(vs_features,key=lambda x: list(x.values())[0][\"count\"], reverse=True)\n\tsyn_res = sorted(list(mongo.db.verbnet.references.syn_restrs.find({}, {'_id':0})), key=sort_key)\n\tsel_res = sorted(list(mongo.db.verbnet.references.sel_restrs.find({}, {'_id':0})), key=sort_key)\n\treturn render_template('welcome_page.html',\n\t\tgen_themroles=gen_themroles, predicates=predicates, vs_features=vs_features, vs_features_freq = vs_features_freq, syn_res=syn_res, sel_res=sel_res\n\t)\n\n@app.route('/contact_us', methods=['GET', 'POST'])\ndef contact_us():\n\t## mail recipients \n\trecipients = configs['MAIL_SETUP']['recipients'].split(',')\n\tif request.method=='POST':\n\t\t## unused variable \"reply_to_name\"\n\t\t#reply_to_name = request.form.get('name')\n\t\treply_to=request.form.get('email')\n\t\tsubject = request.form.get('subject')\n\t\tmessage = request.form.get('message')\n\t\tmsg = Message(subject=subject, \n\t\t\t\t\t\tsender=app.config.get(\"MAIL_USERNAME\"), \n\t\t\t\t\t\trecipients=recipients,\n\t\t\t\t\t\tbody=message)\n\t\tmsg.add_recipient(reply_to)\n\t\tprint(msg);\n\t\tmail.send(msg)\n\n\treturn render_template('contact.html')\n\n@app.route('/references_page', methods=['GET'])\ndef references_page():\n\tgen_themroles = sorted(list(mongo.db.verbnet.references.gen_themroles.find({}, {'_id':0})), key=sort_key)\n\tgen_themroles_freq = sorted(gen_themroles,key=lambda x: list(x.values())[0][\"count\"], reverse=True)\n\tpredicates = sorted(list(mongo.db.verbnet.references.predicates.find({}, {'_id':0})), key=sort_key)\n\tpredicates_freq = sorted(predicates,key=lambda x: list(x.values())[0][\"count\"], reverse=True)\n\tvs_features = sorted(list(mongo.db.verbnet.references.vs_features.find({}, {'_id':0})), key=sort_key)\n\tvs_features_freq = sorted(vs_features,key=lambda x: list(x.values())[0][\"count\"], reverse=True)\n\tsyn_res = sorted(list(mongo.db.verbnet.references.syn_restrs.find({}, {'_id':0})), key=sort_key)\n\tsel_res = sorted(list(mongo.db.verbnet.references.sel_restrs.find({}, {'_id':0})), key=sort_key)\n\n\t## All Page details are returned by get_ref_page in a dictioanry format\n\treturn render_template('references.html',\n\t\tgen_themroles=gen_themroles, gen_themroles_freq = gen_themroles_freq, predicates=predicates, vs_features=vs_features, vs_features_freq = vs_features_freq, predicates_freq = predicates_freq, syn_res=syn_res, sel_res=sel_res\n\t)\n\n@app.route('/_process_query', methods=['GET','POST'])\ndef process_query(common_query_string = None):\n\tif request.form.get('lemma_query_string') or common_query_string:\n\t\tif(common_query_string):\n\t\t\tprint('entered common if loop')\n\t\t\tquery_string = common_query_string\n\t\t\tlemmas = [x.lower() for x in query_string.split(' ')]\n\t\t\tlogic = \"or\"\n\t\t\tsort_behavior = \"alpha\"\n\t\t\tincl_vn = True\n\t\t\tincl_fn = True\n\t\t\tincl_pb = True\n\t\t\tincl_wn = True\n\t\t\tmatched_ids = find_matching_ids(lemmas, incl_vn, incl_fn, incl_pb, incl_wn, logic, sort_behavior)\n\t\t\tprint('done common if loop')\n\t\t\treturn render_template('results.html', matched_ids=matched_ids, query_string=query_string, sort_behavior=sort_behavior)\n\n\t\telse:\n\t\t\tprint('entered common if loop')\n\t\t\tquery_string = request.form['lemma_query_string']\n\t\t\t# print(request.form.get('lemma_query_string')+' POOOOOPPP!!')\n\t\t\tlemmas = [x.lower() for x in query_string.split(' ')]\n\t\t\tlogic = request.form['logic']\n\t\t\tsort_behavior = request.form['sort_behavior']\n\t\t\tform_keys = list(request.form.keys())\n\t\t\tincl_vn = True if 'incl_vn' in form_keys else False\n\t\t\tincl_fn = True if 'incl_fn' in form_keys else False\n\t\t\tincl_pb = True if 'incl_pb' in form_keys else False\n\t\t\tincl_wn = True if 'incl_wn' in form_keys else False\n\t\t\tmatched_ids = find_matching_ids(lemmas, incl_vn, incl_fn, incl_pb, incl_wn, logic, sort_behavior)\n\t\t\treturn render_template('results.html', matched_ids=matched_ids, query_string=query_string, sort_behavior=sort_behavior)\n\n\telif request.form.get('vn_attribute'):\n\t\tquery_string = request.form['attribute_query_string']\n\t\t#if query string is empty, return all possible instances of this attribute\n\t\t#e.g. all predicates, themroles, etc.\n\t\tif query_string == '':\n\t\t\treturn ''\n\n\t\tattribute_type = request.form['vn_attribute']\n\t\tif attribute_type == 'themrole':\n\t\t\tthemrole = query_string[0].upper() + query_string[1:].lower()\n\t\t\tsort_behavior = 'alpha'\n\t\t\tmatched_ids = {'VerbNet':sorted([vn_class['class_id'] for vn_class in mongo.db.verbnet.find({'frames.semantics.args': {'arg_type':'ThemRole', 'value':themrole}})])}\n\t\t\treturn render_template('themrole_search.html', themrole=themrole.upper(), matched_ids=matched_ids, query_string=query_string, sort_behavior=sort_behavior)\n\n\t\telif attribute_type == 'predicate':\n\t\t\tpredicate = query_string.lower()\n\t\t\tsort_behavior = 'alpha'\n\t\t\tmatched_ids = {'VerbNet':sorted([vn_class['class_id'] for vn_class in mongo.db.verbnet.find({'frames.semantics.predicate':predicate})])}\n\t\t\treturn render_template('predicate_search.html', predicate=predicate.upper(), matched_ids=matched_ids, query_string=query_string, sort_behavior=sort_behavior)\n\n\t\telif attribute_type == 'vs_feature':\n\t\t\tvs_feature = query_string\n\t\t\tmatched_ids = {'VerbNet':sorted([vn_class['class_id'] for vn_class in mongo.db.verbnet.find({'members.vs_features': vs_feature})])}\n\t\t\treturn render_template('vs_feature_search.html', vs_feature=vs_feature.upper(), matched_ids=matched_ids)\n\n\t\telif attribute_type == 'selrestr':\n\t\t\tselrestr_type = query_string[1:]\n\t\t\tselrestr_val = query_string[0]\n\t\t\tsort_behavior = 'alpha'\n\t\t\tclass_level_selrestr_ids = set([doc['class_id'] for doc in mongo.db.vn_themrole_fields.find({'themrole_fields.selrestr_list': {'$elemMatch': {'value':selrestr_val, 'type':selrestr_type}}})])\n\t\t\tmatched_ids = {'VerbNet':sorted(list(class_level_selrestr_ids))}\n\t\t\tframe_level_selrestr_ids = set([doc['class_id'] for doc in mongo.db.vn_themrole_fields.find({'themrole_fields.frame_level_selrestrs_list': {'$elemMatch': {'value':selrestr_val, 'type':selrestr_type}}})])\n\t\t\tmatched_ids['VerbNet'].extend(sorted(list(frame_level_selrestr_ids)))\n\t\t\treturn render_template('selrestr_search.html', selrestr = selrestr_val.upper()+selrestr_type.upper(), matched_ids=matched_ids, sort_behavior=sort_behavior, level=None)\n\n\t\telif attribute_type == 'synrestr':\n\t\t\tsynrestr_type = query_string[1:]\n\t\t\tsynrestr_val = query_string[0]\n\t\t\tsort_behavior = 'alpha'\n\t\t\tclass_level_synrestr_ids = set([doc['class_id'] for doc in mongo.db.vn_themrole_fields.find({'themrole_fields.synrestr_list': {'$elemMatch': {'value':synrestr_val, 'type':synrestr_type}}})])\n\t\t\tframe_level_synrestr_ids = set([doc['class_id'] for doc in mongo.db.vn_themrole_fields.find({'themrole_fields.frame_level_synrestrs_list': {'$elemMatch': {'value':synrestr_val, 'type':synrestr_type}}})])\n\t\t\tmatched_ids = {'VerbNet':sorted(list(class_level_synrestr_ids.union(frame_level_synrestr_ids)))}\n\t\t\treturn render_template('synrestr_search.html', synrestr = synrestr_val.upper()+synrestr_type.upper(), matched_ids=matched_ids, sort_behavior=sort_behavior)\n\n\telif request.args.get('themrole'):\n\t\tthemrole = request.args.get('themrole')\n\t\tquery_string = ''\n\t\tsort_behavior = 'alpha'\n\t\tmatched_ids = {'VerbNet':sorted([vn_class['class_id'] for vn_class in mongo.db.verbnet.find({'frames.semantics.args': {'arg_type':'ThemRole', 'value':themrole}})])}\n\t\treturn render_template('themrole_search.html', themrole=themrole.upper(), matched_ids=matched_ids, query_string=query_string, sort_behavior=sort_behavior)\n\n\telif request.args.get('pred'):\n\t\tpredicate = request.args.get('pred')\n\t\tquery_string = ''\n\t\tsort_behavior = 'alpha'\n\t\tmatched_ids = {'VerbNet':sorted([vn_class['class_id'] for vn_class in mongo.db.verbnet.find({'frames.semantics.predicate':predicate})])}\n\t\treturn render_template('predicate_search.html', predicate=predicate.upper(), matched_ids=matched_ids, query_string=query_string, sort_behavior=sort_behavior)\n\n\n\telif request.args.get('const'):\n\t\tconst = request.args.get('const')\n\t\tquery_string = ''\n\t\tsort_behavior = 'alpha'\n\t\tmatched_ids = {'VerbNet':sorted([vn_class['class_id'] for vn_class in mongo.db.verbnet.find({'frames.semantics.args': {'arg_type':'Constant', 'value':const}})])}\n\t\treturn render_template('constant_search.html', const=const.upper(), matched_ids=matched_ids, query_string=query_string, sort_behavior=sort_behavior)\n\n\n\telif request.args.get('verb_specific_arg'):\n\t\tvs_arg = request.args.get('verb_specific_arg')\n\t\tquery_string = ''\n\t\tsort_behavior = 'alpha'\n\t\tmatched_ids = {'VerbNet':sorted([vn_class['class_id'] for vn_class in mongo.db.verbnet.find({'frames.semantics.args': {'arg_type':'VerbSpecific', 'value':vs_arg}})])}\n\t\treturn render_template('vs_arg_search.html', vs_arg=vs_arg.upper(), matched_ids=matched_ids, query_string=query_string, sort_behavior=sort_behavior)\n\n\telif request.args.get('verb_specific_feature'):\n\t\tvs_feature = request.args.get('verb_specific_feature')\n\t\tmatched_ids = {'VerbNet':sorted([vn_class['class_id'] for vn_class in mongo.db.verbnet.find({'members.vs_features': vs_feature})])}\n\t\treturn render_template('vs_feature_search.html', vs_feature=vs_feature.upper(), matched_ids=matched_ids)\n\n\n\telif request.args.get('selrestr'):\n\t\tselrestr_type = request.args.get('selrestr')\n\t\tselrestr_val = request.args.get('selrestr_val')\n\t\tlevel = request.args.get('level')\n\t\tsort_behavior = 'alpha'\n\t\tif level == 'class':\n\t\t\tclass_level_selrestr_ids = set([doc['class_id'] for doc in mongo.db.vn_themrole_fields.find({'themrole_fields.selrestr_list': {'$elemMatch': {'value':selrestr_val, 'type':selrestr_type}}})])\n\t\t\tmatched_ids = {'VerbNet':sorted(list(class_level_selrestr_ids))}\n\t\t\treturn render_template('selrestr_search.html', selrestr = selrestr_val.upper()+selrestr_type.upper(), matched_ids=matched_ids, sort_behavior=sort_behavior, level=level)\n\n\t\telif level == 'frame':\n\t\t\tframe_level_selrestr_ids = set([doc['class_id'] for doc in mongo.db.vn_themrole_fields.find({'themrole_fields.frame_level_selrestrs_list': {'$elemMatch': {'value':selrestr_val, 'type':selrestr_type}}})])\n\t\t\tmatched_ids = {'VerbNet':sorted(list(frame_level_selrestr_ids))}\n\t\t\treturn render_template('selrestr_search.html', selrestr = selrestr_val.upper()+selrestr_type.upper(), matched_ids=matched_ids, sort_behavior=sort_behavior, level=level)\n\n\n\telif request.args.get('synrestr'):\n\t\tsynrestr_type = request.args.get('synrestr')\n\t\tsynrestr_val = request.args.get('synrestr_val')\n\t\tsort_behavior = 'alpha'\n\t\tclass_level_synrestr_ids = set([doc['class_id'] for doc in mongo.db.vn_themrole_fields.find({'themrole_fields.synrestr_list': {'$elemMatch': {'value':synrestr_val, 'type':synrestr_type}}})])\n\t\tframe_level_synrestr_ids = set([doc['class_id'] for doc in mongo.db.vn_themrole_fields.find({'themrole_fields.frame_level_synrestrs_list': {'$elemMatch': {'value':synrestr_val, 'type':synrestr_type}}})])\n\t\tmatched_ids = {'VerbNet':sorted(list(class_level_synrestr_ids.union(frame_level_synrestr_ids)))}\n\t\treturn render_template('synrestr_search.html', synrestr = synrestr_val.upper()+synrestr_type.upper(), matched_ids=matched_ids, sort_behavior=sort_behavior)\n\treturn ''\n\n\n#POST request:
in \"results.html\"\n@app.route('/_display_element', methods=['GET','POST'])\ndef display_element():\n\tif request.form.get('resource_key') == 'VerbNet':\n\t\tvn_class_id = request.form['vn_class_id']\n\t\tmatched_elements = mongo.db.verbnet.find({'class_id': vn_class_id})\n\t\treturn render_template('render_verbnet_top.html', vn_elements = matched_elements, first_level = True)\n\n\telif request.form.get('resource_key') == 'FrameNet':\n\t\tfn_name = request.form['fn_name']\n\t\tmatched_element = mongo.db.framenet.find_one({'name': fn_name})\n\t\treturn render_template('render_framenet.html', frame_json = matched_element)\n\n\telif request.form.get('resource_key') == 'PropBank':\n\t\tpb_lemma = request.form['pb_lemma']\n\t\tmatched_element = mongo.db.propbank.find_one({'predicates.lemma': pb_lemma})\n\t\treturn render_template('render_propbank.html', frame_json = matched_element)\n\n\telif request.form.get('resource_key') == 'OntoNotes':\n\t\ton_lemma = request.form['on_lemma']\n\t\tmatched_element = mongo.db.ontonotes.find_one({'lemma': on_lemma})\n\t\treturn render_template('render_ontonotes.html', frame_json = matched_element)\n\n@app.route('/verbnet/')\ndef render_vn_class(vn_class_id):\n\tmatched_elements = mongo.db.verbnet.find({'class_id':vn_class_id})\n\treturn render_template('render_verbnet_top.html', vn_elements=matched_elements, first_level=True)\n\n@app.route('/welcome_frame')\ndef welcome_frame():\n\treturn render_template('welcome_frame.html')\n\n\n@app.route('/class_hierarchy')\ndef class_hierarchy():\n\treturn render_template('class_hierarchy.html', class_by_num=sort_by_id(), class_by_name=sort_by_char())\n\n@app.route('/nlp_applications')\ndef applications():\n\treturn render_template('applications.html')\n\n@app.route('/uvi_search_anywhere', methods=['GET','POST'])\ndef uvi_search_anywhere():\n\tif request.form.get('common_query_string'):\n\t\tuvi_search()\n\t\tquery_string = request.form.get('common_query_string')\n\t\tlemmas = [x.lower() for x in query_string.split(' ')]\n\t\tlogic = \"or\"\n\t\tsort_behavior = \"alpha\"\n\t\tincl_vn = True\n\t\tincl_fn = True\n\t\tincl_pb = True\n\t\tincl_wn = True\n\t\tmatched_ids = find_matching_ids(lemmas, incl_vn, incl_fn, incl_pb, incl_wn, logic, sort_behavior)\n\t\treturn render_template('results.html', matched_ids=matched_ids, query_string=query_string, sort_behavior=sort_behavior)\n\telse:\n\t\tprocess_query()\n\t\tgen_themroles = sorted(list(mongo.db.verbnet.references.gen_themroles.find({}, {'_id':0})), key=sort_key)\n\t\tpredicates = sorted(list(mongo.db.verbnet.references.predicates.find({}, {'_id':0})), key=sort_key)\n\t\tvs_features = sorted(list(mongo.db.verbnet.references.vs_features.find({}, {'_id':0})), key=sort_key)\n\t\tsyn_res = sorted(list(mongo.db.verbnet.references.syn_restrs.find({}, {'_id':0})), key=sort_key)\n\t\tsel_res = sorted(list(mongo.db.verbnet.references.sel_restrs.find({}, {'_id':0})), key=sort_key)\n\t\treturn render_template('uvi_search.html',gen_themroles=gen_themroles, predicates=predicates, vs_features=vs_features, syn_res=syn_res, sel_res=sel_res)\n\n","sub_path":"uvi_web/uvi_flask.py","file_name":"uvi_flask.py","file_ext":"py","file_size_in_byte":17847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"593451603","text":"# -*- coding: utf-8 -*-\nimport torch\nimport random\nimport inspect\nimport numpy as np\nfrom itertools import islice, repeat\nimport os\nimport functools\nfrom subprocess import *\nimport subprocess\n\n\ndef check_path(path, exist_ok=False, log=print):\n \"\"\"Check if `path` exists, makedirs if not else warning/IOError.\"\"\"\n if os.path.exists(path):\n if exist_ok:\n log(f\"path {path} exists, may overwrite...\")\n else:\n raise IOError(f\"path {path} exists, stop.\")\n else:\n os.makedirs(os.path.dirname(path), exist_ok=True)\n\n\ndef split_corpus(path, shard_size, default=None):\n \"\"\"yield a `list` containing `shard_size` line of `path`,\n or repeatly generate `default` if `path` is None.\n \"\"\"\n if path is not None:\n return _split_corpus(path, shard_size)\n else:\n return repeat(default)\n\n\ndef _split_corpus(path, shard_size):\n \"\"\"Yield a `list` containing `shard_size` line of `path`.\n \"\"\"\n with open(path, \"rb\") as f:\n if shard_size <= 0:\n yield f.readlines()\n else:\n while True:\n shard = list(islice(f, shard_size))\n if not shard:\n break\n yield shard\n\n\ndef aeq(*args):\n \"\"\"\n Assert all arguments have the same value\n \"\"\"\n arguments = (arg for arg in args)\n first = next(arguments)\n assert all(arg == first for arg in arguments), \\\n \"Not all arguments have the same value: \" + str(args)\n\n\ndef sequence_mask(lengths, max_len=None):\n \"\"\"\n Creates a boolean mask from sequence lengths.\n \"\"\"\n batch_size = lengths.numel()\n max_len = max_len or lengths.max()\n return (torch.arange(0, max_len, device=lengths.device)\n .type_as(lengths)\n .repeat(batch_size, 1)\n .lt(lengths.unsqueeze(1)))\n\n\ndef tile(x, count, dim=0):\n \"\"\"\n Tiles x on dimension dim count times.\n \"\"\"\n perm = list(range(len(x.size())))\n if dim != 0:\n perm[0], perm[dim] = perm[dim], perm[0]\n x = x.permute(perm).contiguous()\n out_size = list(x.size())\n out_size[0] *= count\n batch = x.size(0)\n x = x.view(batch, -1) \\\n .transpose(0, 1) \\\n .repeat(count, 1) \\\n .transpose(0, 1) \\\n .contiguous() \\\n .view(*out_size)\n if dim != 0:\n x = x.permute(perm).contiguous()\n return x\n\n\ndef use_gpu(opt):\n \"\"\"\n Creates a boolean if gpu used\n \"\"\"\n return (hasattr(opt, 'gpu_ranks') and len(opt.gpu_ranks) > 0) or \\\n (hasattr(opt, 'gpu') and opt.gpu > -1)\n\n\ndef set_random_seed(seed, is_cuda):\n \"\"\"Sets the random seed.\"\"\"\n if seed > 0:\n torch.manual_seed(seed)\n # this one is needed for torchtext random call (shuffled iterator)\n # in multi gpu it ensures datasets are read in the same order\n random.seed(seed)\n # some cudnn methods can be random even after fixing the seed\n # unless you tell it to be deterministic\n torch.backends.cudnn.deterministic = True\n # This one is needed for various tranfroms\n np.random.seed(seed)\n\n if is_cuda and seed > 0:\n # These ensure same initialization in multi gpu mode\n torch.cuda.manual_seed(seed)\n\n\ndef generate_relative_positions_matrix(length, max_relative_positions,\n cache=False):\n \"\"\"Generate the clipped relative positions matrix\n for a given length and maximum relative positions\"\"\"\n if cache:\n distance_mat = torch.arange(-length + 1, 1, 1).unsqueeze(0)\n else:\n range_vec = torch.arange(length)\n range_mat = range_vec.unsqueeze(-1).expand(-1, length).transpose(0, 1)\n distance_mat = range_mat - range_mat.transpose(0, 1)\n distance_mat_clipped = torch.clamp(distance_mat,\n min=-max_relative_positions,\n max=max_relative_positions)\n # Shift values to be >= 0\n final_mat = distance_mat_clipped + max_relative_positions\n return final_mat\n\n\ndef relative_matmul(x, z, transpose):\n \"\"\"Helper function for relative positions attention.\"\"\"\n batch_size = x.shape[0]\n heads = x.shape[1]\n length = x.shape[2]\n x_t = x.permute(2, 0, 1, 3)\n x_t_r = x_t.reshape(length, heads * batch_size, -1)\n if transpose:\n z_t = z.transpose(1, 2)\n x_tz_matmul = torch.matmul(x_t_r, z_t)\n else:\n x_tz_matmul = torch.matmul(x_t_r, z)\n x_tz_matmul_r = x_tz_matmul.reshape(length, batch_size, heads, -1)\n x_tz_matmul_r_t = x_tz_matmul_r.permute(1, 2, 0, 3)\n return x_tz_matmul_r_t\n\n\ndef fn_args(fun):\n \"\"\"Returns the list of function arguments name.\"\"\"\n return inspect.getfullargspec(fun).args\n\n\ndef report_matrix(row_label, column_label, matrix):\n header_format = \"{:>10.10} \" + \"{:>10.7} \" * len(row_label)\n row_format = \"{:>10.10} \" + \"{:>10.7f} \" * len(row_label)\n output = header_format.format(\"\", *row_label) + '\\n'\n for word, row in zip(column_label, matrix):\n max_index = row.index(max(row))\n row_format = row_format.replace(\n \"{:>10.7f} \", \"{:*>10.7f} \", max_index + 1)\n row_format = row_format.replace(\n \"{:*>10.7f} \", \"{:>10.7f} \", max_index)\n output += row_format.format(word, *row) + '\\n'\n row_format = \"{:>10.10} \" + \"{:>10.7f} \" * len(row_label)\n return output\n\n\ndef check_model_config(model_config, root):\n # we need to check the model path + any tokenizer path\n for model in model_config[\"models\"]:\n model_path = os.path.join(root, model)\n if not os.path.exists(model_path):\n raise FileNotFoundError(\n \"{} from model {} does not exist\".format(\n model_path, model_config[\"id\"]))\n if \"tokenizer\" in model_config.keys():\n if \"params\" in model_config[\"tokenizer\"].keys():\n for k, v in model_config[\"tokenizer\"][\"params\"].items():\n if k.endswith(\"path\"):\n tok_path = os.path.join(root, v)\n if not os.path.exists(tok_path):\n raise FileNotFoundError(\n \"{} from model {} does not exist\".format(\n tok_path, model_config[\"id\"]))\n\n\n\ndef jarWrapper(*args):\n process = Popen(['scala', '-jar'] + list(args), stdout=PIPE, stderr=PIPE)\n ret = []\n while process.poll() is None:\n line = process.stdout.readline()\n if line != '' and line.endswith('\\n'):\n ret.append(line[:-1])\n stdout, stderr = process.communicate()\n ret += stdout.split('\\n')\n if stderr != '':\n ret += stderr.split('\\n')\n ret.remove('')\n return ret\n\n\ndef call_subprocess(args):\n return subprocess.call(args)\n\n\nclass ClassRegistry(object):\n \"\"\"Helper class to create a registry of classes.\"\"\"\n\n def __init__(self, base_class=None):\n \"\"\"Initializes the class registry.\n\n Args:\n base_class: Ensure that classes added to this registry are a subclass of\n :obj:`base_class`.\n \"\"\"\n self._base_class = base_class\n self._registry = {}\n\n @property\n def class_names(self):\n \"\"\"Class names registered in this registry.\"\"\"\n return set(self._registry.keys())\n\n def register(self, cls=None, name=None, alias=None):\n \"\"\"Registers a class.\n\n Args:\n cls: The class to register. If not set, this method returns a decorator for\n registration.\n name: The class name. Defaults to ``cls.__name__``.\n alias: An optional alias or list of alias for this class.\n\n Returns:\n :obj:`cls` if set, else a class decorator.\n\n Raises:\n TypeError: if :obj:`cls` does not extend the expected base class.\n ValueError: if the class name is already registered.\n \"\"\"\n if cls is None:\n return functools.partial(self.register, name=name, alias=alias)\n if self._base_class is not None and not issubclass(cls, self._base_class):\n raise TypeError(\"Class %s does not extend %s\" % (cls.__name__, self._base_class.__name__))\n if name is None:\n name = cls.__name__\n self._register(cls, name)\n if alias is not None:\n if not isinstance(alias, (list, tuple)):\n alias = (alias,)\n for alias_name in alias:\n self._register(cls, alias_name)\n return cls\n\n def _register(self, cls, name):\n if name in self._registry:\n raise ValueError(\"Class name %s is already registered\" % name)\n self._registry[name] = cls\n\n def get(self, name):\n \"\"\"Returns the class with name :obj:`name` or ``None`` if it does not exist\n in the registry.\n \"\"\"\n return self._registry.get(name)\n","sub_path":"onmt/utils/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":8761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"492077554","text":"from PyQt5.QtWidgets import QWidget, QPushButton, QHBoxLayout \n \nclass HBoxLayout(QWidget):\n\tdef __init__(self): \n\t\tsuper().__init__() \n\t\tself.horizontalUi() \n \n\tdef horizontalUi(self):\n\t\tself.resize(300, 100) \n\t\tself.move(300,300) \n\t\tself.setWindowTitle('Penerapan QHBoxLayout') \n \n\t\tself.button1 = QPushButton('Start') \n\t\tself.button2 = QPushButton('Pause') \n\t\tself.button3 = QPushButton('Stop') \n \n\t\tlayout = QHBoxLayout()\n\t\tlayout.addWidget(self.button1)\n\t\tlayout.addWidget(self.button2)\n\t\tlayout.addWidget(self.button3) \n \n\t\tself.setLayout(layout) ","sub_path":"Praktikum 5 (Layout)/(2)HBoxLayout/HBoxLayout.py","file_name":"HBoxLayout.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"362771711","text":"#!/usr/bin/env python3\n# Copyright 2021 Emily Smith and Weigang Yin Permission is hereby granted, free of charge, to\n# any person obtaining a copy of this software and associated documentation\n# files (the \"Software\"), to deal in the Software without restriction,\n# including without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to permit\n# persons to whom the Software is furnished to do so, subject to the following\n# conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nfrom __future__ import print_function\nfrom math import trunc\nfrom time import sleep\nimport os, logging, json, time\nimport subprocess\nfrom periphery import I2C\n\ndef check_temp(temp_sensor):\n raw = subprocess.getoutput(\"cat /sys/bus/iio/devices/iio\\:device0/in_\" + temp_sensor + \"_temp_raw\")\n raw_value = float(raw)\n\n offset = subprocess.getoutput(\"cat /sys/bus/iio/devices/iio\\:device0/in_\" + temp_sensor + \"_temp_offset\")\n offset_value = float(offset)\n\n scale = subprocess.getoutput(\"cat /sys/bus/iio/devices/iio\\:device0/in_\" + temp_sensor + \"_temp_scale\")\n scale_value = float(scale)\n\n temp = (raw_value + offset_value)*scale_value/1024\n return temp\n\n#Get and Check Temperature threshold\nTEMP_THRESHOLD = float(95)\nif (TEMP_THRESHOLD > 95.0):\n print(\"Temperature Threshold set to %.2f. This is too high!!\" %TEMP_THRESHOLD)\n TEMP_THRESHOLD = float(95)\n print(\"Starting temperature monitoring. Automatic shutdown will occur at 95 C\")\n\nelif (TEMP_THRESHOLD < 65.0):\n print(\"Temperature Threshold set to %.2f. This is too low!!\" %TEMP_THRESHOLD)\n TEMP_THRESHOLD = float(65)\n print(\"Starting temperature monitoring. Automatic shutdown will occur at 65 C\")\n\nelse:\n print(\"Starting temperature monitoring. Automatic shutdown will occur at %.2f C.\" %TEMP_THRESHOLD)\n\nlogging.basicConfig(filename='/logs/temp.log', level=logging.INFO)\n\n#Wait for first round of 12c polling to complete and be written to file \ni2c_file = '/logs/i2c_hardware.json'\nwhile not os.path.isfile(i2c_file):\n sleep(10)\n\ngfex_temp = float(30)\nwhile gfex_temp < TEMP_THRESHOLD:\n\n logging.info(str(subprocess.getoutput(\"date\")))\n\n try:\n with open(i2c_file, 'r') as j :\n i2c_data = json.load(j)\n except:\n logging.info(\"Problems opening the json file. Trying again.\")\n continue\n\n temp = i2c_data['TEMPSENSORS']\n pwr = i2c_data['POWERMODULES']\n mpd = i2c_data['MINIPODS']\n \n # Read board temperature sensors zynq\n temp_ps = check_temp(\"temp0_ps\")\n temp_pl = check_temp(\"temp2_pl\")\n temp_zynq = max(temp_ps, temp_pl)\n logging.info(\"ZYNQ+ temperature is %.2f C.\" %temp_zynq)\n\n # Read board temperature sensors AD7414\n temp_7414_A=temp['U82']['TEMP']\n temp_7414_B=temp['U83']['TEMP']\n temp_7414_C=temp['U84']['TEMP']\n temp_7414_D=temp['U87']['TEMP']\n temp_ad7414 = max(temp_7414_A,temp_7414_B,temp_7414_C,temp_7414_D)\n logging.info(\"AD7414 temperature is %.2f C.\" %temp_ad7414)\n\n #12V power module BMR458 temperature\n temp_bmr458=pwr['U11_12V']['TEMP']\n logging.info(\"BMR458 temperature is %.2f C.\" %temp_bmr458)\n\n # LTM4630A power modules Temperature monitoring\n temp_ltm_A=pwr['Z_U66_MGTAVTT']['TEMP']\n temp_ltm_B=pwr['Z_U73']['TEMP']\n temp_ltm_C=pwr['Z_U55']['TEMP']\n temp_ltm_D=pwr['Z_U59']['TEMP']\n temp_ltm_E=pwr['A_U122']['TEMP']\n temp_ltm_F=pwr['A_U77']['TEMP']\n temp_ltm_G=pwr['A_U30']['TEMP']\n temp_ltm_H=pwr['B_U123']['TEMP']\n temp_ltm_I=pwr['B_U124']['TEMP']\n temp_ltm_J=pwr['B_U40']['TEMP']\n temp_ltm_K=pwr['C_U126']['TEMP']\n temp_ltm_L=pwr['C_U125']['TEMP']\n temp_ltm_M=pwr['C_U44']['TEMP']\n temp_DCDC = max(temp_bmr458,temp_ltm_A,temp_ltm_B,temp_ltm_C,temp_ltm_D,temp_ltm_E,temp_ltm_F,temp_ltm_G,temp_ltm_H,temp_ltm_I,temp_ltm_J,temp_ltm_K,temp_ltm_L,temp_ltm_M)\n logging.info(\"gfex DCDC temperature is %.2f C.\" %temp_DCDC)\n\n # MiniPODs monitoring\n temp_mini_spare=mpd['RX_CALO_S_U91']['TEMP']\n\n temp_mini_ZA=mpd['TX_FELIX_Z_U3']['TEMP']\n temp_mini_ZB=mpd['TX_L1TOPO_Z_U24']['TEMP']\n temp_mini_ZC=mpd['TX_GLOBAL_Z_U56']['TEMP']\n temp_mini_ZD=mpd['RX_FELIX_Z_U72']['TEMP']\n \n temp_mini_A1=mpd['TX_L1TOPO_A_U32']['TEMP']\n temp_mini_A2=mpd['TX_L1TOPO_A_U25']['TEMP']\n temp_mini_A3=mpd['RX_CALO_A_U96']['TEMP']\n temp_mini_A4=mpd['RX_CALO_A_U102']['TEMP']\n temp_mini_A5=mpd['RX_CALO_A_U103']['TEMP']\n temp_mini_A6=mpd['RX_CALO_A_U104']['TEMP']\n temp_mini_A7=mpd['RX_CALO_A_U105']['TEMP']\n temp_mini_A8=mpd['RX_CALO_A_U106']['TEMP']\n temp_mini_A9=mpd['RX_CALO_A_U27']['TEMP']\n temp_mini_A10=mpd['RX_CALO_A_U97']['TEMP']\n\n temp_mini_B1=mpd['TX_L1TOPO_B_U33']['TEMP']\n temp_mini_B2=mpd['TX_L1TOPO_B_U27']['TEMP']\n temp_mini_B3=mpd['RX_CALO_B_U98']['TEMP']\n temp_mini_B4=mpd['RX_CALO_B_U100']['TEMP']\n temp_mini_B5=mpd['RX_CALO_B_U101']['TEMP']\n temp_mini_B6=mpd['RX_CALO_B_U108']['TEMP']\n temp_mini_B7=mpd['RX_CALO_B_U109']['TEMP']\n temp_mini_B8=mpd['RX_CALO_B_U111']['TEMP']\n temp_mini_B9=mpd['RX_CALO_B_U112']['TEMP']\n temp_mini_B10=mpd['RX_CALO_B_U113']['TEMP']\n\n temp_mini_C1=mpd['TX_L1TOPO_C_U34']['TEMP']\n temp_mini_C2=mpd['TX_L1TOPO_C_U42']['TEMP']\n temp_mini_C3=mpd['RX_CALO_C_U114']['TEMP']\n temp_mini_C4=mpd['RX_CALO_C_U115']['TEMP']\n temp_mini_C5=mpd['RX_CALO_C_U116']['TEMP']\n temp_mini_C6=mpd['RX_CALO_C_U117']['TEMP']\n temp_mini_C7=mpd['RX_CALO_C_U118']['TEMP']\n temp_mini_C8=mpd['RX_CALO_C_U119']['TEMP']\n temp_mini_C9=mpd['RX_CALO_C_U120']['TEMP']\n temp_mini_C10=mpd['RX_CALO_C_U90']['TEMP']\n\n\n temp_mini_z = max(temp_mini_ZA,temp_mini_ZB,temp_mini_ZC,temp_mini_ZD, temp_mini_spare)\n temp_mini_a = max(temp_mini_A1,temp_mini_A2,temp_mini_A3,temp_mini_A4,temp_mini_A5,temp_mini_A6,temp_mini_A7,temp_mini_A8,temp_mini_A9,temp_mini_A10)\n temp_mini_b = max(temp_mini_B1,temp_mini_B2,temp_mini_B3,temp_mini_B4,temp_mini_B5,temp_mini_B6,temp_mini_B7,temp_mini_B8,temp_mini_B9,temp_mini_B10)\n temp_mini_c = max(temp_mini_C1,temp_mini_C2,temp_mini_C3,temp_mini_C4,temp_mini_C5,temp_mini_C6,temp_mini_C7,temp_mini_C8,temp_mini_C9,temp_mini_C10)\n\n temp_minipods = max(temp_mini_z,temp_mini_a,temp_mini_b,temp_mini_c)\n logging.info(\"Minipods temperature is %.2f C.\" %temp_minipods)\n\n gfex_temp = max(temp_zynq,temp_ad7414,temp_DCDC,temp_minipods)\n logging.info(\"gFEX_Max temperature is %.2f C.\" %gfex_temp)\n \n temp_datagpio= int(temp_zynq)+int(temp_ad7414)*256+int(temp_DCDC)*256*256+int(temp_minipods)*256*256*256\n temp_datagpiostr= str(temp_datagpio)\n\n gpiocmdA = subprocess.getoutput(\"/software/misc/ipmc_auto_shutdown/gpio-dev-mem-test -g 0x00A0020000 -o\" + temp_datagpiostr)\n gpiocmdB = subprocess.getoutput(\"/software/misc/ipmc_auto_shutdown/gpio-dev-mem-test -g 0x00A0022000 -o 1\" )\n gpiocmdC = subprocess.getoutput(\"/software/misc/ipmc_auto_shutdown/gpio-dev-mem-test -g 0x00A0022000 -o 0\" )\n gpiocmdD = subprocess.getoutput(\"/software/misc/ipmc_auto_shutdown/gpio-dev-mem-test -g 0x00A0021000 -i\" )\n \n time.sleep(1)\n\nelse:\n logging.info(\"The gFEX temp is %.2f C and has overheated. Shutting down the board immediately.\" % gfex_temp)\n print(\"The gFEX temp is %.2f C and has overheated. Shutting down the board immediately.\" % gfex_temp)\n set_i2c_mux(TCA9548_U93_ADDR,SENSOR_IIC_BUS)\n time.sleep(10)\n adm1066_shutdown(ADM1066_U52_ADDR)\n","sub_path":"recipes-core/init/init-ipmc-auto-shutdown/ipmc_auto_shutdown/gpio_all_sensor_autoshutdown.py","file_name":"gpio_all_sensor_autoshutdown.py","file_ext":"py","file_size_in_byte":8007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"273352100","text":"print('begin')\nimport numpy as np\nimport matplotlib.pyplot as plt \nfrom sklearn.pipeline import Pipeline\nfrom sklearn.feature_selection import RFECV\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn import linear_model\nfrom sklearn.ensemble.forest import RandomForestRegressor\n\n\n#from sklearn.ensemble.forest import RandomForestRegressor\n#from sklearn.ensemble import GradientBoostingRegressor\nroad1 = \"E:/tianchi_koubei/mid_dataset/weather_pm_feature.txt\"\nroad2 = \"E:/tianchi_koubei/mid_dataset/count_shop_pay_correct.txt\"\nway1 = 'r'\nroad3 = \"E:/tianchi_koubei/result/select_result2_withoutfeature_2.0.csv\"\nway2 = 'w'\ndef create_xday(xday):\n for i in range(1,504):\n xday.append(i)\n return xday\nxday_list = []\nxday = create_xday(xday_list)\ndef create_weekend(xweekend):\n j = 3\n qweekend = [68, 102, 190, 190, 229, 348, 446, 467]\n for i in range(1,504): \n if j == 6 or j ==7:\n if i not in qweekend:\n xweekend.append(1)\n if j == 7:\n j = 1\n else:\n j += 1\n else:\n if j == 7:\n j = 1\n else:\n j += 1\n xweekend.append(0)\n else:\n xweekend.append(0)\n j += 1\n return xweekend\nxweekend_list = []\nxweekend = create_weekend(xweekend_list)\ndef create_weekday():\n j = 3\n weekday = []\n for i in range(1,504):\n weekday.append(j)\n j += 1\n if j == 8:\n j = 1\n return weekday\n\nxweekday = create_weekday()\ndef create_holiday(xday):\n ho_f = []\n holiday = [51,65,66,67,88,89,93,94,95,96,97,98,99,134,177,178,185,186,187,222,223,224,225,226,227,228,229,237,277,278,279,306,307,308,345,346,347,406,443,444,445,459,460,461,462,463,464,465]\n for d in xday:\n if d not in holiday:\n ho_f.append(0)\n else:\n ho_f.append(1)\n return ho_f\nxholiday = create_holiday(xday)\nfr1 = open(road1,way1)\nfr2 = open(road2,way1)\nfw = open(road3,way2)\n#fw_diffmean = open(road4,way2)\n\ni = 0\n#读取特征\ndef readfile_oneshop_X(fr,xday,xweekend,xweekday,xholiday):\n X = []\n X.append(xday)\n X.append(xweekend)\n X.append(xweekday)\n X.append(xholiday)\n '''\n for r in range(0,5):\n line = fr.readline()\n re = line.strip('\\n').split(',')\n data_str = map(float,re[1:])\n data_float = []\n for s in data_str:\n data_float.append(s)\n X.append((data_float))\n '''\n return np.array(X).T\n#读取目标值\ndef readfile_oneshop_Y(fr):\n line = fr.readline()\n re = line.strip('\\n').split(',')\n data_str = map(float,re[1:])\n data_float = []\n for s in data_str:\n data_float.append(s)\n\n return data_float\n\ndef mean_normal_weekend_diff(pay_day,xday,xweekend,start,end):\n y_pre = []\n nor_pay = []\n weekend_pay = []\n for p,n,w in zip(pay_day,xday[:start],xweekend[:start]):\n if w == 1:\n weekend_pay.append(p)\n else:\n nor_pay.append(p)\n nor = np.mean(nor_pay)\n weekend = np.mean(weekend_pay)\n if end == 0:\n for d in xweekend[start:]:\n if d == 0:\n y_pre.append(nor)\n else:\n y_pre.append(weekend)\n return y_pre\n else:\n for d in xweekend[start:end]:\n if d == 0:\n y_pre.append(nor)\n else:\n y_pre.append(weekend)\n return y_pre\ndef Evaluation(pred,test):\n shop_err = 0\n for i in range(0,len(pred)):\n for p,t in zip(pred[i],test[i]):\n if (p+t) == 0.0:\n shop_err += 0.0\n else:\n shop_err += abs((p-t)/(p+t))\n total_err = shop_err/(len(pred)*len(pred[0]))\n return total_err\n#shuchu\ndef output(fw,shopid,y_pre):\n y_pre_str = []\n y_pre_int = map(int,y_pre)\n y_pre_tostr = map(str,y_pre_int)\n for i in y_pre_tostr:\n y_pre_str.append(i)\n fw.write(str(shopid)+','+','.join(y_pre_str)+'\\n')\n################## \ndef Evaluation(pred,test):\n shop_err = 0\n for i in range(0,len(pred)):\n for p,t in zip(pred[i],test[i]):\n if (p+t) == 0.0:\n shop_err += 0.0\n else:\n shop_err += abs((p-t)/(p+t))\n total_err = shop_err/(len(pred)*len(pred[0]))\n return total_err\n\nun_pre = []\n\nY_test = []\n\n\n#err_shop_rcv = []\nwhile i<2000:\n # readfile\n X = []\n X = readfile_oneshop_X(fr1,xday,xweekend,xweekday,xholiday )[-364:]\n Y = readfile_oneshop_Y(fr2)[-350:]\n x_train = X[-289:-21]\n y_train = Y[-275:-7]\n x_val = X[-21:-14]\n y_val = Y[-7:]\n x_test = X[-14:]\n ###\n \n RigeLinearCV = linear_model.RidgeCV(cv=10)\n rcv = RigeLinearCV.fit(x_train,y_train)\n y_pre_rcv = rcv.predict(x_val)\n ###\n params_rf = {'n_estimators':500,'min_samples_split':2,'n_jobs':4}\n \n rf = RandomForestRegressor(**params_rf)\n rf.fit(x_train,y_train)\n y_pre_rf = rf.predict(x_val)\n ###\n y_pre_diff1 = mean_normal_weekend_diff(Y[-14:-7],xday[-28:-14],xweekend[-28:-14],-7,0)\n y_pre_diff2 = mean_normal_weekend_diff(Y[-21:-7],xday[-35:-14],xweekend[-35:-14],-14,0)\n ###\n \n \n #Y_test.append(y_test)\n #y_pre_diff = mean_normal_weekend_diff(Y,xday,xweekend,-21,-14)\n \n ###\n loss_rcv = Evaluation([y_pre_rcv],[y_val])\n loss_rf = Evaluation([y_pre_rf],[y_val])\n loss_diffmean1 = Evaluation([y_pre_diff1],[y_val])\n loss_diffmean2 = Evaluation([y_pre_diff2],[y_val])\n\n union = {loss_rcv:1,loss_rf:2,loss_diffmean1:3,loss_diffmean2:4}\n minloss = min(union.keys())\n minloss_num = union[minloss]\n\n x_un = np.concatenate((x_train,x_val),axis=0)\n y_un = np.append(y_train,y_val)\n\n #print(len(x_un))\n #print(len(y_un))\n if minloss_num == 2:\n rf.fit(x_un,y_un)\n y_pre = rf.predict(x_test)\n #plt.title('rf')\n elif minloss == 1:\n rcv.fi(x_un,y_un)\n y_pre =rcv.predict(x_test)\n #plt.title('rcv')\n elif minloss == 3:\n y_pre = mean_normal_weekend_diff(Y[-7:],xday[-21:],xweekend[-21:],-14,0)\n else:\n y_pre = mean_normal_weekend_diff(Y[-14:],xday[-28:],xweekend[-28:],-14,0)\n #plt.title('diff')\n \n #print(y_pre)\n \n #print(y_pre)\n output(fw,i+1,y_pre)\n \n\n '''\n plt.scatter(xday[-289:-14],y_un)\n #plt.scatter(xday[-14:],y_test,color = 'green')\n plt.scatter(xday[-14:],y_pre,color = 'green')\n plt.plot(xday[-14:],y_pre,color = 'red')\n plt.title(str())\n path = \"E://tianchi_koubei/fig/select_pre/\"+str(i+1)+'.png'\n plt.savefig(path+\".png\")\n plt.clf()#清除图像,所有的都画到一起了\n '''\n \n print(i)\n i += 1\n\nfr1.close()\nfr2.close()\nfw.close()\n#fw_gbrt.close()\n#print((Evaluation(un_pre,Y_test)))\n#print(Evaluation(diffmean_pre,Y_test))\n#print(err_shop)","sub_path":"train_pre/predict_select_rcv_rf_2.0.py","file_name":"predict_select_rcv_rf_2.0.py","file_ext":"py","file_size_in_byte":6875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"410940859","text":"from helper import *\nfrom pcnn import *\n\nfrom flask import Flask, request, jsonify\n\n\napp = Flask(__name__)\n\n@app.route(\"/train\", methods=['GET', 'POST'])\ndef train():\n data = request.get_json()\n config_file = data['config_file']\n es_query = data['es_query']\n print('train pcnn with {} and es_query {}'.format(\n config_file, str(es_query)))\n\n # config_file = 'configs/config.json'\n # es_query={\"query\": {\n # \"match_phrase\": {\n # \"doc.split\": \"train\"\n # }\n # }\n # }\n\n parser = argparse.ArgumentParser(description='PCNN')\n args_ = parser.parse_args()\n args_.config = config_file\n args = get_config(args_)\n if not args.restore and not args.onlyTest: \n args.name = args.name + str(uuid.uuid4())[0:6] + \\\n '_' + time.strftime(\"%d_%m_%Y\") + '_' + time.strftime(\"%H:%M:%S\")\n\n tf.set_random_seed(args.seed)\n random.seed(args.seed)\n np.random.seed(args.seed)\n set_gpu(args.gpu)\n\n model = PCNN(args)\n\n config = tf.ConfigProto()\n config.gpu_options.allow_growth=True\n with tf.Session(config=config) as sess:\n sess.run(tf.global_variables_initializer())\n if not args.onlyTest:\n model.fit(sess, es_query=es_query)\n else:\n saver = tf.train.Saver()\n logger = model.logger\n\n save_dir = os.path.join('checkpoints/', args.name)\n if not os.path.exists(save_dir):\n logger.info('Save Path {} doesnt exist.'.format(save_dir))\n sys.exit()\n save_path = os.path.join(save_dir, 'best_validation')\n saver.restore(sess, save_path) # Restore model\n\n if not args.no_eval:\n test_loss, test_pred, test_acc, \n y, y_pred, logit_list, y_hot, \n wrd_attens, e_pair, bag_sizes = model.predict(sess, None, \n split=\"test\",\n es_query=es_query)\n test_prec, test_rec, test_f1 = model.calc_prec_recall_f1(\n y, y_pred, 0)\n y_true = np.array([e[1:] for e in y_hot]).reshape((-1))\n y_scores = np.array([e[1:] for e in logit_list]).reshape((-1))\n area_pr = average_precision_score(y_true, y_scores)\n\n logger.info('Main result (test): \\\n Prec:{} | Rec:{} | F1:{} | Area:{}'.format(\n test_prec, test_rec, test_f1, area_pr))\n\n pickle.dump({\n 'logit_list': logit_list, \n 'y_hot': y_hot, \n 'e_pair':e_pair, \n 'bag_sizes':bag_sizes\n }, \n open(\"results/{}/onlyTest_precision_recall.pkl\".\n format(args.name), 'wb'))\n else:\n test_pred, y_pred, logit_list, \n wrd_attens, e_pair, bag_sizes = model.predict(sess, None, \n split=\"test\", \n no_eval=True,\n es_query=es_query)\n pickle.dump({\n 'logit_list': logit_list, \n 'e_pair':e_pair, \n 'bag_sizes':bag_sizes\n }, \n open(\"results/{}/onlyTest_precision_recall.pkl\".\n format(args.name), 'wb'))\n\n\n\n\n return 'query received'\n\n\nif __name__ == \"__main__\":\n # train()\n app.run(host='0.0.0.0', port=80)\n\n","sub_path":"pcnn_tinkertoy/src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"418392019","text":"#!/usr/bin/python3\nfrom pylab import *\nfrom math import *\nfrom numpy import *\n\ndef p4():\n \"\"\"2.12: Prime Numbers\"\"\"\n print(\"2.12 [Prime Numbers]:\")\n max_prime = int(input(\"Max: \"))\n primes = [2]\n\n def is_prime(n):\n sqrt_n = sqrt(n)\n for p in primes:\n if p > sqrt_n:\n return True\n if n % p == 0:\n return False\n for n in range(3, max_prime, 2):\n if is_prime(n):\n primes.append(n)\n print(\", \".join([str(x) for x in primes]))\n\nif __name__ == \"__main__\":\n p4()\n","sub_path":"Fall 2018/Comp/hw.1/p4.py","file_name":"p4.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"428380581","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:\n if(root==None):\n return []\n L = []\n queue = []\n queue.append(root);\n while(True):\n count = len(queue)\n l=[]\n while(count>0):\n node = queue.pop(0)\n l.append(node.val)\n if(node.left!=None):\n queue.append(node.left)\n if(node.right!=None):\n queue.append(node.right)\n count-=1\n L.append(l)\n if(len(queue)==0):\n break\n return L[::-1] \n","sub_path":"95.py","file_name":"95.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"461620790","text":"import glob\nimport pickle\nfrom sys import argv\n\nfrom pip._vendor.webencodings import labels\nfrom python_speech_features import mfcc\nimport librosa\nimport matplotlib.pyplot as plt\n#import shutil\nfrom sklearn.cluster import KMeans\nimport numpy as np\nfrom sklearn.linear_model import LogisticRegression\n\n# usage: python3 recosons.py k1 k2 verbose\n# ATTENTION: les noms de fichiers ne doivent comporter ni - ni espace\n\n#sur ligne de commande: les 2 parametres de k means puis un param de verbose\n\nk1 = int(argv[1])\nk2 = int(argv[2])\n\nif argv[3] == \"True\":\n verbose = True;\nelse:\n verbose = False;\n\n\nlistSons=glob.glob(\"Guitareélectrique/*.wav\")\ntmpa = len(listSons) #on mémorise le nb d'éléments de la première classe\nlistSons += glob.glob(\"GuitareAcoustique/*.wav\")\n#liste des labels:\ngroundTruth = [0]*tmpa\ntmpb = len(listSons)-tmpa #nb. éléments de la snde classe\ngroundTruth += [1]*tmpb\n\n\nlesMfcc = np.empty(shape=(0, 13), dtype=float) # array of all MFCC from all sounds\ndimSons = [] # nb of mfcc per file\n\nfor s in listSons:\n if verbose:\n print(\"###\",s,\"###\")\n (sig,rate) = librosa.load(s)\n mfcc_feat = mfcc(sig,rate,nfft=1024)\n if verbose:\n print(\"MFCC: \", mfcc_feat.shape)\n dimSons.append(mfcc_feat.shape[0])\n lesMfcc = np.append(lesMfcc,mfcc_feat,axis=0)\n\n#BOW initialization\nbows = np.empty(shape=(0,k1),dtype=int)\n\n# everything ready for the 1st k-means\nkmeans1 = KMeans(n_clusters=k1, random_state=0).fit(lesMfcc)\nif verbose:\n print(\"result of kmeans 1\", kmeans1.labels_)\n\n#writing the BOWs for second k-means\ni = 0\nfor nb in dimSons: # for each sound (file)\n tmpBow = np.array([0]*k1)\n j = 0\n while j < nb: # for each MFCC of this sound (file)\n tmpBow[kmeans1.labels_[i]] += 1\n j+=1\n i+=1\n tmpBow = tmpBow / nb\n copyBow = tmpBow.copy()\n bows = np.append(bows, [copyBow], 0)\nif verbose:\n print(\"nb of MFCC vectors per file : \", dimSons)\n print(\"BOWs : \", bows)\n \nplt.plot(range(1,11),range(1,11),bows)\nplt.show()\n\n#ready for second k-means\nkmeans2 = KMeans(n_clusters=k2, random_state=0).fit(bows)\nif verbose:\n print(\"result of kmeans 2\", kmeans2.labels_)\n\n\n#écriture\nwith open(\"kmean1\",'wb') as output:\n pickle.dump(kmeans1,output,pickle.HIGHEST_PROTOCOL)\nwith open(\"kmean2\",'wb') as output:\n pickle.dump(kmeans2,output,pickle.HIGHEST_PROTOCOL)\n\n#cŕeation d'un objet de regression logistique\nlogisticRegr = LogisticRegression()\n#apprentissage\nlogisticRegr.fit(bows, groundTruth)\n#calcul des labels pŕeditslabels\nPredicted = logisticRegr.predict(bows)\n#calcul et affichage du score\nscore = logisticRegr.score(bows, groundTruth)\nprint(\"train score = \", score)\n#sauvegarde de l'objet\nwith open('sauvegarde.logr', 'wb') as output:\n pickle.dump(logisticRegr, output, pickle.HIGHEST_PROTOCOL)\n#chargement de l'objet\nwith open('sauvegarde.logr', 'rb') as input:\n logisticRegr = pickle.load(input)\n\n\n\n\n\n\nplt.scatter(lesMfcc[ : , 0], lesMfcc[ : , 1], s =50,c=kmeans1.labels_)\ncentroids = kmeans1.cluster_centers_\nplt.scatter(centroids[:, 0], centroids[:, 1], c='red', s=50)\nplt.show()\n\n\n\n\n\n\n\nlistSonsToTest = glob.glob(\"16954_electrique.wav\")\n#listSonsToTest = glob.glob(\"17426_acoustique.wav\")\n#lecture\nwith open(\"kmean1\",\"rb\") as input :\n kmeans1saved = pickle.load(input)\n\nk1 = kmeans1saved.n_clusters\n\nif argv[3] == \"True\":\n verbose = True\nelse:\n verbose = False\n\n#On recupère le mfcc du son\nlesMfcc = np.empty(shape=(0, 13), dtype=float) # array of all MFCC from all sounds\ndimSons = [] # nb of mfcc per file\n\nfor son in listSonsToTest:\n if verbose:\n print(\">###\", son, \"###<\")\n (sig, rate) = librosa.load(son)\n mfcc_feat = mfcc(sig, rate, nfft=1024)\n if verbose:\n print(\"MFCC: \", mfcc_feat.shape)\n dimSons.append(mfcc_feat.shape[0])\n lesMfcc = np.append(lesMfcc, mfcc_feat, axis=0)\n\n\n#On crée le premier kmean avec les mfcc\nmfccpredict = kmeans1saved.predict(lesMfcc)\n\n#on calcule les bows\nbows = np.empty(shape=(0,k1),dtype=int)\n\n#writing the BOWs for second k-means\ni = 0\nfor nb in dimSons: # for each sound (file)\n tmpBow = [0]*k1\n j = 0\n while j < nb: # for each MFCC of this sound (file)\n tmpBow[mfccpredict[i]] += 1\n j+=1\n i+=1\n copyBow = tmpBow.copy()\n bows = np.append(bows, [copyBow], 0)\nif verbose:\n print(\"nb of MFCC vectors per file : \", dimSons)\n print(\"BOWs :\\n\", bows)\n\n#On fait la prédiction avec logisticRegr\n#lecture\nwith open(\"sauvegarde.logr\",\"rb\") as input :\n logisticRegr = pickle.load(input)\n\nprediction = logisticRegr.predict(bows)\nif verbose:\n print(\"result of logisticRegr\", prediction)\n\n","sub_path":"son/recosons.py","file_name":"recosons.py","file_ext":"py","file_size_in_byte":4629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"588133597","text":"from pyquery import PyQuery as pq\nimport requests\nimport os\n\n#下载单个网页的PPT\ndef downUrl(url,filepath):\n\tprint(\"downloading from url:\"+url)\n\tdoc = pq(url,encoding='gbk')\n\ta = doc(\"body > div > div.pleft.left > dl > dd > ul.downurllist >li>a\")\n\tdownUrl = a.attr(\"href\")\n\tpptname = doc(\"body > div > div.pleft.left > dl > dd > div.ppt_info.clearfix > h1\").text()\n\tfilename = filepath+\"/\"+pptname+\".zip\"\n\t# filename = downUrl.split(\"/\")[-1]\n\tr = requests.get(downUrl)\n\tif not os.path.exists(filepath):\n\t\tos.makedirs(filepath)\n\twith open(filename,'wb') as f:\n\t f.write(r.content)\n\tprint(\"PPT downloaded:\"+filename)\n\n#获取ppt的网页链接\ndef geturls(index):\n\tbaseurl = 'http://www.1ppt.com'\n\tdoc = pq(baseurl+\"/moban/ppt_moban_\"+index+\".html\")\n\threfs = doc(\"body > div.w.center.mt4 > dl.dlbox >dd >ul>li>a\")\n\turls = []\n\tfor item in hrefs.items():\n\t prefs = item.attr('href')\n\t urls.append(baseurl+str(prefs))\n\treturn urls\n\nif __name__ == '__main__':\n\tindex = input(\"请输入需要爬取的页数:\")\n\turls = geturls(index)\n\tsavepath = \"./PPT\"\n\tfor url in urls:\n\t\tdownUrl(url,savepath)\n\n\n\n\n","sub_path":"爬取PPT/pyPPt.py","file_name":"pyPPt.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"335010769","text":"from django.test import TestCase\n\nfrom .models import Category, Product, Colour, Size, Material\n\n\nclass TestModels(TestCase):\n\n def setUp(self):\n\n self.category1 = Category.objects.create(\n name='nature',\n friendly_name='Nature',\n )\n\n self.product1 = Product.objects.create(\n category=self.category1,\n name='newproduct',\n description='this product',\n price=9999,\n sku='1234',\n )\n\n self.material = Material.objects.create(\n value='material'\n )\n\n self.size = Size.objects.create(\n value='XS'\n )\n\n self.colour = Colour.objects.create(\n name='Black & White'\n )\n\n def test_category_str_method_returns_name(self):\n category = self.category1\n self.assertEqual(str(category), 'nature')\n\n def test_category_get_friendly_name(self):\n category = self.category1\n self.assertEqual(category.get_friendly_name(), 'Nature')\n\n def test_product_str_method_returns_name(self):\n product = self.product1\n self.assertEqual(str(product), 'newproduct')\n\n def test_material_str_method_returns_value(self):\n material = self.material\n self.assertEqual(str(material), 'material')\n\n def test_size_str_method_returns_value(self):\n size = self.size\n self.assertEqual(str(size), 'XS')\n\n def test_colour_str_method_returns_name(self):\n colour = self.colour\n self.assertEqual(str(colour), 'Black & White')\n","sub_path":"products/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"381757135","text":"# -*- coding: utf-8 -*-\n\"\"\"Class to set App lib directory for current version of Python\"\"\"\nimport os\nimport sys\n\n\nclass AppLib:\n \"\"\"Set App Lib Directory\"\"\"\n\n def __init__(self):\n \"\"\"Initialize App properties.\"\"\"\n self._lib_directories = None\n\n # All Python Version that will be searched\n self.lib_major_version = f'lib_{sys.version_info.major}'\n self.lib_minor_version = f'{self.lib_major_version}.{sys.version_info.minor}'\n self.lib_micro_version = f'{self.lib_minor_version}.{sys.version_info.micro}'\n\n def find_lib_directory(self):\n \"\"\"Find the optimal lib directory.\"\"\"\n lib_directory = None\n if self.lib_micro_version in self.lib_directories:\n lib_directory = self.lib_micro_version\n elif self.lib_minor_version in self.lib_directories:\n lib_directory = self.lib_minor_version\n elif self.lib_major_version in self.lib_directories:\n lib_directory = self.lib_major_version\n else:\n for lv in [self.lib_micro_version, self.lib_minor_version, self.lib_major_version]:\n for d in self.lib_directories:\n if lv in d:\n lib_directory = d\n break\n else:\n continue\n break\n return lib_directory\n\n @property\n def lib_directories(self):\n \"\"\"Return all \"lib_\" directories.\"\"\"\n if self._lib_directories is None:\n self._lib_directories = []\n app_path = os.getcwd()\n contents = os.listdir(app_path)\n for c in contents:\n # ensure content starts with lib, is directory, and is readable\n if c.startswith('lib') and os.path.isdir(c) and (os.access(c, os.R_OK)):\n self._lib_directories.append(c)\n return sorted(self._lib_directories, reverse=True)\n\n def update_path(self):\n \"\"\"Update sys path to ensure all required modules can be found.\n\n All Apps must be able to access included modules, this method will ensure that the system\n path has been updated to include the \"cwd\" and the proper \"lib_\" directories.\n \"\"\"\n lib_directory = self.find_lib_directory()\n lib_latest = os.path.join(os.getcwd(), 'lib_latest')\n\n # insert the appropriate lib_directory into system path if found, otherwise insert\n # lib_latest directory into the system Path. This entry will be bumped to index 1\n # after adding the current working directory.\n if lib_directory is None:\n lib_directory = lib_latest\n sys.path.insert(0, os.path.join(os.getcwd(), lib_directory))\n\n # insert the current working directory into the system Path for the App, ensuring that it is\n # always the first entry in the list.\n cwd = os.getcwd()\n try:\n sys.path.remove(cwd)\n except ValueError:\n pass\n sys.path.insert(0, cwd)\n","sub_path":"apps/CA_Abuse_ch__MalwareBazaar/code/app/app_lib.py","file_name":"app_lib.py","file_ext":"py","file_size_in_byte":3003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"298587400","text":"from flask import Flask\nfrom flask_restful import Resource, Api\n\napp = Flask(__name__)\napi = Api(app)\n\n\nclass Rest(Resource):\n def get(self):\n return {'rest': 'OK'}\n\napi.add_resource(Rest, '/')\n\n\nif __name__ == '__main__':\n app.run(debug=True, host=\"127.0.0.1\", port=8080)\n \n\n\n","sub_path":"Machine Learning/sba-3-api/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"544019252","text":"# Copyright (c) 2016-2017, Christiaan Frans Rademan.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# * Neither the name of the copyright holders nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport sys\nimport logging\nif sys.version[0] == '2':\n import thread\nelse:\n import _thread as thread\nimport threading\n\nlock = threading.Lock()\n\nlog = logging.getLogger(__name__)\n\n\nclass ThreadDict(object):\n def __init__(self):\n self.threads = {}\n\n def _thread(self):\n lock.acquire()\n try:\n self._thread_id = thread.get_ident()\n if self._thread_id not in self.threads:\n self.threads[self._thread_id] = {}\n return self.threads[self._thread_id]\n finally:\n lock.release()\n\n def clear(self):\n lock.acquire()\n try:\n self._thread_id = thread.get_ident()\n if self._thread_id in self.threads:\n del self.threads[self._thread_id]\n finally:\n lock.release()\n\n def __setitem__(self, key, value):\n data = self._thread()\n lock.acquire()\n try:\n data[key] = value\n finally:\n lock.release()\n\n def __getitem__(self, key):\n data = self._thread()\n if key in data:\n return self.get(key)\n else:\n raise KeyError(key)\n\n def __delitem__(self, key):\n data = self._thread()\n lock.acquire()\n try:\n del data[key]\n finally:\n lock.release()\n\n def __contains__(self, key):\n data = self._thread()\n return key in data\n\n def __iter__(self):\n data = self._thread()\n return iter(data)\n\n def __len__(self):\n data = self._thread()\n return len(data)\n\n def __repr__(self):\n data = self._thread()\n return repr(data)\n\n def __str__(self):\n data = self._thread()\n return str(data)\n\n def update(self, update):\n data = self._thread()\n lock.acquire()\n try:\n data.update(update)\n finally:\n lock.release()\n\n def get(self, key, default=None):\n data = self._thread()\n return data.get(key, default)\n","sub_path":"tachyonic/common/threaddict.py","file_name":"threaddict.py","file_ext":"py","file_size_in_byte":3729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"43244210","text":"from twisted.internet.protocol import DatagramProtocol\nfrom twisted.python import failure\nfrom twisted.internet import error, task, reactor\nfrom threading import Thread, Lock\nimport time\nimport json\nimport commands\nfrom config import *\nimport logging\nimport traceback\nfrom db import Db\nimport game.game\n\nconnectionDone = failure.Failure(error.ConnectionDone())\n\nlock = Lock()\ndb = Db(lock)\n\n\nclass UDProtocol(DatagramProtocol):\n requests = ['connect', 'disconnect', 'ping']\n errors = {'001': 'Bad request', '002': 'Wrong request', '003': 'Connection first'}\n\n timeout = 5\n update = 1 / 2\n\n def __init__(self, ip, port, r, server):\n self.ip = ip\n self.port = port\n self.reactor = r\n self.server = server\n self.loop = task.LoopingCall(self.run)\n self.loop.start(self.update)\n\n def datagramReceived(self, datagram, address):\n if DEBUG and not datagram.count(b'ping'):\n self.server.logger.info(\"Datagram %s received from %s\" % (repr(datagram), repr(address)))\n\n try:\n message = json.loads(datagram.decode('utf-8'))\n request = message.get('request')\n data = message.get('data')\n callback = message.get('callback')\n handler = self.server.connections.get(address)\n except (UnicodeDecodeError, json.decoder.JSONDecodeError):\n self.send(self.get_error_message('001'), address)\n return\n\n if not handler and request != 'connect':\n self.send(self.get_error_message('003'), address, callback)\n return\n\n if request:\n try:\n if request not in self.requests:\n raise Exception('002')\n response = getattr(self, request)(data, address)\n except Exception as ex:\n response = self.get_error_message(ex.args[0])\n else:\n response = handler['user'].on_message(message)\n self.send(response, address, callback)\n\n def get_error_message(self, error_id):\n return {'type': 'error', 'data': {'code': error_id, 'message': self.errors[error_id]}}\n\n def send(self, data, address, callback=None):\n if not data:\n return\n if callback:\n data['callback'] = callback\n if type(address) == list:\n for addr in address:\n self.transport.write(json.dumps(data).encode('utf-8'), addr)\n return\n self.transport.write(json.dumps(data).encode('utf-8'), address)\n\n def connect(self, _, address):\n if self.server.connections.get(address):\n self.disconnect(None, address)\n user = User(address, self, self.server.main_game, self.server.secret_key)\n user.on_open()\n self.server.connections[address] = {'time': time.time(), 'user': user}\n\n def disconnect(self, _, address):\n if not self.server.connections.get(address):\n return\n handler = self.server.connections.pop(address)\n handler['user'].on_close()\n\n def ping(self, _, address):\n if not self.server.connections.get(address):\n raise Exception('003')\n self.server.connections[address]['time'] = time.time()\n\n def run(self):\n t = time.time()\n for handler in self.server.connections.copy().values():\n if t - handler['time'] > self.timeout:\n self.disconnect(None, handler['user'].addr)\n\n\nclass User:\n secret_key = ''\n\n def __init__(self, addr, udp, main_game, secret_key):\n self.udp = udp\n self.secret_key = secret_key\n self.temp = db\n self.name = None\n self.id = None\n self.channel = self.temp.main_channel\n self.rights = 0\n self.addr = addr\n self.logger = logging.getLogger('Server')\n self.player_info = {}\n self.game = main_game\n self.me = None\n\n def get_information(self):\n return {\n 'user': self.name,\n 'user_id': self.id,\n 'user_rights': self.rights,\n 'player_info': self.player_info,\n }\n\n def on_open(self):\n self.temp.handlers.append(self)\n self.logger.info('%s Connection' % repr(self.addr))\n self.send({\n 'type': 'welcome',\n 'data': {\n 'message': 'udp server WELCOME!',\n 'version': VERSION\n }\n })\n\n def on_message(self, message):\n if message.get('type'):\n message_type = message['type']\n message_type = message_type.replace('__', '')\n message_type = message_type.lower()\n data = message.get('data')\n try:\n resp = getattr(commands, message_type)(self, data)\n except Exception as ex:\n resp = {'type': message_type + '_error', 'data': str(ex)}\n self.logger.error('%s Error %s %s %s' % (self.addr, message_type, data, str(ex)))\n if DEBUG:\n traceback.print_exc()\n elif message.get('action'):\n action = message['action']\n action = action.replace('__', '')\n action = action.lower()\n data = message.get('data')\n try:\n resp = self.me.action(action, data)\n except Exception as ex:\n resp = {'type': action + '_error', 'data': str(ex)}\n self.logger.error('%s Error %s %s %s' % (self.addr, action, data, str(ex)))\n if DEBUG:\n traceback.print_exc()\n else:\n resp = commands.error(None)\n if message.get('id'):\n resp['id'] = message['id']\n if resp:\n self.send(resp)\n\n def on_close(self):\n commands.leave(self, None)\n if self.channel:\n self.channel.leave(self)\n self.temp.handlers.remove(self)\n self.logger.info('%s Disconnect' % (self.addr,))\n\n def send(self, data):\n self.udp.send(data, self.addr)\n\n\nclass Server:\n secret_key = 'shouldintermittentvengeancearmagainhisredrighthandtoplagueus'\n\n def __init__(self, ip='0.0.0.0', port=8956):\n\n form = '[%(asctime)s] %(levelname)s: %(message)s'\n self.logger = logging.getLogger(\"Server\")\n logging.basicConfig(level=logging.INFO, format=form)\n log_handler = logging.FileHandler('logs/log.txt')\n log_handler.setFormatter(logging.Formatter(form))\n self.logger.addHandler(log_handler)\n\n self.main_game = game.game.Game(db.main_channel)\n\n self.ip = ip\n self.port = port\n\n self.connections = {}\n\n self.reactor = reactor\n self.udp = UDProtocol(ip, port, reactor, self)\n reactor.listenUDP(port, self.udp)\n\n def run(self):\n self.logger.info('Start %s:%s' % (IP, PORT))\n self.main_game.start()\n Console()\n self.reactor.run()\n\n\nclass Console(Thread):\n def __init__(self):\n super().__init__(target=self.run)\n self.start()\n\n def run(self):\n while True:\n try:\n out = eval(input())\n if out is not None:\n print(out)\n except KeyboardInterrupt:\n exit()\n except:\n traceback.print_exc()\n\n\nif __name__ == '__main__':\n s = Server()\n s.run()\n","sub_path":"SocketServer/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":7345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"269359431","text":"# get station and weather data\n\nfrom requests import get\nimport webbrowser\nimport folium\nimport os\nimport html\n\nurl = 'https://apex.oracle.com/pls/apex/raspberrypi/weatherstation/getalllastmeasurement'\n\nstation_data = get(url).json()\n\n# only get data where temperature is available and accurate\ntemps = []\ntmax = 0.0\ntmin = 100.0\nlons = [data['weather_stn_long'] for data in station_data['items']]\nlats = [data['weather_stn_lat'] for data in station_data['items']]\nwsnames = [html.escape(station['weather_stn_name']) for station in stations['items']]\nfor data in station_data['items']:\n if 'ambient_temp' in data:\n t = data['ambient_temp']\n if t > 50 or t < -30:\n t = 20\n if t > tmax:\n tmax = t\n if t < tmin:\n tmin = t\n temps.append(str(t))\n\ndef colourgrad(minimum, maximum, value):\n minimum, maximum = float(minimum), float(maximum)\n ratio = 2 * (value-minimum) / (maximum - minimum)\n b = int(max(0, 255*(1 - ratio)))\n g = int(max(0, 255*(ratio - 1)))\n r = 255 - b - g\n hexcolour = '#%02x%02x%02x' % (r,g,b)\n return hexcolour\n\n# setting up map\n\nmap_ws = folium.Map(location=[0, 0], zoom_start=2)\nfor n in range(len(lons)-1):\n hcol = colourgrad(tmin, tmax, float(temps[n]))\n folium.CircleMarker([lats[n], lons[n]],\n radius = 5,\n popup = wsnames[n]+':'+temps[n],\n fill_color = hcol).add_to(map_ws)\n\nCWD = os.getcwd()\nmap_ws.save('osm.html')\nwebbrowser.open_new('file://'+CWD+'/'+'osm.html')","sub_path":"Mapping the Weather/project2.py","file_name":"project2.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"571532184","text":"from dask import delayed\nfrom dask import array\nimport xarray as xr\nimport numpy as np\nfrom dask.distributed import Client\nfrom warnings import warn\n\n\ndef setup_dask_clinet(workers=2, threads=2, memory_limit_per_worker='2GB'):\n Client(n_workers=workers, threads_per_worker=threads, memory_limit=memory_limit_per_worker)\n\n\nclass COAsT:\n def __init__(self, workers=2, threads=2, memory_limit_per_worker='2GB'):\n # self.client = Client(n_workers=workers, threads_per_worker=threads, memory_limit=memory_limit_per_worker)\n self.dataset = None\n # Radius of the earth in km\n self.earth_raids = 6371.007176\n\n def load(self, file, chunks: dict = None):\n self.dataset = xr.open_dataset(file, chunks=chunks)\n\n def load_multiple(self, directory_to_files, chunks: dict = None):\n self.dataset = xr.open_mfdataset(\n directory_to_files, chunks=chunks, parallel=True, combine=\"by_coords\", compat='override'\n )\n\n def subset(self, domain, nemo, points_a: array, points_b: array):\n raise NotImplementedError\n\n def distance_between_two_points(self):\n raise NotImplementedError\n\n def calculate_haversine_distance(self, lon1, lat1, lon2, lat2):\n '''\n # Estimation of geographical distance using the Haversine function.\n # Input can be single values or 1D arrays of locations. This\n # does NOT create a distance matrix but outputs another 1D array.\n # This works for either location vectors of equal length OR a single loc\n # and an arbitrary length location vector.\n #\n # lon1, lat1 :: Location(s) 1.\n # lon2, lat2 :: Location(s) 2.\n '''\n\n # Convert to radians for calculations\n lon1 = xr.ufuncs.deg2rad(lon1)\n lat1 = xr.ufuncs.deg2rad(lat1)\n lon2 = xr.ufuncs.deg2rad(lon2)\n lat2 = xr.ufuncs.deg2rad(lat2)\n\n # Latitude and longitude differences\n dlat = (lat2 - lat1) / 2\n dlon = (lon2 - lon1) / 2\n\n # Haversine function.\n distance = xr.ufuncs.sin(dlat) ** 2 + xr.ufuncs.cos(lat1) * xr.ufuncs.cos(lat2) * xr.ufuncs.sin(dlon) ** 2\n distance = 2 * 6371.007176 * xr.ufuncs.arcsin(xr.ufuncs.sqrt(distance))\n\n return distance\n\n def get_subset_as_xarray(self, var: str, points_x: slice, points_y: slice, line_length: int = None,\n time_counter: int = 0):\n \"\"\"\n This method gets a subset of the data across the x/y indices given for the chosen variable.\n\n Setting time_counter to None will treat `var` as only having 3 dimensions depth, y, x\n\n there is a check on `var` to see the size of the time_counter, if 1 then time_counter is fixed to index 0.\n\n :param var: the name of the variable to get data from\n :param points_x: a list/array of indices for the x dimension\n :param points_y: a list/array of indices for the y dimension\n :param line_length: (Optional) the length of your subset (assuming simple line transect)\n :param time_counter: (Optional) which time slice to get data from, if None and the variable only has one a time\n channel of length 1 then time_counter is fixed too an index of 0\n :return: data across all depths for the chosen variable along the given indices\n \"\"\"\n\n try:\n [time_size, _, _, _] = self.dataset[var].shape\n if time_size == 1:\n time_counter == 0\n\n except ValueError:\n time_counter = None\n\n dx = xr.DataArray(points_x)\n dy = xr.DataArray(points_y)\n\n if time_counter is None:\n smaller = self.dataset[var].isel(x=dx, y=dy)\n else:\n smaller = self.dataset[var].isel(time_counter=time_counter, x=dx, y=dy)\n\n return smaller\n\n def get_2d_subset_as_xarray(self, var: str, points_x: slice, points_y: slice, line_length: int = None,\n time_counter: int = 0):\n \"\"\"\n\n :param var:\n :param points_x:\n :param points_y:\n :param line_length:\n :param time_counter:\n :return:\n \"\"\"\n\n try:\n [time_size, _, _, _] = self.dataset[var].shape\n if time_size == 1:\n time_counter == 0\n except ValueError:\n time_counter = None\n\n if time_counter is None:\n smaller = self.dataset[var].isel(x=points_x, y=points_y)\n else:\n smaller = self.dataset[var].isel(time_counter=time_counter, x=points_x, y=points_y)\n\n return smaller\n\n def plot_simple_2d(self, x, y, data: xr.DataArray, cmap, plot_info: dict):\n \"\"\"\n This is a simple method that will plot data in a 2d. It is a wrapper for matplotlib's 'pcolormesh' method.\n\n `cmap` and `plot_info` are required to run this method, `cmap` is passed directly to `pcolormesh`.\n\n `plot_info` contains all the required information for setting the figure;\n - ylim\n - xlim\n - clim\n - title\n - fig_size\n - ylabel\n\n :param x: The variable contain the x axis information\n :param y: The variable contain the y axis information\n :param data: the DataArray a user wishes to plot\n :param cmap:\n :param plot_info:\n :return:\n \"\"\"\n import matplotlib.pyplot as plt\n\n plt.close('all')\n\n fig = plt.figure()\n plt.rcParams['figure.figsize'] = plot_info['fig_size']\n\n ax = fig.add_subplot(411)\n plt.pcolormesh(x, y, data, cmap=cmap)\n\n plt.ylim(plot_info['ylim'])\n plt.xlim(plot_info['xlim'])\n plt.title(plot_info['title'])\n plt.ylabel(plot_info['ylabel'])\n plt.clim(plot_info['clim'])\n plt.colorbar()\n\n return plt\n\n def plot_cartopy(self, var: str, plot_var: array, params, time_counter: int = 0):\n try:\n import cartopy.crs as ccrs # mapping plots\n import cartopy.feature # add rivers, regional boundaries etc\n from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER # deg symb\n from cartopy.feature import NaturalEarthFeature # fine resolution coastline\n except ImportError:\n import sys\n warn(\"No cartopy found - please run\\nconda install -c conda-forge cartopy\")\n sys.exit(-1)\n\n import matplotlib.pyplot as plt\n plt.close('all')\n fig = plt.figure(figsize=(10, 10))\n ax = fig.gca()\n ax = plt.subplot(1, 1, 1, projection=ccrs.PlateCarree())\n\n cset = self.dataset[var].isel(time_counter=time_counter, deptht=0).plot.pcolormesh \\\n (np.ma.masked_where(plot_var == np.NaN, plot_var), transform=ccrs.PlateCarree(), cmap=params.cmap)\n\n cset.set_clim([params.levs[0], params.levs[-1]])\n\n ax.add_feature(cartopy.feature.OCEAN)\n ax.add_feature(cartopy.feature.BORDERS, linestyle=':')\n ax.add_feature(cartopy.feature.RIVERS)\n coast = NaturalEarthFeature(category='physical', scale='10m', facecolor='none', name='coastline')\n ax.add_feature(coast, edgecolor='gray')\n\n gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,\n linewidth=0.5, color='gray', alpha=0.5, linestyle='-')\n\n gl.xlabels_top = False\n gl.xlabels_bottom = True\n gl.ylabels_right = False\n gl.ylabels_left = True\n gl.xformatter = LONGITUDE_FORMATTER\n gl.yformatter = LATITUDE_FORMATTER\n\n plt.colorbar(cset, shrink=params.colorbar_shrink, pad=.05)\n\n # tmp = self.dataset.votemper\n # tmp.attrs = self.dataset.votemper.attrs\n # tmp.isel(time_counter=time_counter, deptht=0).plot.contourf(ax=ax, transform=ccrs.PlateCarree())\n # ax.set_global()\n # ax.coastlines()\n plt.show()\n\n def plot_movie(self):\n raise NotImplementedError\n","sub_path":"coast/COAsT.py","file_name":"COAsT.py","file_ext":"py","file_size_in_byte":7932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"245038872","text":"import os\n\nREADME_CONTENT_CHECK_FOR=[]\n\ndef test_readme_exists():\n assert os.path.isfile(\n \"README.md\"), \"README.md file missing!\"\n\n\n\n\ndef test_readme_proper_description():\n READMELOOKSGOOD = True\n f = open(\"README.md\", \"r\", encoding=\"utf8\")\n content = f.read()\n f.close()\n for c in README_CONTENT_CHECK_FOR:\n if c not in content:\n print(c)\n READMELOOKSGOOD = False\n pass\n assert READMELOOKSGOOD == True, \"You have not described all the functions/class well in your README.md file\"\n\n\ndef test_readme_file_for_formatting():\n f = open(\"README.md\", \"r\", encoding=\"utf8\")\n content = f.read()\n f.close()\n assert content.count(\"#\") >= 10\n","sub_path":"test_cases.py","file_name":"test_cases.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"250855004","text":"import spacy # utile pour le traitement de language naturel (NLP)\nimport wikipedia # utile pour le scraping \"simple\" de Wikipédia\n\n# chargement de la version anglaise web de SpaCy\nnlp = spacy.load('en_core_web_sm')\n\ndef subject(question):\n\t\"\"\"subject(question): trouve le groupe nomimal sujet de la question\"\"\"\n\tdoc = nlp(question)\n\n\tspan = doc[doc[4].left_edge.i:doc[4].right_edge.i+1]\n\tspan.merge()\n\n\tsubj = [token.text for token in doc if token.dep_ in [\"nsubj\", \"nsubjpass\"]]\n\n\treturn ' '.join(word for word in subj)\n\ndef keywords(question):\n\t\"\"\"keywords(question): retourne les mots importants de la question\"\"\"\n\tdoc = nlp(question)\n\n\tkw = [token.text for token in doc if token.pos_ in [\"ADJ\",\"ADP\",\"ADV\",\"NOUN\",\"NUM\",\"PROPN\",\"VERB\",\"X\"]]\n\n\treturn kw\n\ndef get_wiki_page(subj):\n\t\"\"\"get_wiki_page(subj): retourne la page traitant du sujet de la question\"\"\"\n\tpage_name = wikipedia.search(subj)[0]\n\t\n\tpage = wikipedia.page(page_name)\n\n\treturn page.content\n\n# exemple : on rentre une question, on identifie le sujet et les mots importants, puis on écrit la page dans un fichier\nquestion = \"Where did the World Cup take place in 1930 ?\"\nsubj = subject(question)\nkw = keywords(question)\n\npage = get_wiki_page(subj)\n\nf = open('page.txt','w')\nf.write(str(page.encode('utf-8')))\nf.close()\n\n\n\n\nclass ask:\n\tdef __init__(self, question):\n\t\tself.question = question\n\t\tself.subject = subject(question)\n\t\tself.keywords = keywords(question)\n\n\tdef wikipedia_page(self):\n\t\tpage_name = wikipedia.search(self.subject)[0]\n\t\tpage = wikipedia.page(page_name)\n\n\t\tprint(page.url)\n\nquestion_1 = ask(\"When is John F. Kennedy born ?\")\n\nquestion_1.wikipedia_page()\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"ask.py","file_name":"ask.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"601047156","text":"\"\"\"\nCopyright (c) 2004-Present Pivotal Software, Inc.\n\nThis program and the accompanying materials are made available under\nthe terms of the under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport os\nimport socket\nfrom time import sleep\nimport pexpect as pexpect\n\nimport tinctest\nfrom tinctest.lib import local_path\nfrom gppylib.commands.base import Command\nfrom mpp.lib.config import GPDBConfig\nfrom mpp.lib.PSQL import PSQL\nfrom mpp.gpdb.tests.storage.walrepl.run import StandbyRunMixin\nfrom mpp.gpdb.tests.storage.walrepl.lib.verify import StandbyVerify\nfrom mpp.gpdb.tests.storage.walrepl.lib import WalReplException \nfrom mpp.gpdb.tests.storage.walrepl.lib.pg_util import GpUtility\n\n\nclass GpinitStandby(object):\n '''Class for gpinitstandby operations \n Disclaimer: Some of these may repeat with the mpp/lib version'''\n def __init__(self):\n self.stdby = StandbyVerify()\n self.runmixin = StandbyRunMixin()\n self.runmixin.createdb(dbname='walrepl') \n self.mdd = os.environ.get('MASTER_DATA_DIRECTORY')\n self.config = GPDBConfig()\n self.pgutil = GpUtility()\n self.host = socket.gethostname()\n \n def run(self, option = ''):\n '''Runs gpinitstandby and returns True if successfull '''\n gpinitstandby_cmd = 'gpinitstandby -a %s' % option\n cmd = Command(name='Running Gpinitstandby', cmdStr=\"%s\" % gpinitstandby_cmd)\n tinctest.logger.info(\" %s\" % cmd)\n cmd.run(validateAfter=False)\n result = cmd.get_results()\n if result.rc != 0:\n return False\n return True\n\n def verify_gpinitstandby(self, primary_pid): \n '''Verify the presence of standby in recovery mode '''\n if (self.stdby.check_gp_segment_config()) and (self.stdby.check_pg_stat_replication()) and (self.stdby.check_standby_processes())and self.compare_primary_pid(primary_pid) :\n return True\n return False\n\n def get_masterhost(self):\n std_sql = \"select hostname from gp_segment_configuration where content=-1 and role='p';\"\n master_host = PSQL.run_sql_command(std_sql, flags = '-q -t', dbname= 'postgres')\n return master_host.strip()\n\n def get_standbyhost(self):\n std_sql = \"select hostname from gp_segment_configuration where content='-1' and role='m';\"\n standby_host = PSQL.run_sql_command(std_sql, flags = '-q -t', dbname= 'postgres')\n return standby_host.strip()\n\n def get_filespace_location(self):\n fs_sql = \"select fselocation from pg_filespace_entry where fselocation like '%fs_walrepl_a%' and fsedbid=1;\"\n filespace_loc = PSQL.run_sql_command(fs_sql, flags = '-q -t', dbname= 'postgres')\n return filespace_loc.strip()\n\n def get_standbyhostnode(self):\n '''\n Function used to obtain the hostname of one of the segment node inorder to use it as the standby master node\" \n @return : returns the hostname of the segment node which can be used as the standby master node\n '''\n hostlist = self.config.get_hosts()\n standby = ''\n for host in hostlist:\n if host.strip() != self.host:\n standby = host.strip()\n if len(standby) > 0 :\n return standby\n else:\n tinctest.logger.error('No segment host other than master available to have remote standby')\n\n def get_primary_pid(self):\n pid = self.pgutil.get_pid_by_keyword(pgport=os.environ.get('PGPORT'), keyword=self.mdd)\n if int(pid) == -1:\n raise WalReplException('Unable to get pid of primary master process')\n else:\n return int(pid)\n\n def compare_primary_pid(self, initial_pid):\n final_pid = self.get_primary_pid()\n if initial_pid == final_pid :\n return True\n return False\n\n def create_dir_on_standby(self, standby, location):\n fs_cmd = \"gpssh -h %s -e 'rm -rf %s; mkdir -p %s' \" % (standby, location, location)\n cmd = Command(name='Make dierctory on standby before running the command', cmdStr = fs_cmd)\n tinctest.logger.info('%s' % cmd)\n cmd.run(validateAfter=True)\n result = cmd.get_results()\n if result.rc != 0:\n raise WalReplException('Unable to create directory on standby')\n else:\n return True\n \n def initstand_by_with_default(self):\n master_host = self.get_masterhost()\n gp_cmd = \"/bin/bash -c 'gpinitstandby -s %s'\" % (master_host)\n logfile = open(local_path('install.log'),'w')\n\n child = pexpect.spawn(gp_cmd, timeout=400)\n child.logfile = logfile\n sleep(2)\n check = child.expect(['.* Enter standby filespace location for filespace pg_system .*', ' '])\n if check != 0:\n child.close()\n\n l_file = open(local_path('install.log'),'r')\n lines = l_file.readlines()\n for line in lines:\n if 'default: NA' in line:\n return True\n return False\n\n def init_with_prompt(self,filespace_loc):\n standby = self.get_standbyhostnode() \n gp_cmd = \"/bin/bash -c 'gpinitstandby -s %s -a'\" % (standby)\n logfile = open(local_path('install2.log'),'w')\n\n child = pexpect.spawn(gp_cmd, timeout=400)\n child.logfile = logfile\n sleep(5)\n check = child.expect(['.* Enter standby filespace location for filespace.*', ' '])\n child.sendline(filespace_loc)\n\n sleep(10)\n check = child.expect(['.*Successfully created standby master.*'])\n if check != 0:\n tinctest.logger.error('gpinitstandy failed')\n return False\n child.close()\n return True\n","sub_path":"src/test/tinc/tincrepo/mpp/gpdb/tests/storage/walrepl/gpinitstandby/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"66974726","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import colors\nimport matplotlib\nimport os\nimport array\nimport numpy as np\nfrom scipy import misc\nfrom PIL import Image\nfrom math import ceil\nimport argparse\nfrom os import listdir, system\nfrom os.path import isfile, join, isdir\n\n\"\"\"\nThis file is for converting a nested directory structure of exes into a nested\ndirectory structure of imgs, like created in the fileSplitter file. The other\nfileImageWriter file is for converting a directory of files to a directory of images\n\nprovide grey filepath if you want to write grey files, and color if you want\ncolor files. Size is the maximum filesize, so if your maximum filesize is 10MB\nbut you want it to be 11MB with empty space the size argument will add this\nextra space. Otherwise each file will be only as large as it needs to be to fit\nin the data. Resize is for deciding how large you want the files, e.g. i'm\nworking with a 32 bit CNN so all of mine willl be -r 32.\n\"\"\"\n\nWIDTH = 384\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-g\", \"--grey\", default=None,\n help=\"path to save grey files\")\nparser.add_argument(\"-c\", \"--color\", default=None,\n help=\"path to save color files\")\nparser.add_argument(\"-s\", \"--size\", type=int, default=None,\n help=\"maximum bytes for image file\")\nparser.add_argument(\"-f\", \"--files\", default=None, required=True,\n help=\"directory containing files to convert\")\nparser.add_argument(\"-r\", \"--resize\", default=None, type=int,\n help=\"values to resize to, e.g. -r 32\")\nargs = parser.parse_args()\n\ndef generate_black_image(n,m):\n \"\"\"\n Creates a black png image to write file to\n\n Args:\n n (int): width of image to create\n m (int): height of image to write\n \"\"\"\n img = Image.new('RGB', (n,m), (0, 0, 0))\n img.save(\"null.png\", \"PNG\")\n\ndef generate_colormap():\n \"\"\"\n Creates a colormap to use when creating RGB color images of files\n\n Returns:\n im: colormap\n x: values\n \"\"\"\n x = np.array([ np.arange(x,x+16)/256 for x in range(0,256,16) ])\n im = plt.imshow(x, cmap=plt.cm.nipy_spectral)\n #plt.show()\n return im, x\n\ndef write_bytes_to_file(filepath, dirname, filename, size, colorPath, greyPath, resize, colDct):\n \"\"\"\n Write bytes to an image file\n\n Args:\n filepath (string): filepath to directory to read file from\n dirname (string): name of file to use as new directory name containing section images\n filename (string): filename of section file\n size (int): maximum size if specified, otherwise size of file is used\n colorPath (string): path to directory to store color images\n greyPath (string): path to directory to store grey images\n resize (int): size to resize images to, e.g. resizexresize\n colDct (color map dictionary): dictionary storing color map for RGB\n \"\"\"\n\n path = '{}/{}/{}'.format(filepath,dirname,filename)\n f = open(path, 'rb')\n bytes = f.read()\n\n if not size:\n size = len(bytes)\n if size == 0:\n return\n generate_black_image(WIDTH, int(ceil(size/WIDTH)))\n\n elif size > len(bytes):\n size = len(bytes)\n\n # create new directory for files\n cmd = 'mkdir {}/{}'.format(greyPath, dirname)\n system(cmd)\n\n nullImageColor = None\n nullImageGrey = None\n colorPixels = None\n greyPixels = None\n\n if greyPath:\n nullImageGrey = Image.open(\"null.png\")\n greyPixels = nullImageGrey.load()\n if colorPath:\n nullImageColor = Image.open(\"null.png\")\n colorPixels = nullImageColor.load()\n\n byteCounter = 0\n\n for i in range(0, int(ceil(size/WIDTH))):\n for j in range(0,WIDTH):\n if byteCounter == size-1: break\n byte = hex(bytes[byteCounter])\n\n if greyPath:\n greyRGBvalue = int(byte,16)\n greyPixels[j, i] = (greyRGBvalue, greyRGBvalue, greyRGBvalue)\n if colorPath:\n x,y = 0,0\n if len(byte) == 3:\n x,y = 0, int(byte[2], 16)\n else:\n x, y = int(byte[2],16), int(byte[3], 16)\n # 0,0 is top left. 15,0 is top right. x is correct y is flipped.\n colorPixels[j, i] = colDct[x][y]\n byteCounter += 1\n\n filename = filename[:-4] + \".png\" if filename[-4:] == '.exe' else filename + \".png\"\n if greyPath:\n saveTo = '{}/{}/{}'.format(greyPath, dirname, filename)\n if resize:\n nullImageGrey = nullImageGrey.resize((resize,resize))\n nullImageGrey.save(saveTo)\n if colorPath:\n if resize:\n nullImageColor = nullImageColor.resize((resize, resize))\n nullImageColor.save(colorPath + filename)\n\nif args.size:\n generate_black_image(WIDTH, int(ceil(args.size/WIDTH)))\n\ncolDct = {}\nif args.color:\n cmap, vals = generate_colormap()\n # generate colordict once so it doesn't get recomputed\n colDct = {0 : {},1 : {},2 : {},3:{},4:{},5:{},6:{},7:{},8:{},9:{},10:{},11:{},12:{},13:{},14:{},15:{}}\n for i in range(0,16):\n for j in range(0,16):\n r,g,b,_ = cmap.to_rgba(vals[j, i])\n if not colDct[i].get(j):\n colDct[i][j] = (int(r*255),int(g*255),int(b*255))\n\n# get directories for files\ndir = [f for f in listdir(args.files) if isdir(join(args.files, f))]\n\n# for each filedirectory in dir, e.g. each file1.exe dir representing sections\nfor d in dir:\n # get all section files\n files = [ f for f in listdir(args.files + d) if isfile(join(args.files + d, f))]\n # for each section, write bytes to image file\n for fl in files:\n write_bytes_to_file(args.files, d, fl, args.size, args.color, args.grey, args.resize, colDct)\n","sub_path":"src/data-preparation/sectionImageWriter.py","file_name":"sectionImageWriter.py","file_ext":"py","file_size_in_byte":5821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"321772464","text":"import csv\nimport os\ntry:\n import psycopg2\nexcept ImportError:\n # Fall back to psycopg2cffi\n from psycopg2cffi import compat\n compat.register()\nimport psycopg2\n\n\nconn = psycopg2.connect(\"host=localhost dbname=fec user=postgres password='abcd1234'\")\ncur = conn.cursor()\n\nwith open('manually_coloring_committees.csv', 'r') as f:\n reader = csv.reader(f)\n next(reader, None) # skip the header\n for row in reader:\n if len(row) != 4:\n break\n\n query = \"\"\"\n UPDATE\n committees\n SET\n rev13_rep_percent={manual_color_rep},\n rev13_dem_percent={manual_color_dem},\n rev13_oth_percent={manual_color_indep}\n WHERE\n cmte_id='{cmte_id}';\n \"\"\".format(\n cmte_id=row[0],\n manual_color_dem=row[1],\n manual_color_rep=row[2],\n manual_color_indep=row[3]\n )\n cur.execute(query)\n conn.commit()\n","sub_path":"fill_out_manually_identified_committees.py","file_name":"fill_out_manually_identified_committees.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"529435992","text":"import math\nimport os\n\nimport alpaca_trade_api.rest as alpaca\nimport pandas as pd\nfrom stockstats import StockDataFrame\n\nfrom trading_scripts.utils.constants import ( # ATR_MULTIPLIER,; MAX_DRAWDOWN_PCT,\n HISTORICAL_DATA_INTERVAL,\n HISTORICAL_DATA_PERIOD,\n)\nfrom trading_scripts.utils.helpers import (\n create_client,\n get_historical_data,\n get_last_quote,\n get_positions,\n is_market_open,\n)\nfrom trading_scripts.utils.logger import log\n\n# from time import sleep\n\n\nclass Buyer:\n symbol: str = \"\"\n positions: list[dict] = []\n data: pd.DataFrame = None\n api: alpaca = None\n\n def __init__(\n self, symbol: str = \"\", cash: float = None, sma_fast=10, sma_slow=25, atr=2\n ) -> None:\n self.symbol = symbol\n self.sma_fast = sma_fast\n self.sma_slow = sma_slow\n self.atr = atr\n self.api = create_client()\n self.positions = get_positions()\n self.is_market_open: bool = is_market_open()\n if self.symbol:\n self.data = self.__get_data()\n self._cash = cash\n\n def __get_data(self):\n return StockDataFrame.retype(\n get_historical_data(\n symbol=self.symbol,\n interval=HISTORICAL_DATA_INTERVAL,\n period=HISTORICAL_DATA_PERIOD,\n )\n )\n\n @property\n def position_symbols(self):\n return map(lambda position: position.symbol, self.positions)\n\n @property\n def symbol_is_in_portfolio(self):\n return self.symbol in self.position_symbols\n\n def submit_order(\n self,\n side: str,\n qty: float,\n type: str = \"market\",\n time_in_force: str = \"day\",\n **kwargs,\n ) -> alpaca.Order:\n return self.api.submit_order(\n symbol=self.symbol,\n qty=qty,\n side=side,\n type=type,\n time_in_force=time_in_force,\n **kwargs,\n )\n\n def sma_crossover_signal(self):\n sma_fast = self.data.get(f\"close_{self.sma_fast}_sma\")\n sma_slow = self.data.get(f\"close_{self.sma_slow}_sma\")\n return sma_fast.gt(sma_slow).iloc[-1]\n\n def get_drawdown_points(self):\n atr = self.data.get(\"atr\").iloc[-1]\n output = self.atr * atr\n return round(output, 2)\n\n @property\n def available_cash(self):\n account = self.api.get_account()\n return float(account.cash)\n\n @property\n def last_price(self):\n return get_last_quote(self.symbol)\n\n # def get_trailing_stop_loss_points(\n # self, price: float, get_drawdown_points: float = 5.0\n # ):\n # return min(\n # self.get_drawdown_points(get_drawdown_points),\n # round(price * MAX_DRAWDOWN_PCT, 2),\n # )\n\n def calc_position_size(self):\n # Position Size = (Total Trading Account Size X Risk Percentage) / Distance to Stop Loss from entry\n available_cash = self.available_cash\n risk_pct = 0.05\n last_price = self.last_price\n distance_to_stop = last_price / self.get_drawdown_points()\n position_qty = math.floor((available_cash * risk_pct) / distance_to_stop)\n position_cost = position_qty * last_price\n print(\n f\"available_cash: {available_cash}, position_qty: {position_qty}, position_cost {position_cost}\"\n )\n return position_qty\n\n def create_buy_order(self, qty: int = 0) -> alpaca.Order:\n # log.debug(\"Buyer#create_buy_order\")\n if not qty:\n qty = self.calc_position_size()\n\n # create a new buy order\n try:\n order = self.api.submit_order(\n symbol=self.symbol,\n side=\"buy\",\n type=\"market\",\n qty=qty,\n time_in_force=\"day\",\n )\n log.success(f\"Buy order for {qty} shares of {self.symbol} submitted\")\n return order\n except Exception as error:\n log.error(f\"ERROR: {error}\")\n\n def create_trailing_stop_loss_order(self, buy_order: alpaca.Order):\n # create trailing stop loss order\n # if isinstance(buy_order, alpaca.Position):\n # price = buy_order.current_price\n # else:\n # price = buy_order.filled_avg_price\n try:\n trail_price = self.get_drawdown_points()\n # trail_price = self.get_trailing_stop_loss_points(float(price))\n sell_order = self.submit_order(\n side=\"sell\",\n type=\"trailing_stop\",\n time_in_force=\"gtc\",\n trail_price=trail_price,\n qty=buy_order.qty,\n )\n log.success(\"Trailing Stop order created\")\n log.info(\n f\"HWM: {sell_order.hwm}, Trail Price: {sell_order.trail_price}, Stop Price: {sell_order.stop_price}\"\n )\n except Exception as error:\n log.error(f\"ERROR: {error}\")\n\n def clear_buy_orders(self):\n orders = self.api.list_orders()\n for order in orders:\n if order.side == \"buy\" and order.status != \"filled\":\n try:\n self.api.cancel_order(order.id)\n log.info(f\"Cancelled open buy order for {order.symbol}\")\n except:\n log.warning(f\"Failure to cancel open buy order: {order.id}\")\n\n def run(self):\n if os.getenv(\"IS_TEST\"):\n log.info(\"Preventing purchase in test environment\")\n return\n\n # # only run if market is open\n # if not self.is_market_open:\n # # print(\"Market is not open - preventing execution\")\n # return\n\n # log.info(\"Starting Buyer.run\")\n # if self.symbol_is_in_portfolio:\n # # log.info(f\"Preventing purchase of {self.symbol} - already in portfolio\")\n # return\n\n # print(self.sma_crossover_signal())\n if not self.sma_crossover_signal():\n # log.info(f\"No SMA crossover signal for {self.symbol}\")\n return\n\n qty = self.calc_position_size()\n if qty < 1:\n # log.warning(f\"0 qty order unfilled for {self.symbol}\")\n return\n\n # buy assets\n self.create_buy_order(qty)\n # order = self.create_buy_order(qty)\n\n # prevent execution on error\n # if not order:\n # log.warning(\"Preventing further execution after no buy order returned\")\n # return\n\n # # wait until the order is filled\n # count = 0\n # while order.status != \"filled\" and count < 15:\n # # log.debug(f\"Buy order status: {order.status}\")\n # sleep(0.1)\n # order = self.api.get_order(order.id)\n # count += 1\n\n # # create trailing stop loss order once the order is filled\n # if order.status == \"filled\":\n # log.success(f\"Buy order for {self.symbol} filled\")\n # self.create_trailing_stop_loss_order(order)\n","sub_path":"trading_scripts/lib/Buyer.py","file_name":"Buyer.py","file_ext":"py","file_size_in_byte":6953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"239545889","text":"import os\nimport sys\nimport shutil\nimport logging\n\ndestination_dir='~/.backup/bash'\n\nlogging.basicConfig(filename=log_file,level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\nif not os.path.exists(destination_dir):\n os.makedirs(destination_dir)\n\ntry:\n # print filename\n # copy new bashrc \n shutil.copyfile('~/.bashrc',destination_dir)\n logging.info(\"copied with success:%s\",destination)\nexcept IOError as e:\n logging.warn(\"Error copying: %s\\n%s\", destination_dir,e.message)\n sys.exit()\n # exit\n \n\n\n","sub_path":"notmand/bashconf-setup.py","file_name":"bashconf-setup.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"487070923","text":"#takes user name and birthdate as string input\nname =raw_input(\"Enter your first name: \")\nbirthdate =raw_input(\"Enter your birth date: \")\n\n#file name and creates file if non-existent\nfileName = name + \".txt\"\nf = open(fileName, 'a+')\n\n#writes birthdate on file\nf.write(birthdate)\n\n#closes file\nf.close()\n","sub_path":"writeFile.py","file_name":"writeFile.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"275882742","text":"# import necessary libraries\nfrom flask import Flask, render_template, redirect\nimport pymongo\nimport scrape_mars\n\n# create instance of Flask app\napp = Flask(__name__)\n\n# Use flask_pymongo to set up mongo connection\nconn = \"mongodb://localhost:27017\"\nclient = pymongo.MongoClient(conn)\n\n@app.route(\"/\")\ndef index():\n mars_dict = client.db.mars_dict.find_one()\n return render_template(\"index.html\", mars_dict=mars_dict)\n\n\n@app.route(\"/scrape\")\ndef scraper():\n mars_dict = client.db.mars_dict\n mars_data = scrape_mars.scrape()\n mars_dict.update({}, mars_data, upsert=True)\n return redirect(\"/\", code=302)\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"Web Scraping and Document Databases/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"90676526","text":"\n\nMsamp, Esamp = run_ising(lattice, temp,num_steps,num_burnin,j,b)\n\nM_mean, E_mean, M_std, E_std = get_plot_values(temp,Msamp,Esamp,num_analysis)\ntemp_arr.append(temp)\nM_mean_arr.append(M_mean)\nE_mean_arr.append(E_mean)\nM_std_arr.append(M_std)\nE_std_arr.append(E_std)\n\ndef get_plot_values(temp,Msamp,Esamp,num_analysis): #only for plotting at end\n try:\n M_mean = np.average(Msamp[-num_analysis:])\n E_mean = np.average(Esamp[-num_analysis:])\n M_std = np.std(Msamp[-num_analysis:])\n E_std = np.std(Esamp[-num_analysis:])\n return M_mean, E_mean, M_std, E_std\n except:\n logging.error(\"Temp={0}: Error getting plot values\".format(temp))\n return False\n\ndef plot_graphs(temp_arr,M_mean_arr,M_std_arr,E_mean_arr,E_std_arr): #plot graphs at end\n plt.figure(1)\n plt.ylim(0,1)\n plt.errorbar(temp_arr, np.absolute(M_mean_arr), yerr=M_std_arr, uplims=True, lolims=True,fmt='o')\n plt.xlabel('Temperature')\n plt.ylabel('Magnetization')\n plt.figure(2)\n plt.errorbar(temp_arr, E_mean_arr, yerr=E_std_arr, fmt='o')\n plt.xlabel('Temperature')\n plt.ylabel('Energy')\n plt.show()","sub_path":"python_with_c/e_m_plotting.py","file_name":"e_m_plotting.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"156149230","text":"import pygame\nfrom numpy import pi\nfrom pygame.draw import *\nfrom paintbrush import Paintbrush\nfrom classes_of_gun_objects import Gun, Shell, Target, Bomb\nfrom menu import menu\nfrom manual import manual\nfrom score import score\n\n\nRED = (255, 0, 0)\nBLUE = (0, 0, 255)\nWHITE = (255, 255, 255)\nBLACK = (0,0,0)\nFPS = 50\n\n\nnumber_of_guns = menu()\nmanual(number_of_guns)\ntarget_radius = 50\nwindow_size_x = 1500\nwindow_size_y = 800\nheight_above_the_gun = 70\nradius_of_gyration_min = 100\nradius_of_gyration_max = 200\nmax_speed = 20\nmin_speed = 5\nmove_1 = 0\nmove_2 = 0\nmove_angle_1 = 0\nmove_angle_2 = 0\ngun_1_color = RED\ngun_2_color = BLUE\npower_up = 1\npower_up_1 = False\npower_up_2 = False\nshift_of_gun = 8\nangle_of_gun = pi/100\nlimit_of_power = 100\ngun_size_length = 100\ngun_size_height = 50\nballs = []\nnumber_of_balls = 100\nshell_radius = 30\nlimit_of_speed = 100\nacceleration = 4\nscore_1 = 0\nscore_2 = 0\nspeed_bomb = 1\nacceleration_bomb = 1/5\nradius_bomb = 50\ncolor_period = 1000\nexistence_1 = True\nexistence_2 = number_of_guns\n\n\n\n\n\n\n\ndef new_ball(gun_x, power, gun_y, angle, max_speed, max_power, acceleration, number, balls, number_of_balls, radius):\n balls.append(Shell(gun_x, gun_y, max_speed*power/max_power, angle, acceleration, number, radius))\n if len(balls) >= number_of_balls:\n balls.pop(0)\n \n \n\npygame.init()\nfont = pygame.font.Font(None, 25)\nscreen = pygame.display.set_mode([window_size_x, window_size_y])\nscreen.fill(WHITE)\n\ntarget_1 = Target(1, target_radius, window_size_x, window_size_y, height_above_the_gun, radius_of_gyration_min, radius_of_gyration_max, max_speed, min_speed)\ntarget_2 = Target(2, target_radius, window_size_x, window_size_y, height_above_the_gun, radius_of_gyration_min, radius_of_gyration_max, max_speed, min_speed)\ntarget_3 = Target(3, target_radius, window_size_x, window_size_y, height_above_the_gun, radius_of_gyration_min, radius_of_gyration_max, max_speed, min_speed)\nbomb = Bomb(window_size_x, window_size_y, FPS, speed_bomb, acceleration_bomb, radius_bomb, color_period, BLACK, RED)\n\ngun_1 = Gun(0, gun_1_color, pi/2, limit_of_power)\nif number_of_guns:\n gun_2 = Gun(window_size_x - gun_size_length, gun_2_color, pi/2, limit_of_power)\n\n\npygame.display.update()\npygame.display.set_caption(\"Gun\")\nclock = pygame.time.Clock()\nfinished = False\npaintbrush = Paintbrush(screen, window_size_y, gun_size_height, gun_size_length, target_radius, RED, BLACK, WHITE, shell_radius, BLACK)\nwhile finished == False:\n x1, y1, color = bomb.start()\n if(y1 + radius_bomb >= window_size_y - 1.5*gun_size_height):\n x2, angle, color = gun_1.get_parameters()\n if number_of_guns:\n x3, angle, color = gun_2.get_parameters()\n if(x1 + radius_bomb > x3) and (x1 - radius_bomb < x3 + gun_size_length) and number_of_guns:\n existence_2 = False\n if(x1 + radius_bomb > x2) and (x1 - radius_bomb < x2 + gun_size_length):\n existence_1 = False\n \n if existence_1 == False and existence_2 == False:\n finished = True\n \n \n clock.tick(FPS)\n target_1.turn()\n target_2.turn()\n target_3.turn()\n for i in range(0, len(balls)):\n x, y, number = balls[i].get_parameters()\n if target_1.hit(x,y, shell_radius):\n balls.pop(i)\n if number == 1:\n score_1 += 1\n else:\n score_2 += 1\n elif target_2.hit(x,y, shell_radius):\n balls.pop(i)\n if number == 1:\n score_1 += 2\n else:\n score_2 += 2\n elif target_3.hit(x,y, shell_radius):\n balls.pop(i)\n if number == 1:\n score_1 += 3\n else:\n score_2 += 3\n else:\n balls[i].move(window_size_x)\n if y > window_size_y:\n balls.pop(i)\n else:\n paintbrush.shell_draw(x, y)\n x, angle, color = gun_1.get_parameters()\n power = gun_1.power()\n paintbrush.scale(power, limit_of_power, 1, window_size_x, BLACK, RED)\n text = font.render(\"Score: \" + str(score_1), True, BLACK)\n place = text.get_rect(center=(50, 35))\n screen.blit(text, place)\n if number_of_guns:\n text = font.render(\"Score: \" + str(score_2), True, BLACK)\n place = text.get_rect(center=(window_size_x - 50, 35))\n screen.blit(text, place)\n if number_of_guns:\n power = gun_2.power()\n paintbrush.scale(power, limit_of_power, 2, window_size_x, BLACK, RED)\n if existence_1:\n paintbrush.gun_draw(angle, x, BLACK, color)\n if existence_2:\n x, angle, color = gun_2.get_parameters()\n paintbrush.gun_draw(angle, x, BLACK, color)\n x, y = target_1.get_parameters()\n paintbrush.target_draw(x, y)\n x, y = target_2.get_parameters()\n paintbrush.target_draw(x, y)\n x, y = target_3.get_parameters()\n paintbrush.target_draw(x, y)\n \n x, y, color = bomb.start()\n paintbrush.bomb_draw(x, y, radius_bomb, color)\n \n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n finished = True\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT:\n move_2 = -1\n elif event.key == pygame.K_RIGHT:\n move_2 = 1\n if event.key == pygame.K_a:\n move_1 = -1\n elif event.key == pygame.K_d:\n move_1 = 1\n if event.key == pygame.K_w:\n move_angle_1 = 1\n elif event.key == pygame.K_s:\n move_angle_1 = -1\n if event.key == pygame.K_UP:\n move_angle_2 = 1\n elif event.key == pygame.K_DOWN:\n move_angle_2 = -1\n \n if event.key == pygame.K_v:\n power_up_1 = True\n if event.key == pygame.K_p:\n power_up_2 = True\n elif event.type == pygame.KEYUP:\n if event.key == pygame.K_LEFT and move_2 != 0:\n move_2 = 0\n elif event.key == pygame.K_RIGHT and move_2 != 0:\n move_2 = 0\n if event.key == pygame.K_a and move_1 != 0:\n move_1 = 0\n elif event.key == pygame.K_d and move_1 != 0:\n move_1 = 0\n if event.key == pygame.K_w and move_angle_1 != 0:\n move_angle_1 = 0\n elif event.key == pygame.K_s and move_angle_1 != 0:\n move_angle_1 = 0\n if event.key == pygame.K_UP and move_angle_2 != 0:\n move_angle_2 = 0\n elif event.key == pygame.K_DOWN and move_angle_2 != 0:\n move_angle_2 = 0\n \n if event.key == pygame.K_v and power_up_1:\n power_up_1 = False\n x, angle, power = gun_1.shot()\n if existence_1:\n new_ball(x + gun_size_length/2, power, window_size_y - gun_size_height*3/2, angle, limit_of_speed, limit_of_power, acceleration, 1, balls, number_of_balls, shell_radius)\n if event.key == pygame.K_p and power_up_2:\n power_up_2 = False\n if number_of_guns:\n x, angle, power = gun_2.shot()\n if existence_2:\n new_ball(x + gun_size_length/2, power, window_size_y - gun_size_height*3/2, angle, limit_of_speed, limit_of_power, acceleration, 2, balls, number_of_balls, shell_radius)\n gun_1.move(move_1*shift_of_gun, window_size_x, gun_size_length)\n gun_1.turn(move_angle_1*angle_of_gun)\n if power_up_1:\n gun_1.increase_power(power_up)\n if number_of_guns:\n gun_2.move(move_2*shift_of_gun, window_size_x, gun_size_length)\n gun_2.turn(move_angle_2*angle_of_gun)\n if power_up_2:\n gun_2.increase_power(power_up)\n pygame.display.update()\n screen.fill(WHITE)\npygame.quit()\n\nscore(number_of_guns, score_1, score_2)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"649525876","text":"#cool.py\n#Moves a blue rectangle around the screen\n#Use WASD or arrow keys to move character\nimport pygame,sys #imports modules\nfrom pygame.locals import * #imports a libary of pygame\n\npygame.init() #initialises pygame\ndisplay = pygame.display.set_mode((600,400)) #creates a pygame window\nFPS = pygame.time.Clock() #Sets up a clock\npygame.display.set_caption(\"Cool stuff\") #Sets window title\nimgx = 10 #x/y variables for the character\nimgy = 10\n\nwhite=(255,255,255) #Declares colours\nblue= (10,255,10)\ndisplay.fill(white)\nwhile True: #main loop\n pygame.draw.rect(display,blue,(imgx,imgy,imgx+30,imgy+30))#Draws a square based on imgy and imgx\n\n for event in pygame.event.get(): #checks for events\n if event.type == QUIT: #If player wants to quit..\n pygame.quit #..stops pygame\n sys.exit #Exits the window\n elif event.type == KEYDOWN: #If there is a key down..\n if event.key in (K_LEFT,K_a): #If the key is left or d\n imgx -= 30 #Moves character left\n elif event.key in (K_RIGHT,K_d): #If the key is right or a\n imgx += 30 #moves character right\n elif event.key in (K_UP,K_w): #If the key is up or w\n imgy -= 30 #moves character up\n elif event.key in (K_DOWN,K_s): #If the key is down or s\n imgy += 30 #Moves character down\n pygame.display.update() #Updates screen\n #clock.tick(30) #FPS tick (30 FPS)\n","sub_path":"HW/5/cool.py","file_name":"cool.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"416797846","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\nfrom setuptools import setup, find_packages\r\nimport os, sys\r\n\r\nwith open('README.md') as readme_file:\r\n readme = readme_file.read()\r\n\r\n\r\nwith open('requirements.txt') as f:\r\n requirements = f.read().splitlines()\r\n\r\ndata_dir = os.path.join(sys.prefix, \"local/lib/python2.7/dist-packages/biocertainty\")\r\n\r\n \r\nsetup(name='biocertainty',\t\r\n version='1.0.8',\t\r\n description='Python package that provides the certainty about biomedical statements.',\t\r\n url='https://github.com/Guindillator/BioCertainty',\t\r\n author='Mario Prieto',\t\r\n author_email='mario.prieto@upm.es',\t\r\n license='Wilkinson Laboratory',\r\n packages=find_packages(),\r\n install_requires=requirements,\r\n long_description=readme,\r\n package_dir={'biocertainty':\r\n 'biocertainty'},\t\r\n zip_safe=False,\r\n classifiers=[\r\n 'Development Status :: 2 - Pre-Alpha',\r\n 'Intended Audience :: Developers',\r\n 'License :: OSI Approved :: MIT License',\r\n 'Natural Language :: English',\r\n \"Programming Language :: Python :: 2\",\r\n 'Programming Language :: Python :: 2.7'\r\n ],\r\n test_suite='tests',\r\n# install_requires=requirements,\r\n# data_files=[('', ['data/training_set.csv'])],\r\n# package_data = {'': ['data/training_set.csv']},\r\n data_files = [(os.path.join(data_dir), [(\"data/training_set.csv\"),\r\n (\"data/model.json\"), \r\n (\"data/model.h5\")])],\r\n# package_data = {\"biocertainty\": [( \"data/training_set.csv\"),\r\n# ( \"data/model.json\"), \r\n# ( \"data/model.h5\")]},\r\n# # package_data = {\"biocertainty\": [os.path.join(data_dir, \"data/training_set.csv\"),\r\n# # os.path.join(data_dir, \"data/model.json\"), \r\n# # os.path.join(data_dir, \"data/model.h5\")]},\r\n include_package_data = True, \r\n setup_requires=[\r\n # dependency for `python setup.py test`\r\n 'pytest-runner',\r\n # dependencies for `python setup.py build_sphinx`\r\n 'sphinx',\r\n 'recommonmark'\r\n ],\r\n tests_require=[\r\n 'pytest',\r\n 'pytest-cov',\r\n 'pycodestyle',\r\n ]\r\n)\r\n\r\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"575049138","text":"# -*- coding: utf-8 -*-\nimport unittest\n\nfrom openprocurement.api.tests.base import snitch\n\nfrom openprocurement.tender.belowthreshold.tests.base import (\n test_organization,\n)\nfrom openprocurement.tender.belowthreshold.tests.bid_blanks import (\n # TenderBidDocumentResourceTest\n not_found,\n # TenderBidderBatchDocumentWithDSResourceTest\n create_tender_bid_with_documents,\n create_tender_bid_with_document_invalid,\n create_tender_bid_with_document,\n)\n\nfrom openprocurement.tender.openua.tests.base import (\n BaseTenderUAContentWebTest,\n test_tender_data,\n test_features_tender_ua_data,\n)\nfrom openprocurement.tender.openua.tests.bid_blanks import (\n # TenderBidResourceTest\n create_tender_biddder_invalid,\n create_tender_bidder,\n patch_tender_bidder,\n get_tender_bidder,\n delete_tender_bidder,\n deleted_bid_is_not_restorable,\n deleted_bid_do_not_locks_tender_in_state,\n get_tender_tenderers,\n bid_Administrator_change,\n draft1_bid,\n draft2_bids,\n bids_invalidation_on_tender_change,\n bids_activation_on_tender_documents,\n # TenderBidFeautreResourceTest\n features_bidder,\n features_bidder_invalid,\n # TenderBidDocumentResourceTest\n create_tender_bidder_document,\n put_tender_bidder_document,\n patch_tender_bidder_document,\n create_tender_bidder_document_nopending,\n # TenderBidDocumentWithDSResourceTest\n create_tender_bidder_document_json,\n put_tender_bidder_document_json,\n)\n\n\nclass TenderBidResourceTestMixin(object):\n test_create_tender_biddder_invalid = snitch(create_tender_biddder_invalid)\n test_create_tender_bidder = snitch(create_tender_bidder)\n test_patch_tender_bidder = snitch(patch_tender_bidder)\n test_get_tender_bidder = snitch(get_tender_bidder)\n test_delete_tender_bidder = snitch(delete_tender_bidder)\n test_deleted_bid_is_not_restorable = snitch(deleted_bid_is_not_restorable)\n test_deleted_bid_do_not_locks_tender_in_state = snitch(deleted_bid_do_not_locks_tender_in_state)\n test_get_tender_tenderers = snitch(get_tender_tenderers)\n test_bid_Administrator_change = snitch(bid_Administrator_change)\n test_bids_invalidation_on_tender_change = snitch(bids_invalidation_on_tender_change)\n test_bids_activation_on_tender_documents = snitch(bids_activation_on_tender_documents)\n\n\nclass TenderBidDocumentResourceTestMixin(object):\n test_create_tender_bidder_document = snitch(create_tender_bidder_document)\n test_put_tender_bidder_document = snitch(put_tender_bidder_document)\n test_patch_tender_bidder_document = snitch(patch_tender_bidder_document)\n test_create_tender_bidder_document_nopending = snitch(create_tender_bidder_document_nopending)\n\n\nclass TenderBidResourceTest(BaseTenderUAContentWebTest, TenderBidResourceTestMixin):\n initial_data = test_tender_data\n initial_status = 'active.tendering'\n author_data = test_organization\n\n test_draft1_bid = snitch(draft1_bid)\n test_draft2_bids = snitch(draft2_bids)\n\n\nclass TenderBidFeaturesResourceTest(BaseTenderUAContentWebTest):\n initial_data = test_features_tender_ua_data\n initial_status = 'active.tendering'\n\n test_features_bidder = snitch(features_bidder)\n test_features_bidder_invalid = snitch(features_bidder_invalid)\n\n\nclass TenderBidDocumentResourceTest(BaseTenderUAContentWebTest, TenderBidDocumentResourceTestMixin):\n initial_status = 'active.tendering'\n author_data = test_organization\n\n def setUp(self):\n super(TenderBidDocumentResourceTest, self).setUp()\n # Create bid\n response = self.app.post_json('/tenders/{}/bids'.format(\n self.tender_id), {'data': {'selfEligible': True, 'selfQualified': True,\n 'tenderers': [test_organization], \"value\": {\"amount\": 500}}})\n bid = response.json['data']\n self.bid_id = bid['id']\n self.bid_token = response.json['access']['token']\n\n test_not_found = snitch(not_found)\n\n\nclass TenderBidDocumentWithDSResourceTest(TenderBidDocumentResourceTest):\n docservice = True\n\n test_create_tender_bidder_document_json = snitch(create_tender_bidder_document_json)\n test_put_tender_bidder_document_json = snitch(put_tender_bidder_document_json)\n\n\n\nclass TenderBidderBatchDocumentWithDSResourceTest(BaseTenderUAContentWebTest):\n docservice = True\n initial_status = 'active.tendering'\n\n bid_data_wo_docs = {'tenderers': [test_organization],\n 'value': {'amount': 500},\n 'selfEligible': True,\n 'selfQualified': True,\n 'documents': []\n }\n\n create_tender_bid_with_document_invalid = snitch(create_tender_bid_with_document_invalid)\n create_tender_bid_with_document = snitch(create_tender_bid_with_document)\n create_tender_bid_with_documents = snitch(create_tender_bid_with_documents)\n\n\ndef suite():\n suite = unittest.TestSuite()\n suite.addTest(unittest.makeSuite(TenderBidDocumentResourceTest))\n suite.addTest(unittest.makeSuite(TenderBidDocumentWithDSResourceTest))\n suite.addTest(unittest.makeSuite(TenderBidFeaturesResourceTest))\n suite.addTest(unittest.makeSuite(TenderBidResourceTest))\n return suite\n\n\nif __name__ == '__main__':\n unittest.main(defaultTest='suite')\n","sub_path":"openprocurement/tender/openua/tests/bid.py","file_name":"bid.py","file_ext":"py","file_size_in_byte":5292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"188222718","text":"#!/usr/bin/env python3\n\"\"\" Likelihood for Binomial distribution \"\"\"\nimport numpy as np\n\n\ndef likelihood(x, n, P):\n \"\"\" Likelihood for Binomial distribution \"\"\"\n if type(n) is not int or n <= 0:\n raise ValueError(\"n must be a positive integer\")\n if type(x) is not int or x < 0:\n raise ValueError(\"x must be an integer that is greater than or\"\n \" equal to 0\")\n if x > n:\n raise ValueError(\"x cannot be greater than n\")\n if type(P) is not np.ndarray or len(P.shape) != 1:\n raise TypeError(\"P must be a 1D numpy.ndarray\")\n for i in P:\n if i < 0 or i > 1:\n raise ValueError(\"All values in P must be in the range [0, 1]\")\n fact = np.math.factorial\n a = fact(n) / (fact(x) * fact(n - x))\n b = (P**x) * ((1 - P)**(n - x))\n return a * b\n","sub_path":"math/0x07-bayesian_prob/0-likelihood.py","file_name":"0-likelihood.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"196897808","text":"import numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.model_selection import train_test_split, cross_val_score\r\nfrom sklearn import metrics\r\nfrom sklearn.metrics import auc\r\nfrom sklearn.metrics import roc_curve\r\nfrom sklearn import preprocessing\r\nle = preprocessing.LabelEncoder()\r\ndf = pd.read_csv('./spam.csv',delimiter=\"\\t\", error_bad_lines=False)\r\ndf[\"Label\"]=df.index\r\ndf.index = np.arange(1, len(df) + 1)\r\nx=df.iloc[:,0]\r\ny=df.iloc[:,1]\r\ny=le.fit_transform(y)\r\nX_train_raw, X_test_raw, y_train, y_test = train_test_split(x,y)\r\n\r\n#X_train_raw=x\r\n#y_train=y\r\nvectorizer = TfidfVectorizer()\r\nX_train = vectorizer.fit_transform(X_train_raw)\r\nX_test = vectorizer.transform(X_test_raw)\r\n\r\nclassifier = LogisticRegression()\r\nclassifier.fit(X_train, y_train)\r\npredict = classifier.predict_proba(X_test)[:,1]\r\nfpr, tpr, thresholds = roc_curve(y_test, predict, pos_label=2)\r\nroc_auc = auc(y_test, predict)\r\n# Plot ROC curve\r\nplt.plot(fpr, tpr, label='ROC curve (area = %0.3f)' % roc_auc)\r\nplt.plot([0, 1], [0, 1], 'k--') # random predictions curve\r\nplt.xlim([0.0, 1.0])\r\nplt.ylim([0.0, 1.0])\r\nplt.xlabel('False Positive Rate or (1 - Specifity)')\r\nplt.ylabel('True Positive Rate or (Sensitivity)')\r\nplt.title('Receiver Operating Characteristic')\r\nplt.legend(loc=\"lower right\")\r\nplt.show()\r\n","sub_path":"28_ROC_curve.py","file_name":"28_ROC_curve.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"595078448","text":"#Give the absolute value of the number\n#Author Shane Kelly\n\n#In the question, number is ambiguos but the output implies that we should \n#be dealing with floats so I am casting the input to a float \n\nnumber= float(input(\"Enter a number:\"))\nabsoluteValue = abs(number)\n\nprint('The absolute value of {} is{}'.format(number, absoluteValue))\n","sub_path":"Week_03/lab3.2.2-absolute.py","file_name":"lab3.2.2-absolute.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"341332912","text":"import random\nfrom repo import GraphFile, Graph\nfrom service import GraphService\nfrom ui import UI\n\n'''\n This function creates a random graph which will be stored in a file.\n It uses two inputs from the user, a number of vertices and a number of edges\n'''\n\n\ndef create_random_graph():\n number_of_vertices = int(input(\"Type the number of vertices: \"))\n number_of_edges = int(input(\"Type the number of edges: \"))\n probable_id_for_vertex = list(range(number_of_vertices))\n probable_cost_for_vertex = []\n for index in range(number_of_edges + 1):\n new_cost = random.randrange(0, number_of_edges + 100, 2)\n probable_cost_for_vertex.append(new_cost)\n random_file = open(\"random_graph\", 'w+')\n first_line = str(number_of_vertices) + \" \" + str(number_of_edges) + \" \\n\"\n random_file.write(first_line)\n for line_index in range(number_of_edges):\n start_vertex_id = random.randrange(len(probable_id_for_vertex))\n start_vertex = str(probable_id_for_vertex[start_vertex_id])\n end_vertex_id = random.randrange(len(probable_id_for_vertex))\n end_vertex = str(probable_id_for_vertex[end_vertex_id])\n cost_id = random.randrange(len(probable_cost_for_vertex))\n cost = str(probable_cost_for_vertex[cost_id])\n line = start_vertex + \" \" + end_vertex + \" \" + cost + '\\n'\n random_file.write(line)\n random_file.close()\n\n\n'''\n From the start of the application the user has two choices\n To use a random graph or to use a specific one\n'''\n\n\ndef choice():\n print(\"If you want to work with a random graph press 1\")\n print(\"If you want to work with a specific graph press 2\")\n command = input(\">>> \")\n if command == '1':\n create_random_graph()\n repo = GraphFile(\"random_graph\", Graph.read_line, Graph.write_line, Graph.read_first_line,\n Graph.write_first_line)\n service = GraphService(repo)\n console = UI(service)\n console.ui_main()\n elif command == '2':\n repo = GraphFile(\"graph\", Graph.read_line, Graph.write_line, Graph.read_first_line, Graph.write_first_line)\n service = GraphService(repo)\n console = UI(service)\n console.ui_main()\n else:\n raise TypeError(\"Please choose one of the above\")\n\n\nchoice()\n","sub_path":"Lab_1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"37641540","text":"import asyncio\nimport json\nfrom http import HTTPStatus\n\nfrom aiohttp import web\nfrom aiologger import Logger\nfrom asynctest import TestCase, Mock, CoroutineMock, MagicMock\n\nfrom app.middlewares import middleware\n\n\nclass MiddlewareTests(TestCase):\n async def setUp(self):\n self.request = MagicMock(\n rel_url=\"https://www.conversion.com\",\n loop=CoroutineMock(spec=asyncio.AbstractEventLoop),\n app={\"logger\": Mock(spec=Logger)},\n )\n\n async def test_404_responses_returns_json_responses_as_is(self):\n response = web.json_response(status=HTTPStatus.NOT_FOUND)\n handler = CoroutineMock(return_value=response)\n middleware_response = await middleware(self.request, handler)\n\n handler.assert_awaited_once_with(self.request)\n self.assertEqual(middleware_response, response)\n\n async def test_404_exceptions_returns_a_json_response_for_non_json_responses(\n self\n ):\n exc = web.HTTPNotFound()\n handler = CoroutineMock(side_effect=exc)\n middleware_response = await middleware(self.request, handler)\n\n handler.assert_called_once_with(self.request)\n\n self.assertEqual(middleware_response.content_type, \"application/json\")\n self.assertEqual(middleware_response.status, 404)\n self.assertEqual(middleware_response.reason, exc.reason)\n self.assertEqual(\n json.loads(middleware_response.text), {\"message\": \"404: Not Found\"}\n )\n\n async def test_500_exceptions_returns_a_valid_json_response(self):\n exc = web.HTTPInternalServerError()\n handler = CoroutineMock(side_effect=exc)\n middleware_response = await middleware(self.request, handler)\n\n handler.assert_called_once_with(self.request)\n\n self.assertEqual(middleware_response.content_type, \"application/json\")\n self.assertEqual(middleware_response.status, 500)\n self.assertEqual(\n json.loads(middleware_response.text),\n {\"message\": \"500: Internal Server Error\"},\n )\n\n async def test_422_exceptions_gets_logged_and_returns_a_valid_json_response(\n self\n ):\n exc = web.HTTPUnprocessableEntity(body=b\"{'data': ['missing']}\")\n handler = CoroutineMock(side_effect=exc)\n middleware_response = await middleware(self.request, handler)\n\n handler.assert_called_once_with(self.request)\n self.assertEqual(middleware_response.content_type, \"application/json\")\n self.assertEqual(middleware_response.status, 422)\n self.assertEqual(middleware_response.reason, exc.reason)\n\n async def test_other_exceptions_gets_raised(self):\n exc = web.HTTPBadGateway()\n handler = CoroutineMock(side_effect=exc)\n\n with self.assertRaises(web.HTTPBadGateway):\n await middleware(self.request, handler)\n","sub_path":"tests/test_middlewares.py","file_name":"test_middlewares.py","file_ext":"py","file_size_in_byte":2846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"610882071","text":"import random\nimport wand\nfrom flat import rgb, font, shape, strike, document, command\n\nr=random\nred = rgb(255, 0, 0)\n#lato = font.open('Lato-Reg.otf')\nfigure = shape().stroke(red).width(0.5)\n#headline = strike(lato).color(red).size(20, 24)\n\nd = document(100, 100, 'mm')\np = d.addpage()\np.place(figure.circle(50, 50, 20))\np.place(figure.circle(50, 50, 20)).position(random.randint(50,50),random.randint(50,50))\nd.pdf('hello.pdf')\n\nfrom wand.image import Image as wi\npdf = wi(filename=\"hello.pdf\", resolution=300)\npdfimage = pdf.convert(\"jpeg\")\ni=1\nfor img in pdfimage.sequence:\n page = wi(image=img)\n page.save(filename=str(i)+\".jpg\")\n i +=1","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"429085817","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.3 (3230)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: ./src/Support/Host.py\n# Compiled at: 2014-08-01 13:34:49\n# Size of source mod 2**32: 1387 bytes\nfrom binding import *\nfrom src.namespace import sys\ngetDefaultTargetTriple = sys.Function('getDefaultTargetTriple', cast(ConstStdString, str))\nif LLVM_VERSION >= (3, 3):\n getProcessTriple = sys.Function('getProcessTriple', cast(ConstStdString, str))\n isLittleEndianHost = sys.CustomFunction('isLittleEndianHost', 'llvm_sys_isLittleEndianHost', cast(Bool, bool))\n isBigEndianHost = sys.CustomFunction('isBigEndianHost', 'llvm_sys_isBigEndianHost', cast(Bool, bool))\nelse:\n isLittleEndianHost = sys.Function('isLittleEndianHost', cast(Bool, bool))\n isBigEndianHost = sys.Function('isBigEndianHost', cast(Bool, bool))\ngetHostCPUName = sys.Function('getHostCPUName', cast(ConstStdString, str))\ngetHostCPUFeatures = sys.CustomFunction('getHostCPUFeatures', 'llvm_sys_getHostCPUFeatures', PyObjectPtr, PyObjectPtr)","sub_path":"pycfiles/llvmpy-0.12.7.tar/Host.cpython-33.py","file_name":"Host.cpython-33.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"550935539","text":"from microbit import *\nfrom neopixel import NeoPixel\n \nnum_pixels = 24\nforeground = [0, 0, 255] # Hex color - red, green and blue\nbackground = [16, 16, 16]\n \nring = NeoPixel(pin0, num_pixels)\n \nwhile True:\n # blue dot circles around a white background (for PixelRing 24)\n for i in range(0, num_pixels):\n ring[i] = foreground # set pixel i to foreground\n ring.show() # actually display it\n sleep(50) # milliseconds\n ring[i] = background # set pixel to background before moving on\n ring.show()\n","sub_path":"koulutus/HaloDisplayTest.py","file_name":"HaloDisplayTest.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"492192649","text":"import RPi.GPIO as GPIO\nimport time\n\nKEY=20\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(KEY,GPIO.IN,GPIO.PUD_UP)\n\nwhile(True):\n if GPIO.input(KEY)==0:\n print(\"Key Test Program\")\n break","sub_path":"reference/python_projects1/python_projects1/key_press.py","file_name":"key_press.py","file_ext":"py","file_size_in_byte":192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"258793323","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n' multi job module '\n\n__author__ = 'Yuechen Yang'\n\nfrom util.operate_mysql import *\nfrom util.process_job import *\nfrom util.common import *\nfrom util.multi_processes import *\n\nclass Calculat_MA_MACD_2_Mysql(Process_Job, Multi_Processes):\n\n ########################################### 从数据库中获取股票列表数据 #################################################\n def get_stock_index_list_from_mysql(self, source_index_list_table_name):\n operatMySQl = OperateMySQL()\n\n stock_list = []\n operatMySQl.execute(\"SELECT distinct stock_index FROM %s\" % source_index_list_table_name)\n records = operatMySQl.fetchall()\n for row in records:\n stock_list.append(\"%06d\" % int(row[0]))\n\n print(\"Total Stock Number:%s Time%s\" % (len(records), (str(datetime.datetime.now()))))\n\n return stock_list\n\n ########################################################################################################################\n ######################################## MACD 计算 #######################################################\n ########################################################################################################################\n ################################################### 计算MACD 值 ########################################################\n def calculate_macd(self, records, SHORT=12, LONG=26, M=9):\n macd_list = []\n index = 0\n precision = 2\n laset_row = None\n\n for row in records:\n code, date, open, high, low, close, volume, turnover = row[:8]\n index = index + 1\n if (index == 1):\n ema12 = close\n ema26 = close\n diff = 0.0\n dea = 0.0\n bar = 0.0\n laset_row = row + (\n round(ema12, precision), round(ema26, precision), round(diff, precision), round(dea, precision),\n round(bar, precision),)\n macd_list.append(laset_row)\n else:\n ema12 = close * 2 / (SHORT + 1) + last_day_ema12 * (SHORT - 1) / (SHORT + 1)\n ema26 = close * 2 / (LONG + 1) + last_day_ema26 * (LONG - 1) / (LONG + 1)\n ema12 = my_round(ema12)\n ema26 = my_round(ema26)\n diff = ema12 - ema26\n dea = ((last_day_dea * 8) + (diff * 2)) / 10\n bar = 2 * (diff - dea)\n\n laset_row = row + (my_round(ema12), my_round(ema26), my_round(diff), my_round(dea), my_round(bar))\n macd_list.append(laset_row)\n last_day_ema12 = ema12\n last_day_ema26 = ema26\n last_day_dea = dea\n\n return macd_list\n\n ########################################################################################################################\n ######################################### MA 计算 ########################################################\n ########################################################################################################################\n ################################################## 计算一组算术 MA 值 ##################################################\n def calculate_ma(self, records, ma_x):\n queue_close = []\n ma_list = []\n index = 0\n for row in records:\n code, date, open, high, low, close, volume, turnover = row[:8]\n index = index + 1\n queue_close.append(float(close))\n ma_update = sum(queue_close) / len(queue_close)\n if (index >= ma_x):\n queue_close.pop(0)\n ma_list.append(row + (str(round(ma_update, 2)),))\n return ma_list\n\n ######################################### 计算单只股票的算术MA 值 并插入数据库 #########################################\n def process(self, from_table_name, to_talbe_name, stock_index, index, list_len):\n operatMySQl = OperateMySQL()\n\n ma_list = [2, 3, 5, 8, 10, 13, 20, 21, 30, 34, 55, 60, 89, 120]\n\n # 打印进度 时间 ID\n print(\"processed: %s%%, Id:%s, Time:%s\" % (\n int((index / list_len) * 100), stock_index, (str(datetime.datetime.now()))))\n\n sql = \"SELECT * FROM {0} where stock_index = '{1}'\"\n sql = sql.format(from_table_name, stock_index)\n operatMySQl.execute(sql)\n records = operatMySQl.fetchall()\n # 计算MA\n for m_ma in ma_list:\n records = self.calculate_ma(records, m_ma)\n # 计算MACD\n records = self.calculate_macd(records)\n for record in records:\n sqli = \"insert into %s \" % to_talbe_name + \"values ('{0}',\\\"{1}\\\",{2},{3},{4},{5},{6},{7},{8},{9},\" \\\n \"{10},{11},{12},{13},{14},{15},{16},{17},{18},{19},{20});\"\n code, date, open, high, low, close, volume, turnover, ma2, ma3, ma5, ma8, \\\n ma10, ma13, ma20, ma21, ma30, ma34, ma55, ma60, ma89, ma120, ema12, ema26, diff, dea, bar = record[:27]\n sqlm = sqli.format(code, date, ma2, ma3, ma5, ma8, ma10, ma13, ma20, ma21, ma30,\n ma34, ma55, ma60, ma89, ma120, ema12, ema26, diff, dea, bar)\n # print(sqlm)\n try:\n operatMySQl.execute(sqlm)\n # print(sqlm)\n except:\n print(\"Insert Error\", sqlm)\n\n operatMySQl.commit()\n\n def __init__(self, from_table_name, to_talbe_name):\n #初始化本策略参数\n self.__from_table_name = from_table_name\n self.__to_talbe_name = to_talbe_name\n\n def get_list(self):\n return self.get_stock_index_list_from_mysql(self.__from_table_name)\n\n def get_args(self):\n return self.__from_table_name, self.__to_talbe_name\n","sub_path":"stock_rule/calculat_ma_macd_2_mysql.py","file_name":"calculat_ma_macd_2_mysql.py","file_ext":"py","file_size_in_byte":5918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"387221778","text":"#TODO\n'''\nMap plot\n'''\n\nfrom .taylor import TaylorDiagram\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport numpy as np\nfrom mpl_toolkits.basemap import Basemap\nfrom .io import Raster\n\n\ndef layout(src, *arg, **kargs):\n '''\n Inputs:\n -----------------------\n :src - geoPackage.io.Raster object\n :kargs - {'cmap': plt.cm.colorbar object,\n 'location': location of colorbar right/bottom,\n 'remove_neg': bool; don't display negative values\n 'cb_label': label of colorbar,\n 'extent': base map extent 'global'/'local',\n 'save': save path}\n\n Returns:\n -----------------------\n :map - Basemap object\n '''\n cmap= kargs.get('cmap', cm.rainbow)\n loc= kargs.get('location', 'bottom')\n cb_label= kargs.get('cb_label', '')\n extent= kargs.get('extent', 'global')\n dst= kargs.get('save', None)\n remove= kargs.get('remove_neg', True)\n figkargs= {key: kargs[key] for key in kargs.keys() if key in ['figsize', 'dpi']}\n meshplotkargs= {key: kargs[key] for key in kargs.keys() if key in ['vmin', 'vmax']}\n\n if not isinstance(src, Raster):\n raise ValueError('expected geo.Package.io.Raster object, but get %s'%type(src))\n\n ulx, xres, _, uly, _, yres = src.geotransform\n m,n= src.array.shape\n xmin= ulx+ 0.5*xres\n ymin= uly+ 0.5*yres\n xmax = xmin + ((src.layer.RasterXSize-0.5) * xres)\n ymax = ymin + ((src.layer.RasterYSize-0.5) * yres)\n lons= np.linspace(xmin, xmax, n)\n lats= np.linspace(ymin, ymax, m)\n x,y = np.meshgrid(lons, lats)\n data= src.array\n if remove:\n data[data<0]= np.nan\n # print(xmin, xmax, ymin, ymax)\n\n if extent=='global':\n map_extent= (-180, 180, -90, 90)\n else:\n map_extent= (xmin, xmax, ymin, ymax)\n\n fig= plt.figure(**figkargs)\n m = Basemap(projection='cyl', resolution='l',\n llcrnrlat=map_extent[3], urcrnrlat=map_extent[2],\n llcrnrlon=map_extent[0], urcrnrlon=map_extent[1])\n m.drawcoastlines(linewidth=0.5)\n m.drawparallels(np.arange(-90, 91, 45), labels=[True,False,False,True], dashes=[10,10], linewidth=.5)\n m.drawmeridians(np.arange(-180, 180, 45), labels=[True,False,False,True], dashes=[10,10], linewidth=.5)\n # cmap= plt.get_cmap('rainbow') if cmap is None else plt.get_cmap(cmap)\n x,y = m(x,y)\n map = m.pcolormesh(x,y, data, cmap=cmap, **meshplotkargs)\n cb = m.colorbar(location=loc, pad='10%')\n cb.set_label(cb_label)\n if dst is not None:\n fig.savefig(dst)\n\n return map\n\n\ndef taylorPlot(*args, **kargs):\n '''\n Inputs:\n ------------------------\n :args\n data=arg[0]\n example\n [\n [std, cc, name]\n ]\n :kargs\n refstd=1.0, fig=None, rect=111, label='_', srange=(0, 1.5), extend=False\n '''\n data= args[0]\n markers= args[1]\n colors= args[2]\n dst= kargs.get('save', None)\n diakargs= {key: kargs[key] for key in kargs.keys() if key in ['refstd', 'fig', 'rect', 'label', 'srange', 'extend']}\n figkargs= {key: kargs[key] for key in kargs.keys() if key in ['figsize', 'dpi']}\n dia= TaylorDiagram(**diakargs)\n fig = plt.figure(**figkargs)\n for i, (stddev, corrcoef, name) in enumerate(data):\n dia.add_sample(stddev, corrcoef,\n marker=markers[i], ms=10, ls='',\n mfc=colors[i],mec=colors[i],\n# mfc='k', mec='k',\n label=str(name))\n contours = dia.add_contours(levels=5, colors='0.5')\n plt.clabel(contours, inline=1, fontsize=10, fmt='%.2f')\n\n dia.add_grid() # Add grid\n dia._ax.axis[:].major_ticks.set_tick_out(True) # Put ticks outward\n\n # Add a figure legend and title\n fig.legend(dia.samplePoints,\n [ p.get_label() for p in dia.samplePoints ],\n numpoints=1, prop=dict(size='large'), loc='upper right')\n cbar= fig.add_axes((0.5,0.9,.4,.01))\n cb = plt.colorbar(orientation='horizontal', mappable= plt.matplotlib.cm.ScalarMappable(cmap=plt.matplotlib.cm.rainbow), cax=cbar, fraction=0.70, shrink=0.7,ticks=[0,1,2,3,4])\n cb.set_label('Temperature')\n cb.ax.set_xticks(range(5))\n cb.ax.set_xticklabels(['cold','hot'])\n# fig.suptitle(\"Taylor diagram\", size='x-large') # Figure title\n if dst is not None:\n fig.savefig(dst, dpi=144)\n\n return dia\n","sub_path":"visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":4427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"535932220","text":"from pyspark.sql import SparkSession\r\nfrom pyspark.sql.functions import explode\r\nfrom pyspark.sql.types import IntegerType, StringType, StructType\r\nfrom pyspark.sql.functions import explode\r\nfrom pyspark.sql.functions import split\r\nfrom pyspark.sql.functions import desc, col\r\nspark = SparkSession \\\r\n .builder \\\r\n .appName(\"Task1\") \\\r\n .getOrCreate()\r\n\r\n'''\r\nuserSchema = StructType().add(\"name\", \"string\").add(\"age\", \"integer\").add(\"ID\",\"string\"), Lang, Date, Source, len, Likes, RTs, Hashtags, UserMentionNames, UserMentionID, Name, Place, Followers,\r\n'''\r\nuserSchema = StructType() \\\r\n\t.add(\"ID\",\"string\") \\\r\n\t.add(\"Lang\",\"string\") \\\r\n\t.add(\"Date\",\"string\") \\\r\n\t.add(\"Source\",\"string\") \\\r\n\t.add(\"len\",\"string\") \\\r\n\t.add(\"Likes\",\"string\") \\\r\n\t.add(\"RTs\",\"string\") \\\r\n\t.add(\"Hashtags\",\"string\") \\\r\n\t.add(\"UserMentionNames\",\"string\") \\\r\n\t.add(\"UserMentionID\",\"string\") \\\r\n\t.add(\"Name\",\"string\") \\\r\n\t.add(\"Place\",\"string\") \\\r\n \t.add(\"Followers\",\"integer\") \\\r\n\t.add(\"Friends\",\"integer\") \r\n\r\ncsvDF = spark \\\r\n .readStream \\\r\n .option(\"sep\", \";\") \\\r\n .schema(userSchema) \\\r\n .csv(\"hdfs://localhost:9000/stream/\") \r\n \r\n\r\nwords=csvDF.select(explode(split(csvDF.Hashtags,\",\")).alias(\"Hashtags\"))\r\n\t\r\nwordcounts=words.groupBy(\"Hashtags\").count().select(\"Hashtags\",\"count\")\r\nwc=wordcounts.orderBy(desc(\"count\")).select(\"Hashtags\",\"count\").limit(5)\r\n\r\nquery=wc \\\r\n\t.writeStream \\\r\n\t.outputMode (\"complete\") \\\r\n\t.format(\"console\") \\\r\n\t.start()\r\nquery.awaitTermination(60)\r\nquery.stop()\r\n\r\n","sub_path":"adminmgr/media/code/A3/task1/BD_543_565_624_nB6Oxom.py","file_name":"BD_543_565_624_nB6Oxom.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"349943715","text":"import javaproperties\nimport sys\nimport os\nlang={}\n\nf=open(sys.argv[1],'r')\n\nfor line in f:\n line=line.strip()\n if len(line)>=1 and line[0]!='#' and '=' in line:\n pair=line.split('=',1)\n lang[pair[0]]=pair[1]\nf.close()\nos.system('cp %s %s.ref'%(sys.argv[1],sys.argv[1]))\nf=open(sys.argv[1],'w')\nf.write(javaproperties.dumps(lang))\n","sub_path":"src/coding.py","file_name":"coding.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"115119825","text":"import sqlite3\nfrom numpy import empty\nimport config\nimport alpaca_trade_api as tradeapi\nimport smtplib, ssl\nfrom alpaca_trade_api.rest import TimeFrame\nfrom datetime import date, datetime, timedelta, timezone\nfrom timezone import is_dst\nfrom helpers import calculate_quantity\n\ndef place_opening_range_breakout_orders():\n\n context = ssl.create_default_context()\n\n connection = sqlite3.connect(config.DB_FILE)\n connection.row_factory = sqlite3.Row\n\n cursor = connection.cursor()\n\n cursor.execute(\"\"\"\n SELECt id FROM strategy WHERE name = 'opening_range_breakout'\n \"\"\")\n\n strategy_id = cursor.fetchone()['id']\n\n username = config.USERNAME\n\n cursor.execute(\"\"\"\n SELECT id FROM users\n WHERE username = ?\n \"\"\", (username,))\n\n user_id = cursor.fetchone()\n current_id = user_id[0]\n\n cursor.execute(\"\"\"\n SELECT symbol, name\n FROM stock JOIN stock_strategy on stock_strategy.stock_id = stock.id\n WHERE strategy_id = ?\n AND user_id = ?\n \"\"\", (strategy_id, current_id,))\n\n stocks = cursor.fetchall()\n symbols = [stock['symbol'] for stock in stocks]\n\n api = tradeapi.REST(config.API_KEY, config.SECRET_KEY, base_url=config.BASE_URL)\n\n # Usando el día de ayer para prevenir problemas durante demos\n current_date = (date.today() - timedelta(days=1)).isoformat()\n\n if is_dst():\n start_minute_bar = f\"{current_date} 09:30:00-05:00\"\n end_minute_bar = f\"{current_date} 09:45:00-05:00\"\n orders = api.list_orders(status='all', limit=500, after=f'{current_date}T09:30:00-05:00')\n else: \n start_minute_bar = f\"{current_date} 09:30:00-04:00\"\n end_minute_bar = f\"{current_date} 09:45:00-04:00\"\n orders = api.list_orders(status='all', limit=500, after=f'{current_date}T09:30:00-04:00')\n\n existing_order_symbols = [order.symbol for order in orders if order.status != 'canceled']\n\n messages = []\n\n messages.append(f'Hi {username} \\n Here are the results for your submitted orders: \\n\\n')\n\n for symbol in symbols:\n minute_bars = api.get_bars(symbol, TimeFrame.Minute, (datetime.now(timezone.utc) - timedelta(days=1)).isoformat(), (datetime.now(timezone.utc) - timedelta(hours=1)).isoformat()).df\n\n opening_range_mask = (minute_bars.index >= start_minute_bar) & (minute_bars.index < end_minute_bar)\n opening_range_bars = minute_bars.loc[opening_range_mask]\n\n print(opening_range_bars)\n\n if not opening_range_bars.empty:\n\n opening_range_low = opening_range_bars['low'].min()\n opening_range_high = opening_range_bars['high'].max()\n opening_range = opening_range_high - opening_range_low\n\n after_opening_range_mask = minute_bars.index >= end_minute_bar\n after_opening_range_bars = minute_bars.loc[after_opening_range_mask]\n print(f'############## {symbol} with a high of {opening_range_high} #############')\n print(after_opening_range_bars)\n\n after_opening_range_breakout = after_opening_range_bars[after_opening_range_bars['close'] > opening_range_high]\n\n if not after_opening_range_breakout.empty:\n if symbol not in existing_order_symbols:\n limit_price = after_opening_range_breakout.iloc[0]['close']\n\n messages.append(f\"Placing order for {symbol} at {limit_price}, closed above {opening_range_high} at {after_opening_range_breakout.iloc[0]}\")\n \n print(f\"Placing order for {symbol} at {limit_price}, closed above {opening_range_high} at {after_opening_range_breakout.iloc[0]}\")\n\n try:\n api.submit_order(\n symbol=symbol,\n side='buy',\n type='limit', \n qty=calculate_quantity(limit_price),\n time_in_force='day',\n order_class='bracket',\n limit_price = limit_price,\n take_profit=dict(\n limit_price=limit_price + opening_range + 0.02,\n ),\n stop_loss=dict(\n stop_price=limit_price - opening_range - 0.02,\n )\n )\n except Exception as e:\n print(f'Could not submit order. Error: {e}')\n messages.append(f'Could not submit order for {symbol}. Error: {e}')\n \n else:\n print(f'Conditions met, but order for {symbol} already existing. Skipping...')\n messages.append(f'Conditions met, but order for {symbol} already existing.')\n\n else:\n print(f'Initial conditions met but no point through the day ideal to buy for {symbol}')\n messages.append(f'Initial conditions met but no point through the day ideal to buy for {symbol}')\n \n else:\n messages.append(f'Unable to retrieve sufficient data to place order for {symbol}')\n\n messages.append(f'\\n\\n Good luck with the trades, \\n The team at Get Rich or Try Again')\n\n corrected_email_date = date.today().isoformat()\n \n with smtplib.SMTP_SSL(\"smtp.gmail.com\", config.EMAIL_PORT, context=context) as server:\n server.login(config.EMAIL_ADDRESS, config.EMAIL_PASSWORD)\n email_message = f'Subject: Trade Notifications for {corrected_email_date}\\n\\n'\n email_message += \"\\n\\n\".join(messages)\n cursor.execute(\"\"\"\n SELECT email \n FROM users\n WHERE id = ?\n \"\"\", (current_id,))\n\n current_email = cursor.fetchone()[0]\n\n server.sendmail(config.EMAIL_ADDRESS, current_email, email_message)\n\n cursor.execute(\"\"\"\n DELETE FROM stock_strategy\n WHERE user_id = ?\n \"\"\", (current_id,))\n\n connection.commit()","sub_path":"opening_range_breakout.py","file_name":"opening_range_breakout.py","file_ext":"py","file_size_in_byte":6048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"136666881","text":"class Request:\n def __init__(self, req_line, headers, body, headers_raw=None):\n \"\"\"\n HTTP request data class\n :type body: bytearray\n :type headers: dict\n :type req_line: str\n \"\"\"\n self.method, self.path, self.proto = req_line.split()\n self.headers = headers\n self.body = body\n self.headers_raw = headers_raw\n","sub_path":"request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"337315957","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 19 15:12:37 2017\n\n@author: viper\n\n\n\"\"\"\n\n\n# Modules....\nimport os\nimport matplotlib\nmatplotlib.use('pgf')\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom skimage import io\nfrom skimage import morphology\nfrom skimage import color\nfrom skimage import segmentation\nfrom skimage import feature\nfrom skimage import filters\n\nfrom sklearn import cluster\nfrom skimage.util import img_as_float\nfrom skimage.util import img_as_ubyte\n\nimport regiongrowing as rg\n\nimport PIL.Image as Image\n\n\n\"\"\"\nAuxiliaryfunctions\n\"\"\"\n\ndef watershed(im,markers,filename='image.png',sigma = 3, heightmap=None):\n plt.close('all') # Close all remaining figures\n plt.figure(1)\n x, y = markers.T # Extract the markers coordinates\n # Create a marker matrix\n\n markers_ws = np.zeros(im.shape, dtype=np.int)\n i=1\n for k in markers:\n x_,y_ = k\n markers_ws[x_.astype(np.int), y_.astype(np.int)] = i\n i+=1\n\n markers_ws = morphology.dilation(markers_ws, morphology.disk(3))\n if heightmap is None:\n canny = feature.canny(im, sigma = sigma)\n canny=morphology.dilation(canny, morphology.disk(1))\n plt.imshow(canny, cmap='gray')\n labels_hat = segmentation.watershed(canny, markers_ws)\n\n else:\n canny = heightmap\n #canny=morphology.dilation(canny, morphology.disk(1))\n plt.imshow(canny, cmap='gray')\n labels_hat = segmentation.watershed(canny, markers_ws)\n from skimage import color\n color_labels = color.label2rgb(labels_hat, im)\n\n plt.imshow(segmentation.mark_boundaries(color_labels, labels_hat))\n plt.axis('off')\n\n plt.plot(y, x, 'or', ms=4)\n plt.savefig('Processed/Watershed/'+filename)\n matList = rg.labelExtractor(labels_hat)\n plt.imshow(matList[0],cmap='gray')\n plt.savefig('Processed/Watershed/sky_'+filename)\n plt.imshow(matList[1],cmap='gray')\n plt.savefig('Processed/Watershed/water_'+filename)\n plt.close('all')\n return labels_hat\ndef randomWalker(im,markers,filename):\n \"\"\"\n Note 1 : ginput uses the coordinates of matplotlib which does not correspond to those of the matrix !\n To be more specific, the x axis for matplotlib.ginput represents the columns of the matrix when the y axis represents \n the lines of the matrix.\n \"\"\"\n x, y = markers.T\n plt.imshow(im, cmap='gray')\n plt.plot(x, y, 'or', ms=4) # show where the markers are\n # Array of markers\n markers_rw = np.zeros(im.shape, dtype=np.int)\n i=1\n for k in markers:\n x,y = k\n markers_rw[x.astype(np.int), y.astype(np.int)] = i # See Note 1\n i+=1 \n #markers_rw = morphology.dilation(markers_rw, morphology.disk(25)) # Give more \"weight\" to the markers \n plt.imshow(markers_rw) \n from skimage import segmentation\n labels_rw = segmentation.random_walker(im, markers_rw, beta=2500, mode='bf')\n plt.imshow(segmentation.mark_boundaries(color.label2rgb(labels_rw, im), labels_rw))\n plt.plot(x, y, 'ok', ms=2)\n plt.savefig('Processed/Random Walker/'+filename)\n matList = rg.labelExtractor(labels_rw)\n plt.imshow(matList[0],cmap='gray')\n plt.savefig('Processed/Random Walker/sky_'+filename)\n plt.imshow(matList[1],cmap='gray')\n plt.savefig('Processed/Random Walker/water_'+filename)\n plt.close('all')\n return labels_rw\ndef clustering(im, filename):\n # Matrix to array conversion\n w, h = tuple(im.shape)\n image_array = np.reshape(im, (w * h,1))\n \"\"\" \n % K-Means clustering method %\n \"\"\"\n Kmeans = cluster.KMeans(n_clusters=6, random_state=0).fit(image_array)\n labels = Kmeans.predict(image_array)\n image_kmeans = np.reshape(labels, (w, h))\n #print('Estimated number of clusters: %d' % n_clusters_)\n \"\"\" \n % MeanShift clustering method %\n \"\"\"\n bandwidth = cluster.estimate_bandwidth(image_array, quantile=0.3, n_samples=500) # Estimate on n_sample sampled data\n ms = cluster.MeanShift(bandwidth=bandwidth, bin_seeding=True) # Much, much slower if bin_seeding=False (from ~1s to ~6min)\n ms.fit(image_array)\n labels = ms.predict(image_array)\n image_ms = np.reshape(labels, (w, h))\n #print('Estimated number of clusters: %d' % n_clusters_) \n \"\"\" \n % DBSCAN clustering method %\n \"\"\"\n db = cluster.DBSCAN(eps=0.5, min_samples=150).fit(image_array) # Execution time grows with eps, works badly with \n core_samples_mask = np.zeros_like(db.labels_, dtype=bool)\n core_samples_mask[db.core_sample_indices_] = True\n labels = db.labels_\n image_db = np.reshape(labels, (w, h))\n #print('Estimated number of clusters: %d' % n_clusters_) \n \"\"\"\n Plotting the results\n \"\"\"\n f, axarr = plt.subplots(2, 2)\n axarr[0,0].imshow(im, cmap='gray')\n axarr[0,0].set_title('Original Image')\n axarr[0,0].axis('off')\n axarr[0,1].imshow(image_kmeans, cmap='plasma')\n axarr[0,1].set_title('K-Means')\n axarr[0,1].axis('off')\n axarr[1,0].imshow(image_ms, cmap='plasma')\n axarr[1,0].set_title('MeanShift')\n axarr[1,0].axis('off')\n axarr[1,1].imshow(image_db, cmap='plasma')\n axarr[1,1].set_title('DBSCAN')\n axarr[1,1].axis('off')\n plt.savefig('Processed/Clustering/'+filename,dpi = 96*len(axarr))\n plt.close('all') \ndef felzenszwalb(im, filename):\n plt.close('all') # Close all remaining figures\n im = img_as_float(im)\n im=color.grey2rgb(im) \n plt.figure(1)\n plt.imshow(im, cmap='gray')\n labels=color.label2rgb(segmentation.felzenszwalb(im, scale=800, sigma=0.5, min_size=250),im)\n labels = img_as_ubyte(labels)\n imout = Image.fromarray(labels, mode = 'RGB')\n imout.save('Processed/Felzenszwalb/'+filename)\n \ndef slic(im, filename):\n plt.close('all') # Close all remaining figures\n im = img_as_float(im)\n labels=segmentation.slic(im, n_segments=25, compactness=0.001, sigma=1) # sigma > 0 => smoothed image \n labels=img_as_ubyte(segmentation.mark_boundaries(color.label2rgb(labels, im), labels))\n imout = Image.fromarray(labels, mode = 'RGB')\n imout.save('Processed/Slic/'+filename)\n\ndef quickshift(im, filename):\n plt.close('all') # Close all remaining figures\n im = img_as_float(im)\n canny = feature.canny(im, sigma=6)\n plt.figure(1)\n mu=2\n im-= mu*canny\n w, h = im.shape\n for i in range(w):\n for j in range(h):\n if im[i,j]<0:\n im[i,j]=0\n im=color.gray2rgb(im)\n labels = segmentation.quickshift(im, kernel_size=5, max_dist=600, ratio=0.9,sigma=0)\n labels=img_as_ubyte(color.label2rgb(labels, im))\n imout = Image.fromarray(labels, mode = 'RGB')\n io.imsave('Processed/Quickshift/'+filename, labels)\n\n \ndef regionGrowing(image, seeds, pixelThreshold, regionThreshold, filename, matList):\n plt.close('all') # Close all remaining figures\n y, x = seeds.T\n\n labels = rg.regionGrowing(image, seeds, pixelThreshold, regionThreshold)\n plt.imshow(segmentation.mark_boundaries(color.label2rgb(labels, image), labels))\n plt.plot(x, y, 'or', ms=3)\n plt.savefig('Processed/Region Growing/'+filename)\n matList.append(labels)\n \"\"\"\n plt.imshow(matList[0],cmap='gray')\n plt.savefig('Processed/Region Growing/sky_'+filename)\n plt.figure(frameon=False)\n plt.axis('off') \n\n plt.imshow(matList[1],cmap='gray')\n plt.savefig('Processed/Region Growing/water_'+filename)\n plt.figure(frameon=False)\n plt.axis('off')\n \"\"\"\n return labels\n \n\"\"\"\nMain function\n\"\"\" \ndef main():\n \n \"\"\"\n Description : process every relevant file (i.e. images) in the current work directory\n Need an existing 'Processed' folder with two subfolders in it ('Watershed' and 'Random Walker')\n \"\"\"\n plt.close('all') # Close all remaining figures\n n= 3\n matList=[]\n pTh= 5000\n rTh = 2550\n isFirstIteration=True\n fileList = os.listdir(os.getcwd())\n for filename in fileList:\n try:\n im = io.imread(filename)\n print('processing '+filename)\n if filename == 'S1_0.tiff':\n pTh=1600\n rTh=2000\n else:\n pTh= 5000\n rTh = 2000\n if isFirstIteration:\n\n # Open the image\n plt.figure(1)\n plt.imshow(im, cmap='gray')\n print('Choose '+str(n)+ ' points for segmentation in this order : Sky, water, others')\n markers = plt.ginput(n) # n points to choose as markers/seeds\n print('Init done')\n\n markers=np.asarray(markers) # Convert a Python list to a Numpy array\n seeds=markers\n isFirstIteration = False\n for i in range(len(seeds)):\n x_,y_ = seeds[i]\n seeds[i]=[y_,x_]\n markers.astype(int)\n seeds.astype(int)\n if filename == 'DoP_0.tiff':\n watershed(im,markers,filename,1)\n elif filename == 'AoP_0.tiff':\n watershed(im,markers,filename,2)\n else:\n watershed(im,markers,filename) \n randomWalker(im,markers,filename)\n clustering(im, filename)\n felzenszwalb(im, filename)\n slic(im, filename)\n quickshift(im, filename)\n if (im[0,0].dtype == 'uint8'):\n regionGrowing(im, seeds, pTh/256, rTh/256, filename, matList)\n else:\n regionGrowing(im, seeds, pTh, rTh, filename, matList)\n\n else:\n markers=np.asarray(markers) # Convert a Python list to a Numpy array\n if filename == 'DoP_0.tiff':\n watershed(im,markers,filename,1)\n elif filename == 'AoP_0.tiff':\n watershed(im,markers,filename,2)\n else:\n watershed(im,markers,filename) \n randomWalker(im,markers,filename)\n clustering(im, filename)\n felzenszwalb(im, filename)\n slic(im, filename)\n quickshift(im, filename)\n if (im[0,0].dtype == 'uint8'):\n regionGrowing(im, seeds, pTh/256, rTh/256, filename, matList)\n else:\n regionGrowing(im, seeds, pTh, rTh, filename, matList)\n \n except IOError:\n print(filename+' : Not a file or not an image (IOError). This file will be skipped.')\n plt.close('all')\n print('Done !')\n\n \nif __name__ == \"__main__\":\n main()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"89961591","text":"#!/home/mitsuki/.pyenv/versions/anaconda3-4.3.1/bin/python\n\nimport os\nimport sys\n\ntarget = sys.argv[1]\ndirec = \"../material/{}\".format(target)\nname_fp = \"{}/target.lst\".format(direc)\nout_fp = \"{}/gtdb/{}.batch\".format(direc, target)\nos.makedirs(\"{}/gtdb\".format(direc), exist_ok=True)\n\nnames = [line.strip() for line in open(name_fp, 'r')]\nwith open(out_fp, 'w') as f:\n for name in names:\n fp = \"/home/mitsuki/data/mag/genome/{0}/{0}.dnaseq\".format(name)\n f.write(\"{}\\t{}\\n\".format(fp, name))\nprint(\"DONE: output {}\".format(out_fp))\n\n","sub_path":"gtdb/batch.py","file_name":"batch.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"159054763","text":"try:\n from osgeo import osr, ogr, gdal\nexcept ImportError:\n import osr, ogr, gdal\n\nimport sys\n#############################################################################\n# Argument processing.\n\ninfilename = None\noutfilename = None\n\nargv = gdal.GeneralCmdLineProcessor( sys.argv )\nif argv is None:\n sys.exit( 0 )\n\ni = 1\nwhile i < len(argv):\n\targ = argv[i]\n\tif infilename is None:\n\t\tinfilename = arg\n\telif outfilename is None:\n\t\toutfilename = arg\n\ti = i + 1\n\n#############################################################################\n# remove duplicate line\n\nlines_seen = set() # holds lines already seen\noutfile = open(outfilename, \"w\")\nfor line in open(infilename, \"r\"):\n if line not in lines_seen: # not a duplicate\n outfile.write(line)\n lines_seen.add(line)\noutfile.close()\n","sub_path":"rmDuplicateLine.py","file_name":"rmDuplicateLine.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"462623243","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[18]:\n\n\nimport io\nimport os\nimport time\nimport requests\nimport pymongo\nimport pandas as pd\nfrom bs4 import BeautifulSoup as bs\nfrom splinter import Browser\nfrom splinter.exceptions import ElementDoesNotExist\n\n\n# In[19]:\ndef scrape():\n\n titles = []\n teasers = []\n tweets = []\n hemisphere_image_urls = []\n\n news_title = \"\"\n news_p = \"\"\n mars_weather = \"\"\n featured_image_url = \"\"\n\n\n # In[20]:\n\n\n executable_path = {'executable_path': 'chromedriver.exe'}\n browser = Browser('chrome', **executable_path, headless=False)\n\n\n # In[21]:\n\n\n url = 'https://mars.nasa.gov/news/?page=0&per_page=40&order=publish_date+desc%2Ccreated_at+desc&search=&category=19%2C165%2C184%2C204&blank_scope=Latest'\n\n browser.visit(url)\n\n html = browser.html\n\n soup = bs(html, 'html.parser')\n\n\n # In[22]:\n\n\n load = \"y\"\n\n while load == \"y\":\n\n if(browser.is_element_present_by_tag(\"ul\", wait_time=5)):\n \n load = \"n\"\n\n results = soup.find_all('div', class_='list_text')\n\n for result in results:\n try:\n title = result.find('a').text\n titles.append(title)\n except ElementDoesNotExist:\n print(\"Child tag does not exist or does not have valid text.\")\n\n try:\n teaser = result.find(\"div\", class_=\"article_teaser_body\").text\n teasers.append(teaser)\n except ElementDoesNotExist:\n print(\"Child tag