diff --git "a/820.jsonl" "b/820.jsonl" new file mode 100644--- /dev/null +++ "b/820.jsonl" @@ -0,0 +1,602 @@ +{"seq_id":"360042954","text":"import collections\n\nfrom bittorrent.exceptions.exceptions import InvalidTorrentFileBencoding\n\n\nclass Decoder(object):\n \"\"\"The Decoder class is designed to decoded bencoded byte strings.\n\n Attributes\n ----------\n bytes : _data\n Corresponds to a torrent file's bencoded content.\n int : _curr_index\n Corresponds to the index at which the instance is at\n in the bencoding process.\n\n Raises\n ------\n TypeError\n Raises a TypeError if the data constructor parameter is not\n a bytes string.\n \"\"\"\n\n def __init__(self, data: bytes):\n if data is None or not data or not isinstance(data, bytes):\n raise TypeError('Metainfo file data must be in bytes form')\n\n self._data = data\n self._curr_index = 0\n\n self._bdecode = {\n b'l': self._decode_list,\n b'd': self._decode_dict,\n b'i': self._decode_int,\n b'0': self._decode_str,\n b'1': self._decode_str,\n b'2': self._decode_str,\n b'3': self._decode_str,\n b'4': self._decode_str,\n b'5': self._decode_str,\n b'6': self._decode_str,\n b'7': self._decode_str,\n b'8': self._decode_str,\n b'9': self._decode_str,\n }\n\n def decode(self) -> bytes:\n \"\"\"This method is designed to decode a bencoded byte string.\n The returned result can be a byte string, an integer, a list,\n or a dictionary depending on the contents of the bencoded byte\n string. Lists and dictionaries may contain nested lists and\n dictionaries.\n\n Returns\n -------\n str, int, list, or dict\n Returns the decoded bencoded contents.\n\n Raises\n ------\n InvalidTorrentFileBencoding\n This method raises an InvalidTorrentFileBencoding exception\n if the contents of the bencoded byte string are not valid.\n See the following page for bencoding specifications:\n https://wiki.theory.org/index.php/BitTorrentSpecification#Bencoding\n \"\"\"\n self._curr_index = 0\n\n curr_byte = bytes([self._data[self._curr_index]])\n\n res = self._bdecode[curr_byte]()\n\n if self._curr_index != len(self._data):\n raise InvalidTorrentFileBencoding(\n 'The number of decoded bytes does not match '\n 'the number of total bytes.'\n )\n\n return res\n\n def _decode_str(self):\n \"\"\"This method decodes bencoded strings. Bencoded strings are\n represented in the following format: \":\", where\n corresponds to the string's length, and corresponds\n to the string.\n \"\"\"\n colon_index = self._data.find(b':', self._curr_index)\n if colon_index == -1:\n raise InvalidTorrentFileBencoding(\n 'Expected to find a colon after string\\'s length. '\n 'Error occured at {}.'.format(self._curr_index)\n )\n\n try:\n str_length = int(self._data[self._curr_index:colon_index])\n except ValueError:\n raise InvalidTorrentFileBencoding(\n 'Expected a valid integer to indicate the string length. '\n 'Obtained \"{}\" at {}.'.format(\n self._data[self._curr_index:colon_index], self._curr_index\n )\n )\n\n decoded_str = self._data[colon_index+1:colon_index+1+str_length]\n decoded_str = decoded_str\n\n self._curr_index = colon_index + 1 + str_length\n\n return decoded_str\n\n def _decode_int(self):\n \"\"\"This method decodes bencoded integers. Bencoded integers are\n represented in the following format: \"ie\", where \n corresponds to the bencoded integer.\n \"\"\"\n self._curr_index += 1\n int_end = self._data.find(b'e', self._curr_index)\n if int_end == -1:\n raise InvalidTorrentFileBencoding(\n 'Expected to find an \"e\" to delimit the integer. '\n 'Error occured at {}.'.format(self._curr_index)\n )\n\n i = self._data[self._curr_index:int_end]\n\n if len(i) > 1:\n if bytes([i[0]]) == b'0' or (bytes([i[0]]) == b'-' and bytes([i[1]]) == b'0'):\n raise InvalidTorrentFileBencoding((\n 'Integers may not be represented with leading 0s. '\n 'Error occured at {}.'.format(self._curr_index)\n ))\n\n try:\n i = int(i)\n except ValueError:\n raise InvalidTorrentFileBencoding(\n 'Could not coerce the following byte string to an integer: '\n '{}. Error occured at {}'.format(i, self._curr_index)\n )\n\n self._curr_index = int_end + 1\n\n return i\n\n def _decode_list(self):\n \"\"\"This method decodes bencoded lists. Bencoded lists are\n represented in the following format: \"le\", where\n corresponds to the list's elements. These can be\n strings, integers, lists or dictionaries.\n \"\"\"\n lst = []\n self._curr_index += 1\n\n while self._curr_index < len(self._data) and bytes([self._data[self._curr_index]]) != b'e':\n curr_byte = bytes([self._data[self._curr_index]])\n\n element = self._bdecode[curr_byte]()\n lst.append(element)\n\n self._curr_index += 1\n\n return lst\n\n def _decode_dict(self):\n \"\"\"This method decodes bencoded dictionaries. Bencoded dictionaries\n are represented in the following format: \"de\",\n where corresponds to a bencoded string, and where\n corresponds to the key's value. Values can be strings,\n integers, lists, or dictionaries.\n \"\"\"\n d = collections.OrderedDict()\n self._curr_index += 1\n\n while self._curr_index < len(self._data) and bytes([self._data[self._curr_index]]) != b'e':\n curr_byte = bytes([self._data[self._curr_index]])\n key = self._decode_str()\n\n curr_byte = bytes([self._data[self._curr_index]])\n val = self._bdecode[curr_byte]()\n\n d[key] = val\n\n self._curr_index += 1\n\n return d\n\n\ndef decode(data: bytes) -> dict:\n \"\"\"This method decodes a bencoded byte string and returns its\n contents in the form of a string, integer, list, or dictionary.\n Lists and dictionaries can contain nested lists and dictionaries.\n\n Returns\n -------\n dict\n Returns the decoded bencoded contents.\n\n Raises\n ------\n TypeError\n A TypeError is raised if the data parameter is not an instance\n of the bytes class.\n InvalidTorrentFileBencoding\n This method raises an InvalidTorrentFileBencoding exception\n if the contents of the bencoded byte string are not valid.\n See the following page for bencoding specifications:\n https://wiki.theory.org/index.php/BitTorrentSpecification#Bencoding\n \"\"\"\n decoder = Decoder(data)\n\n return decoder.decode()\n\n\nif __name__ == \"__main__\":\n pass\n","sub_path":"bittorrent/bencoding/decode.py","file_name":"decode.py","file_ext":"py","file_size_in_byte":7174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"203019310","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/nex/projects/mvt/mvt/ios/net_datausage.py\n# Compiled at: 2020-02-11 11:39:52\n# Size of source mod 2**32: 1401 bytes\nimport logging\nfrom .net_base import NetBase\nlog = logging.getLogger(__name__)\nDATAUSAGE_BACKUP_ID = '0d609c54856a9bb2d56729df1d68f2958a88426b'\nDATAUSAGE_ROOT_PATHS = [\n 'private/var/wireless/Library/Databases/DataUsage.sqlite']\n\nclass Datausage(NetBase):\n __doc__ = 'This class extracts data from DataUsage.sqlite and attempts to identify\\n any suspicious processes if running on a full filesystem dump.'\n\n def run(self):\n self._find_database(backup_id=DATAUSAGE_BACKUP_ID, root_paths=DATAUSAGE_ROOT_PATHS)\n log.info('Found DataUsage database at path: %s', self.file_path)\n self._extract()\n self._find_suspicious_processes()","sub_path":"pycfiles/mvt-1.1-py3-none-any/net_datausage.cpython-37.py","file_name":"net_datausage.cpython-37.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"441324775","text":"\"\"\" test classes for testing convention.py \"\"\"\n\n# lib imports\nimport unittest\n\n# vfxpipe imports\nimport vp.convention\n\nclass TestConventionModule(unittest.TestCase):\n \"\"\" Convention Module Test Case \"\"\"\n\n\n def test_split_path(self):\n\n path = 'proj_root/proj_name/seq_name/shot_num/step_name/user_name/path_type/file_name.0001.ext'\n\n self.assertEqual(\n vp.convention.split_path(path),\n {\n 'proj_root': 'proj_root',\n 'proj': 'proj_name',\n 'seq': 'seq_name',\n 'shot': 'shot_num',\n 'step': 'step_name',\n 'user': 'user_name',\n 'path_type': 'path_type',\n 'file_name': 'file_name.0001.ext'\n }\n )\n\n def test_split_file_name(self):\n\n self.assertEqual(\n vp.convention.split_file_name('somefile.0001.ext'),\n {'file_name': 'somefile', 'frame': '0001', 'ext': 'ext'}\n )\n\n self.assertEqual(\n vp.convention.split_file_name('somefile.0001.ext.gz'),\n {'file_name': 'somefile', 'frame': '0001', 'ext': 'ext.gz'}\n )\n\n self.assertEqual(\n vp.convention.split_file_name(\n 'part_a-part_b.0001.ext.gz',\n convention='{name0}-{name1}.{frame}.{ext}'\n ),\n {'name0': 'part_a', 'name1': 'part_b', 'frame': '0001', 'ext': 'ext.gz'}\n )\n\n self.assertEqual(\n vp.convention.split_file_name(\n 'somefile.0011.ext.gz',\n convention='somefile.{frame}.ext.gz'\n ),\n {'frame': '0011'}\n )\n\n\n def test_join_path(self):\n\n path = 'proj_root/proj_name/seq_name/shot_num/step_name/user_name/path_type/file_name.0001.ext'\n\n self.assertEqual(\n vp.convention.join_path({\n 'proj_root': 'proj_root',\n 'proj': 'proj_name',\n 'seq': 'seq_name',\n 'shot': 'shot_num',\n 'step': 'step_name',\n 'user': 'user_name',\n 'path_type': 'path_type',\n 'file_name': 'file_name.0001.ext',\n }),\n path\n )\n\n def test_join_file_name(self):\n\n file_name = 'file_name.0001.ext'\n\n self.assertEqual(\n vp.convention.join_file_name({\n 'file_name': 'file_name',\n 'frame': '0001',\n 'ext': 'ext'\n }),\n file_name\n )\n","sub_path":"src/py/vp/tests/test_convention.py","file_name":"test_convention.py","file_ext":"py","file_size_in_byte":2516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"513088306","text":"#!/usr/bin/python3\n# _*_ coding: utf-8 _*_\nfrom django.urls import path\nfrom . import views\n\n\napp_name = 'session_demo'\n\nurlpatterns = [\n path(\"\", views.index, name='index'),\n path(\"get/\", views.get_session, name='get-session'),\n path(\"pop/\", views.pop_session, name='pop-session'),\n path(\"ks/\", views.session_keys, name='session-keys'),\n path(\"its/\", views.session_items, name='session-items'),\n path(\"clear/\", views.clear_session, name='clear-session'),\n path(\"flush/\", views.flush_session, name='flush-session'),\n]\n\n","sub_path":"demo/chapter07_cookie_session/session_demo/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"457843419","text":"import mysql.connector as db\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\r\n# Source: https://matplotlib.org/2.1.2/gallery/axes_grid1/scatter_hist.html\r\n\r\nmydb = db.connect(host=\"localhost\",user=\"dash\",passwd=\"dash5adlmz\",database=\"dashdb\")\r\nmySQLdb = mydb.cursor()\r\n\r\n\r\ndef QueryDB(query):\r\n\tglobal mySQLdb\r\n\tmySQLdb.execute(query)\r\n\tmyresult = mySQLdb.fetchall()\r\n\treturn myresult\r\ndef sumQuery(dat):\r\n\tsummation = 0;\r\n\tfor element in dat:\r\n\t\tsummation = summation + element[0]\r\n\treturn summation\r\ndef parseData(uniqDict):\r\n\tx = []\r\n\ty = []\r\n\tsIP = sorted(uniqDict,key=uniqDict.get,reverse=True)\r\n\tfor i in range(5):\r\n\t\tdel uniqDict[sIP[i]]\r\n\tfor element in uniqDict:\r\n\t\tx.append(uniqDict[element][0])\r\n\t\ty.append(uniqDict[element][1])\r\n\treturn (x,y)\r\n\r\nquery = \"Select INET_NTOA(ipDestination),packetCount from DBaseGMPackets\"\r\ndata = QueryDB(query)\r\nuniqDict = {}\r\nfor element in data:\r\n\tif element[0] not in uniqDict.keys():\r\n\t\tquery = \"Select positives from DBaseDRAEval where ipAddress=INET_ATON(\\\"\" + element[0] + \"\\\")\"\r\n\t\tposi = QueryDB(query)\r\n\t\tuniqDict[element[0]] = (element[1],sumQuery(posi))\r\n\telse:\r\n\t\tuniqDict[element[0]] = (uniqDict[element[0]][0] + element[1],uniqDict[element[0]][1])\r\ncount,positives = parseData(uniqDict)\r\ny = pd.Series(count)\r\nx = pd.Series(positives)\r\n\r\n\r\nfig, scatter = plt.subplots(figsize=(5.5, 5.5))\r\n\r\n# the scatter plot:\r\nscatter.scatter(x, y)\r\nscatter.set_aspect('auto')\r\nplt.xlim(x.min(),x.max())\r\nplt.ylim(y.min(),y.max())\r\nplt.title('Risk Assement Severity Orderd by Count', y=1.45, loc='left')\r\nplt.xlabel('Severity')\r\nplt.ylabel('Count')\r\n\r\n\r\n\r\n# create new axes on the right and on the top of the current axes\r\n# The first argument of the new_vertical(new_horizontal) method is\r\n# the height (width) of the axes to be created in inches.\r\nmarker = make_axes_locatable(scatter)\r\nhistX = marker.append_axes(\"top\", 1.2, pad=0.1, sharex=scatter)\r\nhistY = marker.append_axes(\"right\", 1.2, pad=0.1, sharey=scatter)\r\n\r\n\r\n# make some labels invisible\r\nhistX.xaxis.set_tick_params(labelbottom=False)\r\nhistY.yaxis.set_tick_params(labelleft=False)\r\n\r\n# now determine nice limits by hand:\r\nxbinwidth = .1\r\nybinwidth = len(count)/20\r\nxmax = np.max(np.abs(x))\r\nymax = np.max(np.abs(y))\r\nxlim = (int(xmax/xbinwidth) + 1)*xbinwidth\r\nylim = (int(ymax/ybinwidth) + 1)*ybinwidth\r\n\r\n\r\nxbins = np.arange(-xlim, xlim + xbinwidth, xbinwidth)\r\nhistX.hist(x, bins=xbins)\r\nybins = np.arange(-ylim, ylim + ybinwidth, ybinwidth)\r\nhistY.hist(y, bins=ybins, orientation='horizontal')\r\n\r\n# the xaxis of histX and yaxis of histY are shared with scatter,\r\n# thus there is no need to manually adjust the xlim and ylim of these\r\n# axis.\r\n\r\nplt.savefig('/opt/lampp/htdocs/DASH/dist/dash-new/assets/img/rTopRight.png')\r\n","sub_path":"Server/Instance/Framework/GraphGeneration/rTopRight.py","file_name":"rTopRight.py","file_ext":"py","file_size_in_byte":2820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"499093708","text":"import os\nimport csv\nimport platform\n\n# CSV save option defaults\nOS \t\t= platform.system()\noptions = None\n\nif OS.startswith('win') == True:\n\toptions = {'delimiter': '\\\\', 'pathBase': 'C:'}\nelif OS == 'Darwin' or OS.startswith('linux'):\n\toptions = {'delimiter': '/', 'pathBase': '/Users'}\n\n#\n# Main functionality\n#\ndef checkPathType(path):\n\t\"\"\"Function that checks validity of path\"\"\"\n\tif type(path) is not str:\n\t\tpath = str(path)\n\n\tif path.startswith('.') or path.startswith('C:') or path.startswith('/Users'):\n\t\treturn True\n\telse:\n\t\treturn False\n\t\t\ndef checkIfExists(name, path):\n\t\"\"\"Function that checks if file exists in specified directory\"\"\"\n\tos.chdir(path)\n\tcurDir = os.getcwd()\n\tif name in os.listdir(curDir):\n\t\treturn False\n\telse:\n\t\treturn True\n\ndef saveData(data, dest, name):\n\tfileName \t= name or 'scraped_data'\n\tvalidDest \t= checkPathType(dest)\n\tvalidData \t= type(data)\n\tcanSave \t= checkIfExists(fileName, dest)\n\n\tif validDest and canSave:\n\n\t\tif validData is list:\n\t\t\tcsvFile \t= open(dest + '/' + name + '.csv', 'w')\n\t\t\twriter \t\t= csv.writer(csvFile)\n\t\t\ttry:\n\t\t\t\tfor item in data:\n\t\t\t\t\twriter.writerow(item)\n\t\t\tfinally:\n\t\t\t\tcsvFile.close()\n\n\t\telse: raise ValueError('Invalid data format')\n\n\telse: raise ValueError('File already exists')","sub_path":"myScraper/csvSaveOption.py","file_name":"csvSaveOption.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"325135542","text":"class Solution:\n def gameOfLife(self, board: [[]]) -> None:\n now = []\n for i in range(len(board)):\n now.append(list(board[i]))\n\n dirX = [-1, 0, 1, 1, 1, 0, -1, -1]\n dirY = [-1, -1, -1, 0, 1, 1, 1, 0]\n\n n = len(now)\n for x in range(n):\n for y in range(len(now[x])):\n live = 0\n for i in range(8):\n posx, posy = x + dirX[i], y + dirY[i]\n if 0 <= posx < n and 0 <= posy < len(now[posx]):\n if now[posx][posy] == 1:\n print(x, y, posx, posy)\n live += 1\n print('x: %d, y: %d, live: %d' % (x, y, live))\n if now[x][y] == 1:\n if live < 2 or live > 3:\n board[x][y] = 0\n else:\n if live == 3:\n board[x][y] = 1\n\n\ntest = [\n [0, 1, 0],\n [0, 0, 1],\n [1, 1, 1],\n [0, 0, 0]\n]\ndemo = Solution()\ndemo.gameOfLife(test)\n\nprint(test)\n","sub_path":"leetcode/289.py","file_name":"289.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"561104120","text":"import dotenv\nimport os\nimport re\nfrom netmiko import ConnectHandler\n\ndotenv.load_dotenv()\n\nUSERNAME = os.getenv(\"USERNAME\")\nPASSWORD = os.getenv(\"PASSWORD\")\n\ncisco_cloud_router = {'device_type': 'cisco_ios',\n\t\t 'ip': '10.0.0.5',\n\t\t 'username': USERNAME,\n 'password': PASSWORD}\n\nconnection = ConnectHandler(**cisco_cloud_router)\n\nif connection.check_enable_mode():\n\tprint('We are in enable!')\n\tconfig_commands = ['interface GigabitEthernet2', 'ip address 203.0.113.1 255.255.255.192', 'no shut']\n\tconnection.send_config_set(config_commands=config_commands)\nelse:\n\tprint('We are not in enable!')\n\noutput = connection.send_command('show run int GigabitEthernet2')\nprint(output)\n\noutput = connection.send_command('show ip int brief')\nprint(output)\n\nsplit_lines = output.split('\\n')\nprint(split_lines)\n\nfor line in split_lines:\n\tif 'gigabitethernet2' in line.lower():\n\t\tinterface_status = re.match(r'\\S+\\s+\\S+\\s+\\S+\\s+\\S+\\s+(\\S+)\\s+(\\S+)', line)\n\t\tif interface_status.group(1).lower() == 'up':\n\t\t\tprint('The interface status is \"UP\"!')\n\t\telse:\n\t\t\tprint(f'The interface status is \"{interface_status.group(1)}\"!')\n\t\tif interface_status.group(2).lower() == 'up':\n\t\t\tprint('The interface protocol is \"UP!\"')\n\t\telse:\n\t\t\tprint(f'The interface protocol is \"{interface_status.group(2)}\"!')\n\nif connection.check_enable_mode():\n\tprint('We are in enable mode again!')\n\tconfig_commands = ['ip route 10.255.255.2 255.255.255.255 203.0.113.2']\n\tconnection.send_config_set(config_commands=config_commands)\nelse:\n\tprint('We are not in eable!')\n\noutput = connection.send_command('show ip route 10.255.255.2')\nprint(output)\n\nif output == '% Network not in table':\n\tprint('Something went wrong!')\nelse:\n\tprint('The route was successfully added!')\n\tprint(output)\n","sub_path":"netmiko_task3.py","file_name":"netmiko_task3.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"414089083","text":"# https://gist.github.com/mkropat/7550097\nimport os\n\nif os.name == 'nt':\n import ctypes\n from ctypes import windll, wintypes\n from uuid import UUID\n\n\n class _GUID(ctypes.Structure):\n _fields_ = [\n (\"Data1\", wintypes.DWORD),\n (\"Data2\", wintypes.WORD),\n (\"Data3\", wintypes.WORD),\n (\"Data4\", wintypes.BYTE * 8)\n ]\n\n def __init__(self, uuidstr):\n uuid = UUID(uuidstr)\n ctypes.Structure.__init__(self)\n self.Data1, self.Data2, self.Data3, self.Data4[0], self.Data4[1], rest = uuid.fields\n for i in range(2, 8):\n self.Data4[i] = rest >> (8 - i - 1) * 8 & 0xff\n\n\n SHGetKnownFolderPath = windll.shell32.SHGetKnownFolderPath\n SHGetKnownFolderPath.argtypes = [\n ctypes.POINTER(_GUID), wintypes.DWORD,\n wintypes.HANDLE, ctypes.POINTER(ctypes.c_wchar_p)\n ]\n\n\n def _get_known_folder_path(uuidstr):\n pathptr = ctypes.c_wchar_p()\n guid = _GUID(uuidstr)\n if SHGetKnownFolderPath(ctypes.byref(guid), 0, 0, ctypes.byref(pathptr)):\n raise ctypes.WinError()\n return pathptr.value\n\n\n FOLDERID_Music = '{4BD8D571-6D19-48D3-BE97-422220080E43}'\n FOLDERID_MusicLibrary = '{2112AB0A-C86A-4FFE-A368-0DE96E47012E}'\n\n\n def get_music_folders():\n music_folder = _get_known_folder_path(FOLDERID_Music)\n music_library_folder = _get_known_folder_path(FOLDERID_MusicLibrary)\n return [music_folder, music_library_folder]\nelse:\n def get_music_folders():\n home = os.path.expanduser(\"~\")\n return [os.path.join(home, \"Music\")]\n","sub_path":"background_work/user_music_folder.py","file_name":"user_music_folder.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"142217140","text":"def sort(array, key=lambda x: x, reverse=False):\n '''Pigeonhole sorting is a sorting algorithm that is suitable for sorting\n lists of elements where the number of elements and the number of possible\n key values are approximately the same.\n\n The algorithms goes as follows: first, set up an auxiliary array of empty\n `pigeonholes` and then put each element of the array in a specific hole\n and then just pull out the elements in order to get the sorted array.\n\n Running time: O(n + N) where n is the input size and N the number of key\n values.\n '''\n if len(array) <= 1:\n return array\n\n left = key(min(array, key=key))\n right = key(max(array, key=key))\n\n holes = [[] for i in range(right - left + 1)]\n for value in array:\n holes[key(value) - left].append(value)\n\n array = []\n for pigeon in holes:\n array.extend(pigeon)\n\n return array[::-1] if reverse else array\n","sub_path":"order/pigeonholesort.py","file_name":"pigeonholesort.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"311114016","text":"from urllib.request import urlretrieve\n\nURL_PATH = 'https://s3.amazonaws.com/tcmg476/http_access_log'\nLOCAL_FILE = 'local_copy.log'\n\n# Use urlretrieve() to fetch a remote copy and save into the local file path\nlocal_file, headers = urlretrieve(URL_PATH, LOCAL_FILE)\n\n# Alt.: supply an anonmymous callback function to print a simple progress bar to screen\nlocal_file, headers = urlretrieve(URL_PATH, LOCAL_FILE, lambda x,y,z: print('.', end='', flush=True))\n\n# Alt. 2: a progress bar with reduced output (every 1000 blocks)\nlocal_file, headers = urlretrieve(URL_PATH, LOCAL_FILE, lambda x,y,z: print('.', end='', flush=True) if x % 100 == 0 else False)\n\nFILE_NAME = 'local_copy.log'\n\nfh = open(FILE_NAME)\ncounter = 0\ncounter2 = 0\n\nfor line in fh:\n counter += 1\n if \"Apr\" in line and \"1995\" in line:\n counter2 += 1\n elif \"May\" in line and \"1995\" in line:\n counter2 += 1\n elif \"Jun\" in line and \"1995\" in line:\n counter2 += 1\n elif \"Jul\" in line and \"1995\" in line:\n counter2 += 1\n elif \"Aug\" in line and \"1995\" in line:\n counter2 += 1\nprint(\"There have been\", counter, \"total requests!\")\nprint (\"There have been\", counter2, \"requests in the last 6 months!\")\n","sub_path":"final code.py","file_name":"final code.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"261922061","text":"import copy\nLL_grammar = None\nTERMINALS = None\nSTART_SYMBOL = None\nNONTERMINAL = None\nPT = {}\nFIRST_SET = {}\nFOLLOW_SET = {}\n\n\n# Get the first set of given symobols\ndef FIRST(X):\n if X.__class__ == list:\n if X.__len__() > 1:\n XXF = FIRST(X[0])\n if '' in XXF:\n XXXF = FIRST(X[1:])\n for xxxf in XXXF:\n if xxxf not in XXF:\n XXF += [xxxf]\n return XXF\n elif X.__len__() == 1:\n return FIRST(X[0])\n elif X.__len__() == 0:\n return []\n if X in TERMINALS or X == '':\n return [X]\n first_set = []\n for grammar in LL_grammar:\n if X == grammar[0]:\n emp_num = 1\n for Y in grammar[1:]:\n # add epsilon to set if Y is ''\n if Y == '' and '' not in first_set:\n first_set += ['']\n break\n # break in my grammar requirement\n YF = FIRST(Y)\n # print(X, 'is trying to extract FIRST from', Y, ': ', YF)\n # add nonrepeated Y's set to X's set if no epsilon\n for f in YF:\n if f not in first_set:\n first_set += [f]\n if '' not in YF:\n break\n emp_num += 1\n # if all Y's set has epsilon, add epsilon to set\n if emp_num == grammar.__len__() and '' not in first_set:\n first_set += ['']\n return first_set\n\n\n# # Get the follow set of given symobols\n# def FOLLOW(B):\n# follow_set = []\n# if B == START_SYMBOL:\n# follow_set += ['$']\n# return follow_set\n# for grammar in LL_grammar:\n# counter = 1\n# for b in grammar[1:]:\n# counter += 1\n# if B == b:\n# if grammar[counter:] != []:\n# first_set = FIRST(grammar[counter:])\n# follow_set += [ne for ne in first_set if ne != '']\n# if '' in first_set and B != grammar[0]:\n# for f in FOLLOW(grammar[0]):\n# # print('I was stuck in', grammar)\n# if f not in follow_set:\n# follow_set += [f]\n# else:\n# # print('I was stuck in', grammar)\n# if B != grammar[0]:\n# # print('I was stuck in', grammar)\n# return FOLLOW(grammar[0])\n# return follow_set\n\n\ndef setFOLLOW(nonterminal):\n for nt in nonterminal:\n FOLLOW_SET[nt] = []\n FOLLOW_SET[START_SYMBOL] += ['$']\n for grammar in LL_grammar:\n counter = 1\n # print('Here is the grammar', grammar)\n for b in grammar[1:-1]:\n counter += 1\n if b in nonterminal:\n # print('Now we used', grammar[counter:], 'to get', FIRST(grammar[counter:]), 'for', b)\n first_set = [ne for ne in FIRST(grammar[counter:]) if ne != '']\n for f in first_set:\n if f not in FOLLOW_SET[b]:\n FOLLOW_SET[b] += [f]\n temFOLLOW_SET = None\n while temFOLLOW_SET != FOLLOW_SET:\n # print('CHANGE!')\n temFOLLOW_SET = copy.deepcopy(FOLLOW_SET)\n for grammar in LL_grammar:\n counter = 1\n for b in grammar[1:]:\n counter += 1\n if b in nonterminal:\n NEXT = grammar[counter:]\n if (NEXT == []) or ('' in FIRST(NEXT)):\n # print(b, 'is adding', grammar[0], '\\'s grammar', FOLLOW_SET[grammar[0]])\n for f in FOLLOW_SET[grammar[0]]:\n if f not in FOLLOW_SET[b]:\n FOLLOW_SET[b] += [f]\n\n\n# initialize the ll grammer by using FIRST() and FOLLOW()\ndef init_grammar(start, terminal, nonterminal, ll_grammar):\n global LL_grammar, TERMINALS, START_SYMBOL\n LL_grammar = ll_grammar\n TERMINALS = terminal\n START_SYMBOL = start\n for nt in nonterminal:\n # FIRST_SET[nt] = FIRST(nt)\n # print('First---', nt, '---', FIRST(nt))\n # print('Follow---', nt, '---', FOLLOW(nt))\n PT[nt] = {}\n for t in TERMINALS:\n PT[nt][t] = []\n PT[nt]['$'] = []\n setFOLLOW(nonterminal)\n # for nt in nonterminal:\n # print('Follow---', nt, '---', FOLLOW_SET[nt])\n ### Sould change if using setFOLLOW\n for gm in LL_grammar:\n ft = FIRST(gm[1:])\n # print(ft)\n for f in ft:\n if f == '':\n fl = FOLLOW_SET[gm[0]]\n # print(fl)\n for ff in fl:\n PT[gm[0]][ff] += gm\n else:\n PT[gm[0]][f] += gm\n rows_labels = [i for i in nonterminal]\n columns_labels = [j for j in terminal] + ['$']\n\n\n # print('\\t', end='')\n # for j in columns_labels:\n # print(j, end='\\t')\n # print('')\n # for i in rows_labels:\n # print(i, end='\\t')\n # for j in columns_labels:\n # print(PT[i][j], end='\\t')\n # print('')\n\n return PT\n # print('\\t', end='')\n # for j in columns_labels:\n # print(j, end='\\t')\n\n\ndef strip_empty(array):\n while array[0] == '':\n del array[0]\n\n\ndef parse_tokens(tokens, ST):\n matched = 0\n tokens += [{'type': '$', 'value': '$'}]\n stack = [ST, '$']\n while stack != []:\n print('STACK:', stack)\n # print('Want to match:', tokens[matched]['type'])\n # try:\n # print('stack[0] is ', stack[0], 'matched: ', tokens[matched]['value'])\n NEXT = PT[stack[0]][tokens[matched]['type']]\n if NEXT != []:\n del stack[0] # This deletion will not change the parse table\n stack = NEXT[1:] + stack # it will deep copy NEXT to stack\n strip_empty(stack)\n while stack[0] == tokens[matched]['type']:\n print('matched:', tokens[matched]['type'])\n del stack[0]\n matched += 1\n if matched == tokens.__len__():\n break\n else:\n print('Compile Error.')\n break\n # except KeyError:\n # print('Unhandled error:')\n # print('tokens[matched][type]', tokens[matched]['type'])\n # break\n return True\n # if matched == tokens.__len__():\n # print('Parse completed.')\n # else:\n # print('Tokens excesses.')\n\n\nif __name__ == '__main__':\n START_SYMBOL = 'EXP'\n TERMINAL = [\n '(', ')', '+', '-', '*', 'NUMBER'\n # '+', '-', '*', '/', '(', ')', 'id'\n # 'i', 't', 'e', 'a', 'b'\n ]\n NONTERMINAL = [\n 'EXP', 'EXP_', 'TERM', 'TERM_', 'ADDOP', 'FACTOR', 'MULOP'\n # 'E', 'T', 'F', 'G', 'GG'\n # 'E', 'E_', 'T', 'T_', 'F'\n # 'S', 'S_', 'E'\n ]\n LL_grammar = [\n ['EXP', 'TERM', 'EXP_'],\n ['EXP_', 'ADDOP', 'TERM', 'EXP_'],\n ['EXP_', ''],\n ['ADDOP', '+'],\n ['ADDOP', '-'],\n ['TERM', 'FACTOR', 'TERM_'],\n ['TERM_', ''],\n ['MULOP', '*'],\n ['FACTOR', '(', 'EXP', ')'],\n ['FACTOR', 'NUMBER']\n # GG has a higher priority\n ]\n pt = init_grammar(START_SYMBOL, TERMINAL, NONTERMINAL, LL_grammar)\n # print(pt)\n test_tokens = [\n {'type': 'NUMBER', 'line': 1, 'value': 1.0},\n {'type': '+', 'line': 1, 'value': '+'},\n {'type': 'NUMBER', 'line': 1, 'value': 3.0},\n {'type': '+', 'line': 1, 'value': '+'},\n {'type': 'NUMBER', 'line': 1, 'value': 4.0},\n {'type': '+', 'line': 2, 'value': '+'},\n {'type': 'NUMBER', 'line': 2, 'value': 5.0}\n ]\n parse_tokens(test_tokens, START_SYMBOL)\n","sub_path":"ll_parser.py","file_name":"ll_parser.py","file_ext":"py","file_size_in_byte":7802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"171783714","text":"from os import path\nfrom wordcloud import WordCloud\nimport matplotlib.pyplot as plt\nimport jieba\n\n# 词云使用特殊形状的轮廓需要numpy和pillow, 如客户端不支持可以去掉\nfrom PIL import Image\nimport numpy as np\n\n# 步骤1:使用os导入文件中的信息\n# 注意编码问题\nd = path.dirname(__file__)\ntext = open(path.join(d, \"image/shopcart.txt\")).read()\n\n# 步骤2:使用jieba分词\ntextlist = jieba.lcut(text)\nstring = \" \".join(textlist)\nprint(textlist)\n\n# 步骤3:设置一张词云图对象\nbg = np.array(Image.open(\"image/shop.jpg\"))\nwordcloud = WordCloud(\n background_color=\"white\", \n max_font_size=40, \n mask=bg, \n font_path='image/NotoSansHans-Black.otf'\n).generate(string)\n\n# 步骤4:使用 matplotlib 显示图片\n# 步骤4-1:创建一个图表画布\nplt.figure()\n# 步骤4-2:设置图片\nplt.imshow(wordcloud, interpolation=\"bilinear\")\n# 步骤4-3:取消图表x、y轴\nplt.axis(\"off\")\n# 显示图片\nplt.show()\n\ncounts={}\nchild=['儿童', '宝宝', '青少年', '幼儿', '中大童', '小童', '男孩', '女孩', '12 ', '7 ', '15 ', '3 ', '4 ', '5', '亲子']\nadult = ['男', '女', '妈妈', '爸爸', '成人', '中老年']\nfood =['早餐', '代餐 ', '饱腹 ', '食品 ', '五谷杂粮', '粗粮 ', '小吃', '主食', '零食', '奶酪 ', '烘焙', '海鲜', '糖果']\ntoy =['滑板车 ', '闪光']\nbook=['进口 ', '小说 ', '桥梁 ', '书', '英文原版 ', '全彩', '卡通', '启蒙 ', '绘本 ', '图画书 ', '新华 ', '正版', '数学 ', '书籍', '平装 ', '套装', '系列 ', '全套']\ncloth = ['套头毛衣 ', '线衣 ', '针织 ', '上衣', '纯棉', '羽绒服']\nfamily = ['户外 ', '手推车 ', '家居服']\nrword = '其他'\nfor word in textlist:\n # 去标点符号\n if word == ' ':\n continue\n elif word in child or word in toy or word in book:\n rword = '孩子'\n elif word in adult or word in cloth:\n rword = '大人'\n elif word in food or word in family:\n rword = '全家'\n\n counts[rword] = counts.get(rword, 0) + 1\nprint(counts)","sub_path":"ShopCartWorldCloud.py","file_name":"ShopCartWorldCloud.py","file_ext":"py","file_size_in_byte":2069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"638844338","text":"from __future__ import print_function\nimport argparse\nimport torch\nimport torch.optim as optim\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.optim.lr_scheduler import *\n\nfrom tqdm import tqdm, trange\nfrom tqdm._utils import _term_move_up\nprefix = _term_move_up() + '\\r'\n\nimport random\nimport os\nfrom datasets import get_data_loaders\nfrom models import get_model\nimport utils\nfrom numpy.random import beta\n\n\nif __name__ == '__main__':\n\n parser = utils.args()\n args = parser.parse_args()\n print(args)\n \n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n torch.manual_seed(args.seed)\n train_loader, test_loader, metadata = get_data_loaders(args)\n model = get_model(args, metadata)\n print(\"N parameters : \", model.n_parameters)\n\n if args.resume is not None:\n model.load_state_dict(torch.load(args.resume)[\"state_dict\"])\n\n model = model.to(device)\n rot_model = nn.Sequential(nn.Linear(model.n_filters,4))\n rot_model = rot_model.to(device)\n\n if args.optimizer==\"sgd\":\n optimizer = torch.optim.SGD([\n {'params': model.parameters()},\n {'params': rot_model.parameters()}],\n lr=args.lr, \n momentum=args.momentum, \n weight_decay=args.weight_decay\n )\n scheduler = ReduceLROnPlateau(optimizer, factor=args.gamma, patience=args.patience, verbose=True, min_lr=args.min_lr)\n elif args.optimizer==\"adam\":\n optimizer = torch.optim.Adam([\n {'params': model.parameters()},\n {'params': rot_model.parameters()}],\n lr=args.lr, \n momentum=args.momentum, \n weight_decay=args.weight_decay\n )\n scheduler = None\n\n lossfn = nn.CrossEntropyLoss()\n\n try:\n os.mkdir(\"logs\")\n except:\n pass\n logger = utils.Logger(\"logs/{}.log\".format(args.name))\n\n with open(\"logs/{}.log\".format(args.name), \"a\") as f:\n f.write(str(args))\n f.write(\"\\n*******\\n\")\n\n print(\"-\"*80 + \"\\n\")\n\n TOTAL_TRAIN = len(train_loader.dataset)\n TOTAL_TEST = len(test_loader.dataset)\n\n test_loss = 0\n test_rloss = 0\n test_racc = 0\n test_acc = 0\n \n for epoch in range(1, args.epochs + 1):\n logger[\"Epoch\"] = epoch\n\n lr = optimizer.state_dict()[\"param_groups\"][0][\"lr\"]\n logger[\"lr\"] = lr\n\n # TRAINING\n rot_model.train()\n model.train()\n train_acc = 0\n train_racc = 0\n train_loss = 0\n train_rloss = 0\n for batch_idx, (x,y) in tqdm(enumerate(train_loader), \n total=len(train_loader),\n position=1, \n leave=False, \n ncols=100,\n unit=\"batch\"):\n\n x, y = x.to(device), y.to(device)\n bs = x.size(0)\n x_ = []\n y_ = []\n a_ = []\n for j in range(bs):\n x90 = x[j].transpose(2,1).flip(1)\n x180 = x90.transpose(2,1).flip(1)\n x270 = x180.transpose(2,1).flip(1)\n x_ += [x[j], x90, x180, x270]\n y_ += [y[j] for _ in range(4)]\n a_ += [torch.tensor(0),torch.tensor(1),torch.tensor(2),torch.tensor(3)]\n\n x_ = torch.autograd.Variable(torch.stack(x_,0)).to(device)\n y_ = torch.autograd.Variable(torch.stack(y_,0)).to(device)\n a_ = torch.autograd.Variable(torch.stack(a_,0)).to(device)\n\n final_feat,scores = model.forward(x_, get_features=True)\n rotate_scores = rot_model(final_feat)\n\n p1 = torch.argmax(scores,1)\n train_acc += (p1==y_).sum().item()\n p2 = torch.argmax(rotate_scores,1)\n train_racc += (p2==a_).sum().item()\n\n optimizer.zero_grad()\n rloss = lossfn(rotate_scores,a_)\n closs = lossfn(scores, y_)\n loss = closs + rloss\n loss.backward()\n optimizer.step()\n\n train_loss = train_loss+closs.data.item()\n train_rloss = train_rloss+rloss.data.item()\n\n cur_size = (1+batch_idx)*args.batch_size\n\n tqdm.write(prefix+\"Epoch {}/{}, Test_Loss : {:.3f}, Test_acc : {:.4f}, \\\nTest_Rloss : {:.3f}, Test_Racc : {:.2f}, \\\nTrain_Loss : {:.3f}, Train_Acc : {:.4f}, \\\nTrain_Rloss : {:.3f}, Train_Racc : {:.2f}, LR : {:.1E}\".format(\n epoch, args.epochs, test_loss, test_acc, \n test_rloss, test_racc,\n train_loss/cur_size, train_acc/cur_size, \n train_rloss/cur_size, train_racc/cur_size, lr))\n\n \n logger.update({\"train_loss\" : train_loss/TOTAL_TRAIN, \n \"train_acc\" : train_acc/TOTAL_TRAIN,\n \"train_rot_loss\" : train_rloss/(4*TOTAL_TRAIN),\n \"train_rot_acc\" : train_racc/(4*TOTAL_TRAIN)})\n\n model.eval()\n rot_model.eval()\n\n with torch.no_grad():\n test_acc = 0\n test_racc = 0\n for i,(x,y) in enumerate(test_loader):\n bs = x.size(0)\n x_ = []\n y_ = []\n a_ = []\n for j in range(bs):\n x90 = x[j].transpose(2,1).flip(1)\n x180 = x90.transpose(2,1).flip(1)\n x270 = x180.transpose(2,1).flip(1)\n x_ += [x[j], x90, x180, x270]\n y_ += [y[j] for _ in range(4)]\n a_ += [torch.tensor(0),torch.tensor(1),torch.tensor(2),torch.tensor(3)]\n\n x_ = torch.autograd.Variable(torch.stack(x_,0)).to(device)\n y_ = torch.autograd.Variable(torch.stack(y_,0)).to(device)\n a_ = torch.autograd.Variable(torch.stack(a_,0)).to(device)\n\n final_feat,scores = model.forward(x_, True)\n rotate_scores = rot_model(final_feat)\n\n test_rloss += lossfn(rotate_scores,a_)\n test_loss = lossfn(scores, y_)\n p1 = torch.argmax(scores,1)\n test_acc += (p1==y_).sum().item()\n p2 = torch.argmax(rotate_scores,1)\n test_racc += (p2==a_).sum().item()\n test_loss /= TOTAL_TEST\n test_acc /= TOTAL_TEST\n test_rloss /= 4*TOTAL_TEST\n test_racc /= 4*TOTAL_TEST\n\n logger.update({ \"test_loss\" : test_loss,\n \"test_acc\" : test_acc, \n \"test_rot_loss\" : test_rloss,\n \"test_rot_acc\" : test_racc })\n print()\n\n if scheduler is not None:\n scheduler.step(logger[\"test_loss\"])\n \n if args.checkpoint_freq != 0 and epoch%args.checkpoint_freq == 0:\n name = args.name+ \"_e\" + str(epoch) + \"_acc{:d}.model\".format(int(10000*logger[\"test_acc\"]))\n model.save(name)\n\n logger.log()\n\n model.save(args.name+\".model\")","sub_path":"Grippon/train_rotate.py","file_name":"train_rotate.py","file_ext":"py","file_size_in_byte":7160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"167699993","text":"import os\r\nimport time\r\nimport datetime\r\nfrom auto_conversion import after\r\nfrom _AdditionalScript_main import main\r\n\r\ndef upload(a=None):\r\n print(\"WarsawGTFS_Everyday: Starting conversion...\")\r\n absdir = os.getcwd()\r\n v = main(a, True)\r\n os.chdir(absdir)\r\n if v != a:\r\n after()\r\n print(\"===== Done! =====\")\r\n loctime = time.asctime(time.localtime(time.time()))\r\n print(\"Script finished running at: \" + loctime)\r\n print(\"=========================\")\r\n return v\r\n\r\nprint(\"=== WarsawGTFS_Everyday: Starting script! ===\")\r\nprint(\"First run forces gtfs creation!\")\r\nversion = upload()\r\nwhile True:\r\n now = datetime.datetime.today()\r\n if now.hour == 0 and now.minute == 1: version = upload(version)\r\n time.sleep(30)\r\n","sub_path":"gtfs_everyday.py","file_name":"gtfs_everyday.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"69419743","text":"#encontrar el calor latente de fusion\r\n#input\r\nmasa=float(input(\"ingrese la masa:\"))\r\nfusion=float(input(\"ingrese la fusion:\"))\r\n\r\n#procesing\r\nq_fusion=(masa*fusion)\r\n#vereficador\r\nq_fusion_vapor=(q_fusion>740)\r\n#output\r\nprint(\"el calor de fusion es es:\",q_fusion)\r\nprint(\"¿el calor es el adecudo para que se evapore?\",q_fusion_vapor)\r\n","sub_path":"#vereficador20.py","file_name":"#vereficador20.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"436549303","text":"#! /usr/bin/env python\n#\ndef zeta_values ( n_data ):\n\n#*****************************************************************************80\n#\n## ZETA_VALUES returns some values of the Riemann Zeta function.\n#\n# Discussion:\n#\n# ZETA(N) = sum ( 1 <= I < Infinity ) 1 / I^N\n#\n# In Mathematica, the function can be evaluated by:\n#\n# Zeta[n]\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 22 February 2015\n#\n# Author:\n#\n# John Burkardt\n#\n# Reference:\n#\n# Milton Abramowitz and Irene Stegun,\n# Handbook of Mathematical Functions,\n# US Department of Commerce, 1964.\n#\n# Stephen Wolfram,\n# The Mathematica Book,\n# Fourth Edition,\n# Wolfram Media / Cambridge University Press, 1999.\n#\n# Parameters:\n#\n# Input/output, integer N_DATA. The user sets N_DATA to 0 before the\n# first call. On each call, the routine increments N_DATA by 1, and\n# returns the corresponding data; when there is no more data, the\n# output value of N_DATA will be 0 again.\n#\n# Output, integer N, the argument of the Zeta function.\n#\n# Output, real F, the value of the Zeta function.\n#\n import numpy as np\n\n n_max = 15\n\n n_vec = np.array ( ( \\\n 2, \\\n 3, \\\n 4, \\\n 5, \\\n 6, \\\n 7, \\\n 8, \\\n 9, \\\n 10, \\\n 11, \\\n 12, \\\n 16, \\\n 20, \\\n 30, \\\n 40 ))\n\n f_vec = np.array ( ( \\\n 0.164493406684822643647E+01, \\\n 0.120205690315959428540E+01, \\\n 0.108232323371113819152E+01, \\\n 0.103692775514336992633E+01, \\\n 0.101734306198444913971E+01, \\\n 0.100834927738192282684E+01, \\\n 0.100407735619794433939E+01, \\\n 0.100200839292608221442E+01, \\\n 0.100099457512781808534E+01, \\\n 0.100049418860411946456E+01, \\\n 0.100024608655330804830E+01, \\\n 0.100001528225940865187E+01, \\\n 0.100000095396203387280E+01, \\\n 0.100000000093132743242E+01, \\\n 0.100000000000090949478E+01 ))\n\n if ( n_data < 0 ):\n n_data = 0\n\n if ( n_max <= n_data ):\n n_data = 0\n n = 0\n f = 0.0\n else:\n n = n_vec[n_data]\n f = f_vec[n_data]\n n_data = n_data + 1\n\n return n_data, n, f\n\ndef zeta_values_test ( ):\n\n#*****************************************************************************80\n#\n## ZETA_VALUES_TEST demonstrates the use of ZETA_VALUES.\n#\n# Licensing:\n#\n# This code is distributed under the GNU LGPL license.\n#\n# Modified:\n#\n# 22 February 2015\n#\n# Author:\n#\n# John Burkardt\n#\n import platform\n\n print ( '' )\n print ( 'ZETA_VALUES_TEST:' )\n print ( ' Python version: %s' % ( platform.python_version ( ) ) )\n print ( ' ZETA_VALUES stores values of the ZETA function.' )\n print ( '' )\n print ( ' N ZETA(N)' )\n print ( '' )\n\n n_data = 0\n\n while ( True ):\n\n n_data, n, f = zeta_values ( n_data )\n\n if ( n_data == 0 ):\n break\n\n print ( ' %6d %24.16f' % ( n, f ) )\n#\n# Terminate.\n#\n print ( '' )\n print ( 'ZETA_VALUES_TEST:' )\n print ( ' Normal end of execution.' )\n return\n\nif ( __name__ == '__main__' ):\n from timestamp import timestamp\n timestamp ( )\n zeta_values_test ( )\n timestamp ( )\n\n","sub_path":"test_values/zeta_values.py","file_name":"zeta_values.py","file_ext":"py","file_size_in_byte":3110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"481734067","text":"import tarfile, shutil\nimport settings as s\nimport os\nfrom threading import Thread\n\n\ndef remove(id):\n path = os.path.join(s.DIR_PACKS, id)\n\n if not os.path.exists(path):\n raise NameError(\"Package do not exists\")\n shutil.rmtree(os.path.join(s.DIR_PACKS, id))\n\n\nclass Package():\n def __init__(self, recipes, id):\n if not recipes:\n raise ValueError(\"not 'recipes' provided\")\n if not id:\n raise ValueError(\"not 'id' provided\")\n\n self.id = id\n self.directory = os.path.join(s.DIR_PACKS, self.id)\n if not os.path.exists(self.directory):\n os.makedirs(self.directory)\n\n self.recipes = self._saveRecipes(recipes)\n self.check = self._checkRecipes()\n self.package = None\n\n # Private methods\n\n def _saveRecipes(self, recipes):\n '''Save the recipes tar in the proper directory. Raises tarfile.ReadError if not a tar file.'''\n pathname = os.path.join(self.directory, s.NAME_REC)\n recipes.save(pathname)\n return tarfile.open(pathname)\n\n def _checkRecipes(self):\n '''Return [True, None] if the recipe is ok and [False, err] if there is any problem. `err` is the failure description.'''\n err = None\n # check required files\n items = self.recipes.getnames()\n\n requiredFiles = [\n 'recipe/package/services',\n 'recipe/package/docker-compose.yml'\n ]\n for req in requiredFiles:\n if req not in items:\n err = 'the recipes archive do not have a \\''+req+'\\' element.'\n break\n if err:\n return False, err\n else:\n return True, None\n\n def _package(self):\n recipes = os.path.join(self.directory, s.NAME_REC)\n package = os.path.join(self.directory, s.NAME_PACK)\n # shutil.copyfile(recipes, packagetemp)\n # self.package = tarfile.open(packagetemp, mode='a')\n # self.package.add(s.DIR_WIZARD, 'wizard')\n # self.package.add(s.LAUNCHSCRIPT_LOC, 'launch.sh')\n # self.package.close()\n # shutil.move(packagetemp, package)\n comcloud_temp = os.path.join(self.directory, 'comcloud')\n shutil.copytree(s.DIR_WIZARD+'/src', comcloud_temp)\n shutil.copy(recipes, comcloud_temp+'/resources/package.tar')\n\n self.package = tarfile.open(package, mode='a')\n self.package.add(comcloud_temp, 'comcloud')\n self.package.close()\n\n shutil.rmtree(comcloud_temp)\n\n\n # Public methods\n def build(self):\n thread = Thread(target= self._package)\n thread.start()\n","sub_path":"src/controllers/packages.py","file_name":"packages.py","file_ext":"py","file_size_in_byte":2616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"584777623","text":"# _*_ coding: utf-8 _*_\nfrom odoo import models, fields, api\nfrom odoo.exceptions import UserError\n\nclass TransferCrmBatch(models.TransientModel):\n _name = 'transfer.crm.batch'\n\n team_id = fields.Many2one(comodel_name='crm.team', string='銷售團隊', domain=[('transfer_crm', '=', True)])\n batch_line = fields.Many2many(comodel_name='sale.order.line')\n\n def transfer_information(self):\n for line in self.batch_line:\n if line.is_transfer_crm == False:\n data = self.env['crm.lead'].create({\n 'partner_id':line.order_partner_id.id,\n 'name': line.order_partner_id.name + '-' + line.product_id.name + '-續報商機',\n 'email_from': line.order_partner_id.email,\n 'phone': line.order_partner_id.phone,\n 'user_id': line.order_id.user_id.id,\n 'company_id': line.order_id.company_id.id,\n 'team_id': self.team_id.id,\n })\n data.team_id = self.team_id.id\n line.is_transfer_crm = True","sub_path":"addons_jptip/jp_sale_product/wizard/transfer_crm_batch.py","file_name":"transfer_crm_batch.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"6606906","text":"# This program models the model the self-consistent field method which is essential to the Electronic Structure Theory. - Bhavesh Manivannan\n\nimport os\nimport numpy as np\nimport scipy.linalg as sp\nimport sys\nimport time\nimport math\n\nnp.set_printoptions(threshold=np.nan)\n\nclass ProjectFour:\n enuc = 0 # 9.779406144413407\n eelec = 0\n etotal_new = 0\n etotal_old = 99999999999\n one_e = 0\n two_e = 0\n doubly_occupied_orbitals = 5\n overlap_array = [[]]\n overlap_raw_input = []\n l_eig_vector = [[]]\n lambda_eig_value = [[]]\n kinetic_array = [[]]\n kinetic_raw_input = []\n potential_array = [[]]\n potential_raw_input = []\n h_array = [[]]\n eri_array =[[[[]]]]\n eri_raw_input = []\n inverse_square_root = [[]]\n transposed_overlap = [[]]\n fock_array = [[]]\n epsilon_eig_value = [[]]\n c_eig_vector = [[]]\n scf_array = [[]]\n density_array = [[]]\n new_density_array = [[]]\n rms = 0\n convergence = False\n\n def read_enuc(self, __file_name__):\n file_name = __file_name__\n with open(file_name) as f_obj:\n lines = f_obj.readlines()\n for line in lines:\n self.enuc = float(line)\n\n def create_2d_array(self, row, column):\n n = row\n m = column\n array = [[0] * m for i in range(n)]\n return array\n\n def read_overlap(self, __file_name__):\n file_name = __file_name__\n with open(file_name) as f_obj:\n lines = f_obj.readlines()\n for line in lines:\n self.overlap_raw_input.append(line.strip())\n\n # Placing the Overlap value inside the 2d list\n def extract_values_from_overlap(self):\n self.overlap_array = self.create_2d_array(24, 24)\n for x in range(3, len(self.overlap_raw_input)):\n # Gets AO\n par = self.overlap_raw_input[x].partition(' ')\n temp_AO = int(par[0])\n\n # Gets MO\n par = par[2].lstrip().partition(' ')\n temp_MO = int(par[0])\n\n # Gets Overlap\n par = par[2].lstrip().partition(' ')\n temp_overlap = par[0]\n\n # Sets the value at index (AO, MO) to the correct value in overlap_array\n self.overlap_array[temp_AO][temp_MO] = temp_overlap\n\n def read_kinetic(self, __file_name__):\n file_name = __file_name__\n with open(file_name) as f_obj:\n lines = f_obj.readlines()\n for line in lines:\n self.kinetic_raw_input.append(line.strip())\n\n # Placing the Kinetic value inside the 2d list\n def extract_values_from_kinetic(self):\n self.kinetic_array = self.create_2d_array(24, 24)\n for x in range(3, len(self.kinetic_raw_input)):\n # Gets AO\n par = self.kinetic_raw_input[x].partition(' ')\n temp_AO = int(par[0])\n\n # Gets MO\n par = par[2].lstrip().partition(' ')\n temp_MO = int(par[0])\n\n # Gets Kinetic\n par = par[2].lstrip().partition(' ')\n temp_kinetic = par[0]\n\n # Sets the value at index (AO, MO) to the correct value in kinetic_array\n self.kinetic_array[temp_AO][temp_MO] = temp_kinetic\n\n def read_potential(self, __file_name__):\n file_name = __file_name__\n with open(file_name) as f_obj:\n lines = f_obj.readlines()\n for line in lines:\n self.potential_raw_input.append(line.strip())\n\n # Placing the Potential value inside the 2d list\n def extract_values_from_potential(self):\n self.potential_array = self.create_2d_array(24, 24)\n for x in range(3, len(self.potential_raw_input)):\n # Gets AO\n par = self.potential_raw_input[x].partition(' ')\n temp_AO = int(par[0])\n\n # Gets MO\n par = par[2].lstrip().partition(' ')\n temp_MO = int(par[0])\n\n # Gets Potential\n par = par[2].lstrip().partition(' ')\n temp_potential = par[0]\n\n # Sets the value at index (AO, MO) to the correct value in overlap_array\n self.potential_array[temp_AO][temp_MO] = temp_potential\n\n def form_h(self):\n self.h_array = self.create_2d_array(24, 24)\n for u in range (0, 24):\n for v in range(0, 24):\n self.h_array[u][v] = float(self.kinetic_array[u][v]) + float(self.potential_array[u][v])\n\n # Creates the 4d array to store the AOs in\n def create_four_d_array(self, value, *dim):\n \"\"\"\n Create 4D-array\n :param dim: a tuple of dimensions - (w, x, y, z)\n :param value: value with which 4D-array is to be filled\n :return: 4D-array\n \"\"\"\n return [[[[value for x in range(dim[3])] for x in range(dim[2])] for x in range(dim[1])] for x in range(dim[0])]\n\n def read_eri(self, __file_name__):\n file_name = __file_name__\n with open(file_name) as f_obj:\n lines = f_obj.readlines()\n for line in lines:\n self.eri_raw_input.append(line.strip())\n\n def extract_values_from_eri(self):\n m = 24\n n = 24\n o = 24\n p = 24\n \n # Creates the array\n self.eri_array = self.create_four_d_array(0, *(m, n, o, p))\n for x in range(0, len(self.eri_raw_input)):\n # Gets w\n par = self.eri_raw_input[x].partition(' ')\n temp_w = int(par[0])\n\n # Gets x\n par = par[2].lstrip().partition(' ')\n temp_x = int(par[0])\n\n # Gets y\n par = par[2].lstrip().partition(' ')\n temp_y = int(par[0])\n\n # Gets z\n par = par[2].lstrip().partition(' ')\n temp_z = int(par[0])\n\n # Gets mo_value\n par = par[2].lstrip().partition(' ')\n temp_ao_value = par[0]\n\n # Set the value in the current iteration to index in 4d array\n self.eri_array[temp_w][temp_x][temp_y][temp_z] = temp_ao_value\n self.eri_array[temp_x][temp_w][temp_y][temp_z] = temp_ao_value\n self.eri_array[temp_x][temp_w][temp_z][temp_y] = temp_ao_value\n self.eri_array[temp_w][temp_x][temp_z][temp_y] = temp_ao_value\n self.eri_array[temp_y][temp_z][temp_w][temp_x] = temp_ao_value\n self.eri_array[temp_y][temp_z][temp_x][temp_w] = temp_ao_value\n self.eri_array[temp_z][temp_y][temp_x][temp_w] = temp_ao_value\n self.eri_array[temp_z][temp_y][temp_w][temp_x] = temp_ao_value\n\n def convert_lists_to_arrays(self):\n self.overlap_array = np.asarray(self.overlap_array, float)\n self.kinetic_array = np.asarray(self.kinetic_array, float)\n self.potential_array = np.asarray(self.potential_array, float)\n self.h_array = np.asarray(self.h_array, float)\n self.eri_array = np.asarray(self.eri_array, float)\n\n # Finds Λ (Eigenvector value) and L(Eigenvector matrix)\n def diagonalize_overlap(self):\n #L^−1 (inverse eigenvector matrix) * S(overlap_array) * L(eigenvector matrix) = Λ (eigenvalue matrix)\n self.lambda_eig_value, self.l_eig_vector, = np.linalg.eigh(self.overlap_array)\n print(\"Overlap Eigenvalues:\", '\\n', self.lambda_eig_value, '\\n')\n temp_eig_value = self.create_2d_array(24,24)\n temp_eig_value = np.asarray(temp_eig_value, float)\n temp_col = 0\n for row in range (0, 24):\n temp_eig_value[row][temp_col] = self.lambda_eig_value[row]\n temp_col+=1\n self.lambda_eig_value = temp_eig_value\n\n def double_check_overlap(self):\n temp_transposed_eig_vector = np.transpose(self.l_eig_vector)\n temp_overlap = np.matmul(temp_transposed_eig_vector, self.l_eig_vector)\n arr = np.copy(self.lambda_eig_value)\n self.overlap_array = temp_overlap\n\n # Finds S^(-1/2)\n def inverse_square_root_matrix(self):\n arr = np.copy(self.overlap_array)\n arr = sp.cholesky(arr)\n arr = np.linalg.inv(arr)\n self.overlap_array = arr\n print(\"S^(-1/2):\", '\\n',self.overlap_array)\n\n # Creates initial guess of the Fock Matrix\n def fock_initial_guess(self):\n temp_array = np.matmul(np.transpose(self.overlap_array), self.h_array)\n temp_array = np.matmul(temp_array, self.overlap_array)\n self.fock_array = temp_array\n\n # Finds epsilon (Eigenvector value) and C(Eigenvector matrix) of the Fock Matrix\n def diagonalize_fock(self):\n #C^−1 (inverse eigenvector matrix) * F(fock_array) * C(eigenvector matrix) = epsilon (eigenvalue matrix)\n self.epsilon_eig_value, self.c_eig_vector, = np.linalg.eigh(self.fock_array)\n temp_eig_value = self.create_2d_array(24,24)\n temp_eig_value = np.asarray(temp_eig_value, float)\n temp_col = 0\n for row in range (0, 24):\n temp_eig_value[row][temp_col] = self.epsilon_eig_value[row]\n temp_col+=1\n self.epsilon_eig_value = temp_eig_value\n\n # C Eigenvector Matrix\n def scf(self):\n self.scf_array = np.matmul(self.overlap_array, self.c_eig_vector)\n\n # Summation for density matrix (D)\n def form_density_matrix(self):\n self.density_array = self.create_2d_array(24,24)\n self.density_array = np.asarray(self.density_array, float)\n for u in range (0, 24):\n for v in range (0, 24):\n temp_value = 0\n for m in range (0, self.doubly_occupied_orbitals):\n temp_value += (self.scf_array[u][m] * self.scf_array[v][m])\n self.density_array[u][v] = temp_value\n\n # Form the new Fock Matrix\n def form_new_fock(self):\n for u in range (0, 24):\n for v in range (0, 24):\n temp_value = 0\n for p in range (0, 24):\n for o in range(0, 24):\n temp_value += (self.density_array[p][o] * (2 * self.eri_array[u][v][p][o] - self.eri_array[u][p][v][o]))\n self.fock_array[u][v] = temp_value + self.h_array[u][v]\n\n\n # Computes the Electronic energy (eelec)\n def compute_electronic_energy(self):\n temp_value = 0\n e_one = 0\n e_two = 0\n for u in range (0, 24):\n for v in range (0, 24):\n temp_value += (self.density_array[u][v] * (self.h_array[u][v] + self.fock_array[u][v]))\n e_one += self.density_array[u][v] * self.h_array[u][v]\n e_two += self.density_array[u][v] * self.fock_array[u][v]\n self.eelec = temp_value\n print(\"Electronic Energy:\", self.eelec)\n print(\"Total Energy:\", self.eelec + self.enuc)\n self.one_e = e_one\n self.two_e = e_two\n print(\"E One(Density Matrix Value * H Value):\", e_one)\n print(\"E Two(Density Matrix Value * Fock Matrix Value):\", e_two)\n\n # Adds the Nuclear energy and the Electrical energy together\n def compute_total_energy(self):\n self.etotal_new = self.eelec + self.enuc\n\n def transform_new_fock(self):\n temp_array = np.matmul(np.transpose(self.overlap_array), self.fock_array)\n temp_array = np.matmul(temp_array, self.overlap_array)\n self.fock_array= temp_array\n\n def diagonalize_transformed_fock(self):\n # C^−1 (inverse eigenvector matrix) * F(fock_array) * C(eigenvector matrix) = epsilon (eigenvalue matrix)\n self.epsilon_eig_value, self.c_eig_vector, = np.linalg.eigh(self.fock_array)\n temp_eig_value = self.create_2d_array(24,24)\n temp_eig_value = np.asarray(temp_eig_value, float)\n temp_col = 0\n for row in range (0, 24):\n temp_eig_value[row][temp_col] = self.epsilon_eig_value[row]\n temp_col+=1\n\n def scf_transform(self):\n self.scf_array = np.matmul(self.overlap_array, self.c_eig_vector)\n\n def form_new_density_matrix(self):\n self.new_density_array = self.create_2d_array(24, 24)\n self.new_density_array = np.asarray(self.new_density_array, float)\n for u in range(0, 24):\n for v in range(0, 24):\n temp_value = 0\n for m in range(0, self.doubly_occupied_orbitals):\n temp_value += (self.scf_array[u][m] * self.scf_array[v][m])\n self.new_density_array[u][v] = temp_value\n\n # returns true if passes test and false if it doesnt (doesnt check difference in total energy)\n def test_convergence(self):\n temp_value = 0\n for u in range (0, 24):\n for v in range (0, 24):\n temp_value += ((self.new_density_array[u][v] - self.density_array[u][v])**2)\n self.rms = math.sqrt(temp_value)\n if(self.rms<10**-10):\n return True\n else:\n return False\n\n def difference_energy(self):\n if((self.etotal_new - self.etotal_old) < 10**-10):\n return True\n else:\n return False\n\n # Checks difference in total energy + iterates up to 10\n def iteration(self):\n # if test_convergence returns false then set the old electronic energy to the new electronic energy and do the TEST\n for i in range (0, 50):\n print(i, '\\n')\n test.form_new_fock()\n test.compute_electronic_energy()\n test.compute_total_energy()\n if self.etotal_old != 99999999999:\n if self.convergence and self.difference_energy():\n print(\"Final RMS:\", self.rms)\n print(\"Final Difference:\", self.etotal_new-self.etotal_old)\n print(\"Final Energy:\", self.two_e + self.one_e + self.enuc)\n print (\"Final Iterations\", i)\n break\n else:\n self.etotal_old = self.etotal_new\n test.transform_new_fock()\n test.diagonalize_transformed_fock()\n test.scf_transform()\n test.form_new_density_matrix()\n self.convergence = test.test_convergence()\n self.density_array = self.new_density_array\n\nstart = time.time()\ntest = ProjectFour()\ntest.read_enuc(\"enuc.txt\")\ntest.read_overlap(\"ao_overlap.txt\")\ntest.extract_values_from_overlap()\ntest.read_kinetic(\"ao_kinetic.txt\")\ntest.extract_values_from_kinetic()\ntest.read_potential(\"ao_potential.txt\")\ntest.extract_values_from_potential()\ntest.form_h()\ntest.read_eri(\"ao_eri.txt\")\ntest.extract_values_from_eri()\ntest.convert_lists_to_arrays()\ntest.diagonalize_overlap()\ntest.inverse_square_root_matrix()\ntest.fock_initial_guess()\ntest.diagonalize_fock()\ntest.scf()\ntest.form_density_matrix()\ntest.iteration()\n","sub_path":"Self-Consistent Field Method.py","file_name":"Self-Consistent Field Method.py","file_ext":"py","file_size_in_byte":14557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"622934146","text":"# -*- coding: UTF-8 -*-\n# !/usr/bin/bash python3\n# ----------------------------------\n# Name: fizzbuzz\n# Purpose:\n\n# Author: ronniefeng\n# Copyright: (C) AIDC, Tencent 2019\n# Licence: \n#\n# Created: 2019-05-23\n# Modified:\n# Contributors:\n#\n# ----------------------------------\n\nimport sys\nimport fire\n\n\nclass FizzBuzz(object):\n \"\"\"\n class comment\n \"\"\"\n\n def __init__(self, fizz, buzz):\n self.fizz = fizz\n self.buzz = buzz\n\n def is_fizz(self, number):\n if number % self.fizz == 0 or str(self.fizz) in str(number):\n return True\n\n return False\n\n def is_buzz(self, number):\n if number % self.buzz == 0 or str(self.buzz) in str(number):\n return True\n\n return False\n\n # def is_fizz_buzz(self, number):\n # if self.is_fizz(number) and self.is_buzz(number):\n # return True\n #\n # return False\n\n def report(self, number):\n # if self.is_fizz_buzz(number):\n # return \"FizzBuzz\"\n #\n # if self.is_fizz(number):\n # return \"Fizz\"\n #\n # if self.is_buzz(number):\n # return \"Buzz\"\n\n s = ''\n if self.is_fizz(number):\n s += \"Fizz\"\n if self.is_buzz(number):\n s += \"Buzz\"\n\n if not s:\n s = str(number)\n\n return s\n\n\ndef count_off(count, fizz, buzz):\n fb = FizzBuzz(fizz, buzz)\n\n for n in range(1, count + 1):\n s = fb.report(n)\n print(\"%i -> %s\" % (n, s))\n\n\ndef main():\n\n fire.Fire()\n\nif __name__ == '__main__':\n sys.exit(main())\n","sub_path":"kata_puzzle/fizzbuzz.py","file_name":"fizzbuzz.py","file_ext":"py","file_size_in_byte":1605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"457038409","text":"import unittest\n\nimport torch\nimport numpy as np\nimport scipy.io as sio\nfrom radon_transform.layers import np_iradon\n\nclass TestNPIRADON(unittest.TestCase):\n\tdef test_npiradon_cpu(self):\n\t\tradon_img = sio.loadmat('rdQ.mat')['rdQ']\n#\t\ttheta = sio.loadmat('theta.mat')['theta']\n\t\ttheta = np.linspace(0., 180., 50, endpoint=False)\n\t\ttarget = sio.loadmat('sparse.mat')['sparse']\n\n\t\tradon_img = torch.from_numpy(radon_img).float()\n\t\ttheta = torch.from_numpy(theta).float()\n\n\t\trecon_fbp = np_iradon(radon_img, theta, output_size=512)\n\t\tsio.savemat('torch_np_iradon.mat', dict(fbp_img=recon_fbp.numpy()))\n\n\t\terror = recon_fbp - torch.from_numpy(target).float()\n\n\t\ttol = 5e-5\n\t\troi_err = error.mean().abs()\n\t\tnorm_err = torch.norm(error, 2)\n\t\tprint(\"Error: %.3f, Norm: %.3f\" % (roi_err, norm_err))\n\t\tassert(roi_err < tol)\n\nif __name__ == \"__main__\":\n\tunittest.main()","sub_path":"tests/test_np_iradon.py","file_name":"test_np_iradon.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"202939543","text":"import json\nimport logging\nimport requests\nimport traceback\n\nfrom will import settings\n\nROOM_NOTIFICATION_URL = \"https://%(server)s/v2/room/%(room_id)s/notification?auth_token=%(token)s\"\nROOM_TOPIC_URL = \"https://%(server)s/v2/room/%(room_id)s/topic?auth_token=%(token)s\"\nPRIVATE_MESSAGE_URL = \"https://%(server)s/v2/user/%(user_id)s/message?auth_token=%(token)s\"\nSET_TOPIC_URL = \"https://%(server)s/v2/room/%(room_id)s/topic?auth_token=%(token)s\"\nUSER_DETAILS_URL = \"https://%(server)s/v2/user/%(user_id)s?auth_token=%(token)s\"\nALL_USERS_URL = \"https://%(server)s/v2/user?auth_token=%(token)s&start-index=%(start_index)s\"\n\n\nclass HipChatMixin(object):\n\n def send_direct_message(self, user_id, message_body, html=False, notify=False, **kwargs):\n if kwargs:\n logging.warn(\"Unknown keyword args for send_direct_message: %s\" % kwargs)\n\n format = \"text\"\n if html:\n format = \"html\"\n\n try:\n # https://www.hipchat.com/docs/apiv2/method/private_message_user\n url = PRIVATE_MESSAGE_URL % {\"server\": settings.HIPCHAT_SERVER,\n \"user_id\": user_id,\n \"token\": settings.V2_TOKEN}\n data = {\n \"message\": message_body,\n \"message_format\": format,\n \"notify\": notify,\n }\n headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}\n requests.post(url, headers=headers, data=json.dumps(data), **settings.REQUESTS_OPTIONS)\n except:\n logging.critical(\"Error in send_direct_message: \\n%s\" % traceback.format_exc())\n\n def send_direct_message_reply(self, message, message_body):\n try:\n message.reply(message_body).send()\n except:\n logging.critical(\"Error in send_direct_message_reply: \\n%s\" % traceback.format_exc())\n\n def send_room_message(self, room_id, message_body, html=False, color=\"green\", notify=False, **kwargs):\n if kwargs:\n logging.warn(\"Unknown keyword args for send_room_message: %s\" % kwargs)\n\n format = \"text\"\n if html:\n format = \"html\"\n\n try:\n # https://www.hipchat.com/docs/apiv2/method/send_room_notification\n url = ROOM_NOTIFICATION_URL % {\"server\": settings.HIPCHAT_SERVER,\n \"room_id\": room_id,\n \"token\": settings.V2_TOKEN}\n data = {\n \"message\": message_body,\n \"message_format\": format,\n \"color\": color,\n \"notify\": notify,\n }\n headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}\n requests.post(url, headers=headers, data=json.dumps(data), **settings.REQUESTS_OPTIONS)\n except:\n logging.critical(\"Error in send_room_message: \\n%s\" % traceback.format_exc())\n\n def set_room_topic(self, room_id, topic):\n try:\n # https://www.hipchat.com/docs/apiv2/method/send_room_notification\n url = ROOM_TOPIC_URL % {\"server\": settings.HIPCHAT_SERVER,\n \"room_id\": room_id,\n \"token\": settings.V2_TOKEN}\n data = {\n \"topic\": topic,\n }\n headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}\n requests.put(url, headers=headers, data=json.dumps(data), **settings.REQUESTS_OPTIONS)\n except:\n logging.critical(\"Error in set_room_topic: \\n%s\" % traceback.format_exc())\n\n def get_hipchat_user(self, user_id, q=None):\n url = USER_DETAILS_URL % {\"server\": settings.HIPCHAT_SERVER,\n \"user_id\": user_id,\n \"token\": settings.V2_TOKEN}\n r = requests.get(url, **settings.REQUESTS_OPTIONS)\n if q:\n q.put(r.json())\n else:\n return r.json()\n\n @property\n def full_hipchat_user_list(self):\n if not hasattr(self, \"_full_hipchat_user_list\"):\n full_roster = {}\n\n # Grab the first roster page, and populate full_roster\n url = ALL_USERS_URL % {\"server\": settings.HIPCHAT_SERVER,\n \"token\": settings.V2_TOKEN,\n \"start_index\": 0}\n r = requests.get(url, **settings.REQUESTS_OPTIONS)\n for user in r.json()['items']:\n full_roster[\"%s\" % (user['id'],)] = user\n\n # Keep going through the next pages until we're out of pages.\n while 'next' in r.json()['links']:\n url = \"%s&auth_token=%s\" % (r.json()['links']['next'], settings.V2_TOKEN)\n r = requests.get(url, **settings.REQUESTS_OPTIONS)\n\n for user in r.json()['items']:\n full_roster[\"%s\" % (user['id'],)] = user\n\n self._full_hipchat_user_list = full_roster\n return self._full_hipchat_user_list\n","sub_path":"will/mixins/hipchat.py","file_name":"hipchat.py","file_ext":"py","file_size_in_byte":5065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"111477865","text":"import os\n\nseasons = [\n '2016-2017',\n '2017-2018',\n '2018-2019',\n '2019-2020',\n '2021-2022'\n]\n\ncommands = [\n 'rankings',\n 'results'\n]\n\nwith open('../src/stores/seasons_data.js', 'w') as writer:\n writer.write('export const seasons_data = [')\n for season in seasons:\n if season != seasons[0]:\n writer.write(',\\n')\n writer.write('{{\\nyear: \\'{}\\',\\n'.format(season))\n for command in commands:\n if command != commands[0]:\n writer.write(',\\n')\n writer.write('{}: '.format(command))\n filename = '{}-{}.json'.format(command, season)\n os.system('rm {}'.format(filename))\n os.system(\n 'python -m scrapy crawl {} -a season={} -o {}'.format(command, season, filename))\n with open(filename) as f:\n results = f.read()\n writer.write(results)\n writer.write('\\n}')\n writer.write('\\n]')\n","sub_path":"scrapper/scrap.py","file_name":"scrap.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"431731777","text":"__author__ = 'chris'\n\nfrom collections import namedtuple\n\n\nNameSpaceMapping = namedtuple(\"NameSpaceTuple\", \"namespace prefix\")\nXsd = NameSpaceMapping(\"http://www.w3.org/2001/XMLSchema\", \"xs\")\n\n# key = ns_prefix\n# val = ns\nprimitive_nsmap = dict()\nprimitive_nsmap[Xsd.prefix] = Xsd.namespace\n ","sub_path":"schemavore/namespace.py","file_name":"namespace.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"394129351","text":"from src.utils.tk import TKUtils\nfrom src.view.janela_de_cadastro import JanelaDeCadastro\n\n\nclass Formulario(JanelaDeCadastro):\n\n def __init__(self, eventos):\n super().__init__(titulo='Cadastrar Atividade')\n\n self.eventos = eventos\n\n self.campo_descricao = {}\n self.campo_titulo = {}\n\n def iniciar(self):\n super().iniciar(texto='Cadastrar', campos=2)\n\n self.criar_campo_titulo()\n self.criar_campo_descricao()\n\n def obter_campos(self):\n campos = {}\n\n campos['titulo'] = self.campo_titulo['input'].get()\n campos['descricao'] = self.campo_descricao['input'].get()\n\n return campos\n\n def criar_campo_titulo(self):\n cnf, grid = {}, {}\n\n cnf['text'] = 'Titulo'\n cnf['pady'] = 4\n\n grid['row'] = 0\n grid['column'] = 0\n grid['sticky'] = 'W'\n\n self.campo_titulo['label'] =\\\n TKUtils.obter_label(master=self.corpo, cnf=cnf, grid=grid)\n\n cnf, grid = {}, {}\n\n cnf['placeholder'] = 'Capinar um lote'\n\n grid['row'] = 0\n grid['column'] = 1\n\n self.campo_titulo['input'] =\\\n TKUtils.obter_input(master=self.corpo, cnf=cnf, grid=grid)\n\n def criar_campo_descricao(self):\n cnf, grid = {}, {}\n\n cnf['text'] = 'Descrição'\n cnf['pady'] = 4\n\n grid['row'] = 1\n grid['column'] = 0\n grid['sticky'] = 'W'\n\n self.campo_descricao['label'] =\\\n TKUtils.obter_label(master=self.corpo, cnf=cnf, grid=grid)\n\n cnf, grid = {}, {}\n\n cnf['placeholder'] = 'Programar um drone para capinar um lote'\n\n grid['row'] = 1\n grid['column'] = 1\n\n self.campo_descricao['input'] =\\\n TKUtils.obter_input(master=self.corpo, cnf=cnf, grid=grid)\n","sub_path":"src/view/atividade/cadastro.py","file_name":"cadastro.py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"17206413","text":"from twilio.rest import Client\n\n## The following code is adapted from this example or video : https://www.twilio.com/docs/sms/quickstart/python-msg-svc\n# I changed the account_sid and auth_token value to mach my API\naccount_sid = 'AC56ac5cf2f5d4673750dd02063d836b7c'\nauth_token = '8d344743b1a290d19b362bbd2342bb64'\nclient = Client(account_sid, auth_token)\n\n\n\ndef fun():\n # I changed line 12 to 20 to make the phone number can enter from terminal\n inputNum = input(\"Please enter your phone number\")\n phoneNum = \"44\" + inputNum\n message = client.messages.create(\n from_='441865920701',\n # I adapted the body information\n body='Congratulations, the registration was successful.'\n 'Thank you for updating your fitness center account details.'\n 'We will send you the activity information and discount information in time. ',\n to=phoneNum\n )\n print(message.sid)\n## The end of the code is adapted from this example or video : https://www.twilio.com/docs/sms/quickstart/python-msg-svc\n","sub_path":"project/liaoy19/Message.py","file_name":"Message.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"645528137","text":"people = {'wyy': {'phone': '18012592490', 'sex': 'male'}, 'hty': {'phone': '15625455695', 'sex': 'female'},\n 'gll': {'phone': '18916058036', 'sex': 'female'}, 'sf': {'phone': '14256985623', 'sex': 'female'}}\nname=input(\"Input the name U want to Check:\")\nrequset=input(\"U want check?p/s :\")\n\nkey=requset\nlabel=requset\nif requset== 'p':\n key= 'phone'\n label='phone number'\nif requset== 's':\n key= 'sex'\n label='sex'\nprint(f\"{name} 's {label} is {people.get(name,{}).get(key,'not available')}\")","sub_path":"Dict-test.py","file_name":"Dict-test.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"480030718","text":"\"\"\"This file is Avature spider created on top of the ATSSpider\nscrapy crawl avature -a mining_job_id=9999 -a iteration=1 -a url=\"http://belk.avature.net\" -a robots_obey=0 -a extract=1\n\nForbdden by robots.txt\n\nsample url:\n http://baxter.avature.net\n http://belk.avature.net\n http://rei.jobs\n\"\"\"\nimport hashlib\n\nfrom re import compile\nfrom urlparse import urlsplit\n\nfrom scrapy.http import Request\nfrom scrapy.selector import Selector\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import ConvertDateString, Replace, RemoveBadElements\n\npattern = {\n 'raw_loc': compile(r'City:\\s*([^|]*)\\|\\s*State:\\s*([^|]*)'),\n}\n\n\nclass Avature(ATSSpider):\n\n name = 'avature' # unique identifier for this spider\n desc_xpaths = [\n '//div[@class=\"tPad1\"][not(contains(., \"Apply Now\"))]',\n \"//*[@itemprop='description' or @class='jobDetailDescription']\",\n ]\n\n def start_requests(self):\n \"\"\"Overrides to redirect to search job page.\n if 'path' not found in start url,\n it will redirect to /careers/searchjobs.\n \"\"\"\n for url in self.start_urls:\n (scheme, netloc, path, query, fragment) = urlsplit(url)\n if not path:\n url = \"%s%s\" % (url, '/careers/searchjobs')\n\n yield Request(url)\n\n def parse(self, response):\n \"\"\"Parse job links in that page.\n Get pagination and loop through pages\n Usually 20 jobs per page, some have 5\n \"\"\"\n self.set_meta_language(response)\n\n sel = Selector(response)\n for anchor in sel.xpath(\n \"//li/h3/a[contains(@href,'/JobDetail')] |\"\n \"//li/h2/a[contains(@href,'/JobDetail')] |\"\n \"//li/h4/a[contains(@href,'/JobDetail')] |\"\n '//table[@class=\"jobList\"]//h3/a |'\n '//div[contains(@class, \"jobListItem\")]//a |'\n '//li[@class=\"jobResultItem\"]/a'\n ):\n job_url = anchor.xpath('./@href').extract()\n if job_url:\n yield Request(\n callback=self.parse_job_callback(),\n meta={\n 'location': anchor.xpath(\n './../following-sibling::p[@class=\"job-context\"]/text()'\n ).extract()\n },\n url=job_url[0]\n )\n # MNL-435: check next page link to paginate.\n # some sites dont display total page\n next_page = sel.xpath('//a[.=\"Next >>\"]/@href').extract()\n if next_page:\n next_page_url = next_page[0]\n yield Request(next_page_url, callback=self.parse)\n\n def parse_job(self, response):\n \"\"\"Extract job data\n \"\"\"\n sel = Selector(response)\n location = ''\n loader = BrightcorpItemLoader(selector=sel)\n raw_loc = response.meta.get('location')\n if raw_loc:\n match = pattern['raw_loc'].search(raw_loc[0])\n if match:\n location = ', '.join(match.groups())\n\n date = sel.xpath(\"//*[@itemprop='datePosted']/text()\").extract()\n\n referencenumber = self.get_referencenumber(response)\n\n loader.add_xpath(\"title\", \"//*[@itemprop='title']/text()\")\n loader.add_xpath(\n \"description\", self.desc_xpaths,\n RemoveBadElements(['a']),\n Replace('If you require accommodation in completing the application process please email')\n )\n loader.add_xpath(\n \"location\",\n \"//*[@itemprop='Location']/span/text()|//*[@itemprop='jobLocation']//text()\",\n Replace('Location: ', ''), Replace('Job', '')\n )\n if not loader.get_output_value('location'):\n loader.add_value('location', location)\n loader.add_value(\"referencenumber\", referencenumber)\n\n loader.add_value(\"url\", response.url)\n if date:\n # SCRP-560\n # removing empty spaces in date string\n # Mar- 3-2015\n loader.add_value(\n \"date\",\n date,\n Replace(' ', ''),\n ConvertDateString(\"%d-%b-%Y\")\n )\n if not loader.get_output_value('date'):\n loader.add_value(\n \"date\",\n date,\n Replace(' ', ''),\n ConvertDateString(\"%b-%d-%Y\")\n )\n else:\n loader.add_value('date', response.meta.get('date'), ConvertDateString('%d-%b-%Y'))\n loader.add_xpath(\n 'jobtype',\n '//div[@class=\"detailsJob\"]/p/span[contains(text(), \"Job Type:\")]/../text()'\n )\n loader.add_xpath(\n 'jobcategory',\n '//div[@class=\"detailsJob\"]/p/span[contains(text(), \"Job Function:\")]/../text()'\n )\n loader.add_value('apply_url', response.url)\n\n yield loader.load_item()\n\n def set_custom_item(self, response):\n \"\"\"Pass reference number and job data not found in job description page\n \"\"\"\n referencenumber = self.get_referencenumber(response)\n\n self.loader.add_value(\"referencenumber\", referencenumber)\n\n @staticmethod\n def get_referencenumber(response):\n \"\"\"Extract referencenumber\n \"\"\"\n sel = Selector(response)\n\n subdomain = urlsplit(response.url).netloc.split('.')[0]\n\n referencenumber = sel.xpath(\"//span[.='Ref#:']/following::text()[1]\").extract()\n if not referencenumber:\n referencenumber = response.url.split('/')[-1]\n else:\n referencenumber = referencenumber[0].strip()\n if not referencenumber:\n # some ref id/# are empty e.g. RSA (https://rsa.avature.net)\n referencenumber = hashlib.md5(response.url).hexdigest()\n\n referencenumber = \"%s-%s\" % (subdomain, referencenumber)\n\n return referencenumber\n","sub_path":"brightcorp/brightcorp/spiders/avature.py","file_name":"avature.py","file_ext":"py","file_size_in_byte":5982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"430025188","text":"import requests\nimport json\nimport os\nimport datetime\n\ndef get_data(api_key=\"DEMO_KEY\"):\n raw_response = requests.get(f'https://api.nasa.gov/planetary/apod?api_key={api_key}').text\n response = json.loads(raw_response)\n return response\n\ndef get_picture_url():\n return get_data()['url']\n\ndef dir_check(dir_name):\n if not os.path.exists(dir_name):\n os.makedirs(dir_name)\n\ndef download_image_and_explanation():\n today = datetime.date.today()\n dir_check('apod')\n if os.path.isfile(f'apod/{today}.png') == False:\n data = get_data()\n url = data['url']\n raw_image = requests.get(url).content\n explanation = data['explanation']\n with open(f'apod/{today}.png', 'wb') as file:\n file.write(raw_image)\n with open(f'apod/{today}.txt', 'w') as file:\n file.write(explanation)\n return today\n\ndef get_picture():\n return \"apod/\"+str(download_image_and_explanation())+\".png\"\n\ndef get_explanation():\n return \"apod/\"+str(download_image_and_explanation())+\".txt\"\n\n","sub_path":"apod.py","file_name":"apod.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"540723061","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# vim: sw=4:ts=4:expandtab\n\n\"\"\"\ncsv2ofx\n~~~~~~~\n\nConverts a csv file to ofx and qif\n\nExamples:\n literal blocks::\n\n python example_google.py\n\nAttributes:\n ENCODING (str): Default file encoding.\n\"\"\"\n\nfrom __future__ import (\n absolute_import, division, print_function, with_statement,\n unicode_literals)\n\nimport hashlib\nimport itertools as it\n\nfrom functools import partial\nfrom datetime import datetime as dt\nfrom operator import itemgetter\n\nfrom builtins import *\nfrom six.moves import filterfalse\nfrom meza.process import merge, group\nfrom dateutil.parser import parse\n\nfrom . import utils\n\n__title__ = 'csv2ofx'\n__package_name__ = 'csv2ofx'\n__author__ = 'Reuben Cummings'\n__description__ = 'converts a csv file of transactions to an ofx or qif file'\n__email__ = 'reubano@gmail.com'\n__version__ = '0.19.3'\n__license__ = 'MIT'\n__copyright__ = 'Copyright 2015 Reuben Cummings'\n\n\nmd5 = lambda content: hashlib.md5(content.encode('utf-8')).hexdigest()\n\n\nclass Content(object):\n def __init__(self, mapping=None, **kwargs):\n \"\"\" Base content constructor\n Args:\n mapping (dict): bank mapper (see csv2ofx.mappings)\n kwargs (dict): Keyword arguments\n\n Kwargs:\n split_header (str): Transaction field to use for the split account.\n start (date): Date from which to begin including transactions.\n end (date): Date from which to exclude transactions.\n\n Examples:\n >>> from csv2ofx.mappings.mint import mapping\n >>> Content(mapping) #doctest: +ELLIPSIS\n \n \"\"\"\n mapping = mapping or {}\n [self.__setattr__(k, v) for k, v in mapping.items()]\n\n if not hasattr(self, 'is_split'):\n self.is_split = False\n\n if kwargs.get('split_header'):\n self.split_account = itemgetter(kwargs['split_header'])\n else:\n self.split_account = None\n\n self.start = kwargs.get('start') or dt(1970, 1, 1)\n self.end = kwargs.get('end') or dt.now()\n\n def get(self, name, tr=None, default=None):\n \"\"\" Gets an attribute which could be either a normal attribute,\n a mapping function, or a mapping attribute\n\n Args:\n name (str): The attribute.\n tr (dict): The transaction. Require if `name` is a mapping function\n (default: None).\n\n default (str): Value to use if `name` isn't found (default: None).\n\n Returns:\n (mixed): Either the value of the attribute function applied to the\n transaction, or the value of the attribute.\n\n Examples:\n >>> import datetime\n >>> from datetime import datetime as dt\n >>> from csv2ofx.mappings.mint import mapping\n >>>\n >>> tr = {'Transaction Type': 'debit', 'Amount': 1000.00}\n >>> start = dt(2015, 1, 1)\n >>> Content(mapping, start=start).get('start') # normal attribute\n datetime.datetime(2015, 1, 1, 0, 0)\n >>> Content(mapping).get('amount', tr) # mapping function\n 1000.0\n >>> Content(mapping).get('has_header') # mapping attribute\n True\n \"\"\"\n try:\n attr = getattr(self, name)\n except AttributeError:\n attr = None\n value = None\n else:\n value = None\n\n try:\n value = value or attr(tr) if attr else default\n except TypeError:\n value = attr\n except KeyError:\n value = default\n\n return value\n\n def skip_transaction(self, tr):\n \"\"\" Determines whether a transaction should be skipped (isn't in the\n specified date range)\n\n Args:\n tr (dict): The transaction.\n\n Returns:\n (bool): Whether or not to skip the transaction.\n\n Examples:\n >>> from csv2ofx.mappings.mint import mapping\n >>> from datetime import datetime as dt\n >>>\n >>> tr = {'Date': '06/12/10', 'Amount': 1000.00}\n >>> Content(mapping, start=dt(2010, 1, 1)).skip_transaction(tr)\n False\n >>> Content(mapping, start=dt(2013, 1, 1)).skip_transaction(tr)\n True\n \"\"\"\n return not (self.end >= parse(self.get('date', tr)) >= self.start)\n\n def convert_amount(self, tr):\n \"\"\" Converts a string amount into a number\n\n Args:\n tr (dict): The transaction.\n\n Returns:\n (decimal): The converted amount.\n\n Examples:\n >>> from decimal import Decimal\n >>> from datetime import datetime as dt\n >>> from csv2ofx.mappings.mint import mapping\n >>>\n >>> tr = {'Date': '06/12/10', 'Amount': '$1,000'}\n >>> Content(mapping, start=dt(2010, 1, 1)).convert_amount(tr)\n Decimal('1000.00')\n \"\"\"\n return utils.convert_amount(self.get('amount', tr))\n\n def transaction_data(self, tr):\n \"\"\" gets transaction data\n\n Args:\n tr (dict): the transaction\n\n Returns:\n (dict): the QIF content\n\n Examples:\n >>> import datetime\n >>> from decimal import Decimal\n >>> from csv2ofx.mappings.mint import mapping\n >>> tr = {'Transaction Type': 'debit', 'Amount': 1000.00, \\\n'Date': '06/12/10', 'Description': 'payee', 'Original Description': \\\n'description', 'Notes': 'notes', 'Category': 'Checking', 'Account Name': \\\n'account'}\n >>> Content(mapping).transaction_data(tr) == {\n ... 'account_id': 'e268443e43d93dab7ebef303bbe9642f',\n ... 'memo': 'description notes', 'split_account_id':\n ... None, 'currency': 'USD',\n ... 'date': datetime.datetime(2010, 6, 12, 0, 0),\n ... 'class': None, 'bank': 'account', 'account': 'account',\n ... 'split_account': None,\n ... 'bank_id': 'e268443e43d93dab7ebef303bbe9642f',\n ... 'id': 'ee86450a47899254e2faa82dca3c2cf2', 'payee': 'payee',\n ... 'amount': Decimal('-1000.00'), 'check_num': None,\n ... 'type': 'debit'}\n True\n \"\"\"\n account = self.get('account', tr)\n split_account = self.get('split_account', tr)\n bank = self.get('bank', tr, account)\n\n raw_amount = str(self.get('amount', tr))\n amount = self.convert_amount(tr)\n _type = self.get('type', tr)\n\n if _type:\n amount = -1 * amount if _type.lower() == 'debit' else amount\n else:\n _type = 'CREDIT' if amount > 0 else 'DEBIT'\n\n date = self.get('date', tr)\n payee = self.get('payee', tr)\n desc = self.get('desc', tr)\n notes = self.get('notes', tr)\n memo = '%s %s' % (desc, notes) if desc and notes else desc or notes\n check_num = self.get('check_num', tr)\n details = ''.join(filter(None, [date, raw_amount, payee, memo]))\n\n return {\n 'date': parse(date),\n 'currency': self.get('currency', tr, 'USD'),\n 'bank': bank,\n 'bank_id': self.get('bank_id', tr, md5(bank)),\n 'account': account,\n 'account_id': self.get('account_id', tr, md5(account)),\n 'split_account': split_account,\n 'split_account_id': md5(split_account) if split_account else None,\n 'amount': amount,\n 'payee': payee,\n 'memo': memo,\n 'class': self.get('class', tr),\n 'id': self.get('id', tr, check_num) or md5(details),\n 'check_num': check_num,\n 'type': _type,\n }\n\n def gen_trxns(self, groups, collapse=False):\n for grp, transactions in groups:\n if self.is_split and collapse:\n # group transactions by `collapse` field and sum the amounts\n byaccount = group(transactions, collapse)\n op = lambda values: sum(map(utils.convert_amount, values))\n merger = partial(merge, pred=self.amount, op=op)\n trxns = [merger(dicts) for _, dicts in byaccount]\n else:\n trxns = transactions\n\n yield (grp, trxns)\n\n def clean_trxns(self, groups):\n for grp, trxns in groups:\n _args = [trxns, self.convert_amount]\n\n # if it's split, transactions skipping is all or none\n if self.is_split and self.skip_transaction(trxns[0]):\n continue\n elif self.is_split and not utils.verify_splits(*_args):\n raise Exception('Splits do not sum to zero.')\n elif not self.is_split:\n filtered_trxns = filterfalse(self.skip_transaction, trxns)\n else:\n filtered_trxns = trxns\n\n if self.is_split:\n main_pos = utils.get_max_split(*_args)[0]\n else:\n main_pos = 0\n\n keyfunc = lambda enum: enum[0] != main_pos\n sorted_trxns = sorted(enumerate(filtered_trxns), key=keyfunc)\n yield (grp, main_pos, sorted_trxns)\n","sub_path":"csv2ofx/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":9229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"513263374","text":"import numpy as np\n\n\nclass AcmeProduct:\n\n def __init__(self, name, price=10, weight=20, flammability=.5,\n identifier=np.random.randint(1000000, 9999999)):\n self.name = name\n self.price = price\n self.weight = weight\n self.flammability = flammability\n self.identifier = identifier\n\n def stealability(self):\n steal_me = self.price / self.weight\n if steal_me < .5:\n return 'Not so stealable'\n elif steal_me >= .5 and steal_me < 1.0:\n return 'Kinda stealable'\n else:\n return 'Very stealable'\n\n def explode(self):\n would_explode = self.flammability * self.weight\n if would_explode < 10:\n return 'fizzle'\n elif would_explode >= 10 and would_explode < 50:\n return 'boom'\n else:\n return 'BABOOM'\n\n\nclass BoxingGlove(AcmeProduct):\n\n def __init__(self, weight=10):\n super().__init__(weight)\n self.weight = weight\n # if I wanted to inherit other properties like name or price, add them\n # to super()\n\n def explode(self):\n return '...it\\'s a glove.'\n\n def punch(self):\n if self.weight < 5:\n return 'That tickles'\n elif self.weight >= 5 and self.weight < 15:\n return 'Hey that hurt!'\n else:\n return 'Ouch!'\n\n#prod = AcmeProduct('Toy', 20, 5, .2)\n# print(prod.__dict__)\n\n# autopep8 -i -a acme.py","sub_path":"Sprint/acme.py","file_name":"acme.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"87803258","text":"import unittest\nimport pandas as pd\nimport numpy as np\n\nfrom engine.tolerance import get_time_var_selector, compute_statistics, select_max_diff, compute_max_rel_diff_dataframe\nfrom util.constants import compute_statistics, dataframe_type_dict\n\nTEST_VARIABLES = [\"v1\", \"v2\"]\nTEST_TIMESTEPS = np.arange(3)\n\n\ndef create_dummy_tol_dataframe(k):\n frame = {}\n\n size = len(TEST_VARIABLES) * len(TEST_TIMESTEPS)\n for c in compute_statistics:\n frame[c] = np.ones(size) * k\n\n frame[\"ntime\"] = np.repeat(TEST_TIMESTEPS, len(TEST_VARIABLES))\n frame[\"time\"] = np.repeat(TEST_TIMESTEPS, len(TEST_VARIABLES))\n frame[\"name\"] = TEST_VARIABLES * len(TEST_TIMESTEPS)\n\n df = pd.DataFrame.from_dict(frame)\n\n return df\n\n\ndef hand_written_dataframes():\n frame = [None] * 3\n frame[0] = {\"max\": [10, 4, 2, 56, 79, 38],\n \"min\": [3, 9, 1, 97, 46, 52],\n \"mean\": [5, 1, 8, 16, 24, 94],\n \"ntime\": [1, 2, 3, 1, 2, 3],\n \"time\": [1, 2, 3, 1, 2, 3],\n \"name\": [\"v1\", \"v1\", \"v1\", \"v2\", \"v2\", \"v2\"]}\n\n frame[1] = {\"max\": [1, 2, 5, 28, 64, 13],\n \"min\": [3, 3, 5, 24, 12, 64],\n \"mean\": [1, 10, 5, 35, 85, 13],\n \"ntime\": [1, 2, 3, 1, 2, 3],\n \"time\": [1, 2, 3, 1, 2, 3],\n \"name\": [\"v1\", \"v1\", \"v1\", \"v2\", \"v2\", \"v2\"]}\n\n frame[2] = {\"max\": [1, 4, 2, 79, 89, 64],\n \"min\": [8, 6, 10, 25, 46, 35],\n \"mean\": [2, 3, 1, 15, 45, 57],\n \"ntime\": [1, 2, 3, 1, 2, 3],\n \"time\": [1, 2, 3, 1, 2, 3],\n \"name\": [\"v1\", \"v1\", \"v1\", \"v2\", \"v2\", \"v2\"]}\n\n df_ref = {\"max\": [10, 4, 5, 79, 89, 64],\n \"min\": [8, 9, 10, 97, 46, 64],\n \"mean\": [5, 10, 8, 35, 85, 94],\n \"ntime\": [1, 2, 3, 1, 2, 3],\n \"time\": [1, 2, 3, 1, 2, 3],\n \"name\": [\"v1\", \"v1\", \"v1\", \"v2\", \"v2\", \"v2\"]}\n\n return [pd.DataFrame(d).sort_values(by=[\"name\", \"ntime\"]).reset_index(drop=True)\n for d in frame], pd.DataFrame(df_ref)\n\n\nclass TestTolerance(unittest.TestCase):\n\n def setUp(self):\n self.dfs = [create_dummy_tol_dataframe(k) for k in [1, 10]]\n self.hand_dfs, self.df_ref = hand_written_dataframes()\n\n def tearDown(self):\n return\n\n def test_tolerance(self):\n diff = compute_max_rel_diff_dataframe(self.dfs[0], self.dfs[1], TEST_VARIABLES)\n for c in compute_statistics:\n ref = np.ones(len(diff.index))*9\n self.assertTrue((diff[c] == ref).all(), \"Compute rel diff failed on statistic {}\".format(c))\n\n df_max = select_max_diff(self.hand_dfs, TEST_VARIABLES)\n for c in compute_statistics:\n self.assertTrue((df_max[c].values == self.df_ref[c].values).all(),\n \"Select max test failed on statistic {}. Got {} instead of {}\"\n .format(c, df_max[c], self.df_ref[c]))\n\n self.assertTrue((df_max.index == self.df_ref.index).all(), \"indices of DataFrames do not match!\")\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"unittest/engine/test_tolerance.py","file_name":"test_tolerance.py","file_ext":"py","file_size_in_byte":3113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"145282397","text":"n = int(input())\nc = 0\ndef ap(a1, n, d):\n return a1 + (n - 1) * d\n\nfor i in range(1, n + 1):\n numbers = list(map(int, str(i)))\n if len(numbers) < 3:\n c += 1\n else:\n a1 = numbers[0]\n d = numbers[1] - a1\n for index, number in enumerate(numbers): \n if number != ap(a1, index + 1 , d):\n break\n if index == len(numbers) - 1:\n c += 1\nprint(c)\n\"\"\"문제\n어떤 양의 정수 X의 각 자리가 등차수열을 이룬다면, 그 수를 한수라고 한다. 등차수열은 연속된 두 개의 수의 차이가 일정한 수열을 말한다. N이 주어졌을 때, 1보다 크거나 같고, N보다 작거나 같은 한수의 개수를 출력하는 프로그램을 작성하시오. \n\n입력\n첫째 줄에 1,000보다 작거나 같은 자연수 N이 주어진다.\n\n출력\n첫째 줄에 1보다 크거나 같고, N보다 작거나 같은 한수의 개수를 출력한다.\n\n예제 입력 1 \n110\n예제 출력 1 \n99\n예제 입력 2 \n1\n예제 출력 2 \n1\n예제 입력 3 \n210\n예제 출력 3 \n105\n예제 입력 4 \n1000\n예제 출력 4 \n144\n예제 입력 5 \n500\n예제 출력 5 \n119\"\"\"","sub_path":"devgony/06-function/03-1065-ArithmeticProgression.py","file_name":"03-1065-ArithmeticProgression.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"340741029","text":"# from 'game_src/game/views' import * \nfrom collections import *\ndef specs():\n\n\t#Space separated (tokenized) strings\n\taccept_strings = [\"?\", \"! ?\", \"( ? ) ?\", \"! )\"]\n\treject_strings = [\")\", \") (\"]\n\n\tconfig = {\n\t\t'num_rules': 6, #Number of rules\n\t\t'size_rules' : 4, #Number of symbols in RHS\n\t\t'num_nonterms' : 4, #Number of nonterms\n\t\t'expansion_constant' : 6, #Determines the max. number of parse actions to take while parsing\n\t\t'optimize' : False, # enable optimized mode\n\t\t'neg_egs' : True, # consider negative examples \n\t\t'threshold' : 0.2 # number of unsat cores to break\n\t}\n\n\treturn accept_strings,reject_strings,config\n\ndef find_original_grammar():\n\t##incorrect string and everything else is ok. last accept string\n\toriginal_grammar = [['S','eps','eps','F','S'], ['S','eps','eps','eps','Q'], ['S','(','S',')','S'], ['F','eps','eps','!','A'], ['Q','eps','eps','?','A'],['A','eps','eps','eps','eps']]\n\t# return get_original_grammar()\n\treturn original_grammar\n\ndef get_parse_table():\n\tparse_table = [{'non_term':'S' ,'(':3 ,')':0 ,'!':1 ,'?':2 ,'$':0},{'non_term':'F' ,'(':0 ,')':0 ,'!':4 ,'?':0 ,'$':0},{'non_term':'Q' ,'(':0 ,')':0 ,'!':0 ,'?':5 ,'$':0},{'non_term':'A' ,'(':6 ,')':6 ,'!':6 ,'?':6 ,'$':6}]\n\treturn parse_table\n\ndef nums():\n\toriginal_grammar = find_original_grammar()\n\tnum_vars = {'num_rules':len(original_grammar), 'size_rules':len(original_grammar[0])-1}\n\treturn num_vars\n\ndef get_first_set():\n\tfirst_set = [{'non_term':'S' ,'(':1 ,')':0 ,'!':1 ,'?':1 ,'eps':0},{'non_term':'F' ,'(':0 ,')':0 ,'!':1 ,'?':0 ,'eps':0},{'non_term':'Q' ,'(':0 ,')':0 ,'!':0 ,'?':1 ,'eps':0},{'non_term':'A' ,'(':0 ,')':0 ,'!':0 ,'?':0 ,'eps':1}]\n\treturn first_set\n\ndef get_follow_set():\n\tfollow_set = [{'non_term':'S' ,'(':0 ,')':1 ,'!':0 ,'?':0 ,'$':1},{'non_term':'F' ,'(':1 ,')':0 ,'!':1 ,'?':1 ,'$':0},{'non_term':'Q' ,'(':0 ,')':1 ,'!':0 ,'?':0 ,'$':1},{'non_term':'A' ,'(':1 ,')':1 ,'!':1 ,'?':1 ,'$':1}]\n\treturn follow_set\n\naccept_strings = [\"?\", \"! ?\", \"( ? ) ?\"]\nreject_strings = [\")\", \") (\"]\n\n##\tS -> (S)S | eps\n##\n\n","sub_path":"Grammar_examples/input_specs8i1.py","file_name":"input_specs8i1.py","file_ext":"py","file_size_in_byte":2030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"608233027","text":"import tweepy\n#import asyncio\nimport time\nimport threading\nfrom custom_stream_listener import CustomStreamListener as CSL\nfrom custom_thread import CustomThread\nfrom tweet_feed import Feed\nimport data_object\nfrom basic_cleaner import BasicCleaner\n\n\n\nrun_for_seconds = 10\ntoggle_live = True\ndataset_file_path = \"../test_set\"\ntrack = [\"how\", \"does\", \"one\", \"even\", \"go\", \"so\", \"far\", \"as\", \"to\" ]\nsentiment_range = [float(-1), float(-0.5)]\n\nqueue_stream = []\nqueue_cleaned = []\n\nstream = None\nlistener = None\n\n\n\ndef setup_tweet_stream(out_stream):\n feed = Feed()\n if toggle_live:\n global listener \n listener = feed.live_get_listener(out_stream)\n global stream \n stream = feed.live_get_streamer(listener, track)\n else:\n global queue_stream\n queue_stream = feed.disk_get_tweet_queue(dataset_file_path)\n\n\n\ndef clean_process():\n tweet = queue_stream.pop(0)\n new_data_obj = data_object.get_dataobj_converted(tweet)\n BasicCleaner.autocleaner(new_data_obj, sentiment_range, True)\n queue_cleaned.append(new_data_obj)\n\n\n\nswitch_cleaner_loop = True # // AA: hack\ndef cleaner_loop():\n while switch_cleaner_loop:\n if len(queue_stream) > 0:\n try:\n clean_process()\n except:\n print(\"cleaner_loop issue in main.py\")\n\n\n\nsetup_tweet_stream(queue_stream)\n\nfirst_thread = CustomThread(cleaner_loop, False)\nfirst_thread.start()\n\n \n\n# // prevent immediate termination\nwhile run_for_seconds > 0:\n run_for_seconds -= 1\n time.sleep(1)\n\nswitch_cleaner_loop = False\nstream.disconnect() if stream is not None else ...\nfirst_thread.stop()\nprint(\"terminating program\")","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"227589186","text":"if __name__ == '__main__':\r\n\tm = int(input())\r\n\tm_array = set(map(int, input().split()))\r\n\tn = int(input())\r\n\tn_array = set(map(int, input().split()))\r\n\tm_diff_n = m_array.difference(n_array)\r\n\tn_diff_m = n_array.difference(m_array)\r\n\tm_diff_n.update(n_diff_m)\r\n\tfor num in sorted(m_diff_n):\r\n\t\tprint(num)","sub_path":"symmetric_difference.py","file_name":"symmetric_difference.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"173750247","text":"from move.MoveUtils import move_to_uci_move\nimport Evaluation\n\nmax_utility = 999999\nmaximum_depth = 4 # not counting evaluation nodes (e.g. for maximum_depth = 4: max (at depth 0),min,max,min,evaluate (at depth 4))\ncount = -1\ntransposition_count = -1\n\n\ndef get_best_move(board, opponents_uci_move, is_engine_white):\n best_move = 'no move'\n transposition_table = {} # {hash: (depth, score, best_move)}\n # for depth_max in range(maximum_depth, maximum_depth + 1): # debug\n for depth_max in range(1, maximum_depth + 1):\n best_move = alpha_beta_at_root(board, opponents_uci_move, is_engine_white, depth_max, transposition_table) # print(board.current_hash)\n transposition_table.clear()\n return best_move\n\n\ndef visit_node():\n global count\n count += 1\n return count\n\n\ndef use_transposition_table():\n global transposition_count\n transposition_count += 1\n return transposition_count\n\n\ndef alpha_beta_at_root(board, opponents_uci_move, is_engine_white, depth_max, transposition_table):\n best_move = 'none'\n best_move_val = -max_utility if is_engine_white else max_utility\n moves = board.get_color_moves(is_engine_white, opponents_uci_move)\n visit_node()\n if len(moves) == 1:\n return moves[0], Evaluation.evaluate(board.board)\n if board.current_hash in transposition_table: # depth always smaller (iterative deepening)\n best_move_calculated = transposition_table[board.current_hash][2]\n if best_move_calculated != 'none':\n moves.insert(0, best_move_calculated) # search best move found earlier first (+ duplicate move by doing so :/ )\n for move in moves:\n move.do_move(board)\n val = alpha_beta(board, opponents_uci_move, not is_engine_white, -max_utility, max_utility, depth_max - 1, transposition_table)\n move.undo_move(board)\n if is_engine_white:\n if val > best_move_val:\n best_move, best_move_val = move, val\n else:\n if val < best_move_val:\n best_move, best_move_val = move, val\n transposition_table[board.current_hash] = (depth_max, best_move_val, best_move)\n return best_move, best_move_val\n\n\ndef alpha_beta(board, opponents_uci_move, is_engine_white, alpha, beta, depth, transposition_table):\n if board.current_hash in transposition_table:\n if transposition_table[board.current_hash][0] >= depth:\n use_transposition_table()\n return transposition_table[board.current_hash][1]\n best_move_calculated = transposition_table[board.current_hash][2]\n else:\n best_move_calculated = 'none'\n visit_node()\n if depth == 0:\n evaluation = Evaluation.evaluate(board.board)\n transposition_table[board.current_hash] = (depth, evaluation, 'none')\n return evaluation\n moves = board.get_color_moves(is_engine_white, opponents_uci_move)\n if best_move_calculated != 'none':\n moves.insert(0, best_move_calculated)\n\n if is_engine_white:\n best_val, best_move = -max_utility, 'none'\n for move in moves:\n uci_move = move_to_uci_move(move)\n move.do_move(board)\n val = alpha_beta(board, uci_move, not is_engine_white, alpha, beta, depth - 1, transposition_table)\n move.undo_move(board)\n if val > best_val:\n best_val, best_move = val, move\n alpha = max(alpha, best_val)\n if alpha >= beta:\n break\n else:\n best_val, best_move = +max_utility, 'none'\n for move in moves:\n uci_move = move_to_uci_move(move)\n move.do_move(board)\n val = alpha_beta(board, uci_move, not is_engine_white, alpha, beta, depth - 1, transposition_table)\n move.undo_move(board)\n if val < best_val:\n best_val, best_move = val, move\n beta = min(beta, best_val)\n if beta <= alpha:\n break\n transposition_table[board.current_hash] = (depth, best_val, best_move)\n return best_val\n","sub_path":"Ai.py","file_name":"Ai.py","file_ext":"py","file_size_in_byte":4046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"622079975","text":"#!/usr/bin/env python3\n#coding: utf-8\nimport os\nimport BlastClass\nimport ArvoreFilo\nfrom sys import platform\nfrom flask import Flask, render_template, request, send_file, flash, redirect, url_for\nfrom werkzeug.utils import secure_filename\n\nHOST_ADDR=\"localhost\"\nDATABASES={\n 1 : [\"genomas/protNC_030850.1.fasta\", \"genomas/protCM001879.1.fasta\"], \n 2 : [\"genomas/NC_030850.1.fasta\", \"genomas/CM001879.1.fasta\"]\n}\nQUERY_DEFAULT=\"userSeq.fasta\"\nUPLOADS_FOLDER=\"uploads/\"\nDOWNLOADS_FOLDER=\"downloads/\"\nXML_NAME=\"resultado.xml\"\nTREE_NAME=\"tree.pdf\"\nARVORE_INST = ArvoreFilo.Arvore()\nBLAST_INST = BlastClass.Blast(\n os.path.join(\n DOWNLOADS_FOLDER, \n XML_NAME\n )\n)\nSEQUENCE_BAR_STATUS=\"\"\n\napp = Flask(__name__)\napp.secret_key = b'BDk^iUe99W*0r0S!eM9!8A'\napp.config[\"UPLOAD_FOLDER\"] = UPLOADS_FOLDER\n\n@app.route(\"/\")\ndef home():\n sequence_status = \"is-hidden\"\n if platform == \"linux\":\n seqspid = os.system(\"pidof sequenceserver\")\n if seqspid != 256:\n sequence_status = \"\"\n SEQUENCE_BAR_STATUS = sequence_status\n return render_template(\"index.html\", home_bar_classes=\"is-active\", sequence_bar_classes=sequence_status, blast_classes=\"is-hidden\")\n\n@app.route(\"/\", methods=[\"POST\"])\ndef runBlast():\n filename = \"\"\n genoma1 = request.form.get(\"genoma1\")\n genoma2 = request.form.get(\"genoma2\")\n genomaU = request.form.get(\"tree-nucleotideo\")\n if genoma1 or genoma2:\n listaFastas = []\n if genoma1:\n listaFastas.append(\"genomas/{}.fasta\".format(genoma1))\n if genoma2:\n listaFastas.append(\"genomas/{}.fasta\".format(genoma2))\n if \"file\" in request.files:\n arquivo = request.files[\"file\"]\n if arquivo.filename != \"\":\n filename = secure_filename(arquivo.filename)\n arquivo.save(os.path.join(\"genomas/\", filename))\n listaFastas.append(\"genomas/{}\".format(filename))\n if len(genomaU) > 0:\n filename = \"userTree.fasta\"\n with open(os.path.join(\"genomas/\", filename), \"w\") as arquivo:\n arquivo.write(genomaU)\n listaFastas.append(\"genomas/{}\".format(filename))\n ARVORE_INST.run(listaFastas)\n return redirect(url_for(\"downloadtree\"))\n \n upFolder = app.config[\"UPLOAD_FOLDER\"]\n mBlast = request.form.get(\"modoBlast\")\n uInput = request.form.get(\"nucleotideo\")\n genoma = request.form.get(\"escolhaGenoma\")\n bValor = int(mBlast)\n dbValor = int(genoma)\n\n if \"file\" in request.files:\n arquivo = request.files[\"file\"]\n if arquivo.filename != \"\":\n filename = secure_filename(arquivo.filename)\n arquivo.save(os.path.join(upFolder, filename))\n if len(uInput) > 0:\n filename = QUERY_DEFAULT\n with open(os.path.join(upFolder, filename), \"w\") as arquivo:\n arquivo.write(uInput)\n\n if filename == \"\":\n flash(\"Não foi fornecido arquivo nem sequência.\")\n return render_template(\"index.html\", blast_bar_classes=\"is-active\", sequence_bar_classes=SEQUENCE_BAR_STATUS, home_classes=\"is-hidden\")\n\n query = os.path.join(upFolder, filename)\n BLAST_INST.run(DATABASES[bValor][dbValor], bValor, query)\n return redirect(url_for(\"downloadxml\"))\n\n@app.route(\"/download/blast\")\ndef downloadxml():\n return send_file(\n os.path.join(DOWNLOADS_FOLDER, XML_NAME), \n as_attachment=True, \n cache_timeout=0\n )\n\n@app.route(\"/download/tree\")\ndef downloadtree():\n return send_file(\n os.path.join(DOWNLOADS_FOLDER, TREE_NAME), \n as_attachment=True, \n cache_timeout=0\n )\n\nif __name__ == \"__main__\":\n app.run(host=HOST_ADDR, debug=True)\n\n","sub_path":"website/website.py","file_name":"website.py","file_ext":"py","file_size_in_byte":3708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"46126597","text":"# -*- coding: utf-8 -*-\n#\n#\n# Authors: Laurent Mignon\n# Copyright (c) 2013 Acsone SA/NV (http://www.acsone.eu)\n# All Rights Reserved\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n#\nfrom openerp.tests import common\nimport time\n\nACC_NUMBER = \"BE38733040385372\"\n\n\nclass bankaccount_completion(common.TransactionCase):\n\n def prepare(self):\n self.company_a = self.browse_ref('base.main_company')\n self.profile_obj = self.registry(\"account.statement.profile\")\n self.account_bank_statement_obj = self.registry(\"account.bank.statement\")\n self.account_bank_statement_line_obj = self.registry(\"account.bank.statement.line\")\n self.completion_rule_id = self.ref('account_statement_bankaccount_completion.bank_statement_completion_rule_10')\n self.journal_id = self.registry(\"ir.model.data\").get_object_reference(self.cr, self. uid, \"account\", \"bank_journal\")[1]\n self.partner_id = self.ref('base.main_partner')\n # Create the profile\n self.account_id = self.registry(\"ir.model.data\").get_object_reference(self.cr, self.uid, \"account\", \"a_recv\")[1]\n self.journal_id = self.registry(\"ir.model.data\").get_object_reference(self.cr, self. uid, \"account\", \"bank_journal\")[1]\n self.profile_id = self.profile_obj.create(self.cr, self.uid, {\n \"name\": \"TEST\",\n \"commission_account_id\": self.account_id,\n \"journal_id\": self.journal_id,\n \"rule_ids\": [(6, 0, [self.completion_rule_id])]})\n # Create the completion rule\n\n # Create a bank statement\n self.statement_id = self.account_bank_statement_obj.create(self.cr, self.uid, {\n \"balance_end_real\": 0.0,\n \"balance_start\": 0.0,\n \"date\": time.strftime('%Y-%m-%d'),\n \"journal_id\": self.journal_id,\n \"profile_id\": self.profile_id\n\n })\n\n # Create bank a statement line\n self.statement_line_id = self.account_bank_statement_line_obj.create(self.cr, self.uid, {\n 'amount': 1000.0,\n 'name': 'EXT001',\n 'ref': 'My ref',\n 'statement_id': self.statement_id,\n 'partner_acc_number': ACC_NUMBER\n })\n\n # Add a bank account number to the partner\n res_bank_obj = self.registry('res.partner.bank')\n res_bank_obj.create(self.cr, self.uid, {\n \"state\": \"bank\",\n \"company_id\": self.company_a.id,\n \"partner_id\": self.partner_id,\n \"acc_number\": ACC_NUMBER,\n \"footer\": True,\n \"bank_name\": \"Reserve\"\n })\n\n def test_00(self):\n \"\"\"Test complete partner_id from bank account number\n \n Test the automatic completion of the partner_id based on the account number associated to the\n statement line\n \"\"\"\n self.prepare()\n statement_line = self.account_bank_statement_line_obj.browse(self.cr, self.uid, self.statement_line_id)\n # before import, the\n self.assertFalse(statement_line.partner_id, \"Partner_id must be blank before completion\")\n statement_obj = self.account_bank_statement_obj.browse(self.cr, self.uid, self.statement_id)\n statement_obj.button_auto_completion()\n statement_line = self.account_bank_statement_line_obj.browse(self.cr, self.uid, self.statement_line_id)\n self.assertEquals(self.partner_id, statement_line.partner_id['id'], \"Missing expected partner id after completion\")\n","sub_path":"__unported__/account_statement_bankaccount_completion/tests/test_bankaccount_completion.py","file_name":"test_bankaccount_completion.py","file_ext":"py","file_size_in_byte":4184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"38060836","text":"import sys\ndef sumfac(d):\n total = 0\n a = int(d ** 0.5)\n for i in range(1, a + 1):\n if d % i == 0:\n total += i\n if i != d / i:\n total += d / i\n return total - d\n\ndef isPerfect(d):\n if d == sumfac(d):\n return True\n else:\n return False\ndef main():\n d = sys.stdin\n for i in d:\n i = i.strip()\n if i.isnumeric():\n print(isPerfect(int(i)))\nif __name__ == '__main__':\n main()\n","sub_path":"week06/perfect_062.py","file_name":"perfect_062.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"599031011","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n'''\n@author: zhaogao\n@license: (C) Copyright 2013-2017.\n@contact: 449628536@qq.com\n@software: learn-py\n@file: len32_multiple_exception.py\n@time: 2017/11/29 上午11:30\n'''\n\ntry:\n file = open('/Users/zhaogao/PycharmProjects/learn-py/len32_multiple_exception.y', 'rb')\nexcept (IOError, EOFError) as e:\n print('an error occurred. {}'.format(e.args[-1]))\n\ntry:\n file = open('/Users/zhaogao/PycharmProjects/learn-py/len32_multiple_exception.y', 'rb')\nexcept IOError as e:\n print('an IOError occurred. {}'.format(e.args[-1]))\nexcept EOFError as e:\n print('an EOFError occurred. {}'.format(e.args[-1]))\n\ntry:\n file = open('/Users/zhaogao/PycharmProjects/learn-py/len32_multiple_exception.y', 'rb')\nexcept Exception:\n\n raise","sub_path":"inter-py/len32_multiple_exception.py","file_name":"len32_multiple_exception.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"387054510","text":"def gcd(a,b):\n if(b == 0):\n return a\n else:\n r = a % b\n return gcd(b,r)\n\ndef __main__():\n print(\"Enter 2 numbers \")\n a = int(input())\n b = int(input())\n if(a < b):\n print(gcd(b,a))\n else:\n print(gcd(a,b))\n\n__main__()\n","sub_path":"Exe0608.py","file_name":"Exe0608.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"306474734","text":"# Napisz program, który wczyta od użytkownika tekst, a następnie podwoi w nim co drugi znak i wyświetli wynik,\n#\n# np.: ALA MA PSA -> ALLA MAA PPSAA\n\ndef czengetor():\n napis = input('Podaj tekst, ziomku: ')\n napis1 = ''\n znak = 0\n for i in napis:\n if znak % 2 != 0: # and napis.index(i) != 0:\n napis1 += i * 2\n else:\n napis1 += i\n znak += 1\n return napis1\n\n\nprint(czengetor())\n","sub_path":"zjazd_do_bazy_2/zadanie_dod_slack_2.py","file_name":"zadanie_dod_slack_2.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"128687505","text":"# -*- coding: utf-8 -*-\nimport time\nfrom datetime import datetime\nfrom datetime import time as datetime_time\nfrom dateutil import relativedelta\n\nimport babel\n\nfrom odoo import api, fields, models, tools, _\nfrom odoo.addons import decimal_precision as dp\nfrom odoo.exceptions import UserError, ValidationError\n\n\nclass HrPayslip(models.Model):\n _inherit = 'hr.payslip'\n \n# @api.model\n# def create(self,vals):\n# res = super(HrPayslip,self).create(vals)\n# #For faster performance used query.\n# if res.date_from and res.date_to and res.contract_id:\n# self._cr.execute(\"select count(id) from hr_attendance where check_in::date>='%s' and check_out::date<='%s' and employee_id=%d\"%(res.date_from,res.date_to,res.employee_id.id))\n# result = self._cr.fetchone()\n# if result and result[0]:\n# self.env['hr.payslip.worked_days'].create({'name': '%s Attendances'%(res.employee_id.name),'number_of_days':result[0], 'code' : 'Attendance', 'payslip_id':res.id,'contract_id':res.contract_id.id})\n# return res\n# \n @api.onchange('employee_id', 'date_from', 'date_to')\n def onchange_employee(self):\n res = super(HrPayslip, self).onchange_employee()\n lst = []\n if self.date_from and self.date_to and self.contract_id:\n self._cr.execute(\"select count(id) from hr_attendance where check_in::date>='%s' and check_out::date<='%s' and employee_id=%d\" % (self.date_from, self.date_to, self.employee_id.id))\n result = self._cr.fetchone()\n if result and result[0]:\n lst.append({'name': '%s Attendances' % (self.employee_id.name),\n 'number_of_days': result[0],\n 'code' : 'Attendance',\n 'contract_id': self.contract_id.id})\n # leave\n self._cr.execute(\"\"\"select sum(number_of_days_temp)\n from hr_holidays\n where date_from::date >= '%s'\n and date_to::date <= '%s'\n and state = 'validate'\n and type = 'remove'\n and employee_id='%s'\"\"\" % (self.date_from, self.date_to, self.employee_id.id))\n result = self._cr.fetchone()\n print (\"\\n\\n --payslip_attendance_ext--\", result)\n if result:\n lst.append({'name': '%s Leave' % (self.employee_id.name),\n 'number_of_days': result[0] if result[0] else 0.00,\n 'code' : 'Leave',\n 'contract_id': self.contract_id.id})\n #self.worked_days_line_ids = False\n worked_days_lines = self.worked_days_line_ids.browse([])\n for r in lst:\n worked_days_lines += worked_days_lines.new(r)\n self.worked_days_line_ids += worked_days_lines\n return res\n","sub_path":"payslip_attendance_ext/models/hr_payslip.py","file_name":"hr_payslip.py","file_ext":"py","file_size_in_byte":2970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"396291404","text":"# encoding: utf-8\n\n'''\nCreated on 2016-05-02\n\n@author: jasonzhu\n'''\n\n\nimport pandas as pd\n\nif __name__ == '__main__':\n df = pd.read_csv('QuestionsWithSkillHierarchy.csv', encoding='utf-8')\n # df_all['ancestry'] = df_all['ancestry'].apply(lambda x: '/'.join(x.split('/')[0:2]))\n\n\n df.groupby(['major_skill']).size().to_frame().to_csv('major_skill_count.csv', encoding='utf-8')\n df.groupby(['major_skill', 'subskill']).size().to_frame().to_csv('sub_skill_count.csv', encoding='utf-8')","sub_path":"com/judking/python/sqore/miscellaneous/QuestionCountBySkills.py","file_name":"QuestionCountBySkills.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"54142957","text":"import sys, xbmc, json\n\ntry:\n\tfrom urlparse import parse_qsl\n\tfrom urllib import quote_plus\nexcept:\n\tfrom urllib.parse import parse_qsl, quote_plus\n\n\nif __name__ == '__main__':\n\titem = sys.listitem\n\tmessage = item.getLabel()\n\tpath = item.getPath()\n\tplugin = 'plugin://plugin.video.firefly/'\n\targs = path.split(plugin, 1)\n\txbmc.log('args = %s' % args, 2)\n\n\tparams = dict(parse_qsl(args[1].replace('?', '')))\n\n\n\txbmc.executebuiltin(path)\n","sub_path":"context.firefly/sourceSelect.py","file_name":"sourceSelect.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"319955281","text":"import pandas as pd\nimport numpy as np\nimport sys\nimport os\nimport datetime as dt\nfrom dateutil.parser import parse\nfrom collections import defaultdict\nfrom pandas.tseries.offsets import Minute\nimport datetime as dt\nfrom datetime import datetime, timedelta\nimport simplejson as json\n\nsys.path.append(os.path.join(os.path.expanduser(\"~\"),\n 'python', 'pdtools'))\nimport pdtools\n\nCONFIG = json.load(open(os.path.join(os.path.expanduser('~/python/nzem/nzem'),\n 'config.json')))\n\nclass Offer(object):\n \"\"\"docstring for Offer\"\"\"\n def __init__(self, offers, run_operations=True):\n super(Offer, self).__init__()\n self.offers = offers.copy()\n self.offer_stack = None\n if run_operations:\n self._retitle_columns()\n self._convert_dates()\n self._map_location()\n self._apply_datetime()\n self._sort_offers()\n self.offers.index = np.arange(len(self.offers))\n\n def stack_columns(self):\n self.offer_stack = pd.concat(self._stacker(), ignore_index=True)\n\n\n def filter_stack(self, date=None, period=None, product_type=None,\n reserve_type=None, island=None, company=None,\n region=None, station=None, non_zero=False,\n return_df=False):\n\n if not type(self.offer_stack) == pd.core.frame.DataFrame:\n self.stack_columns()\n\n fstack = self.offer_stack.copy()\n\n if date:\n fstack = fstack.eq_mask(\"Trading Date\", date)\n\n if period:\n fstack = fstack.eq_mask(\"Trading Period\", period)\n\n if product_type:\n fstack = fstack.eq_mask(\"Product Type\", product_type)\n\n if reserve_type:\n fstack = fstack.eq_mask(\"Reserve Type\", reserve_type)\n\n if island:\n fstack = fstack.eq_mask(\"Island\", island)\n\n if company:\n fstack = fstack.eq_mask(\"Company\", company)\n\n if region:\n fstack = fstack.eq_mask(\"Region\", region)\n\n if station:\n fstack = fstack.eq_mask(\"Station\", station)\n\n if non_zero:\n fstack = fstack.gt_mask(\"Max\", 0)\n\n self.fstack = fstack\n\n if return_df:\n return fstack\n\n\n def clear_offers(self, requirement, fstack=None, return_df=True):\n \"\"\" Clear the offers against a requirement \"\"\"\n\n if not type(fstack) == pd.core.frame.DataFrame:\n fstack = self.fstack.copy()\n\n if len(fstack[\"Trading Datetime\"].unique()) > 1:\n raise ValueError(\"Filtered Dataset contains more than one\\\n date, this invalidates the clearing\")\n\n if len(fstack[\"Reserve Type\"].unique()) > 1:\n raise ValueError(\"Filtered Dataset contains more than one\\\n type of data, this invalidates the clearing\")\n\n # Drop the zero offers\n fstack = fstack.gt_mask(\"Max\", 0.0)\n # Sort by price\n fstack.sort(columns=[\"Price\"], inplace=True)\n\n # Reindex\n fstack.index = np.arange(len(fstack))\n\n # Cumulative Offers\n fstack[\"Cumulative Offers\"] = fstack[\"Max\"].cumsum()\n\n # Apply a cleared flag\n marginal_unit = fstack.ge_mask(\"Cumulative Offers\", requirement).index[0]\n fstack[\"Cleared\"] = False\n fstack[\"Cleared\"][:marginal_unit+1] = True\n\n # Determine the dispatched quantity\n fstack[\"Cleared Quantity\"] = 0\n fstack[\"Cleared Quantity\"][:marginal_unit] = fstack[\"Max\"][:marginal_unit]\n\n # Special case for the marginal unit.\n fstack[\"Cleared Quantity\"][marginal_unit] = requirement - fstack[\"Max\"][:marginal_unit].sum()\n\n # Determine the dispatched price\n fstack[\"Clearing Price\"] = fstack.eq_mask(\"Cleared\", True)[\"Price\"].max()\n\n self.cleared_fstack = fstack\n if return_df:\n return fstack\n\n\n\n\n def _stacker(self):\n \"\"\" General Stacker designed to handle all forms of\n offer dataframe, energy, plsr, and IL\n \"\"\"\n\n\n general_columns = [x for x in self.offers.columns if \"Band\" not in x]\n band_columns = [x for x in self.offers.columns if x not in general_columns]\n filterdict = self._assign_band(band_columns)\n\n for key in filterdict:\n\n all_cols = general_columns + filterdict[key].values()\n\n single = self.offers[all_cols].copy()\n # Assign identifiers\n single[\"Product Type\"] = key[0]\n single[\"Reserve Type\"] = key[1]\n single[\"Band Number\"] = key[2]\n\n single.rename(columns={v: k for k, v in filterdict[key].items()},\n inplace=True)\n\n yield single\n\n\n def _assign_band(self, band_columns):\n \"\"\" Figure out what type of columns they are from the bands\n Should return a list of lists of the form\n\n Product Type, Reserve Type, Band, Params*\n \"\"\"\n\n filtered = defaultdict(dict)\n for band in band_columns:\n split = band.split()\n\n band_number = int(split[0][4:])\n param = split[-1]\n reserve_type = self._reserve_type(band)\n product_type = self._product_type(band)\n\n filtered[(product_type, reserve_type, band_number)][param] = band\n\n return filtered\n\n def _reserve_type(self, band):\n return \"FIR\" if \"6S\" in band else \"SIR\" if \"60S\" in band else \"Energy\"\n\n def _product_type(self, band):\n return \"PLSR\" if (\n \"Plsr\" in band) else \"TWDSR\" if (\n \"Twdsr\" in band) else\"IL\" if (\n \"6S\" in band or \"60S\" in band) else \"Energy\"\n\n\n def _retitle_columns(self):\n self.offers.rename(columns={x: x.replace('_', ' ').title()\n for x in self.offers.columns}, inplace=True)\n\n\n def _map_location(self, user_map=None,\n left_on=\"Grid Exit Point\", right_on=\"Grid Exit Point\"):\n \"\"\"\n Map the location based upon the node.\n Useful when looking at regional instances\n \"\"\"\n\n if not user_map:\n user_map = pd.read_csv(CONFIG['map-location'])\n user_map = user_map[[\"Node\", \"Load Area\", \"Island Name\"]]\n user_map.rename(columns={\"Node\": \"Grid Exit Point\",\n \"Load Area\": \"Region\", \"Island Name\": \"Island\"}, inplace=True)\n\n self.offers = self.offers.merge(user_map, left_on=left_on, right_on=right_on)\n\n\n def _convert_dates(self, date_col=\"Trading Date\"):\n\n self.offers[date_col] = pd.to_datetime(self.offers[date_col])\n\n\n def _apply_datetime(self, date_col=\"Trading Date\",\n period_col=\"Trading Period\", datetime_col=\"Trading Datetime\"):\n\n self.offers[datetime_col] = self.offers[date_col] + self.offers[period_col].apply(self._period_minutes)\n\n\n def _period_minutes(self, period):\n return timedelta(minutes=int(period)*30 -15)\n\n def _sort_offers(self, datetime_col=\"Trading Datetime\"):\n self.offers.sort(columns=[datetime_col], inplace=True)\n\n\n\n\n\nclass ILOffer(Offer):\n \"\"\"\n ILOffer\n ===========\n\n Wrapper around an IL Offer dataframe which provides a number\n of useful functions in assessing the Energy Offers.\n Is created by passing a pandas DataFrame in the standard WITS\n template and then modificiations are made from there\n \"\"\"\n def __init__(self, offers):\n super(ILOffer, self).__init__(offers)\n\n\n def merge_stacked_offers(self, plsr_offer):\n\n if not type(self.offer_stack) == pd.core.frame.DataFrame:\n self.stack_columns()\n\n if not type(plsr_offer.offer_stack) == pd.core.frame.DataFrame:\n plsr_offer.stack_columns()\n\n return ReserveOffer(pd.concat([self.offer_stack,\n plsr_offer.offer_stack], ignore_index=True))\n\n\n\nclass PLSROffer(Offer):\n \"\"\"\n PLSROffer\n ===========\n\n Wrapper around an PLSR Offer dataframe which provides a number\n of useful functions in assessing the Energy Offers.\n Is created by passing a pandas DataFrame in the standard WITS\n template and then modificiations are made from there\n \"\"\"\n def __init__(self, offers):\n super(PLSROffer, self).__init__(offers)\n\n\n def merge_stacked_offers(self, il_offer):\n\n if not type(self.offer_stack) == pd.core.frame.DataFrame:\n self.stack_columns()\n\n if not type(il_offer.offer_stack) == pd.core.frame.DataFrame:\n il_offer.stack_columns()\n\n return ReserveOffer(pd.concat([self.offer_stack,\n il_offer.offer_stack], ignore_index=True))\n\n\n\nclass ReserveOffer(Offer):\n \"\"\"\n ReserveOffer\n ============\n\n Container for mixed PLSR, IL and TWDSR Offers.\n Created by using the merge offers method of either the ILOffer\n or PLSROffer classes.\n \"\"\"\n def __init__(self, offers):\n super(ReserveOffer, self).__init__(offers, run_operations=False)\n\n # Note, a raw Offer frame isn't passed, therefore manually add it\n # to the offer stack\n self.offer_stack = offers\n\n\nclass EnergyOffer(Offer):\n \"\"\"\n EnergyOffer\n ===========\n\n Wrapper around an Energy Offer dataframe which provides a number\n of useful functions in assessing the Energy Offers.\n Is created by passing a pandas DataFrame in the standard WITS\n template and then modificiations are made from there\n \"\"\"\n def __init__(self, offers):\n super(EnergyOffer, self).__init__(offers)\n\n\n","sub_path":"nzem/offers/offer_frames.py","file_name":"offer_frames.py","file_ext":"py","file_size_in_byte":9480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"137039069","text":"# -*- coding: utf-8 -*-\n\nimport pandas as pd\nfrom loguru import logger\n\n@logger.catch\ndef joins(df1):\n '''\n Parsing logs_join \n Params : raw dataframe\n Return : pandas data frame\n '''\n df1 = df1.drop(columns='data')\n df1 = df1.sort_values(by='date')\n\n s1 = df1.loc[df1.action == 'JOIN']\n s2 = df1.loc[df1.action == 'LEFT']\n s1.index = s1['date']\n s2.index = s2['date']\n s1 = s1.drop(columns='action')\n s2 = s2.drop(columns='action')\n\n df1 = pd.merge_asof(s1, s2, left_index=True, right_index=True, suffixes=(\"\", \"_left\"), by='initiator', direction='forward', allow_exact_matches=False)\n df1 = df1.reset_index(drop=True)\n return(df1)","sub_path":"parse/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"99730331","text":"try:\n import concurrent.futures as futures\nexcept ImportError:\n try:\n import futures\n except ImportError:\n futures = None\n\nimport zipfile\nimport shutil\nimport tempfile\nimport requests\n\nfrom os import path\n\n\n#--- Globals ----------------------------------------------\n# [tlib](https://github.com/vim-scripts/tlib):This library provides some utility functions.\n# [vim-addon-mw-utils](https://github.com/MarcWeber/vim-addon-mw-utils):interpret a file by function and cache file automatically.\n# [tabular](https://github.com/godlygeek/tabular): Aligning Text.\n# [ale](https://github.com/w0rp/ale): Syntax and lint checking for vim (async)\n# [vim-yankstack](https://github.com/maxbrunsfeld/vim-yankstack): Maintains a history of previous yanks, changes and deletes\n# [ack.vim](https://github.com/mileszs/ack.vim): Vim plugin for `the_silver_searcher` (ag) or ack -- a wicked fast grep\n# [ctrlp.vim](https://github.com/ctrlpvim/ctrlp.vim): Fuzzy file, buffer, mru and tag finder. It's mapped to ``\n# [NERD Tree](https://github.com/scrooloose/nerdtree): A tree explorer plugin for vim\n# [lightline.vim](https://github.com/itchyny/lightline.vim): A light and configurable statusline/tabline for Vim\n# [lightline-ale](https://github.com/maximbaz/lightline-ale) This plugin provides ALE indicator for the lightline vim plugin.\n# [vim-indent-object](https://github.com/michaeljsmith/vim-indent-object): Defines a new text object representing lines of code at the same indent level. Useful for python/vim scripts\n# [vim-surround](https://github.com/tpope/vim-surround): surround content quickly\n# [vim-expand-region](https://github.com/terryma/vim-expand-region): Allows you to visually select increasingly larger regions of text using the same key combination\n# [vim-multiple-cursors](https://github.com/terryma/vim-multiple-cursors): Sublime Text style multiple selections for Vim, CTRL+N is remapped to CTRL+S (due to YankRing)\n# [vim-fugitive](https://github.com/tpope/vim-fugitive): A Git wrapper so awesome, it should be illegal\n# [vim-repeat](https://github.com/tpope/vim-repeat):enable repeating supported plugin maps with \".\"\n# [vim-commentary](https://github.com/tpope/vim-commentary): Comment stuff out. Use `gcc` to comment out a line (takes a count), `gc` to comment out the target of a motion. `gcu` uncomments a set of adjacent commented lines.\n# [comfortable-motion](https://github.com/yuttie/comfortable-motion.vim). Brings physics-based smooth scrolling to the Vim world!\n# [vim-gitgutter](https://github.com/airblade/vim-gitgutter): A Vim plugin which shows a git diff in the gutter (sign column) and stages/undoes hunks.\n# [vim-markdown](https://github.com/tpope/vim-markdown):\n# [vim-markdown](https://github.com/plasticboy/vim-markdown):\n# [comfortable-motion.vim](https://github.com/yuttie/comfortable-motion.vim):smooth scrolling with C-d/C-u.\n# [pathogen.vim](https://github.com/tpope/vim-pathogen): Manage your vim runtimepath\n\nPLUGINS = \"\"\"\ntlib https://github.com/vim-scripts/tlib\nvim-addon-mw-utils https://github.com/MarcWeber/vim-addon-mw-utils\ntabular https://github.com/godlygeek/tabular\nale https://github.com/w0rp/ale\nvim-yankstack https://github.com/maxbrunsfeld/vim-yankstack\nack.vim https://github.com/mileszs/ack.vim\nctrlp.vim https://github.com/ctrlpvim/ctrlp.vim\nnerdtree https://github.com/scrooloose/nerdtree\nlightline.vim https://github.com/itchyny/lightline.vim\nlightline-ale https://github.com/maximbaz/lightline-ale\nvim-indent-object https://github.com/michaeljsmith/vim-indent-object\nvim-surround https://github.com/tpope/vim-surround\nvim-expand-region https://github.com/terryma/vim-expand-region\nvim-multiple-cursors https://github.com/terryma/vim-multiple-cursors\nvim-fugitive https://github.com/tpope/vim-fugitive\nvim-repeat https://github.com/tpope/vim-repeat\nvim-commentary https://github.com/tpope/vim-commentary\nvim-go https://github.com/fatih/vim-go\nvim-gitgutter https://github.com/airblade/vim-gitgutter\nvim-markdown https://github.com/tpope/vim-markdown\nvim-markdown https://github.com/plasticboy/vim-markdown\ncomfortable-motion.vim https://github.com/yuttie/comfortable-motion.vim\n\"\"\".strip()\n\nGITHUB_ZIP = '%s/archive/master.zip'\n\nSOURCE_DIR = path.join(path.dirname(__file__), 'sources_non_forked')\n\n\ndef download_extract_replace(plugin_name, zip_path, temp_dir, source_dir):\n temp_zip_path = path.join(temp_dir, plugin_name)\n\n # Download and extract file in temp dir\n req = requests.get(zip_path)\n open(temp_zip_path, 'wb').write(req.content)\n\n zip_f = zipfile.ZipFile(temp_zip_path)\n zip_f.extractall(temp_dir)\n\n plugin_temp_path = path.join(temp_dir,\n path.join(temp_dir, '%s-master' % plugin_name))\n\n # Remove the current plugin and replace it with the extracted\n plugin_dest_path = path.join(source_dir, plugin_name)\n\n try:\n shutil.rmtree(plugin_dest_path)\n except OSError:\n pass\n\n shutil.move(plugin_temp_path, plugin_dest_path)\n print('Updated {0}'.format(plugin_name))\n\n\ndef update(plugin):\n name, github_url = plugin.split(' ')\n zip_path = GITHUB_ZIP % github_url\n download_extract_replace(name, zip_path,\n temp_directory, SOURCE_DIR)\n\n\nif __name__ == '__main__':\n temp_directory = tempfile.mkdtemp()\n\n try:\n if futures:\n with futures.ThreadPoolExecutor(16) as executor:\n executor.map(update, PLUGINS.splitlines())\n else:\n [update(x) for x in PLUGINS.splitlines()]\n finally:\n shutil.rmtree(temp_directory)\n","sub_path":"update_plugins.py","file_name":"update_plugins.py","file_ext":"py","file_size_in_byte":5587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"414316835","text":"import re\nimport string\nimport pandas as pd\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\nfrom hw_4_header_nb_svm import *\n\n# commented lines can be useful for testing\n\nre_tok = re.compile(f'([{string.punctuation}“”¨«»®´·º½¾¿¡§£₤‘’])')\n\ndef tokenize(s):\n return re_tok.sub(r' \\1 ', s).split()\n\ntrain = pd.read_csv(TRAIN_FILE) [:NUM_SAMPLES_TRAIN]\ntest = pd.read_csv(TEST_X_FILE) [:NUM_SAMPLES_TEST]\ntest_y_all = pd.read_csv(TEST_Y_FILE) [:NUM_SAMPLES_TEST]\n\n# delete samples that don't play in test (they are marked with -1)\ntest_y = test_y_all[~(test_y_all.toxic == -1)]\ntest = test[~(test_y_all.toxic == -1)]\n\ntrain[COMMENT].fillna(\"unknown\", inplace=True)\ntest[COMMENT].fillna(\"unknown\", inplace=True)\n\nvec = TfidfVectorizer(ngram_range=(1,2),\n tokenizer=tokenize,\n min_df=3,\n max_df=0.9,\n analyzer=ANALYZER,\n strip_accents='unicode',\n use_idf=1,\n smooth_idf=1,\n sublinear_tf=1,\n max_features=MAX_FEATURES_WORD)\n\nX = vec.fit_transform(train[COMMENT])\ntest_X = vec.transform(test[COMMENT])\n","sub_path":"hw_4_preprocessing_nb_svm.py","file_name":"hw_4_preprocessing_nb_svm.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"533750946","text":"# Copyright 2020 Ram Rachum and collaborators.\n# This program is distributed under the MIT license.\n\nfrom typing import (Iterable, Union, Optional, Tuple, Any, Iterator, Type,\n Sequence, Callable, Hashable, Mapping, TypeVar)\nimport itertools\n\nfrom .utils import ImmutableDict\nfrom .base import State, PlayerId, SinglePlayerState\nfrom . import exceptions\nfrom . import strategizing\n\nclass Culture:\n def __init__(self, state_type: Type[State],\n player_id_to_strategy: Mapping[PlayerId, strategizing.Strategy]) -> None:\n self.State = state_type\n self.player_id_to_strategy = player_id_to_strategy\n\n\n def iterate_many_games(self, *, n: int = 10, max_length: int = 100,\n state_factory: Optional[Callable] = None, be_training: bool = True) \\\n -> Iterator[State]:\n state_factory = ((lambda: self.State.make_initial()) if state_factory is None\n else state_factory)\n for _ in range(n):\n state: State = state_factory()\n yield from self.iterate_game(state, max_length, be_training=be_training)\n\n\n def iterate_game(self, state: State, max_length: Optional[int] = None, *,\n be_training: bool = True) -> Iterator[State]:\n yield state\n iterator = range(1, max_length) if max_length is not None else itertools.count(1)\n for _ in iterator:\n if state.is_end:\n return\n state = self.get_next_state(state, be_training=be_training)\n yield state\n\n\n def get_next_state(self, state: State, *, be_training: bool = True) -> State:\n if state.is_end:\n raise exceptions.GameOver\n player_id_to_action = {\n player_id: self.player_id_to_strategy[player_id\n ].decide_action_for_observation(observation)\n for player_id, observation in state.player_id_to_observation.items()\n if not observation.is_end\n }\n next_state = state.get_next_state_from_actions(player_id_to_action)\n if be_training:\n for player_id, action in player_id_to_action.items():\n strategy = self.player_id_to_strategy[player_id]\n observation = state.player_id_to_observation[player_id]\n strategy.train(observation, action, next_state.player_id_to_observation[player_id])\n return next_state\n\n\nclass SinglePlayerCulture(Culture):\n\n def __init__(self, state_type: Type[SinglePlayerState], *,\n strategy: strategizing.Strategy) -> None:\n self.strategy = strategy\n Culture.__init__(self, state_type=state_type,\n player_id_to_strategy=ImmutableDict({None: strategy}))\n\n","sub_path":"grid_royale/gamey/culturing.py","file_name":"culturing.py","file_ext":"py","file_size_in_byte":2863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"352672082","text":"from random import shuffle\nfrom string import ascii_uppercase, maketrans, translate\n\nimport pygame as pg\n\nfrom .. import tools, prepare\nfrom ..components.labels import Label\n\n\nclass TitleScreen(tools._State):\n def __init__(self):\n super(TitleScreen, self).__init__()\n self.font = prepare.FONTS[\"Perfect DOS VGA 437 Win\"]\n self.next = \"MENU\"\n self.text = \"CRYPTOGRAMMER\"\n self.encrypt()\n self.letters = list(set((x for x in self.text)))\n shuffle(self.letters)\n self.timer = 0\n self.switch_span = 300\n self.make_labels()\n\n def encrypt(self):\n from_ = ascii_uppercase\n to_ = list(ascii_uppercase)\n shuffle(to_)\n to_ = \"\".join(to_)\n self.trans_table = maketrans(from_, to_)\n self.encrypted = translate(self.text, self.trans_table)\n\n def make_labels(self):\n top = 200\n left = 200\n self.labels = []\n style = {\"font_path\": self.font, \"font_size\": 64, \"text_color\": (25, 84, 25)}\n for char in self.encrypted:\n self.labels.append(Label(char, {\"topleft\": (left, top)}, **style))\n left += 50\n\n def choose_letter(self):\n try:\n letter = self.letters.pop()\n except IndexError:\n letter = None\n return letter\n\n def change_letter(self, indx, letter):\n to_replace = self.encrypted[indx]\n for i, label in enumerate(self.labels):\n if self.encrypted[i] == to_replace:\n label.set_text(letter)\n\n def switch_letter(self):\n if not self.letters:\n return\n letter = self.choose_letter()\n indx = self.text.index(letter)\n self.change_letter(indx, letter)\n\n def startup(self, persistent):\n self.persist = persistent\n\n def get_event(self,event):\n if event.type == pg.QUIT:\n self.quit = True\n elif event.type == pg.KEYUP:\n if event.key == pg.K_ESCAPE:\n self.quit = True\n else:\n self.done = True\n elif event.type == pg.MOUSEBUTTONUP:\n self.done = True\n\n def update(self, dt):\n self.timer += dt\n if self.timer >= self.switch_span:\n self.timer -= self.switch_span\n self.switch_letter()\n\n def draw(self, surface):\n surface.fill(pg.Color(\"black\"))\n for label in self.labels:\n label.draw(surface)\n","sub_path":"data/states/title_screen.py","file_name":"title_screen.py","file_ext":"py","file_size_in_byte":2442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"378438585","text":"from pyspark.sql import SparkSession\n\n# the source for this data pipeline is a kafka topic, defined below\nspark = SparkSession.builder.appName(\"balance-events\").getOrCreate()\nspark.sparkContext.setLogLevel('WARN')\n\ngearPositionRawStreamingDF = spark \\\n .readStream \\\n .format(\"kafka\") \\\n .option(\"kafka.bootstrap.servers\", \"localhost:9092\") \\\n .option(\"subscribe\",\"gear-position\") \\\n .option(\"startingOffsets\",\"earliest\")\\\n .load()\n\n#it is necessary for Kafka Data Frame to be readable, to cast each field from a binary to a string\ngearPositionStreamingDF = gearPositionRawStreamingDF.selectExpr(\"cast(key as string) truckId\", \"cast(value as string) gearPosition\")\n\n# this creates a temporary streaming view based on the streaming dataframe\n# it can later be queried with spark.sql, we will cover that in the next section\ngearPositionStreamingDF.createOrReplaceTempView(\"GearPosition\")\n\n\n# this selects the data from the temporary view\ngearPositionSelectStarDF = spark.sql(\"select * from GearPosition\")\n\n# this takes the stream and \"sinks\" it to kafka as it is updated one message at a time:\ngearPositionSelectStarDF.selectExpr(\"cast(truckId as string) as key\", \"cast(gearPosition as string) as value\") \\\n .writeStream \\\n .format(\"kafka\") \\\n .option(\"kafka.bootstrap.servers\", \"localhost:9092\")\\\n .option(\"topic\", \"gear-position-updates\")\\\n .option(\"checkpointLocation\",\"/tmp/kafkacheckpoint\")\\\n .start()\\\n .awaitTermination()\n","sub_path":"sparkstream/gearpos.py","file_name":"gearpos.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"437862696","text":"import scapy.all as scapy\nimport time\nimport sys\n\ndef get_mac(ip):\n #scapy.ls(scapy.ARP())\n arp_re = scapy.ARP(pdst = ip)\n #scapy.ls(scapy.Ether())\n broad = scapy.Ether(dst= \"ff:ff:ff:ff:ff:ff\")\n anwer = broad/arp_re\n cre_list = scapy.srp(anwer, timeout=1, verbose= False)[0]\n return cre_list[0][1].hwsrc\n\ndef spoof (target_ip, spoof_ip):\n mac = get_mac(target_ip)\n packet = scapy.ARP(op= 2, pdst= target_ip, hwdst=mac, psrc= spoof_ip)\n scapy.send(packet, verbose =False)\n\ndef restore (target_ip, spoof_ip):\n target_mac = get_mac(target_ip)\n dest_mac = get_mac(spoof_ip)\n\n packet = scapy.ARP(op= 2, pdst=target_ip, hwdst= target_ip, psrc= spoof_ip, hwsrc=dest_mac)\n scapy.send(packet, verbose = False)\n\n\ntarget_ip = \"192.168.106.128\"\ngateway = \"192.168.106.2\"\ntry:\n count = 0\n while True:\n spoof(target_ip, gateway)\n spoof(gateway, target_ip)\n count = count + 2\n print(\"\\r[+] so goi gui: \"+ str(count)),\n sys.stdout.flush()\n time.sleep(1)\nexcept KeyboardInterrupt:\n restore(target_ip, gateway)\n restore(gateway, target_ip)\n\n\n\n","sub_path":"tee.py","file_name":"tee.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"446949425","text":"import logging\nfrom collections import defaultdict\nfrom ecs_container_exporter.utils import create_metric, create_task_metrics, TASK_CONTAINER_NAME_TAG\n\nlog = logging.getLogger()\n\n\ndef calculate_io_metrics(stats, task_container_tags):\n \"\"\"\n Calculate IO metrics from the below data:\n\n \"blkio_stats\": {\n \"io_merged_recursive\": [],\n \"io_queue_recursive\": [],\n \"io_service_bytes_recursive\": [\n {\n \"major\": 259,\n \"minor\": 0,\n \"op\": \"Read\",\n \"value\": 10653696\n },\n {\n \"major\": 259,\n \"minor\": 0,\n \"op\": \"Write\",\n \"value\": 0\n },\n {\n \"major\": 259,\n \"minor\": 0,\n \"op\": \"Sync\",\n \"value\": 10653696\n },\n {\n \"major\": 259,\n \"minor\": 0,\n \"op\": \"Async\",\n \"value\": 0\n },\n {\n \"major\": 259,\n \"minor\": 0,\n \"op\": \"Total\",\n \"value\": 10653696\n }\n ],\n \"io_service_time_recursive\": [],\n \"io_serviced_recursive\": [\n {\n \"major\": 259,\n \"minor\": 0,\n \"op\": \"Read\",\n \"value\": 164\n },\n {\n \"major\": 259,\n \"minor\": 0,\n \"op\": \"Write\",\n \"value\": 0\n },\n {\n \"major\": 259,\n \"minor\": 0,\n \"op\": \"Sync\",\n \"value\": 164\n },\n {\n \"major\": 259,\n \"minor\": 0,\n \"op\": \"Async\",\n \"value\": 0\n },\n {\n \"major\": 259,\n \"minor\": 0,\n \"op\": \"Total\",\n \"value\": 164\n }\n ],\n \"io_time_recursive\": [],\n \"io_wait_time_recursive\": [],\n \"sectors_recursive\": []\n },\n \"\"\"\n metrics_by_container = {}\n # task level metrics\n task_metrics = defaultdict(int)\n # assume these will always be gauge\n metric_type = 'gauge'\n for container_id, container_stats in stats.items():\n metrics = []\n blkio_stats = container_stats.get('blkio_stats')\n\n iostats = {'io_service_bytes_recursive': 'bytes', 'io_serviced_recursive': 'iops'}\n for blk_key, blk_type in iostats.items():\n tags = task_container_tags[container_id]\n read_counter = write_counter = 0\n for blk_stat in blkio_stats.get(blk_key):\n if blk_stat['op'] == 'Read' and 'value' in blk_stat:\n read_counter += blk_stat['value']\n elif blk_stat['op'] == 'Write' and 'value' in blk_stat:\n write_counter += blk_stat['value']\n\n metrics.append(\n create_metric('disk_read_' + blk_type + '_total', read_counter, tags,\n metric_type, 'Total disk read ' + blk_type)\n )\n metrics.append(\n create_metric('disk_written_' + blk_type + '_total', write_counter, tags,\n metric_type, 'Total disk written ' + blk_type)\n )\n task_metrics['disk_read_' + blk_type + '_total'] += read_counter\n task_metrics['disk_written_' + blk_type + '_total'] += write_counter\n\n metrics_by_container[container_id] = metrics\n\n # task level metrics\n metrics_by_container[TASK_CONTAINER_NAME_TAG] = create_task_metrics(task_metrics, metric_type)\n\n return metrics_by_container\n","sub_path":"ecs_container_exporter/io_metrics.py","file_name":"io_metrics.py","file_ext":"py","file_size_in_byte":3724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"144883881","text":"\"\"\"baike URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.9/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url, include\nfrom django.contrib import admin\nfrom . import views\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n\turl(r'^registration/',include('registration.urls')),\n\turl(r'^accounts/', include('django.contrib.auth.urls')),\n\turl(r'^entry/',include('entry.urls')),\n url(r'^home/$', views.search, name = 'search'),\n url(r'^search/$', views.search, name = 'search'),\n url(r'^search_tag/$', views.search_tag, name = 'search_tag'),\n url(r'^search_onvoting/$', views.search_onvoting, name = 'search_onvoting'),\n url(r'^search_onvoting_tag/$', views.search_onvoting_tag, name = 'search_onvoting_tag'),\n]\n","sub_path":"project files/baike/baike/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"578881828","text":"from typing import List\n\nclass Solution:\n def findMinArrowShots(self, points: List[List[int]]) -> int:\n START = 0\n END = 1\n MIN_NUM = -2147483648\n\n sorted_points = sorted(points, key=lambda coords: coords[END])\n minimum_shots = 0\n last_shot_index = -2147483649\n\n for balloon in sorted_points:\n if last_shot_index < balloon[START]:\n minimum_shots += 1\n last_shot_index = balloon[END]\n # print('[', balloon[START], ',', balloon[END], ']', minimum_shots, last_shot_index)\n return minimum_shots\n\nclass Main:\n def exec(self):\n solution = Solution()\n inputs = self.exam()\n for points in inputs:\n answer = solution.findMinArrowShots(points)\n print(answer)\n\n def exam(self):\n return [\n [[10,16],[2,8],[1,6],[7,12]],\n [[1,2],[3,4],[5,6],[7,8]],\n [[1,2],[2,3],[3,4],[4,5]],\n [[1,2]],\n [[2,3],[2,3]],\n [[-2147483648,2147483647]]\n ]\n\nmain = Main()\nmain.exec()","sub_path":"leetcode/452.py","file_name":"452.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"51888992","text":"# -*-coding:Latin-1 -*\n\nfrom _operator import attrgetter\n\n\nclass Students:\n \"\"\"Class that Describe Students\"\"\"\n\n def __init__(self, name, age, avg):\n \"\"\"Constructor For the student and initialize all arguments\"\"\"\n self.name = name\n self.age = age\n self.avg = avg\n\n def __repr__(self):\n \"\"\"print information about students\"\"\"\n return \"\".format(self.name, self.age, self.avg)\n\n\nstudents = [\n Students(\"Clément\", 14, 16),\n Students(\"Charles\", 12, 15),\n Students(\"Oriane\", 14, 18),\n Students(\"Thomas\", 11, 12),\n Students(\"Damien\", 12, 15),\n]\n\nprint(sorted(students, key=attrgetter(\"age\", \"avg\", \"name\"), reverse=True))","sub_path":"POO/SortOject.py","file_name":"SortOject.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"342519371","text":"#!/usr/bin/python\n# coding=utf-8\n\ndef rst2html(src, part='whole', cfg={}):\n '''A RST HTML Generator, 返回 HTML 字符串.'''\n import locale\n locale.setlocale(locale.LC_ALL, '')\n from docutils.core import publish_parts\n\n from prettywriter import Writer\n\n args = {\n 'field_name_limit' : 80, \n }\n args.update(cfg)\n\n return publish_parts(src, writer=Writer(), settings_overrides=args)[part]\n","sub_path":"wonder/rst2html/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"564487235","text":"from .model_base import DataModel\n\n__all__ = ['QuadModel']\n\n\nclass QuadModel(DataModel):\n \"\"\"\n A data model for 4D image arrays.\n\n Parameters\n ----------\n init : any\n Any of the initializers supported by `~jwst.datamodels.DataModel`.\n\n data : numpy array\n The science data. 4-D.\n\n dq : numpy array\n The data quality array. 4-D.\n\n err : numpy array\n The error array. 4-D\n \"\"\"\n schema_url = \"quad.schema.yaml\"\n\n def __init__(self, init=None, **kwargs):\n super(QuadModel, self).__init__(init=init, **kwargs)\n\n # Implicitly create arrays\n self.dq = self.dq\n self.err = self.err\n","sub_path":"jwst/datamodels/quad.py","file_name":"quad.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"621668926","text":"from __future__ import with_statement\nimport pytest\n\nimport redis\nfrom redis.exceptions import ConnectionError\nfrom redis.client import StrictRedis\n\nfrom .conftest import skip_if_server_version_lt\n\nlong_suffix = \"r83waAS90OpwCKXcZpXy\"\nstreams = [\"S\" + str(stream) + \"_\" + long_suffix for stream in range(0, 5)]\nstreams_from_start_dict = dict([(s, 0) for s in streams[0:3]])\nfirst_3_streams_dict = dict([(s, 0) for s in streams])\n\nmessage_num = 20\n\n\n@pytest.fixture\ndef srs(sr):\n sr.delete(*streams)\n for x in range(0, message_num):\n sr.xadd(\"S0_\"+long_suffix, index=x)\n sr.xadd(\"S1_\"+long_suffix, index=1000 + x)\n sr.xadd(\"S2_\"+long_suffix, index=2000 + x)\n yield sr\n sr.delete(*streams)\n\n\ndef check_response_order(list_of_messages):\n last_timestamp = 0\n last_index = 0\n for msg in list_of_messages:\n timestamp = int(msg[1][0:13])\n index = int(msg[1][14:])\n assert(timestamp >= last_timestamp)\n if timestamp == last_timestamp:\n assert(index > last_index)\n last_index = index\n\n\nclass TestPubSubSubscribeUnsubscribe(object):\n\n @skip_if_server_version_lt('4.9.0')\n def test_all_stream_specifiers(self, srs):\n # Initializing without any streams should error\n with pytest.raises(redis.exceptions.RedisError):\n empty_streams = srs.streams()\n\n # Test that all messages from 0 to end are returned in order...\n # ...using keyword args\n messages_from_args = [msg for msg in srs.streams(block=0, stop_on_timeout=True, **first_3_streams_dict)]\n assert(len(messages_from_args) == message_num*3)\n check_response_order(messages_from_args)\n\n # ...using the streams keyword\n messages_from_streamdict = [msg for msg in srs.streams(streams=first_3_streams_dict, block=0,\n stop_on_timeout=True)]\n assert(len(messages_from_streamdict) == message_num*3)\n check_response_order(messages_from_streamdict)\n\n # ...using a really short count\n messages_short_limit = [msg for msg in srs.streams(streams=first_3_streams_dict, block=0, count=3,\n stop_on_timeout=True, )]\n assert(len(messages_short_limit) == message_num*3)\n check_response_order(messages_short_limit)\n\n # ...using a list (which will return an empty list as it is listening from now)\n messages_from_list = [msg for msg in srs.streams(streams=list(first_3_streams_dict.keys()), block=0,\n stop_on_timeout=True)]\n assert(messages_from_list == [])\n\n # ...using a set (which will also return an empty list as it is listening from now)\n messages_from_set = [msg for msg in srs.streams(streams=set(first_3_streams_dict.keys()), block=0,\n stop_on_timeout=True)]\n assert(messages_from_set == [])\n\n # Grab a message somewhere in the middle of the messages_from_args to get an intermediate timestamp\n middle_stream = messages_from_args[message_num-1][0]\n middle_index = messages_from_args[message_num-1][1]\n if isinstance(middle_index, bytes):\n middle_index = middle_index.decode()\n middle_ts, middle_subindex = middle_index.split(\"-\")\n\n # ...using an intermediate index\n messages_from_index = [msg for msg in srs.streams(streams={middle_stream: middle_index}, block=0,\n stop_on_timeout=True)]\n assert(len(messages_from_index) > 0)\n\n # ...using just the timestamp of the index, byte-encoded if python 3\n messages_from_timestamp = [msg for msg in srs.streams(streams={middle_stream.encode(): middle_ts.encode()},\n block=0, stop_on_timeout=True)]\n assert(len(messages_from_timestamp) > 0)\n\n @skip_if_server_version_lt('4.9.0')\n def test_stream_blocking(self, srs):\n\n # Load the list, but listen at the end with no blocking.\n stream_no_block = srs.streams(streams=streams, block=None)\n with pytest.raises(StopIteration):\n _ = stream_no_block.next()\n\n # Listen at the end with specified blocking (10 ms) and stop_on_timeout.\n stream_with_stop = srs.streams(streams=streams, block=10, stop_on_timeout=True)\n with pytest.raises(StopIteration):\n _ = stream_with_stop.next()\n\n # Listen at the end with specified blocking and no stop_on_timeout.\n stream_no_stop = srs.streams(streams=streams, block=10)\n msg = stream_no_stop.next()\n assert(msg is None)\n\n # Add another msg to stream_no_stop and return it\n srs.xadd(\"S3_\" + long_suffix, index=4000)\n msg = stream_no_stop.next()\n assert(isinstance(msg, tuple) and msg[0] == \"S3_\" + long_suffix)\n\n # Listen as above with specified timeout object.\n stream_timeout_resp = srs.streams(streams=streams, block=10, timeout_response=\"Arbitrary Response\")\n msg = stream_timeout_resp.next()\n assert(msg == \"Arbitrary Response\")\n\n @skip_if_server_version_lt('4.9.0')\n def test_connection_exceptions(self, srs):\n\n # Default: losing connection raises connection error\n strm_raise_conn_loss = srs.streams(streams=streams, block=10)\n srs.xadd(\"S3_\" + long_suffix, index=4000)\n _ = strm_raise_conn_loss.next()\n strm_raise_conn_loss.connection = StrictRedis(host=long_suffix)\n with pytest.raises(redis.exceptions.ConnectionError):\n _ = strm_raise_conn_loss.next()\n\n # returning connection error rather than raising it\n strm_ret_conn_loss = srs.streams(streams=streams, block=10, raise_connection_exceptions=False)\n srs.xadd(\"S3_\" + long_suffix, index=4000)\n _ = strm_ret_conn_loss.next()\n real_connection = strm_ret_conn_loss.connection\n\n # simulate lost connection\n strm_ret_conn_loss.connection = StrictRedis(host=long_suffix)\n msg = strm_ret_conn_loss.next()\n assert isinstance(msg, ConnectionError)\n\n # simulate restored connection\n strm_ret_conn_loss.connection = real_connection\n msg = strm_ret_conn_loss.next()\n assert msg is None\n","sub_path":"tests/test_streamiterator.py","file_name":"test_streamiterator.py","file_ext":"py","file_size_in_byte":6380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"145063457","text":"import numpy as np\nfrom sklearn import svm\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.externals import joblib\nimport json\n\n#用本地保存的模型进行测试,输出每个领域的概率,和概率最大的领域,\n\ndef pre_data():\n pre_content=open('D:\\\\Program Files\\\\JetBrains\\\\py_workspaces\\\\classification\\\\controller\\\\pre_test_data.txt',mode='r',encoding='utf-8')\n pre_line = ''\n pre_list = []\n for line in pre_content:\n pre_line += pre_content.readline()\n pre_list.append(pre_line)\n pre_list=np.array(pre_list)\n vectorizer_pre = TfidfVectorizer()\n vectorizer_pre.max_features=26\n pre_x = vectorizer_pre.fit_transform(pre_list.ravel())\n clf = joblib.load('D:\\\\Program Files\\\\JetBrains\\\\py_workspaces\\\\classification\\\\domain_classification\\\\train_module') # 模型本地回调\n # print(clf.predict(pre_x) ) #概率最大\n # print(clf.predict_proba(pre_x)) #概率\n # print(clf.predict_log_proba(pre_x)) #分类概率的对数\n\n proba = clf.predict_proba(pre_x).tolist() # 把numpy.ndarray转化为list再转化为str\n dir = {'baby': proba[0][9], 'car': proba[0][8], 'food': proba[0][7], 'health': proba[0][6], 'legend': proba[0][5],\n 'life': proba[0][4], 'love': proba[0][3], 'news': proba[0][2],\n 'science': proba[0][1], 'sexual': proba[0][0]}\n json_data = json.dumps(dir)\n return json_data\npre_data()\n","sub_path":"domain_classification/classify_dataPre.py","file_name":"classify_dataPre.py","file_ext":"py","file_size_in_byte":1452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"7568141","text":"#!/usr/bin/env python3\n\nimport argparse\nimport sys\n\nimport requests\n\nimport config\n\n\ndef main():\n\n conf_dict = {}\n\n # get config from arguments\n parser = argparse.ArgumentParser(description='Submit job to aCT server')\n parser.add_argument('--proxy', default=None,\n help='path to proxy file')\n parser.add_argument('--server', default=None,\n help='URL to aCT server')\n parser.add_argument('--port', default=None,\n help='port on aCT server')\n parser.add_argument('--cadir', default=None,\n help='path to directory with CA certificates')\n parser.add_argument('--conf', default=None,\n help='path to configuration file')\n parser.add_argument('--site', default='default',\n help='site that jobs should be submitted to')\n parser.add_argument('xRSL', help='path to job description file')\n args = parser.parse_args()\n\n conf_dict['proxy'] = args.proxy\n conf_dict['server'] = args.server\n conf_dict['port'] = args.port\n conf_dict['cadir'] = args.cadir\n\n config.parse_non_param_conf(conf_dict, args.conf)\n\n request_url = conf_dict['server'] + ':' + str(conf_dict['port']) + '/jobs'\n try:\n files = {'xrsl': open(args.xRSL, 'r')}\n except Exception as e:\n print('error opening xRSL file: {}'.format(str(e)))\n sys.exit(2)\n form = {'site': args.site}\n\n try:\n r = requests.post(request_url, files=files, data=form, cert=conf_dict['proxy'], verify=conf_dict['cadir'])\n except Exception as e:\n print('requests error: {}'.format(str(e)))\n sys.exit(5)\n\n if r.status_code == 200:\n print('{} - succesfully submited job with id {}'.format(r.status_code, r.text))\n else:\n print('{} - {}'.format(r.status_code, r.text))\n sys.exit(4)\n\n\n","sub_path":"src/act/client/aCT-client/src/actsub.py","file_name":"actsub.py","file_ext":"py","file_size_in_byte":1810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"443930304","text":"\nassert __name__ == \"__main__\"\n\nimport sys\n\nsaturation = 0.33\nblackv = 0.25\ncolorv = 1.00\nwhitev = 0.75\n\nxmult = 0.875\nymult = 0.75\nzmult = 1.0\n\ndef main () :\n\tassert len (sys.argv) == 2\n\tcolors = []\n\tcolors.extend (generate_hsv (saturation, blackv * xmult, colorv * xmult, whitev * xmult))\n\tcolors.extend (generate_hsv (saturation, blackv * zmult, colorv * ymult, whitev * ymult))\n\tcolors.extend (generate_hsv (saturation, blackv * ymult, colorv * zmult, whitev * zmult))\n\tcolors = convert_hsv_to_rgb (colors)\n\tcolors = convert_rgb_to_web (colors)\n\tcolor = sys.argv[1]\n\tif color[-2:] == \"-x\" :\n\t\trow = 0\n\telif color[-2:] == \"-y\" :\n\t\trow = 1\n\telif color[-2:] == \"-z\" :\n\t\trow = 2\n\telse :\n\t\tassert False\n\tcolor = {\n\t\t\t\"black\" : 0, \"red\" : 1, \"yellow\" : 2, \"green\" : 3, \"cyan\" : 4,\n\t\t\t\"blue\" : 5, \"magenta\" : 6, \"white\" : 7\n\t} [color[:-2]]\n\tcolor = int (color)\n\tcolor = colors[color + row * 8]\n\tsys.stdout.write (color)\n\n\ndef generate_hsv (saturation, black_value, color_value, white_value) :\n\tcolors = []\n\tcount = 6\n\tcolors.append ((0.0, 0.0, black_value))\n\tfor i in xrange (count) :\n\t\thue = 360.0 / count * i\n\t\tcolor = (hue, saturation, color_value)\n\t\tcolors.append (color)\n\tcolors.append ((0.0, 0.0, white_value))\n\treturn colors\n\n\ndef convert_hsv_to_rgb (inputs) :\n\toutputs = []\n\tfor h, s, v in inputs :\n\t\ti = int (h / 60) % 6\n\t\tf = h / 60 - int (h / 60)\n\t\tp = v * (1 - s)\n\t\tq = v * (1 - f * s)\n\t\tt = v * (1 - ((1 - f) * s))\n\t\tif i == 0 :\n\t\t\toutput = (v, t, p)\n\t\telif i == 1 :\n\t\t\toutput = (q, v, p)\n\t\telif i == 2 :\n\t\t\toutput = (p, v, t)\n\t\telif i == 3 :\n\t\t\toutput = (p, q, v)\n\t\telif i == 4 :\n\t\t\toutput = (t, p, v)\n\t\telif i == 5 :\n\t\t\toutput = (v, p, q)\n\t\toutputs.append (output)\n\treturn outputs\n\n\ndef convert_rgb_to_web (inputs) :\n\toutputs = []\n\tfor red, green, blue in inputs :\n\t\tred = int (red * 255)\n\t\tgreen = int (green * 255)\n\t\tblue = int (blue * 255)\n\t\toutput = '#%02x%02x%02x' % (red, green, blue)\n\t\toutputs.append (output)\n\treturn outputs\n\n\nmain ()\n","sub_path":"dia-shapes/mosaic-old/shapes/colors.py","file_name":"colors.py","file_ext":"py","file_size_in_byte":1955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"195563851","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\npages = ['',1,2,3,4,5,6]\r\nfor page in pages:\r\n response = requests.get('http://www.tesoro.es/en/deuda-publica/subastas/resultados-subastas-anteriores?type=bonos_del_estado&page='+str(page)).content\r\n print(response)\r\n div = BeautifulSoup(response).find('div', attrs={'class':'item-list'})\r\n if div is not None:\r\n\r\n for li in div.find_all('li'):\r\n print(li.find('a')['href'])\r\n resp = requests.get('http://www.tesoro.es'+li.find('a')['href']).content\r\n h2 = BeautifulSoup(resp).find('h2', attrs={'class':'pane-title'})\r\n print(h2.text)\r\n table = BeautifulSoup(resp).find('table')\r\n print(table)","sub_path":"scripts/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"447305706","text":"#单继承实例\n\nclass Point():\n\tx = 0.0\n\ty = 0.0\n\n\tdef __init__(self,x,y):\n\t\tself.x = x\n\t\tself.y = y\n\t\tprint(\"Point constructor\")\n\n\tdef Tostring(self):\n\t\treturn \"{X:\"+str(self.x)+\",Y:\"+str(self.y)+\"}\"\n\nclass Circle(Point):\n\tradius = 0.0\n\n\tdef __init__(self,x,y,radius):\n\t\tsuper.__init__(x,y)\n\t\tself.radius = radius\n\t\tprint(\"Circle constructor\")\n\n\tdef Tostring(self):\n\t\treturn super().Tostring()+\\\n\t\t\",{RADIUS=\"+str(self.radius)+\"}\"\n\n\np = Point(20,20)\n\nprint(p.Tostring())\n\nc = Circle(100,100,50)\nprint(c.Tostring())\n\n\n# Point constructor\n# {X:20,Y:20}\n# Point constructor\n# Circle constructor\n# {X:100,Y:100},{RADIUS=50}\n","sub_path":"python/algorithm/chapter_01/single_inherit.py","file_name":"single_inherit.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"307810745","text":"\n\nfrom xai.brain.wordbase.nouns._firefighter import _FIREFIGHTER\n\n#calss header\nclass _FIREFIGHTERS(_FIREFIGHTER, ):\n\tdef __init__(self,): \n\t\t_FIREFIGHTER.__init__(self)\n\t\tself.name = \"FIREFIGHTERS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"firefighter\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_firefighters.py","file_name":"_firefighters.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"367690665","text":"import collections\nimport numpy as np\nimport os\nimport json\n\nfrom home_platform.semantic import SuncgSemantics\n\nTEST_SUNCG_DATA_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"..\", \"tests\", \"data\", \"suncg\")\n\n\ndef get_instances_from_frames(images, scene, segmentation_renderer):\n instance_color_mapping = collections.OrderedDict(segmentation_renderer.instance_color_mapping)\n all_instances = instance_color_mapping.keys()\n all_colors = np.stack(instance_color_mapping.values())\n eps = 1e-2\n instances_found = set([])\n\n for image in images:\n unique_colors = np.unique(image.reshape((-1, image.shape[-1])), axis=0)\n for color in unique_colors:\n z = np.sum(np.abs(all_colors - color[:3]), axis=1)\n x = np.min(z)\n if x < eps:\n item_idx = np.argmin(z)\n # if (color[:3]==np.array(MODEL_CATEGORY_COLOR_MAPPING[item])).all():\n instance_id = all_instances[item_idx]\n if instance_id not in instances_found:\n instances_found.add(instance_id)\n\n return instances_found\n\n\ndef get_object_properties(obj):\n \"\"\"\n Sets category, color and material properties of an object\n \"\"\"\n\n properties = {}\n semanticsNp = obj.find('**/semantics')\n if not semanticsNp.isEmpty():\n properties['size'] = semanticsNp.getTag('overall-size')\n if properties['size'] == 'normal':\n properties['size'] = 'small'\n properties['shape'] = semanticsNp.getTag('coarse-category')\n properties['color'] = semanticsNp.getTag('basic-colors').split(',')[0]\n properties['material'] = semanticsNp.getTag('materials')\n\n return properties\n\n\ndef compute_all_relationships(objects):\n directions = ['right', 'left', 'front', 'behind']\n all_relationships = {x: [] for x in directions}\n\n for i, obj1 in enumerate(objects):\n related_objects = {x: [] for x in directions}\n for j, obj2 in enumerate(objects):\n if obj1 == obj2:\n continue\n diff = [obj1.getPos()[k] - obj2.getPos()[k] for k in [0, 1]]\n if diff[0] > 0:\n related_objects['right'].append(j)\n else:\n related_objects['left'].append(j)\n\n if diff[1] > 0:\n related_objects['front'].append(j)\n else:\n related_objects['behind'].append(j)\n\n for d in directions:\n all_relationships[d].append(related_objects[d])\n\n return all_relationships\n\n\ndef generate_metadata_from_instances(scene, instances_found):\n \"\"\"\n Generates a JSON file that contains a list of objects, and directional relationships b/w each pair of objects\n :param house_id:\n :return:\n \"\"\"\n keys = ['shape', 'size', 'color', 'material']\n\n metadata = {\n 'info': {'split': 'train'},\n 'scenes': [\n {\n \"split\": \"train\",\n \"image_index\": 0,\n \"image_filename\": \"SUNCG_env_000000.png\",\n \"objects\": [],\n \"relationships\": {}\n }\n ]\n }\n\n semantic_world = SuncgSemantics(scene, TEST_SUNCG_DATA_DIR)\n objects_seen = []\n for idx, obj in enumerate(scene.getAllObjects()):\n instance_id = obj.getTag('instance-id')\n model_id = obj.getTag('instance-id')\n\n # Ignore cellings, floors and walls\n if instance_id in instances_found:\n props = get_object_properties(obj)\n if not props:\n continue\n objects_seen.append(obj)\n metadata['scenes'][0]['objects'].append({k: v for k, v in props.iteritems() if k in keys})\n\n metadata['scenes'][0]['relationships'] = compute_all_relationships(objects_seen)\n return metadata\n\n\ndef create_metadata_from_frames(images, scene, segmentation_renderer):\n instances_found = get_instances_from_frames(images, scene, segmentation_renderer)\n metadata = generate_metadata_from_instances(scene, instances_found)\n with open('metadata.json', 'wb') as fp:\n json.dump(metadata, fp)","sub_path":"question_gen/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"433105853","text":"import os\nimport numpy as np\nfrom matplotlib.pyplot import *\n\nos.chdir('/Users/mehdifatemi/Dropbox/Python/local/Data/Total')\n\nt1, mean_MC_info_gap1, selected_actions1 = np.load('ER10.npy')\nt2, mean_MC_info_gap2, selected_actions2 = np.load('ER30.npy')\nt3, mean_MC_info_gap3, selected_actions3 = np.load('ER75.npy')\n\nt4, mean_MC_info_gap4, selected_actions4 = np.load('BA10.npy')\nt5, mean_MC_info_gap5, selected_actions5 = np.load('BA30.npy')\nt6, mean_MC_info_gap6, selected_actions6 = np.load('BA75.npy')\n\n\nf = figure(figsize=(12, 8))\nsubplots_adjust(hspace=0.1)\n\n## ER\n\nax1 = subplot(325)\nplot(t1[1:], mean_MC_info_gap1[1:], '-o', linewidth = 2 \\\n , ms=7, lw=2, alpha=0.7, mfc='orange')\nax1.xaxis.grid(True, linestyle='-', which='major', color='lightgrey')\nxlabel('Time (sec)')\nylabel('10')\n\nax2 = subplot(323)\nplot(t1[1:], mean_MC_info_gap2[1:], '-o', linewidth = 2 \\\n , ms=7, lw=2, alpha=0.7, mfc='orange')\nsetp(ax2.get_xticklabels(), visible=False)\nax2.xaxis.grid(True, linestyle='-', which='major', color='lightgrey')\nylabel('30')\n\nax3 = subplot(321)\nplot(t1[1:], mean_MC_info_gap3[1:], '-o', linewidth = 2 \\\n , ms=7, lw=2, alpha=0.7, mfc='orange')\nsetp(ax3.get_xticklabels(), visible=False)\nax3.xaxis.grid(True, linestyle='-', which='major', color='lightgrey')\nylabel('75')\n\n\n## BA\n\nax4 = subplot(322)\nplot(t1[1:], mean_MC_info_gap6[1:], '-o', linewidth = 2 \\\n , ms=7, lw=2, alpha=0.7, mfc='orange')\nsetp(ax4.get_xticklabels(), visible=False)\nax4.xaxis.grid(True, linestyle='-', which='major', color='lightgrey')\nylabel('75')\n\nax5 = subplot(324)\nplot(t1[1:], mean_MC_info_gap5[1:], '-o', linewidth = 2 \\\n , ms=7, lw=2, alpha=0.7, mfc='orange')\nsetp(ax5.get_xticklabels(), visible=False)\nax5.xaxis.grid(True, linestyle='-', which='major', color='lightgrey')\nylim(0,350)\nylabel('30')\n\nax6 = subplot(326)\nplot(t1[1:], mean_MC_info_gap4[1:], '-o', linewidth = 2 \\\n , ms=7, lw=2, alpha=0.7, mfc='orange')\nax6.xaxis.grid(True, linestyle='-', which='major', color='lightgrey')\nxlabel('Time (sec)')\nylabel('10')\n\n\n\n########################\n## vertical label ##\n########################\nax = f.add_axes( [0., 0., 1, 1] )\nax.set_axis_off()\nax.set_xlim(0, 1)\nax.set_ylim(0, 1)\nax.text( \n .04, 0.5, \"Entropic State\", rotation='vertical',\n horizontalalignment='center', verticalalignment='center'\n)\n\nshow() \n","sub_path":"Data/Total/file_reader.py","file_name":"file_reader.py","file_ext":"py","file_size_in_byte":2335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"507508584","text":"import mock\nfrom cliquet.events import AfterResourceChanged\nfrom kinto.tests.support import unittest, BaseWebTest\nfrom kinto_emailer import get_message, get_collection_record, send_notification\n\nCOLLECTION_RECORD = {\n 'kinto-emailer': {\n 'record.update': {\n 'sender': 'kinto@restmail.net',\n 'subject': 'Configured subject',\n 'template': 'Bonjour les amis.',\n 'recipients': ['kinto-emailer@restmail.net'],\n }\n }\n}\n\n\nclass PluginSetupTest(BaseWebTest, unittest.TestCase):\n def __init__(self, *args, **kwargs):\n super(PluginSetupTest, self).__init__(*args, **kwargs)\n self.app = self._get_test_app({\n 'includes': ['kinto.plugins.default_bucket', 'kinto_emailer'],\n 'emailer.sender': 'kinto.email@restmail.net',\n })\n\n def test_capability_is_exposed(self):\n resp = self.app.get('/')\n capabilities = resp.json['capabilities']\n self.assertIn('emailer', capabilities)\n expected = {\n \"description\": \"Provide emailing capabilities to the server.\",\n \"url\": \"https://github.com/Kinto/kinto-emailer/\",\n }\n self.assertEqual(expected, capabilities['emailer'])\n\n def test_get_message_returns_a_configured_message(self):\n message = get_message(COLLECTION_RECORD,\n {'resource_name': 'record',\n 'action': 'update'})\n\n assert message.subject == 'Configured subject'\n assert message.sender == 'kinto@restmail.net'\n assert message.recipients == ['kinto-emailer@restmail.net']\n assert message.body == 'Bonjour les amis.'\n\n def test_get_emailer_info_return_none_if_emailer_not_configured(self):\n message = get_message({}, {'resource_name': 'record',\n 'action': 'update'})\n assert message is None\n\n def test_get_message_returns_default_subject_to_new_message(self):\n collection_record = {\n 'kinto-emailer': {\n 'record.update': {\n 'sender': 'kinto@restmail.net',\n 'template': 'Bonjour les amis.',\n 'recipients': ['kinto-emailer@restmail.net'],\n }\n }\n }\n\n message = get_message(collection_record,\n {'resource_name': 'record',\n 'action': 'update'})\n\n assert message.subject == 'New message'\n\n def test_get_collection_record(self):\n storage = mock.MagicMock()\n\n get_collection_record(\n storage,\n bucket_id=\"default\",\n collection_id=\"foobar\")\n\n storage.get.assert_called_with(\n collection_id='collection',\n parent_id='/buckets/default',\n object_id='foobar')\n\n def test_send_notification_is_called_on_new_record(self):\n with mock.patch('kinto_emailer.send_notification') as mocked:\n app = self._get_test_app({\n 'includes': ['kinto.plugins.default_bucket', 'kinto_emailer'],\n 'emailer.sender': 'kinto.email@restmail.net',\n })\n app.post_json('/buckets/default/collections/foobar/records',\n headers={'Authorization': 'Basic bmF0aW06'})\n event = mocked.call_args[0][0]\n assert isinstance(event, AfterResourceChanged)\n\n def test_send_notification_ignore_non_record_events(self):\n event = mock.MagicMock()\n event.payload = {'resource_name': 'collection'}\n\n with mock.patch('kinto_emailer.get_collection_record') as mocked:\n send_notification(event)\n assert not mocked.called\n\n def test_send_notification_does_not_call_the_mailer_if_no_message(self):\n event = mock.MagicMock()\n event.payload = {\n 'resource_name': 'record',\n 'action': 'update',\n 'bucket_id': 'default',\n 'collection_id': 'foobar'\n }\n\n with mock.patch(\n 'kinto_emailer.get_collection_record',\n return_value=COLLECTION_RECORD) as get_collection_record:\n with mock.patch('kinto_emailer.get_mailer') as get_mailer:\n send_notification(event)\n assert get_collection_record.called\n assert get_mailer().send.called\n","sub_path":"kinto_emailer/tests/test_includeme.py","file_name":"test_includeme.py","file_ext":"py","file_size_in_byte":4377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"108137780","text":"from mediacloud.test.basetest import ApiBaseTest\nfrom mediacloud.test import QUERY_LAST_WEEK, QUERY_ENGLISH_LANGUAGE\n\n\nclass ApiWordCountTest(ApiBaseTest):\n\n QUERY = 'robots'\n\n def testSort(self):\n term_freq = self._mc.wordCount('*', QUERY_LAST_WEEK)\n last_count = None\n for word in term_freq:\n if last_count is not None:\n self.assertLessEqual(word['count'], last_count)\n last_count = word['count']\n\n def testNumWords(self):\n term_freq = self._mc.wordCount('*', QUERY_LAST_WEEK)\n self.assertEqual(len(term_freq), 500)\n term_freq = self._mc.wordCount('*', QUERY_LAST_WEEK, num_words=101)\n self.assertEqual(len(term_freq), 101)\n\n def testStopWords(self):\n term_freq = self._mc.wordCount('*', QUERY_LAST_WEEK)\n term_freq_with_stopwords = self._mc.wordCount('*', QUERY_LAST_WEEK, include_stopwords=True)\n self.assertNotEqual(term_freq[0]['term'], term_freq_with_stopwords[0]['term'])\n\n def testStats(self):\n term_freq = self._mc.wordCount('*', QUERY_LAST_WEEK, include_stats=True)\n self.assertTrue('stats' in term_freq.keys())\n self.assertTrue('words' in term_freq.keys())\n\n def testBigram(self):\n term_freq = self._mc.wordCount(QUERY_ENGLISH_LANGUAGE, QUERY_LAST_WEEK, ngram_size=2)\n for term in term_freq:\n self.assertEqual(len(term['term'].split(' ')), 2,\n u\"Uh oh - '{}' doesn't seem like a bigram! ({})\".format(term['term'], term['stem']))\n\n def testRandomSeed(self):\n term_freq = self._mc.wordCount('*', QUERY_LAST_WEEK)\n random_term_freq = self._mc.wordCount('*', QUERY_LAST_WEEK, random_seed=20)\n self.assertEqual(len(term_freq), len(random_term_freq))\n\n def testWordCountPost(self):\n results = self._mc.wordCount(\"robot\", QUERY_LAST_WEEK, http_method='POST')\n self.assertGreater(len(results), 0)\n","sub_path":"mediacloud/test/api_word_count_test.py","file_name":"api_word_count_test.py","file_ext":"py","file_size_in_byte":1941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"541889508","text":"# Copyright 2017-2019 TensorHub, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Utility module for TensorFlow events.\n\nIt's safe to import this module even when TensorFlow isn't installed\nas all required external modules are lazily loaded.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\n\nimport glob\nimport hashlib\nimport logging\nimport os\n\nlog = logging.getLogger(\"guild\")\n\nclass ScalarReader(object):\n\n def __init__(self, dir):\n self.dir = dir\n\n def __iter__(self):\n \"\"\"Yields (tag, val, step) for scalars.\n \"\"\"\n try:\n from tensorboard.backend.event_processing import event_accumulator\n except ImportError:\n pass\n else:\n events = event_accumulator._GeneratorFromPath(self.dir).Load()\n for event in events:\n if not event.HasField(\"summary\"):\n continue\n for val in event.summary.value:\n if not val.HasField(\"simple_value\"):\n continue\n yield val.tag, val.simple_value, event.step\n\ndef iter_events(root_path):\n \"\"\"Returns an iterator that yields (dir, digest, reader) tuples.\n\n For each yielded events dir, `digest` changes whenever events have\n been written to the dir.\n\n `reader` is an instance of ScalarReader that can be used to read\n scalars in dir.\n \"\"\"\n ensure_tf_logging_patched()\n try:\n from tensorboard.backend.event_processing import io_wrapper\n except ImportError:\n pass\n else:\n for subdir_path in io_wrapper.GetLogdirSubdirectories(root_path):\n if _linked_resource_path(subdir_path, root_path):\n log.debug(\"skipping linked resource path %s\", subdir_path)\n continue\n digest = _event_files_digest(subdir_path)\n yield subdir_path, digest, ScalarReader(subdir_path)\n\ndef _linked_resource_path(path, root):\n \"\"\"Returns True if path is a linked resource under root.\n\n This is used to exclude tfevents under root that are linked\n resources.\n \"\"\"\n if _has_steps(root):\n return _links_under_root(path, root) > 1\n else:\n return not _real_path_under_root(path, root)\n\ndef _has_steps(path):\n return os.path.exists(os.path.join(path, \".guild\", \"attrs\", \"steps\"))\n\ndef _links_under_root(path, root):\n \"\"\"Returns the number of links to path uses user root.\"\"\"\n links = 0\n last_path = None\n while path != root and path != last_path:\n if os.path.islink(path):\n links += 1\n last_path = path\n path = os.path.dirname(path)\n return links\n\ndef _real_path_under_root(path, root):\n \"\"\"Returns True if real path is under root.\"\"\"\n real_path = os.path.realpath(path)\n real_root = os.path.realpath(root)\n return real_path.startswith(real_root)\n\ndef _event_files_digest(dir):\n \"\"\"Returns a digest for dir that changes when events change.\n\n The digest includes the list of event logs and their associated\n sizes.\n \"\"\"\n event_files = sorted(glob.glob(os.path.join(dir, \"*.tfevents.*\")))\n to_hash = \"\\n\".join([\n \"{}\\n{}\".format(filename, os.path.getsize(filename))\n for filename in event_files\n if os.path.isfile(filename)])\n return hashlib.md5(to_hash.encode(\"utf-8\")).hexdigest()\n\ndef ensure_tf_logging_patched():\n _ensure_tf_oldstyle_logging_patched()\n _ensure_tf_newstyle_logging_patched()\n\ndef _ensure_tf_oldstyle_logging_patched():\n try:\n from tensorflow import logging\n except ImportError:\n pass\n else:\n logging.info = logging.debug = lambda *_arg, **_kw: None\n\ndef _ensure_tf_newstyle_logging_patched():\n try:\n from tensorboard.util import tb_logging\n except ImportError:\n pass\n else:\n logger = tb_logging.get_logger()\n logger.info = logger.debug = lambda *_arg, **_kw: None\n","sub_path":"guild/tfevent.py","file_name":"tfevent.py","file_ext":"py","file_size_in_byte":4421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"398156967","text":"#!/bin/python3\r\n\r\nimport math\r\nimport os\r\nimport random\r\nimport re\r\nimport sys\r\n\r\n# Complete the breakingRecords function below.\r\ndef breaking_records(score):\r\n min = max = score[0]\r\n min_count = max_count = 0\r\n for i in score[1:]:\r\n if i > max:\r\n max_count += 1\r\n max = i\r\n if i < min:\r\n min_count += 1\r\n min = i\r\n return max_count, min_count\r\n\r\n\r\nn = int(input())\r\nscore = list(map(int, input().split()))\r\nprint(*breaking_records(score))","sub_path":"Algorithms/Breaking_the_records/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"408416942","text":"import xbmc\nimport datetime\n\nclass HueMonitor(xbmc.Monitor):\n\n def __init__(self, *args, **kwargs):\n xbmc.Monitor.__init__(self)\n\n\n def onSettingsChanged(self):\n logger.debuglog('running in mode {!s}'.format(hue.settings.mode))\n last = datetime.datetime.now()\n hue.settings.readxml()\n hue.update_settings()\n","sub_path":"resources/lib/HueMonitor.py","file_name":"HueMonitor.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"486130152","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Oct 27 16:25:41 2018\n\n@author: Lxiao217\n\"\"\"\nimport os, shutil\noriginal_dataset_dir = 'F:\\\\python\\\\DeepLearning\\\\train'\nbase_dir = 'F:\\\\python\\\\DeepLearning\\\\cats_and_dogs_small'\nif not os.path.exists(base_dir):\n os.mkdir(base_dir)\n\ntrain_dir = os.path.join(base_dir, 'train')\nif not os.path.exists(train_dir):\n os.mkdir(train_dir)\n\ntest_dir = os.path.join(base_dir, 'test')\nif not os.path.exists(test_dir):\n os.mkdir(test_dir)\n\nvalidation_dir = os.path.join(base_dir, 'validation')\nif not os.path.exists(validation_dir):\n os.mkdir(validation_dir)\n\ntrain_cats_dir = os.path.join(train_dir, 'cats')\nif not os.path.exists(train_cats_dir):\n os.mkdir(train_cats_dir)\n\ntrain_dogs_dir = os.path.join(train_dir, 'dogs')\nif not os.path.exists(train_dogs_dir):\n os.mkdir(train_dogs_dir)\n\nvalidation_cats_dir = os.path.join(validation_dir, 'cats')\nif not os.path.exists(validation_cats_dir):\n os.mkdir(validation_cats_dir)\n\nvalidation_dogs_dir = os.path.join(validation_dir, 'dogs')\nif not os.path.exists(validation_dogs_dir):\n os.mkdir(validation_dogs_dir)\n\ntest_cats_dir = os.path.join(test_dir, 'cats')\nif not os.path.exists(test_cats_dir):\n os.mkdir(test_cats_dir)\n\ntest_dogs_dir = os.path.join(test_dir, 'dogs')\nif not os.path.exists(test_dogs_dir):\n os.mkdir(test_dogs_dir)\n\n#将前1000张猫的图片复制到train_cats_dir中\nfnames = ['cat.{}.jpg'.format(i) for i in range (1000)]\nfor fname in fnames:\n src = os.path.join(original_dataset_dir, fname)\n if not os.path.exists(src):\n nameList = fname.split('.')\n picindex = int(nameList[1])\n newindex = picindex + 6666\n newName = nameList[0] + '.' + str(newindex) + '.' + nameList[2]\n src = os.path.join(original_dataset_dir, newName)\n dst = os.path.join(train_cats_dir, fname)\n shutil.copyfile(src, dst)\n#500张验证猫\nfnames = ['cat.{}.jpg'.format(i) for i in range(1000, 1500)]\nfor fname in fnames:\n src = os.path.join(original_dataset_dir, fname)\n if not os.path.exists(src):\n nameList = fname.split('.')\n picindex = int(nameList[1])\n newindex = picindex + 6666 #用的原始index+6666的图片\n newName = nameList[0] + '.' + str(newindex) + '.' + nameList[2]\n src = os.path.join(original_dataset_dir, newName)\n dst = os.path.join(validation_cats_dir, fname)\n shutil.copyfile(src, dst)\n#500张测试猫\nfnames = ['cat.{}.jpg'.format(i) for i in range(1500, 2000)]\nfor fname in fnames:\n src = os.path.join(original_dataset_dir, fname)\n if not os.path.exists(src):\n nameList = fname.split('.')\n picindex = int(nameList[1])\n newindex = picindex + 6666\n newName = nameList[0] + '.' + str(newindex) + '.' + nameList[2]\n src = os.path.join(original_dataset_dir, newName)\n dst = os.path.join(test_cats_dir, fname)\n shutil.copyfile(src, dst)\n\n#1000张训练狗\nfnames = ['dog.{}.jpg'.format(i) for i in range(1000)]\nfor fname in fnames:\n src = os.path.join(original_dataset_dir, fname)\n if not os.path.exists(src):\n nameList = fname.split('.')\n picindex = int(nameList[1])\n newindex = picindex + 6666\n newName = nameList[0] + '.' + str(newindex) + '.' + nameList[2]\n src = os.path.join(original_dataset_dir, newName)\n dst = os.path.join(train_dogs_dir, fname)\n shutil.copyfile(src, dst)\n\n#500张验证狗\nfnames = ['dog.{}.jpg'.format(i) for i in range(1000, 1500)]\nfor fname in fnames:\n src = os.path.join(original_dataset_dir, fname)\n if not os.path.exists(src):\n nameList = fname.split('.')\n picindex = int(nameList[1])\n newindex = picindex + 6666\n newName = nameList[0] + '.' + str(newindex) + '.' + nameList[2]\n src = os.path.join(original_dataset_dir, newName)\n dst = os.path.join(validation_dogs_dir, fname)\n shutil.copyfile(src, dst)\n\n#500张测试狗\nfnames = ['dog.{}.jpg'.format(i) for i in range(1500, 2000)]\nfor fname in fnames:\n src = os.path.join(original_dataset_dir, fname)\n if not os.path.exists(src):\n nameList = fname.split('.')\n picindex = int(nameList[1])\n newindex = picindex + 6666\n newName = nameList[0] + '.' + str(newindex) + '.' + nameList[2]\n src = os.path.join(original_dataset_dir, newName)\n dst = os.path.join(test_dogs_dir, fname)\n shutil.copyfile(src, dst)\n\nfrom keras import models\nfrom keras import layers\n\nmodel = models.Sequential()\nmodel.add(layers.Conv2D(32, (3,3), activation = 'relu', input_shape = (150, 150, 3)))\nmodel.add(layers.MaxPooling2D((2,2)))\n\nmodel.add(layers.Conv2D(64, (3,3), activation = 'relu'))\nmodel.add(layers.MaxPooling2D((2,2)))\n\nmodel.add(layers.Conv2D(128, (3,3), activation = 'relu'))\nmodel.add(layers.MaxPooling2D((2,2)))\n\nmodel.add(layers.Conv2D(128, (3,3), activation = 'relu'))\nmodel.add(layers.MaxPooling2D((2,2)))\n\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(512, activation = 'relu'))\nmodel.add(layers.Dense(1, activation = 'sigmoid'))\n\nfrom keras import optimizers\nmodel.compile(loss = 'binary_crossentropy',\n optimizer = optimizers.RMSprop(lr = 0.001),\n metrics = ['acc'])\n\nfrom keras.preprocessing.image import ImageDataGenerator\ntrain_datagen = ImageDataGenerator(rescale = 1./255)\ntest_datagen = ImageDataGenerator(rescale = 1./255)\ntrain_generator = train_datagen.flow_from_directory(\n train_dir,\n target_size = (150,150),\n batch_size = 20,\n class_mode = 'binary') #因为使用了binary_crossentropy损失,所以需要用二进制标签\n\nvalidation_generator = test_datagen.flow_from_directory(\n validation_dir,\n target_size = (150,150),\n batch_size = 20,\n class_mode = 'binary')\n\nhistory = model.fit_generator(\n train_generator,\n steps_per_epoch = 100,\n epochs = 30,\n validation_data = validation_generator,\n validation_steps = 50)\n\n#保存模型\nmodel.save('cats_and_dogs_small_2.h5')\n#绘制训练过程中的损失曲线和精度曲线\nimport matplotlib.pyplot as plt\nacc = history.history['acc']\nval_acc = history.history['val_acc']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\nepochs = range(1, len(acc) + 1)\n\nplt.plot(epochs, acc, 'b*', label = 'Train_acc')\nplt.plot(epochs, val_acc, 'b', label = 'Validation_acc')\nplt.title('Training and Validation Accuracy')\nplt.legend()\n\nplt.figure()\n\nplt.plot(epochs, loss, 'r*', label = 'Train_loss')\nplt.plot(epochs, val_loss, 'r', label = 'Validation_loss')\nplt.title('Training and Validation Loss')\nplt.legend()\n\nplt.show()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"DeepLearning/cats_dogs.py","file_name":"cats_dogs.py","file_ext":"py","file_size_in_byte":6662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"492750124","text":"import math\n\na = input(\"Name eingeben: \")\nb = input(\"Anzahl eingeben: \")\n\ndef function(a):\n c = c + a\n count = count + 1\n print(a)\n while count < b:\n function(c)\n print(count)\n\nprint(function(a))","sub_path":"Musciator Presentation/snippet 2.py","file_name":"snippet 2.py","file_ext":"py","file_size_in_byte":217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"236301612","text":"#!/usr/bin/python\n\nimport os\nimport pickle\nimport re\nimport sys\n\n#sys.path.append( \"../tools/\" )\n\n\n\"\"\"\n Starter code to process the texts of accuate and inaccurate category to extract\n the features and get the documents ready for classification.\n\n The list of all the texts from accurate category are in the accurate_files list\n likewise for texts of inaccurate category are in (inaccurate_files)\n\n The data is stored in lists and packed away in pickle files at the end.\n\"\"\"\n\n\naccurate_files = open(\"./rawDatasetLocation/accurateFiles.txt\", \"r\")\ninaccurate_files = open(\"./rawDatasetLocation/inaccurateFiles.txt\", \"r\")\n\nlabel_data = []\nfeature_data = []\n\n### temp_counter is a way to speed up the development--there are\n### thousands of lines of accurate and inaccurate text, so running over all of them\n### can take a long time\n### temp_counter helps you only look at the first 200 lines in the list so you\n### can iterate your modifications quicker\ntemp_counter = 0\n\n\nfor name, from_text in [(\"accurate\", accurate_files), (\"inaccurate\", inaccurate_files)]:\n for path in from_text:\n ### only look at first 200 texts when developing\n ### once everything is working, remove this line to run over full dataset\n temp_counter = 1\n if temp_counter < 200:\n path = os.path.join('..', path[:-1])\n print(path)\n text = open(path, \"r\")\n line = text.readline()\n while line:\n ### use a function parseOutText to extract the text from the opened text\n #stem_text = parseOutText(text)\n stem_text = text.readline().strip()\n print(stem_text)\n ### use str.replace() to remove any instances of the words\n# stem_text = stem_text.replace(\"germani\",\"\")\n ### append the text to feature_data\n feature_data.append(stem_text)\n ### append a 0 to label_data if text is from Sara, and 1 if text is from Chris\n if(name == \"accurate\"):\n label_data.append(\"0\")\n elif(name == \"inaccurate\"):\n label_data.append(\"1\")\n \n line = text.readline()\n\n text.close()\n\nprint(\"texts processed\")\naccurate_files.close()\ninaccurate_files.close()\n\n#print(\"Result=\"+feature_data[152])\n\npickle.dump( feature_data, open(\"./createdDataset/dataSet.pkl\", \"wb\") )\npickle.dump( label_data, open(\"./createdDataset/dataLabel.pkl\", \"wb\") )\n\n\n\n\n\n#### in Part 4, do TfIdf vectorization here\n#from nltk.corpus import stopwords\n#sw = stopwords.words(\"english\")\n#from sklearn.feature_extraction.text import TfidfVectorizer\n#vectorizer = TfidfVectorizer(stop_words=sw, lowercase=True)\n##from sklearn.feature_extraction.text import CountVectorizer\n##vectorizer = CountVectorizer()\n#bag_of_words = vectorizer.fit(feature_data)\n#bag_of_words = vectorizer.transform(feature_data) #calculates count\n##print(bag_of_words)\n#print(vectorizer.get_feature_names())\n#print(len(vectorizer.get_feature_names()))\n#print(vectorizer.get_feature_names()[34597])\n","sub_path":"SentimentAnlysis/DatasetProcessing/create_dataset_text.py","file_name":"create_dataset_text.py","file_ext":"py","file_size_in_byte":3123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"153627016","text":"import os, numpy\n\nDOWNLOAD_DIR = '/home/thomas/Downloads'\nOUTPUT_DIR = '/home/thomas/Desktop'\nOUTPUT_FILENAME = 'codejam.out'\nLOGNAME = 'CodeJamHelper'\n\ndef get_input():\n\tfilenames = filter(lambda x: x[-3:] == '.in', os.listdir(DOWNLOAD_DIR))\n\tfileinfo = map(lambda fname: (fname, os.path.getmtime(os.path.join(DOWNLOAD_DIR, fname))), filenames)\n\tfileinfo = sorted(fileinfo, key=lambda x: x[1], reverse=True)\n\tif len(fileinfo) > 0:\n\t\tlog('%d files with extension *.in found in %s' % (len(fileinfo), DOWNLOAD_DIR))\n\t\tfor idx in enumerate(fileinfo):\n\t\t\tlog('%s) %s' % (idx[0], idx[1][0]))\n\t\twhile(True):\n\t\t\ttry:\n\t\t\t\tchoice = raw_input(\"[%s] select file (0):\" % (LOGNAME))\n\t\t\t\tif choice == \"\":\n\t\t\t\t\tchoice = 0\n\t\t\t\telse:\n\t\t\t\t\tchoice = int(choice)\n\t\t\texcept ValueError: pass\n\t\t\telse:\n\t\t\t\tfilename = fileinfo[choice]\n\t\t\t\tbreak\n\t\tlog('opening %s' % filename[0])\n\t\twith open(os.path.join(DOWNLOAD_DIR, filename[0])) as fp:\n\t\t\tlines = map(lambda x: str.rstrip(x, \"\\n\"), fp.readlines())\n\t\treturn lines\n\telse:\n\t\tlog('no files in %s with extension *.in found' % DOWNLOAD_DIR)\n\ndef get_count(input):\n\treturn int(input[0].strip())\n\ndef get_cases(input):\n\treturn input[1:]\n\ndef get_case_tuples(input,tupleDesc):\n\tinputTuples = []\n\tfor listPos in xrange(1,len(input),len(tupleDesc)):\n\t\ttmp = []\n\t\tfor tuplePos in xrange(0,len(tupleDesc)):\n\t\t\ttmp.append(tupleDesc[tuplePos](input[listPos + tuplePos]))\n\t\tinputTuples.append(tuple(tmp))\n\treturn inputTuples\n\ndef matrix_from_2Dlist(list, conversionMap):\n\tm,n = len(list),len(list[0])\n\tA = numpy.zeros((m,n))\n\tfor mx in xrange(m):\n\t\tfor nx in xrange(n):\n\t\t\tA[mx][nx] = conversionMap[list[mx][nx]]\n\treturn A\n\ndef save_output(lines):\n\tfor idx, line in enumerate(lines):\n\t\tlines[idx] = \"Case #%s: %s\\n\" % (idx+1, line)\n\tlines[idx] = lines[idx][:-1]\n\tlog('writing %d lines to %s/%s' % (idx+1, OUTPUT_DIR, OUTPUT_FILENAME))\n\twith open(os.path.join(OUTPUT_DIR, OUTPUT_FILENAME), 'w') as fp:\n\t\tfp.writelines(lines)\n\ndef log(string):\n\tprint('[%s] %s' % (LOGNAME, string))","sub_path":"solutions_python/Problem_118/1354.py","file_name":"1354.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"184144581","text":"import pandas as pd\nimport numpy as np\nfrom collections import Counter, defaultdict\nfrom mstools.metrics import metrics\n\n\ndef merge_hor(X, y):\n whole = pd.concat([X, y], axis=1)\n return whole\n\n\ndef distinct_cluster_classes(data, column_name):\n classes = np.unique(data[column_name].values)\n classes = classes[classes >= 0]\n return classes\n\n\ndef sample_training_set(X, y, no_data_points=1000):\n whole = pd.concat([X, y], axis=1)\n sample = whole.sample(n=1000)\n X, y = sample.iloc[:, :-y.shape[-1]], sample.iloc[:, -y.shape[-1]:]\n return X, y\n\n\ndef sample_from_clusters(X, y, column_name='cluster_id', no_data_points: int = 5000):\n\n cluster_ids = y[column_name].values.flatten().tolist()\n cluster_ids = list(filter(lambda x: x >= 0, cluster_ids))\n sample_ratio = no_data_points/len(cluster_ids)\n counter = Counter(cluster_ids)\n\n sample = pd.DataFrame(columns=X.columns)\n\n for key in counter.keys():\n row_indices = y.loc[y[column_name] == key].index\n cluster_sample = X.loc[row_indices]\n no_cluster_data_points = sample_ratio * counter[key]\n subsample = cluster_sample.sample(n=round(no_cluster_data_points))\n sample = pd.concat([sample, subsample], axis=0)\n\n #sample = sample.sample(n=no_data_points)\n y_sample = y.loc[sample.index]\n return [sample, y_sample]\n\n\ndef get_from(df, column_name, column_value):\n output = df.copy()\n output = output.loc[output[column_name] == column_value]\n return output\n\n\ndef create_mz_signatures_of_class_vs_id(X, Y):\n \"\"\"creates a default dict where mean mz spectra of classes from different samples (class vs id) are stored\n\n Arguments:\n X {pd.Dataframe} -- dataframe with mass channels\n Y {pd.Dataframe} -- dataframe with targets and metadata\n\n Returns:\n defaultdict -- defaultdict with main key on id and secondary key on class\n \"\"\"\n ref_mz_dict = defaultdict(dict)\n ids = np.unique(Y['id'].values)\n classes = np.unique(Y['class_bin'].values)\n\n for clas in classes:\n for idd in ids:\n buffer = get_from(Y, 'id', idd)\n buffer = get_from(buffer, 'class_bin', clas)\n buffer = X.loc[buffer.index]\n ref_mz_dict[idd][clas] = np.mean(buffer, axis=0)\n return ref_mz_dict\n\n\ndef get_similarity_from_mz_dict(mz_dict, id1, class1, id2, class2):\n \"\"\"Calculates similarity index between two mz spectra from mz_dict from \n create_mz_signatures_of_class_vs_id function\n\n Arguments:\n mz_dict {defaultdict} -- dictionary with reference spectra\n id1 {int} -- id of first sample\n class1 {int} -- class of first sample\n id2 {int} -- id of second sample\n class2 {int} -- class of second sample\n\n Returns:\n float -- similarity index\n \"\"\"\n first = mz_dict[id1][class1].values\n second = mz_dict[id2][class2].values\n return metrics.similarity_index(first, second)\n\n\ndef remove_noise_spectra(X, Y):\n Y_noiseless = Y.loc[Y['cluster_id'] != -1]\n X_noiseless = X.loc[Y_noiseless.index]\n return X_noiseless, Y_noiseless\n","sub_path":"mstools/utils/df_tools.py","file_name":"df_tools.py","file_ext":"py","file_size_in_byte":3097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"34428809","text":"'''\r\n Author:Lu Fanshen\r\n Function:Homework\r\n Version:1\r\n Date:\r\n Comments:\r\n'''\r\n\r\n# -*- coding: utf-8 -*-\r\nimport numpy as np\r\nfrom scipy.optimize import leastsq\r\nimport pylab as pl\r\n \r\ndef func(x, p):\r\n \"\"\"\r\n 数据拟合所用的函数: A*sin(2*pi*k*x + theta)\r\n \"\"\"\r\n A, k, theta = p\r\n return A*np.sin(2*np.pi*k*(x+theta)) \r\n\r\ndef residuals(p, y, x):\r\n \"\"\"\r\n 实验数据x, y和拟合函数之间的差,p为拟合需要找到的系数\r\n \"\"\"\r\n return y - func(x, p)\r\n\r\nx = np.linspace(0, 0.8*np.pi, 17)\r\nA, k, theta = 46.3,0.79,np.pi/20 # 真实数据的函数参数\r\ny0 = func(x, [A, k, theta]) # 真实数据\r\n\r\np0 = [48, 0.8, 0] # 第一次猜测的函数拟合参数\r\n\r\n# 调用leastsq进行数据拟合\r\n# residuals为计算误差的函数\r\n# p0为拟合参数的初始值\r\n# args为需要拟合的实验数据\r\nplsq = leastsq(residuals, p0, args=(y0, x))\r\n\r\nprint(\"真实参数:\", [A, k, theta] )\r\nprint(\"拟合参数\", plsq[0]) # 实验数据拟合后的参数\r\npl.rcParams['font.family'] = ['Heiti']\r\npl.rcParams['font.sans-serif'] = ['Heiti'] # 步骤一(替换sans-serif字体)\r\npl.rcParams['axes.unicode_minus'] = False # 步骤二(解决坐标轴负数的负号显示问题)\r\npl.plot(x, y0, label=u\"真实数据\")\r\npl.plot(x, func(x, plsq[0]), label=u\"拟合数据\")\r\npl.legend()\r\npl.show()","sub_path":"homework8_1.py","file_name":"homework8_1.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"411544554","text":"def chess_match():\n total_score1 = 0\n total_score2 = 0\n\n num_games = int(input(\"Antall partier: \"))\n\n if num_games < 1:\n print(\"Så kjedelig, da blir det ingen kamp!\")\n else:\n for i in range(num_games):\n print(f\"Parti {i + 1}\")\n score1 = float(input(\"Antall poeng til spiller 1 i partiet: \"))\n score2 = float(input(\"Antall poeng til spiller 2 i partiet: \"))\n\n total_score1 += score1\n total_score2 += score2\n\n print(\"Kampen er slutt!\")\n print(f\"Spiller 1 fikk {total_score1} poeng\")\n print(f\"Spiller 2 fikk {total_score2} poeng\")\n\n\ndef end_of_match(num_games, game, total_score1, total_score2):\n if total_score1 >= (num_games/2 + 0.5):\n return 1\n elif total_score2 >= (num_games/2 + 0.5):\n return 2\n elif game == num_games and total_score2 == total_score1:\n return 3\n return 0\n\n\ndef chess_scorer():\n legal_result = False\n\n while not legal_result:\n result = float(input(\"Resultat for spiller 1: \"))\n\n if result == 0.0 or result == 0.5 or result == 1.0:\n legal_result = True\n else:\n print(\"Umulig resultat\")\n\n return result, 1 - result\n\n\ndef player_score(results):\n player_score = 0\n for result in results:\n if type(result) == float:\n player_score += result\n return player_score\n\n\ndef main():\n print(chess_match())\n print(chess_scorer())\n print(player_score([0.0, 1.0, 0.5, 1.0, None, 0.5, None, None, None]))\n\nmain()","sub_path":"Eksamensoppgaver/2013 Kont/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"128141891","text":"#! /usr/bin/env python3\n\nimport readline, sys\n\nout_of = int(sys.argv[1])\nwhile 1:\n line = input(\"Type half of what you mean:\")\n total = 0\n for num in line.split(\"-\"):\n total += int(num*2)\n print(\"Total: %d (%f%%)\" % (total, total * (100.0 / out_of)))\n","sub_path":"old.py","file_name":"old.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"399538303","text":"\n\"\"\"\nA strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).\n\nWrite a function to determine if a number is strobogrammatic. The number is represented as a string.\n\nFor example, the numbers \"69\", \"88\", and \"818\" are all strobogrammatic.\n\"\"\"\n\n\n\nclass Solution(object):\n def __init__(self):\n self.dic = {'8': '8', '6': '9', '9': '6', '1':'1', '0': '0'}\n \n def isStrobogrammatic(self, num):\n \"\"\"\n :type num: str\n :rtype: bool\n \"\"\"\n N = len(num)\n for i in range(N):\n x, y = num[i], num[N-1-i]\n if x not in self.dic or (x in self.dic and y != self.dic[x]):\n return False\n return True\n","sub_path":"leetcode/Strobogrammatic Number.py","file_name":"Strobogrammatic Number.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"621061050","text":"\nfrom django.conf.urls import url, include\nimport views\n\nurlpatterns = [\n url(r'^ws/tables/$', views.TablesListView.as_view()),\n url(r'^ws/form/settable/$', views.SetTableFormView.as_view()),\n url(r'^ws/form/settable/(?P\\d+)/$', views.SetTableFormView.as_view()),\n url(r'^ws/settable/$', views.SetTableListView.as_view()),\n]\n","sub_path":"restorant/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"26536194","text":"\nimport os\nimport numpy as np\nimport tensorflow as tf\nfrom time import time\nfrom metric import AP, MRR\nfrom dataset import DataSet\nfrom HGRUCell import HGRUCell\nfrom HTGRUCell import HTGRUCell_Tissa, HTGRUCell_TIMEGRU1\nfrom argparse import ArgumentParser, ArgumentDefaultsHelpFormatter\n# from modules import multihead_attention\n# from disan import disan\nimport logging\nimport sys\n\nparser = ArgumentParser(\"deep_personalization\",\n\t\t\t\t\t\t formatter_class=ArgumentDefaultsHelpFormatter,\n\t\t\t\t\t\t conflict_handler='resolve')\n\nparser.add_argument('--num_epoch', default=10, type=int,\n\t\t\t\t\t help='The number of the epochs.')\n\nparser.add_argument('--batch_size', default=200, type=int,\n\t\t\t\t\t help='Batch size of the input data.')\n\nparser.add_argument('--max_query', default=300, type=int,\n\t\t\t\t\t help='Maximum number of queries in user history.')\n\nparser.add_argument('--dict_size', default=300, type=int,\n\t\t\t\t\t help='Length of Doc2Vector embedding.')\n\nparser.add_argument('--state_size', default=900, type=int,\n\t\t\t\t\t help='Length of state vector of the user profile model.')\n\nparser.add_argument('--feature_size', default=98, type=int,\n\t\t\t\t\t help='Length of additional feature vector.')\n\nparser.add_argument('--short_state_size', default=300, type=int,\n\t\t\t\t\t help='Length of short state vector of the user profile model.')\n\nparser.add_argument('--long_state_size', default=600, type=int,\n\t\t\t\t\t help='Length of long state vector of the user profile model.')\n\nparser.add_argument('--hidden_unit_num', default=512, type=int,\n\t\t\t\t\t help='Number of unit in hidden layer.')\n\nparser.add_argument('--atten_hidden_unit_num', default=300, type=int,\n\t\t\t\t\t help='Number of unit in hidden layer.')\n\nparser.add_argument('--atten_type', default='static', type=str,\n\t\t\t\t\t help='Use which kind of attention or not.')\n\nparser.add_argument('--save', default=os.path.join(os.getcwd(),'model.ckpt'), type=str,\n\t\t\t\t\t help='Save or not, if save, then enter the filename.')\n\nparser.add_argument('--test_model', default=True, type=str,\n\t\t\t\t\t help='Train or test the model.')\n\nparser.add_argument('--score_model', default=True, type=str,\n\t\t\t\t\t help='Calculate the score of the model.')\n\nparser.add_argument('--limitation', default=5000000, type=int,\n\t\t\t\t\t help='Limitation of training set.')\n\nparser.add_argument('--early_stops', default=True, type=str,\n\t\t\t\t\t help='Train or test the model.')\n\nparser.add_argument('--verbose', default=True, type=str,\n\t\t\t\t\t help='Verbose.')\n\nparser.add_argument('--logname', default=\"hsqa.log\", type=str,\n\t\t\t\t\t help='Verbose.')\n\nargs = parser.parse_args()\n\ndef getlogger(filename):\n\tlogger = logging.getLogger('mylogger') \n\tlogger.setLevel(logging.DEBUG) \n\t\n\t# 创建一个handler,用于写入日志文件 \n\tfh = logging.FileHandler(filename) \n\tfh.setLevel(logging.DEBUG) \n\t\n\t# 再创建一个handler,用于输出到控制台 \n\tch = logging.StreamHandler() \n\tch.setLevel(logging.DEBUG) \n\t\n\t# 定义handler的输出格式 \n\tformatter = logging.Formatter('[%(asctime)s][%(thread)d][%(filename)s][line: %(lineno)d][%(levelname)s] ## %(message)s')\n\tfh.setFormatter(formatter) \n\tch.setFormatter(formatter) \n\t\n\t# 给logger添加handler \n\tlogger.addHandler(fh) \n\t# logger.addHandler(ch) \n\t\n\t# 记录一条日志 \n\tlogger.info('foorbar') \n\n\treturn logger\n\nmyLogger = getlogger(args.logname)\ndatasource_score = DataSet(max_query=args.max_query, limitation=args.limitation, \n\tbatch_size=args.batch_size, num_epoch=args.num_epoch)\ndatasource_score.prepare_hierarchical_dataset()\ndatasource_score.prepare_score_dataset()\n\n\nclass HSQA:\n\tATTEN_TYPE={'dynamic','static', False}\n\tdef __init__(self):\n\t\tif args.atten_type not in HSQA.ATTEN_TYPE:\n\t\t\traise ValueError('Attention type not valid')\n\t\tself.batch_size = args.batch_size\n\t\tself.num_epoch = args.num_epoch\n\t\tself.max_query = args.max_query\n\t\tself.state_size = args.state_size\n\t\tself.feature_size = args.feature_size\n\t\tself.short_state_size = args.short_state_size\n\t\tself.long_state_size = args.long_state_size\n\t\tself.dict_size = args.dict_size\n\t\tself.hidden_unit_num = args.hidden_unit_num\n\t\tself.atten_hidden_unit_num = args.atten_hidden_unit_num\n\t\tself.atten_type = args.atten_type\n\t\tself.test_model = args.test_model\n\t\tself.score_model = args.score_model\n\t\tself.limitation = args.limitation\n\t\tself.early_stops = args.early_stops\n\t\tself.save = args.save\n\t\tself.verbose = args.verbose\n\t\tself.num_classes = 2\n\t\tself.start_time = time()\n\n\tdef get_atten(self, atten_type):\n\t\tif atten_type == 'dynamic':\n\t\t\treturn self.dynamic_atten\n\t\telif atten_type == 'static':\n\t\t\treturn self.static_atten\n\n\tdef reset_graph(self):\n\t\tif 'sess' in globals() and sess:\n\t\t\tsess.close()\n\t\ttf.reset_default_graph()\n\n\tdef early_stop(self):\n\t\tif len(self.valid_accuracy)<3:\n\t\t\treturn True\n\t\tif self.valid_accuracy[-3]>self.valid_accuracy[-2] and self.valid_accuracy[-2]>self.valid_accuracy[-1]:\n\t\t\treturn False\n\t\telse:\n\t\t\treturn True\n\n\tdef dynamic_atten(self, outputs):\n\t\twith tf.variable_scope('AttentionLayer'):\n\t\t\tAttn_q = tf.layers.dense(inputs=self.q, units=self.atten_hidden_unit_num, activation=tf.nn.sigmoid)\n\t\t\tAttn_q = tf.layers.dense(inputs=self.q, units=self.dict_size, activation=tf.nn.sigmoid)\n\t\tratios = tf.reduce_sum(self.history_q*tf.expand_dims(Attn_q, 1), 2)\n\t\tmask = tf.sequence_mask(self.seq, self.max_query, dtype=tf.float32)\n\t\ta = tf.exp(ratios)/tf.expand_dims(tf.reduce_sum(tf.exp(ratios)*mask, 1), 1)\n\t\tatten_final_state = tf.reduce_sum(outputs*tf.expand_dims(a, 2)*tf.expand_dims(mask, 2), 1)\n\t\treturn atten_final_state\n\t\n\tdef static_atten(self, outputs):\n\t\tq_norm = tf.sqrt(tf.reduce_sum(tf.square(self.q), 1))\n\t\thistory_q_norm = tf.sqrt(tf.reduce_sum(tf.square(self.history_q), 2))\n\t\tratios = tf.reduce_sum(self.history_q*tf.expand_dims(self.q, 1), 2)/(history_q_norm*tf.expand_dims(q_norm, 1)+1)\n\t\ta = tf.nn.softmax(ratios*tf.cast(ratios>0.5,dtype=np.float32)+0.05*ratios*tf.cast(ratios<=0.5,dtype=np.float32))\n\t\tatten_final_state = tf.reduce_sum(outputs*tf.expand_dims(a, 2), 1)\n\t\treturn atten_final_state\n\n\tdef pairwise_loss(self, score1, score2):\n\t\treturn (1/(1+tf.exp(score2-score1)))\n\n\tdef build_graph(self):\n\t\tself.history_x = tf.placeholder(tf.float32, [self.batch_size, self.max_query, 2*self.dict_size+2])\n\t\tself.history_xt = tf.placeholder(tf.float32, [self.batch_size, self.max_query, 2*(self.dict_size)+3])\n\n\t\tself.d_1 = tf.placeholder(tf.float32, [self.batch_size, self.dict_size])\n\t\tself.d_2 = tf.placeholder(tf.float32, [self.batch_size, self.dict_size])\n\t\tself.q = tf.placeholder(tf.float32, [self.batch_size, self.dict_size])\n\t\tself.y = tf.placeholder(tf.int32, [self.batch_size])\n\t\tself.seq = tf.placeholder(tf.int32, [self.batch_size])\n\t\tself.features_1 = tf.placeholder(tf.float32, [self.batch_size, self.feature_size])\n\t\tself.features_2 = tf.placeholder(tf.float32, [self.batch_size, self.feature_size])\n\t\tself.lambdas = tf.placeholder(tf.float32, [self.batch_size])\n\t\tself.t = tf.placeholder(tf.float32,[self.batch_size, self.max_query])\n\t\tself.tt = tf.reshape(self.t,[self.batch_size, self.max_query, 1])\n\t\tself.history_src_mask = tf.placeholder(tf.bool, [self.batch_size, self.max_query])\n\t\tself.long_final_state_feed = tf.placeholder(tf.float32, [self.batch_size, self.long_state_size])\n\t\tself.short_final_state_feed = tf.placeholder(tf.float32, [self.batch_size, self.short_state_size])\n\n\t\tself.short_history_x = tf.placeholder(tf.float32, [self.batch_size, self.max_query, 2*self.dict_size+2])\n\t\tself.history_src_mask_short = tf.placeholder(tf.bool, [self.batch_size, self.max_query])\n\n\n\n\t\tcell = HGRUCell(num_units=self.short_state_size+self.long_state_size, \n\t\t\t\t\t\tshort_state_size=self.short_state_size,\n\t\t\t\t\t\tlong_state_size=self.long_state_size)\n\t\t# cell = tf.contrib.rnn.GRUCell(num_units=self.state_size)\n\t\tinit_state = tf.get_variable('init_state',[1, self.state_size], dtype=np.float32)\n\t\tinit_state = tf.tile(init_state, [self.batch_size, 1])\n\n\t\t# self.history_src, b, e = tf.split(self.history_x, num_or_size_splits=[2* self.dict_size, 1, 1], axis = 2)\n\t\t# self.history_src_short, b_short, e_short = tf.split(self.short_history_x, num_or_size_splits=[2* self.dict_size, 1, 1], axis = 2)\n\n\n\t\t# with tf.variable_scope('long_state_disan',reuse = tf.AUTO_REUSE):\n\t\t# \tlong_state = disan(self.history_src,self.history_src_mask,is_train=True)\n\t\t# \tshort_state = disan(self.history_src_short,self.history_src_mask_short,is_train=True)\n\t\t# with tf.variable_scope('short_state_disan'):\n\t\t# \tshort_state = disan(self.history_src_short,self.history_src_mask_short,is_train=True)\n\t\t\n\t\tself.history_xt = tf.concat([self.history_x,self.tt],axis = 2)\n\t\toutputs, self.final_state = tf.nn.dynamic_rnn(cell=cell, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\tinputs=self.history_xt, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\tsequence_length=self.seq, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\tinitial_state=init_state)\n\n\n\n\t\t# outputs = multihead_attention(queries= outputs, keys = outputs, values = outputs, num_heads = 4, dropout_rate=0.1)\n\n\t\tif isinstance(self.atten_type, str):\n\t\t\tself.history_q, self.history_d, _ = tf.split(self.history_x, num_or_size_splits=[self.dict_size, self.dict_size, 2], axis=2)\n\t\t\tatten_model = self.get_atten(self.atten_type)\n\t\t\tself.final_state = atten_model(outputs)\n\n\t\tself.short_final_state, self.long_final_state = tf.split(\n\t\t\tself.final_state, num_or_size_splits=[self.short_state_size, self.long_state_size], axis=1)\n\t\t\n\n\t\t# self.short_final_state = tf.layers.dense(inputs = )\n\t\t# self.long_final_state = long_state\n\t\t# self.long_final_state = self.long_final_state_feed\n\t\t# self.short_final_state = self.short_final_state_feed\n\n\t\t# self.short_final_state = short_state\n\n\t\twith tf.variable_scope('MatchingUserProfileDoc'):\n\t\t\tshort_user_profile = tf.layers.dense(inputs=self.short_final_state, units=self.hidden_unit_num, activation=tf.nn.sigmoid)\n\t\t\tshort_user_profile = tf.layers.dense(inputs=short_user_profile, units=self.dict_size, activation=tf.nn.sigmoid)\n\t\t\tlong_user_profile = tf.layers.dense(inputs=self.long_final_state, units=self.atten_hidden_unit_num, activation=tf.nn.sigmoid)\n\t\t\tlong_user_profile = tf.layers.dense(inputs=long_user_profile, units=self.dict_size, activation=tf.nn.sigmoid)\n\t\t\tsup_mo = tf.sqrt(tf.reduce_sum(tf.square(short_user_profile), 1))\n\t\t\tlup_mo = tf.sqrt(tf.reduce_sum(tf.square(long_user_profile), 1))\n\t\t\td1_mo = tf.sqrt(tf.reduce_sum(tf.square(self.d_1), 1))\n\t\t\td2_mo = tf.sqrt(tf.reduce_sum(tf.square(self.d_2), 1))\n\t\t\tself.score_1_1 = tf.expand_dims((tf.reduce_sum(short_user_profile*self.d_1, 1))/(sup_mo*d1_mo+1), 1)\n\t\t\tself.score_2_1 = tf.expand_dims((tf.reduce_sum(short_user_profile*self.d_2, 1))/(sup_mo*d2_mo+1), 1)\n\t\t\tself.score_1_2 = tf.expand_dims((tf.reduce_sum(long_user_profile*self.d_1, 1))/(lup_mo*d1_mo+1), 1)\n\t\t\tself.score_2_2 = tf.expand_dims((tf.reduce_sum(long_user_profile*self.d_2, 1))/(lup_mo*d2_mo+1), 1)\n\n\t\twith tf.variable_scope('FullyConnected'):\n\t\t\tscore_1 = tf.layers.dense(inputs=self.features_1, units=1, activation=tf.nn.tanh)\n\t\t\tscore_1 = score_1 + self.score_1_1 + self.score_1_2\n\t\t\t# score_1 = self.score_1_1 + self.score_1_2\n\n\t\twith tf.variable_scope('FullyConnected', reuse=True):\n\t\t\tscore_2 = tf.layers.dense(inputs=self.features_2, units=1, activation=tf.nn.tanh)\n\t\t\tscore_2 = score_2 + self.score_2_1 + self.score_2_2\n\t\t\t# score_2 = self.score_2_1 + self.score_2_2\n\n\n\t\tself.score = tf.concat([score_1, score_2], 1)\n\n\t\tself.p_score = tf.concat([self.pairwise_loss(score_1, score_2),\n\t\t\t\t\tself.pairwise_loss(score_2, score_1)], 1)\n\n\t\tself.preds = tf.nn.softmax(self.score)\n\t\tself.correct = tf.equal(tf.cast(tf.argmax(self.preds,1),tf.int32), self.y)\n\t\tself.accuracy = tf.reduce_mean(tf.cast(self.correct, tf.float32))\n\n\t\tself.loss = tf.reduce_mean(\n\t\t\tself.lambdas*tf.nn.sparse_softmax_cross_entropy_with_logits(\n\t\t\t\tlabels=self.y, logits=self.p_score))\n\t\t#gradient_all = tf.train.AdamOptimizer(1e-3).compute_gradients(loss=loss)\n\t\tself.train_step = tf.train.AdamOptimizer(1e-3).minimize(self.loss)\n\t\tself.init_all_vars = tf.global_variables_initializer()\n\t\tself.saver = tf.train.Saver()\n\n\tdef prepare_graph(self):\n\t\tself.config = tf.ConfigProto(allow_soft_placement=True)\n\t\tself.config.gpu_options.allow_growth = True\n\t\tself.graph_ = tf.Graph()\n\t\twith self.graph_.as_default():\n\t\t\ttf.set_random_seed(2018)\n\t\t\twith tf.variable_scope('HSQA', initializer=tf.uniform_unit_scaling_initializer(seed=2018)) as scope:\n\t\t\t\tself.build_graph()\n\t\tself.session_ = tf.Session(graph=self.graph_, config=self.config)\n\t\tself.session_.run(self.init_all_vars)\n\n\tdef get_mask(self,X_train,seq_train):\n\t\tmask_train = []\n\t\tfor ii in range(0,np.array(X_train.shape[0])):\n\t\t\tmask_train_item = []\n\t\t\tfor jj in range(0,np.array(X_train.shape[1])):\n\t\t\t\tmask_train_item.append(False)\n\t\t\tmask_train.append(mask_train_item)\n\n\t\tfor iidx,seq_train_num in enumerate(seq_train):\n\t\t\tfor jj in range(0,seq_train_num):\n\t\t\t\tmask_train[iidx][jj] = True\n\t\treturn mask_train\n\t\n\tdef get_short_x(self,X_train,seq_train):\n\n\t\tnew_X_train = np.zeros((X_train.shape[0],X_train.shape[1],X_train.shape[2]),dtype=np.float64)\n\t\tnew_seq_train = np.zeros(X_train.shape[0],dtype=np.int32)\n\n\n\n\t\tfor ii in range(np.array(X_train).shape[0]):\n\t\t\tseq_len = seq_train[ii]\n\t\t\tX_train_item = X_train[ii]\n\t\t\tfor jj in range(seq_len):\n\t\t\t\tb = X_train[ii][seq_len - 1 - jj][-2]\n\t\t\t\te = X_train[ii][seq_len - 1 - jj][-1]\n\t\t\t\tif b == 1:\n\t\t\t\t\tbreak\n\t\t\tfor j in range(seq_len - 1 - jj, seq_len):\n\t\t\t\tnew_X_train[ii][j - (seq_len - 1 - jj)] = X_train[ii][j]\n\t\t\t\n\t\t\tnew_seq_train[ii] = jj + 1\n\t\t\n\t\treturn new_X_train, new_seq_train\n\n\n\t\t\t\n\n\n\n\t\t\t\n\n\n\tdef train_network(self, datasource):\n\t\ttf.set_random_seed(2018)\n\t\tif not hasattr(self, 'session_'):\n\t\t\tself.prepare_graph()\n\n\t\tself.train_losses = []\n\t\tself.train_accuracy = []\n\t\tself.valid_losses = []\n\t\tself.valid_accuracy = []\n\t\tfor idx, epoch in enumerate(datasource.gen_epochs()):\n\t\t\ttraining_loss = 0.0\n\t\t\ttraining_acc = 0.0\n\t\t\ttrain_steps = 0\n\t\t\tvalid_loss = 0.0\n\t\t\tvalid_acc = 0.0\n\t\t\tvalid_steps = 0\n\t\t\tepoch_cnt = 0\n\t\t\t\n\n\t\t\tfor X_train, seq_train, d1_train, d2_train, Y_train, q_train, lambda_train,\tf1_train, f2_train, dt_train, qt_train, st_train, ct_train,\\\n\t\t\t\tX_valid, seq_valid, d1_valid, d2_valid, Y_valid, q_valid, lambda_valid, f1_valid, f2_valid,dt_valid, qt_valid, st_valid, ct_valid in epoch:\n\n\t\t\t\t# print(np.array(X_train).shape)\n\t\t\t\t# print(X_train)\n\t\t\t\t# print(np.array(X_train).shape)\n\t\t\t\t# print(np.array(dt_train).shape)\n\t\t\t\t# print(qt_train)\n\t\t\t\t# print(np.array(X_train).shape)\n\t\t\t\t# print(np.array(X_train))\n\t\t\t\t# print(np.array(seq_train).shape)\n\t\t\t\t# print(np.array(seq_train))\n\t\t\t\t# print(seq_train)\n\n\t\t\t\t# mask_train = []\n\t\t\t\t# for ii in range(0,np.array(X_train.shape[0])):\n\t\t\t\t# \tmask_train_item = []\n\t\t\t\t# \tfor jj in range(0,np.array(X_train.shape[1])):\n\t\t\t\t# \t\tmask_train_item.append(False)\n\t\t\t\t# \tmask_train.append(mask_train_item)\n\n\t\t\t\t# for iidx,seq_train_num in enumerate(seq_train):\n\t\t\t\t# \tfor jj in range(0,seq_train_num):\n\t\t\t\t# \t\tmask_train[iidx][jj] = True\n\t\t\t\t# print(seq_train)\n\t\t\t\t# print(np.array(X_train))\n\n\t\t\t\t\n\t\t\t\tmask_train = self.get_mask(X_train, seq_train)\n\t\t\t\tnew_X_train, new_seq_train = self.get_short_x(X_train, seq_train)\n\t\t\t\tmask_train_short = self.get_mask(new_X_train, new_seq_train)\n\n\t\t\t\t# print(new_X_train)\n\t\t\t\t# print(new_seq_train)\n\t\t\t\t# print(\"#######################\")\n\n\t\t\t\t# X_train_np = np.array(X_train)\n\t\t\t\t# qt_np = np.random.rand(X_train_np.shape[0],X_train_np.shape[1])\n\t\t\t\t# print(qt_np.shape)\n\t\t\t\t# print(np.array(st_train).shape)\n\t\t\t\t# print(np.array(ct_train).shape)\n\t\t\t\t# print(np.array(qt_train).shape)\n\t\t\t\t# print(np.array(qt_train))\n\t\t\t\t# print(qt_train[0])\n\n\t\t\t\t# print(qt_train.tolist())\n\t\t\t\t# #print(dt_train, ct_train)\n\t\t\t\t# d2_train_np = np.array(d2_train)\n\t\t\t\t# trand = np.random.rand(1,300)\n\t\t\t\t# trandlist = trand.tolist()\n\n\t\t\t\t\n\t\t\t\ttime_train = time()\n\n\t\t\t\tfeed_dict_train = {self.history_x:X_train, self.seq:seq_train, self.d_1:d1_train, self.d_2:d2_train, self.y:Y_train, self.short_final_state_feed:np.zeros((self.batch_size,self.short_state_size),),self.long_final_state_feed:np.zeros((self.batch_size,self.long_state_size),),\n\t\t\t\t\t\t\t self.q:q_train, self.lambdas:lambda_train, self.features_1:f1_train, self.features_2:f2_train, self.t:qt_train,self.history_src_mask:mask_train,self.short_history_x:new_X_train,self.history_src_mask_short:mask_train_short}\n\t\t\t\t\n\t\t\t\tX_train_np = np.array(X_train)\n\t\t\t\t# print(X_train_np.shape)\n\t\t\t\t# print(d2_train_np.shape)\n\t\t\t\t# print(trand.shape)\n\t\t\t\t# print(trand.dtype)\n\t\t\t\ttrain_loss_, training_state, train_acc_, score= self.session_.run([self.loss,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.train_step,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.accuracy,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.score_1_1],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfeed_dict_train)\n\t\t\t\t#print(epoch_cnt)\n\t\t\t\tepoch_cnt += 1\n\t\t\t\t# print(epoch_cnt)\n\t\t\t\t# if train_steps % 100 == 0:\n\t\t\t\t# \tprint(train_steps)\n\t\t\t\t# print(\"scores!!\", score[:2])\n\t\t\t\ttraining_loss += train_loss_\n\t\t\t\ttraining_acc += train_acc_\n\t\t\t\ttrain_steps += 1\n\n\t\t\t\t# mask_valid = []\n\t\t\t\t# for ii in range(0,np.array(X_valid.shape[0])):\n\t\t\t\t# \tmask_valid_item = []\n\t\t\t\t# \tfor jj in range(0,np.array(X_valid.shape[1])):\n\t\t\t\t# \t\tmask_valid_item.append(False)\n\t\t\t\t# \tmask_valid.append(mask_valid_item)\n\n\t\t\t\t# for iidx,seq_valid_num in enumerate(seq_valid):\n\t\t\t\t# \tfor jj in range(0,seq_valid_num):\n\t\t\t\t# \t\tmask_valid[iidx][jj] = True\n\t\t\t\tmask_valid = self.get_mask(X_valid, seq_valid)\n\t\t\t\t\n\t\t\t\tnew_X_valid,new_seq_valid = self.get_short_x(X_valid, seq_valid)\n\t\t\t\tmask_valid_short = self.get_mask(new_X_valid, new_seq_valid)\n\n\t\t\t\tfeed_dict_valid = {self.history_x:X_valid, self.seq:seq_valid, self.d_1:d1_valid, self.d_2:d2_valid, self.y:Y_valid,self.short_final_state_feed:np.zeros((self.batch_size,self.short_state_size)),self.long_final_state_feed:np.zeros((self.batch_size,self.long_state_size),),\n\t\t\t\t\t\t\t self.q:q_valid, self.lambdas:lambda_valid, self.features_1:f1_valid, self.features_2:f2_valid,self.t:qt_valid,self.history_src_mask:mask_valid,self.short_history_x:new_X_valid,self.history_src_mask_short:mask_valid_short}\n\t\t\t\tvalid_loss_, valid_acc_ = self.session_.run([self.loss,\n\t\t\t\t\t\t\t\t\t\t\t\t\tself.accuracy],\n\t\t\t\t\t\t\t\t\t\t\t\t\tfeed_dict_valid)\n\t\t\t\tvalid_loss += valid_loss_\n\t\t\t\tvalid_acc += valid_acc_\n\t\t\t\tvalid_steps += 1\n\t\t\t\tif self.verbose:\n\t\t\t\t\t# print(\"\\tBatch Loss: \", train_loss_, \"\\tAccuracy: \", train_acc_, \"\\tTime cost: \", time()-time_train, \"s.\", \"epoch_cnt\", epoch_cnt,\"idx,\",idx)\n\t\t\t\t\t# print(\"\\tBatch Valid Loss: \", valid_loss_, \"\\tAccuracy: \", valid_acc_, \"\\tTime cost: \", time()-time_train, \"s.\")\n\t\t\t\t\tmyLogger.info(\"\\tBatch Loss: \" + str(train_loss_) + \"\\tAccuracy: \" + str(train_acc_) + \"\\tTime cost: \" + str(time()-time_train) + \"s.\" + \"epoch_cnt\" + str(epoch_cnt) + \"idx,\" + str(idx)) \n\t\t\t\t\tmyLogger.info(\"\\tBatch Valid Loss: \" + str(valid_loss_) + str(\"\\tAccuracy:\") + str(valid_acc_) + \"\\tTime cost: \" + str(time()-time_train) + \"s.\")\n\t\t\t\t\n\t\t\t\t\n\t\t\t\ttem = '%d'%idx + \"/\" + '%d'%args.num_epoch + \", %d\"%epoch_cnt + \"/\" + \"%d\"%(len(datasource.Y_train)/args.batch_size) + \", time cost: \" +\"%f\"%(time()-time_train) + \"s.\"\n\t\t\t\tsys.stdout.write('\\r' + tem)\n\t\t\t\tsys.stdout.flush()\n\t\t\tself.train_losses.append(training_loss/train_steps)\n\t\t\tself.train_accuracy.append(training_acc/train_steps)\n\t\t\tself.valid_losses.append(valid_loss/valid_steps)\n\t\t\tself.valid_accuracy.append(valid_acc/valid_steps)\n\n\t\t\tif self.early_stops:\n\t\t\t\tif not self.early_stop():\n\t\t\t\t\tbreak\n\n\t\t\tif isinstance(self.save, str):\n\t\t\t\tself.saver.save(self.session_, self.save)\n\t\t\t\n\n\n\t\t\tevaluation_score = AP()\n\t\t\tself.score_network(datasource_score, evaluation_score)\n\n\t\treturn self\n\n\tdef test_network(self, datasource):\n\t\ttf.set_random_seed(2018)\n\t\tif not hasattr(self, 'session_'):\n\t\t\tself.prepare_graph()\n\t\t\tself.saver.restore(self.session_,tf.train.latest_checkpoint('./'))\n\t\t\t\n\t\ttraining_loss = 0.0\n\t\ttraining_acc = 0.0\n\t\ttrain_steps = 0\n\t\tprint(datasource.gen_test_batchs())\n\t\t# for X, seq, d1, d2, Y, q, lambdas, f1_test, f2_test in datasource.gen_test_batchs():\n\t\tfor i , batch in enumerate(datasource.gen_test_batchs()):\n\t\t\tfor X, seq, d1, d2, Y, q, lambdas, f1_test, f2_test, t1_test, t2_test, t3_test, t4_test in batch:\n\n\t\t\t\ttrain_steps += 1\n\n\t\t\t\ttrand = np.random.rand(1,300)\n\t\t\t\ttrandlist = trand.tolist()\n\n\t\t\t\tfeed_dict_test = {self.history_x: X, self.seq: seq, self.d_1: d1, self.d_2: d2, self.y: Y,self.short_final_state_feed:np.zeros((self.batch_size,self.short_state_size)),self.long_final_state_feed:np.zeros((self.batch_size,self.long_state_size),),\n\t\t\t\t\t\t\tself.q: q, self.lambdas:lambdas, self.features_1:f1_test, self.features_2:f2_test,self.t:t2_test,self.short_history_x:new_X_train,self.history_src_mask_short:mask_train_short}\n\t\t\t\ttraining_loss_, accuracy_, = self.session_.run([self.loss,\n\t\t\t\t\t\t\t\t\t\t\tself.accuracy],\n\t\t\t\t\t\t\t\t\t\t\tfeed_dict_test)\t\t\t\n\t\t\t\ttraining_loss += training_loss_\n\t\t\t\ttraining_acc += accuracy_\n\t\tprint(\"Average loss on test data set: \", training_loss/train_steps)\n\t\tprint(\"Accuracy:\", training_acc/train_steps)\n\t\treturn self\n\n\tdef score_network(self, datasource, evaluation):\n\t\ttf.set_random_seed(2018)\n\t\tif not hasattr(self, 'session_'):\n\t\t\tself.prepare_graph()\n\t\t\tself.saver = tf.train.import_meta_graph('model.ckpt.meta')\n\t\t\tself.saver.restore(self.session_,tf.train.latest_checkpoint('./'))\n\n\t\twith open('test_score.txt', 'w') as f:\n\t\t\tfor X, lines, seq, d1, q, qt, features in datasource.gen_score_test_batchs():\n\t\t\t\tstart_time = time()\n\t\t\t\t# trand = np.random.rand(1,300)\n\t\t\t\t# trandlist = trand.tolist()\n\n\t\t\t\t# mask_train = []\n\t\t\t\t# for ii in range(0,np.array(X.shape[0])):\n\t\t\t\t# \tmask_train_item = []\n\t\t\t\t# \tfor jj in range(0,np.array(X.shape[1])):\n\t\t\t\t# \t\tmask_train_item.append(False)\n\t\t\t\t# \tmask_train.append(mask_train_item)\n\n\t\t\t\t# for iidx,seq_train_num in enumerate(seq):\n\t\t\t\t# \tfor jj in range(0,seq_train_num):\n\t\t\t\t# \t\tmask_train[iidx][jj] = True\n\t\t\t\tmask_train = self.get_mask(X, seq)\n\n\t\t\t\tnew_X_train, new_seq_train = self.get_short_x(X, seq)\n\t\t\t\tmask_train_short = self.get_mask(new_X_train, new_seq_train)\n\n\t\t\t\tfeed_dict_test_score = {self.history_x: X, self.seq: seq, self.d_1: d1, self.d_2: d1, self.q: q, self.history_src_mask:mask_train,self.short_final_state_feed:np.zeros((self.batch_size,self.short_state_size)),self.long_final_state_feed:np.zeros((self.batch_size,self.long_state_size),),\n\t\t\t\t\t\t\t\t self.features_1:features, self.features_2:features,self.t:qt,self.short_history_x:new_X_train,self.history_src_mask_short:mask_train_short}\n\t\t\t\tscores = self.session_.run([self.score], feed_dict_test_score)\n\t\t\t\tevaluation.write_score(scores, lines, f)\n\t\t\t\t\n\t\twith open('test_score.txt', 'r') as f:\n\t\t\tevaluation.evaluate(f)\n\ndef main():\n\tdatasource = DataSet(max_query=args.max_query, limitation=args.limitation, \n\t\t\t\tbatch_size=args.batch_size, num_epoch=args.num_epoch)\n\tdatasource.prepare_hierarchical_dataset()\n\tprint(np.array(datasource.X_train).shape)\n\n\t# for i , batch in enumerate(datasource.gen_test_batchs()):\n\t# \tfor X, seq, d1, d2, Y, q, lambdas, f1_test, f2_test, dt_test, qt_test, st_test, ct_test in batch:\n\t# \t\tprint(X)\n\tmodel = HSQA()\n\tmodel = model.train_network(datasource)\n\tevaluation = AP()\n\t#print(\"Train Losses in different epoches are \", model.train_losses)\n\t#print(\"Train Accuracy in different epoches are \", model.train_accuracy)\n\t#print(\"Valid Losses in different epoches are \", model.valid_losses)\n\t#print(\"Valid Accuracy in different epoches are \", model.valid_accuracy)\n\t# if model.test_model:\n\t# \tmodel = model.test_network(datasource)\n\t# if model.score_model:\n\t# \tdatasource.prepare_score_dataset()\n\t# \tmodel.score_network(datasource, evaluation)\n\t# model = model.test_network(datasource)\n\tdatasource.prepare_score_dataset()\n\tmodel.score_network(datasource, evaluation)\n\nif __name__ == '__main__':\n\t# os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"\"\n\tmain()\n","sub_path":"hsqa.py","file_name":"hsqa.py","file_ext":"py","file_size_in_byte":23551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"543031066","text":"\"\"\"\nFiles\n\nWrite a script that creates a new output file called myfile.txt and writes \nthe string \"Hello file world!\" in it. Then write another script that opens \nmyfile.txt, and reads and prints its contents. Run your two scripts \nfrom the system command line. \n\nDoes the new file show up in the directory where you ran your scripts? \n\nWhat if you add a different directory path to the filename passed to open?\n\nNote: file write methods do not add newline characters to your strings; \nadd an explicit ‘\\n’ at the end of the string if you want to fully terminate \nthe line in the file.\n\"\"\"\n\nwith open(\"myfile.txt\", \"a\") as f:\n f.write(\"Hello file world!\\n\")\n f.close\n\nwith open(\"myfile.txt\", \"r\") as f:\n for line in f.readlines():\n print(line, end=\"\")\n f.close","sub_path":"08_files_json/task_1.py","file_name":"task_1.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"639492431","text":"\"\"\"\nWrite a Python program that takes as inputs 5 integers. The program should check to see if any of the 5 are\nduplicates of another (i.e., check whether any of the integers were entered more than once). If, after all\ninputs are entered, a duplicate is found, the program should print “Duplicates”, otherwise it should print\n“All Unique”.\n\"\"\"\n\ndups = False\n\nnums = []\n\nfor i in range(5): # Loop 5 times\n\tnum = float(input(\"Give me number \" + str(i+1) + \": \")) # Ask user for number input $num\n\n\tif num in nums: # Check to see if the number is already in $nums\n\t\tdups = True # If the number already exists in $nums, set $dups to True\n\t\tnums.append(num) # Still want to append it so we have the number\n\telse:\n\t\tnums.append(num) # Otherwise, append $num to the list $nums\n\nif dups == True: # If $dups is True\n\tprint(\"Duplicates\") # Print \"Duplicates\"\nelse: # else (basically saying if $dups is False)\n\tprint(\"All unique\") # Print \"All unique\"","sub_path":"Midterm_Prep/question1.py","file_name":"question1.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"181188117","text":"import scrapy\nimport logging\n\nclass CountriesSpider(scrapy.Spider):\n name = 'countries'\n allowed_domains = ['www.worldometers.info']\n start_urls = ['https://www.worldometers.info/world-population/population-by-country/']\n\n\n def parse(self, response):\n # title = response.xpath(\"//h1/text()\").get()\n countries = response.xpath(\"//tr/td/a\")\n for country in countries:\n name = country.xpath(\".//text()\").get()\n link = country.xpath(\".//@href\").get()\n\n # construct full url link\n # absolute_url = f\"https://www.worldometers.info{link}\" # option 1\n absolute_url = response.urljoin(link) #option 2\n\n # send GET request with the full url\n yield scrapy.Request(url=absolute_url,\n callback=self.parse_country,\n meta={'country_name' : name})\n\n # option 3: without the need to construct absolute url\n # yield response.follow(url=link,\n # callback=self.parse_country)\n\n def parse_country(self, response):\n name = response.request.meta['country_name']\n pop_rows = response.xpath(\n \"//h2[contains(text(),'historical')]/following::table[1]/tbody/tr\"\n )\n\n for row in pop_rows:\n year = row.xpath(\".//td[1]/text()\").get()\n population = row.xpath(\".//td[2]/strong/text()\").get()\n yield {\n 'name': name,\n 'year' : year,\n 'population' : population\n }\n\n","sub_path":"worldometers/worldometers/spiders/countries.py","file_name":"countries.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"581524144","text":"import os\nimport cv2\nimport numpy as np\n\nTARGET_FOLDER_PATH = \"visionpeople/img/target_person/\"\n\n\n# Traverse function where each face is matched with the frame\ndef traverse_frame(current_frame, target_dir):\n\n target = cv2.imread(target_dir, 0)\n cv2.resize(target, (0, 0), fx=0.5, fy=0.5)\n\n result = cv2.matchTemplate(target, current_frame, cv2.TM_CCOEFF_NORMED)\n\n min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)\n\n return [min_val, max_val, min_loc, max_loc]\n\n\n# Get the dirs of the faces to use as targets\ntarget_faces = []\n\nfor file in os.listdir(TARGET_FOLDER_PATH):\n temp_path = TARGET_FOLDER_PATH + file\n target_faces.append(temp_path)\n\n# Use machine camera to return the frames\ncv2.namedWindow(\"Frame\")\nvc = cv2.VideoCapture(0)\n\nif vc.isOpened():\n rval, frame = vc.read()\nelse:\n rval = False\n\nwhile rval:\n rval, frame = vc.read()\n frame = np.flip(frame, axis=1) # Flip frame to mirror\n\n # Show frame\n cv2.imshow(\"Frame\", frame)\n\n # Wait for ESC key to end program\n key = cv2.waitKey(5)\n if key == 27: #ESC\n break\n\ncv2.destroyAllWindows()\n","sub_path":"face_detector.py","file_name":"face_detector.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"295413729","text":"# !/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Author : Chicken dishes\n# Created Time : 2019/11/16 15:56\n\n\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import Column, Integer, String, DateTime, Text\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker, scoped_session\nimport datetime\n\n\nclass DbBase(object):\n def __init__(self):\n self.engine = create_engine(\n 'mysql+pymysql://tan:tan@10.1.14.167:3306/ck',\n max_overflow=0, # 超过连接池外最多创建的连接\n pool_size=5, # 连接池大小\n pool_timeout=30, # 池中没有线程最多等待时间,否则报错\n pool_recycle=-1, # 多久之后对线程池中的线程进行连接回收(重置)\n encoding='utf-8',\n echo=True, )\n\n session = sessionmaker(bind=self.engine)\n # 实例化类\n\n con = scoped_session(session)\n\n\nBase = declarative_base()\n\n\nclass User(Base):\n __tablename__ = 'user'\n id = Column(Integer, primary_key=True)\n name = Column(String(32), index=True, nullable=True)\n","sub_path":"scripts/mysql_base/sqlalchemy_con.py","file_name":"sqlalchemy_con.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"277177132","text":"class Solution(object):\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n #Just catch all ascending \n maxProfit = 0\n if len(prices) <= 1: return 0\n for i in range (1, len(prices)):\n if prices[i] > prices[i-1]:\n maxProfit += prices[i] - prices[i-1]\n return maxProfit\n","sub_path":"stock_ii/StockII.py","file_name":"StockII.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"308766080","text":"import pandas as pd\nimport PruebaModel\nfrom AppCtxt import APPCTXT\n\nclass SDMTPrueba(PruebaModel.PruebaModel):\n def __init__(self, valores):\n nombre = \"SDMT\"\n baremos = (pd.read_csv(APPCTXT().get_resource('./Baremos/TablaSDMT.csv')),\n pd.read_csv(APPCTXT().get_resource('./Baremos/EscolaridadSDMT.csv')))\n campos = (\"C\")\n\n super(SDMTPrueba,self).__init__(nombre, valores, baremos, campos)\n \n\n def calcularPERP(self, datos):\n tablaSDMT = self.baremos[0]\n tablaescolaridadSDMT = self.baremos[1]\n\n sdmtVal = self.valores\n escolaridad = datos[0]\n\n if escolaridad < 8:\n escolaridad = 8\n elif escolaridad > 20:\n escolaridad =20\n \n ajustes = tablaescolaridadSDMT[tablaescolaridadSDMT['Escolaridad'] == escolaridad].iloc[0]\n \n temp = tablaSDMT[(sdmtVal >= tablaSDMT['SDMTMIN']) & (sdmtVal <= tablaSDMT['SDMTMAX'])].iloc[0]\n puntuacionEscalar = temp['Escalar'] + ajustes['SDMT']\n rangoPercentil = (temp['PercentilMin'], temp['PercentilMax'])\n\n if puntuacionEscalar < 2:\n puntuacionEscalar = 2\n elif puntuacionEscalar > 18:\n puntuacionEscalar = 18\n\n\n # print(\"Puntuacion escalar: \", puntuacionEscalar)\n # print(\"Rango Percentil:\", rangoPercentil)\n\n self.puntuacionEscalar = (puntuacionEscalar)\n self.rangoPercentil = (rangoPercentil)\n\n print(self.puntuacionEscalar)\n print(self.rangoPercentil)\n\n","sub_path":"src/main/python/pruebas/SDMTPrueba.py","file_name":"SDMTPrueba.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"316062893","text":"import socket\naa=\"\"\ns = socket.socket()\nport = 80\ns.bind(('', port))\ns.listen(5)\nwhile True:\n c, addr = s.accept()\n print (\"Socket Up and running with a connection from\",addr)\n rcvdData = c.recv(1024).decode()\n if rcvdData==\"OK\" :\n a=open(\"data.txt\",\"r\")\n for x in a:\n \n aa=aa+\"\\n\"+x\n a.close()\n kk=\"hi Boss\"\n c.send(aa.encode());\n c.close()\n s.close()","sub_path":"Socket1.py","file_name":"Socket1.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"520947050","text":"\"\"\"\n@name: containerCombine.py\n@author: Archibald Neil MacDonald\n@copyright: Archibald Neil Macdonald - all rights reserved. Copyright 2014\n@brief: Contains the ContainerCombine class, that deals with checking the validility of combination items, and combining the items.\n\"\"\"\n\nimport collections\nimport combine\n\nclass ContainerCombine():\n\n def __init__(self,container):\n \"\"\"\n @brief: Container combine does a variety of tests on the containers to check how many items, they contain, duplicate items, etc. \n Can be called to combine all the items within the container array and produces a combined item that can be retrieved from getCombinedItem.\n \n @param [in] self: \n @param [in] container: array of containers that may include items.\n \"\"\"\n self._containers = container\n self.combinedItem = None\n self.combined = False\n \n def hasCombined(self):\n return self.combined\n \n def isSuccessfulCombination(self):\n if self.combinedItem and self.combined:\n return True\n else:\n return False\n\n def getCombinedItem(self):\n return self.combinedItem\n \n def reset(self):\n self.combinedItem = False\n self.combined = False\n \n def combineContainerItems(self):\n \"\"\"\n @brief: Combines all the items within the container array and saves the possible result in self.combinedItem.\n \"\"\"\n itemList = []\n for container in self._containers:\n if container.item:\n itemList.append(container.item.name)\n \n self.combinedItem = combine.combineItems(itemList)\n \n self.combined = True\n \n def getItemsCount(self): \n \"\"\"\n @brief: Returns the number of valid items within the container array.\n \n @param [in] self: \n @return: As integer, number of items that do not equal none in the container array.\n \"\"\"\n items = 0\n for container in self._containers:\n if container.item:\n items += 1\n return items\n \n def getMostDuplicates(self):\n \"\"\"\n @brief: Finds how many duplicates of the most duplicated item there are within the container array.\n \n @param [in] self: \n @return: As integer, most number of duplicates within array.\n \"\"\"\n names = []\n \n for container in self._containers:\n if container.item:\n names.append(container.item.name)\n \n counter=collections.Counter(names)\n return counter.most_common(1)[0][1]\n \n def hasDrinkIngredient(self):\n \"\"\"\n @brief: Queries the containers to see if there is at least one Spirit ingredient or one non-alcoholic ingredient. Drinks\n can not be made just out of extras.\n \n @param [in] self: \n @return: True or False\n \"\"\"\n \n for container in self._containers:\n if container.item:\n if container.item.category == \"Non-Alc\" or container.item.category == \"Spirits\":\n return True\n return False\n \n def isButtonActive(self):\n \"\"\"\n @brief: Checks to see if the combine button can be activated or not.\n @param [in] self: \n @return: Boolean. True if button not disabled, false if button should be disabled.\n \"\"\"\n numItems = self.getItemsCount()\n \n #Ensure user has placed three items into combine boxes.\n if numItems < 3:\n return False\n \n #Ensures there is at least one spirit or one non-alc ingredient in the list\n if not self.hasDrinkIngredient():\n return False\n \n #Ensure items placed in boxes are not all of same type.\n if numItems == self.getMostDuplicates():\n return False\n \n return True","sub_path":"game/scripts/combination/containerCombine.py","file_name":"containerCombine.py","file_ext":"py","file_size_in_byte":3958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"449012991","text":"from django.db import models\nfrom django.core.validators import RegexValidator\n\nfrom users.models import Doctor, Client\n\n\nSCHEDULE_CHOICES = (\n ('Every day', 'Every day'),\n ('Every week', 'Every week'),\n ('Except weekend', 'Except weekend'),\n ('Once', 'Once')\n)\n\n\nclass Hospital(models.Model):\n \"\"\"Hospital objects\"\"\"\n\n title = models.CharField(max_length=255, unique=True)\n short_title = models.CharField(max_length=255)\n type = models.CharField(max_length=255)\n logo = models.ImageField(null=True, upload_to='hospitals/')\n description = models.TextField()\n opening_time = models.TimeField(auto_now=False, auto_now_add=False)\n closing_time = models.TimeField(auto_now=False, auto_now_add=False)\n address = models.CharField(max_length=255)\n phone_regex = RegexValidator(regex=r'^\\+?1?\\d{9,15}$',\n message=\"Phone number must be entered in the format: '+999999999'.\")\n phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True)\n services = models.ManyToManyField('Service')\n reviews_amount = models.PositiveIntegerField(default=0)\n hospital_likes_amount = models.PositiveIntegerField(default=0)\n rating = models.DecimalField(default=0, max_digits=3, decimal_places=2)\n\n def __str__(self):\n return self.short_title\n\n def add_like(self):\n self.hospital_likes_amount += 1\n self.save()\n\n\nclass Service(models.Model):\n \"\"\"Services provided by each hospital\"\"\"\n\n title = models.CharField(max_length=255)\n url = models.SlugField(max_length=255, unique=True)\n\n def __str__(self):\n return self.title\n\n\nclass RatingStar(models.Model):\n \"\"\"\"Available amounts of stars for one comment\"\"\"\n value = models.SmallIntegerField(default=0)\n\n def __str__(self):\n return f'{self.value}'\n\n\nclass Review(models.Model):\n \"\"\"Client can leave a review after visiting the hospital\"\"\"\n\n author = models.ForeignKey(Client, on_delete=models.CASCADE)\n rating = models.ForeignKey(RatingStar, related_name='hospital_review', on_delete=models.CASCADE)\n hospital = models.ForeignKey(Hospital, related_name='reviews', on_delete=models.CASCADE)\n text = models.TextField()\n created_at = models.DateTimeField(auto_now=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n\nclass HospitalLike(models.Model):\n \"\"\"Likes for hospitals\"\"\"\n\n user = models.ForeignKey(Client, related_name='hospital_likes', on_delete=models.CASCADE)\n hospital = models.ForeignKey(Hospital, related_name='likes', on_delete=models.CASCADE)\n\n\nclass Specialization(models.Model):\n \"\"\"Doctor services specialization\"\"\"\n\n title = models.CharField(max_length=255)\n url = models.SlugField(max_length=255, unique=True)\n\n def __str__(self):\n return self.title\n\n\nclass Feedback(models.Model):\n \"\"\"Client can leave a feedback after visiting a doctor\"\"\"\n\n author = models.ForeignKey(Client, on_delete=models.CASCADE)\n rating = models.ForeignKey(RatingStar, related_name='client_feedback', on_delete=models.CASCADE)\n text = models.TextField()\n created_at = models.DateTimeField(auto_now=True)\n updated_at = models.DateTimeField(auto_now=True)\n doctor = models.ForeignKey(Doctor, related_name='feedbacks', on_delete=models.CASCADE)\n\n\nclass DoctorLike(models.Model):\n \"\"\"Likes for doctors\"\"\"\n\n user = models.ForeignKey(Client, related_name='doctor_likes', on_delete=models.CASCADE)\n doctor = models.ForeignKey(Doctor, related_name='likes', on_delete=models.CASCADE)\n\n\nclass Schedule(models.Model):\n \"\"\"Doctor's Schedule\"\"\"\n doctor = models.ForeignKey(Doctor, related_name='schedule', on_delete=models.CASCADE)\n time_from = models.TimeField(auto_now=False, auto_now_add=False)\n time_to = models.TimeField(auto_now=False, auto_now_add=False)\n date = models.DateField()\n periodicity = models.CharField(max_length=255, choices=SCHEDULE_CHOICES, null=True, blank=True)\n\n class Meta:\n unique_together = ['doctor', 'date']\n\n\nclass Visit(models.Model):\n \"\"\"Visits for each doctor which clients can book\"\"\"\n doctor = models.ForeignKey(Doctor, related_name='visits', on_delete=models.CASCADE)\n time = models.TimeField(auto_now=False, auto_now_add=False)\n date = models.DateField()\n\n class Meta:\n unique_together = ['doctor', 'time', 'date']\n\n def __str__(self):\n return f'{self.id}. Doctor: {self.doctor.first_name}, Date: {self.date}, Time: {self.time}'\n\n\nclass Booking(models.Model):\n \"\"\"Model for booking a visit to doctor\"\"\"\n visit = models.OneToOneField(Visit, related_name='booking_visit', on_delete=models.CASCADE)\n client = models.ForeignKey(Client, verbose_name='clients', on_delete=models.CASCADE)\n service = models.TextField(null=True, blank=True)\n\n def __str__(self):\n return f'{self.client} : {self.visit}'\n","sub_path":"src/hospital/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"238381064","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\n\nclass Solution(object):\n def myPow_mine(self, x, n):\n if n == 0:\n return 1\n elif n < 0:\n return 1/self.myPow(x, -n)\n else:\n y = self.myPow(x, n//2) # do not repeat this line.\n if n % 2 == 0:\n return y * y\n else:\n return y * y * x\n\n\nclass Solution(object):\n def myPow(self, x, n):\n \"\"\"\n :type x: float\n :type n: int\n :rtype: float\n \"\"\"\n if n < 0:\n return 1/self.myPow(x, -n)\n ans = 1\n while n:\n if n%2 != 0:\n ans *= x\n x *= x\n\n n = n / 2\n return ans\n","sub_path":"Week_03/pow(x_n).py","file_name":"pow(x_n).py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"380629604","text":"from context import T_Shirt_payment\n\nclass User_Interface: #Class for User_interface\n\n @staticmethod\n def checkChoices(message,options,errorMessage): ##function for checking the inputs (use for many cases. message for the user, options for values to check and errorMessage if something goes wrong\n inputVal = input(message).upper()\n while inputVal not in options:\n print(errorMessage)\n print()\n inputVal = input(message).upper()\n return inputVal\n\n @staticmethod\n def divider(number_of_lines,mid_word=''): ##function for design of menu with lines\n draw=' '\n for i in range(int(number_of_lines/2)):\n draw+=\"-\"\n draw+=mid_word\n for i in range(number_of_lines-int(number_of_lines/2)):\n draw+=\"-\"\n return draw\n\n @staticmethod\n def Menu(): ##1st menu appear to user \n print('\\n\\n',\"Welcome to the Assigment3 T-shirt shop\".center(80))\n print('Please choose something from the menu'.center(82))\n print('\\n\\n'+User_Interface.divider(70,' MENU '))\n print('1. Buy a t-shirt')\n print('2. Exit')\n print(User_Interface.divider(79))\n return int(User_Interface.checkChoices('Enter your choice [1-2]: ',['1','2'],'Wrong Choise..Please enter an integer between 1-2.'))\n\n @staticmethod\n def tshirt_buy(tshirt_list,top=False): #function for t-shirt transaction\n if top:\n print('Please give the info for the t-shirt you want to buy.\\n') \n print(\"T-shirt's availabe Colors: \"+','.join([color.capitalize() for color in T_Shirt_payment.color])+\".\")\n Tshirt_color = User_Interface.checkChoices(\"Give T-shirt's color: \",[color.upper() for color in T_Shirt_payment.color],'Wrong color.Please give one of: '+','.join([color.capitalize() for color in T_Shirt_payment.color])+'.').lower()\n print(\"T-shirt's availabe sizes: \"+','.join([size.capitalize() for size in T_Shirt_payment.size])+\".\")\n Tshirt_size = User_Interface.checkChoices(\"Give T-shirt's size: \",[size.upper() for size in T_Shirt_payment.size],'Wrong size.Please give one of: '+','.join([size.capitalize() for size in T_Shirt_payment.size])+'.').lower()\n print(\"T-shirt's availabe fabric: \"+','.join([fabric.capitalize() for fabric in T_Shirt_payment.fabric])+\".\")\n Tshirt_fabric = User_Interface.checkChoices(\"Give T-shirt's fabric: \",[fabric.upper() for fabric in T_Shirt_payment.fabric],'Wrong fabric.Please give one of: '+','.join([fabric.capitalize() for fabric in T_Shirt_payment.fabric])+'.').lower()\n print(\"Please choose a payment method from the following list: \"+','.join([payment.capitalize() for payment in T_Shirt_payment.payment])+\".\")\n Tshirt_payment = User_Interface.checkChoices(\"Give payment method: \",[payment.upper() for payment in T_Shirt_payment.payment],'Wrong payment method.Please give one of: '+','.join([payment.capitalize() for payment in T_Shirt_payment.payment])+'.').lower()\n\n new_Tshirt = T_Shirt_payment ( t_color = Tshirt_color, t_size = Tshirt_size, t_fabric = Tshirt_fabric , t_payment = Tshirt_payment, strategy=None )\n tshirt_list.append(new_Tshirt) #fill the tshirt list with as many as tshirt user likes \n anotherDec = User_Interface.checkChoices(\"Want to buy another t-shirt? Type 'y' for yes and 'n' for no.\",['Y','N'],'Wrong choice!') #ask user for adding another t-shirt\n if anotherDec == 'Y': #if yes fill inputs for another t-shirt\n User_Interface.tshirt_buy(tshirt_list,top=True) \n else:\n print('\\n')\n print('T-shirt transaction completed succesfully.')\n return tshirt_list #return tshirt list to main module.\n @staticmethod\n def exitprogram(): #prints for exit\n print(User_Interface.divider(79))\n print(User_Interface.divider(79))\n print('Program terminated. Thanks for using it.\\nCopyrights: Pantelakis Ioannis\\n')\n","sub_path":"u_i.py","file_name":"u_i.py","file_ext":"py","file_size_in_byte":3961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"587808078","text":"\r\n\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom scipy.stats import skew\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.linear_model import LinearRegression, RidgeCV, ElasticNetCV\r\nfrom sklearn.ensemble import RandomForestRegressor\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.metrics import mean_squared_error\r\nimport math\r\n\r\n\r\ntrain = pd.read_csv(\"train.csv\")\r\n\r\ntrain.head()\r\ntrain.drop(\"Id\", axis = 1, inplace = True)\r\ntrain.head()\r\n\r\n# doing a log transform on the SalePrice to lessen the effect of outliers\r\nSalePrice_train = train.SalePrice\r\nSalePrice_train = np.log(SalePrice_train)\r\n\r\nplt.hist(train.SalePrice)\r\nplt.hist(SalePrice_train)\r\n\r\n\r\n# changing out numeric variables that aren't actually numeric\r\ntrain = train.replace({\"MSSubClass\" : {20 : \"SC20\", 30 : \"SC30\", 40 : \"SC40\", 45 : \"SC45\", \r\n 50 : \"SC50\", 60 : \"SC60\", 70 : \"SC70\", 75 : \"SC75\", \r\n 80 : \"SC80\", 85 : \"SC85\", 90 : \"SC90\", 120 : \"SC120\", \r\n 150 : \"SC150\", 160 : \"SC160\", 180 : \"SC180\", 190 : \"SC190\"},\r\n \"MoSold\" : {1 : \"Jan\", 2 : \"Feb\", 3 : \"Mar\", 4 : \"Apr\",\r\n 5 : \"May\", 6 : \"Jun\", 7 : \"Jul\", 8 : \"Aug\",\r\n 9 : \"Sep\", 10 : \"Oct\", 11 : \"Nov\", 12 : \"Dec\"}\r\n })\r\n\r\n# replacing NA's in variables #TODO: doublecheck this section\r\ntrain.loc[:, \"Alley\"] = train.loc[:, \"Alley\"].fillna(\"None\")\r\n# BedroomAbvGr : NA most likely means 0\r\ntrain.loc[:, \"BedroomAbvGr\"] = train.loc[:, \"BedroomAbvGr\"].fillna(0)\r\n# BsmtQual etc : data description says NA for basement features is \"no basement\"\r\ntrain.loc[:, \"BsmtQual\"] = train.loc[:, \"BsmtQual\"].fillna(\"No\")\r\ntrain.loc[:, \"BsmtCond\"] = train.loc[:, \"BsmtCond\"].fillna(\"No\")\r\ntrain.loc[:, \"BsmtExposure\"] = train.loc[:, \"BsmtExposure\"].fillna(\"No\")\r\ntrain.loc[:, \"BsmtFinType1\"] = train.loc[:, \"BsmtFinType1\"].fillna(\"No\")\r\ntrain.loc[:, \"BsmtFinType2\"] = train.loc[:, \"BsmtFinType2\"].fillna(\"No\")\r\ntrain.loc[:, \"BsmtFullBath\"] = train.loc[:, \"BsmtFullBath\"].fillna(0)\r\ntrain.loc[:, \"BsmtHalfBath\"] = train.loc[:, \"BsmtHalfBath\"].fillna(0)\r\ntrain.loc[:, \"BsmtUnfSF\"] = train.loc[:, \"BsmtUnfSF\"].fillna(0)\r\n# CentralAir : NA most likely means No\r\ntrain.loc[:, \"CentralAir\"] = train.loc[:, \"CentralAir\"].fillna(\"N\")\r\n# Condition : NA most likely means Normal\r\ntrain.loc[:, \"Condition1\"] = train.loc[:, \"Condition1\"].fillna(\"Norm\")\r\ntrain.loc[:, \"Condition2\"] = train.loc[:, \"Condition2\"].fillna(\"Norm\")\r\n# EnclosedPorch : NA most likely means no enclosed porch\r\ntrain.loc[:, \"EnclosedPorch\"] = train.loc[:, \"EnclosedPorch\"].fillna(0)\r\n# External stuff : NA most likely means average\r\ntrain.loc[:, \"ExterCond\"] = train.loc[:, \"ExterCond\"].fillna(\"TA\")\r\ntrain.loc[:, \"ExterQual\"] = train.loc[:, \"ExterQual\"].fillna(\"TA\")\r\n# Fence : data description says NA means \"no fence\"\r\ntrain.loc[:, \"Fence\"] = train.loc[:, \"Fence\"].fillna(\"No\")\r\n# FireplaceQu : data description says NA means \"no fireplace\"\r\ntrain.loc[:, \"FireplaceQu\"] = train.loc[:, \"FireplaceQu\"].fillna(\"No\")\r\ntrain.loc[:, \"Fireplaces\"] = train.loc[:, \"Fireplaces\"].fillna(0)\r\n# Functional : data description says NA means typical\r\ntrain.loc[:, \"Functional\"] = train.loc[:, \"Functional\"].fillna(\"Typ\")\r\n# GarageType etc : data description says NA for garage features is \"no garage\"\r\ntrain.loc[:, \"GarageType\"] = train.loc[:, \"GarageType\"].fillna(\"No\")\r\ntrain.loc[:, \"GarageFinish\"] = train.loc[:, \"GarageFinish\"].fillna(\"No\")\r\ntrain.loc[:, \"GarageQual\"] = train.loc[:, \"GarageQual\"].fillna(\"No\")\r\ntrain.loc[:, \"GarageCond\"] = train.loc[:, \"GarageCond\"].fillna(\"No\")\r\ntrain.loc[:, \"GarageArea\"] = train.loc[:, \"GarageArea\"].fillna(0)\r\ntrain.loc[:, \"GarageCars\"] = train.loc[:, \"GarageCars\"].fillna(0)\r\n# HalfBath : NA most likely means no half baths above grade\r\ntrain.loc[:, \"HalfBath\"] = train.loc[:, \"HalfBath\"].fillna(0)\r\n# HeatingQC : NA most likely means typical\r\ntrain.loc[:, \"HeatingQC\"] = train.loc[:, \"HeatingQC\"].fillna(\"TA\")\r\n# KitchenAbvGr : NA most likely means 0\r\ntrain.loc[:, \"KitchenAbvGr\"] = train.loc[:, \"KitchenAbvGr\"].fillna(0)\r\n# KitchenQual : NA most likely means typical\r\ntrain.loc[:, \"KitchenQual\"] = train.loc[:, \"KitchenQual\"].fillna(\"TA\")\r\n# LotFrontage : NA most likely means no lot frontage\r\ntrain.loc[:, \"LotFrontage\"] = train.loc[:, \"LotFrontage\"].fillna(0)\r\n# LotShape : NA most likely means regular\r\ntrain.loc[:, \"LotShape\"] = train.loc[:, \"LotShape\"].fillna(\"Reg\")\r\n# MasVnrType : NA most likely means no veneer\r\ntrain.loc[:, \"MasVnrType\"] = train.loc[:, \"MasVnrType\"].fillna(\"None\")\r\ntrain.loc[:, \"MasVnrArea\"] = train.loc[:, \"MasVnrArea\"].fillna(0)\r\n# MiscFeature : data description says NA means \"no misc feature\"\r\ntrain.loc[:, \"MiscFeature\"] = train.loc[:, \"MiscFeature\"].fillna(\"No\")\r\ntrain.loc[:, \"MiscVal\"] = train.loc[:, \"MiscVal\"].fillna(0)\r\n# OpenPorchSF : NA most likely means no open porch\r\ntrain.loc[:, \"OpenPorchSF\"] = train.loc[:, \"OpenPorchSF\"].fillna(0)\r\n# PavedDrive : NA most likely means not paved\r\ntrain.loc[:, \"PavedDrive\"] = train.loc[:, \"PavedDrive\"].fillna(\"N\")\r\n# PoolQC : data description says NA means \"no pool\"\r\ntrain.loc[:, \"PoolQC\"] = train.loc[:, \"PoolQC\"].fillna(\"No\")\r\ntrain.loc[:, \"PoolArea\"] = train.loc[:, \"PoolArea\"].fillna(0)\r\n# SaleCondition : NA most likely means normal sale\r\ntrain.loc[:, \"SaleCondition\"] = train.loc[:, \"SaleCondition\"].fillna(\"Normal\")\r\n# ScreenPorch : NA most likely means no screen porch\r\ntrain.loc[:, \"ScreenPorch\"] = train.loc[:, \"ScreenPorch\"].fillna(0)\r\n# TotRmsAbvGrd : NA most likely means 0\r\ntrain.loc[:, \"TotRmsAbvGrd\"] = train.loc[:, \"TotRmsAbvGrd\"].fillna(0)\r\n# Utilities : NA most likely means all public utilities\r\ntrain.loc[:, \"Utilities\"] = train.loc[:, \"Utilities\"].fillna(\"AllPub\")\r\n# WoodDeckSF : NA most likely means no wood deck\r\ntrain.loc[:, \"WoodDeckSF\"] = train.loc[:, \"WoodDeckSF\"].fillna(0)\r\n\r\n# recoding ordinal variables ## TODO: doublecheck this section\r\ntrain = train.replace({\"Alley\" : {\"Grvl\" : 1, \"Pave\" : 2},\r\n \"BsmtCond\" : {\"No\" : 0, \"Po\" : 1, \"Fa\" : 2, \"TA\" : 3,\r\n \"Gd\" : 4, \"Ex\" : 5},\r\n \"BsmtExposure\" : {\"No\" : 0, \"Mn\" : 1, \"Av\": 2, \"Gd\" : 3},\r\n \"BsmtFinType1\" : {\"No\" : 0, \"Unf\" : 1, \"LwQ\": 2, \"Rec\" : 3,\r\n \"BLQ\" : 4, \"ALQ\" : 5, \"GLQ\" : 6},\r\n \"BsmtFinType2\" : {\"No\" : 0, \"Unf\" : 1, \"LwQ\": 2, \"Rec\" : 3,\r\n \"BLQ\" : 4, \"ALQ\" : 5, \"GLQ\" : 6},\r\n \"BsmtQual\" : {\"No\" : 0, \"Po\" : 1, \"Fa\" : 2, \"TA\": 3, \"Gd\" : 4, \"Ex\" : 5},\r\n \"ExterCond\" : {\"Po\" : 1, \"Fa\" : 2, \"TA\": 3, \"Gd\": 4, \"Ex\" : 5},\r\n \"ExterQual\" : {\"Po\" : 1, \"Fa\" : 2, \"TA\": 3, \"Gd\": 4, \"Ex\" : 5},\r\n \"FireplaceQu\" : {\"No\" : 0, \"Po\" : 1, \"Fa\" : 2, \"TA\" : 3,\r\n \"Gd\" : 4, \"Ex\" : 5},\r\n \"Functional\" : {\"Sal\" : 1, \"Sev\" : 2, \"Maj2\" : 3, \"Maj1\" : 4,\r\n \"Mod\": 5, \"Min2\" : 6, \"Min1\" : 7, \"Typ\" : 8},\r\n \"GarageCond\" : {\"No\" : 0, \"Po\" : 1, \"Fa\" : 2, \"TA\" : 3,\r\n \"Gd\" : 4, \"Ex\" : 5},\r\n \"GarageQual\" : {\"No\" : 0, \"Po\" : 1, \"Fa\" : 2, \"TA\" : 3,\r\n \"Gd\" : 4, \"Ex\" : 5},\r\n \"HeatingQC\" : {\"Po\" : 1, \"Fa\" : 2, \"TA\" : 3, \"Gd\" : 4, \"Ex\" : 5},\r\n \"KitchenQual\" : {\"Po\" : 1, \"Fa\" : 2, \"TA\" : 3, \"Gd\" : 4, \"Ex\" : 5},\r\n \"LandSlope\" : {\"Sev\" : 1, \"Mod\" : 2, \"Gtl\" : 3},\r\n \"LotShape\" : {\"IR3\" : 1, \"IR2\" : 2, \"IR1\" : 3, \"Reg\" : 4},\r\n \"PavedDrive\" : {\"N\" : 0, \"P\" : 1, \"Y\" : 2},\r\n \"PoolQC\" : {\"No\" : 0, \"Fa\" : 1, \"TA\" : 2, \"Gd\" : 3, \"Ex\" : 4},\r\n \"Street\" : {\"Grvl\" : 1, \"Pave\" : 2},\r\n \"Utilities\" : {\"ELO\" : 1, \"NoSeWa\" : 2, \"NoSewr\" : 3, \"AllPub\" : 4}}\r\n )\r\n\r\n\r\n# creating combined quality variables\r\ntrain[\"OverallScore\"] = train[\"OverallQual\"] + train[\"OverallCond\"]\r\ntrain[\"GarageScore\"] = train[\"GarageQual\"] + train[\"GarageCond\"]\r\ntrain[\"ExterScore\"] = train[\"ExterQual\"] + train[\"ExterCond\"]\r\ntrain[\"TotalSqFt\"] = train[\"GrLivArea\"] + train[\"TotalBsmtSF\"]\r\ntrain[\"TotalBathrooms\"] = train[\"BsmtFullBath\"] + (0.5 * train[\"BsmtHalfBath\"]) + train[\"FullBath\"] + (0.5 * train[\"HalfBath\"])\r\n\r\n# splitting DataFrame into categorical and numeric features for easier manipulation\r\ncategorical = train.select_dtypes(include = \"object\").columns\r\ntrain_cat = train[categorical]\r\nnumerical = train.select_dtypes(exclude = \"object\").columns\r\ntrain_num = train[numerical]\r\n\r\n# filling numerical NA's with median values\r\ntrain_num = train_num.fillna(train_num.median())\r\n\r\n# log transform of skewed numerical variables, using 0.5 as my cutoff\r\nskewness = train_num.apply(lambda x: skew(x))\r\nskewness = skewness[abs(skewness) > 0.5]\r\nskewness = skewness.index\r\ntrain_num[skewness] = np.log1p(train_num[skewness])\r\n# normal np.log throwing errors, have to use np.log1p, which adds one and then\r\n# does the log, which avoids the 'divide by zero' error\r\n\r\n# using StandardScaler to get all the numerical variables on the same scale\r\nscaler = StandardScaler()\r\ntrain_num[:] = scaler.fit_transform(train_num[:])\r\n# have to use the [:] notation to keep the column names and such, otherwise the scaling will turn it into an array\r\n\r\n# turning categorical variables into dummy variables\r\n# couldn't get linear regression to work without converting\r\ntrain_cat = pd.get_dummies(train_cat)\r\n\r\n# putting together categorical and numerical after dropping SalePrice before analysis\r\ntrain_num = train_num.drop(\"SalePrice\", axis = 1)\r\ntrain = pd.concat([train_num, train_cat], axis = 1)\r\n\r\n# 70/30 train / test split for cross validation\r\nx_train, x_test, y_train, y_test = train_test_split(train, SalePrice_train, test_size = 0.3)\r\n\r\n\r\n# RMSE calculation\r\ndef rmse(pred_val, true_val):\r\n rmse = np.sqrt(mean_squared_error(true_val, pred_val))\r\n return(rmse)\r\n\r\n\r\n# linear regression on the training set\r\nlin = LinearRegression()\r\nlin.fit(x_train, y_train)\r\nlin_predicted_values = lin.predict(x_train)\r\nrmse(lin_predicted_values, y_train) # 0.088334\r\nlin_predicted_values = lin.predict(x_test)\r\nrmse(lin_predicted_values, y_test) # super high value, may be overfitted\r\n\r\n# ridge regression\r\nridge = RidgeCV(alphas = [0.01, 0.1, 0.5, 1, 5, 10, 25, 50, 75, 100])\r\nridge.fit(x_train, y_train)\r\nrid_predicted_values = ridge.predict(x_train)\r\nrmse(rid_predicted_values, y_train) # 0.100268\r\nrid_predicted_values = ridge.predict(x_test)\r\nrmse(rid_predicted_values, y_test) # 0.157455\r\n\r\n# elastic net\r\nelast = ElasticNetCV(alphas = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1])\r\nelast.fit(x_train, y_train)\r\nela_predicted_values = elast.predict(x_train)\r\nrmse(ela_predicted_values, y_train) # 0.15485\r\nela_predicted_values = elast.predict(x_test)\r\nrmse(ela_predicted_values, y_test) # 0.16907\r\n\r\n# random forest\r\nrndfrst = RandomForestRegressor(n_estimators=100, max_features=\"log2\", n_jobs=-1)\r\nrndfrst.fit(x_train, y_train)\r\nrndfrst_predicted_values = rndfrst.predict(x_train)\r\nrmse(rndfrst_predicted_values, y_train) # 0.055047\r\nrndfrst_predicted_values = rndfrst.predict(x_test)\r\nrmse(rndfrst_predicted_values, y_test) # 0.14496\r\n\r\n\r\n\r\n# time to generate predictions for Kaggle\r\ntest = pd.read_csv(\"test.csv\")\r\n\r\ntest = test.replace({\"MSSubClass\" : {20 : \"SC20\", 30 : \"SC30\", 40 : \"SC40\", 45 : \"SC45\", \r\n 50 : \"SC50\", 60 : \"SC60\", 70 : \"SC70\", 75 : \"SC75\", \r\n 80 : \"SC80\", 85 : \"SC85\", 90 : \"SC90\", 120 : \"SC120\", \r\n 150 : \"SC150\", 160 : \"SC160\", 180 : \"SC180\", 190 : \"SC190\"},\r\n \"MoSold\" : {1 : \"Jan\", 2 : \"Feb\", 3 : \"Mar\", 4 : \"Apr\",\r\n 5 : \"May\", 6 : \"Jun\", 7 : \"Jul\", 8 : \"Aug\",\r\n 9 : \"Sep\", 10 : \"Oct\", 11 : \"Nov\", 12 : \"Dec\"}\r\n })\r\n\r\n# replacing NA's in variables #TODO: doublecheck this section\r\ntest.loc[:, \"Alley\"] = test.loc[:, \"Alley\"].fillna(\"None\")\r\n# BedroomAbvGr : NA most likely means 0\r\ntest.loc[:, \"BedroomAbvGr\"] = test.loc[:, \"BedroomAbvGr\"].fillna(0)\r\n# BsmtQual etc : data description says NA for basement features is \"no basement\"\r\ntest.loc[:, \"BsmtQual\"] = test.loc[:, \"BsmtQual\"].fillna(\"No\")\r\ntest.loc[:, \"BsmtCond\"] = test.loc[:, \"BsmtCond\"].fillna(\"No\")\r\ntest.loc[:, \"BsmtExposure\"] = test.loc[:, \"BsmtExposure\"].fillna(\"No\")\r\ntest.loc[:, \"BsmtFinType1\"] = test.loc[:, \"BsmtFinType1\"].fillna(\"No\")\r\ntest.loc[:, \"BsmtFinType2\"] = test.loc[:, \"BsmtFinType2\"].fillna(\"No\")\r\ntest.loc[:, \"BsmtFullBath\"] = test.loc[:, \"BsmtFullBath\"].fillna(0)\r\ntest.loc[:, \"BsmtHalfBath\"] = test.loc[:, \"BsmtHalfBath\"].fillna(0)\r\ntest.loc[:, \"BsmtUnfSF\"] = test.loc[:, \"BsmtUnfSF\"].fillna(0)\r\n# CentralAir : NA most likely means No\r\ntest.loc[:, \"CentralAir\"] = test.loc[:, \"CentralAir\"].fillna(\"N\")\r\n# Condition : NA most likely means Normal\r\ntest.loc[:, \"Condition1\"] = test.loc[:, \"Condition1\"].fillna(\"Norm\")\r\ntest.loc[:, \"Condition2\"] = test.loc[:, \"Condition2\"].fillna(\"Norm\")\r\n# EnclosedPorch : NA most likely means no enclosed porch\r\ntest.loc[:, \"EnclosedPorch\"] = test.loc[:, \"EnclosedPorch\"].fillna(0)\r\n# External stuff : NA most likely means average\r\ntest.loc[:, \"ExterCond\"] = test.loc[:, \"ExterCond\"].fillna(\"TA\")\r\ntest.loc[:, \"ExterQual\"] = test.loc[:, \"ExterQual\"].fillna(\"TA\")\r\n# Fence : data description says NA means \"no fence\"\r\ntest.loc[:, \"Fence\"] = test.loc[:, \"Fence\"].fillna(\"No\")\r\n# FireplaceQu : data description says NA means \"no fireplace\"\r\ntest.loc[:, \"FireplaceQu\"] = test.loc[:, \"FireplaceQu\"].fillna(\"No\")\r\ntest.loc[:, \"Fireplaces\"] = test.loc[:, \"Fireplaces\"].fillna(0)\r\n# Functional : data description says NA means typical\r\ntest.loc[:, \"Functional\"] = test.loc[:, \"Functional\"].fillna(\"Typ\")\r\n# GarageType etc : data description says NA for garage features is \"no garage\"\r\ntest.loc[:, \"GarageType\"] = test.loc[:, \"GarageType\"].fillna(\"No\")\r\ntest.loc[:, \"GarageFinish\"] = test.loc[:, \"GarageFinish\"].fillna(\"No\")\r\ntest.loc[:, \"GarageQual\"] = test.loc[:, \"GarageQual\"].fillna(\"No\")\r\ntest.loc[:, \"GarageCond\"] = test.loc[:, \"GarageCond\"].fillna(\"No\")\r\ntest.loc[:, \"GarageArea\"] = test.loc[:, \"GarageArea\"].fillna(0)\r\ntest.loc[:, \"GarageCars\"] = test.loc[:, \"GarageCars\"].fillna(0)\r\n# HalfBath : NA most likely means no half baths above grade\r\ntest.loc[:, \"HalfBath\"] = test.loc[:, \"HalfBath\"].fillna(0)\r\n# HeatingQC : NA most likely means typical\r\ntest.loc[:, \"HeatingQC\"] = test.loc[:, \"HeatingQC\"].fillna(\"TA\")\r\n# KitchenAbvGr : NA most likely means 0\r\ntest.loc[:, \"KitchenAbvGr\"] = test.loc[:, \"KitchenAbvGr\"].fillna(0)\r\n# KitchenQual : NA most likely means typical\r\ntest.loc[:, \"KitchenQual\"] = test.loc[:, \"KitchenQual\"].fillna(\"TA\")\r\n# LotFrontage : NA most likely means no lot frontage\r\ntest.loc[:, \"LotFrontage\"] = test.loc[:, \"LotFrontage\"].fillna(0)\r\n# LotShape : NA most likely means regular\r\ntest.loc[:, \"LotShape\"] = test.loc[:, \"LotShape\"].fillna(\"Reg\")\r\n# MasVnrType : NA most likely means no veneer\r\ntest.loc[:, \"MasVnrType\"] = test.loc[:, \"MasVnrType\"].fillna(\"None\")\r\ntest.loc[:, \"MasVnrArea\"] = test.loc[:, \"MasVnrArea\"].fillna(0)\r\n# MiscFeature : data description says NA means \"no misc feature\"\r\ntest.loc[:, \"MiscFeature\"] = test.loc[:, \"MiscFeature\"].fillna(\"No\")\r\ntest.loc[:, \"MiscVal\"] = test.loc[:, \"MiscVal\"].fillna(0)\r\n# OpenPorchSF : NA most likely means no open porch\r\ntest.loc[:, \"OpenPorchSF\"] = test.loc[:, \"OpenPorchSF\"].fillna(0)\r\n# PavedDrive : NA most likely means not paved\r\ntest.loc[:, \"PavedDrive\"] = test.loc[:, \"PavedDrive\"].fillna(\"N\")\r\n# PoolQC : data description says NA means \"no pool\"\r\ntest.loc[:, \"PoolQC\"] = test.loc[:, \"PoolQC\"].fillna(\"No\")\r\ntest.loc[:, \"PoolArea\"] = test.loc[:, \"PoolArea\"].fillna(0)\r\n# SaleCondition : NA most likely means normal sale\r\ntest.loc[:, \"SaleCondition\"] = test.loc[:, \"SaleCondition\"].fillna(\"Normal\")\r\n# ScreenPorch : NA most likely means no screen porch\r\ntest.loc[:, \"ScreenPorch\"] = test.loc[:, \"ScreenPorch\"].fillna(0)\r\n# TotRmsAbvGrd : NA most likely means 0\r\ntest.loc[:, \"TotRmsAbvGrd\"] = test.loc[:, \"TotRmsAbvGrd\"].fillna(0)\r\n# Utilities : NA most likely means all public utilities\r\ntest.loc[:, \"Utilities\"] = test.loc[:, \"Utilities\"].fillna(\"AllPub\")\r\n# WoodDeckSF : NA most likely means no wood deck\r\ntest.loc[:, \"WoodDeckSF\"] = test.loc[:, \"WoodDeckSF\"].fillna(0)\r\n\r\n# recoding ordinal variables ## TODO: doublecheck this section\r\ntest = test.replace({\"Alley\" : {\"Grvl\" : 1, \"Pave\" : 2},\r\n \"BsmtCond\" : {\"No\" : 0, \"Po\" : 1, \"Fa\" : 2, \"TA\" : 3,\r\n \"Gd\" : 4, \"Ex\" : 5},\r\n \"BsmtExposure\" : {\"No\" : 0, \"Mn\" : 1, \"Av\": 2, \"Gd\" : 3},\r\n \"BsmtFinType1\" : {\"No\" : 0, \"Unf\" : 1, \"LwQ\": 2, \"Rec\" : 3,\r\n \"BLQ\" : 4, \"ALQ\" : 5, \"GLQ\" : 6},\r\n \"BsmtFinType2\" : {\"No\" : 0, \"Unf\" : 1, \"LwQ\": 2, \"Rec\" : 3,\r\n \"BLQ\" : 4, \"ALQ\" : 5, \"GLQ\" : 6},\r\n \"BsmtQual\" : {\"No\" : 0, \"Po\" : 1, \"Fa\" : 2, \"TA\": 3, \"Gd\" : 4, \"Ex\" : 5},\r\n \"ExterCond\" : {\"Po\" : 1, \"Fa\" : 2, \"TA\": 3, \"Gd\": 4, \"Ex\" : 5},\r\n \"ExterQual\" : {\"Po\" : 1, \"Fa\" : 2, \"TA\": 3, \"Gd\": 4, \"Ex\" : 5},\r\n \"FireplaceQu\" : {\"No\" : 0, \"Po\" : 1, \"Fa\" : 2, \"TA\" : 3,\r\n \"Gd\" : 4, \"Ex\" : 5},\r\n \"Functional\" : {\"Sal\" : 1, \"Sev\" : 2, \"Maj2\" : 3, \"Maj1\" : 4,\r\n \"Mod\": 5, \"Min2\" : 6, \"Min1\" : 7, \"Typ\" : 8},\r\n \"GarageCond\" : {\"No\" : 0, \"Po\" : 1, \"Fa\" : 2, \"TA\" : 3,\r\n \"Gd\" : 4, \"Ex\" : 5},\r\n \"GarageQual\" : {\"No\" : 0, \"Po\" : 1, \"Fa\" : 2, \"TA\" : 3,\r\n \"Gd\" : 4, \"Ex\" : 5},\r\n \"HeatingQC\" : {\"Po\" : 1, \"Fa\" : 2, \"TA\" : 3, \"Gd\" : 4, \"Ex\" : 5},\r\n \"KitchenQual\" : {\"Po\" : 1, \"Fa\" : 2, \"TA\" : 3, \"Gd\" : 4, \"Ex\" : 5},\r\n \"LandSlope\" : {\"Sev\" : 1, \"Mod\" : 2, \"Gtl\" : 3},\r\n \"LotShape\" : {\"IR3\" : 1, \"IR2\" : 2, \"IR1\" : 3, \"Reg\" : 4},\r\n \"PavedDrive\" : {\"N\" : 0, \"P\" : 1, \"Y\" : 2},\r\n \"PoolQC\" : {\"No\" : 0, \"Fa\" : 1, \"TA\" : 2, \"Gd\" : 3, \"Ex\" : 4},\r\n \"Street\" : {\"Grvl\" : 1, \"Pave\" : 2},\r\n \"Utilities\" : {\"ELO\" : 1, \"NoSeWa\" : 2, \"NoSewr\" : 3, \"AllPub\" : 4}}\r\n )\r\n\r\n\r\n# creating combined quality variables\r\ntest[\"OverallScore\"] = test[\"OverallQual\"] + test[\"OverallCond\"]\r\ntest[\"GarageScore\"] = test[\"GarageQual\"] + test[\"GarageCond\"]\r\ntest[\"ExterScore\"] = test[\"ExterQual\"] + test[\"ExterCond\"]\r\ntest[\"TotalSqFt\"] = test[\"GrLivArea\"] + test[\"TotalBsmtSF\"]\r\ntest[\"TotalBathrooms\"] = test[\"BsmtFullBath\"] + (0.5 * test[\"BsmtHalfBath\"]) + test[\"FullBath\"] + (0.5 * test[\"HalfBath\"])\r\n\r\n\r\n# splitting DataFrame into categorical and numeric features for easier manipulation\r\ncategorical = test.select_dtypes(include = \"object\").columns\r\ntest_cat = test[categorical]\r\nnumerical = test.select_dtypes(exclude = \"object\").columns\r\ntest_num = test[numerical]\r\n\r\n# filling numerical NA's with median values\r\ntest_num = test_num.fillna(test_num.median())\r\n\r\n# log transform of skewed numerical variables, using 0.5 as my cutoff\r\nskewness = test_num.apply(lambda x: skew(x))\r\nskewness = skewness[abs(skewness) > 0.5]\r\nskewness = skewness.index\r\ntest_num[skewness] = np.log1p(test_num[skewness])\r\n# normal np.log throwing errors, have to use np.log1p, which adds one and then\r\n# does the log, which avoids the 'divide by zero' error\r\n\r\n# using StandardScaler to get all the numerical variables on the same scale\r\nscaler = StandardScaler()\r\ntest_num[:] = scaler.fit_transform(test_num[:])\r\n# have to use the [:] notation to keep the column names and such, otherwise the scaling will turn it into an array\r\n\r\n# turning categorical variables into dummy variables\r\n# couldn't get linear regression to work without converting\r\ntest_cat = pd.get_dummies(test_cat)\r\n\r\n# putting together categorical and numerical after dropping SalePrice before analysis\r\ntest = pd.concat([test_num, test_cat], axis = 1)\r\n\r\n# Adding columns to test that are not present in train so that our predictions below will have the same shape\r\ntest_cols_to_add = train.columns.difference(test.columns)\r\ntest_cols_to_add = test_cols_to_add[:-2]\r\ntest = test.reindex(columns=[*test.columns.tolist(), *test_cols_to_add], fill_value=0)\r\n\r\n\r\n# still hitting the same error since the columns aren't in the same order\r\n# lin_predicted_values = pd.DataFrame(lin.predict(test))\r\n# lin_predicted_values = np.exp(rid_predicted_values)\r\n# temp_for_Id_values = pd.read_csv(\"test.csv\")\r\n# lin_predicted_values[\"Id\"] = temp_for_Id_values[\"Id\"]\r\n# lin_predicted_values.columns = [\"SalePrice\", \"Id\"]\r\n# lin_predicted_values = lin_predicted_values[[\"Id\", \"SalePrice\"]]\r\n# lin_predicted_values.to_csv(\"linear_predictions.csv\")\r\n\r\ntemp_for_Id_values = pd.read_csv(\"test.csv\")\r\n\r\nrid_predicted_values = pd.DataFrame(ridge.predict(test))\r\nrid_predicted_values = np.exp(rid_predicted_values)\r\nrid_predicted_values[\"Id\"] = temp_for_Id_values[\"Id\"]\r\nrid_predicted_values.columns = [\"SalePrice\", \"Id\"]\r\nrid_predicted_values = rid_predicted_values[[\"Id\", \"SalePrice\"]]\r\nrid_predicted_values.to_csv(\"ridge_predictions.csv\")\r\n\r\nela_predicted_values = pd.DataFrame(elast.predict(test))\r\nela_predicted_values = np.exp(ela_predicted_values)\r\nela_predicted_values[\"Id\"] = temp_for_Id_values[\"Id\"]\r\nela_predicted_values.columns = [\"SalePrice\", \"Id\"]\r\nela_predicted_values = ela_predicted_values[[\"Id\", \"SalePrice\"]]\r\nela_predicted_values.to_csv(\"elastic_net_predictions.csv\")\r\n\r\nrf_predicted_values = pd.DataFrame(rndfrst.predict(test))\r\nrf_predicted_values = np.exp(rf_predicted_values)\r\nrf_predicted_values[\"Id\"] = temp_for_Id_values[\"Id\"]\r\nrf_predicted_values.columns = [\"SalePrice\", \"Id\"]\r\nrf_predicted_values = rf_predicted_values[[\"Id\", \"SalePrice\"]]\r\nrf_predicted_values.to_csv(\"random_forest_predictions.csv\")\r\n\r\n","sub_path":"Assignment 4 - SB.py","file_name":"Assignment 4 - SB.py","file_ext":"py","file_size_in_byte":22517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"505774432","text":"#This tree really only makes sense for numeric data values\n#is there a way to force input in python?\n#stores equal data to the left\n\n######________DEFINE THE TREE CLASS_______######\nclass BinaryTree:\n def __init__(self):\n self.root = None\n \n def clear(self):\n if(self.root != None):\n self.root = None\n \n def insert_node(self, data):\n aNode = Node(data)\n if(self.root == None):\n self.root = aNode\n self.root.parent = None\n else:\n self.root.insert_node(aNode)\n \n def bulk_insert_nodes(self, datum):\n for i in datum:\n self.insert_node(i)\n\n def report_root(self):\n if(self.root == None):\n print(\"The tree is empty\")\n else:\n print(\"The root node is:\", str(self.root.data))\n if(self.root.right != None):\n print(\"root.right is:\", str(self.root.right.data))\n if(self.root.left != None):\n print(\"root.left is:\", str(self.root.left.data)) \n\n def report_depth_first(self):\n if(self.root == None):\n print(\"The list is empty\")\n else:\n self.root.report_depth_first()\n\n def contains(self, data): #depth first\n if(self.root == None):\n return False\n else:\n return self.root.contains(data)\n\n def delete(self, data):\n if(self.root == None):\n print(\"The tree is empty\") \n elif(self.root.data == data):\n #The root has no children\n if(self.root.right == None and self.root.left == None):\n self.root = None\n #One child (right)\n elif(self.root.right != None and self.root.left == None):\n newRoot = self.root.right\n newRoot.parent = None\n self.root = newRoot\n #One child (left)\n elif(self.root.right == None and self.root.left != None):\n newRoot = self.root.left\n newRoot.parent = None\n self.root = newRoot\n #Two children (tricky)\n else:\n #find the left most child of the parent's right child\n newRoot = self.root.right\n connectRoot = self.root.right\n while(connectRoot.left != None):\n connectRoot = connectRoot.left\n #go about making this the new root node with the left side of the tree as its child\n self.root.left.parent = connectRoot\n connectRoot.left = self.root.left\n newRoot.parent = None\n self.root = newRoot\n #The tree has data and it's not the root\n else:\n self.root.delete(data)\n\n######________DEFINE THE NODE CLASS_______######\nclass Node:\n def __init__(self, data):\n self.data = data\n self.right = None\n self.left = None\n self.parent = None\n\n def insert_node(self, node):\n if(node.data > self.data):\n if(self.right == None):\n self.right = node\n self.right.parent = self\n else:\n self.right.insert_node(node)\n #the case where data is less than self.data\n else:\n if(self.left == None):\n self.left = node\n self.left.parent = self\n else:\n self.left.insert_node(node)\n \n def report_depth_first(self):\n print(str(self.data))\n #recursively head all the way left of each node\n if(self.left != None):\n self.left.report_depth_first()\n #and then go right for each node\n if(self.right != None):\n self.right.report_depth_first()\n\n def contains(self, data): #returns true or false\n if(self.data == data):\n print(\"The tree contains:\", data)\n else:\n if(data > self.data):\n if(self.right != None):\n self.right.contains(data)\n else:\n if(self.left != None):\n self.left.contains(data)\n\n #as it stands this method cannot be called on the root\n def delete(self, data):\n #Four Cases:\n #The node is a leaf: WORKS CORRECTLY\n if(self.data == data and (self.left == None and self.right == None)):\n if(data > self.parent.data):\n self.parent.right = None\n else:\n self.parent.left = None\n \n \n #The node has a right child WORKS CORRECTLY\n elif(self.data == data and (self.left == None and self.right != None)):\n parentNode = self.parent\n rightNode = self.right\n parentNode.right = self.right\n rightNode.parent = parentNode\n\n #The node has a left child WORKS CORRECTLY\n elif(self.data == data and (self.left != None and self.right == None)):\n parentNode = self.parent\n leftNode = self.left\n parentNode.left = self.left\n leftNode.parent = parentNode\n\n #The node has a left and right child (tricky) [going to be like root delete but have to handle parent]\n elif(self.data == data and (self.right != None and self.left != None)):\n #requires declaring three nodes to delete it\n parentNode = self.parent\n rightNode = self.right\n connectNode = self.right\n while(connectNode.left != None):\n connectNode = connectNode.left\n #bring up the right node\n rightNode.parent = self.parent\n #attach it to the left\n connectNode.left = self.left\n #finish removing it from the list\n parentNode.right = self.right\n \n #it's not the right node, keep calling delete until it is\n else:\n if(data > self.data):\n if(self.right != None):\n self.right.delete(data)\n else:\n if(self.left != None):\n self.left.delete(data)\n\n\n######________TESTING THE CLASSES_______######\nif(__name__ == '__main__'):\n print(\"TESTING BINARY TREE FUNCTIONS:\")\n tree = BinaryTree()\n numbers = [25, 4,80,7,6,234,34,16,1,4,9,10] #8 ones\n tree.bulk_insert_nodes(numbers)\n tree.report_depth_first()\n tree.report_root()\n for i in numbers:\n tree.contains(i)\n tree.clear()\n tree.report_depth_first()\n tree.bulk_insert_nodes([8,7,6,5])\n print(\"******************************\")\n tree.report_depth_first()\n tree.delete(6)\n print(\"******************************\")\n tree.report_depth_first()\n print(\"******************************\")\n tree.report_root()\n tree.clear()\n print(\"******************************\")\n tree.bulk_insert_nodes([2,3])\n tree.report_depth_first()\n print(\"******************************\")\n tree.delete(3)\n tree.report_depth_first()\n tree.report_root()\n print(\"******************************\")\n tree.insert_node(1)\n tree.report_depth_first()\n tree.delete(1)\n tree.report_root()\n print(\"******************************\")\n tree.report_depth_first()\n tree.clear()\n print(\"******************************\")\n #make a new tree to test deleting a root with two children\n testnums = [10,18,6,20,16,15,4]\n tree.bulk_insert_nodes(testnums)\n tree.report_depth_first()\n tree.delete(10)\n print(\"******************************\")\n tree.report_depth_first()\n tree.report_root()\n print(\"******************************\")\n #make a tree to test node with parent and two children deletion\n tree.clear()\n testnumstwo = [10,18,20,19,16,15,6,4]\n tree.bulk_insert_nodes(testnumstwo)\n tree.report_depth_first()\n tree.delete(18)\n tree.delete(10)\n print(\"******************************\")\n tree.report_depth_first()\n\n\n\n","sub_path":"BinaryTree/BinaryTree.py","file_name":"BinaryTree.py","file_ext":"py","file_size_in_byte":7919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"453568675","text":"from sqlalchemy import Column, Integer, String, ForeignKey\nfrom sqlalchemy.dialects.postgresql import ARRAY\nfrom sqlalchemy.ext.associationproxy import association_proxy\nfrom sqlalchemy.orm import relationship, backref\n\nfrom uchan.lib.database import ModelBase\nfrom uchan.lib.models import MutableList\n\n\ndef create_moderator_for_proxy(moderator):\n board_moderator = BoardModerator()\n board_moderator.moderator = moderator\n board_moderator.roles = []\n return board_moderator\n\n\nclass Board(ModelBase):\n __tablename__ = 'board'\n\n id = Column(Integer(), primary_key=True)\n name = Column(String(128), unique=True, index=True, nullable=False)\n refno_counter = Column(Integer(), nullable=False, default=1)\n config_id = Column(Integer, ForeignKey('config.id'), nullable=False, index=True)\n\n config = relationship('Config', cascade='all')\n threads = relationship('Thread', backref='board', cascade='all, delete-orphan')\n logs = relationship('ModeratorLog', backref='board')\n\n moderators = association_proxy('board_moderators', 'moderator', creator=create_moderator_for_proxy)\n\n\nclass BoardModerator(ModelBase):\n __tablename__ = 'boardmoderator'\n\n board_id = Column(Integer, ForeignKey('board.id'), primary_key=True)\n moderator_id = Column(Integer, ForeignKey('moderator.id'), primary_key=True)\n\n roles = Column(MutableList.as_mutable(ARRAY(String)), index=True, nullable=False)\n\n board = relationship(Board, backref=backref('board_moderators', cascade='all, delete-orphan'))\n moderator = relationship('Moderator', backref=backref('board_moderators', cascade='all, delete-orphan'))\n","sub_path":"uchan/lib/models/board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"66482353","text":"from socket import *\nfrom codecs import decode\n\n\"\"\"\nClient for obtaining the day and time.\n\"\"\"\n\nHOST = 'localhost'\nPORT = 5000\nBUFSIZE = 1024\nADDRESS = (HOST, PORT)\n\nserver = socket(AF_INET, SOCK_STREAM) #Create a socket\nserver.connect(ADDRESS) #Connect it to a host\ndayAndTime = decode(server.recv(BUFSIZE), 'ascii') #Read and decode a string\nprint(dayAndTime) \nserver.close() #Close the connection\n","sub_path":"Fundamentals of Python - Chapter 10/clientsocket.py","file_name":"clientsocket.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"495099447","text":"#!/usr/bin/env python\n# Custom i3blocks python script for displaying network ip, ssid, and \n# wifi signal when connected to a network via ethernet or wifi\n#\n# Config proper device names\n###########################\nwirelessDevice = 'wifi0' #\nethernetDevice = 'net0' #\n###########################\nfrom subprocess import check_output\nimport re\nfile=open('/sys/class/net/' + wirelessDevice + '/operstate')\nwifiState = file.read().split('\\n')[0];\nfile.close()\nfile=open('/sys/class/net/' + ethernetDevice + '/operstate')\nethState = file.read().split('\\n')[0];\nfile.close()\n# If wifi is up we get its ip and ssid\nif wifiState == 'up':\n\taux = check_output(['ip', 'addr', 'show', wirelessDevice], universal_newlines=True)\n\twifiIp = '<uncknown ip>'\n\tmatch = re.search(r'inet ([0-9]*\\.[0-9]*\\.[0-9]*\\.[0-9]*)/', aux)\n\tif match:\n\t\twifiIp = match.group(1);\n\taux = check_output(['nmcli', '-t', '-f', 'active,ssid', 'dev', 'wifi'], universal_newlines=True)\n\twifiSsid = '<uncknown ssid>'\n\tmatch = re.search('(sí|yes):(.*)', aux)\n\tif match:\n\t\twifiSsid = match.group(2);\n\taux = check_output(['nmcli', '-t', '-f', 'active,signal', 'dev', 'wifi'], universal_newlines=True)\n\twifiSignal = 0\n\tmatch = re.search('(sí|yes):([0-9]*\\n)', aux)\n\tif match:\n\t\twifiSignal = int(match.group(2));\n# If eth link is up we get its ip\nif ethState == 'up':\n\taux = check_output(['ip', 'addr', 'show', ethernetDevice], universal_newlines=True)\n\tmatch = re.search('inet ([0-9]*\\.[0-9]*\\.[0-9]*\\.[0-9]*)/', aux)\n\tif match:\n\t\tethIp = match.group(1);\noutput=''\ndef color(percent):\n\tif percent < 10:\n\t\treturn \"#FFFFFF\"\n\tif percent < 20:\n\t\treturn \"#FF0000\"\n\tif percent < 30:\n\t\treturn \"#FF3300\"\n\tif percent < 40:\n\t\treturn \"#FF6600\"\n\tif percent < 50:\n\t\treturn \"#FF9900\"\n\tif percent < 60:\n\t\treturn \"#FFCC00\"\n\tif percent < 70:\n\t\treturn \"#FFFF00\"\n\tif percent < 80:\n\t\treturn \"#CCFF00\"\n\treturn \"#00FF00\"\nif (wifiState == 'down') & (ethState == 'down'):\n\toutput = '\\uf00d NOT CONNECTED'\nif wifiState == 'up':\n\toutput += '\\uf1eb {} ({}%) {}'.format(wifiSsid, color(wifiSignal), wifiSignal, wifiIp)\nif ethState == 'up':\n\toutput += '\\uf0ec {}'.format(ethIp)\n\nprint(output)","sub_path":"i3blocks-scripts/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":2277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"145061494","text":"import requests\nimport sys\n\nthe_url = str(sys.argv[1])\nf_name = str(sys.argv[2])\nr = requests.get(the_url)\n\nwith open(f_name, 'w', encoding=\"utf-8\") as f:\n f.write(\"The status of the HTTP request is: \" + \"\\n\" + str(r.status_code) + \"\\n\\n\")\n f.write(\"This is what is contained in the body: \" + \"\\n\" + str(r.content))\n","sub_path":"internet-programming/submission-hw-5/assignment-5.py","file_name":"assignment-5.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"645256159","text":"from pymongo import MongoClient\n\nmyclient = MongoClient('mongodb://localhost:27017/')\ndb = myclient['Diabetes_database']\nDiabetes_user = db['user_details']\nDiabetes_prediction = db['prediction_details']\n\ndef save_diabetes_details(Pregnancies,Glucose,BloodPressure,SkinThickness,Insulin,BMI,DiabetesPedigreeFunction,Age):\n diabetes_patient_details = {\"Pregnancies\": Pregnancies, \"Glucose\":Glucose,\"BloodPressure\":BloodPressure,\n \"SkinThickness\": SkinThickness,\"Insulin\":Insulin,\"BMI\":BMI,'DiabetesPedigreeFunction':DiabetesPedigreeFunction,\"Age\":Age}\n Diabetes_prediction.insert(diabetes_patient_details)\n\n return \"Saved Successfully\"","sub_path":"diabetes_db.py","file_name":"diabetes_db.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"582387980","text":"data = {\n \"variant\": {\n \"id\": 808950810,\n \"product_id\": 632910392,\n \"title\": \"Pink\",\n \"price\": \"199.00\",\n \"sku\": \"IPOD2008PINK\",\n \"position\": 1,\n \"inventory_policy\": \"continue\",\n \"compare_at_price\": \"\",\n \"fulfillment_service\": \"manual\",\n \"inventory_management\": \"shopify\",\n \"option1\": \"Pink\",\n \"option2\": \"\",\n \"option3\": \"\",\n \"created_at\": \"2020-05-22T14:26:11-04:00\",\n \"updated_at\": \"2020-05-22T14:26:11-04:00\",\n \"taxable\": True,\n \"barcode\": \"1234_pink\",\n \"grams\": 567,\n \"image_id\": 562641783,\n \"weight\": 1.25,\n \"weight_unit\": \"lb\",\n \"inventory_item_id\": 808950810,\n \"inventory_quantity\": 10,\n \"old_inventory_quantity\": 10,\n \"tax_code\": \"DA040000\",\n \"requires_shipping\": True,\n \"admin_graphql_api_id\": \"gid://shopify/ProductVariant/808950810\",\n \"presentment_prices\": [\n {\n \"price\": {\n \"currency_code\": \"USD\",\n \"amount\": \"199.00\"\n },\n \"compare_at_price\": \"\"\n }\n ]\n }\n}","sub_path":"EzeeShip/API/shopify/ProductVariant.py","file_name":"ProductVariant.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"199879424","text":"def onHear(event):\n potion = pet.findNearestByType(\"potion\")\n message = event.message\n if message == \"Fetch\":\n pet.fetch(potion)\n else:\n pet.moveXY(54, 34)\n\npet.on(\"hear\", onHear);\n\nwhile True:\n enemies = hero.findEnemies()\n\n # Fix for weak hero\n maxim = 0\n strongest = None\n for enemy in enemies:\n if enemy.health > maxim:\n maxim = enemy.health\n strongest = enemy\n if strongest:\n while strongest.health > 0:\n hero.attack(strongest)\n else:\n hero.moveXY(40, 34)\n","sub_path":"7_Sarven_Desert/343-Alchemic_Power/alchemic_power.py","file_name":"alchemic_power.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"421729158","text":"# -*- encoding: utf-8 -*-\n\"\"\"\nAuthor: Yousab Maged\nDate: 21,Oct 2019\n\"\"\"\n\nfrom math import *\nimport pandas as pd\n\n\nclass BiSection:\n\n fn = ''\n\n #fn is the f(x) which is a form input\n def __init__(self, fn):\n self.fn = fn\n\n # Evaluate f(x)\n def f(self, x):\n #return (667.38/x)*(1-exp(-0.145843*x))-40\n return eval(self.fn)\n\n #Generate table values in (x,y) points, Get x lower and x upper\n #x param is the initial x from a form input\n #s param is the x incrementer step\n def generate_table(self, x, s):\n returnedValues = dict()\n table_dict={}\n fx, fx_old = 0, 0\n while fx*fx_old >= 0:\n fx_old = fx\n fx = self.f(x)\n table_dict[x] = self.f(x)\n x = x+s\n returnedValues['xl'] = x-2*s\n returnedValues['xu'] = x-s\n returnedValues['table'] = table_dict\n return returnedValues\n #bisect(xl, xu, 0.000001)\n\n def bisect_iter(self,xl,xu,iMax):\n iter=0\n while iter <= iMax:\n xm = (xl+xu)/2\n fl= self.f(xl)\n fm = self.f(xm)\n test = fl * fm\n if test < 0:\n xu = xm\n elif test > 0:\n xl = xm\n else:\n break\n iter = iter +1\n xr = xm\n return xr\n\n def bisect_error(self,xl,xu,eValue):\n iter=0\n xm_old=0\n while True:\n xm = (xl+xu)/2\n if abs(xm - xm_old) >= eValue:\n fl=self.f(xl)\n fm = self.f(xm)\n test = fl * fm\n if test < 0:\n xu = xm\n elif test > 0:\n xl = xm\n else:\n break\n iter = iter +1\n else:\n break\n xr = xm\n return xr\n\n #Apply the bisect algorithm\n #xl is the lower x bound value\n #xu is the upper x bound value\n def bisect(self,xl, xu, es):\n while True:\n xm = (xl+xu)/2\n fl = self.f(xl)\n fm = self.f(xm)\n test = fl * fm\n if test < 0:\n xu = xm\n elif test > 0:\n xl = xm\n else:\n break\n xr = xm\n return xr\n","sub_path":"app/algos.py","file_name":"algos.py","file_ext":"py","file_size_in_byte":2327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"10311295","text":"#!/usr/bin/env python3\n#\n# Usage:\n# zcat ${candidate_file} | python download_candidates.py --langs en,${fr_lang} | gzip -c > ${OUTPUT_FILE}\n#\n\nimport argparse\nimport base64\nimport json\nimport os\nimport sys\nfrom multiprocessing import Pool, context\n\nfrom tqdm import tqdm\n\nimport langid\nfrom ccdownloader import CCDownloader\nfrom html2text import html2text\n\nsys.path.append(\"{0}/..\".format(os.path.dirname(os.path.realpath(__file__))))\nfrom utils.textsanitzer import TextSanitizer\n\nCOMMONCRAWL_S3_URL = \"https://commoncrawl.s3.amazonaws.com/\"\n\n\ndef find_header_uri(header):\n for line in header.split(\"\\n\"):\n if line.startswith(\"WARC-Target-URI\"):\n return line.split()[1:][0].strip()\n\n\ndef download_and_process(uri):\n try:\n # parse\n file_range, file_url = uri.split(\"@\", 1)\n file_url = COMMONCRAWL_S3_URL + file_url\n\n # download the content and convert to plaintext\n downloader = CCDownloader()\n res = downloader.download(\n file_url, file_range, timeout=60, html_only=True)\n if not res:\n return \"\"\n\n html, header = res\n plain = html2text(html)\n langid_lang = langid.classify(plain)[0].lower()\n langid_lang2 = TextSanitizer.guess_lang_from_data2(\n html, is_html=True).lower()\n\n # skip if the detected language is not accepted\n if langid_lang not in accepted_languages or langid_lang2 not in accepted_languages:\n return \"\"\n\n # lett format\n encoded_html = base64.b64encode(\n \"undefined\".encode('utf-8')).decode('utf-8')\n encoded_plain = base64.b64encode(plain.encode('utf-8')).decode('utf-8')\n lett = \"{0}\\ttext/html\\tcharset=utf-8\\t{1}\\t{2}\\t{3}\".format(\n langid_lang, uri, encoded_html, encoded_plain)\n\n return \"{0}\\t{1}\".format(find_header_uri(header), lett)\n\n except Exception as e:\n sys.stderr.write(\"Error: {0}; Skipping: {1}\\n\".format(e, uri))\n return \"\"\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Download frequent domains.')\n parser.add_argument('--candidates', dest='candidates',\n help='candidate file', required=False)\n parser.add_argument('--langs', dest='langs',\n help='comma-separated list of accepted languages', required=True)\n parser.add_argument('--poolsize', dest='poolsize',\n help='Pool size for downloading', required=False, default=10)\n parser.add_argument('--infodir', dest='infodir',\n help='Saves url mapping info into this dir', required=False, default='.')\n args = parser.parse_args()\n\n sys.stderr.write(\"Pool size: {0}\\n\".format(args.poolsize))\n\n accepted_languages = list(map(lambda x: x.lower(), args.langs.split(',')))\n\n if args.candidates:\n # find number of lines\n candidate_lines = None\n with open(args.candidates) as f:\n candidate_lines = sum([1 for _ in f])\n sys.stderr.write(\n \"{0} candidates to process...\\n\".format(candidate_lines))\n\n pbar = None\n if args.candidates:\n candidate_file = open(args.candidates, 'r')\n else:\n candidate_file = sys.stdin\n\n for line in candidate_file:\n line_obj = json.loads(line)\n\n with tqdm(total=len(line_obj['uri'])) as pbar:\n results = []\n with Pool(int(args.poolsize)) as p:\n for uri in line_obj['uri']:\n r = p.apply_async(download_and_process,\n (uri,), callback=lambda x: pbar.update(1))\n results.append(r)\n\n with open(os.path.join(args.infodir, 'urlinfo'), 'w') as f:\n for idx, r in enumerate(results):\n try:\n output = r.get(timeout=60)\n except context.TimeoutError:\n continue\n\n if output:\n uri, text = output.split('\\t', 1)\n print(text)\n f.write(\"{0}\\t{1}\\n\".format(\n line_obj['uri'][idx], uri))\n\n if args.candidates:\n candidate_file.close()\n\n sys.stderr.write(\"Done.\\n\")\n","sub_path":"experimental/commoncrawl/download_candidates.py","file_name":"download_candidates.py","file_ext":"py","file_size_in_byte":4308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"57965400","text":"#!/usr/bin/env python\n\nfrom flask import jsonify, g\nfrom itsdangerous import (TimedJSONWebSignatureSerializer\n as Serializer, BadSignature, SignatureExpired)\nfrom sqlalchemy import *\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import relationship\nfrom .app import CApp\nimport md5\nimport datetime\n\n\nclass CDatabase(object):\n _DB_PATH_PATTERN = 'mysql+mysqldb://root:%s@%s/%s?charset=utf8'\n _DB_PATH = None\n _ENGINE = None\n\n @classmethod\n def init(cls, address, name, password):\n cls._DB_PATH = cls._DB_PATH_PATTERN % (password, address, name)\n cls._ENGINE = create_engine(cls._DB_PATH, echo=False)\n\n @classmethod\n def get_engine(cls):\n if not cls._ENGINE:\n cls._ENGINE = create_engine(cls._DB_PATH, echo=False)\n return cls._ENGINE\n\n @classmethod\n def get_session(cls):\n if not cls._ENGINE:\n cls._ENGINE = create_engine(cls._DB_PATH, echo=False)\n return Session(cls._ENGINE)\n\nCDatabase.init('localhost', 'okno', 'adminq1!')\nmetadata = MetaData(bind=CDatabase.get_engine())\nBase = automap_base()\nBase.prepare(CDatabase.get_engine(), reflect=True)\n\nclass TUser(declarative_base()): #-> specjalnosc_id\n __table__ = Table('uzytkownik', metadata, autoload=True)\n\n def generate_auth_token(self, expiration = 3600*30):\n s = Serializer(CApp().get_app().config['SECRET_KEY'], expires_in = expiration)\n return s.dumps({ 'id': self.uzytkownik_id,\n 'name': self.imie_1,\n 'lastname': self.nazwisko,\n 'email': self.email,\n 'phone': self.telefon,\n 'birth': '%s' % self.data_urodzenia,\n 'active': self.aktywny,\n 'login': self.login })\n\n @staticmethod\n def verify_auth_token(token):\n s = Serializer(CApp().get_app().config['SECRET_KEY'])\n try:\n data = s.loads(token)\n except SignatureExpired:\n return None\n except BadSignature:\n return None\n try:\n session = CDatabase.get_session()\n user = session.query(TUser).get(data['id'])\n finally:\n session.close()\n return user\n\n def verify_password(self, password):\n hash_ = md5.new()\n hash_.update(password)\n return self.haslo == hash_.hexdigest()\n\nTStudent = Base.classes.student_dodatkowe #uzytkownik_id, wydzial_id, specjalnosc_id\nTDepartment = Base.classes.sl_wydzial #nazwa\nTSpeciality = Base.classes.specjalnosc #nazwa, wydzial_id\nTSpeciality2Plan = Base.classes.specjalnosc_plan #specjalnosc_id -> plan_id\nTPlan = Base.classes.plan #nazwa\nTSubject2Plan = Base.classes.plan_pozycja #przedmiot_id -> plan_id, ects\nTSubject = Base.classes.przedmiot\n\nTGeneralAnnounce = Base.classes.ogloszenie_ogolne\nTConstAnnounce = Base.classes.ogloszenie_stale\nTCalendar = Base.classes.kalendarz_pozycja\nTYear = Base.classes.sl_rok_akademicki\n\nTEmployee = Base.classes.pracownik_dodatkowe\n\nclass TPeriod(declarative_base()):\n __table__ = Table('obc_okres', metadata, autoload=True)\n\n @staticmethod\n def find_current():\n date = datetime.datetime.now()\n return TPeriod.find(date)\n \n @staticmethod\n def find(date):\n session = CDatabase.get_session()\n try:\n return session.query(TPeriod).\\\n filter(TPeriod.data_od <= date).\\\n filter(TPeriod.data_do >= date).\\\n first().rok_akademicki_id\n finally:\n session.close()\n \nclass TSubjectEdition(declarative_base()):\n __table__ = Table('przedmiot_edycja', metadata, autoload=True)\n\n @staticmethod\n def get_current_edition(subject_id):\n session = CDatabase.get_session()\n try:\n academic_year = TPeriod.find_current()\n return session.query(TSubjectEdition).\\\n filter(TSubjectEdition.przedmiot_id == subject_id).\\\n filter(TSubjectEdition.rok_akademicki_id == academic_year).\\\n first().przedmiot_edycja_id\n finally:\n session.close()\n\nclass TSubjectEdition2Student(declarative_base()):\n __table__ = Table('przedmiot_edycja_student', metadata, autoload=True)\n \n @staticmethod\n def save(subject_edition_id, user_id):\n session = CDatabase.get_session()\n try:\n record = TSubjectEdition2Student(przedmiot_edycja_id=subject_edition_id,\n uzytkownik_id=user_id,\n data_zapisu=datetime.datetime.now())\n session.add(record)\n session.flush()\n session.commit()\n finally:\n session.close() \n\n","sub_path":"common/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":4888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"558491653","text":"from django.http import HttpResponse\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nimport sqlite3\nfrom polls.registerform import UserForm,UserProfileForm,InterestsForm\nfrom polls.misc_functions import mail,random_num, tablechk, intrchk\nfrom polls.models import ProfilePicture,UserProfile\nimport json,datetime\nfrom django.contrib.sessions.models import Session\nimport time\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\n\notp=0\nResponse=''\n\n\n\n\n\ndef register(request):\n registered = False\n\n\n # If it's a HTTP POST, we're interested in processing form data\n print('chk0')\n if request.method == 'POST':\n if request.POST.get('emailid')!='0':\n eidstr= request.POST.get('emailid')\n else:\n eidstr= request.POST.get('emailid2')\n vara= tablechk('polls_userprofile','emailid', eidstr )\n if(vara==1):\n\n print(\"alpha\"+str(vara))\n if request.POST.get('emailid')!='0':\n ajaxstr='chk1'\n # print(ajaxstr)\n user_form = UserForm(data=request.POST)\n\n # print('chk2')\n response_dict={}\n\n\n if request.POST.get('password') == request.POST.get('conpassword'):\n\n if vara==1:\n\n print(\"kutta\")\n otpstr=mail(request.POST.get('emailid'))\n\n message='mail sent'\n str1= request.POST.get('emailid')\n print(\"ert\"+otpstr+str1)\n\n\n # Save the user's form data to the database.\n user = user_form.save()\n # Now we hash the password with the set_password method.\n # Once hashed, we can update the user object.\n #user.password(user.password)\n user.save()\n conn = sqlite3.connect('db.sqlite3')\n cursor=conn.cursor()\n cursor.execute('''UPDATE polls_users SET otp = ? where emailid = ? ''',(otpstr,str1))\n cursor.close()\n conn.commit()\n ajaxstr=\"Email sent\"\n registered= True\n response_dict.update({'resp1' : ajaxstr, 'gamma' : 0})\n\n return HttpResponse(json.dumps(response_dict),content_type='application/javascript')\n\n else:\n ajaxstr='Email id already registered'\n response_dict.update({'resp1' : ajaxstr,'gamma':0})\n return HttpResponse(json.dumps(response_dict))\n else:\n return HttpResponse(\"Password don't match\")\n\n else :\n response_dict={}\n gamma=0\n response_dict.update({'gamma':gamma, 'resp1': 'Email has been sent'})\n return HttpResponse(json.dumps(response_dict),content_type='application/javascript')\n else:\n response_dict={}\n gamma=1\n if(request.POST.get('emailid')==request.POST.get('emailid2')):\n response_dict.update({'gamma':gamma, 'resp1': 'Email id already registered'})\n else :\n response_dict.update({'gamma':gamma, 'resp1': 'Chal gaya', })\n return HttpResponse(json.dumps(response_dict),content_type='application/javascript')\n\n # Not a HTTP POST, so we render our form using two ModelForm instances.\n # These forms will be blank, ready for user input.\n else:\n user_form = UserForm()\n user_profileform = UserProfileForm()\n ajaxstr='Email has been sent4545'\n print(ajaxstr)\n\n # Render the template depending on the context.\n return render_to_response('polls/registerform.html',{'user_form': user_form,'user_profileform' : user_profileform ,'registered':registered},context_instance=RequestContext(request))\n\ndef ajax(request):\n if ('client_response') in request.POST:\n x = request.POST['client_response']\n if(otp==int(x)):\n # print (otp)\n Response='True'\n else:\n Response='False'\n\n response_dict = {'Response':Response}\n return HttpResponse(json.dumps(response_dict), content_type='application/javascript')\n else:\n return render_to_response('registerform.html', context_instance=RequestContext(request))\n\ndef transfer_details(request,eid,otp):\n\n conn = sqlite3.connect('db.sqlite3')\n cursor=conn.cursor()\n cursor.execute('''Select emailid from polls_users where emailid = ? and otp = ?''',(eid,otp))\n conn.commit()\n emailid_final=cursor.fetchone()\n cursor.execute('''Select password from polls_users where emailid = ? and otp = ?''',(eid,otp))\n conn.commit()\n password_final=cursor.fetchone()\n cursor.execute('''Select college from polls_users where emailid = ? and otp = ?''',(eid,otp))\n conn.commit()\n college_final=cursor.fetchone()\n cursor.execute('''Select username from polls_users where emailid = ? and otp = ?''',(eid,otp))\n username_final=cursor.fetchone()\n conn.commit()\n cursor.execute('''DELETE FROM polls_users where emailid = ?''', (eid,))\n conn.commit()\n\n\n cursor.execute('''INSERT INTO polls_userprofile (emailid, password, college,username) values(?,?,?,?)''',(emailid_final[0],password_final[0],college_final[0],username_final[0]))\n conn.commit()\n # if request.session.get('last_visit'):\n #\n # # The session has a value for the last visit\n # last_visit_time = request.session.get('last_visit')\n # visits = request.session.get('visits', 0)\n # if (datetime.now() - datetime.strptime(last_visit_time[:-7], \"%Y-%m-%d %H:%M:%S\")).days > 0:\n # request.session['visits'] = visits + 1\n # request.session['last_visit'] = str(datetime.now())\n # new_sessionid=request.session._get_new_session_key()\n # cursor.execute('''INSERT INTO polls_global (emailid, username, sessionid,is_loggedin) values(?,?,?,?)''',(emailid_final[0],username_final[0],new_sessionid ,True))\n\n\n # else:\n # The get returns None, and the session does not have a value for the last visit.\n request.session['last_visit'] = str(time.strftime(\"%H:%M:%S\"))\n request.session['visits'] = 1\n request.session['eid']=eid\n request.session['otp']=otp\n new_sessionid=request.session._get_new_session_key()\n cursor.execute('''INSERT INTO polls_global (emailid, username, sessionid,is_loggedin) values(?,?,?,?)''',(emailid_final[0],username_final[0],new_sessionid ,True))\n conn.commit()\n user_profileform= UserProfileForm()\n #if request.session.has_key('last_visit'):\n\n return render_to_response('polls/registerform.html',{'user_form': user_profileform, 'eid' : eid, 'otp' : otp},context_instance=RequestContext(request))\n\n\n\ndef register2(request,eid,otp):\n if request.method=='POST':\n userprofile_form=UserProfileForm(request.POST, request.FILES)\n if userprofile_form.is_valid():\n firstname=request.POST['firstname']\n lastname=request.POST['lastname']\n dob=request.POST['dob']\n gender=request.POST['gender']\n fathername=request.POST['fathername']\n permaadd=request.POST['permaadd']\n contact=request.POST['contact']\n if 'picture' in request.FILES:\n userprofile_form.picture=request.FILES['picture']\n\n new=ProfilePicture(emailid=eid, picture=userprofile_form.picture)\n new.save()\n conn = sqlite3.connect('db.sqlite3')\n cursor=conn.cursor()\n cursor.execute('''UPDATE polls_userprofile SET firstname=? , lastname=? ,dob=?, gender=?,fathername=?,permaadd=?,contact =? where emailid = ? ''',(firstname,lastname,dob,gender,fathername,permaadd,contact,eid,))\n print ('alpha')\n conn.commit()\n interest_form=InterestsForm()\n return render_to_response('polls/interestform.html',{'interest_form': interest_form, 'eid' : eid, 'otp' : otp},context_instance=RequestContext(request))\n\n else:\n # Invalid form or forms - mistakes or something else?\n # Print problems to the terminal.\n # They'll also be shown to the user. \n return HttpResponse(userprofile_form.errors)\n\n else:\n userprofile_form = UserProfileForm()\n\n # Render the template depending on the context.\n return render_to_response('polls/userprofileform.html',{'userprofile_form': userprofile_form},context_instance=RequestContext(request))\n\n\n\ndef register3(request,eid,otp):\n if request.method=='POST':\n interest_form=InterestsForm(data=request.POST)\n if interest_form.is_valid():\n interest1=request.POST['interest1']\n interest2=request.POST['interest2']\n interest3=request.POST['interest3']\n interest4=request.POST['interest4']\n interest5=request.POST['interest5']\n interest1=str(interest1)\n interest2=str(interest2)\n interest3=str(interest3)\n interest4=str(interest4)\n interest5=str(interest5)\n conn=sqlite3.connect('db.sqlite3')\n\n cursor=conn.cursor()\n cursor.execute('''UPDATE polls_userprofile SET interest1=?,interest2=?,interest3=?,interest4=?,interest5=? where emailid=? ''',(intrchk(interest1),intrchk(interest2),intrchk(interest3),intrchk(interest4),intrchk(interest5),eid,))\n conn.commit()\n\n return HttpResponse(\" \"+str(interest1))\n else :\n return HttpResponse(interest_form.errors)\n\n else:\n interest_form=InterestsForm()\n\n\n\n\n # Render the template depending on the context.\n return render_to_response('polls/interestform.html',{'interest_form': interest_form},context_instance=RequestContext(request))\n\ndef func1(request):\n conn=sqlite3.connect('db.sqlite3')\n cursor=conn.cursor()\n cursor.execute('''UPDATE polls_userprofile set interest1=? where emailid=?''',(intrchk(1),'vsandstorm0@gmail.com',))\n conn.commit()\n\n return HttpResponse(\"qwe\")\n\ndef test(request):\n return render_to_response('polls/quizm.htm',context_instance=RequestContext(request))\n\ndef quizcrtab(request):\n conn=sqlite3.connect('db.sqlite3')\n cursor=conn.cursor()\n cursor.execute('''CREATE TABLE quiz2 (\n quesno INTEGER PRIMARY KEY AUTOINCREMENT,\n ques TEXT NOT NULL,\n options INTEGER NOT NULL,\n opt1 TEXT NOT NULL,\n opt2 TEXT NOT NULL,\n opt3 TEXT NOT NULL,\n opt4 TEXT NOT NULL,\n opt5 TEXT NOT NULL,\n opt6 TEXT NOT NULL,\n opt7 TEXT NOT NULL,\n opt8 TEXT NOT NULL,\n opt9 TEXT NOT NULL,\n opt10 TEXT NOT NULL,\n ans TEXT NOT NULL\n )''')\n conn.commit()\n\n return HttpResponse(\"qwe\")\n\ndef quizuptab(request):\n if(request.method=='POST'):\n ques=request.POST['ques']\n options=request.POST['nq']\n opt1=request.POST['o1']\n opt2=request.POST['o2']\n opt3=request.POST['o3']\n opt4=request.POST['o4']\n opt5=request.POST['o5']\n opt6=request.POST['o6']\n opt7=request.POST['o7']\n opt8=request.POST['o8']\n opt9=request.POST['o9']\n opt10=request.POST['o10']\n c1=request.POST.get('c1',0)\n c2=request.POST.get('c2',0)\n c3=request.POST.get('c3',0)\n c4=request.POST.get('c4',0)\n c5=request.POST.get('c5',0)\n c6=request.POST.get('c6',0)\n c7=request.POST.get('c7',0)\n c8=request.POST.get('c8',0)\n c9=request.POST.get('c9',0)\n c10=request.POST.get('c10',0)\n if(c1!=0):\n c1='1'\n if(c2!=0):\n c2='1'\n if(c3!=0):\n c3='1'\n if(c4!=0):\n c4='1'\n if(c5!=0):\n c5='1'\n if(c6!=0):\n c6='1'\n if(c7!=0):\n c7='1'\n if(c8!=0):\n c8='1'\n if(c9!=0):\n c9='1'\n if(c10!=0):\n c10='1'\n ans=str(c1)+str(c2)+str(c3)+str(c4)+str(c5)+str(c6)+str(c7)+str(c8)+str(c9)+str(c10)\n conn=sqlite3.connect('db.sqlite3')\n cursor=conn.cursor()\n print(\"chala\")\n cursor.execute('''INSERT INTO quiz2 (ques,options,opt1,opt2,opt3,opt4,opt5,opt6,opt7,opt8,opt9,opt10,ans) values(?,?,?,?,?,?,?,?,?,?,?,?,?)''',(ques,options,opt1,opt2,opt3,opt4,opt5,opt6,opt7,opt8,opt9,opt10,ans))\n conn.commit()\n cursor.execute('''Select ques from quiz2 ''')\n conn.commit()\n qarray=cursor.fetchall()\n\n tabname='quiz2'\n cursor.execute(\" Select Count (*) from \"+tabname)\n conn.commit()\n up=cursor.fetchone()\n i=[0]*up[0]\n arrayq=[\"\"]*(up[0]+1)\n print(up[0])\n for k in range(0,up[0]):\n arrayq[k]=qarray[k][0]\n i[k]=k\n return render_to_response('polls/quizm.htm',{\"qarray\":arrayq,\"limits\":i,\"up\":up[0]},context_instance=RequestContext(request))\n #return HttpResponse(\"Baad diya\")\n\n\n else:\n conn=sqlite3.connect('db.sqlite3')\n cursor=conn.cursor()\n cursor.execute('''Select ques from quiz2 ''')\n conn.commit()\n qarray=cursor.fetchall()\n tabname='quiz2'\n cursor.execute(\" Select Count (*) from \"+tabname)\n conn.commit()\n up=cursor.fetchone()\n i=[0]*up[0]\n arrayq=[\"\"]*(up[0]+1)\n #print(up[0])\n for k in range(0,up[0]):\n arrayq[k]=qarray[k][0]\n i[k]=k\n #print(arrayq[1][0])\n return render_to_response('polls/quizm.htm',{\"qarray\":arrayq,\"limits\":i,\"up\":up[0]},context_instance=RequestContext(request))\n #return render_to_response('polls/quizm.htm',context_instance=RequestContext(request))\n\n\ndef editq(request):\n if(request.method==\"POST\"):\n pry=request.POST.get(\"qid\")\n pry1=pry[1:]\n pry2=int(pry1)+1\n print(pry2)\n conn=sqlite3.connect('db.sqlite3')\n cursor=conn.cursor()\n cursor.execute('''Select ques from quiz2 where quesno = ?''',(pry2,) )\n conn.commit()\n quesa=cursor.fetchone()\n ques=quesa[0]\n option=[\"\"]*11\n cursor.execute('''Select opt1,opt2,opt3,opt4,opt5,opt6,opt7,opt8,opt9,opt10 from quiz2 where quesno = ?''',(pry2,) )\n conn.commit()\n clap=cursor.fetchall()\n print(clap[0][1])\n for i in range(1,11):\n option[i]=clap[0][i-1]\n cursor.execute('''Select options from quiz2 where quesno = ?''',(pry2,) )\n conn.commit()\n print(option)\n noptionsa=cursor.fetchone()\n noptions=noptionsa[0]\n cursor.execute('''Select ans from quiz2 where quesno = ?''',(pry2,) )\n conn.commit()\n ansa=cursor.fetchone()\n ans=ansa[0]\n print(ans)\n response_dict={}\n #response_dict.update({'ques':ques,'id':pry2, 'noptions':noptions, 'ans':ans,'opt1': option[1], 'opt2': option[2], 'opt3': option[3], 'opt4': option[4], 'opt5': option[5], 'opt6': option[6], 'opt7': option[7], 'opt8': option[8], 'opt9': option[9], 'opt10': option[10], })\n response_dict.update({'ques':ques,'id':pry2, 'noptions':noptions, 'ans':ans, 'option': option})\n return HttpResponse(json.dumps(response_dict),content_type='application/javascript')\n","sub_path":"sarvasv 27-7/untitled2/polls/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":15185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"300621653","text":"\"\"\"\nPlot TSR versus Cp\n\nUNFINISHED*** couldn't figure out how to set rotor speed to constant\n\"\"\"\nimport sys\nlibpath = 'C:\\\\Users\\\\jrinker\\\\Documents\\\\GitHub\\\\dissertation'\nif (libpath not in sys.path): sys.path.append(libpath)\n\nimport JR_Library.main as jr\nimport numpy as np\nimport os, json\n\n# define TSRs, wind speed to analyze\nTSRs = np.linspace(7,8,2)\nwind_speed = 8.0\nTMax = 10.0\nrho = 1.225\n\n# set pitch angle to analyze\nTName = 'WP1.5A08V03'\n\n# specify the directory to write the files to\nturb_dir = os.path.join('C:\\\\Users\\\\jrinker\\\\Documents\\\\GitHub\\\\' + \\\n 'dissertation\\\\FAST_models\\\\FAST7',TName)\n\n# load turbine model\nfTDictName = os.path.join(turb_dir,'parameters',TName+'_Dict.dat')\nwith open(fTDictName,'r') as f:\n TurbDict = json.load(f)\n \n# set pitch angle to analyze\nBldPitch = TurbDict['Rotor']['MinPitchAng']\nRotorRad = TurbDict['Rotor']['RotDiam']/2.\nGenRPM = TurbDict['Nacelle']['RatedGenRPM']\n\n# set wind speed directory, filename\nwind_dir = 'C:\\\\Users\\\\jrinker\\\\Documents\\\\GitHub\\\\' + \\\n 'dissertation\\\\FAST_models\\\\wind_files'\nwind_fname = 'NoShr_'+'{:.1f}'.format(wind_speed).zfill(4)+'.wnd'\nfileID = ''\n\nos.chdir(turb_dir)\n\n# loop through TSRs\nCps = np.empty(TSRs.shape)\nfor i_u in range(len(TSRs)):\n \n # calculate rotor speed\n TSR = TSRs[i_u]\n RotSpeed = TSR*wind_speed/RotorRad*(30./np.pi)\n \n # write FAST file\n jr.writeFASTFiles(turb_dir,TName,wind_fname,wind_speed,\n wind_dir=wind_dir,fileID=fileID,TMax=TMax,GenDOF='False')\n \n # run FAST\n fname = os.path.join(turb_dir,TName)\n os.system('FAST.exe '+fname+'.fst')\n \n # load FAST file\n FAST = jr.ReadFASTFile(fname+'.out')\n \n # get generator power\n GenPwr = np.mean(FAST['Data'][:,FAST['Fields'].index('GenPwr')][-20:])\n \n # calculate and save cp value\n Cp = GenPwr/(0.5*rho*np.pi*(RotorRad**2)*wind_speed**3)\n Cps[i_u] = Cp\n \nplt.figure(1)\nplt.clf()\nplt.plot(TSRs,Cps)","sub_path":"FAST_models/WindPACT/code/calc-TSR_vs_Cp.py","file_name":"calc-TSR_vs_Cp.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"322720883","text":"import json\nimport grequests\n\nfrom bs4 import BeautifulSoup\nfrom django.contrib.admin.views.decorators import staff_member_required\nfrom django.http import HttpResponse, HttpResponseForbidden\nfrom django.shortcuts import get_object_or_404\n\nfrom parse.models import Site, SiteTitle\n\n\nREQUESTS_COUNT = 5\n\n\n@staff_member_required\ndef get_titles(request, site_id):\n if request.is_ajax():\n # current Chrome 39.0.2171.99 headers set\n headers = {\n 'Accept-type': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',\n 'Accept-Encoding': 'gzip, deflate, sdch',\n 'Accept-Language': 'ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.99 Safari/537.36',\n }\n\n site = get_object_or_404(Site, id=int(site_id))\n reqs = (grequests.get(site.url, headers=headers, verify=False) for x in range(REQUESTS_COUNT))\n reqs_map = grequests.map(reqs)\n \n total_titles = 0\n requests_sent = len(reqs_map) \n for response in reqs_map:\n if response and response.status_code == 200 and len(response.text):\n soup = BeautifulSoup(response.text) \n title = soup.find('title').text\n # create new title object if all is OK\n if title:\n new_title = SiteTitle(name=title, site=site)\n new_title.save()\n total_titles += 1\n \n response_data = {\n 'status': 'OK',\n 'total_titles': total_titles,\n 'requests_sent': requests_sent,\n }\n return HttpResponse(json.dumps(response_data), content_type=\"application/json\")\n else:\n return HttpResponseForbidden()","sub_path":"project/parse/admin_views.py","file_name":"admin_views.py","file_ext":"py","file_size_in_byte":1874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"406481058","text":"import pandas\nimport numpy as np\nimport csv\n\nw = [-0.03053024 ,-0.02277121 ,0.20342201, -0.22243108, -0.05347607, 0.50973682,\n -0.55534354 , 0.00349552, 1.0865513 ]\n\nb = 1.742024455315198\n\ndf_data = pandas.read_csv(\"./data/PM2.5/test.csv\",header=None,encoding='Big5')\n\ndf_data = df_data[df_data[1] == 'PM2.5']\n\ndata_x = df_data.iloc[:,2:].values.astype(np.float)\ndf_head = df_data.iloc[:,0].values.astype(np.str).tolist()\n\nf = open('./result/PM2.5/test.csv',\"w\",newline='')\nwriter = csv.writer(f)\nwriter.writerow(['id','value'])\n\nfor i in range(len(data_x)):\n x = data_x[i]\n y = np.sum(np.multiply(w,x)) + b\n writer.writerow([df_head[i],y])\n\nf.close()","sub_path":"test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"496494809","text":"import sys\nimport tensorflow.python.platform\nimport numpy as np\n\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.framework import common_shapes\n# pylint: disable=wildcard-import\n# 'Constant' gets imported in the module 'array_ops'.\nfrom tensorflow.python.framework.constant_op import constant\nfrom tensorflow.python.ops import init_ops\nfrom tensorflow.python.ops import variable_scope as vs\nfrom tensorflow.python.ops import gen_gru_ops\n\n\ndef token_sample(ground_truth, token_distribution, sample_prob, seed=0, name=None):\n return gen_gru_ops.token_sample(\n ground_truth, token_distribution, sample_prob, seed=seed, name=name)\n\n@ops.RegisterShape(\"TokenSample\")\ndef _TokenSampleShape(op):\n return [op.inputs[0].get_shape()]\n\nops.NoGradient(\"TokenSample\")\n\n\n@ops.RegisterShape(\"UniformDistributionSampler\")\ndef _UniformDistributionSamplerShape(op):\n batch_size = op.inputs[0].get_shape()[0].value\n return [tensor_shape.TensorShape([batch_size])]\n\nops.NoGradient(\"UniformDistributionSampler\")\n\n\ndef gru_cell(cell_size, sequence_len, h_prev, x, name=None, scope=None, time_idx=None):\n r\"\"\"GRU Cell\n\n Args:\n sequence_len: A `Tensor` of type `int64`.\n h_prev: A `Tensor` of type `float32`.\n x: A `Tensor` of type `float32`.\n cell_size: An `int`.\n name: A name for the operation (optional).\n\n Returns:\n A tuple of `Tensor` objects (r, z, rh, g, h).\n r: A `Tensor` of type `float32`.\n z: A `Tensor` of type `float32`.\n rh: A `Tensor` of type `float32`.\n g: A `Tensor` of type `float32`.\n h: A `Tensor` of type `float32`.\n \"\"\"\n with vs.variable_scope(scope or \"GruCell\"):\n input_size = x.get_shape()[1].value\n\n wxr = vs.get_variable(\"wxr\", [input_size, cell_size])\n whr = vs.get_variable(\"whr\", [cell_size, cell_size])\n wxz = vs.get_variable(\"wxz\", [input_size, cell_size])\n whz = vs.get_variable(\"whz\", [cell_size, cell_size])\n wxh = vs.get_variable(\"wxh\", [input_size, cell_size])\n whh = vs.get_variable(\"whh\", [cell_size, cell_size])\n\n br = vs.get_variable(\"br\", [cell_size], initializer=init_ops.constant_initializer(1.0))\n bz = vs.get_variable(\"bz\", [cell_size], initializer=init_ops.constant_initializer(1.0))\n bh = vs.get_variable(\"bh\", [cell_size], initializer=init_ops.constant_initializer(0.0))\n\n return gen_gru_ops._gru_cell(cell_size=cell_size, sequence_len=sequence_len,\n wxr=wxr, whr=whr, wxz=wxz, whz=whz, wxh=wxh, whh=whh, br=br, bz=bz,\n bh=bh, h_prev=h_prev, x=x, name=name, time_idx=time_idx)\n\n\n@ops.RegisterShape(\"GruCell\")\ndef _GruCellShape(op):\n batch_size = op.inputs[0].get_shape()[0].value\n cell_size = op.get_attr(\"cell_size\")\n\n return [tensorflow.TensorShape([batch_size, cell_size])] * 5\n\n\n@ops.RegisterGradient(\"GruCell\")\ndef _GruCellGrad(op, *grad):\n gru_grads = gen_gru_ops._gru_cell_grad(cell_size=op.get_attr(\"cell_size\"),\n sequence_len=op.inputs[0],\n wxr=op.inputs[1],\n whr=op.inputs[2],\n wxz=op.inputs[3],\n whz=op.inputs[4],\n wxh=op.inputs[5],\n whh=op.inputs[6],\n br=op.inputs[7],\n bz=op.inputs[8],\n bh=op.inputs[9],\n h_prev=op.inputs[10],\n x=op.inputs[11],\n r=op.outputs[0],\n z=op.outputs[1],\n rh=op.outputs[2],\n hh=op.outputs[3],\n h=op.outputs[4],\n dh=grad[4],\n time_idx=op.get_attr(\"time_idx\"))\n\n gru_grads_ = [None]\n for gru_grad in gru_grads:\n if isinstance(gru_grad, list):\n gru_grads_ += gru_grad\n else:\n gru_grads_ += [gru_grad]\n return gru_grads_\n\n\n@ops.RegisterShape(\"GruCellGrad\")\ndef _GruCellGradShape(op):\n batch_size = op.inputs[0].get_shape()[0].value\n input_size = op.inputs[1].get_shape()[0].value\n cell_size = op.get_attr(\"cell_size\")\n\n return [tensor_shape.TensorShape([input_size, cell_size]),\n tensor_shape.TensorShape([cell_size, cell_size])] * 3 + [\n tensor_shape.TensorShape([cell_size])] * 3 + [\n tensor_shape.TensorShape([batch_size, cell_size])] + [\n tensor_shape.TensorShape([batch_size, input_size])]\n\n\ndef gru(cell_size, sequence_len, xs, name=None, scope=None):\n r\"\"\"gru\n\n args:\n sequence_len: a `tensor` of type `int64`.\n cell_size: an `int`.\n xs: a list of at least 1 `tensor` objects of type `float32`.\n name: a name for the operation (optional).\n\n returns:\n a tuple of `tensor` objects (rs, zs, rhs, gs, hs).\n rs: a list with the same number of `tensor` objects as `xs` of `tensor` objects of type `float32`.\n zs: a list with the same number of `tensor` objects as `xs` of `tensor` objects of type `float32`.\n rhs: a list with the same number of `tensor` objects as `xs` of `tensor` objects of type `float32`.\n gs: a list with the same number of `tensor` objects as `xs` of `tensor` objects of type `float32`.\n hs: a list with the same number of `tensor` objects as `xs` of `tensor` objects of type `float32`.\n \"\"\"\n with vs.variable_scope(scope or \"Gru\"):\n input_size = xs[0].get_shape()[1].value\n\n wxr = vs.get_variable(\"wxr\", [input_size, cell_size])\n whr = vs.get_variable(\"whr\", [cell_size, cell_size])\n wxz = vs.get_variable(\"wxz\", [input_size, cell_size])\n whz = vs.get_variable(\"whz\", [cell_size, cell_size])\n wxh = vs.get_variable(\"wxh\", [input_size, cell_size])\n whh = vs.get_variable(\"whh\", [cell_size, cell_size])\n\n br = vs.get_variable(\"br\", [cell_size], initializer=init_ops.constant_initializer(1.0))\n bz = vs.get_variable(\"bz\", [cell_size], initializer=init_ops.constant_initializer(1.0))\n bh = vs.get_variable(\"bh\", [cell_size], initializer=init_ops.constant_initializer(0.0))\n\n return gen_gru_ops._gru(cell_size=cell_size, sequence_len=sequence_len,\n wxr=wxr, whr=whr, wxz=wxz, whz=whz, wxh=wxh, whh=whh, br=br, bz=bz,\n bh=bh, xs=xs, name=name)\n\n\n@ops.RegisterShape(\"Gru\")\ndef _GruShape(op):\n batch_size = op.inputs[0].get_shape()[0].value\n cell_size = op.get_attr(\"cell_size\")\n\n return [tensor_shape.TensorShape([batch_size, cell_size])] * ((len(op.inputs) - 10) * 5)\n\n\n@ops.RegisterShape(\"Sink\")\ndef _SinkShape(op):\n return []\n\n\n@ops.RegisterGradient(\"Gru\")\ndef _GruGrad(op, *grad):\n outputs = zip(*[iter(op.outputs)] * (len(op.outputs) / 5))\n grads = zip(*[iter(grad)] * (len(grad) / 5))\n gru_grads = gen_gru_ops._gru_grad(cell_size=op.get_attr(\"cell_size\"),\n sequence_len=op.inputs[0],\n wxr=op.inputs[1],\n whr=op.inputs[2],\n wxz=op.inputs[3],\n whz=op.inputs[4],\n wxh=op.inputs[5],\n whh=op.inputs[6],\n br=op.inputs[7],\n bz=op.inputs[8],\n bh=op.inputs[9],\n xs=op.inputs[10:],\n rs=outputs[0],\n zs=outputs[1],\n rhs=outputs[2],\n gs=outputs[3],\n hs=outputs[4],\n dhs=grads[4])\n\n gru_grads_ = [None]\n for gru_grad in gru_grads:\n if isinstance(gru_grad, list):\n gru_grads_ += gru_grad\n else:\n gru_grads_ += [gru_grad]\n return gru_grads_\n\n\n@ops.RegisterShape(\"GruGrad\")\ndef _GruGradShape(op):\n batch_size = op.inputs[0].get_shape()[0].value\n input_size = op.inputs[1].get_shape()[0].value\n cell_size = op.get_attr(\"cell_size\")\n\n return [tensor_shape.TensorShape([input_size, cell_size]),\n tensor_shape.TensorShape([cell_size, cell_size])] * 3 + [\n tensor_shape.TensorShape([cell_size])] * 3 + [\n tensor_shape.TensorShape([batch_size, input_size])] * ((len(op.inputs) - 10) / 7)\n\n\ndef gru_fused(cell_size, sequence_len, xs, name=None, scope=None):\n r\"\"\"gru\n\n args:\n sequence_len: a `tensor` of type `int64`.\n cell_size: an `int`.\n xs: a list of at least 1 `tensor` objects of type `float32`.\n name: a name for the operation (optional).\n\n returns:\n a tuple of `tensor` objects (rzs, rhs, gs, hs).\n rzs: a list with the same number of `tensor` objects as `xs` of `tensor` objects of type `float32`.\n rhs: a list with the same number of `tensor` objects as `xs` of `tensor` objects of type `float32`.\n gs: a list with the same number of `tensor` objects as `xs` of `tensor` objects of type `float32`.\n hs: a list with the same number of `tensor` objects as `xs` of `tensor` objects of type `float32`.\n \"\"\"\n with vs.variable_scope(scope or \"Gru\"):\n input_size = xs[0].get_shape()[1].value\n\n wxr = vs.get_variable(\"wxr\", [input_size, cell_size])\n whr = vs.get_variable(\"whr\", [cell_size, cell_size])\n wxz = vs.get_variable(\"wxz\", [input_size, cell_size])\n whz = vs.get_variable(\"whz\", [cell_size, cell_size])\n wxh = vs.get_variable(\"wxh\", [input_size, cell_size])\n whh = vs.get_variable(\"whh\", [cell_size, cell_size])\n\n return gen_gru_ops._gru_fused(cell_size=cell_size, sequence_len=sequence_len,\n wxr=wxr, whr=whr, wxz=wxz, whz=whz, wxh=wxh, whh=whh, xs=xs, name=name)\n\n\n@ops.RegisterShape(\"GruFused\")\ndef _GruFusedShape(op):\n batch_size = op.inputs[0].get_shape()[0].value\n cell_size = op.get_attr(\"cell_size\")\n sequence_len_max = len(op.inputs) - 7\n\n return [tensor_shape.TensorShape([batch_size, cell_size * 2])] * sequence_len_max + [tensor_shape.TensorShape([batch_size, cell_size])] * (sequence_len_max * 3)\n\n\n@ops.RegisterGradient(\"GruFused\")\ndef _GruFusedGrad(op, *grad):\n outputs = zip(*[iter(op.outputs)] * (len(op.outputs) / 4))\n grads = zip(*[iter(grad)] * (len(grad) / 4))\n gru_grads = gen_gru_ops._gru_fused_grad(cell_size=op.get_attr(\"cell_size\"),\n sequence_len=op.inputs[0],\n wxr=op.inputs[1],\n whr=op.inputs[2],\n wxz=op.inputs[3],\n whz=op.inputs[4],\n wxh=op.inputs[5],\n whh=op.inputs[6],\n xs=op.inputs[7:],\n rzs=outputs[0],\n rhs=outputs[1],\n gs=outputs[2],\n hs=outputs[3],\n dhs=grads[3])\n\n gru_grads_ = [None]\n for gru_grad in gru_grads:\n if isinstance(gru_grad, list):\n gru_grads_ += gru_grad\n else:\n gru_grads_ += [gru_grad]\n return gru_grads_\n\n\n@ops.RegisterShape(\"GruFusedGrad\")\ndef _GruFusedGradShape(op):\n batch_size = op.inputs[0].get_shape()[0].value\n input_size = op.inputs[1].get_shape()[0].value\n cell_size = op.get_attr(\"cell_size\")\n\n return [tensor_shape.TensorShape([input_size, cell_size]),\n tensor_shape.TensorShape([cell_size, cell_size])] * 3 + [\n tensor_shape.TensorShape([batch_size, input_size])] * ((len(op.inputs) - 7) / 6)\n\nops.NoGradient(\"CCTCWeaklySupervisedAlignmentLabel\")\n@ops.RegisterShape(\"CCTCWeaklySupervisedAlignmentLabel\")\ndef _CCTCWeaklySupervisedAlignmentLabelShape(op):\n batch_size = op.inputs[0].get_shape()[0].value\n return [tensor_shape.TensorShape([batch_size])] * 2\n\n\nops.NoGradient(\"CCTCWsjGreedySupervisedAlignment\")\n@ops.RegisterShape(\"CCTCWsjGreedySupervisedAlignment\")\ndef _CCTCWsjGreedySupervisedAlignmentShape(op):\n batch_size = op.inputs[0].get_shape()[0].value\n return [tensor_shape.TensorShape([batch_size])] * 2\n\n\n@ops.RegisterShape(\"CCTCBootstrapAlignment\")\ndef _CCTCBootstrapAlignmentShape(op):\n batch_size = op.inputs[0].get_shape()[0].value\n return [tensor_shape.TensorShape([batch_size])] * op.get_attr(\"features_len_max\") * 2\n\n\n@ops.RegisterShape(\"CCTCEditDistance\")\ndef _CCTCEditDistanceShape(op):\n batch_size = op.inputs[0].get_shape()[0].value\n return [tensor_shape.TensorShape([batch_size])]\n\n@ops.RegisterShape(\"CCTCEditDistanceReinforceGrad\")\ndef _CCTCEditDistanceReinforceGradShape(op):\n batch_size = op.inputs[0].get_shape()[0].value\n features_len_max = op.get_attr(\"features_len_max\")\n vocab_size = op.inputs[features_len_max].get_shape()[1].value\n return [tensor_shape.TensorShape([batch_size, vocab_size])] * features_len_max + [\n tensor_shape.TensorShape([batch_size])] * features_len_max\n\n@ops.RegisterGradient(\"CCTCEditDistance\")\ndef _CCTCEditDistanceGrad(op, *grad):\n features_len_max = op.get_attr(\"features_len_max\")\n tokens_len_max = op.get_attr(\"tokens_len_max\")\n grads = gen_gru_ops.cctc_edit_distance_reinforce_grad(\n op.inputs[features_len_max * 0:features_len_max * 1],\n op.inputs[features_len_max * 2:features_len_max * 3],\n op.inputs[features_len_max * 3:features_len_max * 4],\n op.inputs[features_len_max * 4:features_len_max * 4 + tokens_len_max],\n op.inputs[-1])\n\n return [None] * features_len_max + grads[0] + [None] * features_len_max + grads[1] + [None] * tokens_len_max + [None]\n","sub_path":"tensorflow/python/ops/gru_ops.py","file_name":"gru_ops.py","file_ext":"py","file_size_in_byte":12329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"454650378","text":"import sys\n\nfrom PyQt5.QtWidgets import QApplication, QWidget\nfrom PyQt5.QtCore import QThread\n\nfrom gyro_sensor import GyroSensor\nfrom line_sensor import LineSensor\nfrom rfid_sensor import RFIDSensor\nfrom tag_decoder import TagDecoder\nfrom motor_controller import MotorController\nfrom robot_controller import RobotController\nfrom line_follower import LineFollower\n\ndef main():\n\tapp = QApplication(sys.argv)\n\n\t#RFID thread\n\trfidSensor = RFIDSensor()\n\ttagDecoder = TagDecoder()\n\t\n\trfidSensor.rfidRead.connect(tagDecoder.onRfidRead)\n\t\n\trfidThread = QThread()\n\trfidSensor.moveToThread(rfidThread)\n\ttagDecoder.moveToThread(rfidThread)\n\t\n\trfidThread.started.connect(rfidSensor.run)\n\t\n\t#Line Sensor thread\n\tlineSensor = LineSensor()\n\t\n\tlineSensorThread = QThread()\n\tlineSensor.moveToThread(lineSensorThread)\n\t\n\tlineSensorThread.started.connect(lineSensor.run)\n\t\n\t#Gyro Sensor thread\n\tgyroSensor = GyroSensor()\n\t\n\tgyroSensorThread = QThread()\n\tgyroSensor.moveToThread(gyroSensorThread)\n\t\n\tgyroSensorThread.started.connect(gyroSensor.run)\n\t\n\t#Motor Controller thread\n\tmotorController = MotorController()\n\t\n\tmotorControllerThread = QThread()\n\tmotorController.moveToThread(motorControllerThread)\n\t\n\tmotorControllerThread.started.connect(motorController.run)\n\t\n\t#Controller thread\n\trobotController = RobotController()\n\tlineFollower = LineFollower()\n\t\n\trobotControllerThread = QThread()\n\trobotController.moveToThread(robotControllerThread)\n\tlineFollower.moveToThread(robotControllerThread)\n\t\n\trobotControllerThread.started.connect(robotController.run)\n\t\n\t#Inter-thread connections\n\ttagDecoder.tagDecoded.connect(robotController.onTagDecoded)\n\tlineSensor.lineRead.connect(lineFollower.onLineRead)\n\n\t#Run all threads!\n\trfidThread.start()\n\tlineSensorThread.start()\n\tgyroSensorThread.start()\n\tmotorControllerThread.start()\n\trobotControllerThread.start()\n\t\t\n\tsys.exit(app.exec_())\n\t\nmain()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"204841735","text":"from contextlib import contextmanager\nimport os.path\n\nfrom alembic.config import Config as AlembicConfig\nfrom alembic.migration import MigrationContext\nfrom alembic.script import ScriptDirectory\nfrom alembic import command\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import scoped_session, sessionmaker\nfrom sqlalchemy.ext.declarative import declarative_base\n\ntry:\n from conf.storage import SQLALCHEMY_URI\nexcept ImportError as e:\n import sys\n sys.stderr.write('Error: Update conf/storage.py\\n')\n sys.exit(1)\n\n\nengine = create_engine(SQLALCHEMY_URI)\ndb_session = scoped_session(sessionmaker(autocommit=False,\n autoflush=False,\n bind=engine))\nBase = declarative_base()\nBase.query = db_session.query_property()\n\n\ndef init_db(app):\n if not is_alembic_head():\n raise Exception('alembic is not on the head')\n\n # import all modules here that might define models so that\n # they will be registered properly on the metadata. Otherwise\n # you will have to import them first before calling init_db()\n import models\n from utils.login import init_db; init_db(app)\n\n Base.metadata.create_all(bind=engine)\n\n @app.teardown_request\n def shutdown_session(exception=None):\n db_session.remove()\n\n\n@contextmanager\ndef transaction(**kwargs):\n Session = sessionmaker(bind=engine, **kwargs)\n session = Session()\n try:\n yield session\n session.commit()\n except:\n session.rollback()\n raise\n\n\ndef is_alembic_head():\n alembic_cfg_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),\n 'alembic.ini')\n alembic_cfg = AlembicConfig(alembic_cfg_path)\n context = MigrationContext.configure(db_session.connection())\n script = ScriptDirectory.from_config(alembic_cfg)\n current_revision = context.get_current_revision()\n head_revision = script.get_current_head()\n return current_revision == head_revision\n","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":2022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"240197737","text":"from torchvision.datasets.utils import download_url\nimport os\nimport tarfile\nimport hashlib\nimport torchvision\nimport torch\nfrom torchvision.transforms import transforms\n# This is a fix to overcome OS permissions for downloading models:\nimport ssl\nssl._create_default_https_context = ssl._create_unverified_context\n\n# Main data module:\ndef DataModule(batch_size,ks,imagenet_stats):\n\n # https://github.com/fastai/imagenette\n # Define parameters for dataset construction:\n dataset_url = 'https://s3.amazonaws.com/fast-ai-imageclas/imagenette2.tgz'\n dataset_filename = dataset_url.split('/')[-1]\n dataset_foldername = dataset_filename.split('.')[0]\n data_path = './data'\n dataset_filepath = os.path.join(data_path, dataset_filename)\n dataset_folderpath = os.path.join(data_path, dataset_foldername)\n\n os.makedirs(data_path, exist_ok=True) # Create a data folder (@ project folder)\n\n # If data does not exist, download it from specified URL:\n download = False\n if not os.path.exists(dataset_filepath):\n download = True\n else:\n md5_hash = hashlib.md5()\n\n file = open(dataset_filepath, \"rb\")\n\n content = file.read()\n\n md5_hash.update(content)\n\n digest = md5_hash.hexdigest()\n if digest != 'fe2fc210e6bb7c5664d602c3cd71e612':\n download = True\n if download:\n download_url(dataset_url, data_path)\n # Extract tar file containing dataset examples\n with tarfile.open(dataset_filepath, 'r:gz') as tar:\n tar.extractall(path=data_path)\n\n # Define model-input transforms for data augmentation:\n train_transform = TwoCropsTransform(transforms.Compose([transforms.RandomResizedCrop(scale=(0.2, 1), size=224),\n transforms.RandomHorizontalFlip(),\n transforms.RandomApply(\n [transforms.ColorJitter(0.8, 0.8, 0.8, 0.2)], p=0.8),\n transforms.RandomGrayscale(p=0.2),\n # transforms.GaussianBlur(kernel_size=ks),\n transforms.ToTensor(),\n transforms.Normalize(**imagenet_stats)]))\n\n # Define train and val dataset wrappers:\n dataset_train = torchvision.datasets.ImageFolder(os.path.join(dataset_folderpath, 'train'), train_transform)\n dataset_validation = torchvision.datasets.ImageFolder(os.path.join(dataset_folderpath, 'val'), train_transform)\n # Define train and val dataloaders:\n train_dataloader = torch.utils.data.DataLoader(\n dataset_train,\n batch_size=batch_size,\n num_workers=8,\n drop_last=True,\n shuffle=True,\n )\n validation_dataloader = torch.utils.data.DataLoader(\n dataset_validation,\n batch_size=batch_size,\n num_workers=8,\n drop_last=True,\n shuffle=True,\n )\n return train_dataloader,validation_dataloader,transforms\n\n\"\"\"For MoCo scheme: Create a positive example out of a given query example\"\"\"\nclass TwoCropsTransform:\n \"\"\"Take two random crops of one image as the query and key.\"\"\"\n\n def __init__(self, base_transform):\n self.base_transform = base_transform\n\n def __call__(self, x):\n q = self.base_transform(x)\n k = self.base_transform(x)\n return [q, k]\n\n def __repr__(self):\n format_string = self.__class__.__name__ + '(\\n\\t'\n format_string += self.base_transform.__repr__().replace('\\n', '\\n\\t')\n format_string += '\\n)'\n return format_string","sub_path":"DataModule.py","file_name":"DataModule.py","file_ext":"py","file_size_in_byte":3744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"248077902","text":"import cv2\nimport os\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\"\"\"\nhttps://github.com/simonmeister/motion-rcnn/tree/master/devkit\nOptical flow maps are saved as 3-channel uint16 PNG images: The first channel\ncontains the u-component, the second channel the v-component and the third\nchannel denotes if the pixel is valid or not (1 if true, 0 otherwise). To convert\nthe u-/v-flow into floating point values, convert the value to float, subtract\n2^15 and divide the result by 64.0:\n\nflow_u(u,v) = ((float)I(u,v,1)-2^15)/64.0;\nflow_v(u,v) = ((float)I(u,v,2)-2^15)/64.0;\nvalid(u,v) = (bool)I(u,v,3);\n\"\"\"\ndef read_Opflow(estimation, gt):\n img_estimation = cv2.imread(estimation, -1)\n img_gt = cv2.imread(gt, -1)\n\n if (img_estimation.shape[0] != img_gt.shape[0]) or (img_estimation.shape[1] != img_gt.shape[1]):\n print(\"ERROR: file size is wrong!\")\n return\n else:\n fu_estimation = (img_estimation[:, :, 2] - 2. ** 15) / 64\n fv_estimation = (img_estimation[:, :, 1] - 2. ** 15) / 64\n valid_estimation = img_estimation[:,:,0]\n Opflow_estimation = np.transpose(np.array([fu_estimation, fv_estimation, valid_estimation]), (1, 2, 0))\n\n fu_gt = (img_gt[:, :, 2] - 2. ** 15) / 64\n fv_gt = (img_gt[:, :, 1] - 2. ** 15) / 64\n valid_gt = img_gt[:,:,0]\n Opflow_gt = np.transpose(np.array([fu_gt, fv_gt, valid_gt]),(1,2,0))\n\n print(Opflow_estimation.shape)\n plt.figure(1)\n plt.imshow(Opflow_estimation)\n if not os.path.exists('results'):\n os.makedirs('results')\n plt.savefig('results/Opflow_estimation.png')\n plt.show()\n\n plt.figure(2)\n plt.imshow(Opflow_gt)\n plt.savefig('results/Opflow_gt.png')\n plt.show()\n \n return Opflow_estimation, Opflow_gt\ndef calculate_error(Opflow_test, Opflow_gt):\n Opflow_u = Opflow_test[:, :, 0] - Opflow_gt[:, :, 0]\n Opflow_v = Opflow_test[:, :, 1] - Opflow_gt[:, :, 1]\n Opflow_error = np.sqrt(Opflow_u * Opflow_u + Opflow_v * Opflow_v)\n\n valid_gt = Opflow_gt[:, :, 2]\n\n Opflow_error[valid_gt == 0] = 0\n\n plt.figure(1)\n plt.imshow(Opflow_error, cmap=\"magma\")\n plt.colorbar()\n plt.tick_params(axis='both', labelbottom=False, labelleft=False)\n plt.savefig('results/Opflow_error.png')\n plt.show()\n\n return Opflow_error\n# def calculate_error(pred, gt):\n# flowExist = (gt[:, :, 2] == 1)\n# pred_flow = pred[flowExist]\n# gt_flow = gt[flowExist]\n# # print(flowExist.shape)\n# img_err = np.zeros(shape=gt[:, :, 1].shape)\n#\n# err = gt_flow[:, :2] - pred_flow[:, :2]\n#\n# squared_err = np.sum(err ** 2, axis=1)\n# vect_err = np.sqrt(squared_err)\n# hit = vect_err < 3.0\n# img_err[flowExist] = vect_err\n#\n# msen = np.mean(vect_err)\n# pepn = 100 * (1 - np.mean(hit))\n# plot_Opflow_error (vect_err,gt[:, :, 2], 100)\n# return msen, pepn, img_err, vect_err\n\ndef calculate_msen(Opflow_error, Opflow_gt):\n valid_gt = Opflow_gt[:, :, 2]\n msen = np.mean(Opflow_error[valid_gt != 0])\n return msen\n\ndef calculate_pepn(Opflow_error, Opflow_gt, threshold=3):\n valid_gt = Opflow_gt[:, :, 2]\n pepn = (np.sum(Opflow_error[valid_gt != 0] > threshold)/len(Opflow_error[valid_gt != 0]))\n return pepn\n\ndef plot_Opflow_error(Opflow_error, Opflow_gt, bins = 20):\n valid_gt = Opflow_gt[:, :, 2]\n plt.figure()\n plt.hist(Opflow_error[valid_gt != 0], bins=bins, density=True)\n plt.title('Density of Optical Flow Error')\n plt.xlabel('Optical Flow error')\n plt.ylabel('The Percentage of Pixels')\n plt.savefig('results/Opflow_error_2.png')\n plt.show()\n\nif __name__ == \"__main__\":\n estimation1 = \"./Datasets/results_opticalflow_kitti/results/LKflow_000045_10.png\"\n gt1 = \"./Datasets/data_stereo_flow/training/flow_noc/000045_10.png\"\n\n estimation2 = \"./Datasets/results_opticalflow_kitti/results/LKflow_000157_10.png\"\n gt2 = \"./Datasets/data_stereo_flow/training/flow_noc/000157_10.png\"\n\n Opflow_test, Opflow_gt = read_Opflow(estimation1, gt1)\n Opflow_error = calculate_error(Opflow_test, Opflow_gt)\n\n msen = calculate_msen(Opflow_error, Opflow_gt)\n pepn = calculate_pepn(Opflow_error, Opflow_gt, threshold=3)\n plot_Opflow_error(Opflow_error, Opflow_gt, bins=100)\n\n print(\"MSEN = {}\".format(msen))\n print(\"PEPN = {}\".format(pepn))\n\n","sub_path":"week4/optical_flow_functions.py","file_name":"optical_flow_functions.py","file_ext":"py","file_size_in_byte":4360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"360886041","text":"#!/usr/bin/env python\n\nfrom fitparse import FitFile\nimport datetime\nfrom tqdm import tqdm\n\n'''\nMethods for parsing gps data from Garmin FIT files\n'''\n\n\ndef parse_uuid_string(uuid_string):\n '''\n Parses a video uuid string from fit similar to: VIRBactioncameraULTRA30_Timelapse_3840_2160_1.0000_3936073999_36a2eff0_1_111_2019-01-17-09-01-03.fit\n Returns a tuple (camera_type, video_type, width, height, frame_rate, serial, unknown_1, unkown_2, video_id, fit_filename)\n '''\n return tuple(uuid_string.split(\"_\"))\n\n\ndef get_lat_lon_time_from_fit(geotag_file_list, local_time=True, verbose=False):\n '''\n Read location and time stamps from a track in a FIT file.\n\n Returns a tuple (video_start_time, points) where points is a list of tuples (time, lat, lon, altitude)\n '''\n vids = {}\n for geotag_file in geotag_file_list:\n\n alt = None\n lat = None\n lon = None\n time_delta = None\n try:\n fit = FitFile(geotag_file)\n\n vid_times = {}\n\n timestamp_correlations = fit.get_messages(162)\n timestamp_correlation = next(timestamp_correlations).get_values()\n timestamp = timestamp_correlation['local_timestamp']\n offset = datetime.timedelta(seconds=timestamp_correlation['system_timestamp'],\n milliseconds=timestamp_correlation['system_timestamp_ms'])\n start_time = timestamp - offset\n camera_events = (c for c in fit.get_messages(161) if c.get('camera_event_type').value in ['video_start', 'video_end'])\n for start in tqdm(camera_events, desc='Extracting Video data from .FIT file'):\n vid_id = parse_uuid_string(start.get('camera_file_uuid').value)[-2]\n end = next(camera_events)\n start_timedelta = datetime.timedelta(seconds=start.get('timestamp').value, milliseconds=start.get('timestamp_ms').value)\n start_timestamp = start_time + start_timedelta\n end_timedelta = datetime.timedelta(seconds=end.get('timestamp').value, milliseconds=end.get('timestamp_ms').value)\n end_timestamp = start_time + end_timedelta\n vid_times[vid_id] = (start_timestamp, end_timestamp)\n\n points = []\n for vid_id, times in tqdm(vid_times.items(), desc='Extracting GPS data from .FIT file'):\n gps_metadata = (g for g in fit.get_messages(160) if times[0] <= (start_time + datetime.timedelta(seconds=g.get('timestamp').value, milliseconds=g.get('timestamp_ms').value)) <= times[-1])\n for gps in gps_metadata:\n try:\n alt = gps.get('enhanced_altitude').value\n lat_in_semicircles = gps.get('position_lat').value\n lat = float(lat_in_semicircles) * 180 / 2**31\n lon_in_semicircles = gps.get('position_long').value\n lon = float(lon_in_semicircles) * 180 / 2**31\n time_delta = datetime.timedelta(seconds=gps.get('timestamp').value, milliseconds=gps.get('timestamp_ms').value)\n wp_datetime = start_time + time_delta\n except:\n continue\n if alt is not None and lat is not None and lon is not None and wp_datetime is not None and times[0] <= wp_datetime <= times[-1]:\n points.append((wp_datetime, lat, lon, alt))\n try:\n vids[int(vid_id)] = (times[0], sorted(points))\n except:\n vids[vid_id] = (times[0], sorted(points))\n\n except ValueError:\n if verbose:\n print(\"Warning: {} is not formatted properly\".format(geotag_file))\n pass\n except StopIteration:\n if verbose:\n print(\"Warning: {} does not have enough iterations\".format(geotag_file))\n pass\n return vids\n","sub_path":"mapillary_tools/fit_parser.py","file_name":"fit_parser.py","file_ext":"py","file_size_in_byte":3988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"514260221","text":"import tkinter\nfrom tkinter import *\nfrom engine import *\nimport sys\n\nward = None\nclass Chat:\n def __init__(self, master) :\n self.master = master\n self.master.title(\"Chat\")\n self.c=Canvas(master,borderwidth=0,background=\"wheat3\")\n self.frame=Frame(self.c,background=\"blue\")\n self.sc=Scrollbar(master,orient=\"vertical\",command=self.c.yview)\n self.c.configure(yscrollcommand=self.sc.set)\n self.sc.pack(side=\"right\",fill=\"y\")\n self.c.pack(side=\"left\",fill=\"both\",expand=True, pady=(0,80))\n self.c.create_window((4,4),window=self.frame,anchor=\"nw\")\n self.frame.bind(\"\",lambda event,canvas=self.c: self.onConfig())\n self.content = StringVar()\n self.content.set(\"\")\n self.text_box = Entry(self.master, textvar=self.content,width=50)\n self.text_box.bind(\"\", self.submit)\n self.text_box.place(x=50,y=650)\n\n self.welcome_msg = BotBubble(self.frame, content=\"What topic are you interested in?\")\n # self.text_box.pack( side = tkinter.BOTTOM, padx = 100 , pady = 40)\n\n def submit(self,event = None):\n global ward\n ward = self.content.get()\n self.content.set(\"\")\n a=UserBubble(self.frame,ward)\n\n def onConfig (self):\n self.c.configure(scrollregion=self.c.bbox(\"all\"))\n\n\ndef main():\n try:\n if (str(sys.argv[1]) == \"1\"):\n master = Tk()\n master.minsize(width=600, height=700)\n master.maxsize(width=600, height=700)\n a = Chat(master)\n master[\"bg\"] = \"wheat3\"\n master.mainloop()\n except:\n return\n\nmain()\n","sub_path":"app/chat.py","file_name":"chat.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"10801339","text":"# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n# 1\n# / \\\n# 2 2\n# / \\ / \\\n# 3 4 4 3\n# \n# [1, 2, 2, 3, 4, 4, 3]\n\n\nclass Solution:\n\n # def flatten(self, root: TreeNode, xs):\n # print(xs)\n # if (root):\n # if (root.left):\n # xs.append(root.left.val)\n # elif (root.left or root.right):\n # xs.append(None)\n\n # if (root.right):\n # xs.append(root.right.val)\n # elif (root.left or root.right):\n # xs.append(None)\n\n # self.flatten(root.left, xs)\n # self.flatten(root.right, xs)\n\n def __isSymmetric(self, t1: TreeNode, t2: TreeNode):\n if (t1 == None and t2 == None): return True\n if (t1 == None or t2 == None): return False\n print(f\"{t1.val} {t2.val}\")\n return (t1.val == t2.val) and self.__isSymmetric(t1.left, t2.right) and self.__isSymmetric(t1.right, t2.left)\n\n def isSymmetric(self, root: TreeNode) -> bool:\n return self.__isSymmetric(root, root)\n\ns = Solution()\nroot = TreeNode(1)\nroot.left = TreeNode(2)\nroot.right = TreeNode(2)\nroot.left.left = TreeNode(3)\nroot.left.right = TreeNode(4)\nroot.right.left = TreeNode(4)\nroot.right.right = TreeNode(3)\nres = s.isSymmetric(root)\nprint(res)","sub_path":"lc/python3/101-symmetric-tree.py","file_name":"101-symmetric-tree.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"390826131","text":"# Copyright (c) 2018 David Chan\n# \n# This software is released under the MIT License.\n# https://opensource.org/licenses/MIT\n\nimport pytest\n\nfrom searchlet.environments import GridEnvironment, GridState\nfrom searchlet.algorithms import BFS\n\n\ndef test_bfs():\n # First create and initialize the environment\n env = GridEnvironment(10, 10)\n env.initialize()\n\n # Get the start and goal\n start = GridState(0, 0)\n goal = GridState(5, 5)\n\n # Solve the problem\n path = BFS.solve(env, start, goal)\n\n if path[0] is None:\n raise AssertionError(\"BFS could not find feasible path in solvable environment\")\n\n\nif __name__ == '__main__':\n pytest.main()","sub_path":"searchlet/test/test_bfs.py","file_name":"test_bfs.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"250288415","text":"\"\"\"\n\nMemory Agent class to provide basic functionality for Ocean Agents\n\n\"\"\"\n\nimport json\nimport re\nimport secrets\n\nfrom starfish.agent import AgentBase\nfrom starfish.ddo.ddo import DDO\nfrom starfish.listing import Listing\nfrom starfish.purchase import Purchase\nfrom starfish.utils.crypto_hash import hash_sha3_256\nfrom starfish.utils.did import (\n decode_to_asset_id,\n did_generate_random\n)\n\n\nclass MemoryAgent(AgentBase):\n \"\"\"\n\n Memory Agent class allows to register, list, purchase and consume assets.\n\n :param ocean: Ocean object that is being used.\n :type ocean: :class:`.Ocean`\n\n \"\"\"\n\n def __init__(self, network, ddo=None):\n\n if ddo is None:\n did = did_generate_random()\n ddo = DDO(did)\n\n AgentBase.__init__(self, network, ddo=ddo)\n\n self._memory = {\n 'listing': {},\n 'asset': {},\n 'purchase': {}\n }\n\n def register_asset(self, asset):\n \"\"\"\n\n Register a memory asset with the ocean network.\n\n :param object metadata: asset object to register for this asset.\n\n :return: A :class:`.AssetBase` object that has been registered, if failure then return None.\n :type: :class:`.AssetBase` class\n\n \"\"\"\n\n asset_id = hash_sha3_256(asset.metadata_text)\n did = f'{self._ddo.did}/{asset_id}'\n\n self._memory['asset'][did] = asset\n asset.set_did(did)\n return asset\n\n def create_listing(self, listing_data, asset_did):\n \"\"\"\n\n Create a listing on the market place for this asset\n\n :param dict listing_data: Listing inforamiton to give for this asset\n :param str asset_did: asset DID to assign to this listing\n :return: A new :class:`.Listing` object that has been registered, if failure then return None.\n :type: :class:`.Listing` class\n\n \"\"\"\n listing = None\n if listing_data:\n listing_id = decode_to_asset_id(asset_did)\n listing_data['listing_id'] = listing_id,\n listing_data['asset_did'] = asset_did\n listing = Listing(self, listing_id, asset_did, listing_data)\n self._memory['listing'][listing_id] = listing\n return listing\n\n def update_listing(self, listing):\n \"\"\"\n\n Update the listing to the agent server.\n\n :param listing: Listing object to update\n :type listing: :class:`.Listing` class\n\n \"\"\"\n self._memory['listing'][listing.listing_id] = listing\n\n def validate_asset(self, asset):\n \"\"\"\n\n Validate an asset\n\n :param asset: Asset to validate.\n :return: True if the asset is valid\n \"\"\"\n return asset is not None\n\n def get_listing(self, listing_id):\n \"\"\"\n\n Return an listing from the given listing_id.\n\n :param str listing_id: Id of the listing.\n\n :return: a registered listing given a Id of the listing\n :type: :class:`.Listing` class\n\n \"\"\"\n listing = None\n if listing_id in self._memory['listing']:\n listing = self._memory['listing'][listing_id]\n return listing\n\n def search_listings(self, text, sort=None, offset=100, page=0):\n \"\"\"\n\n Search for listings with the givien 'text'\n\n :param str text: Text to search all listing data for.\n :param sort: sort the results ( defaults: None, no sort).\n :type sort: str or None\n :param int offset: Return the result from with the maximum record count ( defaults: 100 ).\n :param int page: Returns the page number based on the offset.\n\n :return: a list of listing objects found using the search.\n :type: :class:`.Listing` objects\n\n For example::\n\n # return the 300 -> 399 records in the search for the text 'weather' in the metadata.\n my_result = agent.search_registered_assets('weather', None, 100, 3)\n\n \"\"\"\n listing_id_list = []\n for listing_id, listing in self._memory['listing'].items():\n if re.search(text, json.dumps(listing.data)):\n listing_id_list.append(listing.listing_id)\n\n return listing_id_list\n\n def purchase_asset(self, listing, account):\n \"\"\"\n\n Purchase an asset using it's listing and an account.\n\n :param listing: Listing to use for the purchase.\n :type listing: :class:`.Listing`\n :param account: Ocean account to purchase the asset.\n :type account: :class:`.Account` object to use for registration.\n\n \"\"\"\n purchase = None\n\n purchase_id = secrets.token_hex(64)\n if purchase_id:\n purchase = Purchase(self, listing, purchase_id, account)\n self._memory['purchase'][purchase_id] = (purchase, account.address)\n\n return purchase\n\n def purchase_wait_for_completion(self, asset, account, purchase_id, timeoutSeconds):\n \"\"\"\n\n Wait for completion of the purchase\n\n TODO: issues here...\n + No method as yet to pass back paramaters and values during the purchase process\n + We assume that the following templates below will always be used.\n\n \"\"\"\n return True\n\n def is_access_granted_for_asset(self, asset, account, purchase_id=None):\n \"\"\"\n\n Check to see if the account and purchase_id have access to the assed data.\n\n\n :param asset: Asset to check for access.\n :type asset: :class:`.Asset` object\n :param account: Ocean account to purchase the asset.\n :type account: :class:`.Account` object to use for registration.\n :param str purchase_id: purchase id that was used to purchase the asset.\n\n :return: True if the asset can be accessed and consumed.\n :type: boolean\n \"\"\"\n\n if purchase_id in self._memory['purchase']:\n purchase, account_address = self._memory['purchase'][purchase_id]\n return purchase and account.is_address_equal(account_address)\n\n return False\n\n def get_asset_purchase_ids(self, asset):\n \"\"\"\n\n Returns as list of purchase id's that have been used for this asset\n\n :param asset: DataAsset to return purchase details.\n :type asset: :class:`.DataAsset` object\n\n :return: list of purchase ids\n :type: list\n\n \"\"\"\n return []\n\n def consume_asset(self, listing, account, purchase_id):\n \"\"\"\n Consume the asset and download the data. The actual payment to the asset\n provider will be made at this point.\n\n :param listing: Listing that was used to make the purchase.\n :type listing: :class:`.Listing`\n :param str purchase_id: purchase id that was used to purchase the asset.\n :param account: Ocean account that was used to purchase the asset.\n :type account: :class:`.Account` object to use for registration.\n\n :return: True if the asset has been consumed and downloaded\n :type: boolean\n\n \"\"\"\n return purchase_id in self._memory['purchase']\n","sub_path":"starfish/agent/memory_agent.py","file_name":"memory_agent.py","file_ext":"py","file_size_in_byte":7046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"518985283","text":"from django.urls import path\r\n\r\nfrom .views import home, scrape, get_ListProduct, detail_Product\r\n\r\n\r\napp_name = 'scrapping'\r\n\r\nurlpatterns = [\r\n path('', home, name='home'),\r\n path('scrapping-product/', scrape, name ='scrape'),\r\n path('detail-product/', detail_Product, name ='detail'),\r\n path('list-product/', get_ListProduct, name ='list'),\r\n]","sub_path":"django-project/scrapping/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"274502822","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom django.http import HttpResponse, Http404\n\nfrom .models import Hunt, Stage\n\nINCLUDE_DEBUG_HTML = False\n\ndef index(request):\n\n return render(request, \"treasure_app/index.html\", {})\n\ndef settings(request):\n\n return render(request, \"treasure_app/settings.html\",\n {\"show_debug\": INCLUDE_DEBUG_HTML,\n \"page_title\": \"Settings\",\n \"page_name\": request.path.split('/')[-1],\n })\n\ndef hunts(request):\n\n try:\n all_hunts = Hunt.objects.all()\n return render(request,\n \"treasure_app/hunts.html\",\n {\"show_debug\" : INCLUDE_DEBUG_HTML,\n \"page_title\" : \"Hunts\",\n \"page_name\" : request.path.split('/')[-1],\n \"hunts\": all_hunts,\n })\n except Exception as e:\n raise Http404(\"could not list Hunts because: {0}\".format(e))\n\ndef my_hunts(request):\n\n try:\n all_hunts = Hunt.objects.all()\n return render(request,\n \"treasure_app/my-hunts.html\",\n {\"show_debug\": INCLUDE_DEBUG_HTML,\n \"page_title\" : \"My Hunts\",\n \"page_name\": request.path.split('/')[-1],\n # \"hunts\": all_hunts,\n })\n except Exception as e:\n raise Http404(\"could not list Hunts because: {0}\".format(e))\n\n\n\ndef hunt(request, hunt_id):\n\n try:\n h = Hunt.objects.get(id=hunt_id)\n return render(request,\n \"treasure_app/hunt.html\",\n {\"hunt\":h,\n \"show_debug\": INCLUDE_DEBUG_HTML,})\n except Exception as e:\n raise Http404(\"Hunt id={0} not found bcause: {1}\".format(hunt_id, e))\n\ndef hunt_fragment(request, hunt_id):\n\n try:\n h = Hunt.objects.get(id=hunt_id)\n #\n # Calculate some useful values, keeping the HTML cleaner\n #\n finish_time = h.start_time\n stage_finish = {}\n stage_start = {}\n for stage in h.stage_set.all():\n stage_start[stage.id] = finish_time\n finish_time += stage.duration\n stage_finish[stage.id] = finish_time\n\n\n page_values = {\n \"hunt\" : h,\n \"finish_time\" : finish_time,\n \"stage_starts\" : stage_start,\n \"stage_finishes\" : stage_finish,\n \"show_debug\": INCLUDE_DEBUG_HTML,\n }\n\n return render(request, \"treasure_app/hunt-fragment.html\", page_values)\n except Exception as e:\n raise Http404(\"Hunt id={0} not found bcause: {1}\".format(hunt_id, e))\n\n\n# def join_hunt(request, hunt_id):\n#\n# try:\n# h = Hunt.objects.get(id=hunt_id)\n# return render(request,\n# \"treasure_app/join.html\",\n# {\"hunt\": h,\n# \"show_debug\": INCLUDE_DEBUG_HTML,})\n# except Exception as e:\n# raise Http404(\"Hunt id={0} not found bcause: {1}\".format(hunt_id, e))","sub_path":"treasure_poc/treasure_app/page_views.py","file_name":"page_views.py","file_ext":"py","file_size_in_byte":3090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"625856859","text":"# -*- coding: utf-8 -*-\n#\n# ramstk.exim.export.py is part of The RAMSTK Project\n#\n# All rights reserved.\n# Copyright 2007 - 2019 Doyle Rowland doyle.rowland reliaqual com\n\"\"\"The RAMSTK Export module.\"\"\"\n\n# Standard Library Imports\nimport os\nfrom typing import Any, Dict\n\n# Third Party Imports\n# noinspection PyPackageRequirements\nimport pandas as pd\n# noinspection PyPackageRequirements\nfrom openpyxl import load_workbook\nfrom pubsub import pub\nfrom treelib import Tree\n\n\nclass Export:\n \"\"\"Contains the methods for exporting data from a program database.\"\"\"\n def __init__(self) -> None:\n \"\"\"Initialize an Export module instance.\"\"\"\n # Initialize private dictionary attributes.\n self._dic_output_data: Dict[str, Dict[int, Dict[Any, Any]]] = {}\n\n # Initialize private list attributes.\n\n # Initialize private scalar attributes.\n self._df_output_data: pd.DataFrame = pd.DataFrame()\n\n # Initialize public dictionary attributes.\n\n # Initialize public list attributes.\n\n # Initialize public scalar attributes.\n\n # Subscribe to PyPubSub messages.\n pub.subscribe(self._do_load_data, 'succeed_get_functions_tree')\n pub.subscribe(self._do_load_data, 'succeed_get_requirements_tree')\n pub.subscribe(self._do_load_data, 'succeed_get_hardware_tree')\n pub.subscribe(self._do_load_data, 'succeed_get_validations_tree')\n pub.subscribe(self._do_load_output, 'request_load_output')\n pub.subscribe(self._do_export, 'request_export_data')\n\n def _do_export(self, file_type: str, file_name: str) -> None:\n \"\"\"Export selected RAMSTK module data to external file.\n\n :param file_type: the type of file to export the data to.\n Supported files types are:\n - CSV (using a semi-colon (;) delimiter)\n - Excel\n - Text (using a blank space delimiter)\n :param file_name: the name, with full path, of the file to export\n the RAMSTK Program database data to.\n :return: None\n :rtype: None\n \"\"\"\n if file_type == 'csv':\n self._do_export_to_delimited_text(file_name, separator=';')\n elif file_type == 'excel':\n self._do_export_to_excel(file_name)\n elif file_type == 'text':\n self._do_export_to_delimited_text(file_name, separator=' ')\n\n def _do_export_to_delimited_text(self, file_name: str, separator: str):\n \"\"\"Export RAMSTK project data to a delimited text file.\n\n :param file_name: the name of the file to export data.\n :param separator: the field delimiter to use.\n :return: None\n :rtype: None\n \"\"\"\n for _key in self._dic_output_data:\n self._df_output_data = pd.DataFrame(self._dic_output_data[_key])\n\n self._df_output_data.to_csv(file_name, sep=separator, index=True)\n\n # pylint: disable=abstract-class-instantiated\n def _do_export_to_excel(self, file_name: str) -> None:\n \"\"\"Export RAMSTK project data to an Excel file.\n\n :param file_name: the name of the file to export data.\n :return: None\n :rtype: None\n \"\"\"\n _file, _extension = os.path.splitext(file_name)\n\n for _key in self._dic_output_data:\n self._df_output_data = pd.DataFrame(self._dic_output_data[_key])\n if _extension == '.xls':\n # xlwt can't write each module to a separate sheet so we'll\n # have to make a separate workbook for each work stream module.\n _writer = pd.ExcelWriter('{0:s}_{1:s}.xls'.format(_file, _key),\n engine='xlwt')\n elif _extension in ['.xlsx', '.xlsm']:\n _writer = pd.ExcelWriter(file_name, engine='openpyxl')\n # Set the writer workbook if it already exists, otherwise\n # just continue. This allows each work stream module to be\n # written to it's own worksheet. If the workbook doesn't\n # exist it will be created when the first module is written.\n try:\n _workbook = load_workbook(file_name)\n _writer.book = _workbook\n except FileNotFoundError:\n pass\n else:\n file_name = _file + '.xls'\n _writer = pd.ExcelWriter(file_name, engine='xlwt')\n self._df_output_data.to_excel(_writer,\n '{0:s}'.format(_key),\n index=True)\n _writer.save()\n\n _writer.close()\n\n @staticmethod\n def _do_load_output(module: str) -> None:\n \"\"\"Load data from the requested RAMSTK module into a Pandas DataFrame.\n\n :param module: the RAMSTK module to load for export.\n :return: None\n :rtype: None\n \"\"\"\n pub.sendMessage('request_get_{0:s}_tree'.format(module.lower()))\n\n def _do_load_data(self, tree: Tree) -> None:\n \"\"\"Load the attribute data into a Pandas DataFrame.\n\n :param tree: the data manager tree for the module to export.\n :return: None\n :rtype: None\n \"\"\"\n _dic_temp = {}\n _module = tree.get_node(0).tag.lower()\n self._dic_output_data[_module] = {}\n\n # pylint: disable=unused-variable\n for __, _node in enumerate(tree.nodes):\n _tag = tree.nodes[_node].tag\n try:\n _attributes = tree.nodes[_node].data[_tag].get_attributes()\n for _key in _attributes:\n _dic_temp[_key] = _attributes[_key]\n # TODO: Remove KeyError once all modules are updated to use\n # plural form for _module attribute.\n except (KeyError, TypeError):\n pass\n self._dic_output_data[_module][\n tree.nodes[_node].identifier] = _dic_temp\n","sub_path":"src/ramstk/exim/export.py","file_name":"export.py","file_ext":"py","file_size_in_byte":5958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"160581113","text":"# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nDjango settings for xdata project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.6/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.6/ref/settings/\n\"\"\"\n\nfrom secret import *\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os, sys\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\nsys.path.insert(0, os.path.join(BASE_DIR, \"op_tasks\"))\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = MY_SECRET_KEY\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\nTEMPLATE_DEBUG = True\n\n# ADMINS = ADMIN_EMAILS\n\nALLOWED_HOSTS = ['*']\n\nSITE_ROOT = os.path.realpath(os.path.dirname(__file__))\n\nTEMPLATE_DIRS = (\n os.path.join(SITE_ROOT, 'templates'),\n)\n# Application definition\n\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'op_tasks',\n 'exp_portal',\n 'developer',\n 'uploads',\n 'axes', # Throttling capabilities\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'axes.middleware.FailedLoginMiddleware',\n)\n\nROOT_URLCONF = 'xdata.urls'\n\nWSGI_APPLICATION = 'xdata.wsgi.application'\n\nAUTHENTICATION_BACKENDS = (\n 'django.contrib.auth.backends.ModelBackend',\n )\n\n# AUTH_PROFILE_MODULE = 'op_tasks.UserProfile'\n# AUTH_USER_MODEL = 'op_tasks.MyUser'\n\n# Database\n# https://docs.djangoproject.com/en/1.6/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, '../db', 'db.sqlite3'),\n }\n\n # 'default': {\n # 'ENGINE': 'django.db.backends.mysql',\n # 'NAME': 'xdatadb',\n # 'USER': 'xdatauser',\n # 'PASSWORD': 'Dr@perUs3r!',\n # 'HOST': 'localhost', #'127.0.0.1', # Or an IP Address that your DB is hosted on\n # 'PORT': '3306',\n # }\n}\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.6/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'America/New_York'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.6/howto/static-files/\n\n# STATIC_ROOT = \"/var/www/html/stout/static/\"\nSTATIC_ROOT = os.path.join(BASE_DIR, '../static')\n\nSTATIC_URL = '/static/'\n\nSTATICFILES_DIRS = (\n os.path.join(BASE_DIR, \"static\"),\n)\n\nMEDIA_ROOT = os.path.join(BASE_DIR, 'media')\nMEDIA_URL = '/media/'\n\nLOGIN_URL = '/tasking/login'\n\nCRISPY_TEMPLATE_PACK = 'bootstrap3'\n\nSESSION_EXPIRE_AT_BROWSER_CLOSE = True\n\n# Email integration setup\n\nEMAIL_USE_TLS = True\nEMAIL_HOST = 'smtp.gmail.com'\nEMAIL_HOST_USER = 'xdataonline@gmail.com'\nEMAIL_HOST_PASSWORD = MY_EMAIL_PASSWORD\nEMAIL_PORT = 587\n\n# After three failed logins, require users to wait 5 minutes before they can attempt to log in again\nAXES_LOGIN_FAILURE_LIMIT = 3\nfrom datetime import timedelta\nAXES_COOLOFF_TIME=timedelta(seconds = 300)\n\n# Activity Logging Endpoint\nALE_URL = 'http://52.20.48.202'\n","sub_path":"xdata/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":4342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"386833420","text":"#!usr/bin/python\n\n#from __future__ import print_function\nimport sys\nimport glob\nimport flagstat_2\nimport flagstat_db_2\nimport flagstat_import2\nimport os\nimport time\n\n\"\"\"\nParse all flagstat files from the runfolder into a database.\n\"\"\"\n\ndef list_of_files_to_import(runfolder):\n \n #identify all flagstat files in the runfolder and assign it to flagstat_list\n filepath = os.path.abspath(runfolder)\n pattern = \"{}/stats/*.flagstat\".format(str(filepath))\n #print (pattern)\n\n #generate a list of filepath to the flagstat files in the runfolder. \n flagstat_list = glob.glob(pattern)\n flagstat_list = sorted(flagstat_list)\n\n return flagstat_list\n\ndef get_sample_sheet(runfolder, db_dir):\n \n #identify samplesheet*.csv with all the samples listed, use it to check that flagstat_list contains all the samples in the runfolder\n sample_sheet = \"{}/SampleSheet*.csv\".format(str(runfolder))\n sample_sheets = sorted(glob.glob(sample_sheet))\n if sample_sheets:\n return sample_sheets[0]\n else:\n print (\"no SampleSheet*.csv found\")\n with open(os.path.join(db_dir, 'no_samples_check.txt'), 'a') as sample_check_log:\n sample_check_log.writelines(\"no SampleSheet*.csv found in {}\\n\".format(filepath))\n \ndef check_files_to_be_imported(flagstat_list, sample_sheet, db_dir, runfolder):\n \n flagstat_sample_name_list = []\n sample_sheet_sample_name_list = []\n new_flagstat_list = []\n count = 0\n\n \"\"\"create a list of sample_names with flagstat files\"\"\"\n for flagstat in flagstat_list:\n sample_name1 = \"\".join(flagstat.split(\"/\")[-1].split(\".\")[:1])\n #print (sample_name1)\n flagstat_sample_name_list.append(sample_name1)\n #print(flagstat_sample_name_list)\n\n \"\"\"create a list of sample_names in the SampleSheet.csv\"\"\"\n if sample_sheet:\n print (\"SampleSheet present at: {}\".format(sample_sheet))\n with open(os.path.join(db_dir, 'yes_samples_check.txt'), 'a') as sample_check_log:\n sample_check_log.writelines(\"SampleSheet present at: {}\\n\".format(sample_sheet))\n with open(sample_sheet, 'r') as csv:\n \n heading_line = False\n count = 0\n \n for line in csv:\n \n if line.startswith(\"[Data]\"):\n heading_line = True\n\n elif heading_line and count == 0:\n line = line.strip()\n column_headings = line.split(\",\")\n #print (column_headings)\n pos = column_headings.index('Sample_ID')\n count += 1\n \n elif heading_line and count >= 1:\n line = line.strip()\n #print (line)\n sample_name2 = line.split(\",\")[pos]\n #print (sample_name2)\n sample_sheet_sample_name_list.append(sample_name2)\n count += 1\n\n #print (sample_sheet_sample_name_list)\n #print (flagstat_sample_name_list)\n samples_list1 = set(sample_sheet_sample_name_list)\n print (len(samples_list1))\n samples_list2 = set(flagstat_sample_name_list)\n print (len(samples_list2))\n unmatched_samples = samples_list1 ^ samples_list2\n\n if unmatched_samples:\n runfolder_name = os.path.abspath(runfolder).split(\"/\")[-1]\n with open(os.path.join(db_dir, 'samples_check.txt'), 'a') as sample_check_log:\n sample_check_log.writelines(\"The runfolder for the sample sheet is: {}\\n\".format(runfolder_name))\n\n # the following cross-checks the list of unmatched samples in both list and records them in the sample_check.txt\n\n for sample in unmatched_samples:\n if sample in flagstat_sample_name_list:\n print (\"{} not in SampleSheet.csv, check {}\".format(sample, sample))\n with open(os.path.join(db_dir, 'samples_check.txt'), 'a') as sample_check_log:\n sample_check_log.writelines(\"{} not in SampleSheet.csv, check {}\\n\".format(sample, sample))\n\n elif sample in sample_sheet_sample_name_list:\n print (\"{} not in stats/*.flagstat_list, check {}.flagstat\".format(sample, sample))\n with open(os.path.join(db_dir, 'samples_check.txt'), 'a') as sample_check_log:\n sample_check_log.writelines(\"{} not in flagstat_list, check {}.flagstat\\n\".format(sample, sample))\n\n else:\n matched_samples = set(sample_sheet_sample_name_list) & set(flagstat_sample_name_list)\n final_sample_list = list(matched_samples)\n #print (sample_sheet_sample_name_list)\n #print (flagstat_sample_name_list)\n\n if final_sample_list == []:\n print (\"flagstat files checked against SampleSheet.csv, but no matches found, use unchecked flagstat_list\")\n with open (os.path.join(db_dir, 'samples_check.txt'), 'a') as sample_check_log:\n sample_check_log.writelines(\"flagstat files checked against SampleSheet.csv, but no matches found, use unchecked flagstat_list\\n\")\n return flagstat_list\n else:\n for sample in final_sample_list:\n for flagstat in flagstat_list:\n if sample in flagstat:\n new_flagstat_list.append(flagstat)\n print (\"flagstat files checked against SampleSheet.csv\")\n #print (new_flagstat_list)\n return new_flagstat_list\n else:\n return flagstat_list\n\ndef main(runfolder, db_file):\n\n start = time.time()\n\n db_dir = flagstat_import2.database_dir(db_file)\n print (\"directory where database is stored:\", db_dir)\n conn = flagstat_db_2.connect_flagstat_db(db_dir, db_file)\n\n # generate two lists of flagstat fles and compare to create a final list from runfolder to be imported\n flagstat_list = list_of_files_to_import(runfolder)\n sample_sheet = get_sample_sheet(runfolder, db_dir)\n processed_flagstat_list = check_files_to_be_imported(flagstat_list, sample_sheet, db_dir, runfolder)\n exit()\n # execute function to import all flagstat from runfolder into flagstat database\n\n for flagstat in processed_flagstat_list:\n flagstat_import2.main(flagstat, db_file)\n\n runfolder_path = os.path.abspath(runfolder)\n runfolder_name = runfolder_path.split(\"/\")[-1]\n print (\"runfolder: \", runfolder_name)\n \n # import runfolder stats to runfolder table\n flagdict = flagstat_2.data_from_flagstat(db_dir, flagstat_list[0])\n runfolder_id = flagstat_import2.get_runfolder_id(db_dir, conn, runfolder_name, flagdict)\n flagstat_import2.import_runfolder_flagstat_to_db (db_dir, conn, runfolder_id, flagdict)\n\n end = time.time()\n time_taken = end - start\n with open(os.path.join(db_dir, 'time.txt'), 'a') as time_text:\n time_text.writelines(\"time taken to import runfolder {}: {} \\n\".format(runfolder_name, time_taken))\n\nif __name__ == \"__main__\":\n main(sys.argv[1], sys.argv[2])\n \n\"\"\"From terminal navigate to the directory where the script is stored, \n \n enter \"python flagstat_import_runfolder.py\", followed by the filepath of the runfolder you wish to import into the database - sys.argv[1] \n e.g. /mnt/storage/data/NGS/180613_K00178\n\n and then the filepath of the database where the runfolder data will be imported - sys.argv[2] \n e.g. gemini_db.db\"\"\"\n\n","sub_path":"flagstat_import_runfolder.py","file_name":"flagstat_import_runfolder.py","file_ext":"py","file_size_in_byte":7502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"483454150","text":"from django.urls import path, include\nfrom .views import QuestionViewSet, GetQuestionAndAnswer, CommentViewSet, EditorDataViewSet, AnswersQuestion\n\nurlpatterns = [\n path(\"question/\", QuestionViewSet.as_view()),\n path(\"question//\", GetQuestionAndAnswer.as_view()),\n path('comment/', CommentViewSet.as_view()),\n path('editor/', EditorDataViewSet.as_view()),\n path('answer/', AnswersQuestion.as_view())\n\n]","sub_path":"sqanda/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"215000808","text":"import csv\r\nimport json\r\nimport pandas as pd\r\nimport sys, getopt, pprint\r\nfrom pymongo import MongoClient\r\n\r\n#CSV to JSON Conversion\r\ncsvfile = open(r'/home/shivam/Study/project/chicago-current-employee-information/current-employee-names-salaries-and-position-titles.csv', 'r')\r\nreader = csv.DictReader( csvfile )\r\nmongo_client=MongoClient() \r\ndb=mongo_client.Freelancers\r\ndb.Per_info.drop()\r\nheader= [\"Name\", \"Job Titles\", \"Department\",\"Full or Part-Time\", \"Salary or Hourly\", \"Typical Hours\", \"Annual Salary\",\r\n \"Hourly Rate\"]\r\n\r\npp = pprint.PrettyPrinter(indent=4)\r\n\r\nfor each in reader:\r\n row={}\r\n for field in header:\r\n if field in [\"Job Titles\", \"Department\"]:\r\n row[field] = each[field].split(\",\")\r\n elif each[field] != '' and field == \"Annual Salary\":\r\n row[\"Annual Salary\"] = float(each[field])\r\n elif each[field] != '' and field == \"Hourly Rate\":\r\n row[\"Hourly Rate\"] = float(each[field])\r\n elif each[field] != '' and field == \"Typical Hours\":\r\n row[\"Typical Hours\"] = float(each[field])\r\n elif each[field] != '' and field in [\"Name\", \"Job Titles\", \"Department\", \"Salary or Hourly\", \"Full or Part-Time\", \"Annual Salary\"]:\r\n row[field] = float(each[field])\r\n else:\r\n row[field]=each[field]\r\n db.movies.insert(row)\r\n #pp.pprint(row)\r\n \r\n","sub_path":"csv_2_mongo.py","file_name":"csv_2_mongo.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"277350994","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 26 18:46:17 2018\n\n@author: Figo\n\"\"\"\n\nfrom keras.preprocessing.text import Tokenizer\n\nsamples = ['The cat sat on the mat.', 'The dog ate my homework.']\n\n# 创建一个分词器(tokenizer),设置为只考虑前 1000 个最常见的单词\ntokenizer = Tokenizer(num_words=1000)\n# 构建单词索引\ntokenizer.fit_on_texts(samples)\n\n# 将字符串转换为整数索引组成的列表\nsequences = tokenizer.texts_to_sequences(samples)\n# sequences 为 [[1, 2, 3, 4, 1, 5], [1, 6, 7, 8, 9]]\n\n# 也可以直接得到 one-hot 二进制表示。\n# 这个分词器也支持除 one-hot 编码外的其他向量化模式\none_hot_results = tokenizer.texts_to_matrix(samples, mode='binary')\n# one_hot_results.shape 为 (2, 1000)\n\n# 找回单词索引\nword_index = tokenizer.word_index\nprint('Found %s unique tokens.' % len(word_index))","sub_path":"deep_learning_code/deep_learning_2018/6-3Using_Keras_for_word-level_one-hot_encoding.py","file_name":"6-3Using_Keras_for_word-level_one-hot_encoding.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"106528856","text":"import os\nfrom PIL import Image\n\nrawPercent = int(input(\"Please enter desired percentage to scale to\\n\"))\npath = os.getcwd()\npercent = rawPercent/100\n\nfor file in os.listdir(\".\"):\n if file.endswith(\".png\") or file.endswith(\".jpg\"):\n newName = file.split('.')[0] + '_resized_{0}%.'.format(rawPercent) + file.split('.')[1]\n\n img = Image.open(path + '\\\\' + file)\n width = int(img.size[0] * percent)\n height = int(img.size[1] * percent)\n\n img.thumbnail((width, height), Image.ANTIALIAS)\n img.save(str(newName))\n print('Successfully resized {0} to {1}%'.format(file, rawPercent))\n\n","sub_path":"resizer.py","file_name":"resizer.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"535511505","text":"from cvservices.models import *\nfrom cvinterface.views.base_views import *\n\nvocabulary_list_view = DefaultVocabularyListView\nvocabulary_detail_view = DefaultVocabularyDetailView\nvocabulary_list_template = 'cvinterface/vocabularies/default_list.html'\nvocabulary_detail_template = 'cvinterface/vocabularies/default_detail.html'\n\nrequest_list_view = DefaultRequestListView\nrequest_create_view = DefaultRequestCreateView\nrequest_update_view = DefaultRequestUpdateView\nrequest_list_template = 'cvinterface/requests/default_list.html'\nrequest_create_template = 'cvinterface/requests/default_form.html'\nrequest_update_template = 'cvinterface/requests/default_update_form.html'\n\nvocabularies = {\n # optional keys:\n # list_view, detail_view, list_template, detail_template\n\n 'methodtype': {\n 'name': MethodType._meta.verbose_name,\n 'definition': 'A term for describing types of Methods associated with recording or generating data values to attributes. Example method types are like \"expert opinion\", \"field procedure\", \"model simulation\".',\n 'model': MethodType,\n },\n \n 'resourcetype': {\n 'name': ResourceType._meta.verbose_name,\n 'definition': 'A term for describing types of systems models. Example resource types are WEAP, RiverWare, EPANET',\n 'model': ResourceType,\n },\n \n \n 'aggregationstatistic': {\n 'name': AggregationStatistic._meta.verbose_name,\n 'definition': 'A term for describing the statistical action used to calculate over recorded time series values within a time interval. For example, 100 cfs of delivery target to a demand site is a \"cumulative\" aggregation statistic calculated over a time interval like a month.',\n 'model': AggregationStatistic,\n },\n 'elevationdatum': {\n 'name': ElevationDatum._meta.verbose_name,\n 'definition': 'A term for describing vertical datums. Vertical datums are used in WaMDaM to specify the origin for elevations associated with node instance in networks.',\n 'model': ElevationDatum,\n },\n 'seasonname': {\n 'name': SeasonName._meta.verbose_name,\n 'definition': 'A term for describing a categorical value that may correspond to numeric values of an attribute. The CategoricalValue represents steps in time (e.g., Winter, Summer, March, April) or space (e.g., categorical levels of reservoir levels (e.g., inactive, conservation, flood)',\n 'model': SeasonName,\n },\n 'units': {\n 'name': Units._meta.verbose_name,\n 'definition': 'A term for describing the name of the Unit of data value of an attribute.',\n 'model': Units,\n },\n 'objecttypology': {\n 'name': ObjectTypology._meta.verbose_name,\n 'definition': 'A term for describing the category of an Object Type as either: Node, link, network.',\n 'model': ObjectTypology,\n },\n 'attributename': {\n 'name': AttributeName._meta.verbose_name,\n 'definition': 'A Term describing the name of quantitate or qualitative property of a water system component (e.g., reservoir).',\n 'model': AttributeName,\n },\n 'attributedatatype': {\n 'name': AttributeDataType._meta.verbose_name,\n 'definition': 'A term for describing the supported types of data that an attribute in WaMDaM can take based on logical and physical groupings like numeric, text, time stamped values, and parried categorical values. For example, numeric values, descriptor value, electronic files, time series, and multi attribute series.',\n 'model': AttributeDataType,\n },\n 'electronicfileformat': {\n 'name': ElectronicFileFormat._meta.verbose_name,\n 'definition': 'A term for describing the supported physical format of files loaded into WaMDaM as values to attributes(e.g., csv, jpg, NETCDF).',\n 'model': ElectronicFileFormat,\n },\n 'spatialreference': {\n 'name': SpatialReference._meta.verbose_name,\n 'definition': 'A term for describing a geographic reference to all the node instances that belong to the same Master Network.',\n 'model': SpatialReference,\n },\n 'instancename': {\n 'name': InstanceName._meta.verbose_name,\n 'definition': 'A term for describing the name of a specific node or link system component in a specific location which can related synonymous native instance terms (e.g., Hyrum = Hrm & Hyrum Reservoir).',\n 'model': InstanceName,\n },\n 'objecttype': {\n 'name': ObjectType._meta.verbose_name,\n 'definition': 'A term for describing a built or natural water system component .',\n 'model': ObjectType,\n },\n 'categorical': {\n 'name': Categorical._meta.verbose_name,\n 'definition': 'A term for describing descriptive values (characters as numeric or strings) for an attribute. The descriptor values can be shared across attributes of systems components like land use \"Grass_Pasture\" or irrigation type \"Flood\", or site code as \"10000010\"',\n 'model': Categorical,\n }\n}\n\nrequests = {\n # optional keys:\n # list_view, create_view, update_view, list_template, create_template, update_template\n\n 'methodtyperequest': {\n 'vocabulary': 'methodtype',\n 'vocabulary_model': MethodType,\n 'name': MethodTypeRequest._meta.verbose_name,\n 'model': MethodTypeRequest,\n },\n 'resourcetyperequest': {\n 'vocabulary': 'resourcetype',\n 'vocabulary_model': ResourceType,\n 'name': ResourceTypeRequest._meta.verbose_name,\n 'model': ResourceTypeRequest, \n },\n \n 'aggregationstatisticrequest': {\n 'vocabulary': 'aggregationstatistic',\n 'vocabulary_model': AggregationStatistic,\n 'name': AggregationStatisticRequest._meta.verbose_name,\n 'model': AggregationStatisticRequest,\n },\n 'elevationdatumrequest': {\n 'vocabulary': 'elevationdatum',\n 'vocabulary_model': ElevationDatum,\n 'name': ElevationDatumRequest._meta.verbose_name,\n 'model': ElevationDatumRequest,\n },\n 'seasonnamerequest': {\n 'vocabulary': 'seasonname',\n 'vocabulary_model': SeasonName,\n 'name': SeasonNameRequest._meta.verbose_name,\n 'model': SeasonNameRequest,\n },\n 'unitsrequest': {\n 'vocabulary': 'units',\n 'vocabulary_model': Units,\n 'name': UnitsRequest._meta.verbose_name,\n 'model': UnitsRequest,\n },\n 'objecttypologyrequest': {\n 'vocabulary': 'objecttypology',\n 'vocabulary_model': ObjectTypology,\n 'name': ObjectTypologyRequest._meta.verbose_name,\n 'model': ObjectTypologyRequest,\n },\n 'attributenamerequest': {\n 'vocabulary': 'attributename',\n 'vocabulary_model': AttributeName,\n 'name': AttributeNameRequest._meta.verbose_name,\n 'model': AttributeNameRequest,\n },\n 'attributedatatyperequest': {\n 'vocabulary': 'attributedatatype',\n 'vocabulary_model': AttributeDataType,\n 'name': AttributeDataTypeRequest._meta.verbose_name,\n 'model': AttributeDataTypeRequest,\n },\n 'electronicfileformatrequest': {\n 'vocabulary': 'electronicfileformat',\n 'vocabulary_model': ElectronicFileFormat,\n 'name': ElectronicFileFormatRequest._meta.verbose_name,\n 'model': ElectronicFileFormatRequest,\n },\n 'spatialreferencerequest': {\n 'vocabulary': 'spatialreference',\n 'vocabulary_model': SpatialReference,\n 'name': SpatialReferenceRequest._meta.verbose_name,\n 'model': SpatialReferenceRequest,\n },\n 'instancenamerequest': {\n 'vocabulary': 'instancename',\n 'vocabulary_model': InstanceName,\n 'name': InstanceNameRequest._meta.verbose_name,\n 'model': InstanceNameRequest,\n },\n 'objecttyperequest': {\n 'vocabulary': 'objecttype',\n 'vocabulary_model': ObjectType,\n 'name': ObjectTypeRequest._meta.verbose_name,\n 'model': ObjectTypeRequest,\n },\n 'categoricalrequest': {\n 'vocabulary': 'categorical',\n 'vocabulary_model': Categorical,\n 'name': CategoricalRequest._meta.verbose_name,\n 'model': CategoricalRequest,\n }\n}\n\n","sub_path":"cvinterface/controlled_vocabularies.py","file_name":"controlled_vocabularies.py","file_ext":"py","file_size_in_byte":8147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"632598263","text":"#! /usr/bin/env python3\n\n# -----------------------------------\n# Version: 0.0.1\n# Author: Lennard Böhnke\n# Description: Insert description here\n# Last modified: 2017-12-06T17:21:00.291Z\n# -----------------------------------\n\ndef combine(list_1, list_2):\n \"\"\"Function description\"\"\"\n combined_list = []\n if len(list_1) < len(list_2):\n for i in range(len(list_2)):\n combined_list.append(list_2[i])\n if i < len(list_1):\n combined_list.append(list_1[i])\n elif len(list_1) > len(list_2):\n for i in range(len(list_1)):\n combined_list.append(list_1[i])\n if i < len(list_2):\n combined_list.append(list_2[i])\n return print(combined_list)\n\nif __name__ == \"__main__\":\n\n list_1 = [num for num in range(1,9)]\n list_2 = [num for num in range(-1,-3,-1)]\n print(list_1)\n print(list_2)\n\n combine(list_1, list_2)\n\n vowels = set(\"aeiou\")\n string_test = \"simon\"\n print([letter for letter in string_test if letter in vowels])\n\n celsius = [17,13,25,30,25,32,40]\n print([(fahrenheit*9/5)+32 for fahrenheit in celsius])\n","sub_path":"Tutorium/20171206.py","file_name":"20171206.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"67794400","text":"from collections import defaultdict\n\n\nclass Graph:\n\n def __init__(self):\n self.graph_dict = defaultdict(list)\n\n def addEdge(self, u, v):\n self.graph_dict[u].append(v)\n\n def dfs(self, visited, v):\n if v not in visited:\n print(v)\n visited.add(v)\n for n in self.graph_dict[v]:\n self.dfs(visited, n)\n\n\ng = Graph()\ng.addEdge(0, 1)\ng.addEdge(0, 2)\ng.addEdge(1, 2)\ng.addEdge(2, 0)\ng.addEdge(2, 3)\ng.addEdge(3, 3)\nvisited = set()\nprint(g.graph_dict)\ng.dfs(visited, 0)\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"DFS/DFS.py","file_name":"DFS.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"477881041","text":"from Functions.file import get_data, write_data\r\nfrom Functions.Algorithms import LCM\r\n\r\n\r\nr1, r2, r3 = map(int, get_data(\"input.txt\"))\r\n\r\ncommon = LCM(r1, LCM(r2, r3))\r\nvalues = list(map(lambda x: common // x, (r1, r2, r3)))\r\n\r\nout = \"%s %s %s\" % tuple(values)\r\n\r\nwrite_data(\"output.txt\", out)","sub_path":"task2.5.py","file_name":"task2.5.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"11406466","text":"import plyvel\nimport argparse\n\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('artist', type=str, help='artist')\n args = parser.parse_args()\n\n name_area_db = plyvel.DB('result/knock60_result.ldb', create_if_missing=False)\n name_artist = args.artist.encode('utf-8')\n if name_area_db.get(name_artist):\n print('{}: {}'.format(name_artist.decode('utf-8'), name_area_db.get(name_artist).decode('utf-8')))\n else:\n print('Not found.')\n name_area_db.close()\n","sub_path":"Shi-ma/chapter07/knock61.py","file_name":"knock61.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"147535268","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\n#Author:Ying HongBin\n\nimport numpy as np\nimport torch\nfrom PIL import Image\n\nif __name__ == '__main__':\n img = Image.open('test_3.jpg').convert('L')\n arr = []\n for i in range(28):\n for j in range(28):\n pixel = 1.0 - float(img.getpixel((j, i))) / 255.0\n arr.append(pixel)\n arr1 = np.array(arr).reshape(1, 1, 28, 28)\n #arr1 = np.array(arr).reshape(1, 28, 28, 1)\n data = torch.from_numpy(arr1).float()\n #print(arr1.shape())\n print(data.size())\n\n model = torch.load('cnn.pkl')\n output = model(data)[0]\n print(output)\n","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"409628739","text":"from __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.utils import timezone\n# https://docs.djangoproject.com/en/1.11/ref/contrib/postgres/fields/#django.contrib.postgres.fields.JSONField\n# https://docs.djangoproject.com/en/1.11/ref/models/fields/#default\nfrom django.contrib.postgres.fields import JSONField\n\n# Create your models here.\n\nclass SocialBase(models.Model):\n\t# https://docs.djangoproject.com/en/1.11/ref/models/fields/#choices\n\tWECHAT = 'WX'\n\tFACEBOOK = 'FB'\n\tSOCIAL_TYPE = (\n\t\t(WECHAT, 'wechat'),\n\t\t(FACEBOOK, 'facebook'),\n\t)\n\tsocial_app = models.CharField(\n\t\tmax_length=2,\n\t\tchoices=SOCIAL_TYPE,\n\t\tdefault=WECHAT\n\t)\n\n\tclass Meta:\n\t\tabstract = True\n\n\nclass SocialAccount(SocialBase):\n\tuid = models.CharField(\n\t\tmax_length=256,\n\t\tnull=False,\n\t\tblank=False\n\t)\n\tuser_name = models.CharField(\n\t\tmax_length=256,\n\t\tnull=True,\n\t\tblank=True\n\t)\n\tavatar = models.CharField(\n\t\tmax_length=2048,\n\t\tnull=True,\n\t\tblank=True\n\t)\n\tdate_joined = models.DateTimeField(\n\t\tdefault=timezone.now\n\t)\n\textra_data = JSONField()\n\n\tclass Meta:\n\t\tunique_together = ('social_app', 'uid')\n\n\nclass SocialToken(SocialBase):\n\t# https://docs.djangoproject.com/en/1.11/ref/models/fields/#textfield\n\ttoken = models.CharField(\n\t\tmax_length=256,\n\t\tnull=False,\n\t\tblank=False\n\t)\n\texpires_at = models.FloatField(\n\t\tnull=True,\n\t\tblank=True,\n\t)","sub_path":"Django/django-wechat/django_wechat/authentication/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"582995310","text":"#!/usr/bin/env python\r\n\r\nimport os\r\nimport json\r\nimport redis\r\nfrom flask import Flask\r\nfrom flask import request\r\nfrom linkextractor import extract_links\r\n\r\napp = Flask(__name__)\r\nredis_conn = redis.from_url(os.getenv(\"REDIS_URL\", \"redis://localhost:6379\"))\r\n\r\n@app.route(\"/\")\r\ndef index():\r\n return \"Usage: http://[:]/api/\"\r\n\r\n@app.route(\"/api/\")\r\ndef api(url):\r\n qs = request.query_string.decode(\"utf-8\")\r\n if qs != \"\":\r\n url += \"?\" + qs\r\n\r\n jsonlinks = redis_conn.get(url)\r\n if not jsonlinks:\r\n links = extract_links(url)\r\n jsonlinks = json.dumps(links, indent=2)\r\n redis_conn.set(url, jsonlinks)\r\n\r\n response = app.response_class(\r\n status=200,\r\n mimetype=\"application/json\",\r\n response=jsonlinks\r\n )\r\n\r\n return response\r\n\r\napp.run(host=\"0.0.0.0\")\r\n","sub_path":"test/linkextractor/step5/api/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"268319280","text":"# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport unittest\nfrom unittest import mock\nimport requests\nfrom datetime import datetime\nfrom datetime import timedelta\n\nfrom webservice.redirect import RemoteSDAPCache\nfrom webservice.redirect import CollectionNotFound\nfrom webservice.redirect.RemoteSDAPCache import RemoteSDAPList\n\nclass MockResponse:\n def __init__(self, json_data, status_code):\n self.json_data = json_data\n self.status_code = status_code\n\n def json(self):\n return self.json_data\n\nLIST_CONTENT = [\n {\n \"shortName\": \"PM25\",\n \"title\": \"PM25\",\n \"tileCount\": 21515,\n \"start\": 1514818800.0,\n \"end\": 1640991600.0,\n \"iso_start\": \"2018-01-01T15:00:00+0000\",\n \"iso_end\": \"2021-12-31T23:00:00+0000\"\n }\n ]\n\nLIST_CONTENT_FORMER = [LIST_CONTENT[0].copy()]\nLIST_CONTENT_FORMER[0]['start'] = 0\n\ndef mocked_requests_get(*asgs, **kwargs):\n return MockResponse(LIST_CONTENT, 200)\n\n\ndef mocked_requests_get_timeout(*asgs, **kwargs):\n raise requests.exceptions.ConnectTimeout()\n\n\ndef mocked_requests_get_not_found(*asgs, **kwargs):\n return MockResponse({}, 404)\n\n\n\nclass MyTestCase(unittest.TestCase):\n\n @mock.patch('requests.get', side_effect=mocked_requests_get)\n def test_get(self, mock_get):\n remote_sdap_cache = RemoteSDAPCache()\n\n collection = remote_sdap_cache.get('https://aq-sdap.stcenter.net/nexus/', 'PM25')\n self.assertEqual(collection[\"start\"], 1514818800.0)\n\n @mock.patch('requests.get', side_effect=mocked_requests_get_timeout)\n def test_get_timeout(self, mock_get):\n remote_sdap_cache = RemoteSDAPCache()\n with self.assertRaises(CollectionNotFound):\n remote_sdap_cache.get('https://aq-sdap.stcenter.net/nexus/', 'PM25')\n\n\n @mock.patch('requests.get', side_effect=mocked_requests_get_not_found)\n def test_get_not_found(self, mock_get):\n remote_sdap_cache = RemoteSDAPCache()\n with self.assertRaises(CollectionNotFound):\n remote_sdap_cache.get('https://aq-sdap.stcenter.net/nexus/', 'PM25')\n\n @mock.patch('requests.get', side_effect=mocked_requests_get)\n def test_get_expired(self, mock_get):\n remote_sdap_cache = RemoteSDAPCache()\n\n remote_sdap_cache.sdap_lists['https://aq-sdap.stcenter.net/nexus/'] = RemoteSDAPList(\n list=LIST_CONTENT_FORMER,\n outdated_at=datetime.now() - timedelta(seconds=3600*25)\n )\n\n collection = remote_sdap_cache.get('https://aq-sdap.stcenter.net/nexus/', 'PM25')\n\n # check requests.get is called once\n self.assertEqual(mock_get.call_count, 1)\n self.assertEqual(collection[\"start\"], 1514818800.0)\n\n @mock.patch('requests.get', side_effect=mocked_requests_get)\n def test_get_cached_valid(self, mock_get):\n remote_sdap_cache = RemoteSDAPCache()\n\n remote_sdap_cache.sdap_lists['https://aq-sdap.stcenter.net/nexus'] = RemoteSDAPList(\n list=LIST_CONTENT_FORMER,\n outdated_at=datetime.now() - timedelta(seconds=3600 * 23)\n )\n\n collection = remote_sdap_cache.get('https://aq-sdap.stcenter.net/nexus/', 'PM25')\n\n # check requests.get is called once\n self.assertEqual(mock_get.call_count, 0)\n self.assertEqual(collection[\"start\"], 0)\n\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"analysis/tests/redirect/test_RemoteSDAPCache.py","file_name":"test_RemoteSDAPCache.py","file_ext":"py","file_size_in_byte":4086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"550386231","text":"import subprocess\nfrom src.color_print import *\nfrom src.read_file import *\nimport requests\nfrom multiprocessing import Pool\nfrom tqdm import tqdm\nfrom src.get_user_agent import *\n\n\n\ndef oneforall(target):\n ONEFORALL_OUTPUT_PATH = './output/oneforall.txt'\n CMD_STR = \"python3 ./OneForAll-master/oneforall.py --target {target} --path={ONEFORALL_OUTPUT_PATH} run\".format(\n ONEFORALL_OUTPUT_PATH=ONEFORALL_OUTPUT_PATH, target=target)\n print_info('使用OneForAll扫描 Command: ' + color.yellow(CMD_STR))\n CMD = CMD_STR.split(' ')\n rsp = subprocess.Popen(CMD)\n rsp.communicate()\n\n\ndef get_oneforall_info(info): # 对oneforall查询到的子域名去重\n l = []\n for i in info:\n tmp = i.strip().split(',')\n l.append(tmp[5])\n result = set(l)\n return_list = list(result)\n return return_list\n\n\ndef get_subdomain(url, output=None):\n oneforall(url) # Oneforall扫描\n info = read_file('./output/oneforall.txt')\n oneforall_url = get_oneforall_info(info) # 子域名列表\n print_info('对子域名可访问性进行扫描')\n alive_url = judge_get_addressable_url(oneforall_url)\n if output == None:\n Table = PrettyTable(['Subdomain'])\n for subdomain_url in alive_url:\n Table.add_row([subdomain_url])\n print(Table)\n else:\n f = open(output, 'w')\n for subdomain_url in alive_url:\n f.write(subdomain_url + '\\n')\n f.close()\n\n\n\ndef request_get_url(pool_get_url): # 判断url是否可以访问\n try:\n r = requests.request(method='GET', url=pool_get_url, headers=get_user_agent(), timeout=(3, 7)).status_code\n if r == 200:\n return 1, pool_get_url\n else:\n return 0, pool_get_url\n except:\n return 0, pool_get_url,\n\n\ndef judge_get_addressable_url(sub_list): # 判断GET可访问的域名\n scan_url_list = []\n alive_url = []\n for line in sub_list:\n if line.startswith('https://'):\n tmp_url = line.replace('https://', 'http://')\n elif line.startswith('http://'):\n tmp_url = line\n else:\n tmp_url = 'http://' + line\n scan_url_list.append(tmp_url)\n # print(scan_url_list)\n thread_count = 10\n print_info('使用 ' + str(thread_count) + ' 线程')\n with Pool(10) as p:\n pool_result = list(tqdm(p.imap(request_get_url, scan_url_list), total=len(scan_url_list)))\n for result in pool_result:\n if result[0] == 1:\n alive_url.append(str(result[1]).replace('http://', ''))\n return alive_url\n\n\n","sub_path":"src/subdomain_brute.py","file_name":"subdomain_brute.py","file_ext":"py","file_size_in_byte":2571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"152687484","text":"import glob\r\nfrom betting_strategies import *\r\nfrom read_records import *\r\nimport numpy as np\r\n\r\n\r\ndef backtest():\r\n \"\"\"\r\n Test a given strategy on a set of games.\r\n :param games: list of valid Game objects\r\n :param strategy: desired strategy to backtest\r\n :param verbose: boolean to control printing\r\n :return: a list of the profit the strategy yields for each game\r\n \"\"\"\r\n records_dir = 'C:/Users/User/Desktop/arbo-master/DB/betfair/football_metadata'\r\n all_records = glob.glob(records_dir + '/*.txt')\r\n a = all_records[0]\r\n b = 1\r\n redcardcounter = 0\r\n\r\n for f in all_records:\r\n gamename = f.strip('C:/Users/User/Desktop/arbo-master/DB/betfair/football_metadata\\\\').strip('.txt')\r\n filepath = 'C:/Users/User/Desktop/arbo-master/DB/betfair/games_with_red_card.txt'\r\n # open new/existing file\r\n if os.path.isfile(filepath):\r\n currfile = open(filepath, \"ab+\")\r\n else:\r\n currfile = open(filepath, \"wb+\")\r\n\r\n try:\r\n gamefile = open(f)\r\n except:\r\n print('Did not find the file for ' + f)\r\n\r\n linelist = gamefile.readlines()\r\n homeredcards = linelist[4].strip('\\n')\r\n awayredcards = linelist[7].strip('\\n')\r\n\r\n isredcards = False\r\n print(gamename)\r\n if (homeredcards == '[]') & (awayredcards == '[]'):\r\n isredcards = False\r\n print(str(isredcards))\r\n print (homeredcards + awayredcards)\r\n else:\r\n isredcards = True\r\n print(str(isredcards))\r\n print (homeredcards + awayredcards)\r\n redcardcounter += 1\r\n\r\n\r\n if isredcards == True:\r\n linetowrite = gamename\r\n currfile.write((linetowrite + '\\n').encode(encoding='utf-8'))\r\n print(redcardcounter)\r\n\r\n\r\n\r\n\r\n\r\n\r\nbacktest()\r\n","sub_path":"Kelly/get_games_with_red_card.py","file_name":"get_games_with_red_card.py","file_ext":"py","file_size_in_byte":1852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"324032653","text":"from __future__ import annotations\nfrom math import cos, sin\nfrom raytracer import EPSILON\nfrom .tuples import Tuple, dot, Point, Vector, cross\nfrom typing import List\n\n\nclass Matrix:\n def __init__(self, values: List[List[float]] = None):\n self.values = values if values is not None else [[0, 0, 0, 0] for _ in range(4)]\n\n @property\n def size(self):\n rows = len(self.values)\n cols = max([len(col) for col in self.values])\n return max(rows, cols)\n\n def __getitem__(self, key):\n if not isinstance(key, tuple) and len(key) != 2 and not isinstance(key[0], int) and not isinstance(key[1], int):\n raise TypeError(\"wrong subscript: not an 2-tuple of int\")\n return self.values[key[0]][key[1]]\n\n def __setitem__(self, key, value):\n if not isinstance(key, tuple) and len(key) != 2 and not isinstance(key[0], int) and not isinstance(key[1], int):\n raise TypeError(\"wrong subscript: not an 2-tuple of int\")\n self.values[key[0]][key[1]] = value\n\n def __eq__(self, other):\n if self.size != other.size:\n return False\n for row in range(self.size):\n for col in range(self.size):\n if abs(self[row, col] - other[row, col]) >= EPSILON:\n return False\n return True\n\n def __mul__(self, other):\n if isinstance(other, Matrix):\n return self._multiply_by_matrix(other)\n elif isinstance(other, Tuple):\n return self._multiply_by_tuple(other)\n raise TypeError(f\"multiplying matrix by {type(other)} not supported\")\n\n def _multiply_by_matrix(self, other: Matrix):\n m = Matrix()\n for row in range(4):\n for col in range(4):\n m[row, col] = self[row, 0] * other[0, col] + \\\n self[row, 1] * other[1, col] + \\\n self[row, 2] * other[2, col] + \\\n self[row, 3] * other[3, col]\n return m\n\n def _multiply_by_tuple(self, _tuple: Tuple):\n products = []\n for row in range(4):\n result = dot(Tuple(*self.values[row]), _tuple)\n products.append(result)\n return Tuple.create_from(*products)\n\n def row(self, row_nr):\n return self.values[row_nr]\n\n def col(self, col_nr):\n return [r[col_nr] for r in self.values]\n\n def transpose(self) -> Matrix:\n m = Matrix()\n size = self.size\n for row in range(size):\n for col in range(size):\n m[row, col] = self[col, row]\n return m\n\n def determinant(self) -> float:\n if self.size == 2:\n return self[0, 0] * self[1, 1] - self[0, 1] * self[1, 0]\n else:\n products = [el * self.cofactor(0, col) for col, el in enumerate(self.values[0])]\n return sum(products)\n\n def submatrix(self, row, col):\n values = [r[:col] + r[col + 1:] for i, r in enumerate(self.values) if i != row]\n return Matrix(values)\n\n def minor(self, row, col):\n return self.submatrix(row, col).determinant()\n\n def cofactor(self, row, col):\n if (row + col) % 2:\n return -self.minor(row, col)\n else:\n return self.minor(row, col)\n\n @property\n def invertible(self) -> bool:\n return self.determinant() != 0\n\n def inverse(self):\n if not self.invertible:\n raise ValueError('matrix is invertible')\n inverted = Matrix([[0] * self.size for _ in range(self.size)])\n det = self.determinant()\n for row in range(self.size):\n for col in range(self.size):\n cf = self.cofactor(row, col)\n inverted[col, row] = cf / det\n return inverted\n\n def copy(self):\n copy_values = [row[:] for row in self.values]\n return Matrix(copy_values)\n\n @staticmethod\n def identity():\n return Matrix([[1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1]])\n\n def translate(self, x, y, z):\n return Matrix([[1, 0, 0, x],\n [0, 1, 0, y],\n [0, 0, 1, z],\n [0, 0, 0, 1]]) * self\n\n def scale(self, x, y, z):\n return scaling(x, y, z) * self\n\n def rotate_x(self, radians: float):\n return rotation_x(radians) * self\n\n def rotate_y(self, radians: float):\n return rotation_y(radians) * self\n\n def rotate_z(self, radians: float):\n return rotation_z(radians) * self\n\n def shear(self, x2y, x2z, y2x, y2z, z2x, z2y):\n return shearing(x2y, x2z, y2x, y2z, z2x, z2y) * self\n\n def __str__(self):\n return '[' + '\\n '.join([str(row) for row in self.values]) + ']'\n\n __repr__ = __str__\n\n\ndef translation(x, y, z) -> Matrix:\n tr = Matrix.identity()\n tr[0, 3] = x\n tr[1, 3] = y\n tr[2, 3] = z\n return tr\n\n\ndef scaling(x, y, z) -> Matrix:\n sc = Matrix.identity()\n sc[0, 0] = x\n sc[1, 1] = y\n sc[2, 2] = z\n return sc\n\n\ndef rotation_x(radians: float) -> Matrix:\n rot = Matrix.identity()\n rot[1, 1] = cos(radians)\n rot[1, 2] = -sin(radians)\n rot[2, 1] = sin(radians)\n rot[2, 2] = cos(radians)\n return rot\n\n\ndef rotation_y(radians: float) -> Matrix:\n rot = Matrix.identity()\n rot[0, 0] = cos(radians)\n rot[0, 2] = sin(radians)\n rot[2, 0] = -sin(radians)\n rot[2, 2] = cos(radians)\n return rot\n\n\ndef rotation_z(radians: float) -> Matrix:\n rot = Matrix.identity()\n rot[0, 0] = cos(radians)\n rot[0, 1] = -sin(radians)\n rot[1, 0] = sin(radians)\n rot[1, 1] = cos(radians)\n return rot\n\n\ndef shearing(x2y, x2z, y2x, y2z, z2x, z2y) -> Matrix:\n rot = Matrix.identity()\n rot[0, 1] = x2y\n rot[0, 2] = x2z\n rot[1, 0] = y2x\n rot[1, 2] = y2z\n rot[2, 0] = z2x\n rot[2, 1] = z2y\n return rot\n\n\ndef view_transform(_from: Point, to: Point, up: Vector) -> Matrix:\n forward = (to - _from).normalize()\n left = cross(forward, up.normalize())\n true_up = cross(left, forward)\n orientation = Matrix([[left.x, left.y, left.z, 0],\n [true_up.x, true_up.y, true_up.z, 0],\n [-forward.x, -forward.y, -forward.z, 0],\n [0, 0, 0, 1]])\n return orientation * translation(-_from.x, -_from.y, -_from.z)\n\n","sub_path":"src/raytracer/matrices.py","file_name":"matrices.py","file_ext":"py","file_size_in_byte":6367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"312879494","text":"# -*- coding: utf-8 -*-\n\nimport base64\nimport pickle\nimport json\nfrom odoo import api, fields, models, _, tools\nfrom odoo.exceptions import UserError\nfrom odoo.tools.safe_eval import safe_eval\n\nclass MassMailing(models.Model):\n _inherit = 'mail.mass_mailing'\n\n Mail_Limit_Min = 150\n Mail_Action = 'send_mail'\n\n def send_mail(self):\n Mails = self.env['mail.mail']\n author_id = self.env.user.partner_id.id\n smtp_info = self.get_smtp_info()\n for mailing in self:\n # instantiate an email composer + send emails\n res_ids = mailing.get_remaining_recipients()\n if not res_ids:\n raise UserError(_('Please select recipients.'))\n\n # Convert links in absolute URLs before the application of the shortener\n mailing.body_html = self.env['mail.template']._replace_local_links(mailing.body_html)\n\n composer_values = {\n 'author_id': author_id,\n 'attachment_ids': [(4, attachment.id) for attachment in mailing.attachment_ids],\n 'body': mailing.convert_links()[mailing.id],\n 'subject': mailing.name,\n 'model': mailing.mailing_model,\n 'email_from': mailing.email_from,\n 'record_name': False,\n 'composition_mode': 'mass_mail',\n 'mass_mailing_id': mailing.id,\n 'mailing_list_ids': [(4, l.id) for l in mailing.contact_list_ids],\n 'no_auto_thread': mailing.reply_to_mode != 'thread',\n }\n if mailing.reply_to_mode == 'email':\n composer_values['reply_to'] = mailing.reply_to\n\n composer = self.env['mail.compose.message'].with_context(active_ids=res_ids).create(composer_values)\n Mails += composer.with_context(active_ids=res_ids, mass_mailing_send_mail=True).send_mail(auto_commit=True)\n mailing.state = 'done'\n\n separate_data, general_data = self.compute_mail_data(Mails)\n for separate_item in separate_data:\n self.env['mailing.queue'].send_message_action(self.Mail_Action, json.dumps({\n 'general': general_data,\n 'data': separate_item,\n 'smtp': smtp_info,\n }))\n for Mail in Mails:\n Mail.state = 'sent'\n # if smtp_attrs:\n # multi_processing._multiprocessing_mass_mailing_min(msg_list, smtp_attrs)\n\n return True\n\n @api.model\n def get_mails(self):\n result = self.env['mailing.queue'].get_message_action(10, self.Mail_Action)\n return result\n\n @api.model\n def get_smtp_info(self):\n IrMailServer = self.env['ir.mail_server']\n mail_server = IrMailServer.sudo().search([], order='sequence', limit=1)\n if mail_server:\n return {\n 'smtp_server' : mail_server.smtp_host,\n 'smtp_port' : mail_server.smtp_port,\n 'smtp_user' : mail_server.smtp_user,\n 'smtp_password' : mail_server.smtp_pass,\n 'smtp_encryption' : mail_server.smtp_encryption,\n }\n return False\n\n @api.model\n def compute_mail_data(self, mails):\n separate_data = []\n general_data = self.compute_mail_general_data(mails[0])\n for mail in mails:\n for res in self.compute_mail_separate_data(mail):\n separate_data.append(res)\n return [separate_data, general_data]\n\n @api.model\n def compute_mail_general_data(self, mail):\n attachments = [(a['datas_fname'], base64.b64decode(a['datas']))\n for a in mail.attachment_ids.sudo().read(['datas_fname', 'datas'])]\n data = {\n 'email_from': mail.email_from,\n 'subject': mail.subject,\n 'reply_to': mail.reply_to,\n 'subtype': 'html',\n 'attachments': attachments,\n 'subtype_alternative': 'plain',\n 'object_id': mail.res_id and ('%s-%s' % (mail.res_id, mail.model)),\n }\n return data\n\n @api.model\n def compute_mail_separate_data(self, mail):\n res = []\n # headers\n headers = {}\n bounce_alias = self.env['ir.config_parameter'].get_param(\"mail.bounce.alias\")\n catchall_domain = self.env['ir.config_parameter'].get_param(\"mail.catchall.domain\")\n if bounce_alias and catchall_domain:\n if mail.model and mail.res_id:\n headers['Return-Path'] = '%s+%d-%s-%d@%s' % (\n bounce_alias, mail.id, mail.model, mail.res_id, catchall_domain)\n else:\n headers['Return-Path'] = '%s+%d@%s' % (bounce_alias, mail.id, catchall_domain)\n if mail.headers:\n try:\n headers.update(safe_eval(mail.headers))\n except Exception:\n pass\n\n email_list = []\n if mail.email_to:\n email_list.append(mail.send_get_email_dict())\n for partner in mail.recipient_ids:\n email_list.append(mail.send_get_email_dict(partner=partner))\n\n for email in email_list:\n msg = {\n 'email_to': email.get('email_to'),\n 'body': email.get('body'),\n 'body_alternative': email.get('body_alternative'),\n 'email_cc': tools.email_split(mail.email_cc),\n 'message_id': mail.message_id,\n 'references': mail.references,\n 'headers': headers,\n }\n res.append(msg)\n return res\n\n @api.model\n def build_mail(self, datas):\n IrMailServer = self.env['ir.mail_server']\n res = []\n separate_data, simple_data = datas\n for record in separate_data:\n msg_list = IrMailServer.build_email(\n email_from=simple_data.get('email_from'),\n email_to=record.get('email_to'),\n subject=simple_data.get('subject'),\n body=record.get('body'),\n body_alternative=record.get('body_alternative'),\n email_cc=record.get('email_cc'),\n reply_to=simple_data.get('reply_to'),\n attachments=simple_data.get('attachments'),\n message_id=record.get('message_id'),\n references=record.get('references'),\n object_id=simple_data.get('object_id'),\n subtype='html',\n subtype_alternative='plain',\n headers=record.get('headers'),\n )\n res.append(msg_list)\n return res","sub_path":"beta-dev1/opt/odoo/odoo/addons/core/mass_mailing_delimiter/models/mass_mailing.py","file_name":"mass_mailing.py","file_ext":"py","file_size_in_byte":6620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"136837858","text":"import sqlite3\nfrom flask import Flask, render_template, request, g\nfrom flask_library import config_db, picture_time, config_html\nimport os\nimport pandas as pd\nimport calendar\n\n\napp = Flask(__name__, static_folder = \"html/static\", template_folder = \"html/templates\")\n\n##################### setup ########################################################################\nUPLOAD_FOLDER = \"./html/static/uploads/\"\n\nstudents_table = config_db.students_table\npicture_table = config_db.picture_table\nresult_html = config_html.html_string\n\n\ndef get_db():\n db = getattr(g, '_database', None)\n if db is None:\n db = g._database = sqlite3.connect('datebase/test_sqlite3.db')\n return db\n\n@app.teardown_appcontext\ndef close_db(error):\n if hasattr(g, 'test_sqlite3.db'):\n g.sqlite_db.close()\n\n##################### main #########################################################################\n\n@app.route(\"/\")\ndef route_page():\n return render_template(\"route_page.html\")\n\n@app.route(\"/search_card\")\ndef search_card():\n pic_time = picture_time.Picture_time()\n now_year = pic_time.now_year\n\n year_list = [now_year, now_year - 1, now_year - 2]\n month_list = [\"01\", \"02\", \"03\", \"04\", \"05\", \"06\", \"07\", \"08\", \"09\", \"10\", \"11\", \"12\"]\n\n return render_template(\"test.html\", year_list = year_list,\n month_list = month_list)\n\n@app.route(\"/search_card/result\", methods = [\"POST\"])\ndef search_result(input_number = None, input_year = None, input_month = None):\n if request.method == \"POST\":\n input_number = request.values.get('input_number', input_number)\n input_year = request.values.get('input_year', input_year)\n input_month = request.values.get('input_month', input_month)\n\n print(input_month)\n\n if input_number == \"\":\n print(\"input_number is null\")\n return \"404\", 404\n # return render_template(\"error_page.html\")\n\n db = get_db()\n curs = db.cursor()\n curs.execute(\n 'SELECT card_uid FROM students_table WHERE student_name = \"{}\"'.format(input_number)\n )\n for x in curs.fetchone():\n print(x)\n card_uid = x\n\n print(\"card_uid is {}\".format(card_uid))\n\n calendar_date = calendar.Calendar()\n calender_month = calendar_date.monthdayscalendar(year = int(input_year), month = int(input_month))\n maximum_value_day = max(calender_month[-1])\n\n\n picture_list = []\n attendance_list = []\n for x in range(1, maximum_value_day):\n search_value = \"{}-{}-{}\".format(input_year, input_month, \"%02d\"%x)\n print(search_value)\n\n curs.execute(\"\"\"\n SELECT first_hour, second_hour, third_hour, fourth_hour FROM \"{}\" WHERE data = '{}'\"\"\".format(card_uid, search_value)\n )\n\n attendance_data = curs.fetchone()\n print(attendance_data)\n if attendance_data is None:\n result = [None, None, None, None]\n else:\n result = []\n for y in attendance_data:\n if y is not None:\n y = \"{}{}.jpg\".format(search_value[-5:].replace(\"-\", \"\"), y.replace(\":\", \"\"))\n result.append(y)\n picture_list.append(result)\n\n if attendance_data is None:\n result = [None, None, None, None]\n else:\n result = []\n for y in attendance_data:\n result.append(y)\n attendance_list.append(result)\n\n print(calender_month)\n\n result_list = zip(attendance_list, picture_list)\n\n for x, y in result_list:\n print(x)\n print(y)\n print(\"\")\n\n return render_template(\"search_result.html\", calender_month = calender_month,\\\n attendance_list = attendance_list, picture_list = picture_list,\\\n select_year = input_year, select_month = input_month,\\\n select_number = input_number)\n\n # return render_template(\"search_result.html\", calender_month = calender_month,\\\n # result_list = result_list, select_year = input_year,\\\n # select_month = input_month, select_number = input_number)\n#################################################\n@app.route(\"/activate\")\ndef activate(Idm = None):\n if request.method == \"POST\":\n Idm = request.values.get(\"Idm\", Idm)\n\n return render_template(\"activate.html\", Idm = Idm)\n\n \n@app.route(\"/activate_card\")\ndef test_serv():\n\n return render_template(\"card_activate.html\")\n\n\n@app.route(\"/activate_card/result\", methods = ['POST', 'PUT', 'DELETE'])\n@app.route(\"/activate_card/result\", methods = ['GET'])\ndef add_name(user_name = None, Idm = None):\n db = get_db()\n curs = db.cursor()\n curs.execute(students_table)\n db.commit()\n\n if request.method == 'POST': #カードの登録\n user_name = request.values.get('user_name', user_name)\n Idm = request.values.get('Idm', Idm)\n\n print(Idm)\n print(user_name)\n Idm = str(Idm)\n\n #すでに登録済みかの確認\n curs.execute(\n 'SELECT student_name FROM students_table WHERE card_uid = \"{}\"'.format(Idm)\n )\n if curs.fetchone() is not None:\n print(curs.fetchone())\n print(\"already\")\n return 'already matching idm'\n\n # students_tableへ登録\n curs.execute(\n 'INSERT INTO students_table(card_uid, student_name) values(\"{}\", \"{}\")'.format(Idm, user_name)\n )\n db.commit()\n #Idm名のtable作成\n print(\"OK\")\n curs.execute(\n \"\"\"\n CREATE TABLE IF NOT EXISTS \"{}\"\n (\n data DATA,\n first_hour TIME,\n second_hour TIME,\n third_hour TIME,\n fourth_hour TIME\n )\n \"\"\".format(Idm)\n )\n db.commit()\n\n return render_template(\"route_page.html\")\n\n\n##################### RaspberryPi ##################################################################\n\n# receive by RaspberryPi\n@app.route('/upload_pic', methods = ['POST'])\ndef upload_pic():\n db = get_db()\n curs = db.cursor()\n curs.execute(picture_table)\n db.commit()\n\n # get time that taked a picture\n pic_time = picture_time.Picture_time()\n pic_name ='{:02}{:02}{:02}{:02}{:02}.jpg'.format(\n pic_time.now_month, pic_time.now_day, pic_time.now_hour, pic_time.now_minute, pic_time.now_second\n )\n\n created_data = pic_time.created_data()\n created_time = pic_time.created_time()\n created_at = pic_time.created_at()\n\n if request.method == \"POST\":\n # take_out and save request.files\n if 'image_file' not in request.files:\n print(\"Error /upload_file\\nNOT FOUND 'image_file'\")\n print(\"image_file not in requests_file\")\n return \"404\"\n Idm = request.values.get(\"Idm\")\n\n print(\"Idm is {}\".format(Idm))\n\n # check Idm is in db\n curs.execute(students_table)\n db.commit()\n curs.execute(\n 'SELECT card_uid FROM students_table WHERE card_uid = \"{}\" '.format(Idm)\n )\n if curs.fetchone() is None:\n print('not matching idm')\n return \"404\"\n \n file = request.files['image_file']\n file.save(os.path.join(app.config['UPLOAD_FOLDER'], pic_name))\n print(\"saved\")\n\n # insert into picture_table\n curs.execute(\n 'INSERT INTO picture_table(card_uid, pic_name, created_at) \\\n values(\"{}\", \"{}\", \"{}\")'.format(Idm, pic_name, created_at)\n )\n db.commit()\n \n\n # inser into Idm_table\n attendance_hour = pic_time.attendance_hour()\n curs.execute(\"\"\"\n SELECT * FROM \"{}\" WHERE data = '{}'\"\"\".format(Idm, created_data)\n )\n\n # print(curs.fetchone()[0])\n\n if curs.fetchone(): # if data is in today_datebase \n\n print(Idm, attendance_hour, created_time, created_data)\n\n curs.execute(\n 'UPDATE \"{}\" SET \"{}\" = \"{}\" WHERE data = \"{}\"'.format(Idm, attendance_hour, created_time, created_data)\n )\n else: # if data isn't in today_datebase \n curs.execute(\n 'INSERT INTO \"{}\"(data, \"{}\") values(\"{}\", \"{}\")'.format(Idm, attendance_hour, created_data, created_time)\n )\n db.commit()\n return \"200\"\n\n####################################################################################################\nif __name__ == \"__main__\":\n app.config[\"UPLOAD_FOLDER\"] = UPLOAD_FOLDER\n app.debug = True\n\n app.run(host = \"127.0.0.1\", port = 5000)","sub_path":"system/flask_main.py","file_name":"flask_main.py","file_ext":"py","file_size_in_byte":8813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"494910371","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom keras import Sequential\nfrom keras.layers import Dense, Activation\nfrom keras.initializers import Zeros, RandomNormal\nfrom keras.initializers import glorot_normal, glorot_uniform\n\n# Simulate the MNIST input and set the nr of neurons to 256 (for the vis. of the weight initialization)\nn_input = 784\nn_dense = 256\n\n# b=0 for the neurons of the hidden layers.\nb_init = Zeros()\n\n# Init the weights as standard normal distribution.\n#w_init = RandomNormal(stddev=1.0)\n#w_init = glorot_normal()\nw_init = glorot_uniform()\n\n# Design sample network to see the impact of the chosen weights. The activation function is added separately here.\nmodel = Sequential()\nmodel.add(Dense(n_dense,\n input_dim=n_input,\n kernel_initializer=w_init,\n bias_initializer=b_init))\nmodel.add(Activation('sigmoid'))\n\n# Random input for the net\nx = np.random.random((1, n_input))\n\na = model.predict(x)\n\nhis = plt.hist(np.transpose(a))\nplt.show()\n\n","sub_path":"03_Improving_Deep_Networks/weight_init.py","file_name":"weight_init.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"652667934","text":"from selenium import webdriver\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver.common.keys import Keys\n\ndriver = webdriver.Chrome(executable_path=r\"/Users/kapilnegi/Desktop/chromedriver\")\n\n# driver.get(\"http://demo.guru99.com/test/newtours/\")\n# \n# link_Home = driver.find_element_by_link_text(\"Home\")\n# \n# td_Home = driver.find_element_by_xpath(\"/html/body/div/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr\")\n# \n# actions = ActionChains(driver)\n# actions.move_to_element(link_Home).perform()\n# \n# # Combining actions\n# actions.move_to_element(link_Home)\n# actions.click(td_Home)\n# actions.perform()\n\ndriver.get(\"https://www.facebook.com\")\nactions = ActionChains(driver)\ntxtUsername = driver.find_element_by_id(\"email\")\n\n# actions.move_to_element(txtUsername).click(txtUsername).key_down(Keys.SHIFT, txtUsername).send_keys(\"hello\").key_up(Keys.SHIFT, txtUsername).double_click(txtUsername).context_click(txtUsername).perform()\n\nactions.move_to_element(txtUsername)\nactions.click(txtUsername)\nactions.key_down(Keys.SHIFT, txtUsername)\nactions.send_keys(\"hello\")\nactions.key_up(Keys.SHIFT, txtUsername)\nactions.double_click(txtUsername)\nactions.context_click(txtUsername)\nactions.perform()\n\ndriver.quit()\n","sub_path":"src/mouse_keyboard_event.py","file_name":"mouse_keyboard_event.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"351530178","text":"import asyncio\nfrom .config import config\nimport connexion\nfrom connexion.resolver import RestyResolver\nfrom connexion.decorators.response import ResponseValidator\nfrom connexion.decorators.validation import RequestBodyValidator\nfrom connexion.exceptions import NonConformingResponseBody, NonConformingResponseHeaders\nfrom .db import gino as db\nimport json\n# from jsonschema import ValidationError\n# from .logger import log\n# from sqlalchemy.exc import IntegrityError\n# from sqlalchemy.orm.exc import NoResultFound\nfrom . import util, responses\n\n\n# By default validate_response will return the full stack trace to the client.\n# This will instead return a simple 500\nclass CustomResponseValidator(ResponseValidator):\n def validate_response(self, data, status_code, headers, url):\n try:\n super().validate_response(data, status_code, headers, url)\n except(NonConformingResponseBody, NonConformingResponseHeaders):\n raise Exception()\n\n\n# This enables a custom error message for invalid request bodies to be sent to the client.\nclass RequestBodyValidator(RequestBodyValidator):\n def validate_schema(self, data, url):\n if self.is_null_value_valid and connexion.utils.is_null(data):\n return None\n self.validator.validate(data)\n\n\nvalidator_map = {\n 'response': CustomResponseValidator,\n 'body': RequestBodyValidator\n}\ndebug = util.string_to_bool(config.debug)\n\napp = connexion.AioHttpApp('__main__',\n specification_dir='swagger/',\n validator_map=validator_map,\n debug=debug)\napp.add_api('api.spec.yaml',\n resolver=RestyResolver('api'),\n validate_responses=True,\n strict_validation=True,\n pass_context_arg_name='request')\n\n\ndef exists_handler(exception):\n return responses.resource_exists()\n\n\ndef no_result_handler(exception):\n return responses.not_found()\n\n\ndef validation_error_handler(exception):\n return responses.invalid_request_parameters()\n\n\n# app.add_error_handler(NoResultFound, no_result_handler)\n# app.add_error_handler(IntegrityError, exists_handler)\n# app.add_error_handler(ValidationError, validation_error_handler)\n\napplication = app.app\n\n\n# @application.teardown_appcontext\n# def shutdown_session(exception=None):\n# session.remove()\n\n\ndef _parse_headers(dict_in):\n return json.dumps(\n {k: v for k, v in dict_in})\n\n\ndef _parse_params(params):\n return params.to_dict(flat=False)\n\n\n# @application.before_request\n# def before_req():\n # log.info(msg={'headers': _parse_headers(connexion.request.headers),\n # 'params': _parse_params(connexion.request.args),\n # 'body': connexion.request.json,\n # 'url': connexion.request.url,\n # 'method': connexion.request.method})\n\n\n# @application.after_request\n# def after_req(res):\n # log.info(msg={'status_code': res.status_code,\n # 'headers': _parse_headers(res.headers),\n # 'content_type': res.content_type,\n # 'mimetype': res.mimetype,\n # 'body': res.get_json()})\n # return res\n\n\n@asyncio.coroutine\nasync def setup_app(app):\n await db.init()\n app['db'] = db\n return app\n\n\ndef start():\n app_copy = app.app\n app.app = setup_app(app_copy)\n app.run(port=int(config.port))\n","sub_path":"insights_connexion/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"521231641","text":"class Node:\n def __init__(self, value=None):\n self.value = value\n self.left_child = None\n self.right_child = None\n\n\n def has_value(self, value):\n if self.data == value:\n return True\n else:\n return False\n\n\n","sub_path":"node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"352646166","text":"\nfrom misc import dp\n\nimport logging\n\nimport aiogram.utils.markdown as md\nfrom aiogram import Bot, Dispatcher, types\nfrom aiogram.contrib.fsm_storage.memory import MemoryStorage\nfrom aiogram.dispatcher import FSMContext\nfrom aiogram.dispatcher.filters import Text\nfrom aiogram.dispatcher.filters.state import State, StatesGroup\nfrom aiogram.types import ParseMode\nfrom aiogram.utils import executor\n\nuser_commands_list = ''\nadmin_commands_list = '/abc - abc'\n\n\n# States\nclass Form(StatesGroup):\n name = State() # Will be represented in storage as 'Form:name'\n age = State() # Will be represented in storage as 'Form:age'\n gender = State() # Will be represented in storage as 'Form:gender'\n\n\n@dp.message_handler(commands='abc')\nasync def cmd_start(message: types.Message):\n \"\"\"\n Conversation's entry point\n \"\"\"\n # Set state\n await Form.name.set()\n\n await message.reply(\"Hi there! What's your name?\")\n\n\n# You can use state '*' if you need to handle all states\n@dp.message_handler(state=[Form.name, Form.age, Form.gender], commands='cancel')\n@dp.message_handler(Text(equals='cancel', ignore_case=True), state=[Form.name, Form.age, Form.gender])\nasync def cancel_handler(message: types.Message, state: FSMContext):\n \"\"\"\n Allow user to cancel any action\n \"\"\"\n current_state = await state.get_state()\n if current_state is None:\n return\n\n logging.info('Cancelling state %r', current_state)\n # Cancel state and inform user about it\n await state.finish()\n # And remove keyboard (just in case)\n await message.reply('Cancelled.', reply_markup=types.ReplyKeyboardRemove())\n\n\n@dp.message_handler(state=Form.name)\nasync def process_name(message: types.Message, state: FSMContext):\n \"\"\"\n Process user name\n \"\"\"\n await state.update_data(name=str(message.text))\n\n await Form.next()\n await message.reply(\"How old are you?\")\n\n\n# Check age. Age gotta be digit\n@dp.message_handler(lambda message: not message.text.isdigit(), state=Form.age)\nasync def process_age_invalid(message: types.Message):\n \"\"\"\n If age is invalid\n \"\"\"\n return await message.reply(\"Age gotta be a number.\\nHow old are you? (digits only)\")\n\n\n@dp.message_handler(lambda message: message.text.isdigit(), state=Form.age)\nasync def process_age(message: types.Message, state: FSMContext):\n # Update state and data\n await Form.next()\n await state.update_data(age=int(message.text))\n\n # Configure ReplyKeyboardMarkup\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True, selective=True)\n markup.add(\"Male\", \"Female\")\n markup.add(\"Other\")\n\n await message.reply(\"What is your gender?\", reply_markup=markup)\n\n\n@dp.message_handler(lambda message: message.text not in [\"Male\", \"Female\", \"Other\"], state=Form.gender)\nasync def process_gender_invalid(message: types.Message):\n \"\"\"\n In this example gender has to be one of: Male, Female, Other.\n \"\"\"\n return await message.reply(\"Bad gender name. Choose your gender from the keyboard.\")\n\n\n@dp.message_handler(state=Form.gender)\nasync def process_gender(message: types.Message, state: FSMContext):\n await state.update_data(gender=str(message.text))\n\n # Remove keyboard\n markup = types.ReplyKeyboardRemove()\n user_data = await state.get_data()\n # And send message\n await message.answer(text=\"Hi! Nice to meet you\" + str(user_data['name']), reply_markup=markup)\n # Finish conversation\n await state.finish()\n\n\n","sub_path":"handlers/Handlers_not_ready/schedule_commands.py","file_name":"schedule_commands.py","file_ext":"py","file_size_in_byte":3451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"274006885","text":"from django.db import models\nfrom common.models import TimestampedModel\nfrom django.template.defaultfilters import slugify\n\nclass Movement(TimestampedModel):\n \"\"\"\n Composition Movement model definition.\n \"\"\"\n title = models.CharField(max_length=100)\n movement_slug = models.SlugField()\n\n def save(self, *args, **kwargs):\n \"\"\"\n Overidden save method to add slug.\n \"\"\"\n self.movement_slug = slugify(self.title)\n super(Movement, self).save(*args, **kwargs)\n\nclass Composition(TimestampedModel):\n \"\"\"\n Composition entity. Contains relationship to\n `Movement` entity.\n \"\"\"\n title = models.CharField(max_length=100)\n composer = models.CharField(max_length=50)\n movements = models.ManyToManyField(Movement)\n\n class Meta:\n ordering = ('-updated_at',)\n\n\n","sub_path":"composition/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"34278615","text":"from mininet.topo import Topo\r\nfrom mininet.net import Mininet\r\nfrom mininet.node import Controller, OVSSwitch\r\nfrom mininet.cli import CLI\r\nfrom mininet.log import setLogLevel, info\r\n\r\nclass MyTopo( Topo ):\r\n \"Simple topology example.\"\r\n\r\n def build( self ):\r\n \"Create custom topo.\"\r\n\r\n # Add hosts and switches\r\n host1 = self.addHost( 'h1', ip='192.168.2.10' )\r\n host2 = self.addHost( 'h2', ip='192.168.2.20' )\r\n host3 = self.addHost( 'h3', ip='192.168.2.30' )\r\n host4 = self.addHost( 'h4', ip='192.168.2.40' )\r\n switch1 = self.addSwitch( 's1' )\r\n\r\n # Add links\r\n self.addLink(switch1, host1 )\r\n self.addLink(switch1, host2 )\r\n self.addLink(switch1, host3 )\r\n self.addLink(switch1, host4 )\r\n\r\n\r\n\r\ntopos = { 'mytopo': ( lambda: MyTopo() ) }\r\n\r\n#commnad to run it with \r\n# sudo mn --custom testTopo.py --topo mytopo --controller=remote,port=6633 #--controller=remote,port=6655 --switch=ovsk --mac\r\n# once up, run these two commnads\r\n#py net.addLink('c1','s1')\r\n#py net.addLink('c0','s1') \r\n\r\n\r\n","sub_path":"labTopology.py","file_name":"labTopology.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"327933002","text":"\"\"\"\r\n\r\nThis program for maintaining Remote Server\r\nAuthor: H.M. Shah Paran Ali\r\nEmail: paran.duet@gmail.com\r\n\"\"\"\r\n\r\nfrom PyQt5 import QtWidgets, uic\r\nfrom PyQt5.QtWidgets import QMainWindow, QApplication , QPushButton, QToolTip, QMessageBox\r\nimport sys, os, re, paramiko\r\nfrom subprocess import Popen, PIPE\r\nfrom serverLayout import *\r\n\r\n\r\nclass CmdEnv(QMainWindow):\r\n\tdef __init__(self, parent=None):\r\n\t\tsuper().__init__()\r\n\t\r\n\t\tself.ui = uic.loadUi('F:/python/firstPython/pyQt/server/cmdEnvLayout.ui', self)\r\n\t\tself.ui.btnExe.clicked.connect(self.btnExecute)\r\n\t\tself.ui.btnHome.clicked.connect(self.forwardLayout)\r\n\t\tself.ui.btnExit.clicked.connect(self.systemExit)\r\n\t\tself.ui.homeMenu.triggered.connect(self.forwardLayout)\r\n\t\t# self.ui.hostIp.textChanged.connect(self.hostValidate)\r\n\t\t\r\n\tdef is_valid_ip(self, ip):\r\n\t\tm = re.match(r\"^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$\", ip)\r\n\t\treturn bool(m) and all(map(lambda n: 0 <= int(n) <= 255, m.groups()))\r\n\r\n\tdef sshConnect(self, target_host, un, pwd,cmd):\r\n\t\tssh = paramiko.SSHClient()\r\n\t\tssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\r\n\t\t# target_host = self.ui.hostIp.text()\r\n\t\ttarget_port = 22\r\n\t\t# pwd = self.ui.passwd.text()\r\n\t\t# un = self.ui.usr.text()\r\n\t\t# cmd = self.ui.cmdLine.text()\r\n\t\tif self.is_valid_ip(str(target_host)) :\r\n\t\t\tssh.connect( hostname = target_host , username = un, password = pwd )\r\n\t\t\tstdin, stdout, stderr = ssh.exec_command(str(cmd))\r\n\t\t\ttxt = \"%s\" %(stdout.read())\r\n\t\t\tself.ui.display.append(txt)\r\n\t\telse:\r\n\t\t\tQMessageBox.question(self, 'Wrong IP', \"You typed: \" + target_host, QMessageBox.Ok, QMessageBox.Ok)\r\n\t\t\r\n\t\t\r\n\tdef btnExecute(self):\r\n\t\tself.ui.display.setText(\"\")\r\n\t\ttarget_host = self.ui.hostIp.text()\r\n\t\t# target_port = 22\r\n\t\tpwd = self.ui.passwd.text()\r\n\t\tun = self.ui.usr.text()\r\n\t\tcmd = self.ui.cmdLine.text()\r\n\t\tif target_host == \"\" or un == \"\" or pwd == \"\" or cmd == \"\":\r\n\t\t\tQMessageBox.question(self, \"Execution Info !!!\", \"You have missed any of field\", QMessageBox.Ok)\r\n\t\telse:\r\n\t\t\tself.sshConnect(target_host, un, pwd,cmd)\r\n\r\n\tdef forwardLayout(self):\r\n\t\tself.layout = MainWindow()\r\n\t\tself.ui.setVisible(False)\r\n\t\tself.layout.show()\r\n\t\r\n\tdef systemExit(self):\r\n\t\tsys.exit(1)\r\nif __name__==\"__main__\":\r\n\tapp = QApplication(sys.argv)\r\n\tmw = CmdEnv()\r\n\tmw.show()\r\n\tsys.exit(app.exec_())\r\n","sub_path":"cmdEnvLayout.py","file_name":"cmdEnvLayout.py","file_ext":"py","file_size_in_byte":2304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"268792202","text":"import struct\nfrom Exceptions import *\nHEADER = 8\nbuffer = dict()\n\nclass udp(object):\n def __init__(self, src_port, dst_port, payload):\n self.src_port = src_port\n self.dst_port = dst_port\n self.payload = payload\n\n def pack(self):\n return pack(self.src_port, self.dst_port, self.payload)\n\n def __str__(self):\n return 'src: %(src_port)s\\n' \\\n 'dst: %(dst_port)s\\n' \\\n 'payload: %(payload)s}\\n' % self.__dict__\n\n\ndef pack(src_port, dst_port, payload):\n length = len(payload) + HEADER\n uncheck_segment = struct.pack('!HHHH%ds' % len(payload), src_port, dst_port, length, 0, payload)\n checksum_ = checksum(uncheck_segment)\n segment = struct.pack('!HHHH%ds' % len(payload), src_port, dst_port, length, checksum_, payload)\n return segment\n\ndef unpack(segment):\n src_port, dst_port, length, checksum_ = struct.unpack('!HHHH', segment[:HEADER])\n payload = segment[HEADER:]\n checksum_ = checksum(segment)\n if checksum_ != 0:\n raise ChecksumErrorException\n return udp(src_port, dst_port, payload)\n\ndef checksum (data):\n data = data if len(data)%2 ==0 else data+b'\\x00'\n data_array = struct.unpack('!%dH'%(len(data)/2), data)\n s = 0\n for d in data_array:\n s += d\n s = (s & 0xFFFF) + (s >> 16)\n s += (s >> 16)\n return ~s & 0xFFFF\n\n\n\n# u = UDP()\n# header = struct.pack('>H', 65502)+struct.pack('>H', 4040)+struct.pack('>H', 72)+b'\\x2f\\x7f'\n# print(u.decode(b'\\xff\\xde\\x0f\\xc8\\x00\\x48\\x2f\\x7f'))","sub_path":"UDP.py","file_name":"UDP.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"360402865","text":"\"\"\"\r\n\tPackage lang.C\r\n\r\n\tThis package contains C-language specific helper functions\r\n\tfor the code generator.\r\n\"\"\"\r\n\r\nimport os\r\nimport os.path\r\nimport GenBasic\r\nimport Gen\r\nimport Gen.lang\r\nimport Gen.lang.Ctypes as Ctypes\r\nimport MetaModel.DataTypes\r\nfrom GenBasic import GeneratorError\r\n\r\n\r\nSTATEMACHINE_METHOD_NAME = 'process_StateMachine'\r\nMSG_CLASS_NAME = 'Message'\r\nMASK_CLASS_NAME = 'Mask'\r\n\r\n\r\n\r\ndef getSource(clazz):\r\n\t\"\"\" Get the textbuffer for the source file of this class. \"\"\"\r\n\tfn = getSourceFilename(clazz,True)\r\n\treturn Gen.allFiles.get_buffer(fn)\r\n\r\ndef getSourceFilename(clazz,blIncludePath=False):\r\n\t\"\"\" Get the textbuffer for the source file of this class. \"\"\"\r\n\ttry:\r\n\t\tfn = clazz.___Cfilename\r\n\texcept AttributeError:\r\n\t\tfn = classCname(clazz)+'.cpp'\r\n\t\tfn = os.path.join( elementDirName(clazz) , fn )\r\n\t\tclazz.___Cfilename = fn\r\n\tif not blIncludePath:\r\n\t\tfn = fn[1+fn.rfind(os.path.sep):]\r\n\treturn fn\r\n\r\ndef getStateMachineSource(clazz):\r\n\t\"\"\" Get the textbuffer for the statemachine source file of this class. \"\"\"\r\n\tfn = classCname(clazz)+'_SM.c'\r\n\treturn _getFile(clazz,fn)\r\n\r\ndef getHeader(clazz):\r\n\t\"\"\" Get the textbuffer for the header file of this class. \"\"\"\r\n\tfn = getHeaderFilename(clazz,True)\r\n\treturn Gen.allFiles.get_buffer(fn)\r\n\r\n\r\n\r\ndef getHeaderFilename(clazz,blIncludePath=False):\r\n\t\"\"\"\r\n\t\tGet the name of the header file of a class.\r\n\t\tUsed for creating the file or for building #include lines.\r\n\t\"\"\"\r\n\ttry:\r\n\t\tfn = clazz.___Hfilename\r\n\texcept AttributeError:\r\n\t\tfn = classCname(clazz)+'.h'\r\n\t\tfn = os.path.join( elementDirName(clazz) , fn )\r\n\t\tclazz.___Hfilename = fn\r\n\tif not blIncludePath:\r\n\t\tfn = fn[1+fn.rfind(os.path.sep):]\r\n\treturn fn\r\n\r\n\r\ndef elementDirName(element):\r\n\t\"\"\" determine directory name according to the namespace path of the element \"\"\"\r\n\tdirname = element.packagePath(os.path.sep)\r\n\tdirname=dirname.replace(' ','_')\r\n\tdirname=dirname.replace('-','')\r\n\tif dirname==\"\":\r\n\t\tdirname=\".\"\r\n\treturn dirname\r\n\r\n\r\ndef hasVirtualMethods(clazz):\r\n\tattrName=\"___hasVtab\"\t\t# Store result in the 'attribute' for fast reference later.\r\n\tif attrName in clazz.__dict__:\r\n\t\treturn clazz.__dict__[attrName]\r\n\t#check\r\n\tresult=False\r\n\tfor op in clazz.loop_operations(True):\t# loop all ops including superclasses\r\n\t\tif isMethodVirtual(op):\r\n\t\t\tresult=True\r\n\t\t\tbreak\r\n\tclazz.__dict__[attrName] = result\r\n\treturn result\r\n\r\n\r\ndef classCname(clazz):\r\n\t\"\"\" Determine struct/filename for class. Does not add ending '.c' or '.h' \"\"\"\r\n\tclsname = clazz.name\r\n\tclsname=clsname.replace(' ','_')\r\n\tclsname=clsname.replace('-','')\r\n\treturn clsname\r\n\r\n\r\ndef isMethodVirtual(method):\r\n\t\"\"\" Determine if a method is virtual\r\n\t\tChecks if there is a subclass or superclass which\r\n\t\thas a method with same name and set of parameters.\r\n\t\"\"\"\r\n\tif method.name==method.owner[0].name:\r\n\t\treturn False\t\t# constructor\r\n\tif method.name=='~'+method.owner[0].name:\r\n\t\treturn True\t\t# destructor\r\n\treturn Gen.lang.hasSuperClassSameMethod(method) or Gen.lang.hasSubClassSameMethod(method)\r\n\r\n\r\ndef OperationParamList(oper):\r\n\t\"\"\"\r\n\t\tReturn the parameter list of an operation as\r\n\t\ta string such as 'int a,String *s'. No brackets.\r\n\t\"\"\"\r\n\tpList=[]\r\n\tfor para in oper.parameter:\r\n\t\tif para.kind=='return':\r\n\t\t\tcontinue\r\n\t\t(typRepr,arrSz) = Gen.lang.C.typeCrepr(para.type[0])\r\n\t\tarr = ''\r\n\t\tif arrSz>0: arr='[]'\r\n\t\tpList.append( typRepr + ' ' + para.name + arr)\r\n\treturn ','.join(pList)\r\n\r\n\r\ndef OperationParamListSimple(oper):\r\n\t\"\"\" Create the parameter list of an operation as a string such as 'int a,String *s'. No brackets. \"\"\"\r\n\tpList=[]\r\n\tfor para in oper.parameter:\r\n\t\tif para.kind=='return':\r\n\t\t\tcontinue\r\n\t\tpList.append( para.name )\r\n\treturn ','.join(pList)\r\n\r\n\r\ndef typeCrepr( typ , UMLmodel=None ):\r\n\t\"\"\"\r\n\t\tGet the C language representation of a type.\r\n\t\tUse on the classifier referred by attributes\r\n\t\tand parameters using the 'type' relationship.\r\n\r\n\t\tCan process 'DataType' instances, 'CType' instances\r\n\t\tand string names.\r\n\t\"\"\"\r\n\tarraySize=0\r\n\tif typ is None:\r\n\t\ttyp = Ctypes.CTypeVoid()\r\n\tif isinstance(typ,Gen.UMM.DataType):\r\n\t\ttyp = typ.name\r\n\tif isinstance(typ,Gen.UMM.Classifier):\r\n\t\ttyp = Ctypes.CTypePointer(typ)\r\n\tif isinstance(typ,basestring):\r\n\t\t(ctyp,arraySize) = Ctypes.make_Ctype( typ , UMLmodel )\r\n\t\tif ctyp is None:\r\n\t\t\traise GeneratorError( \"cannot recognize datatype '%s'\" %typ )\r\n\t\ttyp = ctyp\r\n\tif not isinstance( typ , Ctypes.CType ):\r\n\t\traise GeneratorError( \"cannot make C representation for %s\" % repr(typ) , typ )\r\n\treturn (typ.Crepr(),arraySize)\r\n\r\n\r\n\r\ndef basicChecks():\r\n\t\"\"\" Do some checking on the model as a whole \"\"\"\r\n\tfor clazz in Gen.model.instances(Gen.UMM.Classifier):\r\n\r\n\t\t# Rule: No multiple inheritance\r\n\t\tif len(clazz.generalization)>1:\r\n\t\t\traise GeneratorError( \"No multiple inheritance supported by generator. Check %s %s\"%(clazz.__class__.__name__,clazz.name) , clazz )\r\n\r\n\t\t# Rule: The C-tor method (if declared in the model) must have instance scope.\r\n\t\tfor oper in clazz.loop_operations():\r\n\t\t\tif oper.name.lower()==clazz.name:\r\n\t\t\t\tif oper.ownerScope!='instance':\r\n\t\t\t\t\traise GeneratorError( \"The constructor method '%s' must have instance scope. Check %s %s\"%(oper.name,clazz.__class__.__name__,clazz.name) , clazz )\r\n\t\t\tif oper.name.lower()==(\"~\"+clazz.name):\r\n\t\t\t\tif oper.ownerScope!='instance':\r\n\t\t\t\t\traise GeneratorError( \"The destructor method '%s' must have instance scope. Check %s %s\"%(oper.name,clazz.__class__.__name__,clazz.name) , clazz )\r\n\t\t\t\tif oper.numParams()>0:\r\n\t\t\t\t\traise GeneratorError( \"The destructor method '%s' may not have parameters. Check %s %s\"%(oper.name,clazz.__class__.__name__,clazz.name) , clazz )\r\n\r\n\r\n\r\ndef _getFile(clazz,filename):\r\n\t\"\"\"\r\n\t\tInternal implementation of getSource and getHeader in one function.\r\n\t\"\"\"\r\n\tdirname = elementDirName(clazz)\r\n\t#create/get textbuffer\r\n\ttextbuffer = Gen.allFiles.get_buffer(os.path.join(dirname,filename))\r\n\r\n\treturn textbuffer\r\n\r\n\r\n","sub_path":"MSDEV8/PROGS/Dyna/PyCodeGen/Gen/lang/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":5876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"280073946","text":"alllist = []\ns_list = [] # 一文を構成する形態素のマップを要素にもつリスト\n\nfrom collections import defaultdict\nwordscounter = defaultdict(lambda:0)\n\nwith open('neko.txt.mecab') as f:\n for line in f:\n if line == 'EOS\\n':\n if len(s_list) > 0:\n alllist.append(s_list.copy())\n s_list.clear()\n continue\n d = {k: v for k, v in [f.split(\":\") for f in line.rstrip(\"\\n\").split(\",\")]} # 一文を構成する各形態素のマップ\n s_list.append(d)\n wordscounter[d['base']] += 1\n\nfor k,v in sorted(dict(wordscounter).items(), key=lambda x:x[1], reverse=True):\n # print(k, v/sum(wordscounter.values()))\n print(k, v)\n\n# print(sum(wordscounter.values()))\n# print(len(wordscounter))","sub_path":"take/chapter04/knock36.py","file_name":"knock36.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"424126801","text":"from run_async import run_async\nimport requests\nimport uuid\n\n\n@run_async\ndef send_mail_async(tos=[], subject=None, message=None):\n\n URL = \"https://api.mailgun.net/v2/fa.signalclients.com/messages\"\n API_KEY = \"key-0hkmak1-40f89hy4tppkmt-8g06pajd5\"\n FROM = \"Signalbase \"\n\n auth = (\"api\", API_KEY)\n data = {\n \"from\": FROM,\n \"to\": tos,\n \"subject\": subject,\n \"html\": message\n }\n resp = requests.post(URL, auth=auth, data=data)\n return True\n\n\ndef make_unique():\n return str(uuid.uuid4())\n","sub_path":"trunk/signalbase-com/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"92818471","text":"# File: consoletest.py\n\n\"\"\"\nThis module implements an interactive test harness in which the\nuser enters a sequence of commands on the console.\n\"\"\"\n\n# Code to ensure that imported modules can come from the current directory\n\nimport os\nimport sys\nsys.path.insert(0, os.getcwd())\n\nfrom tokenscanner import TokenScanner\nimport types\n\n# The ConsoleTest class is a base class for writing convenient interactive\n# tests that read and execute commands from the console. To define a new\n# command xxx, all that the subclass needs to do is define a method that\n# fits the following pattern:\n#\n# def xxxCommand(self, scanner):\n# \"\"\"Help text for the command\"\"\"\n# Code to implement the command\n\nclass ConsoleTest:\n\n def run(self):\n \"\"\"Runs the interactive test program.\"\"\"\n while True:\n line = input(self.getPrompt())\n try:\n self.execute(line)\n except Exception as ex:\n print(\"Error: \" + str(ex))\n\n def execute(self, line):\n scanner = self.createScanner()\n scanner.setInput(line)\n token = scanner.nextToken()\n if token != \"\":\n cmd = self.lookup(token)\n if cmd is None:\n scanner.saveToken(token)\n self.undefinedCommandHook(scanner)\n else:\n cmd(scanner)\n\n def lookup(self, cmd):\n fn = getattr(self, cmd + \"Command\", None)\n if type(fn) != types.MethodType:\n return None\n return fn\n\n# Builtin commands\n\n def quitCommand(self, scanner):\n \"\"\"quit -- Quits the program\"\"\"\n sys.exit()\n\n def helpCommand(self, scanner):\n \"\"\"help -- Prints this help text\"\"\"\n commands = [ ]\n for cmd in dir(self):\n if cmd.endswith(\"Command\"):\n fn = getattr(self, cmd, None)\n if type(fn) == types.MethodType:\n commands.append(fn)\n maxDoc = 0\n for fn in commands:\n docstr = fn.__doc__\n if docstr is not None:\n dash = docstr.find(\" -- \")\n if dash != -1:\n maxDoc = max(maxDoc, dash)\n for fn in commands:\n docstr = fn.__doc__\n if docstr is None:\n print(fn.__name__[:-len(\"Command\")])\n else:\n dash = docstr.find(\" -- \")\n if dash == -1:\n print(docstr)\n else:\n head = docstr[:dash]\n tail = docstr[dash:]\n print(head.ljust(maxDoc) + tail)\n\n def scriptCommand(self, scanner):\n \"\"\"script \"file\" -- Reads a script from the file\"\"\"\n filename = self.scanFilename(scanner)\n if \".\" not in filename:\n filename += \".txt\"\n with open(filename) as f:\n for line in f.read().splitlines():\n print(self.getScriptPrompt() + line)\n self.execute(line)\n\n def scanFilename(self, scanner):\n filename = \"\"\n while (scanner.hasMoreTokens()):\n filename += scanner.nextToken()\n return filename\n\n def nextInt(self, scanner):\n sign = 1\n token = scanner.nextToken()\n if token == \"-\":\n sign = -1\n token = scanner.nextToken()\n return sign * int(token)\n\n def nextFloat(self, scanner):\n sign = 1\n token = scanner.nextToken()\n if token == \"-\":\n sign = -1\n token = scanner.nextToken()\n return sign * float(token)\n\n# Methods available for clients to override\n\n def createScanner(self):\n \"\"\"Creates the scanner used in this test program.\"\"\"\n scanner = TokenScanner()\n scanner.ignoreWhitespace()\n scanner.scanNumbers()\n scanner.scanStrings()\n return scanner\n\n def getPrompt(self):\n return \"-> \"\n\n def getScriptPrompt(self):\n return \"+> \"\n\n def undefinedCommandHook(self, scanner):\n print(\"Undefined command: \" + scanner.nextToken())\n","sub_path":"Dijkstra/consoletest.py","file_name":"consoletest.py","file_ext":"py","file_size_in_byte":4052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"263704619","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\nimport smtplib\r\nURL = 'https://www.amazon.in/255-Bluetooth-Wireless-Earphone-Immersive/dp/B07C2VJFDW/ref=sr_1_6?pf_rd_i=1388921031&pf_rd_m=A1K21FY43GMZF8&pf_rd_p=e1b534f1-3276-56a6-91b1-814616b41341&pf_rd_r=FY0ANF7FV6ANTHA9MVZR&pf_rd_s=merchandised-search-11&pf_rd_t=101&qid=1562742381&refinements=p_n_feature_browse-bin%3A6631672031%7C6631673031&rw_html_to_wsrp=1&s=electronics&sr=1-6'\r\nheaders = {\"User-Agent\": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'}\r\n\r\ndef check_price():\r\n page = requests.get(URL, headers = headers)\r\n\r\n soup = BeautifulSoup(page.content, 'html.parser')\r\n\r\n title = soup.find(id=\"productTitle\").get_text()\r\n price = soup.find(id=\"priceblock_ourprice\").get_text()\r\n converted_price = int(price[2:7].replace(',',''))\r\n if (converted_price<1499):\r\n send_mail()\r\n print(converted_price)\r\n print(title.strip())\r\n\r\n if(converted_price>1399):\r\n send_mail()\r\n\r\ndef send_mail():\r\n server = smtplib.SMTP('smtp.gmail.com', 587)\r\n server.ehlo()\r\n server.starttls()\r\n server.ehlo()\r\n \r\n server.login('abhiakashona@gmail.com', 'derdacvzufwkbpsu')\r\n \r\n subject = 'Price Fell Down!'\r\n body = 'Check the Amazon link https://www.amazon.in/255-Bluetooth-Wireless-Earphone-Immersive/dp/B07C2VJFDW/ref=sr_1_6?pf_rd_i=1388921031&pf_rd_m=A1K21FY43GMZF8&pf_rd_p=e1b534f1-3276-56a6-91b1-814616b41341&pf_rd_r=FY0ANF7FV6ANTHA9MVZR&pf_rd_s=merchandised-search-11&pf_rd_t=101&qid=1562742381&refinements=p_n_feature_browse-bin%3A6631672031%7C6631673031&rw_html_to_wsrp=1&s=electronics&sr=1-6'\r\n\r\n msg = f\"Subject: {subject} \\n{body}\"\r\n\r\n server.sendmail(\r\n 'abhiakashona@gmai.com',\r\n 'abhiakashona@gmail.com',\r\n msg)\r\n print(\"Hey email has been sent!!\")\r\n\r\n server.quit()\r\n \r\n\r\ncheck_price()\r\n\r\n\r\n\r\n","sub_path":"Scrapper.py","file_name":"Scrapper.py","file_ext":"py","file_size_in_byte":1926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"55499583","text":"from django.conf.urls import patterns, url\n\nfrom crud import views\n\nurlpatterns = patterns('',\n\t# ex: /crud/\n\turl(r'^$', views.index, name='index'),\n\n\t# ex: /crud/5/detail/\n\turl(r'^(?P\\d+)/$', views.detail, name='detail'),\n\n\t# ex: /crud/add/\n\turl(r'^add/$', views.add, name='add'),\n)","sub_path":"crud/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"222183770","text":"from django.shortcuts import render, redirect\nfrom django.http import JsonResponse, HttpResponse\nfrom django.views import View\nfrom django.contrib.auth.mixins import LoginRequiredMixin, AccessMixin\nfrom django.urls import reverse\nfrom django.contrib import messages\nfrom django.utils.translation import ugettext as _\nfrom django.utils.text import slugify\nfrom django.contrib.auth import get_user_model\n\nfrom config.views import get_provider, API_URL\nimport datetime\nimport json\n\nfrom bootcamp.reservations.models import PaymentMethod, Reservation\nfrom bootcamp.users.models import User\nfrom .forms import ReservationForm\n\n\nclass PatientOnly(AccessMixin):\n def dispatch(self, request, *args, **kwargs):\n if request.user.is_authenticated and request.user.profile.type == 'P':\n return super(PatientOnly, self).dispatch(request, *args, **kwargs)\n return self.handle_no_permission()\n\n\nclass CreateReservation(PatientOnly, View):\n\n success_message = _('Session reservation success')\n\n def post(self, request):\n start_time = datetime.datetime.strptime(f'{request.POST.get(\"date\")}T{request.POST.get(\"from\")}', '%d-%m-%YT%I:%M %p')\n end_time = datetime.datetime.strptime(f'{request.POST.get(\"date\")}T{request.POST.get(\"to\")}', '%d-%m-%YT%I:%M %p')\n form_data = {\n 'patient' : request.user.pk,\n 'service_id' : request.POST.get('service_id'),\n 'service_name' : request.POST.get('service_name'),\n 'service_duration' : request.POST.get('service_duration'),\n 'start_time' : start_time,\n 'end_time' : end_time,\n 'method' : request.POST.get('payment_method'),\n 'price' : int(request.POST.get('price')),\n }\n try:\n self.provider = User.objects.get(username = slugify(request.POST.get('provider_name')))\n form_data['doctor'] = self.provider.pk\n except User.DoesNotExist:\n print('---- exception create reservation doctor')\n pass\n form = ReservationForm(form_data)\n if form.is_valid():\n return self.form_valid(form)\n return self.form_invalid(form)\n\n def form_invalid(self, form):\n print('---- reservation form invalid ', form.errors.as_data())\n errors = json.loads(form.errors.as_json())\n if errors.get('__all__') and errors.get('__all__')[0]['message']:\n messages.warning(self.request, errors.get('__all__')[0]['message'])\n # return redirect('provider-details', username = self.provider.username, status = 400)\n return HttpResponse(content = form.errors.as_json(), status = 400)\n\n def form_valid(self, form):\n form.save()\n messages.success(self.request, self.success_message)\n return JsonResponse({'success' : True, 'url' : reverse('users:detail', kwargs = {'username' : self.request.user.username})})\n\n\nclass SelectSessionReservation(PatientOnly, View):\n\n def check_reservation(self, start_time, end_time, reservations):\n for res in reservations:\n if start_time <= res.start_time < end_time or start_time <= res.end_time < end_time:\n return False\n return True\n\n def check_reservation_time(self, start_time, end_time, provider):\n valid_time = True\n patient = self.request.user\n patient_reservations = Reservation.objects.next_reservations(patient)\n valid_time = self.check_reservation(start_time, end_time, patient_reservations)\n provider_reservarions = Reservation.objects.next_reservations(provider)\n valid_time = self.check_reservation(start_time, end_time, provider_reservarions)\n return valid_time\n\n def get(self, request):\n start_time = datetime.datetime.strptime(f'{request.GET.get(\"date\")}T{request.GET.get(\"from\")}', '%d-%m-%YT%I:%M %p')\n end_time = datetime.datetime.strptime(f'{request.GET.get(\"date\")}T{request.GET.get(\"to\")}', '%d-%m-%YT%I:%M %p')\n data = get_provider(request, request.GET.get('provider_id'))\n provider_name = data.get('name')\n try:\n provider = get_user_model().objects.get(name = provider_name)\n except get_user_model().DoesNotExist:\n provider = None\n\n if False: # self.check_reservation_time(start_time, end_time, provider):\n messages.warning(request, 'Can\\'t book session at this time, alreay booked.')\n return redirect('provider-details', username = provider.username)\n\n if not data.get('provider_price_list'):\n return redirect('home')\n service = None\n service_id = request.GET.get('service_id')\n for service_item in data['provider_price_list']['items']:\n if service_item['uuid'] == service_id:\n service = service_item\n cxt = {\n 'date' : request.GET.get('date'),\n 'from' : request.GET.get('from'),\n 'to' : request.GET.get('to'),\n 'data' : data,\n 'api_url' : API_URL,\n 'service' : service,\n 'payment_methods' : PaymentMethod.objects.all(),\n 'provider' : provider,\n }\n return render(request, 'pages/session_reservation.html', cxt)\n","sub_path":"bootcamp/reservations/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"39561989","text":"from __future__ import print_function\n###from pkg_resources import resource_string\nfrom jenkinsapi.jenkins import Jenkins\nfrom jenkinsapi.job import Job\nfrom jenkinsapi.views import Views ##for nested view\nimport logging\nimport xml.etree.ElementTree as ET\n#import ConfigParser \nimport string,os,sys\nimport fileinput \n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger()\n\n\n\n###############get information from jenkins_project.conf#############\ndef getDicFromConf(path):\n\tconf_arr = []\n\tbundle_arr = []\n\tconf_dic = {}###the dic for storing the key-value of the conf array \n\tkv_arr = []\n\tfor line in fileinput.input(\"jenkins_project.conf\"):\n\t\tline=line.strip()\n\t\tindex = line.find('#')\n\t\tif line == '' or index == 0:\n\t\t\tcontinue;\n\t\telif index == -1:\n\t\t\t#print('index:',index)\n\t\t\tconf_arr.append(line)\n\t\telse:\n\t\t\tline = line[0:index]; line= line.strip(); conf_arr.append(line);\n\t\t\t#print(line);\n\t\t\t\n\t#print(conf_arr);\n\t\n\tbegin = 0;\n\tend = len(conf_arr)-1;\n\tnew_len = len(conf_arr);\n\t#print('len:',len(conf_arr))\n\tisbundle = 0 ##Record if there is the bundle \n\tisplugin = 0\n\tfor i in range(0,len(conf_arr)):\n\t\tif conf_arr[i]==\"[customize_bundle]\":\n\t\t\tbegin=i\n\t\t\tisbundle=1\n\t\t\tnew_len = begin+1\n\tfor i in range(0,len(conf_arr)):\n\t\tif ('customize_plugin' in conf_arr[i] and isbundle):\n\t\t\tisplugin=1\n\t\t\tend=i-1;\n\t\t\tnew_len=new_len+1\n\n\t#print('begin:',begin,'end:',end,'new_len:',new_len,'isbundle:',isbundle)\n\n\tif isbundle:\n\t\tfor j in range(begin+1,end+1):\n\t\t\tbundle_arr.append(conf_arr[j])\n\t\tfor k in range(0,new_len):\n\t\t\tif k == begin:\n\t\t\t\tconf_dic[conf_arr[begin]]= bundle_arr\n\t\t\telif k > begin:\n\t\t\t\tstr=conf_arr[end+1]\n\t\t\t\tkv_arr = str.split('=')\n\t\t\t\tstr1=kv_arr[0]\n\t\t\t\tstr2=kv_arr[1]\n\t\t\t\tstr1=str1.strip()\n\t\t\t\tstr2=str2.strip()\n\t\t\t\tconf_dic[str1]=str2\n\t\t\telse:\n\t\t\t\tstr = conf_arr[k]\n\t\t\t\tkv_arr = str.split('=')\n\t\t\t\tstr1=kv_arr[0]\n\t\t\t\tstr2=kv_arr[1]\n\t\t\t\tstr1=str1.strip()\n\t\t\t\tstr2=str2.strip()\n\t\t\t\tconf_dic[str1]=str2\n\telse: \n\t\tfor k in range(0,new_len):\n\t\t\tstr = bundle_arr[k]\n\t\t\tkv_arr = str.split('=')\n\t\t\tstr1=kv_arr[0]\n\t\t\tstr2=kv_arr[1]\n\t\t\tstr1=str1.strip()\n\t\t\tstr2=str2.strip()\n\t\t\tconf_dic[str1]=str2\n\tprint('conf_dic:',conf_dic,'\\n','conf_dic_len:',len(conf_dic),'\\n')\n\treturn conf_dic\n\ndef create_job_by_conf(conf_file,config_xml_name):\n\tconf_dic = getDicFromConf(conf_file)#\"jenkins_project.conf\"\n\n\t######connect jenkins and initial#########\n\t'''\n\tif 'jenkins_master' in conf_dic.keys():\n\t\tjenkins_url = 'http://'+conf_dic['jenkins_master']+':8080'\n\t\tjenkins = Jenkins(jenkins_url,username=\"admin\",password=\"cluster\")\n\telse:\n\t\tprint('Please set jenkins_master in jenkins_project.conf.')\n\t'''\n\n\tif 'project_name' in conf_dic.keys():\n\t\tjob_name = conf_dic['project_name']\n\telse:\n\t\tprint('Please set project_name in jenkins_project.conf.\\n')\n\n\tif 'group_name' in conf_dic.keys():\n\t\ttest_view_name = conf_dic['group_name']\n\telse:\n\t\tprint('Please set group_name in jenkins_project.conf.\\n')\n\t\n\tif 'test_cluster' in conf_dic.keys():\n\t\tassignedNode = conf_dic['test_cluster']\n\telse:\n\t\tprint('Please set test_cluster in jenkins_project.conf.\\n')\n\n\tif 'build_schedule' in conf_dic.keys():\n\t\tstr = conf_dic['build_schedule']\n\t\ttimerTrigger_text = 'H '+ str + ' * * *'\n\telse:\n\t\tprint('Please set build_schedule in jenkins_project.conf.\\n')\n\n\tif 'os' in conf_dic.keys():\n\t\tXCAT_TEST_OS = conf_dic['os']\n\telse:\n\t\t#raise Exception(\"Please set os in jenkins_project.conf.\\n!\")\n\t\tprint('Please set os in jenkins_project.conf.\\n')\n\n\t'''\n\tif 'arch' in conf_dic.keys():\n\t\tarch = conf_dic['arch']\n\telse:\n\t\tprint('Please set arch in jenkins_project.conf.')\n\t'''\n\tXCAT_TEST_BRANCH_OR_CORE = ''\n\tif ('branch' in conf_dic.keys() and 'customize_xcat_core' in conf_dic.keys()):\n\t\t#raise Exception(\"Branch and XCAT_TEST_CORE are conflicting.Please reset the configuration file.\\n\")\n\t\tprint('Branch and XCAT_TEST_CORE are conflicting.Please reset the configuration file.\\n')\t\n\telif 'branch' in conf_dic.keys():\n\t\tbranch_str = conf_dic['branch']\n\t\tXCAT_TEST_BRANCH_OR_CORE = '#---------To spcify target xcat build---------\\n\\n#If need to test your own build.\\n#comment \"XCAT_TEST_BRANCH\" line out,move \"#\" out of below \"XCAT_TEST_CORE\" line and set corect value\\n#if need to test the latest daily build in build server,\\n#comment \"XCAT_TEST_CORE\" line out,move \"#\" out of below \"XCAT_TEST_BRANCH\" line and set corect value\\n#for example : master or 2.13\\n\\nexport XCAT_TEST_BRANCH=%s\\n\\n' % (branch_str)\n\telif 'customize_xcat_core' in conf_dic.keys():\n\t\tcore_str = conf_dic['customize_xcat_core']\n\t\tXCAT_TEST_BRANCH_OR_CORE = '#---------To spcify target xcat build---------\\n\\n#If need to test your own build.\\n#comment \"XCAT_TEST_BRANCH\" line out,move \"#\" out of below \"XCAT_TEST_CORE\" line and set corect value\\n#if need to test the latest daily build in build server,\\n#comment \"XCAT_TEST_CORE\" line out,move \"#\" out of below \"XCAT_TEST_BRANCH\" line and set corect value\\n#for example : master or 2.13\\n\\nexport XCAT_TEST_CORE=%s\\n\\n\\n' % (core_str)\n\telse:\n\t\tprint('Please set customize_xcat_core or branch in jenkins_project.conf.\\n')\n\n\tif 'customize_xcat_dep' in conf_dic.keys():\n\t\tdep_str = conf_dic['customize_xcat_dep']\n\t\tXCAT_TEST_DEP = '#---------To spcify target xcat dependency package---------\\n\\n#If not set, will use the latest dependency package in xcat.org\\nexport XCAT_TEST_DEP=%s\\n\\n' % (dep_str)\n\telse:\n\t\tXCAT_TEST_DEP = ''\n\t\tprint('Here didn\\'t set customize_xcat_dep in jenkins_project.conf.\\n')\n\n\tdevelopment = '#For automation development environment, using below 2 line [RECOMMEND]\\nexport XCAT_TEST_GIT_REPO=git@github.ibm.com:gongjie/jenkins.git\\nexport XCAT_TEST_GIT_BRANCH=devel\\n\\n';\n\tproduct = '#For automation product environment, using below 2 line [NOT RECOMMEND]\\nexport XCAT_TEST_GIT_REPO=git@github.ibm.com:xcat2/jenkins.git\\nexport XCAT_TEST_GIT_BRANCH=master\\n\\n\\n';#####Now firstly code commenting in production \n\tif 'automation_env' in conf_dic.keys():\n\t\tenv = conf_dic['automation_env']\n\t\tif env == 'development':\n\t\t\tAUTOMATION_ENV = development\n\t\t\tjenkins_url = 'http://127.0.0.1:8080' #'http://10.2.4.25:8080'\n\t\t\tjenkins = Jenkins(jenkins_url,username=\"dengshuai_super\",password=\"8080\") #Jenkins(jenkins_url,username=\"admin\",password=\"cluster\")\n\t\telif env == 'production':\n\t\t\tAUTOMATION_ENV = product\n\t\t\tjenkins_url = 'http://10.4.32.1:8080'\n\t\t\tjenkins = Jenkins(jenkins_url,username=\"admin\",password=\"cluster\")\n\telse:\n\t\tprint('Please set automation_env in jenkins_project.conf.\\n')\n\n\tif 'mailing_list' in conf_dic.keys():\n\t\tmailing_str = conf_dic['mailing_list']\n\t\tXCAT_TEST_MAILING_LIST = '#---------To specify mailing list ---------\\n#using comma to separate different people\\nexport XCAT_TEST_MAILING_LIST=%s\\n\\n' % (mailing_str)\n\telse:\n\t\tXCAT_TEST_MAILING_LIST = ''\n\t\tprint('Here didn\\'t set mailing_list in jenkins_project.conf.')\n\n\tif 'database' in conf_dic.keys():\n\t\tdatabase_str = conf_dic['database']\n\t\tXCAT_TEST_DATABASE = '#---------To specify the database type----------\\n\\n#Using Mysql by default\\nexport XCAT_TEST_DATABASE=%s\\n\\n' % (database_str)\n\telse:\n\t\tXCAT_TEST_DATABASE = ''\n\t\tprint('Here didn\\'t set database in jenkins_project.conf.')\n\n\n\n\tbundles_str = ''\n\tif '[customize_bundle]' in conf_dic.keys():\n\t\tbundle_arr = conf_dic['[customize_bundle]']\n\t\tfor bundle in bundle_arr:\n\t\t\tbundles_str = bundles_str + bundle + '\\n';\n\t\t\n\t\tBUNDLE_STR = '#---------To specify test case list ---------\\n\\n#If need to customize you own case list,\\n#paste you case in bundle array\\ndeclare -a bundle=(\\n%s)\\nexport XCAT_TEST_CASE=\"${bundle[*]}\"\\n\\n' % (bundles_str);\n\telse:\n\t\tBUNDLE_STR = ''\n\t\tprint('Here didn\\'t set [customize_bundle] in jenkins_project.conf.')\n\n\tif 'customize_plugin' in conf_dic.keys():\n\t\tplugin_str = conf_dic['customize_plugin']\n\t\tXCAT_TEST_PLUGIN = '#---------To specify the additional plugin----------\\n\\n#using this attribute to specify some customize script which\\'s result will be inserted into normal mail report\\n#The plugin script should be check in Jenkins repo \"~/jenkins/plugin\" ahead.\\nexport XCAT_TEST_PLUGIN=%s\\n\\n' % (plugin_str)\n\telse:\n\t\tXCAT_TEST_PLUGIN = ''\n\t\tprint('Here didn\\'t set customize_plugin in jenkins_project.conf.')\n\n\tcommand_text='#!/bin/bash\\n\\nset -x\\n\\n#---------To spcify OS wanted to run whole test based on---------\\n\\n#[naming rule]:\\n#The os name should be consistent with the os name which xcat copycds generated.\\n#Take redhat7.3 for example,the osimage name is rhels7.3-ppc64le-install-compute,\\n#the value of XCAT_TEST_OS should be rhels7.3\\nexport XCAT_TEST_OS=%s\\n\\n\\n%s%s#---------To spcify automation framework code repo---------\\n\\n%s%s%s%s\\n%s#----------------DO NOT MODIFY BELOW LINES-------------\\n\\ncp /tmp/dengshuai/test.sh .\\n./test.sh' % (XCAT_TEST_OS,XCAT_TEST_BRANCH_OR_CORE,XCAT_TEST_DEP,AUTOMATION_ENV,XCAT_TEST_MAILING_LIST,BUNDLE_STR,XCAT_TEST_DATABASE,XCAT_TEST_PLUGIN)\n\n\n\t##############set configure xml from jenkins_project.conf############\n\t'''\n\tjob_name = pass\n\tassignedNode = pass\n\ttimerTrigger_text = pass\n\tcommand_text = pass\n\t'''\n\n\t'''#get the config.xml from a template project\n\ttemplate_job_name = \"ds_project_template\"#\"test8\"#\"ds_project_template\"\n\tconfig_xml_name = \"config.xml\"##\"project_xml_template.xml\"\n\tconfig = jenkins[template_job_name].get_config()\n\tf = open(config_xml_name,'w')\n\tf.write(config)\n\tf.close()\n'''\n\t#config_xml_name = \"config.xml\"\n\ttree = ET.parse(config_xml_name)###\"config.xml\"\n\troot = tree.getroot()\n\t#root.find('assignedNode').text = assignedNode\n\tnode = root.find('assignedNode')\n\tif node is None:\n\t\tnode = ET.SubElement(root,'assignedNode')\n\tnode.text = assignedNode\n\t\n\ttriggers = root.find('triggers')\n\ttimerTrigger = triggers.find('hudson.triggers.TimerTrigger')\n\tif timerTrigger is None:\n\t\ttimerTrigger = ET.SubElement(triggers,'hudson.triggers.TimerTrigger')\n\tspec = timerTrigger.find('spec')\n\tif spec is None:\n\t\tspec = ET.SubElement(timerTrigger,'spec')\n\tspec.text = timerTrigger_text\n\t\n\tbuilders = root.find('builders')\n\tif builders is None:\n\t\tbuilders = ET.SubElement(root,'builders')\n\tshell = builders.find('hudson.tasks.Shell')\n\tif shell is None:\n\t\tshell = ET.SubElement(builders,'hudson.tasks.Shell')\n\tcommand = shell.find('command')\n\tif command is None:\n\t\tcommand = ET.SubElement(shell,'command')\n\tcommand.text = command_text\n\txml = ET.tostring(root).decode('utf-8')\n\t'''\n\tconfig_output_name = \"config_output.xml\"\n\ttree.write(config_output_name,xml_declaration=True, encoding='utf-8', method=\"xml\")\n'''\n\n\t#job_name = 'ds_project_test1'#foo_job1\n\t###xml = resource_string('examples', 'addjob.xml')\n\t#xml = open('./addjob.xml',encoding='utf8').read()\n\t#xml = open(config_output_name).read()\n\tif job_name in jenkins.jobs:\n\t\tlogger.info('the job named '+job_name+' already exists')\n\telse:\n\t\tjob = jenkins.create_job(jobname=job_name, xml=xml);\n\n\ndef create_empty_job_from_string(projectname):\n\tconf_str ='''\n\n \n \n false\n \n \n true\n false\n false\n false\n \n false\n \n \n \n'''\n\tif projectname in jenkins.jobs:\n\t\tlogger.info('the job '+projectname+' already exists')\n\telse:\n\t\tjob = jenkins.create_job(jobname=projectname,xml=conf_str)\n\n\n\n\ndef change_Schedule(jenkins,projectname,time_str):\n\tjob = jenkins[projectname]\n\tconf = job.get_config()\n\troot = ET.fromstring(conf.strip())\n\ttriggers = root.find('triggers')\n\ttimerTrigger = triggers.find('hudson.triggers.TimerTrigger')\n\tif timerTrigger is None:\n\t\ttimerTrigger = ET.SubElement(triggers,'hudson.triggers.TimerTrigger')\n\tspec1 = timerTrigger.find('spec')\n\tif spec1 is None:\n\t\tspec1 = ET.SubElement(timerTrigger,'spec')\n\tspec1.text = time_str\n\tconf_str = ET.tostring(root).decode('utf-8')\n\tjob.update_config(conf_str)\n\t#tree1 = ET.ElementTree(root)\n\t#tree1.write('new1.xml',xml_declaration=True, encoding='utf-8', method=\"xml\")\n\ndef change_Assigned_Node(jenkins,projectname,node_str):\n\tjob = jenkins[projectname]\n\tconf = job.get_config()\n\troot = ET.fromstring(conf.strip())\n\tnode = root.find('assignedNode')\n\tif node is None:\n\t\tnode = ET.SubElement(root,'assignedNode')\n\tnode.text = node_str\n\tconf_str = ET.tostring(root).decode('utf-8')\n\tjob.update_config(conf_str)\n\t#tree1 = ET.ElementTree(root)\n\t#tree1.write('new1.xml',xml_declaration=True, encoding='utf-8', method=\"xml\")\n\ndef change_Description(jenkins,projectname,description_str):\n\tjob = jenkins[projectname]\n\tconf = job.get_config()\n\troot = ET.fromstring(conf.strip())\n\tdes = root.find('description')\n\tif des is None:\n\t\tdes = ET.SubElement(root,'description')\n\tdes.text = description_str\n\tconf_str = ET.tostring(root).decode('utf-8')\n\tjob.update_config(conf_str)\n\t#tree1 = ET.ElementTree(root)\n\t#tree1.write('new1.xml',xml_declaration=True, encoding='utf-8', method=\"xml\")\n\t\n\ndef change_Command(jenkins,projectname,command_str):\n\tjob = jenkins[projectname]\n\tconf = job.get_config()\n\troot = ET.fromstring(conf.strip())\n\tbuilders = root.find('builders')\n\tif builders is None:\n\t\tbuilders = ET.SubElement(root,'builders')\n\tshell = builders.find('hudson.tasks.Shell')\n\tif shell is None:\n\t\tshell = ET.SubElement(builders,'hudson.tasks.Shell')\n\tcommand = shell.find('command')\n\tif command is None:\n\t\tcommand = ET.SubElement(shell,'command')\n\tcommand.text = command_str\n\tconf_str = ET.tostring(root).decode('utf-8')\n\tjob.update_config(conf_str)\n\n\n\ndef change_group_jobs_schedule(jenkins,group_name,timer_str):\n\tif group_name in jenkins.views:\n\t\tfor job in jenkins.views[group_name].items():\n\t\t\tprint(job[0])\n\t\t\tchange_Schedule(jenkins,job[0],timer_str)##job[0]===>the name of job\n\telse:\n\t\t#logger.info('View has been deleted')\n\t\tlogger.error(group_name+' is not in jenkins.\\n')\n\n\nif __name__ == '__main__':\n\tjenkins_url = 'http://127.0.0.1:8080' #'http://10.2.4.25:8080'\n\tjenkins = Jenkins(jenkins_url,username=\"dengshuai_super\",password=\"8080\") \n\t\n\tcreate_job_by_conf(\"jenkins_project.conf\",\"config.xml\")\n\tchange_Description(jenkins,\"test9\",\"I have change the description of test9!\")\n\tchange_Assigned_Node(jenkins,\"test9\",\"12345\")\n\tchange_Schedule(jenkins,\"test9\",\"H 9 * * *\")\n\tchange_Command(jenkins,\"test9\",\"dir\\n\")\n\t\n\tcreate_empty_job_from_string(\"test7\")\n\tchange_Description(jenkins,\"test7\",\"I have change the description of test8!\")\n\tchange_Assigned_Node(jenkins,\"test7\",\"12345\")\n\tchange_Schedule(jenkins,\"test7\",\"H 2 * * *\")\n\tchange_Command(jenkins,\"test7\",\"dir\")\n\t\n\tchange_group_jobs_schedule(jenkins,\"ds_group2\",\"H 8 * * *\")\n\t\n\n'''\n###build a job,params is optional\nparams = {'VERSION': '1.2.3', 'PYTHON_VER': '2.7'}\n#jenkins.build_job(job_name,params)\n\n\n# This will start the job in non-blocking manner\njenkins.build_job('foo', params)\n\n\n# This will start the job and will return a QueueItem object which\n# can be used to get build results\njob = jenkins['foo']\nqi = job.invoke(build_params=params) ##params can be None.\n\n# Block this script until build is finished\nif qi.is_queued() or qi.is_running():\n qi.block_until_complete()\n\nbuild = qi.get_build()\nprint(build)\n'''\n\n'''\n# Get job from Jenkins by job name\nmy_job = jenkins[job_name]\nprint(my_job)\n\n# Delete job using method in Jenkins class\n#\n# Another way is to use:\n#\n# del jenkins[job_name]\n#jenkins.delete_job(job_name)\n\n# Create ListView in main view\nlogger.info('Attempting to create new view')\n#test_view_name = 'ds_group2'#SimpleListView1\nmy_view = jenkins.views.create(test_view_name)\nmy_view.add_job(job_name, my_job)\n\n#assert len(my_view) == 1 ##len(my_view) can get the number of jobs in the view\n\n#logger.info('Attempting to delete view that already exists')\n#del jenkins.views[test_view_name]\n\n#if test_view_name in jenkins.views:\n# logger.error('View was not deleted')\n#else:\n# logger.info('View has been deleted')\n\n\nfor job in jenkins.views[test_view_name].items():\n print(job)\n'''\n###python createJob.py -g group2 -s \"H 6 * * *\"/disable\n###python createJob.py -p project_name\n","sub_path":"createJob2.py","file_name":"createJob2.py","file_ext":"py","file_size_in_byte":16115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"405318037","text":"import os\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n# path to our data folder, contains media, db, local_settings\nDATA_DIR = os.path.join(BASE_DIR, 'data')\n\n# load the secret key, it'll be created if needed\n# NOTE: DO NOT CHECK SECRET.TXT IN TO SOURCE CONTROL\nSECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')\ntry:\n SECRET_KEY = open(SECRET_FILE).read().strip()\nexcept IOError:\n try:\n import random\n SECRET_KEY = ''.join([random.SystemRandom().choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)])\n secret = open(SECRET_FILE, 'w')\n secret.write(SECRET_KEY)\n secret.close()\n except IOError:\n Exception('Please create a %s file with random characters to generate your secret key!' % SECRET_FILE)\n\nSITE_ID = 1\n\n\n# Application definition\n\nINSTALLED_APPS = [\n 'djangocms_admin_style',\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.sites',\n 'django.contrib.staticfiles',\n 'cms',\n 'crispy_forms',\n 'menus',\n 'sekizai',\n 'treebeard',\n 'filer',\n 'easy_thumbnails',\n 'mptt',\n 'djangocms_text_ckeditor',\n 'djangocms_link',\n 'djangocms_file',\n 'djangocms_picture',\n 'djangocms_video',\n 'djangocms_googlemap',\n # 'djangocms_snippet',\n 'djangocms_style',\n 'djangocms_column',\n\n # our apps\n 'hobbytown',\n 'apps.base_user',\n 'apps.email_error',\n 'apps.newsletter',\n 'areas.hb_admin',\n 'areas.public',\n 'areas.public.home',\n 'areas._shared',\n]\n\nMIDDLEWARE_CLASSES = [\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.middleware.locale.LocaleMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'cms.middleware.user.CurrentUserMiddleware',\n 'cms.middleware.page.CurrentPageMiddleware',\n 'cms.middleware.toolbar.ToolbarMiddleware',\n 'cms.middleware.language.LanguageCookieMiddleware',\n]\n\nROOT_URLCONF = 'hobbytown.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [\n os.path.join(BASE_DIR, 'areas', 'hb_admin/templates/hb_admin'),\n os.path.join(BASE_DIR, 'areas', 'public/templates/public'),\n os.path.join(BASE_DIR, 'areas', '_shared/templates/_shared'),\n ],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'cms.context_processors.cms_settings',\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n 'sekizai.context_processors.sekizai',\n 'hobbytown.template_context.current_user',\n ],\n },\n },\n]\n\nCMS_TEMPLATES = [\n ('public/home.html', 'Home page template'),\n ('public/default.html', 'Default page template'),\n]\n\nWSGI_APPLICATION = 'hobbytown.wsgi.application'\n\n\n# Password validation\n# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.10/topics/i18n/\n\nLANGUAGE_CODE = 'en'\n\nLANGUAGES = [\n ('en', 'English'),\n]\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.10/howto/static-files/\n\nSTATICFILES_DIRS = ( )\nfor root, dirs, files in os.walk(BASE_DIR):\n if 'static' in dirs: STATICFILES_DIRS = STATICFILES_DIRS + (os.path.join(root, 'static'),)\n\nSTATIC_URL = '/static/'\nSTATIC_ROOT = os.path.join(BASE_DIR, 'static_root')\nMEDIA_URL = '/media/'\nMEDIA_ROOT = os.path.join(DATA_DIR, 'media')\n\nTHUMBNAIL_HIGH_RESOLUTION = True\nTHUMBNAIL_PROCESSORS = (\n 'easy_thumbnails.processors.colorspace',\n 'easy_thumbnails.processors.autocrop',\n 'filer.thumbnail_processors.scale_and_crop_with_subject_location',\n 'easy_thumbnails.processors.filters'\n)\n\n\n# Email settings\n# Note: the override is in settings_local\nEMAIL_ENABLED = True\nEMAIL_USE_TLS = True\n# EMAIL_USE_SSL = True\nEMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'\n\n\n# load the local settings file\ndef _load_settings(path):\n print (\"Loading configuration from %s\" % (path))\n if os.path.exists(path):\n settings = {}\n # execfile can't modify globals directly, so we will load them manually\n # execfile(path, globals(), settings)\n exec(open(path).read(), globals(), settings)\n\n for setting in settings:\n globals()[setting] = settings[setting]\n_load_settings(os.path.join(BASE_DIR, \"data/settings_local.py\"))","sub_path":"hobbytown/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":5572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"167671023","text":"\"\"\"\nImport Conwy\n\"\"\"\nfrom django.contrib.gis.geos import Point\nfrom data_collection.management.commands import BaseShpImporter\n\nclass Command(BaseShpImporter):\n \"\"\"\n Imports the Polling Station data from Conwy Council\n \"\"\"\n council_id = 'W06000003'\n districts_name = 'Conwy CBC Polling Districts 20160407'\n stations_name = 'Conwy CBC Polling Stations (with UPRN) 20160407.csv'\n elections = [\n 'pcc.2016-05-05',\n 'naw.c.2016-05-05',\n 'naw.r.2016-05-05',\n 'ref.2016-06-23'\n ]\n\n def district_record_to_dict(self, record):\n return {\n 'internal_council_id': record[5],\n 'name': record[4],\n }\n\n def station_record_to_dict(self, record):\n try:\n location = Point(int(record.easting), int(record.northing), srid=self.get_srid())\n except ValueError:\n location = Point(float(record.easting), float(record.northing), srid=self.get_srid())\n\n postcode = record.polling_station_address.split(', ')[-1]\n address = \"\\n\".join(record.polling_station_address.split(', ')[:-1])\n\n return {\n 'internal_council_id': record.districts,\n 'postcode' : postcode,\n 'address' : address,\n 'polling_district_id': record.districts,\n 'location' : location\n }\n","sub_path":"polling_stations/apps/data_collection/management/commands/import_conwy.py","file_name":"import_conwy.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"367478983","text":"#!/usr/bin/env python3\n# -*- encoding: utf-8 -*-\n\n\n'''\n@Useway : 测试模型效果\n@File : test.py\n@Time : 2021/01/14 10:13:19\n@Author : Chen Zhuang \n@Version : 1.0\n@Contact : whut_chenzhuang@163.com\n@Time: 2021/01/14 10:13:19\n'''\n\nfrom pathlib import Path\nfrom net import Generator,Discriminator\nimport torch\nfrom torch.utils.data import DataLoader\nfrom G import OUT_DIR,TEST_DATA_PATH\nfrom icvl_data import LoadData\nfrom utils import *\n\n\nBATCH_SIZE = 72\nFAKE_HR = torch.zeros([72*8,31,144,144])\nHR = torch.zeros([72*8,31,144,144])\nPSNR = 0\nSAMs = 0\n\nif __name__ == \"__main__\":\n \n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n print('test decice is {}'.format(device))\n\n g_model = Generator(BATCH_SIZE).to(device)\n state_dict_g = g_model.state_dict()\n\n d_model = Discriminator(BATCH_SIZE).to(device)\n state_dict_d = d_model.state_dict()\n\n g_weight = OUT_DIR.joinpath('icvl_g_model.pth')\n # g_model = torch.load(g_weight)\n\n d_weight = OUT_DIR.joinpath('icvl_d_model.pth')\n # d_model = torch.load(d_weight)\n\n for n, p in torch.load(g_weight, map_location=lambda storage, loc: storage).items():\n if n in state_dict_g.keys():\n state_dict_g[n].copy_(p)\n else:\n raise KeyError(n)\n\n for n, p in torch.load(d_weight, map_location=lambda storage, loc: storage).items():\n if n in state_dict_d.keys():\n state_dict_d[n].copy_(p)\n else:\n raise KeyError(n)\n\n\n g_model.eval()\n d_model.eval()\n\n _, _, test_paths = get_paths()\n \n test_data = DataLoader(\n LoadData(test_paths,'test'),\n batch_size=BATCH_SIZE,\n shuffle=False,\n num_workers= 2, \n pin_memory= True,\n drop_last= True,\n )\n\n count = 0\n for lr,hr in test_data:\n\n lr = lr.reshape((lr.shape[0],1,lr.shape[1],lr.shape[2],lr.shape[3]))\n lr = lr.to(device)\n hr = hr.reshape((hr.shape[0],1,hr.shape[1],hr.shape[2],hr.shape[3]))\n hr = hr.to(device)\n\n\n with torch.no_grad():\n\n fake_hr = g_model(lr)\n fake_hr = torch.squeeze(fake_hr)\n hr = torch.squeeze(hr)\n\n hr = hr.cpu()\n fake_hr = fake_hr.cpu()\n\n #因为bs 设置的关系 算出来的 就是一张图的平均了\n psnr = PSNR_GPU(hr,fake_hr)\n sam = SAM(hr,fake_hr)\n print('img : {} psnr : {:.4f} sam : {:.4f}'.format(\n count+1,psnr,sam\n ))\n PSNR += psnr\n SAMs += sam\n\n FAKE_HR[count*72:(count+1)*72] = fake_hr\n HR[count*72:(count+1)*72] = hr\n # print(hr.size())\n \n count += 1\n print(PSNR / 8, SAMs / 8)\n torch.save(FAKE_HR, OUT_DIR.joinpath('icvl_test_fake_hr.pth'))\n torch.save(HR, OUT_DIR.joinpath('icvl_hr.pth'))\n \n\n\n \n\n\n\n\n","sub_path":"icvl_test.py","file_name":"icvl_test.py","file_ext":"py","file_size_in_byte":2918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"63426701","text":"from pyramid import renderers\nfrom pyramid.config import Configurator\nfrom pyramid.session import SignedCookieSessionFactory\nfrom webassets import Bundle\n\n\ndef include_js(config):\n\n minjs = Bundle(\n 'node_modules/jquery/dist/jquery.min.js',\n 'node_modules/uikit/dist/js/uikit.min.js',\n 'node_modules/angular/angular.min.js',\n 'node_modules/angular-ui-router/release/angular-ui-router.min.js',\n\n 'js/lib/jquery.nano.js',\n\n 'js/app.js',\n\n 'js/controllers/login.ctrl.js',\n 'js/controllers/home.ctrl.js',\n\n output='js/generated.js',\n filters='jsmin'\n )\n config.add_webasset('minjs', minjs)\n\ndef include_css(config):\n\n theme = '.almost-flat'\n\n mincss = Bundle(\n\n 'node_modules/uikit/dist/css/uikit%s.css' % theme,\n\n 'css/app.css',\n 'css/home.css',\n\n output='css/generated.css',\n filters='cssmin'\n )\n config.add_webasset('mincss', mincss)\n\ndef main(global_config, **settings):\n \"\"\" This function returns a Pyramid WSGI application.\n \"\"\"\n config = Configurator(settings=settings)\n\n config.set_session_factory(SignedCookieSessionFactory('itsaseekreet'))\n\n config.add_mako_renderer('.html')\n\n json_renderer = renderers.JSON()\n config.add_renderer('json', json_renderer)\n\n config.include('pyramid_jinja2')\n config.include('.models')\n config.include('.routes')\n config.include(include_js)\n config.include(include_css)\n config.scan()\n return config.make_wsgi_app()\n","sub_path":"bookroom/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"254098726","text":"\"\"\"\nThis code includes useful functions for data managements.\nFunctions are not data dependent.\n\"\"\"\n\nimport numpy as np\n\n\ndef int_to_onehot(input, total_class):\n \"\"\"\n This function converts integer label data to one-hot encoded matrix.\n\n Parameters\n ----------\n input: vector\n a numpy vector that only contains the label of class.\n total_class: integer\n a integer value which indicates total classes.\n output dimension will be this.\n\n Returns\n -------\n ndarray\n a numpy matrix of (batch size, total class).\n \"\"\"\n # check asserts\n assert isinstance(total_class, int), '\"total_class\" should be positive integer, number of classes.'\n n_input = len(input)\n result = np.zeros((n_input, total_class)).astype('int32') # create output\n result[np.arange(n_input), input] = 1 # set 1 for each label, each data\n return result\n\n\ndef split_data(input, rule=0.9):\n \"\"\"\n This function split inputs to two groups.\n The order of input data (or label) is unchanged.\n Split starts from the start, i.e., 0.9 / 0.1, not 0.1 / 0.9.\n\n Parameters\n ----------\n input: n-dim nparray or list\n an array or a list of anything.\n rule: float, int\n rule to split.\n if 0 < rule < 1, split by ratio. if rule > 1, split by numbers.\n\n Returns\n -------\n tuple\n a tuple of two splitted parts.\n \"\"\"\n # check asserts\n assert 0 < rule, 'Rule should be a positive value.'\n num_input = len(input) # also works for ndarray.\n\n # divide\n if rule < 1:\n num_first = np.floor(num_input * rule)\n num_second = num_input - num_first\n print('Splitted to:', num_first, 'and', num_second)\n first_input = input[:num_first]\n second_input = input[num_first:]\n elif rule >= 1:\n assert rule < num_input, 'Rule cannot be bigger than the number of inputs.'\n assert isinstance(rule, int), 'If rule > 1, rule should be an integer.'\n print('Splitted to:', rule, 'and', num_input - rule)\n first_input = input[:rule]\n second_input = input[rule:]\n else:\n raise ValueError('Invalid input \"rule\".')\n return first_input, second_input\n","sub_path":"lemontree/utils/data_utils.py","file_name":"data_utils.py","file_ext":"py","file_size_in_byte":2207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"418393975","text":"\n# http://www.ibm.com/developerworks/linux/library/l-cpyiter.html\ndef ireduce(func, iterable, init=None):\n if init is None:\n iterable = iter(iterable)\n curr = iterable.next()\n else:\n curr = init\n yield curr\n for x in iterable:\n curr = func(curr, x)\n yield curr\n","sub_path":"square-spiral-py/src/functional.py","file_name":"functional.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"486389124","text":"from __future__ import (\n unicode_literals,\n absolute_import,\n print_function,\n division,\n )\nstr = type('')\n\nimport warnings\nimport pigpio\n\nfrom . import Pin\nfrom .data import pi_info\nfrom ..exc import (\n PinInvalidFunction,\n PinSetInput,\n PinFixedPull,\n PinInvalidPull,\n PinInvalidBounce,\n PinInvalidState,\n PinNonPhysical,\n PinNoPins,\n )\n\n\nclass PiGPIOPin(Pin):\n \"\"\"\n Uses the `pigpio`_ library to interface to the Pi's GPIO pins. The pigpio\n library relies on a daemon (``pigpiod``) to be running as root to provide\n access to the GPIO pins, and communicates with this daemon over a network\n socket.\n\n While this does mean only the daemon itself should control the pins, the\n architecture does have several advantages:\n\n * Pins can be remote controlled from another machine (the other\n machine doesn't even have to be a Raspberry Pi; it simply needs the\n `pigpio`_ client library installed on it)\n * The daemon supports hardware PWM via the DMA controller\n * Your script itself doesn't require root privileges; it just needs to\n be able to communicate with the daemon\n\n You can construct pigpiod pins manually like so::\n\n from gpiozero.pins.pigpiod import PiGPIOPin\n from gpiozero import LED\n\n led = LED(PiGPIOPin(12))\n\n This is particularly useful for controlling pins on a remote machine. To\n accomplish this simply specify the host (and optionally port) when\n constructing the pin::\n\n from gpiozero.pins.pigpiod import PiGPIOPin\n from gpiozero import LED\n from signal import pause\n\n led = LED(PiGPIOPin(12, host='192.168.0.2'))\n\n .. note::\n\n In some circumstances, especially when playing with PWM, it does appear\n to be possible to get the daemon into \"unusual\" states. We would be\n most interested to hear any bug reports relating to this (it may be a\n bug in our pin implementation). A workaround for now is simply to\n restart the ``pigpiod`` daemon.\n\n .. _pigpio: http://abyz.co.uk/rpi/pigpio/\n \"\"\"\n\n _CONNECTIONS = {}\n _PINS = {}\n\n GPIO_FUNCTIONS = {\n 'input': pigpio.INPUT,\n 'output': pigpio.OUTPUT,\n 'alt0': pigpio.ALT0,\n 'alt1': pigpio.ALT1,\n 'alt2': pigpio.ALT2,\n 'alt3': pigpio.ALT3,\n 'alt4': pigpio.ALT4,\n 'alt5': pigpio.ALT5,\n }\n\n GPIO_PULL_UPS = {\n 'up': pigpio.PUD_UP,\n 'down': pigpio.PUD_DOWN,\n 'floating': pigpio.PUD_OFF,\n }\n\n GPIO_EDGES = {\n 'both': pigpio.EITHER_EDGE,\n 'rising': pigpio.RISING_EDGE,\n 'falling': pigpio.FALLING_EDGE,\n }\n\n GPIO_FUNCTION_NAMES = {v: k for (k, v) in GPIO_FUNCTIONS.items()}\n GPIO_PULL_UP_NAMES = {v: k for (k, v) in GPIO_PULL_UPS.items()}\n GPIO_EDGES_NAMES = {v: k for (k, v) in GPIO_EDGES.items()}\n\n def __new__(cls, number, host='localhost', port=8888):\n try:\n return cls._PINS[(host, port, number)]\n except KeyError:\n self = super(PiGPIOPin, cls).__new__(cls)\n try:\n self._connection, self._pi_info = cls._CONNECTIONS[(host, port)]\n except KeyError:\n self._connection = pigpio.pi(host, port)\n revision = hex(self._connection.get_hardware_revision())[2:]\n self._pi_info = pi_info(revision)\n cls._CONNECTIONS[(host, port)] = (self._connection, self._pi_info)\n try:\n self._pi_info.physical_pin('GPIO%d' % number)\n except PinNoPins:\n warnings.warn(\n PinNonPhysical(\n 'no physical pins exist for GPIO%d' % number))\n self._host = host\n self._port = port\n self._number = number\n self._pull = 'up' if self._pi_info.pulled_up('GPIO%d' % number) else 'floating'\n self._pwm = False\n self._bounce = None\n self._when_changed = None\n self._callback = None\n self._edges = pigpio.EITHER_EDGE\n try:\n self._connection.set_mode(self._number, pigpio.INPUT)\n except pigpio.error as e:\n raise ValueError(e)\n self._connection.set_pull_up_down(self._number, self.GPIO_PULL_UPS[self._pull])\n self._connection.set_glitch_filter(self._number, 0)\n self._connection.set_PWM_range(self._number, 255)\n cls._PINS[(host, port, number)] = self\n return self\n\n def __repr__(self):\n if self._host == 'localhost':\n return \"GPIO%d\" % self._number\n else:\n return \"GPIO%d on %s:%d\" % (self._number, self._host, self._port)\n\n @property\n def host(self):\n return self._host\n\n @property\n def port(self):\n return self._port\n\n @property\n def number(self):\n return self._number\n\n def close(self):\n # If we're shutting down, the connection may have disconnected itself\n # already. Unfortunately, the connection's \"connected\" property is\n # rather buggy - disconnecting doesn't set it to False! So we're\n # naughty and check an internal variable instead...\n if self._connection.sl.s is not None:\n self.frequency = None\n self.when_changed = None\n self.function = 'input'\n self.pull = 'up' if self._pi_info.pulled_up('GPIO%d' % self.number) else 'floating'\n\n def _get_function(self):\n return self.GPIO_FUNCTION_NAMES[self._connection.get_mode(self._number)]\n\n def _set_function(self, value):\n if value != 'input':\n self._pull = 'floating'\n try:\n self._connection.set_mode(self._number, self.GPIO_FUNCTIONS[value])\n except KeyError:\n raise PinInvalidFunction('invalid function \"%s\" for pin %r' % (value, self))\n\n def _get_state(self):\n if self._pwm:\n return self._connection.get_PWM_dutycycle(self._number) / 255\n else:\n return bool(self._connection.read(self._number))\n\n def _set_state(self, value):\n if self._pwm:\n try:\n self._connection.set_PWM_dutycycle(self._number, int(value * 255))\n except pigpio.error:\n raise PinInvalidState('invalid state \"%s\" for pin %r' % (value, self))\n elif self.function == 'input':\n raise PinSetInput('cannot set state of pin %r' % self)\n else:\n # write forces pin to OUTPUT, hence the check above\n self._connection.write(self._number, bool(value))\n\n def _get_pull(self):\n return self._pull\n\n def _set_pull(self, value):\n if self.function != 'input':\n raise PinFixedPull('cannot set pull on non-input pin %r' % self)\n if value != 'up' and self._pi_info.pulled_up('GPIO%d' % self._number):\n raise PinFixedPull('%r has a physical pull-up resistor' % self)\n try:\n self._connection.set_pull_up_down(self._number, self.GPIO_PULL_UPS[value])\n self._pull = value\n except KeyError:\n raise PinInvalidPull('invalid pull \"%s\" for pin %r' % (value, self))\n\n def _get_frequency(self):\n if self._pwm:\n return self._connection.get_PWM_frequency(self._number)\n return None\n\n def _set_frequency(self, value):\n if not self._pwm and value is not None:\n self._connection.set_PWM_frequency(self._number, value)\n self._connection.set_PWM_dutycycle(self._number, 0)\n self._pwm = True\n elif self._pwm and value is not None:\n self._connection.set_PWM_frequency(self._number, value)\n elif self._pwm and value is None:\n self._connection.set_PWM_dutycycle(self._number, 0)\n self._pwm = False\n\n def _get_bounce(self):\n return None if not self._bounce else self._bounce / 1000000\n\n def _set_bounce(self, value):\n if value is None:\n value = 0\n elif value < 0:\n raise PinInvalidBounce('bounce must be 0 or greater')\n self._connection.set_glitch_filter(self._number, int(value * 1000000))\n\n def _get_edges(self):\n return self.GPIO_EDGES_NAMES[self._edges]\n\n def _set_edges(self, value):\n f = self.when_changed\n self.when_changed = None\n try:\n self._edges = self.GPIO_EDGES[value]\n finally:\n self.when_changed = f\n\n def _get_when_changed(self):\n if self._callback is None:\n return None\n return self._callback.callb.func\n\n def _set_when_changed(self, value):\n if self._callback is not None:\n self._callback.cancel()\n self._callback = None\n if value is not None:\n self._callback = self._connection.callback(\n self._number, self._edges,\n lambda gpio, level, tick: value())\n\n","sub_path":"gpiozero/pins/pigpiod.py","file_name":"pigpiod.py","file_ext":"py","file_size_in_byte":9005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"390236790","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # dataset definition\n\n# In[ ]:\n\n\nimport os\nimport numpy as np\nfrom PIL import Image\nimport torch\nfrom torch.utils.data import Dataset\nfrom torchvision import transforms\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport tqdm\n\nos.environ['CUDA_VISIBLE_DEVICES'] = '1'\n\n\n# In[ ]:\n\n\nclass MyDataset(Dataset):\n \n def __init__(self, df, dataset_str, img_dir, occ_dir, occ_type):\n \"\"\"\n return: (img, landmarks), aus\n \"\"\"\n self.df, self.dataset_str, self.img_dir = df.copy(), dataset_str, img_dir\n self.occ_dir, self.occ_type = occ_dir, occ_type\n \n self.img_path = ['/'.join([img_dir, val]) for val in df['path']]\n self.landmarks = df.values[:, -48:].reshape((-1,24,2)).astype(np.float32)/108*224\n select_AU = [ 'AU01','AU02', 'AU04', 'AU06', 'AU07', 'AU10', 'AU12', 'AU14', 'AU15', 'AU17','AU23', 'AU24']\n self.aus = df[select_AU].values.astype(np.float32)\n \n def fun(x):\n \"\"\" 单张图像标准化 \"\"\"\n c, w, h = x.shape\n x = x.view((c,-1))\n x = (x-torch.mean(x, dim=1, keepdim=True))/(torch.std(x,dim=1, keepdim=True)+1e-5)\n x = x.view((c,w,h))\n return x\n self.img_preprocess = transforms.Compose([\n transforms.Resize([224, 224], interpolation=Image.CUBIC),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.44225878, 0.27311772, 0.21546765], \\\n std=[0.25960645, 0.16986448, 0.13451453]),\n #transforms.Lambda(lambd=fun),\n ])\n if dataset_str in ['train_mix', 'train_clean', 'train_occ']:\n img_aug = transforms.Compose([\n transforms.ColorJitter(\n brightness=0.4,\n saturation=0.4\n ),\n #transforms.RandomRotation(10),\n #transforms.RandomHorizontalFlip()\n ])\n self.img_preprocess.transforms = img_aug.transforms+self.img_preprocess.transforms\n \n self.occ_img_preprocess = transforms.Compose([\n transforms.RandomRotation(30),\n transforms.RandomHorizontalFlip()\n ])\n self.occ_imgs = self.__get_occ_list()\n \n def __get_occ_list(self):\n file_list = [np.array(Image.open('/'.join([self.occ_dir, val]))) for val in os.listdir(self.occ_dir)]\n return file_list\n \n def __getitem__(self, index):\n X = Image.open(self.img_path[index]).convert(mode='RGB')\n landmarks = self.landmarks[index]\n aus = self.aus[index]\n if self.dataset_str in ['train_mix', 'valid_mix']:\n occlusion = np.random.randint(0, 2, (1,)).astype(np.int64)[0]\n elif self.dataset_str in ['train_clean', 'valid_clean']:\n occlusion = 0\n elif self.dataset_str in ['train_occ', 'valid_occ']:\n occlusion = 1\n \n if occlusion == 1: X = self.__addOcclusion(X)\n \n X = self.img_preprocess(X)\n return (X, torch.tensor(landmarks)), aus\n \n def __addOcclusion(self, X):\n short = min(X.size)\n X = np.array(X)\n # (row, col)随机选取\n row = np.random.randint(X.shape[0]) \n col = np.random.randint(X.shape[1])\n\n if self.occ_type == 'one-sixth':\n occ_size = short // 6\n elif self.occ_type == 'one-third':\n occ_size = short // 3\n elif self.occ_type == 'one-second':\n occ_size = short // 2\n\n # 随机选择一幅遮挡素材\n occ = self.occ_imgs[np.random.randint(0, len(self.occ_imgs))]\n occ = Image.fromarray(occ).convert('RGBA')\n #occ = Image.open(occ)\n occ = self.occ_img_preprocess(occ)\n occ = occ.resize((occ_size, occ_size))\n occ = np.array(occ)\n \n # 在(row, col)处叠加遮挡素材\n row_begin = row - occ_size // 2\n col_begin = col - occ_size // 2\n row_begin = 0 if row_begin < 0 else row_begin\n col_begin = 0 if col_begin < 0 else col_begin\n patch = X[row_begin : (row_begin + occ_size), col_begin : (col_begin + occ_size), :]\n \n # 裁剪mask使得occ,使得occ和patch的shape完全相同\n occ = occ[:patch.shape[0], :patch.shape[1]]\n mask = occ[:, :, 3] > 150 #遮挡图像的白色区域不融合\n mask = np.expand_dims(mask, 2)\n mask = np.tile(mask, [1, 1, 3])\n\n temp = patch * (1 - mask) + occ[:, :, :3] * mask\n X[row_begin : row_begin + occ_size, col_begin : col_begin + occ_size, :] = temp\n X = Image.fromarray(X)\n return X\n \n def __len__(self): return len(self.img_path)\n\ndef compute_mean_std(ds):\n ex1 = []\n exs1 = []\n for i in tqdm.tqdm_notebook(range(len(ds))):\n x, y = ds[i]\n img1 = x.numpy()\n ex1.append(np.mean(img1, axis=(1,2)))\n exs1.append(np.mean(img1*img1, axis=(1,2)))\n ex1 = np.stack(ex1, axis=0).mean(axis=0)\n exs1 = np.stack(exs1, axis=0).mean(axis=0)\n s1 = np.sqrt(exs1-ex1*ex1)\n print(\"mean1:\", ex1)\n print(\"s1:\", s1) \n\n\n# In[ ]:\n\n\n# img_dir = '../dataBP4D/Images'\n# occ_dir = '../Occlusion Resource'\n# df = pd.read_csv('../dataBP4D/label_withLandmarks.csv')\n# m = {}\n# for i, v in enumerate(df.subject.value_counts().index):\n# m[v] = i\n# df.subject = df.subject.map(m)\n# ds = MyDataset(df, 'train_mix', img_dir, occ_dir, occ_type='one-second')\n# img, landmarks = ds[0][0]\n# plt.imshow(np.transpose(img, (1,2,0)))\n# plt.scatter(landmarks[:,1], landmarks[:,0])\n# for i in range(24):\n# plt.text(landmarks[i,1], landmarks[i,0], str(i))\n\n\n# # model definition\n\n# In[ ]:\n\n\nfrom collections import OrderedDict\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torchvision import models\nfrom fastai.vision import Flatten\n\n\n# In[ ]:\n\n\nclass PGUnit(nn.Module):\n def __init__(self, in_channels, size, num_out):\n '''\n input: bs x 512 x k x k\n output: bs x num_out\n '''\n super(PGUnit, self).__init__()\n self.body = nn.Sequential(*[\n nn.Conv2d(in_channels, out_channels=512, kernel_size=3, stride=1, padding=1),\n nn.BatchNorm2d(num_features=512), nn.ReLU(inplace=True),\n nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1),\n nn.BatchNorm2d(num_features=512), nn.ReLU(inplace=True),\n ])\n self.attention = self.__make_attention_layers(512)\n self.fc = nn.Sequential(*[\n nn.Linear(512*size*size, num_out), nn.ReLU(inplace=True),\n ])\n def __make_attention_layers(self, num_features):\n tmp = nn.Sequential(*[\n nn.MaxPool2d(kernel_size=2, stride=2),\n nn.Conv2d(num_features, out_channels=128, kernel_size=1, stride=1, padding=1), #为了改变通道数目\n nn.BatchNorm2d(128),nn.ReLU(inplace=True),\n nn.AdaptiveAvgPool2d(output_size=[1,1]), Flatten(),\n nn.Linear(128, 64),nn.BatchNorm1d(64),nn.ReLU(inplace=True),\n nn.Linear(64,1),nn.BatchNorm1d(1, affine=True),nn.Sigmoid(), #caffe中scale为batchNorm中的后续层,pytorch中默认包含\n ])\n return tmp\n def forward(self, x):\n h = self.body(x)\n attention = self.attention(h)\n features = self.fc(h.view(h.shape[0], -1))\n return features*attention # 相当于caffe的Scale\n\n\n# In[ ]:\n\n\nclass GACNN(nn.Module):\n def __init__(self, num_AU):\n super(GACNN, self).__init__()\n self.vgg_features = models.vgg16_bn(pretrained=True).features # return bs x 512 x28 x28\n for val in range(30, 44): del self.vgg_features._modules[str(val)]\n self.extra_vgg = nn.Sequential(*[\n nn.Conv2d(512, 512, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(512), nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=2),\n ])\n for i in range(24): self._modules['PG%02d' % i] = PGUnit(512, 6, 64)\n self._modules['PGWhole'] = PGUnit(512, 14, 512)\n self.classifier = nn.Sequential(*[\n nn.ReLU(inplace=True),\n nn.Linear(64*24+512, 1024), nn.Dropout(0.5), nn.ReLU(inplace=True),\n nn.Linear(1024, num_AU),\n ])\n def __make_patchs(self, vgg_map, center_landmarks):\n center_landmarks = (center_landmarks/224*28).long()\n upleft_landmarks = (center_landmarks-torch.tensor([[[3,3]]]).cuda()).long()\n upleft_landmarks = torch.clamp(upleft_landmarks, min=0, max=22)\n bs, channels = vgg_map.shape[:2]\n out = torch.rand(24, bs, channels, 6, 6).cuda()\n for i, one_sample in enumerate(upleft_landmarks):\n for j, one_patch in enumerate(one_sample):\n out[j][i] = vgg_map[i][:,one_patch[0]:one_patch[0]+6, one_patch[1]:one_patch[1]+6]\n return out\n \n def forward(self, x):\n img, landmarks = x\n vgg_map = self.vgg_features(img)\n vgg_patchs = self.__make_patchs(vgg_map, landmarks)\n features = []\n for i in range(24):\n features.append(self._modules['PG%02d'%i](vgg_patchs[i]))\n features.append(self._modules['PGWhole'](self.extra_vgg(vgg_map)))\n features = torch.cat(features, dim=1)\n \n out = self.classifier(features)\n return out\n \n\n\n# # training function\n\n# In[ ]:\n\n\nfrom fastai.vision import SmoothenValue\nimport sys\nstdout = sys.stdout\n\n\n# In[ ]:\n\n\ndef train_one_epoch(dl, net, train_options, train_flag=False):\n num_batchs = len(dl)\n y_true, y_pred = [], []\n avg_loss = SmoothenValue(beta=0.99)\n if train_flag is True: net.train()\n else: net.eval()\n i = 0\n for batch_Xs, batch_ys in tqdm.tqdm(dl):\n batch_Xs = [val.cuda() for val in batch_Xs]\n batch_ys = batch_ys.cuda()\n \n batch_ys_ = net(batch_Xs)\n y_true.append(batch_ys.cpu().numpy())\n y_pred.append(batch_ys_.detach().cpu().numpy())\n cost = train_options['loss'](batch_ys_, batch_ys)\n avg_loss.add_value(cost.item())\n \n if train_flag is True:\n train_options['optimizer'].zero_grad()\n cost.backward()\n train_options['optimizer'].step()\n \n if train_options['show']!=-1 and i % train_options['show']==0:\n stdout.write(\"%04d/%04d: loss-->%.6f\\n\" % (i, num_batchs, avg_loss.mov_avg))\n i += 1\n y_true = np.concatenate(y_true, axis=0)\n y_pred = np.concatenate(y_pred, axis=0)\n return y_true, y_pred, avg_loss.mov_avg\n\n\n# In[ ]:\n\n\nfrom sklearn.metrics import accuracy_score, f1_score\nimport time\nimport torch\n\ndef sigmoid(x):\n return 1/(1+np.exp(-x))\n\ndef evaluate_AU(y, y_, pivot=0.5):\n y_ = (sigmoid(y_)>pivot).astype(np.int32)\n f1 = f1_score(y_true=y, y_pred=y_, average='macro', pos_label=1)\n all_f1 = f1_score(y_true=y, y_pred=y_, average=None, pos_label=1)\n return {'f1': f1, 'all_f1':all_f1}\n\ndef show(trn_metric, val_clean_metric, val_occ_metric):\n ans = \"trn: \";\n print(\"trn: \", end='\\n', file=log_file, flush=True)\n for key, val in trn_metric.items():\n if key!='all_f1':\n ans = ans + \"(%s:%.4f)\"%(key,val)\n print(\"(%s:%.4f)\"%(key,val), end='\\n', file=log_file, flush=True)\n else:\n print(val, end='\\n', file=log_file, flush=True)\n ans = ans + \"\\t val_clean: \"\n print(\"val_clean: \", end='\\n', file=log_file, flush=True)\n for key, val in val_clean_metric.items():\n if key!='all_f1':\n ans = ans + \"(%s:%.4f)\"%(key,val)\n print(\"(%s:%.4f)\"%(key,val), end='\\n', file=log_file, flush=True)\n else:\n print(val, end='\\n', file=log_file, flush=True)\n ans = ans + \"\\t val_occ: \"\n print(\"val_occ: \", end='\\n', file=log_file, flush=True)\n for key, val in val_occ_metric.items():\n if key!='all_f1':\n ans = ans + \"(%s:%.4f)\"%(key,val)\n print(\"(%s:%.4f)\"%(key,val), end='\\n', file=log_file, flush=True)\n else:\n print(val, end='\\n', file=log_file, flush=True)\n return ans\n\ndef f_train_process(dl, net, train_options, train_flag):\n #s = time.time()\n y, y_, cost = train_one_epoch(dl, net, train_options, train_flag)\n metric = evaluate_AU(y, y_)\n #print(\"elapsed %.4fs\" % (time.time()-s))\n return metric\ndef train_process(num_epochs, trn_dl, val_dl, net, train_options):\n \n best_eval = {'occ':0, 'clean':0}\n for i in range(num_epochs):\n print((\"epochs %02d\" % i).center(50, '='), end='\\n', file=log_file, flush=True)\n trn_metric = f_train_process(trn_dl, net, train_options, train_flag=True)\n \n val_dl.dataset.dataset_str = 'valid_clean'\n val_clean_metric = f_train_process(valid_dl, net, train_options, train_flag=False)\n val_dl.dataset.dataset_str = 'valid_occ'\n val_occ_metric = f_train_process(valid_dl, net, train_options, train_flag=False)\n \n show_str = show(trn_metric, val_clean_metric, val_occ_metric)\n stdout.write(show_str+'\\n')\n torch.save(net.state_dict(), f='/'.join([model_dir, train_options['time']+(\"Epoch%03d\"%i)]))\n return best_eval\n\n\n# # training\n\n# In[ ]:\n\n\nimport torch.optim as optim\nfrom sklearn.model_selection import KFold, train_test_split\nfrom torch.utils.data import DataLoader\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\n# In[ ]:\n\n\nimg_dir = '../dataBP4D/Images'\nocc_dir = '../Occlusion Resource'\ndf = pd.read_csv('../dataBP4D/label_withLandmarks.csv')\nm = {}\nfor i, v in enumerate(df.subject.value_counts().index):\n m[v] = i\ndf.subject = df.subject.map(m)\n\ndf_all = df.copy()\n\n\n# ## AU recognition with mix training set\n\n# In[ ]:\n\n\nimport time\n\n\n# In[ ]:\n\n\n#get_ipython().system(' rm ./log.txt')\n#get_ipython().system(' rm -r ./tmp/*')\n\n\n# In[ ]:\n\n\nlog_file = open('./log.txt', 'a')\nprint(time.asctime().center(100, '#'), end='\\n', file=log_file, flush=True)\n\n\n# In[ ]:\n\n\nmodel_dir = './tmp'\nif not os.path.exists(model_dir):\n os.makedirs(model_dir)\n\n\n# In[ ]:\n\n\nfrom sklearn.model_selection import KFold\ncv = KFold(n_splits=3, random_state=2019)\nsubjects = df_all.subject.unique()\nfor i, (train_index, valid_index) in enumerate(cv.split(range(len(subjects)))):\n print((\"time%02d\"%i).center(100, '='), end='\\n', file=log_file, flush=True)\n train_index, valid_index = subjects[train_index], subjects[valid_index]\n train_df = df_all[df_all.subject.isin(values=train_index)]\n valid_df = df_all[df_all.subject.isin(values=valid_index)]\n train_ds = MyDataset(train_df, 'train_mix', img_dir, occ_dir, occ_type='one-second')\n valid_ds = MyDataset(valid_df, 'valid_clean', img_dir, occ_dir, occ_type='one-second')\n train_dl = DataLoader(train_ds, batch_size=16, num_workers=4, shuffle=True)\n valid_dl = DataLoader(valid_ds, batch_size=16, num_workers=4, shuffle=False)\n \n my_net = GACNN(num_AU=12).cuda()\n train_options = {}\n for val in my_net.vgg_features.parameters(): val.requires_grad = False\n train_options['optimizer'] = optim.Adam(filter(lambda p: p.requires_grad, my_net.parameters()), lr=1e-4, weight_decay=1e-6)\n train_options['loss'] = nn.BCEWithLogitsLoss().cuda()\n train_options['show'] = -1\n train_options['time'] = 'time%02d_'%i\n cur_best_eval = train_process(10, train_dl, valid_dl, my_net, train_options)\n\n\n# In[ ]:\n\n\nlog_file.close()\n\n\n# # visualize\n\n# In[ ]:\n\n\n0.58, 0.4864\n\n","sub_path":"ExperimentBP4D(GACNN)/GACNN.py","file_name":"GACNN.py","file_ext":"py","file_size_in_byte":15414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"316934775","text":"import pygame\n\nclass View:\n def __init__(self):\n pygame.init()\n self.view = \"start_screen\"\n size = width, height = 329, 249\n self.screen = pygame.display.set_mode(size)\n \n \n def get_event(self):\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n return \"quit\"\n else:\n return False\n\n def draw(self):\n if self.view == \"start_screen\":\n self.screen.fill((124, 124, 124))\n pygame.display.flip()\n","sub_path":"view/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"419128021","text":"#\n# @lc app=leetcode.cn id=35 lang=python3\n#\n# [35] 搜索插入位置\n#\nclass Solution:\n def searchInsert(self, nums, target):\n ## 逐个遍历\n # if target < nums[0]: return 0\n # for idx in range(len(nums)):\n # if nums[idx] == target:\n # return idx\n # elif nums[idx] > target:\n # return idx - 1\n\n ## 二分法查找\n min_idx = 0\n max_idx = len(nums) - 1\n while(min_idx <= max_idx):\n mid =min_idx + (max_idx - min_idx) // 2\n if nums[mid] == target:\n return mid\n elif nums[mid] < target:\n min_idx = mid + 1\n else:\n max_idx = mid - 1\n return min_idx\n\n\n\n \n\n","sub_path":"Leetcode/35.搜索插入位置.py","file_name":"35.搜索插入位置.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"403074039","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nchart = pd.read_csv('test_advanced.csv', sep=',')\n'''\n### Show Counts of Ethnicity\nlabels = ['White', 'Black', 'Hispanic', 'Asian']\nmen_means = chart['ethnicity'].value_counts()\nwidth = 0.35\nfig, ax = plt.subplots()\nax.bar(labels, men_means, width, label='Men')\nax.set_ylabel('Count')\nax.set_title('Counts by Ethnicity')\nax.legend()\n'''\nprint(chart['success_score'].value_counts())\n### Show Undergrad by Income\ntips = chart\nsns.scatterplot(x=\"success_score\", y=\"lawschool\", hue='ethnicity', data=tips)\n\n### Show Languages by Ethnicity\nsns.catplot(x=\"extradegrees\", y=\"income_bracket\", kind='box', data=tips)\n\n### Show Income by Ethnicity\nsns.catplot(x=\"ethnicity\", y=\"income_bracket\", kind='box', data=tips)\n\n### Show Lawschool by Success\nsns.catplot(x=\"success_score\", y=\"lawschool\", kind='box', data=tips)\n\n### Show Income by Success\nsns.catplot(x=\"success_score\", y=\"income_bracket\", kind='box', data=tips)\n\nplt.show()","sub_path":"Archive/Testing_Archive/test_advanced_obvious/analyze_input.py","file_name":"analyze_input.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"20999493","text":"from django.contrib import admin\nfrom django.urls import path, include\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom . import views\n\nurlpatterns = [\n path('dashboard/', views.account_dashboard, name=\"account_dashboard\"),\n path('dashboard/edit_profile', views.edit_profile, name=\"edit_profile\"),\n path('dashboard/orders/', views.dashboard_my_orders, name=\"get_my_orders\"),\n path('all/', views.all_users, name=\"all_users\"),\n path('register/', views.CustomRegistrationView, name=\"registration\"),\n path('ajax/add_friend/', views.add_friend, name=\"add_friend\"),\n path('ajax/cancel_friend/', views.cancel_friend, name=\"cancel_friend\"),\n path('ajax/accept_friend/', views.accept_friend, name=\"accept_friend\"),\n path('ajax/decline_friend/', views.decline_friend, name=\"decline_friend\"),\n path('ajax/remove_friend/', views.remove_friend, name=\"remove_friend\"),\n path('ajax/send_user_message/', views.send_user_message, name=\"send_user_message\"),\n] ","sub_path":"users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"144208306","text":"class Meal(object):\n def __init__(self, heading, time, menu):\n self.heading = heading\n self.time = time\n self.menu = menu\n \n def __str__(self):\n strToReturn = self.heading + '\\n' + self.time + '\\n'\n\n for line in self.menu:\n strToReturn += line + '\\n'\n\n return strToReturn\n","sub_path":"meal.py","file_name":"meal.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"48566559","text":"import pandas as pd\nimport numpy as np\nimport re\nimport glob\nimport math\nfrom math import log\n\n# Read the metadata file\ndfmeta = pd.read_csv(\"/home/poyraden/Josie18/Josie18_MetaData.csv\")\n\n# Path to all Josie18 simulation files\n\nallFiles = glob.glob(\"/home/poyraden/Josie18/Files/Si*/*.O3R\")\nlist_data = []\n\n#Some declarations\n\ncolumnString = \"Tact Tsim Pair Tair Tinlet IM TPint TPext PFcor I_Pump PO3 VMRO3 PO3_OPM VMRO3_OPM ADif_PO3S RDif_PO3S Z\"\ncolumnStr = columnString.split(\" \")\n\n\ncolumn_metaString = \"Year Sim ENSCI Team Code Flow IB1 Cor Sol Buf ADX\"\ncolumnMeta = column_metaString.split(\" \")\n\n#**********************************************\n# Main loop to merge all data sets\n#**********************************************\nfor filename in allFiles:\n file = open(filename,'r')\n # Get the participant information from the name of the file\n tmp_team = filename.split(\"/\")[6]\n header_team =( tmp_team.split(\"_\")[2]).split(\".\")[0]\n file.readline()\n file.readline()\n header_part = int(header_team)\n header_sim = int(file.readline().split()[2])\n file.readline()\n file.readline()\n header_PFunc = float(file.readline().split()[1])\n header_PFcor = float(file.readline().split()[1])\n file.readline()\n header_IB1 = float(file.readline().split()[1])\n \n df = pd.read_csv(filename, sep = \"\\t\", engine=\"python\", skiprows=12, names=columnStr)\n\n # Add the header information to the main df\n \n df = df.join(pd.DataFrame(\n [[header_part, header_sim, header_PFunc, header_PFcor, header_IB1 ]], \n index=df.index, \n columns=['Header_Team', 'Header_Sim', 'Header_PFunc', 'Header_PFcor', 'Header_IB1']\n ))\n # Get the index of the metadata that corresponds to this Simulation Number and Participant (Team)\n \n select_indicesTeam = list(np.where(dfmeta[\"Team\"] == df['Header_Team'][0]))[0]\n select_indicesSim = list(np.where(dfmeta[\"Sim\"] == df['Header_Sim'][0]))[0]\n common = [i for i in select_indicesTeam if i in select_indicesSim]\n index_common = common[0] \n\n ## The index of the metadata that has the information of this simulation = index_common\n # assign this row into a list\n \n list_md = dfmeta.iloc[index_common,:].tolist()\n #print(list_md)\n \n ## Add metadata to the main df\n df = df.join(pd.DataFrame(\n [list_md],\n index = df.index,\n columns=columnMeta\n ))\n \n # I think I need to add the total profile calculation \n # Calc total O3 \n \n dfpair_tmp = df.sort_values(by = 'Pair', ascending=False)\n dfpo3_tmp = df.sort_values(by = 'PO3', ascending=False)\n dfpo3opm_tmp = df.sort_values(by = 'PO3_OPM', ascending=False)\n \n dfpair = dfpair_tmp[dfpair_tmp.Pair >= 0 ]\n dfpair = dfpair_tmp[dfpair_tmp.PO3 > 0]\n dfpo3 = dfpo3_tmp[dfpo3_tmp.Pair >= 0 ]\n dfpo3 = dfpo3_tmp[dfpo3_tmp.PO3 > 0 ]\n dfpo3opm = dfpo3opm_tmp[dfpo3opm_tmp.Pair >= 0 ]\n dfpo3opm = dfpo3opm_tmp[dfpo3opm_tmp.PO3 > 0 ]\n \n \n ## the for loop is very slow :/\n O3_tot = 0.0\n O3_tot_opm = 0.0\n #idx=where(pres ge 0 and oz gt 0)\n for i in range(len(dfpair)-2):\n O3_tot = O3_tot + 3.9449 * (dfpo3.iloc[i]['PO3'] + dfpo3.iloc[i+1]['PO3'])* np.log(dfpair.iloc[i]['Pair']/dfpair.iloc[i+1]['Pair'])\n O3_tot_opm = O3_tot_opm + 3.9449 *(dfpo3opm.iloc[i]['PO3_OPM'] + dfpo3opm.iloc[i+1]['PO3_OPM'])* np.log(dfpair.iloc[i]['Pair']/dfpair.iloc[i+1]['Pair'])\n \n Adif = O3_tot - O3_tot_opm\n Rdif = 100.0 * (O3_tot - O3_tot_opm)/O3_tot_opm\n frac = O3_tot/O3_tot_opm\n \n ## now add these to the df\n print(\"tot O3 is\")\n print(O3_tot)\n df = df.join(pd.DataFrame(\n [[O3_tot, O3_tot_opm ,Adif , Rdif, frac ]], \n index=df.index, \n columns=['O3S', 'OPM', 'ADif', 'RDif', 'frac']\n ))\n \n \n \n list_data.append(df) \n # end of the allfiles loop #\n \n# Merging all the data files to df\n\ndf = pd.concat(list_data,ignore_index=True)\ndf.to_csv(\"/home/poyraden/Josie18/Josie18_Data.csv\")\n \n \n\n\n\n\n\n","sub_path":"Josie18_makeDF.py","file_name":"Josie18_makeDF.py","file_ext":"py","file_size_in_byte":4020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"65684636","text":"\"\"\"\nRoutes and views for the bottle application.\n\"\"\"\n\nfrom bottle import route, view, request, redirect, post\nfrom datetime import datetime\nfrom Connection import coll, games\nfrom bson import ObjectId\nimport random\nimport uuid\nfrom bottle import static_file\nimport os\nimport ast\nimport dis\nimport test\n\ndis.dis(test)\n\n@route('/')\n@route('/home')\n@view('index')\ndef home():\n return dict(\n hide=\"display: initial;\",\n year=datetime.now().year\n )\n\n\n@route('/Continue')\n@view('index')\ndef home():\n \n\n\n\n return dict(\n year=datetime.now().year\n )\n\n@route('/new')\n@view('game')\ndef newGame():\n\n uWarDeck = []\n rWarDeck = []\n\n userName = request.query.get('txtName')\n\n suits = coll.distinct(\"Suits\")\n rank = coll.distinct(\"Rank\")\n randDeck = []\n \n\n while len(randDeck) < 52: \n randRank = random.randint(0,len(rank) -1)\n randSuit = random.randint(0,len(suits) -1)\n card = [suits[randSuit],rank[randRank]] #create random card\n if len(randDeck) == 0:#first card so we just add it\n randDeck.append(card)\n else:\n cardMatch = False;\n for c in randDeck: #checks if card exists\n if c == card:\n cardMatch = True\n break\n if cardMatch == False:\n randDeck.append(card)\n\n\n splitDeck = split(randDeck, 26)\n UserDeck = splitDeck[0]\n RoboDeck = splitDeck[1]\n gameCode = uuid.uuid4().hex\n\n games.insert_one({ \"gameCode\": gameCode, \"userName\": userName, \"roboDeck\": RoboDeck, \"userDeck\":UserDeck })\n\n uWarDeck.append(UserDeck[0])\n rWarDeck.append(RoboDeck[0])\n\n return dict(\n userScore = 0,\n roboScore = 0,\n user =userName,\n code = gameCode,\n userCards = uWarDeck,\n roboCards = rWarDeck,\n year=datetime.now().year\n )\n\n\n@route('/gameOver/')\n@view('gameOver')\ndef gameOver(winner):\n\n return dict(\n year=datetime.now().year,\n winner = winner\n )\n\n\n@route('/game///')\n@view('game')\ndef playGame(ucard, robocard, gCode): \n\n\n\n uWarDeck = []\n rWarDeck = []\n\n #parse returned cards back into list objects\n rCard = ast.literal_eval(robocard)\n uCard = ast.literal_eval(ucard)\n\n #get last card in list val, this will handle if it is a war game or a single card\n rVal = CardValue(rCard[len(rCard) - 1])\n uVal = CardValue(uCard[len(uCard) - 1])\n\n #each user will always have the same ammount of cards on deck so we can just get the count from one of the decks\n onDeckCount = len(rCard)\n\n\n #get decks from database\n UserDeck = list(games.find({\"gameCode\":gCode},{\"userDeck\":1,\"_id\":0}))[0]['userDeck']\n userDeckLen = len(UserDeck)\n\n RoboDeck = list(games.find({\"gameCode\":gCode},{\"roboDeck\":1,\"_id\":0}))[0]['roboDeck']\n roboDeckLen = len(RoboDeck)\n\n if userDeckLen >= 52:\n redirect(\"/gameOver/User\")\n elif roboDeckLen >=52:\n redirect(\"/gameOver/Robo\") \n\n \n #whoever wins round gets cards, if both cards equal a war begins\n if uVal > rVal:\n for x in range(onDeckCount):\n #add won cards to user\n games.update({\"gameCode\":gCode },{\"$push\":{\"userDeck\":rCard[x]}})\n games.update({\"gameCode\":gCode },{\"$push\":{\"userDeck\":uCard[x]}})\n #remove lost cards from Robo, also move existing cards to rear\n if len(uCard) < 2 and uVal > rVal:\n games.update({\"gameCode\":gCode }, { \"$pop\": { \"roboDeck\": -1 } } )\n games.update({\"gameCode\":gCode }, { \"$pop\": { \"userDeck\": -1 } } )\n\n #set up next hand\n uWarDeck.append(UserDeck[1])\n rWarDeck.append(RoboDeck[1])\n\n elif uVal < rVal:\n for x in range(onDeckCount):\n games.update({\"gameCode\":gCode },{\"$push\":{\"roboDeck\":rCard[x]}})\n games.update({\"gameCode\":gCode },{\"$push\":{\"roboDeck\":uCard[x]}})\n #remove lost cards from User, also move existing cards to rear\n if len(rCard) <2 and uVal < rVal:\n games.update({\"gameCode\":gCode }, { \"$pop\": { \"userDeck\": -1 } } )\n games.update({\"gameCode\":gCode }, { \"$pop\": { \"roboDeck\": -1 } } )\n\n #set up next hand\n uWarDeck.append(UserDeck[1])\n rWarDeck.append(RoboDeck[1])\n \n else:\n #add existing cards to war game + 4 because final card matches\n for x in range(onDeckCount):\n uWarDeck.append(uCard[x])\n rWarDeck.append(rCard[x])\n for x in range(4):\n games.update({\"gameCode\":gCode }, { \"$pop\": { \"userDeck\": -1 } } )\n uWarDeck.append(list(games.find({\"gameCode\":gCode},{\"userDeck\":1,\"_id\":0}))[0]['userDeck'][0])\n games.update({\"gameCode\":gCode }, { \"$pop\": { \"roboDeck\": -1 } } )\n rWarDeck.append(list(games.find({\"gameCode\":gCode},{\"roboDeck\":1,\"_id\":0}))[0]['roboDeck'][0])\n \n \n \n UserDeck = list(games.find({\"gameCode\":gCode},{\"userDeck\":1,\"_id\":0}))[0]['userDeck']\n userDeckLen = len(UserDeck)\n\n RoboDeck = list(games.find({\"gameCode\":gCode},{\"roboDeck\":1,\"_id\":0}))[0]['roboDeck']\n roboDeckLen = len(RoboDeck)\n \n\n userName = games.distinct(\"userName\",{\"gameCode\":gCode})[0]\n\n\n return dict(\n userScore = userDeckLen,\n roboScore = roboDeckLen,\n user =userName,\n code = gCode,\n userCards = uWarDeck,\n roboCards = rWarDeck,\n year=datetime.now().year\n )\n\n\n@route('/static/')\ndef server_static(filepath):\n myPath = os.path.join(os.getcwd(), \"static\") #join current directory to static folder as a full path\n return static_file(filename, root=myPath)\n\ndef split(arr, size):\n arrs = []\n while len(arr) > size:\n pice = arr[:size]\n arrs.append(pice)\n arr = arr[size:]\n arrs.append(arr)\n return arrs\n\ndef CardValue(card):\n c = card[1]\n if c == \"K\" or c == \"J\" or c ==\"Q\":\n return 10\n elif c == \"A\":\n return 11\n else:\n return int(c)\n\n\n","sub_path":"WarCards/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":6144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"280136097","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Oct 14 20:59:19 2018\r\n\r\n@author: Administrator\r\n\"\"\"\r\n\r\nimport matplotlib.pyplot as plt\r\nnum=[1.2,3,2,7.2,12,4]\r\nnum1=[1,2,3,4,5,6]\r\nlist=['a','b','c','d','e','f']\r\n#plt.xkcd()\r\nplt.figure()\r\nplt.title('Bar')\r\nplt.barh(range(len(num)),num,color='r',tick_label=list,label='first')\r\nplt.barh(range(len(num1)),num1,color='b',label='second')\r\nplt.legend()\r\nplt.xlabel('X')\r\nplt.ylabel('Y')\r\n","sub_path":"matplotlib/matplotlib_5_barh.py","file_name":"matplotlib_5_barh.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"515202584","text":"\"\"\"\nModule of helper functions for fetching sentiment training data. \n\"\"\"\n\nfrom sumall_analysis_tools.stats.stat_functions import mode_from_str_list\nfrom sumall_analysis_tools.conf.mysql_conf import sentiment_mysql_conf, twitter_mysql_conf, instagram_mysql_conf\n\n\ndef get_manual_data_helper(mysql_conn, stmt):\n \"\"\"Generic helper for pulling down some item and its score list\n \n INPUTS:\n 1) stmt: a sql statement that generates a list of items and cooresponding manual labels\n \"\"\"\n xs = []\n ys = [] \n for row in mysql_conn.select_generator(stmt):\n xs.append(row[0])\n ys.append(mode_from_str_list(row[1]))\n assert(len(xs) == len(ys))\n return xs, ys\n\n\ndef get_joined_sentiments(mysql_conn, item_db, item_table, item_id_column, item_column, sent_db, sent_tbl):\n \"\"\"grabs items (can be anything like comments/tweets/arbitrary text/etc) and its manual labels.\n Function is used when items are in one database.table and the labels of those items, joined using an id, are in another. \n \n INPUTS:\n 0) database connection\n 1) item_db : database where the items are\n 2) item_table : table where the items are\n 3) item_id_column : the id column in the items table\n 4) item_column : the specific colum in the item table to grab\n 5) sent_db : database where manual labels are stored\n 6) sent_tbl : table where manual labels are stored for these items\n \n TABLE IS ASSUMED TO HAVE A score_list COLUMN. All tables in conf/sentiment currently are formatted this way. \n \"\"\" \n stmt = \"\"\"select t1.{item}, t2.score_list \n from {idb}.{itemtbl} t1 join {sdb}.{stbl} t2 on\n t1.{itemid} = t2.{itemid}\"\"\".format(idb = item_db, \n itemtbl = item_table,\n itemid = item_id_column,\n item = item_column,\n sdb = sent_db,\n stbl = sent_tbl)\n return get_manual_data_helper(mysql_conn, stmt) \n\n\ndef get_single_sentiments(mysql_conn, item_db, item_table, item_column):\n \"\"\"grabs items (can be anything like comments/tweets/arbitrary text/etc) and its manual labels.\n Function is used when items and their labels are in one database.table\n \n INPUTS:\n 1) item_db : database where the items are\n 2) item_table : table where the items are\n 3) item_column : the specific colum in the item table to grab\n \n TABLE IS ASSUMED TO HAVE A score_list COLUMN. All tables in conf/sentiment currently are formatted this way. \n \"\"\"\n stmt = \"\"\"select {item}, score_list \n from {idb}.{itemtbl}\"\"\".format(idb = item_db, \n itemtbl = item_table,\n item = item_column)\n return get_manual_data_helper(mysql_conn, stmt) \n\n\n\"\"\"\nSpecific Fetching Functions\n\"\"\"\n\ndef instagram_manual_data(mysql_conn):\n \"\"\"comments\"\"\"\n return get_joined_sentiments(mysql_conn, \n instagram_mysql_conf.INSTAGRAM_DATABASE, \n instagram_mysql_conf.INSTAGRAM_MEDIA_COMMENTS_TABLE, \n 'comment_id', \n 'text', \n sentiment_mysql_conf.SENTIMENT_DATABASE, \n sentiment_mysql_conf.SENTIMENT_INSTAGRAM_COMMENTS_TABLE)\n\ndef twitter_tweets_manual_data(mysql_conn):\n \"\"\"tweets only\"\"\"\n return get_joined_sentiments(mysql_conn, \n twitter_mysql_conf.TWITTER_DATABASE, \n twitter_mysql_conf.TWITTER_TWEETS_TABLE, \n 'tweet_id', \n 'text', \n sentiment_mysql_conf.SENTIMENT_DATABASE, \n sentiment_mysql_conf.SENTIMENT_TWITTER_TWEETS_TABLE)\n\ndef twitter_mentions_manual_data(mysql_conn):\n \"\"\"Mentions only\"\"\"\n return get_joined_sentiments(mysql_conn,\n twitter_mysql_conf.TWITTER_DATABASE, \n twitter_mysql_conf.TWITTER_MENTIONS_TABLE, \n 'mention_id', \n 'text', \n sentiment_mysql_conf.SENTIMENT_DATABASE, \n sentiment_mysql_conf.SENTIMENT_TWITTER_MENTIONS_TABLE)\n\ndef twitter_all_manual_data(mysql_conn):\n \"\"\"Mix tweets and mentions\"\"\"\n xs1, ys1 = twitter_tweets_manual_data(mysql_conn)\n xs2, ys2 = twitter_mentions_manual_data(mysql_conn)\n return xs1+xs2, ys1+ys2\n\n\ndef get_emojis(mysql_conn):\n \"\"\"gets the list of classified emojis\"\"\"\n return get_single_sentiments(mysql_conn,\n sentiment_mysql_conf.SENTIMENT_DATABASE, \n sentiment_mysql_conf.SENTIMENT_EMOJIS_TABLE, \n 'utf_8')\n\ndef get_mpqa(mysql_conn):\n \"\"\"gets the list of classified phrases\"\"\"\n return get_single_sentiments(mysql_conn,\n sentiment_mysql_conf.SENTIMENT_DATABASE, \n sentiment_mysql_conf.SENTIMENT_MPQA_TABLE, \n 'word')\n \n \n\n\"\"\"\nLogic Injection\n\"\"\"\n\ndef fetcher_name_to_function(function_name):\n \"\"\"This takes a string, function_name, and returns the function in this file with the same name. \n This is used so that a RESTful microservice can create machine learning objects from strings passed in with POST requests\n \n Whenever a new function is added to this file, please modify the below\n \n TODO: This can be cleaned up later from a case statement to using has_attr. \n \"\"\"\n if function_name == \"instagram_manual_data\":\n return instagram_manual_data\n elif function_name == \"twitter_tweets_manual_data\":\n return twitter_tweets_manual_data\n elif function_name == \"twitter_mentions_manual_data\":\n return twitter_mentions_manual_data\n elif function_name == \"twitter_all_manual_data\":\n return twitter_all_manual_data\n else:\n raise Exception(\"Unsupported fetcher function name.\")\n\n","sub_path":"sumall_analysis_tools/sentiment_analysis/training_data_fetching_functions.py","file_name":"training_data_fetching_functions.py","file_ext":"py","file_size_in_byte":6459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"59181210","text":"import re\nfrom unis import Runtime\nfrom unis.models import Node\n\nfrom lace.logging import trace\n\n\nclass FlangeError(Exception):\n pass\n\ndef diad(app, f):\n return lambda inst: app(f(inst[1]), f(inst[2]))\ndef monad(app, f):\n return lambda inst: app(f(inst[1]))\ndef nimp(msg):\n def _f():\n raise NotImplemented(msg)\n return _f\ndef recur(f):\n def _f(inst):\n result = [inst[0]]\n for arg in inst[1:]:\n result.append(f(arg))\n return tuple(result)\n return _f\n\n@trace.debug(\"utils\")\ndef build_dep_tree(program):\n def _find_deps(inst):\n if inst and isinstance(inst, tuple):\n if inst[0] == \"query\":\n return _find_deps(inst[3:])\n if inst[0] == \"var\":\n return [inst[1]]\n else:\n deps = []\n for v in inst[1:]:\n _new_deps = _find_deps(v)\n if _new_deps:\n deps.extend(_new_deps)\n return deps\n else:\n return []\n deps = {}\n env = {}\n for i, inst in enumerate(program):\n if inst[0] == \"let\":\n if inst[1] in deps:\n raise SyntaxError(\"{} cannot be rebound [line {}]\".format(inst[1], i))\n deps[inst[1]] = _find_deps(inst[2])\n env[inst[1]] = inst[2]\n \n return env, deps\n\n\n@trace.info(\"utils\")\ndef grammar(re_str, line, lines, handlers):\n groups = re.match(re_str, line[1])\n if not groups:\n raise SyntaxError(\"Bad Syntax [line {}] - {}\".format(*line))\n \n if groups.group(\"op\") in handlers:\n return handlers[groups.group(\"op\")](line, lines)\n else:\n return handlers[\"default\"](line, lines)\n \n\nclass _flange_rt(object):\n __runtime__ = None\n def __init__(self, source):\n if not self.__runtime__:\n if isinstance(source, Runtime):\n type(self).__runtime__ = source\n else:\n conf = {'runtime': {'services': ['unis.services.graph.UnisGrapher']},\n 'cache': {'preload': ['nodes', 'links']}}\n type(self).__runtime__ = Runtime(source, **conf)\n\n@trace.info(\"utils\")\ndef runtime(source=None):\n return _flange_rt(source).__runtime__\n","sub_path":"flange/utils/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"261584807","text":"import sys\nfrom collections import defaultdict\nfrom functools import reduce\nfrom reademptionlib.fasta import FastaParser\nimport pysam\n\n\nclass ReadAlignerStats(object):\n def __init__(self):\n self.fasta_parser = FastaParser()\n\n def count(self, read_alignment_result_bam_path, unaligned_reads_path):\n self._stats = {}\n self._count_aligned_reads_and_alignments(read_alignment_result_bam_path)\n self._count_unaligned_reads(unaligned_reads_path)\n return self._stats\n\n def _count_unaligned_reads(self, unaligned_read_paths):\n\n with open(unaligned_read_paths) as fasta_fh:\n self._stats[\"stats_total\"][\n \"no_of_unaligned_reads\"\n ] = self._count_fasta_entries(fasta_fh)\n\n def _count_fasta_entries(self, fasta_fh):\n return reduce(\n lambda x, y: x + 1, self.fasta_parser.entries(fasta_fh), 0\n )\n\n def _count_aligned_reads_and_alignments(\n self, read_alignment_result_bam_path\n ):\n bam = pysam.Samfile(read_alignment_result_bam_path)\n stats_per_ref = defaultdict(dict)\n no_of_hits_per_read_freq = {}\n for ref_id in bam.references:\n self._init_counting_dict(stats_per_ref, ref_id)\n for entry in bam.fetch():\n ref_id = bam.getrname(entry.tid)\n try:\n self._count_alignment(\n entry, ref_id, stats_per_ref, no_of_hits_per_read_freq\n )\n except KeyError:\n sys.stderr.write(\n \"SAM entry with unspecified reference found! Stoping\\n\"\n )\n sys.exit(2)\n self._stats[\"stats_per_reference\"] = stats_per_ref\n for ref_id, stats in stats_per_ref.items():\n stats_per_ref[ref_id][\n \"no_of_hits_per_read_and_freqs\"\n ] = self._calc_down_to_read(\n stats_per_ref[ref_id][\"no_of_hits_per_read_and_freqs\"]\n )\n self._stats[\"stats_total\"] = self._sum_countings(stats_per_ref)\n\n def _sum_countings(self, stats_per_ref):\n total_stats = {}\n for ref_id, stats in stats_per_ref.items():\n for attribute, value in stats.items():\n if type(value) is int or type(value) is float:\n total_stats.setdefault(attribute, 0)\n total_stats[attribute] += value\n elif type(value) is dict:\n total_stats.setdefault(attribute, {})\n for value_int, freq in value.items():\n total_stats[attribute].setdefault(value_int, 0)\n total_stats[attribute][value_int] += freq\n return total_stats\n\n def _calc_down_to_read(self, no_of_hits_per_read_freq):\n \"\"\"As the frequencies were determined via the alignments we need\n to normalized each frequency value down to the read by\n dividing the frequencig by the number of hits per read.\n \"\"\"\n return dict(\n (no_of_hits_per_read, freq / no_of_hits_per_read)\n for no_of_hits_per_read, freq in no_of_hits_per_read_freq.items()\n )\n\n def _init_counting_dict(self, stats_per_ref, ref_id):\n stats_per_ref[ref_id] = defaultdict(float)\n stats_per_ref[ref_id][\"no_of_alignments\"]\n stats_per_ref[ref_id][\"no_of_aligned_reads\"]\n stats_per_ref[ref_id][\"no_of_split_alignments\"]\n stats_per_ref[ref_id][\"no_of_uniquely_aligned_reads\"]\n stats_per_ref[ref_id][\"alignment_length_and_freqs\"] = defaultdict(int)\n stats_per_ref[ref_id][\"no_of_hits_per_read_and_freqs\"] = defaultdict(\n int\n )\n\n def _count_alignment(\n self, entry, ref_id, stats_per_ref, no_of_hits_per_read_freq\n ):\n entry_tags_dict = dict(entry.tags)\n no_of_hits = entry_tags_dict[\"NH\"]\n # Consider split reads\n\n number_of_split_alignments_within_this_SAM_record = float(\n entry_tags_dict.get(\"XH\", 1)\n )\n total_number_of_split_alignments_for_the_whole_read = float(\n entry_tags_dict.get(\"XJ\", 1)\n )\n proportion_of_total_split_alignments_of_the_whole_read_for_this_sam_record = (\n number_of_split_alignments_within_this_SAM_record\n / total_number_of_split_alignments_for_the_whole_read\n )\n if \"XH\" in entry_tags_dict:\n stats_per_ref[ref_id][\n \"no_of_split_alignments\"\n ] += proportion_of_total_split_alignments_of_the_whole_read_for_this_sam_record\n stats_per_ref[ref_id][\"no_of_hits_per_read_and_freqs\"][\n no_of_hits\n ] += (\n 1.0\n / (\n float(no_of_hits)\n * proportion_of_total_split_alignments_of_the_whole_read_for_this_sam_record\n )\n )\n stats_per_ref[ref_id][\n \"no_of_alignments\"\n ] += proportion_of_total_split_alignments_of_the_whole_read_for_this_sam_record\n stats_per_ref[ref_id][\"no_of_aligned_reads\"] += (\n proportion_of_total_split_alignments_of_the_whole_read_for_this_sam_record\n / (float(no_of_hits))\n )\n else:\n stats_per_ref[ref_id][\"no_of_alignments\"] += 1.0\n stats_per_ref[ref_id][\"no_of_aligned_reads\"] += 1.0 / (\n float(no_of_hits)\n )\n stats_per_ref[ref_id][\"no_of_hits_per_read_and_freqs\"][\n no_of_hits\n ] += proportion_of_total_split_alignments_of_the_whole_read_for_this_sam_record\n if no_of_hits == 1:\n stats_per_ref[ref_id][\"no_of_uniquely_aligned_reads\"] += (\n 1.0\n / proportion_of_total_split_alignments_of_the_whole_read_for_this_sam_record\n )\n stats_per_ref[ref_id][\"alignment_length_and_freqs\"][entry.alen] += 1\n","sub_path":"reademptionlib/readalignerstats.py","file_name":"readalignerstats.py","file_ext":"py","file_size_in_byte":5912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"227047117","text":"import cv2\nimport os\n\nimport re\nimport numpy as np\n\ndef load_radiograph(path):\n img = cv2.imread(path)\n return img\n\n\ndef load_landmarks(path):\n '''\n load_landmarks is a function that loads the landmarks out a txt file and put them in a 2D array\n :param path: the path the the landmarks file\n :return: landMarks: a 2D list of x and y coordinates in the [x , y] representation\n '''\n marks = []\n for p in path:\n lines = [int(float(line.rstrip('\\n'))) for line in open(p)]\n #x = [lines[i] for i in range(0, len(lines), 2)]\n #y = [lines[i] for i in range(1, len(lines), 2)]\n xy = [[lines[i], lines[i+1]] for i in range(0, len(lines)-1, 2)]\n marks.append(np.array(xy))\n\n return np.array(marks)\n\n\ndef display_landmarks(name, img, landmarks, mean=None):\n '''\n displays the landmarks on top of the images\n :param name:\n :param img:\n :param landmarks:\n :return:\n '''\n for tooth in landmarks:\n point = tuple([int(tooth[0]), int(tooth[1])])\n cv2.circle(img, point, 4, (0, 0, 255), -1)\n if mean is not None:\n for m in mean:\n point = tuple([int(m[0]), int(m[1])])\n cv2.circle(img, point, 4, (0, 255, 0), -1)\n cv2.namedWindow(name + ' Landmarks', cv2.WINDOW_NORMAL)\n cv2.resizeWindow(name + ' Landmarks', 600, 600)\n cv2.imshow(name + ' Landmarks', img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n\ndef prepare_datapath():\n '''\n This function prepares the datapath\n :return: This functions returns the paths to the patient cases of the landmarks, radiographs and segmenations\n '''\n file = os.path.dirname(os.path.realpath(__file__))\n dir_landmarks = os.path.join(file, \"../res/_Data/Landmarks/original\")\n dir_radiographs = os.path.join(file, \"../res/_Data/Radiographs\")\n dir_segmentations = os.path.join(file, \"../res/_Data/Segmentations\")\n\n files_landmarks_tmp = [f for f in os.listdir(dir_landmarks)]\n files_radiographs = [f for f in os.listdir(dir_radiographs)]\n files_segmentations = [f for f in os.listdir(dir_segmentations)]\n\n files_landmarks_short = list(sorted(set([f.split('-')[0] for f in files_landmarks_tmp])))\n path_landmarks = []\n for f2 in files_landmarks_short:\n tmp = [f1 for f1 in files_landmarks_tmp if re.match(f2, f1)]\n path_landmarks.append([os.path.join(dir_landmarks, f) for f in tmp])\n\n path_radiographs = [os.path.join(dir_radiographs, f) for f in files_radiographs]\n path_segmentations = [os.path.join(dir_segmentations, f) for f in files_segmentations]\n\n return path_landmarks, path_radiographs, path_segmentations\n\n\ndef load():\n '''\n Load the images and the corresponding landmarks\n every cases has 8 tooths of 80 points\n :return: X - the images, landmarks - the landmarks in two n representation\n '''\n path_landmarks, path_radiographs, path_segmentations = prepare_datapath()\n X = [load_radiograph(f) for f in path_radiographs]\n landmarks = [load_landmarks(f) for f in path_landmarks]\n return X, landmarks\n\n\ndef load_tooths():\n '''\n Load the images and the corresponding landmarks\n there is no distinction between the tooths of a case - (112, 80)\n :return: X - the images, landmarks - the landmarks\n '''\n X, landmarks = load()\n new_landsmarks = [item for sublist in landmarks for item in sublist]\n return X , np.array(new_landsmarks)\n\nif __name__ == \"__main__\":\n path_landmarks, path_radiographs, path_segmentations = prepare_datapath()\n X = [load_radiograph(f) for f in path_radiographs]\n landmarks = [load_landmarks(f) for f in path_landmarks]\n\n # display markers of case 1\n display_landmarks('case 1', X[3], landmarks[3])\n load_tooths()\n","sub_path":"IncisorSegmentation/incisorSegmentation/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":3739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"7351187","text":"def test_get_all_planets_with_no_records(client):\n # Act\n response = client.get(\"/planets\")\n response_body = response.get_json()\n\n # Assert\n assert response.status_code == 200\n assert response_body == []\n\ndef test_get_one_planet(client,two_saved_planets):\n # Act\n response = client.get(\"/planets/1\")\n response_body = response.get_json()\n\n # Assert\n assert response.status_code == 200\n assert response_body == {\n \"id\": 1,\n \"name\": \"Mars\",\n \"description\": \"Red Planet\"\n }\n\ndef test_planet_no_data(client):\n #Act\n response=client.get(\"/planets/9999\")\n response_body=response.get_json()\n #Assert\n assert response.status_code == 404\n assert response_body == None\n\ndef test_get_planets(client,two_saved_planets):\n #Act\n response=client.get(\"/planets\")\n response_body=response.get_json()\n #Assert\n assert response.status_code == 200\n assert len(response_body)== 2\n\ndef test_post_planets(client):\n response=client.post(\"/planets\",json={\"name\":\"Jupiter\", \"description\": \"green\"})\n response_body=response.get_data().decode('utf-8')\n print(response_body)\n #Assert\n assert response.status_code == 201\n assert response_body== \"Planet Jupiter successfully created\"","sub_path":"tests/test_routes.py","file_name":"test_routes.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"565542324","text":"#!/usr/bin/env python3\n# encoding: utf-8\n\nfrom urllib.request import urlopen\nfrom urllib.error import HTTPError\nfrom bs4 import BeautifulSoup\nimport re\n\nurls = ('http://wf.hzau.edu.cn/list.asp?classid=52', 'http://wf.hzau.edu.cn/list.asp?classid=113',\n 'http://wf.hzau.edu.cn/list.asp?classid=53', 'http://wf.hzau.edu.cn/list.asp?classid=54', 'http://wf.hzau.edu.cn/list.asp?classid=55')\n\nfor url in urls:\n link = urlopen(url)\n\n links = []\n bs = BeautifulSoup(link, \"lxml\")\n links = bs.find(\"td\", {\"class\": \"news\"}).findAll(\"a\")\n\n for i in links:\n uri = \"http://wf.hzau.edu.cn/\" + i.attrs['href'].lstrip('.')\n try:\n html = urlopen(uri)\n except HTTPError as e:\n print(\"not found\")\n else:\n bs_obj = BeautifulSoup(html.read(), \"lxml\")\n try:\n b = bs_obj.find(text=re.compile(\n r'[A-Za-z0-9\\._+]+@[A-Za-z0-9\\._+]'))\n a = bs_obj.find('td', {'class': 'tittlebg'})\n except AttributeError:\n pass\n else:\n print(a.get_text())\n print(b)\n print('')\n","sub_path":"wenfa.py","file_name":"wenfa.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"278169812","text":"from django.conf.urls import include, patterns, url\n\nimport amo\nfrom apps.editors.views import queue_viewing, review_viewing\nfrom mkt.receipts.urls import receipt_patterns\nfrom mkt.reviewers.api import ReviewersSearchView\nfrom . import api, views, views_themes\n\n\n# All URLs under /reviewers/.\nurl_patterns = patterns('',\n url(r'^apps/$', views.home, name='reviewers.home'),\n url(r'^$', views.route_reviewer, name='reviewers'),\n url(r'^apps/queue/$', views.queue_apps,\n name='reviewers.apps.queue_pending'),\n url(r'^apps/queue/region/(?P[^ /]+)?$', views.queue_region,\n name='reviewers.apps.queue_region'),\n url(r'^apps/queue/rereview/$', views.queue_rereview,\n name='reviewers.apps.queue_rereview'),\n url(r'^apps/queue/updates/$', views.queue_updates,\n name='reviewers.apps.queue_updates'),\n url(r'^apps/queue/escalated/$', views.queue_escalated,\n name='reviewers.apps.queue_escalated'),\n url(r'^apps/queue/moderated/$', views.queue_moderated,\n name='reviewers.apps.queue_moderated'),\n url(r'^apps/queue/device/$', views.queue_device,\n name='reviewers.apps.queue_device'),\n url(r'^apps/review/%s$' % amo.APP_SLUG, views.app_review,\n name='reviewers.apps.review'),\n url(r'^apps/review/%s/manifest$' % amo.APP_SLUG, views.app_view_manifest,\n name='reviewers.apps.review.manifest'),\n url(r'^apps/review/attachment/(\\d+)$', views.attachment,\n name='reviewers.apps.review.attachment'),\n url(r'^apps/review/%s/abuse$' % amo.APP_SLUG, views.app_abuse,\n name='reviewers.apps.review.abuse'),\n url(r'^apps/logs$', views.logs, name='reviewers.apps.logs'),\n url(r'^apps/motd$', views.motd, name='reviewers.apps.motd'),\n url(r'^queue_viewing$', queue_viewing, name='editors.queue_viewing'),\n url(r'^review_viewing$', review_viewing, name='editors.review_viewing'),\n url(r'^apps/reviewing$', views.apps_reviewing,\n name='reviewers.apps.apps_reviewing'),\n\n url('^themes$', views_themes.home,\n name='reviewers.themes.home'),\n url('^themes/pending$', views_themes.themes_list,\n name='reviewers.themes.list'),\n url('^themes/flagged$', views_themes.themes_list,\n name='reviewers.themes.list_flagged',\n kwargs={'flagged': True}),\n url('^themes/updates$', views_themes.themes_list,\n name='reviewers.themes.list_rereview',\n kwargs={'rereview': True}),\n url('^themes/queue/$', views_themes.themes_queue,\n name='reviewers.themes.queue_themes'),\n url('^themes/queue/flagged$', views_themes.themes_queue_flagged,\n name='reviewers.themes.queue_flagged'),\n url('^themes/queue/updates$', views_themes.themes_queue_rereview,\n name='reviewers.themes.queue_rereview'),\n url('^themes/queue/commit$', views_themes.themes_commit,\n name='reviewers.themes.commit'),\n url('^themes/queue/single/(?P[^ /]+)$', views_themes.themes_single,\n name='reviewers.themes.single'),\n url('^themes/history/(?P[^ /]+)?$',\n views_themes.themes_history, name='reviewers.themes.history'),\n url(r'^themes/logs$', views_themes.themes_logs,\n name='reviewers.themes.logs'),\n url('^themes/release$', views_themes.release_locks,\n name='reviewers.themes.release_locks'),\n url('^themes/logs/deleted/$', views_themes.deleted_themes,\n name='reviewers.themes.deleted'),\n url('^themes/search/$', views_themes.themes_search,\n name='reviewers.themes.search'),\n\n url(r'^receipt/', include(receipt_patterns)),\n url(r'^%s/(?P\\d+)/mini-manifest$' % amo.APP_SLUG,\n views.mini_manifest, name='reviewers.mini_manifest'),\n url(r'^signed/%s/(?P\\d+)$' % amo.APP_SLUG,\n views.get_signed_packaged, name='reviewers.signed'),\n\n url(r'''^performance/(?P[^/<>\"']+)?$''', views.performance,\n name='reviewers.performance'),\n url(r'^leaderboard/$', views.leaderboard, name='reviewers.leaderboard'),\n)\n\napi_patterns = patterns('',\n url('^reviewers/search', ReviewersSearchView.as_view(),\n name='reviewers-search-api'),\n url(r'^reviewers/app/(?P[^/<>\"\\']+)/approve/(?P[^ /]+)?$',\n api.ApproveRegion.as_view(), name='approve-region'),\n url(r'^reviewers/reviewing', api.ReviewingView.as_view(),\n name='reviewing-list'),\n url('^reviewers/(?P[\\w-]+)/review/(?P\\d+)/translate'\n '/(?P[a-z]{2}(-[A-Z]{2})?)$',\n views.review_translate,\n name='reviewers.review_translate'),\n url(r'^reviewers/app/(?P[^/<>\"\\']+)/token$',\n api.GenerateToken.as_view(), name='generate-reviewer-token'),\n)\n","sub_path":"mkt/reviewers/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":4688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"291371767","text":"import numpy as np \r\nimport matplotlib.pyplot as plt \r\nfrom mpl_toolkits.mplot3d import Axes3D\r\n\r\nfig = plt.figure()\r\nax = Axes3D(fig)\r\nX = np.arange(-4,4,0.25)\r\nY = np.arange(-4,4,0.25)\r\nX,Y = np.meshgrid(X,Y)\r\n# R只是将二者平方和,开方了\r\nR = np.sqrt(X ** 2 + Y ** 2)\r\nZ = np.sin(R)\r\n#绘制3D热图表面\r\nax.plot_surface(X,Y,Z,rstride=1,cstride=1,cmap=plt.get_cmap(\"rainbow\"))\r\n#绘制等高线\r\nax.contourf(X,Y,Z,zdir=\"z\",offset=-1.5,cmap=plt.get_cmap(\"rainbow\"))\r\n#在z轴方向压缩图的大小\r\nax.set_zlim(-2,2)\r\n\r\nplt.show()","sub_path":"3D_demo.py","file_name":"3D_demo.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"180452821","text":"''' Advent of Code 2018\n Day 3: No Matter How You Slice It\n https://adventofcode.com/2018/day/3\n'''\nimport os\nimport re\n\nfrom collections import defaultdict\n\n\ndef parse_claim(claim_string):\n \"\"\" Parse the claim string and return its value.\n Solved with a simple regex\n \"\"\"\n id, x, y, width, height = map(int, re.findall(r'\\d+', claim_string))\n return id, x, y, width, height\n\n\ndef get_coords(x, y, width, height):\n \"\"\" Returns the claimed coordinates(inches) for\n the given claim data\n \"\"\"\n # walk through square and return all coordinates\n for x_coord in range(width):\n for y_coord in range(height):\n yield (x + x_coord, y + y_coord)\n\n\ndef part_one():\n \"\"\" \n \"\"\"\n input_file = open(os.path.join(\n os.path.dirname(__file__), 'input'), 'r')\n claimed_inches_counts = defaultdict(int)\n for claim in input_file.readlines():\n _, x, y, width, height = parse_claim(claim)\n for coord in get_coords(x, y, width, height):\n claimed_inches_counts[coord] += 1\n overlap_count = 0\n for value in claimed_inches_counts.values():\n if value > 1:\n overlap_count += 1\n return overlap_count\n\n\ndef part_two():\n \"\"\"\n \"\"\"\n input_file = open(os.path.join(\n os.path.dirname(__file__), 'input'), 'r')\n claimed_inches_counts = defaultdict(int)\n # Set with all claims to later subtract the overlapping ones from\n all_claims = set()\n overlapped_claims = set()\n for claim in input_file.readlines():\n claim_id, x, y, width, height = parse_claim(claim)\n # all_claims.add(claim_id)\n for coord in get_coords(x, y, width, height):\n claimed_inches_counts[coord] += 1\n # if claimed_inches_counts[coord] > 1:\n # overlapped_claims.add(claim_id)\n input_file.seek(0)\n for claim in input_file.readlines():\n claim_id, x, y, width, height = parse_claim(claim)\n all_claims.add(claim_id)\n for coord in get_coords(x, y, width, height):\n if claimed_inches_counts[coord] > 1:\n overlapped_claims.add(claim_id)\n return (all_claims - overlapped_claims)\n\n\ndef main():\n print(\"Solution for part one: {}\".format(part_one()))\n print(\"Solution for part two: {}\".format(part_two()))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"advent-of-code/2018/day03/day03.py","file_name":"day03.py","file_ext":"py","file_size_in_byte":2349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"472539402","text":"# Copyright 2020 The Trieste Contributors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom typing import List\n\nimport numpy.testing as npt\nimport numpy as np\nimport pytest\nimport tensorflow as tf\n\nfrom trieste.observer import map_is_finite, filter_finite\n\n\ndef _nan_at_origin(t: tf.Tensor) -> tf.Tensor:\n is_at_origin = tf.reduce_all(t == [[0., 0.]], axis=-1, keepdims=True)\n sums = tf.reduce_sum(t, axis=-1, keepdims=True)\n return tf.where(is_at_origin, tf.constant([[np.nan]]), sums)\n\n\ndef test_filter_finite() -> None:\n ok_query_points = [[-1., 0.], [1., 0.], [0., 2.], [1., 3.]]\n query_points = tf.constant([[0., 0.]] + ok_query_points)\n finite_values = filter_finite(query_points, _nan_at_origin(query_points))\n\n npt.assert_array_almost_equal(finite_values.query_points, ok_query_points)\n npt.assert_array_almost_equal(finite_values.observations, [[-1.], [1.], [2.], [4.]])\n\n\n@pytest.mark.parametrize('qp_shape, obs_shape', [\n ([3, 4], [3, 2]), # observations not N x 1\n ([3, 4], [4, 1]), # different leading dims\n ([3], [3, 1]), # query_points missing a dimension\n ([3, 4, 2], [3, 1]), # query_points have too many dimensions\n])\ndef test_filter_finite_raises_for_invalid_shapes(qp_shape: List[int], obs_shape: List[int]) -> None:\n with pytest.raises(ValueError):\n filter_finite(tf.ones(qp_shape), tf.ones(obs_shape))\n\n\ndef test_map_is_finite() -> None:\n query_points = tf.constant([[0., 0.]] + [[-1., 0.], [1., 0.], [0., 2.], [1., 3.]])\n is_finite = map_is_finite(query_points, _nan_at_origin(query_points))\n\n npt.assert_array_almost_equal(is_finite.query_points, query_points)\n npt.assert_array_almost_equal(is_finite.observations, [[0.], [1.], [1.], [1.], [1.]])\n","sub_path":"tests/unit/test_observer.py","file_name":"test_observer.py","file_ext":"py","file_size_in_byte":2236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"366985010","text":"\"\"\"\n Parkd function.\n -- kandasamy@cs.cmu.edu\n\"\"\"\n\n# pylint: disable=invalid-name\n\nimport numpy as np\n\ndef sub_park_1(x):\n \"\"\" Computes the park function \"\"\"\n x1 = x[0]\n x2 = x[1]\n x3 = x[2]\n x4 = x[3]\n ret = (2.0/3.0) * np.exp(x1 + x2) - x4*np.sin(x3) + x3\n return ret\n\ndef sub_park_2(x):\n \"\"\" Computes the park function \"\"\"\n x1 = x[0]\n x2 = x[1]\n x3 = x[2]\n x4 = x[3]\n ret = (2.0/3.0) * np.exp(x1 + 2*x2) - x4*np.sin(x3) + x3\n return ret\n\ndef sub_park_3(x):\n \"\"\" Computes park function \"\"\"\n x1 = x[0]\n x2 = x[1]\n x3 = x[2]\n x4 = x[3]\n ret = (2.5/3.0) * np.exp(2*x1 + x2) - x4*np.sin(x3) + x3\n return ret\n\ndef sub_park_4(x):\n \"\"\" Computes park function \"\"\"\n x1 = x[0]\n x2 = x[1]\n x3 = x[2]\n x4 = x[3]\n ret = (1.7/3.0) * np.exp(1.3*x1 + x2) - x4*np.sin(1.1*x3) + x3\n return ret\n\ndef park2_4_z(z, x):\n \"\"\" Computes the Parkd function. \"\"\"\n y1 = x[0][0]\n y2 = x[0][1]\n chooser = x[1]\n y3 = (x[2] - 103.0) / 91.0\n y4 = x[3] + 10.0\n x = [y1, y2, y3, y4]\n if chooser == 'rabbit':\n ret = sub_park_1(x)\n elif chooser == 'dog':\n ret = sub_park_2(x)\n elif chooser == 'gerbil':\n ret = sub_park_3(x)\n elif chooser in ['hamster', 'ferret']:\n ret = sub_park_4(x)\n return ret * np.exp(z - 1)\n\ndef park2_4(x):\n \"\"\" Computes the Parkd function. \"\"\"\n return park2_4_z(0.93242, x)\n\n# Write a function like this called obj.\ndef objective(x):\n \"\"\" Objective. \"\"\"\n return park2_4(x)\n\n\ndef main(x):\n \"\"\" main function. \"\"\"\n return park2_4(x)\n\n","sub_path":"examples/synthetic/park2_4/park2_4.py","file_name":"park2_4.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"221424721","text":"import time\nimport requests\nimport json\nimport datetime\n\nfrom django.conf import settings\nfrom django.http import HttpResponse\nfrom syllatokens.models import ServiceToken\nfrom django.views.decorators.csrf import csrf_exempt\nfrom syllatokens.utils import verify_token\nfrom django.http import JsonResponse\n\n\n@csrf_exempt\ndef exchange_google_code(request):\n google_client_id = settings.GOOGLE_CLIENT_ID\n google_client_secret = settings.GOOGLE_CLIENT_SECRET\n \n user = verify_token(request)\n if not user:\n return HttpResponse(status=403)\n \n body_in = json.loads(request.body.decode(\"utf-8\"))\n \n headers = {\n \"content-type\": \"application/json\" \n }\n body_google_req = {\n \"code\": body_in[\"code\"],\n \"client_id\": google_client_id,\n \"client_secret\": google_client_secret,\n \"redirect_uri\": \"postmessage\", # I don't why but this has to be postmessage\n \"grant_type\": \"authorization_code\"\n }\n google_response = requests.post(\"https://www.googleapis.com/oauth2/v4/token\", json=body_google_req, headers=headers)\n print(\"GOOGLE RESP: \", google_response.text)\n body_google_resp = json.loads(google_response.text)\n if \"refresh_token\" in body_google_resp:\n exp_date = datetime.datetime.utcnow() + datetime.timedelta(seconds = body_google_resp[\"expires_in\"])\n ServiceToken.objects.create(access_token=body_google_resp[\"access_token\"],\n refresh_token=body_google_resp[\"refresh_token\"],\n provider=\"google\",\n expiration_date=exp_date,\n user_id=user.id)\n return JsonResponse({'idToken': body_google_resp[\"id_token\"], \"accessToken\": body_google_resp[\"access_token\"]})\n\n\n@csrf_exempt\ndef reassign_google_token(request):\n user = verify_token(request)\n if not user:\n return HttpResponse(status=403)\n \n body_in = json.loads(request.body.decode(\"utf-8\"))\n access_token = body_in[\"accessToken\"]\n print(\"Access token: \", access_token)\n entries = ServiceToken.objects.filter(access_token=access_token)\n if len(entries) == 1:\n exp_date = entries[0].expiration_date.timestamp()\n if exp_date > time.time():\n entries[0].user_id = user.id\n entries[0].save()\n return HttpResponse(status=200)\n return HttpResponse(status=404)\n","sub_path":"syllashare/syllatokens/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"76666404","text":"#! /www/data/testsite/venv/bin/python3 -u\n\nimport requests\nimport random\nimport time\nimport argparse\n\nfrom pathlib import Path\nfrom datetime import datetime\n\n__sites__ = [\n \"http://habrahabr.ru/\",\n \"http://ain.ua/\",\n \"http://geektimes.ru/\",\n \"http://univ.kiev.ua/\",\n \"http://maps.google.com/\",\n 'http://uk.wikipedia.org/',\n 'http://vk.com/',\n 'http://drive.google.com/',\n 'http://mail.google.com/',\n 'http://rutracker.org/'\n]\n\n__users__ = [\n 'Boris',\n 'Ivan',\n 'Vladimir',\n 'Michail',\n 'Victor',\n 'stalker_1997',\n 'J|_Rycckuu',\n 'SexyJunkie69',\n 'AND_HIS_NAME_IS',\n 'JOHN_CENA'\n]\n\n__first_test_url__ = 'http://www.google.com.ua/'\n# More constants at the end of the file\n\n\ndef main():\n print()\n try:\n print('Going to {}'.format(__first_test_url__))\n r = requests.get(__first_test_url__, proxies=__proxies__)\n except requests.TooManyRedirects as e:\n print(e)\n print('Squid is blocking us and we can\\'t get to the redirect page')\n print('Check squid access logs')\n raise\n except requests.ConnectionError:\n print('Can\\'t connect to squid')\n raise\n\n if r.status_code == 200:\n if r.url != __first_test_url__:\n if r.url == __login_page_addr__:\n print('Redirected to the login page')\n\n if __user__ is not None:\n user = __user__\n else:\n user = random.choice(__users__)\n\n n = __users__.index(user) + 1\n\n login_success = initiate_login(user, n)\n if login_success:\n do_stuff(login_success)\n else:\n print('Redirected to {}'.format(r.url))\n print('Which is not a login page')\n else:\n print('Watching {}'.format(r.url))\n print('Passed proxy')\n else:\n print('Connection error')\n print(r.status_code)\n\n if r.status_code >= 400:\n dump_error_page(r, 'logout_post')\n\n\ndef do_stuff(session_data):\n print()\n last_knock = time.time()\n for i in range(__pages_to_watch__):\n if (time.time() - last_knock) > 60:\n print('Time has come to knock on server\\'s door')\n knock(session_data)\n last_knock = time.time()\n\n time.sleep(__timeout__)\n site = random.choice(__sites__)\n print('Going to {}'.format(site))\n try:\n page = requests.get(site, cookies=session_data, proxies=__proxies__)\n print('Watching {}'.format(page.url))\n except Exception as e:\n print('Error')\n print(e)\n print(e.args)\n break\n\n logout_using_session(session_data)\n\ndef knock(session_data):\n print()\n if session_data is None:\n print('No session data to knock')\n return\n r = requests.post(__door_addr__,\n cookies=session_data,\n proxies=__proxies__,\n data={'csrfmiddlewaretoken': session_data['csrftoken']})\n\n if r.status_code == 200:\n if 'application/json' in r.headers['content-type']:\n if 'result' not in r.json().keys():\n print('Malformed JSON in result')\n print(r.json())\n elif r.json()['result'] == 'At home':\n print('Server is at home')\n else:\n print('Something went wrong while knocking')\n print(r.json())\n else:\n print('Result is not JSON, dumping')\n dump_error_page(r, 'knock')\n else:\n print('Knock POST error')\n print(r.status_code)\n\n dump_error_page(r, 'knock')\n\n\ndef logout_using_session(session_data):\n print()\n if session_data is None:\n print('No session data to logout')\n return\n r = requests.post(__logout_page_addr__,\n cookies=session_data,\n proxies=__proxies__,\n data={'csrfmiddlewaretoken': session_data['csrftoken']})\n\n if r.status_code == 200:\n print('Logout POST successful')\n if 'Log out successful' in r.text:\n print('Logout successful')\n else:\n print('Something went wrong during logout')\n print('Logout page is {}'.format(r.url))\n print('And should be {}'.format(__logout_page_addr__))\n print('Is this OK?')\n else:\n print('Log out POST error')\n print(r.status_code)\n\n if r.status_code >= 400:\n dump_error_page(r, 'logout_post')\n\n\ndef initiate_login(username, password):\n login_page = requests.get(__login_page_addr__, proxies=__proxies__)\n csrf = login_page.cookies['csrftoken']\n\n print('Login as {}'.format(username))\n r = requests.post(__login_page_addr__,\n data={'csrfmiddlewaretoken': csrf,\n 'username': username,\n 'password': password},\n headers={'X-CSRFToken': csrf},\n cookies={'csrftoken': csrf},\n proxies=__proxies__)\n\n if r.status_code == 200:\n print('Login POST successful')\n if 'successfully logged in' in r.text:\n print('Login successful')\n session = {'sessionid': r.cookies['sessionid'],\n 'csrftoken': r.cookies['csrftoken']}\n\n return session\n\n elif 'password were incorrect' in r.text:\n print('Wrong username/password')\n elif r.status_code == 403:\n print('Can not login. CSRF token expired?')\n print(r.status_code)\n else:\n print('Login POST error')\n print(r.status_code)\n\n if r.status_code >= 400:\n dump_error_page(r, 'login_post')\n\n\ndef initiate_logout(username, password):\n logout_using_session(initiate_login(username, password))\n\ndef dump_error_page(r, arg):\n er = Path('error_dumps')\n if not er.exists():\n er.mkdir()\n\n time = datetime.now().strftime('%y_%m_%d_%H_%M_%S')\n fs = er / ('error_{}_{}_{}.html'.format(arg, r.status_code, time))\n\n with fs.open(mode='wb') as fd:\n for chunk in r.iter_content(256):\n fd.write(chunk)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\n ('Auth page test script. Example arguments:\\n'\n 'http://10.25.5.2 3128 80 --pages 5 //watch 5 pages as a random user\\n'\n 'http://10.25.5.2 3128 80 --pages 0 --name Boris //test for access, login and logout\\n'\n 'http://10.25.5.2 3128 80 --name Boris //login and logout'),\n formatter_class=argparse.RawDescriptionHelpFormatter)\n parser.add_argument('proxy', help='Proxy server http address.')\n parser.add_argument('proxy_port', help='Squid port on proxy server.')\n parser.add_argument('http_port', help='Port of http server that serves login page on proxy server.')\n parser.add_argument('--timeout', help='Fixed timeout between requests in seconds. Random by default', type=int)\n parser.add_argument('--name', help='Perform actions using specified user name', type=str)\n group = parser.add_mutually_exclusive_group()\n group.add_argument('--pages', help='Number of pages for bot to watch.', type=int,)\n group.add_argument('--knock', help='Just login and knock on server\\'s door', action='store_true')\n args = parser.parse_args()\n\n __login_page_serv__ = args.proxy\n if __login_page_serv__[-1] == '/':\n __login_page_serv__ = __login_page_serv__[:-1]\n\n __proxies__ = {'http': '{}:{}'.format(__login_page_serv__, args.proxy_port)}\n print(\"Using proxy at {}\".format(__proxies__[\"http\"]))\n\n __http_port__ = args.http_port\n\n base = '{}{}/'.format(__login_page_serv__, (':'+__http_port__) if __http_port__ != '80' else '')\n __login_page_addr__ = base + 'login_page/'\n __logout_page_addr__ = __login_page_addr__ + 'logout/'\n __door_addr__ = __login_page_addr__ + 'door'\n print('Expecting login page address to be: {}'.format(__login_page_addr__))\n\n __user__ = None\n if args.name is not None:\n if args.name not in __users__:\n print('Name {} is not available'.format(args.name))\n exit()\n else:\n __user__ = args.name\n\n __timeout__ = args.timeout if args.timeout is not None else random.randint(3, 10)\n\n if args.knock:\n d = initiate_login(__user__, __users__.index(__user__) + 1)\n knock(d)\n logout_using_session(d)\n else:\n if args.pages is not None:\n __pages_to_watch__ = args.pages\n main()\n else:\n initiate_logout(__user__, __users__.index(__user__) + 1)\n","sub_path":"utils/dummy.py","file_name":"dummy.py","file_ext":"py","file_size_in_byte":8707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"318771566","text":"import copy\n\nimport gym\nfrom stable_baselines3 import SAC\nfrom m_sac import MunchausenSAC\n\nfrom make_env import make_env\nfrom copy import deepcopy\nimport time\n\nenv = make_env(\"simple_no_fancy_init\")\n\nSAC_model = SAC.load(\"trained_agents/SAC_bps_no_rel\", env=env)\nM_SAC_model = MunchausenSAC.load(\"trained_agents/Munchausen_SAC_bps_no_rel\", env=env)\n\n\nobs = env.reset()\nm_obs = obs\nm_env = deepcopy(env)\n\ntemp_env = deepcopy(env)\ntemp_obs = obs\nm_temp_env = deepcopy(env)\nm_temp_obs = obs\n\n\ni = 0\n\nnb_success = 0\ncounter = 0\naverage_timesteps = 0\ndone = 0\n\nm_nb_success = 0\nm_counter = 0\nm_average_timesteps = 0\nm_done = 0\n\ncommon_successes = 0\nis_deterministic = True\nwhile i < 10000:\n while done == 0:\n counter += 1\n action, _state = SAC_model.predict(obs, deterministic=is_deterministic)\n obs, reward, done, info = env.step(action)\n\n while m_done == 0:\n m_counter += 1\n m_action, m_state = M_SAC_model.predict(m_obs, deterministic=is_deterministic)\n m_obs, m_reward, m_done, m_info = m_env.step(m_action)\n\n i += 1\n\n if done == 1:\n nb_success += 1\n average_timesteps = average_timesteps + (counter - average_timesteps) / nb_success\n\n if m_done == 1:\n m_nb_success += 1\n m_average_timesteps = m_average_timesteps + (m_counter - m_average_timesteps) / m_nb_success\n\n \"\"\"\n if m_done == 1:# and done == 2:\n temp_done = 0\n m_temp_done = 0\n temp_env.render()\n time.sleep(10)\n while temp_done == 0:\n temp_action, temp_state = SAC_model.predict(temp_obs, deterministic=is_deterministic)\n temp_obs, temp_reward, temp_done, temp_info = temp_env.step(temp_action)\n temp_env.render()\n time.sleep(0.05)\n time.sleep(5)\n temp_env.close()\n\n m_temp_env.render()\n time.sleep(10)\n while m_temp_done == 0:\n m_temp_action, m_temp_state = M_SAC_model.predict(m_temp_obs, deterministic=is_deterministic)\n m_temp_obs, m_temp_reward, m_temp_done, m_temp_info = m_temp_env.step(m_temp_action)\n m_temp_env.render()\n time.sleep(0.05)\n time.sleep(5)\n #m_temp_env.close()\n #\"\"\"\n\n if done==1 and m_done==1:\n common_successes += 1\n\n obs = env.reset()\n m_obs = obs\n m_env = deepcopy(env)\n\n temp_env = deepcopy(env)\n temp_obs = obs\n\n m_temp_env = deepcopy(env)\n m_temp_obs = obs\n\n counter = 0\n done = 0\n m_counter = 0\n m_done = 0\n\n\nprint(f'SAC: {nb_success} successes out of {i} trials. Average time steps is: {average_timesteps}')\nprint(f'M_SAC: {m_nb_success} successes out of {i} trials. Average time steps is: {m_average_timesteps}')\nprint(f'number of common successes: {common_successes}')","sub_path":"particles-env/test_on_same_env.py","file_name":"test_on_same_env.py","file_ext":"py","file_size_in_byte":2770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"535510036","text":"import numpy as np\r\nimport scipy as sp\r\nimport scipy.sparse.linalg as linalg\r\nimport matplotlib.pyplot as plt\r\n\r\n#griddding\r\nk = 200 #number of steps per 1 second\r\nn = 10#number of space steps\r\n\r\ntime = 10 #sec\r\n\r\ndx = 1/n #length of one space step\r\ndt = 1/k #length of one time step\r\nalpha = 1 #speed\r\nr = alpha*dt/dx**2 #Stable factor should be less 1/2\r\ntotal_time_steps = int(time/dt) #total time steps\r\nprint(\"Stable factor:\", r)\r\n\r\nx = np.linspace(0, 1, n+1)\r\n\r\n#initial condition\r\nu = np.zeros((n+1, total_time_steps+1))\r\nu[:, 0] = np.sin(np.pi*x) #u(x,0)= f(x)\r\nu[0, :] = 0\r\nu[n, :] = 0\r\n\r\n# scheme of solving\r\n# theta = 0 (explicit scheme), theta = 1 (implicit scheme), and theta = 1/2 (Crank-Nicolson scheme)\r\ntheta = 0\r\n\r\n#buildin of matrix A\r\na = np.ones(n-1)*(1/dt+2*alpha*theta/dx**2)\r\nb = c = np.ones(n-1)*(-alpha*theta/dx**2)\r\nA = sp.sparse.dia_matrix(([b, a, c], [-1, 0, 1]), [n-1, n-1]).toarray()\r\n\r\nd = np.zeros(n-1)\r\ni = np.arange(1, n)\r\n\r\nfor t in range(0, total_time_steps):\r\n #Building of vector d\r\n d[i-1] = alpha*(1 - theta)/dx**2*u[i-1, t]\\\r\n + (1/dt-2*alpha*(1 - theta)/dx**2)*u[i, t]\\\r\n + alpha*(1 - theta)/dx**2*u[i+1, t]\r\n # solving\r\n u[1:n, t+1] = np.linalg.solve(A, d)\r\n #ploting\r\n plt.plot(x, u[:, t+1])\r\n plt.ylim([0, 1])\r\n plt.pause(0.00001)\r\n plt.clf()\r\n","sub_path":"heat.py","file_name":"heat.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"428266050","text":"class Card:\r\n \"\"\"\" Одна игральная карта. \"\"\"\r\n\r\n RANKS = [\"Т\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"В\", \"Д\", \"К\"]\r\n\r\n SUITS = [u'\\u2660', u'\\u2663', u'\\u2665', u'\\2666']\r\n\r\n def __init__(self, rank, suit):\r\n self.rank = rank\r\n self.suit = suit\r\n\r\n def __str__(self):\r\n rep = self.rank + self.suit\r\n return rep\r\n\r\n\r\nclass Hand:\r\n \"\"\"\" Рука: набор карт на руках у одного игрока. \"\"\"\r\n\r\n def __init__(self):\r\n self.cards = []\r\n\r\n def __str__(self):\r\n if self.cards:\r\n rep = \"\"\r\n for card in self.cards:\r\n rep += str(card) + \"\\t\"\r\n else:\r\n rep = \"<пусто>\"\r\n return rep\r\n\r\n def clear(self):\r\n self.cards = []\r\n\r\n def add(self, card):\r\n self.cards.append(card)\r\n\r\n def give(self, card, other_hand):\r\n self.cards.remove(card)\r\n other_hand.add(card)\r\n\r\ncard1 = Card(rank = \"Т\", suit = Card.SUITS[0])\r\nprint(\"Вывожу на экран объект-карту:\")\r\nprint(card1)\r\n\r\ncard2 = Card(rank = \"2\", suit = Card.SUITS[0])\r\ncard3 = Card(rank = \"3\", suit = Card.SUITS[0])\r\ncard4 = Card(rank = \"4\", suit = Card.SUITS[0])\r\ncard5 = Card(rank = \"5\", suit = Card.SUITS[0])\r\nprint(\"\\nВывожу ещё четыре карты:\")\r\nprint(card2)\r\nprint(card3)\r\nprint(card4)\r\nprint(card5)\r\n\r\n\r\n\r\n\r\nmy_hand = Hand()\r\nprint(\"\\nПечатаю карты, которые у меня на руках до раздачи:\")\r\nprint(my_hand)\r\n\r\nmy_hand.add(card1)\r\nmy_hand.add(card2)\r\nmy_hand.add(card3)\r\nmy_hand.add(card4)\r\nmy_hand.add(card5)\r\nprint(\"\\nПечатаю пять карт, которые появились у меня на руках:\")\r\nprint(my_hand)\r\n\r\nyour_hand = Hand()\r\nmy_hand.give(card1, your_hand)\r\nmy_hand.give(card2, your_hand)\r\nprint(\"\\nПервые две из моих карт я передал вам.\")\r\nprint(\"Теперь у вас на руках:\")\r\nprint(your_hand)\r\nprint(\"А у меня на руках:\")\r\nprint(my_hand)\r\n\r\nmy_hand.clear()\r\nprint(\"n\\А у меня на руках после того, как я сбросил все карты:\")\r\nprint(my_hand)","sub_path":"Card.py","file_name":"Card.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"81569235","text":"def sortedSquares(A):\n \"\"\"\n :type A: List[int]\n :rtype: List[int]\n \"\"\"\n res = []\n for i in A:\n k = i * i\n res.append(k)\n return sorted(res)\n\n\nif __name__ == \"__main__\":\n print(sortedSquares([-4,-1,0,3,10]))","sub_path":"LeetCode/双指针/sortedSquares.py","file_name":"sortedSquares.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"44666734","text":"'''\nInput: a List of integers\nReturns: a List of integers\n\nNotes: \n- want to move zeroes to end of array\n- iterate thru the array...if value at index is 0, then remove it from the array, then append to the end <=== This mostly works but if array is front-loaded with zeroes (e.g., test file test starting at line 48), this won't work....need to also move integers to the front\n- could try swtiching...but that would probably require multiple pass thrus \n'''\ndef moving_zeroes(arr):\n # Your code here\n # Iterate thru array\n for i in range(0, len(arr)):\n # if item is 0, \n if arr[i] == 0:\n # remove item from array and add it to the end\n arr.append(arr.pop(i))\n # otherwise,\n else:\n # remove item from array and insert it at the beginning\n arr.insert(0, arr.pop(i))\n return arr\n\n\nif __name__ == '__main__':\n # Use the main function here to test out your implementation\n arr = [0, 3, 1, 0, -2]\n\n print(f\"The resulting of moving_zeroes is: {moving_zeroes(arr)}\")","sub_path":"moving_zeroes/moving_zeroes.py","file_name":"moving_zeroes.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"22847143","text":"from point3d import Point3D\nfrom vector import Vector\n\n'''\nMethod that create 2 Vectors and applied laplace rule to them\n'''\ndef laplace(point1, point2, point3):\n try:\n vetor1 = point1.createVector(point2)\n vetor2 = point1.createVector(point3)\n\n x = vetor1.coordinates[1] * vetor2.coordinates[2] - vetor1.coordinates[2] * vetor2.coordinates[1]\n y = vetor1.coordinates[2] * vetor2.coordinates[0] - vetor1.coordinates[0] * vetor2.coordinates[2]\n z = vetor1.coordinates[0] * vetor2.coordinates[1] - vetor1.coordinates[1] * vetor2.coordinates[0]\n\n d = -(x * point1.point[0] + y * point1.point[1] + z * point1.point[2])\n\n print(\"Normal Vector: n({}, {}, {})\".format(x, y , z))\n print(\"Plan Equation: {}x + {}y + {}z + {} = 0\".format(x, y, z, d))\n except TypeError:\n print(\"The argument have to be of type Point3D\")\n\n'''\nMain \n'''\nif __name__ == '__main__':\n p1 = Point3D(5, 4, 3)\n p2 = Point3D(6, -1, 2)\n p3 = Point3D(7, 2, -4)\n laplace(p1, p2, p3)","sub_path":"vectorialProduct.py","file_name":"vectorialProduct.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"463579764","text":"\"\"\"Functions related to the runtime configuration file.\"\"\"\nimport os\n\n\ndef find(input_archive):\n \"\"\"Return the relative path of the config file if found.\"\"\"\n filename = '.narrc'\n filepath = os.path.dirname(input_archive)\n at_root = False\n\n if not filepath:\n filepath = '.'\n\n while not at_root:\n for f in os.listdir(filepath):\n if f == filename:\n return os.path.normpath(os.path.join(filepath, filename))\n\n at_root = os.path.abspath(filepath) == os.path.abspath(os.sep)\n filepath = os.path.join(filepath, '..')\n\n return False\n\n\ndef parse(config_fpath):\n \"\"\"Return configurations for a given config file path.\"\"\"\n config = {\n 'mode': 'move',\n 'dir': 'archive',\n 'exclude': '',\n 'exclude_mode': 'remove'\n }\n\n with open(config_fpath, 'r') as f:\n for line in f:\n line = line.strip()\n splitline = line.split('=')\n\n # Check for comments line and if value is set\n if line.startswith('#') or len(splitline) < 2:\n continue\n\n key = splitline[0].rstrip()\n value = splitline[1].lstrip().split('#')\n\n # Check if value is a comment and if it's a valid option\n if value[0] and key in config:\n config[key] = value[0].rstrip()\n\n return config\n","sub_path":"nar/rcfile.py","file_name":"rcfile.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"404549814","text":"#!/usr/bin/python\n\nimport math\n\n\ndef recipe_batches(recipe, ingredients):\n # Initialize a variable to hold number of batches so far\n batch_count = 0\n\n # Keep the Loop running and exit on a return statement\n while True:\n # Loop through the keys in the recipe dictionary\n for i in recipe.keys():\n # Check if the current key in recipe is also in the ingredients dictionary\n if i in ingredients:\n # Check if the value of the current ingredients is less than the value of the current recipe\n if ingredients[i] < recipe[i]:\n # End the loop and return the current batch_count\n return batch_count\n else:\n # Remove the amount of the recipe from the current ingredients\n ingredients[i] -= recipe[i]\n else:\n # Return the batch count if the current recipe is not in ingredients\n return batch_count\n # After the cycle for each item less the amount of recipe, increment the batch count by 1\n batch_count += 1\n\n# A little more efficent solution \ndef recipe_batches_e(recipe, ingredients):\n # define a variable to hold the number of batches\n # we have to loop through and subtract recipe from ingredient\n # check if the recipe and ingredients have same properties\n batches = 0\n\n # if the recipe and the ingredients don't match, end the loop\n if (ingredients.keys() != recipe.keys()):\n return batches\n\n # keep the subtraction loop running till we can subtract anymore\n while True:\n # for each ingredient remove the amount of ingredient consumed\n for item in ingredients:\n # quantity of ingredient has to be greater than the recipe\n if (ingredients[item] >= recipe[item]):\n ingredients[item] = ingredients[item] - recipe[item]\n else:\n return batches\n\n batches += 1\n\n\nif __name__ == '__main__':\n # Change the entries of these dictionaries to test\n # your implementation with different inputs\n recipe = {'milk': 100, 'butter': 50, 'flour': 5}\n ingredients = {'milk': 132, 'butter': 48, 'flour': 51}\n print(\"{batches} batches can be made from the available ingredients: {ingredients}.\".format(\n batches=recipe_batches(recipe, ingredients), ingredients=ingredients))\n","sub_path":"recipe_batches/recipe_batches.py","file_name":"recipe_batches.py","file_ext":"py","file_size_in_byte":2406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"564802985","text":"'''\nAuthor: Puffrora\nDate: 2022-02-24 18:12:35\nLastModifiedBy: Puffrora\nLastEditTime: 2022-02-24 18:38:57\n'''\n\n\nfrom typing import List\n\nclass Solution:\n def countPairs(self, deliciousness: List[int]) -> int:\n\n from collections import defaultdict\n\n deli_dict = defaultdict(int)\n for d in deliciousness:\n deli_dict[d] += 1\n\n #. important edge case\n\n power = 40\n res = 0\n mod = 10**9+7\n for p in range(power):\n target = 1 << p\n for d in deli_dict.keys():\n candidate = target - d\n if candidate in deli_dict:\n if candidate == d:\n n = deli_dict[d]\n res += (n-1) * n // 2\n res %= mod\n elif candidate > d:\n n, m = deli_dict[d], deli_dict[candidate]\n res += m * n\n res %= mod\n return res","sub_path":"Leetcode/leetcode1711 大餐计数.py","file_name":"leetcode1711 大餐计数.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"482363712","text":"from django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom django.conf import settings\nfrom django.contrib.auth.models import User\n\nfrom users.models.profiles import Profiles\n\nimport json\nimport requests\n\n\n@receiver(post_save, sender=User)\ndef create_user_profile(sender, instance, created, **kwargs):\n if created:\n Profiles.objects.create(user=instance)\n\n\n@receiver(post_save, sender=Profiles)\ndef create_sub_domain(sender, instance, created, **kwargs):\n if created:\n if settings.TYPE_SETTINGS == 'local':\n domain = instance.domain + '.local.send.sale'\n elif settings.TYPE_SETTINGS == 'test':\n domain = instance.domain + '.test.send.sale'\n elif settings.TYPE_SETTINGS == 'prod':\n domain = instance.domain + '.send.sale'\n else:\n domain = instance.domain + '.local.send.sale'\n\n payload = {'name': domain, 'type': 'A', 'content': settings.SEND_SALE_IP}\n headers = {'content-type': 'application/json', 'X-Token': str(settings.SELECTEL_API_KEY)}\n\n domain_data_r = requests.get('https://api.selectel.ru/domains/v1/send.sale', headers=headers)\n domain_data = json.loads(domain_data_r.content.decode('utf8'))\n\n r = requests.post('https://api.selectel.ru/domains/v1/%s/records/' % domain_data['id'], data=json.dumps(payload), headers=headers)\n","sub_path":"users/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"641285117","text":"from gevent import monkey; monkey.patch_socket()\n\nimport gevent\nimport requests\nimport urllib3\nfrom urllib3.exceptions import InsecureRequestWarning\n\nurllib3.disable_warnings(InsecureRequestWarning)\n\n\ndef get(ip, _id):\n session = requests.Session()\n session.post(\"https://{}/rest/Sessions\".format(ip), json=dict(UserName=\"USERID\", Password='PASSW0RD'), verify=False)\n req = session.get(\"https://{}/json/health_temperature\".format(ip))\n print(req.status_code)\n # results = req.json()[\"temperature\"]\n # for result in results:\n # if \"inlet\" in result[\"label\"].lower():\n # print result[\"currentreading\"]\n # elif \"exhaust\" in result[\"label\"].lower():\n # print result[\"currentreading\"]\n # else:\n # return\n print(\"Process {} done\".format(_id))\n\n\ndef synchronous():\n for i in range(5):\n get(\"172.20.12.49\", i)\n\n\ndef asynchronous():\n threads = list()\n for i in range(5):\n threads.append(gevent.spawn(get, \"172.20.12.49\", i))\n gevent.joinall(threads)\n\n\nif __name__ == '__main__':\n print(\"synchronous\")\n synchronous()\n print(\"synchronous\")\n asynchronous()\n\n","sub_path":"t04.py","file_name":"t04.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"388912519","text":"# snake1.py\r\n \r\nfrom tkinter import *\r\nglobal rows\r\nglobal cols\r\n\r\ndef draw(event):\r\n\tprint(\"x: \"+str(event.x)+\",y: \"+str(event.y))\r\n\t\r\n\r\n\r\n\r\n\r\n########### copy-paste below here ###########\r\n\r\ndef run():\r\n # create the root and the canvas\r\n root = Tk()\r\n canvas = Canvas(root, width=700, height=700)\r\n canvas.pack()\r\n # Store canvas in root and in canvas itself for callbacks\r\n root.canvas = canvas.canvas = canvas\r\n # Set up canvas data and call init\r\n canvas.data = { }\r\n canvas.bind('', draw)\r\n root.mainloop() # This call BLOCKS (so your program waits until you close the window!)\r\n\r\nrun()\r\n","sub_path":"jeu/essaiJeu.py","file_name":"essaiJeu.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"434878744","text":"import pprint, re, requests, socket\r\nfrom lxml import etree\r\nfrom requests.packages.urllib3.poolmanager import PoolManager\r\nfrom urllib import request, parse\r\n\r\n\r\n\"\"\"\r\n\tScript that will scrap http://www.xicidaili.com/nn/1\r\n\tfor ip and port to check if proxy is working or not\r\n\"\"\"\r\n\r\n\r\ndef test_proxy():\r\n# url = \"http://my-ip.herokuapp.com/\"\r\n# s = requests.session()\r\n\r\n# html = s.get(url)\r\n# print(html, html.content)\r\n\r\n# headers = {\r\n# \t'User-agent': 'Mozilla/5.0', \r\n# \t'referer': ''\r\n# }\r\n# s.cookies.clear()\r\n# s.close()\r\n\r\n# s = requests.session()\r\n# proxy = '122.72.32.72:80'\r\n# proxies = {\r\n# \t'http' : 'http://{}'.format(proxy),\r\n# \t'https' : 'https://{}'.format(proxy),\r\n# \t'ftp' : proxy\r\n# }\r\n\r\n# html = s.get(url, headers=headers, proxies=proxies)\r\n# html = s.get(url)\r\n# print(html, html.content, \"PROXIES: {}\".format(proxies))\r\n# s.cookies.clear()\r\n# s.close()\r\n\r\n# socket.setdefaulttimeout(180)\r\n\r\n# url = \"http://my-ip.herokuapp.com/\"\r\n# r = request.Request(url)\r\n# sock = request.urlopen(r)\r\n# print(sock.read())\r\n\r\n# s = requests.session()\r\n\r\n# headers = {\r\n# \t'User-agent': 'Mozilla/5.0', \r\n# \t'referer': ''\r\n# }\r\n\r\n# 'http://spys.ru/free-proxy-list/PH/'\r\n# html.xpath(\"//font[@class='spy14']\")\r\n# html = s.get('http://proxylist.hidemyass.com/', headers=headers)\r\n# html = s.get('http://www.gatherproxy.com/proxylist/country/?c=Philippines', headers=headers)\r\n# html_tree = etree.HTML(html.content)\r\n# proxys = [\r\n# \t'112.199.65.190:3128',\r\n# \t'120.28.45.202:8090',\r\n# \t'112.119.79.106:8080',\r\n# \t'120.72.26.131:8080',\r\n# \t'43.250.227.94:8080',\r\n# \t'146.88.71.67:8080',\r\n# \t'203.160.172.163:8090',\r\n# \t'202.57.48.102:80',\r\n# \t'122.54.20.214:8090',\r\n# \t'49.150.107.185:80',\r\n# \t'112.199.79.106:8080'\r\n# ]\r\n\r\n# print(html_tree.xpath(\"//table[@id='listable']/tbody\"))\r\n\r\n# for trs in html_tree.xpath(\"//table[@id='listable']/tbody\"):\r\n# \tfor i, tr in enumerate(trs):\r\n# \t\tprint(tr)\r\n# \t\tfor td in tr:\r\n# \t\t\tprint(td, td.text)\r\n\r\n# for i, tr in enumerate(html_tree.xpath(\"//table[@id='listable']/tr\")):\r\n# \tprint(i, tr, tr[1].text, tr[2].text)\r\n\r\n# s.cookies.clear()\r\n# s.close()\r\n\r\n# user_agents = ['Mozilla/5.0', '(Windows NT 6.1; Win64; x64)', 'AppleWebKit/537.36', '(KHTML, like Gecko)', 'Chrome/55.0.2883.87', 'Safari/537.36']\r\n# proxys = [\r\n# \t'122.54.3.171:45554',\r\n# \t'122.53.178.100:1080'\r\n# ]\r\n# print(59, html_tree.xpath(\"//table[@id='tblproxy']/tbody\"))\r\n# for i, tr in enumerate(html_tree.xpath(\"//table[@id='tblproxy']\")):\r\n# \t# print(i, tr, tr[1].text, tr[2].text)\r\n# \tfor td in tr:\r\n# \t\tprint(63, td.text.strip())\r\n\t\r\n# print(proxys)\r\n# s.cookies.clear()\r\n# s.close()\r\n\r\n\t# def is_bad_proxy(ip_port): \r\n\t# \ttry:\r\n\t# \t\tproxy_handler = request.ProxyHandler({'http': ip_port})\r\n\t# \t\topener = request.build_opener(proxy_handler)\r\n\t# \t\topener.addheaders = [('User-agent', 'Mozilla/5.0')]\r\n\t# \t\trequest.install_opener(opener)\r\n\t# \t\treq = request.Request('http://www.google.com') # change the url address here\r\n\t# \t\tsock = request.urlopen(req)\r\n\t# \texcept request.HTTPError as e:\r\n\t# \t\tprint('Error code: {}'.format(e.code))\r\n\t# \t\treturn e.code\r\n\t# \texcept Exception as detail:\r\n\t# \t\tprint(\"ERROR: {}\".format(detail))\r\n\t# \t\treturn 1\r\n\t# \treturn 0\r\n\r\n\t# for i in proxys:\r\n\t# \toks = True\r\n\t# \tprint(\"Checking {}\".format(i))\r\n\t# \ttry:\r\n\t# \t\tproxy_handler = request.ProxyHandler({'http': i})\r\n\t# \t\topener = request.build_opener(proxy_handler)\r\n\t# \t\topener.addheaders = [('User-agent', 'Mozilla/5.0')]\r\n\t# \t\trequest.install_opener(opener)\r\n\t# \t\treq = request.Request('http://my-ip.herokuapp.com/') # change the url address here\r\n\t# \t\tsock = request.urlopen(req)\r\n\t# \t\tprint(\"{} is working\".format(i), sock.getcode())\r\n\r\n\t# \t\t# proxy_handler = request.ProxyHandler({'http': i})\r\n\t# \t\t# opener = request.build_opener(proxy_handler)\r\n\t# \t\t# opener.addheaders = [('User-agent', 'Mozilla/5.0'), ('Referer', '')]\r\n\t# \t\t# request.install_opener(opener)\r\n\t# \t\t# accounts = [\r\n\t# \t\t# \t('mmkronald', '123qwe!!'),\r\n\t# \t\t# \t('mmktest00', '123qwe!!'),\r\n\t# \t\t# \t('mmktest01', '123qwe!!'),\r\n\t# \t\t# \t('mmktest02', '123qwe!!'),\r\n\t# \t\t# ]\r\n\t# \t\t# headers = {\r\n\t# \t\t# \t'User-agent': 'Mozilla/5.0', \r\n\t# \t\t# \t'referer': ''\r\n\t# \t\t# }\r\n\t# \t\t# url = 'https://imgur.com/signin?redirect=http%3A%2F%2Fimgur.com%2F'\r\n\t# \t\t# for account in accounts:\r\n\t# \t\t\t# data = {\r\n\t# \t\t\t# \t'username': account[0].strip(),\r\n\t# \t\t\t# \t'password': account[1].strip()\r\n\t# \t\t\t# }\r\n\t# \t\t\t# proxys = {\r\n\t# \t\t\t# \t'http': 'http://{}'.format(i),\r\n\t# \t\t\t# \t'https': 'https://{}'.format(i),\r\n\t# \t\t\t# \t'ftp': '{}'.format(i),\r\n\t# \t\t\t# }\r\n\r\n\r\n\t# \t\t\t# html = requests.post(url, data, headers = headers, proxies=proxys)\r\n\t# \t\t\t# html_tree = etree.HTML(html.content)\r\n\t# \t\t\t# print(html, i, html.status_code, data, html_tree.xpath(\"//div[@class='dropdown-footer']\"), html_tree.xpath(\"//div[@class='captcha']\"))\r\n\t# \texcept request.HTTPError as e:\r\n\t# \t\toks = False\r\n\t# \t\tprint('{} Error code: {}'.format(i, e.code))\r\n\t# \texcept Exception as detail:\r\n\t# \t\toks = False\r\n\t# \t\tprint(\"{} ERROR: {}\".format(i, detail))\r\n\r\n\t# \tif oks:\r\n\t# \t\tprint(\"REQUESTING FOR {}\".format(i))\r\n\t# \t\t# data = {\r\n\t# \t\t# \t'username': 'mmkronald',\r\n\t# \t\t# \t'password': '123qwe!!'\r\n\t# \t\t# }\r\n\t# \t\t# data = parse.urlencode(data)\r\n\t# \t\t# data = data.encode('ascii')\r\n\r\n\t# \t\t# req = request.Request('https://imgur.com/signin?redirect=http%3A%2F%2Fimgur.com%2F', data=data)\r\n\t# \t\t# sock = request.urlopen(req)\r\n\t# \t\t# print(sock.read())\r\n\r\n\t# \t\taccounts = [\r\n\t# \t\t\t('mmkronald', '123qwe!!'),\r\n\t# \t\t\t('mmktest00', '123qwe!!'),\r\n\t# \t\t\t('mmktest01', '123qwe!!'),\r\n\t# \t\t\t('mmktest02', '123qwe!!'),\r\n\t# \t\t]\r\n\t# \t\t# headers = {\r\n\t# \t\t# \t'User-agent': 'Mozilla/5.0', \r\n\t# \t\t# \t'referer': ''\r\n\t# \t\t# }\r\n\t# \t\t# url = 'https://imgur.com/signin?redirect=http%3A%2F%2Fimgur.com%2F'\r\n\t# \t\t# for account in accounts:\r\n\t# \t\t# \t# data = {\r\n\t# \t\t# \t# \t'username': account[0].strip(),\r\n\t# \t\t# \t# \t'password': account[1].strip()\r\n\t# \t\t# \t# }\r\n\t# \t\t# \t# data = parse.urlencode(data)\r\n\t# \t\t# \t# data = data.encode('ascii')\r\n\r\n\t# \t\t# \treq = request.Request(url)\r\n\t# \t\t# \twith request.urlopen(req) as response:\r\n\t# \t\t# \t\tprint(response.read())\r\n\r\n\t# \t\t# url = 'http://my-ip.herokuapp.com/'\r\n\t# \t\turl = 'https://imgur.com/signin?redirect=http%3A%2F%2Fimgur.com%2F'\r\n\t# \t\t# url = 'http://httpbin.org/ip'\r\n\t# \t\txheaders = {\r\n\t# \t\t\t'User-agent': 'Mozilla/5.0', \r\n\t# \t\t\t'referer': ''\r\n\t# \t\t}\r\n\t# \t\tproxys = {\r\n\t# \t\t\t'http': 'http://{}'.format(i),\r\n\t# \t\t}\r\n\t# \t\tfor account in accounts:\r\n\t# \t\t\tdata = {\r\n\t# \t\t\t\t'username': account[0],\r\n\t# \t\t\t\t'password': account[1]\r\n\t# \t\t\t}\r\n\t\t\t\t\r\n\t# \t\t\ts = requests.session()\r\n\t# \t\t\thtml = s.post(url, data=data, headers=xheaders)\r\n\t# \t\t\thtml_tree = etree.HTML(html.content)\r\n\t# \t\t\tprint(\"XPROXY\", html, i, html.status_code, data, html_tree.xpath(\"//div[@class='dropdown-footer']\"), html_tree.xpath(\"//div[@class='captcha']\"))\r\n\t# \t\t\ts.cookies.clear()\r\n\t# \t\t\ts.close()\r\n\r\n\t# \t\t\tfor user_agent in user_agents:\r\n\t# \t\t\t\ttry:\r\n\t# \t\t\t\t\twheaders = {\r\n\t# \t\t\t\t\t\t'User-agent': user_agent\r\n\t# \t\t\t\t\t}\r\n\t# \t\t\t\t\thtml = s.post(url, data=data, headers=wheaders, proxies=proxys)\r\n\t# \t\t\t\t\thtml_tree = etree.HTML(html.content)\r\n\t# \t\t\t\t\tprint(\"WPROXY\", html, i, html.status_code, data, wheaders, html_tree.xpath(\"//div[@class='dropdown-footer']\"), html_tree.xpath(\"//div[@class='captcha']\"))\r\n\t# \t\t\t\t\ts.cookies.clear()\r\n\t# \t\t\t\t\ts.close()\r\n\t# \t\t\t\texcept Exception as e:\r\n\t# \t\t\t\t\tprint(\"WPROXY\", i, e)\r\n\r\n\t# \t\t\t\tif html_tree.xpath(\"//div[@class='dropdown-footer']\"):\r\n\t# \t\t\t\t\tbreak\r\n\t# \t\t# break\r\n\t# \t\t# if is_bad_proxy(i):\r\n\t# \t\t# \tprint(\"{} bad proxy.\".format(i))\r\n\t# \t\t# else:\r\n\t# \t\t# \tprint(\"{} is working\".format(i))\r\n\t# # r = request.Request('https://www.xicidaili.com/nn/1')\r\n\t# # sock = request.urlopen(r)\r\n\t# # html = sock.read()\r\n\t# # print(html)\r\n\t# # html_tree = etree.HTML(html.content)\r\n\r\n\turl = \"http://httpbin.org/ip\"\r\n\tresponse = requests.get(url)\r\n\tprint(response.text)\r\n\r\n\tsocket.setdefaulttimeout(180)\r\n\tuser_agents = [\r\n\t\t'Mozilla/5.0', \r\n\t\t'(Windows NT 6.1; Win64; x64)', \r\n\t\t'AppleWebKit/537.36', \r\n\t\t'(KHTML, like Gecko)', \r\n\t\t'Chrome/55.0.2883.87', \r\n\t\t'Safari/537.36'\r\n\t]\r\n\taccounts = [\r\n\t\t('mmkronald', '123qwe!!'),\r\n\t\t('mmktest00', '123qwe!!'),\r\n\t\t('mmktest01', '123qwe!!'),\r\n\t\t('mmktest02', '123qwe!!'),\r\n\t]\r\n\r\n\t# Get proxy\r\n\tproxys = []\r\n\t# url = \"https://www.sslproxies.org/\"\r\n\t# url = \"http://www.xicidaili.com/nn/\"\r\n\t# url = \"http://haoip.cc/tiqu.htm\"\r\n\t# headers = {\r\n\t# \t'User-agent': user_agents[0]\r\n\t# }\r\n\t# response = requests.get(url, headers=headers)\r\n\t# html_etree = etree.HTML(response.content)\r\n\t# proxys = [\"{}:{}\".format(tr[1].text, tr[2].text) for index, tr in enumerate(html_etree.xpath(\"//table[@id='ip_list']/tr\"))][1:]\r\n\t# proxys = [ip.strip() for ip in re.findall(r'r/>(.*?) \n PREFIX mwapi: \n PREFIX wdt: \n PREFIX wikibase: \n PREFIX rdfs: \n\n SELECT ?item ?typeLabel\n WHERE { \n SERVICE wikibase:mwapi {\n bd:serviceParam wikibase:api \"EntitySearch\" ;\n wikibase:endpoint \"www.wikidata.org\" ;\n mwapi:search \"%s\";\n mwapi:language \"en\" . \n ?item wikibase:apiOutputItem mwapi:item . \n ?num wikibase:apiOrdinal true . \n } \n #?item (wdt:P279|wdt:P31) ?type \n ?item wdt:P17 ?type \n SERVICE wikibase:label { bd:serviceParam wikibase:language \"en\". }\n } \n ORDER BY ASC(?num)\n LIMIT 1\"\"\" % (\n location\n )\n\n print(f'querying location - {location}')\n sparql.setQuery(query_s)\n sparql.setReturnFormat(JSON)\n results = sparql.query().convert()\n if len(results[\"results\"][\"bindings\"]) > 0:\n return results[\"results\"][\"bindings\"][0]['typeLabel']['value']\n return None\n\n\ndef extract_locations(sents, countries):\n nlp = datautils.get_nlp()\n locs_cnt = Counter()\n for sent in tqdm(sents):\n premise = sent['sentence1']\n doc = nlp(premise)\n for e in doc.ents:\n if e.label_ in ['LOC', 'GPE']:\n locs_cnt[e.text.lower()] += 1\n return locs_cnt\n\n\ndef load_mnli(fname):\n df = pd.read_json(fname, lines=True)\n return df.to_dict(orient='records')\n\n\n@cbox.cmd\ndef extract_mnli_locations(mnli_fname, outfile):\n print('started')\n mnli = load_mnli(mnli_fname)\n\n print('extracting locations from wikidata')\n countries = [c.lower() for c in COUNTRIES]\n locs_cnt = extract_locations(mnli, countries)\n\n with open(outfile, 'w') as fp:\n json.dump(dict(locs_cnt), fp, indent=4)\n\n\n@cbox.cmd\ndef download_locations(locs_cnt_fname, outfile):\n sparql = SPARQLWrapper(\"https://query.wikidata.org/sparql\")\n countries = {c.lower() for c in COUNTRIES}\n\n with open(locs_cnt_fname) as fp:\n locs_cnt = json.load(fp)\n\n with open(outfile) as fp:\n found_locs = [json.loads(l)['location'] for l in fp]\n with open(outfile, 'a') as fp:\n for loc, cnt in locs_cnt.items():\n if loc in found_locs:\n print('already exists')\n continue\n elif '\"' in loc or '?' in loc:\n print(f'invalid char at loc {loc}')\n continue\n res = get_wikidata_country(loc, sparql)\n is_country = loc.lower() in countries\n fp.write(\n json.dumps(\n {\n 'location': loc,\n 'cnt': cnt,\n 'result': res,\n 'is_country': is_country,\n }\n )\n )\n fp.write('\\n')\n fp.flush()\n\n\ndef filter_locations_sents(sentence, doc, loc_entities_types=('LOC', 'GPE')):\n loc_entities = [e for e in doc.ents if e.label_ in loc_entities_types]\n\n # not interesting - no locations\n if len(loc_entities) == 0:\n return False, None\n\n return (\n True,\n {\n 'num_locations': len(loc_entities),\n 'locations': [str(e).lower() for e in loc_entities],\n 'start_char': [e.start_char for e in loc_entities],\n 'end_char': [e.end_char for e in loc_entities],\n # known to us - found on the db\n 'known_location': [\n str(e).lower() in KNOWN_LOCATIONS for e in loc_entities\n ],\n # take either spacy number of span tokens or word regex - the higher\n 'word_count': [\n max(e.end - e.start, count_words(str(e))) for e in loc_entities\n ],\n },\n )\n\n\ndef count_words(s):\n return len(re.findall(r'\\w+', s, flags=re.I | re.U))\n\n\ndef extract_sentences_from_mnli(mnli_samples, filter_func):\n sentence2name = {'sentence1': 'permise', 'sentence2': 'hypothesis'}\n nlp = datautils.get_nlp()\n\n for sample_id, sample in enumerate(tqdm(mnli_samples)):\n for sent_id in sentence2name:\n sent = sample[sent_id]\n\n # parse it with spacy\n doc = nlp(sent)\n is_match, metadata = filter_func(sent, doc)\n\n if is_match:\n yield {\n 'sentence': sent,\n 'type': sentence2name[sent_id],\n 'genre': sample['genre'],\n 'sample_id': sample_id,\n **metadata,\n }\n\n\n@cbox.cmd\ndef extract_mnli_sentences_with_locations(mnli_fname, outfile):\n mnli_samples = load_mnli(mnli_fname)\n matches = extract_sentences_from_mnli(mnli_samples, filter_locations_sents)\n datautils.jsonl_dump(matches, outfile)\n\n\n@cbox.cmd\ndef create_sentences_pool_for_filtering(infile, outfile):\n country2cities = get_country2cities_deduped()\n known_deduped_locations = {c for c in country2cities} | {\n c for cs in country2cities.values() for c in cs\n }\n\n # because we dedup strings each city has exactly one country\n city2country = {\n city: country\n for country, cities in country2cities.items()\n for city in cities\n }\n\n def _filter_sents(x):\n return (\n x['num_locations'] == 1\n and all(x['known_location'])\n and x['word_count'][0] == 1\n and x['genre'] != 'telephone'\n and x['locations'][0].lower() in known_deduped_locations\n )\n\n sents = [x for x in datautils.jsonl_load(infile) if _filter_sents(x)]\n\n random.seed('location location location')\n random.shuffle(sents)\n\n with open(outfile, 'w') as fp:\n writer = csv.DictWriter(\n fp,\n fieldnames=[\n 'original_sentence',\n 'highlighted_sentence',\n 'country',\n 'location',\n 'is_country',\n 'start_char',\n 'end_char',\n 'id',\n ],\n )\n writer.writeheader()\n\n for s in sents:\n loc = s['locations'][0].lower()\n is_country = loc in country2cities\n\n if is_country:\n country = loc\n location = random.choice(country2cities[loc])\n else:\n country = city2country[loc]\n location = loc\n\n schar = s['start_char'][0]\n echar = s['end_char'][0]\n\n row = {\n 'original_sentence': s['sentence'],\n 'highlighted_sentence': s['sentence'][:schar]\n + '**'\n + s['sentence'][schar:echar]\n + '**'\n + s['sentence'][echar:],\n 'country': country,\n 'location': location,\n 'is_country': is_country,\n 'start_char': schar,\n 'end_char': echar,\n 'id': f'{s[\"sample_id\"]}_{s[\"type\"][0]}',\n }\n\n writer.writerow(row)\n\n\n@cbox.cmd\ndef finalize_sentences_for_tagging(infile, outfile):\n df = pd.read_csv(infile)\n\n df = df[df['can_be_entailed'].isin({0, 1})]\n df = df.sample(n=len(df), random_state=42)\n df = df[\n [\n 'id',\n 'original_sentence',\n 'can_be_entailed',\n 'country',\n 'start_char',\n 'end_char',\n ]\n ]\n\n df = df.rename(columns={'original_sentence': 'sentence'})\n country2city = {\n 'Albania': 'Durres',\n 'Argentina': 'Salta',\n 'Australia': 'Sydney',\n 'Dominican': 'Republic\tSantiago',\n 'England': 'Liverpool',\n 'Finland': 'Turku',\n 'France': 'Lyon',\n 'Germany': 'Munich',\n 'Greece': 'Thessaloniki',\n 'Guadeloupe': 'Lamentin',\n 'Indonesia': 'Makassar',\n 'India': 'Mumbai',\n 'Iraq': 'Erbil',\n 'Israel': 'Haifa',\n 'Japan': 'Osaka',\n 'Malaysia': 'Malacca',\n 'Martinique': 'Ducos',\n 'Nepal': 'Pokhara',\n 'Netherlands': 'Rotterdam',\n 'Nicaragua': 'Leon',\n 'Philippines': 'Makati',\n 'Portugal': 'Porto',\n 'Romania': 'Oradea',\n 'South Africa': 'Durban',\n 'Sweden': 'Malmo',\n 'United Kingdom': 'Bristol',\n 'United States': 'Chicago',\n 'Vietnam': 'Dalat',\n }\n df['country'] = df['country'].apply(str.title)\n df['location'] = df['country'].apply(country2city.__getitem__)\n\n random.seed('locations!!')\n df['other_location'] = df['country'].apply(\n lambda x: random.choice(\n sorted(set(country2city.values()) - {country2city[x]})\n )\n )\n\n df['sentence'] = df.apply(\n lambda x: x.sentence[: x.start_char]\n + '{{{location}}}'\n + x.sentence[x.end_char :],\n axis=1,\n )\n\n sec2_labels = ['Neutral', 'Contradiction']\n sec2_word_types = ['Country', 'Location']\n df['section2_label'] = [sec2_labels[i % 2] for i in range(len(df))]\n df['section2_word_type'] = [\n sec2_word_types[(i // 2) % 2] for i in range(len(df))\n ]\n\n df.to_csv(outfile, index=False)\n\n\ndef get_country2cities_deduped():\n country2city = datautils.json_load(COUNTRIES_FNAME)\n\n locations_cnt = Counter()\n for country, cities in country2city.items():\n locations_cnt.update([c.lower() for c in cities + [country.lower()]])\n\n deduped_country2cities = {}\n for country, cities in country2city.items():\n if locations_cnt[country.lower()] == 1:\n deduped_country2cities[country.lower()] = [\n c.lower() for c in cities if locations_cnt[c.lower()] == 1\n ]\n return deduped_country2cities\n\n\nif __name__ == '__main__':\n cbox.main(\n [\n extract_mnli_locations,\n download_locations,\n extract_mnli_sentences_with_locations,\n create_sentences_pool_for_filtering,\n finalize_sentences_for_tagging,\n ]\n )\n","sub_path":"scripts/locations.py","file_name":"locations.py","file_ext":"py","file_size_in_byte":14349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"577861386","text":"'''\nFind the 15th term of the series?\n\n0,0,7,6,14,12,21,18, 28\n\nExplanation : In this series the odd term is increment of 7 {0, 7, 14, 21, 28, 35 – – – – – – }\n\n And even term is a increment of 6 {0, 6, 12, 18, 24, 30 – – – – – – }\n'''\n\n\nnum = int(input('enter the number: '))\n\na=0\n\nb=0\n\nfor i in range(1,num+1):\n\n if(i%2!=0):\n\n a= a+7\n\n else:\n\n b = b+6\n\nif(num%2!=0):\n\n print(' {} term of series is {}'.format(num,a-7))\n\nelse:\n\n print('{} term of series is {}'.format(num,b-6))\n","sub_path":"Codes/Number_Series_with_a_Twist.py","file_name":"Number_Series_with_a_Twist.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"299222003","text":"\"\"\"Test Axis component setup process.\"\"\"\nfrom unittest.mock import AsyncMock, Mock, patch\n\nimport pytest\n\nfrom homeassistant.components import axis\nfrom homeassistant.components.axis.const import DOMAIN as AXIS_DOMAIN\nfrom homeassistant.setup import async_setup_component\n\n\nasync def test_setup_no_config(hass):\n \"\"\"Test setup without configuration.\"\"\"\n assert await async_setup_component(hass, AXIS_DOMAIN, {})\n assert AXIS_DOMAIN not in hass.data\n\n\nasync def test_setup_entry(hass, setup_config_entry):\n \"\"\"Test successful setup of entry.\"\"\"\n assert len(hass.data[AXIS_DOMAIN]) == 1\n assert setup_config_entry.entry_id in hass.data[AXIS_DOMAIN]\n\n\nasync def test_setup_entry_fails(hass, config_entry):\n \"\"\"Test successful setup of entry.\"\"\"\n mock_device = Mock()\n mock_device.async_setup = AsyncMock(return_value=False)\n\n with patch.object(axis, \"AxisNetworkDevice\") as mock_device_class:\n mock_device_class.return_value = mock_device\n\n assert not await hass.config_entries.async_setup(config_entry.entry_id)\n\n assert not hass.data[AXIS_DOMAIN]\n\n\nasync def test_unload_entry(hass, setup_config_entry):\n \"\"\"Test successful unload of entry.\"\"\"\n assert hass.data[AXIS_DOMAIN]\n\n assert await hass.config_entries.async_unload(setup_config_entry.entry_id)\n assert not hass.data[AXIS_DOMAIN]\n\n\n@pytest.mark.parametrize(\"config_entry_version\", [1])\nasync def test_migrate_entry(hass, config_entry):\n \"\"\"Test successful migration of entry data.\"\"\"\n assert config_entry.version == 1\n\n mock_device = Mock()\n mock_device.async_setup = AsyncMock()\n mock_device.async_update_device_registry = AsyncMock()\n mock_device.api.vapix.light_control = None\n mock_device.api.vapix.params.image_format = None\n\n with patch.object(axis, \"get_axis_device\"), patch.object(\n axis, \"AxisNetworkDevice\"\n ) as mock_device_class:\n mock_device_class.return_value = mock_device\n\n assert await hass.config_entries.async_setup(config_entry.entry_id)\n\n assert hass.data[AXIS_DOMAIN]\n assert config_entry.version == 3\n","sub_path":"tests/components/axis/test_init.py","file_name":"test_init.py","file_ext":"py","file_size_in_byte":2093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"484989589","text":"import logging, numpy as np, sys, urllib2\nfrom django.core.cache import cache\nfrom PIL import Image\n\ntry:\n from scipy import ndimage\nexcept:\n from scipy_local import ndimage\n\ntry:\n from cStringIO import StringIO\nexcept:\n from StringIO import StringIO\n\nlogger = logging.getLogger('react')\n\n\ndef rgb_histogram(im):\n r = np.asarray(im.convert('RGB', (1,0,0,0, 1,0,0,0, 1,0,0,0) ))\n g = np.asarray(im.convert('RGB', (0,1,0,0, 0,1,0,0, 0,1,0,0) ))\n b = np.asarray(im.convert('RGB', (0,0,1,0, 0,0,1,0, 0,0,1,0) ))\n hr, hr_bins = np.histogram(r, bins=256, density=True)\n hg, hg_bins = np.histogram(g, bins=256, density=True)\n hb, hb_bins = np.histogram(b, bins=256, density=True)\n h_rgb = np.array([hr, hg, hb]).ravel()\n return h_rgb\n\ndef extract_features(cache_key, url, feature_list=['rgb_histogram']):\n if url:\n logger.debug('extracting features for document at: %s' % url)\n response = urllib2.urlopen(url)\n im = Image.open(StringIO(response.read()))\n feature_dict = cache.get(cache_key, { }) \n\n for feature in feature_list:\n feature_dict[feature] = getattr(sys.modules[__name__], feature)(im) \n cache.set(cache_key, feature_dict)\n\ndef filter(results, source, relevant_docs, irrelevant_docs, feature):\n if feature == 'rgb_histogram':\n distances = { }\n distances_irrelevant = { }\n for photo_id in relevant_docs:\n distances[photo_id] = []\n cache_key = '%s-%s' % (source, photo_id)\n features = cache.get(cache_key)\n ft_1 = features[feature]\n \n for p in results:\n c_key = '%s-%s' % (source, p.get('id'))\n featurez = cache.get(c_key)\n ft_2 = featurez[feature]\n diff = ft_1 - ft_2\n distances[photo_id].append(np.sqrt(np.dot(diff, diff)))\n cum_r_distances = map(sum, zip(*distances.values()))\n if len(cum_r_distances) == 0:\n cum_r_distances = [1.0] * len(results)\n # normalize\n v_max = max(cum_r_distances)\n cum_r_distances = [ x / (v_max * 1.0) for x in cum_r_distances]\n cum_r_distances = [1.0-x for x in cum_r_distances]\n\n for photo_id in irrelevant_docs:\n distances_irrelevant[photo_id] = []\n cache_key = '%s-%s' % (source, photo_id)\n features = cache.get(cache_key)\n ft_1 = features[feature]\n\n for p in results:\n c_key = '%s-%s' % (source, p.get('id'))\n featurez = cache.get(c_key)\n ft_2 = featurez[feature]\n diff = ft_1 - ft_2\n distances_irrelevant[photo_id].append(np.sqrt(np.dot(diff, diff)))\n cum_i_distances = map(sum, zip(*distances_irrelevant.values()))\n if len(cum_i_distances) == 0:\n cum_i_distances = [1.0] * len(results)\n # normalize\n v_max = max(cum_i_distances)\n cum_i_distances = [ x / (v_max * 1.0) for x in cum_i_distances]\n\n scores = [x*y for x,y in zip(cum_r_distances, cum_i_distances)]\n\n sortable = []\n for i, result in enumerate(results):\n sortable.append({'obj': result, 'distance': scores[i]})\n sortable = sorted(sortable, key=lambda s: s['distance'], reverse=True)\n return [s['obj'] for s in sortable] \n return results\n\n\n","sub_path":"react/features.py","file_name":"features.py","file_ext":"py","file_size_in_byte":3385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"211279926","text":"from flask_restful import Resource,reqparse\r\nfrom flask_jwt import jwt_required\r\nimport sqlite3\r\nfrom models.item import ItemModel\r\n\r\nclass Item(Resource):\r\n parser = reqparse.RequestParser()\r\n parser.add_argument('price',\r\n type= float,\r\n required=True,\r\n help=\"REQUIRED FIELD\"\r\n )\r\n parser.add_argument('store_id',\r\n type= int,\r\n required=True,\r\n help=\"REQUIRED FIELD: Store ID\"\r\n )\r\n\r\n @jwt_required()\r\n def get(self,name):\r\n item = ItemModel.find_by_name(name)\r\n if item:\r\n return item.json()\r\n return {'message:': 'Item not found'}, 404\r\n\r\n def post(self,name):\r\n if ItemModel.find_by_name(name):\r\n return {'message': 'Item with name {} already exist'.format(name)}, 400 # Bad request\r\n #req_data = request.get_json() # force=True-> donot look at header... silent=True -> return none, not give error\r\n req_data = Item.parser.parse_args()\r\n item= ItemModel(name,**req_data)\r\n try:\r\n item.save_to_db()\r\n except:\r\n return {\"message:\": \"ERROR INSERTING\"}, 500 #Internal Server ERROR\r\n return item.json(), 201 # code for created, 202 is for accepted the request.\r\n \r\n def delete(self,name):\r\n '''conn = sqlite3.connect('data.db')\r\n\r\n cur = conn.cursor()\r\n\r\n query = \"delete from items where name=?\"\r\n \r\n cur.execute(query, (name,))\r\n conn.commit()\r\n conn.close()\r\n return {'message': 'Item Deleted !!!'}'''\r\n item = ItemModel.find_by_name(name)\r\n if item:\r\n item.delete_from_db()\r\n return {'message: ': 'Item Deleted'}\r\n return {'message: ' : 'Item not found'},404\r\n\r\n def put(self,name):\r\n data = Item.parser.parse_args() # other argument than price will not be used.\r\n\r\n item = ItemModel.find_by_name(name)\r\n #updated_item = ItemModel( name, data['price'])\r\n if item is None:\r\n #try:\r\n # updated_item.insert()\r\n #except:\r\n # return {\"message:\": \"error sds\"}\r\n item = ItemModel(name,**data)\r\n else:\r\n '''try:\r\n updated_item.update()\r\n except:\r\n return {\"message:\": \"error updating\"}'''\r\n item.price = data['price']\r\n\r\n item.save_to_db()\r\n return item.json()\r\n \r\n\r\nclass ItemList(Resource):\r\n def get(self):\r\n return {'items:': list(map(lambda x: x.json(), ItemModel.query.all()))}\r\n #return {'items' : [item.json() for item in ItemModel.query.all()]}\r\n \"\"\"conn = sqlite3.connect('data.db')\r\n\r\n cur = conn.cursor()\r\n\r\n query = \"Select * from items\"\r\n \r\n result = cur.execute(query)\r\n items = []\r\n\r\n for row in result:\r\n items.append({'name':row[0],'price':row[1]})\r\n conn.commit()\r\n conn.close()\r\n return {'ITEM': items}\"\"\"\r\n\r\n ","sub_path":"resources/item.py","file_name":"item.py","file_ext":"py","file_size_in_byte":2974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"151416703","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom django.core.paginator import Paginator, InvalidPage\nfrom django.contrib.sites.models import get_current_site\nfrom django.utils import timezone\nfrom django.http import Http404\nfrom django.conf import settings\n\nfrom haystack.views import SearchView\n\nfrom opps.articles.models import Post, Album, Article\nfrom opps.articles.views.generic import OppsDetail, OppsList\nfrom opps.articles.models import ArticleBox\n\n\nclass PostList(OppsList):\n models = settings.OPPS_LIST_MODELS\n type = \"channels\"\n\n def get_template_names(self):\n \"\"\"\n Implemented here for backwards compatibility\n \"\"\"\n names = super(PostList, self).get_template_names()\n domain_folder = self.get_template_folder()\n aditional_names = [\n '{}/post_list.html'.format(domain_folder),\n 'articles/post_list.html'\n ]\n if self.paginate_suffix:\n aditional_names = [\n '{}/post_list_paginated.html'.format(domain_folder),\n 'articles/post_list_paginated.html'\n ]\n names = names + aditional_names\n return names\n\n @property\n def queryset(self):\n self.site = get_current_site(self.request).domain\n self.long_slug = self.get_long_slug()\n\n if not self.long_slug:\n return None\n\n self.set_channel_rules()\n\n self.articleboxes = ArticleBox.objects.filter(\n channel__long_slug=self.long_slug)\n\n self.excluded_ids = []\n for box in self.articleboxes:\n self.excluded_ids += [a.pk for a in box.ordered_articles()]\n\n self.article = Article.objects.filter(\n site_domain=self.site,\n channel_long_slug__in=self.channel_long_slug,\n date_available__lte=timezone.now(),\n published=True,\n child_class__in=self.models,\n show_on_root_channel=True\n ).exclude(pk__in=self.excluded_ids)\n if self.limit:\n self.article = self.article[:self.limit]\n\n return self.article\n\n\nclass PostDetail(OppsDetail):\n model = Post\n type = 'articles'\n\n\nclass AlbumList(OppsList):\n model = Album\n type = \"channels/album\"\n\n\nclass AlbumDetail(OppsDetail):\n model = Album\n type = 'articles/album'\n\n\nclass TagList(OppsList):\n model = Article\n type = \"tags\"\n template_name_suffix = '_tags'\n channel_long_slug = []\n channel = None\n\n @property\n def queryset(self):\n self.site = get_current_site(self.request).domain\n self.long_slug = self.kwargs['tag']\n self.article = self.model.objects.filter(\n site_domain=self.site,\n tags__slug=self.long_slug,\n date_available__lte=timezone.now(),\n published=True).all()\n return self.article\n\n\nclass Search(SearchView):\n def get_results(self):\n return self.form.search().order_by('-date_available')\n\n def build_page(self):\n paginator = Paginator(self.results, self.results_per_page)\n try:\n paginator.page(int(self.request.GET.get('page', 1)))\n except InvalidPage:\n raise Http404(\"No such page!\")\n\n return (None, self.results)\n","sub_path":"opps/articles/views/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"292454945","text":"import MyCustomGFNeuronClass\nimport numpy as np\nimport scipy as sp\nimport collections\nimport statistics as stat\nimport jsonNeurons as JN\nimport colour\nimport GetAnnotationsRemoveExtraneousInfo\nimport getSkeletonNodesNew as GN\nimport GetGF1Connectivity as GC\nimport pandas\nimport config\nimport exportToCSV as E2C\nimport clusteringAlgorithms\nimport csv\nimport requests\nimport json\nimport itertools\nfrom requests.auth import AuthBase\nfrom collections import defaultdict\nfrom copy import copy, deepcopy\n\ntoken = config.token\nproject_id = config.project_id\n\n\nclass CatmaidApiTokenAuth(AuthBase):\n \"\"\"Attaches HTTP X-Authorization Token headers to the given Request.\"\"\"\n\n def __init__(self, token):\n self.token = token\n\n def __call__(self, r):\n r.headers['X-Authorization'] = 'Token {}'.format(self.token)\n return r\n\n\nclass GFIN_set(object):\n\n def __init__(self, container=None):\n super().__init__()\n if container is None:\n self.container = []\n else:\n self.container = container\n\n self.skeletonID = 4947529\n self.AllGF1Synapses = self._GF1Synapses()\n self.AllGF2Synapses = self._GF2Synapses()\n self.percentTotalSynapses = self._setPercentTotalSynapses()\n self.numNeurons = self._getNumNeurons()\n self.groupName = None\n # self.averageSyn = self._avgSyn()\n self.medianSyn = None\n self.minSyn = None\n self.maxSyn = None\n self.connectorInfo = None # should be a dictionary with the branches as keys and connectorIDs as values\n self.numSynapsesByBranch = None\n self.allSynapseCoordinates = None # will be filled with the coordinate points in format: {conID:x,y,z}\n self.allAnnotations = self._setAllAnnotations()\n self.varCheck = []\n self.allConnectorInfo = None\n self.branchCoordinates = None\n self.neuroDistroAdvanced = []\n self.modality = None\n self.BiUni = None\n self.IpsiContraMid = None\n self.groupNumber = None\n self.morphology = None\n\n def __len__(self):\n return len(self.container)\n\n # allows for indexing/slicing using either the index (nums lessthan 10,000) or the skid(nums greater than 10,000)\n def __getitem__(self, index):\n if isinstance(index, int):\n if index < 10000:\n return self.container[index]\n else:\n for i in self:\n if i.skeletonID == index:\n return i\n # returns subset of type GFIN_set\n elif isinstance(index, slice):\n x = GFIN_set(self.container[index])\n return x\n else:\n raise TypeError\n\n def __setitem__(self, index, value):\n if index <= len(self.container):\n self.container[index] = value\n else:\n raise IndexError()\n\n def __getslice__(self, i, j):\n return self.container[max(0, i):max(0, j):]\n\n def __contains__(self, value):\n return value in self.container\n\n def __repr__(self):\n return str(self.container)\n\n def __add__(self, otherList):\n myList = []\n for i in self.container:\n myList.append(i)\n if isinstance(otherList, MyCustomGFNeuronClass.GFinputNeuron):\n myList.append(otherList)\n added = subSetBuilder(myList)\n for i in vars(self).keys():\n if i is not 'numNeurons' and i is not 'container' and i is not 'percentTotalSynapses':\n setattr(added, i, getattr(self, i))\n return added\n else:\n for i in otherList.container:\n myList.append(i)\n added = subSetBuilder(myList)\n for i in vars(self).keys():\n if i is not 'numNeurons' and i is not 'container' and 'percent' not in i:\n setattr(added, i, getattr(self, i))\n if self.groupName != None:\n if otherList.groupName != None:\n added.groupName = str(self.groupName) + str(otherList.groupName)\n return added\n else:\n added.groupName = str(self.groupName)\n return added\n elif otherList.groupName != None:\n added.groupName = str(otherList.groupName)\n return added\n\n return added\n\n def __sub__(self, otherList):\n myList = []\n for i in self.container:\n myList.append(i)\n if isinstance(otherList, MyCustomGFNeuronClass.GFinputNeuron):\n myList.remove(otherList)\n else:\n for i in otherList.container:\n myList.remove(i)\n subtracted = subSetBuilder(myList)\n return subtracted\n\n '''def append(self, argument):\n if isinstance(argument, int):\n self += argument\n elif isinstance(argument, slice):\n pass\n pass'''\n\n # input should be skeletonID of neuron of interest, function returns the index that can be called on neuron set to get info about that\n # neuron\n def index(self, skeletonID):\n count = 0\n for i in self:\n if i.skeletonID == skeletonID:\n return count\n elif not isinstance(skeletonID, int):\n print(\"Index only for integers\")\n break\n else:\n count += 1\n\n def __str__(self):\n this = \"\"\n for item in self:\n this += str(item)\n this += \"\\n\"\n return this\n\n '''def __str__(self.connectorInfo):\n anteriorCount = len(self.ConnectorInfo['anterior'])\n medialCount = len(self.ConnectorInfo['medial'])\n lateralCount = len(self.ConnectorInfo['lateral'])\n somaTractCount = len(self.ConnectorInfo['soma tact'])\n \n myString = 'Anterior Synapse Count: {}, medial Synapse count: {}, lateral Synapse Count: {}, soma synapse Count: {}'.format(anteriorCount, medialCount, lateralCount, somaTractCount)\n return myString'''\n\n # Sets total GF1 Synapse Count\n def _GF1Synapses(self):\n curSyn = 0\n for item in self:\n curSyn += item.GF1synapseCount\n return curSyn\n\n # Sets total GF2 Synapse Count\n def _GF2Synapses(self):\n curSyn = 0\n for item in self:\n curSyn += item.GF2synapseCount\n return curSyn\n\n # returns the number of neurons in the current group\n def _getNumNeurons(self):\n numNeurons = len(self)\n return numNeurons\n\n # returns the percentCount of any constructed GFIN_set (if not == 99.99%: probably a bug in code); also sets the initial percent total\n # synapses for each individual neuron object, and then checks whether or not their PTS is not zero, so as to avoid resetting to percent\n # synapses of current group\n def _setPercentTotalSynapses(self):\n percentCount = 0\n for item in self:\n if item.percentTotalSynapse != 0:\n item.percentCurrentGroup = item.GF1synapseCount / self.AllGF1Synapses\n percentCount += item.percentTotalSynapse\n elif self.AllGF1Synapses == 0:\n item.percentTotalSynapse = 0\n percentCount += item.percentTotalSynapse\n else:\n item.percentTotalSynapse = item.GF1synapseCount / self.AllGF1Synapses\n percentCount += item.percentTotalSynapse\n return percentCount\n\n def _avgSyn(self):\n myAvgLst = []\n myAvg = 0\n for i in self:\n myAvgLst.append(i.GF1synapseCount)\n myAvg = stat.mean(myAvgLst)\n # self.averageSyn = myAvg\n return myAvg\n\n def _medSyn(self):\n myMedLst = []\n myMed = 0\n for i in self:\n myMedLst.append(i.GF1synapseCount)\n myMed = stat.median(myMedLst)\n self.medianSyn = myMed\n return myMed\n\n def _setAllAnnotations(self):\n annotationList = []\n for neuron in self:\n for annotation in neuron.annotations:\n if annotation not in annotationList and 'type' not in annotation:\n annotationList.append(annotation)\n return annotationList\n\n def minMax(self):\n myOrderedList = sortBySynH2L(self)\n self.minSyn = myOrderedList[-1].GF1synapseCount\n self.maxSyn = myOrderedList[0].GF1synapseCount\n return self\n\n # provides all neurons in the set with a list of x,y,z coordinates for their respective soma attributes. not part of builder because it can be computationally heavy (i.e. many server requests so slow)\n def updateSomata(self):\n for i in self:\n if i.soma is None:\n i.soma = i.getSomaNode()\n else:\n continue\n self.varCheck.append('soma')\n return self\n\n # input is an object of type GFIN_set and result is population of the skeletonNodes attribute for each GFinput neuron in the set\n def updateSkeletonNodes(self):\n for i in self:\n if i.skeletonNodes is None:\n i.getSkeletonNodes()\n else:\n continue\n self.varCheck.append('skeletonNodes')\n return self\n\n def getConnectors(self):\n myBranches = ['lateral', 'medial', 'anterior', 'soma tract', 'descending tract']\n myConnectors = {}\n myConCount = {}\n connectorInfo = GN.getAllConnectorInfo()\n while len(myBranches) is not 0:\n branch = myBranches.pop()\n myConnectors[branch] = GN.getConnectorsByBranch(branch=branch, connectorInfo=connectorInfo)\n myConCount[branch] = len(myConnectors[branch])\n self.connectorInfo = myConnectors\n self.numSynapsesByBranch = myConCount\n self.varCheck.append('connectors')\n return self\n\n\n def getConnectorInfo(self, polarity='postsynaptic'):\n self.allConnectorInfo = getAllConnectorInfo(skeletonID=self.skeletonID, polarity=polarity)\n return self.allConnectorInfo\n\n def getBranchCoordinates(self):\n self.branchCoordinates = findBranchCoordinates(self)\n return self.branchCoordinates\n\n\n\n def getNumPartnersBySkid(self):\n myLC4List = []\n myLPLC2List = []\n myLPC1List = []\n myLPLC1List = []\n\n for neuron in self:\n if 'putative LC4 neuron' in neuron.annotations:\n myLC4List.append(str(neuron.skeletonID))\n if 'LPLC2' in neuron.annotations:\n myLPLC2List.append(str(neuron.skeletonID))\n # if 'Postsynaptic to LPLC1' in neuron.annotations:\n # myLPLC1List.append(str(neuron.skeletonID))\n # if 'postsynaptic to LPC1' in neuron.annotations:\n # myLPC1List.append(str(neuron.skeletonID))\n\n for i in self:\n a = None\n b = None\n c = None\n d = None\n if 'postsynaptic to LC6' in i.annotations:\n countOfLC6SynapsesOntoMyNeuron = 0\n d = {}\n a = GC.getSkeletonPartners(int(i.skeletonID))\n b = a['incoming'] # dict of key = SKID that is presynaptic : value = myNeuronSkid:[0,0,0,0,#synapses]\n c = list(b.keys()) # list of skeletonIDs that are presynaptic to neuron\n listOfLC6 = GetAnnotationsRemoveExtraneousInfo.getListOfSkID_int(annotation=3489456)\n strListOfLC6 = []\n for x in listOfLC6:\n strListOfLC6.append(str(x))\n\n for item in c:\n if item in strListOfLC6:\n d[item] = b[item]['skids'][str(i.skeletonID)][4]\n countOfLC6SynapsesOntoMyNeuron += d[item]\n i.postsynapticToLC6 = countOfLC6SynapsesOntoMyNeuron\n\n if 'Postsynaptic to LC4' in i.annotations:\n countOfLC4SynapsesOntoMyNeuron = 0\n if a is None:\n a = GC.getSkeletonPartners(int(i.skeletonID))\n b = a[\n 'incoming'] # dict of key = SKID that is presynaptic : value = myNeuronSkid:[0,0,0,0,#synapses]\n c = list(b.keys()) # list of skeletonIDs that are presynaptic to neuron\n d = {}\n for item in c:\n if item in myLC4List:\n d[item] = b[item]['skids'][str(i.skeletonID)][4]\n countOfLC4SynapsesOntoMyNeuron += d[item]\n i.postsynapticToLC4 = countOfLC4SynapsesOntoMyNeuron\n if 'Postsynaptic to LPLC2' in i.annotations:\n countOfLPLC2SynapsesOntoMyNeuron = 0\n if a is None:\n a = GC.getSkeletonPartners(int(i.skeletonID))\n b = a[\n 'incoming'] # dict of key = SKID that is presynaptic : value = myNeuronSkid:[0,0,0,0,#synapses]\n c = list(b.keys()) # list of skeletonIDs that are presynaptic to neuron\n d = {}\n for item in c:\n if item in myLPLC2List:\n d[item] = b[item]['skids'][str(i.skeletonID)][4]\n countOfLPLC2SynapsesOntoMyNeuron += d[item]\n i.postsynapticToLPLC2 = countOfLPLC2SynapsesOntoMyNeuron\n\n # putative LPLC1 = 6022624\n if 'Postsynaptic to LPLC1' in i.annotations:\n countOfLPLC1SynapsesOntoMyNeuron = 0\n if a is None:\n a = GC.getSkeletonPartners(int(i.skeletonID))\n b = a[\n 'incoming'] # dict of key = SKID that is presynaptic : value = myNeuronSkid:[0,0,0,0,#synapses]\n c = list(b.keys()) # list of skeletonIDs that are presynaptic to neuron\n d = {}\n listOfLPLC1 = GetAnnotationsRemoveExtraneousInfo.getListOfSkID_int(annotation=6022624)\n strListOfLPLC1 = []\n for x in listOfLPLC1:\n strListOfLPLC1.append(str(x))\n for item in c:\n if item in strListOfLPLC1:\n d[item] = b[item]['skids'][str(i.skeletonID)][4]\n countOfLPLC1SynapsesOntoMyNeuron += d[item]\n i.postsynapticToLPLC1 = countOfLPLC1SynapsesOntoMyNeuron\n\n # putative LPC1 = 2894936\n if 'postsynaptic to LPC1' in i.annotations:\n countOfLPC1SynapsesOntoMyNeuron = 0\n if a is None:\n a = GC.getSkeletonPartners(int(i.skeletonID))\n b = a[\n 'incoming'] # dict of key = SKID that is presynaptic : value = myNeuronSkid:[0,0,0,0,#synapses]\n c = list(b.keys()) # list of skeletonIDs that are presynaptic to neuron\n\n listOfLPC1 = GetAnnotationsRemoveExtraneousInfo.getListOfSkID_int(annotation=2894936)\n strListOfLPC1 = []\n for x in listOfLPC1:\n strListOfLPC1.append(str(x))\n d = {}\n for item in c:\n if item in strListOfLPC1:\n d[item] = b[item]['skids'][str(i.skeletonID)][4]\n countOfLPC1SynapsesOntoMyNeuron += d[item]\n i.postsynapticToLPC1 = countOfLPC1SynapsesOntoMyNeuron\n\n if 'Postsynaptic to LC28' in i.annotations:\n countOfLC28SynapsesOntoMyNeuron = 0\n if a is None:\n a = GC.getSkeletonPartners(int(i.skeletonID))\n b = a[\n 'incoming'] # dict of key = SKID that is presynaptic : value = myNeuronSkid:[0,0,0,0,#synapses] \n c = list(b.keys()) # list of skeletonIDs that are presynaptic to neuron\n\n listOfLC28 = GetAnnotationsRemoveExtraneousInfo.getListOfSkID_int(annotation=2894936)\n strListOfLC28 = []\n for x in listOfLC28:\n strListOfLC28.append(str(x))\n d = {}\n for item in c:\n if item in strListOfLC28:\n d[item] = b[item]['skids'][str(i.skeletonID)][4]\n countOfLC28SynapsesOntoMyNeuron += d[item]\n i.postsynapticToLC28 = countOfLC28SynapsesOntoMyNeuron\n\n if 'postsynaptic to LLPC1' in i.annotations:\n countOfLLPC1SynapsesOntoMyNeuron = 0\n if a is None:\n a = GC.getSkeletonPartners(int(i.skeletonID))\n b = a[\n 'incoming'] # dict of key = SKID that is presynaptic : value = myNeuronSkid:[0,0,0,0,#synapses] \n c = list(b.keys()) # list of skeletonIDs that are presynaptic to neuron\n\n listOfLLPC1 = GetAnnotationsRemoveExtraneousInfo.getListOfSkID_int(annotation=2894936)\n strListOfLLPC1 = []\n for x in listOfLLPC1:\n strListOfLLPC1.append(str(x))\n d = {}\n for item in c:\n if item in strListOfLLPC1:\n d[item] = b[item]['skids'][str(i.skeletonID)][4]\n countOfLLPC1SynapsesOntoMyNeuron += d[item]\n i.postsynapticToLLPC1 = countOfLLPC1SynapsesOntoMyNeuron\n\n if 'Postsynaptic to LPLC3' in i.annotations:\n countOfLPLC3SynapsesOntoMyNeuron = 0\n if a is None:\n a = GC.getSkeletonPartners(int(i.skeletonID))\n b = a[\n 'incoming'] # dict of key = SKID that is presynaptic : value = myNeuronSkid:[0,0,0,0,#synapses] \n c = list(b.keys()) # list of skeletonIDs that are presynaptic to neuron\n\n listOfLPLC3 = GetAnnotationsRemoveExtraneousInfo.getListOfSkID_int(annotation=2894936)\n strListOfLPLC3 = []\n for x in listOfLPLC3:\n strListOfLPLC3.append(str(x))\n d = {}\n for item in c:\n if item in strListOfLPLC3:\n d[item] = b[item]['skids'][str(i.skeletonID)][4]\n countOfLPLC3SynapsesOntoMyNeuron += d[item]\n i.postsynapticToLPLC3 = countOfLPLC3SynapsesOntoMyNeuron\n\n self.varCheck.append('partners')\n return self\n\n def makeJSONPlain(self):\n additionalInfo = outputAllInfo(self)\n JN.autoSaveJSONFlatColor(self, additionalInfo=additionalInfo)\n return\n\n def getAllSkeletonNodes(self):\n for i in self:\n i.getSkeletonNodes()\n self.varCheck.append('skeletonNodes')\n return self\n\n def LPLC2_LP_Filter(self):\n # myGroup = createGroupByAnnotation(self, 'LPLC2')\n\n # gets all skeletonNodes for each skeleton in the set\n self.getAllSkeletonNodes()\n\n LPnodesAvg = {}\n\n for i in self:\n if i.curColor is None:\n JN.autoSaveJSONColorGrad(self)\n\n # tests each node in a given skeleton for whether or not it is within the LP (based on a curve built from the points: (191994, 239560), (218895, 239680), (286360,230800), (318592,216920), (332166,209480) run through \"mycurvefit.com\"\n for x in self:\n LPnodes = []\n for i in x.skeletonNodes:\n if -16938980000 + (332993.6 + 16938980000) / (1.0 + (i[2] / 379562.8) ** 25.65271) <= i[1]:\n LPnodes.append(i)\n xCount = 0\n yCount = 0\n zCount = 0\n divisor = len(LPnodes)\n if divisor == 0:\n print(x.skeletonID)\n divisor = 1\n for i in LPnodes:\n xCount += i[0]\n yCount += i[1]\n zCount += i[2]\n xAvg = xCount / divisor\n yAvg = yCount / divisor\n zAvg = zCount / divisor\n LPnodesAvg[x.skeletonID] = [xAvg, yAvg, zAvg, x.curColor]\n return LPnodesAvg\n\n def colorByType(self):\n for i in self:\n if 'LC4' in i.classification:\n i.curColor = 'cyan'\n elif \"LPLC2\" in i.classification:\n i.curColor = 'yellow'\n return\n\n def colorByGradient(self):\n for i in self:\n if i.curColor is None:\n JN.autoSaveJSONColorGrad(self)\n return\n\n def getAllGFINSynByBranch(self):\n if self.connectorInfo is None:\n self.getConnectors()\n branches = ['soma tract', 'medial', 'anterior', 'lateral', 'descending tract']\n GFsynapses = self.connectorInfo\n tempCount = 0\n for i in self:\n i.getConnectorIDs()\n for item in branches:\n for x in i.connectorIDs:\n if x in GFsynapses[item]:\n tempCount += 1\n i.synLocation[x] = i.connectorIDs[x]\n i.synapsesByBranch[item] = tempCount\n tempCount = 0\n\n self.varCheck.append('synByBranch')\n return self\n\n def findNeuropils(self):\n myNeuropils = ['AL_L', 'AL_R', 'AME_L', 'AME_R', 'AMMC_L', 'AMMC_R', 'AOTU_L', 'AOTU_R', 'ATL_L', 'ATL_R',\n 'AVLP_L', 'AVLP_R', 'BU_L', 'BU_R', 'CAN_L', 'CAN_R', 'CRE_L', 'CRE_R', 'EB', 'EPA_L', 'EPA_R',\n 'FB', 'FLA_L',\n 'FLA_R', 'GA_L', 'GA_R', 'GNG', 'GOR_L', 'GOR_R', 'IB_L', 'IB_R', 'ICL_L', 'ICL_R', 'IPS_L',\n 'IPS_R',\n 'LAL_L', 'LAL_R', 'LH_L', 'LH_R', 'LO_L', 'LO_R', 'LOP_L', 'LOP_R', 'MB_CA_L', 'MB_CA_R',\n 'MB_LAC_L', 'MB_LAC_R', 'MB_ML_L', 'MB_ML_R', 'MB_PED_L', 'MB_PED_R', 'MB_VL_L', 'MB_VL_R',\n 'MB_whole_L',\n 'MB_whole_R', 'ME_L', 'ME_R', 'NO', 'PB', 'PLP_L', 'PLP_R', 'PRW', 'PVLP_L', 'PVLP_R', 'SAD',\n 'SCL_L', 'SCL_R', 'SIP_L', 'SIP_R', 'SLP_L', 'SLP_R', 'SMP_L', 'SMP_R', 'SPS_L', 'SPS_R',\n 'VES_L', 'VES_R', 'WED_L', 'WED_R']\n for i in self:\n for abc in myNeuropils:\n if abc in i.annotations:\n i.neuropils.update({abc: 1})\n else:\n i.neuropils.update({abc: 0})\n return self\n\n def findNeuropilsByDistribution(self):\n neuropils = {'AL_L': 0, 'AL_R': 0, 'AME_L': 0, 'AME_R': 0, 'AMMC_L': 0, 'AMMC_R': 0, 'AOTU_L': 0, 'AOTU_R': 0,\n 'ATL_L': 0, 'ATL_R': 0,\n 'AVLP_L': 0, 'AVLP_R': 0, 'BU_L': 0, 'BU_R': 0, 'CAN_L': 0, 'CAN_R': 0, 'CRE_L': 0, 'CRE_R': 0,\n 'EB': 0, 'EPA_L': 0, 'EPA_R': 0,\n 'FB': 0, 'FLA_L': 0,\n 'FLA_R': 0, 'GA_L': 0, 'GA_R': 0, 'GNG': 0, 'GOR_L': 0, 'GOR_R': 0, 'IB_L': 0, 'IB_R': 0,\n 'ICL_L': 0,\n 'ICL_R': 0, 'IPS_L': 0,\n 'IPS_R': 0,\n 'LAL_L': 0, 'LAL_R': 0, 'LH_L': 0, 'LH_R': 0, 'LO_L': 0, 'LO_R': 0, 'LOP_L': 0, 'LOP_R': 0,\n 'MB_CA_L': 0, 'MB_CA_R': 0,\n 'MB_LAC_L': 0, 'MB_LAC_R': 0, 'MB_ML_L': 0, 'MB_ML_R': 0, 'MB_PED_L': 0, 'MB_PED_R': 0,\n 'MB_VL_L': 0,\n 'MB_VL_R': 0,\n 'MB_whole_L': 0,\n 'MB_whole_R': 0, 'ME_L': 0, 'ME_R': 0, 'NO': 0, 'PB': 0, 'PLP_L': 0, 'PLP_R': 0, 'PRW': 0,\n 'PVLP_L': 0,\n 'PVLP_R': 0, 'SAD': 0,\n 'SCL_L': 0, 'SCL_R': 0, 'SIP_L': 0, 'SIP_R': 0, 'SLP_L': 0, 'SLP_R': 0, 'SMP_L': 0, 'SMP_R': 0,\n 'SPS_L': 0, 'SPS_R': 0,\n 'VES_L': 0, 'VES_R': 0, 'WED_L': 0, 'WED_R': 0}\n\n myNeuropils = ['AL_L', 'AL_R', 'AME_L', 'AME_R', 'AMMC_L', 'AMMC_R', 'AOTU_L', 'AOTU_R', 'ATL_L', 'ATL_R',\n 'AVLP_L', 'AVLP_R', 'BU_L', 'BU_R', 'CAN_L', 'CAN_R', 'CRE_L', 'CRE_R', 'EB', 'EPA_L', 'EPA_R',\n 'FB', 'FLA_L',\n 'FLA_R', 'GA_L', 'GA_R', 'GNG', 'GOR_L', 'GOR_R', 'IB_L', 'IB_R', 'ICL_L', 'ICL_R', 'IPS_L',\n 'IPS_R',\n 'LAL_L', 'LAL_R', 'LH_L', 'LH_R', 'LO_L', 'LO_R', 'LOP_L', 'LOP_R', 'MB_CA_L', 'MB_CA_R',\n 'MB_LAC_L', 'MB_LAC_R', 'MB_ML_L', 'MB_ML_R', 'MB_PED_L', 'MB_PED_R', 'MB_VL_L', 'MB_VL_R',\n 'MB_whole_L',\n 'MB_whole_R', 'ME_L', 'ME_R', 'NO', 'PB', 'PLP_L', 'PLP_R', 'PRW', 'PVLP_L', 'PVLP_R', 'SAD',\n 'SCL_L', 'SCL_R', 'SIP_L', 'SIP_R', 'SLP_L', 'SLP_R', 'SMP_L', 'SMP_R', 'SPS_L', 'SPS_R',\n 'VES_L', 'VES_R', 'WED_L', 'WED_R']\n distributions = {'Anterior': neuropils, 'Medial': neuropils, 'Lateral': neuropils, 'Descending': neuropils,\n 'Soma': neuropils, 'AnteriorMedial': neuropils, 'AnteriorLateral': neuropils,\n 'AnteriorSoma': neuropils, 'AnteriorDescending': neuropils, 'MedialLateral': neuropils,\n 'MedialSoma': neuropils, 'MedialDescending': neuropils,\n 'LateralSoma': neuropils, 'LateralDescending': neuropils, 'SomaDescending': neuropils,\n 'AnteriorMedialLateral': neuropils, 'AnteriorMedialSoma': neuropils,\n 'AnteriorMedialDescending': neuropils,\n 'AnteriorLateralSoma': neuropils, 'AnteriorLateralDescending': neuropils,\n 'AnteriorSomaDescending': neuropils,\n 'MedialLateralSoma': neuropils, 'MedialLateralDescending': neuropils,\n 'MedialSomaDescending': neuropils,\n 'LateralSomaDescending': neuropils,\n 'AnteriorMedialLateralSoma': neuropils, 'AnteriorMedialLateralDescending': neuropils,\n 'AnteriorMedialSomaDescending': neuropils,\n 'AnteriorLateralSomaDescending': neuropils, 'MedialLateralSomaDescending': neuropils,\n 'AllBranches': neuropils}\n\n for key in distributions.keys():\n distributions[key] = distributions['Anterior'].copy()\n\n for neuron in self:\n for abc in neuron.annotations:\n if abc in myNeuropils:\n distributions[neuron.distribution][abc] += 1\n\n self.neuroDistroAdvanced = distributions\n return\n\n '''def findBranchDistributions(self):\n\n distributions = ['Anterior', 'Medial', 'Lateral', 'Descending', 'Soma', 'AnteriorMedial', 'AnteriorLateral',\n 'AnteriorSoma', 'AnteriorDescending', 'MedialLateral', 'MedialSoma', 'MedialDescending',\n 'LateralSoma', 'LateralDescending', 'SomaDescending',\n\n 'AnteriorMedialLateral', 'AnteriorMedialSoma', 'AnteriorMedialDescending',\n 'AnteriorLateralSoma', 'AnteriorLateralDescending', 'AnteriorSomaDescending',\n 'MedialLateralSoma', 'MedialLateralDescending', 'MedialSomaDescending',\n 'LateralSomaDescending',\n\n 'AnteriorMedialLateralSoma', 'AnteriorMedialLateralDescending', 'AnteriorMedialSomaDescending',\n 'AnteriorLateralSomaDescending', 'MedialLateralSomaDescending', 'AllBranches']\n\n\n for i in self:\n if 'Input to GF1 anterior' in i.annotations and 'Input to GF1 medial' not in i.annotations and 'Input to GF1 lateral' not in i.annotations and 'Input to GF1 soma tract' not in i.annotations and 'Input to GF1 descending tract' not in i.annotations:\n i.distribution = 'Anterior'\n elif 'Input to GF1 anterior' not in i.annotations and 'Input to GF1 medial' in i.annotations and 'Input to GF1 lateral' not in i.annotations and 'Input to GF1 soma tract' not in i.annotations and 'Input to GF1 descending tract' not in i.annotations:\n i.distribution = 'Medial'\n elif 'Input to GF1 anterior' not in i.annotations and 'Input to GF1 medial' not in i.annotations and 'Input to GF1 lateral' in i.annotations and 'Input to GF1 soma tract' not in i.annotations and 'Input to GF1 descending tract' not in i.annotations:\n i.distribution = 'Lateral'\n elif 'Input to GF1 anterior' not in i.annotations and 'Input to GF1 medial' not in i.annotations and 'Input to GF1 lateral' not in i.annotations and 'Input to GF1 soma tract' in i.annotations and 'Input to GF1 descending tract' not in i.annotations:\n i.distribution = 'Soma'\n elif 'Input to GF1 anterior' not in i.annotations and 'Input to GF1 medial' not in i.annotations and 'Input to GF1 lateral' not in i.annotations and 'Input to GF1 soma tract' not in i.annotations and 'Input to GF1 descending tract' in i.annotations:\n i.distribution = 'Descending'\n\n elif 'Input to GF1 anterior' in i.annotations and 'Input to GF1 medial' in i.annotations and 'Input to GF1 lateral' not in i.annotations and 'Input to GF1 soma tract' not in i.annotations and 'Input to GF1 descending tract' not in i.annotations:\n i.distribution = 'AnteriorMedial'\n elif 'Input to GF1 anterior' in i.annotations and 'Input to GF1 medial' not in i.annotations and 'Input to GF1 lateral' in i.annotations and 'Input to GF1 soma tract' not in i.annotations and 'Input to GF1 descending tract' not in i.annotations:\n i.distribution = 'AnteriorLateral'\n elif 'Input to GF1 anterior' in i.annotations and 'Input to GF1 medial' not in i.annotations and 'Input to GF1 lateral' not in i.annotations and 'Input to GF1 soma tract' in i.annotations and 'Input to GF1 descending tract' not in i.annotations:\n i.distribution = 'AnteriorSoma'\n elif 'Input to GF1 anterior' in i.annotations and 'Input to GF1 medial' not in i.annotations and 'Input to GF1 lateral' not in i.annotations and 'Input to GF1 soma tract' not in i.annotations and 'Input to GF1 descending tract' in i.annotations:\n i.distribution = 'AnteriorDescending'\n\n elif 'Input to GF1 anterior' not in i.annotations and 'Input to GF1 medial' in i.annotations and 'Input to GF1 lateral' in i.annotations and 'Input to GF1 soma tract' not in i.annotations and 'Input to GF1 descending tract' not in i.annotations:\n i.distribution = 'MedialLateral'\n elif 'Input to GF1 anterior' not in i.annotations and 'Input to GF1 medial' in i.annotations and 'Input to GF1 lateral' not in i.annotations and 'Input to GF1 soma tract' in i.annotations and 'Input to GF1 descending tract' not in i.annotations:\n i.distribution = 'MedialSoma'\n elif 'Input to GF1 anterior' not in i.annotations and 'Input to GF1 medial' in i.annotations and 'Input to GF1 lateral' not in i.annotations and 'Input to GF1 soma tract' not in i.annotations and 'Input to GF1 descending tract' in i.annotations:\n i.distribution = 'MedialDescending'\n\n elif 'Input to GF1 anterior' not in i.annotations and 'Input to GF1 medial' not in i.annotations and 'Input to GF1 lateral' in i.annotations and 'Input to GF1 soma tract' in i.annotations and 'Input to GF1 descending tract' not in i.annotations:\n i.distribution = 'LateralSoma'\n elif 'Input to GF1 anterior' not in i.annotations and 'Input to GF1 medial' not in i.annotations and 'Input to GF1 lateral' in i.annotations and 'Input to GF1 soma tract' not in i.annotations and 'Input to GF1 descending tract' in i.annotations:\n i.distribution = 'LateralDescending'\n\n elif 'Input to GF1 anterior' not in i.annotations and 'Input to GF1 medial' not in i.annotations and 'Input to GF1 lateral' not in i.annotations and 'Input to GF1 soma tract' in i.annotations and 'Input to GF1 descending tract' in i.annotations:\n i.distribution = 'SomaDescending'\n\n elif 'Input to GF1 anterior' in i.annotations and 'Input to GF1 medial' in i.annotations and 'Input to GF1 lateral' in i.annotations and 'Input to GF1 soma tract' not in i.annotations and 'Input to GF1 descending tract' not in i.annotations:\n i.distribution = 'AnteriorMedialLateral'\n elif 'Input to GF1 anterior' in i.annotations and 'Input to GF1 medial' in i.annotations and 'Input to GF1 lateral' not in i.annotations and 'Input to GF1 soma tract' in i.annotations and 'Input to GF1 descending tract' not in i.annotations:\n i.distribution = 'AnteriorMedialSoma'\n elif 'Input to GF1 anterior' in i.annotations and 'Input to GF1 medial' in i.annotations and 'Input to GF1 lateral' not in i.annotations and 'Input to GF1 soma tract' not in i.annotations and 'Input to GF1 descending tract' in i.annotations:\n i.distribution = 'AnteriorMedialDescending'\n elif 'Input to GF1 anterior' in i.annotations and 'Input to GF1 medial' not in i.annotations and 'Input to GF1 lateral' in i.annotations and 'Input to GF1 soma tract' in i.annotations and 'Input to GF1 descending tract' not in i.annotations:\n i.distribution = 'AnteriorLateralSoma'\n elif 'Input to GF1 anterior' in i.annotations and 'Input to GF1 medial' not in i.annotations and 'Input to GF1 lateral' in i.annotations and 'Input to GF1 soma tract' not in i.annotations and 'Input to GF1 descending tract' in i.annotations:\n i.distribution = 'AnteriorLateralDescending'\n elif 'Input to GF1 anterior' in i.annotations and 'Input to GF1 medial' not in i.annotations and 'Input to GF1 lateral' not in i.annotations and 'Input to GF1 soma tract' in i.annotations and 'Input to GF1 descending tract' in i.annotations:\n i.distribution = 'AnteriorSomaDescending'\n\n elif 'Input to GF1 anterior' not in i.annotations and 'Input to GF1 medial' in i.annotations and 'Input to GF1 lateral' in i.annotations and 'Input to GF1 soma tract' in i.annotations and 'Input to GF1 descending tract' not in i.annotations:\n i.distribution = 'MedialLateralSoma'\n elif 'Input to GF1 anterior' not in i.annotations and 'Input to GF1 medial' in i.annotations and 'Input to GF1 lateral' in i.annotations and 'Input to GF1 soma tract' not in i.annotations and 'Input to GF1 descending tract' in i.annotations:\n i.distribution = 'MedialLateralDescending'\n elif 'Input to GF1 anterior' not in i.annotations and 'Input to GF1 medial' in i.annotations and 'Input to GF1 lateral' not in i.annotations and 'Input to GF1 soma tract' in i.annotations and 'Input to GF1 descending tract' in i.annotations:\n i.distribution = 'MedialSomaDescending'\n elif 'Input to GF1 anterior' not in i.annotations and 'Input to GF1 medial' not in i.annotations and 'Input to GF1 lateral' in i.annotations and 'Input to GF1 soma tract' in i.annotations and 'Input to GF1 descending tract' in i.annotations:\n i.distribution = 'LateralSomaDescending'\n\n elif 'Input to GF1 anterior' in i.annotations and 'Input to GF1 medial' in i.annotations and 'Input to GF1 lateral' in i.annotations and 'Input to GF1 soma tract' in i.annotations and 'Input to GF1 descending tract' not in i.annotations:\n i.distribution = 'AnteriorMedialLateralSoma'\n elif 'Input to GF1 anterior' in i.annotations and 'Input to GF1 medial' in i.annotations and 'Input to GF1 lateral' in i.annotations and 'Input to GF1 soma tract' not in i.annotations and 'Input to GF1 descending tract' in i.annotations:\n i.distribution = 'AnteriorMedialLateralDescending'\n elif 'Input to GF1 anterior' in i.annotations and 'Input to GF1 medial' in i.annotations and 'Input to GF1 lateral' not in i.annotations and 'Input to GF1 soma tract' in i.annotations and 'Input to GF1 descending tract' in i.annotations:\n i.distribution = 'AnteriorMedialSomaDescending'\n elif 'Input to GF1 anterior' in i.annotations and 'Input to GF1 medial' not in i.annotations and 'Input to GF1 lateral' in i.annotations and 'Input to GF1 soma tract' in i.annotations and 'Input to GF1 descending tract' in i.annotations:\n i.distribution = 'AnteriorLateralSomaDescending'\n elif 'Input to GF1 anterior' not in i.annotations and 'Input to GF1 medial' in i.annotations and 'Input to GF1 lateral' in i.annotations and 'Input to GF1 soma tract' in i.annotations and 'Input to GF1 descending tract' in i.annotations:\n i.distribution = 'MedialLateralSomaDescending'\n\n elif 'Input to GF1 anterior' in i.annotations and 'Input to GF1 medial' in i.annotations and 'Input to GF1 lateral' in i.annotations and 'Input to GF1 soma tract' in i.annotations and 'Input to GF1 descending tract' in i.annotations:\n i.distribution = 'AllBranches'\n\n return'''\n\n def findBranchDistributions(self):\n\n for neuron in self:\n neuron.synapsesByBranch['medial']\n neuron.synapsesByBranch['lateral']\n neuron.synapsesByBranch['descending tract']\n neuron.synapsesByBranch['soma tract']\n neuron.synapsesByBranch['anterior']\n\n for neuron in self:\n if neuron.synapsesByBranch['medial'] > 0 and neuron.synapsesByBranch['anterior'] is 0 and \\\n neuron.synapsesByBranch['descending tract'] is 0 and neuron.synapsesByBranch['lateral'] is 0 and \\\n neuron.synapsesByBranch['soma tract'] is 0:\n neuron.distribution = 'Medial'\n elif neuron.synapsesByBranch['medial'] is 0 and neuron.synapsesByBranch['anterior'] > 0 and \\\n neuron.synapsesByBranch['descending tract'] is 0 and neuron.synapsesByBranch['lateral'] is 0 and \\\n neuron.synapsesByBranch['soma tract'] is 0:\n neuron.distribution = 'Anterior'\n elif neuron.synapsesByBranch['medial'] is 0 and neuron.synapsesByBranch['anterior'] is 0 and \\\n neuron.synapsesByBranch['descending tract'] > 0 and neuron.synapsesByBranch['lateral'] is 0 and \\\n neuron.synapsesByBranch['soma tract'] is 0:\n neuron.distribution = 'Descending'\n if neuron.synapsesByBranch['medial'] is 0 and neuron.synapsesByBranch['anterior'] is 0 and \\\n neuron.synapsesByBranch['descending tract'] is 0 and neuron.synapsesByBranch['lateral'] > 0 and \\\n neuron.synapsesByBranch['soma tract'] is 0:\n neuron.distribution = 'Lateral'\n elif neuron.synapsesByBranch['medial'] is 0 and neuron.synapsesByBranch['anterior'] is 0 and \\\n neuron.synapsesByBranch['descending tract'] is 0 and neuron.synapsesByBranch['lateral'] is 0 and \\\n neuron.synapsesByBranch['soma tract'] > 0:\n neuron.distribution = 'Soma'\n\n elif neuron.synapsesByBranch['medial'] > 0 and neuron.synapsesByBranch['anterior'] > 0 and \\\n neuron.synapsesByBranch['descending tract'] is 0 and neuron.synapsesByBranch['lateral'] is 0 and \\\n neuron.synapsesByBranch['soma tract'] is 0:\n neuron.distribution = 'AnteriorMedial'\n elif neuron.synapsesByBranch['medial'] is 0 and neuron.synapsesByBranch['anterior'] > 0 and \\\n neuron.synapsesByBranch['descending tract'] is 0 and neuron.synapsesByBranch['lateral'] > 0 and \\\n neuron.synapsesByBranch['soma tract'] is 0:\n neuron.distribution = 'AnteriorLateral'\n elif neuron.synapsesByBranch['medial'] is 0 and neuron.synapsesByBranch['anterior'] > 0 and \\\n neuron.synapsesByBranch['descending tract'] is 0 and neuron.synapsesByBranch['lateral'] is 0 and \\\n neuron.synapsesByBranch['soma tract'] > 0:\n neuron.distribution = 'AnteriorSoma'\n elif neuron.synapsesByBranch['medial'] is 0 and neuron.synapsesByBranch['anterior'] > 0 and \\\n neuron.synapsesByBranch['descending tract'] > 0 and neuron.synapsesByBranch['lateral'] is 0 and \\\n neuron.synapsesByBranch['soma tract'] is 0:\n neuron.distribution = 'AnteriorDescending'\n\n elif neuron.synapsesByBranch['medial'] > 0 and neuron.synapsesByBranch['anterior'] is 0 and \\\n neuron.synapsesByBranch['descending tract'] is 0 and neuron.synapsesByBranch['lateral'] > 0 and \\\n neuron.synapsesByBranch['soma tract'] is 0:\n neuron.distribution = 'MedialLateral'\n elif neuron.synapsesByBranch['medial'] > 0 and neuron.synapsesByBranch['anterior'] is 0 and \\\n neuron.synapsesByBranch['descending tract'] is 0 and neuron.synapsesByBranch['lateral'] is 0 and \\\n neuron.synapsesByBranch['soma tract'] > 0:\n neuron.distribution = 'MedialSoma'\n elif neuron.synapsesByBranch['medial'] > 0 and neuron.synapsesByBranch['anterior'] is 0 and \\\n neuron.synapsesByBranch['descending tract'] > 0 and neuron.synapsesByBranch['lateral'] is 0 and \\\n neuron.synapsesByBranch['soma tract'] is 0:\n neuron.distribution = 'MedialDescending'\n\n elif neuron.synapsesByBranch['medial'] is 0 and neuron.synapsesByBranch['anterior'] is 0 and \\\n neuron.synapsesByBranch['descending tract'] is 0 and neuron.synapsesByBranch['lateral'] > 0 and \\\n neuron.synapsesByBranch['soma tract'] > 0:\n neuron.distribution = 'LateralSoma'\n elif neuron.synapsesByBranch['medial'] is 0 and neuron.synapsesByBranch['anterior'] is 0 and \\\n neuron.synapsesByBranch['descending tract'] > 0 and neuron.synapsesByBranch['lateral'] > 0 and \\\n neuron.synapsesByBranch['soma tract'] is 0:\n neuron.distribution = 'LateralDescending'\n\n elif neuron.synapsesByBranch['medial'] is 0 and neuron.synapsesByBranch['anterior'] is 0 and \\\n neuron.synapsesByBranch['descending tract'] > 0 and neuron.synapsesByBranch['lateral'] is 0 and \\\n neuron.synapsesByBranch['soma tract'] > 0:\n neuron.distribution = 'SomaDescending'\n\n elif neuron.synapsesByBranch['medial'] > 0 and neuron.synapsesByBranch['anterior'] > 0 and \\\n neuron.synapsesByBranch['descending tract'] is 0 and neuron.synapsesByBranch['lateral'] > 0 and \\\n neuron.synapsesByBranch['soma tract'] is 0:\n neuron.distribution = 'AnteriorMedialLateral'\n elif neuron.synapsesByBranch['medial'] > 0 and neuron.synapsesByBranch['anterior'] > 0 and \\\n neuron.synapsesByBranch['descending tract'] is 0 and neuron.synapsesByBranch['lateral'] is 0 and \\\n neuron.synapsesByBranch['soma tract'] > 0:\n neuron.distribution = 'AnteriorMedialSoma'\n elif neuron.synapsesByBranch['medial'] > 0 and neuron.synapsesByBranch['anterior'] > 0 and \\\n neuron.synapsesByBranch['descending tract'] > 0 and neuron.synapsesByBranch['lateral'] is 0 and \\\n neuron.synapsesByBranch['soma tract'] is 0:\n neuron.distribution = 'AnteriorMedialDescending'\n elif neuron.synapsesByBranch['medial'] is 0 and neuron.synapsesByBranch['anterior'] > 0 and \\\n neuron.synapsesByBranch['descending tract'] is 0 and neuron.synapsesByBranch['lateral'] > 0 and \\\n neuron.synapsesByBranch['soma tract'] > 0:\n neuron.distribution = 'AnteriorLateralSoma'\n elif neuron.synapsesByBranch['medial'] is 0 and neuron.synapsesByBranch['anterior'] > 0 and \\\n neuron.synapsesByBranch['descending tract'] > 0 and neuron.synapsesByBranch['lateral'] > 0 and \\\n neuron.synapsesByBranch['soma tract'] is 0:\n neuron.distribution = 'AnteriorLateralDescending'\n elif neuron.synapsesByBranch['medial'] is 0 and neuron.synapsesByBranch['anterior'] > 0 and \\\n neuron.synapsesByBranch['descending tract'] > 0 and neuron.synapsesByBranch['lateral'] is 0 and \\\n neuron.synapsesByBranch['soma tract'] > 0:\n neuron.distribution = 'AnteriorSomaDescending'\n\n elif neuron.synapsesByBranch['medial'] > 0 and neuron.synapsesByBranch['anterior'] is 0 and \\\n neuron.synapsesByBranch['descending tract'] is 0 and neuron.synapsesByBranch['lateral'] > 0 and \\\n neuron.synapsesByBranch['soma tract'] > 0:\n neuron.distribution = 'MedialLateralSoma'\n elif neuron.synapsesByBranch['medial'] > 0 and neuron.synapsesByBranch['anterior'] is 0 and \\\n neuron.synapsesByBranch['descending tract'] > 0 and neuron.synapsesByBranch['lateral'] > 0 and \\\n neuron.synapsesByBranch['soma tract'] is 0:\n neuron.distribution = 'MedialLateralDescending'\n elif neuron.synapsesByBranch['medial'] > 0 and neuron.synapsesByBranch['anterior'] is 0 and \\\n neuron.synapsesByBranch['descending tract'] > 0 and neuron.synapsesByBranch['lateral'] is 0 and \\\n neuron.synapsesByBranch['soma tract'] > 0:\n neuron.distribution = 'MedialSomaDescending'\n elif neuron.synapsesByBranch['medial'] is 0 and neuron.synapsesByBranch['anterior'] is 0 and \\\n neuron.synapsesByBranch['descending tract'] > 0 and neuron.synapsesByBranch['lateral'] > 0 and \\\n neuron.synapsesByBranch['soma tract'] > 0:\n neuron.distribution = 'LateralSomaDescending'\n\n elif neuron.synapsesByBranch['medial'] > 0 and neuron.synapsesByBranch['anterior'] > 0 and \\\n neuron.synapsesByBranch['descending tract'] is 0 and neuron.synapsesByBranch['lateral'] > 0 and \\\n neuron.synapsesByBranch['soma tract'] > 0:\n neuron.distribution = 'AnteriorMedialLateralSoma'\n elif neuron.synapsesByBranch['medial'] > 0 and neuron.synapsesByBranch['anterior'] > 0 and \\\n neuron.synapsesByBranch['descending tract'] > 0 and neuron.synapsesByBranch['lateral'] > 0 and \\\n neuron.synapsesByBranch['soma tract'] is 0:\n neuron.distribution = 'AnteriorMedialLateralDescending'\n elif neuron.synapsesByBranch['medial'] > 0 and neuron.synapsesByBranch['anterior'] > 0 and \\\n neuron.synapsesByBranch['descending tract'] > 0 and neuron.synapsesByBranch['lateral'] is 0 and \\\n neuron.synapsesByBranch['soma tract'] > 0:\n neuron.distribution = 'AnteriorMedialSomaDescending'\n elif neuron.synapsesByBranch['medial'] is 0 and neuron.synapsesByBranch['anterior'] > 0 and \\\n neuron.synapsesByBranch['descending tract'] > 0 and neuron.synapsesByBranch['lateral'] > 0 and \\\n neuron.synapsesByBranch['soma tract'] > 0:\n neuron.distribution = 'AnteriorLateralSomaDescending'\n elif neuron.synapsesByBranch['medial'] > 0 and neuron.synapsesByBranch['anterior'] is 0 and \\\n neuron.synapsesByBranch['descending tract'] > 0 and neuron.synapsesByBranch['lateral'] > 0 and \\\n neuron.synapsesByBranch['soma tract'] > 0:\n neuron.distribution = 'MedialLateralSomaDescending'\n\n elif neuron.synapsesByBranch['medial'] > 0 and neuron.synapsesByBranch['anterior'] > 0 and \\\n neuron.synapsesByBranch['descending tract'] > 0 and neuron.synapsesByBranch['lateral'] > 0 and \\\n neuron.synapsesByBranch['soma tract'] > 0:\n neuron.distribution = 'AllBranches'\n\n return\n\n\n\n # will update value of your set's allSynapseCoordinates, which contains in dict form: {connectorID: [x,y,z],...}\n # only run this if you have already run getAllGFINSynByBranch()\n\n def findModality(self):\n for i in self:\n if \"Descending Neuron\" in i.annotations:\n i.modality = \"Descending Neuron\"\n\n elif \"Ascending Neuron\" in i.annotations:\n i.modality = \"Ascending Neuron\"\n\n elif \"Visual\" in i.annotations:\n i.modality = \"VPN\"\n\n elif \"JONeuron\" in i.annotations:\n i.modality = \"JONeuron\"\n\n elif \"Other Visual\" in i.annotations:\n i.modality = \"Other Visual\"\n\n elif \"Non-Visual_Interneuron\" in i.annotations:\n i.modality = \"Non-Visual Interneuron\"\n\n elif \"Visual_Interneuron\" in i.annotations:\n i.modality = \"Visual Interneuron\"\n\n elif \"Mechanosensory Interneuron\" in i.annotations:\n i.modality = \"Mechanosensory Interneuron\"\n\n elif \"Neuron Fragment\" in i.annotations:\n i.modality = \"Unknown\"\n else:\n i.modality = \"Unknown\"\n return\n\n def findMorphology(self):\n for neuron in self:\n if \"Unclassified GF input neuron - Fragment\" in neuron.annotations:\n neuron.morphology = \"Fragment\"\n elif \"Bilateral\" in neuron.annotations:\n if \"Ipsilateral\" in neuron.annotations:\n if \"projection neuron\" in neuron.annotations:\n neuron.morphology = \"BiIpsiProject\"\n elif \"local neuron\" in neuron.annotations:\n neuron.morphology = \"BiIpsiLocal\"\n elif \"contralateral\" in neuron.annotations:\n if \"projection neuron\" in neuron.annotations:\n neuron.morphology = \"BiContraProject\"\n elif \"midLine\" in neuron.annotations:\n if \"projection neuron\" in neuron.annotations:\n neuron.morphology = \"BiMidProject\"\n elif \"local neuron\" in neuron.annotations:\n neuron.morphology = \"BiMidLocal\"\n else:\n if \"projection neuron\" in neuron.annotations:\n neuron.morphology = \"BiProject\"\n elif \"local neuron\" in neuron.annotations:\n neuron.morphology = \"BiLocal\"\n elif \"Unilateral\" in neuron.annotations:\n if \"projection neuron\" in neuron.annotations:\n neuron.morphology = \"UniProject\"\n elif \"local neuron\" in neuron.annotations:\n neuron.morphology = \"UniLocal\"\n return\n\n\n def getGroupNumber(self):\n classes = defaultdict(list)\n indexed = defaultdict(list)\n num = 1\n for neuron in self:\n classes[neuron.classification].append(neuron)\n\n for type in classes.values():\n for neuron in type:\n neuron.groupNumber = num\n num = num + 1\n return\n\n\n\n\n\n def findBiUni(self):\n for i in self:\n if \"Bilateral\" in i.annotations:\n i.BiUni = \"Bilateral\"\n elif \"Unclassified GF input neuron - Fragment\" in i.annotations:\n i.BiUni = \"Fragment\"\n else:\n i.BiUni = \"Unilateral\"\n return\n\n def findIpsiContraMid(self):\n for i in self:\n if \"Ipsilateral\" in i.annotations:\n i.IpsiContraMid = \"Ipsilateral\"\n elif \"contralateral\" in i.annotations:\n i.IpsiContraMid = \"Contralateral\"\n elif \"midLine\" in i.annotations:\n i.IpsiContraMid = \"MidLine\"\n else:\n i.IpsiContraMid = \"No Soma\"\n return\n\n def combineAllSynLocations(self):\n mySet = self\n AllSyn = {}\n count = 0\n if bool(mySet[0].synLocation) == False:\n self.getAllGFINSynByBranch()\n for i in mySet:\n for z in i.synLocation:\n x = z\n while x in AllSyn:\n x = str(z)\n x += str(count)\n x = int(x)\n count += 1\n AllSyn[x] = i.synLocation[z]\n self.allSynapseCoordinates = AllSyn\n self.varCheck.append('synLocation')\n return self\n\n def importClusters(self, selection=None):\n if selection is not None:\n df = pandas.read_csv('C:/Users/tenshawe/Desktop/RCode/newTest/{}.csv'.format(selection),\n converters={\"connectorID\": int, 'X': float, 'Y': float, 'Z': float, 'Cluster': int})\n else:\n df = pandas.read_csv('C:/Users/tenshawe/Desktop/RCode/newTest/AllGF1Synapses8ClustersWithSKID.csv',\n converters={\"connectorID\": int, 'X': float, 'Y': float, 'Z': float, 'Cluster': int})\n for index, row in df.iterrows():\n self[int(row['skeletonID'])].GF1SynapticClusters.append(row['Cluster'])\n self.organizeSynClusters()\n self.varCheck.append('clusters')\n return self\n\n # creates a dict to fill the GF1SynapticClusters attribute of each neuron which has the possible cluster numbers as its keys and the count of synapses in those clusters as its values\n def organizeSynClusters(self):\n if 'clustersOrganized' in self.varCheck:\n return\n for i in self:\n myClusters = {'1': 0, '2': 0, '3': 0, '4': 0, '5': 0, '6': 0, '7': 0, '8': 0}\n myClusterKeys = list(myClusters.keys())\n for item in i.GF1SynapticClusters:\n myClusters[str(int(item))] = myClusters[str(int(item))] + 1\n i.GF1SynapticClusters = myClusters\n self.varCheck.append(\"clustersOrganized\")\n return self\n\n '''\n def importSubClusters(self):\n df=pandas.read_csv('C:/Users/polskyj/myCode/RCode/newTest/BothIDsAndBothClusters.csv',converters={\"connectorID\":int, 'X':float,'Y':float, 'Z':float, 'Cluster':int, 'subCluster':int})\n for index, row in df.iterrows(): \n self[int(row['skeletonID'])].GF1SynapticClusters.append(row['Cluster'], row['subCluster'])\n #self.organizeSynClusters()\n return'''\n\n # returns a list of neurons that provide synaptic output in the given number of clusters\n def getAllNeuronsByNumClusters(self, numClusters):\n myClusterNeurons = self\n for i in self:\n clusterCount = 0\n for item in i.GF1SynapticClusters:\n if i.GF1SynapticClusters[item] > 0:\n clusterCount += 1\n if clusterCount != numClusters:\n myClusterNeurons -= i\n clusterCount = 0\n myNewSet = subSetBuilder(myClusterNeurons)\n if self.groupName is not None:\n myNewSet.groupName = self.groupName + 'in{}GFsynapticClusters'.format(numClusters)\n else:\n myNewSet.groupName = 'in{}GFsynapticClusters'.format(numClusters)\n return myNewSet\n\n # takes as input a list of cluster numbers, for which all neurons with synapses in those clusters will be returned\n\n def chooseNeuronsBySynCluster(self, clusterList):\n newList = []\n for i in self:\n myVar = False\n for clusterNum in clusterList:\n if i.GF1SynapticClusters[str(clusterNum)] != 0:\n myVar = True\n if myVar is True:\n newList.append(i)\n break\n myNeurons = subSetBuilder(newList)\n return myNeurons\n\n def importSubClusters(self, fileName=None):\n # if 'clusters' not in self.varCheck:\n # self.importClusters()\n if fileName is None:\n fileName = 'BothIDsAndBothClusters'\n fileAddress = 'C:/Users/tenshawe/Desktop/RCode/newTest/{}.csv'.format(fileName)\n df = pandas.read_csv(fileAddress,\n converters={\"connectorID\": int, 'X': float, 'Y': float, 'Z': float, 'Cluster': int,\n 'subCluster': int})\n for index, row in df.iterrows():\n if 'tempHolder' in self[int(row['skeletonID'])].subClusters:\n self[int(row['skeletonID'])].subClusters[str(row['Cluster'])] = \\\n self[int(row['skeletonID'])].subClusters['tempHolder']\n del self[int(row['skeletonID'])].subClusters['tempHolder']\n if row['subCluster'] == 1:\n self[int(row['skeletonID'])].subClusters[str(row['Cluster'])]['subCluster1'] += 1\n elif row['subCluster'] == 2:\n self[int(row['skeletonID'])].subClusters[str(row['Cluster'])]['subCluster2'] += 1\n elif row['subCluster'] == 3:\n self[int(row['skeletonID'])].subClusters[str(row['Cluster'])]['subCluster3'] += 1\n return self\n\n # returns a list of dictionaries - each dictionary should contain all relevant quantile information\n def makeQuantiles(self):\n mySetSynCount = self.AllGF1Synapses\n q1 = {}\n q2 = {}\n q3 = {}\n q4 = {}\n q5 = {}\n qs = [q1, q2, q3, q4, q5]\n qNames = ['q1', 'q2', 'q3', 'q4', 'q5']\n\n a = quantiles(self)\n a = np.delete(a, 2)\n myAdditionalInfo = outputAllInfo(self)\n c = 0\n myTempSet = self\n while (c <= 3):\n tempVar = subBySynLT(myTempSet, a[c])\n myTempSet -= tempVar\n for i in tempVar:\n i.quantile = qNames[c]\n qs[c]['synapse_Threshold'] = a[c]\n qs[c]['number_Neurons'] = tempVar.numNeurons\n qs[c]['average_synapse_count'] = tempVar.averageSyn\n qs[c]['median_synapse_count'] = tempVar.medianSyn\n qs[c]['all_GF1_Synapses'] = tempVar.AllGF1Synapses\n qs[c]['percent of all {} synapses on GF1'.format(self.groupName)] = (tempVar.AllGF1Synapses / mySetSynCount)\n\n tempVar = None\n c += 1\n tempVar = subBySynGT(myTempSet, a[c - 1])\n tempVar = sortBySynH2L(tempVar)\n c = 4\n for i in tempVar:\n i.quantile = qNames[c]\n qs[c]['synapse_Threshold'] = tempVar[0].GF1synapseCount\n qs[c]['number_Neurons'] = tempVar.numNeurons\n qs[c]['average_synapse_count'] = tempVar.averageSyn\n qs[c]['median_synapse_count'] = tempVar.medianSyn\n qs[c]['all_GF1_Synapses'] = tempVar.AllGF1Synapses\n qs[c]['percent of all {} synapses on GF1'.format(self.groupName)] = (tempVar.AllGF1Synapses / mySetSynCount)\n\n return qs\n\n def e2c(self):\n if 'soma' not in self.varCheck:\n self.updateSomata()\n if 'partners' not in self.varCheck:\n self.getNumPartnersBySkid()\n if 'synByBranch' not in self.varCheck:\n self.getAllGFINSynByBranch()\n E2C.makeCSV(self, 'saveWithSomaAndBranches')\n return\n\n def createSummary(self):\n mySet = self\n myClassList = []\n # for i in mySet:\n while len(mySet) > 0:\n # if i.classification not in myClassList[i.classification]:\n # myClassList[i.classification] = 1\n tempGroup = createGroupByClassification(mySet, mySet[0].classification)\n tempGroup.minMax()\n tempGroup._medSyn()\n tempGroup._avgSyn()\n myClassList.append(tempGroup)\n myNewSet = []\n for item in mySet:\n if item.classification != mySet[0].classification:\n myNewSet.append(item)\n a = subSetBuilder(myNewSet)\n mySet = a\n\n # for item in tempGroup:\n # mySet -= item\n # print(len(mySet))\n # else:\n # myClassList[i.i.classification] += 1\n # for item in myClassList:\n # #print(item.numNeurons, type(item.numNeurons))\n # if item.numNeurons == 0:\n # myClassList.remove(item)\n # #print('yes')\n # else:\n # print(item, ': no')\n # if item.numNeurons is None:\n # myClassList.remove(item)\n return myClassList\n\n # note that the api endpoint in use here requires entity ids which equals neuron id, not skeleton ID\n # LEFT HEMISPHERE == 1223085\n def correctAnnotations(self):\n mySet = clusteringAlgorithms.removeSomaless(self)\n rightHem = []\n leftHem = []\n for item in mySet:\n if item.soma[0] < 500000:\n rightHem.append(item.skeletonID + 1)\n elif item.soma[0] > 550000:\n leftHem.append(item.skeletonID + 1)\n responseOne = requests.post(\n 'https://neuropil.janelia.org/tracing/fafb/v14/{}/annotations/remove'.format(project_id),\n auth=config.CatmaidApiTokenAuth(token),\n data={'entity_ids': rightHem, 'annotation_ids': [1223085]}\n )\n responseOne = json.loads(responseOne.content)\n print(responseOne)\n responseTwo = requests.post(\n 'https://neuropil.janelia.org/tracing/fafb/v14/{}/annotations/remove'.format(project_id),\n auth=config.CatmaidApiTokenAuth(token),\n data={'entity_ids': leftHem, 'annotation_ids': [1167304]}\n )\n responseTwo = json.loads(responseTwo.content)\n print(responseTwo)\n return\n\n def addAnnotation(self, newAnnotation, addToSkeletons=True, metaAnnotations=None):\n \"\"\"\n\n :param newAnnotation: array of string - to be added to catmaid annotation of neurons (if looking for bulk annotations: set from GFIN objects\n :param addToSkeletons: default is true - if false, will create annotation and annotate it with a meta_annotation\n :param metaAnnotations: default is none - should be array[string] if desired\n :return: print out: success or error (with error message), annotations added (name and id), neuron ids, and list of any new annotations\n \"\"\"\n if addToSkeletons is True:\n mySkids = []\n for item in self:\n mySkids.append(item.skeletonID)\n\n response = requests.post(\n 'https://neuropil.janelia.org/tracing/fafb/v14/{}/annotations/add'.format(project_id),\n auth=config.CatmaidApiTokenAuth(token),\n data={'skeleton_ids': mySkids, 'annotations': newAnnotation}\n )\n else:\n response = requests.post(\n 'https://neuropil.janelia.org/tracing/fafb/v14/{}/annotations/add'.format(project_id),\n auth=config.CatmaidApiTokenAuth(token),\n data={'annotations': newAnnotation, 'meta_annotations': metaAnnotations}\n )\n\n myResults = json.loads(response.content)\n print(myResults)\n return\n\n '''\n def makeDataFrame(self):\n myDataFrame = {}\n myAttributeNames = ['Neuron Name', 'skeletonID', 'GF1 Synapse Count', 'GF2 Synapse Count', 'percent total synapses',\n 'classification', 'hemisphere', 'cellBodyRind', 'somaHemisphere', 'commissure', 'numLC4Syn',\n 'numLPLC2Syn',\n 'numLC6Syn', 'numLPLC1Syn', 'numLPC1Syn', 'numLC28Syn', 'numLLPC1Syn', 'numLPLC3Syn',\n 'lateral branch',\n 'medial branch', 'anterior branch', 'soma tract', 'descending tract']\n myAttributes = [globals()neuronName, skeletonID, GF1synapseCount, GF2synapseCount, percentTotalSynapse, classification, hemisphere, cellBodyRind, somaSide, commissure, postsynapticToLC4, postsynapticToLPLC2, postsynapticToLC6, postsynapticToLPLC1, postsynapticToLPC1, postsynapticToLC28, postsynapticToLLPC1, postsynapticToLPLC3, synapsesByBranch['lateral'], synapsesByBranch['medial'], synapsesByBranch['anterior'], synapsesByBranch['soma tract'], synapsesByBranch['descending tract']]\n for attribute in myAttributeNames:\n myDataFrame[attribute] = []\n for neuron in self:\n for attribute in myAttributeNames:\n myDataFrame[attribute].append()\n return myDataFrame\n '''\n\n def makeDataFrame(self):\n\n myWriter = csv.writer()\n myRows0 = ['Neuron Name', 'skeletonID', 'GF1 Synapse Count', 'GF2 Synapse Count', 'percent total synapses',\n 'classification', 'hemisphere', 'cellBodyRind', 'somaHemisphere', 'commissure', 'numLC4Syn',\n 'numLPLC2Syn', 'numLC6Syn', 'numLPLC1Syn', 'numLPC1Syn', 'numLC28Syn', 'numLLPC1Syn',\n 'numLPLC3Syn', 'lateral branch', 'medial branch', 'anterior branch', 'soma tract',\n 'descending tract']\n myRows = myRows0 + mySet.allAnnotations\n myWriter.writerow(myRows)\n for item in self:\n theseAnnotations = []\n for annotation in self.allAnnotations:\n if annotation in item.annotations:\n theseAnnotations.append(1)\n else:\n theseAnnotations.append(0)\n curRow = [item.neuronName, item.skeletonID, item.GF1synapseCount, item.GF2synapseCount,\n item.percentTotalSynapse, item.classification, item.hemisphere, item.cellBodyRind,\n item.somaSide, item.commissure, item.postsynapticToLC4, item.postsynapticToLPLC2,\n item.postsynapticToLC6, item.postsynapticToLPLC1, item.postsynapticToLPC1,\n item.postsynapticToLC28, item.postsynapticToLLPC1, item.postsynapticToLPLC3,\n item.synapsesByBranch['lateral'], item.synapsesByBranch['medial'],\n item.synapsesByBranch['anterior'], item.synapsesByBranch['soma tract'],\n item.synapsesByBranch['descending tract']]\n fullRow = curRow + theseAnnotations\n myWriter.writerow(fullRow)\n\n return myWriter\n\n def allMyVars(self):\n allVars = dir(self)\n allSigVars = []\n for i in allVars:\n if \"__\" not in i:\n allSigVars.append(i)\n return allSigVars\n\n # Needs to be run before getAllGFINSynByBranch()\n def getJOPartnerNumbers(self):\n with open('KnownJONeuronsRIGHTHEMISPHERE.json') as myJONfile:\n myJO = json.load(myJONfile)\n\n JOskids = []\n for i in myJO:\n JOskids.append(i['skeleton_id'])\n\n joConnectorInfo = GC.getConnectorsStep1(JOskids, \"presynaptic_to\", False)\n joConnectorIDs = []\n for i in joConnectorInfo['connectors']:\n joConnectorIDs.append(i[0])\n\n if self[0].connectorIDs is None:\n for i in self:\n i.getConnectorIDs(polarity='postsynaptic')\n for i in self:\n for item in i.connectorIDs:\n if item in joConnectorIDs:\n i.postsynapticToJON += 1\n self.varCheck.append(\"JO_partners\")\n return self\n\n\ndef getAllConnectorInfo(skeletonID=None, polarity=None):\n if skeletonID is None:\n mySkid = 4947529\n else:\n mySkid = skeletonID\n if polarity is None:\n relation_type = 'postsynaptic'\n else:\n relation_type = polarity\n\n # gets connector ID for all nodes in given skeleton (output: {links:[[skleton ID, Connector ID, X, Y, Z, Confidence, User ID, TNID, Date Created, Date Modified]], tags:[...]\n response = requests.get(\n 'https://neuropil.janelia.org/tracing/fafb/v14/{}/connectors/links/?skeleton_ids[0]={}&relation_type={}_to&with_tags=true'.format(\n project_id, mySkid, relation_type) # ,\n # auth = auth,\n # data = {'skeleton_ids' : mySkid, 'relation_type' : 'postsynaptic_to'}\n )\n connectorInfo = json.loads(response.content)\n # print(connectorInfo)\n return connectorInfo\n\n\n\n#takes list of connectors and returns partner info\n#parameter should be above function call, returns same as above with a list of postsynaptic partner skids apended to end\n#takes long time to run but time varies on number of synapses\ndef getConnectedPartners(connectorIDArray):\n newDict = {}\n for connectorID in connectorIDArray:\n response = requests.get(\n 'https://neuropil.janelia.org/tracing/fafb/v14/1/connectors/{}/'.format(connectorID)\n )\n myR = json.loads(response.content)\n #print(myR)\n newDict[connectorID] = myR\n return newDict\n\n#returns SKID of presynaptic partners of a synapse from a dict from 'getConnectorPartners'\ndef getConnectedPartnersSKIDOnly(connectorIDArray):\n newDict = getConnectedPartners(connectorIDArray)\n partners = []\n skelIDs = []\n id = []\n for i in newDict.items():\n partners.append(i)\n part = i[1].get('partners')\n id = part[1].get('skeleton_id')\n skelIDs.append(id)\n return skelIDs\n\n\n\n# call this to build a GFIN_set from all GF1 input neurons\ndef builder():\n mySet = GFIN_set(np.array(MyCustomGFNeuronClass.builder()))\n mySet._avgSyn()\n mySet._medSyn()\n mySet.minMax()\n return mySet\n\n\n\ndef buildFromSkidList(myList):\n mySet = GFIN_set(np.array(MyCustomGFNeuronClass.buildFromSkidList(myList)))\n return mySet\n\n\n# sorts neurons from low to high synapse counts\ndef sortBySynL2H(mySet):\n L2H = sorted(mySet, key=MyCustomGFNeuronClass.GFinputNeuron.getGF1synapse)\n mySortedList = subSetBuilder(L2H)\n if mySet.groupName != None:\n mySortedList.groupName = mySet.groupName\n return mySortedList\n\n\n# sorts neurons from low to high synapse counts\ndef sortBySynH2L(mySet):\n H2L = sorted(mySet, key=MyCustomGFNeuronClass.GFinputNeuron.getGF1synapse, reverse=True)\n mySortedList = subSetBuilder(H2L)\n if mySet.groupName != None:\n mySortedList.groupName = mySet.groupName\n return mySortedList\n\n\n# returns a subset based upon annotation: mySet = GFIN_set instance, annotation = string annotation, annotation can also be a list of annotation strings\ndef createGroupByAnnotation(mySet, annotation):\n myNewSet = []\n if isinstance(annotation, str):\n for item in mySet:\n for i in item.annotations:\n if i == annotation:\n myNewSet.append(item)\n continue\n elif isinstance(annotation, list):\n for item in mySet:\n for i in item.annotations:\n if i in annotation:\n if item not in myNewSet:\n myNewSet.append(item)\n # continue\n a = subSetBuilder(myNewSet)\n if type(annotation) == list:\n tempName = ', '.join(annotation)\n annotation = tempName\n if mySet.groupName is None:\n a.groupName = annotation\n elif mySet.groupName == \"None\":\n a.groupName = annotation\n\n else:\n a.groupName = mySet.groupName + \"_\" + annotation\n print(\"There are {} neurons with annotation {}: \\n\".format(len(a), a.groupName))\n return a\n\n\n# returns a subset based upon classification: mySet = GFIN_set instance, classification = string classification\ndef createGroupByClassification(mySet, classification):\n myNewSet = []\n for item in mySet:\n if item.classification == classification:\n myNewSet.append(item)\n a = subSetBuilder(myNewSet)\n # print(a.numNeurons)\n\n if mySet.groupName is None or mySet.groupName is 'GF1 Input Neurons':\n a.groupName = classification\n elif mySet.groupName == \"None\" or mySet.groupName == 'GF1 Input Neurons':\n a.groupName = classification\n\n else:\n a.groupName = mySet.groupName + \"_\" + classification\n # print(a.groupName, \":\", len(a), \"/n\")\n\n # print(\"There are {} neurons with classification {}: \\n\".format(len(a), a.groupName))\n return a\n\n\n# returns a subset based upon annotation that neurons do NOT have: mySet = GFIN_set instance, annotation = string annotation\ndef createGroupByNotAnnotation(mySet, annotation):\n myNewSet = mySet\n for item in mySet:\n if annotation in item.annotations:\n myNewSet -= item\n continue\n a = subSetBuilder(myNewSet)\n if myNewSet.groupName is not None:\n myNewSet.groupName += 'not' + str(annotation)\n else:\n myNewSet.groupName = 'not' + str(annotation)\n\n print(\"There are {} neurons left without annotation {}: \\n\".format(len(myNewSet), annotation))\n return a\n\n\n# returns a subset based upon synCount: mySet = GFIN_set instance, synNumber = Number of Synapses(or less) that you want results to have\ndef subBySynLT(mySet, synNumber):\n myNewSet = []\n for item in mySet:\n if item.GF1synapseCount <= synNumber:\n myNewSet.append(item)\n continue\n x = subSetBuilder(myNewSet)\n if mySet.groupName != None:\n x.groupName = str(mySet.groupName) + \"with\" + str(synNumber) + \"synapses\"\n print(\"{} of these neurons have {} or less synapses \\n\".format(len(myNewSet), synNumber))\n return x\n\n\n# returns a subset based upon synCount: mySet = GFIN_set instance, synNumber = Number of Synapses(or greater) that you want results to have\ndef subBySynGT(mySet, synNumber):\n myNewSet = []\n for item in mySet:\n if item.GF1synapseCount >= synNumber:\n myNewSet.append(item)\n continue\n x = subSetBuilder(myNewSet)\n if mySet.groupName != None:\n x.groupName = str(mySet.groupName) + \"with\" + str(synNumber) + \"synapses\"\n print(\"{} of these neurons have {} or more synapses \\n\".format(len(myNewSet), synNumber))\n return x\n\n\n# used by other functions to transform resulting data types into GFIN_set type\n'''def subSetBuilder(fullSet, oldSet = None):\n mySubSet = GFIN_set(np.array(fullSet))\n if isinstance(oldSet, GFIN_set):\n for i in vars(oldSet):\n myI = getattr(oldSet, i)\n if myI is not None:\n setattr(mySubSet, i, myI) \n return mySubSet\n else:\n return mySubSet'''\n'''def subSetBuilder(fullSet, oldSet = None):\n mySubSet = GFIN_set(np.array(fullSet))\n if isinstance(oldSet, GFIN_set):\n myVars = vars(oldSet)\n myVarsKeys = vars(oldSet).keys()\n #print(myVars)\n #myVarsList = list(myVars)\n #myVarsList -= 'container'\n #myVarsList -= 'numNeurons'\n #myVarsList -= 'percentTotalSynapses'\n del myVars['container']\n del myVars['numNeurons']\n del myVars['percentTotalSynapses']\n\n for i in myVars:\n print(i)\n #myI = getattr(fullSet, i)\n myI = myVars[i]\n if myI is not None:\n setattr(mySubSet, i, myI) \n return mySubSet\n else:\n return mySubSet'''\n\n\ndef subSetBuilder(fullSet):\n mySubSet = GFIN_set(np.array(fullSet))\n if isinstance(fullSet, GFIN_set):\n if fullSet.groupName != None:\n mySubSet.groupName = fullSet.groupName\n if mySubSet.allSynapseCoordinates is not None:\n mySubSet.combineAllSynLocations()\n if mySubSet.numSynapsesByBranch is not None:\n mySubSet.numSynapsesByBranch = {}\n branches = ['soma tract', 'medial', 'anterior', 'lateral', 'descending tract']\n for x in branches:\n if x not in mySubSet.numSynapsesByBranch:\n mySubSet.numSynapsesByBranch[x] = 0\n for i in mySubSet:\n mySubSet.numSynapsesByBranch[x] += i.synapsesByBranch[x]\n return mySubSet\n else:\n return mySubSet\n\n\n# use to fix add\ndef subSetBuilderNew(fullSet):\n mySubSet = GFIN_set(np.array(fullSet))\n for i in fullSet:\n for item in i:\n setattr(mySubSet[i.skeletonID], item, (getattr(i, item)))\n return mySubSet\n # old codethat was formerly part of subSetBuilder\n\n\n# unusued consider deleting\ndef sliceBuilder(aSet):\n print(aSet)\n newSet = GFIN_set(np.array(aSet))\n return newSet\n\n\n# Unused - consider deleting\ndef _getSynCount(self):\n mySynCount = 0\n for item in self:\n print(\"item\", item)\n mySynCount += self[item].GF1synapseCount\n return mySynCount\n\n\ndef totalSynapseCount(neurons):\n totalSynapseCount = int()\n for i in neurons:\n totalSynapseCount += neurons[i].GF1synapseCount\n return totalSynapseCount\n\n\nfrom scipy.stats.mstats import mquantiles\n\n\ndef quantiles(mySet):\n mySyns = []\n for i in mySet:\n mySyns.append(i.GF1synapseCount)\n myQuant = mquantiles(mySyns, prob=[0.2, 0.4, 0.5, 0.6, 0.8])\n return myQuant\n\n\nfrom sklearn.cluster import KMeans\n\n\ndef getMyKMeans(mySet):\n mySyns = []\n for i in mySet:\n mySyns.append(i.GF1synapseCount)\n arrayMySyns = np.asarray(mySyns)\n kmeans = KMeans(n_clusters=4).fit(arrayMySyns)\n return (kmeans)\n\n\ndef makeDistributedGroups(mySet):\n a = quantiles(mySet)\n for i in a:\n if i == a[2]:\n continue\n elif i == a[0]:\n b = subBySynLT(mySet, i)\n lastI = i\n JN.makeJsonFile(b)\n elif i == a[4]:\n b = subBySynGT(mySet, i)\n JN.makeJsonFile(b)\n else:\n r = subBySynLT(mySet, i)\n z = subBySynGT(r, lastI)\n lastI = i\n JN.makeJsonFile(z)\n return\n\n\ndef makeDistributedGroupsByColor(mySet):\n mySetSynCount = mySet.AllGF1Synapses\n a = quantiles(mySet)\n a = np.delete(a, 2)\n myAdditionalInfo = outputAllInfo(mySet)\n myBigSet = [None] * 5\n c = 0\n myTempSet = mySet\n while (c <= 3):\n tempVar = subBySynLT(myTempSet, a[c])\n myBigSet[c] = tempVar\n myTempSet -= tempVar\n myAdditionalInfo += \"\\n quantile with <= {} synapses onto GF: \\n - {} neurons in this quantile \\n -average number of synapses: {} \\n -median number of synapses: {} \\n - total number of synapses onto GF in this quantile: {} \\n - % of all {} synapses onto GF: {} \\n\".format(\n a[c], tempVar.numNeurons, tempVar.averageSyn, tempVar.medianSyn, tempVar.AllGF1Synapses, mySet.groupName,\n (tempVar.AllGF1Synapses / mySetSynCount))\n tempVar = None\n c += 1\n tempVar = subBySynGT(myTempSet, a[c - 1])\n myBigSet[c] = tempVar\n myAdditionalInfo += \"\\n quantile with > {} synapses onto GF: \\n - {} neurons in this quantile \\n -average number of synapses: {} \\n -median number of synapses: {} \\n - total number of synapses onto GF in this quantile: {} \\n - % of all {} synapses onto GF: {}\".format(\n a[c - 1], tempVar.numNeurons, tempVar.averageSyn, tempVar.medianSyn, tempVar.AllGF1Synapses, mySet.groupName,\n (tempVar.AllGF1Synapses / mySetSynCount))\n for i in myBigSet:\n i.groupName = mySet.groupName\n # myAdditionalInfo += \"\\n quantile {} synapses or less: \\n - {} neurons in this quantile \\n -average number of synapses: {} \\n -median number of synapses: {} \\n - %LPLC2 synapses: {}\".format(a[myBigSet.index(i)], i.numNeurons, i.avg, i.med)\n JN.autoSaveJSONFlatColor(myBigSet, additionalInfo=myAdditionalInfo)\n return myBigSet\n\n\ndef outputAllInfo(mySet):\n myInfo = \"\"\n myInfo += str(mySet.groupName) + '\\n'\n myInfo += \"number: \" + str(mySet.numNeurons) + '\\n'\n myInfo += \"GF synapse count: \" + str(mySet.AllGF1Synapses) + '\\n'\n myInfo += \"%total GF synapses: \" + str(mySet.percentTotalSynapses) + '\\n'\n myInfo += \"quantiles used: \" + str(quantiles(mySet)) + '\\n'\n return myInfo\n\n\ndef appendNonGFIN(mySet, annotation):\n testList = GetAnnotationsRemoveExtraneousInfo.getListOfSkID_int(annotation)\n curSKIDs = []\n for i in mySet:\n curSKIDs.append(i.skeletonID)\n for item in testList:\n if item not in curSKIDs:\n myNeuron = MyCustomGFNeuronClass.buildSingleCell(int(item))\n mySet += myNeuron\n return mySet\n\n\ndef appendNonGFIN2(mySet, annotation):\n testList = GetAnnotationsRemoveExtraneousInfo.getListOfSkID_int(annotation)\n curSKIDs = []\n for i in mySet:\n curSKIDs.append(i.skeletonID)\n for item in testList:\n if item not in curSKIDs:\n myNeuron = MyCustomGFNeuronClass.buildSingleCellQuick(int(item))\n mySet += myNeuron\n return mySet\n\n\ndef appendLC6partners(mySet, annotation):\n testList = GetAnnotationsRemoveExtraneousInfo.getListOfSkID_int(annotation)\n curSKIDs = []\n for i in mySet:\n curSKIDs.append(i.skeletonID)\n for item in testList:\n if item not in curSKIDs:\n myNeuron = MyCustomGFNeuronClass.buildSingleCellLC6partners(int(item))\n mySet += myNeuron\n return mySet\n\n\ndef findBranchCoordinates(mySet):\n # get list of coordinates by synapse id\n mySet.combineAllSynLocations()\n # get list of synapse id by branch\n mySet.getAllGFINSynByBranch()\n\n descend = mySet.connectorInfo.get('descending tract')\n descend_coords = []\n soma = mySet.connectorInfo.get('soma tract')\n soma_coords = []\n anterior = mySet.connectorInfo.get('anterior')\n anterior_coords = []\n medial = mySet.connectorInfo.get('medial')\n medial_coords = []\n lateral = mySet.connectorInfo.get('lateral')\n lateral_coords = []\n\n all_coords = list(mySet.allConnectorInfo.values())\n\n for i in all_coords[0]:\n if i[1] in descend:\n descend_coords.append(i)\n for i in all_coords[0]:\n if i[1] in soma:\n soma_coords.append(i)\n for i in all_coords[0]:\n if i[1] in anterior:\n anterior_coords.append(i)\n for i in all_coords[0]:\n if i[1] in medial:\n medial_coords.append(i)\n for i in all_coords[0]:\n if i[1] in lateral:\n lateral_coords.append(i)\n\n return mySet\n\n\n\n\n","sub_path":"CustomNeuronClassSet.py","file_name":"CustomNeuronClassSet.py","file_ext":"py","file_size_in_byte":81901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"442376953","text":"from django.shortcuts import render,redirect,HttpResponseRedirect\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.shortcuts import render,redirect\nfrom django.urls import reverse\nfrom django.http import JsonResponse\nfrom .models import Commnet\nfrom .forms import CommentForm\nimport json\n\n# Create your views here.\ndef updateComment(request):\n\n if request.session.get(\"is_login\"):\n referer = request.META.get(\"HTTP_REFERER\", reverse('home'))\n commen_form = CommentForm(request.POST)\n if commen_form.is_valid():\n #检查通过 ,保存数据\n comment = Commnet()\n comment.author= request.session.get('username')\n comment.text = commen_form.cleaned_data['text']\n comment.content_object =commen_form.cleaned_data['content_object']\n parent= commen_form.cleaned_data['parent']\n\n if not parent is None:\n comment.root = parent.root if not parent.root is None else parent\n comment.parent = parent\n comment.reply_to = parent.author\n comment.save()\n data={}\n data[\"status\"]=\"SUCCESS\"\n data[\"username\"]=comment.author\n data[\"text\"] = comment.text\n data[\"comment_time\"] = comment.datetime.strftime(\"%Y-%m-%d %H:%M:%S\")\n\n if not parent is None:\n data['reply_to'] = comment.reply_to\n else:\n data['reply_to'] =''\n data['id'] =comment.id\n data[\"root_id\"]= comment.root.id if not comment.root is None else ''\n else:\n # return render(request,\"error.html\",{'message':commen_form.errors,'redirect_to':referer})\n data = {}\n data[\"status\"] = \"error\"\n data['message']=list(commen_form.errors.values())[0]\n data[\"is_login\"] = True\n return JsonResponse(data)\n else:\n data={}\n data[\"is_login\"] =False\n return JsonResponse(data)\n\n","sub_path":"comment/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"432394654","text":"import logging\n\nimport arrow\nimport requests.exceptions\nfrom celery import Task\nfrom celery.exceptions import SoftTimeLimitExceeded\nfrom flask import Flask, request\nfrom flask_babelex import Babel\nfrom flask_login import current_user\nfrom flask_migrate import Migrate\nfrom raven.contrib.flask import Sentry\nfrom werkzeug.utils import find_modules, import_string\n\nfrom ads.cache import redis_store\nfrom ads.common import ApiException, ApiResult, cache as flask_cache\nfrom ads.models import db\nfrom ads.ext.yandex import DirectError\nfrom ads.tasks import celery_app\nfrom ads.utils import configure_logging, create_stream_handler\nfrom ads.views.admin import admin\nfrom ads.views.auth import login_manager\n\n\ndef register_blueprints(app):\n for name in find_modules('ads.views', recursive=True, include_packages=True):\n mod = import_string(name)\n if hasattr(mod, 'blueprint'):\n app.register_blueprint(mod.blueprint)\n\n\ndef register_other_things(app):\n db.init_app(app)\n Migrate(app, db)\n redis_store.init_app(app)\n Babel(app)\n flask_cache.init_app(app)\n login_manager.init_app(app)\n admin.init_app(app)\n\n @app.after_request\n def after_request(response):\n logging.getLogger('ads_requests').debug(\n '{:15} {:4} {} {} {!r}'.format(\n request.remote_addr,\n request.method,\n request.full_path,\n response.status,\n current_user,\n )\n )\n return response\n\n @app.shell_context_processor\n def ctx():\n from pprint import pprint\n from ads.models import DirectAccount\n from ads.utils import pretty\n return {\n 'arrow': arrow,\n 'pprint': pprint,\n 'db': db,\n 'pretty': pretty,\n 'DirectAccount': DirectAccount,\n }\n\n\ndef create_app():\n class ArrowJSONEncoder(Flask.json_encoder):\n def default(self, obj):\n if isinstance(obj, arrow.Arrow):\n return obj.timestamp\n return super().default(obj)\n\n class ApiFlask(Flask):\n json_encoder = ArrowJSONEncoder\n\n def make_response(self, rv):\n if isinstance(rv, ApiResult):\n return rv.to_response()\n return super().make_response(rv)\n\n app = ApiFlask(__name__, static_folder=None)\n app.config.from_object('ads.config')\n configure_logging(app)\n\n if app.config['ADS_ENV'] == 'development':\n print('\\n=== Configuring development app ===\\n')\n\n app.jinja_env.auto_reload = True\n app.config.update({\n 'DEBUG': True,\n 'PROPAGATE_EXCEPTIONS': False,\n 'TEMPLATES_AUTO_RELOAD': True,\n 'SESSION_COOKIE_SECURE': False,\n 'REMEMBER_COOKIE_SECURE': False,\n })\n stream_handler = create_stream_handler()\n app.logger.addHandler(stream_handler)\n logging.getLogger('ads').addHandler(stream_handler)\n else:\n app.sentry = Sentry(app, dsn=app.config['SENTRY_DSN'])\n\n app.register_error_handler(ApiException, lambda err: err.to_result())\n register_blueprints(app)\n register_other_things(app)\n\n return app\n\n\ndef create_celery(app):\n class ContextTask(Task):\n throws = (\n DirectError,\n requests.exceptions.Timeout,\n requests.exceptions.ConnectionError,\n )\n expires = 300\n\n def __call__(self, *args, **kwargs):\n with app.app_context():\n try:\n return super().__call__(*args, **kwargs)\n except Exception as exc:\n db.session.rollback()\n self._handle_occured_exception(exc, args, kwargs)\n raise\n\n def _handle_occured_exception(self, exc, args, kwargs):\n msg = '(task={!r}, args={}, kwargs={})'.format(self.name, args, kwargs)\n\n if isinstance(exc, SoftTimeLimitExceeded):\n app.logger.error('SoftTimeLimitExceeded: {}'.format(msg))\n elif isinstance(exc, DirectError):\n app.logger.error('DirectError: {}: {}'.format(msg, exc))\n elif isinstance(exc, requests.exceptions.Timeout):\n app.logger.error('Timeout: {}: {}'.format(msg, exc))\n elif isinstance(exc, requests.exceptions.ConnectionError):\n app.logger.error('Connection: {}: {}'.format(msg, exc))\n else:\n app.logger.exception('Error: {}'.format(msg))\n\n if getattr(app, 'sentry', None):\n app.sentry.user_context({\n 'task_name': self.name,\n 'task_args': str(args),\n 'task_kwargs': str(kwargs)\n })\n app.sentry.captureException()\n\n celery_app.config_from_object('ads.celeryconfig')\n celery_app.Task = ContextTask\n return celery_app\n","sub_path":"ads/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"404734805","text":"from Globals import *\nfrom LogicElements import *\nfrom SwitchesCalculating import *\nfrom Functions import *\n\ndef getCoverOfCombo(globalHigh, globalLow, testCover, combination, coverCount):\n currentCoverCount = coverCount\n# print \"combination \" + combination\n# # print \"testCover\" + str(testCover[combination])\n# print \"globalBreakUpsHigh \" + str(globalHigh)\n# print \"globalBreakUpsLow \" + str(globalLow)\n for nodeName, breakTypeList in testCover[combination].items():\n for breakType in breakTypeList:\n if (str(breakType) == str(1)):\n if (globalHigh[nodeName] > 0):\n\n currentCoverCount = currentCoverCount - 1\n if (str(breakType) == str(0)):\n if (globalLow[nodeName] > 0):\n currentCoverCount = currentCoverCount - 1\n# print \"currentCoverCount \" + str(currentCoverCount)\n# print \"\\n\"\n return currentCoverCount\n\n#return list of 2 dict\ndef getTestCover(allTestCombo):\n\n for i in range(len(allTestCombo)):\n for j in range(len(allTestCombo[i])):\n allTestCombo[i][j] = str(allTestCombo[i][j])\n\n #print allTestCombo\n #exit()\n\n testCover = dict()\n testCoverStat = dict()\n for currentCombo in allTestCombo:\n rightOutput = getSchemeOutput(currentCombo, \"R\", 0)\n currentComboCover = dict()\n coverCounter = 0\n for currentNode in GLNodes:\n incorrect1 = getSchemeOutput(currentCombo, currentNode, 1)\n incorrect0 = getSchemeOutput(currentCombo, currentNode, 0)\n currentNodeCover = list()\n if (int(incorrect1) != int(rightOutput)):\n currentNodeCover.append(1)\n if (int(incorrect0) != int(rightOutput)):\n currentNodeCover.append(0)\n if (len(currentNodeCover) > 0):\n currentComboCover[currentNode] = currentNodeCover\n coverCounter = coverCounter + 1\n else:\n currentComboCover[currentNode] = \"-\"\n if (coverCounter > 0):\n\n key = listToString(currentCombo)\n testCover[key] = currentComboCover\n testCoverStat[key] = coverCounter\n return [testCover, testCoverStat]\n\ndef getFullCoverCombosForSequence(testCover, testCoverStat, sequences):\n globalBreakUpsHigh = {\"F1\" : 0, \"F2\": 0, \"F3\" : 0, \"F4\": 0, \"F5\" : 0, \"F6\": 0 }\n globalBreakUpsLow = {\"F1\" : 0, \"F2\": 0, \"F3\" : 0, \"F4\": 0, \"F5\" : 0, \"F6\": 0 }\n globalBreakCount = 12\n\n counter = 0\n sequenceCover = list()\n\n for combination in sequences:\n #print \"combination \" + combination\n combination = listToString(combination)\n coverCount = testCoverStat[combination]\n if (globalBreakCount == 0):\n break\n currentCoverCount = getCoverOfCombo(globalBreakUpsHigh, globalBreakUpsLow, testCover, combination, coverCount)\n\n if (currentCoverCount > 0):\n globalBreakCount = globalBreakCount - currentCoverCount\n for nodeName, breakTypeList in testCover[combination].items():\n for breakType in breakTypeList:\n if (str(breakType) == '1'):\n globalBreakUpsHigh[nodeName] = 1\n if (str(breakType) == '0'):\n globalBreakUpsLow[nodeName] = 1\n sequenceCover.append(combination)\n counter = counter + 1\n if (globalBreakCount == 0):\n return [sequenceCover, counter]\n return 0\n\ndef getFullCoverCombos(testCover, testCoverStat):\n globalBreakUpsHigh = {\"F1\" : 0, \"F2\": 0, \"F3\" : 0, \"F4\": 0, \"F5\" : 0, \"F6\": 0 }\n globalBreakUpsLow = {\"F1\" : 0, \"F2\": 0, \"F3\" : 0, \"F4\": 0, \"F5\" : 0, \"F6\": 0 }\n globalBreakCount = 12\n\n maxBreakCount = 0\n maxBreakCombo = 0\n counter = 0\n\n comboListToCover = list()\n while (globalBreakCount > 0):\n for combination, coverCount in testCoverStat.items():\n# print str(combination) + \" \" + str(coverCount)\n if (counter == 0):\n if (globalBreakCount == 12):\n maxBreakCount = coverCount\n maxBreakCombo = combination\n else:\n# print \"@@@ First combo\"\n currentCoverCount = getCoverOfCombo(globalBreakUpsHigh, globalBreakUpsLow, testCover, combination, coverCount)\n maxBreakCount = currentCoverCount\n maxBreakCombo = combination\n else:\n #print \"12312coverCount \" + str(coverCount)\n if (globalBreakCount == 12):\n if (maxBreakCount < coverCount):\n maxBreakCount = coverCount\n maxBreakCombo = combination\n else:\n currentCoverCount = getCoverOfCombo(globalBreakUpsHigh, globalBreakUpsLow, testCover, combination, coverCount)\n #print \"currentCover \" + str(currentCoverCount) + \" combo \" + combination\n if (maxBreakCount < currentCoverCount):\n# print \"combination\" + combination\n maxBreakCount = currentCoverCount\n maxBreakCombo = combination\n counter = counter + 1\n counter = 0\n comboListToCover.append(maxBreakCombo)\n globalBreakCount = globalBreakCount - maxBreakCount\n# print \"globalBreakCount \" + str(globalBreakCount)\n# print \"testCover[maxBreakCombo]\" + str(testCover[maxBreakCombo])\n for nodeName, breakTypeList in testCover[maxBreakCombo].items():\n #print nodeName + \" \" + str(breakTypeList)\n for breakType in breakTypeList:\n if (str(breakType) == '1'):\n globalBreakUpsHigh[nodeName] = 1\n if (str(breakType) == '0'):\n globalBreakUpsLow[nodeName] = 1\n maxBreakComboCount = 0\n maxBreakCombo = 0\n return comboListToCover\n","sub_path":"kidsvt_6th/ComboMaxCover.py","file_name":"ComboMaxCover.py","file_ext":"py","file_size_in_byte":6141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"521764716","text":"from gym import error\n\nfrom hanabi_environments.card import Card\nfrom hanabi_environments.hint import Hints\n\n\n# temporary\nDISCARD = 0\nPLAY = 1\nHINT = 2\n\n\nclass Player(object):\n '''\n initialization params:\n player_id - unique integer identification number for a Hanabi Player.\n n_inhand - number of Card objects in the hand of this Hanabi Player.\n empty_player - whether this player is a placeholder, 'empty', for\n dehugging purposes.\n\n public attributes:\n hand - a collection of Card objects that represents a player's hand.\n hints - a collect of hints that represents the hints a player can give.\n hints_given_to_me - collection of hints representing hints a player received.\n empty_player - for debugging, whether player is a placeholder.\n n_inhand - number of Card objects in the hand of Hanabi Player.\n other_player_hands - collection of Card objects representing other player's\n Hanabi card hands.\n player_id - unique integer identification number for a Hanabi Player.\n played_this_round - boolean value represents whether a player played this round.\n\n public methods:\n add_card_to_hand - add a passed in Card object to {self.hand}.\n add_hint_to_my_hints - add a passed in hint to {self.hints}.\n generate_all_hints - generate all hints a player could possible give this turn.\n get_hand - get the hand of Player, return {self.hand}.\n get_a_hint_to_give - returns a specific hint from {self.hints} given that index.\n get_hints_i_can_give - get the giveable hints of Player, return {self.hints}.\n get_other_player_hands - get the hands of other playerx this specific round.\n get_hand_indices - get the indices of valid cards in {self.hand}.\n get_player_state - return the \"player state\" of this Player to be processed in\n HanabiEnv.observation_space.\n get_player_id - get unique player identifier, return {self.player_jd}.\n parse_action - parse a possible action and reformat if possible.\n player_move - processes a possible action and handles possible errors.\n remove_card_from_hand - remove a Card object from {self.cards}.\n remove_hint_from_my_hints - remove a hint from {self.hints}.\n reset_hand - resets a player's hand, resets played_this_round.\n set_hand - pass in an existing hand and set {self.hand} to that hand.\n set_player_id - set the Plaer's unique {self.player_id} identifier.\n update_player_state - updates the Player's state when the new round starts.\n '''\n def __init__(self, player_id, n_inhand, empty_player=False):\n self.hand = []\n self.hints = []\n self.hints_given_to_me = []\n self.empty_player = empty_player\n self.n_inhand = n_inhand\n self.other_player_hands = {}\n self.player_id = player_id\n self.played_this_round = False\n\n def add_card_to_hand(self, add_card_index, card_to_add):\n '''If you play or discard a card, after removing a card, you will\n draw a card from the deck and add it to your hand.\n return Card object - the added card, which can be printed\n if in debug mode'''\n self.hand[add_card_index] = card_to_add\n return card_to_add\n\n def remove_card_from_hand(self, remove_card_index):\n '''If you play or discard a card, you will have to remove it from\n your hand. \n return Card object - the discarded card, which can be printed\n if in debug mode'''\n discarded_card = self.hand[remove_card_index]\n self.hand[remove_card_index] = Card(-1, -1)\n return discarded_card\n\n def add_hint_to_my_hints(self, hint):\n '''If you received a hint from another player, \n update hints_given_to_me to include that hint'''\n self.hints_given_to_me.append(hint)\n # hint is (0=color or 1= number, color or number, indices)\n\n def remove_hint_from_my_hints(self, card_index):\n '''\n Based on current hand, update the hints_given_to_me variable\n For example, if you just played a card, a hint given about the\n card you just played is no longer relevant and should be removed\n from hints_given_to_me or, if you just discarded a card and got\n a new card, the hint about the card that you just discaded is not\n relevant and should be removed from hints_given_to_me\n '''\n empty_hints = []\n for hint in self.hints_given_to_me:\n if card_index in hint[2]:\n hint[2].remove(card_index)\n if len(hint[2]) == 0:\n empty_hints.append(hint)\n for hint in empty_hints:\n self.hints_given_to_me.remove(hint)\n\n def generate_all_hints(self, player_dict):\n '''Generate all possible hints you could give.\n First update other player hands, then create a Hints object\n return Hints object - stores all the hints in a list of tuples: \n (player_id, (boolean color or number?, int representing exact color or number, indices))'''\n self.other_player_hands = self.get_other_player_hands(player_dict, for_step=False, listify=False)\n player_hints = Hints(self.player_id, self.other_player_hands).hints\n return player_hints\n\n def get_hand(self, for_step):\n '''Get the player hand. If for_step = True, use to return at the \n end of env.step() because the observation space desires a certain\n format as defined in env.observation_space'''\n if for_step:\n return [[card.color, card.number] for card in self.hand]\n else:\n return self.hand\n\n def get_hints_i_can_give(self):\n '''Get all possible hints the player can give\n return Hints object - stores all the hints in a list of tuples:\n (player_id, (boolean color or number?, int representing exact color or number, indices))'''\n return self.hints\n\n def get_a_hint_to_give(self, hint_index):\n '''Return a specific hint you want to give, given the index\n of that hint.\n returns a tuple of the format:\n (player_id, (boolean color or number?, int representing exact color or number, indices))'''\n if isinstance(hint_index, tuple): #this is for the server. is a tuple of player, index\n return hint_index\n return self.hints[hint_index]\n\n def get_other_player_hands(self, player_dict, for_step, listify):\n '''Update this player knowledge of other players hands\n return list if listify else dict - representing player and each of their hands'''\n other_hands = {}\n for player_id in player_dict.keys():\n if player_id != self.player_id:\n # print (player_id)\n # print (player_dict)\n other_hands[player_id] = player_dict[player_id].get_hand(for_step)\n other_hands_list = [(player_idx, other_hands[player_idx]) for player_idx in other_hands.keys()]\n if listify:\n return other_hands_list\n else:\n return other_hands\n\n def get_hand_indices(self):\n '''Get indices of valid cards in hand.\n return list of valid card indices - to be used when the agent is determining\n if they can play a specific card or not'''\n return [index for index, card in enumerate(self.hand) if card.is_valid()]\n\n def get_player_state(self, player_dict, for_step):\n '''Update the player state and return it. If for_step = True, \n use to return at the end of env.step() because the observation space \n desires a certain format as defined in env.observation_space\n return list - consists of the player id, their valid card \n indices, other players hands, hints given to this player, and hints this\n player can give to other players'''\n self.update_player_state(player_dict, for_step)\n return [self.player_id,\n self.get_hand_indices(),\n self.get_other_player_hands(player_dict, for_step, True),\n self.hints_given_to_me,\n self.hints]\n\n def get_player_id(self):\n '''Get this player id\n return int'''\n return self.player_id\n\n def no_cards_left(self):\n '''Get whether or not this player has any cards left\n return boolean - True if no cards left'''\n valid_cards = map(lambda x: x.is_valid(), self.hand.copy())\n return not any(valid_cards)\n\n def reset_all(self):\n '''Reset hand, hints the player can give, and hints player received\n to all empy lists. Use this when resetting the environment at the\n beginning of each game.'''\n self.hand = []\n self.played_this_round = False\n self.hints = []\n self.hints_given_to_me = []\n\n def set_hand(self, hand):\n '''Set the player hand to be a specific list of Card objects'''\n self.hand = hand\n\n def set_player_id(self, value):\n '''Set the player id to be an integer value'''\n self.player_id = value\n\n def update_player_state(self, player_dict, for_step):\n '''Update the player knowledge of other player cards and based\n on that, generate all possible hints it can give'''\n self.other_player_hands = self.get_other_player_hands(player_dict, for_step, listify=True)\n self.hints = self.generate_all_hints(player_dict)\n\n def parse_action(self, action):\n '''Search through the action space representation ((0,0), (0,0), (1,property))\n to extract (2, property), the desired action in the way env.step() can\n easily deal with it'''\n for action_index, action_tup in enumerate(action):\n if action_tup[0] == 1:\n return [action_index, action_tup[1]]\n\n def player_move(self, player_dict, error_handling_dict, action):\n '''\n Error handling of decided action based on other players' observation spaces,\n and community state: tokens, firework decks.\n '''\n self.update_player_state(player_dict, False)\n \n # fireworks = error_handling_dict['fireworks']\n # n_left_deck = len(error_handling_dict['deck'])\n # n_fuse_tokens = error_handling_dict['n_fuse_tokens']\n n_info_tokens = error_handling_dict['n_info_tokens']\n \n [action_index, action_property] = self.parse_action(action)\n # print (action_index, action_property)\n # discard, index of card to discard\n # play, index of card to play\n # hint, index of hint (from hint array) to give\n\n if action_index == DISCARD:\n if self.no_cards_left():\n raise error.Error(('invalid action attempted ({}),player ({})\\'s ' +\n 'hand has no cards left at all!').format(action_index,\n self.player_id))\n to_discard = self.hand[action_property]\n # print (to_discard)\n if to_discard.is_valid():\n valid_action = (action_index, action_property)\n else:\n raise error.Error(('invalid action attempted ({}),player ({})\\'s ' +\n 'card at discard index ({}) is not valid').format(action_index,\n self.player_id,\n action_property))\n elif action_index == PLAY:\n if self.no_cards_left():\n raise error.Error(('invalid action attempted ({}),player ({})\\'s ' +\n 'hand has no cards left at all!').format(action_index,\n self.player_id))\n to_play = self.hand[action_property]\n # print (to_play)\n if to_play.is_valid():\n valid_action = (action_index, action_property)\n else:\n raise error.Error(('invalid action attempted ({}),player ({})\\'s ' +\n 'card at play index {} is not valid').format(action_index,\n self.player_id,\n action_property))\n elif action_index == HINT:\n action_property = action_property \n if len(self.hints) == 0:\n raise error.Error(('invalid action attempted ({}), somehow there ' +\n 'are no available hints. This is likely a huge bug :(').format(action_index))\n elif (len(self.hints) - 1) < action_property: # TAKE OUT THE MODULO FOR NON RANDOM AGENT!!!\n raise error.Error(('invalid action attempted ({}), hint at index ({}) ' +\n 'is not a valid hint or is out of index!').format(action_index,\n action_property))\n elif n_info_tokens == 0:\n raise error.Error(('invalid action attempted ({}), There are no more info tokens left!').format(action_index))\n else:\n valid_action = (action_index, action_property)\n else:\n raise error.Error('invalid action attempted ({}), must be (0), (1), (2)'.format(action_index))\n return valid_action\n","sub_path":"hanabi_environments/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":13626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"553854458","text":"import cinrad\n#\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\nfrom matplotlib import cm, colors\nfrom matplotlib import cm\nimport matplotlib\nmatplotlib.use('TkAgg')\n# ncl调色板的配置\nfid = open('radar.rgb')\ndata=fid.readlines()\nn=len(data);\n#print(n)\nrgb=np.zeros((n,3))\nfor i in np.arange(n):\n #print(data[0].split(' '))\n rgb[i][0]=float(data[i].split(' ')[0])\n rgb[i][1]=data[i].split(' ')[1]\n rgb[i][2]=data[i].split(' ')[2]\nprint((rgb.shape))\n#print(rgb[253])\ncmaps= colors.ListedColormap(rgb)\n\n\n\n#matplotlib.use('TkAgg')\nf = cinrad.io.CinradReader('Z_RADR_I_Z9576_20190810000600_O_DOR_SA_CAP.bin.bz2')\ntilt_number = 0\ndata_radius = 230\ndata_dtype = 'REF' # stands for reflectivity\nra = f.get_data(tilt_number, data_radius, data_dtype)\n\nv = []\nv.append(ra)\ngmap =cinrad.easycalc.GridMapper(v)\ngrid = gmap(0.1)\nlon = grid.lon\nlat = grid.lat\ndata = grid.data\n\nh = []\nheight = ra.height\nrb = ra\nrb.data = height\nh.append(rb)\ngcma = cinrad.easycalc.GridMapper(h)\ngcmd = gcma(0.1)\nlon2 = gcmd.lon\nlat2 = gcmd.lat\nhig = gcmd.data\nfrom mpl_toolkits.mplot3d import Axes3D\nfig = plt.figure()\n# 创建3d图形的两种方式\n# ax = Axes3D(fig)\nax = fig.add_subplot(111, projection='3d')\ncolor_map =data.reshape(43*49)\nprint(color_map.shape)\n# ax.scatter(lon2, lat2,hig,c=color_map,cmap=cmaps, s=5)\n\n#ax.plot_surface(lon2, lat2,hig,facecolors=data,rstride=1, cstride=1, cmap=cmaps,shade=True)\nax.plot_surface(lon2, lat2,hig,facecolors=cmaps(data/100),rstride=1, cstride=1)\nprint(lon2.shape)\nprint(lat2.shape)\nprint(hig.shape)\nprint(data.shape)\n# ax.scatter(lon2, lat2,hig,cmap='jet', s=40,\n# label='Points')\n# ax.contourf(lon,lat,data,zdir='z',offset=-2)\nax.contourf(lon,lat,data,cmap=cmaps,zdir='z',offset=-20)\n\n\nplt.show()","sub_path":"met_plot/rader/pup/demo5.py","file_name":"demo5.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"417504352","text":"\"\"\"Module for enforcing module 'requires' statements.\"\"\"\n\nimport os\nimport shutil\nfrom typing import Union\nfrom pathlib import Path\n\nfrom mypy_extensions import TypedDict\n\nfrom astrality import utils\n\n\nclass RequirementDict(TypedDict, total=False):\n \"\"\"Available keys in requirement dictionary.\"\"\"\n\n shell: str\n timeout: Union[int, float]\n env: str\n installed: str\n\n\nclass Requirement:\n \"\"\"\n Class for determining if module dependencies are satisfied.\n\n Object is truthy if requirements are satisfied.\n\n :param requirements: Dictionary containing requirements.\n :param directory: Module directory.\n :param timeout: Default timeout for shell commands.\n \"\"\"\n\n successful: bool\n\n def __init__(\n self,\n requirements: RequirementDict,\n directory: Path,\n timeout: Union[int, float] = 1,\n ) -> None:\n \"\"\"Construct RequirementStatement object.\"\"\"\n self.successful: bool = True\n self.repr: str = ''\n\n # Check shell requirements\n if 'shell' in requirements:\n command = requirements['shell']\n result = utils.run_shell(\n command=command,\n fallback=False,\n timeout=requirements.get('timeout') or timeout,\n working_directory=directory,\n )\n if result is False:\n self.repr = f'Unsuccessful command: \"{command}\", '\n self.successful = False\n else:\n self.repr = f'Sucessful command: \"{command}\" (OK), '\n\n # Check environment requirements\n if 'env' in requirements:\n env_variable = requirements['env']\n if env_variable not in os.environ:\n self.repr += f'Missing environment variable: \"{env_variable}\", '\n self.successful = False\n else:\n self.repr += 'Found environment variable: ' \\\n f'\"{env_variable}\" (OK), '\n\n # Check installed requirements\n if 'installed' in requirements:\n program = requirements['installed']\n in_path = bool(shutil.which(program))\n if not in_path:\n self.repr += f'Program not installed: \"{program}\", '\n self.successful = False\n else:\n self.repr += f'Program installed: \"{program}\" (OK), '\n\n def __bool__(self) -> bool:\n \"\"\"Return True if all requirements are satisfied.\"\"\"\n return self.successful\n\n def __repr__(self) -> str:\n \"\"\"Return string representation of requirement object.\"\"\"\n self.repr = self.repr if self.repr else 'No requirements (OK), '\n return 'Module requirements: ' + self.repr\n","sub_path":"astrality/requirements.py","file_name":"requirements.py","file_ext":"py","file_size_in_byte":2729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"253738400","text":"from flask import redirect, url_for, g, current_app, render_template, request\nfrom maintain_frontend.decorators import requires_permission\nfrom maintain_frontend.constants.permissions import Permissions\nfrom maintain_frontend.send_payment_link.validation.customer_email_validator import CustomerEmailValidator\nfrom maintain_frontend.dependencies.audit_api.audit_api import AuditAPIService\nfrom maintain_frontend.dependencies.notification_api.notification_api_service import NotificationAPIService\nfrom maintain_frontend import config\n\n\ndef register_routes(bp):\n bp.add_url_rule('/enter-email', view_func=get_enter_email, methods=['GET'])\n bp.add_url_rule('/enter-email', view_func=post_enter_email, methods=['POST'])\n\n\n@requires_permission([Permissions.add_lon])\ndef get_enter_email():\n current_app.logger.info('Endpoint called')\n if g.session.send_payment_link_info is None:\n current_app.logger.info('Redirecting to: %s', url_for(\"send_payment_link.send_payment_link\"))\n return redirect(url_for(\"send_payment_link.send_payment_link\"))\n\n previous_data = None\n\n # If user information has already been set then populate for edit\n if g.session.send_payment_link_info.email is not None:\n current_app.logger.info(\"User information has been found, populating for edit\")\n previous_data = g.session.send_payment_link_info\n\n current_app.logger.info(\"Displaying page 'enter_email.html\")\n return render_template('enter_email.html',\n request_body=previous_data,\n submit_url=url_for(\"send_payment_link.post_enter_email\"))\n\n\n@requires_permission([Permissions.add_lon])\ndef post_enter_email():\n email = request.form.get('email')\n current_app.logger.info(\"Endpoint called with customer email as '{}'\".format(email))\n\n validator = CustomerEmailValidator.validate(email)\n if validator.errors:\n current_app.logger.warning(\"Validation errors found\")\n return render_template(\n 'enter_email.html',\n validation_errors=validator.errors,\n validation_summary_heading=validator.summary_heading_text,\n error_heading_message=validator.summary_heading_text,\n request_body=request.form,\n submit_url=url_for(\"send_payment_link.post_enter_email\")\n ), 400\n\n # Send email\n NotificationAPIService.send_message_notify(\n email,\n config.NOTIFY_PAYMENT_LINK_TEMPLATE_ID,\n {}\n )\n\n # Clear down the session information for payment\n g.session.send_payment_link_info = None\n g.session.commit()\n\n AuditAPIService.audit_event(\"LON payment link sent to user {}\".format(email))\n\n return render_template('email_confirmation.html')\n","sub_path":"maintain_frontend/send_payment_link/enter_email.py","file_name":"enter_email.py","file_ext":"py","file_size_in_byte":2733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"63488544","text":"import pandas as pd\r\nimport datetime\r\nimport os\r\nimport pickle\r\n\r\nstart = datetime.datetime.now()\r\n\r\nclass Day:\r\n def __init__(self, date, open, close, high, low):\r\n self.date = date\r\n self.day_open = open\r\n self.day_close = close\r\n self.day_high = high\r\n self.day_low = low\r\n self.put_option_chain = {'strike': [], 'premium': []}\r\n self.call_option_chain = {'strike': [], 'premium': []}\r\n\r\n if date.weekday() == 0:\r\n self.weekday_str = 'Monday'\r\n elif date.weekday() == 1:\r\n self.weekday_str = 'Tuesday'\r\n elif date.weekday() == 2:\r\n self.weekday_str = 'Wednesday'\r\n elif date.weekday() == 3:\r\n self.weekday_str = 'Thursday'\r\n elif date.weekday() == 4:\r\n self.weekday_str = 'Friday'\r\n\r\n def data_cleansing(self):\r\n for i in range(1, len(self.call_option_chain['strike'])):\r\n delta = self.call_option_chain['strike'][i] - self.call_option_chain['strike'][i - 1]\r\n if delta <= 0 or delta > 2.5:\r\n self.call_option_chain['strike'] = self.call_option_chain['strike'][:i]\r\n self.call_option_chain['premium'] = self.call_option_chain['premium'][:i]\r\n break\r\n\r\n for i in range(1, len(self.put_option_chain['strike'])):\r\n delta = self.put_option_chain['strike'][i] - self.put_option_chain['strike'][i - 1]\r\n if delta <= 0 or delta > 2.5:\r\n self.put_option_chain['strike'] = self.put_option_chain['strike'][:i]\r\n self.put_option_chain['premium'] = self.put_option_chain['premium'][:i]\r\n break\r\n\r\n def calc_profit(self, week_close):\r\n call_buy_index = 0\r\n while self.day_close > self.call_option_chain['strike'][call_buy_index]:\r\n call_buy_index += 1\r\n\r\n try:\r\n call_sell_index = self.call_option_chain['strike'].index(self.call_option_chain['strike'][call_buy_index] + testing_width)\r\n except ValueError:\r\n call_buy_index += 1\r\n call_sell_index = self.call_option_chain['strike'].index(self.call_option_chain['strike'][call_buy_index] + testing_width)\r\n\r\n self.call_premium = self.call_option_chain['premium'][call_buy_index] - self.call_option_chain['premium'][call_sell_index]\r\n while self.call_premium > testing_premium / 2.0:\r\n call_buy_index += 1\r\n call_sell_index += 1\r\n self.call_premium = self.call_option_chain['premium'][call_buy_index] - self.call_option_chain['premium'][call_sell_index]\r\n\r\n self.put_option_chain['strike'].reverse()\r\n self.put_option_chain['premium'].reverse()\r\n put_buy_index = 0\r\n while self.day_close < self.put_option_chain['strike'][put_buy_index]:\r\n put_buy_index += 1\r\n try:\r\n put_sell_index = self.put_option_chain['strike'].index(self.put_option_chain['strike'][put_buy_index] - testing_width)\r\n except ValueError:\r\n put_buy_index += 1\r\n put_sell_index = self.put_option_chain['strike'].index(self.put_option_chain['strike'][put_buy_index] - testing_width)\r\n\r\n self.put_premium = self.put_option_chain['premium'][put_buy_index] - self.put_option_chain['premium'][put_sell_index]\r\n while self.put_premium > testing_premium / 2.0:\r\n put_buy_index += 1\r\n put_sell_index += 1\r\n self.put_premium = self.put_option_chain['premium'][put_buy_index] - self.put_option_chain['premium'][put_sell_index]\r\n\r\n self.total_premium = self.call_premium + self.put_premium\r\n self.buy_put_strike = self.put_option_chain['strike'][put_buy_index]\r\n self.sell_put_strike = self.put_option_chain['strike'][put_sell_index]\r\n self.buy_call_strike = self.call_option_chain['strike'][call_buy_index]\r\n self.sell_call_strike = self.call_option_chain['strike'][call_sell_index]\r\n\r\n if week_close >= self.buy_put_strike and week_close <= self.buy_call_strike:\r\n self.profit = -self.total_premium * 100 * num_contracts\r\n elif week_close > self.buy_call_strike and week_close < self.sell_call_strike:\r\n self.profit = ((week_close - self.buy_call_strike) - self.total_premium) * 100 * num_contracts\r\n elif week_close < self.buy_put_strike and week_close > self.sell_put_strike:\r\n self.profit = ((self.buy_put_strike - week_close) - self.total_premium) * 100 * num_contracts\r\n elif week_close >= self.sell_call_strike or week_close <= self.sell_put_strike:\r\n self.profit = (testing_width - self.total_premium) * 100 * num_contracts\r\n else:\r\n raise Exception(\"Something went horribly wrong...\")\r\n\r\n return self.profit\r\n\r\n\r\nclass Week:\r\n def __init__(self):\r\n self.days_list = []\r\n\r\n\r\nfirst_year = int(input(\"Enter the beginning year: \"))\r\nlast_year = int(input(\"Enter the last year: \"))\r\ntesting_years = range(first_year, last_year + 1)\r\ntesting_width = 1.0\r\nnum_contracts = 1\r\n\r\n\r\n# testing_premium = float(input(\"Enter the testing premium: \"))\r\n# purchase_day = input(\"Enter the weekday of purchase: \")\r\n\r\ntesting_day_list = ['Monday', 'Tuesday', 'Wednesday', 'Thursday']\r\n\r\nweeks_list = []\r\nwith open(f'pickle_data/{testing_years[0]} - {testing_years[-1]}.pickle', 'rb') as pickle_in:\r\n weeks_list = pickle.load(pickle_in)\r\n\r\nbest_parameters = {'total_profit': 0.0, 'premium': 0.0, 'weekday': '', 'max_loss': 0.0, 'max_profit': 0.0, 'roi': 0.0}\r\nworst_parameters = {'total_profit': 0.0, 'premium': 0.0, 'weekday': '', 'max_loss': 0.0, 'max_profit': 0.0, 'roi': 0.0}\r\n\r\ntesting_premium = 0.2\r\nwhile testing_premium <= 0.85:\r\n for purchase_day in testing_day_list:\r\n parameters_profit = 0\r\n max_loss = 0\r\n max_profit = 0\r\n for week in weeks_list:\r\n for day in week.days_list:\r\n if day.weekday_str == purchase_day and len(day.call_option_chain['strike']) != 0:\r\n try:\r\n profit = day.calc_profit(week.days_list[-1].day_close)\r\n except:\r\n break\r\n\r\n if profit <= testing_premium * 100 * num_contracts:\r\n parameters_profit += profit\r\n if parameters_profit < max_loss:\r\n max_loss = parameters_profit\r\n elif parameters_profit > max_profit:\r\n max_profit = parameters_profit\r\n\r\n roi = (parameters_profit - abs(max_loss)) / abs(max_loss)\r\n\r\n print('\\nPerformance:')\r\n print(f'Profit: ${parameters_profit:,.2f}')\r\n print(f'Max loss: ${max_loss:,.2f}')\r\n print(f'Max Profit: ${max_profit:,.2f}')\r\n print(f'ROI: {roi * 100:.2}%')\r\n print('Parameters')\r\n print(f'Premium: {testing_premium}')\r\n print(f'Purchase day: {purchase_day}')\r\n\r\n if parameters_profit > best_parameters['total_profit']:\r\n best_parameters['total_profit'] = parameters_profit\r\n best_parameters['max_loss'] = max_loss\r\n best_parameters['max_profit'] = max_profit\r\n best_parameters['premium'] = testing_premium\r\n best_parameters['weekday'] = purchase_day\r\n best_parameters['roi'] = roi\r\n elif parameters_profit < worst_parameters['total_profit']:\r\n worst_parameters['total_profit'] = parameters_profit\r\n worst_parameters['max_loss'] = max_loss\r\n worst_parameters['max_profit'] = max_profit\r\n worst_parameters['premium'] = testing_premium\r\n worst_parameters['weekday'] = purchase_day\r\n worst_parameters['roi'] = roi\r\n\r\n testing_premium += 0.05\r\n\r\nprint('\\nBest Parameters:\\n')\r\nprint('Performance')\r\nprint(f'Profit: ${best_parameters[\"total_profit\"]:,.2f}')\r\nprint(f'Max loss: ${best_parameters[\"max_loss\"]:,.2f}')\r\nprint(f'Max profit: ${best_parameters[\"max_profit\"]:,.2f}')\r\nprint(f'ROI: {best_parameters[\"roi\"] * 100:.2f}%')\r\nprint('Parameters')\r\nprint(f'Premium: {best_parameters[\"premium\"]:.2f}')\r\nprint(f'Purchase day: {best_parameters[\"weekday\"]}')\r\n\r\nprint('\\nWorst Parameters:\\n')\r\nprint('Performance')\r\nprint(f'Profit: ${worst_parameters[\"total_profit\"]:,.2f}')\r\nprint(f'Max loss: ${worst_parameters[\"max_loss\"]:,.2f}')\r\nprint(f'Max profit: ${worst_parameters[\"max_profit\"]:,.2f}')\r\nprint(f'ROI: {worst_parameters[\"roi\"] * 100:.2f}%')\r\nprint('Parameters')\r\nprint(f'Premium: {worst_parameters[\"premium\"]:.2f}')\r\nprint(f'Purchase day: {worst_parameters[\"weekday\"]}')\r\n\r\nend = datetime.datetime.now()\r\nprint(f'\\nElapsed time: {end - start}')\r\n","sub_path":"Wharton/opt.py","file_name":"opt.py","file_ext":"py","file_size_in_byte":8689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"554900730","text":"#!/usr/bin/env python\nimport sys, os\nimport argparse\n\nimport numpy as np\nimport pandas as pd\nimport uproot\nimport csv, yaml\n\nimport h5py\nimport torch\nimport torch.nn as nn\nimport matplotlib.pyplot as plt\nparser = argparse.ArgumentParser()\nparser.add_argument('--config', action='store', type=str, default='config.yaml', help='Configration file with sample information')\nparser.add_argument('-o', '--output', action='store', type=str, required=True, help='Path to output file')\n#parser.add_argument('-t', '--train', action='store', type=str, required=True, help='Path to training results directory')\nparser.add_argument('-a', '--all', action='store_true', help='use all events for the evaluation, no split')\n\nparser.add_argument('--device', action='store', type=int, default=0, help='device name')\nparser.add_argument('--batch', action='store', type=int, default=256, help='Batch size')\nparser.add_argument('--seed', action='store', type=int, default=12345, help='random seed')\nargs = parser.parse_args()\n\nconfig = yaml.load(open(args.config).read(), Loader=yaml.FullLoader)\nif args.seed: config['training']['randomSeed1'] = args.seed\n\nsys.path.append(\"./python\")\n\ntorch.set_num_threads(os.cpu_count())\nif torch.cuda.is_available() and args.device >= 0: torch.cuda.set_device(args.device)\n\n##### Define dataset instance #####\nfrom dataset.PSDDataset_vae_nomax_1ch import *\n##### Define dataset instance #####\ndset = PSDDataset_vae_nomax_1ch(channel=config['format']['channel'])\nfor sampleInfo in config['samples']:\n if 'ignore' in sampleInfo and sampleInfo['ignore']: continue\n name = sampleInfo['name']\n dset.addSample(name, sampleInfo['path'], weight=sampleInfo['xsec']/sampleInfo['ngen'])\n dset.setProcessLabel(name, sampleInfo['label'])\ndset.initialize()\nlengths = [int(x*len(dset)) for x in config['training']['splitFractions']]\nlengths.append(len(dset)-sum(lengths))\ntorch.manual_seed(config['training']['randomSeed1'])\nkwargs = {'num_workers':min(config['training']['nDataLoaders'], os.cpu_count()),\n 'batch_size':args.batch, 'pin_memory':False}\nfrom torch.utils.data import DataLoader\nif args.all:\n testLoader = DataLoader(dset, **kwargs)\nelse:\n trnDset, valDset, testDset = torch.utils.data.random_split(dset, lengths)\n #testLoader = DataLoader(trnDset, **kwargs)\n #testLoader = DataLoader(valDset, **kwargs)\n testLoader = DataLoader(testDset, **kwargs)\ntorch.manual_seed(torch.initial_seed())\n\n##### Define model instance #####\nfrom models.allModels_ae import *\n#model = WF1DCNNModel(nChannel=dset.nCh, nPoint=dset.nPt)\nmodel = torch.load('result/' + args.output+'/model.pth', map_location='cpu')\nmodel.load_state_dict(torch.load('result/' + args.output+'/weight.pth', map_location='cpu'))\n# model.fc.add_module('output', torch.nn.Sigmoid())\n\ndevice = 'cpu'\nif args.device >= 0 and torch.cuda.is_available():\n model = model.cuda()\n device = 'cuda'\n\ndd = 'result/' + args.output + '/train.csv'\n\nplt.rcParams['lines.linewidth'] = 1\nplt.rcParams['lines.markersize'] = 5\nplt.rcParams[\"legend.loc\"] = 'upper right'\nplt.rcParams[\"legend.frameon\"] = False\nplt.rcParams[\"legend.loc\"] = 'upper left'\nplt.rcParams['figure.figsize'] = (4*2, 3.5*3)\n\nax1 = plt.subplot(3, 2, 1, yscale='log', ylabel='Loss(train)', xlabel='epoch')\nax2 = plt.subplot(3, 2, 2, yscale='log', ylabel='Loss(val)', xlabel='epoch')\n# ax3 = plt.subplot(3, 2, 3, ylabel='Accuracy(train)', xlabel='epoch')\n# ax4 = plt.subplot(3, 2, 4, ylabel='Accuracy(val)', xlabel='epoch')\n#ax1.set_ylim([3e-2,1e-0])\n#ax2.set_ylim([3e-2,1e-0])\n# ax3.set_ylim([0.50,1])\n# ax4.set_ylim([0.50,1])\nfor ax in (ax1, ax2):\n ax.grid(which='major', axis='both', linestyle='-.')\n ax.grid(which='minor', linestyle=':')\n ax.set_xlim([0,400])\nlines, labels = [], []\n\ndff = pd.read_csv(dd)\n\nlabel = dd.split('/')[-1].replace('__', ' ').replace('_', '=')\n\nl = ax1.plot(dff['loss'], '.-', label=label)\nax2.plot(dff['val_loss'], '.-', label=label)\n\n# ax3.plot(dff['acc'], '.-', label=label)\n# ax4.plot(dff['val_acc'], '.-', label=label)\n\nlines.append(l[0])\nlabels.append(label)\n\nax5 = plt.subplot(3,1,3)\nax5.legend(lines, labels)\nax5.axis('off')\n\nplt.tight_layout()\nplt.savefig('result/' + args.output + '/' + args.output + '_loss.png', dpi=300)\n\n#plt.show()\n#plt.close()\nplt.clf()\n\n\n\n##### Start evaluation #####\nfrom tqdm import tqdm\n\nweights = []\nmodel.eval()\nval_loss= 0.\ntrain = {'recon_wf':[], 'origin_wf':[]}\nfor i, (data, label0, weight, rescale, procIdx, fileIdx, idx) in enumerate(tqdm(testLoader)):\n \n data = data.to(device)\n \n output = model(data)\n \n \n train['recon_wf'].append(output)\n train['origin_wf'].append(data)\n \n \n with open(os.path.join('result/'+args.output+'/recon_wf.csv'), 'w') as f:\n writer = csv.writer(f)\n keys = train.keys()\n writer.writerow(keys)\n for row in zip(*[train[key] for key in keys]):\n writer.writerow(row)","sub_path":"eval_ae_nomax_1ch.py","file_name":"eval_ae_nomax_1ch.py","file_ext":"py","file_size_in_byte":4906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"304431456","text":"# pymol_helicity_check.py\n# Copyright (c) 2006-2007 Julien Lefeuvre \n#\n \n\"\"\"\nPymol plugin for checking helicity type\n \nhelicity_check() takes as input a selection ('sele' by default)\nof at least 5 amino acids and computes the distances between\nO(i) - N(i+3)\nO(i) - N(i+4)\nO(i) - N(i+5)\nSee for further info:\nProtein Sci ROHL and DOIG 5 (8) 1687\n'Models for the 3(10)-helix/coil, pi-helix/coil,\nand alpha-helix/3(10)-helix/coil transitions in isolated peptides.'\n \nuses:\n*in the pymol console:\n >run pymol_helicity_check.py\n ----> select some consecutive amino acids\n - this is nicely done with the Display->Sequence tool\n >helicity_check()\n*installing helicity_check\n copy pymol_helicity_check.py in $PYMOL_INSTALL_DIR/modules/pmg_tk/startup\n launch Pymol: you now have a new option in the Plugin menu\n \nhelicity_check uses gnuplot (http://www.gnuplot.info) to display its results\nAs a consequence gnuplot needs to be installed.\n \nThis plugin was tested on linux only, it my need some modifications to run on\nother OSes (hints: launching gnuplot and path to dumpfile)\n\"\"\"\n \n__author__ = \"Julien Lefeuvre \"\n__version__ = \"1.0\"\n__date__ = \"2007-04-02\"\n__copyright__ = \"Copyright (c) 2007 %s. All rights reserved.\" % __author__\n__licence__ = \"BSD\"\n \nfrom pymol import cmd\nfrom math import sqrt\nimport sys\nimport os\nimport subprocess\nimport time\n \ndef __init__(self):\n \"\"\"init function in order to have a nice menu option in Pymol\"\"\"\n self.menuBar.addmenuitem('Plugin', 'command', 'Helicity Check',\n label='Helicity Check', command = lambda: helicity_check())\n \n \nclass Residue(object):\n \n def __init__(self):\n self.name=None\n self.index=None\n self.Ocoord=None\n self.Ncoord=None\n \n \ndef calc_distON(Ocoord,Ncoord):\n \"\"\"return the distance between 2 atoms given their coordinates\"\"\"\n sum = 0\n for o, n in zip(Ocoord, Ncoord):\n sum += (o - n)**2\n return sqrt(sum)\n \n \ndef helicity_check(selection='sele'):\n \"\"\"calcultate distance O[res i]-N[res i+3]\n O[res i]-N[res i+4]\n O[res i]-N[res i+5]\n \"\"\"\n seq_model = cmd.get_model(selection) #get info from selection\n res_lim = seq_model.get_residues()\n \n if len(res_lim)<5:\n sys.stderr.write(\"\\nPlease select at least 5 residues\\n\")\n return\n \n atom_list = seq_model.atom\n res_data=[]\n \n for start,end in res_lim: #extract the data we are interested in\n res=Residue()\n for atom in atom_list[start:end]:\n if atom.name == 'N':\n res.name = atom.resn\n res.index = atom.resi\n res.Ncoord = atom.coord\n elif atom.name == 'O':\n res.Ocoord = atom.coord\n if res.Ocoord and res.Ncoord and res.name and res.index:\n res_data.append(res)\n else:\n sys.stderr.write(\"\\nPlease select complete protein residues\\n\")\n return\n \n res_list = [int(res.index) for res in res_data]\n \n if res_list != range(res_list[0], res_list[-1]+1):\n sys.stderr.write(\"\\nPlease select a unbrocken residue sequence\\n\")\n return\n \n distON3 = []\n distON4 = []\n distON5 = []\n distONs = [distON3, distON4, distON5]\n \n for i,res in enumerate(res_data[:-5]): #distances calculations\n resis = res_data[i+3:i+6]\n for resi, distONi in zip(resis, distONs):\n distONi.append(calc_distON(res.Ocoord, resi.Ncoord))\n \n dump = os.tmpnam()+'.dat'\n dumpfile = file(dump, 'w')\n \n sys.stdout.write('\\n#Distances O(i)---N(i+n)\\n'\n '#ResNum , d(O(i)-N(i+3)) , d(O(i)-N(i+4)) , d(O(i)-N(i+4))\\n')\n for i, d3, d4, d5 in zip(res_list, distON3, distON4, distON5):\n #writing console output\n sys.stdout.write(\n ' %i , %f , %f , %f \\n'%(i, d3, d4, d5))\n #writing data to a dump file for use by gnuplot\n dumpfile.write(\n ' %i %f %f %f \\n'%(i, d3, d4, d5))\n dumpfile.flush()\n \n #launch a gnuplot window to show the distances\n gnuplotcmd = subprocess.Popen(['/usr/bin/gnuplot'], shell=True,\n stdin=subprocess.PIPE)\n gnuplotcmd.stdin.write('set autoscale\\n')\n gnuplotcmd.stdin.write(\"plot \"\n \"'%s' using 1:2 title 'd(O(i)-N(i+3))' with lines, \"\n \"'%s' using 1:3 title 'd(O(i)-N(i+4))' with lines, \"\n \"'%s' using 1:4 title 'd(O(i)-N(i+5))' with lines\\n'\"\n % (dump, dump, dump))\n time.sleep(3)\n dumpfile.close()\n os.remove(dump)\n","sub_path":"structural_biology_scripts/pymol_helicity_check.py","file_name":"pymol_helicity_check.py","file_ext":"py","file_size_in_byte":4648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"556013057","text":"import argparse\n\nfrom config import port, text_files_dir\n\n\ndef get_args():\n ap = argparse.ArgumentParser('Create exercises from German text.')\n\n # Add args\n ap.add_argument('-d', '--debug',\n action='store_true',\n help=\"Enable debugging mode.\")\n\n ap.add_argument('-p', '--port', type=int,\n help=\"Port number to run this service on.\",\n default=port)\n\n ap.add_argument('-t', '--text-files-dir',\n help=\"Directory to store uploaded text files.\",\n default=text_files_dir)\n\n return ap.parse_args()\n","sub_path":"args.py","file_name":"args.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"269354907","text":"from level import level_map\nfrom game_settings import *\nfrom level import LEVEL_HEIGHT, LEVEL_WIDTH\nimport pygame\n\n\ndef mapping(x, y):\n return (x // CELL) * CELL, (y // CELL) * CELL\n\n\ndef ray_casting(player_pos, player_angle):\n casted_walls = []\n x_start, y_start = player_pos\n x_angle, y_angle = mapping(x_start, y_start)\n current_angle = player_angle - HALF_FIELD_OF_VIEW\n for ray in range(NUMBER_OF_RAYS):\n sin_angle = sin(current_angle)\n sin_angle = sin_angle if sin_angle else 0.000001\n cos_angle = cos(current_angle)\n cos_angle = cos_angle if cos_angle else 0.000001\n horizontal_texture, vertical_texture = 1, 1\n if cos_angle >= 0:\n x, k = x_angle + CELL, 1\n else:\n x, k = x_angle, -1\n\n for i in range(0, LEVEL_WIDTH, CELL):\n vertical_depth = (x - x_start) / cos_angle\n vertical_y = y_start + vertical_depth * sin_angle\n vertical_tile = mapping(x + k, vertical_y)\n if vertical_tile in level_map:\n vertical_texture = level_map[vertical_tile]\n break\n x += k * CELL\n\n if sin_angle >= 0:\n y, k = y_angle + CELL, 1\n else:\n y, k = y_angle, -1\n\n for i in range(0, LEVEL_HEIGHT, CELL):\n horizontal_depth = (y - y_start) / sin_angle\n horizontal_x = x_start + horizontal_depth * cos_angle\n horizontal_tile = mapping(horizontal_x, y + k)\n if horizontal_tile in level_map:\n horizontal_texture = level_map[horizontal_tile]\n break\n y += k * CELL\n\n depth, offset, texture = (vertical_depth, vertical_y, vertical_texture)\\\n if vertical_depth < horizontal_depth \\\n else (horizontal_depth, horizontal_x, horizontal_texture)\n offset = int(offset) % CELL\n depth *= cos(player_angle - current_angle)\n depth = max(depth, 0.000001)\n projection_height = int(COEFFICIENT / depth)\n current_angle += DELTA_OF_ANGLE\n casted_walls.append((depth, offset, projection_height, texture))\n return casted_walls\n\n\ndef ray_castings_walls(player, textures):\n walls = []\n casted_walls = ray_casting(player.get_position(), player.angle)\n shot = casted_walls[CENTRAL_RAY][0], casted_walls[CENTRAL_RAY][2]\n for ray, values in enumerate(casted_walls):\n depth, offset, projection_height, texture = values\n if projection_height > HEIGHT:\n k = projection_height / HEIGHT\n texture_height = TEXTURE_HEIGHT / k\n wall = textures[texture].subsurface(offset * TEXTURE_SCALE,\n HALF_TEXTURE_HEIGHT - texture_height // 2,\n TEXTURE_SCALE, texture_height)\n wall = pygame.transform.scale(wall, (SCALE, HEIGHT))\n wall_pos = (ray * SCALE, 0)\n else:\n wall = textures[texture].subsurface(offset * TEXTURE_SCALE, 0, TEXTURE_SCALE,\n TEXTURE_HEIGHT)\n wall = pygame.transform.scale(wall, (SCALE, projection_height))\n wall_pos = (ray * SCALE, HALF_HEIGHT - projection_height // 2)\n walls.append((depth, wall, wall_pos))\n return walls, shot\n","sub_path":"ray_cast.py","file_name":"ray_cast.py","file_ext":"py","file_size_in_byte":3333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"433681228","text":"import sys\nimport random\nfrom PySide6 import *\nimport numpy as np\nimport scipy.signal as sc\n\ndef resize_fit_to_screen(fen, img):\n ratio = img.width/img.height\n fen_ratio = fen.width/fen.height\n\n if fen_ratio>ratio :\n img = img.resize((int(fen.height*ratio),fen.height),Image.BICUBIC, None, 3)\n else :\n img = img.resize((fen.width,int(fen.width/ratio)),Image.BICUBIC,None, 3)\n \n noyau = np.array([[0, -0.1, 0],[-0.1, 1.5, -0.1],[0, -0.1, 0]])\n Filtre_convo(noyau, img)\n\n return img\n\ndef Filtre_convo(noyau, img):\n i=0\n j=0\n size = img.size\n mat_px = img.load()\n R = np.zeros(size)\n G = np.zeros(size)\n B = np.zeros(size)\n\n print (\"traitement de l'image en cours ...\")\n\n while (i < size[0]):\n j=0\n while (j < size[1]):\n R[i,j] = mat_px[i,j][0]\n G[i,j] = mat_px[i,j][1]\n B[i,j] = mat_px[i,j][2]\n j += 1\n i += 1\n\n print (\"Division en matrices RGB ok.\")\n\n R = sc.fftconvolve(noyau, R)\n G = sc.fftconvolve(noyau, G)\n B = sc.fftconvolve(noyau, B)\n\n print (\"Convolution ok.\")\n\n i=0\n while (i < size[0]):\n j=0\n while (j < size[1]):\n if (R[i,j]>255):\n R[i,j]=255\n if (G[i,j]>255):\n G[i,j]=255\n if (B[i,j]>255):\n B[i,j]=255\n if (R[i,j]<0):\n R[i,j]=0\n if (G[i,j]<0):\n G[i,j]=0\n if (B[i,j]<0):\n B[i,j]=0\n mat_px[i,j] = (int(R[i,j]),int(G[i,j]),int(B[i,j])) \n j += 1\n i += 1\n \n print (\"traitement de l'image fini !\")\n\n return img","sub_path":"Cadre_numerique_fct.py","file_name":"Cadre_numerique_fct.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"380481718","text":"import urllib.parse, urllib.request, urllib.error, json\nimport random\nimport keys as keys\nfrom flask import Flask, render_template, request\n\napp = Flask(__name__)\n\ndef pretty(obj):\n return json.dumps(obj, sort_keys=True, indent=2)\n\n## Encode query parameters and create a URL to the API\nbaseurl = 'https://emoji-api.com/emojis'\nparamstr = {\"access_key\":keys.emojikey}\nfullurl = baseurl+\"?\"+urllib.parse.urlencode(paramstr)\n\n## Handle any errors due to HTTP or connection related exceptions\ndef safeGet(url):\n try:\n header = {'User-Agent': 'Mozilla/5.0'}\n req = urllib.request.Request(url, headers=header)\n x = urllib.request.urlopen(req)\n return x\n except urllib.error.URLError as e:\n if hasattr(e, \"code\"):\n print(\"Error trying to retrieve data:\", e)\n elif hasattr(e, 'reason'):\n print(\"We failed to reach a server\")\n print(\"Reason: \", e.reason)\n return None\n\n## The function that takes url to call the API\ndef callPI(url):\n requeststr = safeGet(url).read()\n return json.loads(requeststr)\n\nemojilist = callPI(fullurl)\nemojiGroups = {}\nfor i in emojilist:\n if i[\"group\"] not in emojiGroups:\n emojiGroups[i[\"group\"]] = []\n emojiGroups[i[\"group\"]].append(i[\"codePoint\"])\n else:\n emojiGroups[i[\"group\"]].append(i[\"codePoint\"])\n\ndef getKeywordEmoji(codePoint):\n for i in emojilist:\n if i['codePoint'] == codePoint:\n return i['subGroup']\n\ndef noRepeatWord(list):\n newList = []\n if list != [None]:\n for i in list:\n hyphenWords = i.split(\"-\")\n for word in hyphenWords:\n if word not in newList:\n newList.append(word)\n return newList\n\n@app.route(\"/\")\ndef main_handler():\n return render_template('index.html', page_title=\"Emoji Input\")\n\nclass spotiClient():\n def __init__(self):\n self.accessToken = None\n self.spotifyAuth()\n\n def spotifyAuth(self):\n import base64\n authorization = base64.standard_b64encode((keys.spotifyid +\n ':' + keys.spotifykey).encode())\n headers = {\"Authorization\": \"Basic \" + authorization.decode()}\n params = {\"grant_type\": \"client_credentials\"}\n encodedparams = urllib.parse.urlencode(params).encode()\n request = urllib.request.Request(\n 'https://accounts.spotify.com/api/token',\n data=encodedparams, headers=headers)\n resp = urllib.request.urlopen(request)\n respdata = json.load(resp)\n self.accessToken = respdata['access_token']\n\n def apiRequest(self,\n version=\"v1\",\n endpoint=\"search\",\n item=None,\n params=None):\n if self.accessToken is None:\n print(\n \"Sorry, you must have an access token for this to work.\")\n return {}\n baseurl = \"https://api.spotify.com/\"\n endpointurl = \"%s%s/%s\" % (baseurl, version, endpoint)\n if item is not None:\n endpointurl = endpointurl + \"/\" + item\n if params is not None:\n fullurl = endpointurl + \"?\" + urllib.parse.urlencode(params)\n headers = {\"Authorization\": \"Bearer \" + self.accessToken}\n request = urllib.request.Request(fullurl, headers=headers)\n resp = urllib.request.urlopen(request)\n return json.load(resp)\n\n@app.route(\"/response\", methods=['POST'])\ndef response_handler():\n\n if request.method == 'POST':\n emoji = request.form.get('emojilist')\n codePointList = emoji.split(\",\")\n keywords = []\n for i in codePointList:\n keywords.append(getKeywordEmoji(i))\n\n sclient = spotiClient()\n links = []\n info = {}\n if len(noRepeatWord(keywords)) != 0:\n query = random.choice(noRepeatWord(keywords))\n results = sclient.apiRequest(params={\"q\": query, \"type\": \"track\", \"limit\": \"20\"})\n for k in results['tracks']['items']:\n links.append(k['external_urls']['spotify'])\n info[k['external_urls']['spotify']] = {}\n info[k['external_urls']['spotify']]['artist'] = k['artists'][0]['name']\n info[k['external_urls']['spotify']]['img'] = k['album']['images'][0]['url']\n info[k['external_urls']['spotify']]['name'] = k['name']\n else:\n links.append('https://open.spotify.com/track/1OEwH8MNTyvksafcZjSfnL?si=D_bF5gg-Q7aTRo1GPvr-eA')\n info['https://open.spotify.com/track/1OEwH8MNTyvksafcZjSfnL?si=D_bF5gg-Q7aTRo1GPvr-eA'] = {}\n info['https://open.spotify.com/track/1OEwH8MNTyvksafcZjSfnL?si=D_bF5gg-Q7aTRo1GPvr-eA']['artist'] = 'Kevin Farrell'\n info['https://open.spotify.com/track/1OEwH8MNTyvksafcZjSfnL?si=D_bF5gg-Q7aTRo1GPvr-eA']['img'] = 'https://i.scdn.co/image/ab67616d00001e027537b57f46602cca4e47a8d8'\n info['https://open.spotify.com/track/1OEwH8MNTyvksafcZjSfnL?si=D_bF5gg-Q7aTRo1GPvr-eA']['name'] = 'Please Choose One'\n finaltrack = random.choice(links)\n return render_template('response.html', input=finaltrack, image=info[finaltrack]['img'],\n artist=info[finaltrack]['artist'], trackname=info[finaltrack]['name'])\n else:\n return render_template('index.html')\n\nif __name__ == \"__main__\":\n app.run(host=\"localhost\", port=8080, debug=True )","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"170505618","text":"from bs4 import BeautifulSoup\nimport requests\nimport fileinput\nimport subprocess\nimport os\nimport sys\nimport glob\n\ndef get_content():\n # get plot overview section\n url = main_url+'summary/'\n response = requests.get(url)\n analyze_overview(response.text)\n\n # get all the chapters\n section, page = 1, 1\n new_section = True\n while True:\n url = main_url + 'section{}/page/{}/'.format(section, page)\n response = requests.get(url)\n\n if response.status_code == 200:\n analyze_section(response.text, new_section)\n new_section = False\n page += 1\n elif page != 1:\n new_section = True\n page = 1\n section += 1\n else:\n break\n\n # get the character summaries\n url = main_url+'characters/'\n response = requests.get(url)\n if response.status_code == 200:\n analyze_characters(response.text)\n\n # get the themes\n page = 1\n new_section = True\n while True:\n url = main_url + 'themes/page/{}/'.format(page)\n response = requests.get(url)\n\n if response.status_code == 200:\n analyze_themes(response.text, new_section)\n new_section = False\n page += 1\n else:\n break\n\n # get the important quotations\n page = 1\n new_section = True\n while True:\n url = main_url + 'quotes/page/{}/'.format(page)\n response = requests.get(url)\n\n if response.status_code == 200:\n analyze_quotes(response.text, new_section)\n new_section = False\n page += 1\n else:\n break\n\ndef analyze_overview(text):\n soup = BeautifulSoup(text, 'html.parser')\n\n content[0]['title'] = 'Plot Overview'\n content[0]['text'] = [p.text for p in soup.findAll('p')[:-2]]\n\ndef analyze_section(text, new_section):\n soup = BeautifulSoup(text, 'html.parser')\n\n if new_section:\n entry = {'text':[]}\n entry['title'] = soup.findAll('title')[0].text[len(book_title) + 2:]\n else:\n entry = content[1][-1]\n \n first_meaningless_header = soup.findAll('h3', {'class':'more-like-this__title'})[0]\n headers = soup.findAll('h3')\n headers = headers[:headers.index(first_meaningless_header)]\n\n if len(headers) == 0:\n p = soup.findAll('p')[0]\n while p:\n entry['text'][-1].append(p.text)\n p = p.find_next_sibling('p')\n elif not new_section:\n p = headers[0].find_next_sibling('p')\n while p.find_previous_sibling('p'):\n p = p.find_previous_sibling('p')\n\n for i in range(len(headers)):\n if i > 0:\n entry['text'].append([headers[i-1].text])\n next_header = headers[i]\n while p != next_header.find_next_sibling('p'):\n entry['text'][-1].append(p.text)\n p = p.find_next_sibling('p')\n\n entry['text'].append([headers[-1].text])\n while p:\n entry['text'][-1].append(p.text)\n p = p.find_next_sibling('p')\n else:\n p = headers[0].find_next_sibling('p')\n for i in range(len(headers)-1):\n entry['text'].append([headers[i].text])\n next_header = headers[i+1]\n while p != next_header.find_next_sibling('p'):\n entry['text'][i].append(p.text)\n p = p.find_next_sibling('p')\n\n entry['text'].append([headers[-1].text])\n while p:\n entry['text'][-1].append(p.text)\n p = p.find_next_sibling('p')\n\n if new_section:\n content[1].append(entry)\n\ndef analyze_characters(text):\n soup = BeautifulSoup(text, 'html.parser')\n entry = {'title': 'Characters', 'text':[]}\n characters = soup.findAll('div', class_='content_txt')\n\n for character in characters:\n name = character.findAll('b')[0].text\n\n c = character.text\n i0 = c.index('\\xa0-\\xa0')\n # sometimes there is no leading whitespace after hyphen\n if not c[i0+3].isspace():\n i0 -= 1\n\n try:\n i1 = c.index('Read an\\n')\n description = c[i0+4:i1]\n except ValueError:\n description = c[i0+4:]\n\n entry['text'].append([name, description])\n\n content[2] = entry\n\ndef analyze_themes(text, new_section):\n soup = BeautifulSoup(text, 'html.parser')\n\n if new_section:\n entry = {'text':[]}\n entry['title'] = soup.findAll('title')[0].text[len(book_title) + 2:]\n else:\n entry = content[3]\n \n first_meaningless_header = soup.findAll('h3', {'class':'more-like-this__title'})[0]\n headers = soup.findAll('h3')\n headers = headers[:headers.index(first_meaningless_header)]\n\n if len(headers) == 0:\n p = soup.findAll('p')[0]\n while p:\n entry['text'][-1].append(p.text)\n p = p.find_next_sibling('p')\n elif not new_section:\n p = headers[0].find_next_sibling('p')\n while p.find_previous_sibling('p'):\n p = p.find_previous_sibling('p')\n\n for i in range(len(headers)):\n if i > 0:\n entry['text'].append([headers[i-1].text])\n next_header = headers[i]\n while p != next_header.find_next_sibling('p'):\n entry['text'][-1].append(p.text)\n p = p.find_next_sibling('p')\n\n entry['text'].append([headers[-1].text])\n while p:\n entry['text'][-1].append(p.text)\n p = p.find_next_sibling('p')\n else:\n p = headers[0].find_next_sibling('p')\n for i in range(len(headers)-1):\n entry['text'].append([headers[i].text])\n next_header = headers[i+1]\n while p != next_header.find_next_sibling('p'):\n entry['text'][i].append(p.text)\n p = p.find_next_sibling('p')\n\n entry['text'].append([headers[-1].text])\n while p:\n entry['text'][-1].append(p.text)\n p = p.find_next_sibling('p')\n\n if new_section:\n content[3] = entry\n\ndef analyze_quotes(text, new_section):\n soup = BeautifulSoup(text, 'html.parser')\n if new_section:\n entry = {'text':[]}\n entry['title'] = 'Important Quotations'\n else:\n entry = content[4]\n\n entry['text'].append([soup.findAll('h3')[0].text])\n quote = soup.findAll('blockquote', class_='mainTextContent__quote__line')[0].text\n entry['text'][-1].append(quote)\n\n p = soup.findAll('p')[0]\n while p:\n entry['text'][-1].append(p.text)\n p = p.find_next_sibling('p')\n\n if new_section:\n content[4] = entry\n\ndef write_to_pdf():\n def write_section(e, isQuoteSection=False):\n f.write('\\n\\\\newpage\\n')\n f.write('\\\\section{'+str(e['title'])+'}\\n')\n f.write('\\\\textbf{\\\\large{'+str(e['text'][0][0])+'}} \\n\\\\medskip\\n\\n')\n if not isQuoteSection:\n for p in e['text'][0][1:]:\n f.write(p+'\\n\\n')\n for pp in e['text'][1:]:\n f.write('\\\\bigskip\\n\\\\bigskip\\n')\n f.write('\\\\textbf{\\\\large{'+str(pp[0])+'}} \\n\\\\medskip\\n\\n')\n for p in pp[1:]:\n f.write(p+'\\n\\n')\n else:\n f.write('\\\\begin{center}\\n\\\\small{\\\\textit{'+str(e['text'][0][1])+'}}\\n\\\\end{center}\\n\\n')\n for p in e['text'][0][2:]:\n f.write(p+'\\n\\n')\n\n for pp in e['text'][1:]:\n f.write('\\\\bigskip\\n\\\\bigskip\\n')\n f.write('\\\\textbf{\\\\large{'+str(pp[0])+'}} \\n\\\\medskip\\n\\n')\n f.write('\\\\begin{center}\\n\\\\small{\\\\textit{'+str(pp[1])+'}}\\n\\\\end{center}\\n\\n')\n for p in pp[2:]:\n f.write(p+'\\n\\n')\n\n f = open(filename + '.tex', 'w')\n f.write('\\\\documentclass[12pt]{article}\\n\\n')\n f.write('\\\\usepackage{hyperref, indentfirst}\\n')\n f.write('\\\\hypersetup{\\n')\n f.write('colorlinks=true,\\n')\n f.write('linkcolor=blue,\\n')\n f.write('filecolor=magenta,\\n')\n f.write('urlcolor=blue,\\n}\\n\\n')\n f.write('\\\\begin{document}\\n')\n\n f.write('\\\\begin{titlepage}\\n\\\\null\\\\vfill\\n')\n f.write('\\\\begin{center}\\n{\\\\Huge '+str(book_title)+'}\\n\\\\end{center}\\n')\n f.write('\\\\vfill\\n\\\\vfill\\n\\\\vfill\\n')\n f.write('\\\\end{titlepage}\\n\\n')\n\n f.write('\\\\tableofcontents\\n\\n')\n\n # plot summary\n f.write('\\\\newpage\\n')\n f.write('\\\\section{'+str(content[0]['title'])+'}\\n')\n for p in content[0]['text']:\n f.write(p+'\\n\\n')\n\n # chapters\n for e in content[1]:\n write_section(e)\n\n # characters\n write_section(content[2])\n\n # themes\n write_section(content[3])\n\n # quotes\n write_section(content[4], isQuoteSection=True)\n\n f.write('\\\\end{document}\\n')\n f.close()\n\n special_characters = ['%', '&', '\\#', '_']\n for c in special_characters:\n with fileinput.FileInput(filename + '.tex', inplace=True) as filevar:\n for line in filevar:\n print(line.replace(c, '\\\\'+c), end='')\n\nmain_url = sys.argv[1]\nSS = lambda url: BeautifulSoup(requests.get(url).text, 'html.parser')\nbook_title = SS(main_url).findAll('title')[0].text\nfilename = (''.join(book_title.split(':'))).replace(' ', '_')\ncontent = [{}, [], {}, {}, {}]\n\nget_content()\nwrite_to_pdf()\nsubprocess.run(['pdflatex', filename+'.tex'])\nsubprocess.run(['pdflatex', filename+'.tex'])\n\nsubprocess.run(['zathura', filename+'.pdf'])\nsubprocess.run(['mv', filename+'.pdf', '/home/rsirohi/Files/Books/SparkNotes/'])\nfor f in glob.glob('./'+filename+'.*'):\n os.remove(f)","sub_path":"sparknotes.py","file_name":"sparknotes.py","file_ext":"py","file_size_in_byte":9510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"537081562","text":"import os\nimport sys\nimport subprocess\n\nimport boto\nfrom boto.s3.key import Key\nimport scrapelib\n\nfrom billy import db\nfrom billy.conf import settings\nfrom billy.commands import BaseCommand\n\nscraper = scrapelib.Scraper(follow_robots=False)\n\nimport logging\nlogging.getLogger('boto').setLevel(logging.CRITICAL)\n\nclass DownloadPhotos(BaseCommand):\n\n name = 'download-photos'\n help = 'download latest legislator photos and sync to S3'\n\n def add_args(self):\n self.add_argument('abbrs', metavar='ABBR', type=str, nargs='+',\n help='abbreviations for photos to update')\n\n def handle(self, args):\n s3conn = boto.connect_s3(settings.AWS_KEY, settings.AWS_SECRET)\n bucket = s3conn.create_bucket(settings.AWS_BUCKET)\n\n for abbr in args.abbrs:\n\n meta = db.metadata.find_one({'_id': abbr.lower()})\n if not meta:\n print(\"'{0}' does not exist in the database.\".format(abbr))\n sys.exit(1)\n else:\n print(\"Updating ids for {0}\".format(abbr))\n\n orig_dir = 'photos/original'\n small_dir = 'photos/small'\n large_dir = 'photos/large'\n for d in (orig_dir, small_dir, large_dir):\n if not os.path.exists(d):\n os.makedirs(d)\n\n for leg in db.legislators.find({meta['level']: abbr,\n 'photo_url': {'$exists': True}}):\n\n fname = os.path.join(orig_dir, '{0}.jpg'.format(leg['_id']))\n\n # if fname already exists, skip this processing step\n if os.path.exists(fname):\n continue\n\n # error retrieving photo, skip it\n try:\n tmpname, resp = scraper.urlretrieve(leg['photo_url'])\n except scrapelib.HTTPError as he:\n continue\n except Exception as e:\n continue\n\n # original size, standardized filenames\n fname = os.path.join(orig_dir, '{0}.jpg'.format(leg['_id']))\n subprocess.check_call(['convert', tmpname, fname])\n k = Key(bucket)\n k.key = fname\n k.set_contents_from_filename(fname)\n k.set_acl('public-read')\n\n # small - 150x200\n fname = os.path.join(small_dir, '{0}.jpg'.format(leg['_id']))\n subprocess.check_call(['convert', tmpname, '-resize',\n '150x200', fname])\n k = Key(bucket)\n k.key = fname\n k.set_contents_from_filename(fname)\n k.set_acl('public-read')\n","sub_path":"billy/commands/download_photos.py","file_name":"download_photos.py","file_ext":"py","file_size_in_byte":2726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"153669205","text":"#!/usr/bin/python3\n\"\"\"\nKnapsack problem in CPpy\n \nBased on the Numberjack model of Hakan Kjellerstrand\n\"\"\"\nfrom cppy import *\nimport numpy as np\n\n# Problem data\nn = 10\nnp.random.seed(1)\nvalues = np.random.randint(0,10, n)\nweights = np.random.randint(1,5, n)\ncapacity = np.random.randint(sum(weights)*.2, sum(weights)*.5)\n\n# Construct the model.\nx = BoolVar(n)\n\nconstraint = [ sum(x*weights) <= capacity ]\nobjective = sum(x*values)\n\nmodel = Model(constraint, maximize=objective)\nprint(model)\n\n# Statistics are returned after solving.\nstats = model.solve()\n# Variables can be asked for their value in the found solution\n#print(\"Value:\", objective.value())\nprint(\"Solution:\", x.value())\nprint(\"In items: \", [i+1 for i,val in enumerate(x.value()) if val])\n","sub_path":"knapsack.py","file_name":"knapsack.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"273719860","text":"#!/usr/bin/python3\n\nimport re\nimport glob\nimport dbus\nimport dbus.service\n\nDBUS_PATH = '/com/zexilonoxiouz/dimmer/disk'\nDBUS_INTERFACE = 'com.zexilonoxiouz.dimmer.disk'\nDBUS_INTROSPECT = \"\"\"\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\"\"\"\n\nclass Disk(dbus.service.Object):\n def __init__(self, name):\n self.bus_name = dbus.service.BusName(name, dbus.SystemBus())\n dbus.service.Object.__init__(self, self.bus_name, DBUS_PATH)\n def __del__(self):\n self.remove_from_connection()\n return\n\n @dbus.service.method(DBUS_INTERFACE, '', 'as')\n def GetSchedulers(self):\n return ['noop', 'deadline', 'cfq']\n @dbus.service.method(DBUS_INTERFACE, 's')\n def SetScheduler(self, value):\n if value == self.GetScheduler():\n return\n if value not in self.GetSchedulers():\n return\n for child in glob.glob('/sys/block/sd*/queue/scheduler'):\n open(child, 'w').write(value + '\\n')\n @dbus.service.method(DBUS_INTERFACE, '', 's')\n def GetScheduler(self):\n regex = re.compile('\\[(.+)\\]')\n for child in glob.glob('/sys/block/sd*/queue/scheduler'):\n raw = open(child, 'r').read().strip()\n result = regex.findall(raw)\n return result[0]\n return 'none'\n\n # PROPERTIES\n @dbus.service.method(dbus.PROPERTIES_IFACE, 'ss', 'v')\n def Get(self, interface, property):\n if interface != DBUS_INTERFACE:\n raise dbus.exceptions.DBusException('no such interface')\n if property == 'Schedulers':\n return self.GetSchedulers()\n elif property == 'Scheduler':\n return self.GetScheduler()\n else:\n raise dbus.exceptions.DBusException('no such property')\n\n @dbus.service.method(dbus.PROPERTIES_IFACE, 's', 'a{sv}')\n def GetAll(self, interface):\n if interface != DBUS_INTERFACE:\n raise dbus.exceptions.DBusException('no such interface')\n return {\n 'Schedulers': self.GetSchedulers(),\n 'Scheduler' : self.GetScheduler(),\n }\n\n @dbus.service.method(dbus.PROPERTIES_IFACE, 'ssv')\n def Set(self, interface, property, value):\n if interface != DBUS_INTERFACE:\n raise dbus.exceptions.DBusException('no such interface')\n if property == 'Scheduler':\n self.SetScheduler(value)\n else:\n raise dbus.exceptions.DBusException('no such property')\n self.PropertiesChanged(interface, {property:value}, [])\n\n @dbus.service.signal(dbus.PROPERTIES_IFACE, 'sa{sv}as')\n def PropertiesChanged(self, interface, changed, invalidated):\n pass\n\n # INTROSPECTABLE\n @dbus.service.method(dbus.INTROSPECTABLE_IFACE, '', 's')\n def Introspect(self):\n return DBUS_INTROSPECT\n","sub_path":"server/component/disk.py","file_name":"disk.py","file_ext":"py","file_size_in_byte":4583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"633133336","text":"#-*- coding: utf-8 -*- \n#对数据进行基本的探索\n#返回缺失值个数以及最大最小值\n\nimport pandas as pd\n\ndatafile= '../data/air_data.csv' #raw data from airline compnany\nresultfile = '../result/explore.xls' #dataset after explore\n\ndata = pd.read_csv(datafile, encoding = 'utf-8') #read the raw data\n\nexplore = data.describe(percentiles = [], include = 'all').T\n# summury for data T is transport matrix, which is convinient for viewing data\n#‘all’ : All columns of the input will be included in the output.\nexplore['null'] = len(data)-explore['count'] # count() only count the record which is not null\n\nexplore = explore[['null', 'max', 'min']]\nexplore.columns = [u'null value', u'max ', u'min '] #rename the head of table\n\n'''这里只选取部分探索结果。\ndescribe()函数自动计算的字段有count(非空值数)、unique(唯一值数)、top(频数最高者)、freq(最高频数)、mean(平均值)、std(方差)、min(最小值)、50%(中位数)、max(最大值)'''\n\nexplore.to_excel(resultfile) # output the result","sub_path":"gitfviewers-master/梅梅/test/code/data_explore.py","file_name":"data_explore.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"235787077","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom dataclasses import dataclass\nfrom typing import List\n\n\n@dataclass(init=True)\nclass Plotter:\n\n colors: List\n\n def relationship(self, df, x, y, color=None, alpha=1):\n color_ = np.random.choice(self.colors) if not color else color\n plt.plot(df[x], df[y], 'o', label=f'{x} - {y}', color=color_, alpha=alpha)\n plt.xlabel(x)\n plt.ylabel(y)\n plt.legend()\n plt.show()\n","sub_path":"movie_competition/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"383008065","text":"from pyglet.gl import GL_QUADS\nfrom pyglet.graphics import draw as gl_draw\n\nfrom typing import Tuple\n\n# COLOR CONSTANTS\n\nRED = (255, 0, 0)\nBLUE = (0, 0, 255)\nCYAN = (0, 255, 255)\nPINK = (255, 0, 200)\nGREEN = (0, 255, 0)\nBROWN = (80, 50, 0)\nORANGE = (255, 90, 0)\nPURPLE = (140, 0, 255)\nYELLOW = (255, 255, 0)\nSEA_GREEN = (0, 255, 192)\n\nBLACK = (0, 0, 0)\nDARK_GRAY = (64, 64, 64)\nGRAY = (128, 128, 128)\nLIGHT_GRAY = (192, 192, 192)\nWHITE = (255, 255, 255)\n\nCOLORS = {\n \"RED\": (255, 0, 0),\n \"BLUE\": (0, 0, 255),\n \"CYAN\": (0, 255, 255),\n \"PINK\": (255, 0, 200),\n \"GRAY\": (128, 128, 128),\n \"BLACK\": (0, 0, 0),\n \"GREEN\": (0, 255, 0),\n \"BROWN\": (80, 50, 0),\n \"WHITE\": (255, 255, 255),\n \"ORANGE\": (255, 90, 0),\n \"PURPLE\": (140, 0, 255),\n \"YELLOW\": (255, 255, 0),\n \"DARK_GRAY\": (64, 64, 64),\n \"SEA_GREEN\": (0, 255, 192),\n \"LIGHT_GRAY\": (192, 192, 192),\n}\n# end\n\n# MODE CONSTANTS\n\nCENTER = \"center\"\nCORNER = \"corner\"\nCORNERS = \"corners\"\n\n# end\n\n# TYPES\n\nColor = Tuple[int, int, int]\n\n# end\n\n\nclass Rect:\n \"\"\"\n user/pyglet interface class for drawing a rectangle\n \"\"\"\n\n def __init__(\n self,\n x: int,\n y: int,\n w: int,\n h: int,\n id_: str,\n mode: str = \"center\",\n color: Color = DARK_GRAY,\n draw: bool = True,\n ):\n \"\"\"\n args:\n x: int; the x anchor position of the rectangle-\n y: int; the y anchor position of the rectangle\n w: int; the width of the rectangle\n h: int; the height of the rectangle\n id_: str; the logical id for the rectangle (ex. `background`)\n kwargs:\n mode: str; default \"center\"; the draw mode of the rectangle, \"center\", \"corner\", \"corners\"\n color: Color - 3 int Tuple; default DARK_GRAY - (64, 64, 64)\n draw: bool; default True; tells the rectangle to draw or not\n \"\"\"\n\n self.x, self.y = x, y\n self.w, self.h = w, h\n self.color = color\n\n self.id_ = id_\n\n mode = mode.lower()\n\n if mode == CENTER:\n self.coords = [\n self.x - self.w // 2,\n self.y + self.h // 2,\n self.x + self.w // 2,\n self.y + self.h // 2,\n self.x + self.w // 2,\n self.y - self.h // 2,\n self.x - self.w // 2,\n self.y - self.h // 2,\n ]\n elif mode == CORNER:\n self.coords = [\n self.x,\n self.y,\n self.x,\n self.y + self.h,\n self.x + self.w,\n self.y + self.h,\n self.x + self.w,\n self.y,\n ]\n elif mode == CORNERS:\n self.coords = [\n self.x,\n self.y, # x1, y1\n self.x,\n self.h, # x1, y2,\n self.w,\n self.h, # x2, y2,\n self.w,\n self.y, # x2, y1\n ]\n\n if draw:\n self.draw()\n\n def __repr__(self):\n return f\"Rectangle object ({self.coords})\"\n\n def update_pos(self, x, y):\n self.x, self.y = x, y\n\n def draw(self):\n gl_draw(4, GL_QUADS, (\"v2i\", self.coords), (\"c3B\", self.color * 4))\n","sub_path":"include/rect.py","file_name":"rect.py","file_ext":"py","file_size_in_byte":3312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"641554313","text":"import pandas as pd\r\nimport os\r\nimport configparser as cf\r\nimport logging\r\n#import lib.File_Validator as FV\r\nimport File_Validator as FV\r\n\r\n#*Call the logger************************\r\nlog = logging.getLogger(__name__)\r\n\r\n#*******************************************************************\r\n#********************set the properties of config ******************\r\n#*******************************************************************\r\n\r\ncon = cf.ConfigParser()\r\n\r\ncon.read('config.ini')\r\n\r\n\r\nconfig = { \"cpu_percentage_crit\" : float(con['CPU_CRITICAL']['cpu_percentage']),\\\r\n \"cpuqueue_crit\" : float(con['CPU_CRITICAL']['cpuqueue']), \"instances_crit\" : int(con['CPU_CRITICAL']['consecutive_intervals']),\r\n \"cpu_percentage_warn\" : float(con['CPU_WARN']['cpu_percentage']),\\\r\n \"cpuqueue_warn\" : float(con['CPU_WARN']['cpuqueue']), \"instances_warn\" : int(con['CPU_WARN']['consecutive_intervals'])}\r\n \r\n \r\n ##GLOBAL VARIABLE DECLARATION##############################\r\n\r\npath=str('C:\\project\\TQClient\\TQFiles\\TQ_DATA_1537792295157')\r\nserver = \"sawasq05\"\r\nbusy='%busy'\r\nrunq='cpuq-sz'\r\nhigh={}\r\n\r\n#warning variable declaration\r\nkwarn=config[\"instances_warn\"]\r\nQueue_warn=config[\"cpuqueue_warn\"]\r\nPercentage_warn=config[\"cpu_percentage_warn\"]\r\n\r\n#critical variable declaration\r\nkcrit=config[\"instances_crit\"]\r\nQueue_crit=config[\"cpuqueue_crit\"]\r\nPercentage_crit=config[\"cpu_percentage_crit\"]\r\n\r\n#Result will be captured in the global variable\r\ndf1=pd.DataFrame()\r\n\r\ndef cpu_analyzer_call(server, path, k, Queue, Percentage):\r\n\t#variable declaration inside function\r\n\r\n\tcounter=0\r\n\thigh_index=[]\r\n\tindex=[]\r\n\tglobal df1\r\n\tdf1=df1.iloc[0:0]\r\n\tdf = pd.read_csv(path + '/' + server + '/CPU_Busy.csv')\r\n\tdf['Time:Date']=df['Time:Date']+' '+df['Time:Time']\r\n\tdf.drop(['Time:Time'], axis=1, inplace=True)\r\n\tdf['Time:Date'] = pd.to_datetime(df['Time:Date'], format='%m/%d/%Y %I:%M:%S %p')\r\n\t\r\n\tdf1 = pd.read_csv(path + '/' + server + '/Kernel.csv')\r\n\tdf1['Time:Date']=df1['Time:Date']+' '+df1['Time:Time']\r\n\tdf1.drop(['Time:Time'], axis=1, inplace=True)\r\n\tdf1['Time:Date'] = pd.to_datetime(df1['Time:Date'], format='%m/%d/%Y %I:%M:%S %p')\r\n\t\r\n\tresult = pd.merge(df,df1[['Time:Date', 'cpuq-sz']],on='Time:Date')\r\n\t\r\n\t\r\n\t\r\n\ttotal_row = result.shape[0]\r\n\t\r\n\t\r\n\tfor i in range(0,total_row):\r\n\t\t\r\n\t\tif ((result[busy].iloc[i] > Percentage) & (result[runq].iloc[i] > Queue)):\r\n\t\t\t\r\n\t\t\tcounter=counter+1\r\n\t\t\thigh_index.append(i)\r\n\t\t\t\r\n\t\telif (counter >= k):\r\n\t\t\tfin_index = list(high_index)\r\n\t\t\tindex = index[0:] + fin_index[0:]\r\n\t\t\tfin_index = []\r\n\t\t\thigh_index = []\r\n\t\t\tcounter = 0\r\n\t\telse:\r\n\t\t\thigh_index=[]\r\n\t\t\tcounter=0\r\n\t\t\r\n\t\tif ( i == total_row-1 ):\r\n\t\t\r\n\t\t\tif ( counter >= k):\r\n\t\t\t\tfin_index = list(high_index)\r\n\t\t\t\tindex = index[0:] + fin_index[0:]\r\n\t\t\t\tfin_index = []\r\n\t\t\t\thigh_index = []\r\n\t\t\t\tcounter = 0\r\n\t\t\t\tbreak\r\n\t\t\telse:\r\n\t\t\t\tbreak\r\n\t\t\r\n\tif(len(index) > 0):\r\n\t\r\n\t\t\r\n\t\t\r\n\t\tdf1=result.ix[index]\r\n\t\toutput= path + '/' + 'CPU/' + server + '-cpu.csv'\r\n\t\tdf1.to_csv(output, index=False, sep=',')\r\n\t\t#print(df1.head())\r\n\t\t\r\n\telse:\r\n\t\tdf1=df1.iloc[0:0]\r\n'''\t\r\ndef file_validator_call(file, kcrit):\r\n\t\t\ttotal_lines = sum(1 for line in open(file))\r\n\t\t\tif total_lines < (kcrit*2):\r\n\t\t\t\treturn(str(total_lines))\r\n\t\t\t#print (total_lines)\r\n'''\r\ndef cpu_analyze(server, path):\r\n\tlog.info('Call the CPU analyzer, server %s, path %s, Kcrit %s, Queue_crit %s, Percentage_crit %s, interval1 %d, interval2 %d' %(server, path, kcrit, Queue_crit, Percentage_crit, interval1, interval2))\r\n\t\r\n\tfile1=path + '/' + server + '/CPU_Busy.csv'\r\n\tfile2=path + '/' + server + '/Kernel.csv'\r\n\tkcrit = kcrit\r\n\tvalidator1 = FV.file_validator_call(file1, kcrit)\r\n\tvalidator2 = FV.file_validator_call(file2, kcrit)\r\n\t\r\n\t#Validate Data interval for each input file, here the input files are CPU_Busy.csv and Kernel.csv\r\n\tTime_validate1 = FV.time_validator_call(file1)\r\n\tTime_validate2 = FV.time_validator_call(file2)\r\n\t\t\r\n\tif validator1 is not None:\r\n\t\treturn('DNA #' + validator1)\r\n\t\t\r\n\tif validator2 is not None:\r\n\t\treturn('DNA #' + validator2)\r\n\t\r\n\tif file1 is not file2:\r\n\t\treturn('File1 interval not equal to File2')\r\n\telse: \t\r\n\t\t\r\n\t\tlog.info('Call the CPU analyzer, server %s, path %s, Kcrit %s, Queue_crit %s, Percentage_crit %s, interval1 %d, interval2 %d' %(server, path, kcrit, Queue_crit, Percentage_crit, interval1, interval2))\r\n\t\t\r\n\t\tif [interval1 == 1] or [kcrit < 5]:\r\n\t\t\tcpu_analyzer_call(server, path, kcrit, Queue_crit, Percentage_crit)\r\n\t\telif [interval == 5]:\r\n\t\t\tkcrit = kcrit/interval\r\n\t\t\tcpu_analyzer_call(server, path, kcrit, Queue_crit, Percentage_crit)\r\n\t\r\n\tif not df1.empty:\r\n\t\treturn \"CRITICAL\"\r\n\t\r\n\telif df1.empty:\r\n\t\tif [interval1 == 1] or [kwarn < 5]:\r\n\t\t\tcpu_analyzer_call(server, path, kwarn, Queue_warn, Percentage_warn)\r\n\t\telif [interval == 5]:\r\n\t\t\tkcrit = kcrit/interval\r\n\t\t\tcpu_analyzer_call(server, path, kwarn, Queue_warn, Percentage_warn)\r\n\t\t\r\n\t\t\r\n\t\tif not df1.empty:\r\n\t\t\treturn \"WARN\"\r\n\t\telse:\r\n\t\t\treturn \"OK\"\r\n\r\nresult = cpu_analyze(server, path)\r\nprint(result)\r\n\t","sub_path":"tq_analyzer_panda/lib/Cpu_Analyzer-backup.py","file_name":"Cpu_Analyzer-backup.py","file_ext":"py","file_size_in_byte":4958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"394641145","text":"import sys\r\nfrom cx_Freeze import setup, Executable\r\n\r\nbuild_exe_options = {\"packages\": [\"sys\", \"csv\", \"winsound\", \"os\", \"tkinter\", \"io\", \"PyPDF2\"], \"includes\": [\"pfdcut/step_one\", \"pdfcut/step_two\"]}\r\n\r\nsetup(\r\n name = \"pdfcut\",\r\n version = \"3.1\",\r\n description = \"cut volume pdfs into granular sizes\",\r\n options = {\"build_exe\": build_exe_options},\r\n executables = [Executable(\"pdfcut/__main__.py\", base = \"Console\")])","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"348988790","text":"\"\"\"Run trakem alignment in parallel with MPI.\"\"\"\n\nimport os\nimport argparse\nimport numpy as np\nimport cv2\nimport re\nimport glob\nfrom PIL import Image\nfrom tqdm import tqdm\nimport logging\nimport pkg_resources\n\n\ndef parse_args(args=None):\n parser = argparse.ArgumentParser()\n parser.add_argument('input', default=None, type=str,\n help='path to trakem2 input file')\n parser.add_argument('output', default=None, type=str,\n help='path to output aligned images')\n parser.add_argument('--pairs', default=None, type=str,\n help='path to pairs definition file')\n parser.add_argument('--min', default=1024, type=int,\n help='minimum image size for SIFT feature extraction')\n parser.add_argument('--max', default=2048, type=int,\n help='maximum image size for SIFT feature extraction')\n parser.add_argument('--begin', default=0, type=int,\n help='the index of the first image to align')\n parser.add_argument('--fiji', default='fiji', type=str,\n help='specify ImageJ-linux64 executable path')\n return parser.parse_args(args)\n\n\ndef align(input, output, pairs=None, min_octave=1024, max_octave=2048,\n begin=0, fiji='fiji'):\n \"\"\"Run trakem2 alignment.\n\n Parameters\n ----------\n input : str\n Path to the trakem2 input file.\n output : str\n Path to write subdivided trakem2 inputs.\n pairs : str\n Path to the pairs definition file.\n min_octave : int\n Minimum image size for SIFT feature extraction. Default: 1024.\n max_octave : int\n Maximum image size for SIFT feature extraction. Default: 2048\n begin : int\n The index of the first image to align.\n fiji : str\n Path to an ImageJ-linux64 executable.\n \"\"\"\n # Set up the output directory and get the ImageJ script to run.\n os.makedirs(output, exist_ok=True)\n resource_path = 'ext/align.bsh'\n bsh_path = pkg_resources.resource_filename(__name__, resource_path)\n logging.warning('macro: %s', bsh_path)\n\n # Set up the align command.\n if pairs:\n command = '%s --headless -Dinput=%s -Doutput=%s -Dpairs=%s -Dmin=%d -Dmax=%d -Dbegin=%d -- --no-splash %s' % (\n fiji, input, output, pairs, min_octave, max_octave, begin, bsh_path)\n else:\n command = '%s --headless -Dinput=%s -Doutput=%s -Dmin=%d -Dmax=%d -Dbegin=%d -- --no-splash %s' % (\n fiji, input, output, min_octave, max_octave, begin, bsh_path)\n\n # Align the volume.\n print(command)\n os.system(command)\n\n\ndef main():\n args = parse_args()\n align(args.input,\n args.output,\n pairs=args.pairs,\n min_octave=args.min,\n max_octave=args.max,\n begin=args.begin,\n fiji=args.fiji)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"happyneuron/trakem2/align.py","file_name":"align.py","file_ext":"py","file_size_in_byte":2891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"41247744","text":"\"\"\" CommandLine - Get and parse command line options\n\n NOTE: This still is very much work in progress !!!\n\n Different version are likely to be incompatible.\n\n TODO:\n\n * Incorporate the changes made by (see Inbox)\n * Add number range option using srange()\n\n\"\"\"\n\nfrom __future__ import print_function\n\n__copyright__ = \"\"\"\\\nCopyright (c), 1997-2006, Marc-Andre Lemburg (mal@lemburg.com)\nCopyright (c), 2000-2006, eGenix.com Software GmbH (info@egenix.com)\nSee the documentation for further information on copyrights,\nor contact the author. All Rights Reserved.\n\"\"\"\n\n__version__ = '1.2'\n\nimport sys\nimport traceback\n\n### Application baseclass\n\nclass Application:\n\n \"\"\" Command line application interface with builtin argument\n parsing.\n\n \"\"\"\n # Options the program accepts (Option instances)\n options = []\n\n # The help layout looks like this:\n # [header] - defaults to ''\n #\n # options:\n # [options] - formatted from self.options\n #\n # Note: all fields that do not behave as template are formatted\n # using the instances dictionary as substitution namespace,\n # e.g. %(name)s will be replaced by the applications name.\n #\n\n # Header (default to program name)\n header = ''\n\n # Name (defaults to program name)\n name = ''\n\n # Copyright to show\n copyright = __copyright__\n\n # Generate debug output ?\n debug = 0\n\n # Generate verbose output ?\n verbose = 0\n\n def __init__(self):\n # Start Application\n rc = 0\n try:\n # Start application\n rc = self.main()\n if rc is None:\n rc = 0\n\n except SystemExit as rcException:\n rc = rcException.code\n\n except KeyboardInterrupt:\n print()\n print('* User Break')\n print()\n rc = 1\n\n raise SystemExit(rc)\n\n def exit(self, rc=0):\n\n \"\"\" Exit the program.\n\n rc is used as exit code and passed back to the calling\n program. It defaults to 0 which usually means: OK.\n\n \"\"\"\n raise SystemExit(rc)\n\n def print_header(self):\n\n print('-'*72)\n print(self.header % self.__dict__)\n print('-'*72)\n print()\n\n # Handlers for long options have two underscores in their name\n\n def handle__copyright(self,arg):\n\n self.print_header()\n copyright = self.copyright % self.__dict__\n print(copyright.strip())\n print()\n return 0\n\n def main(self):\n\n \"\"\" Override this method as program entry point.\n\n The return value is passed to sys.exit() as argument. If\n it is None, 0 is assumed (meaning OK). Unhandled\n exceptions are reported with exit status code 1 (see\n __init__ for further details).\n\n \"\"\"\n return None\n","sub_path":"performance/benchmarks/pybench/CommandLine.py","file_name":"CommandLine.py","file_ext":"py","file_size_in_byte":2850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"132300066","text":"from behave import given, when, then\nfrom selenium.webdriver.common.by import By\nfrom time import sleep\n\nPRODUCTS = (By.XPATH, \"/*[@id='wfm-pmd_deals_section']/div[6]//li[.//div[contains(@class, 'brand-name')]]\")\nPRODUCT_NAME = (By.CSS_SELECTOR, \"span.wfm-sales-item-card__product-name\")\n\n@given('Open Amazon Wholefoodsdeals page')\ndef open_wholefoodsdeals_page(context):\n context.driver.get(\"https://www.amazon.com/wholefoodsdeals\")\n\n@then('Verify all items on Prime sale have Name and Regular price tag')\ndef verify_name_and_regular(context):\n product_elements = context.driver.find_elements(*PRODUCTS)\n\n for product_element in product_elements:\n assert 'Regular' in product_element.text, f'Expected Regular to be in {product_element.text}'\n\n product_name = product_element.find_element(*PRODUCT_NAME).text\n print('\\n',product_name)\n assert '' != product_name, f'Expected non-empty product name'\n\n\n\n","sub_path":"features/steps/wholefoods_deals.py","file_name":"wholefoods_deals.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"299973765","text":"from sys import stdout\nfrom makeup_artist import Makeup_artist\nimport logging\nfrom flask import Flask, render_template, Response\nfrom flask_socketio import SocketIO\nfrom camera import Camera\nfrom utils import base64_to_pil_image, pil_image_to_base64\n\n\napp = Flask(__name__)\napp.logger.addHandler(logging.StreamHandler(stdout))\napp.config['SECRET_KEY'] = 'secret!'\napp.config['DEBUG'] = True\nsocketio = SocketIO(app)\ncamera = Camera()\n\n\n@socketio.on('input image', namespace='/test')\ndef test_message(input):\n input = input.split(\",\")[1]\n camera.enqueue_input(input)\n #camera.enqueue_input(base64_to_pil_image(input))\n\n\n@socketio.on('connect', namespace='/test')\ndef test_connect():\n app.logger.info(\"client connected\")\n\n\n@app.route('/')\ndef index():\n \"\"\"Video streaming home page.\"\"\"\n return render_template('index.html')\n\n\n@app.route('/take_picture')\ndef take_picture():\n return print('I got clicked')\n\nif __name__ == '__main__':\n socketio.run(app)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"360021894","text":"#ImportModules\nimport ShareYourSystem as SYS\n\n#Define a Unbound method like function\ndef foo(_InstanceVariable,*_LiargVariablesList,**_KwargVariablesDict):\n\n\t#print\n\tprint('In the foo function ')\n\tprint('_KwargVariablesDict is ')\n\tprint(_KwargVariablesDict)\n\tprint('')\n\n\t#get the wrapped method\n\tWrapUnboundMethod=getattr(\n\t\tgetattr(\n\t\t\tSYS,\n\t\t\t_KwargVariablesDict['BindDoClassStr']\n\t\t),\n\t\t_KwargVariablesDict['BindObserveWrapMethodStr']\n\t)\n\n\t#call\n\tWrapUnboundMethod(_InstanceVariable,10.*_InstanceVariable.MakingMyFloat)\n\n\n#Definition a MakerClass decorated by the BinderClass\n@SYS.BinderClass(**{\n\t'ObservingWrapMethodStr':'make',\n\t'BindingIsBool':True,\n\t'BindingDecorationUnboundMethod':foo,\n\t'BindingItemTuplesList':[('MyFooInt',1)]\n})\nclass MakerClass(object):\n\n\tdef default_init(self,\n\t\t\t\t\t_MakingMyFloat=0.,\n\t\t\t\t\t_MadeMyInt=0,\n\t\t\t\t\t**_KwarVariablesDict\n\t\t\t\t):\n\t\tobject.__init__(self)\n\n\tdef do_make(self):\n\t\t\n\t\t#Print\n\t\tprint('I make')\n\t\t\n\t\t#cast\n\t\tself.MadeMyInt=int(self.MakingMyFloat)\n\n#Definition and do a first make\nMyMaker=MakerClass().make(3.)\n\n#Use the other binded method that is completely fooooo\nMyMaker.foo_make()\n\n#Definition the AttestedStr\nSYS._attest(\n\t[\n\t\t'MakerClass.foo is '+str(MakerClass.foo),\n\t\t'MakerClass.foo_make is '+str(MakerClass.foo_make),\n\t\t'MyMaker is '+SYS._str(\n\t\tMyMaker,\n\t\t**{\n\t\t\t'RepresentingBaseKeyStrsListBool':False,\n\t\t\t'RepresentingAlineaIsBool':False\n\t\t}\n\t\t)\n\t]\n) \n\n#Print\n\n\n\n\n\n\n\n\n","sub_path":"Pythonlogy/build/lib/ShareYourSystem/Standards/Classors/Binder/03_ExampleDoc.py","file_name":"03_ExampleDoc.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"648068404","text":"# -*- coding:utf-8 -*-\n# @Desc: \n# @Author: Administrator\n# @DateTime: 2020/7/31 15:08\n\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_migrate import Migrate\n\ndb = SQLAlchemy()\nmigrate = Migrate()\n\n# ORM映射及数据库迁移\ndef init_extends(app):\n\n db.init_app(app)\n migrate.init_app(app, db)\n\n\n\n","sub_path":"AppBlueprintSpilt/AppBlueprintSpilt/extends.py","file_name":"extends.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"185531215","text":"from typing import Tuple, Dict, Union\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom functools import reduce\nfrom ctools.model import FCDRQN\nfrom ctools.torch_utils import one_hot\nfrom ctools.utils import squeeze, list_split\n\n\nclass ComaActorNetwork(nn.Module):\n\n def __init__(\n self,\n obs_dim: int,\n action_dim: int,\n embedding_dim: int = 64,\n ):\n super(ComaActorNetwork, self).__init__()\n self._obs_dim = squeeze(obs_dim)\n self._act_dim = action_dim\n self._embedding_dim = embedding_dim\n # rnn discrete network\n self._main = FCDRQN(obs_dim, action_dim, embedding_dim)\n\n def forward(self, inputs: Dict) -> Dict:\n agent_state = inputs['obs']['agent_state']\n prev_state = inputs['prev_state']\n if len(agent_state.shape) == 3: # B, A, N\n agent_state = agent_state.unsqueeze(0)\n unsqueeze_flag = True\n else:\n unsqueeze_flag = False\n T, B, A = agent_state.shape[:3]\n agent_state = agent_state.reshape(T, -1, *agent_state.shape[3:])\n prev_state = reduce(lambda x, y: x + y, prev_state)\n output = self._main({'obs': agent_state, 'prev_state': prev_state, 'enable_fast_timestep': True})\n logit, next_state = output['logit'], output['next_state']\n next_state = list_split(next_state, step=A)\n logit = logit.reshape(T, B, A, -1)\n if unsqueeze_flag:\n logit = logit.squeeze(0)\n return {'logit': logit, 'next_state': next_state, 'action_mask': inputs['obs']['action_mask']}\n\n\nclass ComaCriticNetwork(nn.Module):\n\n def __init__(\n self,\n input_dim: int,\n action_dim: int,\n embedding_dim: int = 128,\n ):\n super(ComaCriticNetwork, self).__init__()\n self._input_dim = squeeze(input_dim)\n self._act_dim = squeeze(action_dim)\n self._embedding_dim = embedding_dim\n self._act = nn.ReLU()\n self._fc1 = nn.Linear(self._input_dim, embedding_dim)\n self._fc2 = nn.Linear(embedding_dim, embedding_dim)\n self._fc3 = nn.Linear(embedding_dim, action_dim)\n\n def forward(self, data: Dict) -> Dict:\n \"\"\"\n Overview:\n forward computation graph of qmix network\n Arguments:\n - data (:obj:`dict`): input data dict with keys ['obs', 'prev_state', 'action']\n - agent_state (:obj:`torch.Tensor`): each agent local state(obs)\n - global_state (:obj:`torch.Tensor`): global state(obs)\n - action (:obj:`torch.Tensor`): the masked action\n \"\"\"\n x = self._preprocess_data(data)\n x = self._act(self._fc1(x))\n x = self._act(self._fc2(x))\n q = self._fc3(x)\n return {'q_value': q}\n\n def _preprocess_data(self, data: Dict) -> torch.Tensor:\n t_size, batch_size, agent_num = data['obs']['agent_state'].shape[:3]\n agent_state, global_state = data['obs']['agent_state'], data['obs']['global_state']\n action = one_hot(data['action'], self._act_dim) # T, B, A,N\n action = action.reshape(t_size, batch_size, -1, agent_num * self._act_dim).repeat(1, 1, agent_num, 1)\n action_mask = (1 - torch.eye(agent_num).to(action.device))\n action_mask = action_mask.view(-1, 1).repeat(1, self._act_dim).view(agent_num, -1) # A, A*N\n action = (action_mask.unsqueeze(0).unsqueeze(0)) * action # T, B, A, A*N\n global_state = global_state.unsqueeze(2).repeat(1, 1, agent_num, 1)\n\n x = torch.cat([global_state, agent_state, action], -1)\n return x\n\n\nclass ComaNetwork(nn.Module):\n\n def __init__(self, agent_num: int, obs_dim: Tuple, act_dim: Tuple, embedding_dim: int):\n super(ComaNetwork, self).__init__()\n act_dim = act_dim[-1]\n actor_input_dim = obs_dim['agent_state'][-1]\n critic_input_dim = obs_dim['agent_state'][-1] + squeeze(obs_dim['global_state']) + agent_num * act_dim\n self._actor = ComaActorNetwork(actor_input_dim, act_dim, embedding_dim)\n self._critic = ComaCriticNetwork(critic_input_dim, act_dim, embedding_dim)\n\n def forward(self, data: Dict, mode: Union[str, None] = None) -> Dict:\n assert mode in ['compute_action', 'compute_q_value'], mode\n if mode == 'compute_action':\n return self._actor(data)\n elif mode == 'compute_q_value':\n return self._critic(data)\n","sub_path":"ctools/model/coma/coma.py","file_name":"coma.py","file_ext":"py","file_size_in_byte":4431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"190485646","text":"import torch\nfrom torch import nn\n\n\nclass CrossNet(nn.Module):\n \"\"\"The Cross Network part of Deep&Cross Network model\"\"\"\n\n def __init__(\n self, in_features, layer_num=2, parameterization=\"vector\",\n ):\n super(CrossNet, self).__init__()\n self.layer_num = layer_num\n self.parameterization = parameterization\n if self.parameterization == \"vector\":\n # weight in DCN. (in_features, 1)\n self.kernels = torch.nn.ParameterList(\n [\n nn.Parameter(nn.init.xavier_normal_(torch.empty(in_features, 1)))\n for i in range(self.layer_num)\n ]\n )\n elif self.parameterization == \"matrix\":\n # weight matrix in DCN-M. (in_features, in_features)\n self.kernels = torch.nn.ParameterList(\n [\n nn.Parameter(\n nn.init.xavier_normal_(torch.empty(in_features, in_features))\n )\n for i in range(self.layer_num)\n ]\n )\n else: # error\n raise ValueError(\"parameterization should be 'vector' or 'matrix'\")\n\n self.bias = torch.nn.ParameterList(\n [\n nn.Parameter(nn.init.zeros_(torch.empty(in_features, 1)))\n for _ in range(self.layer_num)\n ]\n )\n\n def forward(self, inputs):\n x_0 = inputs.unsqueeze(2)\n x_l = x_0\n for i in range(self.layer_num):\n if self.parameterization == \"vector\":\n xl_w = torch.tensordot(x_l, self.kernels[i], dims=([1], [0]))\n dot_ = torch.matmul(x_0, xl_w)\n x_l = dot_ + self.bias[i]\n elif self.parameterization == \"matrix\":\n dot_ = torch.matmul(\n self.kernels[i], x_l\n ) # W * xi (bs, in_features, 1)\n dot_ = dot_ + self.bias[i] # W * xi + b\n dot_ = x_0 * dot_ # x0 · (W * xi + b) Hadamard-product\n else: # error\n raise ValueError(\"parameterization should be 'vector' or 'matrix'\")\n x_l = dot_ + x_l\n x_l = torch.squeeze(x_l, dim=2)\n return x_l\n\n\nclass CrossNetMix(nn.Module):\n \"\"\"The Cross Network part of DCN-Mix model\"\"\"\n\n def __init__(\n self, in_features, low_rank=4, num_experts=4, layer_num=2, device=\"cpu\"\n ):\n super(CrossNetMix, self).__init__()\n self.layer_num = layer_num\n self.num_experts = num_experts\n\n # U: (in_features, low_rank)\n self.U_list = torch.nn.ParameterList(\n [\n nn.Parameter(\n nn.init.xavier_normal_(\n torch.empty(num_experts, in_features, low_rank)\n )\n )\n for _ in range(self.layer_num)\n ]\n )\n # V: (in_features, low_rank)\n self.V_list = torch.nn.ParameterList(\n [\n nn.Parameter(\n nn.init.xavier_normal_(\n torch.empty(num_experts, in_features, low_rank)\n )\n )\n for i in range(self.layer_num)\n ]\n )\n # C: (low_rank, low_rank)\n self.C_list = torch.nn.ParameterList(\n [\n nn.Parameter(\n nn.init.xavier_normal_(torch.empty(num_experts, low_rank, low_rank))\n )\n for i in range(self.layer_num)\n ]\n )\n self.gating = nn.ModuleList(\n [nn.Linear(in_features, 1, bias=False) for i in range(self.num_experts)]\n )\n self.bias = torch.nn.ParameterList(\n [\n nn.Parameter(nn.init.zeros_(torch.empty(in_features, 1)))\n for i in range(self.layer_num)\n ]\n )\n self.to(device)\n\n def forward(self, inputs):\n x_0 = inputs.unsqueeze(2) # (bs, in_features, 1)\n x_l = x_0\n for i in range(self.layer_num):\n output_of_experts = []\n gating_score_of_experts = []\n for expert_id in range(self.num_experts):\n # (1) G(x_l)\n # compute the gating score by x_l\n gating_score_of_experts.append(self.gating[expert_id](x_l.squeeze(2)))\n\n # (2) E(x_l)\n # project the input x_l to $\\mathbb{R}^{r}$\n v_x = torch.matmul(\n self.V_list[i][expert_id].t(), x_l\n ) # (bs, low_rank, 1)\n\n # nonlinear activation in low rank space\n v_x = torch.tanh(v_x)\n v_x = torch.matmul(self.C_list[i][expert_id], v_x)\n v_x = torch.tanh(v_x)\n\n # project back to $\\mathbb{R}^{d}$\n uv_x = torch.matmul(\n self.U_list[i][expert_id], v_x\n ) # (bs, in_features, 1)\n\n dot_ = uv_x + self.bias[i]\n dot_ = x_0 * dot_ # Hadamard-product\n\n output_of_experts.append(dot_.squeeze(2))\n\n # (3) mixture of low-rank experts\n output_of_experts = torch.stack(\n output_of_experts, 2\n ) # (bs, in_features, num_experts)\n gating_score_of_experts = torch.stack(\n gating_score_of_experts, 1\n ) # (bs, num_experts, 1)\n moe_out = torch.matmul(\n output_of_experts, gating_score_of_experts.softmax(1)\n )\n x_l = moe_out + x_l # (bs, in_features, 1)\n x_l = x_l.squeeze() # (bs, in_features)\n return x_l\n","sub_path":"player-rl/modules/cross_net.py","file_name":"cross_net.py","file_ext":"py","file_size_in_byte":5672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"99627287","text":"import pandas as pd\nimport os\nimport glob\n\nif __name__ == \"__main__\":\n # hashtag list of interest\n list = 'hashtag_list.txt'\n f = open(list, \"r\")\n list_of_interest = f.readlines()\n for i in range(len(list_of_interest)):\n list_of_interest[i] = list_of_interest[i].replace(\"\\n\", \"\")\n\n # output csv\n output = \"daily_hashtag_count.csv\"\n o = open(output, \"w\")\n\n # input the data\n path = '/Users/rossierao/Desktop/Datafest/SampleTest/data/'\n csv_dir = path + '*.CSV'\n inputs = glob.glob(csv_dir)\n for input in inputs:\n date_loc = input.find(\"2020-\")\n date = input[date_loc:date_loc + 10]\n data = pd.read_csv(input)\n # select only the English version\n data = data.query(\"lang == 'en'\")\n\n # sample size\n #sample_data = data.sample(frac=0.01, replace=False, random_state = 706)\n #o.write(\"data size: \" + str(data.shape[0]) + \"\\n\")\n #o.write(\"sample size: \" + str(sample_data.shape[0]) + \"\\n\")\n #o.write(\"\\n\")\n\n num_tweets = data.shape[0]\n hashtag = data.text.str.findall(r'#.*?(?=\\s|$)').explode().str.lower().str.replace('[^a-z0-9#]', '')\n counts = hashtag.value_counts()\n count_of_interest = []\n for x in list_of_interest:\n try:\n count_of_interest.append(int(counts.loc[x]/num_tweets*1000000))\n except:\n print(\"No hashtag today: \" + x + \" \" + input, end = \"\\n\")\n count_of_interest.append(0)\n\n # write to csv\n for i in range(len(list_of_interest)):\n o.write(list_of_interest[i] + \",\" + str(count_of_interest[i]) + \",\" + date + \"\\n\")\n\n print(\"Successful! \" + input, end = \"\\n\")\n\n o.close()\n\n\n\n\n","sub_path":"hashtag_count.py","file_name":"hashtag_count.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"123161749","text":"# Copyright Notice:\n# Copyright 2017-2019 DMTF. All rights reserved.\n# License: BSD 3-Clause License. For full text see link: https://github.com/DMTF/Redfish-Event-Listener/blob/master/LICENSE.md\n\nimport socket\nimport time\nimport traceback\nimport json\nfrom datetime import datetime as DT\nimport configparser\nimport sys\nimport threading\nimport requests\nfrom http_parser.http import HttpStream\nfrom http_parser.reader import SocketReader\nimport signal\nimport ssl\nimport os\nfrom datetime import datetime\n\n### Print the tool banner\nprint('Redfish Event Listener v1.0.2')\n\n### Initializing the global parameter\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\nlistenerip = config.get('SystemInformation', 'ListenerIP')\nlistenerport = config.get('SystemInformation', 'ListenerPort')\nuseSSL = config.getboolean('SystemInformation', 'UseSSL')\ncertfile = config.get('CertificateDetails', 'certfile')\nkeyfile = config.get('CertificateDetails', 'keyfile')\n\n\nName = config.get('SubsciptionDetails', 'Name')\nDestination = config.get('SubsciptionDetails', 'Destination')\nEventType = config.get('SubsciptionDetails', 'EventTypes')\nEventTypeString = [EventType]\nEventTypes = json.dumps(EventTypeString)\nprint(\"EventTypes: \", EventTypes)\nContextDetail = config.get('SubsciptionDetails', 'Context')\nProtocol = config.get('SubsciptionDetails', 'Protocol')\nSubscriptionURI = config.get('SubsciptionDetails', 'SubscriptionURI')\n\nServerIPs = config.get('ServerInformation', 'ServerIPs')\nUserNames = config.get('ServerInformation', 'UserNames')\nPasswords = config.get('ServerInformation', 'Passwords')\ncertcheck = config.getboolean('ServerInformation', 'certcheck')\n\nverbose = True \n\nif useSSL:\n context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\n context.load_cert_chain(certfile=certfile, keyfile=keyfile)\n\n# exit gracefully on CTRL-C\nsignal.signal(signal.SIGINT, lambda x, y: sys.exit(0))\n\n### Bind socket connection and listen on the specified port\nbindsocket = socket.socket()\nbindsocket.bind((listenerip, int(listenerport)))\nbindsocket.listen(5)\nprint('Listening on {}:{} via {}'.format(listenerip, listenerport, 'HTTPS' if useSSL else 'HTTP'))\nevent_count = {}\ndata_buffer = []\n\n\n### Function to perform GET/PATCH/POST/DELETE operation for REDFISH URI\ndef callResourceURI(ConfigURI, URILink, Method='GET', payload=None, header=None, LocalUser=None, LocalPassword=None):\n print(\"URI is: \", ConfigURI + URILink)\n try:\n startTime2 = DT.now()\n response = statusCode = expCode = None\n if certcheck:\n if Method == 'GET':\n response = requests.get(ConfigURI + URILink, auth=(LocalUser, LocalPassword), timeout=30)\n elif Method == 'PATCH':\n response = requests.patch(ConfigURI + URILink, data=payload, auth=(LocalUser, LocalPassword),\n timeout=30)\n elif Method == 'POST':\n response = requests.post(ConfigURI + URILink, data=payload, auth=(LocalUser, LocalPassword), timeout=30)\n else:\n if header is None:\n if Method == 'GET':\n response = requests.get(ConfigURI + URILink, verify=False, auth=(LocalUser, LocalPassword),\n timeout=30)\n elif Method == 'PATCH':\n header = {\"content-type\": \"application/json\"}\n response = requests.patch(ConfigURI + URILink, data=payload, verify=False,\n auth=(LocalUser, LocalPassword), headers=header, timeout=30)\n elif Method == 'POST':\n header = {\"content-type\": \"application/json\"}\n response = requests.post(ConfigURI + URILink, data=payload, verify=False,\n auth=(LocalUser, LocalPassword), headers=header, timeout=30)\n elif Method == 'CREATE':\n header = {\"content-type\": \"application/json\"}\n response = requests.post(ConfigURI + URILink, data=payload, verify=False, headers=header,\n timeout=30)\n elif Method == 'DELETE':\n header = {\"content-type\": \"application/json\"}\n response = requests.delete(ConfigURI + URILink, data=payload, verify=False,\n auth=(LocalUser, LocalPassword), headers=header, timeout=30)\n else:\n if Method == 'GET':\n response = requests.get(ConfigURI + URILink, verify=False, headers=header, timeout=30)\n elif Method == 'PATCH':\n response = requests.patch(ConfigURI + URILink, data=payload, verify=False, headers=header,\n timeout=30)\n elif Method == 'POST':\n response = requests.post(ConfigURI + URILink, data=payload, verify=False, headers=header,\n timeout=30)\n elif Method == 'DELETE':\n response = requests.delete(ConfigURI + URILink, data=payload, verify=False, headers=header,\n timeout=30)\n\n endTime2 = DT.now()\n execTime2 = endTime2 - startTime2\n\n if response is not None:\n statusCode = response.status_code\n if Method == 'GET':\n expCode = 200\n elif Method == 'PATCH':\n expCode = [200, 204]\n elif Method == 'POST' or Method == 'CREATE':\n expCode = [200, 201, 204]\n elif Method == 'DELETE':\n expCode = [200, 201, 204]\n\n print('Method = {}, status = {}, expected status = {}'.format(Method, statusCode, expCode))\n\n try:\n decoded = response.json()\n except:\n decoded = \"\"\n if (Method == 'GET' and statusCode == expCode):\n return statusCode, True, decoded, response.headers, str(execTime2)\n elif (Method == 'PATCH' and statusCode in expCode):\n return statusCode, True, decoded, response.headers, str(execTime2)\n elif (Method == 'DELETE' and statusCode in expCode):\n return statusCode, True, decoded, response.headers, str(execTime2)\n elif Method == 'POST' and (statusCode in expCode):\n return statusCode, True, decoded, response.headers, str(execTime2)\n elif (Method == 'CREATE') and (statusCode in expCode):\n Token = response.headers['X-Auth-Token']\n print(\"Token value: \", Token)\n header = {\"X-Auth-Token\": Token}\n return statusCode, True, \"\", response.headers, str(execTime2)\n else:\n return statusCode, False, \"\", response.headers, str(execTime2)\n\n except Exception as err:\n print(\"Exception occurred in while performing subscription.\")\n print(traceback.print_exc())\n return None, False, \"\", [], \"\"\n\n\ndef GetPostPayload(AttributeNameList, AttributeValueList, DataType=\"string\"):\n payload = \"\"\n if DataType.lower() == \"string\":\n for i in range(0, len(AttributeNameList)):\n if i == len(AttributeNameList) - 1:\n payload = payload + \"\\\"\" + str(AttributeNameList[i]) + \"\\\":\\\"\" + str(AttributeValueList[i]) + \"\\\"\"\n elif AttributeNameList[i] == \"EventTypes\":\n payload = payload + \"\\\"\" + str(AttributeNameList[i]) + \"\\\":\" + str(AttributeValueList[i]) + \",\"\n else:\n payload = payload + \"\\\"\" + str(AttributeNameList[i]) + \"\\\":\\\"\" + str(AttributeValueList[i]) + \"\\\",\"\n\n payload = \"{\" + payload + \"}\"\n print(\"Payload details are \", payload)\n\n return payload\n\n\n### Create Subsciption on the servers provided by users if any\ndef PerformSubscription():\n global ServerIPs, UserNames, Passwords, Destination, EventTypes, ContextDetail,Name, Protocol, SubscriptionURI, verbose\n ServerIPList = [x for x in ServerIPs.split(\",\") if x.strip() != '']\n UserNameList = UserNames.split(\",\")\n PasswordList = Passwords.split(\",\")\n AttributeNameList = ['Name', 'Destination', 'EventTypes', 'Context', 'Protocol']\n AttributeValueList = [Name, Destination, EventTypes, ContextDetail, Protocol]\n\n if (len(ServerIPList) == len(UserNameList) == len(PasswordList)) and (len(ServerIPList) > 0):\n print(\"Count of Server is \", len(ServerIPList))\n payload = GetPostPayload(AttributeNameList, AttributeValueList, \"string\")\n for i in range(0, len(ServerIPList)):\n print(\"ServerIPList:::\", ServerIPList[i])\n print(\"UserNameList:::\", UserNameList[i])\n statusCode, Status, body, headers, ExecTime = callResourceURI(ServerIPList[i].strip(), SubscriptionURI,\n Method='POST', payload=payload, header=None,\n LocalUser=UserNameList[i].strip(),\n LocalPassword=PasswordList[i].strip())\n\n if Status:\n print(\"Subcription is successful for %s\" % ServerIPList[i])\n\n else:\n print(\"Subcription is not successful for %s or it is already present.\" % ServerIPList[i])\n\n else:\n print(\"\\nNo subscriptions are specified. Continuing with Listener.\")\n\n print(\"\\nContinuing with Listener.\")\n\n\n### Function to read data in json format using HTTP Stream reader, parse Headers and Body data, Response status OK to service and Update the output into file\ndef process_data(newsocketconn, fromaddr):\n if useSSL:\n connstreamout = context.wrap_socket(newsocketconn, server_side=True)\n else:\n connstreamout = newsocketconn\n ### Output File Name\n outputfile = \"Events_\" + str(fromaddr[0]) + \".txt\"\n logfile = \"TimeStamp.log\"\n global event_count, data_buffer\n outdata = headers = HostDetails = \"\"\n try:\n try:\n ### Read the json response using Socket Reader and split header and body\n r = SocketReader(connstreamout)\n p = HttpStream(r)\n headers = p.headers()\n print(\"headers: \", headers)\n\n if p.method() == 'POST':\n bodydata = p.body_file().read()\n bodydata = bodydata.decode(\"utf-8\")\n print(\"\\n\")\n print(\"bodydata: \", bodydata)\n data_buffer.append(bodydata)\n for eachHeader in headers.items():\n if eachHeader[0] == 'Host' or eachHeader[0] == 'host':\n HostDetails = eachHeader[1]\n\n ### Read the json response and print the output\n print(\"\\n\")\n print(\"Server IP Address is \", fromaddr[0])\n print(\"Server PORT number is \", fromaddr[1])\n print(\"Listener IP is \", HostDetails)\n print(\"\\n\")\n outdata = json.loads(bodydata)\n if 'Events' in outdata and verbose:\n event_array = outdata['Events']\n for event in event_array:\n print(\"EventType is \", event['EventType'])\n print(\"MessageId is \", event['MessageId'])\n if 'EventId' in event:\n print(\"EventId is \", event['EventId'])\n if 'EventTimestamp' in event:\n print(\"EventTimestamp is \", event['EventTimestamp'])\n if 'Severity' in event:\n print(\"Severity is \", event['Severity'])\n if 'Message' in event:\n print(\"Message is \", event['Message'])\n if 'MessageArgs' in event:\n print(\"MessageArgs is \", event['MessageArgs'])\n if 'Context' in outdata:\n print(\"Context is \", outdata['Context'])\n print(\"\\n\")\n if 'MetricValues' in outdata and verbose:\n metric_array = outdata['MetricValues']\n print(\"Metric Report Name is: \", outdata.get('Name'))\n for metric in metric_array:\n print(\"Member ID is: \", metric.get('MetricId'))\n print(\"Metric Value is: \", metric.get('MetricValue'))\n print(\"TimeStamp is: \", metric.get('Timestamp'))\n if 'MetricProperty' in metric:\n print(\"Metric Property is: \", metric['MetricProperty'])\n print(\"\\n\")\n\n ### Check the context and send the status OK if context matches\n #if outdata.get('Context', None) != ContextDetail:\n # print(\"Context ({}) does not match with the server ({}).\"\n # .format(outdata.get('Context', None), ContextDetail))\n print(\"SEND OK BACK!!\")\n StatusCode = \"HTTP/1.1 200 OK\\n Content-Type: application/json\\n {}\"\n\n connstreamout.send(StatusCode)\n connstreamout.shutdown(socket.SHUT_RDWR)\n connstreamout.close()\n\n with open(logfile, 'a') as f:\n if 'EventTimestamp' in outdata:\n receTime = datetime.now()\n sentTime = datetime.strptime(outdata['EventTimestamp'], \"%Y-%m-%d %H:%M:%S.%f\")\n f.write(\"%s %s %sms\\n\" % (\n sentTime.strftime(\"%Y-%m-%d %H:%M:%S.%f\"), receTime, (receTime - sentTime).microseconds / 1000))\n else:\n f.write('No available timestamp.')\n\n try:\n if event_count.get(str(fromaddr[0])):\n event_count[str(fromaddr[0])] = event_count[str(fromaddr[0])] + 1\n else:\n event_count[str(fromaddr[0])] = 1\n\n print(\"Event Counter for Host %s = %s\" % (str(fromaddr[0]), event_count[fromaddr[0]]))\n print(\"\\n\")\n fd = open(outputfile, \"a\")\n fd.write(\"Time:%s Count:%s\\nHost IP:%s\\nEvent Details:%s\\n\" % (\n time.ctime(), event_count[str(fromaddr[0])], str(fromaddr), json.dumps(outdata)))\n fd.close()\n\n except Exception as err:\n print(traceback.print_exc())\n\n if p.method() == 'GET':\n # for x in data_buffer:\n # print(x)\n res = \"HTTP/1.1 200 OK\\n\" \\\n \"Content-Type: application/json\\n\" \\\n \"\\n\" + json.dumps(data_buffer)\n connstreamout.send(res)\n connstreamout.shutdown(socket.SHUT_RDWR)\n connstreamout.close()\n #data_buffer.clear()\n except Exception as err:\n print(\"Data needs to read in normal Text format.\")\n\n finally:\n print(\"CLOSE\")\n\n\n### Script starts here\nif len(sys.argv) > 1 and sys.argv[1] in (\"-v\", \"-V\"):\n verbose = True\n\n### Perform the Subscription if provided\nPerformSubscription()\n\n### Accept the TCP connection using certificate validation using Socket wrapper\n\n\nwhile True:\n try:\n ### Socket Binding\n newsocketconn, fromaddr = bindsocket.accept()\n try:\n ### Multiple Threads to handle different request from different servers\n threading.Thread(target=process_data, args=(newsocketconn, fromaddr)).start()\n except Exception as err:\n print(traceback.print_exc())\n except Exception as err:\n print(\"Exception occurred in socket binding.\")\n print(traceback.print_exc())\n","sub_path":"Rest_Client/Redfish-Event-Listener/RedfishEventListener_v1.py","file_name":"RedfishEventListener_v1.py","file_ext":"py","file_size_in_byte":15870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"331525762","text":"# coding: utf-8\nimport os\n\narray = [[' '] * 3 for i in range(0,3)]\n\nprint(array[0])\nprint(array[1])\nprint(array[2])\n\nCoordsX = 0\nCoordsY = 0\n\ndef afficherTab():\n print(array[0])\n print(array[1])\n print(array[2])\n print(\"\\n\\n\")\n\nremplie = 0\n \ndef gagne(joueur):\n win = False\n global remplie\n #Teste les lignes\n for ligne in range (1,len(array)+1):\n if (array[CoordsX][0]==array[CoordsX][1] and array[CoordsX][1]==array[CoordsX][2] and array[CoordsX][1]!=\" \"):\n victoire=joueur\n #Teste les colonnes\n for col in range (1,len(array)+1):\n if (array[0][CoordsY]==array[1][CoordsY] and array[1][CoordsY]==array[2][CoordsY] and array[1][CoordsY]!=\" \"):\n victoire=joueur\n #Teste deux diagonales\n rang=1\n if (array[rang][rang]==array[rang+1][rang+1] and array[rang+1][rang+1]==array[rang+2][rang+2] and array[rang+1][rang+1]!=\" \"):\n victoire=joueur\n if (array[rang+2][rang]==array[rang+1][rang+1] and array[rang+1][rang+1]==array[rang][rang+2] and array[rang+1][rang+1]!=\" \"):\n victoire=joueur\n #Un gagnant ?\n if victoire!=0:\n print(\"le joueur %s gagne\"%[victory])\n exit()\n #Match nul ?\n if remplie==dimensions*dimensions:\n print(\"match nul\")\n exit()\n \ndef saisieCoords(joueur):\n \n if joueur == 1:\n \n CoordsX = int(input(\"Choisissez la case en x : \"))\n CoordsY = int(input(\"Choisissez la case en y : \"))\n \n \n while array[CoordsY-1][CoordsX-1] != ' ' :\n print(\"La case a déja été choisie ! Choisissez une autre position\")\n CoordsX = int(input(\"Choisissez la case en x : \"))\n CoordsY = int(input(\"Choisissez la case en y : \"))\n \n print(\"Le joueur \" + str(joueur) + \" a joué !\")\n array[CoordsY-1][CoordsX-1] = 'x'\n \n gagne(1)\n \n elif joueur == 2:\n \n CoordsX = int(input(\"Choisissez la case en x : \"))\n CoordsY = int(input(\"Choisissez la case en y : \")) \n \n \n while array[CoordsY-1][CoordsX-1] != ' ' :\n print(\"La case a déja été choisie ! Choisissez une autre position\")\n CoordsX = int(input(\"Choisissez la case en x : \"))\n CoordsY = int(input(\"Choisissez la case en y : \"))\n \n print(\"Le joueur \" + str(joueur) + \" a joué !\")\n array[CoordsY-1][CoordsX-1] = 'o'\n \n gagne(2)\n \nwin = False \njoueur = 1\n\nwhile win == False:\n if joueur == 1:\n print(\"C'est au joueur 1 de jouer !\")\n saisieCoords(1)\n afficherTab()\n joueur = 2\n elif joueur == 2:\n print(\"C'est au joueur 2 de jouer !\")\n saisieCoords(2)\n afficherTab()\n joueur = 1\n \n \n \nos.system(\"pause\")","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"151370398","text":"import os\n\n# import tarfile module to extracting map data\nimport tarfile\n\n# import panda main module\nimport direct.directbase.DirectStart\n\nfrom pandac.PandaModules import *\n\n# functions and classes for reading the configuration file\nimport conf\n\n# class that manages the map\nclass Map:\n def __init__(self, map_name):\n # extract the map files to the tmp directory.\n map_file = tarfile.open(os.path.join('maps', map_name + '.tar.gz'))\n map_file.extractall(os.path.join('tmp', 'map'))\n \n # read map info file\n self.info = conf.ReadConfig(os.path.join('tmp', 'map', 'info.txt'))\n \n # Generate terrain\n self.map_terrain = GeoMipTerrain('mySimpleTerrain')\n heightmap_path = os.path.join('tmp', 'map', 'heightmap.png')\n self.map_terrain.setHeightfield(heightmap_path)\n self.map_terrain.generate()\n # set the terrain block size\n self.map_terrain.setBlockSize(64)\n # set focal point and quality level\n self.map_terrain.setNear(5000) #?\n self.map_terrain.setFar(5000) #?\n # set terrain focal point\n self.map_terrain.setFocalPoint(base.camera)\n # get the nodepath of the terrain\n self.map_node = self.map_terrain.getRoot()\n # add nodepath to the render object\n self.map_node.reparentTo(render)\n # set the map size\n # 1 pixel on the .png image = 2 metres\n # ok but tell why\n self.map_node.setSx(4)\n self.map_node.setSy(4)\n self.map_node.setSz(self.info.z)\n # set terrain pos\n # why 100?\n map_x = -100 - self.info.width / 2\n map_y = -100 - self.info.height / 2\n map_z = self.info.underground\n self.map_node.setPos(map_x, map_y, map_z)\n \n # Skydrome\n self.skytexture = loader.loadTexture('textures/sky.jpg')\n self.skydrome = loader.loadModel('smiley.egg')\n self.skydrome.reparentTo(render)\n self.skydrome.setTwoSided(True)\n self.skydrome.setPos(0, 0, 0)\n self.skydrome.setScale(2000, 2000, 2000)\n self.skydrome.setTexture(self.skytexture, 1)\n self.skydrome.setTexScale(TextureStage.getDefault(), 1, 2)\n \n # Provvisorio solo per rendere la mappa decente\n tex = loader.loadTexture('textures/grass.jpg')\n ts = TextureStage('ts')\n self.map_node.setTexture(ts, tex, 1)\n self.map_node.setTexScale(ts, 64, 64)\n \n # add objects to the map\n self.loaded_models = {}\n \n # list of the model that must be loaded\n modelsToLoad = conf.read_values(os.path.join('tmp', 'map', 'objects.txt'))\n for (x, y, z, name) in modelsToLoad:\n modelpath = os.path.join('models', name)\n \n if not self.loaded_models.has_key(name):\n try:\n self.loaded_models[name] = loader.loadModel(modelpath+'.egg')\n except:\n self.loaded_models[name] = loader.loadModel(modelpath+'.egg.pz')\n \n self.loaded_models[name].reparentTo(render)\n self.loaded_models[name].setPos(int(x), int(y), int(z))\n \n def pixy_to_xy(self, pix_x, pix_y):\n 'From map pixel to global (x, y) coordinates.'\n raise NotImplementedError\n \n def xy_to_pixel(self, x, y):\n 'From global (x, y) coordinates to map pixel.'\n pix_x = (100 + self.info.width/2 + x) / 4\n pix_y = (100 + self.info.height/2 + y) / 4\n return pix_x, pix_y\n\n def elevation(self, x, y):\n \"Returns the elevation of the given terrain in metres from the 0 on z axis.\"\n # positions in pixels\n pix_x, pix_y = self.xy_to_pixel(x, y)\n # terrain elevation\n elevation = self.map_terrain.getElevation(pix_x, pix_y) * self.info.z\n # height on z axis\n z = elevation + self.info.underground\n return z\n \n","sub_path":"map.py","file_name":"map.py","file_ext":"py","file_size_in_byte":3930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"211923183","text":"import json\nfrom pymongo import MongoClient\nfrom pymongo.errors import OperationFailure, DuplicateKeyError\nfrom tqdm import tqdm\nfrom functools import partial\nfrom copy import deepcopy\nimport argparse\n\n\ndef read_config(config_filename):\n \"\"\"Read the json config.\"\"\"\n\n with open(config_filename, 'r') as f:\n config = json.load(f, strict=False)\n\n return config\n\ndef get_database_connection(config, section, drop=False):\n \"\"\"Get a pymongo connection.\"\"\"\n\n\n server = config[section + \"_server\"]\n database = config[section + \"_database\"]\n\n print(f\"[ .. ] Connecting to {server} database {database}\")\n client = MongoClient(server)\n\n if drop:\n print(f\"Dropping database {database} on {server}\")\n client.drop_database(database)\n\n db = client[database]\n\n print(f\"[ OK ] Connected to {server} database {database}\")\n\n return db\n\n\ndef iterate_mongo(db):\n \"\"\"Go over each entry in a database.\"\"\"\n for collection_name in tqdm(db.list_collection_names(), desc=\"DB\"):\n collection = db[collection_name]\n try:\n for entry in tqdm(collection.find(), desc=collection_name,\n total=collection.estimated_document_count()):\n yield collection_name, entry\n except OperationFailure as e:\n print(\"Copy failed for collection \" + collection_name)\n print(e)\n\ndef sink(g):\n \"\"\"Iterate over all entries.\"\"\"\n for entry in g:\n pass\n\n\ndef pseudonymize(collection, entry, pseudonymizer, config):\n \"\"\"Pseudonymize an entry in the database.\"\"\"\n\n entry_out = entry\n\n if collection in config['pseudonymize']:\n entry_out = deepcopy(entry)\n\n config_keys = config['pseudonymize'][collection]\n entry_keys = entry_out.keys()\n\n # print(config_keys, entry_keys)\n\n for field in set(config_keys).intersection(entry_keys):\n entry_out[field] = pseudonymizer.pseudonymize(entry[field])\n\n return collection, entry_out\n\n\ndef write_entry(collection, entry, db):\n \"\"\"Write data to a collection.\"\"\"\n try:\n db[collection].insert_one(entry)\n except DuplicateKeyError:\n pass\n return collection, entry\n\n\ndef compose_with_args(fs):\n \"\"\"Apply many functions one after another.\"\"\"\n\n def compose_fcn(args):\n for f in fs:\n # print(f, args)\n args = f(*args)\n return args\n\n return compose_fcn\n\n\nclass CountPseudonymizer():\n \"\"\"Pseudonymize strings.\"\"\"\n \n def __init__(self):\n self.mapping = {}\n \n def pseudonymize(self, inp):\n inp = str(inp)\n \n if inp in self.mapping:\n return self.mapping[inp]\n \n out = str(len(self.mapping))\n \n self.mapping[inp] = out\n \n return out\n\n\nparser = argparse.ArgumentParser(description=\"Copy a mongo database with pseudonymization\")\nparser.add_argument('--config', type=str, required=True)\nparser.add_argument('--drop', action='store_true')\n\n\ndef main_fcn():\n \"\"\"Main function to run.\"\"\"\n\n # obtaining config filename from command line\n args = parser.parse_args()\n\n # connecting to the source and to the destination\n config = read_config(args.config)\n source = get_database_connection(config, \"source\")\n destination = get_database_connection(config, \"destination\",\n drop=args.drop)\n\n # function to pseudonymize entries\n pseudonymize_p = partial(pseudonymize,\n pseudonymizer=CountPseudonymizer(),\n config=config)\n\n # function to write to the target\n write_p = partial(write_entry, db=destination)\n\n # two functions together\n pseudonymize_and_write = compose_with_args([pseudonymize_p, write_p])\n\n # generator with all items in the source database\n items = iterate_mongo(source)\n\n # generator with entries after pseudonymizing and writing\n out = map(pseudonymize_and_write, items)\n\n # running the operation\n sink(out)\n","sub_path":"mongo_pseudonymize/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"33244434","text":"from Crypto import Random\nimport socket\n\n\nclass DiffieHellman:\n p = 5821\n g = 2\n\n def handshake(self, ip, port):\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n a = int.from_bytes(Random.new().read(16), 'big')\n A = pow(self.g, a, self.p)\n s.sendto(str(A).encode(), (ip, port))\n B, server = s.recvfrom(1024)\n B = int(B.decode())\n return pow(B, a, self.p)\n\n def wait_for_handshake(self, ip, port):\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.bind((ip, port))\n A, address = s.recvfrom(1024)\n A = int(A.decode())\n b = int.from_bytes(Random.new().read(16), 'big')\n B = pow(self.g, b, self.p)\n s.sendto(str(B).encode(), address)\n return pow(A, b, self.p)\n","sub_path":"dh.py","file_name":"dh.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"562717989","text":"import unittest2\nimport collada\nimport StringIO\nfrom lxml.etree import fromstring, tostring\n\nclass TestLight(unittest2.TestCase):\n\n def setUp(self):\n self.dummy_collada_text = \"\"\"\n \n \n \"\"\"\n self.dummy = collada.Collada(StringIO.StringIO(self.dummy_collada_text))\n\n def test_sun_light_saving(self):\n sunlight = collada.light.SunLight(\"mysunlight\", (1,1,1))\n self.assertEqual(sunlight.id, \"mysunlight\")\n self.assertTupleEqual(sunlight.color, (1,1,1))\n sunlight.color = (0.1, 0.2, 0.3)\n sunlight.id = \"yoursunlight\"\n sunlight.save()\n loaded_sunlight = collada.light.Light.load(self.dummy, {}, fromstring(tostring(sunlight.xmlnode)))\n self.assertTrue(isinstance(loaded_sunlight, collada.light.SunLight))\n self.assertTupleEqual(sunlight.color, (0.1, 0.2, 0.3))\n self.assertEqual(sunlight.id, \"yoursunlight\")\n \n def test_ambient_light_saving(self):\n ambientlight = collada.light.AmbientLight(\"myambientlight\", (1,1,1))\n self.assertEqual(ambientlight.id, \"myambientlight\")\n self.assertTupleEqual(ambientlight.color, (1,1,1))\n ambientlight.color = (0.1, 0.2, 0.3)\n ambientlight.id = \"yourambientlight\"\n ambientlight.save()\n loaded_ambientlight = collada.light.Light.load(self.dummy, {}, fromstring(tostring(ambientlight.xmlnode)))\n self.assertTrue(isinstance(loaded_ambientlight, collada.light.AmbientLight))\n self.assertTupleEqual(ambientlight.color, (0.1, 0.2, 0.3))\n self.assertEqual(ambientlight.id, \"yourambientlight\")\n \n def test_point_light_saving(self):\n pointlight = collada.light.PointLight(\"mypointlight\", (1,1,1), 0.4, 0.5, 0.6)\n self.assertEqual(pointlight.id, \"mypointlight\")\n self.assertTupleEqual(pointlight.color, (1,1,1))\n self.assertEqual(pointlight.constant_att, 0.4)\n self.assertEqual(pointlight.linear_att, 0.5)\n self.assertEqual(pointlight.quad_att, 0.6)\n pointlight.color = (0.1, 0.2, 0.3)\n pointlight.constant_att = 0.7\n pointlight.linear_att = 0.8\n pointlight.quad_att = 0.9\n pointlight.id = \"yourpointlight\"\n pointlight.save()\n loaded_pointlight = collada.light.Light.load(self.dummy, {}, fromstring(tostring(pointlight.xmlnode)))\n self.assertTrue(isinstance(loaded_pointlight, collada.light.PointLight))\n self.assertTupleEqual(pointlight.color, (0.1, 0.2, 0.3))\n self.assertEqual(pointlight.constant_att, 0.7)\n self.assertEqual(pointlight.linear_att, 0.8)\n self.assertEqual(pointlight.quad_att, 0.9)\n self.assertEqual(pointlight.id, \"yourpointlight\")\n\nif __name__ == '__main__':\n unittest2.main()\n","sub_path":"collada/tests/test_light.py","file_name":"test_light.py","file_ext":"py","file_size_in_byte":2842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"477743463","text":"#############################################\n# Wikidocs\n# 파이썬으로 배우는 알고리즘 트레이딩\n#############################################\n\n# 참고 : https://wikidocs.net/2843\n# 파이썬 기본 자료 구조\n\n### 연습문제 2-1\n\"\"\"\n 다음(Daum) 주가 89,000원, 100주\n 네이버(Naver) 주가 751,000원, 20주\n 주식 총액 계산하는 프로그램\n\"\"\"\ndaum = 89000 * 100\nnaver = 751000 * 20\nsum_stock = daum + naver\n\n\n### 연습문제 2-2\n# 주식총액에서 다음, 네이버 주가가 각각 5%, 10% 하락한 경우 손실액\ndaum_down = daum - (daum * 0.05)\nnaver_down = naver - (naver * 0.10)\nsum_stock_down = daum_down + naver_down\n\ndaum = 89000\nnaver = 751000\nloss = (daum * 0.05 * 100) + (naver * 0.1 * 20)\nprint(loss)\n\n### 연습문제 2-3\n# 화씨 온도(F) → 섭씨 온도(C) 변환\nF = 50\nC = (F-32) / 1.8\nprint(C)\n\n### 연습문제 2-4\n# 화면에 \"pizza\" 10번 출력하는 프로그램\np = \"pizza\"\nprint(p * 10)\nprint(\"pizza\\n\" * 10)\n\n### 연습문제 2-5\n# 3일 연속으로 하한가 기록했을 때 종가\nnaver = 1000000\nnaver_1 = naver - (naver * 0.3)\nnaver_2 = naver_1 - (naver_1 * 0.3)\nnaver_3 = naver_2 - (naver_2 * 0.3)\nprint(naver_3)\n\n# 연습문제 2-6\n# 다음 형식 출력\n\"\"\"\n이름: 파이썬\n생년월일: 2014년 12월 12일\n주민등록번호: 20141212-16233210\n\"\"\"\nprint(\" 이름: 파이썬\\n 생년월일: 2014년 12월 12일\\n 주민등록번호: 20141212-1623210\")\n\n# 연습문제 2-7\n# s라는 변수에 'Daum KaKao' 문자 바인딩, 문자 슬라이싱/연결하기로\n# 'KaKao Daum'으로 변경하기\ns = 'Daum KaKao'\nprint(s[5:] + ' ' + s[:5])\n\n# 연습문제 2-8\n# a라는 변수에 'hello world'를 'hi world'로 변경\na = 'hello world'\nprint(a[0] + 'i ' + a[6:])\nprint('hi ' + a[6:])\n\n# 연습문제 2-9\n# x라는 변수에 'abcdef'를 'bcdefa'로 변경\nx = 'abcdef'\nprint(x[1:] + x[0])","sub_path":"Stock_0019_Wikidocs_001.py","file_name":"Stock_0019_Wikidocs_001.py","file_ext":"py","file_size_in_byte":1877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"585321603","text":"import pandas as pd\r\nimport numpy as np\r\nimport re\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nimport warnings \r\nwarnings.filterwarnings('ignore')\r\nimport pickle\r\nfrom tensorflow.keras import layers\r\nfrom tensorflow.keras import Model\r\nimport tensorflow as tf\r\nimport model\r\nfrom flask import Flask,jsonify,request,redirect,url_for\r\nimport flask\r\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\r\nimport io\r\nimport urllib, base64\r\nimport os\r\nfrom datetime import datetime\r\n\r\n\r\napp = Flask(__name__)\r\n\r\n\r\n##### PREPROCESSING ############\r\ndef remove_spaces(text):\r\n text = re.sub(r\" '(\\w)\",r\"'\\1\",text)\r\n text = re.sub(r\" \\,\",\",\",text)\r\n text = re.sub(r\" \\.+\",\".\",text)\r\n text = re.sub(r\" \\!+\",\"!\",text)\r\n text = re.sub(r\" \\?+\",\"?\",text)\r\n text = re.sub(\" n't\",\"n't\",text)\r\n text = re.sub(\"[\\(\\)\\;\\_\\^\\`\\/]\",\"\",text)\r\n \r\n return text\r\n\r\ndef decontract(text):\r\n text = re.sub(r\"won\\'t\", \"will not\", text)\r\n text = re.sub(r\"can\\'t\", \"can not\", text)\r\n text = re.sub(r\"n\\'t\", \" not\", text)\r\n text = re.sub(r\"\\'re\", \" are\", text)\r\n text = re.sub(r\"\\'s\", \" is\", text)\r\n text = re.sub(r\"\\'d\", \" would\", text)\r\n text = re.sub(r\"\\'ll\", \" will\", text)\r\n text = re.sub(r\"\\'t\", \" not\", text)\r\n text = re.sub(r\"\\'ve\", \" have\", text)\r\n text = re.sub(r\"\\'m\", \" am\", text)\r\n return text\r\n\r\ndef preprocess(text):\r\n text = re.sub(\"\\n\",\"\",text)\r\n text = remove_spaces(text) # REMOVING UNWANTED SPACES\r\n text = re.sub(r\"\\.+\",\".\",text)\r\n text = re.sub(r\"\\!+\",\"!\",text)\r\n text = decontract(text) # DECONTRACTION\r\n text = re.sub(\"[^A-Za-z0-9 ]+\",\"\",text)\r\n text = text.lower()\r\n return text \r\n\r\n## Plot for alpha values ## \r\ndef plot( input_sent , output_sent , alpha ) :\r\n\r\n input_words = input_sent.split() \r\n output_words = output_sent.split() \r\n fig, ax = plt.subplots()\r\n sns.set_style(\"darkgrid\")\r\n sns.heatmap(alpha[:len(input_words),:], xticklabels= output_words , yticklabels=input_words,linewidths=0.01)\r\n ax.xaxis.tick_top() \r\n\r\n \r\n for filename in os.listdir('static/images'):\r\n if filename.startswith('plt'): # not to remove other images\r\n os.remove('static/images/' + filename)\r\n\r\n path = \"static/images/plt_\" + datetime.now().strftime(\"%m_%d_%Y_%H_%M_%S\") + \".jpg\"\r\n plt.savefig(path)\r\n\r\n return path\r\n\r\n\r\n@app.route(\"/\")\r\ndef hello():\r\n return flask.render_template(\"home.html\", filename = [\"static/images/book.jpg\",\"static/images/blog.jpg\",\"static/images/model.jpg\"])\r\n\r\n@app.route(\"/home\")\r\ndef home():\r\n return flask.render_template(\"home.html\", filename = [\"static/images/book.jpg\",\"static/images/blog.jpg\",\"static/images/model.jpg\"])\r\n\r\n\r\n@app.route(\"/index\")\r\ndef index():\r\n return flask.render_template(\"index.html\",filename = \"static/images/book.jpg\") \r\n\r\n@app.route(\"/predict\",methods=[\"POST\",\"GET\"])\r\ndef predict():\r\n text = request.form[\"sent\"]\r\n text = preprocess(text)\r\n\r\n seq = tk_inp.texts_to_sequences([text])\r\n seq = pad_sequences(seq,maxlen = 20 , padding=\"post\")\r\n state = model1.layers[0].initialize(1)\r\n enc_output,state_h,state_c= model1.layers[0](seq,state)\r\n\r\n pred = []\r\n \r\n input_state_h = state_h\r\n input_state_c = state_c\r\n prev_attention = np.zeros(shape = (1,20,1),dtype=\"float32\")\r\n prev_attention[:,1] = 1 \r\n \r\n current_vec = tf.ones((1,1))\r\n \r\n alpha_values = []\r\n\r\n for i in range(20):\r\n \r\n fc , dec_state_h ,dec_state_c, alphas = model1.layers[1].layers[0](enc_output , current_vec ,input_state_h ,input_state_c,prev_attention)\r\n \r\n alpha_values.append(alphas)\r\n \r\n current_vec = np.argmax(fc , axis = -1)\r\n \r\n input_state_h = dec_state_h\r\n input_state_c = dec_state_c\r\n prev_attention = alphas\r\n \r\n pred.append(tk_out.index_word[current_vec[0][0]])\r\n \r\n if tk_out.index_word[current_vec[0][0]]==\"\":\r\n break\r\n \r\n pred_sent = \" \".join(pred)\r\n \r\n alpha_values = tf.squeeze(tf.concat(alpha_values,axis=-1),axis=0)\r\n\r\n html = plot( text , pred_sent , alpha_values ) \r\n \r\n return flask.render_template(\"output.html\",filename=\"static/images/book.jpg\",input =request.form[\"sent\"] ,output = pred_sent ,alpha= html)\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n print(\"####### LOADING ###########\")\r\n tk_inp = pickle.load(open(\"load/tk_inp\",\"rb\"))\r\n\r\n tk_out = pickle.load(open(\"load/tk_out\",\"rb\"))\r\n\r\n model1 = model.encoder_decoder(enc_vocab_size=len(tk_inp.word_index)+1,\r\n enc_emb_dim = 300,\r\n enc_units=256,enc_input_length=35,\r\n dec_vocab_size =len(tk_out.word_index)+1,\r\n dec_emb_dim =300,\r\n dec_units=256,\r\n dec_input_length = 35,\r\n \r\n att_units=256,\r\n batch_size=512,\r\n att_mode = \"dot\")\r\n\r\n model1.compile(optimizer=\"adam\",loss='sparse_categorical_crossentropy')\r\n model1.build([(512,35),(512,35)])\r\n \r\n model1.load_weights(\"load/best.h5\")\r\n print(\"####### MODEL LOADED ###########\")\r\n\r\n\r\n app.run(debug=True)","sub_path":"deployment/deploy.py","file_name":"deploy.py","file_ext":"py","file_size_in_byte":5294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"399833053","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom uncertainties import ufloat\n\ndef linregress(x, y):\n assert len(x) == len(y)\n\n x, y = np.array(x), np.array(y)\n\n N = len(y)\n Delta = N * np.sum(x**2) - (np.sum(x))**2\n\n A = (N * np.sum(x * y) - np.sum(x) * np.sum(y)) / Delta\n B = (np.sum(x**2) * np.sum(y) - np.sum(x) * np.sum(x * y)) / Delta\n\n sigma_y = np.sqrt(np.sum((y - A * x - B)**2) / (N - 2))\n\n A_error = sigma_y * np.sqrt(N / Delta)\n B_error = sigma_y * np.sqrt(np.sum(x**2) / Delta)\n\n return A, A_error, B, B_error\n\n#Daten:\nt, I = np.genfromtxt('Daten/Jod.txt',unpack = 'True')\nt = t*200\n\n#Nullwert:\nN0 = 195/900\n\n#Anpassung Nullwert (200 s):\nN0 = N0*200\n\nI = I - N0\n\n\nplt.errorbar(t, I, xerr = 0, yerr = np.sqrt(I), fmt = 'kx', label = r'Messwerte')\nm, dm, b, db = linregress(t, np.log(I))\nx = np.linspace(0,3000)\nplt.plot(x, np.exp(m*x+b), 'r-', label = r'Ausgleichsfunktion')\n\nM = ufloat(m,dm)\nB = ufloat(b,db)\nNe = ufloat(np.exp(b),db*np.exp(6.28))\nNn = Ne*(1-np.exp(200*m))\nT = -np.log(2)/M\n\nprint(\n'Halbwertszeit:', T,\n'Steigung:',M,\n'Verschiebung:',B,\n'Nulleffekt', N0,\n'N(0):', Ne,\n'Vorfaktor', Nn,\n'Messwerte mit Nulleffekt:',I,\n'Poisson-Fehler:',np.sqrt(I)\n)\n\nplt.legend(loc='best')\nplt.grid()\nplt.ylabel(r'P')\nplt.xlabel(r't/\\si{\\second}')\nplt.yscale('log')\nplt.savefig('build/Jod.pdf')\n","sub_path":"19 Aktivierung mit Neutronen/Jod.py","file_name":"Jod.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"410060338","text":"import os\nimport seria\nimport yaml\n\n\nclass FiggyPyError(Exception):\n pass\n\n \nclass Config(object):\n \"\"\"Configuration object\n\n Object can be created with a filename only, relative path, or absolute path.\n If only name or relative path is provided, look in this order:\n\n 1. current directory\n 2. `~/.config/`\n 3. `/etc/`\n\n It is a good idea to include you __package__ in the file name.\n For example, `cfg = Config(os.path.join(__package__, 'config.yaml'))`.\n This way it will look for your_package/config.yaml,\n ~/.config/your_package/config.yaml, and /etc/your_package/config.yaml.\n \"\"\"\n _dirs = [\n os.curdir,\n os.path.join(os.path.expanduser(\"~\"), '.config'),\n \"/etc/\"\n ]\n\n def __init__(self, f):\n self._f = self._get_file(f)\n self._cfg = self._get_cfg(self._f)\n\n def _get_cfg(self, f):\n \"\"\"Get configuration from config file\"\"\"\n try:\n with open(f, 'r') as _fo:\n try:\n _seria_in = seria.load(_fo)\n _y = _seria_in.dump('yaml')\n except Exception as e:\n raise\n except IOError:\n raise FiggyPyError(\"could not open configuration file\")\n\n _cfg = yaml.load(_y)\n for k, v in _cfg.items():\n setattr(self, k, v)\n\n def _get_file(self, f):\n \"\"\"Get a config file if possible\"\"\"\n if os.path.isabs(f):\n return f\n else:\n for d in Config._dirs:\n _f = os.path.join(d, f)\n if os.path.isfile(_f):\n return _f\n raise FiggyPyError(\"could not find configuration file {} in dirs {}\"\n .format(f, Config._dirs))\n","sub_path":"figgypy/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"622059480","text":"# generating folder structures for all zeolites\n\nfrom maze.extra_framework_maker import ExtraFrameworkMaker\nfrom maze.io_zeolite import read_vasp\nfrom maze.zeolite import PerfectZeolite, Zeolite\nfrom ase.neighborlist import natural_cutoffs, NeighborList\nimport os\nfrom pathlib import Path\nfrom ase.io import write, read\nfrom ase.visualize import view\nimport copy\nimport shutil\nfrom glob import glob\nfrom ase.constraints import FixAtoms\nfrom ase import Atoms\nimport numpy as np\nimport pickle\n\n\nclass SaveExtraFrameworkConfigurations(object):\n\n def __init__(self, sample_zeolite: str):\n self.sample_zeolite = sample_zeolite\n\n def save_bare_zeo(self, output_dir):\n EFzeolite = ExtraFrameworkMaker(iza_code=self.sample_zeolite)\n output_dir0 = os.path.join(output_dir, '00_' + sample_zeolite)\n Path(output_dir0).mkdir(parents=True, exist_ok=True)\n my_path = os.path.join(output_dir0, sample_zeolite)\n write(my_path + '.traj', EFzeolite.EFzeolite)\n print(self.sample_zeolite, 'is done!')\n\n def save_all_Al_zeo(self, zeo_dir, output_1Al, output_2Al):\n EFzeolite = ExtraFrameworkMaker(self.sample_zeolite, zeo_dir)\n EFzeolite.make_extra_frameworks(replace_1Al=True, replace_2Al=True, print_statement=True)\n info_dict = {'T_indices': EFzeolite.t_site_indices, 'Atoms_count': len(EFzeolite.EFzeolite),\n 'Al_pair_count': len(EFzeolite.traj_2Al), 'T_count': len(EFzeolite.t_site_indices)}\n print('Number of unique Al pairs for %s: ' % self.sample_zeolite, len(EFzeolite.traj_2Al))\n\n print(len(EFzeolite.traj_1Al))\n if not os.path.exists(output_1Al):\n os.mkdir(output_1Al)\n for site_name, atoms_1Al in EFzeolite.dict_1Al_replaced.items():\n output_dir1 = os.path.join(output_1Al, site_name)\n Path(output_dir1).mkdir(parents=True, exist_ok=True)\n my_path = os.path.join(output_dir1, site_name)\n write(my_path + '.traj', atoms_1Al[0])\n\n if not os.path.exists(output_2Al):\n os.mkdir(output_2Al)\n for site_name, atoms_2Al in EFzeolite.dict_2Al_replaced.items():\n output_dir2 = os.path.join(output_2Al, site_name)\n Path(output_dir2).mkdir(parents=True, exist_ok=True)\n my_path = os.path.join(output_dir2, site_name)\n write(my_path + '.traj', atoms_2Al)\n\n with open(output_2Al + '/info_dict_%s.pickle' % self.sample_zeolite, 'wb') as f:\n pickle.dump(info_dict, f)\n\n def save_H_structures(self, dir_name, Al_num: str):\n folder = dir_name + '/' + self.sample_zeolite + '/' + Al_num\n filepaths = [os.path.join(folder, dirs) for dirs in os.listdir(folder_name) if 'T' in dirs]\n for filepath in filepaths:\n files = [files for files in os.listdir(filepath) if '.traj' in files]\n for file in files:\n atoms = read(os.path.join(filepath, file))\n EFzeolite = ExtraFrameworkMaker()\n dict_H = EFzeolite.get_Bronsted_sites(atoms)\n for site_name, my_atoms in dict_H.items():\n output_dir1 = os.path.join(filepath, 'H')\n Path(output_dir1).mkdir(parents=True, exist_ok=True)\n my_path = os.path.join(output_dir1, self.sample_zeolite + '_' + Al_num + '_' + site_name)\n write(my_path + '.traj', my_atoms)\n\n def save_all_ZCu(self, filepath, output_dir):\n filepath = filepath + '/00_' + self.sample_zeolite\n files = [files for files in os.listdir(filepath) if 'T' in files]\n Path(output_dir).mkdir(parents=True, exist_ok=True)\n for file in files:\n atoms = read(os.path.join(filepath, file, '%s.traj' % file), '0')\n EFzeolite = ExtraFrameworkMaker()\n dict_ZCu = EFzeolite.get_Z_TM(atoms, 2.6, 'Cu')\n\n for site_name, my_atoms in dict_ZCu.items():\n output_dir1 = os.path.join(output_dir, file + '_' + site_name)\n Path(output_dir1).mkdir(parents=True, exist_ok=True)\n write(output_dir1 + '/1Cu.traj', my_atoms)\n print(self.sample_zeolite, 'is done!')\n\n def save_all_CuOCu(self, filepath, output_dir0):\n files = [files for files in os.listdir(filepath) if 'T' in files]\n Path(output_dir0).mkdir(parents=True, exist_ok=True)\n for file in files:\n output_dir1 = os.path.join(output_dir0, file)\n Path(output_dir1).mkdir(parents=True, exist_ok=True)\n atoms = read(os.path.join(filepath, file, '%s.traj' % file), '0')\n EF_atoms = read('/Users/jiaweiguo/Desktop/MAZE-sim-master/demos/CuOCu_cluster.traj', '0')\n try:\n EFzeolite = ExtraFrameworkMaker()\n my_atoms = EFzeolite.insert_ExtraFrameworkAtoms(atoms, EF_atoms)\n write(output_dir1 + '/CuOCu.traj', my_atoms)\n except:\n print(self.sample_zeolite, file, ' failed!')\n\n\nif __name__ == '__main__':\n topo = ['CHA', 'MOR', 'MWW', 'FAU', 'FER', 'MFI', 'BEC', 'MON', 'MSE', 'AFO', 'AHT', 'BOG', 'CFI',\n 'CGF', 'DON', 'EMT', 'EON', 'EUO', 'GON', 'IWS', 'LTF', 'MTW', 'OBW', 'OSI', 'RHO', 'RSN',\n 'SBE', 'SSY', 'TER', 'VFI', 'WEI', 'ABW', 'ACO', 'AET', 'AFI', 'AFN', 'AFR', 'AFT', 'AFY',\n 'ANA', 'APC', 'APD', 'AST', 'ASV', 'ATN', 'ATO', 'ATT', 'ATV', 'AWW', 'BCT', 'BIK', 'BOF',\n 'BRE', 'BSV', 'CAN', 'CGS', 'CHI', 'CLO', 'CON', 'CZP', 'DDR', 'DFO', 'DFT', 'EAB', 'EDI',\n 'ERI', 'ESV', 'ETR', 'EZT', 'FAR', 'FRA', 'GIS', 'GIU', 'GME', 'GOO', 'HEU', 'IFR', 'IHW',\n 'ISV', 'ITE', 'ITH', 'ITR', 'IWR', 'IWV', 'JBW', 'KFI', 'LEV', 'LIO', 'LOS', 'LOV', 'LTA',\n 'LTL', 'LTN', 'MAR', 'MAZ', 'MEL', 'MEP', 'MER', 'MFS', 'MOZ', 'MTF', 'MTN', 'NAB', 'NAT',\n 'NES', 'NON', 'NPO', 'NSI', 'OFF', 'OSO', 'PAU', 'PHI', 'PON', 'RRO', 'RTH', 'RUT', 'RWR',\n 'RWY', 'SAO', 'SAS', 'SAV', 'SBN', 'SBS', 'SBT', 'SFE', 'SFF', 'SFG', 'SFH', 'SFN', 'SFO',\n 'SFS', 'SIV', 'SOD', 'STF', 'STW', 'THO', 'TOL', 'USI', 'UTL', 'VET', 'VNI', 'VSV', 'WEN',\n 'YUG', 'ZON', 'IWW', 'STT', 'SVR', 'TUN', 'STO', 'AEI', 'AEL', 'AEN', 'AFG', 'AFS', 'AFX',\n 'ATS', 'AVL', 'AWO', 'BOZ', 'BPH', 'CAS', 'CDO', 'DAC', 'DOH', 'EPI', 'FER', 'UWY', 'TON',\n 'TSC', 'UEI', 'UFI', 'UOS', 'UOZ', 'SZR', 'STI', 'SVV', 'SGT', 'SOF', 'SOS', 'SSF', 'SAT',\n 'SAF', 'RTE', 'PUN', 'PCR', 'OWE', 'PAR', 'NPT', 'MVY', 'MSO', 'MEI', 'LIT', 'LAU', 'LTJ',\n 'JOZ', 'JRY', 'JSN', 'JST', 'JSW', 'ITW', 'ITV', 'IRR', 'IMF', 'BEA']\n \"\"\"\n failed_zeo = []\n for sample_zeolite in topo:\n try:\n traj_saver = SaveExtraFrameworkConfigurations(sample_zeolite)\n # traj_saver.save_bare_zeo('/Users/jiaweiguo/Box/00_bare_zeo/')\n input_dir = '/Users/jiaweiguo/Box/all_zeo_database/1Al'\n output_dir = '/Users/jiaweiguo/Box/all_zeo_database/1Al_Cu/00_%s' % sample_zeolite\n traj_saver.save_all_ZCu(input_dir, output_dir)\n except:\n failed_zeo.append(sample_zeolite)\n print(failed_zeo)\n \"\"\"\n failed_zeo = []\n for sample_zeolite in ['MFI', 'EUO', 'CHI']:\n try:\n zeo_dir = '/Users/jiaweiguo/Box/all_zeo_database/Silica_unopt/00_%s/%s.traj' % (sample_zeolite, sample_zeolite)\n output_1Al = '/Users/jiaweiguo/Box/all_zeo_database/1Al/00_%s' % sample_zeolite\n output_2Al = '/Users/jiaweiguo/Box/all_zeo_database/2Al/00_%s' % sample_zeolite\n traj_saver = SaveExtraFrameworkConfigurations(sample_zeolite)\n traj_saver.save_all_Al_zeo(zeo_dir, output_1Al, output_2Al)\n print(sample_zeolite + ' is done!')\n except:\n failed_zeo.append(sample_zeolite)\n print(failed_zeo)\n \"\"\"\n for sample_zeolite in topo:\n filepath = '/Users/jiaweiguo/Box/all_zeo_database/2Al/00_%s/' % sample_zeolite\n output_dir = '/Users/jiaweiguo/Box/all_zeo_database/2Al_CuOCu/01_%s/' % sample_zeolite\n traj_saver = SaveExtraFrameworkConfigurations(sample_zeolite)\n traj_saver.save_all_CuOCu(filepath, output_dir)\n print(sample_zeolite, ' is done!')\n break\n \"\"\"\n","sub_path":"demos/demo_folder_structure.py","file_name":"demo_folder_structure.py","file_ext":"py","file_size_in_byte":8266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"586586911","text":"import pyaudio\nimport wave\nimport cv2\nimport os\nimport audioop\nimport time\nimport numpy as np\nimport random\nimport pickle\nimport requests\nimport re\nimport select\nimport sys\nimport threading\nimport speech_recognition\nfrom scipy.io.wavfile import read\nfrom IPython.display import Audio, display, clear_output\nfrom main_functions import *\nfrom threading import *\ntry:\n from StringIO import StringIO\nexcept ImportError:\n from io import StringIO\n\n\n\nr = speech_recognition.Recognizer()\n\n\ndef add_user():\n\n\n name = input(\"Enter Name:\")\n dir = \"./voice_database/\" + name\n choice = input (\"Enter number 0-10:\")\n\n\n\n #Voice authentication\n FORMAT = pyaudio.paInt16\n CHANNELS = 2\n RATE = 44100\n CHUNK = 1024\n RECORD_SECONDS = 4\n\n\n os.mkdir(dir)\n\n for i in range(3):\n audio = pyaudio.PyAudio()\n\n if i == 0:\n time.sleep(1.0)\n os.system('cls' if os.name == 'nt' else 'clear')\n print(\"Speak your number in {} seconds\".format(2))\n time.sleep(2.0)\n\n elif i ==1:\n time.sleep(2.0)\n print(\"Speak your number one more time\")\n time.sleep(0.8)\n\n else:\n time.sleep(2.0)\n print(\"Speak your number one last time\")\n time.sleep(0.8)\n\n # start Recording\n stream = audio.open(format=FORMAT, channels=CHANNELS,\n rate=RATE, input=True,\n frames_per_buffer=CHUNK)\n\n print(\"recording...\")\n frames = []\n\n for _ in range(0, int(RATE / CHUNK * RECORD_SECONDS)):\n data = stream.read(CHUNK)\n frames.append(data)\n stream.stop_stream()\n stream.close()\n audio.terminate()\n waveFile = wave.open(\"temp\" + '.wav', 'wb')\n waveFile.setnchannels(CHANNELS)\n waveFile.setsampwidth(audio.get_sample_size(FORMAT))\n waveFile.setframerate(RATE)\n waveFile.writeframes(b''.join(frames))\n waveFile.close()\n harvard = speech_recognition.AudioFile('temp.wav')\n with harvard as source:\n print(\"Start reading file\")\n audio2 = r.record(source,duration=4)\n print(\"File read\")\n text = r.recognize_google(audio2, language='en-IN')\n print(\"Recognized number: \")\n print (text)\n os.remove('temp.wav')\n\n\n\n\n\n\n\n\n # saving wav file of speaker\n waveFile = wave.open(dir + '/' + str((i+1)) + '.wav', 'wb')\n waveFile.setnchannels(CHANNELS)\n waveFile.setsampwidth(audio.get_sample_size(FORMAT))\n waveFile.setframerate(RATE)\n waveFile.writeframes(b''.join(frames))\n waveFile.close()\n print(\"Done\")\n dest = \"./gmm_models/\"\n count = 1\n\n for path in os.listdir(dir):\n path = os.path.join(dir, path)\n\n features = np.array([])\n\n # reading audio files of speaker\n (sr, audio) = read(path)\n\n # extract 40 dimensional MFCC & delta MFCC features\n vector = extract_features(audio,sr)\n\n if features.size == 0:\n features = vector\n else:\n features = np.vstack((features, vector))\n\n # when features of 3 files of speaker are concatenated, then do model training\n if count == 3:\n gmm = GMM(n_components = 16, n_iter = 200, covariance_type='diag',n_init = 3)\n gmm.fit(features)\n\n # saving the trained gaussian model\n pickle.dump(gmm, open(dest + name + '.gmm', 'wb'))\n print(name + ' added successfully')\n\n features = np.asarray(())\n count = 0\n count = count + 1\n\nif __name__ == '__main__':\n add_user()\n","sub_path":"Voice-Authentication-and-Recognition-master/add_user.py","file_name":"add_user.py","file_ext":"py","file_size_in_byte":3677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"400172639","text":"from Cookie import SimpleCookie\nfrom urllib import quote\nimport datetime\nfrom swift.common.swob import Request, HeaderKeyDict\nfrom swift.common.utils import get_logger, urlparse\n\n\ndef create_auth_cookie(cookie_name, auth_domain,\n token='', path='/', expires_in=0,\n secure=False, httponly=False):\n cookie = SimpleCookie()\n cookie[cookie_name] = token\n cookie[cookie_name]['path'] = path\n if not auth_domain.startswith('localhost'):\n cookie[cookie_name]['domain'] = auth_domain\n expiration = datetime.datetime.utcnow() + \\\n datetime.timedelta(seconds=expires_in)\n cookie[cookie_name]['expires'] = expiration.strftime(\n '%a, %d %b %Y %H:%M:%S GMT')\n if secure:\n cookie[cookie_name]['secure'] = True\n if httponly:\n cookie[cookie_name]['HttpOnly'] = True\n return cookie[cookie_name].output(header='').strip()\n\n\ndef extract_from_cookie_to_header(req, cookie_key, header_names):\n value = None\n try:\n value = SimpleCookie(\n req.environ.get('HTTP_COOKIE', ''))[cookie_key].value\n if value:\n for name in header_names:\n req.headers[name] = value\n except KeyError:\n pass\n if not value:\n for name in header_names:\n value = req.headers.get(name, None)\n if value:\n break\n return value\n\n\nclass LiteAuthToken(object):\n\n def __init__(self, app, conf):\n self.app = app\n self.conf = conf\n self.logger = get_logger(conf, log_route='lite-auth')\n\n def __call__(self, env, start_response):\n req = Request(env)\n extract_from_cookie_to_header(req,\n 'session',\n ('x-auth-token', 'x-storage-token'))\n\n def cookie_resp(status, response_headers, exc_info=None):\n resp_headers = HeaderKeyDict(response_headers)\n if 'x-auth-token' in resp_headers:\n auth_token = resp_headers['x-auth-token']\n expires_in = int(resp_headers.get('x-auth-token-expires', 0))\n storage_url = resp_headers.get('x-storage-url', '')\n path_parts = urlparse(storage_url)\n domain = path_parts.hostname\n secure = False\n if path_parts.scheme == 'https':\n secure = True\n if auth_token and domain:\n new_cookie = create_auth_cookie('session',\n domain,\n token=auth_token,\n expires_in=expires_in,\n secure=secure,\n httponly=True)\n response_headers.append(('Set-Cookie', new_cookie))\n new_cookie = create_auth_cookie('storage',\n domain,\n token=quote(storage_url,\n safe=''),\n expires_in=expires_in,\n secure=secure)\n response_headers.append(('Set-Cookie', new_cookie))\n return start_response(status, response_headers, exc_info)\n\n return self.app(env, cookie_resp)\n\n\ndef filter_factory(global_conf, **local_conf):\n \"\"\"Returns a WSGI filter app for use with paste.deploy.\"\"\"\n conf = global_conf.copy()\n conf.update(local_conf)\n\n def auth_filter(app):\n return LiteAuthToken(app, conf)\n return auth_filter\n","sub_path":"liteauth/liteauth_token.py","file_name":"liteauth_token.py","file_ext":"py","file_size_in_byte":3774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"208186288","text":"#!/usr/bin/env python3\n##############################################################################\n# Script to convert /home/rluu/download/trading/data/data_CycleTrader/Stocks_ZIP/Stocks/Stocks_Daily_Trading/DJIA_1928_2009_OHLCV.txt to the CSV format we want.\n##############################################################################\n\nimport sys\nimport os\nimport copy\n\n# For logging.\nimport logging\n\n# Header line to put as the first line of text in the destination file.\nheaderLine = \"\\\"Date\\\",\\\"Open\\\",\\\"High\\\",\\\"Low\\\",\\\"Close\\\",\\\"Volume\\\",\\\"OpenInt\\\"\"\nlinesToSkip = 2\n\ninputFile = \"/home/rluu/download/trading/data/data_CycleTrader/Wheat_ZIP/Cash/W1890_82.TXT\"\n\noutputFile = \"/tmp/W1890_82_converted.txt\"\n\n# Use Windows newlines.\nnewline = \"\\r\\n\"\n\n# For logging.\nlogging.basicConfig(level=logging.INFO,\n format='%(levelname)s: %(message)s')\nmoduleName = globals()['__name__']\nlog = logging.getLogger(moduleName)\n\n##############################################################################\n\ndef shutdown(rc):\n \"\"\"Exits the script, but first flushes all logging handles, etc.\"\"\"\n logging.shutdown()\n sys.exit(rc)\n\n##############################################################################\n\n# Lines in the destination file.\nconvertedLines = []\n\n# Read input file.\nwith open(inputFile) as f:\n i = 0\n \n for line in f:\n if i >= linesToSkip:\n \n # Check the number of fields.\n fields = line.split(\"\\t\")\n numFieldsExpected = 3\n if len(fields) != numFieldsExpected:\n log.error(\"Line does not have {} data fields\".\\\n format(numFieldsExpected))\n shutdown(1)\n \n dateStr = fields[0].strip()\n highStr = fields[1].strip()\n lowStr = fields[2].strip()\n openStr = \"{}\".format((float(lowStr) + float(highStr)) / 2.0)\n closeStr = \"{}\".format((float(lowStr) + float(highStr)) / 2.0)\n volumeStr = \"0\"\n openIntStr = \"0\"\n \n # Make sure date is the right length.\n if len(dateStr) != 4:\n log.error(\"dateStr is not the expected number \" +\n \"of characters: \" + dateStr)\n shutdown(1)\n \n log.debug(\"dateStr == {}\".format(dateStr))\n #monthStr = dateStr[4:6]\n #dayStr = dateStr[6:8]\n #yearStr = dateStr[0:4]\n monthStr = \"01\"\n dayStr = \"01\"\n yearStr = dateStr\n convertedLine = \"\"\n \n convertedLine += monthStr + \"/\" + dayStr + \"/\" + yearStr\n convertedLine += \",\"\n \n convertedLine += openStr\n convertedLine += \",\"\n\n convertedLine += highStr\n convertedLine += \",\"\n\n convertedLine += lowStr\n convertedLine += \",\"\n\n convertedLine += closeStr\n convertedLine += \",\"\n\n convertedLine += volumeStr\n convertedLine += \",\"\n\n convertedLine += openIntStr\n\n \n convertedLines.append(convertedLine)\n\n i += 1\n\n\n# Insert header line.\nconvertedLines.insert(0, headerLine)\n\n# Write to file, truncating if it already exists.\nwith open(outputFile, \"w\") as f:\n for line in convertedLines:\n f.write(line.rstrip() + newline)\n \nlog.info(\"Done.\")\n\n","sub_path":"misc/DataFormatting/temp/convertCBOTCashToAppend.py","file_name":"convertCBOTCashToAppend.py","file_ext":"py","file_size_in_byte":3471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"41493911","text":"from django.contrib import admin\nfrom consulting.models import Topic, Question, Role\nfrom django.utils.translation import ugettext, ugettext_lazy as _\n\n\nclass TopicAdmin(admin.ModelAdmin):\n prepopulated_fields = {'slug': ('name',)}\n list_display = ('name', 'hidden', 'questions')\n\n def questions(self, instance):\n return instance.questions.all().count()\n questions.short_description = _('Total questions count')\n\nadmin.site.register(Topic, TopicAdmin)\n\nclass QuestionAdmin(admin.ModelAdmin):\n readonly_fields = ('date_added', 'date_answered', 'expert')\n\nadmin.site.register(Question, QuestionAdmin)\n\nadmin.site.register(Role)\n","sub_path":"consulting/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"64754030","text":"import xlsxwriter\nfrom uszipcode import SearchEngine\nimport xlrd\n\nsearch = SearchEngine(simple_zipcode=True)\n\n#find a substring between two other substrings; found on stack overflow\ndef find_between(s, first, last):\n\ttry:\n\t\tstart = s.index(first) + len(first)\n\t\tend = s.index(last, start)\n\t\treturn s[start:end]\n\texcept ValueError:\n\t\treturn ''\n\n#get todays date in format: mm_dd_yyyy\ndef getTodaysDate():\n\ttoday = datetime.datetime.today()\n\tmonth = today.month\n\tday = today.day\n\tyear = today.year\n\tif today.month < 10:\n\t\tmonth = '0' + str(month)\n\tif today.day < 10:\n\t\tday = '0' + str(day)\n\treturn str(month) + '_' + str(day) + '_' + str(year)\n\n#return current time in format hh_mm\ndef getTime():\n\tcurrent_time = datetime.datetime.today().time()\n\thour = current_time.hour\n\tif hour < 10:\n\t\thour = '0' + str(hour)\n\tminute = current_time.minute\n\tif minute < 10:\n\t\tminute = '0' + str(minute)\n\treturn str(hour) + '_' + str(minute)\n\n#given a filename with the extension CSV, reads the file and converts a comma seperated list into a list\ndef convertCSVToList(filename):\n\tif '.csv' not in str(filename):\n\t\tfilename = str(filename) + '.csv'\n\tf = open(filename, mode='r', encoding='utf-8-sig')\n\tlines = f.readlines()\n\tf.close()\n\tdata = []\n\tfor line in lines:\n\t\tdata_line = line.split(',')\n\t\tdata.append(data_line)\n\treturn data\n\n#provide filename and a list of lists\ndef createCSVFromList(filename, csv_data):\n\tif '.csv' not in str(filename):\n\t\tfilename = str(filename) + '.csv'\n\tf = open(filename, mode='w')\n\tfor row in csv_data:\n\t\trow_value = ''\n\t\tfor element in row:\n\t\t\trow_value += (str(element) + ',')\n\t\tf.write(row_value[:-1].strip() + '\\n')\n\tf.close()\n\n'''\nconvert .xlsx file to dictionary\nfilename is path to .xlsx file\ndictionary format: {worksheet_name : [[column_data], [column_data_2], [column_data_k]]}\n'''\ndef convertExcelToDictionary(filename):\n\tif '.xlsx' not in str(filename):\n\t\tfilename = str(filename) + '.xlsx'\n\twb = xlrd.open_workbook(filename)\n\tsheets = {}\n\tfor i in range(0, wb.nsheets):\n\t\tactive_sheet = wb.sheet_by_index(i)\n\t\tname = active_sheet.name\n\t\tsheets.update({name : []})\n\t\tnum_of_rows = active_sheet.nrows\n\t\tfor k in range(0, num_of_rows):\n\t\t\tvalues = []\n\t\t\tfor element in active_sheet.row(k):\n\t\t\t\tvalues.append(str(element.value).strip())\n\t\t\tsheets[name].append(values)\n\treturn sheets\n\n'''\nsheet_data should be a dictionary where:\neach key is the name of a worksheet\neach value paired to each key is a list of a lists\neach inner-most list is a list of elements that should be added to that worksheet\nie: {sheet_name: [[1,2,3], [4,5,6], [7,8,9]]}\n'''\ndef convertDictionaryToExcel(sheet_data, excel_name): #sheet_data = {sheet_name: [list, of, list, of, elements]}\n\tif '.xlsx' not in str(excel_name):\n\t\texcel_name = str(excel_name) + '.xlsx'\n\tfinal_workbook = xlsxwriter.Workbook(excel_name)\n\tsheet_name = excel_name.split('/')[-1].split('.')[0]\n\tfor sheet_name in sheet_data:\n\t\tfinal_workbook.add_worksheet(sheet_name)\n\t\trow_num = 0 #Row 1\n\t\tcolumn_num = 0 #column A\n\t\tfor row in sheet_data[sheet_name]:\n\t\t\tfor element in row:\n\t\t\t\tfinal_workbook.sheetnames[sheet_name].write_string(row_num, column_num, element)\n\t\t\t\tcolumn_num += 1\n\t\t\trow_num += 1\n\t\t\tcolumn_num = 0\n\tfinal_workbook.close()\n\ndef getLocationDataFromZip(zipcode):\n\tzipcode = int(zipcode)\n\tzipcode_search = search.by_zipcode(zipcode)\n\tlat = float((zipcode_search.bounds_north + zipcode_search.bounds_south)/2)\n\tlng = float((zipcode_search.bounds_west + zipcode_search.bounds_east)/2)\n\tcoords = (lat, lng)\n\tcity = zipcode_search.major_city\n\tcounty = zipcode_search.county\n\tstate = zipcode_search.state\n\ttry:\n\t\tstate = us.states.lookup(state).name\n\texcept:\n\t\tpass\n\treturn {'zipcode': zipcode, 'coordinates': {'lat': coords[0], 'lng': coords[1]}, 'city': city, 'county': county, 'state': state}\n\ndef getLocationDataFromCoords(lat, lng):\n\tresult = getLocationDataFromZip(search.by_coordinates(lat, lng)[0].zipcode)\n\tresult['coordinates'] = {'lat': lat, 'lng': lng}\n\treturn result\n\n#client secret filename should be a json file provided by google\ndef loginToGoogle(client_secret_filename):\n\tscope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']\n\tcreds = ServiceAccountCredentials.from_json_keyfile_name(client_secret_filename, scope)\n\tclient = gspread.authorize(creds)\n\treturn client\n\ndef getSheet(client, sheet_name):\n\tsheet = client.open(sheet_name)\n\treturn sheet\n\ndef getExistingWorksheets(sheet):\n\texisting_worksheets = sheet.worksheets()\n\treturn existing_worksheets\n\ndef getWorksheetData(worksheet):\n\treturn worksheet.get_all_records()","sub_path":"scrapingtools.py","file_name":"scrapingtools.py","file_ext":"py","file_size_in_byte":4557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"458961113","text":"##############################################################################\n# Imports\n##############################################################################\n\nimport os\nimport re\n\n##############################################################################\n# Methods\n##############################################################################\n\n\ndef get_install_prefix_from_config_cmake(isolated=False):\n '''\n Parse the config.cmake looking for the CMAKE_INSTALL_PREFIX\n '''\n suffix = \"_isolated\" if isolated else \"\"\n print(\"get_underlays_list_from_config_cmake\")\n f = open('config.cmake')\n for line in f:\n # use .*? where ? makes the match non-greedy\n m = re.search('^set\\(CMAKE_INSTALL_PREFIX \"(.*?)\"', line)\n if m:\n return m.group(1) + suffix\n return \"\"\n\n\ndef get_underlays_list_from_config_cmake(base_path=os.getcwd()):\n '''\n Parse the config.cmake looking for the underlays list.\n '''\n f = open(os.path.join(base_path, 'config.cmake'))\n for line in f:\n # use .*? where ? makes the match non-greedy\n m = re.search('^set\\(UNDERLAY_ROOTS \"(.*?)\"', line)\n if m:\n return m.group(1).split(';')\n return []\n","sub_path":"src/yujin_tools/config_cache.py","file_name":"config_cache.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"621004164","text":"# Python device with configuration transfer\nfrom iocompython import Root, MemoryBlock, Connection, Signal, json2bin\nimport ioterminal \nimport time\n\ndef main():\n device_name = 'mydevice'\n device_nr = 3\n full_device_name = device_name + str(device_nr)\n\n root = Root(device_name, device_nr=device_nr, network_name='cafenet', security='certchainfile=myhome-bundle.crt')\n root.queue_events()\n ioterminal.start(root)\n exp = MemoryBlock(root, 'up', 'exp')\n imp = MemoryBlock(root, 'down', 'imp')\n conf_exp = MemoryBlock(root, 'up', 'conf_exp')\n conf_imp = MemoryBlock(root, 'down', 'conf_imp')\n\n with open('test_device.json', 'r') as file:\n signal_conf = file.read()\n data = json2bin(signal_conf)\n\n info = MemoryBlock(root, 'up,auto', 'info', nbytes=len(data))\n info.publish(data)\n \n connection = Connection(root, \"127.0.0.1\", \"tls,up\")\n\n frd_cmd = Signal(root, \"frd_cmd\")\n tod_cmd = Signal(root, \"tod_cmd\")\n\n stream = root.initconf(full_device_name, flags = 'device')\n\n while (ioterminal.run(root)):\n imp.receive()\n conf_imp.receive()\n\n # If this device receives \"what is congifuration\" command, return it. Here massive \"Hulabaloo\" \n # for any persistent block number.\n state_bits, cmd = frd_cmd.get_ext()\n if (state_bits & 2) and cmd == 1:\n print(root.setconf(full_device_name, str.encode(\"Hulabaloo\"), flags = 'device'))\n\n # If this device receives \"configure youself\" command, just print the received configuration.\n state_bits, cmd = tod_cmd.get_ext()\n if (state_bits & 2) and cmd == 1:\n print(root.getconf(full_device_name, flags = 'device'))\n\n exp.send()\n conf_exp.send()\n time.sleep(0.03) \n \n root.delete()\n\nif (__name__ == '__main__'): \n main()\n\n","sub_path":"extensions/iocompython/tests/test_device.py","file_name":"test_device.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"294815955","text":"import codecs\nimport os\n\nfrom Hiphop.settings import BASE_DIR\n\nCRT_PATH = os.path.join(BASE_DIR, 'Init')\n\nwith open(os.path.join(CRT_PATH, 'phrase'), 'wb+') as f:\n for s in codecs.open(os.path.join(CRT_PATH, 'phrase_raw'), 'r+', encoding='utf8'):\n if s[-1] == '\\n':\n s = s[:-1]\n flag = True\n for c in s:\n if c.upper() in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()~{}[]`1234567890-=_+?<>,.;:\\\"\\'':\n flag = False\n if flag:\n f.write((s+'\\n').encode())\n","sub_path":"Init/polish_phrase.py","file_name":"polish_phrase.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"56771498","text":"class Solution:\n def judgeCircle(self, moves):\n dict = {i:0 for i in 'UDLR'}\n for i in moves:\n dict[i] = dict[i] + 1\n\n if dict['U'] == dict['D'] and dict['L'] == dict['R']:\n return True\n else:\n return False\n\n","sub_path":"routecircle.py","file_name":"routecircle.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"251960001","text":"import sys\n\nsys.stdin = open('input.txt', 'r')\n\n\ndef insertion_sort(arr, n):\n for i in range(1, n):\n # arr[1..i]의 적합한 자리에 a[i]를 삽입한다.\n\n loc = i - 1\n new_item = arr[i] # 비교 대상\n # 이지점에서 arr[1 .. i-1]은 이미 정렬된상태\n\n while loc >= 0 and new_item < arr[loc]: # 왼쪽과 비교하면서, 비교대상이 해당 원소보다 작을동안 돈다\n arr[loc + 1] = arr[loc] # 한칸씩 옆으로 미는 작업\n loc -= 1 # 위치 감소\n\n arr[loc + 1] = new_item # 자기자리에 와서 비교대상으로 변경\n\n\nN = int(input())\n\nnumbers = [int(input()) for _ in range(N)]\n\ninsertion_sort(numbers, len(numbers))\n\nfor num in numbers:\n print(num)\n","sub_path":"PYTHON/BAEKJOON/2750_수_정렬하기(버블,선택,삽입)/2750_insertion.py","file_name":"2750_insertion.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"425314312","text":"#!/usr/bin/env python3\n\"\"\"\n######################################################################\n#\n# $HeadURL: https://bss-srv4.bioinformatics.ic.ac.uk/svn/BugBuilder/trunk/bin/run_sis $\n# $Author: jamesa $\n# $Revision: 179 $\n# $Date: 2016-03-10 10:32:17 +0000 (Thu, 10 Mar 2016) $\n#\n# Wrapper for ragout to permit use via BugBuilder scaffolding stages\n#\n# This file is part of BugBuilder (https://github.com/jamesabbott/BugBuilder)\n# and is distributed under the Artistic License 2.0 - see accompanying LICENSE\n# file for details\n#\n######################################################################\n\nWrapper for SIS scaffolder to permit use withing BugBuilder's scaffolding configuration.\nSIS makes use of MUMmer to carry out alignments, and post-processes the show_coords output.\nThese MUMmer stages need running prior to executing SIS itself. Following SIS execution the\ngenerated scaffolds (which consist of ordered contigs, with one scaffold per fasta file)\nare reprocessed into a multifasta file of 'N' gapped scaffold sequences.\n\n\n\"\"\"\nimport glob\nimport subprocess\nimport sys\nimport os\nfrom .shared_methods import make_nucmer_delta_show_cmds\nfrom Bio import SeqIO\nfrom Bio.Seq import Seq\nfrom Bio.SeqRecord import SeqRecord\n\n\ndef make_ragout_recipe(references, target):\n \"\"\" dictates whick files are your references, etc\n should look something like this:\n\n .references = rf122,col,jkd,n315\n .target = usa\n\n col.fasta = references/COL.fasta\n jkd.fasta = references/JKD6008.fasta\n rf122.fasta = references/RF122.fasta\n n315.fasta = references/N315.fasta\n usa.fasta = usa300_contigs.fasta\n\n \"\"\"\n raw_ref_names = [os.path.basename(x) for x in references]\n # ragout ddoesnt like periods in names\n ref_names = [os.path.splitext(x)[0].replace(\".\", \"_\") for x in raw_ref_names]\n ref_names_exts = [os.path.splitext(x)[1] for x in raw_ref_names]\n target_name = os.path.splitext(os.path.basename(target))[0].replace(\".\", \"_\")\n lines = [\n \"# ragout recipe file generated by BugBuilder\",\n \".references = \" + \",\".join([os.path.splitext(x)[0] for x in ref_names]),\n \".target = \" + target_name]\n lines.append(target_name + os.path.splitext(target)[1] + \" = \" + target)\n for idx, ref in enumerate(references):\n lines.append(ref_names[idx] + ref_names_exts[idx] + \" = \" + ref)\n return lines\n\n\ndef make_ragout_cmd(exe, scaff_dir, threads, ragout_recipe):\n return \"{exe} --outdir {scaff_dir} --synteny sibelia --threads {threads} {ragout_recipe} --debug\".format(**locals())\n\n\ndef run(config, args, results, ref, contigs, scaff_dir, logger):\n \"\"\" we need to explicitly set the reference and the contigs files cause we\n may have partitioned them (using blast to see which contigs go with\n which contigs)\n \"\"\"\n if config.python2 is None:\n raise ValueError(\n \"ragout requires having python2 available! \"+\n \" we recommend creaing a conda environement just for \" +\n \" ragout (`conda create --name ragout ragout`) which \" +\n \" ensures that ragout and its dependencies will be installed\" +\n \" and available in the path with python2\")\n recipe_file = os.path.join(scaff_dir, \"ragout_recipe.txt\")\n recipe_lines = make_ragout_recipe(references=args.references, target=contigs)\n with open(recipe_file, \"w\") as outf:\n for line in recipe_lines:\n print(line)\n outf.write(line + \"\\n\")\n\n logger.debug(\"Using ragout to scaffold %s against %s\", contigs,\n \", \".join(args.references))\n cmd = make_ragout_cmd(exe=config.ragout, scaff_dir=scaff_dir,\n threads=args.threads, ragout_recipe=recipe_file)\n logger.debug(cmd)\n subprocess.run(cmd,\n shell=sys.platform != \"win32\",\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n check=True)\n","sub_path":"BugBuilder/run_ragout.py","file_name":"run_ragout.py","file_ext":"py","file_size_in_byte":3926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"120366642","text":"import sys\nimport os\nimport win32com.client as win32\n\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom django.http import HttpResponse\nfrom forms import RegisterByEmail\nfrom forms import RegisterByToken\nfrom models import Token\nsys.path.append(os.path.dirname(__file__) + \"\\\\..\\\\lib\")\nfrom ldap_lib import MyLDAP\nfrom user_lib import MyUser\n\n\ndef send_mail(u_mail, content):\n '''\n Function to send mail with user and password\n '''\n outlook = win32.Dispatch('outlook.application')\n mail = outlook.CreateItem(0)\n mail.To = u_mail\n mail.Subject = 'LDAP Registration'\n mail.HTMLBody = content\n mail.send\n\n# Create your views here.\ndef register(request):\n form = RegisterByEmail\n token = \"\"\n if request.method == 'POST':\n form = RegisterByEmail(request.POST)\n if form.is_valid():\n mail = form.cleaned_data.get('mail')\n Token.objects.get_or_create(mail=mail)\n queryset = Token.objects.filter(mail=mail)\n _token = [p.token for p in queryset]\n token = _token[0]\n send_mail(mail, 'http://localhost:8000/auths/register-by-token/' + token)\n \n return render_to_response('auths/register.html', {'form': form, 'token': token}, \n context_instance=RequestContext(request))\n\ndef register_by_access_token(request, backend):\n ldap = \"OpenLDAP\"\n if request.method == 'POST':\n form = RegisterByToken(request.POST)\n if form.is_valid():\n queryset = Token.objects.filter(token=backend)\n _mail = [p.mail for p in queryset]\n mail = _mail[0].encode('utf-8', 'ignore')\n name = form.cleaned_data.get('name').encode('utf-8', 'ignore')\n surname = form.cleaned_data.get('surname').encode('utf-8', 'replace')\n uid = form.cleaned_data.get('uid').encode('utf-8', 'ignore')\n myuser = MyUser()\n myuser.add_parameters(uid, mail, name, surname)\n myldap = MyLDAP(ldap)\n ldap_ = myldap.connect()\n myldap.add_new_user(myuser, ldap_)\n myldap.disconnect(ldap_)\n \n form = RegisterByToken\n queryset = Token.objects.filter(token=backend)\n _mail = [p.mail for p in queryset]\n mail = _mail[0]\n form.base_fields[\"mail\"].initial = mail\n \n return render_to_response('auths/register_by_token.html', {'form': form}, \n context_instance=RequestContext(request))\n ","sub_path":"django/auths/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"18859578","text":"import json\nimport pickle\nimport torch\nfrom torch import optim\nfrom torch.utils.data import DataLoader\nfrom tqdm import tqdm\nfrom pytorch_pretrained_bert.modeling import BertConfig\nfrom model.data import Corpus\nfrom model.net import BertTagger\nfrom model.utils import batchify\n\n\n\ndef evaluate(model, data_loader, device):\n if model.training:\n model.eval()\n\n model.eval()\n avg_loss = 0\n for step, mb in tqdm(enumerate(data_loader), desc='eval_step', total=len(data_loader)):\n x_mb, y_mb, _ = map(lambda elm: elm.to(device), mb)\n\n with torch.no_grad():\n mb_loss = model(x_mb, labels=y_mb)\n avg_loss += mb_loss.item()\n x_mb.cpu()\n y_mb.cpu()\n else:\n avg_loss /= (step+1)\n\n return avg_loss\n\n\n# load configs\nwith open('experiment/config.json') as f:\n params = json.loads(f.read())\n\n# loading vocabs\ntoken_vocab_path = params['filepath'].get('token_vocab')\nlabel_vocab_path = params['filepath'].get('label_vocab')\nwith open(token_vocab_path, 'rb') as f:\n token_vocab = pickle.load(f)\nwith open(label_vocab_path, 'rb') as f:\n label_vocab = pickle.load(f)\n\n\n# model\nconfig = BertConfig('bert/bert_config.json')\nmodel = BertTagger(config=config, num_labels=len(label_vocab.token_to_idx), vocab=token_vocab)\nbert_pretrained = torch.load('bert/pytorch_model.bin')\nmodel.load_state_dict(bert_pretrained, strict=False)\n\n# training params\nepochs = params['training'].get('epochs')\nbatch_size = params['training'].get('batch_size')\nlearning_rate = params['training'].get('learning_rate')\nsummary_step = params['training'].get('summary_step')\n\n\n# creating dataset, dataloader\n# train_path = params['filepath'].get('train')\n# val_path = params['filepath'].get('val')\ntrain_path = 'dataset/new_train.pkl'\nval_path = 'dataset/new_val.pkl'\ntrain_data = Corpus(train_path, token_vocab.to_indices, label_vocab.to_indices)\ntrain_loader = DataLoader(train_data, batch_size=batch_size, shuffle=False, num_workers=16,\n drop_last=True, collate_fn=batchify)\nval_data = Corpus(val_path, token_vocab.to_indices, label_vocab.to_indices)\nval_loader = DataLoader(val_data, batch_size=batch_size, shuffle=False, num_workers=16,\n drop_last=True, collate_fn=batchify)\n\n\n# optimizer\nopt = optim.Adam([\n {\"params\": model.bert.parameters(), \"lr\": learning_rate/100},\n {\"params\": model.classifier.parameters(), \"lr\": learning_rate}\n])\n\n# using gpu\ndevice = torch.device('cuda:1') if torch.cuda.is_available() else torch.device('cpu')\nmodel.to(device)\n\n\n# train\nfor epoch in tqdm(range(epochs), desc='epochs'):\n tr_loss = 0\n model.train()\n for step, mb in tqdm(enumerate(train_loader), desc='train_steps', total=len(train_loader)):\n x_mb, y_mb, _ = map(lambda elm: elm.to(device), mb)\n opt.zero_grad()\n mb_loss = model(x_mb, labels=y_mb)\n\n mb_loss.backward()\n opt.step()\n\n tr_loss += mb_loss.item()\n x_mb.cpu()\n y_mb.cpu()\n if (epoch * len(train_loader) + step) % summary_step == 0:\n val_loss = evaluate(model, val_loader, device)\n model.train()\n\n else:\n tr_loss /= (step+1)\n\n val_loss = evaluate(model, val_loader, device)\n\n tqdm.write('epoch : {}, tr_loss : {:.3f}, val_loss : {:.3f}'.format(epoch+1, tr_loss, val_loss))\n\nckpt = {'model_state_dict': model.state_dict(),\n 'opt_state_dict': opt.state_dict()}\n# save_path = params['filepath'].get('ckpt')\nsave_path = 'tokenize.pth'\ntorch.save(ckpt, save_path)\n","sub_path":"char_train.py","file_name":"char_train.py","file_ext":"py","file_size_in_byte":3526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"388281856","text":"#!/usr/bin/python3\n#https://www.coursera.org/\n#Course 1 Week 1\n\nimport tools\n\n#Reverse Complement Problem: Find the reverse complement of a DNA string.\n# Input: A DNA string Pattern.\n# Output: Patternrc , the reverse complement of Pattern.\n\ndef ReverseComplement(Pattern):\n\tReversePattern = ''\n\tfor i in range(len(text)):\n\t\tReversePattern = tools.Nucl[i:i+1] + ReversePattern\t\t\n\treturn ReversePattern\n","sub_path":"c1w1.py","file_name":"c1w1.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"514439843","text":"import json\nclass Stats:\n\n def __init__(self, data, row):\n \"\"\"\n Stats class defines the characteristics like most popular hour/day/device\n for one specific restaurant\n :param data: pointer to csv file to collect information\n :param row: row to collect data from\n \"\"\"\n self.most_popular_hr = {\n \"hour\": \"\",\n \"quanity\": -1\n }\n self.most_popular_day = {\n \"day\": \"\",\n \"quantity\": -1\n }\n self.most_popular_device = \"\"\n self.distance_from_home = -1\n self.median_dwell_time = -1\n self.visits_by_day = -1\n\n self.popular_hour_list = []\n self.popular_day_dict= []\n\n self.data = data\n self.row = row\n\n def getDwell(self):\n return self.median_dwell_time\n\n def getMostPopularHr(self):\n return self.most_popular_hr[\"hour\"]\n\n def getMostPopularDay(self):\n return self.most_popular_day[\"day\"]\n\n def getMostPopularDevice(self):\n return self.most_popular_device\n\n def getDistanceFromHome(self):\n return self.distance_from_home\n\n def set_attributes(self):\n pop_hour = self._setHour()\n self.most_popular_hr[\"hour\"] = pop_hour[0]\n self.most_popular_hr[\"quantity\"] = pop_hour[1]\n\n pop_day = self._setDay()\n self.most_popular_day[\"day\"] = pop_day[0]\n self.most_popular_day[\"quantity\"] = pop_day[1]\n\n self.most_popular_device = self._setDevice()\n self.distance_from_home = self._setDistance()\n self.median_dwell_time = self._setDwell()\n self.visits_by_day = self._setVisitsByDay()\n\n self.popular_hour_list = self.data.loc[self.data.index[self.row], 'popularity_by_hour']\n self.popular_day_dict = json.loads(self.data.loc[self.data.index[self.row], 'popularity_by_day'])\n\n def __repr__(self):\n hour = \"\\tMost Popular Hour: \" + self.most_popular_hr[\"hour\"] + \"\\n\"\n day = \"\\tMost Popular Day: \" + self.most_popular_day[\"day\"] + \"\\n\"\n device = \"\\tMost Popular Device: \" + self.most_popular_device + \"\\n\"\n distance_from_home = \"\\tDistance From Home (in miles): \" + str(round(self.distance_from_home,2)) + \"\\n\"\n dwell_time = \"\\tMedian Dwell Time: (in minutes) \" + str(int(self.median_dwell_time)) + \"\\n\"\n # visits = \"\\tVisits by Day: \" + str(self.visits_by_day) + \"\\n\"\n\n return hour + day + device + distance_from_home + dwell_time # + visits\n\n def _setHour(self):\n hours = json.loads(self.data.loc[self.data.index[self.row], 'popularity_by_hour'])\n maximum = -1\n to_return = \"\"\n\n for index, hour_sum in enumerate(hours):\n if hour_sum > maximum:\n maximum = int(hour_sum)\n to_return = str(index) + \" to \" + str(index+1)\n return [to_return, maximum]\n\n def _setDay(self):\n days = json.loads(self.data.loc[self.data.index[self.row], 'popularity_by_day'])\n maximum = -1\n to_return = \"\"\n for key,value in days.items():\n if value > maximum:\n to_return = key\n maximum = value\n return [to_return, maximum]\n\n def _setDevice(self):\n devices = json.loads(self.data.loc[self.data.index[self.row], 'device_type'])\n if devices[\"android\"] > devices[\"ios\"]:\n return \"Android\"\n else: return \"IOS\"\n\n def _setDistance(self):\n distance = self.data.loc[self.data.index[self.row], 'distance_from_home']\n return distance/1609.344\n\n def _setDwell(self):\n return self.data.loc[self.data.index[self.row], 'median_dwell']\n\n def _setVisitsByDay(self):\n return self.data.loc[self.data.index[self.row], 'visits_by_day']\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Stats.py","file_name":"Stats.py","file_ext":"py","file_size_in_byte":3768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"252299550","text":"import sys\nimport snap\nimport math\nimport numpy as np\nfrom csv import writer\nfrom lasso import lasso\nfrom numpy.random import default_rng\n\nif len(sys.argv) != 5:\n print(\"USAGE: python3 tabulate_performance_gnu.py \")\n exit(1)\n\nrng = default_rng()\n\ngraph = snap.LoadEdgeList(snap.TNGraph, \"p2p-Gnutella08.txt\", 0, 1)\n\n# print(\"Nodes and Edges: (\",graph.GetNodes(), graph.GetEdges(),\")\")\n\nn = graph.GetNodes()\n\nd = int(sys.argv[1])\nm = int(sys.argv[2])\nprint(\"d: \", d)\nprint(\"m: \", m)\n\nscoreMat = np.zeros((n, 1))\nA = np.zeros((m, n))\n\n########################\n# MAKE MEASUREMENT MATRIX\n########################\nfor j in range(n): # 0 ... n-1\n # Select d numbers without replacement from 0 ... m-1\n row = rng.choice(m, size=d, replace=False)\n A[row, j] = 1\n# Measurement matrix constructed\n\n######################################################################\n# FIND THE LOCAL BETWEENESS VALUES(Global betweenness is not tractable)\n######################################################################\nfor u in graph.Nodes():\n v = u.GetId()\n num_nbrs, nbrs = graph.GetNodesAtHop(v, 1, False)\n nbrs.insert(0, v)\n egoadj = np.zeros((len(nbrs), len(nbrs)))\n for i, v1 in enumerate(nbrs):\n for j, v2 in enumerate(nbrs):\n if v1 != v2:\n egoadj[i, j] = 1 if graph.IsEdge(\n v1, v2) else 0\n adj2 = np.dot(egoadj, egoadj)\n score = 0\n for (x, y), value in np.ndenumerate(egoadj):\n # 1-egoAdj comes from the value==0 condition\n if x < y and value == 0 and adj2[x, y] != 0:\n score = score + 1 / (adj2[x, y])\n scoreMat[v] = score\nscoreMat = scoreMat/np.linalg.norm(scoreMat) # Normalize the scores\n\n#########################\n# GET THE MEASURED MATRIX\n#########################\ny = np.zeros((m, 1)) # This is the matrix we get as measured in real life\nfor i in range(m):\n y[i] = A[i, :].dot(scoreMat)\n\n#####################\n# SOLVE LASSO PROBLEM\n#####################\nx = lasso(A, y)\n\n###############################\n# CALCULATE RECONSTRUCTION ERROR\n###############################\nMSE = np.linalg.norm(scoreMat-x)\nprint(\"Relative L2-Norm Error Percentage: \", 100*MSE, \"%\")\n# print(np.linalg.norm(scoreMat)) # This is ofc 1\n\n##########################\n# PARAMETER FOR CHANGING K\n##########################\ntopk = 200 # Change this to get the topK information flow hotspots\ntopk = int(sys.argv[3])\n\nidxTopK = np.argpartition(x.flatten(), -topk)[-topk:] # Indices not sorted\nidxTopK = np.sort(idxTopK)\nrealTopK = np.argpartition(scoreMat.flatten(), -topk)[-topk:] # Indices not sorted\nrealTopK = np.sort(realTopK)\n\nCATERROR = topk - np.size(np.intersect1d(idxTopK, realTopK))\nprint(\"Categorization Error: \", CATERROR, \" mismatches\")\n\n\n# Row which we want to append to our error csv file\nOutputList=[d,m,topk,100*MSE,CATERROR]\nwith open(sys.argv[4], 'a') as f_object:\n writer_object = writer(f_object)\n writer_object.writerow(OutputList)\n f_object.close()\n ","sub_path":"DICeNOD/performance_gnutella/tabulate_performance_gnu.py","file_name":"tabulate_performance_gnu.py","file_ext":"py","file_size_in_byte":3003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"613516273","text":"from typing import Optional\n\nfrom great_expectations.core import ExpectationConfiguration\nfrom great_expectations.execution_engine import (\n ExecutionEngine,\n PandasExecutionEngine,\n SparkDFExecutionEngine,\n)\nfrom great_expectations.execution_engine.sqlalchemy_execution_engine import (\n SqlAlchemyExecutionEngine,\n)\nfrom great_expectations.expectations.metrics.column_aggregate_metric import (\n ColumnMetricProvider,\n column_aggregate_partial,\n column_aggregate_value,\n)\nfrom great_expectations.expectations.metrics.column_aggregate_metric import sa as sa\nfrom great_expectations.expectations.metrics.metric_provider import metric_value\nfrom great_expectations.validator.validation_graph import MetricConfiguration\n\n\ndef unique_proportion(_metrics):\n total_values = _metrics.get(\"table.row_count\")\n unique_values = _metrics.get(\"column.distinct_values.count\")\n null_count = _metrics.get(\"column_values.nonnull.unexpected_count\")\n\n if total_values > 0:\n return unique_values / (total_values - null_count)\n else:\n return 0\n\n\nclass ColumnUniqueProportion(ColumnMetricProvider):\n metric_name = \"column.unique_proportion\"\n\n @metric_value(engine=PandasExecutionEngine)\n def _pandas(*args, metrics, **kwargs):\n return unique_proportion(metrics)\n\n @metric_value(engine=SqlAlchemyExecutionEngine)\n def _sqlalchemy(*args, metrics, **kwargs):\n return unique_proportion(metrics)\n\n @metric_value(engine=SparkDFExecutionEngine)\n def _spark(*args, metrics, **kwargs):\n return unique_proportion(metrics)\n\n @classmethod\n def _get_evaluation_dependencies(\n cls,\n metric: MetricConfiguration,\n configuration: Optional[ExpectationConfiguration] = None,\n execution_engine: Optional[ExecutionEngine] = None,\n runtime_configuration: Optional[dict] = None,\n ):\n table_domain_kwargs = {\n k: v for k, v in metric.metric_domain_kwargs.items() if k != \"column\"\n }\n return {\n \"column.distinct_values.count\": MetricConfiguration(\n \"column.distinct_values.count\", metric.metric_domain_kwargs\n ),\n \"table.row_count\": MetricConfiguration(\n \"table.row_count\", table_domain_kwargs\n ),\n \"column_values.nonnull.unexpected_count\": MetricConfiguration(\n \"column_values.nonnull.unexpected_count\", metric.metric_domain_kwargs\n ),\n }\n","sub_path":"great_expectations/expectations/metrics/column_aggregate_metrics/column_proportion_of_unique_values.py","file_name":"column_proportion_of_unique_values.py","file_ext":"py","file_size_in_byte":2479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"454606056","text":"import numpy as np\n\n# NANDゲートを実装\ndef NAND(x1, x2):\n\n # パラメータの設定\n x = np.array([x1, x2])\n w = np.array([-0.5, -0.5]) # 重みとバイアスだけがANDと違う!\n b = 0.7\n\n # 重み付き入力の総和を計算\n tmp = np.sum(x*w) + b\n\n # 出力の設定\n if tmp <= 0:\n return 0\n else:\n return 1\n\nif __name__ == '__main__':\n for xs in [(0,0), (1,0), (0,1), (1,1)]:\n y = NAND(xs[0], xs[1])\n print(str(xs) + \" -> \" + str(y))\n","sub_path":"ch02/nand_gate.py","file_name":"nand_gate.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"111959523","text":"import sys\n\nfrom matrix import extract_matrix_from_csv, Matrix\n\n\ndef main():\n has_provided_filenames = len(sys.argv) > 2\n\n first_matrix_filename = sys.argv[1] if has_provided_filenames else './matrix1.csv'\n first_matrix_values = extract_matrix_from_csv(first_matrix_filename)\n first_matrix = Matrix(first_matrix_values)\n\n second_matrix_filename = sys.argv[2] if has_provided_filenames else './matrix2.csv'\n second_matrix_values = extract_matrix_from_csv(second_matrix_filename)\n second_matrix = Matrix(second_matrix_values)\n \n result = first_matrix + second_matrix\n\n if result:\n print('true' if result.is_symmetric else 'false')\n else:\n print('undefined')\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"classA/4/homework2/task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"119811574","text":"import os, sys, re, shutil\nimport numpy as np\nimport gc\n\nfrom ase.io import read, write\nfrom ase.calculators.lj import LennardJones\nfrom ase.calculators.lammpslib import LAMMPSlib\n\n\n# Load Directories\nxyzDir = os.path.join(os.getcwd(), \"xyz\")\ninDir = os.path.join(os.getcwd(), \"in\")\nrawDir = os.path.join(os.getcwd(), \"raw\")\nhesDir = os.path.join(os.getcwd(), \"Hessians\") \ntrajvdWDir = os.path.join(os.getcwd(), \"Trajectories_vdW\")\ntrajIDDir = os.path.join(os.getcwd(), \"Trajectories_ID\")\npicDir = os.path.join(os.getcwd(), \"Pictures\")\n\n# Run all structures\nfor i in sorted(os.listdir(inDir)):\n name = i.split(\".\")[0]\n inputfile = os.path.join(inDir, name+\".in\")\n hessian = os.path.join(hesDir, name+\".hes\")\n \n gc.collect()\n outputfile = os.path.join(trajIDDir, name+\".traj\")\n os.system(\"python Identity_run.py -i {} -o {}\".format(inputfile, outputfile))\n \n outputfile = os.path.join(trajvdWDir, name+\".traj\")\n os.system(\"python precon_vdW_run.py -i {} --hessian {} -o {}\".format(inputfile, hessian, outputfile))\n gc.collect()\n \n \n","sub_path":"all_run.py","file_name":"all_run.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"620836852","text":"import argparse\nimport logging\nimport os\n\nfrom boto3 import Session\nfrom configparser import ConfigParser\nfrom logging.handlers import TimedRotatingFileHandler\n\nfrom google_drive import PyDriveWrapper\n\n\ndef get_arguments():\n parser = argparse.ArgumentParser(description='This script upload provided s3 file to Google Team Drive')\n parser.add_argument('--s3_file', type=str, required=True, help='S3 path of the file to upload')\n parser.add_argument('--team_drive_id', type=str, required=False, help='ID of the google team drive to upload to')\n parser.add_argument('--folder_id', type=str, required=False, help='ID of the google folder to upload to')\n\n return parser.parse_args()\n\n\ndef setup_logger(logger_name, logger_level=logging.INFO, log_filename=None):\n # If log_filename is not defined, take logger_name\n if not log_filename:\n log_filename = \"{}.log\".format(logger_name)\n\n # Initialize logger object\n logger = logging.getLogger(logger_name)\n logger.setLevel(logger_level)\n\n # Create logs folder\n log_folder = 'logs'\n if not os.path.exists(log_folder):\n os.makedirs(log_folder, exist_ok=True)\n\n # Assign log file path\n log_file_path = os.path.join(log_folder, log_filename)\n\n # Add a rotating handler to logger\n time_rotating_handler = TimedRotatingFileHandler(log_file_path, when='midnight', backupCount=5)\n time_rotating_handler.setLevel(logger_level)\n time_rotating_handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))\n logger.addHandler(time_rotating_handler)\n\n return logger\n\n\nif __name__ == '__main__':\n logger_ = setup_logger(logger_name=__file__)\n\n # Assign cmd arguments to variable\n args = get_arguments()\n s3_file = args.s3_file\n team_drive_id = args.team_drive_id\n folder_id = args.folder_id\n\n # Extract necessary info for downloading file from s3\n bucket_name = s3_file.split(\"//\")[-1].split(\"/\")[0]\n key = s3_file.split(bucket_name + \"/\")[-1]\n filename = key.split(\"/\")[-1]\n\n # Read aws credentials from config.ini file\n config = ConfigParser()\n config.read('config.ini')\n aws_access_key_id = config['s3']['aws_access_key_id']\n aws_secret_access_key = config['s3']['aws_secret_access_key']\n\n # Download file from s3\n try:\n aws_session = Session(aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key)\n s3_client = aws_session.resource('s3')\n logger_.info(\"Downloading {} from s3\".format(s3_file))\n s3_client.Bucket(bucket_name).download_file(key, filename)\n logger_.info(\"Downloaded {} from s3\".format(s3_file))\n except Exception as e:\n raise\n\n # Upload downloaded file to gdrive\n try:\n drive = PyDriveWrapper()\n logger_.info(\"Uploading {} to gdrive\".format(filename))\n drive.upload_file(file_to_upload=filename, filename=filename, team_drive_id=team_drive_id, folder_id=folder_id,\n replace=True)\n logger_.info(\"Uploaded {} to gdrive\".format(filename))\n except Exception as e:\n raise\n\n # Delete downloaded file\n try:\n logger_.info(\"Removing {} from local\".format(filename))\n os.remove(filename)\n logger_.info(\"Removed {} from local\".format(filename))\n except Exception as e:\n raise\n","sub_path":"drive/s3_to_gdrive.py","file_name":"s3_to_gdrive.py","file_ext":"py","file_size_in_byte":3348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"621683202","text":"'''\nCreated on Jan 22, 2019\n\n@author: RayL\n'''\nfrom cursor import Cursor #Import needed sprites/ classes\nfrom button import Button\nimport pygame\nfrom sprites import bg\n\nclass Mainmenu():\n \"\"\"Class that represents the main menu\"\"\"\n def __init__(self,window):\n \"\"\"Constructor\"\"\"\n self.window = window \n pygame.font.init()\n self.buttonFont = pygame.font.Font(\"emulogic.ttf\",15) #Prepare fonts\n self.tutorialFont = pygame.font.Font(\"emulogic.ttf\",10)\n self.titleFont = pygame.font.Font(\"emulogic.ttf\",25)\n self.title = self.titleFont.render(\"Megaman Battles\", False, (0,0,0))\n self.playButton = Button(self.buttonFont.render(\"Play Game (2P)\",\n False,\n (0,0,0)),\n self.window,\n 400,\n 150,\n 1) #Initialize player button\n self.tutorialButton = Button(self.buttonFont.render(\"Read Tutorial\",\n False,\n (0,0,0)),\n self.window,\n 400,\n 300,\n 2) #Initialize tutorial button\n self.buttons = [self.playButton,self.tutorialButton] #List to hold buttons\n self.buttonIndex = 0 #Index to see which button is chosen.\n self.cursor = Cursor(self.buttons[self.buttonIndex].x + 256,\n self.buttons[self.buttonIndex].y,\n self.window) #Initialize cursor\n self.running = True\n \n def draw(self):\n \"\"\"Draw main menu\"\"\"\n self.window.blit(bg,(0,0)) #Draw background first\n self.window.blit(self.title,(350,50)) #Draw title\n self.playButton.draw() #Draw buttons\n self.tutorialButton.draw()\n self.cursor.draw() #Draw cursor\n pygame.display.update() #Update display\n \n def run(self):\n \"\"\"Run the main menu\"\"\"\n while self.running:\n pygame.time.delay(125) #Delay to not take multiple inputs at once\n self.cursor.move(self.buttons[self.buttonIndex].y) #Move the cursor\n for event in pygame.event.get(): #Loop to check for user exit. \n if event.type == pygame.QUIT:\n return 3\n keys = pygame.key.get_pressed() #Get keys\n if keys[pygame.K_DOWN]: #If they pressed down\n if self.buttonIndex + 1 == len(self.buttons): #If the index exceeds the list length\n self.buttonIndex = 0 #Move the cursor to the first button\n else:\n self.buttonIndex += 1 #Move the cursor down.\n if keys[pygame.K_UP]: #If up is pressed\n if self.buttonIndex - 1 == -1: #If the index is less than 0\n self.buttonIndex = len(self.buttons) - 1 #Move the cursor to the last button\n else:\n self.buttonIndex -= 1 #Move the cursor up\n if keys[pygame.K_RETURN]: #If Enter is pressed\n return self.buttons[self.buttonIndex].getDecision() #Return decision stored in selected button\n self.draw() #Draw\n \n def tutorial(self):\n run = True\n texts = [self.tutorialFont.render(\"There are two players in this game.\",False,(0,0,0)),\n self.tutorialFont.render(\"Player one is on the left and player two is on the right.\",False,(0,0,0)),\n self.tutorialFont.render(\"Player one uses WASD to move and space to shoot.\", False, (0,0,0)),\n self.tutorialFont.render(\"Player two uses IJKL and Backslash (the button above enter) to shoot.\",False,(0,0,0)),\n self.tutorialFont.render(\"Both players cannot cross the middle of the arena.\",False,(0,0,0)),\n self.tutorialFont.render(\"Good luck and Have Fun! Press\",False,(0,0,0)),\n self.tutorialFont.render(\"Enter to go back to the main menu.\",False,(0,0,0))\n ] #Tutorial text split into lines\n self.window.blit(bg,(0,0)) #Blit background once.\n i = 0\n for text in texts: #Blit each line of text\n self.window.blit(text,(200,i))\n i += 30\n pygame.display.update() #Update display\n while run: #Main loop\n pygame.time.delay(100) #Delay\n for event in pygame.event.get(): #Loop to check for user exit. \n if event.type == pygame.QUIT:\n run = False\n keys = pygame.key.get_pressed()\n if keys[pygame.K_RETURN]: #If enter is pressed, exit\n run = False","sub_path":"mainmenu.py","file_name":"mainmenu.py","file_ext":"py","file_size_in_byte":5004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"249619741","text":"\n\nfrom __future__ import division\nimport math\nimport python_color\n\n\ndef get_color_hex(val, min, max, rgb_min, rgb_max, rgb_start, rgb_end):\n if (val == min):\n return rgb_min\n elif (val == max):\n return rgb_max\n else:\n hsv_start = python_color.ColorRgb(rgb_start).to_hsv()\n hsv_end = python_color.ColorRgb(rgb_end).to_hsv()\n ratio = (val - min) / (max - min)\n return python_color.ColorHsv((\n hsv_start.hue + ratio * (hsv_end.hue - hsv_start.hue)\n , hsv_start.sat + ratio * (hsv_end.sat - hsv_start.sat)\n , hsv_start.val + ratio * (hsv_end.val- hsv_start.val))).to_rgb().to_hex()","sub_path":"old/unused/python_functions.py","file_name":"python_functions.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"645167043","text":"#! /usr/bin/env python\n#encoding:utf-8\nfrom __future__ import division\n\nimport tensorflow as tf\nimport numpy as np\nimport math\nimport os\nimport time\nimport datetime\nimport data_helpers\nfrom text_cnn import TextCNN\nfrom tensorflow.contrib import learn\n\n# Parameters\n# ==================================================\n\n# Data loading params\ntf.flags.DEFINE_float(\"dev_sample_percentage\", .1, \"Percentage of the training data to use for validation\")\ntf.flags.DEFINE_string(\"positive_data_file\", \"\", \"Data source for the positive data.\")\ntf.flags.DEFINE_string(\"negative_data_file\", \"\", \"Data source for the positive data.\")\ntf.flags.DEFINE_string(\"positive_vec_file\", \"\", \"Data source for the positive data.\")\ntf.flags.DEFINE_string(\"negative_vec_file\", \"\", \"Data source for the positive data.\")\ntf.flags.DEFINE_string(\"output_dir\", \"\", \"directory for save train output\")\n\ntf.flags.DEFINE_string(\"vocab_embedding_file\", \"\", \"word embedding for vocabulary.\")\n\n# Model Hyperparameters\ntf.flags.DEFINE_integer(\"embedding_dim\", 200, \"Dimensionality of character embedding (default: 128)\")\ntf.flags.DEFINE_string(\"filter_sizes\", \"1,2,3,4\", \"Comma-separated filter sizes (default: '3,4,5')\")\ntf.flags.DEFINE_integer(\"num_filters\", 128, \"Number of filters per filter size (default: 128)\")\ntf.flags.DEFINE_float(\"dropout_keep_prob\", 0.5, \"Dropout keep probability (default: 0.5)\")\ntf.flags.DEFINE_float(\"l2_reg_lambda\", 0.2, \"L2 regularizaion lambda (default: 0.0)\")\n\n# Training parameters\ntf.flags.DEFINE_integer(\"batch_size\", 128, \"Batch Size (default: 128)\")\ntf.flags.DEFINE_integer(\"num_epochs\", 200, \"Number of training epochs (default: 200)\")\ntf.flags.DEFINE_integer(\"evaluate_every\", 50, \"Evaluate model on dev set after this many steps (default: 50)\")\ntf.flags.DEFINE_integer(\"checkpoint_every\", 100, \"Save model after this many steps (default: 100)\")\n# Misc Parameters\ntf.flags.DEFINE_boolean(\"allow_soft_placement\", True, \"Allow device soft device placement\")\ntf.flags.DEFINE_boolean(\"log_device_placement\", False, \"Log placement of ops on devices\")\n\nFLAGS = tf.flags.FLAGS\nFLAGS._parse_flags()\nprint(\"\\nParameters:\")\nfor attr, value in sorted(FLAGS.__flags.items()):\n\tprint(\"{}={}\".format(attr.upper(), value))\nprint(\"\")\n\n# Data Preparatopn\n# ==================================================\n\ndef tokenizer(iterator):\n\t\"\"\"Tokenizer generator.\n\tArgs:\n\t\titerator: Input iterator with strings.\n\tYields:\n\t\tarray of tokens per each value in the input.\n\t\"\"\"\n\tfor value in iterator:\n\t\tyield value.split(' ')\n\n# Load data\nprint(\"Loading data...\")\nx_text, y = data_helpers.load_data_and_labels(FLAGS.positive_data_file, FLAGS.negative_data_file)\nnum_train = int(len(y)*(1.0-FLAGS.dev_sample_percentage))\nvector_train = data_helpers.load_vector(FLAGS.positive_vec_file, FLAGS.negative_vec_file)\nnum_validate = len(y)-num_train\n\nW_pretrain = np.loadtxt(FLAGS.vocab_embedding_file)\nfor i in range(len(W_pretrain)):\n\tif math.isnan(np.sum(W_pretrain[i])):\n\t\tW_pretrain[i] = np.zeros(shape=FLAGS.embedding_dim)\n\n# Build vocabulary\nmax_document_length = max([len(x.split(\" \")) for x in x_text])\nvocab_processor = learn.preprocessing.VocabularyProcessor(max_document_length,tokenizer_fn=tokenizer)\nx = np.array(list(vocab_processor.fit_transform(x_text)))\n\n# Randomly shuffle data\nnp.random.seed(1)\nshuffle_indices = np.random.permutation(np.arange(len(y)))\nx = x[shuffle_indices]\ny = y[shuffle_indices]\nx_text = np.array(x_text)[shuffle_indices]\nvector_train = vector_train[shuffle_indices]\n\n# Split train/test set\nx_train, x_dev = x[:num_train], x[num_train:]\ny_train, y_dev = y[:num_train], y[num_train:]\nvector_train, vector_validate = vector_train[:num_train], vector_train[num_train:]\nprint(\"Vocabulary Size: {:d}\".format(len(vocab_processor.vocabulary_)))\nprint(\"Train/Dev split: {:d}/{:d}\".format(len(y_train), len(y_dev)))\n\ntest_save_dir=FLAGS.output_dir+'/test_result/'\nif not os.path.exists(test_save_dir):\n\tos.makedirs(test_save_dir)\nwith open(test_save_dir+'/text_label', 'w') as fout:\n\tfor i in range(num_validate):\n\t\tidx='0' if y_dev[i][0]==1 else '1'\n\t\tfout.write(x_text[i+num_train]+'\\t'+idx+'\\n')\n\n# Training\n# ==================================================\n\nwith tf.Graph().as_default():\n\tsession_conf = tf.ConfigProto(\n\t allow_soft_placement=FLAGS.allow_soft_placement,\n\t log_device_placement=FLAGS.log_device_placement)\n\tsess = tf.Session(config=session_conf)\n\twith sess.as_default():\n\t\tcnn = TextCNN(\n\t\t\tsequence_length=x_train.shape[1],\n\t\t\tnum_classes=y_train.shape[1],\n\t\t\tnum_features=vector_train.shape[1],\n\t\t\tvocab_size=len(vocab_processor.vocabulary_),\n\t\t\tembedding_size=FLAGS.embedding_dim,\n\t\t\tfilter_sizes=list(map(int, FLAGS.filter_sizes.split(\",\"))),\n\t\t\tnum_filters=FLAGS.num_filters,\n\t\t\tl2_reg_lambda=FLAGS.l2_reg_lambda,\n\t\t\tW_pretrain=W_pretrain,\n\t\t\t)\n\n\t\t# Define Training procedure\n\t\tglobal_step = tf.Variable(0, name=\"global_step\", trainable=False)\n\t\toptimizer = tf.train.AdamOptimizer(1e-4)\n\t\t#optimizer = tf.train.RMSPropOptimizer(1e-4)\n\t\tgrads_and_vars = optimizer.compute_gradients(cnn.loss)\n\t\ttrain_op = optimizer.apply_gradients(grads_and_vars, global_step=global_step)\n\n\t\t# Keep track of gradient values and sparsity (optional)\n\t\tgrad_summaries = []\n\t\tfor g, v in grads_and_vars:\n\t\t\tif g is not None:\n\t\t\t\tgrad_hist_summary = tf.histogram_summary(\"{}/grad/hist\".format(v.name), g)\n\t\t\t\tsparsity_summary = tf.scalar_summary(\"{}/grad/sparsity\".format(v.name), tf.nn.zero_fraction(g))\n\t\t\t\tgrad_summaries.append(grad_hist_summary)\n\t\t\t\tgrad_summaries.append(sparsity_summary)\n\t\tgrad_summaries_merged = tf.merge_summary(grad_summaries)\n\n\t\t# Output directory for models and summaries\n\t\tout_dir=FLAGS.output_dir\n\t\tprint(\"Writing to {}\\n\".format(out_dir))\n\n\t\t# Summaries for loss and accuracy\n\t\tloss_summary = tf.scalar_summary(\"loss\", cnn.loss)\n\t\tacc_summary = tf.scalar_summary(\"accuracy\", cnn.accuracy)\n\n\t\t# Train Summaries\n\t\ttrain_summary_op = tf.merge_summary([loss_summary, acc_summary, grad_summaries_merged])\n\t\ttrain_summary_dir = os.path.join(out_dir, \"summaries\", \"train\")\n\t\ttrain_summary_writer = tf.train.SummaryWriter(train_summary_dir, sess.graph)\n\n\t\t# Dev summaries\n\t\tdev_summary_op = tf.merge_summary([loss_summary, acc_summary])\n\t\tdev_summary_dir = os.path.join(out_dir, \"summaries\", \"dev\")\n\t\tdev_summary_writer = tf.train.SummaryWriter(dev_summary_dir, sess.graph)\n\n\t\t# Checkpoint directory. Tensorflow assumes this directory already exists so we need to create it\n\t\tcheckpoint_dir = os.path.abspath(os.path.join(out_dir, \"checkpoints\"))\n\t\tcheckpoint_prefix = os.path.join(checkpoint_dir, \"model\")\n\t\tif not os.path.exists(checkpoint_dir):\n\t\t\tos.makedirs(checkpoint_dir)\n\t\tsaver = tf.train.Saver(tf.all_variables())\n\n\t\tgraph_dir = os.path.abspath(os.path.join(out_dir, \"graphDef\"))\n\t\tif not os.path.exists(graph_dir):\n\t\t\tos.makedirs(graph_dir)\n\t\ttf.train.write_graph(sess.graph_def, graph_dir, \"test.pb\")\n\n\t\t# Write vocabulary\n\t\tvocab_processor.save(os.path.join(out_dir, \"vocab\"))\n\n\t\t# Initialize all variables\n\t\tinit = tf.initialize_variables(tf.all_variables(), name='init_all_vars_op')\n\t\tsess.run(init)\n\t\t\n\t\tdef save():\n\t\t\tfor variable in tf.trainable_variables():\n\t\t\t\ttensor = tf.constant(variable.eval())\n\t\t\t\ttf.assign(variable, tensor, name=\"nWeights\")\n\n\t\tdef train_step(x_batch, y_batch, features_batch):\n\t\t\t\"\"\"\n\t\t\tA single training step\n\t\t\t\"\"\"\n\t\t\tfeed_dict = {\n\t\t\t cnn.input_x: x_batch,\n\t\t\t cnn.input_y: y_batch,\n\t\t\t cnn.dropout_keep_prob: FLAGS.dropout_keep_prob,\n\t\t\t cnn.input_features: features_batch\n\t\t\t}\n\t\t\t_, step, summaries, loss, accuracy= sess.run(\n\t\t\t\t[train_op, global_step, train_summary_op, cnn.loss, cnn.accuracy],\n\t\t\t\tfeed_dict)\n\t\t\ttime_str = datetime.datetime.now().isoformat()\n\t\t\t#print(\"{}: step {}, loss {:g}, acc {:g}\".format(time_str, step, loss, accuracy))\n\t\t\ttrain_summary_writer.add_summary(summaries, step)\n\t\t\n\t\tdef dump_eval(y_label,y_predict):\n\t\t\ttp_count = 0\n\t\t\tfn_count = 0\n\t\t\tfp_count = 0\n\t\t\ttn_count = 0\n\t\t\tfor l,p in zip(y_label[:,1],y_predict):\n\t\t\t\tif l==1 and p==1:\n\t\t\t\t\ttp_count += 1\n\t\t\t\telif l==0 and p==1:\n\t\t\t\t\tfn_count += 1\n\t\t\t\telif l==1 and p==0:\n\t\t\t\t\tfp_count += 1\n\t\t\t\telse:\n\t\t\t\t\ttn_count += 1\n\t\t\tacc_p = tp_count / (tp_count + fp_count)\n\t\t\tacc_n = tn_count / (tn_count + fn_count)\n\t\t\tacc = (tp_count + tn_count) / (tp_count + fn_count + fp_count + tn_count)\n\t\t\trecall = tp_count / (tp_count + fn_count)\n\t\t\tf1 = 2 * recall * acc / (acc + recall)\n\t\t\twith open(test_save_dir+'/predict', 'w') as fout:\n\t\t\t\tfout.write('\\n'.join([str(i) for i in y_predict]))\n\t\t\treturn acc_p,acc_n,acc,recall,f1\n\n\t\tdef dev_step(x_batch, y_batch, features_batch, writer=None):\n\t\t\t\"\"\"\n\t\t\tEvaluates model on a dev set\n\t\t\t\"\"\"\n\t\t\tfeed_dict = {\n\t\t\t cnn.input_x: x_batch,\n\t\t\t cnn.input_y: y_batch,\n\t\t\t cnn.dropout_keep_prob: 1.0,\n\t\t\t cnn.input_features: features_batch\n\t\t\t}\n\t\t\tstep, summaries, loss, accuracy, y_predict = sess.run(\n\t\t\t\t[global_step, dev_summary_op, cnn.loss, cnn.accuracy, cnn.predictions],\n\t\t\t\tfeed_dict)\n\t\t\tacc_p,acc_n,acc,recall,f1 = dump_eval(y_batch,y_predict)\n\t\t\t\n\t\t\ttime_str = datetime.datetime.now().isoformat()\n\t\t\tprint(\"Eval:{}: step {}, loss {:g}, acc_p {:g}, acc_n {:g}, acc {:g}, recall {:g}, f1 {:g}\".format(time_str, step, loss,acc_p,acc_n,acc,recall,f1))\n\t\t\tif writer:\n\t\t\t\twriter.add_summary(summaries, step)\n\n\t\t# Generate batches\n\t\tbatches = data_helpers.batch_iter(\n\t\t\tlist(zip(x_train, y_train, vector_train)), FLAGS.batch_size, FLAGS.num_epochs)\n\t\t# Training loop. For each batch...\n\t\tfor batch in batches:\n\t\t\tx_batch, y_batch, features_batch = zip(*batch)\n\t\t\ttrain_step(x_batch, y_batch, features_batch)\n\t\t\tcurrent_step = tf.train.global_step(sess, global_step)\n\t\t\tif current_step % FLAGS.evaluate_every == 0:\n\t\t\t\tdev_step(x_dev, y_dev, vector_validate, writer=dev_summary_writer)\n\t\t\tif current_step % FLAGS.checkpoint_every == 0:\n\t\t\t\tpath = saver.save(sess, checkpoint_prefix, global_step=current_step)\n","sub_path":"textcnn/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":9811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"2083941","text":"# deleting the repeating elements in the array\nprint('''Venkatesh\n121910313056''')\nn = int(input('enter the number of elements in the array: '))\nprint ('Enter the elements of the array')\na = []\nb = []\n#Taking the user input\nfor i in range(0,n):\n i = int(input())\n a.append(i)\nprint(f'The original array = {a}')\n# Deleting the repeated elements by using \"not in\" \nfor i in a:\n if i not in b:\n b.append(i)\n\nprint(f'Array without the repeated elements = {b}')\n","sub_path":"deleting the repeating elements in the array.py","file_name":"deleting the repeating elements in the array.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"429586775","text":"import numpy as np\nimport scipy as sp\nimport scipy.io as spio\nimport scipy.interpolate\nimport sqlite3 as sql\nimport pandas as pd\nfrom datetime import datetime\nfrom glob import glob\nimport os.path\nfrom astropy.convolution import convolve, Gaussian1DKernel\nimport utilities as u\n\ndef loadmat_sbx(filename):\n '''\n this function should be called instead of direct spio.loadmat\n as it cures the problem of not properly recovering python dictionaries\n from mat files. It calls the function check keys to cure all entries\n which are still mat-objects\n '''\n data = spio.loadmat(filename, struct_as_record=False, squeeze_me=True)\n info = _check_keys(data)['info']\n # Defining number of channels/size factor\n if info['channels'] == 1:\n info['nChan'] = 2; factor = 1\n elif info['channels'] == 2:\n info['nChan'] = 1; factor = 2\n elif info['channels'] == 3:\n info['nChan'] = 1; factor = 2\n\n # Determine number of frames in whole file\n info['max_idx'] = int(os.path.getsize(filename[:-4] + '.sbx')/info['recordsPerBuffer']/info['sz'][1]*factor/4/(2-info['scanmode'])-1)\n info['fr']=info['resfreq']/info['config']['lines']*(2-info['scanmode'])\n return info\n\n\ndef _check_keys(dict):\n '''\n checks if entries in dictionary are mat-objects. If yes\n todict is called to change them to nested dictionaries\n '''\n\n for key in dict:\n if isinstance(dict[key], spio.matlab.mio5_params.mat_struct):\n dict[key] = _todict(dict[key])\n return dict\n\ndef _todict(matobj):\n '''\n A recursive function which constructs from matobjects nested dictionaries\n '''\n\n dict = {}\n for strg in matobj._fieldnames:\n elem = matobj.__dict__[strg]\n if isinstance(elem, spio.matlab.mio5_params.mat_struct):\n dict[strg] = _todict(elem)\n else:\n dict[strg] = elem\n return dict\n\n\ndef load_scan_sess(sess,plane=0,fneu_coeff=.7):\n '''loads imaging aligned behavioral data and neural data for a single session\n inputs:\n sess: row from pandas array of session metadata\n can also be a dictionary as long as the following fields are present and valid\n 'data file' - raw VR *.sqlite data file path\n 'scanmat' - Neurolabware .mat file path\n 's2pfolder' - Suite2P output path\n plane: which imaging plane to load - zero indexed\n fneu_coeff: coefficient to multiply neuropil coefficient by for dF/F calculation\n outputs:\n VRDat: imaging aligned behavioral data as pandas array (timepoints x number of variables)\n C: dF/F (timepoints x neurons)\n S: deconcolved activity rate (timepoints x neurons)\n F_: raw extracted fluorescence (timepoints x neurons)'''\n\n # load aligned VR Data\n VRDat = behavior_dataframe(sess['data file'],scanmats=sess['scanmat'],concat=False)\n\n # load imaging\n info = loadmat_sbx(sess['scanmat'])\n\n # suite2p output folder\n folder = os.path.join(sess['s2pfolder'],'plane%i' % plane)\n\n F= np.load(os.path.join(folder,'F.npy')) # raw extracted fluorescence\n Fneu = np.load(os.path.join(folder,'Fneu.npy')) # neuropil fluorescence\n iscell = np.load(os.path.join(folder,'iscell.npy')) # mask for whether ROI is a cell or not\n S = np.load(os.path.join(folder,'spks.npy')) # deconvolved activity rate\n F_ = F-fneu_coeff*Fneu #neuropil correction\n C=F_[iscell[:,0]>0,:].T\n C = u.df(C) # dF/F\n S=S[iscell[:,0 ]>0,:].T\n frame_diff = VRDat.shape[0]-C.shape[0] # make sure that VR data and imaging data are the same length\n print('frame diff',frame_diff)\n assert (frame_diff==0), \"something is wrong with aligning VR and calcium data\"\n return VRDat,C,S,F_[iscell[:,0]>0,:].T\n\n\ndef load_session_db(dir = \"G:\\\\My Drive\\\\\"):\n '''open the sessions sqlite database and add some columns\n inputs:\n dir: base directory for VR data\n\n outputs:\n df: pandas array 'dataframe' which contains metadata for all sessions '''\n\n # find sqlite file that contains metadata\n vr_fname = os.path.join(dir,\"VR_Data\",\"TwoTower\",\"behavior.sqlite\")\n\n # open a connections to pandas dataframe\n conn = sql.connect(vr_fname)\n df = pd.read_sql(\"SELECT MouseName, DateFolder, SessionNumber,Track, RewardCount, Imaging, ImagingRegion FROM sessions\",conn)\n sdir = os.path.join(dir,\"VR_Data\",\"TwoTower\")\n\n # convert file name to date time\n df['DateTime'] = [datetime.strptime(s,'%d_%m_%Y') for s in df['DateFolder']]\n\n # build data file name\n df['data file'] = [ build_VR_filename(df['MouseName'].iloc[i],\n df['DateFolder'].iloc[i],\n df['Track'].iloc[i],\n df['SessionNumber'].iloc[i],serverDir=sdir) for i in range(df.shape[0])]\n\n twop_dir = os.path.join(dir,\"2P_Data\",\"TwoTower\")\n\n # build folders for 2P data locations\n # .mat\n df['scanmat'] = [build_2P_filename(df.iloc[i],serverDir=twop_dir) for i in range(df.shape[0])]\n # add s2p filefolder\n df['s2pfolder']=[build_s2p_folder(df.iloc[i],serverDir=twop_dir) for i in range(df.shape[0])]\n\n # close connection to sqlite file\n conn.close()\n return df\n\ndef build_s2p_folder(df,serverDir=\"G:\\\\My Drive\\\\2P_Data\\\\TwoTower\\\\\"):\n '''build Suite2P results folder from metadata information. called internally from load_session_db\n inputs:\n df: single row from metadata array\n outputs:\n Suite2p results path'''\n\n # build folder name\n res_folder = os.path.join(serverDir,df['MouseName'],df['DateFolder'],df['Track'],\"%s_*%s_*\" % (df['Track'],df['SessionNumber']),'suite2p')\n # check for potential matches\n match= glob(res_folder)\n assert len(match)<2, \"Suite2P multiple matching subfolders\"\n if len(match)<1:\n return None\n else:\n return match[0]\n\n\n\ndef build_2P_filename(df,serverDir = \"G:\\\\My Drive\\\\2P_Data\\\\TwoTower\\\\\"):\n ''' use sessions database inputs to build appropriate filenames for 2P data\n called internally from load_session_db\n inputs: same as build_s2p_folder\n outputs: path to Neurolabware *.mat file'''\n\n mouse,date,scene,sess = df[\"MouseName\"],df[\"DateFolder\"],df[\"Track\"],df[\"SessionNumber\"]\n info_fname = os.path.join(serverDir,mouse,date,scene,\"%s_*%s_*[0-9].mat\" % (scene,sess))\n info_file = glob(info_fname)\n if len(info_file)>0:\n match= glob(info_file[0])\n assert len(match)<2, \"2P .mat: multiple matching files\"\n if len(match)==0:\n return None\n else:\n return info_file[0]\n else:\n return None\n\ndef build_VR_filename(mouse,date,scene,session,serverDir = \"G:\\\\My Drive\\\\VR_Data\\\\TwoTower\\\\\",verbose = False):\n '''use sessions database to build filenames for behavioral data (also a\n sqlite database)\n called internally from load_session_db\n inputs: same as build_s2p_folder\n outputs: path to Unity created .sqlite beahvioral data\n '''\n fname = os.path.join(serverDir,mouse,date,\"%s_%s.sqlite\" % (scene,session))\n file=glob(fname)\n\n if len(file)==1:\n return file[0]\n elif len(file)>1:\n if verbose:\n print(\"%s\\\\%s\\\\%s\\\\%s_%s.sqlite\" % (serverDir, mouse, date, scene, session))\n print(\"file doesn't exist or multiples, errors to come!!!\")\n else:\n if verbose:\n print(\"%s\\\\%s\\\\%s\\\\%s_%s.sqlite\" % (serverDir, mouse, date, scene, session))\n print(\"file doesn't exist or multiples, errors to come!!!\")\n\ndef behavior_dataframe(filenames,scanmats=None,concat = True,fix_teleports=True):\n '''Load a list of vr sessions given filenames. Capable of concatenating for\n averaging data across sessions. If scanmats is not None, aligns VR data to\n imaging data.\n inputs:\n filenames - string or list of strings with paths to VR sqlite files\n scanmats- string or list of strings with paths to .mat files from 2P data\n concat- bool, whether or not to concatenate sessions\n outpus:\n df/frames - [aligned][concatenated] VR dataframe/list of VR dataframes\n '''\n # print(filenames)\n # if there is imaging data\n if scanmats is None:\n # if multiple sessions\n if isinstance(filenames,list):\n frames = [_VR_interp(_get_frame(f)) for f in filenames] # load data and interpolate onto even time grid\n df = pd.concat(frames,ignore_index=True) # concatenate data\n else: #load single session\n df = _VR_interp(_get_frame(filenames,fix_teleports=fix_teleports))\n df['trial number'] = np.cumsum(df['teleport']) # fix trial numbers\n\n if isinstance(filenames,list):\n if concat:\n return df\n else:\n return frames\n else:\n return df\n\n else:\n if isinstance(filenames,list):\n # check to make sure number of scanmats and sqlite files is the same\n if len(filenames)!=len(scanmats):\n raise Exception(\"behavior and scanfile lists must be of the same length\")\n else:\n # load and align all VR data\n frames = [_VR_align_to_2P(_get_frame(f,fix_teleports=fix_teleports),s) for (f,s) in zip(filenames,scanmats)]\n df = pd.concat(frames,ignore_index=True)\n else:\n df = _VR_align_to_2P(_get_frame(filenames,fix_teleports=fix_teleports),scanmats)\n\n df['trial number'] = np.cumsum(df['teleport'])\n\n if isinstance(filenames,list):\n if concat:\n return df\n else:\n return frames\n else:\n return df\n\ndef _VR_align_to_2P(vr_dframe,infofile, n_imaging_planes = 1,n_lines = 512.):\n '''align VR behavior data to 2P sample times using splines. called internally\n from behavior_dataframe if scanmat exists\n inputs:\n vr_dframe- VR pandas dataframe loaded directly from .sqlite file\n infofile- path\n n_imaging_planes- number of imaging planes (not implemented)\n n_lines - number of lines collected during each frame (default 512.)\n outputs:\n ca_df - calcium imaging aligned VR data frame (pandas dataframe)\n '''\n\n info = loadmat_sbx(infofile) # load .mat file with ttl times\n fr = info['fr'] # frame rate\n # print(info)\n lr = fr*n_lines # line rate\n\n ## on Feb 6, 2019 noticed that AA's new National Instruments board\n ## created a floating ground on my TTL circuit. This caused a bunch of extra TTLs\n ## due to unexpected grounding of the signal.\n\n\n orig_ttl_times = info['frame']/fr + info['line']/lr # including error ttls\n dt_ttl = np.diff(np.insert(orig_ttl_times,0,0)) # insert zero at beginning and calculate delta ttl time\n tmp = np.zeros(dt_ttl.shape)\n tmp[dt_ttl<.005] = 1 # find ttls faster than 200 Hz (unrealistically fast - probably a ttl which bounced to ground)\n # ensured outside of this script that this finds the true start ttl on every scan\n mask = np.insert(np.diff(tmp),0,0) # find first ttl in string that were too fast\n mask[mask<0] = 0\n print('num aberrant ttls',tmp.sum())\n\n frames = info['frame'][mask==0] # should be the original ttls up to a 1 VR frame error\n lines = info['line'][mask==0]\n\n ##\n ##\n\n # times of each ttl (VR frame)\n ttl_times = frames/fr + lines/lr\n numVRFrames = frames.shape[0]\n\n # create empty pandas dataframe to store calcium aligned data\n ca_df = pd.DataFrame(columns = vr_dframe.columns, index = np.arange(info['max_idx']))\n ca_time = np.arange(0,1/fr*info['max_idx'],1/fr) # time on this even grid\n if (ca_time.shape[0]-ca_df.shape[0])==1: # occaionally a 1 frame correction due to\n # scan stopping mid frame\n print('one frame correction')\n ca_time = ca_time[:-1]\n\n\n ca_df.loc[:,'time'] = ca_time\n mask = ca_time>=ttl_times[0] # mask for when ttls have started on imaging clock\n # (i.e. imaging started and stabilized, ~10s)\n\n # take VR frames for which there are valid TTLs\n vr_dframe = vr_dframe.iloc[-numVRFrames:]\n # print(ttl_times.shape,vr_dframe.shape)\n\n # linear interpolation of position\n print(ttl_times[0],ttl_times[-1])\n print(ca_time[mask][0],ca_time[mask][-1])\n f_mean = sp.interpolate.interp1d(ttl_times,vr_dframe['pos']._values,axis=0,kind='slinear')\n ca_df.loc[mask,'pos'] = f_mean(ca_time[mask])\n ca_df.loc[~mask,'pos']=-500.\n\n # nearest frame interpolation\n near_list = ['morph','clickOn','towerJitter','wallJitter','bckgndJitter']\n f_nearest = sp.interpolate.interp1d(ttl_times,vr_dframe[near_list]._values,axis=0,kind='nearest')\n ca_df.loc[mask,near_list] = f_nearest(ca_time[mask])\n ca_df.fillna(method='ffill',inplace=True)\n ca_df.loc[~mask,near_list]=-1.\n\n # integrate, interpolate and then take difference, to make sure data is not lost\n cumsum_list = ['dz','lick','reward','tstart','teleport','rzone']\n f_cumsum = sp.interpolate.interp1d(ttl_times,np.cumsum(vr_dframe[cumsum_list]._values,axis=0),axis=0,kind='slinear')\n ca_cumsum = np.round(np.insert(f_cumsum(ca_time[mask]),0,[0,0, 0,0 ,0,0],axis=0))\n if ca_cumsum[-1,-2]=ttl_times[0] # mask for when ttls have started on imaging clock\n # (i.e. imaging started and stabilized, ~10s)\n\n # take VR frames for which there are valid TTLs\n vr_dframe = vr_dframe.iloc[-numVRFrames:]\n # print(ttl_times.shape,vr_dframe.shape)\n\n # linear interpolation of position\n print(ttl_times[0],ttl_times[-1])\n print(ca_time[mask][0],ca_time[mask][-1])\n\n near_list = ['LEDCue']\n f_nearest = sp.interpolate.interp1d(ttl_times,vr_dframe[near_list]._values,axis=0,kind='nearest')\n ca_df.loc[mask,near_list] = f_nearest(ca_time[mask])\n ca_df.fillna(method='ffill',inplace=True)\n ca_df.loc[~mask,near_list]=-1.\n\n # integrate, interpolate and then take difference, to make sure data is not lost\n cumsum_list = ['dz','lick','reward','gng','manrewards']\n f_cumsum = sp.interpolate.interp1d(ttl_times,np.cumsum(vr_dframe[cumsum_list]._values,axis=0),axis=0,kind='slinear')\n ca_cumsum = np.round(np.insert(f_cumsum(ca_time[mask]),0,[0, 0,0 ,0,0],axis=0))\n if ca_cumsum[-1,-2].import unittest\n\n\nimport unittest\nimport os\n\nfrom qtpy import QtWidgets\nfrom mock import Mock\n\nfrom controller.NewFileInDirectoryWatcher import NewFileInDirectoryWatcher\n\nunittest_folder = os.path.join(os.path.dirname(__file__), '..', 'test_files')\n\n\nclass TestNewFileInDirectoryWatcher(unittest.TestCase):\n def setUp(self):\n self.app = QtWidgets.QApplication([])\n\n def tearDown(self):\n self.delete_if_exists('test.txt')\n\n def delete_if_exists(self, file_name):\n if os.path.exists(os.path.join(unittest_folder, file_name)):\n os.remove(os.path.join(unittest_folder, file_name))\n\n def test_new_file(self):\n self.watcher = NewFileInDirectoryWatcher(unittest_folder, file_types=['.txt'], activate=True)\n self.watcher.file_added = Mock()\n file_path = os.path.join(unittest_folder, 'test.txt')\n self.delete_if_exists('test.txt')\n\n f = open(file_path, 'w')\n f.write(\"abcdefg\"*20)\n f.close()\n\n self.watcher.check_files()\n self.watcher.file_added.emit.assert_called_once_with(file_path)\n\n\n","sub_path":"t-rax/test/controller_test/test_NewFileInDirectoryWatcher.py","file_name":"test_NewFileInDirectoryWatcher.py","file_ext":"py","file_size_in_byte":1970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"466400668","text":"import typing as tp\n\nfrom aiogram.types import Message\nfrom aiogram.types import ParseMode\nfrom aiogram.utils.markdown import code as md_code\n\nfrom api.auth import (\n session_exists,\n fetch_code,\n authorize,\n deauthorize,\n fetch_user,\n)\n\nMD2 = ParseMode.MARKDOWN_V2\n\n\nasync def set_code(message: Message) -> None:\n chat_id = message.chat.id\n if await session_exists(chat_id):\n await message.reply(\"Вы уже авторизованы.\\n\"\n \"Для сброса введите команду /reset_code\")\n return\n\n code = message.text.removeprefix(\"/set_code\").strip()\n if not code:\n await message.reply(\"Код пуст, попробуйте ещё раз\")\n return\n\n result = await authorize(chat_id, code)\n if not result.success:\n await message.reply(\"Не удалось авторизоваться.\\n\" f\"{result.details}\")\n return\n\n user = await fetch_user(chat_id)\n await message.reply(f\"Здравия желаю, {user.full_name}!\\n\"\n f\"Должность: командир взвода {user.milgroup}\")\n\n\nasync def my_code(message: Message) -> None:\n # `fetch_code` contract is fulfilled by auth middleware\n code = await fetch_code(message.chat.id)\n await message.reply(f\"Текущий код: {md_code(code)}\", parse_mode=MD2)\n\n\nasync def reset_code(message: Message) -> None:\n chat_id = message.chat.id\n result = await deauthorize(chat_id)\n\n if result.success:\n await message.reply(\"Код успешно сброшен\")\n else:\n await message.reply(\"Не удалось сбросить код.\\n\" f\"{result.details}\")\n","sub_path":"tgbot/src/handlers/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"397698202","text":"#!/opt/miniconda37/bin/python\n\nfrom to_dir_and_angle import calcWithoutIt, calculateIt\nfrom select_and_save import read_selected_stashes\n\nimport timeit\n\npath = '/na/gpfs1/ARCHIWUM/MM/IRIS/Sample_data'\nstashes = ['m01s03i225', 'm01s03i226']\ndata = read_selected_stashes(path, stashes)\nu = data[0].data\nv = data[1].data\n\nV1, a1 = calculateIt(u, v)\nV2, a2 = calcWithoutIt(u, v)\n\nprint((a1 == a2).all())\nprint((V1 == V2).all())\n\nSETUP='''\nfrom to_dir_and_angle import calcWithoutIt, calculateIt \nfrom select_and_save import read_selected_stashes \n \nimport numpy as np \nimport timeit \n \npath = '/na/gpfs1/ARCHIWUM/MM/IRIS/Sample_data' \nstashes = ['m01s03i225', 'm01s03i226'] \nrotation_angles = read_selected_stashes(path, stashes) \nu = rotation_angles[0].rotation_angles \nv = rotation_angles[1].rotation_angles \n'''\n\nwithIt = 'V1,a2 = calculateIt(u,v)'\nwithoutIt = 'V2, a2 = calcWithoutIt(u, v)'\n\nnum = 100\n\n#WITH 25.851256957277656\nprint('WITH\\n:')\nprint(timeit.timeit(stmt=withIt,setup=SETUP,number=num))\n\n#WITHOUT 22.489431232213974 \nprint('WITHOUT\\n:')\nprint(timeit.timeit(stmt=withoutIt,setup=SETUP,number=num))\n","sub_path":"UM_utils/other/test_speed.py","file_name":"test_speed.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"610821286","text":"t=int(input())\nfor i in range(t):\n a=input()\n b=input()\n c=[]\n \n for j in range(len(a)):\n column = []\n for i in range(len(b)):\n column.append(0)\n c.append(column)\n j=0\n \n while j < len(a):\n k=0\n while k < len(b):\n if a[j]==b[k]:\n c[j][k]=1+c[j-1][k-1]\n else:\n c[j][k]=max(c[j-1][k],c[j][k-1])\n k+=1 \n j+=1 \n \n print(c[len(a)-1][len(b)-1])\n \n","sub_path":"LCS1.py","file_name":"LCS1.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"176254015","text":"# noinspection PyUnresolvedReferences\nfrom pydelicious import get_popular,get_userposts,get_urlposts\n# noinspection PyUnresolvedReferences\nimport time\ndef initializeUserDict(tag,count=5):\n user_dict={}\n # get the top count' popular posts\n for p1 in get_popular(tag=tag)[0:2]:\n # find all users who posted this\n for p2 in get_urlposts(p1['url']):\n user=p2['user']\n user_dict[user]={}\n return user_dict\n\ndef fillItems(user_dict):\n all_items={}\n # Find links posted by all users\n for user in user_dict:\n if user is None or user=='': continue\n for post in get_userposts(user):\n url=post['url']\n user_dict[user][url]=1.0\n all_items[url]=1\n # Fill in missing items with 0\n for ratings in user_dict.values():\n for item in all_items:\n if item not in ratings:\n ratings[item]=0.0\n\n return user_dict\n\n#print get_userposts('anliberant')\n\ndelusers=initializeUserDict('programming')\n#print delusers\nprint(fillItems(delusers))\n#for user in delusers:\n # [print user for user in delusers]\n#print(delusers)","sub_path":"deliciousrec.py","file_name":"deliciousrec.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"6104667","text":"#!/usr/bin/python\n\nimport os\nimport json\nimport sys\nimport struct\nimport subprocess\nimport time\n\n# NOTES:\n# - print here will send back to the front end, and won't work.\n\nglobal DEBUG\nDEBUG=1\nglobal DBGFD\nglobal FILE_CONTAINING_CMD_TORUN\nFILE_CONTAINING_CMD_TORUN=\"tb-my-ed.cmd\"\nglobal mysrc\n\ndef dbgwr(data):\n global DEBUG, DBGFD\n\n if DEBUG:\n DBGFD.write(data)\n DBGFD.write(\"\\n\")\n DBGFD.flush()\n return\n\n# Encode a message for transmission, given its content.\ndef encode_message_v2(message_content):\n encoded_content = json.dumps(message_content)\n encoded_length = struct.pack('=I', len(encoded_content))\n return {'length': encoded_length, 'content': encoded_content}\n\n# Send an encoded message to stdout.\ndef send_reply_v2(msg_str):\n encoded_msg = encode_message_v2(msg_str)\n sys.stdout.write(encoded_msg['length'])\n sys.stdout.write(encoded_msg['content'])\n sys.stdout.flush()\n\ndef encode_message_v3(message_content):\n encoded_content = json.dumps(message_content).encode(\"utf-8\")\n encoded_length = struct.pack('=I', len(encoded_content))\n # use struct.pack(\"10s\", bytes), to pack a string of the length of \n # 10 characters\n return {\n 'length': encoded_length, \n 'content': struct.pack(str(len(encoded_content))+\"s\",encoded_content)\n }\n\ndef send_reply_v3(msg_str):\n encoded_msg = encode_message_v3(msg_str)\n sys.stdout.buffer.write(encoded_msg['length'])\n sys.stdout.buffer.write(encoded_msg['content'])\n sys.stdout.buffer.flush()\n\ndef send_reply(msg_str):\n if sys.version_info < (3, 0):\n send_reply_v2(msg_str)\n else:\n send_reply_v3(msg_str)\n\n# Read a message from stdin and decode it. Message contains:\n# numbytes in binary + payload in ascii with quotes \n# Eg, payload xyz, then: 5000 followed by \"xyz\", ie, 050000002278797A22\n#\n# Caveats:\n# o a newline is considered one byte by JS, but when we receives it's two \"\\n\"\n# hence can't use msg size for communication protocol\n#\ndef get_message():\n global mysrc\n fullmsg = '\"\"' # create empty string with double quotes\n\n # python does not have do while loop.\n while True:\n # payload size is 4 bytes binary, read that. \n len_field = mysrc.read(4)\n # dbgwr(\"len_field val: \" + str(len_field))\n \n if not len_field:\n dbgwr(\"invalid len_field val: \" + str(len_field))\n sys.exit(0)\n\n # first byte out of 4 is the length, extract it for debug \n msg_len = struct.unpack('=I', len_field)[0]\n dbgwr(\"pid:\" + str(os.getpid()) + \" Will read \" + str(msg_len) +\n \" bytes from stdin\")\n\n # don't use msg_len for anything: sender single newline for example\n # gets converted to two chars \"\\n\". Thus if sender sends 5 :abcd\\n:\n # we get 8 including two double quotes: \" + abcd + \\ + n \"\n msg = mysrc.read(msg_len)\n if sys.version_info >= (3, 0):\n msg = msg.decode(\"utf-8\") # string from binary data\n\n # dbgwr(\"got msg: \" + msg + \" len: \" + str(len(msg)))\n # dbgwr(\"read: \" + str(msg_len) + \" bytes. msg.size:\" + str(len(msg)))\n\n if msg[1:-1] == \"tbMyEd-done-done-done\":\n break\n else:\n # remove trailing double quote and leading double quote\n fullmsg = fullmsg[:-1] + msg[1:]\n send_reply(\"tbMyEd-ack\")\n # time.sleep(1)\n\n # json.loads(str): take a json string and convert to python dictionary\n return json.loads(fullmsg or 'null')\n\n\ndef read_cmd_from_file():\n fd = open(FILE_CONTAINING_CMD_TORUN, 'r')\n cmdline = fd.read()\n # dbgwr(\"cmdline from file: :\" + cmdline + \":\")\n fd.close\n\n cmdline = cmdline.strip() # remove leading/trailing spaces\n cmdline = cmdline.strip(\"\\n\") # remove newline\n\n return cmdline\n\ndef invoke_vim(msg):\n tmpfn = \"/tmp/tbird-vim-\" + str(os.getpid())\n\n if os.path.exists(tmpfn):\n prev = tmpfn + \".prev\"\n os.rename(tmpfn, prev)\n\n fd = open(tmpfn, 'w')\n if sys.version_info < (3, 0):\n fd.write(msg)\n else:\n fd.buffer.write(msg)\n fd.close()\n\n #cmd = \"/bin/xterm -title VIMCOMPOSE -name VIMCOMPOSE -rvc -ulc -bdc -cm \" \\\n # \" -dc -bc -rw +sb -sl 5000 -ut +cn -geometry 80x64 -e /bin/vim \"\n cmd = read_cmd_from_file()\n cmd += \" \" + tmpfn\n dbgwr(\"cmd is: \" + cmd)\n\n # in python 3, change this to subprocess.run()\n p = subprocess.call(cmd, shell=True, stdout=subprocess.PIPE)\n\n dbgwr(\"invoke_vim done....\")\n\n return tmpfn\n \n\ndef main(args):\n global DEBUG, DBGFD, mysrc\n\n if DEBUG:\n DBGFD = open('/tmp/tb-myed.out', 'a+')\n dbgwr(\"===========================================================\")\n dbgwr(\"/tmp/tb-myed.out opened/created\\n\")\n sys.stderr = DBGFD\n else:\n DBGFD = -1\n\n if sys.version_info < (3, 0):\n mysrc = sys.stdin\n else:\n mysrc = sys.stdin.buffer\n\n message = get_message() # returns type string\n\n # message type is unicode, so convert to ascii, otherwise it will fail the \n # write to file if there any unicode non-ascii characters.\n message = message.encode('ascii', 'replace')\n tmpfn = invoke_vim(message)\n \n with open(tmpfn) as file:\n data = file.read()\n send_reply(data)\n\n dbgwr(\"\\n\")\n if DEBUG:\n DBGFD.close()\n\nif __name__ == \"__main__\":\n sys.exit(main(sys.argv))\n","sub_path":"backendMyEd.py","file_name":"backendMyEd.py","file_ext":"py","file_size_in_byte":5436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"358722651","text":"def moveZeroes(nums) :\n \"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"\n #双指针 j始终指向不为0的元素\n j=0\n for i in range(len(nums)):\n if nums[i]!=0:\n #j中始终为不为0的元素\n nums[j]=nums[i]\n # 这一步相当关键 把替换的位置设为0\n if i!=j:\n nums[i]=0\n j=j+1\n\n return nums\n\nif __name__ == '__main__':\n nums=[0,1,0,3,12]\n num=moveZeroes(nums)\n print(num)","sub_path":"Week_01/day1-2/283 移动0.py","file_name":"283 移动0.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"565322137","text":"from django.shortcuts import render\nfrom django.http import *\nfrom .models import Book, Author, BookInstance, Genre\nfrom django.views import generic\n\n# Create your views here.\n\n\ndef index(request):\n num_books = Book.objects.all().count()\n num_instances = BookInstance.objects.all().count()\n num_instances_available = BookInstance.objects.count()\n num_authors = Author.objects.count()\n\n return render(request, 'index.html',\n context={\n 'num_books': num_books,\n 'num_instances': num_instances,\n 'num_instances_available': num_instances_available,\n 'num_authors': num_authors,\n# 'num_visits': num_visits\n })\n\n\nclass BookListView(generic.ListView):\n model = Book\n\n\nclass BookDetailView(generic.DetailView):\n model = Book\n\n","sub_path":"catalog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"540259431","text":"# encoding: utf-8\n# Poker Game\n# ------------------------------ IMPORTS ------------------------------\nimport random\nimport time\n# from myfile import *\n# ------------------------------ DEFINITIONS ------------------------------\n\n\ndef space_check(num): # Code to reverse printing 10 on top and bottom of card\n if num == '10':\n return ''\n else:\n return ' '\n\n# ------------------------------ VARIABLES ------------------------------\ncards = ['A♦', '2♦', '3♦', '4♦', '5♦', '6♦', '7♦',\n '8♦', '9♦', 'T♦', 'J♦', 'Q♦', 'K♦',\n 'A♣', '2♣', '3♣', '4♣', '5♣', '6♣', '7♣',\n '8♣', '9♣', 'T♣', 'J♣', 'Q♣', 'K♣',\n 'A♥', '2♥', '3♥', '4♥', '5♥', '6♥', '7♥',\n '8♥', '9♥', 'T♥', 'J♥', 'Q♥', 'K♥',\n 'A♠', '2♠', '3♠', '4♠', '5♠', '6♠', '7♠',\n '8♠', '9♠', 'T♠', 'J♠', 'Q♠', 'K♠']\n\ninvalid = [] # Cards that have already been drawn\nhand = [] # Cards in user's hand\nai_hand = [] # Cards in AI's hand\ndealt = 0 # Amount of times dealt\n\n# Top card outline\nc1_top = c2_top = c3_top = c4_top = c5_top = '┌─────────┐'\n\n# Middle card outline\nc1_middle = c2_middle = c3_middle = c4_middle = c5_middle = '│'\n\n# Bottom card outline\nc1_bottom = c2_bottom = c3_bottom = c4_bottom = c5_bottom = '└─────────┘'\n\n# First card suit sections\nc1_sect1 = c1_sect2 = c1_sect3 = c1_sect4 = c1_sect5 = c1_sect6 = c1_sect7 = c1_sect8 = c1_sect9 = c1_sect10 = c1_sect11 = c1_sect12 = c1_sect13 = c1_sect14 = c1_sect15 = ' '\n\n# Second card suit sections\nc2_sect1 = c2_sect2 = c2_sect3 = c2_sect4 = c2_sect5 = c2_sect6 = c2_sect7 = c2_sect8 = c2_sect9 = c2_sect10 = c2_sect11 = c2_sect12 = c2_sect13 = c2_sect14 = c2_sect15 = ' '\n\n# Third card suit sections\nc3_sect1 = c3_sect2 = c3_sect3 = c3_sect4 = c3_sect5 = c3_sect6 = c3_sect7 = c3_sect8 = c3_sect9 = c3_sect10 = c3_sect11 = c3_sect12 = c3_sect13 = c3_sect14 = c3_sect15 = ' '\n\n# Fourth card suit sections\nc4_sect1 = c4_sect2 = c4_sect3 = c4_sect4 = c4_sect5 = c4_sect6 = c4_sect7 = c4_sect8 = c4_sect9 = c4_sect10 = c4_sect11 = c4_sect12 = c4_sect13 = c4_sect14 = c4_sect15 = ' '\n\n# Fifth card suit sections\nc5_sect1 = c5_sect2 = c5_sect3 = c5_sect4 = c5_sect5 = c5_sect6 = c5_sect7 = c5_sect8 = c5_sect9 = c5_sect10 = c5_sect11 = c5_sect12 = c5_sect13 = c5_sect14 = c5_sect15 = ' '\n\n# ------------------------------ CODE ------------------------------\nprint('Welcome to Poker!')\nprint('Choose AI difficulty:')\nprint('1) Easy')\nprint('2) Medium')\nprint('3) Hard')\nwhile True: # While user hasn't chosen a difficulty\n user_ai = input('> ')\n try:\n user_ai = int(user_ai)\n break\n except ValueError: # If input isn't a number\n print('Choose the AI difficulty number.')\nif user_ai == 1:\n ai_difficulty = 1\n print('You have selected Easy.')\nelif user_ai == 2:\n ai_difficulty = 2\n print('You have selected Medium.')\nelif user_ai == 3:\n ai_difficulty = 3\n print('You have selected Hard.')\n# time.sleep(1.5)\n\nwhile dealt < 5: # While 5 cards haven't been dealt to the user and AI\n card_gen = random.randint(0, 51) # Generate a random card for the user\n ai_card_gen = random.randint(0, 51) # Generate a random card for the AI\n while True:\n if card_gen in invalid:\n card_gen = random.randint(0, 51)\n elif ai_card_gen in invalid: # If generated card has already been drawn\n ai_card_gen = random.randint(0, 51)\n elif card_gen == ai_card_gen: # If user and AI draw the same card\n card_gen = random.randint(0, 51)\n ai_card_gen = random.randint(0, 51)\n else:\n break\n invalid.append(card_gen) # Add user drawn card to invalid list\n invalid.append(ai_card_gen) # Add AI drwan card to invalid list\n hand.append(cards[card_gen]) # Add drawn card to user's hand\n ai_hand.append(cards[ai_card_gen]) # Add drawn card to AI's hand\n dealt += 1\nhand.sort() # Organise the user's cards\n\n# Assigning card value and suit from user's cards\nc1_num = hand[0][0]\nc1_suit = hand[0][1]\nc2_num = hand[1][0]\nc2_suit = hand[1][1]\nc3_num = hand[2][0]\nc3_suit = hand[2][1]\nc4_num = hand[3][0]\nc4_suit = hand[3][1]\nc5_num = hand[4][0]\nc5_suit = hand[4][1]\n\n# Setting T card value to 10\nif c1_num == 'T':\n c1_num = '10'\nif c2_num == 'T':\n c2_num = '10'\nif c3_num == 'T':\n c3_num = '10'\nif c4_num == 'T':\n c4_num = '10'\nif c5_num == 'T':\n c5_num = '10'\n\n# Setting card color to red if suit is diamonds or hearts\nif c1_suit == '♦' or c1_suit == '♥': # If first card is diamonds or hearts\n c1_suit = '\\033[0;31m' + c1_suit + '\\033[0;0m'\n c1_top = '\\033[0;31m' + c1_top + '\\033[0;0m'\n c1_middle = '\\033[0;31m' + c1_middle + '\\033[0;0m'\n c1_bottom = '\\033[0;31m' + c1_bottom + '\\033[0;0m'\nif c2_suit == '♦' or c2_suit == '♥': # If second card is diamonds or hearts\n c2_suit = '\\033[0;31m' + c2_suit + '\\033[0;0m'\n c2_top = '\\033[0;31m' + c1_top + '\\033[0;0m'\n c2_middle = '\\033[0;31m' + c1_middle + '\\033[0;0m'\n c2_bottom = '\\033[0;31m' + c1_bottom + '\\033[0;0m'\nif c3_suit == '♦' or c3_suit == '♥': # If third card is diamonds or hearts\n c3_suit = '\\033[0;31m' + c3_suit + '\\033[0;0m'\n c3_top = '\\033[0;31m' + c1_top + '\\033[0;0m'\n c3_middle = '\\033[0;31m' + c1_middle + '\\033[0;0m'\n c3_bottom = '\\033[0;31m' + c1_bottom + '\\033[0;0m'\nif c4_suit == '♦' or c4_suit == '♥': # If fourth card is diamonds or hearts\n c4_suit = '\\033[0;31m' + c4_suit + '\\033[0;0m'\n c4_top = '\\033[0;31m' + c1_top + '\\033[0;0m'\n c4_middle = '\\033[0;31m' + c1_middle + '\\033[0;0m'\n c4_bottom = '\\033[0;31m' + c1_bottom + '\\033[0;0m'\nif c5_suit == '♦' or c5_suit == '♥': # If fifth card is diamonds or hearts\n c5_suit = '\\033[0;31m' + c5_suit + '\\033[0;0m'\n c5_top = '\\033[0;31m' + c1_top + '\\033[0;0m'\n c5_middle = '\\033[0;31m' + c1_middle + '\\033[0;0m'\n c5_bottom = '\\033[0;31m' + c1_bottom + '\\033[0;0m'\n\n# Setting card suit sections\n# First card\nif c1_num == 'A': # If card value is Ace\n c1_sect8 = c1_suit\nelif c1_num == '2': # If card value is 2\n c1_sect2 = c1_sect14 = c1_suit\nelif c1_num == '3': # If card value is 3\n c1_sect2 = c1_sect8 = c1_sect14 = c1_suit\nelif c1_num == '4': # If card value is 4\n c1_sect1 = c1_sect3 = c1_sect13 = c1_sect15 = c1_suit\nelif c1_num == '5': # If card value is 5\n c1_sect1 = c1_sect3 = c1_sect8 = c1_sect13 = c1_sect15 = c1_suit\nelif c1_num == '6': # If card value is 6\n c1_sect1 = c1_sect3 = c1_sect7 = c1_sect9 = c1_sect13 = c1_sect15 = c1_suit\nelif c1_num == '7': # If card value is 7\n c1_sect1 = c1_sect3 = c1_sect5 = c1_sect7 = c1_sect9 = c1_sect13 = c1_sect15 = c1_suit\nelif c1_num == '8': # If card value is 8\n c1_sect1 = c1_sect3 = c1_sect5 = c1_sect7 = c1_sect9 = c1_sect11 = c1_sect13 = c1_sect15 = c1_suit\nelif c1_num == '9': # If card value is 9\n c1_sect1 = c1_sect2 = c1_sect3 = c1_sect7 = c1_sect8 = c1_sect9 = c1_sect13 = c1_sect14 = c1_sect15 = c1_suit\nelif c1_num == '10': # If card value is 10\n c1_sect1 = c1_sect3 = c1_sect4 = c1_sect6 = c1_sect7 = c1_sect9 = c1_sect10 = c1_sect12 = c1_sect13 = c1_sect15 = c1_suit\nelif c1_num == 'J': # If card value is Jack\n c1_sect8 = c1_suit\nelif c1_num == 'Q': # If card value is Queen\n c1_sect8 = c1_suit\nelif c1_num == 'K': # If card value is King\n c1_sect8 = c1_suit\n\n# Second card\nif c2_num == 'A': # If card value is Ace\n c2_sect8 = c2_suit\nelif c2_num == '2': # If card value is 2\n c2_sect2 = c2_sect14 = c2_suit\nelif c2_num == '3': # If card value is 3\n c2_sect2 = c2_sect8 = c2_sect14 = c2_suit\nelif c2_num == '4': # If card value is 4\n c2_sect1 = c2_sect3 = c2_sect13 = c2_sect15 = c2_suit\nelif c2_num == '5': # If card value is 5\n c2_sect1 = c2_sect3 = c2_sect8 = c2_sect13 = c2_sect15 = c2_suit\nelif c2_num == '6': # If card value is 6\n c2_sect1 = c2_sect3 = c2_sect7 = c2_sect9 = c2_sect13 = c2_sect15 = c2_suit\nelif c2_num == '7': # If card value is 7\n c2_sect1 = c2_sect3 = c2_sect5 = c2_sect7 = c2_sect9 = c2_sect13 = c2_sect15 = c2_suit\nelif c2_num == '8': # If card value is 8\n c2_sect1 = c2_sect3 = c2_sect5 = c2_sect7 = c2_sect9 = c2_sect11 = c2_sect13 = c2_sect15 = c2_suit\nelif c2_num == '9': # If card value is 9\n c2_sect1 = c2_sect2 = c2_sect3 = c2_sect7 = c2_sect8 = c2_sect9 = c2_sect13 = c2_sect14 = c2_sect15 = c2_suit\nelif c2_num == '10': # If card value is 10\n c2_sect1 = c2_sect3 = c2_sect4 = c2_sect6 = c2_sect7 = c2_sect9 = c2_sect10 = c2_sect12 = c2_sect13 = c2_sect15 = c2_suit\nelif c2_num == 'J': # If card value is Jack\n c2_sect8 = c2_suit\nelif c2_num == 'Q': # If card value is Queen\n c2_sect8 = c2_suit\nelif c2_num == 'K': # If card value is King\n c2_sect8 = c2_suit\n\n# Third card\nif c3_num == 'A': # If card value is Ace\n c3_sect8 = c3_suit\nelif c3_num == '2': # If card value is 2\n c3_sect2 = c3_sect14 = c3_suit\nelif c3_num == '3': # If card value is 3\n c3_sect2 = c3_sect8 = c3_sect14 = c3_suit\nelif c3_num == '4': # If card value is 4\n c3_sect1 = c3_sect3 = c3_sect13 = c3_sect15 = c3_suit\nelif c3_num == '5': # If card value is 5\n c3_sect1 = c3_sect3 = c3_sect8 = c3_sect13 = c3_sect15 = c3_suit\nelif c3_num == '6': # If card value is 6\n c3_sect1 = c3_sect3 = c3_sect7 = c3_sect9 = c3_sect13 = c3_sect15 = c3_suit\nelif c3_num == '7': # If card value is 7\n c3_sect1 = c3_sect3 = c3_sect5 = c3_sect7 = c3_sect9 = c3_sect13 = c3_sect15 = c3_suit\nelif c3_num == '8': # If card value is 8\n c3_sect1 = c3_sect3 = c3_sect5 = c3_sect7 = c3_sect9 = c3_sect11 = c3_sect13 = c3_sect15 = c3_suit\nelif c3_num == '9': # If card value is 9\n c3_sect1 = c3_sect2 = c3_sect3 = c3_sect7 = c3_sect8 = c3_sect9 = c3_sect13 = c3_sect14 = c3_sect15 = c3_suit\nelif c3_num == '10': # If card value is 10\n c3_sect1 = c3_sect3 = c3_sect4 = c3_sect6 = c3_sect7 = c3_sect9 = c3_sect10 = c3_sect12 = c3_sect13 = c3_sect15 = c3_suit\nelif c3_num == 'J': # If card value is Jack\n c3_sect8 = c3_suit\nelif c3_num == 'Q': # If card value is Queen\n c3_sect8 = c3_suit\nelif c3_num == 'K': # If card value is King\n c3_sect8 = c3_suit\n\n# Fourth card\nif c4_num == 'A': # If card value is Ace\n c4_sect8 = c4_suit\nelif c4_num == '2': # If card value is 2\n c4_sect2 = c4_sect14 = c4_suit\nelif c4_num == '3': # If card value is 3\n c4_sect2 = c4_sect8 = c4_sect14 = c4_suit\nelif c4_num == '4': # If card value is 4\n c4_sect1 = c4_sect3 = c4_sect13 = c4_sect15 = c4_suit\nelif c4_num == '5': # If card value is 5\n c4_sect1 = c4_sect3 = c4_sect8 = c4_sect13 = c4_sect15 = c4_suit\nelif c4_num == '6': # If card value is 6\n c4_sect1 = c4_sect3 = c4_sect7 = c4_sect9 = c4_sect13 = c4_sect15 = c4_suit\nelif c4_num == '7': # If card value is 7\n c4_sect1 = c4_sect3 = c4_sect5 = c4_sect7 = c4_sect9 = c4_sect13 = c4_sect15 = c4_suit\nelif c4_num == '8': # If card value is 8\n c4_sect1 = c4_sect3 = c4_sect5 = c4_sect7 = c4_sect9 = c4_sect11 = c4_sect13 = c4_sect15 = c4_suit\nelif c4_num == '9': # If card value is 9\n c4_sect1 = c4_sect2 = c4_sect3 = c4_sect7 = c4_sect8 = c4_sect9 = c4_sect13 = c4_sect14 = c4_sect15 = c4_suit\nelif c4_num == '10': # If card value is 10\n c4_sect1 = c4_sect3 = c4_sect4 = c4_sect6 = c4_sect7 = c4_sect9 = c4_sect10 = c4_sect12 = c4_sect13 = c4_sect15 = c4_suit\nelif c4_num == 'J': # If card value is Jack\n c4_sect8 = c4_suit\nelif c4_num == 'Q': # If card value is Queen\n c4_sect8 = c4_suit\nelif c4_num == 'K': # If card value is King\n c4_sect8 = c4_suit\n\n# Fifth card\nif c5_num == 'A': # If card value is Ace\n c5_sect8 = c5_suit\nelif c5_num == '2': # If card value is 2\n c5_sect2 = c5_sect14 = c5_suit\nelif c5_num == '3': # If card value is 3\n c5_sect2 = c5_sect8 = c5_sect14 = c5_suit\nelif c5_num == '4': # If card value is 4\n c5_sect1 = c5_sect3 = c5_sect13 = c5_sect15 = c5_suit\nelif c5_num == '5': # If card value is 5\n c5_sect1 = c5_sect3 = c5_sect8 = c5_sect13 = c5_sect15 = c5_suit\nelif c5_num == '6': # If card value is 6\n c5_sect1 = c5_sect3 = c5_sect7 = c5_sect9 = c5_sect13 = c5_sect15 = c5_suit\nelif c5_num == '7': # If card value is 7\n c5_sect1 = c5_sect3 = c5_sect5 = c5_sect7 = c5_sect9 = c5_sect13 = c5_sect15 = c5_suit\nelif c5_num == '8': # If card value is 8\n c5_sect1 = c5_sect3 = c5_sect5 = c5_sect7 = c5_sect9 = c5_sect11 = c5_sect13 = c5_sect15 = c5_suit\nelif c5_num == '9': # If card value is 9\n c5_sect1 = c5_sect2 = c5_sect3 = c5_sect7 = c5_sect8 = c5_sect9 = c5_sect13 = c5_sect14 = c5_sect15 = c5_suit\nelif c5_num == '10': # If card value is 10\n c5_sect1 = c5_sect3 = c5_sect4 = c5_sect6 = c5_sect7 = c5_sect9 = c5_sect10 = c5_sect12 = c5_sect13 = c5_sect15 = c5_suit\nelif c5_num == 'J': # If card value is Jack\n c5_sect8 = c5_suit\nelif c5_num == 'Q': # If card value is Queen\n c5_sect8 = c5_suit\nelif c5_num == 'K': # If card value is King\n c5_sect8 = c5_suit\n\nprint('Your hand:')\n\n# Card numbers\nprint(' 1 2 3 4 5 ')\nprint('{} {} {} {} {}'.format(c1_top, c2_top, c3_top, c4_top, c5_top)) # Top card outline\nprint('{}{}{} {} {}{}{} {} {}{}{} {} {}{}{} {} {}{}{} {}'.format(c1_middle, c1_num, space_check(c1_num), c1_middle, c2_middle, c2_num, space_check(c2_num), c2_middle, c3_middle, c3_num, space_check(c3_num), c3_middle, c4_middle, c4_num, space_check(c4_num), c4_middle, c5_middle, c5_num, space_check(c5_num), c5_middle)) # Top card numbers\nprint('{} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}'.format(c1_middle, c1_sect1, c1_sect2, c1_sect3, c1_middle, c2_middle, c2_sect1, c2_sect2, c2_sect3, c2_middle, c3_middle, c3_sect1, c3_sect2, c3_sect3, c3_middle, c4_middle, c4_sect1, c4_sect2, c4_sect3, c4_middle, c5_middle, c5_sect1, c5_sect2, c5_sect3, c5_middle)) # Card suit sections\nprint('{} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}'.format(c1_middle, c1_sect4, c1_sect5, c1_sect6, c1_middle, c2_middle, c2_sect4, c2_sect5, c2_sect6, c2_middle, c3_middle, c3_sect4, c3_sect5, c3_sect6, c3_middle, c4_middle, c4_sect4, c4_sect5, c4_sect6, c4_middle, c5_middle, c5_sect4, c5_sect5, c5_sect6, c5_middle)) # Card suit sections\nprint('{} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}'.format(c1_middle, c1_sect7, c1_sect8, c1_sect9, c1_middle, c2_middle, c2_sect7, c2_sect8, c2_sect9, c2_middle, c3_middle, c3_sect7, c3_sect8, c3_sect9, c3_middle, c4_middle, c4_sect7, c4_sect8, c4_sect9, c4_middle, c5_middle, c5_sect7, c5_sect8, c5_sect9, c5_middle)) # Card suit sections\nprint('{} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}'.format(c1_middle, c1_sect10, c1_sect11, c1_sect12, c1_middle, c2_middle, c2_sect10, c2_sect11, c2_sect12, c2_middle, c3_middle, c3_sect10, c3_sect11, c3_sect12, c3_middle, c4_middle, c4_sect10, c4_sect11, c4_sect12, c4_middle, c5_middle, c5_sect10, c5_sect11, c5_sect12, c5_middle)) # Card suit sections\nprint('{} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}'.format(c1_middle, c1_sect13, c1_sect14, c1_sect15, c1_middle, c2_middle, c2_sect13, c2_sect14, c2_sect15, c2_middle, c3_middle, c3_sect13, c3_sect14, c3_sect15, c3_middle, c4_middle, c4_sect13, c4_sect14, c4_sect15, c4_middle, c5_middle, c5_sect13, c5_sect14, c5_sect15, c5_middle)) # Card suit sections\nprint('{} {}{}{} {} {}{}{} {} {}{}{} {} {}{}{} {} {}{}{}'.format(c1_middle, space_check(c1_num), c1_num, c1_middle, c2_middle, space_check(c2_num), c2_num, c2_middle, c3_middle, space_check(c3_num), c3_num, c3_middle, c4_middle, space_check(c4_num), c4_num, c4_middle, c5_middle, space_check(c5_num), c5_num, c5_middle)) # Bottom card numbers\nprint('{} {} {} {} {}'.format(c1_bottom, c2_bottom, c3_bottom, c4_bottom, c5_bottom)) # Bottom card outline\nprint('Combinations:')\nprint('a) High Card: Highest value card.')\nprint('b) One Pair: Two cards of the same value.')\nprint('c) Two Pairs: Two different pairs.')\nprint('d) Three of a Kind: Three cards of the same value.')\nprint('e) Straight: All cards are consecutive values.')\nprint('f) Flush: All cards of the same suit.')\nprint('g) Full House: Three of a kind and a pair.')\nprint('h) Four of a Kind: Four cards of the same value.')\nprint('i) Straight Flush: All cards are consecutive values of same suit.')\nprint('j) Royal Flush: Ten, Jack, Queen, King, Ace, in same suit')\nprint()\nprint('Select cards and combination you would like to use. E.g \\'1,3,4,5,h\\'')\ntrim = ','\nselected_cards = 0\ncard1 = card2 = card3 = card4 = card5 = ''\nwhile True: # While the correct cards and combination haven't been chosen\n while True: # While selection can't be converted into an integer\n user_cards = input('> ')\n selection = list(user_cards)\n while trim in selection:\n selection.remove(trim)\n selection_combination = selection[-1:][0]\n selection_cards = selection[:-1]\n try: # Trying to convert list into integer\n selection_cards = [int(x) for x in selection_cards]\n break\n except ValueError:\n print('One or more of your selection isn\\'t a card!')\n user_cards = input('> ')\n for i in range(len(selection_cards)):\n if selection_cards[i] == 1:\n selected_cards += 1\n elif selection_cards[i] == 2:\n selected_cards += 1\n elif selection_cards[i] == 3:\n selected_cards += 1\n elif selection_cards[i] == 4:\n selected_cards += 1\n elif selection_cards[i] == 5:\n selected_cards += 1\n if selected_cards == 1:\n if selection_combination != 'a':\n print('You didn\\'t select enough cards to use this combination!')\n selected_cards = 0\n else:\n card1 = hand[selection_cards[0]-1]\n break\n elif selected_cards == 2:\n if selection_combination != 'b':\n print('You didn\\'t select enough cards to use this combination!')\n selected_cards = 0\n else:\n card1 = hand[selection_cards[0]-1]\n card2 = hand[selection_cards[1]-1]\n break\n elif selected_cards == 3:\n if selection_combination != 'd':\n print('You didn\\'t select enough cards to use this combination!')\n selected_cards = 0\n else:\n card1 = hand[selection_cards[0]-1]\n card2 = hand[selection_cards[1]-1]\n card3 = hand[selection_cards[2]-1]\n break\n elif selected_cards == 4:\n if selection_combination != 'c' or selection_combination != 'h':\n print('You didn\\'t select enough cards to use this combination!')\n selected_cards = 0\n else:\n card1 = hand[selection_cards[0]-1]\n card2 = hand[selection_cards[1]-1]\n card3 = hand[selection_cards[2]-1]\n card4 = hand[selection_cards[3]-1]\n break\n elif selected_cards == 5:\n if selection_combination != 'e' or selection_combination != 'f' or selection_combination != 'g' or selection_combination != 'i' or selection_combination != 'j':\n print('You didn\\'t select enough cards to use this combination!')\n selected_cards = 0\n else:\n card1 = hand[selection_cards[0]-1]\n card2 = hand[selection_cards[1]-1]\n card3 = hand[selection_cards[2]-1]\n card4 = hand[selection_cards[3]-1]\n card5 = hand[selection_cards[4]-1]\n break\nprint(card1)\nprint(card2)\nprint(card3)\nprint(card4)\nprint(card5)\n","sub_path":"poker.py","file_name":"poker.py","file_ext":"py","file_size_in_byte":19790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"41456131","text":"class Node:\n\n def __init__(self, value = None, next_node = None):\n self.value = value\n self.next_node = next_node\n\n def get_node_value(self):\n return self.value\n\n def get_next_node(self):\n return self.next_node\n\n def set_next_node(self, next_node_2):\n self.next_node = next_node_2\n\n# Linked LIst\nclass LinkedList:\n\n def __init__(self):\n self.head = None\n self.tail = None\n\n def add_to_tail(self, value):\n \n new_node = Node(value, None)\n\n if not self.head:\n self.head = new_node\n self.tail = new_node\n else:\n self.tail.set_next_node(new_node)\n self.tail = new_node\n\n def remove_head(self):\n\n if not self.head:\n return None\n\n if not self.head.get_next_node():\n head = self.head\n self.head = None\n self.tail = None\n return head.get_node_value()\n\n value = self.head.get_node_value()\n\n self.head = self.head.get_node_value()\n \n return value\n\n def remove_tail(self):\n if not self.head:\n return None\n\n if self.head is self.tail:\n value = self.head.get_node_value()\n self.head = None\n self.tail = None\n return value\n\n current = self.head\n\n while current.get_next_node() is not self.tail:\n current = current.get_next_node()\n\n value = self.tail.get_node_value()\n self.tail = current\n return value\n\n def contains(self, value):\n if not self.head:\n return False\n\n current = self.head\n\n while current:\n if current.get_node_value() == value:\n return True\n\n current = current.get_next_node()\n\n return False\n\n def get_max(self):\n if not self.head:\n return None\n\n max_value = self.head.get_node_value()\n\n current = self.head.get_node_value()\n\n while current:\n if current.get_node_value() > max_value:\n current = current.get_next_node()\n return max_value \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"singly_linked_list/singly_linked_list.py","file_name":"singly_linked_list.py","file_ext":"py","file_size_in_byte":2163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"249753152","text":"import json\nimport os\nimport warnings\n\nimport pandas as pd\n\nfrom rdt import transformers\n\nTRANSFORMERS = {\n 'datetime': 'DTTransformer',\n 'categorical': 'CatTransformer',\n 'number': 'NumberTransformer'\n}\n\n\nDEPRECATION_MESSAGE = (\n 'Usage of the argument `missing` in the method `{}` is soon to be deprecated '\n 'and should be used at class-level. It will stop working after release v0.2.0.'\n)\n\n\nclass HyperTransformer:\n \"\"\"Multitable transformer.\n\n Arguments:\n metadata(str or dict): Path to the meta.json file or its parsed contents.\n dir_name(str): Path to the root directory of meta.json.\n missing (bool): Wheter or not to handle missing values before transforming data.\n\n The main propouse of the HyperTransformer class is to easily manage transformations\n for a whole dataset.\n \"\"\"\n\n @staticmethod\n def get_class(class_name):\n \"\"\"Get class object of transformer from its class name.\n\n Args:\n class_name(str): Name of the transform.\n\n Returns:\n BaseTransformer\n \"\"\"\n return getattr(transformers, class_name)\n\n @staticmethod\n def _get_pii_fields(table_metadata):\n \"\"\"Return a list of fields marked as sensitive information.\n\n Args:\n table_metadata (dict): Metadata corresponding to a table.\n\n Returns:\n list[dict]: List of metadata for each field marked as `pii`.\n \"\"\"\n return [field for field in table_metadata['fields'] if field.get('pii')]\n\n @classmethod\n def _anonymize_table(cls, table_data, pii_fields):\n \"\"\"Anonymize in `table_data` the fields in `pii_fields`.\n\n Args:\n table_data (pandas.DataFrame): Original dataframe/table.\n pii_fields (list[dict]): Metadata for the fields to transform.\n\n Result:\n pandas.DataFrame: Anonymized table.\n \"\"\"\n for pii_field in pii_fields:\n field_name = pii_field['name']\n transformer = cls.get_class(TRANSFORMERS['categorical'])(pii_field)\n table_data[field_name] = transformer.anonymize_column(table_data)\n\n return table_data\n\n def _get_tables(self, base_dir):\n \"\"\"Load the contents of meta_file and the corresponding data.\n\n If fields containing Personally Identifiable Information are detected in the metadata\n they are anonymized before asign them into `table_dict`.\n\n Args:\n base_dir(str): Root folder of the dataset files.\n\n Returns:\n dict: Mapping str -> tuple(pandas.DataFrame, dict)\n \"\"\"\n table_dict = {}\n\n for table in self.metadata['tables']:\n if table['use']:\n relative_path = os.path.join(base_dir, self.metadata['path'], table['path'])\n data_table = pd.read_csv(relative_path)\n pii_fields = self._get_pii_fields(table)\n data_table = self._anonymize_table(data_table, pii_fields)\n\n table_dict[table['name']] = (data_table, table)\n\n return table_dict\n\n def _get_transformers(self):\n \"\"\"Load the contents of meta_file and extract information about the transformers.\n\n Returns:\n dict: tuple(str, str) -> Transformer.\n \"\"\"\n transformer_dict = {}\n\n for table in self.metadata['tables']:\n table_name = table['name']\n\n for field in table['fields']:\n transformer_type = field.get('type')\n if transformer_type:\n col_name = field['name']\n transformer_dict[(table_name, col_name)] = transformer_type\n\n return transformer_dict\n\n def __init__(self, metadata, dir_name=None, missing=True):\n\n self.transformers = {} # key=(table_name, col_name) val=transformer\n\n if isinstance(metadata, str):\n dir_name = os.path.dirname(metadata)\n with open(metadata, 'r') as f:\n self.metadata = json.load(f)\n\n elif isinstance(metadata, dict):\n self.metadata = metadata\n if dir_name is None:\n raise ValueError('dir_name is required when metadata is a dict.')\n\n else:\n raise ValueError('Incorrect type for metadata: It can only be either dict or str.')\n\n self.table_dict = self._get_tables(dir_name)\n self.transformer_dict = self._get_transformers()\n self.missing = missing\n\n def _fit_transform_column(self, table, metadata, transformer_name, table_name):\n \"\"\"Transform a column from table using transformer and given parameters.\n\n Args:\n table (pandas.DataFrame): Dataframe containing column to transform.\n metadata (dict): Metadata for given column.\n transformer_name (str): Name of transformer to use on column.\n table_name (str): Name of table in original dataset.\n\n Returns:\n pandas.DataFrame: Dataframe containing the transformed column. If self.missing=True,\n it will contain a second column containing 0 and 1 marking if that\n value was originally null or not.\n \"\"\"\n\n column_name = metadata['name']\n content = {}\n columns = []\n\n if self.missing and table[column_name].isnull().any():\n null_transformer = transformers.NullTransformer(metadata)\n clean_column = null_transformer.fit_transform(table[column_name])\n null_name = '?' + column_name\n columns.append(null_name)\n content[null_name] = clean_column[null_name].values\n table[column_name] = clean_column[column_name]\n\n transformer_class = self.get_class(transformer_name)\n transformer = transformer_class(metadata)\n\n self.transformers[(table_name, column_name)] = transformer\n content[column_name] = transformer.fit_transform(table)[column_name].values\n\n columns = [column_name] + columns\n return pd.DataFrame(content, columns=columns)\n\n def _reverse_transform_column(self, table, metadata, table_name):\n \"\"\"Reverses the transformtion on a column from table using the given parameters.\n\n Args:\n table (pandas.DataFrame): Dataframe containing column to transform.\n metadata (dict): Metadata for given column.\n table_name (str): Name of table in original dataset.\n\n Returns:\n pandas.DataFrame: Dataframe containing the transformed column. If self.missing=True,\n it will contain a second column containing 0 and 1 marking if that\n value was originally null or not.\n It will return None in the case the column is not in the table.\n \"\"\"\n\n column_name = metadata['name']\n\n if column_name not in table:\n return\n\n null_name = '?' + column_name\n content = pd.DataFrame(columns=[column_name], index=table.index)\n transformer = self.transformers[(table_name, column_name)]\n content[column_name] = transformer.reverse_transform(table[column_name].to_frame())\n\n if self.missing and null_name in table[column_name]:\n content[null_name] = table.pop(null_name)\n null_transformer = transformers.NullTransformer(metadata)\n content[column_name] = null_transformer.reverse_transform(content)\n\n return content\n\n def fit_transform_table(\n self, table, table_meta, transformer_dict=None, transformer_list=None, missing=None):\n \"\"\"Create, apply and store the specified transformers for `table`.\n\n Args:\n table(pandas.DataFrame): Contents of the table to be transformed.\n\n table_meta(dict): Metadata for the given table.\n\n transformer_dict(dict): Mapping `tuple(str, str)` -> `str` where the tuple in the\n keys represent the (table_name, column_name) and the value\n the name of the assigned transformer.\n\n transformer_list(list): List of transformers to use. Overrides the transformers in\n the meta_file.\n\n missing(bool): Wheter or not use NullTransformer to handle missing values.\n\n Returns:\n pandas.DataFrame: Transformed table.\n \"\"\"\n\n if missing is None:\n missing = self.missing\n\n else:\n self.missing = missing\n warnings.warn(DEPRECATION_MESSAGE.format('fit_transform_table'), DeprecationWarning)\n\n result = pd.DataFrame()\n table_name = table_meta['name']\n\n for field in table_meta['fields']:\n col_name = field['name']\n\n if transformer_list:\n for transformer_name in transformer_list:\n if field['type'] == self.get_class(transformer_name).type:\n transformed = self._fit_transform_column(\n table, field, transformer_name, table_name)\n\n result = pd.concat([result, transformed], axis=1)\n\n elif (table_name, col_name) in transformer_dict:\n transformer_name = TRANSFORMERS[transformer_dict[(table_name, col_name)]]\n transformed = self._fit_transform_column(\n table, field, transformer_name, table_name)\n\n result = pd.concat([result, transformed], axis=1)\n\n return result\n\n def transform_table(self, table, table_meta, missing=None):\n \"\"\"Apply the stored transformers to `table`.\n\n Args:\n table(pandas.DataFrame): Contents of the table to be transformed.\n\n table_meta(dict): Metadata for the given table.\n\n missing(bool): Wheter or not use NullTransformer to handle missing values.\n\n Returns:\n pandas.DataFrame: Transformed table.\n \"\"\"\n\n if missing is None:\n missing = self.missing\n\n else:\n self.missing = missing\n warnings.warn(DEPRECATION_MESSAGE.format('transform_table'), DeprecationWarning)\n\n content = {}\n columns = []\n table_name = table_meta['name']\n\n for field in table_meta['fields']:\n column_name = field['name']\n\n if missing and table[column_name].isnull().any():\n null_transformer = transformers.NullTransformer(field)\n clean_column = null_transformer.fit_transform(table[column_name])\n null_name = '?' + column_name\n columns.append(null_name)\n content[null_name] = clean_column[null_name].values\n column = clean_column[column_name]\n\n else:\n column = table[column_name].to_frame()\n\n transformer = self.transformers[(table_name, column_name)]\n content[column_name] = transformer.transform(column)[column_name].values\n columns.append(column_name)\n\n return pd.DataFrame(content, columns=columns)\n\n def reverse_transform_table(self, table, table_meta, missing=None):\n \"\"\"Transform a `table` back to its original format.\n\n Args:\n table(pandas.DataFrame): Contents of the table to be transformed.\n\n table_meta(dict): Metadata for the given table.\n\n missing(bool): Wheter or not use NullTransformer to handle missing values.\n\n Returns:\n pandas.DataFrame: Table in original format.\n \"\"\"\n\n if missing is None:\n missing = self.missing\n\n else:\n self.missing = missing\n warnings.warn(\n DEPRECATION_MESSAGE.format('reverse_transform_table'), DeprecationWarning)\n\n result = pd.DataFrame(index=table.index)\n table_name = table_meta['name']\n\n for field in table_meta['fields']:\n new_column = self._reverse_transform_column(table, field, table_name)\n if new_column is not None:\n result[field['name']] = new_column\n\n return result\n\n def fit_transform(\n self, tables=None, transformer_dict=None, transformer_list=None, missing=None):\n \"\"\"Create, apply and store the specified transformers for the given tables.\n\n Args:\n tables(dict): Mapping of table names to `tuple` where each tuple is on the form\n (`pandas.DataFrame`, `dict`). The `DataFrame` contains the table data\n and the `dict` the corresponding meta information.\n If not specified, the tables will be retrieved using the meta_file.\n\n transformer_dict(dict): Mapping `tuple(str, str)` -> `str` where the tuple is\n (table_name, column_name).\n\n transformer_list(list): List of transformers to use. Overrides the transformers in\n the meta_file.\n\n missing(bool): Wheter or not use NullTransformer to handle missing values.\n\n Returns:\n dict: Map from `str` (table_names) to `pandas.DataFrame` (transformed data).\n \"\"\"\n\n if missing is None:\n missing = self.missing\n\n else:\n self.missing = missing\n warnings.warn(DEPRECATION_MESSAGE.format('fit_transform'), DeprecationWarning)\n\n transformed = {}\n\n if tables is None:\n tables = self.table_dict\n\n if transformer_dict is None and transformer_list is None:\n transformer_dict = self.transformer_dict\n\n for table_name in tables:\n table, table_meta = tables[table_name]\n transformed_table = self.fit_transform_table(\n table, table_meta, transformer_dict, transformer_list)\n\n transformed[table_name] = transformed_table\n\n return transformed\n\n def transform(self, tables, table_metas=None, missing=None):\n \"\"\"Apply all the saved transformers to `tables`.\n\n Args:\n tables(dict): mapping of table names to `tuple` where each tuple is on the form\n (`pandas.DataFrame`, `dict`). The `DataFrame` contains the table data\n and the `dict` the corresponding meta information.\n If not specified, the tables will be retrieved using the meta_file.\n\n table_metas(dict): Full metadata file for the dataset.\n\n missing(bool): Wheter or not use NullTransformer to handle missing values.\n\n Returns:\n dict: Map from `str` (table_names) to `pandas.DataFrame` (transformed data).\n \"\"\"\n\n if missing is None:\n missing = self.missing\n\n else:\n self.missing = missing\n warnings.warn(DEPRECATION_MESSAGE.format('transform'), DeprecationWarning)\n\n transformed = {}\n\n for table_name in tables:\n table = tables[table_name]\n\n if table_metas is None:\n table_meta = self.table_dict[table_name][1]\n else:\n table_meta = table_metas[table_name]\n\n transformed[table_name] = self.transform_table(table, table_meta)\n\n return transformed\n\n def reverse_transform(self, tables, table_metas=None, missing=None):\n \"\"\"Transform data back to its original format.\n\n Args:\n tables(dict): mapping of table names to `tuple` where each tuple is on the form\n (`pandas.DataFrame`, `dict`). The `DataFrame` contains the transformed\n data and the `dict` the corresponding meta information.\n If not specified, the tables will be retrieved using the meta_file.\n\n table_metas(dict): Full metadata file for the dataset.\n\n missing(bool): Wheter or not use NullTransformer to handle missing values.\n\n Returns:\n dict: Map from `str` (table_names) to `pandas.DataFrame` (transformed data).\n \"\"\"\n\n if missing is None:\n missing = self.missing\n\n else:\n self.missing = missing\n warnings.warn(DEPRECATION_MESSAGE.format('reverse_transform'), DeprecationWarning)\n\n reverse = {}\n\n for table_name in tables:\n table = tables[table_name]\n if table_metas is None:\n table_meta = self.table_dict[table_name][1]\n else:\n table_meta = table_metas[table_name]\n\n reverse[table_name] = self.reverse_transform_table(table, table_meta)\n\n return reverse\n","sub_path":"rdt/hyper_transformer.py","file_name":"hyper_transformer.py","file_ext":"py","file_size_in_byte":16720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"417720677","text":"from queue import Queue\nimport threading\nimport time\n\n\nclass Facturador:\n\n def __init__(self, sistema):\n self.sistema = sistema\n self.queue = Queue(maxsize=0)\n self.cantidadDeHilos = 2\n self.hilos = []\n self.facturas = []\n self.lock = threading.Lock()\n\n def facturar(self, pedidos):\n for i in range(self.cantidadDeHilos):\n hilo = threading.Thread(target=self.facturarPedido, args=(pedidos, ), daemon=True)\n hilo.start()\n self.hilos.append(hilo)\n\n for hilo in self.hilos:\n hilo.join()\n\n self.terminarFacturacion()\n\n def facturarPedido(self, pedidos):\n while len(pedidos) > 1:\n self.lock.acquire()\n try:\n pedido = pedidos.pop()\n self.facturas.append(pedido.facturar(self.sistema.getUltimoNumerodeFactura()))\n except:\n print('Error')\n finally:\n self.lock.release()\n\n\n def terminarFacturacion(self):\n self.sistema.facturacionTerminada(self.facturas)\n","sub_path":"src/entidades/Facturador.py","file_name":"Facturador.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"176547085","text":"#!/usr/bin/python3\n# -*- encoding: utf-8 -*-\n\n\"\"\"The primes 3, 7, 109, and 673, are quite remarkable.\nBy taking any two primes and concatenating them in any order the result will\nalways be prime. For example, taking 7 and 109, both 7109 and 1097 are prime.\nThe sum of these four primes, 792, represents the lowest sum for a set of four\nprimes with this property.\n\nFind the lowest sum for a set of five primes for which any two primes\nconcatenate to produce another prime.\"\"\"\n\nfrom time import clock\nfrom eulerlib import isPrime\nfrom eulerlib import generatePrimeList\n\ndef checkCondition(num1, num2):\n \"\"\"Checks if the concatenation of two prime numbers results in another\n prime number in both ways\"\"\"\n concat = int(str(num1) + str(num2))\n reverse = int(str(concat)[::-1])\n\n if isPrime(concat) and isPrime(reverse):\n return True\n else:\n return False\n\ndef nextPrime(start):\n \"\"\"Returns the prime number immediately to the right of 'start'\"\"\"\n out = start + 1\n while not isPrime(out):\n out += 1\n\n return out\n\ndef main():\n primes = [3, 7, 109, 673]\n guess = nextPrime(primes[-1])\n done = list(map(lambda x: checkCondition(x, guess), primes))\n\n while not all(done):\n guess = nextPrime(guess)\n print(\"Trying %s\" % guess)\n done = list(map(lambda x: checkCondition(x, guess), primes))\n #print(done)\n\n primes.append(guess)\n print(\"The new list of numbers which satisfy the condition is %s\" % primes)\n\nif __name__ == '__main__':\n start = clock()\n main()\n end = clock()\n print(\"Time elapsed: %s seconds.\" % (end - start))\n","sub_path":"Python/euler060.py","file_name":"euler060.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"273773353","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n\n\n path('create', views.createNote, name='createNote'),\n path('', views.getNote, name='getNote'),\n path('details/', views.getDetailNote, name='getDetailNote'),\n path('update/', views.updateNote, name='updateNote'),\n path('delete/', views.deleteNote, name='deleteNote'),\n \n\n]\n","sub_path":"note/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"647285354","text":"from .utils import get_t2meta_cls\n\n\nclass BaseOptions:\n def __init__(self, changes):\n self.changes = changes or []\n\n def merge(self, super_opts):\n if super_opts:\n self.changes += super_opts.changes\n return self\n\n @classmethod\n def from_meta(cls, meta):\n if meta:\n kwargs = {k: v for k, v in meta.__dict__.items() if not k.startswith(\"_\")}\n else:\n kwargs = {}\n return cls(**kwargs)\n\n\nclass OrderingOptionsMixin:\n def __init__(self, can_order_by, default_ordering):\n self.can_order_by = self._to_tuple(can_order_by)\n self.default_ordering = self._to_tuple(default_ordering)\n\n assert not (\n set(self._cleaned_names(self.default_ordering)) - set(self.can_order_by)\n )\n\n @classmethod\n def _to_tuple(cls, value):\n if value is None:\n value = tuple()\n elif isinstance(value, str):\n value = (value,)\n else:\n value = tuple(value)\n\n assert isinstance(value, tuple)\n assert all([isinstance(v, str) and v for v in value]) or not value\n assert len(value) == len(set(value))\n\n return value\n\n @classmethod\n def _cleaned_names(cls, ordering):\n return [name.replace(\"-\", \"\") for name in ordering]\n\n def validate_ordering(self, ordering):\n return all(\n [item in self.can_order_by for item in self._cleaned_names(ordering)]\n )\n\n\nclass InputObjectOptions(BaseOptions):\n def __init__(\n self, abstract=False, changes=None, required=None, model=None, fields=None\n ):\n assert not fields or model\n super().__init__(changes)\n self.abstract = abstract\n self.required = required or {}\n self.model = model\n self.fields = None\n self.required_fields = None\n if not fields:\n return\n self.fields = []\n self.required_fields = []\n for name in fields:\n if name.startswith(\"*\"):\n name = name[1:]\n self.required_fields.append(name)\n self.fields.append(name)\n\n def merge(self, super_opts):\n super().merge(super_opts)\n if not self.model and super_opts and super_opts.abstract:\n self.model = super_opts.model\n return self\n\n\nclass DjangoObjectTypeOptions(OrderingOptionsMixin, BaseOptions):\n def __init__(self, can_order_by=None, default_ordering=None, changes=None):\n BaseOptions.__init__(self, changes)\n OrderingOptionsMixin.__init__(self, can_order_by, default_ordering)\n\n\nclass QueriesOptions(BaseOptions):\n def __init__(self, enable_ordering_for=None, changes=None):\n super().__init__(changes)\n self.enable_ordering_for = enable_ordering_for or []\n\n\nclass MutationOptions(BaseOptions):\n def __init__(self, action, input_type, output_type, description=None):\n self.action = action\n self.input_type = input_type\n self.output_type = output_type\n self.description = description\n","sub_path":"graphene_t2/options.py","file_name":"options.py","file_ext":"py","file_size_in_byte":3047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"398855391","text":"import sys\nimport re\nimport os\n\nfrom optparse import OptionParser\nfrom Trie import Trie\nfrom TokenCollector import TokenCollector\nfrom CommentChecker import CommentChecker\n\n#Prints the progress bar\ndef progress(count, total, status=''):\n bar_len = 60\n filled_len = int(round(bar_len * count / float(total)))\n percents = round(100.0 * count / float(total), 1)\n bar = '=' * filled_len + '-' * (bar_len - filled_len)\n sys.stdout.write('\\r[%s] %s%s ...%s' % (bar, percents, '%', status))\n sys.stdout.flush()\n\n#For command-line arguments\nparser = OptionParser()\n#Adding command-line options\nparser.add_option('-i', '--include', dest = 'include', help ='Includes the file/files ie words that the user doesn\\'t want to be flagged as spelling mistakes', metavar = 'FILE')\nparser.add_option('-e', '--exclude', dest = 'exclude', help ='Includes the file/files ie words that the user doesn\\'t want to be flagged as spelling mistakes', metavar = 'FILE')\nparser.add_option('-c', '--check', dest = 'check', help ='Includes the file/files ie words that the user doesn\\'t want to be flagged as spelling mistakes', metavar = 'FILE')\n#Parse command-line arguments\n(options, args) = parser.parse_args()\n\n#If no files to check exit\nif options.check == None:\n print(\"No files to check\")\n print(\"Exiting\")\n sys.exit()\n exclude = []\n \n#Splitting exclude folders into list\nif options.exclude != None:\n exclude = re.split(\" \", options.exclude)\n \n#If not a valid path\nif not (os.path.isdir(options.check) or os.path.isfile(options.check)):\n print(\"Check path \\033[1;31m\",options.check, \"\\033[0m not found\")\n sys.exit()\n\n#Opening the dictionary file\nfile = open('words.txt', 'r')\n\n#Creating a trie\ntrie = Trie()\n\ni = 0\nline = file.readline()\n\n#For every word in words.txt add the word to trie\nwhile line != \"\":\n if i % 100 == 0:\n progress(i, 466454, status=\"Loading words\")\n i += 1\n trie.count += 1\n line = line[0:len(line)-1]\n trie.add(line.lower())\n line = file.readline()\nprint(\"\\n\")\n\n#If include file is specified\n# For every word in included file add it to trie\nif not options.include == None:\n include = options.include\n include = re.split(\" \", include)\n\n for f in include:\n try:\n file = open(os.path.join(os.getcwd(), f), \"r\")\n line = file.readline()\n while line != \"\":\n trie.count += 1\n line = line[0:len(line)-1]\n trie.add(line.lower())\n line = file.readline()\n except FileNotFoundError:\n print(\"Include file \\033[1;31m\",os.path.join(os.getcwd(), f), \"\\033[0m not found\")\n sys.exit()\nprint(\"\\n\")\n\n#Collect all tokens from the files\ntoken_collector = TokenCollector(options.check, exclude)\nall_tokens = token_collector.get_tokens()\n\ncount = 0\ntoken_count = len(all_tokens)\n\n#Add collected tokens to the trie\nfor token in all_tokens:\n count += 1\n progress(count, token_count, status=\"Loading tokens\")\n trie.add(token)\nprint(\"\\n\")\n\n#Check the comments\ncc = CommentChecker(options.check, exclude)\ncc.check_comments(trie)\n\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":3120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"552897472","text":"\"\"\"\r\nName: Brian Nguyen\r\nClass: CECS 378 - Intro to Computer Security Principles\r\nStart Date: 3/13/19\r\nEnd Date: 3/24/19\r\n\"\"\"\r\n\r\n\r\nimport binascii\r\nfrom textwrap import wrap\r\nimport time\r\n\r\n# location of save file (on my system)\r\nlocation = \"C:\\\\OLDGAMES\\\\ultima\\\\SAVED.GAM\"\r\nf = open(location, 'rb').read()\r\n# removes all special characters and returns only the letters and numbers\r\nhex_encoded = binascii.hexlify(f).decode('utf-8')\r\n# combines two characters and appends them to a list\r\nhex_list = wrap(hex_encoded, 2)\r\nx = 32\r\n\r\n\"\"\"\r\n\r\nFunctions for changing the character stats\r\n\r\n\"\"\"\r\n\r\n\r\ndef change_strength(character):\r\n i = 14\r\n change = input(\"Enter your new value: \").lower()\r\n while len(change) != 2:\r\n change = input(\"Please enter again: \").lower()\r\n print('Changing...')\r\n time.sleep(2)\r\n hex_change_single(character, change, i)\r\n\r\n\r\ndef change_intelligence(character):\r\n change = input(\"Enter your new value: \").lower()\r\n while len(change) != 2:\r\n change = input(\"Please enter again: \").lower()\r\n # 1. Brian\r\n i = 16\r\n print('Changing...')\r\n time.sleep(2)\r\n hex_change_single(character, change, i)\r\n\r\ndef change_dexterity(character):\r\n change = input(\"Enter your new value: \").lower()\r\n while len(change) != 2:\r\n change = input(\"Please enter again: \").lower()\r\n i = 15\r\n print('Changing...')\r\n time.sleep(2)\r\n hex_change_single(character, change, i)\r\n\r\ndef change_hp(character):\r\n change = input(\"Enter your new value (PLEASE PUT 4 DIGITS): \").lower()\r\n while len(change) != 4:\r\n change = input(\"Please enter again: \").lower()\r\n # first half\r\n a = change[0:len(change) // 2]\r\n # second half\r\n b = change[len(change) // 2 if len(change) % 2 == 0 else ((len(change) // 2) + 1):]\r\n i = 18\r\n print('Changing...')\r\n time.sleep(2)\r\n hex_change_double(character, a, b, i)\r\n\r\ndef change_max_hp(character):\r\n change = input(\"Enter your new value (PLEASE PUT 4 DIGITS): \").lower()\r\n while len(change) != 4:\r\n change = input(\"Please enter again: \").lower()\r\n # first half\r\n a = change[0:len(change) // 2]\r\n # second half\r\n b = change[len(change) // 2 if len(change) % 2 == 0 else ((len(change) // 2) + 1):]\r\n i = 20\r\n print('Changing...')\r\n time.sleep(2)\r\n hex_change_double(character, a, b, i)\r\n\r\ndef change_experience(character):\r\n change = input(\"Enter your new value (PLEASE PUT 4 DIGITS): \").lower()\r\n while len(change) != 4:\r\n change = input(\"Please enter again: \").lower()\r\n # first half\r\n a = change[0:len(change) // 2]\r\n # second half\r\n b = change[len(change) // 2 if len(change) % 2 == 0 else ((len(change) // 2) + 1):]\r\n i = 22\r\n print('Changing...')\r\n time.sleep(2)\r\n hex_change_double(character, a, b, i)\r\n\r\n\r\ndef hex_change_single(character, change, i):\r\n # 1. Brian\r\n if character == 1:\r\n hex_list[i] = change\r\n # 2. Shamino\r\n elif character == 2:\r\n hex_list[i + x] = change\r\n # 3. Iolo\r\n elif character == 3:\r\n hex_list[i + (x * 2)] = change\r\n # 4. Mariah\r\n elif character == 4:\r\n hex_list[i + (x * 3)] = change\r\n # 5. Geoffrey\r\n elif character == 5:\r\n hex_list[i + (x * 4)] = change\r\n # 6. Jaana\r\n elif character == 6:\r\n hex_list[i + (x * 5)] = change\r\n # 7. Julia\r\n elif character == 7:\r\n hex_list[i + (x * 6)] = change\r\n # 8. Dupre\r\n elif character == 8:\r\n hex_list[i + (x * 7)] = change\r\n # 9. Katrina\r\n elif character == 9:\r\n hex_list[i + (x * 8)] = change\r\n # 10. Sentri\r\n elif character == 10:\r\n hex_list[i + (x * 9)] = change\r\n # 11. Gwenno\r\n elif character == 11:\r\n hex_list[i + (x * 10)] = change\r\n # 12. Johne\r\n elif character == 12:\r\n hex_list[i + (x * 11)] = change\r\n # 13. Gorn\r\n elif character == 13:\r\n hex_list[i + (x * 12)] = change\r\n # 14. Maxwell\r\n elif character == 14:\r\n hex_list[i + (x * 13)] = change\r\n # 15. Toshi\r\n elif character == 15:\r\n hex_list[i + (x * 14)] = change\r\n # 16. Saduj\r\n elif character == 16:\r\n hex_list[i + (x * 15)] = change\r\n print('Success!')\r\n\r\n\r\ndef hex_change_double(character, a, b, i):\r\n # 1. Brian\r\n if character == 1:\r\n hex_list[i], hex_list[i + 1] = b, a\r\n # 2. Shamino\r\n elif character == 2:\r\n hex_list[i + x], hex_list[(i + x) + 1] = b, a\r\n # 3. Iolo\r\n elif character == 3:\r\n hex_list[i + (x * 2)], hex_list[(i + (x * 2)) + 1] = b, a\r\n # 4. Mariah\r\n elif character == 4:\r\n hex_list[i + (x * 3)], hex_list[(i + (x * 3)) + 1] = b, a\r\n # 5. Geoffrey\r\n elif character == 5:\r\n hex_list[i + (x * 4)], hex_list[(i + (x * 4)) + 1] = b, a\r\n # 6. Jaana\r\n elif character == 6:\r\n hex_list[i + (x * 5)], hex_list[(i + (x * 5)) + 1] = b, a\r\n # 7. Julia\r\n elif character == 7:\r\n hex_list[i + (x * 6)], hex_list[(i + (x * 6)) + 1] = b, a\r\n # 8. Dupre\r\n elif character == 8:\r\n hex_list[i + (x * 7)], hex_list[(i + (x * 7)) + 1] = b, a\r\n # 9. Katrina\r\n elif character == 9:\r\n hex_list[i + (x * 8)], hex_list[(i + (x * 8)) + 1] = b, a\r\n # 10. Sentri\r\n elif character == 10:\r\n hex_list[i + (x * 9)], hex_list[(i + (x * 9)) + 1] = b, a\r\n # 11. Gwenno\r\n elif character == 11:\r\n hex_list[i + (x * 10)], hex_list[(i + (x * 10)) + 1] = b, a\r\n # 12. Johne\r\n elif character == 12:\r\n hex_list[i + (x * 11)], hex_list[(i + (x * 11)) + 1] = b, a\r\n # 13. Gorn\r\n elif character == 13:\r\n hex_list[i + (x * 12)], hex_list[(i + (x * 12)) + 1] = b, a\r\n # 14. Maxwell\r\n elif character == 14:\r\n hex_list[i + (x * 13)], hex_list[(i + (x * 13)) + 1] = b, a\r\n # 15. Toshi\r\n elif character == 15:\r\n hex_list[i + (x * 14)], hex_list[(i + (x * 14)) + 1] = b, a\r\n # 16. Saduj\r\n elif character == 16:\r\n hex_list[i + (x * 15)], hex_list[(i + (x * 15)) + 1] = b, a\r\n print('Success!')\r\n\r\ndef change_gold():\r\n change = input(\"Enter your new value (PLEASE PUT 4 DIGITS): \").lower()\r\n while len(change) != 4:\r\n change = input(\"Please enter again: \").lower()\r\n # first half\r\n a = change[0:len(change) // 2]\r\n # second half\r\n b = change[len(change) // 2 if len(change) % 2 == 0 else ((len(change) // 2) + 1):]\r\n print('Changing...')\r\n time.sleep(2)\r\n hex_list[516], hex_list[517] = b, a\r\n print('Success!\\n')\r\n\r\n\r\n\"\"\"\r\nFunctions for changing items\r\n\"\"\"\r\n\r\n\r\ndef change_keys():\r\n change = input(\"Enter your new value: \").lower()\r\n while len(change) != 2:\r\n change = input(\"Please enter again: \").lower()\r\n print('Changing...')\r\n time.sleep(2)\r\n hex_list[518] = change\r\n print('Success!')\r\n\r\n\r\ndef change_gems():\r\n change = input(\"Enter your new value: \").lower()\r\n while len(change) != 2:\r\n change = input(\"Please enter again: \").lower()\r\n print('Changing...')\r\n time.sleep(2)\r\n hex_list[519] = change\r\n print('Success!')\r\n\r\n\r\ndef change_skull_keys():\r\n change = input(\"Enter your new value: \").lower()\r\n while len(change) != 2:\r\n change = input(\"Please enter again: \").lower()\r\n print('Changing...')\r\n time.sleep(2)\r\n hex_list[523] = change\r\n print('Success!')\r\n\r\n\r\ndef change_black_badges():\r\n change = input(\"Enter your new value: \").lower()\r\n while len(change) != 2:\r\n change = input(\"Please enter again: \").lower()\r\n print('Changing...')\r\n time.sleep(2)\r\n hex_list[536] = change\r\n print('Success!')\r\n\r\n\r\ndef change_magic_carpets():\r\n change = input(\"Enter your new value: \").lower()\r\n while len(change) != 2:\r\n change = input(\"Please enter again: \").lower()\r\n print('Changing...')\r\n time.sleep(2)\r\n hex_list[522] = change\r\n print('Success!')\r\n\r\n\r\ndef change_magic_axes():\r\n change = input(\"Enter your new value: \").lower()\r\n while len(change) != 2:\r\n change = input(\"Please enter again: \").lower()\r\n print('Changing...')\r\n time.sleep(2)\r\n hex_list[576] = change\r\n print('Success!\\n')\r\n\r\n\r\n\"\"\"\r\nMenu functions\r\n\"\"\"\r\n\r\n\r\ndef main_menu():\r\n print(\"----------------\\n\"\r\n \"1.\\tChange Character Stats\\n\"\r\n \"2.\\tChange Character Items\\n\"\r\n \"3.\\tExit\\n\")\r\n choice = int(input('Enter your selection: '))\r\n while choice < 1 or choice > 3:\r\n choice = int(input(\"Please try again: \"))\r\n return choice\r\n\r\n\r\ndef character_menu():\r\n print(\"----------------\\n\"\r\n \"1.\\tBrian (main character)\\n\"\r\n \"2.\\tShamino\\n\"\r\n \"3.\\tIolo\\n\"\r\n \"4.\\tMariah\\n\"\r\n \"5.\\tGeoffrey\\n\"\r\n \"6.\\tJaana\\n\"\r\n \"7.\\tJulia\\n\"\r\n \"8.\\tDupre\\n\"\r\n \"9.\\tKatrina\\n\"\r\n \"10.\\tSentri\\n\"\r\n \"11.\\tGwenno\\n\"\r\n \"12.\\tJohne\\n\"\r\n \"13.\\tGorn\\n\"\r\n \"14.\\tMaxwell\\n\"\r\n \"15.\\tToshi\\n\"\r\n \"16.\\tSaduj\\n\"\r\n )\r\n choice = int(input(\"What character are you choosing? \"))\r\n while choice < 1 or choice > 16:\r\n choice = int(input(\"Please try again: \"))\r\n return choice\r\n\r\n\r\ndef stats_menu():\r\n print(\"----------------\\n\"\r\n \"1.\\tStrength\\n\"\r\n \"2.\\tIntelligence\\n\"\r\n \"3.\\tDexterity\\n\"\r\n \"4.\\tHP\\n\"\r\n \"5.\\tMax HP\\n\"\r\n \"6.\\tExperience\\n\"\r\n )\r\n choice = int(input(\"What stat you like to change? \"))\r\n while choice < 1 or choice > 6:\r\n choice = int(input(\"Please try again: \"))\r\n return choice\r\n\r\n\r\ndef item_menu():\r\n print(\"----------------\\n\"\r\n \"1.\\tKeys\\n\"\r\n \"2.\\tSkull Keys\\n\"\r\n \"3.\\tGems\\n\"\r\n \"4.\\tBlack Badges\\n\"\r\n \"5.\\tMagic Carpets\\n\"\r\n \"6.\\tMagic Axes\\n\"\r\n \"7.\\tGold\\n\")\r\n choice = int(input(\"What item you like to change? \"))\r\n while choice < 1 or choice > 7:\r\n choice = int(input(\"Please try again: \"))\r\n return choice\r\n\r\n\r\ndef return_main_menu():\r\n print(\"Returning to main menu...\\n\")\r\n time.sleep(3)\r\n return user_interface()\r\n\r\n\r\ndef user_interface():\r\n while True:\r\n s = main_menu()\r\n # change character stats\r\n if s == 1:\r\n # select character\r\n character = character_menu()\r\n stat = stats_menu()\r\n # 1. strength\r\n if stat == 1:\r\n change_strength(character)\r\n # 2. intelligence\r\n if stat == 2:\r\n change_intelligence(character)\r\n # 3. dexterity\r\n if stat == 3:\r\n change_dexterity(character)\r\n # 4. hp\r\n if stat == 4:\r\n change_hp(character)\r\n # 5. max hp\r\n if stat == 5:\r\n change_max_hp(character)\r\n # 6. experience\r\n if stat == 6:\r\n change_experience(character)\r\n # change character items\r\n if s == 2:\r\n item = item_menu()\r\n # 1. keys\r\n if item == 1:\r\n change_keys()\r\n # 2. skull keys\r\n if item == 2:\r\n change_skull_keys()\r\n # 3. gems\r\n if item == 3:\r\n change_gems()\r\n # 4. black badges\r\n if item == 4:\r\n change_black_badges()\r\n # 5. magic carpets\r\n if item == 5:\r\n change_magic_carpets()\r\n # 6. magic axes\r\n if item == 6:\r\n change_magic_axes()\r\n # 7. gold\r\n if item == 7:\r\n change_gold()\r\n if s == 3:\r\n break\r\n\r\n\r\ndef main():\r\n print(\"Welcome to B-Rye's Ultima V Hacking Tool!\\n\"\r\n \"Please note that all values entered are in hexadecimal\\n\"\r\n \"and have a length of 2 unless stated otherwise.\\n\"\r\n \"Enjoy!\\n\")\r\n user_interface()\r\n\r\n\r\nmain()\r\nf = open(location, 'wb')\r\nnew = \"\".join(hex_list)\r\nhex_encoded = binascii.unhexlify(new)\r\nf.write(hex_encoded)\r\n","sub_path":"Project 2/ultima_hack.py","file_name":"ultima_hack.py","file_ext":"py","file_size_in_byte":12028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"314645408","text":"import time\nimport datetime\nimport os\nimport tools\nimport configRead\n\n\ndef get_time_stamp():\n ct = time.time()\n local_time = time.localtime(ct)\n data_head = time.strftime(\"%Y-%m-%d %H:%M:%S\", local_time)\n data_secs = (ct - int(ct)) * 1000\n time_stamp = \"%s.%03d\" % (data_head, data_secs)\n return time_stamp\n\ndef get_hour():\n ct = time.time()\n local_time = time.localtime(ct)\n hourtime = time.strftime(\"%H:%M:%S\", local_time)\n return hourtime\n\t\ndef time_cmp(first_time, second_time):\n if first_time arr[j + 1]:\n # - If elements in wrong position (relative to each other, swap them)\n temp = arr[j]\n arr[j] = arr[j+1]\n arr[j+1] = temp\n return arr\n\n\n\nlist2 = [5,4,3,2,1]\nbubble_sort(list2)\n\n# STRETCH: implement the Count Sort function below\n# def count_sort( arr, maximum=-1 ):\n\n# return arr","sub_path":"src/iterative_sorting/iterative_sorting.py","file_name":"iterative_sorting.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"117790468","text":"__author__ = 'DreTaX'\n__version__ = '1.3'\n\nimport clr\n\nclr.AddReferenceByPartialName(\"Pluton\")\nimport Pluton\nimport re\n\n\"\"\"\n Class\n\"\"\"\n\n\nclass IllegalName:\n\n def getIllegal(self):\n if not Plugin.IniExists(\"IllegalNames\"):\n IllegalNames = Plugin.CreateIni(\"IllegalNames\")\n IllegalNames.AddSetting(\"IllegalNames\", \"Name1\", \"Suck\")\n IllegalNames.AddSetting(\"IllegalNames\", \"Name2\", \"Fuck\")\n IllegalNames.AddSetting(\"IllegalNames\", \"Name3\", \"SHITSERVER\")\n IllegalNames.Save()\n return Plugin.GetIni(\"IllegalNames\")\n\n def IllegalNameConfig(self):\n if not Plugin.IniExists(\"IllegalNameConfig\"):\n loc = Plugin.CreateIni(\"IllegalNameConfig\")\n loc.Save()\n return Plugin.GetIni(\"IllegalNameConfig\")\n\n def CutName(self, string):\n name = string.encode('UTF-8')\n name = name.decode('UTF-8', 'strict')\n name = re.sub(r'[^\\x00-\\x7F]+','', name)\n return name\n\n def On_ClientAuth(self, AuthEvent):\n Player = AuthEvent.con\n name = str(AuthEvent.Name)\n n = len(name)\n ini = self.IllegalNameConfig()\n asciie = int(ini.GetSetting(\"options\", \"CheckForNonAscii\"))\n regex = int(ini.GetSetting(\"options\", \"CheckWithRegEx\"))\n illini = self.getIllegal()\n reason = ini.GetSetting(\"options\", \"DisconnectReason\")\n reason2 = ini.GetSetting(\"options\", \"DisconnectReason2\")\n listnames = illini.EnumSection(\"IllegalNames\")\n counted = len(listnames)\n i = 0\n if counted > 0:\n for checkn in listnames:\n get = illini.GetSetting(\"IllegalNames\", checkn)\n i += 1\n lowername = name.lower()\n lowercheck = get.lower()\n if counted >= i:\n if lowercheck in lowername:\n Player.Kick(reason)\n return\n if regex == 1:\n starts = name.startswith(' ')\n ends = name.endswith(' ')\n if starts is True:\n name.replace(name[0], '')\n if ends is True:\n name.replace(name[n], '')\n a = re.match('^[a-zA-Z0-9_!+?%éáűőúöüó()<>/\\@#,.\\\\s\\[\\]-]+$', name)\n if not a or n <= 1:\n Player.Kick(reason2)\n return\n name = re.sub(' +',' ', name)\n name = re.sub('[\\t]+','', name)\n if asciie == 1:\n newname = self.CutName(name)\n name = newname\n AuthEvent.con.username = name","sub_path":"PlutonPlugins/IllegalName/IllegalName.py","file_name":"IllegalName.py","file_ext":"py","file_size_in_byte":2581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"128584180","text":"import os.path\n\nfrom talk_video_maker import mainfunc, opts, qr\nfrom talk_video_maker.syncing import offset_video, get_audio_offset\n\nFPS = 25\n\nDEFAULT_TEMPLATE = os.path.join(os.path.abspath(os.path.dirname(__file__)),\n 'pyvo.svg')\n\ndef apply_logo(template, logo_name, duration, logo_elem, page_elem=None):\n sizes = template.element_sizes[logo_elem]\n logo_overlay = template.exported_slide(\n 'logo-' + logo_name, duration=duration,\n width=sizes['w'], height=sizes['h'])\n logo_overlay = logo_overlay.resized_by_template(\n template, logo_elem, page_elem)\n return logo_overlay\n\ndef make_info_overlay(template, duration, logo=None):\n info_overlay = template.exported_slide('vid-only', duration=min(duration, 10))\n if logo:\n info_overlay |= apply_logo(template, logo, info_overlay.duration, 'logo2', 'vid-only')\n return info_overlay.faded_out(1)\n\n@mainfunc(__name__)\ndef make_pyvo(\n template: opts.TemplateOption(\n default=DEFAULT_TEMPLATE, help='Main template'),\n screen_vid: opts.VideoOption(\n default='*.ogv',\n help='Video file with the screen grab'),\n speaker_vid: opts.VideoOption(\n default='*.MTS',\n help='Video file with recording of the speaker'),\n speaker: opts.TextOption(help='Name of the speaker'),\n title: opts.TextOption(help='Name of the talk'),\n url: opts.TextOption(help='URL of the talk'),\n event: opts.TextOption(help='Name of the event'),\n date: opts.DateOption(help='Date of the event'),\n trim: opts.TextOption(\n default='b',\n help='Video trimming mode ' +\n '(a=whole screencast, b=whole speaker video, pad=include both videos, intersect=include only common part)'),\n preview: opts.FlagOption(\n help='Only process a small preview of the video'),\n av_offset: opts.FloatOption(\n default=0,\n help='Audio/Video offset correction for the speaker video'),\n screen_offset: opts.FloatOption(\n default=None,\n help='Manual time offset of the screencast'),\n speaker_only: opts.FlagOption(\n help='Only use the speaker video'),\n logo: opts.TextOption(\n default='',\n help='Pyvo logo variant (can be \"tuplak\", \"ruby\")'),\n praha: opts.FlagOption(\n help='Skip sponsors slide & include Pyvec overlay'),\n widescreen: opts.FlagOption(\n help='Make the screencast span the whole screen, not just a 4:3 area'),\n no_end: opts.FlagOption(\n help='Do not include the end slides'),\n ):\n for n in '', '2':\n template = template.with_text('txt-speaker' + n, speaker + ':')\n template = template.with_text('txt-title' + n, title)\n template = template.with_text('txt-event' + n, event)\n template = template.with_text('txt-date' + n, date.strftime('%Y-%m-%d'))\n template = template.with_text('txt-url', url)\n\n if not screen_vid and not speaker_only:\n raise ValueError('No screen video')\n if not speaker_vid:\n raise ValueError('No speaker video')\n\n if praha:\n # no overlay for PiP videos yet\n assert speaker_only\n\n export_template = template\n export_template = export_template.without('vid-screen')\n export_template = export_template.without('vid-speaker')\n export_template = export_template.without('qrcode')\n export_template = export_template.without('vid-only')\n export_template = export_template.without('slide-overlay')\n\n if logo:\n export_template = export_template.without('logo')\n export_template = export_template.without('logo2')\n\n sponsors = export_template.exported_slide('slide-sponsors', duration=6)\n sponsors = sponsors.faded_in(0.5)\n sponsors = sponsors.faded_out(0.5)\n\n last = export_template.exported_slide('slide-last', duration=7)\n\n qr_sizes = template.element_sizes['qrcode']\n last_sizes = template.element_sizes['slide-last']\n qrcode = qr.TextQR(url).resized(qr_sizes['w'], qr_sizes['h'])\n qrcode = qrcode.exported_slide(duration=last.duration)\n qrcode = qrcode.resized_by_template(template, 'qrcode', 'slide-last')\n\n last = last | qrcode\n last = last.faded_in(0.5)\n\n if av_offset:\n speaker_vid = speaker_vid.with_video_offset(av_offset)\n\n if speaker_only:\n speaker_vid = speaker_vid.resized_by_template(template, 'vid-only', 'vid-only')\n speaker_vid = speaker_vid.with_fps(FPS)\n\n if preview:\n speaker_vid = speaker_vid.trimmed(end=30)\n\n duration = speaker_vid.duration\n\n main = speaker_vid | make_info_overlay(export_template, duration, logo)\n else:\n speaker_vid = speaker_vid.resized_by_template(template, 'vid-speaker')\n speaker_vid = speaker_vid.with_fps(FPS)\n\n if widescreen:\n screen_vid = screen_vid.resized_by_template(template, None)\n else:\n screen_vid = screen_vid.resized_by_template(template, 'vid-screen')\n screen_vid = screen_vid.with_fps(FPS)\n\n if screen_offset is None:\n if not any(s.type == 'audio' for s in screen_vid.streams):\n raise ValueError('screencast has no audio, specify screen_offset manually')\n screen_offset = get_audio_offset(screen_vid, speaker_vid)\n\n screen_vid, speaker_vid = offset_video(screen_vid, speaker_vid,\n screen_offset, mode=trim)\n\n if preview:\n speaker_vid = speaker_vid.trimmed(end=30)\n screen_vid = screen_vid.trimmed(end=30)\n\n screen_vid = screen_vid.muted()\n\n duration = max(screen_vid.duration, speaker_vid.duration)\n\n page = export_template.exported_slide(duration=duration)\n if logo:\n page |= apply_logo(export_template, logo, page.duration, 'logo')\n if widescreen:\n main = page | screen_vid | make_info_overlay(export_template, duration) | speaker_vid\n else:\n main = page | speaker_vid | screen_vid\n\n if praha:\n overlay = export_template.exported_slide('slide-overlay', duration=main.duration)\n main |= overlay\n main = main.faded_out(0.5)\n if not no_end:\n if not praha:\n main += sponsors\n main += last\n\n blank = export_template.exported_slide('slide-blank', duration=main.duration)\n result = blank | main\n\n print(result.graph)\n\n return result\n","sub_path":"pyvo/make_vid.py","file_name":"make_vid.py","file_ext":"py","file_size_in_byte":6534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"73279850","text":"import matplotlib.pyplot as plt\nfrom matplotlib import font_manager as fm # 한글 폰트 설정\nimport pandas as pd\n\n# 데이터 변수 선언 -------------------------------------\nTEMP_CSV = \"../../DATA/WEATHER/tem10y.csv\"\n\n# ----------------------------------------------------\n# 데이터 준비\n# ----------------------------------------------------\ndf = pd.read_csv(TEMP_CSV, encoding=\"utf-8\")\n\n# 온도가 30도를 넘는 데이터 확인\nhot_bool = (df[\"기온\"] > 30)\n\n# 데이터 추출\nhot = df[hot_bool]\n\n# 연별로 세기\ncnt = hot.groupby([\"연\"])[\"연\"].count()\nprint(cnt)\n\n# 출력\nfont_path = r'C:\\Windows\\Fonts\\malgun.ttf'\nfont_name = fm.FontProperties(fname=font_path).get_name()\nplt.rc('font', family=font_name)\nplt.rc('axes', unicode_minus=False)\ncnt.plot()\nplt.savefig(\"tem-over30.png\")\nplt.show()\n","sub_path":"PythonAI/Source/W2D5/src/over30.py","file_name":"over30.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"164432703","text":"import asyncio as a\nimport discord as d\nfrom discord.ext.commands import command\nfrom discord.ext.commands import bot_has_permissions\nfrom discord.ext import commands as c\nfrom .i18n import i18n\n\nDGHANGMANSHANPES = [\n\t'```\\n_\\n\\n\\n\\n_```',\n\t'```\\n_\\n\\n\\n\\u2500\\u2500\\u2500\\u2500\\u2500\\n```',\n\t'```\\n\\u250c\\u2500\\u2500\\u2500\\u2510\\n\\u2502\\n\\u2502\\n\\u2502\\n\\u2514\\u2500\\\n\\u2500\\u2500\\u2500\\n```',\n\t'```\\n\\u250c\\u2500\\u2500\\u2500\\u2510\\n\\u2502 O\\n\\u2502\\n\\u2502\\n\\u2514\\\n\\u2500\\u2500\\u2500\\u2500\\n```',\n\t'```\\n\\u250c\\u2500\\u2500\\u2500\\u2510\\n\\u2502 O\\n\\u2502 /\\n\\u2502\\n\\u2514\\\n\\u2500\\u2500\\u2500\\u2500\\n```',\n\t'```\\n\\u250c\\u2500\\u2500\\u2500\\u2510\\n\\u2502 O\\n\\u2502 / \\\\\\n\\u2502\\n\\\n\\u2514\\u2500\\u2500\\u2500\\u2500\\n```',\n\t'```\\n\\u250c\\u2500\\u2500\\u2500\\u2510\\n\\u2502 O\\n\\u2502 /|\\\\\\n\\u2502\\n\\\n\\u2514\\u2500\\u2500\\u2500\\u2500\\n```',\n\t'```\\n\\u250c\\u2500\\u2500\\u2500\\u2510\\n\\u2502 O\\n\\u2502 /|\\\\\\n\\u2502 /\\n\\\n\\u2514\\u2500\\u2500\\u2500\\u2500\\n```',\n\t'```\\n\\u250c\\u2500\\u2500\\u2500\\u2510\\n\\u2502 O\\n\\u2502 /|\\\\\\n\\u2502 / \\\n\\\\\\n\\u2514\\u2500\\u2500\\u2500\\u2500\\n```'\n]\n\nclass Hangman(object):\n\tdef __init__(self, bot, logger ,db):\n\t\tself.bot = bot\n\t\tself.logger = logger\n\t\tself.db = db\n\n\t@staticmethod\n\tdef substrs(sub, string):\n\t\tlast_found = -1\n\t\twhile 1:\n\t\t\tlast_found = string.lower().find(sub, last_found + 1)\n\t\t\tif last_found == -1:\n\t\t\t\tbreak\n\t\t\tyield last_found\n\n\t@command()\n\t@c.check(lambda ctx: \\\n\t\tctx.guild \\\n\t\tand (not ctx.channel.permissions_for(ctx.guild.me).manage_messages)\n\t)\n\tasync def crudehangman(self, ctx):\n\t\t\"\"\"Hangman for less permissions\n\n\t\tUse this first in the server, to start the game in that channel;\n\t\tNext, send the word in a DM with the bot, to set it.\n\t\tOnce that's been done, guess a letter by sending it.\n\t\t\"\"\"\n\t\tself.logger.info('Games.crudehangman', extra={'ctx': ctx})\n\t\tif self.db.execute(\n\t\t\t'SELECT channel_id FROM ch_channels_occupied WHERE channel_id=?',\n\t\t\t(ctx.channel.id,)\n\t\t).fetchone() is not None:\n\t\t\tawait ctx.send(i18n(ctx, 'hangman/crudehangman-occupied'))\n\t\t\townerq = await self.bot.is_owner(ctx.author)\n\t\t\tif not ownerq:\n\t\t\t\treturn\n\t\tself.db.execute(\n\t\t\t'INSERT INTO ch_channels_occupied VALUES (?)',\n\t\t\t(ctx.channel.id,)\n\t\t)\n\t\tawait ctx.send(i18n(ctx, 'hangman/awaiting-dm'))\n\t\ttry:\n\t\t\tmsg = await ctx.bot.wait_for('message',\n\t\t\t\tcheck=lambda m: \\\n\t\t\t\t\tisinstance(m.channel, d.DMChannel) \\\n\t\t\t\t\tand m.author == ctx.author,\n\t\t\t\ttimeout=60.0)\n\t\texcept a.TimeoutError:\n\t\t\tawait ctx.send(i18n(ctx, 'hangman/timeout'))\n\t\t\treturn\n\t\tWORD = WORD.content\n\t\tletters = ['_'] * len(WORD)\n\t\tlowers = (\n\t\t\t'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',\n\t\t\t'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',\n\t\t\t'u', 'v', 'w', 'x', 'y', 'z'\n\t\t)\n\t\tfor i in range(len(WORD)):\n\t\t\tif WORD[i].lower() not in lowers:\n\t\t\t\tletters[i] = WORD[i]\n\t\tmissed = []\n\t\tshanpe = 0\n\t\tawait ctx.send(i18n(\n\t\t\tctx, 'hangman/main', DGHANGMANSHANPES[shanpe], \"\", \"\".join(letters)\n\t\t))\n\t\twhile \"\".join(letters) != WORD and shanpe < len(DGHANGMANSHANPES) - 1:\n\t\t\tletter = (await ctx.bot.wait_for('message',\n\t\t\t\tcheck=lambda m: \\\n\t\t\t\t\tm.channel == ctx.channel \\\n\t\t\t\t\tand m.content in lowers)\n\t\t\t).content\n\t\t\tif WORD.lower().find(letter) != -1:\n\t\t\t\tfor i in self.substrs(letter, WORD):\n\t\t\t\t\tletters[i] = WORD[i]\n\t\t\telse:\n\t\t\t\tif letter not in missed:\n\t\t\t\t\tmissed.append(letter)\n\t\t\t\t\tshanpe += 1\n\t\t\tawait ctx.send(i18n(\n\t\t\t\tctx, 'hangman/main', DGHANGMANSHANPES[shanpe],\n\t\t\t\ti18n(ctx, 'hangman/comma-sep').join(missed), \"\".join(letters)\n\t\t\t))\n\t\tif \"\".join(letters) == WORD:\n\t\t\tawait ctx.send(i18n(ctx, 'hangman/won'))\n\t\telse:\n\t\t\tawait ctx.send(i18n(ctx, 'hangman/lost', WORD))\n\t\tself.db.execute(\n\t\t\t'DELETE FROM ch_channels_occupied WHERE channel_id=?',\n\t\t\t(ctx.channel.id,)\n\t\t)\n\n\t@command()\n\t@bot_has_permissions(\n\t\tmanage_messages=True, add_reactions=True, read_message_history=True\n\t)\n\tasync def hangman(self, ctx):\n\t\t\"\"\"Hangman!\n\n\t\tUse this in the channel to start the game there,\n\t\tDM the bot the word to set it\n\t\tthen send letters to guess them.\n\t\tRequires the \"Manage Messages\" permission.\n\t\t\"\"\"\n\t\tREGS = '\\U0001f1e6 \\U0001f1e7 \\U0001f1e8 \\U0001f1e9 \\U0001f1ea \\\n\\U0001f1eb \\U0001f1ec \\U0001f1ed \\U0001f1ee \\U0001f1ef \\U0001f1f0 \\U0001f1f1 \\\n\\U0001f1f2 \\U0001f1f3 \\U0001f1f4 \\U0001f1f5 \\U0001f1f6 \\U0001f1f7 \\U0001f1f8 \\\n\\U0001f1f9 \\U0001f1fa \\U0001f1fb \\U0001f1fc \\U0001f1fd \\U0001f1fe \\U0001f1ff' \\\n.split(' ')\n\t\tREGS1, REGS2 = REGS[:13], REGS[13:]\n\t\tNEIN = '\\u274c'\n\t\tself.logger.info('Games.hangman', extra={'ctx': ctx})\n\t\tawait ctx.send(i18n(ctx, 'hangman/awaiting-dm'))\n\t\ttry:\n\t\t\tmsg = await ctx.bot.wait_for('message',\n\t\t\t\tcheck=lambda m: \\\n\t\t\t\t\tisinstance(m.channel, d.DMChannel) \\\n\t\t\t\t\tand m.author == ctx.author,\n\t\t\t\ttimeout=60.0)\n\t\texcept a.TimeoutError:\n\t\t\tawait ctx.send(i18n(ctx, 'hangman/timeout'))\n\t\t\treturn\n\t\tWORD = msg.content\n\t\tletters = ['_'] * len(WORD)\n\t\tlowers = (\n\t\t\t'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',\n\t\t\t'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',\n\t\t\t'w', 'x', 'y', 'z'\n\t\t)\n\t\ttranslate = {}\n\t\tfor regn in range(len(REGS)):\n\t\t\ttranslate[REGS[regn]] = lowers[regn]\n\t\tfor i in range(len(WORD)):\n\t\t\tif WORD[i].lower() not in lowers:\n\t\t\t\tletters[i] = WORD[i]\n\t\tmissed = []\n\t\tshanpe = 0\n\t\tstatus = await ctx.send(i18n(\n\t\t\tctx, 'hangman/main', DGHANGMANSHANPES[shanpe],\n\t\t\ti18n(ctx, 'hangman/comma-sep').join(missed),\n\t\t\t\"\".join(letters),\n\t\t\t'\\n**{}**'.format(\n\t\t\t\ti18n(ctx, 'hangman/wait')\n\t\t\t)\n\t\t))\n\t\treactionmsg1 = await ctx.send('_ _')\n\t\treactionmsg2 = await ctx.send('_ _')\n\t\tawait status.add_reaction(NEIN)\n\t\tfor reg in REGS1:\n\t\t\tawait reactionmsg1.add_reaction(reg)\n\t\tfor reg in REGS2:\n\t\t\tawait reactionmsg2.add_reaction(reg)\n\t\tawait status.edit(content=status.content[:-25])\n\t\twhile \"\".join(letters) != WORD and shanpe < len(DGHANGMANSHANPES) - 1:\n\t\t\ttry:\n\t\t\t\treaction, user = await ctx.bot.wait_for(\n\t\t\t\t\t'reaction_add',\n\t\t\t\t\tcheck=lambda r, u: \\\n\t\t\t\t\t\tr.message.id in (status.id, reactionmsg1.id, reactionmsg2.id) \\\n\t\t\t\t\t\tand str(r) in REGS + [NEIN] \\\n\t\t\t\t\t\tand u.id != self.bot.user.id,\n\t\t\t\t\ttimeout=600.0\n\t\t\t\t)\n\t\t\texcept a.TimeoutError:\n\t\t\t\tawait status.edit(content=i18n(ctx, 'hangman/timeout2'))\n\t\t\t\tawait status.clear_reactions()\n\t\t\t\tawait reactionmsg1.delete()\n\t\t\t\tawait reactionmsg2.delete()\n\t\t\t\treturn\n\t\t\tif str(reaction) == NEIN:\n\t\t\t\tif user.id == ctx.author.id:\n\t\t\t\t\tawait status.edit(\n\t\t\t\t\t\tcontent=i18n(ctx, 'pm_games/game-cancelled')\n\t\t\t\t\t)\n\t\t\t\t\tawait status.clear_reactions()\n\t\t\t\t\tawait reactionmsg1.delete()\n\t\t\t\t\tawait reactionmsg2.delete()\n\t\t\t\t\treturn\n\t\t\t\telse:\n\t\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tletter = translate[str(reaction)]\n\t\t\tawait reaction.message.remove_reaction(reaction, user)\n\t\t\tif WORD.lower().find(letter) != -1:\n\t\t\t\tfor i in self.substrs(letter, WORD):\n\t\t\t\t\tletters[i] = WORD[i]\n\t\t\telse:\n\t\t\t\tif letter not in missed:\n\t\t\t\t\tmissed.append(letter)\n\t\t\t\t\tshanpe += 1\n\t\t\tawait status.edit(content=i18n(\n\t\t\t\tctx, 'hangman/main', DGHANGMANSHANPES[shanpe],\n\t\t\t\ti18n(ctx, 'hangman/comma-sep').join(missed),\n\t\t\t\t\"\".join(letters),\n\t\t\t\t\"\"\n\t\t\t))\n\t\tif \"\".join(letters) == WORD:\n\t\t\tawait ctx.send(i18n(ctx, 'hangman/won'))\n\t\telse:\n\t\t\tawait ctx.send(i18n(ctx, 'hangman/lost', WORD))\n","sub_path":"kenny2automate/hangman.py","file_name":"hangman.py","file_ext":"py","file_size_in_byte":7073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"171769081","text":"\ndef urlfy(s):\n new_s = \"\"\n for i in range(len(s)):\n if s[i] ==' ':\n new_s += \"%20\"\n else:\n new_s += s[i]\n return s, new_s\n\n# Unit Testing\nprint(urlfy(\"the internet longest url\"))\n# assert urlfy(\"the new url\") == \"the%20new%20url\"\n","sub_path":"cracking_the_CI/urlfy.py","file_name":"urlfy.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"638895859","text":"# from serial import Serial\nfrom serial.serialwin32 import Serial\n\nfrom diy.settings import port_time, printlog\n\n\nclass PortManager:\n\n def __init__(self, port_num):\n super(PortManager, self).__init__()\n self.port_num = port_num\n self.ser = Serial(self.port_num, 115200, timeout=port_time) # windows系统使用com8口连接串行口\n # self.port_num = port_num\n\n def close_port(self):\n if self.ser is not None:\n self.ser.close()\n\n # def interface_swicth(self, b):\n # try:\n # if self.ser is not None:\n # self.ser = serial.Serial(self.port_num, 115200, timeout=0.5) # winsows系统使用com8口连接串行口\n # if b:\n # print('打开端口')\n # if not self.ser.is_open:\n # self.ser.open()\n # else:\n # print('关闭端口')\n # if self.ser.is_open:\n # self.ser.close()\n # return True\n # except Exception as e:\n # print('错误')\n # print(e)\n # return False\n\n def get_data_from_interface(self):\n if not self.ser.is_open:\n printlog('端口开启')\n self.ser.open() # enable port\n else:\n printlog('端口已经开启')\n\n while True:\n line_str = self.ser.readline()\n # print(line_str)\n yield line_str\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.close_port()\n\n\nif __name__ == '__main__':\n import re\n\n with PortManager('com4') as pm:\n source_data = pm.get_data_from_interface()\n for d in source_data:\n s = d.decode('utf-8')\n search = re.match(r'air pressure:(.*)\\s*force:(.*)\\s*displacement:(.*)\\s*', s, re.M | re.I)\n if search:\n print(search.group(1))\n print(search.group(2).strip())\n print(search.group(3).strip())\n","sub_path":"data_source/Interface.py","file_name":"Interface.py","file_ext":"py","file_size_in_byte":2026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"248448795","text":"import tracemalloc\nimport gc\nimport aiormq\nimport pamqp\nimport pytest\n\nimport aio_pika\n\n\n@pytest.fixture(autouse=True)\ndef memory_tracer():\n tracemalloc.start()\n tracemalloc.clear_traces()\n\n filters = (\n tracemalloc.Filter(True, aiormq.__file__),\n tracemalloc.Filter(True, pamqp.__file__),\n tracemalloc.Filter(True, aio_pika.__file__),\n )\n\n snapshot_before = tracemalloc.take_snapshot().filter_traces(filters)\n\n try:\n yield\n\n gc.collect()\n\n snapshot_after = tracemalloc.take_snapshot().filter_traces(filters)\n\n top_stats = snapshot_after.compare_to(\n snapshot_before, 'lineno', cumulative=True\n )\n\n assert not top_stats\n finally:\n tracemalloc.stop()\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"432668359","text":"from pl.edu.agh.neural.Layers import Layers\nfrom pl.edu.agh.neural.gui.creator.LayerModel import LayerModel\n\nclass NetworkModel(object):\n DEFAULT_NEURONS_COUNT = 2\n DEFAULT_INPUT_NEURONS_COUNT = 2\n\n def __init__(self, minWeight=0.0, maxWeight=1.0, empty=False):\n self.input_neurons = NetworkModel.DEFAULT_INPUT_NEURONS_COUNT\n self.layers_data = []\n self.minWeight = minWeight\n self.maxWeight = maxWeight\n if not empty:\n self.add_layer()\n\n def layers(self):\n return self.layers_data\n\n def add_layer(self):\n layer_name = self._layer_name(len(self.layers_data) + 1)\n input_neurons = self.input_neurons\n if len(self.layers_data) != 0:\n input_neurons = self.layers_data[-1].rowCount()\n layer_model = LayerModel(layer_name, Layers.default_layer(), NetworkModel.DEFAULT_NEURONS_COUNT, input_neurons,\n self.minWeight,\n self.maxWeight)\n self.layers_data.append(layer_model)\n return layer_model\n\n def remove_layer(self):\n del self.layers_data[-1]\n\n def set_network_input_neurons(self, neurons_number):\n self.input_neurons = neurons_number\n if len(self.layers_data) != 0:\n self.layers_data[0].set_input_neurons(neurons_number)\n\n def set_neurons_for_layer(self, layer_index, neurons_number):\n self.layers_data[layer_index].set_neurons(neurons_number)\n if layer_index != len(self.layers_data) - 1:\n self.layers_data[layer_index + 1].set_input_neurons(neurons_number)\n\n def layer_model(self, layer_number):\n return self.layers_data[layer_number]\n\n def default_layer(self):\n return self.layers_data[0]\n\n def network_inputs(self):\n return self.input_neurons\n\n def _layer_name(self, layer_number):\n return str(layer_number) + \" layer\"\n\n def set_min_random_weights(self, value):\n self.minWeight = value\n\n def set_max_random_weights(self, value):\n self.maxWeight = value\n\n @staticmethod\n def from_network(network):\n model = NetworkModel(empty=True)\n model.set_network_input_neurons(network.inputs_count())\n for layer in network.get_layers():\n layer_model = model.add_layer()\n neurons = layer.get_neurons()\n layer_model.set_layer_type(Layers.get_type(layer))\n layer_model.set_neurons(len(neurons))\n for neuron_index in range(len(neurons)):\n neuron = neurons[neuron_index]\n layer_model.set_psp_for_neuron(neuron_index, neuron.get_psp().NAME)\n layer_model.set_activation_for_neuron(neuron_index, neuron.get_activator().NAME)\n layer_model.set_bias_for_neuron(neuron_index, neuron.get_bias().get_weight())\n inputs = neuron.get_inputs()\n for input_index in range(len(inputs)):\n layer_model.set_weight_for_connection(neuron_index, input_index,\n round(neuron.get_input_edge(input_index).get_weight(), 3))\n return model\n","sub_path":"NeuralNetwork/pl/edu/agh/neural/gui/creator/NetworkModel.py","file_name":"NetworkModel.py","file_ext":"py","file_size_in_byte":3082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"84392777","text":"class TraductorInterface:\r\n isRunning = False\r\n colaImpresion = []\r\n\r\n def __init__(self, comando, *args):\r\n self.comando = comando\r\n\r\n def run(self, jsonTicket):\r\n actions = jsonTicket.keys()\r\n rta = []\r\n for action in actions:\r\n if action == \"listcommand\":\r\n actionlist = jsonTicket[action]\r\n for action1 in actionlist:\r\n lista2 = action1\r\n for action2 in lista2:\r\n try:\r\n fnAction1 = getattr(self, action2)\r\n if isinstance(lista2[action2], list):\r\n res1 = fnAction1(*lista2[action2])\r\n rta.append({\"action\": action2, \"params\":lista2[action2],\"rta\": res1})\r\n elif isinstance(lista2[action2], dict):\r\n res1 = fnAction1(**lista2[action2])\r\n rta.append({\"action\": action2,\"params\":lista2[action2], \"rta\": res1})\r\n else:\r\n res1 = fnAction1(lista2[action2])\r\n rta.append({\"action\": action2, \"params\":lista2[action2], \"rta\": res1}) \r\n except Exception as e:\r\n reserror = str(e)\r\n rta.append({\"action\": action2, \"params\":lista2[action2], \"err\": reserror})\r\n else:\r\n try:\r\n fnAction = getattr(self, action)\r\n if isinstance(jsonTicket[action], list):\r\n res = fnAction(*jsonTicket[action])\r\n rta.append({\"action\": action, \"params\":jsonTicket[action], \"rta\": res})\r\n\r\n elif isinstance(jsonTicket[action], dict):\r\n res = fnAction(**jsonTicket[action])\r\n rta.append({\"action\": action, \"params\":jsonTicket[action], \"rta\": res})\r\n else:\r\n res = fnAction(jsonTicket[action])\r\n except Exception as e:\r\n reserror = str(e)\r\n rta.append({\"action\": action, \"params\":jsonTicket[action], \"err\": reserror})\r\n return rta\r\n","sub_path":"Traductores/TraductorInterface.py","file_name":"TraductorInterface.py","file_ext":"py","file_size_in_byte":2291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"234478549","text":"import pygame as pg\nimport math\n\nfrom script import image,sound\nfrom script.effect import Effect\n\nclass Bala(pg.sprite.Sprite):\n\tdef __init__(self,point,angle,value,effect):\n\t\t\n\t\tpg.sprite.Sprite.__init__(self)\n\t\tself.image_b = image['bullet_{}'.format(value)]\n\t\tself.image = pg.transform.rotate(self.image_b,angle)\n\t\tself.rect = self.image.get_rect()\n\t\tradians = math.radians(angle)\n\t\tself.rect.x = point[0] + (2 * math.sin(radians)) - self.rect.width//2 \n\t\tself.rect.y = point[1] + (2 * math.cos(radians)) - self.rect.height //2\n\t\t\n\t\tself.vlx = -10 * math.sin(radians)\n\t\tself.vly = -10 * math.cos(radians)\n\t\n\t\tself.angle = angle\n\t\tself.effect = effect\n\n\tdef update(self):\n\t\t#Eliminar balas que chocan entre si\n\t\t\t\n\t\tself.rect.x +=self.vlx\n\t\tself.rect.y += self.vly\n\n\tdef explosion(self):\n\t\tframes = {\n\t\t\t0:(0,0),\n\t\t\t1:(0,14),\n\t\t\t2:(0,28),\n\t\t\t3:(0,42),\n\t\t}\n\t\tself.point_ball = ((self.rect.centerx,self.rect.centery))\n\n\t\teffect = Effect(self.point_ball,\n\t\t\t\t\t\tself.angle,\n\t\t\t\t\t\tframes,(14,14),\n\t\t\t\t\t\timage['explosion'])\n\n\t\tself.effect.add(effect)\n\t\t\n\t\tself.kill()\n\n\nclass Cannon:\n\tdef __init__(self):\n\t\tself.cont = 10\n\t\tself.fire = False\n\t\tself.load = False\n\n\t\tself.effect_frames = {\n\t\t\t\t0:(0,0),\n\t\t\t\t1:(0,15),\n\t\t\t\t2:(0,30),\n\t\t\t\t3:(0,45),\n\t\t\t\t4:(0,60),\n\t\t\t}\n\n\tdef update_cannon(self,automatico = False):\n\t\t\n\t\tself.effect.update()\n\t\tself.bullets.update()\n\n\t\tif self.gun != True:\n\n\t\t\tlimit = 10\n\n\t\t\tif self.cont < limit: \n\t\t\t\tself.cont +=1\n\t\t\t\tself.fire = False\n\t\t\telse: \n\t\t\t\tself.load = True\n\t\t\n\t\t#Arma 2 con tiempo de cargar menor\n\n\t\telse:\n\t\t\tlimit = 20\n\t\t\tif self.cont < limit: \n\t\t\t\tself.cont +=1\n\t\t\t\tself.fire = False\n\t\t\telse: \n\t\t\t\tself.load = True\n\n\t\tif (self.fire == True and self.cont >= 10 \n\t\t\tor automatico == True and self.cont >= 40):\n\t\t\t\n\t\t\t# Codigo cutre, lo voy a mejorar pronto, lo prometo.\n\t\t\t#bueno tal vez no xD.\n\t\t\t#Bueno, medio lo hice, por ahora no importa mucho\n\t\t\t\n\t\t\tif self.gun != True:\n\t\t\t\tself.queue_shot(1)\n\t\t\telse:\n\t\t\t\tself.queue_shot(2)\n\n\tdef queue_shot(self,queue):\n\t\tpos_gun = 0\n\n\t\t\"\"\"Cantidad de balas que se disparan al mismo tiempo\"\"\"\n\t\tfor i in range(queue):\n\n\t\t\tif queue > 1:\n\t\t\t\tif i == 0:\n\t\t\t\t\tpos_gun -= 10\n\t\t\t\telif i > 0:\n\t\t\t\t\tpos_gun +=20\n\n\t\t\tself.point_ball = ((self.rect.centerx - \n\t\t\t\t\t\t\t\tpos_gun,\n\t\t\t\t\t\t\t\tself.rect.centery-pos_gun))\n\t\t\t\n\t\t\tsound['shot'].stop()\n\t\t\tsound['shot'].play()\n\t\t\t\n\t\t\tself.effect.add(Effect(self.point_ball,\n\t\t\t\t\t\t\t\t\t\tself.angle,\n\t\t\t\t\t\t\t\t\t\tself.effect_frames,\n\t\t\t\t\t\t\t\t\t\t(16,15),image['wave_shot']))\n\n\t\t\tself.bullets.add(Bala(self.point_ball,\n\t\t\t\t\t\t\t\t\t\tself.angle,\n\t\t\t\t\t\t\t\t\t\tself.value,\n\t\t\t\t\t\t\t\t\t\tself.effect\n\t\t\t\t\t\t\t\t\t\t))\n\n\n\t\tself.load = False\n\t\tself.cont = 0\n\nif __name__ == '__main__':\n\tpass \n","sub_path":"script/cannon.py","file_name":"cannon.py","file_ext":"py","file_size_in_byte":2663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"112954810","text":"def listSum(numList):\n if len(numList) == 1:\n return numList[0]\n else:\n return numList[0] + listSum(numList[1:])\n\n\nif __name__ == \"__main__\":\n print(\"The sum of [1, 2, 3, 4, 5] is:\")\n print(listSum([1, 2, 3, 4, 5]))\n\n# Overview: In the above code we are simply breaking down the amount of work each time #\n# We end up calling:\n# sum(1,2,3,4,5) = 1 +\n# sum (2,3,4,5) = 2 +\n# sum (3,4,5) = 3 +\n# sum(4,5) = 4 +\n# sum(5) = 5\n","sub_path":"Recursion/CalculateTheSumOfListOfNumbers.py","file_name":"CalculateTheSumOfListOfNumbers.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"270619969","text":"import gym\n\nimport torch\nfrom torch import nn, optim\n\nfrom rl.agents import REINFORCE\nfrom rl.env import GymEnv\nfrom rl import nn as rlnn\n\n\nclass Agent(REINFORCE):\n def __init__(self, nb_actions):\n width = 48\n feature = nn.Sequential(\n nn.Linear(2, width),\n nn.ELU(),\n )\n policy = nn.Sequential(\n nn.Linear(width, nb_actions),\n )\n value = nn.Sequential(\n nn.Linear(width, 1),\n )\n params = [\n {'params': feature.parameters()},\n {'params': policy.parameters()},\n {'params': value.parameters()},\n ]\n optimizer = optim.Adam(params)\n super().__init__(policy=policy, value=value, feature=feature,\n optimizer=optimizer, gamma=1.)\n\n def preprocess_state(self, state):\n return state.float()\n\n\ndef create_example():\n env = GymEnv(gym.make('MountainCar-v0'), max_steps=200)\n agent = Agent(env.nb_actions)\n settings = {}\n return agent, env, settings\n","sub_path":"examples/reinforce/reinforce.py","file_name":"reinforce.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"191470403","text":"from flask import Flask, request, json, jsonify\napp = Flask(__name__)\n\nimport sys\nsys.path.append('.')\nfrom user import User\n\n@app.route(\"/hello\", methods=['GET'])\ndef hello():\n return \"world\"\n\n@app.route(\"/users//money\", methods=['GET'])\ndef money(id):\n rows = User.money(id)\n total = 0\n for row in rows:\n total += row[2]\n t = {'total': str(total)}\n print(t)\n return jsonify(t=t)\n\n@app.route(\"/sum\", methods=['POST'])\ndef sum():\n data = request.get_json()\n x = int(data['x'])\n y = int(data['y'])\n data['sum'] = x + y\n return jsonify(data=data)\n\nif __name__ == \"__main__\":\n app.run(debug=True, host='0.0.0.0')\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"283406033","text":"import requests\nimport json\nimport os\nimport sys\nimport argparse\n\n# get_player_json\n#\n# Returns the raw json of the player's stats from the API\ndef get_player_json(player):\n url = \"https://pubgtracker.com/api/profile/pc/%s\" % (player)\n headers = {'TRN-Api-Key': os.environ[\"PUBG_API_KEY\"]}\n r = requests.get(url, headers=headers)\n\n # The server returns a 500 if the player isn't found, so if we\n # see a 500 this is the most likely problem.\n if r.status_code != 200:\n print(\"Player %s not found. Please enter a valid player.\" % (player))\n sys.exit(1)\n return r.json()\n\n# parse_player_stats\n#\n# This turns the json stats list into a convenient\n# dictionary with the stat name as the key.\n#\n# input:\n# player_stats_raw: the player stats as a list of attributes\n#\n# output:\n# a stats dictionary with the stat name as the key and\n# the stat value as the value\ndef parse_player_stats(player_stats_raw):\n player_stats = {}\n for stat in player_stats_raw:\n stat_name = stat[\"field\"]\n stat_value = stat[\"value\"]\n player_stats[stat_name] = stat_value\n return player_stats\n\n# get_player_stats\n#\n# This gets the dictionary of a player's stats given the match_type and\n# region.\n#\n# inputs:\n# player_json: the json stats for the player\n# match_type: the type of match\n# region: the region for the stats\n#\n# output:\n# A dictionary of the player's stats\ndef get_player_stats(player_json, match_type, region):\n for stats_meta in player_json[\"Stats\"]:\n if stats_meta[\"Match\"] == match_type and stats_meta[\"Region\"] == region:\n player_stats_raw = stats_meta[\"Stats\"]\n return parse_player_stats(player_stats_raw)\n\n# Pretty prints the result into columns and rows while filtering\n# out unwanted stats\ndef pretty_print_stats(all_players, stats):\n print(\"Player\\t\", end='')\n for stat in stats:\n print(\"%20s\\t\" % (stat), end='')\n print(\"\")\n for player, player_stats in all_players.items():\n print(\"%s\\t\" % player, end='')\n for stat in stats:\n print(\"%20s\\t\" % player_stats[stat], end='')\n print(\"\")\n\n# Parse the arguments to get players to compare\nparser = argparse.ArgumentParser()\nparser.add_argument(\"players\", nargs=\"+\")\nargs = parser.parse_args()\n\nregion = \"agg\"\nmatch_type = \"solo\"\nstats = [\"KillDeathRatio\",\"WinRatio\",\"Rating\"]\n\nall_stats = {}\n\nfor player in args.players:\n player_json = get_player_json(player)\n all_stats[player] = get_player_stats(player_json, match_type, region)\n\npretty_print_stats(all_stats, stats)\n","sub_path":"compare.py","file_name":"compare.py","file_ext":"py","file_size_in_byte":2573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"466417877","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nimport sqlite3\n# import os.path\n\n# Создание своего исключения\nclass Error(Exception):\n\tpass\nclass NotFound(Error):\n\tpass\n\ndef create():\n\t'''Create new Document'''\n\treturn Document(status = Document.New)\n\ndef load(id):\n\t'''Load document from database'''\n\tDoc = Document(id = id)\n\tDoc.restore()\n\treturn Doc\n\nclass Document(object):\n\tNew = 1\n\tStatus_Allowed = [New]\n\n\tdef __init__(self, **kwargs):\n\t\tif \"id\" in kwargs:\n\t\t\tself.__Id = kwargs[\"id\"]\n\t\t\tdel kwargs[\"id\"]\n\t\tif \"status\" in kwargs:\n\t\t\tif kwargs[\"status\"] not in Document.Status_Allowed:\n\t\t\t\traise ValueError\n\t\t\tself.__Status = kwargs[\"status\"]\n\t\t\tdel kwargs[\"status\"]\n\t\tself.__Others = {}\n\t\tfor (keys, value) in kwargs.items():\n\t\t\tself.__Others[keys] = value\n\t\n\tdef __getattribute__(self, name):\n\t\tif name[0] != \"_\":\n\t\t\treturn super(Document, self).__getattribute__(name)\n\t\tif \"__\" in name:\n\t\t\treturn super(Document, self).__getattribute__(name)\n\t\tif name in self.__dict__:\n\t\t\treturn super(Document, self).__getattribute__(name)\n\t\tif name in type(self).__dict__:\n\t\t\treturn super(Document, self).__getattribute__(name)\n\n\t\tfor base in type(self).__bases__:\n\t\t\tif name in base.__dict__:\n\t\t\t\treturn super(Document, self).__getattribute__(name)\n\n\t\tName = name[1:]\n\t\ttry:\n\t\t\treturn super(Document, self).__getattribute__(Name)\n\t\texcept AttributeError as Exc:\n\t\t\tif (\"'%s'\" % Name) in str(Exc):\n\t\t\t\traise\n\t\t\treturn None\n\n\tid = property(lambda self: self.__Id)\n\tstatus = property(lambda self: self.__Status)\n\n\t# Два подчекивания метод класса\n\t# Одно подчеркивания метод класса виден в наследующих клаcсах\n\t\n\t# @property\n\t# def _id(self):\n\t# \ttry:\n\t# \t\treturn self.id\n\t# \texcept AttributeError:\n\t# \t\treturn None\n\n\t# @property\n\t# def status(self):\n\t# \treturn self.__Status\n\n\t# @status.setter\n\t# def status(self, value):\n\t# \tself.__Status = value\n\t# \tif self.__Status == None:\n\t# \t\tdel self.__Status\n\n\t# @property\n\t# def _status(self):\n\t# \ttry:\n\t# \t\treturn self.status\n\t# \texcept AttributeError:\n\t# \t\treturn None\n\n\t@staticmethod\n\t# def connect(self):\n\tdef connect():\n\t\t# conn = sqlite3.connect(os.path.expanduser(\"~/data.db\"))\n\t\tpath = \"data.db\"\n\t\treturn sqlite3.connect(path)\n\n\tdef _save(self, conn):\n\t\t\tcurr = conn.cursor()\n\t\t\ttry:\n\t\t\t\tcurr.execute('''\n\t\t\t\t\tupdate t_document\n\t\t\t\t\t\tset f_status = ?\n\t\t\t\t\t\twhere i_id = ?\n\t\t\t\t''', (self._status, self.id))\n\t\t\texcept AttributeError:\n\t\t\t\tcurr.execute(\"insert into t_document(f_status) values (?)\", (self._status,))\n\n\t\t\t\tcurr.execute(\"select max(i_id) from t_document\")\n\n\t\t\t\tfor(id) in curr:\n\t\t\t\t\tself.__Id = id\n\n\tdef save(self):\n\t\twith Document.connect() as conn:\n\t\t\tself._save(conn)\n\n\tdef restore(self):\n\t\twith Document.connect() as conn:\n\t\t\tcurr = conn.cursor()\n\t\t\tcurr.execute(\"select f_status from t_document where i_id = ?\", (self.id,))\n\n\t\t\tfor (status,) in curr:\n\t\t\t\tself.__Status = status\n\t\t\t\tif self.__Status == None:\n\t\t\t\t\tdel self.__Status\n\t\t\t\treturn\n\t\t\traise NotFound()\n\t\n\t# @staticmethod\n\t# def create_table(self):\n\t@classmethod\n\tdef create_table(self):\n\t\twith Document.connect() as conn:\n\t\t\tcurr = conn.cursor()\n\t\t\tcurr.execute('''\n\t\t\t\tcreate table t_document(\n\t\t\t\t\ti_id integer not null primary key autoincrement,\n\t\t\t\t\tf_status integer null,\n\t\t\t\t\tf_kind integer null\n\t\t\t\t);\n\t\t\t''')\n\nif __name__ == \"__main__\":\n\tDoc = create()\n\tprint(\"Status \", Doc.status)\n\ttry:\n\t\tprint(\"ID = \", Doc.id)\n\texcept AttributeError:\n\t\tprint(\"\")\n\n\tDoc = load(id = 1)\n\ttry:\n\t\tprint(\"Status = \", Doc.status)\n\texcept AttributeError:\n\t\tprint(\"\")\n\ttry:\n\t\tprint(\"ID = \", Doc.id)\n\texcept AttributeError:\n\t\tprint(\"\")\n\n\tDoc = load(id = \"123\")\n\ttry:\n\t\tprint(\"Status = \", Doc.status)\n\texcept AttributeError:\n\t\tprint(\"\")\n\ttry:\n\t\tprint(\"ID = \", Doc.id)\n\texcept AttributeError:\n\t\tprint(\"\")","sub_path":"two/mDocument.py","file_name":"mDocument.py","file_ext":"py","file_size_in_byte":3837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"353461256","text":"from datetime import datetime\nfrom airflow import DAG\nfrom airflow.operators.dummy_operator import DummyOperator\nfrom airflow.operators.python_operator import PythonOperator\n\nimport invest_dw as idw\nimport invest_dw.database_etl as etl\nimport invest_dw.database_io as dio\nimport invest_dw.finviz as fin\nimport pandas as pd\n\n\ninvest_dw_dir = '/home/haizui/Documents/GIT/github/invest-dw'\nconfig_dir = invest_dw_dir + '/config_mysql.ini'\n\n\ndef load_finviz_table(screener_table_name, target_table_name = None):\n if target_table_name is None:\n target_table_name = screener_table_name\n \n columns, table = fin.screenerTable(screener_table_name, page_max=3)\n\n print('Saving data to database')\n config = dio.readConfig(config_dir)\n \n data_pd = pd.DataFrame(data=table, columns=columns)\n etl.writeTablePrestage(config, data_pd, screener_table_name)\n \n etl.loadTableHash(config\n , 'prestage'\n , screener_table_name\n , 'stage'\n , 'finviz_'+target_table_name\n , hash_column = 'Sha256'\n , truncate_target = True)\n\n etl.loadTableSCD(config\n , 'stage'\n , 'finviz_'+target_table_name\n , 'finviz'\n , target_table_name\n , hash_column='Sha256') \n\ndef load_finviz_price():\n load_finviz_table(screener_table_name='valuation', target_table_name='price') \n return 'Done'\n\ndag = DAG('load_finviz_prices_dag', description='Load stock prices from Finviz',\n schedule_interval='*/5 * * * *', # Every 5 minutes\n start_date=datetime(2018, 10, 29), catchup=False)\n\ndummy_operator = DummyOperator(task_id='dummy_task', dag=dag)\nprice_operator = PythonOperator(task_id='load_finviz_prices_task', python_callable=load_finviz_price, dag=dag)\ndummy_operator >> price_operator\n\n","sub_path":"airflow/dags/load_prices.py","file_name":"load_prices.py","file_ext":"py","file_size_in_byte":1915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"210253347","text":"from fuzzywuzzy import process, fuzz\n\n\ndef match_by_fuzzy_string_search(\n possible_matches: List[str], string_to_be_searched: str\n) -> str:\n scores = dict()\n for candidate in possible_matches:\n n = len(candidate.split())\n n_grams = generate_ngrams(string_to_be_searched, n)\n for n_gram in n_grams:\n possible_match, score = process.extractOne(\n n_gram, possible_matches, scorer=fuzz.ratio\n )\n old_score = scores.get(possible_match, 0)\n if score > old_score:\n scores[possible_match] = score\n\n if scores:\n most_possible_match = max(scores, key=scores.get)\n most_score = scores.get(most_possible_match)\n if most_score > 80:\n return most_possible_match\n\n return \"\"\n","sub_path":"gist/python/text/fuzzy.py","file_name":"fuzzy.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"557947299","text":"#install dependencies\r\nimport os\r\nimport argparse\r\nimport logging\r\nimport re\r\nfrom apache_beam.options.pipeline_options import PipelineOptions\r\nimport apache_beam as beam\r\n\r\nos.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = r\"C:\\Users\\jerem\\Desktop\\yelp_capstone_project\\key_auth_4.json\"\r\n\r\nclass dataingestion:\r\n\r\n def parse_method(self, string_input):\r\n\r\n # Strip out carriage return, newline and quote characters.\r\n values = re.split(\",\", re.sub('\\r\\n', '', re.sub('\"', '', string_input)))\r\n row = dict(\r\n zip(('year', 'state', 'month', 'number', 'date'),\r\n values))\r\n return row\r\n\r\ndef run():\r\n\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('--input',dest='input',\r\n required=False,\r\n help='Input file to read. This can be a local file or '\r\n 'a file in a Google Storage Bucket.',\r\n default='gs://data_project_6_amazon/amazon.csv' )\r\n parser.add_argument('--output',\r\n dest='output',\r\n required=False,\r\n help='Output BQ table to write results to.',\r\n default='amazon.amazoned_raw_data')\r\n parser.add_argument('--project', dest='project', required=False, help='Project name', default='decent-beacon-367514',\r\n action=\"store\")\r\n parser.add_argument('--bucket_name', dest='bucket_name', required=False, help='bucket name',\r\n default='dataflow_python_test')\r\n parser.add_argument('--runner', dest='runner', required=False, help='Runner Name', default='DataflowRunner',\r\n action=\"store\")\r\n parser.add_argument('--jobname', dest='job_name', required=False, help='jobName', default='etl3',\r\n action=\"store\")\r\n parser.add_argument('--staging_location', dest='staging_location', required=False, help='staging_location',\r\n default='gs://data_project_amazon_staging/staging/')\r\n parser.add_argument('--region', dest='region', required=False, help='Region', default='us-west1',\r\n action=\"store\")\r\n parser.add_argument('--temp_location', dest='temp_location', required=False, help='temp location',\r\n default='gs://data_project_amazon_staging/temp/')\r\n\r\n\r\n args = parser.parse_args()\r\n\r\n pipeline_options = {\r\n 'project': args.project,\r\n 'staging_location': args.staging_location,\r\n 'runner': args.runner,\r\n 'job_name': args.job_name,\r\n 'region': args.region,\r\n 'output': args.output,\r\n 'input': args.input,\r\n 'temp_location': args.temp_location}\r\n print(pipeline_options)\r\n pipeline_options_val = PipelineOptions.from_dictionary(pipeline_options)\r\n p = beam.Pipeline(options=pipeline_options_val)\r\n data_ingestion = dataingestion()\r\n\r\n (p | 'Read from a File' >> beam.io.ReadFromText(pipeline_options[\"input\"], skip_header_lines=1)\r\n | 'String To BigQuery Row' >> beam.Map(lambda s: data_ingestion.parse_method(s)) |\r\n 'Write to BigQuery' >> beam.io.Write(\r\n beam.io.WriteToBigQuery(\r\n pipeline_options[\"output\"],\r\n schema='year:STRING,state:STRING,month:STRING,number:STRING,date:STRING',\r\n create_disposition=beam.io.BigQueryDisposition.CREATE_IF_NEEDED,\r\n write_disposition=beam.io.BigQueryDisposition.WRITE_TRUNCATE)))\r\n p.run().wait_until_finish()\r\n\r\n#BigQuerySink\r\n\r\n\r\nif __name__ == '__main__':\r\n logging.getLogger().setLevel(logging.INFO)\r\n run()","sub_path":"data_project_6_pipeline_gcp_raw_data.py","file_name":"data_project_6_pipeline_gcp_raw_data.py","file_ext":"py","file_size_in_byte":3629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"442786191","text":"import logging\nlogging.basicConfig()\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\nlogger.info(\"Loaded \" + __name__)\n\nimport cv2\nfrom .files_cleanup import cleanup\nimport os\nfrom datetime import datetime,timedelta\nimport csv\nimport traceback\nimport time\n\nclass VideoManager(object):\n def __init__(self, filename, fourcc, fps, frameSize=None,limit_fps=False, base_dir=\"\",process_dir=None,\n max_sizeMB =0, max_seconds=0, max_period=0,timestamp_filename=True, \n cleanupDays=3, delete=True, annotations = False,annotations_header=None,annotations_extension='.csv'):\n \n self.videow = None\n if type(fourcc) ==str:\n self.fourcc = cv2.VideoWriter_fourcc(*'XVID')\n else:\n self.fourcc = fourcc\n self.fps = fps\n self.frameSize =frameSize\n self.annotations = annotations\n if self.annotations:\n self.annotations_header= annotations_header\n self.annotations_extension= annotations_extension\n self.limit_fps = limit_fps\n\n filename, file_extension = os.path.splitext(filename)\n self.filename = filename\n self.file_extension =file_extension\n self.max_sizeMB =max_sizeMB\n self.max_seconds = max_seconds\n self.max_period= max_period\n self.cleanupDays = cleanupDays\n self.cleanup_delete = delete\n \n\n if timestamp_filename:\n self.filename_pattern = '%s-%s%s'%(self.filename, '{}', self.file_extension)\n if self.annotations:\n self.filename_pattern_annotations = '%s-%s%s'%(self.filename, '{}', self.annotations_extension)\n self.cleanup_pattern = '.*%s-%s%s'%(self.filename, '.*', self.file_extension)\n else:\n self.filename_pattern = '%s%s'%(self.filename, self.file_extension)\n if self.annotations:\n self.filename_pattern_annotations = '%s-%s'%(self.filename, self.annotations_extension)\n self.cleanup_pattern = '.*%s%s'%(self.filename, self.file_extension)\n \n if base_dir:\n self.filename_pattern = os.path.join(base_dir, self.filename_pattern)\n if self.annotations:\n self.filename_pattern_annotations = os.path.join(base_dir,self.filename_pattern_annotations)\n self.base_dir = base_dir\n else:\n self.base_dir = os.path.dirname(self.filename)\n \n if process_dir is None:\n process_dir=self.base_dir\n \n self.process_dir=process_dir\n # If directory not present-create it \n if not os.path.exists(self.base_dir):\n os.makedirs(self.base_dir)\n if not os.path.exists(self.process_dir):\n os.makedirs(self.process_dir)\n \n \n self.unprocessed_vids=[]\n self.cap=None\n self.processTime=datetime.now()\n\n \n def clock(self):\n return cv2.getTickCount() / cv2.getTickFrequency()\n\n def writeAnnotationHeader(self):\n with open(self.aname,'a') as file :\n writer = csv.writer(file)\n writer.writerow(self.annotations_header)\n\n def writeAnnotations(self,annotations):\n with open(self.aname,'a') as file :\n writer = csv.writer(file)\n for annotation in annotations:\n annotation.insert(0,str(self.current_framecount))\n writer.writerow(annotation)\n \n def write(self, imgcv, annotations = None):\n ### initilize video writer object\n new_video = False\n if self.videow is None:\n \n # Cleanup old files to recover disk space\n cleanup(self.cleanupDays, path=self.base_dir, pattern=self.cleanup_pattern, delete=self.cleanup_delete)\n # Start new recording\n datestr = datetime.now().strftime(\"%d-%m-%y-%H:%M:%S\")\n self.vname = self.filename_pattern.format(datestr)\n if self.annotations:\n self.aname=self.filename_pattern_annotations.format(datestr)\n logger.info('Annotations file created - %s', self.aname)\n self.writeAnnotationHeader()\n self.videow = cv2.VideoWriter(self.vname, self.fourcc, int(self.fps), self.frameSize)\n self.videoStartTime=time.time()\n logger.info('Video Opened - %s', self.vname)\n # Frame Count and fps calculation variable init\n self.current_framecount = 0\n self.timer = 0\n new_video = True\n self.last_time=self.clock()\n \n writing = False\n ### write frame with desired fps\n if self.timer == 0:\n if len(imgcv.shape) == 2:\n imgcv = cv2.cvtColor(imgcv, cv2.COLOR_GRAY2BGR)\n \n if (imgcv.shape[1],imgcv.shape[0]) != self.frameSize:\n imgcv = cv2.resize(imgcv,self.frameSize)\n if self.annotations and annotations is not None:\n self.writeAnnotations(annotations)\n \n self.videow.write(imgcv)\n writing = True,\n self.current_framecount+=1\n if self.limit_fps:\n self.timer = self.clock() - self.last_time \n if self.timer > 1.0/self.fps:\n self.timer = 0\n self.last_time=self.clock()\n\n if (self.max_sizeMB and os.path.getsize(self.vname)/1000000 > self.max_sizeMB):\n self.videow.release()\n self.videow = None\n with open(\"{}.released\".format(self.vname), 'w') as outfile:\n logger.info('Video Release after %d MB - %s', self.max_sizeMB, self.vname) \n elif self.max_seconds and self.current_framecount > self.max_seconds * self.fps:\n self.videow.release()\n self.videow = None\n with open(\"{}.released\".format(self.vname), 'w') as outfile:\n logger.info('Video Release after %d seconds - %s', self.max_seconds, self.vname) \n \n elif self.max_period and time.time()-self.videoStartTime > self.max_period:\n self.videow.release()\n self.videow = None\n with open(\"{}.released\".format(self.vname), 'w') as outfile:\n logger.info('Video Release after period of %d secons - %s', self.max_period, self.vname) \n \n\n if new_video:\n return self.vname, self.current_framecount-1, writing\n else:\n return None, self.current_framecount-1, writing\n\n def release(self):\n ret = self.videow.release()\n self.videow = None\n return ret\n \n # Method to get unprocessed videos\n # Videos which are released but not read\n def get_unprocessed_videos(self):\n videos=[]\n print(\"looking in \",self.base_dir)\n for root, dirs, files in os.walk(self.base_dir):\n #print(path)\n for name in files:\n if name.endswith((\".mp4\",\".avi\")):\n #Check if released\n file_released=\"{}/{}.released\".format(self.base_dir,name)\n file_processed=\"{}/{}.processed\".format(self.process_dir,name)\n \n if os.path.isfile(file_released) and not os.path.isfile(file_processed):\n videos.append(\"{}/{}\".format(root,name))\n \n videos=sorted(videos)\n print(videos)\n return videos\n \n def get_process_time(self):\n return self.processTime \n \n def read(self):\n try:\n if self.cap is None:\n while len(self.unprocessed_vids)==0:\n #import pdb;pdb.set_trace()\n self.unprocessed_vids= self.get_unprocessed_videos()\n if len(self.unprocessed_vids) ==0:\n logger.info(\"no videos for processing..sleeping for 60 sec\")\n time.sleep(5)\n else:\n break\n \n self.processVid=self.unprocessed_vids.pop(0)\n logger.info(\"processing video-{}\".format(self.processVid))\n self.cap= cv2.VideoCapture(self.processVid)\n self.frameCount=0\n self.timeStampStr=self.processVid[-21:-4]\n self.startTime = datetime.strptime(self.timeStampStr, \"%d-%m-%y-%H:%M:%S\")\n \n self.frameCount +=1\n self.processTime = self.startTime + timedelta(seconds=self.frameCount/self.fps) \n #print(\"process time\",str(self.processTime))\n ret,img = self.cap.read()\n if ret:\n return ret,img\n else:\n self.cap.release()\n self.cap=None\n vidName=self.processVid[len(self.base_dir):]\n processFileName=\"{}/{}.processed\".format(self.process_dir,vidName)\n with open(processFileName, 'w') as outfile:\n logger.info(\"Video processed complete-{}\".format(self.processVid)) \n return self.read()\n except Exception as e:\n logger.info(\"Exception occured while reading from videos -{}\".format(str(e)))\n logger.info(traceback.format_exc())\n return 0, None\n \n \nif __name__ == '__main__':\n manager = VideoManager(filename='test.avi',\n fourcc = 'XVID',\n fps = 30,\n frameSize = (640,480),\n base_dir = '/Users/saurabh_veda/workspace_kumar/test_videos',\n max_sizeMB = 500,\n max_seconds= 60,\n cleanupDays = 1)\n \n while True:\n ret,img=manager.read()\n if ret:\n cv2.imshow(\"vid\",img)\n cv2.waitKey(1)","sub_path":"common/videoManager.py","file_name":"videoManager.py","file_ext":"py","file_size_in_byte":9964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"194487215","text":"# -*- coding: utf-8 -*-\n\nfrom model.contact import Contact\nimport random\n\ndef test_edit_contact(app, db, check_ui):\n contact_ = Contact(firstname = \"Иванов\", middlename = \"Иванович\", lastname = \"Иванов\", company = \"Компания\",\n address = \"Адрес\", home = \"+1234124214\", mobile = \"+345345345\", work = \"+32423435\", fax = \"+2342343254\", email = \"jkhj@jhjk.sfd\",\n email2 = \"gfgh@sdf.sdf\", email3 = \"bhjg@sdf.sdf\", homepage = \"https://translate.google.ru/\", notes = \"комментарий\",\n address2 = \"Второй адрес\", new_group = \"Name1\", bday = \"1\", bmonth = \"January\", byear = \"1988\", aday = \"2\", amonth = \"March\", ayear = \"1989\")\n if app.contact.count() == 0:\n app.contact.create(contact_)\n old_contacts = db.get_contact_list()\n contact = random.choice(old_contacts)\n contactNew = Contact(firstname = \"И\", middlename=\"O\", lastname=\"Ф\",\n company=\"asda\",\n address=\"\", home=\"\", mobile=\"\", work=\"\",\n fax=\"\", email=\"\",\n email2=\"\", email3=\"\",\n homepage=\"\", notes=\"\",\n address2=\"\", new_group=\"[none]\", bday=\"-\", bmonth=\"-\",\n byear=\"\", aday=\"-\", amonth=\"-\", ayear=\"\")\n contactNew.id = contact.id\n app.contact.edit_contact_by_id(contact.id, contactNew)\n new_contacts = db.get_contact_list()\n assert len(old_contacts) == app.contact.count()\n old_contacts.append(contactNew)\n old_contacts.remove(contact)\n assert old_contacts == new_contacts\n if check_ui:\n assert sorted(new_contacts, key=Contact.id_or_max) == sorted(app.contact.get_contact_list(),\n key=Contact.id_or_max)\n\n\n\n\n\n","sub_path":"test/test_edit_contact.py","file_name":"test_edit_contact.py","file_ext":"py","file_size_in_byte":1989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"354788504","text":"\"\"\"\nHarvester of pubmed for the SHARE notification service\n\"\"\"\n\n\nfrom __future__ import unicode_literals\n\nfrom scrapi.base import schemas\nfrom scrapi.base import helpers\nfrom scrapi.base import OAIHarvester\n\n\ndef oai_extract_url_pubmed(identifiers):\n identifiers = [identifiers] if not isinstance(identifiers, list) else identifiers\n for item in identifiers:\n try:\n found_url = helpers.URL_REGEX.search(item).group()\n if 'viewcontent' not in found_url and '/pubmed/' in found_url:\n return found_url.decode('utf-8')\n except AttributeError:\n continue\n\n\nclass PubMedHarvester(OAIHarvester):\n short_name = 'pubmed'\n long_name = 'PubMed Central'\n url = 'http://www.ncbi.nlm.nih.gov/pmc/'\n\n schema = helpers.updated_schema(\n schemas.OAISCHEMA,\n {\n \"uris\": {\n \"canonicalUri\": ('//dc:identifier/node()', oai_extract_url_pubmed)\n }\n }\n )\n\n base_url = 'http://www.pubmedcentral.nih.gov/oai/oai.cgi'\n property_list = [\n 'type', 'source', 'publisher', 'rights',\n 'format', 'setSpec', 'date', 'identifier'\n ]\n","sub_path":"scrapi/harvesters/pubmed.py","file_name":"pubmed.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"573904377","text":"\ndef update_data(attrname, old, new):\n\n # Get the current slider values\n M = M_slider.value * 2.e33\n f = f_slider.value\n v = v_slider.value * 1.e5\n k = k_slider.value\n t = t_original\n tn = 8.8\n B = 13.8\n c = 3*(10**10)\n E = 3.9*(10**10)\n td = (((2.*k*M)/(B*c*v))**(1./2.))/60./60./24.\n integrand = (t/td)*(np.exp(t**2/td**2))*(np.exp(-t/tn))\n my_int = integrate.cumtrapz(integrand,t, initial = 0)\n L = ((2.*M*f)/(td)) * (np.exp((-t**2)/td**2)) * E * my_int\n magnitude = -2.5*np.log10(L/4e33)+4.3\n radii = v * t * 24*60*60\n temperature = (L/(4*np.pi*(radii**2)*(5.67*10**-5)))**0.25\n county = 0\n wavelength = 5*10**-5\n wavelength_B = 4.45*10**-5\n wavelength_r = 6.58*10**-5\n wavelength_i = 8.06*10**-5\n wavelength_V = 5.51*10**-5\n wavelength_U = 3.65*10**-5\n distance = lumdist * (3*10**24)\n luminosityblackbody = blackbody(radii, temperature, 5.*(10**-5)*np.ones(len(radii))) * wavelength**2 / c / distance**2\n luminosityblackbody_B = blackbody(radii, temperature, 5.*(10**-5)*np.ones(len(radii))) * wavelength_B**2 / c / distance**2\n luminosityblackbody_r = blackbody(radii, temperature, 5.*(10**-5)*np.ones(len(radii))) * wavelength_r**2 / c / distance**2\n luminosityblackbody_i = blackbody(radii, temperature, 5.*(10**-5)*np.ones(len(radii))) * wavelength_i**2 / c / distance**2\n luminosityblackbody_V= blackbody(radii, temperature, 5.*(10**-5)*np.ones(len(radii))) * wavelength_V**2 / c / distance**2\n luminosityblackbody_U = blackbody(radii, temperature, 5.*(10**-5)*np.ones(len(radii))) * wavelength_U**2 / c / distance**2\n magblackbody = -2.5*np.log10(luminosityblackbody)-48.6\n magblackbody_B = -2.5*np.log10(luminosityblackbody_B)-48.6\n magblackbody_r = -2.5*np.log10(luminosityblackbody_r)-48.6\n magblackbody_i = -2.5*np.log10(luminosityblackbody_i)-48.6\n magblackbody_V = -2.5*np.log10(luminosityblackbody_V)-48.6\n magblackbody_U = -2.5*np.log10(luminosityblackbody_U)-48.6\n # Generate the new curve\n L = ((2.*M*f)/(td)) * (np.exp((-t**2)/td**2)) * E * my_int\n magnitude = -2.5*np.log10(L/4e33)+4.3\n\n\n source.data = dict(x=t*(1.+redshift) + T_slider.value, y= magblackbody ,yB = magblackbody_B, yr = magblackbody_r,yi = magblackbody_i, yV = magblackbody_V, yU = magblackbody_U)","sub_path":"all_files/UpdateData.py","file_name":"UpdateData.py","file_ext":"py","file_size_in_byte":2311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"453110954","text":"\"\"\"\r\nNabil Ahmed\r\nID: 25364170\r\nBoyer Moore\r\n\"\"\"\r\n\r\nfrom Zbox_Student import z_b_o_x\r\n\r\n\r\ndef BoyerMoore(text, pat):\r\n \"\"\"\r\n Boyer Moore Algorithm takes a Text and Pattern both of type and does exact pattern matching\r\n of the PAT on the TEXT. It uses the Bad Character Shift rule and the Good Suffix rule to efficiently\r\n shift while matching the pattern with text.\r\n :param text: Type\r\n :param pat: Type\r\n :return: List : Type\r\n \"\"\"\r\n alphabets = [] # My Domain of ASCII characters will be stored in this list(Required for Bad Character)\r\n sub_list = [-1]\r\n for i in range(128):\r\n alphabets.append(sub_list) # Initiating -1 as a sublist to my alphabets list\r\n\r\n print_array = [] # For storing the final result from the Boyer Moore Function\r\n\r\n for letter in range(len(pat)):\r\n alphabets_index = ord(pat[letter])\r\n if alphabets[alphabets_index][0] == -1:\r\n alphabets[alphabets_index].remove(-1)\r\n alphabets[alphabets_index].append(letter)\r\n\r\n zi_val = z_b_o_x(pat) # Z values on my pat\r\n matched_prefix = [] # Matched Prefix Array\r\n\r\n for z in range(len(pat)):\r\n matched_prefix.append(0)\r\n\r\n if zi_val[len(zi_val)-1] == 0:\r\n for i in range(len(zi_val)-2, -1, -1): # start from len - 2\r\n if zi_val[i] + i == len(pat):\r\n matched_prefix[i] = zi_val[i]\r\n else:\r\n matched_prefix[i] = matched_prefix[i + 1]\r\n else: # right most value of zi is not equals to zero\r\n for i in range(len(zi_val)-1, -1, -1): # start from len - 2\r\n if zi_val[i] + i == len(pat):\r\n matched_prefix[i] = zi_val[i]\r\n else:\r\n matched_prefix[i] = matched_prefix[i + 1]\r\n\r\n rev_pat = pat[::-1]\r\n zi_values = z_b_o_x(rev_pat)\r\n\r\n Zi_suffix = []\r\n for i in range(len(zi_values)-1, -1, -1):\r\n Zi_suffix.append(zi_values[i])\r\n\r\n goodsuffix = []\r\n for i in range(len(pat)):\r\n goodsuffix.append(0)\r\n\r\n i = 0\r\n while i < len(pat):\r\n if Zi_suffix[i] != 0:\r\n j = len(pat)- Zi_suffix[i] - 1\r\n goodsuffix[j] = i\r\n i += 1\r\n\r\n for i in range(len(pat), len(text) + 1):\r\n k = i - 1\r\n j = len(pat) - 1\r\n skp = 1 # normally skip by 1\r\n good_suffix_skip = 0\r\n bad_character_skp = 0\r\n while j >= 0:\r\n if text[k] != pat[j]: # if mismatch occurs do Good suffix\r\n if j < len(pat) - 2: # Good Suffix\r\n if goodsuffix[j+1] > 0:\r\n good_suffix_skip = len(pat) - goodsuffix[j+1]\r\n if goodsuffix[j + 1] == 0:\r\n good_suffix_skip = len(pat) - matched_prefix[j + 1]\r\n\r\n # Else:Bad Character:\r\n z = alphabets[ord(text[k])]\r\n for z1 in range(len(z) - 1, -1, -1):\r\n if z[z1] < j:\r\n bad_character_skp = j - z[z1] # if bad character exists count the number of skips\r\n break\r\n\r\n skp = max(good_suffix_skip, bad_character_skp)\r\n break\r\n\r\n j -= 1\r\n k -= 1\r\n\r\n if j == -1: # If there is an exact match\r\n # return k+1 # k + 1 because we want the starting index of the matched pattern\r\n print_array.append(k + 1)\r\n # skp = len(pat) - matched_prefix[1]\r\n i += skp\r\n return print_array\r\n\r\n# print(BoyerMoore(text_1, pat_1))\r\n","sub_path":"q1/Boyer_Moore.py","file_name":"Boyer_Moore.py","file_ext":"py","file_size_in_byte":3579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"540997475","text":"from otree.api import (\n models,\n widgets,\n BaseConstants,\n BaseSubsession,\n BaseGroup,\n BasePlayer,\n Currency as c,\n currency_range,\n)\nimport numpy as np\nimport pandas as pd\nimport random\n\ndoc = \"\"\"\nThis is a coordination game with 4 players.\n\"\"\"\n\n\nclass Constants(BaseConstants):\n name_in_url = 'block1'\n players_per_group = 4\n num_rounds = 10\n\n instructions_template = 'block1/instructions.html'\n instructions_new_template = 'block1/instructions_new.html'\n\n # payoffs if player picks green\"\"\",\n onegreen_payoff = c(0)\n twogreen_payoff = c(0)\n threegreen_payoff = c(0)\n fourgreen_payoff = c(0)\n\n # payoffs if player picks purple\n onepurple_payoff = c(0)\n twopurple_payoff = c(0)\n threepurple_payoff = c(0)\n fourpurple_payoff = c(0)\n\n # payoffs if player picks yellow\n oneyellow_payoff = c(3)\n twoyellow_payoff = c(6)\n threeyellow_payoff = c(9)\n fouryellow_payoff = c(12)\n\n\nclass Subsession(BaseSubsession):\n def vars_for_admin_report(self):\n decisions = [\n p.decision for p in self.get_players() if p.decision != None\n ]\n if decisions:\n return dict(\n decisionlist=decisions\n )\n else:\n return dict(\n decisionlist='(no data)',\n )\n\n\nclass Group(BaseGroup):\n def set_payoffs(self):\n for p in self.get_players():\n p.set_payoff()\n\n\nclass Player(BasePlayer):\n decision = models.StringField(\n widget=widgets.RadioSelectHorizontal\n )\n\n def decision_choices(self):\n import random\n choices = [['Green', 'Green'], ['Purple', 'Purple'], ['Yellow', 'Yellow']]\n random.shuffle(choices)\n return choices\n\n def other_player1(self):\n return self.get_others_in_group()[0]\n def other_player2(self):\n return self.get_others_in_group()[1]\n def other_player3(self):\n return self.get_others_in_group()[2]\n\n def set_payoff(self):\n greenval = 0\n purpleval = 0\n yellowval = 3\n todf = {'Green': [greenval, 2*greenval, 3*greenval, 4*greenval],\n 'Purple': [purpleval, 2*purpleval, 3*purpleval, 4*purpleval],\n 'Yellow': [yellowval, 2*yellowval, 3*yellowval, 4*yellowval]}\n payoff_matrix = pd.DataFrame(todf)\n\n choicecolumn = payoff_matrix[self.decision]\n self.payoff = choicecolumn[[self.other_player1().decision,\n self.other_player2().decision,\n self.other_player3().decision].count(self.decision)]\n\n\n\ndoc = \"\"\"\nThis is a coordination game with 4 players.\n\"\"\"","sub_path":"block1/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"612050059","text":"# Palindrom finder\nimport time\n\ndef check_if_palindrom(number):\n \"\"\"\n Find if number is Palindrom\n @param number - int\n @return boolean\n \"\"\"\n if(str(number)==reverse(str(number))):\n return True\n return False\n\ndef reverse(text):\n \"\"\"\n Text reverse\n @param text - input text\n @return reverser text\n \"\"\"\n text = str(text)\n if len(text) <= 1:\n return text\n return reverse(text[1:]) + text[0]\n\ndef try_to_make_palindrom(number):\n \"\"\"\n Palindrome Making\n @param number - number from wihich will be trying to make palindrom\n @return palindrom or error message\n \"\"\"\n start_time = time.clock() \n while True:\n if(check_if_palindrom(number)):\n break\n elif(time.clock() - start_time > 5): #Time for making palindrome 5s\n return \"End of time for making palindrom from given number\"\n else:\n number = number + int(reverse(number))\n return number\n\n#main\nlista = []\n\ntry:\n\tlow_range = int(input(\"Enter the lower limit: \"))\n\thigh_range = int(input(\"Enter the upper limit: \"))\n\tfor x in range(low_range,high_range):\n\t\tlista.append((x,try_to_make_palindrom(x)))\n\tprint(lista)\nexcept Exception as e:\n\tprint(e)\n\ntry:\n\tinput(\"Press Enter key to continue...\")\nexcept:\n\tpass\n\n","sub_path":"PalindromNumbers.py","file_name":"PalindromNumbers.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"28156148","text":"#!/usr/bin/python\nimport math\nimport numpy.random as random\n\n\noverflow_time = [0]\npos = []\nstddev = 500\nmin_time = 300\ncoefficient = 30\n\n# read file\nwith open('positions.txt', 'r') as f:\n s = f.readline()\n num_nodes = int(s)\n for i in range(0, num_nodes):\n s = f.readline()\n split = s.split()\n x = int(split[0])\n y = int(split[1])\n pos.append((x, y))\n\n\ndef distance_to(i):\n dx = abs(pos[i][0] - pos[0][0])\n dy = abs(pos[i][1] - pos[0][1])\n\n return int(math.sqrt(dx ** 2 + dy ** 2))\n\nfor i in range(1, num_nodes):\n d = distance_to(i)\n time = coefficient * max(min_time, int(random.normal(loc=d, scale=stddev)))\n overflow_time.append(time)\n\nprint(overflow_time)\n\nwith open('overflow_time.txt', 'w') as f:\n f.write(str(num_nodes) + '\\n')\n for t in overflow_time:\n f.write(str(t) + '\\n')\n","sub_path":"gen_overflow_time.py","file_name":"gen_overflow_time.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"171451533","text":"# -*- coding: utf-8 -*-\nimport inspect\n\nimport yurlungur\nfrom yurlungur.core import app, env\n\n\"\"\"internal module\"\"\"\n\n\nclass YException(NotImplementedError):\n \"\"\"\n >>> raise NotImplementedError(app.application)\n \"\"\"\n pass\n\n\nclass YMObject(object):\n \"\"\"command wrapper for any application\"\"\"\n\n def __getattr__(self, item):\n for cmd, _ in inspect.getmembers(app.application):\n if cmd == item:\n setattr(\n yurlungur, cmd,\n (lambda str: dict(inspect.getmembers(app.application))[str])(cmd)\n )\n return getattr(yurlungur, item)\n\n return None\n\n def eval(self, script):\n if env.Maya():\n import maya.mel as mel\n return mel.eval(script)\n if env.Houdini():\n app.application.hscript(script)\n\n raise YException\n\n @property\n def module(self):\n return app.application.__name__\n\n\nclass MetaObject(type):\n def __new__(cls, name, bases, attrs):\n return super(MetaObject, cls).__new__(cls, name, bases, attrs)\n\n\nclass MetaAttr(type):\n def __new__(cls, name, bases, attrs):\n return super(MetaAttr, cls).__new__(cls, name, bases, attrs)\n\n\nclass MetaNode(type):\n def __new__(cls, name, bases, attrs):\n return super(MetaNode, cls).__new__(cls, name, bases, attrs)\n\n\n# Dynamic Class\n_YObject = MetaObject(\"YObject\", (object,), {\"__doc__\": MetaObject.__doc__})\n_YNode = MetaNode(\"YNode\", (object,), {\"__doc__\": MetaNode.__doc__})\n_YAttr = MetaAttr(\"YAttr\", (object,), {\"__doc__\": MetaAttr.__doc__})\n_YVector = _YMatrix = _YColor = OM = object\n\nif env.Maya():\n import maya.api.OpenMaya as OM\n\n _YVector = type('_YVector', (OM.MVector,), dict())\n _YMatrix = type('_YMatrix', (OM.MMatrix,), dict())\n _YColor = type('_YColor', (OM.MColor,), dict())\n\nelif env.Houdini() or env.Unreal():\n meta = YMObject()\n\n _YVector = type('_YVector', (\n meta.Vector if hasattr(meta, \"Vector\") else meta.Vector3,\n ), dict())\n\n _YMatrix = type('_YMatrix', (\n meta.Matrix if hasattr(meta, \"Matrix\") else meta.Matrix4,\n ), dict())\n\n _YColor = type('_YColor', (meta.Color,), dict())\n\nelif env.Blender():\n import mathutils\n\n _YVector = type('_YVector', (mathutils.Vector,), dict())\n _YMatrix = type('_YMatrix', (mathutils.Matrix,), dict())\n _YColor = type('_YColor', (mathutils.Color,), dict())\n","sub_path":"yurlungur/core/wrapper.py","file_name":"wrapper.py","file_ext":"py","file_size_in_byte":2424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"560778929","text":"from asyncio import sleep\nfrom os import remove\nfrom telethon import events\nimport asyncio\nfrom datetime import datetime\nfrom telethon.errors.rpcerrorlist import UserIdInvalidError\nfrom userbot.utils import sudo_cmd, errors_handler\nfrom telethon.tl.functions.channels import EditBannedRequest\nfrom userbot.uniborgConfig import Config\nfrom telethon.tl.types import ChatBannedRights\nBOTLOG = True\nBOTLOG_CHATID = Config.PRIVATE_CHANNEL_BOT_API_ID \n\nUNBAN_RIGHTS = ChatBannedRights(\n until_date=None,\n send_messages=None,\n send_media=None,\n send_stickers=None,\n send_gifs=None,\n send_games=None,\n send_inline=None,\n embed_links=None,\n)\n\nNO_ADMIN = \"`I am not an admin nub nibba!`\"\nNO_PERM = \"`I don't have sufficient permissions! This is so sed. Alexa play despacito`\"\nNO_SQL = \"`Running on Non-SQL mode!`\"\n\nMUTE_RIGHTS = ChatBannedRights(until_date=None, send_messages=True)\n\nUNMUTE_RIGHTS = ChatBannedRights(until_date=None, send_messages=False)\n\n\n@borg.on(sudo_cmd(pattern=r\"mute(?: |$)(.*)\" ,allow_sudo = True))\n@errors_handler\nasync def spider(spdr):\n try:\n from userbot.plugins.sql_helper.mute_sql import mute\n except AttributeError:\n await spdr.delete()\n return\n \n # Admin or creator check\n chat = await spdr.get_chat()\n admin = chat.admin_rights\n creator = chat.creator\n\n # If not admin and not creator, return\n if not admin and not creator:\n await spdr.reply(NO_ADMIN)\n return\n\n user, reason = await get_user_from_event(spdr)\n if user:\n pass\n else:\n return\n\n self_user = await spdr.client.get_me()\n\n if user.id == self_user.id:\n await spdr.reply(\n f\"Sorry, I can't mute my self\")\n return\n \n if mute(spdr.chat_id, user.id) is False:\n return await spdr.reply(f\"Error! User probably already muted.\")\n else:\n try:\n await spdr.client(\n EditBannedRequest(spdr.chat_id, user.id, MUTE_RIGHTS))\n\n # Announce that the function is done\n if reason:\n await spdr.reply(f\"{user.first_name} was muted in {spdr.chat.title}\\n\"\n f\"`Reason:`{reason}\")\n else:\n await spdr.reply(f\"{user.first_name} was muted in {spdr.chat.title}\")\n\n\n # Announce to logging group\n if BOTLOG:\n await spdr.client.send_message(\n BOTLOG_CHATID, \"#MUTE\\n\"\n f\"USER: [{user.first_name}](tg://user?id={user.id})\\n\"\n f\"CHAT: {spdr.chat.title}(`{spdr.chat_id}`)\")\n except UserIdInvalidError:\n return await spdr.reply(\"`Uh oh my mute logic broke!`\")\n\n\n\n\n@borg.on(sudo_cmd(pattern=r\"unmute(?: |$)(.*)\" ,allow_sudo = True))\nasync def unmoot(unmot):\n \"\"\" For .unmute command, unmute the replied/tagged person \"\"\"\n # Admin or creator check\n chat = await unmot.get_chat()\n admin = chat.admin_rights\n creator = chat.creator\n\n # If not admin and not creator, return\n if not admin and not creator:\n await unmot.reply(NO_ADMIN)\n return\n\n # Check if the function running under SQL mode\n try:\n from userbot.plugins.sql_helper.mute_sql import unmute\n except AttributeError:\n await unmot.delete()\n return\n\n # If admin or creator, inform the user and start unmuting\n await unmot.edit('```Unmuting...```')\n user = await get_user_from_event(unmot)\n user = user[0]\n if user:\n pass\n else:\n return\n\n if unmute(unmot.chat_id, user.id) is False:\n return await unmot.reply(\"`Error! User probably already unmuted.`\")\n else:\n\n try:\n await unmot.client(\n EditBannedRequest(unmot.chat_id, user.id, UNBAN_RIGHTS))\n await unmot.reply(\"Unmuted Successfully\")\n except UserIdInvalidError:\n await unmot.reply(\"`Uh oh my unmute logic broke!`\")\n return\n\n if BOTLOG:\n await unmot.client.send_message(\n BOTLOG_CHATID, \"#UNMUTE\\n\"\n f\"USER: [{user.first_name}](tg://user?id={user.id})\\n\"\n f\"CHAT: {unmot.chat.title}(`{unmot.chat_id}`)\")\n\n\n\n\nasync def get_user_from_event(event):\n \"\"\" Get the user from argument or replied message. \"\"\"\n args = event.pattern_match.group(1).split(' ', 1)\n extra = None\n if event.reply_to_msg_id:\n previous_message = await event.get_reply_message()\n user_obj = await event.client.get_entity(previous_message.from_id)\n extra = event.pattern_match.group(1)\n elif args:\n user = args[0]\n if len(args) == 2:\n extra = args[1]\n\n if user.isnumeric():\n user = int(user)\n\n if not user:\n await event.edit(\"`Pass the user's username, id or reply!`\")\n return\n\n if event.message.entities is not None:\n probable_user_mention_entity = event.message.entities[0]\n\n if isinstance(probable_user_mention_entity,\n MessageEntityMentionName):\n user_id = probable_user_mention_entity.user_id\n user_obj = await event.client.get_entity(user_id)\n return user_obj\n try:\n user_obj = await event.client.get_entity(user)\n except (TypeError, ValueError) as err:\n await event.edit(str(err))\n return None\n\n return user_obj, extra\n\n\nasync def get_user_from_id(user, event):\n if isinstance(user, str):\n user = int(user)\n\n try:\n user_obj = await event.client.get_entity(user)\n except (TypeError, ValueError) as err:\n await event.edit(str(err))\n return None\n\n return user_obj\n\n","sub_path":"userbot/plugins/mute.py","file_name":"mute.py","file_ext":"py","file_size_in_byte":5739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"374972030","text":"from os import system\nimport os\n\ndir = os.path.split(os.getcwd())[0]\ncode_dir = dir + '/scripts'\n\n\nexperiments = ['fmril']\nnor_methods = ['indi'] # 'no'\nclf_methods = ['svm']\nsource_ids = [i for i in range(10,65)]\ntarget_ids = [i for i in range(5)]\nop_function = 'maplin'\n\nfor experiment in experiments:\n for nor_method in nor_methods:\n for clf_method in clf_methods:\n for source_id in source_ids:\n for target_id in target_ids:\n if source_id != target_id:\n cmd = \"frioul_batch -n '11,12,13,14,15,16,17,18' -c 3 \" \\\n \"'/hpc/crise/anaconda3/bin/python3.5 \" \\\n \"%s/frioul_ot_pair_circulaire_kfold.py %s %s %s %d %d %s'\" \\\n % (code_dir, experiment, nor_method, clf_method, source_id, target_id, op_function)\n # a = commands.getoutput(cmd)\n a = system(cmd)\n print(cmd)\n","sub_path":"scripts/frioul_cmd_ot_pair_circulaire_kfold.py","file_name":"frioul_cmd_ot_pair_circulaire_kfold.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"533471099","text":"from flask import Flask, render_template, request, escape\r\nfrom vsearch import search4letters\r\n\r\napp = Flask('name')\r\n\r\ndef log_request(req, res):\r\n with open('vsearch.log', 'a') as log:\r\n print(req.form, file=log, end = '|')\r\n print(req.remote_addr, file=log, end = '|')\r\n print(req.user_agent, file=log, end = '|')\r\n print(res, file=log, end = '|')\r\n\r\n\r\n@app.route('/')\r\ndef hello() -> str:\r\n return 'Hello world from Flask!'\r\n\r\n\r\n\r\n@app.route(\"/search4\", methods=['POST'])\r\ndef do_search() -> 'html':\r\n phrase = request.form['phrase']\r\n letters = request.form['letters']\r\n title = 'Here are your results:'\r\n results = str(search4letters(phrase, letters))\r\n log_request(request, results)\r\n return render_template('results.html',\r\n the_phrase = phrase, \r\n the_letters = letters, \r\n the_title = title, \r\n the_results = results,)\r\n\r\n\r\n@app.route('/viewlog')\r\ndef view_the_log():\r\n contents = []\r\n with open('vsearch.log') as log:\r\n for line in log:\r\n contents.append([])\r\n for item in line.split('|'):\r\n contents[-1].append(escape(item))\r\n return str(contents)\r\n \r\n\r\n@app.route('/')\r\n@app.route('/entry')\r\ndef entry_page() -> 'html':\r\n return render_template('entry.html', the_title = 'Welcome to search4letters online')\r\n\r\n\r\napp.run()\r\n","sub_path":"webapp/hello_flask.py","file_name":"hello_flask.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"190527598","text":"from sense_hat import SenseHat\nsense = SenseHat()\nfrom time import sleep\n\n#sense.show_message(\"Welcome\")\n#sleep(3)\nsense.show_letter(\"1\")\n\nlvl = 1\n\n#functions\ndef move_up(event):\n global lvl\n if event.action == \"released\":\n lvl += 1\n if lvl == 1: \n sense.show_letter(\"1\")\n if lvl == 2: \n sense.show_letter(\"2\")\n if lvl == 3: \n sense.show_letter(\"3\")\n if lvl == 4: \n sense.show_letter(\"4\")\n if lvl == 5: \n sense.show_letter(\"5\")\n \ndef move_down(event):\n global lvl\n if event.action == \"released\" and lvl > 1:\n lvl -= 1\n if lvl == 1:\n sense.show_letter(\"1\")\n if lvl == 2:\n sense.show_letter(\"2\")\n if lvl == 3:\n sense.show_letter(\"3\")\n if lvl == 4:\n sense.show_letter(\"4\")\n if lvl == 5:\n sense.show_letter(\"5\")\n\ndef restart():\n import sys\n #print(\"argv was\",sys.argv)\n #print(\"sys.executable was\", sys.executable)\n print(\"restart now\")\n import os\n os.execv(sys.executable, ['python'] + sys.argv)\n \ndef move_middle(event):\n game_over = 1\n while game_over == 1:\n if lvl == 1: \n sense.clear()\n sense.show_message(\"1\")\n game_over = 2\n while game_over == 2:\n import marble_maze_level_1.py\n print (\"1\")\n execfile('marble_maze_level_1.py')\n exit(1)\n if lvl == 2: \n sense.clear()\n sense.show_message(\"2\")\n game_over = 3\n while game_over == 3:\n import marble_maze_level_2.py\n print (\"2\")\n execfile('marble_maze_level_2.py')\n exit(1)\n if lvl == 3: \n sense.clear()\n sense.show_message(\"3\")\n game_over = 4\n while game_over == 4:\n import marble_maze_level_1_old.py\n print (\"3\")\n execfile('marble_maze_level_1_old.py')\n restart()\n \nsense.stick.direction_up = move_up\nsense.stick.direction_down = move_down\nsense.stick.direction_middle = move_middle","sub_path":"marble_maze_menu_BA.py","file_name":"marble_maze_menu_BA.py","file_ext":"py","file_size_in_byte":2219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"6348947","text":"from django.contrib.auth.models import User\nfrom django.utils.translation import gettext as _\nfrom django.db import models\n\n# Create your models here.\nDEGREE_TYPE = ((u'本科', u'本科'), (u'硕士', u'硕士'), (u'博士', u'博士'))\n\nJobsType = [\n (0, \"技术类\"),\n (1, \"产品类\"),\n (2, \"运营类\"),\n (3, \"设计类\")\n]\n\nCities = [\n (0, \"上海\"),\n (1, \"北京\"),\n (2, \"深圳\")\n]\n\n\nclass Job(models.Model):\n job_type = models.SmallIntegerField(choices=JobsType, blank=False, verbose_name=\"职位类型\")\n job_name = models.CharField(max_length=250, blank=False, verbose_name=\"职位名称\")\n job_city = models.SmallIntegerField(choices=Cities, blank=False, verbose_name=\"工作地点\")\n job_responsibility = models.TextField(max_length=1024, verbose_name=\"工作职责\")\n job_requirement = models.TextField(max_length=1024, blank=False, verbose_name=\"工作要求\")\n creator = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, verbose_name=\"创建人\")\n create_date = models.DateTimeField(auto_now_add=True, verbose_name=\"创建日期\")\n modified_date = models.DateTimeField(auto_now=True, verbose_name=\"修改时间\")\n\n class Meta:\n db_table = 'job'\n\n def __str__(self):\n return self.job_name\n\n\nclass Resume(models.Model):\n # Translators: 简历实体的翻译\n username = models.CharField(max_length=135, verbose_name=_('姓名'))\n applicant = models.ForeignKey(User, verbose_name=_(\"申请人\"), null=True, on_delete=models.SET_NULL)\n city = models.CharField(max_length=135, verbose_name=_('城市'))\n phone = models.CharField(max_length=135, verbose_name=_('手机号码'))\n email = models.EmailField(max_length=135, blank=True, verbose_name=_('邮箱'))\n apply_position = models.CharField(max_length=135, blank=True, verbose_name=_('应聘职位'))\n born_address = models.CharField(max_length=135, blank=True, verbose_name=_('生源地'))\n gender = models.CharField(max_length=135, blank=True, verbose_name=_('性别'))\n picture = models.ImageField(upload_to='images/', blank=True, verbose_name=_('个人照片'))\n attachment = models.FileField(upload_to='file/', blank=True, verbose_name=_('简历附件'))\n\n # 学校与学历信息\n bachelor_school = models.CharField(max_length=135, blank=True, verbose_name=_('本科学校'))\n master_school = models.CharField(max_length=135, blank=True, verbose_name=_('研究生学校'))\n doctor_school = models.CharField(max_length=135, blank=True, verbose_name=u'博士生学校')\n major = models.CharField(max_length=135, blank=True, verbose_name=_('专业'))\n degree = models.CharField(max_length=135, choices=DEGREE_TYPE, blank=True, verbose_name=_('学历'))\n created_date = models.DateTimeField(verbose_name=\"创建日期\", auto_now_add=True)\n modified_date = models.DateTimeField(verbose_name=\"修改日期\", auto_now=True)\n\n # 候选人自我介绍,工作经历,项目经历\n candidate_introduction = models.TextField(max_length=1024, blank=True, verbose_name=u'自我介绍')\n work_experience = models.TextField(max_length=1024, blank=True, verbose_name=u'工作经历')\n project_experience = models.TextField(max_length=1024, blank=True, verbose_name=u'项目经历')\n\n class Meta:\n verbose_name = _('简历')\n verbose_name_plural = _('简历列表')\n\n def __str__(self):\n return self.username\n\nResume.objects.raw()","sub_path":"jobs/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"23097303","text":"\"\"\"empty message\n\nRevision ID: 64a4ef331e98\nRevises: a040ac5c86e6\nCreate Date: 2018-06-19 10:52:32.447034\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '64a4ef331e98'\ndown_revision = 'a040ac5c86e6'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('shaker', sa.Column('free_bet', sa.Integer(), server_default='0', nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('shaker', 'free_bet')\n # ### end Alembic commands ###\n","sub_path":"restapi/migrations/versions/64a4ef331e98_.py","file_name":"64a4ef331e98_.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"436317100","text":"####################################\n# Copyright Christopher Abiad, 2013\n# All Rights Reserved\n####################################\n\"\"\"In-place quicksorting.\"\"\"\n\n__author__ = 'Christopher Abiad'\n\nfrom random import randrange\n\ndef _partition(l, low, high):\n \"\"\"Partition the list using a random element as the pivot.\n\n NOTE: The part of the list we care about goes from low to high-1.\n \"\"\"\n\n # Pick a random element and move it to the end of the list. This randomness\n # improves performance on partially sorted lists\n p = randrange(low, high)\n if p != high - 1:\n l[p], l[high - 1] = l[high - 1], l[p]\n p = high - 1\n\n # 'fh' is 'first high'. The index of the first element in the list that's\n # >= the pivot\n fh = low\n\n # Iterate through the elements in the overall list, creating three\n # sublists as we iterate:\n # (1) The values from i to high-2 are unexamined.\n # (2) The values between low and fh-1 are < the pivot.\n # (3) The values from fh to i+1 are >= the pivot.\n #\n # Note that the pivot itself is at high-1, so we don't need to check it\n for i in xrange(low, high - 1):\n if l[i] < l[p]:\n if fh != i:\n l[i], l[fh] = l[fh], l[i]\n fh += 1\n\n # At the end of the iteration, the first high element represents the\n # pivot's final location. Since we moved the pivot to the end of the list,\n # we can swap places with the element at fh.\n l[p], l[fh] = l[fh], l[p]\n\n return fh\n\n\ndef _qsort(l, low, high):\n if high - low > 1:\n p = _partition(l, low, high)\n _qsort(l, low, p)\n _qsort(l, p + 1, high)\n\n\ndef qsort(l):\n \"\"\"In-place quick sort of a Python list.\"\"\"\n _qsort(l, 0, len(l))\n\n\nif __name__ == '__main__':\n from pprint import pprint\n val = [5, 4, 3, 2, 2]\n qsort(val)\n pprint(val)\n assert(val == [2, 2, 3, 4, 5])\n\n val = []\n qsort(val)\n pprint(val)\n assert(val == [])\n\n val = [1]\n qsort(val)\n pprint(val)\n assert(val == [1])\n\n val = [1, 2, 3, 4, 5]\n qsort(val)\n pprint(val)\n assert(val == [1, 2, 3, 4, 5])\n\n val = [3, 2, 1, 6, 2]\n qsort(val)\n pprint(val)\n assert(val == [1, 2, 2, 3, 6])","sub_path":"dockerized-gists/4974696/snippet.py","file_name":"snippet.py","file_ext":"py","file_size_in_byte":2211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"374822367","text":"#!/usr/bin/python3\nimport tornado.ioloop\nimport tornado.web\nimport tornado.websocket\nimport tornado.gen\nimport os\nimport sys\nimport struct\nimport binascii\nimport collections\nimport heapq\nimport optparse\nimport signal\nimport strus\nimport strusMessage\n\n# [0] Globals and helper classes:\n# The address of the global statistics server:\nstatserver = \"localhost:7183\"\n# Strus storage server addresses:\nstorageservers = []\n# Strus client connection factory:\nmsgclient = strusMessage.RequestClient()\n\n# Query analyzer structures (parallel to document analyzer definition in strusIR):\nstrusctx = strus.Context()\nanalyzer = strusctx.createQueryAnalyzer()\nanalyzer.addElement( \"word\", \"text\", \"word\", [\"lc\", [\"stem\", \"en\"], [\"convdia\", \"en\"]])\n\n# Query evaluation structures:\nResultRow = collections.namedtuple(\n 'ResultRow', ['docno', 'docid', 'weight', 'title', 'abstract'])\n\n\n# [1] HTTP handlers:\n# Answer a query (issue a query to all storage servers and merge it to one result):\nclass QueryHandler( tornado.web.RequestHandler ):\n @tornado.gen.coroutine\n def queryStats( self, terms):\n rt = ([],0,None)\n try:\n statquery = b\"Q\"\n for term in terms:\n ttype = term['type'].encode('utf-8')\n tvalue = term['value'].encode('utf-8')\n statquery += b'T'\n typesize = len( ttype)\n valuesize = len( tvalue)\n statquery += struct.pack( \">HH\", typesize, valuesize)\n statquery += struct.pack( \"%ds%ds\" % (typesize,valuesize), ttype, tvalue)\n statquery += b'N'\n ri = statserver.rindex(':')\n host,port = statserver[:ri],int( statserver[ri+1:])\n conn = yield msgclient.connect( host, port)\n statreply = yield msgclient.issueRequest( conn, statquery)\n\n if (statreply[0] == ord('E')):\n raise Exception( \"failed to query global statistics: %s\" % statreply[1:])\n elif (statreply[0] != ord('Y')):\n raise Exception( \"protocol error loading global statistics\")\n dflist = []\n collsize = 0\n statsofs = 1\n statslen = len(statreply)\n while (statsofs < statslen):\n (statsval,) = struct.unpack_from( \">q\", statreply, statsofs)\n statsofs += struct.calcsize( \">q\")\n if (len(dflist) < len(terms)):\n dflist.append( statsval)\n elif (len(dflist) == len(terms)):\n collsize = statsval\n else:\n break\n if (statsofs != statslen):\n raise Exception(\"result does not match query\")\n rt = (dflist, collsize, None)\n except Exception as e:\n rt = ([],0,\"query statistic server failed: %s\" % e)\n raise tornado.gen.Return( rt)\n\n @tornado.gen.coroutine\n def issueQuery( self, serveraddr, qryblob):\n rt = (None,None)\n ri = serveraddr.rindex(':')\n host,port = serveraddr[:ri],int( serveraddr[ri+1:])\n result = None\n conn = None\n try:\n conn = yield msgclient.connect( host, port)\n reply = yield msgclient.issueRequest( conn, qryblob)\n if (reply[0] == ord('E')):\n rt = (None, \"storage server %s:%d returned error: %s\"\n % (host, port, reply[1:]))\n elif (reply[0] == ord('Y')):\n result = []\n row_docno = 0\n row_docid = None\n row_weight = 0.0\n row_title = \"\"\n row_abstract = \"\"\n replyofs = 1\n replysize = len(reply)-1\n while (replyofs < replysize):\n if (reply[ replyofs] == ord('_')):\n if (row_docid != None):\n result.append( ResultRow(\n row_docno, row_docid, row_weight, row_title, row_abstract))\n row_docno = 0\n row_docid = None\n row_weight = 0.0\n row_title = \"\"\n row_abstract = \"\"\n replyofs += 1\n elif (reply[ replyofs] == ord('D')):\n (row_docno,) = struct.unpack_from( \">I\", reply, replyofs+1)\n replyofs += struct.calcsize( \">I\") + 1\n elif (reply[ replyofs] == ord('W')):\n (row_weight,) = struct.unpack_from( \">f\", reply, replyofs+1)\n replyofs += struct.calcsize( \">f\") + 1\n elif (reply[ replyofs] == ord('I')):\n (docidlen,) = struct.unpack_from( \">H\", reply, replyofs+1)\n replyofs += struct.calcsize( \">H\") + 1\n (row_docid,) = struct.unpack_from( \"%us\" % docidlen, reply, replyofs)\n replyofs += docidlen\n elif (reply[ replyofs] == ord('T')):\n (titlelen,) = struct.unpack_from( \">H\", reply, replyofs+1)\n replyofs += struct.calcsize( \">H\") + 1\n (row_title,) = struct.unpack_from( \"%us\" % titlelen, reply, replyofs)\n replyofs += titlelen\n elif (reply[ replyofs] == ord('A')):\n (abstractlen,) = struct.unpack_from( \">H\", reply, replyofs+1)\n replyofs += struct.calcsize( \">H\") + 1\n (row_abstract,) = struct.unpack_from( \"%us\" % abstractlen, reply, replyofs)\n replyofs += abstractlen\n else:\n rt = (None, \"storage server %s:%u protocol error: \"\n \"unknown result column name\" % (host,port))\n row_docid = None\n break\n if (row_docid != None):\n result.append( ResultRow(\n row_docno, row_docid, row_weight, row_title, row_abstract))\n rt = (result, None)\n else:\n rt = (None, \"protocol error storage %s:%u query: \"\n \"unknown header %c\" % (host,port,reply[0]))\n except Exception as e:\n rt = (None, \"storage server %s:%u connection error: %s\"\n % (host, port, str(e)))\n raise tornado.gen.Return( rt)\n\n @tornado.gen.coroutine\n def issueQueries( self, servers, qryblob):\n results = None\n try:\n results = yield [ self.issueQuery( addr, qryblob) for addr in servers ]\n except Exception as e:\n raise tornado.gen.Return( [], [\"error issueing query: %s\" % str(e)])\n raise tornado.gen.Return( results)\n\n # Merge code derived from Python Cookbook (Sebastien Keim, Raymond Hettinger and Danny Yoo)\n # referenced in from http://wordaligned.org/articles/merging-sorted-streams-in-python:\n def mergeResultIter( self, resultlists):\n # prepare a priority queue whose items are pairs of the form (-weight, resultlistiter):\n heap = []\n for resultlist in resultlists:\n resultlistiter = iter(resultlist)\n for result in resultlistiter:\n # subseq is not empty, therefore add this subseq pair\n # (current-value, iterator) to the list\n heap.append((-result.weight, result, resultlistiter))\n break\n # make the priority queue into a heap\n heapq.heapify(heap)\n while heap:\n # get and yield the result with the highest weight (minus lowest negative weight):\n negative_weight, result, resultlistiter = heap[0]\n yield result\n for result in resultlistiter:\n # resultlists is not finished, replace best pair in the priority queue\n heapq.heapreplace( heap, (-result.weight, result, resultlistiter))\n break\n else:\n # subseq has been exhausted, therefore remove it from the queue\n heapq.heappop( heap)\n\n def mergeQueryResults( self, results, firstrank, nofranks):\n merged = []\n errors = []\n itrs = []\n maxnofresults = firstrank + nofranks\n for result in results:\n if (result[0] == None):\n errors.append( result[1])\n else:\n itrs.append( iter( result[0]))\n ri = 0\n for result in self.mergeResultIter( itrs):\n if (ri == maxnofresults):\n break\n merged.append( result)\n ri += 1\n return (merged[ firstrank:maxnofresults], errors)\n\n @tornado.gen.coroutine\n def evaluateQueryText( self, querystr, firstrank, nofranks):\n rt = None\n try:\n maxnofresults = firstrank + nofranks\n terms = analyzer.analyzeTermExpression( [\"text\", querystr])\n if len( terms) > 0:\n # Get the global statistics:\n dflist,collectionsize,error = yield self.queryStats( terms)\n if (error != None):\n raise Exception( error)\n # Assemble the query:\n qry = b\"Q\"\n qry += b\"S\"\n qry += struct.pack( \">q\", collectionsize)\n qry += b\"I\"\n qry += struct.pack( \">H\", 0)\n qry += b\"N\"\n qry += struct.pack( \">H\", maxnofresults)\n for ii in range( 0, len( terms)):\n qry += b\"T\"\n type = terms[ii]['type'].encode('utf-8')\n typesize = len( type)\n value = terms[ii]['value'].encode('utf-8')\n valuesize = len( value)\n qry += struct.pack( \">qHH\", dflist[ii], typesize, valuesize)\n qry += struct.pack( \"%ds%ds\" % (typesize,valuesize), type, value)\n # Query all storage servers and merge the results:\n results = yield self.issueQueries( storageservers, qry)\n rt = self.mergeQueryResults( results, firstrank, nofranks)\n except Exception as e:\n rt = ([], [\"error evaluation query: %s\" % str(e)])\n raise tornado.gen.Return( rt)\n\n @tornado.gen.coroutine\n def get(self):\n try:\n # q = query terms:\n querystr = self.get_argument( \"q\", None)\n # i = firstrank:\n firstrank = int( self.get_argument( \"i\", 0))\n # n = nofranks:\n nofranks = int( self.get_argument( \"n\", 20))\n # Evaluate query with BM25 (Okapi):\n result = yield self.evaluateQueryText( querystr, firstrank, nofranks)\n # Render the results:\n self.render( \"search_bm25_html.tpl\", results=result[0], messages=result[1])\n except Exception as e:\n self.render( \"search_error_html.tpl\", message=e)\n\n# Insert a multipart document (POST request):\nclass InsertHandler( tornado.web.RequestHandler ):\n @tornado.gen.coroutine\n def post(self, port):\n try:\n # Insert documents:\n conn = yield msgclient.connect( 'localhost', int(port))\n\n cmd = b\"I\" + self.request.body\n reply = yield msgclient.issueRequest( conn, cmd)\n if (reply[0] == ord('E')):\n raise Exception( reply[1:].decode('UTF-8'))\n elif (reply[0] != ord('Y')):\n raise Exception( \"protocol error server reply on insert: %c\" % reply[0])\n\n (nofDocuments,) = struct.unpack( \">I\", reply[1:])\n self.write( \"OK %u\\n\" % (nofDocuments))\n except Exception as e:\n self.write( \"ERR \" + str(e) + \"\\n\")\n\n# [3] Dispatcher:\napplication = tornado.web.Application([\n # /query in the URL triggers the handler for answering queries:\n (r\"/query\", QueryHandler),\n # /insert in the URL triggers the post handler for insert requests:\n (r\"/insert/([0-9]+)\", InsertHandler),\n # /static in the URL triggers the handler for accessing static \n # files like images referenced in tornado templates:\n (r\"/static/(.*)\",tornado.web.StaticFileHandler,\n {\"path\": os.path.dirname(os.path.realpath(sys.argv[0]))},)\n])\n\ndef on_shutdown():\n print('Shutting down')\n tornado.ioloop.IOLoop.current().stop()\n\n# [5] Server main:\nif __name__ == \"__main__\":\n try:\n # Parse arguments:\n usage = \"usage: %prog [options] {}\"\n parser = optparse.OptionParser( usage=usage)\n parser.add_option(\"-p\", \"--port\", dest=\"port\", default=80,\n help=\"Specify the port of this server as PORT (default %u)\" % 80,\n metavar=\"PORT\")\n parser.add_option(\"-s\", \"--statserver\", dest=\"statserver\", default=statserver,\n help=\"Specify the address of the statistics server \"\n \"as ADDR (default %s\" % statserver,\n metavar=\"ADDR\")\n\n (options, args) = parser.parse_args()\n myport = int(options.port)\n statserver = options.statserver\n if (statserver[0:].isdigit()):\n statserver = '{}:{}'.format( 'localhost', statserver)\n\n # Positional arguments are storage server addresses,\n # if empty use default at localhost:7184\n for arg in args:\n if (arg[0:].isdigit()):\n storageservers.append( '{}:{}'.format( 'localhost', arg))\n else:\n storageservers.append( arg)\n if (len( storageservers) == 0):\n storageservers.append( \"localhost:7184\")\n\n # Start server:\n print( \"Starting server ...\\n\")\n application.listen( myport )\n print( \"Listening on port %u\\n\" % myport )\n ioloop = tornado.ioloop.IOLoop.current()\n signal.signal( signal.SIGINT,\n lambda sig, frame: ioloop.add_callback_from_signal(on_shutdown))\n ioloop.start()\n print( \"Terminated\\n\")\n except Exception as e:\n print( e)\n\n\n","sub_path":"codeproject/Distributing-the-search-index-with-Strus/strusHttpServer.py","file_name":"strusHttpServer.py","file_ext":"py","file_size_in_byte":14171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"242978577","text":"import os\nimport json\nimport unittest\nfrom mock import Mock\nfrom dmcontent.content_loader import ContentLoader\nfrom werkzeug.datastructures import MultiDict\n\nfrom app.presenters.search_presenters import filters_for_lot, set_filter_states\n\n\ncontent_loader = ContentLoader('tests/fixtures/content')\ncontent_loader.load_manifest('g6', 'data', 'manifest')\nquestions_builder = content_loader.get_builder('g6', 'manifest')\n\n\ndef _get_fixture_data():\n test_root = os.path.abspath(\n os.path.join(os.path.dirname(__file__), \"..\")\n )\n fixture_path = os.path.join(\n test_root, 'fixtures', 'search_results_fixture.json'\n )\n with open(fixture_path) as fixture_file:\n return json.load(fixture_file)\n\n\ndef _get_fixture_multiple_pages_data():\n test_root = os.path.abspath(\n os.path.join(os.path.dirname(__file__), \"..\")\n )\n fixture_path = os.path.join(\n test_root, 'fixtures', 'search_results_multiple_pages_fixture.json'\n )\n with open(fixture_path) as fixture_file:\n return json.load(fixture_file)\n\n\nclass TestSearchFilters(unittest.TestCase):\n\n def _get_filter_group_by_label(self, lot, label):\n filter_groups = filters_for_lot(lot, questions_builder)\n for filter_group in filter_groups:\n if filter_group['label'] == label:\n return filter_group\n\n def _get_request_for_params(self, params):\n return Mock(args=MultiDict(params))\n\n def test_get_filter_groups_from_questions_with_radio_filters(self):\n radios_filter_group = self._get_filter_group_by_label(\n 'saas', 'Radios example'\n )\n\n self.assertEqual({\n 'label': 'Radios example',\n 'filters': [\n {\n 'label': 'Option 1',\n 'name': 'radiosExample',\n 'id': 'radiosExample-option-1',\n 'value': 'option 1',\n },\n {\n 'label': 'Option 2',\n 'name': 'radiosExample',\n 'id': 'radiosExample-option-2',\n 'value': 'option 2',\n }\n ]\n }, radios_filter_group)\n\n def test_get_filter_groups_from_questions_with_checkbox_filters(self):\n checkboxes_filter_group = self._get_filter_group_by_label(\n 'saas', 'Checkboxes example'\n )\n self.assertEqual({\n 'label': 'Checkboxes example',\n 'filters': [\n {\n 'label': 'Option 1',\n 'name': 'checkboxesExample',\n 'id': 'checkboxesExample-option-1',\n 'value': 'option 1',\n },\n {\n 'label': 'Option 2',\n 'name': 'checkboxesExample',\n 'id': 'checkboxesExample-option-2',\n 'value': 'option 2',\n }\n ]\n }, checkboxes_filter_group)\n\n def test_get_filter_groups_from_questions_with_boolean_filters(self):\n booleans_filter_group = self._get_filter_group_by_label(\n 'saas', 'Booleans example'\n )\n self.assertEqual({\n 'label': 'Booleans example',\n 'filters': [\n {\n 'label': 'Option 1',\n 'name': 'booleanExample1',\n 'id': 'booleanExample1',\n 'value': 'true',\n },\n {\n 'label': 'Option 2',\n 'name': 'booleanExample2',\n 'id': 'booleanExample2',\n 'value': 'true',\n }\n ]\n }, booleans_filter_group)\n\n def test_request_filters_are_set(self):\n search_filters = filters_for_lot('saas', questions_builder)\n request = self._get_request_for_params({\n 'q': 'email',\n 'booleanExample1': 'true'\n })\n\n set_filter_states(search_filters, request)\n self.assertEqual(search_filters[0]['filters'][0]['name'],\n 'booleanExample1')\n self.assertEqual(search_filters[0]['filters'][0]['checked'], True)\n self.assertEqual(search_filters[0]['filters'][1]['name'],\n 'booleanExample2')\n self.assertEqual(search_filters[0]['filters'][1]['checked'], False)\n\n def test_filter_groups_have_correct_default_state(self):\n request = self._get_request_for_params({\n 'q': 'email',\n 'lot': 'paas'\n })\n\n search_filters = filters_for_lot('paas', questions_builder)\n set_filter_states(search_filters, request)\n self.assertEqual(\n search_filters[0],\n {\n 'label': 'Booleans example',\n 'filters': [\n {\n 'checked': False,\n 'label': 'Option 1',\n 'name': 'booleanExample1',\n 'id': 'booleanExample1',\n 'value': 'true',\n },\n {\n 'checked': False,\n 'label': 'Option 2',\n 'name': 'booleanExample2',\n 'id': 'booleanExample2',\n 'value': 'true',\n }\n ]\n }\n )\n\n def test_filter_groups_have_correct_state_when_changed(self):\n request = self._get_request_for_params({\n 'q': 'email',\n 'lot': 'paas',\n 'booleanExample1': 'true'\n })\n\n search_filters = filters_for_lot('paas', questions_builder)\n set_filter_states(search_filters, request)\n\n self.assertEqual(\n search_filters[0],\n {\n 'label': 'Booleans example',\n 'filters': [\n {\n 'checked': True,\n 'label': 'Option 1',\n 'name': 'booleanExample1',\n 'id': 'booleanExample1',\n 'value': 'true',\n },\n {\n 'checked': False,\n 'label': 'Option 2',\n 'name': 'booleanExample2',\n 'id': 'booleanExample2',\n 'value': 'true',\n }\n ]\n }\n )\n\n def test_no_lot_is_the_same_as_all(self):\n all_filters = self._get_filter_group_by_label(\n 'all', 'Radios example'\n )\n no_lot_filters = self._get_filter_group_by_label(\n None, 'Radios example'\n )\n\n self.assertTrue(all_filters)\n self.assertEqual(all_filters, no_lot_filters)\n\n def test_instance_has_correct_filter_groups_for_paas(self):\n search_filters = filters_for_lot('paas', questions_builder)\n\n filter_group_labels = [\n group['label'] for group in search_filters\n ]\n\n self.assertTrue('Booleans example' in filter_group_labels)\n self.assertTrue('Checkboxes example' in filter_group_labels)\n self.assertTrue('Radios example' in filter_group_labels)\n\n def test_instance_has_correct_filter_groups_for_iaas(self):\n search_filters = filters_for_lot('iaas', questions_builder)\n\n filter_group_labels = [\n group['label'] for group in search_filters\n ]\n\n self.assertFalse('Booleans example' in filter_group_labels)\n self.assertTrue('Checkboxes example' in filter_group_labels)\n self.assertTrue('Radios example' in filter_group_labels)\n","sub_path":"tests/unit/test_search_presenters.py","file_name":"test_search_presenters.py","file_ext":"py","file_size_in_byte":7685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"430383358","text":"import importlib\n\nfrom django.conf import settings\n\n\ndef parse_message_string(message):\n if message[0] == '?':\n message = message[1:]\n elif message.startswith(settings.FRISKY_BOT_NAME):\n message = message[len(settings.FRISKY_BOT_NAME):]\n message.strip()\n split = message.split()\n command = split[0]\n arguments = split[1:]\n return command, arguments\n\n\ndef get_reply_from_plugin(message, sender, channel):\n command, arguments = parse_message_string(message)\n try:\n plugin = importlib.import_module(f'plugins.{command}')\n if hasattr(plugin, 'handle_message'):\n handler = getattr(plugin, 'handle_message')\n if callable(handler):\n return handler(*arguments, channel=channel, sender=sender)\n except ModuleNotFoundError:\n plugin = importlib.import_module(f'plugins.learn')\n if hasattr(plugin, 'handle_message'):\n handler = getattr(plugin, 'handle_message')\n if callable(handler):\n args = [command] + arguments\n return handler(*args, channel=channel, sender=sender)\n\n\ndef get_reply_for_reaction(reaction, reacting_user, commenting_user, comment, added):\n reactjis = {\n 'upvote': 'votes',\n 'downvote': 'votes',\n 'brain': 'learn',\n }\n if reaction in reactjis.keys():\n plugin_name = reactjis[reaction]\n plugin = importlib.import_module(f'plugins.{plugin_name}')\n if hasattr(plugin, 'handle_reaction'):\n handler = getattr(plugin, 'handle_reaction')\n if callable(handler):\n return handler(reaction, reacting_user, commenting_user, comment, added)\n\n\ndef handle_message(channel_name, sender, message, reply_channel) -> None:\n if message[0] != '?' and not message.startswith(settings.FRISKY_BOT_NAME):\n return\n reply = get_reply_from_plugin(message, sender, channel_name)\n if reply is not None:\n reply_channel(reply)\n\n\ndef handle_reaction(reaction, reacting_user, commenting_user, comment, added, reply_channel):\n \"\"\"\n\n This function is EXPERIMENTAL. Please don't base your plugins on it at this time\n\n :param comment:\n :param reaction:\n :param reacting_user:\n :param commenting_user:\n :param added:\n :param reply_channel:\n :return:\n \"\"\"\n reply = get_reply_for_reaction(reaction, reacting_user, commenting_user, comment, added)\n if reply is not None:\n reply_channel(reply)\n","sub_path":"frisky/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"267892155","text":"# https://www.hackerrank.com/challenges/merge-the-tools/problem?h_r=next-challenge&h_v=zen\r\n\r\n\r\ndef merge_the_tools(s, k):\r\n n_elem = int(len(s) / k)\r\n for i in range(0, n_elem):\r\n alphas = {\"A\": 1, \"B\": 1,\r\n \"C\": 1, \"D\": 1,\r\n \"E\": 1, \"F\": 1,\r\n \"G\": 1, \"H\": 1,\r\n \"I\": 1, \"J\": 1,\r\n \"K\": 1, \"L\": 1,\r\n \"M\": 1, \"N\": 1,\r\n \"O\": 1, \"P\": 1,\r\n \"Q\": 1, \"R\": 1,\r\n \"S\": 1, \"T\": 1,\r\n \"U\": 1, \"V\": 1,\r\n \"W\": 1, \"X\": 1,\r\n \"Y\": 1, \"Z\": 1}\r\n res = []\r\n for j in range(i * k, (i + 1) * k):\r\n if alphas[s[j]] > 0:\r\n res.append(s[j])\r\n alphas[s[j]] = 0\r\n print(\"\".join(res))\r\n\r\n return\r\n\r\n\r\nif __name__ == '__main__':\r\n # string, k = input(), int(input)\r\n string = \"AABCAAADA\"\r\n k = 3\r\n merge_the_tools(string, k)\r\n\r\n\r\n","sub_path":"hackerrank/merge-tools.py","file_name":"merge-tools.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"561817087","text":"# Find pairs which gives specific sum value\nfrom doublylinkedlist.doubly_linkedlist import Dll\n\n\ndef pairs_with_sum(head, sum_val):\n\n # Create empty list\n pairs = list()\n p = head\n q = None\n while p:\n q = p.next\n while q:\n if p.data + q.data == sum_val:\n pairs.append(\"(\" + str(p.data) + \",\" + str(q.data) + \")\")\n q = q.next\n p = p.next\n\n return pairs\n\n\nif __name__ == \"__main__\":\n dll = Dll()\n dll.add_at_head(1)\n dll.add_at_head(2)\n dll.add_at_head(3)\n dll.add_at_head(4)\n dll.add_at_head(5)\n print(\"Elements of linked list: \")\n dll.print_dll()\n print(\"\\n\")\n sum_value = 6\n print(\"The pairs which gives sum value {} are: \".format(sum_value))\n print(pairs_with_sum(dll.head, sum_value))\n\n\n","sub_path":"doublylinkedlist/pairs_with_sum_dll.py","file_name":"pairs_with_sum_dll.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"160323043","text":"import tensorflow as tf\nimport numpy as np\n\nclass DoubleDQN:\n def __init__(\n self,\n n_actions,\n n_features,\n learning_rate=0.01,\n reward_decay=0.9,\n e_greedy=0.9,\n replace_target_iter=300,\n memory_size=500,\n batch_size=32,\n e_greedy_increment=None,\n output_graph=False,\n double_q=True,\n sess=None\n ):\n self.n_actions = n_actions\n self.n_features = n_features\n self.lr = learning_rate\n self.gamma = reward_decay\n self.e_greedy = e_greedy\n self.replace_target_iter = replace_target_iter\n self.memory_size = memory_size\n self.batch_size = batch_size\n self.e_greedy_increment = e_greedy_increment\n self.epsilon = 0 if e_greedy_increment is not None else self.e_greedy\n self.learn_step_counter = 0\n self.memory = np.zeros((self.memory_size, n_features * 2 + 2))\n self.double_q = double_q\n self.build()\n t_params = tf.get_collection('target_net_params')\n e_params = tf.get_collection('eval_net_params')\n self.replace_target_op = [tf.assign(t, e) for t, e in zip(t_params, e_params)]\n\n if sess is None:\n self.sess = tf.Session()\n else:\n self.sess = sess\n if output_graph:\n tf.summary.FileWriter(\"logs/\", self.sess.graph)\n self.sess.run(tf.global_variables_initializer())\n self.cost_history = []\n self.saver = tf.train.Saver()\n\n def build(self):\n self.s = tf.placeholder(tf.float32, [None, self.n_features], name='s')\n self.s_ = tf.placeholder(tf.float32, [None, self.n_features], name='s_')\n self.q_target = tf.placeholder = tf.placeholder(tf.float32, [None, self.n_actions], name='Q_target')\n n_l1, w_initializer, b_initializer = 10, tf.random_normal_initializer(0., 0.3), tf.constant_initializer(0.1)\n\n def build_net(net_name, param_name, placeholder, n_actions, n_features, n_l1):\n with tf.variable_scope(net_name):\n c_names = [param_name, tf.GraphKeys.GLOBAL_VARIABLES]\n with tf.variable_scope('l1'):\n w1 = tf.get_variable('w1', [n_features, n_l1], initializer=w_initializer, collections=c_names)\n b1 = tf.get_variable('b1', [1, n_l1], initializer=b_initializer, collections=c_names)\n l1 = tf.nn.relu(tf.matmul(placeholder, w1) + b1)\n with tf.variable_scope('l2'):\n w2 = tf.get_variable('w2', [n_l1, n_actions], initializer=w_initializer, collections=c_names)\n b2 = tf.get_variable('b2', [1, n_actions], initializer=b_initializer, collections=c_names)\n target = tf.matmul(l1, w2) + b2\n return target\n\n self.q_eval = build_net('eval_net', 'eval_net_params', self.s, self.n_actions, self.n_features, n_l1)\n self.q_next = build_net('target_net', 'target_net_params', self.s_, self.n_actions, self.n_features, n_l1)\n\n with tf.variable_scope('loss'):\n self.loss = tf.reduce_mean(tf.squared_difference(self.q_target, self.q_eval))\n with tf.variable_scope('train'):\n self.train_op = tf.train.RMSPropOptimizer(self.lr).minimize(self.loss)\n\n def store_transition(self, s, a, r, s_):\n if not hasattr(self, 'memory_counter'):\n self.memory_counter = 0\n transition = np.hstack((s, [a, r], s_))\n index = self.memory_counter % self.memory_size\n self.memory[index, :] = transition\n self.memory_counter += 1\n\n def choose_action(self, observation):\n observation = observation[np.newaxis, :]\n actions_value = self.sess.run(self.q_eval, feed_dict={self.s:observation})\n action = np.argmax(actions_value)\n if not hasattr(self, 'q'):\n self.q = []\n self.running_q = 0\n self.running_q = self.running_q * 0.99 + 0.01 * np.max(actions_value)\n self.q.append(self.running_q)\n if np.random.uniform() > self.epsilon:\n action = np.random.randint(0, self.n_actions)\n return action\n\n def choose_action_test(self, observation):\n observation = observation[np.newaxis, :]\n actions_value = self.sess.run(self.q_eval, feed_dict={self.s: observation})\n action = np.argmax(actions_value)\n return action\n\n def learn(self):\n if self.learn_step_counter % self.replace_target_iter == 0:\n self.sess.run(self.replace_target_op)\n print('\\ntarget_net_replaced\\n')\n if self.memory_counter > self.memory_size:\n sample_index = np.random.choice(self.memory_size, size=self.batch_size)\n else:\n sample_index = np.random.choice(self.memory_counter, size=self.batch_size)\n batch_memory = self.memory[sample_index]\n\n q_next, q_evalnext = self.sess.run([self.q_next, self.q_eval],\n feed_dict={self.s_:batch_memory[:, -self.n_features:],\n self.s:batch_memory[:, -self.n_features:]\n })\n q_eval = self.sess.run(self.q_eval, feed_dict={self.s:batch_memory[:, :self.n_features]})\n\n q_target = q_eval.copy()\n batch_index = np.arange(self.batch_size, dtype=np.int32)\n eval_act_index = batch_memory[:, self.n_features].astype(int)\n reward = batch_memory[:, self.n_features + 1]\n\n if self.double_q:\n max_act_index = np.argmax(q_evalnext, axis=1).astype(int)\n q_select = q_next[batch_index, max_act_index]\n else:\n q_select = np.max(q_next, axis=1)\n\n q_target[batch_index, eval_act_index] = reward + self.gamma * q_select\n\n _, cost = self.sess.run([self.train_op, self.loss],\n feed_dict={self.s:batch_memory[:, :self.n_features],\n self.q_target:q_target})\n\n self.cost_history.append(cost)\n self.epsilon = self.epsilon + self.e_greedy_increment if self.epsilon < self.e_greedy else self.e_greedy\n self.learn_step_counter += 1\n\n def plot_cost(self):\n import matplotlib.pyplot as plt\n plt.plot(np.arange(len(self.cost_history)), self.cost_history)\n plt.ylabel('cost')\n plt.xlabel('train step')\n plt.show()\n\n def save_model(self, save_path):\n self.saver.save(self.sess, save_path)\n","sub_path":"DQN_Double.py","file_name":"DQN_Double.py","file_ext":"py","file_size_in_byte":6545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"502222484","text":"#\n# @lc app=leetcode.cn id=459 lang=python3\n#\n# [459] 重复的子字符串\n#\n# https://leetcode-cn.com/problems/repeated-substring-pattern/description/\n#\n# algorithms\n# Easy (38.79%)\n# Total Accepted: 4K\n# Total Submissions: 10.2K\n# Testcase Example: '\"abab\"'\n#\n# 给定一个非空的字符串,判断它是否可以由它的一个子串重复多次构成。给定的字符串只含有小写英文字母,并且长度不超过10000。\n#\n# 示例 1:\n#\n#\n# 输入: \"abab\"\n#\n# 输出: True\n#\n# 解释: 可由子字符串 \"ab\" 重复两次构成。\n#\n#\n# 示例 2:\n#\n#\n# 输入: \"aba\"\n#\n# 输出: False\n#\n#\n# 示例 3:\n#\n#\n# 输入: \"abcabcabcabc\"\n#\n# 输出: True\n#\n# 解释: 可由子字符串 \"abc\" 重复四次构成。 (或者子字符串 \"abcabc\" 重复两次构成。)\n#\n#\n#\n\n\nclass Solution:\n def repeatedSubstringPattern(self, s: str) -> bool:\n arr = []\n prev = 0\n for i in range(1, len(s)):\n if s[i] == s[0]:\n arr.append(i)\n if len(s) % (i - prev) != 0:\n return False\n prev = i\n if not len(arr):\n return False\n for idx in arr:\n if s[0:idx] * (len(s) // idx) == s:\n return True\n return False\n","sub_path":"easy/459.重复的子字符串/459.重复的子字符串.py","file_name":"459.重复的子字符串.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"90184413","text":"\"\"\"Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:\n\n21 22 23 24 25\n20 7 8 9 10\n19 6 1 2 11\n18 5 4 3 12\n17 16 15 14 13\n\nIt can be verified that the sum of the numbers on the diagonals is 101.\nWhat is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?\n\"\"\"\n\ndef get_this_damn_spiral_sum(n):\n total = 1\n for i in range(3,n+1,2):\n print(i**2)\n var = i-1\n sqr = i**2\n total += sqr * 4 - (6*var)\n\n\n return total\n\nprint(get_this_damn_spiral_sum(1001))\n","sub_path":"028.py","file_name":"028.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"437610590","text":"\"\"\"\nAuthor: Jing (https://github.com/gnijuohz)\n\nConvert Sorted Array to Binary Search Tree: https://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree \n\nGiven an array where elements are sorted in ascending order, convert it to a height balanced BST. \nTags\nTree, Depth-first Search \n\"\"\"\n\n# 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 # @param num, a list of integers\n # @return a tree node\n def sortedArrayToBST(self, num):\n if not num:\n return None\n end = len(num) - 1\n return self.constructTree(num, 0, end)\n def constructTree(self, array, start, end):\n if start > end:\n return None\n mid = (start + end)/2\n node = TreeNode(array[mid])\n node.left = self.constructTree(array, start, mid-1)\n node.right = self.constructTree(array, mid+1, end)\n return node","sub_path":"solutions/Convert-Sorted-Array-to-Binary-Search-Tree.py","file_name":"Convert-Sorted-Array-to-Binary-Search-Tree.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"27419371","text":"\n# -*- coding: utf-8 -*-\n\nfrom bs4 import BeautifulSoup\nimport requests\n# import re\nimport xlrd\n\n### this module allows to get schedule\n\ndef find_col_and_string(sheet, name):\n\n try:\n\n for col in range(0,100):\n\n cell = sheet.cell(2, col)\n if cell.value == name:\n\n return {'string': 2, 'col': col}\n\n\n except Exception as er:\n\n print(\"can't find! {}\".format(er))\n \ndef get_clean_lists(list_one, list_two, list_three):\n\n list_one_new = []\n list_two_new = []\n list_three_middle = [] \n list_three_new = []\n\n for i, value in enumerate(list_one):\n\n if list_one[i] != \"\": #and list_two[i] != '': \n\n list_one_new.append(value)\n\n for i, value in enumerate(list_two):\n\n if list_one[i] != \"\": \n\n list_two_new.append(value)\n\n for i, value in enumerate(list_three):\n\n if value != \"\" and len(str(value)) <= 5:\n\n list_three_middle.append(value)\n\n list_three_new.append('')\n\n for i, value in enumerate(list_two_new[1:len(list_two_new)]):\n\n if value != '':\n\n if len(list_three_middle):\n\n list_three_new.append(list_three_middle.pop(0))\n\n else: \n\n list_three_new.append(\"\")\n\n else:\n\n list_three_new.append(\"\")\n\n\n list_three_new = [ 'каб. ' + i if type(i) == str else 'каб. ' + str(int(i)) for i in list_three_new ]\n list_three_new = [i if len(i.replace(\" \", \"\")) > 4 else \"\" for i in list_three_new]\n\n return list_one_new, list_two_new, list_three_new\n\n\n\ndef load_schedule_from_site():\n\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:45.0) Gecko/20100101 Firefox/45.0'\n }\n \n r = requests.get(url=\"https://s11028.edu35.ru/2013-06-12-15-17-31/raspisanie\", headers = headers)\n soup = BeautifulSoup(r.content.decode('utf-8'), features = 'lxml')\n \n # soup = BeautifulSoup(html, \"lxml\")\n\n\n links = soup.findAll('a', {'class': 'at_url'})\n\n link = links[-1]['href']\n \n\n schedule = requests.get(link)\n out = open(\"schedule.xls\", \"wb\")\n\n out.write(schedule.content)\n out.close()\n\ndef get_text(list_one, list_two, list_three):\n\n result = ''\n for i, value in enumerate(list_one):\n\n result = result + list_one[i] + ' - '+list_two[i]+ ' - '+str(list_three[i])+ '\\n'\n\n return result\n\ndef get_schedule(grade):\n\n load_schedule_from_site()\n\n ###### FOR FORMAT XLS ######\n\n book = xlrd.open_workbook(\"schedule.xls\")\n sheet = book.sheet_by_index(0)\n place_of_time = find_col_and_string(sheet, 'Время')\n place_of_objects = find_col_and_string(sheet, grade.lower())\n \n\n\n values_of_time = sheet.col_values(place_of_time.get('col'), start_rowx=place_of_time.get('string'), end_rowx=50)\n \n values_of_subjects = sheet.col_values(place_of_objects.get('col'), start_rowx = place_of_objects.get('string'), end_rowx=50)\n values_of_stadiums = sheet.col_values(place_of_objects.get('col') + 1, start_rowx = place_of_objects.get('string'), end_rowx=50)\n\n\n values_of_time, values_of_subjects, values_of_stadiums = get_clean_lists(values_of_time, values_of_subjects, values_of_stadiums)\n\n return get_text(values_of_time, values_of_subjects, values_of_stadiums)\n \n\nif __name__ == '__main__':\n\n print(get_schedule('6г'))\n\n\n","sub_path":"db_tutorial/mybots/vk_bot/Schedule40/schedule.py","file_name":"schedule.py","file_ext":"py","file_size_in_byte":3356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"647274281","text":"from room import Room\nfrom player import Player\nfrom item import Item\n# Declare all the rooms\n\nroom = {\n 'outside': Room(\"Outside Cave Entrance\",\n \"North of you, the cave mount beckons\"),\n\n 'foyer': Room(\"Foyer\", \"\"\"Dim light filters in from the south. Dusty\npassages run north and east.\"\"\"),\n\n 'overlook': Room(\"Grand Overlook\", \"\"\"A steep cliff appears before you, falling\ninto the darkness. Ahead to the north, a light flickers in\nthe distance, but there is no way across the chasm.\"\"\"),\n\n 'narrow': Room(\"Narrow Passage\", \"\"\"The narrow passage bends here from west\nto north. The smell of gold permeates the air.\"\"\"),\n\n 'treasure': Room(\"Treasure Chamber\", \"\"\"You've found the long-lost treasure\nchamber! Sadly, it has already been completely emptied by\nearlier adventurers. The only exit is to the south.\"\"\"),\n}\n\nitems = {\n 'sword': Item('sword', 'very sharp and metally'),\n 'food': Item('food', 'very tasty and fulfilling'),\n 'coins': Item('coins', 'goldie stuff that we all love'),\n 'grass': Item('grass', 'you got some grass on your way here'),\n 'beer': Item('beer', 'one of your favorites')\n}\n\n# Link rooms together\n\nroom['outside'].n_to = room['foyer']\nroom['foyer'].s_to = room['outside']\nroom['foyer'].n_to = room['overlook']\nroom['foyer'].e_to = room['narrow']\nroom['overlook'].s_to = room['foyer']\nroom['narrow'].w_to = room['foyer']\nroom['narrow'].n_to = room['treasure']\nroom['treasure'].s_to = room['narrow']\n\n#\n# Main\n#\nroom['overlook'].addItemToRoom(items['food'])\nroom['outside'].addItemToRoom(items['sword'])\nroom['narrow'].addItemToRoom(items['coins'])\n# print(room['outside'].displayRoomsItems())\n\n# Make a new player object that is currently in the 'outside' room.\n\nplayer = Player('Alex', room['outside'])\nplayer.addItemToInventory(items['beer'])\nplayer.addItemToInventory(items['grass'])\n# Write a loop that:\n#\n# * Prints the current room name\n# * Prints the current description (the textwrap module might be useful here).\n# * Waits for user input and decides what to do.\n#\n# If the user enters a cardinal direction, attempt to move to the room there.\n# Print an error message if the movement isn't allowed.\n#\n# If the user enters \"q\", quit the game.\n\nuserInput = None\n\nwhile(userInput != 'q'):\n player.displayCurrentLocation()\n player.current_room.displayRoomsItems()\n player.current_room.displayDescription()\n\n correct = False\n directionsDictionary = {'n_to': player.current_room.n_to, 's_to': player.current_room.s_to,\n 'e_to': player.current_room.e_to, 'w_to': player.current_room.w_to, }\n\n while not correct:\n userInput = input(\n \"Enter which direction you want to go ( n, s, e, w), 'i' or 'inventory' to see your item and 'q' to quit: \")\n\n if len(userInput.split(' ')) == 1:\n roomDirection = userInput + '_to'\n if userInput == 'i' or userInput == 'inventory':\n player.displayPlayerItems()\n elif userInput != 'q' and directionsDictionary[roomDirection] != None:\n player.movePlayerToRoom(directionsDictionary[roomDirection])\n correct = True\n elif userInput != 'q' and directionsDictionary[roomDirection] == None:\n print('No road that direction')\n else:\n correct = True\n elif len(userInput.split(' ')) == 2:\n\n userCommand = userInput.split(' ')\n\n if userCommand[0] == 'get' or userCommand[1] == 'take':\n print(userCommand[0], userCommand[1])\n removedItemFromRoom = player.current_room.removeItemFromRoom(\n userCommand[1])\n player.addItemToInventory(removedItemFromRoom)\n removedItemFromRoom.on_take()\n elif userCommand[0] == 'drop':\n droppedItem = player.removeItemFromInventory(userCommand[1])\n droppedItem.on_drop()\n player.current_room.addItemToRoom(droppedItem)\n","sub_path":"src/adv.py","file_name":"adv.py","file_ext":"py","file_size_in_byte":4014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"433556528","text":"import logging\nimport pytest\nfrom click_skeleton.testing import run_cli\nfrom musicbot.cli import main_cli\n\nlogger = logging.getLogger(__name__)\n\n\n@pytest.mark.runner_setup(mix_stderr=False)\ndef test_spotify_playlists(cli_runner):\n run_cli(cli_runner, main_cli, [\n '--quiet',\n 'spotify', 'playlists'\n ])\n\n\n@pytest.mark.runner_setup(mix_stderr=False)\ndef test_spotify_tracks(cli_runner):\n run_cli(cli_runner, main_cli, [\n '--quiet',\n 'spotify', 'tracks'\n ])\n\n\n@pytest.mark.runner_setup(mix_stderr=False)\ndef test_spotify_diff(cli_runner, common_args):\n run_cli(cli_runner, main_cli, [\n '--quiet',\n 'spotify', 'diff',\n *common_args,\n ])\n","sub_path":"tests/test_spotify.py","file_name":"test_spotify.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"537991628","text":"from flask import Flask, render_template, request, jsonify\r\nimport os\r\nfrom werkzeug import secure_filename\r\nimport fitz\r\nimport sys\r\nimport random\r\n\r\napp = Flask(__name__, template_folder='templates')\r\nAPP_ROOT = os.path.dirname(os.path.abspath(__file__))\r\n@app.route(\"/\") #index Page\r\ndef index():\r\n return render_template(\"index.html\")\r\n\r\n@app.route('/uploader', methods=['GET', 'POST'])\r\ndef upload_file():\r\n if request.method == 'POST':\r\n f = request.files['file']\r\n f.save(secure_filename(f.filename))\r\n temp = list(f.filename)\r\n name = temp[:-3]\r\n name = \"\".join(name)\r\n ofile = name+'txt'\r\n print(name)\r\n doc = fitz.open(f.filename)\r\n pages = len(doc)\r\n fout = open(ofile, \"w\")\r\n for page in doc:\r\n text = page.getText()\r\n fout.write(text)\r\n li = []\r\n gross = []\r\n UAN = []\r\n EPF = []\r\n EE = []\r\n ER = []\r\n EPS = []\r\n d = {}\r\n e = {}\r\n ll = []\r\n lp = []\r\n fout.close()\r\n f = open(ofile,'r')\r\n for i in f.readline():\r\n li.append(i)\r\n print(li)\r\n print(\"Member Details\")\r\n start = 0\r\n length = len(li)\r\n for i in range(start, length):\r\n if len(li[i].split()) > 4:\r\n a = li[i].split()\r\n if a[0].__contains__(\",\"):\r\n gross.append(a[0])\r\n else:\r\n continue\r\n else:\r\n continue\r\n for i in range(start + 1, length):\r\n try:\r\n a = li[i].split()\r\n if len(a[5]) == 12 and int(a[5]):\r\n # print(a[5])\r\n UAN.append(a[5])\r\n EPF.append(a[7])\r\n EE.append(a[3])\r\n ER.append(a[-2])\r\n EPS.append(a[2])\r\n datalist = [UAN, EPF, EE, ER, EPS]\r\n d[UAN] = datalist\r\n print(d)\r\n if len(a[6]) == 12 and int(a[6]):\r\n # print(a[6])\r\n UAN.append(a[6])\r\n EPF.append(a[8])\r\n EE.append(a[4])\r\n ER.append(a[-2])\r\n EPS.append(a[3])\r\n datalist = [UAN, EPF, EE, ER, EPS]\r\n d[UAN] = datalist\r\n if len(a[7]) == 12 and int(a[7]):\r\n # print(a[7])\r\n UAN.append(a[7])\r\n EPF.append(a[9])\r\n EE.append(a[5])\r\n ER.append(a[-2])\r\n EPS.append(a[4])\r\n datalist = [UAN, EPF, EE, ER, EPS]\r\n d[UAN] = datalist\r\n except Exception:\r\n continue\r\n for i in range(len(gross)):\r\n a = []\r\n a.append(\"Gross =\"+gross[i])\r\n a.append(\"EPF =\"+EPF[i])\r\n a.append(\"EE =\"+EE[i])\r\n a.append(\"ER =\"+ER[i])\r\n a.append(\"EPS =\"+EPS[i])\r\n d[UAN[i]] = a\r\n print(d)\r\n f = open(ofile, 'r')\r\n li = []\r\n for i in f:\r\n li.append(i.split())\r\n print(\"NAME \" + \" \".join(li[9]))\r\n return jsonify(d)\r\nif __name__ == '__main__':\r\n app.run(debug=True)\r\n","sub_path":"Flask3/wwwTRY1.py","file_name":"wwwTRY1.py","file_ext":"py","file_size_in_byte":3358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"570905199","text":"#===========文件写入==============\n\ntext = \"good morning.\\ngood night.\\n\"\nprint(text)\n# docs https://docs.python.org/3/\nmy_file = open('this file.txt','w')\nmy_file.write(text)\nmy_file.close()\n#===========文件追加写入===========\nnew_text = \"good tomorrow\\n\"\nmy_file = open('this file.txt','a')\nmy_file.write(new_text)\nmy_file.close()\n#===========文件读取===============\nmy_file = open('this file.txt','r')# 读入的是文件\ncontent = my_file.read() # 读入文件所有内容\nprint(type(my_file))\ncontent_line = my_file.readline()# 每调用一次读取一行\ncontent_lines = my_file.readlines()# 读取所有内容,按照行放入list中\n\nprint(content_line)\n","sub_path":"class1 python 基础/10文件读写.py","file_name":"10文件读写.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"392219496","text":"from PyQt5 import QtCore, QtGui, QtWidgets\r\nfrom PyQt5.QtWidgets import *\r\nfrom PyQt5.QtCore import QCoreApplication\r\n\r\nimport caesar_cipher, autokey_cipher, multiplicative_cipher, stream_cipher, transposition_cipher, vigenere_cipher, case_transform, reverse_transform\r\n\r\nclass Ui_MainWindow(object):\r\n def __init__(self):\r\n super().__init__()\r\n self.key = 3\r\n self.input_text = \"\"\r\n self.output_text = \"jj\"\r\n self.cipher_chosen = \"Caesar Cipher\"\r\n self.trans_chosen = \"Case Transform\"\r\n self.trans_yes = 0\r\n \r\n def setupUi(self, MainWindow):\r\n MainWindow.setObjectName(\"MainWindow\")\r\n MainWindow.resize(1920, 1080)\r\n MainWindow.setAutoFillBackground(True)\r\n MainWindow.setStyleSheet(\"background-color: #A8CF99;\")\r\n \r\n self.centralwidget = QtWidgets.QWidget(MainWindow)\r\n self.centralwidget.setObjectName(\"centralwidget\")\r\n self.centralwidget.setGeometry(QtCore.QRect(10, 5, 1910, 1080))\r\n #self.centralwidget.setStyleSheet(\"background-color: black;\")\r\n \r\n # For encryption button\r\n self.radioButton1 = QtWidgets.QRadioButton(self.centralwidget)\r\n self.radioButton1.setGeometry(QtCore.QRect(1050, 40, 200, 60))\r\n self.radioButton1.setObjectName(\"Encrypt\")\r\n \r\n # For decryption Button\r\n self.radioButton2 = QtWidgets.QRadioButton(self.centralwidget)\r\n self.radioButton2.setGeometry(QtCore.QRect(1400, 40, 200, 60))\r\n self.radioButton2.setObjectName(\"Decrypt\")\r\n \r\n \r\n # For Dropdown Cipher\r\n cipher_list = [\"Caesar Cipher\", \"Multiplicative Cipher\", \"Autokey Cipher\", \"Stream Cipher\", \"Transposition Cipher\", \"Vigenere Cipher\"]\r\n self.comboBox = QtWidgets.QComboBox(self.centralwidget)\r\n self.comboBox.setGeometry(QtCore.QRect(1400, 150, 400, 80))\r\n self.comboBox.setObjectName(\"comboBox\")\r\n self.comboBox.setEditable(True)\r\n self.comboBox.addItems(cipher_list)\r\n \r\n # For Dropdown Transform\r\n cipher_list = [\"Case Transform\", \"Reverse Transform\"]\r\n self.comboBox1 = QtWidgets.QComboBox(self.centralwidget)\r\n self.comboBox1.setGeometry(QtCore.QRect(1400, 300, 400, 80))\r\n self.comboBox1.setObjectName(\"comboBox1\")\r\n self.comboBox1.setEditable(True)\r\n self.comboBox1.addItems(cipher_list)\r\n \r\n # For input button\r\n self.inputButton = QtWidgets.QPushButton(self.centralwidget)\r\n self.inputButton.setGeometry(QtCore.QRect(1050, 150, 200, 80))\r\n self.inputButton.setObjectName(\"inputButton\")\r\n \r\n # Checkbox for Transform\r\n self.trans_checkbox = QtWidgets.QCheckBox(self.centralwidget)\r\n self.trans_checkbox.setGeometry(QtCore.QRect(1050, 310, 200, 60))\r\n self.trans_checkbox.setObjectName(\"trans_checkbox\")\r\n \r\n # For Run button\r\n self.runButton = QtWidgets.QPushButton(self.centralwidget)\r\n self.runButton.setGeometry(QtCore.QRect(1050, 500, 500, 80))\r\n self.runButton.setObjectName(\"runButton\")\r\n \r\n # For flush Button\r\n self.flushButton = QtWidgets.QPushButton(self.centralwidget)\r\n self.flushButton.setGeometry(QtCore.QRect(750, 40, 200, 60))\r\n self.flushButton.setObjectName(\"flushButton\")\r\n \r\n # For open Button\r\n self.openButton = QtWidgets.QPushButton(self.centralwidget)\r\n self.openButton.setGeometry(QtCore.QRect(20, 40, 200, 60))\r\n self.openButton.setObjectName(\"openButton\")\r\n \r\n #For the list widget input\r\n self.listWidget = QtWidgets.QListWidget(self.centralwidget)\r\n self.listWidget.setGeometry(QtCore.QRect(20, 150, 450, 800))\r\n self.listWidget.setObjectName(\"listWidget\")\r\n item = QtWidgets.QListWidgetItem()\r\n self.listWidget.addItem(item)\r\n \r\n #For the list widget output\r\n self.listWidget1 = QtWidgets.QListWidget(self.centralwidget)\r\n self.listWidget1.setGeometry(QtCore.QRect(500, 150, 450, 800))\r\n self.listWidget1.setObjectName(\"listWidget1\")\r\n item = QtWidgets.QListWidgetItem()\r\n self.listWidget1.addItem(item)\r\n \r\n \r\n self.retranslateUi(MainWindow)\r\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\r\n \r\n \r\n #----------------------------------------------------------\r\n def retranslateUi(self, MainWindow):\r\n _translate = QtCore.QCoreApplication.translate\r\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"Cryptography\"))\r\n \r\n # For encrypt radio button\r\n self.radioButton1.setText(_translate(\"centralwidget\", \"Encrypt\"))\r\n self.radioButton1.setStyleSheet('QRadioButton {background-color: white; color: green; border:3px solid green;}')\r\n self.radioButton1.setChecked(True)\r\n font = QtGui.QFont()\r\n font.setFamily(\"Sitka Small\")\r\n font.setPointSize(12)\r\n self.radioButton1.setFont(font)\r\n #self.radioButton1.toggled.connect(self.onEncryptButton)\r\n \r\n # For decryption Button\r\n self.radioButton2.setText(_translate(\"centralwidget\", \"Decrypt\"))\r\n self.radioButton2.setStyleSheet('QRadioButton {background-color: white; color: green; border:3px solid green;}')\r\n font = QtGui.QFont()\r\n font.setFamily(\"Sitka Small\")\r\n font.setPointSize(12)\r\n self.radioButton2.setFont(font)\r\n #self.radioButton2.toggled.connect(self.onDecryptButton)\r\n \r\n # For the drop down transform\r\n self.comboBox.setStyleSheet('QComboBox {background-color: white; color: green; border:3px solid green; font-family: Sitka Small; font: 12;} QComboBox::down-arrow {border: 1px dotted green;}')\r\n font = QtGui.QFont()\r\n font.setFamily(\"Sitka Small\")\r\n font.setPointSize(8)\r\n self.comboBox.setFont(font)\r\n font = QtGui.QFont(\"Sitka\", 10)\r\n line_edit = self.comboBox.lineEdit()\r\n line_edit.setFont(font)\r\n self.comboBox.activated[str].connect(self.choose_cipher)\r\n \r\n # For the drop down transform\r\n self.comboBox1.setStyleSheet('QComboBox {background-color: white; color: green; border:3px solid green; font-family: Sitka Small; font: 12;} QComboBox::down-arrow {border: 1px dotted green;}')\r\n font = QtGui.QFont()\r\n font.setFamily(\"Sitka Small\")\r\n font.setPointSize(8)\r\n self.comboBox1.setFont(font)\r\n font = QtGui.QFont(\"Sitka\", 10)\r\n line_edit = self.comboBox1.lineEdit()\r\n line_edit.setFont(font)\r\n self.comboBox1.activated[str].connect(self.choose_transform)\r\n \r\n # For Key input\r\n self.inputButton.setText(_translate(\"centralwidget\", \"Enter the key\"))\r\n self.inputButton.setStyleSheet('QPushButton {background-color: white; color: green; border:4px solid green;}') \r\n font = QtGui.QFont()\r\n font.setFamily(\"Sitka Small\")\r\n font.setPointSize(12)\r\n self.inputButton.setFont(font)\r\n self.inputButton.clicked.connect(self.take_input)\r\n \r\n # Checkbox for Transform\r\n self.trans_checkbox.setText(_translate(\"centralwidget\", \"Transform\"))\r\n self.trans_checkbox.setStyleSheet('QCheckBox {background-color: white; color: green; border:3px solid green;}') \r\n font = QtGui.QFont()\r\n font.setFamily(\"Sitka Small\")\r\n font.setPointSize(10)\r\n self.trans_checkbox.setFont(font)\r\n self.trans_checkbox.stateChanged.connect(self.transbox)\r\n \r\n # For run button\r\n self.runButton.setText(_translate(\"centralwidget\", \"Submit\"))\r\n self.runButton.setStyleSheet('QPushButton {background-color: white; color: green; border:6px solid green;}') \r\n font = QtGui.QFont()\r\n font.setFamily(\"Sitka Small\")\r\n font.setPointSize(18)\r\n self.runButton.setFont(font)\r\n self.runButton.clicked.connect(self.runClicked)\r\n \r\n # For flush button\r\n self.flushButton.setText(_translate(\"centralwidget\", \"Save\"))\r\n self.flushButton.setStyleSheet('QPushButton {background-color: white; color: green; border:3px solid green;}') \r\n font = QtGui.QFont()\r\n font.setFamily(\"Sitka Small\")\r\n font.setPointSize(14)\r\n self.flushButton.setFont(font)\r\n self.flushButton.clicked.connect(self.flushClicked)\r\n \r\n # For open Button\r\n self.openButton.setText(_translate(\"centralwidget\", \"Open\"))\r\n self.openButton.setStyleSheet('QPushButton {background-color: white; color: green; border:3px solid green;}') \r\n font = QtGui.QFont()\r\n font.setFamily(\"Sitka Small\")\r\n font.setPointSize(14)\r\n self.openButton.setFont(font)\r\n self.openButton.clicked.connect(self.openClicked)\r\n \r\n # For list widget input\r\n font = QtGui.QFont()\r\n font.setFamily(\"Sitka Small\")\r\n font.setPointSize(10)\r\n self.listWidget.setWordWrap(True)\r\n self.listWidget.setFont(font)\r\n self.listWidget.setStyleSheet('QListWidget {background-color: white; color: green; border:3px solid green;}') \r\n __sortingEnabled = self.listWidget.isSortingEnabled()\r\n self.listWidget.setSortingEnabled(False)\r\n item = self.listWidget.item(0)\r\n item.setText(_translate(\"MainWindow\", \"\"))\r\n self.listWidget.setSortingEnabled(__sortingEnabled)\r\n \r\n # For list widget output\r\n font = QtGui.QFont()\r\n font.setFamily(\"Sitka Small\")\r\n font.setPointSize(10)\r\n self.listWidget1.setWordWrap(True)\r\n self.listWidget1.setFont(font)\r\n self.listWidget1.setStyleSheet('QListWidget {background-color: white; color: green; border:3px solid green;}') \r\n __sortingEnabled = self.listWidget1.isSortingEnabled()\r\n self.listWidget1.setSortingEnabled(False)\r\n item = self.listWidget1.item(0)\r\n item.setText(_translate(\"MainWindow\", \"\"))\r\n self.listWidget1.setSortingEnabled(__sortingEnabled)\r\n \r\n \r\n def onEncryptButton(self):\r\n if self.trans_yes == 0:\r\n if (self.cipher_chosen == \"Caesar Cipher\"):\r\n self.key = int(self.key)\r\n self.output_text = caesar_cipher.caesar_encryption(self.input_text, self.key)\r\n if (self.cipher_chosen == \"Multiplicative Cipher\"):\r\n self.key = int(self.key)\r\n self.output_text = multiplicative_cipher.multi_encrypt(self.input_text, self.key)\r\n if (self.cipher_chosen == \"Autokey Cipher\"):\r\n self.key = str(self.key)\r\n self.output_text = autokey_cipher.autokey_encrypt(self.input_text, self.key)\r\n if (self.cipher_chosen == \"Stream Cipher\"):\r\n self.key = str(self.key)\r\n self.output_text = stream_cipher.stream_encrypt(self.input_text, self.key)\r\n if (self.cipher_chosen == \"Transposition Cipher\"):\r\n self.key = str(self.key)\r\n self.output_text = transposition_cipher.transposition_encrypt(self.input_text, self.key)\r\n if (self.cipher_chosen == \"Vigenere Cipher\"):\r\n self.key = str(self.key)\r\n self.output_text = vigenere_cipher.vigenere_encrypt(self.input_text, self.key)\r\n else:\r\n if (self.trans_chosen == \"Case Transform\"):\r\n self.output_text = case_transform.case_transform(self.input_text)\r\n if (self.trans_chosen == \"Reverse Transform\"):\r\n self.output_text = reverse_transform.reverse(self.input_text)\r\n \r\n \r\n def onDecryptButton(self):\r\n if self.trans_yes == 0:\r\n if (self.cipher_chosen == \"Caesar Cipher\"):\r\n self.key = int(self.key)\r\n self.output_text = caesar_cipher.caesar_decryption(self.input_text, self.key)\r\n if (self.cipher_chosen == \"Multiplicative Cipher\"):\r\n self.key = int(self.key)\r\n self.output_text = multiplicative_cipher.multi_decrypt(self.input_text, self.key)\r\n if (self.cipher_chosen == \"Autokey Cipher\"):\r\n self.key = str(self.key)\r\n self.output_text = autokey_cipher.autokey_decrypt(self.input_text, self.key)\r\n if (self.cipher_chosen == \"Stream Cipher\"):\r\n self.key = str(self.key)\r\n self.output_text = stream_cipher.stream_decrypt(self.input_text, self.key)\r\n if (self.cipher_chosen == \"Transposition Cipher\"):\r\n self.key = str(self.key)\r\n self.output_text = transposition_cipher.transposition_decrypt(self.input_text, self.key)\r\n if (self.cipher_chosen == \"Vigenere Cipher\"):\r\n self.key = str(self.key)\r\n self.output_text = vigenere_cipher.vigenere_decrypt(self.input_text, self.key)\r\n else:\r\n if (self.trans_chosen == \"Case Transform\"):\r\n self.output_text = case_transform.case_transform(self.input_text)\r\n if (self.trans_chosen == \"Reverse Transform\"):\r\n self.output_text = reverse_transform.reverse(self.input_text)\r\n \r\n def choose_cipher(self, text):\r\n self.listWidget1.clear()\r\n self.cipher_chosen = text\r\n \r\n def choose_transform(self, text):\r\n self.listWidget1.clear()\r\n self.trans_chosen = text\r\n \r\n def take_input(self):\r\n self.listWidget1.clear()\r\n inp, done = QtWidgets.QInputDialog.getText(self.centralwidget, 'Key Input', 'Enter the key:') \r\n if done:\r\n self.key = inp\r\n \r\n def transbox(self, checked):\r\n if checked:\r\n self.trans_yes = 1\r\n else:\r\n self.trans_yes = 0\r\n \r\n \r\n \r\n def runClicked(self):\r\n if self.radioButton1.isChecked():\r\n self.onEncryptButton()\r\n if self.radioButton2.isChecked():\r\n self.onDecryptButton()\r\n self.listWidget1.clear()\r\n self.listWidget1.addItem(self.output_text)\r\n return\r\n \r\n \r\n def flushClicked(self):\r\n filename = QFileDialog.getSaveFileName(MainWindow, \"Save File\", '.txt')\r\n path = filename[0]\r\n if not path:\r\n return\r\n file1 = open(path, 'w')\r\n file1.write(self.output_text)\r\n file1.close() #Close the output file\r\n self.listWidget.clear()\r\n self.listWidget.addItem(self.input_text)\r\n \r\n \r\n def openClicked(self):\r\n self.listWidget1.clear()\r\n self.listWidget.clear() #clear the widget\r\n filename = QFileDialog.getOpenFileName() #open file dialog box\r\n path = filename[0] #it's address\r\n if not path:\r\n return\r\n file1 = open(path, \"r\") #open it\r\n self.input_text = file1.read() #assigning the string value\r\n self.listWidget.addItem(self.input_text) #showing it on listwidget\r\n file1.close() #Close the input file\r\n \r\n \r\nif __name__ == \"__main__\":\r\n import sys\r\n app = QtWidgets.QApplication(sys.argv)\r\n MainWindow = QtWidgets.QMainWindow()\r\n ui = Ui_MainWindow()\r\n ui.setupUi(MainWindow)\r\n MainWindow.show()\r\n sys.exit(app.exec_())","sub_path":"Codes/mainGUI.py","file_name":"mainGUI.py","file_ext":"py","file_size_in_byte":15330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"510165655","text":"import turtle\n\nscreen = turtle.Screen()\nscreen.bgcolor(\"#a5653a\")\n\nbob = turtle.Turtle()\nbob.shape(\"turtle\")\nbob.color(\"green\")\nbob.pensize(6)\nbob.speed(1)\n\nfor _ in range(6):\n bob.forward(200)\n bob.left(60)\n\nscreen.mainloop()","sub_path":"1_bimestre/slide_1/Chapter_3/ex6/hexagon.py","file_name":"hexagon.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"534277686","text":"import json\nimport random\n\nfrom gevent import pywsgi, sleep\nfrom geventwebsocket.handler import WebSocketHandler\n\n\nclass WebSocketApp(object):\n \"\"\"Send random data to the websocket\"\"\"\n\n def __call__(self, environ, start_response):\n client = (environ['REMOTE_ADDR'], environ['REMOTE_PORT'])\n print(\"New client:\", client)\n ws = environ['wsgi.websocket']\n while True:\n data = 'a' * 32 * 1024\n ws.send(data)\n # ws.send_frame(data, ws.OPCODE_TEXT)\n print(\"sent[%s]: %d bytes\" % (client, len(data)))\n data = ws.receive()\n if data is None:\n print(\"connection closed: %s\" % (client,))\n break\n print(\"recv[%s]: %d bytes\" % (client, len(data)))\n\n print(\"%s: wait for 5 seconds\\n\" % (client,))\n sleep(5)\n\n\naddress = (\"\", 10000)\nserver = pywsgi.WSGIServer(address, WebSocketApp(),\n handler_class=WebSocketHandler)\n\nprint(\"websocket listen at\", address)\nserver.serve_forever()\n","sub_path":"gevent/websocket/websocket_server.py","file_name":"websocket_server.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"248453625","text":"import sys\nimport subprocess\nimport os\nimport re\nimport time\n\n\n\nclass Test(object):\n \"\"\"\n Global database of all of the answers I did/want give students\n \"\"\"\n \n \n \"\"\"\n This is the scaling I use whenever I apply a timeout, i.e. if the student's\n solution needs more than TimeoutScalingFactor the time of my simple code, \n then I consider the submission to be wrong.\n \"\"\"\n TimeoutScalingFactor = 4\n \n def __init__(self, submitted_file, benchmark_file = \"\"):\n \"\"\"\n submitted_file: String\n File submitted by student\n \n benchmark_file: String\n File to benchmark/validate against. Can be empty if no such thing is \n available or shall be provided. \n \"\"\"\n self.submitted_file = submitted_file\n self.benchmark_file = benchmark_file\n \n self.compilation_success = True \n self.yields_correct_result = True\n \n self.last_output = \"\"\n \n self.timeout = 4000\n \n self.runtime = 0\n pass\n\n\n def ignore_wrong_output(self):\n if self.compilation_success:\n self.yields_correct_result = True\n\n\n def __get_submitted_executable_name(self):\n return \"submitted.out\"\n\n\n def __get_benchmark_executable_name(self):\n return \"benchmark.out\"\n\n\n def compile(self,compiler_call=\"g++ -O3\"):\n \"\"\"\n \n Compiles the code (and also compiles the solution). The routine needs the \n report file to write errors to, and it wants to know what the solution file\n is called. That's the file submitted by the student.\n \n Returns 1 if successful. Otherwise 0\n \n \"\"\"\n success = True \n try:\n invocation = compiler_call + \" -o \" + self.__get_submitted_executable_name() + \" \" + self.submitted_file\n returnCode = subprocess.run(invocation, shell=True)\n if returnCode.returncode!=0:\n self.last_output = \"ERROR: tried to translate with \" + invocation + \" and got \" + str(returnCode.stderr)\n return 0\n else:\n return 1\n except Exception as e:\n self.last_output = \"ERROR: wanted to translate but got an exception \" + str(e)\n return 0\n \n\n def run(self,arguments=\"\",environment_variables={\"OMP_NUM_THREADS\": \"1\"}):\n \"\"\"\n \n Compiles the code (and also compiles the solution). The routine needs the \n report file to write errors to, and it wants to know what the solution file\n is called. That's the file submitted by the student.\n \n Returns 1 if successful. Otherwise 0\n \n \"\"\"\n success = True \n encoding = 'utf-8'\n try:\n invocation = \"./\" + self.__get_submitted_executable_name() + \" \" + arguments\n my_environment = os.environ\n for i in environment_variables:\n print( \"export \" + i + \"=\" + environment_variables[i] )\n my_environment[ i ] = environment_variables[i]\n\n start_solution = time.time()\n returnCode = subprocess.run(invocation, timeout=self.timeout, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, env=my_environment )\n if returnCode.returncode!=0:\n self.last_output = \"ERROR: tried to run code with \" + arguments + \" and got \" + str(returnCode.stderr)\n return 0\n else:\n self.last_output = returnCode.stdout.decode(encoding).splitlines()[-1]\n self.runtime = time.time() - start_solution\n return 1\n except Exception as e:\n self.last_output = \"ERROR: wanted to run code but got an exception \" + str(e)\n return 0\n\n \n def search_for_pattern_in_output(self,search_pattern):\n result = \"\"\n m = re.findall( search_pattern, self.last_output )\n if m:\n result = str(m[-1])\n return result\n \n\n \n \n\n # if self.benchmark_file!=\"\":\n # invocation = compiler_call + \" -o \" + self.__get_benchmark_executable_name() + \" \" + self.benchmark_file\n # returnCode = subprocess.run(invocation, shell=True)\n \n \n ","sub_path":"Parallel/Test.py","file_name":"Test.py","file_ext":"py","file_size_in_byte":4058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"145335959","text":"# !/usr/bin/python\n# -*- coding: utf-8 -*-\nimport unittest\n\nfrom lab2 import LinearFunction\n\n__author__ = 'asaskevich'\n\n\nclass TestCase(unittest.TestCase):\n def test_math(self):\n f = LinearFunction(10, 4)\n g = LinearFunction(8, 5)\n self.assertNotEqual(f, g)\n self.assertEqual(f + g, LinearFunction(18, 9))\n self.assertEqual(f - g, LinearFunction(2, -1))\n self.assertEqual(-f, LinearFunction(-10, 4))\n self.assertEqual(f(1), f[1])\n self.assertEqual(f(1), 14)\n self.assertEqual(f * 2, LinearFunction(20, 4))\n self.assertEqual(f + 2, LinearFunction(10, 6))\n self.assertEqual(f - 2, LinearFunction(10, 2))\n self.assertEqual(f(g), f[g])\n self.assertEqual(f(g), g(f))\n\n def test_str(self):\n f = LinearFunction(1.23, 5.6789)\n self.assertEqual(str(f), '1.23 x + 5.68')\n\n def test_incompatible_types_sum(self):\n try:\n f = LinearFunction(5, 6)\n f + 'a'\n except Exception as e:\n self.assertIsInstance(e, TypeError)\n\n def test_incompatible_types_mul(self):\n try:\n f = LinearFunction(5, 6)\n f * 'a'\n except Exception as e:\n self.assertIsInstance(e, TypeError)\n\n def test_incompatible_types_sub(self):\n try:\n f = LinearFunction(5, 6)\n f - 'a'\n except Exception as e:\n self.assertIsInstance(e, TypeError)\n\n def test_incompatible_types_eq(self):\n try:\n f = LinearFunction(5, 6)\n f == 'a'\n except Exception as e:\n self.assertIsInstance(e, TypeError)\n\n def test_incompatible_types_call(self):\n try:\n f = LinearFunction(5, 6)\n g = f['a']\n except Exception as e:\n self.assertIsInstance(e, TypeError)\n","sub_path":"kurs_3/sem_1/IGI/lb/Laboratornaya_2/Лабораторная 2/tests/test_linearfunction.py","file_name":"test_linearfunction.py","file_ext":"py","file_size_in_byte":1841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"223036785","text":"def init():\n SOFTWARE = {\n (\"BitDefenderFree\", \"https://download.bitdefender.com/windows/bp/agent/en-us/bitdefender_online.exe\"),\n (\"Brave\", \"https://laptop-updates.brave.com/latest/winx64\"),\n (\"Discord\", \"https://discordapp.com/api/download?platform=win\"),\n (\"git\", \"https://git-scm.com/download/win\"),\n (\"GitKraken\", \"https://www.gitkraken.com/download/windows64\"),\n (\"GOG\", \"https://content-system.gog.com/open_link/download?path=/open/galaxy/client/setup_galaxy_1.2.46.172.exe\"),\n (\"PotPlayer\", \"http://get.daum.net/PotPlayer64/Version/Latest/PotPlayerSetup64.exe\"),\n (\"Steam\", \"https://steamcdn-a.akamaihd.net/client/installer/SteamSetup.exe\"),\n (\"qBittorrent\", \"https://sourceforge.net/projects/qbittorrent/files/qbittorrent-win32/qbittorrent-4.1.1/qbittorrent_4.1.1_x64_setup.exe/download\"),\n (\"UPlay\", \"http://ubi.li/4vxt9\"),\n (\"7Zip\", \"https://www.7-zip.org/a/7z1805-x64.exe\")\n }\n\n for name, url in SOFTWARE:\n file = r\"windows\\installers\\{}Setup.exe\".format(name)\n\n download(name, url, file)\n\n install(name, file)\n\n\ndef download(name, url, file):\n from pathlib import Path\n from urllib.request import urlretrieve\n\n if Path(file).is_file():\n print(\"{}Setup exists\".format(name))\n return\n\n print(\"Downloading {}...\".format(name))\n\n try:\n urlretrieve(url, file)\n except BaseException:\n print(\"Failed to download {}\".format(name))\n\n\ndef install(name, file):\n from subprocess import Popen\n\n print(\"Installing {}...\".format(name))\n\n Popen(\"{} /S\".format(file), shell=True)\n","sub_path":"windows/software.py","file_name":"software.py","file_ext":"py","file_size_in_byte":1638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"131358372","text":"# -*- coding: utf-8 -*-\r\ndef train_moran_v2(config_file):\r\n\r\n import sys\r\n sys.path.append('./recognition_model/MORAN_V2')\r\n\r\n import argparse\r\n import random\r\n import torch\r\n import torch.backends.cudnn as cudnn\r\n import torch.optim as optim\r\n import torch.utils.data\r\n from torch.autograd import Variable\r\n import numpy as np\r\n import os\r\n import tools.utils as utils\r\n import tools.dataset as dataset\r\n import time\r\n from collections import OrderedDict\r\n from models.moran import MORAN\r\n from alphabet.wordlist import result\r\n from yacs.config import CfgNode as CN\r\n\r\n # from wordlistart import result\r\n from alphabet.wordlistlsvt import result\r\n\r\n def read_config_file(config_file):\r\n # 用yaml重构配置文件\r\n f = open(config_file)\r\n opt = CN.load_cfg(f)\r\n return opt\r\n\r\n opt = read_config_file(config_file)\r\n\r\n\r\n # Modify\r\n opt.alphabet = result\r\n\r\n assert opt.ngpu == 1, \"Multi-GPU training is not supported yet, due to the variant lengths of the text in a batch.\"\r\n\r\n if opt.experiment is None:\r\n opt.experiment = 'expr'\r\n os.system('mkdir {0}'.format(opt.experiment))\r\n\r\n opt.manualSeed = random.randint(1, 10000) # fix seed\r\n print(\"Random Seed: \", opt.manualSeed)\r\n random.seed(opt.manualSeed)\r\n np.random.seed(opt.manualSeed)\r\n torch.manual_seed(opt.manualSeed)\r\n\r\n cudnn.benchmark = True\r\n\r\n print(opt)\r\n\r\n if not torch.cuda.is_available():\r\n assert not opt.cuda, 'You don\\'t have a CUDA device.'\r\n\r\n if torch.cuda.is_available() and not opt.cuda:\r\n print(\"WARNING: You have a CUDA device, so you should probably run with --cuda\")\r\n\r\n train_nips_dataset = dataset.lmdbDataset(root=opt.train_nips,\r\n transform=dataset.resizeNormalize((opt.imgW, opt.imgH)), reverse=opt.BidirDecoder)\r\n assert train_nips_dataset\r\n '''\r\n train_cvpr_dataset = dataset.lmdbDataset(root=opt.train_cvpr,\r\n transform=dataset.resizeNormalize((opt.imgW, opt.imgH)), reverse=opt.BidirDecoder)\r\n assert train_cvpr_dataset\r\n '''\r\n '''\r\n train_dataset = torch.utils.data.ConcatDataset([train_nips_dataset, train_cvpr_dataset])\r\n '''\r\n train_dataset = train_nips_dataset\r\n\r\n train_loader = torch.utils.data.DataLoader(\r\n train_dataset, batch_size=opt.batchSize,\r\n shuffle=False, sampler=dataset.randomSequentialSampler(train_dataset, opt.batchSize),\r\n num_workers=int(opt.workers))\r\n\r\n test_dataset = dataset.lmdbDataset(root=opt.valroot,\r\n transform=dataset.resizeNormalize((opt.imgW, opt.imgH)), reverse=opt.BidirDecoder)\r\n\r\n nclass = len(opt.alphabet.split(opt.sep))\r\n nc = 1\r\n\r\n converter = utils.strLabelConverterForAttention(opt.alphabet, opt.sep)\r\n criterion = torch.nn.CrossEntropyLoss()\r\n\r\n if opt.cuda:\r\n MORAN = MORAN(nc, nclass, opt.nh, opt.targetH, opt.targetW, BidirDecoder=opt.BidirDecoder, CUDA=opt.cuda)\r\n else:\r\n MORAN = MORAN(nc, nclass, opt.nh, opt.targetH, opt.targetW, BidirDecoder=opt.BidirDecoder, inputDataType='torch.FloatTensor', CUDA=opt.cuda)\r\n\r\n if opt.MORAN != '':\r\n print('loading pretrained model from %s' % opt.MORAN)\r\n if opt.cuda:\r\n state_dict = torch.load(opt.MORAN)\r\n else:\r\n state_dict = torch.load(opt.MORAN, map_location='cpu')\r\n MORAN_state_dict_rename = OrderedDict()\r\n for k, v in state_dict.items():\r\n name = k.replace(\"module.\", \"\") # remove `module.`\r\n MORAN_state_dict_rename[name] = v\r\n MORAN.load_state_dict(MORAN_state_dict_rename, strict=True)\r\n\r\n image = torch.FloatTensor(opt.batchSize, nc, opt.imgH, opt.imgW)\r\n text = torch.LongTensor(opt.batchSize * 5)\r\n text_rev = torch.LongTensor(opt.batchSize * 5)\r\n length = torch.IntTensor(opt.batchSize)\r\n\r\n if opt.cuda:\r\n MORAN.cuda()\r\n MORAN = torch.nn.DataParallel(MORAN, device_ids=range(opt.ngpu))\r\n image = image.cuda()\r\n text = text.cuda()\r\n text_rev = text_rev.cuda()\r\n criterion = criterion.cuda()\r\n\r\n image = Variable(image)\r\n text = Variable(text)\r\n text_rev = Variable(text_rev)\r\n length = Variable(length)\r\n\r\n # loss averager\r\n loss_avg = utils.averager()\r\n\r\n # setup optimizer\r\n if opt.adam:\r\n optimizer = optim.Adam(MORAN.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999))\r\n elif opt.adadelta:\r\n optimizer = optim.Adadelta(MORAN.parameters(), lr=opt.lr)\r\n elif opt.sgd:\r\n optimizer = optim.SGD(MORAN.parameters(), lr=opt.lr, momentum=0.9)\r\n else:\r\n optimizer = optim.RMSprop(MORAN.parameters(), lr=opt.lr)\r\n\r\n\r\n def levenshtein(s1, s2):\r\n if len(s1) < len(s2):\r\n return levenshtein(s2, s1)\r\n\r\n # len(s1) >= len(s2)\r\n if len(s2) == 0:\r\n return len(s1)\r\n\r\n previous_row = range(len(s2) + 1)\r\n for i, c1 in enumerate(s1):\r\n current_row = [i + 1]\r\n for j, c2 in enumerate(s2):\r\n insertions = previous_row[j + 1] + 1\r\n deletions = current_row[j] + 1\r\n substitutions = previous_row[j] + (c1 != c2)\r\n current_row.append(min(insertions, deletions, substitutions))\r\n previous_row = current_row\r\n\r\n return previous_row[-1]\r\n\r\n\r\n\r\n\r\n\r\n def val(dataset, criterion, max_iter=1000):\r\n print('Start val')\r\n data_loader = torch.utils.data.DataLoader(\r\n dataset, shuffle=False, batch_size=opt.batchSize, num_workers=int(opt.workers)) # opt.batchSize\r\n val_iter = iter(data_loader)\r\n max_iter = min(max_iter, len(data_loader))\r\n n_correct = 0\r\n n_total = 0\r\n distance = 0.0\r\n loss_avg = utils.averager()\r\n\r\n f = open('./log.txt','a',encoding='utf-8')\r\n\r\n for i in range(max_iter):\r\n data = val_iter.next()\r\n if opt.BidirDecoder:\r\n cpu_images, cpu_texts, cpu_texts_rev = data\r\n utils.loadData(image, cpu_images)\r\n t, l = converter.encode(cpu_texts, scanned=True)\r\n t_rev, _ = converter.encode(cpu_texts_rev, scanned=True)\r\n utils.loadData(text, t)\r\n utils.loadData(text_rev, t_rev)\r\n utils.loadData(length, l)\r\n preds0, preds1 = MORAN(image, length, text, text_rev, test=True)\r\n cost = criterion(torch.cat([preds0, preds1], 0), torch.cat([text, text_rev], 0))\r\n preds0_prob, preds0 = preds0.max(1)\r\n preds0 = preds0.view(-1)\r\n preds0_prob = preds0_prob.view(-1)\r\n sim_preds0 = converter.decode(preds0.data, length.data)\r\n preds1_prob, preds1 = preds1.max(1)\r\n preds1 = preds1.view(-1)\r\n preds1_prob = preds1_prob.view(-1)\r\n sim_preds1 = converter.decode(preds1.data, length.data)\r\n sim_preds = []\r\n for j in range(cpu_images.size(0)):\r\n text_begin = 0 if j == 0 else length.data[:j].sum()\r\n if torch.mean(preds0_prob[text_begin:text_begin+len(sim_preds0[j].split('$')[0]+'$')]).data[0] >\\\r\n torch.mean(preds1_prob[text_begin:text_begin+len(sim_preds1[j].split('$')[0]+'$')]).data[0]:\r\n sim_preds.append(sim_preds0[j].split('$')[0]+'$')\r\n else:\r\n sim_preds.append(sim_preds1[j].split('$')[0][-1::-1]+'$')\r\n else:\r\n cpu_images, cpu_texts = data\r\n utils.loadData(image, cpu_images)\r\n t, l = converter.encode(cpu_texts, scanned=True)\r\n utils.loadData(text, t)\r\n utils.loadData(length, l)\r\n preds = MORAN(image, length, text, text_rev, test=True)\r\n cost = criterion(preds, text)\r\n _, preds = preds.max(1)\r\n preds = preds.view(-1)\r\n sim_preds = converter.decode(preds.data, length.data)\r\n\r\n loss_avg.add(cost)\r\n for pred, target in zip(sim_preds, cpu_texts):\r\n if pred == target.lower():\r\n n_correct += 1\r\n f.write(\"预测 %s 目标 %s\\n\" % ( pred,target ) )\r\n distance += levenshtein(pred,target) / max(len(pred),len(target))\r\n n_total += 1\r\n\r\n f.close()\r\n\r\n print(\"correct / total: %d / %d, \" % (n_correct, n_total))\r\n print('levenshtein distance: %f' % (distance/n_total))\r\n\r\n accuracy = n_correct / float(n_total)\r\n print('Test loss: %f, accuray: %f' % (loss_avg.val(), accuracy))\r\n return accuracy\r\n\r\n def trainBatch():\r\n data = train_iter.next()\r\n if opt.BidirDecoder:\r\n cpu_images, cpu_texts, cpu_texts_rev = data\r\n utils.loadData(image, cpu_images)\r\n t, l = converter.encode(cpu_texts, scanned=True)\r\n t_rev, _ = converter.encode(cpu_texts_rev, scanned=True)\r\n utils.loadData(text, t)\r\n utils.loadData(text_rev, t_rev)\r\n utils.loadData(length, l)\r\n preds0, preds1 = MORAN(image, length, text, text_rev)\r\n cost = criterion(torch.cat([preds0, preds1], 0), torch.cat([text, text_rev], 0))\r\n else:\r\n cpu_images, cpu_texts = data\r\n utils.loadData(image, cpu_images)\r\n t, l = converter.encode(cpu_texts, scanned=True)\r\n utils.loadData(text, t)\r\n utils.loadData(length, l)\r\n preds = MORAN(image, length, text, text_rev)\r\n cost = criterion(preds, text)\r\n\r\n MORAN.zero_grad()\r\n cost.backward()\r\n optimizer.step()\r\n return cost\r\n\r\n t0 = time.time()\r\n acc = 0\r\n acc_tmp = 0\r\n for epoch in range(opt.niter):\r\n\r\n train_iter = iter(train_loader)\r\n i = 0\r\n while i < len(train_loader):\r\n # print(\"main函数里,可迭代次数为 %d\" % len(train_loader))\r\n\r\n if i % opt.valInterval == 0:\r\n for p in MORAN.parameters():\r\n p.requires_grad = False\r\n MORAN.eval()\r\n\r\n acc_tmp = val(test_dataset, criterion)\r\n if acc_tmp > acc:\r\n acc = acc_tmp\r\n torch.save(MORAN.state_dict(), '{0}/{1}_{2}.pth'.format(\r\n opt.experiment, i, str(acc)[:6]))\r\n\r\n if i % opt.saveInterval == 0:\r\n torch.save(MORAN.state_dict(), '{0}/{1}_{2}.pth'.format(\r\n opt.experiment, epoch, i))\r\n\r\n for p in MORAN.parameters():\r\n p.requires_grad = True\r\n MORAN.train()\r\n\r\n cost = trainBatch()\r\n loss_avg.add(cost)\r\n\r\n if i % opt.displayInterval == 0:\r\n t1 = time.time()\r\n print ('Epoch: %d/%d; iter: %d/%d; Loss: %f; time: %.2f s;' %\r\n (epoch, opt.niter, i, len(train_loader), loss_avg.val(), t1-t0)),\r\n loss_avg.reset()\r\n t0 = time.time()\r\n\r\n i += 1","sub_path":"model/train/moran_v2.py","file_name":"moran_v2.py","file_ext":"py","file_size_in_byte":11180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"60372862","text":"\"\"\"Posts messages to a Slack channel when new posts appear on Askbot\"\"\"\nimport json\nimport logging\nimport requests\nfrom urllib.parse import urlparse\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\ntry:\n from django.utils.translation import ugettext as _\nexcept ImportError:\n from django.utils.translation import gettext as _\nfrom askbot_slack import conf #register slack settings\nfrom askbot.conf import settings as askbot_settings\nfrom askbot.models import Post\n\n\ndef get_full_url(url):\n \"\"\"Returns full url for a given relative url\"\"\"\n base_url = urlparse(askbot_settings.APP_URL or 'http://localhost/')\n return base_url.scheme + '://' + base_url.netloc + url\n\n\ndef post_msg(msg):\n \"\"\"\n Post message to specific slack channel defined in config.\n \"\"\"\n payload = {\n \"text\": msg,\n \"username\": askbot_settings.SLACK_USERNAME,\n \"channel\": askbot_settings.SLACK_CHANNEL\n }\n try:\n requests.post(askbot_settings.SLACK_WEBHOOK_URL, data=json.dumps(payload))\n except Exception as error: #pylint: disable=broad-except\n message = unicode(error).encode('utf-8')\n logging.critical('Cannot post to slack channel: %s', message)\n\n\n\n@receiver(post_save, sender=Post)\ndef notify_post_created(sender, instance, created, raw, using, **kwargs):\n \"\"\"\n Post message when Askbot Post is created. A Post includes Questions, Comments and Answers.\n \"\"\"\n if created and askbot_settings.SLACK_ENABLED:\n params = {\n 'user': instance.author,\n 'title': instance.thread.title,\n 'url': get_full_url(instance.get_absolute_url())\n }\n if instance.is_question():\n msg = _('%(user)s asked \"%(title)s\": %(url)s') % params\n elif instance.is_answer():\n msg = _('%(user)s answered \"%(title)s\": %(url)s') % params\n elif instance.is_comment():\n msg = _('%(user)s commented on \"%(title)s\": %(url)s') % params\n post_msg(msg)\n","sub_path":"askbot_slack/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"347590210","text":"# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.\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 os\nimport sys\nimport time\nimport shutil\nimport argparse\nimport ast\nimport logging\nimport numpy as np\nimport paddle.fluid as fluid\nimport paddle.fluid.framework as framework\n\nfrom models import *\nfrom data.modelnet40_reader import ModelNet40ClsReader\nfrom data.data_utils import *\nfrom utils import *\n\nlogging.root.handlers = []\nFORMAT = '%(asctime)s-%(levelname)s: %(message)s'\nlogging.basicConfig(level=logging.INFO, format=FORMAT, stream=sys.stdout)\nlogger = logging.getLogger(__name__)\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(\"PointNet++ classification train script\")\n parser.add_argument(\n '--model',\n type=str,\n default='MSG',\n help='SSG or MSG model to train, default MSG')\n parser.add_argument(\n '--use_gpu',\n type=ast.literal_eval,\n default=True,\n help='default use gpu.')\n parser.add_argument(\n '--batch_size',\n type=int,\n default=16,\n help='training batch size, default 16')\n parser.add_argument(\n '--num_points',\n type=int,\n default=2048,\n help='number of points in a sample, default: 4096')\n parser.add_argument(\n '--num_classes',\n type=int,\n default=40,\n help='number of classes in dataset, default: 40')\n parser.add_argument(\n '--lr',\n type=float,\n default=0.01,\n help='initial learning rate, default 0.01')\n parser.add_argument(\n '--lr_decay',\n type=float,\n default=0.7,\n help='learning rate decay gamma, default 0.5')\n parser.add_argument(\n '--bn_momentum',\n type=float,\n default=0.99,\n help='initial batch norm momentum, default 0.99')\n parser.add_argument(\n '--decay_steps',\n type=int,\n default=12500,\n help='learning rate and batch norm momentum decay steps, default 12500')\n parser.add_argument(\n '--weight_decay',\n type=float,\n default=1e-5,\n help='L2 regularization weight decay coeff, default 1e-5.')\n parser.add_argument(\n '--epoch',\n type=int,\n default=201,\n help='epoch number. default 201.')\n parser.add_argument(\n '--data_dir',\n type=str,\n default='dataset/ModelNet40/modelnet40_ply_hdf5_2048',\n help='dataset directory')\n parser.add_argument(\n '--save_dir',\n type=str,\n default='checkpoints_cls',\n help='directory name to save train snapshoot')\n parser.add_argument(\n '--resume',\n type=str,\n default=None,\n help='path to resume training based on previous checkpoints. '\n 'None for not resuming any checkpoints.')\n parser.add_argument(\n '--log_interval',\n type=int,\n default=1,\n help='mini-batch interval for logging.')\n parser.add_argument(\n '--enable_ce',\n action='store_true',\n help='The flag indicating whether to run the task '\n 'for continuous evaluation.')\n args = parser.parse_args()\n return args\n\n\ndef train():\n args = parse_args()\n print_arguments(args)\n # check whether the installed paddle is compiled with GPU\n check_gpu(args.use_gpu)\n\n if not os.path.isdir(args.save_dir):\n os.makedirs(args.save_dir)\n\n assert args.model in ['MSG', 'SSG'], \\\n \"--model can only be 'MSG' or 'SSG'\"\n\n # build model\n if args.enable_ce:\n SEED = 102\n fluid.default_main_program().random_seed = SEED\n framework.default_startup_program().random_seed = SEED\n\n startup = fluid.Program()\n train_prog = fluid.Program()\n with fluid.program_guard(train_prog, startup):\n with fluid.unique_name.guard():\n train_model = PointNet2ClsMSG(args.num_classes, args.num_points) \\\n if args.model == \"MSG\" else \\\n PointNet2ClsSSG(args.num_classes, args.num_points)\n train_model.build_model(bn_momentum=args.bn_momentum)\n train_feeds = train_model.get_feeds()\n train_loader = train_model.get_loader()\n train_outputs = train_model.get_outputs()\n train_loss = train_outputs['loss']\n lr = fluid.layers.exponential_decay(\n learning_rate=args.lr,\n decay_steps=args.decay_steps,\n decay_rate=args.lr_decay,\n staircase=True)\n lr = fluid.layers.clip(lr, 1e-5, args.lr)\n params = []\n for var in train_prog.list_vars():\n if fluid.io.is_parameter(var):\n params.append(var.name)\n optimizer = fluid.optimizer.Adam(learning_rate=lr,\n regularization=fluid.regularizer.L2Decay(args.weight_decay))\n optimizer.minimize(train_loss, parameter_list=params)\n train_keys, train_values = parse_outputs(train_outputs)\n\n test_prog = fluid.Program()\n with fluid.program_guard(test_prog, startup):\n with fluid.unique_name.guard():\n test_model = PointNet2ClsMSG(args.num_classes, args.num_points) \\\n if args.model == \"MSG\" else \\\n PointNet2ClsSSG(args.num_classes, args.num_points)\n test_model.build_model()\n test_feeds = test_model.get_feeds()\n test_outputs = test_model.get_outputs()\n test_loader = test_model.get_loader()\n test_prog = test_prog.clone(True)\n test_keys, test_values = parse_outputs(test_outputs)\n\n place = fluid.CUDAPlace(0) if args.use_gpu else fluid.CPUPlace()\n exe = fluid.Executor(place)\n exe.run(startup)\n\n if args.resume:\n if not os.path.isdir(args.resume):\n assert os.path.exists(\"{}.pdparams\".format(args.resume)), \\\n \"Given resume weight {}.pdparams not exist.\".format(args.resume)\n assert os.path.exists(\"{}.pdopt\".format(args.resume)), \\\n \"Given resume optimizer state {}.pdopt not exist.\".format(args.resume)\n fluid.load(train_prog, args.resume, exe)\n\n build_strategy = fluid.BuildStrategy()\n build_strategy.memory_optimize = False\n build_strategy.enable_inplace = False\n build_strategy.fuse_all_optimizer_ops = False\n train_compile_prog = fluid.compiler.CompiledProgram(\n train_prog).with_data_parallel(loss_name=train_loss.name,\n build_strategy=build_strategy)\n test_compile_prog = fluid.compiler.CompiledProgram(test_prog)\n\n def save_model(exe, prog, path):\n if os.path.isdir(path):\n shutil.rmtree(path)\n logger.info(\"Save model to {}\".format(path))\n fluid.save(prog, path)\n\n # get reader\n trans_list = [\n PointcloudScale(),\n PointcloudRotate(),\n PointcloudRotatePerturbation(),\n PointcloudTranslate(),\n PointcloudJitter(),\n PointcloudRandomInputDropout(),\n ]\n modelnet_reader = ModelNet40ClsReader(args.data_dir, mode='train', transforms=trans_list)\n train_reader = modelnet_reader.get_reader(args.batch_size, args.num_points)\n train_loader.set_sample_list_generator(train_reader, place)\n modelnet_reader = ModelNet40ClsReader(args.data_dir, mode='test', transforms=None)\n test_reader = modelnet_reader.get_reader(args.batch_size, args.num_points)\n test_loader.set_sample_list_generator(test_reader, place)\n\n train_stat = Stat()\n test_stat = Stat()\n\n ce_time = 0\n ce_loss = []\n\n for epoch_id in range(args.epoch):\n try:\n train_loader.start()\n train_iter = 0\n train_periods = []\n while True:\n cur_time = time.time()\n train_outs = exe.run(train_compile_prog, fetch_list=train_values + [lr.name])\n period = time.time() - cur_time\n train_periods.append(period)\n train_stat.update(train_keys, train_outs[:-1])\n if train_iter % args.log_interval == 0:\n log_str = \"\"\n for name, values in zip(train_keys + ['learning_rate'], train_outs):\n log_str += \"{}: {:.5f}, \".format(name, np.mean(values))\n if name == 'loss':\n ce_loss.append(np.mean(values))\n logger.info(\"[TRAIN] Epoch {}, batch {}: {}time: {:.2f}\".format(epoch_id, train_iter, log_str, period))\n train_iter += 1\n except fluid.core.EOFException:\n logger.info(\"[TRAIN] Epoch {} finished, {}average time: {:.2f}\".format(epoch_id, train_stat.get_mean_log(), np.mean(train_periods[1:])))\n ce_time = np.mean(train_periods[1:])\n save_model(exe, train_prog, os.path.join(args.save_dir, str(epoch_id)))\n\n # evaluation\n if not args.enable_ce:\n try:\n test_loader.start()\n test_iter = 0\n test_periods = []\n while True:\n cur_time = time.time()\n test_outs = exe.run(test_compile_prog, fetch_list=test_values)\n period = time.time() - cur_time\n test_periods.append(period)\n test_stat.update(test_keys, test_outs)\n if test_iter % args.log_interval == 0:\n log_str = \"\"\n for name, value in zip(test_keys, test_outs):\n log_str += \"{}: {:.4f}, \".format(name, np.mean(value))\n logger.info(\"[TEST] Epoch {}, batch {}: {}time: {:.2f}\".format(epoch_id, test_iter, log_str, period))\n test_iter += 1\n except fluid.core.EOFException:\n logger.info(\"[TEST] Epoch {} finished, {}average time: {:.2f}\".format(epoch_id, test_stat.get_mean_log(), np.mean(test_periods[1:])))\n finally:\n test_loader.reset()\n test_stat.reset()\n test_periods = []\n\n finally:\n train_loader.reset()\n train_stat.reset()\n train_periods = []\n\n # only for ce\n if args.enable_ce:\n card_num = get_cards()\n _loss = 0\n _time = 0\n try:\n _time = ce_time\n _loss = np.mean(ce_loss[1:])\n except:\n print(\"ce info error\")\n print(\"kpis\\ttrain_cls_%s_duration_card%s\\t%s\" % (args.model, card_num, _time))\n print(\"kpis\\ttrain_cls_%s_loss_card%s\\t%f\" % (args.model, card_num, _loss))\n\ndef get_cards():\n num = 0\n cards = os.environ.get('CUDA_VISIBLE_DEVICES', '')\n if cards != '':\n num = len(cards.split(\",\"))\n return num\n\nif __name__ == \"__main__\":\n train()\n","sub_path":"PaddleCV/3d_vision/PointNet++/train_cls.py","file_name":"train_cls.py","file_ext":"py","file_size_in_byte":11411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"150857975","text":"import tensorflow as tf\n\nBASIC_CONV_MODEL_LAYERS = [(32,3),(64,3),(128,3)]\nBASIC_CONV_MODEL_BOTTLENECK = 8\n\nBASIC_FC_HEAD_LAYERS = [1024,512,256,128,64]\n\nBASIC_CONV_HEAD_LAYERS = [(64,3),(128,3),(256,3)]\n\ndef basic_conv_block(inputs, params=None, is_training=True, reuse=None):\n\n with tf.variable_scope(\"Basic_conv_block\", reuse=reuse):\n\n x = inputs\n # x = tf.layers.batch_normalization(inputs, training=is_training)\n\n for i, (filters, kernel_size) in enumerate(BASIC_CONV_MODEL_LAYERS):\n x = tf.layers.conv2d(x, filters=filters,kernel_size=kernel_size,activation=tf.nn.relu,padding=\"same\",reuse=reuse,name=\"conv_{}\".format(i+1))\n x = tf.layers.max_pooling2d(x, pool_size=2, strides=2, name=\"pool_{}\".format(i+1))\n #x = tf.layers.batch_normalization(x, training=is_training)\n\n # global max pool\n\n # bottleneck layer\n # x = tf.layers.conv2d(x,filters=BASIC_CONV_MODEL_BOTTLENECK,kernel_size=1,activation=tf.nn.relu,padding=\"same\",reuse=reuse,name=\"bottleneck\")\n # x = tf.layers.batch_normalization(x, training=is_training)\n\n return x\n\ndef basic_head_fc(inputs, params=None, is_training=True):\n\n # Get hyperparameters\n if params is None: params = {}\n num_classes = params.get('num_classes', 2)\n\n x = tf.layers.flatten(inputs)\n\n for i, num_units in enumerate(BASIC_FC_HEAD_LAYERS):\n x = tf.layers.dense(x, units=num_units, activation=tf.nn.relu, name=\"fc_{}\".format(i+1))\n x = tf.layers.batch_normalization(x, training=is_training)\n\n logits = tf.layers.dense(x, units=num_classes, name=\"logits\")\n\n return logits\n\ndef basic_head_conv(inputs, params=None, is_training=True):\n\n # Get hyperparameters\n if params is None: params = {}\n num_classes = params.get('num_classes', 2)\n\n x = inputs\n\n for i, (filters, kernel_size) in enumerate(BASIC_CONV_HEAD_LAYERS):\n x = tf.layers.conv2d(x,filters=filters,kernel_size=kernel_size,activation=tf.nn.relu,padding=\"same\",name=\"conv_{}\".format(i+1))\n x = tf.layers.batch_normalization(x, training=is_training)\n\n pool = tf.layers.average_pooling2d(x, pool_size=x.get_shape().as_list()[1], strides=1, name=\"global_avg_pool\")\n flatten = tf.layers.flatten(pool)\n\n logits = tf.layers.dense(flatten, units=num_classes, name=\"logits\")\n\n return logits\n\n\n","sub_path":"ctalearn/models/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":2342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"84617564","text":"#!/usr/bin/env python\n\"\"\"\nScript Header\n\n$Id: cmPROV21320_3pcc_upgrade_DualStack_https\n\nCopyright (c) 2016-2017 Cisco Systems, Inc.\n\nReferences:\n Tph10182140c\n Tph10182137c\n\nTopology:\n 1. One 3PCC Phone\n 2. HTTPS server and dual stack\n\nNotes:\n Precondition:\n 1. For this script the load server should support TFTP, HTTP and HTTPS\n 2. Provide the image_location, image_location_domain\n and image_location_ipv6 in env_example.txt\n\nKnown Bugs:\n\n\"\"\"\n\nimport tng\nimport logging\nfrom tng_sl.contrib.setup_helper import SetupHelpersTestCase\nfrom tng_sl.contrib.mpp.phone_config_helper import PhoneConfigHelper\nfrom cmPROV_3pcc_upgrade_base import UpgradeBaseClass\n\n\nlog = logging.getLogger('UpgradeDualStackhttps')\n\n\nclass UpgradeDualStackhttps(UpgradeBaseClass, SetupHelpersTestCase):\n helpers = (PhoneConfigHelper, )\n helper_number_devices = 1\n\n # TIMS_ID: Tph10182140c\n # Author: Yang Wang (yangw3@cisco.com)\n # Description and Test Steps:\n # upgrade_https_ipv6\n # 1. Config upgrade rule of ipv6 domainName on oPhone1 webpage\n # 2. Phone upgrade as upgrade rule\n # 3. phone back to origin build\n # Verify:\n # 1. Phone upgrade as target build\n\n def test0101_upgrade_ipv6_https(self):\n log.info(\"Start of upgrade over ipv6 HTTPS\")\n self.setup_ugrade_rule_and_upgrade(\n 'https',\n self.https[\"domain_name_ipv6\"],\n self.alt_image_one,\n self.https)\n self.check_phone_firmware()\n log.info(\"End of upgrade over ipv6 HTTPS\")\n\n # TIMS_ID: Tph10182137c\n # Author: Yang Wang (yangw3@cisco.com)\n # Description and Test Steps:\n # upgrade_https_dualdomain\n # 1. Config upgrade rule of dual domainName on oPhone1 webpage\n # 2. Phone upgrade as upgrade rule\n # 3. phone back to origin build\n # Verify:\n # 1. Phone upgrade as target build\n\n def test0102_upgrade_dualdomain_https(self):\n log.info(\"Start of upgrade over dualdomain HTTPS\")\n self.setup_ugrade_rule_and_upgrade(\n 'https',\n self.https[\"domain_name\"],\n self.alt_image_two,\n self.https)\n self.check_phone_firmware()\n log.info(\"End of upgrade over dualdomain HTTPS\")\n\n\ndef main():\n tng.api.runner()\n\nif __name__ == '__main__':\n tng.run(main)\n","sub_path":"common/Provisioning/cmPROV21320_3pcc_upgrade_DualStack_https.py","file_name":"cmPROV21320_3pcc_upgrade_DualStack_https.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"115213840","text":"import math\n\ndef float_to_string(number):\n return (\"%101.0f\" % number).strip()\n\ndef get_int_str(number):\n n_str = float_to_string(number)\n return n_str.split(\".\")[0]\n\ndef get_first_digits(number, how_many):\n n_str = get_int_str(number)\n return n_str[0:how_many]\n\ndef half_size(value):\n return int(math.ceil(float(value)/2)) \n\ndef get_end_for_size(size):\n return float(\"\".join(['9']*size))\ndef get_first_for_size(size):\n return float(\"\".join(['1'] + ['0']*(size-1)))\n\ndef reverse_string(string):\n return string[::-1]\n\ndef is_palyndrome(number):\n n_str = get_int_str(number)\n size = len(n_str)\n if size % 2 == 0:\n first_half = n_str[0:size/2]\n second_half = n_str[size/2:len(n_str)] \n \n else:\n first_half = n_str[0:size/2]\n second_half = n_str[(size/2 + 1):len(n_str)]\n return first_half == reverse_string(second_half)\n\ndef generate_palyndrome(half, size):\n if size==1:\n return half\n else:\n if size % 2 == 0:\n half_str = get_int_str(half)\n return half_str + reverse_string(half_str)\n else:\n half_str = get_int_str(half)\n prefix = half_str[0:-1]\n middle = half_str[-1]\n suffix = reverse_string(prefix)\n return prefix+middle+suffix\n \ndef generate_palindromes(start,end):\n count = 0\n start_size = len(get_int_str(start))\n end_size = len(get_int_str(end))\n end_half = get_first_digits(end, half_size(end_size))\n \n current_size = start_size\n current_half = float(get_first_digits(start, half_size(current_size)))\n current_half_size_end = get_end_for_size(half_size(current_size))\n \n while True:\n pal = float(generate_palyndrome(current_half, current_size))\n if pal > end:\n break\n \n if pal >= start:\n pal_str = float_to_string(pal)\n p2 = math.pow(pal,2) \n if is_palyndrome(p2):\n #print float_to_string(pal), float_to_string(p2), is_palyndrome(p2)\n count = count + 1\n elif len(pal_str) == pal_str.count('0') + pal_str.count('1'):\n #print pal_str\n count = count\n \n current_half = current_half + 1.0\n if current_half > float(current_half_size_end):\n current_size = current_size + 1\n current_half_size_end = get_end_for_size(half_size(current_size))\n current_half = get_first_for_size(half_size(current_size)) \n \n return count\n\n\ndef get_numbs(start,end):\n start = math.ceil(math.sqrt(start))\n end = math.floor(math.sqrt(end))\n pals = generate_palindromes(start, end)\n return pals\n\n\n\nfile = open(\"C-small-attempt0.in\")\nlines = file.readlines()\nlines = lines[1:]\n\nout = open(\"results.out\", \"w\")\nfor i in range(len(lines)):\n splits = lines[i].split(\" \")\n start = float(splits[0])\n end = float(splits[1])\n print >> out, \"Case #\"+str(i+1)+\":\",get_numbs(start,end)\n\n\n\n","sub_path":"solutions_2463486_0/Python/djokov/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":3057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"553151981","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\nimport sys\nsys.path.append(\"/home/hanson/facetools\")\nsys.path.append(\"TrainingNet\")\nsys.path.append(\"TrainingLoss\")\nimport numpy as np\nimport tensorflow as tf\nimport importlib\nimport config\nimport tensorflow.contrib.slim as slim\nimport time\nfrom datetime import datetime\nfrom utils.benchmark_validate import *\nimport shutil\nimport faceutils as fu\nfrom utils.input_dataset import TFRecordDataset\n\n\n\nclass trainFR():\n def __init__(self):\n #1. load config file\n self.conf=config.get_config()\n #2. create log and model saved dir according to the datetime\n subdir = datetime.strftime(datetime.now(), '%Y%m%d-%H%M%S')\n self.models_dir = os.path.join(\"saved_models\", subdir, \"models\")\n if not os.path.isdir(self.models_dir): # Create the model directory if it doesn't exist\n os.makedirs(self.models_dir)\n self.logs_dir = os.path.join(\"saved_models\", subdir, \"logs\")\n if not os.path.isdir(self.logs_dir): # Create the log directory if it doesn't exist\n os.makedirs(self.logs_dir)\n self.topn_models_dir = os.path.join(\"saved_models\", subdir, \"topn\")#topn dir used for save top accuracy model\n if not os.path.isdir(self.topn_models_dir): # Create the topn model directory if it doesn't exist\n os.makedirs(self.topn_models_dir)\n \n #3. load dataset\n if self.conf.use_tfrecord:\n self.inputdataset=TFRecordDataset(self.conf)\n else:\n self.inputdataset=fu.TFImageDataset(self.conf)\n \n \n\n self.traindata_iterator,self.traindata_next_element=self.inputdataset.generateDataset( )\n self.nrof_classes=self.inputdataset.nrof_classes\n\n\n def make_model(self):\n #2.load dataset and define placeholder\n self.phase_train = tf.placeholder(tf.bool, name='phase_train')\n self.images_input = tf.placeholder(name='input', shape=[None, self.conf.input_img_height,self.conf.input_img_width, 3], dtype=tf.float32)\n self.labels_input = tf.placeholder(name='labels', shape=[None, ], dtype=tf.int64)\n\n #3.load model and inference\n network = importlib.import_module(self.conf.fr_model_def)\n print (\"trianing network:%s\"%self.conf.fr_model_def)\n print (\"input image [ height:%d width:%d channel:%d ]\"%(self.conf.input_img_height,self.conf.input_img_width,3))\n\n self.prelogits = network.inference(\n self.images_input,\n dropout_keep_prob=0.8,\n phase_train=self.phase_train,\n weight_decay=self.conf.weight_decay,\n feature_length=self.conf.feature_length)\n \n def summary(self):\n\n #add grad histogram op\n for grad, var in self.grads:\n if grad is not None:\n tf.summary.histogram(var.op.name + '/gradients', grad)\n\n #add trainabel variable gradients\n for var in tf.trainable_variables():\n tf.summary.histogram(var.op.name, var)\n\n #add loss summary\n tf.summary.scalar(\"softmax_loss\",self.softmaxloss)\n tf.summary.scalar(\"total_loss\",self.total_loss)\n tf.summary.scalar(\"learning_rate\",self.learning_rate)\n\n self.summary_op = tf.summary.merge_all()\n\n def loss(self):\n logits = slim.fully_connected(self.prelogits,\n self.nrof_classes,\n activation_fn=None,\n weights_initializer=slim.initializers.xavier_initializer(),\n weights_regularizer=slim.l2_regularizer(5e-4),\n scope='Logits',\n reuse=False)\n self.softmaxloss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=self.labels_input),name=\"loss\")\n\n # Norm for the prelogits\n eps = 1e-4\n prelogits_norm = tf.reduce_mean(tf.norm(tf.abs(self.prelogits)+eps, ord=1, axis=1))\n tf.add_to_collection('losses', prelogits_norm * 5e-4)\n tf.add_to_collection('losses', self.softmaxloss)\n\n custom_loss=tf.get_collection(\"losses\")\n regularization_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)\n self.total_loss=tf.add_n(custom_loss+regularization_losses,name='total_loss')\n\n\n\n embeddings = tf.nn.l2_normalize(self.prelogits, 1, 1e-10, name='embeddings')\n self.predict_labels=tf.argmax(logits,1)\n\n #adjust learning rate\n self.global_step = tf.Variable(0, trainable=False)\n if self.conf.lr_type=='exponential_decay':\n self.learning_rate = tf.train.exponential_decay(self.conf.learning_rate,\n self.global_step,\n self.conf.learning_rate_decay_step,\n self.conf.learning_rate_decay_rate,\n staircase=True)\n elif self.conf.lr_type=='piecewise_constant':\n self.learning_rate = tf.train.piecewise_constant(self.global_step, self.conf.boundaries, self.conf.values)\n elif self.conf.lr_type=='manual_modify':\n pass\n\n\n print (\"lr stratege : %s\"%self.conf.lr_type)\n\n\n def optimizer(self):\n if self.conf.optimizer=='ADAGRAD':\n opt = tf.train.AdagradOptimizer(self.learning_rate)\n elif self.conf.optimizer=='ADADELTA':\n opt = tf.train.AdadeltaOptimizer(self.learning_rate, rho=0.9, epsilon=1e-6)\n elif self.conf.optimizer=='ADAM':\n opt = tf.train.AdamOptimizer(self.learning_rate, beta1=0.9, beta2=0.999, epsilon=0.1)\n elif self.conf.optimizer=='RMSPROP':\n opt = tf.train.RMSPropOptimizer(self.learning_rate, decay=0.9, momentum=0.9, epsilon=1.0)\n elif self.conf.optimizer=='MOM':\n opt = tf.train.MomentumOptimizer(self.learning_rate, 0.9, use_nesterov=True)\n else:\n raise ValueError('Invalid optimization algorithm')\n print (\"optimizer stratege : %s\"%self.conf.optimizer)\n\n self.grads = opt.compute_gradients(self.total_loss)\n update_ops = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)+tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n apply_gradient_op = opt.apply_gradients(self.grads, global_step=self.global_step)\n\n\n variable_averages = tf.train.ExponentialMovingAverage(0.9999, self.global_step)\n variables_averages_op = variable_averages.apply(tf.trainable_variables())\n\n with tf.control_dependencies([apply_gradient_op, variables_averages_op]):\n self.train_op = tf.no_op(name='train')\n\n return self.train_op\n\n\n def process(self):\n saver=tf.train.Saver(tf.trainable_variables(),max_to_keep=2)\n\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n sess.run(tf.local_variables_initializer())\n summary_writer=tf.summary.FileWriter(self.logs_dir,sess.graph)\n\n for epoch in range(self.conf.max_nrof_epochs):\n sess.run(self.traindata_iterator.initializer)\n while True:\n use_time=0\n try:\n start_time=time.time()\n images_train, labels_train = sess.run(self.traindata_next_element)\n \n input_dict={self.phase_train:True,self.images_input:images_train,self.labels_input:labels_train}\n result_op=[self.train_op,self.global_step,self.learning_rate,self.total_loss,self.predict_labels,self.labels_input]\n _,step,lr,train_loss,predict_labels,real_labels ,summary_str= sess.run(result_op+[self.summary_op],feed_dict=input_dict)\n summary_writer.add_summary(summary_str, global_step=step)\n end_time=time.time()\n use_time+=(end_time-start_time)\n train_acc=np.equal(predict_labels,real_labels).mean()\n\n #display train result\n if(step%self.conf.display_iter==0):\n print (\"step:%d lr:%f time:%.3f s total_loss:%.3f acc:%.3f epoch:%d\"%(step,lr,use_time,train_loss,train_acc,epoch) )\n use_time=0\n \n if (self.conf.save_iter!=-1 and step%self.conf.save_iter==0):\n print (\"save checkpoint\")\n filename_cpkt = os.path.join(self.models_dir, \"%d.ckpt\"%step)\n saver.save(sess, filename_cpkt)\n\n if (self.conf.test_iter!=-1 and step%self.conf.test_iter==0):\n if self.conf.benchmark_dict[\"test_lfw\"] :\n acc_dict=test_benchmark(self.conf,self.models_dir)\n if acc_dict[\"lfw_acc\"]>self.conf.topn_threshold:\n with open(os.path.join(self.logs_dir,\"topn_acc.txt\"),\"a+\") as topn_file:\n topn_file.write(\"%s %s\\n\"%(os.path.join(self.topn_models_dir, \"%d.ckpt\"%step),str(acc_dict)) )\n shutil.copyfile(os.path.join(self.models_dir, \"%d.ckpt.meta\"%step),os.path.join(self.topn_models_dir, \"%d.ckpt.meta\"%step))\n shutil.copyfile(os.path.join(self.models_dir, \"%d.ckpt.index\"%step),os.path.join(self.topn_models_dir, \"%d.ckpt.index\"%step))\n shutil.copyfile(os.path.join(self.models_dir, \"%d.ckpt.data-00000-of-00001\"%step),os.path.join(self.topn_models_dir, \"%d.ckpt.data-00000-of-00001\"%step))\n \n \n except tf.errors.OutOfRangeError:\n print(\"End of epoch \")\n break\n def run(self):\n self.make_model()\n self.loss()\n self.optimizer()\n self.summary()\n self.process()\n\n\n\n\nif __name__==\"__main__\":\n fr=trainFR()\n fr.run()","sub_path":"trainFR_softmax.py","file_name":"trainFR_softmax.py","file_ext":"py","file_size_in_byte":10388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"411536506","text":"import unittest\n\nfrom data_structures.trees_and_graphs.binary_search_tree import (\n BinarySearchTree\n)\n\n\ndef recursive_helper(current_node, is_balanced):\n \"\"\"Recursively check if left and right trees of current node are balanced\n\n Parameters\n ----------\n current_node : Node\n Node to check in a binary search tree\n is_balanced : bool\n True if all nodes checked so far are balanced, False if any nodes\n checked so far are unbalanced\n\n Returns\n -------\n height : int\n Height of current node\n is_balanced : bool\n True if all nodes checked so far are balanced, False if any nodes\n checked so far are unbalanced\n \"\"\"\n # Break case for recursion:\n if current_node is None:\n return 0, is_balanced\n\n # Recursively get heights of sub-trees at left and right nodes, checking\n # that both sub-trees are balanced\n left_height, is_balanced_left = recursive_helper(\n current_node.left_node, is_balanced\n )\n if not is_balanced_left:\n return None, is_balanced_left\n right_height, is_balanced_right = recursive_helper(\n current_node.right_node, is_balanced\n )\n if not is_balanced_right:\n return None, is_balanced_right\n\n # Check that heights of left and right sub-trees don't differ by more than\n # 1\n if abs(left_height - right_height) > 1:\n return None, False\n\n return max(left_height, right_height) + 1, is_balanced\n\n\ndef check_balanced(tree):\n \"\"\"Check if a binary search tree is balanced\n\n Tree is balanced if the left and right sub-tree of every node has heights\n that do not differ from each other by more than 1. Height is the number of\n connections from the current node to the leaf node, along the most direct\n (downward) route.\n\n Parameters\n ----------\n tree : BinarySearchTree\n Tree to check\n\n Returns\n -------\n is_balanced : bool\n True if all nodes in tree are balanced, False if any nodes are\n unbalanced\n \"\"\"\n node, is_balanced = recursive_helper(tree.root, True)\n\n return is_balanced\n\n\nclass Test(unittest.TestCase):\n \"\"\"Test cases\"\"\"\n # Define test case inputs, and expected outputs\n data = [\n ([9, 7, 10, 6, 8, 11], True),\n ([9, 7, 11, 5, 8, 3], False),\n ]\n\n def test_check_balanced(self):\n for test_input, test_output in self.data:\n # Generate tree from array\n tree = BinarySearchTree()\n [tree.insert(i) for i in test_input]\n\n self.assertEqual(\n check_balanced(tree), test_output\n )\n\n\nif __name__ == '__main__':\n\n unittest.main()\n","sub_path":"chapter_4/4_check_balanced.py","file_name":"4_check_balanced.py","file_ext":"py","file_size_in_byte":2663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"17692537","text":"## python cmp2.py /netshare1/home1/szzhongxin/proj1/hansun/annotation/snpindel_snp3030_raw.snp.recalibrated.vcf hcc_validated\n\nimport sys\n\na=[]\nb=[]\n\ninFile1=open(sys.argv[1],'r')\ninFile2=open(sys.argv[2],'r')\n\ni=0\nwhile i<125 :\n inFile1.readline()\n i+=1\n\nfor line in inFile1 :\n fields=line.split('\\t')\n pos=fields[0]+'\\t'+fields[1]\n a.append(pos)\n \n\n \nfor line in inFile2 :\n fields=line.split('\\t')\n pos='chr'+fields[1]+'\\t'+fields[3]\n b.append(pos)\n \ninFile1.close()\ninFile2.close()\n\nsa=set(a)\nsb=set(b)\n\nab=sa & sb \nprint('\\t'.join(list(ab)))\n\n\n\n","sub_path":"cc_mcc_seq/Cmp/cmp2.py","file_name":"cmp2.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"63362773","text":"from __future__ import print_function\nimport nltk\nfrom nltk.corpus import wordnet as wn\n\t\ndef predictive_ontology(word_list):\n\tprint(\"\\n~Beginning Predictive Ontology~\\n\")\n\tchoiceSets(word_list)\n\tsimilarity(word_list)\n\ndef choiceSets(word_list):\n\thypernyms = [wn.synsets(word)[0].hypernyms() for word in word_list if wn.synsets(word)]\n\thypernyms = filter(None, hypernyms) \n\tchoice_sets = [{\"name\": first_lemma_name(hypernym[0]), \"choices\" : [first_lemma_name(hyponym) for hyponym in hypernym[0].hyponyms()]} for hypernym in hypernyms]\n\tunique_choice_sets = {}\n\tfor choice_set in choice_sets:\n\t\tunique_choice_sets[choice_set[\"name\"]] = choice_set[\"choices\"]\n\n\tprint(\"\\n\\nnames of sets\\n\", ', '.join([choice_set for choice_set in unique_choice_sets]))\n\tprint(\"\\n\\nchoice sets\\n\", unique_choice_sets)\n\ndef similarity(word_list):\n\tsimilarities = []\n\tsynsets = [wn.synsets(word)[0] for word in word_list if wn.synsets(word)]\n\tfor firstWord in synsets:\n\t\tfor otherWord in synsets:\n\t\t\tif first_lemma_name(firstWord) not in first_lemma_name(otherWord):\n\t\t\t\tsimilarity = {\"first_word\": first_lemma_name(firstWord), \"second_word\": first_lemma_name(otherWord), \"distance\": firstWord.path_similarity(otherWord)}\n\t\t\t\tsimilarities.append(similarity)\n\tsimilarities = sorted(similarities, key=lambda similarity: similarity[\"distance\"], reverse=True)\n\n\tprint(\"\\n\\n50 most similar word pairings\\n\", similarities[:50])\n\ndef first_lemma_name(synset):\n\treturn synset.lemmas()[0].name()\n\n","sub_path":"modules/predictive_ontology.py","file_name":"predictive_ontology.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"367680465","text":"def is_all_upper(text: str) -> bool:\n t = True\n x = 0\n arr=text\n y = len(text)\n print(type(x))\n while x < y:\n if (arr[x].isupper() or arr[x] == \" \" or arr[x].isdigit()):\n x+=1\n t = True\n continue\n else:\n t = False\n print(t)\n return False\n print(t)\n return t\n\nif __name__ == '__main__':\n print(\"Example:\")\n # print(is_all_upper('ALL UPPER'))\n\n # These \"asserts\" are used for self-checking and not for an auto-testing\n assert is_all_upper('ALL UPPER') == True\n assert is_all_upper('all lower') == False\n assert is_all_upper('mixed UPPER and lower') == False\n assert is_all_upper('') == True\n print(\"Coding complete? Click 'Check' to earn cool rewards!\")\n","sub_path":"is_all_upper.py","file_name":"is_all_upper.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"421216517","text":"#! /usr/bin/python\n# -*- coding: euc-jp -*-\n# Written by Shigeki Matsuda\n# Copyright (C) 2013 NICT\n\nimport sys\n\nimport numpy\nimport theano\nimport theano.tensor as T\n\n# 推定条件の設定\n\ndatfilename=sys.argv[1] # 入力データのファイル名\noutfilename=sys.argv[2] # 出力データのファイル名\nrbmfilename=sys.argv[3] # RBM 定義ファイル名\n\nmbsize =int(sys.argv[4]) # ミニバッチサイズ\n\n# モデルパラメータの読み込みと領域の確保\n\nW=theano.shared(\n value=numpy.load(rbmfilename+\".W.npy\"),\n name=\"W\")\n\nHBias=theano.shared(\n value=numpy.load(rbmfilename+\".HBias.npy\"),\n name=\"HBias\")\n\nVBias=theano.shared(\n value=numpy.load(rbmfilename+\".VBias.npy\"),\n name=\"VBias\")\n\nhidnum=len(HBias.get_value())\nvisnum=len(VBias.get_value())\n\n\n# 伝播の数式の作成\n\nv0act=T.fmatrix(\"v0act\")\nh0act=T.nnet.sigmoid(T.dot(v0act,W )+HBias)\n\n# 出力計算用 Python 関数の作成\n\npropageter=theano.function(inputs=[v0act],outputs=h0act)\n\n# 出力データの計算処理\nfor i in range(1,17):\n # 学習用入力データファイルの読み込み\n data=numpy.fromfile(datfilename+str(i)+\".xdat\",dtype=\">f4\")\n data=data.reshape(len(data)/visnum,visnum)\n\n mbnum=len(data)/mbsize\n\n f=open(outfilename+str(i)+\".xdat\",\"wb\")\n\n for b in range(mbnum):\n out=propageter(data[mbsize*b:mbsize*(b+1)])\n out.byteswap(True)\n out.tofile(f)\n del data\n del out \n f.close()\n","sub_path":"DNN/audiovisual/script/fprop_rbm.py","file_name":"fprop_rbm.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"250281185","text":"# https://stackoverflow.com/questions/22676/how-do-i-download-a-file-over-http-using-python\n# progress bar - https://stackoverflow.com/questions/22676/how-do-i-download-a-file-over-http-using-python\n\nimport requests\nfrom requests import Response\nfrom os.path import normpath, basename\n\n\ndef download_file(url, file_save_as: str = None) -> str:\n resp: Response = requests.get(url, stream=True)\n if file_save_as is None:\n file_save_as = basename(normpath(url)) # url.split(\"/\")[-1]\n with open(file_save_as, 'wb') as file:\n for chunk in resp.iter_content(chunk_size=1024):\n if chunk: # filter out keep-alive new chunks\n file.write(chunk)\n file.flush()\n\n\ndownload_file(\"https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3\")\ndownload_file(\"https://images.unsplash.com/photo-1526666923127-b2970f64b422?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1052&q=80\", file_save_as='telescope.jpg')\n","sub_path":"python/http/download_file.py","file_name":"download_file.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"427279154","text":"class Solution:\n def addDigits(self, num):\n \"\"\"\n :type num: int\n :rtype: int\n \"\"\"\n while len(str(num))!=1:\n num = sum([int(x) for x in str(num)])\n return num\n\ns = Solution()\nprint(s.addDigits(38))","sub_path":"258. Add Digits.py","file_name":"258. Add Digits.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"179437796","text":"import time\nimport sys, getopt\nfrom os import listdir\nfrom os.path import isfile, join\nimport entity_extraction\nimport json\nimport csv\nimport file_utils\n\ndef get_files(directory):\n files = [f for f in listdir(directory) if isfile(join(directory, f))]\n return files\n\ndef process(input_dir, output_dir, language):\n event_list = set()\n\n with open('event_KG.csv', \"r\") as csvfile:\n content = csv.reader(csvfile)\n for row in content:\n event_list.add(row[0])\n\n checkpoint_doc_list = []\n\n if not file_utils.path_exists(output_dir):\n # create the output dir\n file_utils.create_folder(output_dir)\n else:\n try:\n checkpoint_doc_list = file_utils.read_file_to_list(output_dir+'/checkpoint.txt')\n except:\n pass\n\n input_files = get_files(input_dir)\n\n print('Total number of docs:',len(input_files))\n print('Already processed :', len(checkpoint_doc_list))\n\n for file in input_files:\n\n if file in checkpoint_doc_list:\n continue\n\n file_content = file_utils.read_json_file(input_dir+'/'+file)\n\n processed_outputs = {}\n\n while True:\n\n for doc_id in file_content:\n\n text = file_content[doc_id]['info']['body'].replace('\\n', ' ').strip()\n\n # maximum number of characters Wikifier can process\n max_char = 20000\n number_of_queries = int(len(text) / max_char) +1\n\n wikifier_annotations = {'annotations':[]}\n for i in range(0, number_of_queries):\n start_index, end_index = i*max_char, -1\n if i != number_of_queries -1:\n end_index = (i + 1) * max_char\n wikifier_text = text[start_index:end_index]\n wikifier_output = entity_extraction.get_wikifier_annotations(wikifier_text, language)\n\n if wikifier_output['processed'] == True:\n\n # extract each annotation and add to the global list\n for wiki_anno in wikifier_output['annotations']:\n wikifier_annotations['annotations'].append(wiki_anno)\n else:\n print(\"Rate limit is reached, sleeping for 10 mins\")\n time.sleep(10 * 60)\n\n spacy_annotations = entity_extraction.get_spacy_annotations(text, language)\n\n linked_entities = entity_extraction.link_annotations(spacy_annotations, wikifier_annotations)\n linked_entities = entity_extraction.fix_entity_types(linked_entities, event_list)\n\n # save the content\n output = {\"text\": text, \"merged_entities\": linked_entities, \"spacy_entities\": spacy_annotations,\n \"wikifier_entities\": wikifier_annotations}\n processed_outputs[doc_id] = output\n\n output_json = json.dumps(processed_outputs)\n file_utils.save_string_to_file(output_json, output_dir + '/' + file)\n checkpoint_doc_list.append(file)\n\n file_utils.save_list_to_file(checkpoint_doc_list, output_dir + '/checkpoint.txt')\n\n print('Processed: ', len(checkpoint_doc_list), '/', len(input_files))\n\n break\n\ndef main(argv):\n input_dir = ''\n output_dir = ''\n language = ''\n try:\n opts, args = getopt.getopt(argv,\"hi:o:l:\",[\"i_dir=\",\"o_dir=\", \"lang=\"])\n except getopt.GetoptError:\n print('preprocess_documents.py -i -o -l ')\n sys.exit(2)\n for opt, arg in opts:\n if opt == '-h':\n print('preprocess_documents.py -i -o -l ')\n sys.exit()\n elif opt in (\"-i\", \"--i_dir\"):\n input_dir = arg\n elif opt in (\"-o\", \"--o_dir\"):\n output_dir = arg\n elif opt in (\"-l\", \"--lang\"):\n language = arg\n\n print('Input dir: ', input_dir)\n print('Output dir: ', output_dir)\n print('Language: ', language)\n\n if input_dir =='' or output_dir =='' or language == '':\n print('preprocess_documents.py -i -o -l ')\n else:\n process(input_dir, output_dir, language)\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])","sub_path":"preprocess_documents.py","file_name":"preprocess_documents.py","file_ext":"py","file_size_in_byte":4301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"383837802","text":"import re\nimport os\n\n\nchp_sep_word = \"Глава [\\d\\.'I''V''X']*.*?\\n\"\nart_sep_word = \"Статья [\\d\\.]+\\. \"\npar_sep_word = \"\\n\\d\\. \"\nart_sep_word_name = 'Статья [\\d\\.]+?\\. .*?\\n'\n\n\nclass Collection: #класс для коллекции\n def __init__(self, text):\n self.text = text\n self.d = {}\n\n def itersplit(self, sep):\n #функция для разделения текста по sep и возвращаю по одному\n exp = re.compile(sep)\n if exp.search(self.text, 0) is None:\n return\n m1 = exp.search(self.text, 0)\n pos = m1.start()\n if sep == chp_sep_word:\n pos = m1.start()\n m1 = exp.search(self.text, pos)\n while True:\n m = exp.search(self.text, m1.start() + 1)\n if not m:\n yield self.text[pos:], m1[0]\n break\n yield self.text[pos:m.start()], m1[0]\n pos = m.end()\n m1 = m\n\n\ndef iter_by_chapter(collect, doc_id):\n #итерирование по главам с возвращением двух словрей -- d[текст] = номер главы,\n # d[номер главы] = текст\n d_chp, d_rev = {}, {}\n for i, num_chp in collect.itersplit(chp_sep_word):\n num_chp = num_chp.split(' ')[1]\n d_chp[doc_id, num_chp] = i\n d_rev[i] = (doc_id, num_chp)\n return d_chp, d_rev\n\n\ndef iter_by_art(collect, doc_id):\n d_art, d_rev = {}, {}\n for i, num_chp in collect.itersplit(chp_sep_word):\n new_col = Collection(i)\n k = 0\n for j, num_art in new_col.itersplit(art_sep_word_name):\n if k == 0:\n j = re.sub(f\".*?{num_art}\", '', j)\n j = re.sub(\"§.+\\n\", '', j)\n num_art = num_art.split(' ')[1]\n d_art[(doc_id, num_art[:-1])] = j\n d_rev[j] = (doc_id, num_art[:-1])\n k += 1\n return d_art, d_rev\n\n\ndef art_name(collect, doc_id):\n name = {}\n for i, num_chp in collect.itersplit(chp_sep_word):\n new_col = Collection(i)\n for j, num_art in new_col.itersplit(art_sep_word_name):\n name[(doc_id, num_art.split(' ')[1][:-1])] = ' '.join(num_art.split()[2:])\n return name\n\n\ndef iter_by_par(collect, doc_id): #возвращение словарей с номером главы, статьи и пункта\n d_par, d_rev = {}, {}\n for i, num_chp in collect.itersplit(chp_sep_word):\n new_col = Collection(i)\n num_chp = num_chp.split(' ')[1]\n for j, num_art in new_col.itersplit(art_sep_word):\n num_art = num_art.split(' ')[1]\n new_col2 = Collection(j)\n for f, num_par in new_col2.itersplit(par_sep_word):\n num_par = re.search('[\\d\\.]', num_par)[0]\n d_par[(doc_id, num_chp, num_art, num_par)] = f\n d_rev[f] = (doc_id, num_chp, num_art, num_par)\n return d_par, d_rev\n\n\ndef chp(col): #итерирование по главам\n for i, num_chp in col.itersplit(chp_sep_word):\n yield i\n\n\ndef art(col): #итерирование по статьям\n for i, num_chp in col.itersplit(chp_sep_word):\n new_col = Collection(i)\n for j, num_art in new_col.itersplit(art_sep_word_name):\n yield j\n\n\ndef par(col): #итерирование по пунктам\n for i, num_chp in col.itersplit(chp_sep_word):\n new_col = Collection(i)\n for j, num_art in new_col.itersplit(art_sep_word):\n new_col2 = Collection(j)\n for f, num_par in new_col2.itersplit(par_sep_word):\n yield f\n\n\ndef iter_by_docs(docs, dir, iter_by, it): #итерирование по документам, в параметрах по чему итерироваться(iter_by), и что именно нужно сделать при итерировании -- вернуть словарь(it=0) или постепенно каждую часть(it=1)\n doc_id = docs[docs.find('_') + 1: docs.find('.')]\n f = open(os.path.join(dir, docs), 'r', encoding='utf-8')\n file = f.read()\n c = Collection(file)\n if it == 0:\n if iter_by == 'chapter':\n return iter_by_chapter(c, doc_id)\n elif iter_by == 'paragraph':\n return iter_by_par(c, doc_id)\n elif iter_by == 'article':\n return iter_by_art(c, doc_id)\n else:\n print(\"MISTAKE\")\n return\n else:\n if iter_by == 'chapter':\n return chp(c)\n elif iter_by == 'paragraph':\n return par(c)\n elif iter_by == 'article':\n return art(c)\n elif iter_by == 'art_name':\n return art_name(c, doc_id)\n else:\n print(\"MISTAKE\")\n return\n\n\ndef iter_pravoved(docs, encoding='utf-8'):\n doc_id = docs[docs.rfind('_') + 1: docs.rfind('.')]\n f = open(docs, 'r', encoding=encoding)\n file = f.read()\n c = Collection(file)\n return iter_by_art(c, doc_id)\n","sub_path":"find_norm_pipeline/tools/codexes_process_tools.py","file_name":"codexes_process_tools.py","file_ext":"py","file_size_in_byte":5052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"133578517","text":"# Parse the bizarre yahoo json formats ...\nfrom jsonutils import pprint\n\nfrom fantasy.models.fantasygame import FantasyGame\nfrom fantasy.models.league import League\nfrom fantasy.models.draftresults import DraftResults\nfrom fantasy.models.player import Player\n\n# Parse the respone to get the list of all games played by a user\ndef fantasy_games(data):\n\tgames = []\n\tgame_list = data['fantasy_content']['users']['0']['user'][1]['games']\n\tfor key in game_list.keys():\n\t\tif key=='count':\n\t\t\tcontinue\n\t\tgame = game_list[key]\n\t\tif 'game' in game:\n\t\t\tgame_data = game['game']\n\t\t\tif isinstance(game_data, list):\n\t\t\t\tgame_data = game['game'][0]\n\t\telse:\n\t\t\tgame_data = game[0]['code']\n\n\t\tgames.append(FantasyGame(game_data))\n\n\treturn games\n\n# Get the list of all leagues played for a given fantasy game\ndef leagues(data):\n\tleagues = []\n\tleague_list = data['fantasy_content']['users']['0']['user'][1]['games']['0']['game'][1]['leagues']\n\t\n\tfor key in league_list.keys():\n\t\tif key=='count':\n\t\t\tcontinue\n\t\tleague = league_list[key]\n\t\t\n\t\tleague_data = league['league']\n\t\tif isinstance(league_data, list):\n\t\t\tleague_data = league['league'][0]\n\t\n\t\tleagues.append(League(league_data))\n\n\treturn leagues\n\n# Get the draft results for a given league\ndef draft_results(data):\n\traw_results = data['fantasy_content']['league'][1]['draft_results']\n\treturn DraftResults(raw_results)\n\n# Parse our the player stats from a league\ndef players_stats(data):\n\tplayer_list = data['fantasy_content']['league'][1]['players']\n\tret_count = player_list['count']\n\tplayers = []\n\tfor x in xrange(0,ret_count):\n\t\tplayer = player_list[repr(x)]\n\t\tplayers.append(player)\n\treturn players\n\n# Parse out an individual player stats\ndef player_stats(data):\n\tp_data = data['player']\n\treturn Player(p_data)\n","sub_path":"fantasy/io/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"427980207","text":"from spc700 import SPC700\nfrom script import Script\nfrom struct import unpack\nfrom id666tag import ID666Tag, ExtendedID666Tag\n\nimport os\nclass SPCFile:\n def __init__(self, filepath=None):\n self.header = \"\"\n self.header_flags = 0\n self.version = 0\n self.spc700 = None\n self.id666 = None\n self.extended666 = None\n self.path = None\n if filepath is not None:\n self.path = filepath\n self.__parsefile()\n\n def __parsefile(self):\n with open(self.path, 'rb') as f:\n headerbytes = f.read(0x25)\n spcregbytes = f.read(0x09)\n id666bytes = f.read(0xD2)\n ram = f.read(0x10000)\n dspregbytes = f.read(0xC0)\n iplram = f.read(0x40)\n extendedid666bytes = f.read()\n self.__parserheader(headerbytes)\n self.spc700 = SPC700(spcregbytes, bytearray(ram), dspregbytes, iplram)\n self.id666 = ID666Tag(id666bytes)\n self.extended666 = ExtendedID666Tag(extendedid666bytes)\n\n def __parserheader(self, headerbytes):\n fields = unpack(\"<33s4B\", headerbytes)\n self.header= fields[0].decode()\n self.header_flags = fields[3]\n self.version = fields[4]\n\n def disassemble(self, pc, stop, rel, hex, addr):\n self.spc700.PC = int(pc, 16)\n script = Script()\n while self.spc700.PC < (0x10000 if stop==\"eof\" else int(stop,16)):\n decinc = self.spc700.decodePC()\n script.instructions[decinc.offset] = decinc\n song_folder = \"\" if \"OST Track\" not in self.extended666.values else \"{:02d} - \".format(self.extended666.values[\"OST Track\"])\n song_folder += self.id666.song_title\n path = os.path.join(\n \"test\",\n self.id666.game_title,\n song_folder\n )\n filename = os.path.basename(self.path).replace('.spc','.s')\n os.makedirs(path, exist_ok=True)\n script.export(os.path.join(path, filename), addr, hex, rel)\n\n def run(self, pc):\n self.spc700.PC = int(pc, 16)\n while True:\n self.spc700.step()\n\n def extract_samples(self):\n song_folder = \"\" if \"OST Track\" not in self.extended666.values else \"{:02d} - \".format(self.extended666.values[\"OST Track\"])\n song_folder += self.id666.song_title\n path = os.path.join(\n \"test\",\n self.id666.game_title,\n song_folder\n )\n os.makedirs(path, exist_ok=True)\n for track_id in range(64):\n sample = self.spc700.io.DSP.sample_2_wav(track_id)\n if sample is not None and sample != b'\\0':\n filename = os.path.join(path,\"sample_{:02d}.wav\".format(track_id))\n with open(filename,'wb') as f:\n f.write(sample)\n\n def __repr__(self):\n result = \"{}\\n{}\\n{}\\n{}\".format(\n self.header,\n str(self.id666),\n str(self.extended666),\n str(self.spc700),\n )\n return result","sub_path":"spcfile.py","file_name":"spcfile.py","file_ext":"py","file_size_in_byte":3022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"543787645","text":"from t4cast.views import const\nfrom PySide.QtGui import *\nfrom PySide.QtCore import *\n\n\nclass LinkPopup(QDialog):\n def __init__(self, id_, src, dst, dir_, parent=None):\n super(LinkPopup, self).__init__(parent)\n self.parent = parent\n self.value = None\n\n self.setWindowTitle('Link Properties')\n\n main_layout = QVBoxLayout()\n self.setLayout(main_layout)\n\n properties_group = QGroupBox('Link attributes', self)\n properties_layout = QGridLayout(properties_group)\n\n id_label = QLabel('Id:')\n id_val = QLineEdit()\n id_val.setText(str(id_))\n id_val.setEnabled(False)\n\n nodes_label = QLabel('Nodes:')\n\n src_label = QLabel('Source:')\n self.src_val = QLineEdit()\n self.src_val.setText(str(src))\n self.src_val.setEnabled(False)\n\n dst_label = QLabel('Destination:')\n self.dst_val = QLineEdit()\n self.dst_val.setText(str(dst))\n self.dst_val.setEnabled(False)\n\n nodes_swap_btn = QPushButton('Switch nodes')\n nodes_swap_btn.clicked.connect(self.swap_nodes)\n\n nodes_group = QGroupBox(self)\n nodes_layout = QGridLayout(nodes_group)\n\n nodes_layout.addWidget(src_label, 0, 0)\n nodes_layout.addWidget(self.src_val, 0, 1)\n nodes_layout.addWidget(dst_label, 1, 0)\n nodes_layout.addWidget(self.dst_val, 1, 1)\n nodes_layout.addWidget(nodes_swap_btn, 2, 1)\n\n dir_label = QLabel('Direction:')\n self.dir_val = QComboBox()\n self.dir_val.addItems(['one way', 'two way'])\n if dir_ == const.ONE_WAY:\n self.dir_val.setCurrentIndex(0)\n elif dir_ == const.TWO_WAY:\n self.dir_val.setCurrentIndex(1)\n\n properties_layout.addWidget(id_label, 0, 0)\n properties_layout.addWidget(id_val, 0, 1)\n\n properties_layout.addWidget(nodes_label, 1, 0)\n properties_layout.addWidget(nodes_group, 1, 1)\n\n properties_layout.addWidget(dir_label, 2, 0)\n properties_layout.addWidget(self.dir_val, 2, 1)\n\n btn_group = QGroupBox(self)\n btn_layout = QHBoxLayout(btn_group)\n\n ok_btn = QPushButton('Save', self)\n ok_btn.clicked.connect(self.ok)\n cancel_btn = QPushButton('Cancel', self)\n cancel_btn.clicked.connect(self.cancel)\n\n btn_layout.addWidget(ok_btn)\n btn_layout.addWidget(cancel_btn)\n\n main_layout.addWidget(properties_group)\n main_layout.addWidget(btn_group)\n\n self.exec_()\n\n def swap_nodes(self):\n src_val = self.src_val.text()\n dst_val = self.dst_val.text()\n self.src_val.setText(dst_val)\n self.dst_val.setText(src_val)\n\n def ok(self):\n self.value = [self.src_val.text(), self.dst_val.text(), self.dir_val.currentText()]\n self.close()\n\n def cancel(self):\n self.value = None\n self.close()\n\n\nclass NodePopup(QDialog):\n def __init__(self, id_, x, y, type_, parent=None):\n super(NodePopup, self).__init__(parent)\n self.parent = parent\n self.value = None\n\n self.setWindowTitle('Edit Node Properties')\n\n main_layout = QVBoxLayout()\n self.setLayout(main_layout)\n\n properties_group = QGroupBox('Node attributes', self)\n properties_layout = QGridLayout(properties_group)\n\n id_label = QLabel('Id:')\n id_val = QLineEdit()\n id_val.setText(str(id_))\n id_val.setEnabled(False)\n\n x_label = QLabel('Longitude:')\n self.x_val = QLineEdit()\n self.x_val.setText(str(x))\n\n y_label = QLabel('Latitude:')\n self.y_val = QLineEdit()\n self.y_val.setText(str(y))\n\n type_label = QLabel('Type:')\n self.type_val = QComboBox()\n self.type_val.addItems(['zonal centroid', 'intermediate node'])\n if type_ == const.ZONAL_CENTROID:\n self.type_val.setCurrentIndex(0)\n elif type_ == const.INTERMEDIATE_NODE:\n self.type_val.setCurrentIndex(1)\n\n properties_layout.addWidget(id_label, 0, 0)\n properties_layout.addWidget(id_val, 0, 1)\n\n properties_layout.addWidget(x_label, 1, 0)\n properties_layout.addWidget(self.x_val, 1, 1)\n\n properties_layout.addWidget(y_label, 2, 0)\n properties_layout.addWidget(self.y_val, 2, 1)\n\n properties_layout.addWidget(type_label, 3, 0)\n properties_layout.addWidget(self.type_val, 3, 1)\n\n btn_group = QGroupBox(self)\n btn_layout = QHBoxLayout(btn_group)\n\n ok_btn = QPushButton('Save', self)\n ok_btn.clicked.connect(self.ok)\n cancel_btn = QPushButton('Cancel', self)\n cancel_btn.clicked.connect(self.cancel)\n\n btn_layout.addWidget(ok_btn)\n btn_layout.addWidget(cancel_btn)\n\n main_layout.addWidget(properties_group)\n main_layout.addWidget(btn_group)\n\n self.exec_()\n\n def ok(self):\n self.value = [self.x_val.text(), self.y_val.text(), self.type_val.currentText()]\n self.close()\n\n def cancel(self):\n self.value = None\n self.close()\n\n","sub_path":"1.x/t4cast/views/popups/toolbox_popups.py","file_name":"toolbox_popups.py","file_ext":"py","file_size_in_byte":5073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"159818959","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('aristotle_dse', '0008_auto_20160318_2335'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='datasetspecification',\n name='clusters',\n field=models.ManyToManyField(to='aristotle_dse.DataSetSpecification', null=True, through='aristotle_dse.DSSClusterInclusion', blank=True),\n ),\n migrations.AlterField(\n model_name='datasetspecification',\n name='data_elements',\n field=models.ManyToManyField(to='aristotle_mdr.DataElement', null=True, through='aristotle_dse.DSSDEInclusion', blank=True),\n ),\n ]\n","sub_path":"aristotle_dse/migrations/0009_auto_20160725_1958.py","file_name":"0009_auto_20160725_1958.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"579803017","text":"# Author: Christian Brodbeck \nfrom collections import defaultdict\nfrom glob import glob\nfrom itertools import chain, product\nimport os\nimport re\nimport shutil\nimport subprocess\nfrom time import localtime, strftime\nimport traceback\n\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom .. import fmtxt\nfrom .._utils import LazyProperty, ask, deprecated\nfrom .._utils.com import Notifier, NotNotifier\n\n\ndef _etree_expand(node, state):\n for tk, tv in node.items():\n if tk == '.':\n continue\n\n for k, v in state.items():\n name = '{%s}' % tk\n if str(v).startswith(name):\n tv[k] = {'.': v.replace(name, '')}\n if len(tv) > 1:\n _etree_expand(tv, state)\n\n\ndef _etree_node_repr(node, name, indent=0):\n head = ' ' * indent\n out = [(name, head + node['.'])]\n for k, v in node.items():\n if k == '.':\n continue\n\n out.extend(_etree_node_repr(v, k, indent=indent + 3))\n return out\n\n\nclass LayeredDict(dict):\n \"\"\"Dictionary which can store and restore states\"\"\"\n def __init__(self):\n self._states = []\n dict.__init__(self)\n\n def __repr__(self):\n return (\"\" % (len(self._states), dict.__repr__(self)))\n\n def get_stored(self, key, level, default=None):\n \"\"\"Retrieve a field value from any level\n\n Parameters\n ----------\n key : str\n the field name (dictionary key).\n level : int\n The level from which to retrieve the value. -1 = the current level.\n \"\"\"\n return self._states[level].get(key, default)\n\n def restore_state(self, state=-1, discard_tip=True):\n \"\"\"Restore a previously stored state\n\n Parameters\n ----------\n state : int | dict\n Index of the state which to restore (specified as index into a\n list of stored states, i.e., negative values access recently\n stored states).\n discard_tip : bool\n Discard the relevant state after restoring it. All states stored\n later are discarded either way.\n\n See Also\n --------\n .get_stored(): Retrieve a stored value without losing stored states\n \"\"\"\n if isinstance(state, int):\n index = state\n state = self._states[index]\n if discard_tip:\n del self._states[index:]\n elif index != -1: # -1 + 1 = 0\n del self._states[index + 1:]\n elif not isinstance(state, dict):\n raise TypeError(\"state needs to be either int or dict, got %r\" %\n (state,))\n\n self.clear()\n self.update(state)\n\n def store_state(self):\n \"Store the current state\"\n self._states.append(self.copy())\n\n\nclass _TempStateController(object):\n def __init__(self, experiment):\n self.experiment = experiment\n\n def __enter__(self):\n self.experiment._store_state()\n\n def __exit__(self, exc_type, exc_value, traceback):\n self.experiment._restore_state()\n\n\nclass TreeModel(object):\n \"\"\"\n A hierarchical collection of format strings and field values\n\n Notes\n -----\n Any subclass should make sure to call the ``._store_state()`` method at the\n end of initialization.\n \"\"\"\n owner = None # email address as string (for notification)\n _auto_debug = False # in notification block\n\n _fmt_pattern = re.compile('\\{([\\w-]+)\\}')\n\n # a dictionary of static templates (i.e., templates that do not have any hooks)\n _templates = {}\n defaults = {}\n\n exclude = {} # field_values to exclude (e.g. subjects)\n\n _repr_args = ()\n _repr_kwargs = ()\n\n def __init__(self, **state):\n self.exclude = self.exclude.copy()\n\n # scaffold for state\n self._fields = LayeredDict()\n self._field_values = LayeredDict()\n self._params = LayeredDict()\n self._terminal_fields = []\n self._user_fields = [] # terminal fields that are relevant for user\n self._secondary_cache = defaultdict(tuple) # secondary cache-files\n\n # scaffold for hooks\n self._compound_members = {}\n self._compounds = defaultdict(list)\n self._eval_handlers = defaultdict(list)\n self._post_set_handlers = defaultdict(list)\n self._set_handlers = {}\n self._slave_fields = defaultdict(list)\n self._slave_handlers = {}\n\n # construct initial state: make all defaults available, then set as\n # many values as we can\n self._defaults = dict(self.defaults)\n self._defaults.update(state)\n for k, v in self._templates.items():\n if v is None or isinstance(v, str):\n self._register_constant(k, v)\n elif isinstance(v, tuple):\n self._register_field(k, v, v[0])\n else:\n err = (\"Invalid templates field value: %r. Need None, tuple \"\n \"or string\" % v)\n raise TypeError(err)\n\n if self.owner:\n task = self.__class__.__name__\n self.notification = Notifier(self.owner, task, self._crash_report,\n self._auto_debug)\n else:\n self.notification = NotNotifier()\n\n def __repr__(self):\n args = [repr(self._fields[arg]) for arg in self._repr_args]\n kwargs = [(arg, repr(self._fields[arg])) for arg in self._repr_kwargs]\n\n no_initial_state = len(self._fields._states) == 0\n for k in sorted(self._fields):\n if k in self._repr_args or k in self._repr_kwargs:\n continue\n elif k in self._compound_members:\n continue\n elif '{' in self._fields[k]:\n continue\n\n v = self._fields[k]\n if no_initial_state or v != self._fields.get_stored(k, level=0):\n kwargs.append((k, repr(v)))\n\n args.extend('='.join(pair) for pair in kwargs)\n args = ', '.join(args)\n return \"%s(%s)\" % (self.__class__.__name__, args)\n\n def _bind_eval(self, key, handler):\n self._eval_handlers[key].append(handler)\n\n def _bind_post_set(self, key, handler):\n handlers = self._post_set_handlers[key]\n if handler not in handlers:\n handlers.append(handler)\n\n def _bind_set(self, key, handler):\n if key in self._set_handlers:\n raise KeyError(\"set-handler for %r already set\" % key)\n self._set_handlers[key] = handler\n\n def _crash_report(self):\n out = []\n\n # try:\n # source = inspect.getsource(self.__class__)\n # except Exception as e:\n # source = \"Failed to retrieve source:\\n\" + traceback.format_exc(e)\n # out.append(source)\n\n try:\n tree = str(self.show_state())\n except Exception as e:\n tree = \"Failed to retrieve state:\\n\" + traceback.format_exc(e)\n out.append(tree)\n\n # package versions\n from .. import __version__\n import mne\n import scipy\n out.append('\\n'.join((\"Eelbrain %s\" % __version__,\n \"mne-python %s\" % mne.__version__,\n \"SciPy %s\" % scipy.__version__,\n \"NumPy %s\" % np.__version__)))\n\n return out\n\n def _find_missing_fields(self):\n \"\"\"Check that all field names occurring in templates are valid entries\n\n Raises\n ------\n KeyError\n If any field names occurring in templates are not registered fields.\n \"\"\"\n # find field names occurring in field values but not as fields\n missing = set()\n for temp in self._fields.values():\n for field in self._fmt_pattern.findall(temp):\n if field not in self._fields:\n missing.add(field)\n if missing:\n raise KeyError(\"The following fields occur in templates but \"\n \"are undefined: %s\" % ', '.join(sorted(missing)))\n\n def _register_compound(self, key, elements):\n \"\"\"Register a field that is composed out of other fields\n\n The compound always reflects ``' '.join(elements)`` including only\n elements that are not empty.\n\n Parameters\n ----------\n key : str\n The name of the compound field.\n elements : tuple of str\n The field names of the elements.\n \"\"\"\n self._compound_members[key] = elements\n for e in elements:\n self._compounds[e].append(key)\n self._bind_post_set(e, self._update_compounds)\n self._fields[key] = None\n self._update_compound(key)\n\n def _register_constant(self, key, value):\n value = self._defaults.get(key, value)\n if value is None:\n raise ValueError(\"The %r field needs to be set as default\" % key)\n self._fields[key] = value\n\n def _register_field(self, key, values=None, default=None, set_handler=None,\n eval_handler=None, post_set_handler=None,\n depends_on=None, slave_handler=None, internal=False):\n \"\"\"Register an iterable field\n\n Parameters\n ----------\n key : str\n Name of the field.\n values : None | sequence of str\n Possible values for this field, if known.\n default : None | str\n Set the default value (if None, the first element in values).\n set_handler : None | callable\n Function to call instead of updating the state value. The return\n value of the set_handler is sent to the post_set_handler.\n eval_handler : None | callable\n Function to use for evaluating a value before setting. Can be\n called without actually setting the value; any parameter changes\n need to be evaluated in post_set_handlers.\n post_set_handler : None | callable\n Function to call after the value is changed. Needs to be able to\n handle non-existing values for ``e.set(..., vmatch=False)`` calls.\n depends_on : str | sequence of str\n Slave fields: Fields in depends_on trigger change in ``key``.\n slave_handler : func\n Slave fields: Function that determines the new value of ``key``.\n internal : bool\n The field is set by methods as needed but should not be exposed to\n the user.\n \"\"\"\n if key in self._fields:\n raise KeyError(\"Field already exists: %r\" % key)\n\n if depends_on is not None:\n if (set_handler is not None or eval_handler is not None or\n post_set_handler is not None):\n raise RuntimeError(\"Slave values can't have other handlers\")\n elif slave_handler is None:\n raise RuntimeError(\"Slave value requires slave_handler\")\n self._register_slave_field(key, depends_on, slave_handler)\n if default is None:\n default = slave_handler(self._fields)\n if set_handler is not None:\n self._bind_set(key, set_handler)\n if eval_handler is not None:\n self._bind_eval(key, eval_handler)\n if post_set_handler is not None:\n self._bind_post_set(key, post_set_handler)\n\n default = self._defaults.get(key, default)\n\n if values is not None:\n values = tuple(values)\n if default is None:\n if len(values):\n default = values[0]\n else:\n msg = \"Values for %r empty, can`t set default\" % key\n raise RuntimeError(msg)\n elif default not in values:\n err = (\"Default %r for %r not in values \"\n \"%s\" % (default, key, str(values)))\n raise ValueError(err)\n\n self._field_values[key] = values\n\n self._terminal_fields.append(key)\n if depends_on is None and not internal:\n self._user_fields.append(key)\n self._fields[key] = ''\n if default is not None:\n self.set(**{key: default})\n\n def _register_slave_field(self, key, depends_on, handler):\n \"\"\"Register a field that strictly depends on one or more other fields\n\n Parameters\n ----------\n key : str\n Field name.\n depends_on : str | sequence of str\n Fields that trigger change.\n handler : func\n Function that determines the new value.\n\n Notes\n -----\n Restrictions:\n\n - Slave fields can not have any other handlers\n - Slave fields can not depend on other slave fields\n \"\"\"\n if isinstance(depends_on, str):\n depends_on = (depends_on,)\n for dep in depends_on:\n self._slave_fields[dep].append(key)\n self._slave_handlers[key] = handler\n self._fields[key] = handler(self._fields)\n\n def expand_template(self, temp, keep=()):\n \"\"\"Expand all constant variables in a template\n\n Parameters\n ----------\n temp : str\n Template or name of the template which should be expanded.\n keep : container (implements __contains__)\n Names of the variables which should not be expanded.\n\n Returns\n -------\n formatted_temp : str\n Template with all variables replaced by their values, except\n variables which have entries in field_values or in ``keep``.\n \"\"\"\n temp = self._fields.get(temp, temp)\n\n while True:\n stop = True\n for name in self._fmt_pattern.findall(temp):\n if (name in keep) or (self._field_values.get(name, False)):\n pass\n else:\n temp = temp.replace('{%s}' % name, self._fields[name])\n stop = False\n\n if stop:\n break\n\n return temp\n\n def find_keys(self, temp, root=True):\n \"\"\"Find all terminal field names that are relevant for a template.\n\n Parameters\n ----------\n temp : str\n Template (or field name) for which to find terminal field names.\n root : bool\n Include \"root\" if present (default True).\n\n Returns\n -------\n keys : set\n All terminal field names that are relevant for formatting ``temp``.\n \"\"\"\n keys = set()\n\n if temp in self._compound_members:\n temporary_keys = list(self._compound_members[temp])\n else:\n temp = self._fields.get(temp, temp)\n temporary_keys = self._fmt_pattern.findall(temp)\n\n while temporary_keys:\n key = temporary_keys.pop()\n\n if key == 'root':\n if root:\n keys.add('root')\n # are there sub-fields?\n elif (key in self._compound_members or\n self._fmt_pattern.findall(self._fields[key])):\n keys.update(self.find_keys(key, root))\n else:\n keys.add(key)\n\n return keys\n\n def format(self, string, vmatch=True, **kwargs):\n \"\"\"Format a string (i.e., replace any '{xxx}' fields with their values)\n\n Parameters\n ----------\n string : str\n Template string.\n vmatch : bool\n For fields with known names, only allow existing field names.\n others :\n State parameters.\n\n Returns\n -------\n formatted_string : str\n The template temp formatted with current state values.\n \"\"\"\n self.set(match=vmatch, **kwargs)\n\n while self._fmt_pattern.search(string):\n string = string.format(**self._fields)\n\n return string\n\n def get(self, temp, **state):\n return self.format('{%s}' % temp, **state)\n\n def _get_rel(self, temp, start):\n \"Get the path of ``temp`` relative to ``start`` (both field names)\"\n abs_ = self.get(temp)\n start_ = self.get(start)\n return os.path.relpath(abs_, start_)\n\n def get_field_values(self, field, exclude=True):\n \"\"\"Find values for a field taking into account exclusion\n\n Parameters\n ----------\n field : str\n Field for which to find values.\n exclude : bool | list of str | str\n Exclude values. If True, exclude values based on ``self.exclude``.\n \"\"\"\n values = self._field_values[field]\n if exclude is True:\n exclude = self.exclude.get(field, None)\n elif isinstance(exclude, str):\n exclude = (exclude,)\n\n if exclude:\n values = [v for v in values if v not in exclude]\n else:\n values = list(values)\n\n return values\n\n def iter(self, fields, exclude=True, values={}, mail=False, prog=False,\n **constants):\n \"\"\"\n Cycle the experiment's state through all values on the given fields\n\n Parameters\n ----------\n fields : sequence | str\n Field(s) over which should be iterated.\n exclude : bool | dict {str: bool, str: str, str: iterator over str}\n Exclude values from iteration. Boolean specifies whether to apply\n standard exclusion (``self.exclude``). A ``dict`` can be used to\n customize the exclusion per field with one of {field: bool,\n field: value, field: (sequence of values, )}. If only some fields\n are specified in a dict, True is assumed for absent fields.\n values : dict {str: iterator over str}\n Fields with custom values to iterate over (instead of the\n corresponding field values) with {name: (sequence of values)}\n entries.\n *others* :\n Fields with constant values throughout the iteration.\n \"\"\"\n # set constants\n self.set(**constants)\n\n if isinstance(fields, str):\n fields = (fields,)\n yield_str = True\n else:\n yield_str = False\n iter_fields = tuple(f for f in chain(fields, values) if f not in constants)\n\n # gather possible values to iterate over\n field_values = {}\n for field in iter_fields:\n if field in values:\n field_values[field] = values[field]\n else:\n if isinstance(exclude, bool):\n exclude_ = exclude\n elif field in exclude:\n exclude_ = exclude[field]\n else:\n exclude_ = True\n field_values[field] = self.get_field_values(field, exclude_)\n\n # pick out the fields to iterate, but drop excluded cases:\n v_lists = []\n for field in iter_fields:\n v_lists.append(field_values[field])\n\n if len(v_lists):\n with self._temporary_state:\n for v_list in product(*v_lists):\n self._restore_state(discard_tip=False)\n self.set(**dict(zip(iter_fields, v_list)))\n\n if yield_str:\n yield self.get(fields[0])\n else:\n yield tuple(self.get(f) for f in fields)\n else:\n yield ()\n\n def iter_temp(self, temp, exclude=True, values={}, **constants):\n \"\"\"\n Iterate through all paths conforming to a template given in ``temp``.\n\n Parameters\n ----------\n temp : str\n Name of a template in the MneExperiment.templates dictionary, or\n a path template with variables indicated as in ``'{var_name}'``\n \"\"\"\n # if the name is an existing template, retrieve it\n temp = self.expand_template(temp, values.keys())\n\n # find variables for iteration\n variables = set(self._fmt_pattern.findall(temp))\n variables.difference_update(constants)\n\n for _ in self.iter(variables, exclude, values, **constants):\n path = temp.format(**self._fields)\n yield path\n\n def _partial(self, temp, skip=()):\n \"Format a template while leaving some slots unfilled\"\n skip = set(skip)\n fields = self._fields.copy()\n fields.update({k: '{%s}' % k for k in skip})\n string = '{%s}' % temp\n\n while set(self._fmt_pattern.findall(string)).difference(skip):\n string = string.format(**fields)\n\n return string\n\n def _copy_state(self):\n \"\"\"Copy of the state that can be used with ``._restore_state()``\"\"\"\n return self._fields.copy(), self._field_values.copy(), self._params.copy()\n\n def _restore_state(self, state=-1, discard_tip=True):\n \"\"\"Restore a previously stored state\n\n Parameters\n ----------\n state : int\n Index of the state which to restore (specified as index into a\n list of stored states, i.e., negative values access recently\n stored states).\n discard_tip : bool\n Discard the relevant state after restoring it. All states stored\n later are discarded either way.\n \"\"\"\n if isinstance(state, int):\n s1 = s2 = s3 = state\n else:\n s1, s2, s3 = state\n self._fields.restore_state(s1, discard_tip)\n self._field_values.restore_state(s2, discard_tip)\n self._params.restore_state(s3, discard_tip)\n\n def set(self, match=True, allow_asterisk=False, **state):\n \"\"\"Set the value of one or more fields.\n\n Parameters\n ----------\n match : bool\n For fields with stored values, only allow valid values.\n allow_asterisk : bool\n If a value contains '*', set the value without the normal value\n evaluation and checking mechanism.\n kwargs :\n Fields and values to set. Invalid fields raise a KeyError. Unless\n match == False, Invalid values raise a ValueError.\n \"\"\"\n if not state:\n return\n\n # fields with special set handlers\n handled_state = {}\n for k in state.keys():\n if k in self._set_handlers:\n handled_state[k] = self._set_handlers[k](state.pop(k))\n\n # make sure only valid fields are set\n for k in state:\n if k not in self._fields:\n raise KeyError(\"No template named %r\" % k)\n\n # eval all values\n for k in state.keys():\n eval_handlers = self._eval_handlers[k]\n v = state[k]\n if not isinstance(v, str):\n msg = \"Values have to be strings, got %s=%r\" % (k, v)\n raise TypeError(msg)\n elif '*' in v and allow_asterisk:\n pass\n elif eval_handlers:\n for handler in eval_handlers:\n try:\n v = handler(v)\n except ValueError:\n if match:\n raise\n\n if not isinstance(v, str):\n err = \"Invalid conversion: %s=%r\" % (k, v)\n raise RuntimeError(err)\n state[k] = v\n elif not match:\n pass\n elif k not in self._field_values:\n pass\n elif v not in self.get_field_values(k, False):\n raise ValueError(\n f\"Variable {k!r} has no value {v!r}. In order to see valid \"\n f\"values use e.show_fields(); In order to set a non-\"\n f\"existent value, use e.set({k!s}={v!r}, match=False).\")\n\n self._fields.update(state)\n\n # fields depending on changes in other fields\n slave_state = {}\n for state_key in set(state).union(handled_state).intersection(self._slave_fields):\n for slave_key in self._slave_fields[state_key]:\n if slave_key not in slave_state:\n v = self._slave_handlers[slave_key](self._fields)\n if v is not None:\n slave_state[slave_key] = v\n self._fields.update(slave_state)\n\n # call post_set handlers\n for k, v in chain(state.items(), handled_state.items(), slave_state.items()):\n for handler in self._post_set_handlers[k]:\n handler(k, v)\n\n def show_fields(self, str_out=False):\n \"\"\"\n Generate a table for all iterable fields and ther values.\n\n Parameters\n ----------\n str_out : bool\n Return the table as a string (instead of printing it).\n \"\"\"\n lines = []\n for key in self._field_values:\n values = list(self.get_field_values(key))\n line = '%s:' % key\n head_len = len(line) + 1\n while values:\n v = repr(values.pop(0))\n if values:\n v += ','\n if len(v) < 80 - head_len:\n line += ' ' + v\n else:\n lines.append(line)\n line = ' ' * head_len + v\n\n if not values:\n lines.append(line)\n\n table = '\\n'.join(lines)\n if str_out:\n return table\n else:\n print(table)\n\n def show_state(self, temp=None, empty=False, hide=()):\n \"\"\"List all top-level fields and their values\n\n (Top-level fields are fields whose values do not contain templates)\n\n Parameters\n ----------\n temp : None | str\n Only show variables relevant to this template.\n empty : bool\n Show empty variables (items whose value is the empty string '').\n hide : collection of str\n State variables to hide.\n\n Returns\n -------\n state : Table\n Table of (relevant) variables and their values.\n \"\"\"\n table = fmtxt.Table('lll')\n table.cells('Key', '*', 'Value')\n table.caption('*: Value is modified from initialization state.')\n table.midrule()\n\n if temp is None:\n keys = self._user_fields\n else:\n keys = self.find_keys(temp)\n\n for k in sorted(keys):\n if k in hide:\n continue\n\n v = self._fields[k]\n if v != self._fields.get_stored(k, level=0):\n mod = '*'\n else:\n mod = ''\n\n if empty or mod or v:\n table.cells(k, mod, repr(v))\n\n return table\n\n def show_tree(self, root='root', fields=None):\n \"\"\"\n Print a tree of the filehierarchy implicit in the templates\n\n Parameters\n ----------\n root : str\n Name of the root template (e.g., 'besa-root').\n fields : list of str\n Which fields to include in the tree (default is all).\n \"\"\"\n if fields is None:\n fields = self._fields\n else:\n # find all implied fields\n new_fields = set(fields)\n fields = {}\n while new_fields:\n k = new_fields.pop()\n fields[k] = v = self._fields[k]\n new_fields.update([f for f in self._fmt_pattern.findall(v) if\n f not in fields])\n\n tree = {'.': self.get(root)}\n root_temp = '{%s}' % root\n for k, v in fields.items():\n if str(v).startswith(root_temp):\n tree[k] = {'.': v.replace(root_temp, '')}\n _etree_expand(tree, fields)\n nodes = _etree_node_repr(tree, root)\n name_len = max(len(n) for n, _ in nodes)\n path_len = max(len(p) for _, p in nodes)\n pad = ' ' * (80 - name_len - path_len)\n print('\\n'.join(n.ljust(name_len) + pad + p.ljust(path_len) for\n n, p in nodes))\n\n def _store_state(self):\n \"\"\"Store the current state\n\n See also\n --------\n ._restore_state() : restore a previously stored state\n \"\"\"\n self._fields.store_state()\n self._field_values.store_state()\n self._params.store_state()\n\n @LazyProperty\n def _temporary_state(self):\n return _TempStateController(self)\n\n def _update_compound(self, key):\n compound = ''\n for item_key in self._compound_members[key]:\n value = self.get(item_key)\n if value == '*':\n compound += '*'\n elif value:\n if compound and not compound.endswith('*'):\n compound += ' '\n compound += value\n self.set(**{key: compound})\n\n def _update_compounds(self, key, _):\n for compound in self._compounds[key]:\n self._update_compound(compound)\n\n\nclass FileTree(TreeModel):\n \"\"\":class:`TreeModel` subclass for a file system hierarchy\"\"\"\n _repr_args = ('root',)\n\n def __init__(self, **state):\n TreeModel.__init__(self, **state)\n self._make_handlers = {}\n self._cache_handlers = {}\n self._register_field('root', eval_handler=self._eval_root)\n\n def _bind_cache(self, key, handler):\n \"\"\"Bind a cache function to a ``*-file`` key\n\n The cache function is called every time the file name is retrieved and\n should recreate the file if it is outdated.\n\n The cache function can return the filename of the created file since\n it is called every time the specific file is requested. Note that this\n causes problems for ``glob()``.\n \"\"\"\n if key in self._cache_handlers:\n raise RuntimeError(\"Cache handler for %r already defined.\" % key)\n elif key in self._make_handlers:\n raise RuntimeError(\"Make handler for %r already defined.\" % key)\n self._cache_handlers[key] = handler\n\n def _bind_make(self, key, handler):\n \"\"\"Bind a make function to a ``*-file`` key\n\n The make function is called only when the file name is retrieved and\n the file does not exist.\n \"\"\"\n if key in self._cache_handlers:\n raise RuntimeError(\"Cache handler for %r already defined.\" % key)\n elif key in self._make_handlers:\n raise RuntimeError(\"Make handler for %r already defined.\" % key)\n self._make_handlers[key] = handler\n\n @staticmethod\n def _eval_root(root):\n root = os.path.abspath(os.path.expanduser(root))\n if root != '':\n root = os.path.normpath(root)\n return root\n\n def get(self, temp, fmatch=False, vmatch=True, match=True, mkdir=False,\n make=False, **kwargs):\n \"\"\"\n Retrieve a formatted template\n\n With match=True, '*' are expanded to match a file,\n and if there is not a unique match, an error is raised. With\n mkdir=True, the directory containing the file is created if it does not\n exist.\n\n Parameters\n ----------\n temp : str\n Name of the requested template.\n fmatch : bool\n \"File-match\": If the template contains asterisk ('*'), use glob to\n fill it in. An IOError is raised if the pattern does not match\n exactly one file.\n vmatch : bool\n \"Value match\": Require existence of the assigned value (only\n applies for fields with stored values).\n match : bool\n Do any matching (i.e., match=False sets fmatch as well as vmatch\n to False).\n mkdir : bool\n If the directory containing the file does not exist, create it.\n make : bool\n If a requested file does not exists, make it if possible.\n kwargs :\n Set any state values.\n \"\"\"\n if not match:\n fmatch = vmatch = False\n\n path = TreeModel.get(self, temp, vmatch=vmatch, **kwargs)\n path = os.path.expanduser(path)\n\n # assert the presence of the file\n if fmatch and ('*' in path):\n paths = glob(path)\n if len(paths) == 0 and make and temp in self._make_handlers:\n self._make_handlers[temp]()\n paths = glob(path)\n\n if len(paths) == 1:\n path = paths[0]\n elif len(paths) > 1:\n err = \"More than one files match %r: %r\" % (path, paths)\n raise IOError(err)\n else:\n raise IOError(\"No file found for %r\" % path)\n\n # create the directory\n if mkdir:\n if temp.endswith('dir'):\n dirname = path\n else:\n dirname = os.path.dirname(path)\n if not os.path.exists(dirname):\n root = self.get('root')\n if root == '':\n raise IOError(\"Prevented from creating directories because \"\n \"root is not set. Use root='.' for a \"\n \"relative root.\")\n elif os.path.exists(root):\n os.makedirs(dirname)\n else:\n raise IOError(\"Prevented from creating directories because \"\n \"Root does not exist: %r\" % root)\n\n # make the file\n if make:\n if temp in self._cache_handlers:\n path = self._cache_handlers[temp]() or path\n elif not os.path.exists(path):\n if temp in self._make_handlers:\n with self._temporary_state:\n self._make_handlers[temp]()\n elif temp.endswith('-dir'):\n os.makedirs(path)\n else:\n raise RuntimeError(\"No make handler for %r.\" % temp)\n\n return path\n\n def glob(self, temp, inclusive=False, **state):\n \"\"\"Find all files matching a certain pattern\n\n Parameters\n ----------\n temp : str\n Name of the path template for which to find files.\n inclusive : bool\n Treat all unspecified fields as ``*`` (default False).\n\n See Also\n --------\n copy : Copy files.\n move : Move files.\n rm : Delete files.\n\n Notes\n -----\n State parameters can include an asterisk ('*') to match multiple files.\n Uses :func:`glob.glob`.\n \"\"\"\n pattern = self._glob_pattern(temp, inclusive, **state)\n return glob(pattern)\n\n def _glob_pattern(self, temp, inclusive=False, **state):\n if inclusive:\n for key in self._terminal_fields:\n if key not in state and key != 'root':\n state[key] = '*'\n with self._temporary_state:\n pattern = self.get(temp, allow_asterisk=True, **state)\n return pattern\n\n def _find_files_with_target(self, action, temp, dst_root, inclusive, overwrite, confirm, state):\n if dst_root is None:\n if 'root' not in state:\n raise TypeError(\"Need to specify at least one of root and dst_root\")\n dst_root = self.get('root')\n src_filenames = self.glob(temp, inclusive, **state)\n root = self.get('root')\n errors = [filename for filename in src_filenames if not\n filename.startswith(root)]\n if errors:\n raise ValueError(\n f\"{len(errors)} files are not located in the root directory \"\n f\"({errors[0]}, ...)\")\n rel_filenames = [os.path.relpath(filename, root) for filename in\n src_filenames]\n dst_filenames = [os.path.join(dst_root, filename) for filename in\n rel_filenames]\n if not overwrite:\n exist = tuple(filter(os.path.exists, dst_filenames))\n if exist:\n raise ValueError(\n f\"{len(exist)} of {len(src_filenames)} files already exist \"\n f\"({dst_filenames[0]}, ...)\")\n\n n = len(src_filenames)\n if not n:\n print(\"No files matching pattern.\")\n return 0, None, None\n if not confirm:\n print(f\"{action} {self.get('root')} -> {dst_root}:\")\n for filename in rel_filenames:\n print(\" \" + filename)\n if input(f\"{action} {n} files? (confirm with 'yes'): \") != 'yes':\n return 0, None, None\n return n, src_filenames, dst_filenames\n\n def copy(self, temp, dst_root=None, inclusive=False, confirm=False,\n overwrite=False, **state):\n \"\"\"Copy files to a different root folder\n\n Parameters\n ----------\n temp : str\n Name of the path template for which to find files.\n dst_root : str\n Path to the root to which the files should be moved. If the target\n is the experiment's root directory, specify ``root`` as the source\n root and leave ``dst_root`` unspecified.\n inclusive : bool\n Treat all unspecified fields as ``*`` (default False).\n confirm : bool\n Skip asking for confirmation before copying the files.\n overwrite : bool\n Overwrite target files if they already exist.\n\n See Also\n --------\n glob : Find all files matching a template.\n move : Move files.\n rm : Delete files.\n\n Notes\n -----\n State parameters can include an asterisk ('*') to match multiple files.\n \"\"\"\n n, src_filenames, dst_filenames = self._find_files_with_target(\n 'Copy', temp, dst_root, inclusive, overwrite, confirm, state)\n if not n:\n return\n for src, dst in tqdm(zip(src_filenames, dst_filenames), \"Copying\", n):\n dirname = os.path.dirname(dst)\n if not os.path.exists(dirname):\n os.makedirs(dirname)\n\n if os.path.isdir(src):\n shutil.copytree(src, dst)\n else:\n shutil.copy(src, dst)\n\n def move(self, temp, dst_root=None, inclusive=False, confirm=False,\n overwrite=False, **state):\n \"\"\"Move files to a different root folder\n\n Parameters\n ----------\n temp : str\n Name of the path template for which to find files.\n dst_root : str\n Path to the root to which the files should be moved. If the target\n is the experiment's root directory, specify ``root`` as the source\n root and leave ``dst_root`` unspecified.\n inclusive : bool\n Treat all unspecified fields as ``*`` (default False).\n confirm : bool\n Skip asking for confirmation before moving the files.\n overwrite : bool\n Overwrite target files if they already exist.\n\n See Also\n --------\n copy : Copy files.\n glob : Find all files matching a template.\n rm : Delete files.\n\n Notes\n -----\n State parameters can include an asterisk ('*') to match multiple files.\n \"\"\"\n n, src_filenames, dst_filenames = self._find_files_with_target(\n 'Move', temp, dst_root, inclusive, overwrite, confirm, state)\n if not n:\n return\n for src, dst in tqdm(zip(src_filenames, dst_filenames), \"Moving\", n):\n dirname = os.path.dirname(dst)\n if not os.path.exists(dirname):\n os.makedirs(dirname)\n os.rename(src, dst)\n\n def show_file_status(self, temp, row, col=None, count=True, present='time',\n absent='-', **kwargs):\n \"\"\"Compile a table about the existence of files\n\n Parameters\n ----------\n temp : str\n The name of the path template for the files to examine.\n row : str\n Field over which to alternate rows.\n col : None | str\n Field over which to alternate columns (default is a single column).\n count : bool\n Add a column with a number for each line (default True).\n present : 'time' | 'date' | str\n String to display when a given file is present. 'time' to use last\n modification date and time (default); 'date' for date only.\n absent : str\n String to display when a given file is absent (default '-').\n others :\n ``self.iter()`` kwargs.\n \"\"\"\n if col is None:\n col_v = (None,)\n ncol = 1\n else:\n col_v = self.get_field_values(col)\n ncol = len(col_v)\n\n # table header\n table = fmtxt.Table('r' * bool(count) + 'l' * (ncol + 1))\n if count:\n table.cell()\n table.cell(row)\n if col is None:\n table.cell(temp)\n else:\n for name in col_v:\n table.cell(name)\n table.midrule()\n\n # body\n for i, row_v in enumerate(self.iter(row, **kwargs)):\n if count:\n table.cell(i)\n table.cell(row_v)\n for v in col_v:\n if v is None:\n path = self.get(temp)\n else:\n path = self.get(temp, **{col: v})\n\n if os.path.exists(path):\n if present == 'time':\n r = strftime('%x %X', localtime(os.path.getmtime(path)))\n elif present == 'date':\n r = strftime('%x', localtime(os.path.getmtime(path)))\n else:\n r = present\n else:\n r = absent\n table.cell(r)\n\n return table\n\n def show_file_status_mult(self, files, fields, count=True, present='X',\n absent='-', **kwargs):\n \"\"\"\n Compile a table about the existence of multiple files\n\n Parameters\n ----------\n files : str | list of str\n The names of the path templates whose existence to list.\n fields : str | list of str\n The names of the variables for which to list files (i.e., for each\n unique combination of ``fields``, list ``files``).\n count : bool\n Add a column with a number for each subject.\n present : str\n String to display when a given file is present.\n absent : str\n String to display when a given file is absent.\n\n Examples\n --------\n >>> e.show_file_status_mult(['raw-file', 'trans-file', 'fwd-file'],\n ... 'subject')\n Subject Raw-file Trans-file Fwd-file\n -----------------------------------------------\n 0 AD001 X X X\n 1 AD002 X X X\n 2 AD003 X X X\n ...\n \"\"\"\n if not isinstance(files, (list, tuple)):\n files = [files]\n if not isinstance(fields, (list, tuple)):\n fields = [fields]\n\n ncol = (len(fields) + len(files))\n table = fmtxt.Table('r' * bool(count) + 'l' * ncol)\n if count:\n table.cell()\n for name in fields + files:\n table.cell(name.capitalize())\n table.midrule()\n\n for i, _ in enumerate(self.iter(fields, **kwargs)):\n if count:\n table.cell(i)\n\n for field in fields:\n table.cell(self.get(field))\n\n for temp in files:\n path = self.get(temp)\n if os.path.exists(path):\n table.cell(present)\n else:\n table.cell(absent)\n\n return table\n\n def show_in_finder(self, temp, **kwargs):\n \"Reveal the file corresponding to the ``temp`` template in the Finder.\"\n fname = self.get(temp, **kwargs)\n subprocess.call([\"open\", \"-R\", fname])\n\n @deprecated('0.30', 'use .copy() or .move() instead')\n def push(self, dst_root, names, overwrite=False, exclude=False, **kwargs):\n \"\"\"Copy files to another experiment root folder.\n\n Before copying any files the user is asked for confirmation.\n\n Parameters\n ----------\n dst_root : str\n Path to the root to which the files should be copied.\n names : str | sequence of str\n Name(s) of the template(s) of the files that should be copied.\n overwrite : bool\n Overwrite target files if they already exist.\n others :\n Update experiment state.\n\n See Also\n --------\n move : Move files to a different root folder.\n\n Notes\n -----\n Use ``e.show_tree()`` to find out which element(s) to copy.\n \"\"\"\n if isinstance(names, str):\n names = [names]\n\n # find files\n files = []\n for name in names:\n for src in self.iter_temp(name, exclude=exclude, **kwargs):\n if '*' in src:\n raise NotImplementedError(\"Can't fnmatch here yet\")\n\n if os.path.exists(src):\n dst = self.get(name, root=dst_root)\n if src == dst:\n raise ValueError(\"Source == destination (%r)\" % src)\n\n if os.path.exists(dst):\n flag = 'o' if overwrite else 'e'\n else:\n flag = ' '\n else:\n dst = None\n flag = 'm'\n files.append((src, dst, flag))\n\n # prompt for confirmation\n root = self.get('root')\n n_root = len(root)\n for src, dst, flag in files:\n if src.startswith(root):\n src = src[n_root:]\n print(' '.join((flag, src[-78:])))\n print(\"Flags: o=overwrite, e=skip, it exists, m=skip, source is \"\n \"missing\")\n if input(\"Proceed? (confirm with 'yes'): \") != 'yes':\n return\n\n # copy the files\n for src, dst, flag in files:\n if flag in ('e', 'm'):\n continue\n\n dirpath = os.path.dirname(dst)\n if not os.path.exists(dirpath):\n os.makedirs(dirpath)\n\n if os.path.isdir(src):\n if flag == 'o':\n shutil.rmtree(dst)\n shutil.copytree(src, dst)\n else:\n shutil.copy(src, dst)\n\n def rename(self, old, new, exclude=False):\n \"\"\"Rename all files corresponding to a pattern (or template)\n\n Parameters\n ----------\n old : str\n Template for the files to be renamed. Can interpret '*', but will\n raise an error in cases where more than one file fit the pattern.\n new : str\n Template for the new names.\n\n Examples\n --------\n The following command will collect a specific file for each subject and\n place it in a common folder:\n\n >>> e.rename('info-file', '/some_other_place/{subject}_info.txt')\n \"\"\"\n new = self.expand_template(new)\n files = []\n for old_name in self.iter_temp(old, exclude):\n if '*' in old_name:\n matches = glob(old_name)\n if len(matches) == 1:\n old_name = matches[0]\n elif len(matches) > 1:\n err = (\"Several files fit the pattern %r\" % old_name)\n raise ValueError(err)\n\n if os.path.exists(old_name):\n new_name = self.format(new)\n files.append((old_name, new_name))\n\n if not files:\n print(\"No files found for %r\" % old)\n return\n\n old_pf = os.path.commonprefix([pair[0] for pair in files])\n new_pf = os.path.commonprefix([pair[1] for pair in files])\n n_pf_old = len(old_pf)\n n_pf_new = len(new_pf)\n\n table = fmtxt.Table('lll')\n table.cells('Old', '', 'New')\n table.midrule()\n table.caption(\"%s -> %s\" % (old_pf, new_pf))\n for old, new in files:\n table.cells(old[n_pf_old:], '->', new[n_pf_new:])\n\n print(table)\n\n msg = \"Rename %s files (confirm with 'yes')? \" % len(files)\n if input(msg) == 'yes':\n for old, new in files:\n dirname = os.path.dirname(new)\n if not os.path.exists(dirname):\n os.makedirs(dirname)\n os.rename(old, new)\n\n def rename_field(self, temp, field, old, new, exclude=False, **kwargs):\n \"\"\"Change the value of one field in paths corresponding to a template\n\n Parameters\n ----------\n temp : str\n Template name.\n field : str\n Field to change.\n old : str\n Old value.\n new : str\n New value.\n kwargs :\n ``self.iter_temp`` arguments.\n \"\"\"\n items = [] # (tag, src, dst)\n kwargs[field] = old\n dst_kwa = {field: new}\n for src in self.iter_temp(temp, exclude, ** kwargs):\n dst = self.get(temp, **dst_kwa)\n if os.path.exists(src):\n if os.path.exists(dst):\n tag = 'o'\n else:\n tag = ' '\n else:\n tag = 'm'\n items.append((tag, src, dst))\n\n src_prefix = os.path.commonprefix(tuple(item[1] for item in items))\n dst_prefix = os.path.commonprefix(tuple(item[2] for item in items))\n src_crop = len(src_prefix)\n dst_crop = len(dst_prefix)\n\n # print info\n if src_prefix == dst_prefix:\n lines = ['in ' + src_prefix, '']\n else:\n lines = [src_prefix, '->' + dst_prefix, '']\n\n for tag, src, dst in items:\n lines.append('%s %s -> %s' % (tag, src[src_crop:], dst[dst_crop:]))\n lines.append('')\n msg = 'Legend m: source is missing; o: will overwite a file'\n lines.append(msg)\n print('\\n'.join(lines))\n rename = tuple(item for item in items if item[0] == ' ')\n if not rename:\n return\n\n msg = \"Rename %i files (confirm with 'yes')? \" % len(rename)\n if input(msg) != 'yes':\n return\n\n for _, src, dst in rename:\n os.rename(src, dst)\n print(\"Done\")\n\n def rm(self, temp, inclusive=False, confirm=False, **constants):\n \"\"\"Remove all files corresponding to a template\n\n Asks for confirmation before deleting anything. Uses glob, so\n individual templates can be set to '*'.\n\n Parameters\n ----------\n temp : str\n Name of the path template for which to find and delete files.\n inclusive : bool\n Treat all unspecified fields as ``*`` (default False).\n confirm : bool\n Confirm removal of the selected files. If False (default) the user\n is prompted for confirmation with a list of files; if True, the\n files are removed immediately.\n **others** :\n Set field values (values can be '*' to match all).\n\n See Also\n --------\n glob : Find all files matching a template.\n copy : Copy files\n move : Move files.\n \"\"\"\n files = self.glob(temp, inclusive, **constants)\n secondary_files = []\n for stemp in self._secondary_cache[temp]:\n secondary_files.extend(self.glob(stemp, inclusive, **constants))\n\n if files or secondary_files:\n print(\"root: %s\\n\" % self.get('root'))\n print('\\n'.join(self._remove_root(files)))\n is_dir = tuple(map(os.path.isdir, files))\n if not confirm:\n n_dirs = sum(is_dir)\n n_files = len(files) - n_dirs\n if n_files and n_dirs:\n info = \"Delete %i files and %i directories\" % (n_files, n_dirs)\n elif n_files:\n info = \"Delete %i files\" % n_files\n elif n_dirs:\n info = \"Delete %i directories\" % n_dirs\n else:\n info = ''\n\n if secondary_files:\n sinfo = '%i secondary files' % len(secondary_files)\n if info:\n info += ' (%s)' % sinfo\n else:\n info = \"Delete %s\" % sinfo\n info += '?'\n\n if ask(info, (('yes', 'delete files'),\n ('no', \"don't delete files (default)\")),\n allow_empty=True) != 'yes':\n print('aborting...')\n return\n\n print('deleting...')\n dirs = (p for p, isdir in zip(files, is_dir) if isdir)\n files = (p for p, isdir in zip(files, is_dir) if not isdir)\n for path in dirs:\n shutil.rmtree(path)\n for path in chain(files, secondary_files):\n os.remove(path)\n else:\n print(\"No files found for %r\" % temp)\n\n def _remove_root(self, paths):\n root = self.get('root')\n root_len = len(root)\n return (path[root_len:] if path.startswith(root) else path\n for path in paths)\n","sub_path":"eelbrain/_experiment/experiment.py","file_name":"experiment.py","file_ext":"py","file_size_in_byte":53314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"380054041","text":"from django.urls import path\nfrom . import views\n\nurlpatterns=[\n path('', views.index),\n path('results', views.results),\n # path('pick', views.pick),\n path('register', views.registration),\n path('create_user', views.create_user),\n path('login_page', views.login_page),\n path('sign_in', views.sign_in),\n path('player_search', views.player_search),\n path('create', views.create),\n path('add_goat', views.add_goat),\n path('submit', views.submit),\n path('run_bet', views.run_bet),\n path('winner_page', views.winner_page),\n path('matchup_maker', views.matchup_maker),\n path('matchup_picker', views.matchup_picker),\n path('random_match', views.random_match),\n path('stats_comp', views.stats_comp)\n]","sub_path":"goat_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"181127668","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\"\"\"=================================================\n@Project : algorithm/graph_theory/shortest_path\n@File : dijkstra.py\n@Author : YuweiYin\n==================================================\"\"\"\n\nimport sys\nimport time\nimport math\n\n\"\"\"\n单源最短路径 Single Source Shortest Path\n非负权值加权图的最短路径 - Dijkstra 算法\n\n参考资料:\nIntroduction to Algorithm (aka CLRS) Third Edition - Chapter 24\n\"\"\"\n\n\n# 边结构体,表达边的信息,可随任务自定义 (增添其它值元素 val 对象)\nclass Edge:\n # 构造方法\n def __init__(self, from_v=None, to_v=None, weight=1, is_directed=True):\n self.from_v = from_v # 边的起始顶点(关键字/序号)\n self.to_v = to_v # 边的终止顶点(关键字/序号)\n self.weight = weight # 边的权重值 (默认值为 1,如果全部边的权重都相同,那图 G 就是无权图)\n self.is_directed = is_directed # True 则表明此边是有向边,False 为无向边\n # 对无向边而言,起始顶点和终止顶点可以互换\n\n # 类序列化输出方法\n def __str__(self):\n return str(self.from_v) + '->' + str(self.to_v) +\\\n '\\t weight:' + str(self.weight) + '\\t is_directed:' + str(self.is_directed)\n\n\n# 用于邻接表的顶点结构体\n# 这里是用散列表 (而不是用链表) 来表达某顶点的所有邻接顶点\nclass VertexList:\n # 构造方法\n def __init__(self, key, val=None, distance=0, p=None):\n self.key = key # 本顶点的关键字 key (通常为顶点序号、唯一标志符)\n self.val = val # 本顶点的值元素 val (可自定义为任意对象,为结点附带的信息)\n self.neighbor = dict({}) # 本顶点的邻居字典,key 为邻居的关键字,value 为 Edge 边结构体\n # 如果是有向图,本结点为关联边的出发点 from_v,其邻居关联边的终止点 to_v\n '''如下为最短路径算法所需的属性'''\n self.distance = distance # 从源结点 s 到本结点的最短路径权重值\n self.p = p # 本结点的前驱结点/最短路径树的父结点\n\n # 类序列化输出方法\n def __str__(self):\n return str(self.key) + ' is connected to:' + str([v.key for v in self.neighbor])\n\n # 增添本顶点的邻居 neighbor,以字典结构存储\n # 注意:如果不允许图有自环/自圈,那么在增添邻居/边 的时候要禁止增添 self.neighbor[self.key] 项。这里暂不限制\n def add_neighbor(self, key, weight=1, is_directed=True):\n # 如果 neighbor 字典里已有此 key,则会覆盖。起到了更新边信息的作用\n self.neighbor[key] = Edge(from_v=self.key, to_v=key, weight=weight, is_directed=is_directed)\n\n # 以 Edge 边结构体来增添本顶点的邻居 neighbor\n def add_edge(self, edge):\n # 检查输入 edge 的合法性\n if isinstance(edge, Edge):\n # 如果 edge 是有向边,那么本结点需要是 edge 的出发点 from_v\n if edge.is_directed:\n if edge.from_v == self.key:\n self.neighbor[edge.to_v] = edge\n # 如果 edge 是无向边,那么本结点需要是 edge 的出发点 from_v 或结束点 to_v 之一\n else:\n if edge.from_v == self.key:\n self.neighbor[edge.to_v] = edge\n elif edge.to_v == self.key:\n # 先把 from_v 和 to_v 交换\n edge.to_v = edge.from_v\n edge.from_v = self.key\n self.neighbor[edge.to_v] = edge\n\n # 返回本顶点的所有邻接顶点(的关键字/序号) 数组\n def get_connections(self):\n return self.neighbor.keys()\n\n # 返回本顶点到邻居 neighbor 的 Edge 边结构体\n def get_weight(self, neighbor):\n if neighbor in self.neighbor:\n return self.neighbor[neighbor]\n else:\n return None\n\n\n# 邻接表的图结构,通常适合稀疏图\n# 输入顶点结构体列表���边结构体列表\nclass AdjacencyList:\n # 构造函数,edges 必须是二维数组,内部维度是一系列长度为 2 或者 3 的数组,\n # 分别代表着边的起始顶点 start、终止顶点 end 以及边权(可选)\n def __init__(self, vertices, edges):\n assert isinstance(vertices, list)\n\n self.edges = edges # 存储输入的边列表\n self.vertices = vertices # 存储输入的顶点列表 (可以从下标映射到顶点)\n self.v2index = dict({}) # 由顶点映射到其下标 (既是邻接矩阵的行/列下标,也是 vertices 列表的下标)\n self.key2index = dict({}) # 由顶点的关键字/唯一标志符映射到其下标\n for index, vertex in enumerate(vertices):\n self.v2index[vertex] = index\n self.key2index[vertex.key] = index\n\n self.adj_l = dict({}) # 本图的顶点字典, key 为顶点的序号,val 为顶点结构体\n for vertex in vertices:\n assert isinstance(vertex, VertexList)\n self.adj_l[vertex.key] = vertex\n\n # 若 edges 合法,则进行边初始化处理\n if isinstance(edges, list):\n for edge in edges:\n assert isinstance(edge, Edge)\n # 如果是有向边\n if edge.is_directed:\n from_v = edge.from_v\n if from_v in self.adj_l:\n self.adj_l[from_v].add_edge(edge)\n # 如果是无向边\n else:\n from_v = edge.from_v\n to_v = edge.to_v\n if from_v in self.adj_l:\n self.adj_l[from_v].add_edge(edge)\n if to_v in self.adj_l:\n self.adj_l[to_v].add_edge(edge)\n\n # 判断 key 号为 _key 的顶点是否位于顶点列表中\n def __contains__(self, _key):\n return _key in self.adj_l\n\n # 类迭代器方法\n def __iter__(self):\n return iter(self.adj_l.values())\n\n # 获取图中 key 号为 _key 的顶点,如果没有此顶点则返回 None\n def get_vertex(self, _key):\n if _key in self.adj_l:\n return self.adj_l[_key]\n else:\n return None\n\n # 邻接表 - 图转置\n def graph_transposition(self):\n for edge in self.edges:\n assert isinstance(edge, Edge)\n # 其实如果是无向边,无需处理,但这里还是转了\n temp = edge.from_v\n edge.from_v = edge.to_v\n edge.to_v = temp\n\n # 输出每个结点的信息\n def print_vertex_info(self):\n for v in self.vertices:\n if isinstance(v.p, VertexList):\n print(v.key, '\\tdistance:', v.distance, '\\tp:', v.p.key)\n else:\n print('Shortest Path Tree root:', v.key, '\\tdistance:', v.distance)\n\n\n# 元素结构体\nclass Element:\n def __init__(self, key, val=None):\n self.key = key # (必备) 关键字 key。按每个顶点的 min_w 属性作为最小优先队列 Q 的 key\n self.val = val # (可选) 值对象 val。每个顶点 Vertex 结构体\n self.left = self # 本结点所在循环双向链表的 左兄弟结点\n self.right = self # 本结点所在循环双向链表的 右兄弟结点\n self.parent = None # 本结点的父结点\n self.child = None # 本结点的(某一个)孩子结点\n self.degree = 0 # 本结点的孩子链表中的孩子数目\n self.mark = False # 指示本结点自从上一次成为另一个孩子的结点后,是否失去过孩子\n\n\n# 斐波那契(最小)堆 Fibonacci Min-Heap 数据结构\nclass FibonacciHeap:\n # 创建一个新的斐波那契堆 H\n # 此构造函数即为 make_fib_heap 过程\n # (摊还/实际)时间复杂度 O(1)\n def __init__(self, kv_list=None):\n # 斐波那契堆 H 就是本类(对象) self,有如下两个属性\n self.min = None # 指向 H 中具有最小关键字的树的根结点\n self.n = 0 # 表示 H 中当前含有的结点总数目\n\n # 如果传入的 kv_list 为列表,则以插入的方式构建斐波那契堆 H\n # 如果传入的 kv_list 不为列表或者内容不合法,则是一个空斐波那契堆\n if isinstance(kv_list, list):\n for kv in kv_list:\n assert isinstance(kv, list) and len(kv) == 2\n self.fib_heap_insert(kv[0], kv[1])\n\n '''如下为 5 个可合并堆的基本操作'''\n\n # 创建并返回一个新的斐波那契堆\n # 构造函数即为 make_fib_heap 过程\n # (摊还/实际)时间复杂度 O(1)\n # def make_fib_heap(self):\n # self.min = None # 指向 H 中具有最小关键字的树的根结点\n # self.n = 0 # 表示 H 中当前含有的结点总数目\n\n # 根据 key/val 构造结点,并插入到斐波那契堆 H 中\n # 操作成功返回 True,否则返回 False\n # (摊还/实际)时间复杂度 O(1)\n def fib_heap_insert(self, insert_key, insert_val):\n # 根据 key/val 创建一个新的 Element 结点\n insert_ele = Element(insert_key, insert_val)\n # 判断当前斐波那契堆 H 是否为空\n if isinstance(self.min, Element):\n # 如果 H 不为空,先插入当前新结点到根链表\n insert_ele.right = self.min.right\n assert isinstance(self.min.right, Element) # 由于是循环双向链表,所以有此断言\n self.min.right.left = insert_ele\n self.min.right = insert_ele\n insert_ele.left = self.min\n\n # 然后再检查是否需要更改 H.min\n if insert_key < self.min.key:\n self.min = insert_ele\n else:\n # 如果 H 为空,则使得当前新结点 为 H 的根链表中唯一的结点\n self.min = insert_ele\n # 结点总数目加一\n self.n += 1\n return True\n\n # 根据 Element 对象构造结点,并插入到斐波那契堆 H 中\n # 操作成功返回 True,否则返回 False\n # (摊还/实际)时间复杂度 O(1)\n def fib_heap_insert_ele(self, insert_ele):\n if isinstance(insert_ele, Element):\n # 判断当前斐波那契堆 H 是否为空\n if isinstance(self.min, Element):\n # 如果 H 不为空,先插入当前新结点到根链表\n insert_ele.right = self.min.right\n assert isinstance(self.min.right, Element) # 由于是循环双向链表,所以有此断言\n self.min.right.left = insert_ele\n self.min.right = insert_ele\n insert_ele.left = self.min\n\n # 然后再检查是否需要更改 H.min\n if insert_ele.key < self.min.key:\n self.min = insert_ele\n else:\n # 如果 H 为空,则使得当前新结点 为 H 的根链表中唯一的结点\n self.min = insert_ele\n # 结点总数目加一\n self.n += 1\n return True\n else:\n return False\n\n # 合并两个斐波那契堆\n # 操作成功返回 True,否则返回 False\n # (摊还/实际)时间复杂度 O(1)\n # (此为静态函数,不对本斐波那契堆 self 作用)\n @staticmethod\n def fib_heap_union(h1, h2):\n if isinstance(h1, FibonacciHeap) and isinstance(h2, FibonacciHeap):\n # h1 和 h2 均为斐波那契堆,考察二者是否为空堆\n if isinstance(h1.min, Element) and isinstance(h2.min, Element):\n # 二者均不为空,则正常合并。\n # 先构建一个新的空斐波那契堆,并设置 min 为 h1.min\n union_heap = FibonacciHeap()\n union_heap.min = h1.min\n\n # 将 h2 连接到 union_heap 中 (两个循环双向链表的连接)\n assert isinstance(union_heap.min.right, Element)\n assert isinstance(h2.min.left, Element)\n union_heap.min.right.left = h2.min.left\n h2.min.left.right = union_heap.min.right\n union_heap.min.right = h2.min\n h2.min.left = union_heap.min\n\n # 检查是否需要更新 min\n if h2.min.key < union_heap.min.key:\n union_heap.min = h2.min\n # 增加结点数目\n union_heap.n = h1.n + h2.n\n # 返回合并后的斐波那契堆\n return union_heap\n elif isinstance(h1.min, Element):\n # 如果仅 h1 为非空堆,则返回 h1\n return h1\n elif isinstance(h2.min, Element):\n # 如果仅 h2 为非空堆,则返回 h2\n return h2\n else:\n # 如果 h1 和 h2 均为空堆,则任意返回其中一个 (这里返回 h1)\n return h1\n elif isinstance(h1, FibonacciHeap):\n # 如果仅 h1 为斐波那契堆,则返回 h1\n return h1\n elif isinstance(h2, FibonacciHeap):\n # 如果仅 h2 为斐波那契堆,则返回 h2\n return h2\n else:\n # 如果 h1 和 h2 均不为斐波那契堆,则返回空\n return None\n\n # 查询最小结点\n # (摊还/实际)时间复杂度 O(1)\n def fib_heap_minimum(self):\n return self.min\n\n # 查询最小结点 - 输出其 key/val\n # (摊还/实际)时间复杂度 O(1)\n def fib_heap_print_min_kv(self):\n if isinstance(self.min, Element):\n print(self.min.key, self.min.val)\n else:\n print('Fibonacci Heap is Empty!')\n\n # 抽取最小结点 (查找、删除、返回)\n # (摊还)时间复杂度 O(log n)\n def fib_heap_extract_min(self):\n z = self.min # 待删除的结点 z\n if isinstance(z, Element):\n # 判断待删结点 z 是否有孩子结点\n # 如果没有孩子结点,则跳过下面的分支,直接删除 z,并寻找替代的 min\n if isinstance(z.child, Element):\n # 如果待删结点 z 有孩子结点,则把其所有孩子均移至根链表\n # 先遍历此孩子链表,将其父指针均置为空\n ptr = z.child\n ptr.parent = None\n while ptr.right != z.child:\n ptr = ptr.right\n ptr.parent = None\n # 然后将此孩子链表链接到 H 的根链表 (两个循环双向链表的连接)\n # 孩子的孩子结点则不改动\n z.child.right.left = z.left\n z.left.right = z.child.right\n z.child.right = z\n z.left = z.child\n # 清除 z 的孩子指针\n z.child = None\n\n # 从根链表中删除结点 z\n if z.right == z:\n # 本堆仅有 z 一个结点,删除之后堆为空\n assert z.left == z and self.n == 1\n self.min = None\n self.n = 0\n else:\n # 本堆不止 z 一个结点,则正常删除 z (通过修改链表指针链接)\n self.min = z.right # 将 min 改为 z.right,但它不一定是根链表中的最小结点,之后会修复此性质\n z.right.left = z.left\n z.left.right = z.right\n # 合并根链表中的结点,减少根链表的结点数目,并修复性质:让 self.min 确实为最小元素\n self._consolidate()\n self.n -= 1\n # 返回被删结点 z\n return z\n else:\n # self.min 不是 Element 对象,表明此斐波那契堆为空堆\n return None\n\n # 辅助函数:合并斐波那契堆 H 的根链表\n # 重复执行如下步骤,直到根链表中的每个结点有不同的 degree 度数\n # 1. 在根链表中找到两个具有相同度数的根 x 和 y。不失一般性,假定 x.key <= y.key\n # 2. 把 y 链接到 x:从根链表中移除 y,调用 _fib_heap_link 过程,使 y 成为 x 的孩子\n # 过程 2 将 x.degree 属性增加 1,并清除 y 上的 mark 标记\n def _consolidate(self):\n # 辅助数组 d_arr 用于记录根结点对应的度数的轨迹\n # 如果 d_arr[i] == y,那么当前的 y 是一个具有 y.degree == i 的结点\n # d_arr 数组的长度为最大度数的上界 D(H.n),可以证明 D(H.n) <= \\floor(log_{phi} n) = O(log n)\n phi = (1 + math.sqrt(5)) / 2 # 黄金分割率 golden_ratio ~= 1.61803\n # phi = round(phi, 5) # 四舍五入仅保留小数点后几位,可加速下面的对数运算\n max_d = int(math.log(self.n, phi)) + 1 # 最大度数的上界\n\n # 创建长度为 max_d 的辅助数据 d_arr\n # 如果 d_arr 中某结点关键字 key 为 inf,则表示仅为占位结点\n inf = 0x3f3f3f3f\n d_arr = []\n for i in range(max_d):\n empty_node = Element(inf)\n d_arr.append(empty_node)\n\n # 循环处理根链表中的每个根结点 cur_root\n ptr = self.min.right\n assert isinstance(ptr, Element) # 进入 _consolidate 前已保证本斐波那契堆不是空堆,故有此断言\n while ptr != self.min:\n # ptr 可能会成为别的结点的子结点,所以不再是根结点,因此下一个检查的也就不是 ptr.right 了\n next_root = ptr.right # 记录下一个应该检查的根结点\n cur_root = ptr\n assert isinstance(cur_root, Element)\n cur_d = cur_root.degree # 当前结点的度数\n assert 0 <= cur_d < max_d\n\n # 若存在与当前根结点 cur_root 相同度数的结点 y,需要合并这两个结点\n while d_arr[cur_d].key != inf:\n y = d_arr[cur_d] # 取出此结点 y,让它加入 cur_root 的孩子链表\n assert isinstance(y, Element)\n # 如果原本在 trace 数组里的结点 y 的关键字 key 更小,则交换 cur_root 和 y\n if y.key < cur_root.key:\n temp = y\n y = cur_root\n cur_root = temp\n # 让结点 y 加入结点 cur_root 的孩子链表\n self._fib_heap_link(cur_root, y)\n # 让 d_arr[cur_d] 变为占位元素\n empty_node = Element(inf)\n d_arr[cur_d] = empty_node\n # 此时 cur_root 的度数增加了 1,所以要检查此新度数会不会又是重复的\n cur_d += 1\n # 循环处理完后,把 cur_root 加入数组 d_arr 相应的位置\n assert 0 <= cur_d < max_d\n d_arr[cur_d] = cur_root\n ptr = next_root\n\n # 外层 while 循环忽略了 self.min 结点,所以此时要对 self.min 结点做相同的处理\n cur_root = self.min\n assert isinstance(cur_root, Element)\n cur_d = cur_root.degree # 当前结点的度数\n assert 0 <= cur_d < max_d\n\n # 若存在与当前根结点 cur_root 相同度数的结点 y,需要合并这两个结点\n while d_arr[cur_d].key != inf:\n y = d_arr[cur_d] # 取出此结点 y,让它加入 cur_root 的孩子链表\n assert isinstance(y, Element)\n # 如果原本在 trace 数组里的结点 y 的关键字 key 更小,则交换 cur_root 和 y\n if y.key < cur_root.key:\n temp = y\n y = cur_root\n cur_root = temp\n # 让结点 y 加入结点 cur_root 的孩子链表\n self._fib_heap_link(cur_root, y)\n # 让 d_arr[cur_d] 变为占位元素\n empty_node = Element(inf)\n d_arr[cur_d] = empty_node\n # 此时 cur_root 的度数增加了 1,所以要检查此新度数会不会又是重复的\n cur_d += 1\n # 循环处理完后,把 cur_root 加入数组 d_arr 相应的位置\n assert 0 <= cur_d < max_d\n d_arr[cur_d] = cur_root\n\n # 最后,对处理好后的 d_arr 进行遍历\n self.min = None\n for i in range(max_d):\n if isinstance(d_arr[i], Element) and d_arr[i].key != inf:\n # 如果 d_arr[i] 不是占位元素,则将之插入到根链表\n new_root = d_arr[i]\n if isinstance(self.min, Element):\n # 如果此时 self.min 存在,则将 d_arr[i] 结点插入根链表\n new_root.right = self.min.right\n self.min.right.left = new_root\n new_root.left = self.min\n self.min.right = new_root\n # 并视情况更新 self.min\n if new_root.key < self.min.key:\n self.min = new_root\n else:\n # 如果此时 self.min 为空,则创建一个仅含 d_arr[i] 结点的根链表\n new_root.left = new_root.right = new_root\n new_root.parent = None\n self.min = new_root\n\n # 辅助函数:让结点 y 加入结点 cur_root 的孩子链表\n def _fib_heap_link(self, cur_root, y):\n assert isinstance(y, Element) and isinstance(cur_root, Element)\n assert self.n >= 2 and y.right != y # 此时根链表至少有两个结点\n # 1. 将结点 y 从根链表中移除\n y.right.left = y.left\n y.left.right = y.right\n\n # 2. 让 y 加入 cur_root 的孩子链表,并增加 cur_root 的度数\n if isinstance(cur_root.child, Element):\n # 如果 cur_root 已有孩子结点,则正常插入\n y.parent = cur_root\n y.right = cur_root.child.right\n cur_root.child.right.left = y\n y.left = cur_root.child\n cur_root.child.right = y\n else:\n # 否则让 y 成为 cur_root 的唯一孩子结点\n cur_root.child = y\n y.parent = cur_root\n y.left = y.right = y\n cur_root.degree += 1\n\n # 3. 重置结点 y 的 mark 标志为 False (此时没有失去孩子)\n y.mark = False\n\n '''如下为 2 个斐波那契堆可以额外完成的操作'''\n\n # 减小某结点的关键字 key\n # (摊还)时间复杂度 O(1)\n # 操作成功则返回 True,否则返回 False\n def fib_heap_decrease_key(self, x, new_k):\n if isinstance(x, Element):\n if x.key < new_k:\n # 只能降 key,不能升 key\n return False\n elif x.key == new_k:\n # 已满足目标\n return True\n else:\n x.key = new_k\n # 如果父结点存在,则观察是否需要维护最小堆性质\n y = x.parent\n if isinstance(y, Element) and x.key < y.key:\n # 结点 x 比其父结点 y 的关键字 key 更小,需要维护最小堆性质\n self._cut(x, y) # 从 y 中移除 x,并将 x 加入根链表\n self._cascading_cut(y) # y 失去了孩子 x,进行处理\n # 视情况更新 self.min\n if x.key < self.min.key:\n self.min = x\n return True\n else:\n return False\n\n # 辅助函数:切断 x 与其父结点 y 的关联,并将 x 加入根链表\n def _cut(self, x, y):\n assert isinstance(x, Element) and isinstance(y, Element)\n # 1. 将 x 从其父结点 y 的孩子链表中移除,并减小 y 的度数\n if x == x.right:\n # 如果 x 是 y 的唯一孩子\n assert x == x.left and y.child == x\n y.child = None\n else:\n # 如果 x 不是 y 的唯一孩子,则正常移除 x\n x.right.left = x.left\n x.left.right = x.right\n # 如果 y 的 child 指针当前指向了 x,则要更换 child 指针的指向\n if y.child == x:\n y.child = x.right\n y.degree -= 1\n\n # 2. 把 x 加入到根链表中\n assert isinstance(self.min, Element)\n x.right = self.min.right\n self.min.right.left = x\n x.left = self.min\n self.min.right = x\n\n # 3. 修改 x 的父指针、重置 mark 标记\n x.parent = None\n x.mark = False\n\n # 辅助函数:\n def _cascading_cut(self, y):\n assert isinstance(y, Element)\n z = y.parent\n # 如果 y 的父结点不是空,表示 y 不是根结点\n if isinstance(z, Element):\n if not y.mark:\n # 如果此前 y 没有失去过孩子,则此时记录 y 失去过孩子\n # 因为 _cascading_cut 函数调用前 执行了 _cut 函数\n y.mark = True\n else:\n # 继续向上处理:\n # 先调用 _cut 函数:从 z 中移除 y,并将 y 移至根链表\n self._cut(y, z)\n # 然后递归调用 _cascading_cut 函数,处理父结点 z\n self._cascading_cut(z)\n\n # 删除某结点\n # 假定在斐波那契堆中任何关键字的当前值均大于 -inf 负无穷\n # 则删除操作仅需调用之前实现好的两个操作\n # 删除成功则返回被删除的结点,否则返回 None\n # (摊还)时间复杂度 O(log n)\n def fib_heap_delete(self, x):\n neg_inf = -0x3f3f3f3f\n if isinstance(x, Element) and x.key > neg_inf:\n # 1. 把待删除结点的关键字 key 降到负无穷 -inf,从而成为了 self.min\n if self.fib_heap_decrease_key(x, neg_inf):\n # 2. 如果降 key 成功,则把最小值抽取出来\n return self.fib_heap_extract_min()\n else:\n return None\n else:\n return None\n\n\nclass Dijkstra:\n def __init__(self):\n self.inf = 0x3f3f3f3f - 1 # 所有结点的 distance 初始化为 inf\n # 注意这里的 inf 无穷要小于 斐波那契堆 fib_heap_extract_min 中的 inf\n\n # 初始化每个结点的 distance 和 p 属性\n def initialize_single_source(self, adj_l, source_v):\n assert isinstance(adj_l, AdjacencyList) and isinstance(source_v, VertexList)\n for v in adj_l.vertices:\n assert isinstance(v, VertexList)\n v.distance = self.inf\n v.p = None\n source_v.distance = 0\n\n # 对边 (u, v) 进行松弛操作\n @staticmethod\n def relax(u, v, weight_func=lambda x: x):\n assert isinstance(u, VertexList) and isinstance(v, VertexList)\n # 获取边 (u, v)\n assert v.key in u.neighbor\n edge = u.neighbor[v.key]\n # 检查是否可以对从 s 到 v 的最短路径进行改善\n # 将 s->u 的最短路径距离 加上 u->v 的边权重值\n cur_dis = u.distance + weight_func(edge.weight)\n # cur_dis 与当前得到的 s->v 的最短路径估计 进行比较\n if cur_dis < v.distance:\n # 如果前者更小,则更新估计值 v.d 并修改前驱结点 v.p\n v.distance = cur_dis\n v.p = u\n\n # 寻找图 adj_l 从源结点 source_v 出发的单源最短路径\n # 这里默认图为邻接表结构,weight_func 为恒等函数\n def do_dijkstra(self, adj_l, source_v, weight_func=lambda x: x):\n assert isinstance(adj_l, AdjacencyList) and isinstance(source_v, VertexList)\n # 1. 对所有结点的 d 值和 p 值进行初始化\n self.initialize_single_source(adj_l, source_v)\n\n # 2. 将集合 S 初始化为一个空集\n # s_set = []\n\n # 3. (利用斐波那契堆)创建最小优先队列 Q 并将 V 中全部结点入队\n min_pri_q = FibonacciHeap(kv_list=None)\n v2ele = dict({}) # 顶点的关键字到 Element 对象的映射\n for v in adj_l.vertices:\n assert isinstance(v, VertexList)\n # 每个结点在 Q 中的关键值 key 为其 distance 值\n new_ele = Element(key=v.distance, val=v) # 封装为 Element 结构体\n v2ele[v.key] = new_ele\n min_pri_q.fib_heap_insert_ele(insert_ele=new_ele)\n\n # 4. 只要 Q 不空,则继续 while 循环\n while min_pri_q.min is not None:\n # 4.1. 取出 Q 中最小 d 值的结点 u\n u_ele = min_pri_q.fib_heap_extract_min()\n assert isinstance(u_ele, Element)\n u_vertex = u_ele.val\n assert isinstance(u_vertex, VertexList)\n # 4.2. 把结点 u 加入集合 S 中\n # s_set.append(u_vertex)\n # 4.3. 在 for 循环中,对于 u 的每个邻接结点 v,松弛边 (u, v)\n for edge in u_vertex.neighbor.values():\n # 先通过边中存储的的 from/to 关键字获取 u/v 顶点结构体\n assert isinstance(edge, Edge)\n assert edge.from_v in adj_l.key2index and edge.to_v in adj_l.key2index\n u = adj_l.vertices[adj_l.key2index[edge.from_v]]\n v = adj_l.vertices[adj_l.key2index[edge.to_v]]\n assert isinstance(u, VertexList) and isinstance(v, VertexList)\n # 对边 (u, v) 进行松弛操作\n # self.relax(u, v, weight_func)\n # 检查是否可以对从 s 到 v 的最短路径进行改善\n # 将 s->u 的最短路径距离 加上 u->v 的边权重值\n cur_dis = u.distance + weight_func(edge.weight)\n # cur_dis 与当前得到的 s->v 的最短路径估计 进行比较\n if cur_dis < v.distance:\n # 如果前者更小,则更新估计值 v.d 并修改前驱结点 v.p\n v.distance = cur_dis\n v.p = u\n # 最小优先队列 Q 执行 decrease_key 操作\n assert v.key in v2ele\n min_pri_q.fib_heap_decrease_key(v2ele[v.key], cur_dis)\n\n\ndef main():\n # 构造图同《CLRS》Chapter 24.3 的(带非负边权)有向图\n # 用于构造邻接表的顶点的 key/val 信息列表\n list_vertices_info = [\n ['s', 100], ['t', 200], ['x', 300], ['y', 400], ['z', 500]\n ]\n # 有向边的 from/to/weight/is_directed 信息列表\n # is_directed 为 True 表示此边为有向边,否则为无向边\n di_edges_info = [\n ['s', 't', 10, True], ['s', 'y', 5, True], ['t', 'y', 2, True],\n ['t', 'x', 1, True], ['y', 't', 3, True], ['y', 'x', 9, True],\n ['y', 'z', 2, True], ['x', 'z', 4, True], ['z', 'x', 6, True],\n ['z', 's', 7, True]\n ]\n\n # 根据前述列表信息构造结点列表\n list_vertices = []\n di_edges = []\n for v in list_vertices_info:\n list_vertices.append(VertexList(key=v[0], val=v[1]))\n for e in di_edges_info:\n di_edges.append(Edge(from_v=e[0], to_v=e[1], weight=e[2], is_directed=e[3]))\n\n # 创建邻接表 (用邻接链表+无向图 执行最短路径算法)\n adj_l = AdjacencyList(list_vertices, di_edges)\n\n # 设置源结点\n source_v_key = 's'\n assert source_v_key in adj_l.key2index\n source_v = adj_l.vertices[adj_l.key2index[source_v_key]]\n\n # 执行 Dijkstra 算法\n # Shortest Path Tree root: s \tdistance: 0\n # t \tdistance: 8 \tp: y\n # x \tdistance: 9 \tp: t\n # y \tdistance: 5 \tp: s\n # z \tdistance: 7 \tp: y\n start = time.process_time()\n dijkstra = Dijkstra()\n dijkstra.do_dijkstra(adj_l, source_v)\n end = time.process_time()\n\n # 输出结果\n adj_l.print_vertex_info()\n\n print('Running Time: %.5f ms' % ((end - start) * 1000))\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"Algorithm-Essence/graph-theory/shortest-path/dijkstra.py","file_name":"dijkstra.py","file_ext":"py","file_size_in_byte":31981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"103449646","text":"# %%\nimport os\nimport json\nimport numpy as np\nfrom pathlib import Path\nimport tensorflow as tf\n\n# basename = os.path.basename(\n# \"C:\\\\Users\\\\taeya\\\\Documents\\\\ARK\\\\data\\\\abstraction-and-reasoning-challenge\\\\training\"\n# )\n# print(basename)\nfor tra_tst_val in [\"training\", \"evaluation\", \"test\"]:\n files_ds = tf.data.Dataset.list_files(\n \"C:\\\\Users\\\\taeya\\\\Documents\\\\ARK\\\\data\\\\abstraction-and-reasoning-challenge\\\\\"+tra_tst_val+\"\\\\*.json\"\n )\n\n # plotter = plotter.Plotter(CH_source, SIZE)\n\n tra_tst_key = (\"train\", \"test\")\n in_out_key = (\"input\", \"output\")\n\n for file_path in files_ds:\n file_path = file_path.numpy()\n path = Path(file_path.decode(\"utf-8\"))\n json_open = open(path, \"r\")\n json_load = json.load(json_open)\n for train_or_test, one_episode in json_load.items():\n for i, inputs_or_outputs in enumerate(one_episode):\n for input_or_output, one_image in inputs_or_outputs.items():\n one_image = np.array(one_image)\n save_path = path.parent.joinpath(\"one_photos\")\n save_path.mkdir(exist_ok=True)\n save_name = save_path.joinpath(\n path.stem + train_or_test + input_or_output + str(i)\n )\n np.save(save_name, one_image)\n\n#%%\nimport glob\nfrom pathlib import Path\nimport json\nimport numpy as np\nimport os\n\nimport data_processing.arc.plotter as plotter\nimport data_processing.arc.tag as tag \nfrom importlib import reload\nreload(plotter)\nreload(tag)\n\nword_change = {\"train\": \"base\", \"test\": \"novel\"} \nbase_path = \"C:\\\\Users\\\\taeya\\\\Documents\\\\ARK\\\\data\\\\abstraction-and-reasoning-challenge\\\\\"\n\nmax_size = 10\nristrict_epi_len = 5\nonly_one_tag = True\nmake_path = base_path+\"\\\\max_epi_\"+str(ristrict_epi_len)+\"_max_size_\"+str(max_size)\nmake_path += \"_only_one_tag\" if only_one_tag else \"\"\nos.makedirs(make_path, exist_ok=True)\nskill_list = tag.skill_list\nepisode_in_one_skill = []\n\nplotter_instance = plotter.Plotter()\n\nfor tra_tst_val in [\"training\", \"evaluation\", \"test\"]:\n file_list = glob.glob(base_path +tra_tst_val+\"\\\\*.json\")\n\n base_max = novel_max = num_upper_max_size = 0\n for file in file_list:\n path = Path(file)\n with open(path, \"r\") as f:\n json_load = json.load(f)\n\n base_ind = novel_ind = 0\n images = {}\n for train_or_test, one_episode in json_load.items():\n for i, inputs_or_outputs in enumerate(one_episode):\n for input_or_output, one_image in inputs_or_outputs.items():\n one_image = np.array(one_image)\n base_or_novel = word_change[train_or_test]\n if input_or_output == \"input\":\n if base_or_novel == \"base\":\n base_ind += 1\n else:\n novel_ind += 1\n ind = str(base_ind) if base_or_novel == \"base\" else str(novel_ind)\n images[base_or_novel + ind + input_or_output] = one_image\n\n is_one_skill = False\n if path.stem+\".json\" in tag.skill_series.keys() :\n file_tag = tag.skill_series[path.stem+\".json\"]\n if len(file_tag) == 1:\n episode_in_one_skill.append(file_tag[0])\n is_one_skill = True\n \n is_upper_max_size = False\n for image in images.values():\n\n if image.shape[0] > max_size or image.shape[1] > max_size:\n is_upper_max_size = True\n break\n\n if base_ind <= ristrict_epi_len and is_upper_max_size == False:\n \n if only_one_tag is True and is_one_skill is False:\n pass\n else:\n os.makedirs(make_path + \"\\\\\"+tra_tst_val, exist_ok=True)\n np.savez(make_path + \"\\\\\"+tra_tst_val + \"\\\\\"+path.stem , **images)\n \n if is_one_skill:\n num_upper_max_size += 1\n \n\n \n # if is_upper_max_size:\n # for key, image in images.items():\n # plotter_instance.plot_some(image.reshape(-1, image.shape[0], image.shape[1]),key, fold = 2)\n if base_max < base_ind:\n base_max = base_ind\n if novel_max < novel_ind:\n novel_max = novel_ind\n print(tra_tst_val, base_max, novel_max)\n # print(len(episode_in_one_skill))\n # print(len(skill_list))\n print(num_upper_max_size)\n \"\"\"\n trainのepisode数最大beseで10,novelで3\n evalのepisode数最大beseで7,novelで2\n testのepisode数最大beseで6,novelで2\n \"\"\"\n\n# %%\n","sub_path":"data_processing/arc/make_arc_np_data.py","file_name":"make_arc_np_data.py","file_ext":"py","file_size_in_byte":4666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"407296711","text":"import selenium\nfrom selenium import webdriver\nfrom openpyxl import Workbook\n\n\nurl = 'http://www.cwl.gov.cn/kjxx/ssq/kjgg/'\noption = webdriver.ChromeOptions()\noption.add_argument('headless') #配置浏览器静默显示参数\nbrowser = selenium.webdriver.Chrome(chrome_options=option)\nbrowser.get(url)\ntbody = browser.find_elements_by_xpath(\"/html/body/div[1]/div/div[3]/table/tbody/tr\")\n# ssqlist = []\ntable = Workbook()\nsheet = table.create_sheet()\nsheet['A1'] = \"Nums\"\nsheet['B1'] = \"Date\"\nsheet['C1'] = \"Red1\"\nsheet['D1'] = \"Red2\"\nsheet['E1'] = \"Red3\"\nsheet['F1'] = \"Red4\"\nsheet['G1'] = \"Red5\"\nsheet['H1'] = \"Red6\"\nsheet['I1'] = \"Blue\"\n\ni = 2\nfor tr in tbody:\n ssq = {}\n ssq['num'] = tr.find_element_by_xpath(\"./td[1]\").text\n ssq['opendate'] = tr.find_element_by_xpath(\"./td[2]\").text\n ssq['redball'] = tr.find_element_by_xpath(\"./td[3]\").text\n # ssq['reds'] = tr.find_elements_by_class_name('rq1')\n # for red in ssq['reds']:\n # print(red.text)\n # print(type(ssq['redballs']))\n # print(ssq['redballs'])\n ssq['blueball'] = tr.find_element_by_xpath(\"./td[4]\").text\n # 写入单元格ABCD列,i为行号\n sheet['A'+str(i)] = ssq['num']\n sheet['B'+str(i)] = ssq['opendate']\n sheet['C'+str(i)] = ssq['redball'][0:2]\n sheet['D'+str(i)] = ssq['redball'][2:4]\n sheet['E'+str(i)] = ssq['redball'][4:6]\n sheet['F'+str(i)] = ssq['redball'][6:8]\n sheet['G'+str(i)] = ssq['redball'][8:10]\n sheet['H'+str(i)] = ssq['redball'][10:12]\n sheet['I'+str(i)] = ssq['blueball']\n # print(ssq)\n # ssqlist.append(ssq)\n i += 1\ntry:\n table.save('SSQ.xlsx')\n print('success!')\nexcept expression as identifier:\n pritn('failed!')\nexit()\n","sub_path":"getSSQ.py","file_name":"getSSQ.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"444831952","text":"from numpy import *\nimport operator\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom os import listdir\ndef createDateSet():\n\tgroup = array([[1.0,1.1],[1.1,1.0],[0,0],[0,0.1]])\n\tlabels=['A','A','B','B']\n\treturn group,labels\ndef classfy0(inX,dataSet,labels,k):\n\tdataSetSize=dataSet.shape[0]\n\t# tile(A,reps)参数都是arraylike类型,将A复制成reps[0]行,reps[1]列,\n\tdiffMat=tile(inX,(dataSetSize,1))-dataSet\n\tsqDiffMat=diffMat**2\n\tsqDistances=sqDiffMat.sum(axis=1)\n\tdistances=sqDistances**0.5\n\t# 得到距离值按从小到大排序后的索引\n\tsortedDistIndicies=distances.argsort()\n\tclassCount={ }\n\tfor i in range(k):\n\t\t# 取出索引列表中的第i项对应的label(标签值或者叫类别)\n\t\tvoteIlabel=labels[sortedDistIndicies[i]]\n\t\t# 按类别的统计个数放入到字典中\n\t\t# dict.get()方法用的很好,当存在voteIlabel时,返回对应的value值,不存在时,返回0,适合用来计数\n\t\tclassCount[voteIlabel]=classCount.get(voteIlabel,0)+1\n\tsortedClassCount=sorted(classCount.items(),key=operator.itemgetter(1),reverse=True)\n\t#python3下dict.items()以列表返回字典的键值对,python2下是dict.iteritems()\n\treturn sortedClassCount[0][0]\n\ndef file2matrix(filename):\n\twith open(filename) as f:\n\t\tarrayOLines=f.readlines()\n\t\tnumberOfLines=len(arrayOLines)\n\t\treturnMat=zeros((numberOfLines,3))\n\t\tclassLabelVector=[]\n\t\tindex=0\n\t\tfor line in arrayOLines:\n\t\t\tline=line.strip()\n\t\t\tlistFromLine=line\n\n\t\t\tlistFromLine=line.split('\\t')\n\t\t\t# split('\\t')用来切割数据集中两个数字间没逗号的数据\n\t\t\t# listFromLine = line.split(',')\n\t\t\t# split(',')切割数据集中带逗号“,”的数据\n\t\t\treturnMat[index,:]=listFromLine[0:3]\n\t\t\tclassLabelVector.append(int(listFromLine[-1]))\n\t\t\tindex+=1\n\t\treturn returnMat,classLabelVector\n'''Mat[:,0]就是取矩阵Mat的所有行的第0列的元素,\n\n\tMat[:,1] 就是取所有行的第1列的元素。\n\n\tMat[:, m:n]即取矩阵Mat的所有行中的的第m到n-1列数据,含左不含右。\n\n\tMat[0,:]就是取矩阵X的第0行的所有元素,\n\n\tMat[1,:]取矩阵X的第1行的所有元素。\n'''\ndef autoNorm(dataSet):\n\tminVals=dataSet.min(0)\n\tmaxVals=dataSet.max(0)\n\tranges=maxVals-minVals\n\tnormDataSet=zeros(shape(dataSet))\n\tm=normDataSet.shape[0]\n\tnormDataSet=dataSet-tile(minVals,(m,1))\n\tnormDataSet=normDataSet/tile(ranges,(m,1))\n\treturn normDataSet,ranges,minVals\n'''\n\tb = a.min(para): \n\t当para等于0时,b是一个1*n矩阵,是矩阵a每一列的最小值组成的矩阵;\n\t当para等于1时,b是一个1*m矩阵,是矩阵a每一行的最小值组成的矩阵;\n\tmax同理!!!\n\t#将每列的最小值放在minVals中 \n minVals = dataSet.min(0) \n #将每列的最大值放在maxVals中 \n maxVals = dataSet.max(0) \n #计算可能的取值范围 \n ranges=maxVals-minVals \n #创建新的返回矩阵 \n normDataSet = zeros(shape(dataSet)) \n #得到数据集的行数 shape方法用来得到矩阵或数组的维数 \n m = dataSet.shape[0] \n #tile:numpy中的函数。tile将原来的一个数组minVals,扩充成了m行1列的数组 \n #矩阵中所有的值减去最小值 \n normDataSet = dataSet - tile(minVals,(m,1)) \n #矩阵中所有的值除以最大取值范围进行归一化 \n normDataSet = normDataSet/tile(ranges,(m,1)) \n #返回归一矩阵 取值范围 和最小值 \n return normDataSet,ranges,minVals \n '''\ndef dataClassTest(filename,hoRatio):\n\t# hoRatio=0.1\n\tdataDataMat,datingLabels=file2matrix(filename)\n\tnormMat,ranges,minVals=autoNorm(dataDataMat)\n\tm=normMat.shape[0]\n\tnumTestVecs=int(m*hoRatio)\n\terrorCount=0.0\n\tfor i in range(numTestVecs):\n\t\tclassfierResult=classfy0(normMat[i,:],normMat[numTestVecs:m,:],datingLabels[numTestVecs:m],3)\n\t\tprint(\"the classfier came back with :%d,the real answer is :%d\"%(classfierResult,datingLabels[i]))\n\t\tif (classfierResult!=datingLabels[i]):\n\t\t\terrorCount+=1\n\tprint(\"the total error rate is :%f\"%(errorCount/numTestVecs))\n\ndef classfyPerson():\n\tresultList=['not at all','in small doses','in large doses']\n\tpercentTats=float(input(\"请输入玩视频游戏所占时间百分比\"))\n\tffMiles=float(input(\"请输入每年飞行里程数:\"))\n\ticeCream=float(input(\"请输入每周消耗冰淇淋公升数\"))\n\tdataDataMat,datingLabels=file2matrix(\"H:\\IDM下载\\jqxxzsfydm_pdf\\MLiA_SourceCode\\machinelearninginaction\"\n\t\t\t\t\t\t\t\t\t\t \"\\Ch02\\datingTestSet2.txt\")\n\tnormMat,ranges,minVals=autoNorm(dataDataMat)\n\tinArr=array([ffMiles,percentTats,iceCream])\n\tclassfierResult=classfy0((inArr-minVals)/ranges,normMat,datingLabels,3)\n\tprint(\"你可能喜欢这个人的程度是:%s\"%resultList[classfierResult-1])\n\ndef img2vector(filename):\n\t#当路径下面包含\\0 \\t时,会出现错误,可以用\\\\或者/来替代前面的\\0 \\t\n\t'''一般情况下,Python解释器会将遇到的‘\\’识别为路径,会自动增加一个'\\'以便和转义字符进行区分,但若遇到转义字符则不增加‘\\’。\n例如:上述文件名将被转换为 F:\\\\eclipse_workspace\\\\machine_learning_example\\\\Ch02\\trainingDigits\\0_38.txt。因而出错。\n文件路径中若包含‘\\0’、'\\t' 等特殊转义字符时要特别注意。\n推荐文件路径写法:\nF:/eclipse_workspace/machine_learning_example/Ch02/trainningDigits/0_38.txt ,斜杠反过来了,这样就不会出现歧义了。\nF:\\\\eclipse_workspace\\\\machine_learning_example\\\\Ch02\\\\trainningDigits\\\\0_38.txt'''\n\treturnVect=zeros((1,1024))\n\twith open(filename) as f:\n\t\tfor i in range(32):\n\t\t\tlineStr=f.readline()\n\t\t\tfor j in range(32):\n\t\t\t\treturnVect[0,32*i+j]=int(lineStr[j])\n\treturn returnVect\n\ndef handwritingClassTest():\n\thwlabels=[]\n\ttrainingFileList=listdir(\"H:\\IDM下载\\jqxxzsfydm_pdf\\MLiA_SourceCode\\machinelearninginaction\\Ch02/trainingDigits\")\n\tm=len(trainingFileList)\n\ttrainingMat=zeros((m,1024))\n\tfor i in range(m):\n\t\tfileNameStr=trainingFileList[i]\n\t\tfileStr=fileNameStr.split('.')[0]\n\t\tclassNumStr=int(fileStr.split('_')[0])\n\t\thwlabels.append(classNumStr)\n\t\ttrainingMat[i,:]=img2vector('H:\\IDM下载\\jqxxzsfydm_pdf\\MLiA_SourceCode\\machinelearninginaction'\n\t\t\t\t\t\t\t '\\Ch02/trainingDigits/%s'%fileNameStr)\n\ttestFileList=listdir('H:\\IDM下载\\jqxxzsfydm_pdf\\MLiA_SourceCode\\machinelearninginaction\\Ch02/testDigits')\n\terrorCount=0.0\n\tmTest=len(testFileList)\n\tfor i in range(mTest):\n\t\tfileNameStr=testFileList[i]\n\t\tfileStr=fileNameStr.split('.')[0]\n\t\tclassNumStr=int(fileStr.split('_')[0])\n\t\tvectorUnderTest=img2vector('H:\\IDM下载\\jqxxzsfydm_pdf\\MLiA_SourceCode\\machinelearninginaction'\n\t\t\t\t\t\t\t\t '\\Ch02/testDigits/%s'%fileNameStr)\n\t\tclassfierResult=classfy0(vectorUnderTest,trainingMat,hwlabels,3)\n\t\tprint('the classfier came back with:%d ,the real answer is :%d'%(classfierResult,classNumStr))\n\t\tif classfierResult!=classNumStr:\n\t\t\terrorCount+=1\n\tprint(\"the total number of errors is : %d \"%errorCount)\n\tprint(mTest)\n\tprint(\"the total error rate is %f\"%(errorCount/float(mTest)))\n\n\nif __name__=='__main__':\n\t# group,labels=createDateSet()\n\t# print(group)\n\t# print(labels)\n\t# print(classfy0([0,0],group,labels,3))\n\tdataDataMat,datingLabels=file2matrix('H:\\IDM下载\\jqxxzsfydm_pdf\\MLiA_SourceCode\\machinelearninginaction\\Ch02\\datingTestSet2.txt')\n\tprint(dataDataMat)\n\tprint(datingLabels)\n\tfig=plt.figure()\n\tax = fig.add_subplot(111)\n\t# ax.scatter(dataDataMat[:,1],dataDataMat[:,2])\n\tax.scatter(dataDataMat[:, 0], dataDataMat[:, 1],15.0*array(datingLabels),15.0*array(datingLabels))\n\tplt.show()\n\tnormMat, ranges, minVals = autoNorm(dataDataMat)\n\tprint(normMat)\n\tprint(ranges)\n\tprint(minVals)\n'''figure()用来创建一个图的对象。\n\t\n\tadd_subplot(x,y,z) 是这么个意思:将画布划分为x行y列,图像画在从左到右从上到下的第z块。\n\t\n\tscatter() 用来画出散点。这里它接收了4个参数:\n\t\n\t(1)横轴数据。这里是dataSet[:, 0],也就是数据集的第1个特征(飞行里程数)\n\t\n\t(2)纵轴数据。这里是dataSet[:, 1],也就是数据集的第2个特征(游戏百分比)\n\t\n\t(3)每个散点的标度(scalar),从实际上看是散点的半径,或者说有多“粗”。\n\t这里是15 * array(datingLabels)。什么意思呢?每个散点对应一个标签datingLabel,要么1,要么2,要么3。\n\t把这个值乘以15,变成15,30,45,意思就是标签为1的散点的“粗度”是15,以此类推。其实就是为了在图上面好看出散点的标签。\n\t(4)每个散点的颜色。这里是array(datingLabels)。意思是不同的散点,按照他的标签(1或2或3)给他分配一种颜色。\n\t目的也是为了在图上面好看出散点的标签。\n'''\n","sub_path":"Machine_Learning/knn/kNN.py","file_name":"kNN.py","file_ext":"py","file_size_in_byte":8584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"130610761","text":"import sys\nimport numpy as np\n#import numpy.random as random\nimport scipy.io.wavfile\nimport scipy.special\nimport matplotlib.pyplot as plt\n\nMORSE_TABLE = {\n 'E': '.',\n 'T': '-',\n 'I': '..',\n 'A': '.-', \n 'N': '-.',\n 'M': '--',\n 'S': '...',\n 'U': '..-',\n 'R': '.-.',\n 'W': '.--',\n 'D': '-..',\n 'K': '-.-',\n 'G': '--.',\n 'O': '---',\n 'H': '....',\n 'V': '...-',\n 'F': '..-.',\n# ' ': '..--', \n 'L': '.-..',\n# ' ': '.-.-',\n 'P': '.--.',\n 'J': '.---', \n 'B': '-...',\n 'X': '-..-',\n 'C': '-.-.',\n 'Y': '-.--', \n 'Z': '--..',\n 'Q': '--.-',\n# ' ': '---.',\n# ' ': '----',\n '0': '-----',\n '1': '.----',\n '2': '..---',\n '3': '...--',\n '4': '....-',\n '5': '.....',\n '6': '-....',\n '7': '--...',\n '8': '---..',\n '9': '----.',\n '': '-.--.', # also as (\n '': '.-.-.', # also as +\n '': '.-...', # also as &\n '': '-.-.-',\n '=': '-...-', # also \n '/': '-..-.',\n '?': '..--..',\n ',': '--..--',\n '.': '.-.-.-',\n '': '...-.-'\n}\n\ndef cdf_chi2_1dim(x):\n ''' Cumulative probability distribution function of chi-squared distribution with 1 dimension,\n i.e. distribution of power if the amplitude is unity normal distributed.\n '''\n return scipy.special.erf(np.sqrt(x / 2 ))\n # return np.tanh(np.sqrt(x) * np.sqrt(np.pi/2) * np.log(2))\n\ndef pdf_chi2_1dim(x, scale=1):\n ''' Probability distribution function of chi-squared distribution with 1 dimension,\n i.e. distribution of power if the amplitude is unity normal distributed.\n Gamma(1/2, 2*scale)\n '''\n y = x / scale\n return np.exp(-y / 2) / np.sqrt(2 * np.pi * y)\n\ndef pdf_half_normal(x, sigma=1):\n return np.sqrt(2 / np.pi) / sigma * np.exp(-x*x / (2*sigma*sigma))\n\ndef pdf_chi2_2dim(x, scale=1):\n y = x / scale\n return np.exp(-y / 2) / 2\n\ndef pdf_rayleigh(x, sigma=1):\n return x / (sigma * sigma) * np.exp(-x*x / (2*sigma*sigma))\n\ndef pdf_normal(x, mu, sigma):\n x_norm = (x - mu) / sigma\n return np.exp( -(x_norm**2)/2 ) / sigma / np.sqrt(2*np.pi)\n\ndef goertzel_power(frame, k):\n π = np.pi\n ω = 2 * π * k / len(frame)\n coeff = 2 * np.cos(ω)\n\n sprev = 0\n sprev2 = 0\n for x_n in frame:\n s = x_n + (coeff * sprev) - sprev2\n sprev2 = sprev\n sprev = s\n\n power = (sprev2 * sprev2) + (sprev * sprev) - (coeff * sprev * sprev2)\n return power # \n # return power / len(frame) * 15\n\nclass FST:\n def __init__(self):\n self.arcs = dict()\n self.arcs_from_state_sym_in = dict()\n self.arcs_from_state_sym_out = dict()\n self.final_states = set()\n\n def add_final(self, state):\n self.final_states.add(state)\n\n def add_arc(self, state_from, state_to, sym_in, sym_out, prob):\n key = (state_from, state_to, sym_in, sym_out)\n # print(f'Arc {key} -> {prob}')\n self.arcs[key] = prob\n\n if not (state_from, sym_in) in self.arcs_from_state_sym_in:\n self.arcs_from_state_sym_in[state_from, sym_in] = list()\n self.arcs_from_state_sym_in[state_from, sym_in].append( (state_to, sym_out, prob) )\n\n if not (state_from, sym_out) in self.arcs_from_state_sym_out:\n self.arcs_from_state_sym_out[state_from, sym_out] = list()\n self.arcs_from_state_sym_out[state_from, sym_out].append( (state_to, sym_in, prob) )\n\n def translate(self, state_from, sym_in):\n if (state_from, sym_in) in self.arcs_from_state_sym_in:\n return self.arcs_from_state_sym_in[state_from, sym_in]\n else:\n return []\n\n def translate_reverse(self, state_from, sym_out):\n if (state_from, sym_out) in self.arcs_from_state_sym_out:\n return self.arcs_from_state_sym_out[state_from, sym_out]\n else:\n return []\n\nclass CWFrontend:\n def __init__(self, N, K, D):\n self.N = N\n self.K = K\n self.D = D\n # self.win = np.hamming(N)\n self.win = np.blackman(N)\n self.sigma_nse = 0.05\n self.sigma_sig = 0.2\n self.p_stat = []\n self.sig_stat = []\n self.sig_stat_norm = []\n self.noise_stat = []\n self.p_hist = [0.1, 0.1, 0.1, 0.1]\n self.last_power = 0\n self.is_mark = False\n self.counter = [0, 0]\n self.count_stats = (list(), list())\n \n def process(self, frame):\n scale = 1.0 / self.N\n frame_win = self.win * (frame) # + 0.2 * np.random.normal(size=self.N))\n power1 = scale * goertzel_power(frame_win, self.K)\n power2 = scale * goertzel_power(frame_win, self.K + 3)\n power3 = scale * goertzel_power(frame_win, self.K - 3)\n power4 = scale * goertzel_power(frame_win, self.K + 2)\n power5 = scale * goertzel_power(frame_win, self.K - 2)\n \n power1 += 0.07 * (power1 - self.last_power)\n if power1 < 1e-9: \n power1 = 1e-9\n self.last_power = power1\n\n # noise_pwr = 3.4 * min( (power1, power2, power3, power4, power5) )\n # noise_pwr = 2.7 * min( (power1, power2, power3) )\n # noise_pwr = np.mean( (power2, power3) )\n noise_pwr = np.mean( (power2, power3, power4, power5) )\n self.sigma_nse += 0.1 * (noise_pwr - self.sigma_nse)\n\n # Calculate posterior probability from two component mixture pdf\n pd_noise = pdf_half_normal(np.sqrt(power1), np.sqrt(self.sigma_nse))\n # pd_noise = pdf_chi2_1dim(power1 / self.sigma_nse, 1)\n pd_signal = pdf_rayleigh(np.sqrt(power1), np.sqrt(self.sigma_sig))\n # pd_signal = pdf_rayleigh(np.sqrt(power1) / self.sigma_sig / 1.0, 1.0)\n p = pd_signal / (pd_noise + pd_signal) # mixture weights are assumed 0.5/0.5\n\n # if power1 > 9 * self.sigma_nse:\n if p > 0.95:\n # self.sig_stat.append( power1 )\n #sigma_mle = np.sqrt( np.sum(np.power(self.sig_stat, 2)) / (2 * len(self.sig_stat)) )\n # sigma_mle = np.sqrt( np.sum(self.sig_stat) / (2 * len(self.sig_stat)) )\n self.sigma_sig += 0.1 * (power1/2 - self.sigma_sig)\n # else:\n # self.noise_stat.append( power1 / self.sigma_nse )\n\n self.p_hist.append(p)\n # p_filt = p\n # p_filt = self.p_hist[-1] * np.sqrt(self.p_hist[-2])\n p_filt = np.sqrt(self.p_hist[-1] * self.p_hist[-2]) # * self.p_hist[-4]\n # p_filt = 2*(self.p_hist[-1] - 0.5) * (self.p_hist[-2] - 0.5) + 0.5\n self.p_stat.append( p_filt )\n self.D.process(p_filt)\n\n if self.is_mark:\n if p_filt < 0.35:\n #self.count_stats[1].append(self.counter[1])\n self.is_mark = False\n self.counter[0] = 1\n else:\n self.counter[1] += 1\n else:\n if p_filt > 0.65:\n self.count_stats[0].append(self.counter[0] + np.random.normal(scale=0.5))\n self.count_stats[1].append(self.counter[1] + np.random.normal(scale=0.5))\n self.is_mark = True\n self.counter[1] = 1\n else:\n self.counter[0] += 1\n\nclass FSTDecoder:\n def __init__(self):\n self.F1 = self.create_f1()\n self.F2 = self.create_f2()\n self.F3 = self.create_f3()\n self.history = list()\n #initial_states = { 0: (0, None, '') }\n initial_states = { (0, 11, 0): (0, None, ('', '', '')) }\n self.history.append(initial_states)\n self.decoded = ''\n self.hypothesis = ''\n self.t = 0\n\n def process(self, p):\n if p < 1e-6:\n p = 1e-6\n if 1 - p < 1e-6:\n p = 1 - 1e-6\n self.t += 1\n states = self.history[-1]\n next_states = dict()\n for (sym_out, prob_sym) in (('0', np.log(1 - p)), ('1', np.log(p))):\n for state_from in states:\n prob_acc, _, _ = states[state_from]\n for (state_to, sym_in, prob_trans) in self.F1.translate_reverse(state_from[0], sym_out):\n f2_match = self.F2.translate_reverse(state_from[1], sym_in)\n # Allow epsilon:epsilon transitions\n if sym_in == '' and len(f2_match) == 0:\n f2_match = [ (state_from[1], '', 0) ]\n for (state2_to, sym2_in, prob2_trans) in f2_match:\n f3_match = self.F3.translate_reverse(state_from[2], sym2_in)\n # Allow epsilon:epsilon transitions\n if sym2_in == '' and len(f3_match) == 0:\n f3_match = [ (state_from[2], '', 0) ]\n\n for (state3_to, sym3_in, prob3_trans) in f3_match:\n prob_new = prob_acc + prob_sym + prob_trans + prob2_trans + prob3_trans\n state_new = (state_to, state2_to, state3_to)\n if state_new not in next_states or prob_new > next_states[state_new][0]:\n next_states[state_new] = (prob_new, state_from, (sym_in, sym2_in, sym3_in))\n\n idx = sorted(next_states, key=lambda x: -next_states[x][0])\n next_states = {key: next_states[key] for key in idx[:200]}\n # if idx[0] == (0, 11, 0):\n if idx[0] == (0, 0, 0):\n # if idx[0][1] == 0 and idx[0][2] == 0:\n # if idx[0][2] == 0:\n hypothesis = self.decode()\n if len(hypothesis) > len(self.hypothesis):\n self.hypothesis = hypothesis\n print(f'{self.decoded}{hypothesis}_')\n if idx[0] == (0, 11, 0):\n self.decoded += self.decode()\n self.hypothesis = ''\n self.history = list()\n # next_states = { (0, 11, 0): (0, None, ('', '', '')) }\n # pass\n self.history.append(next_states)\n\n def decode(self):\n states = self.history[-1]\n winner = max(states, key=lambda x: states[x][0])\n word_in = []\n for states in reversed(self.history):\n prob_acc, winner, sym_in = states[winner]\n word_in.append(sym_in)\n # print(''.join([x[0] for x in reversed(word_in)]))\n # print(''.join([x[1] for x in reversed(word_in)]))\n return (''.join([x[2] for x in reversed(word_in)]))\n\n def create_f1(self):\n F = FST()\n idx_state = 1\n\n def add_pdf(F, sym_in, sym_out, probs, idx_state):\n prob_sum = sum(probs)\n for length, prob in enumerate(probs):\n if prob == 0:\n continue\n if length == 0:\n F.add_arc(0, 0, sym_in, sym_out, np.log(prob / prob_sum))\n else:\n q1 = 0\n q2 = idx_state\n while length > 0:\n if q1 == 0:\n F.add_arc(q1, q2, sym_in, sym_out, np.log(prob / prob_sum))\n else:\n F.add_arc(q1, q2, '', sym_out, 0)\n idx_state += 1\n q1 = q2\n q2 = idx_state\n length -= 1\n F.add_arc(q1, 0, '', sym_out, 0)\n return idx_state\n\n idx_state = add_pdf(F, 'M', '1', [0, 1, 3, 3, 1], idx_state) # mark\n idx_state = add_pdf(F, '_', '0', [0, 1, 3, 3, 1], idx_state) # space\n F.add_final(0)\n return F\n \n def create_f2(self):\n F = FST()\n # Dot (M)\n F.add_arc(0, 1, '.', 'M', 0)\n # Dash (MMM)\n F.add_arc(0, 2, '-', 'M', 0)\n F.add_arc(2, 3, '', 'M', 0)\n F.add_arc(3, 1, '', 'M', 0)\n # Intersymbol space (_)\n F.add_arc(1, 0, '', '_', 0)\n # Intercharacter space (___)\n F.add_arc(1, 4, '|', '_', 0)\n F.add_arc(4, 5, '', '_', 0)\n F.add_arc(5, 0, '', '_', 0)\n # Interword space (_______ and longer)\n F.add_arc(1, 6, ' ', '_', 0)\n F.add_arc(6, 7, '', '_', 0)\n F.add_arc(7, 8, '', '_', 0)\n F.add_arc(8, 9, '', '_', 0)\n F.add_arc(9, 10, '', '_', 0)\n F.add_arc(10, 11, '', '_', 0)\n F.add_arc(11, 0, '', '_', 0)\n \n F.add_arc(11, 11, '', '_', 0)\n F.add_final(0)\n return F\n\n def create_f3(self):\n F = FST()\n idx_next = 2\n for sym_in in MORSE_TABLE:\n q1 = 0\n q2 = idx_next\n for sym_out in MORSE_TABLE[sym_in][:-1]:\n F.add_arc(q1, q2, '', sym_out, 0)\n idx_next += 1\n q1 = q2\n q2 = idx_next\n F.add_arc(q1, 1, sym_in, MORSE_TABLE[sym_in][-1], 0)\n\n F.add_arc(1, 0, '', '|', 0)\n F.add_arc(1, 0, ' ', ' ', 0)\n F.add_final(1)\n return F\n\nclass SlicerDecoder:\n def __init__(self, wpm=20, fps=65):\n t_unit = 1200 / wpm\n t_frame = 1000 / fps\n self.min_unit = 0.5 * t_unit / t_frame\n self.min_long = 2.0 * t_unit / t_frame\n self.min_word = 5.0 * t_unit / t_frame\n self.thr_lo = 0.35\n self.thr_hi = 0.65\n self.is_mark = False\n self.counter = [0, 0]\n self.elements = ''\n self.decoded = ''\n self.lookup = {elements: char for (char, elements) in MORSE_TABLE.items()}\n pass\n \n def process(self, p):\n if self.is_mark:\n if p < self.thr_lo:\n self.is_mark = False\n if self.counter[1] > self.min_unit:\n self.counter[0] = 1\n self.process_mark(self.counter[1])\n else:\n self.counter[1] += 1\n else:\n if p > self.thr_hi:\n self.is_mark = True\n if self.counter[0] > self.min_unit:\n self.counter[1] = 1\n self.process_space(self.counter[0])\n else:\n self.counter[0] += 1\n\n def process_mark(self, count):\n if count < self.min_long:\n self.elements += '.' # dit\n elif count < self.min_word:\n self.elements += '-' # dash\n \n def process_space(self, count):\n if count < self.min_long:\n pass # interelement space\n elif count < self.min_word:\n self.elements += '|' # intercharacter space\n else:\n self.elements += ' ' # interword space\n\n def decode(self):\n print(self.elements)\n decoded = list()\n for word in self.elements.split(' '):\n if word == '':\n continue\n word_decoded = ''\n for char in word.split('|'):\n if char in self.lookup:\n word_decoded += self.lookup[char]\n else:\n word_decoded += '_'\n pass\n decoded.append(word_decoded)\n return ' '.join(decoded)\n\ndef main():\n fs, sig = scipy.io.wavfile.read(sys.argv[1])\n sig = sig * (1/32768)\n fdet = float(sys.argv[2])\n wpm = float(sys.argv[3])\n\n t_unit = 1.2 / wpm\n samples_unit = fs * t_unit\n\n # N = 260 # Analysis frame length\n S = int(samples_unit / 3.5) # Analysis step size\n N = int(3.2*S) # Analysis frame length\n K = int(0.5 + (N * fdet / fs)) # Analysis frequency bin\n print(f'Sampling frequency: {fs}Hz')\n print(f'Detection frequency: {K*fs/N}Hz')\n\n D = FSTDecoder()\n # D = SlicerDecoder(fps=fs/S, wpm=wpm)\n frontend = CWFrontend(N, K, D)\n\n for idx in range(0, len(sig) - N, S):\n frontend.process(sig[idx:idx+N])\n\n D.decoded += D.decode()\n\n print(D.decoded)\n print()\n print(f'Sigma(signal) = {frontend.sigma_sig:.4f}')\n print(f'Sigma(noise) = {frontend.sigma_nse:.4f}')\n snr = 10 * np.log10(frontend.sigma_sig / frontend.sigma_nse)\n print(f'SNR = {snr:.1f} dB')\n\n # plt.hist(frontend.sig_stat_norm, bins=np.linspace(0, 4, 20), density=True)\n # plt.hist(-np.array(frontend.noise_stat), bins=np.linspace(-4, 0, 20), density=True)\n # x1 = np.linspace(0, 4, 100)\n # x2 = np.linspace(0.1, 4, 100)\n # y1 = [pdf_rayleigh(x_i) for x_i in x1]\n # y2 = [pdf_chi2_1dim(x_i) for x_i in x2]\n # plt.plot(x1, y1)\n # plt.plot(-x2, y2)\n # plt.plot(frontend.p_stat, marker='.')\n plt.hist(-np.array(frontend.count_stats[0]), bins=range(-30, 15))\n plt.hist(frontend.count_stats[1], bins=range(-30, 15))\n # plt.scatter(frontend.count_stats[0], frontend.count_stats[1])\n # plt.imshow(np.tile(frontend.p_stat, (200, 1)), vmin=0, vmax=1, cmap=plt.get_cmap('viridis'))\n plt.grid()\n plt.show()\n\nif __name__ == '__main__':\n main()\n sys.exit(0)\n","sub_path":"decoder.py","file_name":"decoder.py","file_ext":"py","file_size_in_byte":16748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"197503928","text":"import unittest\nfrom selenium import webdriver\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as ec\nfrom parameterized import parameterized\n\nimport HtmlTestRunner\n\n\ndef setUpModule():\n print(\"Executing begin of module\")\n\n\ndef tearDownModule():\n print(\"Executing end of module\")\n\n\nclass TestOrhmUnitTests(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n print(\"Opening application\")\n cls.driver = webdriver.Chrome()\n cls.driver.maximize_window()\n cls.driver.get(\"https://opensource-demo.orangehrmlive.com/\")\n cls.driver.find_element_by_xpath(\"//*[@id='txtUsername']\").send_keys(\"Admin\")\n cls.driver.find_element_by_xpath(\"//*[@id='txtPassword']\").send_keys(\"admin123\")\n cls.driver.find_element_by_xpath(\"//*[@id='btnLogin']\").click()\n\n @classmethod\n def tearDownClass(cls):\n print(\"Closing application and webdriver\")\n cls.driver.quit()\n\n def setUp(self):\n print(\"Main page of the application\")\n self.driver.find_element_by_id(\"menu_dashboard_index\").click()\n wait = WebDriverWait(self.driver, 20)\n wait.until(ec.visibility_of_element_located((By.TAG_NAME, \"h1\")))\n\n def test_navigate_user_page(self):\n print(\"Navigate to user search page\")\n admin = self.driver.find_element_by_id(\"menu_admin_viewAdminModule\")\n usermanagement = self.driver.find_element_by_id(\"menu_admin_UserManagement\")\n users = self.driver.find_element_by_id(\"menu_admin_viewSystemUsers\")\n\n wait = WebDriverWait(self.driver, 20)\n\n actions = ActionChains(self.driver)\n actions.move_to_element(admin).move_to_element(usermanagement).move_to_element(users).click().perform()\n\n wait.until(ec.visibility_of_element_located((By.TAG_NAME, \"h1\")))\n self.assertEqual(self.driver.find_element_by_tag_name(\"h1\").text, \"System Users\", \"Verifying navigation to users page\")\n\n @parameterized.expand([(\"robert\"), (\"hannah\"), (\"steven\")])\n def test_search_employee(self, searchQuery):\n pim = self.driver.find_element_by_id(\"menu_pim_viewPimModule\")\n employeelist = self.driver.find_element_by_id(\"menu_pim_viewEmployeeList\")\n\n actions = ActionChains(self.driver)\n actions.move_to_element(pim).move_to_element(employeelist).click().perform()\n wait = WebDriverWait(self.driver, 20)\n\n if self.driver.find_element_by_css_selector(\"table[id='resultTable']\").is_displayed():\n self.driver.find_element_by_id(\"empsearch_employee_name_empName\").click()\n self.driver.find_element_by_id(\"empsearch_employee_name_empName\").clear()\n self.driver.find_element_by_id(\"empsearch_employee_name_empName\").send_keys(searchQuery)\n self.driver.find_element_by_id(\"searchBtn\").click()\n wait.until(ec.visibility_of(self.driver.find_element_by_xpath(\"//*[@id='resultTable']/tbody\")))\n\n self.assertGreaterEqual(len(self.driver.find_element_by_xpath(\"//*[@id='resultTable']/tbody\").find_elements_by_tag_name(\"tr\")), 1, \"Count of search results\")\n\n @unittest.SkipTest\n def test_future_case(self):\n print(\"Skipped test \")\n\n @unittest.skip(\"Skipping test\")\n def test_future_case1(self):\n print(\"Skipped test \")\n\n\nif __name__ == '__main__':\n unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output='../reports/'))\n\n'''\nsuite = unittest.TestLoader().loadTestsFromTestCase(TestOrhmUnitTests)\nunittest.TextTestRunner(verbosity=2).run(suite)\n'''","sub_path":"practice/OHRMUnitTests.py","file_name":"OHRMUnitTests.py","file_ext":"py","file_size_in_byte":3653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"329656272","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n \n def addTwoNumbers(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n l1_val, l2_val = 0, 0\n \n tmp1, tmp2 = l1, l2\n \n while tmp1:\n l1_val = l1_val * 10 + tmp1.val\n tmp1 = tmp1.next\n \n while tmp2:\n l2_val = l2_val * 10 + tmp2.val\n tmp2 = tmp2.next\n\n ans_val = l1_val + l2_val\n \n headNode = tmpNode = ListNode(0)\n \n ans = list(str(ans_val))\n \n for i in ans:\n tmpNode.next = ListNode(int(i))\n tmpNode = tmpNode.next\n \n return headNode.next\n \n ","sub_path":"Algorithm/Add Two Numbers II/Add Two Numbers II.py","file_name":"Add Two Numbers II.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"225099682","text":"from .command import Command, CommandException\r\nimport numpy as np\r\n\r\n@Command.register(\"maxoutable\", \"max\", usage=\"maxoutable \")\r\nclass MaxoutableCommand(Command):\r\n def execute(self, score, level, lines):\r\n max_score = self.calculate_max_possible_score(int(score), int(level), int(lines))\r\n if max_score >= 999999:\r\n self.send_message(f\"Still maxoutable. Maximum possible score before 29 is {max_score}\")\r\n else:\r\n self.send_message(f\"Not maxoutable. Maximum possible score before 29 is {max_score}\")\r\n\r\n def calculate_max_possible_score(self, score, level, lines):\r\n next_level = np.minimum(level*10+10, np.maximum(100, level*10-50))\r\n current_level = level\r\n if lines < next_level:\r\n lines_left = next_level - lines\r\n t_left = np.ceil(lines_left/4.0)\r\n score += t_left * (1200 * (current_level + 1))\r\n lines += (t_left*4)\r\n current_level += 1\r\n else:\r\n lines_over = lines - next_level + 1\r\n extra_levels = np.ceil(lines_over/10.0)\r\n current_level += extra_levels\r\n\r\n lines = int(lines)\r\n while current_level < 29:\r\n old_linestring = str(lines)\r\n lines += 4\r\n score += (1200 * (current_level + 1))\r\n linestring = str(lines)\r\n if linestring[len(linestring)-2] != old_linestring[len(old_linestring)-2]:\r\n current_level += 1 \r\n \r\n return int(score)\r\n","sub_path":"classic_tetris_project/commands/maxoutable.py","file_name":"maxoutable.py","file_ext":"py","file_size_in_byte":1576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"651815884","text":"#!/usr/bin/env python\n\nimport gridworld as W\nimport maxent as M\nimport plot as P\nimport trajectory as T\nimport solver as S\nimport optimizer as O\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\n\ndef setup_mdp(GRID_SIZE, p_slip, avoid_states):\n \"\"\"\n Set-up our MDP/GridWorld\n \"\"\"\n # create our world\n world = W.IcyGridWorld(size=GRID_SIZE, p_slip=p_slip)\n\n # set up the reward function\n # reward = np.zeros(world.n_states)\n\n reward = np.ones(world.n_states)\n\n reward[3] = 2\n\n # Define some obstacles or avoid regions\n for s in avoid_states:\n reward[s] = 0\n\n # set up terminal states\n terminal = [3]\n # print(world.n_states)\n # print(reward)\n return world, reward, terminal\n\n\ndef generate_trajectories(world, reward, terminal):\n \"\"\"\n Generate some \"expert\" trajectories.\n \"\"\"\n # parameters\n n_trajectories = 5\n print(\"\\nNumber of experts: %d\\n\" %(n_trajectories))\n discount = 0.7\n weighting = lambda x: x**5\n\n # set up initial probabilities for trajectory generation\n initial = np.zeros(world.n_states)\n initial[12] = 1.0\n\n # generate trajectories\n value = S.value_iteration(world.p_transition, reward, discount)\n policy = S.stochastic_policy_from_value(world, value, w=weighting)\n policy_exec = T.stochastic_policy_adapter(policy)\n tjs = list(T.generate_trajectories(n_trajectories, world, policy_exec, initial, terminal))\n\n return tjs, policy\n\n\ndef maxent(world, terminal, trajectories):\n \"\"\"\n Maximum Entropy Inverse Reinforcement Learning\n \"\"\"\n # set up features: we use one feature vector per state\n features = W.state_features(world)\n\n # choose our parameter initialization strategy:\n # initialize parameters with constant\n init = O.Constant(1.0)\n\n # choose our optimization strategy:\n # we select exponentiated gradient descent with linear learning-rate decay\n optim = O.ExpSga(lr=O.linear_decay(lr0=0.2))\n\n # actually do some inverse reinforcement learning\n reward = M.irl(world.p_transition, features, terminal, trajectories, optim, init)\n\n return reward\n\n\ndef maxent_causal(world, terminal, trajectories, discount=0.7):\n \"\"\"\n Maximum Causal Entropy Inverse Reinforcement Learning\n \"\"\"\n # set up features: we use one feature vector per state\n features = W.state_features(world)\n\n # choose our parameter initialization strategy:\n # initialize parameters with constant\n init = O.Constant(1.0)\n\n # choose our optimization strategy:\n # we select exponentiated gradient descent with linear learning-rate decay\n optim = O.ExpSga(lr=O.linear_decay(lr0=0.2))\n\n # actually do some inverse reinforcement learning\n reward = M.irl_causal(world.p_transition, features, terminal, trajectories, optim, init, discount)\n\n return reward\n\ndef mce_irl(grid_size, p_slip, avoid_states):\n\n cwd = os.getcwd()\n fig_dir = \"figs\"\n if not os.path.exists(fig_dir):\n os.makedirs(fig_dir)\n \n # common style arguments for plotting\n style = {\n 'border': {'color': 'red', 'linewidth': 0.5},\n 'cmap': \"Blues\",\n }\n\n # set-up mdp\n world, reward, terminal = setup_mdp(grid_size, p_slip, avoid_states)\n\n # show our original reward\n ax = plt.figure(num='Original Reward').add_subplot(111)\n tt = P.plot_state_values(ax, world, reward, **style)\n plt.colorbar(tt)\n plt.draw()\n\n plt.savefig(os.path.join(fig_dir, \"gt_reward.png\"))\n\n\n print(\"\\nGenerating expert trajectories ...\\n\")\n # generate \"expert\" trajectories\n trajectories, expert_policy = generate_trajectories(world, reward, terminal)\n\n # show our expert policies\n ax = plt.figure(num='Expert Trajectories and Policy').add_subplot(111)\n P.plot_stochastic_policy(ax, world, expert_policy, **style)\n\n for t in trajectories:\n P.plot_trajectory(ax, world, t, lw=5, color='white', alpha=0.025)\n\n plt.draw()\n plt.savefig(os.path.join(fig_dir, \"demonstrations.png\"))\n\n\n '''\n print(\"ME-IRL ...\")\n # maximum entropy reinforcement learning (non-causal)\n reward_maxent = maxent(world, terminal, trajectories)\n\n # show the computed reward\n ax = plt.figure(num='MaxEnt Reward').add_subplot(111)\n P.plot_state_values(ax, world, reward_maxent, **style)\n plt.draw()\n '''\n\n print(\"\\nPerforming MCE-IRL ...\\n\")\n # maximum casal entropy reinforcement learning (non-causal)\n reward_maxcausal = maxent_causal(world, terminal, trajectories)\n\n # print(reward_maxcausal)\n\n # show the computed reward\n ax = plt.figure(num='MaxEnt Reward (Causal)').add_subplot(111)\n tt = P.plot_state_values(ax, world, reward_maxcausal, **style)\n plt.colorbar(tt)\n plt.draw()\n plt.savefig(os.path.join(fig_dir, \"maxent_causal_reward.png\"))\n\n print(\"\\nDone! Rewards learned\\n\")\n\n # plt.show()\n return (reward_maxcausal, world, terminal)","sub_path":"src/frozenlake_mce_irl.py","file_name":"frozenlake_mce_irl.py","file_ext":"py","file_size_in_byte":4892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"100800260","text":"import pygal\r\nfrom pygal.style import LightSolarizedStyle\r\n\r\nHEIGHT = 600\r\nWIDTH = 700\r\n\r\npoints = [((-1, 0), (1, 5), (4, 3), (2, 6), (7, 2)), ((3, 6), (5, 4), (7, 10), (9, 8),\r\n (8, 6)),\r\n ((7, 11), (9, 6), (11, 13), (13, 6))]\r\n\r\ntypes = ['A numbers', 'B numbers', 'C numbers']\r\n\r\nxy_chart = pygal.XY(height=HEIGHT, width=WIDTH, style=LightSolarizedStyle,\r\n stroke=True, show_legend=True,\r\n human_readable=True, fill=False, show_dots=True,\r\n dot_size=4)\r\nxy_chart.title = 'Points and Types'\r\nxy_chart.x_labels = map(lambda x: str(x) if not x % 3 else '', range(20))\r\nfor type, point in zip(types, points):\r\n xy_chart.add(type, point)\r\nxy_chart.render_to_file('xy_chart.svg')","sub_path":"Project 2/15.10bdaice.py","file_name":"15.10bdaice.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"479160426","text":"# ===============================================================================\n# product: WoniuTalk(服务端)\n# version: 1.3\n# author: Leo\n# updated: 02/21/2019\n#\n# 基本要求:\n# 信息的接收与发送 ==> Done\n# 多线程实现 ==> Done\n# 群聊和私聊 ==> Done\n# ===============================================================================\nimport socket\nimport threading\n\n\nclass WoniuTalkServer:\n def __init__(self, ip, port):\n # 以二维列表的���式保存所有的客户端用户姓名和连接,如下格式:\n # [ ['leo', client_user1], ['steve', client_user2], ...]\n self.clients = []\n # 服务器接收消息:\n # 1、绑定一个确定的端口地址\n # 2、启动监听端口的进程\n # 3、准备接收信息\n # 4、当有信息时,接收它\n self.server = socket.socket()\n self.server.bind((ip, port))\n self.server.listen()\n print('服务器启动成功,欢迎来撩!')\n\n def accept_client(self):\n # while死循环,用于等待建立与客户端的通道,表示可以接受无数个。\n while True:\n client_user, address = self.server.accept() # 等待新的连接通道的建立:阻塞\n welcome_msg = '[服务器回复]:欢迎来自%s的朋友,请输入您的姓名:' % str(address)\n client_user.send(welcome_msg.encode())\n user_name = client_user.recv(1024).decode()\n print('[服务器回复]:欢迎来自%s的朋友<%s>加入群聊!' % (str(address), user_name))\n\n # 将当前对话的用户名和client_user组成一个列表加入到clients列表中,构成了一个二维列表\n self.clients.append([user_name, client_user])\n\n # 群发消息给所有连接的客户端用户,告知有新用户加入\n for c in self.clients:\n c[1].send(('欢迎<%s>加入群聊!' % user_name).encode())\n\n threading.Thread(target=self.send_receive, args=(user_name, client_user, address)).start()\n\n def send_receive(self, user_name, client_user, address):\n try:\n while True:\n msg_from_client = client_user.recv(1024).decode() # 接收来自客户端的消息\n print('来自%s的朋友<%s>说:' % (str(address), user_name) + msg_from_client)\n\n # 判断是群发还是私信\n if str(msg_from_client).startswith(\"@\"):\n msg_list = msg_from_client.split('##') # 拆分消息,以空格为标识,将'@用户名'和'消息内容'存至列表\n private_name = msg_list[0][1:] # 获取用户姓名\n private_msg = msg_list[1] # 获取消息内容\n private_client = self.search_for_client(private_name)\n if private_client is not None:\n private_client.send(('<%s>悄悄地对你说:%s' % (user_name, private_msg)).encode())\n else:\n client_user.send(('您私聊的用户<%s>不存在!' % private_name).encode())\n\n else:\n msg_to_client = '<%s>说:%s' % (user_name, msg_from_client) # 往客户端连接通道发消息\n # 一旦收到一个客户端的消息,则群发\n for c in self.clients:\n c[1].send(msg_to_client.encode())\n except:\n print('好像有异常出现,服务器自行停止!')\n\n # 根据用户的昵称或姓名,找到对应的连接\n def search_for_client(self, user_name):\n for c in self.clients:\n if user_name == c[0]:\n return c[1]\n else:\n return None\n\n\nif __name__ == '__main__':\n server_ip = '19.19.19.251'\n server_port = 7777\n talk_server = WoniuTalkServer(server_ip, server_port)\n try:\n talk_server.accept_client() # 只要receive方法中有异常发生,均会进入except分支运行其代码\n except ConnectionResetError:\n print(\"好像有异常出现,服务器自行停止。\")\n","sub_path":"Seal_Pagoda/python/project/woniu_talk/server_v3.py","file_name":"server_v3.py","file_ext":"py","file_size_in_byte":4191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"270794521","text":"import random\n\nimport requests\nfrom spider.models import *\nfrom spider.runspider.zhaopin.base_zhaopin import BaseZhaoPin\n\n\nclass ZhaoPin(BaseZhaoPin):\n \"\"\"\n 连接数据库\n \"\"\"\n def __init__(self, param):\n \"\"\"\n 初始化属性\n \"\"\"\n super(ZhaoPin, self).__init__(param=param)\n self.status = param.get('status')\n self.payload = json.loads(param.get('param'))\n self.start_page = int(param.get('start_page')) if param.get('start_page') else 1\n self.access_token = ''\n\n def parse_list(self, nodes):\n \"\"\"\n 解析列表页,储存url\n :param nodes:\n :return:\n \"\"\"\n detail_list = []\n for node in nodes:\n if self.sign == 0:\n if self.status == 'on' and node['careerStatus'] == '在职':\n modifyDate = node['modifyDate']\n url = 'http://ihr.zhaopin.com/resumesearch/getresumedetial.do?access_token={}&resumeNo={}_1_1&searchresume=1&resumeSource=1&t={}&k={}'\n url = url.format(self.access_token, node['id'], node['t'], node['k'])\n detail_url = url\n detail_list.append(detail_url+';;' + modifyDate)\n if not self.status:\n modifyDate = node['modifyDate']\n url = 'http://ihr.zhaopin.com/resumesearch/getresumedetial.do?access_token={}&resumeNo={}_1_1&searchresume=1&resumeSource=1&t={}&k={}'\n url = url.format(self.access_token, node['id'], node['t'], node['k'])\n detail_url = url\n detail_list.append(detail_url + ';;' + modifyDate)\n else:\n break\n return detail_list\n\n def run(self):\n \"\"\"\n 执行\n :return:\n \"\"\"\n try:\n try:\n self.access_token = self.get_access_token()\n except Exception as E:\n print(E)\n SpiderTask.objects.change_task1_status(task_id=self.task_id)\n while True:\n self.payload['start'] = int(self.start_page) - 1\n print(\"{}当前抓取页码为:{}\".format(self.table_name,self.start_page))\n while True:\n try:\n r = requests.post('https://rdapi.zhaopin.com/rd/search/resumeList',\n headers=self.headers, data=json.dumps(self.payload), timeout=3)\n break\n except:\n continue\n data_dict = json.loads(r.content.decode())\n node_list = data_dict['data']['dataList']\n if len(node_list) != 0 and self.sign == 0:\n data_list = self.parse_list(node_list)\n SpiderData.objects.add_data_list(data_list=data_list, task_id=self.task_id)\n if self.start_page < 134 and self.sign == 0:\n self.start_page += 1\n time.sleep(3)\n else:\n break\n else:\n break\n if self.sign == 0:\n SpiderTask.objects.finish_task1(task_id=self.task_id)\n print('爬虫:{} 抓取完成'.format(self.table_name))\n else:\n print('爬虫:{} 抓取中断'.format(self.table_name))\n except Exception as E:\n print(E)\n SpiderTask.objects.change_task1_status(task_id=self.task_id)\n print('爬虫:{} 抓取中断'.format(self.table_name))\n self.update_data_count()\n\n\n\n\n\n\n\n","sub_path":"salesmindData/spider/runspider/zhaopin/zhaopin_condition.py","file_name":"zhaopin_condition.py","file_ext":"py","file_size_in_byte":3653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"327587533","text":"class Person:\n age = None\n sex = None\n name = None\n\nclass worker(Person):\n def work(self,work):\n print(\"年龄为\",self.age,\"的\",self.name,\"正在干活!\",work)\n\nclass student(Person):\n id = None\n def sing(self,sing):\n print(\"年龄为\",self.age,\"的\",self.name,\"的\",self.id,\"学生正在!\" ,sing)\n\n def study(self, study):\n print(\"年龄为\", self.age, \"的\", self.name, \"的\", self.id, \"学生正在!\", study)\n\nw = worker()\nw.name = \"张三\"\nw.age = 13\nw.sex = \"女\"\nw.work(\"监工\")\n\ns = student()\ns.name = \"李四\"\ns.age = 21\ns.sex = \"男\"\ns.id = \"1211111\"\ns.sing(\"唱歌\")\ns.study(\"学习\")","sub_path":"day11/demo/person.py","file_name":"person.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"467877021","text":"from skopt.space import Real, Categorical, Integer\nfrom skopt.utils import use_named_args\nfrom skopt import gp_minimize\nfrom skopt.plots import plot_evaluations, plot_objective, plot_convergence\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nfrom models import Model\nfrom run_model import make_model\n\n\nwith open('opt_results.txt', 'w') as f:\n f.write('Hyper OPT Results')\n\ndim_batch_size = Categorical(categories=[4, 8, 12, 24, 32], name='batch_size')\ndim_lookback = Integer(low=5, high=20, prior='uniform', name='lookback')\ndim_learning_rate = Real(low=1e-7, high=1e-3, prior='uniform', name='lr')\ndim_lstm_units = Categorical(categories=[16, 32, 64, 128], name='lstm_units')\ndim_act1_f = Categorical(categories=['relu', 'tanh', 'elu', 'LeakyRelu', 'none'], name='lstm1_act')\ndim_act2_f = Categorical(categories=['relu', 'tanh', 'elu', 'LeakyRelu', 'none'], name='lstm2_act')\n\ndefault_values = [12, 10, 0.00001, 32, 'none', 'none' ]\n\ndimensions = [dim_batch_size, dim_lookback, dim_learning_rate,\n dim_lstm_units, dim_act1_f, dim_act2_f]\n\ndef objective_fn(**kwargs):\n\n data_config, nn_config, total_intervals = make_model(**kwargs)\n\n df = pd.read_csv('data/all_data_30min.csv')\n\n model = Model(data_config=data_config,\n nn_config=nn_config,\n data=df,\n intervals=total_intervals\n )\n\n\n model.build_nn()\n\n history = model.train_nn(indices='random')\n return np.min(history.history['val_loss'])\n\n@use_named_args(dimensions=dimensions)\ndef fitness(batch_size, lookback, lr,\n lstm_units, lstm1_act, lstm2_act\n ):\n\n if lstm1_act == 'none':\n lstm1_act = None\n if lstm2_act == 'none':\n lstm2_act = None\n\n enc_config = {'n_h': lstm_units, # length of hidden state m\n 'n_s': lstm_units, # length of hidden state m\n 'm': lstm_units, # length of hidden state m\n 'enc_lstm1_act': lstm1_act,\n 'enc_lstm2_act': lstm2_act,\n }\n\n error = objective_fn(batch_size=batch_size,\n lookback=lookback,\n lr=lr,\n enc_config=enc_config,\n epochs=10)\n\n msg = \"\"\"\\nwith lstm_units {}, lstm1_act {}, lstm2_act {}, batch_size {} lookback {} lr {} val loss is {}\n \"\"\".format(lstm_units, lstm1_act, lstm2_act, batch_size, lookback, lr, error)\n print(msg)\n with open('opt_results.txt', 'a') as fp:\n fp.write(msg)\n\n return error\n\n\nsearch_result = gp_minimize(func=fitness,\n dimensions=dimensions,\n acq_func='EI', # Expected Improvement.\n n_calls=80,\n # acq_optimizer='auto',\n x0=default_values,\n random_state=10)\n\n_ = plot_evaluations(search_result)\nplt.savefig('evaluations', dpi=400, bbox_inches='tight')\nplt.show()\n\n_ = plot_objective(search_result)\nplt.savefig('objective', dpi=400, bbox_inches='tight')\nplt.show()\n\n\n_ = plot_convergence(search_result)\nplt.savefig('convergence', dpi=400, bbox_inches='tight')\nplt.show()","sub_path":"hyper_opt.py","file_name":"hyper_opt.py","file_ext":"py","file_size_in_byte":3191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"17603199","text":"from datasetviewer.fileloader.interfaces.FileLoaderPresenterInterface import FileLoaderPresenterInterface\nfrom datasetviewer.fileloader.Command import Command\nimport datasetviewer.fileloader.FileLoaderTool as FileLoaderTool\nfrom datasetviewer.mainview.interfaces.MainViewPresenterInterface import MainViewPresenterInterface\n\nclass FileLoaderPresenter(FileLoaderPresenterInterface):\n \"\"\"\n\n Presenter for overseeing the File Loading component of the interface. Receives commands from an associated\n FileLoaderView via a `notify` method. If a `FILEOPENREQUEST` signal is received then the FileLoaderPresenter\n attempts to open this file and pass the data to the MainViewPresenter.\n\n Private Attributes:\n _main_presenter (str): The MainViewPresenter object. This is set to None in the constructor and assigned with\n the `register_master` method.\n _view (FileLoaderView): The FileLoaderView that this Presenter will manage.\n\n Raises:\n ValueError: If the `file_loader_view` is None.\n\n \"\"\"\n\n def __init__(self, file_loader_view):\n\n super().__init__()\n\n if file_loader_view is None:\n raise ValueError(\"Error: Cannot create FileLoaderPresenter when View is None.\")\n\n self._main_presenter = None\n self._view = file_loader_view\n\n def register_master(self, master):\n \"\"\"\n\n Register the MainViewPresenter as the FileLoaderPresenter's master. Subscribing in the MainViewPresenter\n isn't necessary as the MainViewPresenter doesn't send instructions to the FileLoaderPresenter.\n\n Args:\n master (MainViewPresenter): An instance of a MainViewPresenter.\n\n \"\"\"\n assert (isinstance(master, MainViewPresenterInterface))\n\n self._main_presenter = master\n\n def notify(self, command):\n \"\"\"\n\n Interpret a command from the FileLoaderView and take the appropriate action.\n\n Note:\n `register_master` must be called before this method can be called.\n\n Args:\n command (Command): A Command from the FileLoaderView indicating that an event has taken place.\n\n Raises:\n ValueError: If the command isn't recognised.\n\n \"\"\"\n if command == Command.FILEOPENREQUEST:\n file_path = self._view.get_selected_file_path()[0]\n\n # Do nothing if the FileDialog was closed without a file being selected\n if not file_path:\n return\n\n try:\n dict = self._load_data(file_path)\n self._main_presenter.set_dict(dict)\n\n except (ValueError, OSError) as e:\n self._view.show_reject_file_message(str(e))\n\n else:\n raise ValueError(\"FileLoaderPresenter received an unrecognised command: {}\".format(str(command)))\n\n def _load_data(self, file_path):\n \"\"\"\n Given a file path, load this file and covert it to a data dictionary. Instructs the view to display a message\n indicating that the file could not be loaded in the case of failure.\n\n Args:\n file_path (str): The path of the file to be loaded.\n\n Returns:\n DataSet: An OrderedDict of Variables containing xarrays.\n\n Raises:\n ValueError: If the file does not exist.\n OSError: If the file exists, but does not have the appropriate format/contents and cannot be converted to\n an xarray.\n \"\"\"\n\n dict = FileLoaderTool.file_to_dict(file_path)\n return dict\n","sub_path":"datasetviewer/fileloader/FileLoaderPresenter.py","file_name":"FileLoaderPresenter.py","file_ext":"py","file_size_in_byte":3534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"460375688","text":"from core.advbase import *\nfrom module.x_alt import X_alt\n\ndef module():\n return Tobias\n\n\nclass TobiasXAlt(XAltBuff):\n def enable_x(self, enabled):\n super().enable_x(enabled)\n try:\n self.adv.a_fs_dict['default'].set_enabled(not enabled)\n self.adv.a_dodge.enabled = not enabled\n except (KeyError, AttributeError):\n pass\n\nclass Tobias(Adv):\n comment = 'c5fs, no s2, s!cleo ss after s1'\n\n conf = {}\n conf['slots.a'] = [\n 'A_Dogs_Day',\n 'Study_Rabbits',\n 'Castle_Cheer_Corps',\n 'From_Whence_He_Comes',\n 'Bellathorna'\n ]\n conf['slots.d'] = 'Freyja'\n conf['acl'] = \"\"\"\n `s1\n `s3\n `s4, fsc\n `fs, xf=5\n \"\"\"\n conf['coabs'] = ['Bow','Blade','Dagger2']\n conf['share'] = ['Dragonyule_Xainfried', 'Templar_Hope']\n\n def prerun(self):\n self.s1.autocharge_init(85)\n self.s2.charge(1) # 1 sp/s regen\n self.s2_x_alt = TobiasXAlt(group='sacred')\n self.s2_sp_buff = EffectBuff('sacred_blade', 10, lambda: self.s1.autocharge_timer.on(), lambda: self.s1.autocharge_timer.off())\n\n def s2_proc(self, e):\n if e.group == 'enhanced':\n self.s2_x_alt.on(10)\n self.s2_sp_buff.on(7)\n else:\n self.s2_x_alt.off()\n self.s2_sp_buff.off()\n self.s2.charge(1) # 1 sp/s regen\n\nif __name__ == '__main__':\n from core.simulate import test_with_argv\n test_with_argv(None, *sys.argv)","sub_path":"adv/tobias.py","file_name":"tobias.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"448854298","text":"import logging\n\nimport skrough.typing as rght\nfrom skrough.algorithms.exceptions import LoopBreak\nfrom skrough.logs import log_start_end\nfrom skrough.structs.state import ProcessingState\n\nlogger = logging.getLogger(__name__)\n\n\n@log_start_end(logger)\ndef inner_stop_hook_empty(\n state: ProcessingState, # pylint: disable=unused-argument\n elements: rght.Elements,\n) -> bool:\n return len(elements) == 0\n\n\n@log_start_end(logger)\ndef inner_stop_hook_empty_loop_break(\n state: ProcessingState, # pylint: disable=unused-argument\n elements: rght.Elements,\n) -> bool:\n if len(elements) == 0:\n raise LoopBreak()\n return False\n","sub_path":"src/skrough/algorithms/hooks/inner_stop_hooks.py","file_name":"inner_stop_hooks.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"464524485","text":"import matplotlib.pyplot as plt\nimport tensorflow as tf\n\n\ndef density2image(model, size, extent):\n grid_x = tf.linspace(start=extent[0], stop=extent[1], num=size)\n grid_y = tf.linspace(start=extent[3], stop=extent[2], num=size)\n grid_x, grid_y = tf.meshgrid(grid_x, grid_y)\n grid_x, grid_y = tf.reshape(grid_x, shape=(size, size, 1)), tf.reshape(grid_y, shape=(size, size, 1))\n grid = tf.concat([grid_x, grid_y], axis=-1)\n grid = tf.reshape(grid, shape=(size ** 2, 2))\n\n p = model(grid)\n return tf.reshape(p, shape=(size, size)).numpy()\n\n","sub_path":"_helper.py","file_name":"_helper.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"186431407","text":"\n\n\"\"\"\nKeep some default parameters for the epidemic model. \n\"\"\"\nimport numpy \nimport logging \nfrom apgl.util import Util \nfrom apgl.util import PathDefaults \nfrom apgl.graph.GraphStatistics import GraphStatistics\nfrom exp.viroscopy.model.HIVGraph import HIVGraph\nfrom exp.viroscopy.model.HIVEpidemicModel import HIVEpidemicModel\nfrom exp.viroscopy.model.HIVRates import HIVRates\nfrom exp.viroscopy.model.HIVVertices import HIVVertices\nfrom exp.viroscopy.HIVGraphReader import HIVGraphReader, CsvConverters\n\nclass HIVModelUtils(object):\n def __init__(self): \n pass \n \n @staticmethod\n def estimatedRealTheta():\n \"\"\"\n This is taken from simulated runs using the real data \n \"\"\"\n theta = numpy.array([ 500, 0.5, 0.5, 0.5, 0.2, 0.2, 500, 0.5, 0.5, 0.1, 0.1, 0.1])\n sigmaTheta = theta*2\n return theta, sigmaTheta \n \n @staticmethod\n def toyTheta(): \n theta = numpy.array([100, 0.5, 1.0, 0.5, 1.0/800, 0.01, 200, 0.1, 0.2, 38.0/1000, 30.0/1000, 170.0/1000])\n #theta = numpy.array([ 500, 0.5, 0.5, 0.5, 0.2, 0.2, 500, 0.5, 0.5, 0.1, 0.1, 0.1])\n sigmaTheta = theta*2\n return theta, sigmaTheta \n \n @staticmethod \n def toySimulationParams(loadTarget=True): \n \n if loadTarget: \n resultsDir = PathDefaults.getOutputDir() + \"viroscopy/toy/\" \n graphFile = resultsDir + \"ToyEpidemicGraph0\"\n targetGraph = HIVGraph.load(graphFile) \n \n startDate = 0.0 \n endDate = 500.0\n recordStep = 50\n M = 5000\n \n if loadTarget: \n return startDate, endDate, recordStep, M, targetGraph\n else: \n return startDate, endDate, recordStep, M\n \n @staticmethod \n def realSimulationParams(): \n hivReader = HIVGraphReader()\n targetGraph = hivReader.readSimulationHIVGraph()\n \n numRecordSteps = 10 \n #Note that 5% of the population is bi \n M = targetGraph.size * 4\n #This needs to be from 1986 to 2004 \n startDate = CsvConverters.dateConv(\"01/01/1986\")\n endDates = [CsvConverters.dateConv(\"01/01/1987\"), CsvConverters.dateConv(\"01/01/1989\"), CsvConverters.dateConv(\"01/01/1991\"), CsvConverters.dateConv(\"01/01/1993\"), CsvConverters.dateConv(\"01/01/1995\"), CsvConverters.dateConv(\"01/01/1997\")]\n endDates = [float(i) for i in endDates]\n \n return float(startDate), endDates, numRecordSteps, M, targetGraph\n \n @staticmethod \n def simulate(theta, startDate, endDate, recordStep, M, graphMetrics=None): \n undirected = True\n graph = HIVGraph(M, undirected)\n logging.debug(\"Created graph: \" + str(graph))\n \n alpha = 2\n zeroVal = 0.9\n p = Util.powerLawProbs(alpha, zeroVal)\n hiddenDegSeq = Util.randomChoice(p, graph.getNumVertices())\n \n rates = HIVRates(graph, hiddenDegSeq)\n model = HIVEpidemicModel(graph, rates, endDate, startDate, metrics=graphMetrics)\n model.setRecordStep(recordStep)\n model.setParams(theta)\n \n logging.debug(\"Theta = \" + str(theta))\n \n return model.simulate(True)\n \n @staticmethod \n def generateStatistics(graph, startDate, endDate, recordStep): \n \"\"\"\n For a given theta, simulate the epidemic, and then return a number of \n relevant statistics. \n \"\"\"\n times = [] \n removedIndices = []\n \n for t in numpy.arange(startDate, endDate+1, recordStep): \n times.append(t)\n removedIndices.append(graph.removedIndsAt(t))\n\n V = graph.getVertexList().getVertices()\n \n removedArray = numpy.array([len(x) for x in removedIndices])\n maleArray = numpy.array([numpy.sum(V[x, HIVVertices.genderIndex]==HIVVertices.male) for x in removedIndices])\n femaleArray = numpy.array([numpy.sum(V[x, HIVVertices.genderIndex]==HIVVertices.female) for x in removedIndices])\n heteroArray = numpy.array([numpy.sum(V[x, HIVVertices.orientationIndex]==HIVVertices.hetero) for x in removedIndices])\n biArray = numpy.array([numpy.sum(V[x, HIVVertices.orientationIndex]==HIVVertices.bi) for x in removedIndices])\n randDetectArray = numpy.array([numpy.sum(V[x, HIVVertices.detectionTypeIndex]==HIVVertices.randomDetect) for x in removedIndices])\n conDetectArray = numpy.array([numpy.sum(V[x, HIVVertices.detectionTypeIndex]==HIVVertices.contactTrace) for x in removedIndices])\n \n vertexArray = numpy.c_[removedArray, maleArray, femaleArray, heteroArray, biArray, randDetectArray, conDetectArray]\n \n graphStats = GraphStatistics()\n removedGraphStats = graphStats.sequenceScalarStats(graph, removedIndices, slowStats=False)\n \n return times, vertexArray, removedGraphStats\n \n toyTestPeriod = 250 \n realTestPeriods = [365, 365, 365, 730]","sub_path":"exp/viroscopy/model/HIVModelUtils.py","file_name":"HIVModelUtils.py","file_ext":"py","file_size_in_byte":4952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"617346386","text":"#!/usr/bin/env python\r\n\r\n\r\n\r\nimport os\r\n\r\nimport py_compile\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nos.system(\"apt-get install figlet\")\r\n\r\n\r\n\r\nos.system(\"clear\")\r\n\r\n\r\n\r\nos.system(\"figlet Compiler\")\r\n\r\n\r\n\r\n\r\n\r\nprint(\"\"\"\r\n\r\ncompiler started..\r\n\r\n\r\n\r\n\"\"\")\r\n\r\n\r\n\r\n\r\n\r\ncompil=input(\"name of program----->\")\r\n\r\n\t\r\n\r\npy_compile.compile(compil)","sub_path":"derleme.py","file_name":"derleme.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"302808922","text":"# Importing important libraries\nimport csv\nimport numpy as np\nimport statistics as stats\nimport keras\nfrom keras import backend as k\nfrom keras.models import Sequential\nfrom keras.layers import Activation\nfrom keras.layers.core import Dense\nfrom keras.optimizers import Adam\nfrom keras.metrics import categorical_crossentropy\n\n# Declearing lists to store data\ndata_list = [] \ndata_label = []\n\n# Reading csv File\nwith open(\"train.csv\") as csvfile:\n\tprint(\"Loading Data...\")\n\treadCsv = csv.reader(csvfile, delimiter=',')\n\t# Storing Data\n\tnext(readCsv)\n\tfor rows in readCsv:\n\t\tdata_label.append(float(rows[0]))\n\t\tdata_list.append(list(map(float, rows[1:])))\t\t\nprint(\"Done\")\n# Declaring necessary Variables\nn = len(data_label)\ntrainDataLen = int(0.8*n)\n\n#Declaring X and y\nXtrain = np.array(data_list)\nytrain = np.array(data_label)\nprint(Xtrain.shape)\nprint(ytrain.shape)\nprint(Xtrain.shape)\nprint(Xtrain.shape)\n\n# Training\n\nmodel = Sequential([\n\tDense(16, input_shape=(784,), activation='relu'),\n\tDense(32, activation='relu'),\n\tDense(10, activation='softmax')\n\t])\n\nmodel.compile(Adam(lr=.0001), loss='sparse_categorical_crossentropy', metrics=['accuracy'])\nmodel.fit(Xtrain, ytrain, batch_size=5, epochs=25, shuffle=True, verbose=2, validation_split = 0.2)\n","sub_path":"mnist/mnist/keras_sol.py","file_name":"keras_sol.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"259550738","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os, sys, json, random\nfrom collections import Counter\nfrom tqdm import tqdm\nfrom loguru import logger\nfrom pathlib import Path\n\nfrom transformers.optimization import AdamW, get_linear_schedule_with_warmup\n\nimport sys\nsys.path.append('../../')\n\nfrom theta.utils import init_theta, seg_generator\n# from theta.modeling.trainer import get_default_optimizer_parameters\nfrom theta.modeling.ner import init_labels, load_model, InputExample, examples_to_dataset, load_examples_from_bios_file, NerTrainer\n\nner_labels = []\nseg_len = 510\nseg_backoff = 32\nfold = 2\n\n# -------------------- Data --------------------\ntrain_base_file = \"../../../../competitions/CCKS2020/event_element/data/event_element_train_data_label.txt\"\ntest_base_file = \"../../../../competitions/CCKS2020/event_element/data/event_element_dev_data.txt\"\n\nall_event_elements = {\n \"破产清算\": [\"公司名称\", \"受理法院\", \"裁定时间\", \"公告时间\", \"公司行业\"],\n \"重大安全事故\": [\"公司名称\", \"公告时间\", \"伤亡人数\", \"其他影响\", \"损失金额\"],\n \"股东增持\": [\"增持的股东\", \"增持金额\", \"增持开始日期\"],\n \"股东减持\": [\"减持的股东\", \"减持金额\", \"减持开始日期\"],\n \"股权质押\": [\"质押方\", \"接收方\", \"质押开始日期\", \"质押结束日期\", \"质押金额\"],\n \"股权冻结\": [\"被冻结股东\", \"冻结开始日期\", \"冻结结束日期\", \"冻结金额\"],\n \"高层死亡\": [\"公司名称\", \"高层人员\", \"高层职务\", \"死亡/失联时间\", \"死亡年龄\"],\n \"重大资产损失\": [\"公司名称\", \"损失金额\", \"其他损失\", \"公告时间\"],\n \"重大对外赔付\": [\"公司名称\", \"赔付对象\", \"赔付金额\", \"公告时间\"]\n}\n\nevent_elements = all_event_elements\n\n# merged_results_best_0.74917.txt\n# 2020年5月17日 16:00\n\n# 0.749170977583234\n# {\n# '整体': 'P:0.733126, R:0.765934, F1:0.749171',\n#\n# '破产清算': 'P:0.937294, R:0.901587, F1:0.919094',\n# '重大安全事故': 'P:0.922131, R:0.922131, F1:0.922131',\n# '股东减持': 'P:0.578629, R:0.784153, F1:0.665893',\n# '股权质押': 'P:0.767188, R:0.756549, F1:0.761831',\n# '股东增持': 'P:0.598967, R:0.682353, F1:0.637947',\n# '股权冻结': 'P:0.728033, R:0.557692, F1:0.631579',\n# '高层死亡': 'P:0.969789, R:0.978659, F1:0.974203',\n# '重大资产损失': 'P:0.860465, R:0.852535, F1:0.856481',\n# '重大对外赔付': 'P:0.705882, R:0.705882, F1:0.705882'\n# }\n\n# fixed_event_element_submission_roberta_2e-5_512_4_10_old_crf_no_loss_by_ncrfpp.txt\n# 2020年5月16日 18:20\n# 0.741167023554604\n# {\n# '整体': 'P:0.731572, R:0.751017, F1:0.741167', # Top\n#\n# '破产清算': 'P:0.937294, R:0.901587, F1:0.919094', # Top\n# '重大安全事故': 'P:0.915323, R:0.930328, F1:0.922764', # Top\n# '股东减持': 'P:0.579449, R:0.747268, F1:0.652745',\n# '股权质押': 'P:0.735878, R:0.742681, F1:0.739264',\n# '股东增持': 'P:0.598967, R:0.682353, F1:0.637947', # Top\n# '股权冻结': 'P:0.745011, R:0.538462, F1:0.625116',\n# '高层死亡': 'P:0.957704, R:0.966463, F1:0.962064',\n# '重大资产损失': 'P:0.860465, R:0.852535, F1:0.856481', # Top\n# '重大对外赔付': 'P:0.754386, R:0.632353, F1:0.688000'\n# }\n\n# fixed_event_element_submission_roberta_2e-5_512_4_10_old_crf_noloss.txt\n# 2020年5月15日 21:02\n# 0.726913970007893\n# {\n# '整体': 'P:0.705747,R:0.7493897477624084,F1:0.7269139700078927',\n#\n# '破产清算': 'P:0.917219, R:0.879365, F1:0.897893',\n# '重大安全事故': 'P:0.912863, R:0.901639, F1:0.907216',\n# '股东减持': 'P:0.581590, R:0.759563, F1:0.658768',\n# '股权质押': 'P:0.767188, R:0.756549, F1:0.761831', # Top\n# '股东增持': 'P:0.527301, R:0.662745, F1:0.587315',\n# '股权冻结': 'P:0.632381, R:0.532051, F1:0.577894',\n# '高层死亡': 'P:0.960725, R:0.969512, F1:0.965099',\n# '重大资产损失': 'P:0.869159, R:0.857143, F1:0.863109',\n# '重大对外赔付': 'P:0.692308, R:0.661765, F1:0.676692'\n# }\n\n# fixed_event_element_submission_merge_last_gqzy.txt\n# 2020年5月7日 17:18\n# 0.732050431320504\n# {\n# '整体': 'P:0.716736, R:0.748034, F1:0.732050',\n#\n# '破产清算': 'P:0.910596, R:0.873016, F1:0.891410',\n# '重大安全事故': 'P:0.894737, R:0.905738, F1:0.900204',\n# '股东减持': 'P:0.563008, R:0.756831, F1:0.645688',\n# '股权质押': 'P:0.703216, R:0.741140, F1:0.721680',\n# '股东增持': 'P:0.606440, R:0.664706, F1:0.634238',\n# '股权冻结': 'P:0.728033, R:0.557692, F1:0.631579', # Top\n# '高层死亡': 'P:0.972561, R:0.972561, F1:0.972561',\n# '重大资产损失': 'P:0.854369, R:0.811060, F1:0.832151',\n# '重大对外赔付': 'P:0.750000, R:0.661765, F1:0.703125'\n# }\n\n# fixed_event_element_submission_roberta_2e-5_512_4_10_ncrfpp_no_loss.txt\n# 2020年5月15日 20:56\n# 0.731642544150843\n# {\n# '整体': 'P:0.716701, R:0.747220, F1:0.731643',\n#\n# '破产清算': 'P:0.909385, R:0.892063, F1:0.900641',\n# '重大安全事故': 'P:0.903361, R:0.881148, F1:0.892116',\n# '股东减持': 'P:0.568856, R:0.733607, F1:0.640811',\n# '股权质押': 'P:0.697101, R:0.741140, F1:0.718447',\n# '股东增持': 'P:0.587940, R:0.688235, F1:0.634146',\n# '股权冻结': 'P:0.741304, R:0.546474, F1:0.629151',\n# '高层死亡': 'P:0.969789, R:0.978659, F1:0.974203', # Top\n# '重大资产损失': 'P:0.869565, R:0.829493, F1:0.849057',\n# '重大对外赔付': 'P:0.705882, R:0.705882, F1:0.705882' # Top\n# }\n\n# fixed_event_element_submission_roberta_2e-5_512_4_10_new_crf_noloss.txt\n# 2020年5月14日 22:15\n# 0.728845130388505\n# fixed_event_element_submission_roberta_2e-5_512_4_10_new_crf_noloss_fix_zdaqsg.txt\n# 2020年5月15日 00:34 股东减持 'P:0.578629, R:0.784153, F1:0.665893'\n# 0.728459182314556\n# {\n# '整体': 'P:0.715330, R:0.742880, F1:0.728845',\n#\n# '破产清算': 'P:0.889968, R:0.873016, F1:0.881410',\n# '重大安全事故': 'P:0.878151, R:0.856557, F1:0.867220',\n# '股东减持': 'P:0.575727, R:0.784153, F1:0.663968', # Top\n# '股权质押': 'P:0.707281, R:0.733436, F1:0.720121',\n# '股东增持': 'P:0.598182, R:0.645098, F1:0.620755',\n# '股权冻结': 'P:0.737418, R:0.540064, F1:0.623497',\n# '高层死亡': 'P:0.961078, R:0.978659, F1:0.969789',\n# '重大资产损失': 'P:0.829384, R:0.806452, F1:0.817757',\n# '重大对外赔付': 'P:0.716666, R:0.632353, F1:0.671875'\n# }\n\n\ndef get_top_list(json_file, event_types):\n top_list = {}\n with open(json_file, 'r') as fr:\n lines = fr.readlines()\n for line in lines:\n line = line.strip()\n json_d = json.loads(line)\n events = json_d['events']\n if events:\n master_event_type = get_master_event_type(events)\n if master_event_type in event_types:\n top_list[json_d['doc_id']] = line\n return top_list\n\n\ndef merge_all_tops():\n\n candidates = [\n (\"fixed_event_element_submission_roberta_2e-5_512_4_10_old_crf_no_loss_by_ncrfpp.txt\",\n ['破产清算', '重大安全事故', '股东增持', '重大资产损失']),\n (\"fixed_event_element_submission_merge_last_gqzy.txt\", ['股权冻结']),\n (\"fixed_event_element_submission_roberta_2e-5_512_4_10_old_crf_noloss.txt\",\n ['股权质押']),\n (\"fixed_event_element_submission_roberta_2e-5_512_4_10_ncrfpp_no_loss.txt\",\n ['高层死亡', '重大对外赔付']),\n (\"fixed_event_element_submission_roberta_2e-5_512_4_10_new_crf_noloss_fix_zdaqsg.txt\",\n ['股东减持']),\n ]\n\n final_lines = []\n\n final_top_list = {}\n for json_file, event_types in candidates[1:]:\n top_list = get_top_list(json_file, event_types)\n final_top_list.update(top_list)\n\n with open(candidates[0][0], 'r') as fr:\n lines = fr.readlines()\n\n merged_result_file = \"merged_results.txt\"\n with open(merged_result_file, 'w') as wr:\n for line in lines:\n line = line.strip()\n json_d = json.loads(line)\n doc_id = json_d['doc_id']\n if doc_id in final_top_list:\n line = final_top_list[doc_id]\n wr.write(f\"{line}\\n\")\n\n logger.info(f\"Merged result saved to {merged_result_file}\")\n\n\ndef get_result_file(args):\n return f\"{args.output_dir}/event_element_result.json\"\n\n\ndef get_submission_file(args):\n return f\"{args.output_dir}/event_element_submission.json\"\n\n\n# def seg_generator(iterables, seg_len, seg_backoff=0):\n# if seg_len <= 0:\n# yield iterables\n# else:\n# # 确保iterables列表中每一项的条目数相同\n# assert sum([len(x)\n# for x in iterables]) == len(iterables[0]) * len(iterables)\n# n_segs = len(iterables[0]) // seg_len\n# for i in range(n_segs + 1):\n# s0 = seg_len * i\n# s1 = seg_len * (i + 1) if i < n_segs - 1 else len(iterables[0])\n# if s0 < s1:\n# segs = [x[s0:s1] for x in iterables]\n# yield segs\n# # raise StopIteration\n\n\ndef load_train_eval_examples(train_base_file):\n label2id = {}\n id2label = {}\n train_base_examples = []\n with open(train_base_file, 'r') as fr:\n lines = fr.readlines()\n for line in tqdm(lines, desc=f\"train & eval\"):\n d = json.loads(line)\n guid = d['doc_id']\n text = d['content']\n words = [w for w in text]\n labels = ['O'] * len(words)\n for e in d['events']:\n event_type = e['event_type']\n # if event_type not in ['破产清算']: # ['股东减持', '股东增持']:\n # continue\n for k, v in e.items():\n if not v:\n continue\n\n if k not in ['event_id', 'event_type']:\n label = '_'.join((event_type, k))\n if label not in label2id:\n n = len(label2id) + 1\n label2id[label] = n\n id2label[n] = label\n ner_labels.append(label)\n n = label2id[label]\n i0 = text.find(v)\n while i0 >= 0:\n # if i0 >= 0:\n if len(v) == 1:\n # if labels[i0] == 'O':\n # labels[i0] = f\"S-{label}\"\n pass\n else:\n labels[i0] = f\"B-{label}\"\n for j0 in range(1, len(v)):\n labels[i0 + j0] = f\"I-{label}\"\n i0 = text.find(v, i0 + 1)\n\n for seg_words, seg_labels in seg_generator((words, labels),\n seg_len, seg_backoff):\n train_base_examples.append(\n InputExample(guid=guid,\n text_a=seg_words,\n labels=seg_labels))\n\n # if seg_len > 0:\n # n_segs = len(text) // seg_len\n # for i in range(n_segs + 1):\n # s0 = seg_len * i\n # s1 = seg_len * (i + 1) if i < n_segs - 1 else len(text)\n # if s0 < s1:\n # seg_text = text[s0:s1]\n # seg_words = words[s0:s1]\n # seg_labels = labels[s0:s1]\n #\n # train_base_examples.append(\n # InputExample(guid=guid,\n # text_a=seg_words,\n # labels=seg_labels))\n # else:\n # train_base_examples.append(\n # InputExample(guid=guid, text_a=words, labels=labels))\n # train_base_examples = train_base_examples[:100]\n\n random.shuffle(train_base_examples)\n train_rate = 0.9\n\n num_eval_examples = int(len(train_base_examples) * (1 - train_rate))\n num_train_samples = len(train_base_examples) - num_eval_examples\n\n if fold == 0:\n eval_examples = train_base_examples[num_train_samples:]\n train_examples = train_base_examples[:num_train_samples]\n else:\n s = num_eval_examples * (fold - 1)\n e = num_eval_examples * fold\n eval_examples = train_base_examples[s:e]\n train_examples = train_base_examples[:s] + train_base_examples[e:]\n logger.info(\n f\"Loaded {len(train_examples)} train examples, {len(eval_examples)} eval examples.\"\n )\n return train_examples, eval_examples\n\n\ndef load_test_examples(test_base_file):\n with open(test_base_file, 'r') as fr:\n\n test_examples = []\n lines = fr.readlines()\n for line in tqdm(lines, desc=f\"test\"):\n d = json.loads(line)\n guid = d['doc_id']\n words = [w for w in d['content']]\n\n for seg_words, in seg_generator((words, ), seg_len, seg_backoff):\n test_examples.append(\n InputExample(guid=guid, text_a=seg_words, labels=None))\n\n logger.info(f\"Loaded {len(test_examples)} test examples.\")\n return test_examples\n\n\ntrain_examples, eval_examples = load_train_eval_examples(train_base_file)\ntest_examples = load_test_examples(test_base_file)\n\nlogger.info(f\"ner_labels: {ner_labels}\")\n# -------------------- Model --------------------\n\n# def load_model(args):\n# model = load_pretrained_model(args)\n# model.to(args.device)\n# return model\n#\n\n# def build_model(args):\n# # -------- model --------\n# model = load_pretrained_model(args)\n# model.to(args.device)\n#\n# # -------- optimizer --------\n# optimizer_parameters = get_default_optimizer_parameters(\n# model, args.weight_decay)\n# optimizer = AdamW(optimizer_parameters,\n# lr=args.learning_rate,\n# correct_bias=False)\n#\n# # -------- scheduler --------\n# scheduler = get_linear_schedule_with_warmup(\n# optimizer,\n# num_warmup_steps=args.total_steps * args.warmup_rate,\n# num_training_steps=args.total_steps)\n#\n# return model, optimizer, scheduler\n\n# -------------------- Trainer --------------------\n\n\nclass Trainer(NerTrainer):\n def __init__(self, args):\n super(Trainer, self).__init__(args, build_model=None)\n\n # def build_model(self, args):\n # return build_model(args)\n\n # def on_predict_end(self, args, test_dataset):\n # super(Trainer, self).on_predict_end(args, test_dataset)\n #\n # test_pred_crf_file = Path(args.output_dir) / \"test_pred_crf.json\"\n # logger.info(f\"Write pred_results to {test_pred_crf_file}\")\n # with open(test_pred_crf_file, \"w\") as fwriter:\n # for i, json_d in enumerate(self.pred_results):\n # json_line = json.dumps(json_d, ensure_ascii=False)\n #\n # if i < len(self.pred_results) - 1:\n # json_line += \",\\n\"\n # else:\n # json_line += \"\\n\"\n #\n # fwriter.write(json_line)\n\n\ndef save_predict_results(args, pred_results, pred_results_file, test_examples):\n test_results = {}\n for json_d, example in tqdm(zip(pred_results, test_examples)):\n guid = example.guid\n text = ''.join(example.text_a)\n\n if guid not in test_results:\n test_results[guid] = {\n \"guid\": guid,\n \"content\": \"\",\n \"events\": [],\n \"tagged_text\": \"\"\n }\n\n s0 = 0\n tagged_text = test_results[guid]['tagged_text']\n text_offset = len(test_results[guid]['content'])\n for entity in json_d['entities']:\n event_type = entity[0]\n s = entity[1]\n e = entity[2] + 1\n entity_text = text[s:e]\n test_results[guid]['events'].append(\n (event_type, entity_text, text_offset + s, text_offset + e))\n\n tagged_text += f\"{text[s0:s]}\\n\"\n tagged_text += f\"【{event_type} | {entity_text}】\\n\"\n s0 = e\n\n tagged_text += f\"{text[s0:]}\\n\"\n test_results[guid]['tagged_text'] = tagged_text\n test_results[guid]['content'] += text\n\n json.dump(test_results,\n open(f\"{pred_results_file}\", 'w'),\n ensure_ascii=False,\n indent=2)\n\n\ndef export_bios_file(examples, bios_file):\n fw_bios = open(bios_file, 'w')\n for example in tqdm(examples):\n # for test examples\n labels = example.labels\n if labels is None:\n labels = ['O'] * len(example.text_a)\n\n for w, t in zip(example.text_a, labels):\n fw_bios.write(f\"{w} {t}\\n\")\n fw_bios.write(\"\\n\")\n logger.info(f\"export {len(examples)} examples to {bios_file}\")\n\n\ndef eda(args):\n export_bios_file(train_examples, args.train_file)\n export_bios_file(eval_examples, args.eval_file)\n export_bios_file(test_examples, args.test_file)\n\n\ndef get_event_role(event):\n for role, value in event.items():\n if role == 'event_type':\n continue\n break\n return role, value\n\n\n# 获得事件主体字段名\ndef get_event_subject_field(event_type):\n elements = event_elements[event_type]\n subject_field = elements[0]\n return subject_field\n\n\n# 获得事件集合的主事件类型\ndef get_master_event_type(events):\n event_types = [event['event_type'] for event in events]\n\n # # 查找第一个(出现最多?)的事件主字段的类型\n # for event in events:\n # event_type = event['event_type']\n # subject_field = get_event_subject_field(event_type)\n # role, value = get_event_role(event)\n # if role == subject_field:\n # return event_type\n\n # 查找出现最多次数的事件类型为主事件类型\n if event_types:\n c = Counter(event_types)\n master_event_type = c.most_common(1)[0][0]\n else:\n master_event_type = None\n return master_event_type\n\n\n# 保持事件集合的事件的完整性\n# 1. 只保留一个主事件类型\n# 2. 补充缺失的事件主体\n# 3. 补充公告时间\n\nannouncement_events = ['破产清算', '重大安全事故', '重大资产损失', '重大对外赔付']\n\n\ndef keep_events_completeness(events):\n new_events = []\n\n if events:\n master_event_type = get_master_event_type(events)\n subject_field = get_event_subject_field(master_event_type)\n\n has_no_subject = False\n subject0 = None\n for event in events:\n if event['event_type'] != master_event_type:\n continue\n if subject_field in event:\n subject0 = event[subject_field]\n else:\n if subject0:\n event[subject_field] = subject0\n else:\n has_no_subject = True\n new_events.append(event)\n\n if has_no_subject and subject0:\n for event in new_events:\n if subject_field not in event:\n event[subject_field] = subject0\n return new_events\n\n\n# 尝试将event0合并到event\n# 返回合并成功修改后的event,\n# 不可合并则返回None\ndef try_merge_last(event0, event):\n new_event = None\n if event0['event_type'] == event['event_type']:\n # 先检查两个事件相同key的值是否不同\n same_keys = [k for k in event0.keys() if k in event.keys()]\n if sum([event0[k] != event[k] for k in same_keys]) > 0:\n return None\n diff_keys = [k for k in event0.keys() if k not in event.keys()]\n new_event = event\n if diff_keys:\n for k in diff_keys:\n new_event[k] = event0[k]\n return new_event\n\n\n# 合并事件last\ndef merge_events_last(events):\n\n done = False\n final_events = []\n\n if not events:\n return done, final_events\n\n master_event_type = get_master_event_type(events)\n if master_event_type not in [\"股权质押\"]:\n return done, final_events\n\n for event0 in events:\n found = False\n # for i, event in enumerate(final_events):\n # event = final_events[i]\n # for i in range(len(final_events) - 1, -1, -1):\n if final_events:\n event = final_events[-1]\n new_event = try_merge_last(event0, event)\n if new_event:\n found = True\n final_events[-1] = new_event\n # final_events[i] = new_event\n # break\n if not found:\n final_events.append(event0)\n\n return True, final_events\n\n\n# 尝试将event0合并到event\n# 返回合并成功修改后的event,\n# 不可合并则返回None\ndef try_merge(event0, event):\n new_event = None\n if event0['event_type'] == event['event_type']:\n # 先检查两个事件相同key的值是否不同\n same_keys = [k for k in event0.keys() if k in event.keys()]\n if sum([event0[k] != event[k] for k in same_keys]) > 0:\n return None\n diff_keys = [k for k in event0.keys() if k not in event.keys()]\n new_event = event\n if diff_keys:\n for k in diff_keys:\n new_event[k] = event0[k]\n return new_event\n\n\n# 合并事件\ndef merge_events(events):\n\n final_events = []\n for event0 in events:\n found = False\n for i, event in enumerate(final_events):\n event = final_events[i]\n new_event = try_merge(event0, event)\n if new_event:\n found = True\n final_events[i] = new_event\n break\n if not found:\n final_events.append(event0)\n return final_events\n\n\n# 假设事件要素按出现顺序展开,出现事件主体(event_elements列表中第一个元素)时,\n# 结束上一事件。展开中的事件若只有主体,则抛弃。\n# 事件要素重复时出现时,新建事件并延续事件主体。\ndef merge_events_by_subject(events):\n\n final_events = []\n event_type0 = None\n subject_field0 = None\n subject_value0 = None\n current_event = {}\n\n def append_current_event():\n if current_event and subject_value0 is not None:\n # if subject_value0 is not None:\n # current_event['event_type'] = event_type0\n # current_event[subject_field0] = subject_value0\n new_event = {\n 'event_type': event_type0,\n subject_field0: subject_value0\n }\n new_event.update(current_event)\n final_events.append(new_event)\n\n done = False\n if events:\n # event_types = [event['event_type'] for event in events]\n # c = Counter(event_types)\n # master_event_type = c.most_common(1)[0][0]\n master_event_type = get_master_event_type(events)\n\n # logger.debug(f\"{master_event_type}\")\n if master_event_type in [\"股东减持\"]:\n for event in events:\n event_type = event['event_type']\n # elements = event_elements[event_type]\n # subject_field = elements[0]\n subject_field = get_event_subject_field(event_type)\n if event_type != event_type0:\n # TODO\n append_current_event()\n # if current_event:\n # current_event['event_type'] = event_type0\n # current_event[subject_field0] = subject_value0\n # final_events.append(current_event)\n event_type0 = event_type\n current_event = {}\n subject_field0 = subject_field\n subject_value0 = None\n\n # for role, value in event.items():\n # if role == 'event_type':\n # continue\n # break\n role, value = get_event_role(event)\n if role == subject_field:\n append_current_event()\n # if current_event:\n # current_event['event_type'] = event_type0\n # current_event[subject_field0] = subject_value0\n # final_events.append(current_event)\n\n current_event = {}\n subject_value0 = value\n\n else:\n if role not in current_event.keys():\n current_event[role] = value\n else:\n append_current_event()\n # if current_event:\n # current_event['event_type'] = event_type0\n # current_event[subject_field0] = subject_value0\n # final_events.append(current_event)\n current_event = {}\n current_event[role] = value\n\n append_current_event()\n # if current_event:\n # current_event['event_type'] = event_type0\n # current_event[subject_field0] = subject_value0\n # final_events.append(current_event)\n done = True\n\n return done, final_events\n\n\ndef process_only_once_events(events):\n final_events = []\n\n done = False\n if events:\n event_types = [event['event_type'] for event in events]\n c = Counter(event_types)\n master_event_type = c.most_common(1)[0][0]\n\n # logger.debug(f\"{master_event_type}\")\n if master_event_type in [\"破产清算\", \"重大安全事故\", \"高层死亡\", \"重大资产损失\", \"重大对外赔付\"]:\n elements = event_elements[master_event_type]\n\n the_only_event = {}\n the_only_event['event_type'] = master_event_type\n for role in elements:\n values = []\n for event in events:\n if role in event:\n values.append(event[role])\n if len(values) > 0:\n c1 = Counter(values)\n value = c1.most_common(1)[0][0]\n the_only_event[role] = value\n final_events = [the_only_event]\n done = True\n return done, final_events\n\n\ndef analysis_report(report):\n guid = report['guid']\n\n events = []\n for event in report['events']:\n event_label = event[0]\n event_value = event[1]\n s = event[2]\n e = event[3]\n\n tokens = event_label.split('_')\n assert len(tokens) >= 2\n event_type = tokens[0]\n event_role = \"\".join(tokens[1:])\n events.append({'event_type': event_type, event_role: event_value})\n\n # online: 0.68423\n # final_events = merge_events(events)\n\n # online: 0.69393\n done, final_events = process_only_once_events(events)\n if not done:\n done, final_events = merge_events_by_subject(events)\n if not done:\n done, final_events = merge_events_last(events)\n if not done:\n final_events = merge_events(events)\n\n final_events = keep_events_completeness(final_events)\n\n result = {'doc_id': guid, 'events': final_events}\n return result\n\n\ndef fix_results_file(args):\n \"\"\"\n 只出现两个相同类型的事件,保留较多项事件,并添加较少项事件中新出现的项。\n 整 体: P: 0.71483 -> 0.74525 R: 0.55818 -> 0.54272 F1: 0.62687 -> 0.62806\n\n 破产清算: P: 0.76000 -> 0.80967 R: 0.84444 -> 0.85079 F1: 0.80000 -> 0.82972\n\n 重大安全事故: P: 0.80816 -> 0.82500 R: 0.81148 -> 0.81148 F1: 0.80982 -> 0.81818\n 高层死亡 : P: 0.95224 -> 0.95796 R: 0.97256 -> 0.97256 F1: 0.96229 -> 0.96520\n\n\n 重大对外赔付: P: 0.59677 -> 0.66071 R: 0.54412 -> 0.54118 F1: 0.56923 -> 0.59677\n 重大资产损失: P: 0.65779 -> 0.70661 R: 0.79724 -> 0.78802 F1: 0.72083 -> 0.74510\n\n 股权冻结 : P: 0.74797 -> 0.78042 R: 0.44231 -> 0.42147 F1: 0.55589 -> 0.54735\n 股权质押 : P: 0.80612 -> 0.83241 R: 0.48690 -> 0.46687 F1: 0.60711 -> 0.59822\n 股东增持 : P: 0.54664 -> 0.56738 R: 0.49412 -> 0.47059 F1: 0.51905 -> 0.51447\n 股东减持 : P: 0.54975 -> 0.56267 R: 0.30191 -> 0.27596 F1: 0.38977 -> 0.37030\n\n\n \"\"\"\n results_file = args.results_file\n\n # donot_fixes = ['股权冻结', '股权质押', '股东增持', '股东减持']\n donot_fixes = ['股东减持', '股权质押']\n # donot_fixes = []\n\n # with open(dev_base_file, 'r') as f:\n # dev_lines = f.readlines()\n\n fixed_results_file = f\"fixed_{os.path.basename(results_file)}\"\n fw = open(fixed_results_file, 'w')\n\n num_dup = 0\n with open(results_file, 'r') as f:\n lines = f.readlines()\n for i, z in enumerate(tqdm(lines, desc='Load')):\n z = json.loads(z)\n events = z['events']\n\n # 只保留超过项目数据大于2的事件\n # events = [e for e in events if len(e) > 3]\n\n # text = dev_lines[i] #z['content']\n # logger.info(text)\n\n # new_events = []\n # for e in events:\n # # logger.info(f\"{e}\")\n # if e['event_type'] == '股东减持':\n # if '减持' not in text:\n # continue\n # elif e['event_type'] == '股东增持':\n # if '增持' not in text:\n # continue\n # new_events.append(e)\n # # logger.info(f\"events: {events}\")\n # # logger.info(f\"new_events: {new_events}\")\n # events = new_events\n\n # logger.debug(f\"events: {events}\")\n event_types = [e['event_type'] for e in events]\n # 列出出现重复事件的事件\n if len(event_types) != len(set(event_types)):\n e0 = events[0]\n e1 = events[1]\n if len(event_types) == 2 and event_types[0] == event_types[\n 1] and len(e0) != len(e1):\n num_dup += 1\n event_type = event_types[0]\n if event_type not in donot_fixes:\n print(f\"{json.dumps(z, ensure_ascii=False, indent=2)}\")\n if len(e0) > len(e1):\n e_more = e0\n e_less = e1\n else:\n e_more = e1\n e_less = e0\n for k, v in e_less.items():\n if k not in e_more:\n e_more[k] = v\n events = [e_more]\n print(\n f\"{json.dumps(events, ensure_ascii=False, indent=2)}\"\n )\n # z['events'] = [e_more]\n # print(f\"{json.dumps(z, ensure_ascii=False, indent=2)}\")\n print(\"\")\n z['events'] = events\n fw.write(f\"{json.dumps(z, ensure_ascii=False)}\\n\")\n\n logger.info(f\"Total {num_dup} duplicate examples.\")\n fw.close()\n logger.info(f\"Fixed results file: {fixed_results_file}\")\n\n\ndef generate_submission(args):\n result_file = get_result_file(args)\n logger.info(\"Load result file {result_file}\")\n reports = json.load(open(result_file, 'r'))\n results = []\n for guid, report in tqdm(reports.items()):\n result = analysis_report(report)\n results.append(result)\n\n submission_file = get_submission_file(args)\n with open(submission_file, 'w') as fw:\n for result in results:\n line = json.dumps(result, ensure_ascii=False)\n fw.write(f\"{line}\\n\")\n\n logger.info(f\"Submission file saved to {submission_file}\")\n\n\ndef load_results(result_file):\n all_events = {}\n fr = open(result_file, 'r')\n lines = fr.readlines()\n for line in lines:\n line = line.strip()\n events = json.loads(line)\n all_events[events['doc_id']] = events\n\n return all_events\n\n\nimport glob\n\n\ndef new_unique_events(e0, events):\n final_t_events = []\n\n if len(events) == 0:\n return [e0]\n\n found = False\n for e in events:\n if not found:\n new_event = try_merge(e0, e)\n if new_event:\n final_t_events.append(new_event)\n found = True\n else:\n final_t_events.append(e)\n else:\n final_t_events.append(e)\n if not found:\n final_t_events.append(e0)\n return final_t_events\n\n\ndef merge_multi(args):\n top_events = load_results('merged_results_best_0.74917.txt')\n\n files = glob.glob(\"./results/fixed*.txt\")\n for result_file in files:\n logger.info(f\"{result_file}\")\n single_events = load_results(result_file)\n\n for doc_id, events in single_events.items():\n tt_events = top_events[doc_id]\n\n t_events = tt_events['events']\n s_events = events['events']\n master_s_event_type = get_master_event_type(s_events)\n\n if len(t_events) == 0:\n final_events = [\n e for e in s_events\n if e['event_type'] == master_s_event_type\n ]\n else:\n if master_s_event_type not in ['股东增持', '股东减持', '股权质押', '股权冻结']:\n continue\n\n if master_s_event_type == '股东减持' and t_events:\n continue\n\n master_t_event_type = get_master_event_type(t_events)\n if t_events:\n if master_s_event_type != master_t_event_type:\n continue\n\n final_events = [e for e in t_events]\n for e in s_events:\n if e['event_type'] != master_t_event_type:\n continue\n final_events = new_unique_events(e, final_events)\n\n tt_events['events'] = final_events\n\n merge_multi_file = \"merge_multi.json.txt\"\n wr = open(merge_multi_file, 'w')\n for doc_id, events in tqdm(top_events.items(), desc=\"Write\"):\n wr.write(json.dumps(events, ensure_ascii=False))\n wr.write(\"\\n\")\n logger.info(f\"Merge multi saved to {merge_multi_file}\")\n\n\ndef main(args):\n init_theta(args)\n init_labels(args, ner_labels)\n\n if args.do_eda:\n eda(args)\n return\n\n if args.do_merge:\n merge_all_tops()\n return\n\n if args.merge_multi:\n merge_multi(args)\n return\n\n if args.generate_submission:\n generate_submission(args)\n return\n\n if args.fix_results:\n fix_results_file(args)\n return\n\n trainer = Trainer(args)\n tokenizer = trainer.tokenizer\n\n # tokenizer = load_pretrained_tokenizer(args)\n\n # def examples_to_dataset(examples, label2id, tokenizer, max_seq_length):\n # from functools import partial\n # do_examples_to_dataset = partial(examples_to_dataset,\n # label2id=args.label2id,\n # tokenizer=tokenizer)\n\n # --------------- train phase ---------------\n if args.do_train:\n # train_examples = load_examples_from_bios_file(args.train_file)\n # eval_examples = load_examples_from_bios_file(args.eval_file)\n # train_examples, eval_examples = load_train_eval_examples(\n # train_base_file)\n\n # train_dataset = do_examples_to_dataset(\n # examples=train_examples, max_seq_length=args.train_max_seq_length)\n # eval_dataset = do_examples_to_dataset(\n # examples=eval_examples, max_seq_length=args.eval_max_seq_length)\n\n trainer.train(args, train_examples, eval_examples)\n\n # --------------- predict phase ---------------\n if args.do_eval:\n # eval_examples = load_examples_from_bios_file(args.eval_file)\n # train_examples, eval_examples = load_train_eval_examples(\n # train_base_file)\n # eval_dataset = do_examples_to_dataset(\n # examples=eval_examples, max_seq_length=args.eval_max_seq_length)\n\n model = load_model(args)\n trainer.evaluate(args, model, eval_examples)\n\n # --------------- predict phase ---------------\n if args.do_predict:\n # test_examples = load_examples_from_bios_file(args.test_file)\n # test_examples = load_test_examples(test_base_file)\n # test_dataset = do_examples_to_dataset(\n # examples=test_examples, max_seq_length=args.eval_max_seq_length)\n\n model = load_model(args)\n\n # s0 = 0\n # while s0 < len(text):\n # seg_text = text[s0:s0 + seg_len]\n # out = find_events_in_text(seg_text)\n # # out['doc_id'] = l['doc_id']\n #\n # if out:\n # event_outputs += out['events']\n # s0 += seg_len\n #\n # if seg_len == 0:\n # break\n\n trainer.predict(args, model, test_examples)\n\n save_predict_results(args, trainer.pred_results, get_result_file(args),\n test_examples)\n\n\ndef add_special_args(parser):\n parser.add_argument(\"--do_eda\", action=\"store_true\", help=\"\")\n parser.add_argument(\"--generate_submission\", action=\"store_true\", help=\"\")\n parser.add_argument(\"--results_file\", type=str, help=\"Results file name\")\n parser.add_argument(\"--fix_results\",\n action=\"store_true\",\n help=\"Fix results.\")\n parser.add_argument(\"--do_merge\",\n action=\"store_true\",\n help=\"Merge results.\")\n parser.add_argument(\"--merge_multi\",\n action=\"store_true\",\n help=\"Merge multi.\")\n return parser\n\n\nif __name__ == '__main__':\n from theta.modeling.ner.args import get_args\n args = get_args([add_special_args])\n main(args)\n","sub_path":"theta-master-0826/theta/examples/run_category_entities.py","file_name":"run_category_entities.py","file_ext":"py","file_size_in_byte":38621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"222793687","text":"import numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom Causal_bound import Causal_bound\nfrom Causal_bound import causal_bound_case1\nfrom Data_generation import Data_generation\n\ndef intfy(W):\n return np.array(list(map(int,W)))\n\ndef inverse_logit(Z):\n return np.exp(Z) / (np.exp(Z)+1)\n\ndef upper_bound_KL_case1(p, ubKL):\n q = causal_bound_case1(p,ubKL,'max')\n return q\n\ndef upper_bound_KL_case3(mu_hat, ubKL, std_sydox, std_hat):\n # In here, std_ymux is computed from Ds\n if std_sydox != std_hat:\n C = ubKL + 0.5 - np.log(std_sydox / std_hat) - (std_hat ** 2) / (2 * std_sydox ** 2)\n else:\n C = ubKL + 0.5 - (std_hat ** 2) / (2 * std_sydox ** 2)\n UB = mu_hat + std_sydox * np.sqrt(2 * C)\n return UB\n\ndef true_answer(Intv):\n reward_0 = np.mean( Intv[Intv['X']==0]['Y'] )\n reward_1 = np.mean(Intv[Intv['X'] == 1]['Y'])\n rewards = [reward_0, reward_1]\n return np.argmax(rewards), np.max(rewards), rewards\n\ndef pulling_receive(at,Intv, Na_T):\n return list(Intv[Intv['X'] == at]['Y'])[Na_T[at]]\n\n# Setting\nT = 5000 # number of rounds\ncase_num = 4\nif case_num != 4:\n dim = 1 # Dimension. Only matter for case_num = 4\nelse:\n dim = 100\n\nN = 100*dim\n# N = max(T*100,dim*200) # Number of data to be sampled (for accurate interventional effect)\nNs = 20*dim # Number of Ds\n\nObs, Intv, Intv_S = Data_generation(case_num=case_num ,N=N,Ns=Ns,dim = dim,seed_num=12345)\n\n# Identify optimal arm, optimal rewards, and rewards for all arm.\n## Binary {0,1} are assumed, but one can generalize.\nopt_arm, opt_reward, rewards = true_answer(Intv=Intv)\n\n# If not case 1, (Y continuous)\nif case_num != 1:\n std_sydox0 = np.std(Intv_S[Intv_S['X'] == 0]['Y'])\n std_sydox1 = np.std(Intv_S[Intv_S['X'] == 1]['Y'])\n std_sydox = [std_sydox0, std_sydox1]\n\n std_yx0 = np.std(Obs[Obs['X']==0]['Y'])\n std_yx1 = np.std(Obs[Obs['X'] == 1]['Y'])\n std_yx = [std_yx0, std_yx1]\n\n# Compute LB, UB using causal bound technique.\n## Not necessary for KB-UCB.\nLB0, p_true0, UB0 = Causal_bound(case_num=case_num , dim=dim, Obs=Obs, Intv=Intv, Intv_S = Intv_S, x=0, z=0)\nLB1, p_true1, UB1 = Causal_bound(case_num=case_num , dim=dim, Obs=Obs, Intv=Intv, Intv_S = Intv_S, x=1, z=0)\nLB = [LB0,LB1]\nL_max = np.max(LB)\nUB = [UB0,UB1]\n\nK = 2 # Number of arms.\nArm = []\nReward = []\n\n# Number of selection of arm a at time t\n## if we choose a at time t, then Na_T +=1 from t+1\nNa_T = dict()\nsum_reward = 0 # sum of rewards by far to compute cum.regret.\n\n''' Bandit start! '''\n# Initialization\nfor t in range(K):\n at = t # For each arm\n Na_T[at] = 0 # Setting each arm selection to 0\n rt = pulling_receive(at,Intv,Na_T) # Pulling and receive rewards\n Arm.append(at)\n Reward.append(rt)\n\n # Last step for each round\n ## Update the pulled arm selection\n Na_T[at] += 1\n\n ## Update regret\n ### Choose mean of rewards for arm at\n sum_reward += rewards[at]\n # As t starts from 0, we are at t+1 rounds.\n cum_regret = (t+1)*opt_reward - sum_reward\n\n# Initializing the probability of choosing arm\nprob_opt = Na_T[opt_arm] / K\nBandit = pd.DataFrame({'Arm':Arm, 'Reward':Reward, 'Cum_regret': cum_regret, 'Prob_opt':prob_opt })\nft = lambda x: np.log(x) + 3*np.log( np.log( x ) )\n\n# Iterate for round K to T\nfor t in range(K, T):\n # For each round, we compute upper bound for each arm,\n # and select one with highest value.\n Ua_t_list = []\n for a in range(K): # for each arm,\n # Compute the empirical mean for each arm by far.\n mu_hat = np.mean(Bandit[Bandit['Arm'] == a]['Reward'])\n # Compute the KL_bound\n ubKL = ft(t) / Na_T[a]\n UB_a = UB[a]\n\n # Compute upper bound Ua(t) for arm a at time t\n ## if Y are binary\n if case_num == 1:\n Ua_t = upper_bound_KL_case1(p=mu_hat,ubKL=ubKL)\n if pd.isnull(UB_a):\n Ua_t_list.append(Ua_t)\n else:\n Ua_t_list.append(min(Ua_t, UB_a))\n ## If Y are continuous\n elif case_num != 1:\n # If we don't have enough data to estimate sigma_do\n # Compute using Ds\n # Otherwise, Compute using accumulated data\n if Na_T[a] < Ns: # If Ds is more accurate\n # From Intv_S sample\n std_ydox_a = std_sydox[a]\n # From accumulate bandit\n std_yhat_a = np.std(Bandit[Bandit['Arm']==a]['Reward'])\n else:\n # From Bandit for both\n std_ydox_a = np.std(Bandit[Bandit['Arm'] == a]['Reward'])\n std_yhat_a = np.std(Bandit[Bandit['Arm'] == a]['Reward'])\n\n Ua_t = upper_bound_KL_case3(mu_hat=mu_hat, ubKL=ubKL,std_sydox = std_ydox_a,std_hat = std_yhat_a)\n if pd.isnull(Ua_t):\n Ua_t_list.append(UB_a)\n else:\n Ua_t_list.append(min(Ua_t, UB_a ) )\n\n # print(t,a,UB_a, Ua_t, min(Ua_t, UB_a ))\n # Choose arm with maximal UB\n at= np.argmax(Ua_t_list)\n if UB_a < Ua_t and opt_arm == at:\n print(at,\"works!\")\n rt = pulling_receive(at,Intv,Na_T)\n\n # Add the visiting number after pulling\n Na_T[at] += 1\n\n # We are at t+1 rounds.\n prob_opt = Na_T[opt_arm] / (t + 1 )\n sum_reward += rewards[int(at)]\n cum_regret = round((t+1) * opt_reward - sum_reward,3)\n\n Bandit_iter = pd.DataFrame({'Arm': [at], 'Reward': [rt], 'Cum_regret': cum_regret,'Prob_opt':prob_opt})\n Bandit_iter.index = [t]\n Bandit = Bandit.append(Bandit_iter)\n\nBandit_BKL = Bandit\n\n# # Graphical illustration\n# f, ax = plt.subplots(2, sharex='all')\n# plt.title(\"B-KL-UCB\")\n# ax[0].set_title('Cumulative regret')\n# ax[0].plot(Bandit['Cum_regret'])\n#\n# ax[1].set_title('Probability of choosing opt arm')\n# ax[1].plot(Bandit['Prob_opt'])\n\n","sub_path":"Bandit/B-KL-UCB.py","file_name":"B-KL-UCB.py","file_ext":"py","file_size_in_byte":5798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"284274812","text":"\"\"\"@package PySideWidgetCollection.loadingdialog.loadingdialog\n@brief A loading screen for time consuming processes.\n@date 2016/02/05\n@version 2.0\n@author Paul Schweizer\n@email paulschweizer@gmx.net\n\"\"\"\nimport os\nimport logging\n\nfrom PySide import QtCore, QtGui\n\nfrom PySideWidgetCollection import utility\n__all__ = ['LoadingDialog']\n\n\nbase_class, form_class = utility.load_ui_bases(__file__, 'LoadingDialog')\n\n\nclass LoadingDialog(base_class, form_class):\n\n \"\"\"Show a screen while running a background process.\n\n The dialog will be shown until the given callback has run.\n \"\"\"\n\n def __init__(self, callback=lambda: None, text='Loading ...'):\n \"\"\"Initialize the LoadingDialog.\"\"\"\n super(LoadingDialog, self).__init__()\n self.setupUi(self)\n\n self.callback = callback\n self.return_value = None\n self.painted = False\n\n # Set the window opacity\n self.setAttribute(QtCore.Qt.WA_TranslucentBackground)\n self.setAttribute(QtCore.Qt.WA_PaintOnScreen)\n self.setWindowFlags(QtCore.Qt.Widget | QtCore.Qt.FramelessWindowHint)\n\n # Fill the screen\n desktop = QtGui.QApplication.instance().desktop()\n self.setGeometry(desktop.screenGeometry(QtGui.QCursor().pos()))\n\n # Set the semi-transparent background\n palette = QtGui.QPalette()\n pxm = QtGui.QPixmap(os.path.join(os.path.dirname(__file__), 'resource',\n 'semi_transparent_bg.png'))\n brush = QtGui.QBrush(pxm)\n palette.setBrush(QtGui.QPalette.Window, brush)\n self.setPalette(palette)\n\n # Set the text\n self.label.setText(text)\n\n # Show the loading dialog\n self.exec_()\n # end def __init__\n\n def paintEvent(self, event):\n \"\"\"Overridden to show the dialog while running the callback.\n\n After the first paint event, that paints the widget on the\n screen, the callback is launched. This ensures that the dialog\n is visible while running the background task and makes it\n possible to close the dialog afterwards.\n @param event The QPaintEvent\n \"\"\"\n if not self.painted:\n self.painted = True\n cursor = QtGui.QCursor()\n cursor.setShape(QtCore.Qt.WaitCursor)\n self.setCursor(cursor)\n self.update(self.rect())\n elif self.painted:\n try:\n self.return_value = self.callback()\n except Exception as e:\n logging.exception(e)\n # end try to\n self.close()\n # end if\n # end def paintEvent\n# end class LoadingDialog\n","sub_path":"loadingdialog/loadingdialog.py","file_name":"loadingdialog.py","file_ext":"py","file_size_in_byte":2654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"354437470","text":"from collections import deque\n\nN = int(input())\n\nedge = [[] for _ in range(N)]\nconect = [[i,0] for i in range(N)] # つながる頂点の数 ... 多い頂点に大きい数字を与える\n\nfor _ in range(N-1) :\n a , b = map(int,input().split())\n a -= 1\n b -= 1\n conect[a][1] += 1\n conect[b][1] += 1\n edge[a].append(b)\n edge[b].append(a)\n\nc = list(map(int,input().split()))\nc.sort()\n\nnet = lambda A : A[1]\n\nconect.sort(key=net,reverse=True)\n\nans = [0] * N\n\nfor i in range(N) :\n ans[conect[i][0]] = c[i]\n\nchecked = [False] * N\nlength = 0\n\nfor c , check in enumerate(checked) :\n if check :\n continue\n\n stack = deque([c])\n\n while stack :\n current = stack.pop()\n\n if checked[current] :\n continue\n\n checked[current] = True\n for v in edge[current] :\n if not checked[v] :\n stack.append(v)\n length += min(ans[current] , ans[v])\n\nprint(length)\n\nfor a in ans :\n print(a,end=' ')\n\nprint('')","sub_path":"AtCoder/other/M-SOLUTIONS/d.py","file_name":"d.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"213304671","text":"#minutes to hours converter\n\nprint(\"How many minutes would you like to convert into hours?\")\n\n#input has to be converted to an integer\nminutes = int(input(\"~> \"))\n#if it isn't, line 8 and 9 don't work. can't divide a string by 60.\nhours = round(minutes / 60)\nextra_minutes = minutes % 60\n\n#remember to put the % and (min...etc) within the parantheses of print!\nprint(\"%r minutes is equal to %r hour(s) and %r minutes.\" % (minutes, hours,\n extra_minutes))\n\n#below is the version of the minutes to hours converter from the textbook\n#minutes_to_convert = 123\n#hours_decimal = minutes_to_convert/60\n#hours_part = int(hours_decimal)\n#minutes_decimal = hours_decimal-hours_part\n#minutes_part = round(minutes_decimal*60)\n#print(\"Hours\")\n#print(hours_part)\n#print(\"Minutes\")\n#print(minutes_part)\n","sub_path":"get-programming-python3/capstone6.py","file_name":"capstone6.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"559141830","text":"from keras.preprocessing.text import Tokenizer\r\n\r\ntext = \"나는 맛있는 밥을 먹었다\"\r\n\r\ntoken = Tokenizer()\r\ntoken.fit_on_texts([text]) # 띄어쓰기로 단어 구분\r\nprint(token.word_index)\r\n# {'나는': 1, '맛있는': 2, '밥을': 3, '먹었다': 4}\r\n\r\nx = token.texts_to_sequences([text])\r\nprint(x) # [[1, 2, 3, 4]]\r\n\r\nfrom keras.utils import to_categorical\r\n\r\nword_size = len(token.word_index) + 1\r\nprint(word_size)\r\n\r\nx = to_categorical(x, num_classes=word_size)\r\n# or x = to_categorical(x, 5) \r\n# or x = to_categorical(x) \r\nprint(x)\r\n","sub_path":"keras/keras120_embedding1.py","file_name":"keras120_embedding1.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"366385729","text":"import requests, html2text, re\n\nhtml = requests.get('http://sinacn.weibodangan.com//user/1788862154/') # 代抓\np = re.compile(r'\\d{3,}') # 正则抓三位以上数字\nnum = p.findall(html2text.html2text(html.text)) # 查找全部\nprint('\\n' + \"数字ID \" + num[2] + '\\n' + '关注Following ' + num[4] + '\\n' + '粉丝Fans ' + num[5] + '\\n' + '微博Posts ' + num[6])\nf = open('/Users/alicewish/我的坚果云/Python.txt', 'w')\nlong = \"数字ID \" + num[2] + '\\n' + '关注Following ' + num[4] + '\\n' + '粉丝Fans ' + num[5] + '\\n' + '微博Posts ' + num[6]\ntry:\n f.write(long)\nfinally:\n f.close()\n","sub_path":"文本处理-正则.py","file_name":"文本处理-正则.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"419761955","text":"import json\nimport requests\nfrom os import environ\n\n# Weather App Id\nWEATHER_APP_ID = environ.get('WEATHER_APP_ID')\n\n# OpenWeatherMap URLS\nWEATHER_API_BASE_URL = \"http://api.openweathermap.org/data\"\nWEATHER_API_VERSION = \"2.5\"\nWEATHER_API_URL = \"{}/{}/weather\".format(WEATHER_API_BASE_URL, WEATHER_API_VERSION)\n\ndef getWeatherFromZip(zipcode):\n \"\"\" Through a US zipcode, gets the json for the weather \"\"\"\n state = 'us'\n weather_api_endpoint = \"{}?zip={},{}&appid={}\".format(WEATHER_API_URL,zipcode,state,WEATHER_APP_ID)\n weather_response = requests.get(weather_api_endpoint)\n weather_data = json.loads(weather_response.text)\n\n return weather_data","sub_path":"datafoo/openWeather.py","file_name":"openWeather.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"129852335","text":"from pptx import Presentation\nfo = open(\"DLcontent.txt\", \"w\",encoding='utf8', errors='ignore')\n\n# for x in range(9):\nprs = Presentation('Digital Logic.pptx')\n# text_runs will be populated with a list of strings,\n# one for each text run in presentation\nfor slide in prs.slides:\n\tlist_of_elements = []\n\tfor shape in slide.shapes:\n\t\tif not shape.has_text_frame:\n\t\t\tcontinue\n\t\tfor paragraph in shape.text_frame.paragraphs:\n\t\t\tline = ''\n\t\t\tfor run in paragraph.runs:\n\t\t\t\tline += run.text\t\n\t\t\tlist_of_elements.append(line)\n\t\t\n\tfor elements in list_of_elements:\n\t\tprint(elements)\n\t\tfo.write(elements +'\\n')\n\tfo.write('\\n')\n","sub_path":"ppt.py","file_name":"ppt.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"141227476","text":"text = \"It's four in the morning the end of December\"\nwords = text.split()\n\ni = 0\n\nvowels = []\nwhile i < len(words):\n word = words[i]\n i += 1\n\n if word[0].lower() in ['a', 'e', 'i', 'o', 'u']:\n vowels.append(word)\n\nprint(vowels)\n\n","sub_path":"S05/loops/iterate_over_collection_items_2.py","file_name":"iterate_over_collection_items_2.py","file_ext":"py","file_size_in_byte":246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"469076012","text":"\r\ndef result (text):\r\n countAlphaNum = 0\r\n for i in text:\r\n if i.isalnum (): # check for alpha numeric values\r\n countAlphaNum += 1\r\n \r\n if countAlphaNum != 0: # if there is any alpha numeric value, print 'true'\r\n print (\"True\")\r\n \r\n else:\r\n print ('False')\r\n \r\n countAlpha = 0\r\n for i in text:\r\n if i.isalpha (): # check for alphabetic\r\n countAlpha += 1\r\n\r\n if countAlpha != 0:\r\n print(\"True\")\r\n\r\n else:\r\n print('False')\r\n\r\n countDigit = 0\r\n for i in text:\r\n if i.isdigit(): # check for digits\r\n countDigit += 1\r\n\r\n if countDigit != 0:\r\n print(\"True\")\r\n\r\n else:\r\n print('False')\r\n\r\n countLower = 0\r\n for i in text:\r\n if i.islower(): # check for lowercase values\r\n countLower += 1\r\n\r\n if countLower != 0:\r\n print(\"True\")\r\n\r\n else:\r\n print('False')\r\n \r\n countUpper = 0\r\n for i in text:\r\n if i.isupper(): # check for upper case values\r\n countUpper += 1\r\n\r\n if countUpper != 0:\r\n print(\"True\")\r\n\r\n else:\r\n print('False')\r\n\r\nstring = input ()\r\nresult (string)\r\n","sub_path":"stringValidators.py","file_name":"stringValidators.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"534441737","text":"#Display the given pyramid with step number entered by the user.\r\ndef py(n):\r\n x=1\r\n for i in range(1,n+1):\r\n for j in range(1,i+1):\r\n print(x, end=\" \")\r\n x=x+i\r\n x=i+1\r\n print(\"\\r\")\r\nn=int(input(\"Enter the limit:\"))\r\npy(n)\r\n","sub_path":"pythoncycle3/P05.py","file_name":"P05.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"618329096","text":"import pandas as pd\r\nimport os\r\nimport logging\r\nimport configparser as cf\r\nimport lib.File_Validator as FV\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.dates as mdates\r\n\r\n#*Call the logger************************\r\nlog = logging.getLogger(__name__)\r\n\r\n#*******************************************************************\r\n#********************set the properties of config ******************\r\n#*******************************************************************\r\n\r\ncon = cf.ConfigParser()\r\n\r\ncon.read('config.ini')\r\n\r\n\r\nconfig = { \"mem_percentage_crit\" : float(con['MEMORY_CRIT']['mem_percentage']),\\\r\n \"instances_crit\" : int(con['MEMORY_CRIT']['consecutive_intervals']),\\\r\n\"mem_percentage_warn\" : float(con['MEMORY_WARN']['mem_percentage']),\\\r\n \"instances_warn\" : int(con['MEMORY_WARN']['consecutive_intervals']) }\r\n \r\n \r\n ##GLOBAL VARIABLE DECLARATION##############################\r\n\r\npath=str('C:\\project\\TQClient\\TQFiles\\TQ_DATA_1530894769048')\r\nserver = \"sawasq05\"\r\n#busy='%busy'\r\n#runq='cpuq-sz'\r\nhigh={}\r\nkcrit=config[\"instances_crit\"]\r\nPercentage_crit=config[\"mem_percentage_crit\"]\r\nkwarn=config[\"instances_warn\"]\r\nPercentage_warn=config[\"mem_percentage_warn\"]\r\n\r\n#Result will be captured in the global variable\r\ndf1=pd.DataFrame()\r\n\r\ndef mem_analyzer_call(server, path, k, Percentage, status):\r\n\t#variable declaration inside function\r\n\tglobal df1\r\n\tMempath = path + '/' + server + '/' + 'Memory_Busy.csv'\r\n\tlog.info('memory busy will be saved at %s' %Mempath)\r\n\tcounter=0\r\n\thigh_index=[]\r\n\tindex=[]\r\n\tdf = pd.read_csv(path + '/' + server + '/Memory_Util.csv')\r\n\tdf[\"pct_mem_utilization\"] = ((df['usedmem'] -df['cachedmem'] -df['buffermem'])/df['totalmem']) *100\r\n\ttry:\r\n\t\tdf.to_csv(Mempath, columns=[\"Time:Date\", \"Time:Time\", \"Interval\", \"pct_mem_utilization\"])\r\n\texcept:\r\n\t\tlog.exception(\"Error found during saving the memory busy data\")\r\n\tdf['Date-Time']=df['Time:Date']+' '+df['Time:Time']\r\n\tdf.drop(['Time:Time', 'Time:Date'], axis=1, inplace=True)\r\n\tdf['Date-Time'] = pd.to_datetime(df['Date-Time'], format='%m/%d/%Y %I:%M:%S %p')\r\n\t\r\n\tresult = df\r\n \t\r\n\t#result[\"pct_mem_utilization\"] = ((result['usedmem'] -result['cachedmem'])/result['totalmem']) *100\r\n\t#result[\"pct_mem_utilization\"] = ((result['usedmem'] -result['cachedmem'] -result['buffermem'])/result['totalmem']) *100\r\n\t\r\n#\tprint(result.dtypes)\r\n\t#print(result[\"pct_mem_utilization\"])\r\n\ttotal_row = result.shape[0]\r\n\t\r\n\t####Defining Plot Variables ########################################\r\n\tTitle = server.upper() + '- ' + 'Percent MEM UTILIZATION'\r\n\tchart_path = path +'/' + 'Charts' + '/' + server + '-mem_util.png'\r\n\t\r\n\tresult.drop(['System', 'Interval'], axis=1, inplace=True)\r\n\tresult.round({'pct_mem_utilization': 1})\r\n\tfig, ax1 = plt.subplots(figsize=(1366/96,768/96))\r\n\txfmt = mdates.DateFormatter('%m/%d/%Y %I:%M:%S %p')\r\n\tax1.xaxis.set_major_formatter(xfmt)\r\n\tax1.plot(result['Date-Time'], result['pct_mem_utilization'], 'b-')\r\n\tax1.set_xlabel('TIME')\r\n\t# Make the y-axis label, ticks and tick labels match the line color.\r\n\tax1.set_ylabel('%busy', color='b', fontsize=17)\r\n\t#ax1.set_xticks('%busy', result['date time'], rotation='vertical')\r\n\tplt.xticks(rotation=90)\r\n\tax1.tick_params('%busy', colors='b')\r\n\tax1.set_title(Title, fontsize=22, color='r')\r\n\tplt.gcf().autofmt_xdate()\r\n\r\n\t#fig.tight_layout()\r\n\t#plt.show()\r\n\tplt.savefig(chart_path, dpi=96)\r\n\tplt.close()\r\n\t##################################################################\r\n\t\r\n\t\r\n\tfor i in range(0, total_row):\r\n\r\n\t\tif (result[\"pct_mem_utilization\"].iloc[i] > Percentage):\r\n\r\n\t\t\tcounter=counter+1\r\n\t\t\thigh_index.append(i)\r\n\t\t#\tprint(high_index)\r\n\t\t\t\r\n\t\telif (counter >= k):\r\n\t\t\tfin_index=list(high_index)\r\n\t\t\tindex = index[0:] + fin_index[0:]\r\n\t\t\tfin_index=[]\r\n\t\t\thigh_index=[]\r\n\t\t\tcounter=0\r\n\t\t\t\r\n\t\t\t\r\n\t\telse:\r\n\t\t\thigh_index=[]\r\n\t\t\tcounter=0\r\n\r\n\t\tif ( i == total_row-1 ):\r\n\t\t#\tprint(i, total_row-1)\r\n\t\t\tif ( counter >= k):\r\n\t\t\t\tfin_index = list(high_index)\r\n\t\t\t\tindex = index[0:] + fin_index[0:]\r\n\t\t\t\tfin_index = []\r\n\t\t\t\thigh_index = []\r\n\t\t\t\tcounter = 0\r\n\t\t\t\tbreak\r\n\t\t\telse:\r\n\t\t\t\tbreak\r\n\t\t\r\n\tif(len(index) >0):\r\n\t\t\r\n\t\tdf1=result.ix[index]\r\n\t\toutput= path + '/' + 'Memory/' + server + '-' + status + '-memory.csv'\r\n\t\tdf1.to_csv(output, index=False, sep=',')\r\n\telse:\r\n\t\tdf1=df1.iloc[0:0]\r\n\r\n\r\ndef mem_analyzer(server, path, interval1):\r\n\tif (interval1 == 1 ):\r\n\t\tkcr = int(kcrit)\r\n\telif ( interval1 == 5 ):\r\n\t\tkcr = int(kcrit/interval1)\r\n\telif ( interval1 > 5 ):\r\n\t\tkcr = 1\r\n\tif ( interval1 == 1 ):\r\n\t\tkwr = int(kwarn)\r\n\telif ( interval1 == 5 ):\r\n\t\tkwr = int(kwarn/interval1)\r\n\telif ( interval1 > 5 ):\r\n\t\tkwr = 1\r\n\tstatus='crit'\r\n\tmem_analyzer_call(server, path, kcr, Percentage_crit, status)\r\n\tif not df1.empty:\r\n\t\tstatus='warn'\r\n\t\tmem_analyzer_call(server, path, kwr, Percentage_warn, status)\r\n\t\treturn \"CRITICAL\"\r\n\telif df1.empty:\r\n\t\tstatus='warn'\r\n\t\tmem_analyzer_call(server, path, kwr, Percentage_warn, status)\r\n\t\tif not df1.empty:\r\n\t\t\treturn \"WARN\"\r\n\t\telse:\r\n\t\t\treturn \"OK\"\r\ndef mem_analyze(server, path):\r\n\tfile = path + '/' + server + '/Memory_Util.csv'\r\n\t\r\n\tTime_validate1 = FV.time_validator_call(file, path, server, 'memory')\r\n\t\r\n\tif Time_validate1 is \"DNA\":\r\n\t\treturn(\"DNA\")\r\n\telse:\r\n\t\tvalidator1 = FV.file_validator_call(file, kcrit, Time_validate1)\r\n\t\r\n\tif validator1 is not None:\r\n\t\treturn('NED #' + validator1)\r\n\tvalue=mem_analyzer(server, path, Time_validate1)\r\n\treturn(value)\r\n#result = mem_analyze(server, path)\r\n#print(result)\r\n\t\r\n\t","sub_path":"tq_analyzer_panda/lib/Memory_Analyzer.py","file_name":"Memory_Analyzer.py","file_ext":"py","file_size_in_byte":5411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"229783085","text":"arrayList = [[1,3,7], # A\r\n [0,2,3,4,6], # B\r\n [1], # C\r\n [0,1,6], # D\r\n [1,5,6,7], # E\r\n [4,7], # F\r\n [1,3,4], # G\r\n [0,5]] # H\r\n\r\n\r\nlevel = [False,False,False,False,False,False,False,False] \r\n\r\n\r\ndef breadth_first_search(start):\r\n for i in range(len(arrayList[start])):\r\n if arrayList[start][i] != -1:\r\n if level[arrayList[start][i]] == False:\r\n level[arrayList[start][i]] = True\r\n else:\r\n arrayList[start][i] = -1\r\n\r\n for i in range(len(arrayList[start])):\r\n if arrayList[start][i] != -1:\r\n breadth_first_search(arrayList[start][i])\r\n\r\n\r\n\"\"\"def virtualize_vertices(startPoint):\r\n if startPoint == 0:\r\n return 'A'\r\n if startPoint == 1:\r\n return 'B'\r\n if startPoint == 2:\r\n return 'C'\r\n if startPoint == 3:\r\n return 'D'\r\n if startPoint == 4:\r\n return 'E'\r\n if startPoint == 5:\r\n return 'E'\r\n if startPoint == 6:\r\n return 'G'\r\n if startPoint == 7:\r\n return 'H'\"\"\"\r\n\r\n\r\ndef output(start_v, s):\r\n \r\n print(s, start_v , ': ')\r\n\r\n s = s + ' '\r\n\r\n for i in range(len(arrayList[start_v])):\r\n if arrayList[start_v][i] != -1:\r\n output(arrayList[start_v][i], s)\r\n\r\n\r\nprint('Введите вершину: ')\r\nstart_v = int(input())\r\n\r\nlevel[start_v] = True\r\nbreadth_first_search(start_v)\r\noutput(start_v, ' ')\r\n\r\n\r\n\r\n\r\n\r\n\"\"\"\r\ndef breadth_first_search(s):\r\n level[s] = 0\r\n point = [s]\r\n while point:\r\n i = point.pop(0)\r\n for k in arrayList[i]: \r\n if level[k] is -1: \r\n point.append(k) \r\n level[k] = level[i] + 1\r\n\r\n\r\nprint('Введите стартовую вершину')\r\nstartPoint = str(input())\r\nif startPoint == 'A':\r\n startPoint = 0\r\nif startPoint == 'B':\r\n startPoint = 1\r\nif startPoint == 'C':\r\n startPoint = 2\r\nif startPoint == 'D':\r\n startPoint = 3\r\nif startPoint == 'E':\r\n startPoint = 4\r\nif startPoint == 'F':\r\n startPoint = 5\r\nif startPoint == 'G':\r\n startPoint = 6\r\nif startPoint == 'H':\r\n startPoint = 7\r\n\r\nfor i in range(len(level)):\r\n if level[i] == -1:\r\n breadth_first_search(startPoint)\r\n\r\n\r\nprint('От H до')\r\nprint(' A B C D E F G H ')\r\nprint(level)\r\nprint('Максимальный уровень вершины = ',max(level)) \"\"\"\r\n\r\n","sub_path":"lab_6.py","file_name":"lab_6.py","file_ext":"py","file_size_in_byte":2470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"101700356","text":"import json\nfrom django.contrib.auth.decorators import login_required\nfrom django.http.response import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom app.models import VideoSessionTrack, Session, SessionInstance, Teacher\n\n\n@csrf_exempt\n@login_required\ndef record_instance(request):\n if request.method == \"POST\":\n session = Session.objects.get(pk=request.POST['id'])\n if 'type' in request.session and request.session['type'] == 'preview':\n return HttpResponse(json.dumps({}), content_type='application/json')\n if not session.presentation_file:\n try:\n vs = VideoSessionTrack.objects.get_or_create(student=request.user, session=session)[0]\n except VideoSessionTrack.MultipleObjectsReturned:\n vs = VideoSessionTrack.objects.filter(student=request.user, session=session)[0]\n if request.POST['message'] == 'ended':\n vs.ended = True\n elif request.POST['message'] == 'paused':\n vs.pauses += str(request.POST['time'])\n elif request.POST['message'] == 'back':\n vs.skipbacks += str(request.POST['startTime']) + ',' + str(request.POST['endTime'])\n elif request.POST['message'] == 'forward':\n vs.skipforwards += str(request.POST['startTime']) + ',' + str(request.POST['endTime'])\n vs.save()\n return HttpResponse(json.dumps({}), content_type='application/json')\n\n\n@csrf_exempt\n@login_required\ndef advice_toggle(request):\n if request.method == \"POST\":\n if 'instance' in request.POST:\n instance = SessionInstance.objects.get(pk=int(request.POST['instance']))\n setattr(instance, request.POST['key'], not getattr(instance, request.POST['key']))\n instance.save()\n else:\n pass\n return HttpResponse(json.dumps({}), content_type='application/json')\n\n\n@csrf_exempt\n@login_required\ndef record_page_change(request, session_id):\n if request.method == \"POST\":\n session = Session.objects.get(pk=session_id)\n user = request.user\n\n instances = SessionInstance.objects.filter(session=session, user=user)\n if instances.count() == 0:\n instance = SessionInstance.objects.create(session=session, user=user, time_spent=0)\n else:\n instance = instances[0]\n page = int(request.POST['page'])\n time = int(request.POST['time']) / 1000\n instance.pages += str(page) + ','\n instance.pages_time += str(time) + ','\n instance.save()\n\n return HttpResponse(json.dumps({}), content_type='application/json')\n\n\n@csrf_exempt\n@login_required\ndef record_teacher_time_spent(request, session_id):\n if request.method == \"POST\":\n session = Session.objects.get(pk=session_id)\n session.time_spent_teacher += int(request.POST['time']) / 1000\n session.save()\n return HttpResponse(json.dumps({}), content_type='application/json')\n\n\n@csrf_exempt\n@login_required\ndef first_guide_record(request, teacher_id):\n if request.method == \"POST\":\n teacher = Teacher.objects.get(pk=teacher_id)\n teacher.first_guide = False\n teacher.save()\n return HttpResponse(json.dumps({}), content_type='application/json')\n\n\n@csrf_exempt\n@login_required\ndef demo_guide_record(request, teacher_id):\n if request.method == \"POST\":\n teacher = Teacher.objects.get(pk=teacher_id)\n teacher.demo_course_guide = False\n teacher.save()\n return HttpResponse(json.dumps({}), content_type='application/json')\n","sub_path":"app/recording.py","file_name":"recording.py","file_ext":"py","file_size_in_byte":3576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"257853054","text":"from ncore.rest import request\nfrom ncore.wsgi import WSGIApp\nfrom ncore.data import HTTPStore, PrefixDict\n\ntry:\n import json\nexcept ImportError:\n import simplejson as json\n\nfrom wsgiref.simple_server import make_server\nfrom threading import Thread\nfrom socket import getfqdn\nfrom time import sleep\nimport logging\n\nclass FooApp(object):\n name = 'foo'\n\n def __init__(self, user, config_file='/etc/foobox.conf'):\n self.config = json.loads(file(config_file, 'r').read())\n self.data = HTTPStore(self.config['common']['data_url'])\n try:\n self.config.update(json.loads(self.data['%s/config' % user]))\n except KeyError: pass\n self.data = PrefixDict(self.data, '%s/%s/' % (user, self.name))\n\n self.server = '%s/%s' % (self.config['common']['foobox_url'], user)\n \n def recv(self, text, dst=None):\n msg = {\n 'src': self.name,\n 'text': text,\n }\n if dst:\n msg['dst'] = dst\n msg = json.dumps(msg)\n logging.debug('Sending json to server: %s' % msg)\n status, response = request('POST', '%s/message' % self.server, msg)\n if status != 200:\n logging.error('Error sending message: %s, %s' % (status, response))\n \n def send(self, msg):\n logging.info('Recieved message from %s: %s' % (msg['src'], msg['text']))\n \n def register(self, url, name=None):\n if not name:\n name = self.name\n app = {\n 'name': name,\n 'url': url,\n }\n app = json.dumps(app)\n status, response = request('POST', '%s/app' % self.server, app)\n if status != 200:\n logging.error('Error registering app %s: %s, %s' % (self.name, status, response))\n else:\n logging.info('Registered %s as %s' % (self.name, url))\n \n def run(self):\n pass\n\nclass FooResponder(object):\n def __init__(self, handler=None):\n self.handler = handler\n\n def POST(self):\n msg = self.app.get_content().value\n msg = json.loads(msg)\n self.handler.send(msg)\n self.app.status = '200 OK'\n yield self.app.status\n return\n\ndef start_app(myapp, user='synack', listen_port=0):\n app = myapp(user)\n logging.basicConfig(filename=app.config['common']['log_path'], level=logging.DEBUG, format='%(asctime)s - ' + user + ' - %(levelname)s - %(message)s')\n\n urls = [\n ('^/', FooResponder),\n ]\n wsgiapp = WSGIApp(urls, handler=app)\n\n server = make_server(app.config['fooapp']['bind_address'], listen_port, wsgiapp)\n listen_addr, listen_port = server.socket.getsockname()\n\n app.register('http://%s:%i/' % (app.config['fooapp']['callback_ip'], listen_port))\n\n t = Thread(target=app.run)\n t.setDaemon(True)\n t.start()\n server.serve_forever()\n\nif __name__ == '__main__':\n start_app(FooApp)\n","sub_path":"fooapp.py","file_name":"fooapp.py","file_ext":"py","file_size_in_byte":2881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"648381764","text":"__author__ = 'prags11'\n\nimport turtle\n\ndef drawSquare(side) :\n for _ in range(4) :\n turtle.forward(side)\n turtle.left(90)\n\ndef main():\n sideLength = int(input('Enter side length :'))\n drawSquare(sideLength);\n input(\"enter something\")\n\nif __name__ == '__main__' :\n main()","sub_path":"Graphics/lec2/lec3_square.py","file_name":"lec3_square.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"596164913","text":"#!/usr/bin/python\nfrom __future__ import print_function\nimport pickle\nnames = [\"james\",\"julie\",\"mikey\",\"sarah\"]\ndef sanitize(time_string):\n\tif '-' in time_string:\n\t\tsplitter = '-'\n\telif ':' in time_string:\n\t\tsplitter = ':'\n\telse:\n\t\treturn(time_string)\n\t(mins,secs) = time_string.split(splitter)\n\treturn(mins + '.' + secs)\n\ndef get_coach_data(filename):\n\ttry:\n\t\twith open(filename) as jsf: \n\t\t\tdata = jsf.readline()\n\t\treturn(data.strip().split(','))\t\n\texcept IOError as ioerr:\n\t\tprint('File error:' + str(ioerr))\n\t\treturn (None)\n\nfor name in names:\n\tdatas = get_coach_data(name + \".txt\")\n\tprint(sorted(set([sanitize(data) for data in datas]))[0:3])\n","sub_path":"Python/moveit/chapter5/hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"256581284","text":"import tensorflow as tf\n#enable Eager execution\ntf.enable_eager_execution()\n\nimport numpy as np\n\ndef tensornorm(a):\n \"\"\"divides by max value of tensor to normalise between 0 and 1\"\"\"\n TensorMax = tf.reduce_max(tf.abs(a))\n norm_condition = tf.complex(tf.reciprocal(TensorMax),0.)\n \n return tf.multiply(a,norm_condition),norm_condition\n\ndef ComplexInnerProduct(temp,data,psd,df):\n \"\"\"computes complex inner product in the fourier domain IP = 4 deltaf sum((a * conguagte(b))/Weights)\"\"\"\n \n weights = tf.sqrt(psd)\n norm = (4*df)\n a_weight = tf.div_no_nan(temp,weights)\n b_conj = tf.conj(data)\n b_weight = tf.div_no_nan(tf.cast(b_conj,dtype=tf.complex64),weights)\n a_dot_b = tf.reduce_sum(tf.multiply(a_weight,b_weight))\n \n return tf.multiply(norm,a_dot_b)\n\ndef InnerProduct(temp,data,psd,df):\n \"\"\"computes inner product in the fourier domain IP = 4 deltaf RE sum((a * conguagte(b))/Weights)\"\"\"\n \n return tf.real(ComplexInnerProduct(temp,data,psd,df))\n\ndef matchedfilter(temp,data,psd,df):\n \"\"\"Computes the overlap between two waveforms\"\"\"\n \n prod_a_b = InnerProduct(temp,data,psd,df)\n prod_a_a = InnerProduct(temp,temp,psd,df)\n prod_b_b = InnerProduct(data,data,psd,df)\n \n sigma = tf.sqrt(tf.multiply(prod_a_a,prod_b_b))\n \n return tf.divide(prod_a_b,sigma)\n\ndef match(temp,data,psd,df,freq,tc_low = -1.,tc_high = 1.,samples=201):\n \"\"\"Calculate the max match between two waveforms by maximisiung over coalescence time\"\"\"\n \n t_c = tf.cast(tf.linspace(tc_low,tc_high,samples),dtype=tf.float32)\n freq_tc = tf.tensordot(t_c,freq,axes=0)\n freq_tc = tf.cast(freq_tc,dtype=tf.complex64)\n shift_factor = tf.exp(1j*2*np.pi*freq_tc)\n\n match_max = np.zeros(len(t_c))\n for coa_time in range(len(t_c)):\n waveform_shift = shift_factor[coa_time,:]\n waveform_shifted = tf.multiply(waveform_shift,temp)\n match_max[coa_time] = matchedfilter(waveform_shifted,data,psd,df)\n \n return t_c, match_max\n\ndef match_cpu(temp,data,psd,df,freq,norm_condition,tc_low = -1.,tc_high = 1.,samples=201):\n \"\"\"Calculate the max match between two waveforms by maximisiung over coalescence time, calculated on the cpu\"\"\"\n \n with tf.device('/cpu:0'):\n t_c = tf.cast(tf.linspace(tc_low,tc_high,samples),dtype=tf.float32)\n freq_tc = tf.tensordot(t_c,freq,axes=0)\n freq_tc = tf.cast(freq_tc,dtype=tf.complex64)\n shift_factor = tf.exp(1j*2*np.pi*freq_tc)\n\n match_max = np.zeros(len(t_c))\n for coa_time in range(len(t_c)):\n waveform_shift = shift_factor[coa_time,:]\n waveform_shifted = tf.multiply(waveform_shift,temp)\n match_max[coa_time] = matchedfilter(waveform_shifted,data,psd,df)\n \n return t_c, match_max\n\ndef loglikelihood(temp,data,psd,df):\n \"\"\"Computes the relative log likelihood of two data sets, computed by -1/2 \"\"\"\n return (InnerProduct(data,temp,psd,df)-0.5*InnerProduct(temp,temp,psd,df))\n\n\ndef SNR(temp,data,psd,df):\n \"\"\"Compute the SNR at the true value of the parameters \"\"\"\n\n return tf.sqrt(2*loglikelihood(temp,data,psd,df))\n","sub_path":"legacy/MSc Archive/taylorflow/overlap.py","file_name":"overlap.py","file_ext":"py","file_size_in_byte":3153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"534521529","text":"# Serial command using pyserial\r\n# for CoolLED pE-300\r\n# GUI control\r\n# N Laohakunakorn, University of Edinburgh, 2021\r\n\r\nimport serial, atexit\r\n\r\nfrom PyQt5.QtWidgets import *\r\nfrom PyQt5.QtCore import *\r\nfrom PyQt5.QtGui import *\r\nfrom pyqtgraph import PlotWidget, plot\r\nimport pyqtgraph as pg\r\npg.setConfigOption('background','w') # set background default to white\r\npg.setConfigOption('antialias',True)\r\nimport traceback, sys\r\n\r\n### Configure serial communication \r\nPORTNAME = 'COM3' # set port name here\r\nser = serial.Serial() \r\nser.baudrate = 9600\r\nser.port = PORTNAME\r\nser.bytesize = 8 \r\nser.parity = 'N'\r\nser.stopbits = 1\r\nser.timeout = 0 # second\r\n\r\n# GUI\r\nclass WorkerSignals(QObject):\r\n '''defines signals from running worker thread\r\n '''\r\n finished = pyqtSignal()\r\n error = pyqtSignal(tuple)\r\n result = pyqtSignal(object)\r\n\r\n\r\nclass Worker(QRunnable):\r\n '''worker thread\r\n '''\r\n def __init__(self, fn, *args, **kwargs):\r\n super(Worker, self).__init__()\r\n self.fn = fn\r\n self.args = args\r\n self.kwargs = kwargs\r\n self.signals = WorkerSignals()\r\n # Add the callback to our kwargs\r\n self.kwargs['results'] = self.signals.result\r\n\r\n @pyqtSlot()\r\n def run(self):\r\n '''initialise runner function with passed args, kwargs\r\n '''\r\n try:\r\n result = self.fn(*self.args, **self.kwargs)\r\n except:\r\n traceback.print_exc()\r\n exctype, value = sys.exc_info()[:2]\r\n self.signals.error.emit((exctype, value, traceback.format_exc()))\r\n else:\r\n self.signals.result.emit(result)\r\n finally:\r\n self.signals.finished.emit()\r\n\r\n\r\nclass MainWindow(QMainWindow):\r\n\r\n def __init__(self, *args, **kwargs):\r\n super(MainWindow, self).__init__(*args, **kwargs)\r\n\r\n\r\n self.setWindowTitle(\"MCL Microstage Controller\")\r\n self.setFixedSize(300,300)\r\n\r\n self.generalLayout = QVBoxLayout()\r\n self._centralWidget = QWidget(self)\r\n self.setCentralWidget(self._centralWidget)\r\n self._centralWidget.setLayout(self.generalLayout)\r\n\r\n buttons = {'LED ON': (0, 0)\r\n }\r\n self._createButtons(buttons)\r\n\r\n\r\n self.show()\r\n self.threadpool = QThreadPool()\r\n print(\"Multithreading with maximum %d threads\" % self.threadpool.maxThreadCount())\r\n\r\n self.resetButtonsState()\r\n\r\n # Auxilary functions\r\n\r\n def _createButtons(self,buttons):\r\n self.buttons = {}\r\n buttonsLayout = QGridLayout()\r\n\r\n for btnText, pos in buttons.items():\r\n self.buttons[btnText] = QPushButton(btnText)\r\n self.buttons[btnText].setFixedSize(100,60)\r\n self.buttons[btnText].setCheckable(True)\r\n self.buttons[btnText].clicked.connect(self.getButtonsState) # when button clicked, get state\r\n buttonsLayout.addWidget(self.buttons[btnText], pos[0], pos[1])\r\n self.generalLayout.addLayout(buttonsLayout)\r\n\r\n # slots\r\n\r\n def getButtonsState(self):\r\n # read state of buttons and trigger actions\r\n state = []\r\n for btnText, pos in self.buttons.items():\r\n state.append(int(self.buttons[btnText].isChecked()))\r\n binstring = ''.join(['1' if x else '0' for x in state])\r\n\r\n # Write command\r\n INPUT = binstring \r\n if bool(int(INPUT)):\r\n print('LED on')\r\n CMD = 'CSN\\n'\r\n ser.write(CMD.encode())\r\n else:\r\n print('LED off')\r\n CMD = 'CSF\\n'\r\n ser.write(CMD.encode())\r\n \r\n def resetButtonsState(self):\r\n for btnText, pos in self.buttons.items():\r\n self.buttons[btnText].setChecked(False)\r\n\r\n\r\ndef handle_exit():\r\n ser.close()\r\n print('Port closed')\r\n\r\ndef main(ser):\r\n\r\n # Open port\r\n ser.open()\r\n print('Port open')\r\n # Make sure to close port on exit\r\n atexit.register(handle_exit)\r\n\r\n # here is the app running\r\n app = QApplication(sys.argv)\r\n\r\n window = MainWindow()\r\n window.show()\r\n\r\n sys.exit(app.exec_())\r\n\r\n\r\nif __name__=='__main__':\r\n main(ser)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"333996741","text":"#!/usr/bin/env python3\nimport os\nimport lab\nimport json\nimport copy\n\nimport pytest\n\nimport sys\nsys.setrecursionlimit(10000)\n\nTEST_DIRECTORY = os.path.join(os.path.dirname(__file__), 'test_inputs')\n\n## HELPER FUNCTIONS\n\ndef _open_case(casename):\n with open(os.path.join(TEST_DIRECTORY, casename + \".json\")) as f:\n cnf = json.load(f)\n res = [[(variable, polarity)\n for variable, polarity in clause]\n for clause in cnf]\n rev = [[(variable, polarity)\n for variable, polarity in clause[::-1]]\n for clause in cnf]\n rev_f = sorted(rev)\n s_f = res[::-1]\n s_f_2 = sorted(res, key=len)\n return res, rev, rev_f, s_f, s_f_2\n\ndef _satisfiable(cnf):\n assignment = lab.satisfying_assignment(copy.deepcopy(cnf))\n assert all(any(variable in assignment and assignment[variable] == polarity\n for variable, polarity in clause)\n for clause in cnf)\n\n\ndef _unsatisfiable(cnf):\n assignment = lab.satisfying_assignment(copy.deepcopy(cnf))\n assert assignment is None\n\n\ndef _test_from_file(casename, testfunc):\n for cnf in _open_case(casename):\n testfunc(cnf)\n\n\n## TESTS FOR SAT SOLVER\n\ndef test_sat_small_nested_backtrack():\n cnf = [[(\"a\",True), (\"b\",True)], [(\"a\",False), (\"b\",False), (\"c\",True)],\n [(\"b\",True),(\"c\",True)], [(\"b\",True),(\"c\",False)]]\n _satisfiable(cnf)\n\ndef test_sat_small_double_backtrack():\n # a will be guessed as True, which is wrong\n # then a both assignments on b will fail and cause a backtrack to a\n cnf = [[(\"a\",True),(\"b\",True)], [(\"a\",False),(\"b\",False),(\"c\",True)], [(\"b\",True),(\"c\",True)], [(\"b\",True),(\"c\",False)], [(\"a\",False),(\"b\",False),(\"c\",False)]]\n _satisfiable(cnf)\n\ndef test_sat_small_deep_double_backtrack():\n # a will be guessed as True, which is wrong\n # then a both assignments on b will fail and cause a backtrack to a\n cnf = [[(\"d\",True),(\"b\",True)],[(\"a\",True),(\"b\",True)], [(\"a\",False),(\"b\",False),(\"c\",True)], [(\"b\",True),(\"c\",True)], [(\"b\",True),(\"c\",False)], [(\"a\",False),(\"b\",False),(\"c\",False)]]\n _satisfiable(cnf)\n\ndef test_sat_small_deep_double_backtrack2():\n cnf = [[(\"d\",True),(\"b\",True)],[(\"a\",False),(\"b\",True)], [(\"a\",True),(\"b\",False),(\"c\",True)], [(\"b\",True),(\"c\",True)], [(\"b\",True),(\"c\",False)], [(\"a\",True),(\"b\",False),(\"c\",False)]]\n _satisfiable(cnf)\n\ndef test_sat_big_A():\n _test_from_file('A', _satisfiable)\n\ndef test_sat_big_B():\n _test_from_file('B', _satisfiable)\n\ndef test_sat_big_C():\n _test_from_file('C', _satisfiable) # irrelevancies\n\ndef test_sat_big_D():\n _test_from_file('D', _unsatisfiable)\n\ndef test_sat_big_E():\n _test_from_file('E', _unsatisfiable)\n\ndef test_sat_big_F():\n _test_from_file('F', _satisfiable)\n\ndef test_sat_big_G():\n _test_from_file('G', _unsatisfiable)\n\ndef test_sat_big_H():\n _test_from_file('H', _satisfiable)\n\ndef test_sat_big_I():\n _test_from_file('I', _satisfiable)\n\n\n# These three tests use your satisfying_assignment code to solve sudoku\n# puzzles (formulated as Boolean formulas).\n#\n# See http://www.cs.qub.ac.uk/~I.Spence/SuDoku/SuDoku.html for one\n# explanation of how to formulate a CNF formula for a sudoku puzzle.\n\n\ndef _get_sudoku(n):\n with open(os.path.join(TEST_DIRECTORY, 'sudoku%s.json' % n)) as f:\n return [[tuple(literal) for literal in clause] for clause in json.loads(f.read())]\n\n\ndef _run_sudoku_test(n, original):\n result = lab.satisfying_assignment(_get_sudoku(n))\n assert result is not None, \"There is a valid sudoku solution, but your code returned None.\"\n _check_sudoku(original, _assignment_to_grid(result))\n\n\ndef _assignment_to_grid(a):\n a = {k for k,v in a.items() if v}\n out = []\n for r in range(9):\n row = []\n for c in range(9):\n row.append([v+1 for v in range(9) if '%s_%s_%s' % (r, c, v) in a][0])\n out.append(row)\n return out\n\n\ndef _get_superblock(sr, sc):\n return {(r, c) for r in range(sr*3, (sr+1)*3) for c in range(sc*3, (sc+1)*3)}\n\n\ndef _check_sudoku(original, result):\n all_nums = set(range(1, 10))\n\n # all values from original must be preserved\n assert all((iv==jv or iv == 0) for i,j in zip(original, result) for iv, jv in zip(i, j))\n\n # all rows must contain the right values\n assert all(set(i) == all_nums for i in result)\n\n # all columns must contain the right values\n for c in range(9):\n assert set(i[c] for i in result) == all_nums\n\n # all superblocks must contain the right values\n for sr in range(3):\n for sc in range(3):\n assert set(result[r][c] for r, c in _get_superblock(sr, sc)) == all_nums\n\n\ndef test_sat_sudoku1():\n \"\"\"\n sudoku corresponding to the following board (0 denotes empty)\n \"\"\"\n original = [[5,1,7,6,0,0,0,3,4],\n [2,8,9,0,0,4,0,0,0],\n [3,4,6,2,0,5,0,9,0],\n [6,0,2,0,0,0,0,1,0],\n [0,3,8,0,0,6,0,4,7],\n [0,0,0,0,0,0,0,0,0],\n [0,9,0,0,0,0,0,7,8],\n [7,0,3,4,0,0,5,6,0],\n [0,0,0,0,0,0,0,0,0]]\n _run_sudoku_test(1, original)\n\n\ndef test_sat_sudoku2():\n \"\"\"\n sudoku corresponding to the following board (0 denotes empty)\n \"\"\"\n original = [[5,1,7,6,0,0,0,3,4],\n [0,8,9,0,0,4,0,0,0],\n [3,0,6,2,0,5,0,9,0],\n [6,0,0,0,0,0,0,1,0],\n [0,3,0,0,0,6,0,4,7],\n [0,0,0,0,0,0,0,0,0],\n [0,9,0,0,0,0,0,7,8],\n [7,0,3,4,0,0,5,6,0],\n [0,0,0,0,0,0,0,0,0]]\n _run_sudoku_test(2, original)\n\n\ndef test_sat_sudoku3():\n \"\"\"\n sudoku corresponding to the following board (0 denotes empty)\n (from http://www.extremesudoku.info/sudoku.html)\n \"\"\"\n original = [[0,0,1,0,0,9,0,0,3],\n [0,8,0,0,2,0,0,9,0],\n [9,0,0,1,0,0,8,0,0],\n [1,0,0,5,0,0,4,0,0],\n [0,7,0,0,3,0,0,5,0],\n [0,0,6,0,0,4,0,0,7],\n [0,0,8,0,0,5,0,0,6],\n [0,3,0,0,7,0,0,4,0],\n [2,0,0,3,0,0,9,0,0]]\n _run_sudoku_test(3, original)\n\n\n## TESTS FOR SCHEDULING\n\ndef _open_scheduling_case(casename):\n with open(os.path.join(TEST_DIRECTORY, casename + \".json\")) as f:\n v = json.load(f)\n return ({p[0] : p[1]\n for p in v[0].items()}, v[1])\n\n\ndef _scheduling_satisfiable(casename=None, students=None, sessions=None):\n if casename is not None:\n students, sessions = _open_scheduling_case(casename)\n formula = lab.boolify_scheduling_problem(copy.deepcopy(students),\n copy.deepcopy(sessions))\n sched = lab.satisfying_assignment(formula)\n assert sched is not None\n\n unplaced_students = set(students)\n\n for var, val in sched.items():\n if val:\n student, session = var.split('_')\n\n assert student in unplaced_students, \"Students should be assigned at most one session.\"\n unplaced_students.remove(student)\n\n assert student in students, \"This is not a valid student.\"\n assert session in sessions, \"This is not a valid session.\"\n\n assert session in students[student], \"Student should be assigned a desired session.\"\n\n assert sessions[session] >= 1, \"This session is over-capacity.\"\n sessions[session] -= 1\n\n assert not unplaced_students, \"Some students were not placed into a section!\"\n\n\ndef _scheduling_unsatisfiable(casename):\n students, sessions = _open_scheduling_case(casename)\n sched = lab.satisfying_assignment(\n lab.boolify_scheduling_problem(copy.deepcopy(students),\n copy.deepcopy(sessions)))\n assert sched is None\n\ndef test_scheduling_small():\n student_preferences = {\"Alice\": [\"session1\", \"session2\"], \"Bob\": [\"session3\"], \"Charles\": [\"session3\"]}\n room_capacities = {\"session1\": 1, \"session2\": 1, \"session3\": 3}\n _scheduling_satisfiable(None, student_preferences, room_capacities)\n\n\ndef test_scheduling_small_2():\n student_preferences = {\"student0\": [\"session1\", \"session0\"], \"student1\": [\"session1\", \"session2\"], \"student2\": [\"session2\"]}\n room_capacities = {\"session0\": 2, \"session2\": 2, \"session1\": 1}\n _scheduling_satisfiable(None, student_preferences, room_capacities)\n\ndef test_scheduling_A():\n _scheduling_satisfiable('A_Sat')\n\ndef test_scheduling_B():\n _scheduling_satisfiable('B_Sat')\n\ndef test_scheduling_C():\n _scheduling_unsatisfiable('C_Unsat')\n\ndef test_scheduling_D():\n _scheduling_satisfiable('D_Sat')\n\ndef test_scheduling_E():\n _scheduling_unsatisfiable('E_Unsat')\n\n\nif __name__ == '__main__':\n import os\n import sys\n import json\n import pickle\n import argparse\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--gather\", action='store_true')\n parser.add_argument(\"--server\", action='store_true')\n parser.add_argument(\"--initial\", action='store_true')\n parser.add_argument(\"args\", nargs=\"*\")\n\n parsed = parser.parse_args()\n\n\n class TestData:\n def __init__(self, gather=False):\n self.alltests = None\n self.results = {'passed': []}\n self.gather = gather\n\n @pytest.hookimpl(hookwrapper=True)\n def pytest_runtestloop(self, session):\n yield\n\n def pytest_runtest_logreport(self, report):\n if report.when != 'call':\n return\n self.results.setdefault(report.outcome, []).append(report.head_line)\n\n def pytest_collection_finish(self, session):\n if self.gather:\n self.alltests = [i.name for i in session.items]\n\n\n pytest_args = ['-v', __file__]\n\n if parsed.server:\n pytest_args.insert(0, '--color=yes')\n\n if parsed.gather:\n pytest_args.insert(0, '--collect-only')\n\n testinfo = TestData(parsed.gather)\n res = pytest.main(\n ['-k', ' or '.join(parsed.args), *pytest_args],\n **{'plugins': [testinfo]}\n )\n\n if parsed.server:\n _dir = os.path.dirname(__file__)\n if parsed.gather:\n with open(os.path.join(_dir, 'alltests.json'), 'w' if parsed.initial else 'a') as f:\n f.write(json.dumps(testinfo.alltests))\n f.write('\\n')\n else:\n with open(os.path.join(_dir, 'results.json'), 'w' if parsed.initial else 'a') as f:\n f.write(json.dumps(testinfo.results))\n f.write('\\n')\n","sub_path":"lab05-sat-solver/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":10523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"488513229","text":"if __name__ == \"__main__\": # noqa\n import matplotlib\n\n matplotlib.use(\"Agg\")\n\nimport matplotlib.pyplot as plt\nimport xarray as xr\n\nfrom .profile_calculation import FORCING_VARS\n\n\ndef main(ds):\n N_vars = len(FORCING_VARS)\n fig, axes = plt.subplots(nrows=N_vars, figsize=(10, 3 * N_vars), sharex=True)\n\n for v, ax in zip(FORCING_VARS, axes):\n v_adv = f\"d{v}dt_adv\"\n ds[v_adv].plot(ax=ax, y=\"level\")\n\n title = f\"{ds.name} {ds.trajectory_type} trajectory\\n{ds.domain_name} domain\\n\"\n if hasattr(ds, \"velocity_method\"):\n title += f\"{ds.velocity_method} velocity method using {ds.velocity_method_kwargs_height}m height\\n\"\n\n plt.suptitle(title, y=1.01)\n\n return fig\n\n\nif __name__ == \"__main__\":\n import argparse\n\n argparser = argparse.ArgumentParser()\n argparser.add_argument(\"forcing_profile.nc\")\n args = argparser.parse_args()\n\n input_filename = vars(args)[\"forcing_profile.nc\"]\n ds = xr.open_dataset(input_filename)\n fig = main(ds=ds)\n\n output_filename = input_filename.replace(\".nc\", \".png\")\n plt.savefig(output_filename, fig=fig, bbox_inches=\"tight\")\n print(f\"Saved plot to {output_filename}\")\n","sub_path":"lagtraj/forcings/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"295169832","text":"from custom.custom_models.neural_networks import *\nfrom aisy.sca_deep_learning_aes import AisyAes\n\naisy = AisyAes()\naisy.set_dataset(\"ascad-variable.h5\")\naisy.set_database_name(\"database_ascad_early_stopping.sqlite\")\naisy.set_aes_leakage_model(leakage_model=\"HW\", byte=2)\naisy.set_number_of_profiling_traces(100000)\naisy.set_number_of_attack_traces(2000)\naisy.set_batch_size(400)\naisy.set_epochs(25)\naisy.set_neural_network(mlp)\n\nearly_stopping = {\n \"metrics\": {\n \"accuracy\": {\n \"direction\": \"max\",\n \"class\": \"accuracy\",\n \"parameters\": []\n },\n \"loss\": {\n \"direction\": \"min\",\n \"class\": \"loss\",\n \"parameters\": []\n },\n \"number_of_traces\": {\n \"direction\": \"min\",\n \"class\": \"number_of_traces\",\n \"parameters\": []\n },\n \"success_rate\": {\n \"direction\": \"max\",\n \"class\": \"success_rate\",\n \"parameters\": []\n }\n }\n}\n\naisy.run(\n early_stopping=early_stopping,\n key_rank_attack_traces=1000\n)\n\nmetrics_validation = aisy.get_metrics_validation()\nfor metric in metrics_validation:\n print(\"{}: {}\".format(metric['metric'], metric['values']))\n","sub_path":"scripts/script_aes_custom_metrics.py","file_name":"script_aes_custom_metrics.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"527744648","text":"from typing import Dict\n\nfrom backend.utils.psyonix_api_handler import get_rank\n\n\nclass PlaylistRank:\n def __init__(self, name: str, rank: int, rating: int, streak: int = 0):\n self.name = name\n self.rank = rank\n self.rating = rating\n self.streak = streak\n\n\nclass PlayerRanks:\n def __init__(self, ranks: Dict[str, PlaylistRank]):\n if 'duel' in ranks and ranks['duel'] is not None:\n self.duel = ranks['duel'].__dict__\n else:\n self.duel = PlaylistRank(\"Unranked (div 1)\", 0, 0).__dict__\n if 'doubles' in ranks and ranks['doubles'] is not None:\n self.doubles = ranks['doubles'].__dict__\n else:\n self.doubles = PlaylistRank(\"Unranked (div 1)\", 0, 0).__dict__\n if 'standard' in ranks and ranks['standard'] is not None:\n self.standard = ranks['standard'].__dict__\n else:\n self.standard = PlaylistRank(\"Unranked (div 1)\", 0, 0).__dict__\n if 'hoops' in ranks and ranks['hoops'] is not None:\n self.hoops = ranks['hoops'].__dict__\n else:\n self.hoops = PlaylistRank(\"Unranked (div 1)\", 0, 0).__dict__\n if 'rumble' in ranks and ranks['rumble'] is not None:\n self.rumble = ranks['rumble'].__dict__\n else:\n self.rumble = PlaylistRank(\"Unranked (div 1)\", 0, 0).__dict__\n if 'dropshot' in ranks and ranks['dropshot'] is not None:\n self.dropshot = ranks['dropshot'].__dict__\n else:\n self.dropshot = PlaylistRank(\"Unranked (div 1)\", 0, 0).__dict__\n if 'snowday' in ranks and ranks['snowday'] is not None:\n self.snowday = ranks['snowday'].__dict__\n else:\n self.snowday = PlaylistRank(\"Unranked (div 1)\", 0, 0).__dict__\n if 'tournament' in ranks and ranks['tournament'] is not None:\n self.tournament = ranks['tournament'].__dict__\n else:\n self.tournament = PlaylistRank(\"Unranked (div 1)\", 0, 0).__dict__\n\n @staticmethod\n def create_from_id(id_: str) -> 'PlayerRanks':\n try:\n rank_datas = get_rank(id_)\n # print(rank_datas)\n player_rank_params = {\n rank_data['mode']: PlaylistRank(\n rank_data['string'],\n rank_data['tier'],\n rank_data['rank_points'],\n rank_data['streak'] if 'streak' in rank_data else 0\n )\n for playlist, rank_data in rank_datas.items()\n }\n return PlayerRanks(player_rank_params)\n except:\n return PlayerRanks(dict())\n","sub_path":"backend/blueprints/spa_api/service_layers/player/player_ranks.py","file_name":"player_ranks.py","file_ext":"py","file_size_in_byte":2642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"60157302","text":"# coding: utf-8\n# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department\n# Distributed under the terms of \"New BSD License\", see the LICENSE file.\n\nimport numpy as np\nimport re\nimport time\nfrom datetime import datetime\nfrom sqlalchemy import Column, create_engine, DateTime, Float, Integer, MetaData, String, Table, text, and_, or_\nfrom sqlalchemy.pool import NullPool\nfrom sqlalchemy.sql import select\nfrom sqlalchemy.exc import OperationalError, DatabaseError\n\n\"\"\"\nDatabaseAccess class deals with accessing the database\n\"\"\"\n\n__author__ = \"Murat Han Celik\"\n__copyright__ = \"Copyright 2019, Max-Planck-Institut für Eisenforschung GmbH\" \\\n \" - Computational Materials Design (CM) Department\"\n__version__ = \"1.0\"\n__maintainer__ = \"Jan Janssen\"\n__email__ = \"janssen@mpie.de\"\n__status__ = \"production\"\n__date__ = \"Sep 1, 2017\"\n\n\nclass AutorestoredConnection:\n def __init__(self, engine):\n self.engine = engine\n self._conn = None\n\n def execute(self, *args, **kwargs):\n try:\n if not self._conn or self._conn.closed:\n self._conn = self.engine.connect()\n result = self._conn.execute(*args, **kwargs)\n except OperationalError:\n time.sleep(5)\n result = self.execute(*args, **kwargs)\n return result\n\n def close(self):\n if self._conn is not None:\n self._conn.close()\n\n\nclass DatabaseAccess(object):\n \"\"\"\n A core element of PyIron, which generally deals with accessing the database: getting, sending, changing some data\n to the db.\n\n Args:\n connection_string (str): SQLalchemy connection string which specifies the database to connect to\n typical form: dialect+driver://username:password@host:port/database\n example: 'postgresql://scott:tiger@cmcent56.mpie.de/mdb'\n table_name (str): database table name, a simple string like: 'simulation'\n\n Murat Han Celik\n \"\"\"\n def __init__(self, connection_string, table_name):\n \"\"\"\n Initialize the Database connection\n\n Args:\n connection_string (str): SQLalchemy connection string which specifies the database to connect to\n typical form: dialect+driver://username:password@host:port/database\n example: 'postgresql://scott:tiger@cmcent56.mpie.de/mdb'\n table_name (str): database table name, a simple string like: 'simulation'\n \"\"\"\n self.table_name = table_name\n self._keep_connection = False\n self._sql_lite = 'sqlite' in connection_string\n try:\n if not self._sql_lite:\n self._engine = create_engine(connection_string,\n connect_args={'connect_timeout': 15},\n poolclass=NullPool)\n self.conn = AutorestoredConnection(self._engine)\n else:\n self._engine = create_engine(connection_string)\n self.conn = self._engine.connect()\n self.conn.connection.create_function(\"like\", 2, self.regexp)\n self._keep_connection = True\n except Exception as except_msg:\n raise ValueError(\"Connection to database failed: \" + str(except_msg))\n\n self.__reload_db()\n self.simulation_table = Table(str(table_name), self.metadata,\n Column('id', Integer, primary_key=True, autoincrement=True),\n Column('parentid', Integer),\n Column('masterid', Integer),\n Column('projectpath', String(50)),\n Column('project', String(255)),\n Column('job', String(50)),\n Column('subjob', String(255)),\n Column('chemicalformula', String(30)),\n Column('status', String(20)),\n Column('hamilton', String(20)),\n Column('hamversion', String(50)),\n Column('username', String(20)),\n Column('computer', String(100)),\n Column('timestart', DateTime),\n Column('timestop', DateTime),\n Column('totalcputime', Float),\n extend_existing=True)\n self.metadata.create_all()\n self._viewer_mode = False\n\n @property\n def viewer_mode(self):\n \"\"\"\n Get viewer_mode - if viewer_mode is enable pyiron has read only access to the database.\n\n Returns:\n bool: returns TRUE when viewer_mode is enabled\n \"\"\"\n return self._viewer_mode\n\n @viewer_mode.setter\n def viewer_mode(self, value):\n \"\"\"\n Set viewer_mode - if viewer_mode is enable pyiron has read only access to the database.\n\n Args:\n value (bool): TRUE or FALSE\n \"\"\"\n if isinstance(value, bool):\n self._viewer_mode = value\n else:\n raise TypeError('Viewmode can only be TRUE or FALSE.')\n\n # Internal functions\n def __del__(self):\n \"\"\"\n Close database connection\n\n Returns:\n\n \"\"\"\n if not self._keep_connection:\n self.conn.close()\n\n def __reload_db(self):\n \"\"\"\n Reload database\n\n Returns:\n\n \"\"\"\n self.metadata = MetaData(bind=self._engine)\n self.metadata.reflect(self._engine)\n\n @staticmethod\n def regexp(expr, item):\n \"\"\"\n Regex function for SQLite\n Args:\n expr: str, regex expression\n item: str, item which needs to be checked\n\n Returns:\n\n \"\"\"\n expr = expr.replace('%', '(.)*')\n expr = expr.replace('_', '.')\n expr = '^' + expr\n if expr[-1] is not '%':\n expr += '$'\n reg = re.compile(expr)\n if item is not None:\n return reg.search(item) is not None\n\n # Table functions\n def get_table_headings(self, table_name=None):\n \"\"\"\n Get column names\n\n Args:\n table_name (str): simple string of a table_name like: 'jobs_username'\n\n Returns:\n list: list of column names like:\n ['id',\n 'parentid',\n 'masterid',\n 'projectpath',\n 'project',\n 'job',\n 'subjob',\n 'chemicalformula',\n 'status',\n 'hamilton',\n 'hamversion',\n 'username',\n 'computer',\n 'timestart',\n 'timestop',\n 'totalcputime']\n \"\"\"\n if table_name is None:\n table_name = self.table_name\n self.__reload_db()\n try:\n simulation_list = Table(str(table_name), self.metadata, autoload=True, autoload_with=self._engine)\n except Exception:\n raise ValueError(str(table_name) + \" does not exist\")\n return [column.name for column in iter(simulation_list.columns)]\n\n def add_column(self, col_name, col_type):\n \"\"\"\n Add an additional column - required for modification on the database\n\n Args:\n col_name (str, list): name of the new column, normal string like: 'myColumn'\n col_type (str, list: SQL type of the new column, SQL type like: 'varchar(50)'\n\n Returns:\n\n \"\"\"\n if not self._viewer_mode:\n if isinstance(col_name, list):\n col_name = col_name[-1]\n if isinstance(col_type, list):\n col_type = col_type[-1]\n self._engine.execute('ALTER TABLE %s ADD COLUMN %s %s' % (self.simulation_table.name, col_name, col_type))\n else:\n raise PermissionError('Not avilable in viewer mode.')\n\n def change_column_type(self, col_name, col_type):\n \"\"\"\n Modify data type of an existing column - required for modification on the database\n\n Args:\n col_name (str, list): name of the new column, normal string like: 'myColumn'\n col_type (str, list: SQL type of the new column, SQL type like: 'varchar(50)'\n\n Returns:\n\n \"\"\"\n if not self._viewer_mode:\n if isinstance(col_name, list):\n col_name = col_name[-1]\n if isinstance(col_type, list):\n col_type = col_type[-1]\n self._engine.execute('ALTER TABLE %s ALTER COLUMN %s TYPE %s' % (self.simulation_table.name,\n col_name,\n col_type))\n else:\n raise PermissionError('Not avilable in viewer mode.')\n\n def get_items_sql(self, where_condition=None, sql_statement=None):\n \"\"\"\n Submit an SQL query to the database\n\n Args:\n where_condition (str): SQL where query, query like: \"project LIKE 'lammps.phonons.Ni_fcc%'\"\n sql_statement (str): general SQL query, normal SQL statement\n\n Returns:\n list: get a list of dictionaries, where each dictionary represents one item of the table like:\n [{u'chemicalformula': u'BO',\n u'computer': u'localhost',\n u'hamilton': u'VAMPS',\n u'hamversion': u'1.1',\n u'id': 1,\n u'job': u'testing',\n u'masterid': None,\n u'parentid': 0,\n u'project': u'database.testing',\n u'projectpath': u'/TESTING',\n u'status': u'KAAAA',\n u'subjob': u'testJob',\n u'timestart': u'2016-05-02 11:31:04.253377',\n u'timestop': u'2016-05-02 11:31:04.371165',\n u'totalcputime': 0.117788,\n u'username': u'User'},\n {u'chemicalformula': u'BO',\n u'computer': u'localhost',\n u'hamilton': u'VAMPS',\n u'hamversion': u'1.1',\n u'id': 2,\n u'job': u'testing',\n u'masterid': 0,\n u'parentid': 0,\n u'project': u'database.testing',\n u'projectpath': u'/TESTING',\n u'status': u'KAAAA',\n u'subjob': u'testJob',\n u'timestart': u'2016-05-02 11:31:04.253377',\n u'timestop': u'2016-05-02 11:31:04.371165',\n u'totalcputime': 0.117788,\n u'username': u'User'}.....]\n \"\"\"\n\n if where_condition:\n where_condition = where_condition.replace(\n 'like', 'similar to') if self._engine.dialect.name is \"postgresql\" else where_condition\n try:\n query = \"select * from \" + self.table_name + \" where \" + where_condition\n query.replace('%', '%%')\n result = self.conn.execute(text(query))\n except Exception as except_msg:\n print(\"EXCEPTION in get_items_sql: \", except_msg)\n raise ValueError(\"EXCEPTION in get_items_sql: \", except_msg)\n elif sql_statement:\n sql_statement = sql_statement.replace(\n 'like', 'similar to') if self._engine.dialect.name is \"postgresql\" else sql_statement\n # TODO: make it save against SQL injection\n result = self.conn.execute(text(sql_statement))\n else:\n result = self.conn.execute(text(\"select * from \" + self.table_name))\n row = result.fetchall()\n if not self._keep_connection:\n self.conn.close()\n\n # change the date of str datatype back into datetime object\n output_list = []\n for col in row:\n # ensures working with db entries, which are camel case\n timestop_index = [item.lower() for item in col.keys()].index('timestop')\n timestart_index = [item.lower() for item in col.keys()].index('timestart')\n tmp_values = col.values()\n if (col.values()[timestop_index] and col.values()[timestart_index]) is not None:\n # changes values\n try:\n tmp_values[timestop_index] = datetime.strptime(\n str(tmp_values[timestop_index]), '%Y-%m-%d %H:%M:%S.%f')\n tmp_values[timestart_index] = datetime.strptime(\n str(tmp_values[timestart_index]), '%Y-%m-%d %H:%M:%S.%f')\n except ValueError:\n print(\"error in: \", str(col))\n output_list += [dict(zip(col.keys(), tmp_values))]\n return output_list\n\n # Item functions\n def add_item_dict(self, par_dict):\n \"\"\"\n Create a new database item\n\n Args:\n par_dict (dict): Dictionary with the item values and column names as keys, like:\n {'chemicalformula': 'BO',\n 'computer': 'localhost',\n 'hamilton': 'VAMPS',\n 'hamversion': '1.1',\n 'job': 'testing',\n 'subjob' : 'SubJob',\n 'parentid': 0L,\n 'myCol': 'Blubbablub',\n 'project': 'database.testing',\n 'projectpath': '/root/directory/tmp',\n 'status': 'KAAAA',\n 'timestart': datetime(2016, 5, 2, 11, 31, 4, 253377),\n 'timestop': datetime(2016, 5, 2, 11, 31, 4, 371165),\n 'totalcputime': 0.117788,\n 'username': 'Test'}\n\n Returns:\n int: Database ID of the item created as an int, like: 3\n \"\"\"\n if not self._viewer_mode:\n try:\n par_dict = dict((key.lower(), value) for key, value in par_dict.items()) # make keys lowercase\n result = self.conn.execute(self.simulation_table.insert(par_dict)).inserted_primary_key[-1]\n if not self._keep_connection:\n self.conn.close()\n return result\n except Exception as except_msg:\n raise ValueError(\"Error occurred: \" + str(except_msg))\n else:\n raise PermissionError('Not avilable in viewer mode.')\n\n def __get_items(self, col_name, var):\n \"\"\"\n Get multiple items from the database\n\n Args:\n col_name (str): column to query for, like : 'id'\n var (str, int): value of the specific column, like: '2'\n\n ----> __get_items('id', '2')\n\n Returns:\n dict: Dictionary where the key is the column name, like:\n [{'chemicalformula': u'BO',\n 'computer': u'computer',\n 'hamilton': u'VAMPS',\n 'hamversion': u'1.1',\n ------>'id': 2,\n 'job': u'testing',\n 'parentid': 0,\n 'project': u'database.testing',\n 'projectpath': u'/root/directory/tmp',\n 'samucol': None,\n 'status': u'Testing',\n 'timestart': datetime.datetime(2016, 5, 2, 11, 31, 4, 253377),\n 'timestop': datetime.datetime(2016, 5, 2, 11, 31, 4, 371165),\n 'totalcputime': 0.117788,\n 'username': u'Test'}]\n \"\"\"\n try:\n if type(var) is list:\n var = var[-1]\n query = select([self.simulation_table], self.simulation_table.c[str(col_name)] == var)\n except Exception:\n raise ValueError(\"There is no Column named: \" + col_name)\n try:\n result = self.conn.execute(query)\n except (OperationalError, DatabaseError):\n if not self._sql_lite:\n self.conn = AutorestoredConnection(self._engine)\n else:\n self.conn = self._engine.connect()\n self.conn.connection.create_function(\"like\", 2, self.regexp)\n result = self.conn.execute(query)\n row = result.fetchall()\n if not self._keep_connection:\n self.conn.close()\n return [dict(zip(col.keys(), col.values())) for col in row]\n\n def item_update(self, par_dict, item_id):\n \"\"\"\n Modify Item in database\n\n Args:\n par_dict (dict): Dictionary of the parameters to be modified,, where the key is the column name.\n {'job' : 'maximize',\n 'subjob' : 'testing',\n ........}\n item_id (int, list): Database Item ID (Integer) - '38' can also be [38]\n\n Returns:\n\n \"\"\"\n if not self._viewer_mode:\n if type(item_id) is list:\n item_id = item_id[-1] # sometimes a list is given, make it int\n if np.issubdtype(type(item_id), np.integer):\n item_id = int(item_id)\n # all items must be lower case, ensured here\n par_dict = dict((key.lower(), value) for key, value in par_dict.items())\n query = self.simulation_table.update(self.simulation_table.c['id'] == item_id).values()\n try:\n self.conn.execute(query, par_dict)\n except (OperationalError, DatabaseError):\n if not self._sql_lite:\n self.conn = AutorestoredConnection(self._engine)\n else:\n self.conn = self._engine.connect()\n self.conn.connection.create_function(\"like\", 2, self.regexp)\n\n self.conn.execute(query, par_dict)\n if not self._keep_connection:\n self.conn.close()\n else:\n raise PermissionError('Not avilable in viewer mode.')\n\n def delete_item(self, item_id):\n \"\"\"\n Delete Item from database\n\n Args:\n item_id (int): Databse Item ID (Integer), like: 38\n\n Returns:\n\n \"\"\"\n if not self._viewer_mode:\n self.conn.execute(self.simulation_table.delete(self.simulation_table.c['id'] == int(item_id)))\n if not self._keep_connection:\n self.conn.close()\n else:\n raise PermissionError('Not avilable in viewer mode.')\n\n # Shortcut\n def get_item_by_id(self, item_id):\n \"\"\"\n Get item from database by searching for a specific item Id.\n\n Args:\n item_id (int): Databse Item ID (Integer), like: 38\n\n Returns:\n dict: Dictionary where the key is the column name, like:\n {'chemicalformula': u'BO',\n 'computer': u'localhost',\n 'hamilton': u'VAMPS',\n 'hamversion': u'1.1',\n 'id': 1,\n 'job': u'testing',\n 'masterid': None,\n 'parentid': 0,\n 'project': u'database.testing',\n 'projectpath': u'/root/directory/tmp',\n 'status': u'KAAAA',\n 'subjob': u'SubJob',\n 'timestart': datetime.datetime(2016, 5, 2, 11, 31, 4, 253377),\n 'timestop': datetime.datetime(2016, 5, 2, 11, 31, 4, 371165),\n 'totalcputime': 0.117788,\n 'username': u'Test'}\n \"\"\"\n # convert item_id to int type\n # needed since psycopg2 gives otherwise an error for np.int64 type (bigint in database)\n if item_id is None:\n return None\n if isinstance(item_id, (str, float)):\n item_id = int(item_id)\n if np.issubdtype(type(item_id), np.integer):\n try:\n return self.__get_items('id', int(item_id))[-1]\n except TypeError as except_msg:\n raise TypeError(\"Wrong data type given as parameter. item_id has to be Integer or String: \", except_msg)\n except IndexError as except_msg:\n raise IndexError(\"Error when trying to find elements by given Job ID: \", except_msg)\n else:\n raise TypeError('THE SQL database ID has to be an integer.')\n\n def query_for_element(self, element):\n return or_(\n *[self.simulation_table.c['chemicalformula'].like('%' + element +\n '[ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]%'),\n self.simulation_table.c['chemicalformula'].like('%' + element)])\n\n def get_items_dict(self, item_dict, return_all_columns=True):\n \"\"\"\n\n Args:\n item_dict (dict): a dict type, which has a certain syntax for this function:\n a normal dict like {'hamilton': 'VAMPE', 'hamversion': '1.1'} has similarities with a\n simple query like\n select * from table_name where hamilton = 'VAMPE AND hamversion = '1.1'\n as seen it puts an AND for every key, value combination in the dict and searches for it.\n\n another syntax is for an OR statement, simply: {'hamilton': ['VAMPE', 'LAMMPS']}, the\n query would be:\n select * from table_name where hamilton = 'VAMPE' OR hamilton = 'LAMMPS'\n\n and lastly for a LIKE statement, simply: {'project': 'database.%'}, the query would be\n select * from table_name where project LIKE 'database.%'\n that means you can simply add the syntax for a like statement like '%' and it will\n automatically operate a like-search\n\n of course you can also use a more complex select method, with everything in use:\n {'hamilton': ['VAMPE', 'LAMMPS'],\n 'project': 'databse%',\n 'hamversion': '1.1'}\n select * from table_name where (hamilton = 'VAMPE' Or hamilton = 'LAMMPS') AND\n (project LIKE 'database%') AND hamversion = '1.1'\n return_all_columns (bool): return all columns or only the 'id' - still the format stays the same.\n\n Returns:\n list: the function returns a list of dicts like get_items_sql, but it does not format datetime:\n [{'chemicalformula': u'Ni108',\n 'computer': u'mapc157',\n 'hamilton': u'LAMMPS',\n 'hamversion': u'1.1',\n 'id': 24,\n 'job': u'DOF_1_0',\n 'parentid': 21L,\n 'project': u'lammps.phonons.Ni_fcc',\n 'projectpath': u'D:/PyIron/PyIron_data/projects',\n 'status': u'finished',\n 'timestart': datetime.datetime(2016, 6, 24, 10, 17, 3, 140000),\n 'timestop': datetime.datetime(2016, 6, 24, 10, 17, 3, 173000),\n 'totalcputime': 0.033,\n 'username': u'test'},\n {'chemicalformula': u'Ni108',\n 'computer': u'mapc157',\n 'hamilton': u'LAMMPS',\n 'hamversion': u'1.1',\n 'id': 21,\n 'job': u'ref',\n 'parentid': 20L,\n 'project': u'lammps.phonons.Ni_fcc',\n 'projectpath': u'D:/PyIron/PyIron_data/projects',\n 'status': u'finished',\n 'timestart': datetime.datetime(2016, 6, 24, 10, 17, 2, 429000),\n 'timestop': datetime.datetime(2016, 6, 24, 10, 17, 2, 463000),\n 'totalcputime': 0.034,\n 'username': u'test'},.......]\n \"\"\"\n if not isinstance(item_dict, dict):\n raise TypeError(\"Wrong DataType! Only Dicts are usable!\")\n and_statement = [] # list for the whole sqlalchemy statement\n # here we go through all keys and values of item_dict\n for key, value in item_dict.items():\n # if a value of item_dict is a list, we have to make an or statement of it\n if key == 'element_lst':\n part_of_statement = [self.query_for_element(element=element) for element in value]\n elif isinstance(value, list):\n or_statement = [self.simulation_table.c[str(key)] == element\n if '%' not in element\n else self.simulation_table.c[str(key)].like(element)\n for element in value]\n # here we wrap the given values in an sqlalchemy-type or_statement\n part_of_statement = [or_(*or_statement)]\n else:\n if '%' not in str(value):\n part_of_statement = [self.simulation_table.c[str(key)] == value]\n else:\n part_of_statement = [self.simulation_table.c[str(key)].like(value)]\n # here all statements are wrapped together for the and statement\n and_statement += part_of_statement\n if return_all_columns:\n query = select([self.simulation_table], and_(*and_statement))\n else:\n query = select([self.simulation_table.columns['id']], and_(*and_statement))\n try:\n result = self.conn.execute(query)\n except (OperationalError, DatabaseError):\n if not self._sql_lite:\n self.conn = AutorestoredConnection(self._engine)\n else:\n self.conn = self._engine.connect()\n self.conn.connection.create_function(\"like\", 2, self.regexp)\n\n result = self.conn.execute(query)\n row = result.fetchall()\n if not self._keep_connection:\n self.conn.close()\n return [dict(zip(col.keys(), col.values())) for col in row]\n\n","sub_path":"pyiron/base/database/generic.py","file_name":"generic.py","file_ext":"py","file_size_in_byte":26586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"475615038","text":"from functools import cmp_to_key\nimport json\ndef jsons(filename):\n data = {}\n f1 = sortedFile('../app/static/icd91.txt')\n f2 = sortedFile('../app/static/icd92.txt')\n f3 = sortedFile('../app/static/icd93.txt')\n i1 = i2 = i3 = 0\n while i1 < len(f1):\n firstNum = f1[i1][:f1[i1].find('-')]\n secondNum = f1[i1][f1[i1].find('-')+1: f1[i1].find(' ')]\n cat1 = {}\n data[firstNum] = [f1[i1], cat1]\n while f2[i2][:f2[i2].find(\" \")] bInt:\n return 1\n else:\n return 0\n\ndef sortedFile(filename):\n myArr = []\n with open(filename) as f:\n for line in f:\n myArr.append(line.strip())\n return sorted(myArr, key = cmp_to_key(sort))\n\n\n\nif __name__ == '__main__':\n jsons('icd91.txt')\n","sub_path":"scraper/makeJSONs.py","file_name":"makeJSONs.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"579549951","text":"doors_closed = True\nlights_off = True\n\nalarm_codes = [\"1234\", \"4321\", \"0000\"]\nuser_code = \"123\"\n\nif not doors_closed:\n print(\"Please close the doors!\")\nelif not lights_off:\n print(\"Please turn the lights off\")\nelif user_code not in alarm_codes:\n print(user_code + \" is not the correct alarm code!\")\nelse:\n print(\"Good to go.\")\n","sub_path":"alarm.py","file_name":"alarm.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"113901265","text":"\"\"\"Tests for mritopng\"\"\"\n\nimport os\nimport uuid\nimport tempfile\nimport filecmp\nimport unittest\nimport mritopng\n\nclass TestMRIToPNG(unittest.TestCase):\n\n def test_no_syntax_errors(self):\n \"\"\" A dummy test to make sure the mritopng library got built \"\"\"\n if 'mri_to_png' not in dir(mritopng):\n self.fail()\n\n def test_convert_file(self):\n \"\"\" Tests conversion of a single DICOM file \"\"\"\n curr_path = os.path.dirname(os.path.realpath(__file__))\n sample_path = os.path.join(curr_path, 'data', 'samples', 'dicom1')\n expected_path = os.path.join(curr_path, 'data', 'expected', 'dicom1.png')\n actual_path = os.path.join(tempfile.gettempdir(), '%s.%s' % (uuid.uuid4(), \"png\"))\n\n print('Actual File Path: %s' % actual_path)\n\n # Try the file conversion\n try:\n mritopng.convert_file(sample_path, actual_path)\n except Exception as err:\n self.fail('%s' % err)\n\n self.assertTrue(filecmp.cmp(actual_path, expected_path),\n 'PNG generated from dicom1 does not match the expected version')\n","sub_path":"tests/test_mritopng.py","file_name":"test_mritopng.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"148249769","text":"# Given a sorted array of integers (including negatives),\n# return a sorted array of squares of those integers.\n# e.g. [-6, -4, 1, 2, 3 ,5] → [1, 4, 9, 16, 25, 36]\n\ndef sorted_squares(nums):\n \n len_n = len(nums)\n i = 0\n out_list = []\n while nums[i] < 0:\n i += 1\n # now i is the first 0 or positive num index (because it is already sorted)\n if i > 0:\n low = i-1\n high = i\n else: # all are positive\n return [n*n for n in nums]\n \n while low >= 0 and high < len_n:\n if abs(nums[low]) < abs(nums[high]):\n out_list.append(nums[low]**2)\n low -= 1\n else:\n out_list.append(nums[high]**2)\n high += 1\n \n if low < 0:\n while high < len_n:\n out_list.append(nums[high]**2)\n high += 1\n else:\n while low >= 0:\n out_list.append(nums[low]**2)\n low -= 1\n \n return out_list\n\n\nif __name__ == '__main__':\n nums = [-6, -4, 1, 2, 3 ,5] # [1, 4, 9, 16, 25, 36]\n\n print(sorted_squares(nums))","sub_path":"1 Numerics/1-13_sorted_squares.py","file_name":"1-13_sorted_squares.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"80875199","text":"# python3\n\n\nclass Query:\n def __init__(self, query):\n self.type = query[0]\n if self.type == 'check':\n self.ind = int(query[1])\n else:\n self.s = query[1]\n\n\nclass QueryProcessor:\n _multiplier = 263\n _prime = 1000000007\n\n def __init__(self, bucket_count):\n self.bucket_count = bucket_count\n # store all strings in one list\n self.elems = [[] for counter in range(bucket_count)]\n\n def _hash_func(self, s):\n ans = 0\n for c in reversed(s):\n ans = (ans * self._multiplier + ord(c)) % self._prime\n return ans % self.bucket_count\n\n def add_string(self, string):\n key = self._hash_func(string)\n if string in self.elems[key]:\n return\n else:\n self.elems[key].append(string)\n\n def del_string(self, string):\n key = self._hash_func(string)\n for ind, item in enumerate(self.elems[key]):\n if item == string:\n self.elems[key].pop(ind)\n break\n\n def find_string(self, string):\n key = self._hash_func(string)\n for item in self.elems[key]:\n if item == string:\n return True\n return False\n\n def check(self, i):\n return self.elems[i]\n\n def read_query(self):\n return Query(input().split())\n\n def write_search_result(self, was_found):\n print('yes' if was_found else 'no')\n\n def write_chain(self, chain):\n print(' '.join(reversed(chain)))\n\n def process_query(self, query):\n if query.type == \"check\":\n # use reverse order, because we append strings to the end\n self.write_chain(self.check(query.ind))\n else:\n if query.type == 'find':\n self.write_search_result(self.find_string(query.s))\n elif query.type == 'add':\n self.add_string(query.s)\n else:\n self.del_string(query.s)\n\n def process_queries(self):\n n = int(input())\n for i in range(n):\n self.process_query(self.read_query())\n\nif __name__ == '__main__':\n bucket_count = int(input())\n proc = QueryProcessor(bucket_count)\n proc.process_queries()\n","sub_path":"DataStructuresAndAlgorithmsSpecialization/course_2_DataStructures/hashTables/hash_chains.py","file_name":"hash_chains.py","file_ext":"py","file_size_in_byte":2226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"131912542","text":"'''ceci est un programme qui trace l orbite elliptique avec Euler'''\r\n\r\n#importation des mondules\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n#definir deux fonctions de du et de dv\r\ndef du(G,M,x,y):\r\n n1=(x**2)+(y**2)\r\n n2=G*M\r\n return (-n2*x)/(n1**(1.5))\r\n\r\ndef dv(G,M,x,y):\r\n n1=(x**2)+(y**2)\r\n n2=G*M\r\n return (-n2*y)/(n1**(1.5))\r\n\r\n\r\nh=1/3650 #le pas du temps\r\nG=4*((np.pi)**2) #constant\r\nM=1 #constant\r\nt=np.arange(0,5,h) #maille de temps\r\nnpas=t.shape[0] #nombre de pas\r\n\r\nx=np.zeros(npas) #creation du tableau vide x\r\ny=np.zeros(npas) #creation du tableau vide y\r\nu=np.zeros(npas) #creation du tableau vide u\r\nv=np.zeros(npas) #creation du tableau vide v\r\n\r\n#conditions initiales\r\nx[0]=0\r\ny[0]=-1\r\nu[0]=0.8*np.sqrt(G*M)\r\nv[0]=0 \r\n\r\n\r\n\r\n#boucle d integration par la methode Euler\r\nfor k in range(0,npas-1):\r\n \r\n x[k+1]=x[k]+h*u[k]\r\n u[k+1]=u[k]+h*du(G,M,x[k],y[k])\r\n y[k+1]=y[k]+h*v[k]\r\n v[k+1]=v[k]+h*dv(G,M,x[k],y[k])\r\n\r\n#tracer la courbe \r\nplt.plot(x,y,'b')\r\nplt.xlabel('x')\r\nplt.ylabel('y')\r\nplt.axis('equal')\r\nplt.show()\r\n#calculer la variation relative de l energie\r\nEt=0.5*(u**2+v**2)-(G*M/np.sqrt(x**2+y**2))\r\nvar=np.abs((Et-Et[0])/Et[0])\r\n","sub_path":"lab8/etoile_elliptique.py","file_name":"etoile_elliptique.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"83846562","text":"import os\nimport datetime\n\nlistOfLogFiles = []\nlistOfAllFiles = os.listdir(\"c:\\\\kurser\")\nfor filnamn in listOfAllFiles:\n if filnamn.find(\".log\") != -1:\n listOfLogFiles.append(filnamn)\n print(filnamn)\n\n\n\n\n\n\nwith open(\"c:\\\\logfile.txt\", \"a\") as myfile:\n myfile.write(f\"{datetime.datetime.now()} Nu startar Claes-scriptet\\n\")\n\n","sub_path":"demoFiler.py","file_name":"demoFiler.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"190886379","text":"from django.http import HttpResponse, HttpResponseNotFound\nfrom django.shortcuts import render\nfrom integrator.helper import serialize_integration\nfrom integrator.models import AuthenticationField, Integration\nfrom integrator.validate import validate_integration_form_data\nimport json\nfrom mongoengine.errors import NotUniqueError\n\n\ndef get_integrations(request):\n integrations = Integration.objects.all()\n context = {'integrations': integrations}\n return render(request, 'integrations.html', context)\n\ndef get_integration_detail(request, integration_id):\n try:\n integration = Integration.objects.get(name=integration_id)\n except Integration.DoesNotExist:\n return HttpResponseNotFound('

Page not found

')\n context = {'integration': integration}\n return render(request, 'integration.html', context)\n\ndef create_integration_form(request):\n return render(request, 'create_integration_form.html')\n\ndef create_integration(request):\n if not request.is_ajax():\n return HttpResponse(status=400)\n\n integration_data = {}\n for key, value in json.loads(request.body).iteritems():\n if value:\n integration_data[key] = value\n \n is_valid, errors = validate_integration_form_data(integration_data)\n if not is_valid:\n return HttpResponse(content=json.dumps(errors), content_type=\"application/json\", status=400)\n \n auth_field_list = integration_data.get('auth_field_list', {})\n if auth_field_list:\n del(integration_data['auth_field_list'])\n\n\n integration = Integration(**integration_data)\n for key, value in auth_field_list.iteritems():\n data = {'element': key}\n data.update(value)\n embedded_auth_field = AuthenticationField(**data)\n integration.authentication_configuration.append(embedded_auth_field)\n \n try:\n integration.save(force_insert=True)\n except NotUniqueError:\n errors = {'name': 'Integration with name '+ integration.name +' already exists'}\n return HttpResponse(content=json.dumps(errors), content_type=\"application/json\", status=400)\n\n #Need to do this to honor the json response that is expected by the ajax client\n return HttpResponse(status=200, content=json.dumps({}), content_type=\"application/json\")","sub_path":"integrator/views/ui/integration/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"167243977","text":"import tensorflow as tf\nimport os\nimport inspect\nfrom NNModels.GAN import GAN\nfrom NNModels.DNNClassifier import DNNClassifier\nfrom NNModels.nz_data_loader import NZDataLoader\nfrom NNModels.basel_data_loader import BaselDataLoader\nfrom NNModels.generated_data_source import GeneratedDataSource\nfrom NNModels.data_loader import DataLoader\nfrom helpers.data import make_roc_plot\n\n\ndef main(argv):\n if argv[1] == 'NZ':\n year = 2012\n data_loader = NZDataLoader(year)\n dataset_name = \"NZ\"\n elif argv[1] == 'basel':\n year = 20122015\n data_loader = BaselDataLoader(year, 'categorical_normalized_mixed_grouping')\n dataset_name = \"PATREC\"\n else:\n print(\"Invalid argument\")\n return -1\n\n # Get directories\n ROOT_DIR = os.path.dirname(os.path.abspath(inspect.stack()[0][1]))\n GAN_MODEL_DIR = ROOT_DIR + '/{}/models/GAN'.format(dataset_name)\n DNN_MODEL_DIR = ROOT_DIR + '/{}/models/gen_dnn'.format(dataset_name)\n PLOT_DIR = ROOT_DIR + '/{}/plots/gen_dnn'.format(dataset_name)\n GENERATED_DATA_DIR = ROOT_DIR + '/{}/data/generated'.format(dataset_name)\n\n if not os.path.exists(PLOT_DIR):\n os.makedirs(PLOT_DIR)\n\n if not os.path.exists(GENERATED_DATA_DIR):\n os.makedirs(GENERATED_DATA_DIR)\n\n # Get GAN\n # Configuration\n gan_config = dict()\n gan_config['model_dir'] = GAN_MODEL_DIR\n gan_config['random_sample_size'] = 100\n gan_config['gen_hidden_units'] = [128, 256]\n gan_config['data_dim'] = len(data_loader.get_header_list_with_label())\n gan_config['disc_hidden_units'] = [256, 128]\n gan_config['gen_learning_rate'] = 0.0001\n gan_config['disc_learning_rate'] = 0.0001\n gan_config['batch_size'] = 1000\n gan_config['label_smoothing'] = 0.9\n gan_config['num_disc_training_steps'] = 1\n gan_config['feature_matching'] = True\n gan_config['batch_normalization'] = False\n gan_config['batch_normalization_decay'] = 0.99\n gan_config['shortcuts_in_generator'] = False\n gan_config['minibatch_averaging'] = True\n gan_config['dropout_keep_prob'] = 0.9\n gan_config['learning_rate_decay'] = 0.98\n gan_config['gradient_summary'] = False\n gan_config['steps_per_epoch'] = 1 # Dummy value\n\n gan = GAN(gan_config)\n\n # Get DNN\n # Configuration\n dnn_config = dict()\n dnn_config['data_loader'] = data_loader\n dnn_config['hidden_units'] = [256, 128, 64]\n dnn_config['n_classes'] = 2\n dnn_config['model_dir'] = DNN_MODEL_DIR\n dnn_config['learning_rate'] = 0.001\n\n # Create the classifier object\n classifier = DNNClassifier(dnn_config)\n\n if argv[2] == 'train':\n print(\"training\")\n # Train the classifier using generated data\n for i in range(0, 50):\n # Generate some data\n generated_data = GeneratedDataSource(gan.sample(10000), data_loader.get_header_list_with_label(),\n data_loader.get_diagnosis_headers(), data_loader.get_procedure_headers(),\n data_loader.get_label_name(), data_loader.get_histogram_headers(),\n data_loader.get_barchart_headers(),\n True, data_loader.get_rounding_exception_columns())\n\n # Train the DNN using the generated data\n data_dict, labels = generated_data.get_packaged_data_and_labels()\n classifier.train(data_dict, labels, batch_size=100, epochs=1)\n elif argv[2] == 'eval':\n print(\"evaluating\")\n data_loader.load_data()\n eval_data, eval_labels = data_loader.get_packaged_data_by_type(DataLoader.TESTING_DATA)\n results = classifier.evaluate(eval_data, eval_labels)\n print(str(results))\n\n # Make ROC curve\n # Get the prediction probabilities\n probas = classifier.predict_proba(eval_data)\n\n # Make the plot\n make_roc_plot(eval_labels, probas, '{}/plot.png'.format(PLOT_DIR))\n\n elif argv[2] == 'generate':\n generated_data = GeneratedDataSource(gan.sample(480000), data_loader.get_header_list_with_label(),\n data_loader.get_diagnosis_headers(), data_loader.get_procedure_headers(),\n data_loader.get_label_name(), data_loader.get_histogram_headers(),\n data_loader.get_barchart_headers(),\n True, data_loader.get_rounding_exception_columns())\n\n generated_data.save(GENERATED_DATA_DIR, \"generated1\")\n\n\nif __name__ == '__main__':\n tf.logging.set_verbosity(tf.logging.INFO)\n tf.app.run(main)\n","sub_path":"generativeDNN.py","file_name":"generativeDNN.py","file_ext":"py","file_size_in_byte":4712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"624138899","text":"import Bicycles\n\nBrian=Bicycles.Customer(200)\nLori=Bicycles.Customer(500)\nHaley=Bicycles.Customer(1000)\n\nBMX=Bicycles.Bicycle(\"BMX bike\", 40, 60)\nRoad=Bicycles.Bicycle(\"Road Bike\", 20, 100)\nMountain=Bicycles.Bicycle(\"Mountain Bike\", 50, 30)\n\nBikestore1=Bicycles.Bikeshop(\"Brians Bikes\")\nprint(\"Brian has \"+str(Brian.budgetleft())+\" dollars left\")\nBikestore1.restock(BMX, 3)\nBikestore1.printinv()\nBikestore1.sell(BMX,Brian)\nprint(Brian.budgetleft())\nBikestore1.printinv()\nBikestore1.salesreport()\nprint(\"Brian has \"+str(Brian.budgetleft())+\" dollars left and a new \"+str(Brian.bike))","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"217221803","text":"\"\"\"Модуль содержит классы воинов\"\"\"\r\nimport random\r\nimport time\r\nclass Warrior():\r\n \"\"\"Класс Воин.\r\nКонструктор принимает данные имен лет и рассы\"\"\"\r\n def __init__ (self, name, age, race):\r\n \r\n self.name = name\r\n self.age = age\r\n self.race = race\r\n self.healthy = 100\r\n self.unhealthy = 20\r\n \r\n def info(self):\r\n \"\"\"Инструкция для вывода характеристик воина.\"\"\"\r\n time.sleep(0.6)\r\n print( \"Имя: \" + self.name )\r\n time.sleep(0.8)\r\n print( \"Возраст: \" + str( self.age ) )\r\n time.sleep(0.7)\r\n print( \"Раса: \" + self.race )\r\n time.sleep(0.8)\r\n print( \"Здоровье: \" + str( self.healthy ) )\r\n time.sleep(0.6)\r\n print()\r\n \r\n\r\n def fight(self):\r\n \r\n \"\"\"Инструкция для вычисления рандомного удара.\"\"\"\r\n rando = random.randint(1,2)\r\n x = rando\r\n \r\n if x == 1:\r\n print( \"<----------------------------------------------->\" )\r\n time.sleep(0.6)\r\n print( voin1.name, \", наносит удар игроку:\", voin2.name )\r\n time.sleep(0.7)\r\n print( \"Удар\" )\r\n time.sleep(0.9)\r\n print( \"Удар\" )\r\n time.sleep(0.6)\r\n print( \"Супер-удар\" )\r\n voin2.healthy -= self.unhealthy\r\n time.sleep(0.8)\r\n print( \"Здоровье \" + voin2.name + \" отнялось на: \" + str( self.unhealthy ) )\r\n print()\r\n time.sleep(0.7)\r\n print( \"Текущее здоровье \" + voin2.name + \": \" + str( voin2.healthy ) )\r\n print( \"<----------------------------------------------->\" )\r\n time.sleep(0.6)\r\n \r\n if voin2.healthy == 0:\r\n print(\"Здоровье игрока \" + voin2.name + \" закончилось!\")\r\n time.sleep(0.7)\r\n print()\r\n time.sleep(0.7)\r\n print(\"Победил: \" + voin1.name + \" со здоровьем: \" + str( voin1.healthy ) )\r\n time.sleep(0.7)\r\n print()\r\n print(\"Нажмите \\\"ENTER\\\" чтобы завершить сеанс.\")\r\n input()\r\n exit()\r\n \r\n elif x == 2:\r\n print( \"<----------------------------------------------->\" )\r\n time.sleep(0.6)\r\n print( voin2.name , \", наносит удар игроку:\" , voin1.name )\r\n time.sleep(0.7)\r\n print( \"Удар\" )\r\n time.sleep(0.9)\r\n print( \"Удар\" )\r\n time.sleep(0.6)\r\n print( \"Супер-удар\" )\r\n voin1.healthy -= self.unhealthy\r\n time.sleep(0.8)\r\n print( \"Здоровье \" + voin1.name + \" отнялось на: \" + str( self.unhealthy ) )\r\n print()\r\n time.sleep(0.7)\r\n print( \"Текущее здоровье \" + voin1.name + \": \" + str( voin1.healthy ) )\r\n print( \"<----------------------------------------------->\" )\r\n time.sleep(0.6)\r\n\r\n if voin1.healthy == 0:\r\n print(\"Здоровье игрока \" + voin1.name + \" закончилось!\")\r\n time.sleep(0.7)\r\n print()\r\n time.sleep(0.7)\r\n print(\"Победил: \" + voin2.name + \" со здровьем: \" + str( voin2.healthy ) )\r\n time.sleep(0.7)\r\n print()\r\n print(\"Нажмите \\\"ENTER\\\" чтобы завершить сеанс.\")\r\n input()\r\n exit()\r\n else:\r\n print(\"Такого варианта нет.\")\r\n exit()\r\n \r\n\"\"\"Входные данные\"\"\" \r\nvoin1 = Warrior( \"Захар\", 16, \"Воин Савхо��а\" )\r\nvoin2 = Warrior( \"Вадик\", 19, \"Колхозник\" )\r\n\"\"\"Для тех кто не в теме в консколь надо писать voin1.fight() или voin2.fight()\"\"\" \r\n","sub_path":"Warrior.py","file_name":"Warrior.py","file_ext":"py","file_size_in_byte":4281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"199416849","text":"import shutil\nimport os\nfrom app.main.config import get_config\nfrom flask import current_app\nfrom pathlib import Path\n\nfrom ..model.database import *\nfrom .response import *\n\nTEST_RESULTS_ROOT = 'test_results'\nUSER_SCRIPT_ROOT = 'user_scripts'\nBACK_SCRIPT_ROOT = 'back_scripts'\nTEST_PACKAGE_ROOT = 'pypi'\nUSERS_ROOT = Path(get_config().USERS_ROOT)\nUPLOAD_ROOT = Path(get_config().UPLOAD_ROOT)\nSTORE_ROOT = Path(get_config().STORE_ROOT)\ntry:\n os.makedirs(UPLOAD_ROOT)\nexcept FileExistsError:\n pass\ntry:\n os.makedirs(USERS_ROOT)\nexcept FileExistsError:\n pass\ntry:\n os.makedirs(STORE_ROOT)\nexcept FileExistsError:\n pass\n\ndef get_test_result_path(task):\n return get_test_results_root(task) / str(task.id)\n\ndef get_test_results_root(task=None, team=None, organization=None):\n if task:\n if team or organization:\n current_app.logger.error('team or organization should not used along wite task')\n return None\n organization = task.organization\n team = task.team\n\n result_dir = USERS_ROOT / organization.path\n if team:\n result_dir = result_dir / team.path\n result_dir = result_dir / TEST_RESULTS_ROOT\n return result_dir\n\ndef get_back_scripts_root(task=None, team=None, organization=None):\n if task:\n if team or organization:\n current_app.logger.error('team or organization should not used along wite task')\n return None\n organization = task.organization\n team = task.team\n\n result_dir = USERS_ROOT / organization.path\n if team:\n result_dir = result_dir / team.path\n result_dir = result_dir / BACK_SCRIPT_ROOT\n return result_dir\n\ndef get_user_scripts_root(task=None, team=None, organization=None):\n if task:\n if team or organization:\n current_app.logger.error('team or organization should not used along wite task')\n return None\n organization = task.organization\n team = task.team\n\n result_dir = USERS_ROOT / organization.path\n if team:\n result_dir = result_dir / team.path\n result_dir = result_dir / USER_SCRIPT_ROOT\n return result_dir\n\ndef get_upload_files_root(task):\n return UPLOAD_ROOT / task.upload_dir\n\ndef get_test_store_root(task=None, proprietary=False, team=None, organization=None):\n if task:\n organization = task.organization\n team = task.team\n proprietary = task.test.package.proprietary if task.test.package else False\n\n if not proprietary or (not team and not organization):\n return STORE_ROOT\n\n store_dir = USERS_ROOT / organization.path\n if team:\n store_dir = store_dir / team.path\n store_dir = store_dir / TEST_PACKAGE_ROOT\n return store_dir\n\ndef is_path_secure(path):\n drive, _ = os.path.splitdrive(path)\n if drive:\n return False\n if os.path.pardir in path or path.startswith('/'):\n return False\n return True\n","sub_path":"webserver/app/main/util/get_path.py","file_name":"get_path.py","file_ext":"py","file_size_in_byte":2916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"286222424","text":"from oslo.config import cfg\nfrom oslo import messaging\nimport socket\n\n\nCONF = cfg.CONF\n\nclass Service(object):\n \n version = '1.0'\n \n def __init__(self, topic, endpoints):\n self.hostname = socket.gethostname()\n self.topic = topic \n self.transport = messaging.get_transport(cfg.CONF)\n self.target = messaging.Target(topic=self.topic, server=self.hostname, version=self.version)\n self.endpoints = endpoints \n self.server = messaging.get_rpc_server(self.transport, self.target, self.endpoints)\n \n def start(self):\n self.server.start()\n \n def stop(self):\n self.server.stop()\n\n\ndef call(topic, ctxt, method, timeout=10, server=None, version='1.0', **kwargs):\n transport = messaging.get_transport(cfg.CONF)\n target = messaging.Target(topic=topic, server=server, version=version)\n client = messaging.RPCClient(transport, target)\n cctxt = client.prepare(timeout=timeout)\n return client.call(ctxt, method, **kwargs)\n\ndef cast(topic, ctxt, method, server=None, version='1.0', **kwargs):\n transport = messaging.get_transport(cfg.CONF)\n target = messaging.Target(topic=topic, server=server, version=version)\n client = messaging.RPCClient(transport, target)\n client.cast(ctxt, method, **kwargs)\n \ndef cast_fanout(topic, ctxt, method, version='1.0', **kwargs):\n transport = messaging.get_transport(cfg.CONF)\n target = messaging.Target(topic=topic, fanout=True, version=version)\n client = messaging.RPCClient(transport, target)\n client.cast(ctxt=ctxt, method=method, **kwargs)","sub_path":"server/rpc.py","file_name":"rpc.py","file_ext":"py","file_size_in_byte":1587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"159974645","text":"# dic = {\"及时雨\":\"宋江\",\"易大师\":\"剑圣\",\"维恩\":\"暗影猎手\"}\n# print(dic.keys())\n# for key in dic.keys():\n# print(key)\n\n# print(dic.values())\n# for value in dic.values():\n# print(value)\n\ndic = {\"及时雨\":\"宋江\",\"易大师\":\"剑圣\",\"维恩\":\"暗影猎手\"}\nprint(dic.items())\nfor item in dic.items():\n k,v = item\n print(k,v)\n # print(item[0])\n # print(item[1])\n\n#解构,捷报\n# a , b = 1 , 2\n# print(a)\n# print(b)\n\n# a , b , c = (\"麻花藤\",\"马云\",\"不知道\")","sub_path":"day05/dict常用操作.py","file_name":"dict常用操作.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"170683225","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('list/', views.career_list, name='career_list'),\n path('award/', views.award_list, name='award_list'),\n path('award/create/', views.award_create, name='award_create'),\n path('award/read//', views.award_read, name='award_read'),\n path('award/update//', views.award_update, name='award_update'),\n path('award/delete//', views.award_delete, name='award_delete'),\n]","sub_path":"kik_profile/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"51003941","text":"import csv\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nif __name__==\"__main__\":\n path=\"8.Advertising.csv\"\n data=pd.read_csv(path)\n x=data[['TV','Radio','Newspaper']]\n y=data['Sales']\n # print(x)\n # #tv=data['TV'] pandas Series对象\n # plt.plot(data['TV'],y,'ro',label='TV')\n # plt.plot(data['Radio'],y,'g^',label='Radio')\n # plt.plot(data['Newspaper'],y,'mv',label='Newspaper')\n # plt.legend(loc='lower right')\n # plt.grid()\n # plt.savefig('figure1.png')\n # plt.show()\n\n # plt.figure( figsize=(9,12) )\n # plt.subplot(311)\n # plt.plot(data['TV'],y,'ro')\n # plt.title('TV')\n # plt.grid()\n #\n # plt.subplot(312)\n # plt.plot(data['Radio'],y,'g^')\n # plt.title('Radio')\n # plt.grid()\n #\n # plt.subplot(313)\n # plt.plot(data['Newspaper'],y,'b*')\n # plt.title('Newspaper')\n # plt.grid()\n #\n # plt.tight_layout()\n # plt.savefig('figure2.png')\n # plt.show()\n\n print(type(y))#pandas.core.series.Series\n print(type(x))#pandas.core.frame.DataFrame\n x_train,x_test,y_train,y_test=train_test_split(x,y,random_state=1)\n linreg=LinearRegression()\n model=linreg.fit(x_train,y_train)\n print(model)\n print(linreg.coef_)\n print(linreg.intercept_)\n\n y_hat=linreg.predict(x_test)\n # print(y_hat)\n # print(type(y_hat))numpy.ndarray\n mse=np.average( (y_hat-np.array(y_test))**2 )\n rmse=np.sqrt(mse)\n print(\"mse\",mse,\" rmse\",rmse)\n t=np.arange(len(x_test))\n plt.plot(t,y_test,\"r-\",linewidth=2,label=\"Test\")\n plt.plot(t,y_hat,\"g-\",linewidth=2,label=\"Predict\")\n plt.legend(loc=\"upper right\")\n plt.grid()\n plt.savefig('figre3.png')\n plt.show()","sub_path":"07回归/8.1.Advertising.py","file_name":"8.1.Advertising.py","file_ext":"py","file_size_in_byte":1805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"450912428","text":"import logging\nimport os.path\nimport pkgutil\nimport sys\n\nfrom aiohttp import web\n\nfrom ..apis.aiohttp_api import AioHttpApi\nfrom ..exceptions import ConnexionException\nfrom .abstract import AbstractApp\n\nlogger = logging.getLogger('connexion.aiohttp_app')\n\n\nclass AioHttpApp(AbstractApp):\n\n def __init__(self, import_name, only_one_api=False, **kwargs):\n super(AioHttpApp, self).__init__(import_name, AioHttpApi, server='aiohttp', **kwargs)\n self._only_one_api = only_one_api\n self._api_added = False\n\n def create_app(self):\n return web.Application(**self.server_args)\n\n def get_root_path(self):\n mod = sys.modules.get(self.import_name)\n if mod is not None and hasattr(mod, '__file__'):\n return os.path.dirname(os.path.abspath(mod.__file__))\n\n loader = pkgutil.get_loader(self.import_name)\n filepath = None\n\n if hasattr(loader, 'get_filename'):\n filepath = loader.get_filename(self.import_name)\n\n if filepath is None:\n raise RuntimeError(\"Invalid import name '{}'\".format(self.import_name))\n\n return os.path.dirname(os.path.abspath(filepath))\n\n def set_errors_handlers(self):\n pass\n\n def add_api(self, specification, **kwargs):\n if self._only_one_api:\n if self._api_added:\n raise ConnexionException(\n \"an api was already added, \"\n \"create a new app with 'only_one_api=False' \"\n \"to add more than one api\"\n )\n else:\n self.app = self._get_api(specification, kwargs).subapp\n self._api_added = True\n return self.app\n\n api = self._get_api(specification, kwargs)\n try:\n self.app.add_subapp(api.base_path, api.subapp)\n except ValueError:\n raise ConnexionException(\n \"aiohttp doesn't allow to set empty base_path ('/'), \"\n \"use non-empty instead, e.g /api\"\n )\n\n return api\n\n def _get_api(self, specification, kwargs):\n return super(AioHttpApp, self).add_api(specification, **kwargs)\n\n def run(self, port=None, server=None, debug=None, host=None, **options):\n if port is not None:\n self.port = port\n elif self.port is None:\n self.port = 5000\n\n self.server = server or self.server\n self.host = host or self.host or '0.0.0.0'\n\n if debug is not None:\n self.debug = debug\n\n logger.debug('Starting %s HTTP server..', self.server, extra=vars(self))\n\n if self.server == 'aiohttp':\n logger.info('Listening on %s:%s..', self.host, self.port)\n\n access_log = options.pop('access_log', None)\n\n if options.pop('use_default_access_log', None):\n access_log = logger\n\n web.run_app(self.app, port=self.port, host=self.host, access_log=access_log, **options)\n else:\n raise Exception('Server {} not recognized'.format(self.server))\n","sub_path":"airflow/_vendor/connexion/apps/aiohttp_app.py","file_name":"aiohttp_app.py","file_ext":"py","file_size_in_byte":3059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"174784720","text":"from marshmallow.schema import BaseSchema\nfrom querystring_parser import parser as qs_parser\nfrom webargs import core\nfrom webargs.core import json, get_value, dict2schema\nfrom webargs.falconparser import FalconParser\n\n\nclass Parser(FalconParser):\n def parse(\n self,\n argmap,\n req=None,\n locations=None,\n validate=None,\n error_status_code=None,\n error_headers=None\n ):\n\n qs = '&'.join(part for part in req.query_string.split('&') if ('=' in part and part[-1] != '='))\n req._params = qs_parser.parse(qs)\n return super().parse(\n argmap,\n req=req,\n locations=locations,\n validate=validate,\n error_status_code=error_status_code,\n error_headers=error_headers\n )\n\n def parse_querystring(self, req, name, field):\n data = field.prepare_data(name, req.params) if hasattr(field, 'prepare_data') else req.params\n return core.get_value(data, name, field)\n\n def parse_json(self, req, name, field):\n json_data = self._cache.get(\"json_data\")\n if json_data is None:\n try:\n self._cache[\"json_data\"] = json_data = req.media\n except json.JSONDecodeError as e:\n return self.handle_invalid_json_error(e, req)\n return get_value(json_data, name, field, allow_many_nested=True)\n\n def _get_schema(self, argmap, req):\n if isinstance(argmap, BaseSchema):\n schema = argmap\n elif isinstance(argmap, type) and issubclass(argmap, BaseSchema):\n schema = argmap()\n elif callable(argmap):\n schema = argmap(req)\n else:\n schema = dict2schema(argmap, self.schema_class)()\n return schema\n","sub_path":"mcod/core/api/parsers.py","file_name":"parsers.py","file_ext":"py","file_size_in_byte":1802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"416062918","text":"\"\"\"Common settings and globals.\"\"\"\nimport os\n\nfrom datetime import timedelta\nfrom os.path import abspath, basename, dirname, join, normpath\nfrom os import environ\nfrom sys import path\n\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom djcelery import setup_loader\n\nROOT_PATH = os.path.dirname(__file__)\npath.append(ROOT_PATH)\n\nSITE_NAME = os.path.basename(ROOT_PATH)\nSITE_DOMAIN = SITE_NAME + \".com\"\n\n\n########## DEBUG CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#debug\nDEBUG = False\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug\nTEMPLATE_DEBUG = DEBUG\n########## END DEBUG CONFIGURATION\n\n\n########## MANAGER CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#admins\nADMINS = (\n ('Dang Nguyen', 'dangnguyen_1712@yahoo.com'),\n)\n\nADMINS_USERNAME = (\n \"dtn29\",\n \"dtn1712\",\n)\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#managers\nMANAGERS = ADMINS\n########## END MANAGER CONFIGURATION\n\nMANDRILL_API_KEY = environ.get(\"MANDRILL_API_KEY\") \nSERVER_EMAIL=environ.get('SERVER_EMAIL')\n\nEMAIL_BACKEND = \"djrill.mail.backends.djrill.DjrillBackend\"\nEMAIL_HOST = 'smtp.mandrillapp.com'\nEMAIL_HOST_USER = SERVER_EMAIL\nEMAIL_HOST_PASSWORD = environ.get('EMAIL_HOST_PASSWORD')\n\nEMAIL_PORT = 587\nEMAIL_USE_TLS = True\n\n########## GENERAL CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#time-zone\nTIME_ZONE = 'America/Los_Angeles'\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#language-code\nLANGUAGE_CODE = 'en-us'\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#site-id\nSITE_ID = 1\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n\nUSE_I18N = True\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-l10n\nUSE_L10N = True\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-tz\nUSE_TZ = True\n########## END GENERAL CONFIGURATION\n\n\n########## MEDIA CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root\nMEDIA_ROOT = os.path.join(ROOT_PATH, 'assets/media')\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url\nMEDIA_URL = '/media/'\n########## END MEDIA CONFIGURATION\n\n\n########## STATIC FILE CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root\nSTATIC_ROOT = 'staticfiles'\n\n# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS\nSTATICFILES_DIRS = (\n os.path.join(ROOT_PATH, 'assets/static'),\n)\n\n# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n 'compressor.finders.CompressorFinder',\n)\n########## END STATIC FILE CONFIGURATION\n\n\n########## SECRET CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key\nSECRET_KEY = \"chbrc3p7q%g9e80a(&bm$ci6ygdc_ak99q6ep90!#evq7yc@@@\"\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FIXTURE_DIRS\nFIXTURE_DIRS = (\n os.path.join(ROOT_PATH, 'fixtures'),\n)\n########## END FIXTURE CONFIGURATION\n\n\n########## TEMPLATE CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors\nTEMPLATE_CONTEXT_PROCESSORS = (\n 'django.contrib.auth.context_processors.auth',\n 'django.core.context_processors.debug',\n 'django.core.context_processors.i18n',\n 'django.core.context_processors.media',\n 'django.core.context_processors.static',\n 'django.core.context_processors.tz',\n 'django.contrib.messages.context_processors.messages',\n 'django.core.context_processors.request',\n 'django_mobile.context_processors.flavour',\n 'allauth.account.context_processors.account',\n \"allauth.socialaccount.context_processors.socialaccount\",\n \"soulightrd.apps.main.context_processors.site_data\",\n \"soulightrd.apps.main.context_processors.global_data\",\n)\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-loaders\nTEMPLATE_LOADERS = (\n \"django_mobile.loader.Loader\",\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n)\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs\nTEMPLATE_DIRS = (\n os.path.join(ROOT_PATH, 'assets/templates'),\n os.path.join(ROOT_PATH, 'assets/templates/sites'),\n os.path.join(ROOT_PATH, 'assets/templates/sites/non_responsive'),\n os.path.join(ROOT_PATH, 'assets/templates/sites/non_responsive/apps'),\n os.path.join(ROOT_PATH, 'assets/templates/sites/non_responsive/apps/auth'),\n os.path.join(ROOT_PATH, 'assets/templates/sites/responsive'),\n os.path.join(ROOT_PATH, 'assets/templates/sites/responsive/apps'),\n os.path.join(ROOT_PATH, 'assets/templates/sites/responsive/apps/auth'),\n)\n########## END TEMPLATE CONFIGURATION\n\n\n########## URL CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#root-urlconf\nROOT_URLCONF = '%s.urls' % SITE_NAME\n########## END URL CONFIGURATION\n\n\n########## APP CONFIGURATION\nDJANGO_APPS = (\n # Default Django apps:\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n\n # Useful template tags:\n 'django.contrib.humanize',\n\n # Admin panel and documentation:\n 'django.contrib.admin',\n 'django.contrib.admindocs',\n)\n\nTHIRD_PARTY_APPS = (\n # Allauth\n 'allauth',\n 'allauth.account',\n 'allauth.socialaccount',\n 'allauth.socialaccount.providers.facebook',\n \n # Database migration helpers:\n 'south',\n\n # Static file management:\n 'compressor',\n\n # Asynchronous task queue:\n 'djcelery',\n\n # Search\n \"haystack\",\n \n # Others\n \"dajaxice\",\n 'django_mobile',\n \"cities_light\",\n \"djmoney\",\n 'profiler',\n \"djrill\",\n 'sorl.thumbnail',\n 'crispy_forms',\n)\n\nLOCAL_APPS = (\n \"soulightrd.apps.alarm\",\n \"soulightrd.apps.about\",\n \"soulightrd.apps.auth\",\n \"soulightrd.apps.discover\",\n \"soulightrd.apps.mailer\",\n \"soulightrd.apps.main\",\n \"soulightrd.apps.member\",\n \"soulightrd.apps.message\",\n \"soulightrd.apps.notification\",\n \"soulightrd.apps.organization\",\n \"soulightrd.apps.payment\",\n \"soulightrd.apps.project\",\n \"soulightrd.apps.search\",\n)\n\nINSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS\n\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': True,\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n }\n },\n 'formatters': {\n 'verbose': {\n 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'\n },\n 'simple': {\n 'format': '%(levelname)s %(message)s'\n },\n },\n 'handlers': {\n 'null': {\n 'level': 'DEBUG',\n 'class': 'logging.NullHandler',\n },\n 'console':{\n 'level': 'DEBUG',\n 'class': 'logging.StreamHandler',\n 'formatter': 'simple'\n },\n 'mail_admins': {\n 'level': 'ERROR',\n 'filters': ['require_debug_false'],\n 'class': 'django.utils.log.AdminEmailHandler'\n },\n 'logfile_soulightrd': {\n 'level': 'DEBUG',\n 'class': 'logging.FileHandler',\n 'filename': os.path.join(ROOT_PATH, \"logs/soulightrd.log\"),\n }, \n 'logfile_dajaxice': {\n 'level': 'DEBUG',\n 'class': 'logging.FileHandler',\n 'filename': os.path.join(ROOT_PATH, \"logs/dajaxice.log\"),\n }, \n 'logfile_facebook': {\n 'level': 'DEBUG',\n 'class': 'logging.FileHandler',\n 'filename': os.path.join(ROOT_PATH, \"logs/django_facebook.log\"),\n },\n\n },\n 'loggers': {\n 'django': {\n 'handlers': ['null'],\n 'propagate': True,\n 'level': 'INFO',\n },\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n 'propagate': False,\n },\n 'dajaxice': {\n 'handlers': ['logfile_dajaxice'],\n 'level': 'ERROR',\n },\n 'django_facebook':{\n 'handlers': ['logfile_facebook'],\n 'level': 'DEBUG',\n },\n 'soulightrd': {\n 'handlers': ['logfile_soulightrd'],\n 'level': 'ERROR',\n },\n }, \n}\n\n\n########## CELERY CONFIGURATION\n# See: http://celery.readthedocs.org/en/latest/configuration.html#celery-task-result-expires\nCELERY_TASK_RESULT_EXPIRES = timedelta(minutes=30)\n\n# See: http://docs.celeryproject.org/en/master/configuration.html#std:setting-CELERY_CHORD_PROPAGATES\nCELERY_CHORD_PROPAGATES = True\n\n# See: http://celery.github.com/celery/django/\nsetup_loader()\n########## END CELERY CONFIGURATION\n\n\n########## WSGI CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application\nWSGI_APPLICATION = 'wsgi.application'\n########## END WSGI CONFIGURATION\n\n\n########## COMPRESSION CONFIGURATION\n# See: http://django_compressor.readthedocs.org/en/latest/settings/#django.conf.settings.COMPRESS_ENABLED\nCOMPRESS_ENABLED = True\n\n# See: http://django-compressor.readthedocs.org/en/latest/settings/#django.conf.settings.COMPRESS_CSS_HASHING_METHOD\nCOMPRESS_CSS_HASHING_METHOD = 'content'\n\n# See: http://django_compressor.readthedocs.org/en/latest/settings/#django.conf.settings.COMPRESS_CSS_FILTERS\nCOMPRESS_CSS_FILTERS = [\n 'compressor.filters.template.TemplateFilter',\n]\n\n# See: http://django_compressor.readthedocs.org/en/latest/settings/#django.conf.settings.COMPRESS_JS_FILTERS\nCOMPRESS_JS_FILTERS = [\n 'compressor.filters.template.TemplateFilter',\n]\n########## END COMPRESSION CONFIGURATION\n\n\n\nAUTH_PROFILE_MODULE = 'main.UserProfile'\n\nSERIALIZATION_MODULES = {\n 'json': \"django.core.serializers.json\",\n}\n\nAUTHENTICATION_BACKENDS = (\n 'allauth.account.auth_backends.AuthenticationBackend',\n 'django.contrib.auth.backends.ModelBackend', \n)\n\nACCOUNT_ACTIVATION_DAYS = 7\nACCOUNT_AUTHENTICATION_METHOD = 'email'\nACCOUNT_EMAIL_REQUIRED = True\nACCOUNT_USERNAME_REQUIRED = False\nACCOUNT_PASSWORD_MIN_LENGTH = 4\nACCOUNT_EMAIL_VERIFICATION = \"optional\"\n\n#HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'\n#HAYSTACK_DEFAULT_OPERATOR = 'OR'\n\nLOGIN_URL = '/accounts/login'\nLOGIN_REDIRECT_URL = '/'\nLOGOUT_REDIRECT_URL = '/'\n\nACCOUNT_LOGOUT_ON_GET = True\nACCOUNT_CONFIRM_EMAIL_ON_GET = True\nACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = \"/?action=confirm_email&result=success\"\n\nACCOUNT_USERNAME_BLACKLIST = [\n 'admin','signup','login','password',\"accounts\"\n 'logout','confirm_email','search','settings',\n 'buzz','messages',\"about\",'api','asset','photo',\n 'feeds','friends'\n]\n\nACCOUNT_EMAIL_SUBJECT_PREFIX = \"[SoulightRd]\"\nACCOUNT_ADAPTER = \"soulightrd.apps.auth.adapters.CustomAccountAdapter\"\n\nSOCIALACCOUNT_PROVIDERS = {\n 'facebook': {\n 'SCOPE': ['email', 'publish_stream',\"user_about_me\",\"user_birthday\",\"user_location\",\"user_events\",\"user_friends\",\"read_friendlists\"],\n 'METHOD': 'js_sdk',\n 'VERIFIED_EMAIL': False\n }\n}\n\n\nGEOIP_PATH = os.path.join(ROOT_PATH, \"db/geolocation\") ### path for geoip dat\n\nGEOIP_DATABASE = os.path.join(ROOT_PATH, \"db/geolocation/GeoLiteCity.dat\")\n\nCITIES_FILES = {\n 'city': {\n 'filename': 'cities1000.zip',\n 'urls': ['http://download.geonames.org/export/dump/'+'{filename}']\n },\n}\n\nSOCIALACCOUNT_ADAPTER = \"soulightrd.apps.auth.adapters.CustomSocialAccountAdapter\"\n\nSOCIAL_FRIENDS_USING_ALLAUTH = True\n\nMAX_MANDRILL_EMAIL_ALLOW = 12000\n\nOW_LY_API_KEY = \"6sv891CJpDcuiz8eyRHfy\"\n\nFACEBOOK_PROVIDER = \"facebook\"\nFACEBOOK_APP_NAME = \"SoulightRd Facebook App\"\n\nCRISPY_TEMPLATE_PACK = 'bootstrap3'\n\n\n\nSTAGE = \"dev\"\n\nDEBUG = True\n\nTEMPLATE_DEBUG = DEBUG\n\nWEBSITE_HOMEPAGE = \"http://localhost:8000/\"\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(ROOT_PATH, 'db/dev/soulightrd.db'),\n 'USER': '',\n 'PASSWORD': '',\n 'HOST': '',\n 'PORT': '',\n }\n}\n\n\n########## CACHE CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#caches\nCACHES = {\n 'default': {\n 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',\n }\n}\n########## END CACHE CONFIGURATION\n\n\n########## CELERY CONFIGURATION\n# See: http://docs.celeryq.org/en/latest/configuration.html#celery-always-eager\nCELERY_ALWAYS_EAGER = True\n\n# See: http://docs.celeryproject.org/en/latest/configuration.html#celery-eager-propagates-exceptions\nCELERY_EAGER_PROPAGATES_EXCEPTIONS = True\n########## END CELERY CONFIGURATION\n\n\n########## TOOLBAR CONFIGURATION\n# See: https://github.com/django-debug-toolbar/django-debug-toolbar#installation\nINSTALLED_APPS += (\n 'debug_toolbar',\n)\n\n# See: https://github.com/django-debug-toolbar/django-debug-toolbar#installation\nINTERNAL_IPS = ('127.0.0.1',)\n\nHAYSTACK_CONNECTIONS = {\n 'default': {\n 'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',\n 'PATH': os.path.join(ROOT_PATH, 'db/dev/whoosh_index'),\n 'INCLUDE_SPELLING': False,\n }\n}\n\nDEBUG_TOOLBAR_CONFIG = {\n 'INTERCEPT_REDIRECTS': False,\n}\n########## END TOOLBAR CONFIGURATION\n\nSTATIC_URL = '/static/'\n\n\nMIDDLEWARE_CLASSES = (\n # Use GZip compression to reduce bandwidth.\n 'django.middleware.gzip.GZipMiddleware',\n\n # Default Django middleware.\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django_mobile.middleware.MobileDetectionMiddleware',\n 'django_mobile.middleware.SetFlavourMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'debug_toolbar.middleware.DebugToolbarMiddleware',\n \"profiler.middleware.ProfileMiddleware\",\n \n)\n\nBROKER_URL = 'redis://localhost:6379/0'\nCELERY_RESULT_BACKEND = 'redis://localhost:6379/0'\n\nFACEBOOK_APP_ID = '1449654595310684'\nFACEBOOK_APP_SECRET = 'b78767a5b624cb510f0f1996be62d24b'\n\n\n","sub_path":"soulightrd/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":14242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"213504339","text":"import BaseHTTPServer\nimport urlparse\nimport sys\nimport subprocess\nimport time\nimport os\nimport xml.etree.ElementTree as etree\nimport json\n\nHOST = '127.0.0.1'\nPORT = 8080\nNIKTO_PATH = './nikto-master/program/'\n\nclass Utility(object):\n\n\t@classmethod\n\tdef get_queries(cls, path):\n\t\tif path[1] == '?':\n\t\t\tpairs = urlparse.parse_qs(path[2:])\n\t\t\tif pairs and 'host' in pairs and 'cgidirs' in pairs:\n\t\t\t\treturn [pairs['host'][0],pairs['cgidirs'][0]]\n\n\t@classmethod\n\tdef run_nikto(cls, args):\n\t\tcwd = os.getcwd()\n\t\tfile_path = '{0}/{1}.xml'.format(cwd, hex(int(time.time())))\n\t\tcmd = \"cd {0} && perl nikto.pl -h {1} -C {2} -o {3} -config {4}/nikto.conf\"\n\t\tformat_cmd = cmd.format(NIKTO_PATH, args[0], args[1], file_path, cwd)\n\t\tsubprocess.call(format_cmd, shell=True)\n\t\tresponse_xml = open(file_path).read()\n\t\tresponse_json = cls._parse_nikto(response_xml)\n\t\tos.remove(file_path)\n\t\treturn response_json\n\n\t@classmethod\n\tdef _parse_nikto(cls, xml):\n\t\troot = etree.fromstring(xml)\n\t\tparsed = { 'results': [] }\n\t\tfor item in root.findall('./niktoscan/scandetails/item'):\n\t\t\tparsed_item = { \"id\": item.attrib['id'] }\n\t\t\tfor child in item:\n\t\t\t\tparsed_item[child.tag] = child.text\n\t\t\tparsed['results'].append(parsed_item)\n\t\treturn json.dumps(parsed)\n\n\nclass Handler(BaseHTTPServer.BaseHTTPRequestHandler):\n\n\tdef do_GET(self):\n\t\targs = Utility.get_queries(self.path)\n\t\tif args:\n\t\t\tresponse_json = Utility.run_nikto(args)\n\t\t\tself.send_response(200)\n\t\t\tself.send_header('Content-type', 'text/json')\n\t\t\tself.end_headers()\n\t\t\tself.wfile.write(response_json)\n\t\telse:\n\t\t\tself.send_response(400)\n\t\t\tself.send_header('Content-type', 'text/plain')\n\t\t\tself.end_headers()\n\t\t\tself.wfile.write('Error 400: Bad Request')\n\n\ndef main():\n\tRequestHandlerClass = Handler\n\tserver = BaseHTTPServer.HTTPServer((HOST, PORT), Handler)\n\ttry:\n\t\tserver.serve_forever()\n\texcept KeyboardInterrupt:\n\t pass\n\tserver.server_close()\n\nif __name__ == '__main__':\n main()\n","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"334099392","text":"\nfrom flask import Flask, jsonify, request, json\nfrom src.branches_controller import *\nfrom src.login_controller import *\nfrom src.packages_controller import *\nfrom src.manager_controller import *\nfrom src.admin_controller import *\nfrom src.register_controller import *\nfrom src.info_controller import *\n\napp = Flask(__name__)\n\n@app.route(\"/ask_branches\", methods=['GET'])\ndef get_branches_handler():\n\tresponse = get_branches()\n\treturn jsonify( response )\n\n@app.route(\"/branches\", methods=['POST'])\ndef get_branch_handler():\n\tjson_request = request.get_json(force=True)\n\tbranch_name_str = json_request['id']\n\tresponse = get_branch( branch_name_str )\n\treturn jsonify( response)\n\n@app.route(\"/login\", methods=['POST'])\ndef post_login_handler():\n\tjson_request = request.get_json(force=True)\n\tusername_str = json_request['username']\n\tpassword_str = json_request['password']\n\tid_branch_int = json_request['id_branch']\n\tresponse = user_login( username_str, password_str )\n\tresponse2 = get_branch( id_branch_int )\n\tresponse3 = \"NONE\"\n\tif( response[\"status\"] == 100 ):\n\t\tresponse3 = get_packages_by_id_client( response[\"data\"][\"id\"], id_branch_int )\n\tif( response[\"status\"] == 101 ):\n\t\tresponse3 = get_packages_by_branch( id_branch_int )\n\treturn jsonify( {\"status\":response[\"status\"], \n\t\t\t\t\t\"data\":response[\"data\"],\n\t\t\t\t\t\"branch\":response2[\"data\"],\n\t\t\t\t\t\"packages\":response3 } )\n\n@app.route(\"/manager\", methods=['POST'])\ndef info_manager_total_handler():\n\tjson_request = request.get_json(force=True)\n\toperation = json_request['operation']\n\tresponse = {\"status\":404,\"data\":\"Operation doesn't exist\"}\n\tif( operation == 1 ):\n\t\tid_branch_int = json_request['branch']\n\t\tdate_min = json_request['date_min']\n\t\tdate_max = json_request['date_max']\n\t\tresponse = get_total_manager( id_branch_int, date_min, date_max )\n\t\tresponse = {\"status\":200, \"data\":response}\n\telif( operation == 2 ):\n\t\tdate_min = json_request['date_min']\n\t\tdate_max = json_request['date_max']\n\t\tresponse = get_3_top_clients( date_min, date_max )\n\t\tresponse = {\"status\":200, \"data\":response}\n\treturn jsonify(response)\n\n@app.route(\"/admin\", methods=['POST'])\ndef admin_handler():\n\tjson_request = request.get_json(force=True)\n\toperation = json_request['operation']\n\tresponse = {\"status\":404,\"data\":\"Operation doesn't exist\"}\n\tif( operation == 1 ):\n\t\ttype_int = json_request['type']\n\t\tdate_min = json_request['date_min']\n\t\tdate_max = json_request['date_max']\n\t\tresponse = get_total_by_type( type_int, date_min, date_max )\n\t\tresponse = {\"status\":200,\"data\":response}\n\telif( operation == 2 ):\n\t\tbranch = json_request['branch']\n\t\tresponse = get_total_amount( branch )\n\t\tresponse = {\"status\":200,\"data\":response}\n\telif( operation == 3 ):\n\t\tdate_min = json_request['date_min']\n\t\tdate_max = json_request['date_max']\n\t\tresponse = get_packages_per_client( date_min, date_max )\n\t\tresponse = {\"status\":200,\"data\":response}\n\telif( operation == 4 ):\n\t\tdate_min = json_request['date_min']\n\t\tdate_max = json_request['date_max']\n\t\tresponse = get_avg_packages( date_min, date_max )\n\t\tresponse = {\"status\":200,\"data\":response}\n\treturn jsonify(response)\n\n@app.route(\"/register\", methods=['POST'])\ndef register_handler():\n\tjson_request = request.get_json(force=True)\n\tclient_id = json_request['id']\n\tname = json_request['name']\n\tlname = json_request['lname']\n\ttelephone = json_request['telephone']\n\tusername = json_request['username']\n\tpassword = json_request['password']\n\tclient_type = json_request['type']\n\tprovince = json_request['province']\n\tresponse = create_user( client_id,\n\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\tlname,\n\t\t\t\t\t\t\ttelephone,\n\t\t\t\t\t\t\tusername,\n\t\t\t\t\t\t\tpassword,\n\t\t\t\t\t\t\tclient_type,\n\t\t\t\t\t\t\tprovince )\n\treturn jsonify(response)\n\n@app.route(\"/new_package\", methods=['POST'])\ndef new_package_handler():\n\tjson_request = request.get_json(force=True)\n\tclient_id = json_request['id']\n\treception_date = json_request['reception_date']\n\ttype_package = json_request['type']\n\tweight = json_request['weight']\n\tdescription = json_request['description']\n\tvalue = json_request['value']\n\tbranch = json_request['branch']\n\tresponse = new_package(\tclient_id,\n\t\t\t\t\t\t\treception_date,\n\t\t\t\t\t\t\ttype_package,\n\t\t\t\t\t\t\tweight,\n\t\t\t\t\t\t\tdescription,\n\t\t\t\t\t\t\tvalue,\n\t\t\t\t\t\t\tbranch )\n\treturn jsonify(response)\n\n@app.route(\"/package\", methods=['POST'])\ndef update_package_handler():\n\tjson_request = request.get_json(force=True)\n\tpackage = json_request['package_id']\n\tdelivery_date = json_request['delivery_date']\n\tresponse = update_package( package, delivery_date )\n\treturn jsonify(response)\n\n@app.route(\"/ask_types\", methods=['GET'])\ndef ask_types_handler():\n\tresponse = get_types()\n\treturn jsonify({\"status\":200,\"data\":response})\n\n\nif __name__ == \"__main__\":\n\t#app.debug = True\t\t# Release server\n\tapp.debug = True\t\t# For debugging purposes\n\tapp.run( host = '0.0.0.0', port=8080, processes=True )\n\n","sub_path":"aplicacion/api_server.py","file_name":"api_server.py","file_ext":"py","file_size_in_byte":4788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"216948320","text":"#!/usr/bin/env python3\n\"\"\"Instantiates and runs the Listener class. Try\n\n listen.py --help\n\nfor details.\n\nExamples:\n\n logger/listener/listen.py \\\n --logfile test/nmea/NBP1700/s330/raw/NBP1700_s330 \\\n --interval 0.25 \\\n --transform_slice 1: \\\n --transform_timestamp \\\n --transform_prefix s330 \\\n --write_file -\n\n(Reads lines from the Seapath300 sample logfiles every 0.25 seconds,\nstrips the old timestamps off, prepends a new one, then the prefix\n's330', then writes the result to stdout.)\n\n logger/listener/listen.py \\\n --config_file test/configs/simple_logger.json\n\n(Instantiates logger from config file that says to read from the\nproject's LICENSE file, prepend a timestamp and the string \"license:\"\nand writ to stdout every 0.2 seconds.)\n\nThe listen.py script is essentially a form of 'cat' on steroids,\nreading records from files, serial or network ports, modifying what it\nreceives, then writing it back out to somewhere else.\n\nFor fun, you can even run listen.py as an Ouroboros script, feeding it on its\nown output:\n\n echo x > tmp\n listen.py --file tmp --prefix p --write_file tmp --tail --interval 1 -v -v\n\n\"\"\"\nimport argparse\nimport logging\nimport re\nimport sys\nimport time\n\nsys.path.append('.')\n\nfrom logger.readers.composed_reader import ComposedReader\nfrom logger.readers.logfile_reader import LogfileReader\nfrom logger.readers.network_reader import NetworkReader\nfrom logger.readers.serial_reader import SerialReader\nfrom logger.readers.text_file_reader import TextFileReader\nfrom logger.readers.database_reader import DatabaseReader\nfrom logger.readers.timeout_reader import TimeoutReader\n\nfrom logger.transforms.prefix_transform import PrefixTransform\nfrom logger.transforms.regex_filter_transform import RegexFilterTransform\nfrom logger.transforms.qc_filter_transform import QCFilterTransform\nfrom logger.transforms.slice_transform import SliceTransform\nfrom logger.transforms.timestamp_transform import TimestampTransform\nfrom logger.transforms.parse_nmea_transform import ParseNMEATransform\nfrom logger.transforms.xml_aggregator_transform import XMLAggregatorTransform\nfrom logger.transforms.true_winds_transform import TrueWindsTransform\nfrom logger.transforms.derived_data_transform import DerivedDataTransform\nfrom logger.transforms.derived_data_transform import ComposedDerivedDataTransform\n\nfrom logger.writers.composed_writer import ComposedWriter\nfrom logger.writers.network_writer import NetworkWriter\nfrom logger.writers.text_file_writer import TextFileWriter\nfrom logger.writers.logfile_writer import LogfileWriter\nfrom logger.writers.database_writer import DatabaseWriter\nfrom logger.writers.record_screen_writer import RecordScreenWriter\n\nfrom logger.utils import read_json, timestamp\nfrom logger.listener.listener import Listener\n\n################################################################################\nclass ListenerFromLoggerConfig(Listener):\n \"\"\"Helper class for instantiating a Listener object from a Python dict.\"\"\"\n ############################\n def __init__(self, config):\n \"\"\"Create a Listener from a Python config dict.\"\"\"\n kwargs = self._kwargs_from_config(config)\n super().__init__(**kwargs)\n\n ############################\n def _kwargs_from_config(self, config_json):\n \"\"\"Parse a kwargs from a JSON string, making exceptions for keywords\n 'readers', 'transforms', and 'writers' as internal class references.\"\"\"\n kwargs = {}\n for key, value in config_json.items():\n\n # Declaration of readers, transforms and writers. Note that the\n # singular \"reader\" is a special case for TimeoutReader that\n # takes a single reader.\n if key in ['reader', 'readers', 'transforms', 'writers']:\n kwargs[key] = self._class_kwargs_from_config(value)\n\n # If value is a simple float/int/string/etc, just add to keywords\n elif type(value) in [float, bool, int, str, list]:\n kwargs[key] = value\n\n # Else what do we have?\n else:\n raise ValueError('unexpected key:value in configuration: '\n '{}: {}'.format(key, str(value)))\n return kwargs\n\n ############################\n def _class_kwargs_from_config(self, class_json):\n \"\"\"Parse a class's kwargs from a JSON string.\"\"\"\n if not type(class_json) in [list, dict]:\n raise ValueError('class_kwargs_from_config expected dict or list; '\n 'got: \"{}\"'.format(class_json))\n\n # If we've got a list, recurse on each element\n if type(class_json) is list:\n return [self._class_kwargs_from_config(c) for c in class_json]\n\n # Get name and constructor for component we're going to instantiate\n class_name = class_json.get('class', None)\n if class_name is None:\n raise ValueError('missing \"class\" definition in \"{}\"'.format(class_json))\n class_const = globals().get(class_name, None)\n if not class_const:\n raise ValueError('No component class \"{}\" found: \"{}\"'.format(\n class_name, class_json))\n\n # Get the keyword args for the component\n kwarg_dict = class_json.get('kwargs', {})\n kwargs = self._kwargs_from_config(kwarg_dict)\n if not kwargs:\n logging.info('No kwargs found for component {}'.format(class_name))\n\n # Instantiate!\n logging.info('Instantiating {}({})'.format(class_name, kwargs))\n component = class_const(**kwargs)\n return component\n\n################################################################################\nclass ListenerFromLoggerConfigFile(ListenerFromLoggerConfig):\n \"\"\"Helper class for instantiating a Listener object from a JSON config.\"\"\"\n ############################\n def __init__(self, config_file):\n \"\"\"Create a Listener from a Python config file.\"\"\"\n config = read_json.read_json(config_file)\n super().__init__(config)\n\n################################################################################\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n epilog='Note that arguments are parsed and applied IN ORDER, so if you '\n 'want a flag like --tail to be applied to a reader, or --slice_separator '\n 'to be applied to --transform_slice, it must appear before that reader on '\n 'the command line. Similarly, transforms will be added to the queue and '\n 'applied in the order they appear on the command line; multiple '\n 'specifications of a reader, writer or transform will result in multiple '\n 'instances of it being created. Trust us, that\\'s a feature.'\n )\n\n ############################\n # Set up from config file\n parser.add_argument('--config_file', dest='config_file', default=None,\n help='Read Listener configuration from JSON file. If '\n 'specified, no other command line arguments (except '\n '-v) are allowed.')\n\n ############################\n # Readers\n parser.add_argument('--network', dest='network', default=None,\n help='Comma-separated network addresses to read from')\n\n parser.add_argument('--database', dest='database', default=None,\n help='Format: user@host:database:field1,field2,... '\n 'Read specified fields from database. If no fields are '\n 'specified, read all fields in database. Should '\n 'be accompanied by the --database_password flag.')\n\n parser.add_argument('--file', dest='file', default=None,\n help='Comma-separated files to read from in parallel. '\n 'Note that wildcards in a filename will be expanded, '\n 'and the resulting files read sequentially. A single '\n 'dash (\\'-\\') will be interpreted as stdout.')\n\n parser.add_argument('--logfile', dest='logfile', default=None,\n help='Comma-separated logfile base filenames to read '\n 'from in parallel. Logfile dates will be added '\n 'automatically.')\n\n parser.add_argument('--logfile_use_timestamps', dest='logfile_use_timestamps',\n action='store_true', default=False,\n help='Make LogfileReaders deliver records at intervals '\n 'corresponding to the intervals indicated by the stored '\n 'record timestamps.')\n\n parser.add_argument('--serial', dest='serial', default=None,\n help='Comma-separated serial port spec containing at '\n 'least port=[port], but also optionally baudrate, '\n 'timeout, max_bytes and/or other SerialReader '\n 'parameters.')\n\n parser.add_argument('--interval', dest='interval', type=float, default=0,\n help='Number of seconds between reads')\n\n parser.add_argument('--tail', dest='tail',\n action='store_true', default=False, help='Do not '\n 'exit after reading file EOF; continue to check for '\n 'additional input.')\n\n parser.add_argument('--refresh_file_spec', dest='refresh_file_spec',\n action='store_true', default=False, help='When at EOF '\n 'and --tail is specified, check for new matching files '\n 'that may have appeared since our last attempt to read.')\n\n ############################\n # Transforms\n parser.add_argument('--transform_prefix', dest='prefix', default='',\n help='Prefix each record with this string')\n \n parser.add_argument('--transform_timestamp', dest='timestamp',\n action='store_true', default=False,\n help='Timestamp each record as it is read')\n\n parser.add_argument('--transform_slice', dest='slice', default='',\n help='Return only the specified (space-separated) '\n 'fields of a text record. Can be comma-separated '\n 'integer values and/or ranges, e.g. \"1,3,5:7,-1\". '\n 'Note: zero-base indexing, so \"1:\" means \"start at '\n 'second element.')\n\n parser.add_argument('--slice_separator', dest='slice_separator', default=' ',\n help='Field separator for --slice.')\n\n parser.add_argument('--transform_regex_filter', dest='regex_filter',\n default='',\n help='Only pass records containing this regex.')\n\n parser.add_argument('--transform_qc_filter', dest='qc_filter',\n default='', help='Pass nothing unless the fields in the '\n 'received DASRecord exceed comma-separated '\n ':: bounds.')\n\n parser.add_argument('--transform_parse_nmea', dest='parse_nmea',\n action='store_true', default=False,\n help='Convert tagged, timestamped NMEA records into '\n 'Python DASRecords.')\n\n parser.add_argument('--time_format', dest='time_format',\n default=timestamp.TIME_FORMAT,\n help='Format in which to expect time strings.')\n\n parser.add_argument('--transform_aggregate_xml', dest='aggregate_xml',\n default='', help='Aggregate records of XML until a '\n 'completed XML record whose outer element matches '\n 'the specified tag has been seen, then pass it along '\n 'as a single record.')\n\n ############################\n # Writers\n parser.add_argument('--write_file', dest='write_file', default=None,\n help='File(s) to write to (\\'-\\' for stdout)')\n\n parser.add_argument('--write_logfile', dest='write_logfile', default=None,\n help='Filename base to write to. A date string that '\n 'corresponds to the timestamped date of each record '\n 'Will be appended to filename, with one file per date.')\n\n parser.add_argument('--write_network', dest='write_network', default=None,\n help='Network address(es) to write to')\n\n parser.add_argument('--write_database', dest='write_database', default=None,\n help='user@host:database to write to. Should be '\n 'accompanied by the --database_password flag.')\n\n parser.add_argument('--database_password', dest='database_password',\n default=None, help='Password for database specified by '\n '--write_database and/or --read_database.')\n\n parser.add_argument('--write_record_screen', dest='write_record_screen',\n action='store_true', default=False,\n help='Display the most current DASRecord field values '\n 'on the terminal.')\n \n ############################\n # Miscellaneous args\n parser.add_argument('--check_format', dest='check_format',\n action='store_true', default=False, help='Check '\n 'reader/transform/writer format compatibility')\n\n parser.add_argument('-v', '--verbosity', dest='verbosity',\n default=0, action='count',\n help='Increase output verbosity')\n\n ############################\n # Set up logging before we do any other argument parsing (so that we\n # can log problems with argument parsing.)\n parsed_args = parser.parse_args() \n LOGGING_FORMAT = '%(asctime)-15s %(filename)s:%(lineno)d %(message)s'\n logging.basicConfig(format=LOGGING_FORMAT)\n\n LOG_LEVELS ={0:logging.WARNING, 1:logging.INFO, 2:logging.DEBUG}\n verbosity = min(parsed_args.verbosity, max(LOG_LEVELS))\n logging.getLogger().setLevel(LOG_LEVELS[verbosity])\n\n ############################\n # If --config_file present, create Listener from config file. If\n # not, manually parse and create from all other arguments on command\n # line.\n if parsed_args.config_file:\n # Ensure that no other flags have been specified.\n i = 1\n while i < len(sys.argv):\n if sys.argv[i] in ['-v', '--verbosity']:\n i += 1\n elif sys.argv[i] == '--config_file':\n i += 2\n else:\n raise ValueError(\n 'When --config is specified, no other command '\n 'line arguments (except -v) may be used: {}'.format(sys.argv[i]))\n\n # Read config file and instantiate\n listener = ListenerFromLoggerConfigFile(parsed_args.config_file)\n\n # If not --config, go parse all those crazy command line arguments manually\n else:\n ############################\n # Where we'll store our components\n readers = []\n transforms = []\n writers = []\n\n ############################\n # Parse args out. We do this in a rather non-standard way to use the\n # order of args on the command line to determine the order of our\n # transforms. Specifically: break command line up into sections that\n # end with the next '-'-prefixed argument (excluding the empty\n # argument '-' and arguments starting with a negative number),\n # and process those sections sequentially, adding\n # them to the 'args' namespace as we go.\n #\n # So\n #\n # listen.py -v 1 2 3 -w -x - -y -4 -1,1 -z\n #\n # will be processed in five chunks:\n #\n # ['-v', '1', '2', '3']\n # ['-w']\n # ['-x', '-']\n # ['-y', '-4', '-1,1']\n # ['-z']\n #\n #\n # Functionally, it means that\n #\n # --transform_a --transform_b \n #\n # will push transform_a into the transform list before transform_b,\n # (meaning it will be applied to records first), while\n #\n # --transform_b --transform_a \n #\n # will do the opposite. It also means that repeating a transform on\n # the command line will apply it twice. Repetitions of readers or\n # writers will create multiple instances but, since readers and\n # writers are applied in parallel, ordering is irrelevant.\n\n arg_start = arg_end = 1 # start at beginning of args, minus script name;\n all_args = None # initial namespace is empty\n\n # Loop while we have args left\n while arg_end <= len(sys.argv):\n\n arg_start = arg_end\n arg_end += 1\n\n # Get everything up to, but not including, the next arg beginning with '-'\n # that isn't a plain '-' or something numeric.\n while arg_end < len(sys.argv):\n next_arg = sys.argv[arg_end]\n if next_arg.find('-') == 0:\n if next_arg != '-' and not re.match('-\\d', next_arg):\n break\n arg_end += 1\n\n # We have our next set of arguments - parse them\n arg_list = sys.argv[arg_start:arg_end]\n logging.debug('next set of command line arguments: %s', arg_list)\n\n # These are just the new values\n new_args = parser.parse_args(arg_list)\n\n # We also want to accumulate old arguments so that we have access\n # to flags that have been previously set.\n all_args = parser.parse_args(arg_list, all_args)\n\n logging.debug('namespace of all command-line args so far: %s', all_args)\n\n ##########################\n # Now go through new_args and see what they want us to do. Draw\n # on all_args for the previously-set options that a reader,\n # transform or writer might need.\n\n ##########################\n # Readers\n if new_args.file:\n for filename in new_args.file.split(','):\n readers.append(TextFileReader(\n file_spec=filename, tail=all_args.tail,\n refresh_file_spec=all_args.refresh_file_spec))\n\n if new_args.network:\n for addr in new_args.network.split(','):\n readers.append(NetworkReader(network=addr))\n\n if new_args.logfile:\n for filebase in new_args.logfile.split(','):\n readers.append(LogfileReader(\n filebase=filebase, use_timestamps=all_args.logfile_use_timestamps,\n refresh_file_spec=all_args.refresh_file_spec))\n\n # For each comma-separated spec, parse out values for\n # user@host:database:data_id[:message_type]. We count on\n # --database_password having been specified somewhere.\n if new_args.database:\n password = all_args.database_password\n (user, host_db) = new_args.database.split('@')\n (host, database) = host_db.split(':', maxsplit=1)\n if ':' in database:\n (database, fields) = database.split(':')\n else:\n fields = None\n readers.append(DatabaseReader(fields=fields,\n database=database, host=host,\n user=user, password=password))\n\n # SerialReader is a little more complicated than other readers\n # because it can take so many parameters. Use the kwargs trick to\n # pass them all in.\n if new_args.serial:\n kwargs = {}\n for pair in new_args.serial.split(','):\n (key, value) = pair.split('=')\n kwargs[key] = value\n readers.append(SerialReader(**kwargs))\n\n ##########################\n # Transforms\n if new_args.slice:\n transforms.append(SliceTransform(new_args.slice,\n all_args.slice_separator))\n if new_args.timestamp:\n transforms.append(TimestampTransform(time_format=all_args.time_format))\n if new_args.prefix:\n transforms.append(PrefixTransform(new_args.prefix))\n if new_args.regex_filter:\n transforms.append(RegexFilterTransform(new_args.regex_filter))\n if new_args.qc_filter:\n transforms.append(QCFilterTransform(new_args.qc_filter))\n if new_args.parse_nmea:\n transforms.append(ParseNMEATransform(time_format=all_args.time_format))\n if new_args.aggregate_xml:\n transforms.append(XMLAggregatorTransform(new_args.aggregate_xml))\n\n ##########################\n # Writers\n if new_args.write_file:\n for filename in new_args.write_file.split(','):\n if filename == '-':\n filename = None\n writers.append(TextFileWriter(filename=filename))\n if new_args.write_logfile:\n writers.append(LogfileWriter(filebase=new_args.write_logfile))\n if new_args.write_network:\n for addr in new_args.write_network.split(','):\n writers.append(NetworkWriter(network=addr))\n if new_args.write_record_screen:\n writers.append(RecordScreenWriter())\n if new_args.write_database:\n password = all_args.database_password\n # Parse out values for user@host:database. We count on\n # --database_password having been specified somewhere.\n (user, host_db) = new_args.write_database.split('@')\n (host, database) = host_db.split(':')\n writers.append(DatabaseWriter(database=database, host=host,\n user=user, password=password))\n\n ##########################\n # Now that we've got our readers, transforms and writers defined,\n # create the Listener.\n listener = Listener(readers=readers, transforms=transforms, writers=writers,\n interval=all_args.interval,\n check_format=all_args.check_format)\n\n ############################\n # Whichever way we created the listener, run it.\n listener.run()\n","sub_path":"logger/listener/listen.py","file_name":"listen.py","file_ext":"py","file_size_in_byte":21232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"611646562","text":"from manim import *\nfrom math import sin, cos, sqrt\n\nfrom manim.utils.rate_functions import ease_out_sine\nfrom numpy import square\n\nclass S1(Scene):\n def construct(self):\n text1 = Text(\"Everyone, it's a new year!\").set_color_by_gradient(RED_B, YELLOW_B)\n self.play(Write(text1))\n self.play(text1.animate.shift(UP*3))\n \n time = ValueTracker(0)\n initTheta = PI/4\n l = 2\n g = 9.8\n w = np.sqrt(g/l)\n p = 2*PI/w\n\n originX = 0\n originY = 1\n startPoint = Dot([originX, originY, 0], radius=0.05, color=RED_B)\n originShft = originX * RIGHT + originY * UP\n\n theta = DecimalNumber().shift(10*UP)\n theta.add_updater(lambda m: m.set_value(initTheta*np.sin(w*time.get_value())))\n self.add(theta)\n\n def getLine(x, y):\n line = Line(start=ORIGIN + originShft, end=x*RIGHT+y*UP+originShft, color=RED_B)\n global verticalLine\n verticalLine = DashedLine(start=line.get_start(), end=line.get_start() + l*DOWN, color=YELLOW_B)\n\n return line\n\n def getAngle(theta):\n global angle\n global thetaLabel\n if theta == 0:\n angle = VectorizedPoint().move_to(10 * UP)\n thetaLabel = VectorizedPoint().move_to(10 * UP)\n else:\n if theta > 0:\n angle = Angle(line, verticalLine, quadrant=(1, 1), other_angle=True, color=YELLOW_B, fill_opacity=0.5)\n else:\n angle = Angle(line, verticalLine, quadrant=(1, 1), other_angle=False, color=YELLOW_B, fill_opacity=0.5)\n\n return angle\n\n def getEndBall(x, y):\n endBall = Dot(fill_color=RED_B, fill_opacity=1).move_to(x*RIGHT+y*UP+originShft).scale(l)\n return endBall\n\n line = always_redraw(lambda: getLine(l * np.sin(theta.get_value()), -l * np.cos(theta.get_value())))\n angle = always_redraw(lambda: getAngle(theta.get_value()))\n angleText = MathTex(r'\\theta').scale(0.5).add_updater(lambda m: m.next_to(angle, DOWN))\n ball = always_redraw(lambda: getEndBall(l * np.sin(theta.get_value()), -l * np.cos(theta.get_value())))\n\n self.play(Create(VGroup(startPoint, line, verticalLine)))\n self.play(Create(VGroup(angle, angleText)))\n self.play(Create(ball))\n\n textDesc = Text(\"I think we should have a look at pendulums...\").scale(0.7).shift(DOWN*3).set_color_by_gradient(BLUE_B, LIGHT_BROWN)\n\n self.play(time.animate.set_value(2.5*p), Write(textDesc), rate_func=linear, run_time = 5) \n self.wait()\n\nclass S2(Scene):\n def construct(self):\n time = ValueTracker(0)\n initThetaS = PI/4\n initTheta = Variable(initThetaS, r'\\theta')\n l = 5\n g = 9.8\n w = np.sqrt(g/l)\n p = 2*PI/w\n\n originX = -2.25\n originY = 3\n startPoint = Dot([originX, originY, 0], radius=0.1, color=BLUE_B)\n originShft = originX* RIGHT + originY * UP\n\n theta = DecimalNumber().shift(10*UP)\n theta.add_updater(lambda m: m.set_value(initTheta.tracker.get_value()*np.sin(w*time.get_value())))\n self.add(theta)\n\n def getLine(x, y):\n line = Line(start=ORIGIN + originShft, end=x*RIGHT+y*UP+originShft, color=BLUE_B)\n global verticalLine\n verticalLine = DashedLine(start=line.get_start(), end=line.get_start() + l*DOWN, color=WHITE)\n\n return line\n\n def getEndBall(x, y):\n endBall = Dot(fill_color=BLUE_B, fill_opacity=1).move_to(x*RIGHT+y*UP+originShft).scale(l)\n return endBall\n\n line = always_redraw(lambda: getLine(l * np.sin(theta.get_value()), -l * np.cos(theta.get_value())))\n ball = always_redraw(lambda: getEndBall(l * np.sin(theta.get_value()), -l * np.cos(theta.get_value())))\n\n self.add(VGroup(startPoint, line, verticalLine, ball))\n\n self.play(time.animate.set_value(2*p), rate_func=ease_out_sine, run_time=5)\n\n wDef = MathTex(r'w = \\sqrt{\\frac{g}{l}}').shift(UP*1, RIGHT*3)\n naturalFreqLabel = Text('\"Natural Frequency\"').scale(0.7).set_color_by_gradient(RED_B, YELLOW_B).align_to(wDef, LEFT).next_to(wDef, UP, buff=DEFAULT_MOBJECT_TO_MOBJECT_BUFFER+0.1).shift(1*RIGHT)\n wDef1 = MathTex(r'w = \\sqrt{\\frac{g}{l}}').shift(UP*1, RIGHT*3)\n thetaEquationMotion = MathTex(r'{{\\theta}}(t)={{\\theta}} \\cos(wt)').set_color_by_tex(\"heta\", BLUE).next_to(wDef, DOWN, buff=DEFAULT_MOBJECT_TO_MOBJECT_BUFFER+0.2).align_to(wDef, LEFT)\n thetaRange = MathTex(r'-3 < {{\\theta}}< 3').set_color_by_tex(\"heta\", BLUE).next_to(thetaEquationMotion, DOWN, buff=DEFAULT_MOBJECT_TO_MOBJECT_BUFFER+0.5).align_to(thetaEquationMotion, LEFT)\n\n self.play(Write(wDef))\n self.add(wDef1)\n self.play(Write(naturalFreqLabel))\n self.wait()\n self.play(Transform(wDef, thetaEquationMotion))\n self.play(Create(thetaRange))\n self.wait()\n\n self.play(time.animate.set_value(4*p), rate_func=ease_out_sine, run_time=5)\n\n self.play(FadeOut(VGroup(wDef1, naturalFreqLabel, thetaEquationMotion, thetaRange, wDef)))\n\n normal = always_redraw(lambda: Arrow(start=[l * np.sin(theta.get_value())+originX, -l * np.cos(theta.get_value())+originY, 0], end=[l* np.sin(theta.get_value())+2*np.cos(theta.get_value())+originX, -l * np.cos(theta.get_value())+2*np.sin(theta.get_value())+originY, 0]) )\n normalLabel = always_redraw(lambda: MathTex(r'\\mid \\vec{v} \\mid = mg \\sin(\\theta)').next_to(normal, DOWN, buff=0.7).scale(0.7).align_to(normal, ORIGIN))\n self.play(Create(VGroup(normal, normalLabel)))\n initTheta.label.set_color(BLUE)\n initTheta.shift(3*RIGHT).scale(1.2)\n\n self.play(Create(initTheta))\n self.wait()\n self.play(initTheta.tracker.animate.set_value(1))\n\n self.wait()\n self.play(time.animate.set_value(6*p), rate_func=ease_out_sine, run_time=5)\n self.play(FadeOut(normalLabel))\n\nclass S3(Scene):\n def construct(self):\n plane = NumberPlane(x_range=[-10, 10, 1], y_range=[-10, 10, 1], axis_config={\"include_numbers\": True}).scale(1)\n xLabel = plane.get_x_axis_label(r\"\\theta\", edge=RIGHT, direction=RIGHT).scale(0.7)\n yLabel = plane.get_y_axis_label(r\"\\dot{\\theta}\", edge=UP, direction=UP).scale(0.7)\n func = lambda pos: ((-0.01*pos[1]) - np.sin(pos[0]))*UP + pos[1]*RIGHT\n vectorField = ArrowVectorField(func, x_range=[-10, 10, 0.5]).scale(1)\n\n self.play(Create(VGroup(plane, xLabel, yLabel)))\n self.play(*[GrowArrow(vec) for vec in vectorField], run_time=3)\n\n self.wait()\n phaseSpaceText = Text('\"Phase Space\"').set_color_by_gradient(RED_B, YELLOW_B).shift(UP*3).add_background_rectangle(BLACK, 0.5)\n self.play(Create(phaseSpaceText))\n\n opacityStreams = ValueTracker(0)\n streams = always_redraw(lambda: StreamLines(func, color=WHITE, virtual_time=1).set_opacity(opacityStreams.get_value()) )\n self.add(streams)\n streams.start_animation()\n self.play(opacityStreams.animate.set_value(0.3))\n self.wait(5)\n self.play(FadeOut(streams), FadeOut(phaseSpaceText))\n self.wait()\n\nclass S4(Scene):\n def construct(self):\n text = Text(\"Pendulums are very difficult to make.\").scale(0.7).shift(UP*3).set_color_by_gradient(RED_B, YELLOW_B)\n\n time = ValueTracker(0)\n initTheta = PI/4\n l = 2\n g = 9.8\n w = np.sqrt(g/l)\n p = 2*PI/w\n\n originX = 0\n originY = 1\n startPoint = Dot([originX, originY, 0], radius=0.05, color=RED_B)\n originShft = originX * RIGHT + originY * UP\n\n theta = DecimalNumber().shift(10*UP)\n theta.add_updater(lambda m: m.set_value(initTheta*np.sin(w*time.get_value())))\n self.add(theta)\n\n def getLine(x, y):\n line = Line(start=ORIGIN + originShft, end=x*RIGHT+y*UP+originShft, color=RED_B)\n global verticalLine\n verticalLine = DashedLine(start=line.get_start(), end=line.get_start() + l*DOWN, color=YELLOW_B)\n\n return line\n\n def getAngle(theta):\n global angle\n global thetaLabel\n if theta == 0:\n angle = VectorizedPoint().move_to(10 * UP)\n thetaLabel = VectorizedPoint().move_to(10 * UP)\n else:\n if theta > 0:\n angle = Angle(line, verticalLine, quadrant=(1, 1), other_angle=True, color=YELLOW_B, fill_opacity=0.5)\n else:\n angle = Angle(line, verticalLine, quadrant=(1, 1), other_angle=False, color=YELLOW_B, fill_opacity=0.5)\n\n return angle\n\n def getEndBall(x, y):\n endBall = Dot(fill_color=RED_B, fill_opacity=1).move_to(x*RIGHT+y*UP+originShft).scale(l)\n return endBall\n\n line = always_redraw(lambda: getLine(l * np.sin(theta.get_value()), -l * np.cos(theta.get_value())))\n angle = always_redraw(lambda: getAngle(theta.get_value()))\n angleText = MathTex(r'\\theta').scale(0.5).add_updater(lambda m: m.next_to(angle, DOWN))\n ball = always_redraw(lambda: getEndBall(l * np.sin(theta.get_value()), -l * np.cos(theta.get_value())))\n\n self.play(Write(text))\n self.play(Create(VGroup(startPoint, line, verticalLine)))\n self.play(Create(VGroup(angle, angleText)))\n self.play(Create(ball))\n\n self.play(time.animate.set_value(2*p), run_time=5, rate_func=linear)\n \n text2 = Text(\"Also the phase space took a long time to render...\").scale(0.7).set_color_by_gradient(BLUE_B, LIGHT_BROWN).shift(DOWN*3)\n\n self.play(Write(text2))","sub_path":"systems/pendulum/animations/pendulums.py","file_name":"pendulums.py","file_ext":"py","file_size_in_byte":9709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"505780259","text":"import requests\nfrom bs4 import BeautifulSoup\nimport datetime\n\n\ndef codechef(username):\n details = []\n url = \"https://www.codechef.com/users/\"\n page = requests.get(url + username)\n soup = BeautifulSoup(page.content, 'html.parser')\n data = soup.find_all('div', class_=\"rating-number\")\n problems = soup.select('div h5')\n solved = problems[0].get_text()\n details.append(int(solved[14:len(solved) - 1]))\n details.append(data[0].get_text())\n return details\n\n\ndef codeforces(username):\n details = []\n flag2 = 0\n url = \"http://codeforces.com/contests/with/\" + username\n\n page = requests.get(url)\n soup = BeautifulSoup(page.content, 'html.parser')\n\n pro = []\n data = soup.find('div', class_=\"datatable\")\n data = data.text\n data = data.strip()\n\n for i in range(len(data)):\n if data[i] != \" \" and data[i] != \"\\n\" and data[i] != \"\\r\":\n pro.append(data[i])\n\n i = 49\n if i >= len(pro):\n details.append(0)\n else:\n number = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\n total = \"\"\n\n while pro[i] in number:\n total += pro[i]\n i += 1\n\n details.append(int(total))\n\n url = \"http://codeforces.com/profile/\" + username\n\n page = requests.get(url)\n soup = BeautifulSoup(page.content, 'html.parser')\n\n data = soup.find_all('div', class_=\"info\")\n data = data[0].text\n data = data.strip()\n data = data.split(\"\\n\")\n\n for i in range(len(data)):\n data[i] = data[i].strip()\n\n for i in range(len(data)):\n if data[i] == \"Contest rating:\":\n d = data[i + 2]\n details.append(int(d[:4]))\n flag2 = 1\n break\n\n if flag2 == 0:\n details.append(0)\n\n print(details[0])\n return details\n\n\ndef hackerEarth(username):\n details = []\n\n if username[0] == \"@\":\n username = username[1:]\n\n url = \"https://www.hackerearth.com/users/pagelets/\" + username + \"/coding-data/\"\n\n page = requests.get(url)\n soup = BeautifulSoup(page.content, 'html.parser')\n\n data = soup.find_all('div', class_=\"line-height-18\")\n pro = data[0].text\n ratings = data[1].text\n\n pro = pro.split(\" \")\n pro = pro[2].split(\"\\n\")\n details.append(int(pro[0]))\n\n ratings = ratings.split(\" \")\n ratings = ratings[1].split(\"\\n\")\n details.append(int(ratings[0]))\n\n return details\n\n\ndef hackerrank(username):\n def valid_date(datestring):\n try:\n datetime.datetime.strptime(datestring, '%Y-%m-%d')\n return True\n except ValueError:\n return False\n\n details = []\n\n url = \"https://www.hackerrank.com/rest/hackers/\" + username + \"/submission_histories\"\n\n page = requests.get(url)\n soup = BeautifulSoup(page.content, 'html.parser')\n\n data = soup.find(text=True)\n\n dd = 0\n string = \"\"\n pro = []\n for i in data:\n if dd == 2:\n dd = 0\n if not valid_date(string):\n pro.append(int(string))\n string = \"\"\n elif i == '\"':\n dd += 1\n elif dd == 1:\n string += i\n\n details.append(sum(pro))\n\n url = \"https://www.hackerrank.com/rest/hackers/\" + username + \"/rating_histories_elo\"\n number = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.']\n page = requests.get(url)\n soup = BeautifulSoup(page.content, 'html.parser')\n data = soup.findAll(text=True)\n rank = data[0][-75:-60]\n flag = 0\n total = \"\"\n for i in range(len(rank)):\n if rank[i] in number or flag == 1:\n total += rank[i]\n flag = 1\n if len(total) == 5:\n break\n details.append(float(total))\n\n return details\n\n\ndef spoj(username):\n details = []\n url = \"http://www.spoj.com/users/\"\n page = requests.get(url + username)\n soup = BeautifulSoup(page.content, 'html.parser')\n data = soup.find_all('div', class_=\"col-md-6 text-center valign-center\")\n data = data[0].text\n data = data.split(\"\\n\")\n\n details.append(int(data[3]))\n\n ranking = soup.find_all('div', class_=\"col-md-3\")\n ranking = ranking[0].text\n ranking = ranking.split(\"\\n\")\n ranking = (ranking[4])[14:]\n ranking = ranking.split(\" \")\n details.append(int(ranking[0]))\n\n return details\n\n\ndef github(username):\n details = []\n url = \"https://github.com/\"\n page = requests.get(url + username)\n soup = BeautifulSoup(page.content, 'html.parser')\n data = soup.find_all('span', class_=\"Counter\")\n details.append(int(data[0].get_text()))\n\n url = \"https://github.com/\" + username + \"?tab=repositories\"\n page = requests.get(url)\n soup = BeautifulSoup(page.content, 'html.parser')\n data = soup.find_all('div', class_=\"d-inline-block mb-1\")\n desc = soup.find_all('p', class_=\"col-9 d-inline-block text-gray mb-2 pr-4\")\n\n if len(data) == len(desc):\n for i in range(len(data)):\n string = data[i].text\n string = string.strip()\n string = string.split(\" \")\n link = \"http://www.github.com/\" + username + \"/\" + string[0]\n description = desc[i].text\n description = description.strip()\n details.append((string[0], description, link))\n return details\n\n else:\n return details\n","sub_path":"hackerProfile/Profile/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":5294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"518126540","text":"# inner.py\nfrom django.conf.urls import url\nfrom .views import ProjectsListView, ProjectDetailView, TestTemplateView\n\nurlpatterns = [\n url(r'^$', ProjectsListView.as_view(), name='ProjectsListView'),\n url(r'^test/$', TestTemplateView.as_view(), name='TestTemplateView'),\n url(r'^(?P[\\w-]+)', ProjectDetailView.as_view(), name='ProjectDetailView'),\n]\n\n","sub_path":"projects/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"256346974","text":"import json\nimport logging\nfrom typing import Dict\n\nfrom allennlp.common.checks import ConfigurationError\nfrom allennlp.common.file_utils import cached_path\nfrom allennlp.data import Token\nfrom allennlp.data.dataset_readers.dataset_reader import DatasetReader\nfrom allennlp.data.fields import Field, LabelField, MetadataField, TextField\nfrom allennlp.data.instance import Instance\nfrom allennlp.data.token_indexers import SingleIdTokenIndexer, TokenIndexer\nfrom allennlp.data.tokenizers import Tokenizer, WordTokenizer\nfrom allennlp.data.tokenizers.word_splitter import JustSpacesWordSplitter\nfrom overrides import overrides\nfrom pytorch_transformers.tokenization_auto import AutoTokenizer\n\nlogger = logging.getLogger(__name__) # pylint: disable=invalid-name\n\n# TODO: unify with XNLI; just hardcore \"en\" as language tag\n\n@DatasetReader.register(\"xnli_xlm\")\nclass XnliReaderXLM(DatasetReader):\n \"\"\"\n Reads a file from the Multi Natural Language Inference (MNLI) dataset. This data is\n formatted as jsonl, one json-formatted instance per line. The keys in the data are\n \"gold_label\", \"sentence1\", and \"sentence2\". We convert these keys into fields named \"label\",\n \"premise\" and \"hypothesis\", along with a metadata field containing the tokenized strings of the\n premise and hypothesis.\n\n Parameters\n ----------\n tokenizer : ``Tokenizer``, optional (default=``WordTokenizer()``)\n We use this ``Tokenizer`` for both the premise and the hypothesis. See :class:`Tokenizer`.\n token_indexers : ``Dict[str, TokenIndexer]``, optional (default=``{\"tokens\": SingleIdTokenIndexer()}``)\n We similarly use this for both the premise and the hypothesis. See :class:`TokenIndexer`.\n max_sent_len : ``int``\n Examples where premis or hypothesis are larger then this will be filtered out\n \"\"\"\n\n def __init__(self,\n xlm_model_name: str,\n do_lowercase: bool,\n token_indexers: Dict[str, TokenIndexer] = None,\n max_sent_len: int = 80,\n dataset_field_name: str = \"dataset\",\n lazy: bool = False) -> None:\n super().__init__(lazy)\n self._tokenizer = AutoTokenizer.from_pretrained(xlm_model_name, do_lower_case=do_lowercase)\n self._token_indexers = token_indexers or {'tokens': SingleIdTokenIndexer()}\n self._max_sent_len = max_sent_len\n self._dataset_field_name = dataset_field_name\n\n @overrides\n def _read(self, file_path: str):\n # if `file_path` is a URL, redirect to the cache\n file_path = cached_path(file_path)\n\n with open(file_path, 'r') as nli_file:\n logger.info(\"Reading XNLI / MultiNLI / SNLI instances from jsonl dataset at: %s\", file_path)\n for line in nli_file:\n example = json.loads(line)\n\n language = \"en\" # by default we assume we work with MNLI which is in en \n if \"language\" in example:\n language = example[\"language\"] # xnli\n\n label = example[\"gold_label\"]\n if label == '-':\n # These were cases where the annotators disagreed; we'll just skip them. It's\n # like 800 out of 400k examples in the training data.\n continue\n\n\n premise = example[\"sentence1\"]\n hypothesis = example[\"sentence2\"]\n\n try:\n yield self.text_to_instance(premise, hypothesis, language, label=label)\n except ValueError:\n continue\n\n @overrides\n def text_to_instance(self, # type: ignore\n premise: str,\n hypothesis: str,\n language: str,\n label: str = None) -> Instance:\n # pylint: disable=arguments-differ\n fields: Dict[str, Field] = {}\n premise_tokens = self._tokenizer.tokenize(premise, lang=language)\n premise_tokens = [Token(t) for t in premise_tokens]\n \n hypothesis_tokens = self._tokenizer.tokenize(hypothesis, lang=language)\n hypothesis_tokens = [Token(t) for t in hypothesis_tokens]\n \n # filter out very long sentences\n if self._max_sent_len is not None:\n # These were sentences are too long for bert; we'll just skip them. It's\n # like 1000 out of 400k examples in the training data.\n\n if len(premise_tokens) + len(hypothesis_tokens) > self._max_sent_len:\n raise ValueError()\n\n premise_hypothesis_tokens = [Token(\"\")] + premise_tokens + [Token(\"\")] + hypothesis_tokens + [Token(\"\")] \n fields['premise_hypothesis'] = TextField(premise_hypothesis_tokens, self._token_indexers)\n \n if label:\n if label == 'contradictory':\n label = 'contradiction'\n fields['label'] = LabelField(label)\n \n metadata = {\"premise_tokens\": [x.text for x in premise_tokens],\n \"hypothesis_tokens\": [x.text for x in hypothesis_tokens]}\n fields[\"metadata\"] = MetadataField(metadata)\n\n fields[self._dataset_field_name] = MetadataField(metadata=\"nli-\" + language)\n\n return Instance(fields)\n","sub_path":"align/data/xnli_reader_xlm.py","file_name":"xnli_reader_xlm.py","file_ext":"py","file_size_in_byte":5270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"128267472","text":"import math\n\na = int (input(\"Digite a variável a: \"))\nb = int (input(\"Digite a variável b: \"))\nc = int (input(\"Digite a variável c: \"))\n\ndelta = b**2 - (4*a*c)\n\n#se delta é menor que 0, não existe raiz real\nif delta < 0:\n print(\"Não existem raízes reais.\")\n\n\n#se delta é igual a 0, só existe uma raíz real \nelif delta == 0:\n x1 = (-b )/(2*a)\n print (\"A equação possui apenas uma raiz real, que é \",\"%.2f\" %x1)\n#lembrar sempre de usar o %.2f pra referenciar variável\n\n\nelif delta > 0:\n rDelta = math.sqrt (delta)\n x1 = (-b - rDelta)/(2*a)\n x2 = (-b + rDelta)/(2*a)\n print(\"As raízes são \", \"%.2f\" %x1,\" e \",\"%.2f\" %x2)","sub_path":"Exercicios Listas/baskahra.py","file_name":"baskahra.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"5908701","text":"# -*- coding: utf-8 -*-\n\nfrom .plus import DeviceProfile\nfrom .genericFEC import genericFEC\n\n#################################################################################################\n\nclass rower(DeviceProfile):\n channelPeriod = 8192\n deviceType = 0x11 #FE-C\n name = 'Rower'\n\n\n def __init__(self, node, network, callbacks=None):\n super(rower, self).__init__(node, network, callbacks)\n\n self.page16 = genericFEC()\n self._elapsedTime = 0.0\n self._distanceTraveled = 0\n self._instantaneousSpeed = 0.0\n self._kmSpeed = 0.0\n self._cadence = 0\n self._power = 0\n self._detected_device = None\n\n def event_time_correction(self, time_difference):\n return time_difference * 1000 / 1024\n\n def processData(self, data):\n with self.lock:\n dataPageNumber = data[0]\n\n if(dataPageNumber == 16):\n self.page16.p16(data)\n self._elapsedTime = self.page16.elapsedTime\n self._distanceTraveled = self.page16.distanceTraveled\n self._instantaneousSpeed = self.page16.instantaneousSpeed\n self._kmSpeed = self.page16.kmSpeed\n\n if(dataPageNumber == 22):\n self._cadence = data[4]\n self._power = data[5] + (256 * data[6])\n if (self._power == 65535): ## FFFF invalid\n self._power = 0.0\n self._cadence = 0\n\n#################################################################################\n\n callback = self.callbacks.get('onRower')\n if callback:\n callback(self._elapsedTime, self._distanceTraveled, self._instantaneousSpeed, self._kmSpeed, self._cadence, self._power)\n\n","sub_path":"src/ant/plus/rower.py","file_name":"rower.py","file_ext":"py","file_size_in_byte":1785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"548515501","text":"import sys\nfrom config import *\nsys.path.append(PLUGIN_PATH)\n\n# Import plugins here\nimport log_all, log_sorted, usernames, no_changes, sp_opcolor, usercolors, bad_cmd, welcome, menus, timed_events, schedule, plugin_helpers\nimport player_cmd as cmd\nimport menu_test, testing\n\n# Set ordering here\n\nplugins = []\n\n# basic logging\n#plugins.append(log_all) # Only on when needed - chews disk space\nplugins.append(log_sorted) # Always first to catch all raw packets\n\n# utility\nplugins.append(usernames) # The earlier the better, name the login packets sooner.\nplugins.append(schedule) # Before anything that depends on it.\nplugins.append(plugin_helpers) # Lots of things depend on this. Do it early.\nplugins.append(cmd) # Should probably be before anything that depends on it\nplugins.append(menus) # Should probably be before anything that depends on it\n\n# features\nplugins.append(welcome) # Has /help, so high priority. But should be after usernames (for the welcome)\nplugins.append(usercolors)\nplugins.append(menu_test)\n\nplugins.append(testing)\n\n# tail\nplugins.append(bad_cmd) # Always last out of chat commands\n","sub_path":"plugins.py","file_name":"plugins.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"116381839","text":"\"\"\"peewee note\n1. 当使用非自增的主键时, 调用save时, 需要传入参数 force_insert=True\n\n\n\"\"\"\nimport peewee\nimport playhouse.pool\nfrom BlockFileUpload.block_config import DATABASE, DATABASE_SQLITE, DEBUG\n\n\ndef gen_db(database_config):\n engine = getattr(peewee, database_config.get(\"ENGINE\", \"SqliteDatabase\"))\n params = {\"thread_safe\": True, \"autorollback\": False, }\n params.update(database_config.get(\"OPTIONS\", {}))\n if \"POOL\" in database_config:\n pool = database_config[\"POOL\"]\n if pool.get(\"ENABLE\", False):\n engine = getattr(playhouse.pool, \"Pooled\" + database_config.get(\"ENGINE\", \"SqliteDatabase\"))\n params[\"max_connections\"] = pool.get(\"max_connections\", 20)\n params[\"stale_timeout\"] = pool.get(\"stale_timeout\", None)\n params[\"timeout\"] = pool.get(\"timeout\", None)\n params[\"thread_safe\"] = False\n args = {\"database\": \"NAME\", \"user\": \"USER\", \"password\": \"PASSWORD\", \"host\": \"HOST\", \"port\": \"PORT\"}\n for k, v in args.items():\n value = database_config.get(v, None)\n if value:\n params[k] = value\n\n db = engine(**params)\n return db\n\n\ndb = gen_db(DATABASE_SQLITE) if DEBUG else gen_db(DATABASE)\n\n\nclass BaseModel(peewee.Model):\n class Meta:\n database = db\n only_save_dirty = True\n legacy_table_names = False\n\n def save(self, force_insert=False, only=None):\n for k, v in self._meta.fields.items():\n if getattr(self, k) and v.choices:\n if getattr(self, k) not in v.choices:\n raise peewee.IntegrityError(\"{} fields choices are: {}\".format(k, list(v.choices.keys())))\n return super().save(force_insert, only)\n","sub_path":"models/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"409048688","text":"from string import Template\n\nfirst=\"X\"\ncenter=\"0000\"\nlast=15\n#构造字符串模板\ntemp=Template(\"员工信息以$f开头,中间填充一串$c.最后是流水号$l\")\n#将模板的占位符替换为具体的变量值,以构成字符串\ntxt=temp.substitute(f=first,c=center,l=last)\nprint(txt)","sub_path":"PythonDemo/Day01/10Unix_Shell格式.py","file_name":"10Unix_Shell格式.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"586045997","text":"inFile = open('input.txt', 'r', encoding='utf8')\r\noutFile = open('output.txt', 'w', encoding='utf8')\r\nparties = []\r\nvotes = 0\r\ni = 0\r\nfor line in inFile:\r\n tempData = line.strip()\r\n name = line[:line.rfind(' ')]\r\n number = int(line[line.rfind(' ') + 1:])\r\n parties.append([number, i, name])\r\n votes += number\r\n i += 1\r\nnumOfPart = i\r\nplaces = [0] * numOfPart\r\nquot = []\r\nfor i in range(numOfPart):\r\n quot.append([i, 0, parties[i][1]])\r\nfirstQuot = votes / 450\r\nvacantPlaces = 450\r\nfor i in range(numOfPart):\r\n places[i] = parties[i][0] // firstQuot\r\n quot[i][1] = parties[i][0] % firstQuot\r\n vacantPlaces -= places[i]\r\nquot.sort(key=lambda x: (-x[1], -x[2], x[0]))\r\ni = 0\r\nwhile vacantPlaces != 0:\r\n places[quot[i][2]] += 1\r\n vacantPlaces -= 1\r\n i += 1\r\n i %= numOfPart\r\nfor i in range(numOfPart):\r\n print(parties[i][2], int(places[i]), file=outFile)\r\ninFile.close()\r\noutFile.close()\r\n","sub_path":"lesson7/7.t9.statedumaelection.py","file_name":"7.t9.statedumaelection.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"69849671","text":"import datetime\nimport feedparser\n\nfrom webapp import controllers\nfrom flask import url_for\n\n\ndef get_item_date(item):\n if 'published_parsed' in list(item.keys()):\n return datetime.datetime(*item.published_parsed[:7])\n else:\n return datetime.datetime.now()\n\n\ndef get_items_from_feed(url):\n feed = feedparser.parse(url)\n\n if feed.bozo == 1:\n msg = 'Não é possível parsear o feed (%s)' % url\n return False, msg\n\n return feed['items'], False\n\n\ndef news_import(url, language):\n entries, error_msg = get_items_from_feed(url)\n\n if not entries:\n return False, error_msg\n\n for item in entries:\n news_data = dict(url=item.link,\n image_url=url_for('static',\n filename='img/fallback_image.png',\n _external=True),\n publication_date=get_item_date(item),\n title=item.title[:256],\n description=item.summary,\n language=language)\n controllers.create_news_record(news_data)\n\n return True, False\n\n\ndef import_all_press_releases_posts(url, language):\n entries, error_msg = get_items_from_feed(url)\n\n if not entries:\n return False, error_msg\n\n for item in entries:\n journals = controllers.get_journals()\n\n for tag in item['tags']:\n if not tag.term.isupper():\n continue\n\n journal = journals.filter(acronym=tag.term)\n if len(journal) == 0:\n continue\n\n save_press_release(pr=item, journal=journal, language=language)\n\n return True, False\n\n\ndef import_all_press_releases_posts_by_category(url, language):\n journals = controllers.get_journals()\n\n for journal in journals:\n dynamic_url = url.format(language, journal.acronym)\n entries = get_items_from_feed(dynamic_url)\n\n for item in entries[0]:\n save_press_release(pr=item, journal=journal, language=language)\n\n return True, False\n\n\ndef save_press_release(pr, journal, language):\n pr_data = dict(url=pr.link,\n journal=journal,\n publication_date=get_item_date(pr),\n title=pr.title[:256],\n content=pr.summary[:300],\n language=language)\n controllers.create_press_release_record(pr_data)","sub_path":"opac/webapp/helpers/rss_feeds_importer.py","file_name":"rss_feeds_importer.py","file_ext":"py","file_size_in_byte":2434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"75145226","text":"import argparse\nfrom pyubflasher.flasherboard import FlasherBoard\n\nclass BoardMenuAction( argparse.Action ):\n def __init__(self, option_strings, nargs=0, dest=None, **kwargs ):\n super(BoardMenuAction,self).__init__(option_strings=option_strings, \n nargs=nargs,\n dest=dest, \n **kwargs )\n def __call__(self,parser,namespace,values,option_string=None):\n board = FlasherBoard()\n board.printMenu()\n setattr(namespace,self.dest,values)\n\nclass DisplayAllRegistersAction( argparse.Action ):\n def __init__(self, option_strings, nargs=0, dest=None, **kwargs ):\n super(DisplayAllRegistersAction,self).__init__(option_strings=option_strings, \n nargs=nargs,\n dest=dest, \n **kwargs )\n def __call__(self,parse,namespace,values,option_string=None):\n board = FlasherBoard()\n board.queryAllRegisters()\n setattr(namespace,self.dest,values)\n\n","sub_path":"pyubflasher/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"264751570","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import Select\nfrom selenium.webdriver.chrome.options import Options\n\n\nimport os\nimport sys\n\n#Current Working Folder\ndir_path = os.path.dirname(os.path.realpath(__file__))\n\n#Getting Parent of current working folder\nfolder_path = os.path.abspath(os.path.join(dir_path,os.pardir))\n\n#Navigating to the desired folder\nsys.path.insert(0,folder_path+'\\Syslibrary')\n\n#Importing module from Syslibrary\nfrom datadriver import readjson\n\n#Creating a Class object and instance of that object\njsonread1 = readjson()\n\nclass launchapplication():\n def intializebrowser(self):\n\n\n env = jsonread1.jsonread(folder_path+'\\Env\\setup.json')\n if env['browser'] == 'chrome':\n #intialize chrome browser\n browser = webdriver.Chrome(folder_path+'\\Env\\chromedriver.exe')\n browser.implicitly_wait(10)\n browser.maximize_window()\n return browser\n elif env['browser'] == 'firefox':\n #intialize firefox browser\n browser = webdriver.Firefox(folder_path+'\\Env\\geckodriver.exe')\n browser.implicitly_wait(10)\n browser.maximize_window()\n return browser\n elif env['browser']=='headlessChrome':\n #Intialize headless chrome browser\n chrome_options = Options()\n chrome_options.add_argument(\"--headless\")\n chrome_options.add_argument(\"--window-size=1980*1080\")\n chrome_driver = folder_path+'\\Env\\chromedriver.exe'\n browser = webdriver.Chrome(chrome_options = chrome_options,executable_path = chrome_driver)\n browser.implicitly_wait(10)\n return browser\n def closebrowser(self,browser):\n browser.close()\n\n def inputurl(self,browser):\n url = jsonread1.jsonread(folder_path+'\\Env\\setup.json')\n if url['url'] == 'prestagurl':\n prestagurl = jsonread1.jsonread(folder_path+'\\Env\\setup.json')\n browser.get(prestagurl['prestagurl'])\n elif url['url'] == 'stagurl':\n stagurl = jsonread1.jsonread(folder_path+'\\Env\\setup.json')\n browser.get(stagurl['stagurl'])\n\n def app_locators(self):\n app_locators = jsonread1.jsonread(folder_path+'\\Objects\\locators.json')\n return app_locators()\n\n def app_testdata(self):\n app_testdata = jsonread1.jsonread(folder_path+'\\Data\\TestData.json')\n return app_testdata()\n\n def app_loginlink(self,browser,app_locators):\n loginlink = browser.find_element_by_xpath(app_locators('loginlink'))\n return loginlink()\n\n","sub_path":"Library/Launchapplicaton.py","file_name":"Launchapplicaton.py","file_ext":"py","file_size_in_byte":2730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"602137198","text":"def email_largest(ci):\n\tcoursename,person,email,temp,mails,mail1,comail = [],[],[],[],\"\",[],{}\n\t#Separating the strings into 3 \n\tfor i in ci:\n\t\trecord = i.split(\":\")\n\t\tcoursename.append(record[0])\n\t\tperson.append(record[1])\n\t\temail.append(record[2])\n\t\t#Initializing a course - email dictionary\n\t\tif comail.has_key(record[0]) == False:\n\t\t\tcomail[record[0]] = \"\"\n\tfor course,email in zip(coursename,email):\n\t\temh = email + \" \"\n\t\tcomail[course] += emh\n\t\tn = len(comail[course])\n\t\ttemp.append(n)\n\t\tif len(comail[course]) == max(temp):\n\t\t\tmails = comail[course]\n\tmail1 = mails.rstrip(\" \")\n\tt = mail1.split(\" \")\n\tt.sort()\n\tans = \" \".join(t)\n\treturn ans\n\nemail_largest([\"CompSci 100:Fred Jack Smith:fjs@duke.edu\",\"History 117:Fred Jack Smith:fjs@duke.edu\",\"CompSci 102:Arielle Marie Johnson:amj@duke.edu\",\"CompSci 100:Arielle Marie Johnson:amj@duke.edu\",\"CompSci 006:Bertha White:bw@duke.edu\",\"Econ 051:Bertha White:bw@duke.edu\",\"English 112:Harry Potter:hp@duke.edu\",\"CompSci 100:Harry Potter:hp@duke.edu\"])","sub_path":"koan_labs/email_dictionary_practice.py","file_name":"email_dictionary_practice.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"60518882","text":"def Merging(l1,l2):\n\tl3=[]\n\ti=0\t\n\tj=0\n\twhile i < len(l1) and j l1[j]:\n\t\t\t\ttemp=l1[i]\n\t\t\t\tl1[i]=l1[j]\n\t\t\t\tl1[j]=temp\n\n\ndef main():\n\n\tl1=[5,4,3,2]\n\tl2=[1,8,6,7]\n\t\n\t#l3=[]\n\t#for x in \n\t#l3=eval(input(\"Enter the list..:\"))\n\t\n\t#l3=list(l3)\n\t#print(type(l3))\n\tSorting(l1)\n\tSorting(l2)\n\t\n\tprint(\"Sorted lists are:\\n list1={} \\n list2={}\\n\".format(l1,l2) )\n\n\tresult=Merging(l1,l2)\n\t\n\tprint(\"After Merging Two Sorted list is:{}\".format(result))\nif __name__=='__main__':\n\tmain()\n","sub_path":"program in class/TwoListSortingNmerging.py","file_name":"TwoListSortingNmerging.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"207435337","text":"import PIL\nimport glob\nimport os\nimport math\nimport argparse\nimport colorsys\n\nfrom PIL import Image\n\n\nclass FranzMosaic:\n INPUT_DIR = 'img/'\n OUTPUT_DIR = 'out/'\n\n def resize_folder(self):\n allFiles = glob.glob(self.INPUT_DIR + '/**/*.jpg', recursive=True)\n for path in allFiles:\n self.resize(path)\n\n def resize(self, input_image):\n img = Image.open(input_image)\n img = img.resize((1, 1), PIL.Image.ANTIALIAS)\n filename = os.path.basename(input_image)\n img.save(self.OUTPUT_DIR + filename)\n\n def create_new_imate(self):\n all_files = glob.glob(self.OUTPUT_DIR + '/*.jpg')\n len_of_sides = math.floor(math.sqrt(len(all_files)))\n til = Image.new(\"RGB\", (len_of_sides, len_of_sides))\n n = 0\n for y in range(len_of_sides):\n for x in range(len_of_sides):\n print(n)\n im = Image.open(all_files[n]) # 25x25\n til.paste(im, (x, y))\n n += 1\n\n til.save(\"new.png\")\n\n def create_new_sorted_image(self):\n all_files = glob.glob(self.OUTPUT_DIR + '/*.jpg')\n len_of_sides = math.floor(math.sqrt(len(all_files)))\n len_of_sides = 50\n pixel_list = []\n print('mo')\n for n, file in enumerate(all_files[:len_of_sides*len_of_sides]):\n im = Image.open(all_files[n])\n pix = im.load()\n color = pix[0, 0]\n pixel_list.append(color)\n\n #print(pixel_list)\n #exit(0)\n pixel_list.sort(key=lambda rgb: colorsys.rgb_to_hsv(*rgb))\n #pixel_list.sort(key=hilbert.Hilbert_to_int)\n print(pixel_list)\n\n\n new = Image.new('RGB', (len_of_sides+1, len_of_sides+1))\n new.putdata(pixel_list)\n new.save(\"naive_tidy.png\")\n\n\ndef main():\n max = 0\n parser = argparse.ArgumentParser(\n description=\"rescale images and put it together again\")\n\n parser.add_argument('--rescale', '-r', help='Rescale Images to one pixel')\n parser.add_argument('--new', '-n', help='Produce new image')\n parser.add_argument('--sorted', '-s', help='Produce new sorted image')\n\n args = parser.parse_args()\n pic = FranzMosaic()\n\n if args.rescale:\n pic.resize_folder()\n\n if args.new:\n pic.create_new_imate()\n\n if args.sorted:\n pic.create_new_sorted_image()\n\nif __name__ == '__main__':\n main()\n","sub_path":"franz_mosaic/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"291608233","text":"# coding: utf-8\nimport os\nimport itertools as it\n\n# getting all filenames\nsources = []\nfor f in os.listdir('.'):\n if '.f90' in f.lower():\n sources.append(f)\n\n# selecting tests who are working \nstatus = dict()\nfor k in sources:\n status[k] = True\n if 'test_qmrherm_' in k :\n status[k] = False\n if 'test_qmrherm_4.F90' in k:\n status[k] = True\n\nfailing_tests = [ k for k in status if status[k] is False ]\n\n# collecting module usage for each test\nuses = dict() \nfor source in sources:\n modules_used = []\n with open(source,'r') as f:\n lines = f.readlines()\n for line in lines:\n exclmidx = line.find('!')\n if exclmidx is not -1 :\n line = line[:exclmidx]\n if 'use ' in line:\n words = line.split()[:2]\n if words[0] == 'use':\n sanitized = words[1].replace(',','')\n modules_used.append(sanitized.lower())\n uses[source] = modules_used \n\n\n# checking if a combination of two modules causes issues\ndef check_interactionsN(N):\n combinations = dict() \n for k,v in uses.items():\n combinations[k] = list(it.combinations(v,N))\n \n # working pair of modules\n working = set()\n for k,v in combinations.items():\n if status[k] :\n for item in v:\n working.add(item)\n \n # possibly not working pair of modules\n potentially_not_working = set()\n for k,v in combinations.items():\n if not status[k] :\n for item in v:\n potentially_not_working.add(item)\n \n not_working = potentially_not_working.difference(working)\n print(\"problems with combinations of {:d} modules:\".format(N))\n print(not_working)\n \n #possibly not working single modules shares between all tests failing\n potentially_not_working_common = set(combinations[failing_tests[0]])\n for k,v in combinations.items():\n if not status[k] :\n potentially_not_working_common.intersection_update(v)\n \n not_working_common = potentially_not_working_common.difference(working)\n \n print(\"problems with combinations of {:d} modules (common):\".format(N))\n print(not_working_common)\n\ncheck_interactionsN(1)\ncheck_interactionsN(2)\ncheck_interactionsN(3)\n","sub_path":"examples/check_module_use.py","file_name":"check_module_use.py","file_ext":"py","file_size_in_byte":2345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"482593418","text":"import enum\nimport numpy as np\nfalseOrders = {}\ntrueOrders = {}\nw1 = \"Welcome to our vegetable warehouse!\" \nw2 = \"Place your order for products in the form below this text.\" \nw3 = \"We guarantee quality and timely delivery.\" \nw4 = \"Thank you for being with us!\"\n\nprint('%+60s \\n %+70s \\n %+62s \\n %+55s \\n' % (w1, w2, w3, w4))\n\nclass products (enum.Enum):\n apricot = 100\n pineapple = 101\n banana = 102\n pear = 103\n lemon = 104\n peach = 105\n kiwi = 106\n potato = 107\n cabbage = 108\n pepper = 109\n tomato = 110\n carrot = 111\n\nclass dc (enum.Enum):\n firstDC = 1\n secondDC = 2\n thirdDC = 3\n\ndt_shops = [(\"shopIndex\", np.int_), (\"DC\", dc)]\nshops = np.array([(11001, dc.firstDC), (11002, dc.secondDC), (11003, dc.secondDC), (11004, dc.thirdDC),(11005, dc.thirdDC)], dt_shops)\n\ndef doOrder():\n #Avialable products list\n shopIndex = int(input(\"Shop index: \")) \n if shopIndex in shops[\"shopIndex\"]:\n print(\"Acces is allowed. Avialable products: \")\n else:\n print(\"There is no such shop in our database\")\n doOrder()\n for i in products:\n print(\" *\", i.name, \" --- \" , i.value)\n \n #Array which contains tuples for each order\n shopOrder = []\n dt = [(\"prodIndex\", np.int_), (\"tareType\", bool), (\"weight\", np.float_)]\n while True: \n prodIndex = input(\"Index of product: \")\n tareType = True if input(\"tareType: \").lower() == \"y\" else False\n weight = input(\"weight: \")\n order = (prodIndex, tareType, weight)\n if len(order) != 3:\n print(\"Error\")\n continue \n shopOrder.append(order)\n ans = input((\"Succsefull. Would you like to continue? (Y/N)\")).lower()\n if ans == \"n\":\n shopOrder = np.array(shopOrder, dt)\n shopOrder = np.sort(shopOrder, order = \"tareType\")\n break\n\n #Divide the shop order in two parts by the prioricy\n i = len(shopOrder)-1\n while i>-1 and shopOrder[i][1] != False:\n i-=1\n if i < 0:\n trueOrders[shopIndex] = shopOrder\n else: \n falseOrders[shopIndex] = shopOrder[0:i+1] \n trueOrders[shopIndex] = shopOrder[i+1:len(shopOrder)] \n \nwhile True:\n doOrder()\n ans = input((\"Would you like to place an order for another shop? (Y/N)\")).lower()\n if ans == \"n\":\n break\n\nprint(\"The first prioricy orders: \") \nfor i in shops:\n if i[\"shopIndex\"] in falseOrders:\n for j in falseOrders[i[\"shopIndex\"]]:\n print( products(j[0]).name, \"-\", j[2], \"Kg. Shop#\", i[\"shopIndex\"], \"in the\", i[\"DC\"].name)\n\nprint(\"\\n The second prioricy orders: \")\nfor i in shops:\n if i[\"shopIndex\"] in trueOrders:\n for j in trueOrders[i[\"shopIndex\"]]:\n print( products(j[0]).name, \"-\", j[2], \"Kg. Shop#\", i[\"shopIndex\"], \"in the\", i[\"DC\"].name)\nprint()\n\n\n","sub_path":"Laba3/VegetableWarehouse.py","file_name":"VegetableWarehouse.py","file_ext":"py","file_size_in_byte":2852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"600512500","text":"#!/usr/bin/env python3\n\nimport vnc\nimport exception as ex\n\nfrom tornado import gen\nfrom tornado.web import RequestHandler, MissingArgumentError\nfrom tornado.websocket import WebSocketHandler, WebSocketClosedError\n\nfrom importlib import import_module\n\nclass Protocols(dict):\n def support(self, protocol):\n if protocol in self:\n return True\n try:\n self.__add(protocol)\n return True\n except:\n return False\n \n def __add(self, protocol):\n self[protocol] = import_module(protocol).ServerInterface\n return self\n\nprotocols = Protocols(vnc=vnc.ServerInterface)\n\n\nclass ProtocolSelectHandler(RequestHandler):\n @gen.coroutine\n def post(self, *args, **kargs):\n try:\n prot = self.get_argument(\"protocol\")\n except MissingArgumentError: # shouldn't be possible\n # refuse conn (serve error page)\n pass\n \n if protocols.support(prot):\n self.render(\n \"conn.html\", \n pxy_host = self.request.host,\n srv_host = self.get_argument(\"host\"),\n srv_port = self.get_argument(\"port\"),\n vnc_pw = self.get_argument(\"vnc_pw\")\n )\n else:\n # refuse conn (serve error page)\n pass\n \n \nclass ClientHandler(WebSocketHandler):\n def open(self, *args, **kargs):\n self.__server_connected = False\n self.__si = None\n \n @gen.coroutine\n def on_message(self, cmd):\n try:\n if self.__server_connected:\n self.__si.handle_cmd(cmd)\n elif cmd[0] == 0: # connect\n prot = bytes.decode(cmd[2: cmd[1]+2])\n if protocols.support(prot):\n self.__si = protocols[prot](self)\n else:\n self.close(1002, \"unsupported protocol \" + prot)\n return\n \n try:\n yield self.__si.connect(cmd[2+cmd[1] :])\n self.__server_connected = True\n except ex.ConnectError:\n self.close(1002, \"failed to connect\")\n except (IndexError, ex.CmdError):\n # TODO: log bad cmd format\n return\n except:\n # self.close(1002, \"??? error ???\")\n raise\n \n def on_close(self): # clean up server side\n if self.__si:\n self.__si.close()\n self.__si = None\n self.__server_connected = False\n \n def send_cmd(self, cmd):\n try:\n self.write_message(cmd, True) # binary data\n except WebSocketClosedError:\n # TODO: log client disconnected\n return # resources already cleaned up by on_close()\n except:\n # TODO: log error\n self.close(1002, \"error\")\n return\n \n def check_origin(self, origin):\n return True # accept all clients\n \n \n \n \n \n \n \n \n \n \n ","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"642081905","text":"# 137. Single Number II\n# Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.\n\n# Note:\n\n# Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?\n\n# Example 1:\n\n# Input: [2,2,3,2]\n# Output: 3\n# Example 2:\n\n# Input: [0,1,0,1,0,1,99]\n# Output: 99\n\nfrom collections import Counter, defaultdict\nimport operator\n\n\ndef singleNumber(nums):\n map = defaultdict(int)\n for n in nums:\n map[n] += 1\n\n minNumber = (0, float(\"inf\"))\n for k, v in map.items():\n if v < minNumber[1]:\n minNumber = (k, v)\n return minNumber[0]\n\n\ndef singleNumber2(nums):\n map = Counter(nums)\n return min(map.items(), key=operator.itemgetter(1))[0]\n\n\nprint(singleNumber([2, 2, 3, 2])) # 3\nprint(singleNumber([0, 1, 0, 1, 0, 1, 99])) # 99\n","sub_path":"LeetCode/SingleNumberII.py","file_name":"SingleNumberII.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"86365378","text":"\"\"\" a modified version of CRNN torch repository https://github.com/bgshih/crnn/blob/master/tool/create_dataset.py \"\"\"\n\nimport fire\nimport os\nimport lmdb\nimport cv2\n\nimport numpy as np\n\n\ndef checkImageIsValid(imageBin):\n if imageBin is None:\n return False\n imageBuf = np.frombuffer(imageBin, dtype=np.uint8)\n img = cv2.imdecode(imageBuf, cv2.IMREAD_GRAYSCALE)\n imgH, imgW = img.shape[0], img.shape[1]\n if imgH * imgW == 0:\n return False\n return True\n\n\ndef writeCache(env, cache):\n with env.begin(write=True) as txn:\n for k, v in cache.items():\n txn.put(k, v)\n\n\ndef get_gt_from_file_name(file_name, classes): \n name = '.'.join(file_name.split('.')[:-1])\n label = ''\n conversion = {'~~Star~~':'*',\n '~~BackSlash~~':'\\\\',\n '~~Slash~~':'/' ,\n '~~Colon~~':':',\n '~~SemiColon~~':';',\n '__LeftBrace__':'<',\n # '_':'<',\n '~~RightBrace~~':'>',\n '~~underscore~~':'_',\n '~~score~~':'-' ,\n }\n\n for key, value in conversion.items():\n name = name.replace(key, value)\n\n # name = name.replace('__LeftBrace__','<')\n # name = name.replace('-', '<')\n name = name.split('_')[0] \n for ch in name:\n if classes is not None and classes.get(ch) is None:\n print('unknown class: ' + ch)\n label += ''\n else:\n label += ch\n return label\n\n\ndef load_classes_dictionary(file_path, include_space=False):\n classes = {} \n with open (file_path, 'r') as f:\n lines = f.readlines()\n for line in lines: \n id, label = line.strip().split()\n classes[label] = id\n if include_space:\n classes[' '] = str(int(id) + 1)\n return classes\n\n\ndef createDataset(inputPath, outputPath, checkValid=True, use_space=True):\n \"\"\"\n Create LMDB dataset for training and evaluation.\n ARGS:\n inputPath : input folder path where starts imagePath\n outputPath : LMDB output path\n checkValid : if true, check the validity of every image\n use_space : if true add space classes\n \"\"\"\n os.makedirs(outputPath, exist_ok=True)\n env_train = lmdb.open(os.path.join(outputPath, 'train'), map_size=1099511627776)\n env_val = lmdb.open(os.path.join(outputPath, 'val'), map_size=1099511627776)\n #classes = load_classes_dictionary(os.path.join(inputPath, 'kr_labels.txt'), use_space)\n cache_train = {}\n cache_val = {}\n\n with env_train.begin(write=False) as txn :\n num_samples = txn.get('num-samples'.encode())\n if num_samples is None: \n cnt_train = 1\n else:\n cnt_train = int(num_samples)\n\n with env_val.begin(write=False) as txn:\n num_samples = txn.get('num-samples'.encode())\n if num_samples is None: \n cnt_val = 1 \n else:\n cnt_val = int(num_samples) \n\n import glob\n import random \n\n for image_path in glob.iglob(os.path.join(inputPath, \"**\"), recursive=True):\n print(f'{image_path}')\n if os.path.isfile(image_path): \n _ , file_name = os.path.split(image_path)\n #label = get_gt_from_file_name(file_name, classes) \n label = ''\n else:\n continue\n\n #Current implementation has no consideration for UNK character \n #This time I decieded to remove samples which have character \n if label.find('') >= 0 : \n continue \n\n if len(label) > 30 :\n print(f'skip {label} {len(label)}')\n continue\n\n with open(image_path, 'rb') as f:\n imageBin = f.read()\n\n if checkValid:\n try:\n if not checkImageIsValid(imageBin):\n print('%s is not a valid image' % image_path)\n continue\n except:\n print('error occured', image_path)\n with open(outputPath + '/error_image_log.txt', 'a') as log:\n log.write('%s-th image data occured error\\n' % str(image_path))\n continue\n\n if random.randrange(0, 10) > 0: \n imageKey = 'image-%09d'.encode() % cnt_train\n labelKey = 'label-%09d'.encode() % cnt_train\n cache_train[imageKey] = imageBin\n cache_train[labelKey] = label.encode()\n if cnt_train % 1000 == 0:\n writeCache(env_train, cache_train)\n cache_train = {}\n print('Written %d' % (cnt_train))\n cnt_train += 1\n else :\n imageKey = 'image-%09d'.encode() % cnt_val\n labelKey = 'label-%09d'.encode() % cnt_val\n cache_val[imageKey] = imageBin\n cache_val[labelKey] = label.encode()\n if cnt_val % 1000 == 0:\n writeCache(env_val, cache_val)\n cache_val = {}\n print('Written %d' % (cnt_val))\n cnt_val += 1\n\n cache_train['num-samples'.encode()] = str(cnt_train-1).encode()\n writeCache(env_train, cache_train)\n cache_val['num-samples'.encode()] = str(cnt_val-1).encode()\n writeCache(env_val, cache_val)\n print('Created dataset with train: %d val: %dsamples' % (cnt_train-1, cnt_val-1))\n\n\nif __name__ == '__main__':\n fire.Fire(createDataset)\n","sub_path":"create_lmdb_dataset.py","file_name":"create_lmdb_dataset.py","file_ext":"py","file_size_in_byte":5368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"402532100","text":"# -*- coding: utf-8 -*-\n\"\"\"\nLanguage: python3\nGoal: Batch running for Face Recognization test\n\"\"\"\nimport os\nimport sys\nimport time\nimport subprocess\n\nprint(sys.version)\nprint(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))\n### Defs region\ndef startJob(iAdbDevices, appObj, iAppID):\n cmd = \"adb\" + iAdbDevices + \"shell input keyevent 224\"\n (status, output) = subprocess.getstatusoutput(cmd)\n time.sleep(5)\n\n cmd = \"adb\" + iAdbDevices + \"shell am start -n \" + appObj\n (status, output) = subprocess.getstatusoutput(cmd)\n \n while (1):\n cmd = \"adb\" + iAdbDevices + \"shell ps|grep -E \\\"\" + iAppID + \"\\\"\"\n (status, output) = subprocess.getstatusoutput(cmd)\n if \"\" == output:\n print(\"Wait app start: \" + status)\n time.sleep(10)\n else:\n print(\"App start: \" + output)\n break\n return\n\ndef preJobEx(pushThing, dstSuffix, dataDst, logDst, iAdbDevices):\n cmd = \"adb\" + iAdbDevices + \"shell rm -rf \" + logDst + \"/*\"\n (status, output) = subprocess.getstatusoutput(cmd)\n return\n\ndef preJob(pushThing, dstSuffix, dataDst, logDst, iAdbDevices):\n cmd = \"adb\" + iAdbDevices + \"shell rm -rf \" + logDst + \"/*\"\n (status, output) = subprocess.getstatusoutput(cmd)\n\n cmd = \"adb\" + iAdbDevices + \"shell rm -rf \" + dataDst + \"/*\"\n (status, output) = subprocess.getstatusoutput(cmd)\n\n if True:\n cmd = \"adb\" + iAdbDevices + \"push \" + pushThing + \" \" + dataDst + \"/\" \\\n + dstSuffix\n print(\"PushOne: \" + cmd)\n else:\n cmd = \"adb\" + iAdbDevices + \" shell cp -r \" + \"/sdcard/TestFull/\" \\\n + pushThing.split(\"/\")[-1] + \" \" + dataDst\n print(\"CopyOne: \" + cmd)\n\n (status, output) = subprocess.getstatusoutput(cmd)\n time.sleep(60)\n return\n\ndef postJob(logLocal, logRemote, iAdbDevices):\n if not os.path.exists(logLocal):\n os.makedirs(logLocal)\n\n cmd = \"adb\" + iAdbDevices + \"pull \" + logRemote + \" \" + logLocal\n (status, output) = subprocess.getstatusoutput(cmd)\n print(str(output))\n\n if -1 != output.find(\"0 files pulled.\"):\n return False\n else:\n return True\n\n### Params region\ncAdbDevices = \" -s 2255a361 \"\ndataFolder = \"/media/devin/OpenImage600/face3/\"\nobjs = [\"sunhaiyan\", \"xinglj\", \"baoyuandong\"]\nobjs = [\"yanchangjian\"]\n\ncDataDst = \"/sdcard/TestData\"\ncLogDst = \"/sdcard/TestLog\"\ncAppID = \"com.megvii.test\"\ncAppObj = \"com.megvii.test/com.facepp.demo.LoadingActivity\"\ncLocalResults = \"/home/devin/Desktop/tmp/\"\n\nfolderDoneList = \\\n[]\n\n### Job region\nfor obj in objs:\n dataSet = dataFolder + obj + \"/cameraData\"\n for rt, dirs, files in os.walk(dataSet):\n for name in dirs:\n if name in folderDoneList:\n continue\n\n pushOne = os.path.join(rt, name)\n preJob(pushOne, name, cDataDst, cLogDst, cAdbDevices)\n\n if True:\n rtv = False\n while (not rtv):\n print(\"App start~\")\n startJob(cAdbDevices, cAppObj, cAppID)\n while (1):\n cmd = \"adb\" + cAdbDevices + \"shell ps|grep -E \\\"\" \\\n + cAppID + \"\\\"\"\n (status, output) = subprocess.getstatusoutput(cmd)\n # print(status)\n # print(output)\n if \"\" == output:\n print(\"App finished~\")\n break\n else:\n print(\"App running: \" + output)\n cmd = \"adb\" + cAdbDevices \\\n + \"shell input keyevent 224\"\n (status, output) = subprocess.getstatusoutput(cmd)\n time.sleep(30)\n rtv = postJob(cLocalResults + obj, cLogDst, cAdbDevices)\n else:\n for suffix in [\"first/\", \"second/\", \"third/\"]:\n cLocalOriResults = cLocalResults\n cLocalOriResults += suffix\n if not os.path.exists(cLocalOriResults):\n os.makedirs(cLocalOriResults)\n\n preJobEx(pushOne, name, cDataDst, cLogDst, cAdbDevices)\n\n rtv = False\n while (not rtv):\n print(suffix + \": App start~\")\n startJob(cAdbDevices, cAppObj, cAppID)\n while (1):\n cmd = \"adb\" + cAdbDevices + \"shell ps|grep -E \\\"\" \\\n + cAppID + \"\\\"\"\n (status, output) = subprocess.getstatusoutput(cmd)\n # print(status)\n # print(output)\n if \"\" == output:\n print(\"App finished~\")\n break\n else:\n print(\"App running: \" + output)\n cmd = \"adb\" + cAdbDevices \\\n + \"shell input keyevent 224\"\n (status, output) = subprocess.getstatusoutput(cmd)\n time.sleep(30)\n rtv = postJob(cLocalOriResults + obj, cLogDst, cAdbDevices)\n\n folderDoneList.append(name)\n print(\"Folders Done~\")\n for it in folderDoneList:\n print(\"\\\"\" + it + \"\\\",\", end = ' ')\n print()\n print(time.strftime('%H:%M:%S', time.localtime()))\n print(obj + \" \" + str(len(folderDoneList)) + \": \" + name + \" done~\")\n folderDoneList = []\n\nprint(os.linesep)\nprint(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))","sub_path":"jobTool/AutoFrTest.py","file_name":"AutoFrTest.py","file_ext":"py","file_size_in_byte":5788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"119393557","text":"from motor_control import *\nfrom servo_control import *\nfrom gaussian_fit import *\nfrom ccd_time_snap import *\nimport numpy as np\nimport sys\nimport serial\nimport time\nimport threading\nimport copy\nexposure=0.7\ngain=1\npc=20#pixel_clock\ngoaldis=100\ndef step_size():\n return 100\n #sets how far each engine moves for every iteration of gradient descent\ndef image_center(arr):\n return {'x':int(arr.shape[0]/2),'y':int(arr.shape[1]/2)}\ndef distance(pos,goalpos):\n dis=(pos['x']-goalpos['x'])**2+(pos['y']-goalpos['y'])**2\n return dis\ndef optimal_movement(light):#calculates the movement of motors along the \"gradient\"\n step=step_size()\n dist0=np.array([distance(d.center,d.goalpos)for d in light.dots])\n dist=np.zeros([light.motors.size,light.dots.size])\n derivative=np.zeros([light.motors.size,light.dots.size])#initialize what will become the gradient\n for index,motor in enumerate(light.motors):\n move(motor,int(step))\n for i,d in enumerate(light.dots):\n d.take_picture()\n dist[index][i]=distance(d.center,d.goalpos)\n move(motor,-int(step))#find how distance varies with each parameter\n for k in range(light.motors.size):\n for l in range(light.dots.size):\n derivative[k,l]=(dist[k,l]-dist0[l])/step\n derivative=np.sum(derivative,axis=1)#sum the contrubutions of both dots\n movement=(-1)*(derivative*(step/(np.sum(np.absolute(derivative)))))\n movement=np.rint(movement).astype(int)\n return movement\ndef optimize(light):\n for d in light.dots:\n d.take_picture()\n while(max([distance(d.center,d.goalpos)for d in light.dots]) >goaldis):#ta skladnia pewnie tak nie dziala\n movement=optimal_movement(light)\n for i,m in enumerate(movement):\n print(\"motor: \",light.motors[i],\"movement: \",m,\"\\n\" )\n print(\"\\n\")\n for index,motor in enumerate(light.motors):\n move(motor,movement[index])\n for d in light.dots:\n d.take_picture()\n id=(d.servos[0].id-1)*2+(d.servos[1].id-3)+1\n f=open(\"center\"+str(id)+\".pos\",\"a+\")\n f.write(str(d.center['x'])+\" \"+str(d.center['y'])+\"\\n\")\n f.close()\ndef run_experiment(beams):\n for light in beams:\n for d in light.dots:\n d.take_picture()\n optimize(light)\nclass servo(object):\n def __init__(self,num,openpos,closedpos):\n self.id=num\n self.op=openpos\n self.cp=closedpos#angle which cuts off the beam corresponding to this dot at some point\nclass dot(object):\n def __init__(self,servos,image=None,goalpos=None):\n if(image is not None):\n self.image=image\n else:\n self.image=np.empty([1280,1024,3])\n self.center=find_center(self.image)\n self.servos=servos\n if(goalpos is None):\n self.goalpos=image_center(self.image)\n else:\n self.goalpos=goalpos \n def take_picture(self):\n for s in servos:\n if s in self.servos:\n print(\"turning: \",s.id,\" to open position: \",s.op)\n turn(s.id,s.op)\n time.sleep(0.1)\n else:\n print(\"turning: \",s.id,\" to closed position: \",s.cp)\n turn(s.id,s.cp)\n time.sleep(0.1)\n time.sleep(0.5)\n UEye420_Snapper(Exposure=exposure,Gain=gain,File_Location=\"./photo_tmp.bmp\", pixel_clock=pc)\n self.image=np.array(Image.open(\"./photo_tmp.bmp\"))\n self.center=find_center(self.image)\nclass beam(object):\n def __init__(self,motors,servos,prev_pos=None,goalpos=None):\n self.motors=np.array(motors)\n self.dots=[]\n self.dots.append(dot([servos[0],servos[1]]))\n self.dots.append(dot([servos[0],servos[2]]))\n self.dots=np.array(self.dots)\nservos=[servo(1,90,0),servo(2,60,150),servo(3,0,90),servo(4,180,90)]\n#to zdjecie jest tymczasowe i nic nigdzie nie robi\nmoved_beams=[beam(motors=[1,2,3,4],servos=[servos[0]]+servos[2:4]),beam(motors=[5,6,7,8],servos=[servos[1]]+servos[2:4])]\nfor d in moved_beams[0].dots:\n d.take_picture()\nmoved_beams[1].dots[0].goalpos=moved_beams[0].dots[0].center\nmoved_beams[1].dots[1].goalpos=moved_beams[0].dots[1].center\nmoved_beams[0].dots[0].goalpos=moved_beams[0].dots[0].center\nmoved_beams[0].dots[1].goalpos=moved_beams[0].dots[1].center\n#this way the first beam is assumed to be centered\nrun_experiment([moved_beams[1]])\n\n","sub_path":"align_lasers.py","file_name":"align_lasers.py","file_ext":"py","file_size_in_byte":4433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"514012684","text":"data = {\n 'name': 'Hanzo main',\n 'nickname': 'sloth',\n 'image': '4.jpg',\n 'greeting_msg': 'Hello!!',\n 'about': \"\"\"\n Hanzo is gay, he married in 2014 with s76,his wife. He always gonna war in world of overwatch. He kill everyone who he got they in his sides with Golden bow. Sometimes, he fight by has his wife to help him. This is Hanjo's story..\n \"\"\",\n 'work': {\n 'position': 'Hanjo#500',\n 'at': 'shimada Clan'\n },\n 'courses': [\n {\n 'name': 'How to aim with golden arrows',\n 'school': 'shimada Clan',\n 'url': 'kobayashimaru'\n },\n {\n 'name': 'Advanced aim like pro-player',\n 'school': 'shimada Clan',\n 'url': 'adv-nav'\n },\n {\n 'name': 'Basic sonic arrows',\n 'school': 'shimada Clan',\n 'url': 'warp-design'\n },\n {\n 'name': 'Klingon Physiology',\n 'school': 'shimada Institute of Technology',\n 'url': 'klingon-phys'\n }\n ],\n 'skills': [\n 'fightin with older',\n 'leader',\n 'kill someone by one shot!',\n 'to powerfull in sketter arrow',\n 'hard to kill with 1 by 1',\n 'Sleep every time by Ana'\n ]\n}\n","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"637432184","text":"from dataChest import *\nfrom scipy.optimize import curve_fit\nimport matplotlib.pyplot as plt\n\n#Z:\\mcdermott-group\\data\\Micromachining\\2022-09-22 - DR2\\MAS\\MM_1\\11-11-22\\T1_Poisoning_vs_bias_time_vary_idle\npath = ['Micromachining', '2022-09-22 - DR2', 'MAS','MM_1','11-14-22', 'T1_Poisoning_vs_bias_time_vary_idle']\ndc = dataChest(path)\ncontents = dc.ls()\nfiles = contents[0]\nf = files[0]\nprint(f)\ndc.openDataset(f)\nvarsList = dc.getVariables()\n# print(varsList)\ndata = dc.getData(variablesList=['Single Shot Occupation', 'Idle Time', 'Bias Time'])\nstates = data[:,0]\n# print(data)\nidle = data[:,1]\nbias = data[:,2]\n\n#find the dimension of one of the axis and then find the other dimension\ncount = 0\nfor i in range(len(bias)):\n if(bias[i] != bias[i-1]):\n count = count + 1\n\ndim_bias = int(count)\ndim_idle = int(len(states)/dim_bias)\n\n#take the first couple entries of the axis that doesn't repeat immediately\nidle_sep = idle[:dim_idle]\n\nbias_sep = []\n#for every 61'st element (the idle dimension) we want to add a bias to our list\nfor i in range(dim_bias):\n bias_sep.append(bias[dim_idle*i])\n\n#Reshape the states vector into the relevant matrix\nstate_sep = np.reshape(states, (dim_bias, dim_idle))\n# print(state_sep[:][0])\n\n#fit\ndef func(x, a, b, c):\n return a * np.exp(-b * x) + c\n\n\n# print(len(idle_sep), len(state_sep[:][0]))\n\ngamma = []\nfor j in range(dim_bias):\n # plt.plot(idle_sep, state_sep[:][j])\n # plt.show\n #fit to f(t)=A*exp(-B*t)+C\n popt, pcov = curve_fit(func, idle_sep, state_sep[:][j], [0.7, 1/20000, 0.2])\n gamma.append(popt[1])\n\ngamma = np.array(gamma)*1000\nbias_sep = np.array(bias_sep)/1000\n\nplt.plot(bias_sep, gamma)\nplt.xlabel(\"bias time [us]\")\nplt.ylabel(r'$\\Gamma_1$ [1/us]')\nplt.show()","sub_path":"projects/MM/T1_Poisoning_bias_time_Fit.py","file_name":"T1_Poisoning_bias_time_Fit.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"497961330","text":"import os\nimport time\nimport csv\nimport requests\nfrom bs4 import BeautifulSoup\nimport jieba\nfrom wordcloud import WordCloud\nfrom tqdm import tqdm\n\n\nHEADERS = {\n \"X-Requested-With\": \"XMLHttpRequest\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36\"\n \"(KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36\",\n}\n\n\nSTART_URL = (\"https://search.51job.com/list/020000,000000,0000,00,9,99,Python,2,{}.html?\"\n \"lang=c&stype=1&postchannel=0000&workyear=02&cotype=99°reefrom=99&jobterm=99&\"\n \"companysize=99&lonlat=0%2C0&radius=-1&ord_field=0&confirmdate=9&fromType=&dibiaoid=0\"\n \"&address=&line=&specialarea=00&from=&welfare=\"\n )\n\nget_urls = []\n\ndef job_spider():\n \"\"\"\n 获取职位详情的url链接\n \"\"\"\n urls = [START_URL.format(p) for p in range(1,4)]\n print(\"正在获取链接\")\n\n for url in urls:\n html = requests.get(url, headers=HEADERS).content.decode(\"gbk\")\n bs = BeautifulSoup(html, \"lxml\").find(\"div\", class_=\"dw_table\").find_all(\n \"div\", class_=\"el\"\n )\n for b in bs:\n try:\n href, post = b.find(\"a\")[\"href\"], b.find(\"a\")[\"title\"]\n get_urls.append(href)\n except Exception:\n continue\n\n\ndef job_details():\n \"\"\"\n 获取职位详细信息,薪资待遇、任职要求等\n :return:\n \"\"\"\n print(\"正在下载职位详细信息\")\n \"这里会删除原文件\"\n\n if os.path.exists(\"./post_salary.csv\"):\n os.remove(\"./post_salary.csv\")\n if os.path.exists(\"./post_require.txt\"):\n os.remove(\"./post_require.txt\")\n for url in get_urls:\n r = requests.get(url, headers=HEADERS)\n html = r.text\n\n try:\n soup = BeautifulSoup(html,\"lxml\")\n post = soup.find(\"div\",class_=\"cn\").find(\"h1\").text\n salary = soup.find(\"div\",class_=\"cn\").find(\"strong\").text\n txt = soup.find(class_=\"msg ltype\").text.strip()\n c_txt = txt.replace(\"|\",\",\")\n t_txt = salary + \",\" + post +\",\" + c_txt\n d_txt = \"\".join(t_txt.split())\n e_txt = d_txt + \"\\n\"\n\n with open(\"post_salary.csv\",\"a\",encoding=\"utf-8\") as f:\n f.write(e_txt)\n f.close()\n bs = BeautifulSoup(html, \"lxml\").find(\n \"div\", class_=\"bmsg job_msg inbox\"\n ).text\n s = bs.replace(\"微信\", \"\").replace(\"分享\", \"\").replace(\"邮件\", \"\").replace(\n \"\\t\", \"\"\n ).strip()\n with open(\"post_require.txt\", 'a', encoding=\"utf-8\") as f:\n f.writelines(s)\n f.close()\n except Exception:\n continue\n\n\ndef post_salary():\n \"\"\"\n 整理职位信息,取薪资、学历、经验、职位、地点\n \"\"\"\n\n print(\"正在统一处理薪资单位\")\n re_post = []\n\n with open(\"post_salary.csv\", \"r\", encoding=\"utf-8\") as f:\n f_csv = csv.reader(f)\n\n for row in f_csv:\n #if not \"郑州\" in row[2]:\n # continue\n if not \"上海\" in row[2]:\n continue\n if \"千/月\" in row[0]:\n row[0] = row[0][:-3] + \",1\"\n re_post.append((row[0], row[4], row[3],row[1],row[2]))\n if \"万/月\" in row[0]:\n row[0] = row[0][:-3] + \",10\"\n re_post.append((row[0], row[4], row[3],row[1],row[2]))\n if \"万/年\" in row[0]:\n row[0] = row[0][:-3] + \",0.8\"\n re_post.append((row[0], row[4], row[3],row[1],row[2]))\n\n with open(\"re_post_salary.csv\",\"w\",encoding=\"utf-8\",newline=\"\") as f:\n r_csv = csv.writer(f)\n r_csv.writerows(re_post)\n\n\ndef post_key():\n \"\"\"\n 统计职位要求中的关键字排名\n \"\"\"\n print(\"正在提取关键字\")\n\n txt = open(\"post_require.txt\", \"r\", encoding=\"utf-8\").read()\n seg_list = jieba.lcut(txt)\n counts = {}\n \"关键字与排名之间存在对应关系,选择用字典\"\n for seg in seg_list:\n if len(seg) == 1:\n continue\n else:\n counts[seg] = counts.get(seg, 1) + 1\n item_sort = sorted(counts.items(), key=lambda value: value[1], reverse=True)\n\n with open(\"post_key.csv\", \"w\", encoding=\"utf-8\", newline=\"\") as f:\n f_csv = csv.writer(f)\n f_csv.writerows(item_sort)\n\ndef word_cloud():\n \"\"\"\n 生成词云\n \"\"\"\n print(\"词云图片将保存在wc.jpg\")\n\n counter = {}\n with open(\"post_key.csv\", \"r\", encoding=\"utf-8\") as f:\n f_csv = csv.reader(f)\n for row in f_csv:\n counter[row[0]] = counter.get(row[0], int(row[1]))\n # pprint(counter)\n wc = WordCloud(\n font_path=\"msyh.ttf\", max_words=15, height=600, width=1200\n ).generate_from_frequencies(\n counter\n )\n\n wc.to_file(\"wc.jpg\")\n\n\njob_spider()\njob_details()\npost_key()\npost_salary()\nword_cloud()\n","sub_path":"51job.py","file_name":"51job.py","file_ext":"py","file_size_in_byte":4960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"649789236","text":"from functools import lru_cache\nfrom urllib.parse import unquote\n\nfrom bs4 import BeautifulSoup\n\nfrom ..core.website import Website\nfrom ..core.session import session\n\n\nclass MondeDiplomatique(Website):\n\n base_url = \"https://www.monde-diplomatique.fr/\"\n login_url = \"https://lecteurs.mondediplo.net/?page=connexion_sso\"\n alias = [\"diplomatique\", \"diplo\"]\n\n description_meta = {\"name\": [\"description\"]}\n\n article_node = (\"div\", {\"class\": \"texte\"})\n\n clean_nodes = [\"figure\", \"div\", \"small\", \"a\"]\n clean_attributes = [\"h3\", \"span\"]\n\n @property\n def login_dict(self):\n credentials = self.credentials\n assert credentials is not None\n\n c = session.get(self.login_url)\n c.raise_for_status()\n\n e = BeautifulSoup(c.content, features=\"lxml\")\n attrs = dict(name=\"formulaire_action_args\")\n form_id = e.find(\"input\", attrs=attrs).attrs[\"value\"]\n\n return {\n \"formulaire_action\": \"identification_sso\",\n \"formulaire_action_args\": form_id,\n \"retour\": \"https://www.monde-diplomatique.fr/\",\n \"site_distant\": \"https://www.monde-diplomatique.fr/\",\n \"valider\": \"Valider\",\n \"email\": credentials[\"username\"],\n \"mot_de_passe\": credentials[\"password\"],\n }\n\n @lru_cache()\n def latest_issue_url(self):\n\n c = session.get(self.base_url)\n c.raise_for_status()\n\n e = BeautifulSoup(c.content, features=\"lxml\")\n\n current = e.find(\"a\", attrs={\"id\": \"entree-numero\"}).attrs[\"href\"]\n\n c = session.get(self.base_url + current)\n c.raise_for_status()\n\n e = BeautifulSoup(c.content, features=\"lxml\")\n\n attrs = {\"class\": \"format PDF\"}\n url = e.find(\"div\", attrs=attrs).find(\"a\").attrs[\"href\"]\n return self.base_url + url\n\n def file_name(self, c) -> str:\n return unquote(\n c.headers[\"Content-Disposition\"]\n .split(\";\")[1]\n .split(\"=\")[1]\n .strip('\"')\n )\n","sub_path":"kiosque/website/mondediplomatique.py","file_name":"mondediplomatique.py","file_ext":"py","file_size_in_byte":2016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"178545557","text":"#!/usr/bin/python\n#\n# (C) 2018 Hyrax Authors\n#\n# cffi interface to MIRACL\n# TODO look at how numpypy gets bigints back and forth to C\n#\n# pylint: disable=unused-variable\n\nfrom itertools import islice\nimport os.path as OP\nimport random\n\n# set up FFI\nimport cffi\nffi = cffi.FFI()\nffi.cdef(\"\"\"\n void pymr_clear(void);\n char **pymr_set_curve(char *filename, int nelms, bool check_points);\n char **pymr_pow_gh(char *varg, char *varh);\n char **pymr_pow_g(char *varg);\n char **pymr_pow_h(char *varh);\n char **pymr_maul(char **bval, char *xval);\n char **pymr_exp_mul(char **bmvals, char *xval);\n char **pymr_exp_powh(char **bval, char *xval, char *yval);\n char **pymr_exp(char **bval, char *xval);\n char **pymr_div(char **bcvals);\n char **pymr_mul(char **bcvals);\n char **pymr_sqr(char **bval);\n char **pymr_multiexp(char **blst, char **xlst, unsigned num);\n char **pymr_multimul(char **blst, unsigned lb);\n char **pymr_pow_gih(char **lst, unsigned lx, char *varh, unsigned nstart);\n char **pymr_pow_gi(char **lst, unsigned lx, unsigned nstart, int nskip);\n char **pymr_decompress(char *xval);\n char *pymr_compress(char **bval);\n char *pymr_get_error(void);\n int *pymr_get_sizes(void);\n\"\"\")\nmircffi = ffi.dlopen(OP.join(OP.dirname(OP.realpath(__file__)), 'lib', 'pymircffi.so'))\n\nclass MiraclEC(object):\n # pylint: disable=too-many-public-methods\n curve = 'm191'\n\n def __init__(self, curve=None, maxbases=-1, check_points=False, keepstrs=False):\n self.rand = random.SystemRandom()\n self.keepstrs = keepstrs\n\n self.curve = curve if curve is not None else self.curve\n ecsfile = self.ec_file_path(self.curve)\n (self.q, self.maxlen) = self.set_curve(ecsfile, maxbases, check_points)\n self.set_data_sizes()\n\n self.g = self.pow_g(1)\n self.h = self.pow_h(1)\n self.gh = self.pow_gh(1, 1)\n\n @staticmethod\n def ec_file_path(curve):\n return OP.join(OP.dirname(OP.realpath(__file__)), 'ecslib', '%s_multi.ecs'%curve)\n\n @staticmethod\n def get_curve_line(curve, num):\n with open(MiraclEC.ec_file_path(curve), 'r') as f:\n return [ f.readline() for _ in xrange(0, num) ][-1]\n\n @staticmethod\n def get_order(curve):\n return int(MiraclEC.get_curve_line(curve, 5), 16)\n\n @staticmethod\n def get_field(curve):\n return int(MiraclEC.get_curve_line(curve, 2), 16)\n\n @staticmethod\n def clear():\n mircffi.pymr_clear()\n\n def points_to_cstrs(self, points, length=None):\n if length is None:\n length = len(points)\n # allocate one giant output string\n outdata = ffi.new('char []', length * self.point_size)\n offsets = [None] * 2 * length\n for (idx, point) in enumerate(islice(points, length)):\n if isinstance(point[0], str):\n xstr = point[0]\n ystr = point[1]\n else:\n xstr = '%x'%point[0]\n ystr = '%x'%point[1]\n ioff = self.point_size * idx\n offsets[2*idx] = outdata + ioff\n offsets[2*idx+1] = outdata + ioff + self.scalar_size\n ffi.memmove(offsets[2*idx], xstr, len(xstr))\n ffi.memmove(offsets[2*idx+1], ystr, len(ystr))\n return (ffi.new('char *[]', offsets), outdata)\n\n def scalars_to_cstrs(self, scalars, length=None):\n if length is None:\n length = len(scalars)\n # allocate one giant output string\n outdata = ffi.new('char []', length * self.scalar_size)\n offsets = [None] * length\n for (idx, scalar) in enumerate(islice(scalars, length)):\n outstr = '%x'%scalar\n offsets[idx] = outdata + self.scalar_size * idx\n ffi.memmove(offsets[idx], outstr, len(outstr))\n return (ffi.new('char *[]', offsets), outdata)\n\n def set_data_sizes(self):\n data_sizes = ffi.unpack(mircffi.pymr_get_sizes(), 3)\n # scalar_size has to fit either a struct big or a string encoding a data_sizes[0]-bit number\n self.scalar_size = max(2 + (data_sizes[0] + 3) // 4, data_sizes[1])\n # point_size has to fit either two scalar_sizes or a struct epoint\n self.point_size = max(2 * self.scalar_size, data_sizes[2])\n\n def return_point(self, cstrs, force=False):\n if cstrs == ffi.NULL:\n raise RuntimeError(ffi.string(mircffi.pymr_get_error()))\n\n if self.keepstrs and not force:\n return (ffi.string(cstrs[0]), ffi.string(cstrs[1]))\n return (int(ffi.string(cstrs[0]), 16), int(ffi.string(cstrs[1]), 16))\n\n def rand_scalar(self):\n return self.rand.randint(1, self.q - 1)\n\n def set_curve(self, ecsfile, max_bases, check_points):\n return self.return_point(mircffi.pymr_set_curve(ecsfile, max_bases, check_points), True)\n\n def compress(self, point):\n if point == (0, 0):\n return None\n else:\n (arg, refs) = self.points_to_cstrs((point,))\n ret = mircffi.pymr_compress(arg)\n if ret == ffi.NULL:\n raise RuntimeError(ffi.string(mircffi.pymr_get_error()))\n if self.keepstrs:\n return ffi.string(ret)\n return int(ffi.string(ret), 16)\n\n def decompress(self, point):\n if point is None:\n return (0, 0)\n return self.return_point(mircffi.pymr_decompress('%x'%point))\n\n def pow_gh(self, valg, valh):\n return self.return_point(mircffi.pymr_pow_gh('%x'%valg, '%x'%valh))\n\n def pow_g(self, valg):\n return self.return_point(mircffi.pymr_pow_g('%x'%valg))\n\n def pow_h(self, valh):\n return self.return_point(mircffi.pymr_pow_h('%x'%valh))\n\n def maul(self, bval, xval):\n (arg, refs) = self.points_to_cstrs((bval,))\n return self.return_point(mircffi.pymr_maul(arg, '%x'%xval))\n\n # maybe\n def exp_mul(self, bval, xval, mval):\n (arg, refs) = self.points_to_cstrs((bval, mval))\n return self.return_point(mircffi.pymr_exp_mul(arg, '%x'%xval))\n\n def exp_powh(self, bval, xval, yval):\n (arg, refs) = self.points_to_cstrs((bval,))\n return self.return_point(mircffi.pymr_exp_powh(arg, '%x'%xval, '%x'%yval))\n\n def exp(self, bval, xval):\n (arg, refs) = self.points_to_cstrs((bval,))\n return self.return_point(mircffi.pymr_exp(arg, '%x'%xval))\n\n def div(self, c1val, c2val):\n (arg, refs) = self.points_to_cstrs((c1val, c2val))\n return self.return_point(mircffi.pymr_div(arg))\n\n def mul(self, c1val, c2val):\n (arg, refs) = self.points_to_cstrs((c1val, c2val))\n return self.return_point(mircffi.pymr_mul(arg))\n\n def sqr(self, c1val):\n (arg, refs) = self.points_to_cstrs((c1val,))\n return self.return_point(mircffi.pymr_sqr(arg))\n\n def multiexp(self, bvals, xvals, length=None):\n if length is None:\n length = min(len(bvals), len(xvals))\n (arg, refs) = self.points_to_cstrs(bvals, length)\n (arg2, refs2) = self.scalars_to_cstrs(xvals, length)\n return self.return_point(mircffi.pymr_multiexp(arg, arg2, length))\n\n def multimul(self, bvals):\n (arg, refs) = self.points_to_cstrs(bvals)\n return self.return_point(mircffi.pymr_multimul(arg, len(bvals)))\n\n def pow_gih(self, lvalg, valh, gi, length=None):\n if length is None:\n length = len(lvalg)\n (arg, refs) = self.scalars_to_cstrs(lvalg, length)\n return self.return_point(mircffi.pymr_pow_gih(arg, length, '%x'%valh, gi))\n\n def pow_gi(self, lvalg, gi, skip=1, length=None):\n if length is None:\n length = len(lvalg)\n (arg, refs) = self.scalars_to_cstrs(lvalg, length)\n return self.return_point(mircffi.pymr_pow_gi(arg, length, gi, skip))\n\n def pow_gij(self, i, j, valx1, valx2):\n (arg, refs) = self.scalars_to_cstrs((valx1, valx2))\n return self.return_point(mircffi.pymr_pow_gi(arg, 2, min(i,j), abs(j-i)))\n","sub_path":"src/fennel/pymircffi/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"126376439","text":"import random\ndef sort_colors(arr):\n\tred, white, blue = 0, 0, len(arr) - 1\n\n\twhile white <= blue:\n\t\tif arr[white] == 0:\n\t\t\tarr[red], arr[white] = arr[white], arr[red]\n\t\t\tred += 1\n\t\t\twhite += 1\n\n\t\telif arr[white] == 1:\n\t\t\twhite += 1\n\n\t\telse:\n\t\t\tarr[white], arr[blue] = arr[blue], arr[white]\n\t\t\tblue -= 1\n\n\treturn arr\n\ntest_arr = [0, 2, 1, 2, 0, 0, 1, 1, 0, 2, 1, 0, 2, 0, 2, 0, 1, 1]\nprint(sort_colors(test_arr))\n\n#print(random.sample(range(1, 20), 18))","sub_path":"SortColors.py","file_name":"SortColors.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"405962769","text":"\"\"\"webissues URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.8/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Add an import: from blog import urls as blog_urls\n 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))\n\"\"\"\nfrom django.conf.urls import include, url\nfrom track.views import *\n#from django.contrib.auth import views\nfrom track import views\nfrom django.contrib.auth.views import login, logout\nfrom django.contrib.auth.views import logout,login\nfrom track.form import *\nfrom rest_framework import routers\nfrom django.views.generic import TemplateView\nfrom django.contrib import admin\n\nrouter=routers.DefaultRouter()\nrouter.register('issue',IssueSet)\nrouter.register('project',ProjectSet)\nrouter.register('user',UserSet)\n\nurlpatterns = [\n #url('',include('track.url',namespace='track')),\n url(r'^api/',include(router.urls)),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^$',index,name='index'),\n url(r'^index/',index,name='index'),\n url(r'^accounts/login/',views.login,name='login'),\n #url(r'login',views.loginview,name='loginview'),\n #url(r'^accounts/login',views.login,{'template_name': 'registration/logins.html', 'authentication_form': LoginForm}),\n #url(r'accounts/logout',views.logout,{'next_page':'/login'}),\n #url(r'^accounts/login',login.as_view(),name='login'),\n url(r'^accounts/auth/',auth_view,name='auth'),\n url(r'^nav',TemplateView.as_view(template_name='new_nav.html')),\n url(r'^accounts/logout/',logout,{'template_name':'registration/logout.html'}),\n url(r'^accounts/profile/',profile,name='profile'),\n url(r'^accounts/auth/',auth_view,name='authview'),\n url(r'^total',noproject,name='number_of_project'),\n url(r'^issues/(?P\\d+)$',edit,name='issue_edit'),\n url(r'^updateproject/(?P\\d+)$',projectupdate,name='project_edit'),\n url(r'^project/(?P\\d+)$',projectis_issue,name='project_issue'),\n url(r'^create/(?P\\d+)$',create,name='create_issue'),\n url(r'^create/$',selectproject,name='project_selection'),\n url('^new/',new,name='new'),\n url(r'^edit/',edit,name='edit'),\n url(r'^delete/(?P\\d+)$',delete_issue,name='delete_issue'),\n url(r'^test',export_csv,name='csv'),\n url(r'^create/project$',create_project,name='create_project'),\n url(r'^api/',include('rest_framework.urls',namespace='rest_framework'))\n]\n","sub_path":"webissues/webissues/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"393150873","text":"\nfrom procesos import *\nfrom visualizacion import *\n\nif __name__ == '__main__':\n [X, T, PHI] = cargar_txt(experimental_data_file, '\\\\07-05-2021\\\\f=15.22_a=6.0', X='X', T='T', PHI='PHI')\n img_file = 'E:\\mnustes_science\\images\\img_lab\\\\07-05-2021\\\\f=15.22_a=6.0'\n\n ########## PROCESOS Y OTROS #########\n X = np.array([i - X[-1] / 2 for i in X])\n PHI_filtrado = filtro_superficie(PHI, 10, 'YX')\n mean, std = proyeccion_desvesta(PHI_filtrado)\n PHI_filtrado = nivel(PHI_filtrado, mean)\n PHI_proyectado, frec, power_density = proyeccion_maximos(PHI_filtrado)\n PHI_std = (PHI_proyectado[np.argmax(PHI_proyectado)] / std[np.argmax(std)]) * std\n\n #################### CONVERSION A CM ##################\n [X, PHI_proyectado, PHI_std] = resize_arrays_referenced(4, [X, PHI_proyectado, PHI_std], img_file)\n sinegauss_fit, parametros = fit_gauss_sin(X, PHI_std)\n gaussian_fit = gauss(X, parametros[0], parametros[1])\n visualizacion(X, [PHI_std, sinegauss_fit, gaussian_fit], ['r', 'grey', 'black'], ['-', ':', '--'],\n tipo=\"2D_multiple\", guardar='si',\n path=experimental_data_file, file='\\\\07-05-2021\\\\f=15.22_a=6.0\\\\datos_procesados',\n nombre='plot')\n guardar_txt(experimental_data_file, '\\\\07-05-2021\\\\f=15.22_a=6.0\\\\datos_procesados', X=X, parametros=parametros, PHI_std=PHI_std, sinegauss_fit=sinegauss_fit, gaussian_fit=gaussian_fit)\n","sub_path":"Experimento/codigos_fallidos/faraday_gaussian_fit.py","file_name":"faraday_gaussian_fit.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"388982372","text":"from __future__ import print_function\n\nimport os\nimport ase.io\nimport ipywidgets as ipw\nfrom ipywidgets import Layout\nfrom IPython.display import clear_output\nfrom fileupload import FileUploadWidget\nimport tarfile\nimport zipfile\nimport tempfile\nimport nglview\n\n\nclass MultiStructureUploadWidget(ipw.VBox):\n def __init__(self, text=\"Upload Zip or Tar archive\", node_class=None, **kwargs):\n \"\"\" Upload multiple structures and store them in AiiDA database.\n\n :param text: Text to display before upload button\n :type text: str\n :param node_class: AiiDA node class for storing the structure.\n Possible values: 'StructureData', 'CifData' or None (let the user decide).\n Note: If your workflows require a specific node class, better fix it here.\n \"\"\"\n\n self.file_upload = FileUploadWidget(text)\n\n # define the view part of the widget\n self.viewer = nglview.NGLWidget()\n self.selection_slider = ipw.SelectionSlider(\n options=[None,],\n disabled=False,\n orientation='vertical',\n description='Browse structures:',\n readout=False,\n layout = Layout(width='50%'),\n )\n view = ipw.HBox([self.viewer, self.selection_slider])\n\n # define the action part of the widget\n self.btn_store_all = ipw.Button(description='Store all in AiiDA', disabled=True)\n self.btn_store_selected = ipw.Button(description='Store selected', disabled=True)\n self.structure_description = ipw.Text(placeholder=\"Description (optional)\")\n self.data_format = ipw.RadioButtons(\n options=['StructureData', 'CifData'], description='Data type:')\n\n # if node_class is predefined, there is no need to select it afterwards\n if node_class is None:\n store = ipw.HBox(\n [self.btn_store_all, self.data_format, self.structure_description, self.btn_store_selected])\n else:\n store = ipw.HBox([self.btn_store_all, self.structure_description, self.btn_store_selected])\n self.data_format.value = node_class\n\n # define main data objects\n self.structure_ase = None # contains the selected structure in the ase format\n self.structure_nodes = [] # a list that contains all stored structure objects\n self.structure_names = [] # list of uploaded structures\n\n # put all visual parts in children list and initialize the parent Vbox widget with it\n children = [self.file_upload, view, store]\n super(MultiStructureUploadWidget, self).__init__(\n children=children, **kwargs)\n\n # attach actions to the buttons\n self.file_upload.observe(self._on_file_upload, names='data')\n self.selection_slider.on_trait_change(self.change_structure, 'value')\n self.btn_store_all.on_click(self._on_click_store_all)\n self.btn_store_selected.on_click(self._on_click_store_selected)\n\n # create aiida-related things\n from aiida import load_dbenv, is_dbenv_loaded\n from aiida.backends import settings\n if not is_dbenv_loaded():\n load_dbenv(profile=settings.AIIDADB_PROFILE)\n\n # function to be called when selection_slider changes\n def change_structure(self):\n if self.selection_slider.value is None:\n pass\n else:\n self.select_structure(filepath=self.selection_slider.value)\n\n # pylint: disable=unused-argument\n def _on_file_upload(self, change):\n # I redefine both: structure_names and structure_nodes, since we are now uploading a different archive\n self.structure_names = []\n self.structure_nodes = []\n\n # download an archive and put its content into a file\n archive = tempfile.NamedTemporaryFile(suffix=self.file_upload.filename)\n with open(archive.name, 'w') as f:\n f.write(self.file_upload.data)\n self.archive_name = archive.name\n\n # create a temporary folder where all the structure will be extracted\n self.tmp_folder = tempfile.mkdtemp()\n\n # extract tar archive\n if tarfile.is_tarfile(self.archive_name):\n try:\n with tarfile.open(self.archive_name, \"r:*\", format=tarfile.PAX_FORMAT) as tar:\n if not tar.getmembers():\n raise ValueError(\"The input tar file is empty.\")\n for member in tar.getmembers():\n tar.extract(path=self.tmp_folder, member=member)\n except tarfile.ReadError:\n raise ValueError(\"The input tar file is corrupted.\")\n\n # extract zip archive\n elif zipfile.is_zipfile(self.archive_name):\n try:\n with zipfile.ZipFile(self.archive_name, \"r\", allowZip64=True) as zipf:\n if not zipf.namelist():\n raise ValueError(\"The input zip file is empty.\")\n for member in zipf.namelist():\n zipf.extract(path=self.tmp_folder, member=member)\n except zipfile.BadZipfile:\n raise ValueError(\"The input zip file is corrupted.\")\n else:\n raise ValueError(\"The file you provided does not look like Zip or Tar archive\")\n\n # put all extracted files into a list\n for (dirpath, dirnames, filenames) in os.walk(self.tmp_folder):\n for filename in filenames:\n self.structure_names.append(dirpath+'/'+filename)\n if not self.structure_names:\n raise ValueError(\"Even though the input archive seem not to be empty, it does not contain any file\")\n\n # redefining the options for the slider and its default value\n # together with slider's value update the structure selection also changes,\n # as change_structure() called on slider's value change\n self.selection_slider.options = self.structure_names\n self.selection_slider.value = self.structure_names[0]\n\n def get_ase(self, filepath):\n file_sub_path = filepath[len(self.tmp_folder)+1:]\n try:\n traj = ase.io.read(filepath, index=\":\")\n except AttributeError:\n print(\"Looks like {} file does not contain structure coordinates\".format(file_sub_path))\n return None\n if len(traj) > 1:\n print(\"Warning: Uploaded file {} contained more than one structure. \"\n \"I take the first one.\".format(file_sub_path))\n return traj[0]\n\n def get_description(self, structure_ase, filepath):\n formula = structure_ase.get_chemical_formula()\n return \"{} ({})\".format(formula, filepath.split('/')[-1])\n\n def select_structure(self, filepath):\n structure_ase = self.get_ase(filepath)\n self.btn_store_all.disabled = False\n self.btn_store_selected.disabled = False\n\n if structure_ase is None:\n self.structure_ase = None\n self.btn_store_selected.disabled = True\n self.refresh_view()\n return\n\n self.structure_description.value = self.get_description(structure_ase, filepath)\n self.structure_ase = structure_ase\n self.refresh_view()\n\n\n def refresh_view(self):\n viewer = self.viewer\n # Note: viewer.clear() only removes the 1st component\n # pylint: disable=protected-access\n for comp_id in viewer._ngl_component_ids:\n viewer.remove_component(comp_id)\n if self.structure_ase is None:\n return\n viewer.add_component(nglview.ASEStructure(\n self.structure_ase)) # adds ball+stick\n viewer.add_unitcell()\n\n # pylint: disable=unused-argument\n def _on_click_store_all(self, change):\n self.structure_nodes = []\n # comment this if you are sure that it is safe, and the selection_slider does not interfere with store_structure() function\n self.selection_slider.disabled = True\n for filepath in self.structure_names:\n self.store_structure(filepath)\n # comment this if you are sure that it is safe, and the selection_slider does not interfere with store_structure() function\n self.selection_slider.disabled = False\n\n # pylint: disable=unused-argument\n def _on_click_store_selected(self, change):\n self.store_structure(self.selection_slider.value, description=self.structure_description.value)\n\n def store_structure(self, filepath, description=None):\n structure_ase = self.get_ase(filepath)\n if structure_ase is None:\n return\n\n # determine data source\n if filepath.endswith('.cif'):\n source_format = 'CIF'\n else:\n source_format = 'ASE'\n\n # perform conversion\n if self.data_format.value == 'CifData':\n if source_format == 'CIF':\n from aiida.orm.data.cif import CifData\n structure_node = CifData(\n file=filepath,\n scan_type='flex',\n parse_policy='lazy')\n else:\n from aiida.orm.data.cif import CifData\n structure_node = CifData()\n structure_node.set_ase(structure_ase)\n else:\n # Target format is StructureData\n from aiida.orm.data.structure import StructureData\n structure_node = StructureData(ase=structure_ase)\n\n #TODO: Figure out whether this is still necessary for StructureData\n # ensure that tags got correctly translated into kinds\n for t1, k in zip(structure_ase.get_tags(),\n structure_node.get_site_kindnames()):\n t2 = int(k[-1]) if k[-1].isnumeric() else 0\n assert t1 == t2\n if description is None:\n structure_node.description = self.get_description(structure_ase, filepath)\n else:\n structure_node.description = description\n structure_node.label = \".\".join(filepath.split('/')[-1].split('.')[:-1])\n structure_node.store()\n self.structure_nodes.append(structure_node)\n print(\"Stored in AiiDA: \" + repr(structure_node))\n\n @property\n def node_class(self):\n return self.data_format.value\n\n @node_class.setter\n def node_class(self, value):\n self.data_format.value = value\n","sub_path":"aiida_widgets/structures_multi.py","file_name":"structures_multi.py","file_ext":"py","file_size_in_byte":10337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"82739518","text":"from tkinter import *\n#James Dumitru\n#Math\ndef addition():\n entry_3.insert(0, int(entry_1.get()) + int(entry_2.get()))\ndef subtraction():\n entry_3.insert(0, int(entry_1.get()) - int(entry_2.get()))\ndef multiply():\n entry_3.insert(0, int(entry_1.get()) * int(entry_2.get()))\ndef divide():\n entry_3.insert(0, int(entry_1.get()) / int(entry_2.get()))\n\n#Window_box\nwindow = Tk()\nwindow.configure(background='orange')\nwindow.title(\"Lab 9\")\nlabel_1 = Label(window, text=\"Calculator\", height=3, width=10, background='orange')\nlabel_1.pack()\nlabel_num1=Label(window,text=\"1st Number\", background='orange')\nlabel_num1.pack(side=TOP)\nlistbox_0=Listbox(window,height=40,width=40)\nlistbox_0.pack()\nlabel_num2=Label(window,text=\"2nd Number\", background='orange')\nlabel_num2.pack(side=TOP)\nframe_1 = Frame(window)\nframe_1.pack()\n\nframe_2 = Frame(window)\nframe_2.pack()\n\n#Buttons from add, subtract, multiply and divide\nbutton_1 = Button(frame_1, text=\"Add\", fg=\"blue\", command=addition)\nbutton_1.pack(side=LEFT)\nbutton_2 = Button(frame_1, text=\"Subtract\", fg=\"blue\", command=subtraction)\nbutton_2.pack(side=RIGHT)\nbutton_3 = Button(frame_2, text=\"Multiply\", fg=\"blue\", command=multiply)\nbutton_3.pack(side=LEFT)\nbutton_4 = Button(frame_2, text=\"Divide\", fg=\"blue\", command=divide)\nbutton_4.pack(side=RIGHT)\nentry_1 = Entry(listbox_0, bd=2) # 1st Text box option\nentry_1.pack(side=TOP)\nentry_2 = Entry(listbox_0, bd=2) # 2nd Text box option\nentry_2.pack(side=TOP)\nentry_3 = Listbox(window,height=10,width=20)\nentry_3.pack(side=TOP)\nwindow.mainloop()","sub_path":"calc.py","file_name":"calc.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"649642542","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Apr 14 16:53:07 2019\n\n@author: tob10\n\"\"\"\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass TTConv(torch.nn.Module):\n def __init__(\n self, \n conv_size,\n inp_ch_modes, \n out_ch_modes,\n ranks,\n stride=1,\n padding=0\n ):\n \"\"\"\n tt-conv-layer (convolution of full input tensor with tt-filters\n (make tt full then use conv2d))\n Args:\n inp: input tensor, float - [batch_size, H, W, C]\n conv_size: convolution window size, list [wH, wW]\n inp_ch_modes: input channels modes, np.array (int32) of size d\n out_ch_modes: output channels modes, np.array (int32) of size d\n ranks: tt-filters ranks, np.array (int32) of size (d + 1) \n strides: strides, list of 2 ints - [sx, sy] \n padding \n trainable: trainable variables flag, bool\n\n Returns:\n out: output tensor, float - [batch_size, prod(out_modes)]\n\n In the constructor we instantiate two nn.Linear modules and assign them as\n member variables.\n \"\"\"\n super(TTConv, self).__init__()\n \n self.inp_ch_modes=inp_ch_modes\n self.out_ch_modes=out_ch_modes\n self.ranks=ranks\n self.stride=stride\n self.padding=padding\n \n # filter initialiased with glorot initialisation with the right parameter\n self.filters = nn.Parameter(\n torch.nn.init.xavier_uniform_(\n torch.empty(ranks[0], 1, conv_size[0], conv_size[1])\n )\n )\n self.d = len(inp_ch_modes)\n \n self.cores = nn.ParameterList()\n for i in range(self.d):\n # initialise each core with once again glorot initialisation with\n # parameter matching the output and input channel mode\n # (the c_i/s_i multiply to C/S)\n empty_core = torch.empty(\n out_ch_modes[i] * ranks[i + 1], ranks[i] * inp_ch_modes[i]\n )\n empty_core = nn.Parameter(\n torch.nn.init.xavier_uniform_(empty_core)\n )\n self.cores.append(empty_core)\n \n def forward(self, inp):\n # should we use clone to keep self.cores untouched? \n cores = self.cores\n inp_ch, inp_h, inp_w = list(inp.shape)[1:4] #shape 0 is batchsize, 1 is inp_ch...\n tmp = torch.reshape(inp, (-1, inp_ch, inp_h, inp_w))\n tmp = torch.reshape(tmp, (-1, 1, inp_h, inp_w)) # we want h and w at last entry \n tmp = F.conv2d(\n tmp,\n self.filters,\n bias=None,\n stride=self.stride,\n padding=self.padding\n ) #might need to look at the order of the stride\n \n h, w = list(tmp.shape)[2:4]\n tmp = torch.reshape(tmp, (-1, inp_ch, h, w, self.ranks[0])) \n tmp = torch.transpose(tmp, 4, 0) #[4,1,2,3,0]\n tmp = torch.transpose(tmp, 4, 3) #[4,1,2,0,3]\n tmp = torch.transpose(tmp, 2, 3) #[4,1,0,2,3]\n #tmp shape = [r, c, b, h, w]\n \n for i in range(self.d): \n tmp = torch.reshape(tmp, (self.ranks[i] * self.inp_ch_modes[i], -1))\n tmp = torch.mm(cores[i], tmp) \n tmp = torch.reshape(tmp, (self.out_ch_modes[i], -1))\n tmp = torch.transpose(tmp, 1, 0)\n \n out_ch = np.prod(self.out_ch_modes)\n out = torch.reshape(tmp, (-1, out_ch, h, w))\n #out shape is [batch_size, out_ch, h, w]\n \n return out","sub_path":"modules/tlayers/TTConv.py","file_name":"TTConv.py","file_ext":"py","file_size_in_byte":3642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"223227323","text":"\"\"\"\n@author : 'XXY'\n@contact : '529379497@qq.com'\n@researchFie1d : 'NLP DL ML'\n@date : 2018/9/25 0025 下午 6:54\n\"\"\"\n\n\"\"\"\n思路:对输入的两个字符串分别建立hash表(用字典{key:value}实现)需要从a-z,A-Z,遍历一次字符串,每出现一个字符对应的key值加1。之后比较连个hash表,\n判断是否某个字符在两个hash表中都存在,如果是就用‘_’替换。最后输出字符串。\n\"\"\"\n\n\ndef replace_same(str1, str2):\n l1 = list(str1)\n l2 = list(str2)\n hashTable1 = {}\n hashTable2 = {}\n for i in range(65, 91):\n hashTable1[i] = 0\n hashTable2[i] = 0\n for i in range(97, 123):\n hashTable1[i] = 0\n hashTable2[i] = 0\n for i in l1:\n hashTable1[ord(i)] += 1\n for i in l2:\n hashTable2[ord(i)] += 1\n for i in l1 if len(l1)>=len(l2) else l2:\n if hashTable1[ord(i)]>0 and hashTable2[ord(i)]>0:\n l1[l1.index(i)] = '_'\n l2[l2.index(i)] = '_'\n print(\"\".join(l1))\n print(\"\".join(l2))\ndef judge(str1, str2):\n if len(str1) > 10 or len(str2)>10:\n print('请输入长度不超过100的字符串')\n return False\n elif str1==\"\" or str2==\"\":\n print('字符串不能为空')\n return False\n for j in a:\n if 65<=ord(j)<=90 or 97<=ord(j)<=122:\n continue\n else:\n print('请输入只包含字母的字符串')\n return False\n return True\nif __name__ == '__main__':\n a = input(\"a=\")\n b = input(\"b=\")\n if judge(a, b):\n replaceSame(a, b)","sub_path":"替换重复字母.py","file_name":"替换重复字母.py","file_ext":"py","file_size_in_byte":1567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"97185807","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport usuelles\nimport random\n\nBREEDRATE = 0.25\n\nclass Food:\n def __init__(self):\n self.amount = 10\n\n def __repr__(self):\n return \"\\033[1;33;40mF \" + str(self.amount) + \"\\033[1;37;40m\"\n\nclass Slime:\n def __init__(self):\n self.vitesse = 0\n self.taille = 1\n self.foodMax = 40\n self.food = self.foodMax // 2\n self.turn = 0\n self.generation = 0\n\n\n def __repr__(self):\n return \"\\033[1;32;40mS \" + str(self.generation) + \"\\033[1;37;40m\"\n\n def eat(self, target, amount):\n target.amount -= amount\n self.food += amount\n self.food = min(self.foodMax, self.food)\n\n def fatigue(self, amount):\n self.food -= amount\n\n def getBreededGenes(self):\n return [max(1, self.vitesse + np.random.randint(-5, 6)), max(1, self.taille + np.random.randint(-1, 2)),\n max(1, self.foodMax + np.random.randint(-5, 6))]\n\n\nclass Terrain:\n def __init__(self, taille):\n self.taille = taille\n self.plateau = np.empty((taille, taille), dtype = object)\n\n def clear(self):\n self.plateau = np.empty((self.taille, self.taille), dtype = object)\n\n def spawnFood(self, rate, foodLimit):\n l = 0\n for i in range(self.taille):\n for j in range(self.taille):\n if random.random() <= rate and self.plateau[i, j] == None and l < foodLimit:\n self.plateau[i, j] = Food()\n l += 1\n\n def clearFood(self):\n for i in range(self.taille):\n for j in range(self.taille):\n if type(self.plateau[i, j]) == Food:\n self.plateau[i, j] = None\n\n def spawnSlimes(self, number):\n if self.taille ** 2 < number:\n pass\n a = 0\n while a < number:\n i, j = tuple(np.random.randint(0, self.taille, 2))\n if self.plateau[i, j] == None:\n self.plateau[i, j] = Slime()\n a += 1\n\n def step(self, turn):\n for i in range(self.taille):\n for j in range(self.taille):\n if type(self.plateau[i, j]) == Slime and self.plateau[i, j].turn < turn:\n S = self.plateau[i, j]\n f = self.searchFood((i, j))\n p = self.searchPlace((i, j))\n if S.food >= S.foodMax // 2:\n self.breed(S, (i, j))\n if f != None and S.food < S.foodMax:\n F = self.plateau[f[0], f[1]]\n S.eat(F, min(S.taille, F.amount))\n if F.amount == 0:\n self.plateau[f[0], f[1]] = None\n elif p != None:\n self.plateau[p[0], p[1]] = S\n self.plateau[i, j] = None\n S.fatigue(S.taille)\n if S.food <= 0:\n self.plateau[p[0], p[1]] = None\n S.turn = turn\n\n\n def searchFood(self, coords):\n possible = []\n for i in [-1, 0, 1]:\n for j in [-1, 0, 1]:\n a, b = (usuelles.clipcoord(i + coords[0], self.taille), usuelles.clipcoord(j + coords[1], self.taille))\n if type(self.plateau[a, b]) == Food and (i, j) != (0, 0):\n possible.append((a, b))\n if possible != []:\n return possible[np.random.randint(0, len(possible))]\n else:\n return None\n\n def searchPlace(self, coords):\n possible = []\n for i in [-1, 0, 1]:\n for j in [-1, 0, 1]:\n a, b = (usuelles.clipcoord(i + coords[0], self.taille), usuelles.clipcoord(j + coords[1], self.taille))\n if self.plateau[a, b] == None and (i, j) != (0, 0):\n possible.append((a, b))\n if possible != []:\n return possible[np.random.randint(0, len(possible))]\n else:\n return None\n\n def cycle(self, number, foodRate, foodLimit):\n for i in range(number):\n T.spawnFood(foodRate, foodLimit)\n self.step(i)\n #print(T.plateau)\n #T.clearFood()\n if i % 50 == 0:\n print(i)\n\n def breed(self, slime, coords):\n p = self.searchPlace(coords)\n if p != None and random.random() <= BREEDRATE:\n x, y = p\n genes = slime.getBreededGenes()\n S = Slime()\n S.vitesse = genes[0]\n S.taille = genes[1]\n S.foodMax = genes[2]\n S.food = S.foodMax // 2\n S.generation = slime.generation + 1\n self.plateau[p[0], p[1]] = S\n self.turn = slime.turn + 1\n slime.food //= 2\n\n def getTrucs(self):\n vitesse = []\n taille = []\n foodMax = []\n for i in range(self.taille):\n for j in range(self.taille):\n if type(self.plateau[i, j]) == Slime:\n S = self.plateau[i, j]\n vitesse.append(S.vitesse)\n taille.append(S.taille)\n foodMax.append(S.foodMax)\n plt.subplot(2, 2, 1)\n plt.hist(vitesse)\n plt.subplot(2, 2, 2)\n plt.hist(taille)\n plt.subplot(2, 2, 3)\n plt.hist(foodMax)\n plt.show()\n\n\n\nT = Terrain(50)\nT.spawnSlimes(250)\nT.cycle(10000, 0.15, 10)\nT.getTrucs()\n","sub_path":"evolution.py","file_name":"evolution.py","file_ext":"py","file_size_in_byte":5440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"446942414","text":"\n\n#calss header\nclass _WHAT():\n\tdef __init__(self,): \n\t\tself.name = \"WHAT\"\n\t\tself.definitions = [u'the thing(s) that; that which: ', u'used to introduce something you are going to say: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'pronouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/pronouns/_what.py","file_name":"_what.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"500751016","text":"import requests\nimport json\nfrom predictActions import Predict_Action\nfrom predictNumbers import Predict_Number\nimport wave\nimport pyaudio\nfrom scipy.io.wavfile import read\nimport trimAudio\nfrom soundfile import SoundFile, SEEK_END\nimport numpy as np\n\n# server url\nURL = \"http://127.0.0.1:5000/predict\"\nTEST_URL = \"https://olcer.net/capstone/API/notify\"\nheaders = {\n \"User-Agent\": \"PostmanRuntime/7.26.8\", \n}\n\n\n\n# audio file we'd like to send for predicting keyword\nFILE_PATH = \"Test_Dataset/four/a6285644_nohash_2.wav\"\n\n# Constants for voice recording\nRECORDED_AUDIO = \"rawAudio.wav\"\nchunk = 1024\nFORMAT = pyaudio.paInt16\nchannels = 1\nsample_rate = 16000 \nrecord_seconds = 3\np = pyaudio.PyAudio()\n\ndef recordVoice(FORMAT, channels, sample_rate, input, output, chunk):\n # 5 seconds voice recording\n stream = p.open(format=FORMAT,\n channels=channels,\n rate=sample_rate,\n input=True,\n output=True,\n frames_per_buffer=chunk)\n\n frames = []\n print(\"Recording...\")\n for _ in range(int(sample_rate / chunk * record_seconds)):\n data = stream.read(chunk)\n # if you want to hear your voice while recording\n # stream.write(data)\n frames.append(data)\n print(\"Finished recording.\")\n # stop and close stream\n stream.stop_stream()\n stream.close()\n # terminate pyaudio object\n\n # p.terminate() # Comment this line\n\n # save audio file\n # open the file in 'write bytes' mode\n wf = wave.open(RECORDED_AUDIO, \"wb\")\n # set the channels\n wf.setnchannels(channels)\n # set the sample format\n wf.setsampwidth(p.get_sample_size(FORMAT))\n # set the sample rate\n wf.setframerate(sample_rate)\n # write the frames as bytes\n wf.writeframes(b\"\".join(frames))\n # close the file\n wf.close()\n\ndef numberToInt(str):\n if str == \"zero\":\n return 0\n elif str == \"one\":\n return 1\n elif str == \"two\":\n return 2\n elif str == \"three\":\n return 3\n else:\n return 4\n\ndef isFan(device):\n if(device == 4):\n return True\n \n return False\n \n\ndef actionToInt(str):\n if str == \"on\":\n return 1\n else:\n return 0\n\n\n\n\n\nif __name__ == \"__main__\":\n\n isContinue = True\n \n while isContinue :\n fullPhrase = \"\"\n print(\"#################\\nFor Lock: say 'zero'\\nFor LED 1: say 'one'\\nFor LED 2: say 'two'\\nFor LED 3: say 'three'\\nFor Fan: say 'four'\\n#################\")\n # Get device number\n print(\"#################\\nWhat is the number of the device that you want to interact with?\\n#################\")\n input(\"Press ENTER to record your voice...\")\n recordVoice(FORMAT, channels, sample_rate, True, True, chunk)\n trimAudio.trimAudio(1, 'rawAudio.wav')\n pn = Predict_Number()\n device = pn.predict('trimedAudio.wav')\n\n deviceNum = numberToInt(device)\n print(deviceNum)\n\n fullPhrase += device + \" \"\n print(fullPhrase)\n\n \n \n # Get action to perform\n print(\"#################\\nDo you want to turn the device on or off?\\n#################\")\n input(\"Press ENTER to record your voice...\")\n recordVoice(FORMAT, channels, sample_rate, True, True, chunk)\n trimAudio.trimAudio(1, 'rawAudio.wav')\n pa = Predict_Action()\n action = pa.predict('trimedAudio.wav')\n\n actionNum = actionToInt(action)\n print(actionNum)\n\n fullPhrase += action\n\n print(deviceNum, actionNum)\n print(fullPhrase)\n\n \"\"\"\n # Send string request to server\n values = {'word': fullPhrase}\n requests.post( \n URL,\n headers=headers,\n json=values\n )\n\n \"\"\"\n # Send int request to server\n values = {'device': deviceNum, 'action': actionNum}\n requests.post( \n TEST_URL,\n headers=headers,\n json=values\n )\n \n # Check if the user wants to continue with the process\n cntStr = input(\"Press Q to terminate the process, Press any key to continue interacting... PRESS ENTER after your input.\\n\")\n if cntStr == \"Q\" or cntStr == \"q\":\n isContinue = False\n else:\n continue\n\n print(\"PROCESS TERMINATED.\")\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":4420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"633318031","text":"#!/home/a/anaconda3/envs/tinysleepnet/bin/python\n\n#!/bin/env python\n\nimport argparse\nimport glob\nimport importlib\nimport os\nimport numpy as np\nimport shutil\nimport sklearn.metrics as skmetrics\nimport tensorflow as tf\n\n\n''' todo:\n 1) look around for a sleep dataset with electrodes similar to muse\n 2) add additional data for each epoch:\n spectrogram?\n respiratory rate?\n spo2\n (noise, light, spo2, pulse...)\n 3) generate a daily report notebook\n 4) questions:\n -why is AF7 and AF8 poor at predicting rems\n -why am I not registering much deep sleep?\n -how well can TP9 and TP10 substitute for Cz and Pz\n '''\n\n\n\nfrom data import load_data, get_subject_files\nfrom model import TinySleepNet\nfrom minibatching import (iterate_minibatches,\n iterate_batch_seq_minibatches,\n iterate_batch_multiple_seq_minibatches)\nfrom utils import (get_balance_class_oversample,\n print_n_samples_each_class,\n save_seq_ids,\n load_seq_ids)\nfrom logger import get_logger\n\nimport scriptine\n\n\nconfig = {\n # Train\n \"n_epochs\": 200,\n \"learning_rate\": 1e-4,\n \"adam_beta_1\": 0.9,\n \"adam_beta_2\": 0.999,\n \"adam_epsilon\": 1e-8,\n \"clip_grad_value\": 5.0,\n \"evaluate_span\": 50,\n \"checkpoint_span\": 50,\n\n # Early-stopping\n \"no_improve_epochs\": 50,\n\n # Model\n \"model\": \"model-mod-8\",\n \"n_rnn_layers\": 1,\n \"n_rnn_units\": 128,\n \"sampling_rate\": 100.0,\n \"input_size\": 3000,\n \"n_classes\": 5,\n \"l2_weight_decay\": 1e-3,\n\n # Dataset\n \"dataset\": \"sleepedf\",\n \"data_dir\": \"./data/sleepedf/sleep-cassette/eeg_fpz_cz\",\n \"n_folds\": 20,\n \"n_subjects\": 20,\n\n # Data Augmentation\n \"augment_seq\": True,\n \"augment_signal_full\": True,\n \"weighted_cross_ent\": True,\n}\n\nconfig.update({\n \"seq_length\": 20,\n \"batch_size\": 15,\n})\n\nconfig.update({\n \"batch_size\": 1,\n \"seq_length\": 1,\n})\nconfig[\"class_weights\"] = np.ones(config[\"n_classes\"], dtype=np.float32)\n\n\nimport pandas as pd\n\n\ndef getAccData(h5fname):\n x = pd.read_hdf(h5fname, 'Muse/ACC').reset_index(drop=True)\n x = x[x.ts.cummax().diff()>0]\n x['orientation'] = 180/np.pi*np.arctan(x.Y/x.X)\n x['motion'] = x.Y.rolling(1000).std().fillna(0)\n return x\n\ndef getPpgData(h5fname):\n #read the data\n x = pd.read_hdf(h5fname, 'Muse/PPG').reset_index(drop=True)\n x = x[x.ts.cummax().diff()>0]\n x.index = x.ts\n\n #label with heartbeat cycle (based on PPG1)\n x['PPG1m'] = x.PPG1.rolling(5).mean()\n isPeak = x['PPG1m'] == x['PPG1m'].rolling(int(.5*64), center=True).max()\n isPeak -= isPeak.rolling(20).max().shift(1).fillna(0) #remove consecutive isPeak trues\n isPeak = isPeak.clip(0,1)\n x['cycle'] = isPeak.cumsum()\n\n #compute PPG1 stats on each cycle\n b = x['PPG1m'].groupby(x['cycle']).agg(['count','min','first','last','idxmin', ('idxfirst',lambda y: y.index.values[0]), ('idxlast',lambda y: y.index.values[-1])])\n b['max'] = b['first'] + (b['last']-b['first']) * (b['idxmin']-b['idxfirst']) / (b['idxlast']-b['idxfirst'])\n ppg = pd.DataFrame()\n ppg['ts'] = b['idxfirst']\n ppg['bpm'] = 1 / (b['count']/64/60)\n ppg['ampl1'] = (b['max']-b['min']) / (b['max']+b['min'])\n\n #compute PPG2 stats on each cycle\n x['PPG2m'] = x.PPG2.rolling(5).mean()\n b = x['PPG2m'].groupby(x['cycle']).agg(['count','min','first','last','idxmin', ('idxfirst',lambda y: y.index.values[0]), ('idxlast',lambda y: y.index.values[-1])])\n b['max'] = b['first'] + (b['last']-b['first']) * (b['idxmin']-b['idxfirst']) / (b['idxlast']-b['idxfirst'])\n ppg['ampl2'] = (b['max']-b['min']) / (b['max']+b['min'])\n ppg['spo2'] = 0\n return ppg\n\ndef predict_command(h5fname):\n # Add dummy class weights\n trues = []\n preds = []\n #tf.random.set_random_seed(123)\n\n model = TinySleepNet(\n config=config,\n output_dir='out_sleepedf/train/0',\n use_rnn=True,\n testing=True,\n use_best=True,\n )\n\n x = pd.read_hdf(h5fname, 'Muse/EEG').reset_index(drop=True)\n\n #resample to 100Hz\n x = x[x.ts==x.ts.cummax()]\n ts = np.arange(x.ts.values[0], x.ts.values[-1], 10**7)\n ts -= ts%1000\n x = x.set_index('ts').reindex(ts, method='nearest')\n\n #\n n_epochs = len(x)//3000\n x = x.iloc[:n_epochs*3000]\n p = pd.DataFrame()\n p['ts'] = x.index[::3000]\n for c in 'AF7 AF8 TP9 TP10'.split():\n night_x = x[c].values.reshape( (n_epochs,3000,1,1))\n print('night_x', night_x.shape, night_x.mean(), night_x.std())\n night_y = np.zeros(n_epochs)\n\n\n # Create minibatches for testing\n test_minibatch_fn = iterate_batch_multiple_seq_minibatches(\n [night_x],\n [night_y],\n batch_size=config[\"batch_size\"],\n seq_length=config[\"seq_length\"],\n shuffle_idx=None,\n augment_seq=False,\n )\n\n # Evaluate\n test_outs = model.evaluate(test_minibatch_fn)\n #from IPython import embed; embed()\n print('test_outs', c, np.array(test_outs['test/preds']).mean())\n p[c] = test_outs['test/preds']\n\n # Filter bad data\n isBad = night_x[:,:,0,0].std(axis=1) > 500\n print(c, isBad.sum(), p[c].mean(), p[c].std())\n p[c][isBad] = -1\n\n #acc data\n y = getAccData(h5fname)\n y = y.set_index('ts').reindex(p.ts, method='ffill')\n for c in ['orientation','motion']:\n p[c] = y[c].values\n\n #ppg data\n ppg = getPpgData(h5fname)\n\n #save results\n store = pd.HDFStore(h5fname, complib='zlib',complevel=5)\n store.put('tinysleepnet', p)\n store.put('spo2', ppg)\n\n #from IPython import embed; embed()\n tf.reset_default_graph()\n\n\n\nif __name__ == \"__main__\":\n scriptine.run()\n ","sub_path":"mypredict.py","file_name":"mypredict.py","file_ext":"py","file_size_in_byte":5796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"221848784","text":"# https://www.hackerrank.com/challenges/detect-html-tags-attributes-and-attribute-values\n\nfrom html.parser import HTMLParser\n\nclass MyHTMLParser(HTMLParser):\n\n def handle_starttag(self, tag, attrs):\n print(tag)\n for attr in attrs:\n print('->', attr[0], '>', attr[1])\n\n def handle_startendtag(self, tag, attrs):\n print(tag)\n for attr in attrs:\n print('->', attr[0], '>', attr[1])\n\n\nif __name__ == '__main__':\n html = ''\n for _ in range(int(input())):\n html += input()\n\n parser = MyHTMLParser()\n parser.feed(html)\n parser.close()","sub_path":"Python/Regex and Parsing/detect-html-tags-attributes-and-attribute-values.py","file_name":"detect-html-tags-attributes-and-attribute-values.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"196015187","text":"#Games\r\n\r\ndef menuDisplay():\r\n print(\"(RPS) Rock Paper Scissors \\n(HM) Hangman \\n\")\r\n print(\"Please input any choices in CAPS\")\r\n\r\ndef mainRPS():\r\n def getMove():\r\n validMove = False\r\n while not validMove:\r\n rpsChoice = input(\"Rock - Paper - Scissors\\nR - P - S : \")\r\n if rpsChoice == 'R' or rpsChoice == 'S' or rpsChoice == 'P':\r\n validMove = True\r\n return rpsChoice\r\n else:\r\n print(\"we both know that's not a valid choice. try again!\")\r\n def opponentMove():\r\n import random\r\n moves = ['R', 'S', 'P']\r\n randomMove = random.choice(moves)\r\n return randomMove\r\n def tauntReplay(wins, total):\r\n print(\"dead end! function still under construction\")\r\n #find a way to taunt the player to ask \"best 2/3 or 3/5\"\r\n \r\n playCount = 0\r\n playerWins = 0\r\n playerLosses = 0\r\n totalGames = 0\r\n while playCount < 4:\r\n import time\r\n print(\"\\n======================\\n\")\r\n playerMove = getMove()\r\n npcMove = opponentMove()\r\n time.sleep(1)\r\n print(\"I chose\", npcMove, \"\\n\")\r\n if playerMove == npcMove:\r\n print(\"tie! \\ntry again! \")\r\n elif playerMove == 'R':\r\n if npcMove == 'S':\r\n print(\"rock beats scissors! \\nyou win! \")\r\n playerWins = playerWins + 1\r\n elif npcMove == 'P':\r\n print(\"paper beats rock! \\nI win!\")\r\n playerLosses = playerLosses + 1\r\n elif playerMove == 'S':\r\n if npcMove == 'R':\r\n print(\"rock beats scissors! \\nI win!\")\r\n playerLosses = playerLosses + 1\r\n elif npcMove == 'P':\r\n print(\"scissors beats paper! \\nyou win!\")\r\n playerWins = playerWins + 1\r\n elif playerMove == 'P':\r\n if npcMove == 'R':\r\n print(\"paper beats rock! \\nyou win!\")\r\n playerWins = playerWins + 1\r\n elif npcMove == 'S':\r\n print(\"scissors beats paper! \\nI win!\")\r\n playerLosses = playerLosses + 1\r\n totalGames = totalGames + 1\r\n playCount = playCount + 1\r\n print(\"\\nTotal wins:\", playerWins, \"\\nTotal losses:\", playerLosses)\r\n if playCount == 3:\r\n contDecision = input(\"\\nplay again? (Y)\\n\")\r\n if contDecision != 'Y':\r\n playCount = 888\r\n if playerWins > playerLosses:\r\n print(\"you win!\")\r\n elif playerWins == playerLosses:\r\n print(\"we tied!\")\r\n else:\r\n print(\"loser! I win!\")\r\n else:\r\n playCount = 0\r\n print(\"===============\\ngame over!\\n\")\r\n\r\ndef mainHM():\r\n \r\n def chooseWord():\r\n choice = input(\"we have words! we have the best words! \\ndo you want to choose your own word? (Y/N) \")\r\n if choice == 'Y':\r\n word = input(\"alright alright alright \\nwhat's your word? \")\r\n else:\r\n import random\r\n import time\r\n time.sleep(1)\r\n difficulty = int(input(\"great! you're gonna love our words, we've got the best words! \\nlevel of difficulty [1,2,3] \"))\r\n while not (difficulty < 4 and difficulty > 0):\r\n print(\"you mock our words!\")\r\n difficulty = input(\"try again \")\r\n libraryOne = ['toad', 'goat', 'june', 'gray', 'coat', 'blue', 'bike', 'girls']\r\n libraryTwo = ['orange', 'french', 'nothing', 'manacle', 'octopus', 'defend', 'painting', 'diamonds']\r\n libraryThree = ['television', 'orangutan', 'surreptitious', 'gargantuan', 'undetermined', 'dedication', 'cerulean']\r\n if difficulty == 1:\r\n word = random.choice(libraryOne)\r\n elif difficulty == 2:\r\n word = random.choice(libraryTwo)\r\n else:\r\n word = random.choice(libraryThree)\r\n return word\r\n\r\n\r\n import time\r\n playingHM = True\r\n print(\"welcome to hangman! together we'll watch your idiocy kill an innocent man.\\n\")\r\n time.sleep(1)\r\n while playingHM:\r\n word = chooseWord()\r\n print(\"\\nand now we guess!\")\r\n guesses = ''\r\n turns = 10\r\n failures = 0\r\n while turns > 0:\r\n guess = input(\"choose a letter: \")\r\n guesses = guesses + guess\r\n print(\"you have guessed\", guesses)\r\n for char in word:\r\n if char in guesses:\r\n print (char),\r\n else:\r\n print(\"_\")\r\n failures = failures + 1\r\n if guess not in word:\r\n turns = turns - 1\r\n print(\"wrong!\")\r\n print(\"you have\", turns, \"turns!\\n\")\r\n if turns == 0:\r\n print(\"loser!\")\r\n print(\"the word was\", word)\r\n contChoice = input(\"play again? (Y/N) \")\r\n if contChoice != 'Y':\r\n playingHM = False\r\n#how to end the game when they get the word correct?\r\n\r\n\r\n\r\n \r\n \r\n \r\n\r\n\r\n \r\n\r\nvisitingArcade = True\r\nwhile visitingArcade:\r\n menuDisplay()\r\n gameChoice = input(\"which game do you want to play? \\n\")\r\n if gameChoice == 'RPS':\r\n mainRPS()\r\n elif gameChoice == 'HM':\r\n mainHM()\r\n else:\r\n print(\"I don't know that game!\")\r\n arcadeChoice = input(\"do you want to play something else? (Y) \\n\")\r\n if arcadeChoice != 'Y':\r\n visitingArcade = False\r\n \r\n\r\n\r\n\r\n\r\n","sub_path":"Arcade Games.py","file_name":"Arcade Games.py","file_ext":"py","file_size_in_byte":5613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"284902372","text":"class Car(object):\r\n\r\n\r\n def __init__(self, car_name='General', car_model='GM' ,car_type='honda' ):\r\n self.car_type = car_type\r\n self.model = car_model\r\n self.name = car_name\r\n self.speed = 0\r\n\r\n if car_name== 'Porshe' or car_name== 'Koenigsegg':\r\n self.num_of_doors = 2\r\n else:\r\n self.num_of_doors = 4\r\n\r\n if car_type == 'trailer':\r\n self.num_of_wheels = 8\r\n else:\r\n self.num_of_wheels = 4\r\n\r\n def doors(self, num_of_doors):\r\n pass\r\n\r\n def drive(self, moving_man):\r\n return moving_man\r\n\r\n def drive(self, speed):\r\n if self.car_type == 'trailer':\r\n self.speed = speed * 11\r\n else:\r\n self.speed = 10 ** speed\r\n\r\n return self\r\n\r\n def wheels(self, number_of_wheels):\r\n return number_of_wheels\r\n\r\n\r\n def is_saloon(self):\r\n if self.car_type == 'trailer':\r\n return False\r\n else:\r\n return True\r\n","sub_path":"class_car.py","file_name":"class_car.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"314876837","text":"import os\nimport pandas\nimport pathlib\nfrom scipy.stats import stats\n\n\nclass Output:\n\n def __init__(self, rwr_df, multiplexall, top: int):\n\n self.rwr_result_list = rwr_df\n self.multiplexall = multiplexall\n\n self._df = rwr_df\n\n multiplex_node_prob_zero_df = self._df.loc[self._df.score == 0][['multiplex', 'node']].drop_duplicates()\n multiplex_node_prob_zero_df['score'] = 0\n self._df = (self._df.loc[self._df.score > 0]).groupby(['multiplex', 'node']).agg(stats.gmean).reset_index()\n self._df = pandas.concat([multiplex_node_prob_zero_df, self._df], axis=0)\n self._df = self._df.drop_duplicates(['multiplex', 'node'], keep='first')\n self._df.sort_values('score', ascending=False, inplace=True)\n\n #######################################################################\n #\n # Keep only top k nodes\n #\n #######################################################################\n\n if not (top is None):\n self._df = self._df.groupby('multiplex').head(top)\n\n def to_sif(self, bipartiteall, path: str):\n pathlib.Path(os.path.dirname(path)).mkdir(exist_ok=True, parents=True)\n out_lst = [] # list of edges with relation type to write\n selected_nodes = self._df.node.tolist()\n\n # Multiplex undirected edges\n for u, v, edgeidx in self.multiplexall.multigraph.edges:\n if (u in selected_nodes) or (v in selected_nodes):\n edge_data_dic = self.multiplexall.multigraph.get_edge_data(u, v, edgeidx)\n out_lst.append((u, edge_data_dic['network_key'], v))\n\n # Multiplex directed edges\n for u, v, edgeidx in self.multiplexall.multidigraph.edges:\n if u in selected_nodes or v in selected_nodes:\n edge_data_dic = self.multiplexall.multigraph.get_edge_data(u, v)\n for edge_key in edge_data_dic:\n out_lst.append((u, edge_data_dic['network_key'], v))\n\n # Bipartite undirected edges\n for u, v in bipartiteall.graph.edges:\n if u in selected_nodes or v in selected_nodes:\n edge_data_dic = bipartiteall.graph.get_edge_data(u, v)\n out_lst.append((u, edge_data_dic['network_key'], v))\n\n # Bipartite directed edges\n for u, v in bipartiteall.digraph.edges:\n if u in selected_nodes or v in selected_nodes:\n edge_data_dic = bipartiteall.digraph.get_edge_data(u, v)\n out_lst.append((u, edge_data_dic['network_key'], v))\n\n out_df = pandas.DataFrame(out_lst, columns=['node1', 'relationship_type', 'node2'], dtype=str)\n out_df.to_csv(path, sep=\"\\t\", header=False, index=False)\n\n def to_tsv(self, outdir: str, degree: bool):\n pathlib.Path(outdir).mkdir(exist_ok=True, parents=True)\n out_df = self._df\n\n #######################################################################\n #\n # Annotate nodes with layers and degrees\n #\n #######################################################################\n\n if degree:\n\n undirdegree_df = pandas.DataFrame(columns=['multiplex', 'layer', 'node', 'degree'])\n inoutdegree_df = pandas.DataFrame(columns=['multiplex', 'layer', 'node', 'indegree', 'outdegree'])\n\n for multiplex in self.multiplexall.multiplex_tuple:\n for layer in multiplex.layer_tuple:\n if layer.graph_type[0] == '0': # undirected graph\n degree_layer_df = pandas.DataFrame(layer.networkx.degree, columns=['node', 'degree'])\n degree_layer_df['multiplex'] = multiplex.key\n degree_layer_df['layer'] = layer.key\n undirdegree_df = pandas.concat([undirdegree_df, degree_layer_df], axis=0)\n\n if layer.graph_type[0] == '1': # directed graph\n indegree_layer_df = pandas.DataFrame(layer.networkx.in_degree, columns=['node', 'indegree'])\n outdegree_layer_df = pandas.DataFrame(layer.networkx.out_degree, columns=['node', 'outdegree'])\n inoutdegree_layer_df = indegree_layer_df.merge(outdegree_layer_df, on='node')\n inoutdegree_layer_df['multiplex'] = multiplex.key\n inoutdegree_layer_df['layer'] = layer.key\n inoutdegree_df = pandas.concat([inoutdegree_df, inoutdegree_layer_df], axis=0)\n\n degree_out_df = pandas.concat([undirdegree_df, inoutdegree_df], axis=0)\n out_df = out_df.merge(degree_out_df, on=['multiplex', 'node'])\n\n out_df.dropna(axis=1, how='all', inplace=True) # drop columns where all nan\n\n #######################################################################\n #\n # To csv\n # Will write one file per multiplex\n #\n #######################################################################\n\n for multiplex in sorted(out_df.multiplex.unique()):\n\n out_i_df = out_df.loc[out_df.multiplex == multiplex]\n multiplex_tsv_path = os.path.join(outdir, \"multiplex_\" + str(multiplex) + \".tsv\")\n out_i_df.to_csv(multiplex_tsv_path, sep='\\t', index=False, header=True, na_rep='NA')\n\n return out_df\n","sub_path":"multixrank/Output.py","file_name":"Output.py","file_ext":"py","file_size_in_byte":5338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"530928182","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport os.path\nimport setuptools\n\nversion_file = os.path.abspath(os.path.join(os.path.dirname(__file__), \"storage_utils\", \"__version__.py\"))\nwith open(version_file, mode=\"rt\") as f:\n exec(f.read())\n# noinspection PyUnresolvedReferences\nVERSION = __version__\n\nextras_require = {\n \"s3\": [\"s3fs\"],\n \"hdfs\": [\"pyarrow\"]\n}\nextras_require[\"complete\"] = {v for req in extras_require.values() for v in req}\n\nsetuptools.setup(\n\n name=\"storage-utils\",\n version=VERSION,\n description=\"Blob storage utilities\",\n long_description=\"Blob storage utilities\",\n url=\"https://volantisiq.com\",\n license=\"MIT\",\n\n author=\"Akrom Khasani\",\n author_email=\"akrom@volantis.io\",\n\n packages=setuptools.find_packages(exclude=(\"tests*\",)),\n python_requires=\">=3.7\",\n install_requires=[],\n extras_require=extras_require,\n platforms=[\n \"any\"\n ],\n\n classifiers=[\n \"Development Status :: 3 - Alpha\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: Implementation :: CPython\"\n ]\n\n)\n","sub_path":"pypi_install_script/storage-utils-0.0.5.1.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"641137403","text":"from keras import datasets\n\n\nfrom dnpy.layers import *\nfrom dnpy.net import *\nfrom dnpy.optimizers import *\nfrom dnpy.regularizers import *\nfrom dnpy import metrics, losses\nfrom dnpy import utils\n\n# For debugging\nnp.random.seed(42)\n\n\ndef main():\n # Get data\n (x_train, y_train), (x_test, y_test) = datasets.mnist.load_data()\n\n # Pre-processing\n # Normalize\n x_train = x_train/255.0\n x_test = x_test/255.0\n\n # Classes to categorical\n num_classes = 10\n y_train = utils.to_categorical(y_train, num_classes=num_classes)\n y_test = utils.to_categorical(y_test, num_classes=num_classes)\n\n # Shuffle dataset\n x_train, y_train = utils.shuffle_dataset(x_train, y_train)\n x_test, y_test = utils.shuffle_dataset(x_test, y_test)\n\n # Params *********************************\n batch_size = int(len(x_train)/10)\n epochs = 10\n\n # Define architecture\n l_in = Input(shape=x_train[0].shape)\n l = Reshape(l_in, shape=(28*28,))\n l1 = Relu(Dense(l, 1024))\n l2 = Relu(Dense(l1, 1024))\n l = Add([l1, l2])\n l = Relu(Dense(l, 1024))\n l_out = Softmax(Dense(l, num_classes))\n\n # Build network\n mymodel = Net()\n mymodel.build(\n l_in=[l_in],\n l_out=[l_out],\n optimizer=Adam(lr=0.001),\n losses=[losses.CrossEntropy()],\n metrics=[[metrics.CategoricalAccuracy()]],\n debug=False,\n smart_derivatives=True,\n )\n\n # Print model\n mymodel.summary()\n\n # Train\n mymodel.fit([x_train], [y_train],\n x_test=[x_test], y_test=[y_test],\n batch_size=batch_size, epochs=epochs,\n evaluate_epoch=False,\n print_rate=1)\n\n # Evaluate\n # m = mymodel.evaluate([x_test], [y_test], batch_size=batch_size)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"examples/4_mnist_res.py","file_name":"4_mnist_res.py","file_ext":"py","file_size_in_byte":1796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"158230940","text":"#!/usr/bin/env python\n# rsam_plot.py\n# plot rsam data for one channel and filter type\n\nimport matplotlib\nmatplotlib.use('Agg')\nfrom matplotlib.patches import Rectangle\nimport matplotlib.pyplot as plt\nimport datetime as dt\nimport math\nfrom matplotlib.dates import date2num\nfrom matplotlib.dates import num2date\nimport matplotlib.dates as mdates\nimport matplotlib.ticker as mticker\nfrom obspy.core import read, Trace, Stream\nimport sys\nimport os\nimport numpy as np\nimport scipy as sp\nimport pytz\n\n# start here\nif (len(sys.argv) < 8) | (len(sys.argv) > 10):\n sys.exit(\n \"syntax rsam_plot.py site(DRZ.10-EHZ.CH) rsam_dir date1(yyyymmdd) date2(yyyymmdd) plot_dir basetriglev filter(lp,hp,bp,none) [f1 f2]\")\nelse:\n site = sys.argv[1]\n rsam_dir = sys.argv[2]\n date1 = sys.argv[3]\n date2 = sys.argv[4]\n plot_dir = sys.argv[5]\n basetrig = sys.argv[6]\n plot_file = os.path.join(plot_dir, 'rsam_plot')\nif len(sys.argv) == 8: # filter = none\n filtype = sys.argv[7]\nelif len(sys.argv) == 9: # filter = lp or hp, one frequency given\n filtype = sys.argv[7]\n f = float(sys.argv[8])\nelif len(sys.argv) == 10: # filter = bp, two frequencies given\n filtype = sys.argv[7]\n f1 = float(sys.argv[8])\n f2 = float(sys.argv[9])\n\n# site dir like DRZ.CH\nsite_dir = str.split(site, '.')[0] + '.' + str.split(site, '.')[2]\n\n# format dates as datetime variables\nd1 = dt.datetime.strptime(date1, '%Y%m%d')\nyd1 = date2num(d1)\nd2 = dt.datetime.strptime(date2, '%Y%m%d')\nyd2 = date2num(d2)\nyd2 = yd2 + 1 # so date range is inclusive\ndates = num2date(np.arange(yd1, yd2, 1))\n\nst = Stream() # create empty stream\nfor date in dates:\n # get rsam file name\n yd = date.strftime(\"%Y.%j\")\n if filtype == 'none':\n rsamfile = os.path.join(rsam_dir, site_dir, yd + '.' + site + '.rsam')\n elif (filtype == 'lp') | (filtype == 'hp'):\n strf = '%.2f' % f # string version with 2 decimal places\n rsamfile = os.path.join(\n rsam_dir, site_dir, yd + '.' + site + '.' + filtype + '_' + strf + '.rsam')\n elif filtype == 'bp':\n strf1 = '%.2f' % f1 # string version with 2 decimal places\n strf2 = '%.2f' % f2 # string version with 2 decimal places\n rsamfile = os.path.join(\n rsam_dir, site_dir, yd + '.' + site + '.' + filtype + '_' + strf1 + '-' + strf2 + '.rsam')\n\n # process rsamfile\n if os.path.isfile(rsamfile):\n st += read(rsamfile)\n\n# merge to single stream\nst.merge(fill_value='interpolate')\ntr = st[0]\n\n# parse VAL data\nval_changes, val_level_at_change = [], []\nwith open('/home/samto/PROCESSING/WIR/calendar_VAB.csv', 'r') as openfile:\n rc = 0\n for row in openfile:\n if rc == 0:\n rc += 1\n continue\n cols = row.split(',')\n val_changes.append(dt.datetime.strptime(cols[1] + '-' + cols[0],\n '%Y-%b-%d'))\n val_level_at_change.append(cols[2][:-1])\n\n# plot\nstart = date2num(tr.stats.starttime.datetime) # as decimal years\nend = date2num(tr.stats.endtime.datetime)\n\n\n# build plot ticks\nplot_range = (tr.stats.endtime.datetime - tr.stats.starttime.datetime).total_seconds() / 86400\ntick_range = math.ceil(plot_range)\nsecond_offset = 86400 - (tr.stats.starttime.datetime.hour * 3600 +\n tr.stats.starttime.datetime.minute * 60 +\n tr.stats.starttime.datetime.second +\n tr.stats.starttime.datetime.microsecond / 1000000)\nxticks = []\nxtick_labels = []\nfor n in range(tick_range):\n xticks.append((tr.stats.starttime.datetime + dt.timedelta(seconds=second_offset) + dt.timedelta(days=n)).astimezone(pytz.timezone('Pacific/Auckland')).date())\n if n % 2 == 0:\n xtick_labels.append(str(xticks[-1]))\n else:\n xtick_labels.append('')\n\n# add end time of data to val change calendar for plotting clarity\nval_changes.append(tr.stats.endtime.datetime)\nval_level_at_change.append(val_level_at_change[-1])\n\n# time values\n#t = np.arange(start, end, tr.stats.delta/86400)\nt = sp.linspace(start, end, tr.stats.npts)\n\n# plot\n#date and time\nnow = dt.datetime.now()\n\n#base trigger level string for title\nif basetrig == '0':\n basetrig = 'null'\n\nif filtype == 'none':\n title = 'RSAM: ' + site + ', date: ' + date1 + '-' + date2 + \\\n ' UT, filter: ' + filtype + ', plotted at: ' + \\\n now.strftime(\"%Y-%m-%d %H:%M\") + ', BTL = ' + basetrig\nelif (filtype == 'lp') | (filtype == 'hp'):\n title = 'RSAM: ' + site + ', date: ' + date1 + '-' + date2 + ' UT, filter: ' + \\\n filtype + ' ' + strf + ' Hz' + ', plotted at: ' + \\\n now.strftime(\"%Y-%m-%d %H:%M\") + ', BTL = ' + basetrig\nelif filtype == 'bp':\n title = 'RSAM: ' + site + ', date: ' + date1 + '-' + date2 + ' UT, filter: ' + filtype + \\\n ' ' + strf1 + ' - ' + strf2 + ' Hz' + \\\n ', plotted at: ' + now.strftime(\"%Y-%m-%d %H:%M\") + ', BTL = ' + basetrig\nfig = plt.figure(figsize=(15, 5))\nplt.axes([0.1, 0.2, 0.85, 0.7])\n\nmaxy = 1.1 * tr.data.max()\nplt.ylim(bottom=0, top=maxy)\n\n#base trigger level on plot, if in scale\nif basetrig != 'null':\n bt = float(basetrig)\n half = bt / 2\n plt.axhline(y=bt, linestyle='--', color = 'red', label='RSAM alert value')\n #colour areas based on relation to BTL\n plt.axhspan(0, half, alpha=0.1, color='green', label='Weak RSAM zone') #low rectangle\n plt.axhspan(half, bt, alpha=0.1, color='orange', label='Moderate RSAM zone') #moderate rectangle\n plt.axhspan(bt, 100000, alpha=0.1, color='red', label='Strong RSAM zone') #high rectangle\n\nplt.plot_date(t, tr.data, linewidth=1, linestyle='-', marker='None', color='black', label='RSAM')\n\n# Plot VAL calendar\nplt.vlines(val_changes, 0, 999999, linestyles='dashed', color='black', label='VAL change')\nfor n in range(len(val_changes) - 1):\n if int(val_level_at_change[n - 1]) < 3 and int(val_level_at_change[n]) == 4: # Catch when an eruption occurs\n plt.annotate(s='VAL ' + val_level_at_change[n],\n xy=(val_changes[n],\n maxy - maxy/11),\n xytext=(val_changes[n] + dt.timedelta(hours=12),\n maxy - 2 * maxy/10),\n bbox={'boxstyle': 'square',\n 'fc': '1',\n 'alpha': 0.8},\n arrowprops={'facecolor': 'black',\n 'arrowstyle': '->',\n 'relpos': (0, 0.5)})\n else:\n plt.annotate(s='VAL ' + val_level_at_change[n],\n xy=(val_changes[n],\n maxy - maxy/11),\n xytext=(val_changes[n] + dt.timedelta(seconds=(val_changes[n + 1] - val_changes[n]).total_seconds() / 2),\n maxy - maxy/10),\n bbox={'boxstyle': 'square',\n 'fc': '1',\n 'alpha': 0.8},\n arrowprops={'facecolor': 'black',\n 'arrowstyle': '->',\n 'relpos': (0, 0.5)})\n\n# Add eruption box\n\neruption_dt = dt.datetime.strptime('2019-12-09T01:11:47Z',\n '%Y-%m-%dT%H:%M:%SZ')\nrect = Rectangle(xy=(eruption_dt - dt.timedelta(hours=6), 0),\n width=(dt.timedelta(hours=12)),\n height=maxy + maxy/20,\n fill=True,\n color='red',\n alpha=0.2)\nplt.gca().add_patch(rect)\nplt.text(s='Eruption',\n x=eruption_dt,\n y=maxy,\n horizontalalignment='center',\n bbox={'boxstyle': 'square',\n 'fc': '1',\n 'alpha': 0.8},\n fontdict={'fontsize': 12,\n 'weight': 'bold',\n 'color': 'red'})\n\n# plt.title(title)\nplt.title('Real-Time Seismic Amplitude (RSAM: a measure of seismic energy) at Whakaari/White Island in the last month',\n y=1.03,\n fontdict={'fontsize': 14})\nplt.yticks(plt.gca().get_yticks(),\n fontsize=12)\nplt.ylabel('ground velocity (nm/s)',\n fontsize=14,\n labelpad=10)\nplt.xticks(ticks=xticks,\n labels=xtick_labels,\n rotation=30,\n ha='right',\n fontsize=12)\nplt.xlabel('date (NZT)',\n fontsize=14,\n labelpad=5)\nplt.xlim(t[0], t[-1])\n\nplt.legend(loc='upper left')\n\nplt.savefig(plot_file + '.png', dpi=600, fmt='png')\nplt.savefig(plot_file + '.svg', dpi=600, fmt='svg')\n# plt.show()\n","sub_path":"rsam_plot.py","file_name":"rsam_plot.py","file_ext":"py","file_size_in_byte":8501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"275078950","text":"import pandas\r\nimport warnings\r\nwarnings.filterwarnings('ignore')\r\ndata = pandas.read_csv(r'C:\\Cricket Adda\\T20 Data\\All T20 Data\\ipl_all_matches.csv')\r\ndf = pandas.DataFrame(data, columns = ['bowler', 'ball', 'runs_off_bat', 'wicket_type', 'wides', 'noballs', 'match_id', 'innings', 'extras', 'legbyes', 'byes', 'bowling_team'])\r\ndf = df[df['match_id']>=1200000]\r\ndf1 = (df[(df['bowling_team']=='Rajasthan Royals') & (df['ball'] > 15) & (df['ball'] > 15) & (df['innings'] < 3)])\r\nindex = df1.index\r\nrows = len(index)\r\ndf2 = df1[(df1['wicket_type']=='caught') | (df['wicket_type'] == 'bowled') | (df1['wicket_type']=='lbw') | (df['wicket_type'] == 'caught and bowled') | (df['wicket_type'] == 'stumped') | (df['wicket_type'] == 'hit wicket') | (df['wicket_type'] == 'run out')]\r\nindex = df2.index\r\nwickets = len(index)\r\nruns1 = df1['runs_off_bat'].sum() \r\nruns2 = df1['extras'].sum()\r\nruns = (runs1) + (runs2) \r\nnoofwides = df1[df1['wides']> 0]\r\nindex = noofwides.index\r\nfinalwides = len(index)\r\nnoofnoballs = df1[df1['noballs'] > 0]\r\nindex = noofnoballs.index\r\nfinalnoballs = len(index)\r\nfinalrows = rows - finalwides - finalnoballs\r\naverage = runs/wickets\r\nstrikerate = finalrows/wickets\r\neconomy = (runs/finalrows)*6\r\nname = df1['bowling_team'].iloc[1]\r\nprint(\"Team: \", name)\r\nprint(\"Runs: \", runs)\r\nprint(\"Wickets: \", wickets)\r\nprint(\"Overs: \", int(finalrows/6)+(finalrows%6)/10)\r\nprint(\"Average\", round(average,2))\r\nprint(\"Economy\", round(economy,2))\r\nprint(\"Strike-rate\", round(strikerate,2))\r\n\r\n","sub_path":"Specific Bowling Team.py","file_name":"Specific Bowling Team.py","file_ext":"py","file_size_in_byte":1502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"11822562","text":"from openerp import models,fields,api\nfrom openerp.tools.float_utils import float_compare\nimport openerp.addons.decimal_precision as dp\n\n\n#INHERITANCE MODELS\n\nclass product_product(models.Model):\n _inherit = 'product.product'\n \n def get_customer_sale_price(self, discount_type, sale_price, cost_price, quantity):\n return self.product_tmpl_id.get_customer_sale_price(discount_type, sale_price, cost_price, quantity)\n\nclass product_template(models.Model):\n _inherit = 'product.template'\n \n def get_customer_sale_price(self, discount_type_id, sale_price, cost_price, quantity):\n if discount_type_id and sale_price and self.is_pneumatics:\n margin_percent = ((sale_price - cost_price)/sale_price)*100\n if margin_percent < 0:\n margin_percent = 0\n if margin_percent > 100:\n margin_percent = 100\n margin_percent = round(margin_percent,2)\n discounts = self.env['discount.type.discount'].search([('discount_type_id','=',discount_type_id),('margin_min','<=',margin_percent),('margin_max','>=',margin_percent)])\n if discounts:\n sale_price = sale_price-((discounts[0].discount_percent/100)*sale_price)\n return sale_price\n\nclass sale_order(models.Model):\n _inherit = 'sale.order'\n \n discount_type_id = fields.Many2one('product.discount.type', 'Discount type', states={'draft': [('readonly', False)]})\n \n \n @api.multi\n def onchange_partner_id(self, partner):\n result = super(sale_order, self).onchange_partner_id(partner)\n if not result:\n result = {'value':{}}\n elif not result.has_key('value'):\n result['value'] = {}\n \n partner_obj = self.env[\"res.partner\"].browse(partner)\n \n result['value'].update({'discount_type_id':partner_obj.discount_type_id.id})\n \n return result\n \n \n #@api.onchange('discount_type_id') -- don't know why it doesn't works\n @api.one\n def update_all_prices(self):\n for line in self.order_line:\n on_change_res = line.product_id_change_with_wh_quotation_address_discount_type(\n pricelist=self.pricelist_id.id, \n product=line.product_id.id, \n qty=line.product_uom_qty, \n uom=line.product_uom.id, \n discount_type_id=self.discount_type_id.id, \n partner_id=self.partner_id.id\n )\n \n \n if on_change_res.has_key('value'):\n if on_change_res['value'].has_key('purchase_price'): \n line.purchase_price = on_change_res['value']['purchase_price']\n if on_change_res['value'].has_key('brut_sale_price'): \n line.brut_sale_price = on_change_res['value']['brut_sale_price']\n #For Sale price, we get customer price\n customer_price = line.product_id.get_customer_sale_price(self.discount_type_id.id, line.product_id.list_price, line.product_id.cost_price, line.product_uom_qty)\n product_price = line.product_id.list_price\n discount = 100-(100*customer_price/product_price)\n line.price_unit = product_price\n line.discount = discount\n \n \nsale_order()\n\nclass res_partner(models.Model):\n _inherit = 'res.partner' \n discount_type_id = fields.Many2one('product.discount.type', string='Discount type')\n discount_exceptions = fields.One2many('customer.discount.exception','partner_id','Discount exceptions')\nres_partner()\n\n\nclass sale_order_line(models.Model):\n _inherit = 'sale.order.line'\n \n @api.model\n def _calc_line_base_price(self, line):\n return line.price_unit\n \n @api.one\n @api.onchange('discount','brut_sale_price')\n def update_price_unit(self):\n #prevent loop\n price_calculated = self.brut_sale_price - (self.brut_sale_price*self.discount/100)\n \n if float_compare(price_calculated, self.price_unit, precision_digits=self.env['decimal.precision'].precision_get('Product Price')) == 0:\n return\n \n new_price_unit = self.brut_sale_price - (self.brut_sale_price*self.discount/100)\n self.price_unit = new_price_unit\n \n \n @api.one\n @api.onchange('price_unit')\n def update_discount(self):\n #prevent loop\n price_calculated = self.brut_sale_price - (self.brut_sale_price*self.discount/100)\n if float_compare(price_calculated, self.price_unit, precision_digits=self.env['decimal.precision'].precision_get('Product Price')) == 0:\n return\n \n if self.brut_sale_price:\n new_discount = 100 - (self.price_unit / self.brut_sale_price) * 100\n else:\n new_discount = 0\n self.discount = new_discount\n \n \n @api.multi\n def product_id_change_with_wh_quotation_address_discount_type(self, pricelist, product, qty=0,\n uom=False, qty_uos=0, uos=False, name='', partner_id=False,\n lang=False, update_tax=True, date_order=False, packaging=False, fiscal_position=False, flag=False, warehouse_id=False, quotation_address_id=False, discount_type_id=False):\n \n #for pneumatics product, don't use price list. Discount is computed in get_customer_sale_price function below via discount type.\n product_obj = self.env['product.product'].browse(product)\n if product_obj and product_obj.is_pneumatics:\n pricelist = 1\n \n res = super(sale_order_line, self).product_id_change_with_wh_quotation_address(pricelist, product, qty=qty,\n uom=uom, qty_uos=qty_uos, uos=uos, name=name, partner_id=partner_id,\n lang=lang, update_tax=update_tax, date_order=date_order, packaging=packaging, fiscal_position=fiscal_position, flag=flag, warehouse_id=warehouse_id, quotation_address_id=quotation_address_id)\n \n if res.has_key('value') and res['value'].has_key('price_unit') and res['value'].has_key('purchase_price'):\n product = self.env['product.product'].browse(product)\n customer_price = product.get_customer_sale_price(discount_type_id, res['value']['price_unit'], res['value']['purchase_price'], qty)\n product_price = product.list_price\n if product_price:\n discount = 100-(100*customer_price/product_price)\n else:\n discount = 0\n res['value']['price_unit'] = customer_price\n res['value']['discount'] = discount\n \n return res\n \n @api.multi\n def product_uom_qty_change_with_wh_discount_type(self, pricelist, product, qty=0,\n uom=False, qty_uos=0, uos=False, name='', partner_id=False,\n lang=False, update_tax=True, date_order=False, packaging=False, fiscal_position=False, flag=False, warehouse_id=False, discount_type_id=False):\n \n res = {}\n #change price of pneumatics products when qty change\n product_obj = self.env['product.product'].browse(product)\n if product_obj and product_obj.is_pneumatics:\n pricelist = 1\n res = self.product_id_change_with_wh_quotation_address_discount_type(pricelist, product, qty=qty,\n uom=uom, qty_uos=qty_uos, uos=uos, name=name, partner_id=partner_id,\n lang=lang, update_tax=update_tax, date_order=date_order, packaging=packaging, fiscal_position=fiscal_position, flag=flag, warehouse_id=warehouse_id, quotation_address_id=False, discount_type_id=discount_type_id)\n \n #don't change route type when change qty\n if res.get('value') and res['value'].get('route_id'):\n res['value'].pop('route_id')\n \n #if line already saved : don't change price\n if self.id:\n if res.get('value') and res['value'].get('price_unit'):\n res['value'].pop('price_unit')\n if res.get('value') and res['value'].get('discount'):\n res['value'].pop('discount')\n if res.get('value') and res['value'].get('brut_sale_price'):\n res['value'].pop('brut_sale_price')\n \n \n return res\n \n#BASE MODELS\n\nclass discount_type_discount(models.Model):\n _name = 'discount.type.discount'\n _order = 'discount_type_id, margin_min, margin_max' \n \n discount_type_id = fields.Many2one('product.discount.type', string=\"Discount type\")\n margin_max = fields.Float(string=\"Maximum margin\")\n margin_min = fields.Float(string=\"Minimum margin\")\n discount_percent = fields.Float(string=\"Discount (percent)\")\n \ndiscount_type_discount()\n\n\nclass product_discount_type(models.Model):\n _name = 'product.discount.type'\n _order = 'name'\n \n name = fields.Char(string=\"name\")\n discounts = fields.One2many('discount.type.discount', 'discount_type_id', string='Discounts')\n \n #product_group_discounts = fields.One2many('product.group.discount', 'discount_type_id', string='Product group discounts')\n #to copy in new module\n\nproduct_discount_type()\n\nclass customer_discount_exception(models.Model):\n _name = 'customer.discount.exception'\n _order = 'partner_id, categ_id, discount'\n \n partner_id = fields.Many2one('res.partner', 'Partner')\n categ_id = fields.Many2one('product.category', 'Product category')\n discount = fields.Float('Discount')\n #product_group_id = fields.Many2one('product.group', 'Product group')\n #to copy in new module\n \ncustomer_discount_exception()\n","sub_path":"elneo_autocompute_saleprice/customer_discount.py","file_name":"customer_discount.py","file_ext":"py","file_size_in_byte":9566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"332894273","text":"import gym\r\nfrom cart_pole_NeuralNetwork import *\r\n\r\ngame = 'CartPole-v0'\r\nwins = 0\r\nfinished = False\r\nenv = gym.make(game)\r\nprint(env.action_space.n)\r\nprint(env.observation_space.shape[0])\r\nnn = neuralNetwork(env.observation_space.shape[0], env.action_space.n)\r\nfor episode in range(1000):\r\n observation = env.reset()\r\n for t in range(1000):\r\n if episode >= 150:\r\n env.render()\r\n nn.memoryState.append(observation)\r\n action = nn.prediction(observation)\r\n nn.memoryAction.append(action)\r\n observation, reward, done, info = env.step(action)\r\n nn.memoryNextState.append(observation)\r\n if done:\r\n print(t)\r\n if t == 199:\r\n print('Win!')\r\n wins += 1\r\n if wins >= 5:\r\n nn.save('NN_model_'+game+'_3.h5')\r\n finished = True\r\n nn.memoryReward.append(-1)\r\n else:\r\n print('Lose!')\r\n wins = 0\r\n nn.memoryReward.append(-1)\r\n break\r\n nn.memoryReward.append(0)\r\n print('Episode: '+str(episode))\r\n print('Wins: '+str(wins))\r\n if finished:\r\n break\r\n if wins == 0 and episode % 3 == 0:\r\n nn.replay(episode)\r\n # input('waiting...')\r\n","sub_path":"DQN/cart_pole.py","file_name":"cart_pole.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"481816091","text":"import asyncio\n\nimport bs4\nimport pandas as pd\nimport us\n\nfrom ...puppet import with_page\nfrom ... import DatasetBaseNoDate\nfrom .. import CountyData\n\n\nclass Washington(DatasetBaseNoDate, CountyData):\n source = \"https://www.doh.wa.gov/Emergencies/COVID19/DataDashboard\"\n state_fips = int(us.states.lookup(\"Washington\").fips)\n has_fips = False\n url = \"https://www.doh.wa.gov/Emergencies/COVID19/DataDashboard\"\n\n def get(self) -> pd.DataFrame:\n return asyncio.run(self._get_data())\n\n async def _get_data(self):\n async with with_page(headless=True) as page:\n await page.goto(\n \"https://www.doh.wa.gov/Emergencies/COVID19/DataDashboard\",\n {\"waitUntil\": \"networkidle2\"},\n )\n\n res = await page.content()\n\n soup = bs4.BeautifulSoup(res)\n tables = soup.select(\"#pnlConfirmedCasesDeathsTbl table\")\n assert len(tables) == 1\n dfs = pd.read_html(str(tables[0]))\n assert len(dfs) == 1\n df = (\n dfs[0]\n .query(\"County not in ('Unassigned', 'Total')\")\n .rename(\n columns={\n \"County\": \"county\",\n \"Confirmed Cases\": \"cases_total\",\n \"Hospitalizations\": \"hospital_beds_in_use_covid_total\",\n \"Deaths\": \"deaths_total\",\n }\n )\n .assign(\n vintage=self._retrieve_vintage(), dt=self._retrieve_dt(tz=\"US/Pacific\")\n )\n .melt(\n id_vars=[\"vintage\", \"dt\", \"county\"],\n var_name=\"variable_name\",\n value_name=\"value\",\n )\n )\n return df\n","sub_path":"src/cmdc_tools/datasets/official/WA/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"58515326","text":"'''\nУрок 3. Основы сетевого программирования\n1. Реализовать простое клиент-серверное взаимодействие по протоколу JIM (JSON instant messaging):\na. клиент отправляет запрос серверу;\nb. сервер отвечает соответствующим кодом результата.\nКлиент и сервер должны быть реализованы в виде отдельных скриптов, содержащих соответствующие функции.\nФункции клиента:\n1. Сформировать presence-сообщение;\n2. Отправить сообщение серверу;\n3. Получить ответ сервера;\n4. Разобрать сообщение сервера;\n5. Параметры командной строки скрипта client.py []:\n6. Addr — ip-адрес сервера;\n7. Port — tcp-порт на сервере, по умолчанию 7777.\nФункции сервера:\n1. Принимает сообщение клиента;\n2. Формирует ответ клиенту;\n3. Отправляет ответ клиенту.\nИмеет параметры командной строки:\n-p — TCP-порт для работы (по умолчанию использует 7777);\n-a — IP-адрес для прослушивания (по умолчанию слушает все доступные адреса).\n'''\nimport sys, json, time, logging, logs.config.server_config_log, decorators\nfrom config import *\nfrom socket import *\n\nlog = logging.getLogger('Server_log')\nlogger = decorators.Log(log)\n\n@logger\ndef check_correct_presence_and_response(presence_message):\n log.info('Запуск ф-ии проверки корректности запроса')\n if ACTION in presence_message and presence_message[ACTION] == 'Unknown':\n return {RESPONSE: UNKNOWN_ERROR}\n elif ACTION in presence_message and \\\n presence_message[ACTION] == PRESENCE and \\\n TIME in presence_message and \\\n isinstance(presence_message[TIME], float):\n # Если всё хорошо шлем ОК\n log.info(f'Проверка успешна, ответ: {RESPONSE}: {OK}')\n return {RESPONSE: OK}\n else:\n # Иначе шлем код ошибки\n log.warning(f'{RESPONSE}: {WRONG_REQUEST}, {ERROR}: \"Не верный запрос\"')\n return {RESPONSE: WRONG_REQUEST, ERROR: 'Не верный запрос'}\n\n@logger\ndef start_server(serv_addr=server_address, serv_port=server_port):\n alive = True\n s = socket(AF_INET,SOCK_STREAM)\n\n if not isinstance(serv_addr,str) or not isinstance(serv_port,int):\n log.error('Полученный адрес сервера или порт не является строкой или числом!')\n s.close()\n raise ValueError\n\n s.bind((serv_addr,serv_port))\n s.listen(1)\n #print('Готов к приему клиентов! \\n')\n log.info('Запуск сервера! Готов к приему клиентов! \\n')\n #answer = 'Сервер сообщение получил! Привет клиент!'\n\n while alive:\n client, address = s.accept()\n client_message = json.loads(client.recv(1024).decode(\"utf-8\"))\n #print(f'Принято сообщение от клиента: {client_message}')\n log.info(f'Принято сообщение от клиента: {client_message}')\n answer = check_correct_presence_and_response(client_message)\n #print(f\"Приветствуем пользователя {client_message.get('user').get('account_name')}!\")\n #print('Отправка ответа клиенту:',answer)\n log.info(f\"Приветствуем пользователя {client_message.get('user').get('account_name')}!\")\n log.info(f'Отправка ответа клиенту: {answer}')\n client.send(json.dumps(answer).encode('utf-8'))\n client.close\n\nif __name__ == \"__main__\":\n if len(sys.argv) > 1:\n for i in range(1,len(sys.argv)):\n if sys.argv[i] == '-p' and i+1 < len(sys.argv):\n server_port = sys.argv[i+1]\n if sys.argv[i] == '-a' and i+1 < len(sys.argv):\n server_address = sys.argv[i+1]\n\n #Показывать лог в консоль при запуске сервера напрямую\n server_stream_handler = logging.StreamHandler(sys.stdout)\n server_stream_handler.setLevel(logging.INFO)\n server_stream_handler.setFormatter(logs.config.server_config_log.log_format)\n log.addHandler(server_stream_handler)\n\n start_server()","sub_path":"Block3/Homework6/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"542180167","text":"import json\n# import math\nimport time\n\nimport requests\n\n\ndef get_category(content):\n url = \"http://39.96.199.128:9000/article/analysis\"\n text = {\n 'text': content\n }\n data = requests.post(url, data=text).text\n data = json.loads(data)\n status = data['status']\n classify = ''\n codes = ''\n if status == 'success':\n cates = data['category']\n areas = data['area']\n region = ''\n if areas:\n for area in areas:\n region = region + area + '|'\n for cate in cates:\n pro = cate['accuracy']\n pro = float(pro)\n if pro >= 0.05:\n cateName = cate['tagName']\n code = cate['tag']\n classify = classify + cateName + '|'\n codes = codes + code + '|'\n return classify, codes, region\n\n\nif __name__ == '__main__':\n from lxml import etree\n url = 'http://www.zgyj.org.cn/indnews/071930205.html'\n html = requests.get(url).text\n soup = etree.HTML(html)\n content = soup.xpath(\"//div[@class='container']/div[@class='row']/div[@class='col-xs-12 col-sm-12 col-md-10 article_yq']/div[@class='nr']/div[3]//text()\")\n print(content)\n content = ''.join(content).replace('\\xa0', '').replace('\\u3000', '').replace('\\r', '').replace('\\n',\n '').replace('\\t',\n '').replace(\n ' ', '')\n s = time.time()\n cate, code, region = get_category(content)\n y = time.time()\n x = y - s\n print(cate, code, region)","sub_path":"HY_NEWS/HY_NEWS/util_custom/tools/cate.py","file_name":"cate.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"585995772","text":"\"\"\"Module for seriaizers\"\"\"\n\ndef marca_serializer(dato):\n \"\"\"serializar los datos en la busqueda actualizar marca\"\"\"\n return {\n 'nombre': dato.nombre,\n 'id': dato.id,\n 'url': dato.get_absolute_url()\n }\n\ndef rubro_serializer(dato):\n \"\"\"serializar los datos en la busqueda de rubros\"\"\"\n return {\n 'nombre': dato.nombre,\n 'id': dato.id,\n 'url': dato.get_absolute_url()\n }\n\ndef articulo_serializer(dato):\n \"\"\"Para serializar el articulo\"\"\"\n return {\n 'descripcion': dato.descripcion,\n 'codigo': dato.codigo,\n 'marca': dato.marca.nombre,\n 'precio': dato.precio,\n 'url': dato.get_absolute_url()\n }\n\ndef proveedor_serializer(dato):\n \"\"\"Serializar el proveedor\"\"\"\n return {\n 'id': str(dato.cliente.id),\n 'nombre': dato.cliente.nombre,\n 'repres': dato.repres,\n 'cuit': dato.cliente.cuit,\n 'email': dato.cliente.email\n }\n\ndef cliente_serializer(dato):\n \"\"\"Serializar el Cliente\"\"\"\n return {\n 'id': str(dato.id),\n 'dni': dato.dni,\n 'nombre': dato.nombre,\n 'telefono': dato.telefono,\n 'email': dato.email,\n 'url': dato.get_absolute_url(),\n }\n\ndef carrito_serializer(dato):\n \"\"\"serializar el carrito\"\"\"\n return {\n 'articulo': dato.articulo.descripcion,\n 'cantidad': dato.cantidad,\n 'precio': dato.articulo.precio,\n 'subtotal': dato.subtotal\n }\n","sub_path":"gestion/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"399148574","text":"from conans import ConanFile, CMake, tools\nimport os\n\nclass Ld64Conan(ConanFile):\n name = 'ld64'\n\n # ld64 version 530 is from Xcode 11.3.1.\n # https://en.wikipedia.org/wiki/Xcode#Xcode_7.0_-_10.x_(since_Free_On-Device_Development)\n # https://opensource.apple.com/release/developer-tools-1131.html\n # https://b33p.net/kosada/vuo/vuo/-/issues/4144\n # https://b33p.net/kosada/vuo/vuo/-/issues/17561\n # https://b33p.net/kosada/vuo/vuo/-/issues/17836\n ld64_version = '530'\n\n # dyld version 750.6 is from macOS 10.15.6.\n # https://opensource.apple.com/release/macos-10156.html\n dyld_version = '750.6'\n\n # Not from Xcode 11, but from the latest version that Apple provides:\n tapi_version = '1100.0.11'\n\n # Apple stopped publishing their LLVM/Clang source code after Xcode 8.2.1.\n # This is the earliest version that supports tapi-1100.0.11.\n llvm_version = '11.0.0'\n\n package_version = '5'\n version = '%s-%s' % (ld64_version, package_version)\n\n requires = 'llvm/5.0.2-3@vuo/stable'\n build_requires = 'macos-sdk/11.0-0@vuo/stable'\n settings = 'os', 'compiler', 'build_type', 'arch'\n url = 'https://opensource.apple.com/'\n license = 'https://opensource.apple.com/source/ld64/ld64-%s/APPLE_LICENSE.auto.html' % ld64_version\n description = 'Combines several object files and libraries, resolves references, and produces an ouput file'\n ld64_source_dir = 'ld64-%s' % ld64_version\n dyld_source_dir = 'dyld-%s' % dyld_version\n llvm_source_dir = 'llvm-%s.src' % llvm_version\n tapi_source_dir = '%s/projects/tapi-%s' % (llvm_source_dir, tapi_version)\n\n build_llvm_x86_dir = '_build_llvm_x86'\n build_llvm_arm_dir = '_build_llvm_arm'\n install_universal_dir = '_install_universal'\n\n exports_sources = '*.patch'\n\n def source(self):\n tools.get('https://opensource.apple.com/tarballs/ld64/ld64-%s.tar.gz' % self.ld64_version,\n sha256='ee37f0487601c08c7d133bc91cad2e9084d00d02aa4709d228a9a065960aa187')\n tools.get('https://opensource.apple.com/tarballs/dyld/dyld-%s.tar.gz' % self.dyld_version,\n sha256='4fd378cf30718e0746c91b145b90ddfcaaa4c0bf01158d0461a4e092d7219222')\n\n tools.get('https://github.com/llvm/llvm-project/releases/download/llvmorg-%s/llvm-%s.src.tar.xz' % (self.llvm_version, self.llvm_version),\n sha256='913f68c898dfb4a03b397c5e11c6a2f39d0f22ed7665c9cefa87a34423a72469')\n with tools.chdir('%s/projects' % self.llvm_source_dir):\n tools.get('https://github.com/llvm/llvm-project/releases/download/llvmorg-%s/clang-%s.src.tar.xz' % (self.llvm_version, self.llvm_version),\n sha256='0f96acace1e8326b39f220ba19e055ba99b0ab21c2475042dbc6a482649c5209')\n tools.get('https://opensource.apple.com/tarballs/tapi/tapi-%s.tar.gz' % self.tapi_version,\n sha256='1c1d7079e65c615cb12d58c1de5c49031e56774e1f17e55a57faa5d4253b9126')\n with tools.chdir('tapi-%s' % self.tapi_version):\n tools.replace_in_file('CMakeLists.txt', 'check_linker_flag(\"-Wl,-no_inits\" LINKER_SUPPORTS_NO_INITS)', '')\n tools.replace_in_file('CMakeLists.txt', 'check_linker_flag(\"-Wl,-iosmac_version_min,12.0\" LINKER_SUPPORTS_IOSMAC)', '')\n tools.patch(patch_file='../../../tapi.patch')\n\n # Remove the CrashReporter stuff, which isn't open source.\n tools.replace_in_file('%s/src/ld/Options.cpp' % self.ld64_source_dir,\n '#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070',\n '#if 0')\n\n with tools.chdir(self.dyld_source_dir):\n tools.replace_in_file('include/mach-o/dyld.h', '__API_UNAVAILABLE(bridgeos)', '')\n tools.replace_in_file('include/mach-o/dyld_priv.h', ', bridgeos(3.0)', '')\n\n with tools.chdir(self.ld64_source_dir):\n # Don't include Swift demangling since we don't use it.\n tools.replace_in_file('src/create_configure',\n 'if [ -f \"${DT_TOOLCHAIN_DIR}/usr/lib/libswiftDemangle.dylib\" ]; then',\n 'if false; then')\n\n tools.replace_in_file('ld64.xcodeproj/project.pbxproj',\n '\t\t\t\tSDKROOT = macosx.internal;',\n '\t\t\t\tSDKROOT = macosx;')\n tools.replace_in_file('ld64.xcodeproj/project.pbxproj',\n '\t\t\t\tVALID_ARCHS = \"x86_64 i386 ppc\";',\n '\t\t\t\tVALID_ARCHS = \"x86_64 arm64\";')\n tools.replace_in_file('ld64.xcodeproj/project.pbxproj',\n '\t\t\t\tMACOSX_DEPLOYMENT_TARGET = 10.14;',\n '\t\t\t\tMACOSX_DEPLOYMENT_TARGET = 10.11;')\n\n self.run('mv %s/APPLE_LICENSE %s/%s.txt' % (self.ld64_source_dir, self.ld64_source_dir, self.name))\n\n def build(self):\n cmake = CMake(self)\n cmake.definitions['CMAKE_OSX_SYSROOT'] = self.deps_cpp_info['macos-sdk'].rootpath\n cmake.definitions['CMAKE_CXX_FLAGS'] = ' -I%s/%s/projects/clang-%s.src/include' % (os.getcwd(), self.llvm_source_dir, self.llvm_version)\n cmake.definitions['CMAKE_CXX_FLAGS'] += ' -I%s/%s/projects/clang-%s.src/include' % (os.getcwd(), self.build_llvm_x86_dir, self.llvm_version)\n cmake.definitions['CMAKE_OSX_DEPLOYMENT_TARGET'] = '10.11'\n cmake.definitions['LLVM_INCLUDE_TESTS'] = 'OFF'\n cmake.definitions['LLVM_TARGETS_TO_BUILD'] = 'X86;AArch64'\n cmake.definitions['CLANG_TABLEGEN_EXE'] = 'clang-tblgen'\n\n\n self.output.info(\"=== Build libtapi for x86_64 ===\")\n cmake.definitions['CMAKE_OSX_ARCHITECTURES'] = 'x86_64'\n cmake.definitions['LLVM_DEFAULT_TARGET_TRIPLE'] = 'x86_64-apple-macos10.11.0'\n tools.mkdir(self.build_llvm_x86_dir)\n with tools.chdir(self.build_llvm_x86_dir):\n cmake.configure(source_dir='../%s' % self.llvm_source_dir, build_dir='.')\n cmake.build(target='libtapi')\n\n\n self.output.info(\"=== Build libtapi for arm64 ===\")\n cmake.definitions['CMAKE_CROSSCOMPILING'] = 'ON'\n cmake.definitions['CMAKE_OSX_ARCHITECTURES'] = 'arm64'\n cmake.definitions['LLVM_DEFAULT_TARGET_TRIPLE'] = 'arm64-apple-macos10.11.0'\n cmake.definitions['LLVM_TARGET_ARCH'] = 'AArch64'\n # tblgen needs to run on the host, so it should be x86 even when cross-compiling for arm.\n cmake.definitions['LLVM_TABLEGEN'] = '%s/%s/bin/llvm-tblgen' % (os.getcwd(), self.build_llvm_x86_dir)\n cmake.definitions['CLANG_TABLEGEN'] = '%s/%s/bin/clang-tblgen' % (os.getcwd(), self.build_llvm_x86_dir)\n cmake.definitions['CLANG_TABLEGEN_EXE'] = cmake.definitions['CLANG_TABLEGEN']\n flags = ' -target arm64-apple-macos10.11.0'\n cmake.definitions['CMAKE_C_FLAGS'] = flags\n cmake.definitions['CMAKE_CXX_FLAGS'] += flags\n tools.mkdir(self.build_llvm_arm_dir)\n with tools.chdir(self.build_llvm_arm_dir):\n cmake.configure(source_dir='../%s' % self.llvm_source_dir, build_dir='.')\n cmake.build(target='libtapi')\n\n\n self.output.info(\"=== Merge x86_64 + arm64 libtapi ===\")\n tools.mkdir(self.install_universal_dir)\n with tools.chdir(self.install_universal_dir):\n tools.mkdir('lib')\n with tools.chdir('lib'):\n self.run('lipo -create ../../%s/lib/libtapi.dylib ../../%s/lib/libtapi.dylib -output libtapi.dylib' % (self.build_llvm_x86_dir, self.build_llvm_arm_dir))\n self.run('codesign --sign - libtapi.dylib')\n\n\n self.output.info(\"=== Build ld for both x86_64 + arm64 ===\")\n with tools.chdir(self.ld64_source_dir):\n tools.replace_in_file('ld64.xcodeproj/project.pbxproj',\n '\"-ltapi\",',\n '\"%s/../%s/lib/libtapi.dylib\",' % (os.getcwd(), self.install_universal_dir))\n self.run('RC_SUPPORTED_ARCHS=\"x86_64 arm64\" xcodebuild ARCHS=\"x86_64 arm64\" -target ld HEADER_SEARCH_PATHS=\"../%s/include ../%s/include ../%s/include ../%s/projects/tapi-%s/include src/ld\"' % (self.dyld_source_dir, self.llvm_source_dir, self.tapi_source_dir, self.build_llvm_x86_dir, self.tapi_version))\n\n\n def package(self):\n self.copy('ld', src='%s/build/Release-assert' % self.ld64_source_dir, dst='bin')\n self.copy('libtapi.dylib', src='%s/lib' % self.install_universal_dir, dst='lib')\n self.copy('%s.txt' % self.name, src=self.ld64_source_dir, dst='license')\n","sub_path":"conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":8560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"183410345","text":"from sympy.interactive.printing import init_printing\r\ninit_printing(use_unicode=False, wrap_line=True, no_global=True)\r\nfrom sympy import *\r\nimport numpy as np\r\nfrom scipy.stats import norm\r\n\r\n\r\ndef optFreeBond(period_comp=None, C=None, disc_rate=None, T=None,\r\n FaceV=1, price=None):\r\n # if(FaceV is None):\r\n # FaceV = self.P\r\n\r\n N = T * period_comp + 1\r\n\r\n disc_rate_sym, T_sym, FaceV_sym, price_sym = symbols('r T F P')\r\n\r\n C_sym = MatrixSymbol('C', N, 1)\r\n period_comp_sym = MatrixSymbol('k', N, 1)\r\n t_sym = MatrixSymbol('t', N, 1)\r\n\r\n if (C != None):\r\n C_sym.values = Matrix(C * np.concatenate([[0], np.ones(N)]))\r\n if (price != None):\r\n price_sym = price_sym.subs(price_sym, price)\r\n if (disc_rate != None):\r\n disc_rate_sym = disc_rate_sym.subs(disc_rate_sym, disc_rate)\r\n\r\n if (price == None):\r\n unk = price_sym\r\n else:\r\n unk = disc_rate_sym\r\n\r\n Expr = 0\r\n\r\n for i in range(N):\r\n Expr = Expr + C_sym.values[i] / (1 + disc_rate_sym / period_comp) ** i\r\n if (i == T * period_comp):\r\n Expr = Expr + FaceV / (1 + disc_rate_sym / period_comp) ** i\r\n pass\r\n Expr = Expr - price_sym\r\n\r\n ans = unk\r\n\r\n # for soltn in solve(Expr, unk) : ans = soltn if soltn > 0 & soltn.is_real else ans\r\n # ans = solve(Expr,unk)\r\n\r\n ans = Matrix([nsolve(Expr, unk, 0.01), relational.Eq(Expr, 0)])\r\n\r\n return (ans)\r\n\r\n\r\n\r\ndef binomial_ir(spotr, std):\r\n N = len(spotr)\r\n rates = {}\r\n rates_sym = {}\r\n i_sym = {}\r\n spotr = np.asarray(spotr)\r\n\r\n ratesM = MatrixSymbol('R', N, N)\r\n std_sym = Symbol('sigma')\r\n\r\n\r\n for i in range(N):\r\n rates[i] = []\r\n rates_sym[i] = []\r\n i_sym[i] = Symbol('i%d' % i)\r\n\r\n\r\n for i in range(N):\r\n for j in range(i+1):\r\n rates[i].append([spotr[i]*np.exp((i-2*j)*std)])\r\n rates_sym[i].append([i_sym[i] * exp((i - 2 * j) * std_sym)])\r\n for j in range(i+1, N):\r\n rates[i].append([0])\r\n rates_sym[i].append([0])\r\n\r\n ans_num = rates[0]\r\n ans_sym = rates_sym[0]\r\n\r\n class Answer:\r\n def __init__(self, symbolic, numeric):\r\n self.syms = symbolic\r\n self.num = numeric\r\n\r\n\r\n for i in range(1,N):\r\n ans_num = np.c_[ans_num, np.array(rates[i])]\r\n ans_sym = np.c_[ans_sym, np.array(rates_sym[i])]\r\n\r\n ratesM.values = Matrix(ans_sym)\r\n ans = Answer(ratesM, ans_num)\r\n\r\n return(ans)\r\n\r\n\r\n\r\ndef call_simple(call_price, price, T, per, sUp, sDown, cUp, cDown, rate):\r\n hedge_ratio = (cUp - cDown) / (sUp - sDown)\r\n\r\n c = call_price # write one call option\r\n hS = hedge_ratio*price # buy h units\r\n\r\n prob = ((1 + rate/per) - sDown/price) / ((sUp - sDown) / price)\r\n\r\n T = T*per\r\n\r\n class Call:\r\n def __init__(self, hedge_ratio, hS, sUp, sDown, prob, cUp, cDown, rate, per, T):\r\n self.valueDwn_arb = hS + (-hedge_ratio*sDown + cDown)/(1+rate/per)**T\r\n self.valueUp_arb = hS + (-hedge_ratio*sUp + cUp)/(1+rate/per)**T\r\n self.value_exp = (prob*cUp + (1 - prob)*cDown)/(1+rate/per)**T\r\n\r\n\r\n\r\n arb_call = Call(hedge_ratio, hS, sUp, sDown, prob, cUp, cDown, rate, per, T)\r\n\r\n return(arb_call)\r\n\r\n\r\n\r\n\r\n'''_____________________________NON-DIVIDEND PAYING___________________________'''\r\ndef option_binLattice(price, strike_p, u, d, T, per, rate, option_type='call'):\r\n\r\n option = {}\r\n optMove = {}\r\n\r\n prob = ((1 + rate / per) - d) / (u - d)\r\n\r\n N = T*per\r\n\r\n for i in range(N+1):\r\n optMove[i] = np.array([])\r\n for j in range(i+1):\r\n optMove[i] = np.append(optMove[i], u**(i-j)*d**(j))\r\n\r\n for i in range(N, -1, -1):\r\n option[i] = np.array([])\r\n\r\n for j in range(i + 1):\r\n \r\n if ((i == N) & (option_type == 'call')):\r\n option[N] = np.append(option[N], max([0, optMove[N][j] * price - strike_p]))\r\n \r\n elif ((i == N) & (option_type == 'put')):\r\n option[N] = np.append(option[N], max([0, strike_p - optMove[N][j] * price]))\r\n \r\n else:\r\n option[i] = np.append(option[i], max([0, prob*option[i+1][j]\r\n + (1- prob)*option[i+1][j + 1]])/(1+rate/per))\r\n if(option_type == 'call'):\r\n option[i][j] = max([option[i][j], optMove[i][j]*price - strike_p])\r\n elif(option_type == 'put'):\r\n option[i][j] = max([option[i][j], strike_p - optMove[i][j]*price])\r\n else:\r\n option[i][j] = None\r\n\r\n return option\r\n\r\ndef option_BlackScholes(price, strikeP, years, rate, carryBenefits=0, variance=0.1, option_type='call'):\r\n\r\n d1 = float((log(price/strikeP)+(rate - carryBenefits + variance/2)*years)/sqrt(variance*years))\r\n d2 = d1 - sqrt(variance*years)\r\n \r\n if(option_type == 'call'):\r\n option = float(price*exp(-carryBenefits*years)*norm.cdf(d1) - exp(-rate*years)*strikeP*norm.cdf(-d1))\r\n elif(option_type == 'put'):\r\n option = float(exp(-rate*years)*strikeP*norm.cdf(-d2) - price*exp(-carryBenefits*years)*norm.cdf(d1))\r\n else:\r\n option = None\r\n \r\n return option\r\n\r\n\r\ndef testing():\r\n c = call_simple(None, 100, 1, 1, 135, 74, 35, 0, 0.0515)\r\n print(c.valueDwn_arb)\r\n print(c.valueUp_arb)\r\n print(c.value_exp)\r\n b = option_BlackScholes(100, 100, 1, 0.05, carryBenefits=0, variance=0.3, option_type='call')\r\n return option_binLattice(72, 75, 1.356, 0.541, 2, 1, 0.03, option_type='call')\r\n\r\ntesting()","sub_path":"FinSym.py","file_name":"FinSym.py","file_ext":"py","file_size_in_byte":5637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"269527522","text":"# -*- coding: utf-8 -*-\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn import datasets\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import mean_squared_error\nfrom math import sqrt\n\n\"\"\"A simple decision tree model.\nO'Reilly E-book page:\nhttps://learning.oreilly.com/library/view/building-machine-learning/9781484244708/html/463852_1_En_23_Chapter.xhtml\n\"\"\"\n\n# Make the models deterministic\nRANDOM_SEED = 42\n\n\nclass RandomForestDemo:\n \"\"\"In this code example, we will build a random forest classification model and a random forest\n regression model.\n\n One of the significant advantages of this class of models is that they perform well on linear and\n non-linear datasets. Moreover, they implicitly take care of feature selection and work well with\n high-dimensional datasets. On the flip side, these models can very easily overfit the dataset and\n fail to generalize to new examples. This downside is mitigated by aggregating a large number of\n decision trees in techniques like Random forests and boosting ensemble algorithms.\n \"\"\"\n\n def make_prediction(self, data, dataset):\n \"\"\"Train a models and predict using the specified dataset.\n\n :param data: tuple - a tuple containing the data and the targets.\n :param dataset: string - the particular dataset we will train on.\n :return:\n \"\"\"\n # Separate features and target\n X = data[0]\n y = data[1]\n\n # Split in train and test sets\n X_train, X_test, y_train, y_test = train_test_split(X, y, shuffle=True)\n\n # Create the model\n model = self.get_classifier(dataset)\n\n # Fit the model on the training set\n model.fit(X_train, y_train)\n\n # Make predictions on the test set\n predictions = model.predict(X_test)\n\n # Evaluate the model performance.\n if dataset == 'flowers':\n accuracy = accuracy_score(y_test, predictions)\n print('Classifier accuracy {:.2f}'.format(accuracy))\n else:\n rmse = sqrt(mean_squared_error(y_test, predictions))\n print('Regression root mean squared error {:.2f}'.format(rmse))\n\n @staticmethod\n def get_classifier(dataset_name):\n if dataset_name == 'flowers':\n return RandomForestClassifier(n_estimators=100, max_depth=2, random_state=RANDOM_SEED)\n else:\n return RandomForestRegressor(n_estimators=100, max_depth=2, random_state=RANDOM_SEED)\n\n\nif __name__ == \"__main__\":\n\n # Get some sample data from sklearn datasets. Setting return_X_y to True will\n # constrain the output to be a tuple containing only the data and the targets.\n flower_data = datasets.load_iris(return_X_y=True)\n housing_data = datasets.load_boston(return_X_y=True)\n\n # Predict with the two models and the two datasets.\n predictor = RandomForestDemo()\n predictor.make_prediction(flower_data, 'flowers')\n predictor.make_prediction(housing_data, 'housing')\n","sub_path":"random_forest.py","file_name":"random_forest.py","file_ext":"py","file_size_in_byte":3098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"388893071","text":"import simpy\nimport random\nfrom enum import Enum\n\n# перечисление, описывающее все возможные варианты маршрутов\nclass Way(Enum):\n long_way = 'по маршруту горячие блюда -> напитки -> касса'\n middle_way = 'по маршруту холодные закуски -> напитки -> касса'\n short_way = 'по маршруту напитки -> касса'\n\n# счетчик для подсчета студентов\ncounter = 0\n# создание среды моделирования\nenv = simpy.Environment()\n# ресурсы пунктов выдачи\nservices = {Way.long_way: simpy.Resource(env), \n Way.middle_way: simpy.Resource(env), \n Way.short_way: simpy.Resource(env)}\n# ресуры касс\ncashiers = [simpy.Resource(env), simpy.Resource(env)]\n# списки для подсчета средних и максимальных задержек и длинн очередей для кажого случая\nservices_queue_length = {Way.long_way: [], \n Way.middle_way: [], \n Way.short_way: []}\nservices_queue_time = {Way.long_way: [], \n Way.middle_way: [], \n Way.short_way: []}\ncashiers_queue_length = [[], []]\ncashiers_queue_time = {Way.long_way: [[], []], \n Way.middle_way: [[], []], \n Way.short_way: [[], []]}\nall_queue_time = {Way.long_way: [], \n Way.middle_way: [], \n Way.short_way: []}\nall_clients = []\n\n\nclass Student:\n # инициализатор класса клиента\n def __init__(self, way):\n # запоминаем номер клиента для последующего логирования\n global counter\n counter += 1\n self.counter = counter\n # запоминаем маршрут клиента\n self.way = way\n # в инициализаторе сразу определям сколько клиент проведет \n # на выдаче и на кассе продвигаясь по выбранному маршруту\n if way == Way.long_way: # по маршруту горячие блюда -> напитки -> касса\n self.service_time = random.randrange(50, 120) + random.randrange(5, 20)\n self.cashier_time = random.randrange(20, 40) + random.randrange(5, 10)\n elif way == Way.middle_way: # по маршруту холодные закуски -> напитки -> касса\n self.service_time = random.randrange(60, 180) + random.randrange(5, 20)\n self.cashier_time = random.randrange(5, 15) + random.randrange(5, 10)\n elif way == Way.short_way: # по маршруту напитки -> касса\n self.service_time = random.randrange(5, 20)\n self.cashier_time = random.randrange(5, 10)\n\n # занимаем очередь по выбранному маршруту и ожидаем в ней\n def wait_service(self):\n with services[self.way].request() as req:\n services_queue_length[self.way] +=\\\n [1 if not len(services_queue_length[self.way]) else services_queue_length[self.way][-1]+1]\n time = env.now\n print('{0}: wait for {1} service-queue student {2}'\n .format(env.now, self.way, self.counter))\n # yield req\n yield env.timeout(self.service_time)\n services_queue_length[self.way] +=\\\n [services_queue_length[self.way][-1]-1]\n services_queue_time[self.way] += [env.now - time]\n print('{0}: service free student {1} after {2}'\n .format(env.now, self.counter, self.service_time))\n\n # занимаем очередь к наиболее пустой очереди к кассе и ожидаем в ней\n def wait_cashier(self):\n queue_num = 1 if len(cashiers_queue_length[0]) >= len(cashiers_queue_length[1]) else 0\n with cashiers[queue_num].request() as req:\n cashiers_queue_length[queue_num]+=\\\n [1 if not len(cashiers_queue_length[queue_num]) else cashiers_queue_length[queue_num][-1]+1]\n time = env.now\n print('{0}: wait for cashier-queue student {1}'.format(env.now, self.counter))\n # yield req\n yield env.timeout(self.cashier_time)\n cashiers_queue_length[queue_num] += [cashiers_queue_length[queue_num][-1]-1]\n cashiers_queue_time[self.way][queue_num] += [env.now - time]\n print('{0}: cashier free student {1} after {2}'\n .format(env.now, self.counter, self.cashier_time))\n\n # полная обработка одного клиента\n def processes(self):\n global all_clients\n all_clients += [1 if not len(all_clients) else all_clients[-1]+1]\n time = env.now\n yield env.process(self.wait_service())\n yield env.process(self.wait_cashier())\n all_queue_time[self.way] += [env.now - time]\n all_clients += [all_clients[-1]-1]\n\nqueue = []\n\ndef man(env, service, cashier):\n while True:\n global queue, all_clients\n # интервал прибытия между группами\n yield env.timeout(random.expovariate(1/30))\n # моделирование потока по группам\n p = random.random()\n if p <= 0.5: # 1 человек\n students_num = 1\n elif p <= 0.8: # 2 человека\n students_num = 2\n elif p <= 0.9: # 3 человека\n students_num = 3\n else:\n students_num = 4\n print('{0}: New group with {1} student'.format(env.now, students_num))\n # распределение по маршрутам\n for i in range(students_num):\n p = random.random()\n if p <= 0.8: # Way.long_way\n student = Student(Way.long_way)\n elif p <= 0.95: # Way.middle_way\n student = Student(Way.middle_way)\n else: # Way.short_way\n student = Student(Way.short_way)\n env.process(student.processes())\n\nrandom.seed(42)\nenv.process(man(env, services, cashiers))\nenv.run(until=90*60) # 90 минут работы системы\n\nfrom numpy import average, max\n\nprint('Максимальное и среднее число клиентов к пунктам выдачи')\nfor i, j in services_queue_length.items():\n print('Max ', i.value, max(j))\n print('Avg ', i.value, average(j))\nprint('Максимальное и среднее число клиентов к обеим кассам')\nfor i in cashiers_queue_length:\n print('Max ', max(i))\n print('Avg ', average(i))\nprint('Средняя и максимальная задержка в очередях по каждому маршруту')\nfor i, j in services_queue_time.items():\n print('Avg ', i.value, average(j))\n print('Max ', i.value, max(j))\nprint('Средняя и максимальная задержка в очередях к кассам для всех типов клиентов')\nfor i, j in cashiers_queue_time.items():\n for k in range(len(j)):\n print('Avg для клиента ', i.value, 'касса: ', k+1, average(j[k]))\n print('Max для клиента ', i.value, 'касса: ', k+1, max(j[k]))\nprint('Средняя и максимальная задержка в очередях для всех типов клиентов')\nfor i, j in all_queue_time.items():\n print('Avg для клиента ', i.value, average(j))\n print('Max для клиента ', i.value, max(j))\n\nprint('Среднее и максимальное число клиентов во всей системе')\nprint('Avg ', average(all_clients))\nprint('Max ', max(all_clients))","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"109079741","text":"from conans import ConanFile, CMake, tools\n\nclass InstallerConan(ConanFile):\n name = \"Installer\"\n version = \"0.1\"\n settings = {\n \"os\": [\"Windows\", \"Linux\", \"Macos\"], \n \"arch\": [\"x86\", \"x86_64\"],\n \"compiler\" : [\"gcc\", \"Visual Studio\", \"apple-clang\"],\n \"build_type\": [\"Debug\", \"Release\"]\n }\n generators = \"cmake\", \"visual_studio\"\n exports_sources = \"*\"\n\n def generateInstaller(self):\n if self.settings.os == \"Windows\":\n self.run(\"%s && %s\" % (tools.vcvars_command(self.settings), tools.build_sln_command(self.settings, \"PACKAGE.vcxproj\")))\n else:\n pass#... \n\n def build(self):\n cmake = CMake(self)\n cmake.configure()\n cmake.build()\n self.generateInstaller()\n\n def package(self):\n self.copy(\"*.zip\") # final artifact\n\n def deploy(self):\n self.copy(\"*.zip\") # final artifact\n\n\n","sub_path":"installer/conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"299157719","text":"import os\nimport csv\n\ncsv_filename = 'contacts.csv'\n# def clear_screen():\n# os.system('cls' if os.name == 'nt' else 'clear')\n\ndef show_menu():\n # clear_screen()\n print(\"=== APLIKASI KONTAK ===\")\n print(\"[1] Lihat Daftar Kontak\")\n print(\"[2] Buat Kontak Baru\")\n print(\"[3] Edit Kontak\")\n print(\"[4] Hapus Kontak\")\n print(\"[5] Cari Kontak\")\n print(\"[0] Exit\")\n print(\"------------------------\")\n selected_menu = input(\"Pilih menu => \")\n\n if (selected_menu == \"1\"):\n show_contact()\n elif(selected_menu == \"2\"):\n create_contact()\n elif(selected_menu == \"3\"):\n edit_contact()\n elif(selected_menu == \"4\"):\n delete_contact()\n elif(selected_menu == \"5\"):\n search_contact()\n elif(selected_menu == \"0\"):\n exit()\n else:\n print(\"Kamu memilih menu yang salah!\")\n back_to_menu()\n\ndef back_to_menu():\n print(\"\\n\")\n input(\"tekan enter untuk kembali ... \")\n show_menu()\n\ndef show_contact():\n # clear_screen()\n contact = []\n with open(csv_filename) as csv_file:\n csv.reader = csv.reader(csv_filename, delimiter = ',')\n for row in csv.reader:\n contact.append(row)\n if (len(contact) > 0):\n labels = contact.pop(0)\n print(f\"{labels[0]} \\t {labels[1]} \\t\\t {labels[2]}\")\n print(\"-\" * 34)\n for data in contact:\n print(f'{data[0]} \\t {data[1]} \\t {data[2]}')\n else:\n print(\"Tidak ada data!\")\n back_to_menu()\n\ndef create_contact():\n # clear_screen()\n with open(csv_filename, mode='a') as csv_file:\n fieldnames = ['NO','NAMA','TELEPON']\n writer = csv.DictWriter(csv_file, fieldnames=fieldnames)\n\n no = input(\"No urut: \")\n nama = input(\"Nama lengkap: \")\n telepon = input(\"No. Telepon: \")\n writer.writerow({'NO': no, 'NAMA': nama, 'TELEPON': telepon})\n print(\"Berhasil disimpan!\")\n back_to_menu()\n\ndef search_contact():\n # clear_screen()\n contacts = []\n\n with open(csv_filename, mode=\"r\") as csv_file:\n csv_reader = csv.DictReader(csv_file)\n for row in csv_reader:\n contacts.append(row)\n\n no = input(\"Cari berdasrakan nomer urut => \")\n\n data_found = []\n\n # mencari contact\n indeks = 0\n for data in contacts:\n if (data['NO'] == no):\n data_found = contacts[indeks]\n\n indeks = indeks + 1\n\n if len(data_found) > 0:\n print(\"DATA DITEMUKAN: \")\n print(f\"Nama: {data_found['NAMA']}\")\n print(f\"Telepon: {data_found['TELEPON']}\")\n else:\n print(\"Tidak ada data ditemukan\")\n back_to_menu()\n\ndef edit_contact():\n # clear_screen()\n contacts = []\n\n with open(csv_filename, mode=\"r\") as csv_file:\n csv_reader = csv.DictReader(csv_filename)\n for row in csv_reader:\n contacts.append(row)\n\n print(\"NO \\t NAMA \\t\\t TELEPON\")\n print(\"-\" * 32)\n\n for data in contacts:\n print(f\"{data['NO']} \\t {data['NAMA']} \\t {data['TELEPON']}\")\n\n print(\"-----------------------\")\n no = input(\"Pilih nomer kontak> \")\n nama = input(\"nama baru: \")\n telepon = input(\"nomer telepon baru: \")\n\n # mencari contact dan mengubah datanya\n # dengan data yang baru\n indeks = 0\n for data in contacts:\n if (data['NO'] == no):\n contacts[indeks]['NAMA'] = nama\n contacts[indeks]['TELEPON'] = telepon\n indeks = indeks + 1\n\n # Menulis data baru ke file CSV (tulis ulang)\n with open(csv_filename, mode=\"w\") as csv_file:\n fieldnames = ['NO', 'NAMA', 'TELEPON']\n writer = csv.DictWriter(csv_file, fieldnames=fieldnames)\n writer.writeheader()\n for new_data in contacts:\n writer.writerow({'NO': new_data['NO'], 'NAMA': new_data['NAMA'], 'TELEPON': new_data['TELEPON']})\n\n back_to_menu()\n\ndef delete_contact():\n # clear_screen()\n contacts = []\n\n with open(csv_filename, mode=\"r\") as csv_file:\n csv_reader = csv.DictReader(csv_file)\n for row in csv_reader:\n contacts.append(row)\n\n print(\"NO \\t NAMA \\t\\t TELEPON\")\n print(\"-\" * 32)\n\n for data in contacts:\n print(f\"{data['NO']} \\t {data['NAMA']} \\t {data['TELEPON']}\")\n\n print(\"-----------------------\")\n no = input(\"Hapus nomer> \")\n\n # mencari contact dan mengubah datanya\n # dengan data yang baru\n indeks = 0\n for data in contacts:\n if (data['NO'] == no):\n contacts.remove(contacts[indeks])\n indeks = indeks + 1\n\n # Menulis data baru ke file CSV (tulis ulang)\n with open(csv_filename, mode=\"w\") as csv_file:\n fieldnames = ['NO', 'NAMA', 'TELEPON']\n writer = csv.DictWriter(csv_file, fieldnames=fieldnames)\n writer.writeheader()\n for new_data in contacts:\n writer.writerow({'NO': new_data['NO'], 'NAMA': new_data['NAMA'], 'TELEPON': new_data['TELEPON']})\n\n print(\"Data sudah terhapus\")\n back_to_menu()\n\nif __name__ == '__main__':\n while True:\n show_menu()","sub_path":"petanikode/files/AplikasiCRUDSPythonCSV/App.py","file_name":"App.py","file_ext":"py","file_size_in_byte":5006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"221854215","text":"from numba import jit\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.colors import LinearSegmentedColormap\r\nfrom datetime import datetime\r\n\r\n\r\n@jit\r\ndef mandelbrot(z, max_iterations=1000):\r\n \"\"\"\r\n Function that returns either how many steps it took before the value of the quadratic polynomial x^2+c exceeds\r\n 2, or returns the max_iterations number, defaults to 1000\r\n\r\n Arguments:\r\n z (complex number): Seed for the iteration, start value for c\r\n max_iterations (int, optional): How many times the function should loop before it exits. Defaults to 1000\r\n\r\n Returns:\r\n int < max_iterations: How many steps it took for the value of the quadratic polynomial to exceed 2\r\n int == max_iterations: Seed is presumably in Mandelbrot Set\r\n \"\"\"\r\n c = z\r\n for i in range(max_iterations):\r\n if abs(z) > 2:\r\n return i\r\n z = z * z + c\r\n return max_iterations\r\n\r\n\r\n@jit\r\ndef draw_mandelbrot_set(xmin, xmax, ymin, ymax, width, height, max_iterations):\r\n \"\"\"\r\n Function that generates a matrix, feeding x and y to the mandelbrot function as a complex number x + yj, and stores\r\n the return values for each coordinate\r\n\r\n Arguments:\r\n xmin (float): Lowest value for x, the real part of the complex number\r\n xmax (float): Highest value for x, the real part of the complex number\r\n ymin (float): Lowest value for y, the imaginary part of the complex number\r\n ymax (float): Highest value for y, the imaginary part of the complex number\r\n width (int): The width of the matrix\r\n height (int): The height of the matrix\r\n max_iterations (int): Number of times the mandelbrot function should iterate\r\n\r\n Returns:\r\n temp_matrix (2d Array): The result of the calculations for each complex number x + yj\r\n \"\"\"\r\n row = np.linspace(xmin, xmax, width)\r\n col = np.linspace(ymin, ymax, height)\r\n temp_matrix = np.empty((width, height))\r\n for i in range(width):\r\n for j in range(height):\r\n temp_matrix[i, j] = mandelbrot(row[i] + 1j*col[j], max_iterations)\r\n return temp_matrix\r\n\r\n\r\ndef main(xmin, xmax, ymin, ymax, width, height, image_name=\"numba_image\", max_iterations=1000):\r\n \"\"\"\r\n The function that generates a colourmap, calculates the mandelbrot set with draw_mandelbrot_set and stores the\r\n \"\"\"\r\n\r\n startTime = datetime.now()\r\n print(\"Program started\")\r\n\r\n # rgb values are divided by 255 to become values between 0 and 1\r\n colours = [(0.1411764705882353, 0.1607843137254902, 0.1803921568627451), # grey - rgb(36, 41, 46)\r\n (0.11372549019607843, 0.7254901960784313, 0.32941176470588235)] # green - rgb(29, 185, 84)\r\n custom_colourmap = LinearSegmentedColormap.from_list(\"gray_to_green\", colours, 1000)\r\n mandelbrot_matrix = draw_mandelbrot_set(xmin, xmax, ymin, ymax, width, height, max_iterations)\r\n extent = [xmin, xmax, ymin, ymax]\r\n\r\n plt.imshow(mandelbrot_matrix, cmap=custom_colourmap, extent=extent)\r\n plt.savefig(image_name + \".png\")\r\n print(datetime.now() - startTime)\r\n\r\n\r\n# Runs if mandelbrot_1.py is called directly from commandline\r\nif __name__ == \"__main__\":\r\n mandelbrot_fast_parameters = [-2.0, 0.5, -1.25, 1.25, 1000, 1000, \"numba_image\", 80]\r\n mandelbrot_slow_parameters = [-0.74877, -0.74872, 0.06505, 0.06510, 1000, 1000, \"numba_image\", 1000]\r\n main(*mandelbrot_fast_parameters)\r\n # main(*mandelbrot_slow_parameters)\r\n","sub_path":"assignment4/mandelbrot_3.py","file_name":"mandelbrot_3.py","file_ext":"py","file_size_in_byte":3494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"523884597","text":"def permute(single, sequence):\n perms = []\n for element in sequence:\n chars = [char for char in element]\n for i in range(len(chars) + 1):\n tmp = chars[:]\n tmp.insert(i, single)\n perms.append(\"\".join(tmp))\n \n return perms\n\ndef permutations(sequence):\n length = len(sequence)\n if length == 1:\n return [sequence]\n else:\n return sorted(permute(sequence[0], permutations(sequence[1:])))\n\nprint(permutations('0123456789')[1000000-1])\n","sub_path":"python/problem-24.py","file_name":"problem-24.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"266854011","text":"from invoke import task\n\nfrom chops.core import ChopsApplication\n\n\ndef tasks(app: ChopsApplication):\n @task\n def example(ctx):\n \"\"\"Example local task.\"\"\"\n ctx.info('This is an example local task for the project \"{}\".'.format(app.config['project_name']))\n\n ctx.info('Available tasks:')\n ctx.pp.pprint(app.get_tasks())\n\n ctx.info('Chops version:')\n app.logger.warn('Executing chops version task...')\n app.run_task('version', ctx)\n\n return [example]\n","sub_path":"examples/web_app/chops_tasks.py","file_name":"chops_tasks.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"17910976","text":"import datetime\nimport functools\n\nfrom profiling.models import Profiling\n\n\n# 记录各视图函数运行的时间\ndef profile(threshold=300, type_='api'):\n def decorator(func):\n @functools.wraps(func)\n def wrapper(request, *args, **kwargs):\n start = datetime.datetime.now().timestamp()\n result = func(request, *args, **kwargs)\n time_used = (datetime.datetime.now().timestamp() - start) * 1000\n time_used = round(time_used, 4)\n if time_used > threshold:\n\n # write to db start\n if request.method == 'GET':\n args = str(request.GET)\n elif request.method == 'POST' and request.POST:\n args = str(request.POST)\n else:\n args = str(request.body)\n Profiling.objects.create(\n name='{}.{}'.format(func.__module__, func.__name__),\n type=type_,\n time=str(time_used),\n args=args\n )\n # write to db end\n return result\n\n return wrapper\n\n return decorator\n","sub_path":"backend/profiling/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"112186916","text":"import argparse\nimport time\nimport sys\nimport os\n\nfrom global_config import *\nfrom torch.autograd import Variable\nfrom torch.utils.data import DataLoader\nfrom model.sentence_localizer import SentenceLocalizer\nfrom dataset import ANetDataFull, ANetDataSample, collate_fn\nfrom utils.model_saver import ModelSaver\nfrom utils.helper_function import *\n\ndef train(model, data_loader, params, logger, step, optimizer):\n model.train()\n\n _start_time = time.time()\n accumulate_loss = 0\n accumulate_iou = 0\n\n logger.info('learning rate:' + '*' * 86)\n logger.info('training on optimizing localizing')\n for param_group in optimizer.param_groups:\n logger.info(' ' * 7 + '|%s: %s,', param_group['name'], param_group['lr'])\n logger.info('*' * 100)\n for idx, batch_data in enumerate(data_loader):\n batch_time = time.time()\n\n # data pre processing\n video_feat, video_len, video_mask, sent_feat, sent_len, sent_mask, sent_gather_idx, ts_time, _, _ = batch_data\n video_feat = Variable(video_feat.cuda())\n video_len = Variable(video_len.cuda())\n video_mask = Variable(video_mask.cuda())\n sent_feat = Variable(sent_feat.cuda())\n sent_len = Variable(sent_len.cuda())\n sent_mask = Variable(sent_mask.cuda())\n sent_gather_idx = Variable(sent_gather_idx.cuda())\n ts_time = Variable(ts_time.cuda())\n\n # forward\n confidence_logit, regressing_result, pred_time = model.forward(video_feat, video_len, video_mask,\n sent_feat, sent_len, sent_mask, sent_gather_idx)\n\n # backward\n loss = model.build_loss(confidence_logit, regressing_result, ts_time, video_len[:, 1].contiguous(), params['lambda'])\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n # statics\n miou = model.compute_mean_iou(pred_time.data, ts_time.data)\n accumulate_loss += loss.cpu().data[0]\n accumulate_iou += miou\n if params['batch_log_interval'] != -1 and idx % params['batch_log_interval'] == 0:\n logger.info('train: epoch[%05d], batch[%04d/%04d], elapsed time=%0.4fs, loss: %06.6f, miou: %06.6f',\n step, idx, len(data_loader), time.time() - batch_time, loss.cpu().data[0], miou)\n logger.info('epoch [%05d]: elapsed time:%0.4fs, avg loss: %06.6f, miou: %06.6f',\n step, time.time() - _start_time, accumulate_loss / len(data_loader), accumulate_iou / len(data_loader))\n logger.info('*'*80)\n\n\ndef eval(model, data_loader, params, logger, step, saver):\n model.eval()\n\n _start_time = time.time()\n accumulate_loss = 0\n accumulate_iou = 0\n pred_dict = {'version': 'V0',\n 'results':{},\n 'external_data':{\n 'used': True,\n 'details': 'provided C3D feature'\n },\n 'params': params}\n\n logger.info('testing:' + '*' * 86)\n\n for idx, batch_data in enumerate(data_loader):\n batch_time = time.time()\n\n # data pre processing\n video_feat, video_len, video_mask, sent_feat, sent_len, sent_mask, sent_gather_idx, ts_time, _, key = batch_data\n video_feat = Variable(video_feat.cuda())\n video_len = Variable(video_len.cuda())\n video_mask = Variable(video_mask.cuda())\n sent_feat = Variable(sent_feat.cuda())\n sent_len = Variable(sent_len.cuda())\n sent_mask = Variable(sent_mask.cuda())\n sent_gather_idx = Variable(sent_gather_idx.cuda())\n ts_time = Variable(ts_time.cuda())\n # forward\n confidence_logit, regressing_result, pred_time = model.forward(video_feat, video_len, video_mask,\n sent_feat, sent_len, sent_mask, sent_gather_idx)\n\n # statics\n loss = model.build_loss(confidence_logit, regressing_result, ts_time,\n video_len[:, 1].contiguous().index_select(dim=0, index=sent_gather_idx), params['lambda'])\n miou = model.compute_mean_iou(pred_time.data, ts_time.data)\n accumulate_loss += loss.cpu().data[0]\n accumulate_iou += miou\n if params['batch_log_interval'] != -1 and idx % params['batch_log_interval'] == 0:\n logger.info('test: epoch[%05d], batch[%04d/%04d], elapsed time=%0.4fs, loss: %06.6f, miou: %06.6f',\n step, idx, len(data_loader), time.time() - batch_time, loss.cpu().data[0], miou)\n\n # submits\n pred_time = pred_time.cpu().data.numpy()\n sent_feat = sent_feat.cpu().data.numpy()\n ts_time = ts_time.cpu().data.numpy()\n for idx in range(len(sent_gather_idx)):\n video_key = key[sent_gather_idx.cpu().data[idx]]\n if video_key not in pred_dict['results']:\n pred_dict['results'][video_key] = list()\n pred_dict['results'][video_key].append({\n 'sentence': data_loader.dataset.rtranslate(sent_feat[idx]),\n 'timestamp': pred_time[idx].tolist(),\n 'gt_sentence': data_loader.dataset.rtranslate(sent_feat[idx]),\n 'gt_timestamp': ts_time[idx].tolist()\n })\n\n saver.save_submits(pred_dict, step)\n logger.info('epoch [%05d]: elapsed time:%0.4fs, avg loss: %06.6f, miou: %06.6f',\n step, time.time() - _start_time, accumulate_loss / len(data_loader), accumulate_iou / len(data_loader))\n logger.info('*'*80)\n\n\ndef construct_model(params, saver, logger):\n if params['model'] != \"SentenceLocalizer\":\n raise Exception('Model Not Implemented')\n\n # def __init__(self, hidden_dim, rnn_layer, rnn_cell, rnn_dropout, bidirectional, attention_type, scale,\n # sent_vocab_size, sent_embedding_dim, video_feature_dim, fc_dropout, anchor_list, feature_mixer_type,\n # video_use_residual, sent_use_residual):\n\n model = SentenceLocalizer(params['hidden_dim'], params['rnn_layer'], params['rnn_cell'], params['rnn_dropout'],\n params['bidirectional'], params['attention_type'], params['regressor_scale'],\n params['vocab_size'], params['sent_embedding_dim'], params['video_feature_dim'],\n params['fc_dropout'], params['anchor_list'], params['feature_mixer_type'],\n params['video_use_residual'], params['sent_use_residual'])\n\n logger.info('*' * 100)\n sys.stdout.flush()\n print(model)\n sys.stdout.flush()\n logger.info('*' * 100)\n if params['checkpoint'] is not None:\n logger.warn('use checkpoint: %s', params['checkpoint'])\n state_dict, params_ = saver.load_model(params['checkpoint'])\n param_refine(params, params_)\n model.load_state_dict(state_dict)\n else:\n pass\n # model_initialize(model, logger)\n return model\n\ndef main(params):\n params['anchor_list'] = ANCHOR_LIST\n logger = logging.getLogger(params['alias'])\n set_device(logger, params['gpu_id'])\n saver = ModelSaver(params, os.path.abspath('./third_party/densevid_eval'))\n model = construct_model(params, saver, logger)\n\n model = model.cuda()\n\n training_set = ANetDataSample(params['train_data'], params['feature_path'],\n params['translator_path'], params['video_sample_rate'], logger)\n val_set = ANetDataFull(params['val_data'], params['feature_path'],\n params['translator_path'], params['video_sample_rate'], logger)\n train_loader = DataLoader(training_set, batch_size=params['batch_size'], shuffle=True,\n num_workers=params['num_workers'], collate_fn=collate_fn, drop_last=True)\n val_loader = DataLoader(val_set, batch_size=params['batch_size']/3, shuffle=True,\n num_workers=params['num_workers'], collate_fn=collate_fn, drop_last=True)\n\n optimizer = torch.optim.SGD(model.get_parameter_group(params),\n lr=params['lr'], weight_decay=params['weight_decay'], momentum=params['momentum'])\n\n lr_scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer,\n milestones=params['lr_step'], gamma=params[\"lr_decay_rate\"])\n eval(model, val_loader, params, logger, 0, saver)\n exit()\n for step in range(params['training_epoch']):\n lr_scheduler.step()\n train(model, train_loader, params, logger, step, optimizer)\n\n # validation and saving\n if step % params['test_interval'] == 0:\n eval(model, val_loader, params, logger, step, saver)\n if step % params['save_model_interval'] == 0 and step != 0:\n saver.save_model(model,step, {'step': step})\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n\n # datasets\n parser.add_argument('--train_data', type=str, default='./data/densecap/train.json',\n help='training data path')\n parser.add_argument('--val_data', type=str, default='./data/densecap/val_1.json',\n help='validation data path')\n parser.add_argument('--feature_path', type=str, default='./data/anet_v1.3.c3d.hdf5',\n help='feature path')\n parser.add_argument('--vocab_size', type=int, default=6000,\n help='vocabulary size')\n parser.add_argument('--translator_path', type=str, default='./data/translator6000.pkl',\n help='translator path')\n\n # model setting\n parser.add_argument('--model', type=str, default=\"SentenceLocalizer\",\n help='the model to be used')\n parser.add_argument('--checkpoint', type=str, default=None,\n help='model checkpoint')\n parser.add_argument('--save_model_interval', type=int, default=1,\n help='save the model parameters every a certain step')\n\n # network setting\n parser.add_argument('--sent_embedding_dim', type=int, default=512)\n parser.add_argument('--video_feature_dim', type=int, default=500)\n parser.add_argument('--hidden_dim', type=int, default=512,\n help='hidden dimension of rnn')\n parser.add_argument('--rnn_cell', type=str, default='gru',\n help='rnn cell used in the model')\n parser.add_argument('--bidirectional', type=bool, default=False,\n help='Whether to use bidirectional RNN')\n parser.add_argument('--rnn_layer', type=int, default=2,\n help='layers number of rnn')\n parser.add_argument('--fc_dropout', type=float, default=0.3,\n help='dropout')\n parser.add_argument('--rnn_dropout', type=float, default=0.3,\n help='rnn_dropout')\n parser.add_argument('--video_sample_rate', type=int, default=2,\n help='video sample rate')\n parser.add_argument('--attention_type', type=str, default='type0',\n help='attention module used in encoding')\n parser.add_argument('--regressor_scale', type=float, default=0.1,\n help='regressor scale, used to normalize the regressor head')\n parser.add_argument('--feature_mixer_type', type=str, default='type0',\n help='multi-model feature fusion function')\n parser.add_argument('--video_use_residual', type=bool, default=True)\n parser.add_argument('--sent_use_residual', type=bool, default=False)\n # training setting\n parser.add_argument('--lambda', type=float, default=0.1)\n parser.add_argument('--runs', type=str, default='runs',\n help='folder where models are saved')\n parser.add_argument('--gpu_id', type=int, default=-1,\n help='the id of gup used to train the model, -1 means automatically choose the best one')\n parser.add_argument('--optim_method', type=str, default='SGD',\n help='masks for caption loss')\n parser.add_argument('--caption_loss_mask', type=float, default=1,\n help='masks for caption loss')\n parser.add_argument('--reconstruction_loss_mask', type=float, default=1,\n help='masks for caption loss')\n parser.add_argument('--training_epoch', type=int, default=100,\n help='training epochs in total')\n parser.add_argument('--batch_size', type=int, default=96,\n help='batch size used to train the model')\n parser.add_argument('--grad_clip', type=float, default=5,\n help='gradient clip threshold(not used)')\n parser.add_argument('--lr', type=float, default=1e-2,\n help='learning rate used to train the model')\n parser.add_argument('--lr_decay_step', type=int, default=5,\n help='decay learning rate after a certain epochs, UNUSED')\n parser.add_argument('--lr_decay_rate', type=float, default=0.1,\n help='decay learning rate by this value every decay step')\n parser.add_argument('--momentum', type=float, default=0.8,\n help='momentum used in the process of learning')\n parser.add_argument('--weight_decay', type=float, default=1e-4,\n help='weight decay, i.e. weight normalization')\n parser.add_argument('--num_workers', type=int, default=1,\n help='used in data loader(only 1 is supported because of bugs in h5py)')\n parser.add_argument('--batch_log_interval', type=int, default=10,\n help='log interval')\n parser.add_argument('--batch_log_interval_test', type=int, default=20,\n help='log interval')\n parser.add_argument('--test_interval', type=int, default=1,\n help='test interval between training')\n parser.add_argument('--switch_optim_interval', type=int, default=1,\n help='switch the optimizing target every interval epoch')\n parser.add_argument('--alias', type=str, default='test',\n help='alias used in model/checkpoint saver')\n parser.add_argument('--soft_mask_function_scale', type=float, default=1,\n help='alias used in model/checkpoint saver')\n parser.add_argument('--pretrain_epoch', type=int, default=5,\n help='pretrain with fake01')\n parser.add_argument('--lr_step', type=int, nargs='+', default=[5, 20, 50],\n help='lr_steps used to decay the learning_rate')\n params = parser.parse_args()\n params = vars(params)\n\n main(params)\n print('training finished successfully!')\n\n","sub_path":"eval_script/evaluate_sl_gd.py","file_name":"evaluate_sl_gd.py","file_ext":"py","file_size_in_byte":14714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"504700577","text":"import ERP_org as org\r\norg = {} # empty dictionary\r\n\r\n\r\ndef my_decorator(func):\r\n\r\n def wrap_func():\r\n print('*'*30)\r\n func()\r\n print('*'*30)\r\n\r\n return wrap_func\r\n\r\n\r\n@my_decorator\r\ndef create_org():\r\n org_name = input(\"Enter organisation name : \")\r\n if org_name not in org.keys():\r\n org[org_name] = {}\r\n print(f\"{org_name} organisation created successfully \")\r\n\r\n else:\r\n print(f\"{org_name} organisation already available on system !\")\r\n\r\n\r\n@my_decorator\r\ndef modify_org_name():\r\n org_name = input(\"Enter organisation name : \")\r\n if org_name not in org.keys():\r\n print(f\"{org_name} organisation not available on system !\")\r\n else:\r\n temp = org[org_name]\r\n del org[org_name]\r\n org_name = input(\"Enter new organisation name : \")\r\n org[org_name] = temp\r\n print(f'{org_name} organisation name updated successfully ')\r\n\r\n\r\n@my_decorator\r\ndef show_org():\r\n org_name = input(\"Enter organisation name : \")\r\n if org_name not in org.keys():\r\n print(f\"{org_name} organisation not available on the system !\")\r\n else:\r\n print(org)\r\n # for k, v in org[org_name].values():\r\n # name_str = \"\"\r\n # for i in v:\r\n # name_str = name_str + \"|\" + i + emp[i]['name']\r\n # print(f'{i} | {name_str}')\r\n\r\n\r\n@my_decorator\r\ndef manage_org_menu():\r\n print(\"1.Add organistion\")\r\n print(\"2.modify organistaion\")\r\n print(\"3.show organisation\")\r\n print(\"4.exit\")\r\n","sub_path":"Ananthu/Aug17Python/ERP_proj_using_modules/ERP_org.py","file_name":"ERP_org.py","file_ext":"py","file_size_in_byte":1530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"12006734","text":"# -*- coding: utf-8 -*-\nfrom django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('payment/index/', views.index), # 给templates返回数据,利用django模板进行测试,正常情况下由前端发起请求,参考接口get_pay_url即可\n path('payment/pay_url/', views.get_pay_url), # 获取支付宝支付链接\n path('payment/get_result/', views.pay_result), # 支付宝处理完成后同步回调通知\n path('payment/update_order/', views.update_order), # 支付宝处理完成后支付宝服务器异步回调通知\n path('payment/cancel_order/', views.cancel_order), # 取消订单视图\n]\n","sub_path":"apps/payment/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":"57"} +{"seq_id":"173128568","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nfrom __future__ import absolute_import\n\nimport math\nfrom PIL import Image\n\ndef ramp(from_val, to_val, percent):\n f = percent / 100.0\n return int(round(from_val * (1 - f) + to_val * f))\n\n\nimg_from = Image.open('./art/clark-kent.png')\nimg_to = Image.open('./art/superman.png')\n\nassert img_from.size == img_to.size\nwidth, height = size = img_from.size\n\nfor frame in range(0, 100):\n print('Generando frame {}'.format(frame), end=' ')\n output = Image.new('RGB', size)\n for y in range(0, height):\n for x in range(0, width):\n pos = (x, y)\n color_from = img_from.getpixel(pos)\n color_to = img_to.getpixel(pos)\n percent = frame * 1\n red = ramp(color_from[0], color_to[0], percent)\n green = ramp(color_from[1], color_to[1], percent)\n blue = ramp(color_from[2], color_to[2], percent)\n output.putpixel(pos, (red, green, blue))\n output.save('movie/frame_{:04d}.png'.format(frame), 'PNG')\n print('[OK]')\n","sub_path":"make-trans.py","file_name":"make-trans.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"76328791","text":"\n\nfrom xai.brain.wordbase.nouns._egret import _EGRET\n\n#calss header\nclass _EGRETS(_EGRET, ):\n\tdef __init__(self,): \n\t\t_EGRET.__init__(self)\n\t\tself.name = \"EGRETS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"egret\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_egrets.py","file_name":"_egrets.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"407973970","text":"import cx_Oracle\nimport pandas as pd\nimport datetime as dt\nfrom typing import List, Tuple\n\n\nclass ForecastedDemandFetchForRevisionRepo():\n \"\"\"block wise forecasted demand fetch repository\n \"\"\"\n\n def __init__(self, con_string):\n \"\"\"initialize connection string\n Args:\n con_string ([type]): connection string \n \"\"\"\n self.connString = con_string\n \n def toListOfTuple(self,df:pd.core.frame.DataFrame) -> List[Tuple]:\n \"\"\"convert forecasted BLOCKWISE demand data to list of tuples[(timestamp,entityTag,demandValue),]\n Args:\n df (pd.core.frame.DataFrame): forecasted block wise demand dataframe\n Returns:\n List[Tuple]: list of tuple of forecasted blockwise demand data [(timestamp,entityTag,demandValue),]\n \"\"\" \n demandData =[]\n for ind in df.index:\n demandTuple = (str(df['TIME_STAMP'][ind]), df['ENTITY_TAG'][ind], float(df['FORECASTED_DEMAND_VALUE'][ind]) )\n demandData.append(demandTuple)\n return demandData\n\n\n def fetchForecastedDemandForRevision(self, start_Time: dt.datetime, end_Time: dt.datetime, entityTag:str, avgBiasError: float) -> List[Tuple]:\n \"\"\"fetch forecasted demand from B+3 blocks, applying DA R0 forecast*(1+avg forecast bias error), and return list of tuple [(timestamp,entityTag,demandValue),]\n\n Args:\n startTime (dt.datetime): start time\n endTime (dt.datetime): end time\n entityTag (str): entity tag\n avgBiasError(float): calculated avg bias error\n\n Returns:\n List[Tuple]: list of tuple [(timestamp,entityTag,demandValue),]\n \"\"\"\n # startTime = b+3 block \n startTime = end_Time + dt.timedelta(minutes= 46)\n\n #endTime will today last block if not in 22:30 - 22:45 revision block else tommorows last block \n currdate = dt.datetime.now().replace(hour =0 ,minute =0,second=0, microsecond=0)\n # currdate = dt.datetime.strptime(\"2021-01-29 12:10:40\", '%Y-%m-%d %H:%M:%S').replace(hour =0 ,minute =0,second=0, microsecond=0)\n startExceptionTime = currdate + dt.timedelta(hours = 22, minutes= 30) \n endExceptionTime = currdate + dt.timedelta(hours = 22, minutes= 45) \n\n if startExceptionTime <= dt.datetime.now() < endExceptionTime:\n # if startExceptionTime <= dt.datetime.strptime(\"2021-01-29 12:10:40\", '%Y-%m-%d %H:%M:%S') < endExceptionTime:\n endTime = currdate + dt.timedelta(days=1, hours=23, minutes=59)\n fetch_sql = \"SELECT time_stamp, entity_tag, forecasted_demand_value FROM dfm4_forecast_revision_store WHERE time_stamp BETWEEN TO_DATE(:start_time,'YYYY-MM-DD HH24:MI:SS') and TO_DATE(:end_time,'YYYY-MM-DD HH24:MI:SS') and entity_tag =:entity and revision_no='R0A' ORDER BY time_stamp\"\n\n else:\n endTime = currdate + dt.timedelta(hours=23, minutes=59)\n fetch_sql = \"SELECT time_stamp, entity_tag, forecasted_demand_value FROM dfm4_dayahead_demand_forecast WHERE time_stamp BETWEEN TO_DATE(:start_time,'YYYY-MM-DD HH24:MI:SS') and TO_DATE(:end_time,'YYYY-MM-DD HH24:MI:SS') and entity_tag =:entity ORDER BY time_stamp\"\n\n try: \n connection = cx_Oracle.connect(self.connString)\n\n except Exception as err:\n print('error while creating a connection', err)\n else:\n try:\n cur = connection.cursor()\n cur.execute(\"ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS' \")\n forecastedDemandDf = pd.read_sql(fetch_sql, params={\n 'start_time': startTime, 'end_time': endTime, 'entity':entityTag}, con=connection)\n\n except Exception as err:\n print('error while creating a cursor', err)\n else:\n connection.commit()\n finally:\n cur.close()\n connection.close()\n\n #applying DA R0 forecast*(1+avg forecast bias error)\n \n forecastedDemandDf['FORECASTED_DEMAND_VALUE'] = forecastedDemandDf['FORECASTED_DEMAND_VALUE']*(1+avgBiasError)\n \n data : List[Tuple] = self.toListOfTuple(forecastedDemandDf)\n return data","sub_path":"src/intraDayRevision/forecastedDemandFetchForRevision.py","file_name":"forecastedDemandFetchForRevision.py","file_ext":"py","file_size_in_byte":4223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"28834742","text":"import pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ndata = pd.read_csv('..\\data_for_public_release\\data_for_public_release\\survey_data.csv')\r\n\r\n\r\n\r\nmen = data[(data.STATUS == 'Complete') & (data.GENDER == 'Woman')]['FORMAL.EDUCATION']\r\n\r\nparents_of_men = data[(data.STATUS == 'Complete') & (data.GENDER == 'Woman')]['PARENTS.FORMAL.EDUCATION']\r\n\r\nmeans1 = ( men[men == 'Less than secondary (high) school'].count(), men[men == 'Secondary (high) school graduate or equivalent'].count(), men[men == 'Some college, no degree'].count(), men[men == 'Vocational/trade program or apprenticeship'].count(), men[men == \"Bachelor's degree\"].count(), men[men == \"Master's degree\"].count(), men[men == \"Doctorate (Ph.D.) or other advanced degree (e.g. M.D., J.D.)\"].count())\r\n\r\nmeans2 = (parents_of_men[parents_of_men == 'Less than secondary (high) school'].count(), parents_of_men[parents_of_men == 'Secondary (high) school graduate or equivalent'].count(), parents_of_men[parents_of_men == 'Some college, no degree'].count(), parents_of_men[parents_of_men == 'Vocational/trade program or apprenticeship'].count(), parents_of_men[parents_of_men == \"Bachelor's degree\"].count(), parents_of_men[parents_of_men == \"Master's degree\"].count(), parents_of_men[parents_of_men == \"Doctorate (Ph.D.) or other advanced degree (e.g. M.D., J.D.)\"].count())\r\n\r\nind = np.arange(len(means1))\r\n\r\nwidth = .35\r\n\r\nfig, axes = plt.subplots()\r\n\r\naxes.bar(ind - width/2, height = means2, width = width, color = 'purple', label = \"Women Surveyors' Parents\")\r\n\r\naxes.bar(ind + width/2, height = means1, width = width, color = 'IndianRed', label = 'Women Surveyors')\r\n\r\naxes.set_ylabel('Surveyors')\r\n\r\naxes.set_xticks(ind)\r\n\r\naxes.set_xticklabels(('Secondary school','High school','College','Vocational','BS','MS','PhD'))\r\n\r\naxes.set_title('Education Distribution')\r\n\r\naxes.legend()\r\n\r\nplt.show()","sub_path":"OSS_survey_v10.py","file_name":"OSS_survey_v10.py","file_ext":"py","file_size_in_byte":1883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"594878521","text":"'''\nCreated on Mar 30, 2019\n\n@author: Jiaming\n'''\nimport tkinter as tk\nfrom PIL import Image\nfrom WordCard import WordCard\nimport numpy as np\nfrom pynput.mouse import Controller, Button\nfrom trained_model import CNN\nimport threading\n\n\n\n\n\n \ndef to_drawing_board(frame):\n object_list = {0:\"Apple\", 1:\"Banana\", 2:\"Bus\", 3:\"Fish\"}\n for widget in frame.winfo_children():\n widget.destroy()\n lines_info = []\n frame_canvas = tk.Frame(frame)\n frame_buttons = tk.Frame(frame)\n\n \n\n def draw_line(event):\n \n canvas.create_oval(event.x-LINE_LENTH, event.y-LINE_LENTH, event.x+LINE_LENTH, event.y+LINE_LENTH, fill=\"black\")\n if event.x<400 and event.x>=0 and event.y<400 and event.y>=0:\n \n lines_info.append((event.x, event.y))\n \n \n \n \n def clear_canvas(canvas):\n canvas.delete(\"all\")\n lines_info.clear()\n \n \n LINE_LENTH = 2\n exp = None\n pre = None\n def creat_label(): \n obj_index = np.random.randint(0, 4)\n obj = object_list[obj_index]\n \n text = \"\"\"\n Could You Draw a(an) %s \n \"\"\"%(obj)\n global exp\n exp = obj\n lb = tk.Label(frame_canvas, text=text)\n lb.pack(side=\"top\")\n return lb\n \n lb = creat_label()\n canvas = tk.Canvas(frame_canvas, bg=\"white\", cursor=\"circle\", width=400, height=400)\n canvas.pack(side=\"bottom\")\n canvas.bind(\"\", draw_line)\n \n frame_canvas.pack(side=\"top\")\n frame_buttons.pack(side=\"bottom\")\n \n\n tk.Button(frame_buttons, text=\"Submit!\", command= lambda: create_image_matrix(lines_info, lb)).pack(side=\"right\", padx=100)\n tk.Button(frame_buttons, text=\"Clear Canvas\", command= lambda: clear_canvas(canvas)).pack(side=\"left\", padx=100)\n \n def create_image_matrix(lines_info, lb):\n \n def renew_label(lb, predic_name):\n global pre\n pre = predic_name\n global exp\n flag = pre == exp\n obj_index = np.random.randint(0, 4)\n obj = object_list[obj_index]\n while obj == predic_name:\n obj_index = np.random.randint(0, 4)\n obj = object_list[obj_index]\n if flag: \n text = \"\"\"\n You Got the Correct Answer! %s, Could You Draw a(an) %s? \n \"\"\"%(predic_name, obj)\n else:\n text = \"\"\"\n Sadly, Your Paint More Likes %s, Try It Again, Could You Draw a(an) %s? \n \"\"\"%(predic_name, obj)\n lb.configure(text=text)\n lb.update()\n exp = obj\n out_put = np.zeros((400, 400))\n \n def fill_out(point):\n x = point[1]\n y = point[0]\n out_put[x, y] = 255\n r = 3\n for i in range(x-r, x+r+1):\n for j in range(y-r, y+r+1):\n if i>0 and i<400 and j>0 and j<400:\n out_put[i, j] = 255\n \n for point in lines_info:\n fill_out(point)\n \n for i in range(out_put.shape[0]):\n for j in range(out_put.shape[1]):\n if out_put[i, j]==0:\n out_put[i, j]=255\n else:\n out_put[i, j]=0\n \n out_put = Image.fromarray(out_put).convert(\"L\")\n out_put.resize((256, 256), Image.ANTIALIAS)\n n = np.random.randint(0, 1000)\n image_name = \"Images/output\"+str(n)+\".png\"\n out_put.save(image_name)\n global modelrre\n predic_name = CNN(image_name,model)\n \n renew_label(lb, predic_name)\n clear_canvas(canvas)\n \n \n''' \ndef mimic_mouse():\n import serial\n serialport = serial.Serial(\"/dev/serial0\", 115200, timeout=1)\n def get_v(x, y, v=3):\n dx=0\n dy=0\n if x>700:\n dy=v\n if x<300:\n dy = -v\n if y>700:\n dx=-v\n if y<300:\n dx=+v\n return (dx, dy)\n \n \n def parse_info(str):\n #print(str)\n try:\n info = str.split(\" \")\n x = eval(info[0].split(\"'\")[1].split(',')[0])\n y = eval(info[1].split(\",\")[0])\n button = eval(info[2][0])\n return (x, y, button)\n except:\n return None\n \n mouse = Controller()\n global kill_thread\n while kill_thread!=True:\n info = parse_info(str(serialport.readline()))\n if info!=None:\n c_p= (info[0], info[1])\n button = info[2]\n if button == 1:\n mouse.press(Button.left)\n else:\n mouse.release(Button.left)\n v=get_v(c_p[0], c_p[1])\n dx = v[0]\n dy = v[1]\n mouse.move(dx, dy)\n \n else:\n pass \n \n '''\ndef destroy_win(root):\n global kill_thread\n kill_thread = True\n root.destroy()\n \nif __name__ == \"__main__\":\n from keras.models import load_model\n model = load_model(\"mymodel.h5\")\n kill_thread = False\n #t=threading.Thread(target = mimic_mouse)\n #t.start()\n root = tk.Tk()\n root.title(\"Drawing and Learning\")\n root.geometry(\"600x500\")\n \n cards_frame = tk.Frame(root)\n \n app = WordCard(\"apple\", \"Images/apple.jpg\", 0)\n ban = WordCard(\"banana\", \"Images/banana.jpg\", 1)\n bus = WordCard(\"bus\", \"Images/bus.jpg\", 2)\n fis = WordCard(\"fish\", \"Images/fish.jpg\", 3)\n \n frame_pictures = tk.Frame(cards_frame)\n frame_button = tk.Frame(cards_frame)\n frame_left = tk.Frame(frame_pictures)\n tk.Label(frame_left, image = app.image).pack(side=\"top\", ipadx = 30)\n tk.Label(frame_left, text= app.name).pack(side=\"top\")\n tk.Label(frame_left, image = bus.image).pack(side=\"top\", ipadx = 30)\n tk.Label(frame_left, text= bus.name).pack(side=\"top\")\n frame_left.pack(side=\"left\")\n \n frame_right = tk.Frame(frame_pictures)\n tk.Label(frame_right, image = ban.image).pack(side=\"top\", ipadx = 30)\n tk.Label(frame_right, text= ban.name).pack(side=\"top\")\n tk.Label(frame_right, image = fis.image).pack(side=\"top\", ipadx = 30)\n tk.Label(frame_right, text= fis.name).pack(side=\"top\")\n frame_right.pack(side=\"right\")\n frame_pictures.pack(side=\"top\")\n frame_button.pack(side=\"bottom\")\n tk.Button(frame_button, text=\"Ready to draw\", command=lambda:to_drawing_board(cards_frame)).pack(side=\"bottom\")\n cards_frame.pack()\n root.protocol('WM_DELETE_WINDOW', lambda:destroy_win(root))\n root.mainloop()\n\n ","sub_path":"Frame.py","file_name":"Frame.py","file_ext":"py","file_size_in_byte":6615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"360981822","text":"from __future__ import print_function\nimport keras\nfrom keras.datasets import cifar10\nfrom keras.models import load_model\nimport scipy.io as sio\nfrom keras import backend as K\nimport numpy as np\nimport random\n\n\n\ndef normalize(X_train,X_test):\n #this function normalize inputs for zero mean and unit variance\n # it is used when training a model.\n # Input: training set and test set\n # Output: normalized training set and test set according to the trianing set statistics.\n mean = np.mean(X_train,axis=(0,1,2,3))\n std = np.std(X_train, axis=(0, 1, 2, 3))\n X_train = (X_train-mean)/(std+1e-7)\n X_test = (X_test-mean)/(std+1e-7)\n return X_train, X_test\n# -----------------------------------------------------------------------------------------------------------------------\n# Variable Initializations\nnum_classes = 6\nm_Itotalfeatures=5000\nm_startFeatures=4500\n# input image dimensions\nimg_rows, img_cols = 32, 32\n# -----------------------------------------------------------------------------------------------------------------------\n# Load the data\n# ----------------------------------------------------------------------------------------------------------------------\n# Load the model\nfor x in range(5):\n random.seed(x)\n label = random.sample(range(10), 10)\n str1 = ''.join(str(e) for e in label)\n saveNameModel = str1 + 'CIFAR' + '.h5'\n model=load_model(saveNameModel)\n print(model.summary())\n #-------------------------------------------------------------------------------------------------------\n # Function to get a layer output\n get_1st_layer_output = K.function([model.layers[0].input],\n [model.layers[51].output])\n (x_train, y_train), (x_test, y_test) = cifar10.load_data()\n x_train = x_train.astype('float32')\n x_test = x_test.astype('float32')\n x_train, x_test = normalize(x_train, x_test)\n \n if K.image_data_format() == 'channels_first':\n x_train = x_train.reshape(x_train.shape[0], 3, img_rows, img_cols)\n x_test = x_test.reshape(x_test.shape[0], 3, img_rows, img_cols)\n input_shape = (1, img_rows, img_cols)\n else:\n x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 3)\n x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 3)\n input_shape = (img_rows, img_cols, 3)\n \n \n a1=[y_train == label[0]]\n a11 = np.reshape(a1[0], [a1[0].shape[0]])\n x_train_zeros = x_train[a11]\n layer_output_zeros = get_1st_layer_output([x_train_zeros])[0]\n layer_output=layer_output_zeros[m_startFeatures:m_Itotalfeatures]\n print('1 shape:', layer_output.shape)\n # Class 2\n a2=[y_train == label[1]]\n a21 = np.reshape(a2[0], [a2[0].shape[0]])\n x_train_ones = x_train[a21]\n layer_ouput_ones=get_1st_layer_output([x_train_ones])[0]\n layer_output=np.concatenate((layer_output,layer_ouput_ones[m_startFeatures:m_Itotalfeatures]),axis=0)\n print('2 shape:', layer_output.shape)\n # Class 3\n a3=[y_train == label[2]]\n a31 = np.reshape(a3[0], [a3[0].shape[0]])\n x_train_twos= x_train[a31]\n layer_ouput_twos=get_1st_layer_output([x_train_twos])[0]\n layer_output=np.concatenate((layer_output,layer_ouput_twos[m_startFeatures:m_Itotalfeatures]),axis=0)\n print('3 shape:', layer_output.shape)\n # Class 4\n a4=[y_train == label[3]]\n a41 = np.reshape(a4[0], [a4[0].shape[0]])\n x_train_threes= x_train[a41]\n layer_ouput_threes=get_1st_layer_output([x_train_threes])[0]\n layer_output=np.concatenate((layer_output,layer_ouput_threes[m_startFeatures:m_Itotalfeatures]),axis=0)\n print('4 shape:', layer_output.shape)\n # Class 5\n a5=[y_train == label[4]]\n a51 = np.reshape(a5[0], [a5[0].shape[0]])\n x_train_four= x_train[a51]\n layer_ouput_fours=get_1st_layer_output([x_train_four])[0]\n layer_output=np.concatenate((layer_output,layer_ouput_fours[m_startFeatures:m_Itotalfeatures]),axis=0)\n print('5 shape:', layer_output.shape)\n # Class 6\n a6=[y_train == label[5]]\n a61 = np.reshape(a6[0], [a6[0].shape[0]])\n x_train_five= x_train[a61]\n layer_ouput_fives=get_1st_layer_output([x_train_five])[0]\n layer_output=np.concatenate((layer_output,layer_ouput_fives[m_startFeatures:m_Itotalfeatures]),axis=0)\n print('6 shape:', layer_output.shape)\n # Class 7\n a7=[y_train == label[6]]\n a71 = np.reshape(a7[0], [a7[0].shape[0]])\n x_train_sixes = x_train[a71]\n layer_ouput_sixes = get_1st_layer_output([x_train_sixes])[0]\n layer_output = np.concatenate((layer_output, layer_ouput_sixes[m_startFeatures:m_Itotalfeatures]), axis=0)\n print('7 shape:', layer_output.shape)\n # Class 8\n a8=[y_train == label[7]]\n a81 = np.reshape(a8[0], [a8[0].shape[0]])\n x_train_seven = x_train[a81]\n layer_ouput_seven = get_1st_layer_output([x_train_seven])[0]\n layer_output = np.concatenate((layer_output, layer_ouput_seven[m_startFeatures:m_Itotalfeatures]), axis=0)\n print('8 shape:', layer_output.shape)\n # Class 9\n a9=[y_train == label[8]]\n a91 = np.reshape(a9[0], [a9[0].shape[0]])\n x_train_eight = x_train[a91]\n layer_ouput_eight = get_1st_layer_output([x_train_eight])[0]\n layer_output = np.concatenate((layer_output, layer_ouput_eight[m_startFeatures:m_Itotalfeatures]), axis=0)\n print('9 shape:', layer_output.shape)\n # Class 10\n a10=[y_train == label[9]]\n a101 = np.reshape(a10[0], [a10[0].shape[0]])\n x_train_nine = x_train[a101]\n layer_ouput_nine = get_1st_layer_output([x_train_nine])[0]\n layer_output = np.concatenate((layer_output, layer_ouput_nine[m_startFeatures:m_Itotalfeatures]), axis=0)\n print('10 shape:', layer_output.shape)\n \n # target for testing \n y_train_zeros = y_train[y_train == label[0]]\n y_train_sorted =np.zeros((500,),dtype=int)\n y_train_ones = y_train[y_train == label[1]]\n y_train_sorted = np.concatenate((y_train_sorted,np.ones((500,),dtype=int)), axis=0)\n y_train_twos = y_train[y_train == label[2]]\n y_train_sorted = np.concatenate((y_train_sorted, 2*np.ones((500,),dtype=int)), axis=0)\n y_train_threes = y_train[y_train == label[3]]\n y_train_sorted = np.concatenate((y_train_sorted,3*np.ones((500,),dtype=int)), axis=0)\n y_train_fours = y_train[y_train == label[4]]\n y_train_sorted = np.concatenate((y_train_sorted, 4*np.ones((500,),dtype=int)), axis=0)\n y_train_fives = y_train[y_train == label[5]]\n y_train_sorted = np.concatenate((y_train_sorted, 5*np.ones((500,),dtype=int)), axis=0)\n y_train_sixes = y_train[y_train == label[6]]\n y_train_sorted = np.concatenate((y_train_sorted,6*np.ones((500,),dtype=int)), axis=0)\n y_train_sevens = y_train[y_train == label[7]]\n y_train_sorted = np.concatenate((y_train_sorted, 7*np.ones((500,),dtype=int)), axis=0)\n y_train_eights = y_train[y_train == label[8]]\n y_train_sorted = np.concatenate((y_train_sorted, 8*np.ones((500,),dtype=int)), axis=0)\n y_train_nines = y_train[y_train == label[9]]\n y_train_sorted = np.concatenate((y_train_sorted, 9*np.ones((500,),dtype=int)), axis=0)\n\n saveNameFile = 'Test\\\\' +str1 + 'CiFar' + 'TestL51.mat'\n output = {}\n output['TestDataSet'] = layer_output\n output['TestTarget'] = y_train_sorted\n sio.savemat(saveNameFile, output)\n","sub_path":"Cifar/RF+EVT/CIFAR_Test_Features.py","file_name":"CIFAR_Test_Features.py","file_ext":"py","file_size_in_byte":7271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"304082077","text":"# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nfrom typing import Dict, List, Sequence\n\nfrom autosynth import github\n\n\"\"\"Chunks that identify a repo from its name as belonging to a language.\n\nIn other words, we can look at the repo name python-spanner and know that it's\nfor a python library because it contains the word 'python'.\n\"\"\"\n_SILVER_NAME_CHUNKS = (\n \"nodejs\",\n \"python\",\n \"ruby\",\n \"dotnet\",\n \"php\",\n \"java\",\n \"go\",\n \"elixir\",\n)\n\n\"\"\"Language names as reported by github.\"\"\"\n_SILVER_LANGUAGE_NAMES = (\n \"JavaScript\",\n \"TypeScript\",\n \"Python\",\n \"Java\",\n \"PHP\",\n \"Ruby\",\n \"Go\",\n \"C#\",\n \"Elixir\",\n)\n\n\ndef list_split_repositories(\n repo_name_chunk: str, majority_languages: Sequence[str] = ()\n) -> List[Dict]:\n \"\"\"List github repos for a programming language.\n\n Args:\n repo_name_chunk (str): return repos that have this chunk in the repo name.\n Example: \"nodejs\"\n majority_languages (Sequence[str], optional): return repos that have a majority\n of their code written in one of these programming languages.\n Example: (\"JavaScript\", \"TypeScript\")\n\n Returns:\n List[Dict]: [description]\n \"\"\"\n\n gh = github.GitHub(os.environ[\"GITHUB_TOKEN\"])\n all_repos = set(\n [repo[\"name\"] for repo in gh.list_repos(\"googleapis\") if not repo[\"archived\"]]\n )\n # Find repos with the language as part of the repo name.\n lang_repos = set([repo for repo in all_repos if repo_name_chunk in repo.split(\"-\")])\n if majority_languages:\n # Ignore all repos whose name tags them for a language.\n silver_name_chunks = set(_SILVER_NAME_CHUNKS)\n all_lang_repos = set(\n [\n repo\n for repo in all_repos\n if silver_name_chunks.intersection(set(repo.split(\"-\")))\n ]\n )\n # Find repos with the majority of their code written in the language.\n silver_language_names = set(_SILVER_LANGUAGE_NAMES)\n for repo in all_repos - all_lang_repos:\n languages = gh.get_languages(f\"googleapis/{repo}\")\n ranks = [\n (count, lang)\n for (lang, count) in languages.items()\n # Ignore languages we don't care about, like Shell.\n if lang in silver_language_names\n ]\n if ranks and max(ranks)[1] in majority_languages:\n lang_repos.add(repo)\n\n synth_repos = []\n for repo in sorted(lang_repos):\n # Only repos with a synth.py in the top-level directory.\n if not gh.list_files(f\"googleapis/{repo}\", \"synth.py\"):\n continue\n synth_repos.append({\"name\": repo, \"repository\": f\"googleapis/{repo}\"})\n return synth_repos\n","sub_path":"autosynth/providers/list_split_repositories.py","file_name":"list_split_repositories.py","file_ext":"py","file_size_in_byte":3308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"169554863","text":"#!/usr/bin/env python\n\n# encoding=utf-8\nimport json\nfrom ast import parse\nfrom base64 import b64decode\nfrom importlib import import_module\nimport sys\n\n_map = {}\nm = import_module('_ast')\n\n\n# print(dir(m))\n\ndef _build_map():\n attrs = []\n for item in dir(m):\n item_str = str(item)\n\n if item_str.startswith('__'):\n continue\n\n attrs.append(item_str)\n\n for item in attrs:\n print(item)\n _map[getattr(m, item)] = 'Py%s' % item\n\n\ndef node_to_dict(node):\n if isinstance(node, list):\n return [node_to_dict(_) for _ in node]\n\n if not hasattr(node, '_fields'):\n return node\n\n type_ = node.__class__.__name__\n # pprint(type_)\n # print('n',node.__class__.__name__)\n # print(_map[node.__class__.__name__])\n\n ret = dict(type=type_)\n\n for field in node._fields:\n # print('f', field, getattr(node, field))\n ret[field] = node_to_dict(getattr(node, field))\n\n return ret\n\n\nsource = b64decode(sys.argv[1])\ntree = parse(source)\n\nast = node_to_dict(tree)\nprint(json.dumps(ast))\n# print(tree)\n# print(tree.body)\n\n# pprint(export_dict(tree))\n","sub_path":"bin/python-parser.py","file_name":"python-parser.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"365491391","text":"# coding: utf-8\n\nfrom the_tale.game.balance import constants as c\n\n\ndef job_power(power, powers):\n # делим интервал от минимального до максимального размера проекта на равные куски\n # количество кусков равно количеству сущностей + 2\n # дополнительные сущности соответствуют фейковым худшей и лучшей\n # тогда даже если сущность одна, сила её проекта будет между минимумом и максимумом, но не будте равна им\n index = len([p for p in powers if p < power])\n\n interval = c.JOB_MAX_POWER - c.JOB_MIN_POWER\n delta = interval / (len(powers) + 1)\n\n return c.JOB_MIN_POWER + delta * (index + 1)\n","sub_path":"src/the_tale/the_tale/game/jobs/logic.py","file_name":"logic.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"213370072","text":"#https://stackoverflow.com/questions/48071949/how-to-use-the-alpha-vantage-api-directly-from-python\n#https://www.profitaddaweb.com/2018/07/alpha-vantage-preprocessed-free-apis-in.html\nimport requests\nimport alpha_vantage\nimport json\nimport pandas as pd\nimport datetime\nimport numpy as np\nimport time\nfrom mpl_finance import candlestick_ohlc\nimport matplotlib\nimport matplotlib.dates as mdates\nimport matplotlib.path as mpath\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import figure\nfrom matplotlib import style\n\ndef get_stock_time_frame(symbol, start_date, end_date):\n dates=pd.date_range(start_date,end_date)\n df1=pd.DataFrame(index=dates)\n print(symbol,\"start\")\n df_temp=pd.read_csv(\"{}.csv\".format(symbol),index_col=\"date\",parse_dates=True,na_values=['nan'])\n df1=df1.join(df_temp,how='inner')\n print(symbol,\"finish\")\n df1.to_csv('tmp.csv')\n return df1\ndef get_stock_daily(symbol,sizeoption):\n data = { \"function\": \"TIME_SERIES_DAILY_ADJUSTED\", \n \"symbol\": symbol,\n \"outputsize\" : sizeoption, \n \"datatype\": \"json\", \n \"apikey\": \"AXTFJ8VGFWQ1PWZD\" } \n response = requests.get(API_URL, data) \n data = response.json()\n print(symbol,\"start\")\n data=data['Time Series (Daily)'];\n df=pd.DataFrame(columns=['date','open','high','low','close','adjusted close','volume']) \n for d,p in data.items():\n date=datetime.datetime.strptime(d,'%Y-%m-%d')\n data_row=[date,float(p['1. open']),float(p['2. high']),float(p['3. low']),float(p['4. close']), float(p['5. adjusted close']), int(p['6. volume'])]\n df.loc[-1,:]=data_row\n df.index=df.index+1\n data=df.sort_values('date')\n data.to_csv(symbol + '.csv', index=False)\n print(symbol,\"finish\")\n return data\n\n\nif __name__ == \"__main__\":\n symbols = ['FB']\n sizeoption = 'full'\n API_URL = \"https://www.alphavantage.co/query\" \n for symbol in symbols:\n stock_daily=get_stock_daily(symbol,sizeoption)\n df= get_stock_time_frame(symbol,'2017-12-29','2019-01-14')\n df1=df.loc['2017-12-29':'2019-01-14','adjusted close']\nstar = mpath.Path.unit_regular_star(6)\ncircle = mpath.Path.unit_circle()\nverts = np.concatenate([circle.vertices, star.vertices[::-1, ...]])\ncodes = np.concatenate([circle.codes, star.codes])\ncut_star = mpath.Path(verts, codes)\nax = df1.plot(fontsize=40,marker=cut_star, markersize=15)\nstart, end = ax.get_xlim()\nax.xaxis.set_ticks(np.arange(start, end, 20))\nfig = matplotlib.pyplot.gcf()\nfig.set_size_inches(80, 60)\nax.set_xlabel(\"Date\")\nax.set_ylabel(\"Price\")\nax.annotate('Q4,2017 earning',\n (df1.index[df1==df1.loc['2018-01-31']], df1.loc['2018-01-31']),\n xytext=(20, 20), \n textcoords='offset points',\n arrowprops=dict(arrowstyle='-|>'),fontsize=60)\nax.annotate('Q1,2018 earning',\n #tmp workout around to solve the problem for two day same closing price\n (df1.index[df1==df1.loc['2018-04-26']], df1.loc['2018-04-25']),\n xytext=(20, 20), \n textcoords='offset points',\n arrowprops=dict(arrowstyle='-|>'),fontsize=60)\nax.annotate('Q2,2018 earning',\n (df1.index[df1==df1.loc['2018-07-25']], df1.loc['2018-07-25']),\n xytext=(20, 20), \n textcoords='offset points',\n arrowprops=dict(arrowstyle='-|>'),fontsize=60)\nax.annotate('Q3,2018 earning',\n (df1.index[df1==df1.loc['2018-10-30']], df1.loc['2018-10-30']),\n xytext=(20, 20), \n textcoords='offset points',\n arrowprops=dict(arrowstyle='-|>'),fontsize=60)\nfig.savefig('test2png.png', dpi=80)\n#plt.show()","sub_path":"get_single_daily_19_1_17_working.py","file_name":"get_single_daily_19_1_17_working.py","file_ext":"py","file_size_in_byte":3713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"166166165","text":"#!/usr/bin/env python\n\nimport os\nimport glob\nimport warnings\nimport datetime\n\n\n# function to self update itself. considering following conditions\n# - the current user can write to this directory\n# - running every run_time_difference seconds to avoid extra runs\n# - avoiding concurrent runs\n# - remote git repo is working.\n# - git command line utility is present in that machine\n\ndef __self_update():\n \"\"\"A function to self update a python package's repo.\"\"\"\n current_repo_dir = os.path.dirname(__file__)\n # add `lastrun.ignore` file in your project's .gitignore so that changes to this file is ignored\n time_status_file = current_repo_dir + \"/lastrun.ignore\"\n run_time_difference = 600000\n # check if time_status_file file exists. if not try creating it. if unable to create, simply return without updating\n try:\n with open(time_status_file, 'a'):\n os.utime(time_status_file, None)\n except EnvironmentError:\n warnings.warn(\"WARNING: No WRITE permission on status file. Can not perform update\")\n return\n\n with open(time_status_file, 'r') as status_file_read:\n last_update_run = status_file_read.read().strip()\n\n if not last_update_run:\n last_update_run = 0\n else:\n last_update_run = int(last_update_run)\n\n current_time_since_epoch_milliseconds = int((datetime.datetime.utcnow() -\n datetime.datetime(1970, 1, 1)).total_seconds() * 1000)\n\n # time difference between current run and last run is less than run_time_difference milli seconds, don't run\n if (current_time_since_epoch_milliseconds - last_update_run) < run_time_difference:\n return\n else:\n import fcntl\n import subprocess\n fp = open(time_status_file, 'w')\n try:\n fcntl.flock(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)\n except IOError:\n fp.close()\n return\n git_up_cmd = 'cd {0} && git reset --hard HEAD >/dev/null 2>&1 && git clean -f -d >/dev/null 2>&1 ' \\\n '&& git pull >/dev/null 2>&1'.format(current_repo_dir)\n try:\n subprocess.check_output([git_up_cmd], shell=True)\n fp.write(str(current_time_since_epoch_milliseconds))\n except subprocess.CalledProcessError:\n warnings.warn(\"WARNING: Failed to update repo.\")\n pass\n finally:\n fcntl.flock(fp, fcntl.LOCK_UN)\n fp.close()\n\n\nif 'DISABLE_REPO_AUTO_UPDATE' in os.environ and os.environ['DISABLE_REPO_AUTO_UPDATE'] == '1':\n warnings.warn(\n \"WARNING: Self update disabled using environment variable DISABLE_REPO_AUTO_UPDATE\")\nelse:\n __self_update()\n\nmodules = glob.glob(os.path.dirname(__file__) + \"/*.py\")\n__all__ = [os.path.basename(f)[:-3] for f in modules if os.path.isfile(f) and not f.startswith('__')]\n","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"572039857","text":"import param\nimport random\nimport copy\n\n\nclass Individual:\n mut_count = 0\n def __init__(self):\n self.gen = [random.randint(-param.max_gen_value, param.max_gen_value) for i in range(param.len_exp)]\n self.calc_fitness()\n\n def calc_fitness(self):\n func = param.init_f\n self.fitness = abs(sum([self.gen[i] * func[i] for i in range(param.len_exp)]) + func[-1])\n\n def crossover(self, other):\n child = copy.copy(self)\n\n left, right = sorted([random.randint(0, param.len_exp-1) for i in range(2)])\n child.gen = self.gen[0:left] + self.gen[right:] + other.gen[left:right]\n for i in range(param.len_exp):\n child.gen[i] = random.randint(*sorted([child.gen[i], self.gen[i]]))\n\n if random.random() < param.mut_chance:\n child.mutation()\n\n child.calc_fitness()\n return child\n\n def mutation(self):\n Individual.mut_count += 1\n self.gen[random.randint(0, param.len_exp-1)] = random.randint(-param.max_gen_value, param.max_gen_value)\n\n def __str__(self):\n return str(self.fitness) + str(self.gen)","sub_path":"individual.py","file_name":"individual.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"272245592","text":"#!/usr/bin/env python3\n\"\"\"parse.py: Extracts contacts from HTML of GSA Directory search results\"\"\"\n__author__= \"John Dunagan\"\n__email__= \"jcdunagan@wustl.edu\"\n# https://github.com/jcdunagan/GSADirectoryScraper\n\nfrom bs4 import BeautifulSoup\nimport re\n\n# Various string cleaners\nclean_name = lambda x: re.sub('[\\t\\n ]+', ' ', x).strip()\nclean_dep_code = lambda x: re.sub('[()]', '', x).strip()\nclean_dep_title = lambda x: x.strip()\nclean_addr = clean_name\n\ncon_string_valid = lambda x: bool(re.search('\\w+', x)) and not x.endswith(';')\nclean_con_key = lambda x: x.replace(':', '').strip()\nclean_con_value = clean_dep_title\n\n\ndef parse_row(tr):\n \"\"\"Extract single entry from row\"\"\"\n person = dict()\n\n # Extract name and department from name span\n name_span = tr.find(\"span\", \"name\")\n if name_span:\n # Assumes every name string contains comma\n last, first = name_span.contents[0].split(',')\n person['firstname'] = clean_name(first)\n person['lastname'] = clean_name(last)\n\n\n # Extract department code (i.e. M1AG)\n # QUESTION: what are these codes officially called?\n if name_span.span:\n code = clean_dep_code(name_span.span.string)\n title = clean_dep_title(name_span.span['title'])\n person['department'] = {'code': code, 'title': title}\n\n # Extract address and position from address span\n address_span = tr.find(\"span\", \"address\")\n if address_span:\n # Separate into lines and clean up excess whitespace\n address_strings = list(map(clean_addr, address_span.stripped_strings))\n\n lines = len(address_strings)\n if lines == 1:\n # 1 line means it's somebody's position with no address\n person['position'] = address_strings[0]\n elif lines == 2:\n # 2 lines means it's an address with no title\n person['address'] = address_strings[:]\n elif lines > 2:\n # 3 lines, we can assume first is position, next 2 are address\n person['position'], *person['address'] = address_strings\n # 4 lines is unanticipated, but information WILL be extracted\n\n # Extract various contact info from number span\n number_span = tr.find(\"span\", \"number\")\n if number_span:\n contacts = dict()\n\n # Eliminate empties and 'nbsp;'\n stripped = list(filter(con_string_valid, number_span.stripped_strings))\n\n # Find labels of form \"Phone:\" or \"Email:\"\n keys = [(i,s) for i,s in enumerate(stripped) if s.endswith(':')]\n\n for i, s in keys:\n # Next entry should be value\n contacts[clean_con_key(s)] = clean_con_value(stripped[i+1])\n\n person['contacts'] = contacts\n\n return person\n\ndef parse_table(table):\n \"\"\"Extract contacts from table\"\"\"\n return list(map(parse_row, table.tbody.find_all('tr')))\n\n\ndef parse_html(html_doc):\n \"\"\"Extract contacts from page source\"\"\"\n soup = BeautifulSoup(html_doc, 'html.parser')\n\n if not soup.table or soup.find(class_='bg-warning'):\n return []\n else:\n return parse_table(soup.table)\n\n\nif __name__ == '__main__':\n with open('sample.html','r') as f:\n html_doc = f.read()\n\n persons = parse_html(html_doc)\n for p in persons:\n print(p['lastname'])\n","sub_path":"parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":3288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"540967956","text":"\n\nfrom xai.brain.wordbase.nouns._saying import _SAYING\n\n#calss header\nclass _SAYINGS(_SAYING, ):\n\tdef __init__(self,): \n\t\t_SAYING.__init__(self)\n\t\tself.name = \"SAYINGS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"saying\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_sayings.py","file_name":"_sayings.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"227392304","text":"#print(\"Simpel additions miniräknare med 2 tal\")\n#tal1 = int(input(\"Tal 1: \"))\n#tal2 = int(input(\"Tal 2: \"))\n#summa = str(tal1 + tal2)\n#print(\"Summa: \" + summa)\n\n\n#raknesatt = input('Välj raknesatt (\" + - * / \"): ')\n#if raknesatt is not \"+\" or \"-\" or \"*\" or \"/\":\n# print(\"Välj ett av de skriva formlerna\")\n#tal1 = int(input(\"Tal 1:\" ))\n#tal2 = int(input(\"Tal 2:\" ))\n#if raknesatt == \"*\":\n# summa = str(tal1 * tal2)\n# print(\"summa: \" + summa)\n#elif raknesatt == \"+\":\n# summa = str(tal1 + tal2)\n# print(\"summa: \" + summa)\n#elif raknesatt == \"-\":\n# summa = str(tal1 - tal2)\n# print(\"summa: \" + summa)\n#elif raknesatt == \"/\":\n# summa = str(tal1 / tal2)\n# print(\"summa: \" + summa)\n\n#while True:\n# noError = True\n# raknesatt = str(input('Välj raknesatt (\" + - * / \"): '))\n# print(raknesatt)\n# if raknesatt is \"+\" or \"-\" or \"*\" or \"/\":\n# try:\n# tal1 = int(input(\"Tal 1:\" ))\n# except(ValueError):\n# print(\"Du måste skriva in ett heltal: \")\n# noError = False\n# try:\n# tal2 = int(input(\"Tal 2:\" ))\n# except(ValueError):\n# print(\"Du måste skriva in ett heltal: \")\n# noError = False\n# else:\n# print(\"Skriv ett av de giltiga tecknen\")\n# if noError == True:\n# if raknesatt == \"*\":\n# summa = str(tal1 * tal2)\n# print(\"summa: \" + summa)\n# break\n# elif raknesatt == \"+\":\n# summa = str(tal1 + tal2)\n# print(\"summa: \" + summa)\n# break\n# elif raknesatt == \"-\":\n# summa = str(tal1 - tal2)\n# print(\"summa: \" + summa)\n# break\n# elif raknesatt == \"/\":\n# summa = str(tal1 / tal2)\n# print(\"summa: \" + summa)\n# break\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nwhile True:\n while True:\n operator = str(input('Välj operator (\" + - * / \"): '))\n if operator == \"+\" or operator == \"-\" or operator == \"/\" or operator == \"*\":\n break\n else:\n print(\"Välj ett av de valda...\")\n\n while True:\n try: \n tal1 = int(input(\"Tal 1:\" ))\n break\n except(ValueError):\n print('Skriv ett heltal')\n\n while True:\n while True:\n try: \n tal2 = int(input(\"Tal 2:\" ))\n break\n except(ValueError):\n print('Skriv ett heltal')\n\n if operator == \"*\":\n summa = str(tal1 * tal2)\n break\n\n elif operator == \"+\":\n summa = str(tal1 + tal2)\n break\n\n elif operator == \"-\":\n summa = str(tal1 - tal2)\n break\n\n elif operator == \"/\":\n summa = str(tal1 / tal2)\n break\n \n print(\"Summa: \" + summa)\n\n while True:\n svarNy = input(\"Vill du räkna ut ett nytt tal? [y/n] \").lower()\n if svarNy == \"y\":\n break\n elif svarNy == \"n\":\n exit()\n else:\n print('Svara gärna med \"y\" eller \"n\"')\n","sub_path":"minräknare.py","file_name":"minräknare.py","file_ext":"py","file_size_in_byte":3063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"513920751","text":"import argparse, codecs, sys\nfrom unicodedata import category\n\n# remove utf8 space\ndef trim(line):\n new_line = []\n for c in line:\n if c == ' ' or category(c) != 'Zs':\n new_line.append(c)\n return ''.join(new_line)\n\ndef parse(line):\n ss = trim(line.strip()).split(' ')\n all_feat = [x.split('|') for x in ss if len(x) > 0]\n all_feat = filter(lambda x: len(x) == 4, all_feat)\n toks = [x[0] for x in all_feat if len(x[0]) > 0]\n stems = [x[1] if x[1] != 'null' else x[0] for x in all_feat if len(x[0]) > 0]\n tags = ['_'.join(x[2].split(',')[:2]) for x in all_feat if len(x[0]) > 0]\n readings = [x[3] for x in all_feat if len(x[0]) > 0]\n\n return toks, stems, tags, readings\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--stem_file', dest='stem_file', action='store', type=str, help='output file for sentence stems')\n parser.add_argument('--tok_file', dest='tok_file', action='store', type=str, help='output file for sentence toks')\n parser.add_argument('--pos_file', dest='pos_file', action='store', type=str, help='output file for sentence pos')\n parser.add_argument('--all_file', dest='all_file', action='store', type=str, help='output file for sentence pos and stem and tok')\n parser.add_argument('--input_file', dest='input_file', action='store', type=str, help='output file for sentence inputs')\n args = parser.parse_args()\n\n if args.stem_file:\n stem_out = codecs.open(args.stem_file, 'w', encoding='utf-8')\n if args.tok_file:\n tok_out = codecs.open(args.tok_file, 'w', encoding='utf-8')\n if args.pos_file:\n pos_out = codecs.open(args.pos_file, 'w', encoding='utf-8')\n if args.all_file:\n all_out = codecs.open(args.all_file, 'w', encoding='utf-8')\n\n with codecs.open(args.input_file, 'r', encoding='utf-8') as fin:\n for line in fin:\n toks, stems, tags, readings = parse(line)\n if args.tok_file:\n tok_out.write('%s\\n' % ' '.join(toks))\n if args.stem_file:\n stem_out.write('%s\\n' % ' '.join(stems))\n if args.pos_file:\n pos_out.write('%s\\n' % ' '.join(['%s|%s' % (tok, tag) for tok, tag in zip(toks, tags)]))\n if args.all_file:\n all_out.write('%s\\n' % ' '.join(['%s|%s|%s|%s' % (tok, tag, stem, reading) for tok, stem, tag, reading in zip(toks, stems, tags, readings)]))\n\n if args.stem_file:\n stem_out.close()\n if args.tok_file:\n tok_out.close()\n if args.pos_file:\n pos_out.close()\n\n\n\n\n\n","sub_path":"src/parse_kuromoji.py","file_name":"parse_kuromoji.py","file_ext":"py","file_size_in_byte":2513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"648559490","text":"#!/usr/bin/env python\n\nimport smtplib\nimport sys\n\ndef mail(fr, to, subj, body, srv='smtp.hcs.harvard.edu'):\n server = smtplib.SMTP(srv)\n message = \"\"\"\\\nFrom: %s\nTo: %s\nSubject: %s\n\n%s\n\"\"\" % (fr, to, subj, body)\n \n server.sendmail(fr, to, message)\n server.quit()\n\n\nif __name__ == '__main__':\n if len(sys.argv) != 5:\n sys.exit(-1)\n\n fr = sys.argv[1]\n to = sys.argv[2]\n subj = sys.argv[3]\n file = sys.argv[4]\n \n fp = open(file, 'r')\n body = fp.read()\n\n mail(fr, to, subj, body)\n","sub_path":"subscribers_notifier/sendemail.py","file_name":"sendemail.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"149261199","text":"import pickle, os, json, time\nfrom google.oauth2 import service_account\nfrom google_auth_oauthlib.flow import InstalledAppFlow\n\nclass AuthenticateGCP:\n 'Authentication Library for GCP projects'\n\n def __init__(self):\n self.current_directory = os.path.dirname(os.path.realpath(__file__))\n \n\n def oauth_flow(self, suffix, redirect_uri, oauth_scope):\n '''\n This function requires you to have a client secret stored as client_secret.json.\n 1) Ensure you have correct OAuth client ID set up to access your required API: https://console.cloud.google.com/apis/credentials\n 2) Download your project's JSON file by clicking the Download icon\n 3) Rename the file client_secret.json and place it in the /config directory of your project's repo\n '''\n # oauth scope - Find out if you need readonly access, or write/execute permissions, this will depend on the intent of your project\n redirect_uri = redirect_uri\n oauth_scope = oauth_scope\n try:\n credentials = pickle.load(open(self.current_directory + '/config-'+ suffix + '/credentials.pickle', 'rb'))\n except (OSError, IOError):\n try:\n flow = InstalledAppFlow.from_client_secrets_file(self.current_directory + '/config-' + suffix + '/client_secret.json', scopes=oauth_scope)\n credentials = flow.run_console()\n pickle.dump(credentials, open(self.current_directory + '/config-' + suffix + '/credentials.pickle', 'wb'))\n except (OSError, IOError) as e:\n print(e)\n print('Client secret file not found. Make sure you have OAuth client ID set up to access your required API: https://console.cloud.google.com/apis/credentials /n Also make sure to download your porject\\'s JSON file and place in the /config directory of this repo.')\n\n return credentials\n\n def export_google_credentials(self):\n # Use OS library to export service account credentials to script's environment \n #service_account_file = self.current_directory + '/service-account.json'\n service_account_file = 'service-account.json'\n os.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = service_account_file\n\n return os.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"]\n\n def service_account(self):\n '''\n Make sure service account file in saved in project's config folder\n '''\n \n service_account_file = self.current_directory + '/service-account.json'\n credentials = service_account.Credentials.from_service_account_file(service_account_file)\n\n return credentials\n\nclass ErrorHandling:\n\n def __init__(self, HttpError, max_retries, retry_errors, wait_interval):\n\n self.max_retries = max_retries\n self.retry_errors = retry_errors\n self.wait_interval = wait_interval\n self.HttpError = HttpError\n\n\n def http_retry(self):\n\n # This function ensures code is retried max_retries number of times if failed due to Http error\n\n retries = 0\n while retries <= self.max_retries:\n decoded_error_body = self.HttpError.content.decode('utf-8')\n json_error = json.loads(decoded_error_body)\n if json_error['error']['code'] in self.retry_errors:\n time.sleep(self.wait_interval)\n retries += 1\n continue\n\n return","sub_path":"authenticator.py","file_name":"authenticator.py","file_ext":"py","file_size_in_byte":3413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"221889407","text":"import cv2\nfrom timeit import default_timer as timer\nfrom sort import *\nfrom pedestrian.counter import get_roi_contour, is_in_roi, get_count_change, is_empty_roi, get_count_in_roi\nfrom pathlib import Path\nimport math\n\n # camera = cv2.VideoCapture(\"pedestrians.avi\")\n # camera.open(\"pedestrians.avi\")\n # ped_cascade = cv2.CascadeClassifier('cascade3.xml')\n # frame_count = 0\n # # create instance of SORT\n # mot_tracker = Sort()\n # cont = get_roi_contour(int(camera.get(4)), int(camera.get(3)))\n # pre_objs = []\n # current_objs = []\n # ped_count_in_roi = 0\n # while True:\n\ndef dis(x1,y1,x2,y2):\n return math.hypot(x2 - x1, y2 - y1)\n\ndef at_least_one_standing(pre, curr, thr):\n for ob in pre:\n if ob[1] == 'i':\n for ob2 in curr:\n if ob2[0] == ob[0]:\n if ob2[1] == 'i':\n if dis(ob2[2], ob2[3], ob[2], ob[3]) < thr:\n return True\n return False\n\ndef ped(frame, ped_cascade, current_objs, cont, frame_count, ped_count_in_roi, wait_frm_count, mot_tracker, thresh):\n start = timer()\n grayvideo = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n cars = ped_cascade.detectMultiScale(grayvideo, 1.1, minNeighbors=4) # 1.1 #2\n\n mot_before_list = []\n for (x, y, w, h) in cars:\n cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)\n mot_before_list.append([x, y, (x+w), (y+h), 0.8])\n mot_before_np = np.array(mot_before_list)\n track_bbs_ids = mot_tracker.update(mot_before_np)\n mot_x1, mot_y1, mot_x2, mot_y2, obj_id = [0, 0, 0, 0, 0]\n trk_with_wid_hgt = []\n pre_objs = current_objs.copy() # keep copy in buffer\n current_objs[:] = [] # make current list empty\n for i in track_bbs_ids:\n mot_x1, mot_y1, mot_x2, mot_y2, obj_id = i\n x1_i = int(mot_x1)\n y1_i = int(mot_y1)\n x2_i = int(mot_x2)\n y2_i = int(mot_y2)\n cv2.rectangle(frame, (x1_i, y1_i), (x2_i, y2_i), (255, 0, 0), 2)\n text = str(obj_id)\n print(text)\n cv2.putText(frame, text, (x1_i, y1_i - 7), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)\n wid = x2_i - x1_i\n higt = y2_i - y1_i\n trk_with_wid_hgt.append([x1_i, y1_i, wid, higt, obj_id])\n cen_x = x1_i + wid / 2\n cen_y = y1_i + higt / 2\n if is_in_roi(cen_x, cen_y, cont[0]):\n current_objs.append((obj_id, 'i', cen_x, cen_y))\n else:\n current_objs.append((obj_id, 'o'))\n frame_count_return = frame_count + 1\n cv2.drawContours(frame, cont, 0, (255, 0, 0), 2, 8)\n chng = get_count_change(pre_objs, current_objs)\n buff = ped_count_in_roi + chng\n if buff < 0: # This is resetting procedure\n ped_count_in_roi_return = 0\n else:\n ped_count_in_roi_return = buff\n cnt_in_roi = get_count_in_roi(current_objs)\n if buff < cnt_in_roi:\n ped_count_in_roi_return = cnt_in_roi\n\n if is_empty_roi(pre_objs, current_objs): # This is also resetting procedure\n ped_count_in_roi_return = 0\n wait_frm_count_rtn = 0\n else:\n if at_least_one_standing(pre_objs, current_objs, thresh):\n wait_frm_count_rtn = wait_frm_count + 1\n else:\n wait_frm_count_rtn = 0\n cv2.putText(frame, str(ped_count_in_roi_return), (20, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)\n cv2.imshow(\"vid\", frame)\n end = timer()\n print(int(1 / (end - start)))\n\n return ped_count_in_roi_return, frame_count_return, wait_frm_count_rtn\n # k = cv2.waitKey(10)\n # if k == ord('q'):\n # break\n # elif k == ord('s'):\n # cv2.imwrite('pedestrian_still.jpg', frame)\n\n# camera.release()\n# cv2.destroyAllWindows()\n\nif __name__ == \"__main__\":\n camera = cv2.VideoCapture(str(Path.cwd().parent / 'videos' / 'pedestrians8tv.mp4'))\n #camera.open(\"pedestrians.avi\")\n ped_cascade = cv2.CascadeClassifier('cascade3.xml')\n frm_count = 0\n # create instance of SORT\n mot_tracker = Sort()\n cont = get_roi_contour(int(camera.get(4)), int(camera.get(3)))\n pre_objs = []\n current_objs = []\n ped_count_in_roi = 0\n wait_frame_count = 0\n while True:\n (grabbed, framez) = camera.read()\n cv2.putText(framez, \"Wait time : \" + str(wait_frame_count), (15, 80), cv2.FONT_HERSHEY_SIMPLEX, 0.5,\n (0, 255, 0), 2)\n ped_count_in_roi, frm_count, wait_frame_count = ped(framez, ped_cascade, current_objs, cont, frm_count, ped_count_in_roi,wait_frame_count,\n mot_tracker, 5)\n k = cv2.waitKey(10)\n if k == ord('q'):\n break\n elif k == ord('s'):\n cv2.imwrite('pedestrian_still.jpg', framez)\n\n camera.release()\n cv2.destroyAllWindows()\n","sub_path":"pedestrian/pedestrian_Detection.py","file_name":"pedestrian_Detection.py","file_ext":"py","file_size_in_byte":4775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"69007270","text":"from loguru import logger\nfrom util import util\nimport pytz\nimport datetime\nfrom telegram import ParseMode\n\n\ndef handle(update, context):\n\n try:\n util.log_chat(\"day\", update)\n\n response = generate_response()\n logger.info(\"[day] Generated response={}\", response)\n\n update.message.reply_text(text=response, parse_mode=ParseMode.HTML)\n except Exception as e:\n logger.error(\n \"[day] Caught Error! e={} \\n update.message={} \", e, update.message\n )\n\n\ndef generate_response():\n\n ist = pytz.timezone(\"Asia/Kolkata\")\n\n today = datetime.datetime.now()\n today = ist.localize(today)\n\n last_day_of_the_year = datetime.datetime(year=today.year, month=12, day=31)\n last_day_of_the_year = ist.localize(last_day_of_the_year)\n\n response = \"Day:
{}/{}
\".format(\n today.strftime(\"%j\"), last_day_of_the_year.strftime(\"%j\")\n )\n\n return response\n","sub_path":"src/handlers/day.py","file_name":"day.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"114639622","text":"#!/usr/bin/env python3\n\n\n\"\"\"Py-DDA\n\nA package for the multi-Doppler analysis of radar radial velocity data. \n\n\"\"\"\n\n\nDOCLINES = __doc__.split(\"\\n\")\n\nimport glob\n\nfrom numpy.distutils.core import setup\nfrom numpy.distutils.misc_util import Configuration\n\n\nNAME = 'pydda'\nMAINTAINER = 'Robert Jackson'\nDESCRIPTION = DOCLINES[0]\nLONG_DESCRIPTION = \"\\n\".join(DOCLINES[2:])\nLICENSE = 'BSD'\nPLATFORMS = \"Linux, Windows, OSX\"\nMAJOR = 0\nMINOR = 1\nMICRO = 0\n#SCRIPTS = glob.glob('scripts/*')\n#TEST_SUITE = 'nose.collector'\n#TESTS_REQUIRE = ['nose']\nVERSION = '%d.%d.%d' % (MAJOR, MINOR, MICRO)\n\n\ndef configuration(parent_package='', top_path=None):\n \"\"\" Configuration of PyDDA package. \"\"\"\n config = Configuration(None, parent_package, top_path)\n config.set_options(ignore_setup_xxx_py=True,\n assume_default_configuration=True,\n delegate_options_to_subpackages=True,\n quiet=True)\n config.add_subpackage('pydda')\n return config\n\n\ndef setup_package():\n \"\"\" Setup of PyDDA package. \"\"\"\n setup(\n name=NAME,\n maintainer=MAINTAINER,\n description=DESCRIPTION,\n long_description=LONG_DESCRIPTION,\n version=VERSION,\n license=LICENSE,\n platforms=PLATFORMS,\n configuration=configuration,\n include_package_data=True,\n #test_suite=TEST_SUITE,\n #tests_require=TESTS_REQUIRE,\n #scripts=SCRIPTS,\n )\n\nif __name__ == '__main__':\n setup_package()\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"561605584","text":"from autof2.interface import send_data, window,mouse\nfrom autof2.readf2 import parse\nfrom autof2.navigation import navigation\nfrom autof2.interface.send_data import SendData\n\n##import window\n##import mouse\n##import clipboard\n##import parse\n##import navigation\nimport csv\n\nimport time\nimport win32gui\nimport win32con\n##from send_data import SendData\n\ndef drag_window():\n win32gui.ShowWindow(window.f2_hwnd, win32con.SW_MAXIMIZE)\n win32gui.SetForegroundWindow(window.f2_hwnd)\n c = window.get_corners(window.f2_hwnd)\n mouse.click_and_drag(c[0] +25,c[1] + 50,c[2] - 25,c[3]-50)\n\ndef get_window():\n send = SendData()\n send = SendData()\n drag_window()\n send.send('%c')\n data = None\n for i in range(3):\n try:\n data = clipboard.get_clipboard()\n break\n except:\n time.sleep(0.01)\n return data\n\ndef run_purchase_list(from_date, to_date,supplier, new = True):\n if new:\n navigation.to_purchase_list()\n drag_window()\n send = SendData()\n send.send(from_date)\n send.send('{enter}')\n send.send(to_date)\n send.send('{enter}')\n send.send('{DOWN}')\n send.send(supplier)\n send.send('{enter}')\n send.send('{F11}')\n send.send('n')\n send.send('screen')\n send.send('{enter}')\n\n for i in range(15):\n screen = parse.process_scene(get_window())\n if parse.identify_screen(screen,'Inkoop advies avc',1):\n return get_window()\n time.sleep(0.1)\n \n\ndef get_orders(orders = {}):\n # change string to list of string, per line\n \n screen = None\n screen = parse.process_scene(get_window())\n '''\n for i in range(10):\n try:\n screen = parse.process_scene(get_window())\n except:\n time.sleep(0.1)\n if screen:\n break\n time.sleep(0.1)\n '''\n # get supplier name\n supplier = parse.distribution_list_supplier(screen)\n if not supplier:\n\n return None\n\n # get list of orders\n if supplier not in orders:\n orders[supplier] = []\n return orders\n\ndef total_orders(orders):\n orders_totals = {}\n for o in orders:\n if (o.category, o.name, o.grade,o.colour) in orders_totals:\n orders_totals[(o.category, o.name, o.grade,o.colour)] += o.quantity\n else:\n orders_totals[(o.category, o.name, o.grade,o.colour)] = o.quantity\n print(o.quantity)\n \n return orders_totals\n\ndef get_full_report(from_date,to_date,supplier ):\n send = SendData()\n run_purchase_list(from_date, to_date,supplier)\n screen = parse.process_scene(get_window())\n o = parse.distribution_list_product(screen)\n i = 0\n print(screen[-1])\n while '< More >' in screen[-1] and i < 10:\n send.send('{enter}')\n time.sleep(0.8)\n screen = parse.process_scene(get_window())\n o.extend(parse.distribution_list_product(screen))\n i+=1\n return o\n\ndef thursday_orders(from_date,to_date,supplier): \n orders = get_full_report(from_date, to_date,supplier)\n t = total_orders(orders)\n l = []\n for line in t:\n l.append((line, t[line]))\n l.sort()\n for line in l:\n print(line[0][0],\"\\t\",line[0][1].strip('*'),\"\\t\",line[0][2],\"\\t\",line[0][3],\"\\t\",line[1])\n\n return t,l, orders\n \ndef make_shipment_list(date = '051115', client='CAN*ON',plist = '03'):\n send = SendData()\n navigation.to_order_order(date,client,plist)\n screen = parse.process_scene(get_window())\n categories = parse.order_categories(screen)\n items = {}\n for c in categories:\n if navigation.to_order_category(c[0],c[1]):\n screen = parse.process_scene(get_window())\n ### get items\n \n items[c[1]] = parse.parse_order_category(c[1])[c[1]]\n time.sleep(.1)\n print(items[c[1]])\n\n \n send.send(\"{F12}\")\n return items\n\ndef make_shipment_list_NZ(date = '051115', client='CAN*ON',plist = '03'):\n send = SendData()\n navigation.to_order_order(date,client,plist)\n time.sleep(1.5)\n screen = parse.process_scene(get_window())\n categories = parse.order_categories(screen)\n print(categories)\n items = {}\n \n for c in categories:\n if navigation.to_order_category(c[0],c[1]):\n time.sleep(.5)\n screen = parse.process_scene(get_window())\n print(screen)\n ### get items\n \n items[c[1]] = parse.parse_order_category_NZ(c[1])[c[1]]\n time.sleep(.3)\n print(items[c[1]])\n\n \n send.send(\"{F12}\")\n return items\n\ndef make_virtual_shipment_list(date = '051115', client='CAN*ON',plist = '03'):\n send = SendData()\n navigation.to_order_order(date,client,plist)\n screen = parse.process_scene(get_window())\n categories = parse.order_categories(screen)\n items = {}\n for c in categories:\n if navigation.to_order_category(c[0],c[1]):\n screen = parse.process_scene(get_window())\n ### get items\n \n items[c[1]] = parse.parse_virtual_order_category(c[1])[c[1]]\n## print(items[c[1]])\n\n \n send.send(\"{F12}\")\n return items\n\n\ndef get_groupings(grouping_loc = \"D:\\\\BuyProg\\\\new\\pricelist_groupings.csv\"):\n groupings = {}\n with open(grouping_loc, 'r') as file:\n for line in file:\n line = line.strip()\n line = line.split(',')\n groupings[line[1]] = line[0]\n return groupings\n\ndef open_excel(from_date,to_date,supplier):\n t, a = thursday_orders(from_date,to_date,supplier)\n \n\n \n\n\n##if __name__ == \"__main__\":\n## send = SendData()\n## t, a, o = thursday_orders('131215', '191215','CAROSA')\n## for i in o:\n## print(i.category,\"\\t\", i.name,\"\\t\", i.quantity)\n\n","sub_path":"autof2/readf2/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":5811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"581852502","text":"# $Id: RA2Cleaning_cff.py,v 1.16 2012/12/19 14:19:01 seema Exp $\n\n# Standard Event cleaning \nfrom StopTupleMaker.Skims.noscraping_cfi import *\nfrom StopTupleMaker.Skims.vertex_cfi import *\nfrom StopTupleMaker.Skims.HBHENoiseFilter_cff import *\n\nra2StdCleaning = cms.Sequence(\n noscraping \n * oneGoodVertex\n)\n\n# RA2 detector noise cleaning\nfrom RecoMET.METFilters.eeNoiseFilter_cfi import *\nfrom StopTupleMaker.Skims.beamHaloFilter_cfi import *\nfrom StopTupleMaker.Skims.HBHENoiseFilter_cff import *\nfrom RecoMET.METFilters.hcalLaserEventFilter_cfi import *\nfrom RecoMET.METFilters.eeBadScFilter_cfi import *\nfrom RecoMET.METFilters.trackingFailureFilter_cfi import *\nhcalLaserEventFilter.vetoByRunEventNumber=cms.untracked.bool(False)\nhcalLaserEventFilter.vetoByHBHEOccupancy=cms.untracked.bool(True)\nfrom RecoMET.METFilters.ecalLaserCorrFilter_cfi import *\n\nra2NoiseCleaning = cms.Sequence(\n eeNoiseFilter\n * trackingFailureFilter \n * beamHaloFilter\n * HBHENoiseFilter # rejects the event\n * HBHENoiseFilterRA2 # produced a boolean & stores it\n * hcalLaserEventFilter \n * eeBadScFilter\n * ecalLaserCorrFilter\n) \n\n## RA2 post reconstruction cleaning\n# badly reconstructed muons\nfrom StopTupleMaker.Skims.muonPFCandidateProducer_cfi import *\n\nfrom RecoMET.METFilters.greedyMuonPFCandidateFilter_cfi import *\ngreedyMuons = greedyMuonPFCandidateFilter.clone()\ngreedyMuons.PFCandidates = cms.InputTag('muonPFCandidateProducer')\n\nfrom RecoMET.METFilters.inconsistentMuonPFCandidateFilter_cfi import *\ninconsistentMuons = inconsistentMuonPFCandidateFilter.clone()\ninconsistentMuons.PFCandidates = cms.InputTag('muonPFCandidateProducer')\n\nselectGoodPFEventsSequence = cms.Sequence(\n muonPFCandidateProducer \n * inconsistentMuons \n * greedyMuons\n)\n\n# ECAL dead cell filters\nfrom RecoMET.METFilters.EcalDeadCellTriggerPrimitiveFilter_cfi import *\nEcalDeadCellTriggerPrimitiveFilter.tpDigiCollection = cms.InputTag(\"ecalTPSkimNA\")\nra2EcalTPFilter = EcalDeadCellTriggerPrimitiveFilter.clone()\n\nfrom RecoMET.METFilters.EcalDeadCellBoundaryEnergyFilter_cfi import *\nra2EcalBEFilter = EcalDeadCellBoundaryEnergyFilter.clone()\nra2EcalBEFilter.recHitsEB = \"reducedEcalRecHitsEB\"\nra2EcalBEFilter.recHitsEE = \"reducedEcalRecHitsEE\"\n\nra2EcalPostRecoCleaning = cms.Sequence( \n ra2EcalTPFilter\n * ra2EcalBEFilter\n)\n\n# tracking-POG filters\nfrom RecoMET.METFilters.trackingPOGFilters_cff import *\n## NOTE: to make tagging mode of the tracking POG filters (three of them), please do:\n## Also the stored boolean for the three filters is opposite to what we usually\n## have for other filters, i.e., true means rejected bad events while false means \n## good events.\nmanystripclus53X.taggedMode = cms.untracked.bool(True)\nmanystripclus53X.forcedValue = cms.untracked.bool(False)\ntoomanystripclus53X.taggedMode = cms.untracked.bool(True)\ntoomanystripclus53X.forcedValue = cms.untracked.bool(False)\nlogErrorTooManyClusters.taggedMode = cms.untracked.bool(True)\nlogErrorTooManyClusters.forcedValue = cms.untracked.bool(False)\ntrackingPOGCleaning = cms.Sequence(manystripclus53X * toomanystripclus53X * logErrorTooManyClusters)\n\n# after all MET POG recommeded filters, also check JetID\nfrom StopTupleMaker.Skims.RA2JetIDFailureFilter_cfi import *\n\nra2PostCleaning = cms.Sequence(\n ra2NoiseCleaning\n * selectGoodPFEventsSequence \n * ra2EcalPostRecoCleaning\n #* trackingPOGCleaning # should be run on AODs\n #* ra2PBNR #(to be jet-by-jet)\n)\n","sub_path":"Skims/python/RA2Cleaning_cff.py","file_name":"RA2Cleaning_cff.py","file_ext":"py","file_size_in_byte":3935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"77412985","text":"from Base.get_driver import getDriver\ndriver=getDriver(\"com.android.settings\",\".Settings\")\n# driver.close_app()\ndriver.quit()\nif driver.is_app_installed(\"com.vcooline.aike\"):\n driver.remove_app(\"com.vcooline.aike\")\n print(\"卸载完成\")\nelse:\n driver.install_app(\"C:\\\\爱客CRM.apk\")\n print(\"安装完成\")","sub_path":"Scripts/test17.py","file_name":"test17.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"632289437","text":"# --------------------------------------------------------------------------\n# Introdução a Programação de Computadores - IPC\n# Universidade do Estado do Amazonas - UEA\n# Prof. Jucimar Jr\n# TIAGO FERREIRA ARANHA 1715310047\n#\n# 11. Altere o programa anterior, intercalando 3 vetores de 10 elementos cada.\n# ---------------------------------------------------------------------------\n\nvetores = []\nvetor4 = []\n\nn = 0\nwhile n < 3:\n vet = []\n m = 0\n while m < 2:\n numero = int(input())\n vet.append(numero)\n m += 1\n vetores.append(vet)\n n += 1\n\n# print(vetores)\n\n\nfor i, vetor in enumerate(vetores):\n print(\"Vetor %d: :\" % (i + 1), vetor)\n vetor4.append(vetores[n][0])\n\n\nfor i, vetor in enumerate(vetores):\n print(\"Vetor %d: :\" % (i + 1), vetor)\n vetor4.append(vetores[n][1])\n\n\nprint(\"Vetor 4:\", vetor4)\n","sub_path":"lista06/lista06_lista01_questao11.py","file_name":"lista06_lista01_questao11.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"276048686","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport os\nfrom scipy.stats import binned_statistic\nimport sys\nimport glob\n\ndef read_dat(file):\n with open(file) as f:\n lines = f.readlines()\n n = len(lines)\n preds = np.zeros((n, 1))\n for i in range(n):\n preds[i] = float(lines[i])\n return(preds)\n\ndef read_P_RPS(path, nmodel):\n with open(path) as f:\n lines = f.readlines()\n ibin = 0\n y = np.zeros((nmodel, 2))\n for num, j in enumerate(lines[1:]):\n tm = j.strip().split()\n v = float(tm[0])\n r = float(tm[1])\n y[ibin, 0] = v\n y[ibin, 1] = r\n ibin += 1\n return(y)\n\ndef P_RPS(v, rho):\n \"\"\"\n Defining RPS pressure as potential prediction variable\n \"\"\"\n rho0 = rho * (1 - 0.1) / (10) + 0.1\n v0 = v * (0.7 - 0.3) / (10) + 0.3\n P0 = rho0 * v0 ** 2\n P0_min = min(P0)\n P0_max = max(P0)\n # P0_min = 0.009\n # P0_max = 0.49\n P = 10.0 * (P0 - P0_min) / (P0_max - P0_min)\n return P\n\ndef main():\n # constants and directories\n root_dir = '/Users/austin.shen/Dropbox/UWA/ICRAR_Kenji/archive/trained_models/'\n preds_dir = 'm9.dir_e300_density_P_RPS/'\n\n f8 = 'predictions_dir8.dat'\n f7 = 'predictions_dir7.dat'\n\n # expected values\n truth_dir = '../../../data/'\n dir_8 = 'm1.dir_8_density/'\n dir_7 = 'm1.dir_7_density/'\n f_y = '2dfvn.dat'\n\n # reading prediction files\n preds_8 = read_dat(root_dir + preds_dir + f8)\n preds_7 = read_dat(root_dir + preds_dir + f7)\n y_8 = read_P_RPS(truth_dir + dir_8 + f_y, nmodel = 10000)\n y_7 = read_P_RPS(truth_dir + dir_7 + f_y, nmodel = 10000)\n\n P_RPS_8 = P_RPS(y_8[:,0], y_8[:,1])\n\n # plotting\n x = np.linspace(0, 10, 500)\n y = np.linspace(0, 10, 500)\n\n # binned error data\n bin_x = np.array([0.5 + i for i in range(10)])\n bin_means = binned_statistic(np.array(P_RPS_8), np.array(preds_8).reshape(len(preds_8)), statistic=\"mean\", bins=10)[0]\n bin_std = binned_statistic(np.array(P_RPS_8), np.array(preds_8).reshape(len(preds_8)), statistic=\"std\", bins=10)[0]\n # bin_counts = binned_statistic(np.array(P_RPS_8), np.array(preds_8).reshape(len(preds_8)), statistic=\"count\", bins=10)[0]\n # bin_error = bin_std / np.sqrt(bin_counts)\n\n plt.rc('text', usetex = True)\n plt.rc('font', family = 'serif')\n plt.plot(x, y, dashes=[6, 2], color='black', alpha=0.5)\n plt.scatter(P_RPS_8, preds_8, marker='.', color='red', alpha=0.1)\n (_, caps, _) = plt.errorbar(bin_x, bin_means, yerr=bin_std, color='black', alpha=0.5, fmt='o', markersize=2, capsize=5)\n for cap in caps:\n cap.set_markeredgewidth(1)\n plt.xlabel(r\"$P_{rps,c}$\", fontsize=14)\n plt.ylabel(r\"$P_{rps,p}$\", fontsize=14)\n plt.tight_layout()\n # plt.show()\n plt.savefig(\"../../../plots/paper/FIG7.pdf\")\n\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"figures/figure7.py","file_name":"figure7.py","file_ext":"py","file_size_in_byte":2849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"167358335","text":"import tensorflow as tf\n\nxx=[1,2,3]\nyy=[1,2,3]\n\nw=tf.Variable(tf.random_uniform([1],-1,1))\nb=tf.Variable(tf.random_uniform([1],-1,1))\n\nx=tf.placeholder(tf.float32)\nx_test=[5,7]\n\nhypothesis = w * x + b\n#평균 제곱 오차를 구한다.\ncost = tf.reduce_mean((hypothesis-yy)**2)\n#옵티마이저를 지정한다(학습 방법을 지정한다)\n#optimizer=tf.train.GradientDescentOptimizer(learning_rate=0.1)\noptimizer=tf.train.GradientDescentOptimizer(learning_rate=0.01)\n#학습 진행\ntrain=optimizer.minimize(loss=cost)\n\nsess=tf.Session()\nsess.run(tf.global_variables_initializer())\n#EP\nfor i in range(10):\n sess.run(train,feed_dict={x:xx})\n print(i,sess.run(cost,feed_dict={x:xx}))\nfor i in range(len(x_test)):\n print(\"x=\",x_test[i],\"predict:\",sess.run(hypothesis,feed_dict={x:x_test}))\nsess.close()","sub_path":"DATE_18_7_19/Tensorflow/LinerRegression/LinearReg_simple_placeholder.py","file_name":"LinearReg_simple_placeholder.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"262285085","text":"import spira\nimport numpy as np\n\nfrom spira import param\nfrom copy import copy, deepcopy\nfrom spira.gdsii.elemental.port import PortAbstract\nfrom spira.core.initializer import ElementalInitializer\n\n\nclass Term(PortAbstract):\n \"\"\"\n Terminals are horizontal ports that connect SRef instances\n in the horizontal plane. They typically represents the\n i/o ports of a components.\n\n Examples\n --------\n >>> term = spira.Term()\n \"\"\"\n\n width = param.FloatField(default=2)\n length = param.FloatField(default=0.1)\n\n def __init__(self, port=None, polygon=None, **kwargs):\n super().__init__(port=port, polygon=polygon, **kwargs)\n\n from spira import shapes\n if polygon is None:\n rect_shape = shapes.RectangleShape(\n p1=[0, 0],\n p2=[self.width, self.length]\n )\n pp = spira.Polygons(\n shape=rect_shape,\n gdslayer=spira.Layer(number=65)\n )\n pp.rotate(angle=self.orientation, center=self.midpoint)\n # pp.rotate(angle=90-self.orientation, center=self.midpoint)\n pp.move(midpoint=pp.center, destination=self.midpoint)\n self.polygon = pp\n else:\n self.polygon = polygon\n\n arrow_shape = shapes.ArrowShape(\n a = self.width/10,\n b = self.width/20,\n c = self.width/5\n )\n\n arrow_shape.apply_merge\n # arrow_shape.rotate(angle=self.orientation)\n\n self.arrow = spira.Polygons(\n shape=arrow_shape,\n gdslayer=spira.Layer(number=77)\n )\n\n self.arrow.rotate(angle=self.orientation)\n # self.arrow.rotate(angle=90-self.orientation)\n\n def __repr__(self):\n return (\"[SPiRA: Term] (name {}, number {}, midpoint {}, \" +\n \"width {}, orientation {})\").format(self.name,\n self.gdslayer.number, self.midpoint,\n self.width, self.orientation\n )\n\n def _copy(self):\n new_port = Term(parent=self.parent,\n name=self.name,\n midpoint=self.midpoint,\n width=self.width,\n length=self.length,\n gdslayer=deepcopy(self.gdslayer),\n poly_layer=deepcopy(self.poly_layer),\n text_layer=deepcopy(self.text_layer),\n orientation=self.orientation)\n return new_port\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"spira/gdsii/elemental/term.py","file_name":"term.py","file_ext":"py","file_size_in_byte":2394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"631403876","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 23 10:47:13 2018\n\n@author: antoine\n\"\"\"\nimport numpy as np\nfrom keras.models import Model\nfrom keras.layers import Input,Dense, Conv1D, MaxPooling1D, Concatenate, Flatten\n\n\nclass Firm:\n def __init__(self,params,observation_size=12):\n print('NEW INIT')\n \n \n \n ###Initial firm parameters\n self.initial_funds=params['initial_funds']\n self.funds=self.initial_funds\n self.initial_inventory=params['initial_inventory']\n self.inventory=params['initial_inventory']\n self.max_inventory=params['max_inventory']\n self.production_queue=[0]*params['production_time']\n self.current_reward=0.\n self.WACC=params['WACC']\n self.cost=params['cost']\n self.production_time=params['production_time']\n self.epsilon_greedy=params['epsilon_greedy']\n ##Set explore rate evolution\n self.explore_rate=params['initial_explore_rate']\n self.explore_rate_decay=params['explore_rate_decay']\n self.min_explore_rate=params['min_explore_rate']\n self.explore_turns=params['explore_turns']\n self.temperature=10\n \n self.bankrupt=False\n \n ##Scaling parameters:\n self.mean_action=0\n self.std_action=1\n self.mean_obs=0\n self.std_obs=1\n self.mean_Q=0\n self.std_Q=1\n \n \n self.plot_frequency=params['plot_frequency']\n self.possible_actions=params['possible_actions']\n self.last_action=self.possible_actions[0]\n self.env_obs_size=observation_size\n self.memory_size=params['memory_size']\n self.init_event_memory()\n self.init_Q_estimator(observation_size)\n \n self.epochs=params['epochs']\n \n self.replay_memory_size=params['replay_memory_size']\n self.init_replay_memory()\n\n self.n_step=0\n self.played_games=0\n \n \n self.list_rewards=[]\n self.funds_evolution=[]\n self.list_actions=[]\n\n def get_state(self):\n return np.array([(self.funds,self.current_reward,self.inventory,*self.last_action)])\n \n \n def init_Q_estimator(self,n_input):\n self.Q_estimator_shape=(n_input,self.possible_actions.shape[1],1)\n input_actions=Input(shape=(self.possible_actions.shape[1],))\n x_actions = Dense(10,activation='relu')(input_actions)\n input_data = Input(shape=(self.memory_size,n_input+self.get_state().shape[1],))\n x_data = Conv1D(10,3,activation='relu')(input_data)\n x_data = Conv1D(10,3,activation='relu')(x_data)\n x_data = MaxPooling1D(3)(x_data)\n x_data=Flatten()(x_data)\n x=Concatenate()([x_data,x_actions])\n x=Dense(10,activation='relu')(x)\n estimated_Q = Dense(1,activation='linear')(x)\n self.Q_estimator = Model(inputs=[input_actions,input_data], outputs=estimated_Q)\n self.Q_estimator.compile(optimizer='rmsprop',\n loss='mse')\n \n def estimate_Q(self,actions,observations,rescale=True):\n actions=(actions-self.mean_action)/self.std_action\n observations=(observations-self.mean_obs)/self.std_obs\n return self.Q_estimator.predict([actions,observations])[:,0]\n \n def fit_Q(self,rescale=True):\n if rescale:\n action_memory=(self.action_memory-self.mean_action)/self.std_action\n observation_memory=(self.observation_memory-self.mean_obs)/self.std_obs\n Q_memory=(self.Q_memory-self.mean_Q)/self.std_Q\n self.Q_estimator.fit([action_memory,observation_memory],Q_memory,epochs=self.epochs,verbose=0)\n \n \n\n ###Initialize the replay memory\n def init_replay_memory(self):\n self.action_memory=np.zeros((0,self.Q_estimator_shape[1]))\n self.observation_memory=np.zeros((0,self.event_memory.shape[1],self.event_memory.shape[2]))\n self.Q_memory=np.zeros((0,self.Q_estimator_shape[2]))\n \n def update_replay_memory(self,action,state_observation,Q_value):\n self.observation_memory=np.concatenate((self.observation_memory,state_observation),0)\n self.action_memory=np.concatenate((self.action_memory,action),0)\n Q_value=np.array([(Q_value,)])\n self.Q_memory=np.concatenate((self.Q_memory,Q_value),0)\n if np.shape(self.action_memory)[0]>self.replay_memory_size:\n self.observation_memory=self.observation_memory[1:]\n self.action_memory=self.action_memory[1:]\n self.Q_memory=self.Q_memory[1:]\n \n def update_scaling(self):\n self.mean_obs=0.5*self.mean_obs+0.5*np.mean(self.observation_memory,0)\n self.std_obs=0.5*self.std_obs+0.5*np.std(self.observation_memory,0)\n \n self.mean_action=0.5*self.mean_action+0.5*np.mean(self.action_memory,0)\n self.std_action=0.5*self.std_action+0.5*np.std(self.action_memory,0)\n \n self.std_Q=0.5*self.std_Q+np.std(self.Q_memory,0)*0.5\n self.mean_Q=0.5*self.mean_Q+np.mean(self.Q_memory,0)*0.5\n \n def init_event_memory(self):\n self.event_memory=np.zeros((1,self.memory_size,self.env_obs_size+self.get_state().shape[1]))\n \n def update_event_memory(self,new_observation):\n new_event_memory=np.concatenate((new_observation.reshape((1,1,-1)),self.event_memory),1)\n self.event_memory=new_event_memory[:,:self.memory_size,:]\n \n def reset(self):\n self.bankrupt=False\n self.update_scaling()\n if self.explore_rate>self.min_explore_rate:\n self.explore_rate*=self.explore_rate_decay\n if self.temperature>0.1:\n self.temperature*=self.explore_rate_decay\n self.fit_Q()\n \n self.played_games+=1\n self.n_step=0\n print(self.played_games)\n print(self.funds)\n self.rewards=0\n self.inventory=self.initial_inventory\n self.funds=self.initial_funds\n self.init_event_memory()\n \n def compute_best_action(self,observation):\n observation=np.repeat(observation,len(self.possible_actions),0)\n values=self.estimate_Q(self.possible_actions,observation)\n return self.possible_actions[np.argmax(values)], np.max(values)\n \n def compute_action_values(self,observation):\n observation=np.repeat(observation,len(self.possible_actions),0)\n values=self.estimate_Q(self.possible_actions,observation)\n return values\n\n def act(self, observation):\n if self.funds<0:\n self.bankrupt=True\n print('Firm bankruptcy')\n self.n_step+=1\n state_observation=np.concatenate((self.get_state(),observation),1)\n self.previous_observation=state_observation\n self.update_event_memory(state_observation)\n if self.epsilon_greedy:\n if (self.played_games=self.max_inventory:\n self.inventory=self.max_inventory\n self.production_queue=self.production_queue[1:]\n \n def get_sales(self,purchase):\n if self.inventory-purchase>=0:\n self.inventory=self.inventory-purchase\n return purchase\n else:\n self.inventory=0\n return self.inventory\n","sub_path":"CNN_market_reaction/Firm.py","file_name":"Firm.py","file_ext":"py","file_size_in_byte":8547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"550476458","text":"import time\nimport re\nfrom pymongo import MongoClient\n\n__KARMA_REGEX = re.compile(r'<@!{0,1}(\\d*?)> {0,1}(\\+\\+|--)')\n__COOLDOWN_IN_SECONDS = 3600\n\n\ndef __log_karma_given_event(database, message, user_id):\n database.users.update({'_id': message.author.id}, {'$inc': {f'karma_given.{user_id}': 1}}, upsert=True)\n\ndef __log_karma_received_event(database, message, user_id):\n database.aesthetics.users.update({'_id': user_id}, {'$inc': {f'karma_from.{message.author.id}': 1}}, upsert=True)\n\ndef __time_left(time_in_db, cooldown):\n return (cooldown/60) - ((time.time() - time_in_db)/60)\n\nasync def __update_database_if_valid(client, config, message, user_id, operation):\n mongo_client = MongoClient(config['mongo_connection'])\n database = mongo_client[message.server.id]\n\n cooldown = __COOLDOWN_IN_SECONDS\n if operation == '++':\n change = 1\n m = 'gained'\n elif operation == '--':\n cooldown *= 2\n change = -1\n m = 'lost'\n\n result = database.users.find_one({'_id': user_id})\n\n if result is not None and result.get('karma_timestamp', False):\n if (time.time() - result['karma_timestamp']) > cooldown:\n database.users.update_one({'_id': user_id}, {'$inc': {'karma': change}, '$set': {'karma_timestamp': time.time()}})\n __log_karma_given_event(database, message, user_id)\n __log_karma_received_event(database, message, user_id)\n await client.send_message(message.channel, '%s %s a karma. **Currently: %d**\\nGiven by: %s' % (message.server.get_member(user_id).display_name, m, result['karma']+change, message.author.display_name))\n else:\n await client.send_message(message.channel, 'That user gained karma too recently please wait some time. %d minutes left.' % __time_left(result['karma_timestamp'], cooldown))\n else:\n database.users.update_one({'_id': user_id}, {'$inc': {'karma': change}, '$set': {'karma_timestamp': time.time()}}, upsert=True)\n __log_karma_given_event(database, message, user_id)\n __log_karma_received_event(database, message, user_id)\n await client.send_message(message.channel, '%s %s their first karma\\nGiven by: %s' % (message.server.get_member(user_id).display_name, 'gained' if change > 0 else 'lost', message.author.display_name))\n\n mongo_client.close()\n\nasync def handle(client, config, message):\n matches = __KARMA_REGEX.findall(message.content)\n if matches:\n for match in matches:\n if message.author.id == match[0]:\n await client.send_message(message.channel, 'You cannot edit your own karma.')\n else:\n client.send_typing(message.channel)\n await __update_database_if_valid(client, config, message, match[0], match[1])\n","sub_path":"mods-available/karma_mod.py","file_name":"karma_mod.py","file_ext":"py","file_size_in_byte":2785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"577404475","text":"#!/usr/bin/env python\n# -*- coding:utf8 -*-\n\nimport os, imp, json, re\nfrom common import db, conf\nfrom consts import *\nfrom core import *\nfrom zbase import *\nfrom interface import *\n\ntry:\n import cPickle as pickle\nexcept ImportError:\n import pickle\n\n\ndef process_change_ip_show(node, show=True):\n try:\n import json\n def showIpTag(item):\n if type(item) == dict:\n if item.has_key('show_select_ip'):\n item['show_select_ip'] = show\n return item\n\n objpro = node.process\n recpro = objpro.wf_process\n\n business_form = db.session.query(ProcessForm).filter_by(process_id=recpro.id,\n form_name=\"__business_requirement\").first()\n # __business_requirement\n if business_form:\n blist = business_form.form_value\n blist = json.loads(blist)\n blist = map(showIpTag, blist)\n business_form.form_value = json.dumps(blist, ensure_ascii=False)\n db.session.commit()\n except BaseException as e:\n app.logger.info(u\"zfunc::process_change_ip_show Error :%s \" % GetException(e))\n\n\ndef apply_device_department(self):\n objpro = self.process\n process = objpro.wf_process\n business_requirement_record = db.session.query(ProcessForm).filter_by(process_id=process.id,\n form_name=\"__business_requirement\").first()\n if process.flow_id in [FLOW_QUARTER_PURCHASE, FLOW_TEMPORARY_PURCHASE]:\n # 季度采购和临时采购流程 归属人tag取\"业务运维认领节点\"的执行人\n business_tag = process.executor\n elif process.flow_id in [FLOW_SERVER_USE_APPLY, ]:\n # 服务器领用申请 归属人tag取 流程申请人\n business_tag = process.user_name\n else:\n app.logger.info(u\"zfunc::apply_device_department Error : 业务tag为空\")\n business_tag = ''\n\n if not business_requirement_record:\n return\n business_requirements = json.loads(business_requirement_record.form_value)\n assets = []\n errmsg = []\n\n def cmdbapi(item):\n count = int(item['machine_num'])\n department = item['department']\n room = item['room']\n device_type = item['machine_type']\n\n data = {\n 'count': count,\n 'department': department,\n 'room': room,\n 'device_type': device_type,\n 'business_tag': business_tag\n }\n result = CMDB.apply_device_department(data=data)\n if str(result.get(\"code\", 1000)) == \"0\":\n msg = result['value']\n if type(msg) == unicode or type(msg) == str:\n msg = msg.replace(\"u'\", \"\").replace(\"'\", \"\")\n assets.append(msg)\n else:\n emsg = result.get(\"message\", \"\")\n emsg = \"product:%s\\nroom:%s\\ndepartment:%s\\ndevice_type:%s\\ncount:%s\\nerror:%s\" % \\\n (count, room, department, device_type, count, emsg)\n errmsg.append(emsg)\n\n business_requirements = filter(lambda item: False if item['machine_type'].lower()[0] == \"v\" else True,\n business_requirements)\n business_requirements = filter(lambda item: item['product'], business_requirements)\n map(cmdbapi, business_requirements)\n\n # if assets:\n # title = u\"[CMDB接口返回的固资号][工单:%s]-%s-%s\" % (process.flow_name, process.process_name, process.now_step_cnname)\n # content = u\"固定资产号:%s\" % b\",\".join(assets)\n # to = \"\"\n # Event.post_event(\"notice_mail\", dict(to=to, title=title, content=content))\n #\n # if errmsg:\n # content = u\"ProcessID:%s\\nCMDB apply_device_department ERROR:\\n%s\" % (process.id, \"\\n\".join(errmsg))\n # title = u\"[CMDB接口调用失败][工单:%s]-%s-%s\" % (process.flow_name, process.process_name, process.now_step_cnname)\n # to = \"\"\n # Event.post_event(\"notice_mail\", dict(to=to, title=title, content=content))\n","sub_path":"server/db/zfunc.py","file_name":"zfunc.py","file_ext":"py","file_size_in_byte":4072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"344844221","text":"import sklearn\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\nfrom sklearn.pipeline import Pipeline, FeatureUnion\r\nfrom sklearn.cross_validation import train_test_split\r\nfrom sklearn.metrics import accuracy_score, classification_report, confusion_matrix, recall_score, precision_score, f1_score\r\nfrom sklearn.svm import SVC, LinearSVC\r\nimport time\r\n\r\nimport nltk\r\nfrom nltk.tokenize import TweetTokenizer\r\nfrom nltk.stem import WordNetLemmatizer \r\nfrom nltk.stem import LancasterStemmer\r\nfrom nltk.corpus import stopwords as sw\r\n\r\nfrom collections import Counter\r\n\r\nfrom sklearn.base import BaseEstimator, TransformerMixin\r\nfrom sklearn.feature_extraction import DictVectorizer\r\n\r\nimport numpy as np\r\nimport sys, re, os\r\nimport xml.etree.ElementTree as ET\r\nfrom operator import itemgetter\r\n\r\ndef main():\r\n t0 = time.time() #added to see the total duration of the program\r\n\r\n try:\r\n trainDirectory = str(sys.argv[1])\r\n testDirectory = str(sys.argv[2])\r\n except:\r\n print(\"Please use python3 svm.py trainDirectory testDirectory (e.g. training/english testing/english)\")\r\n sys.exit(1)\r\n\r\n try:\r\n goldPath = str(sys.argv[3])\r\n except:\r\n print(\"Please define the path to the gold-standard file (e.g. english/gold.txt), so accuracy, precision and recall over test-set can be calculated.\")\r\n sys.exit(1)\r\n\r\n trainDocuments, testDocuments = createDocuments(trainDirectory,testDirectory)\r\n\r\n # Preprocess the data (e.g. tokenisation)\r\n trainDocuments = preprocessData(trainDocuments)\r\n testDocuments = preprocessData(testDocuments)\r\n\r\n\r\n #create seperate lists for tweets and the genders\r\n train_ids, train_tweets, train_genders, train_ages = createLists(trainDocuments,\"train\")\r\n test_ids, test_tweets = createLists(testDocuments,\"test\")\r\n\r\n #predict gender\r\n classifierGender = classifyGender(train_tweets, train_genders)\r\n predicted_genders = classifierGender.predict(test_tweets)\r\n\r\n language = testDirectory.split(\"/\")[-1]\r\n\r\n #only predict age for spanish and english\r\n if \"spanish\" in language or \"english\" in language:\r\n classifierAge = classifyAge(train_tweets, train_ages)\r\n predicted_ages = classifierAge.predict(test_tweets)\r\n\r\n else:\r\n predicted_ages = [\"XX-XX\" for i in range(len(test_ids))]\r\n\r\n\r\n\r\n #write predictions to truth file\r\n outFile = open(testDirectory+\"/truthPredicted.txt\",\"w+\")\r\n \r\n userDictGender = {}\r\n userDictAge = {}\r\n for idx, i in enumerate(test_ids):\r\n idn = i\r\n gender = predicted_genders[idx]\r\n age = predicted_ages[idx]\r\n\r\n if idn not in userDictGender:\r\n userDictGender[idn] = [gender]\r\n userDictAge[idn] = [age]\r\n else:\r\n userDictGender[idn].append(gender)\r\n userDictAge[idn].append(age)\r\n\r\n for key in userDictGender:\r\n gender = Counter(userDictGender[key]).most_common(1)[0][0]\r\n age = Counter(userDictAge[key]).most_common(1)[0][0]\r\n\r\n outFile.write(key+\":::\"+gender+\":::\"+age+\"\\n\")\r\n\r\n outFile.close()\r\n\r\n\r\n # Calculate metrics\r\n goldFile = open(goldPath,\"r+\").read().split(\"\\n\")\r\n predictedFile = open(testDirectory+\"/truthPredicted.txt\",\"r+\").read().split(\"\\n\")\r\n\r\n goldFile = [line.split(\":::\")[:3] for line in goldFile if line]\r\n goldFile = sorted(goldFile, key=itemgetter(0))\r\n \r\n predictedFile = [line.split(\":::\") for line in predictedFile if line]\r\n predictedFile = sorted(predictedFile, key=itemgetter(0))\r\n\r\n\r\n goldGenders = [i[1] for i in goldFile]\r\n goldAges = [i[2] for i in goldFile]\r\n predictedGenders = [i[1] for i in predictedFile]\r\n predictedAges = [i[2] for i in predictedFile]\r\n\r\n goldCombined = goldGenders + goldAges\r\n predictedCombined = predictedGenders + predictedAges\r\n\r\n #Gender\r\n results(goldGenders,predictedGenders,\"gender\",language)\r\n\r\n if \"spanish\" in language or \"english\" in language:\r\n #Age\r\n results(goldAges,predictedAges,\"age\",language)\r\n\r\n #Gender+Age\r\n results(goldCombined,predictedCombined,\"combined\",language)\r\n\r\n total_time = time.time() - t0\r\n print(\"\\ntotal time: \", total_time)\r\n \r\n\r\n\r\ndef results(gold,predicted,part,language):\r\n accuracy = accuracy_score(gold, predicted)\r\n precision = precision_score(gold,predicted,average=\"macro\")\r\n recall = recall_score(gold,predicted,average=\"macro\")\r\n f1 = f1_score(gold,predicted,average=\"macro\")\r\n confusionMatrix = sklearn.metrics.confusion_matrix(gold, predicted)\r\n\r\n \r\n print(\"\\n\\n\"+'\\033[95m'+part+'\\033[0m'+\":\\nAccuracy = \", round(accuracy,3),\"\\n\")\r\n\r\n labelsGender = [\"F\",\"M\"]\r\n print(\"\\t\\t {} \\t {} \\t {}\".format(\"Precision\",\"Recall\",\"F1-score\"))\r\n for label in labelsGender:\r\n precisionScore = sklearn.metrics.precision_score(gold,predicted, average=\"micro\", labels=label)\r\n recallScore = sklearn.metrics.recall_score(gold,predicted, average=\"micro\", labels=label)\r\n f1Score = sklearn.metrics.f1_score(gold,predicted, average=\"micro\", labels=label)\r\n\r\n print(\"{} \\t\\t {} \\t\\t {} \\t\\t {}\".format(label,round(precisionScore,3),round(recallScore,3),round(f1Score,3)))\r\n\r\n print(\"\\nAvg/total \\t {} \\t\\t {} \\t\\t {}\".format(round(precision,3),round(recall,3),round(f1,3)))\r\n\r\n print(\"\\nConfusion Matrix:\")\r\n createConfusionMatrix(confusionMatrix, part, language)\r\n\r\n\r\n return accuracy, precision, recall, f1, confusionMatrix\r\n\r\n \r\ndef identity(x):\r\n return x\r\n\r\n\r\ndef tweetIdentity(arg):\r\n tokenizer = TweetTokenizer(strip_handles=True, reduce_len=True)\r\n tokens = tokenizer.tokenize(arg)\r\n return tokens\r\n\r\n\r\ndef customLemmatizer(arg):\r\n \"\"\"\r\n Preprocesser function to test different lemma.\r\n \"\"\"\r\n wnl = WordNetLemmatizer()\r\n st = LancasterStemmer()\r\n return st.stem(wnl.lemmatize(arg))\r\n\r\n\r\n\r\ndef classifyGender(train_tweets, train_genders):\r\n\r\n vec_word = TfidfVectorizer(preprocessor = customLemmatizer,\r\n tokenizer = tweetIdentity,\r\n binary=True,\r\n lowercase=False, \r\n analyzer='word', \r\n ngram_range=(1,2))\r\n\r\n vec_char = TfidfVectorizer(preprocessor = customLemmatizer,\r\n tokenizer = tweetIdentity,\r\n binary=True,\r\n lowercase=False, \r\n analyzer='char', \r\n ngram_range=(3,5))\r\n\r\n\r\n gender_stereotypes_vec = Pipeline([\r\n ('stereotypes', LinguisticGenderFeatures()),\r\n ('vec', DictVectorizer())\r\n ])\r\n\r\n combined_feats = FeatureUnion([(\"vec_word\", vec_word), (\"vec_char\", vec_char), (\"vec_stereo\", gender_stereotypes_vec)])\r\n\r\n\r\n\r\n classifier = Pipeline([('vec', combined_feats),\r\n ('classifier', LinearSVC(multi_class='crammer_singer'))])\r\n\r\n \r\n classifier.fit(train_tweets, train_genders) \r\n return classifier\r\n\r\n\r\ndef classifyAge(train_tweets, train_ages):\r\n \r\n vec_word = TfidfVectorizer(preprocessor = customLemmatizer,\r\n tokenizer = tweetIdentity,\r\n binary=True,\r\n lowercase=False, \r\n analyzer='word', \r\n ngram_range=(1,2),\r\n max_features=400000)\r\n\r\n vec_char = TfidfVectorizer(preprocessor = customLemmatizer,\r\n tokenizer = tweetIdentity,\r\n binary=True,\r\n lowercase=False, \r\n analyzer='char', \r\n ngram_range=(3,5),\r\n max_features=400000)\r\n\r\n combined_feats = FeatureUnion([(\"vec_word\", vec_word), (\"vec_char\", vec_char)])\r\n\r\n\r\n classifier = Pipeline([('vec', combined_feats),\r\n ('classifier', LinearSVC())])\r\n\r\n\r\n classifier.fit(train_tweets, train_ages) \r\n return classifier\r\n\r\n\r\nclass LinguisticGenderFeatures(BaseEstimator, TransformerMixin):\r\n def fit(self, x, y=None):\r\n return self\r\n\r\n def _get_features(self, doc):\r\n counts = Counter(doc)\r\n text_string = \" \".join(doc)\r\n pos_tagged_text = nltk.pos_tag(doc)\r\n apologetic_words = [\"sorry\", \"scusa\", \"scusi\", \"colpa\", \"excuus\", \"spijt\", \"siento\", \"culpa\"]\r\n tag_questions = [\"right?\", \"isn't it?\", \"aren't they?\", \"verdad?\", \"toch?\", \"giusto?\", \"vero?\"]\r\n swearwords = [\"shit\", \"crap\", \"fuck\", \"merda\", \"cazzo\", \"gvd\", \"kut\", \"mierda\"]\r\n return {\r\n \"swearing\": len([word for word in swearwords if word in doc])\r\n #\"words\": len(doc)\r\n # \"unique_words\": len(set(doc)),\r\n # \"adjectives\": len([word[1] for word in pos_tagged_text if word[1] == \"JJ\"]),\r\n # \"adverbs\": len([word[1] for word in pos_tagged_text if word[1] == \"RB\"]),\r\n # \"exclamation\": counts[\"!\"],\r\n # \"apologetic_lang\": len([word for word in doc if word in apologetic_words]),\r\n # \"tag_questions\": len([tag for tag in tag_questions if tag in text_string]),\r\n # \"questions\": counts[\"?\"]}\r\n }\r\n \r\n def transform(self, raw_documents):\r\n return [ self._get_features(doc) for doc in raw_documents]\r\n\r\ndef createLists(documents,part):\r\n if part == \"train\":\r\n ids = []\r\n tweets = []\r\n genders = []\r\n ages = []\r\n\r\n for i in documents:\r\n if i != \"\":\r\n idn = i[0]\r\n tweet = i[1]\r\n gender = i[2]\r\n age = i[3]\r\n\r\n ids.append(idn)\r\n genders.append(gender)\r\n tweets.append(tweet)\r\n ages.append(age)\r\n\r\n return ids, tweets, genders, ages\r\n else:\r\n ids = []\r\n tweets = []\r\n\r\n for i in documents:\r\n if i != \"\":\r\n idn = i[0]\r\n tweet = i[1]\r\n\r\n ids.append(idn)\r\n tweets.append(tweet)\r\n\r\n return ids, tweets\r\n \r\n\r\ndef createDocuments(trainDirectory,testDirectory):\r\n docWithAllTraining = []\r\n\r\n for f in os.listdir(trainDirectory):\r\n if f != \"truth.txt\": #ignore the (possible) txt file at the end\r\n document = open(trainDirectory+'/'+f,\"r+\").read() \r\n\r\n goldDocument = open(trainDirectory+'/truth.txt',\"r+\").read().split(\"\\n\")\r\n\r\n # print(document)\r\n idName = f[:-4] #filename - .xml\r\n tree = ET.parse(trainDirectory+\"/\"+f)\r\n root = tree.getroot()\r\n\r\n #find gold values\r\n for line in goldDocument:\r\n if line != \"\":\r\n line = line.strip().split(\":::\")\r\n idGold = line[0].strip()\r\n gender = line[1].strip()\r\n ageGroup = line[2].strip()\r\n\r\n if idGold == idName:\r\n for child in root:\r\n tweet = child.text.strip()\r\n # print(tweet)\r\n\r\n docWithAllTraining.append([idName,tweet,gender,ageGroup])\r\n\r\n docWithAllTesting = []\r\n for f in os.listdir(testDirectory):\r\n if f != \"truth.txt\": #ignore the (possible) txt file at the end\r\n document = open(testDirectory+'/'+f,\"r+\").read() \r\n\r\n # print(document)\r\n idName = f[:-4] #filename - .xml\r\n tree = ET.parse(testDirectory+\"/\"+f)\r\n root = tree.getroot()\r\n\r\n for child in root:\r\n tweet = child.text.strip()\r\n # print(tweet)\r\n\r\n docWithAllTesting.append([idName,tweet])\r\n\r\n\r\n return docWithAllTraining, docWithAllTesting\r\n\r\n\r\ndef url_to_placeholder(tweet):\r\n tweet= re.sub(r\"http\\S+\", \"url\", str(tweet))\r\n return tweet\r\n\r\ndef number_to_placeholder(tweet):\r\n tweet = re.sub(r'[0-9]+', \"num\", str(tweet))\r\n return tweet\r\n\r\ndef tokenize_tweet(tweet):\r\n tokenizer = TweetTokenizer(reduce_len=True)\r\n tokens = tokenizer.tokenize(tweet)\r\n return \" \".join(tokens)\r\n\r\ndef clean_tweets(tweet):\r\n tweet = tokenize_tweet(tweet)\r\n cleaned_tweet = url_to_placeholder(number_to_placeholder(tweet))\r\n return cleaned_tweet\r\n \r\ndef preprocessData(documents):\r\n for idx, i in enumerate(documents):\r\n tweet = i[1]\r\n tweet = clean_tweets(tweet)\r\n\r\n documents[idx][1] = tweet\r\n\r\n return(documents)\r\n\r\ndef createConfusionMatrix(confusionMatrix,part,language):\r\n print()\r\n if part == \"gender\":\r\n labels = ['F','M']\r\n elif part == \"age\":\r\n labels = ['18-24','25-34','35-49','50-XX']\r\n else:\r\n labels = ['18-24','25-34','35-49','50-XX','F','M']\r\n\r\n\r\n print(\"{:10s}\".format(\"\"), end=\"\")\r\n [print(\"{:<8s}\".format(item), end=\"\") for item in labels]\r\n print()\r\n\r\n for idx, elem in enumerate(confusionMatrix):\r\n print(\"{:10s}\".format(labels[idx]), end=\"\")\r\n [print(\"{:<8d}\".format(el), end=\"\") for el in elem]\r\n print()\r\n\r\n \r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"svmFinal.py","file_name":"svmFinal.py","file_ext":"py","file_size_in_byte":13453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"441646654","text":"#coding: utf-8\r\n\r\nlistas = [[]]\r\nwhile True:\r\n print(\"1-Cadastrar pessoa\")\r\n print(\"2-Listar todos os cadastros\")\r\n print(\"3-Procurar cadastro\")\r\n opcao1 = int(input())\r\n if opcao1 == 1:\r\n nova = []\r\n id = input(\"Id da pessoa\")\r\n nome = input(\"Digite o nome da pessoa\")\r\n idade = input(\"Idade da pessoa\")\r\n nova.append(id)\r\n nova.append(nome.title())\r\n nova.append(idade)\r\n listas.append(nova)\r\n\r\n\r\n elif opcao1 == 2:\r\n for mostrar in listas:\r\n try:\r\n print(\"Nome: %s - Idade: %s - ID: %s\" % (mostrar[1], mostrar[2], mostrar[0]))\r\n except:\r\n print(\"Essa pessoa não possui algum dos valores a seguir: Nome, Idade, ID\")\r\n\r\n elif opcao1 == 3:\r\n print(\"Em construção\")\r\n \r\n else:\r\n print(\"Opção invalida!!\")\r\n","sub_path":"Barbearia.py","file_name":"Barbearia.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"454693352","text":"from typing import Optional, List\r\n\r\nfrom arcticpy import CCDPhase\r\nfrom arcticpy import TrapInstantCapture\r\n\r\nfrom autoconf.dictable import Dictable\r\n\r\n\r\nclass AbstractCTI:\r\n @property\r\n def trap_list(self):\r\n raise NotImplementedError\r\n\r\n @property\r\n def delta_ellipticity(self):\r\n return sum([trap.delta_ellipticity for trap in self.trap_list])\r\n\r\n\r\nclass CTI1D(AbstractCTI, Dictable):\r\n def __init__(\r\n self,\r\n trap_list: Optional[List[TrapInstantCapture]] = None,\r\n ccd: Optional[CCDPhase] = None,\r\n ):\r\n \"\"\"\r\n An object which determines the behaviour of CTI during 1D clocking.\r\n\r\n This includes the traps that capture and trail electrons and the CCD volume filling behaviour.\r\n\r\n Parameters\r\n ----------\r\n trap_list\r\n The traps on the dataset that capture and release electrons during clocking.\r\n ccd\r\n The CCD volume filling parameterization which dictates how an electron cloud fills pixels and thus\r\n how it is subject to traps.\r\n \"\"\"\r\n self._trap_list = trap_list\r\n self.ccd = ccd\r\n\r\n @property\r\n def trap_list(self):\r\n return self._trap_list\r\n\r\n\r\nclass CTI2D(AbstractCTI, Dictable):\r\n def __init__(\r\n self,\r\n parallel_trap_list: Optional[List[TrapInstantCapture]] = None,\r\n parallel_ccd: Optional[CCDPhase] = None,\r\n serial_trap_list: Optional[List[TrapInstantCapture]] = None,\r\n serial_ccd: Optional[CCDPhase] = None,\r\n ):\r\n \"\"\"\r\n An object which determines the behaviour of CTI during 2D parallel and serial clocking.\r\n\r\n This includes the traps that capture and trail electrons and the CCD volume filling behaviour.\r\n\r\n Parameters\r\n ----------\r\n parallel_trap_list\r\n The traps on the dataset that capture and release electrons during parallel clocking.\r\n parallel_ccd\r\n The CCD volume filling parameterization which dictates how an electron cloud fills pixel in the parallel\r\n direction and thus how it is subject to traps.\r\n serial_trap_list\r\n The traps on the dataset that capture and release electrons during serial clocking.\r\n serial_ccd\r\n The CCD volume filling parameterization which dictates how an electron cloud fills pixel in the serial\r\n direction and thus how it is subject to traps.\r\n \"\"\"\r\n self.parallel_trap_list = parallel_trap_list\r\n self.parallel_ccd = parallel_ccd\r\n self.serial_trap_list = serial_trap_list\r\n self.serial_ccd = serial_ccd\r\n\r\n @property\r\n def trap_list(self) -> List[TrapInstantCapture]:\r\n \"\"\"\r\n Combine the parallel and serial trap lists to make an overall list of traps in the model.\r\n\r\n This is not a straight forward list addition, because **PyAutoFit** model's store the `parallel_traps` and\r\n `serial_traps` entries as a `ModelInstance`. This object does not allow for straight forward list addition.\r\n \"\"\"\r\n parallel_traps = self.parallel_trap_list or []\r\n serial_traps = self.serial_trap_list or []\r\n\r\n return [trap for trap in parallel_traps] + [trap for trap in serial_traps]\r\n\r\n\r\ndef is_parallel_fit(model):\r\n if model.parallel_ccd is not None and model.serial_ccd is None:\r\n return True\r\n return False\r\n\r\n\r\ndef is_serial_fit(model):\r\n if model.parallel_ccd is None and model.serial_ccd is not None:\r\n return True\r\n return False\r\n\r\n\r\ndef is_parallel_and_serial_fit(model):\r\n if model.parallel_ccd is not None and model.serial_ccd is not None:\r\n return True\r\n return False\r\n","sub_path":"autocti/model/model_util.py","file_name":"model_util.py","file_ext":"py","file_size_in_byte":3711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"253578666","text":"\"\"\"\nPS Model Creator\n----------------\n\nThis module provides convenience functions for model creation of the ``PS``.\n\"\"\"\nimport logging\nimport shutil\n\nfrom omc3.model.accelerators.accelerator import AccExcitationMode\nfrom omc3.model.accelerators.ps import Ps\nfrom omc3.model.constants import ERROR_DEFFS_TXT\nfrom omc3.model.model_creators.abstract_model_creator import ModelCreator\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass PsModelCreator(ModelCreator):\n @classmethod\n def get_madx_script(cls, accel: Ps) -> str:\n madx_script = accel.get_base_madx_script()\n replace_dict = {\n \"USE_ACD\": str(int(accel.excitation == AccExcitationMode.ACD)),\n \"DPP\": accel.dpp,\n \"OUTPUT\": str(accel.model_dir),\n }\n madx_template = accel.get_file(\"twiss.mask\").read_text()\n madx_script += madx_template % replace_dict\n return madx_script\n\n @classmethod\n def get_correction_check_script(cls, accel: Ps, corr_file: str, chrom: bool) -> str:\n raise NotImplemented(\"Correction check is not implemented for the Ps model creator yet. \")\n\n @classmethod\n def prepare_run(cls, accel: Ps) -> None:\n # get path of file from PS model directory (without year at the end)\n shutil.copy(accel.get_file(\"error_deff.txt\"), accel.model_dir / ERROR_DEFFS_TXT)\n","sub_path":"omc3/model/model_creators/ps_model_creator.py","file_name":"ps_model_creator.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"211037450","text":"import numpy as np\r\nimport cv2\r\nimport skimage\r\nfrom matplotlib import pyplot as plt\r\nfrom time import time\r\nimport scipy.misc\r\nfrom sklearn.decomposition import MiniBatchDictionaryLearning\r\nfrom sklearn.feature_extraction.image import extract_patches_2d\r\nfrom sklearn.feature_extraction.image import reconstruct_from_patches_2d\r\n\r\n\r\ndef show_with_diff(image, reference, title):\r\n \"\"\"Helper function to display denoising\"\"\"\r\n plt.figure(figsize=(5, 3.3))\r\n plt.subplot(1, 2, 1)\r\n plt.title('Image')\r\n plt.imshow(image, vmin=0, vmax=1, cmap=plt.cm.gray,\r\n interpolation='nearest')\r\n plt.xticks(())\r\n plt.yticks(())\r\n plt.subplot(1, 2, 2)\r\n difference = image - reference\r\n\r\n plt.title('Difference (norm: %.2f)' % np.sqrt(np.sum(difference ** 2)))\r\n plt.imshow(difference, vmin=-0.5, vmax=0.5, cmap=plt.cm.gray,\r\n interpolation='nearest')\r\n plt.xticks(())\r\n plt.yticks(())\r\n plt.suptitle(title, size=16)\r\n plt.subplots_adjust(0.02, 0.02, 0.98, 0.79, 0.02, 0.2)\r\n #plt.savefig('omp_frames/simpleframe_{}.png'.format(framenum),image)\r\n scipy.misc.imsave('omp_frames/simpleframe_{}.png'.format(framenum), image)\r\n\r\n##import video##\r\n\r\ncap = cv2.VideoCapture('samples/sam1.mp4')\r\n\r\nframenum = 0\r\nwhile(cap.isOpened()):\r\n framenum += 1\r\n ret, frame = cap.read()\r\n if ret:\r\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n #cv2.imshow('frame',gray)\r\n gray = np.asarray(gray, dtype=np.float32)\r\n gray/=255\r\n face=gray\r\n # downsample for higher speed\r\n #face = gray[::2, ::2] + gray[1::2, ::2] + gray[::2, 1::2] + gray[1::2, 1::2]\r\n #face /= 4.0\r\n height, width = face.shape\r\n\r\n # Distort the right half of the image\r\n print('Distorting image...')\r\n distorted = face.copy()\r\n distorted += 1* np.random.randn(height, width )\r\n\r\n# Extract all reference patches from the left half of the image\r\n print('Extracting reference patches...')\r\n t0 = time()\r\n patch_size = (7, 7)\r\n data = extract_patches_2d(gray, patch_size)\r\n data = data.reshape(data.shape[0], -1)\r\n data -= np.mean(data, axis=0)\r\n data /= np.std(data, axis=0)\r\n print('done in %.2fs.' % (time() - t0))\r\n print ('frame number =', framenum)\r\n\r\n# #############################################################################\r\n# Learn the dictionary from reference patches\r\n\r\n print('Learning the dictionary...')\r\n t0 = time()\r\n dico = MiniBatchDictionaryLearning(n_components=100, alpha=10, n_iter=500)\r\n V = dico.fit(data).components_\r\n dt = time() - t0\r\n print('done in %.2fs.' % dt)\r\n\r\n plt.figure(figsize=(4.2, 4))\r\n for i, comp in enumerate(V[:100]):\r\n plt.subplot(10, 10, i + 1)\r\n plt.imshow(comp.reshape(patch_size), cmap=plt.cm.gray_r,\r\n interpolation='nearest')\r\n plt.xticks(())\r\n plt.yticks(())\r\n plt.suptitle('Dictionary learned from face patches\\n' +\r\n 'Train time %.1fs on %d patches' % (dt, len(data)),\r\n fontsize=16)\r\n plt.subplots_adjust(0.08, 0.02, 0.92, 0.85, 0.08, 0.23)\r\n\r\n\r\n print('Extracting noisy patches... ')\r\n t0 = time()\r\n data = extract_patches_2d(distorted, patch_size)\r\n data = data.reshape(data.shape[0], -1)\r\n intercept = np.mean(data, axis=0)\r\n data -= intercept\r\n print('done in %.2fs.' % (time() - t0))\r\n\r\n transform_algorithms = [\r\n ('Orthogonal Matching Pursuit\\n1 atom', 'omp',\r\n {'transform_n_nonzero_coefs': 1})]\r\n\r\n reconstructions = {}\r\n for title, transform_algorithm, kwargs in transform_algorithms:\r\n print(title + '...')\r\n reconstructions[title] = face.copy()\r\n t0 = time()\r\n dico.set_params(transform_algorithm=transform_algorithm, **kwargs)\r\n code = dico.transform(data)\r\n patches = np.dot(code, V)\r\n\r\n patches += intercept\r\n patches = patches.reshape(len(data), *patch_size)\r\n if transform_algorithm == 'threshold':\r\n patches -= patches.min()\r\n patches /= patches.max()\r\n reconstructions[title] = reconstruct_from_patches_2d(\r\n patches, (height, width))\r\n dt = time() - t0\r\n print('done in %.2fs.' % dt)\r\n show_with_diff(reconstructions[title], face,\r\n title + ' (time: %.1fs)' % dt)\r\n\r\n #plt.show()\r\n\r\n\r\n\r\n\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\ncap.release()\r\n\r\n#show_with_diff(distorted, face, 'Distorted image')\r\n\r\n","sub_path":"frame_by_frame_omp.py","file_name":"frame_by_frame_omp.py","file_ext":"py","file_size_in_byte":4492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"440102049","text":"import numpy as np\nimport tensorflow as tf\nimport gym\nimport load_policy\nfrom model import Model\nfrom ant_model import AntModel\nfrom humanoid_model import HumanoidModel\nfrom behavior_cloning import BehaviorCloning\n\nclass DAgger:\n\n def __init__(self, behavior_cloner, expert_policy_file):\n\n self.behavior_cloner = behavior_cloner\n\n print('loading and building expert policy')\n self.policy_fn = load_policy.load_policy(expert_policy_file)\n print('loaded and built')\n\n def ask_expert(self, observations):\n\n new_actions = self.policy_fn(observations)\n new_actions = new_actions.reshape(new_actions.shape[0], new_actions.shape[-1])\n self.behavior_cloner.add_data(observations, new_actions)\n\n def run(self, n_iter=4, n_epochs=300, n_steps=500):\n\n self.behavior_cloner.train(n_epochs)\n returns_list = []\n\n for i in range(n_iter):\n\n total_return, new_observations = self.behavior_cloner.test(n_steps)\n self.ask_expert(new_observations)\n self.behavior_cloner.train(n_epochs)\n returns_list.append(total_return)\n\n total_return, obs = self.behavior_cloner.test(1000)\n returns_list.append(total_return)\n print(returns_list)\n\nif __name__ == \"__main__\":\n\n obs_file = '/home/elsa/Desktop/homework/hw1/Humanoid-v1_obs.npy'\n actions_file = '/home/elsa/Desktop/homework/hw1/Humanoid-v1_actions.npy'\n\n copyCat = BehaviorCloning('Humanoid-v1', HumanoidModel, obs_file, actions_file, batch_size=100)\n copyCat.model.load(\"humanoid_model.ckpt\")\n dAgger = DAgger(copyCat, 'experts/Humanoid-v1.pkl')\n\n dAgger.run()\n\n","sub_path":"hw1/DAgger.py","file_name":"DAgger.py","file_ext":"py","file_size_in_byte":1652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"323555048","text":"import threading \nimport time\n\nclass myThreading(threading.Thread):\n def __init__(self,threadId,name,counter):\n threading.Thread.__init__(self)\n self.threadId=threadId\n self.name=name\n self.counter=counter\n\n def run(self):\n print(\"starting\" + self.name)\n threadLock.acquire()\n print_time(self.name ,self.counter,3)\n threadLock.release()\n\ndef print_time(threadName,delay,counter):\n while counter:\n time.sleep(delay)\n print(\"%s:%s\"%(threadName,time.ctime(time.time())))\n counter -=1\n\n\nthreadLock=threading.Lock()\nthreads=[]\n\nthread1=myThreading(1,\"Thread-1\",2)\nthread2=myThreading(2,\"Thread-2\",4)\n\nthread1.start()\nthread2.start()\nthreads.append(thread1)\nthreads.append(thread2)\nfor i in threads:\n i.join()\nprint(\"exit main thread\")\n","sub_path":"scn.py","file_name":"scn.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"361794363","text":"\"\"\"\nThis problem was asked by Google.\n\nFind the minimum number of coins required to make n cents.\n\nYou can use standard American denominations, that is, 1¢, 5¢, 10¢, and 25¢.\n\nFor example, given n = 16, return 3 since we can make it with a 10¢, a 5¢, and a 1¢.\n\"\"\"\n\ndef number_of_coins(value):\n coins = [25, 10, 5, 1]\n no_coins = 0\n for i in coins:\n if value > 0:\n no_coins = no_coins + value // i\n print(str(i) + \":- \" + str(value //i))\n value = value % i\n\n return no_coins\n\nprint(\"Number of coins: \" + str(number_of_coins(123456)))","sub_path":"138_Google.py","file_name":"138_Google.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"64625886","text":"# Copyright (c) 2019, IRIS-HEP\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# * Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nfrom collections import OrderedDict\n\n\n# noinspection PyClassHasNoInit\nclass TestXAODTransformer:\n\n def test_arrow_table(self, mocker):\n import mock\n from servicex.transformer.xaod_transformer import XAODTransformer\n\n attr_names = [\n \"Electrons.pt()\", \"Electrons.eta()\", \"Muons.e()\"\n ]\n\n from servicex.transformer.xaod_events import XAODEvents\n iterator = mock.MagicMock(XAODEvents)\n iterator.iterate = mock.Mock(return_value=iter([\n {'Electrons': [\n {'pt()': 4.0, 'eta()': 5.0},\n {'pt()': 8.0, 'eta()': 10.0}\n ],\n 'Muons': [\n {'e()': 1.0}, {'e()': 2.0}, {'e()': 3.0}\n ]\n },\n {'Electrons': [\n {'pt()': 14.0, 'eta()': 15.0},\n {'pt()': 18.0, 'eta()': 20.0}\n ],\n 'Muons': [\n {'e()': 1.0}, {'e()': 2.0}, {'e()': 3.0}\n ]\n }\n ]))\n\n iterator.attr_name_list = attr_names\n iterator.get_entry_count = mock.Mock(return_value=1000)\n transformer = XAODTransformer(iterator)\n table = transformer.arrow_table(2, 100).next()\n\n assert table.column_names == ['Electrons_pt',\n 'Muons_e',\n 'Electrons_eta']\n\n assert len(table) == 2\n assert table.num_rows == 2\n assert table.num_columns == 3\n assert table.shape == (2, 3)\n pydict = table.to_pydict()\n print(pydict)\n assert pydict == OrderedDict([\n ('Electrons_pt', [[4.0, 8.0], [14.0, 18.0]]),\n ('Muons_e', [[1.0, 2.0, 3.0], [1.0, 2.0, 3.0]]),\n ('Electrons_eta', [[5.0, 10.0], [15.0, 20.0]])\n ])\n\n iterator.iterate.assert_called_with(100)\n","sub_path":"servicex/transformer/tests/test_xaod_transformer.py","file_name":"test_xaod_transformer.py","file_ext":"py","file_size_in_byte":3404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"121087134","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/io/RulingParser.py\n# Compiled at: 2019-12-11 16:37:58\n\"\"\"HTML Parser for extracting card rulings from the WW online rulings list.\"\"\"\nimport re\nfrom logging import Logger\nfrom sqlobject import SQLObjectNotFound\nfrom sutekh.base.io.SutekhBaseHTMLParser import SutekhBaseHTMLParser, HTMLStateError, LogState, LogStateWithInfo\nfrom sutekh.base.core.BaseAdapters import IAbstractCard\nfrom sutekh.core.SutekhObjectMaker import SutekhObjectMaker\n\nclass RuleDict(dict):\n \"\"\"Dictionary object which holds the extracted rulings information.\"\"\"\n _aSectionKeys = [\n 'title', 'card']\n _oMasterOut = re.compile('\\\\s*-\\\\s*Master\\\\s*\\\\:?\\\\s*Out\\\\-of\\\\-Turn$')\n _oCommaThe = re.compile('\\\\s*\\\\,\\\\s*The$')\n _dOddTitles = {\"Absilmilard's Army\": \"Absimiliard's Army\", \n 'Ankara Citadel': 'The Ankara Citadel, Turkey', \n 'Carlotta': 'Carlotta Giovanni', \n \"Donal O'Connor\": \"Dónal O'Connor\", \n 'Herald of Topeth': 'Herald of Topheth', \n 'Illusions of Kindred': 'Illusions of the Kindred', \n 'Khobar Towers': 'Khobar Towers, Al-Khubar', \n 'Mehemet of the Ahl-i-Batin': 'Mehemet of the Ahl-i-Batin (Mage)', \n 'Lazar Dobrescu': 'Lázár Dobrescu', \n 'Merill Molitor': 'Merrill Molitor', \n 'Peace Treaty:shado': 'Peace Treaty', \n 'Rotschreck': 'Rötschreck', \n 'Seattle Committe': 'Seattle Committee', \n 'Shackles of Enkindu': 'Shackles of Enkidu', \n 'Shadow Court Satyr': 'Shadow Court Satyr (Changeling)', \n 'Smiling Jack the Anarch': 'Smiling Jack, The Anarch', \n 'Tereza Rotas': 'Tereza Rostas', \n 'The Eldest Command the Undeath': 'The Eldest Command Undeath', \n 'Ur-Shulgi': 'Ur-Shulgi, The Shepherd'}\n\n def __init__(self, oLogger):\n self._oLogger = oLogger\n super(RuleDict, self).__init__()\n self._oMaker = SutekhObjectMaker()\n\n def _find_card(self, sTitle):\n \"\"\"Find the abstract card this rules applies to.\"\"\"\n sTitle = self._oMasterOut.sub('', sTitle)\n sTitle = self._oCommaThe.sub('', sTitle)\n try:\n return IAbstractCard(sTitle)\n except SQLObjectNotFound:\n pass\n\n try:\n return IAbstractCard(self._dOddTitles[sTitle])\n except KeyError:\n pass\n except SQLObjectNotFound:\n pass\n\n try:\n return IAbstractCard('The ' + sTitle)\n except SQLObjectNotFound:\n pass\n\n return\n\n def clear_rule(self):\n \"\"\"Remove current contents of the rule.\"\"\"\n dKeep = {}\n for sKey in self._aSectionKeys:\n if sKey in self:\n dKeep[sKey] = self[sKey]\n\n self.clear()\n for sKey, sValue in dKeep.items():\n self[sKey] = sValue\n\n def save(self):\n \"\"\"Add the rulings to the database.\"\"\"\n if not ('title' in self and 'code' in self and 'text' in self):\n return\n else:\n if 'card' not in self:\n self['card'] = self._find_card(self['title'])\n if self['card'] is None:\n return\n self._oLogger.info('Card: %s', self['card'].name)\n oRuling = self._oMaker.make_ruling(self['text'], self['code'])\n if 'url' in self:\n oRuling.url = self['url']\n oRuling.syncUpdate()\n self['card'].addRuling(oRuling)\n return\n\n\nclass NoSection(LogState):\n \"\"\"Not in any ruling section.\"\"\"\n\n def transition(self, sTag, _dAttr):\n \"\"\"Transition to InSection if needed.\"\"\"\n if sTag == 'p':\n return InSection(RuleDict(self._oLogger), self._oLogger)\n return self\n\n\nclass InSection(LogStateWithInfo):\n \"\"\"In a ruling section.\"\"\"\n\n def transition(self, sTag, _dAttr):\n \"\"\"Transition to SectionTitle or NoSection as needed.\"\"\"\n if sTag == 'b':\n return SectionTitle(self._dInfo, self._oLogger)\n if sTag == 'p':\n return InSection(RuleDict(self._oLogger), self._oLogger)\n return NoSection(self._oLogger)\n\n\nclass SectionTitle(LogStateWithInfo):\n \"\"\"In the title of the section.\"\"\"\n\n def transition(self, sTag, _dAttr):\n \"\"\"Transition to SectionWithTitle if needed.\"\"\"\n if sTag == 'b':\n raise HTMLStateError('Unexpected tag in SectionTitle', sTag, self._sData)\n elif sTag == '/b':\n self._dInfo['title'] = self._sData.strip().strip(':')\n return SectionWithTitle(self._dInfo, self._oLogger)\n return self\n\n\nclass SectionWithTitle(LogStateWithInfo):\n \"\"\"In a section with a known title.\"\"\"\n\n def transition(self, sTag, _dAttr):\n \"\"\"Transition to SectionRule, InSection or NoSection if needed.\"\"\"\n if sTag == 'ul':\n return SectionRule(self._dInfo, self._oLogger)\n if sTag == 'p':\n return InSection(RuleDict(self._oLogger), self._oLogger)\n if sTag == '/ul':\n return NoSection(self._oLogger)\n return self\n\n\nclass SectionRule(LogStateWithInfo):\n \"\"\"In a ruling in the section.\"\"\"\n\n def transition(self, sTag, _dAttr):\n \"\"\"Transition to the appropriate InRule State.\"\"\"\n if sTag == 'li':\n return InRuleText(self._dInfo, self._oLogger)\n if sTag == '/ul':\n return NoSection(self._oLogger)\n return self\n\n\nclass InRuleText(LogStateWithInfo):\n \"\"\"In the text of a ruling.\"\"\"\n oCodePattern = re.compile('\\\\[[^]]*\\\\]')\n\n def transition(self, sTag, dAttr):\n \"\"\"Transition to SectionRule if needed.\"\"\"\n if sTag == 'a':\n if 'text' not in self._dInfo:\n self._dInfo['text'] = self._sData.strip()\n self._dInfo['url'] = dAttr['href']\n return InRuleUrl(self._dInfo, self._oLogger)\n if sTag == '/li':\n if 'code' not in self._dInfo:\n oMatch = self.oCodePattern.search(self._sData)\n if oMatch:\n self._dInfo['code'] = oMatch.group()\n self._dInfo['text'] = self.oCodePattern.sub('', self._sData).strip()\n self._dInfo.save()\n self._dInfo.clear_rule()\n return SectionRule(self._dInfo, self._oLogger)\n return self\n\n\nclass InRuleUrl(LogStateWithInfo):\n \"\"\"In the url associated with this ruling.\"\"\"\n\n def transition(self, sTag, _dAttr):\n \"\"\"Transition to SectionRule if needed.\"\"\"\n if sTag == 'a':\n raise HTMLStateError('Unexpected tag in InRuleUrl', sTag, self._sData)\n elif sTag == '/a':\n self._dInfo['code'] = self._sData.strip()\n return InRuleText(self._dInfo, self._oLogger)\n return self\n\n\nclass RulingParser(SutekhBaseHTMLParser):\n \"\"\"Actual Parser for the WW rulings HTML files.\"\"\"\n\n def __init__(self, oLogHandler):\n self._oLogger = Logger('WW Rulings parser')\n if oLogHandler is not None:\n self._oLogger.addHandler(oLogHandler)\n super(RulingParser, self).__init__()\n return\n\n def reset(self):\n \"\"\"Reset the parser\"\"\"\n super(RulingParser, self).reset()\n self._oState = NoSection(self._oLogger)","sub_path":"pycfiles/Sutekh-1.0.0-py2.7/RulingParser.py","file_name":"RulingParser.py","file_ext":"py","file_size_in_byte":7347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"8310019","text":"# Create your views here.\nfrom __future__ import unicode_literals\n\nfrom rest_framework import views\nfrom rest_framework.response import Response\nfrom .models import *\nfrom rest_framework.authtoken.views import ObtainAuthToken\nfrom .serializer import LoginSerializer\nfrom rest_framework.authtoken.serializers import AuthTokenSerializer\nfrom rest_framework.status import HTTP_400_BAD_REQUEST\nfrom django.http import HttpResponse\nimport datetime\nfrom django.contrib.auth import login\nfrom rest_framework_swagger.views import get_swagger_view\n\nschema_view = get_swagger_view(title='Pastebin API')\nfrom django.conf import settings\n#from sett import *\n# Create your views here.\n\n\n\nclass ObtainExpiringAuthToken(ObtainAuthToken):\n\n \"\"\"View enabling username/password exchange for expiring token.\"\"\"\n model = Token\n def post(self, request):\n print(\"heelo\")\n \"\"\"Validate User has valid token or not.\"\"\"\n username = request.data[\"username\"]\n user_obj = User.objects.get(username=username)\n k = Mapping_Record.object.filter(uuid = \"abc\")\n k.update(schema = '{\"hgf\":\"dkdk\"}')\n\n\n \"\"\"Respond to POSTed username/password with token and store login history.\"\"\"\n serializer = AuthTokenSerializer(data=request.data)\n if serializer.is_valid():\n token, _ = Token.objects.get_or_create(\n user=serializer.validated_data['user']\n )\n token, created = Token.objects.get_or_create(user=user_obj)\n\n if user_obj is not None:\n if user_obj.is_active:\n login(request, serializer.validated_data[\"user\"])\n\n data = {}\n now = datetime.datetime.now()\n data['success'] = True\n data['message'] = 'Logged In Successfully'\n data['auth_key'] = token.key\n data[\"username\"] = username\n return Response(data)\n\n return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)\n\n\nclass Upload_schema(views.APIView):\n def post(self,request):\n schema = request.data[\"schema\"]\n table_id = request.data[\"table_id\"]\n return HttpResponse(\"hello\")\n\n# if request.method == \"POST\":\n# return HttpResponse(\"hello\")\n# else:\n# return HttpResponse(\"error\")\n\n\n\n\n\n\n","sub_path":"table_dump/galilio/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"145215896","text":"import pandas as pd\n\n\ndef get_model_field_names(model, ignore_fields=['content_object']):\n \"\"\"\n :param model: a django model class\n :param ignore_fields: is a list of field names to ignore by default\n :return: all model field names (as strings) and returns a list of them ignoring the ones we don't work (like\n the 'content_objects' field)\n \"\"\"\n model_fields = model._meta.get_field()\n model_field_names = list(set([f.name for f in model_fields if f.name not in ignore_fields]))\n return model_field_names\n\n\ndef get_lookup_fields(model, fields=None):\n \"\"\"\n\n :param models: a Django model class\n :param fields: is a list of field name strings.\n :return: This method compares the lookups we want vs the lookups that are avaulable. It gnores the unavailable\n fields we passed.\n \"\"\"\n model_field_names = get_model_field_names(model)\n if fields is not None:\n \"\"\"\n we'll iterate through all the passed fields)names\n and verify they are valid by only including the valid ones\n \"\"\"\n lookup_fields = []\n for x in fields:\n if \"__\" in x:\n lookup_fields.append(x)\n elif x in model_field_names:\n lookup_fields.append(x)\n else:\n \"\"\"\n No field names were passed, use the default model fields\n \"\"\"\n lookup_fields = model_field_names\n return lookup_fields\n\n\ndef qs_to_dataset(qs, fields=None):\n \"\"\"\n :param qs: is any Django queryset\n :param fields: list of field name strings, ignoring non-model field names\n :return: This method is the final step, simply calling the fields we fromed on the queryset\n and turning it into a list of dictionaries with key/value pairs.\n \"\"\"\n lookup_fields = get_lookup_fields(qs.model, fields=fields)\n return list(qs.values(*lookup_fields))\n\n\ndef convert_to_dataframe(qs, fields=None, index=None):\n \"\"\"\n\n :param qs: a queryset from django\n :param fields: is a list of filed names from the Model of the Queryset\n :param index: is thee preferred index column we want out dataframe to be set to\n :return: Using the methods from above, we can easyly build a dataframe from this data.\n \"\"\"\n lookup_fields = get_lookup_fields(qs.model, fields=fields)\n index_col = None\n if index in lookup_fields:\n index_col = index\n elif \"id\" in lookup_fields:\n index_col = 'id'\n values = qs_to_dataset(qs, fields=fields)\n df = pd.DataFrame.from_records(values, columns=lookup_fields, index=index_col)\n return df\n\n","sub_path":"digitalSoil/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"372163191","text":"import argparse\nfrom overrides import overrides\n\nfrom sacrerouge.datasets.duc_tac.duc2001 import tasks\nfrom sacrerouge.commands import DatasetSetupSubcommand\n\n\n@DatasetSetupSubcommand.register('duc2001')\nclass DUC2001Subcommand(DatasetSetupSubcommand):\n @overrides\n def add_subparser(self, parser: argparse._SubParsersAction):\n description = 'Setup the DUC 2001 dataset'\n self.parser = parser.add_parser('duc2001', description=description, help=description)\n self.parser.add_argument(\n 'data_root',\n type=str,\n help='The path to the root of the repository with the DUC/TAC data (https://github.com/danieldeutsch/duc-tac-data)'\n )\n self.parser.add_argument(\n 'output_dir',\n type=str,\n help='The directory where the data should be saved'\n )\n self.parser.set_defaults(subfunc=self.run)\n\n @overrides\n def run(self, args):\n tasks.setup(args.data_root, args.output_dir)\n","sub_path":"sacrerouge/datasets/duc_tac/duc2001/subcommand.py","file_name":"subcommand.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"403208036","text":"\"\"\"Trainining script for WaveRNN vocoder\n\nusage: train.py [options]\n\noptions:\n --data-root= Directory contains preprocessed features.\n --checkpoint-dir= Directory where to save model checkpoints [default: checkpoints].\n --output-dir= Output Directory [default: model_outputs]\n --hparams= Hyper parameters [default: ].\n --preset= Path of preset parameters (json).\n --checkpoint= Restore model from checkpoint path if given.\n --restore-parts= Restore part of the model.\n --log-event-path= Log event path.\n --reset-optimizer Reset optimizer.\n --speaker-id= Use specific speaker of data in case for multi-speaker datasets.\n --no-cuda Don't run on GPU\n -h, --help Show this help message and exit\n\"\"\"\nimport os\nimport pickle\nimport time\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom docopt import docopt\nfrom torch import optim\nfrom torch.utils.data import Dataset, DataLoader\n\nimport hparams\nfrom hparams import hparams\nimport utils.display as display\nfrom utils.dsp import DSP\nfrom models import *\n\nclass AudioDataset(Dataset):\n def __init__(self, ids, path):\n self.path = path\n self.metadata = ids\n\n def __getitem__(self, index):\n file = self.metadata[index]\n m = np.load(f'{self.path}/mel/{file}.npy')\n x = np.load(f'{self.path}/quant/{file}.npy')\n return m, x\n\n def __len__(self):\n return len(self.metadata)\n\n\ndef collate(batch):\n pad = 2\n mel_win = seq_len // dsp.hop_length + 2 * pad\n max_offsets = [x[0].shape[-1] - (mel_win + 2 * pad) for x in batch]\n mel_offsets = [np.random.randint(0, offset) for offset in max_offsets]\n sig_offsets = [(offset + pad) * dsp.hop_length for offset in mel_offsets]\n\n mels = [x[0][:, mel_offsets[i]:mel_offsets[i] + mel_win] \\\n for i, x in enumerate(batch)]\n\n coarse = [x[1][sig_offsets[i]:sig_offsets[i] + seq_len + 1] \\\n for i, x in enumerate(batch)]\n\n mels = np.stack(mels).astype(np.float32)\n coarse = np.stack(coarse).astype(np.int64)\n\n mels = torch.FloatTensor(mels)\n coarse = torch.LongTensor(coarse)\n\n x_input = 2 * coarse[:, :seq_len].float() / (2**hparams.bits - 1.) - 1.\n y_coarse = coarse[:, 1:]\n\n return x_input, mels, y_coarse\n\n\ndef train(model, optimiser, epochs, batch_size, classes, seq_len, step, lr=1e-4):\n\n for p in optimiser.param_groups:\n p['lr'] = lr\n criterion = nn.NLLLoss().to(device)\n\n for e in range(epochs):\n trn_loader = DataLoader(dataset, collate_fn=collate, batch_size=hparams.batch_size,\n num_workers=hparams.num_workers, shuffle=True, pin_memory=(not no_cuda))\n\n running_loss = 0.\n val_loss = 0.\n start = time.time()\n running_loss = 0.\n\n iters = len(trn_loader)\n\n #with torch.autograd.profiler.profile(enabled=False, use_cuda=True) as prof:\n with torch.autograd.detect_anomaly():\n #with torch.autograd.profiler.emit_nvtx(enabled=False):\n for i, (x, m, y) in enumerate(trn_loader) :\n\n x, m, y = x.to(device), m.to(device), y.to(device)\n\n if no_cuda:\n y_hat = model(x, m)\n else:\n y_hat = torch.nn.parallel.data_parallel(model, (x, m))\n\n y_hat = y_hat.transpose(1, 2).unsqueeze(-1)\n y = y.unsqueeze(-1)\n loss = criterion(y_hat, y)\n\n optimiser.zero_grad()\n loss.backward(retain_graph=True)\n optimiser.step()\n running_loss += loss.item()\n\n speed = (i + 1) / (time.time() - start)\n avg_loss = running_loss / (i + 1)\n\n step += 1\n\n k = step // 1000\n print('Epoch: %i/%i -- Batch: %i/%i -- Loss: %.3f -- Speed: %.2f steps/sec -- Step: %ik '%\n (e + 1, epochs, i + 1, iters, avg_loss, speed, k))\n\n #print(prof.table(sort_by='cuda_time'))\n #prof.export_chrome_trace(f'{output_path}/chrome_trace')\n\n torch.save(model.state_dict(), MODEL_PATH)\n np.save(checkpoint_step_path, step)\n if e % 5 == 0:\n generate(e, data_root, output_path, test_ids)\n print(' ')\n\n\ndef generate(epoch, data_root, output_path, test_ids, samples=3):\n test_mels = [np.load(f'{data_root}/mel/{dataset_id}.npy') for dataset_id in test_ids[:samples]]\n ground_truth = [np.load(f'{data_root}/quant/{dataset_id}.npy') for dataset_id in test_ids[:samples]]\n os.makedirs(f'{output_path}/{epoch}', exist_ok=True)\n\n for i, (gt, mel) in enumerate(zip(ground_truth, test_mels)):\n print('\\nGenerating: %i/%i' % (i+1, samples))\n gt = 2 * gt.astype(np.float32) / (2**hparams.bits - 1.) - 1.\n dsp.save_wav(gt, f'{output_path}/{epoch}/target_{i}.wav')\n output = model.generate(mel)\n dsp.save_wav(output, f'{output_path}/{epoch}/generated_{i}.wav')\n\n\nif __name__ == \"__main__\":\n args = docopt(__doc__)\n print(\"Command line args:\\n\", args)\n checkpoint_dir = args[\"--checkpoint-dir\"]\n output_path = args[\"--output-dir\"]\n checkpoint_path = args[\"--checkpoint\"]\n checkpoint_restore_parts = args[\"--restore-parts\"]\n preset = args[\"--preset\"]\n\n data_root = args[\"--data-root\"]\n if data_root is None:\n data_root = os.join(os.dirname(__file__), \"data\", \"ljspeech\")\n\n log_event_path = args[\"--log-event-path\"]\n reset_optimizer = args[\"--reset-optimizer\"]\n no_cuda = args[\"--no-cuda\"]\n\n device = torch.device(\"cpu\" if no_cuda else \"cuda\")\n\n # Load preset if specified\n if preset is not None:\n with open(preset) as f:\n hparams.parse_json(f.read())\n # Override hyper parameters\n hparams.parse(args[\"--hparams\"])\n assert hparams.name == \"WaveRNN\"\n #print(hparams_debug_string())\n\n dsp = DSP(hparams)\n hparams.hop_length=dsp.hop_length\n seq_len = dsp.hop_length * 5\n step = 0\n\n os.makedirs(f'{checkpoint_dir}/', exist_ok=True)\n\n MODEL_PATH = f'{checkpoint_dir}/model.pyt'\n #data_root = f'data/'\n checkpoint_step_path = f'{checkpoint_dir}/model_step.npy'\n os.makedirs(output_path, exist_ok=True)\n\n with open(os.path.join(data_root, 'dataset_ids.pkl'), 'rb') as f:\n dataset_ids = pickle.load(f)\n test_ids = dataset_ids[-50:]\n dataset_ids = dataset_ids[:-50]\n\n dataset = AudioDataset(dataset_ids, data_root)\n data_loader = DataLoader(dataset, collate_fn=collate, batch_size=hparams.batch_size,\n num_workers=hparams.num_workers, shuffle=True)\n\n model = Model(device, rnn_dims=hparams.rnn_dims, fc_dims=hparams.fc_dims, bits=hparams.bits, pad=hparams.pad,\n upsample_factors=hparams.upsample_factors, feat_dims=hparams.feat_dims,\n compute_dims=hparams.compute_dims, res_out_dims=hparams.res_out_dims, res_blocks=hparams.res_blocks).to(device)\n\n if not os.path.exists(MODEL_PATH):\n torch.save(model.state_dict(), MODEL_PATH)\n else:\n print(\"\\t\\t Loading saved state\")\n model.load_state_dict(torch.load(MODEL_PATH))\n\n optimiser = optim.Adam(model.parameters())\n train(model, optimiser, epochs=hparams.epochs, batch_size=hparams.batch_size, classes=2**hparams.bits,\n seq_len=seq_len, step=step, lr=hparams.lr)\n\n generate(step, data_root, output_path, test_ids)\n\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":7590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"616025053","text":"import numpy as np\nfrom glob import glob\nimport yaml\nfrom scipy.ndimage import zoom\nimport matplotlib.pyplot as plt\n\n# Keras\nimport keras\nfrom keras.preprocessing.image import load_img\nfrom keras.preprocessing.image import img_to_array\n\n\nclass DataHandler(keras.utils.Sequence):\n \"\"\"Generates Samples for Keras\"\"\"\n\n def __init__(self,\n dir,\n epoch_size,\n batch_size=64,\n initial_scale=1,\n scale=4,\n bord=200,\n crop_height=200,\n crop_weidth=200,\n shuffle=True,\n augment=False):\n self.dir = dir\n self.batch_size = batch_size\n self.epoch_size = epoch_size\n self.init_scale = initial_scale\n self.scale = scale\n self.bord = bord\n self.crop_height = crop_height\n self.crop_weidth = crop_weidth\n self.shuffle = shuffle\n self.augment = augment\n self.settings = locals()\n _ = self.settings.pop('self')\n\n self.images = glob(dir + '/*.jpg')\n if self.epoch_size > len(self.images) // self.batch_size:\n self.epoch_size = None\n self.on_epoch_end()\n\n def __len__(self):\n \"\"\"Denotes the number of batches per epoch\"\"\"\n return int(np.floor(len(self.images) / self.batch_size))\n\n def on_epoch_end(self):\n \"\"\"Updates indexes after each epoch\"\"\"\n self.indexes = np.arange(len(self.images))\n if self.shuffle:\n np.random.shuffle(self.indexes)\n\n @staticmethod\n def get_image_array(path):\n return img_to_array(load_img(path))\n\n def __getitem__(self, index):\n \"\"\"Generate one batch of Samples\"\"\"\n indexes = self.indexes[index * self.batch_size: (index + 1) * self.batch_size]\n\n images_hr = [self.resize(self.crop(self.get_image_array(self.images[index])), self.init_scale) / 255.0\n for index in indexes]\n images_lr = [self.resize(image, self.scale) for image in images_hr]\n\n return images_hr, images_lr\n\n def crop(self, image):\n while True:\n y = np.random.randint(image.shape[0] - self.crop_height)\n x = np.random.randint(image.shape[1] - self.crop_weidth)\n crop = image[y:y + self.crop_height, x:x + self.crop_weidth]\n if crop[0].max() != crop[0].min() and \\\n crop[1].max() != crop[1].min() and \\\n crop[2].max() != crop[2].min():\n break\n return crop\n\n def resize(self, image, scale):\n return np.array([zoom(i, 1.0 / scale) for i in image.transpose([2, 0, 1])]).transpose((1, 2, 0))\n\n def get_dict_parameters(self):\n return self.settings\n\n def save_setting(self, path):\n yaml.dump(self.settings, open(path, 'w'))\n\n\nif __name__ == \"__main__\":\n BATCH_SIZE = 16\n img_paths = '../Samples'\n path_crop = ['example_batch_hr.jpeg', 'example_batch_lr.jpeg']\n\n d = DataHandler(img_paths, scale=2, batch_size=BATCH_SIZE, shuffle=True)\n images = d.__getitem__(1)\n for index in range(2):\n fig = plt.figure(figsize=(40, 40))\n columns = 4\n rows = 4\n\n for i in range(1, len(images[index]) + 1):\n ax = fig.add_subplot(rows, columns, i)\n plt.imshow(images[index][i - 1])\n\n plt.savefig(path_crop[index], dpi=300)\n","sub_path":"ISR/utils/datahandler_keras_loader.py","file_name":"datahandler_keras_loader.py","file_ext":"py","file_size_in_byte":3393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"592666344","text":"import pygame\nimport random\nimport syllables as syl\n\n_SIZE = (800, 600)\n\ndef main():\n\n # Initialise screen\n pygame.init()\n screen = pygame.display.set_mode(_SIZE)\n pygame.display.set_caption('Hiragana Trainer')\n\n # Fill background\n background = pygame.Surface(screen.get_size())\n background = background.convert()\n background.fill((255, 255, 255))\n\n clock = pygame.time.Clock()\n\n crashed = False\n\n # Scoretext on the display\n right, wrong = 0, 0\n def handle_score():\n font = pygame.font.Font(None, 36)\n text = font.render(f\"Right: {right} and Wrong: {wrong}\", 1, (255, 10, 10))\n textpos = text.get_rect()\n textpos.centerx = background.get_rect().centerx\n background.blit(text, textpos)\n\n def init_type_syl():\n return random.choice(syl.syllables)\n\n # Variables\n type_syl = init_type_syl()\n floating_sil = \"\"\n locked_sil = \"\"\n\n def handle_syllables():\n background.blit(type_syl.get_image(), type_syl.get_pos())\n font = pygame.font.Font(None, 36)\n text = font.render(f\"{floating_sil}\", 1, (255, 10, 10))\n background.blit(text, (380, 500))\n\n def draw_window():\n background.fill((255, 255, 255)) # Erases everything old\n handle_score()\n handle_syllables()\n screen.blit(background, (0, 0))\n pygame.display.flip()\n\n # Blit everything to the screen\n draw_window()\n\n while not crashed:\n\n for event in pygame.event.get():\n\n #print(event)\n\n if event.type == pygame.QUIT:\n crashed = True\n\n if event.type == pygame.KEYDOWN:\n # lock the current floating syllable as the answer to the current kana.\n if event.dict['unicode'] == ' ' or event.dict['unicode'] == '\\r':\n locked_sil = floating_sil.strip()\n floating_sil = \"\"\n\n if type_syl.get_name() == locked_sil:\n right += 1\n type_syl = init_type_syl()\n else:\n wrong += 1\n # delete the last letter typed.\n elif event.dict['unicode'] == '\\x08':\n floating_sil = floating_sil[:-1]\n # add the given letter to the answer string.\n else:\n floating_sil += event.dict['unicode']\n\n print(f\"Floating syl: {floating_sil} and Locked syl: {locked_sil} and to type: {type_syl.get_name()}\")\n\n draw_window()\n\n clock.tick(60)\n\n pygame.quit()\n quit()\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/oldmain.py","file_name":"oldmain.py","file_ext":"py","file_size_in_byte":2636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"492039170","text":"__author__ = 'fred'\n\nfrom scipy import optimize as opt\nimport numpy as np\n\nfrom pythonUtils import data\n\ninput_file = \"co2.data\"\n\n\ndef main():\n dat = data.Data(input_file, col_names=[\"x\", \"xerr\", \"y\", \"yerr\"])\n x = dat.x\n y = dat.y\n fits, errs = opt.curve_fit(lambda x, a, b: a * x + b, x, y)\n print(str(np.asmatrix(errs) * np.asmatrix(fits).transpose()))\n with open(input_file + \".fit\", \"w+\") as out_file:\n out_file.write(str(fits) + \"\\n\")\n out_file.write(str(errs))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"W5/auswertung/versuch1.py","file_name":"versuch1.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"464159951","text":"import csv\nfrom csv_downloader import get_todays_csv_file\n\ncsv_file = get_todays_csv_file()\nwith open(csv_file, 'r') as csvfile:\n csvReader = csv.reader(csvfile)\n next(csvReader)\n for row in csvReader:\n print('HMSET \\\"{}\\\" code \\\"{}\\\" name \\\"{}\\\" open \\\"{}\\\" high \\\"{}\\\" low \\\"{}\\\" close \\\"{}\\\"\\r'.format(row[1].strip(), row[0], row[1], row[4], row[5], row[6], row[7]))\n print('ZADD open {} \\\"{}\\\"\\r'.format(float(row[4]), row[1].strip()))\n","sub_path":"redis_commands.py","file_name":"redis_commands.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"440764530","text":"# pylint: disable=C0114\n\nimport copy\nimport re\n\n\nimport Persistence.log as log\nlog_ = log.getLogger(__name__)\n\nclass User:\n # pylint: disable=R0903\n def __init__(self, **kwargs):\n self.screen_name = kwargs['screen_name']\n self.id = kwargs['id']\n self._mention = {\n 'screen_name': self.screen_name,\n 'name': kwargs['name'],\n 'id': self.id,\n 'indices': [0, 0]\n }\n self.follows = kwargs.get('follows', False)\n self.follow_after = self.follows\n\n def mention(self, start):\n result = copy.deepcopy(self._mention)\n result['indices'][0] = start\n result['indices'][1] = start + len(self.screen_name)\n return result\n\nUser.theBot = User(\n id=1065715403622617089,\n id_str='1065715403622617089',\n name='DS100-Bot',\n screen_name='_ds_100',\n location='',\n description='''Expandiert DS100-Abkürzungen. #DS100 und #$KURZ verwenden, oder den Bot\n taggen. #folgenbitte und der Bot findet #$KURZ ohne Aufforderung. Siehe Webseite.''',\n url='https://t.co/s7A9JO049r',\n entities={\n 'url': {\n 'urls': [{\n 'url': 'https://t.co/s7A9JO049r',\n 'expanded_url': 'https://ds100.frankfurtium.de/',\n 'display_url': 'ds100.frankfurtium.de',\n 'indices': [0, 23]\n }]\n },\n 'description': {'urls': []}\n },\n protected=False,\n followers_count=61,\n friends_count=29,\n listed_count=0,\n favourites_count=0,\n utc_offset=None,\n time_zone=None,\n geo_enabled=False,\n verified=False,\n statuses_count=250,\n lang=None,\n contributors_enabled=False,\n is_translator=False,\n is_translation_enabled=False,\n profile_background_color='F5F8FA',\n profile_background_image_url=None,\n profile_background_image_url_https=None,\n profile_background_tile=False,\n profile_image_url=\n 'http://pbs.twimg.com/profile_images/1140888262619385856/dODzmIW9_normal.png',\n profile_image_url_https=\n 'https://pbs.twimg.com/profile_images/1140888262619385856/dODzmIW9_normal.png',\n profile_link_color='1DA1F2',\n profile_sidebar_border_color='C0DEED',\n profile_sidebar_fill_color='DDEEF6',\n profile_text_color='333333',\n profile_use_background_image=True,\n has_extended_profile=False,\n default_profile=True,\n default_profile_image=False,\n following=False,\n follow_request_sent=False,\n notifications=False,\n translator_type='none',\n follows=True)\nUser.followed = User(id=11, id_str='11',\n name='Followee account',\n screen_name='followee',\n description='Fake: This user is followed by the bot.',\n follows=True)\nUser.notfollowed = User(id=12, id_str='12',\n name='Some other Account',\n screen_name='someotheraccount',\n description='Fake: This user is not followed by the bot.',\n follows=False)\nUser.followers = []\nfor i in range(21, 26):\n User.followers.append(User(id=i, name='Follower', screen_name='follower{}'.format(i),\n follows=True))\nUser.nonfollowers = []\nfor i in range(31, 37):\n User.nonfollowers.append(User(id=i, name='Nonfollower', screen_name='otherone{}'.format(i),\n follows=False))\n\nclass TweepyMock:\n # pylint: disable=R0902\n def __init__(self, **kwargs):\n self.raw = kwargs\n self.add_to_raw('expected_answer', None)\n self.add_to_raw('display_text_range', [0, len(self.raw['full_text'])])\n self.add_to_raw('in_reply_to_status_id', None)\n self.add_to_raw('in_reply_to_user_id', None)\n self.add_to_raw('in_reply_to_screen_name', None)\n self.id = self.raw['id']\n self.full_text = self.raw['full_text']\n self.create_entities()\n self.author = self.raw['user']\n self.display_text_range = self.raw['display_text_range']\n if 'quoted_status_id' in self.raw:\n self.quoted_status_id = self.raw['quoted_status_id']\n else:\n self.quoted_status_id = None\n self.in_reply_to_status_id = self.raw['in_reply_to_status_id']\n self.expected_answer = self.raw.get('expected_answer', None)\n self.retweeted_status = self.raw.get('retweeted_status', False)\n if 'extended_entities' in self.raw:\n self.extended_entities = self.raw['extended_entities']\n\n def add_to_raw(self, key, val):\n if key not in self.raw:\n self.raw[key] = val\n\n def create_entities(self):\n self.add_to_raw('entities', {})\n if 'hashtags' not in self.raw['entities']:\n # create your own hashtag list\n ht = re.compile(r\"\"\"\\#(\\w+)\"\"\")\n self.raw['entities']['hashtags'] = []\n for t in ht.finditer(self.full_text):\n self.raw['entities']['hashtags'].append({\n 'text': t.group(1),\n 'indices': [t.start(1), t.end(1)]\n })\n if 'user_mentions' not in self.raw['entities']:\n self.raw['entities']['user_mentions'] = []\n self.entities = self.raw['entities']\n\n def __str__(self):\n lines = self.full_text.splitlines()\n length = max([len(l) for l in lines])\n length = max(length, len(self.author.screen_name) + 2)\n result = \"┏{}┓\\n\".format('━'*(length+2))\n result += (\"┃ @{{:{}}} ┃\\n\".format(length - 1)).format(self.author.screen_name + \":\")\n for l in lines:\n result += (\"┃ {{:{}}} ┃\\n\".format(length)).format(l)\n result += \"┗{}┛\".format('━'*(length+2))\n return result\n\ndef mocked_tweets():\n # pylint: disable=C0301, R0915\n # signatures bot*:\n # tl/nl: in timeline / not in timeline\n # ab/ns/xs/na: abbreviation present (#FF, $123) / no sigil (FF) / explicit source (#DS:FF) / no abbreviation present\n # xm/im: explicit mention / implicit mention (@ outside display_text_range)\n # mt/md/me: magic tag / default magic tag / else magic tag\n # pr/rt/re: pure retweet / retweet=quote / reply\n # fs/fe #folgenbitte / #entfolgen\n list_of_tweets = []\n list_of_tweets.append(TweepyMock(\n full_text='This tweet should never been seen nor processed by the Bot. bot%nl%na%101',\n expected_answer=None,\n id=101,\n user=User.notfollowed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet should appear in the Bot’s timeline, but should be ignored. bot%tl%na%102',\n id=102,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet explicitly mentions @_ds_100, but no other tweet. bot%tl%xm%na%103',\n id=103,\n entities={'user_mentions': [User.theBot.mention(31)]},\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet explicitly mentions @_ds_100, but no other tweet. bot%nl%xm%na%104',\n id=104,\n entities={'user_mentions': [User.theBot.mention(31)]},\n user=User.notfollowed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet includes magic hashtag #DS100, but no other tweet. bot%tl%md%na%105',\n id=105,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet includes magic hashtag #DB640, but no other tweet. bot%nl%mt%na%106',\n id=106,\n user=User.notfollowed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet is ignored because of #NOBOT #FF bot%tl%me%301',\n id=107,\n user=User.followed,\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet my own #FF bot%...%108',\n id=108,\n user=User.theBot\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet pure retweet #FF bot%tl%ab%pr%109',\n id=109,\n retweeted_status=True,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='#entfolgen bot%tl%fe%151',\n id=151,\n user=User.followers[0]\n ))\n list_of_tweets.append(TweepyMock(\n full_text='#entfolgen bot%nl%fe%152',\n id=152,\n user=User.followers[1]\n ))\n list_of_tweets.append(TweepyMock(\n full_text='#entfolgen @_ds_100 bot%xm%fe%153',\n id=153,\n entities={'user_mentions': [User.theBot.mention(12)]},\n user=User.followers[2]\n ))\n User.followers[2].follow_after = False\n list_of_tweets.append(TweepyMock(\n full_text='@_ds_100 #entfolgen bot%im%fe%154',\n id=154,\n display_text_range=[10, 52],\n entities={'user_mentions': [User.theBot.mention(0)]},\n user=User.followers[3]\n ))\n list_of_tweets.append(TweepyMock(\n full_text='#DS100 #entfolgen bot%mt%fe%155',\n id=155,\n user=User.followers[4]\n ))\n list_of_tweets.append(TweepyMock(\n full_text='#folgenbitte bot%tl%fs%161',\n id=161,\n user=User.nonfollowers[0]\n ))\n list_of_tweets.append(TweepyMock(\n full_text='#folgenbitte bot%nl%fs%162',\n id=162,\n user=User.nonfollowers[1]\n ))\n list_of_tweets.append(TweepyMock(\n full_text='#folgenbitte @_ds_100 bot%xm%fs%163',\n id=163,\n entities={'user_mentions': [User.theBot.mention(12)]},\n user=User.nonfollowers[2]\n ))\n User.nonfollowers[2].follow_after = True\n list_of_tweets.append(TweepyMock(\n full_text='@_ds_100 #folgenbitte bot%im%fs%164',\n id=164,\n display_text_range=[10, 62],\n entities={'user_mentions': [User.theBot.mention(0)]},\n user=User.nonfollowers[3]\n ))\n list_of_tweets.append(TweepyMock(\n full_text='#DS100 #folgenbitte bot%mt%fs%165',\n id=165,\n entities={'user_mentions': []},\n user=User.nonfollowers[4]\n ))\n list_of_tweets.append(TweepyMock(\n full_text='@_ds_100 This tweet xm @_ds_100 in a reply #folgenbitte bot%nl%xm%im%fs%issue[9]%204',\n display_text_range=[9, 75],\n id=166,\n entities={'user_mentions': [\n User.theBot.mention(0),\n User.theBot.mention(23)\n ]},\n user=User.nonfollowers[5]\n ))\n User.nonfollowers[5].follow_after = True\n list_of_tweets.append(TweepyMock(\n full_text='This tweet is quoted with explicit mention. bot%ns%nl%201 FF FK FM FW',\n expected_answer='FF: Frankfurt (Main) Hbf\\nFK: Kassel Hbf\\nFW: Wiesbaden Hbf',\n id=201,\n user=User.notfollowed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet explicitly mentions @_ds_100 and quotes tweet bot%xm%rt[201]%221: https://t.co/f4k3url_12',\n expected_answer=None,\n id=221,\n entities={'user_mentions': [User.theBot.mention(31)]},\n user=User.notfollowed,\n quoted_status_id=201\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet is replied-to with explicit mention. bot%nl%ns%202 FF FK FM FW',\n expected_answer='FF: Frankfurt (Main) Hbf\\nFK: Kassel Hbf\\nFW: Wiesbaden Hbf',\n id=202,\n user=User.notfollowed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='@followee @_ds_100 This tweet: bot%xm%re[202]%222',\n id=222,\n entities={'user_mentions': [User.notfollowed.mention(0), User.theBot.mention(11)]},\n in_reply_to_status_id=202,\n in_reply_to_user_id=User.notfollowed.id,\n in_reply_to_screen_name=User.notfollowed.screen_name,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet is replied to with magic hashtag _FFM. bot%nl%ns%203 #FW',\n expected_answer='FFM#FW: Friedhof Westhausen',\n id=203,\n user=User.notfollowed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet replies with magic hashtag #_FFM. bot%nl%me%re[203]%223',\n id=223,\n user=User.notfollowed,\n in_reply_to_status_id=203,\n in_reply_to_user_id=User.notfollowed.id,\n in_reply_to_screen_name=User.notfollowed.screen_name\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet my own will be quoted #FF bot%tl%ab%204',\n id=204,\n user=User.theBot\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet quotes myself, @_ds_100! bot%tl%ab%pr%re[204]%224',\n id=224,\n entities={'user_mentions': [User.theBot.mention(26)]},\n user=User.followed,\n in_reply_to_status_id=204,\n in_reply_to_screen_name=User.theBot.screen_name\n ))\n list_of_tweets.append(TweepyMock(\n full_text='Hallo @_ds_100, do you know $1733? bot%tl%xm%ab[1,$]%issue[8]%301',\n expected_answer='1733: Hannover --Kassel-- - Würzburg',\n id=301,\n entities={'user_mentions': [User.theBot.mention(6)]},\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet plain tags #FF #_FH #DS:FFU #DS:_FKW #DS:HG_ bot%tl%ab%ns%401',\n expected_answer='FF: Frankfurt (Main) Hbf\\nFFU: Fulda\\nHG: Göttingen',\n id=401,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet different cases #DS:FF #DS:Fkw #ÖBB:Aa #ÖBB:AB bot%tl%xs%402',\n expected_answer='FF: Frankfurt (Main) Hbf\\nÖBB#Aa: W․Mat․-Altmannsdorf (in Wbf)',\n id=402,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet blacklist #DBL #DS:WLAN bot%tl%bl%403',\n expected_answer='WLAN: Langen',\n id=403,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet mixes sources #MS #_FFM #WBC #_NO #OSL #DS:FF #BRG #DS100 #FKW bot%tl%ab%xs%is%mt%me%404',\n expected_answer='FFM#MS: Festhalle/Messe\\nFFM#WBC: Willy-Brandt-Platz (C-Ebene)\\nNO#OSL: Oslo S\\nFF: Frankfurt (Main) Hbf\\nNO#BRG: Bergen\\nFKW: Kassel-Wilhelmshöhe',\n id=404,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet do not find CH = Chur #_CH #BS bot%tl%ab%mt%issue[13]%411',\n expected_answer='CH#BS: Basel SBB',\n id=411,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet make sure 411 works: #CH:CH bot%tl%xs%issue[13]%412',\n expected_answer='CH#CH: Chur',\n id=412,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet unusual tags Vol Ⅰ: #NO:249 #NO:ÅBY bot%tl%xs%unusual%420',\n expected_answer='NO#249: H-sign 249\\nNO#ÅBY: Åneby',\n id=420,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet unusual tags Vol Ⅱ: $DS:VDE8¹ #CH:600133 #CH:ALT94 bot%tl%xs%unusual%421',\n expected_answer='VDE8¹: Nürnberg-Erfurt\\nCH#600133: UNO Linie 600, km 133.179\\nCH#ALT94: Altstätten SG 94',\n id=421,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet unusual tags Vol Ⅲ: #AT:Aa_G #AT:Aa_Z9 #AT:Z bot%tl%xs%unusual%422',\n expected_answer='AT#Aa G: Grenze ÖBB-WLB im km 7,610\\nAT#Aa Z9: Wr․ Neudorf\\nAT#Z: Zell am See',\n id=422,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet unusual tags Vol Ⅳ: #DS:AA_G #DS:AAG #DS:EM302 bot%tl%xs%unusual%423',\n expected_answer='AA G: Hamburg-Altona Gbf\\nAAG: Ascheberg (Holst)\\nEM302: Oberhausen Sbk M302',\n id=423,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet unusual tags Vol Ⅴ: #BOT:SARS_COV_2 #BOT:REKURSION #BOT:toggle bot%tl%xs%unusual%424',\n expected_answer='SARS COV 2: Dieser Bot ist offiziell Virusfrei™ und immun. Kuscheln, Händchenhalten etc. ist erlaubt. Bitte nicht anniesen (weil ist eklig). Lasst euch impfen, sobald ihr die Gelegenheit bekommt!\\nREKURSION: Siehe bitte #REKURSION',\n id=424,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet unusual tags Vol Ⅵ: #HH:HX #LP:K;#LP:KA+#LP:KALD bot%tl%xs%unusual%425',\n expected_answer='HH#HX: Hauptbahnhof-Nord\\nLP#K: Köln Hbf\\nLP#KA: Karlsruhe Hbf\\nLP#KALD: Kaldenkirchen',\n id=425,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet unusual tags Vol Ⅶ: #UK:ABE #UK:ABER #NL:Ah;#NL:Ahg/#NL:Apn #NL:APD bot%tl%xs%unusual%426',\n expected_answer='UK#ABE: Aber\\nUK#ABER: Aber\\nNL#Ah: Arnhem\\nNL#Ahg: Arnhem Goederenstation\\nNL#Apn: Alphen aan den Rijn',\n id=426,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet unusual tags Vol Ⅷ: #FR:A?#FR:AA!#FR:AAA bot%tl%xs%unusual%427',\n expected_answer='FR#A: Angouleme\\nFR#AA: Aire sur l\\'Adour\\nFR#AAA: Allassac',\n id=427,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet unusual tags Vol Ⅸ: $3640 #FFM:HB #FFM:_HB #FFM:211 #W:J $FFM:A3 bot%tl%xs%unusual%428',\n expected_answer='3640: Frankfurt-Höchst - Bad Soden\\nFFM#HB: Frankfurt Hauptbahnhof\\nFFM#_HB: WA Hauptbahnhof\\nFFM#211: Hauptbahnhof\\nW#J: Jedlersdorf (in F)\\nFFM$A3: Anschlussstrecke A3: Abzweig Nordwest - Oberursel Hohemark',\n id=428,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet unusual tags Vol Ⅹ: $FFM:A $FFM:Aⅰ $FFM:AⅡ $FFM:AIII bot%tl%xs%unusual%429',\n expected_answer='FFM$A: A-Strecke: Südbahnhof - Heddernheim - (Ginnheim/Bad Homburg/Oberursel)\\nFFM$Aⅰ: A-Strecke Teilabschnitt 1 Humser Straße - Hauptwache\\nFFM$AⅡ: A-Strecke Teilabschnitt 2 Hauptwache - Willy-Brandt-Platz\\nFFM$AIII: A-Strecke Teilabschnitt 3 Humser Straße - Weißer Stein',\n id=429,\n user=User.followed\n ))\n\n list_of_tweets.append(TweepyMock(\n full_text='This tweet unusual tags Vol ⅰ: #_NO #249 #ÅBY bot%tl%mt%unusual%430',\n expected_answer='NO#249: H-sign 249\\nNO#ÅBY: Åneby',\n id=430,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet unusual tags Vol ⅱ: #DS100 $VDE8¹ #_CH #600133 #ALT94 bot%tl%mt%unusual%431',\n expected_answer='VDE8¹: Nürnberg-Erfurt\\nCH#600133: UNO Linie 600, km 133.179\\nCH#ALT94: Altstätten SG 94',\n id=431,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet unusual tags Vol ⅲ: #_AT #Aa_G #Aa_Z9 #_AT #Z bot%tl%mt%unusual%432',\n expected_answer='AT#Aa G: Grenze ÖBB-WLB im km 7,610\\nAT#Aa Z9: Wr․ Neudorf\\nAT#Z: Zell am See',\n id=432,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet unusual tags Vol ⅳ: #_DS #AA_G #AAG #EM302 bot%tl%mt%unusual%433',\n expected_answer='AA G: Hamburg-Altona Gbf\\nAAG: Ascheberg (Holst)\\nEM302: Oberhausen Sbk M302',\n id=433,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet unusual tags Vol ⅴ: #DS100 #SARS_COV_2 #REKURSION #toggle bot%tl%mt%unusual%434',\n expected_answer='SARS COV 2: Dieser Bot ist offiziell Virusfrei™ und immun. Kuscheln, Händchenhalten etc. ist erlaubt. Bitte nicht anniesen (weil ist eklig). Lasst euch impfen, sobald ihr die Gelegenheit bekommt!\\nREKURSION: Siehe bitte #REKURSION',\n id=434,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet unusual tags Vol ⅵ: #_HH #HX #_LP #K;#KA+#KALD bot%tl%mt%unusual%435',\n expected_answer='HH#HX: Hauptbahnhof-Nord\\nLP#K: Köln Hbf\\nLP#KA: Karlsruhe Hbf\\nLP#KALD: Kaldenkirchen',\n id=435,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet unusual tags Vol ⅶ: #_UK #ABE #ABER #_NL #Ah;#Ahg/#Apn #APD bot%tl%mt%unusual%436',\n expected_answer='UK#ABE: Aber\\nUK#ABER: Aber\\nNL#Ah: Arnhem\\nNL#Ahg: Arnhem Goederenstation\\nNL#Apn: Alphen aan den Rijn',\n id=436,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet unusual tags Vol ⅷ: #_FR #A?#AA!#AAA bot%tl%mt%unusual%437',\n expected_answer='FR#A: Angouleme\\nFR#AA: Aire sur l\\'Adour\\nFR#AAA: Allassac',\n id=437,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet unusual tags Vol ⅸ: #_DE $3640 #_FFM #HB #FFM:_HB #211 #_W #J #_FFM $A3 bot%tl%mt%unusual%438',\n expected_answer='3640: Frankfurt-Höchst - Bad Soden\\nFFM#HB: Frankfurt Hauptbahnhof\\nFFM#_HB: WA Hauptbahnhof\\nFFM#211: Hauptbahnhof\\nW#J: Jedlersdorf (in F)\\nFFM$A3: Anschlussstrecke A3: Abzweig Nordwest - Oberursel Hohemark',\n id=438,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet unusual tags Vol ⅹ: #_FFM $A $Aⅰ $AⅡ $AIII bot%tl%mt%unusual%439',\n expected_answer='FFM$A: A-Strecke: Südbahnhof - Heddernheim - (Ginnheim/Bad Homburg/Oberursel)\\nFFM$Aⅰ: A-Strecke Teilabschnitt 1 Humser Straße - Hauptwache\\nFFM$AⅡ: A-Strecke Teilabschnitt 2 Hauptwache - Willy-Brandt-Platz\\nFFM$AIII: A-Strecke Teilabschnitt 3 Humser Straße - Weißer Stein',\n id=439,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet media: #_FFM #HB #DS100 bot%tl%mt%mf%440',\n expected_answer='FFM#HB: Frankfurt Hauptbahnhof\\nRALP: Alpirsbach\\nCH#HE: Herisau\\nCH#MS: Münsingen',\n extended_entities={'media': [{'ext_alt_text': '#RALP'},\n {'ext_alt_text': '#_CH #HE'},\n {'ext_alt_text': '#MS'}\n ]},\n id=440,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet media w/o ext_alt: #_FFM #HB bot%tl%mt%mf%441',\n expected_answer='FFM#HB: Frankfurt Hauptbahnhof',\n extended_entities={'media': [{},\n {}\n ]},\n id=441,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet media w/o media: #_FFM #HB bot%tl%mt%mf%442',\n expected_answer='FFM#HB: Frankfurt Hauptbahnhof',\n extended_entities={},\n id=442,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='This tweet #FF $1234 %Hp0 &Awanst /FFM:U2 bot%tl%sigil%450',\n expected_answer='FF: Frankfurt (Main) Hbf\\n1234: HH-Eidelstedt - Rothenburgsort\\nHp0: Halt.\\nAwanst: Ausweichanschlussstelle\\nFFM/U2: Bad Homburg Gonzenheim - Nieder-Eschbach - Riedwiese - Heddernheim - Südbahnhof',\n id=450,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='Blacklist #LZB &LZB bot%tl%bl%451',\n expected_answer='LZB: Linienförmige Zugbeeinflussung',\n id=451,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='Repeated things #FF #FF bot%tl%460',\n expected_answer='FF: Frankfurt (Main) Hbf',\n id=460,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='Repeated things #_FFM #DS:FF #DS100 #DE:FF #FF bot%tl%461',\n expected_answer='FF: Frankfurt (Main) Hbf',\n id=461,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='Bot precedence #AI #_CH #BOT:AI bot%tl%462',\n expected_answer='CH#AI: Airolo\\nAI: Dieser Bot besitzt keine Künstliche Intelligenz. Er ist sozusagen strunzdumm. Lernen kann der Bot nur, indem der Autor lernt und etwas neues dazuprogrammiert.',\n id=462,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='Bot precedence #CH:AI #AI bot%tl%463',\n expected_answer='CH#AI: Airolo\\nAI: Dieser Bot besitzt keine Künstliche Intelligenz. Er ist sozusagen strunzdumm. Lernen kann der Bot nur, indem der Autor lernt und etwas neues dazuprogrammiert.',\n id=463,\n user=User.followed\n ))\n list_of_tweets.append(TweepyMock(\n full_text='Bot flag emoji \\U0001F1E6\\U0001F1F9 #FAQ:AUSLAND bot%tl%501',\n expected_answer=('FAQ#AUSLAND: Kürzel mit X und Z haben als zweiten Buchstaben das Land: '\n + 'XA\\U0001F1E6\\U0001F1F9 '\n + 'XB\\U0001F1E7\\U0001F1EA '\n + 'XC\\U0001f1f7\\U0001f1fa '\n + 'XD\\U0001f1e9\\U0001f1f0 '\n + 'XE\\U0001f1ea\\U0001f1f8 '\n + 'XF\\U0001f1eb\\U0001f1f7 '\n + 'XG\\U0001f1ec\\U0001f1f7 '\n + 'XH\\U0001f1eb\\U0001f1ee '\n + 'XI\\U0001f1ee\\U0001f1f9 '\n + 'XJ\\U0001f1f7\\U0001f1f8 '\n + 'XK\\U0001f1ec\\U0001f1e7 '\n + 'XL\\U0001f1f1\\U0001f1fa '\n + 'XM\\U0001f1ed\\U0001f1fa '\n + 'XN\\U0001f1f3\\U0001f1f1 '\n + 'XO\\U0001f1f3\\U0001f1f4 '\n + 'XP\\U0001f1f5\\U0001f1f1 '\n + 'XQ\\U0001f1f9\\U0001f1f7 '\n + 'XR\\U0001f1ed\\U0001f1f7 '\n + 'XS\\U0001f1e8\\U0001f1ed '\n + 'XT\\U0001f1e8\\U0001f1ff '\n + 'XU\\U0001f1f7\\U0001f1f4 '\n + 'XV\\U0001f1f8\\U0001f1ea '\n + 'XW\\U0001f1e7\\U0001f1ec '\n + 'XX\\U0001f1f5\\U0001f1f9 '\n + 'XY\\U0001f1f8\\U0001f1f0 '\n + 'XZ\\U0001f1f8\\U0001f1ee '\n + 'ZA\\U0001f1f2\\U0001f1f0 '\n + 'ZB\\U0001f1e7\\U0001f1e6 '\n + 'ZE\\U0001f1ea\\U0001f1ea '\n + 'ZI\\U0001f1ee\\U0001f1ea '\n + 'ZK\\U0001f1f0\\U0001f1ff '\n + 'ZL\\U0001f1f1\\U0001f1f9 '\n + 'ZM\\U0001f1f2\\U0001f1e9 '\n + 'ZT\\U0001f1f1\\U0001f1fb '\n + 'ZU\\U0001f1fa\\U0001f1e6 '\n + 'ZW\\U0001f1e7\\U0001f1fe'\n ),\n id=501,\n user=User.followed\n ))\n return list_of_tweets\n\ndef mocked_source():\n try:\n # pylint: disable=E0401,C0415\n from tweet_details import list_of_tweets\n except ModuleNotFoundError:\n log_.critical(\"Keine Tweet-Details gefunden. Bitte get_tweet mit --mode mock ausführen.\")\n return []\n return list_of_tweets\n","sub_path":"Mock/Tweet.py","file_name":"Tweet.py","file_ext":"py","file_size_in_byte":26958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"204522608","text":"import ClientConstants as CC\nimport ClientDownloading\nimport ClientImporting\nimport ClientImportFileSeeds\nimport ClientImportGallerySeeds\nimport ClientImportOptions\nimport ClientNetworkingContexts\nimport ClientNetworkingJobs\nimport ClientPaths\nimport ClientThreading\nimport HydrusConstants as HC\nimport HydrusData\nimport HydrusExceptions\nimport HydrusGlobals as HG\nimport HydrusPaths\nimport HydrusSerialisable\nimport os\nimport random\nimport time\n\nclass Subscription( HydrusSerialisable.SerialisableBaseNamed ):\n \n SERIALISABLE_TYPE = HydrusSerialisable.SERIALISABLE_TYPE_SUBSCRIPTION\n SERIALISABLE_NAME = 'Subscription'\n SERIALISABLE_VERSION = 7\n \n def __init__( self, name ):\n \n HydrusSerialisable.SerialisableBaseNamed.__init__( self, name )\n \n self._gallery_identifier = ClientDownloading.GalleryIdentifier( HC.SITE_TYPE_DEVIANT_ART )\n \n self._gallery_stream_identifiers = ClientDownloading.GetGalleryStreamIdentifiers( self._gallery_identifier )\n \n self._queries = []\n \n new_options = HG.client_controller.new_options\n \n self._checker_options = HG.client_controller.new_options.GetDefaultSubscriptionCheckerOptions()\n \n if HC.options[ 'gallery_file_limit' ] is None:\n \n self._initial_file_limit = 100\n \n else:\n \n self._initial_file_limit = min( 100, HC.options[ 'gallery_file_limit' ] )\n \n \n self._periodic_file_limit = 100\n self._paused = False\n \n self._file_import_options = HG.client_controller.new_options.GetDefaultFileImportOptions( 'quiet' )\n \n new_options = HG.client_controller.new_options\n \n self._tag_import_options = ClientImportOptions.TagImportOptions( is_default = True )\n \n self._last_gallery_page_hit_timestamp = 0\n \n self._no_work_until = 0\n self._no_work_until_reason = ''\n \n self._publish_files_to_popup_button = True\n self._publish_files_to_page = False\n self._merge_query_publish_events = True\n \n \n def _DelayWork( self, time_delta, reason ):\n \n self._no_work_until = HydrusData.GetNow() + time_delta\n self._no_work_until_reason = reason\n \n \n def _GetExampleNetworkContexts( self, query ):\n \n file_seed_cache = query.GetFileSeedCache()\n \n file_seed = file_seed_cache.GetNextFileSeed( CC.STATUS_UNKNOWN )\n \n if file_seed is None:\n \n return [ ClientNetworkingContexts.NetworkContext( CC.NETWORK_CONTEXT_SUBSCRIPTION, self._GetNetworkJobSubscriptionKey( query ) ), ClientNetworkingContexts.GLOBAL_NETWORK_CONTEXT ]\n \n \n url = file_seed.file_seed_data\n \n example_nj = ClientNetworkingJobs.NetworkJobSubscription( self._GetNetworkJobSubscriptionKey( query ), 'GET', url )\n example_network_contexts = example_nj.GetNetworkContexts()\n \n return example_network_contexts\n \n \n def _GetNetworkJobSubscriptionKey( self, query ):\n \n query_text = query.GetQueryText()\n \n return self._name + ': ' + query_text\n \n \n def _GetQueriesForProcessing( self ):\n \n queries = list( self._queries )\n \n if HG.client_controller.new_options.GetBoolean( 'process_subs_in_random_order' ):\n \n random.shuffle( queries )\n \n else:\n \n def key( q ):\n \n return q.GetQueryText()\n \n \n queries.sort( key = key )\n \n \n return queries\n \n \n def _GetSerialisableInfo( self ):\n \n serialisable_gallery_identifier = self._gallery_identifier.GetSerialisableTuple()\n serialisable_gallery_stream_identifiers = [ gallery_stream_identifier.GetSerialisableTuple() for gallery_stream_identifier in self._gallery_stream_identifiers ]\n serialisable_queries = [ query.GetSerialisableTuple() for query in self._queries ]\n serialisable_checker_options = self._checker_options.GetSerialisableTuple()\n serialisable_file_import_options = self._file_import_options.GetSerialisableTuple()\n serialisable_tag_import_options = self._tag_import_options.GetSerialisableTuple()\n \n return ( serialisable_gallery_identifier, serialisable_gallery_stream_identifiers, serialisable_queries, serialisable_checker_options, self._initial_file_limit, self._periodic_file_limit, self._paused, serialisable_file_import_options, serialisable_tag_import_options, self._no_work_until, self._no_work_until_reason, self._publish_files_to_popup_button, self._publish_files_to_page, self._merge_query_publish_events )\n \n \n def _InitialiseFromSerialisableInfo( self, serialisable_info ):\n \n ( serialisable_gallery_identifier, serialisable_gallery_stream_identifiers, serialisable_queries, serialisable_checker_options, self._initial_file_limit, self._periodic_file_limit, self._paused, serialisable_file_import_options, serialisable_tag_import_options, self._no_work_until, self._no_work_until_reason, self._publish_files_to_popup_button, self._publish_files_to_page, self._merge_query_publish_events ) = serialisable_info\n \n self._gallery_identifier = HydrusSerialisable.CreateFromSerialisableTuple( serialisable_gallery_identifier )\n self._gallery_stream_identifiers = [ HydrusSerialisable.CreateFromSerialisableTuple( serialisable_gallery_stream_identifier ) for serialisable_gallery_stream_identifier in serialisable_gallery_stream_identifiers ]\n self._queries = [ HydrusSerialisable.CreateFromSerialisableTuple( serialisable_query ) for serialisable_query in serialisable_queries ]\n self._checker_options = HydrusSerialisable.CreateFromSerialisableTuple( serialisable_checker_options )\n self._file_import_options = HydrusSerialisable.CreateFromSerialisableTuple( serialisable_file_import_options )\n self._tag_import_options = HydrusSerialisable.CreateFromSerialisableTuple( serialisable_tag_import_options )\n \n \n def _NoDelays( self ):\n \n return HydrusData.TimeHasPassed( self._no_work_until )\n \n \n def _QueryBandwidthIsOK( self, query ):\n \n example_network_contexts = self._GetExampleNetworkContexts( query )\n \n threshold = 90\n \n result = HG.client_controller.network_engine.bandwidth_manager.CanDoWork( example_network_contexts, threshold = threshold )\n \n if HG.subscription_report_mode:\n \n HydrusData.ShowText( 'Query \"' + query.GetQueryText() + '\" pre-work bandwidth test. Bandwidth ok: ' + str( result ) + '.' )\n \n \n return result\n \n \n def _ShowHitPeriodicFileLimitMessage( self, query_text ):\n \n message = 'When syncing, the query \"' + query_text + '\" for subscription \"' + self._name + '\" hit its periodic file limit!'\n message += os.linesep * 2\n message += 'This may be because the query has not run in a while--so the backlog of files has built up--or that the site has changed how it presents file urls on its gallery pages (and so the subscription thinks it is seeing new files when it truly is not).'\n message += os.linesep * 2\n message += 'If the former is true, you might want to tweak its numbers and fill in the gap with a manual download page, but if the latter is true, the maintainer for the download parser (hydrus dev or whoever), would be interested in knowing this information so they can roll out a fix.'\n \n HydrusData.ShowText( message )\n \n \n def _UpdateSerialisableInfo( self, version, old_serialisable_info ):\n \n if version == 1:\n \n ( serialisable_gallery_identifier, serialisable_gallery_stream_identifiers, query, period, get_tags_if_url_recognised_and_file_redundant, initial_file_limit, periodic_file_limit, paused, serialisable_file_import_options, serialisable_tag_import_options, last_checked, last_error, serialisable_file_seed_cache ) = old_serialisable_info\n \n check_now = False\n \n new_serialisable_info = ( serialisable_gallery_identifier, serialisable_gallery_stream_identifiers, query, period, get_tags_if_url_recognised_and_file_redundant, initial_file_limit, periodic_file_limit, paused, serialisable_file_import_options, serialisable_tag_import_options, last_checked, check_now, last_error, serialisable_file_seed_cache )\n \n return ( 2, new_serialisable_info )\n \n \n if version == 2:\n \n ( serialisable_gallery_identifier, serialisable_gallery_stream_identifiers, query, period, get_tags_if_url_recognised_and_file_redundant, initial_file_limit, periodic_file_limit, paused, serialisable_file_import_options, serialisable_tag_import_options, last_checked, check_now, last_error, serialisable_file_seed_cache ) = old_serialisable_info\n \n no_work_until = 0\n no_work_until_reason = ''\n \n new_serialisable_info = ( serialisable_gallery_identifier, serialisable_gallery_stream_identifiers, query, period, get_tags_if_url_recognised_and_file_redundant, initial_file_limit, periodic_file_limit, paused, serialisable_file_import_options, serialisable_tag_import_options, last_checked, check_now, last_error, no_work_until, no_work_until_reason, serialisable_file_seed_cache )\n \n return ( 3, new_serialisable_info )\n \n \n if version == 3:\n \n ( serialisable_gallery_identifier, serialisable_gallery_stream_identifiers, query, period, get_tags_if_url_recognised_and_file_redundant, initial_file_limit, periodic_file_limit, paused, serialisable_file_import_options, serialisable_tag_import_options, last_checked, check_now, last_error, no_work_until, no_work_until_reason, serialisable_file_seed_cache ) = old_serialisable_info\n \n checker_options = ClientImportOptions.CheckerOptions( 5, period / 5, period * 10, ( 1, period * 10 ) )\n \n file_seed_cache = HydrusSerialisable.CreateFromSerialisableTuple( serialisable_file_seed_cache )\n \n query = SubscriptionQuery( query )\n \n query._file_seed_cache = file_seed_cache\n query._last_check_time = last_checked\n \n query.UpdateNextCheckTime( checker_options )\n \n queries = [ query ]\n \n serialisable_queries = [ query.GetSerialisableTuple() for query in queries ]\n serialisable_checker_options = checker_options.GetSerialisableTuple()\n \n new_serialisable_info = ( serialisable_gallery_identifier, serialisable_gallery_stream_identifiers, serialisable_queries, serialisable_checker_options, get_tags_if_url_recognised_and_file_redundant, initial_file_limit, periodic_file_limit, paused, serialisable_file_import_options, serialisable_tag_import_options, no_work_until, no_work_until_reason )\n \n return ( 4, new_serialisable_info )\n \n \n if version == 4:\n \n ( serialisable_gallery_identifier, serialisable_gallery_stream_identifiers, serialisable_queries, serialisable_checker_options, get_tags_if_url_recognised_and_file_redundant, initial_file_limit, periodic_file_limit, paused, serialisable_file_import_options, serialisable_tag_import_options, no_work_until, no_work_until_reason ) = old_serialisable_info\n \n new_serialisable_info = ( serialisable_gallery_identifier, serialisable_gallery_stream_identifiers, serialisable_queries, serialisable_checker_options, initial_file_limit, periodic_file_limit, paused, serialisable_file_import_options, serialisable_tag_import_options, no_work_until, no_work_until_reason )\n \n return ( 5, new_serialisable_info )\n \n \n if version == 5:\n \n ( serialisable_gallery_identifier, serialisable_gallery_stream_identifiers, serialisable_queries, serialisable_checker_options, initial_file_limit, periodic_file_limit, paused, serialisable_file_import_options, serialisable_tag_import_options, no_work_until, no_work_until_reason ) = old_serialisable_info\n \n publish_files_to_popup_button = True\n publish_files_to_page = False\n merge_query_publish_events = True\n \n new_serialisable_info = ( serialisable_gallery_identifier, serialisable_gallery_stream_identifiers, serialisable_queries, serialisable_checker_options, initial_file_limit, periodic_file_limit, paused, serialisable_file_import_options, serialisable_tag_import_options, no_work_until, no_work_until_reason, publish_files_to_popup_button, publish_files_to_page, merge_query_publish_events )\n \n return ( 6, new_serialisable_info )\n \n \n if version == 6:\n \n ( serialisable_gallery_identifier, serialisable_gallery_stream_identifiers, serialisable_queries, serialisable_checker_options, initial_file_limit, periodic_file_limit, paused, serialisable_file_import_options, serialisable_tag_import_options, no_work_until, no_work_until_reason, publish_files_to_popup_button, publish_files_to_page, merge_query_publish_events ) = old_serialisable_info\n \n if initial_file_limit is None or initial_file_limit > 1000:\n \n initial_file_limit = 1000\n \n \n if periodic_file_limit is None or periodic_file_limit > 1000:\n \n periodic_file_limit = 1000\n \n \n new_serialisable_info = ( serialisable_gallery_identifier, serialisable_gallery_stream_identifiers, serialisable_queries, serialisable_checker_options, initial_file_limit, periodic_file_limit, paused, serialisable_file_import_options, serialisable_tag_import_options, no_work_until, no_work_until_reason, publish_files_to_popup_button, publish_files_to_page, merge_query_publish_events )\n \n return ( 7, new_serialisable_info )\n \n \n \n def _WorkOnFiles( self, job_key ):\n \n try:\n \n gallery = ClientDownloading.GetGallery( self._gallery_identifier )\n \n except Exception as e:\n \n HydrusData.PrintException( e )\n \n self._DelayWork( HC.UPDATE_DURATION, 'gallery would not load' )\n \n self._paused = True\n \n HydrusData.ShowText( 'The subscription ' + self._name + ' could not load its gallery! It has been paused and the full error has been written to the log!' )\n \n return\n \n \n error_count = 0\n \n all_presentation_hashes = []\n all_presentation_hashes_fast = set()\n \n queries = self._GetQueriesForProcessing()\n \n for query in queries:\n \n this_query_has_done_work = False\n \n query_text = query.GetQueryText()\n file_seed_cache = query.GetFileSeedCache()\n \n def network_job_factory( method, url, **kwargs ):\n \n network_job = ClientNetworkingJobs.NetworkJobSubscription( self._GetNetworkJobSubscriptionKey( query ), method, url, **kwargs )\n \n network_job.OverrideBandwidth( 30 )\n \n job_key.SetVariable( 'popup_network_job', network_job )\n \n return network_job\n \n \n gallery.SetNetworkJobFactory( network_job_factory )\n \n text_1 = 'downloading files'\n query_summary_name = self._name\n \n if query_text != self._name:\n \n text_1 += ' for \"' + query_text + '\"'\n query_summary_name += ': ' + query_text\n \n \n job_key.SetVariable( 'popup_text_1', text_1 )\n \n presentation_hashes = []\n presentation_hashes_fast = set()\n \n while True:\n \n num_urls = file_seed_cache.GetFileSeedCount()\n num_unknown = file_seed_cache.GetFileSeedCount( CC.STATUS_UNKNOWN )\n num_done = num_urls - num_unknown\n \n file_seed = file_seed_cache.GetNextFileSeed( CC.STATUS_UNKNOWN )\n \n if file_seed is None:\n \n if HG.subscription_report_mode:\n \n HydrusData.ShowText( 'Query \"' + query_text + '\" can do no more file work due to running out of unknown urls.' )\n \n \n break\n \n \n if job_key.IsCancelled():\n \n self._DelayWork( 300, 'recently cancelled' )\n \n break\n \n \n p1 = HC.options[ 'pause_subs_sync' ]\n p3 = HG.view_shutdown\n p4 = not self._QueryBandwidthIsOK( query )\n \n if p1 or p3 or p4:\n \n if p4 and this_query_has_done_work:\n \n job_key.SetVariable( 'popup_text_2', 'no more bandwidth to download files, will do some more later' )\n \n time.sleep( 5 )\n \n \n break\n \n \n try:\n \n x_out_of_y = 'file ' + HydrusData.ConvertValueRangeToPrettyString( num_done, num_urls ) + ': '\n \n job_key.SetVariable( 'popup_gauge_2', ( num_done, num_urls ) )\n \n if file_seed.WorksInNewSystem():\n \n def status_hook( text ):\n \n job_key.SetVariable( 'popup_text_2', x_out_of_y + text )\n \n \n \n file_seed.WorkOnURL( file_seed_cache, status_hook, ClientImporting.GenerateSubscriptionNetworkJobFactory( self._GetNetworkJobSubscriptionKey( query ) ), ClientImporting.GenerateMultiplePopupNetworkJobPresentationContextFactory( job_key ), self._file_import_options, self._tag_import_options )\n \n if file_seed.ShouldPresent( self._file_import_options ):\n \n hash = file_seed.GetHash()\n \n if hash not in presentation_hashes_fast:\n \n if hash not in all_presentation_hashes_fast:\n \n all_presentation_hashes.append( hash )\n \n all_presentation_hashes_fast.add( hash )\n \n \n presentation_hashes.append( hash )\n \n presentation_hashes_fast.add( hash )\n \n \n \n else:\n \n job_key.SetVariable( 'popup_text_2', x_out_of_y + 'checking url status' )\n \n ( should_download_metadata, should_download_file ) = file_seed.PredictPreImportStatus( self._file_import_options, self._tag_import_options )\n \n status = file_seed.status\n url = file_seed.file_seed_data\n \n if status == CC.STATUS_SUCCESSFUL_BUT_REDUNDANT:\n \n if self._tag_import_options.ShouldFetchTagsEvenIfURLKnownAndFileAlreadyInDB() and self._tag_import_options.WorthFetchingTags():\n \n job_key.SetVariable( 'popup_text_2', x_out_of_y + 'found file in db, fetching tags' )\n \n downloaded_tags = gallery.GetTags( url )\n \n file_seed.AddTags( downloaded_tags )\n \n \n elif status == CC.STATUS_UNKNOWN:\n \n ( os_file_handle, temp_path ) = ClientPaths.GetTempPath()\n \n try:\n \n job_key.SetVariable( 'popup_text_2', x_out_of_y + 'downloading file' )\n \n if self._tag_import_options.WorthFetchingTags():\n \n downloaded_tags = gallery.GetFileAndTags( temp_path, url )\n \n file_seed.AddTags( downloaded_tags )\n \n else:\n \n gallery.GetFile( temp_path, url )\n \n \n file_seed.CheckPreFetchMetadata( self._tag_import_options )\n \n job_key.SetVariable( 'popup_text_2', x_out_of_y + 'importing file' )\n \n file_seed.Import( temp_path, self._file_import_options )\n \n hash = file_seed.GetHash()\n \n if hash not in presentation_hashes_fast:\n \n if file_seed.ShouldPresent( self._file_import_options ):\n \n if hash not in all_presentation_hashes_fast:\n \n all_presentation_hashes.append( hash )\n \n all_presentation_hashes_fast.add( hash )\n \n \n presentation_hashes.append( hash )\n \n presentation_hashes_fast.add( hash )\n \n \n \n finally:\n \n HydrusPaths.CleanUpTempPath( os_file_handle, temp_path )\n \n \n \n file_seed.WriteContentUpdates( self._tag_import_options )\n \n \n except HydrusExceptions.CancelledException as e:\n \n self._DelayWork( 300, HydrusData.ToUnicode( e ) )\n \n break\n \n except HydrusExceptions.VetoException as e:\n \n status = CC.STATUS_VETOED\n \n note = HydrusData.ToUnicode( e )\n \n file_seed.SetStatus( status, note = note )\n \n except HydrusExceptions.NotFoundException:\n \n status = CC.STATUS_VETOED\n \n note = '404'\n \n file_seed.SetStatus( status, note = note )\n \n except Exception as e:\n \n status = CC.STATUS_ERROR\n \n job_key.SetVariable( 'popup_text_2', x_out_of_y + 'file failed' )\n \n file_seed.SetStatus( status, exception = e )\n \n if isinstance( e, HydrusExceptions.DataMissing ):\n \n # DataMissing is a quick thing to avoid subscription abandons when lots of deleted files in e621 (or any other booru)\n # this should be richer in any case in the new system\n \n pass\n \n else:\n \n error_count += 1\n \n time.sleep( 10 )\n \n \n if error_count > 4:\n \n raise Exception( 'The subscription ' + self._name + ' encountered several errors when downloading files, so it abandoned its sync.' )\n \n \n \n this_query_has_done_work = True\n \n if len( presentation_hashes ) > 0:\n \n job_key.SetVariable( 'popup_files', ( list( presentation_hashes ), query_summary_name ) )\n \n \n time.sleep( ClientImporting.DID_SUBSTANTIAL_FILE_WORK_MINIMUM_SLEEP_TIME )\n \n HG.client_controller.WaitUntilViewFree()\n \n \n if not self._merge_query_publish_events and len( presentation_hashes ) > 0:\n \n ClientImporting.PublishPresentationHashes( query_summary_name, presentation_hashes, self._publish_files_to_popup_button, self._publish_files_to_page )\n \n \n \n if self._merge_query_publish_events and len( all_presentation_hashes ) > 0:\n \n ClientImporting.PublishPresentationHashes( self._name, all_presentation_hashes, self._publish_files_to_popup_button, self._publish_files_to_page )\n \n \n job_key.DeleteVariable( 'popup_files' )\n job_key.DeleteVariable( 'popup_text_1' )\n job_key.DeleteVariable( 'popup_text_2' )\n job_key.DeleteVariable( 'popup_gauge_2' )\n \n \n def _WorkOnFilesCanDoWork( self ):\n \n for query in self._queries:\n \n if query.CanWorkOnFiles():\n \n if self._QueryBandwidthIsOK( query ):\n \n return True\n \n \n \n \n return False\n \n \n def _SyncQuery( self, job_key ):\n \n have_made_an_initial_sync_bandwidth_notification = False\n \n queries = self._GetQueriesForProcessing()\n \n for query in queries:\n \n can_sync = query.CanSync()\n \n if HG.subscription_report_mode:\n \n HydrusData.ShowText( 'Query \"' + query.GetQueryText() + '\" started. Current can_sync is ' + str( can_sync ) + '.' )\n \n \n if not can_sync:\n \n continue\n \n \n done_first_page = False\n seen_some_existing_urls = False\n \n query_text = query.GetQueryText()\n file_seed_cache = query.GetFileSeedCache()\n gallery_seed_log = query.GetGallerySeedLog()\n \n this_is_initial_sync = query.IsInitialSync()\n total_new_urls_for_this_sync = 0\n \n gallery_urls_seen_this_sync = set()\n \n if this_is_initial_sync:\n \n file_limit_for_this_sync = self._initial_file_limit\n \n else:\n \n file_limit_for_this_sync = self._periodic_file_limit\n \n \n file_seeds_to_add = set()\n file_seeds_to_add_ordered = []\n \n prefix = 'synchronising'\n \n if query_text != self._name:\n \n prefix += ' \"' + query_text + '\"'\n \n \n job_key.SetVariable( 'popup_text_1', prefix )\n \n for gallery_stream_identifier in self._gallery_stream_identifiers:\n \n if file_limit_for_this_sync is not None and total_new_urls_for_this_sync >= file_limit_for_this_sync:\n \n break\n \n \n p1 = HC.options[ 'pause_subs_sync' ]\n p2 = job_key.IsCancelled()\n p3 = HG.view_shutdown\n \n if p1 or p2 or p3:\n \n break\n \n \n try:\n \n gallery = ClientDownloading.GetGallery( gallery_stream_identifier )\n \n except Exception as e:\n \n HydrusData.PrintException( e )\n \n self._DelayWork( HC.UPDATE_DURATION, 'gallery would not load' )\n \n self._paused = True\n \n HydrusData.ShowText( 'The subscription ' + self._name + ' could not load its gallery! It has been paused and the full error has been written to the log!' )\n \n return\n \n \n first_gallery_url = gallery.GetGalleryPageURL( query_text, 0 )\n \n gallery_seed = ClientImportGallerySeeds.GallerySeed( first_gallery_url, can_generate_more_pages = True )\n \n if gallery_seed.WorksInNewSystem():\n \n num_existing_urls = 0\n \n def status_hook( text ):\n \n job_key.SetVariable( 'popup_text_1', prefix + ': ' + text )\n \n \n def title_hook( text ):\n \n pass\n \n \n gallery_seed_log.AddGallerySeeds( ( gallery_seed, ) )\n \n stop_reason = 'unknown stop reason'\n \n try:\n \n keep_checking = True\n \n while keep_checking and gallery_seed_log.WorkToDo():\n \n p1 = HC.options[ 'pause_subs_sync' ]\n p2 = HG.view_shutdown\n \n if p1 or p2:\n \n return\n \n \n if job_key.IsCancelled():\n \n stop_reason = 'gallery parsing cancelled, likely by user'\n \n self._DelayWork( 600, stop_reason )\n \n return\n \n \n gallery_seed = gallery_seed_log.GetNextGallerySeed( CC.STATUS_UNKNOWN )\n \n if gallery_seed is None:\n \n stop_reason = 'thought there was a page to check, but apparently there was not!'\n \n break\n \n \n next_gallery_page_hit_timestamp = self._last_gallery_page_hit_timestamp + HG.client_controller.new_options.GetInteger( 'gallery_page_wait_period_subscriptions' )\n \n if not HydrusData.TimeHasPassed( next_gallery_page_hit_timestamp ):\n \n if not done_first_page:\n \n page_check_status = 'checking first page ' + HydrusData.TimestampToPrettyTimeDelta( next_gallery_page_hit_timestamp )\n \n else:\n \n page_check_status = HydrusData.ToHumanInt( total_new_urls_for_this_sync ) + ' new urls found, checking next page ' + HydrusData.TimestampToPrettyTimeDelta( next_gallery_page_hit_timestamp )\n \n \n job_key.SetVariable( 'popup_text_1', prefix + ': ' + page_check_status )\n \n time.sleep( 1 )\n \n continue\n \n \n job_key.SetVariable( 'popup_text_1', prefix + ': found ' + HydrusData.ToHumanInt( total_new_urls_for_this_sync ) + ' new urls, checking next page' )\n \n this_page_file_seed_cache = ClientImportFileSeeds.FileSeedCache()\n \n try:\n \n ( num_urls_added, num_urls_already_in_file_seed_cache, num_urls_total, result_404 ) = gallery_seed.WorkOnURL( gallery_seed_log, this_page_file_seed_cache, status_hook, title_hook, ClientImporting.GenerateSubscriptionNetworkJobFactory( self._GetNetworkJobSubscriptionKey( query ) ), ClientImporting.GenerateMultiplePopupNetworkJobPresentationContextFactory( job_key ), self._file_import_options, gallery_urls_seen_before = gallery_urls_seen_this_sync )\n \n except HydrusExceptions.CancelledException as e:\n \n stop_reason = 'gallery network job cancelled, likely by user'\n \n self._DelayWork( 600, stop_reason )\n \n return\n \n except Exception as e:\n \n stop_reason = HydrusData.ToUnicode( e )\n \n raise\n \n finally:\n \n self._last_gallery_page_hit_timestamp = HydrusData.GetNow()\n done_first_page = True\n \n \n if num_urls_already_in_file_seed_cache > 0:\n \n seen_some_existing_urls = True\n \n \n if num_urls_total == 0:\n \n stop_reason = 'finished query'\n \n break\n \n \n for file_seed in this_page_file_seed_cache.GetFileSeeds():\n \n if file_limit_for_this_sync is not None and total_new_urls_for_this_sync >= file_limit_for_this_sync:\n \n if this_is_initial_sync:\n \n stop_reason = 'hit initial file limit'\n \n else:\n \n if not seen_some_existing_urls: # this tests if we saw some urls in another gallery identifier\n \n self._ShowHitPeriodicFileLimitMessage( query_text )\n \n \n stop_reason = 'hit periodic file limit'\n \n \n keep_checking = False\n \n break\n \n \n if file_seed in file_seeds_to_add:\n \n # this catches the occasional overflow when a new file is uploaded while gallery parsing is going on\n \n continue\n \n \n if file_seed_cache.HasFileSeed( file_seed ):\n \n num_existing_urls += 1\n \n WE_HIT_OLD_GROUND_THRESHOLD = 5\n \n if num_existing_urls > WE_HIT_OLD_GROUND_THRESHOLD:\n \n keep_checking = False\n \n stop_reason = 'saw ' + HydrusData.ToHumanInt( WE_HIT_OLD_GROUND_THRESHOLD ) + ' previously seen urls, so assuming we caught up'\n \n break\n \n \n else:\n \n file_seeds_to_add.add( file_seed )\n file_seeds_to_add_ordered.append( file_seed )\n \n total_new_urls_for_this_sync += 1\n \n \n \n \n finally:\n \n while gallery_seed_log.WorkToDo():\n \n gallery_seed = gallery_seed_log.GetNextGallerySeed( CC.STATUS_UNKNOWN )\n \n if gallery_seed is None:\n \n break\n \n \n gallery_seed.SetStatus( CC.STATUS_VETOED, note = stop_reason )\n \n \n \n else:\n \n def network_job_factory( method, url, **kwargs ):\n \n network_job = ClientNetworkingJobs.NetworkJobSubscription( self._GetNetworkJobSubscriptionKey( query ), method, url, **kwargs )\n \n job_key.SetVariable( 'popup_network_job', network_job )\n \n network_job.OverrideBandwidth( 30 )\n \n return network_job\n \n \n gallery.SetNetworkJobFactory( network_job_factory )\n \n page_index = 0\n num_existing_urls = 0\n keep_checking = True\n \n while keep_checking:\n \n new_urls_this_page = 0\n \n try:\n \n p1 = HC.options[ 'pause_subs_sync' ]\n p2 = HG.view_shutdown\n \n if p1 or p2:\n \n return\n \n \n if job_key.IsCancelled():\n \n raise HydrusExceptions.CancelledException( 'gallery parsing cancelled, likely by user' )\n \n \n next_gallery_page_hit_timestamp = self._last_gallery_page_hit_timestamp + HG.client_controller.new_options.GetInteger( 'gallery_page_wait_period_subscriptions' )\n \n if not HydrusData.TimeHasPassed( next_gallery_page_hit_timestamp ):\n \n if not done_first_page:\n \n page_check_status = 'checking first page ' + HydrusData.TimestampToPrettyTimeDelta( next_gallery_page_hit_timestamp )\n \n else:\n \n page_check_status = HydrusData.ToHumanInt( total_new_urls_for_this_sync ) + ' new urls found, checking next page ' + HydrusData.TimestampToPrettyTimeDelta( next_gallery_page_hit_timestamp )\n \n \n job_key.SetVariable( 'popup_text_1', prefix + ': ' + page_check_status )\n \n time.sleep( 1 )\n \n continue\n \n \n job_key.SetVariable( 'popup_text_1', prefix + ': found ' + HydrusData.ToHumanInt( total_new_urls_for_this_sync ) + ' new urls, checking next page' )\n \n gallery_url = gallery.GetGalleryPageURL( query_text, page_index )\n \n gallery_seed = ClientImportGallerySeeds.GallerySeed( gallery_url, can_generate_more_pages = False )\n \n gallery_seed_log.AddGallerySeeds( ( gallery_seed, ) )\n \n try:\n \n ( page_of_file_seeds, definitely_no_more_pages ) = gallery.GetPage( gallery_url )\n \n finally:\n \n self._last_gallery_page_hit_timestamp = HydrusData.GetNow()\n \n \n done_first_page = True\n \n page_index += 1\n \n if definitely_no_more_pages:\n \n keep_checking = False\n \n \n for file_seed in page_of_file_seeds:\n \n if file_limit_for_this_sync is not None and total_new_urls_for_this_sync >= file_limit_for_this_sync:\n \n if not seen_some_existing_urls and not this_is_initial_sync:\n \n self._ShowHitPeriodicFileLimitMessage( query_text )\n \n \n keep_checking = False\n \n break\n \n \n if file_seed in file_seeds_to_add:\n \n # this catches the occasional overflow when a new file is uploaded while gallery parsing is going on\n \n continue\n \n \n if file_seed_cache.HasFileSeed( file_seed ):\n \n seen_some_existing_urls = True\n \n num_existing_urls += 1\n \n if num_existing_urls > 5:\n \n keep_checking = False\n \n break\n \n \n else:\n \n file_seeds_to_add.add( file_seed )\n file_seeds_to_add_ordered.append( file_seed )\n \n new_urls_this_page += 1\n total_new_urls_for_this_sync += 1\n \n \n \n if new_urls_this_page == 0:\n \n keep_checking = False\n \n \n gallery_seed_status = CC.STATUS_SUCCESSFUL_AND_NEW\n gallery_seed_note = 'checked OK - found ' + HydrusData.ToUnicode( new_urls_this_page ) + ' new urls'\n \n except HydrusExceptions.CancelledException as e:\n \n gallery_seed_status = CC.STATUS_VETOED\n gallery_seed_note = HydrusData.ToUnicode( e )\n \n self._DelayWork( 600, gallery_seed_note )\n \n return\n \n except HydrusExceptions.NotFoundException:\n \n gallery_seed_status = CC.STATUS_VETOED\n gallery_seed_note = '404'\n \n # paheal now 404s when no results, so just naturally break\n \n break\n \n except Exception as e:\n \n gallery_seed_status = CC.STATUS_ERROR\n gallery_seed_note = HydrusData.ToUnicode( e )\n \n raise\n \n finally:\n \n gallery_seed.SetStatus( gallery_seed_status, note = gallery_seed_note )\n \n gallery_seed_log.NotifyGallerySeedsUpdated( ( gallery_seed, ) )\n \n \n \n \n \n file_seeds_to_add_ordered.reverse()\n \n # 'first' urls are now at the end, so the file_seed_cache should stay roughly in oldest->newest order\n \n file_seed_cache.AddFileSeeds( file_seeds_to_add_ordered )\n \n query.RegisterSyncComplete()\n query.UpdateNextCheckTime( self._checker_options )\n \n if query.IsDead():\n \n if this_is_initial_sync:\n \n HydrusData.ShowText( 'The query \"' + query_text + '\" for subscription \"' + self._name + '\" did not find any files on its first sync! Could the query text have a typo, like a missing underscore?' )\n \n else:\n \n HydrusData.ShowText( 'The query \"' + query_text + '\" for subscription \"' + self._name + '\" appears to be dead!' )\n \n \n else:\n \n if this_is_initial_sync:\n \n if not self._QueryBandwidthIsOK( query ) and not have_made_an_initial_sync_bandwidth_notification:\n \n HydrusData.ShowText( 'FYI: The query \"' + query_text + '\" for subscription \"' + self._name + '\" performed its initial sync ok, but that domain is short on bandwidth right now, so no files will be downloaded yet. The subscription will catch up in future as bandwidth becomes available. You can review the estimated time until bandwidth is available under the manage subscriptions dialog. If more queries are performing initial syncs in this run, they may be the same.' )\n \n have_made_an_initial_sync_bandwidth_notification = True\n \n \n \n \n \n \n def _SyncQueryCanDoWork( self ):\n \n return True in ( query.CanSync() for query in self._queries )\n \n \n def CanCheckNow( self ):\n \n return True in ( query.CanCheckNow() for query in self._queries )\n \n \n def CanCompact( self ):\n \n return True in ( query.CanCompact( self._checker_options ) for query in self._queries )\n \n \n def CanReset( self ):\n \n return True in ( not query.IsInitialSync() for query in self._queries )\n \n \n def CanRetryFailures( self ):\n \n return True in ( query.CanRetryFailed() for query in self._queries )\n \n \n def CanRetryIgnored( self ):\n \n return True in ( query.CanRetryIgnored() for query in self._queries )\n \n \n def CanScrubDelay( self ):\n \n return not HydrusData.TimeHasPassed( self._no_work_until )\n \n \n def CheckNow( self ):\n \n for query in self._queries:\n \n query.CheckNow()\n \n \n self.ScrubDelay()\n \n \n def Compact( self ):\n \n for query in self._queries:\n \n query.Compact( self._checker_options )\n \n \n \n def GetBandwidthWaitingEstimate( self, query ):\n \n example_network_contexts = self._GetExampleNetworkContexts( query )\n \n estimate = HG.client_controller.network_engine.bandwidth_manager.GetWaitingEstimate( example_network_contexts )\n \n return estimate\n \n \n def GetBandwidthWaitingEstimateMinMax( self ):\n \n if len( self._queries ) == 0:\n \n return ( 0, 0 )\n \n \n estimates = []\n \n for query in self._queries:\n \n example_network_contexts = self._GetExampleNetworkContexts( query )\n \n estimate = HG.client_controller.network_engine.bandwidth_manager.GetWaitingEstimate( example_network_contexts )\n \n estimates.append( estimate )\n \n \n min_estimate = min( estimates )\n max_estimate = max( estimates )\n \n return ( min_estimate, max_estimate )\n \n \n def GetGalleryIdentifier( self ):\n \n return self._gallery_identifier\n \n \n def GetQueries( self ):\n \n return self._queries\n \n \n def GetPresentationOptions( self ):\n \n return ( self._publish_files_to_popup_button, self._publish_files_to_page, self._merge_query_publish_events )\n \n \n def GetTagImportOptions( self ):\n \n return self._tag_import_options\n \n \n def HasQuerySearchText( self, search_text ):\n \n for query in self._queries:\n \n query_text = query.GetQueryText()\n \n if search_text in query_text:\n \n return True\n \n \n \n return False\n \n \n def Merge( self, potential_mergee_subscriptions ):\n \n unmergable_subscriptions = []\n \n for subscription in potential_mergee_subscriptions:\n \n if subscription._gallery_identifier == self._gallery_identifier:\n \n my_new_queries = [ query.Duplicate() for query in subscription._queries ]\n \n self._queries.extend( my_new_queries )\n \n else:\n \n unmergable_subscriptions.append( subscription )\n \n \n \n return unmergable_subscriptions\n \n \n def PauseResume( self ):\n \n self._paused = not self._paused\n \n \n def Reset( self ):\n \n for query in self._queries:\n \n query.Reset()\n \n \n self.ScrubDelay()\n \n \n def RetryFailures( self ):\n \n for query in self._queries:\n \n query.RetryFailures()\n \n \n \n def RetryIgnored( self ):\n \n for query in self._queries:\n \n query.RetryIgnored()\n \n \n \n def ReviveDead( self ):\n \n for query in self._queries:\n \n if query.IsDead():\n \n query.CheckNow()\n \n \n \n \n def Separate( self, base_name, only_these_queries = None ):\n \n if only_these_queries is None:\n \n only_these_queries = set( self._queries )\n \n else:\n \n only_these_queries = set( only_these_queries )\n \n \n subscriptions = []\n \n for query in self._queries:\n \n if query not in only_these_queries:\n \n continue\n \n \n subscription = self.Duplicate()\n \n subscription._queries = [ query.Duplicate() ]\n \n subscription.SetName( base_name + ': ' + query.GetQueryText() )\n \n subscriptions.append( subscription )\n \n \n self._queries = [ query for query in self._queries if query not in only_these_queries ]\n \n return subscriptions\n \n \n def SetCheckerOptions( self, checker_options ):\n \n self._checker_options = checker_options\n \n for query in self._queries:\n \n query.UpdateNextCheckTime( self._checker_options )\n \n \n \n def SetPresentationOptions( self, publish_files_to_popup_button, publish_files_to_page, merge_query_publish_events ):\n \n self._publish_files_to_popup_button = publish_files_to_popup_button\n self._publish_files_to_page = publish_files_to_page\n self._merge_query_publish_events = merge_query_publish_events\n \n \n def SetTagImportOptions( self, tag_import_options ):\n \n self._tag_import_options = tag_import_options.Duplicate()\n \n \n def SetTuple( self, gallery_identifier, gallery_stream_identifiers, queries, checker_options, initial_file_limit, periodic_file_limit, paused, file_import_options, tag_import_options, no_work_until ):\n \n self._gallery_identifier = gallery_identifier\n self._gallery_stream_identifiers = gallery_stream_identifiers\n self._queries = queries\n self._checker_options = checker_options\n self._initial_file_limit = initial_file_limit\n self._periodic_file_limit = periodic_file_limit\n self._paused = paused\n \n self._file_import_options = file_import_options\n self._tag_import_options = tag_import_options\n \n self._no_work_until = no_work_until\n \n \n def ScrubDelay( self ):\n \n self._no_work_until = 0\n self._no_work_until_reason = ''\n \n \n def Sync( self ):\n \n p1 = not self._paused\n p2 = not HG.view_shutdown\n p3 = self._NoDelays()\n p4 = self._SyncQueryCanDoWork()\n p5 = self._WorkOnFilesCanDoWork()\n \n if HG.subscription_report_mode:\n \n message = 'Subscription \"' + self._name + '\" entered sync.'\n message += os.linesep\n message += 'Unpaused: ' + str( p1 )\n message += os.linesep\n message += 'No delays: ' + str( p3 )\n message += os.linesep\n message += 'Sync can do work: ' + str( p4 )\n message += os.linesep\n message += 'Files can do work: ' + str( p5 )\n \n HydrusData.ShowText( message )\n \n \n if p1 and p2 and p3 and ( p4 or p5 ):\n \n job_key = ClientThreading.JobKey( pausable = False, cancellable = True )\n \n try:\n \n job_key.SetVariable( 'popup_title', 'subscriptions - ' + self._name )\n \n HG.client_controller.pub( 'message', job_key )\n \n self._SyncQuery( job_key )\n \n self._WorkOnFiles( job_key )\n \n except HydrusExceptions.NetworkException as e:\n \n if isinstance( e, HydrusExceptions.NetworkInfrastructureException ):\n \n delay = 3600\n \n else:\n \n delay = HC.UPDATE_DURATION\n \n \n HydrusData.Print( 'The subscription ' + self._name + ' encountered an exception when trying to sync:' )\n HydrusData.PrintException( e )\n \n job_key.SetVariable( 'popup_text_1', 'Encountered a network error, will retry again later' )\n \n self._DelayWork( delay, 'network error: ' + HydrusData.ToUnicode( e ) )\n \n time.sleep( 5 )\n \n except Exception as e:\n \n HydrusData.ShowText( 'The subscription ' + self._name + ' encountered an exception when trying to sync:' )\n HydrusData.ShowException( e )\n \n self._DelayWork( HC.UPDATE_DURATION, 'error: ' + HydrusData.ToUnicode( e ) )\n \n finally:\n \n job_key.DeleteVariable( 'popup_network_job' )\n \n \n HG.client_controller.WriteSynchronous( 'serialisable', self )\n \n if job_key.HasVariable( 'popup_files' ):\n \n job_key.Finish()\n \n else:\n \n job_key.Delete()\n \n \n \n \n def ToTuple( self ):\n \n return ( self._name, self._gallery_identifier, self._gallery_stream_identifiers, self._queries, self._checker_options, self._initial_file_limit, self._periodic_file_limit, self._paused, self._file_import_options, self._tag_import_options, self._no_work_until, self._no_work_until_reason )\n \n \nHydrusSerialisable.SERIALISABLE_TYPES_TO_OBJECT_TYPES[ HydrusSerialisable.SERIALISABLE_TYPE_SUBSCRIPTION ] = Subscription\n\nclass SubscriptionQuery( HydrusSerialisable.SerialisableBase ):\n \n SERIALISABLE_TYPE = HydrusSerialisable.SERIALISABLE_TYPE_SUBSCRIPTION_QUERY\n SERIALISABLE_NAME = 'Subscription Query'\n SERIALISABLE_VERSION = 2\n \n def __init__( self, query = 'query text' ):\n \n HydrusSerialisable.SerialisableBase.__init__( self )\n \n self._query = query\n self._check_now = False\n self._last_check_time = 0\n self._next_check_time = 0\n self._paused = False\n self._status = ClientImporting.CHECKER_STATUS_OK\n self._gallery_seed_log = ClientImportGallerySeeds.GallerySeedLog()\n self._file_seed_cache = ClientImportFileSeeds.FileSeedCache()\n \n \n def _GetSerialisableInfo( self ):\n \n serialisable_gallery_seed_log = self._gallery_seed_log.GetSerialisableTuple()\n serialisable_file_seed_cache = self._file_seed_cache.GetSerialisableTuple()\n \n return ( self._query, self._check_now, self._last_check_time, self._next_check_time, self._paused, self._status, serialisable_gallery_seed_log, serialisable_file_seed_cache )\n \n \n def _InitialiseFromSerialisableInfo( self, serialisable_info ):\n \n ( self._query, self._check_now, self._last_check_time, self._next_check_time, self._paused, self._status, serialisable_gallery_seed_log, serialisable_file_seed_cache ) = serialisable_info\n \n self._gallery_seed_log = HydrusSerialisable.CreateFromSerialisableTuple( serialisable_gallery_seed_log )\n self._file_seed_cache = HydrusSerialisable.CreateFromSerialisableTuple( serialisable_file_seed_cache )\n \n \n def _UpdateSerialisableInfo( self, version, old_serialisable_info ):\n \n if version == 1:\n \n ( query, check_now, last_check_time, next_check_time, paused, status, serialisable_file_seed_cache ) = old_serialisable_info\n \n gallery_seed_log = ClientImportGallerySeeds.GallerySeedLog()\n \n serialisable_gallery_seed_log = gallery_seed_log.GetSerialisableTuple()\n \n new_serialisable_info = ( query, check_now, last_check_time, next_check_time, paused, status, serialisable_gallery_seed_log, serialisable_file_seed_cache )\n \n return ( 2, new_serialisable_info )\n \n \n \n def CanWorkOnFiles( self ):\n \n file_seed = self._file_seed_cache.GetNextFileSeed( CC.STATUS_UNKNOWN )\n \n if HG.subscription_report_mode:\n \n HydrusData.ShowText( 'Query \"' + self._query + '\" CanWorkOnFiles test. Next import is ' + repr( file_seed ) + '.' )\n \n \n return file_seed is not None\n \n \n def CanCheckNow( self ):\n \n return not self._check_now\n \n \n def CanCompact( self, checker_options ):\n \n death_period = checker_options.GetDeathFileVelocityPeriod()\n \n compact_before_this_source_time = self._last_check_time - ( death_period * 2 )\n \n return self._file_seed_cache.CanCompact( compact_before_this_source_time )\n \n \n def CanRetryFailed( self ):\n \n return self._file_seed_cache.GetFileSeedCount( CC.STATUS_ERROR ) > 0\n \n \n def CanRetryIgnored( self ):\n \n return self._file_seed_cache.GetFileSeedCount( CC.STATUS_VETOED ) > 0\n \n \n def CanSync( self ):\n \n if HG.subscription_report_mode:\n \n HydrusData.ShowText( 'Query \"' + self._query + '\" CanSync test. Paused status is ' + str( self._paused ) + ' and check time due is ' + str( HydrusData.TimeHasPassed( self._next_check_time ) ) + ' and check_now is ' + str( self._check_now ) + '.' )\n \n \n if self._paused:\n \n return False\n \n \n return HydrusData.TimeHasPassed( self._next_check_time ) or self._check_now\n \n \n def CheckNow( self ):\n \n self._check_now = True\n self._paused = False\n \n self._next_check_time = 0\n self._status = ClientImporting.CHECKER_STATUS_OK\n \n \n def Compact( self, checker_options ):\n \n death_period = checker_options.GetDeathFileVelocityPeriod()\n \n compact_before_this_time = self._last_check_time - ( death_period * 2 )\n \n return self._file_seed_cache.Compact( compact_before_this_time )\n \n \n def GetFileSeedCache( self ):\n \n return self._file_seed_cache\n \n \n def GetGallerySeedLog( self ):\n \n return self._gallery_seed_log\n \n \n def GetLastChecked( self ):\n \n return self._last_check_time\n \n \n def GetLatestAddedTime( self ):\n \n return self._file_seed_cache.GetLatestAddedTime()\n \n \n def GetNextCheckStatusString( self ):\n \n if self._check_now:\n \n return 'checking on dialog ok'\n \n elif self._status == ClientImporting.CHECKER_STATUS_DEAD:\n \n return 'dead, so not checking'\n \n else:\n \n if HydrusData.TimeHasPassed( self._next_check_time ):\n \n s = 'imminent'\n \n else:\n \n s = HydrusData.TimestampToPrettyTimeDelta( self._next_check_time )\n \n \n if self._paused:\n \n s = 'paused, but would be ' + s\n \n \n return s\n \n \n \n def GetNumURLsAndFailed( self ):\n \n return ( self._file_seed_cache.GetFileSeedCount( CC.STATUS_UNKNOWN ), len( self._file_seed_cache ), self._file_seed_cache.GetFileSeedCount( CC.STATUS_ERROR ) )\n \n \n def GetQueryText( self ):\n \n return self._query\n \n \n def IsDead( self ):\n \n return self._status == ClientImporting.CHECKER_STATUS_DEAD\n \n \n def IsInitialSync( self ):\n \n return self._last_check_time == 0\n \n \n def IsPaused( self ):\n \n return self._paused\n \n \n def PausePlay( self ):\n \n self._paused = not self._paused\n \n \n def RegisterSyncComplete( self ):\n \n self._last_check_time = HydrusData.GetNow()\n \n self._check_now = False\n \n \n def Reset( self ):\n \n self._last_check_time = 0\n self._next_check_time = 0\n self._status = ClientImporting.CHECKER_STATUS_OK\n self._paused = False\n \n self._file_seed_cache = ClientImportFileSeeds.FileSeedCache()\n \n \n def RetryFailures( self ):\n \n self._file_seed_cache.RetryFailures() \n \n \n def RetryIgnored( self ):\n \n self._file_seed_cache.RetryIgnored() \n \n \n def SetCheckNow( self, check_now ):\n \n self._check_now = check_now\n \n \n def SetPaused( self, paused ):\n \n self._paused = paused\n \n \n def SetQueryAndSeeds( self, query, file_seed_cache, gallery_seed_log ):\n \n self._query = query\n self._file_seed_cache = file_seed_cache\n self._gallery_seed_log = gallery_seed_log\n \n \n def UpdateNextCheckTime( self, checker_options ):\n \n if self._check_now:\n \n self._next_check_time = 0\n \n self._status = ClientImporting.CHECKER_STATUS_OK\n \n else:\n \n if checker_options.IsDead( self._file_seed_cache, self._last_check_time ):\n \n self._status = ClientImporting.CHECKER_STATUS_DEAD\n \n self._paused = True\n \n \n last_next_check_time = self._next_check_time\n \n self._next_check_time = checker_options.GetNextCheckTime( self._file_seed_cache, self._last_check_time, last_next_check_time )\n \n \n \n def ToTuple( self ):\n \n return ( self._query, self._check_now, self._last_check_time, self._next_check_time, self._paused, self._status )\n \n \nHydrusSerialisable.SERIALISABLE_TYPES_TO_OBJECT_TYPES[ HydrusSerialisable.SERIALISABLE_TYPE_SUBSCRIPTION_QUERY ] = SubscriptionQuery\n","sub_path":"include/ClientImportSubscriptions.py","file_name":"ClientImportSubscriptions.py","file_ext":"py","file_size_in_byte":69488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"87276711","text":"#!/usr/bin/env python\n\nimport os\nimport random\n\n\nclass LU:\n\tdef __init__(self, tmpdir='/tmp'):\n\t\tself.tmpdir = tmpdir\n\t\n\t\n\tdef getCmdArgs(self, cargs, pattern):\n\t\treturn True\n\t\n\t\n\tdef loadFile(self, name, single_line=False):\n\t\tif name!='':\n\t\t\ttry:\n\t\t\t\tf=open(name, 'r')\n\t\t\t\tout=f.read()\n\t\t\t\tf.close()\n\t\t\t\tif single_line==True:\n\t\t\t\t\tout=out.replace(\"\\n\", '')\n\t\t\t\treturn out\n\t\t\texcept:\n\t\t\t\tpass\n\t\t\t\treturn False\n\t\telse:\n\t\t\treturn False\n\t\n\tdef saveFile(self, name, content):\n\t\tif name!='':\n\t\t\ttry:\n\t\t\t\tf=open(name, 'w')\n\t\t\t\tf.write(content)\n\t\t\t\tf.close()\n\t\t\t\treturn True\n\t\t\texcept:\n\t\t\t\tpass\n\t\t\t\treturn False\n\t\telse:\n\t\t\treturn False\n\t\n\tdef rmFile(self, name):\n\t\tif name!='':\n\t\t\ttry:\n\t\t\t\tos.remove(name)\n\t\t\t\treturn True\n\t\t\texcept:\n\t\t\t\tpass\n\t\t\t\treturn False\n\t\telse:\n\t\t\treturn False\n\t\n\t\n\tdef execCmd(self, command, single_line=False):\n\t\tret=dict({\"status\":False, \"stdout\":\"\", \"stderr\":\"\"})\n\t\tif command!='':\n\t\t\toutid=str(random.randint(100000, 999999))\n\t\t\tfout=self.tmpdir+'/'+outid+'.stdout'\n\t\t\tferr=self.tmpdir+'/'+outid+'.stderr'\n\t\t\ttry:\n\t\t\t\tos.system(command+' > '+fout+' 2>'+ferr)\n\t\t\t\tret['stdout']=self.loadFile(fout)\n\t\t\t\tret['stderr']=self.loadFile(ferr)\n\t\t\t\tself.rmFile(fout)\n\t\t\t\tself.rmFile(ferr)\n\t\t\t\tif single_line==True:\n\t\t\t\t\tret['stdout']=ret['stdout'].replace(\"\\n\", '')\n\t\t\t\tif ret['stdout']=='' or ret['stdout']==\"\\n\":\n\t\t\t\t\tif ret['stderr']!='' and ret['stderr']==\"\\n\":\n\t\t\t\t\t\tret['status']=False\n\t\t\t\t\telse:\n\t\t\t\t\t\tret['status']=True\n\t\t\t\telse:\n\t\t\t\t\tret['status']=False\n\t\t\t\treturn ret\n\t\t\texcept:\n\t\t\t\tpass\n\t\t\t\treturn ret\n\t\telse:\n\t\t\treturn ret\n\n\n\nclass ConfConstructor:\n\tdef __init__(self, cfgdir):\n\t\tself.cfgdir = cfgdir\n\t\n\tdef load(self, name):\n\t\tvalues={}\n\t\tif name!='':\n\t\t\ttry:\n\t\t\t\tf=open(self.cfgdir+'/'+name, 'r')\n\t\t\t\tlines=f.read()\n\t\t\t\tf.close()\n\t\t\t\tline=lines.split(\"\\n\")\n\t\t\t\tfor item in line:\n\t\t\t\t\tval=item.split('=')\n\t\t\t\t\tif val[0]!='' and len(val)>1:\n\t\t\t\t\t\tvalue=val[1].replace('\"', '')\n\t\t\t\t\t\tvalues[val[0]]=value\n\t\t\texcept:\n\t\t\t\tpass\n\t\t\treturn values\n\t\telse:\n\t\t\treturn values\n\t\n\tdef save(self, name, values):\n\t\tif name!='':\n\t\t\tout='#!/bin/bash'\n\t\t\tout=out+\"\\n\\n\"\n\t\t\ttry:\n\t\t\t\titems=values.items()\n\t\t\t\tfor item in items:\n\t\t\t\t\tout=out+item[0]+'=\"'+item[1]+'\"'+\"\\n\"\n\t\t\t\tf=open(self.cfgdir+'/'+name, 'w')\n\t\t\t\tf.write(out)\n\t\t\t\tf.close()\n\t\t\t\treturn True\n\t\t\texcept:\n\t\t\t\tpass\n\t\t\t\treturn False\n\t\telse:\n\t\t\treturn False\n\n\n\nclass LogIt:\n\tdef __init__(self, process, pid=0, facility='user'):\n\t\tself.pname=process\n\t\tself.pid=pid\n\t\tself.facility=facility\n\t\t\n\t\tself.lecho='lecho -o '+self.pname+' '+self.facility+' '\n\t\tif self.pid>0:\n\t\t\tself.lecho=self.lecho+'-i '+str(pid)+' '\n\t\n\t\n\tdef set(self, severity, message, args=dict({}), callback=False):\n\t\tsevlevel=self.checkSeverity(severity)\n\t\tos.system(self.lecho+sevlevel+' \"'+message+'\"')\n\t\tif bool(callback)!=False:\n\t\t\tcallback(severity, message, args)\n\t\n\t\n\tdef checkSeverity(self, severity):\n\t\tif isinstance(severity, int):\n\t\t\tlevels=['emerg', 'alert', 'crit', 'err', 'warn', 'notice', 'info', 'debug']\n\t\t\tlevel=levels[severity]\n\t\telse:\n\t\t\tlevel=severity\n\t\treturn level\n","sub_path":"sources/v1609/lubase.py","file_name":"lubase.py","file_ext":"py","file_size_in_byte":3016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"282341777","text":"from django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.conf import settings\n\nclass Message(models.Model):\n\n\tauthor = models.ForeignKey(\n\t\tsettings.AUTH_USER_MODEL,\n\t\ton_delete=models.CASCADE\n\t)\n\n\ttitle = models.TextField(max_length=255,\n\t\thelp_text=_('Broadcast message title'))\n\n\ttext = models.TextField(max_length=getattr(settings, 'COVIDOFF_MAXIMUM_BROADCAST_MESSAGE_SIZE', 4096),\n\t\thelp_text=_('Broadcast message text'))\n\n\tcreation_date = models.DateTimeField(auto_now_add=True,\n\t\thelp_text=_('Creation date'))\n\n\tlast_update = models.DateTimeField(auto_now=True,\n\t\thelp_text=_('Last update'))\n\nclass Subscription(models.Model):\n\n\tendpoint = models.TextField(max_length=255,\n\t\thelp_text=_('Subscription endpoint ARN'))\n\n\tdevice = models.TextField(max_length=255,\n\t\thelp_text=_('Subscription device ID'))\n","sub_path":"webapp/covidoff/broadcast/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"354804222","text":"\nimport numpy as np\n\nfrom spectral_cube._moments import _moment_shp\n# from spectral_cube.np_compat import allbadtonan\n\n'''\nFunctions for making moment error maps.\n\nBorrows heavily from the functionality in _moments.py from spectral-cube.\n\nFunctions require, at minimum, a SpectralCube object and a scale value that\ncharacterizes the noise.\n'''\n\n\ndef _slice0(cube, axis, scale):\n \"\"\"\n 0th moment along an axis, calculated slicewise\n\n Parameters\n ----------\n cube : SpectralCube\n axis : int\n scale : float\n\n Returns\n -------\n moment0_error : array\n \"\"\"\n shp = _moment_shp(cube, axis)\n result = np.zeros(shp)\n\n view = [slice(None)] * 3\n\n valid = np.zeros(shp, dtype=np.bool)\n for i in range(cube.shape[axis]):\n view[axis] = i\n plane = cube._mask.include(data=cube._data, wcs=cube._wcs, view=view)\n valid |= plane\n result += plane\n result = scale * np.sqrt(result)\n result[~valid] = np.nan\n return result\n\n\ndef _slice1(cube, axis, scale, moment0, moment1):\n \"\"\"\n 1st moment along an axis, calculated slicewise\n\n Parameters\n ----------\n cube : SpectralCube\n axis : int\n scale : float\n moment0 : 0th moment\n moment1 : 1st moment\n\n Returns\n -------\n moment1_error : array\n \"\"\"\n shp = _moment_shp(cube, axis)\n result = np.zeros(shp)\n\n view = [slice(None)] * 3\n pix_cen = cube._pix_cen()[axis]\n\n for i in range(cube.shape[axis]):\n view[axis] = i\n result += np.power((pix_cen[view] - moment1), 2)\n return (scale / moment0) * np.sqrt(result)\n\n\ndef _slice2(cube, axis, scale, moment0, moment1, moment2,\n moment1_err):\n \"\"\"\n 2nd moment error along an axis, calculated slicewise\n\n Parameters\n ----------\n cube : SpectralCube\n axis : int\n scale : float\n moment0 : 0th moment\n moment1 : 1st moment\n moment2 : 2nd moment\n moment1_err : 1st moment error\n\n Returns\n -------\n moment1_error : array\n \"\"\"\n shp = _moment_shp(cube, axis)\n term1 = np.zeros(shp)\n term2 = np.zeros(shp)\n\n view = [slice(None)] * 3\n pix_cen = cube._pix_cen()[axis]\n pix_size = cube._pix_size()[axis]\n\n for i in range(cube.shape[axis]):\n view[axis] = i\n plane = cube._get_filled_data(fill=0, view=view)\n\n term1 += scale**2 * \\\n np.power((np.power((pix_cen[view] - moment1), 2) -\n moment2), 2)\n\n term2 += (plane*pix_size[view]) * (pix_cen[view] - moment1)\n\n return (1/moment0) * np.sqrt(term1 + 4*np.power(moment1_err*term2, 2))\n\n\ndef moment_raywise(cube, order, axis):\n \"\"\"\n Compute moments by accumulating the answer one ray at a time\n \"\"\"\n shp = _moment_shp(cube, axis)\n out = np.zeros(shp) * np.nan\n\n pix_cen = cube._pix_cen()[axis]\n pix_size = cube._pix_size()[axis]\n\n for x, y, slc in cube._iter_rays(axis):\n # the intensity, i.e. the weights\n include = cube._mask.include(data=cube._data, wcs=cube._wcs,\n view=slc)\n if not include.any():\n continue\n\n data = cube.flattened(slc).value * pix_size[slc][include]\n\n if order == 0:\n out[x, y] = data.sum()\n continue\n\n order1 = (data * pix_cen[slc][include]).sum() / data.sum()\n if order == 1:\n out[x, y] = order1\n continue\n\n ordern = (data * (pix_cen[slc][include] - order1) ** order).sum()\n ordern /= data.sum()\n\n out[x, y] = ordern\n return out\n\n\ndef _cube0(cube, axis, scale):\n '''\n\n '''\n\n error_arr = scale * \\\n np.sqrt(np.sum(cube.mask.include(), axis=axis))\n\n error_arr[error_arr == 0] = np.NaN\n\n return error_arr\n\n\ndef _cube1(cube, axis, scale, moment0, moment1):\n '''\n\n '''\n\n pix_cen = cube._pix_cen()[axis]\n\n good_pix = np.isfinite(moment0) + np.isfinite(moment1)\n\n error_arr = np.zeros(moment1.shape)\n\n error_arr[good_pix] = \\\n (scale / moment0[good_pix]) * \\\n np.sqrt(np.sum(np.power((pix_cen - moment1) * good_pix, 2),\n axis=0))[good_pix]\n\n error_arr[~good_pix] = np.NaN\n\n error_arr[error_arr == 0] = np.NaN\n\n return error_arr\n\n\ndef _cube2(cube, axis, scale, moment0, moment1, moment2, moment1_err):\n '''\n '''\n\n pix_cen = cube._pix_cen()[axis]\n\n data = cube._get_filled_data() * cube._pix_size()[axis]\n\n good_pix = np.isfinite(moment0) + np.isfinite(moment1) + \\\n np.isfinite(moment2)\n\n error_arr = np.zeros(moment2.shape)\n\n term11 = (np.power(pix_cen - moment1, 2) * good_pix) - moment2\n\n term1 = scale**2 * np.sum(np.power(term11, 2), axis=axis)[good_pix]\n\n term21 = np.nansum((data * (pix_cen - moment1)), axis=axis)\n\n term2 = 4 * \\\n np.power(moment1_err*term21, 2)[good_pix]\n\n error_arr[good_pix] = (1 / moment0[good_pix]) * np.sqrt(term1 + term2)\n\n error_arr[~good_pix] = np.NaN\n\n error_arr[error_arr == 0] = np.NaN\n\n return error_arr\n","sub_path":"turbustat/data_reduction/_moment_errs.py","file_name":"_moment_errs.py","file_ext":"py","file_size_in_byte":4978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"96262022","text":"\"\"\"그저께, 어제, 오늘 확진자 수를 알려주는 프로그램\"\"\"\n\n\"\"\"#0 기타 사용 함수들\"\"\"\ndef check_item(my_list, word):\n result = False\n for token in my_list:\n if word in token:\n result = True\n return result\n\ndef msg_handle(string):\n isit_covid = False\n day = 0 #(0: default, 1: 오늘, 2:어제, 3:그저께)\n my_list = list(string.lower().split(' '))\n print(string)\n #0 기본 언어 : 코로나, 확진자, 몇, 명\n if check_item(my_list, '코로나'):\n if check_item(my_list, '명') or check_item(my_list, '확진자') or check_item(my_list, '수'):\n isit_covid = True\n #1 오늘\n if check_item(my_list, '오늘'):\n day = 1\n #2 어제\n elif check_item(my_list, '어제'):\n day = 2\n #3 그저께\n elif check_item(my_list, '그저께'):\n day = 3\n else:\n print('무슨 말인지 알아들을 수 없습니다!')\n return [isit_covid, day]\n\n \n\n\"\"\"#1 Open API 정보를 받아오는 부분\"\"\"\nimport urllib.parse\nimport requests\nimport matplotlib.pyplot as plt\nfrom datetime import datetime, timedelta\n\n\nyesterday = datetime.now()-timedelta(days=1)\npast = datetime.now()-timedelta(days=4)\n\nservicekey = \"YOUR_KEY\"\ndecoded_key = urllib.parse.unquote(servicekey)\nprint(decoded_key)\n\nservice_url = \"http://openapi.data.go.kr/openapi/service/rest/Covid19/getCovid19InfStateJson\"\n#딕셔너리 저장할 때 사이트에 있는 파라미터 '그대로' 적을 것\nparams = {\n \"ServiceKey\" : decoded_key,\n \"pageNo\" : \"1\",\n \"numOfRows\" : \"10\",\n \"startCreateDt\" : \"{}{}{}\".format(str(past.year), str(past.month).zfill(2), str(past.day)),# 날짜를 잘 조절할 것! --오늘이 3일이하면 :(\n \"endCreateDt\" : \"{}{}{}\".format(str(yesterday.year), str(yesterday.month).zfill(2), str(yesterday.day)) #날짜를 if문으로 조절하기\n}\nresp = requests.get(service_url, params = params)\n# print(resp.content)\n\nimport xml.etree.ElementTree as ET\n\nresp = requests.get(service_url, params = params)\nroot = ET.fromstring(resp.content)\n\nfor element in root:\n print(element.tag, element.attrib)\n if element.tag == 'header':\n header = list(element)\n elif element.tag == 'body':\n body = list(element)\n\nitems = body[0]\ndecideCnt = []\n\nfor item in items:\n for item_tag in item:\n print(item_tag.tag)\n if item_tag.tag == 'decideCnt':\n decideCnt.append(int(item_tag.text))\ndecideCnt.reverse()\ndaily_patient = []\nfor i in range(1,len(decideCnt)):\n daily_patient.append(decideCnt[i]-decideCnt[i-1])\n# print(decideCnt)\n# print(daily_patient)\n\n\n\n\"\"\"#2 터치센서를 통해 작동을 시작하고, 실제 작동하는 코드\"\"\"\nimport RPi.GPIO as g\nfrom time import sleep\nfrom ears_universal import listen\nfrom mouth_kr import talk\n\ng.setmode(g.BCM)\nsensor = 26\n\ng.setup(26, g.IN)\nprint('Press ctrl+C to quit')\n\ntry:\n while True:\n value = g.input(26)\n if value == True:\n print('sensor detected')\n what_said = listen()[1]\n if msg_handle(what_said)[0]:\n if msg_handle(what_said)[1] == 0:\n talk('죄송해요, 오늘, 어제, 그저께에 대한 정보만 지원하고 있습니다. 더 자세한 정보는 보건복지부 홈페이지를 참조하여 주세요.')\n elif msg_handle(what_said)[1] == 1:\n talk('오늘 코로나19 확진자 수는 {}명입니다아.'.format(daily_patient[-1]))\n elif msg_handle(what_said)[1] == 2:\n talk('어제 코로나19 확진자 수는 {}명입니다아.'.format(daily_patient[-2]))\n elif msg_handle(what_said)[1] == 3:\n talk('그저께 코로나19 확진자 수는 {}명입니다아.'.format(daily_patient[-3]))\n else:\n talk('죄송해요, 코로나 확진자 수 알림 기능만을 지원하고 있습니다. 다른 답변은 드릴 수가 없네요오.')\n else:\n #print('no detection')\n pass\nexcept KeyboardInterrupt:\n g.cleanup()\n print('Goodbye.')\n\n\n","sub_path":"COVID_patient.py","file_name":"COVID_patient.py","file_ext":"py","file_size_in_byte":4113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"650939121","text":"# 这是一个开头\r\n# 人员:Mr Su\r\n# 开发时间:18/11/2020下午8:43\r\n# 文件名:VAE_funtions.py\r\n# 开发工具:PyCharm\r\n\r\n\r\nfrom collections import OrderedDict\r\nfrom tqdm import tqdm\r\nimport numpy as np\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.utils.data as data\r\nimport torch.optim as optim\r\n\r\nfrom mydocument.hw3_helper import *\r\n\r\ndef train(model, train_loader, optimizer, epoch, quiet, grad_clip=None):\r\n model.train()\r\n\r\n if not quiet:\r\n pbar = tqdm(total=len(train_loader.dataset))\r\n losses = OrderedDict()\r\n for x in train_loader:\r\n x = x.cuda()\r\n out = model.loss(x)\r\n optimizer.zero_grad()\r\n out['loss'].backward()\r\n if grad_clip:\r\n torch.nn.utils.clip_grad_norm_(model.parameters(), grad_clip)\r\n optimizer.step()\r\n\r\n desc = f'Epoch {epoch}'\r\n for k, v in out.items():\r\n if k not in losses:\r\n losses[k] = []\r\n losses[k].append(v.item())\r\n avg_loss = np.mean(losses[k][-50:])\r\n desc += f', {k} {avg_loss:.4f}'\r\n\r\n if not quiet:\r\n pbar.set_description(desc)\r\n pbar.update(x.shape[0])\r\n if not quiet:\r\n pbar.close()\r\n return losses\r\n\r\n\r\ndef eval_loss(model, data_loader, quiet):\r\n model.eval()\r\n total_losses = OrderedDict()\r\n with torch.no_grad():\r\n for x in data_loader:\r\n x = x.cuda()\r\n out = model.loss(x)\r\n for k, v in out.items():\r\n total_losses[k] = total_losses.get(k, 0) + v.item() * x.shape[0]\r\n\r\n desc = 'Test '\r\n for k in total_losses.keys():\r\n total_losses[k] /= len(data_loader.dataset)\r\n desc += f', {k} {total_losses[k]:.4f}'\r\n if not quiet:\r\n print(desc)\r\n return total_losses\r\n\r\n\r\ndef train_epochs(model, train_loader, test_loader, train_args, quiet=False):\r\n epochs, lr = train_args['epochs'], train_args['lr']\r\n grad_clip = train_args.get('grad_clip', None)\r\n optimizer = optim.Adam(model.parameters(), lr=lr)\r\n\r\n train_losses, test_losses = OrderedDict(), OrderedDict()\r\n for epoch in range(epochs):\r\n model.train()\r\n train_loss = train(model, train_loader, optimizer, epoch, quiet, grad_clip)\r\n test_loss = eval_loss(model, test_loader, quiet)\r\n\r\n for k in train_loss.keys():\r\n if k not in train_losses:\r\n train_losses[k] = []\r\n test_losses[k] = []\r\n train_losses[k].extend(train_loss[k])\r\n test_losses[k].append(test_loss[k])\r\n return train_losses, test_losses\r\n\r\n\r\nclass MLP(nn.Module):\r\n def __init__(self, input_shape, output_shape, hiddens=[]):\r\n super().__init__()\r\n\r\n if isinstance(input_shape, int):\r\n input_shape = (input_shape,)\r\n if isinstance(output_shape, int):\r\n output_shape = (output_shape,)\r\n\r\n self.input_shape = input_shape\r\n self.output_shape = output_shape\r\n self.hiddens = hiddens\r\n\r\n model = []\r\n prev_h = np.prod(input_shape)\r\n for h in hiddens + [np.prod(output_shape)]:\r\n model.append(nn.Linear(prev_h, h))\r\n model.append(nn.ReLU())\r\n prev_h = h\r\n model.pop()\r\n self.net = nn.Sequential(*model)\r\n\r\n def forward(self, x):\r\n b = x.shape[0]\r\n x = x.view(b, -1)\r\n return self.net(x).view(b, *self.output_shape)\r\n\r\n\r\nclass FullyConnectedVAE(nn.Module):\r\n def __init__(self, input_dim, latent_dim, enc_hidden_sizes=[],\r\n dec_hidden_sizes=[]):\r\n super().__init__()\r\n self.latent_dim = latent_dim\r\n self.encoder = MLP(input_dim, 2 * latent_dim, enc_hidden_sizes)\r\n self.decoder = MLP(latent_dim, 2 * input_dim, dec_hidden_sizes)\r\n\r\n def loss(self, x):\r\n mu_z, log_std_z = self.encoder(x).chunk(2, dim=1)\r\n z = torch.randn_like(mu_z) * log_std_z.exp() + mu_z\r\n mu_x, log_std_x = self.decoder(z).chunk(2, dim=1)\r\n\r\n # Compute reconstruction loss - Note that it may be easier for you\r\n # to use torch.distributions.normal to compute the log_prob\r\n recon_loss = 0.5 * np.log(2 * np.pi) + log_std_x + \\\r\n (x - mu_x) ** 2 * torch.exp(-2 * log_std_x) * 0.5\r\n recon_loss = recon_loss.sum(1).mean()\r\n\r\n # Compute KL\r\n kl_loss = -log_std_z - 0.5 + (torch.exp(2 * log_std_z) + mu_z ** 2) * 0.5\r\n kl_loss = kl_loss.sum(1).mean()\r\n\r\n return OrderedDict(loss=recon_loss + kl_loss, recon_loss=recon_loss,\r\n kl_loss=kl_loss)\r\n\r\n def sample(self, n, noise=True):\r\n with torch.no_grad():\r\n z = torch.randn(n, self.latent_dim).cuda()\r\n mu, log_std = self.decoder(z).chunk(2, dim=1)\r\n if noise:\r\n z = torch.randn_like(mu) * log_std.exp() + mu\r\n else:\r\n z = mu\r\n return z.cpu().numpy()\r\n\r\ndef q1(train_data, test_data, part, dset_id):\r\n \"\"\"\r\n train_data: An (n_train, 2) numpy array of floats,(10000,2)\r\n test_data: An (n_test, 2) numpy array of floats, (2500,2)\r\n\r\n (You probably won't need to use the two inputs below, but they are there\r\n if you want to use them)\r\n part: An identifying string ('a' or 'b') of which part is being run. Most likely\r\n used to set different hyperparameters for different datasets\r\n dset_id: An identifying number of which dataset is given (1 or 2). Most likely\r\n used to set different hyperparameters for different datasets\r\n\r\n Returns\r\n - a (# of training iterations, 3) numpy array of full negative ELBO, reconstruction loss E[-p(x|z)],\r\n and KL term E[KL(q(z|x) | p(z))] evaluated every minibatch\r\n - a (# of epochs + 1, 3) numpy array of full negative ELBO, reconstruciton loss E[-p(x|z)],\r\n and KL term E[KL(q(z|x) | p(z))] evaluated once at initialization and after each epoch\r\n - a numpy array of size (1000, 2) of 1000 samples WITH decoder noise, i.e. sample z ~ p(z), x ~ p(x|z)\r\n - a numpy array of size (1000, 2) of 1000 samples WITHOUT decoder noise, i.e. sample z ~ p(z), x = mu(z)\r\n \"\"\"\r\n\r\n \"\"\" YOUR CODE HERE \"\"\"\r\n\r\n model = FullyConnectedVAE(2, 2, [128, 128], [128, 128]).cuda()\r\n train_loader = data.DataLoader(train_data, batch_size=128, shuffle=True)\r\n test_loader = data.DataLoader(test_data, batch_size=128)\r\n train_losses, test_losses = train_epochs(model, train_loader, test_loader,\r\n dict(epochs=10, lr=1e-3), quiet=True)\r\n train_losses = np.stack((train_losses['loss'], train_losses['recon_loss'], train_losses['kl_loss']), axis=1)\r\n test_losses = np.stack((test_losses['loss'], test_losses['recon_loss'], test_losses['kl_loss']), axis=1)\r\n\r\n samples_noise = model.sample(1000, noise=True)\r\n samples_nonoise = model.sample(1000, noise=False)\r\n\r\n return train_losses, test_losses, samples_noise, samples_nonoise","sub_path":"VAE_funtions.py","file_name":"VAE_funtions.py","file_ext":"py","file_size_in_byte":7012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"115836122","text":"# NL_ES - Non-interruptable load solved with exhaustive search\n# Input:\n# dt - the time step [scalar]\n# pr - the array of prices [array]\n# L - the duration of the task [array]\n# P_NL - the power rate[array]\n# NL_b - the beginning time [array]\n# NL_e - the ending time [array]\n# Output:\n# total_cost - the total cost of all appliances throughout day\n# result_NL - the power distribution of all appliances\n# total_NL - the total power consumption from all appliances\n\nimport numpy as np\nfrom real_time_price import price\n\n\ndef NL_ES(dt, pr, L, P_NL, NL_b, NL_e):\n # N_NL - the number of appliances\n N_NL = len(L)\n # N - the number of time steps\n N = len(pr)\n total_cost = np.repeat(1000000.0, N_NL)\n # start - store the starting point of each appliance\n start = np.zeros(N_NL)\n result_NL = [None] * N_NL\n for m in range(N_NL):\n for i in range(NL_b[m], NL_e[m] - L[m] + 2):\n # cost - temporary value to record the cost of each possibility\n cost = 0\n for j in range(i, i + L[m]):\n cost += pr[j]\n if cost < total_cost[m]:\n total_cost[m] = cost \n start[m] = i\n total_cost[m] *= P_NL[m] * dt\n result_NL[m] = np.zeros(N)\n for i in range(int(start[m]), int(start[m] + L[m])):\n result_NL[m][i] = P_NL[m]\n total_NL = np.sum(result_NL, axis=0)\n \n return np.sum(total_cost), result_NL, total_NL\n","sub_path":"Work/Code/Others/NL_ES.py","file_name":"NL_ES.py","file_ext":"py","file_size_in_byte":1500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"67192818","text":"import urllib\nfrom urllib.request import Request\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport re\nimport os\nfrom tqdm import tqdm \npd.options.mode.chained_assignment = None\n\n# Columns for the Servant Stats\nkeys = ['Class ', 'Japanese Name', 'AKA', 'ID', 'Cost','ATK','HP','Grail ATK','Grail HP','Voice Actor','Illustrator','Attribute', 'Growth Curve','Star Absorption', \n'Star Generation','NP Charge ATK','NP Charge DEF','Death Rate', 'Alignments','Gender', 'Traits', 'Card Order', 'Quick Hits ', 'Arts Hits ', 'Buster Hits ', 'Extra Hits ', \n'Rank ', 'Classification ', 'Type ', 'Hit-Count ',]\n\n'''\nFunctions such as servant_stats(),servant_card_trait(),servant_np_stats() have similar functionality :\n\nExtract data from given tags and tables next to those tags. \nThere are some tags that have a different id for the tag. \n\n'''\n\n# Get the data for the main stats of all the servants \ndef servant_stats(soup,servant_data):\n \n servant_class = soup.find('p',{'class':'ServantInfoClass'})\n s_class = servant_class.find('a')['title']\n servant_data.append(s_class)\n\n servant_stats = soup.find('div',{'class':\"ServantInfoStatsWrapper\"})\n stat_table = servant_stats.find_all('table',{'class':'closetable'})[0]\n\n stat_table_row = stat_table.find_all('tr')\n\n for row in stat_table_row:\n stats = row.find_all('td')\n\n for i in stats:\n stat_text = i.text.strip()\n servant_data.append(re.sub(r'^(.*?):',' ',stat_text))\n\n# Get the data for the Card order, traits and the number of hits for each card\ndef servant_card_trait(soup,servant_data):\n\n servant_stats_2 = soup.find('div',{'class':\"ServantInfoStatsWrapper\"})\n\n stat_table2 = servant_stats_2.find_all('table',{'class':'closetable'})[1]\n stat_table_row2 = stat_table2.find_all('tr')\n\n # Table Data\n stats2 = stat_table_row2[0].find('td')\n stat_text2 = stats2.text.strip()\n servant_data.append(re.sub(r'^(.*?):',' ',stat_text2))\n\n # Card Order\n card_ori = stat_table_row2[1].find('img')['alt']\n servant_data.append(card_ori)\n\n card_hits_row = stat_table_row2[2].find('th')\n\n for i in range(0,4):\n\n card_hits = card_hits_row.find_all('div',{'class':'InumWrapper hidden'})[i]\n\n # Card name \n card_name_loc = card_hits.find('div',{'class':'InumIcon hidden'})\n card_name = card_name_loc.find('a')['title']\n \n # Number of hits\n card_hitcount_loc = card_hits.find('div',{'class':'InumNum hidden'})\n card_hitcount = card_hitcount_loc.text\n \n servant_data.append('{hitcount}'.format(name=card_name,hitcount = card_hitcount))\n\n# Get the data for the Noble Phantasm \ndef servant_np_stats(soup,servant_data):\n\n servant_np = soup.find('span',{'id':'Noble_Phantasm'})\n\n if servant_np is None :\n servant_np = soup.find('span',{'id':'.E2.80.8B.E2.80.8BNoble_Phantasm'}) # Tawara Touta\n \n servant_np_table = servant_np.find_next('table')\n \n np_values_rows = servant_np_table.find_all('tr')[1]\n\n for i in range(0,4):\n\n values = np_values_rows.find_all('td')[i].text\n servant_data.append(values.strip())\n\nclass StatsDB:\n \n def create_StatsDB_file(self,state,servant_df):\n # Read data from the Servant Database .csv file\n # d_link = os.path.join(os.getcwd(),'Servant Database.csv')\n\n if state == True:\n print('Stat Database is already updated')\n # elif os.path.exists(d_link) == False:\n # print('Servant Database file does not exist. Reload the program again')\n else :\n\n print('Creating Servant Stats Database')\n # servant_db = pd.read_csv(d_link)\n servant_db = servant_df.copy()\n\n # Gather the names of all the Servants and replace spaces with _ \n servant_db['Servant Name'] = servant_db['Servant Name'].apply(lambda x : x.replace(' ','_'))\n name_list = servant_db['Servant Name']\n\n total_servant_data = []\n\n for name in tqdm(name_list):\n servant_data = []\n\n # Parse name and create url\n servant_name= urllib.parse.quote(name)\n url = 'https://fategrandorder.fandom.com/wiki/' + servant_name\n\n # Send link and gather the data\n reg = Request(url,headers={'User-Agent': 'Mozilla/5.0'})\n htm = urllib.request.urlopen(reg).read()\n soup = BeautifulSoup(htm,'lxml')\n\n # Called functions\n servant_stats(soup,servant_data)\n servant_card_trait(soup,servant_data)\n servant_np_stats(soup,servant_data)\n\n # Append the given servant data to another list (reshaping is another option but eh....this also works too)\n total_servant_data.append(servant_data)\n\n # Create the servant stats dataframe and strip whitespace fromt \n df = pd.DataFrame(total_servant_data,columns=keys)\n df = df.apply(lambda x : x.str.strip())\n return df\n #df.to_csv(os.path.join(os.getcwd(),'Servant Stats.csv'),encoding='utf-8')\n\n\n\n\n\n\n\n\n","sub_path":"stats_database.py","file_name":"stats_database.py","file_ext":"py","file_size_in_byte":5097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"379435704","text":"import json\n\n# GetJson sınıfı\nclass GetJson:\n \"\"\"\n basit ihtiyaçlara göre geliştirilebilir json sınıfı\n \"\"\"\n @staticmethod\n def load(data=None):\n if data is not None:\n return json.load(data)\n else:\n print(\"Url is empty!\")\n\n @staticmethod\n def loads(data=None):\n if data is not None:\n try:\n return json.loads(data)\n except json.decoder.JSONDecodeError:\n print(\"Error! Execution failed connection\")\n else:\n print(\"Error! url is empty!\")\n","sub_path":"classes/GetJson.py","file_name":"GetJson.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"633755128","text":"import numpy as np\nfrom shinywaffle.common.context import Context\nfrom shinywaffle.backtesting import orders as orders_module\nfrom shinywaffle.data.intrabar_simulation import simulate_intrabar_data\n\n\nclass BacktestBroker:\n\n \"\"\"\n Base class for broker objects.\n Will contain logic for getting order prices\n\n\n\n \"\"\"\n\n def __init__(self, context: Context, fee: float):\n \"\"\"\n Modelling slippage as a normal distribution with mean 0 and standard deviation of 0.05. Generating 100000\n values.\n\n :param context: Context object containing all the cogs\n :param fee: Fee percentage\n \"\"\"\n self.context = context\n self.name = 'Basic broker'\n self.fee = fee\n self.total_commission = 0\n self.order_book = orders_module.OrderBook(context)\n self.slippages = abs(np.random.normal(0, 0.05, 100000)).tolist()\n context.broker = self\n\n def place_order(self, new_order):\n\n \"\"\"\n :param new_order: The order object received by the broker. Submitted further on to the order_book object\n and recieves a PendingOrderEvent.\n :return: PendingOrderEvent\n \"\"\"\n\n pending_order_event = self.order_book.new_order(new_order)\n return pending_order_event\n\n def check_for_order_fill(self, order_id):\n\n \"\"\"\n Method that checks whether or not an order with a given ID will be filled in the current bar.\n\n The order object is gotten from the order_book by its ID. If it is a market order, then it is automatically\n filled and the price is calculated from the self.get_market_order_price method. If the order is a limit order,\n then the order limit price is checked versus the current bar to see if it would be possible to fill.\n\n If is will be filled, then the intra bar prices are simulated using the simulate_intrabar_data method. If the\n order is a buy order, the order will be filled at the price that is first equal to or below the order limit\n price. If it is a sell order, then it will be filled at the price that is first equal to or above the\n order limit price.\n\n :param order_id: ID of the order to check\n :return: OrderFilledEvent\n \"\"\"\n\n order = self.order_book.get_by_id(order_id)\n event = None\n if isinstance(order, orders_module.MarketOrder):\n price = self.get_market_order_price(order)\n event = self.fill_order(order, price)\n\n elif isinstance(order, orders_module.LimitOrder):\n event = None\n if self.is_order_within_bar(order):\n bar = self.context.retrieved_data[order.asset.ticker]['bars'][0]\n previous_bar = self.context.retrieved_data[order.asset.ticker]['bars'][1]\n total_t = (bar.time - previous_bar.time).days\n intra_bar_prices = simulate_intrabar_data(bar, total_t, 0.01)\n\n # Finding fill price for BuyOrder\n if isinstance(order, orders_module.BuyOrder):\n for price in intra_bar_prices:\n if price <= order.order_limit_price:\n # event = self.fill_order(order, order.order_limit_price)\n event = self.fill_order(order, price)\n break\n\n # Finding fill price for SellOrder\n elif isinstance(order, orders_module.SellOrder):\n for price in intra_bar_prices:\n if price >= order.order_limit_price:\n # event = self.fill_order(order, order.order_limit_price)\n event = self.fill_order(order, price)\n break\n\n return event\n\n def is_order_within_bar(self, order) -> bool:\n\n \"\"\"\n Method that checks whether or not the limit order price is within the latest retrieved bar for a given asset.\n Returns True if it is and False if not.\n\n :param order: Order object containing the order limit price\n :return: True/False\n \"\"\"\n\n bar = self.context.retrieved_data[order.asset.ticker]['bars'][0]\n if bar.low <= order.order_limit_price <= bar.high:\n return True\n else:\n return False\n\n def fill_order(self, order, price):\n\n \"\"\"\n Method that fills an order at a given price.\n The order size is calculate: order.volume * price\n Commission is calculated from the calculate_commission() method from the order size\n\n The order_book.fill_order is called with the order.ID, size and commission and returns a OrderFilledEvent\n :param order: Order to fill\n :param price: Fill price of the order\n :return: OrderFilledEvent\n \"\"\"\n\n order_size = order.volume * price\n commission = self.calculate_commission(order_size)\n order_filled_event = self.order_book.fill_order(order.id, price, order_size, commission)\n return order_filled_event\n\n def get_market_order_price(self, order) -> float:\n\n \"\"\"\n Method to get the fill price for a market order. Assuming the market order is filled at the open of the\n current bar. This would be valid since it is filled in the bar after it was submitted\n\n Slippage is taken from the self.slippages list. If the order is a sell order, the slippage is subtracted, and\n if it is a buy order it is added to the price to produce the final fill price.\n\n :param order:\n :return:\n \"\"\"\n\n price_data = self.context.retrieved_data[order.asset.ticker]\n slippage = self.slippages.pop()\n if isinstance(order, orders_module.BuyOrder):\n pass\n if isinstance(order, orders_module.SellOrder):\n slippage *= -1\n\n # Open or close price? Should be open price if it is filled during the next bar\n return price_data['bars'][0].open + slippage\n\n def calculate_commission(self, order_size: float) -> float:\n \"\"\"\n This is a simple commission calculation taking the order size and multiply it by the fee percentage\n :param order_size:\n :return:\n \"\"\"\n commission = order_size * self.fee\n self.total_commission += commission\n return commission\n\n def report(self):\n data = {\n 'name': self.name,\n 'fee': self.fee,\n 'total commission': self.total_commission\n }\n\n return data\n\n","sub_path":"shinywaffle/backtesting/broker.py","file_name":"broker.py","file_ext":"py","file_size_in_byte":6531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"195480691","text":"\ndef getAbsMaxIndex(data_a, data_b):\n max_index = 0\n max_value = -1\n for i in range(len(data_a)):\n cur = abs(data_b[i] - data_a[i])\n if cur >= max_value:\n max_index = i\n\n return max_index\n","sub_path":"SmartStock/MathTools.py","file_name":"MathTools.py","file_ext":"py","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"294069399","text":"import util\nimport os\nimport db\n\nclass ProductConfig:\n\n def __init__(self, conn):\n self.__products = {}\n \n for row in db.load_file(conn, 'products.csv'):\n row['sku'] = row['sku'].strip().upper()\n if not row['sku']: continue\n row['is_fragile'] = row['is_fragile'].strip().lower() == 'yes'\n self.__products[row['sku']] = row\n\n\n def get_attributes(self, sku):\n return self.__products.get(sku, {\n 'sku' : sku,\n 'unit' : '',\n 'grade_text' : '',\n 'grade_font_color' : '',\n 'grade_font' : '',\n 'is_fragile' : False,\n }\n )\n\n\nif __name__ == '__main__':\n ProductConfig()\n","sub_path":"products.py","file_name":"products.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"138306118","text":"with open(\"/Users/myleslangston/Documents/Sparta Global /input.txt\", \"r\") as fp:\n num = fp.readlines(int())\n num = [int(i) for i in num]\n\nfor x in num:\n if 2020 - x in num:\n print(x*(2020-x))\n\nfor x in num:\n for y in num:\n if 2020 - (x+y) in num:\n print(x*(2020-(x+y))*y)\n\n\n\n\n\n\n\n","sub_path":"AdventDay1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"165438965","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# author:fei time:2019/7/2 21:04\n\n# io流\nimport io # 导入io模块\n\nsio = io.StringIO() # 创建一个对象(进行保存读取)--->字符流\n\nsio.write(\"hello\") # 写\nprint(sio.getvalue()) # 读\n\nsio.close() # close后内容就没有了\n\n\nbio = io.BytesIO()\n\nbio.write(b'abcd')\nprint(bio.getvalue())\n\nbio.close()\n","sub_path":"49class/7.02/7.02/lesson14/four_io.py","file_name":"four_io.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"72168962","text":"#!/usr/bin/env python\nfrom durationcorrection import DurationCorrection\nimport h5py\nimport numpy\n\nTAU = 100\nCONCENTRATION = 1\n\ndef rateanalysis(lastiter, directh5path, istate, fstate, timepoints_per_iteration, tau=TAU, conc=CONCENTRATION):\n dc = DurationCorrection.from_files([directh5path], istate, fstate, lastiter=lastiter)\n correction = dc.correction(lastiter, timepoints_per_iteration)\n\n with h5py.File(directh5path, 'r') as directh5:\n raw_rate = directh5['rate_evolution'][lastiter-1][istate][fstate]['expected']\n raw_rate = raw_rate/(tau*conc)\n rate = raw_rate*correction\n return raw_rate, rate\n\ndef main():\n # path to the w_direct output files\n directh5path = './direct.h5'\n # number of timepoints per iteration; since the last timepoint of one \n # iteration overlaps with the first timepoint of the next, we typically\n # have an odd number here (like 11 or 21 or 51).\n timepoints_per_iteration = 3\n \n # number of iterations in the simulation\n n_iterations = None\n if n_iterations is None:\n with h5py.File(directh5path, 'r') as directh5:\n n_iterations = directh5['rate_evolution'].shape[0]\n\n # buffer to hold the corrected rate values; \n raw_rates = numpy.zeros(n_iterations)\n rates = numpy.zeros(n_iterations)\n # loop through all iterations\n for i in range(n_iterations):\n print(\"iter %d\"%(i + 1))\n # calculate corrected rate using data up to iteration iiter\n # and store the result in the buffer\n raw_rates[i], rates[i] = rateanalysis(i + 1, directh5path, 1, 0, timepoints_per_iteration)\n\n # calculate the mean and sem for both raw and corrected rates\n# raw_rates_mean = numpy.mean(raw_rates, axis=1)\n# raw_rates_sem = numpy.std(raw_rates, axis=1)/numpy.sqrt(n_simulations)\n# rates_mean = numpy.mean(rates, axis=1)\n# rates_sem = numpy.std(rates, axis=1)/numpy.sqrt(n_simulations)\n\n # save result with numpy\n numpy.save('raw_rates.npy', raw_rates)\n numpy.save('rates.npy', rates)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"RED_scheme/rate.py","file_name":"rate.py","file_ext":"py","file_size_in_byte":2068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"141701215","text":"from datetime import timedelta\nfrom setproctitle import setproctitle\nfrom time import time\n\n\nclass PytorchProcessName:\n def __init__(self, total_epochs, name=\"ML\"):\n self.name = name\n self.epochs = total_epochs\n self.times = []\n self.epoch = 0\n\n setproctitle(self.name)\n\n def start(self):\n self.times.append(time())\n\n def update_epoch(self, epoch):\n self.times.append(time())\n\n if len(self.times) == 1:\n remaining = \"estimating...\"\n else:\n avg_epoch_duration = np.ediff1d(np.array(self.times)[-10:]).mean()\n epochs_left = self.epochs - epoch\n time_left_in_secs = np.ceil(avg_epoch_duration * epochs_left)\n remaining = timedelta(seconds=time_left_in_secs)\n\n proc_name = self.name + ' remaining: %s' % remaining\n\n setproctitle(proc_name)","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"235281869","text":"\"\"\"\nConfig for the Flask app when running unit tests.\n\"\"\"\nimport os\n\n# Build the URI for the database.\nbasedir = os.path.abspath(os.path.dirname(__file__))\nSQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'database_testing.db')\n\n# Disable database modification notifications.\nSQLALCHEMY_TRACK_MODIFICATIONS = False\n","sub_path":"test/config_testing.py","file_name":"config_testing.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"570982272","text":"# Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\nfrom __future__ import absolute_import\n\nfrom sagemaker.amazon.amazon_estimator import AmazonAlgorithmEstimatorBase, registry\nfrom sagemaker.amazon.common import numpy_to_record_serializer, record_deserializer\nfrom sagemaker.amazon.hyperparameter import Hyperparameter as hp # noqa\nfrom sagemaker.amazon.validation import gt, isin, ge\nfrom sagemaker.predictor import RealTimePredictor\nfrom sagemaker.model import Model\nfrom sagemaker.session import Session\nfrom sagemaker.vpc_utils import VPC_CONFIG_DEFAULT\n\n\nclass FactorizationMachines(AmazonAlgorithmEstimatorBase):\n\n repo_name = 'factorization-machines'\n repo_version = 1\n\n num_factors = hp('num_factors', gt(0), 'An integer greater than zero', int)\n predictor_type = hp('predictor_type', isin('binary_classifier', 'regressor'),\n 'Value \"binary_classifier\" or \"regressor\"', str)\n epochs = hp('epochs', gt(0), \"An integer greater than 0\", int)\n clip_gradient = hp('clip_gradient', (), \"A float value\", float)\n eps = hp('eps', (), \"A float value\", float)\n rescale_grad = hp('rescale_grad', (), \"A float value\", float)\n bias_lr = hp('bias_lr', ge(0), \"A non-negative float\", float)\n linear_lr = hp('linear_lr', ge(0), \"A non-negative float\", float)\n factors_lr = hp('factors_lr', ge(0), \"A non-negative float\", float)\n bias_wd = hp('bias_wd', ge(0), \"A non-negative float\", float)\n linear_wd = hp('linear_wd', ge(0), \"A non-negative float\", float)\n factors_wd = hp('factors_wd', ge(0), \"A non-negative float\", float)\n bias_init_method = hp('bias_init_method', isin('normal', 'uniform', 'constant'),\n 'Value \"normal\", \"uniform\" or \"constant\"', str)\n bias_init_scale = hp('bias_init_scale', ge(0), \"A non-negative float\", float)\n bias_init_sigma = hp('bias_init_sigma', ge(0), \"A non-negative float\", float)\n bias_init_value = hp('bias_init_value', (), \"A float value\", float)\n linear_init_method = hp('linear_init_method', isin('normal', 'uniform', 'constant'),\n 'Value \"normal\", \"uniform\" or \"constant\"', str)\n linear_init_scale = hp('linear_init_scale', ge(0), \"A non-negative float\", float)\n linear_init_sigma = hp('linear_init_sigma', ge(0), \"A non-negative float\", float)\n linear_init_value = hp('linear_init_value', (), \"A float value\", float)\n factors_init_method = hp('factors_init_method', isin('normal', 'uniform', 'constant'),\n 'Value \"normal\", \"uniform\" or \"constant\"', str)\n factors_init_scale = hp('factors_init_scale', ge(0), \"A non-negative float\", float)\n factors_init_sigma = hp('factors_init_sigma', ge(0), \"A non-negative float\", float)\n factors_init_value = hp('factors_init_value', (), \"A float value\", float)\n\n def __init__(self, role, train_instance_count, train_instance_type,\n num_factors, predictor_type,\n epochs=None, clip_gradient=None, eps=None, rescale_grad=None,\n bias_lr=None, linear_lr=None, factors_lr=None,\n bias_wd=None, linear_wd=None, factors_wd=None,\n bias_init_method=None, bias_init_scale=None, bias_init_sigma=None, bias_init_value=None,\n linear_init_method=None, linear_init_scale=None, linear_init_sigma=None, linear_init_value=None,\n factors_init_method=None, factors_init_scale=None, factors_init_sigma=None, factors_init_value=None,\n **kwargs):\n \"\"\"Factorization Machines is :class:`Estimator` for general-purpose supervised learning.\n\n Amazon SageMaker Factorization Machines is a general-purpose supervised learning algorithm that you can use\n for both classification and regression tasks. It is an extension of a linear model that is designed\n to parsimoniously capture interactions between features within high dimensional sparse datasets.\n\n This Estimator may be fit via calls to\n :meth:`~sagemaker.amazon.amazon_estimator.AmazonAlgorithmEstimatorBase.fit`. It requires Amazon\n :class:`~sagemaker.amazon.record_pb2.Record` protobuf serialized data to be stored in S3.\n There is an utility :meth:`~sagemaker.amazon.amazon_estimator.AmazonAlgorithmEstimatorBase.record_set` that\n can be used to upload data to S3 and creates :class:`~sagemaker.amazon.amazon_estimator.RecordSet` to be passed\n to the `fit` call.\n\n To learn more about the Amazon protobuf Record class and how to prepare bulk data in this format, please\n consult AWS technical documentation: https://docs.aws.amazon.com/sagemaker/latest/dg/cdf-training.html\n\n After this Estimator is fit, model data is stored in S3. The model may be deployed to an Amazon SageMaker\n Endpoint by invoking :meth:`~sagemaker.amazon.estimator.EstimatorBase.deploy`. As well as deploying an Endpoint,\n deploy returns a :class:`~sagemaker.amazon.pca.FactorizationMachinesPredictor` object that can be used\n for inference calls using the trained model hosted in the SageMaker Endpoint.\n\n FactorizationMachines Estimators can be configured by setting hyperparameters. The available hyperparameters for\n FactorizationMachines are documented below.\n\n For further information on the AWS FactorizationMachines algorithm,\n please consult AWS technical documentation: https://docs.aws.amazon.com/sagemaker/latest/dg/fact-machines.html\n\n Args:\n role (str): An AWS IAM role (either name or full ARN). The Amazon SageMaker training jobs and\n APIs that create Amazon SageMaker endpoints use this role to access\n training data and model artifacts. After the endpoint is created,\n the inference code might use the IAM role, if accessing AWS resource.\n train_instance_count (int): Number of Amazon EC2 instances to use for training.\n train_instance_type (str): Type of EC2 instance to use for training, for example, 'ml.c4.xlarge'.\n num_factors (int): Dimensionality of factorization.\n predictor_type (str): Type of predictor 'binary_classifier' or 'regressor'.\n epochs (int): Number of training epochs to run.\n clip_gradient (float): Optimizer parameter. Clip the gradient by projecting onto\n the box [-clip_gradient, +clip_gradient]\n eps (float): Optimizer parameter. Small value to avoid division by 0.\n rescale_grad (float): Optimizer parameter. If set, multiplies the gradient with rescale_grad\n before updating. Often choose to be 1.0/batch_size.\n bias_lr (float): Non-negative learning rate for the bias term.\n linear_lr (float): Non-negative learning rate for linear terms.\n factors_lr (float): Noon-negative learning rate for factorization terms.\n bias_wd (float): Non-negative weight decay for the bias term.\n linear_wd (float): Non-negative weight decay for linear terms.\n factors_wd (float): Non-negative weight decay for factorization terms.\n bias_init_method (string): Initialization method for the bias term: 'normal', 'uniform' or 'constant'.\n bias_init_scale (float): Non-negative range for initialization of the bias term that takes\n effect when bias_init_method parameter is 'uniform'\n bias_init_sigma (float): Non-negative standard deviation for initialization of the bias term that takes\n effect when bias_init_method parameter is 'normal'.\n bias_init_value (float): Initial value of the bias term that takes effect\n when bias_init_method parameter is 'constant'.\n linear_init_method (string): Initialization method for linear term: 'normal', 'uniform' or 'constant'.\n linear_init_scale (float): Non-negative range for initialization of linear terms that takes\n effect when linear_init_method parameter is 'uniform'.\n linear_init_sigma (float): Non-negative standard deviation for initialization of linear terms that takes\n effect when linear_init_method parameter is 'normal'.\n linear_init_value (float): Initial value of linear terms that takes effect\n when linear_init_method parameter is 'constant'.\n factors_init_method (string): Initialization method for factorization term: 'normal',\n 'uniform' or 'constant'.\n factors_init_scale (float): Non-negative range for initialization of factorization terms that takes\n effect when factors_init_method parameter is 'uniform'.\n factors_init_sigma (float): Non-negative standard deviation for initialization of factorization terms that\n takes effect when factors_init_method parameter is 'normal'.\n factors_init_value (float): Initial value of factorization terms that takes\n effect when factors_init_method parameter is 'constant'.\n **kwargs: base class keyword argument values.\n \"\"\"\n super(FactorizationMachines, self).__init__(role, train_instance_count, train_instance_type, **kwargs)\n\n self.num_factors = num_factors\n self.predictor_type = predictor_type\n self.epochs = epochs\n self.clip_gradient = clip_gradient\n self.eps = eps\n self.rescale_grad = rescale_grad\n self.bias_lr = bias_lr\n self.linear_lr = linear_lr\n self.factors_lr = factors_lr\n self.bias_wd = bias_wd\n self.linear_wd = linear_wd\n self.factors_wd = factors_wd\n self.bias_init_method = bias_init_method\n self.bias_init_scale = bias_init_scale\n self.bias_init_sigma = bias_init_sigma\n self.bias_init_value = bias_init_value\n self.linear_init_method = linear_init_method\n self.linear_init_scale = linear_init_scale\n self.linear_init_sigma = linear_init_sigma\n self.linear_init_value = linear_init_value\n self.factors_init_method = factors_init_method\n self.factors_init_scale = factors_init_scale\n self.factors_init_sigma = factors_init_sigma\n self.factors_init_value = factors_init_value\n\n def create_model(self, vpc_config_override=VPC_CONFIG_DEFAULT):\n \"\"\"Return a :class:`~sagemaker.amazon.FactorizationMachinesModel` referencing the latest\n s3 model data produced by this Estimator.\n\n Args:\n vpc_config_override (dict[str, list[str]]): Optional override for VpcConfig set on the model.\n Default: use subnets and security groups from this Estimator.\n * 'Subnets' (list[str]): List of subnet ids.\n * 'SecurityGroupIds' (list[str]): List of security group ids.\n\n \"\"\"\n return FactorizationMachinesModel(self.model_data, self.role, sagemaker_session=self.sagemaker_session,\n vpc_config=self.get_vpc_config(vpc_config_override))\n\n\nclass FactorizationMachinesPredictor(RealTimePredictor):\n \"\"\"Performs binary-classification or regression prediction from input vectors.\n\n The implementation of :meth:`~sagemaker.predictor.RealTimePredictor.predict` in this\n `RealTimePredictor` requires a numpy ``ndarray`` as input. The array should contain the\n same number of columns as the feature-dimension of the data used to fit the model this\n Predictor performs inference on.\n\n :meth:`predict()` returns a list of :class:`~sagemaker.amazon.record_pb2.Record` objects, one\n for each row in the input ``ndarray``. The prediction is stored in the ``\"score\"``\n key of the ``Record.label`` field.\n Please refer to the formats details described: https://docs.aws.amazon.com/sagemaker/latest/dg/fm-in-formats.html\n \"\"\"\n\n def __init__(self, endpoint, sagemaker_session=None):\n super(FactorizationMachinesPredictor, self).__init__(endpoint,\n sagemaker_session,\n serializer=numpy_to_record_serializer(),\n deserializer=record_deserializer())\n\n\nclass FactorizationMachinesModel(Model):\n \"\"\"Reference S3 model data created by FactorizationMachines estimator. Calling :meth:`~sagemaker.model.Model.deploy`\n creates an Endpoint and returns :class:`FactorizationMachinesPredictor`.\"\"\"\n\n def __init__(self, model_data, role, sagemaker_session=None, **kwargs):\n sagemaker_session = sagemaker_session or Session()\n repo = '{}:{}'.format(FactorizationMachines.repo_name, FactorizationMachines.repo_version)\n image = '{}/{}'.format(registry(sagemaker_session.boto_session.region_name), repo)\n super(FactorizationMachinesModel, self).__init__(model_data,\n image,\n role,\n predictor_cls=FactorizationMachinesPredictor,\n sagemaker_session=sagemaker_session,\n **kwargs)\n","sub_path":"source/sagemaker-python-sdk/src/sagemaker/amazon/factorization_machines.py","file_name":"factorization_machines.py","file_ext":"py","file_size_in_byte":13816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"548427799","text":"''' \ncreate conditional output for digital output device (LED, Relay, etc)\n'''\n# import required Library\n# input_output_seperator use to seperate input and output devce in items dictionary\nfrom backend.input_output_seperator import input_output_seperator\n\ndef conditional_digital_output_codegenerator(input_dataframe, items_dict):\n\n # Get List of Digitat Output devices\n INPUTs, Digital_OUTPUTs, Analog_OUTPUTs= input_output_seperator(items_dict)\n \n # clearing unused variable\n del INPUTs, Analog_OUTPUTs\n \n # creating index for item_id -> used output digital pin\n pin_index = {}\n \n # iterate through every single digital output device one by one \n for Digital_OUTPUT in Digital_OUTPUTs:\n\n # defined unique item id\n # item id -> {item_name}_{number}\n item_id = f'{Digital_OUTPUT.split(\"_\")[0]}_{Digital_OUTPUT.split(\"_\")[1]}'\n\n # added data to pin_index\n pin_index[item_id] = items_dict[item_id]['Digital_pins'][0]\n\n # create starting empty string condition code\n condition_code = \"\"\"\n\"\"\"\n\n # iterate through row of condition_dataframe\n for index, row in input_dataframe.iterrows():\n\n # create condition comment to identified starting of conditon\n condition_code += f\"\"\"\n//Start of Condition : {index}\n \"\"\"\n\n condition_code += f\"\"\"\nif ({row[\"INPUT\"]} {row[\"CONDITION\"]} {row[\"VALUE\"]})\n\"\"\"\n condition_code += \"\"\"{\"\"\"\n\n condition_code += f\"\"\"\ndigitalWrite({pin_index[row[\"OUTPUT\"]]}, HIGH);\n \"\"\"\n condition_code += \"\"\"\n}else{\n\"\"\"\n\n condition_code += f\"\"\"\ndigitalWrite({pin_index[row[\"OUTPUT\"]]}, LOW);\n \"\"\"\n\n condition_code += \"\"\"\n}\n\"\"\"\n\n condition_code += f\"\"\"\n//End of Condition : {index}\n\"\"\"\n print(condition_code)\n return condition_code\n\n","sub_path":"program/backend/condition_generator.py","file_name":"condition_generator.py","file_ext":"py","file_size_in_byte":1855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"114800853","text":"'''12.WAP to search for a number from a list with linear search'''\n\nl=eval(input(\"Enter the list\"))\ns=int(input(\"Enter number to search\"))\n\nfor i in l:\n if i==s:\n print(\"Found!!\")\n break\nelse:\n print(\"Not found\")","sub_path":"linearsearch.py","file_name":"linearsearch.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"651652230","text":"\"\"\"\nCreate a function that takes a string and an integer (n).\n\nThe function should return a string that repeats the input string n number of times.\n\nIf anything other than a string is passed in you should return \"Not a string\"\n\"\"\"\n\ndef repeat_it(myStr, n):\n if (type(myStr) != str):\n return \"Not a string\"\n return str(myStr) * n\n \n\n\n\nif __name__ == \"__main__\":\n print(\"No string: \" + str(repeat_it(\"\", 2)))\n print(\"Empty list: \" +str(repeat_it([], 1)))\n print(\"Repeat name: \" + str(repeat_it(\"Odwa\", 3)))\n\n","sub_path":"python/8kyu/repeat_it.py","file_name":"repeat_it.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"379104113","text":"# calcul y = Wx, W is fully connect layer, W = G_1*G_2*...G_d\n\nfrom __future__ import print_function\nfrom mpi4py import MPI\nfrom inspect import currentframe, getframeinfo\n\n\n\nimport keras\nimport os\nimport h5py\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.io\nimport itertools\nimport time\nfrom numba import jit\nimport cupy as cp\n#import user define c++ function\nimport multiply_element\nimport eigen_slice\nimport matrix_dot\n\n\n@jit\ndef tt_construct_layer7(filename, feature_x):\n\n mat_dict = {}\n mat_dict.update(scipy.io.loadmat(filename))\n\n a = mat_dict['TT_mat']\n\n dim_arr = a['d'][0][0][0,0]\n #n_arr = a['n'][0][0][0:,0]\n #ps_arr = a['ps'][0][0][0:,0]\n #core_arr = a['core'][0][0][0:,0]\n ranks = a['r'][0][0][0:,0]\n bias = a['bias'][0][0]\n \n right_modes = a['right_modes'][0][0][0,0:]\n right_modes = np.array(right_modes, dtype=np.int32)\n\n left_modes = a['left_modes'][0][0][0,0:]\n left_modes = np.array(left_modes, dtype=np.int32)\n\n\n L_cpp = multiply_element.multiply(left_modes)\n L = np.prod(left_modes)\n\n R_cpp = multiply_element.multiply(right_modes)\n R = np.prod(right_modes)\n\n print('L_cpp-L',L_cpp-L)\n print('R_cpp-R',R_cpp-R)\n\n core_tensor_0 = a['tensor'][0][0][0,0]\n core_tensor_1 = a['tensor'][0][0][0,1]\n core_tensor_2 = a['tensor'][0][0][0,2]\n core_tensor_3 = a['tensor'][0][0][0,3]\n\n\n\n column_len = L\n row_len = R\n\n if dim_arr > 2:\n shape = left_modes*right_modes.ravel()\n else:\n shape = [left_modes[0],right_modes[0]]\n \n tensor_column_len = shape[0]\n tensor_row_len = shape[1]\n tensor_depth_len = shape[2]\n tensor_channel_len = shape[3]\n\n\n\n y_out = np.zeros((L,1), dtype=float, order='F')\n y_out_bk = np.zeros((L,1), dtype=float, order='F')\n\n print(tensor_row_len)\n #t0 = time.time()\n for i in range(0,tensor_row_len):\n \n core_mat_0 = core_tensor_0[:,i,:]\n core_mat_0_bk = matrix_dot.layer7_tensor_to_matrix_slice_0(core_tensor_0,i)\n \n for j in range(0,tensor_column_len):\n \n core_mat_1 = core_tensor_1[:,j,:]\n core_mat_1_bk = matrix_dot.layer7_tensor_to_matrix_slice_1(core_tensor_1,j)\n \n tmp1 = np.dot(core_mat_0, core_mat_1)\n tmp1_bk = matrix_dot.dot_matrix(core_mat_0_bk, core_mat_1_bk)\n \n\n for k in range(0,tensor_depth_len):\n \n core_mat_2 = core_tensor_2[:,k,:]\n core_mat_2_bk = matrix_dot.layer7_tensor_to_matrix_slice_2(core_tensor_2,k)\n \n \n tmp2 = np.dot(tmp1, core_mat_2)\n tmp2_bk = matrix_dot.dot_matrix(tmp1_bk, core_mat_2_bk)\n \n\n ind1 = np.zeros(tensor_channel_len) + i\n ind2 = np.zeros(tensor_channel_len) + j\n ind3 = np.zeros(tensor_channel_len) + k\n ind4 = np.arange(tensor_channel_len)\n \n ind1_bk = matrix_dot.layer7_create_index(tensor_channel_len,1)\n ind2_bk = matrix_dot.layer7_create_index(tensor_channel_len,2)\n ind3_bk = matrix_dot.layer7_create_index(tensor_channel_len,3) \n ind4_bk = matrix_dot.layer7_one_d_arrange(tensor_channel_len) \n \n \n indy = np.ravel_multi_index([ind1.astype('int64'),ind2.astype('int64'),\n ind3.astype('int64'),ind4.astype('int64')],\n (tensor_row_len, tensor_column_len, tensor_depth_len, tensor_channel_len), \n order='F'\n )\n\n indy_bk = matrix_dot.layer7_four_d_ravel_multi_index(ind1_bk.astype('int64'),ind2_bk.astype('int64'),\n ind3_bk.astype('int64'),\n ind4_bk.astype('int64'),tensor_row_len, \n tensor_column_len, tensor_depth_len, \n tensor_channel_len\n )\n \n \n row_index = np.mod(indy, column_len)\n row_index_bk = matrix_dot.layer7_mod(indy_bk, column_len)\n \n \n column_index = np.floor( indy / column_len).astype('int64')\n column_index_bk = matrix_dot.layer7_floor_array(indy_bk / column_len).astype('int64')\n \n \n #tmp3 = np.dot(tmp2,core_tensor_3.reshape([ranks[3], tensor_channel_len],order = 'F'))\n tmp3 = np.dot(tmp2,core_tensor_3)\n tmp3_bk = matrix_dot.dot_matrix(tmp2_bk, core_tensor_3)\n \n \n tmp4 = np.multiply(tmp3,feature_x[[column_index]].reshape([1,tensor_channel_len],order = 'F'))\n \n x_bk = matrix_dot.layer7_Get_feature_x_by_index(feature_x, column_index)\n tmp4_bk = matrix_dot.layer7_multiply_matrix_multiply_element_wise(tmp3_bk, x_bk)\n \n \n \n for l in range(0,tensor_channel_len):\n y_out[row_index[l]] = y_out[row_index[l]] + tmp4[0,l]\n y_out_bk[row_index[l]] = y_out_bk[row_index[l]] + tmp4_bk[0,l]\n \n \n print('final',np.linalg.norm(y_out-y_out_bk,1))\n \n\t\n\n\n \ndef\tRelu_Function(x):\n out = np.maximum(x, 0)\n return out\n\ndef softmax(x):\n \"\"\"Compute softmax values for each sets of scores in x.\"\"\"\n e_x = np.exp(x - np.max(x))\n return e_x / e_x.sum(axis=0) # only difference\n\ndef haarMatrix(n, normalized=1):\n # Allow only size n of power 2\n n = 2**np.ceil(np.log2(n))\n if n > 2:\n h = haarMatrix(n / 2)\n else:\n return np.array([[1, 1], [1, -1]])\n\n # calculate upper haar part\n h_n = np.kron(h, [1, 1])\n # calculate lower haar part \n if normalized:\n h_i = np.sqrt(n/2)*np.kron(np.eye(len(h)), [1, -1])\n else:\n h_i = np.kron(np.eye(len(h)), [1, -1])\n # combine parts\n h = np.vstack((h_n, h_i))\n return h\n\n'''\n ####reconstruct weight matrix\n\t\n a=core_arr[ps_arr[0]-1:ps_arr[1]-1]\n\n for i in range(1,dim_arr):\n cr=core_arr[ps_arr[i]-1:ps_arr[i+1]-1]\n print('i:',i)\n\n cr=np.reshape(cr,[ranks[i],n_arr[i]*ranks[i+1]], order=\"F\")\n print('cr.shape',cr.shape)\n a=np.reshape(a,[-1,ranks[i]], order=\"F\")\n #print('a.shape,a[0:3,0:3]',a.shape,a[0:3,0:3])\n a=np.dot(a,cr)\n #print('a.shape,a[0:3,0:3]',a.shape,a[0:3,0:3])\n\n weight_mat = np.reshape(a, [L, R], order=\"F\");\n ####reconstruct weight matrix\n'''\nif __name__ == '__main__':\n filename = '/home/wade/Document2/TT-haar-devolope/weights/mnist_y_out_layer7.mat'\n feature_x = np.random.randn(4096,1) ;\n tt_construct_layer7(filename, feature_x)\t\t\n ","sub_path":"build_core_by_index_layer7_final.py","file_name":"build_core_by_index_layer7_final.py","file_ext":"py","file_size_in_byte":7236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"529688286","text":"import logging\nimport mimetypes\nfrom normality import stringify\nfrom datetime import date, datetime\nfrom ingestors.util import normalize_mime_type, normalize_extension\n\nlog = logging.getLogger(__name__)\n\n\nclass Ingestor(object):\n \"\"\"Generic ingestor class.\"\"\"\n MIME_TYPES = []\n EXTENSIONS = []\n SCORE = 3\n\n def __init__(self, manager, result):\n self.manager = manager\n self.result = result\n\n def ingest(self, file_path):\n \"\"\"The ingestor implementation. Should be overwritten.\n\n This method does not return anything.\n Use the ``result`` attribute to store any resulted data.\n \"\"\"\n raise NotImplemented()\n\n def update(self, name, value):\n \"\"\"Set a metadata value if it is not already set with a value.\"\"\"\n existing = getattr(self.result, name)\n if existing:\n return\n if not isinstance(value, (date, datetime)):\n value = stringify(value)\n if value is None:\n return\n setattr(self.result, name, value)\n\n @classmethod\n def match(cls, file_path, result=None):\n mime_type = result.mime_type\n if mime_type is None:\n (mime_type, enc) = mimetypes.guess_type(file_path)\n\n if mime_type is not None:\n for match_type in cls.MIME_TYPES:\n match_type = normalize_mime_type(match_type)\n if normalize_mime_type is None:\n continue\n if match_type.lower().strip() == mime_type.lower().strip():\n return cls.SCORE\n\n extensions = [normalize_extension(e) for e in cls.EXTENSIONS]\n extensions = [e for e in extensions if e is not None]\n if normalize_extension(file_path) in extensions:\n return cls.SCORE\n\n return -1\n","sub_path":"ingestors/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"315570650","text":"import csv\nimport sqlite3\nfrom contextlib import closing\nfrom math import *\n\ndb_name = '../SQLite/Station_DB.sqlite3'\n\n#csv(路線図データ)読み込み書き込み\ncsv_file = open(\"../Cytoscape Out/AllJapanRail_Edge_pl_local.csv\", \"r\", encoding = \"utf-8\", errors = \"\", newline = \"\")\nfp1 = csv.reader(csv_file, delimiter = \",\", doublequote = True, lineterminator = \"\\r\\n\", quotechar = '\"', skipinitialspace = True)\nfp2 = open('JR-edge.csv', 'w')\nwriter = csv.writer(fp2, lineterminator = '\\n')\n\n#csvの駅id取り出し\nfor row in fp1:\n left_id = row[18]\n right_id = row[18]\n station_id1 = int(left_id[0:7])\n station_id2 = int(right_id.split(')')[1])\n\n #駅の緯度経度取り出し\n with closing(sqlite3.connect(db_name)) as con:\n cur = con.cursor()\n\n #緯度\n search_lat = 'select lat from stations_db where station_cd = ? or station_g_cd = ?'\n where = (station_id1, station_id1)\n cur.execute(search_lat, where)\n station_lat1 = cur.fetchone()\n #経度\n search_lon = 'select lon from stations_db where station_cd = ? or station_g_cd = ?'\n where = (station_id1, station_id1)\n cur.execute(search_lon, where)\n station_lon1 = cur.fetchone()\n\n #緯度\n search_lat = 'select lat from stations_db where station_cd = ? or station_g_cd = ?'\n where = (station_id2, station_id2)\n cur.execute(search_lat, where)\n station_lat2 = cur.fetchone()\n #経度\n search_lon = 'select lon from stations_db where station_cd = ? or station_g_cd = ?'\n where = (station_id2, station_id2)\n cur.execute(search_lon, where)\n station_lon2 = cur.fetchone()\n\n cur.close()\n con.close()\n\n #距離計算\n if station_lat1 is not None and station_lat2 is not None:\n ra = 6378.140 #赤道の範囲(km)\n rb = 6356.755 #南北極の範囲(km)\n flat = (ra - rb) / ra #地球の地表を平らにする計算\n rad_station_lat1 = radians(station_lat1[0])\n rad_station_lon1 = radians(station_lon1[0])\n rad_station_lat2 = radians(station_lat2[0])\n rad_station_lon2 = radians(station_lon2[0])\n if rad_station_lat1 != rad_station_lat2 and rad_station_lon1 != rad_station_lon2:\n pa = atan(rb / ra * tan(rad_station_lat1))\n pb = atan(rb / ra * tan(rad_station_lat2))\n xx = acos(sin(pa) * sin(pb) + cos(pa) * cos(pb) * cos(rad_station_lon1 - rad_station_lon2))\n c1 = (sin(xx) - xx) * (sin(pa) + sin(pb)) ** 2 / cos(xx / 2) ** 2\n c2 = (sin(xx) + xx) * (sin(pa) - sin(pb)) ** 2 / sin(xx / 2) ** 2\n dr = flat / 8 * (c1 - c2)\n rho = ra * (xx + dr)\n direct_distance = rho\n move_minute = (direct_distance * 1000) / 3600\n\n #csv書き込み\n writer.writerow([station_id1,station_id2,move_minute])\n else:\n #csv書き込み\n writer.writerow([station_id1,station_id2,0])\n else:\n #csv書き込み\n writer.writerow([station_id1,station_id2,0])\n\n#fp1.close()\n#fp2.close()\n","sub_path":"Code_py/JR-list.py","file_name":"JR-list.py","file_ext":"py","file_size_in_byte":3122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"58530923","text":"from jira import JIRA\nimport mysql.connector\nimport datetime\n\nm_Features = []\nm_Issues = []\njira = JIRA(server='http://node9:8900', basic_auth=('shi.zhao', '123456'))\nblock_size = 100\nblock_num = 0\nwhile True:\n start_idx = block_num*block_size\n # issues = jira.search_issues('project = \"LinkoopDB\" AND summary ~ \"use cppjieba CutForSearch, old is Cut\"', start_idx, block_size)\n issues = jira.search_issues('project = \"LinkoopDB\"', start_idx, block_size)\n if len(issues) == 0:\n # Retrieve issues until there are no more to come\n break\n block_num += 1\n for issue in issues:\n if len(issue.fields.versions) == 0:\n m_Issue_Affacted = \"UNKNOWN\"\n else:\n m_Issue_Affacted = str(issue.fields.versions[0])\n if len(issue.fields.components) == 0:\n m_Issue_Module = \"UNKNOWN\"\n else:\n m_Issue_Module = str(issue.fields.components[0])\n m_Issues.append({\n \"Issue_ID\": str(issue.id),\n \"Issue_Title\": str(issue.fields.summary),\n \"Issue_Status\": str(issue.fields.status),\n \"Issue_Type\": str(issue.fields.issuetype),\n \"Issue_Priority\": str(issue.fields.priority),\n \"Issue_Module\": m_Issue_Module,\n \"Issue_Reporter\": str(issue.fields.reporter),\n \"Issue_Assigned\": str(issue.fields.assignee),\n \"Issue_Affected\": m_Issue_Affacted,\n \"Issue_Created\": datetime.datetime.strptime(issue.fields.created[:23], '%Y-%m-%dT%H:%M:%S.%f'),\n \"Issue_Updated\": datetime.datetime.strptime(issue.fields.updated[:23], '%Y-%m-%dT%H:%M:%S.%f')\n })\n if str(issue.fields.issuetype).strip() == \"新功能\":\n m_FeatureID = str(issue.fields.summary).split()[0]\n m_FeatureSummary = str(issue.fields.summary)[len(m_FeatureID):].lstrip()\n if m_FeatureID.find('-') != -1:\n m_UpLevel_FeatureID = m_FeatureID[:m_FeatureID.rfind('-')]\n else:\n m_UpLevel_FeatureID = \"0\"\n m_FeatureDesc = issue.fields.description\n if len(issue.fields.fixVersions) == 0:\n m_Fixed_Version = \"UNKNOWN\"\n else:\n m_Fixed_Version = str(issue.fields.fixVersions[0]).strip()\n if m_Fixed_Version in (\"UNKNOWN\", \"1.0\", \"1.1\", \"1.2\", \"2.0\", \"2.1\"):\n m_Fixed_Version = \"2.1\"\n if m_Fixed_Version in (\"2.2\", \"2.2.2\"):\n m_Fixed_Version = \"2.2\"\n if m_Fixed_Version in (\"2.3\"):\n m_Fixed_Version = \"2.3\"\n if m_Fixed_Version in (\"3.0\"):\n m_Fixed_Version = \"3.0\"\n\n m_Features.append({\n 'Feature_ID': m_FeatureID.strip(),\n 'Feature_Summary': m_FeatureSummary,\n 'UpLevel_Feature_ID': m_UpLevel_FeatureID.strip(),\n 'Feature_Desc': m_FeatureDesc,\n \"Owner_ID\": 'Jira',\n \"Support_Status\": 'Supported',\n \"Component_ID\": '0000',\n \"First_Version\": m_Fixed_Version,\n \"Created_Date\": datetime.datetime.now()\n })\n\n# 连接mysql数据库\nmydb = mysql.connector.connect(\n host=\"node10\",\n user=\"report\",\n passwd=\"123456\",\n database=\"report\",\n autocommit=False\n)\nmycursor = mydb.cursor()\nmycursor.execute(\"Delete From Features\")\nmycursor.close()\nm_nCount = 0\nfor feature in m_Features:\n columns = \",\".join(feature.keys())\n values = ', '.join(['%s'] * len(feature))\n sql = \"INSERT INTO Features({keys}) VALUES ({values})\" \\\n .format(keys=columns, values=values)\n mycursor = mydb.cursor()\n mycursor.execute(sql, tuple(feature.values()))\n m_nCount = m_nCount + 1\n mycursor.close()\nprint(\"Total {\" + str(m_nCount) + \"} rows inserted to Features.\")\n\nmycursor = mydb.cursor()\nmycursor.execute(\"Delete From Issues\")\nmycursor.close()\n\nm_nCount = 0\nfor issue in m_Issues:\n columns = \",\".join(issue.keys())\n values = ', '.join(['%s'] * len(issue))\n sql = \"INSERT INTO Issues({keys}) VALUES ({values})\" \\\n .format(keys=columns, values=values)\n mycursor = mydb.cursor()\n mycursor.execute(sql, tuple(issue.values()))\n m_nCount = m_nCount + 1\n mycursor.close()\nprint(\"Total {\" + str(m_nCount) + \"} rows inserted to Issues.\")\n\n# 提交事务\nmydb.commit()\n\n# 关闭数据库连接\nmydb.close()\n","sub_path":"linkoopdb/regression/common/LoadFeatureFromJira.py","file_name":"LoadFeatureFromJira.py","file_ext":"py","file_size_in_byte":4383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"437242424","text":"\"\"\"\nThe prime factors of 13195 are 5, 7, 13 and 29.\n\nWhat is the largest prime factor of the number 600851475143 ?\n\"\"\"\n\nfrom math import *\n\nnumber = 600851475143\nn = ceil(sqrt(600851475143))\n\nsieve = list(range(2, n+1))\nmarked = [False] * (n)\n\np = 2\n\nfinished = False\n\nwhile not finished: \n\tfor i in range(2*p, n+1, p):\n\t\tmarked[i] = True\n\n\ttry:\n\t\tp = marked.index(False, p+1)\n\t\tif number % p == 0:\n\t\t\tprint(\"%d divides %d!\" % (p, number))\n\n\texcept ValueError:\n\t\tfinished = True\n","sub_path":"p3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"135260754","text":"\n\nfrom xai.brain.wordbase.nouns._tumbleweed import _TUMBLEWEED\n\n#calss header\nclass _TUMBLEWEEDS(_TUMBLEWEED, ):\n\tdef __init__(self,): \n\t\t_TUMBLEWEED.__init__(self)\n\t\tself.name = \"TUMBLEWEEDS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"tumbleweed\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_tumbleweeds.py","file_name":"_tumbleweeds.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"212750086","text":"import nose.tools as nt\nimport numpy as np\nimport theano\nimport theano.tensor as T\n\nimport treeano.nodes as tn\n\nfX = theano.config.floatX\n\n\ndef test_tile_node_serialization():\n tn.check_serialization(tn.TileNode(\"a\"))\n tn.check_serialization(tn.TileNode(\"a\", reps=[1, 2, 3]))\n\n\ndef test_to_one_hot_node_serialization():\n tn.check_serialization(tn.ToOneHotNode(\"a\"))\n\n\ndef test_tile_node():\n network = tn.SequentialNode(\n \"n\",\n [tn.InputNode(\"in\", shape=(3, 4, 5)),\n tn.TileNode(\"t\", reps=(2, 3, 4))]\n ).network()\n fn = network.function([\"in\"], [\"n\"])\n x = np.random.rand(3, 4, 5).astype(fX)\n res = fn(x)[0]\n correct_ans = np.tile(x, (2, 3, 4))\n np.testing.assert_allclose(res, correct_ans)\n assert correct_ans.shape == network[\"t\"].get_variable(\"default\").shape\n\n\ndef test_to_one_hot_node():\n network = tn.SequentialNode(\n \"n\",\n [tn.InputNode(\"in\", shape=(3,)),\n tn.ToOneHotNode(\"ohe\", nb_class=8, cast_int32=True)]\n ).network()\n fn = network.function([\"in\"], [\"n\"])\n x = np.random.randint(8, size=3).astype(fX)\n res = fn(x)[0]\n np.testing.assert_equal(np.argmax(res, axis=1),\n x)\n nt.assert_equal((3, 8),\n network[\"ohe\"].get_variable(\"default\").shape)\n","sub_path":"treeano/nodes/tests/theanode_test.py","file_name":"theanode_test.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"480049447","text":"\nimport utilities\nimport IMP\nimport IMP.domino as domino\nimport IMP.pepdock2 as pepdock2\nimport RMF\nimport math\nimport os\nimport sys\nimport logging\nimport paranoid_log\nlog = logging.getLogger(\"AssignmentsIO\")\n\nclass AssignmentReader:\n\n def get_container_type_to_use(self):\n \"\"\" Select the type of container to use for read/writting asignments from\n domino. So far the type used has been PackedAssignmentContainer, but \n this container makes DOMINO very unefficient for exploring a large\n number of conformations. It is recommended to switch to\n HeapAssignmentContainer in the future\n \"\"\"\n return domino.PackedAssignmentContainer()\n\n def loadAssignmentPartition(self, rac, partition, index):\n \"\"\" Load a file containing the assignments for a partition\n @param rac A domino.ReadAssignmentContainer class\n \"\"\"\n [startPartition, endPartition] = self.getPartitionBoundaries(\n partition, self.tools(\"total_partition_count\"), rac)\n log.debug(\"Partition boundaries for index %s: (%s,%s). Partition: %s. \" \\\n \"Assignments %s\" % (index, startPartition, endPartition, partition, rac.get_number_of_assignments()))\n pac = self.get_container_type_to_use()\n for i in range (startPartition, endPartition):\n pac.add_assignment(rac.get_assignment(i))\n return pac\n\n\n def getPartitionBoundaries(self, currentPartition, totalPartitions, assignmentContainer):\n\n totalAssignments = assignmentContainer.get_number_of_assignments()\n startPartition = None\n endPartition = None\n if (currentPartition == -1):\n startPartition = 0\n endPartition = totalAssignments\n else:\n partitionSize = int(math.ceil(float(totalAssignments) / float (totalPartitions)))\n startPartition = partitionSize * currentPartition\n endPartition = startPartition + partitionSize\n endPartition = min(endPartition, totalAssignments)\n return [startPartition, endPartition]\n\n def readCompleteRestraintCache(self, subset_manager, rc, particles):\n rcName = self.tools.cache_filename(subset_manager.getIndex())\n hdf5 = RMF.open_hdf5_file_read_only(rcName)\n log.debug(\"Loading complete restraint cache %s\\n\" % rcName)\n rc.load_cache(pepdock2.get_sorted_by_name(particles), hdf5)\n\n def readPartitionRestraintCache(self, subset_manager, rc, particles, partition):\n rcName = self.tools.partition_cache_filename(subset_manager.getIndex(), partition)\n log.debug(\"Loading partition restraint cache %s\\n\" % rcName)\n hdf5 = RMF.open_hdf5_file_read_only(rcName)\n rc.load_cache(pepdock2.get_sorted_by_name(particles), hdf5)\n\n\nclass LeafAssignmentReader(AssignmentReader):\n def __init__(self, subset_manager, partition, dt):\n self.manager = subset_manager\n self.partition = partition\n self.tools = dt\n\n def readAssignmentFile(self):\n fn = self.tools.leaf_assignment_filename(self.manager.getIndex())\n log.debug(\"Reading leaf file %s\",fn)\n rac = domino.ReadAssignmentContainer(fn, self.manager.getSubset(),\n self.manager.getSortedParticles(), \"reader\")\n return self.loadAssignmentPartition(rac, self.partition, ind)\n\n\nclass InnerNodeReader(AssignmentReader):\n def __init__(self, firstAds, secondAds, partition, dt):\n self.partition = partition\n self.firstAds = firstAds\n self.secondAds = secondAds\n self.tools = dt\n\n def readFirstAssignmentFile(self):\n inputFile = self.tools.assignment_filename(self.firstAds.getIndex())\n rac = domino.ReadAssignmentContainer(self.tools.getFullAssignmentFile(inputFile),\n self.firstAds.getSubset(), self.firstAds.getSortedParticles(), \"reader\")\n return self.loadAssignmentPartition(rac, self.partition, self.firstAds.getIndex())\n\n def readSecondAssignmentFile(self):\n inputFile = self.tools.assignment_filename(self.secondAds.getIndex())\n rac = domino.ReadAssignmentContainer(self.tools.getFullAssignmentFile(inputFile),\n self.secondAds.getSubset(), self.secondAds.getSortedParticles(), \"reader\")\n pac = self.get_container_type_to_use()\n pac.add_assignments(rac.get_assignments())\n return pac\n\n def loadFirstRestraintCache(self, rc, particles):\n self.readCompleteRestraintCache(self.firstAds, rc, particles)\n\n def loadSecondRestraintCache(self, rc, particles):\n self.readCompleteRestraintCache(self.secondAds, rc, particles)\n\nclass CompleteNodeWriter(AssignmentReader):\n def __init__(self, dt):\n self.tools = dt\n\n def writeAssignmentFile(self, subset_manager, ac):\n ind = subset_manager.getIndex()\n fn = self.tools.assignment_filename(ind)\n log.debug(\"Index %s: Writing assignment file %s\", ind, fn)\n w = domino.WriteAssignmentContainer(fn,\n subset_manager.getSubset(),\n subset_manager.getSortedParticles(), \"writer\")\n w.set_cache_size(1e6)\n w.add_assignments(ac.get_assignments())\n\n del w\n\n def writeRestraintCache(self, subset_manager, rc, particles, restraints):\n ind = subset_manager.getIndex()\n fn = self.tools.cache_filename(ind)\n hdf5_group = RMF.create_hdf5_file(fn)\n log.debug(\"Index %s: Writing restraint cache file %s\",ind, fn)\n rc.save_cache(particles, restraints, hdf5_group, 1e6) #1e6 is max cache size; check how it affects performance\n\nclass PartitionNodeWriter(AssignmentReader):\n def __init__(self, partition, dt):\n self.partition = partition\n self.tools = dt\n\n def writeAssignmentFile(self, subset_manager, ac):\n ind = subset_manager.getIndex()\n fn = self.tools.partition_assignment_filename(ind, self.partition)\n log.debug(\"Index %s: Writing assignment file %s\", ind, fn)\n w = domino.WriteAssignmentContainer(fn, subset_manager.getSubset(), subset_manager.getSortedParticles(), \"writer\")\n w.set_cache_size(1e6)\n w.add_assignments(ac.get_assignments())\n\n del w\n\n def writeRestraintCache(self, subset_manager, rc, particles, restraints):\n ind = subset_manager.getIndex()\n fn = self.tools.partition_cache_filename(ind, self.partition)\n log.debug(\"Index %s: Writing restraint cache file %s\", ind, fn)\n log.paranoid(\"Restraints:\")\n for r in restraints:\n log.paranoid(\"%s\",r)\n hdf5_group = RMF.create_hdf5_file(fn)\n rc.save_cache(particles, restraints, hdf5_group, 1e6) #1e6 is max cache size; check how it affects performance\n\n\nclass MergeNodeReader(AssignmentReader):\n def __init__(self, subset_manager, dt):\n self.manager = subset_manager\n self.tools = dt\n\n def mergeAssignments(self, rc):\n totalPartitionCount = self.tools(\"total_partition_count\")\n pac = self.get_container_type_to_use()\n log.debug(\"MergeNodeReader: Merging assginments\")\n for i in range(int(totalPartitionCount)):\n fn = self.partition_assignment_filename(self.manager.getIndex(), i)\n ac = domino.ReadAssignmentContainer(fn, self.manager.getSubset(), self.manager.getSortedParticles(), \"reader\")\n log.paranoid(\"Read %s assignments from %s\", ac.get_number_of_assignments(), fn)\n for assignment in ac.get_assignments():\n pac.add_assignment(assignment)\n log.debug(\"All assignments merged into %s assignments\",pac.get_number_of_assignments())\n return pac\n\n def mergeRestraints(self, rc, particles):\n totalPartitionCount = self.tools(\"total_partition_count\")\n for i in range(int(totalPartitionCount)):\n self.readPartitionRestraintCache(self.manager, rc, particles, i)\n\n","sub_path":"pyext/src/AssignmentsIO.py","file_name":"AssignmentsIO.py","file_ext":"py","file_size_in_byte":7903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"648910114","text":"\n# read and preprocess sounds in the DSRI environment\n\n# define directories, add r before the name because a normal string cannot be used as a path, alternatives are \n# using / or \\\\ instead of \\\ndir_anfiles = \"/workspace/notebooks/sounds_npy/train\" # directory for both channels\n#dir_anfiles = \"C:/Users/kiki.vanderheijden/Documents/PYTHON/DataFiles\" # sounds left channel\n\n# import packages and libraries\nimport numpy as np\n#from sklearn.utils import shuffle\nfrom sklearn.model_selection import train_test_split\nfrom pytictoc import TicToc \nt = TicToc() # create instant of class\nimport pickle\nimport math\n\n# set parameters\ntestset = 0.25 # size of testset\nnrazlocs = 36 # number of azimuth locations\nazimuthrange = np.arange(0,360,10)\n\nt.tic()\n# =============================================================================\n# THESE ARE THE REAL ONES\n# load numpy arrays from disk\nan_l = np.load(dir_anfiles+\"/an_l_sounds.npy\")\nan_r = np.load(dir_anfiles+\"/an_r_sounds.npy\")\nlabels = np.load(dir_anfiles+\"/labels_sounds.npy\")\nfilenames = pickle.load(open(dir_anfiles+'/listfilenames_sounds.p','rb'))\nt.toc(\"loading the numpy arrays took \")\n# =============================================================================\n\n# retrieve labels from names\nnames_val_angle = np.empty([len(filenames)])\ncnt1 = 0\nfor x in filenames:\n names_val_angle[cnt1] =int(x[1:4])\n cnt1 += 1\n\n#cycle through the labels to get the indices of the angles\nindices_val_angle = np.empty([nrazlocs,int(len(filenames)/nrazlocs)])\nfor x in range(nrazlocs):\n indices_val_angle[x,] = np.where(names_val_angle == azimuthrange[x])[0]\n\n# compute overall number of sounds per location\nnrsounds_loc = math.floor(len(labels[:,0])/nrazlocs)\n\n# intiate empty matrics (or zero matrices)\nan_l_train = np.zeros((nrazlocs*math.floor((1-testset)*nrsounds_loc),len(an_l[1,:,:]),len(an_l[1,1,:]))) # round down here because train_test_split rounds the train size down\nan_r_train = np.zeros((nrazlocs*math.floor((1-testset)*nrsounds_loc),len(an_r[1,:,:]),len(an_r[1,1,:])))\nlabels_train = np.zeros((nrazlocs*math.floor((1-testset)*nrsounds_loc),len(labels[1,:])))\nfilenames_train = list()\nan_l_test = np.zeros((nrazlocs*math.ceil(testset*nrsounds_loc),len(an_l[1,:,:]),len(an_l[1,1,:]))) # round up here because train_test_split rounds the test size up\nan_r_test = np.zeros((nrazlocs*math.ceil(testset*nrsounds_loc),len(an_r[1,:,:]),len(an_r[1,1,:])))\nlabels_test = np.zeros((nrazlocs*math.ceil(testset*nrsounds_loc),len(labels[1,:])))\nfilenames_test = list()\n\n# first take a part away for evaluation\nfor x in range(nrazlocs) :\n # now take all those sounds --> you don't need to shuffle them because os.scandir already read them in an arbitrary order\n temp_idx = indices_val_angle[x,]\n temp_idx = temp_idx.astype(int)\n an_l_temp = an_l[temp_idx,]\n an_r_temp = an_r[temp_idx,]\n labels_temp = labels[temp_idx,]\n filenames_temp = [filenames[i] for i in temp_idx] # indexing from a list is a bit cumbersome...\n # now you need to split the remaining ones into training and test\n an_l_temp_train, an_l_temp_test, an_r_temp_train, an_r_temp_test, labels_temp_train, labels_temp_test, filenames_temp_train, filenames_temp_test = train_test_split(an_l_temp, an_r_temp, labels_temp, filenames_temp, test_size = testset, shuffle = False) \n # add to the matrices in the correct positions\n an_l_train[x*len(an_l_temp_train):(x+1)*len(an_l_temp_train)] = an_l_temp_train\n an_l_test[x*len(an_l_temp_test):(x+1)*len(an_l_temp_test)] = an_l_temp_test\n an_r_train[x*len(an_r_temp_train):(x+1)*len(an_r_temp_train)] = an_r_temp_train\n an_r_test[x*len(an_r_temp_test):(x+1)*len(an_r_temp_test)] = an_r_temp_test\n labels_train[x*len(labels_temp_train):(x+1)*len(labels_temp_train)] = labels_temp_train\n labels_test[x*len(labels_temp_test):(x+1)*len(labels_temp_test)] = labels_temp_test\n filenames_train.extend(filenames_temp_train)\n filenames_test.extend(filenames_temp_test)\n\n# add a fourth dimension ('channel') to train_an_l and train_an_r which should be 1, this is needed for the input to the DNN\nan_l_train = np.expand_dims(an_l_train,axis = 3)\nan_l_test = np.expand_dims(an_l_test,axis = 3)\nan_r_train = np.expand_dims(an_r_train,axis = 3)\nan_r_test = np.expand_dims(an_r_test,axis = 3)\n\n#save numpy arrays for model evaluation after training\nnp.save(dir_anfiles+\"/an_l_train_sounds.npy\",an_l_train)\nnp.save(dir_anfiles+\"/an_r_train_sounds.npy\",an_r_train)\nnp.save(dir_anfiles+\"/an_l_test_sounds.npy\",an_l_test)\nnp.save(dir_anfiles+\"/an_r_test_sounds.npy\",an_r_test)\nnp.save(dir_anfiles+\"/labels_train_sounds.npy\",labels_train)\nnp.save(dir_anfiles+\"/labels_test_sounds.npy\",labels_test)\npickle.dump(filenames_train, open(dir_anfiles+'/listfilenames_train_sounds.p','wb'))\npickle.dump(filenames_test, open(dir_anfiles+'/listfilenames_test_sounds.p','wb'))\n\nprint(\"numpy arrays are saved to disk\")\nprint(\"Shape of training sounds is:\", an_l_train.shape)\nprint(\"Shape of training labels is:\", labels_train.shape)\nprint(\"Shape of test sounds is:\", an_l_test.shape)\nprint(\"Shape of test labels is:\", labels_test.shape)\n\n \n","sub_path":"PrepareData_and_DataSplit.py","file_name":"PrepareData_and_DataSplit.py","file_ext":"py","file_size_in_byte":5129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"158842251","text":"class square():\n def __init__(self, x, y, val):\n self.x = x\n self.y = y\n self.val = val\n self.visited = False\n\n def __str__(self):\n return '(' + str(self.x) + ', ' + str(self.y) + ') -> ' + str(self.val)\n\n\nclass field():\n def __init__(self, val, N, H):\n self.arr = []\n self.N = N\n self.H = H\n\n for j in range(N):\n for i in range(N):\n self.arr.append(square(i, j, val[i + j * N]))\n\n def pre_check(self, x, y):\n if (0 <= x < self.N) and (0 <= y < self.N):\n cell = self.arr[x + y * self.N]\n if not cell.visited:\n return cell\n else:\n return None\n\n def check_nearby_squares(self, cell):\n print('checking..... ' + str(cell), end=' \\n')\n cell.visited = True\n\n nearby_squares = [\n self.pre_check(cell.x + 1, cell.y), # right\n self.pre_check(cell.x, cell.y + 1), # bottom\n self.pre_check(cell.x - 1, cell.y), # left\n self.pre_check(cell.x, cell.y - 1), # top\n ]\n\n for sqr in nearby_squares:\n if sqr is not None:\n if abs(sqr.val - cell.val) <= self.H:\n return sqr\n\n def walk(self):\n\n stack = []\n\n curent_square = self.arr[0]\n\n while True:\n next_square = self.check_nearby_squares(curent_square)\n\n if curent_square.x == self.N - 1 and curent_square.y == self.N - 1:\n print('yes')\n break\n\n if next_square is None:\n curent_square = stack.pop()\n else:\n stack.append(curent_square)\n curent_square = next_square\n\n\nif __name__ == '__main__':\n\n field_vals = [\n\n 3, 6, 4, 9,\n 7, 1, 2, 3,\n 6, 7, 2, 2,\n 7, 7, 1, 5,\n ]\n\n f = field(field_vals, 4, 3)\n f.walk()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"645349753","text":"import numpy as np\nfrom numpy.testing import assert_array_almost_equal\nfrom pfb.operators import Theta, DaskTheta\nfrom pfb.opt import power_method\nimport pytest\n\npmp = pytest.mark.parametrize\n\n@pmp(\"nx\", [128, 250])\n@pmp(\"ny\", [64, 78])\n@pmp(\"nband\", [1, 3, 6])\ndef test_theta_norm(nx, ny, nband):\n theta = Theta(nband, nx, ny)\n\n x = np.random.randn(theta.nbasis+1, nband, theta.nmax)\n\n c = theta.dot(x)\n\n x = theta.hdot(c)\n\n op = lambda x: theta.hdot(theta.dot(x))\n\n L = power_method(op, x.shape, tol=1e-5, maxit=50)\n\n assert(np.allclose(L, 1))\n\n@pmp(\"nx\", [128, 250])\n@pmp(\"ny\", [64, 78])\n@pmp(\"nband\", [1, 3, 6])\ndef test_theta_adjoint(nx, ny, nband):\n theta = Theta(nband, nx, ny)\n\n\n x = np.random.randn(theta.nbasis+1, nband, theta.nmax)\n y = np.random.randn(2, nband, nx, ny)\n\n res1 = np.vdot(y, theta.dot(x))\n\n res2 = np.vdot(theta.hdot(y), x)\n\n assert(np.allclose(res1, res2))\n\n@pmp(\"nx\", [128, 250])\n@pmp(\"ny\", [64, 78])\n@pmp(\"nband\", [1, 3, 6])\ndef test_theta_dask(nx, ny, nband):\n theta = Theta(nband, nx, ny)\n\n x = np.random.randn(theta.nbasis+1, nband, theta.nmax)\n y = np.random.randn(2, nband, nx, ny)\n\n # from time import time\n\n # ti = time()\n res1 = theta.dot(x)\n res2 = theta.hdot(y)\n # print(time()-ti)\n\n theta_dask = DaskTheta(nband, nx, ny, 8)\n\n # ti = time()\n res1_dask = theta_dask.dot(x)\n res2_dask = theta_dask.hdot(y)\n # print(time()-ti)\n\n assert_array_almost_equal(res1, res1_dask, decimal=10)\n assert_array_almost_equal(res2, res2_dask, decimal=10)\n\n\n\n# if __name__==\"__main__\":\n# test_theta_dask(1500, 1500, 8)","sub_path":"pfb/test/test_theta.py","file_name":"test_theta.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"500917117","text":"#!/usr/bin/env python\nfrom __future__ import print_function\nimport roslib\nimport sys\nimport rospy\nimport cv2\nfrom image_crop import ImageCrop\nfrom image_proc import ImageProc\nfrom buoy_detect import CascadeBuoyDetect, BlobDetector\nfrom std_msgs.msg import String\nfrom sensor_msgs.msg import Image\nfrom geometry_msgs.msg import Point\nfrom cv_bridge import CvBridge, CvBridgeError\nfrom dynamic_reconfigure.server import Server\nfrom vision_temp.cfg import VisionBridgeConfig\nimport copy\n\n\n\"\"\"\nROS node for communication between ROS and OpenCV\n\nUses cv_bridge to convert between ros images and opencv images\n\"\"\"\nclass VisionBridge:\n def __init__(self):\n \tself.bridge = CvBridge()\n self.ic = ImageCrop()\n self.ip = ImageProc()\n self.cascadeBuoyDetect = CascadeBuoyDetect()\n self.blobDetector = BlobDetector()\n self.front_img = None\n self.bottom_img = None\n self.crop_img = None\n self.gotColors = False\n\n rospy.init_node('image_bridge', anonymous=True)\n self.srv = Server(VisionBridgeConfig, self.reconfigure)\n\n #dynamic reconfigure variables\n self.crop_image = False\n self.buoy_detection = 0\n self.crop_image_first = True\n self.publish_bottom = False\n\n #publishers\n self.front_pub = rospy.Publisher(\"front_view\",Image,queue_size=1)\n self.algorithm_pub = rospy.Publisher(\"buoy_detection\",Image,queue_size=1)\n self.binary_pub = rospy.Publisher(\"binary\",Image,queue_size=1)\n self.center_pub = rospy.Publisher(\"buoy_center_pub\",Point,queue_size=1)\n\n #subscribers\n #self.imaself.binary_pub = rospy.Publisher(\"binary\",Image,queue_size=1)\n #self.ge_sub = rospy.Subscriber(\"/front/camera/image_raw\",Image,self.callback)\n self.image_sub = rospy.Subscriber(\"/front/camera/image_raw\",Image,self.subFrontCallback,queue_size=1)\n self.image_sub = rospy.Subscriber(\"/bottom/camera/image_raw\",Image,self.subBottomCallback,queue_size=1)\n\n\n def reconfigure(self, config, level):\n rospy.loginfo(\"dynamic_reconfigure\")\n \n self.crop_image = config.crop_image\n self.buoy_detection = config.buoy_detection\n self.publish_bottom = config.bottom_camera\n\n self.blobDetector.setAttributes(p1=config.hough_param1,p2=config.hough_param2,\\\n distance=config.hough_distance, minR = config.hough_minR, maxR = config.hough_maxR)\n\n #self.blobDetector.setHoughCircleParams(config.hough_param1,config.hough_param2,config.hough_distance, config.hough_minR, config.hough_maxR)\n\n self.blobDetector.setAttributes(minArea = config.min_area, maxLength = config.max_length, \\\n circularity = config.circularity_min, aspect_ratio_diff = config.aspect_ratio_diff)\n \n #self.blobDetector.setContoursParams(config.min_area, config.max_length,config.circularity_min, config.aspect_ratio_diff)\n self.blobDetector.setAttributes(adSize = config.ad_size, adMethod = config.ad_guassian,\\\n erodeSize = config.erosion_size, erodeIterations = config.erosion_iterations,\\\n dilateSize = config.dilation_size, dilateIterations = config.dilation_iterations)\n #self.blobDetector.setThresholdParams(config.ad_size, config.ad_guassian,config.erosion_size,config.dilation_size,config.erosion_iterations,config.dilation_iterations)\n\n self.cascadeBuoyDetect.setAttributes(fileName=config.cascade_classifier,\\\n scaleFactor = config.cc_scaleFactor, minNeighbours = config.cc_minNeighbours)\n #self.cascadeBuoyDetect.setParams(config.cascade_classifier,config.cc_scaleFactor, config.cc_minNeighbours)\n\n\n return config\n \n\n def subFrontCallback(self,data):\n try:\n cv_image = self.bridge.imgmsg_to_cv2(data, \"bgr8\")\n self.front_img = cv_image\n except CvBridgeError as e:\n print(e)\n\n def subBottomCallback(self,data):\n try:\n cv_image = self.bridge.imgmsg_to_cv2(data, \"bgr8\")\n self.bottom_img = cv_image\n except CvBridgeError as e:\n print(e)\n \n def initCrop(self):\n self.ic.getCircle(self.front_img)\n self.crop_image_first = False\n \n def cropImage(self):\n if self.crop_image:\n if(self.crop_image_first):\n print(\"initializing image crop\")\n self.initCrop()\n self.crop_img = self.ic.cropImage(self.front_img)\n else:\n self.crop_image_first = True\n self.crop_img = None\n\n def getFrontImage(self):\n if(self.crop_img != None):\n return self.crop_img\n else:\n return self.front_img\n\n def publishFrontView(self):\n img = self.getFrontImage()\n self.front_pub.publish(self.bridge.cv2_to_imgmsg(img, encoding='passthrough'))\n \n def publishBottomView(self):\n bottom = self.getBottomImage()\n self.bottom_pub.publish(self.bridge.cv2_to_imgmsg(bottom, \"bgr8\"))\n\n\n def publishAlgorithm(self):\n front = self.getFrontImage();\n if(self.buoy_detection == 0):\n img, binary = self.blobDetector.process(front,0)\n self.algorithm_pub.publish(self.bridge.cv2_to_imgmsg(img, encoding='bgr8'))\n self.binary_pub.publish(self.bridge.cv2_to_imgmsg(binary, encoding='passthrough'))\n elif(self.buoy_detection == 1):\n img, binary = self.blobDetector.process(front,1)\n self.algorithm_pub.publish(self.bridge.cv2_to_imgmsg(img, encoding='bgr8'))\n self.binary_pub.publish(self.bridge.cv2_to_imgmsg(binary, encoding='passthrough'))\n centers = self.blobDetector.getCenters()\n msg = Point()\n if(len(centers) > 0):\n msg.x = centers[0][0]\n msg.y = centers[0][1]\n self.center_pub.publish(msg)\n elif(self.buoy_detection == 2):\n img = self.cascadeBuoyDetect.process(front) \n self.algorithm_pub.publish(self.bridge.cv2_to_imgmsg(img, encoding='bgr8'))\n \n def main(self,args):\n rate = rospy.Rate(40) \n \n while(not rospy.is_shutdown()):\n if(self.front_img != None):\n self.cropImage()\n self.publishAlgorithm()\n\n\n rate.sleep()\n \n\n\nif __name__ == '__main__':\n bridge = VisionBridge()\n bridge.main(sys.argv)\n","sub_path":"scripts/vision_bridge.py","file_name":"vision_bridge.py","file_ext":"py","file_size_in_byte":6391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"335642633","text":"import pandas as pd\nimport gensim\nimport numpy as np\nfrom gensim import corpora\nfrom gensim.models import LdaModel\nfrom gensim.models import TfidfModel\nfrom gensim.models.coherencemodel import CoherenceModel\nimport matplotlib.pyplot as plt\n\n# import pyLDAvis.gensim\n\n\nclass Topic_LDA_TF_IDF:\n def __init__(self, news_doc_ls):\n self.news_doc_ls = news_doc_ls\n self.news_doc = [doc.split(\",\") for doc in news_doc_ls]\n # dic = corpora.Dictionary(news_doc)\n self.dictionary = corpora.Dictionary(self.news_doc)\n self.corpus = [self.dictionary.doc2bow(text) for text in self.news_doc]\n tfidf_model = TfidfModel(self.corpus)\n self.corpus = tfidf_model[self.corpus]\n\n def Topic_Num_Decision(self, start, stop, size):\n\n model_list = []\n coherence_values = []\n topic_n_list = []\n perplexity_values = []\n\n for num_topics in range(start, stop, size):\n model = LdaModel(\n self.corpus, num_topics=num_topics, id2word=self.dictionary\n )\n model_list.append(model)\n\n coherencemodel = CoherenceModel(\n model=model,\n texts=self.news_doc,\n dictionary=self.dictionary,\n coherence=\"c_v\",\n )\n coherence_values.append(coherencemodel.get_coherence())\n topic_n_list.append(num_topics)\n perplexity_values.append(model.log_perplexity(self.corpus))\n print(num_topics)\n\n return model_list, coherence_values, perplexity_values\n\n def Topic_Num_Decision_Plt(self, start, stop, size):\n\n model_list, coherence_values, perplexity_values = self.Topic_Num_Decision(\n start, stop, size\n )\n x = range(start, stop, size)\n fig, ax1 = plt.subplots()\n color = \"tab:blue\"\n ax1.set_xlabel(\"Number of Topics\")\n ax1.set_ylabel(\"Coherence score\", color=color)\n ax1.plot(x, coherence_values, color=color)\n ax1.tick_params(axis=\"y\", labelcolor=color)\n ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis\n\n color = \"tab:red\"\n ax2.set_ylabel(\n \"Perplexity score\", color=color\n ) # we already handled the x-label with ax1\n ax2.plot(x, perplexity_values, color=color)\n ax2.tick_params(axis=\"y\", labelcolor=color)\n\n fig.tight_layout() # otherwise the right y-label is slightly clipped\n plt.show()\n\n def LDA_TF_IDF(self, num_topics):\n\n ldamodel = gensim.models.ldamodel.LdaModel(\n self.corpus, num_topics=num_topics, id2word=self.dictionary, passes=5,\n )\n\n topics = ldamodel.print_topics(num_words=10)\n for topic in topics:\n print(topic)\n return ldamodel, ldamodel[self.corpus]\n\n","sub_path":"dags/KimsModule/Topic_Modeling_LDA_TF_IDF.py","file_name":"Topic_Modeling_LDA_TF_IDF.py","file_ext":"py","file_size_in_byte":2822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"502729168","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, division, print_function\n\nfrom sys import version_info\nif version_info.major == 3:\n pass\nelif version_info.major == 2:\n input = raw_input\nelse:\n print (\"Unknown python version - input function not safe\")\n\nfrom os import environ\nfrom sys import maxsize\nfrom bisect import bisect_left as bLeft, bisect_right as bRight\nfrom collections import defaultdict\n\n#from sys import setrecursionlimit\n#setrecursionlimit (11000)\n\n\"\"\"\n6\na b c aa d b\n1 2 3 4 5 6\n3\n1 5 caaab\n0 4 xyz\n2 4 bcdybc\nout:\n0 19\n\ntc6 expected out: 239720795 3131903231\ntc7 expected out: 0 7353994\ntc14 expected out: 5042937153 8619278502\n\"\"\"\n\ndef determiningDNAhealth (n, g, h, fldL):\n # create dict of genes\n # px ... initial position (index start 1); h ... health\n # values: [[p1, p2,..], [hs2, hs2], ... ] hs ..health sums\n genD = defaultdict (lambda: [[], [0]])\n subs = set ()\n mxLen = 0\n for ix in range (n):\n gen = g [ix]; lg = len (gen)\n genD [gen] [0].append (ix)\n for j in range (1, lg + 1): subs.add (gen [ : j])\n mxLen = max (mxLen, lg)\n for v in genD.values ():\n lv = len (v [0])\n for i in range (lv):\n v [1].append (v [1] [i] + h [v [0] [i]])\n mn = maxsize; mx = 0\n# print (\"dict max content length\", mxLen)\n# print (\"dict length\", len (genD))\n# print (genD)\n for f, l, d in fldL:\n ln = len (d)\n sm = 0\n for i in range (ln):\n for j in range (1, mxLen + 1):\n if i + j > ln: break\n gn = d [i : i + j]\n if gn not in subs: break\n if gn not in genD: continue\n# print (i, j, gn)\n # evaluate precomputed healthes\n ids, hs = genD [gn]\n sm += hs [bRight (ids, l)] - hs [bLeft (ids, f)]\n mn = min (sm, mn)\n mx = max (sm, mx)\n return str (mn) + \" \" + str (mx)\n\ndef main ():\n fptr = open (environ ['OUTPUT_PATH'], 'w')\n n = int (input ())\n genes = input ().rstrip ().split ()\n health = list (map (int, input ().rstrip ().split ()))\n s = int (input ())\n fldL = []\n for _ in range (s):\n [first, last, d] = input ().split ()\n fldL.append ((int (first), int (last), d))\n result = determiningDNAhealth (n, genes, health, fldL)\n print (result)\n fptr.write (result + '\\n')\n fptr.close ()\n\nif __name__ == '__main__':\n main ()\n","sub_path":"2017/hackerrank/determiningDNAhealth.py","file_name":"determiningDNAhealth.py","file_ext":"py","file_size_in_byte":2486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"186064893","text":"# -*- coding: utf-8 -*-\n\nimport chainer\nimport chainer.functions as F\nimport chainer.links as L\nfrom chainer.cuda import cupy as xp\n\n\nclass SeqEncoder(chainer.Chain):\n def __init__(self, vocab_size, emb_dim, hidden_dim,\n sequence_length):\n self.vocab_size = vocab_size\n self.emb_dim = emb_dim\n self.hidden_dim = hidden_dim\n self.sequence_length = sequence_length\n\n super(SeqEncoder, self).__init__(\n embed=L.EmbedID(self.vocab_size, self.emb_dim),\n lstm1=L.LSTM(self.emb_dim, self.hidden_dim),\n linear_mu=L.Linear(self.hidden_dim, self.hidden_dim),\n linear_ln_var=L.Linear(self.hidden_dim, self.hidden_dim)\n )\n\n def reset_state(self):\n if hasattr(self, \"lstm1\"):\n self.lstm1.reset_state()\n if hasattr(self, \"lstm2\"):\n self.lstm2.reset_state()\n\n def encode(self, x_input, train=True):\n \"\"\"\n inputを逆順にいれる\n \"\"\"\n self.reset_state()\n for i in range(self.sequence_length):\n x = chainer.Variable(xp.asanyarray(x_input[:, self.sequence_length-i-1], 'int32'))\n h0 = self.embed(x)\n h1 = self.lstm1(F.dropout(h0, train=train))\n\n mu = self.linear_mu(h1)\n ln_var = self.linear_ln_var(h1)\n\n return h1, mu, ln_var\n","sub_path":"models/seq_encoder.py","file_name":"seq_encoder.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"322611579","text":"from django.urls import re_path, include\nfrom rest_framework_jwt.views import obtain_jwt_token\n\nurlpatterns = [\n re_path(r'^auth/$', obtain_jwt_token, name='auth'),\n re_path(r'^workflow/', include('workflow.urls')),\n re_path(r'^ticket/', include('ticket.urls')),\n re_path(r'^users/', include('users.urls')),\n re_path(r'^computer-room/', include('computer_room.urls')),\n re_path(r'^equipment/', include('equipment.urls')),\n\n]\n","sub_path":"apps/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"} +{"seq_id":"8162083","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"ILD algorithm using time series from the Lorenz oscillator.\nThe correct time delay is 10, and the averaged local deformation has a clear\nlocal minimum near that value. Moreover, the resulting plot resembles Fig. 9\nfrom Buzug & Pfister, 1992, as expected.\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom nolitsa import data, dimension\n\nsample = 0.01\n\nx = data.lorenz(length=10000, x0=None, sigma=10.0, beta=8.0/3.0, rho=28.0,\n step=0.001, sample=sample, discard=1000)[1][:, 0]\n\ndim = np.arange(2, 7, 1)\nmaxtau = 60\n\nilds = dimension.ild(x, dim=dim, qmax=10, maxtau=maxtau, rp=0.04, nrefp=0.02,\n k=None)\n\nplt.title('ILD for Lorenz attractor')\nplt.xlabel('Time delay')\nplt.ylabel('ILD')\n\nfor d, ild in zip(dim, ilds):\n plt.plot(np.arange(1, maxtau+1), ild, label=f'm = {d}')\n\nplt.legend()\n\nplt.show()\n","sub_path":"examples/ild/lorenz.py","file_name":"lorenz.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"57"}